mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Merge branch 'main' into feat/docker-self-upgrade
Resolve conflicts against the restart-coordinator rewrite and renumber the manager-upgrade-jobs migration from 16 to 19 to avoid colliding with main's 016-018 migrations. Includes review fixes: background the docker pull, add a staleness guard for stuck recreating jobs, move manager-upgrade types to @opencode-manager/shared, wire the active-session pre-check dialog into the Upgrade Manager button, and surface upgrade errors via FetchError-aware messaging.
This commit is contained in:
commit
9effe53bdc
125 files changed
+3899
-975
No files matched your search
@@ -9,7 +9,7 @@
|
||||
"build": "bun build src/index.ts --outdir=dist --target=bun",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "pnpm run test:bun && pnpm run test:vitest",
|
||||
"test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts test/routes/internal-assistant.test.ts src/db/model-state.test.ts src/routes/providers.test.ts src/routes/repos.test.ts",
|
||||
"test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts test/routes/internal-assistant.test.ts src/db/model-state.test.ts src/routes/providers.test.ts src/routes/repos.test.ts src/routes/session-pins.test.ts",
|
||||
"test:vitest": "vitest run",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:watch": "vitest --watch",
|
||||
|
||||
@@ -1,17 +1,7 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { ManagerUpgradeJob, ManagerUpgradeJobStatus } from '@opencode-manager/shared/types'
|
||||
|
||||
export type ManagerUpgradeStatus = 'pending' | 'pulling' | 'recreating' | 'completed' | 'failed'
|
||||
|
||||
export interface ManagerUpgradeJob {
|
||||
id: number
|
||||
status: ManagerUpgradeStatus
|
||||
fromVersion: string | null
|
||||
toVersion: string | null
|
||||
targetImage: string | null
|
||||
error: string | null
|
||||
startedAt: number
|
||||
finishedAt: number | null
|
||||
}
|
||||
export type { ManagerUpgradeJob, ManagerUpgradeJobStatus }
|
||||
|
||||
interface ManagerUpgradeJobRow {
|
||||
id: number
|
||||
@@ -27,7 +17,7 @@ interface ManagerUpgradeJobRow {
|
||||
function rowToJob(row: ManagerUpgradeJobRow): ManagerUpgradeJob {
|
||||
return {
|
||||
id: row.id,
|
||||
status: row.status as ManagerUpgradeStatus,
|
||||
status: row.status as ManagerUpgradeJobStatus,
|
||||
fromVersion: row.from_version,
|
||||
toVersion: row.to_version,
|
||||
targetImage: row.target_image,
|
||||
@@ -40,7 +30,7 @@ function rowToJob(row: ManagerUpgradeJobRow): ManagerUpgradeJob {
|
||||
export function insertUpgradeJob(
|
||||
db: Database,
|
||||
data: {
|
||||
status: ManagerUpgradeStatus
|
||||
status: ManagerUpgradeJobStatus
|
||||
fromVersion?: string
|
||||
toVersion?: string
|
||||
targetImage?: string
|
||||
@@ -74,7 +64,7 @@ export function updateUpgradeJob(
|
||||
db: Database,
|
||||
id: number,
|
||||
patch: Partial<{
|
||||
status: ManagerUpgradeStatus
|
||||
status: ManagerUpgradeJobStatus
|
||||
error: string | null
|
||||
finishedAt: number | null
|
||||
}>,
|
||||
|
||||
@@ -24,9 +24,28 @@ function ensureMigrationsTable(db: Database): void {
|
||||
`)
|
||||
}
|
||||
|
||||
function getAppliedVersions(db: Database): Set<number> {
|
||||
const rows = db.prepare('SELECT version FROM schema_migrations ORDER BY version').all() as MigrationRecord[]
|
||||
return new Set(rows.map(r => r.version))
|
||||
function getAppliedMigrations(db: Database): Map<number, string> {
|
||||
const rows = db.prepare('SELECT version, name FROM schema_migrations ORDER BY version').all() as MigrationRecord[]
|
||||
return new Map(rows.map(r => [r.version, r.name]))
|
||||
}
|
||||
|
||||
/**
|
||||
* Surfaces version-number collisions where a recorded migration's name differs
|
||||
* from the code migration registered under the same version. The runner keys on
|
||||
* version number alone, so a reused version silently skips the real migration
|
||||
* (e.g. an ADD COLUMN), producing later runtime errors that are hard to trace.
|
||||
* This converts that silent skip into a loud, actionable warning.
|
||||
*/
|
||||
function warnOnVersionNameMismatch(applied: Map<number, string>, migrations: Migration[]): void {
|
||||
for (const migration of migrations) {
|
||||
const recordedName = applied.get(migration.version)
|
||||
if (recordedName !== undefined && recordedName !== migration.name) {
|
||||
logger.warn(
|
||||
`Migration version ${migration.version} is recorded as "${recordedName}" but the code defines "${migration.name}". ` +
|
||||
`This migration was skipped; its schema changes may be missing. Verify the database schema and apply the changes manually if needed.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function markApplied(db: Database, migration: Migration): void {
|
||||
@@ -37,7 +56,8 @@ function markApplied(db: Database, migration: Migration): void {
|
||||
export function migrate(db: Database, migrations: Migration[]): void {
|
||||
ensureMigrationsTable(db)
|
||||
|
||||
const applied = getAppliedVersions(db)
|
||||
const applied = getAppliedMigrations(db)
|
||||
warnOnVersionNameMismatch(applied, migrations)
|
||||
const sorted = [...migrations].sort((a, b) => a.version - b.version)
|
||||
const pending = sorted.filter(m => !applied.has(m.version))
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
import { ensureSessionPinsTable } from '../session-pins'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 18,
|
||||
name: 'session-pins',
|
||||
up(db) {
|
||||
ensureSessionPinsTable(db)
|
||||
},
|
||||
down(db) {
|
||||
db.run('DROP TABLE IF EXISTS session_pins')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 16,
|
||||
version: 19,
|
||||
name: 'manager-upgrade-jobs',
|
||||
|
||||
up(db) {
|
||||
@@ -14,7 +14,10 @@ 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-manager-upgrade-jobs'
|
||||
import migration016 from './016-schedule-permission-config'
|
||||
import migration017 from './017-schedule-run-workspace-id'
|
||||
import migration018 from './018-session-pins'
|
||||
import migration019 from './019-manager-upgrade-jobs'
|
||||
|
||||
export const allMigrations: Migration[] = [
|
||||
migration001,
|
||||
@@ -33,4 +36,7 @@ export const allMigrations: Migration[] = [
|
||||
migration014,
|
||||
migration015,
|
||||
migration016,
|
||||
migration017,
|
||||
migration018,
|
||||
migration019,
|
||||
]
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from './migration-runner'
|
||||
import { allMigrations } from './migrations'
|
||||
import { listSessionPins, setSessionPin, ensureSessionPinsTable } from './session-pins'
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
}
|
||||
|
||||
describe('session-pins', () => {
|
||||
let db: Database
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
})
|
||||
|
||||
describe('listSessionPins', () => {
|
||||
it('returns [] on a fresh db', () => {
|
||||
expect(listSessionPins(db)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('setSessionPin', () => {
|
||||
it('pinning returns array with the pin', () => {
|
||||
const pins = setSessionPin(db, 'ses_1', '/w/a', true)
|
||||
expect(pins).toHaveLength(1)
|
||||
expect(pins[0]!.sessionId).toBe('ses_1')
|
||||
expect(pins[0]!.directory).toBe('/w/a')
|
||||
expect(pins[0]!.pinnedAt).toEqual(expect.any(Number))
|
||||
})
|
||||
|
||||
it('pinning the same (sessionId, directory) twice does not create a duplicate', async () => {
|
||||
setSessionPin(db, 'ses_1', '/w/a', true)
|
||||
const first = listSessionPins(db)
|
||||
const firstPinnedAt = first[0]!.pinnedAt
|
||||
|
||||
// Delay to guarantee a different pinnedAt timestamp
|
||||
await new Promise(r => setTimeout(r, 5))
|
||||
const second = setSessionPin(db, 'ses_1', '/w/a', true)
|
||||
expect(second).toHaveLength(1)
|
||||
expect(second[0]!.pinnedAt).toBeGreaterThan(firstPinnedAt)
|
||||
})
|
||||
|
||||
it('same sessionId with different directory produces two distinct pins', () => {
|
||||
setSessionPin(db, 'ses_1', '/w/a', true)
|
||||
const pins = setSessionPin(db, 'ses_1', '/w/b', true)
|
||||
expect(pins).toHaveLength(2)
|
||||
expect(pins.map(p => p.directory).sort()).toEqual(['/w/a', '/w/b'])
|
||||
})
|
||||
|
||||
it('unpinning removes only that pin', () => {
|
||||
setSessionPin(db, 'ses_1', '/w/a', true)
|
||||
setSessionPin(db, 'ses_1', '/w/b', true)
|
||||
|
||||
const afterUnpin = setSessionPin(db, 'ses_1', '/w/a', false)
|
||||
expect(afterUnpin).toHaveLength(1)
|
||||
expect(afterUnpin[0]!.directory).toBe('/w/b')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ensureSessionPinsTable', () => {
|
||||
it('recreates the table if dropped', () => {
|
||||
db.run('DROP TABLE session_pins')
|
||||
|
||||
ensureSessionPinsTable(db)
|
||||
const table = db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_pins'")
|
||||
.get() as { name: string } | undefined
|
||||
|
||||
expect(table).toBeTruthy()
|
||||
expect(table!.name).toBe('session_pins')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
|
||||
export interface SessionPinRecord {
|
||||
sessionId: string
|
||||
directory: string
|
||||
pinnedAt: number
|
||||
}
|
||||
|
||||
export function ensureSessionPinsTable(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS session_pins (
|
||||
session_id TEXT NOT NULL,
|
||||
directory TEXT NOT NULL,
|
||||
pinned_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (session_id, directory)
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
export function listSessionPins(db: Database): SessionPinRecord[] {
|
||||
const rows = db
|
||||
.prepare('SELECT session_id, directory, pinned_at FROM session_pins ORDER BY pinned_at DESC')
|
||||
.all() as { session_id: string; directory: string; pinned_at: number }[]
|
||||
return rows.map(r => ({ sessionId: r.session_id, directory: r.directory, pinnedAt: r.pinned_at }))
|
||||
}
|
||||
|
||||
export function setSessionPin(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
directory: string,
|
||||
pinned: boolean,
|
||||
): SessionPinRecord[] {
|
||||
const run = db.transaction(() => {
|
||||
if (pinned) {
|
||||
db.prepare(`
|
||||
INSERT INTO session_pins(session_id, directory, pinned_at)
|
||||
VALUES(?,?,?)
|
||||
ON CONFLICT(session_id, directory) DO UPDATE SET pinned_at=excluded.pinned_at
|
||||
`).run(sessionId, directory, Date.now())
|
||||
} else {
|
||||
db.prepare('DELETE FROM session_pins WHERE session_id = ? AND directory = ?').run(sessionId, directory)
|
||||
}
|
||||
return listSessionPins(db)
|
||||
})
|
||||
return run()
|
||||
}
|
||||
+26
-11
@@ -15,15 +15,20 @@ import { createFileRoutes } from './routes/files'
|
||||
import { createScheduleRoutes } from './routes/schedules'
|
||||
import { createManagerUpgradeRoutes } from './routes/manager-upgrade'
|
||||
|
||||
async function getAppVersion(): Promise<string> {
|
||||
try {
|
||||
const packageUrl = new URL('../../package.json', import.meta.url)
|
||||
const packageJsonRaw = await readFile(packageUrl, 'utf-8')
|
||||
const packageJson = JSON.parse(packageJsonRaw) as { version?: string }
|
||||
return packageJson.version ?? 'unknown'
|
||||
} catch {
|
||||
return 'unknown'
|
||||
}
|
||||
let cachedAppVersion: Promise<string> | null = null
|
||||
|
||||
function getAppVersion(): Promise<string> {
|
||||
cachedAppVersion ??= (async () => {
|
||||
try {
|
||||
const packageUrl = new URL('../../package.json', import.meta.url)
|
||||
const packageJsonRaw = await readFile(packageUrl, 'utf-8')
|
||||
const packageJson = JSON.parse(packageJsonRaw) as { version?: string }
|
||||
return packageJson.version ?? 'unknown'
|
||||
} catch {
|
||||
return 'unknown'
|
||||
}
|
||||
})()
|
||||
return cachedAppVersion
|
||||
}
|
||||
import { createProvidersRoutes } from './routes/providers'
|
||||
import { createOAuthRoutes } from './routes/oauth'
|
||||
@@ -35,6 +40,7 @@ import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './rout
|
||||
import { createAuth } from './auth'
|
||||
import { createAuthMiddleware } from './auth/middleware'
|
||||
import { createPromptTemplateRoutes } from './routes/prompt-templates'
|
||||
import { createSessionPinRoutes } from './routes/session-pins'
|
||||
import { createInternalRoutes } from './routes/internal'
|
||||
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
|
||||
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
|
||||
@@ -53,6 +59,8 @@ import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode
|
||||
import { OpenCodeSupervisor } from './services/opencode-supervisor'
|
||||
import { ManagerUpgradeService, createDockerRunner } from './services/manager-upgrade'
|
||||
import { isRunningInDocker, isDockerSocketAvailable } from './utils/runtime-env'
|
||||
import { OpenCodeRestartCoordinator } from './services/opencode-restart-coordinator'
|
||||
import { setOpenCodeRestartCoordinator } from './services/opencode-restart'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { parse as parseJsonc } from 'jsonc-parser'
|
||||
import { getModelStatePath, ModelStateSchema } from './routes/providers'
|
||||
@@ -294,7 +302,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)
|
||||
|
||||
@@ -323,6 +331,13 @@ sseAggregator.setPendingActionsFetcher(openCodeClient)
|
||||
sseAggregator.setPasswordResolver(() => new SettingsService(db).getOpenCodeServerPassword())
|
||||
sseAggregator.start()
|
||||
|
||||
sseAggregator.setScheduledSessionsResolver(
|
||||
() => scheduleService.getActiveRunSessionIds(),
|
||||
)
|
||||
|
||||
const openCodeRestartCoordinator = new OpenCodeRestartCoordinator(openCodeClient, sseAggregator)
|
||||
setOpenCodeRestartCoordinator(openCodeRestartCoordinator)
|
||||
|
||||
void scheduleRunnerInstance.start()
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
@@ -336,7 +351,6 @@ const managerUpgradeService = new ManagerUpgradeService(db, {
|
||||
enabled: process.env.OCM_MANAGER_UPGRADE_ENABLED !== 'false',
|
||||
}),
|
||||
})
|
||||
managerUpgradeService.reconcile()
|
||||
|
||||
app.route('/api/auth', createAuthRoutes(auth))
|
||||
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
|
||||
@@ -360,6 +374,7 @@ protectedApi.route('/sse', createSSERoutes())
|
||||
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
|
||||
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
|
||||
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
|
||||
protectedApi.route('/session-pins', createSessionPinRoutes(db))
|
||||
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/manager-upgrade', createManagerUpgradeRoutes(managerUpgradeService))
|
||||
|
||||
|
||||
@@ -7,18 +7,9 @@ import {
|
||||
OAuthAuthorizeResponseSchema,
|
||||
OAuthCallbackRequestSchema
|
||||
} from '../../../shared/src/schemas/auth'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { reloadOpenCodeConfig } from '../services/opencode-restart'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
|
||||
async function reloadOpenCodeConfig(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (openCodeSupervisor) {
|
||||
await openCodeSupervisor.reloadConfig('settings_reload')
|
||||
return
|
||||
}
|
||||
|
||||
await opencodeServerManager.reloadConfig()
|
||||
}
|
||||
|
||||
export function createOAuthRoutes(openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
const app = new Hono()
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { AuthService } from '../services/auth'
|
||||
import { SetCredentialRequestSchema } from '../../../shared/src/schemas/auth'
|
||||
import { logger } from '../utils/logger'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { reloadOpenCodeConfig } from '../services/opencode-restart'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
@@ -54,15 +54,6 @@ async function mirrorModelStateToFile(state: OpenCodeModelStateRecord): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadOpenCodeConfig(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (openCodeSupervisor) {
|
||||
await openCodeSupervisor.reloadConfig('settings_reload')
|
||||
return
|
||||
}
|
||||
|
||||
await opencodeServerManager.reloadConfig()
|
||||
}
|
||||
|
||||
export function createProvidersRoutes(db: Database, openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
const app = new Hono()
|
||||
const authService = new AuthService()
|
||||
|
||||
@@ -8,7 +8,7 @@ import * as repoService from '../services/repo'
|
||||
import * as archiveService from '../services/archive'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { writeFileContent } from '../services/file-operations'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { restartOpenCode } from '../services/opencode-restart'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { logger } from '../utils/logger'
|
||||
@@ -22,16 +22,6 @@ import { ScheduleService } from '../services/schedules'
|
||||
import { ensureAssistantMode, getAssistantModeStatus, buildAssistantRepo } from '../services/assistant-mode'
|
||||
import path from 'path'
|
||||
|
||||
async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (openCodeSupervisor) {
|
||||
await openCodeSupervisor.restart('settings_restart')
|
||||
return
|
||||
}
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
}
|
||||
|
||||
function resolveRepo(database: Database, id: number): Repo | null {
|
||||
return getRepoById(database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'bun:test'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../db/migration-runner'
|
||||
import { allMigrations } from '../db/migrations'
|
||||
import { createSessionPinRoutes } from './session-pins'
|
||||
|
||||
function createTestApp(db: Database): Hono {
|
||||
const app = new Hono()
|
||||
app.route('/session-pins', createSessionPinRoutes(db))
|
||||
return app
|
||||
}
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
}
|
||||
|
||||
describe('session pins routes', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
app = createTestApp(db)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('GET / returns empty pins list initially', async () => {
|
||||
const res = await app.request('/session-pins')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as { pins: unknown[] }
|
||||
expect(data.pins).toEqual([])
|
||||
})
|
||||
|
||||
it('PUT / creates a pin and returns updated list', async () => {
|
||||
const res = await app.request('/session-pins', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: true }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as { pins: Array<{ sessionId: string; directory: string }> }
|
||||
expect(data.pins).toHaveLength(1)
|
||||
expect(data.pins[0]).toMatchObject({ sessionId: 'ses_1', directory: '/w/a' })
|
||||
})
|
||||
|
||||
it('GET / returns pins after creation', async () => {
|
||||
await app.request('/session-pins', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: true }),
|
||||
})
|
||||
|
||||
const res = await app.request('/session-pins')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as { pins: unknown[] }
|
||||
expect(data.pins).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('PUT / with pinned: false removes the pin', async () => {
|
||||
await app.request('/session-pins', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: true }),
|
||||
})
|
||||
|
||||
const res = await app.request('/session-pins', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: false }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as { pins: unknown[] }
|
||||
expect(data.pins).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('PUT / with invalid body returns 400', async () => {
|
||||
const res = await app.request('/session-pins', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: '', directory: '/w/a', pinned: true }),
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
const data = await res.json() as { error: string }
|
||||
expect(data.error).toBe('Invalid request')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { z } from 'zod'
|
||||
import { ToggleSessionPinRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { listSessionPins, setSessionPin } from '../db/session-pins'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
export function createSessionPinRoutes(database: Database) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => {
|
||||
try {
|
||||
return c.json({ pins: listSessionPins(database) })
|
||||
} catch (error) {
|
||||
logger.error('Failed to list session pins', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.put('/', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const input = ToggleSessionPinRequestSchema.parse(body)
|
||||
const pins = setSessionPin(database, input.sessionId, input.directory, input.pinned)
|
||||
return c.json({ pins })
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
logger.error('Failed to toggle session pin', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import type { OpenCodeRestartCoordinator, ResumableSession } from '../services/opencode-restart-coordinator'
|
||||
import { setOpenCodeRestartCoordinator } from '../services/opencode-restart'
|
||||
|
||||
interface TestUserPreferenceRow {
|
||||
preferences: string
|
||||
@@ -450,3 +452,67 @@ describe('settings routes — opencode model discovery', () => {
|
||||
expect(data.models).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('settings routes — restart coordinator wiring', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
setOpenCodeRestartCoordinator(null)
|
||||
})
|
||||
|
||||
it('GET /opencode-active-sessions returns count and sessions from coordinator', async () => {
|
||||
const fakeCoordinator = {
|
||||
captureResumableSessions: vi.fn(() => [{
|
||||
sessionID: 's1',
|
||||
directory: '/a',
|
||||
} satisfies ResumableSession]),
|
||||
abortSessions: vi.fn(),
|
||||
resumeSessions: vi.fn(),
|
||||
runWithResume: vi.fn(),
|
||||
} as unknown as OpenCodeRestartCoordinator
|
||||
setOpenCodeRestartCoordinator(fakeCoordinator)
|
||||
|
||||
app = createTestApp(db)
|
||||
const res = await app.request('/settings/opencode-active-sessions')
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { count: number; sessions: ResumableSession[] }
|
||||
expect(body.count).toBe(1)
|
||||
expect(body.sessions).toEqual([{ sessionID: 's1', directory: '/a' }])
|
||||
expect(fakeCoordinator.captureResumableSessions).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('GET /opencode-active-sessions returns empty when no coordinator', async () => {
|
||||
setOpenCodeRestartCoordinator(null)
|
||||
app = createTestApp(db)
|
||||
const res = await app.request('/settings/opencode-active-sessions')
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { count: number; sessions: ResumableSession[] }
|
||||
expect(body.count).toBe(0)
|
||||
expect(body.sessions).toEqual([])
|
||||
})
|
||||
|
||||
it('POST /opencode-restart routes through coordinator.runWithResume and returns resumedSessions', async () => {
|
||||
const runWithResume = vi.fn().mockResolvedValue({ healthy: true, resumedSessionIDs: ['s1'] })
|
||||
const fakeCoordinator = {
|
||||
captureResumableSessions: vi.fn(() => []),
|
||||
abortSessions: vi.fn(),
|
||||
resumeSessions: vi.fn(),
|
||||
runWithResume,
|
||||
} as unknown as OpenCodeRestartCoordinator
|
||||
setOpenCodeRestartCoordinator(fakeCoordinator)
|
||||
|
||||
app = createTestApp(db)
|
||||
const res = await app.request('/settings/opencode-restart', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { success: boolean; resumedSessions: string[] }
|
||||
expect(body.success).toBe(true)
|
||||
expect(body.resumedSessions).toEqual(['s1'])
|
||||
expect(runWithResume).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -31,6 +31,7 @@ import { opencodeServerManager, ConfigReloadError } from '../services/opencode-s
|
||||
import { getOrCreateInternalToken, rotateInternalToken } from '../services/internal-token'
|
||||
import { sseAggregator } from '../services/sse-aggregator'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { restartOpenCode, reloadOpenCodeConfig, getOpenCodeRestartCoordinator } from '../services/opencode-restart'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { DEFAULT_AGENTS_MD } from '../constants'
|
||||
import { validateSSHPrivateKey } from '../utils/ssh-validation'
|
||||
@@ -92,25 +93,6 @@ function getOpenCodeConfigContentToWrite(
|
||||
return JSON.stringify(appliedConfig, null, 2)
|
||||
}
|
||||
|
||||
async function reloadOpenCodeConfig(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (openCodeSupervisor) {
|
||||
await openCodeSupervisor.reloadConfig('settings_reload')
|
||||
return
|
||||
}
|
||||
|
||||
await opencodeServerManager.reloadConfig()
|
||||
}
|
||||
|
||||
async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (openCodeSupervisor) {
|
||||
await openCodeSupervisor.restart('settings_restart')
|
||||
return
|
||||
}
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
}
|
||||
|
||||
async function restartOpenCodeSafe(openCodeSupervisor: OpenCodeSupervisor | undefined, context: string): Promise<void> {
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
@@ -728,8 +710,12 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
try {
|
||||
logger.info('Manual OpenCode server restart requested')
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
return c.json({ success: true, message: 'OpenCode server restarted successfully' })
|
||||
const { resumedSessionIDs } = await restartOpenCode(openCodeSupervisor)
|
||||
return c.json({
|
||||
success: true,
|
||||
message: 'OpenCode server restarted successfully',
|
||||
resumedSessions: resumedSessionIDs,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Failed to restart OpenCode server:', error)
|
||||
const startupError = opencodeServerManager.getLastStartupError()
|
||||
@@ -1879,6 +1865,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/opencode-active-sessions', (c) => {
|
||||
const sessions = getOpenCodeRestartCoordinator()?.captureResumableSessions() ?? []
|
||||
return c.json({ count: sessions.length, sessions })
|
||||
})
|
||||
|
||||
app.get('/opencode-discover-models', async (c) => {
|
||||
try {
|
||||
const baseUrl = c.req.query('baseUrl')
|
||||
|
||||
@@ -10,9 +10,11 @@ import {
|
||||
getActiveUpgradeJob,
|
||||
} from '../db/manager-upgrade'
|
||||
import type { ManagerUpgradeJob } from '../db/manager-upgrade'
|
||||
import type { ManagerUpgradeStatusResponse } from '@opencode-manager/shared/types'
|
||||
|
||||
const RECREATE_STALE_MS = 10 * 60 * 1000
|
||||
|
||||
export interface SelfContainerInfo {
|
||||
containerId: string
|
||||
project: string
|
||||
service: string
|
||||
workingDir: string
|
||||
@@ -95,14 +97,19 @@ export class ManagerUpgradeService {
|
||||
}
|
||||
}
|
||||
|
||||
async getStatus(): Promise<{
|
||||
supported: boolean
|
||||
inDocker: boolean
|
||||
socketAvailable: boolean
|
||||
enabled: boolean
|
||||
currentVersion: string | null
|
||||
job: ManagerUpgradeJob | null
|
||||
}> {
|
||||
private expireStaleRecreatingJob(): void {
|
||||
const active = getActiveUpgradeJob(this.db)
|
||||
if (active?.status === 'recreating' && Date.now() - active.startedAt > RECREATE_STALE_MS) {
|
||||
updateUpgradeJob(this.db, active.id, {
|
||||
status: 'failed',
|
||||
error: 'recreate helper did not complete in time',
|
||||
finishedAt: Date.now(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async getStatus(): Promise<ManagerUpgradeStatusResponse> {
|
||||
this.expireStaleRecreatingJob()
|
||||
const cap = this.deps.capability()
|
||||
const currentVersion = await this.deps.getCurrentVersion()
|
||||
return {
|
||||
@@ -126,6 +133,8 @@ export class ManagerUpgradeService {
|
||||
)
|
||||
}
|
||||
|
||||
this.expireStaleRecreatingJob()
|
||||
|
||||
// Check for an existing active job before any async Docker/version calls.
|
||||
// This prevents a hung inspectSelf() from blocking the 409 response.
|
||||
const activeEarly = getActiveUpgradeJob(this.db)
|
||||
@@ -147,31 +156,33 @@ export class ManagerUpgradeService {
|
||||
}
|
||||
|
||||
const job = insertUpgradeJob(this.db, {
|
||||
status: 'pending',
|
||||
status: 'pulling',
|
||||
fromVersion: currentVersion ?? undefined,
|
||||
toVersion: resolvedTag,
|
||||
targetImage,
|
||||
startedAt: Date.now(),
|
||||
})
|
||||
|
||||
updateUpgradeJob(this.db, job.id, { status: 'pulling' })
|
||||
// The pull can take minutes; run it detached so the HTTP request returns
|
||||
// immediately and progress/failure is surfaced via the polled job status.
|
||||
void this.pullAndRecreate(job.id, info, targetImage)
|
||||
|
||||
return job
|
||||
}
|
||||
|
||||
private async pullAndRecreate(jobId: number, info: SelfContainerInfo, targetImage: string): Promise<void> {
|
||||
try {
|
||||
await this.deps.runner.pull(targetImage)
|
||||
updateUpgradeJob(this.db, jobId, { status: 'recreating' })
|
||||
this.deps.runner.spawnRecreate(info, targetImage)
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
updateUpgradeJob(this.db, job.id, {
|
||||
updateUpgradeJob(this.db, jobId, {
|
||||
status: 'failed',
|
||||
error: message,
|
||||
finishedAt: Date.now(),
|
||||
})
|
||||
throw new ManagerUpgradeError(message, 500)
|
||||
}
|
||||
|
||||
updateUpgradeJob(this.db, job.id, { status: 'recreating' })
|
||||
this.deps.runner.spawnRecreate(info, targetImage)
|
||||
|
||||
return getLatestUpgradeJob(this.db) as ManagerUpgradeJob
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +210,6 @@ export function createDockerRunner(): DockerRunner {
|
||||
const labels: Record<string, string> = JSON.parse(labelsJson)
|
||||
|
||||
return {
|
||||
containerId,
|
||||
project: labels['com.docker.compose.project'] || '',
|
||||
service: labels['com.docker.compose.service'] || '',
|
||||
workingDir: labels['com.docker.compose.project.working_dir'] || '',
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { OpenCodeRestartCoordinator, type ActiveSessionsProvider, type ResumableSession } from './opencode-restart-coordinator'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
function createFakeActiveSessionsProvider(overrides: Partial<ActiveSessionsProvider> = {}): ActiveSessionsProvider {
|
||||
return {
|
||||
getActiveSessions: vi.fn(() => ({})),
|
||||
isSubagentSession: vi.fn(() => false),
|
||||
getScheduledSessionIds: vi.fn(() => new Set<string>()),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('OpenCodeRestartCoordinator', () => {
|
||||
let client: OpenCodeClient
|
||||
let activeSessions: ActiveSessionsProvider
|
||||
let coordinator: OpenCodeRestartCoordinator
|
||||
|
||||
beforeEach(() => {
|
||||
client = createStubOpenCodeClient()
|
||||
activeSessions = createFakeActiveSessionsProvider()
|
||||
coordinator = new OpenCodeRestartCoordinator(client, activeSessions)
|
||||
})
|
||||
|
||||
describe('captureResumableSessions', () => {
|
||||
it('excludes subagent sessions', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1', 'sub1'],
|
||||
'/b': ['s2'],
|
||||
})
|
||||
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id === 'sub1')
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([
|
||||
{ sessionID: 's1', directory: '/a' },
|
||||
{ sessionID: 's2', directory: '/b' },
|
||||
])
|
||||
})
|
||||
|
||||
it('returns empty array when no active sessions', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({})
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('filters out only subagent sessions, keeps all others', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/x': ['a1', 'a2', 'sub_x'],
|
||||
})
|
||||
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id.startsWith('sub_'))
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([
|
||||
{ sessionID: 'a1', directory: '/x' },
|
||||
{ sessionID: 'a2', directory: '/x' },
|
||||
])
|
||||
})
|
||||
|
||||
it('excludes scheduled sessions', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1', 'sched1'],
|
||||
})
|
||||
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched1']))
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([{ sessionID: 's1', directory: '/a' }])
|
||||
})
|
||||
|
||||
it('excludes both subagent and scheduled sessions simultaneously', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/p': ['manual', 'sub', 'sched'],
|
||||
})
|
||||
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id === 'sub')
|
||||
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched']))
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([{ sessionID: 'manual', directory: '/p' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('runWithResume', () => {
|
||||
it('aborts captured sessions, restarts, then resumes when healthy', async () => {
|
||||
const events: string[] = []
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockImplementation(async (opts) => {
|
||||
events.push(`forward:${opts.path}`)
|
||||
return new Response(null, { status: 200 })
|
||||
})
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1'],
|
||||
'/b': ['s2'],
|
||||
})
|
||||
|
||||
const restart = vi.fn(async () => {
|
||||
events.push('restart')
|
||||
return true
|
||||
})
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
// Assert interleaved ordering: aborts → restart → resumes
|
||||
expect(events).toEqual([
|
||||
'forward:/session/s1/abort',
|
||||
'forward:/session/s2/abort',
|
||||
'restart',
|
||||
'forward:/session/s1/prompt_async',
|
||||
'forward:/session/s2/prompt_async',
|
||||
])
|
||||
|
||||
// Aborts called first for both sessions
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(2, {
|
||||
method: 'POST',
|
||||
path: '/session/s2/abort',
|
||||
directory: '/b',
|
||||
})
|
||||
|
||||
expect(restart).toHaveBeenCalledOnce()
|
||||
|
||||
// Forward was called 4 times: 2 aborts (calls 1-2) + 2 resumes (calls 3-4)
|
||||
expect(forward).toHaveBeenCalledTimes(4)
|
||||
expect(forward).toHaveBeenNthCalledWith(3, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/prompt_async',
|
||||
directory: '/a',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(4, {
|
||||
method: 'POST',
|
||||
path: '/session/s2/prompt_async',
|
||||
directory: '/b',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
|
||||
expect(result).toEqual({ healthy: true, resumedSessionIDs: ['s1', 's2'] })
|
||||
})
|
||||
|
||||
it('does NOT resume when restart returns unhealthy', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1'],
|
||||
})
|
||||
|
||||
const restart = vi.fn(async () => false)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
// Aborts still happen
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(restart).toHaveBeenCalledOnce()
|
||||
|
||||
// No prompt_async calls
|
||||
const promptAsyncCalls = forward.mock.calls.filter(
|
||||
(call: unknown[]) => (call[0] as { path: string }).path.includes('prompt_async'),
|
||||
)
|
||||
expect(promptAsyncCalls).toHaveLength(0)
|
||||
|
||||
expect(result).toEqual({ healthy: false, resumedSessionIDs: [] })
|
||||
})
|
||||
|
||||
it('with no active sessions performs restart only', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({})
|
||||
|
||||
const restart = vi.fn(async () => true)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
expect(restart).toHaveBeenCalledOnce()
|
||||
expect(forward).not.toHaveBeenCalled()
|
||||
|
||||
expect(result).toEqual({ healthy: true, resumedSessionIDs: [] })
|
||||
})
|
||||
|
||||
it('does not abort or resume scheduled sessions', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['manual1', 'sched1'],
|
||||
})
|
||||
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched1']))
|
||||
|
||||
const restart = vi.fn(async () => true)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
// Only manual1 should be aborted and resumed — 2 forward calls total
|
||||
expect(forward).toHaveBeenCalledTimes(2)
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/manual1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(2, {
|
||||
method: 'POST',
|
||||
path: '/session/manual1/prompt_async',
|
||||
directory: '/a',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
|
||||
expect(result).toEqual({ healthy: true, resumedSessionIDs: ['manual1'] })
|
||||
})
|
||||
|
||||
it('is best-effort: per-session errors are swallowed and other sessions still processed', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
// Aborts all succeed, but resume for s2 fails
|
||||
forward
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s1
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s2
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s3
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // resume s1
|
||||
.mockRejectedValueOnce(new Error('connection refused')) // resume s2 fails
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // resume s3
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1', 's2', 's3'],
|
||||
})
|
||||
|
||||
const restart = vi.fn(async () => true)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
expect(result.healthy).toBe(true)
|
||||
expect(result.resumedSessionIDs).toEqual(['s1', 's3'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('abortSessions', () => {
|
||||
it('does not throw when forward rejects and continues processing remaining sessions', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward
|
||||
.mockRejectedValueOnce(new Error('timeout'))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
|
||||
await expect(
|
||||
coordinator.abortSessions([
|
||||
{ sessionID: 's1', directory: '/a' },
|
||||
{ sessionID: 's2', directory: '/b' },
|
||||
]),
|
||||
).resolves.toBeUndefined()
|
||||
|
||||
expect(forward).toHaveBeenCalledTimes(2)
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(2, {
|
||||
method: 'POST',
|
||||
path: '/session/s2/abort',
|
||||
directory: '/b',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('resumeSessions', () => {
|
||||
it('only includes sessions with ok response', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 404 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
|
||||
const sessions: ResumableSession[] = [
|
||||
{ sessionID: 's1', directory: '/a' },
|
||||
{ sessionID: 's2', directory: '/b' },
|
||||
{ sessionID: 's3', directory: '/c' },
|
||||
]
|
||||
|
||||
const result = await coordinator.resumeSessions(sessions)
|
||||
|
||||
expect(result).toEqual(['s1', 's3'])
|
||||
})
|
||||
|
||||
it('does not throw when forward rejects', async () => {
|
||||
vi.mocked(client.forward).mockRejectedValue(new Error('timeout'))
|
||||
|
||||
const result = await coordinator.resumeSessions([{ sessionID: 's1', directory: '/a' }])
|
||||
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import { logger } from '../utils/logger'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
export interface ActiveSessionsProvider {
|
||||
getActiveSessions(): Record<string, string[]>
|
||||
isSubagentSession(sessionId: string): boolean
|
||||
getScheduledSessionIds(): Set<string>
|
||||
}
|
||||
|
||||
export interface ResumableSession {
|
||||
sessionID: string
|
||||
directory: string
|
||||
}
|
||||
|
||||
export interface RestartWithResumeResult {
|
||||
healthy: boolean
|
||||
resumedSessionIDs: string[]
|
||||
}
|
||||
|
||||
export class OpenCodeRestartCoordinator {
|
||||
constructor(
|
||||
private readonly client: OpenCodeClient,
|
||||
private readonly activeSessions: ActiveSessionsProvider,
|
||||
) {}
|
||||
|
||||
captureResumableSessions(): ResumableSession[] {
|
||||
const active = this.activeSessions.getActiveSessions()
|
||||
const scheduled = this.activeSessions.getScheduledSessionIds()
|
||||
const sessions: ResumableSession[] = []
|
||||
|
||||
for (const [directory, sessionIDs] of Object.entries(active)) {
|
||||
for (const sessionID of sessionIDs) {
|
||||
if (!this.activeSessions.isSubagentSession(sessionID) && !scheduled.has(sessionID)) {
|
||||
sessions.push({ sessionID, directory })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sessions
|
||||
}
|
||||
|
||||
async abortSessions(sessions: ResumableSession[]): Promise<void> {
|
||||
await Promise.allSettled(
|
||||
sessions.map(async (s) => {
|
||||
try {
|
||||
await this.client.forward({
|
||||
method: 'POST',
|
||||
path: `/session/${s.sessionID}/abort`,
|
||||
directory: s.directory,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to abort session ${s.sessionID}: ${error}`)
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async resumeSessions(sessions: ResumableSession[]): Promise<string[]> {
|
||||
const results = await Promise.allSettled(
|
||||
sessions.map(async (s) => {
|
||||
try {
|
||||
const response = await this.client.forward({
|
||||
method: 'POST',
|
||||
path: `/session/${s.sessionID}/prompt_async`,
|
||||
directory: s.directory,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
return response.ok ? s.sessionID : null
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to resume session ${s.sessionID}: ${error}`)
|
||||
return null
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
return results
|
||||
.map((result) => (result.status === 'fulfilled' ? result.value : null))
|
||||
.filter((sessionID): sessionID is string => sessionID !== null)
|
||||
}
|
||||
|
||||
async runWithResume(restart: () => Promise<boolean>): Promise<RestartWithResumeResult> {
|
||||
const sessions = this.captureResumableSessions()
|
||||
await this.abortSessions(sessions)
|
||||
const healthy = await restart()
|
||||
const resumedSessionIDs = healthy ? await this.resumeSessions(sessions) : []
|
||||
return { healthy, resumedSessionIDs }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { opencodeServerManager } from './opencode-single-server'
|
||||
import type { OpenCodeSupervisor } from './opencode-supervisor'
|
||||
import type { OpenCodeRestartCoordinator } from './opencode-restart-coordinator'
|
||||
|
||||
let restartCoordinator: OpenCodeRestartCoordinator | null = null
|
||||
|
||||
/**
|
||||
* Registers the process-wide restart coordinator so every restart path can
|
||||
* abort and resume in-flight sessions consistently. Passing null disables
|
||||
* resume (used by tests and pre-initialization paths).
|
||||
*/
|
||||
export function setOpenCodeRestartCoordinator(coordinator: OpenCodeRestartCoordinator | null): void {
|
||||
restartCoordinator = coordinator
|
||||
}
|
||||
|
||||
export function getOpenCodeRestartCoordinator(): OpenCodeRestartCoordinator | null {
|
||||
return restartCoordinator
|
||||
}
|
||||
|
||||
async function performRestart(supervisor?: OpenCodeSupervisor): Promise<boolean> {
|
||||
if (supervisor) {
|
||||
return (await supervisor.restart('settings_restart')).healthy
|
||||
}
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
return opencodeServerManager.checkHealth()
|
||||
}
|
||||
|
||||
/**
|
||||
* The single entry point for restarting the OpenCode server. Every restart
|
||||
* trigger (manual restart, version upgrade/install, workspace config change,
|
||||
* restart-sensitive config saves) routes through here so that interrupted user
|
||||
* sessions are aborted and resumed uniformly when a coordinator is registered.
|
||||
* A full process restart drops in-flight sessions; resuming re-issues a
|
||||
* "continue" prompt once the server is healthy again.
|
||||
*/
|
||||
export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<{ resumedSessionIDs: string[] }> {
|
||||
if (restartCoordinator) {
|
||||
const result = await restartCoordinator.runWithResume(() => performRestart(supervisor))
|
||||
return { resumedSessionIDs: result.resumedSessionIDs }
|
||||
}
|
||||
if (supervisor) {
|
||||
await supervisor.restart('settings_restart')
|
||||
} else {
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
}
|
||||
return { resumedSessionIDs: [] }
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads OpenCode configuration via the non-disruptive API patch. This does
|
||||
* NOT drop the server process, so active sessions keep running and there is
|
||||
* nothing to resume.
|
||||
*/
|
||||
export async function reloadOpenCodeConfig(supervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (supervisor) {
|
||||
await supervisor.reloadConfig('settings_reload')
|
||||
return
|
||||
}
|
||||
await opencodeServerManager.reloadConfig()
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -374,6 +375,11 @@ export class ScheduleService {
|
||||
this.onJobChange = handler
|
||||
}
|
||||
|
||||
getActiveRunSessionIds(): Set<string> {
|
||||
const runs = listRunningScheduleRuns(this.db)
|
||||
return new Set(runs.filter(r => r.sessionId).map(r => r.sessionId!))
|
||||
}
|
||||
|
||||
listAllEnabledJobs(): ScheduleJob[] {
|
||||
return listEnabledScheduleJobs(this.db)
|
||||
}
|
||||
@@ -540,7 +546,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 +586,7 @@ export class ScheduleService {
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, run.id, {
|
||||
worktreePath: wt.worktreePath,
|
||||
runBranch: wt.runBranch,
|
||||
workspaceId: wt.workspaceId,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -594,6 +601,7 @@ export class ScheduleService {
|
||||
body: JSON.stringify({
|
||||
title: sessionTitle,
|
||||
agent: job.agentSlug ?? undefined,
|
||||
permission: buildSchedulePermissionRuleset(job.permissionConfig),
|
||||
}),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
@@ -1111,11 +1119,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)
|
||||
|
||||
@@ -58,6 +58,7 @@ class SSEAggregator {
|
||||
private started = false
|
||||
private pendingActionsFetcher: PendingActionsFetcher | null = null
|
||||
private passwordResolver: OpenCodePasswordResolver | null = null
|
||||
private scheduledSessionsResolver: (() => Set<string>) | null = null
|
||||
|
||||
private constructor() {}
|
||||
|
||||
@@ -69,6 +70,10 @@ class SSEAggregator {
|
||||
this.passwordResolver = resolver
|
||||
}
|
||||
|
||||
setScheduledSessionsResolver(resolver: () => Set<string>): void {
|
||||
this.scheduledSessionsResolver = resolver
|
||||
}
|
||||
|
||||
reconnect(): void {
|
||||
if (!this.started) return
|
||||
logger.info('SSE forcing upstream reconnect (auth changed)')
|
||||
@@ -523,6 +528,10 @@ class SSEAggregator {
|
||||
return false
|
||||
}
|
||||
|
||||
getScheduledSessionIds(): Set<string> {
|
||||
return this.scheduledSessionsResolver?.() ?? new Set()
|
||||
}
|
||||
|
||||
getActiveDirectories(): string[] {
|
||||
return Array.from(this.activeSessions.keys())
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
const mockFn = vi.hoisted(() => vi.fn().mockReturnValue('mocked'))
|
||||
|
||||
describe('bun test vi.hoisted compatibility', () => {
|
||||
it('supports vi.hoisted', () => {
|
||||
expect(mockFn()).toBe('mocked')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { migrate, type Migration } from '../../src/db/migration-runner'
|
||||
import { logger } from '../../src/utils/logger'
|
||||
|
||||
function makeMigration(version: number, name: string, up: () => void): Migration {
|
||||
return { version, name, up, down: () => {} }
|
||||
}
|
||||
|
||||
describe('migrate - version/name mismatch guard', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('warns and skips when an applied version was recorded under a different name', () => {
|
||||
const db = new Database(':memory:')
|
||||
db.run('CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)')
|
||||
db.run("INSERT INTO schema_migrations (version, name, applied_at) VALUES (15, 'repos-add-name', 0)")
|
||||
|
||||
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
|
||||
const up = vi.fn()
|
||||
|
||||
migrate(db, [makeMigration(15, 'schedule-worktree-isolation', up)])
|
||||
|
||||
expect(up).not.toHaveBeenCalled()
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Migration version 15 is recorded as "repos-add-name" but the code defines "schedule-worktree-isolation"'),
|
||||
)
|
||||
})
|
||||
|
||||
it('does not warn when recorded names match', () => {
|
||||
const db = new Database(':memory:')
|
||||
db.run('CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)')
|
||||
db.run("INSERT INTO schema_migrations (version, name, applied_at) VALUES (15, 'schedule-worktree-isolation', 0)")
|
||||
|
||||
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
|
||||
|
||||
migrate(db, [makeMigration(15, 'schedule-worktree-isolation', vi.fn())])
|
||||
|
||||
expect(warnSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('applies pending migrations and records them', () => {
|
||||
const db = new Database(':memory:')
|
||||
const up = vi.fn()
|
||||
|
||||
migrate(db, [makeMigration(1, 'base', up)])
|
||||
|
||||
expect(up).toHaveBeenCalledTimes(1)
|
||||
const row = db.prepare('SELECT version, name FROM schema_migrations WHERE version = 1').get() as { version: number; name: string }
|
||||
expect(row).toEqual({ version: 1, name: 'base' })
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import * as db from '../../src/db/queries'
|
||||
import * as schema from '../../src/db/schema'
|
||||
|
||||
const mockDb = {
|
||||
prepare: vi.fn(),
|
||||
@@ -289,17 +288,4 @@ describe('Database Queries', () => {
|
||||
expect(mockDb.prepare).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Database Schema', () => {
|
||||
it('should have schema module available', () => {
|
||||
expect(schema.initializeDatabase).toBeDefined()
|
||||
expect(typeof schema.initializeDatabase).toBe('function')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Transaction Support', () => {
|
||||
it('should support transaction existence', () => {
|
||||
expect(typeof mockDb.transaction).toBe('function')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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) {
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { DEFAULTS } from '@opencode-manager/shared/config'
|
||||
|
||||
const { HEARTBEAT_INTERVAL_MS } = DEFAULTS.SSE
|
||||
|
||||
describe('SSE Routes', () => {
|
||||
describe('HEARTBEAT_INTERVAL_MS', () => {
|
||||
it('should be 30000ms (30 seconds)', () => {
|
||||
expect(HEARTBEAT_INTERVAL_MS).toBe(30000)
|
||||
})
|
||||
|
||||
it('should fire heartbeats at correct interval', async () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
const heartbeatSpy = vi.fn()
|
||||
const intervalId = setInterval(() => {
|
||||
heartbeatSpy()
|
||||
}, HEARTBEAT_INTERVAL_MS)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(heartbeatSpy).toHaveBeenCalledTimes(0)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30000)
|
||||
expect(heartbeatSpy).toHaveBeenCalledTimes(1)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30000)
|
||||
expect(heartbeatSpy).toHaveBeenCalledTimes(2)
|
||||
|
||||
clearInterval(intervalId)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should fire two heartbeats within 70 seconds', async () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
const heartbeatSpy = vi.fn()
|
||||
const intervalId = setInterval(() => {
|
||||
heartbeatSpy()
|
||||
}, HEARTBEAT_INTERVAL_MS)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(70000)
|
||||
expect(heartbeatSpy).toHaveBeenCalledTimes(2)
|
||||
|
||||
clearInterval(intervalId)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -72,13 +72,6 @@ describe('STT Routes', () => {
|
||||
sttApp = createSTTRoutes(mockDb)
|
||||
})
|
||||
|
||||
describe('createSTTRoutes', () => {
|
||||
it('should create a Hono app with routes', () => {
|
||||
expect(sttApp).toBeDefined()
|
||||
expect(typeof sttApp.fetch).toBe('function')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /status', () => {
|
||||
it('should return status with correct structure', async () => {
|
||||
const req = new Request('http://localhost/status?userId=test')
|
||||
|
||||
@@ -28,7 +28,6 @@ function createRunner(): { runner: DockerRunner; calls: { inspectSelf: SelfConta
|
||||
const runner: DockerRunner = {
|
||||
inspectSelf: vi.fn().mockImplementation(async () => {
|
||||
const info: SelfContainerInfo = {
|
||||
containerId: 'abc123',
|
||||
project: 'opencode',
|
||||
service: 'manager',
|
||||
workingDir: '/app',
|
||||
@@ -164,12 +163,16 @@ describe('ManagerUpgradeService', () => {
|
||||
|
||||
const job = await service.startUpgrade('0.15.0')
|
||||
|
||||
expect(job.status).toBe('recreating')
|
||||
// startUpgrade returns as soon as the job is created; the pull and
|
||||
// recreate continue in the background and are reflected via job status.
|
||||
expect(job.status).toBe('pulling')
|
||||
expect(job.toVersion).toBe('0.15.0')
|
||||
expect(job.targetImage).toBe('opencode-manager:0.15.0')
|
||||
expect(job.fromVersion).toBe('0.14.0')
|
||||
expect(job.error).toBeNull()
|
||||
|
||||
await tick()
|
||||
|
||||
// Pull was called with the resolved target image
|
||||
expect(calls.pulled).toEqual(['opencode-manager:0.15.0'])
|
||||
expect(calls.inspectSelf).toHaveLength(1)
|
||||
@@ -198,6 +201,7 @@ describe('ManagerUpgradeService', () => {
|
||||
})
|
||||
|
||||
await service.startUpgrade('0.15.0')
|
||||
await tick()
|
||||
expect(calls.pulled).toEqual(['my-registry/opencode-manager:0.15.0'])
|
||||
})
|
||||
|
||||
@@ -210,6 +214,7 @@ describe('ManagerUpgradeService', () => {
|
||||
})
|
||||
|
||||
await service.startUpgrade()
|
||||
await tick()
|
||||
expect(calls.pulled).toEqual(['opencode-manager:latest'])
|
||||
})
|
||||
})
|
||||
@@ -279,6 +284,8 @@ describe('ManagerUpgradeService', () => {
|
||||
message: 'An upgrade is already in progress',
|
||||
})
|
||||
|
||||
await tick()
|
||||
|
||||
// Only one pull and one spawn should have occurred
|
||||
expect(calls.pulled).toHaveLength(1)
|
||||
expect(calls.spawned).toHaveLength(1)
|
||||
@@ -286,8 +293,8 @@ describe('ManagerUpgradeService', () => {
|
||||
})
|
||||
|
||||
describe('startUpgrade - pull failure', () => {
|
||||
// Cycle 4: pull fails → job marked failed, 500 thrown
|
||||
it('marks job as failed and throws 500 when pull rejects', async () => {
|
||||
// Cycle 4: pull fails in the background → job marked failed with the error
|
||||
it('marks job as failed when the background pull rejects', async () => {
|
||||
const { runner, calls } = createRunner()
|
||||
runner.pull = vi.fn().mockRejectedValue(new Error('Network error'))
|
||||
|
||||
@@ -297,10 +304,10 @@ describe('ManagerUpgradeService', () => {
|
||||
capability: () => ({ inDocker: true, socket: true, enabled: true }),
|
||||
})
|
||||
|
||||
await expect(service.startUpgrade('0.15.0')).rejects.toMatchObject({
|
||||
status: 500,
|
||||
message: 'Network error',
|
||||
})
|
||||
const job = await service.startUpgrade('0.15.0')
|
||||
expect(job.status).toBe('pulling')
|
||||
|
||||
await tick()
|
||||
|
||||
// spawnRecreate should NOT have been called
|
||||
expect(calls.spawned).toHaveLength(0)
|
||||
@@ -314,6 +321,70 @@ describe('ManagerUpgradeService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('stale recreating jobs', () => {
|
||||
it('getStatus fails a recreating job older than the staleness bound', async () => {
|
||||
const { runner } = createRunner()
|
||||
insertUpgradeJob(db, {
|
||||
status: 'recreating',
|
||||
fromVersion: '0.14.0',
|
||||
toVersion: '0.15.0',
|
||||
startedAt: Date.now() - 11 * 60 * 1000,
|
||||
})
|
||||
|
||||
const service = new ManagerUpgradeService(db, {
|
||||
runner,
|
||||
// Same as fromVersion — the recreate helper never completed
|
||||
getCurrentVersion: vi.fn().mockResolvedValue('0.14.0'),
|
||||
capability: () => ({ inDocker: true, socket: true, enabled: true }),
|
||||
})
|
||||
|
||||
const status = await service.getStatus()
|
||||
expect(status.job).not.toBeNull()
|
||||
expect(status.job!.status).toBe('failed')
|
||||
expect(status.job!.error).toMatch(/did not complete/i)
|
||||
})
|
||||
|
||||
it('startUpgrade proceeds after expiring a stale recreating job', async () => {
|
||||
const { runner, calls } = createRunner()
|
||||
insertUpgradeJob(db, {
|
||||
status: 'recreating',
|
||||
fromVersion: '0.14.0',
|
||||
toVersion: '0.15.0',
|
||||
startedAt: Date.now() - 11 * 60 * 1000,
|
||||
})
|
||||
|
||||
const service = new ManagerUpgradeService(db, {
|
||||
runner,
|
||||
getCurrentVersion: vi.fn().mockResolvedValue('0.14.0'),
|
||||
capability: () => ({ inDocker: true, socket: true, enabled: true }),
|
||||
})
|
||||
|
||||
const job = await service.startUpgrade('0.16.0')
|
||||
expect(job.status).toBe('pulling')
|
||||
await tick()
|
||||
expect(calls.pulled).toEqual(['opencode-manager:0.16.0'])
|
||||
})
|
||||
|
||||
it('getStatus leaves a fresh recreating job untouched', async () => {
|
||||
const { runner } = createRunner()
|
||||
insertUpgradeJob(db, {
|
||||
status: 'recreating',
|
||||
fromVersion: '0.14.0',
|
||||
toVersion: '0.15.0',
|
||||
startedAt: Date.now(),
|
||||
})
|
||||
|
||||
const service = new ManagerUpgradeService(db, {
|
||||
runner,
|
||||
getCurrentVersion: vi.fn().mockResolvedValue('0.14.0'),
|
||||
capability: () => ({ inDocker: true, socket: true, enabled: true }),
|
||||
})
|
||||
|
||||
const status = await service.getStatus()
|
||||
expect(status.job!.status).toBe('recreating')
|
||||
})
|
||||
})
|
||||
|
||||
describe('reconcile', () => {
|
||||
// Cycle 5: recreating job + version matches toVersion → completed
|
||||
it('marks recreating job as completed when current version matches toVersion', async () => {
|
||||
@@ -492,6 +563,7 @@ describe('ManagerUpgradeService', () => {
|
||||
})
|
||||
|
||||
await service.startUpgrade('0.15.0')
|
||||
await tick()
|
||||
// Should NOT produce 'localhost:0.15.0'
|
||||
expect(calls.pulled).toEqual(['localhost:5000/opencode-manager:0.15.0'])
|
||||
expect(calls.spawned[0]!.targetImage).toBe('localhost:5000/opencode-manager:0.15.0')
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
|
||||
@@ -20,6 +20,7 @@ export default defineConfig({
|
||||
'src/db/model-state.test.ts',
|
||||
'src/routes/providers.test.ts',
|
||||
'src/routes/repos.test.ts',
|
||||
'src/routes/session-pins.test.ts',
|
||||
],
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
|
||||
Reference in new issue
Block a user