forked from wrenn/wrenn
Merge pull request 'Added manual template building' (#24) from feat/admin-panel into dev
Reviewed-on: wrenn/wrenn#24
This commit is contained in:
12
db/migrations/20260412213141_seed_platform_team.sql
Normal file
12
db/migrations/20260412213141_seed_platform_team.sql
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
-- +goose Up
|
||||||
|
|
||||||
|
-- Seed the platform team row. This is the sentinel team (all-zeros UUID) that
|
||||||
|
-- owns platform-wide resources: global templates, admin-created capsules, etc.
|
||||||
|
-- No user can become a member of this team — it exists solely to satisfy
|
||||||
|
-- foreign key constraints and to act as a namespace for platform resources.
|
||||||
|
INSERT INTO teams (id, name, slug)
|
||||||
|
VALUES ('00000000-0000-0000-0000-000000000000', 'Platform', 'platform')
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
DELETE FROM teams WHERE id = '00000000-0000-0000-0000-000000000000';
|
||||||
@ -35,6 +35,9 @@ SELECT EXISTS(
|
|||||||
SELECT 1 FROM admin_permissions WHERE user_id = $1 AND permission = $2
|
SELECT 1 FROM admin_permissions WHERE user_id = $1 AND permission = $2
|
||||||
) AS has_permission;
|
) AS has_permission;
|
||||||
|
|
||||||
|
-- name: CountUsers :one
|
||||||
|
SELECT COUNT(*) FROM users;
|
||||||
|
|
||||||
-- name: SearchUsersByEmailPrefix :many
|
-- name: SearchUsersByEmailPrefix :many
|
||||||
SELECT id, email FROM users WHERE email LIKE $1 || '%' ORDER BY email LIMIT 10;
|
SELECT id, email FROM users WHERE email LIKE $1 || '%' ORDER BY email LIMIT 10;
|
||||||
|
|
||||||
|
|||||||
40
frontend/src/lib/api/admin-capsules.ts
Normal file
40
frontend/src/lib/api/admin-capsules.ts
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
import { apiFetch, type ApiResult } from '$lib/api/client';
|
||||||
|
import type { Capsule, CreateCapsuleParams, Snapshot } from '$lib/api/capsules';
|
||||||
|
import type { AdminTemplate } from '$lib/api/builds';
|
||||||
|
|
||||||
|
export async function listAdminCapsules(): Promise<ApiResult<Capsule[]>> {
|
||||||
|
return apiFetch('GET', '/api/v1/admin/capsules');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAdminCapsule(id: string): Promise<ApiResult<Capsule>> {
|
||||||
|
return apiFetch('GET', `/api/v1/admin/capsules/${id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createAdminCapsule(params: CreateCapsuleParams): Promise<ApiResult<Capsule>> {
|
||||||
|
return apiFetch('POST', '/api/v1/admin/capsules', params);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function destroyAdminCapsule(id: string): Promise<ApiResult<void>> {
|
||||||
|
return apiFetch('DELETE', `/api/v1/admin/capsules/${id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function snapshotAdminCapsule(id: string, name?: string): Promise<ApiResult<Snapshot>> {
|
||||||
|
return apiFetch('POST', `/api/v1/admin/capsules/${id}/snapshot`, { name });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fetch platform templates for the admin create dialog. */
|
||||||
|
export async function listPlatformTemplates(): Promise<ApiResult<Snapshot[]>> {
|
||||||
|
const result = await apiFetch<AdminTemplate[]>('GET', '/api/v1/admin/templates');
|
||||||
|
if (!result.ok) return result;
|
||||||
|
// Map AdminTemplate → Snapshot shape.
|
||||||
|
const snapshots: Snapshot[] = result.data.map((t) => ({
|
||||||
|
name: t.name,
|
||||||
|
type: t.type,
|
||||||
|
vcpus: t.vcpus || undefined,
|
||||||
|
memory_mb: t.memory_mb || undefined,
|
||||||
|
size_bytes: t.size_bytes,
|
||||||
|
created_at: t.created_at,
|
||||||
|
platform: true,
|
||||||
|
}));
|
||||||
|
return { ok: true, data: snapshots };
|
||||||
|
}
|
||||||
@ -4,7 +4,7 @@ import { type ApiResult } from '$lib/api/client';
|
|||||||
export type FileEntry = {
|
export type FileEntry = {
|
||||||
name: string;
|
name: string;
|
||||||
path: string;
|
path: string;
|
||||||
type: 'file' | 'directory' | 'symlink';
|
type: 'file' | 'directory' | 'symlink' | 'unknown';
|
||||||
size: number;
|
size: number;
|
||||||
mode: number;
|
mode: number;
|
||||||
permissions: string;
|
permissions: string;
|
||||||
@ -53,12 +53,12 @@ export function formatFileSize(bytes: number): string {
|
|||||||
return `${val < 10 ? val.toFixed(1) : Math.round(val)} ${units[i]}`;
|
return `${val < 10 ? val.toFixed(1) : Math.round(val)} ${units[i]}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function listDir(capsuleId: string, path: string, depth = 1): Promise<ApiResult<ListDirResponse>> {
|
export async function listDir(capsuleId: string, path: string, depth = 1, basePath = '/api/v1/capsules'): Promise<ApiResult<ListDirResponse>> {
|
||||||
try {
|
try {
|
||||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||||
if (auth.token) headers['Authorization'] = `Bearer ${auth.token}`;
|
if (auth.token) headers['Authorization'] = `Bearer ${auth.token}`;
|
||||||
|
|
||||||
const res = await fetch(`/api/v1/capsules/${capsuleId}/files/list`, {
|
const res = await fetch(`${basePath}/${capsuleId}/files/list`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers,
|
headers,
|
||||||
body: JSON.stringify({ path, depth }),
|
body: JSON.stringify({ path, depth }),
|
||||||
@ -76,12 +76,13 @@ export async function readFile(
|
|||||||
capsuleId: string,
|
capsuleId: string,
|
||||||
path: string,
|
path: string,
|
||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
|
basePath = '/api/v1/capsules',
|
||||||
): Promise<ApiResult<string>> {
|
): Promise<ApiResult<string>> {
|
||||||
try {
|
try {
|
||||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||||
if (auth.token) headers['Authorization'] = `Bearer ${auth.token}`;
|
if (auth.token) headers['Authorization'] = `Bearer ${auth.token}`;
|
||||||
|
|
||||||
const res = await fetch(`/api/v1/capsules/${capsuleId}/files/read`, {
|
const res = await fetch(`${basePath}/${capsuleId}/files/read`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers,
|
headers,
|
||||||
body: JSON.stringify({ path }),
|
body: JSON.stringify({ path }),
|
||||||
@ -113,11 +114,12 @@ export async function downloadFile(
|
|||||||
path: string,
|
path: string,
|
||||||
filename: string,
|
filename: string,
|
||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
|
basePath = '/api/v1/capsules',
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||||
if (auth.token) headers['Authorization'] = `Bearer ${auth.token}`;
|
if (auth.token) headers['Authorization'] = `Bearer ${auth.token}`;
|
||||||
|
|
||||||
const res = await fetch(`/api/v1/capsules/${capsuleId}/files/read`, {
|
const res = await fetch(`${basePath}/${capsuleId}/files/read`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers,
|
headers,
|
||||||
body: JSON.stringify({ path }),
|
body: JSON.stringify({ path }),
|
||||||
|
|||||||
@ -15,8 +15,8 @@ export type MetricsResponse = {
|
|||||||
points: MetricPoint[];
|
points: MetricPoint[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function fetchCapsuleMetrics(id: string, range: MetricRange): Promise<ApiResult<MetricsResponse>> {
|
export async function fetchCapsuleMetrics(id: string, range: MetricRange, basePath = '/api/v1/capsules'): Promise<ApiResult<MetricsResponse>> {
|
||||||
return apiFetch('GET', `/api/v1/capsules/${id}/metrics?range=${range}`);
|
return apiFetch('GET', `${basePath}/${id}/metrics?range=${range}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const METRIC_RANGES: MetricRange[] = ['5m', '10m', '1h', '6h', '24h'];
|
export const METRIC_RANGES: MetricRange[] = ['5m', '10m', '1h', '6h', '24h'];
|
||||||
|
|||||||
@ -3,7 +3,8 @@
|
|||||||
import { auth } from '$lib/auth.svelte';
|
import { auth } from '$lib/auth.svelte';
|
||||||
import {
|
import {
|
||||||
IconServer,
|
IconServer,
|
||||||
IconTemplate,
|
IconBox,
|
||||||
|
IconMonitor,
|
||||||
IconSettings,
|
IconSettings,
|
||||||
IconLogout,
|
IconLogout,
|
||||||
IconSidebar,
|
IconSidebar,
|
||||||
@ -22,7 +23,8 @@
|
|||||||
};
|
};
|
||||||
|
|
||||||
const managementItems: NavItem[] = [
|
const managementItems: NavItem[] = [
|
||||||
{ label: 'Templates', icon: IconTemplate, href: '/admin/templates' },
|
{ label: 'Templates', icon: IconBox, href: '/admin/templates' },
|
||||||
|
{ label: 'Capsules', icon: IconMonitor, href: '/admin/capsules' },
|
||||||
{ label: 'Hosts', icon: IconServer, href: '/admin/hosts' }
|
{ label: 'Hosts', icon: IconServer, href: '/admin/hosts' }
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@ -1,12 +1,15 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { createCapsule, listSnapshots, type Capsule, type CreateCapsuleParams, type Snapshot } from '$lib/api/capsules';
|
import { createCapsule, listSnapshots, type Capsule, type CreateCapsuleParams, type Snapshot } from '$lib/api/capsules';
|
||||||
|
import { createAdminCapsule, listPlatformTemplates } from '$lib/api/admin-capsules';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onclose: () => void;
|
onclose: () => void;
|
||||||
oncreated?: (capsule: Capsule) => void;
|
oncreated?: (capsule: Capsule) => void;
|
||||||
|
/** 'team' = user-scoped templates (default), 'platform' = admin platform templates only */
|
||||||
|
templateSource?: 'team' | 'platform';
|
||||||
};
|
};
|
||||||
let { open, onclose, oncreated }: Props = $props();
|
let { open, onclose, oncreated, templateSource = 'team' }: Props = $props();
|
||||||
|
|
||||||
let createForm = $state<CreateCapsuleParams>({ template: 'minimal', vcpus: 1, memory_mb: 512, timeout_sec: 0 });
|
let createForm = $state<CreateCapsuleParams>({ template: 'minimal', vcpus: 1, memory_mb: 512, timeout_sec: 0 });
|
||||||
let creating = $state(false);
|
let creating = $state(false);
|
||||||
@ -37,7 +40,8 @@
|
|||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (open && templates.length === 0 && !templatesLoading) {
|
if (open && templates.length === 0 && !templatesLoading) {
|
||||||
templatesLoading = true;
|
templatesLoading = true;
|
||||||
listSnapshots().then((result) => {
|
const fetcher = templateSource === 'platform' ? listPlatformTemplates : listSnapshots;
|
||||||
|
fetcher().then((result) => {
|
||||||
if (result.ok) templates = result.data;
|
if (result.ok) templates = result.data;
|
||||||
templatesLoading = false;
|
templatesLoading = false;
|
||||||
});
|
});
|
||||||
@ -112,7 +116,8 @@
|
|||||||
async function handleCreate() {
|
async function handleCreate() {
|
||||||
creating = true;
|
creating = true;
|
||||||
createError = null;
|
createError = null;
|
||||||
const result = await createCapsule(createForm);
|
const creator = templateSource === 'platform' ? createAdminCapsule : createCapsule;
|
||||||
|
const result = await creator(createForm);
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
createForm = { template: 'minimal', vcpus: 1, memory_mb: 512, timeout_sec: 0 };
|
createForm = { template: 'minimal', vcpus: 1, memory_mb: 512, timeout_sec: 0 };
|
||||||
templateQuery = 'minimal';
|
templateQuery = 'minimal';
|
||||||
|
|||||||
@ -1,13 +1,15 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { destroyCapsule } from '$lib/api/capsules';
|
import { destroyCapsule } from '$lib/api/capsules';
|
||||||
|
import type { ApiResult } from '$lib/api/client';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
capsuleId: string;
|
capsuleId: string;
|
||||||
onclose: () => void;
|
onclose: () => void;
|
||||||
ondestroyed?: () => void;
|
ondestroyed?: () => void;
|
||||||
|
destroyFn?: (id: string) => Promise<ApiResult<void>>;
|
||||||
};
|
};
|
||||||
let { open, capsuleId, onclose, ondestroyed }: Props = $props();
|
let { open, capsuleId, onclose, ondestroyed, destroyFn }: Props = $props();
|
||||||
|
|
||||||
let destroying = $state(false);
|
let destroying = $state(false);
|
||||||
let error = $state<string | null>(null);
|
let error = $state<string | null>(null);
|
||||||
@ -15,7 +17,8 @@
|
|||||||
async function handleDestroy() {
|
async function handleDestroy() {
|
||||||
destroying = true;
|
destroying = true;
|
||||||
error = null;
|
error = null;
|
||||||
const result = await destroyCapsule(capsuleId);
|
const destroy = destroyFn ?? destroyCapsule;
|
||||||
|
const result = await destroy(capsuleId);
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
error = null;
|
error = null;
|
||||||
ondestroyed?.();
|
ondestroyed?.();
|
||||||
|
|||||||
@ -14,9 +14,14 @@
|
|||||||
type Props = {
|
type Props = {
|
||||||
capsuleId: string;
|
capsuleId: string;
|
||||||
isRunning: boolean;
|
isRunning: boolean;
|
||||||
|
apiBasePath?: string;
|
||||||
|
/** Hide the file preview pane when no file is selected */
|
||||||
|
compact?: boolean;
|
||||||
|
/** Show only the file tree, completely removing the preview panel */
|
||||||
|
treeOnly?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
let { capsuleId, isRunning }: Props = $props();
|
let { capsuleId, isRunning, apiBasePath = '/api/v1/capsules', compact = false, treeOnly = false }: Props = $props();
|
||||||
|
|
||||||
// Directory navigation state
|
// Directory navigation state
|
||||||
let currentPath = $state('~');
|
let currentPath = $state('~');
|
||||||
@ -95,6 +100,9 @@
|
|||||||
// may point to devices, sockets, or directories that can't be read as a file.
|
// may point to devices, sockets, or directories that can't be read as a file.
|
||||||
const isDownloadable = $derived(selectedFile?.type === 'file');
|
const isDownloadable = $derived(selectedFile?.type === 'file');
|
||||||
|
|
||||||
|
// Device files, pipes, sockets, etc. — can't be read or downloaded.
|
||||||
|
const isSpecialFile = $derived(selectedFile?.type === 'unknown');
|
||||||
|
|
||||||
async function navigateTo(path: string) {
|
async function navigateTo(path: string) {
|
||||||
// Abort any in-flight file read and invalidate stale generation so the
|
// Abort any in-flight file read and invalidate stale generation so the
|
||||||
// abort error isn't surfaced in the UI.
|
// abort error isn't surfaced in the UI.
|
||||||
@ -141,7 +149,7 @@
|
|||||||
dirLoading = true;
|
dirLoading = true;
|
||||||
dirError = null;
|
dirError = null;
|
||||||
const gen = ++dirGeneration;
|
const gen = ++dirGeneration;
|
||||||
const result = await listDir(capsuleId, currentPath);
|
const result = await listDir(capsuleId, currentPath, 1, apiBasePath);
|
||||||
if (gen !== dirGeneration) return; // stale response
|
if (gen !== dirGeneration) return; // stale response
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
entries = result.data.entries ?? [];
|
entries = result.data.entries ?? [];
|
||||||
@ -171,6 +179,11 @@
|
|||||||
fileError = null;
|
fileError = null;
|
||||||
highlightedTokens = null;
|
highlightedTokens = null;
|
||||||
|
|
||||||
|
// Non-regular files (devices, pipes, sockets) — nothing to read
|
||||||
|
if (entry.type === 'unknown') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Check if we should preview or prompt download
|
// Check if we should preview or prompt download
|
||||||
if (isBinaryFile(entry.name) || isFileTooLarge(entry.size)) {
|
if (isBinaryFile(entry.name) || isFileTooLarge(entry.size)) {
|
||||||
// Don't load content — the preview pane will show download prompt
|
// Don't load content — the preview pane will show download prompt
|
||||||
@ -182,7 +195,7 @@
|
|||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
fileAbort = controller;
|
fileAbort = controller;
|
||||||
try {
|
try {
|
||||||
const result = await readFile(capsuleId, entry.path, controller.signal);
|
const result = await readFile(capsuleId, entry.path, controller.signal, apiBasePath);
|
||||||
if (gen !== fileGeneration) return; // stale response — user clicked another file
|
if (gen !== fileGeneration) return; // stale response — user clicked another file
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
if (looksLikeBinary(result.data)) {
|
if (looksLikeBinary(result.data)) {
|
||||||
@ -222,7 +235,7 @@
|
|||||||
if (!selectedFile || downloading || selectedFile.type !== 'file') return;
|
if (!selectedFile || downloading || selectedFile.type !== 'file') return;
|
||||||
downloading = true;
|
downloading = true;
|
||||||
try {
|
try {
|
||||||
await downloadFile(capsuleId, selectedFile.path, selectedFile.name);
|
await downloadFile(capsuleId, selectedFile.path, selectedFile.name, undefined, apiBasePath);
|
||||||
} catch {
|
} catch {
|
||||||
fileError = 'Download failed';
|
fileError = 'Download failed';
|
||||||
}
|
}
|
||||||
@ -239,7 +252,7 @@
|
|||||||
|
|
||||||
async function navigateOrOpenFile(path: string) {
|
async function navigateOrOpenFile(path: string) {
|
||||||
// First try as directory
|
// First try as directory
|
||||||
const dirResult = await listDir(capsuleId, path);
|
const dirResult = await listDir(capsuleId, path, 1, apiBasePath);
|
||||||
if (dirResult.ok) {
|
if (dirResult.ok) {
|
||||||
// Resolve actual path from entries (handles ~ expansion by envd)
|
// Resolve actual path from entries (handles ~ expansion by envd)
|
||||||
const resolvedEntries = dirResult.data.entries ?? [];
|
const resolvedEntries = dirResult.data.entries ?? [];
|
||||||
@ -270,7 +283,7 @@
|
|||||||
// Navigate to parent directory
|
// Navigate to parent directory
|
||||||
currentPath = parentPath;
|
currentPath = parentPath;
|
||||||
pathInput = parentPath;
|
pathInput = parentPath;
|
||||||
const parentResult = await listDir(capsuleId, parentPath);
|
const parentResult = await listDir(capsuleId, parentPath, 1, apiBasePath);
|
||||||
if (parentResult.ok) {
|
if (parentResult.ok) {
|
||||||
entries = parentResult.data.entries ?? [];
|
entries = parentResult.data.entries ?? [];
|
||||||
// Find the file in parent listing
|
// Find the file in parent listing
|
||||||
@ -295,6 +308,7 @@
|
|||||||
function fileIcon(entry: FileEntry): string {
|
function fileIcon(entry: FileEntry): string {
|
||||||
if (entry.type === 'directory') return 'dir';
|
if (entry.type === 'directory') return 'dir';
|
||||||
if (entry.type === 'symlink') return 'link';
|
if (entry.type === 'symlink') return 'link';
|
||||||
|
if (entry.type === 'unknown') return 'special';
|
||||||
return 'file';
|
return 'file';
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -439,8 +453,8 @@
|
|||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col gap-1">
|
<div class="flex flex-col gap-1">
|
||||||
<span class="text-ui font-medium text-[var(--color-text-secondary)]">File browser unavailable</span>
|
<span class="text-ui font-medium text-[var(--color-text-secondary)]">Capsule not running</span>
|
||||||
<span class="text-meta text-[var(--color-text-muted)]">Start the capsule to browse its filesystem</span>
|
<span class="text-meta text-[var(--color-text-muted)]">Start or resume the capsule to browse files</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -448,7 +462,8 @@
|
|||||||
<div class="flex flex-1 min-h-0">
|
<div class="flex flex-1 min-h-0">
|
||||||
|
|
||||||
<!-- Left panel: File tree -->
|
<!-- Left panel: File tree -->
|
||||||
<div class="flex w-[380px] shrink-0 flex-col border-r border-[var(--color-border)] bg-[var(--color-bg-2)]">
|
<div class="flex shrink-0 flex-col bg-[var(--color-bg-2)] {(treeOnly || (compact && !selectedFile)) ? 'flex-1' : compact ? 'w-[28.57%] border-r border-[var(--color-border)]' : 'w-[380px] border-r border-[var(--color-border)]'}"
|
||||||
|
>
|
||||||
|
|
||||||
<!-- Path input -->
|
<!-- Path input -->
|
||||||
<form onsubmit={handlePathSubmit} class="border-b border-[var(--color-border)] px-4 py-3">
|
<form onsubmit={handlePathSubmit} class="border-b border-[var(--color-border)] px-4 py-3">
|
||||||
@ -467,7 +482,7 @@
|
|||||||
onfocus={() => (pathInputFocused = true)}
|
onfocus={() => (pathInputFocused = true)}
|
||||||
onblur={() => (pathInputFocused = false)}
|
onblur={() => (pathInputFocused = false)}
|
||||||
onkeydown={handleKeydown}
|
onkeydown={handleKeydown}
|
||||||
placeholder="Enter path..."
|
placeholder="/home/user or ~/file.txt"
|
||||||
spellcheck="false"
|
spellcheck="false"
|
||||||
autocomplete="off"
|
autocomplete="off"
|
||||||
class="flex-1 bg-transparent font-mono text-meta text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-muted)]"
|
class="flex-1 bg-transparent font-mono text-meta text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-muted)]"
|
||||||
@ -554,7 +569,7 @@
|
|||||||
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" />
|
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" />
|
||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
<span class="text-meta text-[var(--color-text-muted)]">Nothing here yet</span>
|
<span class="text-meta text-[var(--color-text-muted)]">Empty directory</span>
|
||||||
</div>
|
</div>
|
||||||
{:else}
|
{:else}
|
||||||
{#each sortedEntries as entry, idx (entry.path)}
|
{#each sortedEntries as entry, idx (entry.path)}
|
||||||
@ -575,6 +590,11 @@
|
|||||||
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
|
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
|
||||||
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
|
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
|
||||||
</svg>
|
</svg>
|
||||||
|
{:else if fileIcon(entry) === 'special'}
|
||||||
|
<svg class="shrink-0 text-[var(--color-text-muted)]" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="12" cy="12" r="10" />
|
||||||
|
<line x1="4.93" y1="4.93" x2="19.07" y2="19.07" />
|
||||||
|
</svg>
|
||||||
{:else}
|
{:else}
|
||||||
<svg class="shrink-0" style="color: {extColor(entry.name)}" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
<svg class="shrink-0" style="color: {extColor(entry.name)}" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||||
@ -636,6 +656,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Right panel: File preview -->
|
<!-- Right panel: File preview -->
|
||||||
|
{#if !treeOnly && (!compact || selectedFile)}
|
||||||
<div class="flex flex-1 flex-col min-w-0 bg-[var(--color-bg-1)]">
|
<div class="flex flex-1 flex-col min-w-0 bg-[var(--color-bg-1)]">
|
||||||
{#if !selectedFile}
|
{#if !selectedFile}
|
||||||
<!-- Empty state -->
|
<!-- Empty state -->
|
||||||
@ -648,8 +669,8 @@
|
|||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col gap-1">
|
<div class="flex flex-col gap-1">
|
||||||
<span class="text-ui text-[var(--color-text-secondary)]">No file selected</span>
|
<span class="text-ui text-[var(--color-text-secondary)]">Select a file to preview</span>
|
||||||
<span class="text-meta text-[var(--color-text-muted)]">Choose a file from the tree, or enter a path directly</span>
|
<span class="text-meta text-[var(--color-text-muted)]">Click a file in the tree or type a path above</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -683,7 +704,7 @@
|
|||||||
<button
|
<button
|
||||||
onclick={handleDownload}
|
onclick={handleDownload}
|
||||||
disabled={downloading || !isDownloadable}
|
disabled={downloading || !isDownloadable}
|
||||||
title={isDownloadable ? undefined : 'Only regular files can be downloaded'}
|
title={isDownloadable ? 'Download file' : 'Not a regular file — download unavailable'}
|
||||||
class="flex items-center gap-1.5 rounded-[var(--radius-button)] border border-[var(--color-border)] bg-[var(--color-bg-3)] px-2.5 py-1 text-badge font-semibold uppercase tracking-[0.05em] text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-4)] hover:text-[var(--color-text-primary)] disabled:opacity-50 disabled:cursor-not-allowed"
|
class="flex items-center gap-1.5 rounded-[var(--radius-button)] border border-[var(--color-border)] bg-[var(--color-bg-3)] px-2.5 py-1 text-badge font-semibold uppercase tracking-[0.05em] text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-4)] hover:text-[var(--color-text-primary)] disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
>
|
>
|
||||||
{#if downloading}
|
{#if downloading}
|
||||||
@ -720,8 +741,30 @@
|
|||||||
<span class="text-meta text-[var(--color-red)]">{fileError}</span>
|
<span class="text-meta text-[var(--color-red)]">{fileError}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{:else if isSpecialFile}
|
||||||
|
<!-- Device file, pipe, socket, etc. — can't read or download -->
|
||||||
|
<div class="flex flex-1 items-center justify-center py-20">
|
||||||
|
<div class="flex flex-col items-center gap-5 text-center" style="animation: fadeUp 0.25s ease both">
|
||||||
|
<div class="flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-3)]">
|
||||||
|
<svg class="text-[var(--color-text-muted)]" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="12" cy="12" r="10" />
|
||||||
|
<line x1="4.93" y1="4.93" x2="19.07" y2="19.07" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-1.5">
|
||||||
|
<span class="text-ui font-medium text-[var(--color-text-primary)]">Not a regular file</span>
|
||||||
|
<span class="text-meta text-[var(--color-text-tertiary)]">
|
||||||
|
<code class="rounded bg-[var(--color-bg-4)] px-1.5 py-0.5 font-mono text-[var(--color-text-secondary)]">{selectedFile.name}</code>
|
||||||
|
is a device, socket, or pipe
|
||||||
|
</span>
|
||||||
|
<span class="mt-1 text-meta text-[var(--color-text-muted)]">
|
||||||
|
These file types can't be read or downloaded.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
{:else if !isDownloadable}
|
{:else if !isDownloadable}
|
||||||
<!-- Non-regular file (symlink, etc.) — no preview or download -->
|
<!-- Symlink — no preview or download -->
|
||||||
<div class="flex flex-1 items-center justify-center py-20">
|
<div class="flex flex-1 items-center justify-center py-20">
|
||||||
<div class="flex flex-col items-center gap-5 text-center" style="animation: fadeUp 0.25s ease both">
|
<div class="flex flex-col items-center gap-5 text-center" style="animation: fadeUp 0.25s ease both">
|
||||||
<div class="flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-3)]">
|
<div class="flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-3)]">
|
||||||
@ -738,7 +781,7 @@
|
|||||||
</span>
|
</span>
|
||||||
{/if}
|
{/if}
|
||||||
<span class="mt-1 text-meta text-[var(--color-text-muted)]">
|
<span class="mt-1 text-meta text-[var(--color-text-muted)]">
|
||||||
Symlinks can't be downloaded directly. Navigate to the target file instead.
|
Open the target path to view or download its contents.
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -763,14 +806,14 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col gap-1.5">
|
<div class="flex flex-col gap-1.5">
|
||||||
{#if isFileTooLarge(selectedFile.size)}
|
{#if isFileTooLarge(selectedFile.size)}
|
||||||
<span class="text-ui font-medium text-[var(--color-text-primary)]">Too large to preview</span>
|
<span class="text-ui font-medium text-[var(--color-text-primary)]">File too large to preview</span>
|
||||||
<span class="text-meta text-[var(--color-text-tertiary)]">
|
<span class="text-meta text-[var(--color-text-tertiary)]">
|
||||||
{formatFileSize(selectedFile.size)} — preview limit is 10 MB
|
{formatFileSize(selectedFile.size)} exceeds the 10 MB preview limit
|
||||||
</span>
|
</span>
|
||||||
{:else}
|
{:else}
|
||||||
<span class="text-ui font-medium text-[var(--color-text-primary)]">Binary file</span>
|
<span class="text-ui font-medium text-[var(--color-text-primary)]">Binary file</span>
|
||||||
<span class="text-meta text-[var(--color-text-tertiary)]">
|
<span class="text-meta text-[var(--color-text-tertiary)]">
|
||||||
Can't display as text — download to view
|
This file type can't be displayed as text
|
||||||
</span>
|
</span>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
@ -807,6 +850,7 @@
|
|||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
349
frontend/src/lib/components/MetricsPanel.svelte
Normal file
349
frontend/src/lib/components/MetricsPanel.svelte
Normal file
@ -0,0 +1,349 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount, onDestroy, tick } from 'svelte';
|
||||||
|
import {
|
||||||
|
fetchCapsuleMetrics,
|
||||||
|
METRIC_RANGES,
|
||||||
|
METRIC_POLL_INTERVALS,
|
||||||
|
type MetricRange,
|
||||||
|
type MetricPoint
|
||||||
|
} from '$lib/api/metrics';
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
capsuleId: string;
|
||||||
|
/** Whether the capsule is in a state that supports metrics */
|
||||||
|
available: boolean;
|
||||||
|
/** Initial range selection */
|
||||||
|
initialRange?: MetricRange;
|
||||||
|
/** API base path for fetching metrics */
|
||||||
|
apiBasePath?: string;
|
||||||
|
/** Layout: 'full' shows padded cards with gap, 'compact' shows borderless stacked charts */
|
||||||
|
layout?: 'full' | 'compact';
|
||||||
|
};
|
||||||
|
|
||||||
|
let { capsuleId, available, initialRange = '10m', apiBasePath = '/api/v1/capsules', layout = 'full' }: Props = $props();
|
||||||
|
|
||||||
|
let range = $state<MetricRange>(initialRange);
|
||||||
|
let points = $state<MetricPoint[]>([]);
|
||||||
|
let metricsLoading = $state(true);
|
||||||
|
let metricsError = $state<string | null>(null);
|
||||||
|
|
||||||
|
let canvasCpu = $state<HTMLCanvasElement | undefined>(undefined);
|
||||||
|
let canvasRam = $state<HTMLCanvasElement | undefined>(undefined);
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
let chartCpu: any = null;
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
let chartRam: any = null;
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
let ChartJS = $state<any>(null);
|
||||||
|
let pollInterval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
let lastDataKey = '';
|
||||||
|
let visibilityHandler: (() => void) | null = null;
|
||||||
|
|
||||||
|
const latestCpu = $derived<number | null>(
|
||||||
|
points.length > 0 ? points[points.length - 1].cpu_pct : null
|
||||||
|
);
|
||||||
|
const latestRamMB = $derived<number | null>(
|
||||||
|
points.length > 0 ? points[points.length - 1].mem_bytes / 1_048_576 : null
|
||||||
|
);
|
||||||
|
|
||||||
|
async function loadMetrics() {
|
||||||
|
if (!available) return;
|
||||||
|
const result = await fetchCapsuleMetrics(capsuleId, range, apiBasePath);
|
||||||
|
if (result.ok) {
|
||||||
|
points = result.data.points;
|
||||||
|
metricsError = null;
|
||||||
|
} else {
|
||||||
|
metricsError = result.error;
|
||||||
|
}
|
||||||
|
metricsLoading = false;
|
||||||
|
updateCharts();
|
||||||
|
}
|
||||||
|
|
||||||
|
function smooth(data: number[], window: number): number[] {
|
||||||
|
if (window <= 1) return data;
|
||||||
|
const out: number[] = [];
|
||||||
|
for (let i = 0; i < data.length; i++) {
|
||||||
|
const start = Math.max(0, i - Math.floor(window / 2));
|
||||||
|
const end = Math.min(data.length, i + Math.ceil(window / 2));
|
||||||
|
let sum = 0;
|
||||||
|
for (let j = start; j < end; j++) sum += data[j];
|
||||||
|
out.push(+(sum / (end - start)).toFixed(2));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function smoothWindow(count: number): number {
|
||||||
|
if (count < 60) return 1;
|
||||||
|
if (count < 200) return 3;
|
||||||
|
if (count < 600) return 5;
|
||||||
|
return 9;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateCharts() {
|
||||||
|
if (!points.length) return;
|
||||||
|
const key = `${points.length}:${points.at(-1)?.timestamp_unix ?? ''}`;
|
||||||
|
if (key === lastDataKey) return;
|
||||||
|
lastDataKey = key;
|
||||||
|
const labels = points.map((p) => {
|
||||||
|
const d = new Date(p.timestamp_unix * 1000);
|
||||||
|
if (range === '5m' || range === '10m') {
|
||||||
|
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||||
|
}
|
||||||
|
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||||
|
});
|
||||||
|
const w = smoothWindow(points.length);
|
||||||
|
if (chartCpu) {
|
||||||
|
chartCpu.data.labels = labels;
|
||||||
|
chartCpu.data.datasets[0].data = smooth(points.map((p) => +p.cpu_pct.toFixed(2)), w);
|
||||||
|
chartCpu.update();
|
||||||
|
}
|
||||||
|
if (chartRam) {
|
||||||
|
chartRam.data.labels = labels;
|
||||||
|
chartRam.data.datasets[0].data = smooth(points.map((p) => +(p.mem_bytes / 1_048_576).toFixed(1)), w);
|
||||||
|
chartRam.update();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setRange(r: MetricRange) {
|
||||||
|
range = r;
|
||||||
|
lastDataKey = '';
|
||||||
|
metricsLoading = true;
|
||||||
|
restartPolling();
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopPolling() {
|
||||||
|
if (pollInterval) { clearInterval(pollInterval); pollInterval = null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function restartPolling() {
|
||||||
|
stopPolling();
|
||||||
|
loadMetrics();
|
||||||
|
pollInterval = setInterval(loadMetrics, METRIC_POLL_INTERVALS[range]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const C_BLUE = '#5a9fd4';
|
||||||
|
const C_BLUE_FILL = 'rgba(90,159,212,0.11)';
|
||||||
|
const C_AMBER = '#d4a73c';
|
||||||
|
const C_AMBER_FILL = 'rgba(212,167,60,0.11)';
|
||||||
|
const C_GRID = 'rgba(255,255,255,0.05)';
|
||||||
|
const C_TICK = '#635f5c';
|
||||||
|
const FONT_MONO = "'JetBrains Mono', monospace";
|
||||||
|
|
||||||
|
const BASE_CHART_OPTIONS = {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
animation: false as const,
|
||||||
|
interaction: { mode: 'index' as const, intersect: false },
|
||||||
|
plugins: {
|
||||||
|
legend: { display: false },
|
||||||
|
tooltip: {
|
||||||
|
backgroundColor: '#111412',
|
||||||
|
borderColor: '#1f2321',
|
||||||
|
borderWidth: 1,
|
||||||
|
titleColor: '#454340',
|
||||||
|
bodyColor: '#d4cfc8',
|
||||||
|
titleFont: { family: FONT_MONO, size: 10 },
|
||||||
|
bodyFont: { family: FONT_MONO, size: 11 },
|
||||||
|
padding: 10,
|
||||||
|
caretSize: 4,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
scales: {
|
||||||
|
x: {
|
||||||
|
grid: { color: C_GRID },
|
||||||
|
ticks: { color: C_TICK, font: { family: FONT_MONO, size: 10 }, maxTicksLimit: 8, maxRotation: 0 },
|
||||||
|
border: { color: C_GRID },
|
||||||
|
},
|
||||||
|
y: {
|
||||||
|
grid: { color: C_GRID },
|
||||||
|
ticks: { color: C_TICK, font: { family: FONT_MONO, size: 10 } },
|
||||||
|
border: { color: C_GRID },
|
||||||
|
beginAtZero: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function initCharts() {
|
||||||
|
if (!ChartJS || !canvasCpu || !canvasRam) return;
|
||||||
|
chartCpu?.destroy();
|
||||||
|
chartRam?.destroy();
|
||||||
|
|
||||||
|
chartCpu = new ChartJS(canvasCpu, {
|
||||||
|
type: 'line',
|
||||||
|
data: {
|
||||||
|
labels: [],
|
||||||
|
datasets: [{
|
||||||
|
data: [], borderColor: C_BLUE, backgroundColor: C_BLUE_FILL,
|
||||||
|
borderWidth: 2, fill: true, tension: 0, pointRadius: 0,
|
||||||
|
pointHoverRadius: 4, pointHoverBackgroundColor: C_BLUE,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
...BASE_CHART_OPTIONS,
|
||||||
|
plugins: { ...BASE_CHART_OPTIONS.plugins, tooltip: { ...BASE_CHART_OPTIONS.plugins.tooltip,
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
callbacks: { label: (ctx: any) => ` ${ctx.parsed.y.toFixed(1)}%` },
|
||||||
|
}},
|
||||||
|
scales: { ...BASE_CHART_OPTIONS.scales, y: { ...BASE_CHART_OPTIONS.scales.y,
|
||||||
|
ticks: { ...BASE_CHART_OPTIONS.scales.y.ticks, callback: (v: string | number) => `${+v}%` },
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
chartRam = new ChartJS(canvasRam, {
|
||||||
|
type: 'line',
|
||||||
|
data: {
|
||||||
|
labels: [],
|
||||||
|
datasets: [{
|
||||||
|
data: [], borderColor: C_AMBER, backgroundColor: C_AMBER_FILL,
|
||||||
|
borderWidth: 2, fill: true, tension: 0, pointRadius: 0,
|
||||||
|
pointHoverRadius: 4, pointHoverBackgroundColor: C_AMBER,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
...BASE_CHART_OPTIONS,
|
||||||
|
plugins: { ...BASE_CHART_OPTIONS.plugins, tooltip: { ...BASE_CHART_OPTIONS.plugins.tooltip,
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
callbacks: { label: (ctx: any) => ` ${ctx.parsed.y.toFixed(0)} MB` },
|
||||||
|
}},
|
||||||
|
scales: { ...BASE_CHART_OPTIONS.scales, y: { ...BASE_CHART_OPTIONS.scales.y,
|
||||||
|
ticks: { ...BASE_CHART_OPTIONS.scales.y.ticks, callback: (v: string | number) => `${+v} MB` },
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
updateCharts();
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (!ChartJS || !available) return;
|
||||||
|
tick().then(() => {
|
||||||
|
if (canvasCpu && canvasRam) {
|
||||||
|
initCharts();
|
||||||
|
restartPolling();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
stopPolling();
|
||||||
|
chartCpu?.destroy(); chartCpu = null;
|
||||||
|
chartRam?.destroy(); chartRam = null;
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
onMount(async () => {
|
||||||
|
if (!available) return;
|
||||||
|
const mod = await import('chart.js/auto');
|
||||||
|
ChartJS = mod.Chart;
|
||||||
|
|
||||||
|
visibilityHandler = () => {
|
||||||
|
if (document.hidden) {
|
||||||
|
stopPolling();
|
||||||
|
} else if (available) {
|
||||||
|
restartPolling();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener('visibilitychange', visibilityHandler);
|
||||||
|
});
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
|
stopPolling();
|
||||||
|
if (visibilityHandler) document.removeEventListener('visibilitychange', visibilityHandler);
|
||||||
|
chartCpu?.destroy();
|
||||||
|
chartRam?.destroy();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.metric-val {
|
||||||
|
transition: color 0.3s ease;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<div class="flex flex-1 flex-col min-h-0">
|
||||||
|
<!-- Controls row -->
|
||||||
|
<div class="flex shrink-0 items-center justify-between {layout === 'full' ? 'px-0 pb-5' : 'border-b border-[var(--color-border)] bg-[var(--color-bg-1)] px-5 py-2'}">
|
||||||
|
{#if layout === 'full'}
|
||||||
|
{#if !metricsLoading}
|
||||||
|
<span class="flex items-center gap-1.5 rounded-[3px] border border-[var(--color-accent)]/25 bg-[var(--color-accent-glow-mid)] px-2 py-1 text-badge font-semibold uppercase tracking-[0.05em] text-[var(--color-accent-mid)]">
|
||||||
|
<span class="h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]" style="animation: wrenn-glow 2.5s ease-in-out infinite"></span>
|
||||||
|
Live
|
||||||
|
</span>
|
||||||
|
{:else}
|
||||||
|
<div></div>
|
||||||
|
{/if}
|
||||||
|
{:else}
|
||||||
|
<div></div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="flex overflow-hidden rounded-[var(--radius-button)] border border-[var(--color-border)]">
|
||||||
|
{#each METRIC_RANGES as r, i}
|
||||||
|
<button
|
||||||
|
onclick={() => setRange(r)}
|
||||||
|
class="px-3 py-1.5 font-mono text-label transition-colors duration-150
|
||||||
|
{range === r
|
||||||
|
? 'bg-[var(--color-bg-5)] text-[var(--color-text-bright)]'
|
||||||
|
: 'text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-secondary)]'}
|
||||||
|
{i > 0 ? 'border-l border-[var(--color-border)]' : ''}"
|
||||||
|
>
|
||||||
|
{r}
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if metricsError}
|
||||||
|
<div class="flex shrink-0 items-center gap-3 rounded-[var(--radius-card)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/8 px-4 py-3 {layout === 'full' ? 'mb-5' : 'mx-5 my-3'}">
|
||||||
|
<svg class="shrink-0 text-[var(--color-red)]" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
|
||||||
|
</svg>
|
||||||
|
<span class="text-ui text-[var(--color-red)]">Could not load metrics: {metricsError}. Will retry automatically.</span>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<!-- Charts — stacked, each grows to fill half -->
|
||||||
|
<div class="flex flex-1 flex-col min-h-0 {layout === 'full' ? 'gap-5' : 'divide-y divide-[var(--color-border)]'}">
|
||||||
|
|
||||||
|
<!-- CPU Usage -->
|
||||||
|
<div class="flex flex-1 flex-col min-h-0 {layout === 'full' ? 'rounded-[var(--radius-card)] border border-[var(--color-border)] bg-[var(--color-bg-2)]' : 'bg-[var(--color-bg-1)]'}">
|
||||||
|
<div class="flex shrink-0 items-center justify-between {layout === 'full' ? 'border-b border-[var(--color-border)] px-6 py-4' : 'px-5 py-2'}">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="h-2 w-2 shrink-0 rounded-full" style="background: {C_BLUE}"></span>
|
||||||
|
<span class="text-label font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">CPU Usage</span>
|
||||||
|
</div>
|
||||||
|
{#if latestCpu !== null}
|
||||||
|
<div class="flex items-baseline gap-1">
|
||||||
|
<span class="metric-val font-serif {layout === 'full' ? 'text-[2.571rem]' : 'text-heading'} leading-none tracking-[-0.04em] text-[var(--color-text-bright)]">{latestCpu.toFixed(1)}</span>
|
||||||
|
<span class="font-mono {layout === 'full' ? 'text-label' : 'text-badge'} text-[var(--color-text-muted)]">%</span>
|
||||||
|
</div>
|
||||||
|
{:else if metricsLoading}
|
||||||
|
<span class="font-serif {layout === 'full' ? 'text-[2.571rem]' : 'text-heading'} leading-none text-[var(--color-text-muted)]">—</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<div class="relative flex-1 min-h-0 {layout === 'full' ? 'min-h-[180px] px-5 pb-5 pt-3' : 'px-4 pb-3 pt-1'}">
|
||||||
|
<canvas bind:this={canvasCpu}></canvas>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- RAM Usage -->
|
||||||
|
<div class="flex flex-1 flex-col min-h-0 {layout === 'full' ? 'rounded-[var(--radius-card)] border border-[var(--color-border)] bg-[var(--color-bg-2)]' : 'bg-[var(--color-bg-1)]'}">
|
||||||
|
<div class="flex shrink-0 items-center justify-between {layout === 'full' ? 'border-b border-[var(--color-border)] px-6 py-4' : 'px-5 py-2'}">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="h-2 w-2 shrink-0 rounded-full" style="background: {C_AMBER}"></span>
|
||||||
|
<span class="text-label font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">RAM Usage</span>
|
||||||
|
</div>
|
||||||
|
{#if latestRamMB !== null}
|
||||||
|
<div class="flex items-baseline gap-1">
|
||||||
|
<span class="metric-val font-serif {layout === 'full' ? 'text-[2.571rem]' : 'text-heading'} leading-none tracking-[-0.04em] text-[var(--color-text-bright)]">{latestRamMB.toFixed(0)}</span>
|
||||||
|
<span class="font-mono {layout === 'full' ? 'text-label' : 'text-badge'} text-[var(--color-text-muted)]">MB</span>
|
||||||
|
</div>
|
||||||
|
{:else if metricsLoading}
|
||||||
|
<span class="font-serif {layout === 'full' ? 'text-[2.571rem]' : 'text-heading'} leading-none text-[var(--color-text-muted)]">—</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<div class="relative flex-1 min-h-0 {layout === 'full' ? 'min-h-[180px] px-5 pb-5 pt-3' : 'px-4 pb-3 pt-1'}">
|
||||||
|
<canvas bind:this={canvasRam}></canvas>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@ -6,9 +6,10 @@
|
|||||||
capsuleId: string;
|
capsuleId: string;
|
||||||
isRunning: boolean;
|
isRunning: boolean;
|
||||||
visible?: boolean;
|
visible?: boolean;
|
||||||
|
apiBasePath?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
let { capsuleId, isRunning, visible = true }: Props = $props();
|
let { capsuleId, isRunning, visible = true, apiBasePath = '/api/v1/capsules' }: Props = $props();
|
||||||
|
|
||||||
type ConnectionState = 'idle' | 'connecting' | 'connected' | 'disconnected' | 'error';
|
type ConnectionState = 'idle' | 'connecting' | 'connected' | 'disconnected' | 'error';
|
||||||
|
|
||||||
@ -93,7 +94,7 @@
|
|||||||
function getWsUrl(): string {
|
function getWsUrl(): string {
|
||||||
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||||
const token = auth.token ? `?token=${encodeURIComponent(auth.token)}` : '';
|
const token = auth.token ? `?token=${encodeURIComponent(auth.token)}` : '';
|
||||||
return `${proto}//${window.location.host}/api/v1/capsules/${capsuleId}/pty${token}`;
|
return `${proto}//${window.location.host}${apiBasePath}/${capsuleId}/pty${token}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function wsSend(ws: WebSocket | null, data: string) {
|
function wsSend(ws: WebSocket | null, data: string) {
|
||||||
|
|||||||
560
frontend/src/routes/admin/capsules/+page.svelte
Normal file
560
frontend/src/routes/admin/capsules/+page.svelte
Normal file
@ -0,0 +1,560 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import AdminSidebar from '$lib/components/AdminSidebar.svelte';
|
||||||
|
import CreateCapsuleDialog from '$lib/components/CreateCapsuleDialog.svelte';
|
||||||
|
import DestroyDialog from '$lib/components/DestroyDialog.svelte';
|
||||||
|
import CopyButton from '$lib/components/CopyButton.svelte';
|
||||||
|
import { onMount, onDestroy } from 'svelte';
|
||||||
|
import { goto } from '$app/navigation';
|
||||||
|
import { toast } from '$lib/toast.svelte';
|
||||||
|
import {
|
||||||
|
listAdminCapsules,
|
||||||
|
destroyAdminCapsule,
|
||||||
|
} from '$lib/api/admin-capsules';
|
||||||
|
import type { Capsule } from '$lib/api/capsules';
|
||||||
|
|
||||||
|
const REFRESH_INTERVAL = 15;
|
||||||
|
const SPIN_DURATION = 600;
|
||||||
|
|
||||||
|
let collapsed = $state(
|
||||||
|
typeof window !== 'undefined'
|
||||||
|
? localStorage.getItem('wrenn_sidebar_collapsed') === 'true'
|
||||||
|
: false
|
||||||
|
);
|
||||||
|
|
||||||
|
let capsules = $state<Capsule[]>([]);
|
||||||
|
let loading = $state(true);
|
||||||
|
let error = $state<string | null>(null);
|
||||||
|
let showCreateDialog = $state(false);
|
||||||
|
let searchQuery = $state('');
|
||||||
|
let spinning = $state(false);
|
||||||
|
|
||||||
|
// Auto-refresh
|
||||||
|
let autoRefresh = $state(true);
|
||||||
|
let countdown = $state(REFRESH_INTERVAL);
|
||||||
|
let countdownInterval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
let refreshInterval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
|
// Sorting
|
||||||
|
type SortKey = 'status' | 'vcpus' | 'memory_mb' | 'started_at' | 'template';
|
||||||
|
let sortKey = $state<SortKey | null>(null);
|
||||||
|
let sortDir = $state<'asc' | 'desc'>('asc');
|
||||||
|
|
||||||
|
// Destroy state
|
||||||
|
let destroyTarget = $state<Capsule | null>(null);
|
||||||
|
|
||||||
|
// Animation tracking
|
||||||
|
let initialAnimationDone = $state(false);
|
||||||
|
let newCapsuleId = $state<string | null>(null);
|
||||||
|
|
||||||
|
let runningCount = $derived(capsules.filter((c) => c.status === 'running').length);
|
||||||
|
|
||||||
|
let filteredCapsules = $derived.by(() => {
|
||||||
|
let list = searchQuery
|
||||||
|
? capsules.filter((c) =>
|
||||||
|
c.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
c.template.toLowerCase().includes(searchQuery.toLowerCase())
|
||||||
|
)
|
||||||
|
: [...capsules];
|
||||||
|
|
||||||
|
if (sortKey) {
|
||||||
|
const key = sortKey;
|
||||||
|
const dir = sortDir === 'asc' ? 1 : -1;
|
||||||
|
list.sort((a, b) => {
|
||||||
|
if (key === 'status' || key === 'template') {
|
||||||
|
return a[key].localeCompare(b[key]) * dir;
|
||||||
|
}
|
||||||
|
if (key === 'started_at') {
|
||||||
|
const ta = a.started_at ? new Date(a.started_at).getTime() : 0;
|
||||||
|
const tb = b.started_at ? new Date(b.started_at).getTime() : 0;
|
||||||
|
return (ta - tb) * dir;
|
||||||
|
}
|
||||||
|
return ((a[key] as number) - (b[key] as number)) * dir;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return list;
|
||||||
|
});
|
||||||
|
|
||||||
|
function toggleSort(key: SortKey) {
|
||||||
|
if (sortKey === key) {
|
||||||
|
sortDir = sortDir === 'asc' ? 'desc' : 'asc';
|
||||||
|
} else {
|
||||||
|
sortKey = key;
|
||||||
|
sortDir = 'asc';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function startAutoRefresh() {
|
||||||
|
stopAutoRefresh();
|
||||||
|
countdown = REFRESH_INTERVAL;
|
||||||
|
countdownInterval = setInterval(() => {
|
||||||
|
countdown--;
|
||||||
|
if (countdown <= 0) countdown = REFRESH_INTERVAL;
|
||||||
|
}, 1000);
|
||||||
|
refreshInterval = setInterval(fetchCapsules, REFRESH_INTERVAL * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopAutoRefresh() {
|
||||||
|
if (countdownInterval) { clearInterval(countdownInterval); countdownInterval = null; }
|
||||||
|
if (refreshInterval) { clearInterval(refreshInterval); refreshInterval = null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleAutoRefresh() {
|
||||||
|
autoRefresh = !autoRefresh;
|
||||||
|
if (autoRefresh) {
|
||||||
|
startAutoRefresh();
|
||||||
|
} else {
|
||||||
|
stopAutoRefresh();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchCapsules(manual = false) {
|
||||||
|
const wasEmpty = capsules.length === 0;
|
||||||
|
if (wasEmpty) loading = true;
|
||||||
|
|
||||||
|
if (manual) {
|
||||||
|
spinning = true;
|
||||||
|
var spinTimer = new Promise<void>((resolve) => setTimeout(resolve, SPIN_DURATION));
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await listAdminCapsules();
|
||||||
|
if (result.ok) {
|
||||||
|
capsules = result.data;
|
||||||
|
error = null;
|
||||||
|
} else {
|
||||||
|
error = result.error;
|
||||||
|
}
|
||||||
|
loading = false;
|
||||||
|
|
||||||
|
if (!initialAnimationDone) {
|
||||||
|
setTimeout(() => { initialAnimationDone = true; }, 400 + (capsules.length * 40));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (autoRefresh) countdown = REFRESH_INTERVAL;
|
||||||
|
|
||||||
|
if (manual) {
|
||||||
|
await spinTimer!;
|
||||||
|
spinning = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleCreated(capsule: Capsule) {
|
||||||
|
goto(`/admin/capsules/${capsule.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleDestroyed() {
|
||||||
|
if (destroyTarget) {
|
||||||
|
const id = destroyTarget.id;
|
||||||
|
capsules = capsules.filter((c) => c.id !== id);
|
||||||
|
toast.success('Capsule destroyed');
|
||||||
|
}
|
||||||
|
destroyTarget = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusColor(status: string): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'running': return 'var(--color-accent)';
|
||||||
|
case 'paused': return 'var(--color-amber)';
|
||||||
|
case 'error': return 'var(--color-red)';
|
||||||
|
default: return 'var(--color-text-muted)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusBg(status: string): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'running': return 'rgba(94,140,88,0.12)';
|
||||||
|
case 'paused': return 'rgba(212,167,60,0.12)';
|
||||||
|
case 'error': return 'rgba(207,129,114,0.12)';
|
||||||
|
default: return 'rgba(255,255,255,0.05)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusBorder(status: string): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'running': return 'rgba(94,140,88,0.3)';
|
||||||
|
case 'paused': return 'rgba(212,167,60,0.3)';
|
||||||
|
case 'error': return 'rgba(207,129,114,0.3)';
|
||||||
|
default: return 'rgba(255,255,255,0.08)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(iso: string | null | undefined): string {
|
||||||
|
if (!iso) return '\u2014';
|
||||||
|
return new Date(iso).toLocaleString([], {
|
||||||
|
month: 'short', day: 'numeric',
|
||||||
|
hour: '2-digit', minute: '2-digit',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function timeAgo(iso: string | undefined): string {
|
||||||
|
if (!iso) return '';
|
||||||
|
const seconds = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
|
||||||
|
if (seconds < 60) return `${seconds}s ago`;
|
||||||
|
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
|
||||||
|
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
|
||||||
|
return `${Math.floor(seconds / 86400)}d ago`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleVisibility() {
|
||||||
|
if (document.hidden) {
|
||||||
|
stopAutoRefresh();
|
||||||
|
} else if (autoRefresh) {
|
||||||
|
fetchCapsules();
|
||||||
|
startAutoRefresh();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
fetchCapsules();
|
||||||
|
startAutoRefresh();
|
||||||
|
document.addEventListener('visibilitychange', handleVisibility);
|
||||||
|
});
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
|
stopAutoRefresh();
|
||||||
|
document.removeEventListener('visibilitychange', handleVisibility);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>Wrenn Admin — Capsules</title>
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.refresh-spin {
|
||||||
|
animation: spin-once 0.6s ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes capsule-born {
|
||||||
|
0%, 25% { background-color: rgba(94, 140, 88, 0.1); }
|
||||||
|
100% { background-color: transparent; }
|
||||||
|
}
|
||||||
|
.capsule-born {
|
||||||
|
animation: capsule-born 1.6s ease-out forwards;
|
||||||
|
}
|
||||||
|
|
||||||
|
.row-stripe {
|
||||||
|
transform: scaleY(0);
|
||||||
|
transform-origin: center;
|
||||||
|
transition: transform 0.18s cubic-bezier(0.25, 1, 0.5, 1);
|
||||||
|
}
|
||||||
|
.capsule-row:hover .row-stripe {
|
||||||
|
transform: scaleY(1);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<div class="flex h-screen overflow-hidden bg-[var(--color-bg-0)]">
|
||||||
|
<AdminSidebar bind:collapsed />
|
||||||
|
|
||||||
|
<main class="flex min-w-0 flex-1 flex-col overflow-hidden">
|
||||||
|
<!-- Header -->
|
||||||
|
<div class="shrink-0 px-8 pt-8 pb-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 class="font-serif text-page leading-none tracking-[-0.03em] text-[var(--color-text-bright)]">
|
||||||
|
Capsules
|
||||||
|
</h1>
|
||||||
|
<p class="mt-2 text-ui text-[var(--color-text-secondary)]">
|
||||||
|
Launch temporary capsules to build and snapshot platform templates.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
{#if !loading && runningCount > 0}
|
||||||
|
<div class="flex items-center gap-2.5 rounded-[var(--radius-card)] border border-[var(--color-accent)]/20 bg-[var(--color-bg-2)] px-3.5 py-2">
|
||||||
|
<span class="relative flex h-[8px] w-[8px]">
|
||||||
|
<span class="animate-status-ping absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]"></span>
|
||||||
|
<span class="relative inline-flex h-[8px] w-[8px] rounded-full bg-[var(--color-accent)]"></span>
|
||||||
|
</span>
|
||||||
|
<span class="font-mono text-body font-semibold text-[var(--color-accent-bright)]">{runningCount}</span>
|
||||||
|
<span class="text-ui text-[var(--color-text-secondary)]">running</span>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<button
|
||||||
|
onclick={() => { showCreateDialog = true; }}
|
||||||
|
class="group flex items-center gap-2.5 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2.5 text-ui font-semibold text-white shadow-sm transition-all duration-200 hover:shadow-[0_0_20px_var(--color-accent-glow-mid)] hover:brightness-115 hover:-translate-y-px active:translate-y-0"
|
||||||
|
>
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="transition-transform duration-200 group-hover:rotate-90"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
|
||||||
|
Launch Capsule
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Content -->
|
||||||
|
<div class="flex-1 overflow-y-auto px-8 pb-6" style="animation: fadeUp 0.35s ease both">
|
||||||
|
<!-- Toolbar -->
|
||||||
|
<div class="mb-4 flex items-center gap-3">
|
||||||
|
<div class="relative flex-1 max-w-[300px]">
|
||||||
|
<svg class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)]" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" />
|
||||||
|
</svg>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Search by ID or template..."
|
||||||
|
bind:value={searchQuery}
|
||||||
|
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-2)] py-2 pl-9 pr-3 font-mono text-ui text-[var(--color-text-bright)] outline-none placeholder:text-[var(--color-text-muted)] transition-colors duration-150 focus:border-[var(--color-accent)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span class="text-ui text-[var(--color-text-secondary)]">{filteredCapsules.length} capsule{filteredCapsules.length !== 1 ? 's' : ''}</span>
|
||||||
|
|
||||||
|
<div class="flex-1"></div>
|
||||||
|
|
||||||
|
<!-- Refresh -->
|
||||||
|
<button
|
||||||
|
onclick={() => fetchCapsules(true)}
|
||||||
|
disabled={spinning}
|
||||||
|
class="flex h-8 w-8 items-center justify-center rounded-[var(--radius-button)] border border-[var(--color-border)] text-[var(--color-text-tertiary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-secondary)] disabled:opacity-50"
|
||||||
|
title="Refresh"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
class={spinning ? 'refresh-spin' : ''}
|
||||||
|
width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<polyline points="23 4 23 10 17 10" />
|
||||||
|
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- Auto-refresh countdown -->
|
||||||
|
<button
|
||||||
|
onclick={toggleAutoRefresh}
|
||||||
|
class="flex items-center gap-1.5 rounded-[var(--radius-button)] border px-2.5 py-1.5 font-mono text-label transition-colors duration-150
|
||||||
|
{autoRefresh
|
||||||
|
? 'border-[var(--color-accent)]/30 text-[var(--color-accent-mid)] hover:border-[var(--color-accent)]/50'
|
||||||
|
: 'border-[var(--color-border)] text-[var(--color-text-muted)] hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-secondary)]'}"
|
||||||
|
title={autoRefresh ? 'Click to disable auto-refresh' : `Click to enable auto-refresh (${REFRESH_INTERVAL}s)`}
|
||||||
|
>
|
||||||
|
{#if autoRefresh}
|
||||||
|
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||||
|
<circle cx="8" cy="8" r="5" stroke="var(--color-accent-glow-mid)" stroke-width="1.5" />
|
||||||
|
<circle
|
||||||
|
cx="8" cy="8" r="5"
|
||||||
|
stroke="var(--color-accent)"
|
||||||
|
stroke-width="1.5"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-dasharray="31.416"
|
||||||
|
stroke-dashoffset={31.416 * (1 - countdown / REFRESH_INTERVAL)}
|
||||||
|
transform="rotate(-90 8 8)"
|
||||||
|
style="transition: stroke-dashoffset 1s linear"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
{countdown}s
|
||||||
|
{:else}
|
||||||
|
Off
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if error}
|
||||||
|
<div class="mb-4 flex items-start gap-3 rounded-[var(--radius-card)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-4 py-3">
|
||||||
|
<svg class="mt-0.5 shrink-0 text-[var(--color-red)]" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
|
||||||
|
</svg>
|
||||||
|
<span class="text-ui text-[var(--color-red)]">{error}. Try refreshing the page.</span>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<!-- Table -->
|
||||||
|
<div class="rounded-[var(--radius-card)] border border-[var(--color-border)] overflow-hidden">
|
||||||
|
<!-- Header row -->
|
||||||
|
<div class="grid grid-cols-[1.6fr_0.9fr_0.5fr_0.5fr_1fr_0.7fr_0.8fr] rounded-t-[var(--radius-card)] border-b border-[var(--color-border)] bg-[var(--color-bg-3)]">
|
||||||
|
<div class="px-5 py-3 text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">ID</div>
|
||||||
|
{@render sortableHeader('Template', 'template')}
|
||||||
|
{@render sortableHeader('CPU', 'vcpus')}
|
||||||
|
{@render sortableHeader('Memory', 'memory_mb')}
|
||||||
|
{@render sortableHeader('Started', 'started_at')}
|
||||||
|
{@render sortableHeader('Status', 'status')}
|
||||||
|
<div class="px-5 py-3 text-right text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Actions</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if loading && capsules.length === 0}
|
||||||
|
<div class="flex items-center justify-center py-16">
|
||||||
|
<div class="flex items-center gap-3 text-ui text-[var(--color-text-secondary)]">
|
||||||
|
<svg class="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||||
|
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
|
||||||
|
</svg>
|
||||||
|
Loading capsules...
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else if filteredCapsules.length === 0 && searchQuery}
|
||||||
|
<div class="flex flex-col items-center justify-center py-[72px]">
|
||||||
|
<div class="relative mb-5">
|
||||||
|
<div class="relative flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-border)] bg-[var(--color-bg-3)]">
|
||||||
|
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--color-text-muted)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">
|
||||||
|
No matching capsules
|
||||||
|
</p>
|
||||||
|
<p class="mt-1.5 text-ui text-[var(--color-text-tertiary)]">
|
||||||
|
No capsules match "<span class="font-mono text-[var(--color-text-secondary)]">{searchQuery}</span>".
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
onclick={() => { searchQuery = ''; }}
|
||||||
|
class="mt-4 rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-ui text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)]"
|
||||||
|
>
|
||||||
|
Clear search
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{:else if filteredCapsules.length === 0}
|
||||||
|
<div class="flex flex-col items-center justify-center py-[72px]">
|
||||||
|
<div class="relative mb-5">
|
||||||
|
<div class="absolute inset-0 -m-4 rounded-full" style="background: radial-gradient(circle, rgba(94,140,88,0.08) 0%, transparent 70%)"></div>
|
||||||
|
<div class="relative flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-accent)]/20 bg-[var(--color-bg-3)]" style="animation: iconFloat 4s ease-in-out infinite">
|
||||||
|
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--color-accent-mid)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<polyline points="4 17 10 11 4 5" /><line x1="12" y1="19" x2="20" y2="19" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">
|
||||||
|
No capsules
|
||||||
|
</p>
|
||||||
|
<p class="mt-1.5 max-w-[340px] text-center text-ui text-[var(--color-text-tertiary)]">
|
||||||
|
Launch a capsule, configure it interactively, then snapshot it as a platform template.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
onclick={() => { showCreateDialog = true; }}
|
||||||
|
class="mt-6 flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2.5 text-ui font-semibold text-white shadow-sm transition-all duration-200 hover:shadow-[0_0_20px_var(--color-accent-glow-mid)] hover:brightness-115 hover:-translate-y-px active:translate-y-0"
|
||||||
|
>
|
||||||
|
Launch Capsule
|
||||||
|
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
{#each filteredCapsules as capsule, i (capsule.id)}
|
||||||
|
{@const stripeColor = capsule.status === 'running' ? 'bg-[var(--color-accent)]' : capsule.status === 'paused' ? 'bg-[var(--color-amber)]' : capsule.status === 'error' ? 'bg-[var(--color-red)]' : 'bg-[var(--color-text-muted)]'}
|
||||||
|
<div
|
||||||
|
class="capsule-row relative grid grid-cols-[1.6fr_0.9fr_0.5fr_0.5fr_1fr_0.7fr_0.8fr] items-center overflow-hidden border-b border-[var(--color-border)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] last:border-b-0 {newCapsuleId === capsule.id ? 'capsule-born' : ''}"
|
||||||
|
style={initialAnimationDone ? '' : `animation: fadeUp 0.35s ease both; animation-delay: ${i * 40}ms`}
|
||||||
|
>
|
||||||
|
<!-- Left accent stripe -->
|
||||||
|
<div class="row-stripe pointer-events-none absolute left-0 top-0 h-full w-0.5 {stripeColor}"></div>
|
||||||
|
|
||||||
|
<!-- ID -->
|
||||||
|
<div class="flex items-center gap-2.5 px-5 py-4">
|
||||||
|
{#if capsule.status === 'running'}
|
||||||
|
<span class="relative flex h-[6px] w-[6px] shrink-0">
|
||||||
|
<span class="animate-status-ping absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]"></span>
|
||||||
|
<span class="relative inline-flex h-[6px] w-[6px] rounded-full bg-[var(--color-accent)]"></span>
|
||||||
|
</span>
|
||||||
|
{:else if capsule.status === 'paused'}
|
||||||
|
<span class="inline-flex h-[6px] w-[6px] shrink-0 rounded-full bg-[var(--color-amber)]"></span>
|
||||||
|
{:else if capsule.status === 'error'}
|
||||||
|
<span class="inline-flex h-[6px] w-[6px] shrink-0 rounded-full bg-[var(--color-red)]"></span>
|
||||||
|
{:else}
|
||||||
|
<span class="inline-flex h-[6px] w-[6px] shrink-0 rounded-full bg-[var(--color-text-muted)]"></span>
|
||||||
|
{/if}
|
||||||
|
{#if searchQuery && capsule.id.toLowerCase().includes(searchQuery.toLowerCase())}
|
||||||
|
{@const matchIdx = capsule.id.toLowerCase().indexOf(searchQuery.toLowerCase())}
|
||||||
|
<a href="/admin/capsules/{capsule.id}" class="font-mono text-ui text-[var(--color-text-bright)] hover:text-[var(--color-accent-bright)] transition-colors duration-150">{capsule.id.slice(0, matchIdx)}<mark class="rounded-[2px] bg-[var(--color-accent-glow-mid)] px-0.5 text-[var(--color-accent-bright)] not-italic">{capsule.id.slice(matchIdx, matchIdx + searchQuery.length)}</mark>{capsule.id.slice(matchIdx + searchQuery.length)}</a>
|
||||||
|
{:else}
|
||||||
|
<a href="/admin/capsules/{capsule.id}" class="font-mono text-ui text-[var(--color-text-bright)] hover:text-[var(--color-accent-bright)] transition-colors duration-150">{capsule.id}</a>
|
||||||
|
{/if}
|
||||||
|
<CopyButton value={capsule.id} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Template -->
|
||||||
|
<div class="min-w-0 px-5 py-4">
|
||||||
|
<span class="block truncate font-mono text-ui text-[var(--color-text-secondary)]">{capsule.template}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- CPU -->
|
||||||
|
<div class="px-5 py-4">
|
||||||
|
<span class="font-mono text-ui text-[var(--color-text-secondary)]">{capsule.vcpus}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Memory -->
|
||||||
|
<div class="px-5 py-4">
|
||||||
|
<span class="font-mono text-ui text-[var(--color-text-secondary)]">{capsule.memory_mb}MB</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Started -->
|
||||||
|
<div class="px-5 py-4">
|
||||||
|
<span class="text-ui text-[var(--color-text-secondary)]" title={capsule.started_at ?? ''}>{formatTime(capsule.started_at)}</span>
|
||||||
|
{#if capsule.last_active_at}
|
||||||
|
<span class="ml-1.5 text-label text-[var(--color-text-muted)]">active {timeAgo(capsule.last_active_at)}</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Status -->
|
||||||
|
<div class="px-5 py-4">
|
||||||
|
<span
|
||||||
|
class="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-label font-semibold uppercase tracking-[0.05em]"
|
||||||
|
style="color: {statusColor(capsule.status)}; background: {statusBg(capsule.status)}; border: 1px solid {statusBorder(capsule.status)}"
|
||||||
|
>
|
||||||
|
{capsule.status}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Actions -->
|
||||||
|
<div class="flex items-center justify-end gap-2 px-5 py-4">
|
||||||
|
{#if capsule.status === 'running' || capsule.status === 'paused'}
|
||||||
|
<button
|
||||||
|
onclick={() => { destroyTarget = capsule; }}
|
||||||
|
class="rounded-[var(--radius-button)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/8 px-3 py-1.5 text-meta font-medium text-[var(--color-red)] transition-all duration-150 hover:bg-[var(--color-red)]/15 hover:border-[var(--color-red)]/50"
|
||||||
|
>
|
||||||
|
Destroy
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Status bar -->
|
||||||
|
<footer
|
||||||
|
class="flex h-7 shrink-0 items-center justify-end border-t border-[var(--color-border)] bg-[var(--color-bg-1)] px-8"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-1.5">
|
||||||
|
<span class="relative flex h-[5px] w-[5px]">
|
||||||
|
<span class="animate-status-ping absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]"></span>
|
||||||
|
<span class="relative inline-flex h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]"></span>
|
||||||
|
</span>
|
||||||
|
<span class="font-mono text-label uppercase tracking-[0.04em] text-[var(--color-text-secondary)]">All systems operational</span>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<CreateCapsuleDialog
|
||||||
|
open={showCreateDialog}
|
||||||
|
onclose={() => { showCreateDialog = false; }}
|
||||||
|
oncreated={handleCreated}
|
||||||
|
templateSource="platform"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{#if destroyTarget}
|
||||||
|
<DestroyDialog
|
||||||
|
open={true}
|
||||||
|
capsuleId={destroyTarget.id}
|
||||||
|
onclose={() => { destroyTarget = null; }}
|
||||||
|
ondestroyed={handleDestroyed}
|
||||||
|
destroyFn={destroyAdminCapsule}
|
||||||
|
/>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#snippet sortableHeader(label: string, key: SortKey)}
|
||||||
|
<button
|
||||||
|
onclick={() => toggleSort(key)}
|
||||||
|
class="flex items-center gap-1 px-5 py-3 text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)] transition-colors duration-150 hover:text-[var(--color-text-secondary)]"
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
{#if sortKey === key}
|
||||||
|
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" class="text-[var(--color-accent)]">
|
||||||
|
{#if sortDir === 'asc'}
|
||||||
|
<polyline points="18 15 12 9 6 15" />
|
||||||
|
{:else}
|
||||||
|
<polyline points="6 9 12 15 18 9" />
|
||||||
|
{/if}
|
||||||
|
</svg>
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
{/snippet}
|
||||||
334
frontend/src/routes/admin/capsules/[id]/+page.svelte
Normal file
334
frontend/src/routes/admin/capsules/[id]/+page.svelte
Normal file
@ -0,0 +1,334 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount, onDestroy } from 'svelte';
|
||||||
|
import { page } from '$app/stores';
|
||||||
|
import { goto } from '$app/navigation';
|
||||||
|
import AdminSidebar from '$lib/components/AdminSidebar.svelte';
|
||||||
|
import TerminalTab from '$lib/components/TerminalTab.svelte';
|
||||||
|
import FilesTab from '$lib/components/FilesTab.svelte';
|
||||||
|
import MetricsPanel from '$lib/components/MetricsPanel.svelte';
|
||||||
|
import DestroyDialog from '$lib/components/DestroyDialog.svelte';
|
||||||
|
import CopyButton from '$lib/components/CopyButton.svelte';
|
||||||
|
import { toast } from '$lib/toast.svelte';
|
||||||
|
import {
|
||||||
|
getAdminCapsule,
|
||||||
|
destroyAdminCapsule,
|
||||||
|
snapshotAdminCapsule,
|
||||||
|
} from '$lib/api/admin-capsules';
|
||||||
|
import type { Capsule } from '$lib/api/capsules';
|
||||||
|
|
||||||
|
const capsuleId: string = $page.params.id ?? '';
|
||||||
|
const API_BASE = '/api/v1/admin/capsules';
|
||||||
|
|
||||||
|
let collapsed = $state(
|
||||||
|
typeof window !== 'undefined'
|
||||||
|
? localStorage.getItem('wrenn_sidebar_collapsed') === 'true'
|
||||||
|
: false
|
||||||
|
);
|
||||||
|
|
||||||
|
let capsule = $state<Capsule | null>(null);
|
||||||
|
let capsuleLoading = $state(true);
|
||||||
|
let capsuleError = $state<string | null>(null);
|
||||||
|
|
||||||
|
// Destroy dialog
|
||||||
|
let showDestroy = $state(false);
|
||||||
|
|
||||||
|
// Snapshot dialog
|
||||||
|
let showSnapshot = $state(false);
|
||||||
|
let snapshotName = $state('');
|
||||||
|
let snapshotting = $state(false);
|
||||||
|
let snapshotError = $state<string | null>(null);
|
||||||
|
|
||||||
|
const metricsAvailable = $derived(
|
||||||
|
capsule?.status === 'running' || capsule?.status === 'paused'
|
||||||
|
);
|
||||||
|
|
||||||
|
async function loadCapsule() {
|
||||||
|
const result = await getAdminCapsule(capsuleId);
|
||||||
|
if (result.ok) {
|
||||||
|
capsule = result.data;
|
||||||
|
capsuleError = null;
|
||||||
|
} else {
|
||||||
|
capsuleError = result.error;
|
||||||
|
}
|
||||||
|
capsuleLoading = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSnapshot() {
|
||||||
|
snapshotting = true;
|
||||||
|
snapshotError = null;
|
||||||
|
const result = await snapshotAdminCapsule(capsuleId, snapshotName.trim() || undefined);
|
||||||
|
if (result.ok) {
|
||||||
|
toast.success(`Snapshot "${result.data.name}" created`);
|
||||||
|
goto('/admin/templates');
|
||||||
|
} else {
|
||||||
|
snapshotError = result.error;
|
||||||
|
}
|
||||||
|
snapshotting = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusColor(status: string): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'running': return 'var(--color-accent)';
|
||||||
|
case 'paused': return 'var(--color-amber)';
|
||||||
|
case 'error': return 'var(--color-red)';
|
||||||
|
default: return 'var(--color-text-muted)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusBg(status: string): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'running': return 'rgba(94,140,88,0.12)';
|
||||||
|
case 'paused': return 'rgba(212,167,60,0.12)';
|
||||||
|
case 'error': return 'rgba(207,129,114,0.12)';
|
||||||
|
default: return 'rgba(255,255,255,0.05)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusBorder(status: string): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'running': return 'rgba(94,140,88,0.3)';
|
||||||
|
case 'paused': return 'rgba(212,167,60,0.3)';
|
||||||
|
case 'error': return 'rgba(207,129,114,0.3)';
|
||||||
|
default: return 'rgba(255,255,255,0.08)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
|
function startPolling() {
|
||||||
|
stopPolling();
|
||||||
|
pollTimer = setInterval(loadCapsule, 10_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopPolling() {
|
||||||
|
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleVisibility() {
|
||||||
|
if (document.hidden) {
|
||||||
|
stopPolling();
|
||||||
|
} else {
|
||||||
|
loadCapsule();
|
||||||
|
startPolling();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
loadCapsule();
|
||||||
|
startPolling();
|
||||||
|
document.addEventListener('visibilitychange', handleVisibility);
|
||||||
|
});
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
|
stopPolling();
|
||||||
|
document.removeEventListener('visibilitychange', handleVisibility);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>Wrenn Admin — {capsuleId}</title>
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<div class="flex h-screen overflow-hidden bg-[var(--color-bg-0)]">
|
||||||
|
<AdminSidebar bind:collapsed />
|
||||||
|
|
||||||
|
<main class="flex min-w-0 flex-1 flex-col overflow-hidden">
|
||||||
|
{#if capsuleLoading}
|
||||||
|
<div class="flex flex-1 items-center justify-center">
|
||||||
|
<div class="flex items-center gap-3 text-ui text-[var(--color-text-secondary)]">
|
||||||
|
<svg class="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56" /></svg>
|
||||||
|
Loading capsule...
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else if capsuleError}
|
||||||
|
<div class="p-8">
|
||||||
|
<div class="flex items-center gap-3 rounded-[var(--radius-card)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/8 px-5 py-4">
|
||||||
|
<svg class="shrink-0 text-[var(--color-red)]" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
|
||||||
|
</svg>
|
||||||
|
<span class="text-ui text-[var(--color-red)]">{capsuleError}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else if capsule}
|
||||||
|
<!-- Breadcrumb + summary + actions -->
|
||||||
|
<div class="shrink-0 px-7 pt-8">
|
||||||
|
<div class="flex items-center gap-2.5">
|
||||||
|
<a
|
||||||
|
href="/admin/capsules"
|
||||||
|
class="font-serif text-page leading-none tracking-[-0.02em] text-[var(--color-text-secondary)] transition-colors duration-150 hover:text-[var(--color-text-bright)]"
|
||||||
|
>
|
||||||
|
Capsules
|
||||||
|
</a>
|
||||||
|
<span class="text-[var(--color-text-muted)] select-none" style="font-size: 1.1rem">›</span>
|
||||||
|
<span class="flex items-center gap-1.5">
|
||||||
|
<span class="font-mono text-[1.1rem] leading-none text-[var(--color-text-bright)]">{capsuleId}</span>
|
||||||
|
<CopyButton value={capsuleId} />
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<span
|
||||||
|
class="ml-1 inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-label font-semibold uppercase tracking-[0.05em]"
|
||||||
|
style="color: {statusColor(capsule.status)}; background: {statusBg(capsule.status)}; border: 1px solid {statusBorder(capsule.status)}"
|
||||||
|
>
|
||||||
|
{#if capsule.status === 'running'}
|
||||||
|
<span class="relative flex h-[5px] w-[5px] shrink-0">
|
||||||
|
<span class="animate-status-ping absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]"></span>
|
||||||
|
<span class="relative inline-flex h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]"></span>
|
||||||
|
</span>
|
||||||
|
{/if}
|
||||||
|
{capsule.status}
|
||||||
|
</span>
|
||||||
|
<span class="font-mono text-ui text-[var(--color-text-muted)]">{capsule.template} · {capsule.vcpus}v · {capsule.memory_mb}MB</span>
|
||||||
|
|
||||||
|
<div class="ml-auto flex items-center gap-2">
|
||||||
|
{#if capsule.status === 'running' || capsule.status === 'paused'}
|
||||||
|
<button
|
||||||
|
onclick={() => { showSnapshot = true; snapshotName = ''; snapshotError = null; }}
|
||||||
|
disabled={snapshotting}
|
||||||
|
class="flex items-center gap-1.5 rounded-[var(--radius-button)] border border-[var(--color-accent)]/30 bg-[var(--color-accent)]/8 px-3 py-1.5 text-meta font-medium text-[var(--color-accent-bright)] transition-all duration-150 hover:bg-[var(--color-accent)]/15 hover:border-[var(--color-accent)]/50 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 4h-5L7 7H2v13a2 2 0 002 2h16a2 2 0 002-2V7h-5l-2.5-3z" /><circle cx="12" cy="15" r="3" /></svg>
|
||||||
|
Snapshot
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onclick={() => { showDestroy = true; }}
|
||||||
|
class="flex items-center gap-1.5 rounded-[var(--radius-button)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/8 px-3 py-1.5 text-meta font-medium text-[var(--color-red)] transition-all duration-150 hover:bg-[var(--color-red)]/15 hover:border-[var(--color-red)]/50"
|
||||||
|
>
|
||||||
|
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6" /><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2" /></svg>
|
||||||
|
Destroy
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-5 shrink-0 border-b border-[var(--color-border)]"></div>
|
||||||
|
|
||||||
|
<!-- Split panels: 50/50 -->
|
||||||
|
<div class="flex flex-1 overflow-hidden">
|
||||||
|
<!-- Left: Terminal -->
|
||||||
|
<div class="flex w-1/2 flex-col overflow-hidden border-r border-[var(--color-border)]">
|
||||||
|
<TerminalTab {capsuleId} isRunning={capsule.status === 'running'} apiBasePath={API_BASE} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Right: Metrics (top 50%) + Files (bottom 50%) -->
|
||||||
|
<div class="flex w-1/2 flex-col overflow-hidden">
|
||||||
|
{#if metricsAvailable}
|
||||||
|
<div class="flex flex-1 flex-col min-h-0 border-b border-[var(--color-border)]">
|
||||||
|
<MetricsPanel {capsuleId} available={metricsAvailable} initialRange="5m" apiBasePath={API_BASE} layout="compact" />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="flex flex-1 flex-col min-h-0 overflow-hidden">
|
||||||
|
<FilesTab {capsuleId} isRunning={capsule.status === 'running'} apiBasePath={API_BASE} compact />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<!-- Status bar -->
|
||||||
|
<footer
|
||||||
|
class="flex h-7 shrink-0 items-center justify-end border-t border-[var(--color-border)] bg-[var(--color-bg-1)] px-7"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-1.5">
|
||||||
|
<span class="relative flex h-[5px] w-[5px]">
|
||||||
|
<span class="animate-status-ping absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]"></span>
|
||||||
|
<span class="relative inline-flex h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]"></span>
|
||||||
|
</span>
|
||||||
|
<span class="font-mono text-label uppercase tracking-[0.04em] text-[var(--color-text-secondary)]">All systems operational</span>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Snapshot dialog -->
|
||||||
|
{#if showSnapshot}
|
||||||
|
<div class="fixed inset-0 z-50 flex items-center justify-center">
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
|
<div
|
||||||
|
class="absolute inset-0 bg-black/60"
|
||||||
|
onclick={() => { if (!snapshotting) showSnapshot = false; }}
|
||||||
|
onkeydown={(e) => { if (e.key === 'Escape' && !snapshotting) showSnapshot = false; }}
|
||||||
|
></div>
|
||||||
|
|
||||||
|
<div class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] overflow-hidden" style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)">
|
||||||
|
<div class="flex items-center gap-4 border-b border-[var(--color-border)] bg-[var(--color-bg-3)] px-6 py-5">
|
||||||
|
<div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-[var(--radius-input)] bg-[var(--color-accent)]/15 text-[var(--color-accent)] shadow-[0_0_12px_var(--color-accent-glow)]">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M14.5 4h-5L7 7H2v13a2 2 0 002 2h16a2 2 0 002-2V7h-5l-2.5-3z" />
|
||||||
|
<circle cx="12" cy="15" r="3" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2 class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">Snapshot as platform template</h2>
|
||||||
|
<p class="mt-0.5 text-meta text-[var(--color-text-muted)] font-mono">{capsuleId}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="px-6 pt-5 pb-6 space-y-4">
|
||||||
|
<div class="flex items-start gap-2.5 rounded-[var(--radius-input)] border border-[var(--color-amber)]/25 bg-[var(--color-amber)]/8 px-3 py-2.5">
|
||||||
|
<svg class="mt-px shrink-0 text-[var(--color-amber)]" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
|
||||||
|
<line x1="12" y1="9" x2="12" y2="13" />
|
||||||
|
<line x1="12" y1="17" x2="12.01" y2="17" />
|
||||||
|
</svg>
|
||||||
|
<p class="text-meta text-[var(--color-amber)] leading-relaxed">This will <strong class="font-semibold">pause, snapshot, and destroy</strong> the capsule. The snapshot will be available as a platform template for all teams.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if snapshotError}
|
||||||
|
<div class="rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-meta text-[var(--color-red)]">
|
||||||
|
{snapshotError}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div class="mb-1.5 flex items-baseline justify-between">
|
||||||
|
<label class="text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="admin-snapshot-name">Template name</label>
|
||||||
|
<span class="text-meta text-[var(--color-text-muted)]">optional</span>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
id="admin-snapshot-name"
|
||||||
|
type="text"
|
||||||
|
bind:value={snapshotName}
|
||||||
|
disabled={snapshotting}
|
||||||
|
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-ui text-[var(--color-text-bright)] outline-none placeholder:text-[var(--color-text-muted)] transition-colors duration-150 focus:border-[var(--color-accent)] disabled:opacity-50"
|
||||||
|
placeholder="e.g. python-3.12, node-22-dev"
|
||||||
|
onkeydown={(e) => { if (e.key === 'Enter' && !snapshotting) handleSnapshot(); }}
|
||||||
|
/>
|
||||||
|
<p class="mt-1.5 text-meta text-[var(--color-text-muted)]">Leave blank for an auto-generated name. If the name already exists, it will be overwritten.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex justify-end gap-3 pt-1">
|
||||||
|
<button
|
||||||
|
onclick={() => { showSnapshot = false; }}
|
||||||
|
disabled={snapshotting}
|
||||||
|
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-ui text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onclick={handleSnapshot}
|
||||||
|
disabled={snapshotting}
|
||||||
|
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
|
||||||
|
>
|
||||||
|
{#if snapshotting}
|
||||||
|
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||||
|
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
|
||||||
|
</svg>
|
||||||
|
Snapshotting...
|
||||||
|
{:else}
|
||||||
|
Snapshot & Destroy
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<DestroyDialog
|
||||||
|
open={showDestroy}
|
||||||
|
{capsuleId}
|
||||||
|
onclose={() => { showDestroy = false; }}
|
||||||
|
ondestroyed={() => { toast.success('Capsule destroyed'); goto('/admin/capsules'); }}
|
||||||
|
destroyFn={destroyAdminCapsule}
|
||||||
|
/>
|
||||||
@ -727,20 +727,16 @@
|
|||||||
<!-- ── Create Template Dialog ──────────────────────────────────────── -->
|
<!-- ── Create Template Dialog ──────────────────────────────────────── -->
|
||||||
{#if showCreate}
|
{#if showCreate}
|
||||||
<div class="fixed inset-0 z-50 flex items-center justify-center">
|
<div class="fixed inset-0 z-50 flex items-center justify-center">
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
<div
|
<div
|
||||||
class="absolute inset-0 bg-black/60"
|
class="absolute inset-0 bg-black/60"
|
||||||
role="button"
|
|
||||||
tabindex="-1"
|
|
||||||
onclick={() => { if (!creating) showCreate = false; }}
|
onclick={() => { if (!creating) showCreate = false; }}
|
||||||
onkeydown={(e) => { if (e.key === 'Escape' && !creating) showCreate = false; }}
|
onkeydown={(e) => { if (e.key === 'Escape' && !creating) showCreate = false; }}
|
||||||
></div>
|
></div>
|
||||||
<div
|
<div
|
||||||
class="relative w-full max-w-[520px] max-h-[90vh] overflow-y-auto rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] shadow-dialog"
|
class="relative w-full max-w-[520px] max-h-[90vh] overflow-y-auto rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)]"
|
||||||
style="animation: fadeUp 0.18s cubic-bezier(0.25,1,0.5,1) both"
|
style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)"
|
||||||
>
|
>
|
||||||
<!-- Top accent edge -->
|
|
||||||
<div class="h-[2px] rounded-t-[var(--radius-card)] bg-gradient-to-r from-transparent via-[var(--color-accent)] to-transparent"></div>
|
|
||||||
|
|
||||||
<div class="p-6">
|
<div class="p-6">
|
||||||
<h2 class="font-serif text-heading leading-tight tracking-[-0.02em] text-[var(--color-text-bright)]">
|
<h2 class="font-serif text-heading leading-tight tracking-[-0.02em] text-[var(--color-text-bright)]">
|
||||||
Create Template
|
Create Template
|
||||||
@ -903,7 +899,7 @@
|
|||||||
<button
|
<button
|
||||||
onclick={handleCreate}
|
onclick={handleCreate}
|
||||||
disabled={creating || !createForm.name.trim() || !createForm.recipe.trim()}
|
disabled={creating || !createForm.name.trim() || !createForm.recipe.trim()}
|
||||||
class="group flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2.5 text-ui font-semibold text-white transition-all duration-200 hover:shadow-[0_0_20px_var(--color-accent-glow-mid)] hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0 disabled:hover:shadow-none"
|
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
|
||||||
>
|
>
|
||||||
{#if creating}
|
{#if creating}
|
||||||
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
|
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
|
||||||
@ -921,20 +917,16 @@
|
|||||||
<!-- ── Delete Template Confirmation ────────────────────────────────── -->
|
<!-- ── Delete Template Confirmation ────────────────────────────────── -->
|
||||||
{#if deleteTarget}
|
{#if deleteTarget}
|
||||||
<div class="fixed inset-0 z-50 flex items-center justify-center">
|
<div class="fixed inset-0 z-50 flex items-center justify-center">
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
<div
|
<div
|
||||||
class="absolute inset-0 bg-black/60"
|
class="absolute inset-0 bg-black/60"
|
||||||
role="button"
|
|
||||||
tabindex="-1"
|
|
||||||
onclick={() => { if (!deleting) deleteTarget = null; }}
|
onclick={() => { if (!deleting) deleteTarget = null; }}
|
||||||
onkeydown={(e) => { if (e.key === 'Escape' && !deleting) deleteTarget = null; }}
|
onkeydown={(e) => { if (e.key === 'Escape' && !deleting) deleteTarget = null; }}
|
||||||
></div>
|
></div>
|
||||||
<div
|
<div
|
||||||
class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] shadow-dialog"
|
class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)]"
|
||||||
style="animation: fadeUp 0.18s cubic-bezier(0.25,1,0.5,1) both"
|
style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)"
|
||||||
>
|
>
|
||||||
<!-- Danger accent edge -->
|
|
||||||
<div class="h-[2px] rounded-t-[var(--radius-card)] bg-gradient-to-r from-transparent via-[var(--color-red)] to-transparent"></div>
|
|
||||||
|
|
||||||
<div class="p-6">
|
<div class="p-6">
|
||||||
<h2 class="font-serif text-heading leading-tight tracking-[-0.02em] text-[var(--color-text-bright)]">
|
<h2 class="font-serif text-heading leading-tight tracking-[-0.02em] text-[var(--color-text-bright)]">
|
||||||
Delete Template
|
Delete Template
|
||||||
@ -960,7 +952,7 @@
|
|||||||
<button
|
<button
|
||||||
onclick={handleDeleteTemplate}
|
onclick={handleDeleteTemplate}
|
||||||
disabled={deleting}
|
disabled={deleting}
|
||||||
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-red)] px-5 py-2.5 text-ui font-semibold text-white transition-all duration-200 hover:shadow-[0_0_16px_rgba(207,129,114,0.25)] hover:brightness-110 disabled:opacity-50"
|
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-red)] px-5 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-110 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
|
||||||
>
|
>
|
||||||
{#if deleting}
|
{#if deleting}
|
||||||
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
|
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
|
||||||
|
|||||||
247
internal/api/handlers_admin_capsules.go
Normal file
247
internal/api/handlers_admin_capsules.go
Normal file
@ -0,0 +1,247 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"connectrpc.com/connect"
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
"git.omukk.dev/wrenn/wrenn/internal/audit"
|
||||||
|
"git.omukk.dev/wrenn/wrenn/internal/auth"
|
||||||
|
"git.omukk.dev/wrenn/wrenn/internal/db"
|
||||||
|
"git.omukk.dev/wrenn/wrenn/internal/id"
|
||||||
|
"git.omukk.dev/wrenn/wrenn/internal/lifecycle"
|
||||||
|
"git.omukk.dev/wrenn/wrenn/internal/service"
|
||||||
|
"git.omukk.dev/wrenn/wrenn/internal/validate"
|
||||||
|
pb "git.omukk.dev/wrenn/wrenn/proto/hostagent/gen"
|
||||||
|
)
|
||||||
|
|
||||||
|
type adminCapsuleHandler struct {
|
||||||
|
svc *service.SandboxService
|
||||||
|
db *db.Queries
|
||||||
|
pool *lifecycle.HostClientPool
|
||||||
|
audit *audit.AuditLogger
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAdminCapsuleHandler(svc *service.SandboxService, db *db.Queries, pool *lifecycle.HostClientPool, al *audit.AuditLogger) *adminCapsuleHandler {
|
||||||
|
return &adminCapsuleHandler{svc: svc, db: db, pool: pool, audit: al}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create handles POST /v1/admin/capsules.
|
||||||
|
func (h *adminCapsuleHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req createSandboxRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid_request", "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ac := auth.MustFromContext(r.Context())
|
||||||
|
|
||||||
|
sb, err := h.svc.Create(r.Context(), service.SandboxCreateParams{
|
||||||
|
TeamID: id.PlatformTeamID,
|
||||||
|
Template: req.Template,
|
||||||
|
VCPUs: req.VCPUs,
|
||||||
|
MemoryMB: req.MemoryMB,
|
||||||
|
TimeoutSec: req.TimeoutSec,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
status, code, msg := serviceErrToHTTP(err)
|
||||||
|
writeError(w, status, code, msg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.audit.LogSandboxCreate(r.Context(), ac, sb.ID, sb.Template)
|
||||||
|
writeJSON(w, http.StatusCreated, sandboxToResponse(sb))
|
||||||
|
}
|
||||||
|
|
||||||
|
// List handles GET /v1/admin/capsules.
|
||||||
|
func (h *adminCapsuleHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||||
|
sandboxes, err := h.svc.List(r.Context(), id.PlatformTeamID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "db_error", "failed to list sandboxes")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resp := make([]sandboxResponse, len(sandboxes))
|
||||||
|
for i, sb := range sandboxes {
|
||||||
|
resp[i] = sandboxToResponse(sb)
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get handles GET /v1/admin/capsules/{id}.
|
||||||
|
func (h *adminCapsuleHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||||
|
sandboxIDStr := chi.URLParam(r, "id")
|
||||||
|
|
||||||
|
sandboxID, err := id.ParseSandboxID(sandboxIDStr)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid_request", "invalid sandbox ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
sb, err := h.svc.Get(r.Context(), sandboxID, id.PlatformTeamID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusNotFound, "not_found", "sandbox not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, sandboxToResponse(sb))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Destroy handles DELETE /v1/admin/capsules/{id}.
|
||||||
|
func (h *adminCapsuleHandler) Destroy(w http.ResponseWriter, r *http.Request) {
|
||||||
|
sandboxIDStr := chi.URLParam(r, "id")
|
||||||
|
ac := auth.MustFromContext(r.Context())
|
||||||
|
|
||||||
|
sandboxID, err := id.ParseSandboxID(sandboxIDStr)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid_request", "invalid sandbox ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.svc.Destroy(r.Context(), sandboxID, id.PlatformTeamID); err != nil {
|
||||||
|
status, code, msg := serviceErrToHTTP(err)
|
||||||
|
writeError(w, status, code, msg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.audit.LogSandboxDestroy(r.Context(), ac, sandboxID)
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
type adminSnapshotRequest struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snapshot handles POST /v1/admin/capsules/{id}/snapshot.
|
||||||
|
// Pauses the capsule, takes a snapshot as a platform template, then destroys the capsule.
|
||||||
|
func (h *adminCapsuleHandler) Snapshot(w http.ResponseWriter, r *http.Request) {
|
||||||
|
sandboxIDStr := chi.URLParam(r, "id")
|
||||||
|
ac := auth.MustFromContext(r.Context())
|
||||||
|
|
||||||
|
sandboxID, err := id.ParseSandboxID(sandboxIDStr)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid_request", "invalid sandbox ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req adminSnapshotRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid_request", "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Name == "" {
|
||||||
|
req.Name = id.NewSnapshotName()
|
||||||
|
}
|
||||||
|
if err := validate.SafeName(req.Name); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid_request", fmt.Sprintf("invalid snapshot name: %s", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
// Verify sandbox exists and belongs to platform team BEFORE any
|
||||||
|
// destructive operations (template overwrite).
|
||||||
|
sb, err := h.db.GetSandboxByTeam(ctx, db.GetSandboxByTeamParams{ID: sandboxID, TeamID: id.PlatformTeamID})
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusNotFound, "not_found", "sandbox not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if sb.Status != "running" && sb.Status != "paused" {
|
||||||
|
writeError(w, http.StatusConflict, "invalid_state", "sandbox must be running or paused")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if name already exists as a platform template.
|
||||||
|
if existing, err := h.db.GetPlatformTemplateByName(ctx, req.Name); err == nil {
|
||||||
|
// Delete old snapshot files from all hosts before removing the DB record.
|
||||||
|
if err := deleteSnapshotBroadcast(ctx, h.db, h.pool, existing.TeamID, existing.ID); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "agent_error", "failed to delete existing snapshot files")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.db.DeleteTemplateByTeam(ctx, db.DeleteTemplateByTeamParams{Name: req.Name, TeamID: id.PlatformTeamID}); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "db_error", "failed to remove existing template record")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
agent, err := agentForHost(ctx, h.db, h.pool, sb.HostID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusServiceUnavailable, "host_unavailable", "sandbox host is not reachable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pre-mark sandbox as "paused" to prevent the reconciler from racing.
|
||||||
|
if sb.Status == "running" {
|
||||||
|
if _, err := h.db.UpdateSandboxStatus(ctx, db.UpdateSandboxStatusParams{
|
||||||
|
ID: sandboxID, Status: "paused",
|
||||||
|
}); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "db_error", "failed to update sandbox status")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use a detached context so the snapshot completes even if the client disconnects.
|
||||||
|
snapCtx, snapCancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||||
|
defer snapCancel()
|
||||||
|
|
||||||
|
newTemplateID := id.NewTemplateID()
|
||||||
|
|
||||||
|
resp, err := agent.CreateSnapshot(snapCtx, connect.NewRequest(&pb.CreateSnapshotRequest{
|
||||||
|
SandboxId: sandboxIDStr,
|
||||||
|
Name: req.Name,
|
||||||
|
TeamId: formatUUIDForRPC(id.PlatformTeamID),
|
||||||
|
TemplateId: formatUUIDForRPC(newTemplateID),
|
||||||
|
}))
|
||||||
|
if err != nil {
|
||||||
|
// Snapshot failed — revert status.
|
||||||
|
if sb.Status == "running" {
|
||||||
|
if _, dbErr := h.db.UpdateSandboxStatus(snapCtx, db.UpdateSandboxStatusParams{
|
||||||
|
ID: sandboxID, Status: "running",
|
||||||
|
}); dbErr != nil {
|
||||||
|
slog.Error("failed to revert sandbox status after snapshot error", "sandbox_id", sandboxIDStr, "error", dbErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
status, code, msg := agentErrToHTTP(err)
|
||||||
|
writeError(w, status, code, msg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpl, err := h.db.InsertTemplate(snapCtx, db.InsertTemplateParams{
|
||||||
|
ID: newTemplateID,
|
||||||
|
Name: req.Name,
|
||||||
|
Type: "snapshot",
|
||||||
|
Vcpus: sb.Vcpus,
|
||||||
|
MemoryMb: sb.MemoryMb,
|
||||||
|
SizeBytes: resp.Msg.SizeBytes,
|
||||||
|
TeamID: id.PlatformTeamID,
|
||||||
|
DefaultUser: "root",
|
||||||
|
DefaultEnv: []byte("{}"),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("failed to insert template record", "name", req.Name, "error", err)
|
||||||
|
writeError(w, http.StatusInternalServerError, "db_error", "snapshot created but failed to record in database")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Destroy the ephemeral capsule after successful snapshot.
|
||||||
|
if err := h.svc.Destroy(snapCtx, sandboxID, id.PlatformTeamID); err != nil {
|
||||||
|
slog.Error("failed to destroy capsule after snapshot", "sandbox_id", sandboxIDStr, "error", err)
|
||||||
|
// Don't fail the response — the snapshot was created successfully.
|
||||||
|
}
|
||||||
|
|
||||||
|
h.audit.LogSnapshotCreate(snapCtx, ac, req.Name)
|
||||||
|
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
slog.Info("snapshot created but client disconnected before response", "name", req.Name)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, templateToResponse(tmpl))
|
||||||
|
}
|
||||||
@ -126,6 +126,14 @@ func (h *authHandler) Signup(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
qtx := h.db.WithTx(tx)
|
qtx := h.db.WithTx(tx)
|
||||||
|
|
||||||
|
// The first user to sign up becomes a platform admin.
|
||||||
|
userCount, err := qtx.CountUsers(ctx)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "db_error", "failed to check user count")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
isFirstUser := userCount == 0
|
||||||
|
|
||||||
userID := id.NewUserID()
|
userID := id.NewUserID()
|
||||||
_, err = qtx.InsertUser(ctx, db.InsertUserParams{
|
_, err = qtx.InsertUser(ctx, db.InsertUserParams{
|
||||||
ID: userID,
|
ID: userID,
|
||||||
@ -143,6 +151,13 @@ func (h *authHandler) Signup(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if isFirstUser {
|
||||||
|
if err := qtx.SetUserAdmin(ctx, db.SetUserAdminParams{ID: userID, IsAdmin: true}); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "db_error", "failed to set admin status")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Create default team.
|
// Create default team.
|
||||||
teamID := id.NewTeamID()
|
teamID := id.NewTeamID()
|
||||||
if _, err := qtx.InsertTeam(ctx, db.InsertTeamParams{
|
if _, err := qtx.InsertTeam(ctx, db.InsertTeamParams{
|
||||||
@ -169,7 +184,7 @@ func (h *authHandler) Signup(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
token, err := auth.SignJWT(h.jwtSecret, userID, teamID, req.Email, req.Name, "owner", false)
|
token, err := auth.SignJWT(h.jwtSecret, userID, teamID, req.Email, req.Name, "owner", isFirstUser)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, "internal_error", "failed to generate token")
|
writeError(w, http.StatusInternalServerError, "internal_error", "failed to generate token")
|
||||||
return
|
return
|
||||||
|
|||||||
@ -38,8 +38,8 @@ func newSnapshotHandler(svc *service.TemplateService, db *db.Queries, pool *life
|
|||||||
// deleteSnapshotBroadcast attempts to delete snapshot files on all online hosts.
|
// deleteSnapshotBroadcast attempts to delete snapshot files on all online hosts.
|
||||||
// Snapshots aren't currently host-tracked in the DB, so we broadcast to all hosts
|
// Snapshots aren't currently host-tracked in the DB, so we broadcast to all hosts
|
||||||
// and ignore NotFound errors.
|
// and ignore NotFound errors.
|
||||||
func (h *snapshotHandler) deleteSnapshotBroadcast(ctx context.Context, teamID, templateID pgtype.UUID) error {
|
func deleteSnapshotBroadcast(ctx context.Context, queries *db.Queries, pool *lifecycle.HostClientPool, teamID, templateID pgtype.UUID) error {
|
||||||
hosts, err := h.db.ListActiveHosts(ctx)
|
hosts, err := queries.ListActiveHosts(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("list hosts: %w", err)
|
return fmt.Errorf("list hosts: %w", err)
|
||||||
}
|
}
|
||||||
@ -47,7 +47,7 @@ func (h *snapshotHandler) deleteSnapshotBroadcast(ctx context.Context, teamID, t
|
|||||||
if host.Status != "online" {
|
if host.Status != "online" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
agent, err := h.pool.GetForHost(host)
|
agent, err := pool.GetForHost(host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -141,7 +141,7 @@ func (h *snapshotHandler) Create(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Delete old snapshot files from all hosts before removing the DB record.
|
// Delete old snapshot files from all hosts before removing the DB record.
|
||||||
if err := h.deleteSnapshotBroadcast(ctx, existing.TeamID, existing.ID); err != nil {
|
if err := deleteSnapshotBroadcast(ctx, h.db, h.pool, existing.TeamID, existing.ID); err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, "agent_error", "failed to delete existing snapshot files")
|
writeError(w, http.StatusInternalServerError, "agent_error", "failed to delete existing snapshot files")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -279,7 +279,7 @@ func (h *snapshotHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.deleteSnapshotBroadcast(ctx, tmpl.TeamID, tmpl.ID); err != nil {
|
if err := deleteSnapshotBroadcast(ctx, h.db, h.pool, tmpl.TeamID, tmpl.ID); err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, "agent_error", "failed to delete snapshot files")
|
writeError(w, http.StatusInternalServerError, "agent_error", "failed to delete snapshot files")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,8 +5,23 @@ import (
|
|||||||
|
|
||||||
"git.omukk.dev/wrenn/wrenn/internal/auth"
|
"git.omukk.dev/wrenn/wrenn/internal/auth"
|
||||||
"git.omukk.dev/wrenn/wrenn/internal/db"
|
"git.omukk.dev/wrenn/wrenn/internal/db"
|
||||||
|
"git.omukk.dev/wrenn/wrenn/internal/id"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// injectPlatformTeam overwrites the AuthContext's TeamID with the platform
|
||||||
|
// sentinel UUID. This lets existing team-scoped handlers (exec, files, pty,
|
||||||
|
// metrics) work unchanged under admin routes. Must run after requireAdmin.
|
||||||
|
func injectPlatformTeam() func(http.Handler) http.Handler {
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ac := auth.MustFromContext(r.Context())
|
||||||
|
ac.TeamID = id.PlatformTeamID
|
||||||
|
ctx := auth.WithAuthContext(r.Context(), ac)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// requireAdmin validates that the authenticated user is a platform admin.
|
// requireAdmin validates that the authenticated user is a platform admin.
|
||||||
// Must run after requireJWT (depends on AuthContext being present).
|
// Must run after requireJWT (depends on AuthContext being present).
|
||||||
// Re-validates against the DB — the JWT is_admin claim is for UI only;
|
// Re-validates against the DB — the JWT is_admin claim is for UI only;
|
||||||
|
|||||||
@ -8,18 +8,21 @@ import (
|
|||||||
"git.omukk.dev/wrenn/wrenn/internal/id"
|
"git.omukk.dev/wrenn/wrenn/internal/id"
|
||||||
)
|
)
|
||||||
|
|
||||||
// requireJWT validates the Authorization: Bearer <token> header, verifies the JWT
|
// requireJWT validates a JWT from the Authorization: Bearer header or the
|
||||||
// signature and expiry, and stamps UserID + TeamID + Email into the request context.
|
// ?token= query parameter (for WebSocket connections that cannot send headers).
|
||||||
func requireJWT(secret []byte) func(http.Handler) http.Handler {
|
func requireJWT(secret []byte) func(http.Handler) http.Handler {
|
||||||
return func(next http.Handler) http.Handler {
|
return func(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
header := r.Header.Get("Authorization")
|
var tokenStr string
|
||||||
if !strings.HasPrefix(header, "Bearer ") {
|
if header := r.Header.Get("Authorization"); strings.HasPrefix(header, "Bearer ") {
|
||||||
|
tokenStr = strings.TrimPrefix(header, "Bearer ")
|
||||||
|
} else if t := r.URL.Query().Get("token"); t != "" {
|
||||||
|
tokenStr = t
|
||||||
|
}
|
||||||
|
if tokenStr == "" {
|
||||||
writeError(w, http.StatusUnauthorized, "unauthorized", "Authorization: Bearer <token> required")
|
writeError(w, http.StatusUnauthorized, "unauthorized", "Authorization: Bearer <token> required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
tokenStr := strings.TrimPrefix(header, "Bearer ")
|
|
||||||
claims, err := auth.VerifyJWT(secret, tokenStr)
|
claims, err := auth.VerifyJWT(secret, tokenStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired token")
|
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired token")
|
||||||
|
|||||||
@ -74,6 +74,7 @@ func New(
|
|||||||
buildH := newBuildHandler(buildSvc, queries, pool)
|
buildH := newBuildHandler(buildSvc, queries, pool)
|
||||||
channelH := newChannelHandler(channelSvc, al)
|
channelH := newChannelHandler(channelSvc, al)
|
||||||
ptyH := newPtyHandler(queries, pool)
|
ptyH := newPtyHandler(queries, pool)
|
||||||
|
adminCapsules := newAdminCapsuleHandler(sandboxSvc, queries, pool, al)
|
||||||
|
|
||||||
// OpenAPI spec and docs.
|
// OpenAPI spec and docs.
|
||||||
r.Get("/openapi.yaml", serveOpenAPI)
|
r.Get("/openapi.yaml", serveOpenAPI)
|
||||||
@ -207,6 +208,23 @@ func New(
|
|||||||
r.Get("/builds", buildH.List)
|
r.Get("/builds", buildH.List)
|
||||||
r.Get("/builds/{id}", buildH.Get)
|
r.Get("/builds/{id}", buildH.Get)
|
||||||
r.Post("/builds/{id}/cancel", buildH.Cancel)
|
r.Post("/builds/{id}/cancel", buildH.Cancel)
|
||||||
|
r.Post("/capsules", adminCapsules.Create)
|
||||||
|
r.Get("/capsules", adminCapsules.List)
|
||||||
|
r.Route("/capsules/{id}", func(r chi.Router) {
|
||||||
|
r.Use(injectPlatformTeam())
|
||||||
|
r.Get("/", adminCapsules.Get)
|
||||||
|
r.Delete("/", adminCapsules.Destroy)
|
||||||
|
r.Post("/snapshot", adminCapsules.Snapshot)
|
||||||
|
r.Post("/exec", exec.Exec)
|
||||||
|
r.Get("/exec/stream", execStream.ExecStream)
|
||||||
|
r.Post("/files/write", files.Upload)
|
||||||
|
r.Post("/files/read", files.Download)
|
||||||
|
r.Post("/files/list", fsH.ListDir)
|
||||||
|
r.Post("/files/mkdir", fsH.MakeDir)
|
||||||
|
r.Post("/files/remove", fsH.Remove)
|
||||||
|
r.Get("/metrics", metricsH.GetMetrics)
|
||||||
|
r.Get("/pty", ptyH.PtySession)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
return &Server{router: r, BuildSvc: buildSvc}
|
return &Server{router: r, BuildSvc: buildSvc}
|
||||||
|
|||||||
@ -11,6 +11,17 @@ import (
|
|||||||
"github.com/jackc/pgx/v5/pgtype"
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const countUsers = `-- name: CountUsers :one
|
||||||
|
SELECT COUNT(*) FROM users
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) CountUsers(ctx context.Context) (int64, error) {
|
||||||
|
row := q.db.QueryRow(ctx, countUsers)
|
||||||
|
var count int64
|
||||||
|
err := row.Scan(&count)
|
||||||
|
return count, err
|
||||||
|
}
|
||||||
|
|
||||||
const deleteAdminPermission = `-- name: DeleteAdminPermission :exec
|
const deleteAdminPermission = `-- name: DeleteAdminPermission :exec
|
||||||
DELETE FROM admin_permissions WHERE user_id = $1 AND permission = $2
|
DELETE FROM admin_permissions WHERE user_id = $1 AND permission = $2
|
||||||
`
|
`
|
||||||
|
|||||||
Reference in New Issue
Block a user