From da8bbce62a7c2aac546e2d2dd0e69b1d97d4071a Mon Sep 17 00:00:00 2001 From: markmorado Date: Thu, 20 Aug 2026 02:04:15 +0500 Subject: [PATCH] fix: console viewport sizing and add VNC control toolbar Fix nested h-screen flexbox layout bug that let the noVNC canvas overflow below the viewport until the browser zoom level was changed (missing min-h-0 on flex children). Also add a fuller console control bar: power menu (reboot/shutdown/hard reset/hard stop), extra-keys menu (Ctrl+Alt+Del, Ctrl+Alt+Backspace, Tab, Esc, Ctrl+Alt+F1-F12), scale toggle, clipboard paste to guest, and console screenshot. Adds a VM hard-reset backend action (qemu status/reset) alongside the existing start/stop/restart/shutdown. --- backend/app/api/proxmox/vms.py | 13 +- backend/app/proxmox/mixins/vm.py | 12 + frontend/src/features/console/ConsolePage.tsx | 291 ++++++++++++++++-- frontend/src/locales/en.json | 23 +- frontend/src/locales/ru.json | 23 +- 5 files changed, 335 insertions(+), 27 deletions(-) diff --git a/backend/app/api/proxmox/vms.py b/backend/app/api/proxmox/vms.py index 927998d..ccc6a1d 100644 --- a/backend/app/api/proxmox/vms.py +++ b/backend/app/api/proxmox/vms.py @@ -3949,16 +3949,17 @@ def control_vm( db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ): - """Управление VM (start/stop/restart/shutdown)""" - if action not in ['start', 'stop', 'restart', 'shutdown']: + """Управление VM (start/stop/restart/shutdown/reset)""" + if action not in ['start', 'stop', 'restart', 'shutdown', 'reset']: raise HTTPException(status_code=400, detail="Invalid action") - + # Проверка прав в зависимости от действия permission_map = { 'start': 'vm:start', 'stop': 'vm:stop', 'shutdown': 'vm:stop', 'restart': 'vm:restart', + 'reset': 'vm:restart', } if not current_user.has_permission(permission_map[action]): raise HTTPException( @@ -4000,6 +4001,9 @@ def control_vm( elif action == 'shutdown': upid = client.shutdown_vm(node, vmid) success = bool(upid) + elif action == 'reset': + upid = client.reset_vm(node, vmid) + success = bool(upid) else: # restart upid = client.restart_vm(node, vmid) success = bool(upid) @@ -4007,7 +4011,7 @@ def control_vm( action_name = 'kill' if action == 'stop' and force else action if success: # Immediately update vm_instances cache so page refresh returns correct status - expected_status = 'running' if action in ('start', 'restart') else 'stopped' + expected_status = 'running' if action in ('start', 'restart', 'reset') else 'stopped' try: cached_vm = db.query(VMInstance).filter( VMInstance.server_id == server_id, @@ -4026,6 +4030,7 @@ def control_vm( 'start': f"Запуск VM {vm_name or vmid}", 'stop': f"Остановка VM {vm_name or vmid}", 'restart': f"Перезапуск VM {vm_name or vmid}", + 'reset': f"Жёсткий сброс VM {vm_name or vmid}", } try: ProxmoxTaskService.register( diff --git a/backend/app/proxmox/mixins/vm.py b/backend/app/proxmox/mixins/vm.py index 5f22283..0adf063 100644 --- a/backend/app/proxmox/mixins/vm.py +++ b/backend/app/proxmox/mixins/vm.py @@ -41,6 +41,18 @@ class VmMixin: logger.error(f"Ошибка перезапуска VM {vmid} на {node}: {e}") return None + def reset_vm(self, node: str, vmid: int) -> Optional[str]: + """Жёсткий сброс VM (аналог кнопки Reset — без ACPI, без остановки/старта заново).""" + if not self.proxmox: + return None + + try: + upid = self.proxmox.nodes(node).qemu(vmid).status.reset.post() + return upid if isinstance(upid, str) else None + except Exception as e: + logger.error(f"Ошибка жёсткого сброса VM {vmid} на {node}: {e}") + return None + def _wait_vm_stopped(self, node: str, vmid: int, timeout: int) -> bool: """Опрашивать статус ВМ, пока не 'stopped' или не выйдет timeout секунд.""" deadline = time.time() + timeout diff --git a/frontend/src/features/console/ConsolePage.tsx b/frontend/src/features/console/ConsolePage.tsx index b77fedf..e215717 100644 --- a/frontend/src/features/console/ConsolePage.tsx +++ b/frontend/src/features/console/ConsolePage.tsx @@ -1,13 +1,63 @@ import { useEffect, useRef, useState, useCallback } from 'react'; import { useTranslation } from 'react-i18next'; import { useParams, useSearchParams } from 'react-router'; -import { Maximize, Minimize, Keyboard, Loader2 } from 'lucide-react'; +import { + Maximize, + Minimize, + Keyboard, + Loader2, + Power, + ChevronDown, + RotateCw, + PowerOff, + Zap, + Square, + ClipboardPaste, + Camera, + Scan, +} from 'lucide-react'; +import { toast } from 'sonner'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; import { apiClient } from '@/lib/api-client'; import { vmTypeLabel } from '@/lib/format'; +import { usePowerAction } from '@/hooks/use-instances'; import '@xterm/xterm/css/xterm.css'; +// X11 keysyms используемые доп. клавишами консоли (см. noVNC core/input/keysym.js) +const KEYSYM = { + BackSpace: 0xff08, + Tab: 0xff09, + Escape: 0xff1b, + Delete: 0xffff, + Control_L: 0xffe3, + Alt_L: 0xffe9, + F1: 0xffbe, +} as const; +const FKEY_CODES = Array.from({ length: 12 }, (_, i) => ({ + label: `F${i + 1}`, + keysym: KEYSYM.F1 + i, + code: `F${i + 1}`, +})); + // noVNC and xterm.js will be loaded dynamically // We use dynamic imports for code splitting @@ -23,6 +73,14 @@ interface VNCData { auth_ticket?: string; } +interface RFBHandle { + disconnect: () => void; + sendCtrlAltDel: () => void; + sendKey: (keysym: number, code: string, down?: boolean) => void; + clipboardPasteFrom: (text: string) => void; + scaleViewport: boolean; +} + export default function ConsolePage() { const { serverId, vmid } = useParams<{ serverId: string; vmid: string }>(); const [searchParams] = useSearchParams(); @@ -30,18 +88,25 @@ export default function ConsolePage() { const node = searchParams.get('node') || ''; const type = searchParams.get('type') || 'qemu'; const isSerial = type === 'qemu' && searchParams.get('mode') === 'serial'; + // Панель управления питанием/консолью доступна для VNC (qemu, не serial); для + // serial и LXC-терминала клавиатура и буфер обмена уже идут через сам xterm. + const isVnc = type === 'qemu' && !isSerial; const [status, setStatus] = useState<'connecting' | 'connected' | 'error'>('connecting'); const [errorMsg, setErrorMsg] = useState(''); const [isFullscreen, setIsFullscreen] = useState(false); + const [scaleToFit, setScaleToFit] = useState(true); + const [clipboardOpen, setClipboardOpen] = useState(false); + const [clipboardText, setClipboardText] = useState(''); const containerRef = useRef(null); - const rfbRef = useRef(null); + const rfbRef = useRef(null); const termRef = useRef(null); const wsRef = useRef(null); const keepaliveRef = useRef | null>(null); const sid = Number(serverId); const vid = Number(vmid); + const power = usePowerAction(sid, vid, type, node); // ==================== VNC Console (QEMU) ==================== const connectVNC = useCallback(async () => { @@ -92,7 +157,7 @@ export default function ConsolePage() { }); rfb.scaleViewport = true; - rfb.resizeSession = true; + rfb.resizeSession = false; rfb.addEventListener('connect', () => { setStatus('connected'); @@ -108,7 +173,8 @@ export default function ConsolePage() { } }); - rfbRef.current = rfb; + rfbRef.current = rfb as RFBHandle; + setScaleToFit(true); } catch (err) { setStatus('error'); setErrorMsg(err instanceof Error ? err.message : 'Failed to connect'); @@ -253,13 +319,87 @@ export default function ConsolePage() { // ==================== Send Ctrl+Alt+Del (VNC) ==================== const sendCtrlAltDel = () => { - if (rfbRef.current) { - (rfbRef.current as { sendCtrlAltDel: () => void }).sendCtrlAltDel(); + rfbRef.current?.sendCtrlAltDel(); + }; + + // ==================== Extra keys (VNC) ==================== + const sendKeyCombo = (keysym: number, code: string) => { + rfbRef.current?.sendKey(keysym, code); + }; + const sendCtrlAltBackspace = () => { + const rfb = rfbRef.current; + if (!rfb) return; + rfb.sendKey(KEYSYM.Control_L, 'ControlLeft', true); + rfb.sendKey(KEYSYM.Alt_L, 'AltLeft', true); + rfb.sendKey(KEYSYM.BackSpace, 'Backspace', true); + rfb.sendKey(KEYSYM.BackSpace, 'Backspace', false); + rfb.sendKey(KEYSYM.Alt_L, 'AltLeft', false); + rfb.sendKey(KEYSYM.Control_L, 'ControlLeft', false); + }; + const sendCtrlAltF = (keysym: number, code: string) => { + const rfb = rfbRef.current; + if (!rfb) return; + rfb.sendKey(KEYSYM.Control_L, 'ControlLeft', true); + rfb.sendKey(KEYSYM.Alt_L, 'AltLeft', true); + rfb.sendKey(keysym, code, true); + rfb.sendKey(keysym, code, false); + rfb.sendKey(KEYSYM.Alt_L, 'AltLeft', false); + rfb.sendKey(KEYSYM.Control_L, 'ControlLeft', false); + }; + + // ==================== Scale toggle (VNC) ==================== + const toggleScale = () => { + const rfb = rfbRef.current; + if (!rfb) return; + const next = !scaleToFit; + rfb.scaleViewport = next; + setScaleToFit(next); + }; + + // ==================== Clipboard → VM (VNC) ==================== + const sendClipboard = () => { + if (!clipboardText) return; + rfbRef.current?.clipboardPasteFrom(clipboardText); + setClipboardOpen(false); + setClipboardText(''); + }; + + // ==================== Screenshot ==================== + const takeScreenshot = () => { + // querySelectorAll + last(): в dev-режиме React StrictMode временно + // монтирует RFB дважды, оставляя осиротевший canvas первым в DOM — + // актуальный (живой) canvas всегда последний. + const canvases = containerRef.current?.querySelectorAll('canvas'); + const canvas = canvases && canvases.length > 0 ? canvases[canvases.length - 1] : null; + if (!canvas) { + toast.error(t('console.screenshot_failed')); + return; } + const link = document.createElement('a'); + link.download = `console-${type}-${vmid}-${Date.now()}.png`; + link.href = canvas.toDataURL('image/png'); + link.click(); + }; + + // ==================== Power actions ==================== + const runPowerAction = (action: 'restart' | 'shutdown' | 'reset' | 'stop', force?: boolean) => { + if ( + (action === 'reset' || (action === 'stop' && force)) && + !window.confirm(action === 'reset' ? t('console.confirm_hard_reset') : t('console.confirm_hard_stop')) + ) { + return; + } + power.mutate( + { action, force }, + { + onSuccess: () => toast.success(t('console.action_sent')), + onError: (err) => toast.error(err.message || t('console.action_failed')), + } + ); }; return ( -
+
{/* Toolbar */}
@@ -281,20 +421,103 @@ export default function ConsolePage() {
- {type === 'qemu' && !isSerial && ( - - )} {isSerial && ( serial )} + + {/* Power menu */} + + }> + + {t('console.power')} + + + + runPowerAction('restart')}> + + {t('console.reboot')} + + runPowerAction('shutdown')}> + + {t('console.shutdown')} + + + {type === 'qemu' && ( + runPowerAction('reset')}> + + {t('console.hard_reset')} + + )} + runPowerAction('stop', true)}> + + {t('console.hard_stop')} + + + + + {isVnc && ( + <> + {/* Extra keys menu */} + + }> + + {t('console.extra_keys')} + + + + {t('console.ctrl_alt_del')} + {t('console.ctrl_alt_backspace')} + sendKeyCombo(KEYSYM.Tab, 'Tab')}>Tab + sendKeyCombo(KEYSYM.Escape, 'Escape')}>Esc + + + Ctrl+Alt+F1…F12 + + {FKEY_CODES.map((k) => ( + sendCtrlAltF(k.keysym, k.code)}> + {k.label} + + ))} + + + + + + {/* Scale toggle */} + + + {/* Clipboard */} + + + {/* Screenshot */} + + + )} +
+ + + + + {t('console.clipboard_title')} + + {t('console.clipboard_desc')} + +