section 6: Phase 6: Launch a multi-run from the TUI (/multirun)

This commit is contained in:
Chris Scott committed 2026-10-07 18:33:03 -04:00
1 parent e63f756c32
commit 0aaa2bd3d6
6 files changed
+590 -3

No files matched your search

+2
View File
@@ -6,6 +6,8 @@ export type ManagerAuth =
| { ok: true; managerUrl: string; token: string }
| { ok: false; message: string }
export type ManagerAuthOk = Extract<ManagerAuth, { ok: true }>
export async function resolveManagerAuth(
managerUrl: string | undefined = readState()?.managerUrl,
): Promise<ManagerAuth> {
+1 -3
View File
@@ -3,7 +3,7 @@ import type { SessionGoal } from '@opencode-manager/shared/schemas'
import { getGoalOutcomeTitle, getGoalStopReasonLabel } from '@opencode-manager/shared/notifications'
import { ManagerApi, ManagerApiError, isManagerRouteMissing } from './manager-api.js'
import { resolveManagerAuth } from './manager-auth.js'
import type { ManagerAuth } from './manager-auth.js'
import type { ManagerAuthOk } from './manager-auth.js'
import { promptDialog, selectDialog, slashArgument } from './tui-dialogs.js'
import { isOpenGoal } from './goal-store.js'
import type { GoalStore } from './goal-store.js'
@@ -13,8 +13,6 @@ export const GOALS_ATTACH_REQUIRED =
'Goals run on OpenCode Manager. Attach with `ocm` (or move this session with /ocm-move) first.'
export const GOALS_ROUTE_MISSING = 'This OpenCode Manager does not expose goals to ocm; upgrade the Manager.'
export type ManagerAuthOk = Extract<ManagerAuth, { ok: true }>
export type GoalCommandDeps = {
remote: RemoteContext | undefined
store: GoalStore | undefined
+161
View File
@@ -0,0 +1,161 @@
import type { Context, ToastOptions } from '@opencode/plugin/tui/context'
import {
MULTI_RUN_MAX_MODELS,
type LaunchMultiRunRequest,
type MultiRun,
type MultiRunEntry,
} from '@opencode-manager/shared/schemas'
import { formatOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import { ManagerApi, ManagerApiError, isManagerRouteMissing } from './manager-api.js'
import { resolveManagerAuth } from './manager-auth.js'
import type { ManagerAuthOk } from './manager-auth.js'
import { multiSelectDialog, promptDialog, selectDialog, slashArgument } from './tui-dialogs.js'
import type { RemoteContext } from './remote-context.js'
export const MULTI_RUN_ATTACH_REQUIRED =
'Multi-runs run on OpenCode Manager. Attach to a Manager repo with `ocm` first.'
export const MULTI_RUN_ROUTE_MISSING = 'This OpenCode Manager does not expose multi-runs to ocm; upgrade the Manager.'
export type ModelOption = {
title: string
description: string
value: string
}
export type MultiRunCommandDeps = {
remote: RemoteContext | undefined
createApi?: (auth: ManagerAuthOk) => ManagerApi
}
export async function listModelOptions(context: Context): Promise<ModelOption[]> {
await context.data.location.model.sync()
const models = context.data.location.model.list() ?? []
return models
.filter((model) => model.enabled && model.status !== 'deprecated')
.map((model) => {
const ref = formatOpenCodeModelRef({ providerID: model.providerID, id: model.id })
return { title: model.name, description: ref, value: ref }
})
}
export function openManagerSessions(context: Context, sessionIDs: string[]): void {
const first = sessionIDs[0]
if (!first) return
if (context.ui.tabs.enabled()) {
for (const sessionID of sessionIDs) context.ui.tabs.open(sessionID)
context.ui.tabs.focus(first)
return
}
context.ui.router.navigate({ type: 'session', sessionID: first })
}
function defaultMultiRunName(prompt: string): string {
return prompt.split('\n')[0].slice(0, 80)
}
function startedSessionIds(run: MultiRun): string[] {
return run.entries
.filter((entry): entry is MultiRunEntry & { sessionId: string } => entry.status === 'started' && entry.sessionId !== null)
.map((entry) => entry.sessionId)
}
function multiRunLaunchToast(run: MultiRun): ToastOptions {
const started = run.entries.filter((entry) => entry.status === 'started').length
const failed = run.entries.filter((entry) => entry.status === 'failed')
const lines = [`Launched ${run.name}: ${started}/${run.entries.length} started`]
for (const entry of failed) lines.push(`${entry.model}: ${entry.error ?? 'failed'}`)
return { variant: failed.length > 0 ? 'warning' : 'success', message: lines.join('\n') }
}
function showMultiRunError(context: Context, error: unknown): void {
if (isManagerRouteMissing(error)) {
context.ui.toast.show({ variant: 'error', message: MULTI_RUN_ROUTE_MISSING })
return
}
if (error instanceof ManagerApiError) {
context.ui.toast.show({ variant: 'error', message: error.message })
return
}
context.ui.toast.show({ variant: 'error', message: error instanceof Error ? error.message : String(error) })
}
async function launchMultiRunFlow(context: Context, api: ManagerApi, repoId: number, prompt: string): Promise<void> {
const name = await promptDialog(context, {
title: 'Multi-run name',
description: 'Name this group of runs.',
placeholder: 'Sweep',
value: defaultMultiRunName(prompt),
})
if (!name) return
const models = await multiSelectDialog(context, {
title: 'Models',
options: await listModelOptions(context),
min: 1,
max: MULTI_RUN_MAX_MODELS,
})
if (!models) return
const isolate = await selectDialog<boolean>(context, 'Isolation', [
{ title: 'Isolated worktrees (recommended)', value: true },
{ title: 'Shared repo directory', value: false },
])
if (isolate === undefined) return
const baseRef = isolate
? await promptDialog(context, {
title: 'Start from',
description: 'Each isolated workspace starts from this branch.',
placeholder: 'Current HEAD',
})
: undefined
const request: LaunchMultiRunRequest = {
repoId,
name,
prompt,
models,
isolate,
...(isolate && baseRef ? { baseRef } : {}),
}
const run = await api.launchMultiRun(request)
context.ui.toast.show(multiRunLaunchToast(run))
openManagerSessions(context, startedSessionIds(run))
}
export async function runMultiRunCommand(
context: Context,
deps: MultiRunCommandDeps,
input?: string,
): Promise<void> {
try {
const remote = deps.remote
if (!remote?.repoId) {
context.ui.toast.show({ variant: 'error', message: MULTI_RUN_ATTACH_REQUIRED })
return
}
const auth = await resolveManagerAuth(remote.managerUrl)
if (!auth.ok) {
context.ui.toast.show({ variant: 'error', message: auth.message })
return
}
const prompt =
slashArgument(input, 'multirun') ||
(await promptDialog(context, {
title: 'Multi-run prompt',
description: 'The prompt to send to every model.',
placeholder: 'Describe the task',
}))
if (!prompt) return
const api = deps.createApi ? deps.createApi(auth) : new ManagerApi(auth.managerUrl, auth.token)
await launchMultiRunFlow(context, api, remote.repoId, prompt)
} catch (error) {
showMultiRunError(context, error)
}
}
+10
View File
@@ -16,6 +16,7 @@ import { pushPhaseProgress, importProgress } from './move-progress.js'
import { warmRepoProxy } from './repo-proxy.js'
import type { MoveProgress } from './move-progress.js'
import { runGoalCommand } from './tui-goal.js'
import { runMultiRunCommand } from './tui-multi-run.js'
import type { GoalStore } from './goal-store.js'
import type { RemoteContext } from './remote-context.js'
@@ -52,6 +53,15 @@ export async function setupOcm(context: Context, setMoveProgress: MoveProgressSe
slash: { name: 'goal', arguments: true },
run: (input) => runGoalCommand(context, { remote: features.remote, store: features.goals }, input),
},
{
id: 'ocm.multirun',
title: 'Multi-run',
description: 'Run one prompt across several models on OpenCode Manager',
group: 'OpenCode Manager',
palette: true,
slash: { name: 'multirun', arguments: true },
run: (input) => runMultiRunCommand(context, { remote: features.remote }, input),
},
],
}))
return null
+403
View File
@@ -0,0 +1,403 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { Context } from '@opencode/plugin/tui/context'
import type { ModelInfo } from '@opencode/client'
import type { MultiRun, MultiRunEntry } from '@opencode-manager/shared/schemas'
import {
listModelOptions,
openManagerSessions,
runMultiRunCommand,
MULTI_RUN_ATTACH_REQUIRED,
MULTI_RUN_ROUTE_MISSING,
} from '../src/tui-multi-run.js'
import { ManagerApiError } from '../src/manager-api.js'
import type { ManagerApi } from '../src/manager-api.js'
import { resolveManagerAuth } from '../src/manager-auth.js'
import type { RemoteContext } from '../src/remote-context.js'
vi.mock('../src/manager-auth.js', () => ({
resolveManagerAuth: vi.fn(),
}))
const remote: RemoteContext = {
managerUrl: 'https://manager.example',
managerHost: 'manager.example',
repoName: 'repo',
repoId: 1,
}
function model(overrides: Partial<ModelInfo> = {}): ModelInfo {
return {
id: 'gpt-5',
modelID: 'gpt-5',
providerID: 'openai',
name: 'GPT-5',
capabilities: {} as ModelInfo['capabilities'],
variants: [],
time: { released: 0 },
cost: [],
status: 'active',
enabled: true,
limit: { context: 0, output: 0 },
...overrides,
} as ModelInfo
}
function entry(overrides: Partial<MultiRunEntry> = {}): MultiRunEntry {
return {
id: 1,
model: 'openai/gpt-5',
status: 'started',
sessionId: 'ses_1',
directory: '/work/1',
isolated: true,
error: null,
createdAt: 1,
updatedAt: 1,
...overrides,
}
}
function multiRun(overrides: Partial<MultiRun> = {}): MultiRun {
return {
id: 3,
repoId: 1,
name: 'sweep',
prompt: 'hello',
isolated: true,
baseRef: null,
createdAt: 1,
entries: [entry()],
fusions: [],
...overrides,
}
}
function createFakeContext() {
const toast = vi.fn()
const prompt = vi.fn()
const select = vi.fn()
const confirm = vi.fn()
const open = vi.fn()
const focus = vi.fn()
const enabled = vi.fn(() => true)
const navigate = vi.fn()
const sync = vi.fn(async () => undefined)
const list = vi.fn(() => [] as ModelInfo[])
const context = {
ui: {
toast: { show: toast },
dialog: { prompt, select, confirm },
tabs: { enabled, open, focus },
router: { navigate, current: () => ({ type: 'session', sessionID: 'ses_a' }) },
},
data: { location: { model: { sync, list } } },
} as unknown as Context
return { context, toast, prompt, select, confirm, open, focus, enabled, navigate, sync, list }
}
function makeApi() {
return {
launchMultiRun: vi.fn(async () => multiRun()),
listMultiRuns: vi.fn(async () => [] as MultiRun[]),
}
}
function depsFor(api: ReturnType<typeof makeApi>, createApi = vi.fn(() => api as unknown as ManagerApi)) {
return { remote, createApi }
}
beforeEach(() => {
vi.mocked(resolveManagerAuth).mockReset()
vi.mocked(resolveManagerAuth).mockResolvedValue({ ok: true, managerUrl: remote.managerUrl, token: 'tok' })
})
describe('listModelOptions', () => {
it('syncs then maps enabled, non-deprecated models to refs', async () => {
const fake = createFakeContext()
fake.list.mockReturnValue([
model({ providerID: 'openai', id: 'gpt-5', name: 'GPT-5' }),
model({ providerID: 'anthropic', id: 'claude', name: 'Claude' }),
model({ providerID: 'openai', id: 'old', name: 'Old', status: 'deprecated' }),
model({ providerID: 'openai', id: 'off', name: 'Off', enabled: false }),
])
await expect(listModelOptions(fake.context)).resolves.toEqual([
{ title: 'GPT-5', description: 'openai/gpt-5', value: 'openai/gpt-5' },
{ title: 'Claude', description: 'anthropic/claude', value: 'anthropic/claude' },
])
expect(fake.sync).toHaveBeenCalledTimes(1)
expect(fake.sync.mock.invocationCallOrder[0]).toBeLessThan(fake.list.mock.invocationCallOrder[0])
})
it('tolerates a model list that is not loaded yet', async () => {
const fake = createFakeContext()
fake.list.mockReturnValue(undefined as unknown as ModelInfo[])
await expect(listModelOptions(fake.context)).resolves.toEqual([])
})
})
describe('openManagerSessions', () => {
it('opens a tab per session then focuses the first when tabs are enabled', () => {
const fake = createFakeContext()
openManagerSessions(fake.context, ['ses_1', 'ses_2'])
expect(fake.open).toHaveBeenNthCalledWith(1, 'ses_1')
expect(fake.open).toHaveBeenNthCalledWith(2, 'ses_2')
expect(fake.focus).toHaveBeenCalledWith('ses_1')
expect(fake.navigate).not.toHaveBeenCalled()
})
it('navigates to the first session when tabs are disabled', () => {
const fake = createFakeContext()
fake.enabled.mockReturnValue(false)
openManagerSessions(fake.context, ['ses_1', 'ses_2'])
expect(fake.navigate).toHaveBeenCalledWith({ type: 'session', sessionID: 'ses_1' })
expect(fake.open).not.toHaveBeenCalled()
expect(fake.focus).not.toHaveBeenCalled()
})
it('does nothing for an empty session list', () => {
const fake = createFakeContext()
openManagerSessions(fake.context, [])
expect(fake.enabled).not.toHaveBeenCalled()
expect(fake.open).not.toHaveBeenCalled()
expect(fake.focus).not.toHaveBeenCalled()
expect(fake.navigate).not.toHaveBeenCalled()
})
})
describe('runMultiRunCommand', () => {
it('refuses when not attached to a Manager', async () => {
const fake = createFakeContext()
const createApi = vi.fn()
await runMultiRunCommand(fake.context, { remote: undefined, createApi }, '/multirun fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: MULTI_RUN_ATTACH_REQUIRED })
expect(createApi).not.toHaveBeenCalled()
})
it('refuses when the attach env carries no repo id', async () => {
const fake = createFakeContext()
const createApi = vi.fn()
await runMultiRunCommand(fake.context, { remote: { ...remote, repoId: undefined }, createApi }, '/multirun fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: MULTI_RUN_ATTACH_REQUIRED })
expect(createApi).not.toHaveBeenCalled()
})
it('launches with the chosen name, models, isolation and base ref, then opens the sessions', async () => {
const fake = createFakeContext()
const api = makeApi()
const run = multiRun({
name: 'sweep',
entries: [entry({ id: 1, sessionId: 'ses_1' }), entry({ id: 2, sessionId: 'ses_2' })],
})
api.launchMultiRun.mockResolvedValue(run)
fake.list.mockReturnValue([
model({ providerID: 'openai', id: 'gpt-5', name: 'GPT-5' }),
model({ providerID: 'anthropic', id: 'claude', name: 'Claude' }),
])
fake.prompt.mockResolvedValueOnce('sweep').mockResolvedValueOnce('main')
fake.select.mockResolvedValueOnce(0).mockResolvedValueOnce(1).mockResolvedValueOnce(-1).mockResolvedValueOnce(true)
await runMultiRunCommand(fake.context, depsFor(api), '/multirun fix the bug')
expect(fake.prompt).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ title: 'Multi-run name', value: 'fix the bug' }),
)
expect(api.launchMultiRun).toHaveBeenCalledWith({
repoId: 1,
name: 'sweep',
prompt: 'fix the bug',
models: ['openai/gpt-5', 'anthropic/claude'],
isolate: true,
baseRef: 'main',
})
expect(fake.toast).toHaveBeenCalledWith({ variant: 'success', message: 'Launched sweep: 2/2 started' })
expect(fake.open).toHaveBeenNthCalledWith(1, 'ses_1')
expect(fake.open).toHaveBeenNthCalledWith(2, 'ses_2')
expect(fake.focus).toHaveBeenCalledWith('ses_1')
})
it('defaults the name to the first 80 characters of the prompt first line', async () => {
const fake = createFakeContext()
const api = makeApi()
fake.list.mockReturnValue([model()])
fake.prompt.mockResolvedValueOnce('name').mockResolvedValueOnce(undefined)
fake.select.mockResolvedValueOnce(0).mockResolvedValueOnce(-1).mockResolvedValueOnce(false)
const longFirstLine = 'a'.repeat(100)
await runMultiRunCommand(fake.context, depsFor(api), `/multirun ${longFirstLine}\nsecond line`)
expect(fake.prompt).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ value: 'a'.repeat(80) }),
)
})
it('omits the base ref when isolation is off', async () => {
const fake = createFakeContext()
const api = makeApi()
fake.list.mockReturnValue([model()])
fake.prompt.mockResolvedValueOnce('sweep')
fake.select.mockResolvedValueOnce(0).mockResolvedValueOnce(-1).mockResolvedValueOnce(false)
await runMultiRunCommand(fake.context, depsFor(api), '/multirun fix it')
expect(api.launchMultiRun).toHaveBeenCalledWith({
repoId: 1,
name: 'sweep',
prompt: 'fix it',
models: ['openai/gpt-5'],
isolate: false,
})
expect(fake.prompt).toHaveBeenCalledTimes(1)
})
it('omits the base ref when the base ref prompt is left blank', async () => {
const fake = createFakeContext()
const api = makeApi()
fake.list.mockReturnValue([model()])
fake.prompt.mockResolvedValueOnce('sweep').mockResolvedValueOnce(undefined)
fake.select.mockResolvedValueOnce(0).mockResolvedValueOnce(-1).mockResolvedValueOnce(true)
await runMultiRunCommand(fake.context, depsFor(api), '/multirun fix it')
expect(api.launchMultiRun).toHaveBeenCalledWith({
repoId: 1,
name: 'sweep',
prompt: 'fix it',
models: ['openai/gpt-5'],
isolate: true,
})
})
it('reports failed entries with a warning toast', async () => {
const fake = createFakeContext()
const api = makeApi()
api.launchMultiRun.mockResolvedValue(
multiRun({
name: 'sweep',
entries: [
entry({ id: 1, model: 'openai/gpt-5', sessionId: 'ses_1' }),
entry({ id: 2, model: 'anthropic/claude', status: 'failed', sessionId: null, error: 'model unavailable' }),
],
}),
)
fake.list.mockReturnValue([model()])
fake.prompt.mockResolvedValueOnce('sweep').mockResolvedValueOnce(undefined)
fake.select.mockResolvedValueOnce(0).mockResolvedValueOnce(-1).mockResolvedValueOnce(true)
await runMultiRunCommand(fake.context, depsFor(api), '/multirun fix it')
expect(fake.toast).toHaveBeenCalledWith({
variant: 'warning',
message: 'Launched sweep: 1/2 started\nanthropic/claude: model unavailable',
})
expect(fake.open).toHaveBeenCalledTimes(1)
expect(fake.open).toHaveBeenCalledWith('ses_1')
})
it('does not call the API when the name dialog is dismissed', async () => {
const fake = createFakeContext()
const api = makeApi()
fake.prompt.mockResolvedValueOnce(undefined)
await runMultiRunCommand(fake.context, depsFor(api), '/multirun fix it')
expect(api.launchMultiRun).not.toHaveBeenCalled()
})
it('does not call the API when the model dialog is dismissed', async () => {
const fake = createFakeContext()
const api = makeApi()
fake.list.mockReturnValue([model()])
fake.prompt.mockResolvedValueOnce('sweep')
fake.select.mockResolvedValueOnce(undefined)
await runMultiRunCommand(fake.context, depsFor(api), '/multirun fix it')
expect(api.launchMultiRun).not.toHaveBeenCalled()
})
it('does not call the API when the isolation dialog is dismissed', async () => {
const fake = createFakeContext()
const api = makeApi()
fake.list.mockReturnValue([model()])
fake.prompt.mockResolvedValueOnce('sweep')
fake.select.mockResolvedValueOnce(0).mockResolvedValueOnce(-1).mockResolvedValueOnce(undefined)
await runMultiRunCommand(fake.context, depsFor(api), '/multirun fix it')
expect(api.launchMultiRun).not.toHaveBeenCalled()
})
it('asks for the prompt when the command has none', async () => {
const fake = createFakeContext()
const api = makeApi()
fake.list.mockReturnValue([model()])
fake.prompt.mockResolvedValueOnce('from dialog').mockResolvedValueOnce('sweep').mockResolvedValueOnce(undefined)
fake.select.mockResolvedValueOnce(0).mockResolvedValueOnce(-1).mockResolvedValueOnce(true)
await runMultiRunCommand(fake.context, depsFor(api), '/multirun')
expect(fake.prompt).toHaveBeenNthCalledWith(1, expect.objectContaining({ title: 'Multi-run prompt' }))
expect(api.launchMultiRun).toHaveBeenCalledWith(expect.objectContaining({ prompt: 'from dialog' }))
})
it('does nothing when the prompt dialog is dismissed', async () => {
const fake = createFakeContext()
const api = makeApi()
fake.prompt.mockResolvedValueOnce(undefined)
await runMultiRunCommand(fake.context, depsFor(api), '/multirun')
expect(api.launchMultiRun).not.toHaveBeenCalled()
})
it('reports an auth failure without calling the API', async () => {
const fake = createFakeContext()
const api = makeApi()
vi.mocked(resolveManagerAuth).mockResolvedValue({ ok: false, message: 'No token stored.' })
await runMultiRunCommand(fake.context, depsFor(api), '/multirun fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'No token stored.' })
expect(api.launchMultiRun).not.toHaveBeenCalled()
})
it('reports a Manager API error message', async () => {
const fake = createFakeContext()
const api = makeApi()
api.launchMultiRun.mockRejectedValue(new ManagerApiError('launch failed', 500, 'boom', 'launch multi-run'))
fake.list.mockReturnValue([model()])
fake.prompt.mockResolvedValueOnce('sweep').mockResolvedValueOnce(undefined)
fake.select.mockResolvedValueOnce(0).mockResolvedValueOnce(-1).mockResolvedValueOnce(true)
await runMultiRunCommand(fake.context, depsFor(api), '/multirun fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'launch failed' })
})
it('reports an outdated Manager when the multi-run route is missing', async () => {
const fake = createFakeContext()
const api = makeApi()
api.launchMultiRun.mockRejectedValue(new ManagerApiError('not found', 404, null, 'launch multi-run'))
fake.list.mockReturnValue([model()])
fake.prompt.mockResolvedValueOnce('sweep').mockResolvedValueOnce(undefined)
fake.select.mockResolvedValueOnce(0).mockResolvedValueOnce(-1).mockResolvedValueOnce(true)
await runMultiRunCommand(fake.context, depsFor(api), '/multirun fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: MULTI_RUN_ROUTE_MISSING })
})
})
+13
View File
@@ -230,6 +230,19 @@ describe('setupOcm', () => {
const goal = factory().commands.find((entry) => entry.id === 'ocm.goal')
expect(goal?.slash).toEqual({ name: 'goal', arguments: true })
})
it('exposes the multi-run slash command', async () => {
const fake = createFakeContext()
await setupOcm(fake.context, vi.fn(), noFeatures)
renderAppSlot(fake)
const factory = fake.layer.mock.calls[0]![0] as () => {
commands: { id: string; slash?: { name: string; arguments?: true } }[]
}
const multiRun = factory().commands.find((entry) => entry.id === 'ocm.multirun')
expect(multiRun?.slash).toEqual({ name: 'multirun', arguments: true })
})
})
describe('ocm.session.move command', () => {