feat(walkthrough): open the change walkthrough from an agent tool call

This commit is contained in:
Chris Scott committed 2026-10-09 11:03:21 -04:00
1 parent 3eb0b02203
commit aa1da8d608
26 files changed
+1367 -175

No files matched your search

@@ -4,6 +4,7 @@ import type { SessionMessageAssistantTool } from '@opencode-manager/shared/openc
import { useSettings } from '@/hooks/useSettings'
import { useToolCallPermission } from '@/contexts/EventContext'
import { explorationLabel, isExplorationComplete } from '@/lib/explorationGroups'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
import { MessagePart } from './MessagePart'
interface ExplorationGroupProps {
@@ -12,6 +13,7 @@ interface ExplorationGroupProps {
directory?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onOpenWalkthrough?: (source?: WalkthroughSource) => void
}
type MemberProps = Omit<ExplorationGroupProps, 'parts'> & { part: SessionMessageAssistantTool }
@@ -4,6 +4,7 @@ import { TextPart } from './TextPart'
import { ToolCallPart } from './ToolCallPart'
import { useSettings } from '@/hooks/useSettings'
import type { ShellNoticeOutcome } from '@/lib/backgroundWork'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
type AssistantContentPart = SessionMessageAssistant['content'][number]
@@ -14,9 +15,10 @@ interface MessagePartProps {
shellOutcome?: ShellNoticeOutcome
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onOpenWalkthrough?: (source?: WalkthroughSource) => void
}
export const MessagePart = memo(function MessagePart({ part, messageID, directory, shellOutcome, onFileClick, onChildSessionClick }: MessagePartProps) {
export const MessagePart = memo(function MessagePart({ part, messageID, directory, shellOutcome, onFileClick, onChildSessionClick, onOpenWalkthrough }: MessagePartProps) {
const { preferences } = useSettings()
const simpleChatMode = preferences?.simpleChatMode ?? false
const showReasoning = preferences?.showReasoning ?? false
@@ -47,6 +49,7 @@ export const MessagePart = memo(function MessagePart({ part, messageID, director
shellOutcome={shellOutcome}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
onOpenWalkthrough={onOpenWalkthrough}
/>
)
default:
@@ -24,6 +24,7 @@ import { CopyButton } from '@/components/ui/copy-button'
import { TTSButton } from '@/components/ui/tts-button'
import { backgroundShellID, collectBackgroundParts, type ShellNoticeOutcome } from '@/lib/backgroundWork'
import { groupExplorationParts, type AssistantContentItem } from '@/lib/explorationGroups'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
import { ExplorationGroup } from './ExplorationGroup'
function getMessageText(message: SessionMessageInfo): string {
@@ -324,6 +325,7 @@ interface MessageRowProps {
directory?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onOpenWalkthrough?: (source?: WalkthroughSource) => void
model?: string
simpleChatMode: boolean
showReasoning: boolean
@@ -344,6 +346,7 @@ const MessageRow = memo(function MessageRow({
directory,
onFileClick,
onChildSessionClick,
onOpenWalkthrough,
model,
simpleChatMode,
showReasoning,
@@ -452,6 +455,7 @@ const MessageRow = memo(function MessageRow({
shellOutcome={shellOutcomeFor(part)}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
onOpenWalkthrough={onOpenWalkthrough}
/>
</div>
))}
@@ -494,6 +498,7 @@ const MessageRow = memo(function MessageRow({
directory={directory}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
onOpenWalkthrough={onOpenWalkthrough}
/>
) : (
<MessagePart
@@ -503,6 +508,7 @@ const MessageRow = memo(function MessageRow({
shellOutcome={shellOutcomeFor(item.part)}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
onOpenWalkthrough={onOpenWalkthrough}
/>
)}
</div>
@@ -570,6 +576,7 @@ interface MessageThreadProps {
pending: SessionInboxInfo[]
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onOpenWalkthrough?: (source?: WalkthroughSource) => void
onUndoMessage?: (restoredPrompt: string) => void
model?: string
isSessionBusy?: boolean
@@ -582,6 +589,7 @@ export const MessageThread = memo(function MessageThread({
pending,
onFileClick,
onChildSessionClick,
onOpenWalkthrough,
onUndoMessage,
model,
isSessionBusy = false,
@@ -649,6 +657,7 @@ export const MessageThread = memo(function MessageThread({
directory={directory}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
onOpenWalkthrough={onOpenWalkthrough}
model={model}
simpleChatMode={simpleChatMode}
showReasoning={showReasoning}
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { act, render, screen, waitFor } from '@testing-library/react'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import type { PermissionRequest, SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
@@ -265,3 +265,119 @@ describe('ToolCallPart background indicator', () => {
expect(screen.queryByText('background')).not.toBeInTheDocument()
})
})
describe('ToolCallPart open walkthrough action', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useSettings.mockReturnValue({
preferences: { expandToolCalls: false },
isLoading: false,
updateSettings: vi.fn(),
isUpdating: false,
})
mocks.useToolCallPermission.mockReturnValue(null)
})
const openWalkthrough = (status: 'running' | 'completed'): SessionMessageAssistantTool => ({
type: 'tool',
id: 'call_ocm',
name: 'ocm',
time: status === 'completed' ? { created: 1, ran: 2, completed: 3 } : { created: 1, ran: 2 },
state:
status === 'completed'
? {
status: 'completed',
input: { action: 'open_walkthrough', params: {} },
content: [{ type: 'text', text: 'Walkthrough opened' }],
}
: {
status: 'running',
input: { action: 'open_walkthrough', params: {} },
metadata: {},
},
})
it('renders an Open walkthrough button and calls the opener', () => {
const onOpenWalkthrough = vi.fn()
renderWithProviders(
<ToolCallPart part={openWalkthrough('completed')} messageID="msg_1" onOpenWalkthrough={onOpenWalkthrough} />,
)
fireEvent.click(screen.getByRole('button', { name: 'Open walkthrough' }))
expect(onOpenWalkthrough).toHaveBeenCalledTimes(1)
})
it('passes the requested source to the opener', () => {
const onOpenWalkthrough = vi.fn()
const part: SessionMessageAssistantTool = {
type: 'tool',
id: 'call_ocm',
name: 'ocm',
time: { created: 1, ran: 2, completed: 3 },
state: {
status: 'completed',
input: { action: 'open_walkthrough', params: { source: { kind: 'staged' } } },
content: [{ type: 'text', text: 'Walkthrough opened' }],
},
}
renderWithProviders(
<ToolCallPart part={part} messageID="msg_1" onOpenWalkthrough={onOpenWalkthrough} />,
)
fireEvent.click(screen.getByRole('button', { name: 'Open walkthrough' }))
expect(onOpenWalkthrough).toHaveBeenCalledWith({ kind: 'staged' })
})
it('passes no source when the call invalidates one', () => {
const onOpenWalkthrough = vi.fn()
const part: SessionMessageAssistantTool = {
type: 'tool',
id: 'call_ocm',
name: 'ocm',
time: { created: 1, ran: 2, completed: 3 },
state: {
status: 'completed',
input: { action: 'open_walkthrough', params: { source: { kind: 'nonsense' } } },
content: [{ type: 'text', text: 'Walkthrough opened' }],
},
}
renderWithProviders(
<ToolCallPart part={part} messageID="msg_1" onOpenWalkthrough={onOpenWalkthrough} />,
)
fireEvent.click(screen.getByRole('button', { name: 'Open walkthrough' }))
expect(onOpenWalkthrough).toHaveBeenCalledWith(undefined)
})
it('does not render the button while the call is still running', () => {
renderWithProviders(
<ToolCallPart part={openWalkthrough('running')} messageID="msg_1" onOpenWalkthrough={vi.fn()} />,
)
expect(screen.queryByRole('button', { name: 'Open walkthrough' })).not.toBeInTheDocument()
})
it('does not render the button for another ocm action', () => {
const otherAction: SessionMessageAssistantTool = {
type: 'tool',
id: 'call_ocm',
name: 'ocm',
time: { created: 1, ran: 2, completed: 3 },
state: {
status: 'completed',
input: { action: 'something_else' },
content: [{ type: 'text', text: 'ok' }],
},
}
renderWithProviders(<ToolCallPart part={otherAction} messageID="msg_1" onOpenWalkthrough={vi.fn()} />)
expect(screen.queryByRole('button', { name: 'Open walkthrough' })).not.toBeInTheDocument()
})
})
@@ -10,6 +10,7 @@ import { useShell } from '@/hooks/useSessionShells'
import { detectFileReferences } from '@/lib/fileReferences'
import { ExternalLink, Loader2, Shield } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { CopyButton } from '@/components/ui/copy-button'
import { BackgroundTaskStatusIcon } from '@/components/session/BackgroundTaskStatusIcon'
import {
@@ -26,6 +27,8 @@ import {
type ShellNoticeOutcome,
} from '@/lib/backgroundWork'
import { getToolInputPath, getToolSpecificRender } from './FileToolRender'
import { readOpenWalkthroughCall } from '@/lib/walkthroughTool'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
const DISPLAY_LIMIT = 30_000
const DISPLAY_HEAD_LENGTH = 20_000
@@ -61,6 +64,7 @@ interface ToolCallPartProps {
shellOutcome?: ShellNoticeOutcome
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onOpenWalkthrough?: (source?: WalkthroughSource) => void
}
function toolInput(part: SessionMessageAssistantTool): Record<string, unknown> | undefined {
@@ -113,7 +117,7 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">{parts}</pre>
}
export const ToolCallPart = memo(function ToolCallPart({ part, messageID, directory, shellOutcome, onFileClick, onChildSessionClick }: ToolCallPartProps) {
export const ToolCallPart = memo(function ToolCallPart({ part, messageID, directory, shellOutcome, onFileClick, onChildSessionClick, onOpenWalkthrough }: ToolCallPartProps) {
const { preferences } = useSettings()
const { userBashCommands } = useUserBash()
const isSubagent = part.name === 'subagent'
@@ -139,6 +143,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
const isWaitingPermission = part.state.status === 'running' && pendingPermission !== null
const outputRef = useRef<HTMLDivElement>(null)
const input = toolInput(part)
const openWalkthrough = readOpenWalkthroughCall(part)
const rawCommand = part.name === 'shell' && typeof input?.command === 'string'
? input.command
: undefined
@@ -349,36 +354,49 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
return (
<div ref={outputRef} className={`border rounded-lg overflow-hidden my-2 transition-all ${getBorderStyle()}`}>
<button
onClick={() => setExpanded(!expanded)}
className="w-full px-4 py-2 bg-card hover:bg-card-hover text-left flex items-center gap-2 text-sm min-w-0"
>
<span className={getStatusColor()}>{getStatusIcon()}</span>
<span className="font-medium">{part.name}</span>
{sandboxIndicator}
{backgroundIndicator}
<div className="flex items-center bg-card">
<button
onClick={() => setExpanded(!expanded)}
className="min-w-0 flex-1 px-4 py-2 hover:bg-card-hover text-left flex items-center gap-2 text-sm"
>
<span className={getStatusColor()}>{getStatusIcon()}</span>
<span className="font-medium">{part.name}</span>
{sandboxIndicator}
{backgroundIndicator}
{previewText && isFileTool ? (
<span
onClick={(e) => {
e.stopPropagation()
if (onFileClick && previewText) {
onFileClick(previewText)
}
}}
className="text-primary text-xs truncate hover:text-primary-hover cursor-pointer underline decoration-dotted"
title={`Click to open ${previewText}`}
>
{previewText}
{previewText && isFileTool ? (
<span
onClick={(e) => {
e.stopPropagation()
if (onFileClick && previewText) {
onFileClick(previewText)
}
}}
className="text-primary text-xs truncate hover:text-primary-hover cursor-pointer underline decoration-dotted"
title={`Click to open ${previewText}`}
>
{previewText}
</span>
) : previewText ? (
<span className="text-muted-foreground text-xs truncate">{previewText}</span>
) : null}
<span className="text-muted-foreground text-xs ml-auto">
{isWaitingPermission ? 'awaiting permission' : isBackgroundShell ? lifecycleLabel(shellStatus) : part.state.status}
</span>
) : previewText ? (
<span className="text-muted-foreground text-xs truncate">{previewText}</span>
) : null}
</button>
<span className="text-muted-foreground text-xs ml-auto">
{isWaitingPermission ? 'awaiting permission' : isBackgroundShell ? lifecycleLabel(shellStatus) : part.state.status}
</span>
</button>
{openWalkthrough ? (
<Button
variant="outline"
size="sm"
className="mr-2 h-7 shrink-0"
onClick={() => onOpenWalkthrough?.(openWalkthrough.source)}
>
Open walkthrough
</Button>
) : null}
</div>
{expanded && (
<div className="bg-card space-y-2 p-3">
@@ -10,6 +10,7 @@ import {
ChangesWalkthroughRegenerate,
ChangesWalkthroughSourcePicker,
ChangesWalkthroughView,
type WalkthroughSourceRequest,
} from '@/components/session/ChangesWalkthroughSheet'
import { PreviewWorkspace } from '@/components/preview/PreviewPanel'
import { RepoMcpContent } from '@/components/repo/RepoMcpDialog'
@@ -36,6 +37,7 @@ interface ToolSidePanelProps {
currentBranch?: string
selectedFilePath?: string
onSkillLoaded?: (skill: SkillFileInfo) => void
walkthroughSourceRequest?: WalkthroughSourceRequest
}
interface RailButtonProps {
@@ -89,6 +91,7 @@ export function ToolSidePanel({
currentBranch = 'main',
selectedFilePath,
onSkillLoaded,
walkthroughSourceRequest,
}: ToolSidePanelProps) {
const { activeTool, toggleTool, closePanel } = panel
const location = useLocation()
@@ -190,7 +193,12 @@ export function ToolSidePanel({
<>
{panelContent ? (
activeTool === 'walkthrough' && sessionId ? (
<ChangesWalkthroughProvider key={sessionId} sessionId={sessionId} active>
<ChangesWalkthroughProvider
key={sessionId}
sessionId={sessionId}
active
sourceRequest={walkthroughSourceRequest}
>
{panelContent}
</ChangesWalkthroughProvider>
) : (
@@ -383,6 +383,100 @@ describe('ChangesWalkthroughSheet', () => {
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith('ses_2', { kind: 'staged' })
})
it('applies an external source request to the walkthrough source', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
renderSheet({ sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' }, nonce: 1 } })
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
})
expect(screen.getByRole('combobox', { name: 'Changes to walk through' })).toHaveTextContent('Staged')
})
it('applies a pull request request with its number and base', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
renderSheet({
sourceRequest: { sessionId: 'ses_1', source: { kind: 'pullRequest', number: 12 }, nonce: 1 },
})
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'pullRequest', number: 12 })
})
expect(screen.getByLabelText('Pull request number')).toHaveValue(12)
})
it('re-applies a repeated request for the same source', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
const { rerender, onOpenChange } = renderSheet({
sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' }, nonce: 1 },
})
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
})
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
await user.click(await screen.findByRole('option', { name: 'Unstaged' }))
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'unstaged' })
})
rerender(
<ChangesWalkthroughSheet
sessionId="ses_1"
open
onOpenChange={onOpenChange}
sourceRequest={{ sessionId: 'ses_1', source: { kind: 'staged' }, nonce: 2 }}
/>,
)
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
})
expect(screen.getByRole('combobox', { name: 'Changes to walk through' })).toHaveTextContent('Staged')
})
it('leaves the current selection when a request carries no source', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
const { rerender, onOpenChange } = renderSheet({
sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' }, nonce: 1 },
})
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
})
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
await user.click(await screen.findByRole('option', { name: 'Unstaged' }))
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'unstaged' })
})
mocks.getChangeWalkthrough.mockClear()
rerender(
<ChangesWalkthroughSheet
sessionId="ses_1"
open
onOpenChange={onOpenChange}
sourceRequest={{ sessionId: 'ses_1', source: undefined, nonce: 2 }}
/>,
)
expect(screen.getByRole('combobox', { name: 'Changes to walk through' })).toHaveTextContent('Unstaged')
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith('ses_1', { kind: 'session' })
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith('ses_1', { kind: 'staged' })
})
it('ignores a request from another session', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
renderSheet({ sourceRequest: { sessionId: 'ses_other', source: { kind: 'staged' }, nonce: 1 } })
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'session' })
})
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith('ses_1', { kind: 'staged' })
})
it('clears a generation error when the source changes', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
@@ -427,12 +521,44 @@ describe('ChangesWalkthroughSheet', () => {
expect(await screen.findByText('Overview')).toBeInTheDocument()
})
it('shows progress while the server is generating instead of the generate button', async () => {
it('shows a skeleton and planning status while the server is generating without stops', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null, generating: true }))
renderSheet()
expect(await screen.findByText(/Generating walkthrough/)).toBeInTheDocument()
expect(await screen.findByText('Planning the walkthrough…')).toBeInTheDocument()
expect(screen.getByTestId('walkthrough-skeleton')).toHaveAttribute('aria-hidden', 'true')
expect(screen.queryByRole('button', { name: 'Generate walkthrough' })).not.toBeInTheDocument()
expect(screen.queryByText(/Generating walkthrough/)).not.toBeInTheDocument()
})
it('shows a skeleton while the walkthrough state is loading', async () => {
mocks.getChangeWalkthrough.mockImplementation(() => new Promise(() => {}))
renderSheet()
expect(await screen.findByText('Loading the walkthrough…')).toBeInTheDocument()
expect(screen.getByTestId('walkthrough-skeleton')).toBeInTheDocument()
})
it('shows a stop body skeleton while its explanation is pending', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(
state({
generating: true,
walkthrough: {
...walkthrough,
stops: [
{ ...walkthrough.stops[0], status: 'ready' },
{ ...walkthrough.stops[1], status: 'pending', explanation: '' },
],
},
}),
)
renderSheet()
await user.click(await screen.findByRole('button', { name: /2\. Wire it up/ }))
expect(await screen.findByText('Explaining this stop…')).toBeInTheDocument()
expect(screen.getByTestId('walkthrough-skeleton')).toBeInTheDocument()
})
it('renders ready and pending stops while generating', async () => {
@@ -18,6 +18,7 @@ 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 { cn } from '@/lib/utils'
import {
DEFAULT_WALKTHROUGH_SOURCE,
describeWalkthroughSource,
@@ -237,14 +238,30 @@ const WalkthroughSourceInputs = memo(function WalkthroughSourceInputs() {
)
})
/**
* A one-shot request to open the walkthrough on a given source. `nonce` makes a repeated request for
* the same source a distinct value, so it re-applies; `source` undefined leaves the selection alone.
*/
export interface WalkthroughSourceRequest {
sessionId: string
source?: WalkthroughSource
nonce: number
}
interface ChangesWalkthroughProviderProps {
sessionId: string
active: boolean
sourceRequest?: WalkthroughSourceRequest
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) {
export function ChangesWalkthroughProvider({
sessionId,
active,
sourceRequest,
children,
}: ChangesWalkthroughProviderProps) {
const [source, setSource] = useState<WalkthroughSource>(DEFAULT_WALKTHROUGH_SOURCE)
const [sourceKind, setSourceKind] = useState<WalkthroughSource['kind']>(DEFAULT_WALKTHROUGH_SOURCE.kind)
const [baseInput, setBaseInput] = useState('')
@@ -277,6 +294,20 @@ export function ChangesWalkthroughProvider({ sessionId, active, children }: Chan
scrollRef.current?.scrollTo?.({ top: 0 })
}, [active, sessionId, sourceKey, walkthrough?.createdAt])
useEffect(() => {
if (!sourceRequest || sourceRequest.sessionId !== sessionId) return
const requested = sourceRequest.source
if (!requested) return
setSource(requested)
setSourceKind(requested.kind)
if (requested.kind === 'branch' || requested.kind === 'pullRequest') {
setBaseInput(requested.base ?? '')
}
if (requested.kind === 'pullRequest') {
setNumberInput(String(requested.number))
}
}, [sourceRequest, sessionId])
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)
@@ -395,6 +426,67 @@ export const ChangesWalkthroughRegenerate = memo(function ChangesWalkthroughRege
)
})
const SKELETON_BAR = 'rounded bg-muted animate-pulse motion-reduce:animate-none'
function WalkthroughSkeletonBar({ className }: { className?: string }) {
return <div className={cn(SKELETON_BAR, 'h-3.5', className)} />
}
function WalkthroughHunkSkeleton() {
const diffLineWidths = ['w-3/4', 'w-1/2', 'w-5/6', 'w-2/3', 'w-1/3', 'w-4/5']
return (
<div 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">
<WalkthroughSkeletonBar className="h-3 w-2/5" />
<div className="ml-auto flex items-center gap-1.5">
<WalkthroughSkeletonBar className="h-3.5 w-10 rounded-full" />
<WalkthroughSkeletonBar className="h-3.5 w-6 rounded-full" />
<WalkthroughSkeletonBar className="h-3.5 w-6 rounded-full" />
</div>
</div>
<div className="space-y-1.5 p-3">
{diffLineWidths.map((width, row) => (
<div key={row} className="flex items-center gap-3">
<WalkthroughSkeletonBar className="h-3 w-6 shrink-0" />
<WalkthroughSkeletonBar className={cn('h-3', width)} />
</div>
))}
</div>
</div>
)
}
/** Placeholder that mirrors the walkthrough layout while it loads or generates; the overview variant adds the title and stop list. */
function WalkthroughSkeleton({ variant = 'overview' }: { variant?: 'overview' | 'body' }) {
return (
<div data-testid="walkthrough-skeleton" aria-hidden="true" className="space-y-4">
{variant === 'overview' ? <WalkthroughSkeletonBar className="h-4 w-1/3" /> : null}
<div className="space-y-2">
<WalkthroughSkeletonBar className="w-full" />
<WalkthroughSkeletonBar className="w-11/12" />
<WalkthroughSkeletonBar className="w-4/5" />
</div>
<div className="space-y-3">
<WalkthroughHunkSkeleton />
{variant === 'overview' ? <WalkthroughHunkSkeleton /> : null}
</div>
{variant === 'overview' ? (
<div className="space-y-1">
{['w-2/3', 'w-1/2', 'w-3/5'].map((width, row) => (
<div key={row} className="flex items-center gap-2 px-2 py-1">
<div className={cn(SKELETON_BAR, 'h-3 w-4 shrink-0 bg-muted/60')} />
<div className={cn(SKELETON_BAR, 'h-3 bg-muted/60', width)} />
</div>
))}
</div>
) : null}
</div>
)
}
/** Renders the walkthrough body; the provider and its chrome supply the surrounding panel. */
export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
const {
@@ -418,6 +510,7 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
const readyStopCount = stops.filter((stop) => stop.status === 'ready').length
const mechanicalHunks = selectedHunks.filter(isMechanicalHunk)
const diffHunks = selectedHunks.filter((hunk) => !isMechanicalHunk(hunk))
const showInitialSkeleton = isLoading || (generating && (walkthrough === null || stops.length === 0))
if (sourcePending) {
return (
@@ -439,114 +532,122 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
</div>
) : null}
{generating ? (
<div className="flex items-center gap-2 rounded-md border border-border bg-muted/20 px-3 py-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 shrink-0 animate-spin" />
<span>
{walkthrough && stops.length > 0
? `Generating walkthrough… ${readyStopCount} of ${stops.length} stops explained`
: 'Generating walkthrough… this can take a minute or two.'}
</span>
</div>
) : null}
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : !walkthrough ? (
generating ? null : (
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Generate a step-by-step walkthrough of {describeWalkthroughSource(source)}.
</p>
<Button onClick={generate}>Generate walkthrough</Button>
</div>
)
) : (
{showInitialSkeleton ? (
<div className="space-y-4">
{stale && !generating ? (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2">
<p className="text-sm text-warning">
Changes have been updated since this walkthrough was generated
<p role="status" aria-live="polite" className="text-sm text-muted-foreground">
{generating ? 'Planning the walkthrough…' : 'Loading the walkthrough…'}
</p>
<WalkthroughSkeleton />
</div>
) : (
<>
{generating ? (
<div className="flex items-center gap-2 rounded-md border border-border bg-muted/20 px-3 py-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />
<span>{`Generating walkthrough… ${readyStopCount} of ${stops.length} stops explained`}</span>
</div>
) : null}
{!walkthrough ? (
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Generate a step-by-step walkthrough of {describeWalkthroughSource(source)}.
</p>
<Button variant="outline" size="sm" onClick={generate}>
<RefreshCw className="mr-2 h-3.5 w-3.5" />
Update walkthrough
</Button>
</div>
) : null}
{failedStopCount > 0 && !generating ? (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-border bg-muted/20 px-3 py-2">
<p className="text-sm text-muted-foreground">Some stops could not be explained</p>
<Button variant="outline" size="sm" onClick={generate}>
Retry unexplained stops
</Button>
</div>
) : null}
{selectedStop ? (
<div className="space-y-3">
<h3 className="text-sm font-semibold text-foreground">{selectedStop.title}</h3>
{selectedStop.status === 'ready' ? (
<ScheduleRunMarkdown content={selectedStop.explanation} />
) : (
<p className="text-sm text-muted-foreground">
{generating ? 'Explaining this stop…' : 'This stop could not be explained.'}
</p>
)}
{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}>
{hunk.file}
</span>
{hunk.truncated ? <Badge variant="outline">truncated</Badge> : null}
<span className={`text-xs ${GIT_STATUS_COLORS[hunk.status]}`}>
{GIT_STATUS_LABELS[hunk.status]}
</span>
</div>
<div className="overflow-x-auto">
<DiffLines diff={hunk.text} />
</div>
</div>
))}
<Button onClick={generate}>Generate walkthrough</Button>
</div>
) : (
<>
<ScheduleRunMarkdown content={walkthrough.summary} />
{stops.length > 0 ? (
<ol className="space-y-0.5">
{stops.map((stop, index) => (
<li key={stop.id}>
<button
type="button"
onClick={() => selectStop(index)}
className="w-full rounded-md px-2 py-1 text-left text-sm text-muted-foreground hover:bg-accent/20 hover:text-foreground"
>
<span className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate">
{index + 1}. {stop.title}
</span>
{stop.status === 'pending' && generating ? (
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" aria-label="Explaining" />
) : stop.status === 'failed' || stop.status === 'pending' ? (
<span className="shrink-0 text-xs text-muted-foreground">not explained</span>
) : null}
</span>
</button>
</li>
))}
</ol>
<div className="space-y-4">
{stale && !generating ? (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2">
<p className="text-sm text-warning">
Changes have been updated since this walkthrough was generated
</p>
<Button variant="outline" size="sm" onClick={generate}>
<RefreshCw className="mr-2 h-3.5 w-3.5" />
Update walkthrough
</Button>
</div>
) : null}
{walkthrough.omittedFiles.length > 0 ? <OmittedFiles files={walkthrough.omittedFiles} /> : null}
</>
{failedStopCount > 0 && !generating ? (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-border bg-muted/20 px-3 py-2">
<p className="text-sm text-muted-foreground">Some stops could not be explained</p>
<Button variant="outline" size="sm" onClick={generate}>
Retry unexplained stops
</Button>
</div>
) : null}
{selectedStop ? (
<div className="space-y-3">
<h3 className="text-sm font-semibold text-foreground">{selectedStop.title}</h3>
{selectedStop.status === 'ready' ? (
<ScheduleRunMarkdown content={selectedStop.explanation} />
) : generating && selectedStop.status === 'pending' ? (
<div className="space-y-3">
<p role="status" aria-live="polite" className="text-sm text-muted-foreground">
Explaining this stop…
</p>
<WalkthroughSkeleton variant="body" />
</div>
) : (
<p className="text-sm text-muted-foreground">
{generating ? 'Explaining this stop…' : 'This stop could not be explained.'}
</p>
)}
{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}>
{hunk.file}
</span>
{hunk.truncated ? <Badge variant="outline">truncated</Badge> : null}
<span className={`text-xs ${GIT_STATUS_COLORS[hunk.status]}`}>
{GIT_STATUS_LABELS[hunk.status]}
</span>
</div>
<div className="overflow-x-auto">
<DiffLines diff={hunk.text} />
</div>
</div>
))}
</div>
) : (
<>
<ScheduleRunMarkdown content={walkthrough.summary} />
{stops.length > 0 ? (
<ol className="space-y-0.5">
{stops.map((stop, index) => (
<li key={stop.id}>
<button
type="button"
onClick={() => selectStop(index)}
className="w-full rounded-md px-2 py-1 text-left text-sm text-muted-foreground hover:bg-accent/20 hover:text-foreground"
>
<span className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate">
{index + 1}. {stop.title}
</span>
{stop.status === 'pending' && generating ? (
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" aria-label="Explaining" />
) : stop.status === 'failed' || stop.status === 'pending' ? (
<span className="shrink-0 text-xs text-muted-foreground">not explained</span>
) : null}
</span>
</button>
</li>
))}
</ol>
) : null}
{walkthrough.omittedFiles.length > 0 ? <OmittedFiles files={walkthrough.omittedFiles} /> : null}
</>
)}
</div>
)}
</div>
</>
)}
</div>
)
@@ -556,15 +657,21 @@ interface ChangesWalkthroughSheetProps {
sessionId: string
open: boolean
onOpenChange: (open: boolean) => void
sourceRequest?: WalkthroughSourceRequest
}
/** 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) {
export function ChangesWalkthroughSheet({
sessionId,
open,
onOpenChange,
sourceRequest,
}: ChangesWalkthroughSheetProps) {
const close = useCallback(() => onOpenChange(false), [onOpenChange])
return (
<SideDrawer isOpen={open} onClose={close} side="right" widthClass="w-full sm:w-[min(640px,92vw)]" ariaLabel="Change walkthrough">
<ChangesWalkthroughProvider key={sessionId} sessionId={sessionId} active={open}>
<ChangesWalkthroughProvider key={sessionId} sessionId={sessionId} active={open} sourceRequest={sourceRequest}>
<SideDrawerHeader
title="Change walkthrough"
onClose={close}
@@ -168,6 +168,23 @@ describe('SideDrawerHeader', () => {
fireEvent.click(screen.getByRole('button', { name: /close/i }))
expect(handleClose).toHaveBeenCalled()
})
it('truncates the title and wraps actions below it on narrow widths', () => {
render(
<SideDrawerHeader
title="Change walkthrough"
onClose={() => {}}
actions={<button type="button">Regenerate</button>}
/>,
)
expect(screen.getByText('Change walkthrough')).toHaveClass('truncate')
const actions = screen.getByRole('button', { name: 'Regenerate' }).parentElement
expect(actions).toHaveClass('order-3', 'basis-full', 'sm:order-2', 'sm:basis-auto')
expect(screen.getByRole('button', { name: /close/i })).toHaveClass('order-2', 'sm:order-3')
})
})
describe('SideDrawerContent', () => {
+9 -5
View File
@@ -112,20 +112,24 @@ export interface SideDrawerHeaderProps {
export function SideDrawerHeader({ title, onClose, meta, actions }: SideDrawerHeaderProps) {
return (
<div className="flex-shrink-0 border-b border-border bg-background px-4 py-2 flex items-center justify-between gap-3">
<div className="min-w-0 flex-1">
<h2 className="text-lg font-semibold text-foreground leading-none">{title}</h2>
<div className="flex-shrink-0 border-b border-border bg-background px-4 py-2 flex flex-wrap items-center justify-between gap-3">
<div className="order-1 min-w-0 flex-1">
<h2 className="truncate text-lg font-semibold text-foreground leading-none">{title}</h2>
{meta ? <div className="mt-1 min-w-0">{meta}</div> : null}
</div>
{actions ? <div className="flex shrink-0 items-center gap-1">{actions}</div> : null}
<button
type="button"
onClick={onClose}
className="text-muted-foreground hover:text-foreground hover:bg-muted transition-colors rounded-sm p-1 shrink-0"
className="order-2 shrink-0 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors rounded-sm p-1 sm:order-3"
aria-label="Close"
>
<X className="w-5 h-5" />
</button>
{actions ? (
<div className="order-3 flex shrink-0 basis-full items-center justify-end gap-1 sm:order-2 sm:basis-auto sm:justify-start">
{actions}
</div>
) : null}
</div>
)
}
@@ -0,0 +1,315 @@
import { describe, it, expect, vi } from 'vitest'
import { renderHook } from '@testing-library/react'
import type {
SessionMessageAssistant,
SessionMessageAssistantTool,
SessionMessageInfo,
} from '@opencode-manager/shared/opencode'
import { useAutoOpenWalkthrough } from '../useAutoOpenWalkthrough'
const openWalkthroughPart = (
id: string,
status: 'running' | 'completed' = 'completed',
): SessionMessageAssistantTool => ({
type: 'tool',
id,
name: 'ocm',
time: { created: 1 },
state:
status === 'completed'
? {
status: 'completed',
input: { action: 'open_walkthrough', params: {} },
content: [{ type: 'text', text: 'Walkthrough opened' }],
}
: {
status: 'running',
input: { action: 'open_walkthrough', params: {} },
metadata: {},
},
})
const otherToolPart = (id: string): SessionMessageAssistantTool => ({
type: 'tool',
id,
name: 'shell',
time: { created: 1, ran: 2, completed: 3 },
state: {
status: 'completed',
input: { command: 'ls' },
content: [{ type: 'text', text: 'ok' }],
},
})
const assistantMessage = (
id: string,
...parts: SessionMessageAssistantTool[]
): SessionMessageAssistant => ({
id,
type: 'assistant',
agent: 'build',
model: { providerID: 'anthropic', id: 'claude' },
time: { created: 1, completed: 2 },
content: parts,
})
interface HookProps {
sessionId: string
messages: SessionMessageInfo[]
enabled: boolean
loading: boolean
onOpen: () => void
}
const renderAutoOpen = (initialProps: HookProps) =>
renderHook((props: HookProps) => useAutoOpenWalkthrough(props), { initialProps })
describe('useAutoOpenWalkthrough', () => {
it('opens once when an open_walkthrough call completes live', () => {
const onOpen = vi.fn()
const { rerender } = renderAutoOpen({
sessionId: 's1',
messages: [],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).not.toHaveBeenCalled()
rerender({
sessionId: 's1',
messages: [assistantMessage('m1', openWalkthroughPart('t1'))],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).toHaveBeenCalledTimes(1)
})
it('opens when a running open_walkthrough call later completes', () => {
const onOpen = vi.fn()
const { rerender } = renderAutoOpen({
sessionId: 's1',
messages: [assistantMessage('m1', openWalkthroughPart('t1', 'running'))],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).not.toHaveBeenCalled()
rerender({
sessionId: 's1',
messages: [assistantMessage('m1', openWalkthroughPart('t1', 'completed'))],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).toHaveBeenCalledTimes(1)
})
it('passes the requested source to the opener', () => {
const onOpen = vi.fn()
const part: SessionMessageAssistantTool = {
type: 'tool',
id: 't1',
name: 'ocm',
time: { created: 1 },
state: {
status: 'completed',
input: { action: 'open_walkthrough', params: { source: { kind: 'pullRequest', number: 7 } } },
content: [{ type: 'text', text: 'Opened the walkthrough.' }],
},
}
const { rerender } = renderAutoOpen({
sessionId: 's1',
messages: [],
enabled: true,
loading: false,
onOpen,
})
rerender({
sessionId: 's1',
messages: [assistantMessage('m1', part)],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).toHaveBeenCalledWith({ kind: 'pullRequest', number: 7 })
})
it('passes no source when the call invalidates one', () => {
const onOpen = vi.fn()
const invalid: SessionMessageAssistantTool = {
type: 'tool',
id: 't1',
name: 'ocm',
time: { created: 1 },
state: {
status: 'completed',
input: { action: 'open_walkthrough', params: { source: { kind: 'nonsense' } } },
content: [{ type: 'text', text: 'Opened the walkthrough.' }],
},
}
const { rerender } = renderAutoOpen({
sessionId: 's1',
messages: [],
enabled: true,
loading: false,
onOpen,
})
rerender({
sessionId: 's1',
messages: [assistantMessage('m1', invalid)],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).toHaveBeenCalledWith(undefined)
})
it('does not open for a call already completed at the first loaded render', () => {
const onOpen = vi.fn()
renderAutoOpen({
sessionId: 's1',
messages: [assistantMessage('m1', openWalkthroughPart('t1'))],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).not.toHaveBeenCalled()
})
it('does not open for historical calls loaded after the initial pending render', () => {
const onOpen = vi.fn()
const { rerender } = renderAutoOpen({
sessionId: 's1',
messages: [],
enabled: true,
loading: true,
onOpen,
})
rerender({
sessionId: 's1',
messages: [assistantMessage('m1', openWalkthroughPart('t1'))],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).not.toHaveBeenCalled()
})
it('does not open while the walkthrough is not docked', () => {
const onOpen = vi.fn()
const { rerender } = renderAutoOpen({
sessionId: 's1',
messages: [],
enabled: false,
loading: false,
onOpen,
})
rerender({
sessionId: 's1',
messages: [assistantMessage('m1', openWalkthroughPart('t1'))],
enabled: false,
loading: false,
onOpen,
})
expect(onOpen).not.toHaveBeenCalled()
})
it('opens at most once per tool call id', () => {
const onOpen = vi.fn()
const message = assistantMessage('m1', openWalkthroughPart('t1'))
const { rerender } = renderAutoOpen({
sessionId: 's1',
messages: [],
enabled: true,
loading: false,
onOpen,
})
rerender({ sessionId: 's1', messages: [message], enabled: true, loading: false, onOpen })
rerender({ sessionId: 's1', messages: [message], enabled: true, loading: false, onOpen })
expect(onOpen).toHaveBeenCalledTimes(1)
})
it('ignores other tools and other ocm actions', () => {
const onOpen = vi.fn()
const { rerender } = renderAutoOpen({
sessionId: 's1',
messages: [],
enabled: true,
loading: false,
onOpen,
})
rerender({
sessionId: 's1',
messages: [assistantMessage('m1', otherToolPart('t1'))],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).not.toHaveBeenCalled()
})
it('does not open a historical call in a different session', () => {
const onOpen = vi.fn()
const { rerender } = renderAutoOpen({
sessionId: 's1',
messages: [],
enabled: true,
loading: false,
onOpen,
})
rerender({
sessionId: 's2',
messages: [assistantMessage('m2', openWalkthroughPart('t2'))],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).not.toHaveBeenCalled()
})
it('does not open an older call paged in after the initial load', () => {
const onOpen = vi.fn()
const { rerender } = renderAutoOpen({
sessionId: 's1',
messages: [assistantMessage('msg_010')],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).not.toHaveBeenCalled()
rerender({
sessionId: 's1',
messages: [assistantMessage('msg_001', openWalkthroughPart('t_old')), assistantMessage('msg_010')],
enabled: true,
loading: false,
onOpen,
})
expect(onOpen).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,59 @@
import { useEffect, useRef } from 'react'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
import { collectOpenWalkthroughCalls } from '@/lib/walkthroughTool'
interface UseAutoOpenWalkthroughOptions {
sessionId: string | undefined
messages: SessionMessageInfo[]
enabled: boolean
loading: boolean
onOpen: (source?: WalkthroughSource) => void
}
/**
* Opens the change walkthrough when an `open_walkthrough` tool call completes live in the viewed
* session. Calls present at the first loaded render are treated as history and ignored, and calls in
* messages older than that render's oldest message stay ignored when the transcript pages in older
* history. Each call opens at most once. `enabled` gates the automatic open so a mode where the
* walkthrough is a full-screen dialog (mobile) leaves the user to open it from the tool call row.
*/
export function useAutoOpenWalkthrough({
sessionId,
messages,
enabled,
loading,
onOpen,
}: UseAutoOpenWalkthroughOptions): void {
const seenRef = useRef<Set<string> | null>(null)
const frontierRef = useRef<string | null>(null)
const sessionRef = useRef<string | undefined>(undefined)
const onOpenRef = useRef(onOpen)
onOpenRef.current = onOpen
useEffect(() => {
if (sessionRef.current !== sessionId || loading) {
sessionRef.current = sessionId
seenRef.current = null
frontierRef.current = null
}
if (loading) return
if (seenRef.current === null) {
seenRef.current = new Set(collectOpenWalkthroughCalls(messages).map((call) => call.id))
frontierRef.current = messages[0]?.id ?? null
return
}
const frontier = frontierRef.current
const liveMessages =
frontier === null ? messages : messages.filter((message) => message.id >= frontier)
let opened = false
for (const call of collectOpenWalkthroughCalls(liveMessages)) {
if (seenRef.current.has(call.id)) continue
seenRef.current.add(call.id)
if (enabled && !opened) {
opened = true
onOpenRef.current(call.source)
}
}
}, [sessionId, messages, enabled, loading])
}
+63
View File
@@ -0,0 +1,63 @@
import { describe, it, expect } from 'vitest'
import type { SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { readOpenWalkthroughCall } from './walkthroughTool'
type Json = null | boolean | number | string | Json[] | { [key: string]: Json }
const ocmPart = (
params: Json,
status: 'running' | 'completed' = 'completed',
): SessionMessageAssistantTool => ({
type: 'tool',
id: 't1',
name: 'ocm',
time: { created: 1 },
state:
status === 'completed'
? {
status: 'completed',
input: { action: 'open_walkthrough', params },
content: [{ type: 'text', text: 'Opened the walkthrough.' }],
}
: {
status: 'running',
input: { action: 'open_walkthrough', params },
metadata: {},
},
})
describe('readOpenWalkthroughCall', () => {
it('returns the validated source the agent requested', () => {
expect(readOpenWalkthroughCall(ocmPart({ source: { kind: 'staged' } }))).toEqual({
id: 't1',
source: { kind: 'staged' },
})
})
it('returns the source with its base for git-backed sources', () => {
expect(readOpenWalkthroughCall(ocmPart({ source: { kind: 'branch', base: 'develop' } }))).toEqual({
id: 't1',
source: { kind: 'branch', base: 'develop' },
})
})
it('returns no source when the agent omitted one', () => {
expect(readOpenWalkthroughCall(ocmPart({}))).toEqual({ id: 't1', source: undefined })
})
it('ignores a source that does not validate', () => {
expect(readOpenWalkthroughCall(ocmPart({ source: { kind: 'nonsense' } }))).toEqual({
id: 't1',
source: undefined,
})
})
it('ignores malformed params', () => {
expect(readOpenWalkthroughCall(ocmPart('not-an-object'))).toEqual({ id: 't1', source: undefined })
expect(readOpenWalkthroughCall(ocmPart(null))).toEqual({ id: 't1', source: undefined })
})
it('returns undefined for an unfinished call', () => {
expect(readOpenWalkthroughCall(ocmPart({ source: { kind: 'staged' } }, 'running'))).toBeUndefined()
})
})
+48
View File
@@ -0,0 +1,48 @@
import type { SessionMessageAssistantTool, SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { WalkthroughSourceSchema } from '@opencode-manager/shared/schemas'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
export const OCM_TOOL_NAME = 'ocm'
export const OPEN_WALKTHROUGH_ACTION = 'open_walkthrough'
export interface OpenWalkthroughCall {
id: string
source?: WalkthroughSource
}
/**
* Reads the optional walkthrough source the agent passed to `open_walkthrough`, ignoring anything that
* does not validate as a `WalkthroughSource`.
*/
function readOpenWalkthroughSource(params: unknown): WalkthroughSource | undefined {
if (typeof params !== 'object' || params === null || Array.isArray(params)) return undefined
const parsed = WalkthroughSourceSchema.safeParse((params as Record<string, unknown>).source)
return parsed.success ? parsed.data : undefined
}
/**
* Reads an assistant tool part as a completed `ocm` `open_walkthrough` call, or undefined for every
* other tool, action, and unfinished state. The call carries the validated source the agent asked to
* open, or undefined when none was given or it did not validate.
*/
export function readOpenWalkthroughCall(
part: SessionMessageAssistantTool,
): OpenWalkthroughCall | undefined {
if (part.name !== OCM_TOOL_NAME || part.state.status !== 'completed') return undefined
if (part.state.input.action !== OPEN_WALKTHROUGH_ACTION) return undefined
return { id: part.id, source: readOpenWalkthroughSource(part.state.input.params) }
}
/** Every completed `open_walkthrough` call in a transcript, in message order. */
export function collectOpenWalkthroughCalls(messages: SessionMessageInfo[]): OpenWalkthroughCall[] {
const calls: OpenWalkthroughCall[] = []
for (const message of messages) {
if (message.type !== 'assistant') continue
for (const part of message.content) {
if (part.type !== 'tool') continue
const call = readOpenWalkthroughCall(part)
if (call) calls.push(call)
}
}
return calls
}
+30 -4
View File
@@ -17,6 +17,7 @@ import { Button } from "@/components/ui/button";
import { ContextUsageIndicator } from "@/components/session/ContextUsageIndicator";
import { useSession, useInterruptSession, useUpdateSession, useCreateSession } from "@/hooks/useOpenCode";
import { useSessionTranscript } from "@/hooks/useSessionTranscript";
import { useAutoOpenWalkthrough } from "@/hooks/useAutoOpenWalkthrough";
import { useRepoActivity } from "@/hooks/useRepoActivity";
import { useSSE } from "@/hooks/useSSE";
import { useUIState } from "@/stores/uiStateStore";
@@ -64,8 +65,9 @@ import { useTerminalDialogParam } from "@/hooks/useOpenTerminal";
import { SessionMoreButton } from "@/components/navigation/SessionMoreButton";
import { SideQuestionDialog } from "@/components/session/SideQuestionDialog";
import { SessionMessagePickerDialog } from "@/components/session/SessionMessagePickerDialog";
import { ChangesWalkthroughSheet } from "@/components/session/ChangesWalkthroughSheet";
import { ChangesWalkthroughSheet, type WalkthroughSourceRequest } from "@/components/session/ChangesWalkthroughSheet";
import { ToolSidePanel } from "@/components/navigation/ToolSidePanel";
import type { WalkthroughSource } from "@opencode-manager/shared/schemas";
import { useToolPanel } from "@/hooks/useToolPanel";
const OLDER_HISTORY_SCROLL_THRESHOLD_PX = 200
@@ -133,6 +135,7 @@ export function SessionDetail() {
const [previewOpen, setPreviewOpen] = useDialogParam('preview');
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
const [walkthroughOpen, setWalkthroughOpen] = useDialogParam('walkthrough');
const [requestedWalkthroughSource, setRequestedWalkthroughSource] = useState<WalkthroughSourceRequest | null>(null);
const [selectedFilePath, setSelectedFilePath] = useState<string | undefined>();
const [showScrollButton, setShowScrollButton] = useState(false);
const [hasPromptContent, setHasPromptContent] = useState(false);
@@ -300,10 +303,30 @@ export function SessionDetail() {
const handleShowSessionsDialog = useCallback(() => setSessionsDialogOpen(true), []);
const handleShowMcpDialog = useCallback(() => setMcpDialogOpen(true), [setMcpDialogOpen]);
const handleShowSkillsDialog = useCallback(() => setSkillsDialogOpen(true), [setSkillsDialogOpen]);
const handleShowWalkthrough = useCallback(() => setWalkthroughOpen(true), [setWalkthroughOpen]);
const handleShowWalkthrough = useCallback((source?: WalkthroughSource) => {
setRequestedWalkthroughSource((current) => ({
sessionId: sessionId ?? '',
source,
nonce: (current?.nonce ?? 0) + 1,
}));
setWalkthroughOpen(true);
}, [sessionId, setWalkthroughOpen]);
const handleShowWalkthroughCommand = useCallback(() => handleShowWalkthrough(), [handleShowWalkthrough]);
const walkthroughSourceRequest =
requestedWalkthroughSource && requestedWalkthroughSource.sessionId === (sessionId ?? '')
? requestedWalkthroughSource
: undefined;
const handleSkillLoaded = useCallback((skill: SkillFileInfo) => showToast.success(`Loaded skill: ${skill.name}`), []);
const handleConnectProvider = useCallback(() => setSettingsTab('providers'), [setSettingsTab]);
useAutoOpenWalkthrough({
sessionId,
messages,
enabled: docked,
loading: messagesLoading,
onOpen: handleShowWalkthrough,
});
const handleMinimizeForm = useCallback((form: FormInfo) => {
setMinimizedFormId(form.id)
}, [])
@@ -558,7 +581,7 @@ export function SessionDetail() {
redo: handleRedo,
showMcp: handleShowMcpDialog,
showSkills: handleShowSkillsDialog,
showWalkthrough: handleShowWalkthrough,
showWalkthrough: handleShowWalkthroughCommand,
showSettings: openSettings,
connectProvider: handleConnectProvider,
}), [
@@ -577,7 +600,7 @@ export function SessionDetail() {
handleRedo,
handleShowMcpDialog,
handleShowSkillsDialog,
handleShowWalkthrough,
handleShowWalkthroughCommand,
openSettings,
handleConnectProvider,
]);
@@ -725,6 +748,7 @@ export function SessionDetail() {
isSessionBusy={isSessionActive}
onFileClick={handleFileClick}
onChildSessionClick={handleChildSessionClick}
onOpenWalkthrough={handleShowWalkthrough}
onUndoMessage={handleUndoMessage}
model={modelRef ? formatOpenCodeModelRef(modelRef) : undefined}
/>
@@ -822,6 +846,7 @@ export function SessionDetail() {
selectedFilePath={selectedFilePath}
repoDirectory={repoDirectory}
onSkillLoaded={handleSkillLoaded}
walkthroughSourceRequest={walkthroughSourceRequest}
/>
)}
</div>
@@ -897,6 +922,7 @@ export function SessionDetail() {
sessionId={sessionId}
open={!docked && walkthroughOpen}
onOpenChange={setWalkthroughOpen}
sourceRequest={walkthroughSourceRequest}
/>
)}