feat(appstore): модуль «App Store» — каталог self-hosted приложений (1 app = 1 LXC + Docker Compose)
All checks were successful
Backend Tests / pytest (Python 3.12) (push) Successful in 1m4s
Deploy to Production / Trigger production update (push) Successful in 12s

Полный цикл M0–M5 по ТЗ:
- Catalog Service: импорт runtipi/runtipi-appstore → catalog_apps, идемпотентный
  синк, кэш логотипов, авто раз в 24ч (APScheduler), флаг update_available.
- App Engine: установка (клон золотого шаблона → pct push compose/.env →
  docker compose up → health-check) с журналом шагов, шифрованием env (Fernet),
  генерацией random-секретов и прогрессом по WebSocket.
- Lifecycle: start/stop/restart/logs/delete + реконсиляция состояния (orphaned).
- Update/Rollback через снапшоты Proxmox (pre-update, хранение последнего 1).
- UI: экраны App Store (сетка/поиск/категории), страница приложения, мастер
  установки (динамическая form_fields + advanced + прогресс + креденшелы),
  My Apps; i18n ru/en; атрибуция Runtipi.
- RBAC app:view/install/manage; только unprivileged LXC; pct exec/push без
  shell-инъекций (base64 + экранирование).
- Модели catalog_apps/installed_apps/app_operations (миграции 31–32).
- Docs: golden-template, appstore-poc/catalog/engine.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
markmorado
2026-07-07 23:05:20 +05:00
parent 782524fff6
commit 0606e8ac77
32 changed files with 3700 additions and 3 deletions

View File

@@ -0,0 +1,92 @@
import { useState } from 'react';
import { useParams, useNavigate } from 'react-router';
import { useTranslation } from 'react-i18next';
import { ArrowLeft, Package, ExternalLink, Download, AlertTriangle, Code } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card } from '@/components/ui/card';
import { useCatalogApp } from '@/hooks/use-appstore';
import InstallWizard from './InstallWizard';
export default function AppDetailPage() {
const { appId = '' } = useParams();
const { t } = useTranslation();
const navigate = useNavigate();
const { data: app, isLoading } = useCatalogApp(appId);
const [wizardOpen, setWizardOpen] = useState(false);
const [showCompose, setShowCompose] = useState(false);
if (isLoading) {
return <div className="py-20 text-center text-sm text-muted-foreground">{t('appstore.loading')}</div>;
}
if (!app) {
return <div className="py-20 text-center text-muted-foreground">{t('appstore.no_apps')}</div>;
}
return (
<div className="mx-auto max-w-3xl space-y-6">
<Button variant="ghost" size="sm" onClick={() => navigate('/appstore')}>
<ArrowLeft className="mr-2 h-4 w-4" />
{t('appstore.back')}
</Button>
<div className="flex items-start gap-4">
{app.logo_url ? (
<img src={app.logo_url} alt="" className="h-16 w-16 shrink-0 rounded-lg object-contain" />
) : (
<div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-lg bg-muted">
<Package className="h-8 w-8 text-muted-foreground" />
</div>
)}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<h1 className="text-xl font-semibold">{app.name}</h1>
{!app.available && <Badge variant="destructive">{t('appstore.unavailable')}</Badge>}
</div>
<p className="text-sm text-muted-foreground">{app.short_desc}</p>
<div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
{app.version && <span>{t('appstore.version')}: {app.version}</span>}
{app.author && <span>{t('appstore.by')} {app.author}</span>}
{(app.categories ?? []).map((c) => <Badge key={c} variant="outline" className="text-2xs">{c}</Badge>)}
</div>
</div>
<Button onClick={() => setWizardOpen(true)} disabled={!app.available}>
<Download className="mr-2 h-4 w-4" />
{t('appstore.install')}
</Button>
</div>
{/* Disclaimer (S-3) */}
<div className="flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/5 p-3 text-xs">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600" />
<div className="space-y-1">
<p>{t('appstore.disclaimer')}</p>
<div className="flex gap-3">
{app.source_url && (
<a href={app.source_url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-primary hover:underline">
<ExternalLink className="h-3 w-3" />{t('appstore.source')}
</a>
)}
{app.compose_yaml && (
<button className="inline-flex items-center gap-1 text-primary hover:underline" onClick={() => setShowCompose((s) => !s)}>
<Code className="h-3 w-3" />{t('appstore.view_compose')}
</button>
)}
</div>
</div>
</div>
{showCompose && app.compose_yaml && (
<pre className="max-h-80 overflow-auto rounded-md border bg-muted/40 p-3 text-xs">{app.compose_yaml}</pre>
)}
{app.description_md && (
<Card className="p-4">
<div className="whitespace-pre-wrap text-sm leading-relaxed text-foreground/90">{app.description_md}</div>
</Card>
)}
<InstallWizard app={app} open={wizardOpen} onOpenChange={setWizardOpen} />
</div>
);
}

View File

@@ -0,0 +1,147 @@
import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Store, Search, RefreshCw, Loader2, Package } from 'lucide-react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select';
import { useCatalog, useCatalogMeta, useInstalledApps, useSyncCatalog } from '@/hooks/use-appstore';
export default function AppStorePage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [search, setSearch] = useState('');
const [category, setCategory] = useState<string>('');
const { data: catalog, isLoading } = useCatalog(search, category);
const { data: meta } = useCatalogMeta();
const { data: installed = [] } = useInstalledApps();
const sync = useSyncCatalog();
const installedIds = useMemo(
() => new Set(installed.map((a) => a.app_id).filter(Boolean)),
[installed],
);
const handleSync = () => {
sync.mutate(undefined, {
onSuccess: (r) => toast.success(t('appstore.sync_done', { total: r.stats.total })),
onError: (e) => toast.error((e as Error).message || t('appstore.sync_failed')),
});
};
const items = catalog?.items ?? [];
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2">
<Store className="h-6 w-6 text-primary" />
<div>
<h1 className="text-xl font-semibold">{t('appstore.title')}</h1>
<p className="text-sm text-muted-foreground">{t('appstore.subtitle')}</p>
</div>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={() => navigate('/my-apps')}>
<Package className="mr-2 h-4 w-4" />
{t('appstore.my_apps')}
</Button>
<Button size="sm" onClick={handleSync} disabled={sync.isPending}>
{sync.isPending
? <Loader2 className="mr-2 h-4 w-4 animate-spin" />
: <RefreshCw className="mr-2 h-4 w-4" />}
{t('appstore.refresh_catalog')}
</Button>
</div>
</div>
{/* Filters */}
<div className="flex flex-wrap items-center gap-3">
<div className="relative w-[280px]">
<Search className="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
className="pl-8"
placeholder={t('appstore.search')}
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
<Select value={category} onValueChange={(v) => setCategory(v ?? '')}>
<SelectTrigger className="w-[200px]">
<SelectValue placeholder={t('appstore.all_categories')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="">{t('appstore.all_categories')}</SelectItem>
{(meta?.categories ?? []).map((c) => (
<SelectItem key={c} value={c}>{c}</SelectItem>
))}
</SelectContent>
</Select>
{meta?.last_synced_at && (
<span className="text-xs text-muted-foreground">
{t('appstore.last_synced')}: {new Date(meta.last_synced_at).toLocaleString()}
</span>
)}
</div>
{/* Grid */}
{isLoading ? (
<div className="py-20 text-center text-sm text-muted-foreground">{t('appstore.loading')}</div>
) : items.length === 0 ? (
<div className="py-20 text-center text-muted-foreground">
<Store className="mx-auto mb-3 h-12 w-12 opacity-40" />
<p>{t('appstore.no_apps')}</p>
</div>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{items.map((app) => (
<Card
key={app.app_id}
className="group flex cursor-pointer flex-col gap-2 p-3 transition-colors hover:border-primary/40"
onClick={() => navigate(`/appstore/${app.app_id}`)}
>
<div className="flex items-start gap-3">
{app.logo_url ? (
<img src={app.logo_url} alt="" className="h-10 w-10 shrink-0 rounded-md object-contain" />
) : (
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-muted">
<Package className="h-5 w-5 text-muted-foreground" />
</div>
)}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<p className="truncate text-sm font-medium">{app.name}</p>
{installedIds.has(app.app_id) && (
<Badge variant="secondary" className="shrink-0">{t('appstore.installed_badge')}</Badge>
)}
</div>
<p className="line-clamp-2 text-xs text-muted-foreground">{app.short_desc}</p>
</div>
</div>
<div className="mt-auto flex flex-wrap items-center gap-1">
{(app.categories ?? []).slice(0, 2).map((c) => (
<Badge key={c} variant="outline" className="text-2xs">{c}</Badge>
))}
{!app.available && (
<Badge variant="destructive" className="text-2xs">{t('appstore.unavailable')}</Badge>
)}
</div>
</Card>
))}
</div>
)}
{/* Атрибуция (риск п.13, юр.) */}
<div className="pt-2 text-center text-2xs text-muted-foreground">
<a href="https://github.com/runtipi/runtipi-appstore" target="_blank" rel="noreferrer" className="hover:underline">
{t('appstore.powered_by')}
</a>
</div>
</div>
);
}

