import { createContext, memo, useCallback, useContext, useEffect, useRef, useState } from 'react' import type { ReactNode, RefObject } from 'react' import { ChevronDown, ChevronLeft, ChevronRight, Loader2, RefreshCw } from 'lucide-react' import { SideDrawer, SideDrawerHeader } from '@/components/ui/side-drawer' import { Button } from '@/components/ui/button' import { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu' import { Badge } from '@/components/ui/badge' import { Input } from '@/components/ui/input' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { DiffLines } from '@/components/file-browser/DiffLines' import { ScheduleRunMarkdown } from '@/components/schedules/ScheduleRunMarkdown' import { useChangeWalkthrough, useGenerateChangeWalkthrough } from '@/hooks/useChangeWalkthrough' import { GIT_STATUS_COLORS, GIT_STATUS_LABELS } from '@/lib/git-status-styles' import { DEFAULT_WALKTHROUGH_SOURCE, describeWalkthroughSource, toWalkthroughSource, walkthroughSourceKey, WalkthroughOmittedFileSchema, } from '@opencode-manager/shared/schemas' import type { ChangeWalkthrough, WalkthroughHunk, WalkthroughOmittedFile, WalkthroughSource, WalkthroughStop, } from '@opencode-manager/shared/schemas' interface WalkthroughErrorLike { message?: string code?: string details?: unknown } function errorCode(error: unknown): string | undefined { return (error as WalkthroughErrorLike | null)?.code } function isNoChangesError(error: unknown): boolean { const code = errorCode(error) return code === 'WALKTHROUGH_NO_CHANGES' || code === 'WALKTHROUGH_NO_TEXT_CHANGES' } function isContextLimitError(error: unknown): boolean { return errorCode(error) === 'WALKTHROUGH_CONTEXT_LIMIT' } function omittedFilesFromError(error: unknown): WalkthroughOmittedFile[] { const details = (error as { details?: { omittedFiles?: unknown } } | null)?.details const parsed = WalkthroughOmittedFileSchema.array().safeParse(details?.omittedFiles) return parsed.success ? parsed.data : [] } function walkthroughErrorMessage(error: unknown): string { if (isNoChangesError(error)) { return 'This session has no text changes to walk through' } if (isContextLimitError(error)) { return 'These changes are too large to walk through' } return (error as WalkthroughErrorLike | null)?.message || 'Failed to load the walkthrough' } const OMITTED_REASON_LABELS: Record = { binary: 'binary file', budget: 'over the diff budget', renamed: 'renamed', modeChange: 'mode change', } function OmittedFiles({ files }: { files: WalkthroughOmittedFile[] }) { return (

Omitted files

{files.map((omitted) => (

{omitted.file} — {OMITTED_REASON_LABELS[omitted.reason]}

))}
) } function isMechanicalHunk(hunk: WalkthroughHunk): boolean { return hunk.additions !== undefined || hunk.deletions !== undefined } function MechanicalHunks({ hunks }: { hunks: WalkthroughHunk[] }) { return ( ) } interface ChangesWalkthroughContextValue { isLoading: boolean walkthrough: ChangeWalkthrough | null stale: boolean generating: boolean error: unknown contextLimitFiles: WalkthroughOmittedFile[] generate: () => void regenerate: () => void stops: WalkthroughStop[] stopIndex: number | null selectedStop: WalkthroughStop | null selectedHunks: WalkthroughHunk[] selectStop: (index: number | null) => void scrollRef: RefObject 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(null) function useChangesWalkthrough(): ChangesWalkthroughContextValue { const value = useContext(ChangesWalkthroughContext) if (!value) throw new Error('useChangesWalkthrough must be used within a ChangesWalkthroughProvider') return value } const WALKTHROUGH_SOURCE_OPTIONS: { value: WalkthroughSource['kind']; label: string }[] = [ { value: 'session', label: 'This session' }, { value: 'uncommitted', label: 'Uncommitted' }, { value: 'staged', label: 'Staged' }, { value: 'unstaged', label: 'Unstaged' }, { value: 'branch', label: 'Branch vs base' }, { value: 'pullRequest', label: 'Pull request' }, ] /** Chooses which set of changes the walkthrough covers from the surrounding chrome; git sources commit as soon as they are valid. */ export const ChangesWalkthroughSourcePicker = memo(function ChangesWalkthroughSourcePicker() { const { sourceKind, setSourceKind, baseInput, setSource } = useChangesWalkthrough() const handleKindChange = useCallback( (next: WalkthroughSource['kind']) => { setSourceKind(next) if (next === 'pullRequest') return const nextSource = toWalkthroughSource({ kind: next, base: baseInput }) if (nextSource) setSource(nextSource) }, [baseInput, setSourceKind, setSource], ) return ( ) }) /** Collects the base branch or pull request number for git-backed walkthrough sources. */ const WalkthroughSourceInputs = memo(function WalkthroughSourceInputs() { const { sourceKind, baseInput, setBaseInput, numberInput, setNumberInput, setSource } = useChangesWalkthrough() const commitInputs = useCallback(() => { const next = toWalkthroughSource({ kind: sourceKind, base: baseInput, number: Number(numberInput) }) if (next) setSource(next) }, [sourceKind, baseInput, numberInput, setSource]) if (sourceKind !== 'branch' && sourceKind !== 'pullRequest') return null return (
setBaseInput(event.target.value)} onBlur={commitInputs} onKeyDown={(event) => { if (event.key === 'Enter') commitInputs() }} /> {sourceKind === 'pullRequest' ? ( setNumberInput(event.target.value)} onBlur={commitInputs} onKeyDown={(event) => { if (event.key === 'Enter') commitInputs() }} /> ) : null}
) }) interface ChangesWalkthroughProviderProps { sessionId: string active: boolean children: ReactNode } /** 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(DEFAULT_WALKTHROUGH_SOURCE) const [sourceKind, setSourceKind] = useState(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) const resetGenerate = generate.reset const [stopIndex, setStopIndex] = useState(null) const scrollRef = useRef(null) const state = stateQuery.data const walkthrough = state?.walkthrough ?? null const stale = state?.stale ?? false const generating = generate.isPending || (state?.generating ?? false) 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(() => { setStopIndex(null) scrollRef.current?.scrollTo?.({ top: 0 }) }, [active, sessionId, sourceKey, walkthrough?.createdAt]) const hunksById = new Map(walkthrough?.hunks.map((hunk) => [hunk.id, hunk]) ?? []) const stops = walkthrough?.stops ?? [] const clampedIndex = stopIndex === null || stops.length === 0 ? null : Math.min(stopIndex, stops.length - 1) const selectedStop = clampedIndex === null ? null : stops[clampedIndex] ?? null const selectedHunks = (selectedStop?.hunkIds ?? []) .map((id) => hunksById.get(id)) .filter((hunk): hunk is WalkthroughHunk => hunk !== undefined) const failedStopCount = stops.filter( (stop) => stop.status === 'failed' || (stop.status === 'pending' && !generating), ).length const selectStop = useCallback((index: number | null) => { setStopIndex(index) scrollRef.current?.scrollTo?.({ top: 0 }) }, []) const value: ChangesWalkthroughContextValue = { isLoading: stateQuery.isLoading, walkthrough, stale, generating, error, contextLimitFiles, generate: () => generate.mutate({}), regenerate: () => generate.mutate({ regenerate: true }), stops, stopIndex: clampedIndex, selectedStop, selectedHunks, selectStop, scrollRef, failedStopCount, source, setSource, sourceKind, setSourceKind, baseInput, setBaseInput, numberInput, setNumberInput, sourcePending, } return {children} } /** Previous/next page controls (overview, then each stop) for the walkthrough chrome; renders nothing until a walkthrough has stops. */ export const ChangesWalkthroughNav = memo(function ChangesWalkthroughNav() { const { stops, stopIndex, selectStop } = useChangesWalkthrough() if (stops.length === 0) return null return (
selectStop(value === 'overview' ? null : Number(value))} > Overview {stops.map((stop, index) => ( {index + 1}. {stop.title} ))}
) }) /** Regenerates the current walkthrough from the chrome; renders nothing until one exists. */ export const ChangesWalkthroughRegenerate = memo(function ChangesWalkthroughRegenerate() { const { walkthrough, generating, regenerate, sourcePending } = useChangesWalkthrough() if (!walkthrough) return null return ( ) }) /** Renders the walkthrough body; the provider and its chrome supply the surrounding panel. */ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() { const { isLoading, walkthrough, stale, generating, error, contextLimitFiles, generate, stops, selectedStop, selectedHunks, selectStop, scrollRef, 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 (

Enter a pull request number

) } return (
{error ? (

{walkthroughErrorMessage(error)}

{contextLimitFiles.length > 0 ? : null}
) : null} {generating ? (
{walkthrough && stops.length > 0 ? `Generating walkthrough… ${readyStopCount} of ${stops.length} stops explained` : 'Generating walkthrough… this can take a minute or two.'}
) : null} {isLoading ? (
) : !walkthrough ? ( generating ? null : (

Generate a step-by-step walkthrough of {describeWalkthroughSource(source)}.

) ) : (
{stale && !generating ? (

Changes have been updated since this walkthrough was generated

) : null} {failedStopCount > 0 && !generating ? (

Some stops could not be explained

) : null} {selectedStop ? (

{selectedStop.title}

{selectedStop.status === 'ready' ? ( ) : (

{generating ? 'Explaining this stop…' : 'This stop could not be explained.'}

)} {mechanicalHunks.length > 0 ? : null} {diffHunks.map((hunk) => (
{hunk.file} {hunk.truncated ? truncated : null} {GIT_STATUS_LABELS[hunk.status]}
))}
) : ( <> {stops.length > 0 ? (
    {stops.map((stop, index) => (
  1. ))}
) : null} {walkthrough.omittedFiles.length > 0 ? : null} )}
)}
) }) interface ChangesWalkthroughSheetProps { sessionId: string open: boolean onOpenChange: (open: boolean) => void } /** The walkthrough as a right-side sheet: full screen on mobile, a drawer over the page on desktop. */ export function ChangesWalkthroughSheet({ sessionId, open, onOpenChange }: ChangesWalkthroughSheetProps) { const close = useCallback(() => onOpenChange(false), [onOpenChange]) return ( } /> ) }