feat(instances): add VM owner assignment and snapshot archive view
All checks were successful
Deploy to Production / Trigger production update (push) Successful in 8s

Surface two previously-unused admin endpoints: assign/clear a VM's owner from
the instance Settings tab, and a /instances/snapshot-archives page listing
snapshots preserved from deleted guests (with config detail), linked from the
Instances header for admins.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-14 18:55:47 +05:00
parent dc95d39465
commit bc462c9f8e
7 changed files with 282 additions and 5 deletions

View File

@@ -67,6 +67,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import { StatusDot } from '@/components/shared/status-dot';
import { useVirtualMachines, useBulkOperation, usePowerAction, useVMStatusSync, useInstancesMetricsSync } from '@/hooks/use-instances';
import { useServers } from '@/hooks/use-nodes';
import { useProfile } from '@/hooks/use-settings';
import { formatBytes, vmTypeLabel, formatUptime } from '@/lib/format';
import { apiClient } from '@/lib/api-client';
import { useDeployTasksStore } from '@/stores/deploy-tasks-store';
@@ -258,6 +259,7 @@ export default function InstancesPage() {
}, [activeTasks.length, activeTasks.map((t) => t.id).join(',')]);
const { data: servers = [] } = useServers();
const { data: profile } = useProfile();
const [search, setSearch] = useState('');
const [statusFilter, setStatusFilter] = useState<string>('all');
@@ -664,10 +666,18 @@ export default function InstancesPage() {
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-[22px] font-semibold">{t('nav.instances', 'Instances')}</h1>
<Button render={<Link to="/instances/create" />} size="sm">
<Plus className="mr-1.5 h-4 w-4" />
{t('instances.create', 'Create Instance')}
</Button>
<div className="flex items-center gap-2">
{profile?.is_admin && (
<Button render={<Link to="/instances/snapshot-archives" />} size="sm" variant="outline">
<Camera className="mr-1.5 h-4 w-4" />
{t('snap_archive.title')}
</Button>
)}
<Button render={<Link to="/instances/create" />} size="sm">
<Plus className="mr-1.5 h-4 w-4" />
{t('instances.create', 'Create Instance')}
</Button>
</div>
</div>
{/* Type Tabs */}

View File

@@ -0,0 +1,112 @@
import { useState } from 'react';
import { Link } from 'react-router';
import { useTranslation } from 'react-i18next';
import { ArrowLeft, Camera, Eye } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { useSnapshotArchives, useSnapshotArchiveDetail } from '@/hooks/use-instances';
export default function SnapshotArchivesPage() {
const { t } = useTranslation();
const { data, isLoading } = useSnapshotArchives({ limit: 200 });
const [detailId, setDetailId] = useState<number | null>(null);
const { data: detail } = useSnapshotArchiveDetail(detailId);
const archives = data?.archives ?? [];
return (
<div className="space-y-6">
<div className="flex items-center gap-3">
<Button render={<Link to="/instances" />} variant="ghost" size="sm"><ArrowLeft className="h-4 w-4" /></Button>
<div>
<h1 className="text-2xl font-bold flex items-center gap-2"><Camera className="h-6 w-6" />{t('snap_archive.title')}</h1>
<p className="text-sm text-muted-foreground">{t('snap_archive.subtitle')}</p>
</div>
{data && <Badge variant="secondary" className="ml-auto">{data.total}</Badge>}
</div>
<Card>
<CardContent className="p-0">
{isLoading ? (
<p className="py-12 text-center text-sm text-muted-foreground">{t('common.loading')}</p>
) : archives.length === 0 ? (
<div className="py-16 text-center text-muted-foreground">
<Camera className="mx-auto h-12 w-12 mb-3 opacity-50" />
<p>{t('snap_archive.empty')}</p>
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>{t('snap_archive.snapshot')}</TableHead>
<TableHead>VM</TableHead>
<TableHead>{t('nodes.title')}</TableHead>
<TableHead>{t('snap_archive.deleted_by')}</TableHead>
<TableHead>{t('snap_archive.archived_at')}</TableHead>
<TableHead className="text-right">{t('common.actions')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{archives.map(a => (
<TableRow key={a.id}>
<TableCell className="font-mono font-medium">
{a.snapname}
{a.description && <p className="text-xs text-muted-foreground font-sans">{a.description}</p>}
</TableCell>
<TableCell>
<span className="text-sm">{a.vm_name || '—'}</span>
<span className="ml-1 text-xs text-muted-foreground">#{a.vmid}</span>
{a.vm_type && <Badge variant="outline" className="ml-2 text-[10px]">{a.vm_type === 'qemu' ? 'VM' : 'LXC'}</Badge>}
</TableCell>
<TableCell className="text-xs text-muted-foreground">{a.server_name || a.server_id}{a.node ? ` / ${a.node}` : ''}</TableCell>
<TableCell className="text-xs">{a.deleted_by || '—'}</TableCell>
<TableCell className="text-xs text-muted-foreground">{a.archived_at ? new Date(a.archived_at).toLocaleString() : '—'}</TableCell>
<TableCell className="text-right">
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setDetailId(a.id)}>
<Eye className="h-3.5 w-3.5" />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
<Dialog open={detailId != null} onOpenChange={(v) => { if (!v) setDetailId(null); }}>
<DialogContent>
<DialogHeader><DialogTitle>{detail?.snapname || t('snap_archive.title')}</DialogTitle></DialogHeader>
{detail && (
<div className="space-y-2 text-sm">
<Row label="VM" value={`${detail.vm_name || ''} #${detail.vmid} (${detail.vm_type})`} />
<Row label={t('nodes.title')} value={`${detail.server_name || detail.server_id}${detail.node ? ` / ${detail.node}` : ''}`} />
{detail.parent && <Row label={t('snap_archive.parent')} value={detail.parent} />}
<Row label={t('snap_archive.deleted_by')} value={detail.deleted_by || '—'} />
{detail.deletion_reason && <Row label={t('snap_archive.reason')} value={detail.deletion_reason} />}
<Row label={t('snap_archive.archived_at')} value={detail.archived_at ? new Date(detail.archived_at).toLocaleString() : '—'} />
{detail.snapshot_config && (
<div>
<p className="mb-1 text-xs font-medium text-muted-foreground">{t('snap_archive.config')}</p>
<pre className="max-h-64 overflow-auto rounded-md bg-muted p-3 text-xs whitespace-pre-wrap">{detail.snapshot_config}</pre>
</div>
)}
</div>
)}
</DialogContent>
</Dialog>
</div>
);
}
function Row({ label, value }: { label: string; value: string }) {
return (
<div className="flex gap-2">
<span className="w-32 shrink-0 text-muted-foreground">{label}</span>
<span className="font-mono">{value}</span>
</div>
);
}

View File

@@ -5,7 +5,9 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useVMConfig, useUpdateConfig, useResizeDisk } from '@/hooks/use-instances';
import { useVMConfig, useUpdateConfig, useResizeDisk, useVMOwner, useSetVMOwner } from '@/hooks/use-instances';
import { useProfile } from '@/hooks/use-settings';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { toast } from 'sonner';
interface Props {
@@ -15,6 +17,58 @@ interface Props {
node: string;
}
const OWNER_NONE = '__none__';
function OwnerCard({ serverId, vmid }: { serverId: number; vmid: number }) {
const { t } = useTranslation();
const { data: profile } = useProfile();
const isAdmin = !!profile?.is_admin;
const { data: owner } = useVMOwner(serverId, vmid, isAdmin);
const setOwner = useSetVMOwner(serverId, vmid);
const [selected, setSelected] = useState<string | null>(null);
if (!isAdmin) return null;
const current = owner?.owner_id != null ? String(owner.owner_id) : OWNER_NONE;
const value = selected ?? current;
const handleSave = () => {
const userId = value === OWNER_NONE ? null : Number(value);
setOwner.mutate(userId, {
onSuccess: () => { toast.success(t('instances.owner_saved')); setSelected(null); },
onError: (e: Error) => toast.error(e.message),
});
};
return (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-semibold flex items-center gap-2">
<Settings className="h-4 w-4" />{t('instances.owner')}
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex items-end gap-2">
<div className="flex-1">
<Label>{t('instances.owner')}</Label>
<Select value={value} onValueChange={v => { if (v) setSelected(v); }}>
<SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={OWNER_NONE}>{t('instances.no_owner')}</SelectItem>
{(owner?.users ?? []).map(u => (
<SelectItem key={u.id} value={String(u.id)}>{u.username}{u.full_name ? ` (${u.full_name})` : ''}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button size="sm" onClick={handleSave} disabled={setOwner.isPending || value === current}>{t('common.save')}</Button>
</div>
<p className="text-xs text-muted-foreground">{t('instances.owner_hint')}</p>
</CardContent>
</Card>
);
}
export default function SettingsTab({ serverId, vmid, type, node }: Props) {
const { t } = useTranslation();
const { data: config } = useVMConfig(serverId, vmid, type, node);
@@ -66,6 +120,8 @@ export default function SettingsTab({ serverId, vmid, type, node }: Props) {
return (
<div className="space-y-6 max-w-2xl">
<OwnerCard serverId={serverId} vmid={vmid} />
{/* CPU & Memory */}
<Card>
<CardHeader className="pb-2">

View File

@@ -213,6 +213,73 @@ export function useRollbackSnapshot(serverId: number, vmid: number, type: string
});
}
// ==================== Owner (admin) ====================
export interface VMOwnerInfo {
owner_id: number | null;
owner: { id: number; username: string; full_name?: string } | null;
users: { id: number; username: string; full_name?: string }[];
}
export function useVMOwner(serverId: number, vmid: number, enabled = true) {
return useQuery<VMOwnerInfo>({
queryKey: ['vm-owner', serverId, vmid],
queryFn: () => apiClient.get(`/proxmox/api/${serverId}/vm/${vmid}/owner`),
enabled: enabled && serverId > 0 && vmid > 0,
retry: false,
});
}
export function useSetVMOwner(serverId: number, vmid: number) {
const qc = useQueryClient();
return useMutation({
mutationFn: (user_id: number | null) =>
apiClient.put(`/proxmox/api/${serverId}/vm/${vmid}/owner`, { user_id }),
onSuccess: () => qc.invalidateQueries({ queryKey: ['vm-owner', serverId, vmid] }),
});
}
// ==================== Snapshot archives (admin audit) ====================
export interface SnapshotArchive {
id: number;
server_id: number;
server_name?: string;
vmid: number;
vm_name?: string;
vm_type?: string;
node?: string;
snapname: string;
description?: string;
snaptime?: number;
parent?: string;
vmstate?: number;
snapshot_config?: string;
deleted_by?: string;
deletion_reason?: string;
archived_at?: string;
}
export function useSnapshotArchives(params?: { server_id?: number; vmid?: number; limit?: number; offset?: number }) {
const qs = new URLSearchParams();
if (params?.server_id) qs.set('server_id', String(params.server_id));
if (params?.vmid) qs.set('vmid', String(params.vmid));
if (params?.limit) qs.set('limit', String(params.limit));
if (params?.offset) qs.set('offset', String(params.offset));
return useQuery<{ total: number; offset: number; limit: number; archives: SnapshotArchive[] }>({
queryKey: ['snapshot-archives', params],
queryFn: () => apiClient.get(`/proxmox/api/snapshot-archives?${qs}`),
});
}
export function useSnapshotArchiveDetail(archiveId: number | null) {
return useQuery<SnapshotArchive>({
queryKey: ['snapshot-archive', archiveId],
queryFn: () => apiClient.get(`/proxmox/api/snapshot-archives/${archiveId}`),
enabled: !!archiveId,
});
}
// ==================== Power Actions ====================
interface PowerActionResult {
status: string;

View File

@@ -160,8 +160,23 @@
"placeholder_disk": "scsi0",
"placeholder_notes": "Описание / заметки об инстансе..."
},
"snap_archive": {
"title": "Snapshot archive",
"subtitle": "Snapshots preserved from deleted VMs/containers",
"empty": "No archived snapshots",
"snapshot": "Snapshot",
"deleted_by": "Deleted by",
"archived_at": "Archived at",
"parent": "Parent",
"reason": "Reason",
"config": "Snapshot config"
},
"instances": {
"create": "Create Instance",
"owner": "Owner",
"no_owner": "No owner",
"owner_saved": "Owner updated",
"owner_hint": "Assign this instance to a user (admin only).",
"search_placeholder": "Search by name, IP, or VMID...",
"all_statuses": "All statuses",
"all_nodes": "All nodes",

View File

@@ -160,8 +160,23 @@
"placeholder_disk": "scsi0",
"placeholder_notes": "Описание / заметки об инстансе..."
},
"snap_archive": {
"title": "Архив снапшотов",
"subtitle": "Снапшоты, сохранённые от удалённых VM/контейнеров",
"empty": "Архивных снапшотов нет",
"snapshot": "Снапшот",
"deleted_by": "Удалил",
"archived_at": "Заархивирован",
"parent": "Родитель",
"reason": "Причина",
"config": "Конфиг снапшота"
},
"instances": {
"create": "Создать инстанс",
"owner": "Владелец",
"no_owner": "Без владельца",
"owner_saved": "Владелец обновлён",
"owner_hint": "Назначить инстанс пользователю (только админ).",
"search_placeholder": "Поиск по имени, IP или VMID...",
"all_statuses": "Все статусы",
"all_nodes": "Все узлы",

View File

@@ -8,6 +8,7 @@ import LoginPage from '@/features/auth/LoginPage';
import DashboardPage from '@/features/dashboard/DashboardPage';
import InstancesPage from '@/features/instances/InstancesPage';
import InstanceDetailPage from '@/features/instances/InstanceDetailPage';
const SnapshotArchivesPage = lazy(() => import('./features/instances/SnapshotArchivesPage.tsx'));
import ConsolePage from '@/features/console/ConsolePage';
// Lazy-loaded pages
@@ -67,6 +68,7 @@ export const router = createBrowserRouter([
{ path: '/dashboard', element: <DashboardPage /> },
{ path: '/instances', element: <InstancesPage /> },
{ path: '/instances/create', element: <SuspenseWrap><CreateInstanceWizard /></SuspenseWrap> },
{ path: '/instances/snapshot-archives', element: <SuspenseWrap><SnapshotArchivesPage /></SuspenseWrap> },
{ path: '/instances/:serverId/:vmid', element: <InstanceDetailPage /> },
{ path: '/nodes', element: <SuspenseWrap><NodesPage /></SuspenseWrap> },
{ path: '/nodes/:serverId', element: <SuspenseWrap><NodeDetailPage /></SuspenseWrap> },