diff --git a/Dockerfile b/Dockerfile index 54db438d..97edcbe0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,7 +28,7 @@ RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | d RUN curl -fsSL https://download.docker.com/linux/debian/gpg | dd of=/usr/share/keyrings/docker-archive-keyring.gpg \ && echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian bookworm stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null \ - && apt-get update && apt-get install -y docker-ce-cli docker-compose-plugin \ + && apt-get update && apt-get install -y docker-ce-cli \ && rm -rf /var/lib/apt/lists/* RUN corepack enable && corepack prepare pnpm@latest --activate diff --git a/backend/package.json b/backend/package.json index d62550b2..456eb40c 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/src/db/manager-upgrade.ts b/backend/src/db/manager-upgrade.ts index 8697b0a4..240fd3c7 100644 --- a/backend/src/db/manager-upgrade.ts +++ b/backend/src/db/manager-upgrade.ts @@ -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 }>, diff --git a/backend/src/db/migration-runner.ts b/backend/src/db/migration-runner.ts index 71f737d4..503bb7ec 100644 --- a/backend/src/db/migration-runner.ts +++ b/backend/src/db/migration-runner.ts @@ -24,9 +24,28 @@ function ensureMigrationsTable(db: Database): void { `) } -function getAppliedVersions(db: Database): Set { - 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 { + 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, 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)) diff --git a/backend/src/db/migrations/016-schedule-permission-config.ts b/backend/src/db/migrations/016-schedule-permission-config.ts new file mode 100644 index 00000000..a6a05aa3 --- /dev/null +++ b/backend/src/db/migrations/016-schedule-permission-config.ts @@ -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 diff --git a/backend/src/db/migrations/017-schedule-run-workspace-id.ts b/backend/src/db/migrations/017-schedule-run-workspace-id.ts new file mode 100644 index 00000000..5affc233 --- /dev/null +++ b/backend/src/db/migrations/017-schedule-run-workspace-id.ts @@ -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 diff --git a/backend/src/db/migrations/018-session-pins.ts b/backend/src/db/migrations/018-session-pins.ts new file mode 100644 index 00000000..1cf09c6e --- /dev/null +++ b/backend/src/db/migrations/018-session-pins.ts @@ -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 diff --git a/backend/src/db/migrations/016-manager-upgrade-jobs.ts b/backend/src/db/migrations/019-manager-upgrade-jobs.ts similarity index 97% rename from backend/src/db/migrations/016-manager-upgrade-jobs.ts rename to backend/src/db/migrations/019-manager-upgrade-jobs.ts index 769dfe45..9bc1e4ed 100644 --- a/backend/src/db/migrations/016-manager-upgrade-jobs.ts +++ b/backend/src/db/migrations/019-manager-upgrade-jobs.ts @@ -1,7 +1,7 @@ import type { Migration } from '../migration-runner' const migration: Migration = { - version: 16, + version: 19, name: 'manager-upgrade-jobs', up(db) { diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts index 0f2fde84..0cec5fb0 100644 --- a/backend/src/db/migrations/index.ts +++ b/backend/src/db/migrations/index.ts @@ -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, ] diff --git a/backend/src/db/schedules.ts b/backend/src/db/schedules.ts index 2a5f1930..d000e895 100644 --- a/backend/src/db/schedules.ts +++ b/backend/src/db/schedules.ts @@ -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 diff --git a/backend/src/db/session-pins.test.ts b/backend/src/db/session-pins.test.ts new file mode 100644 index 00000000..fc5317ed --- /dev/null +++ b/backend/src/db/session-pins.test.ts @@ -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') + }) + }) +}) diff --git a/backend/src/db/session-pins.ts b/backend/src/db/session-pins.ts new file mode 100644 index 00000000..4d6e30a7 --- /dev/null +++ b/backend/src/db/session-pins.ts @@ -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() +} diff --git a/backend/src/index.ts b/backend/src/index.ts index ea8c89d4..b5c0f430 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -15,15 +15,20 @@ import { createFileRoutes } from './routes/files' import { createScheduleRoutes } from './routes/schedules' import { createManagerUpgradeRoutes } from './routes/manager-upgrade' -async function getAppVersion(): Promise { - 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 | null = null + +function getAppVersion(): Promise { + 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)) diff --git a/backend/src/routes/oauth.ts b/backend/src/routes/oauth.ts index 78463f55..516e4ae9 100644 --- a/backend/src/routes/oauth.ts +++ b/backend/src/routes/oauth.ts @@ -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 { - if (openCodeSupervisor) { - await openCodeSupervisor.reloadConfig('settings_reload') - return - } - - await opencodeServerManager.reloadConfig() -} - export function createOAuthRoutes(openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) { const app = new Hono() diff --git a/backend/src/routes/providers.ts b/backend/src/routes/providers.ts index 3c221a8b..d5607c81 100644 --- a/backend/src/routes/providers.ts +++ b/backend/src/routes/providers.ts @@ -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 { - 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() diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 96332476..a21db00e 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -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 { - 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) } diff --git a/backend/src/routes/session-pins.test.ts b/backend/src/routes/session-pins.test.ts new file mode 100644 index 00000000..acd831d8 --- /dev/null +++ b/backend/src/routes/session-pins.test.ts @@ -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') + }) +}) diff --git a/backend/src/routes/session-pins.ts b/backend/src/routes/session-pins.ts new file mode 100644 index 00000000..d18b839e --- /dev/null +++ b/backend/src/routes/session-pins.ts @@ -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 +} diff --git a/backend/src/routes/settings.test.ts b/backend/src/routes/settings.test.ts index 1a1d739b..94be319c 100644 --- a/backend/src/routes/settings.test.ts +++ b/backend/src/routes/settings.test.ts @@ -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) + }) +}) diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index e2cd896a..1d529e06 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -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 { - if (openCodeSupervisor) { - await openCodeSupervisor.reloadConfig('settings_reload') - return - } - - await opencodeServerManager.reloadConfig() -} - -async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise { - if (openCodeSupervisor) { - await openCodeSupervisor.restart('settings_restart') - return - } - - opencodeServerManager.clearStartupError() - await opencodeServerManager.restart() -} - async function restartOpenCodeSafe(openCodeSupervisor: OpenCodeSupervisor | undefined, context: string): Promise { 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') diff --git a/backend/src/services/manager-upgrade.ts b/backend/src/services/manager-upgrade.ts index 5c88cd0d..680abb79 100644 --- a/backend/src/services/manager-upgrade.ts +++ b/backend/src/services/manager-upgrade.ts @@ -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 { + 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 { 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 = 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'] || '', diff --git a/backend/src/services/opencode-restart-coordinator.test.ts b/backend/src/services/opencode-restart-coordinator.test.ts new file mode 100644 index 00000000..a3aab0e0 --- /dev/null +++ b/backend/src/services/opencode-restart-coordinator.test.ts @@ -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 { + return { + getActiveSessions: vi.fn(() => ({})), + isSubagentSession: vi.fn(() => false), + getScheduledSessionIds: vi.fn(() => new Set()), + ...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([]) + }) + }) +}) diff --git a/backend/src/services/opencode-restart-coordinator.ts b/backend/src/services/opencode-restart-coordinator.ts new file mode 100644 index 00000000..65c91bf7 --- /dev/null +++ b/backend/src/services/opencode-restart-coordinator.ts @@ -0,0 +1,89 @@ +import { logger } from '../utils/logger' +import type { OpenCodeClient } from './opencode/client' + +export interface ActiveSessionsProvider { + getActiveSessions(): Record + isSubagentSession(sessionId: string): boolean + getScheduledSessionIds(): Set +} + +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 { + 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 { + 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): Promise { + const sessions = this.captureResumableSessions() + await this.abortSessions(sessions) + const healthy = await restart() + const resumedSessionIDs = healthy ? await this.resumeSessions(sessions) : [] + return { healthy, resumedSessionIDs } + } +} diff --git a/backend/src/services/opencode-restart.ts b/backend/src/services/opencode-restart.ts new file mode 100644 index 00000000..68a92c09 --- /dev/null +++ b/backend/src/services/opencode-restart.ts @@ -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 { + 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 { + if (supervisor) { + await supervisor.reloadConfig('settings_reload') + return + } + await opencodeServerManager.reloadConfig() +} diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index a59c7824..50606dc7 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -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 diff --git a/backend/src/services/schedule-config.ts b/backend/src/services/schedule-config.ts index 0b61e896..4cb575cc 100644 --- a/backend/src/services/schedule-config.ts +++ b/backend/src/services/schedule-config.ts @@ -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, } diff --git a/backend/src/services/schedule-worktree.ts b/backend/src/services/schedule-worktree.ts index 6f3a085e..a07af8e0 100644 --- a/backend/src/services/schedule-worktree.ts +++ b/backend/src/services/schedule-worktree.ts @@ -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( + '/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 | 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 { + async pruneRunArtifacts( + repo: Repo, + artifacts: { runBranch: string | null; worktreePath: string | null; workspaceId?: string | null }[], + ): Promise { 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 | undefined, + ): Promise { + 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 diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index c3756520..5f75c5e0 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -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 { + 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) diff --git a/backend/src/services/sse-aggregator.ts b/backend/src/services/sse-aggregator.ts index 759656b1..cb19c3ea 100644 --- a/backend/src/services/sse-aggregator.ts +++ b/backend/src/services/sse-aggregator.ts @@ -58,6 +58,7 @@ class SSEAggregator { private started = false private pendingActionsFetcher: PendingActionsFetcher | null = null private passwordResolver: OpenCodePasswordResolver | null = null + private scheduledSessionsResolver: (() => Set) | null = null private constructor() {} @@ -69,6 +70,10 @@ class SSEAggregator { this.passwordResolver = resolver } + setScheduledSessionsResolver(resolver: () => Set): 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 { + return this.scheduledSessionsResolver?.() ?? new Set() + } + getActiveDirectories(): string[] { return Array.from(this.activeSessions.keys()) } diff --git a/backend/test/bun-mock-test.test.ts b/backend/test/bun-mock-test.test.ts deleted file mode 100644 index 4494c031..00000000 --- a/backend/test/bun-mock-test.test.ts +++ /dev/null @@ -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') - }) -}) diff --git a/backend/test/db/migration-runner.test.ts b/backend/test/db/migration-runner.test.ts new file mode 100644 index 00000000..643cebc5 --- /dev/null +++ b/backend/test/db/migration-runner.test.ts @@ -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' }) + }) +}) diff --git a/backend/test/db/queries.test.ts b/backend/test/db/queries.test.ts index a2817fb6..dd429b63 100644 --- a/backend/test/db/queries.test.ts +++ b/backend/test/db/queries.test.ts @@ -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') - }) - }) }) diff --git a/backend/test/db/schedules.permission.test.ts b/backend/test/db/schedules.permission.test.ts new file mode 100644 index 00000000..5caf2d52 --- /dev/null +++ b/backend/test/db/schedules.permission.test.ts @@ -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 => ({ + 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) + }) +}) diff --git a/backend/test/db/schedules.test.ts b/backend/test/db/schedules.test.ts index b7920e14..365ac3b4 100644 --- a/backend/test/db/schedules.test.ts +++ b/backend/test/db/schedules.test.ts @@ -20,6 +20,7 @@ function makeJobRow(overrides: Record = {}) { 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 = {}) { 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 }, ]) }) diff --git a/backend/test/mocks/bun-sqlite.ts b/backend/test/mocks/bun-sqlite.ts index 3d925a63..517868ff 100644 --- a/backend/test/mocks/bun-sqlite.ts +++ b/backend/test/mocks/bun-sqlite.ts @@ -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 void>(fn: T) { diff --git a/backend/test/routes/sse.test.ts b/backend/test/routes/sse.test.ts deleted file mode 100644 index e24fb891..00000000 --- a/backend/test/routes/sse.test.ts +++ /dev/null @@ -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() - }) - }) -}) diff --git a/backend/test/routes/stt.test.ts b/backend/test/routes/stt.test.ts index 8c6c31e9..f970d441 100644 --- a/backend/test/routes/stt.test.ts +++ b/backend/test/routes/stt.test.ts @@ -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') diff --git a/backend/test/services/manager-upgrade.test.ts b/backend/test/services/manager-upgrade.test.ts index fcd2c606..3d6f3519 100644 --- a/backend/test/services/manager-upgrade.test.ts +++ b/backend/test/services/manager-upgrade.test.ts @@ -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') diff --git a/backend/test/services/schedule-config.test.ts b/backend/test/services/schedule-config.test.ts index bebcf7bd..38fd1c63 100644 --- a/backend/test/services/schedule-config.test.ts +++ b/backend/test/services/schedule-config.test.ts @@ -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, diff --git a/backend/test/services/schedule-permissions.test.ts b/backend/test/services/schedule-permissions.test.ts new file mode 100644 index 00000000..892b0ec8 --- /dev/null +++ b/backend/test/services/schedule-permissions.test.ts @@ -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' }, + }) + }) +}) diff --git a/backend/test/services/schedule-worktree.test.ts b/backend/test/services/schedule-worktree.test.ts index 59b25e0a..3d40d25a 100644 --- a/backend/test/services/schedule-worktree.test.ts +++ b/backend/test/services/schedule-worktree.test.ts @@ -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 }> { + 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) + }) }) diff --git a/backend/test/services/schedules.permission.test.ts b/backend/test/services/schedules.permission.test.ts new file mode 100644 index 00000000..19a402ec --- /dev/null +++ b/backend/test/services/schedules.permission.test.ts @@ -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) { + 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') + }) +}) diff --git a/backend/test/services/schedules.test.ts b/backend/test/services/schedules.test.ts index 731d2ea4..aa22a063 100644 --- a/backend/test/services/schedules.test.ts +++ b/backend/test/services/schedules.test.ts @@ -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) }) diff --git a/backend/vitest.config.ts b/backend/vitest.config.ts index da53ef82..8fff8255 100644 --- a/backend/vitest.config.ts +++ b/backend/vitest.config.ts @@ -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', diff --git a/docker-compose.yml b/docker-compose.yml index 09aef83a..17c400d8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -23,6 +23,7 @@ services: - WORKSPACE_PATH=/workspace - OCM_IMAGE=${OCM_IMAGE:-ghcr.io/chriswritescode-dev/opencode-manager:latest} - OCM_MANAGER_UPGRADE_ENABLED=${OCM_MANAGER_UPGRADE_ENABLED:-true} + - OCM_IN_DOCKER=true - PROCESS_START_WAIT_MS=2000 - PROCESS_VERIFY_WAIT_MS=1000 - HEALTH_CHECK_INTERVAL_MS=5000 diff --git a/docs/features/ai-config.md b/docs/features/ai-config.md index 927efb83..e953049a 100644 --- a/docs/features/ai-config.md +++ b/docs/features/ai-config.md @@ -44,6 +44,8 @@ You can switch models at any point during a session without losing context. The Configure API keys or OAuth for AI providers. +![Providers Settings](../images/ai-config-providers.png) + ### API Key Method 1. Go to **Settings > Providers** diff --git a/docs/features/assistant-mode.md b/docs/features/assistant-mode.md index cbedd5ee..f03cee0c 100644 --- a/docs/features/assistant-mode.md +++ b/docs/features/assistant-mode.md @@ -40,6 +40,8 @@ When the assistant self-edits its agent definition (e.g., to refine behavior or 3. A welcome prompt is automatically sent to orient the agent 4. Subsequent visits resume the most recent session +![Assistant Page](../images/assistant-page.png) + No manual setup is required. The workspace directory and all managed files are created automatically. ## Session Views diff --git a/docs/features/chat.md b/docs/features/chat.md index 1a5b47fa..197034ac 100644 --- a/docs/features/chat.md +++ b/docs/features/chat.md @@ -19,6 +19,8 @@ Messages stream in real-time using Server-Sent Events (SSE): - No waiting for complete responses - Can interrupt generation if needed +![Chat Conversation](../images/chat-conversation.png) + ## Model Selection Click the **model name** in the chat prompt area to open the quick model switcher. From there you can: @@ -142,6 +144,8 @@ Access your sessions from the sidebar: - Most recent sessions appear first - Click a session to resume +![Session List](../images/chat-session-list.png) + ### Searching Sessions Find sessions by content: @@ -150,6 +154,16 @@ Find sessions by content: 2. Type your search query 3. Results show sessions with matching content +### Pinning Sessions + +Pin important sessions to the top of your session list: + +1. Open the session actions menu (three dots on the session card) +2. Select **Pin to top** +3. The session moves to a **Pinned** section above the **Recent** section + +Pinned sessions stay at the top regardless of age or activity. Unpin anytime from the same menu. See [Session Pinning](session-pins.md) for details. + ### Deleting Sessions Remove sessions you no longer need: diff --git a/docs/features/files.md b/docs/features/files.md index ebeb9f3f..be894190 100644 --- a/docs/features/files.md +++ b/docs/features/files.md @@ -13,6 +13,8 @@ The file browser displays your repository as an expandable tree: - Icons indicate file types - Modified files are highlighted +![File Browser](../images/file-browser.png) + ### Breadcrumbs Navigate quickly using the breadcrumb path at the top: diff --git a/docs/features/git.md b/docs/features/git.md index bfa83ce6..06b73652 100644 --- a/docs/features/git.md +++ b/docs/features/git.md @@ -61,7 +61,7 @@ Access comprehensive git operations via the source control button. - Discard changes to revert modifications - View diffs inline for any changed file -![Changes Tab](../images/git/git-changes.png) +![Changes Tab](../images/git/git-changes.png){ .phone } ### Commits Tab @@ -70,7 +70,7 @@ Access comprehensive git operations via the source control button. - See file changes in each commit - Track ahead/behind status with remote -![Commits Tab](../images/git/git-commits.png) +![Commits Tab](../images/git/git-commits.png){ .phone } ### Branches Tab @@ -79,7 +79,7 @@ Access comprehensive git operations via the source control button. - Switch branches (checks out the branch) - Delete local branches -![Branches Tab](../images/git/git-branch.png) +![Branches Tab](../images/git/git-branch.png){ .phone } ## Diff Viewer @@ -96,7 +96,7 @@ View file changes with a unified diff format: - Diffs appear inline or in a modal depending on context - Use the expand/collapse toggle for large diffs -![Diff Viewer](../images/git/git-diffview.png) +![Diff Viewer](../images/git/git-diffview.png){ .phone } ## Repository Actions diff --git a/docs/features/mcp.md b/docs/features/mcp.md index 21cad152..c992efec 100644 --- a/docs/features/mcp.md +++ b/docs/features/mcp.md @@ -16,11 +16,13 @@ MCP (Model Context Protocol) allows AI models to interact with external tools an Local servers run as processes on your machine: -1. Go to **Settings > MCP Servers** +1. Open a repository and click **MCP** in the sidebar 2. Click **Add Server** 3. Select **Local** 4. Configure: +![MCP Servers List](../images/mcp-servers-list.png) + ```json { "name": "filesystem", diff --git a/docs/features/mobile.md b/docs/features/mobile.md index 5ab3890d..2bfeaf24 100644 --- a/docs/features/mobile.md +++ b/docs/features/mobile.md @@ -11,6 +11,8 @@ The UI is optimized for mobile devices: - Adaptive components - Gesture support +![Mobile Sessions View](../images/mobile-sessions.png){ .phone } + ## Installing as PWA ### iOS diff --git a/docs/features/notifications.md b/docs/features/notifications.md index acfdd567..8b3f45cc 100644 --- a/docs/features/notifications.md +++ b/docs/features/notifications.md @@ -47,6 +47,8 @@ Apple's Push Notification Service (APNs) has strict requirements: ### 1. Generate VAPID Keys +![Notification Settings](../images/notifications-settings.png) + Generate VAPID public/private key pair: ```bash diff --git a/docs/features/overview.md b/docs/features/overview.md index cd43b640..9dda8004 100644 --- a/docs/features/overview.md +++ b/docs/features/overview.md @@ -30,6 +30,7 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI - **File Mentions** - Reference files with `@filename` autocomplete - **Plan/Build Modes** - Toggle between read-only and file-change modes - **Per-Agent Model Selection** — Each agent retains its own model selection independently +- **Session Pinning** — Pin important sessions to a dedicated section at the top of the session list - **Mermaid Diagrams** - Visual diagram rendering in chat [Learn more →](chat.md) @@ -103,3 +104,12 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI - **Session Continuity** — Navigating to the assistant always resumes the most recent session or creates one automatically [Learn more →](assistant-mode.md) + +### OpenCode Server Health + +- **Live Status** — Server health indicator in Settings (Healthy/Unhealthy/Starting) +- **Graceful Restart** — Active sessions are aborted and resumed with `continue` after restart +- **Auto-Recovery** — Configurable health monitoring with automatic recovery on failure +- **Version Management** — View current versions and trigger OpenCode upgrades from the UI + +[Learn more →](server-health.md) diff --git a/docs/features/schedules.md b/docs/features/schedules.md index a36435fe..b779a8fd 100644 --- a/docs/features/schedules.md +++ b/docs/features/schedules.md @@ -67,6 +67,65 @@ Schedules can run with: If a requested model is no longer available, OpenCode Manager falls back to a valid configured model for that provider so the run can still start when possible. +## Skills + +Each schedule can optionally attach skill slugs and notes. Skills modify the agent's behavior during the run — for example, you could attach a review-focused skill to a weekly code review schedule. + +![Skills Tab](../images/schedule-skills-tab.png) + +The **Skills** tab in the schedule dialog lets you: + +- Select one or more **skill slugs** from a multi-select input +- Add free-form **notes** (max 2000 characters) that the agent receives as additional context + +Skill metadata is passed to the OpenCode workspace config when the run starts, making the selected skills available to the agent for that run only. + +## Worktree Isolation + +Each scheduled run executes in a **throwaway git worktree** — an isolated working copy branched off the repository's base branch. This provides two key guarantees: + +- **No side effects on the main working tree** — file changes, branch switches, and experimentations during the run are confined to the worktree. +- **Clean state per run** — every run starts from a fresh branch (`schedule/{jobId}/run-{runId}`) based off the latest remote state. + +When the run completes or fails, the worktree is cleaned up automatically. The worktree is **never auto-pushed** — any changes an agent makes during a scheduled run stay local and are discarded after the run finishes. The real safety boundary is this disposal: modifications affect only the throwaway worktree and are not propagated back to the repository. + +### Branch Configuration + +By default, runs branch off the repository's default branch. You can override this by specifying a **base branch** in the schedule settings — the worktree branches off your chosen branch instead. + +![Branch and Worktree Configuration](../images/schedules/09-schedule-creation.png) + +## Permission Configuration + +Every schedule includes a **Permissions** section in the General tab. These settings control what the agent can access and execute during unattended runs. + +![Permissions Configuration](../images/schedule-permissions.png) + +### Allow Access Outside the Working Directory + +When **disabled** (the default), the agent's file operations are confined to the isolated worktree. Enable this if the schedule requires reading or writing files elsewhere on the system (e.g., accessing a shared configuration directory). + +### Blocked Bash Commands + +The following bash command patterns are always blocked by default: + +``` +git push --force* +git push -f * +sudo * +dd * +mkfs* +shutdown* +reboot* +halt* +kill -9 * +killall * +``` + +These patterns prevent dangerous commands whose blast radius escapes the throwaway worktree. File-mutating commands (`rm -rf`, `git reset --hard`, etc.) are intentionally omitted because they only affect the disposable worktree. + +You can customize the deny list by adding or removing glob patterns. One pattern per line. Changes apply to all future runs of that schedule. + ## Run History Each schedule stores a run history panel with: diff --git a/docs/features/server-health.md b/docs/features/server-health.md new file mode 100644 index 00000000..730f92bb --- /dev/null +++ b/docs/features/server-health.md @@ -0,0 +1,76 @@ +# OpenCode Server Health & Restart + +Monitor the managed OpenCode server's status and control restarts and upgrades from the Settings UI. + +## Overview + +OpenCode Manager runs a supervised OpenCode server process to handle agent sessions. The **OpenCode** tab in Settings shows the server's current status, version information, and provides controls for restarting or upgrading the server without bringing down the Manager itself. + +![Server Health and Status](../images/server-health-status.png) + +## Server Status + +| Indicator | Meaning | +|-----------|---------| +| **Healthy** | The OpenCode server is running and responding to health checks | +| **Unhealthy** | The server is not responding. The Manager will attempt automatic recovery. | +| **Starting** | The server is being initialized after a restart or Manager startup | + +The panel also displays: + +- **OpenCode version** — The installed version of the OpenCode server (e.g., `v1.17.11`) +- **Manager version** — The current OpenCode Manager version (e.g., `v0.14.5`) + +## Health Monitoring + +The Manager periodically polls the OpenCode server's health endpoint. If the server becomes unresponsive: + +1. The Manager logs the failure and increments a failure counter +2. After a configurable number of consecutive failures (default: 2), automatic recovery begins +3. Recovery restarts the OpenCode server process +4. In-flight sessions are aborted and resumed once the server is healthy again + +### Configuration + +Health monitoring is configured through environment variables: + +| Variable | Default | Description | +|----------|---------|-------------| +| `OPENCODE_HEALTH_WATCH_ENABLED` | `true` | Enable health watcher and recovery (`false` in tests) | +| `OPENCODE_HEALTH_POLL_MS` | `30000` | Poll interval in milliseconds | +| `OPENCODE_HEALTH_FAILURE_THRESHOLD` | `2` | Failed checks before recovery starts | + +## Restart with Session Resume + +When you restart the OpenCode server (manually or through an upgrade), active sessions are handled gracefully: + +1. **Capture** — The Manager captures all active user sessions (excluding subagent and scheduled-run sessions) +2. **Abort** — Active sessions are aborted cleanly on the running server +3. **Restart** — The OpenCode server process is stopped and started fresh +4. **Resume** — Once healthy, a `continue` prompt is automatically sent to each previously active session + +### Confirmation + +If there are active sessions when you click **Restart**, a confirmation dialog shows how many sessions will be interrupted. You can proceed or cancel. + +## Upgrading OpenCode + +Click **Update** to check for and install the latest OpenCode version. The process: + +1. Checks the currently installed version against the latest available release +2. Downloads and installs the update if available +3. Restarts the server using the same session-resume flow described above +4. The new version is displayed in the status panel after restart + +If the upgrade fails but the server recovers to a usable state, a recovery notice is shown with the fallback version. + +## Manual Restart Triggers + +Besides the explicit **Restart** button, the server is automatically restarted when: + +- **OpenCode configuration is saved** — Changes to models, agents, commands, or MCP servers that require a server restart +- **Assistant workspace is reloaded** — Via the `POST /assistant/reload` internal API endpoint +- **Config import completes** — Importing a standalone OpenCode config into the workspace +- **Version upgrade** — After installing a new OpenCode version + +Configuration changes that only affect non-process settings (e.g., environment variable passthrough, AGENTS.md) use a non-disruptive config reload instead, which does not interrupt active sessions. diff --git a/docs/features/session-pins.md b/docs/features/session-pins.md new file mode 100644 index 00000000..7056ee9b --- /dev/null +++ b/docs/features/session-pins.md @@ -0,0 +1,41 @@ +# Session Pinning + +Pin important sessions to the top of your session list so you can find them quickly without searching. + +## Overview + +Session pinning lets you mark any session as "pinned" — it moves to a dedicated **Pinned** section above your **Recent** sessions, regardless of how old it is. This is useful for: + +- Active feature branches you switch between throughout the day +- Long-running investigations or debugging sessions +- Sessions with important context you want to keep accessible + +## Pinning a Session + +Each session card has an actions menu (three dots or swipe gesture); the first entry toggles pinning: + +![Session List with Pinned Section](../images/session-pins-list.png) + +The pinned session appears in a **Pinned** section above the **Recent** section. Unpinned sessions stay in **Recent** sorted by last activity. + +![Pin/Unpin Dropdown](../images/session-pin-dropdown.png) + +Pin state persists across page reloads and browser sessions. Pinned sessions remain at the top until you unpin them. + +## Managing Pins + +| Action | How | +|--------|-----| +| **Pin a session** | Open the session actions menu and select **Pin to top** | +| **Unpin a session** | Open the session actions menu and select **Unpin** — it moves back to the Recent section | +| **Bulk operations** | Pin/unpin is per-session. Bulk delete and other management tools work as normal on pinned sessions | + +## What Happens When a Pinned Session is Deleted + +If a pinned session is deleted (manually or by context cleanup), it is removed from the Pinned section automatically. No stale pin entries remain. + +## Notes + +- Pinning is independent of session activity — a pinned session stays pinned even when new sessions push older ones out of the Recent view. +- The Pinned section supports any number of pinned sessions. +- Pinning is per-user and stored server-side, so it follows you across devices. diff --git a/docs/features/skills.md b/docs/features/skills.md index 2772f317..1bf79342 100644 --- a/docs/features/skills.md +++ b/docs/features/skills.md @@ -40,7 +40,9 @@ Skill names must match the pattern `^[a-z0-9]+(-[a-z0-9]+)*$`: ## Managing Skills -Skills are managed through the Settings UI under the Skills section, or via the API. +Skills are managed per-repository through the Skills panel in the sidebar, or via the API. + +![Skills Manager](../images/skills-manager.png) ### API Endpoints diff --git a/docs/features/stt.md b/docs/features/stt.md index bb8c85ea..c05ba8b9 100644 --- a/docs/features/stt.md +++ b/docs/features/stt.md @@ -6,6 +6,8 @@ Dictate messages to AI agents using voice input. OpenCode Manager supports two STT providers: +![STT Settings](../images/stt-settings.png) + 1. **Built-in Browser** - Uses your browser's Web Speech API 2. **External API** - OpenAI-compatible STT endpoints (Whisper) diff --git a/docs/features/tts.md b/docs/features/tts.md index 7f886254..e12fc6ce 100644 --- a/docs/features/tts.md +++ b/docs/features/tts.md @@ -6,6 +6,8 @@ Listen to AI responses with built-in or external TTS. OpenCode Manager supports two TTS providers: +![TTS Settings](../images/tts-settings.png) + 1. **Built-in Browser** - Uses your browser's Web Speech API 2. **External API** - OpenAI-compatible TTS endpoints diff --git a/docs/images/ai-config-providers.png b/docs/images/ai-config-providers.png new file mode 100644 index 00000000..8d4cfab4 Binary files /dev/null and b/docs/images/ai-config-providers.png differ diff --git a/docs/images/assistant-page.png b/docs/images/assistant-page.png new file mode 100644 index 00000000..474f15fe Binary files /dev/null and b/docs/images/assistant-page.png differ diff --git a/docs/images/chat-conversation.png b/docs/images/chat-conversation.png new file mode 100644 index 00000000..452ad901 Binary files /dev/null and b/docs/images/chat-conversation.png differ diff --git a/docs/images/chat-session-list.png b/docs/images/chat-session-list.png new file mode 100644 index 00000000..fc91829c Binary files /dev/null and b/docs/images/chat-session-list.png differ diff --git a/docs/images/file-browser.png b/docs/images/file-browser.png new file mode 100644 index 00000000..d44a6ce4 Binary files /dev/null and b/docs/images/file-browser.png differ diff --git a/docs/images/mcp-servers-list.png b/docs/images/mcp-servers-list.png new file mode 100644 index 00000000..5fadba36 Binary files /dev/null and b/docs/images/mcp-servers-list.png differ diff --git a/docs/images/mobile-sessions.png b/docs/images/mobile-sessions.png new file mode 100644 index 00000000..96da2655 Binary files /dev/null and b/docs/images/mobile-sessions.png differ diff --git a/docs/images/notifications-settings.png b/docs/images/notifications-settings.png new file mode 100644 index 00000000..6a9fc183 Binary files /dev/null and b/docs/images/notifications-settings.png differ diff --git a/docs/images/preview-chat-page.png b/docs/images/preview-chat-page.png new file mode 100644 index 00000000..0634deda Binary files /dev/null and b/docs/images/preview-chat-page.png differ diff --git a/docs/images/preview-files-page.png b/docs/images/preview-files-page.png new file mode 100644 index 00000000..24792154 Binary files /dev/null and b/docs/images/preview-files-page.png differ diff --git a/docs/images/preview-mcp-page.png b/docs/images/preview-mcp-page.png new file mode 100644 index 00000000..adeb1b3a Binary files /dev/null and b/docs/images/preview-mcp-page.png differ diff --git a/docs/images/preview-notifications-page.png b/docs/images/preview-notifications-page.png new file mode 100644 index 00000000..4b382a12 Binary files /dev/null and b/docs/images/preview-notifications-page.png differ diff --git a/docs/images/preview-tts-page.png b/docs/images/preview-tts-page.png new file mode 100644 index 00000000..bfe3a81e Binary files /dev/null and b/docs/images/preview-tts-page.png differ diff --git a/docs/images/schedule-permissions.png b/docs/images/schedule-permissions.png new file mode 100644 index 00000000..8a5ab362 Binary files /dev/null and b/docs/images/schedule-permissions.png differ diff --git a/docs/images/schedule-skills-tab.png b/docs/images/schedule-skills-tab.png new file mode 100644 index 00000000..3eba1534 Binary files /dev/null and b/docs/images/schedule-skills-tab.png differ diff --git a/docs/images/schedules/09-schedule-creation.png b/docs/images/schedules/09-schedule-creation.png index d2ecda70..8f6aef3a 100644 Binary files a/docs/images/schedules/09-schedule-creation.png and b/docs/images/schedules/09-schedule-creation.png differ diff --git a/docs/images/schedules/10-timing-options.png b/docs/images/schedules/10-timing-options.png index fd9e2d0a..56605d36 100644 Binary files a/docs/images/schedules/10-timing-options.png and b/docs/images/schedules/10-timing-options.png differ diff --git a/docs/images/schedules/11-run-history-view.png b/docs/images/schedules/11-run-history-view.png index 8f6dcee2..41cb70e4 100644 Binary files a/docs/images/schedules/11-run-history-view.png and b/docs/images/schedules/11-run-history-view.png differ diff --git a/docs/images/server-health-status.png b/docs/images/server-health-status.png new file mode 100644 index 00000000..8e926ad2 Binary files /dev/null and b/docs/images/server-health-status.png differ diff --git a/docs/images/session-pin-dropdown.png b/docs/images/session-pin-dropdown.png new file mode 100644 index 00000000..e45b0ab7 Binary files /dev/null and b/docs/images/session-pin-dropdown.png differ diff --git a/docs/images/session-pins-list.png b/docs/images/session-pins-list.png new file mode 100644 index 00000000..da64b8c8 Binary files /dev/null and b/docs/images/session-pins-list.png differ diff --git a/docs/images/skills-manager.png b/docs/images/skills-manager.png new file mode 100644 index 00000000..a3ec715b Binary files /dev/null and b/docs/images/skills-manager.png differ diff --git a/docs/images/stt-settings.png b/docs/images/stt-settings.png new file mode 100644 index 00000000..3a290f1d Binary files /dev/null and b/docs/images/stt-settings.png differ diff --git a/docs/images/tts-settings.png b/docs/images/tts-settings.png new file mode 100644 index 00000000..9fe43147 Binary files /dev/null and b/docs/images/tts-settings.png differ diff --git a/docs/index.md b/docs/index.md index 949d1c5a..00c78ada 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,10 +1,15 @@ +--- +hide: + - toc +--- + # OpenCode Manager Mobile-first web interface for [OpenCode](https://opencode.ai) AI agents. Manage, control, and code from any device - your phone, tablet, or desktop.