View File

@@ -0,0 +1,277 @@
import { useCallback, useMemo, useState } from 'react';
import { useNavigate } from 'react-router';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Loader2, CheckCircle2, XCircle, Copy, ExternalLink } from 'lucide-react';
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import {
Select, SelectTrigger, SelectValue, SelectContent, SelectItem,
} from '@/components/ui/select';
import { useServers } from '@/hooks/use-nodes';
import { useInstallApp, useInstalledApp, useOperationProgress } from '@/hooks/use-appstore';
import type { AppOperation, CatalogApp } from '@/types/appstore';
interface Props {
app: CatalogApp;
open: boolean;
onOpenChange: (open: boolean) => void;
}
type Phase = 'form' | 'progress' | 'done' | 'failed';
export default function InstallWizard({ app, open, onOpenChange }: Props) {
const { t } = useTranslation();
const navigate = useNavigate();
const { data: servers = [] } = useServers();
const install = useInstallApp();
const [name, setName] = useState(app.app_id);
const [serverId, setServerId] = useState<string>('');
const [node, setNode] = useState('');
const [answers, setAnswers] = useState<Record<string, string>>({});
const [advanced, setAdvanced] = useState(false);
const [cores, setCores] = useState(2);
const [memory, setMemory] = useState(2048);
const [disk, setDisk] = useState(8);
const [storage, setStorage] = useState('local-lvm');
const [bridge, setBridge] = useState('vmbr0');
const [phase, setPhase] = useState<Phase>('form');
const [installedAppId, setInstalledAppId] = useState<number | null>(null);
const [op, setOp] = useState<AppOperation | null>(null);
const [secrets, setSecrets] = useState<Record<string, string>>({});
const { data: installedApp } = useInstalledApp(phase === 'done' ? (installedAppId ?? 0) : 0);
const onOp = useCallback((o: AppOperation) => {
setOp(o);
if (o.status === 'completed') setPhase('done');
else if (o.status === 'failed') setPhase('failed');
}, []);
useOperationProgress(phase === 'progress' ? installedAppId : null, onOp);
// видимые поля формы (random генерируются на сервере, пользователю не показываем)
const visibleFields = useMemo(
() => (app.form_fields ?? []).filter((f) => (f.type || '').toLowerCase() !== 'random'),
[app.form_fields],
);
const reset = () => {
setPhase('form'); setOp(null); setInstalledAppId(null); setSecrets({});
setName(app.app_id); setServerId(''); setNode(''); setAnswers({});
setAdvanced(false); setCores(2); setMemory(2048); setDisk(8);
setStorage('local-lvm'); setBridge('vmbr0');
};
const handleClose = (o: boolean) => {
if (!o) reset();
onOpenChange(o);
};
const handleInstall = () => {
if (!serverId) { toast.error(t('appstore.select_server')); return; }
install.mutate(
{
app_id: app.app_id, name, server_id: Number(serverId), node: node || undefined,
form_answers: answers, cores, memory, disk, storage, bridge,
},
{
onSuccess: (r) => {
setInstalledAppId(r.installed_app_id);
setSecrets(r.secrets || {});
setPhase('progress');
toast.success(t('appstore.install_started'));
},
onError: (e) => toast.error((e as Error).message || t('appstore.install_failed')),
},
);
};
const copy = (text: string) => {
navigator.clipboard?.writeText(text);
toast.success(t('appstore.copied'));
};
const progress = op?.progress ?? 0;
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>{t('appstore.install_title', { name: app.name })}</DialogTitle>
</DialogHeader>
{phase === 'form' && (
<div className="max-h-[60vh] space-y-4 overflow-y-auto pr-1">
<div className="space-y-1.5">
<Label>{t('appstore.app_name')}</Label>
<Input value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>{t('appstore.server')}</Label>
<Select value={serverId} onValueChange={(v) => setServerId(v ?? '')}>
<SelectTrigger><SelectValue placeholder={t('appstore.select_server')} /></SelectTrigger>
<SelectContent>
{servers.map((s) => (
<SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Динамические поля form_fields */}
{visibleFields.map((f) => {
const type = (f.type || 'text').toLowerCase();
const val = answers[f.env_variable] ?? '';
const set = (v: string) => setAnswers((a) => ({ ...a, [f.env_variable]: v }));
return (
<div key={f.env_variable} className="space-y-1.5">
<Label className="flex items-center gap-1.5">
{f.label || f.env_variable}
{f.required && <span className="text-destructive">*</span>}
</Label>
{type === 'boolean' ? (
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={val === 'true'}
onChange={(e) => set(e.target.checked ? 'true' : 'false')}
/>
{f.hint}
</label>
) : (
<Input
type={type === 'password' ? 'password' : type === 'number' ? 'number' : type === 'email' ? 'email' : 'text'}
value={val}
placeholder={f.hint}
onChange={(e) => set(e.target.value)}
/>
)}
</div>
);
})}
{/* Advanced */}
<div>
<button
type="button"
className="text-sm font-medium text-primary hover:underline"
onClick={() => setAdvanced((a) => !a)}
>
{advanced ? '▾ ' : '▸ '}{t('appstore.step_advanced')}
</button>
{advanced && (
<div className="mt-2 grid grid-cols-2 gap-3">
<NumField label={t('appstore.cores')} value={cores} onChange={setCores} />
<NumField label={t('appstore.memory')} value={memory} onChange={setMemory} />
<NumField label={t('appstore.disk')} value={disk} onChange={setDisk} />
<div className="space-y-1.5">
<Label>{t('appstore.node')}</Label>
<Input value={node} onChange={(e) => setNode(e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>{t('appstore.storage')}</Label>
<Input value={storage} onChange={(e) => setStorage(e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>{t('appstore.bridge')}</Label>
<Input value={bridge} onChange={(e) => setBridge(e.target.value)} />
</div>
</div>
)}
</div>
</div>
)}
{(phase === 'progress' || phase === 'failed') && (
<div className="space-y-3">
<div className="h-2 w-full overflow-hidden rounded-full bg-muted">
<div
className={`h-full transition-all ${phase === 'failed' ? 'bg-destructive' : 'bg-primary'}`}
style={{ width: `${progress}%` }}
/>
</div>
<div className="max-h-[45vh] space-y-1 overflow-y-auto rounded-md border bg-muted/30 p-3 text-xs">
{(op?.steps_log ?? []).map((s, i) => (
<div key={i} className="flex items-center justify-between gap-2">
<span>{s.step}</span>
<span className="text-muted-foreground">{s.progress}%</span>
</div>
))}
{!op && <div className="flex items-center gap-2 text-muted-foreground"><Loader2 className="h-3.5 w-3.5 animate-spin" />{t('appstore.installing')}</div>}
</div>
{phase === 'failed' && (
<div className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 p-2 text-xs text-destructive">
<XCircle className="mt-0.5 h-4 w-4 shrink-0" />
<span>{op?.error_text || t('appstore.install_failed')}</span>
</div>
)}
</div>
)}
{phase === 'done' && (
<div className="space-y-3">
<div className="flex items-center gap-2 text-sm text-emerald-600">
<CheckCircle2 className="h-5 w-5" />
{t('appstore.done')}
</div>
{installedApp?.url && (
<Button variant="outline" className="w-full" onClick={() => window.open(installedApp.url!, '_blank')}>
<ExternalLink className="mr-2 h-4 w-4" />
{installedApp.url}
</Button>
)}
{Object.keys(secrets).length > 0 && (
<div className="space-y-2 rounded-md border p-3">
<p className="text-xs font-medium text-muted-foreground">{t('appstore.credentials')}</p>
{Object.entries(secrets).map(([k, v]) => (
<div key={k} className="flex items-center gap-2">
<Badge variant="outline" className="shrink-0 font-mono text-2xs">{k}</Badge>
<code className="min-w-0 flex-1 truncate rounded bg-muted px-1.5 py-0.5 text-xs">{v}</code>
<Button size="icon-sm" variant="ghost" onClick={() => copy(v)}>
<Copy className="h-3.5 w-3.5" />
</Button>
</div>
))}
</div>
)}
</div>
)}
<DialogFooter>
{phase === 'form' && (
<Button onClick={handleInstall} disabled={install.isPending}>
{install.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{t('appstore.start_install')}
</Button>
)}
{phase === 'done' && (
<>
<Button variant="outline" onClick={() => navigate('/my-apps')}>{t('appstore.my_apps')}</Button>
<Button onClick={() => handleClose(false)}>{t('appstore.close')}</Button>
</>
)}
{(phase === 'progress' || phase === 'failed') && (
<Button variant="outline" onClick={() => handleClose(false)}>{t('appstore.close')}</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
}
function NumField({ label, value, onChange }: { label: string; value: number; onChange: (n: number) => void }) {
return (
<div className="space-y-1.5">
<Label>{label}</Label>
<Input type="number" value={value} onChange={(e) => onChange(Number(e.target.value) || 0)} />
</div>
);
}

View File

@@ -0,0 +1,225 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import {
Package, Store, ExternalLink, RotateCw, Trash2, Loader2,
Play, Square, RefreshCcw, FileText, ArrowUpCircle, Undo2,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { StatusDot } from '@/components/shared/status-dot';
import {
Dialog, DialogContent, DialogHeader, DialogTitle,
} from '@/components/ui/dialog';
import {
useInstalledApps, useAppstoreRealtime, useRetryApp, useDeleteApp,
useLifecycleAction, useReconcile, useAppLogs, useUpdateApp, useRollbackApp,
} from '@/hooks/use-appstore';
import type { InstalledApp } from '@/types/appstore';
export default function MyAppsPage() {
const { t } = useTranslation();
const navigate = useNavigate();
useAppstoreRealtime();
const { data: apps = [], isLoading } = useInstalledApps();
const retry = useRetryApp();
const del = useDeleteApp();
const lifecycle = useLifecycleAction();
const reconcile = useReconcile();
const update = useUpdateApp();
const rollback = useRollbackApp();
const [logsApp, setLogsApp] = useState<InstalledApp | null>(null);
// ТЗ 6.6 — реконсиляция статусов при открытии экрана.
useEffect(() => {
reconcile.mutate();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleDelete = (a: InstalledApp) => {
if (!window.confirm(t('appstore.delete_confirm', { name: a.name }))) return;
del.mutate(a.id, {
onSuccess: () => toast.success(t('appstore.deleted')),
onError: (e) => toast.error((e as Error).message),
});
};
const act = (a: InstalledApp, action: 'start' | 'stop' | 'restart') => {
lifecycle.mutate({ id: a.id, action }, {
onError: (e) => toast.error((e as Error).message),
});
};
const handleRetry = (a: InstalledApp) => {
retry.mutate(a.id, {
onSuccess: () => toast.success(t('appstore.install_started')),
onError: (e) => toast.error((e as Error).message),
});
};
const handleUpdate = (a: InstalledApp) => {
if (!window.confirm(t('appstore.update_confirm', { name: a.name }))) return;
update.mutate(a.id, {
onSuccess: () => toast.success(t('appstore.update_started')),
onError: (e) => toast.error((e as Error).message),
});
};
const handleRollback = (a: InstalledApp) => {
if (!window.confirm(t('appstore.rollback_confirm', { name: a.name }))) return;
rollback.mutate(a.id, {
onSuccess: () => toast.success(t('appstore.rollback_started')),
onError: (e) => toast.error((e as Error).message),
});
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<Package className="h-6 w-6 text-primary" />
<div>
<h1 className="text-xl font-semibold">{t('appstore.my_apps')}</h1>
<p className="text-sm text-muted-foreground">{t('appstore.my_apps_subtitle')}</p>
</div>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={() => reconcile.mutate()} disabled={reconcile.isPending}>
{reconcile.isPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <RefreshCcw className="mr-2 h-4 w-4" />}
{t('appstore.refresh')}
</Button>
<Button variant="outline" size="sm" onClick={() => navigate('/appstore')}>
<Store className="mr-2 h-4 w-4" />
{t('appstore.title')}
</Button>
</div>
</div>
{isLoading ? (
<div className="py-20 text-center text-sm text-muted-foreground">{t('appstore.loading')}</div>
) : apps.length === 0 ? (
<div className="py-20 text-center text-muted-foreground">
<Package className="mx-auto mb-3 h-12 w-12 opacity-40" />
<p>{t('appstore.no_installed')}</p>
</div>
) : (
<div className="overflow-x-auto rounded-lg border">
<table className="w-full text-sm">
<thead className="border-b bg-muted/40 text-left text-xs text-muted-foreground">
<tr>
<th className="px-3 py-2 font-medium">{t('appstore.col_name')}</th>
<th className="px-3 py-2 font-medium">{t('appstore.col_status')}</th>
<th className="px-3 py-2 font-medium">{t('appstore.col_version')}</th>
<th className="px-3 py-2 font-medium">{t('appstore.col_address')}</th>
<th className="px-3 py-2 text-right font-medium">{t('appstore.col_actions')}</th>
</tr>
</thead>
<tbody>
{apps.map((a) => {
const busy = lifecycle.isPending || del.isPending || retry.isPending || update.isPending || rollback.isPending;
return (
<tr key={a.id} className="border-b last:border-0 hover:bg-accent/30">
<td className="px-3 py-2">
<div className="font-medium">{a.name}</div>
<div className="text-xs text-muted-foreground">{a.app_id} · VMID {a.vmid ?? '—'}</div>
</td>
<td className="px-3 py-2">
<span className="inline-flex items-center gap-1.5">
<StatusDot status={a.status} pulse />
<span className="text-xs">{a.status}</span>
</span>
{a.status === 'orphaned' && (
<div className="text-2xs text-amber-600">{t('appstore.orphaned_hint')}</div>
)}
</td>
<td className="px-3 py-2">
{a.version_installed ?? '—'}
{a.update_available && <Badge variant="secondary" className="ml-1.5 text-2xs">update</Badge>}
</td>
<td className="px-3 py-2">
{a.url ? (
<a href={a.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-primary hover:underline">
{a.ip}:{a.port} <ExternalLink className="h-3 w-3" />
</a>
) : '—'}
</td>
<td className="px-3 py-2">
<div className="flex items-center justify-end gap-1">
{a.status === 'stopped' && (
<Button size="icon-sm" variant="ghost" title={t('appstore.start')} onClick={() => act(a, 'start')} disabled={busy}>
<Play className="h-3.5 w-3.5" />
</Button>
)}
{a.status === 'running' && (
<>
<Button size="icon-sm" variant="ghost" title={t('appstore.stop')} onClick={() => act(a, 'stop')} disabled={busy}>
<Square className="h-3.5 w-3.5" />
</Button>
<Button size="icon-sm" variant="ghost" title={t('appstore.restart')} onClick={() => act(a, 'restart')} disabled={busy}>
<RotateCw className="h-3.5 w-3.5" />
</Button>
</>
)}
{a.vmid && a.status !== 'orphaned' && (
<Button size="icon-sm" variant="ghost" title={t('appstore.logs')} onClick={() => setLogsApp(a)}>
<FileText className="h-3.5 w-3.5" />
</Button>
)}
{a.update_available && ['running', 'stopped', 'update_failed'].includes(a.status) && (
<Button size="icon-sm" variant="ghost" className="text-primary" title={t('appstore.update')} onClick={() => handleUpdate(a)} disabled={busy}>
<ArrowUpCircle className="h-3.5 w-3.5" />
</Button>
)}
{a.last_snapshot && (
<Button size="icon-sm" variant="ghost" className="text-amber-600" title={t('appstore.rollback')} onClick={() => handleRollback(a)} disabled={busy}>
<Undo2 className="h-3.5 w-3.5" />
</Button>
)}
{a.status === 'error' && (
<Button size="sm" variant="outline" onClick={() => handleRetry(a)} disabled={busy}>
<RotateCw className="h-3.5 w-3.5" />
<span className="ml-1">{t('appstore.retry')}</span>
</Button>
)}
<Button size="icon-sm" variant="ghost" className="text-destructive" title={t('appstore.delete')} onClick={() => handleDelete(a)} disabled={busy}>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
<LogsDialog app={logsApp} onClose={() => setLogsApp(null)} />
</div>
);
}
function LogsDialog({ app, onClose }: { app: InstalledApp | null; onClose: () => void }) {
const { t } = useTranslation();
const { data: logs, isFetching, refetch } = useAppLogs(app?.id ?? 0, !!app);
return (
<Dialog open={!!app} onOpenChange={(o) => { if (!o) onClose(); }}>
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle className="flex items-center justify-between gap-2 pr-8">
{t('appstore.logs_title', { name: app?.name ?? '' })}
<Button size="sm" variant="outline" onClick={() => refetch()} disabled={isFetching}>
{isFetching ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCcw className="h-3.5 w-3.5" />}
<span className="ml-1">{t('appstore.refresh')}</span>
</Button>
</DialogTitle>
</DialogHeader>
<pre className="max-h-[65vh] overflow-auto rounded-md border bg-muted/40 p-3 text-2xs leading-relaxed">
{isFetching && !logs ? t('appstore.loading') : (logs && logs.trim() ? logs : t('appstore.no_logs'))}
</pre>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,197 @@
import { useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { getTasksWebSocket } from '@/lib/websocket';
import type {
AppOperation, CatalogApp, CatalogListResponse, CatalogMeta,
InstalledApp, InstallResponse,
} from '@/types/appstore';
export const appstoreKeys = {
catalog: (q?: string, category?: string) => ['appstore-catalog', q ?? '', category ?? ''] as const,
catalogMeta: ['appstore-catalog-meta'] as const,
catalogApp: (id: string) => ['appstore-catalog-app', id] as const,
installed: ['appstore-installed'] as const,
installedApp: (id: number) => ['appstore-installed', id] as const,
operations: (id: number) => ['appstore-operations', id] as const,
};
// ── Каталог ────────────────────────────────────────────────────────────────
export function useCatalog(q?: string, category?: string, availableOnly = false) {
const params = new URLSearchParams();
if (q) params.set('q', q);
if (category) params.set('category', category);
if (availableOnly) params.set('available_only', 'true');
const qs = params.toString();
return useQuery({
queryKey: appstoreKeys.catalog(q, category),
queryFn: () => apiClient.get<CatalogListResponse>(`/api/appstore/catalog${qs ? `?${qs}` : ''}`),
});
}
export function useCatalogMeta() {
return useQuery({
queryKey: appstoreKeys.catalogMeta,
queryFn: () => apiClient.get<CatalogMeta>('/api/appstore/catalog/meta'),
});
}
export function useCatalogApp(appId: string) {
return useQuery({
queryKey: appstoreKeys.catalogApp(appId),
queryFn: () => apiClient.get<CatalogApp>(`/api/appstore/catalog/${appId}`),
enabled: !!appId,
});
}
export function useSyncCatalog() {
const qc = useQueryClient();
return useMutation({
mutationFn: () => apiClient.post<{ success: boolean; stats: { total: number } }>('/api/appstore/catalog/sync'),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['appstore-catalog'] });
qc.invalidateQueries({ queryKey: appstoreKeys.catalogMeta });
},
});
}
// ── Установленные ──────────────────────────────────────────────────────────
export function useInstalledApps() {
return useQuery({
queryKey: appstoreKeys.installed,
queryFn: () => apiClient.get<{ items: InstalledApp[] }>('/api/appstore/apps').then((r) => r.items),
});
}
export function useInstalledApp(id: number) {
return useQuery({
queryKey: appstoreKeys.installedApp(id),
queryFn: () => apiClient.get<InstalledApp>(`/api/appstore/apps/${id}`),
enabled: id > 0,
});
}
export function useAppOperations(id: number) {
return useQuery({
queryKey: appstoreKeys.operations(id),
queryFn: () => apiClient.get<{ items: AppOperation[] }>(`/api/appstore/apps/${id}/operations`).then((r) => r.items),
enabled: id > 0,
});
}
export interface InstallArgs {
app_id: string;
name: string;
server_id: number;
node?: string;
form_answers: Record<string, string>;
cores: number;
memory: number;
disk: number;
storage: string;
bridge: string;
}
export function useInstallApp() {
const qc = useQueryClient();
return useMutation({
mutationFn: (data: InstallArgs) => apiClient.post<InstallResponse>('/api/appstore/apps/install', data),
onSuccess: () => qc.invalidateQueries({ queryKey: appstoreKeys.installed }),
});
}
export function useRetryApp() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: number) => apiClient.post(`/api/appstore/apps/${id}/retry`),
onSuccess: () => qc.invalidateQueries({ queryKey: appstoreKeys.installed }),
});
}
export function useDeleteApp() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: number) => apiClient.delete(`/api/appstore/apps/${id}`),
onSuccess: () => qc.invalidateQueries({ queryKey: appstoreKeys.installed }),
});
}
export function useUpdateApp() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: number) => apiClient.post(`/api/appstore/apps/${id}/update`),
onSuccess: () => qc.invalidateQueries({ queryKey: appstoreKeys.installed }),
});
}
export function useRollbackApp() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: number) => apiClient.post(`/api/appstore/apps/${id}/rollback`),
onSuccess: () => qc.invalidateQueries({ queryKey: appstoreKeys.installed }),
});
}
export type LifecycleAction = 'start' | 'stop' | 'restart';
export function useLifecycleAction() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, action }: { id: number; action: LifecycleAction }) =>
apiClient.post(`/api/appstore/apps/${id}/action/${action}`),
onSuccess: () => qc.invalidateQueries({ queryKey: appstoreKeys.installed }),
});
}
export function useReconcile() {
const qc = useQueryClient();
return useMutation({
mutationFn: () => apiClient.post<{ checked: number; changed: number }>('/api/appstore/apps/reconcile'),
onSuccess: () => qc.invalidateQueries({ queryKey: appstoreKeys.installed }),
});
}
export function useAppLogs(id: number, enabled: boolean) {
return useQuery({
queryKey: ['appstore-logs', id],
queryFn: () => apiClient.get<{ logs: string }>(`/api/appstore/apps/${id}/logs?tail=200`).then((r) => r.logs),
enabled: enabled && id > 0,
refetchOnWindowFocus: false,
});
}
// ── Realtime: инвалидация кэшей по WS-событиям + подписка на операцию ──────────
export function useAppstoreRealtime() {
const qc = useQueryClient();
useEffect(() => {
const ws = getTasksWebSocket();
ws.connect();
const off1 = ws.onType('appstore_operation_update', () => {
qc.invalidateQueries({ queryKey: appstoreKeys.installed });
});
const off2 = ws.onType('appstore_app_deleted', () => {
qc.invalidateQueries({ queryKey: appstoreKeys.installed });
});
return () => { off1(); off2(); };
}, [qc]);
}
/** Подписка на прогресс конкретной установки (по installed_app_id). */
export function useOperationProgress(
installedAppId: number | null,
onUpdate: (op: AppOperation) => void,
) {
useEffect(() => {
if (!installedAppId) return;
const ws = getTasksWebSocket();
ws.connect();
const off = ws.onType('appstore_operation_update', (data: unknown) => {
const op = (data as { task?: AppOperation }).task;
if (op && op.installed_app_id === installedAppId) onUpdate(op);
});
return () => { off(); };
}, [installedAppId, onUpdate]);
}

