feat: add web update check and installation functionality

This commit is contained in:
Bohdan Triapitsyn
2025-12-19 19:57:18 +02:00
parent bddb174bd3
commit 6323050461
10 changed files with 1137 additions and 21 deletions
@@ -274,6 +274,7 @@ export const Sidebar: React.FC<SidebarProps> = ({ isOpen, isMobile, children })
error={update.error}
onDownload={update.downloadUpdate}
onRestart={update.restartToUpdate}
runtimeType={update.runtimeType}
/>
</div>
</aside>
+192 -11
View File
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useState, useCallback, useEffect } from 'react';
import {
Dialog,
DialogContent,
@@ -6,10 +6,12 @@ import {
DialogTitle,
} from '@/components/ui/dialog';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import { RiDownloadCloudLine, RiDownloadLine, RiExternalLinkLine, RiLoaderLine, RiRestartLine } from '@remixicon/react';
import { RiCheckLine, RiClipboardLine, RiDownloadCloudLine, RiDownloadLine, RiExternalLinkLine, RiLoaderLine, RiRestartLine, RiTerminalLine } from '@remixicon/react';
import { cn } from '@/lib/utils';
import type { UpdateInfo, UpdateProgress } from '@/lib/desktop';
type WebUpdateState = 'idle' | 'updating' | 'restarting' | 'reconnecting' | 'error';
interface UpdateDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
@@ -20,10 +22,45 @@ interface UpdateDialogProps {
error: string | null;
onDownload: () => void;
onRestart: () => void;
/** Runtime type to show different UI for desktop vs web */
runtimeType?: 'desktop' | 'web' | 'vscode' | null;
}
const GITHUB_RELEASES_URL = 'https://github.com/btriapitsyn/openchamber/releases';
async function installWebUpdate(): Promise<{ success: boolean; error?: string }> {
try {
const response = await fetch('/api/openchamber/update-install', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
return { success: false, error: data.error || `Server error: ${response.status}` };
}
return { success: true };
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : 'Failed to install update' };
}
}
async function waitForServerRestart(maxAttempts = 30, intervalMs = 2000): Promise<boolean> {
for (let i = 0; i < maxAttempts; i++) {
try {
const response = await fetch('/health', { method: 'GET' });
if (response.ok) {
return true;
}
} catch {
// Server not ready yet
}
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
return false;
}
export const UpdateDialog: React.FC<UpdateDialogProps> = ({
open,
onOpenChange,
@@ -34,7 +71,12 @@ export const UpdateDialog: React.FC<UpdateDialogProps> = ({
error,
onDownload,
onRestart,
runtimeType = 'desktop',
}) => {
const [copied, setCopied] = useState(false);
const [webUpdateState, setWebUpdateState] = useState<WebUpdateState>('idle');
const [webError, setWebError] = useState<string | null>(null);
const releaseUrl = info?.version
? `${GITHUB_RELEASES_URL}/tag/v${info.version}`
: GITHUB_RELEASES_URL;
@@ -43,13 +85,69 @@ export const UpdateDialog: React.FC<UpdateDialogProps> = ({
? Math.round((progress.downloaded / progress.total) * 100)
: 0;
const isWebRuntime = runtimeType === 'web';
const updateCommand = info?.updateCommand || 'openchamber update';
// Reset state when dialog closes
useEffect(() => {
if (!open) {
setWebUpdateState('idle');
setWebError(null);
}
}, [open]);
const handleCopyCommand = async () => {
try {
await navigator.clipboard.writeText(updateCommand);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
// Clipboard access denied
}
};
const handleWebUpdate = useCallback(async () => {
setWebUpdateState('updating');
setWebError(null);
const result = await installWebUpdate();
if (!result.success) {
setWebUpdateState('error');
setWebError(result.error || 'Update failed');
return;
}
// Server will restart, wait for it to come back
setWebUpdateState('restarting');
// Wait a bit for server to shut down
await new Promise(resolve => setTimeout(resolve, 2000));
setWebUpdateState('reconnecting');
const serverBack = await waitForServerRestart();
if (serverBack) {
// Reload the page to get the new version
window.location.reload();
} else {
setWebUpdateState('error');
setWebError('Server did not restart. Please refresh manually or run: openchamber restart');
}
}, []);
const isWebUpdating = webUpdateState !== 'idle' && webUpdateState !== 'error';
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<Dialog open={open} onOpenChange={isWebUpdating ? undefined : onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<RiDownloadCloudLine className="h-5 w-5 text-primary" />
Update Available
{webUpdateState === 'restarting' || webUpdateState === 'reconnecting'
? 'Updating...'
: 'Update Available'}
</DialogTitle>
</DialogHeader>
@@ -68,7 +166,24 @@ export const UpdateDialog: React.FC<UpdateDialogProps> = ({
</div>
)}
{info?.body && (
{/* Web update progress */}
{isWebRuntime && isWebUpdating && (
<div className="space-y-3">
<div className="flex items-center gap-3">
<RiLoaderLine className="h-5 w-5 animate-spin text-primary" />
<div className="text-sm">
{webUpdateState === 'updating' && 'Installing update...'}
{webUpdateState === 'restarting' && 'Server restarting...'}
{webUpdateState === 'reconnecting' && 'Waiting for server...'}
</div>
</div>
<p className="text-xs text-muted-foreground">
The page will reload automatically when the update is complete.
</p>
</div>
)}
{info?.body && !isWebUpdating && (
<ScrollableOverlay
className="max-h-48 rounded-md border border-border bg-muted/30 p-3"
fillContainer={false}
@@ -92,7 +207,39 @@ export const UpdateDialog: React.FC<UpdateDialogProps> = ({
</ScrollableOverlay>
)}
{downloading && (
{/* Web runtime: show CLI command only on error as fallback */}
{isWebRuntime && webUpdateState === 'error' && (
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<RiTerminalLine className="h-4 w-4" />
<span>Or update via terminal:</span>
</div>
<div className="flex items-center gap-2">
<code className="flex-1 px-3 py-2 bg-muted rounded-md font-mono text-sm text-foreground overflow-x-auto">
{updateCommand}
</code>
<button
onClick={handleCopyCommand}
className={cn(
'flex items-center justify-center p-2 rounded-md',
'text-muted-foreground hover:text-foreground hover:bg-accent',
'transition-colors',
copied && 'text-primary'
)}
title={copied ? 'Copied!' : 'Copy command'}
>
{copied ? (
<RiCheckLine className="h-4 w-4" />
) : (
<RiClipboardLine className="h-4 w-4" />
)}
</button>
</div>
</div>
)}
{/* Desktop runtime: show download progress */}
{!isWebRuntime && downloading && (
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Downloading...</span>
@@ -107,9 +254,9 @@ export const UpdateDialog: React.FC<UpdateDialogProps> = ({
</div>
)}
{error && (
{(error || webError) && (
<div className="p-3 bg-destructive/10 border border-destructive/20 rounded-lg">
<p className="text-sm text-destructive">{error}</p>
<p className="text-sm text-destructive">{error || webError}</p>
</div>
)}
@@ -129,7 +276,8 @@ export const UpdateDialog: React.FC<UpdateDialogProps> = ({
GitHub
</a>
{!downloaded && !downloading && (
{/* Desktop runtime buttons */}
{!isWebRuntime && !downloaded && !downloading && (
<button
onClick={onDownload}
className={cn(
@@ -145,7 +293,7 @@ export const UpdateDialog: React.FC<UpdateDialogProps> = ({
</button>
)}
{downloading && (
{!isWebRuntime && downloading && (
<button
disabled
className={cn(
@@ -160,7 +308,7 @@ export const UpdateDialog: React.FC<UpdateDialogProps> = ({
</button>
)}
{downloaded && (
{!isWebRuntime && downloaded && (
<button
onClick={onRestart}
className={cn(
@@ -175,6 +323,39 @@ export const UpdateDialog: React.FC<UpdateDialogProps> = ({
Restart to Update
</button>
)}
{/* Web runtime: Update Now button */}
{isWebRuntime && !isWebUpdating && (
<button
onClick={handleWebUpdate}
className={cn(
'flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md',
'text-sm font-medium',
'bg-primary text-primary-foreground',
'hover:bg-primary/90',
'transition-colors'
)}
>
<RiDownloadLine className="h-4 w-4" />
Update Now
</button>
)}
{/* Web runtime: updating state */}
{isWebRuntime && isWebUpdating && (
<button
disabled
className={cn(
'flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md',
'text-sm font-medium',
'bg-primary/50 text-primary-foreground',
'cursor-not-allowed'
)}
>
<RiLoaderLine className="h-4 w-4 animate-spin" />
Updating...
</button>
)}
</div>
</div>
</DialogContent>
+64 -4
View File
@@ -4,6 +4,7 @@ import {
downloadDesktopUpdate,
restartToApplyUpdate,
isDesktopRuntime,
isWebRuntime,
type UpdateInfo,
type UpdateProgress,
} from '@/lib/desktop';
@@ -16,6 +17,8 @@ export type UpdateState = {
info: UpdateInfo | null;
progress: UpdateProgress | null;
error: string | null;
/** Runtime type for conditional UI rendering */
runtimeType: 'desktop' | 'web' | 'vscode' | null;
};
export type UseUpdateCheckReturn = UpdateState & {
@@ -58,12 +61,49 @@ const createMockUpdate = (config: MockUpdateConfig): UpdateState => ({
},
progress: null,
error: null,
runtimeType: 'desktop',
});
const shouldMockUpdate = (): boolean => {
return getMockConfig() !== null;
};
/**
* Check for web updates via server API
*/
async function checkForWebUpdates(): Promise<UpdateInfo | null> {
try {
const response = await fetch('/api/openchamber/update-check', {
method: 'GET',
headers: { Accept: 'application/json' },
});
if (!response.ok) {
throw new Error(`Server responded with ${response.status}`);
}
const data = await response.json();
return {
available: data.available ?? false,
version: data.version,
currentVersion: data.currentVersion ?? 'unknown',
body: data.body,
packageManager: data.packageManager,
updateCommand: data.updateCommand,
};
} catch (error) {
console.warn('Failed to check for web updates:', error);
return null;
}
}
function detectRuntimeType(): 'desktop' | 'web' | 'vscode' | null {
if (isDesktopRuntime()) return 'desktop';
if (isWebRuntime()) return 'web';
// VSCode doesn't support updates through this mechanism
return null;
}
export const useUpdateCheck = (checkOnMount = true): UseUpdateCheckReturn => {
const [state, setState] = useState<UpdateState>({
checking: false,
@@ -73,6 +113,7 @@ export const useUpdateCheck = (checkOnMount = true): UseUpdateCheckReturn => {
info: null,
progress: null,
error: null,
runtimeType: null,
});
// Only check mock mode once at startup - no polling
@@ -85,6 +126,12 @@ export const useUpdateCheck = (checkOnMount = true): UseUpdateCheckReturn => {
return null;
});
// Detect runtime type on mount
useEffect(() => {
const runtime = detectRuntimeType();
setState((prev) => ({ ...prev, runtimeType: runtime }));
}, []);
const checkForUpdates = useCallback(async () => {
if (mockMode) {
const config = getMockConfig();
@@ -98,14 +145,23 @@ export const useUpdateCheck = (checkOnMount = true): UseUpdateCheckReturn => {
}
return;
}
if (!isDesktopRuntime()) {
const runtime = detectRuntimeType();
if (!runtime) {
return;
}
setState((prev) => ({ ...prev, checking: true, error: null }));
setState((prev) => ({ ...prev, checking: true, error: null, runtimeType: runtime }));
try {
const info = await checkForDesktopUpdates();
let info: UpdateInfo | null = null;
if (runtime === 'desktop') {
info = await checkForDesktopUpdates();
} else if (runtime === 'web') {
info = await checkForWebUpdates();
}
setState((prev) => ({
...prev,
checking: false,
@@ -144,6 +200,8 @@ export const useUpdateCheck = (checkOnMount = true): UseUpdateCheckReturn => {
return;
}
// For web runtime, there's no download - user runs CLI command
// This is only applicable to desktop
if (!isDesktopRuntime() || !state.available) {
return;
}
@@ -169,6 +227,7 @@ export const useUpdateCheck = (checkOnMount = true): UseUpdateCheckReturn => {
return;
}
// Only applicable to desktop
if (!isDesktopRuntime() || !state.downloaded) {
return;
}
@@ -192,7 +251,8 @@ export const useUpdateCheck = (checkOnMount = true): UseUpdateCheckReturn => {
}, [mockMode]);
useEffect(() => {
if (checkOnMount && (isDesktopRuntime() || mockMode)) {
const runtime = detectRuntimeType();
if (checkOnMount && (runtime === 'desktop' || runtime === 'web' || mockMode)) {
const timer = setTimeout(() => {
checkForUpdates();
}, 3000);
+9
View File
@@ -9,6 +9,9 @@ export type UpdateInfo = {
currentVersion: string;
body?: string;
date?: string;
// Web-specific fields
packageManager?: string;
updateCommand?: string;
};
export type UpdateProgress = {
@@ -71,6 +74,12 @@ export const isVSCodeRuntime = (): boolean => {
return apis?.runtime?.isVSCode === true;
};
export const isWebRuntime = (): boolean => {
if (typeof window === "undefined") return false;
// Web runtime: not desktop, not VSCode
return !isDesktopRuntime() && !isVSCodeRuntime();
};
export const getDesktopApi = (): DesktopApi | null => {
if (!isDesktopRuntime()) {
return null;