From 206113438cf9f246971e69747149940bbde9213c Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 10:37:29 -0400 Subject: [PATCH] section 10: Phase 10: Session launcher owner --- backend/src/services/session-launcher.ts | 128 ++++++++++++++ .../test/services/session-launcher.test.ts | 166 ++++++++++++++++++ 2 files changed, 294 insertions(+) create mode 100644 backend/src/services/session-launcher.ts create mode 100644 backend/test/services/session-launcher.test.ts diff --git a/backend/src/services/session-launcher.ts b/backend/src/services/session-launcher.ts new file mode 100644 index 00000000..46763c07 --- /dev/null +++ b/backend/src/services/session-launcher.ts @@ -0,0 +1,128 @@ +import type { Database } from 'bun:sqlite' +import { openCodeLocation, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode' +import { getRepoById } from '../db/queries' +import { getErrorMessage } from '../utils/error-utils' +import type { OpenCodeClient } from './opencode/client' +import { resolveOpenCodeModel } from './opencode-models' +import { createRepoWorkspace } from './repo' + +export interface LaunchSessionInput { + repoId: number + prompt: string + title?: string + model?: string + agent?: string + workspace?: { name?: string; ref?: string } +} + +export interface LaunchedSession { + sessionId: string + repoId: number + directory: string + workspaceDirectory: string | null + model: string + title: string | null +} + +export class SessionLaunchError extends Error { + readonly status: 400 | 404 | 502 + + constructor(message: string, status: 400 | 404 | 502) { + super(message) + this.name = 'SessionLaunchError' + this.status = status + } +} + +function withWorkspace(message: string, workspaceDirectory: string | null): string { + return workspaceDirectory ? `${message} (workspace: ${workspaceDirectory})` : message +} + +export class SessionLauncher { + constructor( + private readonly db: Database, + private readonly openCodeClient: OpenCodeClient, + ) {} + + async launch(input: LaunchSessionInput): Promise { + const repo = getRepoById(this.db, input.repoId) + if (!repo || repo.cloneStatus !== 'ready') { + throw new SessionLaunchError('Repository not found or not ready', 404) + } + + let directory = repo.fullPath + let workspaceDirectory: string | null = null + + if (input.workspace) { + try { + const workspace = await createRepoWorkspace(this.openCodeClient, repo, input.workspace) + directory = workspace.directory + workspaceDirectory = workspace.directory + } catch (error) { + throw new SessionLaunchError(withWorkspace(getErrorMessage(error) || 'Failed to create workspace', null), 502) + } + } + + const model = await this.resolveModel(input.model, directory, workspaceDirectory) + + let session: { id: string; title?: string | null } + try { + session = await this.openCodeClient.api.session.create({ + ...(input.title ? { title: input.title } : {}), + ...(input.agent ? { agent: input.agent } : {}), + model: { + providerID: model.providerID, + id: model.id, + ...(model.variant ? { variant: model.variant } : {}), + }, + ...openCodeLocation(directory), + }) + + await this.openCodeClient.api.session.prompt({ sessionID: session.id, text: input.prompt }) + } catch (error) { + throw new SessionLaunchError( + withWorkspace(getErrorMessage(error) || 'Failed to create OpenCode session', workspaceDirectory), + 502, + ) + } + + return { + sessionId: session.id, + repoId: repo.id, + directory, + workspaceDirectory, + model: model.model, + title: session.title ?? input.title ?? null, + } + } + + private async resolveModel( + requestedModel: string | undefined, + directory: string, + workspaceDirectory: string | null, + ): Promise>> { + let resolved: Awaited> + try { + resolved = await resolveOpenCodeModel(this.openCodeClient, directory, { + preferredModel: requestedModel, + }) + } catch (error) { + throw new SessionLaunchError( + withWorkspace(getErrorMessage(error) || 'Failed to resolve OpenCode model', workspaceDirectory), + 502, + ) + } + + if (requestedModel) { + const requestedRef = parseOpenCodeModelRef(requestedModel) + if (!requestedRef || resolved.providerID !== requestedRef.providerID || resolved.id !== requestedRef.id) { + throw new SessionLaunchError( + withWorkspace(`Model ${requestedModel} is not available`, workspaceDirectory), + 400, + ) + } + } + + return resolved + } +} diff --git a/backend/test/services/session-launcher.test.ts b/backend/test/services/session-launcher.test.ts new file mode 100644 index 00000000..c97ce7db --- /dev/null +++ b/backend/test/services/session-launcher.test.ts @@ -0,0 +1,166 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { Database } from 'bun:sqlite' +import type { OpenCodeClient } from '../../src/services/opencode/client' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import { createRepo } from '../../src/db/queries' +import { SessionLauncher, SessionLaunchError } from '../../src/services/session-launcher' + +const mocks = vi.hoisted(() => ({ + resolveOpenCodeModel: vi.fn(), +})) + +vi.mock('../../src/services/opencode-models', () => ({ + resolveOpenCodeModel: mocks.resolveOpenCodeModel, +})) + +const REPO_DIR = '/repos/repo-a' + +interface FakeLaunchClient { + client: OpenCodeClient + create: ReturnType + prompt: ReturnType + worktreeCreate: ReturnType +} + +function createClient(overrides: { workspaceDirectory?: string; createError?: 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 client = { + api: { + location: { + get: vi.fn(async () => ({ project: { id: 'commit-A', directory: REPO_DIR, canonical: REPO_DIR } })), + }, + worktree: { create: worktreeCreate }, + session: { create, prompt }, + }, + } as unknown as OpenCodeClient + + return { client, create, prompt, worktreeCreate } +} + +describe('SessionLauncher', () => { + let db: Database + + beforeEach(() => { + vi.clearAllMocks() + db = new Database(':memory:') + migrate(db, allMigrations) + mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', id: 'gpt-5', model: 'openai/gpt-5' }) + }) + + afterEach(() => { + db.close() + }) + + function readyRepo(overrides: { cloneStatus?: 'cloning' | 'ready' | 'error' } = {}): number { + const repo = createRepo(db, { + localPath: 'repo-a', + sourcePath: REPO_DIR, + defaultBranch: 'main', + cloneStatus: overrides.cloneStatus ?? 'ready', + clonedAt: Date.now(), + isLocal: true, + }) + return repo.id + } + + it('launches in the repo directory with the resolved model and sends the prompt', async () => { + const repoId = readyRepo() + const { client, create, prompt } = createClient() + const launcher = new SessionLauncher(db, client) + + const result = await launcher.launch({ repoId, prompt: 'hello', title: 'T', agent: 'build', model: 'openai/gpt-5' }) + + expect(mocks.resolveOpenCodeModel).toHaveBeenCalledWith(client, REPO_DIR, { preferredModel: 'openai/gpt-5' }) + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ + title: 'T', + agent: 'build', + model: { providerID: 'openai', id: 'gpt-5' }, + location: { directory: REPO_DIR }, + }), + ) + expect(prompt).toHaveBeenCalledWith({ sessionID: 'ses_new', text: 'hello' }) + expect(result).toEqual({ + sessionId: 'ses_new', + repoId, + directory: REPO_DIR, + workspaceDirectory: null, + model: 'openai/gpt-5', + title: 'T', + }) + }) + + it('launches in a new workspace and prompts there', async () => { + const repoId = readyRepo() + const { client, create, worktreeCreate } = createClient() + const launcher = new SessionLauncher(db, client) + + const result = await launcher.launch({ + repoId, + prompt: 'hello', + workspace: { name: 'feature-x', ref: 'feature/x' }, + }) + + expect(worktreeCreate).toHaveBeenCalledWith({ projectID: 'commit-A', name: 'feature-x', branch: 'feature/x' }) + expect(mocks.resolveOpenCodeModel).toHaveBeenCalledWith(client, '/worktrees/feature-x', { preferredModel: undefined }) + expect(create).toHaveBeenCalledWith(expect.objectContaining({ location: { directory: '/worktrees/feature-x' } })) + expect(result).toMatchObject({ + sessionId: 'ses_new', + repoId, + directory: '/worktrees/feature-x', + workspaceDirectory: '/worktrees/feature-x', + }) + }) + + it('rejects an unavailable requested model without creating a session', async () => { + const repoId = readyRepo() + const { client, create } = createClient() + const launcher = new SessionLauncher(db, client) + + const error = await launcher.launch({ repoId, prompt: 'hello', model: 'openai/retired' }).catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(SessionLaunchError) + expect(error).toMatchObject({ status: 400, message: 'Model openai/retired is not available' }) + expect(create).not.toHaveBeenCalled() + }) + + it('rejects a repo that is not ready', async () => { + const repoId = readyRepo({ cloneStatus: 'cloning' }) + const { client, create } = createClient() + const launcher = new SessionLauncher(db, client) + + const error = await launcher.launch({ repoId, prompt: 'hello' }).catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(SessionLaunchError) + expect(error).toMatchObject({ status: 404 }) + expect(create).not.toHaveBeenCalled() + expect(mocks.resolveOpenCodeModel).not.toHaveBeenCalled() + }) + + it('keeps a created workspace and names it when session creation fails', async () => { + const repoId = readyRepo() + const { client, worktreeCreate } = createClient({ + workspaceDirectory: '/worktrees/feature-x', + createError: new Error('boom'), + }) + 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, + message: 'boom (workspace: /worktrees/feature-x)', + }) + expect(worktreeCreate).toHaveBeenCalled() + }) +})