mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +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())
|
||||
}
|
||||
|
||||
@@ -152,6 +152,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`, {
|
||||
|
||||
@@ -9,6 +9,7 @@ const {
|
||||
mockGetOpenCodeConfigs,
|
||||
mockUpdateOpenCodeConfig,
|
||||
mockRestartOpenCodeServer,
|
||||
mockGetActiveOpenCodeSessions,
|
||||
mockGetOpenCodeImportStatus,
|
||||
mockListManagedSkills,
|
||||
mockListOpenCodeDirectoryFiles,
|
||||
@@ -17,6 +18,7 @@ const {
|
||||
mockGetOpenCodeConfigs: vi.fn(),
|
||||
mockUpdateOpenCodeConfig: vi.fn(),
|
||||
mockRestartOpenCodeServer: vi.fn(),
|
||||
mockGetActiveOpenCodeSessions: vi.fn(),
|
||||
mockGetOpenCodeImportStatus: vi.fn(),
|
||||
mockListManagedSkills: vi.fn(),
|
||||
mockListOpenCodeDirectoryFiles: vi.fn(),
|
||||
@@ -36,6 +38,7 @@ vi.mock('@/api/settings', () => ({
|
||||
getOpenCodeConfigs: mockGetOpenCodeConfigs,
|
||||
updateOpenCodeConfig: mockUpdateOpenCodeConfig,
|
||||
restartOpenCodeServer: mockRestartOpenCodeServer,
|
||||
getActiveOpenCodeSessions: mockGetActiveOpenCodeSessions,
|
||||
getOpenCodeImportStatus: mockGetOpenCodeImportStatus,
|
||||
listManagedSkills: mockListManagedSkills,
|
||||
listOpenCodeDirectoryFiles: mockListOpenCodeDirectoryFiles,
|
||||
@@ -85,6 +88,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
})
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue(defaultConfig)
|
||||
mockRestartOpenCodeServer.mockResolvedValue({ success: true, message: 'ok' })
|
||||
mockGetActiveOpenCodeSessions.mockResolvedValue({ count: 2, sessions: [] })
|
||||
})
|
||||
|
||||
it('shows uploaded command and agent directory files in settings', async () => {
|
||||
|
||||
@@ -21,9 +21,11 @@ import { VersionSelectDialog } from './VersionSelectDialog'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { parseJsonc, hasJsoncComments } from '@/lib/jsonc'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import type { OpenCodeConfig, OpenCodeImportStatus } from '@/api/types/settings'
|
||||
|
||||
@@ -81,7 +83,16 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
|
||||
const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false)
|
||||
const [deleteConfirmConfig, setDeleteConfirmConfig] = useState<OpenCodeConfig | null>(null)
|
||||
const [isRestartPromptOpen, setIsRestartPromptOpen] = useState(false)
|
||||
const {
|
||||
restartServerMutation,
|
||||
upgradeOpenCodeMutation,
|
||||
confirmOpen: isRestartPromptOpen,
|
||||
setConfirmOpen: setIsRestartPromptOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
performUpgrade,
|
||||
} = useOpenCodeServerActions()
|
||||
|
||||
const agentsMdRef = useRef<HTMLButtonElement>(null)
|
||||
const commandsRef = useRef<HTMLButtonElement>(null)
|
||||
@@ -124,56 +135,6 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
}
|
||||
}
|
||||
|
||||
const restartServerMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
return await settingsApi.restartOpenCodeServer()
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
|
||||
const upgradeOpenCodeMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
return await settingsApi.upgradeOpenCode()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
if (data.upgraded && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
if (data.upgraded) {
|
||||
showToast.success(`Upgraded to v${data.newVersion} and server restarted`, { id: 'upgrade-opencode' })
|
||||
} else {
|
||||
showToast.success('OpenCode is already up to date', { id: 'upgrade-opencode' })
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
const defaultMessage = 'Failed to upgrade OpenCode'
|
||||
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = (error as { response?: { data?: { recovered?: boolean; recoveryMessage?: string; newVersion?: string } } }).response
|
||||
const data = response?.data
|
||||
|
||||
if (data?.recovered && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
showToast.success(`Upgrade failed but server recovered at v${data.newVersion}`, { id: 'upgrade-opencode' })
|
||||
} else {
|
||||
showToast.error(data?.recoveryMessage || defaultMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
} else {
|
||||
showToast.error(defaultMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
|
||||
const syncOpenCodeImportMutation = useMutation({
|
||||
mutationFn: async () => settingsApi.syncOpenCodeImport(),
|
||||
onSuccess: async () => {
|
||||
@@ -183,50 +144,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
},
|
||||
})
|
||||
|
||||
const getApiErrorMessage = (error: unknown, fallback: string): string => {
|
||||
if (error instanceof FetchError) {
|
||||
let message = error.detail || error.message || fallback
|
||||
|
||||
if (error.validationIssues && error.validationIssues.length > 0) {
|
||||
const issues = error.validationIssues
|
||||
.map((issue) => `${issue.path}: ${issue.message}`)
|
||||
.join('; ')
|
||||
message = `Validation failed: ${issues}`
|
||||
}
|
||||
|
||||
if (error.removedFields && error.removedFields.length > 0) {
|
||||
message += ` (removed invalid fields: ${error.removedFields.join(', ')})`
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = (error as { response?: { data?: { details?: string; error?: string; validationIssues?: Array<{ path: string; message: string }>; removedFields?: string[] } } }).response
|
||||
const data = response?.data
|
||||
|
||||
let message = data?.details || data?.error || fallback
|
||||
|
||||
if (data?.validationIssues && data.validationIssues.length > 0) {
|
||||
const issues = data.validationIssues
|
||||
.map((issue) => `${issue.path}: ${issue.message}`)
|
||||
.join('; ')
|
||||
message = `Validation failed: ${issues}`
|
||||
}
|
||||
|
||||
if (data?.removedFields && data.removedFields.length > 0) {
|
||||
const removed = data.removedFields.join(', ')
|
||||
message += ` (removed invalid fields: ${removed})`
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
const getRestartErrorMessage = (error: unknown): string => {
|
||||
return getApiErrorMessage(error, 'Failed to restart OpenCode server')
|
||||
}
|
||||
const getApiErrorMessage = getOpenCodeApiErrorMessage
|
||||
|
||||
const getOpenCodeImportErrorMessage = (error: unknown): string => {
|
||||
if (error instanceof FetchError && error.code === 'OPENCODE_IMPORT_PROTECTED') {
|
||||
@@ -452,19 +370,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
showToast.loading('Upgrading OpenCode...', { id: 'upgrade-opencode' })
|
||||
try {
|
||||
await upgradeOpenCodeMutation.mutateAsync()
|
||||
} catch (error) {
|
||||
const errorMessage = error && typeof error === 'object' && 'response' in error
|
||||
? ((error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.details
|
||||
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|
||||
|| 'Failed to upgrade OpenCode')
|
||||
: 'Failed to upgrade OpenCode'
|
||||
showToast.error(errorMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
}}
|
||||
onClick={performUpgrade}
|
||||
disabled={upgradeOpenCodeMutation.isPending}
|
||||
>
|
||||
{upgradeOpenCodeMutation.isPending ? (
|
||||
@@ -477,15 +383,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
showToast.loading('Restarting OpenCode server...', { id: 'manual-restart' })
|
||||
try {
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Server restarted successfully', { id: 'manual-restart' })
|
||||
} catch (error) {
|
||||
showToast.error(getRestartErrorMessage(error), { id: 'manual-restart' })
|
||||
}
|
||||
}}
|
||||
onClick={requestRestart}
|
||||
disabled={restartServerMutation.isPending}
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
@@ -519,7 +417,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setIsRestartPromptOpen(true)}
|
||||
onClick={requestRestart}
|
||||
disabled={restartServerMutation.isPending}
|
||||
className="shrink-0"
|
||||
>
|
||||
@@ -1080,18 +978,10 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<RestartServerDialog
|
||||
open={isRestartPromptOpen}
|
||||
onOpenChange={setIsRestartPromptOpen}
|
||||
activeSessionCount={activeSessionCount}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setIsRestartPromptOpen(false)}
|
||||
onConfirm={async () => {
|
||||
showToast.loading('Restarting OpenCode server...', { id: 'config-restart' })
|
||||
try {
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Server restarted successfully', { id: 'config-restart' })
|
||||
setIsRestartPromptOpen(false)
|
||||
} catch (error) {
|
||||
showToast.error(getRestartErrorMessage(error), { id: 'config-restart' })
|
||||
}
|
||||
}}
|
||||
onConfirm={confirmRestart}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -58,4 +58,20 @@ describe('RestartServerDialog', () => {
|
||||
const laterButton = screen.getByRole('button', { name: /later/i })
|
||||
expect(laterButton).toBeDisabled()
|
||||
})
|
||||
|
||||
it('renders the active-session warning when activeSessionCount > 0', () => {
|
||||
render(<RestartServerDialog {...baseProps} activeSessionCount={2} />)
|
||||
|
||||
expect(screen.getByText(/2 sessions/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/continue/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render the active-session warning when activeSessionCount is omitted', () => {
|
||||
render(<RestartServerDialog {...baseProps} />)
|
||||
|
||||
expect(
|
||||
screen.getByText(/Restart the OpenCode server after your changes are saved to apply them to the running server\./)
|
||||
).toBeInTheDocument()
|
||||
expect(screen.queryByText(/sessions? currently working/)).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,7 @@ interface RestartServerDialogProps {
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
isRestarting?: boolean
|
||||
activeSessionCount?: number
|
||||
}
|
||||
|
||||
export function RestartServerDialog({
|
||||
@@ -16,6 +17,7 @@ export function RestartServerDialog({
|
||||
onConfirm,
|
||||
onCancel,
|
||||
isRestarting = false,
|
||||
activeSessionCount,
|
||||
}: RestartServerDialogProps) {
|
||||
const isConfirmDisabled = isRestarting
|
||||
|
||||
@@ -25,7 +27,10 @@ export function RestartServerDialog({
|
||||
<DialogHeader>
|
||||
<DialogTitle>Restart OpenCode Server?</DialogTitle>
|
||||
<DialogDescription>
|
||||
Restart the OpenCode server after your changes are saved to apply them to the running server.
|
||||
{activeSessionCount && activeSessionCount > 0
|
||||
? `${activeSessionCount} session${activeSessionCount === 1 ? '' : 's'} ${activeSessionCount === 1 ? 'is' : 'are'} currently working. Restarting will interrupt ${activeSessionCount === 1 ? 'it' : 'them'} and send "continue" to resume after the server is healthy.`
|
||||
: 'Restart the OpenCode server after your changes are saved to apply them to the running server.'
|
||||
}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="gap-2">
|
||||
|
||||
@@ -3,64 +3,25 @@ import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Loader2, ArrowUpCircle, RotateCcw, History } from 'lucide-react'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { RestartServerDialog } from './RestartServerDialog'
|
||||
|
||||
interface ServerHealthStatusProps {
|
||||
onOpenVersionDialog?: () => void
|
||||
}
|
||||
|
||||
export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: health } = useServerHealth()
|
||||
|
||||
const restartServerMutation = useMutation({
|
||||
mutationFn: async () => settingsApi.restartOpenCodeServer(),
|
||||
onSuccess: () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
|
||||
const upgradeOpenCodeMutation = useMutation({
|
||||
mutationFn: async () => settingsApi.upgradeOpenCode(),
|
||||
onSuccess: (data) => {
|
||||
if (data.upgraded && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
if (data.upgraded) {
|
||||
showToast.success(`Upgraded to v${data.newVersion} and server restarted`, { id: 'upgrade-opencode' })
|
||||
} else {
|
||||
showToast.success('OpenCode is already up to date', { id: 'upgrade-opencode' })
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
const defaultMessage = 'Failed to upgrade OpenCode'
|
||||
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = (error as { response?: { data?: { recovered?: boolean; recoveryMessage?: string; newVersion?: string } } }).response
|
||||
const data = response?.data
|
||||
|
||||
if (data?.recovered && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
showToast.success(`Upgrade failed but server recovered at v${data.newVersion}`, { id: 'upgrade-opencode' })
|
||||
} else {
|
||||
showToast.error(data?.recoveryMessage || defaultMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
} else {
|
||||
showToast.error(defaultMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
const {
|
||||
restartServerMutation,
|
||||
upgradeOpenCodeMutation,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
performUpgrade,
|
||||
} = useOpenCodeServerActions()
|
||||
|
||||
if (!health) {
|
||||
return (
|
||||
@@ -106,19 +67,7 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
showToast.loading('Upgrading OpenCode...', { id: 'upgrade-opencode' })
|
||||
try {
|
||||
await upgradeOpenCodeMutation.mutateAsync()
|
||||
} catch (error) {
|
||||
const errorMessage = error && typeof error === 'object' && 'response' in error
|
||||
? ((error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.details
|
||||
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|
||||
|| 'Failed to upgrade OpenCode')
|
||||
: 'Failed to upgrade OpenCode'
|
||||
showToast.error(errorMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
}}
|
||||
onClick={performUpgrade}
|
||||
disabled={upgradeOpenCodeMutation.isPending}
|
||||
>
|
||||
{upgradeOpenCodeMutation.isPending ? (
|
||||
@@ -131,20 +80,7 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
showToast.loading('Restarting OpenCode server...', { id: 'manual-restart' })
|
||||
try {
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Server restarted successfully', { id: 'manual-restart' })
|
||||
} catch (error) {
|
||||
const errorMessage = error && typeof error === 'object' && 'response' in error
|
||||
? ((error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.details
|
||||
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|
||||
|| 'Failed to restart OpenCode server')
|
||||
: 'Failed to restart OpenCode server'
|
||||
showToast.error(errorMessage, { id: 'manual-restart' })
|
||||
}
|
||||
}}
|
||||
onClick={requestRestart}
|
||||
disabled={restartServerMutation.isPending}
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
@@ -165,6 +101,14 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
<RestartServerDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
activeSessionCount={activeSessionCount}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
onConfirm={confirmRestart}
|
||||
/>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
|
||||
const RESTART_TOAST_ID = 'opencode-restart'
|
||||
const UPGRADE_TOAST_ID = 'upgrade-opencode'
|
||||
|
||||
/**
|
||||
* Centralizes OpenCode server restart/upgrade actions shared by the settings
|
||||
* surfaces. A restart always routes through `POST /opencode-restart`, which
|
||||
* aborts and resumes in-flight sessions; `requestRestart` first checks for
|
||||
* active sessions and opens a confirmation dialog when any would be interrupted.
|
||||
*/
|
||||
export function useOpenCodeServerActions() {
|
||||
const queryClient = useQueryClient()
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [activeSessionCount, setActiveSessionCount] = useState(0)
|
||||
|
||||
const restartServerMutation = useMutation({
|
||||
mutationFn: async () => settingsApi.restartOpenCodeServer(),
|
||||
onSuccess: () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
|
||||
const upgradeOpenCodeMutation = useMutation({
|
||||
mutationFn: async () => settingsApi.upgradeOpenCode(),
|
||||
onSuccess: (data) => {
|
||||
if (data.upgraded && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
if (data.upgraded) {
|
||||
showToast.success(`Upgraded to v${data.newVersion} and server restarted`, { id: UPGRADE_TOAST_ID })
|
||||
} else {
|
||||
showToast.success('OpenCode is already up to date', { id: UPGRADE_TOAST_ID })
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
const defaultMessage = 'Failed to upgrade OpenCode'
|
||||
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = (error as { response?: { data?: { recovered?: boolean; recoveryMessage?: string; newVersion?: string } } }).response
|
||||
const data = response?.data
|
||||
|
||||
if (data?.recovered && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
showToast.success(`Upgrade failed but server recovered at v${data.newVersion}`, { id: UPGRADE_TOAST_ID })
|
||||
} else {
|
||||
showToast.error(data?.recoveryMessage || defaultMessage, { id: UPGRADE_TOAST_ID })
|
||||
}
|
||||
} else {
|
||||
showToast.error(defaultMessage, { id: UPGRADE_TOAST_ID })
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
|
||||
const performRestart = async () => {
|
||||
showToast.loading('Restarting OpenCode server...', { id: RESTART_TOAST_ID })
|
||||
try {
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Server restarted successfully', { id: RESTART_TOAST_ID })
|
||||
} catch (error) {
|
||||
showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to restart OpenCode server'), { id: RESTART_TOAST_ID })
|
||||
}
|
||||
}
|
||||
|
||||
const requestRestart = async () => {
|
||||
try {
|
||||
const { count } = await settingsApi.getActiveOpenCodeSessions()
|
||||
if (count > 0) {
|
||||
setActiveSessionCount(count)
|
||||
setConfirmOpen(true)
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Fall through to an immediate restart when the active-session probe fails.
|
||||
}
|
||||
await performRestart()
|
||||
}
|
||||
|
||||
const confirmRestart = async () => {
|
||||
await performRestart()
|
||||
setConfirmOpen(false)
|
||||
}
|
||||
|
||||
const performUpgrade = async () => {
|
||||
showToast.loading('Upgrading OpenCode...', { id: UPGRADE_TOAST_ID })
|
||||
try {
|
||||
await upgradeOpenCodeMutation.mutateAsync()
|
||||
} catch (error) {
|
||||
showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to upgrade OpenCode'), { id: UPGRADE_TOAST_ID })
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
restartServerMutation,
|
||||
upgradeOpenCodeMutation,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
performUpgrade,
|
||||
}
|
||||
}
|
||||
@@ -137,3 +137,49 @@ export function getErrorMessage(error: OpenCodeError | undefined | null): string
|
||||
const parsed = parseOpenCodeError(error)
|
||||
return parsed ? `${parsed.title}: ${parsed.message}` : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a human-readable message from a Manager REST API error, handling
|
||||
* both {@link FetchError} and axios-style `{ response: { data } }` shapes,
|
||||
* including OpenCode config validation issues and removed fields.
|
||||
*/
|
||||
export function getOpenCodeApiErrorMessage(error: unknown, fallback: string): string {
|
||||
if (error instanceof FetchError) {
|
||||
let message = error.detail || error.message || fallback
|
||||
|
||||
if (error.validationIssues && error.validationIssues.length > 0) {
|
||||
const issues = error.validationIssues
|
||||
.map((issue) => `${issue.path}: ${issue.message}`)
|
||||
.join('; ')
|
||||
message = `Validation failed: ${issues}`
|
||||
}
|
||||
|
||||
if (error.removedFields && error.removedFields.length > 0) {
|
||||
message += ` (removed invalid fields: ${error.removedFields.join(', ')})`
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = (error as { response?: { data?: { details?: string; error?: string; validationIssues?: Array<{ path: string; message: string }>; removedFields?: string[] } } }).response
|
||||
const data = response?.data
|
||||
|
||||
let message = data?.details || data?.error || fallback
|
||||
|
||||
if (data?.validationIssues && data.validationIssues.length > 0) {
|
||||
const issues = data.validationIssues
|
||||
.map((issue) => `${issue.path}: ${issue.message}`)
|
||||
.join('; ')
|
||||
message = `Validation failed: ${issues}`
|
||||
}
|
||||
|
||||
if (data?.removedFields && data.removedFields.length > 0) {
|
||||
message += ` (removed invalid fields: ${data.removedFields.join(', ')})`
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
Reference in new issue
Block a user