View File

@@ -21,6 +21,8 @@ import {
ChevronDown,
Building2,
Check,
Store,
Package,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
@@ -74,6 +76,13 @@ const navGroups: NavGroup[] = [
{ label: 'Tasks', icon: ClipboardList, path: '/tasks', permission: 'vm:view' },
],
},
{
title: 'Applications',
items: [
{ label: 'App Store', icon: Store, path: '/appstore', permission: 'app:view' },
{ label: 'My Apps', icon: Package, path: '/my-apps', permission: 'app:view' },
],
},
{
title: 'Network',
items: [

View File

@@ -15,7 +15,82 @@
"users": "Users",
"workspaces": "Workspaces",
"logs": "Logs",
"settings": "Settings"
"settings": "Settings",
"applications": "Applications",
"app store": "App Store",
"my apps": "My Apps"
},
"appstore": {
"title": "App Store",
"subtitle": "Self-hosted apps, one-click install into an LXC container",
"search": "Search apps…",
"all_categories": "All categories",
"refresh_catalog": "Refresh catalog",
"last_synced": "Last synced",
"never": "never",
"syncing": "Syncing…",
"sync_done": "Catalog synced: {{total}} apps",
"sync_failed": "Catalog sync failed",
"installed_badge": "Installed",
"unavailable": "Unavailable",
"install": "Install",
"no_apps": "No apps found",
"loading": "Loading…",
"by": "by",
"source": "Source",
"version": "Version",
"disclaimer": "This compose file runs as-is from a third-party repository. Review what will be installed.",
"view_compose": "View source compose",
"back": "Back to catalog",
"my_apps": "My Apps",
"my_apps_subtitle": "Installed applications",
"no_installed": "No installed apps yet",
"col_name": "Name",
"col_status": "Status",
"col_version": "Version",
"col_address": "Address",
"col_actions": "Actions",
"open": "Open",
"retry": "Retry",
"delete": "Delete",
"delete_confirm": "Delete app \"{{name}}\" and its LXC container?",
"deleted": "App deleted",
"start": "Start",
"stop": "Stop",
"restart": "Restart",
"logs": "Logs",
"logs_title": "Logs — {{name}}",
"no_logs": "No logs",
"orphaned_hint": "Container removed outside PVEmanager",
"refresh": "Refresh",
"update": "Update",
"rollback": "Rollback",
"update_confirm": "Update \"{{name}}\"? A pre-update snapshot is taken automatically.",
"rollback_confirm": "Roll back \"{{name}}\"? This ALSO reverts the app's DATA to the snapshot moment.",
"update_started": "Update started",
"rollback_started": "Rollback started",
"powered_by": "Powered by Runtipi appstore",
"install_title": "Install {{name}}",
"step_advanced": "Advanced (LXC resources)",
"server": "Server",
"select_server": "Select server",
"node": "Node (optional)",
"storage": "Storage",
"bridge": "Bridge",
"cores": "CPU cores",
"memory": "RAM (MB)",
"disk": "Disk (GB)",
"app_name": "App name",
"start_install": "Install",
"installing": "Installing…",
"install_started": "Installation started",
"credentials": "Credentials (shown once — copy them now)",
"copy": "Copy",
"copied": "Copied",
"done": "Done",
"close": "Close",
"open_app": "Open app",
"install_failed": "Installation failed"
},
"cluster": {
"create_title": "Create cluster",

View File

@@ -15,7 +15,82 @@
"users": "Пользователи",
"workspaces": "Рабочие области",
"logs": "Логи",
"settings": "Настройки"
"settings": "Настройки",
"applications": "Приложения",
"app store": "Каталог приложений",
"my apps": "Мои приложения"
},
"appstore": {
"title": "Каталог приложений",
"subtitle": "Self-hosted приложения, установка в один клик в LXC-контейнер",
"search": "Поиск приложений…",
"all_categories": "Все категории",
"refresh_catalog": "Обновить каталог",
"last_synced": "Обновлён",
"never": "никогда",
"syncing": "Синхронизация…",
"sync_done": "Каталог синхронизирован: {{total}} приложений",
"sync_failed": "Не удалось синхронизировать каталог",
"installed_badge": "Установлено",
"unavailable": "Недоступно",
"install": "Установить",
"no_apps": "Приложения не найдены",
"loading": "Загрузка…",
"by": "автор",
"source": "Источник",
"version": "Версия",
"disclaimer": "Этот compose-файл исполняется как есть из стороннего репозитория. Проверьте, что будет установлено.",
"view_compose": "Показать исходный compose",
"back": "К каталогу",
"my_apps": "Мои приложения",
"my_apps_subtitle": "Установленные приложения",
"no_installed": "Пока нет установленных приложений",
"col_name": "Имя",
"col_status": "Статус",
"col_version": "Версия",
"col_address": "Адрес",
"col_actions": "Действия",
"open": "Открыть",
"retry": "Повторить",
"delete": "Удалить",
"delete_confirm": "Удалить приложение «{{name}}» вместе с LXC-контейнером?",
"deleted": "Приложение удалено",
"start": "Запустить",
"stop": "Остановить",
"restart": "Перезапустить",
"logs": "Логи",
"logs_title": "Логи — {{name}}",
"no_logs": "Логи пусты",
"orphaned_hint": "Контейнер удалён мимо PVEmanager",
"refresh": "Обновить",
"update": "Обновить приложение",
"rollback": "Откатить",
"update_confirm": "Обновить «{{name}}»? Перед обновлением автоматически создаётся снапшот.",
"rollback_confirm": "Откатить «{{name}}»? Откат вернёт и ДАННЫЕ приложения на момент снапшота.",
"update_started": "Обновление запущено",
"rollback_started": "Откат запущен",
"powered_by": "Powered by Runtipi appstore",
"install_title": "Установка {{name}}",
"step_advanced": "Дополнительно (ресурсы LXC)",
"server": "Сервер",
"select_server": "Выберите сервер",
"node": "Нода (опционально)",
"storage": "Хранилище",
"bridge": "Мост",
"cores": "Ядра CPU",
"memory": "RAM (МБ)",
"disk": "Диск (ГБ)",
"app_name": "Имя приложения",
"start_install": "Установить",
"installing": "Установка…",
"install_started": "Установка запущена",
"credentials": "Учётные данные (показаны один раз — скопируйте сейчас)",
"copy": "Копировать",
"copied": "Скопировано",
"done": "Готово",
"close": "Закрыть",
"open_app": "Открыть приложение",
"install_failed": "Ошибка установки"
},
"cluster": {
"create_title": "Создать кластер",

View File

@@ -35,6 +35,9 @@ const UsersPage = lazy(() => import('./features/users/UsersPage.tsx'));
const WorkspacesPage = lazy(() => import('./features/workspaces/WorkspacesPage.tsx'));
const LogsPage = lazy(() => import('./features/logs/LogsPage.tsx'));
const SettingsPage = lazy(() => import('./features/settings/SettingsPage.tsx'));
const AppStorePage = lazy(() => import('./features/appstore/AppStorePage.tsx'));
const AppDetailPage = lazy(() => import('./features/appstore/AppDetailPage.tsx'));
const MyAppsPage = lazy(() => import('./features/appstore/MyAppsPage.tsx'));
function LazyFallback() {
return <div className="flex items-center justify-center py-20 text-muted-foreground text-sm">Loading…</div>;
@@ -86,6 +89,9 @@ export const router = createBrowserRouter([
{ path: '/nodes/:serverId', element: <SuspenseWrap><NodeDetailPage /></SuspenseWrap> },
{ path: '/cluster', element: <SuspenseWrap><ClusterPage /></SuspenseWrap> },
{ path: '/templates', element: <SuspenseWrap><TemplatesPage /></SuspenseWrap> },
{ path: '/appstore', element: <SuspenseWrap><AppStorePage /></SuspenseWrap> },
{ path: '/appstore/:appId', element: <SuspenseWrap><AppDetailPage /></SuspenseWrap> },
{ path: '/my-apps', element: <SuspenseWrap><MyAppsPage /></SuspenseWrap> },
{ path: '/images', element: <SuspenseWrap><ImagesPage /></SuspenseWrap> },
{ path: '/backups', element: <SuspenseWrap><BackupsPage /></SuspenseWrap> },
{ path: '/tasks', element: <SuspenseWrap><TasksPage /></SuspenseWrap> },

View File

@@ -0,0 +1,111 @@
// Типы модуля App Store (каталог + установленные приложения).
export interface FormFieldOption {
value: string;
label?: string;
}
export interface FormField {
type: string; // text | password | email | number | random | boolean | fqdn | ...
label?: string;
env_variable: string;
hint?: string;
required?: boolean;
min?: number;
max?: number;
default?: string | number | boolean;
options?: FormFieldOption[];
}
export interface CatalogAppLight {
app_id: string;
name: string;
version: string | null;
tipi_version: number | null;
categories: string[];
short_desc: string | null;
port: number | null;
architectures: string[];
available: boolean;
unavailable_reason: string | null;
deprecated: boolean;
dynamic_config: boolean;
source_url: string | null;
author: string | null;
logo_url: string | null;
synced_at: string | null;
}
export interface CatalogApp extends CatalogAppLight {
form_fields: FormField[];
description_md: string | null;
compose_yaml?: string;
}
export interface CatalogListResponse {
total: number;
limit: number;
offset: number;
items: CatalogAppLight[];
}
export interface CatalogMeta {
total: number;
last_synced_at: string | null;
repo: string;
ref: string;
categories: string[];
}
export type InstalledStatus =
| 'installing' | 'running' | 'stopped' | 'error'
| 'updating' | 'update_failed' | 'orphaned' | 'deleting';
export interface InstalledApp {
id: number;
app_id: string | null;
server_id: number | null;
vmid: number | null;
node: string | null;
name: string;
version_installed: string | null;
tipi_version_installed: number | null;
ip: string | null;
port: number | null;
url: string | null;
status: InstalledStatus;
update_available: boolean;
last_snapshot: string | null;
owner_id: number | null;
created_at: string | null;
updated_at: string | null;
catalog?: CatalogAppLight;
}
export interface AppOperationStep {
step: string;
progress: number;
ts: string;
}
export interface AppOperation {
id: number;
kind: 'appstore';
installed_app_id: number | null;
type: string;
status: 'running' | 'completed' | 'failed';
progress: number;
steps_log: AppOperationStep[];
error_text: string | null;
user_id: number | null;
started_at: string | null;
finished_at: string | null;
}
export interface InstallResponse {
success: boolean;
installed_app_id: number;
operation_id: number;
vmid: number;
secrets: Record<string, string>;
}