mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat: add schedule permission config and workspace tracking (#297)
* feat: add schedule permission config and workspace tracking Adds permission configuration for scheduled jobs (migration 016) and workspace ID tracking on schedule runs (migration 017). Includes service logic, UI controls, schema updates, and full test coverage. * refactor: convert permission ruleset to object format, exclude active schedule worktrees from sibling repos * refine: reduce destructive bash patterns to host-level commands only
This commit is contained in:
1 parent
9425921200
commit
68cd6b5a0b
22 files changed
+1438
-53
No files matched your search
@@ -0,0 +1,27 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
dflt_value: string | null
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 16,
|
||||
name: 'schedule-permission-config',
|
||||
|
||||
up(db) {
|
||||
const cols = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
if (!cols.some((c) => c.name === 'permission_config')) {
|
||||
db.run('ALTER TABLE schedule_jobs ADD COLUMN permission_config TEXT')
|
||||
}
|
||||
},
|
||||
|
||||
down(_db) {
|
||||
void _db
|
||||
// no-op: SQLite drop-column requires table rebuild; column is nullable so
|
||||
// leaving it in place is safe for rollback scenarios.
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
dflt_value: string | null
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 17,
|
||||
name: 'schedule-run-workspace-id',
|
||||
|
||||
up(db) {
|
||||
const cols = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
if (!cols.some((c) => c.name === 'workspace_id')) {
|
||||
db.run('ALTER TABLE schedule_runs ADD COLUMN workspace_id TEXT')
|
||||
}
|
||||
},
|
||||
|
||||
down(_db) {
|
||||
void _db
|
||||
// no-op: SQLite drop-column requires table rebuild; column is nullable so
|
||||
// leaving it in place is safe for rollback scenarios.
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -14,6 +14,8 @@ import migration012 from './012-opencode-model-state'
|
||||
import migration013 from './013-app-secrets'
|
||||
import migration014 from './014-repos-add-name'
|
||||
import migration015 from './015-schedule-worktree-isolation'
|
||||
import migration016 from './016-schedule-permission-config'
|
||||
import migration017 from './017-schedule-run-workspace-id'
|
||||
|
||||
export const allMigrations: Migration[] = [
|
||||
migration001,
|
||||
@@ -31,4 +33,6 @@ export const allMigrations: Migration[] = [
|
||||
migration013,
|
||||
migration014,
|
||||
migration015,
|
||||
migration016,
|
||||
migration017,
|
||||
]
|
||||
@@ -1,10 +1,12 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import {
|
||||
ScheduleJobSchema,
|
||||
SchedulePermissionConfigSchema,
|
||||
ScheduleRunSchema,
|
||||
ScheduleSkillMetadataSchema,
|
||||
type ScheduleJob,
|
||||
type ScheduleMode,
|
||||
type SchedulePermissionConfig,
|
||||
type ScheduleRun,
|
||||
type ScheduleRunStatus,
|
||||
type ScheduleRunTriggerSource,
|
||||
@@ -26,6 +28,7 @@ interface ScheduleJobRow {
|
||||
prompt: string
|
||||
model: string | null
|
||||
skill_metadata: string | null
|
||||
permission_config: string | null
|
||||
branch: string | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
@@ -50,6 +53,7 @@ interface ScheduleRunRow {
|
||||
run_branch: string | null
|
||||
commit_hash: string | null
|
||||
worktree_path: string | null
|
||||
workspace_id: string | null
|
||||
}
|
||||
|
||||
function parseSkillMetadata(raw: string | null) {
|
||||
@@ -66,6 +70,20 @@ function parseSkillMetadata(raw: string | null) {
|
||||
}
|
||||
}
|
||||
|
||||
function parsePermissionConfig(raw: string | null): SchedulePermissionConfig | null {
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
const result = SchedulePermissionConfigSchema.safeParse(parsed)
|
||||
return result.success ? result.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob {
|
||||
return ScheduleJobSchema.parse({
|
||||
id: row.id,
|
||||
@@ -81,6 +99,7 @@ function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob {
|
||||
prompt: row.prompt,
|
||||
model: row.model,
|
||||
skillMetadata: parseSkillMetadata(row.skill_metadata),
|
||||
permissionConfig: parsePermissionConfig(row.permission_config),
|
||||
branch: row.branch,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
@@ -107,6 +126,7 @@ function rowToScheduleRun(row: ScheduleRunRow): ScheduleRun {
|
||||
runBranch: row.run_branch,
|
||||
commitHash: row.commit_hash,
|
||||
worktreePath: row.worktree_path,
|
||||
workspaceId: row.workspace_id,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -118,6 +138,14 @@ function serializeSkillMetadata(skillMetadata: ScheduleJobPersistenceInput['skil
|
||||
return JSON.stringify(skillMetadata)
|
||||
}
|
||||
|
||||
function serializePermissionConfig(permissionConfig: ScheduleJobPersistenceInput['permissionConfig']): string | null {
|
||||
if (!permissionConfig) {
|
||||
return null
|
||||
}
|
||||
|
||||
return JSON.stringify(permissionConfig)
|
||||
}
|
||||
|
||||
export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJob[] {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(repoId) as ScheduleJobRow[]
|
||||
@@ -147,10 +175,11 @@ export function createScheduleJob(db: Database, repoId: number, input: ScheduleJ
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO schedule_jobs (
|
||||
repo_id, name, description, enabled, schedule_mode, interval_minutes, cron_expression, timezone, agent_slug, prompt, model, skill_metadata,
|
||||
permission_config,
|
||||
branch,
|
||||
created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
const result = stmt.run(
|
||||
@@ -166,6 +195,7 @@ export function createScheduleJob(db: Database, repoId: number, input: ScheduleJ
|
||||
input.prompt,
|
||||
input.model ?? null,
|
||||
serializeSkillMetadata(input.skillMetadata),
|
||||
serializePermissionConfig(input.permissionConfig),
|
||||
input.branch,
|
||||
now,
|
||||
now,
|
||||
@@ -191,7 +221,7 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_jobs
|
||||
SET name = ?, description = ?, enabled = ?, schedule_mode = ?, interval_minutes = ?, cron_expression = ?, timezone = ?,
|
||||
agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, branch = ?, updated_at = ?, next_run_at = ?
|
||||
agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, branch = ?, updated_at = ?, next_run_at = ?
|
||||
WHERE repo_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
@@ -207,6 +237,7 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
|
||||
input.prompt,
|
||||
input.model,
|
||||
serializeSkillMetadata(input.skillMetadata),
|
||||
serializePermissionConfig(input.permissionConfig),
|
||||
input.branch,
|
||||
now,
|
||||
input.nextRunAt,
|
||||
@@ -229,20 +260,41 @@ export interface ScheduleRunArtifact {
|
||||
status: ScheduleRunStatus
|
||||
runBranch: string | null
|
||||
worktreePath: string | null
|
||||
workspaceId: string | null
|
||||
}
|
||||
|
||||
export function listScheduleRunArtifactsByJob(db: Database, repoId: number, jobId: number): ScheduleRunArtifact[] {
|
||||
const rows = db
|
||||
.prepare('SELECT id, status, run_branch, worktree_path FROM schedule_runs WHERE repo_id = ? AND job_id = ? ORDER BY id DESC')
|
||||
.all(repoId, jobId) as { id: number; status: string; run_branch: string | null; worktree_path: string | null }[]
|
||||
.prepare('SELECT id, status, run_branch, worktree_path, workspace_id FROM schedule_runs WHERE repo_id = ? AND job_id = ? ORDER BY id DESC')
|
||||
.all(repoId, jobId) as { id: number; status: string; run_branch: string | null; worktree_path: string | null; workspace_id: string | null }[]
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
status: row.status as ScheduleRunStatus,
|
||||
runBranch: row.run_branch,
|
||||
worktreePath: row.worktree_path,
|
||||
workspaceId: row.workspace_id,
|
||||
}))
|
||||
}
|
||||
|
||||
export interface ActiveScheduleRunWorkspace {
|
||||
worktreePath: string | null
|
||||
workspaceId: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the worktree directories and OpenCode workspace IDs of schedule runs
|
||||
* that still hold a live worktree/workspace (both columns are cleared to null
|
||||
* on finalize). Used to keep an in-progress run's isolated worktree out of the
|
||||
* deletable Sibling surface, since worktrees created via the OpenCode workspace
|
||||
* API live outside getScheduleWorktreesPath().
|
||||
*/
|
||||
export function listActiveScheduleRunWorkspaces(db: Database): ActiveScheduleRunWorkspace[] {
|
||||
const rows = db
|
||||
.prepare('SELECT worktree_path, workspace_id FROM schedule_runs WHERE worktree_path IS NOT NULL OR workspace_id IS NOT NULL')
|
||||
.all() as { worktree_path: string | null; workspace_id: string | null }[]
|
||||
return rows.map((row) => ({ worktreePath: row.worktree_path, workspaceId: row.workspace_id }))
|
||||
}
|
||||
|
||||
export function deleteScheduleRunById(db: Database, repoId: number, jobId: number, runId: number): boolean {
|
||||
const result = db
|
||||
.prepare('DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
|
||||
@@ -393,7 +445,7 @@ export function updateScheduleRunWorktree(
|
||||
repoId: number,
|
||||
jobId: number,
|
||||
runId: number,
|
||||
input: { worktreePath?: string | null; runBranch?: string | null; commitHash?: string | null },
|
||||
input: { worktreePath?: string | null; runBranch?: string | null; commitHash?: string | null; workspaceId?: string | null },
|
||||
): ScheduleRun | null {
|
||||
const existing = getScheduleRunById(db, repoId, jobId, runId)
|
||||
if (!existing) {
|
||||
@@ -402,7 +454,7 @@ export function updateScheduleRunWorktree(
|
||||
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_runs
|
||||
SET worktree_path = ?, run_branch = ?, commit_hash = ?
|
||||
SET worktree_path = ?, run_branch = ?, commit_hash = ?, workspace_id = ?
|
||||
WHERE repo_id = ? AND job_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
@@ -410,6 +462,7 @@ export function updateScheduleRunWorktree(
|
||||
input.worktreePath === undefined ? existing.worktreePath : input.worktreePath,
|
||||
input.runBranch === undefined ? existing.runBranch : input.runBranch,
|
||||
input.commitHash === undefined ? existing.commitHash : input.commitHash,
|
||||
input.workspaceId === undefined ? existing.workspaceId : input.workspaceId,
|
||||
repoId,
|
||||
jobId,
|
||||
runId,
|
||||
@@ -464,7 +517,8 @@ export function listScheduleRunsByJob(db: Database, repoId: number, jobId: numbe
|
||||
error_text,
|
||||
run_branch,
|
||||
commit_hash,
|
||||
worktree_path
|
||||
worktree_path,
|
||||
workspace_id
|
||||
FROM schedule_runs
|
||||
WHERE repo_id = ? AND job_id = ?
|
||||
ORDER BY started_at DESC
|
||||
@@ -588,7 +642,7 @@ export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions =
|
||||
sr.started_at, sr.finished_at, sr.created_at,
|
||||
sr.session_id, sr.session_title,
|
||||
NULL AS log_text, NULL AS response_text, sr.error_text,
|
||||
sr.run_branch, sr.commit_hash, sr.worktree_path,
|
||||
sr.run_branch, sr.commit_hash, sr.worktree_path, sr.workspace_id,
|
||||
sj.name AS job_name, r.local_path AS repo_path, r.name AS repo_name,
|
||||
r.repo_url AS repo_url, r.source_path AS repo_source_path
|
||||
FROM schedule_runs sr
|
||||
|
||||
@@ -291,7 +291,7 @@ try {
|
||||
|
||||
const settingsServiceForSchedules = new SettingsService(db)
|
||||
const credentialProvider = new CredentialProvider(db)
|
||||
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, settingsServiceForSchedules, credentialProvider, db)
|
||||
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, settingsServiceForSchedules, credentialProvider, db, openCodeClient)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager)
|
||||
const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import { getErrorMessage } from '../utils/error-utils'
|
||||
import { sseAggregator } from './sse-aggregator'
|
||||
import { resolveProjectId, isGitMainCheckout } from './project-id-resolver'
|
||||
import { listRepos } from '../db/queries'
|
||||
import { listActiveScheduleRunWorkspaces } from '../db/schedules'
|
||||
import { SettingsService } from './settings'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
@@ -1172,6 +1173,16 @@ export async function getSiblingRepos(
|
||||
const reposRoot = canonical(getReposPath())
|
||||
const scheduleWorktreeRoot = canonical(getScheduleWorktreesPath())
|
||||
|
||||
// Schedule runs may create their isolated worktree via the OpenCode workspace
|
||||
// API, which places it outside getScheduleWorktreesPath(). Exclude any live
|
||||
// run's workspace/worktree so an in-progress run is never surfaced as a
|
||||
// deletable Sibling during the window it exists.
|
||||
const activeRuns = listActiveScheduleRunWorkspaces(database)
|
||||
const activeRunWorkspaceIds = new Set(activeRuns.map((run) => run.workspaceId).filter((id): id is string => id !== null))
|
||||
const activeRunDirectories = new Set(
|
||||
activeRuns.map((run) => run.worktreePath).filter((p): p is string => p !== null).map((p) => canonical(p)),
|
||||
)
|
||||
|
||||
const candidates = workspaces.filter((workspace) => {
|
||||
if (workspace.projectID !== targetProjectId) return false
|
||||
if (!workspace.directory) return false
|
||||
@@ -1180,6 +1191,8 @@ export async function getSiblingRepos(
|
||||
if (workspaceDirectory === targetDirectory) return false
|
||||
if (workspaceDirectory === reposRoot) return false
|
||||
if (workspaceDirectory.startsWith(`${scheduleWorktreeRoot}${path.sep}`)) return false
|
||||
if (activeRunWorkspaceIds.has(workspace.id)) return false
|
||||
if (activeRunDirectories.has(workspaceDirectory)) return false
|
||||
if (knownDirectories.has(workspaceDirectory)) return false
|
||||
|
||||
return true
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
CreateScheduleJobRequest,
|
||||
ScheduleJob,
|
||||
ScheduleMode,
|
||||
SchedulePermissionConfig,
|
||||
ScheduleSkillMetadata,
|
||||
UpdateScheduleJobRequest,
|
||||
} from '@opencode-manager/shared/types'
|
||||
@@ -21,6 +22,7 @@ export interface ScheduleJobPersistenceInput {
|
||||
prompt: string
|
||||
model: string | null
|
||||
skillMetadata: ScheduleSkillMetadata | null | undefined
|
||||
permissionConfig: SchedulePermissionConfig | null
|
||||
branch: string | null
|
||||
nextRunAt: number | null
|
||||
}
|
||||
@@ -106,6 +108,7 @@ export function buildCreateSchedulePersistenceInput(input: CreateScheduleJobRequ
|
||||
return {
|
||||
...base,
|
||||
...scheduleConfig,
|
||||
permissionConfig: input.permissionConfig ?? null,
|
||||
nextRunAt: base.enabled ? scheduleConfig.nextRunAt : null,
|
||||
}
|
||||
}
|
||||
@@ -153,6 +156,7 @@ export function buildUpdatedSchedulePersistenceInput(
|
||||
prompt: input.prompt?.trim() || existing.prompt,
|
||||
model: input.model === undefined ? existing.model : (input.model?.trim() || null),
|
||||
skillMetadata: input.skillMetadata !== undefined ? input.skillMetadata : existing.skillMetadata,
|
||||
permissionConfig: input.permissionConfig === undefined ? existing.permissionConfig : (input.permissionConfig ?? null),
|
||||
branch: input.branch === undefined ? existing.branch : (input.branch?.trim() || null),
|
||||
nextRunAt,
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { Repo } from '../types/repo'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
import type { SettingsService } from './settings'
|
||||
import type { CredentialProvider } from './credential-provider'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { resolveGitIdentity, createGitIdentityEnv, isSSHUrl } from '../utils/git-auth'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { resolveDefaultBranch, createWorktreeSafely, removeWorktree } from './repo'
|
||||
@@ -16,6 +17,7 @@ export interface ScheduleWorktreeContext {
|
||||
directory: string
|
||||
worktreePath: string
|
||||
runBranch: string
|
||||
workspaceId: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -29,12 +31,19 @@ export function buildRepoEnvForRepo(repo: { id?: number; fullPath: string }): Re
|
||||
}
|
||||
}
|
||||
|
||||
interface OpenCodeWorkspace {
|
||||
id: string
|
||||
directory: string
|
||||
branch: string | null
|
||||
}
|
||||
|
||||
export class ScheduleWorktreeManager {
|
||||
constructor(
|
||||
private readonly gitAuthService: GitAuthService,
|
||||
private readonly settingsService: SettingsService,
|
||||
private readonly credentialProvider: CredentialProvider,
|
||||
private readonly db: Database,
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
) {}
|
||||
|
||||
async prepare(
|
||||
@@ -68,17 +77,52 @@ export class ScheduleWorktreeManager {
|
||||
}
|
||||
|
||||
const runBranch = `schedule/${job.id}/run-${runId}`
|
||||
|
||||
// Attempt OpenCode workspace API; fall back to raw git worktree on failure
|
||||
let createdWorkspace: OpenCodeWorkspace | null = null
|
||||
try {
|
||||
createdWorkspace = await this.openCodeClient.postJson<OpenCodeWorkspace>(
|
||||
'/experimental/workspace',
|
||||
{ type: 'worktree', branch: null },
|
||||
{ directory: repo.fullPath },
|
||||
)
|
||||
|
||||
// Re-point the workspace to our run branch and base
|
||||
await executeCommand(['git', '-C', createdWorkspace.directory, 'checkout', '-B', runBranch, baseRef], { env })
|
||||
|
||||
if (!existsSync(createdWorkspace.directory)) {
|
||||
throw new Error(`OpenCode workspace directory was not created at: ${createdWorkspace.directory}`)
|
||||
}
|
||||
|
||||
return {
|
||||
directory: createdWorkspace.directory,
|
||||
worktreePath: createdWorkspace.directory,
|
||||
runBranch,
|
||||
workspaceId: createdWorkspace.id,
|
||||
}
|
||||
} catch (apiError) {
|
||||
logger.warn(`OpenCode workspace API failed, falling back to raw git worktree: ${apiError}`)
|
||||
// Best-effort cleanup of created workspace if checkout/setup failed after API success
|
||||
if (createdWorkspace) {
|
||||
this.openCodeClient.forward({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${encodeURIComponent(createdWorkspace.id)}`,
|
||||
directory: repo.fullPath,
|
||||
}).catch(() => {})
|
||||
}
|
||||
// Fall through to raw git path
|
||||
}
|
||||
|
||||
// Fallback: raw git worktree
|
||||
const worktreePath = path.join(getScheduleWorktreesPath(), `job-${job.id}-run-${runId}`)
|
||||
|
||||
mkdirSync(path.dirname(worktreePath), { recursive: true })
|
||||
|
||||
await createWorktreeSafely(repo.fullPath, worktreePath, runBranch, env, baseRef)
|
||||
|
||||
if (!existsSync(worktreePath)) {
|
||||
throw new Error(`Worktree directory was not created at: ${worktreePath}`)
|
||||
}
|
||||
|
||||
return { directory: worktreePath, worktreePath, runBranch }
|
||||
return { directory: worktreePath, worktreePath, runBranch, workspaceId: null }
|
||||
} finally {
|
||||
if (sshSetup) {
|
||||
await this.gitAuthService.cleanupSSHKey()
|
||||
@@ -89,7 +133,7 @@ export class ScheduleWorktreeManager {
|
||||
async finalize(
|
||||
repo: Repo,
|
||||
job: { id: number; name: string; prompt: string },
|
||||
run: { id: number; worktreePath: string | null; runBranch: string | null; triggerSource: string },
|
||||
run: { id: number; worktreePath: string | null; runBranch: string | null; triggerSource: string; workspaceId?: string | null },
|
||||
): Promise<{ commitHash: string | null }> {
|
||||
if (!run.worktreePath) {
|
||||
return { commitHash: null }
|
||||
@@ -97,7 +141,7 @@ export class ScheduleWorktreeManager {
|
||||
|
||||
let sshSetup = false
|
||||
let env: Record<string, string> | undefined
|
||||
let noChanges = false
|
||||
let commitHash: string | null = null
|
||||
|
||||
try {
|
||||
if (repo.repoUrl && isSSHUrl(repo.repoUrl)) {
|
||||
@@ -109,33 +153,54 @@ export class ScheduleWorktreeManager {
|
||||
|
||||
const status = await executeCommand(['git', '-C', run.worktreePath, 'status', '--porcelain'], { env }).catch(() => '')
|
||||
|
||||
if (!status.trim()) {
|
||||
noChanges = true
|
||||
return { commitHash: null }
|
||||
if (status.trim()) {
|
||||
await executeCommand(['git', '-C', run.worktreePath, 'add', '-A'], { env })
|
||||
|
||||
const title = `Scheduled run: ${job.name} (run #${run.id})`
|
||||
const promptSummary = job.prompt.length > 200 ? `${job.prompt.slice(0, 200)}...` : job.prompt
|
||||
const body = `Trigger: ${run.triggerSource}\nPrompt: ${promptSummary}`
|
||||
await executeCommand(['git', '-C', run.worktreePath, 'commit', '-m', title, '-m', body], { env })
|
||||
|
||||
commitHash = (await executeCommand(['git', '-C', run.worktreePath, 'rev-parse', 'HEAD'], { env })).trim()
|
||||
}
|
||||
|
||||
await executeCommand(['git', '-C', run.worktreePath, 'add', '-A'], { env })
|
||||
|
||||
const title = `Scheduled run: ${job.name} (run #${run.id})`
|
||||
const promptSummary = job.prompt.length > 200 ? `${job.prompt.slice(0, 200)}...` : job.prompt
|
||||
const body = `Trigger: ${run.triggerSource}\nPrompt: ${promptSummary}`
|
||||
await executeCommand(['git', '-C', run.worktreePath, 'commit', '-m', title, '-m', body], { env })
|
||||
|
||||
const commitHash = (await executeCommand(['git', '-C', run.worktreePath, 'rev-parse', 'HEAD'], { env })).trim()
|
||||
// Detach HEAD to protect the run branch from accidental pushes
|
||||
await executeCommand(['git', '-C', run.worktreePath, 'checkout', '--detach'], { env }).catch(() => {})
|
||||
|
||||
return { commitHash }
|
||||
} catch (error) {
|
||||
logger.error(`Failed to finalize schedule run ${run.id} in worktree ${run.worktreePath}:`, error)
|
||||
throw error
|
||||
} finally {
|
||||
// Teardown: delete the worktree/workspace
|
||||
try {
|
||||
await removeWorktree(repo.fullPath, run.worktreePath, env)
|
||||
if (noChanges && run.runBranch) {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', run.runBranch], env ? { env } : undefined).catch(() => {})
|
||||
}
|
||||
await this.deleteWorkspaceOrFallback(repo, run, env)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to remove worktree ${run.worktreePath}:`, error)
|
||||
// Best-effort fallback
|
||||
await removeWorktree(repo.fullPath, run.worktreePath, env).catch(() => {})
|
||||
}
|
||||
|
||||
// Branch reconciliation: ensure the run branch survives teardown
|
||||
if (run.runBranch) {
|
||||
try {
|
||||
if (!commitHash) {
|
||||
// No changes: remove the empty run branch
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', run.runBranch], env ? { env } : undefined).catch(() => {})
|
||||
} else if (run.workspaceId) {
|
||||
// Only the workspace API teardown can remove the run branch; the raw
|
||||
// git fallback leaves it intact, so verify/restore only matters here.
|
||||
try {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'rev-parse', '--verify', `refs/heads/${run.runBranch}`], { env, silent: true })
|
||||
} catch {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'branch', run.runBranch, commitHash], { env })
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Best-effort
|
||||
}
|
||||
}
|
||||
|
||||
if (sshSetup) {
|
||||
await this.gitAuthService.cleanupSSHKey()
|
||||
}
|
||||
@@ -148,16 +213,28 @@ export class ScheduleWorktreeManager {
|
||||
* are local git operations, so no SSH setup is needed; failures are swallowed
|
||||
* per artifact so one bad entry does not block the rest.
|
||||
*/
|
||||
async pruneRunArtifacts(repo: Repo, artifacts: { runBranch: string | null; worktreePath: string | null }[]): Promise<void> {
|
||||
async pruneRunArtifacts(
|
||||
repo: Repo,
|
||||
artifacts: { runBranch: string | null; worktreePath: string | null; workspaceId?: string | null }[],
|
||||
): Promise<void> {
|
||||
if (artifacts.length === 0) return
|
||||
|
||||
const env = await this.buildGitEnv(repo, false, true)
|
||||
|
||||
for (const artifact of artifacts) {
|
||||
if (artifact.worktreePath) {
|
||||
await removeWorktree(repo.fullPath, artifact.worktreePath, env)
|
||||
}
|
||||
}
|
||||
// Workspace/worktree removals are independent per artifact, so run them
|
||||
// concurrently; failures are swallowed per artifact so one bad entry does
|
||||
// not block the rest.
|
||||
await Promise.all(
|
||||
artifacts.map(async (artifact) => {
|
||||
try {
|
||||
await this.deleteWorkspaceOrFallback(repo, artifact, env)
|
||||
} catch {
|
||||
if (artifact.worktreePath) {
|
||||
await removeWorktree(repo.fullPath, artifact.worktreePath, env).catch(() => {})
|
||||
}
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
const branches = artifacts.map((a) => a.runBranch).filter((b): b is string => b !== null && b.length > 0)
|
||||
if (branches.length > 0) {
|
||||
@@ -165,6 +242,33 @@ export class ScheduleWorktreeManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a run's worktree, preferring the OpenCode workspace API when a
|
||||
* workspaceId is present and falling back to a raw `git worktree remove` when
|
||||
* the API is unavailable or returns a non-ok response.
|
||||
*/
|
||||
private async deleteWorkspaceOrFallback(
|
||||
repo: Repo,
|
||||
artifact: { workspaceId?: string | null; worktreePath: string | null },
|
||||
env: Record<string, string> | undefined,
|
||||
): Promise<void> {
|
||||
if (artifact.workspaceId) {
|
||||
const response = await this.openCodeClient.forward({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${encodeURIComponent(artifact.workspaceId)}`,
|
||||
directory: repo.fullPath,
|
||||
})
|
||||
if (!response.ok) {
|
||||
logger.warn(`OpenCode workspace DELETE returned ${response.status}, falling back to raw removeWorktree`)
|
||||
if (artifact.worktreePath) {
|
||||
await removeWorktree(repo.fullPath, artifact.worktreePath, env)
|
||||
}
|
||||
}
|
||||
} else if (artifact.worktreePath) {
|
||||
await removeWorktree(repo.fullPath, artifact.worktreePath, env)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a user-supplied base branch name to a verified git ref, preferring
|
||||
* the remote-tracking branch for freshness. Returns null when neither the
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type ScheduleRunTriggerSource,
|
||||
type UpdateScheduleJobRequest,
|
||||
} from '@opencode-manager/shared/types'
|
||||
import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import type { ScheduleJobWithRepo } from '../db/schedules'
|
||||
import {
|
||||
@@ -540,7 +541,7 @@ export class ScheduleService {
|
||||
throw new ScheduleServiceError('Cannot delete a run while it is in progress. Cancel it first.', 409)
|
||||
}
|
||||
|
||||
await this.worktreeManager.pruneRunArtifacts(repo, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }])
|
||||
await this.worktreeManager.pruneRunArtifacts(repo, [{ runBranch: run.runBranch, worktreePath: run.worktreePath, workspaceId: run.workspaceId }])
|
||||
const deleted = deleteScheduleRunById(this.db, repoId, jobId, runId)
|
||||
if (!deleted) {
|
||||
throw new ScheduleServiceError('Run not found', 404)
|
||||
@@ -580,6 +581,7 @@ export class ScheduleService {
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, run.id, {
|
||||
worktreePath: wt.worktreePath,
|
||||
runBranch: wt.runBranch,
|
||||
workspaceId: wt.workspaceId,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -594,6 +596,7 @@ export class ScheduleService {
|
||||
body: JSON.stringify({
|
||||
title: sessionTitle,
|
||||
agent: job.agentSlug ?? undefined,
|
||||
permission: buildSchedulePermissionRuleset(job.permissionConfig),
|
||||
}),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
@@ -1111,11 +1114,12 @@ export class ScheduleService {
|
||||
worktreePath: fresh.worktreePath,
|
||||
runBranch: fresh.runBranch,
|
||||
triggerSource: fresh.triggerSource,
|
||||
workspaceId: fresh.workspaceId,
|
||||
})
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null, commitHash })
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null, commitHash, workspaceId: null })
|
||||
} catch (error) {
|
||||
logger.error(`Failed to finalize worktree for run ${runId}:`, error)
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null })
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null, workspaceId: null })
|
||||
}
|
||||
} finally {
|
||||
ScheduleService.activeTeardowns.delete(key)
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, expect, it, beforeEach } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { createScheduleJob, getScheduleJobById, updateScheduleJob } from '../../src/db/schedules'
|
||||
import type { ScheduleJobPersistenceInput } from '../../src/services/schedule-config'
|
||||
|
||||
describe('schedule permission config persistence', () => {
|
||||
let db: Database
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
db.exec('PRAGMA foreign_keys = OFF')
|
||||
migrate(db, allMigrations)
|
||||
|
||||
const now = Date.now()
|
||||
db.exec(
|
||||
`INSERT INTO repos (id, repo_url, local_path, branch, default_branch, clone_status, cloned_at)
|
||||
VALUES (1, 'https://github.com/test/repo', 'repos/test', 'main', 'main', 'ready', ${now})`,
|
||||
)
|
||||
})
|
||||
|
||||
const baseInput = (overrides: Partial<ScheduleJobPersistenceInput> = {}): ScheduleJobPersistenceInput => ({
|
||||
name: 'Permission test job',
|
||||
description: null,
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Run a permission test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.now() + 3600000,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
it('round-trips permissionConfig when set on create', () => {
|
||||
const config = {
|
||||
allowExternalDirectory: true,
|
||||
bashDenyPatterns: ['rm -rf /'],
|
||||
}
|
||||
const created = createScheduleJob(db, 1, baseInput({ permissionConfig: config }))
|
||||
|
||||
expect(created.permissionConfig).toEqual(config)
|
||||
|
||||
const fetched = getScheduleJobById(db, 1, created.id)
|
||||
expect(fetched).not.toBeNull()
|
||||
expect(fetched!.permissionConfig).toEqual(config)
|
||||
})
|
||||
|
||||
it('returns null permissionConfig when not provided on create', () => {
|
||||
const created = createScheduleJob(db, 1, baseInput())
|
||||
|
||||
expect(created.permissionConfig).toBeNull()
|
||||
|
||||
const fetched = getScheduleJobById(db, 1, created.id)
|
||||
expect(fetched).not.toBeNull()
|
||||
expect(fetched!.permissionConfig).toBeNull()
|
||||
})
|
||||
|
||||
it('updates permissionConfig independently of other fields', () => {
|
||||
const created = createScheduleJob(db, 1, baseInput())
|
||||
expect(created.permissionConfig).toBeNull()
|
||||
|
||||
const config = {
|
||||
allowExternalDirectory: false,
|
||||
bashDenyPatterns: ['sudo rm -rf *'],
|
||||
}
|
||||
const updated = updateScheduleJob(db, 1, created.id, baseInput({ permissionConfig: config }))
|
||||
expect(updated).not.toBeNull()
|
||||
expect(updated!.permissionConfig).toEqual(config)
|
||||
|
||||
// Verify other fields are unchanged
|
||||
expect(updated!.name).toBe('Permission test job')
|
||||
expect(updated!.prompt).toBe('Run a permission test')
|
||||
})
|
||||
|
||||
it('clears permissionConfig when set to null on update', () => {
|
||||
const config = { allowExternalDirectory: true, bashDenyPatterns: [] }
|
||||
const created = createScheduleJob(db, 1, baseInput({ permissionConfig: config }))
|
||||
expect(created.permissionConfig).toEqual(config)
|
||||
|
||||
const updated = updateScheduleJob(db, 1, created.id, baseInput({ permissionConfig: null }))
|
||||
expect(updated).not.toBeNull()
|
||||
expect(updated!.permissionConfig).toBeNull()
|
||||
})
|
||||
|
||||
it('preserves permissionConfig when updating other fields', () => {
|
||||
const config = { allowExternalDirectory: false, bashDenyPatterns: ['rm -rf *'] }
|
||||
const created = createScheduleJob(db, 1, baseInput({ permissionConfig: config }))
|
||||
expect(created.permissionConfig).toEqual(config)
|
||||
|
||||
const updated = updateScheduleJob(db, 1, created.id, {
|
||||
...baseInput({ permissionConfig: config }),
|
||||
name: 'Updated name',
|
||||
prompt: 'Updated prompt',
|
||||
})
|
||||
expect(updated).not.toBeNull()
|
||||
expect(updated!.name).toBe('Updated name')
|
||||
expect(updated!.prompt).toBe('Updated prompt')
|
||||
expect(updated!.permissionConfig).toEqual(config)
|
||||
})
|
||||
})
|
||||
@@ -20,6 +20,7 @@ function makeJobRow(overrides: Record<string, unknown> = {}) {
|
||||
prompt: 'Generate a weekly summary.',
|
||||
model: 'openai/gpt-5-mini',
|
||||
skill_metadata: JSON.stringify({ skillSlugs: ['planning'], notes: 'Optional notes' }),
|
||||
permission_config: null,
|
||||
branch: null,
|
||||
created_at: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
updated_at: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
@@ -47,6 +48,7 @@ function makeRunRow(overrides: Record<string, unknown> = {}) {
|
||||
run_branch: null,
|
||||
commit_hash: null,
|
||||
worktree_path: null,
|
||||
workspace_id: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
@@ -111,6 +113,7 @@ describe('schedule database queries', () => {
|
||||
prompt: 'Generate a weekly summary.',
|
||||
model: 'openai/gpt-5-mini',
|
||||
skillMetadata: { skillSlugs: ['planning'], notes: 'Optional notes' },
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
})
|
||||
@@ -129,6 +132,7 @@ describe('schedule database queries', () => {
|
||||
'openai/gpt-5-mini',
|
||||
JSON.stringify({ skillSlugs: ['planning'], notes: 'Optional notes' }),
|
||||
null,
|
||||
null,
|
||||
expect.any(Number),
|
||||
expect.any(Number),
|
||||
null,
|
||||
@@ -165,6 +169,7 @@ describe('schedule database queries', () => {
|
||||
prompt: 'Run a new summary.',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: null,
|
||||
})
|
||||
@@ -182,6 +187,7 @@ describe('schedule database queries', () => {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
expect.any(Number),
|
||||
null,
|
||||
42,
|
||||
@@ -300,6 +306,7 @@ describe('schedule database queries', () => {
|
||||
'/worktrees/feature-branch',
|
||||
'feature-x',
|
||||
null,
|
||||
null,
|
||||
42,
|
||||
7,
|
||||
5,
|
||||
@@ -602,8 +609,8 @@ describe('schedule database queries', () => {
|
||||
it('listScheduleRunArtifactsByJob maps run branch/worktree rows', () => {
|
||||
const stmt = {
|
||||
all: vi.fn().mockReturnValue([
|
||||
{ id: 3, status: 'completed', run_branch: 'schedule/7/run-3', worktree_path: null },
|
||||
{ id: 2, status: 'running', run_branch: 'schedule/7/run-2', worktree_path: '/wt/2' },
|
||||
{ id: 3, status: 'completed', run_branch: 'schedule/7/run-3', worktree_path: null, workspace_id: null },
|
||||
{ id: 2, status: 'running', run_branch: 'schedule/7/run-2', worktree_path: '/wt/2', workspace_id: null },
|
||||
]),
|
||||
}
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
@@ -612,8 +619,8 @@ describe('schedule database queries', () => {
|
||||
|
||||
expect(stmt.all).toHaveBeenCalledWith(42, 7)
|
||||
expect(artifacts).toEqual([
|
||||
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null },
|
||||
{ id: 2, status: 'running', runBranch: 'schedule/7/run-2', worktreePath: '/wt/2' },
|
||||
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null, workspaceId: null },
|
||||
{ id: 2, status: 'running', runBranch: 'schedule/7/run-2', worktreePath: '/wt/2', workspaceId: null },
|
||||
])
|
||||
})
|
||||
|
||||
|
||||
@@ -11,7 +11,10 @@ export class Database {
|
||||
prepare(sql: string) {
|
||||
const stmt = this.db.prepare(sql)
|
||||
return {
|
||||
run: (...params: unknown[]) => (stmt.run as (...args: unknown[]) => void)(...params),
|
||||
run: (...params: unknown[]) => {
|
||||
const result = (stmt.run as (...args: unknown[]) => { changes: number; lastInsertRowid: number })(...params)
|
||||
return { changes: result.changes, lastInsertRowid: result.lastInsertRowid }
|
||||
},
|
||||
get: (...params: unknown[]) => (stmt.get as (...args: unknown[]) => unknown)(...params),
|
||||
all: (...params: unknown[]) => (stmt.all as (...args: unknown[]) => unknown[])(...params),
|
||||
}
|
||||
@@ -27,7 +30,8 @@ export class Database {
|
||||
|
||||
run(sql: string, ...params: unknown[]) {
|
||||
const stmt = this.db.prepare(sql)
|
||||
return (stmt.run as (...args: unknown[]) => void)(...params)
|
||||
const result = (stmt.run as (...args: unknown[]) => { changes: number; lastInsertRowid: number })(...params)
|
||||
return { changes: result.changes, lastInsertRowid: result.lastInsertRowid }
|
||||
}
|
||||
|
||||
transaction<T extends (...args: unknown[]) => void>(fn: T) {
|
||||
|
||||
@@ -33,6 +33,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Review the repository and summarize risks.',
|
||||
model: 'openai/gpt-5',
|
||||
skillMetadata: undefined,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: currentDate + 60 * 60_000,
|
||||
})
|
||||
@@ -71,6 +72,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Old prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
@@ -101,6 +103,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Old prompt',
|
||||
model: 'openai/gpt-5-mini',
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
@@ -134,6 +137,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: 'feature/foo',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
@@ -163,6 +167,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
@@ -192,6 +197,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: 'feature/foo',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
@@ -221,6 +227,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Run a report',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: null,
|
||||
lastRunAt: null,
|
||||
@@ -263,6 +270,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: null,
|
||||
lastRunAt: null,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { DEFAULT_DESTRUCTIVE_BASH_PATTERNS, buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
|
||||
|
||||
describe('buildSchedulePermissionRuleset', () => {
|
||||
it('returns the allow-all baseline with default deny rules when given null', () => {
|
||||
const result = buildSchedulePermissionRuleset(null)
|
||||
|
||||
expect(result['*']).toBe('allow')
|
||||
expect(result.external_directory).toBe('deny')
|
||||
for (const pattern of DEFAULT_DESTRUCTIVE_BASH_PATTERNS) {
|
||||
expect(result.bash?.[pattern]).toBe('deny')
|
||||
}
|
||||
})
|
||||
|
||||
it('returns only the allow-all baseline when all permissions are granted', () => {
|
||||
const result = buildSchedulePermissionRuleset({ allowExternalDirectory: true, bashDenyPatterns: [] })
|
||||
|
||||
expect(result).toEqual({ '*': 'allow' })
|
||||
})
|
||||
|
||||
it('includes a single custom bash deny pattern alongside external_directory deny', () => {
|
||||
const result = buildSchedulePermissionRuleset({ allowExternalDirectory: false, bashDenyPatterns: ['rm -rf *'] })
|
||||
|
||||
expect(result).toEqual({
|
||||
'*': 'allow',
|
||||
external_directory: 'deny',
|
||||
bash: { 'rm -rf *': 'deny' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -72,6 +72,19 @@ describe('ScheduleWorktreeManager', () => {
|
||||
}
|
||||
const mockDb = {} as any
|
||||
|
||||
// Default mock OpenCodeClient: postJson rejects (triggers fallback), forward
|
||||
// returns an ok response for teardown safety.
|
||||
const mockOpenCodeClient = {
|
||||
postJson: vi.fn().mockRejectedValue(new Error('API unavailable')),
|
||||
forward: vi.fn().mockResolvedValue(new Response(null, { status: 200 })),
|
||||
getJson: vi.fn(),
|
||||
forwardRaw: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
tmpDir = mkdtempSync(path.join(tmpdir(), 'schedule-worktree-test-'))
|
||||
tmpRoot = tmpDir
|
||||
@@ -113,6 +126,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
mockSettingsService as any,
|
||||
mockCredentialProvider as any,
|
||||
mockDb,
|
||||
mockOpenCodeClient as any,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -126,9 +140,9 @@ describe('ScheduleWorktreeManager', () => {
|
||||
} as any
|
||||
}
|
||||
|
||||
// ---- Tests ----
|
||||
// ---- Fallback (raw git) tests ----
|
||||
|
||||
it('prepare creates a worktree with the correct branch name and returns context', async () => {
|
||||
it('prepare creates a worktree with the correct branch name and returns context (raw git fallback)', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 10, branch: null }
|
||||
@@ -140,6 +154,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
expect(ctx!.directory).toBeDefined()
|
||||
expect(ctx!.worktreePath).toBe(ctx!.directory)
|
||||
expect(ctx!.runBranch).toBe(`schedule/10/run-1`)
|
||||
expect(ctx!.workspaceId).toBeNull()
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
|
||||
// The checked-out branch in the worktree must match the run branch
|
||||
@@ -260,7 +275,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
expect(existsSync(path.join(scheduleWorktreesRoot, 'job-21-run-1'))).toBe(false)
|
||||
})
|
||||
|
||||
it('prepare respects the branch override', async () => {
|
||||
it('prepare respects the branch override (raw git fallback)', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 20, branch: 'dev' }
|
||||
@@ -285,4 +300,252 @@ describe('ScheduleWorktreeManager', () => {
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, ctx!.worktreePath)
|
||||
})
|
||||
|
||||
// ---- OpenCode API path tests ----
|
||||
|
||||
/**
|
||||
* Helper: creates a linked git worktree directory (rather than a clone) so
|
||||
* that refs and objects are shared with the base repo. The worktree is
|
||||
* created with a temp branch that prepare() will later overwrite via
|
||||
* `checkout -B`.
|
||||
*/
|
||||
async function createWorktreeWorkspace(dirName: string): Promise<{ directory: string; cleanup: () => Promise<void> }> {
|
||||
const directory = path.join(tmpDir, dirName)
|
||||
const tempBranch = `_temp_${dirName}`
|
||||
// Create a detached worktree on the current HEAD without creating a branch
|
||||
execSync(`git -C "${baseRepoPath}" worktree add --detach "${directory}" origin/main`, { env })
|
||||
execSync(`git -C "${directory}" config user.email test@test.com`, { env })
|
||||
execSync(`git -C "${directory}" config user.name Test`, { env })
|
||||
const cleanup = async () => {
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, directory)
|
||||
// Also remove any leftover branch the test might have created
|
||||
execSync(`git -C "${baseRepoPath}" branch -D "${tempBranch}" 2>/dev/null || true`, { env })
|
||||
}
|
||||
return { directory, cleanup }
|
||||
}
|
||||
|
||||
it('prepare calls POST /experimental/workspace and returns workspaceId on success', async () => {
|
||||
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-workspace')
|
||||
|
||||
const workspaceId = 'ws-test-123'
|
||||
const mockPost = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: workspaceDirectory,
|
||||
branch: null,
|
||||
})
|
||||
mockOpenCodeClient.postJson = mockPost
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 30, branch: null }
|
||||
const runId = 5
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBe(workspaceId)
|
||||
expect(ctx!.runBranch).toBe('schedule/30/run-5')
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
expect(ctx!.worktreePath).toBe(workspaceDirectory)
|
||||
|
||||
// Verify the API was called correctly
|
||||
expect(mockPost).toHaveBeenCalledWith(
|
||||
'/experimental/workspace',
|
||||
{ type: 'worktree', branch: null },
|
||||
{ directory: repo.fullPath },
|
||||
)
|
||||
|
||||
// Verify the branch was re-pointed
|
||||
const branch = execSync(`git -C "${workspaceDirectory}" rev-parse --abbrev-ref HEAD`, {
|
||||
encoding: 'utf-8',
|
||||
}).trim()
|
||||
expect(branch).toBe('schedule/30/run-5')
|
||||
|
||||
// Cleanup
|
||||
await cleanup()
|
||||
})
|
||||
|
||||
it('prepare falls back to raw git when postJson rejects', async () => {
|
||||
mockOpenCodeClient.postJson = vi.fn().mockRejectedValue(new Error('API unavailable'))
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 40, branch: null }
|
||||
const runId = 10
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBeNull()
|
||||
expect(ctx!.runBranch).toBe('schedule/40/run-10')
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
|
||||
// The worktree path should be under scheduleWorktreesRoot (raw git path)
|
||||
expect(ctx!.worktreePath).toContain(scheduleWorktreesRoot)
|
||||
|
||||
// Cleanup
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, ctx!.worktreePath)
|
||||
})
|
||||
|
||||
it('finalize deletes workspace via API when workspaceId is set', async () => {
|
||||
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-finalize-test')
|
||||
|
||||
const workspaceId = 'ws-finalize-456'
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: workspaceDirectory,
|
||||
branch: null,
|
||||
})
|
||||
|
||||
const deleteMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
|
||||
mockOpenCodeClient.forward = deleteMock
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 50, branch: null, name: 'Finalize API' }
|
||||
const runId = 300
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBe(workspaceId)
|
||||
|
||||
// Write a file so there are changes to commit
|
||||
writeFileSync(path.join(workspaceDirectory, 'output.md'), '# API Finalize Test')
|
||||
|
||||
const result = await manager.finalize(
|
||||
repo,
|
||||
{ id: 50, name: 'Finalize API', prompt: 'test' },
|
||||
{ id: runId, worktreePath: workspaceDirectory, runBranch: ctx!.runBranch, triggerSource: 'manual', workspaceId: ctx!.workspaceId },
|
||||
)
|
||||
|
||||
expect(result.commitHash).toMatch(/^[0-9a-f]{40}$/)
|
||||
|
||||
// Verify DELETE was called with the correct workspaceId
|
||||
expect(deleteMock).toHaveBeenCalledWith({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${encodeURIComponent(workspaceId)}`,
|
||||
directory: repo.fullPath,
|
||||
})
|
||||
|
||||
// The commit must still be reachable on the runBranch in the base repo
|
||||
const log = execSync(`git -C "${baseRepoPath}" log "${ctx!.runBranch}" --oneline`, {
|
||||
encoding: 'utf-8',
|
||||
}).trim()
|
||||
expect(log).toBeTruthy()
|
||||
|
||||
// Clean up in case the API mock didn't actually remove the worktree
|
||||
await cleanup()
|
||||
})
|
||||
|
||||
it('finalize falls back to raw removeWorktree when workspace DELETE fails', async () => {
|
||||
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-delete-fail')
|
||||
|
||||
const workspaceId = 'ws-delete-fail-789'
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: workspaceDirectory,
|
||||
branch: null,
|
||||
})
|
||||
// DELETE returns non-ok response → triggers fallback removeWorktree
|
||||
mockOpenCodeClient.forward = vi.fn().mockResolvedValue(new Response('Not Found', { status: 404 }))
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 60, branch: null, name: 'Delete Fail' }
|
||||
const runId = 400
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBe(workspaceId)
|
||||
|
||||
writeFileSync(path.join(workspaceDirectory, 'data.txt'), 'test data')
|
||||
|
||||
const result = await manager.finalize(
|
||||
repo,
|
||||
{ id: 60, name: 'Delete Fail', prompt: 'test' },
|
||||
{ id: runId, worktreePath: workspaceDirectory, runBranch: ctx!.runBranch, triggerSource: 'manual', workspaceId: ctx!.workspaceId },
|
||||
)
|
||||
|
||||
expect(result.commitHash).toMatch(/^[0-9a-f]{40}$/)
|
||||
// Directory should be cleaned up (via fallback removeWorktree)
|
||||
expect(existsSync(workspaceDirectory)).toBe(false)
|
||||
|
||||
// Clean up in case the directory somehow still exists
|
||||
await cleanup()
|
||||
})
|
||||
|
||||
it('finalize restores run branch if OpenCode delete removed it', async () => {
|
||||
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-branch-restore')
|
||||
|
||||
const workspaceId = 'ws-branch-restore-101'
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: workspaceDirectory,
|
||||
branch: null,
|
||||
})
|
||||
mockOpenCodeClient.forward = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 70, branch: null, name: 'Branch Restore' }
|
||||
const runId = 500
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBe(workspaceId)
|
||||
|
||||
writeFileSync(path.join(workspaceDirectory, 'important.md'), '# Branch Restore Test')
|
||||
|
||||
// Simulate: API delete removes the branch. First detach the worktree
|
||||
// HEAD so git allows the deletion (OpenCode's workspace DELETE handles
|
||||
// the worktree-level cleanup first, then the branch goes away).
|
||||
const runBranch = ctx!.runBranch!
|
||||
execSync(`git -C "${workspaceDirectory}" checkout --detach`, { env })
|
||||
execSync(`git -C "${baseRepoPath}" branch -D "${runBranch}"`, { env })
|
||||
|
||||
const result = await manager.finalize(
|
||||
repo,
|
||||
{ id: 70, name: 'Branch Restore', prompt: 'test' },
|
||||
{ id: runId, worktreePath: workspaceDirectory, runBranch, triggerSource: 'manual', workspaceId: ctx!.workspaceId },
|
||||
)
|
||||
|
||||
expect(result.commitHash).toMatch(/^[0-9a-f]{40}$/)
|
||||
|
||||
// Branch should have been restored by finalize
|
||||
const branchExists = execSync(`git -C "${baseRepoPath}" rev-parse --verify "refs/heads/${runBranch}"`, {
|
||||
encoding: 'utf-8',
|
||||
}).trim()
|
||||
expect(branchExists).toBeTruthy()
|
||||
|
||||
// And the commit hash should match
|
||||
const branchCommit = execSync(`git -C "${baseRepoPath}" rev-parse "${runBranch}"`, {
|
||||
encoding: 'utf-8',
|
||||
}).trim()
|
||||
expect(branchCommit).toBe(result.commitHash)
|
||||
|
||||
await cleanup()
|
||||
})
|
||||
|
||||
it('prepare returns workspaceId null on postJson failure (fallback path)', async () => {
|
||||
mockOpenCodeClient.postJson = vi.fn().mockRejectedValue(new Error('Network error'))
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 80, branch: 'main' }
|
||||
const runId = 15
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBeNull()
|
||||
expect(ctx!.runBranch).toBe('schedule/80/run-15')
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
expect(ctx!.worktreePath).toContain(scheduleWorktreesRoot)
|
||||
|
||||
// Cleanup
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, ctx!.worktreePath)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,314 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ScheduleJob, ScheduleRun } from '@opencode-manager/shared/types'
|
||||
import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getRepoById: vi.fn(),
|
||||
createScheduleJob: vi.fn(),
|
||||
createScheduleRun: vi.fn(),
|
||||
deleteScheduleJob: vi.fn(),
|
||||
deleteScheduleRunById: vi.fn(),
|
||||
deleteScheduleRunsByIds: vi.fn(),
|
||||
listScheduleRunArtifactsByJob: vi.fn(),
|
||||
cleanupOrphanedSchedules: vi.fn(),
|
||||
getScheduleJobById: vi.fn(),
|
||||
getRunningScheduleRunByJob: vi.fn(),
|
||||
getScheduleRunById: vi.fn(),
|
||||
listEnabledScheduleJobs: vi.fn(),
|
||||
listRunningScheduleRuns: vi.fn(),
|
||||
listScheduleJobIdsByRepo: vi.fn(),
|
||||
listScheduleJobsByRepo: vi.fn(),
|
||||
listScheduleRunsByJob: vi.fn(),
|
||||
updateScheduleJob: vi.fn(),
|
||||
updateScheduleJobRunState: vi.fn(),
|
||||
updateScheduleRun: vi.fn(),
|
||||
updateScheduleRunMetadata: vi.fn(),
|
||||
buildCreateSchedulePersistenceInput: vi.fn(),
|
||||
buildUpdatedSchedulePersistenceInput: vi.fn(),
|
||||
computeNextRunAtForJob: vi.fn(),
|
||||
|
||||
resolveOpenCodeModel: vi.fn(),
|
||||
forward: vi.fn(),
|
||||
onEvent: vi.fn(),
|
||||
loggerError: vi.fn(),
|
||||
updateScheduleRunWorktree: vi.fn(),
|
||||
stubWorktreeManager: {
|
||||
prepare: vi.fn().mockResolvedValue(null),
|
||||
finalize: vi.fn().mockResolvedValue({ commitHash: null }),
|
||||
pruneRunArtifacts: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/db/queries', () => ({
|
||||
getRepoById: mocks.getRepoById,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/db/schedules', () => ({
|
||||
createScheduleJob: mocks.createScheduleJob,
|
||||
createScheduleRun: mocks.createScheduleRun,
|
||||
deleteScheduleJob: mocks.deleteScheduleJob,
|
||||
deleteScheduleRunById: mocks.deleteScheduleRunById,
|
||||
deleteScheduleRunsByIds: mocks.deleteScheduleRunsByIds,
|
||||
listScheduleRunArtifactsByJob: mocks.listScheduleRunArtifactsByJob,
|
||||
cleanupOrphanedSchedules: mocks.cleanupOrphanedSchedules,
|
||||
getScheduleJobById: mocks.getScheduleJobById,
|
||||
getRunningScheduleRunByJob: mocks.getRunningScheduleRunByJob,
|
||||
getScheduleRunById: mocks.getScheduleRunById,
|
||||
listEnabledScheduleJobs: mocks.listEnabledScheduleJobs,
|
||||
listRunningScheduleRuns: mocks.listRunningScheduleRuns,
|
||||
listScheduleJobIdsByRepo: mocks.listScheduleJobIdsByRepo,
|
||||
listScheduleJobsByRepo: mocks.listScheduleJobsByRepo,
|
||||
listScheduleRunsByJob: mocks.listScheduleRunsByJob,
|
||||
updateScheduleJob: mocks.updateScheduleJob,
|
||||
updateScheduleJobRunState: mocks.updateScheduleJobRunState,
|
||||
updateScheduleRun: mocks.updateScheduleRun,
|
||||
updateScheduleRunMetadata: mocks.updateScheduleRunMetadata,
|
||||
updateScheduleRunWorktree: mocks.updateScheduleRunWorktree,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/schedule-config', () => ({
|
||||
buildCreateSchedulePersistenceInput: mocks.buildCreateSchedulePersistenceInput,
|
||||
buildUpdatedSchedulePersistenceInput: mocks.buildUpdatedSchedulePersistenceInput,
|
||||
computeNextRunAtForJob: mocks.computeNextRunAtForJob,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-models', () => ({
|
||||
resolveOpenCodeModel: mocks.resolveOpenCodeModel,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/sse-aggregator', () => ({
|
||||
sseAggregator: {
|
||||
onEvent: mocks.onEvent,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
error: mocks.loggerError,
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockCronStop = vi.fn()
|
||||
|
||||
vi.mock('croner', () => ({
|
||||
Cron: vi.fn().mockImplementation(() => ({ stop: mockCronStop })),
|
||||
}))
|
||||
|
||||
import { ScheduleService } from '../../src/services/schedules'
|
||||
import type { ForwardRequest, OpenCodeClient } from '../../src/services/opencode/client'
|
||||
|
||||
function jsonResponse(body: unknown, status: number = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
function textResponse(body: string, status: number = 200): Response {
|
||||
return new Response(body, { status })
|
||||
}
|
||||
|
||||
function createOpenCodeClientStub(): OpenCodeClient {
|
||||
return {
|
||||
forward: mocks.forward,
|
||||
forwardRaw: vi.fn(async () => new Response('', { status: 200 })),
|
||||
getJson: vi.fn(async () => ({}) as unknown),
|
||||
postJson: vi.fn(async () => ({}) as unknown),
|
||||
setProviderAuth: vi.fn(async () => true),
|
||||
deleteProviderAuth: vi.fn(async () => true),
|
||||
startMcpAuth: vi.fn(async () => new Response('', { status: 200 })),
|
||||
authenticateMcp: vi.fn(async () => new Response('', { status: 200 })),
|
||||
} as OpenCodeClient
|
||||
}
|
||||
|
||||
function routeForward(handler: (req: ForwardRequest) => Promise<Response> | Response) {
|
||||
mocks.forward.mockImplementation((req: ForwardRequest) => Promise.resolve(handler(req)))
|
||||
}
|
||||
|
||||
const repo = {
|
||||
id: 42,
|
||||
fullPath: '/workspace/repos/sample-project',
|
||||
localPath: 'sample-project',
|
||||
repoUrl: 'https://github.com/example/sample-project',
|
||||
}
|
||||
|
||||
const baseJob: ScheduleJob = {
|
||||
id: 7,
|
||||
repoId: 42,
|
||||
name: 'Weekly engineering summary',
|
||||
description: 'Summarize repo health and recent changes.',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Review the repository and summarize the current state.',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: 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),
|
||||
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
}
|
||||
|
||||
const baseRun: ScheduleRun = {
|
||||
id: 5,
|
||||
jobId: 7,
|
||||
repoId: 42,
|
||||
triggerSource: 'manual',
|
||||
status: 'running',
|
||||
startedAt: Date.UTC(2026, 2, 9, 12, 5, 0),
|
||||
finishedAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 9, 12, 5, 0),
|
||||
sessionId: null,
|
||||
sessionTitle: null,
|
||||
logText: null,
|
||||
responseText: null,
|
||||
errorText: null,
|
||||
runBranch: null,
|
||||
commitHash: null,
|
||||
worktreePath: null,
|
||||
workspaceId: null,
|
||||
}
|
||||
|
||||
describe('ScheduleService permission ruleset in session creation', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
Reflect.get(ScheduleService, 'activeRuns').clear()
|
||||
Reflect.get(ScheduleService, 'activeTeardowns')?.clear()
|
||||
|
||||
mocks.getRepoById.mockReturnValue(repo)
|
||||
mocks.getRunningScheduleRunByJob.mockReturnValue(null)
|
||||
mocks.createScheduleRun.mockReturnValue(baseRun)
|
||||
mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', modelID: 'gpt-5-mini' })
|
||||
mocks.onEvent.mockReturnValue(vi.fn())
|
||||
mocks.getScheduleRunById.mockReturnValue({
|
||||
...baseRun,
|
||||
sessionId: 'ses-perm-test',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started.',
|
||||
})
|
||||
})
|
||||
|
||||
it('sends default permission ruleset when job.permissionConfig is null', async () => {
|
||||
mocks.getScheduleJobById.mockReturnValue(baseJob)
|
||||
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-perm-1',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started.',
|
||||
}
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return jsonResponse({ id: 'ses-perm-1' })
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'POST') {
|
||||
return textResponse('')
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'GET') {
|
||||
return jsonResponse([{ info: { role: 'assistant', time: { completed: Date.now() } }, parts: [] }])
|
||||
}
|
||||
throw new Error(`Unexpected forward request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub(), mocks.stubWorktreeManager as never)
|
||||
await service.runJob(42, 7, 'manual')
|
||||
|
||||
const sessionCall = mocks.forward.mock.calls.find(
|
||||
([req]) => (req as ForwardRequest).path === '/session' && (req as ForwardRequest).method === 'POST',
|
||||
)
|
||||
expect(sessionCall).toBeDefined()
|
||||
const body = JSON.parse((sessionCall![0] as ForwardRequest).body!)
|
||||
expect(body.title).toBe('Scheduled: Weekly engineering summary')
|
||||
expect(body.agent).toBeUndefined()
|
||||
|
||||
const expectedRules = buildSchedulePermissionRuleset(null)
|
||||
expect(body.permission).toEqual(expectedRules)
|
||||
})
|
||||
|
||||
it('sends custom permission ruleset when job has custom permissionConfig', async () => {
|
||||
const customConfig = { allowExternalDirectory: true, bashDenyPatterns: [] }
|
||||
mocks.getScheduleJobById.mockReturnValue({ ...baseJob, permissionConfig: customConfig })
|
||||
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-perm-2',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started.',
|
||||
}
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return jsonResponse({ id: 'ses-perm-2' })
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'POST') {
|
||||
return textResponse('')
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'GET') {
|
||||
return jsonResponse([{ info: { role: 'assistant', time: { completed: Date.now() } }, parts: [] }])
|
||||
}
|
||||
throw new Error(`Unexpected forward request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub(), mocks.stubWorktreeManager as never)
|
||||
await service.runJob(42, 7, 'manual')
|
||||
|
||||
const sessionCall = mocks.forward.mock.calls.find(
|
||||
([req]) => (req as ForwardRequest).path === '/session' && (req as ForwardRequest).method === 'POST',
|
||||
)
|
||||
expect(sessionCall).toBeDefined()
|
||||
const body = JSON.parse((sessionCall![0] as ForwardRequest).body!)
|
||||
expect(body.title).toBe('Scheduled: Weekly engineering summary')
|
||||
expect(body.agent).toBeUndefined()
|
||||
|
||||
const expectedRules = buildSchedulePermissionRuleset(customConfig)
|
||||
expect(body.permission).toEqual(expectedRules)
|
||||
})
|
||||
|
||||
it('preserves existing fields (title, agent) when permission is added', async () => {
|
||||
mocks.getScheduleJobById.mockReturnValue({ ...baseJob, agentSlug: 'my-agent' })
|
||||
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-perm-3',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started.',
|
||||
}
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return jsonResponse({ id: 'ses-perm-3' })
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'POST') {
|
||||
return textResponse('')
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'GET') {
|
||||
return jsonResponse([{ info: { role: 'assistant', time: { completed: Date.now() } }, parts: [] }])
|
||||
}
|
||||
throw new Error(`Unexpected forward request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub(), mocks.stubWorktreeManager as never)
|
||||
await service.runJob(42, 7, 'manual')
|
||||
|
||||
const sessionCall = mocks.forward.mock.calls.find(
|
||||
([req]) => (req as ForwardRequest).path === '/session' && (req as ForwardRequest).method === 'POST',
|
||||
)
|
||||
expect(sessionCall).toBeDefined()
|
||||
const body = JSON.parse((sessionCall![0] as ForwardRequest).body!)
|
||||
expect(body.title).toBe('Scheduled: Weekly engineering summary')
|
||||
expect(body.agent).toBe('my-agent')
|
||||
expect(body.permission).toBeDefined()
|
||||
expect(body.permission['*']).toBe('allow')
|
||||
})
|
||||
})
|
||||
@@ -154,6 +154,7 @@ const job: ScheduleJob = {
|
||||
prompt: 'Review the repository and summarize the current state.',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
@@ -178,6 +179,7 @@ const baseRun: ScheduleRun = {
|
||||
runBranch: null,
|
||||
commitHash: null,
|
||||
worktreePath: null,
|
||||
workspaceId: null,
|
||||
}
|
||||
|
||||
describe('ScheduleService', () => {
|
||||
@@ -1412,6 +1414,7 @@ describe('ScheduleRunner', () => {
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
@@ -1447,6 +1450,7 @@ describe('ScheduleRunner', () => {
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
@@ -1480,6 +1484,7 @@ describe('ScheduleRunner', () => {
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
@@ -1512,6 +1517,7 @@ describe('ScheduleRunner', () => {
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
@@ -1544,6 +1550,7 @@ describe('ScheduleRunner', () => {
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
@@ -1581,17 +1588,17 @@ describe('ScheduleService run history cleanup', () => {
|
||||
|
||||
it('clearRunHistory prunes finished runs and skips a running run', async () => {
|
||||
mocks.listScheduleRunArtifactsByJob.mockReturnValue([
|
||||
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null },
|
||||
{ id: 2, status: 'running', runBranch: 'schedule/7/run-2', worktreePath: '/wt/2' },
|
||||
{ id: 1, status: 'failed', runBranch: null, worktreePath: null },
|
||||
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null, workspaceId: null },
|
||||
{ id: 2, status: 'running', runBranch: 'schedule/7/run-2', worktreePath: '/wt/2', workspaceId: null },
|
||||
{ id: 1, status: 'failed', runBranch: null, worktreePath: null, workspaceId: null },
|
||||
])
|
||||
mocks.deleteScheduleRunsByIds.mockReturnValue(2)
|
||||
|
||||
const result = await makeService().clearRunHistory(42, 7)
|
||||
|
||||
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, [
|
||||
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null },
|
||||
{ id: 1, status: 'failed', runBranch: null, worktreePath: null },
|
||||
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null, workspaceId: null },
|
||||
{ id: 1, status: 'failed', runBranch: null, worktreePath: null, workspaceId: null },
|
||||
])
|
||||
expect(mocks.deleteScheduleRunsByIds).toHaveBeenCalledWith({}, 42, 7, [3, 1])
|
||||
expect(result).toEqual({ cleared: 2 })
|
||||
@@ -1616,7 +1623,7 @@ describe('ScheduleService run history cleanup', () => {
|
||||
await makeService().deleteRun(42, 7, 5)
|
||||
|
||||
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, [
|
||||
{ runBranch: 'schedule/7/run-5', worktreePath: '/wt/5' },
|
||||
{ runBranch: 'schedule/7/run-5', worktreePath: '/wt/5', workspaceId: null },
|
||||
])
|
||||
expect(mocks.deleteScheduleRunById).toHaveBeenCalledWith({}, 42, 7, 5)
|
||||
})
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Combobox, type ComboboxOption } from '@/components/ui/combobox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { TabsContent } from '@/components/ui/tabs'
|
||||
import { Info } from 'lucide-react'
|
||||
|
||||
@@ -27,6 +28,10 @@ type GeneralTabProps = {
|
||||
repoId?: number
|
||||
onRepoChange?: (repoId: number | undefined) => void
|
||||
repoOptions: ComboboxOption[]
|
||||
allowExternalDirectory: boolean
|
||||
onAllowExternalDirectoryChange: (value: boolean) => void
|
||||
bashDenyPatterns: string[]
|
||||
onBashDenyPatternsChange: (value: string[]) => void
|
||||
}
|
||||
|
||||
function InfoHint({ text }: { text: string }) {
|
||||
@@ -63,6 +68,10 @@ export function GeneralTab({
|
||||
repoId,
|
||||
onRepoChange,
|
||||
repoOptions,
|
||||
allowExternalDirectory,
|
||||
onAllowExternalDirectoryChange,
|
||||
bashDenyPatterns,
|
||||
onBashDenyPatternsChange,
|
||||
}: GeneralTabProps) {
|
||||
return (
|
||||
<TabsContent value="basics" className="mt-0 min-h-0 flex-1 overflow-y-auto pt-4 pb-5">
|
||||
@@ -157,6 +166,37 @@ export function GeneralTab({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-medium text-muted-foreground">Permissions</h3>
|
||||
<div className="rounded-lg border border-border bg-card p-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium">Allow access outside the working directory</p>
|
||||
<InfoHint text="When disabled, runs are confined to the worktree. Enable to allow the agent to read/write files elsewhere on the system." />
|
||||
</div>
|
||||
<Switch checked={allowExternalDirectory} onCheckedChange={onAllowExternalDirectoryChange} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg border border-border bg-card p-4">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="schedule-bash-deny">Blocked bash commands</Label>
|
||||
<InfoHint text="One glob per line. These bash commands are always blocked. The throwaway worktree (never auto-pushed) is the real safety boundary." />
|
||||
</div>
|
||||
<Textarea
|
||||
id="schedule-bash-deny"
|
||||
value={bashDenyPatterns.join('\n')}
|
||||
onChange={(event) => {
|
||||
const patterns = event.target.value.split('\n')
|
||||
onBashDenyPatternsChange(patterns)
|
||||
}}
|
||||
placeholder="rm -rf *"
|
||||
className="font-mono text-xs min-h-[100px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
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 { ScheduleJobDialog } from './ScheduleJobDialog'
|
||||
import { DEFAULT_DESTRUCTIVE_BASH_PATTERNS } from '@opencode-manager/shared/schemas'
|
||||
import type { ScheduleJob } from '@opencode-manager/shared/types'
|
||||
|
||||
// jsdom does not implement scrollIntoView
|
||||
Element.prototype.scrollIntoView = vi.fn()
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
templates: [] as Array<{ id: number; title: string; description: string; category: string; cadenceHint: string; suggestedName: string; suggestedDescription: string; prompt: string }>,
|
||||
useDeletePromptTemplateMutate: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/usePromptTemplates', () => ({
|
||||
usePromptTemplates: () => ({ data: mocks.templates, isLoading: false }),
|
||||
useCreatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useUpdatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useDeletePromptTemplate: () => ({ mutate: mocks.useDeletePromptTemplateMutate, isPending: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/providers', () => ({
|
||||
getProvidersWithModels: () => Promise.resolve([]),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
createOpenCodeClient: () => ({
|
||||
listAgents: () => Promise.resolve([]),
|
||||
getConfig: () => Promise.resolve(null),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
listManagedSkills: () => Promise.resolve([]),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
listRepos: () => Promise.resolve([]),
|
||||
listBranches: () => Promise.resolve({ branches: [], status: { ahead: 0, behind: 0 } }),
|
||||
}))
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function getDefaultJob(overrides?: Partial<ScheduleJob>): ScheduleJob {
|
||||
return {
|
||||
id: 1,
|
||||
repoId: 1,
|
||||
name: 'Test Job',
|
||||
description: null,
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Test prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
nextRunAt: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
async function navigateToGeneralTab(user: ReturnType<typeof userEvent.setup>) {
|
||||
const generalTab = screen.getByRole('tab', { name: 'General' })
|
||||
await user.click(generalTab)
|
||||
}
|
||||
|
||||
async function fillRequiredFields(user: ReturnType<typeof userEvent.setup>) {
|
||||
const nameInput = screen.getByLabelText('Name')
|
||||
await user.type(nameInput, 'Test Job')
|
||||
const promptTab = screen.getByRole('tab', { name: 'Prompt' })
|
||||
await user.click(promptTab)
|
||||
const promptInput = screen.getByRole('textbox', { name: 'Prompt' })
|
||||
await user.type(promptInput, 'Run a test')
|
||||
}
|
||||
|
||||
/** The external-directory switch is the 2nd switch (index 1) after Enabled */
|
||||
function getExternalDirSwitch() {
|
||||
return screen.getAllByRole('switch')[1]
|
||||
}
|
||||
|
||||
describe('ScheduleJobDialog — permission config', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('shows default deny patterns and external-directory toggle off for a new job', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await navigateToGeneralTab(user)
|
||||
|
||||
const textarea = await screen.findByLabelText('Blocked bash commands')
|
||||
const defaultText = DEFAULT_DESTRUCTIVE_BASH_PATTERNS.join('\n')
|
||||
expect(textarea).toHaveValue(defaultText)
|
||||
|
||||
const switchInput = getExternalDirSwitch()
|
||||
expect(switchInput).not.toBeChecked()
|
||||
})
|
||||
|
||||
it('initializes permission config from an existing job', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
const customPatterns = ['rm -rf *', 'sudo *']
|
||||
const job = getDefaultJob({
|
||||
permissionConfig: {
|
||||
allowExternalDirectory: true,
|
||||
bashDenyPatterns: [...customPatterns],
|
||||
},
|
||||
})
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
job={job}
|
||||
onSubmit={onSubmit}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await navigateToGeneralTab(user)
|
||||
|
||||
const textarea = await screen.findByLabelText('Blocked bash commands')
|
||||
expect(textarea).toHaveValue(customPatterns.join('\n'))
|
||||
|
||||
const switchInput = getExternalDirSwitch()
|
||||
expect(switchInput).toBeChecked()
|
||||
})
|
||||
|
||||
it('submits permissionConfig in the create payload', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await navigateToGeneralTab(user)
|
||||
await fillRequiredFields(user)
|
||||
|
||||
// Navigate back to General tab
|
||||
await navigateToGeneralTab(user)
|
||||
|
||||
// Enable external directory access
|
||||
const switchInput = getExternalDirSwitch()
|
||||
await user.click(switchInput)
|
||||
|
||||
// Submit
|
||||
const submitButton = screen.getByRole('button', { name: /Create schedule/i })
|
||||
await user.click(submitButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
const payload = onSubmit.mock.calls[0][0]
|
||||
expect(payload.permissionConfig).toEqual({
|
||||
allowExternalDirectory: true,
|
||||
bashDenyPatterns: [...DEFAULT_DESTRUCTIVE_BASH_PATTERNS],
|
||||
})
|
||||
})
|
||||
|
||||
it('strips empty lines from bash deny patterns before submitting', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await navigateToGeneralTab(user)
|
||||
await fillRequiredFields(user)
|
||||
|
||||
// Navigate back to General tab
|
||||
await navigateToGeneralTab(user)
|
||||
|
||||
// Clear and set patterns with empty lines via paste to preserve newlines
|
||||
const textarea = await screen.findByLabelText('Blocked bash commands')
|
||||
await user.clear(textarea)
|
||||
await user.type(textarea, 'rm -rf *{Enter}{Enter}{Enter}sudo *{Enter}{Enter}')
|
||||
|
||||
// Submit
|
||||
const submitButton = screen.getByRole('button', { name: /Create schedule/i })
|
||||
await user.click(submitButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
const payload = onSubmit.mock.calls[0][0]
|
||||
expect(payload.permissionConfig).toEqual({
|
||||
allowExternalDirectory: false,
|
||||
bashDenyPatterns: ['rm -rf *', 'sudo *'],
|
||||
})
|
||||
})
|
||||
|
||||
it('submits updated permissionConfig when editing an existing job', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
const job = getDefaultJob({
|
||||
permissionConfig: {
|
||||
allowExternalDirectory: false,
|
||||
bashDenyPatterns: ['rm -rf *', 'git push --force*'],
|
||||
},
|
||||
})
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
job={job}
|
||||
onSubmit={onSubmit}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await navigateToGeneralTab(user)
|
||||
|
||||
// Toggle external directory on
|
||||
const switchInput = getExternalDirSwitch()
|
||||
await user.click(switchInput)
|
||||
|
||||
// Add a pattern via Enter key
|
||||
const textarea = await screen.findByLabelText('Blocked bash commands')
|
||||
const existingValue = textarea as HTMLTextAreaElement
|
||||
await user.type(existingValue, '{Enter}sudo *')
|
||||
|
||||
// Submit
|
||||
const submitButton = screen.getByRole('button', { name: /Save changes/i })
|
||||
await user.click(submitButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
const payload = onSubmit.mock.calls[0][0]
|
||||
expect(payload.permissionConfig).toEqual({
|
||||
allowExternalDirectory: true,
|
||||
bashDenyPatterns: ['rm -rf *', 'git push --force*', 'sudo *'],
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
} from '@/components/schedules/schedule-utils'
|
||||
import { getRepoDisplayName } from '@/lib/utils'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME } from '@opencode-manager/shared/utils'
|
||||
import { DEFAULT_DESTRUCTIVE_BASH_PATTERNS } from '@opencode-manager/shared/schemas'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { usePromptTemplates, useDeletePromptTemplate } from '@/hooks/usePromptTemplates'
|
||||
import { PromptTemplateDialog } from './PromptTemplateDialog'
|
||||
@@ -61,6 +62,8 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
const initialSkillSlugsRef = useRef<string[] | undefined>(undefined)
|
||||
const initialSkillNotesRef = useRef<string | undefined>(undefined)
|
||||
const [branch, setBranch] = useState('')
|
||||
const [allowExternalDirectory, setAllowExternalDirectory] = useState(false)
|
||||
const [bashDenyPatterns, setBashDenyPatterns] = useState<string[]>([...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
|
||||
const [templateDialogOpen, setTemplateDialogOpen] = useState(false)
|
||||
const [editingTemplate, setEditingTemplate] = useState<PromptTemplate | undefined>(undefined)
|
||||
const [deletingTemplateId, setDeletingTemplateId] = useState<number | null>(null)
|
||||
@@ -218,6 +221,8 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
initialSkillSlugsRef.current = initialSkillSlugs
|
||||
initialSkillNotesRef.current = initialSkillNotes
|
||||
setBranch(job?.branch ?? '')
|
||||
setAllowExternalDirectory(job?.permissionConfig?.allowExternalDirectory ?? false)
|
||||
setBashDenyPatterns(job?.permissionConfig?.bashDenyPatterns ?? [...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
|
||||
}, [job, open, templates])
|
||||
|
||||
const applyPromptTemplate = (template: PromptTemplate) => {
|
||||
@@ -250,6 +255,10 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
model: model.trim() || undefined,
|
||||
prompt: prompt.trim(),
|
||||
branch: branch.trim() || null,
|
||||
permissionConfig: {
|
||||
allowExternalDirectory,
|
||||
bashDenyPatterns: bashDenyPatterns.map((p) => p.trim()).filter(Boolean),
|
||||
},
|
||||
...(shouldIncludeSkillMetadata ? {
|
||||
skillMetadata: skillSlugs.length > 0 || skillNotes.trim()
|
||||
? {
|
||||
@@ -328,6 +337,10 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
repoId={selectedRepoId}
|
||||
onRepoChange={onRepoChange}
|
||||
repoOptions={repoOptions}
|
||||
allowExternalDirectory={allowExternalDirectory}
|
||||
onAllowExternalDirectoryChange={setAllowExternalDirectory}
|
||||
bashDenyPatterns={bashDenyPatterns}
|
||||
onBashDenyPatternsChange={setBashDenyPatterns}
|
||||
/>
|
||||
|
||||
<TimingTab
|
||||
|
||||
@@ -15,6 +15,62 @@ export const ScheduleSkillMetadataSchema = z.object({
|
||||
})
|
||||
export type ScheduleSkillMetadata = z.infer<typeof ScheduleSkillMetadataSchema>
|
||||
|
||||
/**
|
||||
* Bash commands whose blast radius escapes the throwaway worktree: host-level
|
||||
* commands that damage the machine regardless of cwd, plus force-pushes that can
|
||||
* overwrite remote branches. File-mutating commands (`rm -rf`, `git reset --hard`,
|
||||
* etc.) are intentionally omitted — they only affect the disposable worktree, which
|
||||
* is never auto-pushed and is the real safety boundary.
|
||||
*/
|
||||
export const DEFAULT_DESTRUCTIVE_BASH_PATTERNS = [
|
||||
'git push --force*', 'git push -f *',
|
||||
'sudo *', 'dd *', 'mkfs*',
|
||||
'shutdown*', 'reboot*', 'halt*',
|
||||
'kill -9 *', 'killall *',
|
||||
] as const
|
||||
|
||||
export const SchedulePermissionConfigSchema = z.object({
|
||||
allowExternalDirectory: z.boolean().default(false),
|
||||
bashDenyPatterns: z.array(z.string().min(1).max(200)).max(200)
|
||||
.default([...DEFAULT_DESTRUCTIVE_BASH_PATTERNS]),
|
||||
})
|
||||
export type SchedulePermissionConfig = z.infer<typeof SchedulePermissionConfigSchema>
|
||||
|
||||
export type SchedulePermissionAction = 'allow' | 'deny' | 'ask'
|
||||
|
||||
export interface SchedulePermissionRuleset {
|
||||
'*': SchedulePermissionAction
|
||||
external_directory?: SchedulePermissionAction
|
||||
bash?: Record<string, SchedulePermissionAction>
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an OpenCode permission config object for an unattended scheduled run.
|
||||
*
|
||||
* OpenCode's config/API permission format is keyed by tool, where each value is
|
||||
* either a shorthand action or a glob-pattern -> action map (see
|
||||
* https://opencode.ai/docs/permissions). A top-level `*` sets the baseline; the
|
||||
* server merges tool entries after it and the last matching rule wins, so the
|
||||
* `bash` deny patterns override the allow-all baseline for matching commands.
|
||||
*/
|
||||
export function buildSchedulePermissionRuleset(
|
||||
config: SchedulePermissionConfig | null | undefined,
|
||||
): SchedulePermissionRuleset {
|
||||
const cfg = SchedulePermissionConfigSchema.parse(config ?? {})
|
||||
const ruleset: SchedulePermissionRuleset = { '*': 'allow' }
|
||||
if (!cfg.allowExternalDirectory) {
|
||||
ruleset.external_directory = 'deny'
|
||||
}
|
||||
if (cfg.bashDenyPatterns.length > 0) {
|
||||
const bash: Record<string, SchedulePermissionAction> = {}
|
||||
for (const pattern of cfg.bashDenyPatterns) {
|
||||
bash[pattern] = 'deny'
|
||||
}
|
||||
ruleset.bash = bash
|
||||
}
|
||||
return ruleset
|
||||
}
|
||||
|
||||
export const ScheduleJobSchema = z.object({
|
||||
id: z.number(),
|
||||
repoId: z.number(),
|
||||
@@ -29,6 +85,7 @@ export const ScheduleJobSchema = z.object({
|
||||
prompt: z.string(),
|
||||
model: z.string().nullable(),
|
||||
skillMetadata: ScheduleSkillMetadataSchema.nullable(),
|
||||
permissionConfig: SchedulePermissionConfigSchema.nullable(),
|
||||
branch: z.string().nullable(),
|
||||
createdAt: z.number(),
|
||||
updatedAt: z.number(),
|
||||
@@ -54,6 +111,7 @@ export const ScheduleRunSchema = z.object({
|
||||
runBranch: z.string().nullable(),
|
||||
commitHash: z.string().nullable(),
|
||||
worktreePath: z.string().nullable(),
|
||||
workspaceId: z.string().nullable(),
|
||||
})
|
||||
export type ScheduleRun = z.infer<typeof ScheduleRunSchema>
|
||||
|
||||
@@ -65,6 +123,7 @@ const ScheduleJobBaseRequestSchema = z.object({
|
||||
prompt: z.string().min(1).max(20000),
|
||||
model: z.string().min(1).max(200).optional(),
|
||||
skillMetadata: ScheduleSkillMetadataSchema.nullable().optional(),
|
||||
permissionConfig: SchedulePermissionConfigSchema.nullable().optional(),
|
||||
branch: z.string().min(1).max(200).nullable().optional(),
|
||||
})
|
||||
|
||||
@@ -93,6 +152,7 @@ export const UpdateScheduleJobRequestSchema = z.object({
|
||||
prompt: z.string().min(1).max(20000).optional(),
|
||||
model: z.string().min(1).max(200).nullable().optional(),
|
||||
skillMetadata: ScheduleSkillMetadataSchema.nullable().optional(),
|
||||
permissionConfig: SchedulePermissionConfigSchema.nullable().optional(),
|
||||
branch: z.string().min(1).max(200).nullable().optional(),
|
||||
})
|
||||
export type UpdateScheduleJobRequest = z.infer<typeof UpdateScheduleJobRequestSchema>
|
||||
|
||||
@@ -111,6 +111,7 @@ export type {
|
||||
|
||||
export type {
|
||||
ScheduleMode,
|
||||
SchedulePermissionConfig,
|
||||
ScheduleRunTriggerSource,
|
||||
ScheduleRunStatus,
|
||||
ScheduleSkillMetadata,
|
||||
|
||||
Reference in new issue
Block a user