Merge pull request #430 from chriswritescode-dev/feat/sandbox-sessions

feat(sandbox): per-session sandbox VMs with resource settings and provider arbitration
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-15 17:10:02 -04:00
commit bea9fb4567
63 files changed
+6874 -3412

No files matched your search

@@ -0,0 +1,14 @@
import type { Migration } from '../migration-runner'
import { ensureSessionSandboxModesTable } from '../session-sandbox-modes'
const migration: Migration = {
id: '202610141200-session-sandbox-modes',
up(db) {
ensureSessionSandboxModesTable(db)
},
down(db) {
db.run('DROP TABLE IF EXISTS session_sandbox_modes')
},
}
export default migration
+2
View File
@@ -30,6 +30,7 @@ import migration202610061345 from './202610061345-schedule-workspace-mode'
import migration202610061700 from './202610061700-multi-run-fusions'
import migration202610061701 from './202610061701-change-walkthroughs'
import migration202610081200 from './202610081200-change-walkthrough-sources'
import migration202610141200 from './202610141200-session-sandbox-modes'
export const allMigrations: Migration[] = [
migration001,
@@ -63,4 +64,5 @@ export const allMigrations: Migration[] = [
migration202610061700,
migration202610061701,
migration202610081200,
migration202610141200,
]
+107
View File
@@ -0,0 +1,107 @@
import type { Database } from 'bun:sqlite'
import type { SessionSandboxResources, SessionSandboxSource } from '@opencode-manager/shared/schemas'
export interface SessionSandboxModeRow {
sandboxed: boolean
source: SessionSandboxSource
toggledAt: number
resources: SessionSandboxResources | null
}
interface SessionSandboxModeRawRow {
sandboxed: number
source: SessionSandboxSource
toggled_at: number
cpus: number | null
memory_mib: number | null
}
export function ensureSessionSandboxModesTable(db: Database): void {
db.run(`
CREATE TABLE IF NOT EXISTS session_sandbox_modes (
session_id TEXT PRIMARY KEY,
sandboxed INTEGER NOT NULL CHECK(sandboxed IN (0,1)),
source TEXT NOT NULL CHECK(source IN ('default','user')),
toggled_at INTEGER NOT NULL,
cpus INTEGER CHECK(cpus IS NULL OR cpus > 0),
memory_mib INTEGER CHECK(memory_mib IS NULL OR memory_mib > 0),
updated_at INTEGER NOT NULL
)
`)
}
export function getSessionSandboxMode(db: Database, sessionId: string): SessionSandboxModeRow | null {
const row = db
.prepare('SELECT sandboxed, source, toggled_at, cpus, memory_mib FROM session_sandbox_modes WHERE session_id = ?')
.get(sessionId) as SessionSandboxModeRawRow | undefined
if (!row) return null
return {
sandboxed: row.sandboxed === 1,
source: row.source,
toggledAt: row.toggled_at,
resources: row.cpus !== null && row.memory_mib !== null
? { cpus: row.cpus, memoryMib: row.memory_mib }
: null,
}
}
export function insertSessionSandboxModeIfAbsent(
db: Database,
sessionId: string,
mode: { sandboxed: boolean; source: SessionSandboxSource; resources: SessionSandboxResources | null },
): void {
const now = Date.now()
db.prepare(`
INSERT OR IGNORE INTO session_sandbox_modes(session_id, sandboxed, source, toggled_at, cpus, memory_mib, updated_at)
VALUES(?,?,?,?,?,?,?)
`).run(
sessionId,
mode.sandboxed ? 1 : 0,
mode.source,
now,
mode.resources?.cpus ?? null,
mode.resources?.memoryMib ?? null,
now,
)
}
export function setSessionSandboxed(db: Database, sessionId: string, sandboxed: boolean): void {
const now = Date.now()
db.prepare(`
INSERT INTO session_sandbox_modes(session_id, sandboxed, source, toggled_at, cpus, memory_mib, updated_at)
VALUES(?,?,'user',?,NULL,NULL,?)
ON CONFLICT(session_id) DO UPDATE SET
sandboxed=excluded.sandboxed,
source='user',
toggled_at=excluded.toggled_at,
updated_at=excluded.updated_at
`).run(sessionId, sandboxed ? 1 : 0, now, now)
}
export function setSessionSandboxResources(
db: Database,
sessionId: string,
resources: SessionSandboxResources | null,
defaultSandboxed: boolean,
): void {
const now = Date.now()
db.prepare(`
INSERT INTO session_sandbox_modes(session_id, sandboxed, source, toggled_at, cpus, memory_mib, updated_at)
VALUES(?,?,'default',?,?,?,?)
ON CONFLICT(session_id) DO UPDATE SET
cpus=excluded.cpus,
memory_mib=excluded.memory_mib,
updated_at=excluded.updated_at
`).run(
sessionId,
defaultSandboxed ? 1 : 0,
now,
resources?.cpus ?? null,
resources?.memoryMib ?? null,
now,
)
}
export function deleteSessionSandboxMode(db: Database, sessionId: string): void {
db.prepare('DELETE FROM session_sandbox_modes WHERE session_id = ?').run(sessionId)
}
+19 -8
View File
@@ -39,6 +39,7 @@ import { createAuthMiddleware } from './auth/middleware'
import { createPromptTemplateRoutes } from './routes/prompt-templates'
import { createSessionPinRoutes } from './routes/session-pins'
import { createSessionPermissionModeRoutes } from './routes/session-permission-modes'
import { createSessionSandboxRoutes } from './routes/session-sandbox'
import { createSessionGoalRoutes } from './routes/session-goals'
import { createMultiRunRoutes } from './routes/multi-runs'
import { createChangeWalkthroughRoutes } from './routes/change-walkthroughs'
@@ -53,6 +54,8 @@ import { sseAggregator } from './services/sse-aggregator'
import { ensureDirectoryExists, writeFileContent, fileExists } from './services/file-operations'
import { SettingsService } from './services/settings'
import { SessionPermissionModeService } from './services/session-permission-modes'
import { SessionSandboxService } from './services/session-sandbox'
import { SessionAncestry } from './services/session-ancestry'
import { SessionGoalService } from './services/session-goals'
import { MultiRunService } from './services/multi-runs'
import { ChangeWalkthroughService } from './services/change-walkthroughs'
@@ -70,7 +73,7 @@ import { ScheduleWorktreeManager } from './services/schedule-worktree'
import { migrateGlobalSkills } from './services/skills'
import { installAssistantWorkspace } from './services/assistant-mode'
import { detectSandboxCapability } from './services/sandbox/capability'
import { SandboxRuntimeService, stopWorkspaceSandboxOnShutdown } from './services/sandbox/runtime'
import { SandboxRuntimeService, stopSandboxesOnShutdown } from './services/sandbox/runtime'
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
import { readOpenCodeConfigFile, foldLegacyConfigJsonSource, withOpenCodeConfigLock } from './services/opencode-config-file'
import { seedOpenCodeConfigFile } from './services/opencode-config-apply'
@@ -225,8 +228,8 @@ try {
opencodeServerManager.setDatabase(db)
detectSandboxCapability()
void new SandboxRuntimeService(db).prepareWorkspaceSandboxOnBoot().catch((error) => {
logger.warn('Workspace sandbox preparation failed:', error)
void new SandboxRuntimeService(db).prepareSandboxOnBoot().catch((error) => {
logger.warn('Sandbox preparation failed:', error)
})
const openCodeStatus = await openCodeSupervisor.start()
if (openCodeStatus.healthy) {
@@ -260,7 +263,11 @@ const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
const notificationService = new NotificationService(db)
const sessionSettingsService = new SettingsService(db)
const sessionPermissionModeService = new SessionPermissionModeService(db, openCodeClient, sessionSettingsService)
const sessionAncestry = new SessionAncestry(openCodeClient)
const sessionPermissionModeService = new SessionPermissionModeService(db, openCodeClient, sessionSettingsService, sessionAncestry)
const sessionSandboxService = new SessionSandboxService(db, sessionAncestry, sessionSettingsService, {
removeSessionSandbox: (rootSessionId) => new SandboxRuntimeService(db).removeSessionSandbox(rootSessionId),
})
const sessionGoalService = new SessionGoalService(db, openCodeClient, sessionSettingsService, {
onOutcome: (goal) => {
void notificationService.notifyGoalOutcome(goal).catch((error) => {
@@ -279,6 +286,9 @@ sseAggregator.onEvent((directory, event) => {
sessionPermissionModeService.handleEvent(directory, event).catch((err) => {
logger.error('Session permission mode event handling error:', err)
})
sessionSandboxService.handleEvent(directory, event).catch((err) => {
logger.error('Session sandbox event handling error:', err)
})
sessionGoalService.handleEvent(directory, event).catch((err) => {
logger.error('Session goal event handling error:', err)
})
@@ -341,7 +351,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, sessionPermissionModeService, repoWorkspaces, gitAuthService, sessionGoalService, multiRunService, changeWalkthroughService))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService, repoWorkspaces, gitAuthService, sessionGoalService, multiRunService, changeWalkthroughService, sessionSandboxService))
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService, upgradeWebSocket))
const protectedApi = new Hono()
@@ -362,6 +372,7 @@ protectedApi.route('/notifications', createNotificationRoutes(notificationServic
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
protectedApi.route('/session-pins', createSessionPinRoutes(db))
protectedApi.route('/session-permission-modes', createSessionPermissionModeRoutes(sessionPermissionModeService))
protectedApi.route('/session-sandbox', createSessionSandboxRoutes(sessionSandboxService))
protectedApi.route('/session-goals', createSessionGoalRoutes(sessionGoalService))
protectedApi.route('/multi-runs', createMultiRunRoutes(multiRunService))
protectedApi.route('/change-walkthroughs', createChangeWalkthroughRoutes(changeWalkthroughService))
@@ -468,10 +479,10 @@ const shutdown = async (signal: string) => {
logger.error('Error during shutdown:', error)
}
try {
await stopWorkspaceSandboxOnShutdown(db)
logger.info('Workspace sandbox stopped')
await stopSandboxesOnShutdown(db)
logger.info('Sandbox microVMs stopped')
} catch (error) {
logger.error('Error stopping workspace sandbox:', error)
logger.error('Error stopping sandbox microVMs:', error)
}
process.exit(0)
}
+3 -1
View File
@@ -22,6 +22,7 @@ import { createSessionGoalRoutes } from '../session-goals'
import { createMultiRunRoutes } from '../multi-runs'
import { createChangeWalkthroughRoutes } from '../change-walkthroughs'
import type { SessionPermissionModeService } from '../../services/session-permission-modes'
import type { SessionSandboxService } from '../../services/session-sandbox'
import type { RepoWorkspaceService } from '../../services/repo-workspace'
import type { GitAuthService } from '../../services/git-auth'
import type { SessionGoalService } from '../../services/session-goals'
@@ -40,6 +41,7 @@ export function createInternalRoutes(
sessionGoals: SessionGoalService,
multiRuns: MultiRunService,
changeWalkthroughService: ChangeWalkthroughService,
sessionSandbox: SessionSandboxService,
) {
const app = new Hono()
app.use('/*', createInternalTokenMiddleware(db))
@@ -61,6 +63,6 @@ export function createInternalRoutes(
app.route('/change-walkthroughs', createChangeWalkthroughRoutes(changeWalkthroughService))
app.route('/session-artifacts', createInternalSessionArtifactRoutes(openCodeClient))
app.route('/git-credentials', createInternalGitCredentialsRoutes(db))
app.route('/sandbox', createInternalSandboxRoutes(db))
app.route('/sandbox', createInternalSandboxRoutes(db, sessionSandbox))
return app
}
+19 -2
View File
@@ -2,16 +2,28 @@ import { Hono } from 'hono'
import { z } from 'zod'
import type { Database } from 'bun:sqlite'
import { SandboxRuntimeService } from '../../services/sandbox/runtime'
import type { SessionSandboxService } from '../../services/session-sandbox'
import { logger } from '../../utils/logger'
const SandboxShellRequestSchema = z.object({
directory: z.string().min(1),
sessionId: z.string().min(1),
locationDirectory: z.string().min(1),
enforced: z.boolean().optional(),
})
export function createInternalSandboxRoutes(db: Database) {
export function createInternalSandboxRoutes(db: Database, sessionSandbox: SessionSandboxService) {
const app = new Hono()
app.get('/sessions/:sessionId', async (c) => {
try {
return c.json(await sessionSandbox.getClaim(c.req.param('sessionId')))
} catch (error) {
logger.error('Failed to read session sandbox state', error)
return c.json({ error: error instanceof Error ? error.message : String(error) }, 500)
}
})
app.post('/shell', async (c) => {
let body: unknown
try {
@@ -26,8 +38,13 @@ export function createInternalSandboxRoutes(db: Database) {
}
try {
const target = await sessionSandbox.resolveShellTarget(parsed.data.sessionId)
return c.json(
await new SandboxRuntimeService(db).planShell(parsed.data.directory, parsed.data.enforced === true),
await new SandboxRuntimeService(db).planShell(
parsed.data.directory,
{ ...target, locationDirectory: parsed.data.locationDirectory },
parsed.data.enforced === true,
),
)
} catch (error) {
logger.error('Failed to plan the sandbox shell', error)
+33
View File
@@ -0,0 +1,33 @@
import { Hono } from 'hono'
import { SetSessionSandboxRequestSchema } from '@opencode-manager/shared/schemas'
import { SessionSandboxError, type SessionSandboxService } from '../services/session-sandbox'
import { handleServiceError, parseJsonBody } from '../utils/route-helpers'
export function createSessionSandboxRoutes(service: SessionSandboxService) {
const app = new Hono()
app.get('/:sessionId', async (c) => {
try {
const state = await service.getState(c.req.param('sessionId'))
return c.json(state)
} catch (error) {
return handleServiceError(c, error, 'Failed to read session sandbox state', SessionSandboxError)
}
})
app.put('/:sessionId', async (c) => {
const parsed = await parseJsonBody(c, SetSessionSandboxRequestSchema)
if (!parsed.ok) {
return parsed.response
}
try {
const state = await service.update(c.req.param('sessionId'), parsed.data)
return c.json(state)
} catch (error) {
return handleServiceError(c, error, 'Failed to set session sandbox state', SessionSandboxError)
}
})
return app
}
+12
View File
@@ -33,6 +33,7 @@ import { getOrCreateInternalToken, rotateInternalToken } from '../services/inter
import { sseAggregator } from '../services/sse-aggregator'
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
import { detectSandboxCapability } from '../services/sandbox/capability'
import { sandboxResourceLimitError } from '../services/sandbox/resources'
import { getProcessIdentityAttestationError } from '../services/opencode/process-identity'
import { restartOpenCode, assertValidOpenCodeConfig, listActiveUserSessions } from '../services/opencode-restart'
import type { GitAuthService } from '../services/git-auth'
@@ -377,6 +378,17 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
const currentSettings = settingsService.getSettings(userId)
const requestedSandboxResources = validated.preferences.sandbox
if (
requestedSandboxResources !== undefined
&& (requestedSandboxResources.cpus !== undefined || requestedSandboxResources.memoryMib !== undefined)
) {
const limitError = sandboxResourceLimitError(requestedSandboxResources)
if (limitError !== null) {
return c.json({ error: limitError }, 400)
}
}
if (currentSettings.preferences.sandbox?.enabled !== true && validated.preferences.sandbox?.enabled === true) {
const capability = detectSandboxCapability()
if (capability.available === false) {
+2 -2
View File
@@ -334,7 +334,7 @@ export class NotificationService {
}
async handleSSEEvent(
directory: string,
directory: string | null,
event: SSEEvent
): Promise<void> {
const config = EVENT_CONFIG[event.type];
@@ -358,7 +358,7 @@ export class NotificationService {
repoName,
repoId,
sessionId,
directory,
directory: directory ?? undefined,
url,
});
if (!payload) return;
+251 -9
View File
@@ -1,23 +1,66 @@
import { sandboxPlanTimeoutMs, SANDBOX_UNAVAILABLE_PREFIX } from './sandbox/command'
import {
SANDBOX_FORWARDED_ENV_NAMES,
SANDBOX_SHELL_ENV_NAME,
SANDBOX_SHELL_ENV_WORKDIR,
} from './sandbox/shell-shim'
export const SANDBOX_PLAN_TIMEOUT_MS = sandboxPlanTimeoutMs()
export const SANDBOX_CLAIM_TIMEOUT_MS = 15000
export const SANDBOX_SHELL_STATE_KEY = 'ocm-sandbox.shell-state.v2'
const SANDBOX_DOCKER_HINT = '\n\nCommands run inside an isolated sandbox microVM that includes Docker (docker, docker compose, docker buildx). The Docker daemon is not started automatically: run `ocm-dockerd-start` once before your first docker command; it is safe to run again and exits immediately if the daemon is already running.'
export function buildSandboxPluginSource(id: string, shellShimPath: string, serviceSettingsPath: string): string {
return `import { existsSync } from 'fs'
import { randomUUID } from 'crypto'
import path from 'path'
var SANDBOX_UNAVAILABLE_PREFIX = ${JSON.stringify(SANDBOX_UNAVAILABLE_PREFIX)}
var PLAN_TIMEOUT_MS = ${SANDBOX_PLAN_TIMEOUT_MS}
var CLAIM_TIMEOUT_MS = ${SANDBOX_CLAIM_TIMEOUT_MS}
var SHELL_SHIM_PATH = ${JSON.stringify(shellShimPath)}
var ENV_WORKDIR = ${JSON.stringify(SANDBOX_SHELL_ENV_WORKDIR)}
var ENV_SANDBOX_NAME = ${JSON.stringify(SANDBOX_SHELL_ENV_NAME)}
var FORWARDED_ENV_NAMES = ${JSON.stringify(SANDBOX_FORWARDED_ENV_NAMES)}
var SERVICE_SETTINGS_PATH = path.resolve(${JSON.stringify(serviceSettingsPath)})
var SERVICE_SETTINGS_DIRECTORY = path.dirname(SERVICE_SETTINGS_PATH)
var SERVICE_SETTINGS_DENIED = 'OpenCode Manager denies access to its service settings file (service.json), which holds the OpenCode server password.'
var DOCKER_HINT = ${JSON.stringify(SANDBOX_DOCKER_HINT)}
var SHELL_TOOL_NAME = 'shell'
var SHELL_MARKER_PREFIX = 'ocm-sandbox-required-'
var SHELL_MARKER_PATTERN = /^(ocm-sandbox-required-[0-9a-f-]{36}) && /
var PLAN_NAME_PATTERN = /^ocm-session-[0-9a-f]{12}$/
var ARBITER_KEY = Symbol.for('opencode.sandbox-arbiter.v1')
var SHELL_STATE_KEY = Symbol.for(${JSON.stringify(SANDBOX_SHELL_STATE_KEY)})
var OCM_PROVIDER_ID = 'ocm'
var TIER_RANK = { workload: 3, explicit: 2, default: 1 }
function shellSandboxState() {
var state = globalThis[SHELL_STATE_KEY]
if (state === undefined) {
state = { pendingMarkers: new Map(), sandboxedCallIDs: new Set(), foreignOwners: new Map() }
globalThis[SHELL_STATE_KEY] = state
}
return state
}
var shellState = shellSandboxState()
function sandboxArbiter() {
var registry = globalThis[ARBITER_KEY]
if (registry === undefined) {
registry = { version: 1, providers: new Map(), decisions: new Map() }
globalThis[ARBITER_KEY] = registry
return registry
}
if (registry === null || typeof registry !== 'object' || registry.version !== 1 || !(registry.providers instanceof Map) || !(registry.decisions instanceof Map)) {
throw unavailable('the sandbox arbiter registry at ' + String(ARBITER_KEY) + ' is invalid; refusing to run the command outside its sandbox')
}
return registry
}
function isEnforced() {
return process.env.OCM_SANDBOX_ENFORCED === 'true'
@@ -84,7 +127,9 @@ function lockAccessor(target, key, value) {
try {
Object.defineProperty(target, key, {
get: function () { return value },
set: function () {},
set: function () {
throw unavailable('another plugin tried to replace a shell setting pinned by OpenCode Manager; aborting before the command runs outside its sandbox')
},
configurable: false,
enumerable: true,
})
@@ -98,7 +143,125 @@ function lockAccessor(target, key, value) {
&& target[key] === value
}
async function planSandboxShell(cwd) {
async function resolveSessionClaim(sessionID) {
var baseUrl = process.env.OCM_INTERNAL_API_URL
var token = process.env.OCM_INTERNAL_TOKEN
if (!baseUrl || !token) {
throw unavailable('sandbox session lookup unavailable: internal API is not configured')
}
var controller = new AbortController()
var lookupTimedOut = false
var lookupTimer = setTimeout(function () {
lookupTimedOut = true
controller.abort()
}, PLAN_TIMEOUT_MS)
var body = null
var failure = null
try {
var res = await fetch(baseUrl + '/sandbox/sessions/' + encodeURIComponent(sessionID), {
method: 'GET',
headers: { Authorization: 'Bearer ' + token },
signal: controller.signal,
})
if (!res.ok) {
failure = 'sandbox session lookup failed with status ' + res.status
} else {
body = await res.json()
}
} catch (error) {
failure = lookupTimedOut ? 'sandbox session lookup timed out' : (error instanceof Error ? error.message : String(error))
} finally {
clearTimeout(lookupTimer)
}
if (failure !== null) {
throw unavailable(failure)
}
if (body === null || typeof body !== 'object'
|| typeof body.sandboxed !== 'boolean'
|| (body.source !== 'default' && body.source !== 'user')
|| typeof body.since !== 'number'
|| !isFinite(body.since)) {
throw unavailable('sandbox session lookup returned an invalid response')
}
if (!body.sandboxed) return null
return { tier: body.source === 'user' ? 'explicit' : 'default', since: body.since }
}
function validClaim(claim) {
return claim !== null && typeof claim === 'object'
&& (claim.tier === 'workload' || claim.tier === 'explicit' || claim.tier === 'default')
&& typeof claim.since === 'number'
&& isFinite(claim.since)
}
function raceClaim(provider, request) {
return new Promise(function (resolve, reject) {
var settled = false
var timer = setTimeout(function () {
settled = true
reject(new Error('timed out after ' + CLAIM_TIMEOUT_MS + 'ms'))
}, CLAIM_TIMEOUT_MS)
function settle(fn) {
return function (value) {
if (settled) return
settled = true
clearTimeout(timer)
fn(value)
}
}
Promise.resolve()
.then(function () { return provider.claim(request) })
.then(settle(resolve), settle(reject))
})
}
async function resolveSandboxOwner(request) {
var arbiter = sandboxArbiter()
var providers = Array.from(arbiter.providers.values())
var claims = await Promise.all(providers.map(function (provider) {
return raceClaim(provider, request).then(function (claim) {
if (claim === null) return null
if (!validClaim(claim)) {
throw new Error('returned an invalid claim')
}
return { id: provider.id, tier: claim.tier, since: claim.since }
}).catch(function (error) {
var reason = error instanceof Error ? error.message : String(error)
if (reason.indexOf(SANDBOX_UNAVAILABLE_PREFIX) === 0) reason = reason.slice(SANDBOX_UNAVAILABLE_PREFIX.length)
throw unavailable('sandbox provider ' + provider.id + ' could not decide: ' + reason)
})
}))
var ranked = claims.filter(function (claim) { return claim !== null })
ranked.sort(function (a, b) {
var byTier = TIER_RANK[b.tier] - TIER_RANK[a.tier]
if (byTier !== 0) return byTier
if (a.since !== b.since) return b.since - a.since
if (a.id < b.id) return -1
if (a.id > b.id) return 1
return 0
})
return { owner: ranked.length > 0 ? ranked[0].id : null }
}
function noop() {}
function claimCallDecision(callID, request) {
var arbiter = sandboxArbiter()
if (arbiter.decisions.has(callID)) {
return { decision: arbiter.decisions.get(callID), release: noop }
}
var decision = resolveSandboxOwner(request)
decision.catch(function () {})
arbiter.decisions.set(callID, decision)
return {
decision: decision,
release: function () {
if (arbiter.decisions.get(callID) === decision) arbiter.decisions.delete(callID)
},
}
}
async function planSandboxShell(cwd, sessionID, locationDirectory) {
var baseUrl = process.env.OCM_INTERNAL_API_URL
var token = process.env.OCM_INTERNAL_TOKEN
if (!baseUrl || !token) {
@@ -119,7 +282,7 @@ async function planSandboxShell(cwd) {
'content-type': 'application/json',
Authorization: 'Bearer ' + token,
},
body: JSON.stringify({ directory: cwd, enforced: true }),
body: JSON.stringify({ directory: cwd, sessionId: sessionID, locationDirectory: locationDirectory, enforced: true }),
signal: controller.signal,
})
if (!res.ok) {
@@ -135,17 +298,20 @@ async function planSandboxShell(cwd) {
if (failure !== null) {
throw unavailable(failure)
}
if (plan === null || typeof plan !== 'object' || plan.mode !== 'sandbox' || typeof plan.workdir !== 'string' || plan.workdir.length === 0) {
if (plan === null || typeof plan !== 'object'
|| plan.mode !== 'sandbox'
|| typeof plan.workdir !== 'string' || plan.workdir.length === 0
|| typeof plan.name !== 'string' || !PLAN_NAME_PATTERN.test(plan.name)) {
throw unavailable(plan !== null && typeof plan === 'object' && typeof plan.reason === 'string' ? plan.reason : 'sandbox plan request returned an invalid response')
}
return plan
}
async function pinSandboxShell(event) {
async function pinSandboxShell(event, sessionID, locationDirectory) {
if (!existsSync(SHELL_SHIM_PATH)) {
throw unavailable('the sandbox shell shim is missing at ' + SHELL_SHIM_PATH)
}
var plan = await planSandboxShell(event.cwd)
var plan = await planSandboxShell(event.cwd, sessionID, locationDirectory)
if (plan.env !== null && typeof plan.env === 'object') {
for (var name of FORWARDED_ENV_NAMES) {
if (typeof plan.env[name] === 'string') {
@@ -159,6 +325,42 @@ async function pinSandboxShell(event) {
if (!lockAccessor(event.env, ENV_WORKDIR, plan.workdir)) {
throw unavailable('sandbox enforcement could not pin the sandbox working directory; aborting before the command runs on the host')
}
if (!lockAccessor(event.env, ENV_SANDBOX_NAME, plan.name)) {
throw unavailable('sandbox enforcement could not pin the sandbox session name; aborting before the command runs on the host')
}
}
async function wrapSandboxedShellTool(ctx) {
await ctx.tool.transform(function (editor) {
editor.update(SHELL_TOOL_NAME, function (tool) {
var execute = tool.execute
tool.execute = async function (input, context) {
var claimed = claimCallDecision(context.id, { sessionID: context.sessionID, directory: ctx.location.directory })
try {
var owner = (await claimed.decision).owner
if (owner !== OCM_PROVIDER_ID) {
if (owner !== null) {
shellState.foreignOwners.set(context.id, owner)
}
return await execute(input, context)
}
if (input === null || typeof input !== 'object' || typeof input.command !== 'string') {
throw unavailable('refusing to run a sandboxed shell call without a command')
}
var marker = SHELL_MARKER_PREFIX + randomUUID()
shellState.pendingMarkers.set(marker, { callID: context.id, sessionID: context.sessionID })
shellState.sandboxedCallIDs.add(context.id)
try {
return await execute({ ...input, command: marker + ' && ' + input.command }, context)
} finally {
shellState.pendingMarkers.delete(marker)
}
} finally {
claimed.release()
}
}
})
})
}
export default {
@@ -171,13 +373,53 @@ export default {
})
await ctx.shell.hook('create.before', async (event) => {
if (!isEnforced()) return
await pinSandboxShell(event)
var marked = SHELL_MARKER_PATTERN.exec(event.command)
if (marked === null) return
var pending = shellState.pendingMarkers.get(marked[1])
if (pending === undefined) {
throw unavailable('sandbox marker ' + marked[1] + ' is not pending; refusing to run the command on the host')
}
shellState.pendingMarkers.delete(marked[1])
event.command = event.command.slice(marked[0].length)
await pinSandboxShell(event, pending.sessionID, ctx.location.directory)
})
await ctx.session.hook('context', async (event) => {
if (!isEnforced()) return
var shell = event.tools && event.tools.shell
if (!shell) return
if (typeof shell.description !== 'string' || shell.description.indexOf(DOCKER_HINT) !== -1) return
var owner = null
try {
owner = (await resolveSandboxOwner({ sessionID: event.sessionID, directory: ctx.location.directory })).owner
} catch (error) {
return
}
if (owner !== OCM_PROVIDER_ID) return
shell.description = shell.description + DOCKER_HINT
})
await ctx.tool.hook('execute.after', (event) => {
if (!isEnforced() || event.tool !== 'shell' || event.status !== 'completed') return
if (!isEnforced() || event.tool !== SHELL_TOOL_NAME) return
var owner = shellState.sandboxedCallIDs.has(event.id) ? OCM_PROVIDER_ID : shellState.foreignOwners.get(event.id)
if (owner === undefined) return
shellState.sandboxedCallIDs.delete(event.id)
shellState.foreignOwners.delete(event.id)
if (event.status !== 'completed') return
if (event.result === null || typeof event.result !== 'object') return
event.result = { ...event.result, metadata: { ...(event.result.metadata ?? {}), sandbox: true } }
event.result = { ...event.result, metadata: { ...(event.result.metadata ?? {}), sandbox: true, sandboxProvider: owner } }
})
if (!isEnforced()) return
var arbiter = sandboxArbiter()
var provider = {
id: OCM_PROVIDER_ID,
claim: function (request) { return resolveSessionClaim(request.sessionID) },
}
arbiter.providers.set(OCM_PROVIDER_ID, provider)
await wrapSandboxedShellTool(ctx)
return function () {
if (arbiter.providers.get(OCM_PROVIDER_ID) === provider) {
arbiter.providers.delete(OCM_PROVIDER_ID)
}
}
},
}
`
@@ -417,14 +417,14 @@ class OpenCodeServerManager {
}
if (!sandboxEnforced && this.sandboxEnforced) {
try {
await new SandboxRuntimeService(this.db).stopWorkspaceSandboxForToggle()
logger.info('Sandbox enforcement disabled: stopped the shared workspace microVM')
await new SandboxRuntimeService(this.db).stopAllSandboxesForToggle()
logger.info('Sandbox enforcement disabled: stopped all sandbox microVMs')
} catch (error) {
this.failNonRecoverable(`Failed to stop the workspace sandbox while disabling enforcement: ${error instanceof Error ? error.message : String(error)}`)
}
}
if (sandboxEnforced && !this.sandboxEnforced) {
void new SandboxRuntimeService(this.db).prepareWorkspaceSandboxOnBoot().catch((error) => {
void new SandboxRuntimeService(this.db).prepareSandboxOnBoot().catch((error) => {
logger.warn('Sandbox enforcement enabled but preparing the guest image failed:', error)
})
}
+135 -28
View File
@@ -1,6 +1,7 @@
import path from 'path'
import { createHash } from 'crypto'
import { accessSync, constants, realpathSync, statSync } from 'fs'
import { realpath } from 'fs/promises'
import { lstat, readFile, realpath } from 'fs/promises'
import {
ENV,
getForgeWorktreesPath,
@@ -12,13 +13,31 @@ import {
getScheduleWorktreesPath,
} from '@opencode-manager/shared/config/env'
import { isPathWithinRoot } from '../../utils/fs-safe'
import { executeCommand } from '../../utils/process'
export const WORKSPACE_SANDBOX_NAME = 'ocm-workspace'
export const SESSION_SANDBOX_NAME_PATTERN = /^ocm-session-[0-9a-f]{12}$/
export const SANDBOX_DOCKER_DATA_VOLUME_NAME = 'ocm-workspace-docker-data'
export const SANDBOX_DOCKER_DATA_GUEST_PATH = '/var/lib/docker'
export const SANDBOX_DOCKER_DATA_SIZE = '20G'
const SANDBOX_GIT_RESOLVE_TIMEOUT_MS = 10000
export function sessionSandboxName(rootSessionId: string): string {
return `ocm-session-${createHash('sha256').update(rootSessionId).digest('hex').slice(0, 12)}`
}
export function sandboxDockerDataVolumeName(name: string): string {
return `${name}-docker-data`
}
export type SandboxVmSpec = {
name: string
rootSessionId: string
projectMounts: string[]
cpus: number
memoryMib: number
}
export const SANDBOX_UNAVAILABLE_PREFIX = 'Sandbox enforcement is on but the sandbox is unavailable: '
const SANDBOX_PLAN_REQUEST_MARGIN_MS = 30000
@@ -133,16 +152,16 @@ export function buildSandboxPullArgs(): string[] {
return ['pull', ENV.SANDBOX.IMAGE]
}
export function buildSandboxPingArgs(): string[] {
return ['ping', WORKSPACE_SANDBOX_NAME, '-q']
export function buildSandboxPingArgs(name: string): string[] {
return ['ping', name, '-q']
}
export function buildSandboxVerifyProvisionArgs(): string[] {
export function buildSandboxVerifyProvisionArgs(name: string): string[] {
const uid = resolveSandboxExecUserUid()
if (uid === null) return []
return [
'exec',
WORKSPACE_SANDBOX_NAME,
name,
'--no-tty',
'-q',
'-u',
@@ -167,12 +186,27 @@ export function sandboxMountRoots(): string[] {
]
}
export function sandboxVmMountRoots(spec: SandboxVmSpec): string[] {
const roots: string[] = []
for (const root of [
...spec.projectMounts,
getOpenCodeToolOutputPath(),
getOpenCodeGlobalSkillsPath(),
getOpenCodeAgentTmpPath(),
]) {
if (!roots.includes(root)) {
roots.push(root)
}
}
return roots
}
export function quoteForShell(value: string): string {
return `'${value.replace(/'/g, `'\\''`)}'`
}
function buildSandboxDockerDataMountArg(): string {
return `${SANDBOX_DOCKER_DATA_VOLUME_NAME}:${SANDBOX_DOCKER_DATA_GUEST_PATH}:kind=disk,size=${SANDBOX_DOCKER_DATA_SIZE}`
function buildSandboxDockerDataMountArg(name: string): string {
return `${sandboxDockerDataVolumeName(name)}:${SANDBOX_DOCKER_DATA_GUEST_PATH}:kind=disk,size=${SANDBOX_DOCKER_DATA_SIZE}`
}
function parseSandboxNamedMountSpec(spec: string): { name: string; guest: string } {
@@ -180,33 +214,38 @@ function parseSandboxNamedMountSpec(spec: string): { name: string; guest: string
return { name, guest }
}
export function buildSandboxCreateArgs(): string[] {
const tmpfsSizeMib = resolveSandboxRuntimeTmpfsSizeMib(parseMemoryMib(ENV.SANDBOX.MEMORY))
export function buildSandboxCreateArgs(spec: SandboxVmSpec, options: { replace?: boolean } = {}): string[] {
const tmpfsSizeMib = resolveSandboxRuntimeTmpfsSizeMib(spec.memoryMib)
if (tmpfsSizeMib === null) throw new Error('sandbox memory must be positive to size the runtime tmpfs')
const workdir = spec.projectMounts[0]
if (workdir === undefined) throw new Error('sandbox VM spec must include at least one project mount')
return [
'run',
'-d',
...(options.replace === true ? ['--replace'] : []),
'--name',
WORKSPACE_SANDBOX_NAME,
spec.name,
'--label',
'ocm.managed=true',
'--label',
`ocm.net=${ENV.SANDBOX.NET}`,
'--label',
`ocm.session=${spec.rootSessionId}`,
'-m',
ENV.SANDBOX.MEMORY,
`${spec.memoryMib}M`,
'-c',
String(ENV.SANDBOX.CPUS),
String(spec.cpus),
'--net',
ENV.SANDBOX.NET,
'-u',
resolveSandboxExecUser(),
...sandboxMountRoots().flatMap((root) => ['--mount-dir', `${root}:${root}`]),
...sandboxVmMountRoots(spec).flatMap((root) => ['--mount-dir', `${root}:${root}`]),
'--mount-named',
buildSandboxDockerDataMountArg(),
buildSandboxDockerDataMountArg(spec.name),
'--tmpfs',
`/tmp:${tmpfsSizeMib}M`,
'-w',
getReposPath(),
workdir,
'--entrypoint',
'/usr/bin/env',
'--shell',
@@ -218,20 +257,28 @@ export function buildSandboxCreateArgs(): string[] {
]
}
export function buildSandboxInspectArgs(): string[] {
return ['inspect', WORKSPACE_SANDBOX_NAME, '--format', 'json']
export function buildSandboxInspectArgs(name: string): string[] {
return ['inspect', name, '--format', 'json']
}
export function buildSandboxRemoveArgs(): string[] {
return ['rm', '--force', WORKSPACE_SANDBOX_NAME]
export function buildSandboxRemoveArgs(name: string): string[] {
return ['rm', '--force', name]
}
export function buildSandboxListArgs(): string[] {
return ['ls', '--format', 'json']
}
export function buildSandboxStartArgs(): string[] {
return ['start', WORKSPACE_SANDBOX_NAME]
export function buildSandboxStartArgs(name: string): string[] {
return ['start', name]
}
export function buildSandboxStopArgs(name: string): string[] {
return ['stop', name]
}
export function buildSandboxVolumeRemoveArgs(volume: string): string[] {
return ['volume', 'rm', volume]
}
export function buildSandboxStopManagedArgs(): string[] {
@@ -346,7 +393,7 @@ export function sandboxNetworkPolicyMismatch(inspected: unknown, expected: Sandb
return null
}
function parseMemoryMib(value: string): number | null {
export function parseMemoryMib(value: string): number | null {
const match = /^(\d+(?:\.\d+)?)([gGmM])?$/.exec(value.trim())
if (match === null) return null
const number = Number(match[1])
@@ -422,8 +469,8 @@ function parseSandboxCreateArgs(args: string[]): {
return { name, labels, memory, cpus, user, mountDirs, namedMounts, workdir, entrypoint, shell, image, cmd }
}
export function buildCanonicalSandboxSpec(): Record<string, unknown> {
const args = parseSandboxCreateArgs(buildSandboxCreateArgs())
export function buildCanonicalSandboxSpec(spec: SandboxVmSpec): Record<string, unknown> {
const args = parseSandboxCreateArgs(buildSandboxCreateArgs(spec))
const memoryMib = parseMemoryMib(args.memory)
const bindMounts = args.mountDirs.map((spec) => {
const separator = spec.indexOf(':')
@@ -511,6 +558,66 @@ export async function resolveSandboxWorkDirectory(directory: string): Promise<st
return null
}
async function safeRealpath(target: string): Promise<string | null> {
try {
return await realpath(target)
} catch {
return null
}
}
export async function resolveSessionSandboxMounts(locationDirectory: string): Promise<string[] | null> {
const work = await resolveSandboxWorkDirectory(locationDirectory)
if (work === null) return null
let result: string | { exitCode: number; stdout: string; stderr: string }
try {
result = (await executeCommand(
['git', '-C', work, 'rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir'],
{ ignoreExitCode: true, silent: true, timeout: SANDBOX_GIT_RESOLVE_TIMEOUT_MS },
)) as string | { exitCode: number; stdout: string; stderr: string }
} catch {
return [work]
}
const listing = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
if (listing.exitCode !== 0) return [work]
const lines = listing.stdout.split('\n').map((line) => line.trim()).filter((line) => line !== '')
if (lines.length < 3) return [work]
const top = await resolveSandboxWorkDirectory(lines[0]!)
const gitDir = lines[1]!
const common = await resolveSandboxWorkDirectory(lines[2]!)
if (top === null || common === null) return null
const resolvedTop = await safeRealpath(top)
const resolvedWork = await safeRealpath(work)
const resolvedGitDir = await safeRealpath(gitDir)
const resolvedCommon = await safeRealpath(common)
if (resolvedTop === null || resolvedWork === null || resolvedGitDir === null || resolvedCommon === null) return null
if (!isPathWithinRoot(resolvedTop, resolvedWork)) return null
const topGitPath = path.join(resolvedTop, '.git')
const topGitStat = await lstat(topGitPath).catch(() => null)
if (topGitStat === null || topGitStat.isSymbolicLink()) return null
if (resolvedGitDir === resolvedCommon) {
if (!topGitStat.isDirectory() || resolvedCommon !== topGitPath) return null
} else {
if (!topGitStat.isFile()) return null
if (path.dirname(resolvedGitDir) !== path.join(resolvedCommon, 'worktrees')) return null
let pointer: string
try {
pointer = (await readFile(path.join(resolvedGitDir, 'gitdir'), 'utf8')).trim()
} catch {
return null
}
const resolvedPointer = await safeRealpath(path.isAbsolute(pointer) ? pointer : path.join(resolvedGitDir, pointer))
if (resolvedPointer === null || resolvedPointer !== topGitPath) return null
}
return isPathWithinRoot(top, common) ? [top] : [top, common]
}
export function resolveSandboxExecUser(): string {
const configured = ENV.SANDBOX.EXEC_USER.trim()
if (/^\d+$/.test(configured)) {
@@ -537,13 +644,13 @@ export function resolveSandboxExecUserGid(): number | null {
return Number(gid)
}
export function buildSandboxProvisionArgs(): string[] {
export function buildSandboxProvisionArgs(name: string): string[] {
const uid = resolveSandboxExecUserUid()
const gid = resolveSandboxExecUserGid()
if (uid === null || gid === null) return []
return [
'exec',
WORKSPACE_SANDBOX_NAME,
name,
'--no-tty',
'-q',
'-u',
+43
View File
@@ -0,0 +1,43 @@
import os from 'os'
import { ENV } from '@opencode-manager/shared/config/env'
import type { SandboxPreferences, SessionSandboxResources } from '@opencode-manager/shared/schemas'
import { parseMemoryMib } from './command'
export function envSandboxResources(): SessionSandboxResources {
const cpus = ENV.SANDBOX.CPUS
if (!Number.isInteger(cpus) || cpus <= 0) {
throw new Error(`sandbox cpus must be a positive integer, received ${String(cpus)}`)
}
const memoryMib = parseMemoryMib(ENV.SANDBOX.MEMORY)
if (memoryMib === null || memoryMib <= 0) {
throw new Error(`sandbox memory must be a positive size, received ${JSON.stringify(ENV.SANDBOX.MEMORY)}`)
}
return { cpus, memoryMib }
}
export function resolveSandboxResources(
preferences: SandboxPreferences | undefined,
override: SessionSandboxResources | null,
): SessionSandboxResources {
const env = envSandboxResources()
return {
cpus: override?.cpus ?? preferences?.cpus ?? env.cpus,
memoryMib: override?.memoryMib ?? preferences?.memoryMib ?? env.memoryMib,
}
}
export function sandboxResourceLimitError(resources: Partial<SessionSandboxResources>): string | null {
const maxCpus = os.availableParallelism()
if (resources.cpus !== undefined && resources.cpus > maxCpus) {
return `Requested ${resources.cpus} CPUs exceeds the host limit of ${maxCpus}`
}
const maxMemoryMib = Math.floor(os.totalmem() / 1048576)
if (resources.memoryMib !== undefined && resources.memoryMib > maxMemoryMib) {
return `Requested ${resources.memoryMib} MiB of memory exceeds the host limit of ${maxMemoryMib} MiB`
}
return null
}
+435 -187
View File
@@ -1,9 +1,15 @@
import type { Database } from 'bun:sqlite'
import path from 'path'
import { lstat, realpath } from 'fs/promises'
import { ENV } from '@opencode-manager/shared/config/env'
import {
ENV,
getOpenCodeAgentTmpPath,
getOpenCodeGlobalSkillsPath,
getOpenCodeToolOutputPath,
} from '@opencode-manager/shared/config/env'
import { DEFAULT_SANDBOX_IDLE_STOP_MINUTES, DEFAULT_SANDBOX_MAX_RUNNING_VMS } from '@opencode-manager/shared/schemas'
import { executeCommand } from '../../utils/process'
import { mkdirSafe } from '../../utils/fs-safe'
import { isPathWithinRoot, mkdirSafe } from '../../utils/fs-safe'
import { logger } from '../../utils/logger'
import { SettingsService } from '../settings'
import { CredentialProvider } from '../credential-provider'
@@ -11,7 +17,7 @@ import { getGitIdentityEnvForDirectory } from '../git-identity'
import { getProcessIdentityAttestationError } from '../opencode/process-identity'
import { detectSandboxCapability } from './capability'
import {
WORKSPACE_SANDBOX_NAME,
SESSION_SANDBOX_NAME_PATTERN,
buildCanonicalSandboxSpec,
buildSandboxCreateArgs,
buildSandboxInspectArgs,
@@ -21,15 +27,21 @@ import {
buildSandboxPullArgs,
buildSandboxRemoveArgs,
buildSandboxStartArgs,
buildSandboxStopArgs,
buildSandboxStopManagedArgs,
buildSandboxVerifyProvisionArgs,
buildSandboxVolumeRemoveArgs,
resolveExpectedSandboxNetworkPolicy,
resolveSandboxRuntimeTmpfsSizeMib,
resolveSandboxWorkDirectory,
resolveSessionSandboxMounts,
sandboxDockerDataVolumeName,
sandboxExecutablePath,
sandboxMountRoots,
sandboxNetworkPolicyMismatch,
sandboxProjectRoots,
sandboxVmMountRoots,
sessionSandboxName,
type SandboxVmSpec,
} from './command'
const SANDBOX_LS_CACHE_MS = 5000
@@ -40,11 +52,21 @@ const SANDBOX_PROVISION_RETRY_DELAY_MS = 2000
const SANDBOX_PROVISION_RETRY_ATTEMPTS = 5
const SANDBOX_AGENT_PING_TIMEOUT_MS = 10000
const SANDBOX_AGENT_POLL_DELAY_MS = 1000
const SANDBOX_IDLE_SWEEP_INTERVAL_MS = 60000
const SANDBOX_RUNTIME_TMPFS_GUEST = path.resolve('/tmp')
const SANDBOX_REMOVAL_MISSING_PATTERN = /not found|no such sandbox|unknown sandbox|does not exist/i
const SANDBOX_VOLUME_REMOVAL_MISSING_PATTERN = /not found|no such volume|unknown volume|does not exist/i
const SANDBOX_CREATE_EXISTS_PATTERN = /already exists/i
export type SandboxShellTarget = {
rootSessionId: string
locationDirectory: string
resources: { cpus: number; memoryMib: number }
}
export type SandboxShellPlan =
| { mode: 'host' }
| { mode: 'sandbox'; workdir: string; env?: Record<string, string> }
| { mode: 'sandbox'; name: string; workdir: string; env?: Record<string, string> }
| { mode: 'blocked'; reason: string }
export type SandboxStatus = {
@@ -54,32 +76,62 @@ export type SandboxStatus = {
msbVersion?: string
}
let inFlightBoot: Promise<void> | null = null
let lastKnownRunningAt: number | null = null
type VmState = {
inFlightBoot: Promise<void> | null
inFlightRemoval: Promise<void> | null
lastKnownRunningAt: number | null
lastUsedAt: number
inFlightProvision: Promise<void> | null
backgroundProvisionRetry: Promise<void> | null
provisionRetryGeneration: number
}
const vmStates = new Map<string, VmState>()
let shutdownRequested = false
let stopInProgress = false
let canonicalSandboxSpecMemo: Record<string, unknown> | null = null
let idleSweepTimer: ReturnType<typeof setInterval> | null = null
let idleSweepStartedAt = 0
let startAdmission: Promise<void> = Promise.resolve()
function vmState(name: string): VmState {
const existing = vmStates.get(name)
if (existing !== undefined) return existing
const created: VmState = {
inFlightBoot: null,
inFlightRemoval: null,
lastKnownRunningAt: null,
lastUsedAt: 0,
inFlightProvision: null,
backgroundProvisionRetry: null,
provisionRetryGeneration: 0,
}
vmStates.set(name, created)
return created
}
export function resetSandboxRuntimeState(): void {
inFlightBoot = null
lastKnownRunningAt = null
for (const state of vmStates.values()) {
state.provisionRetryGeneration += 1
state.backgroundProvisionRetry = null
state.inFlightProvision = null
state.inFlightBoot = null
state.inFlightRemoval = null
}
vmStates.clear()
shutdownRequested = false
stopInProgress = false
canonicalSandboxSpecMemo = null
provisionRetryGeneration += 1
backgroundProvisionRetry = null
inFlightProvision = null
}
function memoizedCanonicalSandboxSpec(): Record<string, unknown> {
if (canonicalSandboxSpecMemo === null) {
canonicalSandboxSpecMemo = buildCanonicalSandboxSpec()
idleSweepStartedAt = 0
if (idleSweepTimer !== null) {
clearInterval(idleSweepTimer)
idleSweepTimer = null
}
return canonicalSandboxSpecMemo
startAdmission = Promise.resolve()
}
async function validateSandboxMountRoots(): Promise<void> {
for (const root of sandboxMountRoots()) {
async function validateSandboxVmMountRoots(spec: SandboxVmSpec): Promise<void> {
const creatableRoots = new Set([getOpenCodeToolOutputPath(), getOpenCodeGlobalSkillsPath(), getOpenCodeAgentTmpPath()])
for (const root of sandboxVmMountRoots(spec)) {
const resolvedRoot = path.resolve(root)
let stat
try {
@@ -89,6 +141,9 @@ async function validateSandboxMountRoots(): Promise<void> {
if (errorCode !== 'ENOENT') {
throw new Error(`cannot inspect sandbox mount root ${root}: ${error instanceof Error ? error.message : String(error)}`)
}
if (!creatableRoots.has(root)) {
throw new Error(`sandbox mount root ${root} does not exist`)
}
await mkdirSafe(root)
stat = await lstat(root)
}
@@ -102,88 +157,94 @@ async function validateSandboxMountRoots(): Promise<void> {
}
}
function ensureWorkspaceSandbox(): Promise<void> {
if (inFlightBoot) {
return inFlightBoot
function ensureSessionSandbox(spec: SandboxVmSpec, maxRunningVms: number): Promise<void> {
const state = vmState(spec.name)
if (state.inFlightBoot) {
return state.inFlightBoot
}
inFlightBoot = (async () => {
state.inFlightBoot = (async () => {
if (shutdownRequested || stopInProgress) {
throw new Error('sandbox shutdown is in progress; refusing to boot the workspace sandbox')
throw new Error('sandbox shutdown is in progress; refusing to boot the session sandbox')
}
if (lastKnownRunningAt !== null && Date.now() - lastKnownRunningAt < SANDBOX_LS_CACHE_MS) {
const inFlightRemoval = state.inFlightRemoval
if (inFlightRemoval !== null) {
await inFlightRemoval.catch(() => undefined)
}
if (state.lastKnownRunningAt !== null && Date.now() - state.lastKnownRunningAt < SANDBOX_LS_CACHE_MS) {
return
}
await validateSandboxMountRoots()
await bootWorkspaceSandbox()
await validateSandboxVmMountRoots(spec)
await bootSessionSandbox(spec, maxRunningVms)
})().finally(() => {
inFlightBoot = null
state.inFlightBoot = null
})
return inFlightBoot
return state.inFlightBoot
}
async function bootWorkspaceSandbox(): Promise<void> {
async function bootSessionSandbox(spec: SandboxVmSpec, maxRunningVms: number): Promise<void> {
const state = vmState(spec.name)
try {
const outcome = await inspectSandbox()
const outcome = await inspectSandbox(spec.name)
if (outcome.kind === 'failed' || (outcome.record.config === undefined && outcome.record.active_config === undefined)) {
await bootWorkspaceSandboxFromListing()
await bootSessionSandboxFromListing(spec, maxRunningVms)
} else {
const inspected = outcome.record
if (inspected.active_config !== undefined && inspected.active_config !== null) {
const attestation = await attestWorkspaceSandboxConfig(inspected.active_config)
const attestation = await attestSandboxConfig(spec, inspected.active_config)
if (!attestation.trusted) {
logger.warn(`Recreating unverifiable sandbox ${WORKSPACE_SANDBOX_NAME}: ${attestation.reason}`)
await removeWorkspaceSandbox()
await createWorkspaceSandbox()
logger.warn(`Recreating unverifiable sandbox ${spec.name}: ${attestation.reason}`)
await removeSessionSandboxVm(spec.name)
await createSessionSandbox(spec, maxRunningVms)
}
} else {
const attestation = await attestWorkspaceSandboxConfig(inspected.config)
const attestation = await attestSandboxConfig(spec, inspected.config)
if (!attestation.trusted) {
logger.warn(`Recreating unverifiable sandbox ${WORKSPACE_SANDBOX_NAME}: ${attestation.reason}`)
await removeWorkspaceSandbox()
await createWorkspaceSandbox()
logger.warn(`Recreating unverifiable sandbox ${spec.name}: ${attestation.reason}`)
await removeSessionSandboxVm(spec.name)
await createSessionSandbox(spec, maxRunningVms)
} else {
await startWorkspaceSandbox()
await provisionSandboxExecUser()
const runningAttestation = await attestWorkspaceSandbox(true)
await withStartAdmission(spec.name, maxRunningVms, () => startSessionSandbox(spec.name))
await provisionSandboxExecUser(spec.name)
const runningAttestation = await attestSessionSandbox(spec, true)
if (!runningAttestation.trusted) {
logger.warn(
`Recreating sandbox ${WORKSPACE_SANDBOX_NAME} that failed running attestation: ${runningAttestation.reason}`,
`Recreating sandbox ${spec.name} that failed running attestation: ${runningAttestation.reason}`,
)
await removeWorkspaceSandbox()
await createWorkspaceSandbox()
await removeSessionSandboxVm(spec.name)
await createSessionSandbox(spec, maxRunningVms)
}
}
}
}
lastKnownRunningAt = Date.now()
state.lastKnownRunningAt = Date.now()
} catch (error) {
lastKnownRunningAt = null
state.lastKnownRunningAt = null
throw error
}
}
async function bootWorkspaceSandboxFromListing(): Promise<void> {
const entry = findWorkspaceSandboxEntry(await listSandboxes())
async function bootSessionSandboxFromListing(spec: SandboxVmSpec, maxRunningVms: number): Promise<void> {
const entry = findSessionSandboxEntry(await listSandboxes(), spec.name)
if (!entry) {
await createWorkspaceSandbox()
await createSessionSandbox(spec, maxRunningVms)
} else {
const attestation = await attestWorkspaceSandbox(entry.running)
const attestation = await attestSessionSandbox(spec, entry.running)
if (!attestation.trusted) {
logger.warn(`Recreating unverifiable sandbox ${WORKSPACE_SANDBOX_NAME}: ${attestation.reason}`)
await removeWorkspaceSandbox()
await createWorkspaceSandbox()
logger.warn(`Recreating unverifiable sandbox ${spec.name}: ${attestation.reason}`)
await removeSessionSandboxVm(spec.name)
await createSessionSandbox(spec, maxRunningVms)
} else if (!entry.running) {
await startWorkspaceSandbox()
await provisionSandboxExecUser()
const runningAttestation = await attestWorkspaceSandbox(true)
await withStartAdmission(spec.name, maxRunningVms, () => startSessionSandbox(spec.name))
await provisionSandboxExecUser(spec.name)
const runningAttestation = await attestSessionSandbox(spec, true)
if (!runningAttestation.trusted) {
logger.warn(
`Recreating sandbox ${WORKSPACE_SANDBOX_NAME} that failed running attestation: ${runningAttestation.reason}`,
`Recreating sandbox ${spec.name} that failed running attestation: ${runningAttestation.reason}`,
)
await removeWorkspaceSandbox()
await createWorkspaceSandbox()
await removeSessionSandboxVm(spec.name)
await createSessionSandbox(spec, maxRunningVms)
}
}
}
@@ -250,15 +311,15 @@ function parseInspectMount(mount: unknown): ParsedSandboxMount | null {
return { kind: 'other' }
}
async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAttestation> {
const spec = resolveInspectSpec(config)
if (spec === null) {
async function attestSandboxConfig(spec: SandboxVmSpec, config: unknown): Promise<SandboxAttestation> {
const inspectedSpec = resolveInspectSpec(config)
if (inspectedSpec === null) {
return { trusted: false, reason: 'msb inspect returned an unexpected config shape' }
}
const canonical = memoizedCanonicalSandboxSpec()
const canonical = buildCanonicalSandboxSpec(spec)
const labels = isRecord(spec.labels) ? spec.labels : {}
const labels = isRecord(inspectedSpec.labels) ? inspectedSpec.labels : {}
const canonicalLabels = isRecord(canonical.labels) ? canonical.labels : {}
if (labels['ocm.managed'] !== 'true') {
return { trusted: false, reason: 'sandbox is not labelled ocm.managed=true' }
@@ -269,8 +330,14 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
reason: `sandbox network profile ${String(labels['ocm.net'])} does not match ${canonicalLabels['ocm.net']}`,
}
}
if (labels['ocm.session'] !== canonicalLabels['ocm.session']) {
return {
trusted: false,
reason: `sandbox session label ${String(labels['ocm.session'])} does not match ${String(canonicalLabels['ocm.session'])}`,
}
}
const imageReference = inspectImageReference(spec.image)
const imageReference = inspectImageReference(inspectedSpec.image)
const canonicalImageReference = inspectImageReference(canonical.image)
if (imageReference === null) {
return { trusted: false, reason: 'sandbox image is not an OCI reference' }
@@ -278,7 +345,7 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
if (canonicalImageReference !== null && imageReference !== canonicalImageReference) {
return { trusted: false, reason: `sandbox image ${imageReference} does not match ${canonicalImageReference}` }
}
const image = isRecord(spec.image) ? spec.image : {}
const image = isRecord(inspectedSpec.image) ? inspectedSpec.image : {}
const oci = isRecord(image.Oci) ? image.Oci : null
const rootDisk = oci !== null && isRecord(oci.root_disk) ? oci.root_disk : null
if (rootDisk !== null && rootDisk.kind === 'disk-image') {
@@ -310,7 +377,7 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
return { trusted: false, reason: 'sandbox memory is not a positive finite number; cannot derive the runtime tmpfs size' }
}
const mounts = Array.isArray(spec.mounts) ? spec.mounts : []
const mounts = Array.isArray(inspectedSpec.mounts) ? inspectedSpec.mounts : []
const bindRoots = new Set<string>()
let runtimeTmpfsSeen = false
let dockerDataVolumeSeen = false
@@ -450,7 +517,7 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
return { trusted: false, reason: 'sandbox is missing the Docker data volume mount' }
}
const resources = isRecord(spec.resources) ? spec.resources : {}
const resources = isRecord(inspectedSpec.resources) ? inspectedSpec.resources : {}
if (resources.cpus !== canonicalResources.cpus) {
return { trusted: false, reason: `sandbox cpus ${String(resources.cpus)} does not match ${String(canonicalResources.cpus)}` }
}
@@ -464,7 +531,7 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
return { trusted: false, reason: `sandbox max memory does not match ${String(canonicalResources.max_memory_mib)}` }
}
const runtime = isRecord(spec.runtime) ? spec.runtime : {}
const runtime = isRecord(inspectedSpec.runtime) ? inspectedSpec.runtime : {}
const canonicalRuntime = isRecord(canonical.runtime) ? canonical.runtime : {}
if (runtime.workdir !== canonicalRuntime.workdir) {
return { trusted: false, reason: `sandbox workdir ${String(runtime.workdir)} does not match ${String(canonicalRuntime.workdir)}` }
@@ -494,7 +561,7 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
return { trusted: false, reason: 'sandbox configuration runtime.disable_metrics_sample does not match the canonical specification' }
}
const network = isRecord(spec.network) ? spec.network : {}
const network = isRecord(inspectedSpec.network) ? inspectedSpec.network : {}
if (network.enabled !== true) {
return { trusted: false, reason: 'sandbox networking is disabled' }
}
@@ -523,21 +590,21 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
}
}
const emptyMismatch = emptyArrayMismatch(spec.patches, 'patches')
const emptyMismatch = emptyArrayMismatch(inspectedSpec.patches, 'patches')
if (emptyMismatch !== null) return { trusted: false, reason: emptyMismatch }
const rlimitsMismatch = emptyArrayMismatch(spec.rlimits, 'rlimits')
const rlimitsMismatch = emptyArrayMismatch(inspectedSpec.rlimits, 'rlimits')
if (rlimitsMismatch !== null) return { trusted: false, reason: rlimitsMismatch }
if (spec.init !== null) {
if (inspectedSpec.init !== null) {
return { trusted: false, reason: 'sandbox configuration init must be empty' }
}
if (spec.pull_policy !== 'IfMissing') {
return { trusted: false, reason: `sandbox pull policy ${String(spec.pull_policy)} must be IfMissing` }
if (inspectedSpec.pull_policy !== 'IfMissing') {
return { trusted: false, reason: `sandbox pull policy ${String(inspectedSpec.pull_policy)} must be IfMissing` }
}
if (spec.security_profile !== 'default') {
if (inspectedSpec.security_profile !== 'default') {
return { trusted: false, reason: 'sandbox configuration security_profile must be default' }
}
const lifecycle = isRecord(spec.lifecycle) ? spec.lifecycle : {}
const lifecycle = isRecord(inspectedSpec.lifecycle) ? inspectedSpec.lifecycle : {}
if (lifecycle.ephemeral !== false) {
return { trusted: false, reason: 'sandbox configuration lifecycle.ephemeral must be false' }
}
@@ -547,8 +614,8 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
if (lifecycle.idle_timeout_secs !== null) {
return { trusted: false, reason: 'sandbox configuration lifecycle.idle_timeout_secs must be empty' }
}
if (spec.manifest_digest !== undefined && spec.manifest_digest !== null) {
if (typeof spec.manifest_digest !== 'string' || spec.manifest_digest === '') {
if (inspectedSpec.manifest_digest !== undefined && inspectedSpec.manifest_digest !== null) {
if (typeof inspectedSpec.manifest_digest !== 'string' || inspectedSpec.manifest_digest === '') {
return { trusted: false, reason: 'sandbox manifest digest is malformed' }
}
}
@@ -560,10 +627,10 @@ type SandboxInspectOutcome =
| { kind: 'parsed'; record: Record<string, unknown> }
| { kind: 'failed'; reason: string }
async function inspectSandbox(): Promise<SandboxInspectOutcome> {
async function inspectSandbox(name: string): Promise<SandboxInspectOutcome> {
let result: string | { exitCode: number; stdout: string; stderr: string }
try {
result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxInspectArgs()], {
result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxInspectArgs(name)], {
ignoreExitCode: true,
silent: true,
timeout: SANDBOX_LS_TIMEOUT_MS,
@@ -592,8 +659,8 @@ async function inspectSandbox(): Promise<SandboxInspectOutcome> {
return { kind: 'parsed', record: parsed }
}
async function attestWorkspaceSandbox(running: boolean): Promise<SandboxAttestation> {
const outcome = await inspectSandbox()
async function attestSessionSandbox(spec: SandboxVmSpec, running: boolean): Promise<SandboxAttestation> {
const outcome = await inspectSandbox(spec.name)
if (outcome.kind === 'failed') {
return { trusted: false, reason: outcome.reason }
}
@@ -601,9 +668,9 @@ async function attestWorkspaceSandbox(running: boolean): Promise<SandboxAttestat
if (outcome.record.active_config === undefined || outcome.record.active_config === null) {
return { trusted: false, reason: 'msb inspect returned no active configuration for the running sandbox' }
}
return await attestWorkspaceSandboxConfig(outcome.record.active_config)
return await attestSandboxConfig(spec, outcome.record.active_config)
}
return await attestWorkspaceSandboxConfig(outcome.record.config)
return await attestSandboxConfig(spec, outcome.record.config)
}
async function cacheSandboxImage(): Promise<void> {
@@ -614,9 +681,9 @@ async function cacheSandboxImage(): Promise<void> {
logger.info(`Sandbox guest image ${ENV.SANDBOX.IMAGE} is cached`)
}
async function pingSandboxAgent(): Promise<boolean> {
async function pingSandboxAgent(name: string): Promise<boolean> {
try {
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxPingArgs()], {
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxPingArgs(name)], {
ignoreExitCode: true,
silent: true,
timeout: SANDBOX_AGENT_PING_TIMEOUT_MS,
@@ -627,33 +694,33 @@ async function pingSandboxAgent(): Promise<boolean> {
}
}
async function waitForSandboxAgent(): Promise<boolean> {
async function waitForSandboxAgent(name: string): Promise<boolean> {
const deadline = Date.now() + ENV.SANDBOX.START_TIMEOUT_MS
for (;;) {
if (await pingSandboxAgent()) return true
if (await pingSandboxAgent(name)) return true
if (Date.now() >= deadline) return false
await new Promise((resolve) => setTimeout(resolve, SANDBOX_AGENT_POLL_DELAY_MS))
}
}
async function provisionSandboxExecUser(): Promise<void> {
async function provisionSandboxExecUser(name: string): Promise<void> {
try {
await ensureSandboxExecUserProvisioned()
await ensureSandboxExecUserProvisioned(name)
return
} catch (error) {
logger.warn(
`Sandbox exec user provisioning failed, so sudo will not work inside the guest yet; retrying in the background: ${error instanceof Error ? error.message : String(error)}`,
`Sandbox exec user provisioning failed for ${name}, so sudo will not work inside the guest yet; retrying in the background: ${error instanceof Error ? error.message : String(error)}`,
)
}
scheduleBackgroundProvisionRetry()
scheduleBackgroundProvisionRetry(name)
}
async function provisionSandboxExecUserPasswd(): Promise<void> {
const provisionArgs = buildSandboxProvisionArgs()
async function provisionSandboxExecUserPasswd(name: string): Promise<void> {
const provisionArgs = buildSandboxProvisionArgs(name)
if (provisionArgs.length === 0) {
return
}
if (!(await waitForSandboxAgent())) {
if (!(await waitForSandboxAgent(name))) {
throw new Error('the sandbox agent did not become reachable before the exec user could be provisioned')
}
let lastError: unknown = null
@@ -667,7 +734,7 @@ async function provisionSandboxExecUserPasswd(): Promise<void> {
await executeCommand([sandboxExecutablePath(), ...provisionArgs], {
timeout: ENV.SANDBOX.START_TIMEOUT_MS,
})
const verifyArgs = buildSandboxVerifyProvisionArgs()
const verifyArgs = buildSandboxVerifyProvisionArgs(name)
if (verifyArgs.length > 0) {
await executeCommand([sandboxExecutablePath(), ...verifyArgs], {
timeout: SANDBOX_LS_TIMEOUT_MS,
@@ -684,36 +751,34 @@ async function provisionSandboxExecUserPasswd(): Promise<void> {
)
}
let backgroundProvisionRetry: Promise<void> | null = null
let provisionRetryGeneration = 0
let inFlightProvision: Promise<void> | null = null
function ensureSandboxExecUserProvisioned(): Promise<void> {
if (inFlightProvision) {
return inFlightProvision
function ensureSandboxExecUserProvisioned(name: string): Promise<void> {
const state = vmState(name)
if (state.inFlightProvision) {
return state.inFlightProvision
}
inFlightProvision = provisionSandboxExecUserPasswd().finally(() => {
inFlightProvision = null
state.inFlightProvision = provisionSandboxExecUserPasswd(name).finally(() => {
state.inFlightProvision = null
})
return inFlightProvision
return state.inFlightProvision
}
export function backgroundProvisionRetryForTests(): Promise<void> | null {
return backgroundProvisionRetry
export function backgroundProvisionRetryForTests(name: string): Promise<void> | null {
return vmStates.get(name)?.backgroundProvisionRetry ?? null
}
export function provisionSandboxExecUserForTests(): Promise<void> {
return ensureSandboxExecUserProvisioned()
export function provisionSandboxExecUserForTests(name: string): Promise<void> {
return ensureSandboxExecUserProvisioned(name)
}
function scheduleBackgroundProvisionRetry(): void {
const generation = provisionRetryGeneration
if (backgroundProvisionRetry !== null) return
logger.info('Sandbox exec user provisioning background retry scheduled')
backgroundProvisionRetry = (async () => {
function scheduleBackgroundProvisionRetry(name: string): void {
const state = vmState(name)
const generation = state.provisionRetryGeneration
if (state.backgroundProvisionRetry !== null) return
logger.info(`Sandbox exec user provisioning background retry scheduled for ${name}`)
state.backgroundProvisionRetry = (async () => {
for (let attempt = 1; attempt <= SANDBOX_PROVISION_RETRY_ATTEMPTS; attempt++) {
await new Promise((resolve) => setTimeout(resolve, SANDBOX_PROVISION_RETRY_DELAY_MS))
if (generation !== provisionRetryGeneration) {
if (generation !== state.provisionRetryGeneration) {
logger.info('Sandbox exec user provisioning background retry cancelled by a runtime state reset')
return
}
@@ -722,46 +787,94 @@ function scheduleBackgroundProvisionRetry(): void {
return
}
try {
await ensureSandboxExecUserProvisioned()
await ensureSandboxExecUserProvisioned(name)
logger.info(`Sandbox exec user provisioned by the background retry (attempt ${attempt})`)
return
} catch (error) {
logger.warn(
`Sandbox exec user provisioning background retry attempt ${attempt} failed: ${error instanceof Error ? error.message : String(error)}`,
)
if (generation !== provisionRetryGeneration || shutdownRequested) return
if (generation !== state.provisionRetryGeneration || shutdownRequested) return
}
}
logger.warn(
'Sandbox exec user provisioning retries were exhausted; sudo will not work inside the guest until the next boot cycle',
)
})().finally(() => {
if (generation === provisionRetryGeneration) {
backgroundProvisionRetry = null
if (generation === state.provisionRetryGeneration) {
state.backgroundProvisionRetry = null
}
})
}
async function createWorkspaceSandbox(): Promise<void> {
await executeCommand([sandboxExecutablePath(), ...buildSandboxCreateArgs()], {
timeout: ENV.SANDBOX.START_TIMEOUT_MS,
})
await provisionSandboxExecUser()
const attestation = await attestWorkspaceSandbox(true)
async function createSessionSandbox(spec: SandboxVmSpec, maxRunningVms: number): Promise<void> {
await withStartAdmission(spec.name, maxRunningVms, () => runSandboxCreate(spec))
await provisionSandboxExecUser(spec.name)
const attestation = await attestSessionSandbox(spec, true)
if (!attestation.trusted) {
throw new Error(`newly created sandbox ${WORKSPACE_SANDBOX_NAME} failed attestation: ${attestation.reason}`)
throw new Error(`newly created sandbox ${spec.name} failed attestation: ${attestation.reason}`)
}
}
async function removeWorkspaceSandbox(): Promise<void> {
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxRemoveArgs()], {
async function runSandboxCreate(spec: SandboxVmSpec): Promise<void> {
const first = await executeSandboxCreate(buildSandboxCreateArgs(spec))
if (first.exitCode === 0) return
if (!SANDBOX_CREATE_EXISTS_PATTERN.test(`${first.stdout}\n${first.stderr}`)) {
throw new Error(`Command failed with code ${first.exitCode}: ${first.stderr || first.stdout}`)
}
logger.warn(
`Sandbox ${spec.name} already exists as an orphaned msb sandbox; recreating it with --replace: ${first.stderr || first.stdout}`,
)
const replaced = await executeSandboxCreate(buildSandboxCreateArgs(spec, { replace: true }))
if (replaced.exitCode !== 0) {
throw new Error(`Command failed with code ${replaced.exitCode}: ${replaced.stderr || replaced.stdout}`)
}
}
async function executeSandboxCreate(args: string[]): Promise<{ exitCode: number; stdout: string; stderr: string }> {
const result = (await executeCommand([sandboxExecutablePath(), ...args], {
ignoreExitCode: true,
timeout: ENV.SANDBOX.START_TIMEOUT_MS,
})) as string | { exitCode: number; stdout: string; stderr: string }
return typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
}
async function removeSessionSandboxVm(name: string): Promise<void> {
await runSandboxRemoval(buildSandboxRemoveArgs(name), SANDBOX_REMOVAL_MISSING_PATTERN, 'msb rm')
}
function removeSandboxVmAndVolume(name: string): Promise<void> {
const state = vmState(name)
if (state.inFlightRemoval !== null) {
return state.inFlightRemoval
}
const inFlightBoot = state.inFlightBoot
state.inFlightRemoval = (async () => {
if (inFlightBoot !== null) {
await inFlightBoot.catch(() => undefined)
}
await removeSessionSandboxVm(name)
await runSandboxRemoval(
buildSandboxVolumeRemoveArgs(sandboxDockerDataVolumeName(name)),
SANDBOX_VOLUME_REMOVAL_MISSING_PATTERN,
'msb volume rm',
)
state.lastKnownRunningAt = null
})().finally(() => {
state.inFlightRemoval = null
})
return state.inFlightRemoval
}
async function runSandboxRemoval(args: string[], missingPattern: RegExp, label: string): Promise<void> {
const result = (await executeCommand([sandboxExecutablePath(), ...args], {
ignoreExitCode: true,
timeout: SANDBOX_LS_TIMEOUT_MS,
})) as string | { exitCode: number; stdout: string; stderr: string }
const removal = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
if (removal.exitCode !== 0) {
throw new Error(`msb rm failed with code ${removal.exitCode}: ${removal.stderr || removal.stdout}`)
}
if (removal.exitCode === 0) return
if (missingPattern.test(removal.stderr)) return
throw new Error(`${label} failed with code ${removal.exitCode}: ${removal.stderr || removal.stdout}`)
}
type SandboxLsEntry = {
@@ -794,20 +907,24 @@ async function listSandboxes(): Promise<SandboxLsEntry[]> {
return parsed as SandboxLsEntry[]
}
function findWorkspaceSandboxEntry(entries: SandboxLsEntry[]): { running: boolean } | null {
function sandboxEntryRunning(entry: SandboxLsEntry): boolean {
const status = entry.status ?? entry.state
return String(status).toLowerCase() === 'running'
}
function findSessionSandboxEntry(entries: SandboxLsEntry[], name: string): { running: boolean } | null {
for (const value of entries) {
if (!value || typeof value !== 'object' || Array.isArray(value)) continue
const entry = value as SandboxLsEntry
if (entry.name !== WORKSPACE_SANDBOX_NAME) continue
const status = entry.status ?? entry.state
return { running: String(status).toLowerCase() === 'running' }
if (entry.name !== name) continue
return { running: sandboxEntryRunning(entry) }
}
return null
}
async function startWorkspaceSandbox(): Promise<void> {
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxStartArgs()], {
async function startSessionSandbox(name: string): Promise<void> {
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxStartArgs(name)], {
ignoreExitCode: true,
timeout: ENV.SANDBOX.START_TIMEOUT_MS,
})) as string | { exitCode: number; stdout: string; stderr: string }
@@ -815,32 +932,132 @@ async function startWorkspaceSandbox(): Promise<void> {
return
}
const entry = findWorkspaceSandboxEntry(await listSandboxes())
const entry = findSessionSandboxEntry(await listSandboxes(), name)
if (entry?.running) {
return
}
throw new Error(`msb start failed with code ${result.exitCode}: ${result.stderr || result.stdout}`)
}
async function withStartAdmission<T>(name: string, maxRunningVms: number, run: () => Promise<T>): Promise<T> {
const previous = startAdmission
let release: () => void = () => {}
startAdmission = new Promise<void>((resolve) => {
release = resolve
})
await previous
try {
await admitVmStart(name, maxRunningVms)
return await run()
} finally {
release()
}
}
async function admitVmStart(name: string, maxRunningVms: number): Promise<void> {
const entries = await listSandboxes()
const running: string[] = []
for (const value of entries) {
if (!value || typeof value !== 'object' || Array.isArray(value)) continue
const entry = value as SandboxLsEntry
if (typeof entry.name !== 'string' || entry.name === name) continue
if (!SESSION_SANDBOX_NAME_PATTERN.test(entry.name)) continue
if (sandboxEntryRunning(entry)) running.push(entry.name)
}
if (running.length < maxRunningVms) return
const execTimeoutMs = ENV.SANDBOX.EXEC_TIMEOUT_MS
const candidates = running
.map((vmName) => ({ vmName, lastUsedAt: vmStates.get(vmName)?.lastUsedAt ?? 0 }))
.filter((candidate) => Date.now() - candidate.lastUsedAt >= execTimeoutMs)
if (candidates.length === 0) {
throw new Error(
`${running.length} sandbox VMs are already running (the limit in Settings → Sandbox is ${maxRunningVms}) and none has been idle for ${execTimeoutMs / 60000} minutes; retry when a sandboxed command finishes or raise the limit`,
)
}
candidates.sort((left, right) => left.lastUsedAt - right.lastUsedAt)
const victim = candidates[0]!
let stopResult: { exitCode: number; stdout: string; stderr: string }
try {
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxStopArgs(victim.vmName)], {
ignoreExitCode: true,
timeout: SANDBOX_STOP_TIMEOUT_MS,
})) as string | { exitCode: number; stdout: string; stderr: string }
stopResult = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
} catch (error) {
throw new Error(
`could not stop idle sandbox VM ${victim.vmName} to stay within the limit of ${maxRunningVms} running sandbox VMs: ${error instanceof Error ? error.message : String(error)}`,
)
}
if (stopResult.exitCode !== 0) {
throw new Error(
`could not stop idle sandbox VM ${victim.vmName} to stay within the limit of ${maxRunningVms} running sandbox VMs: ${stopResult.stderr || stopResult.stdout}`,
)
}
const victimState = vmStates.get(victim.vmName)
if (victimState !== undefined) {
victimState.lastKnownRunningAt = null
}
}
function ensureIdleSweepStarted(db: Database): void {
if (idleSweepTimer !== null) return
idleSweepStartedAt = Date.now()
idleSweepTimer = setInterval(() => {
void sweepIdleSandboxes(db)
}, SANDBOX_IDLE_SWEEP_INTERVAL_MS)
const timer = idleSweepTimer as { unref?: () => void }
timer.unref?.()
}
async function sweepIdleSandboxes(db: Database): Promise<void> {
if (shutdownRequested || stopInProgress) return
const idleStopMinutes = sandboxIdleStopMinutes(db)
const threshold = Math.max(idleStopMinutes * 60000, ENV.SANDBOX.EXEC_TIMEOUT_MS)
let entries: SandboxLsEntry[]
try {
entries = await listSandboxes()
} catch (error) {
logger.warn(`Failed to list sandboxes for the idle sweep: ${error instanceof Error ? error.message : String(error)}`)
return
}
for (const value of entries) {
if (shutdownRequested || stopInProgress) return
if (!value || typeof value !== 'object' || Array.isArray(value)) continue
const entry = value as SandboxLsEntry
const name = entry.name
if (typeof name !== 'string' || !SESSION_SANDBOX_NAME_PATTERN.test(name)) continue
const state = vmStates.get(name)
if (state !== undefined && (state.inFlightBoot !== null || state.inFlightRemoval !== null)) continue
const lastActivity = Math.max(state?.lastUsedAt ?? 0, idleSweepStartedAt)
if (Date.now() - lastActivity < threshold) continue
try {
await removeSandboxVmAndVolume(name)
logger.info(`Removed idle sandbox ${name} and its Docker data volume`)
} catch (error) {
logger.warn(`Failed to remove idle sandbox ${name}: ${error instanceof Error ? error.message : String(error)}`)
}
}
}
function sandboxIdleStopMinutes(db: Database): number {
return new SettingsService(db).getSettings('default').preferences.sandbox?.idleStopMinutes ?? DEFAULT_SANDBOX_IDLE_STOP_MINUTES
}
function sandboxMaxRunningVms(db: Database): number {
return new SettingsService(db).getSettings('default').preferences.sandbox?.maxRunningVms ?? DEFAULT_SANDBOX_MAX_RUNNING_VMS
}
export class SandboxRuntimeService {
constructor(private readonly db: Database) {}
async prepareWorkspaceSandboxOnBoot(): Promise<void> {
async prepareSandboxOnBoot(): Promise<void> {
if (!this.isSandboxEnabled()) return
const capability = detectSandboxCapability()
if (!capability.available) return
if (getProcessIdentityAttestationError() !== null) return
ensureIdleSweepStarted(this.db)
await cacheSandboxImage()
await ensureWorkspaceSandbox()
try {
await ensureSandboxExecUserProvisioned()
logger.info('Workspace sandbox is running and its exec user is provisioned')
} catch (error) {
logger.warn(
`Workspace sandbox is running but its exec user is not provisioned yet; retrying in the background: ${error instanceof Error ? error.message : String(error)}`,
)
scheduleBackgroundProvisionRetry()
}
}
isEnabled(): boolean {
@@ -859,7 +1076,7 @@ export class SandboxRuntimeService {
}
}
async planShell(directory: string, enforced = false): Promise<SandboxShellPlan> {
async planShell(directory: string, target: SandboxShellTarget, enforced = false): Promise<SandboxShellPlan> {
if (!enforced && !this.isEnabled()) {
return { mode: 'host' }
}
@@ -871,41 +1088,66 @@ export class SandboxRuntimeService {
if (attestationError !== null) {
return { mode: 'blocked', reason: attestationError }
}
const workDirectory = await resolveSandboxWorkDirectory(directory)
if (workDirectory === null) {
const projectMounts = await resolveSessionSandboxMounts(target.locationDirectory)
if (projectMounts === null) {
return {
mode: 'blocked',
reason: `working directory is outside the sandboxed project roots (${sandboxProjectRoots().join(', ')})`,
reason: `session directory ${target.locationDirectory} is outside the sandboxed project roots (${sandboxProjectRoots().join(', ')})`,
}
}
const workDirectory = await resolveSandboxWorkDirectory(directory)
if (workDirectory === null || !projectMounts.some((mount) => isPathWithinRoot(mount, workDirectory))) {
return {
mode: 'blocked',
reason: `working directory ${directory} is outside this session's sandbox (mounted: ${projectMounts.join(', ')})`,
}
}
const spec: SandboxVmSpec = {
name: sessionSandboxName(target.rootSessionId),
rootSessionId: target.rootSessionId,
projectMounts,
cpus: target.resources.cpus,
memoryMib: target.resources.memoryMib,
}
const state = vmState(spec.name)
state.lastUsedAt = Date.now()
try {
await ensureWorkspaceSandbox()
await ensureSessionSandbox(spec, sandboxMaxRunningVms(this.db))
ensureIdleSweepStarted(this.db)
state.lastUsedAt = Date.now()
const env = {
...new CredentialProvider(this.db).getSandboxGitEnv({ cwd: directory }),
...await getGitIdentityEnvForDirectory(directory, this.db),
}
return Object.keys(env).length > 0
? { mode: 'sandbox', workdir: workDirectory, env }
: { mode: 'sandbox', workdir: workDirectory }
? { mode: 'sandbox', name: spec.name, workdir: workDirectory, env }
: { mode: 'sandbox', name: spec.name, workdir: workDirectory }
} catch (error) {
logger.error('Failed to prepare the workspace sandbox', error)
logger.error('Failed to prepare the session sandbox', error)
return { mode: 'blocked', reason: error instanceof Error ? error.message : String(error) }
}
}
async stopWorkspaceSandbox(): Promise<void> {
async removeSessionSandbox(rootSessionId: string): Promise<void> {
if (!detectSandboxCapability().available) return
await removeSandboxVmAndVolume(sessionSandboxName(rootSessionId))
}
async stopAllSandboxes(): Promise<void> {
shutdownRequested = true
await this.stopManagedSandbox()
await this.stopManagedSandboxes()
}
async stopWorkspaceSandboxForToggle(): Promise<void> {
await this.stopManagedSandbox()
async stopAllSandboxesForToggle(): Promise<void> {
await this.stopManagedSandboxes()
}
private async stopManagedSandbox(): Promise<void> {
private async stopManagedSandboxes(): Promise<void> {
stopInProgress = true
provisionRetryGeneration += 1
backgroundProvisionRetry = null
for (const state of vmStates.values()) {
state.provisionRetryGeneration += 1
state.backgroundProvisionRetry = null
}
try {
await this.runManagedSandboxStop()
} finally {
@@ -914,14 +1156,16 @@ export class SandboxRuntimeService {
}
private async runManagedSandboxStop(): Promise<void> {
while (inFlightBoot) {
try {
await inFlightBoot
} catch {
// a settled boot is done; keep waiting for any other admitted boot
}
for (;;) {
const inFlight = [...vmStates.values()]
.map((state) => state.inFlightBoot)
.filter((boot): boot is Promise<void> => boot !== null)
if (inFlight.length === 0) break
await Promise.all(inFlight.map((boot) => boot.catch(() => undefined)))
}
for (const state of vmStates.values()) {
state.lastKnownRunningAt = null
}
lastKnownRunningAt = null
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxStopManagedArgs()], {
ignoreExitCode: true,
timeout: SANDBOX_STOP_TIMEOUT_MS,
@@ -929,10 +1173,10 @@ export class SandboxRuntimeService {
const stopResult = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
if (stopResult.exitCode !== 0) {
try {
await confirmManagedSandboxStopped()
logger.warn(`msb stop failed with code ${stopResult.exitCode} but the workspace sandbox is confirmed stopped: ${stopResult.stderr || stopResult.stdout}`)
await confirmManagedSandboxesStopped()
logger.warn(`msb stop failed with code ${stopResult.exitCode} but the managed sandbox VMs are confirmed stopped: ${stopResult.stderr || stopResult.stdout}`)
} catch (error) {
logger.error('Failed to confirm the workspace sandbox stopped:', error)
logger.error('Failed to confirm the managed sandbox VMs stopped:', error)
throw error
}
}
@@ -943,13 +1187,17 @@ export class SandboxRuntimeService {
}
}
async function confirmManagedSandboxStopped(): Promise<void> {
const entry = findWorkspaceSandboxEntry(await listSandboxes())
if (entry !== null && entry.running) {
throw new Error('msb stop failed to stop the workspace sandbox; the managed microVM is still running')
async function confirmManagedSandboxesStopped(): Promise<void> {
for (const value of await listSandboxes()) {
if (!value || typeof value !== 'object' || Array.isArray(value)) continue
const entry = value as SandboxLsEntry
if (typeof entry.name !== 'string' || !SESSION_SANDBOX_NAME_PATTERN.test(entry.name)) continue
if (sandboxEntryRunning(entry)) {
throw new Error('msb stop failed to stop the sandbox microVMs; a managed microVM is still running')
}
}
}
export async function stopWorkspaceSandboxOnShutdown(db: Database): Promise<void> {
await new SandboxRuntimeService(db).stopWorkspaceSandbox()
export async function stopSandboxesOnShutdown(db: Database): Promise<void> {
await new SandboxRuntimeService(db).stopAllSandboxes()
}
+10 -2
View File
@@ -6,13 +6,14 @@ import {
resolveSandboxExecUser,
sandboxExecutablePath,
sandboxMountRoots,
WORKSPACE_SANDBOX_NAME,
} from './command'
export const SANDBOX_SHELL_FILENAME = 'ocm-sandbox-shell'
export const SANDBOX_SHELL_ENV_WORKDIR = 'OCM_SANDBOX_WORKDIR'
export const SANDBOX_SHELL_ENV_NAME = 'OCM_SANDBOX_NAME'
/**
* Upper bound on `http.<host>.extraheader` pairs forwarded into the microVM.
* The shim enumerates a fixed set of variable names rather than expanding
@@ -74,7 +75,7 @@ export function buildSandboxShellShimScript(): string {
const execArgs = [
quoteForShell(sandboxExecutablePath()),
'exec',
WORKSPACE_SANDBOX_NAME,
`"$${SANDBOX_SHELL_ENV_NAME}"`,
'--no-tty',
'-q',
'-u',
@@ -92,6 +93,13 @@ if [ -z "\${${SANDBOX_SHELL_ENV_WORKDIR}:-}" ]; then
echo 'ocm-sandbox-shell: sandbox working directory missing; refusing to run on the host' >&2
exit 126
fi
case "\${${SANDBOX_SHELL_ENV_NAME}:-}" in
ocm-session-[0-9abcdef][0-9abcdef][0-9abcdef][0-9abcdef][0-9abcdef][0-9abcdef][0-9abcdef][0-9abcdef][0-9abcdef][0-9abcdef][0-9abcdef][0-9abcdef]) ;;
*)
echo 'ocm-sandbox-shell: sandbox name missing or invalid; refusing to run on the host' >&2
exit 126
;;
esac
ocm_argc=$#
set -- "$@" ${execArgs}
${forwardEnv}
+42
View File
@@ -0,0 +1,42 @@
import type { OpenCodeClient } from './opencode/client'
const MAX_PARENT_HOPS = 10
export class SessionAncestry {
private readonly parentBySession = new Map<string, string | null>()
constructor(private readonly openCodeClient: OpenCodeClient) {}
rememberParent(sessionId: string, parentId: string | null | undefined): void {
this.parentBySession.set(sessionId, parentId ?? null)
}
forget(sessionId: string): void {
this.parentBySession.delete(sessionId)
}
async resolveRootSessionId(sessionId: string): Promise<string> {
let current = sessionId
for (let hops = 0; hops < MAX_PARENT_HOPS; hops += 1) {
const parentId = await this.getParentId(current)
if (!parentId) {
return current
}
current = parentId
}
return current
}
private async getParentId(sessionId: string): Promise<string | null> {
if (this.parentBySession.has(sessionId)) {
return this.parentBySession.get(sessionId) ?? null
}
const session = await this.openCodeClient.api.session.get({ sessionID: sessionId })
const parentId = session.parentID ?? null
this.parentBySession.set(sessionId, parentId)
return parentId
}
}
+1 -1
View File
@@ -256,7 +256,7 @@ export class SessionGoalService {
})
}
async handleEvent(directory: string, event: SSEEvent): Promise<void> {
async handleEvent(directory: string | null, event: SSEEvent): Promise<void> {
const sessionId = sessionIDFromEvent(event)
if (!sessionId) {
return
@@ -14,11 +14,10 @@ import {
} from '../db/session-permission-modes'
import { logger } from '../utils/logger'
import type { OpenCodeClient } from './opencode/client'
import type { SessionAncestry } from './session-ancestry'
import type { SSEEvent } from './sse-aggregator'
import type { SettingsService } from './settings'
const MAX_PARENT_HOPS = 10
export class SessionPermissionModeError extends Error {
status: number
@@ -29,37 +28,18 @@ export class SessionPermissionModeError extends Error {
}
export class SessionPermissionModeService {
private readonly parentBySession = new Map<string, string | null>()
constructor(
private readonly db: Database,
private readonly openCodeClient: OpenCodeClient,
private readonly settingsService: SettingsService,
private readonly ancestry: SessionAncestry,
) {}
private rememberParent(sessionId: string, parentId: string | null | undefined): void {
this.parentBySession.set(sessionId, parentId ?? null)
}
private async resolveRootSessionId(sessionId: string): Promise<string> {
let current = sessionId
for (let hops = 0; hops < MAX_PARENT_HOPS; hops += 1) {
const parentId = await this.getParentId(current)
if (!parentId) {
return current
}
current = parentId
}
return current
}
async handleEvent(directory: string, event: SSEEvent): Promise<void> {
async handleEvent(directory: string | null, event: SSEEvent): Promise<void> {
switch (event.type) {
case 'session.created': {
const { sessionID, parentID, permissions } = event.data
this.rememberParent(sessionID, parentID)
this.ancestry.rememberParent(sessionID, parentID)
const hasExplicitPermissions = Array.isArray(permissions) && permissions.length > 0
if (!parentID && !hasExplicitPermissions && this.defaultMode() === 'auto') {
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto')
@@ -68,7 +48,7 @@ export class SessionPermissionModeService {
}
case 'session.forked': {
const { sessionID, parentID } = event.data
this.rememberParent(sessionID, null)
this.ancestry.rememberParent(sessionID, null)
const sourceMode = await this.getEffectiveMode(parentID)
if (sourceMode.mode === 'auto') {
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto')
@@ -82,7 +62,7 @@ export class SessionPermissionModeService {
}
case 'session.deleted': {
const { sessionID } = event.data
this.parentBySession.delete(sessionID)
this.ancestry.forget(sessionID)
deleteSessionPermissionMode(this.db, sessionID)
return
}
@@ -95,7 +75,7 @@ export class SessionPermissionModeService {
}
async setMode(sessionId: string, mode: SessionPermissionMode, directory: string): Promise<SessionPermissionModeState> {
const rootSessionId = await this.resolveRootSessionId(sessionId)
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
const lockedReason = this.lockReasonForRoot(sessionId, rootSessionId)
if (lockedReason === 'schedule') {
throw new SessionPermissionModeError(
@@ -245,20 +225,9 @@ export class SessionPermissionModeService {
private async resolveRootSessionIdOrNull(sessionId: string): Promise<string | null> {
try {
return await this.resolveRootSessionId(sessionId)
return await this.ancestry.resolveRootSessionId(sessionId)
} catch {
return null
}
}
private async getParentId(sessionId: string): Promise<string | null> {
if (this.parentBySession.has(sessionId)) {
return this.parentBySession.get(sessionId) ?? null
}
const session = await this.openCodeClient.api.session.get({ sessionID: sessionId })
const parentId = session.parentID ?? null
this.parentBySession.set(sessionId, parentId)
return parentId
}
}
+200
View File
@@ -0,0 +1,200 @@
import type { Database } from 'bun:sqlite'
import type {
SessionSandboxClaim,
SessionSandboxResources,
SessionSandboxState,
SetSessionSandboxRequest,
} from '@opencode-manager/shared/schemas'
import {
deleteSessionSandboxMode,
getSessionSandboxMode,
insertSessionSandboxModeIfAbsent,
setSessionSandboxResources,
setSessionSandboxed,
type SessionSandboxModeRow,
} from '../db/session-sandbox-modes'
import { resolveSandboxResources, sandboxResourceLimitError } from './sandbox/resources'
import type { SessionAncestry } from './session-ancestry'
import type { SSEEvent } from './sse-aggregator'
import type { SettingsService } from './settings'
import { logger } from '../utils/logger'
export class SessionSandboxError extends Error {
status: number
constructor(message: string, status: number) {
super(message)
this.status = status
}
}
export class SessionSandboxService {
constructor(
private readonly db: Database,
private readonly ancestry: SessionAncestry,
private readonly settingsService: SettingsService,
private readonly sandboxes: { removeSessionSandbox(rootSessionId: string): Promise<void> },
) {}
async handleEvent(directory: string | null, event: SSEEvent): Promise<void> {
switch (event.type) {
case 'session.created': {
const { sessionID, parentID } = event.data
this.ancestry.rememberParent(sessionID, parentID)
if (!parentID) {
insertSessionSandboxModeIfAbsent(this.db, sessionID, {
sandboxed: this.defaultSandboxed(),
source: 'default',
resources: null,
})
}
return
}
case 'session.forked': {
const { sessionID, parentID } = event.data
this.ancestry.rememberParent(sessionID, null)
const parentRow = await this.resolveParentRootRow(parentID)
insertSessionSandboxModeIfAbsent(this.db, sessionID, {
sandboxed: parentRow?.sandboxed ?? this.defaultSandboxed(),
source: parentRow?.source ?? 'default',
resources: parentRow?.resources ?? null,
})
return
}
case 'session.deleted': {
const { sessionID } = event.data
this.ancestry.forget(sessionID)
if (getSessionSandboxMode(this.db, sessionID) !== null) {
this.removeSandboxInBackground(sessionID, `deleted session ${sessionID}`)
}
deleteSessionSandboxMode(this.db, sessionID)
return
}
}
}
async getState(sessionId: string): Promise<SessionSandboxState> {
const available = this.sandboxSupported()
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
const lockedReason = rootSessionId !== sessionId ? 'child' : null
const stored = getSessionSandboxMode(this.db, rootSessionId)
if (!available) {
return this.buildState(sessionId, rootSessionId, false, stored, lockedReason, false)
}
return this.buildState(sessionId, rootSessionId, stored?.sandboxed ?? this.defaultSandboxed(), stored, lockedReason, true)
}
async getClaim(sessionId: string): Promise<SessionSandboxClaim> {
const available = this.sandboxSupported()
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
if (!available) {
return { sandboxed: false, source: 'default', since: 0 }
}
const stored = getSessionSandboxMode(this.db, rootSessionId)
if (!stored) {
return { sandboxed: this.defaultSandboxed(), source: 'default', since: 0 }
}
return { sandboxed: stored.sandboxed, source: stored.source, since: stored.toggledAt }
}
async update(sessionId: string, request: SetSessionSandboxRequest): Promise<SessionSandboxState> {
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
if (rootSessionId !== sessionId) {
throw new SessionSandboxError('Child sessions inherit sandboxing from their parent session', 400)
}
const available = this.sandboxSupported()
if (request.sandboxed === true && !available) {
throw new SessionSandboxError('Sandboxing is not enabled for this server', 409)
}
if (request.resources != null) {
const limitError = sandboxResourceLimitError(request.resources)
if (limitError !== null) {
throw new SessionSandboxError(limitError, 400)
}
}
const defaultSandboxed = this.defaultSandboxed()
this.db.transaction(() => {
if (request.sandboxed !== undefined) {
setSessionSandboxed(this.db, sessionId, request.sandboxed)
}
if (request.resources !== undefined) {
setSessionSandboxResources(this.db, sessionId, request.resources, defaultSandboxed)
}
})()
if (request.sandboxed === false && available) {
this.removeSandboxInBackground(sessionId, `session ${sessionId} after its sandbox was turned off`)
}
return this.getState(sessionId)
}
async resolveShellTarget(sessionId: string): Promise<{ rootSessionId: string; resources: SessionSandboxResources }> {
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
const stored = getSessionSandboxMode(this.db, rootSessionId)
return {
rootSessionId,
resources: resolveSandboxResources(this.preferences().sandbox, stored?.resources ?? null),
}
}
private removeSandboxInBackground(rootSessionId: string, reason: string): void {
void this.sandboxes.removeSessionSandbox(rootSessionId).catch((error) => {
logger.warn(
`Failed to remove the sandbox microVM for ${reason}: ${error instanceof Error ? error.message : String(error)}`,
)
})
}
private async resolveParentRootRow(parentId: string): Promise<SessionSandboxModeRow | null> {
let rootSessionId: string
try {
rootSessionId = await this.ancestry.resolveRootSessionId(parentId)
} catch {
return null
}
return getSessionSandboxMode(this.db, rootSessionId)
}
private buildState(
sessionId: string,
rootSessionId: string,
sandboxed: boolean,
stored: SessionSandboxModeRow | null,
lockedReason: 'child' | null,
available: boolean,
): SessionSandboxState {
const resources = stored?.resources ?? null
return {
sessionId,
rootSessionId,
sandboxed,
source: stored?.source ?? 'default',
resources,
effectiveResources: resolveSandboxResources(this.preferences().sandbox, resources),
lockedReason,
available,
}
}
private preferences() {
return this.settingsService.getSettings().preferences
}
private sandboxSupported(): boolean {
return this.preferences().sandbox?.enabled === true
}
private defaultSandboxed(): boolean {
return this.preferences().sandbox?.defaultForNewSessions ?? true
}
}
+5 -1
View File
@@ -8,7 +8,7 @@ import { encodeSSEFrame } from '../utils/sse-frame'
type SSEClientCallback = (event: string, data: string) => void
type SSEClientFrameWriter = (frame: Uint8Array) => void
type SSEEventListener = (directory: string, event: SSEEvent) => void
type SSEEventListener = (directory: string | null, event: SSEEvent) => void
interface SSEClient {
id: string
@@ -448,6 +448,7 @@ class SSEAggregator {
return
}
this.notifyListeners(null, event)
this.writeEnvelopeToClients(this.clients.keys(), null, payloadJson)
} catch (error) {
logger.error(`SSE failed to handle ${event.type} event:`, error)
@@ -470,7 +471,10 @@ class SSEAggregator {
private notifyEvent(directory: string, event: SSEEvent): void {
this.handleEvent(directory, event)
this.notifyListeners(directory, event)
}
private notifyListeners(directory: string | null, event: SSEEvent): void {
this.eventListeners.forEach(listener => {
try { listener(directory, event) } catch { /* ignore listener errors */ }
})
@@ -0,0 +1,124 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { Database } from 'bun:sqlite'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import {
deleteSessionSandboxMode,
getSessionSandboxMode,
insertSessionSandboxModeIfAbsent,
setSessionSandboxResources,
setSessionSandboxed,
} from '../../src/db/session-sandbox-modes'
function createTestDb(): Database {
const db = new Database(':memory:')
migrate(db, allMigrations)
return db
}
describe('session sandbox modes db', () => {
let db: Database
beforeEach(() => {
db = createTestDb()
})
afterEach(() => {
db.close()
})
it('returns null for a session with no stored row', () => {
expect(getSessionSandboxMode(db, 'ses_root')).toBeNull()
})
it('stores and reads back the sandbox flag with a default source', () => {
insertSessionSandboxModeIfAbsent(db, 'ses_root', { sandboxed: true, source: 'default', resources: null })
expect(getSessionSandboxMode(db, 'ses_root')).toMatchObject({
sandboxed: true,
source: 'default',
resources: null,
})
})
it('records the user source when the sandbox flag is set explicitly', () => {
setSessionSandboxed(db, 'ses_root', false)
expect(getSessionSandboxMode(db, 'ses_root')).toMatchObject({
sandboxed: false,
source: 'user',
resources: null,
})
})
it('inserts only when no row exists', () => {
insertSessionSandboxModeIfAbsent(db, 'ses_root', { sandboxed: true, source: 'default', resources: null })
insertSessionSandboxModeIfAbsent(db, 'ses_root', { sandboxed: false, source: 'user', resources: null })
expect(getSessionSandboxMode(db, 'ses_root')).toMatchObject({ sandboxed: true, source: 'default' })
})
it('round-trips resources and keeps toggled_at stable across resource updates', () => {
setSessionSandboxed(db, 'ses_root', true)
const toggledAt = getSessionSandboxMode(db, 'ses_root')?.toggledAt
setSessionSandboxResources(db, 'ses_root', { cpus: 4, memoryMib: 8192 }, true)
const row = getSessionSandboxMode(db, 'ses_root')
expect(row).toMatchObject({
sandboxed: true,
source: 'user',
resources: { cpus: 4, memoryMib: 8192 },
})
expect(row?.toggledAt).toBe(toggledAt)
setSessionSandboxResources(db, 'ses_root', { cpus: 8, memoryMib: 16384 }, true)
expect(getSessionSandboxMode(db, 'ses_root')).toMatchObject({
resources: { cpus: 8, memoryMib: 16384 },
toggledAt,
})
})
it('inserts a default-sourced row when resources are set before the flag', () => {
setSessionSandboxResources(db, 'ses_root', { cpus: 4, memoryMib: 8192 }, true)
expect(getSessionSandboxMode(db, 'ses_root')).toMatchObject({
sandboxed: true,
source: 'default',
resources: { cpus: 4, memoryMib: 8192 },
})
})
it('clears resources without changing the sandbox flag or source', () => {
setSessionSandboxed(db, 'ses_root', false)
setSessionSandboxResources(db, 'ses_root', { cpus: 4, memoryMib: 8192 }, false)
const toggledAt = getSessionSandboxMode(db, 'ses_root')?.toggledAt
setSessionSandboxResources(db, 'ses_root', null, false)
expect(getSessionSandboxMode(db, 'ses_root')).toMatchObject({
sandboxed: false,
source: 'user',
resources: null,
toggledAt,
})
})
it('updates toggled_at when the sandbox flag changes', () => {
setSessionSandboxed(db, 'ses_root', true)
const first = getSessionSandboxMode(db, 'ses_root')?.toggledAt ?? 0
setSessionSandboxed(db, 'ses_root', false)
const second = getSessionSandboxMode(db, 'ses_root')?.toggledAt ?? 0
expect(second).toBeGreaterThanOrEqual(first)
})
it('deletes a stored row', () => {
setSessionSandboxed(db, 'ses_root', true)
deleteSessionSandboxMode(db, 'ses_root')
expect(getSessionSandboxMode(db, 'ses_root')).toBeNull()
})
})
@@ -14,6 +14,7 @@ type InternalTestAppOverrides = Partial<{
sessionGoals: CreateInternalRoutesParams[8]
multiRuns: CreateInternalRoutesParams[9]
changeWalkthroughService: CreateInternalRoutesParams[10]
sessionSandbox: CreateInternalRoutesParams[11]
}>
export function createInternalTestApp(
@@ -32,5 +33,6 @@ export function createInternalTestApp(
overrides.sessionGoals ?? ({} as CreateInternalRoutesParams[8]),
overrides.multiRuns ?? ({} as CreateInternalRoutesParams[9]),
overrides.changeWalkthroughService ?? ({} as CreateInternalRoutesParams[10]),
overrides.sessionSandbox ?? ({} as CreateInternalRoutesParams[11]),
)
}
+64 -14
View File
@@ -18,6 +18,14 @@ export type ToolExecuteAfterEvent = {
status: 'completed' | 'error'
result?: ToolResult
error?: unknown
id?: string
[key: string]: unknown
}
export type GeneratedToolExecuteContext = {
signal: AbortSignal
sessionID?: string
id?: string
[key: string]: unknown
}
@@ -25,7 +33,7 @@ export type GeneratedTool = {
name: string
description?: string
input?: unknown
execute?: (input: unknown, context: { signal: AbortSignal; sessionID?: string }) => Promise<unknown>
execute?: (input: unknown, context: GeneratedToolExecuteContext) => Promise<unknown>
[key: string]: unknown
}
@@ -49,9 +57,9 @@ export type SessionContextEvent = {
sessionID: string
agent?: unknown
model?: unknown
system: Array<{ type: string; text: string; [key: string]: unknown }>
system?: Array<{ type: string; text: string; [key: string]: unknown }>
messages?: unknown
tools?: unknown
tools?: Record<string, { description: string; input?: unknown }>
options?: unknown
[key: string]: unknown
}
@@ -63,7 +71,13 @@ export type GeneratedPlugin = {
triggerPermissionEvaluate: (event: PermissionEvaluateEvent) => Promise<void>
triggerSessionPrompt: (event: SessionPromptEvent) => Promise<void>
triggerSessionContext: (event: SessionContextEvent) => Promise<void>
applyToolTransforms: (seed: GeneratedTool[]) => GeneratedTool[]
registeredTools: () => GeneratedTool[]
dispose: () => Promise<void>
}
export type LoadGeneratedPluginOptions = {
location?: { directory: string }
}
type ShellHookCallback = (event: ShellCreateBeforeEvent) => Promise<void> | void
@@ -72,11 +86,22 @@ type PermissionHookCallback = (event: PermissionEvaluateEvent) => Promise<void>
type SessionPromptHookCallback = (event: SessionPromptEvent) => Promise<void> | void
type SessionContextHookCallback = (event: SessionContextEvent) => Promise<void> | void
type SessionHookCallback = SessionPromptHookCallback | SessionContextHookCallback
type ToolTransformCallback = (editor: { add: (tool: GeneratedTool) => void }) => void
type ToolEditor = {
list: () => GeneratedTool[]
get: (id: string) => GeneratedTool | undefined
add: (tool: GeneratedTool) => void
update: (id: string, update: (tool: GeneratedTool) => void) => void
remove: (id: string) => void
namespace: () => void
}
type ToolTransformCallback = (editor: ToolEditor) => void
type Registration = { dispose: () => Promise<void> }
type PluginContext = {
location: { directory: string }
shell: {
hook: (name: string, callback: ShellHookCallback) => Promise<Registration>
}
@@ -92,6 +117,8 @@ type PluginContext = {
}
}
type PluginCleanup = () => Promise<void> | void
function createRegistry<Event>(name: string) {
const callbacks: Array<(event: Event) => Promise<void> | void> = []
return {
@@ -107,7 +134,7 @@ function createRegistry<Event>(name: string) {
}
/** Creates a test plugin context with hook registries, event triggers, and tool transforms. */
function createPluginContext() {
function createPluginContext(location: { directory: string }) {
const shellCreateBefore = createRegistry<ShellCreateBeforeEvent>('create.before')
const toolExecuteAfter = createRegistry<ToolExecuteAfterEvent>('execute.after')
const permissionEvaluate = createRegistry<PermissionEvaluateEvent>('evaluate')
@@ -116,6 +143,7 @@ function createPluginContext() {
const transforms: ToolTransformCallback[] = []
const context: PluginContext = {
location,
shell: {
hook: async (name, callback) => {
if (name !== 'create.before') throw new Error(`unexpected shell hook ${name}`)
@@ -148,6 +176,28 @@ function createPluginContext() {
},
}
const applyToolTransforms = (seed: GeneratedTool[]): GeneratedTool[] => {
const byName = new Map<string, GeneratedTool>()
for (const tool of seed) byName.set(tool.name, tool)
const editor: ToolEditor = {
list: () => [...byName.values()],
get: (id) => byName.get(id),
add: (tool) => {
byName.set(tool.name, tool)
},
update: (id, update) => {
const tool = byName.get(id)
if (tool) update(tool)
},
remove: (id) => {
byName.delete(id)
},
namespace: () => undefined,
}
for (const transform of transforms) transform(editor)
return [...byName.values()]
}
return {
context,
triggerShellCreateBefore: (event: ShellCreateBeforeEvent) => shellCreateBefore.trigger(event),
@@ -157,19 +207,15 @@ function createPluginContext() {
triggerSessionPrompt: (event: SessionPromptEvent) => sessionPrompt.trigger(event),
/** Dispatches a context event so registered callbacks can update it. */
triggerSessionContext: (event: SessionContextEvent) => sessionContext.trigger(event),
registeredTools: () => {
const tools: GeneratedTool[] = []
const editor = { add: (tool: GeneratedTool) => tools.push(tool) }
for (const transform of transforms) transform(editor)
return tools
},
applyToolTransforms,
registeredTools: () => applyToolTransforms([]),
}
}
let importCount = 0
/** Imports a fresh plugin instance, validates its definition, and runs setup in the test context. */
export async function loadGeneratedPlugin(file: string): Promise<GeneratedPlugin> {
export async function loadGeneratedPlugin(file: string, options: LoadGeneratedPluginOptions = {}): Promise<GeneratedPlugin> {
importCount += 1
const imported = (await import(`${pathToFileURL(file).href}?ocm-test=${importCount}`)) as { default?: unknown }
const definition = imported.default
@@ -185,8 +231,8 @@ export async function loadGeneratedPlugin(file: string): Promise<GeneratedPlugin
throw new Error(`${file} must default-export a setup function`)
}
const registrations = createPluginContext()
await (setup as (context: PluginContext) => Promise<void> | void)(registrations.context)
const registrations = createPluginContext({ directory: options.location?.directory ?? process.cwd() })
const cleanup = (await (setup as (context: PluginContext) => Promise<PluginCleanup | void> | PluginCleanup | void)(registrations.context)) as PluginCleanup | void
return {
id,
triggerShellCreateBefore: registrations.triggerShellCreateBefore,
@@ -194,6 +240,10 @@ export async function loadGeneratedPlugin(file: string): Promise<GeneratedPlugin
triggerPermissionEvaluate: registrations.triggerPermissionEvaluate,
triggerSessionPrompt: registrations.triggerSessionPrompt,
triggerSessionContext: registrations.triggerSessionContext,
applyToolTransforms: registrations.applyToolTransforms,
registeredTools: registrations.registeredTools,
dispose: async () => {
if (typeof cleanup === 'function') await cleanup()
},
}
}
+2 -2
View File
@@ -70,9 +70,9 @@ vi.mock('../src/services/schedules', () => ({
vi.mock('../src/services/sandbox/runtime', () => ({
SandboxRuntimeService: vi.fn().mockImplementation(() => ({
prepareWorkspaceSandboxOnBoot: vi.fn().mockResolvedValue(undefined),
prepareSandboxOnBoot: vi.fn().mockResolvedValue(undefined),
})),
stopWorkspaceSandboxOnShutdown: vi.fn().mockResolvedValue(undefined),
stopSandboxesOnShutdown: vi.fn().mockResolvedValue(undefined),
}))
const ipcServerMock = vi.hoisted(() => ({
+137 -20
View File
@@ -9,18 +9,37 @@ import { getOrCreateInternalToken } from '../../src/services/internal-token'
import { migrate } from '../../src/db/migration-runner'
import {
buildCanonicalSandboxSpec,
parseMemoryMib,
resolveExpectedSandboxNetworkPolicy,
resolveSandboxRuntimeTmpfsSizeMib,
WORKSPACE_SANDBOX_NAME,
sessionSandboxName,
type SandboxVmSpec,
} from '../../src/services/sandbox/command'
import { executeCommand } from '../../src/utils/process'
import { detectSandboxCapability } from '../../src/services/sandbox/capability'
import { forceProcessAttestation } from '../../src/services/opencode/process-identity'
import { SessionAncestry } from '../../src/services/session-ancestry'
import { SessionSandboxService } from '../../src/services/session-sandbox'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import { getReposPath, ENV } from '@opencode-manager/shared/config/env'
import { createInternalTestApp } from '../helpers/internal-test-app'
const ROOT_SESSION_ID = 'ses_root'
const VM_NAME = sessionSandboxName(ROOT_SESSION_ID)
const REPO_DIR = path.join(getReposPath(), 'sandbox-route-test')
function vmSpec(): SandboxVmSpec {
return {
name: VM_NAME,
rootSessionId: ROOT_SESSION_ID,
projectMounts: [REPO_DIR],
cpus: ENV.SANDBOX.CPUS,
memoryMib: parseMemoryMib(ENV.SANDBOX.MEMORY) ?? 0,
}
}
function trustedRunningInspect(): { exitCode: number; stdout: string; stderr: string } {
const canonical = buildCanonicalSandboxSpec()
const canonical = buildCanonicalSandboxSpec(vmSpec())
const { memory_mib: memoryMib } = canonical.resources as { memory_mib: number }
const config = {
...canonical,
@@ -42,7 +61,7 @@ function trustedRunningInspect(): { exitCode: number; stdout: string; stderr: st
return {
exitCode: 0,
stdout: JSON.stringify({
name: WORKSPACE_SANDBOX_NAME,
name: VM_NAME,
status: 'Running',
config,
created_at: '2026-08-12T00:00:00Z',
@@ -74,7 +93,6 @@ describe('internal sandbox routes', () => {
let settingsService: SettingsService
let app: Hono
let token: string
let repoDir: string
beforeEach(() => {
mockExecuteCommand.mockClear()
@@ -84,17 +102,22 @@ describe('internal sandbox routes', () => {
db = new Database(':memory:')
migrate(db, allMigrations)
settingsService = new SettingsService(db)
const ancestryClient = {
api: { session: { get: async () => ({ parentID: null }) } },
} as unknown as OpenCodeClient
const sessionSandbox = new SessionSandboxService(db, new SessionAncestry(ancestryClient), settingsService, {
removeSessionSandbox: async () => undefined,
})
app = new Hono()
app.route('/api/internal', createInternalTestApp(db))
app.route('/api/internal', createInternalTestApp(db, { sessionSandbox }))
token = getOrCreateInternalToken(db)
repoDir = path.join(getReposPath(), 'sandbox-route-test')
mkdirSync(repoDir, { recursive: true })
mkdirSync(REPO_DIR, { recursive: true })
})
afterEach(() => {
forceProcessAttestation(null)
db.close()
rmSync(repoDir, { recursive: true, force: true })
rmSync(REPO_DIR, { recursive: true, force: true })
})
function postShell(body: unknown, auth = true) {
@@ -108,34 +131,61 @@ describe('internal sandbox routes', () => {
})
}
function shellBody(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return { directory: REPO_DIR, sessionId: ROOT_SESSION_ID, locationDirectory: REPO_DIR, ...overrides }
}
function getSessionSandbox(sessionId: string, auth = true) {
return app.request(`/api/internal/sandbox/sessions/${sessionId}`, {
headers: {
...(auth ? { authorization: `Bearer ${token}` } : {}),
},
})
}
it('POST /shell returns 401 without bearer token', async () => {
const res = await postShell({ directory: repoDir }, false)
const res = await postShell(shellBody(), false)
expect(res.status).toBe(401)
})
it('POST /shell returns host mode when the sandbox preference is off', async () => {
const res = await postShell({ directory: repoDir })
const res = await postShell(shellBody())
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ mode: 'host' })
expect(mockExecuteCommand).not.toHaveBeenCalled()
})
it('POST /shell returns the mapped sandbox working directory when enforcement is on', async () => {
it('POST /shell returns the named sandbox plan when enforcement is on', async () => {
settingsService.updateSettings({ sandbox: { enabled: true } })
const res = await postShell({ directory: repoDir })
const res = await postShell(shellBody())
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
mode: 'sandbox',
workdir: repoDir,
name: VM_NAME,
workdir: REPO_DIR,
})
})
it('POST /shell returns 400 for a malformed body', async () => {
const res = await postShell({ directory: '' })
const res = await postShell(shellBody({ directory: '' }))
expect(res.status).toBe(400)
expect(await res.json()).toEqual({ error: 'Invalid request' })
})
it('POST /shell returns 400 when sessionId is missing', async () => {
const res = await postShell({ directory: REPO_DIR, locationDirectory: REPO_DIR })
expect(res.status).toBe(400)
expect(await res.json()).toEqual({ error: 'Invalid request' })
})
it('POST /shell returns 400 when locationDirectory is missing', async () => {
const res = await postShell({ directory: REPO_DIR, sessionId: ROOT_SESSION_ID })
expect(res.status).toBe(400)
expect(await res.json()).toEqual({ error: 'Invalid request' })
@@ -145,7 +195,7 @@ describe('internal sandbox routes', () => {
settingsService.updateSettings({ sandbox: { enabled: true } })
mockDetectSandboxCapability.mockReturnValue({ available: false, reason: '/dev/kvm is not available' })
const res = await postShell({ directory: repoDir })
const res = await postShell(shellBody())
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ mode: 'blocked', reason: '/dev/kvm is not available' })
@@ -153,21 +203,88 @@ describe('internal sandbox routes', () => {
})
it('POST /shell never returns host mode for an enforced request even when the preference is off', async () => {
const res = await postShell({ directory: repoDir, enforced: true })
const res = await postShell(shellBody({ enforced: true }))
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
mode: 'sandbox',
workdir: repoDir,
name: VM_NAME,
workdir: REPO_DIR,
})
})
it('POST /shell blocks an enforced request for a directory outside the project roots', async () => {
const res = await postShell({ directory: '/etc', enforced: true })
it('POST /shell blocks an enforced request for a directory outside the session mounts', async () => {
const res = await postShell(shellBody({ directory: '/etc', enforced: true }))
expect(res.status).toBe(200)
const body = (await res.json()) as { mode: string; reason?: string }
expect(body.mode).toBe('blocked')
expect(String(body.reason)).toContain('outside the sandboxed project roots')
expect(String(body.reason)).toContain("outside this session's sandbox")
})
it('POST /shell returns a blocked plan when the session target cannot be resolved', async () => {
const failingApp = new Hono()
failingApp.route(
'/api/internal',
createInternalTestApp(db, {
sessionSandbox: {
resolveShellTarget: async () => {
throw new Error('session ancestry unavailable')
},
} as unknown as SessionSandboxService,
}),
)
const res = await failingApp.request('/api/internal/sandbox/shell', {
method: 'POST',
body: JSON.stringify(shellBody({ enforced: true })),
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
})
expect(res.status).toBe(500)
expect(await res.json()).toEqual({ mode: 'blocked', reason: 'session ancestry unavailable' })
})
it('GET /sessions/:sessionId returns 401 without bearer token', async () => {
const res = await getSessionSandbox('ses_root', false)
expect(res.status).toBe(401)
})
it('GET /sessions/:sessionId reports unsandboxed when the sandbox preference is off', async () => {
const res = await getSessionSandbox('ses_root')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ sandboxed: false, source: 'default', since: 0 })
})
it('GET /sessions/:sessionId reports sandboxed when the sandbox preference is on', async () => {
settingsService.updateSettings({ sandbox: { enabled: true } })
const res = await getSessionSandbox('ses_root')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ sandboxed: true, source: 'default', since: 0 })
})
it('GET /sessions/:sessionId returns 500 with an error when the service fails', async () => {
const failingApp = new Hono()
failingApp.route(
'/api/internal',
createInternalTestApp(db, {
sessionSandbox: {
getClaim: async () => {
throw new Error('lookup failed')
},
} as unknown as SessionSandboxService,
}),
)
const res = await failingApp.request('/api/internal/sandbox/sessions/ses_root', {
headers: { authorization: `Bearer ${token}` },
})
expect(res.status).toBe(500)
expect(await res.json()).toEqual({ error: 'lookup failed' })
})
})
@@ -5,12 +5,14 @@ import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { SettingsService } from '../../src/services/settings'
import { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { SessionAncestry } from '../../src/services/session-ancestry'
import { createSessionPermissionModeRoutes } from '../../src/routes/session-permission-modes'
import { createFakeSessionPermissionClient } from '../helpers/fake-session-permission-client'
function createTestApp(db: Database, parents: Record<string, string | null> = {}): Hono {
const app = new Hono()
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient({ parents }), new SettingsService(db))
const client = createFakeSessionPermissionClient({ parents })
const service = new SessionPermissionModeService(db, client, new SettingsService(db), new SessionAncestry(client))
app.route('/session-permission-modes', createSessionPermissionModeRoutes(service))
return app
}
+204
View File
@@ -0,0 +1,204 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import os from 'os'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { ENV } from '@opencode-manager/shared/config/env'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { SettingsService } from '../../src/services/settings'
import { SessionAncestry } from '../../src/services/session-ancestry'
import { SessionSandboxService } from '../../src/services/session-sandbox'
import { parseMemoryMib } from '../../src/services/sandbox/command'
import { createSessionSandboxRoutes } from '../../src/routes/session-sandbox'
import { createFakeSessionPermissionClient } from '../helpers/fake-session-permission-client'
const ENV_RESOURCES = { cpus: ENV.SANDBOX.CPUS, memoryMib: parseMemoryMib(ENV.SANDBOX.MEMORY) ?? 0 }
function createTestDb(): Database {
const db = new Database(':memory:')
migrate(db, allMigrations)
return db
}
function createTestApp(
db: Database,
options: { parents?: Record<string, string | null>; sandboxEnabled?: boolean } = {},
): Hono {
const settingsService = new SettingsService(db)
if (options.sandboxEnabled) {
settingsService.updateSettings({ sandbox: { enabled: true } })
}
const client = createFakeSessionPermissionClient({ parents: options.parents ?? {} })
const service = new SessionSandboxService(db, new SessionAncestry(client), settingsService, {
removeSessionSandbox: async () => undefined,
})
const app = new Hono()
app.route('/session-sandbox', createSessionSandboxRoutes(service))
return app
}
describe('session sandbox routes', () => {
let db: Database
beforeEach(() => {
db = createTestDb()
})
afterEach(() => {
db.close()
})
it('GET reports unavailable and unsandboxed when server support is disabled', async () => {
const app = createTestApp(db)
const res = await app.request('/session-sandbox/ses_root')
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({
sessionId: 'ses_root',
rootSessionId: 'ses_root',
sandboxed: false,
source: 'default',
resources: null,
effectiveResources: ENV_RESOURCES,
lockedReason: null,
available: false,
})
})
it('GET reports the default sandboxed value when server support is enabled', async () => {
const app = createTestApp(db, { sandboxEnabled: true })
const res = await app.request('/session-sandbox/ses_root')
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({
sessionId: 'ses_root',
rootSessionId: 'ses_root',
sandboxed: true,
source: 'default',
resources: null,
effectiveResources: ENV_RESOURCES,
lockedReason: null,
available: true,
})
})
it('GET reports the child lock reason for a child session', async () => {
const app = createTestApp(db, { parents: { ses_child: 'ses_root', ses_root: null }, sandboxEnabled: true })
const res = await app.request('/session-sandbox/ses_child')
expect(res.status).toBe(200)
await expect(res.json()).resolves.toMatchObject({
sessionId: 'ses_child',
rootSessionId: 'ses_root',
sandboxed: true,
lockedReason: 'child',
available: true,
})
})
it('PUT stores a value and GET reads it back', async () => {
const app = createTestApp(db, { sandboxEnabled: true })
const putRes = await app.request('/session-sandbox/ses_root', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sandboxed: false }),
})
expect(putRes.status).toBe(200)
await expect(putRes.json()).resolves.toMatchObject({
sessionId: 'ses_root',
rootSessionId: 'ses_root',
sandboxed: false,
source: 'user',
available: true,
})
const getRes = await app.request('/session-sandbox/ses_root')
const body = (await getRes.json()) as { sandboxed: boolean }
expect(body.sandboxed).toBe(false)
})
it('PUT stores a resource override and GET reports it', async () => {
const app = createTestApp(db, { sandboxEnabled: true })
const putRes = await app.request('/session-sandbox/ses_root', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ resources: { cpus: 4, memoryMib: 8192 } }),
})
expect(putRes.status).toBe(200)
await expect(putRes.json()).resolves.toMatchObject({
resources: { cpus: 4, memoryMib: 8192 },
effectiveResources: { cpus: 4, memoryMib: 8192 },
})
})
it('PUT rejects a resource override above the host limit with 400', async () => {
const app = createTestApp(db, { sandboxEnabled: true })
const res = await app.request('/session-sandbox/ses_root', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ resources: { cpus: os.availableParallelism() + 1, memoryMib: 1024 } }),
})
expect(res.status).toBe(400)
await expect(res.json()).resolves.toMatchObject({ error: expect.any(String) })
})
it('PUT rejects a body without sandboxed or resources with 400', async () => {
const app = createTestApp(db, { sandboxEnabled: true })
const res = await app.request('/session-sandbox/ses_root', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
})
expect(res.status).toBe(400)
})
it('PUT rejects an invalid body with 400', async () => {
const app = createTestApp(db)
const res = await app.request('/session-sandbox/ses_root', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sandboxed: 'yes' }),
})
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({ error: expect.any(String), details: expect.any(Array) })
})
it('PUT rejects malformed JSON with 400', async () => {
const app = createTestApp(db)
const res = await app.request('/session-sandbox/ses_root', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: '{not json',
})
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({ error: 'Invalid JSON' })
})
it('PUT rejects setting the sandbox flag of a child session with 400', async () => {
const app = createTestApp(db, { parents: { ses_child: 'ses_root', ses_root: null }, sandboxEnabled: true })
const res = await app.request('/session-sandbox/ses_child', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sandboxed: false }),
})
expect(res.status).toBe(400)
})
it('PUT rejects enabling sandboxing with 409 when server support is disabled', async () => {
const app = createTestApp(db)
const res = await app.request('/session-sandbox/ses_root', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sandboxed: true }),
})
expect(res.status).toBe(409)
})
})
+77
View File
@@ -283,6 +283,14 @@ vi.mock('../../src/services/sandbox/capability', () => ({
resetSandboxCapabilityCache: vi.fn(),
}))
const resourcesMock = vi.hoisted(() => ({
sandboxResourceLimitError: vi.fn(),
}))
vi.mock('../../src/services/sandbox/resources', () => ({
sandboxResourceLimitError: resourcesMock.sandboxResourceLimitError,
}))
vi.mock('@opencode-manager/shared/config/env', () => ({
getWorkspacePath: vi.fn(() => '/tmp/test-workspace'),
getReposPath: vi.fn(() => '/tmp/test-repos'),
@@ -363,6 +371,8 @@ describe('Settings Routes - OpenCode Upgrade', () => {
mockSyncManagerGitIdentityConfig.mockResolvedValue({ identity: null, error: null })
mockDetectSandboxCapability.mockReset()
mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 1.0.0' })
resourcesMock.sandboxResourceLimitError.mockReset()
resourcesMock.sandboxResourceLimitError.mockReturnValue(null)
mockInstallOpenCodeVersion.mockReset()
mockInstallOpenCodeVersion.mockResolvedValue('/home/node/.opencode/bin/opencode')
clearOpenCodeVersionCache()
@@ -1378,6 +1388,27 @@ describe('Settings Routes - OpenCode Upgrade', () => {
expect(opencodeServerManager.markRestartPending).not.toHaveBeenCalled()
})
it('does not mark the OpenCode server restart pending when only sandbox.defaultForNewSessions changes', async () => {
mockGetSettings.mockReturnValue({
preferences: { sandbox: { enabled: true, defaultForNewSessions: true } },
updatedAt: 1,
})
mockUpdateSettings.mockReturnValue({
preferences: { sandbox: { enabled: true, defaultForNewSessions: false } },
updatedAt: 2,
})
const req = new Request('http://localhost/', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ preferences: { sandbox: { enabled: true, defaultForNewSessions: false } } }),
})
const res = await settingsApp.fetch(req)
expect(res.status).toBe(200)
expect(opencodeServerManager.markRestartPending).not.toHaveBeenCalled()
})
it('does not mark the OpenCode server restart pending when sandbox is absent from the patch', async () => {
mockGetSettings.mockReturnValue({
preferences: { sandbox: { enabled: true } },
@@ -1588,6 +1619,52 @@ describe('Settings Routes - OpenCode Upgrade', () => {
})
})
describe('PATCH / - sandbox resource host limits', () => {
it('rejects sandbox resources above the host limit with 400 and does not persist settings', async () => {
resourcesMock.sandboxResourceLimitError.mockReturnValue('Requested 8 CPUs exceeds the host limit of 4')
mockGetSettings.mockReturnValue({
preferences: { sandbox: { enabled: true } },
updatedAt: 1,
})
const req = new Request('http://localhost/', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ preferences: { sandbox: { enabled: true, cpus: 8, memoryMib: 4096 } } }),
})
const res = await settingsApp.fetch(req)
const json = await res.json() as { error: string }
expect(res.status).toBe(400)
expect(json.error).toBe('Requested 8 CPUs exceeds the host limit of 4')
expect(resourcesMock.sandboxResourceLimitError).toHaveBeenCalledWith(
expect.objectContaining({ cpus: 8, memoryMib: 4096 }),
)
expect(mockUpdateSettings).not.toHaveBeenCalled()
})
it('accepts sandbox resources within the host limit', async () => {
mockGetSettings.mockReturnValue({
preferences: { sandbox: { enabled: true } },
updatedAt: 1,
})
mockUpdateSettings.mockReturnValue({
preferences: { sandbox: { enabled: true, cpus: 4, memoryMib: 8192 } },
updatedAt: 2,
})
const req = new Request('http://localhost/', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ preferences: { sandbox: { enabled: true, cpus: 4, memoryMib: 8192 } } }),
})
const res = await settingsApp.fetch(req)
expect(res.status).toBe(200)
expect(mockUpdateSettings).toHaveBeenCalledWith({ sandbox: { enabled: true, cpus: 4, memoryMib: 8192 } }, 'default')
})
})
describe('DELETE / - sandbox preference restart pending', () => {
it('marks the OpenCode server restart pending when resetting disables sandboxing', async () => {
mockGetSettings.mockReturnValue({
+3 -1
View File
@@ -12,6 +12,7 @@ import { MultiRunError, MultiRunService } from '../../src/services/multi-runs'
import { RepoWorkspaceError } from '../../src/services/repo'
import type { RepoWorkspaceService } from '../../src/services/repo-workspace'
import { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { SessionAncestry } from '../../src/services/session-ancestry'
import { SettingsService } from '../../src/services/settings'
import type { Repo } from '../../src/types/repo'
import type { OpenCodeClient } from '../../src/services/opencode/client'
@@ -222,6 +223,7 @@ describe('MultiRunService', () => {
db,
client,
new SettingsService(db),
new SessionAncestry(client),
),
): MultiRunService {
return new MultiRunService(db, client, repoWorkspaces, permissionModes)
@@ -706,7 +708,7 @@ describe('MultiRunService', () => {
const repoWorkspaces = createRepoWorkspaces()
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } })
const permissionModes = new SessionPermissionModeService(db, client, settingsService)
const permissionModes = new SessionPermissionModeService(db, client, settingsService, new SessionAncestry(client))
const service = createService(client, repoWorkspaces.service, permissionModes)
const run = await service.launch({
File diff suppressed because it is too large. Load diff
@@ -120,15 +120,15 @@ vi.mock('../../src/services/opencode-home', () => ({
const sandboxRuntimeServiceMock = vi.hoisted(() => ({
SandboxRuntimeService: vi.fn<() => {
isEnabled: () => boolean
stopWorkspaceSandboxForToggle?: () => Promise<void>
prepareWorkspaceSandboxOnBoot?: () => Promise<void>
stopAllSandboxesForToggle?: () => Promise<void>
prepareSandboxOnBoot?: () => Promise<void>
}>(() => ({ isEnabled: () => false })),
}))
vi.mock('../../src/services/sandbox/runtime', () => ({
SandboxRuntimeService: function SandboxRuntimeServiceStub() {
return {
prepareWorkspaceSandboxOnBoot: async () => undefined,
prepareSandboxOnBoot: async () => undefined,
...sandboxRuntimeServiceMock.SandboxRuntimeService(),
}
},
@@ -1097,10 +1097,10 @@ describe('OpenCodeServerManager - server auth', () => {
}, 15000)
it('stops the workspace sandbox when a restart disables enforcement', async () => {
const stopWorkspaceSandboxForToggle = vi.fn().mockResolvedValue(undefined)
const stopAllSandboxesForToggle = vi.fn().mockResolvedValue(undefined)
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => false,
stopWorkspaceSandboxForToggle,
stopAllSandboxesForToggle,
}))
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
@@ -1109,7 +1109,7 @@ describe('OpenCodeServerManager - server auth', () => {
await manager.start()
expect(stopWorkspaceSandboxForToggle).toHaveBeenCalledTimes(1)
expect(stopAllSandboxesForToggle).toHaveBeenCalledTimes(1)
expect(spawnMock).toHaveBeenCalledWith(
'opencode',
expect.any(Array),
@@ -1122,10 +1122,10 @@ describe('OpenCodeServerManager - server auth', () => {
})
it('does not stop the workspace sandbox when the restarted server stays enforced', async () => {
const stopWorkspaceSandboxForToggle = vi.fn().mockResolvedValue(undefined)
const stopAllSandboxesForToggle = vi.fn().mockResolvedValue(undefined)
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => true,
stopWorkspaceSandboxForToggle,
stopAllSandboxesForToggle,
}))
execSyncMock.mockImplementation((cmd: string) => {
if (cmd.includes('lsof')) return spawnMock.mock.calls.length > 0 ? '1234\n' : ''
@@ -1139,7 +1139,7 @@ describe('OpenCodeServerManager - server auth', () => {
await manager.start()
expect(stopWorkspaceSandboxForToggle).not.toHaveBeenCalled()
expect(stopAllSandboxesForToggle).not.toHaveBeenCalled()
expect(spawnMock).toHaveBeenCalledWith(
'opencode',
expect.any(Array),
@@ -1154,7 +1154,7 @@ describe('OpenCodeServerManager - server auth', () => {
it('aborts the disabled restart when the workspace sandbox cannot be stopped', async () => {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => false,
stopWorkspaceSandboxForToggle: vi.fn().mockRejectedValue(new Error('msb stop failed; the managed microVM is still running')),
stopAllSandboxesForToggle: vi.fn().mockRejectedValue(new Error('msb stop failed; the managed microVM is still running')),
}))
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
+421 -39
View File
@@ -6,32 +6,56 @@ import path from 'node:path'
import { ENV, getAssistantOpenCodeDir, getForgeWorktreesPath, getOpenCodeAgentTmpPath, getOpenCodeGlobalSkillsPath, getOpenCodeToolOutputPath, getOpenCodeWorktreesPath, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils'
import {
WORKSPACE_SANDBOX_NAME,
SESSION_SANDBOX_NAME_PATTERN,
SANDBOX_UNAVAILABLE_PREFIX,
SANDBOX_DOCKER_DATA_VOLUME_NAME,
SANDBOX_DOCKER_DATA_GUEST_PATH,
SANDBOX_DOCKER_DATA_SIZE,
buildCanonicalSandboxSpec,
buildSandboxCreateArgs,
buildSandboxInspectArgs,
buildSandboxListArgs,
buildSandboxPingArgs,
buildSandboxProvisionArgs,
buildSandboxPullArgs,
buildSandboxRemoveArgs,
buildSandboxStartArgs,
buildSandboxStopArgs,
buildSandboxStopManagedArgs,
buildSandboxVerifyProvisionArgs,
buildSandboxVersionArgs,
buildSandboxVolumeRemoveArgs,
parseMemoryMib,
quoteForShell,
resolveExpectedSandboxNetworkPolicy,
resolveSandboxExecUser,
resolveSandboxExecUserGid,
resolveSandboxExecUserUid,
resolveSandboxRuntimeTmpfsSizeMib,
resolveSessionSandboxMounts,
sandboxDockerDataVolumeName,
sandboxMountRoots,
sandboxNetworkPolicyMismatch,
sandboxVmMountRoots,
sessionSandboxName,
type SandboxVmSpec,
} from '../../../src/services/sandbox/command'
import { isPathWithinRoot } from '../../../src/utils/fs-safe'
const ROOT_SESSION_ID = 'ses_root'
const VM_NAME = sessionSandboxName(ROOT_SESSION_ID)
const DOCKER_DATA_VOLUME = sandboxDockerDataVolumeName(VM_NAME)
function vmSpec(overrides: Partial<SandboxVmSpec> = {}): SandboxVmSpec {
return {
name: VM_NAME,
rootSessionId: ROOT_SESSION_ID,
projectMounts: [getReposPath()],
cpus: ENV.SANDBOX.CPUS,
memoryMib: parseMemoryMib(ENV.SANDBOX.MEMORY) ?? 0,
...overrides,
}
}
afterEach(() => {
vi.restoreAllMocks()
})
@@ -45,20 +69,44 @@ describe('sandbox command builders', () => {
expect(buildSandboxPullArgs()).toEqual(['pull', ENV.SANDBOX.IMAGE])
})
it('builds inspect args targeting the shared workspace sandbox with JSON output', () => {
expect(buildSandboxInspectArgs()).toEqual(['inspect', WORKSPACE_SANDBOX_NAME, '--format', 'json'])
it('derives a stable, pattern-matching sandbox name from a root session id', () => {
expect(VM_NAME).toMatch(SESSION_SANDBOX_NAME_PATTERN)
expect(sessionSandboxName(ROOT_SESSION_ID)).toBe(VM_NAME)
expect(sessionSandboxName('ses_other')).not.toBe(VM_NAME)
expect(sessionSandboxName('ses_other')).toMatch(SESSION_SANDBOX_NAME_PATTERN)
expect(SESSION_SANDBOX_NAME_PATTERN.test('ocm-workspace')).toBe(false)
expect(SESSION_SANDBOX_NAME_PATTERN.test(`ocm-session-${'a'.repeat(11)}`)).toBe(false)
expect(SESSION_SANDBOX_NAME_PATTERN.test(`ocm-session-${'a'.repeat(13)}`)).toBe(false)
expect(SESSION_SANDBOX_NAME_PATTERN.test(`ocm-session-${'g'.repeat(12)}`)).toBe(false)
expect(sandboxDockerDataVolumeName(VM_NAME)).toBe(`${VM_NAME}-docker-data`)
})
it('builds remove args that force-remove the shared workspace sandbox', () => {
expect(buildSandboxRemoveArgs()).toEqual(['rm', '--force', WORKSPACE_SANDBOX_NAME])
it('builds ping args targeting the named sandbox with quiet output', () => {
expect(buildSandboxPingArgs(VM_NAME)).toEqual(['ping', VM_NAME, '-q'])
})
it('builds inspect args targeting the named sandbox with JSON output', () => {
expect(buildSandboxInspectArgs(VM_NAME)).toEqual(['inspect', VM_NAME, '--format', 'json'])
})
it('builds remove args that force-remove the named sandbox', () => {
expect(buildSandboxRemoveArgs(VM_NAME)).toEqual(['rm', '--force', VM_NAME])
})
it('builds list args that emit machine-readable JSON for all sandboxes', () => {
expect(buildSandboxListArgs()).toEqual(['ls', '--format', 'json'])
})
it('builds start args targeting the shared workspace sandbox', () => {
expect(buildSandboxStartArgs()).toEqual(['start', WORKSPACE_SANDBOX_NAME])
it('builds start args targeting the named sandbox', () => {
expect(buildSandboxStartArgs(VM_NAME)).toEqual(['start', VM_NAME])
})
it('builds stop args targeting the named sandbox', () => {
expect(buildSandboxStopArgs(VM_NAME)).toEqual(['stop', VM_NAME])
})
it('builds volume removal args for the named Docker data volume', () => {
expect(buildSandboxVolumeRemoveArgs(DOCKER_DATA_VOLUME)).toEqual(['volume', 'rm', DOCKER_DATA_VOLUME])
})
it('builds managed-stop args that filter by the ocm.managed label', () => {
@@ -74,15 +122,17 @@ describe('sandbox command builders', () => {
expect(result.stdout).toBe(value)
})
it('builds create args with exactly five identical-path bind mounts and the detached flag', () => {
const args = buildSandboxCreateArgs()
it('builds create args for the VM spec with named mounts, resources, labels, and the project workdir', () => {
const args = buildSandboxCreateArgs(vmSpec())
expect(args[0]).toBe('run')
expect(args).toContain('-d')
expect(args).toContain('--name')
expect(args[args.indexOf('--name') + 1]).toBe(WORKSPACE_SANDBOX_NAME)
expect(args[args.indexOf('--name') + 1]).toBe(VM_NAME)
expect(args[args.indexOf('-w') + 1]).toBe(getReposPath())
expect(args[args.indexOf('-u') + 1]).toBe(resolveSandboxExecUser())
expect(args[args.indexOf('-m') + 1]).toBe(`${parseMemoryMib(ENV.SANDBOX.MEMORY)}M`)
expect(args[args.indexOf('-c') + 1]).toBe(String(ENV.SANDBOX.CPUS))
const labelArgs: string[] = []
for (let i = 0; i < args.length; i++) {
@@ -93,6 +143,7 @@ describe('sandbox command builders', () => {
}
expect(labelArgs).toContain('ocm.managed=true')
expect(labelArgs).toContain(`ocm.net=${ENV.SANDBOX.NET}`)
expect(labelArgs).toContain(`ocm.session=${ROOT_SESSION_ID}`)
const mountArgs: string[] = []
for (let i = 0; i < args.length; i++) {
@@ -101,35 +152,81 @@ describe('sandbox command builders', () => {
mountArgs.push(value)
}
}
expect(mountArgs).toEqual(sandboxMountRoots().map((root) => `${root}:${root}`))
expect(mountArgs).toEqual(sandboxVmMountRoots(vmSpec()).map((root) => `${root}:${root}`))
expect(mountArgs[0]).toBe(`${getReposPath()}:${getReposPath()}`)
expect(mountArgs[1]).toBe(`${getScheduleWorktreesPath()}:${getScheduleWorktreesPath()}`)
expect(mountArgs[2]).toBe(`${getOpenCodeWorktreesPath()}:${getOpenCodeWorktreesPath()}`)
expect(mountArgs[3]).toBe(`${getForgeWorktreesPath()}:${getForgeWorktreesPath()}`)
expect(mountArgs[4]).toBe(`${getOpenCodeToolOutputPath()}:${getOpenCodeToolOutputPath()}`)
expect(mountArgs[5]).toBe(`${getOpenCodeGlobalSkillsPath()}:${getOpenCodeGlobalSkillsPath()}`)
expect(mountArgs[6]).toBe(`${getOpenCodeAgentTmpPath()}:${getOpenCodeAgentTmpPath()}`)
expect(mountArgs).toEqual([
`${getReposPath()}:${getReposPath()}`,
`${getOpenCodeToolOutputPath()}:${getOpenCodeToolOutputPath()}`,
`${getOpenCodeGlobalSkillsPath()}:${getOpenCodeGlobalSkillsPath()}`,
`${getOpenCodeAgentTmpPath()}:${getOpenCodeAgentTmpPath()}`,
])
})
it('explicitly creates the runtime tmpfs required by attestation', () => {
const args = buildSandboxCreateArgs()
const spec = buildCanonicalSandboxSpec()
const resources = spec.resources as { memory_mib: number }
it('mounts an explicit project mount list without duplicating the shared directories', () => {
const spec = vmSpec({ projectMounts: [getScheduleWorktreesPath(), getOpenCodeToolOutputPath()] })
expect(sandboxVmMountRoots(spec)).toEqual([
getScheduleWorktreesPath(),
getOpenCodeToolOutputPath(),
getOpenCodeGlobalSkillsPath(),
getOpenCodeAgentTmpPath(),
])
expect(buildSandboxCreateArgs(spec)[buildSandboxCreateArgs(spec).indexOf('-w') + 1]).toBe(getScheduleWorktreesPath())
})
it('sizes the runtime tmpfs from the spec memory and creates the Docker data disk for the VM', () => {
const spec = vmSpec()
const args = buildSandboxCreateArgs(spec)
const canonical = buildCanonicalSandboxSpec(spec)
const resources = canonical.resources as { memory_mib: number }
expect(args[args.indexOf('--tmpfs') + 1]).toBe(`/tmp:${resolveSandboxRuntimeTmpfsSizeMib(resources.memory_mib)}M`)
})
it('attaches the persistent Docker data disk with the tested mount-named specification', () => {
const args = buildSandboxCreateArgs()
const mountNamedIndex = args.indexOf('--mount-named')
expect(mountNamedIndex).toBeGreaterThan(-1)
expect(args[mountNamedIndex + 1]).toBe(
`${SANDBOX_DOCKER_DATA_VOLUME_NAME}:${SANDBOX_DOCKER_DATA_GUEST_PATH}:kind=disk,size=${SANDBOX_DOCKER_DATA_SIZE}`,
`${DOCKER_DATA_VOLUME}:${SANDBOX_DOCKER_DATA_GUEST_PATH}:kind=disk,size=${SANDBOX_DOCKER_DATA_SIZE}`,
)
})
it('sizes the runtime tmpfs from the VM memory rather than the environment default', () => {
const args = buildSandboxCreateArgs(vmSpec({ memoryMib: 2048 }))
expect(args[args.indexOf('--tmpfs') + 1]).toBe('/tmp:512M')
})
it('rejects a VM spec without a project mount', () => {
expect(() => buildSandboxCreateArgs(vmSpec({ projectMounts: [] }))).toThrow('at least one project mount')
})
it('inserts --replace immediately after -d before the image and never after --', () => {
const plain = buildSandboxCreateArgs(vmSpec())
const replace = buildSandboxCreateArgs(vmSpec(), { replace: true })
expect(plain).not.toContain('--replace')
expect(plain.slice(0, 3)).toEqual(['run', '-d', '--name'])
expect(replace.slice(0, 4)).toEqual(['run', '-d', '--replace', '--name'])
expect(replace.filter((token) => token === '--replace')).toHaveLength(1)
const imageIndex = replace.indexOf(ENV.SANDBOX.IMAGE)
const separatorIndex = replace.indexOf('--')
const replaceIndex = replace.indexOf('--replace')
expect(replaceIndex).toBeLessThan(imageIndex)
expect(replaceIndex).toBeLessThan(separatorIndex)
expect(replace.slice(replaceIndex + 1)).toEqual(plain.slice(2))
})
it('keeps the canonical spec free of the --replace flag', () => {
const canonical = buildCanonicalSandboxSpec(vmSpec())
expect(JSON.stringify(canonical)).not.toContain('--replace')
expect(canonical.name).toBe(VM_NAME)
expect((canonical.image as { Oci: { reference: string } }).Oci.reference).toBe(ENV.SANDBOX.IMAGE)
expect((canonical.runtime as { cmd: string[] }).cmd).toEqual(['sleep', 'infinity'])
expect((canonical.runtime as { workdir: string }).workdir).toBe(getReposPath())
expect(canonical.labels).toEqual({ 'ocm.managed': 'true', 'ocm.net': ENV.SANDBOX.NET, 'ocm.session': ROOT_SESSION_ID })
})
it('never masks the assistant .opencode directory with a tmpfs overlay', () => {
const args = buildSandboxCreateArgs()
const args = buildSandboxCreateArgs(vmSpec())
const tmpfsMounts = args.flatMap((arg, index) => arg === '--tmpfs' ? [args[index + 1]] : [])
expect(tmpfsMounts).toHaveLength(1)
@@ -138,7 +235,7 @@ describe('sandbox command builders', () => {
})
it('pins --entrypoint to /usr/bin/env before the image so msb never inherits the OCI entrypoint', () => {
const args = buildSandboxCreateArgs()
const args = buildSandboxCreateArgs(vmSpec())
const entrypointIndex = args.indexOf('--entrypoint')
expect(entrypointIndex).toBeGreaterThan(-1)
@@ -173,7 +270,7 @@ describe('sandbox command builders', () => {
})
it('derives a canonical spec from the create args matching the security configuration', () => {
const spec = buildCanonicalSandboxSpec()
const spec = buildCanonicalSandboxSpec(vmSpec())
const labels = spec.labels as Record<string, string>
const resources = spec.resources as Record<string, number>
const runtime = spec.runtime as Record<string, unknown>
@@ -181,11 +278,12 @@ describe('sandbox command builders', () => {
const network = spec.network as Record<string, unknown>
const lifecycle = spec.lifecycle as Record<string, unknown>
expect(spec.name).toBe(WORKSPACE_SANDBOX_NAME)
expect(spec.name).toBe(VM_NAME)
const canonicalImage = spec.image as Record<string, { reference: string } | undefined>
expect(canonicalImage.Oci?.reference).toBe(ENV.SANDBOX.IMAGE)
expect(labels['ocm.managed']).toBe('true')
expect(labels['ocm.net']).toBe(ENV.SANDBOX.NET)
expect(labels['ocm.session']).toBe(ROOT_SESSION_ID)
expect(resources.cpus).toBe(ENV.SANDBOX.CPUS)
expect(typeof resources.memory_mib).toBe('number')
expect(runtime.workdir).toBe(getReposPath())
@@ -201,12 +299,9 @@ describe('sandbox command builders', () => {
expect(lifecycle.idle_timeout_secs).toBeNull()
const binds = mounts.filter((mount) => mount.type === 'Bind')
expect(binds).toHaveLength(7)
expect(binds).toHaveLength(4)
expect(binds.map((mount) => mount.host)).toEqual([
getReposPath(),
getScheduleWorktreesPath(),
getOpenCodeWorktreesPath(),
getForgeWorktreesPath(),
getOpenCodeToolOutputPath(),
getOpenCodeGlobalSkillsPath(),
getOpenCodeAgentTmpPath(),
@@ -228,7 +323,7 @@ describe('sandbox command builders', () => {
expect(named).toHaveLength(1)
expect(named[0]).toEqual({
type: 'Named',
name: SANDBOX_DOCKER_DATA_VOLUME_NAME,
name: DOCKER_DATA_VOLUME,
guest: SANDBOX_DOCKER_DATA_GUEST_PATH,
options: { readonly: false, noexec: false, nosuid: false, nodev: false },
stat_virtualization: 'strict',
@@ -342,10 +437,10 @@ describe('sandbox command builders', () => {
vi.spyOn(proc, 'getuid').mockReturnValue(1001)
vi.spyOn(proc, 'getgid').mockReturnValue(1002)
const args = buildSandboxProvisionArgs()
const args = buildSandboxProvisionArgs(VM_NAME)
expect(args[0]).toBe('exec')
expect(args).toContain(WORKSPACE_SANDBOX_NAME)
expect(args).toContain(VM_NAME)
expect(args[args.indexOf('-u') + 1]).toBe('0:0')
const script = args[args.indexOf('-c') + 1]
expect(script).toContain("getent group 1002 >/dev/null 2>&1 || echo 'ocm-exec:x:1002:' >> /etc/group")
@@ -362,7 +457,27 @@ describe('sandbox command builders', () => {
vi.spyOn(proc, 'getuid').mockReturnValue(undefined)
vi.spyOn(proc, 'getgid').mockReturnValue(undefined)
expect(buildSandboxProvisionArgs()).toEqual([])
expect(buildSandboxProvisionArgs(VM_NAME)).toEqual([])
expect(buildSandboxVerifyProvisionArgs(VM_NAME)).toEqual([])
})
it('builds verify-provision args that assert the exec user passwd entry as root', () => {
const proc = process as unknown as { getuid: () => number; getgid: () => number }
vi.spyOn(proc, 'getuid').mockReturnValue(1001)
vi.spyOn(proc, 'getgid').mockReturnValue(1002)
expect(buildSandboxVerifyProvisionArgs(VM_NAME)).toEqual([
'exec',
VM_NAME,
'--no-tty',
'-q',
'-u',
'0:0',
'--',
'/bin/sh',
'-c',
'getent passwd 1001 >/dev/null',
])
})
it('aligns a numeric exec user with the manager gid', async () => {
@@ -683,3 +798,270 @@ describe('sandbox network policy attestation helpers', () => {
)).toContain('network policy')
})
})
describe('resolveSessionSandboxMounts', () => {
function runGit(args: string[], cwd?: string): void {
const result = spawnSync('git', args, { cwd, encoding: 'utf8' })
if (result.status !== 0) {
throw new Error(`git ${args.join(' ')} failed: ${result.stderr}`)
}
}
function restoreWorkspacePath(original: string | undefined): void {
if (original === undefined) {
delete process.env.WORKSPACE_PATH
} else {
process.env.WORKSPACE_PATH = original
}
}
it('returns the single project mount for a plain repository and a non-repository directory, and null outside the roots', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-mounts-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'repos')
const repo = path.join(repos, 'repo')
const plain = path.join(repos, 'plain')
mkdirSync(repo, { recursive: true })
mkdirSync(plain, { recursive: true })
runGit(['init', '-q'], repo)
process.env.WORKSPACE_PATH = tmp
await expect(resolveSessionSandboxMounts(repo)).resolves.toEqual([repo])
await expect(resolveSessionSandboxMounts(plain)).resolves.toEqual([plain])
await expect(resolveSessionSandboxMounts('/etc')).resolves.toBeNull()
await expect(resolveSessionSandboxMounts(path.join(repos, 'missing'))).resolves.toBeNull()
} finally {
restoreWorkspacePath(originalWorkspacePath)
rmSync(tmp, { recursive: true, force: true })
}
})
it('adds the main repository git common dir for a linked worktree', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-worktree-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'repos')
const main = path.join(repos, 'main')
const worktree = path.join(tmp, 'schedule-worktrees', 'job-1-run-2')
mkdirSync(main, { recursive: true })
mkdirSync(path.dirname(worktree), { recursive: true })
runGit(['init', '-q'], main)
runGit(
['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'],
main,
)
runGit(['worktree', 'add', '-q', '-b', 'feature', worktree], main)
process.env.WORKSPACE_PATH = tmp
await expect(resolveSessionSandboxMounts(worktree)).resolves.toEqual([worktree, path.join(main, '.git')])
} finally {
restoreWorkspacePath(originalWorkspacePath)
rmSync(tmp, { recursive: true, force: true })
}
})
it('blocks a forged git dir that has no worktree back-link to the sandbox worktree', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-forged-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'repos')
const main = path.join(repos, 'main')
const unrelatedWorktree = path.join(tmp, 'schedule-worktrees', 'job-9-run-1')
const victim = path.join(repos, 'victim')
mkdirSync(main, { recursive: true })
mkdirSync(path.dirname(unrelatedWorktree), { recursive: true })
mkdirSync(victim, { recursive: true })
runGit(['init', '-q'], main)
runGit(
['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'],
main,
)
runGit(['worktree', 'add', '-q', '-b', 'feature', unrelatedWorktree], main)
writeFileSync(path.join(victim, '.git'), `gitdir: ${path.join(main, '.git')}\n`)
process.env.WORKSPACE_PATH = tmp
await expect(resolveSessionSandboxMounts(victim)).resolves.toBeNull()
} finally {
restoreWorkspacePath(originalWorkspacePath)
rmSync(tmp, { recursive: true, force: true })
}
})
it('blocks a symlinked git dir that points at another repo worktree back-link', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-gitsym-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'repos')
const other = path.join(repos, 'other')
const otherWorktree = path.join(tmp, 'schedule-worktrees', 'other-wt')
const victim = path.join(repos, 'victim')
mkdirSync(other, { recursive: true })
mkdirSync(path.dirname(otherWorktree), { recursive: true })
mkdirSync(victim, { recursive: true })
runGit(['init', '-q'], other)
runGit(
['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'],
other,
)
runGit(['worktree', 'add', '-q', '-b', 'feature', otherWorktree], other)
symlinkSync(path.join(otherWorktree, '.git'), path.join(victim, '.git'))
process.env.WORKSPACE_PATH = tmp
await expect(resolveSessionSandboxMounts(victim)).resolves.toBeNull()
} finally {
restoreWorkspacePath(originalWorkspacePath)
rmSync(tmp, { recursive: true, force: true })
}
})
it('rejects a main repository whose core.worktree points at the repos root', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-core-worktree-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'repos')
const repo = path.join(repos, 'repo')
mkdirSync(repo, { recursive: true })
runGit(['init', '-q'], repo)
runGit(['config', 'core.worktree', repos], repo)
process.env.WORKSPACE_PATH = tmp
await expect(resolveSessionSandboxMounts(repo)).resolves.toBeNull()
} finally {
restoreWorkspacePath(originalWorkspacePath)
rmSync(tmp, { recursive: true, force: true })
}
})
it('rejects a core.worktree escape that plants a matching worktree back-link', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-core-worktree-link-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'repos')
const mine = path.join(repos, 'mine')
const other = path.join(repos, 'other')
mkdirSync(mine, { recursive: true })
mkdirSync(other, { recursive: true })
runGit(['init', '-q'], mine)
runGit(['init', '-q'], other)
runGit(['config', 'core.worktree', other], mine)
const planted = path.join(mine, '.git', 'worktrees', 'x')
mkdirSync(planted, { recursive: true })
writeFileSync(path.join(planted, 'gitdir'), `${path.join(other, '.git')}\n`)
process.env.WORKSPACE_PATH = tmp
await expect(resolveSessionSandboxMounts(mine)).resolves.toBeNull()
} finally {
restoreWorkspacePath(originalWorkspacePath)
rmSync(tmp, { recursive: true, force: true })
}
})
it('rejects a main repository whose git dir is a symlink to another repository git dir', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-symlink-main-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'repos')
const repo = path.join(repos, 'repo')
const other = path.join(repos, 'other')
mkdirSync(repo, { recursive: true })
mkdirSync(other, { recursive: true })
runGit(['init', '-q'], repo)
runGit(['init', '-q'], other)
runGit(
['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'],
repo,
)
rmSync(path.join(repo, '.git'), { recursive: true, force: true })
symlinkSync(path.join(other, '.git'), path.join(repo, '.git'), 'dir')
process.env.WORKSPACE_PATH = tmp
await expect(resolveSessionSandboxMounts(repo)).resolves.toBeNull()
} finally {
restoreWorkspacePath(originalWorkspacePath)
rmSync(tmp, { recursive: true, force: true })
}
})
it('rejects a worktree whose git file is a symlink to another repository linked worktree git file', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-symlink-worktree-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'repos')
const main = path.join(repos, 'main')
const other = path.join(repos, 'other')
const otherWorktree = path.join(repos, 'other-linked')
const worktree = path.join(tmp, 'schedule-worktrees', 'job-1-run-2')
mkdirSync(main, { recursive: true })
mkdirSync(other, { recursive: true })
mkdirSync(path.dirname(worktree), { recursive: true })
runGit(['init', '-q'], main)
runGit(['init', '-q'], other)
runGit(
['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'],
main,
)
runGit(
['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'],
other,
)
runGit(['worktree', 'add', '-q', '-b', 'feature', worktree], main)
runGit(['worktree', 'add', '-q', '-b', 'linked', otherWorktree], other)
rmSync(path.join(worktree, '.git'), { force: true })
symlinkSync(path.join(otherWorktree, '.git'), path.join(worktree, '.git'))
process.env.WORKSPACE_PATH = tmp
await expect(resolveSessionSandboxMounts(worktree)).resolves.toBeNull()
} finally {
restoreWorkspacePath(originalWorkspacePath)
rmSync(tmp, { recursive: true, force: true })
}
})
it('rejects a worktree whose git file points at another repository linked worktree', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-cross-linked-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'repos')
const main = path.join(repos, 'main')
const other = path.join(repos, 'other')
const otherWorktree = path.join(repos, 'other-linked')
const worktree = path.join(tmp, 'schedule-worktrees', 'job-1-run-2')
mkdirSync(main, { recursive: true })
mkdirSync(other, { recursive: true })
mkdirSync(path.dirname(worktree), { recursive: true })
runGit(['init', '-q'], main)
runGit(['init', '-q'], other)
runGit(
['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'],
main,
)
runGit(
['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'],
other,
)
runGit(['worktree', 'add', '-q', '-b', 'feature', worktree], main)
runGit(['worktree', 'add', '-q', '-b', 'linked', otherWorktree], other)
const otherGitDir = path.join(other, '.git', 'worktrees', path.basename(otherWorktree))
writeFileSync(path.join(worktree, '.git'), `gitdir: ${otherGitDir}\n`)
process.env.WORKSPACE_PATH = tmp
await expect(resolveSessionSandboxMounts(worktree)).resolves.toBeNull()
} finally {
restoreWorkspacePath(originalWorkspacePath)
rmSync(tmp, { recursive: true, force: true })
}
})
})
@@ -0,0 +1,64 @@
import { describe, it, expect } from 'vitest'
import os from 'os'
import { ENV } from '@opencode-manager/shared/config/env'
import { parseMemoryMib } from '../../../src/services/sandbox/command'
import {
envSandboxResources,
resolveSandboxResources,
sandboxResourceLimitError,
} from '../../../src/services/sandbox/resources'
describe('sandbox resources', () => {
const hostCpus = os.availableParallelism()
const hostMemoryMib = Math.floor(os.totalmem() / 1048576)
it('reads the environment sandbox resources', () => {
expect(envSandboxResources()).toEqual({
cpus: ENV.SANDBOX.CPUS,
memoryMib: parseMemoryMib(ENV.SANDBOX.MEMORY),
})
})
it('falls back to the environment when no preferences or override are set', () => {
expect(resolveSandboxResources(undefined, null)).toEqual(envSandboxResources())
})
it('prefers preference values over the environment', () => {
expect(resolveSandboxResources({ enabled: false, cpus: 6, memoryMib: 2048 }, null)).toEqual({
cpus: 6,
memoryMib: 2048,
})
})
it('prefers the per-session override over preferences and the environment', () => {
expect(
resolveSandboxResources({ enabled: false, cpus: 6, memoryMib: 2048 }, { cpus: 2, memoryMib: 1024 }),
).toEqual({ cpus: 2, memoryMib: 1024 })
})
it('fills each field independently from preferences and the environment', () => {
const env = envSandboxResources()
expect(resolveSandboxResources({ enabled: false, cpus: 6 }, null)).toEqual({ cpus: 6, memoryMib: env.memoryMib })
expect(resolveSandboxResources({ enabled: false, memoryMib: 2048 }, null)).toEqual({ cpus: env.cpus, memoryMib: 2048 })
})
it('accepts requests within the host limits', () => {
expect(sandboxResourceLimitError({})).toBeNull()
expect(sandboxResourceLimitError({ cpus: hostCpus })).toBeNull()
expect(sandboxResourceLimitError({ memoryMib: hostMemoryMib })).toBeNull()
})
it('rejects a cpu request above the host limit', () => {
const error = sandboxResourceLimitError({ cpus: hostCpus + 1 })
expect(error).toContain(String(hostCpus + 1))
expect(error).toContain(String(hostCpus))
})
it('rejects a memory request above the host limit', () => {
const error = sandboxResourceLimitError({ memoryMib: hostMemoryMib + 1 })
expect(error).toContain(String(hostMemoryMib + 1))
expect(error).toContain(String(hostMemoryMib))
})
})
File diff suppressed because it is too large. Load diff
@@ -4,12 +4,15 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, wri
import { tmpdir } from 'node:os'
import path from 'node:path'
import { getReposPath } from '@opencode-manager/shared/config/env'
import { WORKSPACE_SANDBOX_NAME } from '../../../src/services/sandbox/command'
import { sessionSandboxName } from '../../../src/services/sandbox/command'
import {
SANDBOX_FORWARDED_ENV_NAMES,
SANDBOX_SHELL_ENV_NAME,
SANDBOX_SHELL_ENV_WORKDIR,
} from '../../../src/services/sandbox/shell-shim'
const SANDBOX_NAME = sessionSandboxName('ses_shim_test')
afterEach(() => {
vi.restoreAllMocks()
})
@@ -59,7 +62,7 @@ describe('sandbox shell shim', () => {
const command = 'echo "it\'s a test" && echo line2 | tr a-z A-Z\necho after-newline'
const result = spawnSync(shimPath, ['-c', command], {
encoding: 'utf8',
env: sandboxShellEnv({ [SANDBOX_SHELL_ENV_WORKDIR]: directory }),
env: sandboxShellEnv({ [SANDBOX_SHELL_ENV_WORKDIR]: directory, [SANDBOX_SHELL_ENV_NAME]: SANDBOX_NAME }),
})
expect(result.status).toBe(0)
expect(result.stdout).toBe("it's a test\nLINE2\nafter-newline\n")
@@ -68,7 +71,7 @@ describe('sandbox shell shim', () => {
expect(argv).toEqual([
msbPath,
'exec',
WORKSPACE_SANDBOX_NAME,
SANDBOX_NAME,
'--no-tty',
'-q',
'-u',
@@ -114,6 +117,7 @@ describe('sandbox shell shim', () => {
encoding: 'utf8',
env: sandboxShellEnv({
[SANDBOX_SHELL_ENV_WORKDIR]: directory,
[SANDBOX_SHELL_ENV_NAME]: SANDBOX_NAME,
GIT_CONFIG_COUNT: '1',
GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader',
GIT_CONFIG_VALUE_0: extraheaderValue,
@@ -172,7 +176,7 @@ describe('sandbox shell shim', () => {
const command = 'echo hostile-ok'
const result = spawnSync(shimPath, ['-c', command], {
encoding: 'utf8',
env: sandboxShellEnv({ [SANDBOX_SHELL_ENV_WORKDIR]: directory }),
env: sandboxShellEnv({ [SANDBOX_SHELL_ENV_WORKDIR]: directory, [SANDBOX_SHELL_ENV_NAME]: SANDBOX_NAME }),
})
expect(result.status).toBe(0)
expect(result.stdout).toBe('hostile-ok\n')
@@ -236,6 +240,96 @@ describe('sandbox shell shim', () => {
}
})
it('refuses to run the payload and never invokes msb when the sandbox name env is unset or invalid', async () => {
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-shim-name-'))
const configHome = mkdtempSync(path.join(tmpdir(), 'ocm-shim-config-'))
const msbCaptureFile = path.join(fakeBin, 'msb-invoked.txt')
const payloadFile = path.join(fakeBin, 'payload-ran.txt')
const msbPath = path.join(fakeBin, 'msb')
writeFileSync(msbPath, ['#!/bin/sh', `printf 'invoked' > "${msbCaptureFile}"`].join('\n'), { mode: 0o755 })
const originalMsbPath = process.env.MSB_PATH
process.env.MSB_PATH = msbPath
try {
vi.resetModules()
const shimMod = await import('../../../src/services/sandbox/shell-shim')
const commandMod = await import('../../../src/services/sandbox/command')
commandMod.overrideSandboxExecutableTrustValidator(() => true)
const shimPath = await shimMod.ensureSandboxShellShim(configHome)
const directory = path.join(getReposPath(), 'foo')
for (const name of [
undefined,
'',
'ocm-workspace',
'ocm-session-short',
`ocm-session-${'a'.repeat(11)}`,
`ocm-session-${'a'.repeat(13)}`,
`ocm-session-${'g'.repeat(12)}`,
`ocm-session-${'A'.repeat(12)}`,
`ocm-session-${'a'.repeat(12)}extra`,
]) {
const env: Record<string, string | undefined> = {
...process.env,
[SANDBOX_SHELL_ENV_WORKDIR]: directory,
}
if (name === undefined) {
delete env[SANDBOX_SHELL_ENV_NAME]
} else {
env[SANDBOX_SHELL_ENV_NAME] = name
}
const result = spawnSync(shimPath, ['-c', `touch ${payloadFile}`], { encoding: 'utf8', env })
expect(result.status).toBe(126)
expect(result.stderr).toContain('ocm-sandbox-shell: sandbox name missing or invalid; refusing to run on the host')
expect(existsSync(payloadFile)).toBe(false)
expect(existsSync(msbCaptureFile)).toBe(false)
}
} finally {
if (originalMsbPath === undefined) {
delete process.env.MSB_PATH
} else {
process.env.MSB_PATH = originalMsbPath
}
rmSync(fakeBin, { recursive: true, force: true })
rmSync(configHome, { recursive: true, force: true })
}
})
it('execs the sandbox named by OCM_SANDBOX_NAME', async () => {
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-shim-name-'))
const configHome = mkdtempSync(path.join(tmpdir(), 'ocm-shim-config-'))
const msbPath = path.join(fakeBin, 'msb')
const captureFile = path.join(fakeBin, 'argv.txt')
writeArgvCapturingFakeMsb(msbPath, captureFile)
const originalMsbPath = process.env.MSB_PATH
process.env.MSB_PATH = msbPath
try {
vi.resetModules()
const shimMod = await import('../../../src/services/sandbox/shell-shim')
const commandMod = await import('../../../src/services/sandbox/command')
commandMod.overrideSandboxExecutableTrustValidator(() => true)
const shimPath = await shimMod.ensureSandboxShellShim(configHome)
const directory = path.join(getReposPath(), 'foo')
const otherName = commandMod.sessionSandboxName('ses_other')
const result = spawnSync(shimPath, ['-c', 'echo ok'], {
encoding: 'utf8',
env: sandboxShellEnv({ [SANDBOX_SHELL_ENV_WORKDIR]: directory, [SANDBOX_SHELL_ENV_NAME]: otherName }),
})
expect(result.status).toBe(0)
const argv = readFileSync(captureFile, 'utf8').split('\0').filter((element) => element !== '')
expect(argv[argv.indexOf('exec') + 1]).toBe(otherName)
} finally {
if (originalMsbPath === undefined) {
delete process.env.MSB_PATH
} else {
process.env.MSB_PATH = originalMsbPath
}
rmSync(fakeBin, { recursive: true, force: true })
rmSync(configHome, { recursive: true, force: true })
}
})
it('writes an executable regular shim at sandboxShellShimPath and is idempotent', async () => {
const configHome = mkdtempSync(path.join(tmpdir(), 'ocm-shim-config-'))
try {
@@ -7,6 +7,8 @@ import { createScheduleRun, updateScheduleRunMetadata } from '../../src/db/sched
import { getSessionPermissionMode, setSessionPermissionMode } from '../../src/db/session-permission-modes'
import { SettingsService } from '../../src/services/settings'
import { SessionPermissionModeService } from '../../src/services/session-permission-modes'
import { SessionAncestry } from '../../src/services/session-ancestry'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import type { SSEEvent } from '../../src/services/sse-aggregator'
import {
createFakeSessionPermissionClient,
@@ -32,6 +34,14 @@ function createTestDb(): Database {
return db
}
function createPermissionModeService(
db: Database,
client: OpenCodeClient,
settingsService: SettingsService,
): SessionPermissionModeService {
return new SessionPermissionModeService(db, client, settingsService, new SessionAncestry(client))
}
function permissionAskedEvent(sessionID: string, id: string): SSEEvent {
return {
id: `evt_${id}`,
@@ -94,7 +104,7 @@ describe('SessionPermissionModeService', () => {
})
it('treats a root session with no stored row as ask', async () => {
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await expect(service.getEffectiveMode('ses_root')).resolves.toEqual({
sessionId: 'ses_root',
@@ -107,7 +117,7 @@ describe('SessionPermissionModeService', () => {
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))
const service = createPermissionModeService(db, client, new SettingsService(db))
await expect(service.getEffectiveMode('ses_child')).resolves.toEqual({
sessionId: 'ses_child',
@@ -137,7 +147,7 @@ describe('SessionPermissionModeService', () => {
updateScheduleRunMetadata(db, 1, 1, run.id, { sessionId: 'ses_scheduled' })
setSessionPermissionMode(db, 'ses_scheduled', 'auto')
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await expect(service.getEffectiveMode('ses_scheduled')).resolves.toEqual({
sessionId: 'ses_scheduled',
@@ -149,7 +159,7 @@ describe('SessionPermissionModeService', () => {
it('rejects setMode for a child session', async () => {
const client = createFakeSessionPermissionClient({ parents: { ses_child: 'ses_root', ses_root: null } })
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
const service = createPermissionModeService(db, client, new SettingsService(db))
await expect(service.setMode('ses_child', 'auto', '/abs/repo')).rejects.toMatchObject({ status: 400 })
expect(getSessionPermissionMode(db, 'ses_child')).toBeNull()
@@ -157,7 +167,7 @@ describe('SessionPermissionModeService', () => {
})
it('fails closed to ask when parent resolution fails', async () => {
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient({ failSessionGet: true }), new SettingsService(db))
const service = createPermissionModeService(db, createFakeSessionPermissionClient({ failSessionGet: true }), new SettingsService(db))
await expect(service.getEffectiveMode('ses_root')).resolves.toEqual({
sessionId: 'ses_root',
@@ -169,7 +179,7 @@ describe('SessionPermissionModeService', () => {
it('reads the default mode from session settings', () => {
const settingsService = new SettingsService(db)
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
expect(service.defaultMode()).toBe('ask')
@@ -180,7 +190,7 @@ describe('SessionPermissionModeService', () => {
it('stores the default auto mode for a launched session', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } })
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
await service.applyDefaultMode('ses_launched', DIRECTORY)
@@ -188,7 +198,7 @@ describe('SessionPermissionModeService', () => {
})
it('stores no mode for a launched session when the default is ask', async () => {
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await service.applyDefaultMode('ses_launched', DIRECTORY)
@@ -199,7 +209,7 @@ describe('SessionPermissionModeService', () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } })
setSessionPermissionMode(db, 'ses_launched', 'ask')
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
await service.applyDefaultMode('ses_launched', DIRECTORY)
@@ -213,7 +223,7 @@ describe('SessionPermissionModeService', () => {
parents: { ses_launched: null },
pendingRequests: { [DIRECTORY]: [{ id: 'perm-launched', sessionID: 'ses_launched' }] },
})
const service = new SessionPermissionModeService(db, client, settingsService)
const service = createPermissionModeService(db, client, settingsService)
await service.applyDefaultMode('ses_launched', DIRECTORY)
@@ -228,7 +238,7 @@ describe('SessionPermissionModeService', () => {
it('auto-accepts a permission request for an auto root session', async () => {
setSessionPermissionMode(db, 'ses_root', 'auto')
const client = createFakeSessionPermissionClient({ parents: { ses_root: null } })
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
const service = createPermissionModeService(db, client, new SettingsService(db))
await service.handleEvent(DIRECTORY, permissionAskedEvent('ses_root', 'perm-1'))
@@ -243,7 +253,7 @@ describe('SessionPermissionModeService', () => {
it('auto-accepts a permission request for a child of an auto root session', 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))
const service = createPermissionModeService(db, client, new SettingsService(db))
await service.handleEvent(DIRECTORY, permissionAskedEvent('ses_child', 'perm-2'))
@@ -257,7 +267,7 @@ describe('SessionPermissionModeService', () => {
it('leaves an ask session permission request unanswered', async () => {
const client = createFakeSessionPermissionClient({ parents: { ses_root: null } })
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
const service = createPermissionModeService(db, client, new SettingsService(db))
await service.handleEvent(DIRECTORY, permissionAskedEvent('ses_root', 'perm-3'))
@@ -267,7 +277,7 @@ describe('SessionPermissionModeService', () => {
it('stamps the default auto mode on a new root session but not on a child', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } })
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
await service.handleEvent(DIRECTORY, sessionCreatedEvent('ses_root'))
await service.handleEvent(DIRECTORY, sessionCreatedEvent('ses_child', 'ses_root'))
@@ -277,7 +287,7 @@ describe('SessionPermissionModeService', () => {
})
it('does not stamp a new root session when the default mode is ask', async () => {
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await service.handleEvent(DIRECTORY, sessionCreatedEvent('ses_root'))
@@ -287,7 +297,7 @@ describe('SessionPermissionModeService', () => {
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)
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), settingsService)
await service.handleEvent(
DIRECTORY,
@@ -299,7 +309,7 @@ describe('SessionPermissionModeService', () => {
it('copies an auto source mode onto a forked root session', async () => {
setSessionPermissionMode(db, 'ses_source', 'auto')
const service = new SessionPermissionModeService(
const service = createPermissionModeService(
db,
createFakeSessionPermissionClient({ parents: { ses_source: null } }),
new SettingsService(db),
@@ -311,7 +321,7 @@ describe('SessionPermissionModeService', () => {
})
it('leaves a forked session unstamped when the source is ask', async () => {
const service = new SessionPermissionModeService(
const service = createPermissionModeService(
db,
createFakeSessionPermissionClient({ parents: { ses_source: null } }),
new SettingsService(db),
@@ -325,7 +335,7 @@ describe('SessionPermissionModeService', () => {
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(
const service = createPermissionModeService(
db,
createFakeSessionPermissionClient({ parents: { ses_source: null } }),
new SettingsService(db),
@@ -339,7 +349,7 @@ describe('SessionPermissionModeService', () => {
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(
const service = createPermissionModeService(
db,
createFakeSessionPermissionClient({ parents: { ses_root: null } }),
settingsService,
@@ -374,7 +384,7 @@ describe('SessionPermissionModeService', () => {
})
updateScheduleRunMetadata(db, 1, 1, run.id, { sessionId: 'ses_scheduled' })
const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await expect(service.setMode('ses_scheduled', 'auto', DIRECTORY)).rejects.toMatchObject({ status: 409 })
expect(getSessionPermissionMode(db, 'ses_scheduled')).toBeNull()
@@ -393,7 +403,7 @@ describe('SessionPermissionModeService', () => {
],
},
})
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
const service = createPermissionModeService(db, client, new SettingsService(db))
await service.acceptPendingRequestsForActiveSessions()
@@ -413,7 +423,7 @@ describe('SessionPermissionModeService', () => {
activeSessions: ['ses_child'],
pendingRequests: { [DIRECTORY]: [{ id: 'perm-child', sessionID: 'ses_child' }] },
})
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
const service = createPermissionModeService(db, client, new SettingsService(db))
await service.acceptPendingRequestsForActiveSessions()
@@ -427,13 +437,46 @@ describe('SessionPermissionModeService', () => {
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))
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await service.handleEvent(DIRECTORY, sessionDeletedEvent('ses_root'))
expect(getSessionPermissionMode(db, 'ses_root')).toBeNull()
})
it('clears the stored mode when the session is deleted with a null directory', async () => {
setSessionPermissionMode(db, 'ses_root', 'auto')
const service = createPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await service.handleEvent(null, sessionDeletedEvent('ses_root'))
expect(getSessionPermissionMode(db, 'ses_root')).toBeNull()
})
it('handles a null directory on permission.asked without listing or accepting anything in a guessed location', async () => {
const listed: string[] = []
const client = createFakeSessionPermissionClient({
parents: { ses_root: null },
listRequests: async (directory) => {
listed.push(directory)
return [{ id: 'perm-guess', sessionID: 'ses_root' }]
},
})
const service = createPermissionModeService(db, client, new SettingsService(db))
const event = {
id: 'evt_perm_null',
created: Date.now(),
type: 'permission.asked',
data: { id: 'perm-1', sessionID: 'ses_root', action: 'shell', resources: ['ls'] },
} as unknown as SSEEvent
await expect(service.handleEvent(null, event)).resolves.toBeUndefined()
expect(listed).toEqual([])
expect(client.replyPermission).not.toHaveBeenCalled()
})
it('replies to pending requests for the switched root only', async () => {
const client = createFakeSessionPermissionClient({
parents: { ses_root: null, ses_other: null },
@@ -444,7 +487,7 @@ describe('SessionPermissionModeService', () => {
],
},
})
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
const service = createPermissionModeService(db, client, new SettingsService(db))
await service.setMode('ses_root', 'auto', DIRECTORY)
@@ -466,7 +509,7 @@ describe('SessionPermissionModeService', () => {
return listDeferred.promise
},
})
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
const service = createPermissionModeService(db, client, new SettingsService(db))
const autoSwitch = service.setMode('ses_root', 'auto', DIRECTORY)
await listStarted.promise
@@ -492,7 +535,7 @@ describe('SessionPermissionModeService', () => {
return Promise.resolve({ parentID: null })
},
})
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
const service = createPermissionModeService(db, client, new SettingsService(db))
const autoSwitch = service.setMode('ses_root', 'auto', DIRECTORY)
await childResolutionStarted.promise
@@ -506,7 +549,7 @@ describe('SessionPermissionModeService', () => {
it('does not list pending requests when switching to ask', async () => {
const client = createFakeSessionPermissionClient({ parents: { ses_root: null } })
const service = new SessionPermissionModeService(db, client, new SettingsService(db))
const service = createPermissionModeService(db, client, new SettingsService(db))
await service.setMode('ses_root', 'ask', DIRECTORY)
@@ -0,0 +1,579 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import os from 'os'
import { Database } from 'bun:sqlite'
import { ENV } from '@opencode-manager/shared/config/env'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import {
getSessionSandboxMode,
setSessionSandboxResources,
setSessionSandboxed,
} from '../../src/db/session-sandbox-modes'
import { parseMemoryMib } from '../../src/services/sandbox/command'
import { SettingsService } from '../../src/services/settings'
import { SessionAncestry } from '../../src/services/session-ancestry'
import { SessionSandboxService } from '../../src/services/session-sandbox'
import { logger } from '../../src/utils/logger'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import type { SSEEvent } from '../../src/services/sse-aggregator'
import { createFakeSessionPermissionClient } from '../helpers/fake-session-permission-client'
const DIRECTORY = '/abs/repo'
const ENV_RESOURCES = { cpus: ENV.SANDBOX.CPUS, memoryMib: parseMemoryMib(ENV.SANDBOX.MEMORY) ?? 0 }
function createTestDb(): Database {
const db = new Database(':memory:')
migrate(db, allMigrations)
return db
}
function createService(
db: Database,
client: OpenCodeClient,
settingsService: SettingsService,
sandboxes: { removeSessionSandbox(rootSessionId: string): Promise<void> } = { removeSessionSandbox: async () => undefined },
): SessionSandboxService {
return new SessionSandboxService(db, new SessionAncestry(client), settingsService, sandboxes)
}
function sessionCreatedEvent(sessionID: string, parentID?: string): SSEEvent {
return {
id: `evt_created_${sessionID}`,
created: Date.now(),
type: 'session.created',
location: { directory: DIRECTORY },
data: { sessionID, parentID },
} 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 sessionDeletedEvent(sessionID: string): SSEEvent {
return {
id: `evt_deleted_${sessionID}`,
created: Date.now(),
type: 'session.deleted',
location: { directory: DIRECTORY },
data: { sessionID },
} as unknown as SSEEvent
}
describe('SessionSandboxService', () => {
let db: Database
beforeEach(() => {
db = createTestDb()
})
afterEach(() => {
db.close()
})
it('defaults an unstored root session to the configured default when support is enabled', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient(), settingsService)
await expect(service.getState('ses_root')).resolves.toEqual({
sessionId: 'ses_root',
rootSessionId: 'ses_root',
sandboxed: true,
source: 'default',
resources: null,
effectiveResources: ENV_RESOURCES,
lockedReason: null,
available: true,
})
})
it('reports unavailable and unsandboxed when server sandbox support is disabled', async () => {
const settingsService = new SettingsService(db)
const service = createService(db, createFakeSessionPermissionClient(), settingsService)
setSessionSandboxed(db, 'ses_root', true)
await expect(service.getState('ses_root')).resolves.toEqual({
sessionId: 'ses_root',
rootSessionId: 'ses_root',
sandboxed: false,
source: 'user',
resources: null,
effectiveResources: ENV_RESOURCES,
lockedReason: null,
available: false,
})
})
it('reports the stored value and source when server sandbox support is enabled', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient(), settingsService)
setSessionSandboxed(db, 'ses_root', false)
await expect(service.getState('ses_root')).resolves.toMatchObject({
sessionId: 'ses_root',
rootSessionId: 'ses_root',
sandboxed: false,
source: 'user',
resources: null,
available: true,
})
})
it('reports the per-session override and the effective resources', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient(), settingsService)
setSessionSandboxed(db, 'ses_root', true)
setSessionSandboxResources(db, 'ses_root', { cpus: 4, memoryMib: 8192 }, true)
await expect(service.getState('ses_root')).resolves.toMatchObject({
source: 'user',
resources: { cpus: 4, memoryMib: 8192 },
effectiveResources: { cpus: 4, memoryMib: 8192 },
})
})
it('stamps the default value on a new root session but not on a child', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true, defaultForNewSessions: true } })
const service = createService(db, createFakeSessionPermissionClient(), settingsService)
await service.handleEvent(DIRECTORY, sessionCreatedEvent('ses_root'))
await service.handleEvent(DIRECTORY, sessionCreatedEvent('ses_child', 'ses_root'))
expect(getSessionSandboxMode(db, 'ses_root')).toMatchObject({
sandboxed: true,
source: 'default',
resources: null,
})
expect(getSessionSandboxMode(db, 'ses_child')).toBeNull()
})
it('stamps the configured default of false on a new root session', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true, defaultForNewSessions: false } })
const service = createService(db, createFakeSessionPermissionClient(), settingsService)
await service.handleEvent(DIRECTORY, sessionCreatedEvent('ses_root'))
expect(getSessionSandboxMode(db, 'ses_root')?.sandboxed).toBe(false)
})
it('inherits the root value for a child and reports the child lock', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_root', false)
const client = createFakeSessionPermissionClient({ parents: { ses_child: 'ses_root', ses_root: null } })
const service = createService(db, client, settingsService)
await expect(service.getState('ses_child')).resolves.toMatchObject({
sessionId: 'ses_child',
rootSessionId: 'ses_root',
sandboxed: false,
source: 'user',
lockedReason: 'child',
available: true,
})
})
it('rejects getState when parent resolution fails and support is enabled', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient({ failSessionGet: true }), settingsService)
await expect(service.getState('ses_root')).rejects.toThrow('upstream unavailable')
})
it('rejects getState when parent resolution fails and support is disabled', async () => {
const service = createService(db, createFakeSessionPermissionClient({ failSessionGet: true }), new SettingsService(db))
await expect(service.getState('ses_root')).rejects.toThrow('upstream unavailable')
})
it('copies the parent root sandbox flag, source, and resources onto a forked session', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_source', false)
setSessionSandboxResources(db, 'ses_source', { cpus: 4, memoryMib: 8192 }, false)
const service = createService(
db,
createFakeSessionPermissionClient({ parents: { ses_source: null } }),
settingsService,
)
await service.handleEvent(DIRECTORY, sessionForkedEvent('ses_fork', 'ses_source'))
expect(getSessionSandboxMode(db, 'ses_fork')).toMatchObject({
sandboxed: false,
source: 'user',
resources: { cpus: 4, memoryMib: 8192 },
})
})
it('copies the parent root row onto a fork when the parent is itself a child', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_root', false)
setSessionSandboxResources(db, 'ses_root', { cpus: 2, memoryMib: 4096 }, false)
const service = createService(
db,
createFakeSessionPermissionClient({ parents: { ses_child: 'ses_root', ses_root: null } }),
settingsService,
)
await service.handleEvent(DIRECTORY, sessionForkedEvent('ses_fork', 'ses_child'))
expect(getSessionSandboxMode(db, 'ses_fork')).toMatchObject({
sandboxed: false,
source: 'user',
resources: { cpus: 2, memoryMib: 4096 },
})
})
it('does not overwrite an explicit stored value when copying onto a fork', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_source', true)
setSessionSandboxed(db, 'ses_fork', false)
const service = createService(
db,
createFakeSessionPermissionClient({ parents: { ses_source: null } }),
settingsService,
)
await service.handleEvent(DIRECTORY, sessionForkedEvent('ses_fork', 'ses_source'))
expect(getSessionSandboxMode(db, 'ses_fork')?.sandboxed).toBe(false)
})
it('clears the stored value when the session is deleted', async () => {
setSessionSandboxed(db, 'ses_root', true)
const service = createService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await service.handleEvent(DIRECTORY, sessionDeletedEvent('ses_root'))
expect(getSessionSandboxMode(db, 'ses_root')).toBeNull()
})
it('removes the sandbox microVM when a sandboxed root session is deleted', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_root', true)
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await service.handleEvent(DIRECTORY, sessionDeletedEvent('ses_root'))
expect(removed).toEqual(['ses_root'])
expect(getSessionSandboxMode(db, 'ses_root')).toBeNull()
})
it('removes the sandbox microVM when a root session is deleted with a null directory', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_root', true)
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await service.handleEvent(null, sessionDeletedEvent('ses_root'))
expect(removed).toEqual(['ses_root'])
expect(getSessionSandboxMode(db, 'ses_root')).toBeNull()
})
it('does not remove a sandbox microVM when a child session is deleted', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_root', true)
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await service.handleEvent(DIRECTORY, sessionDeletedEvent('ses_child'))
expect(removed).toEqual([])
})
it('removes the sandbox microVM when a session with a mode row is deleted even when support is disabled', async () => {
setSessionSandboxed(db, 'ses_root', true)
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), new SettingsService(db), {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await service.handleEvent(DIRECTORY, sessionDeletedEvent('ses_root'))
expect(removed).toEqual(['ses_root'])
expect(getSessionSandboxMode(db, 'ses_root')).toBeNull()
})
it('logs and swallows a failure while removing the deleted session sandbox', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_root', true)
const warn = vi.spyOn(logger, 'warn').mockImplementation(() => undefined)
try {
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async () => {
throw new Error('msb rm failed')
},
})
await expect(service.handleEvent(DIRECTORY, sessionDeletedEvent('ses_root'))).resolves.toBeUndefined()
await vi.waitFor(() => {
expect(warn).toHaveBeenCalledWith(expect.stringContaining('msb rm failed'))
})
expect(getSessionSandboxMode(db, 'ses_root')).toBeNull()
} finally {
warn.mockRestore()
}
})
it('removes the sandbox microVM when sandboxing is turned off and returns the updated state', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_root', true)
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await expect(service.update('ses_root', { sandboxed: false })).resolves.toMatchObject({
sessionId: 'ses_root',
rootSessionId: 'ses_root',
sandboxed: false,
source: 'user',
available: true,
})
await vi.waitFor(() => {
expect(removed).toEqual(['ses_root'])
})
})
it('does not remove the sandbox microVM when sandboxing is turned on', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await service.update('ses_root', { sandboxed: true })
expect(removed).toEqual([])
})
it('does not remove the sandbox microVM for a resources-only update', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await service.update('ses_root', { resources: { cpus: 4, memoryMib: 8192 } })
expect(removed).toEqual([])
})
it('logs and swallows a failure while removing the sandbox after it is turned off', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxed(db, 'ses_root', true)
const warn = vi.spyOn(logger, 'warn').mockImplementation(() => undefined)
try {
const service = createService(db, createFakeSessionPermissionClient(), settingsService, {
removeSessionSandbox: async () => {
throw new Error('msb rm failed')
},
})
await expect(service.update('ses_root', { sandboxed: false })).resolves.toMatchObject({ sandboxed: false })
await vi.waitFor(() => {
expect(warn).toHaveBeenCalledWith(expect.stringContaining('msb rm failed'))
})
expect(warn).toHaveBeenCalledWith(expect.stringContaining('ses_root'))
expect(warn).toHaveBeenCalledWith(expect.stringContaining('turned off'))
} finally {
warn.mockRestore()
}
})
it('does not remove the sandbox microVM when sandboxing is turned off and support is disabled', async () => {
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), new SettingsService(db), {
removeSessionSandbox: async (rootSessionId) => {
removed.push(rootSessionId)
},
})
await expect(service.update('ses_root', { sandboxed: false })).resolves.toMatchObject({
sandboxed: false,
available: false,
})
expect(removed).toEqual([])
})
it('rejects updating a child session with 400', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const client = createFakeSessionPermissionClient({ parents: { ses_child: 'ses_root', ses_root: null } })
const service = createService(db, client, settingsService)
await expect(service.update('ses_child', { sandboxed: false })).rejects.toMatchObject({ status: 400 })
expect(getSessionSandboxMode(db, 'ses_child')).toBeNull()
})
it('rejects enabling sandboxing with 409 when server support is disabled', async () => {
const service = createService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await expect(service.update('ses_root', { sandboxed: true })).rejects.toMatchObject({ status: 409 })
expect(getSessionSandboxMode(db, 'ses_root')).toBeNull()
})
it('allows disabling sandboxing when server support is disabled', async () => {
const service = createService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await expect(service.update('ses_root', { sandboxed: false })).resolves.toMatchObject({
sessionId: 'ses_root',
rootSessionId: 'ses_root',
sandboxed: false,
source: 'user',
available: false,
})
expect(getSessionSandboxMode(db, 'ses_root')?.sandboxed).toBe(false)
})
it('rejects a resource override above the host limit with 400', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient(), settingsService)
await expect(
service.update('ses_root', { resources: { cpus: os.availableParallelism() + 1, memoryMib: 1024 } }),
).rejects.toMatchObject({ status: 400 })
expect(getSessionSandboxMode(db, 'ses_root')).toBeNull()
})
it('persists a resource override and keeps the toggle timestamp stable', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient(), settingsService)
await service.update('ses_root', { sandboxed: true })
const toggledAt = getSessionSandboxMode(db, 'ses_root')?.toggledAt
await expect(service.update('ses_root', { resources: { cpus: 4, memoryMib: 8192 } })).resolves.toMatchObject({
source: 'user',
resources: { cpus: 4, memoryMib: 8192 },
effectiveResources: { cpus: 4, memoryMib: 8192 },
})
expect(getSessionSandboxMode(db, 'ses_root')).toMatchObject({ toggledAt })
})
it('clears a resource override with null', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient(), settingsService)
setSessionSandboxResources(db, 'ses_root', { cpus: 4, memoryMib: 8192 }, true)
await expect(service.update('ses_root', { resources: null })).resolves.toMatchObject({
resources: null,
effectiveResources: ENV_RESOURCES,
})
})
it('reports a claim with the toggle timestamp and source', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient(), settingsService)
setSessionSandboxed(db, 'ses_root', false)
const toggledAt = getSessionSandboxMode(db, 'ses_root')?.toggledAt
await expect(service.getClaim('ses_root')).resolves.toEqual({
sandboxed: false,
source: 'user',
since: toggledAt,
})
})
it('reports a zero-since default claim for an unstored root session', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient(), settingsService)
await expect(service.getClaim('ses_root')).resolves.toEqual({
sandboxed: true,
source: 'default',
since: 0,
})
})
it('reports an unsandboxed claim when support is disabled', async () => {
const service = createService(db, createFakeSessionPermissionClient(), new SettingsService(db))
await expect(service.getClaim('ses_root')).resolves.toEqual({
sandboxed: false,
source: 'default',
since: 0,
})
})
it('rejects getClaim on an ancestry error', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient({ failSessionGet: true }), settingsService)
await expect(service.getClaim('ses_root')).rejects.toThrow('upstream unavailable')
})
it('resolves the shell target to the root session and effective resources', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
setSessionSandboxResources(db, 'ses_root', { cpus: 4, memoryMib: 8192 }, true)
const service = createService(
db,
createFakeSessionPermissionClient({ parents: { ses_child: 'ses_root', ses_root: null } }),
settingsService,
)
await expect(service.resolveShellTarget('ses_child')).resolves.toEqual({
rootSessionId: 'ses_root',
resources: { cpus: 4, memoryMib: 8192 },
})
})
})
+49 -11
View File
@@ -515,7 +515,7 @@ describe('SSEAggregator scheduled session replay without a connected client', ()
{ sessionID: 'ses-sched', directory: '/worktrees/run-1' },
])
const seen: Array<{ directory: string; type: string; sessionID: string; status: string }> = []
const seen: Array<{ directory: string | null; type: string; sessionID: string; status: string }> = []
sseAggregator.onEvent((directory, event) => {
if (event.type !== 'session.status') return
seen.push({
@@ -690,7 +690,7 @@ describe('SSEAggregator directory-less session event routing', () => {
sseAggregator.addClient('resolved-a', subscribed.callback, subscribed.writeFrame, ['/r'])
sseAggregator.addClient('resolved-b', global.callback, global.writeFrame, [])
const seen: Array<{ directory: string; type: string; sessionID: string }> = []
const seen: Array<{ directory: string | null; type: string; sessionID: string }> = []
sseAggregator.onEvent((directory, event) => {
seen.push({ directory, type: event.type, sessionID: sessionIDFromEvent(event) ?? '' })
})
@@ -724,16 +724,16 @@ describe('SSEAggregator directory-less session event routing', () => {
])
})
it('broadcasts a directory-less event from an unknown session without notifying listeners', () => {
it('notifies listeners with a null directory for a directory-less event from an unknown session and still broadcasts it', () => {
const client = createCapturingClient()
sseAggregator.addClient('unknown-a', client.callback, client.writeFrame, ['/r'])
const seen: string[] = []
sseAggregator.onEvent((_directory, event) => { seen.push(event.type) })
const seen: Array<{ directory: string | null; type: string }> = []
sseAggregator.onEvent((directory, event) => { seen.push({ directory, type: event.type }) })
emitRawEvent({ type: 'session.execution.succeeded', data: { sessionID: 'ses_unknown' } })
expect(seen).toEqual([])
expect(seen).toEqual([{ directory: null, type: 'session.execution.succeeded' }])
expect(sseAggregator.getActiveSessions()).toEqual({})
expect(client.frames.map(parseFrame)).toEqual([
{
@@ -743,12 +743,50 @@ describe('SSEAggregator directory-less session event routing', () => {
])
})
it('notifies listeners with a null directory for a session.deleted with no location and no remembered directory', () => {
const client = createCapturingClient()
sseAggregator.addClient('deleted-unknown', client.callback, client.writeFrame, ['/r'])
const seen: Array<{ directory: string | null; type: string; sessionID: string }> = []
sseAggregator.onEvent((directory, event) => {
seen.push({ directory, type: event.type, sessionID: sessionIDFromEvent(event) ?? '' })
})
emitRawEvent({ type: 'session.deleted', data: { sessionID: 'ses_unknown' } })
expect(seen).toEqual([{ directory: null, type: 'session.deleted', sessionID: 'ses_unknown' }])
expect(client.frames.map(parseFrame)).toEqual([
{
directory: null,
payload: { id: 'evt_1', created: 1, type: 'session.deleted', data: { sessionID: 'ses_unknown' } },
},
])
})
it('passes the resolved directory to listeners for a located session.deleted', () => {
const client = createCapturingClient()
sseAggregator.addClient('deleted-located', client.callback, client.writeFrame, ['/r'])
const seen: Array<{ directory: string | null; type: string }> = []
sseAggregator.onEvent((directory, event) => { seen.push({ directory, type: event.type }) })
emitRawEvent({ type: 'session.deleted', location: { directory: '/r' }, data: { sessionID: 'ses_located' } })
expect(seen).toEqual([{ directory: '/r', type: 'session.deleted' }])
expect(client.frames.map(parseFrame)).toEqual([
{
directory: '/r',
payload: { id: 'evt_1', created: 1, type: 'session.deleted', location: { directory: '/r' }, data: { sessionID: 'ses_located' } },
},
])
})
it('forgets the remembered directory when session.deleted arrives', () => {
const client = createCapturingClient()
sseAggregator.addClient('deleted-a', client.callback, client.writeFrame, ['/r'])
const seen: string[] = []
sseAggregator.onEvent((_directory, event) => { seen.push(event.type) })
const seen: Array<string | null> = []
sseAggregator.onEvent((directory) => { seen.push(directory) })
emitRawEvent({ type: 'session.created', location: { directory: '/r' }, data: { sessionID: 'ses_del' } })
emitRawEvent({ type: 'session.deleted', data: { sessionID: 'ses_del' } })
@@ -756,7 +794,7 @@ describe('SSEAggregator directory-less session event routing', () => {
seen.length = 0
emitRawEvent({ type: 'session.execution.succeeded', data: { sessionID: 'ses_del' } })
expect(seen).toEqual([])
expect(seen).toEqual([null])
expect(sseAggregator.getActiveSessions()).toEqual({})
expect(client.frames.map(parseFrame).at(-1)).toEqual({
directory: null,
@@ -770,7 +808,7 @@ describe('SSEAggregator directory-less session event routing', () => {
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 }> = []
const seen: Array<{ directory: string | null; type: string; sessionID: string }> = []
sseAggregator.onEvent((directory, event) => {
seen.push({ directory, type: event.type, sessionID: sessionIDFromEvent(event) ?? '' })
})
@@ -813,7 +851,7 @@ describe('SSEAggregator location-scoped catalog event broadcast', () => {
sseAggregator.addClient('catalog-a', subscribed.callback, subscribed.writeFrame, ['/repo-a'])
sseAggregator.addClient('catalog-b', unsubscribed.callback, unsubscribed.writeFrame, [])
const seen: Array<{ directory: string; type: string }> = []
const seen: Array<{ directory: string | null; type: string }> = []
sseAggregator.onEvent((directory, event) => {
seen.push({ directory, type: event.type })
})
+23
View File
@@ -0,0 +1,23 @@
import { fetchWrapper } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { SessionSandboxState, SetSessionSandboxRequest } from '@opencode-manager/shared/schemas'
export async function getSessionSandbox(sessionId: string): Promise<SessionSandboxState> {
return fetchWrapper<SessionSandboxState>(
`${API_BASE_URL}/api/session-sandbox/${encodeURIComponent(sessionId)}`,
)
}
export async function setSessionSandbox(
sessionId: string,
input: SetSessionSandboxRequest,
): Promise<SessionSandboxState> {
return fetchWrapper<SessionSandboxState>(
`${API_BASE_URL}/api/session-sandbox/${encodeURIComponent(sessionId)}`,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
},
)
}
@@ -3,9 +3,12 @@ import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ComposerToolsMenu } from './ComposerToolsMenu'
import { useSessionPermissionMode, useSetSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
import type { SessionPermissionModeState } from '@opencode-manager/shared/schemas'
import { useSessionSandbox, useSetSessionSandbox } from '@/hooks/useSessionSandbox'
import { FetchError } from '@/api/fetchWrapper'
import type { SessionPermissionModeState, SessionSandboxState } from '@opencode-manager/shared/schemas'
vi.mock('@/hooks/useSessionPermissionMode')
vi.mock('@/hooks/useSessionSandbox')
const baseState: SessionPermissionModeState = {
sessionId: 'ses_1',
@@ -14,6 +17,17 @@ const baseState: SessionPermissionModeState = {
lockedReason: null,
}
const baseSandboxState: SessionSandboxState = {
sessionId: 'ses_1',
rootSessionId: 'ses_1',
sandboxed: false,
source: 'default',
resources: null,
effectiveResources: { cpus: 2, memoryMib: 4096 },
lockedReason: null,
available: true,
}
function mockPermissionMode(state: Partial<SessionPermissionModeState> = {}, mutate = vi.fn()) {
vi.mocked(useSessionPermissionMode).mockReturnValue({
data: { ...baseState, ...state },
@@ -26,6 +40,23 @@ function mockPermissionMode(state: Partial<SessionPermissionModeState> = {}, mut
return mutate
}
function mockSandbox(
state: Partial<SessionSandboxState> = {},
mutateAsync = vi.fn().mockResolvedValue(undefined),
) {
const mutate = vi.fn()
vi.mocked(useSessionSandbox).mockReturnValue({
data: { ...baseSandboxState, ...state },
isError: false,
} as ReturnType<typeof useSessionSandbox>)
vi.mocked(useSetSessionSandbox).mockReturnValue({
mutate,
mutateAsync,
isPending: false,
} as unknown as ReturnType<typeof useSetSessionSandbox>)
return { mutate, mutateAsync }
}
function renderMenu(overrides: Partial<React.ComponentProps<typeof ComposerToolsMenu>> = {}) {
const props = {
sessionID: 'ses_1',
@@ -44,6 +75,7 @@ function renderMenu(overrides: Partial<React.ComponentProps<typeof ComposerTools
describe('ComposerToolsMenu', () => {
beforeEach(() => {
vi.clearAllMocks()
mockSandbox()
})
it('does not highlight the trigger when no tool is active', () => {
@@ -92,6 +124,65 @@ describe('ComposerToolsMenu', () => {
expect(item).toHaveTextContent('Inherited from parent session')
})
it('highlights the trigger while commands are sandboxed', () => {
mockPermissionMode()
mockSandbox({ sandboxed: true })
renderMenu()
expect(screen.getByRole('button', { name: 'Composer options' })).toHaveClass('bg-highlight')
})
it('shows the sandbox item checked while commands are sandboxed', async () => {
const user = userEvent.setup()
mockPermissionMode()
mockSandbox({ sandboxed: true })
renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
expect(item).toHaveAttribute('aria-checked', 'true')
})
it('toggles sandboxing via the sandbox endpoint', async () => {
const user = userEvent.setup()
mockPermissionMode()
const { mutate } = mockSandbox()
renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
expect(item).toHaveAttribute('aria-checked', 'false')
await user.click(item)
expect(mutate).toHaveBeenCalledWith({ sandboxed: true })
})
it('hides the sandbox item when sandboxing is unavailable', async () => {
const user = userEvent.setup()
mockPermissionMode()
mockSandbox({ available: false })
renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ })
expect(screen.queryByRole('menuitemcheckbox', { name: /Sandbox commands/ })).not.toBeInTheDocument()
})
it('shows why sandboxing cannot be changed', async () => {
const user = userEvent.setup()
mockPermissionMode()
mockSandbox({ lockedReason: 'child' })
renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
expect(item).toHaveAttribute('aria-disabled', 'true')
expect(item).toHaveTextContent('Inherited from parent session')
})
it('toggles goal mode', async () => {
const user = userEvent.setup()
mockPermissionMode()
@@ -149,3 +240,142 @@ describe('ComposerToolsMenu', () => {
expect(onDictate).toHaveBeenCalledTimes(1)
})
})
describe('ComposerToolsMenu sandbox resources', () => {
beforeEach(() => {
vi.clearAllMocks()
mockPermissionMode()
mockSandbox()
})
async function openResources(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole('button', { name: 'Composer options' }))
const item = await screen.findByRole('menuitem', { name: /Sandbox resources/ })
await user.click(item)
await screen.findByRole('dialog')
}
it('hides the resources item when the session is not sandboxed', async () => {
const user = userEvent.setup()
mockSandbox({ sandboxed: false })
renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument()
})
it('hides the resources item for a child session', async () => {
const user = userEvent.setup()
mockSandbox({ sandboxed: true, lockedReason: 'child' })
renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument()
})
it('hides the resources item when sandboxing is unavailable', async () => {
const user = userEvent.setup()
mockSandbox({ sandboxed: true, available: false })
renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ })
expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument()
})
it('shows the effective values with a custom marker when an override exists', async () => {
const user = userEvent.setup()
mockSandbox({
sandboxed: true,
resources: { cpus: 8, memoryMib: 2048 },
effectiveResources: { cpus: 8, memoryMib: 2048 },
})
renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
const item = await screen.findByRole('menuitem', { name: /Sandbox resources/ })
expect(item).toHaveTextContent('8 CPUs · 2 GiB · custom')
})
it('prefills the dialog from the override', async () => {
const user = userEvent.setup()
mockSandbox({
sandboxed: true,
resources: { cpus: 8, memoryMib: 2048 },
effectiveResources: { cpus: 8, memoryMib: 2048 },
})
renderMenu()
await openResources(user)
expect(screen.getByLabelText('CPUs')).toHaveValue(8)
expect(screen.getByLabelText('Memory (GiB)')).toHaveValue(2)
})
it('prefills the dialog from the effective values without an override', async () => {
const user = userEvent.setup()
mockSandbox({ sandboxed: true, resources: null, effectiveResources: { cpus: 2, memoryMib: 4096 } })
renderMenu()
await openResources(user)
expect(screen.getByLabelText('CPUs')).toHaveValue(2)
expect(screen.getByLabelText('Memory (GiB)')).toHaveValue(4)
})
it('saves the entered resources', async () => {
const user = userEvent.setup()
const { mutateAsync } = mockSandbox({
sandboxed: true,
resources: null,
effectiveResources: { cpus: 2, memoryMib: 4096 },
})
renderMenu()
await openResources(user)
const cpus = screen.getByLabelText('CPUs')
await user.clear(cpus)
await user.type(cpus, '4')
const memory = screen.getByLabelText('Memory (GiB)')
await user.clear(memory)
await user.type(memory, '3')
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(mutateAsync).toHaveBeenCalledWith({ resources: { cpus: 4, memoryMib: 3072 } })
})
it('clears the override with Use defaults', async () => {
const user = userEvent.setup()
const { mutateAsync } = mockSandbox({
sandboxed: true,
resources: { cpus: 8, memoryMib: 2048 },
effectiveResources: { cpus: 8, memoryMib: 2048 },
})
renderMenu()
await openResources(user)
await user.click(screen.getByRole('button', { name: 'Use defaults' }))
expect(mutateAsync).toHaveBeenCalledWith({ resources: null })
})
it('shows the server error when saving resources fails', async () => {
const user = userEvent.setup()
mockSandbox(
{ sandboxed: true, resources: null, effectiveResources: { cpus: 2, memoryMib: 4096 } },
vi.fn().mockRejectedValue(new FetchError('Requested resources exceed the host', 400)),
)
renderMenu()
await openResources(user)
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(await screen.findByRole('alert')).toHaveTextContent('Requested resources exceed the host')
})
})
@@ -1,4 +1,4 @@
import type { ReactNode } from 'react'
import { useState } from 'react'
import { Mic, Paperclip, Plus, Shield, ShieldCheck, Target } from 'lucide-react'
import {
DropdownMenu,
@@ -10,6 +10,11 @@ import {
} from '@/components/ui/dropdown-menu'
import { getIconToggleButtonClassName } from '@/components/ui/icon-toggle-button'
import { usePermissionModeToggle } from '@/hooks/usePermissionModeToggle'
import { useSandboxToggle } from '@/hooks/useSandboxToggle'
import { shouldShowSandboxResources } from '@/lib/sandboxResources'
import { SandboxMenuItems } from './SandboxMenuItems'
import { ToolMenuItemContent } from './ToolMenuItemContent'
import { SessionSandboxResourcesDialog } from './SessionSandboxResourcesDialog'
interface ComposerToolsMenuProps {
sessionID: string
@@ -33,60 +38,62 @@ export function ComposerToolsMenu({
onDictate,
}: ComposerToolsMenuProps) {
const permission = usePermissionModeToggle(sessionID, directory)
const sandbox = useSandboxToggle(sessionID)
const [resourcesOpen, setResourcesOpen] = useState(false)
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label="Composer options"
title="Composer options"
className={`${getIconToggleButtonClassName(permission.isAuto || goalArmed)} flex items-center justify-center min-h-[44px] min-w-[44px]`}
>
<Plus className="w-5 h-5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="end" collisionPadding={8} className="w-64">
<DropdownMenuCheckboxItem
checked={permission.isAuto}
disabled={permission.disabled}
onCheckedChange={permission.toggle}
>
<ToolMenuItemContent
icon={permission.isAuto ? <ShieldCheck className="h-4 w-4" /> : <Shield className="h-4 w-4" />}
title="Accept all permissions"
detail={permission.disabled ? permission.label : undefined}
/>
</DropdownMenuCheckboxItem>
<DropdownMenuCheckboxItem checked={goalArmed} disabled={goalDisabled} onCheckedChange={onToggleGoal}>
<ToolMenuItemContent
icon={<Target className="h-4 w-4" />}
title="Goal mode"
detail={goalDisabled ? goalLabel : undefined}
/>
</DropdownMenuCheckboxItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={onAttachFile} className="pl-8">
<ToolMenuItemContent icon={<Paperclip className="h-4 w-4" />} title="Attach image or PDF" />
</DropdownMenuItem>
{onDictate ? (
<DropdownMenuItem onSelect={onDictate} className="pl-8">
<ToolMenuItemContent icon={<Mic className="h-4 w-4" />} title="Dictate" />
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label="Composer options"
title="Composer options"
className={`${getIconToggleButtonClassName(permission.isAuto || sandbox.isSandboxed || goalArmed)} flex items-center justify-center min-h-[44px] min-w-[44px]`}
>
<Plus className="w-5 h-5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="end" collisionPadding={8} className="w-64">
<DropdownMenuCheckboxItem
checked={permission.isAuto}
disabled={permission.disabled}
onCheckedChange={permission.toggle}
>
<ToolMenuItemContent
icon={permission.isAuto ? <ShieldCheck className="h-4 w-4" /> : <Shield className="h-4 w-4" />}
title="Accept all permissions"
detail={permission.disabled ? permission.label : undefined}
/>
</DropdownMenuCheckboxItem>
<SandboxMenuItems sandbox={sandbox} onOpenResources={() => setResourcesOpen(true)} />
<DropdownMenuCheckboxItem checked={goalArmed} disabled={goalDisabled} onCheckedChange={onToggleGoal}>
<ToolMenuItemContent
icon={<Target className="h-4 w-4" />}
title="Goal mode"
detail={goalDisabled ? goalLabel : undefined}
/>
</DropdownMenuCheckboxItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={onAttachFile} className="pl-8">
<ToolMenuItemContent icon={<Paperclip className="h-4 w-4" />} title="Attach image or PDF" />
</DropdownMenuItem>
) : null}
</DropdownMenuContent>
</DropdownMenu>
)
}
function ToolMenuItemContent({ icon, title, detail }: { icon: ReactNode; title: string; detail?: string }) {
return (
<span className="flex items-start gap-2">
<span className="mt-0.5 shrink-0">{icon}</span>
<span className="flex min-w-0 flex-col">
<span>{title}</span>
{detail ? <span className="text-xs text-muted-foreground">{detail}</span> : null}
</span>
</span>
{onDictate ? (
<DropdownMenuItem onSelect={onDictate} className="pl-8">
<ToolMenuItemContent icon={<Mic className="h-4 w-4" />} title="Dictate" />
</DropdownMenuItem>
) : null}
</DropdownMenuContent>
</DropdownMenu>
{shouldShowSandboxResources(sandbox) ? (
<SessionSandboxResourcesDialog
sessionID={sessionID}
open={resourcesOpen}
onOpenChange={setResourcesOpen}
override={sandbox.resources}
effective={sandbox.effectiveResources!}
/>
) : null}
</>
)
}
@@ -111,6 +111,10 @@ vi.mock('./ComposerToolsMenu', () => ({
ComposerToolsMenu: () => null,
}))
vi.mock('@/components/session/SessionSandboxMenu', () => ({
SessionSandboxMenu: () => null,
}))
vi.mock('./PromptSuggestions', () => ({
PromptSuggestions: (props: { isOpen: boolean; selectedIndex: number }) => {
if (props.isOpen) {
@@ -118,6 +118,10 @@ vi.mock('./ComposerToolsMenu', () => ({
),
}))
vi.mock('@/components/session/SessionSandboxMenu', () => ({
SessionSandboxMenu: () => null,
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
@@ -107,6 +107,10 @@ vi.mock('./ComposerToolsMenu', () => ({
ComposerToolsMenu: () => null,
}))
vi.mock('@/components/session/SessionSandboxMenu', () => ({
SessionSandboxMenu: () => null,
}))
const createTestQueryClient = () => new QueryClient({
defaultOptions: {
queries: { retry: false },
@@ -108,6 +108,10 @@ vi.mock('./ComposerToolsMenu', () => ({
ComposerToolsMenu: () => null,
}))
vi.mock('@/components/session/SessionSandboxMenu', () => ({
SessionSandboxMenu: () => null,
}))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: () => ({ data: undefined }),
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
@@ -29,6 +29,7 @@ import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
import { VoiceStatusOverlay, type VoiceStatusOverlayState } from './VoiceStatusOverlay'
import { PermissionModeToggle } from '@/components/session/PermissionModeToggle'
import { SessionSandboxMenu } from '@/components/session/SessionSandboxMenu'
import { ComposerToolsMenu } from './ComposerToolsMenu'
import { useSessionGoal, useStartSessionGoal } from '@/hooks/useSessionGoals'
import { useSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
@@ -1579,6 +1580,7 @@ return (
{directory && !isMobile && (
<>
<PermissionModeToggle sessionID={sessionID} directory={directory} />
<SessionSandboxMenu sessionID={sessionID} />
<IconToggleButton
active={isGoalArmed}
label={goalButtonLabel}
@@ -0,0 +1,38 @@
import { Box, Cpu } from 'lucide-react'
import { DropdownMenuCheckboxItem, DropdownMenuItem } from '@/components/ui/dropdown-menu'
import { formatSandboxResources, shouldShowSandboxResources, type SandboxToggleState } from '@/lib/sandboxResources'
import { ToolMenuItemContent } from './ToolMenuItemContent'
interface SandboxMenuItemsProps {
sandbox: SandboxToggleState
onOpenResources: () => void
}
export function SandboxMenuItems({ sandbox, onOpenResources }: SandboxMenuItemsProps) {
return (
<>
{sandbox.available ? (
<DropdownMenuCheckboxItem
checked={sandbox.isSandboxed}
disabled={sandbox.disabled}
onCheckedChange={sandbox.toggle}
>
<ToolMenuItemContent
icon={<Box className="h-4 w-4" />}
title="Sandbox commands"
detail={sandbox.disabled ? sandbox.label : undefined}
/>
</DropdownMenuCheckboxItem>
) : null}
{shouldShowSandboxResources(sandbox) ? (
<DropdownMenuItem className="pl-8" aria-haspopup="dialog" onSelect={() => setTimeout(onOpenResources, 0)}>
<ToolMenuItemContent
icon={<Cpu className="h-4 w-4" />}
title="Sandbox resources…"
detail={`${formatSandboxResources(sandbox.effectiveResources!)}${sandbox.resources ? ' · custom' : ''}`}
/>
</DropdownMenuItem>
) : null}
</>
)
}
@@ -0,0 +1,94 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SessionSandboxResourcesDialog } from './SessionSandboxResourcesDialog'
import { useSetSessionSandbox } from '@/hooks/useSessionSandbox'
import type { SessionSandboxResources } from '@opencode-manager/shared/schemas'
vi.mock('@/hooks/useSessionSandbox')
function mockSetSessionSandbox() {
vi.mocked(useSetSessionSandbox).mockReturnValue({
mutate: vi.fn(),
mutateAsync: vi.fn().mockResolvedValue(undefined),
isPending: false,
} as unknown as ReturnType<typeof useSetSessionSandbox>)
}
interface DialogProps {
open: boolean
override: SessionSandboxResources | null
effective: SessionSandboxResources
}
function renderDialog(props: DialogProps) {
return render(
<SessionSandboxResourcesDialog
sessionID="ses_1"
open={props.open}
onOpenChange={vi.fn()}
override={props.override}
effective={props.effective}
/>,
)
}
describe('SessionSandboxResourcesDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
mockSetSessionSandbox()
})
it('keeps a typed value when the effective resources change while open', async () => {
const user = userEvent.setup()
const { rerender } = renderDialog({ open: true, override: null, effective: { cpus: 2, memoryMib: 4096 } })
const cpus = screen.getByLabelText('CPUs')
await user.clear(cpus)
await user.type(cpus, '8')
rerender(
<SessionSandboxResourcesDialog
sessionID="ses_1"
open
onOpenChange={vi.fn()}
override={null}
effective={{ cpus: 4, memoryMib: 8192 }}
/>,
)
expect(screen.getByLabelText('CPUs')).toHaveValue(8)
})
it('re-initializes the draft from the resources when reopened', async () => {
const user = userEvent.setup()
const { rerender } = renderDialog({ open: true, override: null, effective: { cpus: 2, memoryMib: 4096 } })
const cpus = screen.getByLabelText('CPUs')
await user.clear(cpus)
await user.type(cpus, '8')
rerender(
<SessionSandboxResourcesDialog
sessionID="ses_1"
open={false}
onOpenChange={vi.fn()}
override={null}
effective={{ cpus: 2, memoryMib: 4096 }}
/>,
)
rerender(
<SessionSandboxResourcesDialog
sessionID="ses_1"
open
onOpenChange={vi.fn()}
override={{ cpus: 4, memoryMib: 8192 }}
effective={{ cpus: 2, memoryMib: 4096 }}
/>,
)
expect(screen.getByLabelText('CPUs')).toHaveValue(4)
expect(screen.getByLabelText('Memory (GiB)')).toHaveValue(8)
})
})
@@ -0,0 +1,113 @@
import { useEffect, useRef, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useSetSessionSandbox } from '@/hooks/useSessionSandbox'
import { FetchError } from '@/api/fetchWrapper'
import { formatSandboxMemory } from '@/lib/sandboxResources'
import { SessionSandboxResourcesSchema, type SessionSandboxResources } from '@opencode-manager/shared/schemas'
interface SessionSandboxResourcesDialogProps {
sessionID: string
open: boolean
onOpenChange: (open: boolean) => void
override: SessionSandboxResources | null
effective: SessionSandboxResources
}
export function SessionSandboxResourcesDialog({
sessionID,
open,
onOpenChange,
override,
effective,
}: SessionSandboxResourcesDialogProps) {
const setSandbox = useSetSessionSandbox(sessionID)
const [cpus, setCpus] = useState('')
const [memoryGib, setMemoryGib] = useState('')
const [error, setError] = useState<string | null>(null)
const wasOpen = useRef(false)
useEffect(() => {
if (open && !wasOpen.current) {
const source = override ?? effective
setCpus(String(source.cpus))
setMemoryGib(formatSandboxMemory(source.memoryMib))
setError(null)
}
wasOpen.current = open
}, [open, override, effective])
const submit = async (resources: SessionSandboxResources | null) => {
setError(null)
try {
await setSandbox.mutateAsync({ resources })
onOpenChange(false)
} catch (err) {
setError(err instanceof FetchError ? err.message : 'Failed to update sandbox resources')
}
}
const handleSave = () => {
const memoryMib = Math.round(Number(memoryGib.trim()) * 1024)
const parsed = SessionSandboxResourcesSchema.safeParse({ cpus: Number(cpus.trim()), memoryMib })
if (!parsed.success) {
setError('CPUs must be a whole number from 1 to 64 and memory must be at least 1 GiB')
return
}
void submit(parsed.data)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[90%] sm:max-w-sm">
<DialogHeader>
<DialogTitle>Sandbox resources</DialogTitle>
<DialogDescription>
CPU and memory changes apply on this session's next sandboxed command and recreate its VM. The Docker
data volume is kept.
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<div className="space-y-1">
<Label htmlFor="sessionSandboxCpus">CPUs</Label>
<Input
id="sessionSandboxCpus"
type="number"
min={1}
max={64}
step={1}
value={cpus}
onChange={(event) => setCpus(event.target.value)}
/>
</div>
<div className="space-y-1">
<Label htmlFor="sessionSandboxMemory">Memory (GiB)</Label>
<Input
id="sessionSandboxMemory"
type="number"
min={1}
step={0.5}
value={memoryGib}
onChange={(event) => setMemoryGib(event.target.value)}
/>
</div>
{error ? (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
) : null}
</div>
<DialogFooter className="gap-2">
<Button variant="outline" onClick={() => void submit(null)} disabled={setSandbox.isPending}>
Use defaults
</Button>
<Button onClick={handleSave} disabled={setSandbox.isPending}>
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -265,6 +265,31 @@ describe('ToolCallPart background indicator', () => {
await waitFor(() => expect(screen.getByText('✓')).toBeInTheDocument())
expect(screen.queryByText('background')).not.toBeInTheDocument()
})
it('labels a sandboxed command with a non-manager provider', () => {
renderWithProviders(
<ToolCallPart part={completedShell({ sandbox: true, sandboxProvider: 'forge' })} messageID="msg_1" />,
)
const badge = screen.getByText('sandbox · forge')
expect(badge).toHaveAttribute('title', 'Executed inside the forge sandbox')
})
it('keeps the plain sandbox label for the manager provider', () => {
renderWithProviders(
<ToolCallPart part={completedShell({ sandbox: true, sandboxProvider: 'ocm' })} messageID="msg_1" />,
)
const badge = screen.getByText('sandbox')
expect(badge).toHaveAttribute('title', 'Executed inside the sandbox microVM')
})
it('keeps the plain sandbox label when no provider is reported', () => {
renderWithProviders(<ToolCallPart part={completedShell({ sandbox: true })} messageID="msg_1" />)
const badge = screen.getByText('sandbox')
expect(badge).toHaveAttribute('title', 'Executed inside the sandbox microVM')
})
})
describe('ToolCallPart open walkthrough action', () => {
@@ -161,6 +161,11 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
part.state.status === 'completed' &&
(toolMetadata(part).sandbox === true ||
(rawCommand !== undefined && displayCommand !== rawCommand))
const sandboxProvider = (() => {
const provider = toolMetadata(part).sandboxProvider
return typeof provider === 'string' ? provider : undefined
})()
const sandboxProviderLabel = sandboxProvider !== undefined && sandboxProvider !== 'ocm' ? sandboxProvider : undefined
const isUserBashCommand = part.state.status === 'completed' &&
typeof displayCommand === 'string' &&
userBashCommands.has(displayCommand)
@@ -250,10 +255,14 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
<Badge
variant="outline"
className="shrink-0 gap-1 border-success/40 bg-success/15 text-success"
title="Executed inside the sandbox microVM"
title={
sandboxProviderLabel !== undefined
? `Executed inside the ${sandboxProviderLabel} sandbox`
: 'Executed inside the sandbox microVM'
}
>
<Shield className="w-3 h-3" />
sandbox
{sandboxProviderLabel !== undefined ? `sandbox · ${sandboxProviderLabel}` : 'sandbox'}
</Badge>
) : null
@@ -0,0 +1,19 @@
import type { ReactNode } from 'react'
interface ToolMenuItemContentProps {
icon: ReactNode
title: string
detail?: string
}
export function ToolMenuItemContent({ icon, title, detail }: ToolMenuItemContentProps) {
return (
<span className="flex items-start gap-2">
<span className="mt-0.5 shrink-0">{icon}</span>
<span className="flex min-w-0 flex-col">
<span>{title}</span>
{detail ? <span className="text-xs text-muted-foreground">{detail}</span> : null}
</span>
</span>
)
}
@@ -0,0 +1,132 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SessionSandboxMenu } from './SessionSandboxMenu'
import { useSessionSandbox, useSetSessionSandbox } from '@/hooks/useSessionSandbox'
import type { SessionSandboxState } from '@opencode-manager/shared/schemas'
vi.mock('@/hooks/useSessionSandbox')
const baseSandboxState: SessionSandboxState = {
sessionId: 'ses_1',
rootSessionId: 'ses_1',
sandboxed: false,
source: 'default',
resources: null,
effectiveResources: { cpus: 2, memoryMib: 4096 },
lockedReason: null,
available: true,
}
function mockSandbox(
state: Partial<SessionSandboxState> = {},
mutateAsync = vi.fn().mockResolvedValue(undefined),
) {
const mutate = vi.fn()
vi.mocked(useSessionSandbox).mockReturnValue({
data: { ...baseSandboxState, ...state },
isError: false,
} as ReturnType<typeof useSessionSandbox>)
vi.mocked(useSetSessionSandbox).mockReturnValue({
mutate,
mutateAsync,
isPending: false,
} as unknown as ReturnType<typeof useSetSessionSandbox>)
return { mutate, mutateAsync }
}
function renderMenu() {
render(<SessionSandboxMenu sessionID="ses_1" />)
}
describe('SessionSandboxMenu', () => {
beforeEach(() => {
vi.clearAllMocks()
mockSandbox()
})
it('renders nothing when sandboxing is unavailable', () => {
mockSandbox({ available: false })
renderMenu()
expect(screen.queryByRole('button', { name: /Sandbox:/ })).not.toBeInTheDocument()
})
it('reflects the off state in the trigger label', () => {
mockSandbox({ sandboxed: false })
renderMenu()
const trigger = screen.getByRole('button', { name: 'Sandbox: off' })
expect(trigger).not.toHaveClass('bg-highlight')
})
it('reflects the on state in the trigger label', () => {
mockSandbox({ sandboxed: true })
renderMenu()
expect(screen.getByRole('button', { name: 'Sandbox: on' })).toHaveClass('bg-highlight')
})
it('enables sandboxing through the checkbox item', async () => {
const user = userEvent.setup()
const { mutate } = mockSandbox({ sandboxed: false })
renderMenu()
await user.click(screen.getByRole('button', { name: 'Sandbox: off' }))
const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
expect(item).toHaveAttribute('aria-checked', 'false')
await user.click(item)
expect(mutate).toHaveBeenCalledWith({ sandboxed: true })
})
it('disables sandboxing through the checkbox item', async () => {
const user = userEvent.setup()
const { mutate } = mockSandbox({ sandboxed: true })
renderMenu()
await user.click(screen.getByRole('button', { name: 'Sandbox: on' }))
const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
expect(item).toHaveAttribute('aria-checked', 'true')
await user.click(item)
expect(mutate).toHaveBeenCalledWith({ sandboxed: false })
})
it('hides the resources item when the session is not sandboxed', async () => {
const user = userEvent.setup()
mockSandbox({ sandboxed: false })
renderMenu()
await user.click(screen.getByRole('button', { name: 'Sandbox: off' }))
await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument()
})
it('opens the resources dialog from the menu item', async () => {
const user = userEvent.setup()
mockSandbox({ sandboxed: true, effectiveResources: { cpus: 2, memoryMib: 4096 } })
renderMenu()
await user.click(screen.getByRole('button', { name: 'Sandbox: on' }))
const item = await screen.findByRole('menuitem', { name: /Sandbox resources/ })
await user.click(item)
expect(await screen.findByRole('dialog')).toBeInTheDocument()
expect(screen.getByLabelText('CPUs')).toHaveValue(2)
})
it('disables the checkbox and explains inheritance for a child session', async () => {
const user = userEvent.setup()
mockSandbox({ sandboxed: true, lockedReason: 'child' })
renderMenu()
await user.click(screen.getByRole('button', { name: /Inherited from parent session/ }))
const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
expect(item).toHaveAttribute('aria-disabled', 'true')
expect(item).toHaveTextContent('Inherited from parent session')
expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument()
})
})
@@ -0,0 +1,52 @@
import { useState } from 'react'
import { Box } from 'lucide-react'
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { getIconToggleButtonClassName } from '@/components/ui/icon-toggle-button'
import { useSandboxToggle } from '@/hooks/useSandboxToggle'
import { shouldShowSandboxResources } from '@/lib/sandboxResources'
import { SandboxMenuItems } from '@/components/message/SandboxMenuItems'
import { SessionSandboxResourcesDialog } from '@/components/message/SessionSandboxResourcesDialog'
interface SessionSandboxMenuProps {
sessionID: string
}
export function SessionSandboxMenu({ sessionID }: SessionSandboxMenuProps) {
const sandbox = useSandboxToggle(sessionID)
const [resourcesOpen, setResourcesOpen] = useState(false)
if (!sandbox.available) return null
const label = `Sandbox: ${sandbox.isSandboxed ? 'on' : 'off'}${
sandbox.lockedReason === 'child' ? ` (${sandbox.label})` : ''
}`
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label={label}
title={label}
className={getIconToggleButtonClassName(sandbox.isSandboxed)}
>
<Box className="w-5 h-5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start" collisionPadding={8} className="w-64">
<SandboxMenuItems sandbox={sandbox} onOpenResources={() => setResourcesOpen(true)} />
</DropdownMenuContent>
</DropdownMenu>
{shouldShowSandboxResources(sandbox) ? (
<SessionSandboxResourcesDialog
sessionID={sessionID}
open={resourcesOpen}
onOpenChange={setResourcesOpen}
override={sandbox.resources}
effective={sandbox.effectiveResources!}
/>
) : null}
</>
)
}
@@ -84,8 +84,14 @@ describe('SandboxSettings', () => {
await user.click(screen.getByRole('switch', { name: 'Toggle sandbox' }))
expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true, gitCredentials: false } })
expect(screen.getByText('Restart the OpenCode server to apply sandbox changes.')).toBeInTheDocument()
expect(updateSettingsAsync).toHaveBeenCalledWith({
sandbox: { enabled: true, gitCredentials: false, defaultForNewSessions: true },
})
expect(
screen.getByText(
'Restart the OpenCode server to apply changes to sandbox support or git credentials. Per-session sandbox toggles apply immediately.',
),
).toBeInTheDocument()
})
it('disables the switch with a visible reason when microVMs are unavailable', async () => {
@@ -111,7 +117,9 @@ describe('SandboxSettings', () => {
await user.click(toggle)
expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: false, gitCredentials: false } })
expect(updateSettingsAsync).toHaveBeenCalledWith({
sandbox: { enabled: false, gitCredentials: false, defaultForNewSessions: true },
})
})
it('disables the switch while sandbox availability has not been reported', async () => {
@@ -176,7 +184,9 @@ describe('SandboxSettings', () => {
await user.click(screen.getByRole('switch', { name: 'Toggle sandbox' }))
expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true, gitCredentials: true } })
expect(updateSettingsAsync).toHaveBeenCalledWith({
sandbox: { enabled: true, gitCredentials: true, defaultForNewSessions: true },
})
})
it('enables git credential forwarding without changing the sandbox preference', async () => {
@@ -187,7 +197,9 @@ describe('SandboxSettings', () => {
await user.click(screen.getByRole('switch', { name: 'Toggle git credentials in sandbox' }))
expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true, gitCredentials: true } })
expect(updateSettingsAsync).toHaveBeenCalledWith({
sandbox: { enabled: true, gitCredentials: true, defaultForNewSessions: true },
})
})
it('disables the git credential switch while sandboxing is off', async () => {
@@ -198,4 +210,230 @@ describe('SandboxSettings', () => {
expect(screen.getByRole('switch', { name: 'Toggle git credentials in sandbox' })).toBeDisabled()
})
it('hides the default-for-new-sessions switch while sandboxing is off', async () => {
mockUseSettings()
mockHealth({ available: true, enforced: false })
await renderSandbox()
expect(screen.queryByRole('switch', { name: 'Toggle sandbox for new sessions' })).not.toBeInTheDocument()
})
it('saves the default-for-new-sessions preference preserving other fields', async () => {
const { updateSettingsAsync } = mockUseSettings({
preferences: { sandbox: { enabled: true, gitCredentials: true, defaultForNewSessions: true } },
})
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
await user.click(screen.getByRole('switch', { name: 'Toggle sandbox for new sessions' }))
expect(updateSettingsAsync).toHaveBeenCalledWith({
sandbox: { enabled: true, gitCredentials: true, defaultForNewSessions: false },
})
})
it('reflects the persisted default-for-new-sessions preference', async () => {
mockUseSettings({
preferences: { sandbox: { enabled: true, gitCredentials: false, defaultForNewSessions: false } },
})
mockHealth({ available: true, enforced: false })
await renderSandbox()
expect(screen.getByRole('switch', { name: 'Toggle sandbox for new sessions' })).not.toBeChecked()
})
it('renders the resource inputs when sandboxing is enabled', async () => {
mockUseSettings({ preferences: { sandbox: { enabled: true } } })
mockHealth({ available: true, enforced: false })
await renderSandbox()
expect(screen.getByLabelText('Default CPUs')).toBeInTheDocument()
expect(screen.getByLabelText('Default memory (GiB)')).toBeInTheDocument()
expect(screen.getByLabelText('Remove idle sandbox VMs after (minutes)')).toBeInTheDocument()
expect(screen.getByLabelText('Max running sandbox VMs')).toBeInTheDocument()
})
it('hides the resource inputs while sandboxing is off', async () => {
mockUseSettings()
mockHealth({ available: true, enforced: false })
await renderSandbox()
expect(screen.queryByLabelText('Default CPUs')).not.toBeInTheDocument()
expect(screen.queryByLabelText('Max running sandbox VMs')).not.toBeInTheDocument()
})
it('saves CPUs while preserving the other sandbox fields', async () => {
const { updateSettingsAsync } = mockUseSettings({
preferences: {
sandbox: {
enabled: true,
gitCredentials: true,
defaultForNewSessions: false,
idleStopMinutes: 45,
maxRunningVms: 6,
},
},
})
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
const cpus = screen.getByLabelText('Default CPUs')
await user.clear(cpus)
await user.type(cpus, '8')
await user.tab()
expect(updateSettingsAsync).toHaveBeenCalledWith({
sandbox: {
enabled: true,
gitCredentials: true,
defaultForNewSessions: false,
idleStopMinutes: 45,
maxRunningVms: 6,
cpus: 8,
},
})
})
it('saves memory in MiB from the GiB input', async () => {
const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true } } })
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
const memory = screen.getByLabelText('Default memory (GiB)')
await user.type(memory, '2.5')
await user.tab()
expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true, memoryMib: 2560 } })
})
it('omits CPUs when cleared to use the server default', async () => {
const { updateSettingsAsync } = mockUseSettings({
preferences: { sandbox: { enabled: true, cpus: 4, memoryMib: 4096 } },
})
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
await user.clear(screen.getByLabelText('Default CPUs'))
await user.tab()
expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true, memoryMib: 4096 } })
})
it('omits memory when cleared to use the server default', async () => {
const { updateSettingsAsync } = mockUseSettings({
preferences: { sandbox: { enabled: true, cpus: 4, memoryMib: 4096 } },
})
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
await user.clear(screen.getByLabelText('Default memory (GiB)'))
await user.tab()
expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true, cpus: 4 } })
})
it('rejects out-of-range CPUs, keeps the stored value, and warns', async () => {
const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true, cpus: 4 } } })
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
const cpus = screen.getByLabelText('Default CPUs')
await user.clear(cpus)
await user.type(cpus, '999')
await user.tab()
expect(updateSettingsAsync).not.toHaveBeenCalled()
expect(vi.mocked(showToast.error)).toHaveBeenCalledWith('Default CPUs must be a whole number from 1 to 64')
expect(screen.getByLabelText('Default CPUs')).toHaveValue(4)
})
it('rejects out-of-range memory and warns', async () => {
const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true } } })
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
const memory = screen.getByLabelText('Default memory (GiB)')
await user.type(memory, '0.5')
await user.tab()
expect(updateSettingsAsync).not.toHaveBeenCalled()
expect(vi.mocked(showToast.error)).toHaveBeenCalledWith('Default memory must be between 1 and 1024 GiB')
})
it('shows the backend error when the resource preference is rejected', async () => {
mockUseSettings({
preferences: { sandbox: { enabled: true } },
updateSettingsAsync: vi.fn().mockRejectedValue(new FetchError('Default memory exceeds the host memory', 400)),
})
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
const memory = screen.getByLabelText('Default memory (GiB)')
await user.type(memory, '64')
await user.tab()
expect(vi.mocked(showToast.error)).toHaveBeenCalledWith('Default memory exceeds the host memory')
})
it('does not save CPUs when blurred without a change', async () => {
const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true, cpus: 4 } } })
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
const cpus = screen.getByLabelText('Default CPUs')
await user.click(cpus)
await user.tab()
expect(updateSettingsAsync).not.toHaveBeenCalled()
expect(vi.mocked(showToast.success)).not.toHaveBeenCalled()
expect(vi.mocked(showToast.error)).not.toHaveBeenCalled()
})
it('does not save CPUs when a blank value already uses the server default', async () => {
const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true } } })
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
const cpus = screen.getByLabelText('Default CPUs')
await user.click(cpus)
await user.tab()
expect(updateSettingsAsync).not.toHaveBeenCalled()
expect(vi.mocked(showToast.success)).not.toHaveBeenCalled()
})
it('does not save memory when blurred without a change', async () => {
const { updateSettingsAsync } = mockUseSettings({
preferences: { sandbox: { enabled: true, memoryMib: 4096 } },
})
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
const memory = screen.getByLabelText('Default memory (GiB)')
await user.click(memory)
await user.tab()
expect(updateSettingsAsync).not.toHaveBeenCalled()
expect(vi.mocked(showToast.success)).not.toHaveBeenCalled()
})
it('does not save idle stop or max running VMs when blurred at the defaults', async () => {
const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true } } })
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
await user.click(screen.getByLabelText('Remove idle sandbox VMs after (minutes)'))
await user.tab()
await user.click(screen.getByLabelText('Max running sandbox VMs'))
await user.tab()
expect(updateSettingsAsync).not.toHaveBeenCalled()
expect(vi.mocked(showToast.success)).not.toHaveBeenCalled()
})
})
@@ -1,12 +1,52 @@
import { useEffect, useState } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { useServerHealth } from '@/hooks/useServerHealth'
import { Switch } from '@/components/ui/switch'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Box, RotateCcw } from 'lucide-react'
import { showToast } from '@/lib/toast'
import { FetchError } from '@/api/fetchWrapper'
import { SettingsDisclosure } from './SettingsDisclosure'
import {
DEFAULT_SANDBOX_IDLE_STOP_MINUTES,
DEFAULT_SANDBOX_MAX_RUNNING_VMS,
SandboxPreferencesSchema,
SessionSandboxResourcesSchema,
type SandboxPreferences,
} from '@opencode-manager/shared/schemas'
const cpusSchema = SessionSandboxResourcesSchema.shape.cpus
const memoryMibSchema = SessionSandboxResourcesSchema.shape.memoryMib
const idleStopSchema = SandboxPreferencesSchema.shape.idleStopMinutes.unwrap()
const maxRunningVmsSchema = SandboxPreferencesSchema.shape.maxRunningVms.unwrap()
const SANDBOX_CPUS_MIN = cpusSchema.minValue ?? 1
const SANDBOX_CPUS_MAX = cpusSchema.maxValue ?? 64
const SANDBOX_MEMORY_GIB_MIN = (memoryMibSchema.minValue ?? 1024) / 1024
const SANDBOX_MEMORY_GIB_MAX = (memoryMibSchema.maxValue ?? 1048576) / 1024
const SANDBOX_IDLE_MINUTES_MIN = idleStopSchema.minValue ?? 1
const SANDBOX_IDLE_MINUTES_MAX = idleStopSchema.maxValue ?? 1440
const SANDBOX_MAX_VMS_MIN = maxRunningVmsSchema.minValue ?? 1
const SANDBOX_MAX_VMS_MAX = maxRunningVmsSchema.maxValue ?? 32
interface SandboxDraft {
cpus: string
memoryGib: string
idleStopMinutes: string
maxRunningVms: string
}
function toDraft(sandbox: SandboxPreferences | undefined): SandboxDraft {
return {
cpus: sandbox?.cpus !== undefined ? String(sandbox.cpus) : '',
memoryGib: sandbox?.memoryMib !== undefined ? String(sandbox.memoryMib / 1024) : '',
idleStopMinutes: String(sandbox?.idleStopMinutes ?? DEFAULT_SANDBOX_IDLE_STOP_MINUTES),
maxRunningVms: String(sandbox?.maxRunningVms ?? DEFAULT_SANDBOX_MAX_RUNNING_VMS),
}
}
export function SandboxSettings() {
const { preferences, updateSettingsAsync, isUpdating } = useSettings()
@@ -14,12 +54,21 @@ export function SandboxSettings() {
const sandbox = health?.sandbox
const isAvailable = sandbox?.available === true
const enabled = preferences?.sandbox?.enabled ?? false
const gitCredentials = preferences?.sandbox?.gitCredentials ?? false
const sandboxPreferences = preferences?.sandbox
const enabled = sandboxPreferences?.enabled ?? false
const gitCredentials = sandboxPreferences?.gitCredentials ?? false
const defaultForNewSessions = sandboxPreferences?.defaultForNewSessions ?? true
const saveSandbox = async (next: { enabled: boolean; gitCredentials: boolean }, message: string) => {
const [draft, setDraft] = useState<SandboxDraft>(() => toDraft(sandboxPreferences))
useEffect(() => {
setDraft(toDraft(sandboxPreferences))
}, [sandboxPreferences])
const saveSandbox = async (patch: Partial<SandboxPreferences>, message: string) => {
try {
await updateSettingsAsync({ sandbox: next })
const baseSandbox: SandboxPreferences = { ...sandboxPreferences, enabled: sandboxPreferences?.enabled ?? false }
await updateSettingsAsync({ sandbox: { ...baseSandbox, ...patch } })
showToast.success(message)
} catch (error) {
showToast.error(error instanceof FetchError ? error.message : 'Failed to update sandbox preference')
@@ -27,14 +76,104 @@ export function SandboxSettings() {
}
const handleToggle = (next: boolean) =>
saveSandbox({ enabled: next, gitCredentials }, next ? 'Sandboxing enabled' : 'Sandboxing disabled')
saveSandbox(
{ enabled: next, gitCredentials, defaultForNewSessions },
next ? 'Sandboxing enabled' : 'Sandboxing disabled',
)
const handleGitCredentialsToggle = (next: boolean) =>
saveSandbox(
{ enabled, gitCredentials: next },
{ enabled, gitCredentials: next, defaultForNewSessions },
next ? 'Git credentials will be forwarded into the sandbox' : 'Git credential forwarding disabled',
)
const handleDefaultForNewSessionsToggle = (next: boolean) =>
saveSandbox(
{ enabled, gitCredentials, defaultForNewSessions: next },
next ? 'New sessions will start sandboxed' : 'New sessions will start unsandboxed',
)
const commitCpus = () => {
const trimmed = draft.cpus.trim()
if (trimmed === '') {
if (sandboxPreferences?.cpus === undefined) return
void saveSandbox({ cpus: undefined }, 'Default CPUs reset to the server default')
return
}
const value = Number(trimmed)
if (!Number.isInteger(value) || !cpusSchema.safeParse(value).success) {
showToast.error(`Default CPUs must be a whole number from ${SANDBOX_CPUS_MIN} to ${SANDBOX_CPUS_MAX}`)
setDraft((current) => ({
...current,
cpus: sandboxPreferences?.cpus !== undefined ? String(sandboxPreferences.cpus) : '',
}))
return
}
if (value === sandboxPreferences?.cpus) return
void saveSandbox({ cpus: value }, 'Default CPUs saved')
}
const commitMemory = () => {
const trimmed = draft.memoryGib.trim()
if (trimmed === '') {
if (sandboxPreferences?.memoryMib === undefined) return
void saveSandbox({ memoryMib: undefined }, 'Default memory reset to the server default')
return
}
const gib = Number(trimmed)
const memoryMib = Math.round(gib * 1024)
if (!Number.isFinite(gib) || !memoryMibSchema.safeParse(memoryMib).success) {
showToast.error(
`Default memory must be between ${SANDBOX_MEMORY_GIB_MIN} and ${SANDBOX_MEMORY_GIB_MAX} GiB`,
)
setDraft((current) => ({
...current,
memoryGib: sandboxPreferences?.memoryMib !== undefined ? String(sandboxPreferences.memoryMib / 1024) : '',
}))
return
}
if (memoryMib === sandboxPreferences?.memoryMib) return
void saveSandbox({ memoryMib }, 'Default memory saved')
}
const commitIdleStopMinutes = () => {
const value = Number(draft.idleStopMinutes.trim())
if (!Number.isInteger(value) || !idleStopSchema.safeParse(value).success) {
showToast.error(
`Idle stop must be a whole number from ${SANDBOX_IDLE_MINUTES_MIN} to ${SANDBOX_IDLE_MINUTES_MAX} minutes`,
)
setDraft((current) => ({
...current,
idleStopMinutes: String(sandboxPreferences?.idleStopMinutes ?? DEFAULT_SANDBOX_IDLE_STOP_MINUTES),
}))
return
}
if (value === (sandboxPreferences?.idleStopMinutes ?? DEFAULT_SANDBOX_IDLE_STOP_MINUTES)) return
void saveSandbox({ idleStopMinutes: value }, 'Idle removal timeout saved')
}
const commitMaxRunningVms = () => {
const value = Number(draft.maxRunningVms.trim())
if (!Number.isInteger(value) || !maxRunningVmsSchema.safeParse(value).success) {
showToast.error(
`Max running sandbox VMs must be a whole number from ${SANDBOX_MAX_VMS_MIN} to ${SANDBOX_MAX_VMS_MAX}`,
)
setDraft((current) => ({
...current,
maxRunningVms: String(sandboxPreferences?.maxRunningVms ?? DEFAULT_SANDBOX_MAX_RUNNING_VMS),
}))
return
}
if (value === (sandboxPreferences?.maxRunningVms ?? DEFAULT_SANDBOX_MAX_RUNNING_VMS)) return
void saveSandbox({ maxRunningVms: value }, 'Max running sandbox VMs saved')
}
const parsedMaxRunningVms = Number(draft.maxRunningVms.trim())
const helperMaxRunningVms =
Number.isInteger(parsedMaxRunningVms) && maxRunningVmsSchema.safeParse(parsedMaxRunningVms).success
? parsedMaxRunningVms
: DEFAULT_SANDBOX_MAX_RUNNING_VMS
return (
<SettingsDisclosure
title="Sandbox"
@@ -85,13 +224,119 @@ export function SandboxSettings() {
aria-label="Toggle git credentials in sandbox"
/>
</div>
{enabled && (
<>
<div className="flex items-start justify-between gap-3 border-t pt-3">
<div className="min-w-0 space-y-0.5">
<p className="text-sm font-semibold">Sandbox new sessions by default</p>
<p className="text-xs text-muted-foreground">
Start new sessions with command sandboxing enabled. Applies immediately and can be changed per
session from the composer.
</p>
</div>
<Switch
checked={defaultForNewSessions}
disabled={isUpdating}
onCheckedChange={handleDefaultForNewSessionsToggle}
aria-label="Toggle sandbox for new sessions"
/>
</div>
<div className="flex items-center justify-between gap-3 border-t pt-3">
<Label htmlFor="sandboxDefaultCpus" className="min-w-0 text-sm font-semibold">
Default CPUs
</Label>
<Input
id="sandboxDefaultCpus"
type="number"
min={SANDBOX_CPUS_MIN}
max={SANDBOX_CPUS_MAX}
step={1}
inputMode="numeric"
placeholder="Server default"
className="w-36 shrink-0"
disabled={isUpdating}
value={draft.cpus}
onChange={(event) => setDraft((current) => ({ ...current, cpus: event.target.value }))}
onBlur={commitCpus}
/>
</div>
<div className="flex items-center justify-between gap-3 border-t pt-3">
<Label htmlFor="sandboxDefaultMemory" className="min-w-0 text-sm font-semibold">
Default memory (GiB)
</Label>
<Input
id="sandboxDefaultMemory"
type="number"
min={SANDBOX_MEMORY_GIB_MIN}
max={SANDBOX_MEMORY_GIB_MAX}
step={0.5}
placeholder="Server default"
className="w-36 shrink-0"
disabled={isUpdating}
value={draft.memoryGib}
onChange={(event) => setDraft((current) => ({ ...current, memoryGib: event.target.value }))}
onBlur={commitMemory}
/>
</div>
<div className="flex items-center justify-between gap-3 border-t pt-3">
<Label htmlFor="sandboxIdleStopMinutes" className="min-w-0 text-sm font-semibold">
Remove idle sandbox VMs after (minutes)
</Label>
<Input
id="sandboxIdleStopMinutes"
type="number"
min={SANDBOX_IDLE_MINUTES_MIN}
max={SANDBOX_IDLE_MINUTES_MAX}
step={1}
inputMode="numeric"
className="w-36 shrink-0"
disabled={isUpdating}
value={draft.idleStopMinutes}
onChange={(event) => setDraft((current) => ({ ...current, idleStopMinutes: event.target.value }))}
onBlur={commitIdleStopMinutes}
/>
</div>
<div className="flex items-center justify-between gap-3 border-t pt-3">
<Label htmlFor="sandboxMaxRunningVms" className="min-w-0 text-sm font-semibold">
Max running sandbox VMs
</Label>
<Input
id="sandboxMaxRunningVms"
type="number"
min={SANDBOX_MAX_VMS_MIN}
max={SANDBOX_MAX_VMS_MAX}
step={1}
inputMode="numeric"
className="w-36 shrink-0"
disabled={isUpdating}
value={draft.maxRunningVms}
onChange={(event) => setDraft((current) => ({ ...current, maxRunningVms: event.target.value }))}
onBlur={commitMaxRunningVms}
/>
</div>
<p className="text-xs text-muted-foreground @min-[1000px]:col-span-2">
Each sandboxed session gets its own microVM that mounts only that session's repository. A VM unused
for this long, or whose session's sandbox is turned off, is removed together with its Docker data, so
installed packages and Docker images are lost; the next sandboxed command creates a fresh VM. At most{' '}
{helperMaxRunningVms} run at once. CPU and memory changes apply on the session's next sandboxed command
and recreate its VM (the Docker data volume is kept).
</p>
</>
)}
</div>
{health?.opencodeRestartPending && (
<Alert>
<RotateCcw className="h-4 w-4" />
<AlertDescription>
Restart the OpenCode server to apply sandbox changes.
Restart the OpenCode server to apply changes to sandbox support or git credentials. Per-session
sandbox toggles apply immediately.
</AlertDescription>
</Alert>
)}
+31
View File
@@ -0,0 +1,31 @@
import { useSessionSandbox, useSetSessionSandbox } from '@/hooks/useSessionSandbox'
export function useSandboxToggle(sessionID: string) {
const { data, isError } = useSessionSandbox(sessionID)
const setSandbox = useSetSessionSandbox(sessionID)
const loaded = data !== undefined
const isSandboxed = data?.sandboxed ?? false
const available = data?.available ?? true
const lockedReason = data?.lockedReason ?? null
const resources = data?.resources ?? null
const effectiveResources = data?.effectiveResources
const disabled = !loaded || lockedReason !== null || setSandbox.isPending
const label = !loaded
? isError
? 'Sandbox: unavailable'
: 'Sandbox: loading'
: lockedReason === 'child'
? 'Inherited from parent session'
: isSandboxed
? 'Sandbox: commands run in a microVM'
: 'Sandbox: commands run on the host'
const toggle = () => {
if (disabled) return
setSandbox.mutate({ sandboxed: !isSandboxed })
}
return { isSandboxed, available, disabled, label, toggle, lockedReason, resources, effectiveResources }
}
+30
View File
@@ -0,0 +1,30 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getSessionSandbox, setSessionSandbox } from '@/api/sessionSandbox'
import { showToast } from '@/lib/toast'
import { FetchError } from '@/api/fetchWrapper'
import type { SessionSandboxState, SetSessionSandboxRequest } from '@opencode-manager/shared/schemas'
function sessionSandboxQueryKey(sessionId: string) {
return ['session-sandbox', sessionId] as const
}
export function useSessionSandbox(sessionId: string) {
return useQuery({
queryKey: sessionSandboxQueryKey(sessionId),
queryFn: () => getSessionSandbox(sessionId),
staleTime: 30000,
})
}
export function useSetSessionSandbox(sessionId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (input: SetSessionSandboxRequest) => setSessionSandbox(sessionId, input),
onSuccess: (state: SessionSandboxState) => {
queryClient.setQueryData(sessionSandboxQueryKey(sessionId), state)
},
onError: (error) => {
showToast.error(error instanceof FetchError ? error.message : 'Failed to update sandbox mode')
},
})
}
+23
View File
@@ -0,0 +1,23 @@
import type { SessionSandboxResources } from '@opencode-manager/shared/schemas'
import type { useSandboxToggle } from '@/hooks/useSandboxToggle'
export type SandboxToggleState = ReturnType<typeof useSandboxToggle>
export function shouldShowSandboxResources(sandbox: SandboxToggleState): boolean {
return (
sandbox.available &&
sandbox.isSandboxed &&
sandbox.lockedReason !== 'child' &&
sandbox.effectiveResources !== undefined
)
}
export function formatSandboxMemory(memoryMib: number): string {
const gib = memoryMib / 1024
return Number.isInteger(gib) ? String(gib) : String(Number(gib.toFixed(1)))
}
export function formatSandboxResources(resources: SessionSandboxResources): string {
const cpus = `${resources.cpus} CPU${resources.cpus === 1 ? '' : 's'}`
return `${cpus} · ${formatSandboxMemory(resources.memoryMib)} GiB`
}
+19 -8
View File
@@ -3,14 +3,22 @@ set -u
lock=/var/run/ocm-dockerd.lock
log=/var/log/dockerd.log
ready_timeout=60
lock_wait=120
ready_timeout=180
lock_wait=240
socket=unix:///var/run/docker.sock
probe() {
timeout 5 env -u DOCKER_HOST -u DOCKER_CONTEXT docker -H "$socket" info >/dev/null 2>&1
}
dockerd_running() {
[ -f /var/run/docker.pid ] && kill -0 "$(cat /var/run/docker.pid)" 2>/dev/null
}
dockerd_alive() {
dockerd_running || pgrep -x dockerd >/dev/null 2>&1
}
probe && exit 0
if [ "$(id -u)" -ne 0 ]; then
@@ -22,15 +30,18 @@ flock -w "$lock_wait" 9 || exit 1
probe && exit 0
if [ -f /var/run/docker.pid ] && kill -0 "$(cat /var/run/docker.pid)" 2>/dev/null; then
:
else
setsid dockerd >"$log" 2>&1 </dev/null 9>&- &
fi
deadline=$(($(date +%s) + ready_timeout))
launched=0
while [ "$(date +%s)" -lt "$deadline" ]; do
probe && exit 0
if ! dockerd_alive; then
if [ "$launched" -eq 0 ]; then
: >"$log"
launched=1
fi
setsid dockerd >>"$log" 2>&1 </dev/null 9>&- &
fi
sleep 1
done
+1
View File
@@ -14,6 +14,7 @@ export * from './skills'
export * from './internal-assistant'
export * from './session-pins'
export * from './session-permissions'
export * from './session-sandbox'
export * from './session-goals'
export * from './internal-sessions'
export * from './multi-runs'
+44
View File
@@ -0,0 +1,44 @@
import { z } from "zod";
export const SessionSandboxResourcesSchema = z.object({
cpus: z.number().int().min(1).max(64),
memoryMib: z.number().int().min(1024).max(1048576),
});
export type SessionSandboxResources = z.infer<typeof SessionSandboxResourcesSchema>;
export const SessionSandboxSourceSchema = z.enum(['default', 'user']);
export type SessionSandboxSource = z.infer<typeof SessionSandboxSourceSchema>;
export const SetSessionSandboxRequestSchema = z
.object({
sandboxed: z.boolean().optional(),
resources: SessionSandboxResourcesSchema.nullable().optional(),
})
.refine((value) => value.sandboxed !== undefined || value.resources !== undefined, {
message: 'At least one of sandboxed or resources is required',
});
export type SetSessionSandboxRequest = z.infer<typeof SetSessionSandboxRequestSchema>;
export const SessionSandboxStateSchema = z.object({
sessionId: z.string(),
rootSessionId: z.string(),
sandboxed: z.boolean(),
source: SessionSandboxSourceSchema,
resources: SessionSandboxResourcesSchema.nullable(),
effectiveResources: SessionSandboxResourcesSchema,
lockedReason: z.enum(["child"]).nullable(),
available: z.boolean(),
});
export type SessionSandboxState = z.infer<typeof SessionSandboxStateSchema>;
export const SessionSandboxClaimSchema = z.object({
sandboxed: z.boolean(),
source: SessionSandboxSourceSchema,
since: z.number(),
});
export type SessionSandboxClaim = z.infer<typeof SessionSandboxClaimSchema>;
+12
View File
@@ -4,6 +4,7 @@ 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";
import { SessionSandboxResourcesSchema } from "./session-sandbox";
export const CustomCommandSchema = z.object({
name: z.string(),
@@ -148,9 +149,17 @@ export const DEFAULT_GIT_IDENTITY: GitIdentity = {
email: '',
};
export const DEFAULT_SANDBOX_IDLE_STOP_MINUTES = 30;
export const DEFAULT_SANDBOX_MAX_RUNNING_VMS = 4;
export const SandboxPreferencesSchema = z.object({
enabled: z.boolean(),
gitCredentials: z.boolean().optional(),
defaultForNewSessions: z.boolean().optional(),
cpus: SessionSandboxResourcesSchema.shape.cpus.optional(),
memoryMib: SessionSandboxResourcesSchema.shape.memoryMib.optional(),
idleStopMinutes: z.number().int().min(1).max(1440).optional(),
maxRunningVms: z.number().int().min(1).max(32).optional(),
});
export type SandboxPreferences = z.infer<typeof SandboxPreferencesSchema>;
@@ -158,6 +167,9 @@ export type SandboxPreferences = z.infer<typeof SandboxPreferencesSchema>;
export const DEFAULT_SANDBOX_PREFERENCES: SandboxPreferences = {
enabled: false,
gitCredentials: false,
defaultForNewSessions: true,
idleStopMinutes: DEFAULT_SANDBOX_IDLE_STOP_MINUTES,
maxRunningVms: DEFAULT_SANDBOX_MAX_RUNNING_VMS,
};
export const SessionDefaultsSchema = z.object({