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,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) {