mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +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
@@ -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(),
|
||||
|
||||
Reference in new issue
Block a user