mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
feat: add server restart coordination and health status tracking (#300)
* feat: add server restart coordination and health status tracking * refactor: consolidate server restart logic, extract hooks, remove dead code
This commit is contained in:
1 parent
68cd6b5a0b
commit
217f5bd989
19 files changed
+802
-259
No files matched your search
@@ -50,6 +50,8 @@ import { migrateGlobalSkills } from './services/skills'
|
||||
import { installAssistantWorkspace } from './services/assistant-mode'
|
||||
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
|
||||
import { OpenCodeSupervisor } from './services/opencode-supervisor'
|
||||
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'
|
||||
@@ -320,6 +322,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)
|
||||
|
||||
@@ -7,18 +7,9 @@ import {
|
||||
OAuthAuthorizeResponseSchema,
|
||||
OAuthCallbackRequestSchema
|
||||
} from '../../../shared/src/schemas/auth'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { reloadOpenCodeConfig } from '../services/opencode-restart'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
|
||||
async function reloadOpenCodeConfig(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (openCodeSupervisor) {
|
||||
await openCodeSupervisor.reloadConfig('settings_reload')
|
||||
return
|
||||
}
|
||||
|
||||
await opencodeServerManager.reloadConfig()
|
||||
}
|
||||
|
||||
export function createOAuthRoutes(openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
const app = new Hono()
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { AuthService } from '../services/auth'
|
||||
import { SetCredentialRequestSchema } from '../../../shared/src/schemas/auth'
|
||||
import { logger } from '../utils/logger'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { reloadOpenCodeConfig } from '../services/opencode-restart'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
@@ -54,15 +54,6 @@ async function mirrorModelStateToFile(state: OpenCodeModelStateRecord): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadOpenCodeConfig(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (openCodeSupervisor) {
|
||||
await openCodeSupervisor.reloadConfig('settings_reload')
|
||||
return
|
||||
}
|
||||
|
||||
await opencodeServerManager.reloadConfig()
|
||||
}
|
||||
|
||||
export function createProvidersRoutes(db: Database, openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
const app = new Hono()
|
||||
const authService = new AuthService()
|
||||
|
||||
@@ -8,7 +8,7 @@ import * as repoService from '../services/repo'
|
||||
import * as archiveService from '../services/archive'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { writeFileContent } from '../services/file-operations'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { restartOpenCode } from '../services/opencode-restart'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { logger } from '../utils/logger'
|
||||
@@ -22,16 +22,6 @@ import { ScheduleService } from '../services/schedules'
|
||||
import { ensureAssistantMode, getAssistantModeStatus, buildAssistantRepo } from '../services/assistant-mode'
|
||||
import path from 'path'
|
||||
|
||||
async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (openCodeSupervisor) {
|
||||
await openCodeSupervisor.restart('settings_restart')
|
||||
return
|
||||
}
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
}
|
||||
|
||||
function resolveRepo(database: Database, id: number): Repo | null {
|
||||
return getRepoById(database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import type { OpenCodeRestartCoordinator, ResumableSession } from '../services/opencode-restart-coordinator'
|
||||
import { setOpenCodeRestartCoordinator } from '../services/opencode-restart'
|
||||
|
||||
interface TestUserPreferenceRow {
|
||||
preferences: string
|
||||
@@ -450,3 +452,67 @@ describe('settings routes — opencode model discovery', () => {
|
||||
expect(data.models).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('settings routes — restart coordinator wiring', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
setOpenCodeRestartCoordinator(null)
|
||||
})
|
||||
|
||||
it('GET /opencode-active-sessions returns count and sessions from coordinator', async () => {
|
||||
const fakeCoordinator = {
|
||||
captureResumableSessions: vi.fn(() => [{
|
||||
sessionID: 's1',
|
||||
directory: '/a',
|
||||
} satisfies ResumableSession]),
|
||||
abortSessions: vi.fn(),
|
||||
resumeSessions: vi.fn(),
|
||||
runWithResume: vi.fn(),
|
||||
} as unknown as OpenCodeRestartCoordinator
|
||||
setOpenCodeRestartCoordinator(fakeCoordinator)
|
||||
|
||||
app = createTestApp(db)
|
||||
const res = await app.request('/settings/opencode-active-sessions')
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { count: number; sessions: ResumableSession[] }
|
||||
expect(body.count).toBe(1)
|
||||
expect(body.sessions).toEqual([{ sessionID: 's1', directory: '/a' }])
|
||||
expect(fakeCoordinator.captureResumableSessions).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('GET /opencode-active-sessions returns empty when no coordinator', async () => {
|
||||
setOpenCodeRestartCoordinator(null)
|
||||
app = createTestApp(db)
|
||||
const res = await app.request('/settings/opencode-active-sessions')
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { count: number; sessions: ResumableSession[] }
|
||||
expect(body.count).toBe(0)
|
||||
expect(body.sessions).toEqual([])
|
||||
})
|
||||
|
||||
it('POST /opencode-restart routes through coordinator.runWithResume and returns resumedSessions', async () => {
|
||||
const runWithResume = vi.fn().mockResolvedValue({ healthy: true, resumedSessionIDs: ['s1'] })
|
||||
const fakeCoordinator = {
|
||||
captureResumableSessions: vi.fn(() => []),
|
||||
abortSessions: vi.fn(),
|
||||
resumeSessions: vi.fn(),
|
||||
runWithResume,
|
||||
} as unknown as OpenCodeRestartCoordinator
|
||||
setOpenCodeRestartCoordinator(fakeCoordinator)
|
||||
|
||||
app = createTestApp(db)
|
||||
const res = await app.request('/settings/opencode-restart', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { success: boolean; resumedSessions: string[] }
|
||||
expect(body.success).toBe(true)
|
||||
expect(body.resumedSessions).toEqual(['s1'])
|
||||
expect(runWithResume).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -31,6 +31,7 @@ import { opencodeServerManager, ConfigReloadError } from '../services/opencode-s
|
||||
import { getOrCreateInternalToken, rotateInternalToken } from '../services/internal-token'
|
||||
import { sseAggregator } from '../services/sse-aggregator'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { restartOpenCode, reloadOpenCodeConfig, getOpenCodeRestartCoordinator } from '../services/opencode-restart'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { DEFAULT_AGENTS_MD } from '../constants'
|
||||
import { validateSSHPrivateKey } from '../utils/ssh-validation'
|
||||
@@ -92,25 +93,6 @@ function getOpenCodeConfigContentToWrite(
|
||||
return JSON.stringify(appliedConfig, null, 2)
|
||||
}
|
||||
|
||||
async function reloadOpenCodeConfig(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (openCodeSupervisor) {
|
||||
await openCodeSupervisor.reloadConfig('settings_reload')
|
||||
return
|
||||
}
|
||||
|
||||
await opencodeServerManager.reloadConfig()
|
||||
}
|
||||
|
||||
async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (openCodeSupervisor) {
|
||||
await openCodeSupervisor.restart('settings_restart')
|
||||
return
|
||||
}
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
}
|
||||
|
||||
async function restartOpenCodeSafe(openCodeSupervisor: OpenCodeSupervisor | undefined, context: string): Promise<void> {
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
@@ -728,8 +710,12 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
try {
|
||||
logger.info('Manual OpenCode server restart requested')
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
return c.json({ success: true, message: 'OpenCode server restarted successfully' })
|
||||
const { resumedSessionIDs } = await restartOpenCode(openCodeSupervisor)
|
||||
return c.json({
|
||||
success: true,
|
||||
message: 'OpenCode server restarted successfully',
|
||||
resumedSessions: resumedSessionIDs,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Failed to restart OpenCode server:', error)
|
||||
const startupError = opencodeServerManager.getLastStartupError()
|
||||
@@ -1879,6 +1865,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/opencode-active-sessions', (c) => {
|
||||
const sessions = getOpenCodeRestartCoordinator()?.captureResumableSessions() ?? []
|
||||
return c.json({ count: sessions.length, sessions })
|
||||
})
|
||||
|
||||
app.get('/opencode-discover-models', async (c) => {
|
||||
try {
|
||||
const baseUrl = c.req.query('baseUrl')
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { OpenCodeRestartCoordinator, type ActiveSessionsProvider, type ResumableSession } from './opencode-restart-coordinator'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
function createFakeActiveSessionsProvider(overrides: Partial<ActiveSessionsProvider> = {}): ActiveSessionsProvider {
|
||||
return {
|
||||
getActiveSessions: vi.fn(() => ({})),
|
||||
isSubagentSession: vi.fn(() => false),
|
||||
getScheduledSessionIds: vi.fn(() => new Set<string>()),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('OpenCodeRestartCoordinator', () => {
|
||||
let client: OpenCodeClient
|
||||
let activeSessions: ActiveSessionsProvider
|
||||
let coordinator: OpenCodeRestartCoordinator
|
||||
|
||||
beforeEach(() => {
|
||||
client = createStubOpenCodeClient()
|
||||
activeSessions = createFakeActiveSessionsProvider()
|
||||
coordinator = new OpenCodeRestartCoordinator(client, activeSessions)
|
||||
})
|
||||
|
||||
describe('captureResumableSessions', () => {
|
||||
it('excludes subagent sessions', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1', 'sub1'],
|
||||
'/b': ['s2'],
|
||||
})
|
||||
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id === 'sub1')
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([
|
||||
{ sessionID: 's1', directory: '/a' },
|
||||
{ sessionID: 's2', directory: '/b' },
|
||||
])
|
||||
})
|
||||
|
||||
it('returns empty array when no active sessions', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({})
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('filters out only subagent sessions, keeps all others', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/x': ['a1', 'a2', 'sub_x'],
|
||||
})
|
||||
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id.startsWith('sub_'))
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([
|
||||
{ sessionID: 'a1', directory: '/x' },
|
||||
{ sessionID: 'a2', directory: '/x' },
|
||||
])
|
||||
})
|
||||
|
||||
it('excludes scheduled sessions', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1', 'sched1'],
|
||||
})
|
||||
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched1']))
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([{ sessionID: 's1', directory: '/a' }])
|
||||
})
|
||||
|
||||
it('excludes both subagent and scheduled sessions simultaneously', () => {
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/p': ['manual', 'sub', 'sched'],
|
||||
})
|
||||
vi.mocked(activeSessions.isSubagentSession).mockImplementation((id: string) => id === 'sub')
|
||||
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched']))
|
||||
|
||||
const result = coordinator.captureResumableSessions()
|
||||
|
||||
expect(result).toEqual([{ sessionID: 'manual', directory: '/p' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('runWithResume', () => {
|
||||
it('aborts captured sessions, restarts, then resumes when healthy', async () => {
|
||||
const events: string[] = []
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockImplementation(async (opts) => {
|
||||
events.push(`forward:${opts.path}`)
|
||||
return new Response(null, { status: 200 })
|
||||
})
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1'],
|
||||
'/b': ['s2'],
|
||||
})
|
||||
|
||||
const restart = vi.fn(async () => {
|
||||
events.push('restart')
|
||||
return true
|
||||
})
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
// Assert interleaved ordering: aborts → restart → resumes
|
||||
expect(events).toEqual([
|
||||
'forward:/session/s1/abort',
|
||||
'forward:/session/s2/abort',
|
||||
'restart',
|
||||
'forward:/session/s1/prompt_async',
|
||||
'forward:/session/s2/prompt_async',
|
||||
])
|
||||
|
||||
// Aborts called first for both sessions
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(2, {
|
||||
method: 'POST',
|
||||
path: '/session/s2/abort',
|
||||
directory: '/b',
|
||||
})
|
||||
|
||||
expect(restart).toHaveBeenCalledOnce()
|
||||
|
||||
// Forward was called 4 times: 2 aborts (calls 1-2) + 2 resumes (calls 3-4)
|
||||
expect(forward).toHaveBeenCalledTimes(4)
|
||||
expect(forward).toHaveBeenNthCalledWith(3, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/prompt_async',
|
||||
directory: '/a',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(4, {
|
||||
method: 'POST',
|
||||
path: '/session/s2/prompt_async',
|
||||
directory: '/b',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
|
||||
expect(result).toEqual({ healthy: true, resumedSessionIDs: ['s1', 's2'] })
|
||||
})
|
||||
|
||||
it('does NOT resume when restart returns unhealthy', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1'],
|
||||
})
|
||||
|
||||
const restart = vi.fn(async () => false)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
// Aborts still happen
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(restart).toHaveBeenCalledOnce()
|
||||
|
||||
// No prompt_async calls
|
||||
const promptAsyncCalls = forward.mock.calls.filter(
|
||||
(call: unknown[]) => (call[0] as { path: string }).path.includes('prompt_async'),
|
||||
)
|
||||
expect(promptAsyncCalls).toHaveLength(0)
|
||||
|
||||
expect(result).toEqual({ healthy: false, resumedSessionIDs: [] })
|
||||
})
|
||||
|
||||
it('with no active sessions performs restart only', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({})
|
||||
|
||||
const restart = vi.fn(async () => true)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
expect(restart).toHaveBeenCalledOnce()
|
||||
expect(forward).not.toHaveBeenCalled()
|
||||
|
||||
expect(result).toEqual({ healthy: true, resumedSessionIDs: [] })
|
||||
})
|
||||
|
||||
it('does not abort or resume scheduled sessions', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward.mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['manual1', 'sched1'],
|
||||
})
|
||||
vi.mocked(activeSessions.getScheduledSessionIds).mockReturnValue(new Set(['sched1']))
|
||||
|
||||
const restart = vi.fn(async () => true)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
// Only manual1 should be aborted and resumed — 2 forward calls total
|
||||
expect(forward).toHaveBeenCalledTimes(2)
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/manual1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(2, {
|
||||
method: 'POST',
|
||||
path: '/session/manual1/prompt_async',
|
||||
directory: '/a',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
|
||||
expect(result).toEqual({ healthy: true, resumedSessionIDs: ['manual1'] })
|
||||
})
|
||||
|
||||
it('is best-effort: per-session errors are swallowed and other sessions still processed', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
// Aborts all succeed, but resume for s2 fails
|
||||
forward
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s1
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s2
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // abort s3
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // resume s1
|
||||
.mockRejectedValueOnce(new Error('connection refused')) // resume s2 fails
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 })) // resume s3
|
||||
|
||||
vi.mocked(activeSessions.getActiveSessions).mockReturnValue({
|
||||
'/a': ['s1', 's2', 's3'],
|
||||
})
|
||||
|
||||
const restart = vi.fn(async () => true)
|
||||
|
||||
const result = await coordinator.runWithResume(restart)
|
||||
|
||||
expect(result.healthy).toBe(true)
|
||||
expect(result.resumedSessionIDs).toEqual(['s1', 's3'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('abortSessions', () => {
|
||||
it('does not throw when forward rejects and continues processing remaining sessions', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward
|
||||
.mockRejectedValueOnce(new Error('timeout'))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
|
||||
await expect(
|
||||
coordinator.abortSessions([
|
||||
{ sessionID: 's1', directory: '/a' },
|
||||
{ sessionID: 's2', directory: '/b' },
|
||||
]),
|
||||
).resolves.toBeUndefined()
|
||||
|
||||
expect(forward).toHaveBeenCalledTimes(2)
|
||||
expect(forward).toHaveBeenNthCalledWith(1, {
|
||||
method: 'POST',
|
||||
path: '/session/s1/abort',
|
||||
directory: '/a',
|
||||
})
|
||||
expect(forward).toHaveBeenNthCalledWith(2, {
|
||||
method: 'POST',
|
||||
path: '/session/s2/abort',
|
||||
directory: '/b',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('resumeSessions', () => {
|
||||
it('only includes sessions with ok response', async () => {
|
||||
const forward = vi.mocked(client.forward)
|
||||
forward
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 404 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
|
||||
const sessions: ResumableSession[] = [
|
||||
{ sessionID: 's1', directory: '/a' },
|
||||
{ sessionID: 's2', directory: '/b' },
|
||||
{ sessionID: 's3', directory: '/c' },
|
||||
]
|
||||
|
||||
const result = await coordinator.resumeSessions(sessions)
|
||||
|
||||
expect(result).toEqual(['s1', 's3'])
|
||||
})
|
||||
|
||||
it('does not throw when forward rejects', async () => {
|
||||
vi.mocked(client.forward).mockRejectedValue(new Error('timeout'))
|
||||
|
||||
const result = await coordinator.resumeSessions([{ sessionID: 's1', directory: '/a' }])
|
||||
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import { logger } from '../utils/logger'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
export interface ActiveSessionsProvider {
|
||||
getActiveSessions(): Record<string, string[]>
|
||||
isSubagentSession(sessionId: string): boolean
|
||||
getScheduledSessionIds(): Set<string>
|
||||
}
|
||||
|
||||
export interface ResumableSession {
|
||||
sessionID: string
|
||||
directory: string
|
||||
}
|
||||
|
||||
export interface RestartWithResumeResult {
|
||||
healthy: boolean
|
||||
resumedSessionIDs: string[]
|
||||
}
|
||||
|
||||
export class OpenCodeRestartCoordinator {
|
||||
constructor(
|
||||
private readonly client: OpenCodeClient,
|
||||
private readonly activeSessions: ActiveSessionsProvider,
|
||||
) {}
|
||||
|
||||
captureResumableSessions(): ResumableSession[] {
|
||||
const active = this.activeSessions.getActiveSessions()
|
||||
const scheduled = this.activeSessions.getScheduledSessionIds()
|
||||
const sessions: ResumableSession[] = []
|
||||
|
||||
for (const [directory, sessionIDs] of Object.entries(active)) {
|
||||
for (const sessionID of sessionIDs) {
|
||||
if (!this.activeSessions.isSubagentSession(sessionID) && !scheduled.has(sessionID)) {
|
||||
sessions.push({ sessionID, directory })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sessions
|
||||
}
|
||||
|
||||
async abortSessions(sessions: ResumableSession[]): Promise<void> {
|
||||
await Promise.allSettled(
|
||||
sessions.map(async (s) => {
|
||||
try {
|
||||
await this.client.forward({
|
||||
method: 'POST',
|
||||
path: `/session/${s.sessionID}/abort`,
|
||||
directory: s.directory,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to abort session ${s.sessionID}: ${error}`)
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async resumeSessions(sessions: ResumableSession[]): Promise<string[]> {
|
||||
const results = await Promise.allSettled(
|
||||
sessions.map(async (s) => {
|
||||
try {
|
||||
const response = await this.client.forward({
|
||||
method: 'POST',
|
||||
path: `/session/${s.sessionID}/prompt_async`,
|
||||
directory: s.directory,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ parts: [{ type: 'text', text: 'continue' }] }),
|
||||
})
|
||||
return response.ok ? s.sessionID : null
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to resume session ${s.sessionID}: ${error}`)
|
||||
return null
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
return results
|
||||
.map((result) => (result.status === 'fulfilled' ? result.value : null))
|
||||
.filter((sessionID): sessionID is string => sessionID !== null)
|
||||
}
|
||||
|
||||
async runWithResume(restart: () => Promise<boolean>): Promise<RestartWithResumeResult> {
|
||||
const sessions = this.captureResumableSessions()
|
||||
await this.abortSessions(sessions)
|
||||
const healthy = await restart()
|
||||
const resumedSessionIDs = healthy ? await this.resumeSessions(sessions) : []
|
||||
return { healthy, resumedSessionIDs }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { opencodeServerManager } from './opencode-single-server'
|
||||
import type { OpenCodeSupervisor } from './opencode-supervisor'
|
||||
import type { OpenCodeRestartCoordinator } from './opencode-restart-coordinator'
|
||||
|
||||
let restartCoordinator: OpenCodeRestartCoordinator | null = null
|
||||
|
||||
/**
|
||||
* Registers the process-wide restart coordinator so every restart path can
|
||||
* abort and resume in-flight sessions consistently. Passing null disables
|
||||
* resume (used by tests and pre-initialization paths).
|
||||
*/
|
||||
export function setOpenCodeRestartCoordinator(coordinator: OpenCodeRestartCoordinator | null): void {
|
||||
restartCoordinator = coordinator
|
||||
}
|
||||
|
||||
export function getOpenCodeRestartCoordinator(): OpenCodeRestartCoordinator | null {
|
||||
return restartCoordinator
|
||||
}
|
||||
|
||||
async function performRestart(supervisor?: OpenCodeSupervisor): Promise<boolean> {
|
||||
if (supervisor) {
|
||||
return (await supervisor.restart('settings_restart')).healthy
|
||||
}
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
return opencodeServerManager.checkHealth()
|
||||
}
|
||||
|
||||
/**
|
||||
* The single entry point for restarting the OpenCode server. Every restart
|
||||
* trigger (manual restart, version upgrade/install, workspace config change,
|
||||
* restart-sensitive config saves) routes through here so that interrupted user
|
||||
* sessions are aborted and resumed uniformly when a coordinator is registered.
|
||||
* A full process restart drops in-flight sessions; resuming re-issues a
|
||||
* "continue" prompt once the server is healthy again.
|
||||
*/
|
||||
export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<{ resumedSessionIDs: string[] }> {
|
||||
if (restartCoordinator) {
|
||||
const result = await restartCoordinator.runWithResume(() => performRestart(supervisor))
|
||||
return { resumedSessionIDs: result.resumedSessionIDs }
|
||||
}
|
||||
if (supervisor) {
|
||||
await supervisor.restart('settings_restart')
|
||||
} else {
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
}
|
||||
return { resumedSessionIDs: [] }
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads OpenCode configuration via the non-disruptive API patch. This does
|
||||
* NOT drop the server process, so active sessions keep running and there is
|
||||
* nothing to resume.
|
||||
*/
|
||||
export async function reloadOpenCodeConfig(supervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (supervisor) {
|
||||
await supervisor.reloadConfig('settings_reload')
|
||||
return
|
||||
}
|
||||
await opencodeServerManager.reloadConfig()
|
||||
}
|
||||
@@ -375,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)
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user