Merge branch 'main' into feat/docker-self-upgrade

Resolve conflicts against the restart-coordinator rewrite and renumber
the manager-upgrade-jobs migration from 16 to 19 to avoid colliding
with main's 016-018 migrations. Includes review fixes: background the
docker pull, add a staleness guard for stuck recreating jobs, move
manager-upgrade types to @opencode-manager/shared, wire the
active-session pre-check dialog into the Upgrade Manager button, and
surface upgrade errors via FetchError-aware messaging.
This commit is contained in:
Chris Scott committed 2026-07-04 10:36:01 -04:00
commit 9effe53bdc
125 files changed
+3899 -975

No files matched your search

+29 -19
View File
@@ -10,9 +10,11 @@ import {
getActiveUpgradeJob,
} from '../db/manager-upgrade'
import type { ManagerUpgradeJob } from '../db/manager-upgrade'
import type { ManagerUpgradeStatusResponse } from '@opencode-manager/shared/types'
const RECREATE_STALE_MS = 10 * 60 * 1000
export interface SelfContainerInfo {
containerId: string
project: string
service: string
workingDir: string
@@ -95,14 +97,19 @@ export class ManagerUpgradeService {
}
}
async getStatus(): Promise<{
supported: boolean
inDocker: boolean
socketAvailable: boolean
enabled: boolean
currentVersion: string | null
job: ManagerUpgradeJob | null
}> {
private expireStaleRecreatingJob(): void {
const active = getActiveUpgradeJob(this.db)
if (active?.status === 'recreating' && Date.now() - active.startedAt > RECREATE_STALE_MS) {
updateUpgradeJob(this.db, active.id, {
status: 'failed',
error: 'recreate helper did not complete in time',
finishedAt: Date.now(),
})
}
}
async getStatus(): Promise<ManagerUpgradeStatusResponse> {
this.expireStaleRecreatingJob()
const cap = this.deps.capability()
const currentVersion = await this.deps.getCurrentVersion()
return {
@@ -126,6 +133,8 @@ export class ManagerUpgradeService {
)
}
this.expireStaleRecreatingJob()
// Check for an existing active job before any async Docker/version calls.
// This prevents a hung inspectSelf() from blocking the 409 response.
const activeEarly = getActiveUpgradeJob(this.db)
@@ -147,31 +156,33 @@ export class ManagerUpgradeService {
}
const job = insertUpgradeJob(this.db, {
status: 'pending',
status: 'pulling',
fromVersion: currentVersion ?? undefined,
toVersion: resolvedTag,
targetImage,
startedAt: Date.now(),
})
updateUpgradeJob(this.db, job.id, { status: 'pulling' })
// The pull can take minutes; run it detached so the HTTP request returns
// immediately and progress/failure is surfaced via the polled job status.
void this.pullAndRecreate(job.id, info, targetImage)
return job
}
private async pullAndRecreate(jobId: number, info: SelfContainerInfo, targetImage: string): Promise<void> {
try {
await this.deps.runner.pull(targetImage)
updateUpgradeJob(this.db, jobId, { status: 'recreating' })
this.deps.runner.spawnRecreate(info, targetImage)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
updateUpgradeJob(this.db, job.id, {
updateUpgradeJob(this.db, jobId, {
status: 'failed',
error: message,
finishedAt: Date.now(),
})
throw new ManagerUpgradeError(message, 500)
}
updateUpgradeJob(this.db, job.id, { status: 'recreating' })
this.deps.runner.spawnRecreate(info, targetImage)
return getLatestUpgradeJob(this.db) as ManagerUpgradeJob
}
}
@@ -199,7 +210,6 @@ export function createDockerRunner(): DockerRunner {
const labels: Record<string, string> = JSON.parse(labelsJson)
return {
containerId,
project: labels['com.docker.compose.project'] || '',
service: labels['com.docker.compose.service'] || '',
workingDir: labels['com.docker.compose.project.working_dir'] || '',
@@ -0,0 +1,315 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { OpenCodeRestartCoordinator, type ActiveSessionsProvider, type ResumableSession } from './opencode-restart-coordinator'
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
import type { OpenCodeClient } from './opencode/client'
vi.mock('../../src/utils/logger', () => ({
logger: {
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
}))
function createFakeActiveSessionsProvider(overrides: Partial<ActiveSessionsProvider> = {}): ActiveSessionsProvider {
return {
getActiveSessions: vi.fn(() => ({})),
isSubagentSession: vi.fn(() => false),
getScheduledSessionIds: vi.fn(() => new Set<string>()),
...overrides,
}
}
describe('OpenCodeRestartCoordinator', () => {
let client: OpenCodeClient
let activeSessions: ActiveSessionsProvider
let coordinator: OpenCodeRestartCoordinator
beforeEach(() => {
client = createStubOpenCodeClient()
activeSessions = createFakeActiveSessionsProvider()
coordinator = new OpenCodeRestartCoordinator(client, activeSessions)
})
describe('captureResumableSessions', () => {
it('excludes subagent sessions', () => {
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
'/a': ['s1', 'sub1'],
'/b': ['s2'],
})
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id === 'sub1')
const result = coordinator.captureResumableSessions()
expect(result).toEqual([
{ sessionID: 's1', directory: '/a' },
{ sessionID: 's2', directory: '/b' },
])
})
it('returns empty array when no active sessions', () => {
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({})
const result = coordinator.captureResumableSessions()
expect(result).toEqual([])
})
it('filters out only subagent sessions, keeps all others', () => {
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
'/x': ['a1', 'a2', 'sub_x'],
})
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id.startsWith('sub_'))
const result = coordinator.captureResumableSessions()
expect(result).toEqual([
{ sessionID: 'a1', directory: '/x' },
{ sessionID: 'a2', directory: '/x' },
])
})
it('excludes scheduled sessions', () => {
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
'/a': ['s1', 'sched1'],
})
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched1']))
const result = coordinator.captureResumableSessions()
expect(result).toEqual([{ sessionID: 's1', directory: '/a' }])
})
it('excludes both subagent and scheduled sessions simultaneously', () => {
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
'/p': ['manual', 'sub', 'sched'],
})
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id === 'sub')
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched']))
const result = coordinator.captureResumableSessions()
expect(result).toEqual([{ sessionID: 'manual', directory: '/p' }])
})
})
describe('runWithResume', () => {
it('aborts captured sessions, restarts, then resumes when healthy', async () => {
const events: string[] = []
const forward = vi.mocked(client.forward)
forward.mockImplementation(async (opts) => {
events.push(`forward:${opts.path}`)
return new Response(null, { status: 200 })
})
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
'/a': ['s1'],
'/b': ['s2'],
})
const restart = vi.fn(async () => {
events.push('restart')
return true
})
const result = await coordinator.runWithResume(restart)
// Assert interleaved ordering: aborts → restart → resumes
expect(events).toEqual([
'forward:/session/s1/abort',
'forward:/session/s2/abort',
'restart',
'forward:/session/s1/prompt_async',
'forward:/session/s2/prompt_async',
])
// Aborts called first for both sessions
expect(forward).toHaveBeenNthCalledWith(1, {
method: 'POST',
path: '/session/s1/abort',
directory: '/a',
})
expect(forward).toHaveBeenNthCalledWith(2, {
method: 'POST',
path: '/session/s2/abort',
directory: '/b',
})
expect(restart).toHaveBeenCalledOnce()
// Forward was called 4 times: 2 aborts (calls 1-2) + 2 resumes (calls 3-4)
expect(forward).toHaveBeenCalledTimes(4)
expect(forward).toHaveBeenNthCalledWith(3, {
method: 'POST',
path: '/session/s1/prompt_async',
directory: '/a',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
})
expect(forward).toHaveBeenNthCalledWith(4, {
method: 'POST',
path: '/session/s2/prompt_async',
directory: '/b',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
})
expect(result).toEqual({ healthy: true, resumedSessionIDs: ['s1', 's2'] })
})
it('does NOT resume when restart returns unhealthy', async () => {
const forward = vi.mocked(client.forward)
forward.mockResolvedValue(new Response(null, { status: 200 }))
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
'/a': ['s1'],
})
const restart = vi.fn(async () => false)
const result = await coordinator.runWithResume(restart)
// Aborts still happen
expect(forward).toHaveBeenNthCalledWith(1, {
method: 'POST',
path: '/session/s1/abort',
directory: '/a',
})
expect(restart).toHaveBeenCalledOnce()
// No prompt_async calls
const promptAsyncCalls = forward.mock.calls.filter(
(call: unknown[]) => (call[0] as { path: string }).path.includes('prompt_async'),
)
expect(promptAsyncCalls).toHaveLength(0)
expect(result).toEqual({ healthy: false, resumedSessionIDs: [] })
})
it('with no active sessions performs restart only', async () => {
const forward = vi.mocked(client.forward)
forward.mockResolvedValue(new Response(null, { status: 200 }))
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({})
const restart = vi.fn(async () => true)
const result = await coordinator.runWithResume(restart)
expect(restart).toHaveBeenCalledOnce()
expect(forward).not.toHaveBeenCalled()
expect(result).toEqual({ healthy: true, resumedSessionIDs: [] })
})
it('does not abort or resume scheduled sessions', async () => {
const forward = vi.mocked(client.forward)
forward.mockResolvedValue(new Response(null, { status: 200 }))
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
'/a': ['manual1', 'sched1'],
})
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched1']))
const restart = vi.fn(async () => true)
const result = await coordinator.runWithResume(restart)
// Only manual1 should be aborted and resumed — 2 forward calls total
expect(forward).toHaveBeenCalledTimes(2)
expect(forward).toHaveBeenNthCalledWith(1, {
method: 'POST',
path: '/session/manual1/abort',
directory: '/a',
})
expect(forward).toHaveBeenNthCalledWith(2, {
method: 'POST',
path: '/session/manual1/prompt_async',
directory: '/a',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
})
expect(result).toEqual({ healthy: true, resumedSessionIDs: ['manual1'] })
})
it('is best-effort: per-session errors are swallowed and other sessions still processed', async () => {
const forward = vi.mocked(client.forward)
// Aborts all succeed, but resume for s2 fails
forward
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s1
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s2
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s3
.mockResolvedValueOnce(new Response(null, { status: 200 })) // resume s1
.mockRejectedValueOnce(new Error('connection refused')) // resume s2 fails
.mockResolvedValueOnce(new Response(null, { status: 200 })) // resume s3
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
'/a': ['s1', 's2', 's3'],
})
const restart = vi.fn(async () => true)
const result = await coordinator.runWithResume(restart)
expect(result.healthy).toBe(true)
expect(result.resumedSessionIDs).toEqual(['s1', 's3'])
})
})
describe('abortSessions', () => {
it('does not throw when forward rejects and continues processing remaining sessions', async () => {
const forward = vi.mocked(client.forward)
forward
.mockRejectedValueOnce(new Error('timeout'))
.mockResolvedValueOnce(new Response(null, { status: 200 }))
await expect(
coordinator.abortSessions([
{ sessionID: 's1', directory: '/a' },
{ sessionID: 's2', directory: '/b' },
]),
).resolves.toBeUndefined()
expect(forward).toHaveBeenCalledTimes(2)
expect(forward).toHaveBeenNthCalledWith(1, {
method: 'POST',
path: '/session/s1/abort',
directory: '/a',
})
expect(forward).toHaveBeenNthCalledWith(2, {
method: 'POST',
path: '/session/s2/abort',
directory: '/b',
})
})
})
describe('resumeSessions', () => {
it('only includes sessions with ok response', async () => {
const forward = vi.mocked(client.forward)
forward
.mockResolvedValueOnce(new Response(null, { status: 200 }))
.mockResolvedValueOnce(new Response(null, { status: 404 }))
.mockResolvedValueOnce(new Response(null, { status: 200 }))
const sessions: ResumableSession[] = [
{ sessionID: 's1', directory: '/a' },
{ sessionID: 's2', directory: '/b' },
{ sessionID: 's3', directory: '/c' },
]
const result = await coordinator.resumeSessions(sessions)
expect(result).toEqual(['s1', 's3'])
})
it('does not throw when forward rejects', async () => {
vi.mocked(client.forward).mockRejectedValue(new Error('timeout'))
const result = await coordinator.resumeSessions([{ sessionID: 's1', directory: '/a' }])
expect(result).toEqual([])
})
})
})
@@ -0,0 +1,89 @@
import { logger } from '../utils/logger'
import type { OpenCodeClient } from './opencode/client'
export interface ActiveSessionsProvider {
getActiveSessions(): Record<string, string[]>
isSubagentSession(sessionId: string): boolean
getScheduledSessionIds(): Set<string>
}
export interface ResumableSession {
sessionID: string
directory: string
}
export interface RestartWithResumeResult {
healthy: boolean
resumedSessionIDs: string[]
}
export class OpenCodeRestartCoordinator {
constructor(
private readonly client: OpenCodeClient,
private readonly activeSessions: ActiveSessionsProvider,
) {}
captureResumableSessions(): ResumableSession[] {
const active = this.activeSessions.getActiveSessions()
const scheduled = this.activeSessions.getScheduledSessionIds()
const sessions: ResumableSession[] = []
for (const [directory, sessionIDs] of Object.entries(active)) {
for (const sessionID of sessionIDs) {
if (!this.activeSessions.isSubagentSession(sessionID) && !scheduled.has(sessionID)) {
sessions.push({ sessionID, directory })
}
}
}
return sessions
}
async abortSessions(sessions: ResumableSession[]): Promise<void> {
await Promise.allSettled(
sessions.map(async (s) => {
try {
await this.client.forward({
method: 'POST',
path: `/session/${s.sessionID}/abort`,
directory: s.directory,
})
} catch (error) {
logger.warn(`Failed to abort session ${s.sessionID}: ${error}`)
}
}),
)
}
async resumeSessions(sessions: ResumableSession[]): Promise<string[]> {
const results = await Promise.allSettled(
sessions.map(async (s) => {
try {
const response = await this.client.forward({
method: 'POST',
path: `/session/${s.sessionID}/prompt_async`,
directory: s.directory,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
})
return response.ok ? s.sessionID : null
} catch (error) {
logger.warn(`Failed to resume session ${s.sessionID}: ${error}`)
return null
}
}),
)
return results
.map((result) => (result.status === 'fulfilled' ? result.value : null))
.filter((sessionID): sessionID is string => sessionID !== null)
}
async runWithResume(restart: () => Promise<boolean>): Promise<RestartWithResumeResult> {
const sessions = this.captureResumableSessions()
await this.abortSessions(sessions)
const healthy = await restart()
const resumedSessionIDs = healthy ? await this.resumeSessions(sessions) : []
return { healthy, resumedSessionIDs }
}
}
+62
View File
@@ -0,0 +1,62 @@
import { opencodeServerManager } from './opencode-single-server'
import type { OpenCodeSupervisor } from './opencode-supervisor'
import type { OpenCodeRestartCoordinator } from './opencode-restart-coordinator'
let restartCoordinator: OpenCodeRestartCoordinator | null = null
/**
* Registers the process-wide restart coordinator so every restart path can
* abort and resume in-flight sessions consistently. Passing null disables
* resume (used by tests and pre-initialization paths).
*/
export function setOpenCodeRestartCoordinator(coordinator: OpenCodeRestartCoordinator | null): void {
restartCoordinator = coordinator
}
export function getOpenCodeRestartCoordinator(): OpenCodeRestartCoordinator | null {
return restartCoordinator
}
async function performRestart(supervisor?: OpenCodeSupervisor): Promise<boolean> {
if (supervisor) {
return (await supervisor.restart('settings_restart')).healthy
}
opencodeServerManager.clearStartupError()
await opencodeServerManager.restart()
return opencodeServerManager.checkHealth()
}
/**
* The single entry point for restarting the OpenCode server. Every restart
* trigger (manual restart, version upgrade/install, workspace config change,
* restart-sensitive config saves) routes through here so that interrupted user
* sessions are aborted and resumed uniformly when a coordinator is registered.
* A full process restart drops in-flight sessions; resuming re-issues a
* "continue" prompt once the server is healthy again.
*/
export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<{ resumedSessionIDs: string[] }> {
if (restartCoordinator) {
const result = await restartCoordinator.runWithResume(() => performRestart(supervisor))
return { resumedSessionIDs: result.resumedSessionIDs }
}
if (supervisor) {
await supervisor.restart('settings_restart')
} else {
opencodeServerManager.clearStartupError()
await opencodeServerManager.restart()
}
return { resumedSessionIDs: [] }
}
/**
* Reloads OpenCode configuration via the non-disruptive API patch. This does
* NOT drop the server process, so active sessions keep running and there is
* nothing to resume.
*/
export async function reloadOpenCodeConfig(supervisor?: OpenCodeSupervisor): Promise<void> {
if (supervisor) {
await supervisor.reloadConfig('settings_reload')
return
}
await opencodeServerManager.reloadConfig()
}
+13
View File
@@ -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
+4
View File
@@ -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,
}
+130 -26
View File
@@ -7,6 +7,7 @@ import type { Repo } from '../types/repo'
import type { GitAuthService } from './git-auth'
import type { SettingsService } from './settings'
import type { CredentialProvider } from './credential-provider'
import type { OpenCodeClient } from './opencode/client'
import { resolveGitIdentity, createGitIdentityEnv, isSSHUrl } from '../utils/git-auth'
import { executeCommand } from '../utils/process'
import { resolveDefaultBranch, createWorktreeSafely, removeWorktree } from './repo'
@@ -16,6 +17,7 @@ export interface ScheduleWorktreeContext {
directory: string
worktreePath: string
runBranch: string
workspaceId: string | null
}
/**
@@ -29,12 +31,19 @@ export function buildRepoEnvForRepo(repo: { id?: number; fullPath: string }): Re
}
}
interface OpenCodeWorkspace {
id: string
directory: string
branch: string | null
}
export class ScheduleWorktreeManager {
constructor(
private readonly gitAuthService: GitAuthService,
private readonly settingsService: SettingsService,
private readonly credentialProvider: CredentialProvider,
private readonly db: Database,
private readonly openCodeClient: OpenCodeClient,
) {}
async prepare(
@@ -68,17 +77,52 @@ export class ScheduleWorktreeManager {
}
const runBranch = `schedule/${job.id}/run-${runId}`
// Attempt OpenCode workspace API; fall back to raw git worktree on failure
let createdWorkspace: OpenCodeWorkspace | null = null
try {
createdWorkspace = await this.openCodeClient.postJson<OpenCodeWorkspace>(
'/experimental/workspace',
{ type: 'worktree', branch: null },
{ directory: repo.fullPath },
)
// Re-point the workspace to our run branch and base
await executeCommand(['git', '-C', createdWorkspace.directory, 'checkout', '-B', runBranch, baseRef], { env })
if (!existsSync(createdWorkspace.directory)) {
throw new Error(`OpenCode workspace directory was not created at: ${createdWorkspace.directory}`)
}
return {
directory: createdWorkspace.directory,
worktreePath: createdWorkspace.directory,
runBranch,
workspaceId: createdWorkspace.id,
}
} catch (apiError) {
logger.warn(`OpenCode workspace API failed, falling back to raw git worktree: ${apiError}`)
// Best-effort cleanup of created workspace if checkout/setup failed after API success
if (createdWorkspace) {
this.openCodeClient.forward({
method: 'DELETE',
path: `/experimental/workspace/${encodeURIComponent(createdWorkspace.id)}`,
directory: repo.fullPath,
}).catch(() => {})
}
// Fall through to raw git path
}
// Fallback: raw git worktree
const worktreePath = path.join(getScheduleWorktreesPath(), `job-${job.id}-run-${runId}`)
mkdirSync(path.dirname(worktreePath), { recursive: true })
await createWorktreeSafely(repo.fullPath, worktreePath, runBranch, env, baseRef)
if (!existsSync(worktreePath)) {
throw new Error(`Worktree directory was not created at: ${worktreePath}`)
}
return { directory: worktreePath, worktreePath, runBranch }
return { directory: worktreePath, worktreePath, runBranch, workspaceId: null }
} finally {
if (sshSetup) {
await this.gitAuthService.cleanupSSHKey()
@@ -89,7 +133,7 @@ export class ScheduleWorktreeManager {
async finalize(
repo: Repo,
job: { id: number; name: string; prompt: string },
run: { id: number; worktreePath: string | null; runBranch: string | null; triggerSource: string },
run: { id: number; worktreePath: string | null; runBranch: string | null; triggerSource: string; workspaceId?: string | null },
): Promise<{ commitHash: string | null }> {
if (!run.worktreePath) {
return { commitHash: null }
@@ -97,7 +141,7 @@ export class ScheduleWorktreeManager {
let sshSetup = false
let env: Record<string, string> | undefined
let noChanges = false
let commitHash: string | null = null
try {
if (repo.repoUrl && isSSHUrl(repo.repoUrl)) {
@@ -109,33 +153,54 @@ export class ScheduleWorktreeManager {
const status = await executeCommand(['git', '-C', run.worktreePath, 'status', '--porcelain'], { env }).catch(() => '')
if (!status.trim()) {
noChanges = true
return { commitHash: null }
if (status.trim()) {
await executeCommand(['git', '-C', run.worktreePath, 'add', '-A'], { env })
const title = `Scheduled run: ${job.name} (run #${run.id})`
const promptSummary = job.prompt.length > 200 ? `${job.prompt.slice(0, 200)}...` : job.prompt
const body = `Trigger: ${run.triggerSource}\nPrompt: ${promptSummary}`
await executeCommand(['git', '-C', run.worktreePath, 'commit', '-m', title, '-m', body], { env })
commitHash = (await executeCommand(['git', '-C', run.worktreePath, 'rev-parse', 'HEAD'], { env })).trim()
}
await executeCommand(['git', '-C', run.worktreePath, 'add', '-A'], { env })
const title = `Scheduled run: ${job.name} (run #${run.id})`
const promptSummary = job.prompt.length > 200 ? `${job.prompt.slice(0, 200)}...` : job.prompt
const body = `Trigger: ${run.triggerSource}\nPrompt: ${promptSummary}`
await executeCommand(['git', '-C', run.worktreePath, 'commit', '-m', title, '-m', body], { env })
const commitHash = (await executeCommand(['git', '-C', run.worktreePath, 'rev-parse', 'HEAD'], { env })).trim()
// Detach HEAD to protect the run branch from accidental pushes
await executeCommand(['git', '-C', run.worktreePath, 'checkout', '--detach'], { env }).catch(() => {})
return { commitHash }
} catch (error) {
logger.error(`Failed to finalize schedule run ${run.id} in worktree ${run.worktreePath}:`, error)
throw error
} finally {
// Teardown: delete the worktree/workspace
try {
await removeWorktree(repo.fullPath, run.worktreePath, env)
if (noChanges && run.runBranch) {
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', run.runBranch], env ? { env } : undefined).catch(() => {})
}
await this.deleteWorkspaceOrFallback(repo, run, env)
} catch (error) {
logger.error(`Failed to remove worktree ${run.worktreePath}:`, error)
// Best-effort fallback
await removeWorktree(repo.fullPath, run.worktreePath, env).catch(() => {})
}
// Branch reconciliation: ensure the run branch survives teardown
if (run.runBranch) {
try {
if (!commitHash) {
// No changes: remove the empty run branch
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', run.runBranch], env ? { env } : undefined).catch(() => {})
} else if (run.workspaceId) {
// Only the workspace API teardown can remove the run branch; the raw
// git fallback leaves it intact, so verify/restore only matters here.
try {
await executeCommand(['git', '-C', repo.fullPath, 'rev-parse', '--verify', `refs/heads/${run.runBranch}`], { env, silent: true })
} catch {
await executeCommand(['git', '-C', repo.fullPath, 'branch', run.runBranch, commitHash], { env })
}
}
} catch {
// Best-effort
}
}
if (sshSetup) {
await this.gitAuthService.cleanupSSHKey()
}
@@ -148,16 +213,28 @@ export class ScheduleWorktreeManager {
* are local git operations, so no SSH setup is needed; failures are swallowed
* per artifact so one bad entry does not block the rest.
*/
async pruneRunArtifacts(repo: Repo, artifacts: { runBranch: string | null; worktreePath: string | null }[]): Promise<void> {
async pruneRunArtifacts(
repo: Repo,
artifacts: { runBranch: string | null; worktreePath: string | null; workspaceId?: string | null }[],
): Promise<void> {
if (artifacts.length === 0) return
const env = await this.buildGitEnv(repo, false, true)
for (const artifact of artifacts) {
if (artifact.worktreePath) {
await removeWorktree(repo.fullPath, artifact.worktreePath, env)
}
}
// Workspace/worktree removals are independent per artifact, so run them
// concurrently; failures are swallowed per artifact so one bad entry does
// not block the rest.
await Promise.all(
artifacts.map(async (artifact) => {
try {
await this.deleteWorkspaceOrFallback(repo, artifact, env)
} catch {
if (artifact.worktreePath) {
await removeWorktree(repo.fullPath, artifact.worktreePath, env).catch(() => {})
}
}
}),
)
const branches = artifacts.map((a) => a.runBranch).filter((b): b is string => b !== null && b.length > 0)
if (branches.length > 0) {
@@ -165,6 +242,33 @@ export class ScheduleWorktreeManager {
}
}
/**
* Deletes a run's worktree, preferring the OpenCode workspace API when a
* workspaceId is present and falling back to a raw `git worktree remove` when
* the API is unavailable or returns a non-ok response.
*/
private async deleteWorkspaceOrFallback(
repo: Repo,
artifact: { workspaceId?: string | null; worktreePath: string | null },
env: Record<string, string> | undefined,
): Promise<void> {
if (artifact.workspaceId) {
const response = await this.openCodeClient.forward({
method: 'DELETE',
path: `/experimental/workspace/${encodeURIComponent(artifact.workspaceId)}`,
directory: repo.fullPath,
})
if (!response.ok) {
logger.warn(`OpenCode workspace DELETE returned ${response.status}, falling back to raw removeWorktree`)
if (artifact.worktreePath) {
await removeWorktree(repo.fullPath, artifact.worktreePath, env)
}
}
} else if (artifact.worktreePath) {
await removeWorktree(repo.fullPath, artifact.worktreePath, env)
}
}
/**
* Resolves a user-supplied base branch name to a verified git ref, preferring
* the remote-tracking branch for freshness. Returns null when neither the
+12 -3
View File
@@ -7,6 +7,7 @@ import {
type ScheduleRunTriggerSource,
type UpdateScheduleJobRequest,
} from '@opencode-manager/shared/types'
import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
import { getRepoById } from '../db/queries'
import type { ScheduleJobWithRepo } from '../db/schedules'
import {
@@ -374,6 +375,11 @@ export class ScheduleService {
this.onJobChange = handler
}
getActiveRunSessionIds(): Set<string> {
const runs = listRunningScheduleRuns(this.db)
return new Set(runs.filter(r => r.sessionId).map(r => r.sessionId!))
}
listAllEnabledJobs(): ScheduleJob[] {
return listEnabledScheduleJobs(this.db)
}
@@ -540,7 +546,7 @@ export class ScheduleService {
throw new ScheduleServiceError('Cannot delete a run while it is in progress. Cancel it first.', 409)
}
await this.worktreeManager.pruneRunArtifacts(repo, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }])
await this.worktreeManager.pruneRunArtifacts(repo, [{ runBranch: run.runBranch, worktreePath: run.worktreePath, workspaceId: run.workspaceId }])
const deleted = deleteScheduleRunById(this.db, repoId, jobId, runId)
if (!deleted) {
throw new ScheduleServiceError('Run not found', 404)
@@ -580,6 +586,7 @@ export class ScheduleService {
updateScheduleRunWorktree(this.db, repoId, jobId, run.id, {
worktreePath: wt.worktreePath,
runBranch: wt.runBranch,
workspaceId: wt.workspaceId,
})
}
@@ -594,6 +601,7 @@ export class ScheduleService {
body: JSON.stringify({
title: sessionTitle,
agent: job.agentSlug ?? undefined,
permission: buildSchedulePermissionRuleset(job.permissionConfig),
}),
headers: { 'Content-Type': 'application/json' },
})
@@ -1111,11 +1119,12 @@ export class ScheduleService {
worktreePath: fresh.worktreePath,
runBranch: fresh.runBranch,
triggerSource: fresh.triggerSource,
workspaceId: fresh.workspaceId,
})
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null, commitHash })
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null, commitHash, workspaceId: null })
} catch (error) {
logger.error(`Failed to finalize worktree for run ${runId}:`, error)
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null })
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null, workspaceId: null })
}
} finally {
ScheduleService.activeTeardowns.delete(key)
+9
View File
@@ -58,6 +58,7 @@ class SSEAggregator {
private started = false
private pendingActionsFetcher: PendingActionsFetcher | null = null
private passwordResolver: OpenCodePasswordResolver | null = null
private scheduledSessionsResolver: (() => Set<string>) | null = null
private constructor() {}
@@ -69,6 +70,10 @@ class SSEAggregator {
this.passwordResolver = resolver
}
setScheduledSessionsResolver(resolver: () => Set<string>): void {
this.scheduledSessionsResolver = resolver
}
reconnect(): void {
if (!this.started) return
logger.info('SSE forcing upstream reconnect (auth changed)')
@@ -523,6 +528,10 @@ class SSEAggregator {
return false
}
getScheduledSessionIds(): Set<string> {
return this.scheduledSessionsResolver?.() ?? new Set()
}
getActiveDirectories(): string[] {
return Array.from(this.activeSessions.keys())
}