feat(multi-run): always run fusions in a new worktree

This commit is contained in:
Chris Scott committed 2026-10-07 13:12:25 -04:00
1 parent 30783c49ec
commit ec96ac0d55
9 files changed
+69 -210

No files matched your search

+12 -23
View File
@@ -1,7 +1,7 @@
import type { Database } from 'bun:sqlite'
import { existsSync } from 'node:fs'
import { resolve } from 'node:path'
import type { FuseMultiRunRequest, LaunchMultiRunRequest, MultiRun } from '@opencode-manager/shared/schemas'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import {
createMultiRunWithEntries,
getMultiRun,
@@ -168,6 +168,12 @@ export class MultiRunService {
return { run: this.reload(multiRunId), created: false }
}
if (record.repoId === ASSISTANT_REPO_ID) {
throw new MultiRunError('Fusion needs a Git repository because it always runs in a new worktree.', 409, {
code: 'FUSION_REQUIRES_GIT_REPOSITORY',
})
}
let repo: Repo
try {
repo = requireReadyRepo(this.db, record.repoId)
@@ -184,19 +190,6 @@ export class MultiRunService {
return entry
})
if (!request.isolate) {
const overlappingEntryIds = selectedEntries
.filter((entry) => entry.directory !== null && resolve(entry.directory) === resolve(repo.fullPath))
.map((entry) => entry.id)
if (overlappingEntryIds.length > 0) {
throw new MultiRunError(
'The synthesis cannot run in the repository checkout because a selected result ran there. Enable an isolated workspace.',
409,
{ code: 'FUSION_DESTINATION_OVERLAPS_SOURCE', details: { entryIds: overlappingEntryIds } },
)
}
}
const sourcePermissions = buildFusionSourcePermissionRuleset(
selectedEntries
.map((entry) => entry.directory)
@@ -234,7 +227,7 @@ export class MultiRunService {
requestId: request.requestId,
model: request.model,
instructions: request.instructions ?? null,
isolated: request.isolate,
isolated: true,
baseRef: request.baseRef ?? null,
sources: built.sources,
})
@@ -252,14 +245,10 @@ export class MultiRunService {
title: `${record.name} · fusion`,
...(request.agent ? { agent: request.agent } : {}),
permissions: sourcePermissions,
...(request.isolate
? {
workspace: {
name: `${record.name}-fusion-${fusion.id}`,
...(request.baseRef ? { ref: request.baseRef } : {}),
},
}
: {}),
workspace: {
name: `${record.name}-fusion-${fusion.id}`,
...(request.baseRef ? { ref: request.baseRef } : {}),
},
})
updateMultiRunFusion(this.db, fusion.id, ['starting'], {
@@ -204,7 +204,6 @@ describe('FuseMultiRunRequestSchema', () => {
requestId: '00000000-0000-4000-8000-000000000000',
entryIds: [1, 2],
model: 'openai/gpt-5',
isolate: true,
}
it('accepts at least two unique entry ids', () => {
-2
View File
@@ -35,7 +35,6 @@ function fuseBody(overrides: Record<string, unknown> = {}): string {
requestId: '11111111-1111-4111-8111-111111111111',
entryIds: [1, 2],
model: 'openai/a',
isolate: true,
...overrides,
})
}
@@ -175,7 +174,6 @@ describe('multi-run routes', () => {
requestId: '11111111-1111-4111-8111-111111111111',
entryIds: [1, 2],
model: 'openai/a',
isolate: true,
})
})
+17 -67
View File
@@ -1,10 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Database } from 'bun:sqlite'
import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
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 { createMultiRunWithEntries, getMultiRun } 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'
@@ -631,7 +632,6 @@ describe('MultiRunService', () => {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: true,
baseRef: 'develop',
})
@@ -685,7 +685,6 @@ describe('MultiRunService', () => {
requestId: FUSE_REQUEST_ID,
entryIds: [entryIds[0]!, entryIds[2]!],
model: 'openai/d',
isolate: true,
})
expect(sessionCreate).toHaveBeenCalledTimes(1)
@@ -724,7 +723,6 @@ describe('MultiRunService', () => {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: false,
})
const fusionSessionId = fused.fusions[0]!.sessionId!
@@ -751,7 +749,6 @@ describe('MultiRunService', () => {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: false,
})
const fusionSessionId = fused.fusions[0]!.sessionId!
@@ -782,7 +779,6 @@ describe('MultiRunService', () => {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: false,
})
const fusion = fused.fusions[0]!
@@ -810,7 +806,7 @@ describe('MultiRunService', () => {
const entryIds = run.entries.map((entry) => entry.id)
sessionCreate.mockClear()
const request = { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/c', isolate: false }
const request = { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/c' }
const first = await service.fuse(run.id, request)
const second = await service.fuse(run.id, request)
@@ -839,7 +835,7 @@ describe('MultiRunService', () => {
sessionCreate.mockClear()
const error = await service
.fuse(run.id, { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/c', isolate: false })
.fuse(run.id, { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/c' })
.catch((caught: unknown) => caught)
expect(error).toBeInstanceOf(MultiRunError)
@@ -868,7 +864,7 @@ describe('MultiRunService', () => {
sessionCreate.mockClear()
const error = await service
.fuse(run.id, { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/c', isolate: false })
.fuse(run.id, { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/c' })
.catch((caught: unknown) => caught)
expect(error).toBeInstanceOf(FusionContextLimitError)
@@ -894,7 +890,7 @@ describe('MultiRunService', () => {
sessionCreate.mockClear()
const error = await service
.fuse(run.id, { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/retired', isolate: false })
.fuse(run.id, { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/retired' })
.catch((caught: unknown) => caught)
expect(error).toBeInstanceOf(MultiRunError)
@@ -925,7 +921,6 @@ describe('MultiRunService', () => {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: true,
})
expect(created).toBe(true)
@@ -933,6 +928,7 @@ describe('MultiRunService', () => {
expect(fusion.status).toBe('failed')
expect(fusion.error).toContain('fusion boom')
expect(fusion.directory).toBe('/worktrees/Sweep-fusion-1')
expect(fusion.isolated).toBe(true)
})
it('records the created session id on a failed fusion when the prompt is rejected', async () => {
@@ -956,7 +952,6 @@ describe('MultiRunService', () => {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: false,
})
expect(created).toBe(true)
@@ -987,7 +982,6 @@ describe('MultiRunService', () => {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: false,
})
const failedFusion = firstFused.fusions[0]!
expect(failedFusion.status).toBe('failed')
@@ -1000,7 +994,6 @@ describe('MultiRunService', () => {
requestId: '22222222-2222-4222-8222-222222222222',
entryIds,
model: 'openai/c',
isolate: false,
})
.catch((caught: unknown) => caught)
@@ -1036,7 +1029,6 @@ describe('MultiRunService', () => {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: false,
})
expect(firstFused.fusions[0]!.status).toBe('failed')
@@ -1046,7 +1038,6 @@ describe('MultiRunService', () => {
requestId: '33333333-3333-4333-8333-333333333333',
entryIds,
model: 'openai/c',
isolate: false,
})
expect(created).toBe(true)
@@ -1054,65 +1045,25 @@ describe('MultiRunService', () => {
expect(fused.fusions.map((fusion) => fusion.status)).toEqual(['failed', 'started'])
})
it('rejects a non-isolated fusion when a selected result ran in the repository checkout', async () => {
const repoId = readyRepo()
it('rejects fusion for the Assistant before creating a fusion', async () => {
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: false,
})
const entryIds = run.entries.map((entry) => entry.id)
sessionCreate.mockClear()
const record = createMultiRunWithEntries(
db,
{ repoId: ASSISTANT_REPO_ID, name: 'Sweep', prompt: 'go', isolated: false, baseRef: null },
['openai/a', 'openai/b'],
)
const error = await service
.fuse(run.id, {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: false,
})
.fuse(record.id, { requestId: FUSE_REQUEST_ID, entryIds: record.entries.map((entry) => entry.id), model: 'openai/c' })
.catch((caught: unknown) => caught)
expect(error).toBeInstanceOf(MultiRunError)
expect(error).toMatchObject({ status: 409, code: 'FUSION_DESTINATION_OVERLAPS_SOURCE' })
expect((error as MultiRunError).details).toEqual({ entryIds })
expect(error).toMatchObject({ status: 409, code: 'FUSION_REQUIRES_GIT_REPOSITORY' })
expect(repoWorkspaces.create).not.toHaveBeenCalled()
expect(sessionCreate).not.toHaveBeenCalled()
expect(service.list(repoId)[0]!.fusions).toEqual([])
})
it('allows an isolated fusion when the selected results ran in the repository checkout', 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: false,
})
const entryIds = run.entries.map((entry) => entry.id)
sessionCreate.mockClear()
const { run: fused, created } = await service.fuse(run.id, {
requestId: FUSE_REQUEST_ID,
entryIds,
model: 'openai/c',
isolate: true,
})
expect(created).toBe(true)
expect(fused.fusions[0]!.status).toBe('started')
expect(fused.fusions[0]!.directory).toBe('/worktrees/Sweep-fusion-1')
expect(sessionCreate).toHaveBeenCalledTimes(1)
expect(getMultiRun(db, record.id)!.fusions).toEqual([])
})
it('rejects fusion with an entry id that does not belong to the run', async () => {
@@ -1136,7 +1087,6 @@ describe('MultiRunService', () => {
requestId: FUSE_REQUEST_ID,
entryIds: [entryIds[0]!, 9999],
model: 'openai/c',
isolate: false,
})
.catch((caught: unknown) => caught)
+34 -89
View File
@@ -1,4 +1,4 @@
import { useId, useState, type ReactNode } from 'react'
import { useId, useState } from 'react'
import { ArrowRight, ArrowUpRight, Combine, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
@@ -15,7 +15,6 @@ import {
export interface FusionComposerSubmission {
model: string
isolate: boolean
baseRef: string
instructions: string
}
@@ -50,85 +49,54 @@ export function FusionComposer({
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() })
onSubmit({ model, 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}
<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="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 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">
@@ -153,10 +121,12 @@ export function FusionComposer({
</span>
<span className="sm:hidden">
{' '}
<ArrowRight className="inline h-3 w-3" aria-hidden="true" /> {model || 'no model'} ·{' '}
{effectiveIsolate ? 'isolated' : 'repository checkout'}
<ArrowRight className="inline h-3 w-3" aria-hidden="true" /> {model || 'no model'} · new worktree
</span>
<span className="hidden sm:inline">
{' '}
· runs in a new worktree; blank base ref uses the current HEAD; sources are never modified.
</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
@@ -181,31 +151,6 @@ export function FusionComposer({
)
}
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
@@ -575,7 +575,7 @@ describe('MultiRunSheet', () => {
expect(submit).toBeEnabled()
})
it('submits the selected sources, model, instructions and isolated destination', async () => {
it('submits the selected sources, model, instructions and base ref', async () => {
const user = userEvent.setup()
mocks.fuseMultiRun.mockResolvedValue(fuseRun)
renderSheet()
@@ -593,28 +593,11 @@ describe('MultiRunSheet', () => {
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 () => {
it('always runs the fusion in a new worktree without a destination choice', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([
{ ...fuseRun, entries: fuseRun.entries.map((item) => (item.id === 11 ? { ...item, isolated: false } : item)) },
@@ -623,11 +606,8 @@ describe('MultiRunSheet', () => {
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()
expect(screen.queryByRole('radio', { name: 'Repository checkout' })).not.toBeInTheDocument()
expect(screen.getByRole('combobox', { name: 'Base ref' })).toBeInTheDocument()
})
it('shows the new fusion as Starting while the request is pending', async () => {
@@ -116,8 +116,7 @@ export function MultiRunSheet({ repoId, directory, defaultBaseRef, open, onOpenC
entryIds: selection.entryIds,
model: submission.model,
...(submission.instructions ? { instructions: submission.instructions } : {}),
isolate: submission.isolate,
...(submission.isolate && submission.baseRef ? { baseRef: submission.baseRef } : {}),
...(submission.baseRef ? { baseRef: submission.baseRef } : {}),
}
fuse.mutate(
{ runId: selection.runId, request },
+1 -1
View File
@@ -26,7 +26,7 @@ function buildStartingFusion(run: MultiRun, request: FuseMultiRunRequest): Multi
requestId: request.requestId,
model: request.model,
instructions: request.instructions ?? null,
isolated: request.isolate,
isolated: true,
baseRef: request.baseRef ?? null,
status: 'starting',
sessionId: null,
-1
View File
@@ -92,7 +92,6 @@ export const FuseMultiRunRequestSchema = z.object({
.refine((entryIds) => new Set(entryIds).size === entryIds.length, { message: "Entry ids must be unique" }),
model: z.string().min(3),
instructions: z.string().trim().max(FUSION_INSTRUCTIONS_MAX_LENGTH).optional(),
isolate: z.boolean(),
baseRef: z.string().trim().min(1).optional(),
agent: z.string().optional(),
});