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

+9 -3
View File
@@ -3,6 +3,7 @@ import { API_BASE_URL } from '@/config'
import { walkthroughSourceKey } from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthroughState,
ChangeWalkthroughStateWire,
GenerateChangeWalkthroughRequest,
WalkthroughSource,
} from '@opencode-manager/shared/schemas'
@@ -14,9 +15,14 @@ function walkthroughUrl(sessionId: string): string {
export async function getChangeWalkthrough(
sessionId: string,
source: WalkthroughSource,
): Promise<ChangeWalkthroughState> {
const query = `?source=${encodeURIComponent(walkthroughSourceKey(source))}`
return fetchWrapper<ChangeWalkthroughState>(`${walkthroughUrl(sessionId)}${query}`)
hunksFor?: string,
): Promise<ChangeWalkthroughStateWire> {
return fetchWrapper<ChangeWalkthroughStateWire>(walkthroughUrl(sessionId), {
params: {
source: walkthroughSourceKey(source),
...(hunksFor === undefined ? {} : { hunksFor }),
},
})
}
export async function generateChangeWalkthrough(
@@ -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>
@@ -0,0 +1,55 @@
import { renderHook, act } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { useAutosavedSetting } from './useAutosavedSetting'
function renderTrimmedSetting(stored: string | undefined, save: (next: string, previous: string | undefined) => void) {
return renderHook(
({ value }: { value: string | undefined }) =>
useAutosavedSetting<string | undefined, string, string>({
stored: value,
toDraft: (draftStored) => draftStored ?? '',
toCommitted: (draft) => draft.trim(),
isEqual: (a, b) => a === b,
save,
}),
{ initialProps: { value: stored } },
)
}
describe('useAutosavedSetting', () => {
it('saves the normalized value once after the debounce', () => {
vi.useFakeTimers()
try {
const save = vi.fn()
const { result } = renderTrimmedSetting(undefined, save)
act(() => result.current.setDraft(' anthropic/claude '))
act(() => {
vi.advanceTimersByTime(800)
})
expect(save).toHaveBeenCalledTimes(1)
expect(save).toHaveBeenCalledWith('anthropic/claude', '')
} finally {
vi.useRealTimers()
}
})
it('skips an unchanged value and resyncs from the stored value', () => {
const save = vi.fn()
const { result, rerender } = renderTrimmedSetting('a', save)
act(() => result.current.commit())
expect(save).not.toHaveBeenCalled()
act(() => result.current.setDraft('b'))
act(() => result.current.commit())
expect(save).toHaveBeenCalledWith('b', 'a')
rerender({ value: 'c' })
expect(result.current.draft).toBe('c')
act(() => result.current.commit())
expect(save).toHaveBeenCalledTimes(1)
})
})
+74
View File
@@ -0,0 +1,74 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { Dispatch, SetStateAction } from 'react'
import { useDebouncedValue } from './useDebouncedValue'
export const AUTOSAVE_DELAY_MS = 800
interface AutosavedSettingHandlers<TStored, TDraft, TCommitted> {
toDraft: (stored: TStored) => TDraft
toCommitted: (draft: TDraft, previous: TCommitted | undefined) => TCommitted
isEqual: (a: TCommitted, b: TCommitted) => boolean
save: (next: TCommitted, previous: TCommitted | undefined) => void
}
interface UseAutosavedSettingOptions<TStored, TDraft, TCommitted>
extends AutosavedSettingHandlers<TStored, TDraft, TCommitted> {
stored: TStored
delayMs?: number
}
interface UseAutosavedSettingResult<TDraft> {
draft: TDraft
setDraft: Dispatch<SetStateAction<TDraft>>
commit: () => void
}
export function useAutosavedSetting<TStored, TDraft, TCommitted>({
stored,
toDraft,
toCommitted,
isEqual,
save,
delayMs = AUTOSAVE_DELAY_MS,
}: UseAutosavedSettingOptions<TStored, TDraft, TCommitted>): UseAutosavedSettingResult<TDraft> {
const handlers = useRef<AutosavedSettingHandlers<TStored, TDraft, TCommitted>>({
toDraft,
toCommitted,
isEqual,
save,
})
useEffect(() => {
handlers.current = { toDraft, toCommitted, isEqual, save }
})
const [draft, setDraft] = useState<TDraft>(() => toDraft(stored))
const committed = useRef<TCommitted>(toCommitted(draft, undefined))
useEffect(() => {
const nextDraft = handlers.current.toDraft(stored)
setDraft(nextDraft)
committed.current = handlers.current.toCommitted(nextDraft, committed.current)
}, [stored])
const commitDraft = useCallback((value: TDraft) => {
const { toCommitted: normalize, isEqual: equal, save: persist } = handlers.current
const next = normalize(value, committed.current)
if (equal(next, committed.current)) return
const previous = committed.current
committed.current = next
persist(next, previous)
}, [])
const debouncedDraft = useDebouncedValue(draft, delayMs)
useEffect(() => {
commitDraft(debouncedDraft)
}, [commitDraft, debouncedDraft])
const commit = useCallback(() => {
commitDraft(draft)
}, [commitDraft, draft])
return { draft, setDraft, commit }
}
@@ -3,8 +3,12 @@ import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { changeWalkthroughQueryKey, useChangeWalkthrough, useGenerateChangeWalkthrough } from './useChangeWalkthrough'
import { DEFAULT_WALKTHROUGH_SOURCE } from '@opencode-manager/shared/schemas'
import type { ChangeWalkthrough, ChangeWalkthroughState } from '@opencode-manager/shared/schemas'
import { DEFAULT_WALKTHROUGH_SOURCE, walkthroughHunksIdentity } from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthrough,
ChangeWalkthroughState,
ChangeWalkthroughStateWire,
} from '@opencode-manager/shared/schemas'
const mocks = vi.hoisted(() => ({
getChangeWalkthrough: vi.fn(),
@@ -116,6 +120,53 @@ describe('useChangeWalkthrough', () => {
}
})
it('merges cached hunks when the server omits them for a matching identity', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
try {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const walkthroughWithHunks: ChangeWalkthrough = {
...walkthroughForA,
hunks: [
{
id: 'h_1',
file: 'src/a.ts',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-a\n+b',
truncated: false,
},
],
}
const compact: ChangeWalkthroughStateWire = {
...state({ generating: true }),
walkthrough: { ...walkthroughWithHunks, hunks: undefined },
}
mocks.getChangeWalkthrough
.mockResolvedValueOnce(state({ walkthrough: walkthroughWithHunks, generating: true }))
.mockResolvedValueOnce(compact)
const { result } = renderHook(() => useChangeWalkthrough('ses_A', true, DEFAULT_WALKTHROUGH_SOURCE), {
wrapper: createWrapper(queryClient),
})
await waitFor(() => expect(result.current.data?.walkthrough?.hunks).toHaveLength(1))
await act(async () => {
await vi.advanceTimersByTimeAsync(2_000)
})
await waitFor(() => expect(mocks.getChangeWalkthrough).toHaveBeenCalledTimes(2))
expect(mocks.getChangeWalkthrough).toHaveBeenLastCalledWith(
'ses_A',
DEFAULT_WALKTHROUGH_SOURCE,
walkthroughHunksIdentity(walkthroughWithHunks),
)
expect(result.current.data?.walkthrough).toEqual(walkthroughWithHunks)
} finally {
vi.useRealTimers()
}
})
it('invalidating the session key refetches every source', async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
mocks.getChangeWalkthrough.mockResolvedValue(state())
+44 -4
View File
@@ -1,7 +1,14 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { generateChangeWalkthrough, getChangeWalkthrough } from '@/api/changeWalkthroughs'
import { walkthroughSourceKey } from '@opencode-manager/shared/schemas'
import type { GenerateChangeWalkthroughRequest, WalkthroughSource } from '@opencode-manager/shared/schemas'
import { walkthroughHunksIdentity, walkthroughSourceKey } from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthrough,
ChangeWalkthroughState,
ChangeWalkthroughStateWire,
ChangeWalkthroughWire,
GenerateChangeWalkthroughRequest,
WalkthroughSource,
} from '@opencode-manager/shared/schemas'
const GENERATING_POLL_INTERVAL_MS = 2_000
@@ -11,15 +18,48 @@ export function changeWalkthroughQueryKey(sessionId: string, sourceKey?: string)
: (['change-walkthrough', sessionId, sourceKey] as const)
}
function isCompleteWalkthrough(walkthrough: ChangeWalkthroughWire): walkthrough is ChangeWalkthrough {
return walkthrough.hunks !== undefined
}
function mergeChangeWalkthroughState(
state: ChangeWalkthroughStateWire,
cached: ChangeWalkthrough | null,
): ChangeWalkthroughState {
const incoming = state.walkthrough
if (!incoming) {
return { ...state, walkthrough: null }
}
if (isCompleteWalkthrough(incoming)) {
return { ...state, walkthrough: incoming }
}
const hunks =
cached && walkthroughHunksIdentity(cached) === walkthroughHunksIdentity(incoming)
? cached.hunks
: []
return { ...state, walkthrough: { ...incoming, hunks } }
}
export function useChangeWalkthrough(
sessionId: string | undefined,
enabled: boolean,
source: WalkthroughSource,
) {
const sourceKey = walkthroughSourceKey(source)
const queryClient = useQueryClient()
const queryKey = changeWalkthroughQueryKey(sessionId ?? '', sourceKey)
return useQuery({
queryKey: changeWalkthroughQueryKey(sessionId ?? '', sourceKey),
queryFn: () => getChangeWalkthrough(sessionId!, source),
queryKey,
queryFn: async () => {
const cached = queryClient.getQueryData<ChangeWalkthroughState>(queryKey)
const cachedWalkthrough = cached?.walkthrough ?? null
const hunksFor = cachedWalkthrough ? walkthroughHunksIdentity(cachedWalkthrough) : undefined
const state =
hunksFor === undefined
? await getChangeWalkthrough(sessionId!, source)
: await getChangeWalkthrough(sessionId!, source, hunksFor)
return mergeChangeWalkthroughState(state, cachedWalkthrough)
},
enabled: enabled && !!sessionId,
staleTime: 30_000,
refetchInterval: (query) => (query.state.data?.generating ? GENERATING_POLL_INTERVAL_MS : false),
+87 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { parseDiffLines, splitDiffHunks, splitUnifiedDiffByFile } from '@opencode-manager/shared/utils';
import { countDiffLineChanges, parseDiffLines, splitDiffHunks, splitUnifiedDiffByFile } from '@opencode-manager/shared/utils';
const DIFF = [
'diff --git a/src/app.ts b/src/app.ts',
@@ -88,6 +88,31 @@ describe('parseDiffLines', () => {
});
});
describe('countDiffLineChanges', () => {
it('counts additions and removals across hunks', () => {
expect(countDiffLineChanges(DIFF)).toEqual({ added: 3, removed: 2 });
});
it('counts changed lines whose content starts with -- or ++', () => {
const diff = '@@ -1,3 +1,3 @@\n--- old comment\n+++ heading\n const a = 1;';
expect(countDiffLineChanges(diff)).toEqual({ added: 1, removed: 1 });
});
it('ignores file headers before a hunk', () => {
const diff = '--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b';
expect(countDiffLineChanges(diff)).toEqual({ added: 1, removed: 1 });
});
it('returns zero for a patch with no changed lines', () => {
expect(countDiffLineChanges('diff --git a/x b/x\nold mode 100644\nnew mode 100755')).toEqual({
added: 0,
removed: 0,
});
});
});
describe('splitDiffHunks', () => {
it('returns one entry per hunk with the header line and body', () => {
const hunks = splitDiffHunks(DIFF);
@@ -127,6 +152,21 @@ describe('splitUnifiedDiffByFile', () => {
expect(result[0]!.patch.startsWith('diff --git a/src/app.ts b/src/app.ts')).toBe(true);
});
it('counts changed lines whose content starts with -- or ++', () => {
const diff = [
'diff --git a/src/a.sql b/src/a.sql',
'--- a/src/a.sql',
'+++ b/src/a.sql',
'@@ -1,2 +1,2 @@',
'--- old comment',
'+++ heading',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'src/a.sql', status: 'modified', additions: 1, deletions: 1 });
});
it('reads an added file from the new side', () => {
const diff = [
'diff --git a/src/new.ts b/src/new.ts',
@@ -174,6 +214,52 @@ describe('splitUnifiedDiffByFile', () => {
expect(file).toMatchObject({ file: 'src/new.ts', status: 'modified', additions: 0, deletions: 0 });
});
it('reads a mode-only change path from a mnemonic diff header', () => {
const diff = [
'diff --git i/script.sh w/script.sh',
'old mode 100644',
'new mode 100755',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'script.sh', status: 'modified', additions: 0, deletions: 0 });
});
it('reads a mode-only change path from a prefix-less diff header', () => {
const diff = [
'diff --git script.sh script.sh',
'old mode 100644',
'new mode 100755',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'script.sh', status: 'modified' });
});
it('keeps a combined merge-conflict block instead of dropping it', () => {
const diff = [
'diff --cc f.txt',
'index d791e9b,00dbdcf..0000000',
'--- a/f.txt',
'+++ b/f.txt',
'@@@ -1,3 -1,3 +1,7 @@@',
' line1',
'++<<<<<<< HEAD',
' +MAIN',
'++=======',
'+ FEATURE',
'++>>>>>>> feat',
' line3',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'f.txt', status: 'modified' });
expect(file!.patch.startsWith('diff --cc f.txt')).toBe(true);
});
it('keeps a binary block with no hunks', () => {
const diff = [
'diff --git a/assets/logo.png b/assets/logo.png',