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
@@ -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>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user