- OpenCode Manager - Mobile view + OpenCode Manager + Mobile view

## Quick Start @@ -46,8 +51,10 @@ OpenCode Manager runs as a pnpm workspace: - **Chat & Sessions** — Real-time SSE streaming, slash commands, `@file` mentions, Plan/Build modes, Mermaid diagrams — [Learn more](features/chat.md) - **Files** — Directory browser with tree view, syntax highlighting, create/rename/delete, ZIP download — [Learn more](features/files.md) - **Schedules** — Recurring repo jobs with reusable prompts, run history, linked sessions — [Learn more](features/schedules.md) +- **Session Pinning** — Pin important sessions to the top of the session list — [Learn more](features/session-pins.md) - **Assistant Mode** — Dedicated AI workspace with auto-provisioned skills for schedule management, notifications, settings, and repo listing — [Learn more](features/assistant-mode.md) - **AI Configuration** — Model/provider setup, OAuth for Anthropic/GitHub Copilot, custom agents — [Learn more](features/ai-config.md) +- **Server Health & Restart** — Monitor server status, graceful restarts with session resume, auto-recovery — [Learn more](features/server-health.md) - **MCP Servers** — Add local or remote MCP servers with OAuth support — [Learn more](features/mcp.md) - **Skills** — Skill support for extended agent capabilities — [Learn more](features/skills.md) - **Mobile & PWA** — Responsive UI, installable on any device, iOS-optimized — [Learn more](features/mobile.md) diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css index b5985be3..9584f19b 100644 --- a/docs/stylesheets/extra.css +++ b/docs/stylesheets/extra.css @@ -132,10 +132,29 @@ } .md-typeset img { - max-width: 600px; - max-height: 800px; + max-width: 100%; height: auto; - object-fit: contain; + border-radius: 8px; + box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.3); +} + +.md-typeset img.phone { + max-width: 300px; +} + +.md-typeset img.hero { + border-radius: 0; + box-shadow: none; +} + +.md-typeset img.hero-desktop { + width: 100%; + max-width: 1100px; + max-height: none; +} + +.md-typeset img.hero-mobile { + margin-left: 12px; } @keyframes progress { diff --git a/frontend/src/api/sessionPins.test.ts b/frontend/src/api/sessionPins.test.ts new file mode 100644 index 00000000..bb289f92 --- /dev/null +++ b/frontend/src/api/sessionPins.test.ts @@ -0,0 +1,63 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { listSessionPins, toggleSessionPin } from './sessionPins' + +describe('sessionPins', () => { + const fetchMock = vi.fn() + + beforeEach(() => { + fetchMock.mockReset() + vi.stubGlobal('fetch', fetchMock) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + describe('listSessionPins', () => { + it('calls GET /api/session-pins and returns pins array', async () => { + const expectedPins = [ + { sessionId: 's1', directory: '/a', pinnedAt: 100 }, + { sessionId: 's2', directory: '/b', pinnedAt: 200 }, + ] + fetchMock.mockResolvedValue( + new Response(JSON.stringify({ pins: expectedPins }), { status: 200 }), + ) + + const result = await listSessionPins() + + expect(result).toEqual(expectedPins) + + const callUrl = fetchMock.mock.calls[0][0] + expect(callUrl).toEqual(expect.stringContaining('/api/session-pins')) + + const callOptions = fetchMock.mock.calls[0][1] + expect(callOptions.method).toBeUndefined() + }) + }) + + describe('toggleSessionPin', () => { + it('calls PUT /api/session-pins with JSON body and returns pins', async () => { + const input = { sessionId: 's1', directory: '/a', pinned: true } + const expectedPins = [ + { sessionId: 's1', directory: '/a', pinnedAt: 100 }, + ] + fetchMock.mockResolvedValue( + new Response(JSON.stringify({ pins: expectedPins }), { status: 200 }), + ) + + const result = await toggleSessionPin(input) + + expect(result).toEqual(expectedPins) + + const callUrl = fetchMock.mock.calls[0][0] + expect(callUrl).toEqual(expect.stringContaining('/api/session-pins')) + + const callOptions = fetchMock.mock.calls[0][1] + expect(callOptions.method).toBe('PUT') + expect(callOptions.headers['Content-Type']).toBe('application/json') + + const body = JSON.parse(callOptions.body) + expect(body).toEqual(input) + }) + }) +}) diff --git a/frontend/src/api/sessionPins.ts b/frontend/src/api/sessionPins.ts new file mode 100644 index 00000000..5fff4bb3 --- /dev/null +++ b/frontend/src/api/sessionPins.ts @@ -0,0 +1,17 @@ +import { fetchWrapper } from './fetchWrapper' +import { API_BASE_URL } from '@/config' +import type { SessionPin, ToggleSessionPinRequest } from '@opencode-manager/shared/schemas' + +export async function listSessionPins(): Promise { + const res = await fetchWrapper<{ pins: SessionPin[] }>(`${API_BASE_URL}/api/session-pins`) + return res.pins +} + +export async function toggleSessionPin(input: ToggleSessionPinRequest): Promise { + const res = await fetchWrapper<{ pins: SessionPin[] }>(`${API_BASE_URL}/api/session-pins`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(input), + }) + return res.pins +} diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts index 4960c310..3c3fb7dc 100644 --- a/frontend/src/api/settings.ts +++ b/frontend/src/api/settings.ts @@ -15,9 +15,12 @@ import type { InstallSkillResponse, OpenCodeDirectoryFileInfo, } from './types/settings' +import type { ManagerUpgradeJob, ManagerUpgradeStatusResponse } from '@opencode-manager/shared/types' import { API_BASE_URL } from '@/config' import { fetchWrapper, FetchError } from './fetchWrapper' +export type { ManagerUpgradeJob, ManagerUpgradeStatusResponse } + const DEFAULT_USER_ID = 'default' function appendFilesWithManifest(formData: FormData, files: File[]): void { @@ -152,6 +155,10 @@ export const settingsApi = { }) }, + getActiveOpenCodeSessions: async (): Promise<{ count: number; sessions: { sessionID: string; directory: string }[] }> => { + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-active-sessions`) + }, + reloadOpenCodeConfig: async (): Promise<{ success: boolean; message: string; details?: string }> => { try { return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-reload`, { @@ -378,7 +385,7 @@ export const settingsApi = { }) }, - getManagerUpgradeStatus: async (): Promise => { + getManagerUpgradeStatus: async (): Promise => { return fetchWrapper(`${API_BASE_URL}/api/manager-upgrade/status`) }, @@ -430,24 +437,4 @@ export async function rotateManagerToken(): Promise { }) } -export type ManagerUpgradeJobStatus = 'pending' | 'pulling' | 'recreating' | 'completed' | 'failed' -export interface ManagerUpgradeJob { - id: number - status: ManagerUpgradeJobStatus - fromVersion: string | null - toVersion: string | null - targetImage: string | null - error: string | null - startedAt: number - finishedAt: number | null -} - -export interface ManagerUpgradeStatus { - supported: boolean - inDocker: boolean - socketAvailable: boolean - enabled: boolean - currentVersion: string | null - job: ManagerUpgradeJob | null -} diff --git a/frontend/src/components/schedules/GeneralTab.tsx b/frontend/src/components/schedules/GeneralTab.tsx index f666eb04..b3be2af0 100644 --- a/frontend/src/components/schedules/GeneralTab.tsx +++ b/frontend/src/components/schedules/GeneralTab.tsx @@ -2,6 +2,7 @@ import { Combobox, type ComboboxOption } from '@/components/ui/combobox' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Switch } from '@/components/ui/switch' +import { Textarea } from '@/components/ui/textarea' import { TabsContent } from '@/components/ui/tabs' import { Info } from 'lucide-react' @@ -27,6 +28,10 @@ type GeneralTabProps = { repoId?: number onRepoChange?: (repoId: number | undefined) => void repoOptions: ComboboxOption[] + allowExternalDirectory: boolean + onAllowExternalDirectoryChange: (value: boolean) => void + bashDenyPatterns: string[] + onBashDenyPatternsChange: (value: string[]) => void } function InfoHint({ text }: { text: string }) { @@ -63,6 +68,10 @@ export function GeneralTab({ repoId, onRepoChange, repoOptions, + allowExternalDirectory, + onAllowExternalDirectoryChange, + bashDenyPatterns, + onBashDenyPatternsChange, }: GeneralTabProps) { return ( @@ -157,6 +166,37 @@ export function GeneralTab({ /> + +
+

Permissions

+
+
+
+

Allow access outside the working directory

+ +
+ +
+
+
+
+
+ + +
+