feat: add multi-run fusion and session change walkthroughs

Fuse two to five completed multi-run entries into one synthesized session,
and explain a session's diff as ordered walkthrough stops cached by diff hash.

- Multi-run fusion service, persistence, routes and FuseRunDialog
- Change walkthrough service, persistence, routes and ChangesWalkthroughDialog
- Shared unified-diff parser plus bounded text generation, json-extract,
  text-truncate and service-error helpers
This commit is contained in:
Chris Scott committed 2026-10-06 15:27:14 -04:00
1 parent 90c6ccf236
commit b36d412ca2
66 files changed
+6228 -468

No files matched your search

@@ -0,0 +1,112 @@
import { Plus, Minus } from "lucide-react";
import { cn } from "@/lib/utils";
import { parseDiffLines, type DiffLine } from "@opencode-manager/shared/utils";
export function DiffLineRow({
line,
showLineNumbers,
onLineClick,
}: {
line: DiffLine;
showLineNumbers: boolean;
onLineClick?: (lineNumber: number) => void;
}) {
if (line.type === "header") {
return (
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono break-all border-b border-border/30">
{line.content}
</div>
);
}
if (line.type === "hunk") {
return (
<div className="px-4 py-1 bg-accent/20 text-accent-foreground text-xs font-mono break-all border-b border-border/20">
{line.content}
</div>
);
}
const bgClass =
line.type === "add"
? "bg-diff-add/10"
: line.type === "remove"
? "bg-diff-delete/10"
: "";
const textClass =
line.type === "add"
? "text-diff-add"
: line.type === "remove"
? "text-diff-delete"
: "text-foreground";
const lineNumber = line.newLineNumber ?? line.oldLineNumber;
const isClickable = onLineClick && lineNumber !== undefined;
return (
<div
className={cn(
"flex font-mono text-sm border-l-2 transition-colors min-w-0",
bgClass,
line.type === "add" && "border-l-diff-add",
line.type === "remove" && "border-l-diff-delete",
line.type === "context" && "border-l-transparent",
isClickable && "cursor-pointer hover:bg-accent/30",
)}
onClick={() =>
isClickable && lineNumber !== undefined && onLineClick(lineNumber)
}
>
{showLineNumbers && (
<div className="flex-shrink-0 w-20 flex text-xs text-muted-foreground bg-muted/30 select-none">
<span className="w-10 px-2 text-right border-r border-border/50">
{line.oldLineNumber || ""}
</span>
<span className="w-10 px-2 text-right border-r border-border/50">
{line.newLineNumber || ""}
</span>
</div>
)}
<div className="w-6 flex-shrink-0 flex items-center justify-center bg-muted/20">
{line.type === "add" && (
<Plus className="w-3 h-3 text-diff-add" />
)}
{line.type === "remove" && (
<Minus className="w-3 h-3 text-diff-delete" />
)}
</div>
<pre
className={cn(
"flex-1 min-w-0 px-2 py-0.5 whitespace-pre-wrap break-words overflow-hidden",
textClass,
)}
>
{line.content || " "}
</pre>
</div>
);
}
export function DiffLines({
diff,
showLineNumbers = true,
onLineClick,
}: {
diff: string;
showLineNumbers?: boolean;
onLineClick?: (line: number) => void;
}) {
return (
<>
{parseDiffLines(diff).map((line, index) => (
<DiffLineRow
key={index}
line={line}
showLineNumbers={showLineNumbers}
onLineClick={onLineClick}
/>
))}
</>
);
}
@@ -6,8 +6,6 @@ import {
FileX,
FileEdit,
File,
Plus,
Minus,
ArrowLeft,
ExternalLink,
X,
@@ -17,6 +15,7 @@ import { CopyButton } from "@/components/ui/copy-button";
import { cn } from "@/lib/utils";
import type { GitFileStatusType } from "@/types/git";
import { GIT_STATUS_COLORS, GIT_STATUS_LABELS } from "@/lib/git-status-styles";
import { DiffLines } from "./DiffLines";
interface FileDiffViewProps {
repoId: number;
@@ -29,63 +28,6 @@ interface FileDiffViewProps {
isMobile?: boolean;
}
interface DiffLine {
type: "add" | "remove" | "context" | "header" | "hunk";
content: string;
oldLineNumber?: number;
newLineNumber?: number;
}
function parseDiff(diff: string): DiffLine[] {
const lines = diff.split("\n");
const result: DiffLine[] = [];
let oldLine = 0;
let newLine = 0;
for (const line of lines) {
if (
line.startsWith("diff --git") ||
line.startsWith("index ") ||
line.startsWith("---") ||
line.startsWith("+++")
) {
result.push({ type: "header", content: line });
} else if (line.startsWith("@@")) {
const match = line.match(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
if (match) {
oldLine = parseInt(match[1], 10);
newLine = parseInt(match[2], 10);
}
result.push({ type: "hunk", content: line });
} else if (line.startsWith("+")) {
result.push({
type: "add",
content: line.substring(1),
newLineNumber: newLine,
});
newLine++;
} else if (line.startsWith("-")) {
result.push({
type: "remove",
content: line.substring(1),
oldLineNumber: oldLine,
});
oldLine++;
} else if (line.startsWith(" ") || line === "") {
result.push({
type: "context",
content: line.substring(1) || "",
oldLineNumber: oldLine,
newLineNumber: newLine,
});
oldLine++;
newLine++;
}
}
return result;
}
const statusConfig: Record<
GitFileStatusType,
{ icon: typeof FileText; color: string; bgColor: string; label: string }
@@ -128,92 +70,6 @@ const statusConfig: Record<
},
};
function DiffLineComponent({
line,
showLineNumbers,
onLineClick,
}: {
line: DiffLine;
showLineNumbers: boolean;
onLineClick?: (lineNumber: number) => void;
}) {
if (line.type === "header") {
return (
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono break-all border-b border-border/30">
{line.content}
</div>
);
}
if (line.type === "hunk") {
return (
<div className="px-4 py-1 bg-accent/20 text-accent-foreground text-xs font-mono break-all border-b border-border/20">
{line.content}
</div>
);
}
const bgClass =
line.type === "add"
? "bg-diff-add/10"
: line.type === "remove"
? "bg-diff-delete/10"
: "";
const textClass =
line.type === "add"
? "text-diff-add"
: line.type === "remove"
? "text-diff-delete"
: "text-foreground";
const lineNumber = line.newLineNumber ?? line.oldLineNumber;
const isClickable = onLineClick && lineNumber !== undefined;
return (
<div
className={cn(
"flex font-mono text-sm border-l-2 transition-colors min-w-0",
bgClass,
line.type === "add" && "border-l-diff-add",
line.type === "remove" && "border-l-diff-delete",
line.type === "context" && "border-l-transparent",
isClickable && "cursor-pointer hover:bg-accent/30",
)}
onClick={() =>
isClickable && lineNumber !== undefined && onLineClick(lineNumber)
}
>
{showLineNumbers && (
<div className="flex-shrink-0 w-20 flex text-xs text-muted-foreground bg-muted/30 select-none">
<span className="w-10 px-2 text-right border-r border-border/50">
{line.oldLineNumber || ""}
</span>
<span className="w-10 px-2 text-right border-r border-border/50">
{line.newLineNumber || ""}
</span>
</div>
)}
<div className="w-6 flex-shrink-0 flex items-center justify-center bg-muted/20">
{line.type === "add" && (
<Plus className="w-3 h-3 text-diff-add" />
)}
{line.type === "remove" && (
<Minus className="w-3 h-3 text-diff-delete" />
)}
</div>
<pre
className={cn(
"flex-1 min-w-0 px-2 py-0.5 whitespace-pre-wrap break-words overflow-hidden",
textClass,
)}
>
{line.content || " "}
</pre>
</div>
);
}
export function FileDiffView({
repoId,
filePath,
@@ -263,7 +119,6 @@ export function FileDiffView({
const config = statusConfig[diffData.status];
const Icon = config.icon;
const diffLines = diffData.diff ? parseDiff(diffData.diff) : [];
return (
<div className="flex flex-col h-full bg-background overflow-hidden">
@@ -362,18 +217,15 @@ export function FileDiffView({
</div>
) : (
<div className="border-t border-border/30">
{diffLines.map((line, index) => (
<DiffLineComponent
key={index}
line={line}
showLineNumbers={!isMobile}
onLineClick={
onOpenFile
? (lineNum) => onOpenFile(filePath, lineNum)
: undefined
}
/>
))}
<DiffLines
diff={diffData.diff}
showLineNumbers={!isMobile}
onLineClick={
onOpenFile
? (lineNum) => onOpenFile(filePath, lineNum)
: undefined
}
/>
</div>
)}
</div>
@@ -0,0 +1,405 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { FuseRunDialog } from './FuseRunDialog'
import { FetchError } from '@/api/fetchWrapper'
import type { FuseMultiRunRequest, MultiRun } from '@opencode-manager/shared/schemas'
const mocks = vi.hoisted(() => ({
fuseMultiRun: vi.fn(),
listMultiRuns: vi.fn(),
launchMultiRun: vi.fn(),
discardMultiRunEntry: vi.fn(),
useProvidersWithModels: vi.fn(),
useOpenCodeModelState: vi.fn(),
listBranches: vi.fn(),
}))
vi.mock('@/api/multiRuns', () => ({
fuseMultiRun: mocks.fuseMultiRun,
listMultiRuns: mocks.listMultiRuns,
launchMultiRun: mocks.launchMultiRun,
discardMultiRunEntry: mocks.discardMultiRunEntry,
}))
vi.mock('@/hooks/useProvidersWithModels', () => ({
useProvidersWithModels: mocks.useProvidersWithModels,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
}))
vi.mock('@/api/repos', () => ({
listBranches: mocks.listBranches,
}))
vi.mock('@/lib/toast', () => ({
showToast: {
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
},
}))
const providers = [
{
id: 'openai',
name: 'OpenAI',
source: 'configured',
isConnected: true,
models: [
{ id: 'gpt-4o', name: 'GPT-4o' },
{ id: 'gpt-4.1', name: 'GPT-4.1' },
],
},
{
id: 'anthropic',
name: 'Anthropic',
source: 'configured',
isConnected: true,
models: [{ id: 'claude-opus', name: 'Claude Opus' }],
},
]
const run: MultiRun = {
id: 3,
repoId: 7,
name: 'Sweep',
prompt: 'go',
isolated: true,
baseRef: 'main',
createdAt: 1,
entries: [
{
id: 11,
model: 'openai/gpt-4o',
status: 'started',
sessionId: 'ses_1',
directory: '/workspaces/sweep-1',
isolated: true,
error: null,
createdAt: 1,
updatedAt: 1,
},
{
id: 12,
model: 'anthropic/claude-opus',
status: 'started',
sessionId: 'ses_2',
directory: '/workspaces/sweep-2',
isolated: true,
error: null,
createdAt: 1,
updatedAt: 1,
},
{
id: 13,
model: 'openai/gpt-4.1',
status: 'failed',
sessionId: null,
directory: null,
isolated: true,
error: 'launch failed',
createdAt: 1,
updatedAt: 1,
},
],
fusions: [],
}
const nonIsolatedRun: MultiRun = {
...run,
entries: run.entries.map((entry) => (entry.id === 11 ? { ...entry, isolated: false } : entry)),
}
function createWrapper() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
function renderFuseDialog(overrides: Partial<React.ComponentProps<typeof FuseRunDialog>> = {}) {
const onOpenChange = vi.fn()
const onOpenSession = vi.fn()
const view = render(
<FuseRunDialog
repoId={7}
directory="/repo"
run={run}
open
onOpenChange={onOpenChange}
onOpenSession={onOpenSession}
{...overrides}
/>,
{ wrapper: createWrapper() },
)
return { ...view, onOpenChange, onOpenSession }
}
async function selectSourcesAndModel(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole('checkbox', { name: 'openai/gpt-4o' }))
await user.click(screen.getByRole('checkbox', { name: 'anthropic/claude-opus' }))
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
}
describe('FuseRunDialog', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
Element.prototype.scrollIntoView ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
mocks.useProvidersWithModels.mockReturnValue({ data: providers, isLoading: false })
mocks.useOpenCodeModelState.mockReturnValue({ data: { recent: [], favorite: [], variant: {} } })
mocks.listBranches.mockResolvedValue({
branches: [
{ name: 'main', type: 'local', current: true },
{ name: 'feature', type: 'local', current: false },
],
status: { ahead: 0, behind: 0 },
})
})
it('only allows started sources and blocks submit until two sources and a model are selected', async () => {
const user = userEvent.setup()
renderFuseDialog()
const failed = screen.getByRole('checkbox', { name: 'openai/gpt-4.1' })
expect(failed).toBeDisabled()
const submit = screen.getByRole('button', { name: 'Fuse' })
expect(submit).toBeDisabled()
await user.click(screen.getByRole('checkbox', { name: 'openai/gpt-4o' }))
expect(submit).toBeDisabled()
await user.click(screen.getByRole('checkbox', { name: 'anthropic/claude-opus' }))
expect(submit).toBeDisabled()
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
expect(submit).toBeEnabled()
})
it('replaces the synthesis model when a different model is toggled', async () => {
const user = userEvent.setup()
renderFuseDialog()
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
expect(screen.getByRole('checkbox', { name: 'GPT-4o' })).toBeChecked()
await user.click(screen.getByRole('checkbox', { name: 'Claude Opus' }))
expect(screen.getByRole('checkbox', { name: 'GPT-4o' })).not.toBeChecked()
expect(screen.getByRole('checkbox', { name: 'Claude Opus' })).toBeChecked()
})
it('submits the selected sources, model, instructions and workspace', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockResolvedValue({ ...run, fusions: [] })
renderFuseDialog()
await selectSourcesAndModel(user)
await user.type(screen.getByLabelText('Instructions'), 'Merge the best ideas')
await user.click(screen.getByRole('button', { name: 'Fuse' }))
await waitFor(() => {
expect(mocks.fuseMultiRun).toHaveBeenCalledTimes(1)
})
const [runId, request] = mocks.fuseMultiRun.mock.calls[0] as [number, FuseMultiRunRequest]
expect(runId).toBe(3)
expect(request).toEqual({
requestId: expect.stringMatching(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/),
entryIds: [11, 12],
model: 'openai/gpt-4o',
instructions: 'Merge the best ideas',
isolate: true,
baseRef: 'main',
})
})
it('does not submit again while the request is pending', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockReturnValue(new Promise(() => {}))
renderFuseDialog()
await selectSourcesAndModel(user)
const submit = screen.getByRole('button', { name: 'Fuse' })
await user.click(submit)
await user.click(submit)
expect(mocks.fuseMultiRun).toHaveBeenCalledTimes(1)
})
it('lists unavailable sources and reasons from a 409 response', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockRejectedValue(
new FetchError('Some selected results are not ready to fuse', 409, 'FUSION_SOURCES_UNAVAILABLE', undefined, {
details: {
unavailableSources: [
{ entryId: 12, model: 'anthropic/claude-opus', reason: 'running', message: 'The session is still running.' },
],
},
}),
)
renderFuseDialog()
await selectSourcesAndModel(user)
await user.click(screen.getByRole('button', { name: 'Fuse' }))
expect(await screen.findByText('anthropic/claude-opus: The session is still running.')).toBeInTheDocument()
})
it('shows the context limit message for a 413 response', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockRejectedValue(
new FetchError('The selected results are too large to fuse.', 413, 'FUSION_CONTEXT_LIMIT'),
)
renderFuseDialog()
await selectSourcesAndModel(user)
await user.click(screen.getByRole('button', { name: 'Fuse' }))
expect(
await screen.findByText('Too much context: select fewer sources or shorten instructions'),
).toBeInTheDocument()
})
it('closes and opens the new session when the fusion starts', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockImplementation((_runId: number, request: FuseMultiRunRequest) =>
Promise.resolve({
...run,
fusions: [
{
id: 1,
requestId: request.requestId,
model: request.model,
instructions: null,
isolated: true,
baseRef: 'main',
status: 'started',
sessionId: 'ses_fusion',
directory: '/workspaces/fusion',
error: null,
sources: [],
createdAt: 1,
updatedAt: 1,
},
],
}),
)
const { onOpenChange, onOpenSession } = renderFuseDialog()
await selectSourcesAndModel(user)
await user.click(screen.getByRole('button', { name: 'Fuse' }))
await waitFor(() => {
expect(onOpenSession).toHaveBeenCalledWith('ses_fusion', true)
})
expect(onOpenChange).toHaveBeenCalledWith(false)
})
it('regenerates the request id after a failed fusion so retries are idempotent per failure', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockImplementation((_runId: number, request: FuseMultiRunRequest) =>
Promise.resolve({
...run,
fusions: [
{
id: 1,
requestId: request.requestId,
model: request.model,
instructions: null,
isolated: true,
baseRef: 'main',
status: 'failed',
sessionId: null,
directory: null,
error: 'launch failed',
sources: [],
createdAt: 1,
updatedAt: 1,
},
],
}),
)
renderFuseDialog()
await selectSourcesAndModel(user)
const submit = screen.getByRole('button', { name: 'Fuse' })
await user.click(submit)
await waitFor(() => expect(mocks.fuseMultiRun).toHaveBeenCalledTimes(1))
await user.click(submit)
await waitFor(() => expect(mocks.fuseMultiRun).toHaveBeenCalledTimes(2))
const first = mocks.fuseMultiRun.mock.calls[0][1] as FuseMultiRunRequest
const second = mocks.fuseMultiRun.mock.calls[1][1] as FuseMultiRunRequest
expect(second.requestId).not.toBe(first.requestId)
})
it('runs in the repository checkout and omits the base ref when isolation is off', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockResolvedValue({ ...run, fusions: [] })
renderFuseDialog()
await user.click(screen.getByRole('switch', { name: 'Isolated workspace' }))
expect(screen.getByText('Runs in the repository checkout.')).toBeInTheDocument()
expect(screen.queryByRole('combobox', { name: 'Start from' })).not.toBeInTheDocument()
await selectSourcesAndModel(user)
await user.click(screen.getByRole('button', { name: 'Fuse' }))
await waitFor(() => expect(mocks.fuseMultiRun).toHaveBeenCalledTimes(1))
const [, request] = mocks.fuseMultiRun.mock.calls[0] as [number, FuseMultiRunRequest]
expect(request).toMatchObject({ isolate: false })
expect(request).not.toHaveProperty('baseRef')
})
it('forces isolation when a selected source ran in the repository checkout', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockResolvedValue({ ...nonIsolatedRun, fusions: [] })
renderFuseDialog({ run: nonIsolatedRun })
expect(screen.getByRole('switch', { name: 'Isolated workspace' })).toBeEnabled()
await selectSourcesAndModel(user)
const toggle = screen.getByRole('switch', { name: 'Isolated workspace' })
expect(toggle).toBeChecked()
expect(toggle).toBeDisabled()
expect(
screen.getByText('Isolation is required because a selected result ran in the repository checkout'),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Fuse' }))
await waitFor(() => expect(mocks.fuseMultiRun).toHaveBeenCalledTimes(1))
const [, request] = mocks.fuseMultiRun.mock.calls[0] as [number, FuseMultiRunRequest]
expect(request).toMatchObject({ isolate: true, baseRef: 'main' })
})
it('shows the recovered-attempt message when an earlier fusion is already running', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockRejectedValue(
new FetchError('An earlier fusion attempt is already running', 409, 'FUSION_ATTEMPT_RECOVERED', undefined, {
details: { fusions: [{ fusionId: 1, sessionId: 'ses_1' }] },
}),
)
renderFuseDialog()
await selectSourcesAndModel(user)
await user.click(screen.getByRole('button', { name: 'Fuse' }))
expect(
await screen.findByText('An earlier attempt is already running. Open it from the Fusions list.'),
).toBeInTheDocument()
})
})
@@ -0,0 +1,288 @@
import { useCallback, useDeferredValue, useEffect, useMemo, useState } from 'react'
import { Loader2, Search } from 'lucide-react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
import { Checkbox } from '@/components/ui/checkbox'
import { Label } from '@/components/ui/label'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { BranchCombobox } from '@/components/repo/BranchCombobox'
import { ModelCheckboxList } from '@/components/repo/ModelCheckboxList'
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
import { useOpenCodeModelState } from '@/hooks/useModelSelection'
import { useFuseMultiRun } from '@/hooks/useMultiRuns'
import { buildModelSections, filterModelSections } from '@/lib/modelSections'
import { randomId } from '@/lib/utils'
import {
FUSION_INSTRUCTIONS_MAX_LENGTH,
FusionUnavailableDetailsSchema,
MULTI_RUN_FUSION_MIN_SOURCES,
type FuseMultiRunRequest,
type MultiRun,
type MultiRunEntryStatus,
} from '@opencode-manager/shared/schemas'
interface FuseRunDialogProps {
repoId: number
directory?: string
run: MultiRun
open: boolean
onOpenChange: (open: boolean) => void
onOpenSession: (sessionId: string, isolated: boolean) => void
}
const ENTRY_STATUS_LABELS: Record<MultiRunEntryStatus, string> = {
starting: 'Starting',
started: 'Started',
failed: 'Failed',
discarded: 'Discarded',
}
function unavailableDetails(error: unknown) {
const parsed = FusionUnavailableDetailsSchema.safeParse((error as { details?: unknown } | null)?.details)
return parsed.success ? parsed.data : null
}
export function FuseRunDialog({
repoId,
directory,
run,
open,
onOpenChange,
onOpenSession,
}: FuseRunDialogProps) {
const [selectedEntryIds, setSelectedEntryIds] = useState<number[]>([])
const [selectedModel, setSelectedModel] = useState<string | null>(null)
const [instructions, setInstructions] = useState('')
const [isolate, setIsolate] = useState(true)
const [baseRef, setBaseRef] = useState('')
const [modelSearch, setModelSearch] = useState('')
const [requestId, setRequestId] = useState(() => randomId())
const deferredModelSearch = useDeferredValue(modelSearch)
const fuse = useFuseMultiRun(repoId)
const { data: providers } = useProvidersWithModels({ enabled: open, directory })
const { data: modelState } = useOpenCodeModelState(directory, open)
useEffect(() => {
if (!open) return
setSelectedEntryIds([])
setSelectedModel(null)
setInstructions('')
setIsolate(true)
setBaseRef(run.baseRef ?? '')
setModelSearch('')
setRequestId(randomId())
}, [open, run.id, run.baseRef])
const modelSections = useMemo(() => buildModelSections(providers, modelState), [providers, modelState])
const visibleModelSections = useMemo(
() => filterModelSections(modelSections, deferredModelSearch),
[modelSections, deferredModelSearch],
)
const selectedModels = useMemo(() => (selectedModel ? [selectedModel] : []), [selectedModel])
const requiresIsolation = useMemo(
() => run.entries.some((entry) => selectedEntryIds.includes(entry.id) && !entry.isolated),
[run.entries, selectedEntryIds],
)
const effectiveIsolate = requiresIsolation || isolate
const toggleEntry = useCallback((entryId: number, checked: boolean) => {
setSelectedEntryIds((current) => {
if (checked) {
if (current.includes(entryId)) return current
return [...current, entryId]
}
return current.filter((id) => id !== entryId)
})
}, [])
const toggleModel = useCallback((value: string, checked: boolean) => {
setSelectedModel(checked ? value : null)
}, [])
const canSubmit =
selectedEntryIds.length >= MULTI_RUN_FUSION_MIN_SOURCES && selectedModel !== null && !fuse.isPending
const handleSubmit = () => {
if (!selectedModel) return
const trimmedInstructions = instructions.trim()
const request: FuseMultiRunRequest = {
requestId,
entryIds: selectedEntryIds,
model: selectedModel,
...(trimmedInstructions ? { instructions: trimmedInstructions } : {}),
isolate: effectiveIsolate,
...(effectiveIsolate && baseRef ? { baseRef } : {}),
}
fuse.mutate(
{ runId: run.id, request },
{
onSuccess: (result) => {
const fusion = result.fusions.find((candidate) => candidate.requestId === requestId)
if (fusion?.status === 'started' && fusion.sessionId) {
onOpenChange(false)
onOpenSession(fusion.sessionId, fusion.isolated)
} else if (fusion?.status === 'failed') {
setRequestId(randomId())
}
},
},
)
}
const details = unavailableDetails(fuse.error)
const errorCode = (fuse.error as { code?: string } | null)?.code
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen keyboardAware className="sm:max-w-2xl sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 pb-safe">
<DialogHeader className="p-4 sm:p-6 border-b shrink-0">
<DialogTitle>Fuse results</DialogTitle>
<DialogDescription>
Ask one model to synthesise the selected results from “{run.name}”.
</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-4">
<div className="space-y-2">
<Label>Sources</Label>
<div className="divide-y divide-border rounded-md border border-border">
{run.entries.map((entry) => {
const selectable = entry.status === 'started' && !!entry.sessionId
return (
<label key={entry.id} className="flex items-center gap-2 px-3 py-2 text-sm">
<Checkbox
aria-label={entry.model}
checked={selectedEntryIds.includes(entry.id)}
disabled={!selectable}
onCheckedChange={(next) => toggleEntry(entry.id, next === true)}
/>
<span className="min-w-0 flex-1 truncate">{entry.model}</span>
<div className="flex shrink-0 items-center gap-2">
{entry.sessionId ? <SessionStatusIndicator sessionID={entry.sessionId} size="sm" /> : null}
<span className="text-xs text-muted-foreground">{ENTRY_STATUS_LABELS[entry.status]}</span>
</div>
</label>
)
})}
</div>
<p className="text-xs text-muted-foreground">
Select at least {MULTI_RUN_FUSION_MIN_SOURCES} completed results.
</p>
</div>
<div className="space-y-2">
<Label>Synthesis model</Label>
<div className="relative">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={modelSearch}
onChange={(event) => setModelSearch(event.target.value)}
placeholder="Search models..."
aria-label="Search models"
autoComplete="off"
className="pl-9"
/>
</div>
<div className="max-h-56 overflow-y-auto rounded-md border border-border divide-y divide-border">
<ModelCheckboxList
sections={visibleModelSections}
selectedModels={selectedModels}
onToggle={toggleModel}
emptyLabel={modelSections.length === 0 ? 'No models available.' : 'No models match your search.'}
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="fusion-instructions">Instructions</Label>
<Textarea
id="fusion-instructions"
value={instructions}
onChange={(event) => setInstructions(event.target.value)}
maxLength={FUSION_INSTRUCTIONS_MAX_LENGTH}
placeholder="Optional guidance for the synthesis"
rows={3}
/>
</div>
<div className="flex items-center justify-between rounded-lg border border-border p-3">
<div className="space-y-0.5">
<Label htmlFor="fusion-isolate">Isolated workspace</Label>
<p className="text-xs text-muted-foreground">
{requiresIsolation
? 'Isolation is required because a selected result ran in the repository checkout'
: 'Run the synthesis in its own workspace.'}
</p>
</div>
<Switch
id="fusion-isolate"
checked={effectiveIsolate}
disabled={requiresIsolation}
onCheckedChange={setIsolate}
/>
</div>
{effectiveIsolate ? (
<div className="space-y-1.5">
<Label htmlFor="fusion-base-ref">Start from</Label>
<BranchCombobox
id="fusion-base-ref"
repoId={repoId}
value={baseRef}
onValueChange={setBaseRef}
placeholder="Current HEAD"
clearable
/>
<p className="text-xs text-muted-foreground">
{baseRef ? `Starts from ${baseRef}` : 'Starts from current HEAD'}; source workspaces are not modified
or merged.
</p>
</div>
) : (
<p className="text-xs text-muted-foreground">Runs in the repository checkout.</p>
)}
{fuse.error ? (
<div className="space-y-1">
{details ? (
details.unavailableSources.map((source) => (
<p key={source.entryId} className="text-sm text-destructive">
{source.model}: {source.message}
</p>
))
) : errorCode === 'FUSION_CONTEXT_LIMIT' ? (
<p className="text-sm text-destructive">Too much context: select fewer sources or shorten instructions</p>
) : errorCode === 'FUSION_ATTEMPT_RECOVERED' ? (
<p className="text-sm text-destructive">
An earlier attempt is already running. Open it from the Fusions list.
</p>
) : (
<p className="text-sm text-destructive">
{fuse.error instanceof Error ? fuse.error.message : 'Failed to start fusion'}
</p>
)}
</div>
) : null}
<div className="flex justify-end">
<Button onClick={handleSubmit} disabled={!canSubmit}>
{fuse.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Fusing...
</>
) : (
'Fuse'
)}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,54 @@
import { memo } from 'react'
import { Checkbox } from '@/components/ui/checkbox'
import type { ModelSection } from '@/lib/modelSections'
interface ModelCheckboxListProps {
sections: ModelSection[]
selectedModels: string[]
onToggle: (value: string, checked: boolean) => void
emptyLabel: string
maxSelected?: number
}
export const ModelCheckboxList = memo(function ModelCheckboxList({
sections,
selectedModels,
onToggle,
emptyLabel,
maxSelected,
}: ModelCheckboxListProps) {
if (sections.length === 0) {
return <p className="p-3 text-sm text-muted-foreground">{emptyLabel}</p>
}
return (
<>
{sections.map((section) => (
<div key={section.key} className="p-3 space-y-2">
<p className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
{section.icon ? <section.icon className="h-3.5 w-3.5" /> : null}
{section.title}
</p>
{section.options.map((option) => {
const checked = selectedModels.includes(option.value)
const atCapacity = maxSelected !== undefined && selectedModels.length >= maxSelected && !checked
return (
<label key={option.value} className="flex items-center gap-2 text-sm">
<Checkbox
aria-label={option.label}
checked={checked}
disabled={atCapacity}
onCheckedChange={(next) => onToggle(option.value, next === true)}
/>
<span className="truncate">{option.label}</span>
{section.pinned ? (
<span className="ml-auto shrink-0 text-xs text-muted-foreground">{option.providerName}</span>
) : null}
</label>
)
})}
</div>
))}
</>
)
})
@@ -10,9 +10,12 @@ const mocks = vi.hoisted(() => ({
listMultiRuns: vi.fn(),
launchMultiRun: vi.fn(),
discardMultiRunEntry: vi.fn(),
fuseMultiRun: vi.fn(),
useProvidersWithModels: vi.fn(),
useOpenCodeModelState: vi.fn(),
listBranches: vi.fn(),
getChangeWalkthrough: vi.fn(),
generateChangeWalkthrough: vi.fn(),
}))
const mockNavigate = vi.fn()
@@ -26,6 +29,7 @@ vi.mock('@/api/multiRuns', () => ({
listMultiRuns: mocks.listMultiRuns,
launchMultiRun: mocks.launchMultiRun,
discardMultiRunEntry: mocks.discardMultiRunEntry,
fuseMultiRun: mocks.fuseMultiRun,
}))
vi.mock('@/hooks/useProvidersWithModels', () => ({
@@ -40,6 +44,11 @@ vi.mock('@/api/repos', () => ({
listBranches: mocks.listBranches,
}))
vi.mock('@/api/changeWalkthroughs', () => ({
getChangeWalkthrough: mocks.getChangeWalkthrough,
generateChangeWalkthrough: mocks.generateChangeWalkthrough,
}))
vi.mock('@/lib/toast', () => ({
showToast: {
success: vi.fn(),
@@ -107,6 +116,67 @@ const startedRun: MultiRun = {
updatedAt: 1,
},
],
fusions: [],
}
const twoStartedRun: MultiRun = {
...startedRun,
id: 5,
name: 'Pair',
entries: [
startedRun.entries[0],
{
id: 13,
model: 'anthropic/claude-opus',
status: 'started',
sessionId: 'ses_2',
directory: '/workspaces/sweep-2',
isolated: true,
error: null,
createdAt: 1,
updatedAt: 1,
},
],
}
const fusedRun: MultiRun = {
id: 4,
repoId: 7,
name: 'Merged',
prompt: 'go',
isolated: true,
baseRef: 'main',
createdAt: 1,
entries: [
{
id: 21,
model: 'openai/gpt-4o',
status: 'discarded',
sessionId: null,
directory: null,
isolated: true,
error: null,
createdAt: 1,
updatedAt: 1,
},
],
fusions: [
{
id: 31,
requestId: 'req-1',
model: 'openai/gpt-4o',
instructions: null,
isolated: true,
baseRef: 'main',
status: 'started',
sessionId: 'ses_fusion',
directory: '/workspaces/fusion',
error: null,
sources: [{ entryId: 21, sessionId: 'ses_1', model: 'openai/gpt-4o', truncated: true }],
createdAt: 1,
updatedAt: 1,
},
],
}
function createWrapper() {
@@ -161,6 +231,7 @@ describe('MultiRunDialog', () => {
status: { ahead: 0, behind: 0 },
})
mocks.listMultiRuns.mockResolvedValue([])
mocks.getChangeWalkthrough.mockResolvedValue({ walkthrough: null, currentDiffHash: null, stale: false })
})
it('lists favorite then recent models before provider groups without duplicates', () => {
@@ -392,4 +463,69 @@ describe('MultiRunDialog', () => {
expect(mocks.discardMultiRunEntry).toHaveBeenCalledWith(3, 11)
})
})
it('disables Fuse for runs with fewer than two started entries', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([startedRun])
renderDialog()
await user.click(screen.getByRole('tab', { name: 'Runs' }))
await waitFor(() => expect(screen.getByText('openai/gpt-4o')).toBeInTheDocument())
expect(screen.getByRole('button', { name: /fuse/i })).toBeDisabled()
})
it('opens the fuse dialog for a run with two started entries', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([twoStartedRun])
renderDialog()
await user.click(screen.getByRole('tab', { name: 'Runs' }))
const fuseButton = await screen.findByRole('button', { name: /fuse/i })
expect(fuseButton).toBeEnabled()
await user.click(fuseButton)
expect(await screen.findByRole('dialog', { name: 'Fuse results' })).toBeInTheDocument()
})
it('lists fusions with truncation and opens the fusion session', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([fusedRun])
renderDialog()
await user.click(screen.getByRole('tab', { name: 'Runs' }))
await waitFor(() => expect(screen.getByText('Fusions')).toBeInTheDocument())
expect(screen.getByText('from 1 source (truncated)')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /open/i }))
expect(mockNavigate).toHaveBeenCalledWith('/repos/7/sessions/ses_fusion?repoTab=workspaces')
})
it('opens the walkthrough dialog for an entry session', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([startedRun])
renderDialog()
await user.click(screen.getByRole('tab', { name: 'Runs' }))
await waitFor(() => expect(screen.getByText('openai/gpt-4o')).toBeInTheDocument())
await user.click(screen.getByRole('button', { name: /walkthrough/i }))
expect(await screen.findByText('Change walkthrough')).toBeInTheDocument()
await waitFor(() => expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1'))
})
it('opens the walkthrough dialog for a fusion session', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([fusedRun])
renderDialog()
await user.click(screen.getByRole('tab', { name: 'Runs' }))
await waitFor(() => expect(screen.getByText('Fusions')).toBeInTheDocument())
await user.click(screen.getByRole('button', { name: /walkthrough/i }))
expect(await screen.findByText('Change walkthrough')).toBeInTheDocument()
await waitFor(() => expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_fusion'))
})
})
+160 -166
View File
@@ -1,35 +1,34 @@
import { memo, useCallback, useDeferredValue, useEffect, useMemo, useState, type ReactNode } from 'react'
import { useCallback, useDeferredValue, useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Loader2, Trash2, ArrowUpRight, Clock, Search, Star } from 'lucide-react'
import { Loader2, Trash2, ArrowUpRight, Search, Combine, BookOpen } from 'lucide-react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
import { Checkbox } from '@/components/ui/checkbox'
import { Badge } from '@/components/ui/badge'
import { Label } from '@/components/ui/label'
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { BranchCombobox } from '@/components/repo/BranchCombobox'
import { ModelCheckboxList } from '@/components/repo/ModelCheckboxList'
import { FuseRunDialog } from '@/components/repo/FuseRunDialog'
import { ChangesWalkthroughDialog } from '@/components/session/ChangesWalkthroughDialog'
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
import { useOpenCodeModelState } from '@/hooks/useModelSelection'
import { useDiscardMultiRunEntry, useLaunchMultiRun, useMultiRuns } from '@/hooks/useMultiRuns'
import {
formatModelName,
formatProviderName,
providerModelRef,
type ModelSelection,
type OpenCodeModelState,
type ProviderWithModels,
} from '@/api/providers'
import { buildModelSections, filterModelSections } from '@/lib/modelSections'
import { buildSessionPath } from '@opencode-manager/shared/utils'
import {
MULTI_RUN_FUSION_MIN_SOURCES,
MULTI_RUN_MAX_MODELS,
type LaunchMultiRunRequest,
type MultiRun,
type MultiRunEntry,
type MultiRunEntryStatus,
type MultiRunFusion,
type MultiRunFusionStatus,
} from '@opencode-manager/shared/schemas'
interface MultiRunDialogProps {
@@ -47,21 +46,6 @@ interface PendingDiscard {
isolated: boolean
}
interface ModelOption {
value: string
label: string
providerName: string
searchText: string
}
interface ModelSection {
key: string
title: string
icon?: ReactNode
pinned: boolean
options: ModelOption[]
}
const STATUS_LABELS: Record<MultiRunEntryStatus, string> = {
starting: 'Starting',
started: 'Started',
@@ -69,52 +53,10 @@ const STATUS_LABELS: Record<MultiRunEntryStatus, string> = {
discarded: 'Discarded',
}
function buildModelSections(providers: ProviderWithModels[], modelState: OpenCodeModelState | undefined): ModelSection[] {
const optionsByValue = new Map<string, ModelOption>()
const providerSections = providers.map((provider): ModelSection => {
const providerName = formatProviderName(provider)
const options = provider.models.map((model) => {
const label = formatModelName(model)
const value = providerModelRef(provider, model)
const option = { value, label, providerName, searchText: `${label} ${value} ${providerName}`.toLowerCase() }
optionsByValue.set(value, option)
return option
})
return { key: `provider:${provider.id}`, title: providerName, pinned: false, options }
})
const pinnedValues = new Set<string>()
const pinOptions = (selections: ModelSelection[] = []) =>
selections.flatMap((selection) => {
const option = optionsByValue.get(providerModelRef({ id: selection.providerID }, { id: selection.modelID }))
if (!option || pinnedValues.has(option.value)) return []
pinnedValues.add(option.value)
return [option]
})
const favoriteOptions = pinOptions(modelState?.favorite)
const recentOptions = pinOptions(modelState?.recent)
const sections: ModelSection[] = [
{ key: 'favorites', title: 'Favorites', icon: <Star className="h-3.5 w-3.5" />, pinned: true, options: favoriteOptions },
{ key: 'recent', title: 'Recent', icon: <Clock className="h-3.5 w-3.5" />, pinned: true, options: recentOptions },
...providerSections.map((section) => ({
...section,
options: section.options.filter((option) => !pinnedValues.has(option.value)),
})),
]
return sections.filter((section) => section.options.length > 0)
}
function filterModelSections(sections: ModelSection[], query: string): ModelSection[] {
const terms = query.toLowerCase().split(/\s+/).filter(Boolean)
if (terms.length === 0) return sections
return sections
.map((section) => ({
...section,
options: section.options.filter((option) => terms.every((term) => option.searchText.includes(term))),
}))
.filter((section) => section.options.length > 0)
const FUSION_STATUS_LABELS: Record<MultiRunFusionStatus, string> = {
starting: 'Starting',
started: 'Started',
failed: 'Failed',
}
export function MultiRunDialog({
@@ -134,6 +76,8 @@ export function MultiRunDialog({
const [modelSearch, setModelSearch] = useState('')
const deferredModelSearch = useDeferredValue(modelSearch)
const [pendingDiscard, setPendingDiscard] = useState<PendingDiscard | null>(null)
const [fuseRun, setFuseRun] = useState<MultiRun | null>(null)
const [walkthroughSessionId, setWalkthroughSessionId] = useState<string | null>(null)
const { data: providers } = useProvidersWithModels({ enabled: open, directory })
const { data: modelState } = useOpenCodeModelState(directory, open)
@@ -183,10 +127,9 @@ export function MultiRunDialog({
launch.mutate(request, { onSuccess: () => setActiveTab('runs') })
}
const openEntry = (entry: MultiRunEntry) => {
if (!entry.sessionId) return
const openEntry = (sessionId: string, isolated: boolean) => {
onOpenChange(false)
navigate(buildSessionPath(repoId, entry.sessionId, entry.isolated ? { repoTab: 'workspaces' } : undefined))
navigate(buildSessionPath(repoId, sessionId, isolated ? { repoTab: 'workspaces' } : undefined))
}
const confirmDiscard = () => {
@@ -264,6 +207,7 @@ export function MultiRunDialog({
selectedModels={selectedModels}
onToggle={toggleModel}
emptyLabel={modelSections.length === 0 ? 'No models available.' : 'No models match your search.'}
maxSelected={MULTI_RUN_MAX_MODELS}
/>
</div>
</div>
@@ -317,53 +261,112 @@ export function MultiRunDialog({
) : runs.length === 0 ? (
<p className="text-sm text-muted-foreground">No runs yet.</p>
) : (
runs.map((run) => (
<div key={run.id} className="rounded-md border border-border">
<div className="flex items-center justify-between gap-2 border-b border-border px-3 py-2">
<span className="truncate text-sm font-medium">{run.name}</span>
<span className="shrink-0 text-xs text-muted-foreground">
{run.entries.length} model{run.entries.length === 1 ? '' : 's'}
</span>
</div>
<div className="divide-y divide-border">
{run.entries.map((entry) => (
<div key={entry.id} className="flex flex-wrap items-center gap-2 px-3 py-2">
<span className="min-w-0 flex-1 truncate text-sm">{entry.model}</span>
<EntryStatus entry={entry} />
{entry.status === 'failed' && entry.error ? (
<span className="w-full text-xs text-destructive">{entry.error}</span>
) : null}
<div className="flex items-center gap-1">
{entry.sessionId ? (
<Button variant="ghost" size="sm" onClick={() => openEntry(entry)}>
<ArrowUpRight className="mr-1 h-3.5 w-3.5" />
Open
</Button>
) : null}
{entry.status === 'started' || entry.status === 'failed' ? (
<Button
variant="ghost"
size="sm"
className="text-destructive hover:text-destructive"
onClick={() =>
setPendingDiscard({
runId: run.id,
entryId: entry.id,
model: entry.model,
isolated: entry.isolated,
})
}
>
<Trash2 className="mr-1 h-3.5 w-3.5" />
Discard
</Button>
) : null}
</div>
runs.map((run) => {
const startedEntries = run.entries.filter(
(entry) => entry.status === 'started' && entry.sessionId,
).length
return (
<div key={run.id} className="rounded-md border border-border">
<div className="flex items-center justify-between gap-2 border-b border-border px-3 py-2">
<span className="truncate text-sm font-medium">{run.name}</span>
<div className="flex shrink-0 items-center gap-1">
<span className="text-xs text-muted-foreground">
{run.entries.length} model{run.entries.length === 1 ? '' : 's'}
</span>
<Button
variant="ghost"
size="sm"
disabled={startedEntries < MULTI_RUN_FUSION_MIN_SOURCES}
onClick={() => setFuseRun(run)}
>
<Combine className="mr-1 h-3.5 w-3.5" />
Fuse
</Button>
</div>
))}
</div>
<div className="divide-y divide-border">
{run.entries.map((entry) => {
const sessionId = entry.sessionId
return (
<div key={entry.id} className="flex flex-wrap items-center gap-2 px-3 py-2">
<span className="min-w-0 flex-1 truncate text-sm">{entry.model}</span>
<EntryStatus entry={entry} />
{entry.status === 'failed' && entry.error ? (
<span className="w-full text-xs text-destructive">{entry.error}</span>
) : null}
<div className="flex items-center gap-1">
{sessionId ? (
<Button variant="ghost" size="sm" onClick={() => openEntry(sessionId, entry.isolated)}>
<ArrowUpRight className="mr-1 h-3.5 w-3.5" />
Open
</Button>
) : null}
{sessionId ? (
<Button variant="ghost" size="sm" onClick={() => setWalkthroughSessionId(sessionId)}>
<BookOpen className="mr-1 h-3.5 w-3.5" />
Walkthrough
</Button>
) : null}
{entry.status === 'started' || entry.status === 'failed' ? (
<Button
variant="ghost"
size="sm"
className="text-destructive hover:text-destructive"
onClick={() =>
setPendingDiscard({
runId: run.id,
entryId: entry.id,
model: entry.model,
isolated: entry.isolated,
})
}
>
<Trash2 className="mr-1 h-3.5 w-3.5" />
Discard
</Button>
) : null}
</div>
</div>
)
})}
</div>
{run.fusions.length > 0 ? (
<div className="space-y-2 border-t border-border px-3 py-2">
<p className="text-xs font-medium text-muted-foreground">Fusions</p>
{run.fusions.map((fusion) => {
const truncated = fusion.sources.some((source) => source.truncated)
const sessionId = fusion.sessionId
return (
<div key={fusion.id} className="flex flex-wrap items-center gap-2">
<span className="min-w-0 flex-1 truncate text-sm">{fusion.model}</span>
<FusionStatus fusion={fusion} />
<span className="text-xs text-muted-foreground">
from {fusion.sources.length} source{fusion.sources.length === 1 ? '' : 's'}
{truncated ? ' (truncated)' : ''}
</span>
{fusion.status === 'failed' && fusion.error ? (
<span className="w-full text-xs text-destructive">{fusion.error}</span>
) : null}
{sessionId ? (
<Button variant="ghost" size="sm" onClick={() => openEntry(sessionId, fusion.isolated)}>
<ArrowUpRight className="mr-1 h-3.5 w-3.5" />
Open
</Button>
) : null}
{sessionId ? (
<Button variant="ghost" size="sm" onClick={() => setWalkthroughSessionId(sessionId)}>
<BookOpen className="mr-1 h-3.5 w-3.5" />
Walkthrough
</Button>
) : null}
</div>
)
})}
</div>
) : null}
</div>
</div>
))
)
})
)}
</TabsContent>
</Tabs>
@@ -388,58 +391,49 @@ export function MultiRunDialog({
pendingLabel="Discarding..."
isPending={discard.isPending}
/>
{fuseRun ? (
<FuseRunDialog
repoId={repoId}
directory={directory}
run={fuseRun}
open
onOpenChange={(next) => {
if (!next) setFuseRun(null)
}}
onOpenSession={(sessionId, isolated) => {
setFuseRun(null)
openEntry(sessionId, isolated)
}}
/>
) : null}
{walkthroughSessionId ? (
<ChangesWalkthroughDialog
sessionId={walkthroughSessionId}
open
onOpenChange={(next) => {
if (!next) setWalkthroughSessionId(null)
}}
/>
) : null}
</>
)
}
interface ModelCheckboxListProps {
sections: ModelSection[]
selectedModels: string[]
onToggle: (value: string, checked: boolean) => void
emptyLabel: string
}
const ModelCheckboxList = memo(function ModelCheckboxList({
sections,
selectedModels,
onToggle,
emptyLabel,
}: ModelCheckboxListProps) {
if (sections.length === 0) {
return <p className="p-3 text-sm text-muted-foreground">{emptyLabel}</p>
function FusionStatus({ fusion }: { fusion: MultiRunFusion }) {
if (fusion.status === 'started' && fusion.sessionId) {
return (
<div className="flex items-center gap-2">
<SessionStatusIndicator sessionID={fusion.sessionId} size="sm" />
<Badge variant="secondary">{FUSION_STATUS_LABELS[fusion.status]}</Badge>
</div>
)
}
return (
<>
{sections.map((section) => (
<div key={section.key} className="p-3 space-y-2">
<p className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
{section.icon}
{section.title}
</p>
{section.options.map((option) => {
const checked = selectedModels.includes(option.value)
const atCapacity = selectedModels.length >= MULTI_RUN_MAX_MODELS && !checked
return (
<label key={option.value} className="flex items-center gap-2 text-sm">
<Checkbox
aria-label={option.label}
checked={checked}
disabled={atCapacity}
onCheckedChange={(next) => onToggle(option.value, next === true)}
/>
<span className="truncate">{option.label}</span>
{section.pinned ? (
<span className="ml-auto shrink-0 text-xs text-muted-foreground">{option.providerName}</span>
) : null}
</label>
)
})}
</div>
))}
</>
)
})
const variant = fusion.status === 'failed' ? 'destructive' : 'secondary'
return <Badge variant={variant}>{FUSION_STATUS_LABELS[fusion.status]}</Badge>
}
function EntryStatus({ entry }: { entry: MultiRunEntry }) {
if (entry.status === 'started' && entry.sessionId) {
@@ -22,4 +22,22 @@ describe('ScheduleRunMarkdown links', () => {
expect(link.getAttribute('target')).toBe('_blank')
expect(link.getAttribute('rel')).toBe('noopener noreferrer')
})
it('renders raw HTML from generated prose as inert text', () => {
const payload =
'<iframe srcdoc="&lt;script&gt;parent.document.documentElement.dataset.scheduleProbe = 1&lt;/script&gt;"></iframe>'
const { container } = render(<ScheduleRunMarkdown content={`Before\n\n${payload}\n\nAfter`} />)
expect(container.querySelector('iframe')).toBeNull()
expect(container.querySelector('script')).toBeNull()
expect(document.documentElement.dataset.scheduleProbe).toBeUndefined()
expect(screen.getByText(/iframe/)).toBeInTheDocument()
})
it('still renders GFM formatting', () => {
render(<ScheduleRunMarkdown content="**bold** and `code`" onOpenLocalPath={vi.fn()} />)
expect(screen.getByText('bold').tagName).toBe('STRONG')
expect(screen.getByText('code').tagName).toBe('CODE')
})
})
@@ -1,6 +1,5 @@
import ReactMarkdown, { type Components } from 'react-markdown'
import rehypeHighlight from 'rehype-highlight'
import rehypeRaw from 'rehype-raw'
import remarkGfm from 'remark-gfm'
import { markdownComponents } from '@/components/file-browser/MarkdownComponents'
import { MarkdownLink } from '@/components/ui/markdown-link'
@@ -23,7 +22,7 @@ export function ScheduleRunMarkdown({ content, onOpenLocalPath }: ScheduleRunMar
<div className="prose prose-invert prose-enhanced max-w-none break-words text-foreground leading-snug">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeHighlight, rehypeRaw]}
rehypePlugins={[rehypeHighlight]}
components={components}
>
{content}
@@ -0,0 +1,247 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { ChangesWalkthroughDialog } from './ChangesWalkthroughDialog'
import { FetchError } from '@/api/fetchWrapper'
import type { ChangeWalkthrough, ChangeWalkthroughState } from '@opencode-manager/shared/schemas'
const mocks = vi.hoisted(() => ({
getChangeWalkthrough: vi.fn(),
generateChangeWalkthrough: vi.fn(),
}))
vi.mock('@/api/changeWalkthroughs', () => ({
getChangeWalkthrough: mocks.getChangeWalkthrough,
generateChangeWalkthrough: mocks.generateChangeWalkthrough,
}))
const walkthrough: ChangeWalkthrough = {
sessionId: 'ses_1',
diffHash: 'hash-1',
summary: 'This change adds a greeting.',
stops: [
{ title: 'Add the greeting', explanation: 'Introduces the greeting helper.', hunkIds: ['f0h0'] },
{ title: 'Wire it up', explanation: 'Calls the helper from the entry point.', hunkIds: ['f1h0'] },
],
hunks: [
{
id: 'f0h0',
file: 'src/greet.ts',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-const a = 1\n+const a = 2',
truncated: false,
},
{
id: 'f1h0',
file: 'src/main.ts',
status: 'added',
header: '@@ -0,0 +1 @@',
text: '@@ -0,0 +1 @@\n+const b = 3',
truncated: true,
},
],
omittedFiles: [{ file: 'assets/logo.png', reason: 'binary' }],
createdAt: 1,
}
function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
return { walkthrough, currentDiffHash: 'hash-1', stale: false, ...overrides }
}
function createWrapper() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
function renderDialog(overrides: Partial<React.ComponentProps<typeof ChangesWalkthroughDialog>> = {}) {
const onOpenChange = vi.fn()
const view = render(
<ChangesWalkthroughDialog sessionId="ses_1" open onOpenChange={onOpenChange} {...overrides} />,
{ wrapper: createWrapper() },
)
return { ...view, onOpenChange }
}
describe('ChangesWalkthroughDialog', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
Element.prototype.scrollIntoView ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
})
it('generates a walkthrough and renders the summary and first stop', async () => {
const user = userEvent.setup()
let generated = false
mocks.getChangeWalkthrough.mockImplementation(async () =>
generated ? state() : { walkthrough: null, currentDiffHash: 'hash-1', stale: false },
)
mocks.generateChangeWalkthrough.mockImplementation(async () => {
generated = true
return walkthrough
})
renderDialog()
const generate = await screen.findByRole('button', { name: 'Generate walkthrough' })
await user.click(generate)
await waitFor(() => {
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', {})
})
expect(await screen.findByText('This change adds a greeting.')).toBeInTheDocument()
expect(screen.getByText('Stop 1 of 2')).toBeInTheDocument()
expect(screen.getByText('src/greet.ts')).toBeInTheDocument()
expect(screen.getByText('const a = 2')).toBeInTheDocument()
expect(screen.queryByText('src/main.ts')).not.toBeInTheDocument()
expect(screen.getByText('assets/logo.png — binary file')).toBeInTheDocument()
})
it('moves through the stops with the navigator in order', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state())
renderDialog()
expect(await screen.findByText('Stop 1 of 2')).toBeInTheDocument()
expect(screen.getByText('src/greet.ts')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /previous/i })).toBeDisabled()
await user.click(screen.getByRole('button', { name: /next/i }))
expect(await screen.findByText('Stop 2 of 2')).toBeInTheDocument()
expect(screen.getByText('src/main.ts')).toBeInTheDocument()
expect(screen.queryByText('src/greet.ts')).not.toBeInTheDocument()
expect(screen.getByText('truncated')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /next/i })).toBeDisabled()
await user.click(screen.getByRole('button', { name: /previous/i }))
expect(await screen.findByText('Stop 1 of 2')).toBeInTheDocument()
})
it('shows the stale warning and regenerates', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ stale: true, currentDiffHash: 'hash-2' }))
mocks.generateChangeWalkthrough.mockResolvedValue(walkthrough)
renderDialog()
expect(
await screen.findByText('Changes have been updated since this walkthrough was generated'),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /regenerate/i }))
await waitFor(() => {
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { regenerate: true })
})
})
it('renders the no-changes message inline', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue({ walkthrough: null, currentDiffHash: null, stale: false })
mocks.generateChangeWalkthrough.mockRejectedValue(
new FetchError('This session has no changes to walk through', 409, 'WALKTHROUGH_NO_CHANGES'),
)
renderDialog()
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
expect(await screen.findByText('This session has no text changes to walk through')).toBeInTheDocument()
})
it('renders other generation errors inline', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue({ walkthrough: null, currentDiffHash: null, stale: false })
mocks.generateChangeWalkthrough.mockRejectedValue(new Error('model exploded'))
renderDialog()
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
expect(await screen.findByText('model exploded')).toBeInTheDocument()
})
it('lists the omitted files when the diff is too large to walk through', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue({ walkthrough: null, currentDiffHash: null, stale: false })
mocks.generateChangeWalkthrough.mockRejectedValue(
new FetchError('These changes are too large to walk through', 413, 'WALKTHROUGH_CONTEXT_LIMIT', undefined, {
details: {
omittedFiles: [
{ file: 'src/big.ts', reason: 'budget' },
{ file: 'assets/logo.png', reason: 'binary' },
],
},
}),
)
renderDialog()
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
expect(await screen.findByText('These changes are too large to walk through')).toBeInTheDocument()
expect(screen.getByText('src/big.ts — over the diff budget')).toBeInTheDocument()
expect(screen.getByText('assets/logo.png — binary file')).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>'
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: {
...walkthrough,
summary: `Summary ${payload}`,
stops: [{ title: 'Stop', explanation: `Explanation ${payload}`, hunkIds: ['f0h0'] }],
},
}),
)
const { container } = renderDialog()
expect(await screen.findByText(/Summary/)).toBeInTheDocument()
expect(await screen.findByText(/Explanation/)).toBeInTheDocument()
expect(container.querySelector('iframe')).toBeNull()
expect(container.querySelector('script')).toBeNull()
expect(document.documentElement.dataset.walkthroughProbe).toBeUndefined()
})
it.each([
['WALKTHROUGH_NO_CHANGES', 'This session has no changes to walk through'],
['WALKTHROUGH_NO_TEXT_CHANGES', 'This session has no text changes to walk through'],
])('recovers from a prior %s error once changes appear and the dialog is reopened', async (code, serverMessage) => {
const user = userEvent.setup()
let generated = false
mocks.getChangeWalkthrough.mockImplementation(async () =>
generated ? state() : { walkthrough: null, currentDiffHash: null, stale: false },
)
mocks.generateChangeWalkthrough
.mockRejectedValueOnce(new FetchError(serverMessage, 409, code))
.mockImplementationOnce(async () => {
generated = true
return walkthrough
})
const { rerender, onOpenChange } = renderDialog()
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
expect(await screen.findByText('This session has no text changes to walk through')).toBeInTheDocument()
rerender(<ChangesWalkthroughDialog sessionId="ses_1" open={false} onOpenChange={onOpenChange} />)
rerender(<ChangesWalkthroughDialog sessionId="ses_1" open onOpenChange={onOpenChange} />)
const generate = await screen.findByRole('button', { name: 'Generate walkthrough' })
expect(generate).toBeEnabled()
expect(screen.queryByText('This session has no text changes to walk through')).not.toBeInTheDocument()
await user.click(generate)
expect(await screen.findByText('This change adds a greeting.')).toBeInTheDocument()
expect(screen.queryByText('This session has no text changes to walk through')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,243 @@
import { memo, useEffect, useMemo, useState } from 'react'
import { ChevronLeft, ChevronRight, Loader2, RefreshCw } from 'lucide-react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
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 { WalkthroughOmittedFileSchema } from '@opencode-manager/shared/schemas'
import type { WalkthroughHunk, WalkthroughOmittedFile } from '@opencode-manager/shared/schemas'
interface ChangesWalkthroughDialogProps {
sessionId: string
open: boolean
onOpenChange: (open: boolean) => void
}
function isNoChangesError(error: unknown): boolean {
const code = (error as { code?: string } | null)?.code
return code === 'WALKTHROUGH_NO_CHANGES' || code === 'WALKTHROUGH_NO_TEXT_CHANGES'
}
function isContextLimitError(error: unknown): boolean {
return (error as { code?: string } | null)?.code === '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 instanceof Error ? error.message : 'Failed to load the walkthrough'
}
const OMITTED_REASON_LABELS: Record<WalkthroughOmittedFile['reason'], string> = {
binary: 'binary file',
budget: 'over the diff budget',
}
export const ChangesWalkthroughDialog = memo(function ChangesWalkthroughDialog({ sessionId, open, onOpenChange }: ChangesWalkthroughDialogProps) {
const stateQuery = useChangeWalkthrough(sessionId, open)
const generate = useGenerateChangeWalkthrough(sessionId)
const [stopIndex, setStopIndex] = useState(0)
const walkthrough = stateQuery.data?.walkthrough ?? null
const stale = stateQuery.data?.stale ?? false
const error = generate.error ?? stateQuery.error
const contextLimitFiles = isContextLimitError(error) ? omittedFilesFromError(error) : []
useEffect(() => {
generate.reset()
}, [open, sessionId, generate.reset])
useEffect(() => {
setStopIndex(0)
}, [open, sessionId, walkthrough?.createdAt])
const hunksById = useMemo(
() => new Map(walkthrough?.hunks.map((hunk) => [hunk.id, hunk]) ?? []),
[walkthrough],
)
const stops = walkthrough?.stops ?? []
const clampedIndex = stops.length > 0 ? Math.min(stopIndex, stops.length - 1) : 0
const selectedStop = stops[clampedIndex] ?? null
const selectedHunks = (selectedStop?.hunkIds ?? [])
.map((id) => hunksById.get(id))
.filter((hunk): hunk is WalkthroughHunk => hunk !== undefined)
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
mobileFullscreen
keyboardAware
className="sm:max-w-3xl sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 pb-safe"
>
<DialogHeader className="p-4 sm:p-6 border-b shrink-0">
<DialogTitle>Change walkthrough</DialogTitle>
<DialogDescription>Walk through this session's changes, explained step by step.</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-4">
{error ? (
<div className="space-y-2">
<p className="text-sm text-destructive">{walkthroughErrorMessage(error)}</p>
{contextLimitFiles.length > 0 ? (
<div className="space-y-1 rounded-md border border-border bg-muted/20 p-3">
<p className="text-xs font-medium text-muted-foreground">Omitted files</p>
{contextLimitFiles.map((omitted) => (
<p key={omitted.file} className="text-xs text-muted-foreground">
{omitted.file} — {OMITTED_REASON_LABELS[omitted.reason]}
</p>
))}
</div>
) : null}
</div>
) : null}
{stateQuery.isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : !walkthrough ? (
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Generate a step-by-step walkthrough of the changes in this session.
</p>
<Button
onClick={() => generate.mutate({})}
disabled={generate.isPending}
>
{generate.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Generating walkthrough…
</>
) : (
'Generate walkthrough'
)}
</Button>
</div>
) : (
<div className="space-y-4">
{stale ? (
<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.mutate({ regenerate: true })}
disabled={generate.isPending}
>
{generate.isPending ? (
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCw className="mr-2 h-3.5 w-3.5" />
)}
Regenerate
</Button>
</div>
) : null}
<ScheduleRunMarkdown content={walkthrough.summary} />
{stops.length > 0 ? (
<div className="space-y-3">
<ol className="space-y-1">
{stops.map((stop, index) => (
<li key={index}>
<button
type="button"
onClick={() => setStopIndex(index)}
aria-current={index === clampedIndex}
className={
index === clampedIndex
? 'w-full rounded-md bg-accent/40 px-2 py-1 text-left text-sm font-medium text-foreground'
: 'w-full rounded-md px-2 py-1 text-left text-sm text-muted-foreground hover:bg-accent/20'
}
>
{index + 1}. {stop.title}
</button>
</li>
))}
</ol>
<div className="flex items-center justify-between gap-2 border-t border-border pt-3">
<Button
variant="outline"
size="sm"
onClick={() => setStopIndex(clampedIndex - 1)}
disabled={clampedIndex === 0}
>
<ChevronLeft className="mr-1 h-3.5 w-3.5" />
Previous
</Button>
<span className="text-xs text-muted-foreground">
Stop {clampedIndex + 1} of {stops.length}
</span>
<Button
variant="outline"
size="sm"
onClick={() => setStopIndex(clampedIndex + 1)}
disabled={clampedIndex >= stops.length - 1}
>
Next
<ChevronRight className="ml-1 h-3.5 w-3.5" />
</Button>
</div>
{selectedStop ? (
<div className="space-y-3">
<ScheduleRunMarkdown content={selectedStop.explanation} />
{selectedHunks.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">
{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>
) : null}
</div>
) : null}
{walkthrough.omittedFiles.length > 0 ? (
<div className="space-y-1 rounded-md border border-border bg-muted/20 p-3">
<p className="text-xs font-medium text-muted-foreground">Omitted files</p>
{walkthrough.omittedFiles.map((omitted) => (
<p key={omitted.file} className="text-xs text-muted-foreground">
{omitted.file} — {OMITTED_REASON_LABELS[omitted.reason]}
</p>
))}
</div>
) : null}
</div>
)}
</div>
</DialogContent>
</Dialog>
)
})