diff --git a/backend/src/routes/internal/index.ts b/backend/src/routes/internal/index.ts index 727cceb0..f96732f5 100644 --- a/backend/src/routes/internal/index.ts +++ b/backend/src/routes/internal/index.ts @@ -13,6 +13,7 @@ import { createInternalRepoRoutes } from './repos' import { createInternalRepoSyncRoutes } from './repo-sync' import { createInternalRepoMirrorRoutes as mirrorRoutes } from './repo-mirror' import { createInternalOpenCodeWorkspacesRoutes } from './opencode-workspaces' +import { createInternalSessionRoutes } from './sessions' import { createInternalAssistantRoutes } from './assistant' import { createInternalGitCredentialsRoutes } from './git-credentials' import { createInternalSandboxRoutes } from './sandbox' @@ -37,6 +38,7 @@ export function createInternalRoutes( repos.route('/', mirrorRoutes(db)) app.route('/repos', repos) app.route('/opencode-workspaces', createInternalOpenCodeWorkspacesRoutes(db)) + app.route('/sessions', createInternalSessionRoutes(db, openCodeClient)) app.route('/assistant', createInternalAssistantRoutes(openCodeClient)) app.route('/git-credentials', createInternalGitCredentialsRoutes(db)) app.route('/sandbox', createInternalSandboxRoutes(db)) diff --git a/backend/src/routes/internal/sessions.ts b/backend/src/routes/internal/sessions.ts new file mode 100644 index 00000000..b4de90de --- /dev/null +++ b/backend/src/routes/internal/sessions.ts @@ -0,0 +1,222 @@ +import { Hono, type Context } from 'hono' +import { z } from 'zod' +import type { Database } from 'bun:sqlite' +import { + InternalCreateSessionRequestSchema, + InternalForkSessionRequestSchema, + InternalSessionPromptRequestSchema, +} from '@opencode-manager/shared/schemas' +import { isSessionNotFoundError } from '@opencode-manager/shared/opencode' +import { getRepoById, listRepos } from '../../db/queries' +import { getErrorMessage } from '../../utils/error-utils' +import { logger } from '../../utils/logger' +import type { OpenCodeClient } from '../../services/opencode/client' +import { SessionLaunchError, SessionLauncher } from '../../services/session-launcher' +import { isSessionBusy, readLatestAssistantReply } from '../../services/session-reply' + +const INTERNAL_SESSION_LIST_LIMIT_MIN = 1 +const INTERNAL_SESSION_LIST_LIMIT_MAX = 50 +const INTERNAL_SESSION_LIST_LIMIT_DEFAULT = 10 +const INTERNAL_SESSION_WORKSPACE_NAME_FALLBACK = 'ocm-session' + +const ListSessionsQuerySchema = z.object({ + repoId: z.coerce.number().int().optional(), + limit: z.coerce + .number() + .int() + .min(INTERNAL_SESSION_LIST_LIMIT_MIN) + .max(INTERNAL_SESSION_LIST_LIMIT_MAX) + .default(INTERNAL_SESSION_LIST_LIMIT_DEFAULT), +}) + +type JsonBodyResult = { ok: true; value: unknown } | { ok: false } + +async function readJsonBody(c: Context): Promise { + const text = await c.req.text() + if (!text.trim()) { + return { ok: true, value: {} } + } + try { + return { ok: true, value: JSON.parse(text) } + } catch { + return { ok: false } + } +} + +function openCodeErrorResponse(error: unknown): { status: 400 | 404 | 502; body: { error: string } } { + if (error instanceof SessionLaunchError) { + return { status: error.status, body: { error: error.message } } + } + if (isSessionNotFoundError(error)) { + return { status: 404, body: { error: 'Session not found' } } + } + logger.error('Internal session request failed:', error) + return { status: 502, body: { error: getErrorMessage(error) } } +} + +function workspaceNameFromTitle(title: string | undefined): string { + const slug = (title ?? '') + .toLowerCase() + .replace(/[^a-z0-9._-]+/g, '-') + .replace(/^-+/, '') + .replace(/-+$/, '') + return slug || INTERNAL_SESSION_WORKSPACE_NAME_FALLBACK +} + +export function createInternalSessionRoutes(db: Database, openCodeClient: OpenCodeClient) { + const app = new Hono() + const sessionLauncher = new SessionLauncher(db, openCodeClient) + + app.get('/', async (c) => { + const parsedQuery = ListSessionsQuerySchema.safeParse(c.req.query()) + if (!parsedQuery.success) { + return c.json({ error: 'Invalid query', details: parsedQuery.error.issues }, 400) + } + + const { repoId, limit } = parsedQuery.data + const repo = repoId === undefined ? undefined : getRepoById(db, repoId) + if (repoId !== undefined && !repo) { + return c.json({ error: 'Repository not found' }, 404) + } + + try { + const response = await openCodeClient.api.session.list({ + limit, + order: 'desc', + parentID: null, + ...(repo ? { directory: repo.fullPath } : {}), + }) + const active = await openCodeClient.api.session.active() + const repos = listRepos(db) + + const sessions = response.data.map((session) => { + const directory = session.location.directory + const matchedRepo = repos.find((candidate) => candidate.fullPath === directory) + return { + id: session.id, + title: session.title ?? null, + directory, + repoId: matchedRepo?.id ?? null, + busy: session.id in active, + outcome: session.outcome ?? null, + updated: session.time.updated, + } + }) + + return c.json({ sessions }) + } catch (error) { + const mapped = openCodeErrorResponse(error) + return c.json(mapped.body, mapped.status) + } + }) + + app.post('/', async (c) => { + const body = await readJsonBody(c) + if (!body.ok) { + return c.json({ error: 'Invalid JSON' }, 400) + } + + const parsed = InternalCreateSessionRequestSchema.safeParse(body.value) + if (!parsed.success) { + return c.json({ error: 'Invalid request body', details: parsed.error.issues }, 400) + } + + const input = parsed.data + try { + const launched = await sessionLauncher.launch({ + repoId: input.repoId, + prompt: input.prompt, + ...(input.title ? { title: input.title } : {}), + ...(input.model ? { model: input.model } : {}), + ...(input.agent ? { agent: input.agent } : {}), + ...(input.worktree + ? { + workspace: { + name: workspaceNameFromTitle(input.title), + ...(input.ref ? { ref: input.ref } : {}), + }, + } + : {}), + }) + + const url = `/repos/${launched.repoId}/sessions/${launched.sessionId}${launched.workspaceDirectory ? '?repoTab=workspaces' : ''}` + return c.json({ ...launched, url }, 201) + } catch (error) { + const mapped = openCodeErrorResponse(error) + return c.json(mapped.body, mapped.status) + } + }) + + app.post('/:sessionId/prompt', async (c) => { + const sessionId = c.req.param('sessionId') + const body = await readJsonBody(c) + if (!body.ok) { + return c.json({ error: 'Invalid JSON' }, 400) + } + + const parsed = InternalSessionPromptRequestSchema.safeParse(body.value) + if (!parsed.success) { + return c.json({ error: 'Invalid request body', details: parsed.error.issues }, 400) + } + + try { + await openCodeClient.api.session.prompt({ + sessionID: sessionId, + text: parsed.data.text, + delivery: 'queue', + }) + return c.json({ queued: true }, 202) + } catch (error) { + const mapped = openCodeErrorResponse(error) + return c.json(mapped.body, mapped.status) + } + }) + + app.get('/:sessionId/reply', async (c) => { + const sessionId = c.req.param('sessionId') + + try { + const [busy, reply] = await Promise.all([ + isSessionBusy(openCodeClient, sessionId), + readLatestAssistantReply(openCodeClient, sessionId), + ]) + + return c.json({ + busy, + responseText: reply?.responseText ?? null, + errorText: reply?.errorText ?? null, + completed: reply?.completed ?? false, + }) + } catch (error) { + const mapped = openCodeErrorResponse(error) + return c.json(mapped.body, mapped.status) + } + }) + + app.post('/:sessionId/fork', async (c) => { + const sessionId = c.req.param('sessionId') + const body = await readJsonBody(c) + if (!body.ok) { + return c.json({ error: 'Invalid JSON' }, 400) + } + + const parsed = InternalForkSessionRequestSchema.safeParse(body.value) + if (!parsed.success) { + return c.json({ error: 'Invalid request body', details: parsed.error.issues }, 400) + } + + const beforeMessageId = parsed.data.beforeMessageId + try { + const forked = await openCodeClient.api.session.fork({ + sessionID: sessionId, + ...(beforeMessageId ? { before: beforeMessageId } : {}), + }) + return c.json({ sessionId: forked.id, directory: forked.location.directory }) + } catch (error) { + const mapped = openCodeErrorResponse(error) + return c.json(mapped.body, mapped.status) + } + }) + + return app +} diff --git a/backend/src/services/assistant-mode.ts b/backend/src/services/assistant-mode.ts index dc9dfab9..8ce6dda9 100644 --- a/backend/src/services/assistant-mode.ts +++ b/backend/src/services/assistant-mode.ts @@ -31,6 +31,7 @@ const ASSISTANT_SCHEDULES_SKILL_DIR = 'schedule-management' const ASSISTANT_NOTIFICATIONS_SKILL_DIR = 'notifications' const ASSISTANT_SETTINGS_SKILL_DIR = 'manager-settings' const ASSISTANT_REPOS_SKILL_DIR = 'repo-management' +const ASSISTANT_SESSIONS_SKILL_DIR = 'session-management' const ASSISTANT_SKILL_FILENAME = 'SKILL.md' const ASSISTANT_AGENTS_DIR = 'agents' const ASSISTANT_DEFAULT_AGENT_NAME = 'assistant' @@ -77,6 +78,10 @@ function getReposSkillPath(assistantDir: string): string { return path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_REPOS_SKILL_DIR, ASSISTANT_SKILL_FILENAME) } +function getSessionsSkillPath(assistantDir: string): string { + return path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_SESSIONS_SKILL_DIR, ASSISTANT_SKILL_FILENAME) +} + function getAssistantDefaultAgentPath(assistantDir: string): string { return path.join( assistantDir, @@ -897,6 +902,172 @@ List all repos available to OpenCode Manager. The repos are returned in the orde ` } +export function buildSessionsSkill(): string { + return `--- +name: session-management +description: Create and follow up on OpenCode sessions with the ${MANAGER_TOOL_NAME} tool +--- + +## When to Load + +Load this skill when the user asks you to start work in a repo, hand a task to a new session, follow up on a running session, read what a session replied, or fork a session. + +## Tool + +Use the \`${MANAGER_TOOL_NAME}\` tool with the \`request\` action. The tool runs inside OpenCode Manager, so it needs no token, no base URL, and no network access from the shell. It works the same in a normal session, a sandboxed session, and a scheduled run. Paths are relative to the internal API (for example \`/sessions?repoId=1\` or \`/sessions/ses_abc/prompt\`) and query strings are allowed. + +**Arguments:** +\`\`\`ts +{ + action: 'request', + params: { + method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', + path: string // relative internal API path; query strings allowed + body?: object // JSON body for POST and PATCH routes + } +} +\`\`\` + +## Endpoints + +### GET /sessions + +List sessions, newest first. Pass \`repoId\` to restrict the list to one repo and \`limit\` (1-50, default 10) to bound it. + +Query params: \`repoId\`, \`limit\` + +\`\`\`json +{ + "action": "request", + "params": { + "method": "GET", + "path": "/sessions?repoId=1&limit=10" + } +} +\`\`\` + +**Response:** +\`\`\`ts +{ + sessions: Array<{ + id: string + title: string | null + directory: string + repoId: number | null // null when the directory matches no known repo + busy: boolean // true while the session is running + outcome: 'succeeded' | 'failed' | 'interrupted' | null + updated: number + }> +} +\`\`\` + +### POST /sessions + +Create a session in a repo and send the first prompt. The response returns as soon as the prompt is queued, not when the run finishes. Use \`GET /sessions/:sessionId/reply\` to poll for the result. + +Pass \`worktree: true\` to run the session in a new isolated workspace instead of the repo directory. \`ref\` selects the base ref for that workspace. \`model\` must be an available model reference; an unavailable model is rejected with \`400\` rather than silently substituted. + +\`\`\`json +{ + "action": "request", + "params": { + "method": "POST", + "path": "/sessions", + "body": { + "repoId": 1, + "prompt": "Fix the failing login test", + "title": "Fix login test", + "worktree": true + } + } +} +\`\`\` + +**Response (\`201\`):** +\`\`\`ts +{ + sessionId: string + repoId: number + directory: string + workspaceDirectory: string | null + model: string + title: string | null + url: string // deep link to open the session in the UI +} +\`\`\` + +### POST /sessions/:sessionId/prompt + +Queue a follow-up prompt for an existing session. + +\`\`\`json +{ + "action": "request", + "params": { + "method": "POST", + "path": "/sessions/ses_abc/prompt", + "body": { "text": "Also add a regression test" } + } +} +\`\`\` + +**Response (\`202\`):** \`{ "queued": true }\` + +### GET /sessions/:sessionId/reply + +Read the latest assistant reply for a session and whether it is still running. Poll this after creating a session or queueing a prompt until \`busy\` is \`false\`. + +\`\`\`json +{ + "action": "request", + "params": { + "method": "GET", + "path": "/sessions/ses_abc/reply" + } +} +\`\`\` + +**Response:** +\`\`\`ts +{ + busy: boolean + responseText: string | null // latest assistant text, null when there is none yet + errorText: string | null // assistant error message, null when the turn succeeded + completed: boolean // true once the latest assistant turn finished +} +\`\`\` + +### POST /sessions/:sessionId/fork + +Fork a session, optionally before a specific message. Omit \`beforeMessageId\` to fork from the current point. + +\`\`\`json +{ + "action": "request", + "params": { + "method": "POST", + "path": "/sessions/ses_abc/fork", + "body": { "beforeMessageId": "msg_123" } + } +} +\`\`\` + +**Response:** +\`\`\`ts +{ + sessionId: string // the new forked session + directory: string +} +\`\`\` + +## Notes + +- Session creation always goes through OpenCode Manager, which validates the repo and the requested model before creating anything +- There is no delete route. Deleting sessions and workspaces stays out of this tool +- An unknown session returns \`404\`; other failures return \`502\` +` +} + export function buildAssistantOpenCodeConfig(): OpenCodeConfigInput { const config: OpenCodeConfigInput = { default_agent: ASSISTANT_DEFAULT_AGENT_NAME, @@ -1004,6 +1175,7 @@ export async function ensureAssistantMode( await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_NOTIFICATIONS_SKILL_DIR)) await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_SETTINGS_SKILL_DIR)) await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_REPOS_SKILL_DIR)) + await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_SESSIONS_SKILL_DIR)) const schedulesSkillContent = buildSchedulesSkill() const existingSchedulesSkillContent = await fileExists(skillPath) ? await readFileContent(skillPath) : undefined @@ -1036,6 +1208,14 @@ export async function ensureAssistantMode( await writeFileContent(reposSkillPath, reposSkillContent) } + const sessionsSkillPath = getSessionsSkillPath(assistantDir) + const sessionsSkillContent = buildSessionsSkill() + const existingSessionsSkillContent = await fileExists(sessionsSkillPath) ? await readFileContent(sessionsSkillPath) : undefined + const sessionsSkillCreated = !hasSameContentHash(existingSessionsSkillContent, sessionsSkillContent) + if (sessionsSkillCreated) { + await writeFileContent(sessionsSkillPath, sessionsSkillContent) + } + const assistantAgentExists = await fileExists(assistantAgentPath) const assistantAgentContent = buildAssistantDefaultAgentMd() const existingAssistantAgentContent = assistantAgentExists @@ -1098,6 +1278,10 @@ export async function ensureAssistantMode( path: reposSkillPath, created: reposSkillCreated, }, + sessionManagementSkill: { + path: sessionsSkillPath, + created: sessionsSkillCreated, + }, defaultAgent: { name: ASSISTANT_DEFAULT_AGENT_NAME, path: assistantAgentPath, @@ -1201,6 +1385,7 @@ export async function getAssistantModeStatus(repo: Repo): Promise `- ${route}`)) diff --git a/backend/test/routes/internal-sessions.test.ts b/backend/test/routes/internal-sessions.test.ts new file mode 100644 index 00000000..f259372d --- /dev/null +++ b/backend/test/routes/internal-sessions.test.ts @@ -0,0 +1,347 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest' +import { Hono } from 'hono' +import type { Database } from 'bun:sqlite' +import { createInternalRoutes } from '../../src/routes/internal' +import type { ScheduleService } from '../../src/services/schedules' +import type { NotificationService } from '../../src/services/notification' +import type { SettingsService } from '../../src/services/settings' +import type { OpenCodeClient } from '../../src/services/opencode/client' +import type { Repo } from '../../src/types/repo' + +const mockDb = { + prepare: vi.fn().mockReturnValue({ + run: vi.fn(), + get: vi.fn(), + all: vi.fn(), + }), + exec: vi.fn(), + close: vi.fn(), + transaction: vi.fn((fn: () => void) => fn()), +} as unknown as Database + +vi.mock('bun:sqlite', () => ({ + Database: vi.fn(() => mockDb), +})) + +const mockListRepos = vi.fn() +const mockGetRepoById = vi.fn() +vi.mock('../../src/db/queries', async () => { + const { getRepoDisplayName } = await vi.importActual('@opencode-manager/shared/utils') + return { + listRepos: (...args: unknown[]) => mockListRepos(...args), + getRepoById: (...args: unknown[]) => mockGetRepoById(...args), + getRepoName: (repo: Parameters[0]) => getRepoDisplayName(repo), + } +}) + +vi.mock('../../src/db/migration-runner', () => ({ + migrate: vi.fn(), +})) + +vi.mock('../../src/services/internal-token', () => ({ + getOrCreateInternalToken: vi.fn().mockReturnValue('test-internal-token'), +})) + +vi.mock('../../src/services/schedules', () => ({ + ScheduleService: vi.fn(), +})) + +vi.mock('../../src/services/notification', () => ({ + NotificationService: vi.fn(), +})) + +vi.mock('../../src/services/settings', () => ({ + SettingsService: vi.fn(), +})) + +vi.mock('../../src/services/opencode/client', () => ({ + createOpenCodeClient: vi.fn(), +})) + +const mockLaunch = vi.fn() +vi.mock('../../src/services/session-launcher', () => { + class SessionLaunchError extends Error { + readonly status: number + + constructor(message: string, status: number) { + super(message) + this.name = 'SessionLaunchError' + this.status = status + } + } + + class SessionLauncher { + launch = mockLaunch + } + + return { SessionLauncher, SessionLaunchError } +}) + +function makeRepo(overrides: Partial): Repo { + return { + id: 1, + localPath: 'test-repo', + fullPath: '/tmp/test-repo', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + ...overrides, + } +} + +function sessionNotFoundError(): Error { + return Object.assign(new Error('Session not found'), { _tag: 'SessionNotFoundError' }) +} + +const assistantMessage = { + id: 'msg_1', + type: 'assistant', + agent: 'build', + model: { id: 'model', providerID: 'provider' }, + time: { created: 1, completed: 2 }, + content: [{ type: 'text', text: 'All done' }], +} + +describe('internal-sessions routes', () => { + let app: Hono + let token: string + let openCodeClient: OpenCodeClient + let sessionList: ReturnType + let sessionActive: ReturnType + let sessionPrompt: ReturnType + let sessionFork: ReturnType + let messageList: ReturnType + + beforeEach(() => { + vi.clearAllMocks() + mockLaunch.mockReset() + mockGetRepoById.mockReturnValue(null) + mockListRepos.mockReturnValue([]) + + sessionList = vi.fn().mockResolvedValue({ data: [], cursor: {} }) + sessionActive = vi.fn().mockResolvedValue({}) + sessionPrompt = vi.fn().mockResolvedValue({}) + sessionFork = vi.fn() + messageList = vi.fn().mockResolvedValue({ data: [] }) + + openCodeClient = { + api: { + session: { + list: sessionList, + active: sessionActive, + prompt: sessionPrompt, + fork: sessionFork, + }, + message: { list: messageList }, + }, + } as unknown as OpenCodeClient + + const scheduleService = {} as ScheduleService + const notificationService = {} as NotificationService + const settingsService = {} as SettingsService + app = new Hono() + app.route('/api/internal', createInternalRoutes(mockDb, scheduleService, notificationService, settingsService, openCodeClient)) + token = 'test-internal-token' + }) + + it('GET /api/internal/sessions returns 401 without bearer token', async () => { + const res = await app.request('/api/internal/sessions') + expect(res.status).toBe(401) + }) + + it('GET /api/internal/sessions filters by repo and marks busy sessions', async () => { + const repo = makeRepo({ id: 1, fullPath: '/tmp/repo-one' }) + mockGetRepoById.mockReturnValue(repo) + mockListRepos.mockReturnValue([repo]) + sessionList.mockResolvedValue({ + data: [ + { id: 'ses_a', title: 'Alpha', location: { directory: '/tmp/repo-one' }, time: { created: 1, updated: 42 }, outcome: 'succeeded' }, + { id: 'ses_b', location: { directory: '/tmp/elsewhere' }, time: { created: 2, updated: 43 } }, + ], + cursor: {}, + }) + sessionActive.mockResolvedValue({ ses_a: { sessionID: 'ses_a' } }) + + const res = await app.request('/api/internal/sessions?repoId=1&limit=5', { + headers: { authorization: `Bearer ${token}` }, + }) + + expect(res.status).toBe(200) + expect(sessionList).toHaveBeenCalledWith({ limit: 5, order: 'desc', parentID: null, directory: '/tmp/repo-one' }) + const body = await res.json() as { sessions: Array> } + expect(body.sessions).toHaveLength(2) + expect(body.sessions[0]).toMatchObject({ id: 'ses_a', title: 'Alpha', repoId: 1, busy: true, outcome: 'succeeded', updated: 42 }) + expect(body.sessions[1]).toMatchObject({ id: 'ses_b', title: null, repoId: null, busy: false, outcome: null, updated: 43 }) + }) + + it('GET /api/internal/sessions returns 404 for an unknown repoId', async () => { + const res = await app.request('/api/internal/sessions?repoId=99', { + headers: { authorization: `Bearer ${token}` }, + }) + + expect(res.status).toBe(404) + expect(sessionList).not.toHaveBeenCalled() + }) + + it('POST /api/internal/sessions creates a session through the launcher and returns a url', async () => { + mockLaunch.mockResolvedValue({ + sessionId: 'ses_new', + repoId: 1, + directory: '/tmp/repo-one', + workspaceDirectory: null, + model: 'provider/model', + title: 'Do the thing', + }) + + const res = await app.request('/api/internal/sessions', { + method: 'POST', + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ repoId: 1, prompt: 'Do the thing', title: 'Do the thing' }), + }) + + expect(res.status).toBe(201) + expect(mockLaunch).toHaveBeenCalledWith({ repoId: 1, prompt: 'Do the thing', title: 'Do the thing' }) + const body = await res.json() as { sessionId: string; url: string } + expect(body.sessionId).toBe('ses_new') + expect(body.url).toBe('/repos/1/sessions/ses_new') + }) + + it('POST /api/internal/sessions creates an isolated workspace with a slugified name', async () => { + mockLaunch.mockResolvedValue({ + sessionId: 'ses_ws', + repoId: 1, + directory: '/tmp/repo-one-ws', + workspaceDirectory: '/tmp/repo-one-ws', + model: 'provider/model', + title: 'My Feature', + }) + + const res = await app.request('/api/internal/sessions', { + method: 'POST', + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ repoId: 1, prompt: 'Build it', title: 'My Feature!', worktree: true, ref: 'main' }), + }) + + expect(res.status).toBe(201) + expect(mockLaunch).toHaveBeenCalledWith({ + repoId: 1, + prompt: 'Build it', + title: 'My Feature!', + workspace: { name: 'my-feature', ref: 'main' }, + }) + const body = await res.json() as { url: string } + expect(body.url).toBe('/repos/1/sessions/ses_ws?repoTab=workspaces') + }) + + it('POST /api/internal/sessions uses the fallback workspace name when the title has no slug', async () => { + mockLaunch.mockResolvedValue({ + sessionId: 'ses_ws', + repoId: 1, + directory: '/tmp/repo-one-ws', + workspaceDirectory: '/tmp/repo-one-ws', + model: 'provider/model', + title: null, + }) + + const res = await app.request('/api/internal/sessions', { + method: 'POST', + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ repoId: 1, prompt: 'Build it', worktree: true }), + }) + + expect(res.status).toBe(201) + expect(mockLaunch).toHaveBeenCalledWith({ repoId: 1, prompt: 'Build it', workspace: { name: 'ocm-session' } }) + }) + + it('POST /api/internal/sessions rejects an invalid body', async () => { + const res = await app.request('/api/internal/sessions', { + method: 'POST', + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ repoId: 1 }), + }) + + expect(res.status).toBe(400) + expect(mockLaunch).not.toHaveBeenCalled() + }) + + it('POST /api/internal/sessions/:sessionId/prompt queues the prompt', async () => { + const res = await app.request('/api/internal/sessions/ses_a/prompt', { + method: 'POST', + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ text: 'Keep going' }), + }) + + expect(res.status).toBe(202) + expect(await res.json()).toEqual({ queued: true }) + expect(sessionPrompt).toHaveBeenCalledWith({ sessionID: 'ses_a', text: 'Keep going', delivery: 'queue' }) + }) + + it('GET /api/internal/sessions/:sessionId/reply returns the latest assistant reply', async () => { + sessionActive.mockResolvedValue({ ses_a: { sessionID: 'ses_a' } }) + messageList.mockResolvedValue({ data: [assistantMessage] }) + + const res = await app.request('/api/internal/sessions/ses_a/reply', { + headers: { authorization: `Bearer ${token}` }, + }) + + expect(res.status).toBe(200) + expect(messageList).toHaveBeenCalledWith({ sessionID: 'ses_a', order: 'desc', limit: 20 }) + expect(await res.json()).toEqual({ busy: true, responseText: 'All done', errorText: null, completed: true }) + }) + + it('GET /api/internal/sessions/:sessionId/reply returns empty state when there is no assistant message', async () => { + const res = await app.request('/api/internal/sessions/ses_a/reply', { + headers: { authorization: `Bearer ${token}` }, + }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ busy: false, responseText: null, errorText: null, completed: false }) + }) + + it('POST /api/internal/sessions/:sessionId/fork passes before and returns the new session', async () => { + sessionFork.mockResolvedValue({ id: 'ses_fork', location: { directory: '/tmp/repo-one' } }) + + const res = await app.request('/api/internal/sessions/ses_a/fork', { + method: 'POST', + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ beforeMessageId: 'msg_1' }), + }) + + expect(res.status).toBe(200) + expect(sessionFork).toHaveBeenCalledWith({ sessionID: 'ses_a', before: 'msg_1' }) + expect(await res.json()).toEqual({ sessionId: 'ses_fork', directory: '/tmp/repo-one' }) + }) + + it('POST /api/internal/sessions/:sessionId/fork accepts an empty body', async () => { + sessionFork.mockResolvedValue({ id: 'ses_fork', location: { directory: '/tmp/repo-one' } }) + + const res = await app.request('/api/internal/sessions/ses_a/fork', { + method: 'POST', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(res.status).toBe(200) + expect(sessionFork).toHaveBeenCalledWith({ sessionID: 'ses_a' }) + }) + + it('returns 404 when OpenCode reports an unknown session', async () => { + sessionPrompt.mockRejectedValue(sessionNotFoundError()) + + const res = await app.request('/api/internal/sessions/ses_missing/prompt', { + method: 'POST', + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ text: 'Hello' }), + }) + + expect(res.status).toBe(404) + }) + + it('returns 404 for DELETE /api/internal/sessions/:sessionId because no route exists', async () => { + const res = await app.request('/api/internal/sessions/ses_a', { + method: 'DELETE', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(res.status).toBe(404) + }) +}) diff --git a/backend/test/services/assistant-mode.test.ts b/backend/test/services/assistant-mode.test.ts index c2ca9d75..d52921d8 100644 --- a/backend/test/services/assistant-mode.test.ts +++ b/backend/test/services/assistant-mode.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, beforeEach, afterEach } from 'bun:test' import path from 'path' import { access, readFile, writeFile } from 'fs/promises' import { Hono } from 'hono' -import { ensureAssistantMode, getAssistantModeStatus, buildSchedulesSkill, buildReposSkill, buildSettingsSkill, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig, buildAssistantRepo, installAssistantWorkspace } from '../../src/services/assistant-mode' +import { ensureAssistantMode, getAssistantModeStatus, buildSchedulesSkill, buildReposSkill, buildSettingsSkill, buildSessionsSkill, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig, buildAssistantRepo, installAssistantWorkspace } from '../../src/services/assistant-mode' import { createTempAssistantWorkspace, createTestDb, mockRepo } from '../helpers/assistant-workspace' import { createInternalRoutes } from '../../src/routes/internal' import { ScheduleService } from '../../src/services/schedules' @@ -60,6 +60,33 @@ describe('buildReposSkill', () => { }) }) +describe('buildSessionsSkill', () => { + it('instructs the agent to use the ocm tool request action', () => { + const skill = buildSessionsSkill() + expect(skill).toContain('name: session-management') + expect(skill).toContain('"action": "request"') + expect(skill).toContain('"path": "/sessions?repoId=1&limit=10"') + expect(skill).not.toContain('curl') + }) + + it('documents every session route and that creation returns immediately', () => { + const skill = buildSessionsSkill() + expect(skill).toContain('GET /sessions') + expect(skill).toContain('POST /sessions') + expect(skill).toContain('POST /sessions/:sessionId/prompt') + expect(skill).toContain('GET /sessions/:sessionId/reply') + expect(skill).toContain('POST /sessions/:sessionId/fork') + expect(skill).toContain('returns as soon as the prompt is queued') + expect(skill).toContain('poll') + }) + + it('documents that there is no delete route', () => { + const skill = buildSessionsSkill() + expect(skill).toContain('There is no delete route') + expect(skill).not.toContain('DELETE /sessions') + }) +}) + describe('buildSettingsSkill', () => { it('instructs the agent to use the ocm tool request action', () => { const skill = buildSettingsSkill() @@ -175,6 +202,7 @@ describe('ensureAssistantMode', () => { const opencodeJson = await readFile(path.join(ws.assistantDir, 'opencode.json'), 'utf8') const skill = await readFile(path.join(ws.assistantDir, '.opencode/skills/schedule-management/SKILL.md'), 'utf8') const repoSkill = await readFile(path.join(ws.assistantDir, '.opencode/skills/repo-management/SKILL.md'), 'utf8') + const sessionSkill = await readFile(path.join(ws.assistantDir, '.opencode/skills/session-management/SKILL.md'), 'utf8') const assistantAgent = await readFile(path.join(ws.assistantDir, '.opencode/agents/assistant.md'), 'utf8') expect(agentsMd).toContain('.opencode/agents/assistant.md') @@ -192,6 +220,9 @@ describe('ensureAssistantMode', () => { expect(repoSkill).toContain('GET /repos') expect(repoSkill).not.toContain('Authorization: Bearer') expect(repoSkill).not.toContain('.opencode/internal-token') + expect(sessionSkill).toContain('name: session-management') + expect(sessionSkill).toContain('GET /sessions') + expect(sessionSkill).not.toContain('Authorization: Bearer') expect(assistantAgent).toContain('mode: primary') expect(assistantAgent).toContain('Default OpenCode Manager assistant workspace agent') expect(assistantAgent).not.toContain('v file') @@ -212,6 +243,7 @@ describe('ensureAssistantMode', () => { const notificationsSkillPath = path.join(ws.assistantDir, '.opencode/skills/notifications/SKILL.md') const settingsSkillPath = path.join(ws.assistantDir, '.opencode/skills/manager-settings/SKILL.md') const reposSkillPath = path.join(ws.assistantDir, '.opencode/skills/repo-management/SKILL.md') + const sessionsSkillPath = path.join(ws.assistantDir, '.opencode/skills/session-management/SKILL.md') const assistantAgentPath = path.join(ws.assistantDir, '.opencode/agents/assistant.md') const opencodeJsonContent = await readFile(opencodeJsonPath, 'utf8') @@ -262,6 +294,10 @@ describe('ensureAssistantMode', () => { expect(reposSkillContent).toContain('name: repo-management') expect(reposSkillContent).toContain('List repos available') + const sessionsSkillContent = await readFile(sessionsSkillPath, 'utf8') + expect(sessionsSkillContent).toContain('name: session-management') + expect(sessionsSkillContent).toContain('Create and follow up') + const assistantAgentContent = await readFile(assistantAgentPath, 'utf8') expect(assistantAgentContent).toContain('mode: primary') expect(assistantAgentContent).toContain('Self-Editing') @@ -274,6 +310,8 @@ describe('ensureAssistantMode', () => { expect(result.files.agentsMd?.exists).toBe(true) expect(result.repoManagementSkill?.path).toBe(reposSkillPath) expect(result.repoManagementSkill?.created).toBe(true) + expect(result.sessionManagementSkill?.path).toBe(sessionsSkillPath) + expect(result.sessionManagementSkill?.created).toBe(true) expect(result.defaultAgent?.name).toBe('assistant') expect(result.defaultAgent?.path).toBe(assistantAgentPath) expect(result.defaultAgent?.exists).toBe(true) @@ -287,6 +325,8 @@ describe('ensureAssistantMode', () => { expect(status.repoManagementSkill?.path).toBe(path.join(ws.assistantDir, '.opencode/skills/repo-management/SKILL.md')) expect(status.repoManagementSkill?.created).toBe(false) + expect(status.sessionManagementSkill?.path).toBe(path.join(ws.assistantDir, '.opencode/skills/session-management/SKILL.md')) + expect(status.sessionManagementSkill?.created).toBe(false) }) it('preserves custom assistant agent content on subsequent ensureAssistantMode calls', async () => { diff --git a/backend/test/services/opencode-manager-tool-plugin.test.ts b/backend/test/services/opencode-manager-tool-plugin.test.ts index 79fb8814..c2bd023b 100644 --- a/backend/test/services/opencode-manager-tool-plugin.test.ts +++ b/backend/test/services/opencode-manager-tool-plugin.test.ts @@ -255,6 +255,30 @@ describe('ocm-manager plugin', () => { } }) + it('allows session routes and rejects session deletion', async () => { + const tool = await loadTool(configHome) + const allowedRoutes = [ + ['POST', '/sessions'], + ['GET', '/sessions/abc/reply'], + ] as const + + for (const [method, path] of allowedRoutes) { + const fetchMock = jsonResponse({}) + vi.stubGlobal('fetch', fetchMock) + + await runTool(tool, { action: 'request', params: { method, path } }) + + expect(fetchMock).toHaveBeenCalledTimes(1) + } + + const fetchMock = jsonResponse({}) + vi.stubGlobal('fetch', fetchMock) + + await expect(runTool(tool, { action: 'request', params: { method: 'DELETE', path: '/sessions/abc' } })) + .rejects.toThrow(/is not an allowed OpenCode Manager route/) + expect(fetchMock).not.toHaveBeenCalled() + }) + it('rejects non-allow-listed routes without calling the API', async () => { const tool = await loadTool(configHome) const deniedRoutes = [ @@ -264,6 +288,7 @@ describe('ocm-manager plugin', () => { ['POST', '/notifications/send'], ['DELETE', '/settings'], ['PUT', '/opencode-config'], + ['DELETE', '/sessions/abc'], ] as const for (const [method, path] of deniedRoutes) { diff --git a/shared/src/schemas/index.ts b/shared/src/schemas/index.ts index c106483d..bc6f2e5f 100644 --- a/shared/src/schemas/index.ts +++ b/shared/src/schemas/index.ts @@ -13,4 +13,5 @@ export * from './internal-assistant' export * from './session-pins' export * from './session-permissions' export * from './session-goals' +export * from './internal-sessions' export * from './logs' diff --git a/shared/src/schemas/internal-sessions.ts b/shared/src/schemas/internal-sessions.ts new file mode 100644 index 00000000..04499c6d --- /dev/null +++ b/shared/src/schemas/internal-sessions.ts @@ -0,0 +1,31 @@ +import { z } from "zod"; + +export const InternalCreateSessionRequestSchema = z + .object({ + repoId: z.number().int(), + prompt: z.string().trim().min(1).max(20000), + title: z.string().max(200).optional(), + model: z.string().optional(), + agent: z.string().optional(), + worktree: z.boolean().optional(), + ref: z.string().optional(), + }) + .strict(); + +export type InternalCreateSessionRequest = z.infer; + +export const InternalSessionPromptRequestSchema = z + .object({ + text: z.string().trim().min(1).max(20000), + }) + .strict(); + +export type InternalSessionPromptRequest = z.infer; + +export const InternalForkSessionRequestSchema = z + .object({ + beforeMessageId: z.string().optional(), + }) + .strict(); + +export type InternalForkSessionRequest = z.infer; diff --git a/shared/src/schemas/repo.ts b/shared/src/schemas/repo.ts index 3e2923ef..0c1cd659 100644 --- a/shared/src/schemas/repo.ts +++ b/shared/src/schemas/repo.ts @@ -96,6 +96,10 @@ export const AssistantModeStatusSchema = z.object({ path: z.string(), created: z.boolean(), }).optional(), + sessionManagementSkill: z.object({ + path: z.string(), + created: z.boolean(), + }).optional(), defaultAgent: z.object({ name: z.literal('assistant'), path: z.string(),