1
0
forked from wrenn/wrenn

Add admin capsule management, fix file browser for special files, normalize dialog styles

- Admin capsule CRUD: list, create (platform templates), get detail with
  terminal/files/metrics, snapshot, destroy
- First signup auto-promotes to platform admin
- JWT auth via query param for WebSocket connections
- File browser: handle non-regular files (devices, pipes, sockets) gracefully
  instead of showing raw backend errors
- Normalize admin template dialogs to match established dialog patterns:
  remove accent bars, unify animation/shadow/button styles
This commit is contained in:
2026-04-13 04:12:36 +06:00
parent f920023ecf
commit 90bea52ccd
19 changed files with 1417 additions and 50 deletions

View 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 };
}

View File

@ -4,7 +4,7 @@ import { type ApiResult } from '$lib/api/client';
export type FileEntry = {
name: string;
path: string;
type: 'file' | 'directory' | 'symlink';
type: 'file' | 'directory' | 'symlink' | 'unknown';
size: number;
mode: number;
permissions: string;
@ -53,12 +53,12 @@ export function formatFileSize(bytes: number): string {
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 {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
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',
headers,
body: JSON.stringify({ path, depth }),
@ -76,12 +76,13 @@ export async function readFile(
capsuleId: string,
path: string,
signal?: AbortSignal,
basePath = '/api/v1/capsules',
): Promise<ApiResult<string>> {
try {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
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',
headers,
body: JSON.stringify({ path }),
@ -113,11 +114,12 @@ export async function downloadFile(
path: string,
filename: string,
signal?: AbortSignal,
basePath = '/api/v1/capsules',
): Promise<void> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
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',
headers,
body: JSON.stringify({ path }),

View File

@ -15,8 +15,8 @@ export type MetricsResponse = {
points: MetricPoint[];
};
export async function fetchCapsuleMetrics(id: string, range: MetricRange): Promise<ApiResult<MetricsResponse>> {
return apiFetch('GET', `/api/v1/capsules/${id}/metrics?range=${range}`);
export async function fetchCapsuleMetrics(id: string, range: MetricRange, basePath = '/api/v1/capsules'): Promise<ApiResult<MetricsResponse>> {
return apiFetch('GET', `${basePath}/${id}/metrics?range=${range}`);
}
export const METRIC_RANGES: MetricRange[] = ['5m', '10m', '1h', '6h', '24h'];

View File

@ -3,7 +3,8 @@
import { auth } from '$lib/auth.svelte';
import {
IconServer,
IconTemplate,
IconBox,
IconMonitor,
IconSettings,
IconLogout,
IconSidebar,
@ -22,7 +23,8 @@
};
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' }
];

View File

@ -1,12 +1,15 @@
<script lang="ts">
import { createCapsule, listSnapshots, type Capsule, type CreateCapsuleParams, type Snapshot } from '$lib/api/capsules';
import { createAdminCapsule, listPlatformTemplates } from '$lib/api/admin-capsules';
type Props = {
open: boolean;
onclose: () => 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 creating = $state(false);
@ -37,7 +40,8 @@
$effect(() => {
if (open && templates.length === 0 && !templatesLoading) {
templatesLoading = true;
listSnapshots().then((result) => {
const fetcher = templateSource === 'platform' ? listPlatformTemplates : listSnapshots;
fetcher().then((result) => {
if (result.ok) templates = result.data;
templatesLoading = false;
});
@ -112,7 +116,8 @@
async function handleCreate() {
creating = true;
createError = null;
const result = await createCapsule(createForm);
const creator = templateSource === 'platform' ? createAdminCapsule : createCapsule;
const result = await creator(createForm);
if (result.ok) {
createForm = { template: 'minimal', vcpus: 1, memory_mb: 512, timeout_sec: 0 };
templateQuery = 'minimal';

View File

@ -14,9 +14,14 @@
type Props = {
capsuleId: string;
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
let currentPath = $state('~');
@ -95,6 +100,9 @@
// may point to devices, sockets, or directories that can't be read as a 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) {
// Abort any in-flight file read and invalidate stale generation so the
// abort error isn't surfaced in the UI.
@ -141,7 +149,7 @@
dirLoading = true;
dirError = null;
const gen = ++dirGeneration;
const result = await listDir(capsuleId, currentPath);
const result = await listDir(capsuleId, currentPath, 1, apiBasePath);
if (gen !== dirGeneration) return; // stale response
if (result.ok) {
entries = result.data.entries ?? [];
@ -171,6 +179,11 @@
fileError = 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
if (isBinaryFile(entry.name) || isFileTooLarge(entry.size)) {
// Don't load content — the preview pane will show download prompt
@ -182,7 +195,7 @@
const controller = new AbortController();
fileAbort = controller;
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 (result.ok) {
if (looksLikeBinary(result.data)) {
@ -222,7 +235,7 @@
if (!selectedFile || downloading || selectedFile.type !== 'file') return;
downloading = true;
try {
await downloadFile(capsuleId, selectedFile.path, selectedFile.name);
await downloadFile(capsuleId, selectedFile.path, selectedFile.name, undefined, apiBasePath);
} catch {
fileError = 'Download failed';
}
@ -239,7 +252,7 @@
async function navigateOrOpenFile(path: string) {
// First try as directory
const dirResult = await listDir(capsuleId, path);
const dirResult = await listDir(capsuleId, path, 1, apiBasePath);
if (dirResult.ok) {
// Resolve actual path from entries (handles ~ expansion by envd)
const resolvedEntries = dirResult.data.entries ?? [];
@ -270,7 +283,7 @@
// Navigate to parent directory
currentPath = parentPath;
pathInput = parentPath;
const parentResult = await listDir(capsuleId, parentPath);
const parentResult = await listDir(capsuleId, parentPath, 1, apiBasePath);
if (parentResult.ok) {
entries = parentResult.data.entries ?? [];
// Find the file in parent listing
@ -295,6 +308,7 @@
function fileIcon(entry: FileEntry): string {
if (entry.type === 'directory') return 'dir';
if (entry.type === 'symlink') return 'link';
if (entry.type === 'unknown') return 'special';
return 'file';
}
@ -448,7 +462,8 @@
<div class="flex flex-1 min-h-0">
<!-- 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' : 'w-[380px] border-r border-[var(--color-border)]'}"
>
<!-- Path input -->
<form onsubmit={handlePathSubmit} class="border-b border-[var(--color-border)] px-4 py-3">
@ -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="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
</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}
<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" />
@ -636,6 +656,7 @@
</div>
<!-- Right panel: File preview -->
{#if !treeOnly && (!compact || selectedFile)}
<div class="flex flex-1 flex-col min-w-0 bg-[var(--color-bg-1)]">
{#if !selectedFile}
<!-- Empty state -->
@ -720,8 +741,30 @@
<span class="text-meta text-[var(--color-red)]">{fileError}</span>
</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)]">Special 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)]">
Special files can't be previewed or downloaded.
</span>
</div>
</div>
</div>
{: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-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)]">
@ -807,6 +850,7 @@
</div>
{/if}
</div>
{/if}
</div>
{/if}

View File

@ -6,9 +6,10 @@
capsuleId: string;
isRunning: 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';
@ -93,7 +94,7 @@
function getWsUrl(): string {
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
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) {