mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Add version notifications for new releases (#139)
* Add SSH known hosts support and optimize git status fetching * Add opencode-manager version to health endpoint * Add version notifications for new releases --------- Co-authored-by: Fran Boon <fran@aidiq.com>
This commit is contained in:
1 parent
9562867f1d
commit
b38b9e3aca
15 files changed
+261
-18
No files matched your search
+16
-3
@@ -4,6 +4,7 @@ import { cors } from 'hono/cors'
|
||||
import { serveStatic } from '@hono/node-server/serve-static'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { readFile } from 'fs/promises'
|
||||
import { initializeDatabase } from './db/schema'
|
||||
import { createRepoRoutes } from './routes/repos'
|
||||
import { createIPCServer, type IPCServer } from './ipc/ipcServer'
|
||||
@@ -13,6 +14,17 @@ import { createHealthRoutes } from './routes/health'
|
||||
import { createTTSRoutes, cleanupExpiredCache } from './routes/tts';
|
||||
import { createSTTRoutes } from './routes/stt'
|
||||
import { createFileRoutes } from './routes/files'
|
||||
|
||||
async function getAppVersion(): Promise<string> {
|
||||
try {
|
||||
const packageUrl = new URL('../../package.json', import.meta.url)
|
||||
const packageJsonRaw = await readFile(packageUrl, 'utf-8')
|
||||
const packageJson = JSON.parse(packageJsonRaw) as { version?: string }
|
||||
return packageJson.version ?? 'unknown'
|
||||
} catch {
|
||||
return 'unknown'
|
||||
}
|
||||
}
|
||||
import { createProvidersRoutes } from './routes/providers'
|
||||
import { createOAuthRoutes } from './routes/oauth'
|
||||
import { createTitleRoutes } from './routes/title'
|
||||
@@ -225,12 +237,12 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
|
||||
app.route('/api/auth', createAuthRoutes(auth))
|
||||
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
|
||||
|
||||
app.route('/api/health', createHealthRoutes(db))
|
||||
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(requireAuth))
|
||||
|
||||
const protectedApi = new Hono()
|
||||
protectedApi.use('/*', requireAuth)
|
||||
|
||||
protectedApi.route('/health', createHealthRoutes(db))
|
||||
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService))
|
||||
protectedApi.route('/settings', createSettingsRoutes(db))
|
||||
protectedApi.route('/files', createFileRoutes())
|
||||
@@ -287,10 +299,11 @@ if (isProduction) {
|
||||
return c.html(html)
|
||||
})
|
||||
} else {
|
||||
app.get('/', (c) => {
|
||||
app.get('/', async (c) => {
|
||||
const version = await getAppVersion()
|
||||
return c.json({
|
||||
name: 'OpenCode WebUI',
|
||||
version: '2.0.0',
|
||||
version,
|
||||
status: 'running',
|
||||
endpoints: {
|
||||
health: '/api/health',
|
||||
|
||||
@@ -34,7 +34,6 @@ export class SSHHostKeyHandler implements IPCHandler {
|
||||
this.timeoutMs = timeoutMs
|
||||
const configDir = path.join(getWorkspacePath(), 'config')
|
||||
this.knownHostsPath = path.join(configDir, 'known_hosts')
|
||||
this.ensureKnownHostsFile()
|
||||
logger.info(`SSHHostKeyHandler initialized with timeout=${timeoutMs}ms, known_hosts=${this.knownHostsPath}`)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,91 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { readFile } from 'fs/promises'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
|
||||
const GITHUB_REPO_OWNER = 'chriswritescode-dev'
|
||||
const GITHUB_REPO_NAME = 'opencode-manager'
|
||||
|
||||
function compareVersions(a: string, b: string): number {
|
||||
const cleanA = a.replace(/^v/, '')
|
||||
const cleanB = b.replace(/^v/, '')
|
||||
const partsA = cleanA.split('.').map(Number)
|
||||
const partsB = cleanB.split('.').map(Number)
|
||||
|
||||
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
|
||||
const partA = partsA[i] ?? 0
|
||||
const partB = partsB[i] ?? 0
|
||||
if (partA > partB) return 1
|
||||
if (partA < partB) return -1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
interface CachedRelease {
|
||||
tagName: string
|
||||
htmlUrl: string
|
||||
name: string
|
||||
fetchedAt: number
|
||||
}
|
||||
|
||||
let cachedRelease: CachedRelease | null = null
|
||||
const CACHE_TTL_MS = 60 * 60 * 1000
|
||||
|
||||
async function fetchLatestRelease(): Promise<CachedRelease | null> {
|
||||
if (cachedRelease && Date.now() - cachedRelease.fetchedAt < CACHE_TTL_MS) {
|
||||
return cachedRelease
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://api.github.com/repos/${GITHUB_REPO_OWNER}/${GITHUB_REPO_NAME}/releases/latest`,
|
||||
{
|
||||
headers: {
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'User-Agent': 'OpenCode-Manager'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
return cachedRelease
|
||||
}
|
||||
|
||||
const data = await response.json() as { tag_name?: string; html_url?: string; name?: string }
|
||||
const tagName = data.tag_name ?? '0.0.0'
|
||||
const htmlUrl = data.html_url ?? ''
|
||||
const name = data.name ?? tagName
|
||||
|
||||
cachedRelease = {
|
||||
tagName,
|
||||
htmlUrl,
|
||||
name,
|
||||
fetchedAt: Date.now()
|
||||
}
|
||||
|
||||
return cachedRelease
|
||||
} catch {
|
||||
return cachedRelease
|
||||
}
|
||||
}
|
||||
|
||||
const opencodeManagerVersionPromise = (async (): Promise<string | null> => {
|
||||
try {
|
||||
const packageUrl = new URL('../../../package.json', import.meta.url)
|
||||
const packageJsonRaw = await readFile(packageUrl, 'utf-8')
|
||||
const packageJson = JSON.parse(packageJsonRaw) as { version?: unknown }
|
||||
return typeof packageJson.version === 'string' ? packageJson.version : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
})()
|
||||
|
||||
export function createHealthRoutes(db: Database) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', async (c) => {
|
||||
try {
|
||||
const opencodeManagerVersion = await opencodeManagerVersionPromise
|
||||
const dbCheck = db.prepare('SELECT 1').get()
|
||||
const opencodeHealthy = await opencodeServerManager.checkHealth()
|
||||
const startupError = opencodeServerManager.getLastStartupError()
|
||||
@@ -23,7 +102,8 @@ export function createHealthRoutes(db: Database) {
|
||||
opencodePort: opencodeServerManager.getPort(),
|
||||
opencodeVersion: opencodeServerManager.getVersion(),
|
||||
opencodeMinVersion: opencodeServerManager.getMinVersion(),
|
||||
opencodeVersionSupported: opencodeServerManager.isVersionSupported()
|
||||
opencodeVersionSupported: opencodeServerManager.isVersionSupported(),
|
||||
opencodeManagerVersion,
|
||||
}
|
||||
|
||||
if (startupError && !opencodeHealthy) {
|
||||
@@ -32,9 +112,11 @@ export function createHealthRoutes(db: Database) {
|
||||
|
||||
return c.json(response)
|
||||
} catch (error) {
|
||||
const opencodeManagerVersion = await opencodeManagerVersionPromise
|
||||
return c.json({
|
||||
status: 'unhealthy',
|
||||
timestamp: new Date().toISOString(),
|
||||
opencodeManagerVersion,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
}, 503)
|
||||
}
|
||||
@@ -59,5 +141,41 @@ export function createHealthRoutes(db: Database) {
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/version', async (c) => {
|
||||
const currentVersion = await opencodeManagerVersionPromise
|
||||
const latestRelease = await fetchLatestRelease()
|
||||
|
||||
if (!currentVersion) {
|
||||
return c.json({
|
||||
currentVersion: null,
|
||||
latestVersion: null,
|
||||
updateAvailable: false,
|
||||
releaseUrl: null,
|
||||
releaseName: null
|
||||
})
|
||||
}
|
||||
|
||||
if (!latestRelease) {
|
||||
return c.json({
|
||||
currentVersion,
|
||||
latestVersion: null,
|
||||
updateAvailable: false,
|
||||
releaseUrl: null,
|
||||
releaseName: null
|
||||
})
|
||||
}
|
||||
|
||||
const latestVersion = latestRelease.tagName.replace(/^v/, '')
|
||||
const isUpdateAvailable = compareVersions(currentVersion, latestVersion) < 0
|
||||
|
||||
return c.json({
|
||||
currentVersion,
|
||||
latestVersion,
|
||||
updateAvailable: isUpdateAvailable,
|
||||
releaseUrl: latestRelease.htmlUrl,
|
||||
releaseName: latestRelease.name
|
||||
})
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -45,17 +45,25 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS
|
||||
return c.json({ error: 'repoIds must be an array of numbers' }, 400)
|
||||
}
|
||||
|
||||
const statuses = await Promise.all(
|
||||
repoIds.map(async (id) => {
|
||||
try {
|
||||
const status = await git.getStatus(id, database)
|
||||
return [id, status]
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to get git status for repo ${id}:`, error)
|
||||
return null
|
||||
}
|
||||
})
|
||||
)
|
||||
const BATCH_CONCURRENCY = 3
|
||||
const results: Array<[number, GitStatusResponse] | null> = []
|
||||
for (let i = 0; i < repoIds.length; i += BATCH_CONCURRENCY) {
|
||||
const batch = repoIds.slice(i, i + BATCH_CONCURRENCY)
|
||||
const batchResults = await Promise.all(
|
||||
batch.map(async (id) => {
|
||||
try {
|
||||
const status = await git.getStatus(id, database)
|
||||
return [id, status] as [number, GitStatusResponse]
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to get git status for repo ${id}:`, error)
|
||||
return null
|
||||
}
|
||||
})
|
||||
)
|
||||
results.push(...batchResults)
|
||||
}
|
||||
|
||||
const statuses = results
|
||||
|
||||
const resultMap: Record<number, GitStatusResponse> = {}
|
||||
for (const entry of statuses) {
|
||||
@@ -65,6 +73,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return c.json(resultMap)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get batch git status:', error)
|
||||
@@ -371,4 +380,4 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
}
|
||||
@@ -170,6 +170,14 @@ export class GitAuthService {
|
||||
Object.assign(env, this.askpassHandler.getEnv())
|
||||
}
|
||||
|
||||
if (this.sshHostKeyHandler) {
|
||||
const knownHostsPath = this.sshHostKeyHandler.getKnownHostsPath()
|
||||
if (knownHostsPath) {
|
||||
env.GIT_SSH_COMMAND = buildSSHCommandWithKnownHosts(knownHostsPath)
|
||||
Object.assign(env, this.sshHostKeyHandler.getEnv())
|
||||
}
|
||||
}
|
||||
|
||||
return env
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { Login } from './pages/Login'
|
||||
import { Register } from './pages/Register'
|
||||
import { Setup } from './pages/Setup'
|
||||
import { SettingsDialog } from './components/settings/SettingsDialog'
|
||||
import { VersionNotifier } from './components/VersionNotifier'
|
||||
import { useTheme } from './hooks/useTheme'
|
||||
import { TTSProvider } from './contexts/TTSContext'
|
||||
import { AuthProvider } from './contexts/AuthContext'
|
||||
@@ -82,6 +83,7 @@ function AppShell() {
|
||||
<PermissionDialogWrapper />
|
||||
<SSHHostKeyDialogWrapper />
|
||||
<SettingsDialog />
|
||||
<VersionNotifier />
|
||||
<Toaster
|
||||
position="bottom-right"
|
||||
expand={false}
|
||||
|
||||
@@ -206,4 +206,16 @@ export const settingsApi = {
|
||||
body: JSON.stringify({ content }),
|
||||
})
|
||||
},
|
||||
|
||||
getVersionInfo: async (): Promise<VersionInfo> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/health/version`)
|
||||
},
|
||||
}
|
||||
|
||||
export interface VersionInfo {
|
||||
currentVersion: string | null
|
||||
latestVersion: string | null
|
||||
updateAvailable: boolean
|
||||
releaseUrl: string | null
|
||||
releaseName: string | null
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { useVersionCheck } from '@/hooks/useVersionCheck'
|
||||
|
||||
export function VersionNotifier() {
|
||||
const { data, isSuccess } = useVersionCheck()
|
||||
const hasNotifiedRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSuccess || !data || hasNotifiedRef.current) return
|
||||
|
||||
if (data.updateAvailable && data.latestVersion && data.releaseUrl) {
|
||||
hasNotifiedRef.current = true
|
||||
showToast.info(`OpenCode Manager v${data.latestVersion} is available`, {
|
||||
description: 'A new version is ready to install.',
|
||||
action: {
|
||||
label: 'View Release',
|
||||
onClick: () => window.open(data.releaseUrl ?? '', '_blank'),
|
||||
},
|
||||
duration: 10000,
|
||||
})
|
||||
}
|
||||
}, [isSuccess, data])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -35,6 +35,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['repos'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['reposGitStatus'] })
|
||||
setRepoUrl('')
|
||||
setLocalPath('')
|
||||
setBranch('')
|
||||
|
||||
@@ -111,12 +111,15 @@ export function RepoList() {
|
||||
queryKey: ["reposGitStatus", repoIds],
|
||||
queryFn: () => fetchReposGitStatus(repoIds),
|
||||
enabled: repoIds.length > 0,
|
||||
staleTime: 60 * 60 * 1000,
|
||||
gcTime: 60 * 60 * 1000,
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: deleteRepo,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["repos"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["reposGitStatus"] })
|
||||
setDeleteDialogOpen(false)
|
||||
setRepoToDelete(null)
|
||||
},
|
||||
@@ -128,6 +131,7 @@ export function RepoList() {
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["repos"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["reposGitStatus"] })
|
||||
setDeleteDialogOpen(false)
|
||||
setSelectedRepos(new Set())
|
||||
},
|
||||
@@ -155,6 +159,7 @@ export function RepoList() {
|
||||
},
|
||||
onSettled: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["repos"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["reposGitStatus"] })
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { useVersionCheck } from '@/hooks/useVersionCheck'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
@@ -6,6 +7,7 @@ import { Switch } from '@/components/ui/switch'
|
||||
|
||||
export function GeneralSettings() {
|
||||
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
|
||||
const { data: versionInfo, isLoading: isVersionLoading } = useVersionCheck()
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -20,6 +22,31 @@ export function GeneralSettings() {
|
||||
<h2 className="text-lg font-semibold text-foreground mb-6">General Preferences</h2>
|
||||
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-center gap-3 py-3">
|
||||
<span className="text-sm text-muted-foreground">OpenCode Manager</span>
|
||||
{isVersionLoading ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />
|
||||
) : versionInfo?.currentVersion ? (
|
||||
<>
|
||||
<span className="text-sm font-mono bg-muted px-2 py-0.5 rounded">
|
||||
{versionInfo.currentVersion}
|
||||
</span>
|
||||
{versionInfo.updateAvailable && versionInfo.latestVersion && (
|
||||
<a
|
||||
href={versionInfo.releaseUrl ?? ''}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs font-medium text-green-500 hover:text-green-400 transition-colors"
|
||||
>
|
||||
v{versionInfo.latestVersion} available
|
||||
</a>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">unknown</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="theme">Theme</Label>
|
||||
<Select
|
||||
|
||||
@@ -343,7 +343,12 @@ export function OpenCodeConfigManager() {
|
||||
)}
|
||||
{health.opencodeVersion && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
v{health.opencodeVersion}
|
||||
OpenCode v{health.opencodeVersion}
|
||||
</p>
|
||||
)}
|
||||
{health.opencodeManagerVersion && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Manager v{health.opencodeManagerVersion}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -38,6 +38,7 @@ export function BranchesTab({ repoId, currentBranch, repoUrl, isRepoWorktree }:
|
||||
onSuccess: (updatedRepo) => {
|
||||
queryClient.setQueryData(['repo', repoId], updatedRepo)
|
||||
queryClient.invalidateQueries({ queryKey: ['repos'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['reposGitStatus'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['gitStatus', repoId] })
|
||||
refetch()
|
||||
showToast.success(`Switched to branch: ${updatedRepo.currentBranch}`)
|
||||
@@ -55,6 +56,7 @@ export function BranchesTab({ repoId, currentBranch, repoUrl, isRepoWorktree }:
|
||||
mutationFn: (branch: string) => createRepo(repoUrl || undefined, undefined, branch, undefined, true),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['repos'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['reposGitStatus'] })
|
||||
setNewBranchName('')
|
||||
setIsCreating(false)
|
||||
setUseWorktree(false)
|
||||
|
||||
@@ -14,6 +14,7 @@ interface HealthResponse {
|
||||
opencodeVersion: string | null
|
||||
opencodeMinVersion: string
|
||||
opencodeVersionSupported: boolean
|
||||
opencodeManagerVersion: string | null
|
||||
error?: string
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { settingsApi, type VersionInfo } from '@/api/settings'
|
||||
|
||||
async function fetchVersionInfo(): Promise<VersionInfo> {
|
||||
return settingsApi.getVersionInfo()
|
||||
}
|
||||
|
||||
export function useVersionCheck() {
|
||||
return useQuery({
|
||||
queryKey: ['version-check'],
|
||||
queryFn: fetchVersionInfo,
|
||||
staleTime: Infinity,
|
||||
retry: false,
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user