feat(multi-run): add a runs sheet with inline fusion

Replace the centered Multi-run dialog and the stacked Fusion dialog with one
right-side runs sheet, turn fusion into an inline selection mode, and
pre-approve each selected source workspace for the fusion session.

- Move MultiRunDialog into a SideDrawer with Runs / New run tabs; add
  MultiRunCard, FusionComposer and an optimistic starting fusion.
- Add buildFusionSourcePermissionRuleset (external_directory allow, edit deny)
  and thread permissions through SessionLauncher.launch.
- Apply the default permission mode to fusion sessions after launch.
- Let ModelCombobox and BranchCombobox take a listClassName; make SideDrawer
  ignore an Escape already handled by a nested layer.
This commit is contained in:
Chris Scott committed 2026-10-07 11:36:36 -04:00
1 parent b0361cd98b
commit f2e06abb62
23 files changed
+2122 -1736

No files matched your search

+1 -1
View File
@@ -271,7 +271,7 @@ const sessionGoalService = new SessionGoalService(db, openCodeClient, sessionSet
})
sessionGoalService.loadOpenGoals()
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces)
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService)
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient)
sseAggregator.onEvent((directory, event) => {
+29
View File
@@ -1,3 +1,4 @@
import { resolve } from 'node:path'
import {
isSessionNotFoundError,
type FileDiffInfo,
@@ -7,6 +8,7 @@ import {
FUSION_PROMPT_MAX_LENGTH,
type FusionUnavailableSource,
type MultiRunFusionSource,
type SchedulePermissionRuleset,
} from '@opencode-manager/shared/schemas'
import type { MultiRunEntryRecord } from '../db/multi-runs'
import { getErrorMessage } from '../utils/error-utils'
@@ -42,6 +44,33 @@ const FUSION_REPLY_BUDGET_RATIO = 0.4
const FUSION_BLOCK_SEPARATOR = '\n\n'
/**
* Builds the OpenCode session permission ruleset that lets a fusion session read
* its selected source workspaces while denying any edit to them.
*
* Each unique directory is normalized with `resolve` before a pair of rules is
* emitted: an `external_directory` allow so the session may read outside its own
* workspace, followed by an `edit` deny so the read-only reference cannot be
* mutated. Deduplication happens after normalization.
*/
export function buildFusionSourcePermissionRuleset(directories: string[]): SchedulePermissionRuleset {
const seen = new Set<string>()
const ruleset: SchedulePermissionRuleset = []
for (const directory of directories) {
const normalized = resolve(directory).replaceAll('\\', '/')
if (seen.has(normalized)) {
continue
}
seen.add(normalized)
ruleset.push({ action: 'external_directory', resource: `${normalized}/*`, effect: 'allow' })
ruleset.push({ action: 'edit', resource: `${normalized}/*`, effect: 'deny' })
}
return ruleset
}
export class FusionContextLimitError extends ServiceError {
constructor(requiredPerSource: number, availablePerSource: number) {
super(
+12 -1
View File
@@ -19,11 +19,12 @@ import { getRepoById } from '../db/queries'
import type { Repo } from '../types/repo'
import { getErrorMessage } from '../utils/error-utils'
import { ServiceError } from '../utils/service-error'
import { buildFusionPrompt, collectFusionSources } from './multi-run-fusion'
import { buildFusionPrompt, buildFusionSourcePermissionRuleset, collectFusionSources } from './multi-run-fusion'
import type { OpenCodeClient } from './opencode/client'
import { RepoWorkspaceError } from './repo'
import type { RepoWorkspaceService } from './repo-workspace'
import { requireReadyRepo, SessionLauncher, SessionLaunchError, type LaunchedSession } from './session-launcher'
import type { SessionPermissionModeService } from './session-permission-modes'
const MULTI_RUN_LIST_LIMIT = 20
@@ -75,6 +76,7 @@ export class MultiRunService {
private readonly db: Database,
private readonly openCodeClient: OpenCodeClient,
private readonly repoWorkspaces: RepoWorkspaceService,
private readonly permissionModes: SessionPermissionModeService,
) {
this.sessionLauncher = new SessionLauncher(db, openCodeClient, repoWorkspaces)
}
@@ -194,6 +196,12 @@ export class MultiRunService {
}
}
const sourcePermissions = buildFusionSourcePermissionRuleset(
selectedEntries
.map((entry) => entry.directory)
.filter((directory): directory is string => directory !== null),
)
try {
await this.sessionLauncher.resolveModel(repo, request.model)
} catch (error) {
@@ -241,6 +249,7 @@ export class MultiRunService {
model: request.model,
title: `${record.name} · fusion`,
...(request.agent ? { agent: request.agent } : {}),
...(sourcePermissions.length > 0 ? { permissions: sourcePermissions } : {}),
...(request.isolate
? {
workspace: {
@@ -256,6 +265,8 @@ export class MultiRunService {
sessionId: launched.sessionId,
directory: launched.directory,
})
await this.permissionModes.applyDefaultMode(launched.sessionId, launched.directory)
} catch (error) {
const launchError = error instanceof SessionLaunchError ? error : null
const workspaceDirectory = launchError?.workspaceDirectory ?? null
+4
View File
@@ -8,6 +8,8 @@ import type { OpenCodeClient } from './opencode/client'
import { resolveOpenCodeModel, type ResolvedOpenCodeModel } from './opencode-models'
import type { RepoWorkspaceService } from './repo-workspace'
type SessionCreateInput = NonNullable<Parameters<OpenCodeClient['api']['session']['create']>[0]>
interface LaunchSessionInput {
repoId: number
prompt: string
@@ -15,6 +17,7 @@ interface LaunchSessionInput {
model?: string
agent?: string
workspace?: { name?: string; ref?: string }
permissions?: SessionCreateInput['permissions']
}
export interface LaunchedSession {
@@ -109,6 +112,7 @@ export class SessionLauncher {
session = await this.openCodeClient.api.session.create({
...(input.title ? { title: input.title } : {}),
...(input.agent ? { agent: input.agent } : {}),
...(input.permissions ? { permissions: input.permissions } : {}),
model: {
providerID: model.providerID,
id: model.id,
@@ -126,6 +126,21 @@ export class SessionPermissionModeService {
return this.settingsService.getSettings().preferences.sessionDefaults?.permissionMode ?? 'ask'
}
/**
* Records the default permission mode for a session after it has been launched
* and accepts any permission requests it raised before the mode was stored.
*
* Does nothing when the default mode is `ask`, since that needs no stored row.
*/
async applyDefaultMode(sessionId: string, directory: string): Promise<void> {
if (this.defaultMode() !== 'auto') {
return
}
insertSessionPermissionModeIfAbsent(this.db, sessionId, 'auto')
await this.acceptPendingRequestsInDirectory(directory, sessionId)
}
async acceptPendingRequestsForActiveSessions(): Promise<void> {
try {
const active = await this.openCodeClient.api.session.active()
+112 -2
View File
@@ -4,10 +4,13 @@ import { createRepo, deleteRepo } from '../../src/db/queries'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { createMultiRunWithEntries } from '../../src/db/multi-runs'
import { getSessionPermissionMode } from '../../src/db/session-permission-modes'
import { FusionContextLimitError } from '../../src/services/multi-run-fusion'
import { MultiRunError, MultiRunService } from '../../src/services/multi-runs'
import { RepoWorkspaceError } from '../../src/services/repo'
import type { RepoWorkspaceService } from '../../src/services/repo-workspace'
import { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { SettingsService } from '../../src/services/settings'
import type { Repo } from '../../src/types/repo'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import { assistantMessage } from '../helpers/stub-schedule-api'
@@ -109,6 +112,9 @@ function createClient(sessions: Record<string, FakeSessionConfig> = {}): FakeMul
const sessionDiff = vi.fn(async () => [])
const permissionRequestList = vi.fn(async () => ({ data: [] }))
const permissionReply = vi.fn(async () => ({}))
const client = {
api: {
session: {
@@ -119,6 +125,10 @@ function createClient(sessions: Record<string, FakeSessionConfig> = {}): FakeMul
diff: sessionDiff,
},
message: { list: messageList },
permission: {
request: { list: permissionRequestList },
reply: permissionReply,
},
},
} as unknown as OpenCodeClient
@@ -198,8 +208,16 @@ describe('MultiRunService', () => {
return repo.id
}
function createService(client: OpenCodeClient, repoWorkspaces: RepoWorkspaceService): MultiRunService {
return new MultiRunService(db, client, repoWorkspaces)
function createService(
client: OpenCodeClient,
repoWorkspaces: RepoWorkspaceService,
permissionModes: SessionPermissionModeService = new SessionPermissionModeService(
db,
client,
new SettingsService(db),
),
): MultiRunService {
return new MultiRunService(db, client, repoWorkspaces, permissionModes)
}
it('launches one session per model, each in its own workspace named from the group', async () => {
@@ -641,6 +659,98 @@ describe('MultiRunService', () => {
).toEqual(before)
})
it('grants read access to the selected source workspaces and denies edits when fusing', async () => {
const repoId = readyRepo()
const { client, sessionCreate } = createClient()
const repoWorkspaces = createRepoWorkspaces()
const service = createService(client, repoWorkspaces.service)
const run = await service.launch({
repoId,
name: 'Sweep',
prompt: 'go',
models: ['openai/a', 'openai/b', 'openai/c'],
isolate: true,
})
const entryIds = run.entries.map((entry) => entry.id)
sessionCreate.mockClear()
await service.fuse(run.id, {
requestId: FUSE_REQUEST_ID,
entryIds: [entryIds[0]!, entryIds[2]!],
model: 'openai/d',
isolate: true,
})
expect(sessionCreate).toHaveBeenCalledTimes(1)
expect(sessionCreate.mock.calls[0]![0].permissions).toEqual([
{ action: 'external_directory', resource: '/worktrees/Sweep-1/*', effect: 'allow' },
{ action: 'edit', resource: '/worktrees/Sweep-1/*', effect: 'deny' },
{ action: 'external_directory', resource: '/worktrees/Sweep-3/*', effect: 'allow' },
{ action: 'edit', resource: '/worktrees/Sweep-3/*', effect: 'deny' },
])
const serializedPermissions = JSON.stringify(sessionCreate.mock.calls[0]![0].permissions)
expect(serializedPermissions).not.toContain('Sweep-2')
expect(serializedPermissions).not.toContain('Sweep-fusion-1')
})
it('stores the default auto mode on the fusion session', async () => {
const repoId = readyRepo()
const { client, sessionCreate } = createClient()
const repoWorkspaces = createRepoWorkspaces()
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } })
const permissionModes = new SessionPermissionModeService(db, client, settingsService)
const service = createService(client, repoWorkspaces.service, permissionModes)
const run = await service.launch({
repoId,
name: 'Sweep',
prompt: 'go',
models: ['openai/a', 'openai/b'],
isolate: true,
})
const entryIds = run.entries.map((entry) => entry.id)
sessionCreate.mockClear()
const { run: fused } = await service.fuse(run.id, {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: false,
})
const fusionSessionId = fused.fusions[0]!.sessionId!
expect(getSessionPermissionMode(db, fusionSessionId)).toBe('auto')
})
it('stores no mode on the fusion session when the default is ask', async () => {
const repoId = readyRepo()
const { client, sessionCreate } = createClient()
const repoWorkspaces = createRepoWorkspaces()
const service = createService(client, repoWorkspaces.service)
const run = await service.launch({
repoId,
name: 'Sweep',
prompt: 'go',
models: ['openai/a', 'openai/b'],
isolate: true,
})
const entryIds = run.entries.map((entry) => entry.id)
sessionCreate.mockClear()
const { run: fused } = await service.fuse(run.id, {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: false,
})
const fusionSessionId = fused.fusions[0]!.sessionId!
expect(getSessionPermissionMode(db, fusionSessionId)).toBeNull()
})
it('returns the same fusion for a repeated requestId and launches once', async () => {
const repoId = readyRepo()
const { client, sessionCreate } = createClient()
@@ -122,6 +122,32 @@ describe('SessionLauncher', () => {
})
})
it('forwards a permission ruleset to session creation when provided', async () => {
const repoId = readyRepo()
const { client, create } = createClient()
const { service } = createRepoWorkspaces()
const launcher = new SessionLauncher(db, client, service)
const permissions = [
{ action: 'external_directory', resource: '/repos/source/*', effect: 'allow' as const },
{ action: 'edit', resource: '/repos/source/*', effect: 'deny' as const },
]
await launcher.launch({ repoId, prompt: 'hello', permissions })
expect(create).toHaveBeenCalledWith(expect.objectContaining({ permissions }))
})
it('omits the permissions key from session creation when none are given', async () => {
const repoId = readyRepo()
const { client, create } = createClient()
const { service } = createRepoWorkspaces()
const launcher = new SessionLauncher(db, client, service)
await launcher.launch({ repoId, prompt: 'hello' })
expect(create.mock.calls[0]![0]).not.toHaveProperty('permissions')
})
it('launches in a new workspace and prompts there', async () => {
const repoId = readyRepo()
const { client, create } = createClient()
@@ -177,6 +177,54 @@ describe('SessionPermissionModeService', () => {
expect(service.defaultMode()).toBe('auto')
})
it('stores the default auto mode for a launched session', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } })
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
await service.applyDefaultMode('ses_launched', DIRECTORY)
expect(getSessionPermissionMode(db, 'ses_launched')).toBe('auto')
})
it('stores no mode for a launched session when the default is ask', async () => {
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await service.applyDefaultMode('ses_launched', DIRECTORY)
expect(getSessionPermissionMode(db, 'ses_launched')).toBeNull()
})
it('does not override an existing stored ask when applying the default auto mode', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } })
setSessionPermissionMode(db, 'ses_launched', 'ask')
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
await service.applyDefaultMode('ses_launched', DIRECTORY)
expect(getSessionPermissionMode(db, 'ses_launched')).toBe('ask')
})
it('accepts a pending request raised before the launched session mode was recorded', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } })
const client = createFakeSessionPermissionClient({
parents: { ses_launched: null },
pendingRequests: { [DIRECTORY]: [{ id: 'perm-launched', sessionID: 'ses_launched' }] },
})
const service = new SessionPermissionModeService(db, client, settingsService)
await service.applyDefaultMode('ses_launched', DIRECTORY)
expect(client.replyPermission).toHaveBeenCalledTimes(1)
expect(client.replyPermission).toHaveBeenCalledWith({
sessionID: 'ses_launched',
requestID: 'perm-launched',
decision: 'once',
})
})
it('auto-accepts a permission request for an auto root session', async () => {
setSessionPermissionMode(db, 'ses_root', 'auto')
const client = createFakeSessionPermissionClient({ parents: { ses_root: null } })
@@ -2,6 +2,7 @@ import { useCallback, useMemo } from 'react'
import { Combobox, type ComboboxOption } from '@/components/ui/combobox'
import { useModelSections } from '@/hooks/useModelSections'
import { filterModelSections, toModelComboboxOptions } from '@/lib/modelSections'
import { cn } from '@/lib/utils'
interface ModelComboboxProps {
value: string
@@ -15,6 +16,8 @@ interface ModelComboboxProps {
id?: string
disabled?: boolean
className?: string
listClassName?: string
emptyMeansDefault?: boolean
}
export function ModelCombobox({
@@ -29,8 +32,11 @@ export function ModelCombobox({
id,
disabled,
className,
listClassName,
emptyMeansDefault = true,
}: ModelComboboxProps) {
const { sections, defaultModel } = useModelSections(directory, { enabled })
const { sections, defaultModel: openCodeDefaultModel } = useModelSections(directory, { enabled })
const defaultModel = emptyMeansDefault ? openCodeDefaultModel : null
const options = useMemo(() => toModelComboboxOptions(sections, defaultModel), [sections, defaultModel])
@@ -53,7 +59,7 @@ export function ModelCombobox({
ariaLabel={ariaLabel}
disabled={disabled}
className={className}
listClassName="max-h-[min(24rem,60vh)]"
listClassName={cn('max-h-[min(24rem,60vh)]', listClassName)}
/>
)
}
@@ -17,6 +17,7 @@ interface BranchComboboxProps {
clearable?: boolean
id?: string
ariaLabel?: string
listClassName?: string
}
/**
@@ -34,6 +35,7 @@ export function BranchCombobox({
clearable = false,
id,
ariaLabel,
listClassName,
}: BranchComboboxProps) {
const { data: branchesData, isLoading } = useRepoBranches(repoId, enabled)
@@ -69,6 +71,7 @@ export function BranchCombobox({
allowCustomValue={false}
showClear={clearable}
ariaLabel={ariaLabel}
listClassName={listClassName}
/>
)
}
@@ -1,419 +0,0 @@
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(),
useProviders: vi.fn(),
useOpenCodeModelState: vi.fn(),
useOpenCodeDefaultModel: vi.fn(),
listBranches: vi.fn(),
}))
vi.mock('@/api/multiRuns', () => ({
fuseMultiRun: mocks.fuseMultiRun,
listMultiRuns: mocks.listMultiRuns,
launchMultiRun: mocks.launchMultiRun,
discardMultiRunEntry: mocks.discardMultiRunEntry,
}))
vi.mock('@/hooks/useProviders', () => ({
useProviders: mocks.useProviders,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
useOpenCodeDefaultModel: mocks.useOpenCodeDefaultModel,
}))
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',
models: [
{ id: 'gpt-4o', name: 'GPT-4o', released: 0, free: false },
{ id: 'gpt-4.1', name: 'GPT-4.1', released: 0, free: false },
],
},
{
id: 'anthropic',
name: 'Anthropic',
models: [{ id: 'claude-opus', name: 'Claude Opus', released: 0, free: false }],
},
]
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' }))
}
function synthesisCheckboxLabels() {
return screen
.getAllByRole('checkbox')
.map((checkbox) => checkbox.getAttribute('aria-label') ?? '')
.filter((label) => !label.includes('/'))
}
describe('FuseRunDialog', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
Element.prototype.scrollIntoView ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
mocks.useProviders.mockReturnValue({ data: { providers, models: [] }, isLoading: false })
mocks.useOpenCodeModelState.mockReturnValue({ data: { recent: [], favorite: [], variant: {} } })
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: null })
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()
})
it('lists the OpenCode default model first without repeating it', () => {
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: 'anthropic/claude-opus' })
renderFuseDialog()
expect(screen.getByText('Default')).toBeInTheDocument()
expect(synthesisCheckboxLabels()).toEqual(['Claude Opus', 'GPT-4o', 'GPT-4.1'])
})
})
@@ -1,285 +0,0 @@
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 { useModelSections } from '@/hooks/useModelSections'
import { useFuseMultiRun } from '@/hooks/useMultiRuns'
import { 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 { sections: modelSections } = useModelSections(directory, { enabled: open })
useEffect(() => {
if (!open) return
setSelectedEntryIds([])
setSelectedModel(null)
setInstructions('')
setIsolate(true)
setBaseRef(run.baseRef ?? '')
setModelSearch('')
setRequestId(randomId())
}, [open, run.id, run.baseRef])
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,254 @@
import { useId, useState, type ReactNode } from 'react'
import { ArrowRight, ArrowUpRight, Combine, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { ModelCombobox } from '@/components/model/ModelCombobox'
import { BranchCombobox } from '@/components/repo/BranchCombobox'
import { cn } from '@/lib/utils'
import {
FUSION_INSTRUCTIONS_MAX_LENGTH,
FusionRecoveredDetailsSchema,
MULTI_RUN_FUSION_MIN_SOURCES,
type MultiRun,
} from '@opencode-manager/shared/schemas'
export interface FusionComposerSubmission {
model: string
isolate: boolean
baseRef: string
instructions: string
}
interface FusionComposerProps {
repoId: number
directory?: string
run: MultiRun
selectedEntryIds: number[]
isPending: boolean
error: unknown
onCancel: () => void
onSubmit: (submission: FusionComposerSubmission) => void
onOpenSession: (sessionId: string, isolated: boolean) => void
}
const UPWARD_LIST_CLASS = 'bottom-full mt-0 mb-1'
function errorCode(error: unknown): string | undefined {
return (error as { code?: string } | null)?.code
}
export function FusionComposer({
repoId,
directory,
run,
selectedEntryIds,
isPending,
error,
onCancel,
onSubmit,
onOpenSession,
}: FusionComposerProps) {
const optionsId = useId()
const destinationLabelId = useId()
const [model, setModel] = useState('')
const [isolate, setIsolate] = useState(true)
const [baseRef, setBaseRef] = useState(run.baseRef ?? '')
const [instructions, setInstructions] = useState('')
const [optionsOpen, setOptionsOpen] = useState(false)
const requiresIsolation = run.entries.some((entry) => selectedEntryIds.includes(entry.id) && !entry.isolated)
const effectiveIsolate = requiresIsolation || isolate
const totalEntries = run.entries.filter((entry) => entry.status !== 'discarded').length
const canSubmit = selectedEntryIds.length >= MULTI_RUN_FUSION_MIN_SOURCES && model !== '' && !isPending
const handleSubmit = () => {
if (!canSubmit) return
onSubmit({ model, isolate: effectiveIsolate, baseRef: effectiveIsolate ? baseRef : '', instructions: instructions.trim() })
}
return (
<div className="shrink-0 space-y-3 border-t border-border bg-background px-4 pt-3 pb-[calc(env(safe-area-inset-bottom)+0.75rem)]">
<div id={optionsId} className={cn('space-y-3', !optionsOpen && 'hidden sm:block')}>
<div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-end">
<div className="space-y-1.5">
<Label htmlFor="fusion-model">Synthesis model</Label>
<ModelCombobox
id="fusion-model"
ariaLabel="Synthesis model"
value={model}
onChange={setModel}
directory={directory}
placeholder="Select a model"
allowCustomValue={false}
emptyMeansDefault={false}
listClassName={UPWARD_LIST_CLASS}
/>
</div>
<div className="space-y-1.5">
<span id={destinationLabelId} className="text-sm font-medium leading-none">
Destination
</span>
<div
role="radiogroup"
aria-labelledby={destinationLabelId}
className="grid grid-cols-2 gap-1 rounded-md border border-border bg-muted/40 p-1"
>
<DestinationOption checked={effectiveIsolate} onSelect={() => setIsolate(true)}>
Isolated
</DestinationOption>
<DestinationOption checked={!effectiveIsolate} disabled={requiresIsolation} onSelect={() => setIsolate(false)}>
Repository checkout
</DestinationOption>
</div>
</div>
</div>
{requiresIsolation ? (
<p className="text-xs text-muted-foreground">
Isolation is required because a selected result ran in the repository checkout.
</p>
) : null}
{effectiveIsolate ? (
<div className="flex items-center gap-3">
<Label htmlFor="fusion-base-ref" className="shrink-0">
Base ref
</Label>
<div className="min-w-0 flex-1">
<BranchCombobox
id="fusion-base-ref"
repoId={repoId}
value={baseRef}
onValueChange={setBaseRef}
placeholder="Current HEAD"
clearable
listClassName={UPWARD_LIST_CLASS}
/>
</div>
</div>
) : null}
<details className="group rounded-md border border-border">
<summary className="cursor-pointer select-none px-3 py-2 text-sm font-medium">Instructions (optional)</summary>
<div className="px-3 pb-3">
<Textarea
aria-label="Instructions"
value={instructions}
onChange={(event) => setInstructions(event.target.value)}
maxLength={FUSION_INSTRUCTIONS_MAX_LENGTH}
placeholder="Optional guidance for the synthesis"
rows={3}
/>
</div>
</details>
</div>
{error ? <ComposerError error={error} run={run} onOpenSession={onOpenSession} /> : null}
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
<p className="min-w-0 flex-1 text-xs text-muted-foreground">
<span className="font-medium text-foreground sm:font-normal sm:text-muted-foreground">
{selectedEntryIds.length} of {totalEntries} selected
</span>
<span className="sm:hidden">
{' '}
<ArrowRight className="inline h-3 w-3" aria-hidden="true" /> {model || 'no model'} ·{' '}
{effectiveIsolate ? 'isolated' : 'repository checkout'}
</span>
<span className="hidden sm:inline"> · blank base ref uses the current HEAD; sources are never modified.</span>
</p>
<div className="grid grid-cols-2 gap-2 sm:flex sm:shrink-0">
<Button
variant="outline"
className="h-9 sm:hidden"
aria-expanded={optionsOpen}
aria-controls={optionsId}
onClick={() => setOptionsOpen((current) => !current)}
>
Options
</Button>
<Button variant="outline" className="hidden sm:inline-flex" onClick={onCancel}>
Cancel
</Button>
<Button className="h-9" disabled={!canSubmit} aria-busy={isPending} onClick={handleSubmit}>
{isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Combine className="h-4 w-4" />}
Start fusion
</Button>
</div>
</div>
</div>
)
}
interface DestinationOptionProps {
checked: boolean
disabled?: boolean
onSelect: () => void
children: ReactNode
}
function DestinationOption({ checked, disabled, onSelect, children }: DestinationOptionProps) {
return (
<button
type="button"
role="radio"
aria-checked={checked}
disabled={disabled}
onClick={onSelect}
className={cn(
'min-h-9 rounded-sm px-3 py-1.5 text-sm font-medium leading-tight transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
checked ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground',
)}
>
{children}
</button>
)
}
interface ComposerErrorProps {
error: unknown
run: MultiRun
onOpenSession: (sessionId: string, isolated: boolean) => void
}
function ComposerError({ error, run, onOpenSession }: ComposerErrorProps) {
const code = errorCode(error)
if (code === 'FUSION_SOURCES_UNAVAILABLE') {
return <p className="text-sm text-destructive">Some selected results are not ready to fuse. See the marked rows.</p>
}
if (code === 'FUSION_CONTEXT_LIMIT') {
return <p className="text-sm text-destructive">Too much context: select fewer sources or shorten instructions</p>
}
if (code === 'FUSION_ATTEMPT_RECOVERED') {
const parsed = FusionRecoveredDetailsSchema.safeParse((error as { details?: unknown }).details)
const recovered = parsed.success ? parsed.data.fusions : []
return (
<div className="flex flex-wrap items-center gap-2">
<p className="min-w-0 flex-1 text-sm text-destructive">An earlier attempt is already running.</p>
{recovered.map((item) => {
const isolated = run.fusions.find((fusion) => fusion.id === item.fusionId)?.isolated ?? false
return (
<Button
key={item.fusionId}
variant="outline"
size="sm"
className="h-8"
onClick={() => onOpenSession(item.sessionId, isolated)}
>
<ArrowUpRight className="h-3.5 w-3.5" />
Open
</Button>
)
})}
</div>
)
}
return (
<p className="text-sm text-destructive">{error instanceof Error ? error.message : 'Failed to start fusion'}</p>
)
}
@@ -0,0 +1,408 @@
import { useState } from 'react'
import { ArrowUpRight, BookOpen, ChevronRight, Combine, MoreVertical, Trash2, type LucideIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { cn, formatShortRelativeTime } from '@/lib/utils'
import { useSessionStatusForSession, type SessionStatusType } from '@/stores/sessionStatusStore'
import {
MULTI_RUN_FUSION_MIN_SOURCES,
MULTI_RUN_MAX_MODELS,
type MultiRun,
type MultiRunEntry,
type MultiRunFusion,
type MultiRunFusionStatus,
} from '@opencode-manager/shared/schemas'
type StatusTone = 'success' | 'warning' | 'destructive' | 'info' | 'muted'
interface EntryReadiness {
ready: boolean
label: string
tone: StatusTone
reason: string | null
}
interface MultiRunCardProps {
run: MultiRun
expanded: boolean
onExpandedChange: (expanded: boolean) => void
selectedEntryIds: number[] | null
unavailableReasons: ReadonlyMap<number, string>
onStartSelection: () => void
onExitSelection: () => void
onToggleEntry: (entryId: number, checked: boolean) => void
onOpenSession: (sessionId: string, isolated: boolean) => void
onWalkthrough: (sessionId: string) => void
onDiscard: (entry: MultiRunEntry) => void
}
const TONE_CLASSES: Record<StatusTone, string> = {
success: 'border-success/40 text-success',
warning: 'border-warning/40 text-warning',
destructive: 'border-destructive/40 text-destructive',
info: 'border-info/40 text-info',
muted: 'border-border text-muted-foreground',
}
const FUSION_STATUS: Record<MultiRunFusionStatus, { label: string; tone: StatusTone }> = {
starting: { label: 'Starting', tone: 'info' },
started: { label: 'Started', tone: 'muted' },
failed: { label: 'Failed', tone: 'destructive' },
}
const PROMPT_PREVIEW_LENGTH = 240
const HEADER_BUTTON_CLASS = 'h-7 px-2 text-xs'
/**
* Derives the display status of a multi-run entry from its stored status and the
* live session status. The stored `started` status only means the session was
* launched; an entry reads as ready once its session is idle. The server remains
* authoritative when a fusion is submitted.
*/
function describeEntryReadiness(entry: MultiRunEntry, live: SessionStatusType): EntryReadiness {
switch (entry.status) {
case 'discarded':
return { ready: false, label: 'Discarded', tone: 'muted', reason: 'discarded' }
case 'failed':
return { ready: false, label: 'Failed', tone: 'destructive', reason: entry.error ?? 'no final reply' }
case 'starting':
return { ready: false, label: 'Starting', tone: 'info', reason: 'still starting' }
case 'started':
if (!entry.sessionId) {
return { ready: false, label: 'Started', tone: 'muted', reason: 'no session recorded' }
}
if (live.type !== 'idle') {
return { ready: false, label: 'Running', tone: 'warning', reason: 'still running — wait for a final reply' }
}
return { ready: true, label: 'Ready', tone: 'success', reason: null }
}
}
interface RowActionProps {
icon: LucideIcon
label: string
onClick: () => void
}
function RowAction({ icon: Icon, label, onClick }: RowActionProps) {
return (
<Button
variant="ghost"
size="sm"
aria-label={label}
title={label}
className="h-7 w-7 gap-1 px-0 text-xs sm:w-auto sm:px-2"
onClick={onClick}
>
<Icon className="h-3.5 w-3.5" />
<span className="hidden sm:inline">{label}</span>
</Button>
)
}
function StatusPill({ label, tone }: { label: string; tone: StatusTone }) {
return (
<span
className={cn(
'inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2 py-0.5 text-xs font-medium',
TONE_CLASSES[tone],
)}
>
<span className="h-1.5 w-1.5 rounded-full bg-current" aria-hidden="true" />
{label}
</span>
)
}
function formatRunMeta(run: MultiRun): string {
const parts = [
`${run.entries.length} model${run.entries.length === 1 ? '' : 's'}`,
run.isolated ? 'isolated' : 'repository checkout',
]
if (run.isolated && run.baseRef) parts.push(`base ${run.baseRef}`)
parts.push(formatShortRelativeTime(new Date(run.createdAt)))
return parts.join(' · ')
}
export function MultiRunCard({
run,
expanded,
onExpandedChange,
selectedEntryIds,
unavailableReasons,
onStartSelection,
onExitSelection,
onToggleEntry,
onOpenSession,
onWalkthrough,
onDiscard,
}: MultiRunCardProps) {
const [promptExpanded, setPromptExpanded] = useState(false)
const selecting = selectedEntryIds !== null
const isOpen = expanded || selecting
const launchedEntries = run.entries.filter((entry) => entry.status === 'started' && entry.sessionId).length
const selectionFull = (selectedEntryIds?.length ?? 0) >= MULTI_RUN_MAX_MODELS
const promptIsLong = run.prompt.length > PROMPT_PREVIEW_LENGTH
return (
<section
aria-label={run.name}
className={cn(
'rounded-lg border bg-card',
selecting ? 'border-primary/60 ring-1 ring-primary/30' : 'border-border',
)}
>
<div className="flex items-start gap-2 px-3 py-3">
<button
type="button"
aria-expanded={isOpen}
disabled={selecting}
onClick={() => onExpandedChange(!expanded)}
className="flex min-w-0 flex-1 items-start gap-2 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default"
>
<ChevronRight
className={cn('mt-0.5 h-4 w-4 shrink-0 text-muted-foreground transition-transform', isOpen && 'rotate-90')}
aria-hidden="true"
/>
<span className="min-w-0 flex-1">
<span className="flex flex-wrap items-center gap-x-2 gap-y-1">
<span className="truncate text-sm font-semibold text-foreground">{run.name}</span>
{selecting ? (
<span className="rounded-full border border-primary/50 bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
Selection mode
</span>
) : null}
</span>
<span className="mt-0.5 block text-xs text-muted-foreground">{formatRunMeta(run)}</span>
</span>
</button>
{selecting ? (
<Button variant="outline" size="sm" className={HEADER_BUTTON_CLASS} onClick={onExitSelection}>
Exit
</Button>
) : (
<Button
variant="outline"
size="sm"
className={HEADER_BUTTON_CLASS}
disabled={launchedEntries < MULTI_RUN_FUSION_MIN_SOURCES}
onClick={onStartSelection}
>
<Combine className="h-3.5 w-3.5" />
Fuse results
</Button>
)}
</div>
{isOpen ? (
<div className="border-t border-border">
<div className="px-3 py-2">
<p
className={cn(
'whitespace-pre-wrap break-words text-sm text-foreground/90',
promptIsLong && !promptExpanded && 'line-clamp-3',
)}
>
{run.prompt}
</p>
{promptIsLong ? (
<button
type="button"
className="mt-1 text-xs font-medium text-primary hover:underline"
onClick={() => setPromptExpanded((current) => !current)}
>
{promptExpanded ? 'Show less' : 'Show more'}
</button>
) : null}
</div>
<ul className="divide-y divide-border border-t border-border">
{run.entries.map((entry) => (
<EntryRow
key={entry.id}
entry={entry}
selecting={selecting}
checked={selectedEntryIds?.includes(entry.id) ?? false}
selectionFull={selectionFull}
unavailableReason={unavailableReasons.get(entry.id) ?? null}
onToggle={(checked) => onToggleEntry(entry.id, checked)}
onOpenSession={onOpenSession}
onWalkthrough={onWalkthrough}
onDiscard={() => onDiscard(entry)}
/>
))}
</ul>
{run.fusions.length > 0 ? (
<div className="border-t border-border">
<h4 className="flex items-center gap-2 px-3 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Fusions
<span className="rounded-full border border-border px-1.5 text-[11px] font-medium normal-case">
{run.fusions.length}
</span>
</h4>
<ul className="divide-y divide-border">
{run.fusions.map((fusion) => (
<FusionRow
key={fusion.id}
fusion={fusion}
onOpenSession={onOpenSession}
onWalkthrough={onWalkthrough}
/>
))}
</ul>
</div>
) : null}
</div>
) : null}
</section>
)
}
interface EntryRowProps {
entry: MultiRunEntry
selecting: boolean
checked: boolean
selectionFull: boolean
unavailableReason: string | null
onToggle: (checked: boolean) => void
onOpenSession: (sessionId: string, isolated: boolean) => void
onWalkthrough: (sessionId: string) => void
onDiscard: () => void
}
function EntryRow({
entry,
selecting,
checked,
selectionFull,
unavailableReason,
onToggle,
onOpenSession,
onWalkthrough,
onDiscard,
}: EntryRowProps) {
const live = useSessionStatusForSession(entry.sessionId ?? undefined)
const readiness = describeEntryReadiness(entry, live)
const reason = unavailableReason ?? readiness.reason
const unavailable = unavailableReason !== null || !readiness.ready
const sessionId = entry.sessionId
const canDiscard = entry.status === 'started' || entry.status === 'failed'
const isolationLabel = entry.isolated ? 'Isolated' : 'Repository checkout'
const detail = selecting && unavailable
? `Unavailable · ${reason}`
: entry.status === 'failed' && entry.error
? entry.error
: null
return (
<li
className={cn(
'flex items-start gap-2 px-3 py-2.5',
selecting && unavailable && !checked && 'opacity-60',
)}
>
<div className="flex min-w-0 flex-1 items-start gap-2">
{selecting ? (
<label className="-my-1 -ml-1 flex h-7 w-7 shrink-0 cursor-pointer items-center justify-center">
<Checkbox
aria-label={entry.model}
checked={checked}
disabled={!checked && (!readiness.ready || selectionFull)}
onCheckedChange={(next) => onToggle(next === true)}
/>
</label>
) : null}
<div className="min-w-0 flex-1 space-y-0.5">
<p className="truncate text-sm font-medium">{entry.model}</p>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<StatusPill label={readiness.label} tone={readiness.tone} />
{readiness.label === 'Running' && sessionId ? <SessionStatusIndicator sessionID={sessionId} size="sm" /> : null}
<span className="text-xs text-muted-foreground">{isolationLabel}</span>
</div>
{detail ? (
<p className={cn('text-xs', entry.status === 'failed' || unavailableReason ? 'text-destructive' : 'text-muted-foreground')}>
{detail}
</p>
) : null}
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
{sessionId ? (
<RowAction icon={ArrowUpRight} label="Open" onClick={() => onOpenSession(sessionId, entry.isolated)} />
) : null}
{sessionId ? (
<RowAction icon={BookOpen} label="Walkthrough" onClick={() => onWalkthrough(sessionId)} />
) : null}
{canDiscard ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
aria-label={`More actions for ${entry.model}`}
>
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem className="text-destructive focus:text-destructive" onSelect={onDiscard}>
<Trash2 className="h-4 w-4" />
Discard
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : null}
</div>
</li>
)
}
interface FusionRowProps {
fusion: MultiRunFusion
onOpenSession: (sessionId: string, isolated: boolean) => void
onWalkthrough: (sessionId: string) => void
}
function FusionRow({ fusion, onOpenSession, onWalkthrough }: FusionRowProps) {
const truncated = fusion.sources.some((source) => source.truncated)
const sessionId = fusion.sessionId
const status = FUSION_STATUS[fusion.status]
return (
<li className="flex items-start gap-2 px-3 py-2.5">
<div className="min-w-0 flex-1 space-y-0.5">
<p className="truncate text-sm font-medium">{fusion.model}</p>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<StatusPill label={status.label} tone={status.tone} />
{fusion.status === 'started' && sessionId ? <SessionStatusIndicator sessionID={sessionId} size="sm" /> : null}
<span className="text-xs text-muted-foreground">
<span>
from {fusion.sources.length} source{fusion.sources.length === 1 ? '' : 's'}
{truncated ? ' (truncated)' : ''}
</span>
<span> · {formatShortRelativeTime(new Date(fusion.createdAt))}</span>
</span>
</div>
{fusion.status === 'failed' && fusion.error ? <p className="text-xs text-destructive">{fusion.error}</p> : null}
</div>
{sessionId ? (
<div className="flex shrink-0 items-center gap-1">
<RowAction icon={ArrowUpRight} label="Open" onClick={() => onOpenSession(sessionId, fusion.isolated)} />
<RowAction icon={BookOpen} label="Walkthrough" onClick={() => onWalkthrough(sessionId)} />
</div>
) : null}
</li>
)
}
@@ -1,575 +0,0 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { MultiRunDialog } from './MultiRunDialog'
import type { MultiRun } from '@opencode-manager/shared/schemas'
const mocks = vi.hoisted(() => ({
listMultiRuns: vi.fn(),
launchMultiRun: vi.fn(),
discardMultiRunEntry: vi.fn(),
fuseMultiRun: vi.fn(),
useProviders: vi.fn(),
useOpenCodeModelState: vi.fn(),
useOpenCodeDefaultModel: vi.fn(),
listBranches: vi.fn(),
getChangeWalkthrough: vi.fn(),
generateChangeWalkthrough: vi.fn(),
}))
const mockNavigate = vi.fn()
vi.mock('react-router-dom', async (importOriginal) => ({
...(await importOriginal('react-router-dom')),
useNavigate: () => mockNavigate,
}))
vi.mock('@/api/multiRuns', () => ({
listMultiRuns: mocks.listMultiRuns,
launchMultiRun: mocks.launchMultiRun,
discardMultiRunEntry: mocks.discardMultiRunEntry,
fuseMultiRun: mocks.fuseMultiRun,
}))
vi.mock('@/hooks/useProviders', () => ({
useProviders: mocks.useProviders,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
useOpenCodeDefaultModel: mocks.useOpenCodeDefaultModel,
}))
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(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
},
}))
const providers = [
{
id: 'openai',
name: 'OpenAI',
models: [
{ id: 'gpt-4o', name: 'GPT-4o', released: 0, free: false },
{ id: 'gpt-4o-mini', name: 'GPT-4o mini', released: 0, free: false },
{ id: 'gpt-4.1', name: 'GPT-4.1', released: 0, free: false },
],
},
{
id: 'anthropic',
name: 'Anthropic',
models: [
{ id: 'claude-opus', name: 'Claude Opus', released: 0, free: false },
{ id: 'claude-sonnet', name: 'Claude Sonnet', released: 0, free: false },
{ id: 'claude-haiku', name: 'Claude Haiku', released: 0, free: false },
{ id: 'claude-sonnet-4-5', key: 'claude-sonnet-4.5', name: 'Claude Sonnet 4.5', released: 0, free: false },
],
},
]
const startedRun: 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: 'failed',
sessionId: null,
directory: null,
isolated: true,
error: 'launch failed',
createdAt: 1,
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() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
function renderDialog(overrides: Partial<React.ComponentProps<typeof MultiRunDialog>> = {}) {
return render(
<MultiRunDialog
repoId={7}
directory="/repo"
defaultBaseRef="main"
open
onOpenChange={vi.fn()}
{...overrides}
/>,
{ wrapper: createWrapper() },
)
}
function checkboxLabels() {
return screen.getAllByRole('checkbox').map((checkbox) => checkbox.getAttribute('aria-label'))
}
async function fillLaunchForm(user: ReturnType<typeof userEvent.setup>) {
await user.type(screen.getByLabelText('Group name'), 'Sweep')
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
}
describe('MultiRunDialog', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
Element.prototype.scrollIntoView ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
mocks.useProviders.mockReturnValue({ data: { providers, models: [] }, isLoading: false })
mocks.useOpenCodeModelState.mockReturnValue({ data: { recent: [], favorite: [], variant: {} } })
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: null })
mocks.listBranches.mockResolvedValue({
branches: [
{ name: 'main', type: 'local', current: true },
{ name: 'remotes/origin/HEAD', type: 'remote', current: false },
{ name: 'remotes/origin/release', type: 'remote', current: false },
],
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', () => {
mocks.useOpenCodeModelState.mockReturnValue({
data: {
favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet' }],
recent: [
{ providerID: 'openai', modelID: 'gpt-4.1' },
{ providerID: 'anthropic', modelID: 'claude-sonnet' },
{ providerID: 'missing', modelID: 'gone' },
],
variant: {},
},
})
renderDialog()
expect(screen.getByText('Favorites')).toBeInTheDocument()
expect(screen.getByText('Recent')).toBeInTheDocument()
expect(checkboxLabels()).toEqual([
'Claude Sonnet',
'GPT-4.1',
'GPT-4o',
'GPT-4o mini',
'Claude Opus',
'Claude Haiku',
'Claude Sonnet 4.5',
])
})
it('lists the OpenCode default model first without repeating it', () => {
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: 'anthropic/claude-sonnet' })
renderDialog()
expect(screen.getByText('Default')).toBeInTheDocument()
expect(checkboxLabels()).toEqual([
'Claude Sonnet',
'GPT-4o',
'GPT-4o mini',
'GPT-4.1',
'Claude Opus',
'Claude Haiku',
'Claude Sonnet 4.5',
])
})
it('filters models by every search term and keeps favorites first', async () => {
const user = userEvent.setup()
mocks.useOpenCodeModelState.mockReturnValue({
data: { favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet-4.5' }], recent: [], variant: {} },
})
renderDialog()
await user.type(screen.getByLabelText('Search models'), 'sonnet')
await waitFor(() => expect(checkboxLabels()).toEqual(['Claude Sonnet 4.5', 'Claude Sonnet']))
await user.clear(screen.getByLabelText('Search models'))
await user.type(screen.getByLabelText('Search models'), 'anthropic haiku')
await waitFor(() => expect(checkboxLabels()).toEqual(['Claude Haiku']))
await user.type(screen.getByLabelText('Search models'), 'zzz')
expect(await screen.findByText('No models match your search.')).toBeInTheDocument()
})
it('shows the provider name on every search result', async () => {
const user = userEvent.setup()
mocks.useProviders.mockReturnValue({
data: {
providers: [
{
id: 'anthropic',
name: 'Anthropic',
models: [{ id: 'claude-sonnet', name: 'Claude Sonnet', released: 0, free: false }],
},
{
id: 'openrouter',
name: 'OpenRouter',
models: [{ id: 'claude-sonnet', name: 'Claude Sonnet', released: 0, free: false }],
},
],
models: [],
},
isLoading: false,
})
renderDialog()
await user.type(screen.getByLabelText('Search models'), 'claude')
await waitFor(() => expect(checkboxLabels()).toEqual(['Claude Sonnet', 'Claude Sonnet']))
expect(screen.getByText('Anthropic')).toBeInTheDocument()
expect(screen.getByText('OpenRouter')).toBeInTheDocument()
})
it('keeps selections that are hidden by the search filter', async () => {
const user = userEvent.setup()
renderDialog()
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
await user.type(screen.getByLabelText('Search models'), 'claude')
await waitFor(() => expect(screen.queryByRole('checkbox', { name: 'GPT-4o' })).not.toBeInTheDocument())
expect(screen.getByText('1/5 selected')).toBeInTheDocument()
})
it('submits the selected remote branch as the base ref', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(startedRun)
renderDialog()
await fillLaunchForm(user)
const branchSelect = screen.getByRole('combobox', { name: 'Start from' })
await waitFor(() => expect(branchSelect).toBeEnabled())
await user.click(branchSelect)
expect(screen.queryByRole('option', { name: /HEAD/ })).not.toBeInTheDocument()
await user.click(screen.getByRole('option', { name: /release/ }))
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith({
repoId: 7,
name: 'Sweep',
prompt: 'go',
models: ['openai/gpt-4o'],
isolate: true,
baseRef: 'origin/release',
})
})
})
it('hides the base branch and omits it when runs are not isolated', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(startedRun)
renderDialog()
await fillLaunchForm(user)
await user.click(screen.getByRole('switch', { name: 'Isolate runs' }))
expect(screen.queryByRole('combobox', { name: 'Start from' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith({
repoId: 7,
name: 'Sweep',
prompt: 'go',
models: ['openai/gpt-4o'],
isolate: false,
})
})
})
it('caps model selection at five', async () => {
const user = userEvent.setup()
renderDialog()
const names = ['GPT-4o', 'GPT-4o mini', 'GPT-4.1', 'Claude Opus', 'Claude Sonnet']
for (const name of names) {
await user.click(screen.getByRole('checkbox', { name }))
}
expect(screen.getByText('5/5 selected')).toBeInTheDocument()
expect(screen.getByRole('checkbox', { name: 'Claude Haiku' })).toBeDisabled()
await user.click(screen.getByRole('checkbox', { name: 'Claude Haiku' }))
expect(screen.getByText('5/5 selected')).toBeInTheDocument()
})
it('submits the launch request', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(startedRun)
renderDialog()
await user.type(screen.getByLabelText('Group name'), 'Sweep')
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith({
repoId: 7,
name: 'Sweep',
prompt: 'go',
models: ['openai/gpt-4o'],
isolate: true,
baseRef: 'main',
})
})
})
it('keeps the launch tab when the launch request fails', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockRejectedValue(new Error('launch failed'))
renderDialog()
await user.type(screen.getByLabelText('Group name'), 'Sweep')
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalled()
})
expect(screen.getByLabelText('Group name')).toBeInTheDocument()
expect(screen.queryByText('No runs yet.')).not.toBeInTheDocument()
})
it('submits the catalog id for configured model aliases', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(startedRun)
renderDialog()
await user.type(screen.getByLabelText('Group name'), 'Sweep')
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'Claude Sonnet 4.5' }))
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith({
repoId: 7,
name: 'Sweep',
prompt: 'go',
models: ['anthropic/claude-sonnet-4.5'],
isolate: true,
baseRef: 'main',
})
})
})
it('lists run entries with Open and Discard actions', 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.getByText('launch failed')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /open/i })).toBeInTheDocument()
expect(screen.getAllByRole('button', { name: /discard/i })).toHaveLength(2)
})
it('opens a started run in the workspaces tab', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([startedRun])
renderDialog()
await user.click(screen.getByRole('tab', { name: 'Runs' }))
await waitFor(() => {
expect(screen.getByRole('button', { name: /open/i })).toBeInTheDocument()
})
await user.click(screen.getByRole('button', { name: /open/i }))
expect(mockNavigate).toHaveBeenCalledWith('/repos/7/sessions/ses_1?repoTab=workspaces')
})
it('discards an entry after confirmation', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([startedRun])
mocks.discardMultiRunEntry.mockResolvedValue(startedRun)
renderDialog()
await user.click(screen.getByRole('tab', { name: 'Runs' }))
await waitFor(() => {
expect(screen.getAllByRole('button', { name: /discard/i })).toHaveLength(2)
})
await user.click(screen.getAllByRole('button', { name: /discard/i })[0])
const confirmDialog = await screen.findByRole('dialog', { name: 'Discard run' })
await user.click(within(confirmDialog).getByRole('button', { name: 'Discard' }))
await waitFor(() => {
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'))
})
})
@@ -1,447 +0,0 @@
import { useCallback, useDeferredValue, useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
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 { 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 { useModelSections } from '@/hooks/useModelSections'
import { useDiscardMultiRunEntry, useLaunchMultiRun, useMultiRuns } from '@/hooks/useMultiRuns'
import { 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 {
repoId: number
directory?: string
defaultBaseRef?: string
open: boolean
onOpenChange: (open: boolean) => void
}
interface PendingDiscard {
runId: number
entryId: number
model: string
isolated: boolean
}
const STATUS_LABELS: Record<MultiRunEntryStatus, string> = {
starting: 'Starting',
started: 'Started',
failed: 'Failed',
discarded: 'Discarded',
}
const FUSION_STATUS_LABELS: Record<MultiRunFusionStatus, string> = {
starting: 'Starting',
started: 'Started',
failed: 'Failed',
}
export function MultiRunDialog({
repoId,
directory,
defaultBaseRef,
open,
onOpenChange,
}: MultiRunDialogProps) {
const navigate = useNavigate()
const [activeTab, setActiveTab] = useState('launch')
const [name, setName] = useState('')
const [prompt, setPrompt] = useState('')
const [selectedModels, setSelectedModels] = useState<string[]>([])
const [isolate, setIsolate] = useState(true)
const [baseRef, setBaseRef] = useState('')
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 { sections: modelSections } = useModelSections(directory, { enabled: open })
const runsQuery = useMultiRuns(repoId, open)
const launch = useLaunchMultiRun(repoId)
const discard = useDiscardMultiRunEntry(repoId)
useEffect(() => {
if (!open) return
setActiveTab('launch')
setName('')
setPrompt('')
setSelectedModels([])
setIsolate(true)
setBaseRef(defaultBaseRef ?? '')
setModelSearch('')
}, [open, defaultBaseRef])
const visibleModelSections = useMemo(
() => filterModelSections(modelSections, deferredModelSearch),
[modelSections, deferredModelSearch],
)
const toggleModel = useCallback((value: string, checked: boolean) => {
setSelectedModels((current) => {
if (checked) {
if (current.includes(value) || current.length >= MULTI_RUN_MAX_MODELS) return current
return [...current, value]
}
return current.filter((model) => model !== value)
})
}, [])
const canSubmit =
name.trim().length > 0 && prompt.trim().length > 0 && selectedModels.length > 0 && !launch.isPending
const handleLaunch = () => {
const request: LaunchMultiRunRequest = {
repoId,
name: name.trim(),
prompt: prompt.trim(),
models: selectedModels,
isolate,
...(isolate && baseRef ? { baseRef } : {}),
}
launch.mutate(request, { onSuccess: () => setActiveTab('runs') })
}
const openEntry = (sessionId: string, isolated: boolean) => {
onOpenChange(false)
navigate(buildSessionPath(repoId, sessionId, isolated ? { repoTab: 'workspaces' } : undefined))
}
const confirmDiscard = () => {
if (!pendingDiscard) return
discard.mutate(
{ runId: pendingDiscard.runId, entryId: pendingDiscard.entryId },
{ onSuccess: () => setPendingDiscard(null) },
)
}
const runs = runsQuery.data ?? []
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>Multi-run</DialogTitle>
<DialogDescription>
Run one prompt on up to {MULTI_RUN_MAX_MODELS} models at once, each in its own session.
</DialogDescription>
</DialogHeader>
<Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col min-h-0">
<div className="px-4 sm:px-6 pt-3 shrink-0">
<TabsList className="w-full justify-start">
<TabsTrigger value="launch">Launch</TabsTrigger>
<TabsTrigger value="runs">Runs</TabsTrigger>
</TabsList>
</div>
<TabsContent value="launch" className="flex-1 overflow-y-auto p-4 sm:p-6 mt-0 space-y-4">
<div className="space-y-1.5">
<Label htmlFor="multi-run-name">Group name</Label>
<Input
id="multi-run-name"
value={name}
onChange={(event) => setName(event.target.value)}
placeholder="Sweep"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="multi-run-prompt">Prompt</Label>
<Textarea
id="multi-run-prompt"
value={prompt}
onChange={(event) => setPrompt(event.target.value)}
placeholder="The prompt to send to every model"
rows={4}
/>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label>Models</Label>
<span className="text-xs text-muted-foreground">
{selectedModels.length}/{MULTI_RUN_MAX_MODELS} selected
</span>
</div>
<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.'}
maxSelected={MULTI_RUN_MAX_MODELS}
/>
</div>
</div>
<div className="flex items-center justify-between rounded-lg border border-border p-3">
<div className="space-y-0.5">
<Label htmlFor="multi-run-isolate">Isolate runs</Label>
<p className="text-xs text-muted-foreground">Give each model its own workspace.</p>
</div>
<Switch id="multi-run-isolate" checked={isolate} onCheckedChange={setIsolate} />
</div>
{isolate && (
<div className="space-y-1.5">
<Label htmlFor="multi-run-base-ref">Start from</Label>
<BranchCombobox
id="multi-run-base-ref"
repoId={repoId}
value={baseRef}
onValueChange={setBaseRef}
placeholder="Current HEAD"
clearable
/>
<p className="text-xs text-muted-foreground">Each isolated workspace starts from this branch.</p>
</div>
)}
<div className="flex justify-end">
<Button onClick={handleLaunch} disabled={!canSubmit}>
{launch.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Launching...
</>
) : (
'Launch'
)}
</Button>
</div>
</TabsContent>
<TabsContent value="runs" className="flex-1 overflow-y-auto p-4 sm:p-6 mt-0 space-y-4">
{runsQuery.isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : runsQuery.error ? (
<p className="text-sm text-destructive">
{runsQuery.error instanceof Error ? runsQuery.error.message : 'Failed to load runs'}
</p>
) : runs.length === 0 ? (
<p className="text-sm text-muted-foreground">No runs yet.</p>
) : (
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>
)
})
)}
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
<ConfirmDestructiveDialog
open={pendingDiscard !== null}
onOpenChange={(isOpen) => {
if (!isOpen) setPendingDiscard(null)
}}
onConfirm={confirmDiscard}
onCancel={() => setPendingDiscard(null)}
title="Discard run"
description={
pendingDiscard?.isolated
? 'Discard this run and remove its workspace directory? This action cannot be undone.'
: 'Discard this run? This action cannot be undone.'
}
warning={pendingDiscard?.model}
confirmLabel="Discard"
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}
</>
)
}
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>
)
}
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) {
return (
<div className="flex items-center gap-2">
<SessionStatusIndicator sessionID={entry.sessionId} size="sm" />
<Badge variant="secondary">{STATUS_LABELS[entry.status]}</Badge>
</div>
)
}
const variant = entry.status === 'failed' ? 'destructive' : entry.status === 'discarded' ? 'outline' : 'secondary'
return <Badge variant={variant}>{STATUS_LABELS[entry.status]}</Badge>
}
@@ -0,0 +1,735 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { MultiRunSheet } from './MultiRunSheet'
import { FetchError } from '@/api/fetchWrapper'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import type { FuseMultiRunRequest, MultiRun, MultiRunEntry, MultiRunFusion } from '@opencode-manager/shared/schemas'
const mocks = vi.hoisted(() => ({
listMultiRuns: vi.fn(),
launchMultiRun: vi.fn(),
discardMultiRunEntry: vi.fn(),
fuseMultiRun: vi.fn(),
useProviders: vi.fn(),
useOpenCodeModelState: vi.fn(),
useOpenCodeDefaultModel: vi.fn(),
listBranches: vi.fn(),
getChangeWalkthrough: vi.fn(),
generateChangeWalkthrough: vi.fn(),
}))
const mockNavigate = vi.fn()
vi.mock('react-router-dom', async (importOriginal) => ({
...(await importOriginal('react-router-dom')),
useNavigate: () => mockNavigate,
}))
vi.mock('@/api/multiRuns', () => ({
listMultiRuns: mocks.listMultiRuns,
launchMultiRun: mocks.launchMultiRun,
discardMultiRunEntry: mocks.discardMultiRunEntry,
fuseMultiRun: mocks.fuseMultiRun,
}))
vi.mock('@/hooks/useProviders', () => ({
useProviders: mocks.useProviders,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
useOpenCodeDefaultModel: mocks.useOpenCodeDefaultModel,
}))
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(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
},
}))
const providers = [
{
id: 'openai',
name: 'OpenAI',
models: [
{ id: 'gpt-4o', name: 'GPT-4o', released: 0, free: false },
{ id: 'gpt-4o-mini', name: 'GPT-4o mini', released: 0, free: false },
{ id: 'gpt-4.1', name: 'GPT-4.1', released: 0, free: false },
],
},
{
id: 'anthropic',
name: 'Anthropic',
models: [
{ id: 'claude-opus', name: 'Claude Opus', released: 0, free: false },
{ id: 'claude-sonnet', name: 'Claude Sonnet', released: 0, free: false },
{ id: 'claude-haiku', name: 'Claude Haiku', released: 0, free: false },
{ id: 'claude-sonnet-4-5', key: 'claude-sonnet-4.5', name: 'Claude Sonnet 4.5', released: 0, free: false },
],
},
]
function entry(overrides: Partial<MultiRunEntry> & Pick<MultiRunEntry, 'id' | 'model'>): MultiRunEntry {
return {
status: 'started',
sessionId: `ses_${overrides.id}`,
directory: `/workspaces/sweep-${overrides.id}`,
isolated: true,
error: null,
createdAt: 1,
updatedAt: 1,
...overrides,
}
}
function fusion(overrides: Partial<MultiRunFusion> = {}): MultiRunFusion {
return {
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: 11, sessionId: 'ses_11', model: 'openai/gpt-4o', truncated: true }],
createdAt: 1,
updatedAt: 1,
...overrides,
}
}
const oneStartedRun: MultiRun = {
id: 3,
repoId: 7,
name: 'Sweep',
prompt: 'go',
isolated: true,
baseRef: 'main',
createdAt: 1,
entries: [
entry({ id: 11, model: 'openai/gpt-4o' }),
entry({ id: 12, model: 'anthropic/claude-opus', status: 'failed', sessionId: null, directory: null, error: 'launch failed' }),
],
fusions: [],
}
const fuseRun: MultiRun = {
...oneStartedRun,
id: 5,
name: 'Pair',
prompt: 'compare approaches',
entries: [
entry({ id: 11, model: 'openai/gpt-4o' }),
entry({ id: 13, model: 'anthropic/claude-opus' }),
entry({ id: 14, model: 'openai/gpt-4.1' }),
entry({ id: 15, model: 'anthropic/claude-haiku', status: 'failed', sessionId: null, directory: null, error: 'provider overloaded' }),
],
}
const olderRun: MultiRun = {
...oneStartedRun,
id: 2,
name: 'Older sweep',
prompt: 'older prompt',
entries: [entry({ id: 21, model: 'openai/gpt-4.1' }), entry({ id: 22, model: 'openai/gpt-4o-mini' })],
}
function createWrapper() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
function renderSheet(overrides: Partial<React.ComponentProps<typeof MultiRunSheet>> = {}) {
const onOpenChange = vi.fn()
const view = render(
<MultiRunSheet repoId={7} directory="/repo" defaultBaseRef="main" open onOpenChange={onOpenChange} {...overrides} />,
{ wrapper: createWrapper() },
)
return { ...view, onOpenChange }
}
function checkboxLabels() {
return screen.getAllByRole('checkbox').map((checkbox) => checkbox.getAttribute('aria-label'))
}
async function openNewRun(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole('tab', { name: 'New run' }))
}
async function fillLaunchForm(user: ReturnType<typeof userEvent.setup>) {
await openNewRun(user)
await user.type(screen.getByLabelText('Group name'), 'Sweep')
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
}
async function enterSelection(user: ReturnType<typeof userEvent.setup>, runName = 'Pair') {
const card = await screen.findByRole('region', { name: runName })
await user.click(within(card).getByRole('button', { name: /fuse results/i }))
return card
}
async function chooseSynthesisModel(user: ReturnType<typeof userEvent.setup>, value: string) {
await user.click(screen.getByRole('combobox', { name: 'Synthesis model' }))
await user.click(screen.getByRole('option', { name: new RegExp(`${value.replace('.', '\\.')}$`) }))
}
async function selectSourcesAndModel(user: ReturnType<typeof userEvent.setup>) {
const card = await enterSelection(user)
await user.click(within(card).getByRole('checkbox', { name: 'openai/gpt-4o' }))
await user.click(within(card).getByRole('checkbox', { name: 'anthropic/claude-opus' }))
await chooseSynthesisModel(user, 'openai/gpt-4o')
return card
}
function startedFusionResponse(request: FuseMultiRunRequest, status: MultiRunFusion['status'] = 'started'): MultiRun {
return {
...fuseRun,
fusions: [
fusion({
id: 1,
requestId: request.requestId,
model: request.model,
status,
sessionId: status === 'started' ? 'ses_new_fusion' : null,
error: status === 'failed' ? 'launch failed' : null,
sources: [],
}),
],
}
}
describe('MultiRunSheet', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
Element.prototype.scrollIntoView ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
for (const sessionId of useSessionStatus.getState().statuses.keys()) {
useSessionStatus.getState().clearStatus(sessionId)
}
mocks.useProviders.mockReturnValue({ data: { providers, models: [] }, isLoading: false })
mocks.useOpenCodeModelState.mockReturnValue({ data: { recent: [], favorite: [], variant: {} } })
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: null })
mocks.listBranches.mockResolvedValue({
branches: [
{ name: 'main', type: 'local', current: true },
{ name: 'remotes/origin/HEAD', type: 'remote', current: false },
{ name: 'remotes/origin/release', type: 'remote', current: false },
],
status: { ahead: 0, behind: 0 },
})
mocks.listMultiRuns.mockResolvedValue([])
mocks.getChangeWalkthrough.mockResolvedValue({ walkthrough: null, currentDiffHash: null, stale: false })
})
it('opens as a right sheet on the Runs tab', async () => {
renderSheet()
expect(screen.getByRole('dialog', { name: 'Multi-run' })).toBeInTheDocument()
expect(screen.getByRole('tab', { name: 'Runs' })).toHaveAttribute('aria-selected', 'true')
expect(await screen.findByText('No runs yet.')).toBeInTheDocument()
})
it('switches to the New run tab from the empty state', async () => {
const user = userEvent.setup()
renderSheet()
await user.click(await screen.findByRole('button', { name: 'Start a new run' }))
expect(screen.getByRole('tab', { name: 'New run' })).toHaveAttribute('aria-selected', 'true')
expect(screen.getByLabelText('Group name')).toBeInTheDocument()
})
describe('New run', () => {
it('lists the OpenCode default model first without repeating it', async () => {
const user = userEvent.setup()
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: 'anthropic/claude-sonnet' })
renderSheet()
await openNewRun(user)
expect(screen.getByText('Default')).toBeInTheDocument()
expect(checkboxLabels()).toEqual([
'Claude Sonnet',
'GPT-4o',
'GPT-4o mini',
'GPT-4.1',
'Claude Opus',
'Claude Haiku',
'Claude Sonnet 4.5',
])
})
it('filters models by every search term', async () => {
const user = userEvent.setup()
renderSheet()
await openNewRun(user)
await user.type(screen.getByLabelText('Search models'), 'anthropic haiku')
await waitFor(() => expect(checkboxLabels()).toEqual(['Claude Haiku']))
await user.type(screen.getByLabelText('Search models'), 'zzz')
expect(await screen.findByText('No models match your search.')).toBeInTheDocument()
})
it('keeps the form when switching tabs', async () => {
const user = userEvent.setup()
renderSheet()
await fillLaunchForm(user)
await user.click(screen.getByRole('tab', { name: 'Runs' }))
await openNewRun(user)
expect(screen.getByLabelText('Group name')).toHaveValue('Sweep')
expect(screen.getByText('1/5 selected')).toBeInTheDocument()
})
it('caps model selection at five', async () => {
const user = userEvent.setup()
renderSheet()
await openNewRun(user)
for (const name of ['GPT-4o', 'GPT-4o mini', 'GPT-4.1', 'Claude Opus', 'Claude Sonnet']) {
await user.click(screen.getByRole('checkbox', { name }))
}
expect(screen.getByText('5/5 selected')).toBeInTheDocument()
expect(screen.getByRole('checkbox', { name: 'Claude Haiku' })).toBeDisabled()
})
it('submits the launch request and switches to Runs', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(oneStartedRun)
renderSheet()
await fillLaunchForm(user)
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith({
repoId: 7,
name: 'Sweep',
prompt: 'go',
models: ['openai/gpt-4o'],
isolate: true,
baseRef: 'main',
})
})
await waitFor(() => expect(screen.getByRole('tab', { name: 'Runs' })).toHaveAttribute('aria-selected', 'true'))
})
it('submits the selected remote branch as the base ref', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(oneStartedRun)
renderSheet()
await fillLaunchForm(user)
const branchSelect = screen.getByRole('combobox', { name: 'Start from' })
await waitFor(() => expect(branchSelect).toBeEnabled())
await user.click(branchSelect)
await user.click(screen.getByRole('option', { name: /release/ }))
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith(expect.objectContaining({ baseRef: 'origin/release' }))
})
})
it('omits the base ref when runs are not isolated', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(oneStartedRun)
renderSheet()
await fillLaunchForm(user)
await user.click(screen.getByRole('switch', { name: 'Isolate runs' }))
expect(screen.queryByRole('combobox', { name: 'Start from' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => expect(mocks.launchMultiRun).toHaveBeenCalledTimes(1))
expect(mocks.launchMultiRun.mock.calls[0][0]).toEqual({
repoId: 7,
name: 'Sweep',
prompt: 'go',
models: ['openai/gpt-4o'],
isolate: false,
})
})
it('submits the catalog id for configured model aliases', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(oneStartedRun)
renderSheet()
await openNewRun(user)
await user.type(screen.getByLabelText('Group name'), 'Sweep')
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'Claude Sonnet 4.5' }))
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith(
expect.objectContaining({ models: ['anthropic/claude-sonnet-4.5'] }),
)
})
})
it('renders a single disabled launch button while the launch is pending', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockReturnValue(new Promise(() => {}))
renderSheet()
await fillLaunchForm(user)
await user.click(screen.getByRole('button', { name: 'Launch' }))
const pending = await screen.findByRole('button', { name: 'Launching…' })
expect(pending).toBeDisabled()
expect(pending).toHaveAttribute('aria-busy', 'true')
expect(screen.queryByRole('button', { name: 'Launch' })).not.toBeInTheDocument()
await user.click(pending)
expect(mocks.launchMultiRun).toHaveBeenCalledTimes(1)
})
it('keeps the New run tab when the launch request fails', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockRejectedValue(new Error('launch failed'))
renderSheet()
await fillLaunchForm(user)
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => expect(mocks.launchMultiRun).toHaveBeenCalled())
expect(screen.getByRole('tab', { name: 'New run' })).toHaveAttribute('aria-selected', 'true')
expect(screen.getByLabelText('Group name')).toHaveValue('Sweep')
})
})
describe('Runs', () => {
it('expands the newest run and collapses older ones', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([oneStartedRun, olderRun])
renderSheet()
const newest = await screen.findByRole('region', { name: 'Sweep' })
const older = screen.getByRole('region', { name: 'Older sweep' })
expect(within(newest).getByText('go')).toBeInTheDocument()
expect(within(older).queryByText('older prompt')).not.toBeInTheDocument()
expect(within(older).getByText(/^2 models · isolated · base main/)).toBeInTheDocument()
await user.click(within(older).getByRole('button', { name: /older sweep/i }))
expect(within(older).getByText('older prompt')).toBeInTheDocument()
})
it('lists entries with their status and failure reason', async () => {
mocks.listMultiRuns.mockResolvedValue([oneStartedRun])
renderSheet()
const card = await screen.findByRole('region', { name: 'Sweep' })
expect(within(card).getByText('openai/gpt-4o')).toBeInTheDocument()
expect(within(card).getByText('Ready')).toBeInTheDocument()
expect(within(card).getByText('Failed')).toBeInTheDocument()
expect(within(card).getByText('launch failed')).toBeInTheDocument()
})
it('labels a launched entry with a busy session as running', async () => {
useSessionStatus.getState().setStatus('ses_11', { type: 'busy' })
mocks.listMultiRuns.mockResolvedValue([oneStartedRun])
renderSheet()
const card = await screen.findByRole('region', { name: 'Sweep' })
expect(within(card).getByText('Running')).toBeInTheDocument()
expect(within(card).queryByText('Ready')).not.toBeInTheDocument()
})
it('opens a started entry in the workspaces tab and closes the sheet', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([oneStartedRun])
const { onOpenChange } = renderSheet()
const card = await screen.findByRole('region', { name: 'Sweep' })
await user.click(within(card).getByRole('button', { name: 'Open' }))
expect(onOpenChange).toHaveBeenCalledWith(false)
expect(mockNavigate).toHaveBeenCalledWith('/repos/7/sessions/ses_11?repoTab=workspaces')
})
it('discards an entry from its overflow menu after confirmation', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([oneStartedRun])
mocks.discardMultiRunEntry.mockResolvedValue(oneStartedRun)
renderSheet()
await user.click(await screen.findByRole('button', { name: 'More actions for openai/gpt-4o' }))
await user.click(await screen.findByRole('menuitem', { name: /discard/i }))
const confirmDialog = await screen.findByRole('dialog', { name: 'Discard run' })
await user.click(within(confirmDialog).getByRole('button', { name: 'Discard' }))
await waitFor(() => expect(mocks.discardMultiRunEntry).toHaveBeenCalledWith(3, 11))
})
it('opens the walkthrough dialog for an entry session', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([oneStartedRun])
renderSheet()
const card = await screen.findByRole('region', { name: 'Sweep' })
await user.click(within(card).getByRole('button', { name: /walkthrough/i }))
expect(await screen.findByText('Change walkthrough')).toBeInTheDocument()
await waitFor(() => expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_11'))
})
it('lists fusions with truncation and opens the fusion session', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([{ ...oneStartedRun, fusions: [fusion()] }])
renderSheet()
const card = await screen.findByRole('region', { name: 'Sweep' })
expect(within(card).getByText('Fusions')).toBeInTheDocument()
expect(within(card).getByText('from 1 source (truncated)')).toBeInTheDocument()
const fusionRow = within(card).getByText('from 1 source (truncated)').closest('li') as HTMLElement
await user.click(within(fusionRow).getByRole('button', { name: 'Open' }))
expect(mockNavigate).toHaveBeenCalledWith('/repos/7/sessions/ses_fusion?repoTab=workspaces')
})
})
describe('Fusion selection mode', () => {
beforeEach(() => {
mocks.listMultiRuns.mockResolvedValue([fuseRun])
})
it('disables Fuse results for runs with fewer than two launched entries', async () => {
mocks.listMultiRuns.mockResolvedValue([oneStartedRun])
renderSheet()
const card = await screen.findByRole('region', { name: 'Sweep' })
expect(within(card).getByRole('button', { name: /fuse results/i })).toBeDisabled()
})
it('enters selection mode in place and exits it', async () => {
const user = userEvent.setup()
renderSheet()
const card = await enterSelection(user)
expect(within(card).getByText('Selection mode')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /start fusion/i })).toBeDisabled()
await user.click(within(card).getByRole('button', { name: 'Exit' }))
expect(within(card).queryByText('Selection mode')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /start fusion/i })).not.toBeInTheDocument()
expect(within(card).queryByRole('checkbox')).not.toBeInTheDocument()
})
it('dims unready entries with their reason and blocks selecting them', async () => {
const user = userEvent.setup()
useSessionStatus.getState().setStatus('ses_14', { type: 'busy' })
renderSheet()
const card = await enterSelection(user)
expect(within(card).getByRole('checkbox', { name: 'openai/gpt-4.1' })).toBeDisabled()
expect(within(card).getByText('Unavailable · still running — wait for a final reply')).toBeInTheDocument()
expect(within(card).getByRole('checkbox', { name: 'anthropic/claude-haiku' })).toBeDisabled()
expect(within(card).getByText('Unavailable · provider overloaded')).toBeInTheDocument()
expect(within(card).getByRole('checkbox', { name: 'openai/gpt-4o' })).toBeEnabled()
})
it('requires two sources and a synthesis model before starting', async () => {
const user = userEvent.setup()
renderSheet()
const card = await enterSelection(user)
const submit = screen.getByRole('button', { name: /start fusion/i })
await user.click(within(card).getByRole('checkbox', { name: 'openai/gpt-4o' }))
await user.click(within(card).getByRole('checkbox', { name: 'anthropic/claude-opus' }))
expect(submit).toBeDisabled()
expect(screen.getByText('2 of 4 selected')).toBeInTheDocument()
await chooseSynthesisModel(user, 'openai/gpt-4o')
expect(submit).toBeEnabled()
})
it('submits the selected sources, model, instructions and isolated destination', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockResolvedValue(fuseRun)
renderSheet()
await selectSourcesAndModel(user)
await user.click(screen.getByText('Instructions (optional)'))
await user.type(screen.getByLabelText('Instructions'), 'Merge the best ideas')
await user.click(screen.getByRole('button', { name: /start fusion/i }))
await waitFor(() => expect(mocks.fuseMultiRun).toHaveBeenCalledTimes(1))
const [runId, request] = mocks.fuseMultiRun.mock.calls[0] as [number, FuseMultiRunRequest]
expect(runId).toBe(5)
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, 13],
model: 'openai/gpt-4o',
instructions: 'Merge the best ideas',
isolate: true,
baseRef: 'main',
})
})
it('runs in the repository checkout without a base ref when chosen', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockResolvedValue(fuseRun)
renderSheet()
await selectSourcesAndModel(user)
await user.click(screen.getByRole('radio', { name: 'Repository checkout' }))
expect(screen.queryByRole('combobox', { name: 'Base ref' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /start fusion/i }))
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.listMultiRuns.mockResolvedValue([
{ ...fuseRun, entries: fuseRun.entries.map((item) => (item.id === 11 ? { ...item, isolated: false } : item)) },
])
renderSheet()
await selectSourcesAndModel(user)
expect(screen.getByRole('radio', { name: 'Repository checkout' })).toBeDisabled()
expect(screen.getByRole('radio', { name: 'Isolated' })).toHaveAttribute('aria-checked', 'true')
expect(
screen.getByText('Isolation is required because a selected result ran in the repository checkout.'),
).toBeInTheDocument()
})
it('shows the new fusion as Starting while the request is pending', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockReturnValue(new Promise(() => {}))
renderSheet()
const card = await selectSourcesAndModel(user)
await user.click(screen.getByRole('button', { name: /start fusion/i }))
expect(await within(card).findByText('Fusions')).toBeInTheDocument()
expect(within(card).getByText('Starting')).toBeInTheDocument()
expect(within(card).getByText('from 2 sources')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /start fusion/i }))
expect(mocks.fuseMultiRun).toHaveBeenCalledTimes(1)
})
it('opens the new session when the fusion starts', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockImplementation((_runId: number, request: FuseMultiRunRequest) =>
Promise.resolve(startedFusionResponse(request)),
)
const { onOpenChange } = renderSheet()
await selectSourcesAndModel(user)
await user.click(screen.getByRole('button', { name: /start fusion/i }))
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith('/repos/7/sessions/ses_new_fusion?repoTab=workspaces')
})
expect(onOpenChange).toHaveBeenCalledWith(false)
})
it('regenerates the request id after a failed fusion', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockImplementation((_runId: number, request: FuseMultiRunRequest) =>
Promise.resolve(startedFusionResponse(request, 'failed')),
)
renderSheet()
await selectSourcesAndModel(user)
const submit = screen.getByRole('button', { name: /start fusion/i })
await user.click(submit)
await waitFor(() => expect(mocks.fuseMultiRun).toHaveBeenCalledTimes(1))
await waitFor(() => expect(submit).toBeEnabled())
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('shows unavailable source reasons inline on the affected rows', 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: 13, model: 'anthropic/claude-opus', reason: 'running', message: 'The session is still running.' },
],
},
}),
)
renderSheet()
const card = await selectSourcesAndModel(user)
await user.click(screen.getByRole('button', { name: /start fusion/i }))
expect(await within(card).findByText('Unavailable · The session is still running.')).toBeInTheDocument()
expect(screen.getByText('Some selected results are not ready to fuse. See the marked rows.')).toBeInTheDocument()
})
it('shows the context limit message in the composer', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockRejectedValue(
new FetchError('The selected results are too large to fuse.', 413, 'FUSION_CONTEXT_LIMIT'),
)
renderSheet()
await selectSourcesAndModel(user)
await user.click(screen.getByRole('button', { name: /start fusion/i }))
expect(await screen.findByText('Too much context: select fewer sources or shorten instructions')).toBeInTheDocument()
})
it('offers to open a recovered fusion attempt', 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: 31, sessionId: 'ses_recovered' }] },
}),
)
renderSheet()
await selectSourcesAndModel(user)
await user.click(screen.getByRole('button', { name: /start fusion/i }))
expect(await screen.findByText('An earlier attempt is already running.')).toBeInTheDocument()
const message = screen.getByText('An earlier attempt is already running.').parentElement as HTMLElement
await user.click(within(message).getByRole('button', { name: 'Open' }))
expect(mockNavigate).toHaveBeenCalledWith('/repos/7/sessions/ses_recovered')
})
})
})
@@ -0,0 +1,401 @@
import { useCallback, useDeferredValue, useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Loader2, Play, Search } from 'lucide-react'
import { SideDrawer, SideDrawerContent, SideDrawerHeader } from '@/components/ui/side-drawer'
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 { Label } from '@/components/ui/label'
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
import { BranchCombobox } from '@/components/repo/BranchCombobox'
import { ModelCheckboxList } from '@/components/repo/ModelCheckboxList'
import { MultiRunCard } from '@/components/repo/MultiRunCard'
import { FusionComposer, type FusionComposerSubmission } from '@/components/repo/FusionComposer'
import { ChangesWalkthroughDialog } from '@/components/session/ChangesWalkthroughDialog'
import { useModelSections } from '@/hooks/useModelSections'
import { useDiscardMultiRunEntry, useFuseMultiRun, useLaunchMultiRun, useMultiRuns } from '@/hooks/useMultiRuns'
import { filterModelSections } from '@/lib/modelSections'
import { randomId } from '@/lib/utils'
import { buildSessionPath } from '@opencode-manager/shared/utils'
import {
FusionUnavailableDetailsSchema,
MULTI_RUN_MAX_MODELS,
type FuseMultiRunRequest,
type LaunchMultiRunRequest,
type MultiRunEntry,
} from '@opencode-manager/shared/schemas'
interface MultiRunSheetProps {
repoId: number
directory?: string
defaultBaseRef?: string
open: boolean
onOpenChange: (open: boolean) => void
}
type SheetTab = 'runs' | 'new'
interface PendingDiscard {
runId: number
entry: MultiRunEntry
}
interface FusionSelection {
runId: number
entryIds: number[]
}
const NO_UNAVAILABLE_REASONS: ReadonlyMap<number, string> = new Map()
function unavailableReasonsFromError(error: unknown): ReadonlyMap<number, string> {
const parsed = FusionUnavailableDetailsSchema.safeParse((error as { details?: unknown } | null)?.details)
if (!parsed.success) return NO_UNAVAILABLE_REASONS
return new Map(parsed.data.unavailableSources.map((source) => [source.entryId, source.message]))
}
export function MultiRunSheet({ repoId, directory, defaultBaseRef, open, onOpenChange }: MultiRunSheetProps) {
const navigate = useNavigate()
const [activeTab, setActiveTab] = useState<SheetTab>('runs')
const [expandedRuns, setExpandedRuns] = useState<Record<number, boolean>>({})
const [selection, setSelection] = useState<FusionSelection | null>(null)
const [fusionRequestId, setFusionRequestId] = useState(() => randomId())
const [pendingDiscard, setPendingDiscard] = useState<PendingDiscard | null>(null)
const [walkthroughSessionId, setWalkthroughSessionId] = useState<string | null>(null)
const runsQuery = useMultiRuns(repoId, open)
const fuse = useFuseMultiRun(repoId)
const discard = useDiscardMultiRunEntry(repoId)
const resetFuse = fuse.reset
useEffect(() => {
if (!open) return
setActiveTab('runs')
setExpandedRuns({})
setSelection(null)
resetFuse()
}, [open, resetFuse])
const runs = useMemo(() => runsQuery.data ?? [], [runsQuery.data])
const selectedRun = selection ? runs.find((run) => run.id === selection.runId) ?? null : null
const unavailableReasons = useMemo(() => unavailableReasonsFromError(fuse.error), [fuse.error])
const close = useCallback(() => onOpenChange(false), [onOpenChange])
const openSession = (sessionId: string, isolated: boolean) => {
onOpenChange(false)
navigate(buildSessionPath(repoId, sessionId, isolated ? { repoTab: 'workspaces' } : undefined))
}
const startSelection = (runId: number) => {
resetFuse()
setFusionRequestId(randomId())
setSelection({ runId, entryIds: [] })
}
const exitSelection = () => {
resetFuse()
setSelection(null)
}
const toggleEntry = (entryId: number, checked: boolean) => {
resetFuse()
setSelection((current) => {
if (!current) return current
if (!checked) return { ...current, entryIds: current.entryIds.filter((id) => id !== entryId) }
if (current.entryIds.includes(entryId) || current.entryIds.length >= MULTI_RUN_MAX_MODELS) return current
return { ...current, entryIds: [...current.entryIds, entryId] }
})
}
const submitFusion = (submission: FusionComposerSubmission) => {
if (!selection) return
const request: FuseMultiRunRequest = {
requestId: fusionRequestId,
entryIds: selection.entryIds,
model: submission.model,
...(submission.instructions ? { instructions: submission.instructions } : {}),
isolate: submission.isolate,
...(submission.isolate && submission.baseRef ? { baseRef: submission.baseRef } : {}),
}
fuse.mutate(
{ runId: selection.runId, request },
{
onSuccess: (run) => {
const fusion = run.fusions.find((candidate) => candidate.requestId === request.requestId)
if (fusion?.status === 'started' && fusion.sessionId) {
setSelection(null)
openSession(fusion.sessionId, fusion.isolated)
} else if (fusion?.status === 'failed') {
setFusionRequestId(randomId())
}
},
},
)
}
const confirmDiscard = () => {
if (!pendingDiscard) return
discard.mutate(
{ runId: pendingDiscard.runId, entryId: pendingDiscard.entry.id },
{ onSuccess: () => setPendingDiscard(null) },
)
}
return (
<>
<SideDrawer
isOpen={open}
onClose={close}
side="right"
widthClass="w-full sm:w-[min(640px,92vw)]"
ariaLabel="Multi-run"
>
<Tabs
value={activeTab}
onValueChange={(value) => setActiveTab(value as SheetTab)}
className="flex min-h-0 flex-1 flex-col"
>
<SideDrawerHeader
title="Multi-run"
onClose={close}
meta={
<TabsList className="mt-2 grid w-full grid-cols-2 sm:inline-grid sm:w-auto">
<TabsTrigger value="runs">Runs</TabsTrigger>
<TabsTrigger value="new">New run</TabsTrigger>
</TabsList>
}
/>
<TabsContent forceMount value="runs" className="mt-0 flex min-h-0 flex-1 flex-col px-0 data-[state=inactive]:hidden">
<SideDrawerContent className="space-y-3">
{runsQuery.isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : runsQuery.error ? (
<p className="text-sm text-destructive">
{runsQuery.error instanceof Error ? runsQuery.error.message : 'Failed to load runs'}
</p>
) : runs.length === 0 ? (
<div className="space-y-3 py-8 text-center">
<p className="text-sm text-muted-foreground">No runs yet.</p>
<Button variant="outline" onClick={() => setActiveTab('new')}>
Start a new run
</Button>
</div>
) : (
runs.map((run, index) => (
<MultiRunCard
key={run.id}
run={run}
expanded={expandedRuns[run.id] ?? index === 0}
onExpandedChange={(expanded) => setExpandedRuns((current) => ({ ...current, [run.id]: expanded }))}
selectedEntryIds={selection?.runId === run.id ? selection.entryIds : null}
unavailableReasons={selection?.runId === run.id ? unavailableReasons : NO_UNAVAILABLE_REASONS}
onStartSelection={() => startSelection(run.id)}
onExitSelection={exitSelection}
onToggleEntry={toggleEntry}
onOpenSession={openSession}
onWalkthrough={setWalkthroughSessionId}
onDiscard={(entry) => setPendingDiscard({ runId: run.id, entry })}
/>
))
)}
</SideDrawerContent>
{selection && selectedRun ? (
<FusionComposer
key={selectedRun.id}
repoId={repoId}
directory={directory}
run={selectedRun}
selectedEntryIds={selection.entryIds}
isPending={fuse.isPending}
error={fuse.error}
onCancel={exitSelection}
onSubmit={submitFusion}
onOpenSession={openSession}
/>
) : null}
</TabsContent>
<TabsContent forceMount value="new" className="mt-0 flex min-h-0 flex-1 flex-col px-0 data-[state=inactive]:hidden">
<NewRunForm
repoId={repoId}
directory={directory}
defaultBaseRef={defaultBaseRef}
open={open}
onLaunched={() => setActiveTab('runs')}
/>
</TabsContent>
</Tabs>
</SideDrawer>
<ConfirmDestructiveDialog
open={pendingDiscard !== null}
onOpenChange={(isOpen) => {
if (!isOpen) setPendingDiscard(null)
}}
onConfirm={confirmDiscard}
onCancel={() => setPendingDiscard(null)}
title="Discard run"
description={
pendingDiscard?.entry.isolated
? 'Discard this run and remove its workspace directory? This action cannot be undone.'
: 'Discard this run? This action cannot be undone.'
}
warning={pendingDiscard?.entry.model}
confirmLabel="Discard"
pendingLabel="Discarding..."
isPending={discard.isPending}
/>
{walkthroughSessionId ? (
<ChangesWalkthroughDialog
sessionId={walkthroughSessionId}
open
onOpenChange={(next) => {
if (!next) setWalkthroughSessionId(null)
}}
/>
) : null}
</>
)
}
interface NewRunFormProps {
repoId: number
directory?: string
defaultBaseRef?: string
open: boolean
onLaunched: () => void
}
function NewRunForm({ repoId, directory, defaultBaseRef, open, onLaunched }: NewRunFormProps) {
const [name, setName] = useState('')
const [prompt, setPrompt] = useState('')
const [selectedModels, setSelectedModels] = useState<string[]>([])
const [isolate, setIsolate] = useState(true)
const [baseRef, setBaseRef] = useState(defaultBaseRef ?? '')
const [modelSearch, setModelSearch] = useState('')
const deferredModelSearch = useDeferredValue(modelSearch)
const { sections: modelSections } = useModelSections(directory, { enabled: open })
const launch = useLaunchMultiRun(repoId)
const visibleModelSections = useMemo(
() => filterModelSections(modelSections, deferredModelSearch),
[modelSections, deferredModelSearch],
)
const toggleModel = useCallback((value: string, checked: boolean) => {
setSelectedModels((current) => {
if (checked) {
if (current.includes(value) || current.length >= MULTI_RUN_MAX_MODELS) return current
return [...current, value]
}
return current.filter((model) => model !== value)
})
}, [])
const canSubmit =
name.trim().length > 0 && prompt.trim().length > 0 && selectedModels.length > 0 && !launch.isPending
const handleLaunch = () => {
if (!canSubmit) return
const request: LaunchMultiRunRequest = {
repoId,
name: name.trim(),
prompt: prompt.trim(),
models: selectedModels,
isolate,
...(isolate && baseRef ? { baseRef } : {}),
}
launch.mutate(request, { onSuccess: onLaunched })
}
return (
<SideDrawerContent className="space-y-4">
<p className="text-sm text-muted-foreground">
Run one prompt on up to {MULTI_RUN_MAX_MODELS} models at once, each in its own session.
</p>
<div className="space-y-1.5">
<Label htmlFor="multi-run-name">Group name</Label>
<Input id="multi-run-name" value={name} onChange={(event) => setName(event.target.value)} placeholder="Sweep" />
</div>
<div className="space-y-1.5">
<Label htmlFor="multi-run-prompt">Prompt</Label>
<Textarea
id="multi-run-prompt"
value={prompt}
onChange={(event) => setPrompt(event.target.value)}
placeholder="The prompt to send to every model"
rows={4}
/>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label>Models</Label>
<span className="text-xs text-muted-foreground">
{selectedModels.length}/{MULTI_RUN_MAX_MODELS} selected
</span>
</div>
<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.'}
maxSelected={MULTI_RUN_MAX_MODELS}
/>
</div>
</div>
<div className="flex items-center justify-between rounded-lg border border-border p-3">
<div className="space-y-0.5">
<Label htmlFor="multi-run-isolate">Isolate runs</Label>
<p className="text-xs text-muted-foreground">Give each model its own workspace.</p>
</div>
<Switch id="multi-run-isolate" checked={isolate} onCheckedChange={setIsolate} />
</div>
{isolate ? (
<div className="space-y-1.5">
<Label htmlFor="multi-run-base-ref">Start from</Label>
<BranchCombobox
id="multi-run-base-ref"
repoId={repoId}
value={baseRef}
onValueChange={setBaseRef}
placeholder="Current HEAD"
clearable
/>
<p className="text-xs text-muted-foreground">Each isolated workspace starts from this branch.</p>
</div>
) : null}
<div className="flex justify-end">
<Button className="min-w-32" onClick={handleLaunch} disabled={!canSubmit} aria-busy={launch.isPending}>
{launch.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
{launch.isPending ? 'Launching…' : 'Launch'}
</Button>
</div>
</SideDrawerContent>
)
}
@@ -48,6 +48,20 @@ describe('SideDrawer', () => {
expect(handleClose).toHaveBeenCalled()
})
it('ignores an Escape key already handled by a nested layer', () => {
const handleClose = vi.fn()
render(
<SideDrawer isOpen onClose={handleClose} ariaLabel="Test drawer">
<div>Test content</div>
</SideDrawer>,
)
const handled = (event: KeyboardEvent) => event.preventDefault()
document.addEventListener('keydown', handled, { capture: true })
fireEvent.keyDown(document, { key: 'Escape' })
document.removeEventListener('keydown', handled, { capture: true })
expect(handleClose).not.toHaveBeenCalled()
})
})
describe('SideDrawerHeader', () => {
+1 -1
View File
@@ -35,7 +35,7 @@ export function SideDrawer({
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isOpen) {
if (e.key === 'Escape' && isOpen && !e.defaultPrevented) {
onClose()
}
}
+43 -1
View File
@@ -2,7 +2,12 @@ import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tansta
import { discardMultiRunEntry, fuseMultiRun, launchMultiRun, listMultiRuns } from '@/api/multiRuns'
import { repoSiblingsQueryKey } from '@/hooks/useRepoSiblings'
import { showToast } from '@/lib/toast'
import type { FuseMultiRunRequest, LaunchMultiRunRequest, MultiRun } from '@opencode-manager/shared/schemas'
import type {
FuseMultiRunRequest,
LaunchMultiRunRequest,
MultiRun,
MultiRunFusion,
} from '@opencode-manager/shared/schemas'
function multiRunQueryKey(repoId: number) {
return ['multi-runs', repoId] as const
@@ -13,6 +18,29 @@ function invalidateMultiRunCaches(queryClient: QueryClient, repoId: number) {
queryClient.invalidateQueries({ queryKey: repoSiblingsQueryKey(repoId) })
}
function buildStartingFusion(run: MultiRun, request: FuseMultiRunRequest): MultiRunFusion {
const now = Date.now()
const entriesById = new Map(run.entries.map((entry) => [entry.id, entry]))
return {
id: -now,
requestId: request.requestId,
model: request.model,
instructions: request.instructions ?? null,
isolated: request.isolate,
baseRef: request.baseRef ?? null,
status: 'starting',
sessionId: null,
directory: null,
error: null,
sources: request.entryIds.flatMap((entryId) => {
const entry = entriesById.get(entryId)
return entry?.sessionId ? [{ entryId, sessionId: entry.sessionId, model: entry.model, truncated: false }] : []
}),
createdAt: now,
updatedAt: now,
}
}
function countEntries(run: MultiRun, status: MultiRun['entries'][number]['status']) {
return run.entries.filter((entry) => entry.status === status).length
}
@@ -55,7 +83,21 @@ export function useFuseMultiRun(repoId: number) {
return useMutation({
mutationFn: ({ runId, request }: { runId: number; request: FuseMultiRunRequest }) =>
fuseMultiRun(runId, request),
onMutate: async ({ runId, request }) => {
const queryKey = multiRunQueryKey(repoId)
await queryClient.cancelQueries({ queryKey })
queryClient.setQueryData<MultiRun[]>(queryKey, (runs) =>
runs?.map((run) =>
run.id === runId && !run.fusions.some((fusion) => fusion.requestId === request.requestId)
? { ...run, fusions: [...run.fusions, buildStartingFusion(run, request)] }
: run,
),
)
},
onSuccess: (run, variables) => {
queryClient.setQueryData<MultiRun[]>(multiRunQueryKey(repoId), (runs) =>
runs?.map((candidate) => (candidate.id === run.id ? run : candidate)),
)
invalidateMultiRunCaches(queryClient, repoId)
const fusion = run.fusions.find((candidate) => candidate.requestId === variables.request.requestId)
if (fusion?.status === 'started') {
+2 -2
View File
@@ -9,7 +9,7 @@ import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
import { ProjectActionsMenu } from "@/components/repo/ProjectActionsMenu";
import { RepoActionsDialog } from "@/components/repo/RepoActionsDialog";
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
import { MultiRunDialog } from "@/components/repo/MultiRunDialog";
import { MultiRunSheet } from "@/components/repo/MultiRunSheet";
import { SourceControlPanel } from "@/components/source-control";
import { TerminalPanel } from "@/components/terminal/TerminalPanel";
import { PreviewPanel } from "@/components/preview/PreviewPanel";
@@ -343,7 +343,7 @@ export function RepoDetail() {
repoId={repoId}
/>
<MultiRunDialog
<MultiRunSheet
repoId={repoId}
directory={baseDirectory}
defaultBaseRef={currentBranch}
+6
View File
@@ -124,3 +124,9 @@ export const FusionUnavailableDetailsSchema = z.object({
});
export type FusionUnavailableDetails = z.infer<typeof FusionUnavailableDetailsSchema>;
export const FusionRecoveredDetailsSchema = z.object({
fusions: z.array(z.object({ fusionId: z.number().int(), sessionId: z.string() })),
});
export type FusionRecoveredDetails = z.infer<typeof FusionRecoveredDetailsSchema>;