feat(sessions): add permission modes, session goals, ocm session tool and multi-run

Per-session permission modes: each root session runs in ask or auto.
Auto answers each permission request once from the backend, child
sessions inherit their root's mode, forks copy the source's mode, and
scheduled runs and agent-created sessions stay on ask. A lock reason
reports why a session's mode cannot change.

Session goals: arm a goal in the composer and a backend audit loop keeps
the session working until an auditor model returns done or blocked. The
loop is bounded by continuation and token limits, survives restarts, and
pushes an outcome notification. Goals cannot start on scheduled-run or
child sessions.

ocm session tool: allow-listed internal routes to list, create, follow up
on, read replies from, and fork sessions. Created and forked sessions are
pinned to ask, listing covers a repo's workspaces, and replies wait for
the session to settle with a capped response.

Multi-run: launch one prompt on up to five models, optionally each in its
own OpenCode workspace, with per-entry status and discard.

Also add the shared owners this group needed (session launcher, session
reply, workspace create/remove, multi-run storage) and update the feature
docs.
This commit is contained in:
Chris Scott committed 2026-10-03 21:16:05 -04:00
1 parent 2af2577af8
commit 96e02e9646
91 files changed
+2140 -688

No files matched your search

+28 -7
View File
@@ -3,7 +3,6 @@ import type { MultiRunEntryStatus } from '@opencode-manager/shared/schemas'
export interface MultiRunEntryRecord {
id: number
multiRunId: number
model: string
status: MultiRunEntryStatus
sessionId: string | null
@@ -138,7 +137,7 @@ export function getMultiRun(db: Database, id: number): MultiRunRecord | null {
if (!row) {
return null
}
return mapMultiRunRow(db, row)
return toMultiRunRecord(row, loadEntries(db, row.id))
}
export function listMultiRuns(db: Database, repoId: number, limit: number): MultiRunRecord[] {
@@ -150,7 +149,28 @@ export function listMultiRuns(db: Database, repoId: number, limit: number): Mult
LIMIT ?
`)
.all(repoId, limit) as MultiRunRow[]
return rows.map((row) => mapMultiRunRow(db, row))
if (rows.length === 0) {
return []
}
const placeholders = rows.map(() => '?').join(', ')
const entryRows = db
.prepare(`
SELECT ${MULTI_RUN_ENTRY_COLUMNS} FROM multi_run_entries
WHERE multi_run_id IN (${placeholders})
ORDER BY multi_run_id ASC, id ASC
`)
.all(...rows.map((row) => row.id)) as MultiRunEntryRow[]
const entriesByRun = new Map<number, MultiRunEntryRow[]>()
for (const row of rows) {
entriesByRun.set(row.id, [])
}
for (const entryRow of entryRows) {
entriesByRun.get(entryRow.multi_run_id)?.push(entryRow)
}
return rows.map((row) => toMultiRunRecord(row, entriesByRun.get(row.id) ?? []))
}
export function getMultiRunEntry(db: Database, multiRunId: number, entryId: number): MultiRunEntryRecord | null {
@@ -211,11 +231,13 @@ export function updateMultiRunEntry(
return getMultiRunEntry(db, row.multi_run_id, entryId)
}
function mapMultiRunRow(db: Database, row: MultiRunRow): MultiRunRecord {
const entries = db
function loadEntries(db: Database, multiRunId: number): MultiRunEntryRow[] {
return db
.prepare(`SELECT ${MULTI_RUN_ENTRY_COLUMNS} FROM multi_run_entries WHERE multi_run_id = ? ORDER BY id ASC`)
.all(row.id) as MultiRunEntryRow[]
.all(multiRunId) as MultiRunEntryRow[]
}
function toMultiRunRecord(row: MultiRunRow, entries: MultiRunEntryRow[]): MultiRunRecord {
return {
id: row.id,
repoId: row.repo_id,
@@ -231,7 +253,6 @@ function mapMultiRunRow(db: Database, row: MultiRunRow): MultiRunRecord {
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,
+9 -5
View File
@@ -346,9 +346,13 @@ export function deleteRepo(db: Database, id: number): void {
return
}
for (const table of TABLES_WITH_REPO_ID) {
db.prepare(`DELETE FROM ${table} WHERE repo_id = ?`).run(id)
}
const stmt = db.prepare('DELETE FROM repos WHERE id = ?')
stmt.run(id)
const remove = db.transaction(() => {
db.prepare('DELETE FROM multi_run_entries WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)').run(id)
db.prepare('DELETE FROM multi_runs WHERE repo_id = ?').run(id)
for (const table of TABLES_WITH_REPO_ID) {
db.prepare(`DELETE FROM ${table} WHERE repo_id = ?`).run(id)
}
db.prepare('DELETE FROM repos WHERE id = ?').run(id)
})
remove()
}
+11 -8
View File
@@ -233,13 +233,16 @@ const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktree
const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
const notificationService = new NotificationService(db)
const sessionPermissionModeService = new SessionPermissionModeService(db, openCodeClient, settingsServiceForSchedules)
const sessionGoalService = new SessionGoalService(db, openCodeClient, settingsServiceForSchedules, {
const sessionSettingsService = new SettingsService(db)
const sessionPermissionModeService = new SessionPermissionModeService(db, openCodeClient, sessionSettingsService)
const sessionGoalService = new SessionGoalService(db, openCodeClient, sessionSettingsService, {
onOutcome: (goal) => {
void notificationService.notifyGoalOutcome(goal).catch((error) => {
logger.error('Goal outcome notification error:', error)
})
},
resolveSessionLock: async (sessionId) =>
(await sessionPermissionModeService.getEffectiveMode(sessionId)).lockedReason,
})
sessionGoalService.loadOpenGoals()
@@ -259,11 +262,6 @@ notificationService.addEventSuppressor(async (event, sessionId) => {
return (await sessionPermissionModeService.getEffectiveMode(sessionId)).mode === 'auto'
})
notificationService.addEventSuppressor(async (event, sessionId) => {
if (event.type !== 'session.idle' || !sessionId) return false
return sessionGoalService.hasActiveGoal(sessionId)
})
if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
if (!ENV.VAPID.SUBJECT) {
logger.warn('VAPID_SUBJECT is not set — push notifications require a mailto: subject (e.g. mailto:you@example.com)')
@@ -285,6 +283,11 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
sseAggregator.setPendingActionsFetcher(openCodeClient)
sseAggregator.setPasswordResolver(() => new SettingsService(db).getOpenCodeServerPassword())
sseAggregator.onUpstreamConnected(() => {
void sessionPermissionModeService.acceptPendingRequestsForActiveSessions().catch((err) => {
logger.error('Failed to accept pending permission requests for active sessions:', err)
})
})
sseAggregator.start()
void sessionGoalService.recoverOpenGoals().catch((error) => {
@@ -304,7 +307,7 @@ app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
app.route('/api/health', createHealthRoutes(db, openCodeSupervisor))
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(openCodeClient, requireAuth))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService))
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService))
const protectedApi = new Hono()
+3 -1
View File
@@ -17,6 +17,7 @@ import { createInternalSessionRoutes } from './sessions'
import { createInternalAssistantRoutes } from './assistant'
import { createInternalGitCredentialsRoutes } from './git-credentials'
import { createInternalSandboxRoutes } from './sandbox'
import type { SessionPermissionModeService } from '../../services/session-permission-modes'
export function createInternalRoutes(
db: Database,
@@ -24,6 +25,7 @@ export function createInternalRoutes(
notificationService: NotificationService,
settingsService: SettingsService,
openCodeClient: OpenCodeClient,
permissionModes: SessionPermissionModeService,
) {
const app = new Hono()
app.use('/*', createInternalTokenMiddleware(db))
@@ -38,7 +40,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('/sessions', createInternalSessionRoutes(db, openCodeClient, permissionModes))
app.route('/assistant', createInternalAssistantRoutes(openCodeClient))
app.route('/git-credentials', createInternalGitCredentialsRoutes(db))
app.route('/sandbox', createInternalSandboxRoutes(db))
+65 -76
View File
@@ -6,18 +6,25 @@ import {
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 { buildSessionPath } from '@opencode-manager/shared/utils'
import { getRepoById } from '../../db/queries'
import { handleOpenCodeError, parseJsonBody } from '../../utils/route-helpers'
import type { OpenCodeClient } from '../../services/opencode/client'
import type { SessionPermissionModeService } from '../../services/session-permission-modes'
import { SessionLaunchError, SessionLauncher } from '../../services/session-launcher'
import { isSessionBusy, readLatestAssistantReply } from '../../services/session-reply'
import {
isSessionBusy,
readLatestAssistantReply,
truncateSessionReply,
waitForSessionSettled,
} from '../../services/session-reply'
import { resolveRepoForDirectory, resolveRepoProjectId } from '../../services/repo'
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 INTERNAL_SESSION_REPLY_WAIT_MAX_MS = 45000
const ListSessionsQuerySchema = z.object({
repoId: z.coerce.number().int().optional(),
@@ -29,41 +36,22 @@ const ListSessionsQuerySchema = z.object({
.default(INTERNAL_SESSION_LIST_LIMIT_DEFAULT),
})
type JsonBodyResult = { ok: true; value: unknown } | { ok: false }
const ReplyQuerySchema = z.object({
waitMs: z.coerce.number().int().min(0).max(INTERNAL_SESSION_REPLY_WAIT_MAX_MS).optional(),
})
async function readJsonBody(c: Context): Promise<JsonBodyResult> {
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 } } {
function handleSessionRouteError(c: Context, error: unknown) {
if (error instanceof SessionLaunchError) {
return { status: error.status, body: { error: error.message } }
return c.json({ error: error.message }, error.status)
}
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) } }
return handleOpenCodeError(c, error, 'Internal session request failed', { unknownStatus: 502 })
}
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) {
export function createInternalSessionRoutes(
db: Database,
openCodeClient: OpenCodeClient,
permissionModes: SessionPermissionModeService,
) {
const app = new Hono()
const sessionLauncher = new SessionLauncher(db, openCodeClient)
@@ -80,23 +68,28 @@ export function createInternalSessionRoutes(db: Database, openCodeClient: OpenCo
}
try {
const project = repo ? await resolveRepoProjectId(openCodeClient, repo.fullPath) : undefined
const response = await openCodeClient.api.session.list({
limit,
order: 'desc',
parentID: null,
...(repo ? { directory: repo.fullPath } : {}),
...(project ? { project } : {}),
})
const active = await openCodeClient.api.session.active()
const repos = listRepos(db)
const repoIdByDirectory = new Map<string, number | null>()
for (const directory of new Set(response.data.map((session) => session.location.directory))) {
const matchedRepo = await resolveRepoForDirectory(db, directory)
repoIdByDirectory.set(directory, matchedRepo?.id ?? null)
}
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,
repoId: repoIdByDirectory.get(directory) ?? null,
busy: session.id in active,
outcome: session.outcome ?? null,
updated: session.time.updated,
@@ -105,23 +98,17 @@ export function createInternalSessionRoutes(db: Database, openCodeClient: OpenCo
return c.json({ sessions })
} catch (error) {
const mapped = openCodeErrorResponse(error)
return c.json(mapped.body, mapped.status)
return handleSessionRouteError(c, error)
}
})
app.post('/', async (c) => {
const body = await readJsonBody(c)
const body = await parseJsonBody(c, InternalCreateSessionRequestSchema)
if (!body.ok) {
return c.json({ error: 'Invalid JSON' }, 400)
return body.response
}
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
const input = body.data
try {
const launched = await sessionLauncher.launch({
repoId: input.repoId,
@@ -132,50 +119,58 @@ export function createInternalSessionRoutes(db: Database, openCodeClient: OpenCo
...(input.worktree
? {
workspace: {
name: workspaceNameFromTitle(input.title),
name: input.title ?? INTERNAL_SESSION_WORKSPACE_NAME_FALLBACK,
...(input.ref ? { ref: input.ref } : {}),
},
}
: {}),
})
const url = `/repos/${launched.repoId}/sessions/${launched.sessionId}${launched.workspaceDirectory ? '?repoTab=workspaces' : ''}`
permissionModes.pinAsk(launched.sessionId)
const url = buildSessionPath(
launched.repoId,
launched.sessionId,
launched.workspaceDirectory ? { repoTab: 'workspaces' } : undefined,
)
return c.json({ ...launched, url }, 201)
} catch (error) {
const mapped = openCodeErrorResponse(error)
return c.json(mapped.body, mapped.status)
return handleSessionRouteError(c, error)
}
})
app.post('/:sessionId/prompt', async (c) => {
const sessionId = c.req.param('sessionId')
const body = await readJsonBody(c)
const body = await parseJsonBody(c, InternalSessionPromptRequestSchema)
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)
return body.response
}
try {
await openCodeClient.api.session.prompt({
sessionID: sessionId,
text: parsed.data.text,
text: body.data.text,
delivery: 'queue',
})
return c.json({ queued: true }, 202)
} catch (error) {
const mapped = openCodeErrorResponse(error)
return c.json(mapped.body, mapped.status)
return handleSessionRouteError(c, error)
}
})
app.get('/:sessionId/reply', async (c) => {
const sessionId = c.req.param('sessionId')
const parsedQuery = ReplyQuerySchema.safeParse(c.req.query())
if (!parsedQuery.success) {
return c.json({ error: 'Invalid query', details: parsedQuery.error.issues }, 400)
}
try {
const waitMs = parsedQuery.data.waitMs ?? 0
if (waitMs > 0) {
await waitForSessionSettled(openCodeClient, sessionId, waitMs)
}
const [busy, reply] = await Promise.all([
isSessionBusy(openCodeClient, sessionId),
readLatestAssistantReply(openCodeClient, sessionId),
@@ -183,38 +178,32 @@ export function createInternalSessionRoutes(db: Database, openCodeClient: OpenCo
return c.json({
busy,
responseText: reply?.responseText ?? null,
responseText: reply?.responseText ? truncateSessionReply(reply.responseText) : null,
errorText: reply?.errorText ?? null,
completed: reply?.completed ?? false,
})
} catch (error) {
const mapped = openCodeErrorResponse(error)
return c.json(mapped.body, mapped.status)
return handleSessionRouteError(c, error)
}
})
app.post('/:sessionId/fork', async (c) => {
const sessionId = c.req.param('sessionId')
const body = await readJsonBody(c)
const body = await parseJsonBody(c, InternalForkSessionRequestSchema, { allowEmpty: true })
if (!body.ok) {
return c.json({ error: 'Invalid JSON' }, 400)
return body.response
}
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
const beforeMessageId = body.data.beforeMessageId
try {
const forked = await openCodeClient.api.session.fork({
sessionID: sessionId,
...(beforeMessageId ? { before: beforeMessageId } : {}),
})
permissionModes.pinAsk(forked.id)
return c.json({ sessionId: forked.id, directory: forked.location.directory })
} catch (error) {
const mapped = openCodeErrorResponse(error)
return c.json(mapped.body, mapped.status)
return handleSessionRouteError(c, error)
}
})
+4 -11
View File
@@ -1,7 +1,7 @@
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'
import { handleServiceError, parseId, parseJsonBody } from '../utils/route-helpers'
export function createMultiRunRoutes(service: MultiRunService) {
const app = new Hono()
@@ -16,16 +16,9 @@ export function createMultiRunRoutes(service: MultiRunService) {
})
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)
const parsed = await parseJsonBody(c, LaunchMultiRunRequestSchema)
if (!parsed.ok) {
return parsed.response
}
try {
+4 -11
View File
@@ -1,7 +1,7 @@
import { Hono } from 'hono'
import { StartSessionGoalRequestSchema } from '@opencode-manager/shared/schemas'
import { SessionGoalError, type SessionGoalService } from '../services/session-goals'
import { handleServiceError, parseId } from '../utils/route-helpers'
import { handleServiceError, parseId, parseJsonBody } from '../utils/route-helpers'
export function createSessionGoalRoutes(service: SessionGoalService) {
const app = new Hono()
@@ -19,16 +19,9 @@ export function createSessionGoalRoutes(service: SessionGoalService) {
})
app.post('/', async (c) => {
let body: unknown
try {
body = await c.req.json()
} catch {
return c.json({ error: 'Invalid request' }, 400)
}
const parsed = StartSessionGoalRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request' }, 400)
const parsed = await parseJsonBody(c, StartSessionGoalRequestSchema)
if (!parsed.ok) {
return parsed.response
}
try {
+4 -11
View File
@@ -1,7 +1,7 @@
import { Hono } from 'hono'
import { SetSessionPermissionModeRequestSchema } from '@opencode-manager/shared/schemas'
import { SessionPermissionModeError, type SessionPermissionModeService } from '../services/session-permission-modes'
import { handleServiceError } from '../utils/route-helpers'
import { handleServiceError, parseJsonBody } from '../utils/route-helpers'
export function createSessionPermissionModeRoutes(service: SessionPermissionModeService) {
const app = new Hono()
@@ -16,16 +16,9 @@ export function createSessionPermissionModeRoutes(service: SessionPermissionMode
})
app.put('/:sessionId', async (c) => {
let body: unknown
try {
body = await c.req.json()
} catch {
return c.json({ error: 'Invalid request' }, 400)
}
const parsed = SetSessionPermissionModeRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request' }, 400)
const parsed = await parseJsonBody(c, SetSessionPermissionModeRequestSchema)
if (!parsed.ok) {
return parsed.response
}
try {
+9 -7
View File
@@ -932,7 +932,7 @@ Use the \`${MANAGER_TOOL_NAME}\` tool with the \`request\` action. The tool runs
### GET /sessions
List sessions, newest first. Pass \`repoId\` to restrict the list to one repo and \`limit\` (1-50, default 10) to bound it.
List sessions, newest first. Pass \`repoId\` to restrict the list to one repo; this covers every OpenCode workspace of that repo, not only the repo directory. Pass \`limit\` (1-50, default 10) to bound it.
Query params: \`repoId\`, \`limit\`
@@ -953,7 +953,7 @@ Query params: \`repoId\`, \`limit\`
id: string
title: string | null
directory: string
repoId: number | null // null when the directory matches no known repo
repoId: number | null // null when the directory belongs to no known repo
busy: boolean // true while the session is running
outcome: 'succeeded' | 'failed' | 'interrupted' | null
updated: number
@@ -963,9 +963,11 @@ Query params: \`repoId\`, \`limit\`
### 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.
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 read 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.
Sessions created through this tool always start in \`ask\` permission mode; existing sessions keep the mode the user chose.
Pass \`worktree: true\` to run the session in a new isolated workspace instead of the repo directory. Creating a workspace can take tens of seconds; if the request times out it may still have succeeded, so call \`GET /sessions\` before retrying. \`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
{
@@ -1015,14 +1017,14 @@ Queue a follow-up prompt for an existing session.
### 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\`.
Read the latest assistant reply for a session and whether it is still running. Prefer \`?waitMs=30000\` (integer, 0-45000) to wait for the session to settle instead of polling in a loop; the response returns once it settles or the timeout elapses. \`responseText\` is capped.
\`\`\`json
{
"action": "request",
"params": {
"method": "GET",
"path": "/sessions/ses_abc/reply"
"path": "/sessions/ses_abc/reply?waitMs=30000"
}
}
\`\`\`
@@ -1039,7 +1041,7 @@ Read the latest assistant reply for a session and whether it is still running. P
### POST /sessions/:sessionId/fork
Fork a session, optionally before a specific message. Omit \`beforeMessageId\` to fork from the current point.
Fork a session, optionally before a specific message. Omit \`beforeMessageId\` to fork from the current point. The forked session starts in \`ask\` permission mode.
\`\`\`json
{
+45 -21
View File
@@ -1,6 +1,6 @@
import type { Database } from 'bun:sqlite'
import { existsSync } from 'node:fs'
import type { LaunchMultiRunRequest, MultiRun } from '@opencode-manager/shared/schemas'
import { sanitizeRepoDirectoryName } from '@opencode-manager/shared/utils'
import {
createMultiRunWithEntries,
getMultiRun,
@@ -11,11 +11,12 @@ import {
type MultiRunRecord,
} from '../db/multi-runs'
import { getRepoById } from '../db/queries'
import type { Repo } from '../types/repo'
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'
import { removeRepoWorkspace, RepoWorkspaceError } from './repo'
import { requireReadyRepo, SessionLauncher, SessionLaunchError, type LaunchedSession } from './session-launcher'
const MULTI_RUN_LIST_LIMIT = 20
@@ -29,7 +30,7 @@ export class MultiRunError extends Error {
}
}
export function toMultiRun(record: MultiRunRecord): MultiRun {
function toMultiRun(record: MultiRunRecord): MultiRun {
return {
id: record.id,
repoId: record.repoId,
@@ -65,9 +66,11 @@ export class MultiRunService {
}
async launch(request: LaunchMultiRunRequest): Promise<MultiRun> {
const repo = getRepoById(this.db, request.repoId)
if (!repo || repo.cloneStatus !== 'ready') {
throw new MultiRunError('Repository not found or not ready', 404)
let repo: Repo
try {
repo = requireReadyRepo(this.db, request.repoId)
} catch (error) {
throw new MultiRunError(getErrorMessage(error) || 'Repository unavailable', 404)
}
const record = createMultiRunWithEntries(
@@ -82,18 +85,42 @@ export class MultiRunService {
request.models,
)
const slug = sanitizeRepoDirectoryName(request.name)
const results = await Promise.allSettled(
record.entries.map((entry, index) => this.launchEntry(entry, index, request, slug)),
const validations = await Promise.all(
record.entries.map(async (entry) => {
try {
await this.sessionLauncher.resolveModel(repo, entry.model)
return { entry, ok: true as const }
} catch (error) {
return { entry, ok: false as const, error }
}
}),
)
results.forEach((result, index) => {
const entry = record.entries[index]
if (!entry) {
const launchable: Array<{ entry: MultiRunEntryRecord; index: number }> = []
validations.forEach((validation, index) => {
if (validation.ok) {
launchable.push({ entry: validation.entry, index })
return
}
updateMultiRunEntry(this.db, validation.entry.id, ['starting'], {
status: 'failed',
error: getErrorMessage(validation.error) || 'Failed to launch session',
})
})
const results = await Promise.allSettled(
launchable.map(({ entry, index }) => this.launchEntry(entry, index, request)),
)
results.forEach((result, resultIndex) => {
const launch = launchable[resultIndex]
if (!launch) {
return
}
if (result.status === 'fulfilled') {
updateMultiRunEntry(this.db, entry.id, ['starting'], {
updateMultiRunEntry(this.db, launch.entry.id, ['starting'], {
status: 'started',
sessionId: result.value.sessionId,
directory: result.value.directory,
@@ -103,7 +130,7 @@ export class MultiRunService {
const workspaceDirectory =
result.reason instanceof SessionLaunchError ? result.reason.workspaceDirectory : null
updateMultiRunEntry(this.db, entry.id, ['starting'], {
updateMultiRunEntry(this.db, launch.entry.id, ['starting'], {
status: 'failed',
error: getErrorMessage(result.reason) || 'Failed to launch session',
...(workspaceDirectory ? { directory: workspaceDirectory } : {}),
@@ -138,7 +165,7 @@ export class MultiRunService {
this.discardingEntries.add(entryId)
try {
if (entry.isolated && entry.directory) {
if (entry.isolated && entry.directory && existsSync(entry.directory)) {
const repo = getRepoById(this.db, record.repoId)
if (!repo) {
throw new MultiRunError('Repository not found', 404)
@@ -153,9 +180,7 @@ export class MultiRunService {
entry.directory,
)
} catch (error) {
const status = typeof (error as { status?: unknown }).status === 'number'
? (error as { status: number }).status
: 502
const status = error instanceof RepoWorkspaceError ? error.status : 502
throw new MultiRunError(getErrorMessage(error) || 'Failed to remove workspace', status)
}
}
@@ -175,7 +200,6 @@ export class MultiRunService {
entry: MultiRunEntryRecord,
index: number,
request: LaunchMultiRunRequest,
slug: string,
): Promise<LaunchedSession> {
return this.sessionLauncher.launch({
repoId: request.repoId,
@@ -184,7 +208,7 @@ export class MultiRunService {
title: `${request.name} · ${entry.model}`,
...(request.agent ? { agent: request.agent } : {}),
...(request.isolate
? { workspace: { name: `${slug}-${index + 1}`, ...(request.baseRef ? { ref: request.baseRef } : {}) } }
? { workspace: { name: `${request.name}-${index + 1}`, ...(request.baseRef ? { ref: request.baseRef } : {}) } }
: {}),
})
}
+45 -91
View File
@@ -2,34 +2,30 @@ import { Database } from "bun:sqlite";
import webpush from "web-push";
import { logger } from "../utils/logger";
import type { PushSubscriptionRecord } from "../types/settings";
import type { PushNotificationPayload } from "@opencode-manager/shared/types";
import type {
NotificationPreferences,
PushNotificationPayload,
} from "@opencode-manager/shared/types";
import {
NotificationEventType,
DEFAULT_NOTIFICATION_PREFERENCES,
type SessionGoal,
type SessionGoalStatus,
type SessionGoalStopReason,
} from "@opencode-manager/shared/schemas";
import {
getPermissionLabel,
getPermissionDetail,
getFormText,
getGoalOutcomeTitle,
getGoalStopReasonLabel,
} from "@opencode-manager/shared/notifications";
import { SettingsService } from "./settings";
import { sseAggregator, type SSEEvent } from "./sse-aggregator";
import {
getRepoByLocalPath,
getRepoBySourcePath,
getRepoName,
listRepos,
} from "../db/queries";
import { getRepoName } from "../db/queries";
import { getScheduleRunBySessionId } from "../db/schedules";
import type { Repo } from "../types/repo";
import { getReposPath } from "@opencode-manager/shared/config/env";
import { ASSISTANT_REPO_ID } from "@opencode-manager/shared/utils";
import { buildSessionPath } from "@opencode-manager/shared/utils";
import { sessionIDFromEvent } from "@opencode-manager/shared/opencode";
import { resolveProjectId } from "./project-id-resolver";
import path from "path";
import { resolveRepoForDirectory } from "./repo";
interface VapidConfig {
publicKey: string;
@@ -80,31 +76,6 @@ const RUN_OUTCOME_EVENTS = new Set<string>([
NotificationEventType.SESSION_FAILED,
]);
const GOAL_OUTCOME_TITLES: Record<SessionGoalStatus, string> = {
active: "Goal active",
paused: "Goal paused",
completed: "Goal completed",
blocked: "Goal blocked",
stopped: "Goal stopped",
};
const GOAL_STOP_REASON_LABELS: Record<SessionGoalStopReason, string> = {
cancelled: "Cancelled",
user_paused: "Paused by user",
continuation_limit: "Continuation limit reached",
token_budget: "Token budget reached",
turn_error: "Turn failed",
interrupted: "Interrupted",
audit_failed: "Audit failed",
session_deleted: "Session deleted",
};
function truncateNotificationBody(rawBody: string): string {
return rawBody.length > MAX_BODY_LENGTH
? `${rawBody.slice(0, MAX_BODY_LENGTH - 1)}…`
: rawBody;
}
function truncateWithEllipsis(text: string, maxLength: number): string {
if (maxLength <= 0) return "";
if (text.length <= maxLength) return text;
@@ -114,7 +85,7 @@ function truncateWithEllipsis(text: string, maxLength: number): string {
function buildGoalOutcomeBody(goal: SessionGoal, repoName: string | undefined): string {
const reason = goal.stopReason
? GOAL_STOP_REASON_LABELS[goal.stopReason]
? getGoalStopReasonLabel(goal.stopReason)
: goal.lastReason?.trim() || undefined;
const prefix = repoName ? `${repoName} · ` : "";
const separator = " — ";
@@ -126,7 +97,7 @@ function buildGoalOutcomeBody(goal: SessionGoal, repoName: string | undefined):
const objectiveBudget = Math.max(0, MAX_BODY_LENGTH - prefix.length - suffix.length);
const objective = truncateWithEllipsis(goal.objective, objectiveBudget);
return truncateNotificationBody(`${prefix}${objective}${suffix}`);
return truncateWithEllipsis(`${prefix}${objective}${suffix}`, MAX_BODY_LENGTH);
}
function resolveEventSessionId(event: SSEEvent): string | undefined {
@@ -146,8 +117,7 @@ export function buildNotificationUrl(
): string {
if (!repo) return "/";
if (!sessionId) return `/repos/${repo.id}`;
const suffix = repo.id === ASSISTANT_REPO_ID ? "?assistant=1" : "";
return `/repos/${repo.id}/sessions/${sessionId}${suffix}`;
return buildSessionPath(repo.id, sessionId);
}
export function buildEventNotificationPayload(
@@ -169,7 +139,7 @@ export function buildEventNotificationPayload(
const rawBody = context.repoName
? `${context.repoName} · ${detail}`
: detail;
const body = truncateNotificationBody(rawBody);
const body = truncateWithEllipsis(rawBody, MAX_BODY_LENGTH);
return {
title,
@@ -345,25 +315,24 @@ export class NotificationService {
return run ? buildScheduleRunReportUrl(run.id) : null;
}
private async resolveRepoForDirectory(directory: string): Promise<Repo | null> {
const repo =
getRepoBySourcePath(this.db, path.resolve(directory)) ??
getRepoByLocalPath(this.db, path.relative(getReposPath(), directory));
if (repo) return repo;
private async deliverToSubscribers(
payload: PushNotificationPayload,
shouldNotify: (preferences: NotificationPreferences) => boolean
): Promise<void> {
if (!this.isConfigured()) return;
const projectId = await resolveProjectId(directory);
if (!projectId) return null;
const userIds = this.getAllUserIds();
if (userIds.length === 0) return;
const readyRepos = listRepos(this.db).filter(
(candidate) => candidate.cloneStatus === "ready"
);
for (const candidate of readyRepos) {
const candidateProjectId = await resolveProjectId(candidate.fullPath).catch(
() => null
);
if (candidateProjectId === projectId) return candidate;
for (const userId of userIds) {
const settings = this.settingsService.getSettings(userId);
const notifPrefs =
settings.preferences.notifications ?? DEFAULT_NOTIFICATION_PREFERENCES;
if (!shouldNotify(notifPrefs)) continue;
await this.sendToUser(userId, payload);
}
return null;
}
async handleSSEEvent(
@@ -381,12 +350,7 @@ export class NotificationService {
if (await suppressor(event, sessionId)) return;
}
if (!this.isConfigured()) return;
const userIds = this.getAllUserIds();
if (userIds.length === 0) return;
const repo = directory ? await this.resolveRepoForDirectory(directory) : null;
const repo = directory ? await resolveRepoForDirectory(this.db, directory) : null;
const repoId = repo?.id;
const repoName = repo ? getRepoName(repo) : undefined;
const reportUrl = RUN_OUTCOME_EVENTS.has(event.type) ? this.getScheduleRunReportUrl(sessionId) : null;
@@ -401,31 +365,26 @@ export class NotificationService {
});
if (!payload) return;
for (const userId of userIds) {
const settings = this.settingsService.getSettings(userId);
const notifPrefs =
settings.preferences.notifications ?? DEFAULT_NOTIFICATION_PREFERENCES;
if (!notifPrefs.enabled) continue;
if (!notifPrefs.events[config.preferencesKey]) continue;
await this.sendToUser(userId, payload);
}
await this.deliverToSubscribers(
payload,
(preferences) =>
preferences.enabled &&
preferences.events[config.preferencesKey] === true
);
}
async notifyGoalOutcome(goal: SessionGoal): Promise<void> {
if (!this.isConfigured()) return;
const userIds = this.getAllUserIds();
if (userIds.length === 0) return;
if (goal.stopReason === "turn_error") return;
if (goal.stopReason === "cancelled" || goal.stopReason === "user_paused") return;
if (sseAggregator.isSessionBeingViewed(goal.sessionId)) return;
const repo = goal.directory
? await this.resolveRepoForDirectory(goal.directory)
? await resolveRepoForDirectory(this.db, goal.directory)
: null;
const repoName = repo ? getRepoName(repo) : undefined;
const payload: PushNotificationPayload = {
title: GOAL_OUTCOME_TITLES[goal.status],
title: getGoalOutcomeTitle(goal.status),
body: buildGoalOutcomeBody(goal, repoName),
tag: `session-goal-${goal.id}`,
timestamp: Date.now(),
@@ -440,16 +399,11 @@ export class NotificationService {
},
};
for (const userId of userIds) {
const settings = this.settingsService.getSettings(userId);
const notifPrefs =
settings.preferences.notifications ?? DEFAULT_NOTIFICATION_PREFERENCES;
if (!notifPrefs.enabled) continue;
if (notifPrefs.events.goalOutcome === false) continue;
await this.sendToUser(userId, payload);
}
await this.deliverToSubscribers(
payload,
(preferences) =>
preferences.enabled && preferences.events.goalOutcome !== false
);
}
async sendTestNotification(userId: string): Promise<void> {
@@ -3,7 +3,7 @@ import { ASSISTANT_NOTIFICATION_LIMITS } from '@opencode-manager/shared/schemas'
export const MANAGER_TOOL_NAME = 'ocm'
const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 15000
const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 60000
export const MANAGER_TOOL_ALLOWED_ROUTES = [
'GET /settings',
+27 -3
View File
@@ -121,7 +121,7 @@ function buildWorkspaceAliasCandidates(sourcePath: string, rootPath?: string): s
if (relativePath && !relativePath.startsWith('..')) {
const relativeAlias = relativePath
.split(path.sep)
.map(sanitizeRepoDirectoryName)
.map((segment) => sanitizeRepoDirectoryName(segment))
.filter(Boolean)
.join('--')
@@ -1168,6 +1168,30 @@ export async function resolveRepoProjectId(openCodeClient: OpenCodeClient, direc
return project.id
}
export async function resolveRepoForDirectory(
database: Database,
directory: string,
): Promise<Repo | null> {
const repo =
getRepoBySourcePath(database, path.resolve(directory)) ??
getRepoByLocalPath(database, path.relative(getReposPath(), directory))
if (repo) return repo
const projectId = await resolveProjectId(directory)
if (!projectId) return null
const readyRepos = listRepos(database).filter(
(candidate) => candidate.cloneStatus === 'ready',
)
for (const candidate of readyRepos) {
const candidateProjectId = await resolveProjectId(candidate.fullPath).catch(
() => null,
)
if (candidateProjectId === projectId) return candidate
}
return null
}
export async function getSiblingRepos(
database: Database,
repoId: number,
@@ -1265,9 +1289,9 @@ export async function getSiblingRepos(
}
export class RepoWorkspaceError extends Error {
readonly status: 400 | 404
readonly status: 400
constructor(message: string, status: 400 | 404) {
constructor(message: string, status: 400) {
super(message)
this.name = 'RepoWorkspaceError'
this.status = status
+6 -35
View File
@@ -7,7 +7,7 @@ import {
type ScheduleRunTriggerSource,
type UpdateScheduleJobRequest,
} from '@opencode-manager/shared/types'
import { mcpStatusByName, openCodeLocation, sessionIDFromEvent } from '@opencode-manager/shared/opencode'
import { mcpStatusByName, openCodeLocation } from '@opencode-manager/shared/opencode'
import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
import { getRepoById } from '../db/queries'
import type { ScheduleJobWithRepo } from '../db/schedules'
@@ -46,11 +46,11 @@ import {
computeNextRunAtForJob,
} from './schedule-config'
import { resolveOpenCodeModel } from './opencode-models'
import { isSessionBusy, readLatestAssistantReply, type AssistantReplyState } from './session-reply'
import { isSessionBusy, readLatestAssistantReply, sessionSettleSignal, type AssistantReplyState } from './session-reply'
import type { OpenCodeClient } from './opencode/client'
import type { ScheduleWorktreeManager } from './schedule-worktree'
import type { Repo } from '../types/repo'
import { sseAggregator, type SSEEvent, type ScheduledSessionRef } from './sse-aggregator'
import { sseAggregator, type ScheduledSessionRef } from './sse-aggregator'
import { getErrorMessage } from '../utils/error-utils'
import { logger } from '../utils/logger'
import { buildAssistantRepo } from './assistant-mode'
@@ -166,18 +166,6 @@ function buildRunStartedLog(input: {
].join('\n')
}
function getSessionErrorText(event: SSEEvent): string | null {
if (event.type !== 'session.execution.failed') {
return null
}
return event.data.error.message || null
}
function getSessionStatusType(event: SSEEvent): string | null {
return event.type === 'session.status' ? event.data.status.type : null
}
function createSessionMonitor(directory: string, sessionId: string): SessionMonitor {
const queued: SessionSignal[] = []
let waiting: ((signal: SessionSignal) => void) | null = null
@@ -198,26 +186,9 @@ function createSessionMonitor(directory: string, sessionId: string): SessionMoni
return
}
if (sessionIDFromEvent(event) !== sessionId) {
return
}
if (event.type === 'session.execution.failed') {
push({ errorText: getSessionErrorText(event) ?? 'The session reported an unknown error.', disposed: false })
return
}
if (event.type === 'session.execution.interrupted') {
push({ errorText: 'The session execution was interrupted.', disposed: false })
return
}
if (
event.type === 'session.idle'
|| event.type === 'session.execution.succeeded'
|| (event.type === 'session.status' && getSessionStatusType(event) === 'idle')
) {
push({ errorText: null, disposed: false })
const signal = sessionSettleSignal(event, sessionId)
if (signal) {
push({ errorText: signal.errorText, disposed: false })
}
})
+2 -5
View File
@@ -1,6 +1,6 @@
import { SessionGoalVerdictSchema, type SessionGoalVerdict } from '@opencode-manager/shared/schemas'
import { truncateSessionReply } from './session-reply'
export const GOAL_AUDIT_REPLY_MAX_CHARS = 20000
export const GOAL_AUDIT_REASON_MAX_CHARS = 500
export const GOAL_AUDIT_UNPARSED_REASON = 'Auditor response was not understood'
@@ -89,10 +89,7 @@ function truncateReply(reply: string | null): string {
if (!reply) {
return '(no reply yet)'
}
if (reply.length <= GOAL_AUDIT_REPLY_MAX_CHARS) {
return reply
}
return `${reply.slice(0, GOAL_AUDIT_REPLY_MAX_CHARS)}\n\n[reply truncated]`
return truncateSessionReply(reply)
}
function extractFirstJsonObject(text: string): string | null {
+23 -6
View File
@@ -5,6 +5,7 @@ import {
type SessionGoalStatus,
type SessionGoalStopReason,
type SessionGoalTurnState,
type SessionLockReason,
type StartSessionGoalRequest,
} from '@opencode-manager/shared/schemas'
import {
@@ -45,6 +46,7 @@ type PrerequisiteResult<T> = { ok: true; value: T } | { ok: false }
export interface SessionGoalServiceOptions {
quietMs?: number
onOutcome?: (goal: SessionGoal) => void
resolveSessionLock?: (sessionId: string) => Promise<SessionLockReason | null>
}
export class SessionGoalError extends Error {
@@ -60,7 +62,7 @@ export function sessionTokenTotal(tokens: { input: number; output: number; reaso
return tokens.input + tokens.output + tokens.reasoning
}
export function toSessionGoal(record: SessionGoalRecord): SessionGoal {
function toSessionGoal(record: SessionGoalRecord): SessionGoal {
return {
id: record.id,
sessionId: record.sessionId,
@@ -91,6 +93,7 @@ export class SessionGoalService {
private readonly auditGeneration = new Map<string, number>()
private readonly quietMs: number
private readonly onOutcome: (goal: SessionGoal) => void
private readonly resolveSessionLock: (sessionId: string) => Promise<SessionLockReason | null>
constructor(
private readonly db: Database,
@@ -100,6 +103,7 @@ export class SessionGoalService {
) {
this.quietMs = options.quietMs ?? DEFAULT_QUIET_MS
this.onOutcome = options.onOutcome ?? (() => {})
this.resolveSessionLock = options.resolveSessionLock ?? (async () => null)
}
loadOpenGoals(): void {
@@ -180,6 +184,8 @@ export class SessionGoalService {
}
async start(input: StartSessionGoalRequest): Promise<SessionGoal> {
await this.assertSessionCanStartGoal(input.sessionId)
const defaults = this.settingsService.getSettings().preferences.sessionDefaults
const maxContinuations =
input.maxContinuations ?? defaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations
@@ -208,8 +214,21 @@ export class SessionGoalService {
return record ? toSessionGoal(record) : null
}
hasActiveGoal(sessionId: string): boolean {
return getLatestSessionGoal(this.db, sessionId)?.status === 'active'
private async assertSessionCanStartGoal(sessionId: string): Promise<void> {
let lock: SessionLockReason | null
try {
lock = await this.resolveSessionLock(sessionId)
} catch (error) {
logger.error(`Failed to resolve session lock for ${sessionId}:`, error)
return
}
if (lock === 'schedule') {
throw new SessionGoalError('Scheduled runs cannot run goals', 409)
}
if (lock === 'child') {
throw new SessionGoalError('Goals can only be started on top-level sessions', 400)
}
}
pause(id: number): SessionGoal {
@@ -601,7 +620,7 @@ export class SessionGoalService {
}
private transition(id: number, fromStatuses: SessionGoalStatus[], patch: SessionGoalPatch): SessionGoalRecord {
const record = transitionSessionGoal(this.db, id, fromStatuses, patch)
const record = this.applyTransition(id, fromStatuses, patch)
if (!record) {
if (!getSessionGoalById(this.db, id)) {
throw new SessionGoalError('Session goal not found', 404)
@@ -609,8 +628,6 @@ export class SessionGoalService {
throw new SessionGoalError('Session goal cannot transition from its current state', 409)
}
this.syncGoalIndex(record)
this.maybeInvalidateAudits(record, patch)
return record
}
+39 -42
View File
@@ -1,12 +1,14 @@
import type { Database } from 'bun:sqlite'
import { openCodeLocation, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import { sanitizeRepoDirectoryName } from '@opencode-manager/shared/utils'
import { getRepoById } from '../db/queries'
import type { Repo } from '../types/repo'
import { getErrorMessage } from '../utils/error-utils'
import type { OpenCodeClient } from './opencode/client'
import { resolveOpenCodeModel } from './opencode-models'
import { resolveOpenCodeModel, type ResolvedOpenCodeModel } from './opencode-models'
import { createRepoWorkspace } from './repo'
export interface LaunchSessionInput {
interface LaunchSessionInput {
repoId: number
prompt: string
title?: string
@@ -40,33 +42,60 @@ function withWorkspace(message: string, workspaceDirectory: string | null): stri
return workspaceDirectory ? `${message} (workspace: ${workspaceDirectory})` : message
}
export function requireReadyRepo(db: Database, repoId: number): Repo {
const repo = getRepoById(db, repoId)
if (!repo || repo.cloneStatus !== 'ready') {
throw new SessionLaunchError('Repository not found or not ready', 404)
}
return repo
}
export class SessionLauncher {
constructor(
private readonly db: Database,
private readonly openCodeClient: OpenCodeClient,
) {}
async launch(input: LaunchSessionInput): Promise<LaunchedSession> {
const repo = getRepoById(this.db, input.repoId)
if (!repo || repo.cloneStatus !== 'ready') {
throw new SessionLaunchError('Repository not found or not ready', 404)
async resolveModel(repo: Repo, requestedModel?: string): Promise<ResolvedOpenCodeModel> {
let resolved: ResolvedOpenCodeModel
try {
resolved = await resolveOpenCodeModel(this.openCodeClient, repo.fullPath, {
preferredModel: requestedModel,
})
} catch (error) {
throw new SessionLaunchError(getErrorMessage(error) || 'Failed to resolve OpenCode model', 502)
}
if (requestedModel) {
const requestedRef = parseOpenCodeModelRef(requestedModel)
if (!requestedRef || resolved.providerID !== requestedRef.providerID || resolved.id !== requestedRef.id) {
throw new SessionLaunchError(`Model ${requestedModel} is not available`, 400)
}
}
return resolved
}
async launch(input: LaunchSessionInput): Promise<LaunchedSession> {
const repo = requireReadyRepo(this.db, input.repoId)
const model = await this.resolveModel(repo, input.model)
let directory = repo.fullPath
let workspaceDirectory: string | null = null
if (input.workspace) {
try {
const workspace = await createRepoWorkspace(this.openCodeClient, repo, input.workspace)
const workspace = await createRepoWorkspace(this.openCodeClient, repo, {
name: sanitizeRepoDirectoryName(input.workspace.name ?? '', 'session'),
...(input.workspace.ref ? { ref: input.workspace.ref } : {}),
})
directory = workspace.directory
workspaceDirectory = workspace.directory
} catch (error) {
throw new SessionLaunchError(withWorkspace(getErrorMessage(error) || 'Failed to create workspace', null), 502)
throw new SessionLaunchError(getErrorMessage(error) || 'Failed to create workspace', 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({
@@ -98,36 +127,4 @@ export class SessionLauncher {
title: session.title ?? input.title ?? null,
}
}
private async resolveModel(
requestedModel: string | undefined,
directory: string,
workspaceDirectory: string | null,
): Promise<Awaited<ReturnType<typeof resolveOpenCodeModel>>> {
let resolved: Awaited<ReturnType<typeof resolveOpenCodeModel>>
try {
resolved = await resolveOpenCodeModel(this.openCodeClient, directory, {
preferredModel: requestedModel,
})
} catch (error) {
throw new SessionLaunchError(
withWorkspace(getErrorMessage(error) || 'Failed to resolve OpenCode model', workspaceDirectory),
502,
workspaceDirectory,
)
}
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,
workspaceDirectory,
)
}
}
return resolved
}
}
@@ -1,5 +1,6 @@
import type { Database } from 'bun:sqlite'
import type {
SessionLockReason,
SessionPermissionMode,
SessionPermissionModeState,
} from '@opencode-manager/shared/schemas'
@@ -36,11 +37,11 @@ export class SessionPermissionModeService {
private readonly settingsService: SettingsService,
) {}
rememberParent(sessionId: string, parentId: string | null | undefined): void {
private rememberParent(sessionId: string, parentId: string | null | undefined): void {
this.parentBySession.set(sessionId, parentId ?? null)
}
async resolveRootSessionId(sessionId: string): Promise<string> {
private async resolveRootSessionId(sessionId: string): Promise<string> {
let current = sessionId
for (let hops = 0; hops < MAX_PARENT_HOPS; hops += 1) {
@@ -57,9 +58,19 @@ export class SessionPermissionModeService {
async handleEvent(directory: string, event: SSEEvent): Promise<void> {
switch (event.type) {
case 'session.created': {
const { sessionID, parentID } = event.data
const { sessionID, parentID, permissions } = event.data
this.rememberParent(sessionID, parentID)
if (!parentID && this.defaultMode() === 'auto') {
const hasExplicitPermissions = Array.isArray(permissions) && permissions.length > 0
if (!parentID && !hasExplicitPermissions && this.defaultMode() === 'auto') {
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto')
}
return
}
case 'session.forked': {
const { sessionID, parentID } = event.data
this.rememberParent(sessionID, null)
const sourceMode = await this.getEffectiveMode(parentID)
if (sourceMode.mode === 'auto') {
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto')
}
return
@@ -85,61 +96,105 @@ export class SessionPermissionModeService {
async setMode(sessionId: string, mode: SessionPermissionMode, directory: string): Promise<SessionPermissionModeState> {
const rootSessionId = await this.resolveRootSessionId(sessionId)
if (rootSessionId !== sessionId) {
throw new SessionPermissionModeError(
'Child sessions inherit the permission mode of their parent session',
400,
)
}
if (getScheduleRunBySessionId(this.db, rootSessionId)) {
const lockedReason = this.lockReasonForRoot(sessionId, rootSessionId)
if (lockedReason === 'schedule') {
throw new SessionPermissionModeError(
'Scheduled runs use their own permission configuration',
409,
)
}
if (lockedReason === 'child') {
throw new SessionPermissionModeError(
'Child sessions inherit the permission mode of their parent session',
400,
)
}
setSessionPermissionMode(this.db, sessionId, mode)
if (mode === 'auto') {
await this.acceptPendingRequests(sessionId, directory)
await this.acceptPendingRequestsInDirectory(directory, sessionId)
}
return { sessionId, rootSessionId, mode, inherited: false }
return { sessionId, rootSessionId, mode, lockedReason: null }
}
pinAsk(sessionId: string): void {
setSessionPermissionMode(this.db, sessionId, 'ask')
}
defaultMode(): SessionPermissionMode {
return this.settingsService.getSettings().preferences.sessionDefaults?.permissionMode ?? 'ask'
}
async acceptPendingRequestsForActiveSessions(): Promise<void> {
try {
const active = await this.openCodeClient.api.session.active()
const directories = new Set<string>()
for (const sessionId of Object.keys(active ?? {})) {
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionId)
if (!rootSessionId) continue
if (this.effectiveModeForRoot(sessionId, rootSessionId).mode !== 'auto') continue
const directory = await this.resolveSessionDirectory(sessionId)
if (directory) directories.add(directory)
}
for (const directory of directories) {
await this.acceptPendingRequestsInDirectory(directory)
}
} catch (error) {
logger.error('Failed to accept pending permission requests for active sessions:', error)
}
}
private effectiveModeForRoot(
sessionId: string,
rootSessionId: string | null,
): SessionPermissionModeState {
if (!rootSessionId) {
return { sessionId, rootSessionId: sessionId, mode: 'ask', inherited: false }
return { sessionId, rootSessionId: sessionId, mode: 'ask', lockedReason: null }
}
const inherited = rootSessionId !== sessionId
const lockedReason = this.lockReasonForRoot(sessionId, rootSessionId)
if (getScheduleRunBySessionId(this.db, rootSessionId)) {
return { sessionId, rootSessionId, mode: 'ask', inherited }
if (lockedReason === 'schedule') {
return { sessionId, rootSessionId, mode: 'ask', lockedReason }
}
const stored = getSessionPermissionMode(this.db, rootSessionId)
return { sessionId, rootSessionId, mode: stored ?? 'ask', inherited }
return { sessionId, rootSessionId, mode: stored ?? 'ask', lockedReason }
}
private async acceptPendingRequests(rootSessionId: string, directory: string): Promise<void> {
private lockReasonForRoot(sessionId: string, rootSessionId: string): SessionLockReason | null {
if (getScheduleRunBySessionId(this.db, rootSessionId)) {
return 'schedule'
}
return rootSessionId !== sessionId ? 'child' : null
}
private async acceptPendingRequestsInDirectory(directory: string, expectedRootSessionId?: string): Promise<void> {
let requests: PermissionRequest[]
try {
const result = await this.openCodeClient.api.permission.request.list(openCodeLocation(directory))
requests = result.data
} catch (error) {
logger.error(`Failed to list pending permission requests for session ${rootSessionId}:`, error)
logger.error(`Failed to list pending permission requests for directory ${directory}:`, error)
return
}
for (const request of requests) {
await this.autoAcceptRequest(request.sessionID, request.id, rootSessionId)
await this.autoAcceptRequest(request.sessionID, request.id, expectedRootSessionId)
}
}
private async resolveSessionDirectory(sessionId: string): Promise<string | null> {
try {
const session = await this.openCodeClient.api.session.get({ sessionID: sessionId })
return session.location.directory
} catch (error) {
logger.error(`Failed to resolve directory for session ${sessionId}:`, error)
return null
}
}
+79 -1
View File
@@ -1,5 +1,10 @@
import { assistantText, type SessionMessageAssistant, type SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { assistantText, sessionIDFromEvent, type SessionMessageAssistant, type SessionMessageInfo } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from './opencode/client'
import { sseAggregator, type SSEEvent } from './sse-aggregator'
export const SESSION_REPLY_MAX_LENGTH = 20000
const SESSION_REPLY_TRUNCATION_MARKER = '\n\n[reply truncated]'
export interface AssistantReplyState {
responseText: string | null
@@ -7,6 +12,79 @@ export interface AssistantReplyState {
completed: boolean
}
export interface SessionSettleSignal {
errorText: string | null
}
export function truncateSessionReply(text: string): string {
if (text.length <= SESSION_REPLY_MAX_LENGTH) {
return text
}
return `${text.slice(0, SESSION_REPLY_MAX_LENGTH)}${SESSION_REPLY_TRUNCATION_MARKER}`
}
export function sessionSettleSignal(event: SSEEvent, sessionId: string): SessionSettleSignal | null {
if (sessionIDFromEvent(event) !== sessionId) {
return null
}
switch (event.type) {
case 'session.execution.failed':
return { errorText: event.data.error.message || 'The session reported an unknown error.' }
case 'session.execution.interrupted':
return { errorText: 'The session execution was interrupted.' }
case 'session.idle':
case 'session.execution.succeeded':
return { errorText: null }
case 'session.status':
return event.data.status.type === 'idle' ? { errorText: null } : null
default:
return null
}
}
export function waitForSessionSettled(client: OpenCodeClient, sessionId: string, timeoutMs: number): Promise<void> {
if (timeoutMs <= 0) {
return Promise.resolve()
}
return new Promise<void>((resolve) => {
let settled = false
let timer: ReturnType<typeof setTimeout> | null = null
let unsubscribe: () => void = () => {}
const finish = () => {
if (settled) {
return
}
settled = true
if (timer) {
clearTimeout(timer)
}
unsubscribe()
resolve()
}
unsubscribe = sseAggregator.onEvent((_directory, event) => {
if (sessionSettleSignal(event, sessionId)) {
finish()
}
})
timer = setTimeout(finish, timeoutMs)
void isSessionBusy(client, sessionId)
.then((busy) => {
if (!busy) {
finish()
}
})
.catch(() => {
finish()
})
})
}
export function getLatestAssistantReplyState(messages: SessionMessageInfo[]): AssistantReplyState | null {
const assistantMessage = messages.find(
(message): message is SessionMessageAssistant => message.type === 'assistant',
+20 -3
View File
@@ -46,6 +46,7 @@ class SSEAggregator {
private activeSessions: Map<string, Set<string>> = new Map()
private sessionDirectories: Map<string, string> = new Map()
private eventListeners: Set<SSEEventListener> = new Set()
private upstreamConnectedListeners: Set<() => void> = new Set()
private subagentSessions: Map<string, Set<string>> = new Map()
private upstream: EventSource | null = null
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
@@ -370,12 +371,19 @@ class SSEAggregator {
this.upstreamConnected = true
this.reconnectDelay = RECONNECT_DELAY_MS
this.everConnected = true
this.notifyUpstreamConnected()
this.broadcastResync()
if (wasConnectedBefore) {
void this.replaySessionStatusesForTrackedDirectories()
}
}
private notifyUpstreamConnected(): void {
this.upstreamConnectedListeners.forEach(listener => {
try { listener() } catch { /* ignore listener errors */ }
})
}
private broadcastResync(): void {
this.broadcastToAll('resync', JSON.stringify({ timestamp: Date.now() }))
}
@@ -394,6 +402,11 @@ class SSEAggregator {
return () => { this.eventListeners.delete(listener) }
}
onUpstreamConnected(listener: () => void): () => void {
this.upstreamConnectedListeners.add(listener)
return () => { this.upstreamConnectedListeners.delete(listener) }
}
private handleUpstreamMessage(data: string): void {
let event: V2Event
try {
@@ -407,14 +420,17 @@ class SSEAggregator {
const payloadJson = MULTILINE_PATTERN.test(data) ? JSON.stringify(event) : data
const directory = event.location?.directory
const sessionID = sessionIDFromEvent(event)
const forkParentId = event.type === 'session.forked' ? event.data.parentID : undefined
const inheritedDirectory = forkParentId ? this.sessionDirectories.get(forkParentId) : undefined
try {
const resolvedDirectory = directory ?? (sessionID ? this.sessionDirectories.get(sessionID) : undefined)
const rememberedDirectory = directory ?? inheritedDirectory
const resolvedDirectory = rememberedDirectory ?? (sessionID ? this.sessionDirectories.get(sessionID) : undefined)
if (sessionID && event.type === 'session.deleted') {
this.sessionDirectories.delete(sessionID)
} else if (directory && sessionID) {
this.sessionDirectories.set(sessionID, directory)
} else if (sessionID && rememberedDirectory) {
this.sessionDirectories.set(sessionID, rememberedDirectory)
}
if (directory) {
@@ -626,6 +642,7 @@ class SSEAggregator {
this.directoryClients.clear()
this.clients.clear()
this.eventListeners.clear()
this.upstreamConnectedListeners.clear()
}
broadcastToAll(event: string, data: string): void {
+42 -1
View File
@@ -1,5 +1,6 @@
import type { Context } from 'hono'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import type { ZodType } from 'zod'
import { ClientError, openCodeErrorStatus } from '@opencode-manager/shared/opencode'
import { isOAuthErrorCode } from '@opencode-manager/shared/schemas'
import { getErrorMessage } from './error-utils'
@@ -43,7 +44,12 @@ export function handleServiceError(
return c.json({ error: getErrorMessage(error) }, 500)
}
export function handleOpenCodeError(c: Context, error: unknown, fallback: string) {
export function handleOpenCodeError(
c: Context,
error: unknown,
fallback: string,
options?: { unknownStatus?: 500 | 502 },
) {
if (error instanceof Error) {
const tag = (error as { _tag?: unknown })._tag
if (typeof tag === 'string') {
@@ -59,5 +65,40 @@ export function handleOpenCodeError(c: Context, error: unknown, fallback: string
}
logger.error(fallback, error)
const status = options?.unknownStatus ?? 500
if (status === 502) {
return c.json({ error: getErrorMessage(error) || fallback }, 502)
}
return c.json({ error: fallback }, 500)
}
export type JsonBodyResult<T> = { ok: true; data: T } | { ok: false; response: Response }
export async function parseJsonBody<T>(
c: Context,
schema: ZodType<T>,
options?: { allowEmpty?: boolean },
): Promise<JsonBodyResult<T>> {
const text = await c.req.text()
let value: unknown
if (!text.trim()) {
if (!options?.allowEmpty) {
return { ok: false, response: c.json({ error: 'Invalid JSON' }, 400) }
}
value = {}
} else {
try {
value = JSON.parse(text)
} catch {
return { ok: false, response: c.json({ error: 'Invalid JSON' }, 400) }
}
}
const parsed = schema.safeParse(value)
if (!parsed.success) {
return { ok: false, response: c.json({ error: 'Invalid request body', details: parsed.error.issues }, 400) }
}
return { ok: true, data: parsed.data }
}
+19 -6
View File
@@ -239,26 +239,39 @@ describe('Database Queries', () => {
})
describe('deleteRepo', () => {
it('should delete repo schedules before deleting repo by ID', () => {
it('should delete repo-scoped rows, including multi-runs, in one transaction', () => {
mockDb.transaction.mockImplementation((fn: () => void) => fn)
const deleteEntriesStmt = { run: vi.fn().mockReturnValue({ changes: 2 }) }
const deleteMultiRunsStmt = { run: vi.fn().mockReturnValue({ changes: 1 }) }
const deleteRunsStmt = { run: vi.fn().mockReturnValue({ changes: 2 }) }
const deleteJobsStmt = { run: vi.fn().mockReturnValue({ changes: 1 }) }
const deleteSettingsStmt = { run: vi.fn().mockReturnValue({ changes: 0 }) }
const deleteRepoStmt = { run: vi.fn().mockReturnValue({ changes: 1 }) }
mockDb.prepare
.mockReturnValueOnce(deleteRunsStmt)
.mockReturnValueOnce(deleteEntriesStmt)
.mockReturnValueOnce(deleteMultiRunsStmt)
.mockReturnValueOnce(deleteJobsStmt)
.mockReturnValueOnce(deleteRunsStmt)
.mockReturnValueOnce(deleteSettingsStmt)
.mockReturnValueOnce(deleteRepoStmt)
db.deleteRepo(mockDb, 1)
expect(mockDb.prepare).toHaveBeenNthCalledWith(1, 'DELETE FROM schedule_jobs WHERE repo_id = ?')
expect(mockDb.transaction).toHaveBeenCalledTimes(1)
expect(mockDb.prepare).toHaveBeenNthCalledWith(1,
'DELETE FROM multi_run_entries WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)'
)
expect(deleteEntriesStmt.run).toHaveBeenCalledWith(1)
expect(mockDb.prepare).toHaveBeenNthCalledWith(2, 'DELETE FROM multi_runs WHERE repo_id = ?')
expect(deleteMultiRunsStmt.run).toHaveBeenCalledWith(1)
expect(mockDb.prepare).toHaveBeenNthCalledWith(3, 'DELETE FROM schedule_jobs WHERE repo_id = ?')
expect(deleteJobsStmt.run).toHaveBeenCalledWith(1)
expect(mockDb.prepare).toHaveBeenNthCalledWith(2, 'DELETE FROM schedule_runs WHERE repo_id = ?')
expect(mockDb.prepare).toHaveBeenNthCalledWith(4, 'DELETE FROM schedule_runs WHERE repo_id = ?')
expect(deleteRunsStmt.run).toHaveBeenCalledWith(1)
expect(mockDb.prepare).toHaveBeenNthCalledWith(3, 'DELETE FROM repo_settings WHERE repo_id = ?')
expect(mockDb.prepare).toHaveBeenNthCalledWith(5, 'DELETE FROM repo_settings WHERE repo_id = ?')
expect(deleteSettingsStmt.run).toHaveBeenCalledWith(1)
expect(mockDb.prepare).toHaveBeenNthCalledWith(4,
expect(mockDb.prepare).toHaveBeenNthCalledWith(6,
'DELETE FROM repos WHERE id = ?'
)
expect(deleteRepoStmt.run).toHaveBeenCalledWith(1)
@@ -6,11 +6,18 @@ export interface FakePendingPermissionRequest {
sessionID: string
}
export interface FakeSessionInfo {
parentID?: string | null
location?: { directory: string }
}
export interface FakeSessionPermissionClientOptions {
parents?: Record<string, string | null>
directories?: Record<string, string>
activeSessions?: string[]
failSessionGet?: boolean
pendingRequests?: Record<string, FakePendingPermissionRequest[]>
getSession?: (sessionID: string) => Promise<{ parentID?: string | null }>
getSession?: (sessionID: string) => Promise<FakeSessionInfo>
listRequests?: (directory: string) => Promise<FakePendingPermissionRequest[]>
}
@@ -22,6 +29,7 @@ export function createFakeSessionPermissionClient(
options: FakeSessionPermissionClientOptions = {},
): FakeSessionPermissionClient {
const parents = options.parents ?? {}
const directories = options.directories ?? {}
const pendingRequests = options.pendingRequests ?? {}
const replyPermission = vi.fn(async () => {})
@@ -31,7 +39,10 @@ export function createFakeSessionPermissionClient(
if (options.failSessionGet) {
throw new Error('upstream unavailable')
}
return { parentID: parents[sessionID] ?? undefined }
return {
parentID: parents[sessionID] ?? undefined,
location: { directory: directories[sessionID] ?? '' },
}
})
const listRequests =
@@ -43,6 +54,9 @@ export function createFakeSessionPermissionClient(
api: {
session: {
get: async ({ sessionID }: { sessionID: string }) => getSession(sessionID),
active: async () => Object.fromEntries(
(options.activeSessions ?? []).map(sessionID => [sessionID, { type: 'running' as const }]),
),
},
permission: {
request: {
+1
View File
@@ -86,6 +86,7 @@ vi.mock('../src/services/skills', () => ({
const sseAggregatorMock = vi.hoisted(() => ({
onEvent: vi.fn(),
onUpstreamConnected: vi.fn(),
setPendingActionsFetcher: vi.fn(),
setPasswordResolver: vi.fn(),
setScheduledSessionsResolver: vi.fn(),
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import type { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { createInternalRoutes } from '../../src/routes/internal'
@@ -43,7 +44,7 @@ describe('internal/assistant routes', () => {
notificationService = new NotificationService(db)
settingsService = new SettingsService(db)
app = new Hono()
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService))
token = getOrCreateInternalToken(db)
})
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'bun:test'
import type { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { createInternalRoutes } from '../../src/routes/internal'
@@ -29,7 +30,7 @@ describe('internal/notifications routes', () => {
notificationService = new NotificationService(db)
settingsService = new SettingsService(db)
app = new Hono()
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService))
token = getOrCreateInternalToken(db)
})
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'bun:test'
import type { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { readFile, writeFile } from 'fs/promises'
@@ -59,7 +60,7 @@ describe('internal/opencode-config routes', () => {
const notificationService = new NotificationService(db)
const settingsService = new SettingsService(db)
app = new Hono()
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService))
token = getOrCreateInternalToken(db)
})
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import type { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { createInternalRoutes } from '../../src/routes/internal'
@@ -82,7 +83,7 @@ describe('internal-opencode-workspaces routes', () => {
forwardRaw: vi.fn(),
} as unknown as OpenCodeClient
app = new Hono()
app.route('/api/internal', createInternalRoutes(mockDb, scheduleService, notificationService, settingsService, openCodeClient))
app.route('/api/internal', createInternalRoutes(mockDb, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService))
token = 'test-internal-token'
})
+2 -1
View File
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach } from 'vitest'
import type { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { createInternalRoutes } from '../../src/routes/internal'
@@ -30,7 +31,7 @@ describe('internal-repos routes', () => {
notificationService = new NotificationService(db)
settingsService = new SettingsService(db)
app = new Hono()
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService))
token = getOrCreateInternalToken(db)
})
+2 -1
View File
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, mock, vi } from 'bun:test'
import type { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { mkdirSync, rmSync } from 'node:fs'
@@ -93,7 +94,7 @@ describe('internal sandbox routes', () => {
const notificationService = new NotificationService(db)
settingsService = new SettingsService(db)
app = new Hono()
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService))
token = getOrCreateInternalToken(db)
repoDir = path.join(getReposPath(), 'sandbox-route-test')
mkdirSync(repoDir, { recursive: true })
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach } from 'vitest'
import type { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { createInternalRoutes } from '../../src/routes/internal'
@@ -28,7 +29,7 @@ describe('internal-schedules routes', () => {
notificationService = new NotificationService(db)
settingsService = new SettingsService(db)
app = new Hono()
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService))
token = getOrCreateInternalToken(db)
})
+73 -10
View File
@@ -6,6 +6,7 @@ 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 { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import type { Repo } from '../../src/types/repo'
const mockDb = {
@@ -59,6 +60,7 @@ vi.mock('../../src/services/opencode/client', () => ({
}))
const mockLaunch = vi.fn()
const mockPinAsk = vi.fn()
vi.mock('../../src/services/session-launcher', () => {
class SessionLaunchError extends Error {
readonly status: number
@@ -77,6 +79,13 @@ vi.mock('../../src/services/session-launcher', () => {
return { SessionLauncher, SessionLaunchError }
})
const mockResolveRepoForDirectory = vi.fn()
const mockResolveRepoProjectId = vi.fn()
vi.mock('../../src/services/repo', () => ({
resolveRepoForDirectory: (...args: unknown[]) => mockResolveRepoForDirectory(...args),
resolveRepoProjectId: (...args: unknown[]) => mockResolveRepoProjectId(...args),
}))
function makeRepo(overrides: Partial<Repo>): Repo {
return {
id: 1,
@@ -117,6 +126,10 @@ describe('internal-sessions routes', () => {
mockLaunch.mockReset()
mockGetRepoById.mockReturnValue(null)
mockListRepos.mockReturnValue([])
mockResolveRepoForDirectory.mockReset()
mockResolveRepoForDirectory.mockResolvedValue(null)
mockResolveRepoProjectId.mockReset()
mockResolveRepoProjectId.mockResolvedValue('project-1')
sessionList = vi.fn().mockResolvedValue({ data: [], cursor: {} })
sessionActive = vi.fn().mockResolvedValue({})
@@ -139,8 +152,12 @@ describe('internal-sessions routes', () => {
const scheduleService = {} as ScheduleService
const notificationService = {} as NotificationService
const settingsService = {} as SettingsService
const permissionModes = { pinAsk: mockPinAsk } as unknown as SessionPermissionModeService
app = new Hono()
app.route('/api/internal', createInternalRoutes(mockDb, scheduleService, notificationService, settingsService, openCodeClient))
app.route(
'/api/internal',
createInternalRoutes(mockDb, scheduleService, notificationService, settingsService, openCodeClient, permissionModes),
)
token = 'test-internal-token'
})
@@ -149,14 +166,19 @@ describe('internal-sessions routes', () => {
expect(res.status).toBe(401)
})
it('GET /api/internal/sessions filters by repo and marks busy sessions', async () => {
it('GET /api/internal/sessions filters by the repo OpenCode project and resolves workspace directories', async () => {
const repo = makeRepo({ id: 1, fullPath: '/tmp/repo-one' })
mockGetRepoById.mockReturnValue(repo)
mockListRepos.mockReturnValue([repo])
mockResolveRepoProjectId.mockResolvedValue('proj-1')
mockResolveRepoForDirectory.mockImplementation(async (_db: unknown, directory: string) =>
directory === '/tmp/elsewhere' ? null : 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 } },
{ id: 'ses_ws', title: 'Workspace', location: { directory: '/tmp/repo-one-workspaces/feature' }, time: { created: 2, updated: 43 } },
{ id: 'ses_b', location: { directory: '/tmp/elsewhere' }, time: { created: 3, updated: 44 } },
{ id: 'ses_a2', location: { directory: '/tmp/repo-one' }, time: { created: 4, updated: 45 } },
],
cursor: {},
})
@@ -167,11 +189,27 @@ describe('internal-sessions routes', () => {
})
expect(res.status).toBe(200)
expect(sessionList).toHaveBeenCalledWith({ limit: 5, order: 'desc', parentID: null, directory: '/tmp/repo-one' })
expect(mockResolveRepoProjectId).toHaveBeenCalledWith(openCodeClient, '/tmp/repo-one')
expect(sessionList).toHaveBeenCalledWith({ limit: 5, order: 'desc', parentID: null, project: 'proj-1' })
expect(mockResolveRepoForDirectory).toHaveBeenCalledTimes(3)
const body = await res.json() as { sessions: Array<Record<string, unknown>> }
expect(body.sessions).toHaveLength(2)
expect(body.sessions).toHaveLength(4)
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 })
expect(body.sessions[1]).toMatchObject({ id: 'ses_ws', title: 'Workspace', repoId: 1, busy: false, outcome: null, updated: 43 })
expect(body.sessions[2]).toMatchObject({ id: 'ses_b', title: null, repoId: null, busy: false, outcome: null, updated: 44 })
expect(body.sessions[3]).toMatchObject({ id: 'ses_a2', repoId: 1, busy: false, updated: 45 })
})
it('GET /api/internal/sessions lists without a project filter when repoId is omitted', async () => {
sessionList.mockResolvedValue({ data: [], cursor: {} })
const res = await app.request('/api/internal/sessions', {
headers: { authorization: `Bearer ${token}` },
})
expect(res.status).toBe(200)
expect(sessionList).toHaveBeenCalledWith({ limit: 10, order: 'desc', parentID: null })
expect(mockResolveRepoProjectId).not.toHaveBeenCalled()
})
it('GET /api/internal/sessions returns 404 for an unknown repoId', async () => {
@@ -201,12 +239,13 @@ describe('internal-sessions routes', () => {
expect(res.status).toBe(201)
expect(mockLaunch).toHaveBeenCalledWith({ repoId: 1, prompt: 'Do the thing', title: 'Do the thing' })
expect(mockPinAsk).toHaveBeenCalledWith('ses_new')
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 () => {
it('POST /api/internal/sessions passes the raw title as the workspace name', async () => {
mockLaunch.mockResolvedValue({
sessionId: 'ses_ws',
repoId: 1,
@@ -227,13 +266,14 @@ describe('internal-sessions routes', () => {
repoId: 1,
prompt: 'Build it',
title: 'My Feature!',
workspace: { name: 'my-feature', ref: 'main' },
workspace: { name: 'My Feature!', ref: 'main' },
})
expect(mockPinAsk).toHaveBeenCalledWith('ses_ws')
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 () => {
it('POST /api/internal/sessions uses the fallback workspace name when the title is missing', async () => {
mockLaunch.mockResolvedValue({
sessionId: 'ses_ws',
repoId: 1,
@@ -251,6 +291,7 @@ describe('internal-sessions routes', () => {
expect(res.status).toBe(201)
expect(mockLaunch).toHaveBeenCalledWith({ repoId: 1, prompt: 'Build it', workspace: { name: 'ocm-session' } })
expect(mockPinAsk).toHaveBeenCalledWith('ses_ws')
})
it('POST /api/internal/sessions rejects an invalid body', async () => {
@@ -298,6 +339,26 @@ describe('internal-sessions routes', () => {
expect(await res.json()).toEqual({ busy: false, responseText: null, errorText: null, completed: false })
})
it('GET /api/internal/sessions/:sessionId/reply rejects an invalid waitMs', async () => {
const res = await app.request('/api/internal/sessions/ses_a/reply?waitMs=60000', {
headers: { authorization: `Bearer ${token}` },
})
expect(res.status).toBe(400)
expect(messageList).not.toHaveBeenCalled()
})
it('GET /api/internal/sessions/:sessionId/reply returns without waiting when the session is not busy', async () => {
messageList.mockResolvedValue({ data: [assistantMessage] })
const res = await app.request('/api/internal/sessions/ses_a/reply?waitMs=5000', {
headers: { authorization: `Bearer ${token}` },
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ busy: false, responseText: 'All done', errorText: null, completed: true })
})
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' } })
@@ -309,6 +370,7 @@ describe('internal-sessions routes', () => {
expect(res.status).toBe(200)
expect(sessionFork).toHaveBeenCalledWith({ sessionID: 'ses_a', before: 'msg_1' })
expect(mockPinAsk).toHaveBeenCalledWith('ses_fork')
expect(await res.json()).toEqual({ sessionId: 'ses_fork', directory: '/tmp/repo-one' })
})
@@ -322,6 +384,7 @@ describe('internal-sessions routes', () => {
expect(res.status).toBe(200)
expect(sessionFork).toHaveBeenCalledWith({ sessionID: 'ses_a' })
expect(mockPinAsk).toHaveBeenCalledWith('ses_fork')
})
it('returns 404 when OpenCode reports an unknown session', async () => {
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach } from 'bun:test'
import type { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { createInternalRoutes } from '../../src/routes/internal'
@@ -29,7 +30,7 @@ describe('internal/settings routes', () => {
notificationService = new NotificationService(db)
settingsService = new SettingsService(db)
app = new Hono()
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService))
token = getOrCreateInternalToken(db)
})
+14
View File
@@ -90,6 +90,7 @@ describe('multi-run routes', () => {
})
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({ error: 'Invalid request body', details: expect.any(Array) })
expect(service.launch).not.toHaveBeenCalled()
})
@@ -101,6 +102,19 @@ describe('multi-run routes', () => {
})
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({ error: 'Invalid request body', details: expect.any(Array) })
expect(service.launch).not.toHaveBeenCalled()
})
it('POST rejects malformed JSON with 400', async () => {
const res = await app.request('/multi-runs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: '{not json',
})
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({ error: 'Invalid JSON' })
expect(service.launch).not.toHaveBeenCalled()
})
+46 -3
View File
@@ -3,19 +3,20 @@ import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { SessionGoalService } from '../../src/services/session-goals'
import { SessionGoalService, type SessionGoalServiceOptions } from '../../src/services/session-goals'
import { SettingsService } from '../../src/services/settings'
import { createSessionGoalRoutes } from '../../src/routes/session-goals'
import { createFakeSessionGoalClient } from '../helpers/fake-session-goal-client'
const DIRECTORY = '/abs/repo'
function createTestApp(db: Database): Hono {
function createTestApp(db: Database, serviceOptions: SessionGoalServiceOptions = {}): Hono {
const app = new Hono()
const service = new SessionGoalService(
db,
createFakeSessionGoalClient({ busySessions: ['ses_1'] }).client,
new SettingsService(db),
serviceOptions,
)
app.route('/session-goals', createSessionGoalRoutes(service))
return app
@@ -76,7 +77,7 @@ describe('session goal routes', () => {
expect(body.goal.id).toBe(created.goal.id)
})
it('POST rejects an invalid body with 400', async () => {
it('POST rejects an invalid body with 400 and details', async () => {
const app = createTestApp(db)
const res = await app.request('/session-goals', {
@@ -86,6 +87,48 @@ describe('session goal routes', () => {
})
expect(res.status).toBe(400)
const body = await res.json() as { error: string; details: unknown[] }
expect(body.error).toBe('Invalid request body')
expect(Array.isArray(body.details)).toBe(true)
})
it('POST rejects malformed JSON with 400', async () => {
const app = createTestApp(db)
const res = await app.request('/session-goals', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: '{not json',
})
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({ error: 'Invalid JSON' })
})
it('POST rejects a scheduled run session with 409', async () => {
const app = createTestApp(db, { resolveSessionLock: async () => 'schedule' })
const res = await app.request('/session-goals', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: startBody(),
})
expect(res.status).toBe(409)
await expect(res.json()).resolves.toEqual({ error: 'Scheduled runs cannot run goals' })
})
it('POST rejects a child session with 400', async () => {
const app = createTestApp(db, { resolveSessionLock: async () => 'child' })
const res = await app.request('/session-goals', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: startBody(),
})
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({ error: 'Goals can only be started on top-level sessions' })
})
it('POST rejects a second open goal with 409', async () => {
@@ -41,7 +41,20 @@ describe('session permission mode routes', () => {
sessionId: 'ses_root',
rootSessionId: 'ses_root',
mode: 'ask',
inherited: false,
lockedReason: null,
})
})
it('GET reports the child lock reason for a child session', async () => {
const app = createTestApp(db, { ses_child: 'ses_root', ses_root: null })
const res = await app.request('/session-permission-modes/ses_child')
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({
sessionId: 'ses_child',
rootSessionId: 'ses_root',
mode: 'ask',
lockedReason: 'child',
})
})
@@ -58,7 +71,7 @@ describe('session permission mode routes', () => {
sessionId: 'ses_root',
rootSessionId: 'ses_root',
mode: 'auto',
inherited: false,
lockedReason: null,
})
const getRes = await app.request('/session-permission-modes/ses_root')
@@ -75,6 +88,7 @@ describe('session permission mode routes', () => {
body: JSON.stringify({ directory: '/abs/repo', mode: 'always' }),
})
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({ error: 'Invalid request body', details: expect.any(Array) })
})
it('PUT rejects malformed JSON with 400', async () => {
@@ -86,6 +100,7 @@ describe('session permission mode routes', () => {
body: '{not json',
})
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({ error: 'Invalid JSON' })
})
it('PUT rejects setting the mode of a child session with 400', async () => {
+18 -1
View File
@@ -1,4 +1,5 @@
import { describe, expect, it, beforeEach, afterEach } from 'bun:test'
import type { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import path from 'path'
import { access, readFile, writeFile } from 'fs/promises'
import { Hono } from 'hono'
@@ -85,6 +86,22 @@ describe('buildSessionsSkill', () => {
expect(skill).toContain('There is no delete route')
expect(skill).not.toContain('DELETE /sessions')
})
it('documents the ask permission mode and workspace timeout behavior', () => {
const skill = buildSessionsSkill()
expect(skill).toContain('`ask` permission mode')
expect(skill).toContain('keep the mode the user chose')
expect(skill).toContain('may still have succeeded')
expect(skill).toContain('before retrying')
})
it('documents the reply wait parameter and workspace repoId semantics', () => {
const skill = buildSessionsSkill()
expect(skill).toContain('waitMs=30000')
expect(skill).toContain('OpenCode workspace')
expect(skill).toContain('belongs to no known repo')
expect(skill).toContain('capped')
})
})
describe('buildSettingsSkill', () => {
@@ -669,7 +686,7 @@ describe('assistant-mode end-to-end', () => {
const notificationService = new NotificationService(db)
const settingsService = new SettingsService(db)
const app = new Hono()
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, createOpenCodeClient()))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, createOpenCodeClient(), {} as SessionPermissionModeService))
const unauth = await app.request('/api/internal/schedules/all')
expect(unauth.status).toBe(401)
+76 -14
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Database } from 'bun:sqlite'
import { createRepo } from '../../src/db/queries'
import { createRepo, deleteRepo } from '../../src/db/queries'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { createMultiRunWithEntries } from '../../src/db/multi-runs'
@@ -15,12 +15,18 @@ const mocks = vi.hoisted(() => ({
resolveProjectId: vi.fn(),
isGitMainCheckout: vi.fn(),
executeCommand: vi.fn(),
existsSync: vi.fn(),
}))
vi.mock('../../src/services/opencode-models', () => ({
resolveOpenCodeModel: mocks.resolveOpenCodeModel,
}))
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>()
return { ...actual, existsSync: mocks.existsSync }
})
vi.mock('../../src/services/project-id-resolver', () => ({
resolveProjectId: mocks.resolveProjectId,
isGitMainCheckout: mocks.isGitMainCheckout,
@@ -77,6 +83,7 @@ describe('MultiRunService', () => {
vi.clearAllMocks()
db = new Database(':memory:')
migrate(db, allMigrations)
mocks.existsSync.mockReturnValue(true)
mocks.resolveOpenCodeModel.mockImplementation(
async (_client: unknown, _directory: string, options: { preferredModel?: string }) => {
@@ -282,7 +289,32 @@ describe('MultiRunService', () => {
expect(worktreeRemove).not.toHaveBeenCalled()
})
it('records the workspace of a failed isolated launch and removes it on discard', async () => {
it('fails only the entry whose model is unavailable and creates no workspace for it', async () => {
const repoId = readyRepo()
const { client, worktreeCreate, worktreeRemove } = createClient()
const service = createService(client)
const run = await service.launch({
repoId,
name: 'Sweep',
prompt: 'go',
models: ['openai/a', 'openai/retired', 'openai/c'],
isolate: true,
})
expect(run.entries.map((entry) => entry.status)).toEqual(['started', 'failed', 'started'])
expect(run.entries[1]!.directory).toBeNull()
expect(run.entries[1]!.sessionId).toBeNull()
expect(run.entries[1]!.error).toBe('Model openai/retired is not available')
expect(run.entries[0]!.directory).toBe('/worktrees/Sweep-1')
expect(run.entries[2]!.directory).toBe('/worktrees/Sweep-3')
expect(worktreeCreate).toHaveBeenCalledTimes(2)
expect(worktreeCreate.mock.calls.map((call) => call[0].name).sort()).toEqual(['Sweep-1', 'Sweep-3'])
expect(worktreeRemove).not.toHaveBeenCalled()
})
it('marks an isolated entry discarded when its workspace directory is gone', async () => {
const repoId = readyRepo()
const { client, worktreeRemove } = createClient()
const service = createService(client)
@@ -291,24 +323,41 @@ describe('MultiRunService', () => {
repoId,
name: 'Sweep',
prompt: 'go',
models: ['openai/retired'],
models: ['openai/a'],
isolate: true,
})
const entry = run.entries[0]!
expect(entry.directory).toBe('/worktrees/Sweep-1')
mocks.existsSync.mockReturnValue(false)
const discarded = await service.discard(run.id, entry.id)
expect(discarded.entries[0]!.status).toBe('discarded')
expect(worktreeRemove).not.toHaveBeenCalled()
})
it('maps a workspace that is not a deletable sibling to 400 and keeps the entry retryable', async () => {
const repoId = readyRepo()
const { client, workspaces, 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.status).toBe('failed')
expect(entry.directory).toBe('/worktrees/Sweep-1')
expect(entry.error).toContain('/worktrees/Sweep-1')
workspaces.length = 0
const discarded = await service.discard(run.id, entry.id)
const error = await service.discard(run.id, entry.id).catch((caught: unknown) => caught)
expect(discarded.entries[0]!.status).toBe('discarded')
expect(worktreeRemove).toHaveBeenCalledTimes(1)
expect(worktreeRemove).toHaveBeenCalledWith({
projectID: 'commit-A',
directory: '/worktrees/Sweep-1',
force: true,
})
expect(error).toBeInstanceOf(MultiRunError)
expect(error).toMatchObject({ status: 400 })
expect(worktreeRemove).not.toHaveBeenCalled()
expect(service.list(repoId)[0]!.entries[0]!.status).toBe('started')
})
it('records the workspace of a failed isolated launch when prompting fails and removes it on discard', async () => {
@@ -450,4 +499,17 @@ describe('MultiRunService', () => {
const count = db.prepare('SELECT COUNT(*) AS count FROM multi_runs').get() as { count: number }
expect(count.count).toBe(0)
})
it('deletes the repository multi-run rows when the repository is deleted', async () => {
const repoId = readyRepo()
const { client } = createClient()
const service = createService(client)
await service.launch({ repoId, name: 'Sweep', prompt: 'go', models: ['openai/a'], isolate: false })
deleteRepo(db, repoId)
expect(db.prepare('SELECT COUNT(*) AS count FROM multi_runs').get()).toEqual({ count: 0 })
expect(db.prepare('SELECT COUNT(*) AS count FROM multi_run_entries').get()).toEqual({ count: 0 })
})
})
@@ -1,10 +1,40 @@
import { describe, it, expect } from 'vitest'
import { getPermissionLabel, getPermissionDetail, getFormText } from '@opencode-manager/shared/notifications'
import {
getPermissionLabel,
getPermissionDetail,
getFormText,
getGoalOutcomeTitle,
getGoalStopReasonLabel,
} from '@opencode-manager/shared/notifications'
import { buildEventNotificationPayload, buildNotificationUrl } from '../../src/services/notification'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
const ctx = { repoName: 'oc-manager', repoId: 1, sessionId: 'ses_1', directory: '/abs/repo', url: '/repos/1/sessions/ses_1' }
describe('goal notification labels', () => {
it('maps goal stop reasons to human labels', () => {
expect(getGoalStopReasonLabel('cancelled')).toBe('Cancelled')
expect(getGoalStopReasonLabel('user_paused')).toBe('Paused by user')
expect(getGoalStopReasonLabel('continuation_limit')).toBe('Continuation limit reached')
expect(getGoalStopReasonLabel('turn_error')).toBe('Turn failed')
expect(getGoalStopReasonLabel('interrupted')).toBe('Interrupted')
expect(getGoalStopReasonLabel('audit_failed')).toBe('Audit failed')
expect(getGoalStopReasonLabel('session_deleted')).toBe('Session deleted')
})
it('derives the notification title from the status', () => {
expect(getGoalOutcomeTitle('active')).toBe('Goal active')
expect(getGoalOutcomeTitle('paused')).toBe('Goal paused')
expect(getGoalOutcomeTitle('completed')).toBe('Goal completed')
expect(getGoalOutcomeTitle('blocked')).toBe('Goal blocked')
expect(getGoalOutcomeTitle('stopped')).toBe('Goal stopped')
})
it('resolves a stop reason label', () => {
expect(getGoalStopReasonLabel('token_budget')).toBe('Token budget reached')
})
})
describe('getPermissionLabel', () => {
it('maps known V2 permission actions to friendly labels', () => {
expect(getPermissionLabel('shell')).toBe('Run Command')
@@ -5,12 +5,10 @@ import { allMigrations } from '../../src/db/migrations'
import { createRepo } from '../../src/db/queries'
import { createScheduleRun, updateScheduleRunMetadata } from '../../src/db/schedules'
import { NotificationService } from '../../src/services/notification'
import { SessionGoalService } from '../../src/services/session-goals'
import { SettingsService } from '../../src/services/settings'
import { sseAggregator, type SSEEvent } from '../../src/services/sse-aggregator'
import type { PushNotificationPayload } from '@opencode-manager/shared/types'
import type { SessionGoal } from '@opencode-manager/shared/schemas'
import { createFakeSessionGoalClient } from '../helpers/fake-session-goal-client'
const DIRECTORY = '/abs/repo'
const USER_ID = 'user-1'
@@ -194,16 +192,6 @@ describe('NotificationService goal outcomes', () => {
vi.restoreAllMocks()
})
function sessionIdleEvent(sessionID: string): SSEEvent {
return {
id: `evt_idle_${sessionID}`,
created: 1700000000000,
type: 'session.idle',
location: { directory: DIRECTORY },
data: { sessionID },
} as SSEEvent
}
const completedGoal: SessionGoal = {
id: 1,
sessionId: 'ses_goal',
@@ -315,23 +303,74 @@ describe('NotificationService goal outcomes', () => {
expect(send).not.toHaveBeenCalled()
})
it('suppresses session.idle while the session goal is active and notifies once it ends', async () => {
const db = new Database(':memory:')
const service = createService(db)
const fake = createFakeSessionGoalClient()
const goalService = new SessionGoalService(db, fake.client, new SettingsService(db), { quietMs: 0 })
service.addEventSuppressor(async (event, sessionId) => {
if (event.type !== 'session.idle' || !sessionId) return false
return goalService.hasActiveGoal(sessionId)
})
const started = await goalService.start({ sessionId: 'ses_goal', directory: DIRECTORY, objective: 'Ship it' })
it('does not notify when the goal stopped because its turn failed', async () => {
const service = createService()
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
await service.handleSSEEvent(DIRECTORY, sessionIdleEvent('ses_goal'))
expect(send).not.toHaveBeenCalled()
await service.notifyGoalOutcome({
...completedGoal,
id: 11,
status: 'stopped',
stopReason: 'turn_error',
})
goalService.pause(started.id)
await service.handleSSEEvent(DIRECTORY, sessionIdleEvent('ses_goal'))
expect(send).toHaveBeenCalledTimes(1)
expect(send).not.toHaveBeenCalled()
})
it('does not notify when the user cancelled the goal', async () => {
const service = createService()
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
await service.notifyGoalOutcome({
...completedGoal,
id: 12,
status: 'stopped',
stopReason: 'cancelled',
})
expect(send).not.toHaveBeenCalled()
})
it('does not notify when the user paused the goal', async () => {
const service = createService()
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
await service.notifyGoalOutcome({
...completedGoal,
id: 13,
status: 'paused',
stopReason: 'user_paused',
})
expect(send).not.toHaveBeenCalled()
})
it('does not notify while the goal session is being viewed', async () => {
const service = createService()
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
vi.spyOn(sseAggregator, 'isSessionBeingViewed').mockReturnValue(true)
await service.notifyGoalOutcome(completedGoal)
expect(send).not.toHaveBeenCalled()
})
it('notifies the remaining goal outcomes', async () => {
const service = createService()
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
const outcomes: Array<Pick<SessionGoal, 'status' | 'stopReason'>> = [
{ status: 'blocked', stopReason: null },
{ status: 'stopped', stopReason: 'continuation_limit' },
{ status: 'stopped', stopReason: 'token_budget' },
{ status: 'stopped', stopReason: 'interrupted' },
{ status: 'paused', stopReason: 'audit_failed' },
{ status: 'stopped', stopReason: 'session_deleted' },
]
for (const [index, outcome] of outcomes.entries()) {
await service.notifyGoalOutcome({ ...completedGoal, id: 100 + index, ...outcome })
}
expect(send).toHaveBeenCalledTimes(outcomes.length)
})
})
+48
View File
@@ -580,3 +580,51 @@ describe('getSiblingRepos worktree API', () => {
expect(siblings[0]?.id).toBe(1)
})
})
describe('resolveRepoForDirectory', () => {
function createReadyRepo(id: number, localPath: string): Repo {
return {
id,
repoUrl: 'https://github.com/test/repo',
localPath,
fullPath: path.join(getReposPath(), localPath),
sourcePath: path.join(getReposPath(), localPath),
branch: 'main',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
}
}
beforeEach(() => {
vi.clearAllMocks()
})
it('resolves a workspace directory that shares a repo OpenCode project id', async () => {
const { resolveRepoForDirectory } = await import('../../src/services/repo')
const repo = createReadyRepo(1, 'repo-a')
const workspaceDirectory = '/worktrees/feature-x'
getRepoBySourcePath.mockReturnValue(null)
getRepoByLocalPath.mockReturnValue(null)
listRepos.mockReturnValue([repo])
resolveProjectId.mockImplementation(async (directory: string) =>
directory === workspaceDirectory || directory === repo.fullPath ? 'commit-A' : null,
)
const result = await resolveRepoForDirectory({} as never, workspaceDirectory)
expect(result).toBe(repo)
})
it('returns null for a directory that matches no repo', async () => {
const { resolveRepoForDirectory } = await import('../../src/services/repo')
getRepoBySourcePath.mockReturnValue(null)
getRepoByLocalPath.mockReturnValue(null)
listRepos.mockReturnValue([createReadyRepo(1, 'repo-a')])
resolveProjectId.mockResolvedValue(null)
const result = await resolveRepoForDirectory({} as never, '/unknown/directory')
expect(result).toBeNull()
})
})
@@ -3,9 +3,9 @@ import {
buildGoalAuditPrompt,
buildGoalContinuationPrompt,
GOAL_AUDIT_REASON_MAX_CHARS,
GOAL_AUDIT_REPLY_MAX_CHARS,
parseGoalVerdict,
} from '../../src/services/session-goal-audit'
import { SESSION_REPLY_MAX_LENGTH } from '../../src/services/session-reply'
describe('parseGoalVerdict', () => {
it('parses a plain JSON verdict', () => {
@@ -67,11 +67,11 @@ describe('buildGoalAuditPrompt', () => {
})
it('truncates a long reply with a marker', () => {
const reply = 'x'.repeat(GOAL_AUDIT_REPLY_MAX_CHARS + 100)
const reply = 'x'.repeat(SESSION_REPLY_MAX_LENGTH + 100)
const prompt = buildGoalAuditPrompt({ objective: 'Ship it', reply })
expect(prompt).toContain('[reply truncated]')
expect(prompt).not.toContain('x'.repeat(GOAL_AUDIT_REPLY_MAX_CHARS + 1))
expect(prompt).not.toContain('x'.repeat(SESSION_REPLY_MAX_LENGTH + 1))
})
})
+45 -12
View File
@@ -195,6 +195,51 @@ describe('SessionGoalService', () => {
expect(listOpenSessionGoals(db)).toHaveLength(1)
})
it('rejects a goal on a scheduled run session with 409 and creates no goal', async () => {
const service = createService(db, {}, new SettingsService(db), {
resolveSessionLock: async () => 'schedule',
})
await expect(
service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }),
).rejects.toMatchObject({ status: 409, message: 'Scheduled runs cannot run goals' })
expect(listOpenSessionGoals(db)).toHaveLength(0)
})
it('rejects a goal on a child session with 400 and creates no goal', async () => {
const service = createService(db, {}, new SettingsService(db), {
resolveSessionLock: async () => 'child',
})
await expect(
service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }),
).rejects.toMatchObject({ status: 400, message: 'Goals can only be started on top-level sessions' })
expect(listOpenSessionGoals(db)).toHaveLength(0)
})
it('starts a goal when the session is not locked', async () => {
const service = createService(db, {}, new SettingsService(db), {
resolveSessionLock: async () => null,
})
const goal = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' })
expect(goal.status).toBe('active')
expect(listOpenSessionGoals(db)).toHaveLength(1)
})
it('starts a goal when the session lock lookup fails', async () => {
const service = createService(db, {}, new SettingsService(db), {
resolveSessionLock: async () => {
throw new Error('lock lookup failed')
},
})
const goal = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' })
expect(goal.status).toBe('active')
})
it('allows a new goal once the previous one is cancelled', async () => {
const service = createService(db)
const first = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'First' })
@@ -963,18 +1008,6 @@ describe('SessionGoalService recovery', () => {
expect(outcomes).toEqual(['stopped'])
})
it('reports whether a session has an active goal', async () => {
const service = createService(db)
const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' })
expect(service.hasActiveGoal('ses_1')).toBe(true)
expect(service.hasActiveGoal('ses_missing')).toBe(false)
service.pause(started.id)
expect(service.hasActiveGoal('ses_1')).toBe(false)
})
it('retries recovery after a transient session lookup failure without session events', async () => {
const running = await createService(db).start({ sessionId: 'ses_run', directory: DIRECTORY, objective: 'Ship it' })
transitionSessionGoal(db, running.id, ['active'], { turnState: 'running' })
+22 -22
View File
@@ -114,7 +114,7 @@ describe('SessionLauncher', () => {
})
expect(worktreeCreate).toHaveBeenCalledWith({ projectID: 'commit-A', name: 'feature-x', branch: 'feature/x' })
expect(mocks.resolveOpenCodeModel).toHaveBeenCalledWith(client, '/worktrees/feature-x', { preferredModel: undefined })
expect(mocks.resolveOpenCodeModel).toHaveBeenCalledWith(client, REPO_DIR, { preferredModel: undefined })
expect(create).toHaveBeenCalledWith(expect.objectContaining({ location: { directory: '/worktrees/feature-x' } }))
expect(result).toMatchObject({
sessionId: 'ses_new',
@@ -124,18 +124,35 @@ describe('SessionLauncher', () => {
})
})
it('rejects an unavailable requested model without creating a session', async () => {
it('rejects an unavailable requested model before creating a workspace or session', async () => {
const repoId = readyRepo()
const { client, create } = createClient()
const { client, create, worktreeCreate } = createClient()
const launcher = new SessionLauncher(db, client)
const error = await launcher.launch({ repoId, prompt: 'hello', model: 'openai/retired' }).catch((caught: unknown) => caught)
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, message: 'Model openai/retired is not available' })
expect(error).toMatchObject({
status: 400,
message: 'Model openai/retired is not available',
workspaceDirectory: null,
})
expect(worktreeCreate).not.toHaveBeenCalled()
expect(create).not.toHaveBeenCalled()
})
it('slugs a raw workspace name before creating the workspace', async () => {
const repoId = readyRepo()
const { client, worktreeCreate } = createClient({ workspaceDirectory: '/worktrees/Feature-Sweep' })
const launcher = new SessionLauncher(db, client)
await launcher.launch({ repoId, prompt: 'hello', workspace: { name: 'Feature Sweep!' } })
expect(worktreeCreate).toHaveBeenCalledWith({ projectID: 'commit-A', name: 'Feature-Sweep' })
})
it('rejects a repo that is not ready', async () => {
const repoId = readyRepo({ cloneStatus: 'cloning' })
const { client, create } = createClient()
@@ -170,23 +187,6 @@ describe('SessionLauncher', () => {
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') })
@@ -62,6 +62,26 @@ function sessionDeletedEvent(sessionID: string): SSEEvent {
} as unknown as SSEEvent
}
function sessionForkedEvent(sessionID: string, parentID: string): SSEEvent {
return {
id: `evt_forked_${sessionID}`,
created: Date.now(),
type: 'session.forked',
location: { directory: DIRECTORY },
data: { sessionID, parentID, boundary: { messageID: 'msg_1', partID: null } },
} as unknown as SSEEvent
}
function sessionCreatedWithPermissionsEvent(sessionID: string, permissions: unknown[]): SSEEvent {
return {
id: `evt_created_${sessionID}`,
created: Date.now(),
type: 'session.created',
location: { directory: DIRECTORY },
data: { sessionID, permissions },
} as unknown as SSEEvent
}
describe('SessionPermissionModeService', () => {
let db: Database
@@ -80,11 +100,11 @@ describe('SessionPermissionModeService', () => {
sessionId: 'ses_root',
rootSessionId: 'ses_root',
mode: 'ask',
inherited: false,
lockedReason: null,
})
})
it('applies a stored auto root mode to its child and marks it inherited', async () => {
it('applies a stored auto root mode to its child and marks it locked to the child', async () => {
setSessionPermissionMode(db, 'ses_root', 'auto')
const client = createFakeSessionPermissionClient({ parents: { ses_child: 'ses_root', ses_root: null } })
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
@@ -93,7 +113,7 @@ describe('SessionPermissionModeService', () => {
sessionId: 'ses_child',
rootSessionId: 'ses_root',
mode: 'auto',
inherited: true,
lockedReason: 'child',
})
})
@@ -123,7 +143,7 @@ describe('SessionPermissionModeService', () => {
sessionId: 'ses_scheduled',
rootSessionId: 'ses_scheduled',
mode: 'ask',
inherited: false,
lockedReason: 'schedule',
})
})
@@ -143,7 +163,7 @@ describe('SessionPermissionModeService', () => {
sessionId: 'ses_root',
rootSessionId: 'ses_root',
mode: 'ask',
inherited: false,
lockedReason: null,
})
})
@@ -216,6 +236,147 @@ describe('SessionPermissionModeService', () => {
expect(getSessionPermissionMode(db, 'ses_root')).toBeNull()
})
it('does not stamp the default auto mode when the created event carries an explicit permissions ruleset', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } })
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
await service.handleEvent(
DIRECTORY,
sessionCreatedWithPermissionsEvent('ses_root', [{ permission: 'bash', pattern: '*', action: 'allow' }]),
)
expect(getSessionPermissionMode(db, 'ses_root')).toBeNull()
})
it('copies an auto source mode onto a forked root session', async () => {
setSessionPermissionMode(db, 'ses_source', 'auto')
const service = new SessionPermissionModeService(
db,
createFakeSessionPermissionClient({ parents: { ses_source: null } }),
new SettingsService(db),
)
await service.handleEvent(DIRECTORY, sessionForkedEvent('ses_fork', 'ses_source'))
expect(getSessionPermissionMode(db, 'ses_fork')).toBe('auto')
})
it('leaves a forked session unstamped when the source is ask', async () => {
const service = new SessionPermissionModeService(
db,
createFakeSessionPermissionClient({ parents: { ses_source: null } }),
new SettingsService(db),
)
await service.handleEvent(DIRECTORY, sessionForkedEvent('ses_fork', 'ses_source'))
expect(getSessionPermissionMode(db, 'ses_fork')).toBeNull()
})
it('does not overwrite an explicit pin when copying the source mode onto a fork', async () => {
setSessionPermissionMode(db, 'ses_source', 'auto')
setSessionPermissionMode(db, 'ses_fork', 'ask')
const service = new SessionPermissionModeService(
db,
createFakeSessionPermissionClient({ parents: { ses_source: null } }),
new SettingsService(db),
)
await service.handleEvent(DIRECTORY, sessionForkedEvent('ses_fork', 'ses_source'))
expect(getSessionPermissionMode(db, 'ses_fork')).toBe('ask')
})
it('pinAsk overrides a default auto stamp and survives later insert-if-absent events', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } })
const service = new SessionPermissionModeService(
db,
createFakeSessionPermissionClient({ parents: { ses_root: null } }),
settingsService,
)
await service.handleEvent(DIRECTORY, sessionCreatedEvent('ses_root'))
expect(getSessionPermissionMode(db, 'ses_root')).toBe('auto')
service.pinAsk('ses_root')
expect(getSessionPermissionMode(db, 'ses_root')).toBe('ask')
await service.handleEvent(DIRECTORY, sessionCreatedEvent('ses_root'))
expect(getSessionPermissionMode(db, 'ses_root')).toBe('ask')
})
it('rejects setMode for a schedule-run session with 409', async () => {
createRepo(db, {
localPath: 'repo-one',
sourcePath: '/abs/repo',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
isLocal: true,
})
const run = createScheduleRun(db, {
jobId: 1,
repoId: 1,
triggerSource: 'schedule',
status: 'running',
startedAt: Date.now(),
createdAt: Date.now(),
})
updateScheduleRunMetadata(db, 1, 1, run.id, { sessionId: 'ses_scheduled' })
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await expect(service.setMode('ses_scheduled', 'auto', DIRECTORY)).rejects.toMatchObject({ status: 409 })
expect(getSessionPermissionMode(db, 'ses_scheduled')).toBeNull()
})
it('accepts pending requests for active auto sessions and skips ask sessions', async () => {
setSessionPermissionMode(db, 'ses_auto', 'auto')
const client = createFakeSessionPermissionClient({
parents: { ses_auto: null, ses_ask: null },
directories: { ses_auto: DIRECTORY, ses_ask: DIRECTORY },
activeSessions: ['ses_auto', 'ses_ask'],
pendingRequests: {
[DIRECTORY]: [
{ id: 'perm-auto', sessionID: 'ses_auto' },
{ id: 'perm-ask', sessionID: 'ses_ask' },
],
},
})
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
await service.acceptPendingRequestsForActiveSessions()
expect(client.replyPermission).toHaveBeenCalledTimes(1)
expect(client.replyPermission).toHaveBeenCalledWith({
sessionID: 'ses_auto',
requestID: 'perm-auto',
decision: 'once',
})
})
it('accepts a pending request for a child of an active auto root', async () => {
setSessionPermissionMode(db, 'ses_root', 'auto')
const client = createFakeSessionPermissionClient({
parents: { ses_root: null, ses_child: 'ses_root' },
directories: { ses_child: DIRECTORY },
activeSessions: ['ses_child'],
pendingRequests: { [DIRECTORY]: [{ id: 'perm-child', sessionID: 'ses_child' }] },
})
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
await service.acceptPendingRequestsForActiveSessions()
expect(client.replyPermission).toHaveBeenCalledTimes(1)
expect(client.replyPermission).toHaveBeenCalledWith({
sessionID: 'ses_child',
requestID: 'perm-child',
decision: 'once',
})
})
it('clears the stored mode when the session is deleted', async () => {
setSessionPermissionMode(db, 'ses_root', 'auto')
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
+114 -1
View File
@@ -1,13 +1,26 @@
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it, vi, beforeEach } from 'vitest'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import {
SESSION_REPLY_MAX_LENGTH,
getLatestAssistantReplyState,
isSessionBusy,
readLatestAssistantReply,
sessionSettleSignal,
truncateSessionReply,
waitForSessionSettled,
} from '../../src/services/session-reply'
import { assistantMessage } from '../helpers/stub-schedule-api'
const mockOnEvent = vi.fn()
vi.mock('../../src/services/sse-aggregator', () => ({
sseAggregator: { onEvent: (...args: unknown[]) => mockOnEvent(...args) },
}))
beforeEach(() => {
mockOnEvent.mockReset()
})
function createFakeClient(messages: SessionMessageInfo[], active: Record<string, unknown> = {}): OpenCodeClient {
return {
api: {
@@ -100,3 +113,103 @@ describe('isSessionBusy', () => {
await expect(isSessionBusy(createFakeClient([], {}), 'ses-1')).resolves.toBe(false)
})
})
describe('truncateSessionReply', () => {
it('returns short replies unchanged', () => {
expect(truncateSessionReply('short reply')).toBe('short reply')
})
it('caps long replies and appends a truncation marker', () => {
const reply = 'x'.repeat(SESSION_REPLY_MAX_LENGTH + 25)
const truncated = truncateSessionReply(reply)
expect(truncated.startsWith('x'.repeat(SESSION_REPLY_MAX_LENGTH))).toBe(true)
expect(truncated.endsWith('[reply truncated]')).toBe(true)
expect(truncated).not.toContain('x'.repeat(SESSION_REPLY_MAX_LENGTH + 1))
})
})
describe('sessionSettleSignal', () => {
it('signals a clean settle for idle, succeeded, and status idle events', () => {
expect(sessionSettleSignal({ type: 'session.idle', data: { sessionID: 's1' } } as never, 's1')).toEqual({ errorText: null })
expect(sessionSettleSignal({ type: 'session.execution.succeeded', data: { sessionID: 's1' } } as never, 's1')).toEqual({ errorText: null })
expect(sessionSettleSignal({ type: 'session.status', data: { sessionID: 's1', status: { type: 'idle' } } } as never, 's1')).toEqual({ errorText: null })
})
it('signals a failure with the reported error message', () => {
expect(sessionSettleSignal({ type: 'session.execution.failed', data: { sessionID: 's1', error: { message: 'boom' } } } as never, 's1')).toEqual({ errorText: 'boom' })
expect(sessionSettleSignal({ type: 'session.execution.failed', data: { sessionID: 's1', error: { message: '' } } } as never, 's1')).toEqual({ errorText: 'The session reported an unknown error.' })
})
it('signals an interruption', () => {
expect(sessionSettleSignal({ type: 'session.execution.interrupted', data: { sessionID: 's1' } } as never, 's1')).toEqual({ errorText: 'The session execution was interrupted.' })
})
it('ignores events for other sessions and non-settling events', () => {
expect(sessionSettleSignal({ type: 'session.idle', data: { sessionID: 's2' } } as never, 's1')).toBeNull()
expect(sessionSettleSignal({ type: 'session.status', data: { sessionID: 's1', status: { type: 'busy' } } } as never, 's1')).toBeNull()
expect(sessionSettleSignal({ type: 'session.execution.started', data: { sessionID: 's1' } } as never, 's1')).toBeNull()
})
})
describe('waitForSessionSettled', () => {
function captureListener() {
let listener: ((directory: string, event: unknown) => void) | undefined
const unsubscribe = vi.fn()
mockOnEvent.mockImplementation((callback: (directory: string, event: unknown) => void) => {
listener = callback
return unsubscribe
})
return {
emit: (event: unknown) => listener?.('', event),
unsubscribe,
}
}
it('does not subscribe when the timeout is zero', async () => {
const client = createFakeClient([], { 'ses-1': {} })
await expect(waitForSessionSettled(client, 'ses-1', 0)).resolves.toBeUndefined()
expect(mockOnEvent).not.toHaveBeenCalled()
})
it('resolves once the session settles and unsubscribes', async () => {
const client = createFakeClient([], { 'ses-1': {} })
const { emit, unsubscribe } = captureListener()
const settled = waitForSessionSettled(client, 'ses-1', 1000)
emit({ type: 'session.idle', data: { sessionID: 'ses-1' } })
await expect(settled).resolves.toBeUndefined()
expect(unsubscribe).toHaveBeenCalledTimes(1)
})
it('ignores settle events for other sessions', async () => {
const client = createFakeClient([], { 'ses-1': {} })
const { emit, unsubscribe } = captureListener()
const settled = waitForSessionSettled(client, 'ses-1', 1000)
emit({ type: 'session.idle', data: { sessionID: 'ses-2' } })
expect(unsubscribe).not.toHaveBeenCalled()
emit({ type: 'session.idle', data: { sessionID: 'ses-1' } })
await expect(settled).resolves.toBeUndefined()
expect(unsubscribe).toHaveBeenCalledTimes(1)
})
it('resolves immediately when the session is no longer busy after subscribing', async () => {
const client = createFakeClient([], {})
const { unsubscribe } = captureListener()
await expect(waitForSessionSettled(client, 'ses-1', 1000)).resolves.toBeUndefined()
expect(unsubscribe).toHaveBeenCalledTimes(1)
})
it('resolves on timeout and unsubscribes', async () => {
const client = createFakeClient([], { 'ses-1': {} })
const { unsubscribe } = captureListener()
await expect(waitForSessionSettled(client, 'ses-1', 20)).resolves.toBeUndefined()
expect(unsubscribe).toHaveBeenCalledTimes(1)
})
})
@@ -583,6 +583,34 @@ describe('SSEAggregator upstream resynchronization signal', () => {
expect(client.events.filter(event => event.event === 'resync')).toHaveLength(1)
})
it('invokes onUpstreamConnected listeners on the first and every later upstream connect', () => {
const listener = vi.fn()
const unsubscribe = sseAggregator.onUpstreamConnected(listener)
const openUpstream = (sseAggregator as unknown as { handleUpstreamOpen(wasConnectedBefore: boolean): void }).handleUpstreamOpen.bind(sseAggregator)
openUpstream(false)
openUpstream(true)
expect(listener).toHaveBeenCalledTimes(2)
unsubscribe()
openUpstream(true)
expect(listener).toHaveBeenCalledTimes(2)
})
it('isolates a throwing onUpstreamConnected listener from the others', () => {
const throwing = vi.fn(() => { throw new Error('boom') })
const healthy = vi.fn()
sseAggregator.onUpstreamConnected(throwing)
sseAggregator.onUpstreamConnected(healthy)
;(sseAggregator as unknown as { handleUpstreamOpen(wasConnectedBefore: boolean): void }).handleUpstreamOpen(false)
expect(throwing).toHaveBeenCalledTimes(1)
expect(healthy).toHaveBeenCalledTimes(1)
})
})
describe('SSEAggregator directory-indexed broadcast', () => {
@@ -735,4 +763,37 @@ describe('SSEAggregator directory-less session event routing', () => {
payload: { id: 'evt_1', created: 1, type: 'session.execution.succeeded', data: { sessionID: 'ses_del' } },
})
})
it('resolves a directory-less session.forked from the remembered parent directory and notifies listeners', () => {
const subscribed = createCapturingClient()
const global = createCapturingClient()
sseAggregator.addClient('fork-a', subscribed.callback, subscribed.writeFrame, ['/r'])
sseAggregator.addClient('fork-b', global.callback, global.writeFrame, [])
const seen: Array<{ directory: string; type: string; sessionID: string }> = []
sseAggregator.onEvent((directory, event) => {
seen.push({ directory, type: event.type, sessionID: sessionIDFromEvent(event) ?? '' })
})
emitRawEvent({ type: 'session.created', location: { directory: '/r' }, data: { sessionID: 'ses_source' } })
seen.length = 0
emitRawEvent({ type: 'session.forked', data: { sessionID: 'ses_fork', parentID: 'ses_source', boundary: { messageID: 'msg_1' } } })
expect(seen).toEqual([{ directory: '/r', type: 'session.forked', sessionID: 'ses_fork' }])
const forkPayload = {
id: 'evt_1',
created: 1,
type: 'session.forked',
data: { sessionID: 'ses_fork', parentID: 'ses_source', boundary: { messageID: 'msg_1' } },
}
expect(subscribed.frames.map(parseFrame).at(-1)).toEqual({ directory: null, payload: forkPayload })
expect(global.frames.map(parseFrame).at(-1)).toEqual({ directory: null, payload: forkPayload })
seen.length = 0
emitRawEvent({ type: 'session.execution.succeeded', data: { sessionID: 'ses_fork' } })
expect(seen).toEqual([{ directory: '/r', type: 'session.execution.succeeded', sessionID: 'ses_fork' }])
})
})
+116
View File
@@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest'
import { Hono } from 'hono'
import { z, type ZodType } from 'zod'
import { ClientError } from '@opencode-manager/shared/opencode'
import { handleOpenCodeError, parseJsonBody } from '../../src/utils/route-helpers'
function createParseApp(schema: ZodType, options?: { allowEmpty?: boolean }) {
const app = new Hono()
app.post('/', async (c) => {
const result = await parseJsonBody(c, schema, options)
if (!result.ok) {
return result.response
}
return c.json({ data: result.data })
})
return app
}
function createErrorApp(error: unknown, fallback: string, options?: { unknownStatus?: 500 | 502 }) {
const app = new Hono()
app.get('/', (c) => handleOpenCodeError(c, error, fallback, options))
return app
}
describe('parseJsonBody', () => {
const NameSchema = z.object({ name: z.string() })
it('parses a valid JSON body', async () => {
const response = await createParseApp(NameSchema).request('/', {
method: 'POST',
body: JSON.stringify({ name: 'ada' }),
})
expect(response.status).toBe(200)
await expect(response.json()).resolves.toEqual({ data: { name: 'ada' } })
})
it('rejects malformed JSON with an Invalid JSON body', async () => {
const response = await createParseApp(NameSchema).request('/', {
method: 'POST',
body: '{not json',
})
expect(response.status).toBe(400)
await expect(response.json()).resolves.toEqual({ error: 'Invalid JSON' })
})
it('treats an empty body as invalid JSON by default', async () => {
const response = await createParseApp(NameSchema).request('/', { method: 'POST', body: ' ' })
expect(response.status).toBe(400)
await expect(response.json()).resolves.toEqual({ error: 'Invalid JSON' })
})
it('parses an empty body as {} when allowEmpty is set', async () => {
const OptionalSchema = z.object({ name: z.string().optional() })
const response = await createParseApp(OptionalSchema, { allowEmpty: true }).request('/', {
method: 'POST',
body: '',
})
expect(response.status).toBe(200)
await expect(response.json()).resolves.toEqual({ data: {} })
})
it('returns schema issues when the body fails validation', async () => {
const response = await createParseApp(NameSchema).request('/', {
method: 'POST',
body: JSON.stringify({ name: 42 }),
})
expect(response.status).toBe(400)
const body = await response.json() as { error: string; details: unknown[] }
expect(body.error).toBe('Invalid request body')
expect(Array.isArray(body.details)).toBe(true)
expect(body.details.length).toBeGreaterThan(0)
})
})
describe('handleOpenCodeError', () => {
it('falls back to a 500 with the fallback message for unknown errors', async () => {
const response = await createErrorApp(new Error('kaboom'), 'Request failed').request('/')
expect(response.status).toBe(500)
await expect(response.json()).resolves.toEqual({ error: 'Request failed' })
})
it('uses unknownStatus 502 and surfaces the error message', async () => {
const response = await createErrorApp(new Error('kaboom'), 'Request failed', { unknownStatus: 502 }).request('/')
expect(response.status).toBe(502)
await expect(response.json()).resolves.toEqual({ error: 'kaboom' })
})
it('falls back to the fallback message when a 502 error has no message', async () => {
const response = await createErrorApp(new Error(''), 'Request failed', { unknownStatus: 502 }).request('/')
expect(response.status).toBe(502)
await expect(response.json()).resolves.toEqual({ error: 'Request failed' })
})
it('maps a tagged OpenCode not-found error to 404', async () => {
const error = Object.assign(new Error('session gone'), { _tag: 'SessionNotFoundError' })
const response = await createErrorApp(error, 'Request failed').request('/')
expect(response.status).toBe(404)
await expect(response.json()).resolves.toEqual({ error: 'session gone' })
})
it('maps a ClientError to a 502 with the ClientError code', async () => {
const response = await createErrorApp(new ClientError('Transport'), 'Request failed').request('/')
expect(response.status).toBe(502)
await expect(response.json()).resolves.toEqual({ error: 'Request failed', code: 'ClientError' })
})
})
+7 -6
View File
@@ -378,11 +378,11 @@ Retrieve a list of all managed repositories, ordered by the user's repo preferen
### Sessions
These routes back the `session-management` skill, so an agent can start work in a repo, hand a task to a new session, follow it up, read its reply, and fork it. Session creation always goes through the Manager's session launcher, which validates the repository and the requested model before creating anything.
These routes back the `session-management` skill, so an agent can start work in a repo, hand a task to a new session, follow it up, read its reply, and fork it. Session creation always goes through the Manager's session launcher, which validates the repository and the requested model before creating anything. Malformed JSON is rejected with `{ "error": "Invalid JSON" }`; a body that fails validation is rejected with `{ "error": "Invalid request body", "details": [...] }`; unknown upstream failures return `502`.
**GET `/api/internal/sessions`**
List sessions, newest first. Pass `repoId` to restrict the list to one repo and `limit` (1-50, default 10) to bound it.
List sessions, newest first. Pass `repoId` to restrict the list to one repo — this covers every OpenCode workspace of that repo, not only the repo directory — and `limit` (1-50, default 10) to bound it.
**Query Parameters:**
- `repoId` (optional): Restrict to a repository. An unknown id returns `404`.
@@ -395,7 +395,7 @@ List sessions, newest first. Pass `repoId` to restrict the list to one repo and
id: string
title: string | null
directory: string
repoId: number | null // null when the directory matches no known repo
repoId: number | null // null only when the directory belongs to no known repo
busy: boolean // true while the session is running
outcome: 'succeeded' | 'failed' | 'interrupted' | null
updated: number
@@ -412,7 +412,7 @@ List sessions, newest first. Pass `repoId` to restrict the list to one repo and
**POST `/api/internal/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; poll `GET /api/internal/sessions/:sessionId/reply` for the result. Pass `worktree: true` to run in a new isolated workspace, with `ref` selecting its base ref. A requested `model` must be available; an unavailable model is rejected with `400` rather than silently substituted.
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; poll `GET /api/internal/sessions/:sessionId/reply` for the result. Pass `worktree: true` to run in a new isolated workspace, with `ref` selecting its base ref. A requested `model` must be available; an unavailable model is rejected with `400` rather than silently substituted. Sessions created here are pinned to **ask** permission mode. With `worktree: true`, creation can take tens of seconds; a request that times out may still have succeeded, so check `GET /api/internal/sessions` before retrying.
**Request Body:**
```ts
@@ -472,7 +472,7 @@ Queue a follow-up prompt for an existing session.
**GET `/api/internal/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`.
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`. Pass `waitMs` (0-45000) to wait until the session settles instead of polling in a loop; the response returns when it settles or the timeout elapses. `responseText` is capped at 20,000 characters, with a truncation marker appended when it is longer.
**Response:**
```ts
@@ -486,13 +486,14 @@ Read the latest assistant reply for a session and whether it is still running. P
**Status Codes:**
- `200`: Reply state returned
- `400`: Invalid `waitMs`
- `401`: Missing or invalid bearer token
- `404`: Session not found
- `502`: OpenCode error
**POST `/api/internal/sessions/:sessionId/fork`**
Fork a session, optionally before a specific message. Omit `beforeMessageId` to fork from the current point.
Fork a session, optionally before a specific message. Omit `beforeMessageId` to fork from the current point. The forked session is pinned to **ask** permission mode.
**Request Body:**
```ts
+2 -1
View File
@@ -15,7 +15,7 @@ The assistant workspace is a special repository-like directory managed and maint
## Skills Provided
Four skills are provisioned automatically when assistant mode is initialized:
Five skills are provisioned automatically when assistant mode is initialized:
| Skill | What it teaches |
|-------|----------------|
@@ -23,6 +23,7 @@ Four skills are provisioned automatically when assistant mode is initialized:
| `notifications` | Send push notifications to registered user devices with the `ocm` `send_notification` action |
| `manager-settings` | Read and patch user preferences, read and update the OpenCode configuration file, and reload the assistant workspace, through the `ocm` `request` action |
| `repo-management` | List all managed repositories through the `ocm` `request` action |
| `session-management` | List, create, follow up, read the reply of, and fork sessions through the `ocm` `request` action |
The assistant manages the Manager's global OpenCode configuration file through the `ocm` tool (`/opencode-config`), and the file on disk is the source of truth.
+6 -2
View File
@@ -103,7 +103,11 @@ Control who answers OpenCode permission requests for a session. The shield butto
The mode is owned by the backend, so a session in Accept everything keeps working while the browser is closed. Accept everything answers each request once and never saves a permanent rule, and it never overrides a `deny` rule. When you switch a session to Accept everything, requests already waiting are answered immediately.
Child sessions inherit the mode of their root session and cannot change it. Sessions started by a scheduled run always use their schedule's own permission configuration.
Child sessions inherit the mode of their root session and cannot change it, and the composer toggle is disabled for them with an explanation. A session forked from another starts with the source session's mode, except that forks of scheduled runs stay **Ask every time**.
Sessions started by a scheduled run always use their schedule's own permission configuration; the composer toggle is disabled there with an explanation. Sessions created or forked by an agent through the `ocm` tool always start in **Ask every time**, regardless of the default, though an agent can still send follow-ups to a session you switched to **Accept everything**.
If Manager restarts or loses its connection to OpenCode, permission requests already waiting in **Accept everything** sessions are answered when it reconnects.
To change the default for new sessions, go to **Settings → General → Sessions** and pick a **Default permission mode for new sessions**. The default is stamped onto a session when it is created, so changing it only affects sessions created afterwards, never existing ones.
@@ -113,7 +117,7 @@ Auto-accepted requests send no push notification, so you are not alerted for a r
A goal keeps a session working on an objective until an auditor model decides it is done or blocked, without you sending follow-up messages.
Arm goal mode with the target button in the composer, then send your message. That message becomes the goal objective, and it is sent to the session as usual. While a goal is active, each time the session goes idle the auditor decides the next step:
Arm goal mode with the target button in the composer, then send your message. That message becomes the goal objective, and it is sent to the session as usual. Goals cannot be started on scheduled-run sessions or subagent (child) sessions, and the goal button is disabled there. If you arm a goal and send while the agent is still responding, the message is queued and the goal starts; auditing begins after that queued turn. While a goal is active, each time the session goes idle the auditor decides the next step:
- **done** - the objective is verifiably achieved, and the goal completes.
- **blocked** - the agent needs a decision or access it cannot obtain. Three consecutive blocked verdicts stop the goal as blocked.
+3 -3
View File
@@ -12,7 +12,7 @@ Open a repository and click **Multi-run** in the header, next to **New Session**
4. Leave **Isolate runs** on to give each model its own workspace.
5. Optionally set **Start from** to a branch or ref. Empty starts from the current HEAD.
Click **Launch**. Each selected model gets its own session, and the same prompt is sent to all of them. Launching is parallel, and one model failing does not stop the others: the failed entry records its error while the rest keep running.
Click **Launch**. Each selected model gets its own session, and the same prompt is sent to all of them. Models are checked before any workspace is created, so a model that is not available fails its entry without creating a workspace while the other models still launch. Launching is parallel, and one model failing does not stop the others: the failed entry records its error while the rest keep running.
## Isolation
@@ -23,6 +23,6 @@ With **Isolate runs** on, each run is created in its own OpenCode workspace: a d
The **Runs** tab lists each group and its entries. Every entry shows the model, its status, and for a started run the live session status indicator. From here you can:
- **Open** a run to view its session and compare the result.
- **Discard** a run after confirmation. Discarding an isolated run also removes its workspace directory from the Workspaces tab. A non-isolated run keeps its session in the repository.
- **Discard** a run after confirmation. Discarding an isolated run also removes its workspace directory from the Workspaces tab; if that workspace was already removed, for example from the Workspaces tab, discarding still succeeds. A non-isolated run keeps its session in the repository.
Discarding is irreversible and cannot be repeated on an already discarded run.
Discarding is irreversible and cannot be repeated on an already discarded run. Deleting a repository removes its multi-run history.
+1 -1
View File
@@ -11,7 +11,7 @@ Push notifications allow you to receive alerts on your mobile device or desktop
- A **session encounters an error** during execution
- A **session completes successfully**
A notification is suppressed when a visible tab is already viewing the session that raised it, preventing duplicate alerts while you're actively monitoring that session. Subagent sessions never notify. A permission request that a session answers automatically (Accept everything mode) sends no notification, and a session with an active goal does not notify for each intermediate turn.
A notification is suppressed when a visible tab is already viewing the session that raised it, preventing duplicate alerts while you're actively monitoring that session. Subagent sessions never notify. A permission request that a session answers automatically (Accept everything mode) sends no notification. Goal outcome pushes are not sent when you paused or cancelled the goal yourself, when the turn failed (the regular error notification covers it), or while you are viewing the session.
## Supported Events
+1 -1
View File
@@ -57,7 +57,7 @@ OpenCode Manager runs as a pnpm workspace:
- **Files** — Directory browser with tree view, syntax highlighting, create/rename/delete, ZIP download — [Learn more](features/files.md)
- **Schedules** — Recurring repo jobs with reusable prompts, run history, linked sessions — [Learn more](features/schedules.md)
- **Session Pinning** — Pin important sessions to the top of the session list — [Learn more](features/session-pins.md)
- **Assistant Mode** — Dedicated AI workspace with auto-provisioned skills for schedule management, notifications, settings, and repo listing — [Learn more](features/assistant-mode.md)
- **Assistant Mode** — Dedicated AI workspace with auto-provisioned skills for schedule management, notifications, settings, repo listing, and session management — [Learn more](features/assistant-mode.md)
- **AI Configuration** — Model/provider setup, OAuth for Anthropic/GitHub Copilot, custom agents — [Learn more](features/ai-config.md)
- **Server Health & Restart** — Monitor server status, graceful restarts with session resume, auto-recovery — [Learn more](features/server-health.md)
- **Manager Logs** — Manager log lines plus captured OpenCode server stdout/stderr in Settings, with level/source filters, search, and pause/copy controls — [Learn more](features/logs.md)
+13 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { getOpenCodeConfigModel, getProviders, getProvidersWithModels, providerCredentialsApi } from './providers'
import { getOpenCodeConfigModel, getProviders, getProvidersWithModels, providerCredentialsApi, providerModelRef } from './providers'
import { API_BASE_URL } from '@/config'
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
@@ -323,6 +323,18 @@ describe('getProvidersWithModels', () => {
})
})
describe('providerModelRef', () => {
it('prefers the catalog key over the backing model id', () => {
expect(providerModelRef({ id: 'anthropic' }, { id: 'claude-sonnet-4-20250514', key: 'claude-sonnet-4' })).toBe(
'anthropic/claude-sonnet-4'
)
})
it('falls back to the model id when no key is present', () => {
expect(providerModelRef({ id: 'openai' }, { id: 'gpt-4o' })).toBe('openai/gpt-4o')
})
})
describe('providerCredentialsApi', () => {
beforeEach(() => {
vi.clearAllMocks()
+4
View File
@@ -284,6 +284,10 @@ export function formatModelName(model: Model): string {
return model.name || model.id;
}
export function providerModelRef(provider: { id: string }, model: { id: string; key?: string }): string {
return `${provider.id}/${model.key ?? model.id}`;
}
export function formatProviderName(
provider: Provider | ProviderWithModels,
): string {
@@ -14,7 +14,7 @@ describe('sessionPermissionModes', () => {
})
it('calls GET /api/session-permission-modes/:id and returns the state', async () => {
const state = { sessionId: 'ses_1', rootSessionId: 'ses_1', mode: 'ask', inherited: false }
const state = { sessionId: 'ses_1', rootSessionId: 'ses_1', mode: 'ask', lockedReason: null }
fetchMock.mockResolvedValue(new Response(JSON.stringify(state), { status: 200 }))
const result = await getSessionPermissionMode('ses_1')
@@ -26,7 +26,7 @@ describe('sessionPermissionModes', () => {
it('calls PUT /api/session-permission-modes/:id with the mode and directory', async () => {
const input = { directory: '/repo', mode: 'auto' as const }
const state = { sessionId: 'ses_1', rootSessionId: 'ses_1', mode: 'auto' as const, inherited: false }
const state = { sessionId: 'ses_1', rootSessionId: 'ses_1', mode: 'auto' as const, lockedReason: null }
fetchMock.mockResolvedValue(new Response(JSON.stringify(state), { status: 200 }))
const result = await setSessionPermissionMode('ses_1', input)
@@ -91,6 +91,10 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: () => ({ data: undefined }),
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
interrupt: vi.fn(),
startGoal: vi.fn(),
useSessionGoal: vi.fn(),
useSessionPermissionMode: vi.fn(),
agents: [] as Array<{ id: string; name: string; description?: string; mode?: string; hidden?: boolean }>,
setAgent: vi.fn(),
cycleVariant: vi.fn(),
@@ -51,6 +52,10 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useStartSessionGoal: () => ({ mutateAsync: mocks.startGoal, isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: mocks.useSessionPermissionMode,
}))
vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
@@ -118,11 +123,11 @@ describe('PromptInput goal mode', () => {
onPromptChange: vi.fn(),
}
const renderComponent = () => {
const renderComponent = (overrides: Partial<typeof defaultProps> = {}) => {
const queryClient = createTestQueryClient()
return render(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} />
<PromptInput {...defaultProps} {...overrides} />
</QueryClientProvider>
)
}
@@ -130,6 +135,7 @@ describe('PromptInput goal mode', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useSessionGoal.mockReturnValue({ data: null })
mocks.useSessionPermissionMode.mockReturnValue({ data: undefined })
mocks.startGoal.mockResolvedValue({ id: 1 })
mocks.agents = []
mocks.useMobile.mockReturnValue(false)
@@ -214,6 +220,41 @@ describe('PromptInput goal mode', () => {
expect(mocks.startGoal).not.toHaveBeenCalled()
})
it('starts an armed goal before queueing when the session is busy', async () => {
stubMatchMedia(true)
renderComponent({ isStreamingResponse: true })
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: 'Ship the feature' } })
fireEvent.click(screen.getByRole('button', { name: GOAL_BUTTON }))
fireEvent.click(screen.getByTitle('Queue message'))
await waitFor(() => expect(mocks.startGoal).toHaveBeenCalledWith({
sessionId: 'test-session',
directory: '/test',
objective: 'Ship the feature',
}))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalledWith(
expect.objectContaining({ delivery: 'queue' }),
expect.anything(),
))
expect(mocks.startGoal.mock.invocationCallOrder[0]).toBeLessThan(mocks.sendPrompt.mock.invocationCallOrder[0])
})
it('does not start an armed goal for a slash command', async () => {
stubMatchMedia(true)
mocks.useCommands.mockReturnValue({ filterCommands: () => [{ name: 'review' }] })
renderComponent({ isStreamingResponse: true })
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/review the diff' } })
fireEvent.click(screen.getByRole('button', { name: GOAL_BUTTON }))
fireEvent.click(screen.getByTitle('Queue message'))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalled())
expect(mocks.startGoal).not.toHaveBeenCalled()
})
it('disables goal mode while a goal is already active', async () => {
stubMatchMedia(true)
mocks.useSessionGoal.mockReturnValue({ data: { status: 'active' } })
@@ -222,4 +263,26 @@ describe('PromptInput goal mode', () => {
const button = await screen.findByRole('button', { name: OPEN_GOAL_BUTTON })
expect(button).toBeDisabled()
})
it('disables goal mode with a reason for scheduled-run sessions', async () => {
stubMatchMedia(true)
mocks.useSessionPermissionMode.mockReturnValue({
data: { sessionId: 'test-session', rootSessionId: 'test-session', mode: 'ask', lockedReason: 'schedule' },
})
renderComponent()
const button = await screen.findByRole('button', { name: 'Scheduled runs cannot run goals' })
expect(button).toBeDisabled()
})
it('disables goal mode with a reason for child sessions', async () => {
stubMatchMedia(true)
mocks.useSessionPermissionMode.mockReturnValue({
data: { sessionId: 'test-session', rootSessionId: 'test-session', mode: 'ask', lockedReason: 'child' },
})
renderComponent()
const button = await screen.findByRole('button', { name: 'Goals can only be started on top-level sessions' })
expect(button).toBeDisabled()
})
})
@@ -82,6 +82,10 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: () => ({ data: undefined }),
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
@@ -109,6 +109,10 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: () => ({ data: undefined }),
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
+36 -24
View File
@@ -20,6 +20,7 @@ import { usePermissions } from '@/contexts/EventContext'
import { ArrowDown, Upload, X, Mic, MicOff, Target } from 'lucide-react'
import { SquareFill } from '@/components/ui/square-fill'
import { IconToggleButton } from '@/components/ui/icon-toggle-button'
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
import { MentionSuggestions, type MentionItem } from './MentionSuggestions'
@@ -29,6 +30,7 @@ import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
import { VoiceStatusOverlay, type VoiceStatusOverlayState } from './VoiceStatusOverlay'
import { PermissionModeToggle } from '@/components/session/PermissionModeToggle'
import { useSessionGoal, useStartSessionGoal } from '@/hooks/useSessionGoals'
import { useSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
import { detectMentionTrigger, parsePromptToInput, getFilename, filterAgentsByQuery } from '@/lib/promptParser'
import { getNextPrimaryAgentId } from '@/lib/primaryAgents'
import { randomId } from '@/lib/utils'
@@ -233,6 +235,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const interruptSession = useInterruptSession()
const { data: sessionGoal } = useSessionGoal(sessionID)
const startGoal = useStartSessionGoal()
const { data: permissionMode } = useSessionPermissionMode(sessionID)
const { filterCommands } = useCommands({ directory })
const isExactCommandPrompt = (value: string) => {
const commandPrompt = parseCommandPrompt(value)
@@ -295,6 +298,17 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const addUserBashCommand = useUserBash((s) => s.addUserBashCommand)
const startArmedGoal = async (objective: string): Promise<boolean> => {
if (!directory || !objective.trim()) return true
try {
await startGoal.mutateAsync({ sessionId: sessionID, directory, objective })
} catch {
return false
}
setIsGoalArmed(false)
return true
}
const handleSubmit = async () => {
if (!prompt.trim() && imageAttachments.length === 0) return
@@ -307,6 +321,10 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
if (isGoalArmed && !isBashMode && !isExactCommandPrompt(prompt)) {
const goalStarted = await startArmedGoal(parsed.text)
if (!goalStarted) return
}
sendPrompt.mutate(
{
sessionID,
@@ -389,13 +407,9 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
if (isGoalArmed && directory && parsed.text.trim()) {
try {
await startGoal.mutateAsync({ sessionId: sessionID, directory, objective: parsed.text })
} catch {
return
}
setIsGoalArmed(false)
if (isGoalArmed) {
const goalStarted = await startArmedGoal(parsed.text)
if (!goalStarted) return
}
pendingConfirmClearRef.current = {
@@ -1162,27 +1176,25 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
const hideSecondaryButtons = isMobile && isSessionActive
const showMobileScrollButton = isMobile && showScrollButton
const hasOpenGoal = sessionGoal?.status === 'active' || sessionGoal?.status === 'paused'
const goalButtonLabel = hasOpenGoal
? 'A goal is already active for this session'
: isGoalArmed
? 'Goal mode armed: the next message becomes the objective'
: 'Goal mode: the next message becomes the objective'
const lockedReason = permissionMode?.lockedReason ?? null
const goalButtonLabel = lockedReason === 'schedule'
? 'Scheduled runs cannot run goals'
: lockedReason === 'child'
? 'Goals can only be started on top-level sessions'
: hasOpenGoal
? 'A goal is already active for this session'
: isGoalArmed
? 'Goal mode armed: the next message becomes the objective'
: 'Goal mode: the next message becomes the objective'
const goalModeButton = directory ? (
<button
type="button"
<IconToggleButton
active={isGoalArmed}
label={goalButtonLabel}
disabled={lockedReason !== null || hasOpenGoal || isBashMode || startGoal.isPending}
onClick={() => setIsGoalArmed((value) => !value)}
disabled={hasOpenGoal || isBashMode || startGoal.isPending}
aria-pressed={isGoalArmed}
aria-label={goalButtonLabel}
title={goalButtonLabel}
className={`p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border disabled:opacity-50 disabled:cursor-not-allowed disabled:active:scale-100 disabled:hover:scale-100 ${
isGoalArmed
? 'bg-highlight hover:bg-highlight/90 text-highlight-foreground border-highlight'
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
}`}
>
<Target className="w-5 h-5" />
</button>
</IconToggleButton>
) : null
const voiceFeedbackState: VoiceStatusOverlayState | null = isTogglingRecording
? 'starting'
@@ -60,6 +60,7 @@ const providers = [
{ id: 'claude-opus', name: 'Claude Opus' },
{ id: 'claude-sonnet', name: 'Claude Sonnet' },
{ id: 'claude-haiku', name: 'Claude Haiku' },
{ id: 'claude-sonnet-4-5', key: 'claude-sonnet-4.5', name: 'Claude Sonnet 4.5' },
],
},
]
@@ -164,6 +165,28 @@ describe('MultiRunDialog', () => {
})
})
it('submits the catalog id for configured model aliases', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(startedRun)
renderDialog()
await user.type(screen.getByLabelText('Group name'), 'Sweep')
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'Claude Sonnet 4.5' }))
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith({
repoId: 7,
name: 'Sweep',
prompt: 'go',
models: ['anthropic/claude-sonnet-4.5'],
isolate: true,
baseRef: 'main',
})
})
})
it('lists run entries with Open and Discard actions', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([startedRun])
+53 -32
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from 'react'
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Loader2, Trash2, ArrowUpRight } from 'lucide-react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
@@ -14,6 +14,8 @@ import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-di
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
import { useDiscardMultiRunEntry, useLaunchMultiRun, useMultiRuns } from '@/hooks/useMultiRuns'
import { formatModelName, formatProviderName, providerModelRef, type ProviderWithModels } from '@/api/providers'
import { buildSessionPath } from '@opencode-manager/shared/utils'
import {
MULTI_RUN_MAX_MODELS,
type LaunchMultiRunRequest,
@@ -79,7 +81,7 @@ export function MultiRunDialog({
[providers],
)
const toggleModel = (value: string, checked: boolean) => {
const toggleModel = useCallback((value: string, checked: boolean) => {
setSelectedModels((current) => {
if (checked) {
if (current.includes(value) || current.length >= MULTI_RUN_MAX_MODELS) return current
@@ -87,7 +89,7 @@ export function MultiRunDialog({
}
return current.filter((model) => model !== value)
})
}
}, [])
const canSubmit =
name.trim().length > 0 && prompt.trim().length > 0 && selectedModels.length > 0 && !launch.isPending
@@ -108,8 +110,7 @@ export function MultiRunDialog({
const openEntry = (entry: MultiRunEntry) => {
if (!entry.sessionId) return
onOpenChange(false)
const suffix = entry.isolated ? '?repoTab=workspaces' : ''
navigate(`/repos/${repoId}/sessions/${entry.sessionId}${suffix}`)
navigate(buildSessionPath(repoId, entry.sessionId, entry.isolated ? { repoTab: 'workspaces' } : undefined))
}
const confirmDiscard = () => {
@@ -171,33 +172,11 @@ export function MultiRunDialog({
</span>
</div>
<div className="max-h-56 overflow-y-auto rounded-md border border-border divide-y divide-border">
{modelGroups.length === 0 ? (
<p className="p-3 text-sm text-muted-foreground">No models available.</p>
) : (
modelGroups.map((provider) => (
<div key={provider.id} className="p-3 space-y-2">
<p className="text-xs font-medium text-muted-foreground">
{provider.name || provider.id}
</p>
{provider.models.map((model) => {
const value = `${provider.id}/${model.id}`
const checked = selectedModels.includes(value)
const atCapacity = selectedModels.length >= MULTI_RUN_MAX_MODELS && !checked
return (
<label key={value} className="flex items-center gap-2 text-sm">
<Checkbox
aria-label={model.name || model.id}
checked={checked}
disabled={atCapacity}
onCheckedChange={(next) => toggleModel(value, next === true)}
/>
<span className="truncate">{model.name || model.id}</span>
</label>
)
})}
</div>
))
)}
<ModelCheckboxList
providers={modelGroups}
selectedModels={selectedModels}
onToggle={toggleModel}
/>
</div>
</div>
@@ -321,6 +300,48 @@ export function MultiRunDialog({
)
}
interface ModelCheckboxListProps {
providers: ProviderWithModels[]
selectedModels: string[]
onToggle: (value: string, checked: boolean) => void
}
const ModelCheckboxList = memo(function ModelCheckboxList({
providers,
selectedModels,
onToggle,
}: ModelCheckboxListProps) {
if (providers.length === 0) {
return <p className="p-3 text-sm text-muted-foreground">No models available.</p>
}
return (
<>
{providers.map((provider) => (
<div key={provider.id} className="p-3 space-y-2">
<p className="text-xs font-medium text-muted-foreground">{formatProviderName(provider)}</p>
{provider.models.map((model) => {
const value = providerModelRef(provider, model)
const checked = selectedModels.includes(value)
const atCapacity = selectedModels.length >= MULTI_RUN_MAX_MODELS && !checked
return (
<label key={value} className="flex items-center gap-2 text-sm">
<Checkbox
aria-label={formatModelName(model)}
checked={checked}
disabled={atCapacity}
onCheckedChange={(next) => onToggle(value, next === true)}
/>
<span className="truncate">{formatModelName(model)}</span>
</label>
)
})}
</div>
))}
</>
)
})
function EntryStatus({ entry }: { entry: MultiRunEntry }) {
if (entry.status === 'started' && entry.sessionId) {
return (
@@ -21,7 +21,8 @@ vi.mock('@/hooks/usePromptTemplates', () => ({
useDeletePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
}))
vi.mock('@/api/providers', () => ({
vi.mock('@/api/providers', async (importOriginal) => ({
...(await importOriginal<typeof import('@/api/providers')>()),
getProvidersWithModels: mockGetProvidersWithModels,
}))
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob, ScheduleMcpServer } from '@opencode-manager/shared/types'
import { useScheduleModels } from '@/hooks/useScheduleModels'
import { providerModelRef } from '@/api/providers'
import { resolveScheduleModel } from '@/lib/schedules/schedule-model'
import { useAgents } from '@/hooks/useOpenCode'
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
@@ -161,7 +162,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
const providerModel = provider?.models.find((m) => m.key === modelId || m.id === modelId)
configuredValues.add(configDefaultModel)
if (providerModel) {
configuredValues.add(`${providerId}/${providerModel.key ?? providerModel.id}`)
configuredValues.add(providerModelRef({ id: providerId }, providerModel))
configuredValues.add(`${providerId}/${providerModel.id}`)
}
configuredModels.push({
@@ -174,11 +175,11 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
const allModels = providerModels.flatMap((provider) =>
provider.models
.filter((providerModel) => !configuredValues.has(`${provider.id}/${providerModel.key ?? providerModel.id}`))
.filter((providerModel) => !configuredValues.has(providerModelRef(provider, providerModel)))
.map((providerModel) => ({
value: `${provider.id}/${providerModel.key ?? providerModel.id}`,
value: providerModelRef(provider, providerModel),
label: providerModel.name || providerModel.key || providerModel.id,
description: `${provider.id}/${providerModel.key ?? providerModel.id}`,
description: providerModelRef(provider, providerModel),
group: provider.name,
})),
)
@@ -11,7 +11,7 @@ const baseState: SessionPermissionModeState = {
sessionId: 'ses_1',
rootSessionId: 'ses_1',
mode: 'ask',
inherited: false,
lockedReason: null,
}
function mockHooks(overrides: {
@@ -66,14 +66,22 @@ describe('PermissionModeToggle', () => {
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'ask' })
})
it('is disabled and labelled as inherited for child sessions', () => {
mockHooks({ state: { inherited: true, mode: 'auto' } })
it('is disabled and labelled as locked for child sessions', () => {
mockHooks({ state: { lockedReason: 'child', mode: 'auto' } })
render(<PermissionModeToggle sessionID="ses_child" directory="/repo" />)
const button = screen.getByRole('button', { name: 'Inherited from parent session' })
expect(button).toBeDisabled()
})
it('is disabled and labelled for schedule-run sessions', () => {
mockHooks({ state: { lockedReason: 'schedule', mode: 'ask' } })
render(<PermissionModeToggle sessionID="ses_sched" directory="/repo" />)
const button = screen.getByRole('button', { name: "Scheduled runs use the schedule's permission configuration" })
expect(button).toBeDisabled()
})
it('cannot mutate while the mode read is still loading', async () => {
const user = userEvent.setup()
const mutate = vi.fn()
@@ -1,5 +1,6 @@
import { Shield, ShieldCheck } from 'lucide-react'
import { useSessionPermissionMode, useSetSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
import { IconToggleButton } from '@/components/ui/icon-toggle-button'
interface PermissionModeToggleProps {
sessionID: string
@@ -12,18 +13,20 @@ export function PermissionModeToggle({ sessionID, directory }: PermissionModeTog
const loaded = data !== undefined
const isAuto = data?.mode === 'auto'
const inherited = data?.inherited ?? false
const disabled = !loaded || inherited || setMode.isPending
const lockedReason = data?.lockedReason ?? null
const disabled = !loaded || lockedReason !== null || setMode.isPending
const label = !loaded
? isError
? 'Permissions: unavailable'
: 'Permissions: loading'
: inherited
: lockedReason === 'child'
? 'Inherited from parent session'
: isAuto
? 'Permissions: accept everything'
: 'Permissions: ask every time'
: lockedReason === 'schedule'
? "Scheduled runs use the schedule's permission configuration"
: isAuto
? 'Permissions: accept everything'
: 'Permissions: ask every time'
const handleClick = () => {
if (disabled) return
@@ -31,19 +34,8 @@ export function PermissionModeToggle({ sessionID, directory }: PermissionModeTog
}
return (
<button
type="button"
onClick={handleClick}
disabled={disabled}
title={label}
aria-label={label}
className={`p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border disabled:opacity-50 disabled:cursor-not-allowed disabled:active:scale-100 disabled:hover:scale-100 ${
isAuto
? 'bg-highlight hover:bg-highlight/90 text-highlight-foreground border-highlight'
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
}`}
>
<IconToggleButton active={isAuto} label={label} disabled={disabled} onClick={handleClick}>
{isAuto ? <ShieldCheck className="w-5 h-5" /> : <Shield className="w-5 h-5" />}
</button>
</IconToggleButton>
)
}
@@ -107,7 +107,7 @@ describe('SessionGoalBar', () => {
render(<SessionGoalBar sessionID="ses_1" />)
expect(screen.getByText('Goal completed')).toBeInTheDocument()
expect(screen.getByText('continuation limit reached')).toBeInTheDocument()
expect(screen.getByText('Continuation limit reached')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Pause' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Dismiss' }))
@@ -115,6 +115,22 @@ describe('SessionGoalBar', () => {
expect(screen.queryByText('Goal completed')).not.toBeInTheDocument()
})
it('shows the shared stop-reason wording for a user-paused goal', () => {
mockGoals({ ...baseGoal, status: 'stopped', stopReason: 'user_paused' })
render(<SessionGoalBar sessionID="ses_1" />)
expect(screen.getByText('Goal stopped')).toBeInTheDocument()
expect(screen.getByText('Paused by user')).toBeInTheDocument()
})
it('shows the shared stop-reason wording for an audit failure', () => {
mockGoals({ ...baseGoal, status: 'blocked', stopReason: 'audit_failed' })
render(<SessionGoalBar sessionID="ses_1" />)
expect(screen.getByText('Goal blocked')).toBeInTheDocument()
expect(screen.getByText('Audit failed')).toBeInTheDocument()
})
it('cancels the goal through the cancel API', async () => {
const user = userEvent.setup()
const cancel = vi.fn()
@@ -1,32 +1,15 @@
import { useState } from 'react'
import { ChevronDown, ChevronUp, Target } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
useCancelSessionGoal,
usePauseSessionGoal,
useResumeSessionGoal,
useSessionGoal,
} from '@/hooks/useSessionGoals'
import type { SessionGoalStatus, SessionGoalStopReason } from '@opencode-manager/shared/schemas'
const STATUS_LABELS: Record<SessionGoalStatus, string> = {
active: 'Goal active',
paused: 'Goal paused',
completed: 'Goal completed',
blocked: 'Goal blocked',
stopped: 'Goal stopped',
}
const STOP_REASON_LABELS: Record<SessionGoalStopReason, string> = {
cancelled: 'cancelled',
user_paused: 'paused by you',
continuation_limit: 'continuation limit reached',
token_budget: 'token budget reached',
turn_error: 'turn failed',
interrupted: 'interrupted',
audit_failed: 'auditor failed',
session_deleted: 'session deleted',
}
import { getGoalOutcomeTitle, getGoalStopReasonLabel } from '@opencode-manager/shared/notifications'
import type { SessionGoalStatus } from '@opencode-manager/shared/schemas'
const STATUS_CHIP_CLASSES: Record<SessionGoalStatus, string> = {
active: 'bg-highlight text-highlight-foreground border-highlight',
@@ -54,17 +37,18 @@ export function SessionGoalBar({ sessionID }: { sessionID: string }) {
if (isTerminal(goal.status) && dismissedGoalId === goal.id) return null
const terminal = isTerminal(goal.status)
const reason = goal.stopReason ? STOP_REASON_LABELS[goal.stopReason] : goal.lastReason
const reason = goal.stopReason ? getGoalStopReasonLabel(goal.stopReason) : goal.lastReason
return (
<div className="mb-1 flex flex-col gap-1 rounded-lg border border-border bg-card/70 px-2 py-1.5 text-xs">
<div className="flex flex-wrap items-center gap-2">
<span
className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 font-medium ${STATUS_CHIP_CLASSES[goal.status]}`}
<Badge
variant="outline"
className={`gap-1 px-2 py-0.5 font-medium ${STATUS_CHIP_CLASSES[goal.status]}`}
>
<Target className="h-3 w-3" />
{STATUS_LABELS[goal.status]}
</span>
{getGoalOutcomeTitle(goal.status)}
</Badge>
{!terminal && (
<span className="text-muted-foreground">
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { act, render, screen, fireEvent } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SessionAutomationSettings } from './SessionAutomationSettings'
import { useSettings } from '@/hooks/useSettings'
@@ -43,7 +43,7 @@ describe('SessionAutomationSettings', () => {
expect(screen.getByRole('combobox', { name: 'Default permission mode for new sessions' })).toHaveTextContent('Ask every time')
})
it('persists the chosen default permission mode', async () => {
it('persists the chosen default permission mode immediately', async () => {
const user = userEvent.setup()
const updateSettings = vi.fn()
mockUseSettings({
@@ -58,7 +58,7 @@ describe('SessionAutomationSettings', () => {
expect(updateSettings).toHaveBeenCalledWith({ sessionDefaults: { permissionMode: 'auto' } })
})
it('persists the goal auditor model', () => {
it('saves the goal auditor model once on blur with the final value', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
@@ -66,10 +66,11 @@ describe('SessionAutomationSettings', () => {
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Goal auditor model'), {
target: { value: 'anthropic/claude-sonnet-4' },
})
const input = screen.getByLabelText('Goal auditor model')
fireEvent.change(input, { target: { value: 'anthropic/claude-sonnet-4' } })
fireEvent.blur(input)
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
@@ -79,7 +80,37 @@ describe('SessionAutomationSettings', () => {
})
})
it('persists the max automatic continuations', () => {
it('saves the goal auditor model after the debounce without blurring', () => {
vi.useFakeTimers()
try {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Goal auditor model'), {
target: { value: 'anthropic/claude-sonnet-4' },
})
act(() => {
vi.advanceTimersByTime(800)
})
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
goalMaxContinuations: 20,
goalAuditorModel: 'anthropic/claude-sonnet-4',
},
})
} finally {
vi.useRealTimers()
}
})
it('saves an in-range max automatic continuations on blur', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
@@ -87,16 +118,16 @@ describe('SessionAutomationSettings', () => {
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Max automatic continuations'), {
target: { value: '50' },
})
const input = screen.getByLabelText('Max automatic continuations')
fireEvent.change(input, { target: { value: '50' } })
fireEvent.blur(input)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 50 },
})
})
it('persists the token budget per goal', () => {
it('does not save out-of-range max automatic continuations', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
@@ -104,9 +135,24 @@ describe('SessionAutomationSettings', () => {
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Token budget per goal'), {
target: { value: '5000' },
const input = screen.getByLabelText('Max automatic continuations')
fireEvent.change(input, { target: { value: '500' } })
fireEvent.blur(input)
expect(updateSettings).not.toHaveBeenCalled()
})
it('saves the token budget per goal on blur', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
const input = screen.getByLabelText('Token budget per goal')
fireEvent.change(input, { target: { value: '5000' } })
fireEvent.blur(input)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20, goalTokenBudget: 5000 },
@@ -1,26 +1,97 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import type { SessionDefaults, SessionPermissionMode } from '@opencode-manager/shared/schemas'
import {
DEFAULT_SESSION_DEFAULTS,
GOAL_MAX_CONTINUATIONS_MAX,
GOAL_MAX_CONTINUATIONS_MIN,
type SessionDefaults,
type SessionPermissionMode,
} from '@opencode-manager/shared/schemas'
const AUTOSAVE_DELAY_MS = 800
export function SessionAutomationSettings() {
const { preferences, updateSettings } = useSettings()
const sessionDefaults = preferences?.sessionDefaults
const permissionMode = sessionDefaults?.permissionMode ?? 'ask'
const goalMaxContinuations = sessionDefaults?.goalMaxContinuations ?? 20
const goalTokenBudget = sessionDefaults?.goalTokenBudget
const goalAuditorModel = sessionDefaults?.goalAuditorModel ?? ''
const permissionMode = sessionDefaults?.permissionMode ?? DEFAULT_SESSION_DEFAULTS.permissionMode
const updateSessionDefaults = (patch: Partial<SessionDefaults>) => {
updateSettings({
sessionDefaults: {
...sessionDefaults,
permissionMode,
...patch,
},
})
}
const [goalAuditorModel, setGoalAuditorModel] = useState(sessionDefaults?.goalAuditorModel ?? '')
const [goalMaxContinuations, setGoalMaxContinuations] = useState(
String(sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations),
)
const [goalTokenBudget, setGoalTokenBudget] = useState(
sessionDefaults?.goalTokenBudget !== undefined ? String(sessionDefaults.goalTokenBudget) : '',
)
const committed = useRef({
goalAuditorModel: sessionDefaults?.goalAuditorModel,
goalMaxContinuations: sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations,
goalTokenBudget: sessionDefaults?.goalTokenBudget,
})
useEffect(() => {
setGoalAuditorModel(sessionDefaults?.goalAuditorModel ?? '')
setGoalMaxContinuations(
String(sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations),
)
setGoalTokenBudget(
sessionDefaults?.goalTokenBudget !== undefined ? String(sessionDefaults.goalTokenBudget) : '',
)
committed.current = {
goalAuditorModel: sessionDefaults?.goalAuditorModel,
goalMaxContinuations: sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations,
goalTokenBudget: sessionDefaults?.goalTokenBudget,
}
}, [sessionDefaults])
const updateSessionDefaults = useCallback(
(patch: Partial<SessionDefaults>) => {
updateSettings({
sessionDefaults: {
...sessionDefaults,
permissionMode,
...patch,
},
})
},
[sessionDefaults, permissionMode, updateSettings],
)
const commitGoalAuditorModel = useCallback(() => {
const next = goalAuditorModel.trim() || undefined
if (next === committed.current.goalAuditorModel) return
committed.current.goalAuditorModel = next
updateSessionDefaults({ goalAuditorModel: next })
}, [goalAuditorModel, updateSessionDefaults])
const commitGoalMaxContinuations = useCallback(() => {
const value = Number(goalMaxContinuations)
if (!Number.isInteger(value) || value < GOAL_MAX_CONTINUATIONS_MIN || value > GOAL_MAX_CONTINUATIONS_MAX) return
if (value === committed.current.goalMaxContinuations) return
committed.current.goalMaxContinuations = value
updateSessionDefaults({ goalMaxContinuations: value })
}, [goalMaxContinuations, updateSessionDefaults])
const commitGoalTokenBudget = useCallback(() => {
const next = goalTokenBudget.trim() === '' ? undefined : Number(goalTokenBudget)
if (next !== undefined && (!Number.isInteger(next) || next <= 0)) return
if (next === committed.current.goalTokenBudget) return
committed.current.goalTokenBudget = next
updateSessionDefaults({ goalTokenBudget: next })
}, [goalTokenBudget, updateSessionDefaults])
useEffect(() => {
const timer = setTimeout(() => {
commitGoalAuditorModel()
commitGoalMaxContinuations()
commitGoalTokenBudget()
}, AUTOSAVE_DELAY_MS)
return () => clearTimeout(timer)
}, [commitGoalAuditorModel, commitGoalMaxContinuations, commitGoalTokenBudget])
return (
<div className="space-y-6">
@@ -59,7 +130,8 @@ export function SessionAutomationSettings() {
value={goalAuditorModel}
placeholder="provider/model"
className="w-full shrink-0 sm:w-64"
onChange={(event) => updateSessionDefaults({ goalAuditorModel: event.target.value.trim() || undefined })}
onChange={(event) => setGoalAuditorModel(event.target.value)}
onBlur={commitGoalAuditorModel}
/>
</div>
@@ -73,16 +145,12 @@ export function SessionAutomationSettings() {
<Input
id="goalMaxContinuations"
type="number"
min={1}
max={200}
min={GOAL_MAX_CONTINUATIONS_MIN}
max={GOAL_MAX_CONTINUATIONS_MAX}
value={goalMaxContinuations}
className="w-full shrink-0 sm:w-40"
onChange={(event) => {
const value = Number(event.target.value)
if (Number.isInteger(value) && value >= 1 && value <= 200) {
updateSessionDefaults({ goalMaxContinuations: value })
}
}}
onChange={(event) => setGoalMaxContinuations(event.target.value)}
onBlur={commitGoalMaxContinuations}
/>
</div>
@@ -97,20 +165,11 @@ export function SessionAutomationSettings() {
id="goalTokenBudget"
type="number"
min={1}
value={goalTokenBudget ?? ''}
value={goalTokenBudget}
placeholder="No limit"
className="w-full shrink-0 sm:w-40"
onChange={(event) => {
const raw = event.target.value
if (raw === '') {
updateSessionDefaults({ goalTokenBudget: undefined })
return
}
const value = Number(raw)
if (Number.isInteger(value) && value > 0) {
updateSessionDefaults({ goalTokenBudget: value })
}
}}
onChange={(event) => setGoalTokenBudget(event.target.value)}
onBlur={commitGoalTokenBudget}
/>
</div>
</div>
@@ -0,0 +1,29 @@
import type { ReactNode } from 'react'
interface IconToggleButtonProps {
active: boolean
label: string
disabled?: boolean
onClick: () => void
children: ReactNode
}
export function IconToggleButton({ active, label, disabled = false, onClick, children }: IconToggleButtonProps) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-pressed={active}
aria-label={label}
title={label}
className={`p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border disabled:opacity-50 disabled:cursor-not-allowed disabled:active:scale-100 disabled:hover:scale-100 ${
active
? 'bg-highlight hover:bg-highlight/90 text-highlight-foreground border-highlight'
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
}`}
>
{children}
</button>
)
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { repoSiblingsQueryKey } from '@/hooks/useRepoSiblings'
import { showToast } from '@/lib/toast'
import type { LaunchMultiRunRequest, MultiRun } from '@opencode-manager/shared/schemas'
export function multiRunQueryKey(repoId: number) {
function multiRunQueryKey(repoId: number) {
return ['multi-runs', repoId] as const
}
@@ -0,0 +1,72 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useSessionGoal } from './useSessionGoals'
import { getLatestSessionGoal } from '@/api/sessionGoals'
import type { SessionGoal, SessionGoalStatus } from '@opencode-manager/shared/schemas'
vi.mock('@/api/sessionGoals', () => ({
getLatestSessionGoal: vi.fn(),
startSessionGoal: vi.fn(),
pauseSessionGoal: vi.fn(),
resumeSessionGoal: vi.fn(),
cancelSessionGoal: vi.fn(),
}))
vi.mock('@/lib/toast', () => ({
showToast: { error: vi.fn() },
}))
const baseGoal: SessionGoal = {
id: 1,
sessionId: 'ses_1',
directory: '/repo',
objective: 'Ship the feature',
status: 'active',
stopReason: null,
turnState: 'running',
continuationCount: 0,
maxContinuations: 20,
tokenBudget: null,
tokensUsed: 0,
consecutiveBlocked: 0,
lastVerdict: null,
lastReason: null,
createdAt: 1,
updatedAt: 1,
finishedAt: null,
}
function createWrapper(queryClient: QueryClient) {
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
describe('useSessionGoal', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('polls only while the goal is active', async () => {
vi.mocked(getLatestSessionGoal).mockResolvedValue(baseGoal)
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
renderHook(() => useSessionGoal('ses_1'), { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(getLatestSessionGoal).toHaveBeenCalled())
const query = queryClient.getQueryCache().find({ queryKey: ['session-goal', 'ses_1'] })
const refetchInterval = query?.options.refetchInterval as
| ((query: { state: { data?: { status: SessionGoalStatus } } }) => number | false)
| undefined
expect(refetchInterval).toBeTypeOf('function')
expect(refetchInterval!({ state: { data: { status: 'active' } } })).toBe(3000)
expect(refetchInterval!({ state: { data: { status: 'paused' } } })).toBe(false)
expect(refetchInterval!({ state: { data: { status: 'completed' } } })).toBe(false)
expect(refetchInterval!({ state: { data: { status: 'blocked' } } })).toBe(false)
expect(refetchInterval!({ state: { data: { status: 'stopped' } } })).toBe(false)
expect(refetchInterval!({ state: {} })).toBe(false)
})
})
+2 -5
View File
@@ -9,7 +9,7 @@ import {
import { showToast } from '@/lib/toast'
import type { SessionGoal, StartSessionGoalRequest } from '@opencode-manager/shared/schemas'
export function sessionGoalQueryKey(sessionId: string) {
function sessionGoalQueryKey(sessionId: string) {
return ['session-goal', sessionId] as const
}
@@ -17,10 +17,7 @@ export function useSessionGoal(sessionId: string) {
return useQuery({
queryKey: sessionGoalQueryKey(sessionId),
queryFn: () => getLatestSessionGoal(sessionId),
refetchInterval: (query) => {
const status = query.state.data?.status
return status === 'active' || status === 'paused' ? 3000 : false
},
refetchInterval: (query) => (query.state.data?.status === 'active' ? 3000 : false),
})
}
@@ -3,7 +3,7 @@ import { getSessionPermissionMode, setSessionPermissionMode } from '@/api/sessio
import { showToast } from '@/lib/toast'
import type { SessionPermissionModeState, SetSessionPermissionModeRequest } from '@opencode-manager/shared/schemas'
export function sessionPermissionModeQueryKey(sessionId: string) {
function sessionPermissionModeQueryKey(sessionId: string) {
return ['session-permission-mode', sessionId] as const
}
+10
View File
@@ -70,6 +70,16 @@ describe('getSessionPath', () => {
expect(getSessionPath(0, 'ses_1')).toBe('/repos/0/sessions/ses_1?assistant=1');
expect(getSessionPath('0', 'ses_1')).toBe('/repos/0/sessions/ses_1?assistant=1');
});
it('includes a repoTab query param when provided', () => {
expect(getSessionPath(5, 'ses_1', { repoTab: 'workspaces' })).toBe('/repos/5/sessions/ses_1?repoTab=workspaces');
});
it('combines the assistant and repoTab query params', () => {
expect(getSessionPath(0, 'ses_1', { repoTab: 'workspaces' })).toBe(
'/repos/0/sessions/ses_1?assistant=1&repoTab=workspaces'
);
});
});
describe('getRepoPath', () => {
+3 -4
View File
@@ -1,4 +1,4 @@
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils';
import { ASSISTANT_REPO_ID, buildSessionPath } from '@opencode-manager/shared/utils';
export function getAssistantPath(): string {
return '/assistant';
@@ -20,9 +20,8 @@ export function getRepoPath(repoId: number | string): string {
return isAssistantRepo(repoId) ? getAssistantPath() : `/repos/${repoId}`;
}
export function getSessionPath(repoId: number | string, sessionId: string): string {
const suffix = isAssistantRepo(repoId) ? '?assistant=1' : '';
return `/repos/${repoId}/sessions/${sessionId}${suffix}`;
export function getSessionPath(repoId: number | string, sessionId: string, options?: { repoTab?: string }): string {
return buildSessionPath(repoId, sessionId, options);
}
export function parseRepoRoute(pathname: string): { repoId: number | null; section: string | null; sessionId: string | null } {
+2 -1
View File
@@ -1,4 +1,5 @@
import type { ProviderWithModels } from '@/api/providers'
import { providerModelRef } from '@/api/providers'
import type { OpenCodeConfigFile } from '@/api/types/settings'
function normalizeModel(model: unknown): string | null {
@@ -11,7 +12,7 @@ export function buildAvailableModelKeys(providers: ProviderWithModels[]): Set<st
const keys = new Set<string>()
for (const provider of providers) {
for (const model of provider.models) {
keys.add(`${provider.id}/${model.key ?? model.id}`)
keys.add(providerModelRef(provider, model))
keys.add(`${provider.id}/${model.id}`)
}
}
@@ -128,6 +128,9 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: vi.fn(() => ({ data: undefined })),
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: vi.fn(() => null),
}))
@@ -134,6 +134,9 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: vi.fn(() => ({ data: undefined })),
}))
vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
vi.mock('@/components/session/PermissionModeToggle', () => ({ PermissionModeToggle: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
+29
View File
@@ -1,3 +1,32 @@
import type { SessionGoalStatus, SessionGoalStopReason } from '../schemas/session-goals'
const GOAL_OUTCOME_TITLES: Record<SessionGoalStatus, string> = {
active: 'Goal active',
paused: 'Goal paused',
completed: 'Goal completed',
blocked: 'Goal blocked',
stopped: 'Goal stopped',
}
const GOAL_STOP_REASON_LABELS: Record<SessionGoalStopReason, string> = {
cancelled: 'Cancelled',
user_paused: 'Paused by user',
continuation_limit: 'Continuation limit reached',
token_budget: 'Token budget reached',
turn_error: 'Turn failed',
interrupted: 'Interrupted',
audit_failed: 'Audit failed',
session_deleted: 'Session deleted',
}
export function getGoalOutcomeTitle(status: SessionGoalStatus): string {
return GOAL_OUTCOME_TITLES[status]
}
export function getGoalStopReasonLabel(stopReason: SessionGoalStopReason): string {
return GOAL_STOP_REASON_LABELS[stopReason]
}
const PERMISSION_LABELS: Record<string, string> = {
read: 'Read File',
edit: 'Edit File',
+1
View File
@@ -1,3 +1,4 @@
export * from './limits'
export * from './settings'
export * from './repo'
export * from './files'
+3 -8
View File
@@ -1,9 +1,10 @@
import { z } from "zod";
import { SESSION_PROMPT_MAX_LENGTH } from "./limits";
export const InternalCreateSessionRequestSchema = z
.object({
repoId: z.number().int(),
prompt: z.string().trim().min(1).max(20000),
prompt: z.string().trim().min(1).max(SESSION_PROMPT_MAX_LENGTH),
title: z.string().max(200).optional(),
model: z.string().optional(),
agent: z.string().optional(),
@@ -12,20 +13,14 @@ export const InternalCreateSessionRequestSchema = z
})
.strict();
export type InternalCreateSessionRequest = z.infer<typeof InternalCreateSessionRequestSchema>;
export const InternalSessionPromptRequestSchema = z
.object({
text: z.string().trim().min(1).max(20000),
text: z.string().trim().min(1).max(SESSION_PROMPT_MAX_LENGTH),
})
.strict();
export type InternalSessionPromptRequest = z.infer<typeof InternalSessionPromptRequestSchema>;
export const InternalForkSessionRequestSchema = z
.object({
beforeMessageId: z.string().optional(),
})
.strict();
export type InternalForkSessionRequest = z.infer<typeof InternalForkSessionRequestSchema>;
+3
View File
@@ -0,0 +1,3 @@
export const SESSION_PROMPT_MAX_LENGTH = 20000;
export const GOAL_MAX_CONTINUATIONS_MIN = 1;
export const GOAL_MAX_CONTINUATIONS_MAX = 200;
+2 -1
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { SESSION_PROMPT_MAX_LENGTH } from "./limits";
export const MULTI_RUN_MAX_MODELS = 5;
@@ -36,7 +37,7 @@ export type MultiRun = z.infer<typeof MultiRunSchema>;
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),
prompt: z.string().trim().min(1).max(SESSION_PROMPT_MAX_LENGTH),
models: z
.array(z.string().min(3))
.min(1)
+3 -2
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { SESSION_PROMPT_MAX_LENGTH, GOAL_MAX_CONTINUATIONS_MIN, GOAL_MAX_CONTINUATIONS_MAX } from "./limits";
export const SessionGoalStatusSchema = z.enum(["active", "paused", "completed", "blocked", "stopped"]);
@@ -50,8 +51,8 @@ export type SessionGoal = z.infer<typeof SessionGoalSchema>;
export const StartSessionGoalRequestSchema = z.object({
sessionId: z.string().min(1),
directory: z.string().min(1),
objective: z.string().trim().min(1).max(20000),
maxContinuations: z.number().int().min(1).max(200).optional(),
objective: z.string().trim().min(1).max(SESSION_PROMPT_MAX_LENGTH),
maxContinuations: z.number().int().min(GOAL_MAX_CONTINUATIONS_MIN).max(GOAL_MAX_CONTINUATIONS_MAX).optional(),
tokenBudget: z.number().int().positive().optional(),
});
+5 -1
View File
@@ -4,6 +4,10 @@ export const SessionPermissionModeSchema = z.enum(["ask", "auto"]);
export type SessionPermissionMode = z.infer<typeof SessionPermissionModeSchema>;
export const SessionLockReasonSchema = z.enum(["schedule", "child"]);
export type SessionLockReason = z.infer<typeof SessionLockReasonSchema>;
export const SetSessionPermissionModeRequestSchema = z.object({
directory: z.string().min(1),
mode: SessionPermissionModeSchema,
@@ -15,7 +19,7 @@ export const SessionPermissionModeStateSchema = z.object({
sessionId: z.string(),
rootSessionId: z.string(),
mode: SessionPermissionModeSchema,
inherited: z.boolean(),
lockedReason: SessionLockReasonSchema.nullable(),
});
export type SessionPermissionModeState = z.infer<typeof SessionPermissionModeStateSchema>;
+2 -1
View File
@@ -3,6 +3,7 @@ import { NotificationPreferencesSchema, DEFAULT_NOTIFICATION_PREFERENCES } from
import { OPENCODE_CONFIG_SOURCE_NAMES } from "../config/defaults";
import { ColorThemeIdSchema, MANAGER_COLOR_THEME_ID } from "../themes";
import { SessionPermissionModeSchema } from "./session-permissions";
import { GOAL_MAX_CONTINUATIONS_MIN, GOAL_MAX_CONTINUATIONS_MAX } from "./limits";
export const CustomCommandSchema = z.object({
name: z.string(),
@@ -145,7 +146,7 @@ export const DEFAULT_SANDBOX_PREFERENCES: SandboxPreferences = {
export const SessionDefaultsSchema = z.object({
permissionMode: SessionPermissionModeSchema,
goalMaxContinuations: z.number().int().min(1).max(200).optional(),
goalMaxContinuations: z.number().int().min(GOAL_MAX_CONTINUATIONS_MIN).max(GOAL_MAX_CONTINUATIONS_MAX).optional(),
goalTokenBudget: z.number().int().positive().optional(),
goalAuditorModel: z.string().optional(),
});
+19 -2
View File
@@ -3,17 +3,34 @@ export const ASSISTANT_REPO_NAME = 'Assistant'
export const ASSISTANT_REPO_PATH = 'assistant'
export const ASSISTANT_OPENCODE_DIR_NAME = '.opencode'
export function buildSessionPath(
repoId: number | string,
sessionId: string,
options?: { repoTab?: string },
): string {
const params = new URLSearchParams()
if (String(repoId) === String(ASSISTANT_REPO_ID)) {
params.set('assistant', '1')
}
if (options?.repoTab) {
params.set('repoTab', options.repoTab)
}
const search = params.toString()
return `/repos/${repoId}/sessions/${sessionId}${search ? `?${search}` : ''}`
}
function trimTrailingChar(value: string, char: string): string {
let end = value.length
while (end > 0 && value[end - 1] === char) end--
return value.slice(0, end)
}
export function sanitizeRepoDirectoryName(input: string): string {
export function sanitizeRepoDirectoryName(input: string, fallback = 'repo'): string {
const collapsed = input.trim().replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+/, '')
const sanitized = trimTrailingChar(collapsed, '-')
return sanitized || 'repo'
return sanitized || fallback
}
export function getRepoDirectoryNameError(input: string): string | null {