mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Merge pull request #469 from chriswritescode-dev/feat/schedules-sandbox
feat(schedules): run scheduled jobs in a per-job sandbox microVM
This commit is contained in:
28 files changed
+1147
-83
No files matched your search
@@ -0,0 +1,22 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610251900-schedule-sandbox-config',
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
if (!columns.some((column) => column.name === 'sandbox_config')) {
|
||||
db.run('ALTER TABLE schedule_jobs ADD COLUMN sandbox_config TEXT')
|
||||
}
|
||||
},
|
||||
|
||||
down(db) {
|
||||
db.run('ALTER TABLE schedule_jobs DROP COLUMN sandbox_config')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -41,6 +41,7 @@ import migration202610181400 from './202610181400-secrets'
|
||||
import { secretsGlobalScopeIndexMigration } from './202610181410-secrets-global-scope-index'
|
||||
import migration202610221800 from './202610221800-session-device-name'
|
||||
import migration202610231200 from './202610231200-push-subscription-session-id'
|
||||
import migration202610251900 from './202610251900-schedule-sandbox-config'
|
||||
|
||||
export const allMigrations: Migration[] = [
|
||||
migration001,
|
||||
@@ -85,4 +86,5 @@ export const allMigrations: Migration[] = [
|
||||
secretsGlobalScopeIndexMigration,
|
||||
migration202610221800,
|
||||
migration202610231200,
|
||||
migration202610251900,
|
||||
]
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
ScheduleMcpServersSchema,
|
||||
SchedulePermissionConfigSchema,
|
||||
ScheduleRunSchema,
|
||||
ScheduleSandboxConfigSchema,
|
||||
ScheduleSkillMetadataSchema,
|
||||
ScheduleWorkspaceModeSchema,
|
||||
type ScheduleJob,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
type ScheduleRun,
|
||||
type ScheduleRunStatus,
|
||||
type ScheduleRunTriggerSource,
|
||||
type ScheduleSandboxConfig,
|
||||
type ScheduleWorkspaceMode,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME, ASSISTANT_REPO_PATH, getRepoDisplayName } from '@opencode-manager/shared/utils'
|
||||
@@ -39,6 +41,7 @@ interface ScheduleJobRow {
|
||||
mcp_servers: string | null
|
||||
branch: string | null
|
||||
workspace_mode: ScheduleWorkspaceMode | null
|
||||
sandbox_config: string | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
last_run_at: number | null
|
||||
@@ -107,6 +110,19 @@ function parseMcpServers(raw: string | null): ScheduleMcpServer[] {
|
||||
}
|
||||
}
|
||||
|
||||
function parseSandboxConfig(raw: string | null): ScheduleSandboxConfig | null {
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const result = ScheduleSandboxConfigSchema.safeParse(JSON.parse(raw))
|
||||
return result.success ? result.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeWorkspaceMode(raw: string | null): ScheduleWorkspaceMode {
|
||||
const result = ScheduleWorkspaceModeSchema.safeParse(raw)
|
||||
return result.success ? result.data : 'worktree'
|
||||
@@ -133,6 +149,7 @@ function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob {
|
||||
mcpServers: parseMcpServers(row.mcp_servers),
|
||||
branch: row.branch,
|
||||
workspaceMode: normalizeWorkspaceMode(row.workspace_mode),
|
||||
sandbox: parseSandboxConfig(row.sandbox_config),
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
lastRunAt: row.last_run_at,
|
||||
@@ -183,6 +200,10 @@ function serializeMcpServers(mcpServers: ScheduleJobPersistenceInput['mcpServers
|
||||
return mcpServers.length > 0 ? JSON.stringify(mcpServers) : null
|
||||
}
|
||||
|
||||
function serializeSandboxConfig(sandbox: ScheduleJobPersistenceInput['sandbox']): string | null {
|
||||
return sandbox ? JSON.stringify(sandbox) : null
|
||||
}
|
||||
|
||||
export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJob[] {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id IS ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(repoId) as ScheduleJobRow[]
|
||||
@@ -227,9 +248,10 @@ export function createScheduleJob(
|
||||
mcp_servers,
|
||||
branch,
|
||||
workspace_mode,
|
||||
sandbox_config,
|
||||
created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
const result = stmt.run(
|
||||
@@ -251,6 +273,7 @@ export function createScheduleJob(
|
||||
serializeMcpServers(input.mcpServers),
|
||||
input.branch,
|
||||
input.workspaceMode,
|
||||
serializeSandboxConfig(input.sandbox),
|
||||
now,
|
||||
now,
|
||||
null,
|
||||
@@ -275,7 +298,7 @@ export function updateScheduleJob(db: Database, repoId: number | null, jobId: nu
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_jobs
|
||||
SET name = ?, description = ?, enabled = ?, schedule_mode = ?, interval_minutes = ?, cron_expression = ?, timezone = ?,
|
||||
agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, mcp_servers = ?, branch = ?, workspace_mode = ?, directory = ?, updated_at = ?, next_run_at = ?
|
||||
agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, mcp_servers = ?, branch = ?, workspace_mode = ?, sandbox_config = ?, directory = ?, updated_at = ?, next_run_at = ?
|
||||
WHERE repo_id IS ? AND id = ?
|
||||
`)
|
||||
|
||||
@@ -295,6 +318,7 @@ export function updateScheduleJob(db: Database, repoId: number | null, jobId: nu
|
||||
serializeMcpServers(input.mcpServers),
|
||||
input.branch,
|
||||
input.workspaceMode,
|
||||
serializeSandboxConfig(input.sandbox),
|
||||
input.directory ?? null,
|
||||
now,
|
||||
input.nextRunAt,
|
||||
|
||||
+11
-7
@@ -150,6 +150,7 @@ const gitService = createGitService(gitAuthService)
|
||||
const projectConfigService = new ProjectConfigService(db, gitService, gitAuthService)
|
||||
const secretsService = new SecretsService(db)
|
||||
const repoEnvService = new RepoEnvService(db, projectConfigService, secretsService)
|
||||
const sandboxRuntimeService = new SandboxRuntimeService(db, repoEnvService)
|
||||
let openCodeSupervisor: OpenCodeSupervisor | undefined
|
||||
async function ensureOpenCodeConfigFileExists(): Promise<void> {
|
||||
await withOpenCodeConfigLock(foldLegacyConfigJsonSource)
|
||||
@@ -248,7 +249,7 @@ try {
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
detectSandboxCapability()
|
||||
void new SandboxRuntimeService(db, repoEnvService).prepareSandboxOnBoot().catch((error) => {
|
||||
void sandboxRuntimeService.prepareSandboxOnBoot().catch((error) => {
|
||||
logger.warn('Sandbox preparation failed:', error)
|
||||
})
|
||||
const openCodeStatus = await openCodeSupervisor.start()
|
||||
@@ -279,8 +280,16 @@ const resolveServerTerminalService = (serverId: string): TerminalService => {
|
||||
includeLocalEnv: false,
|
||||
})
|
||||
}
|
||||
const sessionSettingsService = new SettingsService(db)
|
||||
const sessionAncestry = new SessionAncestry((serverId) => opencodeServerRegistry.getClient(serverId))
|
||||
const sessionSandboxService = new SessionSandboxService(db, sessionAncestry, sessionSettingsService, {
|
||||
removeSessionSandbox: (rootSessionId) => sandboxRuntimeService.removeSessionSandbox(rootSessionId),
|
||||
})
|
||||
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager, opencodeServerRegistry)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager, opencodeServerRegistry, {
|
||||
sessions: sessionSandboxService,
|
||||
runtime: sandboxRuntimeService,
|
||||
})
|
||||
scheduleService.setWorktreeRemovedHandler(async (directory) => {
|
||||
try {
|
||||
await terminalService.removeAll(directory)
|
||||
@@ -292,12 +301,7 @@ const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthServi
|
||||
const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
|
||||
|
||||
const notificationService = new NotificationService(db, opencodeServerRegistry)
|
||||
const sessionSettingsService = new SettingsService(db)
|
||||
const sessionAncestry = new SessionAncestry((serverId) => opencodeServerRegistry.getClient(serverId))
|
||||
const sessionPermissionModeService = new SessionPermissionModeService(db, opencodeServerRegistry, sessionSettingsService, sessionAncestry)
|
||||
const sessionSandboxService = new SessionSandboxService(db, sessionAncestry, sessionSettingsService, {
|
||||
removeSessionSandbox: (rootSessionId) => new SandboxRuntimeService(db).removeSessionSandbox(rootSessionId),
|
||||
})
|
||||
const sessionGoalService = new SessionGoalService(db, opencodeServerRegistry, sessionSettingsService, {
|
||||
onOutcome: (goal) => {
|
||||
void notificationService.notifyGoalOutcome(goal).catch((error) => {
|
||||
|
||||
@@ -401,6 +401,8 @@ Body matches \`CreateScheduleJobRequest\` schema (discriminated union with \`sch
|
||||
|
||||
Optional \`workspaceMode\` sets where runs execute: \`worktree\` (default, a fresh worktree removed after each run), \`kept-worktree\` (a fresh worktree kept after each run), or \`shared-worktree\` (one worktree and branch reused by every run). Kept and shared worktrees are listed with \`GET /repos/:repoId/schedules/:jobId/worktrees\`. Removing schedule worktrees is done by the user in the Manager UI.
|
||||
|
||||
Optional \`sandbox: { enabled, resources: { cpus, memoryMib } | null }\` runs the scheduled session and its subagents in a dedicated sandbox microVM with Docker available. It works only for schedules on the local OpenCode server, requires server sandboxing to be enabled in settings, and the VM and its Docker volume are removed after each run. The run fails if the VM cannot start.
|
||||
|
||||
\`\`\`json
|
||||
{
|
||||
"action": "request",
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
ScheduleMcpServer,
|
||||
ScheduleMode,
|
||||
SchedulePermissionConfig,
|
||||
ScheduleSandboxConfig,
|
||||
ScheduleSkillMetadata,
|
||||
ScheduleWorkspaceMode,
|
||||
UpdateScheduleJobRequest,
|
||||
@@ -28,6 +29,7 @@ export interface ScheduleJobPersistenceInput {
|
||||
mcpServers: ScheduleMcpServer[]
|
||||
branch: string | null
|
||||
workspaceMode: ScheduleWorkspaceMode
|
||||
sandbox: ScheduleSandboxConfig | null
|
||||
directory?: string | null
|
||||
nextRunAt: number | null
|
||||
}
|
||||
@@ -105,6 +107,7 @@ export function buildCreateSchedulePersistenceInput(input: CreateScheduleJobRequ
|
||||
skillMetadata: input.skillMetadata,
|
||||
branch: input.branch?.trim() || null,
|
||||
workspaceMode: input.workspaceMode ?? 'worktree',
|
||||
sandbox: input.sandbox ?? null,
|
||||
...(input.directory !== undefined ? { directory: input.directory?.trim() || null } : {}),
|
||||
}
|
||||
|
||||
@@ -168,6 +171,7 @@ export function buildUpdatedSchedulePersistenceInput(
|
||||
mcpServers: input.mcpServers ?? existing.mcpServers,
|
||||
branch: input.branch === undefined ? existing.branch : (input.branch?.trim() || null),
|
||||
workspaceMode: input.workspaceMode ?? existing.workspaceMode,
|
||||
sandbox: input.sandbox !== undefined ? input.sandbox : existing.sandbox,
|
||||
...(input.directory !== undefined || existing.directory !== undefined
|
||||
? { directory: input.directory === undefined ? (existing.directory ?? null) : (input.directory?.trim() || null) }
|
||||
: {}),
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type ScheduleRun,
|
||||
type ScheduleRunTriggerSource,
|
||||
type ScheduleRunWorktreesMode,
|
||||
type ScheduleSandboxConfig,
|
||||
type ScheduleWorkspaceMode,
|
||||
type ScheduleWorktree,
|
||||
type UpdateScheduleJobRequest,
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
import { mcpStatusByName, openCodeLocation } from '@opencode-manager/shared/opencode'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { getSessionSandboxMode } from '../db/session-sandbox-modes'
|
||||
import type { ScheduleJobWithRepo } from '../db/schedules'
|
||||
import {
|
||||
cleanupOrphanedSchedules,
|
||||
@@ -64,6 +66,8 @@ import { logger } from '../utils/logger'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import { buildAssistantRepo } from './assistant-mode'
|
||||
import { createScheduleWorktreeDescriber } from './schedule-worktree-paths'
|
||||
import { SessionSandboxError, type SessionSandboxService } from './session-sandbox'
|
||||
import type { SandboxRuntimeService } from './sandbox/runtime'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
|
||||
class ScheduleServiceError extends Error {
|
||||
@@ -264,6 +268,11 @@ interface ScheduleTargetContext {
|
||||
serverId: string
|
||||
}
|
||||
|
||||
export interface ScheduleSandboxDependencies {
|
||||
sessions: Pick<SessionSandboxService, 'assertSandboxRequestAllowed' | 'update' | 'resolveShellTarget'>
|
||||
runtime: Pick<SandboxRuntimeService, 'planShell' | 'removeSessionSandbox'>
|
||||
}
|
||||
|
||||
export class ScheduleService {
|
||||
private static activeRuns = new Map<number, ActiveRun>()
|
||||
private static pendingCancels = new Map<number, PendingCancel>()
|
||||
@@ -276,6 +285,7 @@ export class ScheduleService {
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
private readonly worktreeManager: ScheduleWorktreeManager,
|
||||
private readonly serverRegistry: OpenCodeServerRegistry | null = null,
|
||||
private readonly sandbox: ScheduleSandboxDependencies | null = null,
|
||||
) {}
|
||||
|
||||
setJobChangeHandler(handler: ((job: ScheduleJob | null, jobId: number) => void) | null): void {
|
||||
@@ -482,6 +492,44 @@ export class ScheduleService {
|
||||
}
|
||||
}
|
||||
|
||||
private assertSandboxJobSupported(serverId: string, sandbox: ScheduleSandboxConfig | null | undefined): void {
|
||||
if (sandbox?.enabled !== true) return
|
||||
|
||||
if (serverId !== LOCAL_OPENCODE_SERVER_ID) {
|
||||
throw new ScheduleServiceError('Sandboxed schedules run only on the local OpenCode server.', 400)
|
||||
}
|
||||
|
||||
const dependencies = this.sandbox
|
||||
if (!dependencies) {
|
||||
throw new ScheduleServiceError('Sandboxing is not available for schedules.', 409)
|
||||
}
|
||||
|
||||
try {
|
||||
dependencies.sessions.assertSandboxRequestAllowed({ sandboxed: true, resources: sandbox.resources })
|
||||
} catch (error) {
|
||||
if (error instanceof SessionSandboxError) {
|
||||
throw new ScheduleServiceError(error.message, error.status)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private async startRunSandbox(directory: string, sandbox: ScheduleSandboxConfig, sessionId: string): Promise<void> {
|
||||
const dependencies = this.sandbox
|
||||
if (!dependencies) {
|
||||
throw new ScheduleServiceError('Sandboxing is not available for schedules.', 409)
|
||||
}
|
||||
|
||||
await dependencies.sessions.update(sessionId, { sandboxed: true, resources: sandbox.resources })
|
||||
const target = await dependencies.sessions.resolveShellTarget(sessionId)
|
||||
const plan = await dependencies.runtime.planShell(directory, { ...target, locationDirectory: directory }, true)
|
||||
|
||||
if (plan.mode !== 'sandbox') {
|
||||
const reason = plan.mode === 'blocked' ? plan.reason : 'the shell plan was not sandboxed'
|
||||
throw new ScheduleServiceError(`Sandbox could not start: ${reason}`, 502)
|
||||
}
|
||||
}
|
||||
|
||||
listAllEnabledJobs(): ScheduleJob[] {
|
||||
return listEnabledScheduleJobs(this.db)
|
||||
}
|
||||
@@ -629,6 +677,7 @@ export class ScheduleService {
|
||||
private async createJobForTarget(target: ScheduleJobTarget, input: CreateScheduleJobRequest): Promise<ScheduleJob> {
|
||||
this.assertInPlaceWorkspace(target, input.workspaceMode)
|
||||
const context = this.resolveTargetContext(target)
|
||||
this.assertSandboxJobSupported(context.serverId, input.sandbox)
|
||||
await this.assertAgentAvailable(context.client, context.directory, input.agentSlug?.trim() || null)
|
||||
const request = target.kind === 'server'
|
||||
? { ...input, workspaceMode: 'in-place' as const, directory: context.directory, branch: null }
|
||||
@@ -663,6 +712,9 @@ export class ScheduleService {
|
||||
const existing = this.loadJobForTarget(target, jobId)
|
||||
this.assertInPlaceWorkspace(target, input.workspaceMode)
|
||||
const context = this.resolveTargetContext(target, input.directory ?? existing.directory)
|
||||
if (input.sandbox !== undefined) {
|
||||
this.assertSandboxJobSupported(context.serverId, input.sandbox)
|
||||
}
|
||||
|
||||
if (input.agentSlug !== undefined) {
|
||||
await this.assertAgentAvailable(context.client, context.directory, input.agentSlug?.trim() || null)
|
||||
@@ -902,10 +954,12 @@ export class ScheduleService {
|
||||
const abort = new AbortController()
|
||||
ScheduleService.activeRuns.set(jobId, { runId: run.id, abort })
|
||||
let repo: Repo | null = null
|
||||
let sessionId: string | null = null
|
||||
|
||||
try {
|
||||
const context = this.resolveTargetContext(target, job.directory)
|
||||
repo = context.repo
|
||||
this.assertSandboxJobSupported(context.serverId, job.sandbox)
|
||||
|
||||
let runDirectory = context.directory
|
||||
if (repo) {
|
||||
@@ -956,6 +1010,8 @@ export class ScheduleService {
|
||||
throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to create OpenCode session', 502)
|
||||
}
|
||||
|
||||
sessionId = session.id
|
||||
|
||||
if (abort.signal.aborted) {
|
||||
return this.abandonCancelledStartup(context.client, repoId, jobId, run, job, repo, session.id)
|
||||
}
|
||||
@@ -975,6 +1031,13 @@ export class ScheduleService {
|
||||
throw new ScheduleServiceError('Failed to attach session to run', 500)
|
||||
}
|
||||
|
||||
if (job.sandbox?.enabled === true) {
|
||||
await this.startRunSandbox(runDirectory, job.sandbox, session.id)
|
||||
if (abort.signal.aborted) {
|
||||
return this.abandonCancelledStartup(context.client, repoId, jobId, run, job, repo, session.id)
|
||||
}
|
||||
}
|
||||
|
||||
const sessionMonitor = createSessionMonitor(runDirectory, session.id, context.serverId)
|
||||
ScheduleService.attachSessionMonitor(jobId, run.id, sessionMonitor)
|
||||
|
||||
@@ -1002,6 +1065,7 @@ export class ScheduleService {
|
||||
run,
|
||||
job,
|
||||
repo,
|
||||
sessionId ?? undefined,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1012,6 +1076,7 @@ export class ScheduleService {
|
||||
const failedRun = updateScheduleRun(this.db, repoId, jobId, run.id, {
|
||||
status: 'failed',
|
||||
finishedAt,
|
||||
sessionId,
|
||||
errorText,
|
||||
logText: buildRunLog({
|
||||
job,
|
||||
@@ -1030,7 +1095,7 @@ export class ScheduleService {
|
||||
logger.error(`Failed to update job state for job ${jobId}:`, updateError)
|
||||
}
|
||||
|
||||
await this.teardownWorktree(repoId, jobId, run.id, job, repo)
|
||||
await this.teardownRunResources(repoId, jobId, run.id, job, repo, sessionId)
|
||||
|
||||
ScheduleService.releaseActiveRun(jobId, run.id)
|
||||
|
||||
@@ -1184,7 +1249,7 @@ export class ScheduleService {
|
||||
nextRunAt: job.nextRunAt,
|
||||
})
|
||||
|
||||
await this.teardownWorktree(repoId, jobId, runId, job, repo)
|
||||
await this.teardownRunResources(repoId, jobId, runId, job, repo, run.sessionId)
|
||||
ScheduleService.releaseActiveRun(jobId, runId)
|
||||
ScheduleService.resolveCancel(jobId, runId, 'cancelled')
|
||||
|
||||
@@ -1282,7 +1347,7 @@ export class ScheduleService {
|
||||
} finally {
|
||||
await ScheduleService.awaitCancelDecision(input.job.id, input.runId)
|
||||
input.sessionMonitor.dispose()
|
||||
await this.teardownWorktree(input.repoId, input.job.id, input.runId, input.job, input.repo)
|
||||
await this.teardownRunResources(input.repoId, input.job.id, input.runId, input.job, input.repo, input.sessionId)
|
||||
ScheduleService.releaseActiveRun(input.job.id, input.runId)
|
||||
ScheduleService.clearCancel(input.job.id, input.runId)
|
||||
}
|
||||
@@ -1412,7 +1477,7 @@ export class ScheduleService {
|
||||
} finally {
|
||||
await ScheduleService.awaitCancelDecision(input.job.id, input.runId)
|
||||
input.sessionMonitor.dispose()
|
||||
await this.teardownWorktree(input.repoId, input.job.id, input.runId, input.job, input.repo)
|
||||
await this.teardownRunResources(input.repoId, input.job.id, input.runId, input.job, input.repo, input.sessionId)
|
||||
ScheduleService.releaseActiveRun(input.job.id, input.runId)
|
||||
ScheduleService.clearCancel(input.job.id, input.runId)
|
||||
}
|
||||
@@ -1514,7 +1579,7 @@ export class ScheduleService {
|
||||
nextRunAt: run.triggerSource === 'manual' ? job.nextRunAt : computeNextRunAtForJob(job, finishedAt),
|
||||
})
|
||||
|
||||
await this.teardownWorktree(run.repoId, run.jobId, run.id, job, repo)
|
||||
await this.teardownRunResources(run.repoId, run.jobId, run.id, job, repo, run.sessionId)
|
||||
ScheduleService.releaseActiveRun(job.id, run.id)
|
||||
}
|
||||
|
||||
@@ -1543,38 +1608,70 @@ export class ScheduleService {
|
||||
await this.interruptCancelledSession(client, sessionId)
|
||||
}
|
||||
ScheduleService.clearCancel(jobId, run.id)
|
||||
await this.teardownWorktree(repoId, jobId, run.id, job, repo)
|
||||
await this.teardownRunResources(repoId, jobId, run.id, job, repo, sessionId ?? run.sessionId)
|
||||
ScheduleService.releaseActiveRun(jobId, run.id)
|
||||
return this.loadRun(repoId, jobId, run.id, run)
|
||||
}
|
||||
|
||||
private async teardownWorktree(repoId: number | null, jobId: number, runId: number, job: ScheduleJob, repo: Repo | null): Promise<void> {
|
||||
if (!repo) return
|
||||
private async teardownRunResources(
|
||||
repoId: number | null,
|
||||
jobId: number,
|
||||
runId: number,
|
||||
job: ScheduleJob,
|
||||
repo: Repo | null,
|
||||
sessionId?: string | null,
|
||||
): Promise<void> {
|
||||
const key = `${repoId}:${jobId}:${runId}`
|
||||
if (ScheduleService.activeTeardowns.has(key)) return
|
||||
ScheduleService.activeTeardowns.add(key)
|
||||
try {
|
||||
const fresh = getScheduleRunById(this.db, repoId, jobId, runId)
|
||||
if (!fresh?.worktreePath) return
|
||||
const worktreePath = fresh.worktreePath
|
||||
const remainingWorktreePath = () => (existsSync(worktreePath) ? worktreePath : null)
|
||||
try {
|
||||
const { commitHash } = await this.worktreeManager.finalize(repo, job, {
|
||||
id: runId,
|
||||
worktreePath,
|
||||
runBranch: fresh.runBranch,
|
||||
triggerSource: fresh.triggerSource,
|
||||
})
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: remainingWorktreePath(), commitHash })
|
||||
} catch (error) {
|
||||
logger.error(`Failed to finalize worktree for run ${runId}:`, error)
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: remainingWorktreePath() })
|
||||
if (repo && fresh?.worktreePath) {
|
||||
await this.finalizeRunWorktree(repo, job, runId, fresh.worktreePath, fresh.runBranch, fresh.triggerSource, repoId, jobId)
|
||||
}
|
||||
await this.removeRunSandbox(sessionId ?? fresh?.sessionId ?? null)
|
||||
} finally {
|
||||
ScheduleService.activeTeardowns.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
private async finalizeRunWorktree(
|
||||
repo: Repo,
|
||||
job: ScheduleJob,
|
||||
runId: number,
|
||||
worktreePath: string,
|
||||
runBranch: string | null,
|
||||
triggerSource: ScheduleRunTriggerSource,
|
||||
repoId: number | null,
|
||||
jobId: number,
|
||||
): Promise<void> {
|
||||
const remainingWorktreePath = () => (existsSync(worktreePath) ? worktreePath : null)
|
||||
try {
|
||||
const { commitHash } = await this.worktreeManager.finalize(repo, job, {
|
||||
id: runId,
|
||||
worktreePath,
|
||||
runBranch,
|
||||
triggerSource,
|
||||
})
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: remainingWorktreePath(), commitHash })
|
||||
} catch (error) {
|
||||
logger.error(`Failed to finalize worktree for run ${runId}:`, error)
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: remainingWorktreePath() })
|
||||
}
|
||||
}
|
||||
|
||||
private async removeRunSandbox(sessionId: string | null): Promise<void> {
|
||||
const runtime = this.sandbox?.runtime
|
||||
if (!sessionId || !runtime) return
|
||||
const mode = getSessionSandboxMode(this.db, sessionId)
|
||||
if (mode?.sandboxed !== true && mode?.source !== 'user') return
|
||||
try {
|
||||
await runtime.removeSessionSandbox(sessionId)
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to remove the sandbox microVM for scheduled run session ${sessionId}: ${getErrorMessage(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An assistant message completing is not the end of a run: a multi-step agent
|
||||
* settles one message per tool call. Only a session that has gone idle has
|
||||
|
||||
@@ -109,17 +109,7 @@ export class SessionSandboxService {
|
||||
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)
|
||||
}
|
||||
}
|
||||
this.assertSandboxRequestAllowed(request)
|
||||
|
||||
const defaultSandboxed = this.defaultSandboxed()
|
||||
this.db.transaction(() => {
|
||||
@@ -131,13 +121,30 @@ export class SessionSandboxService {
|
||||
}
|
||||
})()
|
||||
|
||||
if (request.sandboxed === false && available) {
|
||||
if (request.sandboxed === false && this.sandboxSupported()) {
|
||||
this.removeSandboxInBackground(sessionId, `session ${sessionId} after its sandbox was turned off`)
|
||||
}
|
||||
|
||||
return this.getState(sessionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a sandbox change before it is stored or acted on: enabling sandboxing
|
||||
* requires it to be enabled for the server, and the resources must be within limits.
|
||||
*/
|
||||
assertSandboxRequestAllowed(request: SetSessionSandboxRequest): void {
|
||||
if (request.sandboxed === true && !this.sandboxSupported()) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async resolveShellTarget(sessionId: string): Promise<{ rootSessionId: string; resources: SessionSandboxResources }> {
|
||||
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
|
||||
const stored = getSessionSandboxMode(this.db, rootSessionId)
|
||||
|
||||
@@ -6,6 +6,7 @@ import migration015 from '../../src/db/migrations/015-schedule-worktree-isolatio
|
||||
import migration021 from '../../src/db/migrations/021-drop-schedule-run-workspace-id'
|
||||
import migration022 from '../../src/db/migrations/022-schedule-runs-session-index'
|
||||
import migration024 from '../../src/db/migrations/024-schedule-runs-viewed-at'
|
||||
import migration202610251900 from '../../src/db/migrations/202610251900-schedule-sandbox-config'
|
||||
|
||||
describe('schedule migrations', () => {
|
||||
it('creates schedule jobs with nullable interval minutes in v7', () => {
|
||||
@@ -288,3 +289,31 @@ describe('migration 024 - schedule runs viewed at', () => {
|
||||
db.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('migration 202610251900 - schedule sandbox config', () => {
|
||||
it('adds the nullable sandbox_config column and is idempotent', () => {
|
||||
const db = new Database(':memory:')
|
||||
db.run('CREATE TABLE schedule_jobs (id INTEGER PRIMARY KEY, name TEXT)')
|
||||
|
||||
migration202610251900.up(db)
|
||||
migration202610251900.up(db)
|
||||
|
||||
const columns = (db.prepare('PRAGMA table_info(schedule_jobs)').all() as { name: string }[]).map((column) => column.name)
|
||||
expect(columns).toContain('sandbox_config')
|
||||
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('drops the column on rollback', () => {
|
||||
const db = new Database(':memory:')
|
||||
db.run('CREATE TABLE schedule_jobs (id INTEGER PRIMARY KEY, name TEXT)')
|
||||
|
||||
migration202610251900.up(db)
|
||||
migration202610251900.down(db)
|
||||
|
||||
const columns = (db.prepare('PRAGMA table_info(schedule_jobs)').all() as { name: string }[]).map((column) => column.name)
|
||||
expect(columns).not.toContain('sandbox_config')
|
||||
|
||||
db.close()
|
||||
})
|
||||
})
|
||||
@@ -36,6 +36,7 @@ describe('schedule permission config persistence', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.now() + 3600000,
|
||||
...overrides,
|
||||
})
|
||||
@@ -108,4 +109,25 @@ describe('schedule permission config persistence', () => {
|
||||
expect(updated!.prompt).toBe('Updated prompt')
|
||||
expect(updated!.permissionConfig).toEqual(config)
|
||||
})
|
||||
|
||||
it('round-trips a sandbox config', () => {
|
||||
const sandbox = { enabled: true, resources: { cpus: 4, memoryMib: 12288 } }
|
||||
const created = createScheduleJob(db, 1, baseInput({ sandbox }))
|
||||
|
||||
expect(created.sandbox).toEqual(sandbox)
|
||||
|
||||
const fetched = getScheduleJobById(db, 1, created.id)
|
||||
expect(fetched).not.toBeNull()
|
||||
expect(fetched!.sandbox).toEqual(sandbox)
|
||||
})
|
||||
|
||||
it('round-trips a null sandbox config', () => {
|
||||
const created = createScheduleJob(db, 1, baseInput({ sandbox: null }))
|
||||
|
||||
expect(created.sandbox).toBeNull()
|
||||
|
||||
const fetched = getScheduleJobById(db, 1, created.id)
|
||||
expect(fetched).not.toBeNull()
|
||||
expect(fetched!.sandbox).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -117,6 +117,7 @@ describe('schedule database queries', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
})
|
||||
|
||||
@@ -139,6 +140,7 @@ describe('schedule database queries', () => {
|
||||
null,
|
||||
null,
|
||||
'worktree',
|
||||
null,
|
||||
expect.any(Number),
|
||||
expect.any(Number),
|
||||
null,
|
||||
@@ -179,6 +181,7 @@ describe('schedule database queries', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: null,
|
||||
})
|
||||
|
||||
@@ -199,6 +202,7 @@ describe('schedule database queries', () => {
|
||||
null,
|
||||
'worktree',
|
||||
null,
|
||||
null,
|
||||
expect.any(Number),
|
||||
null,
|
||||
42,
|
||||
|
||||
@@ -46,6 +46,7 @@ function scheduleJobInput(name: string, branch: string): ScheduleJobPersistenceI
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
branch,
|
||||
nextRunAt: null,
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ describe('schedule-config', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: currentDate + 60 * 60_000,
|
||||
})
|
||||
})
|
||||
@@ -78,6 +79,7 @@ describe('schedule-config', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -111,6 +113,7 @@ describe('schedule-config', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -147,6 +150,7 @@ describe('schedule-config', () => {
|
||||
mcpServers: [],
|
||||
branch: 'feature/foo',
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -179,6 +183,7 @@ describe('schedule-config', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -211,6 +216,7 @@ describe('schedule-config', () => {
|
||||
mcpServers: [],
|
||||
branch: 'feature/foo',
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -243,6 +249,7 @@ describe('schedule-config', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: null,
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -288,6 +295,7 @@ describe('schedule-config', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: null,
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -296,4 +304,83 @@ describe('schedule-config', () => {
|
||||
|
||||
expect(computeNextRunAtForJob(job, Date.UTC(2026, 2, 9, 12, 0, 0))).toBeNull()
|
||||
})
|
||||
|
||||
describe('sandbox config', () => {
|
||||
const sandbox = { enabled: true, resources: { cpus: 4, memoryMib: 12288 } }
|
||||
|
||||
const existingJob = (sandboxConfig: ScheduleJob['sandbox']): ScheduleJob => ({
|
||||
id: 14,
|
||||
repoId: 42,
|
||||
name: 'Sandbox job',
|
||||
description: null,
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: sandboxConfig,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
})
|
||||
|
||||
it('defaults sandbox to null when creating a schedule', () => {
|
||||
const result = buildCreateSchedulePersistenceInput({
|
||||
name: 'Sandbox job',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
prompt: 'Prompt',
|
||||
})
|
||||
|
||||
expect(result.sandbox).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the provided sandbox when creating a schedule', () => {
|
||||
const result = buildCreateSchedulePersistenceInput({
|
||||
name: 'Sandbox job',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
prompt: 'Prompt',
|
||||
sandbox,
|
||||
})
|
||||
|
||||
expect(result.sandbox).toEqual(sandbox)
|
||||
})
|
||||
|
||||
it('keeps the existing sandbox when omitted from an update', () => {
|
||||
const result = buildUpdatedSchedulePersistenceInput(existingJob(sandbox), {
|
||||
prompt: 'Updated prompt',
|
||||
})
|
||||
|
||||
expect(result.sandbox).toEqual(sandbox)
|
||||
})
|
||||
|
||||
it('replaces the sandbox when provided in an update', () => {
|
||||
const replacement = { enabled: true, resources: null }
|
||||
const result = buildUpdatedSchedulePersistenceInput(existingJob(sandbox), {
|
||||
sandbox: replacement,
|
||||
})
|
||||
|
||||
expect(result.sandbox).toEqual(replacement)
|
||||
})
|
||||
|
||||
it('clears the sandbox when explicitly set to null in an update', () => {
|
||||
const result = buildUpdatedSchedulePersistenceInput(existingJob(sandbox), {
|
||||
sandbox: null,
|
||||
})
|
||||
|
||||
expect(result.sandbox).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -126,6 +126,7 @@ const baseJob: ScheduleJob = {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
|
||||
@@ -36,7 +36,9 @@ const mocks = vi.hoisted(() => ({
|
||||
onEvent: vi.fn(),
|
||||
onServerConnected: vi.fn(),
|
||||
loggerError: vi.fn(),
|
||||
loggerWarn: vi.fn(),
|
||||
updateScheduleRunWorktree: vi.fn(),
|
||||
getSessionSandboxMode: vi.fn(),
|
||||
stubWorktreeManager: {
|
||||
prepare: vi.fn().mockResolvedValue(null),
|
||||
finalize: vi.fn().mockResolvedValue({ commitHash: null }),
|
||||
@@ -75,6 +77,10 @@ vi.mock('../../src/db/schedules', () => ({
|
||||
updateScheduleRunWorktree: mocks.updateScheduleRunWorktree,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/db/session-sandbox-modes', () => ({
|
||||
getSessionSandboxMode: mocks.getSessionSandboxMode,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/schedule-config', () => ({
|
||||
buildCreateSchedulePersistenceInput: mocks.buildCreateSchedulePersistenceInput,
|
||||
buildUpdatedSchedulePersistenceInput: mocks.buildUpdatedSchedulePersistenceInput,
|
||||
@@ -96,7 +102,7 @@ vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
error: mocks.loggerError,
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
warn: mocks.loggerWarn,
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -112,6 +118,7 @@ vi.mock('croner', () => ({
|
||||
}))
|
||||
|
||||
import { ScheduleRunner, ScheduleService } from '../../src/services/schedules'
|
||||
import { SessionSandboxError } from '../../src/services/session-sandbox'
|
||||
import { createStubOpenCodeClient } from '../helpers/stub-opencode-client'
|
||||
import { assistantMessage, createStubScheduleApi, skill } from '../helpers/stub-schedule-api'
|
||||
|
||||
@@ -119,6 +126,33 @@ function makeService(api: OpenCodeApi): ScheduleService {
|
||||
return new ScheduleService({} as never, createStubOpenCodeClient({ api }), mocks.stubWorktreeManager as never)
|
||||
}
|
||||
|
||||
const SANDBOX_RESOURCES = { cpus: 4, memoryMib: 8192 }
|
||||
const SANDBOX_SESSION_MODE = { sandboxed: true, source: 'user' as const, toggledAt: 0, resources: SANDBOX_RESOURCES }
|
||||
|
||||
function makeSandboxService(api: OpenCodeApi) {
|
||||
const sessions = {
|
||||
assertSandboxRequestAllowed: vi.fn(),
|
||||
update: vi.fn().mockResolvedValue({}),
|
||||
resolveShellTarget: vi.fn().mockResolvedValue({ rootSessionId: 'ses-run-1', resources: SANDBOX_RESOURCES }),
|
||||
}
|
||||
const runtime = {
|
||||
planShell: vi.fn().mockResolvedValue({ mode: 'sandbox', name: 'ocm-ses-run-1', workdir: repo.fullPath }),
|
||||
removeSessionSandbox: vi.fn().mockResolvedValue(undefined),
|
||||
}
|
||||
const registry = {
|
||||
get: vi.fn(() => ({ id: 'srv_remote', name: 'Remote server', enabled: true })),
|
||||
getClient: vi.fn(() => createStubOpenCodeClient({ api })),
|
||||
}
|
||||
const service = new ScheduleService(
|
||||
{} as never,
|
||||
createStubOpenCodeClient({ api }),
|
||||
mocks.stubWorktreeManager as never,
|
||||
registry as never,
|
||||
{ sessions, runtime } as never,
|
||||
)
|
||||
return { service, sessions, runtime }
|
||||
}
|
||||
|
||||
function sessionIdleEvent(directory: string, sessionID: string) {
|
||||
return {
|
||||
id: `evt_${sessionID}`,
|
||||
@@ -167,6 +201,7 @@ const job: ScheduleJob = {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -205,6 +240,7 @@ describe('ScheduleService', () => {
|
||||
mocks.getRunningScheduleRunByJob.mockReturnValue(null)
|
||||
mocks.listScheduleJobWorktreeOwners.mockReturnValue([{ id: job.id, repoId: job.repoId, name: job.name }])
|
||||
mocks.createScheduleRun.mockReturnValue(baseRun)
|
||||
mocks.getSessionSandboxMode.mockReturnValue(null)
|
||||
mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', id: 'gpt-5-mini', model: 'openai/gpt-5-mini' })
|
||||
mocks.onEvent.mockReturnValue(vi.fn())
|
||||
mocks.onServerConnected.mockReturnValue(vi.fn())
|
||||
@@ -1324,6 +1360,276 @@ describe('ScheduleService', () => {
|
||||
expect(stub.api.session.create).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('sandboxed runs', () => {
|
||||
const sandboxJob: ScheduleJob = { ...job, sandbox: { enabled: true, resources: SANDBOX_RESOURCES } }
|
||||
|
||||
function runWithSession(sessionId = 'ses-run-1'): ScheduleRun {
|
||||
return {
|
||||
...baseRun,
|
||||
sessionId,
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started. Waiting for assistant response...',
|
||||
}
|
||||
}
|
||||
|
||||
it('boots the run sandbox with the job resources before the first prompt', async () => {
|
||||
mocks.getScheduleJobById.mockReturnValue(sandboxJob)
|
||||
const stub = createStubScheduleApi({ messages: [assistantMessage('Done.', { completed: true })] })
|
||||
const { service, sessions, runtime } = makeSandboxService(stub.api)
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession())
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession())
|
||||
|
||||
await service.runJob(42, 7, 'manual')
|
||||
await vi.waitFor(() => expect(stub.api.session.prompt).toHaveBeenCalledTimes(1))
|
||||
|
||||
expect(sessions.assertSandboxRequestAllowed).toHaveBeenCalledWith({ sandboxed: true, resources: SANDBOX_RESOURCES })
|
||||
expect(sessions.update).toHaveBeenCalledWith('ses-run-1', { sandboxed: true, resources: SANDBOX_RESOURCES })
|
||||
expect(runtime.planShell).toHaveBeenCalledWith(
|
||||
repo.fullPath,
|
||||
{ rootSessionId: 'ses-run-1', resources: SANDBOX_RESOURCES, locationDirectory: repo.fullPath },
|
||||
true,
|
||||
)
|
||||
|
||||
const [metadataOrder] = mocks.updateScheduleRunMetadata.mock.invocationCallOrder
|
||||
const [updateOrder] = sessions.update.mock.invocationCallOrder
|
||||
const [planOrder] = runtime.planShell.mock.invocationCallOrder
|
||||
const [promptOrder] = vi.mocked(stub.api.session.prompt).mock.invocationCallOrder
|
||||
expect(metadataOrder).toBeLessThan(updateOrder ?? 0)
|
||||
expect(updateOrder).toBeLessThan(planOrder ?? 0)
|
||||
expect(planOrder).toBeLessThan(promptOrder ?? 0)
|
||||
})
|
||||
|
||||
it('fails the run without prompting when the sandbox cannot start', async () => {
|
||||
mocks.getScheduleJobById.mockReturnValue(sandboxJob)
|
||||
const stub = createStubScheduleApi()
|
||||
const { service, runtime } = makeSandboxService(stub.api)
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession())
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession())
|
||||
runtime.planShell.mockResolvedValue({ mode: 'blocked', reason: '2 sandbox VMs are already running' })
|
||||
mocks.getSessionSandboxMode.mockReturnValue(SANDBOX_SESSION_MODE)
|
||||
mocks.updateScheduleRun.mockReturnValue({
|
||||
...runWithSession(),
|
||||
status: 'failed',
|
||||
errorText: 'Sandbox could not start: 2 sandbox VMs are already running',
|
||||
})
|
||||
|
||||
await expect(service.runJob(42, 7, 'manual')).rejects.toMatchObject({
|
||||
status: 502,
|
||||
message: 'Sandbox could not start: 2 sandbox VMs are already running',
|
||||
})
|
||||
|
||||
expect(stub.api.session.prompt).not.toHaveBeenCalled()
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({
|
||||
status: 'failed',
|
||||
sessionId: 'ses-run-1',
|
||||
errorText: 'Sandbox could not start: 2 sandbox VMs are already running',
|
||||
}),
|
||||
)
|
||||
expect(runtime.removeSessionSandbox).toHaveBeenCalledWith('ses-run-1')
|
||||
})
|
||||
|
||||
it('removes the sandbox after a completed run and survives a removal failure', async () => {
|
||||
mocks.getScheduleJobById.mockReturnValue(sandboxJob)
|
||||
const stub = createStubScheduleApi({ messages: [assistantMessage('Done.', { completed: true })] })
|
||||
const { service, runtime } = makeSandboxService(stub.api)
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession())
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession())
|
||||
runtime.removeSessionSandbox.mockRejectedValue(new Error('msb rm failed'))
|
||||
mocks.getSessionSandboxMode.mockReturnValue(SANDBOX_SESSION_MODE)
|
||||
|
||||
await service.runJob(42, 7, 'manual')
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({ status: 'completed' }),
|
||||
)
|
||||
})
|
||||
await vi.waitFor(() => expect(runtime.removeSessionSandbox).toHaveBeenCalledWith('ses-run-1'))
|
||||
await vi.waitFor(() => expect(mocks.loggerWarn).toHaveBeenCalled())
|
||||
expect(mocks.updateScheduleRun).not.toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({ status: 'failed' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('removes the sandbox of a cancelled run', async () => {
|
||||
mocks.getScheduleJobById.mockReturnValue(sandboxJob)
|
||||
const stub = createStubScheduleApi({ messages: [] })
|
||||
const { service, runtime } = makeSandboxService(stub.api)
|
||||
const runningRun = runWithSession('ses-run-3')
|
||||
const cancelledRun: ScheduleRun = {
|
||||
...runningRun,
|
||||
status: 'cancelled',
|
||||
finishedAt: Date.UTC(2026, 2, 9, 12, 10, 0),
|
||||
errorText: 'Run cancelled by user.',
|
||||
}
|
||||
mocks.getScheduleRunById.mockReturnValue(runningRun)
|
||||
mocks.updateScheduleRun.mockReturnValue(cancelledRun)
|
||||
mocks.getSessionSandboxMode.mockReturnValue(SANDBOX_SESSION_MODE)
|
||||
|
||||
const result = await service.cancelRun(42, 7, 5)
|
||||
|
||||
expect(result).toEqual(cancelledRun)
|
||||
expect(runtime.removeSessionSandbox).toHaveBeenCalledWith('ses-run-3')
|
||||
})
|
||||
|
||||
it('removes the sandbox of a cancelled run whose job no longer enables sandboxing', async () => {
|
||||
for (const sandbox of [{ enabled: false, resources: SANDBOX_RESOURCES }, null] as const) {
|
||||
mocks.getScheduleJobById.mockReturnValue({ ...job, sandbox })
|
||||
const stub = createStubScheduleApi({ messages: [] })
|
||||
const { service, runtime } = makeSandboxService(stub.api)
|
||||
const runningRun = runWithSession('ses-run-4')
|
||||
mocks.getScheduleRunById.mockReturnValue(runningRun)
|
||||
mocks.updateScheduleRun.mockReturnValue({
|
||||
...runningRun,
|
||||
status: 'cancelled',
|
||||
finishedAt: Date.UTC(2026, 2, 9, 12, 10, 0),
|
||||
errorText: 'Run cancelled by user.',
|
||||
})
|
||||
mocks.getSessionSandboxMode.mockReturnValue(SANDBOX_SESSION_MODE)
|
||||
|
||||
await service.cancelRun(42, 7, 5)
|
||||
|
||||
expect(runtime.removeSessionSandbox).toHaveBeenCalledWith('ses-run-4')
|
||||
runtime.removeSessionSandbox.mockClear()
|
||||
}
|
||||
})
|
||||
|
||||
it('retries sandbox removal when the run session sandbox was turned off during the run', async () => {
|
||||
for (const [mode, expected] of [
|
||||
[{ ...SANDBOX_SESSION_MODE, sandboxed: false, source: 'user' }, true],
|
||||
[{ ...SANDBOX_SESSION_MODE, sandboxed: false, source: 'default' }, false],
|
||||
] as const) {
|
||||
mocks.getScheduleJobById.mockReturnValue(sandboxJob)
|
||||
const stub = createStubScheduleApi({ messages: [] })
|
||||
const { service, runtime } = makeSandboxService(stub.api)
|
||||
const runningRun = runWithSession('ses-run-5')
|
||||
mocks.getScheduleRunById.mockReturnValue(runningRun)
|
||||
mocks.updateScheduleRun.mockReturnValue({ ...runningRun, status: 'cancelled' })
|
||||
mocks.getSessionSandboxMode.mockReturnValue(mode)
|
||||
|
||||
await service.cancelRun(42, 7, 5)
|
||||
|
||||
if (expected) {
|
||||
expect(runtime.removeSessionSandbox).toHaveBeenCalledWith('ses-run-5')
|
||||
} else {
|
||||
expect(runtime.removeSessionSandbox).not.toHaveBeenCalled()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('leaves the sandbox dependencies untouched for a job without an enabled sandbox', async () => {
|
||||
for (const sandbox of [null, { enabled: false, resources: SANDBOX_RESOURCES }] as const) {
|
||||
mocks.getScheduleJobById.mockReturnValue({ ...job, sandbox })
|
||||
const stub = createStubScheduleApi({ messages: [assistantMessage('Done.', { completed: true })] })
|
||||
const { service, sessions, runtime } = makeSandboxService(stub.api)
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession())
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession())
|
||||
|
||||
await service.runJob(42, 7, 'manual')
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
expect.objectContaining({ status: 'completed' }),
|
||||
)
|
||||
})
|
||||
expect(sessions.update).not.toHaveBeenCalled()
|
||||
expect(runtime.planShell).not.toHaveBeenCalled()
|
||||
expect(runtime.removeSessionSandbox).not.toHaveBeenCalled()
|
||||
await vi.waitFor(() => {
|
||||
expect(Reflect.get(ScheduleService, 'activeRuns').has(7)).toBe(false)
|
||||
})
|
||||
mocks.updateScheduleRun.mockClear()
|
||||
}
|
||||
})
|
||||
|
||||
it('validates sandbox settings when saving a local schedule', async () => {
|
||||
const stub = createStubScheduleApi()
|
||||
const { service, sessions } = makeSandboxService(stub.api)
|
||||
mocks.buildCreateSchedulePersistenceInput.mockReturnValue({ name: 'Sandboxed job' })
|
||||
mocks.createScheduleJob.mockReturnValue(sandboxJob)
|
||||
|
||||
await service.createJob(42, {
|
||||
name: 'Sandboxed job',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
prompt: 'Audit the project.',
|
||||
sandbox: { enabled: true, resources: SANDBOX_RESOURCES },
|
||||
})
|
||||
|
||||
expect(sessions.assertSandboxRequestAllowed).toHaveBeenCalledWith({ sandboxed: true, resources: SANDBOX_RESOURCES })
|
||||
expect(mocks.createScheduleJob).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects enabling the sandbox for a remote server schedule', async () => {
|
||||
const stub = createStubScheduleApi({ agents: ['build'] })
|
||||
const { service } = makeSandboxService(stub.api)
|
||||
|
||||
await expect(service.createServerJob('srv_remote', '/srv/audit', {
|
||||
name: 'Remote audit',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
prompt: 'Audit the project.',
|
||||
sandbox: { enabled: true, resources: null },
|
||||
})).rejects.toMatchObject({
|
||||
status: 400,
|
||||
message: 'Sandboxed schedules run only on the local OpenCode server.',
|
||||
})
|
||||
|
||||
expect(mocks.createScheduleJob).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('maps a rejected sandbox request to the schedule error status', async () => {
|
||||
const stub = createStubScheduleApi()
|
||||
const { service, sessions } = makeSandboxService(stub.api)
|
||||
sessions.assertSandboxRequestAllowed.mockImplementation(() => {
|
||||
throw new SessionSandboxError('Sandboxing is not enabled for this server', 409)
|
||||
})
|
||||
|
||||
await expect(service.updateJob(42, 7, { sandbox: { enabled: true, resources: null } })).rejects.toMatchObject({
|
||||
status: 409,
|
||||
message: 'Sandboxing is not enabled for this server',
|
||||
})
|
||||
|
||||
expect(mocks.updateScheduleJob).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('updates a sandboxed schedule without revalidating its stored sandbox config', async () => {
|
||||
const stub = createStubScheduleApi()
|
||||
const { service, sessions } = makeSandboxService(stub.api)
|
||||
const disabledJob = { ...sandboxJob, enabled: false }
|
||||
mocks.getScheduleJobById.mockReturnValue(sandboxJob)
|
||||
sessions.assertSandboxRequestAllowed.mockImplementation(() => {
|
||||
throw new SessionSandboxError('Sandboxing is not enabled for this server', 409)
|
||||
})
|
||||
mocks.buildUpdatedSchedulePersistenceInput.mockReturnValue({ enabled: false })
|
||||
mocks.updateScheduleJob.mockReturnValue(disabledJob)
|
||||
|
||||
await expect(service.updateJob(42, 7, { enabled: false })).resolves.toEqual(disabledJob)
|
||||
|
||||
expect(sessions.assertSandboxRequestAllowed).not.toHaveBeenCalled()
|
||||
expect(mocks.updateScheduleJob).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('ScheduleService startup cancellation', () => {
|
||||
@@ -1338,6 +1644,7 @@ describe('ScheduleService startup cancellation', () => {
|
||||
mocks.getRunningScheduleRunByJob.mockReturnValue(null)
|
||||
mocks.listScheduleJobWorktreeOwners.mockReturnValue([{ id: job.id, repoId: job.repoId, name: job.name }])
|
||||
mocks.createScheduleRun.mockReturnValue(baseRun)
|
||||
mocks.getSessionSandboxMode.mockReturnValue(null)
|
||||
mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', id: 'gpt-5-mini', model: 'openai/gpt-5-mini' })
|
||||
mocks.onEvent.mockReturnValue(vi.fn())
|
||||
mocks.onServerConnected.mockReturnValue(vi.fn())
|
||||
@@ -1601,6 +1908,7 @@ describe('ScheduleService monitor cancellation', () => {
|
||||
mocks.getRunningScheduleRunByJob.mockReturnValue(null)
|
||||
mocks.listScheduleJobWorktreeOwners.mockReturnValue([{ id: job.id, repoId: job.repoId, name: job.name }])
|
||||
mocks.createScheduleRun.mockReturnValue(baseRun)
|
||||
mocks.getSessionSandboxMode.mockReturnValue(null)
|
||||
mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', id: 'gpt-5-mini', model: 'openai/gpt-5-mini' })
|
||||
mocks.onEvent.mockReturnValue(vi.fn())
|
||||
mocks.onServerConnected.mockReturnValue(vi.fn())
|
||||
@@ -2261,6 +2569,7 @@ describe('ScheduleRunner', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
@@ -2300,6 +2609,7 @@ describe('ScheduleRunner', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
@@ -2337,6 +2647,7 @@ describe('ScheduleRunner', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
@@ -2373,6 +2684,7 @@ describe('ScheduleRunner', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
@@ -2409,6 +2721,7 @@ describe('ScheduleRunner', () => {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
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 { SandboxResourceInputs } from '@/components/sandbox/SandboxResourceInputs'
|
||||
import { useSetSessionSandbox } from '@/hooks/useSessionSandbox'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { formatSandboxMemory } from '@/lib/sandboxResources'
|
||||
@@ -69,36 +68,15 @@ export function SessionSandboxResourcesDialog({
|
||||
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>
|
||||
<SandboxResourceInputs
|
||||
idPrefix="sessionSandbox"
|
||||
cpus={cpus}
|
||||
onCpusChange={setCpus}
|
||||
memoryGib={memoryGib}
|
||||
onMemoryGibChange={setMemoryGib}
|
||||
disabled={setSandbox.isPending}
|
||||
error={error}
|
||||
/>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="outline" onClick={() => void submit(null)} disabled={setSandbox.isPending}>
|
||||
Use defaults
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
SANDBOX_CPUS_MAX,
|
||||
SANDBOX_CPUS_MIN,
|
||||
SANDBOX_MEMORY_GIB_MAX,
|
||||
SANDBOX_MEMORY_GIB_MIN,
|
||||
} from '@/lib/sandboxResources'
|
||||
|
||||
type SandboxResourceInputsProps = {
|
||||
idPrefix: string
|
||||
cpus: string
|
||||
onCpusChange: (value: string) => void
|
||||
memoryGib: string
|
||||
onMemoryGibChange: (value: string) => void
|
||||
cpusPlaceholder?: string
|
||||
memoryPlaceholder?: string
|
||||
disabled?: boolean
|
||||
error?: string | null
|
||||
}
|
||||
|
||||
export function SandboxResourceInputs({
|
||||
idPrefix,
|
||||
cpus,
|
||||
onCpusChange,
|
||||
memoryGib,
|
||||
onMemoryGibChange,
|
||||
cpusPlaceholder,
|
||||
memoryPlaceholder,
|
||||
disabled,
|
||||
error,
|
||||
}: SandboxResourceInputsProps) {
|
||||
const cpusId = `${idPrefix}-cpus`
|
||||
const memoryId = `${idPrefix}-memory`
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={cpusId}>CPUs</Label>
|
||||
<Input
|
||||
id={cpusId}
|
||||
type="number"
|
||||
min={SANDBOX_CPUS_MIN}
|
||||
max={SANDBOX_CPUS_MAX}
|
||||
step={1}
|
||||
inputMode="numeric"
|
||||
value={cpus}
|
||||
onChange={(event) => onCpusChange(event.target.value)}
|
||||
placeholder={cpusPlaceholder}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={memoryId}>Memory (GiB)</Label>
|
||||
<Input
|
||||
id={memoryId}
|
||||
type="number"
|
||||
min={SANDBOX_MEMORY_GIB_MIN}
|
||||
max={SANDBOX_MEMORY_GIB_MAX}
|
||||
step={0.5}
|
||||
value={memoryGib}
|
||||
onChange={(event) => onMemoryGibChange(event.target.value)}
|
||||
placeholder={memoryPlaceholder}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{error ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -7,10 +7,25 @@ import { Switch } from '@/components/ui/switch'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { TabsContent } from '@/components/ui/tabs'
|
||||
import { RadioOptionGroup } from '@/components/ui/radio-option-group'
|
||||
import { SandboxResourceInputs } from '@/components/sandbox/SandboxResourceInputs'
|
||||
import { workspaceModeOptions } from '@/components/schedules/schedule-utils'
|
||||
import type { ScheduleWorkspaceMode } from '@opencode-manager/shared/types'
|
||||
import { Info } from 'lucide-react'
|
||||
|
||||
export type ScheduleSandboxFields = {
|
||||
enabled: boolean
|
||||
onEnabledChange: (value: boolean) => void
|
||||
toggleDisabled: boolean
|
||||
unavailableReason: string | null
|
||||
cpus: string
|
||||
onCpusChange: (value: string) => void
|
||||
memoryGib: string
|
||||
onMemoryGibChange: (value: string) => void
|
||||
cpusPlaceholder: string
|
||||
memoryPlaceholder: string
|
||||
error: string | null
|
||||
}
|
||||
|
||||
type GeneralTabProps = {
|
||||
name: string
|
||||
onNameChange: (value: string) => void
|
||||
@@ -42,6 +57,7 @@ type GeneralTabProps = {
|
||||
onAllowQuestionsChange: (value: boolean) => void
|
||||
bashDenyPatterns: string[]
|
||||
onBashDenyPatternsChange: (value: string[]) => void
|
||||
sandbox?: ScheduleSandboxFields
|
||||
}
|
||||
|
||||
function InfoHint({ text }: { text: string }) {
|
||||
@@ -87,6 +103,7 @@ export function GeneralTab({
|
||||
onAllowQuestionsChange,
|
||||
bashDenyPatterns,
|
||||
onBashDenyPatternsChange,
|
||||
sandbox,
|
||||
}: GeneralTabProps) {
|
||||
return (
|
||||
<TabsContent value="basics" className="mt-0 min-h-0 flex-1 overflow-y-auto pt-4 pb-5">
|
||||
@@ -243,6 +260,43 @@ export function GeneralTab({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{sandbox && (
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-medium text-muted-foreground">Sandbox</h3>
|
||||
<div className="rounded-lg border border-border bg-card p-4 space-y-3">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="space-y-0.5">
|
||||
<p id="schedule-sandbox-label" className="text-sm font-medium">Run in sandbox</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Each run and its subagents get a dedicated VM with Docker, removed after the run.
|
||||
</p>
|
||||
{sandbox.unavailableReason ? (
|
||||
<p className="text-xs text-destructive">{sandbox.unavailableReason}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Switch
|
||||
checked={sandbox.enabled}
|
||||
onCheckedChange={sandbox.onEnabledChange}
|
||||
disabled={sandbox.toggleDisabled}
|
||||
aria-labelledby="schedule-sandbox-label"
|
||||
/>
|
||||
</div>
|
||||
{sandbox.enabled && (
|
||||
<SandboxResourceInputs
|
||||
idPrefix="schedule-sandbox"
|
||||
cpus={sandbox.cpus}
|
||||
onCpusChange={sandbox.onCpusChange}
|
||||
memoryGib={sandbox.memoryGib}
|
||||
onMemoryGibChange={sandbox.onMemoryGibChange}
|
||||
cpusPlaceholder={sandbox.cpusPlaceholder}
|
||||
memoryPlaceholder={sandbox.memoryPlaceholder}
|
||||
error={sandbox.error}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
formatScheduleSummary,
|
||||
formatScheduleSandbox,
|
||||
formatTimestamp,
|
||||
getJobStatusTone,
|
||||
formatWorkspaceMode,
|
||||
@@ -193,6 +194,10 @@ export function JobDetailTab({
|
||||
<p className="font-medium">{formatWorkspaceMode(selectedJob.workspaceMode)}</p>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-muted-foreground">Sandbox</p>
|
||||
<p className="font-medium">{formatScheduleSandbox(selectedJob.sandbox)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Created</p>
|
||||
<p className="font-medium">{formatTimestamp(selectedJob.createdAt)}</p>
|
||||
|
||||
@@ -27,6 +27,7 @@ function createJob(id: number, name: string): ScheduleJobWithRepo {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
lastRunAt: null,
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { ScheduleJob } from '@opencode-manager/shared/types'
|
||||
import { ScheduleJobDialog } from './ScheduleJobDialog'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { createUseSettingsMock } from '@/test/test-utils'
|
||||
|
||||
Element.prototype.scrollIntoView = vi.fn()
|
||||
|
||||
vi.mock('@/hooks/useSettings')
|
||||
vi.mock('@/hooks/useServerHealth')
|
||||
|
||||
vi.mock('@/hooks/usePromptTemplates', () => ({
|
||||
usePromptTemplates: () => ({ data: [], isLoading: false }),
|
||||
useCreatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useUpdatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useDeletePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useScheduleTarget', () => ({
|
||||
useScheduleTarget: () => ({ scheduleTarget: undefined, isLoading: false, isError: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useScheduleModels', () => ({
|
||||
useScheduleModels: () => ({ availableModels: null, isLoading: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useAgents: () => ({ data: [], isSuccess: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
listManagedSkills: () => Promise.resolve([]),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/mcp', () => ({
|
||||
mcpApi: {
|
||||
getStatus: () => Promise.resolve({}),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
listRepos: () => Promise.resolve([]),
|
||||
listBranches: () => Promise.resolve({ branches: [], status: { ahead: 0, behind: 0 } }),
|
||||
}))
|
||||
|
||||
function mockSandboxPreferences(enabled: boolean, resources: { cpus?: number; memoryMib?: number } = {}) {
|
||||
vi.mocked(useSettings).mockReturnValue(
|
||||
createUseSettingsMock({ preferences: { sandbox: { enabled, ...resources } } }),
|
||||
)
|
||||
}
|
||||
|
||||
function mockSandboxHealth(available: boolean, reason?: string) {
|
||||
vi.mocked(useServerHealth).mockReturnValue({
|
||||
data: { sandbox: { available, enabled: available, enforced: false, reason } },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
} as unknown as ReturnType<typeof useServerHealth>)
|
||||
}
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function getJob(overrides?: Partial<ScheduleJob>): ScheduleJob {
|
||||
return {
|
||||
id: 1,
|
||||
repoId: 1,
|
||||
name: 'Nightly health check',
|
||||
description: null,
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Check the repo.',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
sandbox: null,
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
lastRunAt: null,
|
||||
nextRunAt: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
async function goToGeneralTab(user: ReturnType<typeof userEvent.setup>) {
|
||||
await user.click(screen.getByRole('tab', { name: 'General' }))
|
||||
}
|
||||
|
||||
async function fillRequiredFields(user: ReturnType<typeof userEvent.setup>) {
|
||||
await user.type(screen.getByLabelText('Name'), 'Nightly health check')
|
||||
await user.click(screen.getByRole('tab', { name: 'Prompt' }))
|
||||
await user.type(screen.getByRole('textbox', { name: 'Prompt' }), 'Check the repo.')
|
||||
}
|
||||
|
||||
describe('ScheduleJobDialog — sandbox', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockSandboxPreferences(true)
|
||||
mockSandboxHealth(true)
|
||||
})
|
||||
|
||||
it('submits the CPU and memory overrides when sandboxing is enabled', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog open onOpenChange={vi.fn()} onSubmit={onSubmit} isSaving={false} />,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await fillRequiredFields(user)
|
||||
await goToGeneralTab(user)
|
||||
|
||||
await user.click(screen.getByRole('switch', { name: 'Run in sandbox' }))
|
||||
await user.type(screen.getByLabelText('CPUs'), '4')
|
||||
await user.type(screen.getByLabelText('Memory (GiB)'), '12')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Create schedule' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
expect(onSubmit.mock.calls[0][0].sandbox).toEqual({
|
||||
enabled: true,
|
||||
resources: { cpus: 4, memoryMib: 12288 },
|
||||
})
|
||||
})
|
||||
|
||||
it('disables the switch with an explanation while sandboxing is turned off in settings', async () => {
|
||||
mockSandboxPreferences(false)
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog open onOpenChange={vi.fn()} onSubmit={vi.fn()} isSaving={false} />,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await goToGeneralTab(user)
|
||||
|
||||
expect(screen.getByRole('switch', { name: 'Run in sandbox' })).toBeDisabled()
|
||||
expect(screen.getByText('Sandboxing is turned off in Settings.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('submits sandbox null when an existing sandboxed job is turned off', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
const job = getJob({ sandbox: { enabled: true, resources: { cpus: 4, memoryMib: 12288 } } })
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog open onOpenChange={vi.fn()} job={job} onSubmit={onSubmit} isSaving={false} />,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await goToGeneralTab(user)
|
||||
|
||||
const toggle = screen.getByRole('switch', { name: 'Run in sandbox' })
|
||||
expect(toggle).toBeChecked()
|
||||
expect(screen.getByLabelText('CPUs')).toHaveValue(4)
|
||||
|
||||
await user.click(toggle)
|
||||
await user.click(screen.getByRole('button', { name: 'Save changes' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
expect(onSubmit.mock.calls[0][0].sandbox).toBeNull()
|
||||
})
|
||||
|
||||
it('hides the sandbox option for a non-local server target', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
onSubmit={vi.fn()}
|
||||
isSaving={false}
|
||||
job={getJob({ repoId: null, serverId: 'srv_kitchen', directory: '/srv/projects/audit', workspaceMode: 'in-place' })}
|
||||
serverTarget={{ serverId: 'srv_kitchen', directory: '/srv/projects/audit' }}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await goToGeneralTab(user)
|
||||
|
||||
expect(screen.queryByRole('switch', { name: 'Run in sandbox' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Sandbox')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -61,6 +61,7 @@ const remoteJob: ScheduleJob = {
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'in-place',
|
||||
sandbox: null,
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
lastRunAt: null,
|
||||
|
||||
@@ -23,9 +23,12 @@ import {
|
||||
import { getRepoDisplayName } from '@/lib/utils'
|
||||
import { getPrimaryAgents } from '@/lib/primaryAgents'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME } from '@opencode-manager/shared/utils'
|
||||
import { DEFAULT_DESTRUCTIVE_BASH_PATTERNS } from '@opencode-manager/shared/schemas'
|
||||
import { DEFAULT_DESTRUCTIVE_BASH_PATTERNS, LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { usePromptTemplates, useDeletePromptTemplate } from '@/hooks/usePromptTemplates'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { formatSandboxMemory, parseSandboxResourceInput } from '@/lib/sandboxResources'
|
||||
import { PromptTemplateDialog } from './PromptTemplateDialog'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { GeneralTab } from './GeneralTab'
|
||||
@@ -76,12 +79,29 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
const [allowExternalDirectory, setAllowExternalDirectory] = useState(false)
|
||||
const [allowQuestions, setAllowQuestions] = useState(false)
|
||||
const [bashDenyPatterns, setBashDenyPatterns] = useState<string[]>([...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
|
||||
const [sandboxEnabled, setSandboxEnabled] = useState(false)
|
||||
const [sandboxCpus, setSandboxCpus] = useState('')
|
||||
const [sandboxMemoryGib, setSandboxMemoryGib] = useState('')
|
||||
const [templateDialogOpen, setTemplateDialogOpen] = useState(false)
|
||||
const [editingTemplate, setEditingTemplate] = useState<PromptTemplate | undefined>(undefined)
|
||||
const [deletingTemplateId, setDeletingTemplateId] = useState<number | null>(null)
|
||||
|
||||
const { data: templates = EMPTY_TEMPLATES } = usePromptTemplates()
|
||||
const deleteTemplateMutation = useDeletePromptTemplate()
|
||||
const { preferences } = useSettings()
|
||||
const { data: health } = useServerHealth()
|
||||
|
||||
const showSandbox = !serverTarget || serverTarget.serverId === LOCAL_OPENCODE_SERVER_ID
|
||||
const sandboxPreferences = preferences?.sandbox
|
||||
const sandboxAvailable = health?.sandbox?.available === true
|
||||
const sandboxUnavailableReason = sandboxPreferences?.enabled !== true
|
||||
? 'Sandboxing is turned off in Settings.'
|
||||
: !sandboxAvailable
|
||||
? (health === undefined ? 'Checking sandbox availability...' : (health.sandbox?.reason ?? 'Sandboxing is unavailable on this host.'))
|
||||
: null
|
||||
const parsedSandboxResources = parseSandboxResourceInput(sandboxCpus, sandboxMemoryGib)
|
||||
const sandboxCpusPlaceholder = sandboxPreferences?.cpus !== undefined ? String(sandboxPreferences.cpus) : 'Server default'
|
||||
const sandboxMemoryPlaceholder = sandboxPreferences?.memoryMib !== undefined ? formatSandboxMemory(sandboxPreferences.memoryMib) : 'Server default'
|
||||
|
||||
const serverTargetId = serverTarget?.serverId
|
||||
const serverTargetDirectory = serverTarget?.directory
|
||||
@@ -178,6 +198,10 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
setAllowExternalDirectory(job?.permissionConfig?.allowExternalDirectory ?? false)
|
||||
setAllowQuestions(job?.permissionConfig?.allowQuestions ?? false)
|
||||
setBashDenyPatterns(job?.permissionConfig?.bashDenyPatterns ?? [...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
|
||||
const sandboxResources = job?.sandbox?.enabled ? job.sandbox.resources : null
|
||||
setSandboxEnabled(job?.sandbox?.enabled ?? false)
|
||||
setSandboxCpus(sandboxResources ? String(sandboxResources.cpus) : '')
|
||||
setSandboxMemoryGib(sandboxResources ? formatSandboxMemory(sandboxResources.memoryMib) : '')
|
||||
}, [job, open, serverTargetDirectory])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -215,6 +239,12 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
const skillNotesChanged = skillNotes.trim() !== (initialSkillNotesRef.current ?? '')
|
||||
const shouldIncludeSkillMetadata = skillSlugsChanged || skillNotesChanged
|
||||
|
||||
const sandbox = !showSandbox || !sandboxEnabled
|
||||
? null
|
||||
: parsedSandboxResources.kind === 'valid'
|
||||
? { enabled: true, resources: parsedSandboxResources.resources }
|
||||
: { enabled: true, resources: null }
|
||||
|
||||
const baseFields = {
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
@@ -231,6 +261,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
allowQuestions,
|
||||
bashDenyPatterns: bashDenyPatterns.map((p) => p.trim()).filter(Boolean),
|
||||
},
|
||||
sandbox,
|
||||
...(shouldIncludeSkillMetadata ? {
|
||||
skillMetadata: skillSlugs.length > 0 || skillNotes.trim()
|
||||
? {
|
||||
@@ -268,6 +299,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
prompt.trim() ? null : 'prompt',
|
||||
isScheduleConfigInvalid ? 'valid timing' : null,
|
||||
showRepoSelector && !job && selectedRepoId === undefined ? 'repository' : null,
|
||||
showSandbox && sandboxEnabled && parsedSandboxResources.kind === 'invalid' ? 'valid sandbox resources' : null,
|
||||
].filter((requirement): requirement is string => requirement !== null)
|
||||
|
||||
return (
|
||||
@@ -326,6 +358,19 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
onAllowQuestionsChange={setAllowQuestions}
|
||||
bashDenyPatterns={bashDenyPatterns}
|
||||
onBashDenyPatternsChange={setBashDenyPatterns}
|
||||
sandbox={showSandbox ? {
|
||||
enabled: sandboxEnabled,
|
||||
onEnabledChange: setSandboxEnabled,
|
||||
toggleDisabled: sandboxUnavailableReason !== null && !sandboxEnabled,
|
||||
unavailableReason: sandboxUnavailableReason,
|
||||
cpus: sandboxCpus,
|
||||
onCpusChange: setSandboxCpus,
|
||||
memoryGib: sandboxMemoryGib,
|
||||
onMemoryGibChange: setSandboxMemoryGib,
|
||||
cpusPlaceholder: sandboxCpusPlaceholder,
|
||||
memoryPlaceholder: sandboxMemoryPlaceholder,
|
||||
error: sandboxEnabled && parsedSandboxResources.kind === 'invalid' ? parsedSandboxResources.message : null,
|
||||
} : undefined}
|
||||
/>
|
||||
|
||||
<TimingTab
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import cronstrue from 'cronstrue'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import type { CreateScheduleJobRequest, ScheduleJob, ScheduleRun, ScheduleWorkspaceMode, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
|
||||
import type { CreateScheduleJobRequest, ScheduleJob, ScheduleRun, ScheduleSandboxConfig, ScheduleWorkspaceMode, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
|
||||
import type { RadioOption } from '@/components/ui/radio-option-group'
|
||||
import { formatDuration } from '@/lib/utils'
|
||||
import { formatSandboxResources } from '@/lib/sandboxResources'
|
||||
|
||||
export const intervalOptions = [
|
||||
{ label: '15m', value: 15 },
|
||||
@@ -68,6 +69,14 @@ export function formatWorkspaceMode(mode: ScheduleWorkspaceMode): string {
|
||||
return workspaceModeOptions.find((option) => option.value === mode)?.label ?? mode
|
||||
}
|
||||
|
||||
export function formatScheduleSandbox(sandbox: ScheduleSandboxConfig | null | undefined): string {
|
||||
if (!sandbox?.enabled) {
|
||||
return 'Off'
|
||||
}
|
||||
|
||||
return sandbox.resources ? `On · ${formatSandboxResources(sandbox.resources)}` : 'On · server defaults'
|
||||
}
|
||||
|
||||
export function getLocalTimeZone(): string {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
|
||||
|
||||
@@ -17,16 +17,18 @@ import {
|
||||
SessionSandboxResourcesSchema,
|
||||
type SandboxPreferences,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
SANDBOX_CPUS_MAX,
|
||||
SANDBOX_CPUS_MIN,
|
||||
SANDBOX_MEMORY_GIB_MAX,
|
||||
SANDBOX_MEMORY_GIB_MIN,
|
||||
} from '@/lib/sandboxResources'
|
||||
|
||||
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
|
||||
|
||||
@@ -1,8 +1,54 @@
|
||||
import type { SessionSandboxResources } from '@opencode-manager/shared/schemas'
|
||||
import { SessionSandboxResourcesSchema, type SessionSandboxResources } from '@opencode-manager/shared/schemas'
|
||||
import type { useSandboxToggle } from '@/hooks/useSandboxToggle'
|
||||
|
||||
export type SandboxToggleState = ReturnType<typeof useSandboxToggle>
|
||||
|
||||
const cpusSchema = SessionSandboxResourcesSchema.shape.cpus
|
||||
const memoryMibSchema = SessionSandboxResourcesSchema.shape.memoryMib
|
||||
|
||||
export const SANDBOX_CPUS_MIN = cpusSchema.minValue ?? 1
|
||||
export const SANDBOX_CPUS_MAX = cpusSchema.maxValue ?? 64
|
||||
export const SANDBOX_MEMORY_GIB_MIN = (memoryMibSchema.minValue ?? 1024) / 1024
|
||||
export const SANDBOX_MEMORY_GIB_MAX = (memoryMibSchema.maxValue ?? 1048576) / 1024
|
||||
|
||||
export type SandboxResourceInputResult =
|
||||
| { kind: 'defaults' }
|
||||
| { kind: 'invalid'; message: string }
|
||||
| { kind: 'valid'; resources: SessionSandboxResources }
|
||||
|
||||
export function parseSandboxResourceInput(
|
||||
cpus: string,
|
||||
memoryGib: string,
|
||||
): SandboxResourceInputResult {
|
||||
const trimmedCpus = cpus.trim()
|
||||
const trimmedMemory = memoryGib.trim()
|
||||
if (!trimmedCpus && !trimmedMemory) {
|
||||
return { kind: 'defaults' }
|
||||
}
|
||||
if (!trimmedCpus || !trimmedMemory) {
|
||||
return {
|
||||
kind: 'invalid',
|
||||
message: 'Enter both CPUs and memory, or leave both empty to use the server defaults.',
|
||||
}
|
||||
}
|
||||
const parsedCpus = Number(trimmedCpus)
|
||||
if (!Number.isInteger(parsedCpus) || !cpusSchema.safeParse(parsedCpus).success) {
|
||||
return {
|
||||
kind: 'invalid',
|
||||
message: `CPUs must be a whole number from ${SANDBOX_CPUS_MIN} to ${SANDBOX_CPUS_MAX}.`,
|
||||
}
|
||||
}
|
||||
const parsedMemory = Number(trimmedMemory)
|
||||
const memoryMib = Math.round(parsedMemory * 1024)
|
||||
if (!Number.isFinite(parsedMemory) || !memoryMibSchema.safeParse(memoryMib).success) {
|
||||
return {
|
||||
kind: 'invalid',
|
||||
message: `Memory must be between ${SANDBOX_MEMORY_GIB_MIN} and ${SANDBOX_MEMORY_GIB_MAX} GiB.`,
|
||||
}
|
||||
}
|
||||
return { kind: 'valid', resources: { cpus: parsedCpus, memoryMib } }
|
||||
}
|
||||
|
||||
export function shouldShowSandboxResources(sandbox: SandboxToggleState): boolean {
|
||||
return (
|
||||
sandbox.available &&
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from 'zod'
|
||||
import { SessionSandboxResourcesSchema } from './session-sandbox'
|
||||
|
||||
export const ScheduleRunTriggerSourceSchema = z.enum(['manual', 'schedule'])
|
||||
export type ScheduleRunTriggerSource = z.infer<typeof ScheduleRunTriggerSourceSchema>
|
||||
@@ -128,6 +129,16 @@ export const SchedulePermissionConfigSchema = z.object({
|
||||
})
|
||||
export type SchedulePermissionConfig = z.infer<typeof SchedulePermissionConfigSchema>
|
||||
|
||||
/**
|
||||
* Sandbox settings for a scheduled run's session. `resources` overrides the
|
||||
* default CPU and memory limits; null keeps the server defaults.
|
||||
*/
|
||||
export const ScheduleSandboxConfigSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
resources: SessionSandboxResourcesSchema.nullable(),
|
||||
})
|
||||
export type ScheduleSandboxConfig = z.infer<typeof ScheduleSandboxConfigSchema>
|
||||
|
||||
export type SchedulePermissionEffect = 'allow' | 'deny' | 'ask'
|
||||
|
||||
/**
|
||||
@@ -191,6 +202,7 @@ export const ScheduleJobSchema = z.object({
|
||||
mcpServers: ScheduleMcpServersSchema,
|
||||
branch: z.string().nullable(),
|
||||
workspaceMode: ScheduleWorkspaceModeSchema,
|
||||
sandbox: ScheduleSandboxConfigSchema.nullable(),
|
||||
createdAt: z.number(),
|
||||
updatedAt: z.number(),
|
||||
lastRunAt: z.number().nullable(),
|
||||
@@ -232,6 +244,7 @@ const ScheduleJobBaseRequestSchema = z.object({
|
||||
mcpServers: ScheduleMcpServersSchema.optional(),
|
||||
branch: z.string().min(1).max(200).nullable().optional(),
|
||||
workspaceMode: ScheduleWorkspaceModeSchema.optional(),
|
||||
sandbox: ScheduleSandboxConfigSchema.nullable().optional(),
|
||||
directory: z.string().min(1).max(4096).optional(),
|
||||
})
|
||||
|
||||
@@ -264,6 +277,7 @@ export const UpdateScheduleJobRequestSchema = z.object({
|
||||
mcpServers: ScheduleMcpServersSchema.optional(),
|
||||
branch: z.string().min(1).max(200).nullable().optional(),
|
||||
workspaceMode: ScheduleWorkspaceModeSchema.optional(),
|
||||
sandbox: ScheduleSandboxConfigSchema.nullable().optional(),
|
||||
directory: z.string().min(1).max(4096).nullable().optional(),
|
||||
})
|
||||
export type UpdateScheduleJobRequest = z.infer<typeof UpdateScheduleJobRequestSchema>
|
||||
|
||||
@@ -159,6 +159,7 @@ export type {
|
||||
ScheduleWorktree,
|
||||
RemoveScheduleWorktreesRequest,
|
||||
SchedulePermissionConfig,
|
||||
ScheduleSandboxConfig,
|
||||
ScheduleRunTriggerSource,
|
||||
ScheduleRunStatus,
|
||||
ScheduleSkillMetadata,
|
||||
|
||||
Reference in new issue
Block a user