mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(schedules): run scheduled jobs in a per-job sandbox microVM
This commit is contained in:
1 parent
11a2661cc6
commit
070cb2f729
28 files changed
+1069
-83
No files matched your search
@@ -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 &&
|
||||
|
||||
Reference in new issue
Block a user