From 891f5427b4e75ffca8ce0324865a353175a57220 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 10:55:25 -0400 Subject: [PATCH] section 12: Phase 12: Multi-run backend: run groups, parallel launch and --- backend/src/db/migrations/027-multi-runs.ts | 16 + backend/src/db/migrations/index.ts | 2 + backend/src/db/multi-runs.ts | 244 ++++++++++ backend/src/index.ts | 5 + backend/src/routes/multi-runs.ts | 51 ++ backend/src/services/multi-runs.ts | 199 ++++++++ backend/src/services/session-launcher.ts | 7 +- backend/test/routes/multi-runs.test.ts | 136 ++++++ backend/test/services/multi-runs.test.ts | 453 ++++++++++++++++++ .../test/services/session-launcher.test.ts | 40 +- shared/src/schemas/index.ts | 1 + shared/src/schemas/multi-runs.ts | 50 ++ 12 files changed, 1201 insertions(+), 3 deletions(-) create mode 100644 backend/src/db/migrations/027-multi-runs.ts create mode 100644 backend/src/db/multi-runs.ts create mode 100644 backend/src/routes/multi-runs.ts create mode 100644 backend/src/services/multi-runs.ts create mode 100644 backend/test/routes/multi-runs.test.ts create mode 100644 backend/test/services/multi-runs.test.ts create mode 100644 shared/src/schemas/multi-runs.ts diff --git a/backend/src/db/migrations/027-multi-runs.ts b/backend/src/db/migrations/027-multi-runs.ts new file mode 100644 index 00000000..c97f6958 --- /dev/null +++ b/backend/src/db/migrations/027-multi-runs.ts @@ -0,0 +1,16 @@ +import type { Migration } from '../migration-runner' +import { ensureMultiRunTables } from '../multi-runs' + +const migration: Migration = { + version: 27, + name: 'multi-runs', + up(db) { + ensureMultiRunTables(db) + }, + down(db) { + db.run('DROP TABLE IF EXISTS multi_run_entries') + db.run('DROP TABLE IF EXISTS multi_runs') + }, +} + +export default migration diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts index db2c76c7..3fbc66f0 100644 --- a/backend/src/db/migrations/index.ts +++ b/backend/src/db/migrations/index.ts @@ -25,6 +25,7 @@ import migration023 from './023-schedule-mcp-servers' import migration024 from './024-schedule-runs-viewed-at' import migration025 from './025-session-permission-modes' import migration026 from './026-session-goals' +import migration027 from './027-multi-runs' export const allMigrations: Migration[] = [ migration001, @@ -53,4 +54,5 @@ export const allMigrations: Migration[] = [ migration024, migration025, migration026, + migration027, ] diff --git a/backend/src/db/multi-runs.ts b/backend/src/db/multi-runs.ts new file mode 100644 index 00000000..209d4e99 --- /dev/null +++ b/backend/src/db/multi-runs.ts @@ -0,0 +1,244 @@ +import type { Database } from 'bun:sqlite' +import type { MultiRunEntryStatus } from '@opencode-manager/shared/schemas' + +export interface MultiRunEntryRecord { + id: number + multiRunId: number + model: string + status: MultiRunEntryStatus + sessionId: string | null + directory: string | null + isolated: boolean + error: string | null + createdAt: number + updatedAt: number +} + +export interface MultiRunRecord { + id: number + repoId: number + name: string + prompt: string + isolated: boolean + baseRef: string | null + createdAt: number + entries: MultiRunEntryRecord[] +} + +export interface CreateMultiRunGroup { + repoId: number + name: string + prompt: string + isolated: boolean + baseRef: string | null +} + +export interface MultiRunEntryPatch { + status?: MultiRunEntryStatus + sessionId?: string | null + directory?: string | null + error?: string | null +} + +interface MultiRunRow { + id: number + repo_id: number + name: string + prompt: string + isolated: number + base_ref: string | null + created_at: number +} + +interface MultiRunEntryRow { + id: number + multi_run_id: number + model: string + status: MultiRunEntryStatus + session_id: string | null + directory: string | null + error: string | null + created_at: number + updated_at: number +} + +const MULTI_RUN_COLUMNS = 'id, repo_id, name, prompt, isolated, base_ref, created_at' + +const MULTI_RUN_ENTRY_COLUMNS = 'id, multi_run_id, model, status, session_id, directory, error, created_at, updated_at' + +export function ensureMultiRunTables(db: Database): void { + db.run(` + CREATE TABLE IF NOT EXISTS multi_runs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + repo_id INTEGER NOT NULL, + name TEXT NOT NULL, + prompt TEXT NOT NULL, + isolated INTEGER NOT NULL, + base_ref TEXT, + created_at INTEGER NOT NULL + ) + `) + db.run(` + CREATE TABLE IF NOT EXISTS multi_run_entries ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + multi_run_id INTEGER NOT NULL, + model TEXT NOT NULL, + status TEXT NOT NULL CHECK(status IN ('starting','started','failed','discarded')), + session_id TEXT, + directory TEXT, + error TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ) + `) + db.run(` + CREATE INDEX IF NOT EXISTS idx_multi_run_entries_group + ON multi_run_entries(multi_run_id) + `) + db.run(` + CREATE INDEX IF NOT EXISTS idx_multi_runs_repo + ON multi_runs(repo_id, created_at DESC) + `) +} + +export function createMultiRunWithEntries( + db: Database, + group: CreateMultiRunGroup, + models: string[], +): MultiRunRecord { + const now = Date.now() + const create = db.transaction(() => { + const result = db + .prepare(`INSERT INTO multi_runs(repo_id, name, prompt, isolated, base_ref, created_at) VALUES(?,?,?,?,?,?)`) + .run(group.repoId, group.name, group.prompt, group.isolated ? 1 : 0, group.baseRef, now) + const multiRunId = Number(result.lastInsertRowid) + + const insertEntry = db.prepare(` + INSERT INTO multi_run_entries(multi_run_id, model, status, session_id, directory, error, created_at, updated_at) + VALUES(?,?,?,?,?,?,?,?) + `) + for (const model of models) { + insertEntry.run(multiRunId, model, 'starting', null, null, null, now, now) + } + + return multiRunId + }) + + const record = getMultiRun(db, create()) + if (!record) { + throw new Error('Failed to create multi-run') + } + return record +} + +export function getMultiRun(db: Database, id: number): MultiRunRecord | null { + const row = db + .prepare(`SELECT ${MULTI_RUN_COLUMNS} FROM multi_runs WHERE id = ?`) + .get(id) as MultiRunRow | undefined + if (!row) { + return null + } + return mapMultiRunRow(db, row) +} + +export function listMultiRuns(db: Database, repoId: number, limit: number): MultiRunRecord[] { + const rows = db + .prepare(` + SELECT ${MULTI_RUN_COLUMNS} FROM multi_runs + WHERE repo_id = ? + ORDER BY created_at DESC, id DESC + LIMIT ? + `) + .all(repoId, limit) as MultiRunRow[] + return rows.map((row) => mapMultiRunRow(db, row)) +} + +export function getMultiRunEntry(db: Database, multiRunId: number, entryId: number): MultiRunEntryRecord | null { + const row = db + .prepare(`SELECT ${MULTI_RUN_ENTRY_COLUMNS} FROM multi_run_entries WHERE id = ? AND multi_run_id = ?`) + .get(entryId, multiRunId) as MultiRunEntryRow | undefined + if (!row) { + return null + } + + const group = db.prepare('SELECT isolated FROM multi_runs WHERE id = ?').get(multiRunId) as + | { isolated: number } + | undefined + return mapEntryRow(row, group?.isolated === 1) +} + +export function updateMultiRunEntry( + db: Database, + entryId: number, + fromStatuses: MultiRunEntryStatus[], + patch: MultiRunEntryPatch, +): MultiRunEntryRecord | null { + const assignments: string[] = ['updated_at = ?'] + const values: (string | number | null)[] = [Date.now()] + + if (patch.status !== undefined) { + assignments.push('status = ?') + values.push(patch.status) + } + if (patch.sessionId !== undefined) { + assignments.push('session_id = ?') + values.push(patch.sessionId) + } + if (patch.directory !== undefined) { + assignments.push('directory = ?') + values.push(patch.directory) + } + if (patch.error !== undefined) { + assignments.push('error = ?') + values.push(patch.error) + } + + const placeholders = fromStatuses.map(() => '?').join(', ') + const result = db + .prepare(`UPDATE multi_run_entries SET ${assignments.join(', ')} WHERE id = ? AND status IN (${placeholders})`) + .run(...values, entryId, ...fromStatuses) + + if (result.changes === 0) { + return null + } + + const row = db.prepare('SELECT multi_run_id FROM multi_run_entries WHERE id = ?').get(entryId) as + | { multi_run_id: number } + | undefined + if (!row) { + return null + } + return getMultiRunEntry(db, row.multi_run_id, entryId) +} + +function mapMultiRunRow(db: Database, row: MultiRunRow): MultiRunRecord { + const entries = db + .prepare(`SELECT ${MULTI_RUN_ENTRY_COLUMNS} FROM multi_run_entries WHERE multi_run_id = ? ORDER BY id ASC`) + .all(row.id) as MultiRunEntryRow[] + + return { + id: row.id, + repoId: row.repo_id, + name: row.name, + prompt: row.prompt, + isolated: row.isolated === 1, + baseRef: row.base_ref, + createdAt: row.created_at, + entries: entries.map((entry) => mapEntryRow(entry, row.isolated === 1)), + } +} + +function mapEntryRow(row: MultiRunEntryRow, isolated: boolean): MultiRunEntryRecord { + return { + id: row.id, + multiRunId: row.multi_run_id, + model: row.model, + status: row.status, + sessionId: row.session_id, + directory: row.directory, + isolated, + error: row.error, + createdAt: row.created_at, + updatedAt: row.updated_at, + } +} diff --git a/backend/src/index.ts b/backend/src/index.ts index f33e8a8a..86fd2f1b 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -38,6 +38,7 @@ import { createPromptTemplateRoutes } from './routes/prompt-templates' import { createSessionPinRoutes } from './routes/session-pins' import { createSessionPermissionModeRoutes } from './routes/session-permission-modes' import { createSessionGoalRoutes } from './routes/session-goals' +import { createMultiRunRoutes } from './routes/multi-runs' import { createLogRoutes } from './routes/logs' import { createInternalRoutes } from './routes/internal' import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers' @@ -48,6 +49,7 @@ import { ensureDirectoryExists, writeFileContent, fileExists } from './services/ import { SettingsService } from './services/settings' import { SessionPermissionModeService } from './services/session-permission-modes' import { SessionGoalService } from './services/session-goals' +import { MultiRunService } from './services/multi-runs' import { opencodeServerManager } from './services/opencode-single-server' import { createOpenCodeClient } from './services/opencode/client' import { NotificationService } from './services/notification' @@ -241,6 +243,8 @@ const sessionGoalService = new SessionGoalService(db, openCodeClient, settingsSe }) sessionGoalService.loadOpenGoals() +const multiRunService = new MultiRunService(db, openCodeClient, gitAuthService) + sseAggregator.onEvent((directory, event) => { sessionPermissionModeService.handleEvent(directory, event).catch((err) => { logger.error('Session permission mode event handling error:', err) @@ -321,6 +325,7 @@ protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db)) protectedApi.route('/session-pins', createSessionPinRoutes(db)) protectedApi.route('/session-permission-modes', createSessionPermissionModeRoutes(sessionPermissionModeService)) protectedApi.route('/session-goals', createSessionGoalRoutes(sessionGoalService)) +protectedApi.route('/multi-runs', createMultiRunRoutes(multiRunService)) protectedApi.route('/schedules', createScheduleRoutes(scheduleService)) protectedApi.route('/logs', createLogRoutes()) diff --git a/backend/src/routes/multi-runs.ts b/backend/src/routes/multi-runs.ts new file mode 100644 index 00000000..315453b4 --- /dev/null +++ b/backend/src/routes/multi-runs.ts @@ -0,0 +1,51 @@ +import { Hono } from 'hono' +import { LaunchMultiRunRequestSchema } from '@opencode-manager/shared/schemas' +import { MultiRunError, type MultiRunService } from '../services/multi-runs' +import { handleServiceError, parseId } from '../utils/route-helpers' + +export function createMultiRunRoutes(service: MultiRunService) { + const app = new Hono() + + app.get('/', (c) => { + try { + const repoId = parseId(c.req.query('repoId'), 'repoId', MultiRunError) + return c.json({ runs: service.list(repoId) }) + } catch (error) { + return handleServiceError(c, error, 'Failed to list multi-runs', MultiRunError) + } + }) + + app.post('/', async (c) => { + let body: unknown + try { + body = await c.req.json() + } catch { + return c.json({ error: 'Invalid request' }, 400) + } + + const parsed = LaunchMultiRunRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request' }, 400) + } + + try { + const run = await service.launch(parsed.data) + return c.json({ run }, 201) + } catch (error) { + return handleServiceError(c, error, 'Failed to launch multi-run', MultiRunError) + } + }) + + app.post('/:id/entries/:entryId/discard', async (c) => { + try { + const multiRunId = parseId(c.req.param('id'), 'multi-run id', MultiRunError) + const entryId = parseId(c.req.param('entryId'), 'entry id', MultiRunError) + const run = await service.discard(multiRunId, entryId) + return c.json({ run }) + } catch (error) { + return handleServiceError(c, error, 'Failed to discard multi-run entry', MultiRunError) + } + }) + + return app +} diff --git a/backend/src/services/multi-runs.ts b/backend/src/services/multi-runs.ts new file mode 100644 index 00000000..27da501c --- /dev/null +++ b/backend/src/services/multi-runs.ts @@ -0,0 +1,199 @@ +import type { Database } from 'bun:sqlite' +import type { LaunchMultiRunRequest, MultiRun } from '@opencode-manager/shared/schemas' +import { sanitizeRepoDirectoryName } from '@opencode-manager/shared/utils' +import { + createMultiRunWithEntries, + getMultiRun, + getMultiRunEntry, + listMultiRuns, + updateMultiRunEntry, + type MultiRunEntryRecord, + type MultiRunRecord, +} from '../db/multi-runs' +import { getRepoById } from '../db/queries' +import { getErrorMessage } from '../utils/error-utils' +import type { GitAuthService } from './git-auth' +import type { OpenCodeClient } from './opencode/client' +import { removeRepoWorkspace } from './repo' +import { SessionLauncher, SessionLaunchError, type LaunchedSession } from './session-launcher' + +const MULTI_RUN_LIST_LIMIT = 20 + +export class MultiRunError extends Error { + status: number + + constructor(message: string, status: number) { + super(message) + this.name = 'MultiRunError' + this.status = status + } +} + +export function toMultiRun(record: MultiRunRecord): MultiRun { + return { + id: record.id, + repoId: record.repoId, + name: record.name, + prompt: record.prompt, + isolated: record.isolated, + baseRef: record.baseRef, + createdAt: record.createdAt, + entries: record.entries.map((entry) => ({ + id: entry.id, + model: entry.model, + status: entry.status, + sessionId: entry.sessionId, + directory: entry.directory, + isolated: entry.isolated, + error: entry.error, + createdAt: entry.createdAt, + updatedAt: entry.updatedAt, + })), + } +} + +export class MultiRunService { + private readonly sessionLauncher: SessionLauncher + private readonly discardingEntries = new Set() + + constructor( + private readonly db: Database, + private readonly openCodeClient: OpenCodeClient, + private readonly gitAuthService: GitAuthService, + ) { + this.sessionLauncher = new SessionLauncher(db, openCodeClient) + } + + async launch(request: LaunchMultiRunRequest): Promise { + const repo = getRepoById(this.db, request.repoId) + if (!repo || repo.cloneStatus !== 'ready') { + throw new MultiRunError('Repository not found or not ready', 404) + } + + const record = createMultiRunWithEntries( + this.db, + { + repoId: request.repoId, + name: request.name, + prompt: request.prompt, + isolated: request.isolate, + baseRef: request.baseRef ?? null, + }, + request.models, + ) + + const slug = sanitizeRepoDirectoryName(request.name) + const results = await Promise.allSettled( + record.entries.map((entry, index) => this.launchEntry(entry, index, request, slug)), + ) + + results.forEach((result, index) => { + const entry = record.entries[index] + if (!entry) { + return + } + if (result.status === 'fulfilled') { + updateMultiRunEntry(this.db, entry.id, ['starting'], { + status: 'started', + sessionId: result.value.sessionId, + directory: result.value.directory, + }) + return + } + + const workspaceDirectory = + result.reason instanceof SessionLaunchError ? result.reason.workspaceDirectory : null + updateMultiRunEntry(this.db, entry.id, ['starting'], { + status: 'failed', + error: getErrorMessage(result.reason) || 'Failed to launch session', + ...(workspaceDirectory ? { directory: workspaceDirectory } : {}), + }) + }) + + return this.reload(record.id) + } + + list(repoId: number): MultiRun[] { + return listMultiRuns(this.db, repoId, MULTI_RUN_LIST_LIMIT).map(toMultiRun) + } + + async discard(multiRunId: number, entryId: number): Promise { + const record = getMultiRun(this.db, multiRunId) + if (!record) { + throw new MultiRunError('Multi-run not found', 404) + } + + const entry = getMultiRunEntry(this.db, multiRunId, entryId) + if (!entry) { + throw new MultiRunError('Multi-run entry not found', 404) + } + + if (entry.status !== 'started' && entry.status !== 'failed') { + throw new MultiRunError('Multi-run entry cannot be discarded from its current state', 409) + } + + if (this.discardingEntries.has(entryId)) { + throw new MultiRunError('Multi-run entry discard already in progress', 409) + } + this.discardingEntries.add(entryId) + + try { + if (entry.isolated && entry.directory) { + const repo = getRepoById(this.db, record.repoId) + if (!repo) { + throw new MultiRunError('Repository not found', 404) + } + + try { + await removeRepoWorkspace( + this.db, + this.openCodeClient, + this.gitAuthService.getGitEnvironment(), + repo, + entry.directory, + ) + } catch (error) { + const status = typeof (error as { status?: unknown }).status === 'number' + ? (error as { status: number }).status + : 502 + throw new MultiRunError(getErrorMessage(error) || 'Failed to remove workspace', status) + } + } + + const updated = updateMultiRunEntry(this.db, entryId, ['started', 'failed'], { status: 'discarded' }) + if (!updated) { + throw new MultiRunError('Multi-run entry cannot be discarded from its current state', 409) + } + + return this.reload(multiRunId) + } finally { + this.discardingEntries.delete(entryId) + } + } + + private async launchEntry( + entry: MultiRunEntryRecord, + index: number, + request: LaunchMultiRunRequest, + slug: string, + ): Promise { + return this.sessionLauncher.launch({ + repoId: request.repoId, + prompt: request.prompt, + model: entry.model, + title: `${request.name} ยท ${entry.model}`, + ...(request.agent ? { agent: request.agent } : {}), + ...(request.isolate + ? { workspace: { name: `${slug}-${index + 1}`, ...(request.baseRef ? { ref: request.baseRef } : {}) } } + : {}), + }) + } + + private reload(multiRunId: number): MultiRun { + const record = getMultiRun(this.db, multiRunId) + if (!record) { + throw new MultiRunError('Multi-run not found', 404) + } + return toMultiRun(record) + } +} diff --git a/backend/src/services/session-launcher.ts b/backend/src/services/session-launcher.ts index 46763c07..90b3f433 100644 --- a/backend/src/services/session-launcher.ts +++ b/backend/src/services/session-launcher.ts @@ -26,11 +26,13 @@ export interface LaunchedSession { export class SessionLaunchError extends Error { readonly status: 400 | 404 | 502 + readonly workspaceDirectory: string | null - constructor(message: string, status: 400 | 404 | 502) { + constructor(message: string, status: 400 | 404 | 502, workspaceDirectory: string | null = null) { super(message) this.name = 'SessionLaunchError' this.status = status + this.workspaceDirectory = workspaceDirectory } } @@ -83,6 +85,7 @@ export class SessionLauncher { throw new SessionLaunchError( withWorkspace(getErrorMessage(error) || 'Failed to create OpenCode session', workspaceDirectory), 502, + workspaceDirectory, ) } @@ -110,6 +113,7 @@ export class SessionLauncher { throw new SessionLaunchError( withWorkspace(getErrorMessage(error) || 'Failed to resolve OpenCode model', workspaceDirectory), 502, + workspaceDirectory, ) } @@ -119,6 +123,7 @@ export class SessionLauncher { throw new SessionLaunchError( withWorkspace(`Model ${requestedModel} is not available`, workspaceDirectory), 400, + workspaceDirectory, ) } } diff --git a/backend/test/routes/multi-runs.test.ts b/backend/test/routes/multi-runs.test.ts new file mode 100644 index 00000000..41c7607c --- /dev/null +++ b/backend/test/routes/multi-runs.test.ts @@ -0,0 +1,136 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { Hono } from 'hono' +import type { MultiRun } from '@opencode-manager/shared/schemas' +import { createMultiRunRoutes } from '../../src/routes/multi-runs' +import { MultiRunError, type MultiRunService } from '../../src/services/multi-runs' + +function createRun(overrides: Partial = {}): MultiRun { + return { + id: 1, + repoId: 1, + name: 'Sweep', + prompt: 'go', + isolated: true, + baseRef: null, + createdAt: 1, + entries: [], + ...overrides, + } +} + +function launchBody(overrides: Record = {}): string { + return JSON.stringify({ + repoId: 1, + name: 'Sweep', + prompt: 'go', + models: ['openai/a'], + isolate: true, + ...overrides, + }) +} + +describe('multi-run routes', () => { + let service: { + list: ReturnType + launch: ReturnType + discard: ReturnType + } + let app: Hono + + beforeEach(() => { + service = { list: vi.fn(), launch: vi.fn(), discard: vi.fn() } + app = new Hono() + app.route('/multi-runs', createMultiRunRoutes(service as unknown as MultiRunService)) + }) + + it('GET returns the repository runs', async () => { + service.list.mockReturnValue([createRun()]) + + const res = await app.request('/multi-runs?repoId=1') + + expect(res.status).toBe(200) + await expect(res.json()).resolves.toEqual({ runs: [createRun()] }) + expect(service.list).toHaveBeenCalledWith(1) + }) + + it('GET rejects a missing repoId with 400', async () => { + const res = await app.request('/multi-runs') + + expect(res.status).toBe(400) + expect(service.list).not.toHaveBeenCalled() + }) + + it('POST launches a run and returns 201', async () => { + service.launch.mockResolvedValue(createRun()) + + const res = await app.request('/multi-runs', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: launchBody(), + }) + + expect(res.status).toBe(201) + await expect(res.json()).resolves.toEqual({ run: createRun() }) + expect(service.launch).toHaveBeenCalledWith({ + repoId: 1, + name: 'Sweep', + prompt: 'go', + models: ['openai/a'], + isolate: true, + }) + }) + + it('POST rejects more than five models with 400', async () => { + const res = await app.request('/multi-runs', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: launchBody({ + models: ['openai/a', 'openai/b', 'openai/c', 'openai/d', 'openai/e', 'openai/f'], + }), + }) + + expect(res.status).toBe(400) + expect(service.launch).not.toHaveBeenCalled() + }) + + it('POST rejects duplicate models with 400', async () => { + const res = await app.request('/multi-runs', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: launchBody({ models: ['openai/a', 'openai/a'] }), + }) + + expect(res.status).toBe(400) + expect(service.launch).not.toHaveBeenCalled() + }) + + it('POST maps a service error to its status', async () => { + service.launch.mockRejectedValue(new MultiRunError('Repository not found or not ready', 404)) + + const res = await app.request('/multi-runs', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: launchBody(), + }) + + expect(res.status).toBe(404) + }) + + it('POST discard calls the service with numeric ids', async () => { + service.discard.mockResolvedValue(createRun()) + + const res = await app.request('/multi-runs/3/entries/7/discard', { method: 'POST' }) + + expect(res.status).toBe(200) + await expect(res.json()).resolves.toEqual({ run: createRun() }) + expect(service.discard).toHaveBeenCalledWith(3, 7) + }) + + it('POST discard maps a missing entry to 404', async () => { + service.discard.mockRejectedValue(new MultiRunError('Multi-run entry not found', 404)) + + const res = await app.request('/multi-runs/3/entries/7/discard', { method: 'POST' }) + + expect(res.status).toBe(404) + }) +}) diff --git a/backend/test/services/multi-runs.test.ts b/backend/test/services/multi-runs.test.ts new file mode 100644 index 00000000..8a95616c --- /dev/null +++ b/backend/test/services/multi-runs.test.ts @@ -0,0 +1,453 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { Database } from 'bun:sqlite' +import { createRepo } 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 { MultiRunError, MultiRunService } from '../../src/services/multi-runs' +import type { GitAuthService } from '../../src/services/git-auth' +import type { OpenCodeClient } from '../../src/services/opencode/client' + +const REPO_DIR = '/repos/repo-a' + +const mocks = vi.hoisted(() => ({ + resolveOpenCodeModel: vi.fn(), + resolveProjectId: vi.fn(), + isGitMainCheckout: vi.fn(), + executeCommand: vi.fn(), +})) + +vi.mock('../../src/services/opencode-models', () => ({ + resolveOpenCodeModel: mocks.resolveOpenCodeModel, +})) + +vi.mock('../../src/services/project-id-resolver', () => ({ + resolveProjectId: mocks.resolveProjectId, + isGitMainCheckout: mocks.isGitMainCheckout, +})) + +vi.mock('../../src/utils/process', () => ({ + executeCommand: mocks.executeCommand, +})) + +interface FakeMultiRunClient { + client: OpenCodeClient + sessionCreate: ReturnType + sessionPrompt: ReturnType + worktreeCreate: ReturnType + worktreeList: ReturnType + worktreeRemove: ReturnType + workspaces: Array<{ directory: string; strategy: string }> +} + +function createClient(): FakeMultiRunClient { + let sessionCounter = 0 + const workspaces: Array<{ directory: string; strategy: string }> = [] + + const sessionCreate = vi.fn(async (input: { title?: string }) => { + sessionCounter += 1 + return { id: `ses_${sessionCounter}`, title: input?.title } + }) + const sessionPrompt = vi.fn(async () => ({})) + const worktreeCreate = vi.fn(async (input: { name?: string }) => { + const directory = `/worktrees/${input.name ?? 'workspace'}` + workspaces.push({ directory, strategy: 'git' }) + return { directory } + }) + const worktreeList = vi.fn(async () => workspaces) + const worktreeRemove = vi.fn(async () => undefined) + + const client = { + api: { + location: { + get: vi.fn(async () => ({ project: { id: 'commit-A', directory: REPO_DIR, canonical: REPO_DIR } })), + }, + worktree: { create: worktreeCreate, list: worktreeList, remove: worktreeRemove }, + session: { create: sessionCreate, prompt: sessionPrompt }, + }, + } as unknown as OpenCodeClient + + return { client, sessionCreate, sessionPrompt, worktreeCreate, worktreeList, worktreeRemove, workspaces } +} + +describe('MultiRunService', () => { + let db: Database + + beforeEach(() => { + vi.clearAllMocks() + db = new Database(':memory:') + migrate(db, allMigrations) + + mocks.resolveOpenCodeModel.mockImplementation( + async (_client: unknown, _directory: string, options: { preferredModel?: string }) => { + const preferred = options?.preferredModel + if (!preferred) { + return { providerID: 'openai', id: 'gpt-5', model: 'openai/gpt-5' } + } + if (preferred === 'openai/retired') { + return { providerID: 'openai', id: 'retired-x', model: 'openai/retired-x' } + } + const [providerID, ...rest] = preferred.split('/') + return { providerID, id: rest.join('/'), model: preferred } + }, + ) + mocks.resolveProjectId.mockResolvedValue('commit-A') + mocks.isGitMainCheckout.mockResolvedValue(false) + mocks.executeCommand.mockResolvedValue('') + }) + + afterEach(() => { + db.close() + }) + + function readyRepo(): number { + const repo = createRepo(db, { + localPath: 'repo-a', + sourcePath: REPO_DIR, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + }) + return repo.id + } + + function createService(client: OpenCodeClient): MultiRunService { + const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService + return new MultiRunService(db, client, gitAuthService) + } + + it('launches one session per model, each in its own workspace named from the group', async () => { + const repoId = readyRepo() + const { client, sessionCreate, sessionPrompt, worktreeCreate } = createClient() + const service = createService(client) + + const run = await service.launch({ + repoId, + name: 'Feature Sweep', + prompt: 'do the thing', + models: ['openai/a', 'openai/b', 'openai/c'], + isolate: true, + baseRef: 'develop', + }) + + expect(run).toMatchObject({ + repoId, + name: 'Feature Sweep', + prompt: 'do the thing', + isolated: true, + baseRef: 'develop', + }) + expect(run.entries.map((entry) => entry.model)).toEqual(['openai/a', 'openai/b', 'openai/c']) + expect(run.entries.map((entry) => entry.status)).toEqual(['started', 'started', 'started']) + expect(run.entries.map((entry) => entry.isolated)).toEqual([true, true, true]) + expect(run.entries.map((entry) => entry.directory)).toEqual([ + '/worktrees/Feature-Sweep-1', + '/worktrees/Feature-Sweep-2', + '/worktrees/Feature-Sweep-3', + ]) + expect(new Set(run.entries.map((entry) => entry.sessionId)).size).toBe(3) + + expect(sessionCreate).toHaveBeenCalledTimes(3) + expect(sessionPrompt).toHaveBeenCalledTimes(3) + expect(sessionPrompt.mock.calls.every((call) => call[0].text === 'do the thing')).toBe(true) + expect( + sessionCreate.mock.calls.map((call) => `${call[0].model.providerID}/${call[0].model.id}`).sort(), + ).toEqual(['openai/a', 'openai/b', 'openai/c']) + + const workspaceCalls = worktreeCreate.mock.calls.map((call) => call[0]) + expect(workspaceCalls.map((call) => call.name).sort()).toEqual([ + 'Feature-Sweep-1', + 'Feature-Sweep-2', + 'Feature-Sweep-3', + ]) + expect(workspaceCalls.every((call) => call.branch === 'develop')).toBe(true) + }) + + it('keeps launching the other models when one model fails', async () => { + const repoId = readyRepo() + const { client, worktreeCreate } = createClient() + const service = createService(client) + + const run = await service.launch({ + repoId, + name: 'Sweep', + prompt: 'go', + models: ['openai/a', 'openai/retired', 'openai/c'], + isolate: false, + }) + + expect(run.entries.map((entry) => entry.status)).toEqual(['started', 'failed', 'started']) + expect(run.entries[1]!.error).toBe('Model openai/retired is not available') + expect(run.entries[1]!.sessionId).toBeNull() + expect(run.entries[0]!.sessionId).toBeTruthy() + expect(run.entries[2]!.sessionId).toBeTruthy() + expect(worktreeCreate).not.toHaveBeenCalled() + }) + + it('does not create workspaces when isolation is off', async () => { + const repoId = readyRepo() + const { client, worktreeCreate } = createClient() + const service = createService(client) + + const run = await service.launch({ + repoId, + name: 'Sweep', + prompt: 'go', + models: ['openai/a', 'openai/b'], + isolate: false, + }) + + expect(run.entries.map((entry) => entry.status)).toEqual(['started', 'started']) + expect(run.entries.every((entry) => entry.directory === REPO_DIR)).toBe(true) + expect(run.entries.every((entry) => entry.isolated === false)).toBe(true) + expect(worktreeCreate).not.toHaveBeenCalled() + }) + + it('rejects a repository that is not ready', async () => { + const { client } = createClient() + const service = createService(client) + + const error = await service + .launch({ repoId: 999, name: 'Sweep', prompt: 'go', models: ['openai/a'], isolate: false }) + .catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(MultiRunError) + expect(error).toMatchObject({ status: 404 }) + }) + + it('removes the workspace when discarding an isolated entry', async () => { + const repoId = readyRepo() + const { client, worktreeRemove } = createClient() + const service = createService(client) + + const run = await service.launch({ + repoId, + name: 'Sweep', + prompt: 'go', + models: ['openai/a'], + isolate: true, + }) + const entry = run.entries[0]! + expect(entry.directory).toBe('/worktrees/Sweep-1') + + const discarded = await service.discard(run.id, entry.id) + + expect(discarded.entries[0]!.status).toBe('discarded') + expect(worktreeRemove).toHaveBeenCalledWith({ + projectID: 'commit-A', + directory: '/worktrees/Sweep-1', + force: true, + }) + }) + + it('rejects discarding an entry twice', async () => { + const repoId = readyRepo() + const { client, worktreeRemove } = createClient() + const service = createService(client) + + const run = await service.launch({ + repoId, + name: 'Sweep', + prompt: 'go', + models: ['openai/a'], + isolate: true, + }) + const entry = run.entries[0]! + await service.discard(run.id, entry.id) + + const error = await service.discard(run.id, entry.id).catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(MultiRunError) + expect(error).toMatchObject({ status: 409 }) + expect(worktreeRemove).toHaveBeenCalledTimes(1) + }) + + it('does not remove a workspace when discarding a non-isolated entry', async () => { + const repoId = readyRepo() + const { client, worktreeRemove } = createClient() + const service = createService(client) + + const run = await service.launch({ + repoId, + name: 'Sweep', + prompt: 'go', + models: ['openai/a'], + isolate: false, + }) + + const discarded = await service.discard(run.id, run.entries[0]!.id) + + expect(discarded.entries[0]!.status).toBe('discarded') + expect(worktreeRemove).not.toHaveBeenCalled() + }) + + it('records the workspace of a failed isolated launch and removes it on discard', async () => { + const repoId = readyRepo() + const { client, worktreeRemove } = createClient() + const service = createService(client) + + const run = await service.launch({ + repoId, + name: 'Sweep', + prompt: 'go', + models: ['openai/retired'], + isolate: true, + }) + const entry = run.entries[0]! + + expect(entry.status).toBe('failed') + expect(entry.directory).toBe('/worktrees/Sweep-1') + expect(entry.error).toContain('/worktrees/Sweep-1') + + const discarded = await service.discard(run.id, entry.id) + + expect(discarded.entries[0]!.status).toBe('discarded') + expect(worktreeRemove).toHaveBeenCalledTimes(1) + expect(worktreeRemove).toHaveBeenCalledWith({ + projectID: 'commit-A', + directory: '/worktrees/Sweep-1', + force: true, + }) + }) + + it('records the workspace of a failed isolated launch when prompting fails and removes it on discard', async () => { + const repoId = readyRepo() + const { client, sessionPrompt, worktreeRemove } = createClient() + sessionPrompt.mockRejectedValueOnce(new Error('prompt boom')) + const service = createService(client) + + const run = await service.launch({ + repoId, + name: 'Sweep', + prompt: 'go', + models: ['openai/a'], + isolate: true, + }) + const entry = run.entries[0]! + + expect(entry.status).toBe('failed') + expect(entry.directory).toBe('/worktrees/Sweep-1') + expect(entry.error).toContain('prompt boom') + + const discarded = await service.discard(run.id, entry.id) + + expect(discarded.entries[0]!.status).toBe('discarded') + expect(worktreeRemove).toHaveBeenCalledTimes(1) + }) + + it('does not record or remove a workspace when isolated workspace creation fails', async () => { + const repoId = readyRepo() + const { client, worktreeCreate, worktreeRemove } = createClient() + worktreeCreate.mockRejectedValueOnce(new Error('no workspace')) + const service = createService(client) + + const run = await service.launch({ + repoId, + name: 'Sweep', + prompt: 'go', + models: ['openai/a'], + isolate: true, + }) + const entry = run.entries[0]! + + expect(entry.status).toBe('failed') + expect(entry.directory).toBeNull() + + const discarded = await service.discard(run.id, entry.id) + + expect(discarded.entries[0]!.status).toBe('discarded') + expect(worktreeRemove).not.toHaveBeenCalled() + }) + + it('removes the workspace once when discards race', async () => { + const repoId = readyRepo() + const { client, worktreeRemove } = createClient() + const service = createService(client) + + const run = await service.launch({ + repoId, + name: 'Sweep', + prompt: 'go', + models: ['openai/a'], + isolate: true, + }) + const entry = run.entries[0]! + + let releaseRemoval: () => void = () => {} + worktreeRemove.mockReturnValueOnce( + new Promise((resolve) => { + releaseRemoval = resolve + }), + ) + + const first = service.discard(run.id, entry.id) + const second = service.discard(run.id, entry.id).catch((caught: unknown) => caught) + + const error = await second + expect(error).toBeInstanceOf(MultiRunError) + expect(error).toMatchObject({ status: 409 }) + + releaseRemoval() + const discarded = await first + + expect(discarded.entries[0]!.status).toBe('discarded') + expect(worktreeRemove).toHaveBeenCalledTimes(1) + }) + + it('keeps the entry retryable when workspace removal fails', async () => { + const repoId = readyRepo() + const { client, worktreeRemove } = createClient() + const service = createService(client) + + const run = await service.launch({ + repoId, + name: 'Sweep', + prompt: 'go', + models: ['openai/a'], + isolate: true, + }) + const entry = run.entries[0]! + + worktreeRemove.mockRejectedValueOnce(new Error('removal failed')) + + const error = await service.discard(run.id, entry.id).catch((caught: unknown) => caught) + expect(error).toBeInstanceOf(MultiRunError) + expect(error).toMatchObject({ status: 502 }) + + expect(service.list(repoId)[0]!.entries[0]!.status).toBe('started') + + const discarded = await service.discard(run.id, entry.id) + + expect(discarded.entries[0]!.status).toBe('discarded') + expect(worktreeRemove).toHaveBeenCalledTimes(2) + }) + + it('lists the most recent groups for a repository', async () => { + const repoId = readyRepo() + const { client } = createClient() + const service = createService(client) + + await service.launch({ repoId, name: 'First', prompt: 'go', models: ['openai/a'], isolate: false }) + await service.launch({ repoId, name: 'Second', prompt: 'go', models: ['openai/b'], isolate: false }) + + const runs = service.list(repoId) + + expect(runs.map((run) => run.name)).toEqual(['Second', 'First']) + }) + + it('persists the group and its entries in one transaction', () => { + const repoId = readyRepo() + db.run(`CREATE TRIGGER fail_entry BEFORE INSERT ON multi_run_entries BEGIN SELECT RAISE(ABORT, 'nope'); END`) + + expect(() => + createMultiRunWithEntries(db, { repoId, name: 'Sweep', prompt: 'go', isolated: false, baseRef: null }, [ + 'openai/a', + 'openai/b', + ]), + ).toThrow() + + const count = db.prepare('SELECT COUNT(*) AS count FROM multi_runs').get() as { count: number } + expect(count.count).toBe(0) + }) +}) diff --git a/backend/test/services/session-launcher.test.ts b/backend/test/services/session-launcher.test.ts index c97ce7db..d81b6365 100644 --- a/backend/test/services/session-launcher.test.ts +++ b/backend/test/services/session-launcher.test.ts @@ -23,13 +23,18 @@ interface FakeLaunchClient { worktreeCreate: ReturnType } -function createClient(overrides: { workspaceDirectory?: string; createError?: Error } = {}): FakeLaunchClient { +function createClient( + overrides: { workspaceDirectory?: string; createError?: Error; worktreeCreateError?: Error } = {}, +): FakeLaunchClient { const create = vi.fn(async (input: { title?: string }) => { if (overrides.createError) throw overrides.createError return { id: 'ses_new', title: input?.title } }) const prompt = vi.fn(async () => ({})) - const worktreeCreate = vi.fn(async () => ({ directory: overrides.workspaceDirectory ?? '/worktrees/feature-x' })) + const worktreeCreate = vi.fn(async () => { + if (overrides.worktreeCreateError) throw overrides.worktreeCreateError + return { directory: overrides.workspaceDirectory ?? '/worktrees/feature-x' } + }) const client = { api: { @@ -160,7 +165,38 @@ describe('SessionLauncher', () => { expect(error).toMatchObject({ status: 502, message: 'boom (workspace: /worktrees/feature-x)', + workspaceDirectory: '/worktrees/feature-x', }) expect(worktreeCreate).toHaveBeenCalled() }) + + it('exposes the created workspace when the requested model is unavailable', async () => { + const repoId = readyRepo() + const { client, create } = createClient({ workspaceDirectory: '/worktrees/feature-x' }) + const launcher = new SessionLauncher(db, client) + + const error = await launcher + .launch({ repoId, prompt: 'hello', model: 'openai/retired', workspace: { name: 'feature-x' } }) + .catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(SessionLaunchError) + expect(error).toMatchObject({ + status: 400, + workspaceDirectory: '/worktrees/feature-x', + }) + expect(create).not.toHaveBeenCalled() + }) + + it('exposes no workspace when workspace creation fails', async () => { + const repoId = readyRepo() + const { client } = createClient({ worktreeCreateError: new Error('no workspace') }) + const launcher = new SessionLauncher(db, client) + + const error = await launcher + .launch({ repoId, prompt: 'hello', workspace: { name: 'feature-x' } }) + .catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(SessionLaunchError) + expect(error).toMatchObject({ status: 502, workspaceDirectory: null }) + }) }) diff --git a/shared/src/schemas/index.ts b/shared/src/schemas/index.ts index bc6f2e5f..34362d61 100644 --- a/shared/src/schemas/index.ts +++ b/shared/src/schemas/index.ts @@ -14,4 +14,5 @@ export * from './session-pins' export * from './session-permissions' export * from './session-goals' export * from './internal-sessions' +export * from './multi-runs' export * from './logs' diff --git a/shared/src/schemas/multi-runs.ts b/shared/src/schemas/multi-runs.ts new file mode 100644 index 00000000..d65c2366 --- /dev/null +++ b/shared/src/schemas/multi-runs.ts @@ -0,0 +1,50 @@ +import { z } from "zod"; + +export const MULTI_RUN_MAX_MODELS = 5; + +export const MultiRunEntryStatusSchema = z.enum(["starting", "started", "failed", "discarded"]); + +export type MultiRunEntryStatus = z.infer; + +export const MultiRunEntrySchema = z.object({ + id: z.number().int(), + model: z.string(), + status: MultiRunEntryStatusSchema, + sessionId: z.string().nullable(), + directory: z.string().nullable(), + isolated: z.boolean(), + error: z.string().nullable(), + createdAt: z.number(), + updatedAt: z.number(), +}); + +export type MultiRunEntry = z.infer; + +export const MultiRunSchema = z.object({ + id: z.number().int(), + repoId: z.number().int(), + name: z.string(), + prompt: z.string(), + isolated: z.boolean(), + baseRef: z.string().nullable(), + createdAt: z.number(), + entries: z.array(MultiRunEntrySchema), +}); + +export type MultiRun = z.infer; + +export const LaunchMultiRunRequestSchema = z.object({ + repoId: z.number().int(), + name: z.string().trim().min(1).max(80), + prompt: z.string().trim().min(1).max(20000), + models: z + .array(z.string().min(3)) + .min(1) + .max(MULTI_RUN_MAX_MODELS) + .refine((models) => new Set(models).size === models.length, { message: "Models must be unique" }), + isolate: z.boolean(), + baseRef: z.string().trim().min(1).optional(), + agent: z.string().optional(), +}); + +export type LaunchMultiRunRequest = z.infer;