Skip to content

Modern Docker Management, Designed for Everyone

feat: remote agents (#239)

Kyle Mendell82cbab506083
diff --git a/app-settings.json b/app-settings.json
deleted file mode 100644
index 57e931163..000000000
--- a/app-settings.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "dockerHost": "unix:///var/run/docker.sock",
- "autoRefresh": true,
- "pollingInterval": 5,
- "stacksDirectory": "/app/data/stacks"
-}
diff --git a/package-lock.json b/package-lock.json
index 12fe1fdd8..5fb014a0e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "arcane",
- "version": "0.13.1",
+ "version": "0.14.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "arcane",
- "version": "0.13.1",
+ "version": "0.14.0",
"dependencies": {
"@codemirror/lang-yaml": "^6.1.2",
"@codemirror/legacy-modes": "^6.5.1",
@@ -16,6 +16,7 @@
"axios": "^1.9.0",
"bcryptjs": "^3.0.2",
"codemirror": "^6.0.1",
+ "date-fns": "^4.1.0",
"dockerode": "^4.0.6",
"dockerode-compose": "^1.4.0",
"js-yaml": "^4.1.0",
@@ -3205,6 +3206,16 @@
"node": ">=4"
}
},
+ "node_modules/date-fns": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz",
+ "integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/kossnocorp"
+ }
+ },
"node_modules/dayjs": {
"version": "1.11.13",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz",
diff --git a/package.json b/package.json
index ef28b28f9..5ceb8e3a0 100644
--- a/package.json
+++ b/package.json
@@ -1,81 +1,82 @@
{
- "name": "arcane",
- "private": true,
- "version": "0.14.0",
- "type": "module",
- "scripts": {
- "dev": "vite dev --port 3000",
- "build": "vite build",
- "preview": "vite preview --port 3000",
- "prepare": "svelte-kit sync || echo ''",
- "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
- "format": "prettier --write ./src",
- "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
- "lint": "eslint ./src",
- "lint:fix": "eslint ./src --fix",
- "test:init": "APP_ENV=TEST npx tsx scripts/init-test-env.ts",
- "test:setup": "npx tsx scripts/setup-test-images.ts",
- "test:e2e": "APP_ENV=TEST npm run test:init && npm run test:setup && playwright test",
- "test:e2e:ui": "playwright test --ui",
- "test:e2e:report": "playwright show-report"
- },
- "devDependencies": {
- "@eslint/compat": "^1.2.5",
- "@eslint/js": "^9.18.0",
- "@internationalized/date": "^3.8.1",
- "@lucide/svelte": "^0.511.0",
- "@playwright/test": "^1.52.0",
- "@sveltejs/adapter-node": "^5.2.12",
- "@sveltejs/kit": "^2.20.8",
- "@sveltejs/vite-plugin-svelte": "^5.0.0",
- "@tailwindcss/vite": "^4.1.7",
- "@types/bcryptjs": "^3.0.0",
- "@types/dockerode": "^3.3.38",
- "@types/dockerode-compose": "^1.4.1",
- "@types/js-yaml": "^4.0.9",
- "@types/proper-lockfile": "^4.1.4",
- "bits-ui": "^2.2.0",
- "clsx": "^2.1.1",
- "eslint": "^9.27.0",
- "eslint-plugin-svelte": "^3.8.1",
- "formsnap": "^2.0.1",
- "globals": "^16.2.0",
- "mode-watcher": "^1.0.7",
- "paneforge": "^1.0.0-next.5",
- "svelte": "5.33.4",
- "svelte-check": "^4.2.1",
- "svelte-sonner": "^1.0.3",
- "sveltekit-superforms": "^2.25.0",
- "tailwind-merge": "^3.3.0",
- "tailwind-variants": "^1.0.0",
- "tailwindcss": "^4.1.7",
- "tw-animate-css": "^1.3.0",
- "typescript": "^5.8.0",
- "typescript-eslint": "^8.33.0",
- "vite": "^6.3.5",
- "zod": "^3.25.32"
- },
- "dependencies": {
- "@codemirror/lang-yaml": "^6.1.2",
- "@codemirror/legacy-modes": "^6.5.1",
- "@swimlane/docker-reference": "^2.0.1",
- "@tanstack/table-core": "^8.21.3",
- "arctic": "^3.7.0",
- "axios": "^1.9.0",
- "bcryptjs": "^3.0.2",
- "codemirror": "^6.0.1",
- "dockerode": "^4.0.6",
- "dockerode-compose": "^1.4.0",
- "js-yaml": "^4.1.0",
- "nanoid": "^5.1.5",
- "prettier": "^3.5.3",
- "prettier-plugin-svelte": "^3.4.0",
- "proper-lockfile": "^4.1.2",
- "runed": "^0.28.0",
- "slugify": "^1.6.6",
- "svelte-codemirror-editor": "^1.4.1",
- "svelte-kit-cookie-session": "^4.1.1",
- "thememirror": "^2.0.1",
- "yaml-env-defaults": "^2.0.5"
- }
+ "name": "arcane",
+ "private": true,
+ "version": "0.14.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite dev --port 3000",
+ "build": "vite build",
+ "preview": "vite preview --port 3000",
+ "prepare": "svelte-kit sync || echo ''",
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
+ "format": "prettier --write ./src",
+ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
+ "lint": "eslint ./src",
+ "lint:fix": "eslint ./src --fix",
+ "test:init": "APP_ENV=TEST npx tsx scripts/init-test-env.ts",
+ "test:setup": "npx tsx scripts/setup-test-images.ts",
+ "test:e2e": "APP_ENV=TEST npm run test:init && npm run test:setup && playwright test",
+ "test:e2e:ui": "playwright test --ui",
+ "test:e2e:report": "playwright show-report"
+ },
+ "devDependencies": {
+ "@eslint/compat": "^1.2.5",
+ "@eslint/js": "^9.18.0",
+ "@internationalized/date": "^3.8.1",
+ "@lucide/svelte": "^0.511.0",
+ "@playwright/test": "^1.52.0",
+ "@sveltejs/adapter-node": "^5.2.12",
+ "@sveltejs/kit": "^2.20.8",
+ "@sveltejs/vite-plugin-svelte": "^5.0.0",
+ "@tailwindcss/vite": "^4.1.7",
+ "@types/bcryptjs": "^3.0.0",
+ "@types/dockerode": "^3.3.38",
+ "@types/dockerode-compose": "^1.4.1",
+ "@types/js-yaml": "^4.0.9",
+ "@types/proper-lockfile": "^4.1.4",
+ "bits-ui": "^2.2.0",
+ "clsx": "^2.1.1",
+ "eslint": "^9.27.0",
+ "eslint-plugin-svelte": "^3.8.1",
+ "formsnap": "^2.0.1",
+ "globals": "^16.2.0",
+ "mode-watcher": "^1.0.7",
+ "paneforge": "^1.0.0-next.5",
+ "svelte": "5.33.4",
+ "svelte-check": "^4.2.1",
+ "svelte-sonner": "^1.0.3",
+ "sveltekit-superforms": "^2.25.0",
+ "tailwind-merge": "^3.3.0",
+ "tailwind-variants": "^1.0.0",
+ "tailwindcss": "^4.1.7",
+ "tw-animate-css": "^1.3.0",
+ "typescript": "^5.8.0",
+ "typescript-eslint": "^8.33.0",
+ "vite": "^6.3.5",
+ "zod": "^3.25.32"
+ },
+ "dependencies": {
+ "@codemirror/lang-yaml": "^6.1.2",
+ "@codemirror/legacy-modes": "^6.5.1",
+ "@swimlane/docker-reference": "^2.0.1",
+ "@tanstack/table-core": "^8.21.3",
+ "arctic": "^3.7.0",
+ "axios": "^1.9.0",
+ "bcryptjs": "^3.0.2",
+ "codemirror": "^6.0.1",
+ "date-fns": "^4.1.0",
+ "dockerode": "^4.0.6",
+ "dockerode-compose": "^1.4.0",
+ "js-yaml": "^4.1.0",
+ "nanoid": "^5.1.5",
+ "prettier": "^3.5.3",
+ "prettier-plugin-svelte": "^3.4.0",
+ "proper-lockfile": "^4.1.2",
+ "runed": "^0.28.0",
+ "slugify": "^1.6.6",
+ "svelte-codemirror-editor": "^1.4.1",
+ "svelte-kit-cookie-session": "^4.1.1",
+ "thememirror": "^2.0.1",
+ "yaml-env-defaults": "^2.0.5"
+ }
}
diff --git a/src/hooks.server.ts b/src/hooks.server.ts
index 34f9d51e2..2c98c6620 100644
--- a/src/hooks.server.ts
+++ b/src/hooks.server.ts
@@ -1,11 +1,12 @@
-import { redirect, type Handle } from '@sveltejs/kit';
import { sequence } from '@sveltejs/kit/hooks';
-import { initComposeService } from '$lib/services/docker/stack-service';
-import { initAutoUpdateScheduler } from '$lib/services/docker/scheduler-service';
+import type { Handle } from '@sveltejs/kit';
+import { redirect } from '@sveltejs/kit';
import { getUserByUsername } from '$lib/services/user-service';
import { getSettings } from '$lib/services/settings-service';
import { checkFirstRun } from '$lib/utils/onboarding.utils';
import { sessionHandler } from '$lib/services/session-handler';
+import { initComposeService } from '$lib/services/docker/stack-service';
+import { initAutoUpdateScheduler } from '$lib/services/docker/scheduler-service';
import { initMaturityPollingScheduler } from '$lib/services/docker/image-service';
// Get environment variable
@@ -19,25 +20,31 @@ try {
process.exit(1);
}
-// Protected paths that require specific permissions
-// const protectedPathPermissions: Record<string, string[]> = {
-// '/containers': ['containers:view'],
-// '/containers/create': ['containers:manage'],
-// '/settings': ['settings:view']
-// // Add other path patterns as needed
-// };
-
// Authentication and authorization handler
const authHandler: Handle = async ({ event, resolve }) => {
const { url } = event;
const path = url.pathname;
// Define paths that don't require authentication
- const publicPaths = ['/auth/login', '/img', '/auth/oidc/login', '/auth/oidc/callback'];
+ const publicPaths = [
+ '/auth/login',
+ '/img',
+ '/auth/oidc/login',
+ '/auth/oidc/callback',
+ '/api/agents/register', // Agent registration
+ '/api/agents/heartbeat' // Agent heartbeat
+ ];
+
+ // Check for specific agent polling patterns that should be public
+ const agentPollingPattern = /^\/api\/agents\/[^\/]+\/tasks$/; // GET /api/agents/{agentId}/tasks
+ const agentResultPattern = /^\/api\/agents\/[^\/]+\/tasks\/[^\/]+\/result$/; // POST /api/agents/{agentId}/tasks/{taskId}/result
+
const isPublicPath = publicPaths.some((p) => path.startsWith(p));
+ const isAgentPolling = agentPollingPattern.test(path) && event.request.method === 'GET';
+ const isAgentResult = agentResultPattern.test(path) && event.request.method === 'POST';
- // Always allow access to public paths
- if (isPublicPath) {
+ // Allow access to public paths and specific agent endpoints
+ if (isPublicPath || isAgentPolling || isAgentResult) {
return await resolve(event);
}
@@ -94,22 +101,7 @@ const authHandler: Handle = async ({ event, resolve }) => {
}
}
- // Continue with permission checks as before
- // if (settings?.auth?.rbacEnabled) {
- // // Check each protected path pattern
- // for (const [pathPattern, requiredPermissions] of Object.entries(protectedPathPermissions)) {
- // if (path.startsWith(pathPattern)) {
- // const hasPermission = requiredPermissions.some((perm) => user.roles.includes(perm));
- // if (!hasPermission) {
- // throw redirect(302, '/auth/unauthorized');
- // }
- // }
- // }
- // }
-
- // Proceed to resolve the route with the authenticated user
return await resolve(event);
};
-// Combine handlers using sequence
export const handle = sequence(sessionHandler, authHandler);
diff --git a/src/lib/components/forms/ImagePullForm.svelte b/src/lib/components/forms/ImagePullForm.svelte
new file mode 100644
index 000000000..a223fc8bb
--- /dev/null
+++ b/src/lib/components/forms/ImagePullForm.svelte
@@ -0,0 +1,71 @@
+<script lang="ts">
+ import { Button } from '$lib/components/ui/button';
+ import { Label } from '$lib/components/ui/label';
+ import { Input } from '$lib/components/ui/input';
+ import { toast } from 'svelte-sonner';
+ import { Loader2 } from '@lucide/svelte';
+
+ interface Props {
+ agentId: string;
+ onClose: () => void;
+ onPull: (imageName: string) => Promise<void>;
+ }
+
+ let { agentId, onClose, onPull }: Props = $props();
+
+ let pulling = $state(false);
+ let imageRef = $state('');
+ let tag = $state('latest');
+
+ async function handlePull() {
+ if (!imageRef.trim()) {
+ toast.error('Please enter an image name');
+ return;
+ }
+
+ pulling = true;
+ try {
+ // Combine image name and tag
+ const fullImageName = tag && tag !== 'latest' ? `${imageRef.trim()}:${tag.trim()}` : imageRef.trim().includes(':') ? imageRef.trim() : `${imageRef.trim()}:latest`;
+
+ await onPull(fullImageName);
+ onClose();
+ toast.success(`Started pulling image: ${fullImageName}`);
+ } catch (err) {
+ console.error('Pull error:', err);
+ toast.error(err instanceof Error ? err.message : 'Failed to pull image');
+ } finally {
+ pulling = false;
+ }
+ }
+
+ function handleKeyPress(event: KeyboardEvent) {
+ if (event.key === 'Enter' && !pulling) {
+ handlePull();
+ }
+ }
+</script>
+
+<div class="space-y-4">
+ <div class="space-y-2">
+ <Label for="imageRef">Image Name</Label>
+ <Input id="imageRef" bind:value={imageRef} placeholder="nginx, redis, ubuntu, etc." disabled={pulling} onkeypress={handleKeyPress} />
+ <p class="text-xs text-muted-foreground">Enter the image name (e.g., nginx, redis, ubuntu)</p>
+ </div>
+
+ <div class="space-y-2">
+ <Label for="tag">Tag (Optional)</Label>
+ <Input id="tag" bind:value={tag} placeholder="latest" disabled={pulling} onkeypress={handleKeyPress} />
+ <p class="text-xs text-muted-foreground">Specify a tag version (defaults to 'latest')</p>
+ </div>
+
+ <div class="flex justify-end space-x-2">
+ <Button variant="outline" onclick={onClose} disabled={pulling}>Cancel</Button>
+ <Button onclick={handlePull} disabled={pulling || !imageRef.trim()}>
+ {#if pulling}
+ <Loader2 class="size-4 mr-2 animate-spin" />
+ {/if}
+ Pull Image
+ </Button>
+ </div>
+</div>
diff --git a/src/lib/components/forms/QuickContainerForm.svelte b/src/lib/components/forms/QuickContainerForm.svelte
new file mode 100644
index 000000000..0009f2f50
--- /dev/null
+++ b/src/lib/components/forms/QuickContainerForm.svelte
@@ -0,0 +1,199 @@
+<script lang="ts">
+ import { Button } from '$lib/components/ui/button';
+ import { Label } from '$lib/components/ui/label';
+ import { Input } from '$lib/components/ui/input';
+ import { Textarea } from '$lib/components/ui/textarea';
+ import { Switch } from '$lib/components/ui/switch/index.js';
+ import { toast } from 'svelte-sonner';
+ import { Loader2, Plus, Trash2 } from '@lucide/svelte';
+
+ interface Props {
+ agentId: string;
+ onClose: () => void;
+ onRun: (data: any) => Promise<void>;
+ }
+
+ let { agentId, onClose, onRun }: Props = $props();
+
+ let running = $state(false);
+ let containerName = $state('');
+ let imageName = $state('');
+ let ports = $state<{ host: string; container: string }[]>([]);
+ let volumes = $state<{ host: string; container: string }[]>([]);
+ let envVars = $state<{ key: string; value: string }[]>([]);
+ let detached = $state(true);
+ let autoRemove = $state(false);
+ let restartPolicy = $state('no');
+
+ function addPort() {
+ ports = [...ports, { host: '', container: '' }];
+ }
+
+ function removePort(index: number) {
+ ports = ports.filter((_, i) => i !== index);
+ }
+
+ function addVolume() {
+ volumes = [...volumes, { host: '', container: '' }];
+ }
+
+ function removeVolume(index: number) {
+ volumes = volumes.filter((_, i) => i !== index);
+ }
+
+ function addEnvVar() {
+ envVars = [...envVars, { key: '', value: '' }];
+ }
+
+ function removeEnvVar(index: number) {
+ envVars = envVars.filter((_, i) => i !== index);
+ }
+
+ async function handleRun() {
+ if (!imageName.trim()) {
+ toast.error('Please enter an image name');
+ return;
+ }
+
+ running = true;
+ try {
+ const data = {
+ imageName: imageName.trim(),
+ containerName: containerName.trim() || undefined,
+ ports: ports.filter((p) => p.host && p.container),
+ volumes: volumes.filter((v) => v.host && v.container),
+ envVars: envVars.filter((e) => e.key && e.value),
+ detached,
+ autoRemove,
+ restartPolicy
+ };
+
+ await onRun(data);
+ onClose();
+ toast.success(`Started container from ${imageName}`);
+ } catch (err) {
+ console.error('Run error:', err);
+ toast.error(err instanceof Error ? err.message : 'Failed to run container');
+ } finally {
+ running = false;
+ }
+ }
+</script>
+
+<div class="space-y-6">
+ <!-- Basic Configuration -->
+ <div class="space-y-4">
+ <div class="space-y-2">
+ <Label for="imageName">Image Name *</Label>
+ <Input id="imageName" bind:value={imageName} placeholder="nginx:alpine" disabled={running} />
+ </div>
+
+ <div class="space-y-2">
+ <Label for="containerName">Container Name (Optional)</Label>
+ <Input id="containerName" bind:value={containerName} placeholder="my-container" disabled={running} />
+ </div>
+ </div>
+
+ <!-- Port Mappings -->
+ <div class="space-y-3">
+ <div class="flex items-center justify-between">
+ <Label>Port Mappings</Label>
+ <Button variant="outline" size="sm" onclick={addPort} disabled={running}>
+ <Plus class="size-4 mr-1" />
+ Add Port
+ </Button>
+ </div>
+ {#each ports as port, index}
+ <div class="flex items-center gap-2">
+ <Input bind:value={port.host} placeholder="8080" disabled={running} class="flex-1" />
+ <span class="text-muted-foreground">:</span>
+ <Input bind:value={port.container} placeholder="80" disabled={running} class="flex-1" />
+ <Button variant="outline" size="sm" onclick={() => removePort(index)} disabled={running}>
+ <Trash2 class="size-4" />
+ </Button>
+ </div>
+ {/each}
+ </div>
+
+ <!-- Volume Mounts -->
+ <div class="space-y-3">
+ <div class="flex items-center justify-between">
+ <Label>Volume Mounts</Label>
+ <Button variant="outline" size="sm" onclick={addVolume} disabled={running}>
+ <Plus class="size-4 mr-1" />
+ Add Volume
+ </Button>
+ </div>
+ {#each volumes as volume, index}
+ <div class="flex items-center gap-2">
+ <Input bind:value={volume.host} placeholder="/host/path" disabled={running} class="flex-1" />
+ <span class="text-muted-foreground">:</span>
+ <Input bind:value={volume.container} placeholder="/container/path" disabled={running} class="flex-1" />
+ <Button variant="outline" size="sm" onclick={() => removeVolume(index)} disabled={running}>
+ <Trash2 class="size-4" />
+ </Button>
+ </div>
+ {/each}
+ </div>
+
+ <!-- Environment Variables -->
+ <div class="space-y-3">
+ <div class="flex items-center justify-between">
+ <Label>Environment Variables</Label>
+ <Button variant="outline" size="sm" onclick={addEnvVar} disabled={running}>
+ <Plus class="size-4 mr-1" />
+ Add Variable
+ </Button>
+ </div>
+ {#each envVars as envVar, index}
+ <div class="flex items-center gap-2">
+ <Input bind:value={envVar.key} placeholder="VARIABLE_NAME" disabled={running} class="flex-1" />
+ <span class="text-muted-foreground">=</span>
+ <Input bind:value={envVar.value} placeholder="value" disabled={running} class="flex-1" />
+ <Button variant="outline" size="sm" onclick={() => removeEnvVar(index)} disabled={running}>
+ <Trash2 class="size-4" />
+ </Button>
+ </div>
+ {/each}
+ </div>
+
+ <!-- Container Options -->
+ <div class="space-y-4">
+ <div class="flex items-center justify-between">
+ <div>
+ <Label>Run in Background</Label>
+ <p class="text-sm text-muted-foreground">Run container in detached mode</p>
+ </div>
+ <Switch bind:checked={detached} disabled={running} />
+ </div>
+
+ <div class="flex items-center justify-between">
+ <div>
+ <Label>Auto Remove</Label>
+ <p class="text-sm text-muted-foreground">Remove container when it stops</p>
+ </div>
+ <Switch bind:checked={autoRemove} disabled={running} />
+ </div>
+
+ <div class="space-y-2">
+ <Label for="restartPolicy">Restart Policy</Label>
+ <select id="restartPolicy" bind:value={restartPolicy} disabled={running} class="w-full px-3 py-2 border border-input bg-background rounded-md">
+ <option value="no">No</option>
+ <option value="always">Always</option>
+ <option value="unless-stopped">Unless Stopped</option>
+ <option value="on-failure">On Failure</option>
+ </select>
+ </div>
+ </div>
+
+ <!-- Actions -->
+ <div class="flex justify-end space-x-2">
+ <Button variant="outline" onclick={onClose} disabled={running}>Cancel</Button>
+ <Button onclick={handleRun} disabled={running || !imageName.trim()}>
+ {#if running}
+ <Loader2 class="size-4 mr-2 animate-spin" />
+ {/if}
+ Run Container
+ </Button>
+ </div>
+</div>
diff --git a/src/lib/components/forms/StackDeploymentForm.svelte b/src/lib/components/forms/StackDeploymentForm.svelte
new file mode 100644
index 000000000..d9a1c14b9
--- /dev/null
+++ b/src/lib/components/forms/StackDeploymentForm.svelte
@@ -0,0 +1,184 @@
+<script lang="ts">
+ import { Button } from '$lib/components/ui/button';
+ import { Label } from '$lib/components/ui/label';
+ import { Textarea } from '$lib/components/ui/textarea';
+ import { Input } from '$lib/components/ui/input';
+ import * as Select from '$lib/components/ui/select';
+ import { toast } from 'svelte-sonner';
+ import { Loader2, Upload, FileText } from '@lucide/svelte';
+
+ interface Props {
+ agentId: string;
+ onClose: () => void;
+ onDeploy: (data: any) => Promise<void>;
+ }
+
+ let { agentId, onClose, onDeploy }: Props = $props();
+
+ let deploying = $state(false);
+ let deploymentMode = $state('compose'); // 'compose' | 'existing' | 'template'
+ let stackName = $state('');
+ let composeContent = $state('');
+ let envContent = $state('');
+ let selectedStack = $state('');
+
+ // Pre-made templates for easy deployment
+ const templates = [
+ {
+ id: 'nginx',
+ name: 'Nginx Web Server',
+ description: 'Simple Nginx web server',
+ compose: `version: '3.8'
+services:
+ nginx:
+ image: nginx:alpine
+ ports:
+ - "80:80"
+ volumes:
+ - ./html:/usr/share/nginx/html:ro
+ restart: unless-stopped`
+ },
+ {
+ id: 'redis',
+ name: 'Redis Cache',
+ description: 'Redis in-memory database',
+ compose: `version: '3.8'
+services:
+ redis:
+ image: redis:alpine
+ ports:
+ - "6379:6379"
+ volumes:
+ - redis_data:/data
+ restart: unless-stopped
+ command: redis-server --appendonly yes
+
+volumes:
+ redis_data:`
+ },
+ {
+ id: 'postgres',
+ name: 'PostgreSQL Database',
+ description: 'PostgreSQL database server',
+ compose: `version: '3.8'
+services:
+ postgres:
+ image: postgres:15-alpine
+ environment:
+ POSTGRES_DB: myapp
+ POSTGRES_USER: admin
+ POSTGRES_PASSWORD: changeme
+ ports:
+ - "5432:5432"
+ volumes:
+ - postgres_data:/var/lib/postgresql/data
+ restart: unless-stopped
+
+volumes:
+ postgres_data:`
+ }
+ ];
+
+ function useTemplate(template: any) {
+ stackName = template.name.toLowerCase().replace(/\s+/g, '-');
+ composeContent = template.compose;
+ deploymentMode = 'compose';
+ }
+
+ async function handleDeploy() {
+ if (!stackName.trim()) {
+ toast.error('Please enter a stack name');
+ return;
+ }
+
+ if (deploymentMode === 'compose' && !composeContent.trim()) {
+ toast.error('Please enter compose content');
+ return;
+ }
+
+ deploying = true;
+ try {
+ await onDeploy({
+ mode: deploymentMode,
+ stackName: stackName.trim(),
+ composeContent: composeContent.trim(),
+ envContent: envContent.trim(),
+ selectedStack
+ });
+ onClose();
+ toast.success(`Stack "${stackName}" deployed successfully`);
+ } catch (err) {
+ console.error('Deploy error:', err);
+ toast.error(err instanceof Error ? err.message : 'Failed to deploy stack');
+ } finally {
+ deploying = false;
+ }
+ }
+</script>
+
+<div class="space-y-6">
+ <!-- Deployment Mode Selection -->
+ <div class="space-y-3">
+ <Label>How would you like to deploy?</Label>
+ <div class="grid grid-cols-3 gap-2">
+ <Button variant={deploymentMode === 'compose' ? 'default' : 'outline'} size="sm" onclick={() => (deploymentMode = 'compose')} class="flex flex-col h-auto p-3">
+ <FileText class="size-4 mb-1" />
+ <span class="text-xs">Write Compose</span>
+ </Button>
+ <Button variant={deploymentMode === 'template' ? 'default' : 'outline'} size="sm" onclick={() => (deploymentMode = 'template')} class="flex flex-col h-auto p-3">
+ <Upload class="size-4 mb-1" />
+ <span class="text-xs">Use Template</span>
+ </Button>
+ <Button variant={deploymentMode === 'existing' ? 'default' : 'outline'} size="sm" onclick={() => (deploymentMode = 'existing')} class="flex flex-col h-auto p-3" disabled>
+ <FileText class="size-4 mb-1" />
+ <span class="text-xs">Existing Stack</span>
+ </Button>
+ </div>
+ </div>
+
+ {#if deploymentMode === 'template'}
+ <!-- Template Selection -->
+ <div class="space-y-3">
+ <Label>Choose a template</Label>
+ <div class="grid gap-2">
+ {#each templates as template}
+ <button class="p-3 text-left border rounded-lg hover:border-primary/50 transition-colors" onclick={() => useTemplate(template)}>
+ <div class="font-medium text-sm">{template.name}</div>
+ <div class="text-xs text-muted-foreground">{template.description}</div>
+ </button>
+ {/each}
+ </div>
+ </div>
+ {/if}
+
+ <!-- Stack Name -->
+ <div class="space-y-2">
+ <Label for="stackName">Stack Name</Label>
+ <Input id="stackName" bind:value={stackName} placeholder="my-awesome-app" disabled={deploying} />
+ </div>
+
+ {#if deploymentMode === 'compose'}
+ <!-- Compose Content -->
+ <div class="space-y-2">
+ <Label for="compose">Docker Compose Content</Label>
+ <Textarea id="compose" bind:value={composeContent} placeholder="version: '3.8'&#10;services:&#10; web:&#10; image: nginx:alpine&#10; ports:&#10; - '80:80'" class="font-mono text-sm min-h-[200px]" disabled={deploying} />
+ </div>
+
+ <!-- Environment Variables (Optional) -->
+ <div class="space-y-2">
+ <Label for="env">Environment Variables (Optional)</Label>
+ <Textarea id="env" bind:value={envContent} placeholder="DATABASE_URL=postgres://user:pass@db:5432/myapp&#10;REDIS_URL=redis://redis:6379" class="font-mono text-sm min-h-[80px]" disabled={deploying} />
+ </div>
+ {/if}
+
+ <!-- Actions -->
+ <div class="flex justify-end space-x-2">
+ <Button variant="outline" onclick={onClose} disabled={deploying}>Cancel</Button>
+ <Button onclick={handleDeploy} disabled={deploying || !stackName.trim()}>
+ {#if deploying}
+ <Loader2 class="size-4 mr-2 animate-spin" />
+ {/if}
+ Deploy Stack
+ </Button>
+ </div>
+</div>
diff --git a/src/lib/components/sidebar.svelte b/src/lib/components/sidebar.svelte
index d86458773..c1dd8bad7 100644
--- a/src/lib/components/sidebar.svelte
+++ b/src/lib/components/sidebar.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { Home, Box, Image, Network, HardDrive, Settings, Menu, X, ChevronRight, ChevronLeft, FileStack, ExternalLink, LogOut, Sun, Moon, ChevronDown, UserIcon, Shield, Bell, Palette, Database, type Icon as IconType, ShieldCheck, LayoutTemplate } from '@lucide/svelte';
+ import { Home, Box, Image, Network, HardDrive, Settings, Menu, X, ChevronRight, Computer, ChevronLeft, FileStack, ExternalLink, LogOut, Sun, Moon, ChevronDown, UserIcon, Shield, Bell, Palette, Database, type Icon as IconType, ShieldCheck, LayoutTemplate } from '@lucide/svelte';
import { page } from '$app/state';
import { fly, slide } from 'svelte/transition';
import { Button } from '$lib/components/ui/button/index.js';
@@ -26,6 +26,7 @@
let {
items = [
{ href: '/', label: 'Dashboard', icon: Home },
+ { href: '/agents', label: 'Agents', icon: Computer },
{ href: '/containers', label: 'Containers', icon: Box },
{ href: '/stacks', label: 'Stacks', icon: FileStack },
{ href: '/images', label: 'Images', icon: Image },
diff --git a/src/lib/components/sidebar/sidebar-agent-switcher.svelte b/src/lib/components/sidebar/sidebar-agent-switcher.svelte
new file mode 100644
index 000000000..d60ff83ba
--- /dev/null
+++ b/src/lib/components/sidebar/sidebar-agent-switcher.svelte
@@ -0,0 +1,89 @@
+<script lang="ts">
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import * as Sidebar from '$lib/components/ui/sidebar/index.js';
+ import { useSidebar } from '$lib/components/ui/sidebar/index.js';
+ import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';
+ import PlusIcon from '@lucide/svelte/icons/plus';
+ import { GalleryVerticalEndIcon } from '@lucide/svelte';
+ import ServerIcon from '@lucide/svelte/icons/server';
+ import type { Agent } from '$lib/types/agent.type';
+
+ // Extend the Agent type to include isLocal for the local Docker option
+ type ExtendedAgent = Agent & { isLocal?: boolean };
+
+ let { agents, hasLocalDocker = false }: { agents: Agent[]; hasLocalDocker?: boolean } = $props();
+ const sidebar = useSidebar();
+
+ const localDockerAgent: ExtendedAgent = {
+ id: 'local',
+ hostname: 'Local Docker',
+ platform: 'local',
+ version: 'N/A',
+ capabilities: [],
+ status: 'online' as const,
+ lastSeen: new Date().toISOString(),
+ registeredAt: new Date().toISOString(),
+ createdAt: new Date().toISOString(),
+ isLocal: true
+ };
+
+ const allAgents: ExtendedAgent[] = $derived(hasLocalDocker ? [localDockerAgent, ...agents] : agents);
+ let activeAgent = $derived(allAgents[0]);
+</script>
+
+<Sidebar.Menu>
+ <Sidebar.MenuItem>
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Sidebar.MenuButton {...props} size="lg" class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground">
+ <div class="bg-sidebar-primary text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
+ {#if activeAgent?.isLocal}
+ <ServerIcon class="size-4" />
+ {:else}
+ <GalleryVerticalEndIcon class="size-4" />
+ {/if}
+ </div>
+ <div class="grid flex-1 text-left text-sm leading-tight">
+ <span class="truncate font-medium">
+ {activeAgent?.hostname}
+ </span>
+ <span class="truncate text-xs">
+ {activeAgent?.isLocal ? 'Local Socket' : activeAgent?.id}
+ </span>
+ </div>
+ <ChevronsUpDownIcon class="ml-auto" />
+ </Sidebar.MenuButton>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content class="w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg" align="start" side={sidebar.isMobile ? 'bottom' : 'right'} sideOffset={4}>
+ <DropdownMenu.Label class="text-muted-foreground text-xs">Docker Instances</DropdownMenu.Label>
+ {#each allAgents as agent, index (agent.id)}
+ <DropdownMenu.Item onSelect={() => (activeAgent = agent)} class="gap-2 p-2">
+ <div class="flex size-6 items-center justify-center rounded-md border">
+ {#if agent.isLocal}
+ <ServerIcon class="size-3.5 shrink-0" />
+ {:else}
+ <GalleryVerticalEndIcon class="size-3.5 shrink-0" />
+ {/if}
+ </div>
+ <div class="flex flex-col">
+ <span>{agent.hostname}</span>
+ {#if agent.isLocal}
+ <span class="text-xs text-muted-foreground">Local Socket</span>
+ {/if}
+ </div>
+ <DropdownMenu.Shortcut>⌘{index + 1}</DropdownMenu.Shortcut>
+ </DropdownMenu.Item>
+ {/each}
+ <DropdownMenu.Separator />
+ <DropdownMenu.Item class="gap-2 p-2">
+ <div class="flex size-6 items-center justify-center rounded-md border bg-transparent">
+ <PlusIcon class="size-4" />
+ </div>
+ <div class="text-muted-foreground font-medium">Add Agent</div>
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Sidebar.MenuItem>
+</Sidebar.Menu>
diff --git a/src/lib/components/sidebar/sidebar-itemgroup.svelte b/src/lib/components/sidebar/sidebar-itemgroup.svelte
new file mode 100644
index 000000000..e02b79251
--- /dev/null
+++ b/src/lib/components/sidebar/sidebar-itemgroup.svelte
@@ -0,0 +1,113 @@
+<script lang="ts">
+ import * as Collapsible from '$lib/components/ui/collapsible/index.js';
+ import * as Sidebar from '$lib/components/ui/sidebar/index.js';
+ import ChevronRightIcon from '@lucide/svelte/icons/chevron-right';
+ import type { Icon as IconType } from '@lucide/svelte';
+ import { page } from '$app/state';
+
+ let {
+ items,
+ label
+ }: {
+ label: string;
+ items: {
+ title: string;
+ url: string;
+ icon?: typeof IconType;
+ items?: {
+ title: string;
+ url: string;
+ icon?: typeof IconType;
+ }[];
+ }[];
+ } = $props();
+
+ // Helper function to check if a URL is active
+ function isActiveItem(url: string): boolean {
+ return page.url.pathname === url || (page.url.pathname.startsWith(url) && url !== '/');
+ }
+
+ // Helper function to check if any child items are active
+ function hasActiveChild(items?: { url: string }[]): boolean {
+ return items?.some((child) => isActiveItem(child.url)) ?? false;
+ }
+
+ // Transform items to include isActive state
+ const enhancedItems = $derived(
+ items.map((item) => {
+ const isItemActive = isActiveItem(item.url);
+ const hasActiveSubItem = hasActiveChild(item.items);
+ const isActive = isItemActive || hasActiveSubItem;
+
+ return {
+ ...item,
+ isActive,
+ items: item.items?.map((subItem) => ({
+ ...subItem,
+ isActive: isActiveItem(subItem.url)
+ }))
+ };
+ })
+ );
+</script>
+
+<Sidebar.Group>
+ <Sidebar.GroupLabel>{label}</Sidebar.GroupLabel>
+ <Sidebar.Menu>
+ {#each enhancedItems as item (item.title)}
+ {#if (item.items?.length ?? 0) > 0}
+ <Collapsible.Root open={item.isActive} class="group/collapsible">
+ {#snippet child({ props })}
+ <Sidebar.MenuItem {...props}>
+ <Collapsible.Trigger>
+ {#snippet child({ props })}
+ {@const Icon = item.icon}
+ <Sidebar.MenuButton {...props} tooltipContent={item.title} isActive={item.isActive}>
+ {#if item.icon}
+ <Icon />
+ {/if}
+ <span>{item.title}</span>
+ <ChevronRightIcon class="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
+ </Sidebar.MenuButton>
+ {/snippet}
+ </Collapsible.Trigger>
+ <Collapsible.Content>
+ <Sidebar.MenuSub>
+ {#each item.items ?? [] as subItem (subItem.title)}
+ <Sidebar.MenuSubItem>
+ <Sidebar.MenuSubButton isActive={subItem.isActive}>
+ {#snippet child({ props })}
+ {@const SubIcon = subItem.icon}
+ <a href={subItem.url} {...props}>
+ {#if subItem.icon}
+ <SubIcon />
+ {/if}
+ <span>{subItem.title}</span>
+ </a>
+ {/snippet}
+ </Sidebar.MenuSubButton>
+ </Sidebar.MenuSubItem>
+ {/each}
+ </Sidebar.MenuSub>
+ </Collapsible.Content>
+ </Sidebar.MenuItem>
+ {/snippet}
+ </Collapsible.Root>
+ {:else}
+ <Sidebar.MenuItem>
+ <Sidebar.MenuButton isActive={item.isActive} tooltipContent={item.title}>
+ {#snippet child({ props })}
+ {@const Icon = item.icon}
+ <a href={item.url} {...props}>
+ {#if item.icon}
+ <Icon />
+ {/if}
+ <span>{item.title}</span>
+ </a>
+ {/snippet}
+ </Sidebar.MenuButton>
+ </Sidebar.MenuItem>
+ {/if}
+ {/each}
+ </Sidebar.Menu>
+</Sidebar.Group>
diff --git a/src/lib/components/sidebar/sidebar-logo.svelte b/src/lib/components/sidebar/sidebar-logo.svelte
new file mode 100644
index 000000000..14923152a
--- /dev/null
+++ b/src/lib/components/sidebar/sidebar-logo.svelte
@@ -0,0 +1,23 @@
+<script lang="ts">
+ import type { AppVersionInformation } from '$lib/types/application-configuration';
+ import { cn } from '$lib/utils';
+
+ let { isCollapsed, versionInformation }: { isCollapsed: boolean; versionInformation: AppVersionInformation } = $props();
+</script>
+
+<div class={cn('flex items-center h-16 transition-all duration-300 border-b border-border/30', isCollapsed ? 'justify-center px-2' : 'gap-3 px-6')}>
+ <div class="shrink-0 flex items-center justify-center relative">
+ <div class={cn('rounded-full bg-gradient-to-br from-primary/20 to-primary/10 text-primary flex items-center justify-center font-semibold border border-primary/20 transition-all duration-300', isCollapsed ? 'size-8' : 'size-10')}>
+ <img src="/img/arcane.svg" alt="Arcane" class={cn('transition-all duration-300 drop-shadow-sm', isCollapsed ? 'size-5' : 'size-7')} width={isCollapsed ? '20' : '28'} height={isCollapsed ? '20' : '28'} />
+ </div>
+ <div class={cn('absolute inset-0 bg-primary/10 rounded-full blur-xl opacity-60 transition-all duration-300', isCollapsed ? 'scale-75' : 'scale-100')}></div>
+ </div>
+ {#if !isCollapsed}
+ <div class="flex flex-col justify-center min-w-0">
+ <span class="text-lg font-bold tracking-tight leading-none bg-gradient-to-r from-foreground to-foreground/80 bg-clip-text text-transparent">Arcane</span>
+ <span class="text-xs text-muted-foreground/80 font-medium">
+ v{versionInformation?.currentVersion}
+ </span>
+ </div>
+ {/if}
+</div>
diff --git a/src/lib/components/sidebar/sidebar-updatebanner.svelte b/src/lib/components/sidebar/sidebar-updatebanner.svelte
new file mode 100644
index 000000000..2214fa931
--- /dev/null
+++ b/src/lib/components/sidebar/sidebar-updatebanner.svelte
@@ -0,0 +1,55 @@
+<script lang="ts">
+ import { cn } from '$lib/utils';
+ import * as Separator from '$lib/components/ui/separator/index.js';
+ import * as Tooltip from '$lib/components/ui/tooltip/index.js';
+ import ExternalLink from '@lucide/svelte/icons/external-link';
+ import { useSidebar } from '$lib/components/ui/sidebar/index.js';
+ import type { AppVersionInformation } from '$lib/types/application-configuration';
+
+ let {
+ isCollapsed,
+ versionInformation,
+ updateAvailable = false
+ }: {
+ isCollapsed: boolean;
+ versionInformation?: AppVersionInformation;
+ updateAvailable?: boolean;
+ } = $props();
+
+ const sidebar = useSidebar();
+</script>
+
+{#if updateAvailable}
+ <div class={cn('pb-2', isCollapsed ? 'px-1' : 'px-4')}>
+ <Separator.Root class="mb-3 opacity-30" />
+
+ {#if !isCollapsed}
+ <div class="transition-all rounded-xl bg-gradient-to-br from-blue-500/10 to-blue-600/5 border border-blue-500/20 hover:shadow-md hover:scale-[1.02] hover:from-blue-500/15 hover:to-blue-600/10 p-3">
+ <a href={versionInformation?.releaseUrl} target="_blank" rel="noopener noreferrer" class="flex items-center justify-between text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 transition-colors duration-200 group">
+ <div class="flex flex-col gap-1">
+ <span class="text-sm font-semibold">Update available</span>
+ <span class="text-xs text-blue-500/80">v{versionInformation?.newestVersion}</span>
+ </div>
+ <ExternalLink size={16} class="transition-transform duration-200 group-hover:scale-110" />
+ </a>
+ </div>
+ {:else}
+ <div class="flex justify-center">
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ {#snippet child({ props })}
+ <div class="w-8 h-8 transition-all rounded-lg bg-gradient-to-br from-blue-500/10 to-blue-600/5 border border-blue-500/20 hover:shadow-md hover:scale-[1.02] hover:from-blue-500/15 hover:to-blue-600/10 flex items-center justify-center" {...props}>
+ <a href={versionInformation?.releaseUrl} target="_blank" rel="noopener noreferrer" class="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 transition-all duration-200 hover:scale-110 flex items-center justify-center w-full h-full">
+ <ExternalLink size={14} />
+ </a>
+ </div>
+ {/snippet}
+ </Tooltip.Trigger>
+ <Tooltip.Content side="right" align="center" hidden={sidebar.state !== 'collapsed' || sidebar.isMobile}>
+ Update available: v{versionInformation?.newestVersion}
+ </Tooltip.Content>
+ </Tooltip.Root>
+ </div>
+ {/if}
+ </div>
+{/if}
diff --git a/src/lib/components/sidebar/sidebar-user.svelte b/src/lib/components/sidebar/sidebar-user.svelte
new file mode 100644
index 000000000..93e871a7a
--- /dev/null
+++ b/src/lib/components/sidebar/sidebar-user.svelte
@@ -0,0 +1,121 @@
+<script lang="ts">
+ import * as Avatar from '$lib/components/ui/avatar/index.js';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import * as Sidebar from '$lib/components/ui/sidebar/index.js';
+ import * as Button from '$lib/components/ui/button/index.js';
+ import { useSidebar } from '$lib/components/ui/sidebar/index.js';
+ import type { User } from '$lib/types/user.type';
+ import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';
+ import LogOutIcon from '@lucide/svelte/icons/log-out';
+ import Sun from '@lucide/svelte/icons/sun';
+ import Moon from '@lucide/svelte/icons/moon';
+ import { mode, toggleMode } from 'mode-watcher';
+ import { cn } from '$lib/utils';
+
+ let { user, isCollapsed }: { user: User; isCollapsed: boolean } = $props();
+ const sidebar = useSidebar();
+
+ // Generate Gravatar URL using browser's crypto API
+ async function getGravatarUrl(email: string, size = 40): Promise<string> {
+ if (!email) return '';
+
+ const encoder = new TextEncoder();
+ const data = encoder.encode(email.toLowerCase().trim());
+ const hashBuffer = await crypto.subtle.digest('MD5', data);
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
+ const hash = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
+
+ return `https://www.gravatar.com/avatar/${hash}?s=${size}&d=mp&r=g`;
+ }
+
+ let gravatarUrl = $state('');
+ $effect(() => {
+ if (user?.email) {
+ getGravatarUrl(user.email).then((url) => {
+ gravatarUrl = url;
+ });
+ } else {
+ gravatarUrl = '';
+ }
+ });
+</script>
+
+<Sidebar.Menu>
+ <Sidebar.MenuItem>
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Sidebar.MenuButton size="lg" class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground" {...props}>
+ {#if user && user.displayName}
+ <Avatar.Root class="size-8 rounded-lg">
+ <Avatar.Image src={gravatarUrl} alt={user.displayName} />
+ <Avatar.Fallback class="rounded-lg bg-gradient-to-br from-primary/20 to-primary/10 text-primary border border-primary/20">
+ {user.displayName?.charAt(0).toUpperCase()}
+ </Avatar.Fallback>
+ </Avatar.Root>
+ {#if !isCollapsed}
+ <div class="grid flex-1 text-left text-sm leading-tight">
+ <span class="truncate font-medium">{user.displayName}</span>
+ <span class="truncate text-xs">{user.email}</span>
+ </div>
+ <ChevronsUpDownIcon class="ml-auto size-4" />
+ {/if}
+ {/if}
+ </Sidebar.MenuButton>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content class="w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg" side={sidebar.isMobile ? 'bottom' : 'right'} align="end" sideOffset={4}>
+ <DropdownMenu.Label class="p-0 font-normal">
+ <div class="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
+ <Avatar.Root class="size-8 rounded-lg">
+ <Avatar.Image src={gravatarUrl} alt={user.displayName} />
+ <Avatar.Fallback class="rounded-lg bg-gradient-to-br from-primary/20 to-primary/10 text-primary border border-primary/20">
+ {user.displayName?.charAt(0).toUpperCase()}
+ </Avatar.Fallback>
+ </Avatar.Root>
+ <div class="grid flex-1 text-left text-sm leading-tight">
+ <span class="truncate font-medium">{user.displayName}</span>
+ <span class="truncate text-xs">{user.email}</span>
+ </div>
+ </div>
+ </DropdownMenu.Label>
+ <DropdownMenu.Separator />
+ <DropdownMenu.Group>
+ <Button.Root
+ variant="ghost"
+ class={cn('w-full flex items-center text-sm font-medium transition-all duration-200 text-muted-foreground hover:bg-gradient-to-br hover:from-muted/80 hover:to-muted/60 hover:text-foreground rounded-xl mb-1', 'hover:shadow-md hover:scale-[1.02] active:scale-[0.98]', isCollapsed ? 'justify-center px-2 py-3 h-11' : 'justify-start gap-3 px-3 py-2.5 h-11')}
+ title={isCollapsed ? 'Toggle theme' : undefined}
+ onclick={toggleMode}
+ >
+ <div class="p-1 rounded-lg transition-colors duration-200 bg-transparent group-hover:bg-muted-foreground/10">
+ {#if mode.current === 'dark'}
+ <Sun size={16} class="transition-transform duration-200" />
+ {:else}
+ <Moon size={16} class="transition-transform duration-200" />
+ {/if}
+ </div>
+ {#if !isCollapsed}
+ <span class="font-medium">Toggle theme</span>
+ {/if}
+ </Button.Root>
+ </DropdownMenu.Group>
+ <DropdownMenu.Separator />
+ <form action="/auth/logout" method="POST">
+ <Button.Root
+ variant="ghost"
+ class={cn('w-full flex items-center text-sm font-medium transition-all duration-200 text-muted-foreground rounded-xl', 'hover:bg-gradient-to-br hover:from-destructive/10 hover:to-destructive/5 hover:text-destructive hover:shadow-md hover:scale-[1.02] active:scale-[0.98]', isCollapsed ? 'justify-center px-2 py-3 h-11' : 'justify-start gap-3 px-3 py-2.5 h-11')}
+ title={isCollapsed ? 'Logout' : undefined}
+ type="submit"
+ >
+ <div class="p-1 rounded-lg transition-colors duration-200 bg-transparent group-hover:bg-destructive/10">
+ <LogOutIcon size={16} class="transition-transform duration-200" />
+ </div>
+ {#if !isCollapsed}
+ <span class="font-medium">Logout</span>
+ {/if}
+ </Button.Root>
+ </form>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Sidebar.MenuItem>
+</Sidebar.Menu>
diff --git a/src/lib/components/sidebar/sidebar.svelte b/src/lib/components/sidebar/sidebar.svelte
new file mode 100644
index 000000000..d4c8a94da
--- /dev/null
+++ b/src/lib/components/sidebar/sidebar.svelte
@@ -0,0 +1,102 @@
+<script lang="ts" module>
+ import AudioWaveformIcon from '@lucide/svelte/icons/audio-waveform';
+ import GalleryVerticalEndIcon from '@lucide/svelte/icons/gallery-vertical-end';
+ import { Computer, FileStack, HardDrive, Home, Network, Container, ImageIcon, SettingsIcon, DatabaseIcon, LayoutTemplate, UserIcon, Shield, ComputerIcon, Paintbrush2Icon } from '@lucide/svelte';
+
+ const staticData = {
+ // agents: [
+ // {
+ // name: 'Local Docker Socket',
+ // logo: GalleryVerticalEndIcon,
+ // plan: 'unix:///var/run/docker.sock'
+ // },
+ // {
+ // name: 'Arcane-Agent',
+ // logo: AudioWaveformIcon,
+ // plan: 'agent-AGENTNAME-666666'
+ // }
+ // ],
+ settingsItems: [
+ {
+ title: 'Settings',
+ url: '/settings',
+ icon: SettingsIcon,
+ items: [
+ { title: 'General', url: '/settings/general', icon: SettingsIcon },
+ { title: 'Docker', url: '/settings/docker', icon: DatabaseIcon },
+ { title: 'Users', url: '/settings/users', icon: UserIcon },
+ { title: 'Security', url: '/settings/security', icon: Shield },
+ { title: 'Agents', url: '/agents', icon: ComputerIcon }
+ ]
+ }
+ ],
+ customizationItems: [
+ {
+ title: 'Templates',
+ url: '/settings/templates',
+ icon: LayoutTemplate
+ }
+ ],
+ managementItems: [
+ { title: 'Dashboard', url: '/', icon: Home },
+ { title: 'Agents', url: '/agents', icon: Computer },
+ { title: 'Containers', url: '/containers', icon: Container },
+ { title: 'Stacks', url: '/stacks', icon: FileStack },
+ { title: 'Images', url: '/images', icon: ImageIcon },
+ { title: 'Networks', url: '/networks', icon: Network },
+ { title: 'Volumes', url: '/volumes', icon: HardDrive }
+ ]
+ };
+</script>
+
+<script lang="ts">
+ import SidebarItemGroup from './sidebar-itemgroup.svelte';
+ import SidebarUser from './sidebar-user.svelte';
+ import SidebarAgentSwitcher from './sidebar-agent-switcher.svelte';
+ import * as Sidebar from '$lib/components/ui/sidebar/index.js';
+ import { useSidebar } from '$lib/components/ui/sidebar/index.js';
+ import type { ComponentProps } from 'svelte';
+ import type { User } from '$lib/types/user.type';
+ import type { AppVersionInformation } from '$lib/types/application-configuration';
+ import SidebarLogo from './sidebar-logo.svelte';
+ import SidebarUpdatebanner from './sidebar-updatebanner.svelte';
+ import type { Agent } from '$lib/types/agent.type';
+
+ let {
+ ref = $bindable(null),
+ collapsible = 'icon',
+ user,
+ versionInformation,
+ hasLocalDocker,
+ agents,
+ ...restProps
+ }: ComponentProps<typeof Sidebar.Root> & {
+ versionInformation: AppVersionInformation;
+ hasLocalDocker: boolean;
+ user?: User | null;
+ agents: Agent[];
+ } = $props();
+
+ const sidebar = useSidebar();
+
+ const isCollapsed = $derived(sidebar.state === 'collapsed');
+</script>
+
+<Sidebar.Root {collapsible} {...restProps}>
+ <Sidebar.Header>
+ <SidebarLogo {isCollapsed} {versionInformation} />
+ <SidebarAgentSwitcher {hasLocalDocker} {agents} />
+ </Sidebar.Header>
+ <Sidebar.Content>
+ <SidebarItemGroup label="Management" items={staticData.managementItems} />
+ <SidebarItemGroup label="Customization" items={staticData.customizationItems} />
+ <SidebarItemGroup label="Administration" items={staticData.settingsItems} />
+ </Sidebar.Content>
+ <Sidebar.Footer>
+ <SidebarUpdatebanner {isCollapsed} {versionInformation} updateAvailable={versionInformation.updateAvailable} />
+ {#if user}
+ <SidebarUser {isCollapsed} {user} />
+ {/if}
+ </Sidebar.Footer>
+ <Sidebar.Rail />
+</Sidebar.Root>
diff --git a/src/lib/components/ui/avatar/avatar-fallback.svelte b/src/lib/components/ui/avatar/avatar-fallback.svelte
new file mode 100644
index 000000000..249d4a4ab
--- /dev/null
+++ b/src/lib/components/ui/avatar/avatar-fallback.svelte
@@ -0,0 +1,17 @@
+<script lang="ts">
+ import { Avatar as AvatarPrimitive } from "bits-ui";
+ import { cn } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ ...restProps
+ }: AvatarPrimitive.FallbackProps = $props();
+</script>
+
+<AvatarPrimitive.Fallback
+ bind:ref
+ data-slot="avatar-fallback"
+ class={cn("bg-muted flex size-full items-center justify-center rounded-full", className)}
+ {...restProps}
+/>
diff --git a/src/lib/components/ui/avatar/avatar-image.svelte b/src/lib/components/ui/avatar/avatar-image.svelte
new file mode 100644
index 000000000..2bb9db4d8
--- /dev/null
+++ b/src/lib/components/ui/avatar/avatar-image.svelte
@@ -0,0 +1,17 @@
+<script lang="ts">
+ import { Avatar as AvatarPrimitive } from "bits-ui";
+ import { cn } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ ...restProps
+ }: AvatarPrimitive.ImageProps = $props();
+</script>
+
+<AvatarPrimitive.Image
+ bind:ref
+ data-slot="avatar-image"
+ class={cn("aspect-square size-full", className)}
+ {...restProps}
+/>
diff --git a/src/lib/components/ui/avatar/avatar.svelte b/src/lib/components/ui/avatar/avatar.svelte
new file mode 100644
index 000000000..f093a97bf
--- /dev/null
+++ b/src/lib/components/ui/avatar/avatar.svelte
@@ -0,0 +1,17 @@
+<script lang="ts">
+ import { Avatar as AvatarPrimitive } from "bits-ui";
+ import { cn } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ ...restProps
+ }: AvatarPrimitive.RootProps = $props();
+</script>
+
+<AvatarPrimitive.Root
+ bind:ref
+ data-slot="avatar"
+ class={cn("relative flex size-8 shrink-0 overflow-hidden rounded-full", className)}
+ {...restProps}
+/>
diff --git a/src/lib/components/ui/avatar/index.ts b/src/lib/components/ui/avatar/index.ts
new file mode 100644
index 000000000..d06457be0
--- /dev/null
+++ b/src/lib/components/ui/avatar/index.ts
@@ -0,0 +1,13 @@
+import Root from "./avatar.svelte";
+import Image from "./avatar-image.svelte";
+import Fallback from "./avatar-fallback.svelte";
+
+export {
+ Root,
+ Image,
+ Fallback,
+ //
+ Root as Avatar,
+ Image as AvatarImage,
+ Fallback as AvatarFallback,
+};
diff --git a/src/lib/components/ui/button/button.svelte b/src/lib/components/ui/button/button.svelte
index 85fb8261e..4daf4535c 100644
--- a/src/lib/components/ui/button/button.svelte
+++ b/src/lib/components/ui/button/button.svelte
@@ -1,34 +1,36 @@
<script lang="ts" module>
- import type { WithElementRef } from '$lib/utils.js';
- import type { HTMLAnchorAttributes, HTMLButtonAttributes } from 'svelte/elements';
- import { type VariantProps, tv } from 'tailwind-variants';
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAnchorAttributes, HTMLButtonAttributes } from "svelte/elements";
+ import { type VariantProps, tv } from "tailwind-variants";
export const buttonVariants = tv({
- base: 'ring-offset-background focus-visible:ring-ring inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
+ base: "focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive inline-flex shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium outline-none transition-all focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
variants: {
variant: {
- default: 'bg-primary text-primary-foreground hover:bg-primary/90',
- destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
- outline: 'border-input bg-background hover:bg-accent hover:text-accent-foreground border',
- secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
- ghost: 'hover:bg-accent hover:text-accent-foreground',
- link: 'text-primary underline-offset-4 hover:underline'
+ default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
+ destructive:
+ "bg-destructive shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60 text-white",
+ outline:
+ "bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50 border",
+ secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
+ ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
+ link: "text-primary underline-offset-4 hover:underline",
},
size: {
- default: 'h-10 px-4 py-2',
- sm: 'h-9 rounded-md px-3',
- lg: 'h-11 rounded-md px-8',
- icon: 'size-10'
- }
+ default: "h-9 px-4 py-2 has-[>svg]:px-3",
+ sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
+ lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
+ icon: "size-9",
+ },
},
defaultVariants: {
- variant: 'default',
- size: 'default'
- }
+ variant: "default",
+ size: "default",
+ },
});
- export type ButtonVariant = VariantProps<typeof buttonVariants>['variant'];
- export type ButtonSize = VariantProps<typeof buttonVariants>['size'];
+ export type ButtonVariant = VariantProps<typeof buttonVariants>["variant"];
+ export type ButtonSize = VariantProps<typeof buttonVariants>["size"];
export type ButtonProps = WithElementRef<HTMLButtonAttributes> &
WithElementRef<HTMLAnchorAttributes> & {
@@ -38,17 +40,41 @@
</script>
<script lang="ts">
- import { cn } from '$lib/utils.js';
-
- let { class: className, variant = 'default', size = 'default', ref = $bindable(null), href = undefined, type = 'button', children, ...restProps }: ButtonProps = $props();
+ let {
+ class: className,
+ variant = "default",
+ size = "default",
+ ref = $bindable(null),
+ href = undefined,
+ type = "button",
+ disabled,
+ children,
+ ...restProps
+ }: ButtonProps = $props();
</script>
{#if href}
- <a bind:this={ref} class={cn(buttonVariants({ variant, size }), className)} {href} {...restProps}>
+ <a
+ bind:this={ref}
+ data-slot="button"
+ class={cn(buttonVariants({ variant, size }), className)}
+ href={disabled ? undefined : href}
+ aria-disabled={disabled}
+ role={disabled ? "link" : undefined}
+ tabindex={disabled ? -1 : undefined}
+ {...restProps}
+ >
{@render children?.()}
</a>
{:else}
- <button bind:this={ref} class={cn(buttonVariants({ variant, size }), className)} {type} {...restProps}>
+ <button
+ bind:this={ref}
+ data-slot="button"
+ class={cn(buttonVariants({ variant, size }), className)}
+ {type}
+ {disabled}
+ {...restProps}
+ >
{@render children?.()}
</button>
{/if}
diff --git a/src/lib/components/ui/button/index.ts b/src/lib/components/ui/button/index.ts
index 3fd7e24ba..fb585d768 100644
--- a/src/lib/components/ui/button/index.ts
+++ b/src/lib/components/ui/button/index.ts
@@ -1,4 +1,9 @@
-import Root, { type ButtonProps, type ButtonSize, type ButtonVariant, buttonVariants } from './button.svelte';
+import Root, {
+ type ButtonProps,
+ type ButtonSize,
+ type ButtonVariant,
+ buttonVariants,
+} from "./button.svelte";
export {
Root,
@@ -8,5 +13,5 @@ export {
buttonVariants,
type ButtonProps,
type ButtonSize,
- type ButtonVariant
+ type ButtonVariant,
};
diff --git a/src/lib/components/ui/collapsible/collapsible-content.svelte b/src/lib/components/ui/collapsible/collapsible-content.svelte
new file mode 100644
index 000000000..bdabb559c
--- /dev/null
+++ b/src/lib/components/ui/collapsible/collapsible-content.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+ import { Collapsible as CollapsiblePrimitive } from "bits-ui";
+
+ let { ref = $bindable(null), ...restProps }: CollapsiblePrimitive.ContentProps = $props();
+</script>
+
+<CollapsiblePrimitive.Content bind:ref data-slot="collapsible-content" {...restProps} />
diff --git a/src/lib/components/ui/collapsible/collapsible-trigger.svelte b/src/lib/components/ui/collapsible/collapsible-trigger.svelte
new file mode 100644
index 000000000..ece7ad68e
--- /dev/null
+++ b/src/lib/components/ui/collapsible/collapsible-trigger.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+ import { Collapsible as CollapsiblePrimitive } from "bits-ui";
+
+ let { ref = $bindable(null), ...restProps }: CollapsiblePrimitive.TriggerProps = $props();
+</script>
+
+<CollapsiblePrimitive.Trigger bind:ref data-slot="collapsible-trigger" {...restProps} />
diff --git a/src/lib/components/ui/collapsible/collapsible.svelte b/src/lib/components/ui/collapsible/collapsible.svelte
new file mode 100644
index 000000000..1238eff6b
--- /dev/null
+++ b/src/lib/components/ui/collapsible/collapsible.svelte
@@ -0,0 +1,11 @@
+<script lang="ts">
+ import { Collapsible as CollapsiblePrimitive } from "bits-ui";
+
+ let {
+ ref = $bindable(null),
+ open = $bindable(false),
+ ...restProps
+ }: CollapsiblePrimitive.RootProps = $props();
+</script>
+
+<CollapsiblePrimitive.Root bind:ref data-slot="collapsible" {...restProps} />
diff --git a/src/lib/components/ui/collapsible/index.ts b/src/lib/components/ui/collapsible/index.ts
new file mode 100644
index 000000000..83c019883
--- /dev/null
+++ b/src/lib/components/ui/collapsible/index.ts
@@ -0,0 +1,15 @@
+import { Collapsible as CollapsiblePrimitive } from "bits-ui";
+
+const Root = CollapsiblePrimitive.Root;
+const Trigger = CollapsiblePrimitive.Trigger;
+const Content = CollapsiblePrimitive.Content;
+
+export {
+ Root,
+ Content,
+ Trigger,
+ //
+ Root as Collapsible,
+ Content as CollapsibleContent,
+ Trigger as CollapsibleTrigger,
+};
diff --git a/src/lib/components/ui/input/index.ts b/src/lib/components/ui/input/index.ts
index 15c0933dc..f47b6d3fb 100644
--- a/src/lib/components/ui/input/index.ts
+++ b/src/lib/components/ui/input/index.ts
@@ -1,7 +1,7 @@
-import Root from './input.svelte';
+import Root from "./input.svelte";
export {
Root,
//
- Root as Input
+ Root as Input,
};
diff --git a/src/lib/components/ui/input/input.svelte b/src/lib/components/ui/input/input.svelte
index 5877828a9..1eae616bc 100644
--- a/src/lib/components/ui/input/input.svelte
+++ b/src/lib/components/ui/input/input.svelte
@@ -1,19 +1,34 @@
<script lang="ts">
- import type { HTMLInputAttributes, HTMLInputTypeAttribute } from 'svelte/elements';
- import type { WithElementRef } from '$lib/utils.js';
- import { cn } from '$lib/utils.js';
+ import type { HTMLInputAttributes, HTMLInputTypeAttribute } from "svelte/elements";
+ import { cn, type WithElementRef } from "$lib/utils.js";
- type InputType = Exclude<HTMLInputTypeAttribute, 'file'>;
+ type InputType = Exclude<HTMLInputTypeAttribute, "file">;
- type Props = WithElementRef<Omit<HTMLInputAttributes, 'type'> & ({ type: 'file'; files?: FileList } | { type?: InputType; files?: undefined })>;
+ type Props = WithElementRef<
+ Omit<HTMLInputAttributes, "type"> &
+ ({ type: "file"; files?: FileList } | { type?: InputType; files?: undefined })
+ >;
- let { ref = $bindable(null), value = $bindable(), type, files = $bindable(), class: className, ...restProps }: Props = $props();
+ let {
+ ref = $bindable(null),
+ value = $bindable(),
+ type,
+ files = $bindable(),
+ class: className,
+ ...restProps
+ }: Props = $props();
</script>
-{#if type === 'file'}
+{#if type === "file"}
<input
bind:this={ref}
- class={cn('border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex h-10 w-full rounded-md border px-3 py-2 text-base file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm', className)}
+ data-slot="input"
+ class={cn(
+ "selection:bg-primary dark:bg-input/30 selection:text-primary-foreground border-input ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-2 text-sm font-medium outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
+ "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
+ "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
+ className
+ )}
type="file"
bind:files
bind:value
@@ -22,10 +37,15 @@
{:else}
<input
bind:this={ref}
- class={cn('border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex h-10 w-full rounded-md border px-3 py-2 text-base file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm', className)}
+ data-slot="input"
+ class={cn(
+ "border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
+ "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
+ "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
+ className
+ )}
{type}
bind:value
{...restProps}
- autocomplete="off"
/>
{/if}
diff --git a/src/lib/components/ui/separator/index.ts b/src/lib/components/ui/separator/index.ts
index 768efac96..82442d2cd 100644
--- a/src/lib/components/ui/separator/index.ts
+++ b/src/lib/components/ui/separator/index.ts
@@ -1,7 +1,7 @@
-import Root from './separator.svelte';
+import Root from "./separator.svelte";
export {
Root,
//
- Root as Separator
+ Root as Separator,
};
diff --git a/src/lib/components/ui/separator/separator.svelte b/src/lib/components/ui/separator/separator.svelte
index 18d33bf63..3648474e8 100644
--- a/src/lib/components/ui/separator/separator.svelte
+++ b/src/lib/components/ui/separator/separator.svelte
@@ -1,8 +1,20 @@
<script lang="ts">
- import { Separator as SeparatorPrimitive } from 'bits-ui';
- import { cn } from '$lib/utils.js';
+ import { Separator as SeparatorPrimitive } from "bits-ui";
+ import { cn } from "$lib/utils.js";
- let { ref = $bindable(null), class: className, orientation = 'horizontal', ...restProps }: SeparatorPrimitive.RootProps = $props();
+ let {
+ ref = $bindable(null),
+ class: className,
+ ...restProps
+ }: SeparatorPrimitive.RootProps = $props();
</script>
-<SeparatorPrimitive.Root bind:ref class={cn('bg-border shrink-0', orientation === 'horizontal' ? 'h-px w-full' : 'min-h-full w-px', className)} {orientation} {...restProps} />
+<SeparatorPrimitive.Root
+ bind:ref
+ data-slot="separator-root"
+ class={cn(
+ "bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=vertical]:h-full data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-px",
+ className
+ )}
+ {...restProps}
+/>
diff --git a/src/lib/components/ui/sheet/index.ts b/src/lib/components/ui/sheet/index.ts
new file mode 100644
index 000000000..01d40c80b
--- /dev/null
+++ b/src/lib/components/ui/sheet/index.ts
@@ -0,0 +1,36 @@
+import { Dialog as SheetPrimitive } from "bits-ui";
+import Trigger from "./sheet-trigger.svelte";
+import Close from "./sheet-close.svelte";
+import Overlay from "./sheet-overlay.svelte";
+import Content from "./sheet-content.svelte";
+import Header from "./sheet-header.svelte";
+import Footer from "./sheet-footer.svelte";
+import Title from "./sheet-title.svelte";
+import Description from "./sheet-description.svelte";
+
+const Root = SheetPrimitive.Root;
+const Portal = SheetPrimitive.Portal;
+
+export {
+ Root,
+ Close,
+ Trigger,
+ Portal,
+ Overlay,
+ Content,
+ Header,
+ Footer,
+ Title,
+ Description,
+ //
+ Root as Sheet,
+ Close as SheetClose,
+ Trigger as SheetTrigger,
+ Portal as SheetPortal,
+ Overlay as SheetOverlay,
+ Content as SheetContent,
+ Header as SheetHeader,
+ Footer as SheetFooter,
+ Title as SheetTitle,
+ Description as SheetDescription,
+};
diff --git a/src/lib/components/ui/sheet/sheet-close.svelte b/src/lib/components/ui/sheet/sheet-close.svelte
new file mode 100644
index 000000000..ae382c123
--- /dev/null
+++ b/src/lib/components/ui/sheet/sheet-close.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+ import { Dialog as SheetPrimitive } from "bits-ui";
+
+ let { ref = $bindable(null), ...restProps }: SheetPrimitive.CloseProps = $props();
+</script>
+
+<SheetPrimitive.Close bind:ref data-slot="sheet-close" {...restProps} />
diff --git a/src/lib/components/ui/sheet/sheet-content.svelte b/src/lib/components/ui/sheet/sheet-content.svelte
new file mode 100644
index 000000000..856922ea3
--- /dev/null
+++ b/src/lib/components/ui/sheet/sheet-content.svelte
@@ -0,0 +1,58 @@
+<script lang="ts" module>
+ import { tv, type VariantProps } from "tailwind-variants";
+ export const sheetVariants = tv({
+ base: "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
+ variants: {
+ side: {
+ top: "data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
+ bottom: "data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
+ left: "data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
+ right: "data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
+ },
+ },
+ defaultVariants: {
+ side: "right",
+ },
+ });
+
+ export type Side = VariantProps<typeof sheetVariants>["side"];
+</script>
+
+<script lang="ts">
+ import { Dialog as SheetPrimitive } from "bits-ui";
+ import XIcon from "@lucide/svelte/icons/x";
+ import type { Snippet } from "svelte";
+ import SheetOverlay from "./sheet-overlay.svelte";
+ import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ side = "right",
+ portalProps,
+ children,
+ ...restProps
+ }: WithoutChildrenOrChild<SheetPrimitive.ContentProps> & {
+ portalProps?: SheetPrimitive.PortalProps;
+ side?: Side;
+ children: Snippet;
+ } = $props();
+</script>
+
+<SheetPrimitive.Portal {...portalProps}>
+ <SheetOverlay />
+ <SheetPrimitive.Content
+ bind:ref
+ data-slot="sheet-content"
+ class={cn(sheetVariants({ side }), className)}
+ {...restProps}
+ >
+ {@render children?.()}
+ <SheetPrimitive.Close
+ class="ring-offset-background focus-visible:ring-ring rounded-xs focus-visible:outline-hidden absolute right-4 top-4 opacity-70 transition-opacity hover:opacity-100 focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none"
+ >
+ <XIcon class="size-4" />
+ <span class="sr-only">Close</span>
+ </SheetPrimitive.Close>
+ </SheetPrimitive.Content>
+</SheetPrimitive.Portal>
diff --git a/src/lib/components/ui/sheet/sheet-description.svelte b/src/lib/components/ui/sheet/sheet-description.svelte
new file mode 100644
index 000000000..333b17a7a
--- /dev/null
+++ b/src/lib/components/ui/sheet/sheet-description.svelte
@@ -0,0 +1,17 @@
+<script lang="ts">
+ import { Dialog as SheetPrimitive } from "bits-ui";
+ import { cn } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ ...restProps
+ }: SheetPrimitive.DescriptionProps = $props();
+</script>
+
+<SheetPrimitive.Description
+ bind:ref
+ data-slot="sheet-description"
+ class={cn("text-muted-foreground text-sm", className)}
+ {...restProps}
+/>
diff --git a/src/lib/components/ui/sheet/sheet-footer.svelte b/src/lib/components/ui/sheet/sheet-footer.svelte
new file mode 100644
index 000000000..dd9ed84b0
--- /dev/null
+++ b/src/lib/components/ui/sheet/sheet-footer.svelte
@@ -0,0 +1,20 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
+</script>
+
+<div
+ bind:this={ref}
+ data-slot="sheet-footer"
+ class={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ {...restProps}
+>
+ {@render children?.()}
+</div>
diff --git a/src/lib/components/ui/sheet/sheet-header.svelte b/src/lib/components/ui/sheet/sheet-header.svelte
new file mode 100644
index 000000000..757a6a566
--- /dev/null
+++ b/src/lib/components/ui/sheet/sheet-header.svelte
@@ -0,0 +1,20 @@
+<script lang="ts">
+ import type { HTMLAttributes } from "svelte/elements";
+ import { cn, type WithElementRef } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
+</script>
+
+<div
+ bind:this={ref}
+ data-slot="sheet-header"
+ class={cn("flex flex-col gap-1.5 p-4", className)}
+ {...restProps}
+>
+ {@render children?.()}
+</div>
diff --git a/src/lib/components/ui/sheet/sheet-overlay.svelte b/src/lib/components/ui/sheet/sheet-overlay.svelte
new file mode 100644
index 000000000..d1a6177db
--- /dev/null
+++ b/src/lib/components/ui/sheet/sheet-overlay.svelte
@@ -0,0 +1,22 @@
+<script lang="ts">
+ import { Dialog as SheetPrimitive } from "bits-ui";
+ import { cn } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ ...restProps
+ }: SheetPrimitive.OverlayProps = $props();
+
+ export { className as class };
+</script>
+
+<SheetPrimitive.Overlay
+ bind:ref
+ data-slot="sheet-overlay"
+ class={cn(
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+ className
+ )}
+ {...restProps}
+/>
diff --git a/src/lib/components/ui/sheet/sheet-title.svelte b/src/lib/components/ui/sheet/sheet-title.svelte
new file mode 100644
index 000000000..9fda327e9
--- /dev/null
+++ b/src/lib/components/ui/sheet/sheet-title.svelte
@@ -0,0 +1,17 @@
+<script lang="ts">
+ import { Dialog as SheetPrimitive } from "bits-ui";
+ import { cn } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ ...restProps
+ }: SheetPrimitive.TitleProps = $props();
+</script>
+
+<SheetPrimitive.Title
+ bind:ref
+ data-slot="sheet-title"
+ class={cn("text-foreground font-semibold", className)}
+ {...restProps}
+/>
diff --git a/src/lib/components/ui/sheet/sheet-trigger.svelte b/src/lib/components/ui/sheet/sheet-trigger.svelte
new file mode 100644
index 000000000..e266975f9
--- /dev/null
+++ b/src/lib/components/ui/sheet/sheet-trigger.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+ import { Dialog as SheetPrimitive } from "bits-ui";
+
+ let { ref = $bindable(null), ...restProps }: SheetPrimitive.TriggerProps = $props();
+</script>
+
+<SheetPrimitive.Trigger bind:ref data-slot="sheet-trigger" {...restProps} />
diff --git a/src/lib/components/ui/sidebar/constants.ts b/src/lib/components/ui/sidebar/constants.ts
new file mode 100644
index 000000000..4de44351d
--- /dev/null
+++ b/src/lib/components/ui/sidebar/constants.ts
@@ -0,0 +1,6 @@
+export const SIDEBAR_COOKIE_NAME = "sidebar:state";
+export const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
+export const SIDEBAR_WIDTH = "16rem";
+export const SIDEBAR_WIDTH_MOBILE = "18rem";
+export const SIDEBAR_WIDTH_ICON = "3rem";
+export const SIDEBAR_KEYBOARD_SHORTCUT = "b";
diff --git a/src/lib/components/ui/sidebar/context.svelte.ts b/src/lib/components/ui/sidebar/context.svelte.ts
new file mode 100644
index 000000000..15248adac
--- /dev/null
+++ b/src/lib/components/ui/sidebar/context.svelte.ts
@@ -0,0 +1,81 @@
+import { IsMobile } from "$lib/hooks/is-mobile.svelte.js";
+import { getContext, setContext } from "svelte";
+import { SIDEBAR_KEYBOARD_SHORTCUT } from "./constants.js";
+
+type Getter<T> = () => T;
+
+export type SidebarStateProps = {
+ /**
+ * A getter function that returns the current open state of the sidebar.
+ * We use a getter function here to support `bind:open` on the `Sidebar.Provider`
+ * component.
+ */
+ open: Getter<boolean>;
+
+ /**
+ * A function that sets the open state of the sidebar. To support `bind:open`, we need
+ * a source of truth for changing the open state to ensure it will be synced throughout
+ * the sub-components and any `bind:` references.
+ */
+ setOpen: (open: boolean) => void;
+};
+
+class SidebarState {
+ readonly props: SidebarStateProps;
+ open = $derived.by(() => this.props.open());
+ openMobile = $state(false);
+ setOpen: SidebarStateProps["setOpen"];
+ #isMobile: IsMobile;
+ state = $derived.by(() => (this.open ? "expanded" : "collapsed"));
+
+ constructor(props: SidebarStateProps) {
+ this.setOpen = props.setOpen;
+ this.#isMobile = new IsMobile();
+ this.props = props;
+ }
+
+ // Convenience getter for checking if the sidebar is mobile
+ // without this, we would need to use `sidebar.isMobile.current` everywhere
+ get isMobile() {
+ return this.#isMobile.current;
+ }
+
+ // Event handler to apply to the `<svelte:window>`
+ handleShortcutKeydown = (e: KeyboardEvent) => {
+ if (e.key === SIDEBAR_KEYBOARD_SHORTCUT && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ this.toggle();
+ }
+ };
+
+ setOpenMobile = (value: boolean) => {
+ this.openMobile = value;
+ };
+
+ toggle = () => {
+ return this.#isMobile.current
+ ? (this.openMobile = !this.openMobile)
+ : this.setOpen(!this.open);
+ };
+}
+
+const SYMBOL_KEY = "scn-sidebar";
+
+/**
+ * Instantiates a new `SidebarState` instance and sets it in the context.
+ *
+ * @param props The constructor props for the `SidebarState` class.
+ * @returns The `SidebarState` instance.
+ */
+export function setSidebar(props: SidebarStateProps): SidebarState {
+ return setContext(Symbol.for(SYMBOL_KEY), new SidebarState(props));
+}
+
+/**
+ * Retrieves the `SidebarState` instance from the context. This is a class instance,
+ * so you cannot destructure it.
+ * @returns The `SidebarState` instance.
+ */
+export function useSidebar(): SidebarState {
+ return getContext(Symbol.for(SYMBOL_KEY));
+}
diff --git a/src/lib/components/ui/sidebar/index.ts b/src/lib/components/ui/sidebar/index.ts
new file mode 100644
index 000000000..318a34178
--- /dev/null
+++ b/src/lib/components/ui/sidebar/index.ts
@@ -0,0 +1,75 @@
+import { useSidebar } from "./context.svelte.js";
+import Content from "./sidebar-content.svelte";
+import Footer from "./sidebar-footer.svelte";
+import GroupAction from "./sidebar-group-action.svelte";
+import GroupContent from "./sidebar-group-content.svelte";
+import GroupLabel from "./sidebar-group-label.svelte";
+import Group from "./sidebar-group.svelte";
+import Header from "./sidebar-header.svelte";
+import Input from "./sidebar-input.svelte";
+import Inset from "./sidebar-inset.svelte";
+import MenuAction from "./sidebar-menu-action.svelte";
+import MenuBadge from "./sidebar-menu-badge.svelte";
+import MenuButton from "./sidebar-menu-button.svelte";
+import MenuItem from "./sidebar-menu-item.svelte";
+import MenuSkeleton from "./sidebar-menu-skeleton.svelte";
+import MenuSubButton from "./sidebar-menu-sub-button.svelte";
+import MenuSubItem from "./sidebar-menu-sub-item.svelte";
+import MenuSub from "./sidebar-menu-sub.svelte";
+import Menu from "./sidebar-menu.svelte";
+import Provider from "./sidebar-provider.svelte";
+import Rail from "./sidebar-rail.svelte";
+import Separator from "./sidebar-separator.svelte";
+import Trigger from "./sidebar-trigger.svelte";
+import Root from "./sidebar.svelte";
+
+export {
+ Content,
+ Footer,
+ Group,
+ GroupAction,
+ GroupContent,
+ GroupLabel,
+ Header,
+ Input,
+ Inset,
+ Menu,
+ MenuAction,
+ MenuBadge,
+ MenuButton,
+ MenuItem,
+ MenuSkeleton,
+ MenuSub,
+ MenuSubButton,
+ MenuSubItem,
+ Provider,
+ Rail,
+ Root,
+ Separator,
+ //
+ Root as Sidebar,
+ Content as SidebarContent,
+ Footer as SidebarFooter,
+ Group as SidebarGroup,
+ GroupAction as SidebarGroupAction,
+ GroupContent as SidebarGroupContent,
+ GroupLabel as SidebarGroupLabel,
+ Header as SidebarHeader,
+ Input as SidebarInput,
+ Inset as SidebarInset,
+ Menu as SidebarMenu,
+ MenuAction as SidebarMenuAction,
+ MenuBadge as SidebarMenuBadge,
+ MenuButton as SidebarMenuButton,
+ MenuItem as SidebarMenuItem,
+ MenuSkeleton as SidebarMenuSkeleton,
+ MenuSub as SidebarMenuSub,
+ MenuSubButton as SidebarMenuSubButton,
+ MenuSubItem as SidebarMenuSubItem,
+ Provider as SidebarProvider,
+ Rail as SidebarRail,
+ Separator as SidebarSeparator,
+ Trigger as SidebarTrigger,
+ Trigger,
+ useSidebar,
+};
diff --git a/src/lib/components/ui/sidebar/sidebar-content.svelte b/src/lib/components/ui/sidebar/sidebar-content.svelte
new file mode 100644
index 000000000..f12180020
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-content.svelte
@@ -0,0 +1,24 @@
+<script lang="ts">
+ import type { HTMLAttributes } from "svelte/elements";
+ import { cn, type WithElementRef } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();
+</script>
+
+<div
+ bind:this={ref}
+ data-slot="sidebar-content"
+ data-sidebar="content"
+ class={cn(
+ "flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
+ className
+ )}
+ {...restProps}
+>
+ {@render children?.()}
+</div>
diff --git a/src/lib/components/ui/sidebar/sidebar-footer.svelte b/src/lib/components/ui/sidebar/sidebar-footer.svelte
new file mode 100644
index 000000000..6259cb952
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-footer.svelte
@@ -0,0 +1,21 @@
+<script lang="ts">
+ import type { HTMLAttributes } from "svelte/elements";
+ import { cn, type WithElementRef } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();
+</script>
+
+<div
+ bind:this={ref}
+ data-slot="sidebar-footer"
+ data-sidebar="footer"
+ class={cn("flex flex-col gap-2 p-2", className)}
+ {...restProps}
+>
+ {@render children?.()}
+</div>
diff --git a/src/lib/components/ui/sidebar/sidebar-group-action.svelte b/src/lib/components/ui/sidebar/sidebar-group-action.svelte
new file mode 100644
index 000000000..fb84e4a23
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-group-action.svelte
@@ -0,0 +1,36 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { Snippet } from "svelte";
+ import type { HTMLButtonAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ child,
+ ...restProps
+ }: WithElementRef<HTMLButtonAttributes> & {
+ child?: Snippet<[{ props: Record<string, unknown> }]>;
+ } = $props();
+
+ const mergedProps = $derived({
+ class: cn(
+ "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground outline-hidden absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ // Increases the hit area of the button on mobile.
+ "after:absolute after:-inset-2 md:after:hidden",
+ "group-data-[collapsible=icon]:hidden",
+ className
+ ),
+ "data-slot": "sidebar-group-action",
+ "data-sidebar": "group-action",
+ ...restProps,
+ });
+</script>
+
+{#if child}
+ {@render child({ props: mergedProps })}
+{:else}
+ <button bind:this={ref} {...mergedProps}>
+ {@render children?.()}
+ </button>
+{/if}
diff --git a/src/lib/components/ui/sidebar/sidebar-group-content.svelte b/src/lib/components/ui/sidebar/sidebar-group-content.svelte
new file mode 100644
index 000000000..415255f1f
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-group-content.svelte
@@ -0,0 +1,21 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
+</script>
+
+<div
+ bind:this={ref}
+ data-slot="sidebar-group-content"
+ data-sidebar="group-content"
+ class={cn("w-full text-sm", className)}
+ {...restProps}
+>
+ {@render children?.()}
+</div>
diff --git a/src/lib/components/ui/sidebar/sidebar-group-label.svelte b/src/lib/components/ui/sidebar/sidebar-group-label.svelte
new file mode 100644
index 000000000..e292945bf
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-group-label.svelte
@@ -0,0 +1,34 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { Snippet } from "svelte";
+ import type { HTMLAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ children,
+ child,
+ class: className,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLElement>> & {
+ child?: Snippet<[{ props: Record<string, unknown> }]>;
+ } = $props();
+
+ const mergedProps = $derived({
+ class: cn(
+ "text-sidebar-foreground/70 ring-sidebar-ring outline-hidden flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
+ className
+ ),
+ "data-slot": "sidebar-group-label",
+ "data-sidebar": "group-label",
+ ...restProps,
+ });
+</script>
+
+{#if child}
+ {@render child({ props: mergedProps })}
+{:else}
+ <div bind:this={ref} {...mergedProps}>
+ {@render children?.()}
+ </div>
+{/if}
diff --git a/src/lib/components/ui/sidebar/sidebar-group.svelte b/src/lib/components/ui/sidebar/sidebar-group.svelte
new file mode 100644
index 000000000..ec18a6976
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-group.svelte
@@ -0,0 +1,21 @@
+<script lang="ts">
+ import type { HTMLAttributes } from "svelte/elements";
+ import { cn, type WithElementRef } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();
+</script>
+
+<div
+ bind:this={ref}
+ data-slot="sidebar-group"
+ data-sidebar="group"
+ class={cn("relative flex w-full min-w-0 flex-col p-2", className)}
+ {...restProps}
+>
+ {@render children?.()}
+</div>
diff --git a/src/lib/components/ui/sidebar/sidebar-header.svelte b/src/lib/components/ui/sidebar/sidebar-header.svelte
new file mode 100644
index 000000000..a1b2db150
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-header.svelte
@@ -0,0 +1,21 @@
+<script lang="ts">
+ import type { HTMLAttributes } from "svelte/elements";
+ import { cn, type WithElementRef } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();
+</script>
+
+<div
+ bind:this={ref}
+ data-slot="sidebar-header"
+ data-sidebar="header"
+ class={cn("flex flex-col gap-2 p-2", className)}
+ {...restProps}
+>
+ {@render children?.()}
+</div>
diff --git a/src/lib/components/ui/sidebar/sidebar-input.svelte b/src/lib/components/ui/sidebar/sidebar-input.svelte
new file mode 100644
index 000000000..19b366601
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-input.svelte
@@ -0,0 +1,21 @@
+<script lang="ts">
+ import type { ComponentProps } from "svelte";
+ import { Input } from "$lib/components/ui/input/index.js";
+ import { cn } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ value = $bindable(""),
+ class: className,
+ ...restProps
+ }: ComponentProps<typeof Input> = $props();
+</script>
+
+<Input
+ bind:ref
+ bind:value
+ data-slot="sidebar-input"
+ data-sidebar="input"
+ class={cn("bg-background h-8 w-full shadow-none", className)}
+ {...restProps}
+/>
diff --git a/src/lib/components/ui/sidebar/sidebar-inset.svelte b/src/lib/components/ui/sidebar/sidebar-inset.svelte
new file mode 100644
index 000000000..d862761d0
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-inset.svelte
@@ -0,0 +1,24 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();
+</script>
+
+<main
+ bind:this={ref}
+ data-slot="sidebar-inset"
+ class={cn(
+ "bg-background relative flex w-full flex-1 flex-col",
+ "md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm",
+ className
+ )}
+ {...restProps}
+>
+ {@render children?.()}
+</main>
diff --git a/src/lib/components/ui/sidebar/sidebar-menu-action.svelte b/src/lib/components/ui/sidebar/sidebar-menu-action.svelte
new file mode 100644
index 000000000..fa3fb0cd8
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-menu-action.svelte
@@ -0,0 +1,43 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { Snippet } from "svelte";
+ import type { HTMLButtonAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ showOnHover = false,
+ children,
+ child,
+ ...restProps
+ }: WithElementRef<HTMLButtonAttributes> & {
+ child?: Snippet<[{ props: Record<string, unknown> }]>;
+ showOnHover?: boolean;
+ } = $props();
+
+ const mergedProps = $derived({
+ class: cn(
+ "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground outline-hidden absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ // Increases the hit area of the button on mobile.
+ "after:absolute after:-inset-2 md:after:hidden",
+ "peer-data-[size=sm]/menu-button:top-1",
+ "peer-data-[size=default]/menu-button:top-1.5",
+ "peer-data-[size=lg]/menu-button:top-2.5",
+ "group-data-[collapsible=icon]:hidden",
+ showOnHover &&
+ "peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
+ className
+ ),
+ "data-slot": "sidebar-menu-action",
+ "data-sidebar": "menu-action",
+ ...restProps,
+ });
+</script>
+
+{#if child}
+ {@render child({ props: mergedProps })}
+{:else}
+ <button bind:this={ref} {...mergedProps}>
+ {@render children?.()}
+ </button>
+{/if}
diff --git a/src/lib/components/ui/sidebar/sidebar-menu-badge.svelte b/src/lib/components/ui/sidebar/sidebar-menu-badge.svelte
new file mode 100644
index 000000000..69e5a3cbd
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-menu-badge.svelte
@@ -0,0 +1,29 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();
+</script>
+
+<div
+ bind:this={ref}
+ data-slot="sidebar-menu-badge"
+ data-sidebar="menu-badge"
+ class={cn(
+ "text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums",
+ "peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
+ "peer-data-[size=sm]/menu-button:top-1",
+ "peer-data-[size=default]/menu-button:top-1.5",
+ "peer-data-[size=lg]/menu-button:top-2.5",
+ "group-data-[collapsible=icon]:hidden",
+ className
+ )}
+ {...restProps}
+>
+ {@render children?.()}
+</div>
diff --git a/src/lib/components/ui/sidebar/sidebar-menu-button.svelte b/src/lib/components/ui/sidebar/sidebar-menu-button.svelte
new file mode 100644
index 000000000..4bef683f0
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-menu-button.svelte
@@ -0,0 +1,103 @@
+<script lang="ts" module>
+ import { tv, type VariantProps } from "tailwind-variants";
+
+ export const sidebarMenuButtonVariants = tv({
+ base: "peer/menu-button outline-hidden ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground group-has-data-[sidebar=menu-action]/menu-item:pr-8 data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm transition-[width,height,padding] focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:font-medium [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
+ variants: {
+ variant: {
+ default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
+ outline:
+ "bg-background hover:bg-sidebar-accent hover:text-sidebar-accent-foreground shadow-[0_0_0_1px_var(--sidebar-border)] hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",
+ },
+ size: {
+ default: "h-8 text-sm",
+ sm: "h-7 text-xs",
+ lg: "group-data-[collapsible=icon]:p-0! h-12 text-sm",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ });
+
+ export type SidebarMenuButtonVariant = VariantProps<
+ typeof sidebarMenuButtonVariants
+ >["variant"];
+ export type SidebarMenuButtonSize = VariantProps<typeof sidebarMenuButtonVariants>["size"];
+</script>
+
+<script lang="ts">
+ import * as Tooltip from "$lib/components/ui/tooltip/index.js";
+ import { cn, type WithElementRef, type WithoutChildrenOrChild } from "$lib/utils.js";
+ import { mergeProps } from "bits-ui";
+ import type { ComponentProps, Snippet } from "svelte";
+ import type { HTMLAttributes } from "svelte/elements";
+ import { useSidebar } from "./context.svelte.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ child,
+ variant = "default",
+ size = "default",
+ isActive = false,
+ tooltipContent,
+ tooltipContentProps,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLButtonElement>, HTMLButtonElement> & {
+ isActive?: boolean;
+ variant?: SidebarMenuButtonVariant;
+ size?: SidebarMenuButtonSize;
+ tooltipContent?: Snippet | string;
+ tooltipContentProps?: WithoutChildrenOrChild<ComponentProps<typeof Tooltip.Content>>;
+ child?: Snippet<[{ props: Record<string, unknown> }]>;
+ } = $props();
+
+ const sidebar = useSidebar();
+
+ const buttonProps = $derived({
+ class: cn(sidebarMenuButtonVariants({ variant, size }), className),
+ "data-slot": "sidebar-menu-button",
+ "data-sidebar": "menu-button",
+ "data-size": size,
+ "data-active": isActive,
+ ...restProps,
+ });
+</script>
+
+{#snippet Button({ props }: { props?: Record<string, unknown> })}
+ {@const mergedProps = mergeProps(buttonProps, props)}
+ {#if child}
+ {@render child({ props: mergedProps })}
+ {:else}
+ <button bind:this={ref} {...mergedProps}>
+ {@render children?.()}
+ </button>
+ {/if}
+{/snippet}
+
+{#if !tooltipContent}
+ {@render Button({})}
+{:else}
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ {#snippet child({ props })}
+ {@render Button({ props })}
+ {/snippet}
+ </Tooltip.Trigger>
+ <Tooltip.Content
+ side="right"
+ align="center"
+ hidden={sidebar.state !== "collapsed" || sidebar.isMobile}
+ {...tooltipContentProps}
+ >
+ {#if typeof tooltipContent === "string"}
+ {tooltipContent}
+ {:else if tooltipContent}
+ {@render tooltipContent()}
+ {/if}
+ </Tooltip.Content>
+ </Tooltip.Root>
+{/if}
diff --git a/src/lib/components/ui/sidebar/sidebar-menu-item.svelte b/src/lib/components/ui/sidebar/sidebar-menu-item.svelte
new file mode 100644
index 000000000..4db445323
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-menu-item.svelte
@@ -0,0 +1,21 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLLIElement>, HTMLLIElement> = $props();
+</script>
+
+<li
+ bind:this={ref}
+ data-slot="sidebar-menu-item"
+ data-sidebar="menu-item"
+ class={cn("group/menu-item relative", className)}
+ {...restProps}
+>
+ {@render children?.()}
+</li>
diff --git a/src/lib/components/ui/sidebar/sidebar-menu-skeleton.svelte b/src/lib/components/ui/sidebar/sidebar-menu-skeleton.svelte
new file mode 100644
index 000000000..cc63b04d5
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-menu-skeleton.svelte
@@ -0,0 +1,36 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import { Skeleton } from "$lib/components/ui/skeleton/index.js";
+ import type { HTMLAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ showIcon = false,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLElement>> & {
+ showIcon?: boolean;
+ } = $props();
+
+ // Random width between 50% and 90%
+ const width = `${Math.floor(Math.random() * 40) + 50}%`;
+</script>
+
+<div
+ bind:this={ref}
+ data-slot="sidebar-menu-skeleton"
+ data-sidebar="menu-skeleton"
+ class={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
+ {...restProps}
+>
+ {#if showIcon}
+ <Skeleton class="size-4 rounded-md" data-sidebar="menu-skeleton-icon" />
+ {/if}
+ <Skeleton
+ class="max-w-(--skeleton-width) h-4 flex-1"
+ data-sidebar="menu-skeleton-text"
+ style="--skeleton-width: {width};"
+ />
+ {@render children?.()}
+</div>
diff --git a/src/lib/components/ui/sidebar/sidebar-menu-sub-button.svelte b/src/lib/components/ui/sidebar/sidebar-menu-sub-button.svelte
new file mode 100644
index 000000000..987f104d9
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-menu-sub-button.svelte
@@ -0,0 +1,43 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { Snippet } from "svelte";
+ import type { HTMLAnchorAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ children,
+ child,
+ class: className,
+ size = "md",
+ isActive = false,
+ ...restProps
+ }: WithElementRef<HTMLAnchorAttributes> & {
+ child?: Snippet<[{ props: Record<string, unknown> }]>;
+ size?: "sm" | "md";
+ isActive?: boolean;
+ } = $props();
+
+ const mergedProps = $derived({
+ class: cn(
+ "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground outline-hidden flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
+ "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
+ size === "sm" && "text-xs",
+ size === "md" && "text-sm",
+ "group-data-[collapsible=icon]:hidden",
+ className
+ ),
+ "data-slot": "sidebar-menu-sub-button",
+ "data-sidebar": "menu-sub-button",
+ "data-size": size,
+ "data-active": isActive,
+ ...restProps,
+ });
+</script>
+
+{#if child}
+ {@render child({ props: mergedProps })}
+{:else}
+ <a bind:this={ref} {...mergedProps}>
+ {@render children?.()}
+ </a>
+{/if}
diff --git a/src/lib/components/ui/sidebar/sidebar-menu-sub-item.svelte b/src/lib/components/ui/sidebar/sidebar-menu-sub-item.svelte
new file mode 100644
index 000000000..681d0f1d3
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-menu-sub-item.svelte
@@ -0,0 +1,21 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ children,
+ class: className,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLLIElement>> = $props();
+</script>
+
+<li
+ bind:this={ref}
+ data-slot="sidebar-menu-sub-item"
+ data-sidebar="menu-sub-item"
+ class={cn("group/menu-sub-item relative", className)}
+ {...restProps}
+>
+ {@render children?.()}
+</li>
diff --git a/src/lib/components/ui/sidebar/sidebar-menu-sub.svelte b/src/lib/components/ui/sidebar/sidebar-menu-sub.svelte
new file mode 100644
index 000000000..8ab11110e
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-menu-sub.svelte
@@ -0,0 +1,25 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLUListElement>> = $props();
+</script>
+
+<ul
+ bind:this={ref}
+ data-slot="sidebar-menu-sub"
+ data-sidebar="menu-sub"
+ class={cn(
+ "border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
+ "group-data-[collapsible=icon]:hidden",
+ className
+ )}
+ {...restProps}
+>
+ {@render children?.()}
+</ul>
diff --git a/src/lib/components/ui/sidebar/sidebar-menu.svelte b/src/lib/components/ui/sidebar/sidebar-menu.svelte
new file mode 100644
index 000000000..946ccceff
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-menu.svelte
@@ -0,0 +1,21 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLUListElement>, HTMLUListElement> = $props();
+</script>
+
+<ul
+ bind:this={ref}
+ data-slot="sidebar-menu"
+ data-sidebar="menu"
+ class={cn("flex w-full min-w-0 flex-col gap-1", className)}
+ {...restProps}
+>
+ {@render children?.()}
+</ul>
diff --git a/src/lib/components/ui/sidebar/sidebar-provider.svelte b/src/lib/components/ui/sidebar/sidebar-provider.svelte
new file mode 100644
index 000000000..5b0d0aa20
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-provider.svelte
@@ -0,0 +1,53 @@
+<script lang="ts">
+ import * as Tooltip from "$lib/components/ui/tooltip/index.js";
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+ import {
+ SIDEBAR_COOKIE_MAX_AGE,
+ SIDEBAR_COOKIE_NAME,
+ SIDEBAR_WIDTH,
+ SIDEBAR_WIDTH_ICON,
+ } from "./constants.js";
+ import { setSidebar } from "./context.svelte.js";
+
+ let {
+ ref = $bindable(null),
+ open = $bindable(true),
+ onOpenChange = () => {},
+ class: className,
+ style,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLDivElement>> & {
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ } = $props();
+
+ const sidebar = setSidebar({
+ open: () => open,
+ setOpen: (value: boolean) => {
+ open = value;
+ onOpenChange(value);
+
+ // This sets the cookie to keep the sidebar state.
+ document.cookie = `${SIDEBAR_COOKIE_NAME}=${open}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
+ },
+ });
+</script>
+
+<svelte:window onkeydown={sidebar.handleShortcutKeydown} />
+
+<Tooltip.Provider delayDuration={0}>
+ <div
+ data-slot="sidebar-wrapper"
+ style="--sidebar-width: {SIDEBAR_WIDTH}; --sidebar-width-icon: {SIDEBAR_WIDTH_ICON}; {style}"
+ class={cn(
+ "group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
+ className
+ )}
+ bind:this={ref}
+ {...restProps}
+ >
+ {@render children?.()}
+ </div>
+</Tooltip.Provider>
diff --git a/src/lib/components/ui/sidebar/sidebar-rail.svelte b/src/lib/components/ui/sidebar/sidebar-rail.svelte
new file mode 100644
index 000000000..e913d2120
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-rail.svelte
@@ -0,0 +1,36 @@
+<script lang="ts">
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+ import { useSidebar } from "./context.svelte.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLButtonElement>, HTMLButtonElement> = $props();
+
+ const sidebar = useSidebar();
+</script>
+
+<button
+ bind:this={ref}
+ data-sidebar="rail"
+ data-slot="sidebar-rail"
+ aria-label="Toggle Sidebar"
+ tabIndex={-1}
+ onclick={sidebar.toggle}
+ title="Toggle Sidebar"
+ class={cn(
+ "hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
+ "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
+ "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
+ "hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
+ "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
+ "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
+ className
+ )}
+ {...restProps}
+>
+ {@render children?.()}
+</button>
diff --git a/src/lib/components/ui/sidebar/sidebar-separator.svelte b/src/lib/components/ui/sidebar/sidebar-separator.svelte
new file mode 100644
index 000000000..18d791bd5
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-separator.svelte
@@ -0,0 +1,19 @@
+<script lang="ts">
+ import { Separator } from "$lib/components/ui/separator/index.js";
+ import { cn } from "$lib/utils.js";
+ import type { ComponentProps } from "svelte";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ ...restProps
+ }: ComponentProps<typeof Separator> = $props();
+</script>
+
+<Separator
+ bind:ref
+ data-slot="sidebar-separator"
+ data-sidebar="separator"
+ class={cn("bg-sidebar-border mx-2 w-auto", className)}
+ {...restProps}
+/>
diff --git a/src/lib/components/ui/sidebar/sidebar-trigger.svelte b/src/lib/components/ui/sidebar/sidebar-trigger.svelte
new file mode 100644
index 000000000..182518278
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar-trigger.svelte
@@ -0,0 +1,35 @@
+<script lang="ts">
+ import { Button } from "$lib/components/ui/button/index.js";
+ import { cn } from "$lib/utils.js";
+ import PanelLeftIcon from "@lucide/svelte/icons/panel-left";
+ import type { ComponentProps } from "svelte";
+ import { useSidebar } from "./context.svelte.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ onclick,
+ ...restProps
+ }: ComponentProps<typeof Button> & {
+ onclick?: (e: MouseEvent) => void;
+ } = $props();
+
+ const sidebar = useSidebar();
+</script>
+
+<Button
+ data-sidebar="trigger"
+ data-slot="sidebar-trigger"
+ variant="ghost"
+ size="icon"
+ class={cn("size-7", className)}
+ type="button"
+ onclick={(e) => {
+ onclick?.(e);
+ sidebar.toggle();
+ }}
+ {...restProps}
+>
+ <PanelLeftIcon />
+ <span class="sr-only">Toggle Sidebar</span>
+</Button>
diff --git a/src/lib/components/ui/sidebar/sidebar.svelte b/src/lib/components/ui/sidebar/sidebar.svelte
new file mode 100644
index 000000000..c8c36df7b
--- /dev/null
+++ b/src/lib/components/ui/sidebar/sidebar.svelte
@@ -0,0 +1,104 @@
+<script lang="ts">
+ import * as Sheet from "$lib/components/ui/sheet/index.js";
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+ import { SIDEBAR_WIDTH_MOBILE } from "./constants.js";
+ import { useSidebar } from "./context.svelte.js";
+
+ let {
+ ref = $bindable(null),
+ side = "left",
+ variant = "sidebar",
+ collapsible = "offcanvas",
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLDivElement>> & {
+ side?: "left" | "right";
+ variant?: "sidebar" | "floating" | "inset";
+ collapsible?: "offcanvas" | "icon" | "none";
+ } = $props();
+
+ const sidebar = useSidebar();
+</script>
+
+{#if collapsible === "none"}
+ <div
+ class={cn(
+ "bg-sidebar text-sidebar-foreground w-(--sidebar-width) flex h-full flex-col",
+ className
+ )}
+ bind:this={ref}
+ {...restProps}
+ >
+ {@render children?.()}
+ </div>
+{:else if sidebar.isMobile}
+ <Sheet.Root
+ bind:open={() => sidebar.openMobile, (v) => sidebar.setOpenMobile(v)}
+ {...restProps}
+ >
+ <Sheet.Content
+ data-sidebar="sidebar"
+ data-slot="sidebar"
+ data-mobile="true"
+ class="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
+ style="--sidebar-width: {SIDEBAR_WIDTH_MOBILE};"
+ {side}
+ >
+ <Sheet.Header class="sr-only">
+ <Sheet.Title>Sidebar</Sheet.Title>
+ <Sheet.Description>Displays the mobile sidebar.</Sheet.Description>
+ </Sheet.Header>
+ <div class="flex h-full w-full flex-col">
+ {@render children?.()}
+ </div>
+ </Sheet.Content>
+ </Sheet.Root>
+{:else}
+ <div
+ bind:this={ref}
+ class="text-sidebar-foreground group peer hidden md:block"
+ data-state={sidebar.state}
+ data-collapsible={sidebar.state === "collapsed" ? collapsible : ""}
+ data-variant={variant}
+ data-side={side}
+ data-slot="sidebar"
+ >
+ <!-- This is what handles the sidebar gap on desktop -->
+ <div
+ data-slot="sidebar-gap"
+ class={cn(
+ "w-(--sidebar-width) relative bg-transparent transition-[width] duration-200 ease-linear",
+ "group-data-[collapsible=offcanvas]:w-0",
+ "group-data-[side=right]:rotate-180",
+ variant === "floating" || variant === "inset"
+ ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
+ : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
+ )}
+ ></div>
+ <div
+ data-slot="sidebar-container"
+ class={cn(
+ "w-(--sidebar-width) fixed inset-y-0 z-10 hidden h-svh transition-[left,right,width] duration-200 ease-linear md:flex",
+ side === "left"
+ ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
+ : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
+ // Adjust the padding for floating and inset variants.
+ variant === "floating" || variant === "inset"
+ ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
+ : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
+ className
+ )}
+ {...restProps}
+ >
+ <div
+ data-sidebar="sidebar"
+ data-slot="sidebar-inner"
+ class="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
+ >
+ {@render children?.()}
+ </div>
+ </div>
+ </div>
+{/if}
diff --git a/src/lib/components/ui/skeleton/index.ts b/src/lib/components/ui/skeleton/index.ts
new file mode 100644
index 000000000..186db219a
--- /dev/null
+++ b/src/lib/components/ui/skeleton/index.ts
@@ -0,0 +1,7 @@
+import Root from "./skeleton.svelte";
+
+export {
+ Root,
+ //
+ Root as Skeleton,
+};
diff --git a/src/lib/components/ui/skeleton/skeleton.svelte b/src/lib/components/ui/skeleton/skeleton.svelte
new file mode 100644
index 000000000..c7e3d26ce
--- /dev/null
+++ b/src/lib/components/ui/skeleton/skeleton.svelte
@@ -0,0 +1,17 @@
+<script lang="ts">
+ import { cn, type WithElementRef, type WithoutChildren } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ ...restProps
+ }: WithoutChildren<WithElementRef<HTMLAttributes<HTMLDivElement>>> = $props();
+</script>
+
+<div
+ bind:this={ref}
+ data-slot="skeleton"
+ class={cn("bg-accent animate-pulse rounded-md", className)}
+ {...restProps}
+></div>
diff --git a/src/lib/components/ui/tooltip/index.ts b/src/lib/components/ui/tooltip/index.ts
index 034ab2079..313a7f069 100644
--- a/src/lib/components/ui/tooltip/index.ts
+++ b/src/lib/components/ui/tooltip/index.ts
@@ -1,18 +1,21 @@
-import { Tooltip as TooltipPrimitive } from 'bits-ui';
-import Content from './tooltip-content.svelte';
+import { Tooltip as TooltipPrimitive } from "bits-ui";
+import Trigger from "./tooltip-trigger.svelte";
+import Content from "./tooltip-content.svelte";
const Root = TooltipPrimitive.Root;
-const Trigger = TooltipPrimitive.Trigger;
const Provider = TooltipPrimitive.Provider;
+const Portal = TooltipPrimitive.Portal;
export {
Root,
Trigger,
Content,
Provider,
+ Portal,
//
Root as Tooltip,
Content as TooltipContent,
Trigger as TooltipTrigger,
- Provider as TooltipProvider
+ Provider as TooltipProvider,
+ Portal as TooltipPortal,
};
diff --git a/src/lib/components/ui/tooltip/tooltip-content.svelte b/src/lib/components/ui/tooltip/tooltip-content.svelte
index c805815f8..b0c399ca4 100644
--- a/src/lib/components/ui/tooltip/tooltip-content.svelte
+++ b/src/lib/components/ui/tooltip/tooltip-content.svelte
@@ -1,16 +1,47 @@
<script lang="ts">
- import { Tooltip as TooltipPrimitive } from 'bits-ui';
- import { cn } from '$lib/utils.js';
+ import { Tooltip as TooltipPrimitive } from "bits-ui";
+ import { cn } from "$lib/utils.js";
- let { ref = $bindable(null), class: className, sideOffset = 4, ...restProps }: TooltipPrimitive.ContentProps = $props();
+ let {
+ ref = $bindable(null),
+ class: className,
+ sideOffset = 0,
+ side = "top",
+ children,
+ arrowClasses,
+ ...restProps
+ }: TooltipPrimitive.ContentProps & {
+ arrowClasses?: string;
+ } = $props();
</script>
-<TooltipPrimitive.Content
- bind:ref
- {sideOffset}
- class={cn(
- 'bg-popover text-popover-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 overflow-hidden rounded-md border px-3 py-1.5 text-sm shadow-md',
- className
- )}
- {...restProps}
-/>
+<TooltipPrimitive.Portal>
+ <TooltipPrimitive.Content
+ bind:ref
+ data-slot="tooltip-content"
+ {sideOffset}
+ {side}
+ class={cn(
+ "bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--bits-tooltip-content-transform-origin) z-50 w-fit text-balance rounded-md px-3 py-1.5 text-xs",
+ className
+ )}
+ {...restProps}
+ >
+ {@render children?.()}
+ <TooltipPrimitive.Arrow>
+ {#snippet child({ props })}
+ <div
+ class={cn(
+ "bg-primary z-50 size-2.5 rotate-45 rounded-[2px]",
+ "data-[side=top]:translate-x-1/2 data-[side=top]:translate-y-[calc(-50%_+_2px)]",
+ "data-[side=bottom]:-translate-y-[calc(-50%_+_1px)] data-[side=bottom]:translate-x-1/2",
+ "data-[side=right]:translate-x-[calc(50%_+_2px)] data-[side=right]:translate-y-1/2",
+ "data-[side=left]:translate-y-[calc(50%_-_3px)]",
+ arrowClasses
+ )}
+ {...props}
+ ></div>
+ {/snippet}
+ </TooltipPrimitive.Arrow>
+ </TooltipPrimitive.Content>
+</TooltipPrimitive.Portal>
diff --git a/src/lib/components/ui/tooltip/tooltip-trigger.svelte b/src/lib/components/ui/tooltip/tooltip-trigger.svelte
new file mode 100644
index 000000000..1acdaa47b
--- /dev/null
+++ b/src/lib/components/ui/tooltip/tooltip-trigger.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+ import { Tooltip as TooltipPrimitive } from "bits-ui";
+
+ let { ref = $bindable(null), ...restProps }: TooltipPrimitive.TriggerProps = $props();
+</script>
+
+<TooltipPrimitive.Trigger bind:ref data-slot="tooltip-trigger" {...restProps} />
diff --git a/src/lib/hooks/is-mobile.svelte.ts b/src/lib/hooks/is-mobile.svelte.ts
new file mode 100644
index 000000000..a34b2040f
--- /dev/null
+++ b/src/lib/hooks/is-mobile.svelte.ts
@@ -0,0 +1,9 @@
+import { MediaQuery } from "svelte/reactivity";
+
+const MOBILE_BREAKPOINT = 768;
+
+export class IsMobile extends MediaQuery {
+ constructor() {
+ super(`max-width: ${MOBILE_BREAKPOINT - 1}px`);
+ }
+}
diff --git a/src/lib/services/agent/agent-manager.ts b/src/lib/services/agent/agent-manager.ts
new file mode 100644
index 000000000..dc00558e0
--- /dev/null
+++ b/src/lib/services/agent/agent-manager.ts
@@ -0,0 +1,214 @@
+import fs from 'fs/promises';
+import path from 'node:path';
+import { BASE_PATH } from '$lib/services/paths-service';
+import type { Agent, AgentTask } from '$lib/types/agent.type';
+import { nanoid } from 'nanoid';
+import { updateDeploymentFromTask } from '$lib/services/deployment-service';
+
+const AGENTS_DIR = path.join(BASE_PATH, 'agents');
+const TASKS_DIR = path.join(BASE_PATH, 'agent-tasks');
+
+// Ensure directories exist
+await fs.mkdir(AGENTS_DIR, { recursive: true });
+await fs.mkdir(TASKS_DIR, { recursive: true });
+
+export async function registerAgent(agent: Agent): Promise<Agent> {
+ const existing = await getAgent(agent.id);
+
+ if (existing) {
+ // Update existing agent
+ return await updateAgent(agent.id, {
+ ...agent,
+ status: 'online',
+ lastSeen: new Date().toISOString(),
+ updatedAt: new Date().toISOString()
+ });
+ } else {
+ // Create new agent
+ const newAgent: Agent = {
+ ...agent,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString()
+ };
+
+ const filePath = path.join(AGENTS_DIR, `${agent.id}.json`);
+ await fs.writeFile(filePath, JSON.stringify(newAgent, null, 2));
+
+ return newAgent;
+ }
+}
+
+export async function getAgent(agentId: string): Promise<Agent | null> {
+ try {
+ const filePath = path.join(AGENTS_DIR, `${agentId}.json`);
+ const agentData = await fs.readFile(filePath, 'utf-8');
+ return JSON.parse(agentData);
+ } catch (error) {
+ return null;
+ }
+}
+
+export async function updateAgent(agentId: string, updates: Partial<Agent>): Promise<Agent> {
+ const existing = await getAgent(agentId);
+ if (!existing) {
+ throw new Error('Agent not found');
+ }
+
+ const updated: Agent = {
+ ...existing,
+ ...updates,
+ updatedAt: new Date().toISOString()
+ };
+
+ const filePath = path.join(AGENTS_DIR, `${agentId}.json`);
+ await fs.writeFile(filePath, JSON.stringify(updated, null, 2));
+
+ return updated;
+}
+
+export async function updateAgentHeartbeat(agentId: string): Promise<void> {
+ await updateAgent(agentId, {
+ status: 'online',
+ lastSeen: new Date().toISOString()
+ });
+}
+
+export async function listAgents(): Promise<Agent[]> {
+ try {
+ const files = await fs.readdir(AGENTS_DIR);
+ const agents: Agent[] = [];
+
+ for (const file of files) {
+ if (file.endsWith('.json')) {
+ const agentData = await fs.readFile(path.join(AGENTS_DIR, file), 'utf-8');
+ agents.push(JSON.parse(agentData));
+ }
+ }
+
+ return agents.sort((a, b) => new Date(b.lastSeen).getTime() - new Date(a.lastSeen).getTime());
+ } catch (error) {
+ console.error('Error listing agents:', error);
+ return [];
+ }
+}
+
+// Simplified task creation - no WebSocket sending needed
+export async function sendTaskToAgent(agentId: string, taskType: string, payload: any): Promise<AgentTask> {
+ const agent = await getAgent(agentId);
+ if (!agent) {
+ throw new Error(`Agent ${agentId} not found`);
+ }
+
+ if (agent.status !== 'online') {
+ throw new Error(`Agent ${agentId} is not online (status: ${agent.status})`);
+ }
+
+ // Create task
+ const task: AgentTask = {
+ id: nanoid(),
+ agentId,
+ type: taskType as any,
+ payload,
+ status: 'pending', // Agent will pick this up on next poll
+ createdAt: new Date().toISOString()
+ };
+
+ // Save task to file - agent will fetch this via HTTP
+ const filePath = path.join(TASKS_DIR, `${task.id}.json`);
+ await fs.writeFile(filePath, JSON.stringify(task, null, 2));
+
+ console.log(`πŸ“‹ Task ${task.id} created for agent ${agentId} (will be picked up on next poll)`);
+
+ return task;
+}
+
+export async function updateTaskStatus(taskId: string, status: string, result?: any, error?: string): Promise<void> {
+ try {
+ const filePath = path.join(TASKS_DIR, `${taskId}.json`);
+ const taskData = await fs.readFile(filePath, 'utf-8');
+ const task = JSON.parse(taskData);
+
+ task.status = status;
+ task.result = result;
+ task.error = error;
+ task.completedAt = status === 'completed' || status === 'failed' ? new Date().toISOString() : undefined;
+
+ await fs.writeFile(filePath, JSON.stringify(task, null, 2));
+
+ // Update corresponding deployment if it exists
+ await updateDeploymentFromTask(taskId, status, result, error);
+
+ console.log(`Task ${taskId} status updated to: ${status}`);
+ } catch (error) {
+ console.error('Error updating task status:', error);
+ }
+}
+
+export async function getTask(taskId: string): Promise<AgentTask | null> {
+ try {
+ const filePath = path.join(TASKS_DIR, `${taskId}.json`);
+ const taskData = await fs.readFile(filePath, 'utf-8');
+ return JSON.parse(taskData);
+ } catch (error) {
+ return null;
+ }
+}
+
+export async function listTasks(agentId?: string): Promise<AgentTask[]> {
+ try {
+ const files = await fs.readdir(TASKS_DIR);
+ const tasks: AgentTask[] = [];
+
+ for (const file of files) {
+ if (file.endsWith('.json')) {
+ const taskData = await fs.readFile(path.join(TASKS_DIR, file), 'utf-8');
+ const task = JSON.parse(taskData);
+
+ if (!agentId || task.agentId === agentId) {
+ tasks.push(task);
+ }
+ }
+ }
+
+ return tasks.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
+ } catch (error) {
+ console.error('Error listing tasks:', error);
+ return [];
+ }
+}
+
+// Add this function - it's an alias for listTasks to match the expected API
+export async function getAgentTasks(agentId: string): Promise<AgentTask[]> {
+ return listTasks(agentId);
+}
+
+// Helper functions remain the same
+export async function sendDockerCommand(agentId: string, command: string, args: string[] = []): Promise<AgentTask> {
+ return sendTaskToAgent(agentId, 'docker_command', {
+ command,
+ args
+ });
+}
+
+export async function deployStackToAgent(agentId: string, stackId: string, composeContent: string, envContent?: string): Promise<AgentTask> {
+ return sendTaskToAgent(agentId, 'stack_deploy', {
+ stackId,
+ composeContent,
+ envContent
+ });
+}
+
+export async function pullImageOnAgent(agentId: string, imageName: string): Promise<AgentTask> {
+ return sendTaskToAgent(agentId, 'image_pull', {
+ imageName
+ });
+}
+
+export async function processAgentMessage(agentId: string, message: any): Promise<void> {
+ console.log(`Processing message from agent ${agentId}:`, message);
+
+ if (message.type === 'task_result') {
+ const { task_id, status, result, error } = message.data;
+ await updateTaskStatus(task_id, status, result, error);
+ }
+}
diff --git a/src/lib/services/agent/agent-stack-service.ts b/src/lib/services/agent/agent-stack-service.ts
new file mode 100644
index 000000000..8462c453b
--- /dev/null
+++ b/src/lib/services/agent/agent-stack-service.ts
@@ -0,0 +1,121 @@
+import { sendTaskToAgent } from '$lib/services/agent/agent-manager';
+import type { Agent } from '$lib/types/agent.type';
+import type { Stack } from '$lib/types/docker/stack.type';
+
+export interface AgentStack extends Stack {
+ agentId: string;
+ agentHostname: string;
+ isRemote: true;
+}
+
+// Add this interface to handle server-side request context
+export interface ServerFetchContext {
+ fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
+}
+
+export async function getStacksFromAgent(agent: Agent, context?: ServerFetchContext): Promise<AgentStack[]> {
+ try {
+ // Send a task to get compose projects from the agent
+ const task = await sendTaskToAgent(agent.id, 'stack_list', {});
+
+ // Poll for task completion
+ const maxAttempts = 30; // 30 seconds timeout
+ const delay = 1000; // 1 second between polls
+
+ console.log(`Polling for stack data from agent ${agent.hostname} (task ${task.id})`);
+
+ for (let i = 0; i < maxAttempts; i++) {
+ await new Promise((resolve) => setTimeout(resolve, delay));
+
+ // Fetch the task status - use context.fetch if provided, otherwise use global fetch
+ const fetchFunc = context?.fetch || fetch;
+ const apiUrl = `/api/agents/${agent.id}/tasks/${task.id}`;
+
+ // Use absolute URL if needed (for server context)
+ const updatedTask = await fetchFunc(apiUrl, {
+ credentials: 'include'
+ }).then((res) => (res.ok ? res.json() : null));
+
+ if (!updatedTask || !updatedTask.task) {
+ console.log(`Polling attempt ${i + 1}: No task data received`);
+ continue;
+ }
+
+ const taskStatus = updatedTask.task.status;
+ console.log(`Polling attempt ${i + 1}: Task status is ${taskStatus}`);
+
+ if (taskStatus === 'completed' && updatedTask.task.result) {
+ console.log(`Task completed, processing stack data`);
+
+ // Parse the result
+ let stacksData;
+ try {
+ // Handle if the result is already parsed JSON or a string that needs parsing
+ if (typeof updatedTask.task.result === 'object') {
+ stacksData = updatedTask.task.result;
+ } else if (typeof updatedTask.task.result === 'string') {
+ stacksData = JSON.parse(updatedTask.task.result);
+ }
+
+ // Handle if the output is nested in a result.output field
+ if (!stacksData && updatedTask.task.result.output) {
+ if (typeof updatedTask.task.result.output === 'object') {
+ stacksData = updatedTask.task.result.output;
+ } else if (typeof updatedTask.task.result.output === 'string') {
+ stacksData = JSON.parse(updatedTask.task.result.output);
+ }
+ }
+ } catch (parseError) {
+ console.error(`Failed to parse stack data: ${parseError}`);
+ return [];
+ }
+
+ if (!stacksData || !stacksData.stacks || !Array.isArray(stacksData.stacks)) {
+ console.log(`No valid stacks data found in task result`);
+ return [];
+ }
+
+ // Convert agent stacks to AgentStack format
+ const stacks: AgentStack[] = stacksData.stacks.map((stack: Stack) => ({
+ ...stack,
+ agentId: agent.id,
+ agentHostname: agent.hostname,
+ isRemote: true,
+ // Ensure the important fields are always set
+ id: stack.id || `${agent.id}_${stack.name}`,
+ name: stack.name,
+ status: stack.status || 'unknown',
+ serviceCount: stack.serviceCount || stack.services?.length || 0
+ }));
+
+ console.log(`Retrieved ${stacks.length} stacks from agent ${agent.hostname}`);
+ return stacks;
+ } else if (taskStatus === 'failed') {
+ console.error(`Task failed: ${updatedTask.task.error || 'Unknown error'}`);
+ return [];
+ }
+ // Continue polling if task is still pending or running
+ }
+
+ console.error(`Polling timed out after ${maxAttempts} seconds`);
+ return [];
+ } catch (error) {
+ console.error(`Failed to get stacks from agent ${agent.hostname}:`, error);
+ return [];
+ }
+}
+
+export async function getAllAgentStacks(agents: Agent[], context?: ServerFetchContext): Promise<AgentStack[]> {
+ const agentStacks: AgentStack[] = [];
+
+ for (const agent of agents) {
+ try {
+ const stacks = await getStacksFromAgent(agent, context);
+ agentStacks.push(...stacks);
+ } catch (error) {
+ console.error(`Failed to get stacks from agent ${agent.hostname}:`, error);
+ }
+ }
+
+ return agentStacks;
+}
diff --git a/src/lib/services/api/agent-api-service.ts b/src/lib/services/api/agent-api-service.ts
new file mode 100644
index 000000000..5161cdbff
--- /dev/null
+++ b/src/lib/services/api/agent-api-service.ts
@@ -0,0 +1,8 @@
+import BaseAPIService from './api-service';
+
+export default class AgentAPIService extends BaseAPIService {
+ async get() {
+ const res = await this.api.get('/agents');
+ return res.data;
+ }
+}
diff --git a/src/lib/services/api/agent-stack-api-service.ts b/src/lib/services/api/agent-stack-api-service.ts
new file mode 100644
index 000000000..592c135f2
--- /dev/null
+++ b/src/lib/services/api/agent-stack-api-service.ts
@@ -0,0 +1,39 @@
+import BaseAPIService from './api-service';
+import type { AgentStack } from '$lib/services/agent/agent-stack-service';
+import type { Agent } from '$lib/types/agent.type';
+
+export default class AgentStackAPIService extends BaseAPIService {
+ /**
+ * Get all stacks from a specific agent
+ */
+ async getStacks(agentId: string): Promise<AgentStack[]> {
+ const res = await this.api.get(`/agents/${agentId}/stacks`);
+ return res.data.stacks || [];
+ }
+
+ /**
+ * Get stacks from all available agents
+ */
+ async getAllAgentStacks(agents: Agent[]): Promise<AgentStack[]> {
+ try {
+ const allStacks: AgentStack[] = [];
+
+ // Process agents sequentially to avoid overwhelming the server
+ for (const agent of agents) {
+ if (agent.status === 'online') {
+ try {
+ const stacks = await this.getStacks(agent.id);
+ allStacks.push(...stacks);
+ } catch (error) {
+ console.error(`Failed to get stacks from agent ${agent.hostname}:`, error);
+ }
+ }
+ }
+
+ return allStacks;
+ } catch (error) {
+ console.error('Failed to get stacks from agents:', error);
+ return [];
+ }
+ }
+}
diff --git a/src/lib/services/api/template-api-service.ts b/src/lib/services/api/template-api-service.ts
index f3b08eb87..dd0c047ca 100644
--- a/src/lib/services/api/template-api-service.ts
+++ b/src/lib/services/api/template-api-service.ts
@@ -1,6 +1,4 @@
import BaseAPIService from './api-service';
-import type { ComposeTemplate } from '$lib/services/template-service';
-import type { TemplateRegistryConfig } from '$lib/types/settings.type';
export default class TemplateAPIService extends BaseAPIService {
/**
diff --git a/src/lib/services/deployment-service.ts b/src/lib/services/deployment-service.ts
new file mode 100644
index 000000000..567e7d8ef
--- /dev/null
+++ b/src/lib/services/deployment-service.ts
@@ -0,0 +1,167 @@
+import fs from 'fs/promises';
+import path from 'node:path';
+import { BASE_PATH } from '$lib/services/paths-service';
+import type { Deployment } from '$lib/types/deployment.type';
+import { nanoid } from 'nanoid';
+
+const DEPLOYMENTS_DIR = path.join(BASE_PATH, 'deployments');
+
+// Ensure directory exists
+await fs.mkdir(DEPLOYMENTS_DIR, { recursive: true });
+
+export async function createDeployment(deployment: Omit<Deployment, 'id' | 'createdAt'>): Promise<Deployment> {
+ const newDeployment: Deployment = {
+ ...deployment,
+ id: nanoid(),
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString()
+ };
+
+ const filePath = path.join(DEPLOYMENTS_DIR, `${newDeployment.id}.json`);
+ await fs.writeFile(filePath, JSON.stringify(newDeployment, null, 2));
+
+ return newDeployment;
+}
+
+export async function updateDeployment(deploymentId: string, updates: Partial<Deployment>): Promise<Deployment | null> {
+ try {
+ const filePath = path.join(DEPLOYMENTS_DIR, `${deploymentId}.json`);
+ const deploymentData = await fs.readFile(filePath, 'utf-8');
+ const deployment = JSON.parse(deploymentData);
+
+ const updatedDeployment = {
+ ...deployment,
+ ...updates,
+ updatedAt: new Date().toISOString()
+ };
+
+ await fs.writeFile(filePath, JSON.stringify(updatedDeployment, null, 2));
+ return updatedDeployment;
+ } catch (error) {
+ console.error('Error updating deployment:', error);
+ return null;
+ }
+}
+
+export async function getDeployment(deploymentId: string): Promise<Deployment | null> {
+ try {
+ const filePath = path.join(DEPLOYMENTS_DIR, `${deploymentId}.json`);
+ const deploymentData = await fs.readFile(filePath, 'utf-8');
+ return JSON.parse(deploymentData);
+ } catch (error) {
+ return null;
+ }
+}
+
+export async function getDeployments(agentId?: string): Promise<Deployment[]> {
+ try {
+ const files = await fs.readdir(DEPLOYMENTS_DIR);
+ const deployments: Deployment[] = [];
+
+ for (const file of files) {
+ if (file.endsWith('.json')) {
+ const deploymentData = await fs.readFile(path.join(DEPLOYMENTS_DIR, file), 'utf-8');
+ const deployment = JSON.parse(deploymentData);
+
+ if (!agentId || deployment.agentId === agentId) {
+ deployments.push(deployment);
+ }
+ }
+ }
+
+ return deployments.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
+ } catch (error) {
+ console.error('Error listing deployments:', error);
+ return [];
+ }
+}
+
+export async function deleteDeployment(deploymentId: string): Promise<boolean> {
+ try {
+ const filePath = path.join(DEPLOYMENTS_DIR, `${deploymentId}.json`);
+ await fs.unlink(filePath);
+ return true;
+ } catch (error) {
+ console.error('Error deleting deployment:', error);
+ return false;
+ }
+}
+
+// Helper functions for creating specific deployment types
+export async function createStackDeployment(agentId: string, stackName: string, composeContent: string, envContent?: string, taskId?: string): Promise<Deployment> {
+ return createDeployment({
+ name: stackName,
+ type: 'stack',
+ status: 'pending',
+ agentId,
+ metadata: {
+ stackName,
+ composeContent,
+ envContent
+ },
+ taskId
+ });
+}
+
+export async function createContainerDeployment(agentId: string, containerName: string, imageName: string, ports?: string[], volumes?: string[], taskId?: string): Promise<Deployment> {
+ return createDeployment({
+ name: containerName || imageName,
+ type: 'container',
+ status: 'pending',
+ agentId,
+ metadata: {
+ containerName,
+ imageName,
+ ports,
+ volumes
+ },
+ taskId
+ });
+}
+
+export async function createImageDeployment(agentId: string, imageName: string, taskId?: string): Promise<Deployment> {
+ return createDeployment({
+ name: imageName,
+ type: 'image',
+ status: 'pending',
+ agentId,
+ metadata: {
+ imageName
+ },
+ taskId
+ });
+}
+
+// Update deployment status based on task completion
+export async function updateDeploymentFromTask(taskId: string, status: string, result?: any, error?: string): Promise<void> {
+ try {
+ // Find deployment by taskId
+ const deployments = await getDeployments();
+ const deployment = deployments.find((d) => d.taskId === taskId);
+
+ if (deployment) {
+ let deploymentStatus: Deployment['status'];
+
+ switch (status) {
+ case 'completed':
+ deploymentStatus = 'completed';
+ break;
+ case 'failed':
+ deploymentStatus = 'failed';
+ break;
+ case 'running':
+ deploymentStatus = 'running';
+ break;
+ default:
+ deploymentStatus = 'pending';
+ }
+
+ await updateDeployment(deployment.id, {
+ status: deploymentStatus,
+ error: status === 'failed' ? error : undefined
+ });
+ }
+ } catch (err) {
+ console.error('Error updating deployment from task:', err);
+ }
+}
diff --git a/src/lib/types/agent.type.ts b/src/lib/types/agent.type.ts
new file mode 100644
index 000000000..dbd7fcc71
--- /dev/null
+++ b/src/lib/types/agent.type.ts
@@ -0,0 +1,65 @@
+export interface AgentMetrics {
+ containerCount?: number;
+ imageCount?: number;
+ stackCount?: number;
+ networkCount?: number;
+ volumeCount?: number;
+}
+
+export interface Agent {
+ id: string;
+ hostname: string;
+ platform: string;
+ version: string;
+ capabilities: string[];
+ status: 'online' | 'offline';
+ lastSeen: string;
+ registeredAt: string;
+ metrics?: AgentMetrics;
+ dockerInfo?: {
+ version: string;
+ containers: number;
+ images: number;
+ };
+ metadata?: Record<string, any>;
+ createdAt: string;
+ updatedAt?: string;
+}
+
+export interface AgentTask {
+ id: string;
+ agentId: string;
+ type: 'docker_command' | 'stack_deploy' | 'image_pull' | 'health_check' | 'container_start' | 'container_stop' | 'container_restart' | 'container_remove' | 'agent_upgrade';
+ payload: Record<string, any>;
+ status: 'pending' | 'running' | 'completed' | 'failed';
+ result?: any;
+ error?: string;
+ createdAt: string;
+ updatedAt?: string;
+}
+
+// Specific payload types for different task types
+export interface DockerCommandPayload {
+ command: string;
+ args: string[];
+}
+
+export interface StackDeployPayload {
+ stackId: string;
+ composeContent: string;
+ envContent?: string;
+}
+
+export interface ImagePullPayload {
+ imageName: string;
+}
+
+export interface ContainerActionPayload {
+ containerId: string;
+ force?: boolean;
+}
+
+export interface AgentUpgradePayload {
+ action: 'upgrade';
+ version?: string;
+}
diff --git a/src/lib/types/deployment.type.ts b/src/lib/types/deployment.type.ts
new file mode 100644
index 000000000..ea38b7db3
--- /dev/null
+++ b/src/lib/types/deployment.type.ts
@@ -0,0 +1,28 @@
+export interface Deployment {
+ id: string;
+ name: string;
+ type: 'stack' | 'container' | 'image';
+ status: 'pending' | 'running' | 'stopped' | 'failed' | 'completed';
+ agentId: string;
+ createdAt: string;
+ updatedAt?: string;
+ metadata?: {
+ stackName?: string;
+ imageName?: string;
+ containerName?: string;
+ composeContent?: string;
+ envContent?: string;
+ ports?: string[];
+ volumes?: string[];
+ };
+ taskId?: string;
+ error?: string;
+}
+
+export interface DeploymentTask {
+ deploymentId: string;
+ taskId: string;
+ status: 'pending' | 'running' | 'completed' | 'failed';
+ result?: any;
+ error?: string;
+}
diff --git a/src/lib/types/docker/stack.type.ts b/src/lib/types/docker/stack.type.ts
index a996141dc..04c426541 100644
--- a/src/lib/types/docker/stack.type.ts
+++ b/src/lib/types/docker/stack.type.ts
@@ -51,6 +51,9 @@ export interface Stack {
composeContent?: string;
envContent?: string;
isLegacy?: boolean;
+ agentId?: string;
+ agentHostname?: string;
+ isRemote?: boolean;
}
export interface StackUpdate {
diff --git a/src/lib/utils/agent-status.utils.ts b/src/lib/utils/agent-status.utils.ts
new file mode 100644
index 000000000..93d91772e
--- /dev/null
+++ b/src/lib/utils/agent-status.utils.ts
@@ -0,0 +1,34 @@
+import type { Agent } from '$lib/types/agent.type';
+
+const AGENT_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
+
+export function isAgentOffline(agent: Agent): boolean {
+ if (!agent.lastSeen) return true;
+
+ const now = new Date();
+ const lastSeen = new Date(agent.lastSeen);
+ const timeSinceLastSeen = now.getTime() - lastSeen.getTime();
+
+ return timeSinceLastSeen > AGENT_TIMEOUT_MS;
+}
+
+export function getActualAgentStatus(agent: Agent): 'online' | 'offline' {
+ return isAgentOffline(agent) ? 'offline' : agent.status;
+}
+
+export function getAgentStatusClasses(agent: Agent): string {
+ const actualStatus = getActualAgentStatus(agent);
+ if (actualStatus === 'online') {
+ return 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400';
+ }
+ return 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400';
+}
+
+export function getAgentStatusText(agent: Agent): string {
+ const actualStatus = getActualAgentStatus(agent);
+ return actualStatus === 'online' ? 'Online' : 'Offline';
+}
+
+export function canSendCommandsToAgent(agent: Agent): boolean {
+ return getActualAgentStatus(agent) === 'online';
+}
diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts
index 6df42d8bc..b7a8bbaa6 100644
--- a/src/routes/+layout.server.ts
+++ b/src/routes/+layout.server.ts
@@ -3,6 +3,8 @@ import { env } from '$env/dynamic/private';
import AppConfigService from '$lib/services/app-config-service';
import type { AppVersionInformation } from '$lib/types/application-configuration';
import type { LayoutServerLoad } from './$types';
+import { listAgents } from '$lib/services/agent/agent-manager';
+import { testDockerConnection } from '$lib/services/docker/core';
let versionInformation: AppVersionInformation;
let versionInformationLastUpdated: number;
@@ -21,6 +23,31 @@ export const load = (async (locals) => {
};
}
+ const agents = await listAgents();
+
+ // Calculate actual status on server side
+ const now = new Date();
+ const timeout = 5 * 60 * 1000; // 5 minutes
+
+ const agentsWithStatus = agents.map((agent) => {
+ const lastSeen = new Date(agent.lastSeen);
+ const timeSinceLastSeen = now.getTime() - lastSeen.getTime();
+
+ return {
+ ...agent,
+ status: timeSinceLastSeen > timeout ? 'offline' : agent.status
+ };
+ });
+
+ // Check if local Docker is available
+ let hasLocalDocker = false;
+ try {
+ hasLocalDocker = await testDockerConnection();
+ } catch (error) {
+ console.log('Local Docker not available:', error);
+ hasLocalDocker = false;
+ }
+
const appConfigService = new AppConfigService();
// Cache the version information for 3 hours
@@ -39,6 +66,8 @@ export const load = (async (locals) => {
return {
versionInformation,
user: locals.locals.user || null,
- csrf
+ csrf,
+ agents: agentsWithStatus,
+ hasLocalDocker
};
}) satisfies LayoutServerLoad;
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index e5ef6584b..5acd8f08a 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -1,15 +1,17 @@
<script lang="ts">
import '../app.css';
import { ModeWatcher } from 'mode-watcher';
- import Nav from '$lib/components/sidebar.svelte';
import { Toaster } from '$lib/components/ui/sonner/index.js';
import { navigating, page } from '$app/state';
import ConfirmDialog from '$lib/components/confirm-dialog/confirm-dialog.svelte';
+ import * as Sidebar from '$lib/components/ui/sidebar/index.js';
+ import AppSidebar from '$lib/components/sidebar/sidebar.svelte';
let { children, data } = $props();
const versionInformation = data.versionInformation;
const user = $derived(data.user);
+ const agents = $derived(data.agents);
const isNavigating = $derived(navigating.type !== null);
const isAuthenticated = $derived(!!user);
@@ -32,14 +34,18 @@
{/if}
<div class="flex min-h-screen bg-background">
- <!-- Only show sidebar when authenticated -->
{#if showSidebar}
- <Nav {versionInformation} {user} />
- {/if}
-
- <main class="flex-1">
- <section class="p-6">
+ <Sidebar.Provider>
+ <AppSidebar hasLocalDocker={data.hasLocalDocker || false} agents={agents || []} {versionInformation} {user} />
+ <main class="flex-1">
+ <section class="p-6">
+ {@render children()}
+ </section>
+ </main>
+ </Sidebar.Provider>
+ {:else}
+ <main class="flex-1">
{@render children()}
- </section>
- </main>
+ </main>
+ {/if}
</div>
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index 968ae96a2..41093601e 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -308,46 +308,44 @@
<section>
<h2 class="text-lg font-semibold tracking-tight mb-4">Quick Actions</h2>
<div class="grid grid-cols-1 sm:grid-cols-3 gap-5">
- <button class="group relative flex flex-col items-center p-5 rounded-xl border bg-card shadow-sm hover:shadow-md transition-all disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:shadow-sm" disabled={!dashboardStates.dockerInfo || stoppedContainers === 0 || isLoading.starting || isLoading.stopping || isLoading.pruning} onclick={handleStartAll}>
- <div class="size-10 rounded-full flex items-center justify-center mb-3 bg-green-500/10 group-hover:bg-green-500/20 transition-colors">
+ <button class="group relative flex flex-col items-center p-6 rounded-xl border bg-card shadow-sm hover:shadow-md transition-all disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:shadow-sm" disabled={!dashboardStates.dockerInfo || stoppedContainers === 0 || isLoading.starting || isLoading.stopping || isLoading.pruning} onclick={handleStartAll}>
+ <div class="size-12 rounded-full flex items-center justify-center mb-4 bg-green-500/10 group-hover:bg-green-500/20 transition-colors">
{#if isLoading.starting}
- <Loader2 class="text-green-500 animate-spin size-5" />
+ <Loader2 class="text-green-500 animate-spin size-6" />
{:else}
- <PlayCircle class="text-green-500 size-5" />
+ <PlayCircle class="text-green-500 size-6" />
{/if}
</div>
- <span class="text-base font-medium mb-2">Start All Stopped</span>
- <StatusBadge variant="sky" text={stoppedContainers.toString()} class="mb-3" />
- <p class="text-xs text-muted-foreground">Start all stopped containers</p>
+ <span class="text-base font-medium text-center">Start All Stopped</span>
+ <span class="text-sm text-muted-foreground mt-1">{stoppedContainers} containers</span>
</button>
- <button class="group relative flex flex-col items-center p-5 rounded-xl border bg-card shadow-sm hover:shadow-md transition-all disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:shadow-sm" disabled={!dashboardStates.dockerInfo || runningContainers === 0 || isLoading.starting || isLoading.stopping || isLoading.pruning} onclick={handleStopAll}>
- <div class="size-10 rounded-full flex items-center justify-center mb-3 bg-blue-500/10 group-hover:bg-blue-500/20 transition-colors">
+ <button class="group relative flex flex-col items-center p-6 rounded-xl border bg-card shadow-sm hover:shadow-md transition-all disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:shadow-sm" disabled={!dashboardStates.dockerInfo || runningContainers === 0 || isLoading.starting || isLoading.stopping || isLoading.pruning} onclick={handleStopAll}>
+ <div class="size-12 rounded-full flex items-center justify-center mb-4 bg-blue-500/10 group-hover:bg-blue-500/20 transition-colors">
{#if isLoading.stopping}
- <Loader2 class="text-blue-500 animate-spin size-5" />
+ <Loader2 class="text-blue-500 animate-spin size-6" />
{:else}
- <StopCircle class="text-blue-500 size-5" />
+ <StopCircle class="text-blue-500 size-6" />
{/if}
</div>
- <span class="text-base font-medium mb-2">Stop All Running</span>
- <StatusBadge variant="sky" text={runningContainers.toString()} class="mb-3" />
- <p class="text-xs text-muted-foreground">Stop all running containers</p>
+ <span class="text-base font-medium text-center">Stop All Running</span>
+ <span class="text-sm text-muted-foreground mt-1">{runningContainers} containers</span>
</button>
<button
- class="group relative flex flex-col items-center p-5 rounded-xl border bg-card shadow-sm hover:shadow-md hover:border-destructive/50 transition-all disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:shadow-sm disabled:hover:border-border"
+ class="group relative flex flex-col items-center p-6 rounded-xl border bg-card shadow-sm hover:shadow-md hover:border-destructive/50 transition-all disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:shadow-sm disabled:hover:border-border"
disabled={!dashboardStates.dockerInfo || isLoading.starting || isLoading.stopping || isLoading.pruning}
onclick={() => (dashboardStates.isPruneDialogOpen = true)}
>
- <div class="size-10 rounded-full flex items-center justify-center mb-3 bg-red-500/10 group-hover:bg-red-500/20 transition-colors">
+ <div class="size-12 rounded-full flex items-center justify-center mb-4 bg-red-500/10 group-hover:bg-red-500/20 transition-colors">
{#if isLoading.pruning}
- <Loader2 class="text-red-500 animate-spin size-5" />
+ <Loader2 class="text-red-500 animate-spin size-6" />
{:else}
- <Trash2 class="text-red-500 size-5" />
+ <Trash2 class="text-red-500 size-6" />
{/if}
</div>
- <span class="text-base font-medium mb-2">Prune System</span>
- <p class="text-xs text-muted-foreground">Remove unused data</p>
+ <span class="text-base font-medium text-center">Prune System</span>
+ <span class="text-sm text-muted-foreground mt-1">Clean unused resources</span>
</button>
</div>
</section>
diff --git a/src/routes/agents/+page.server.ts b/src/routes/agents/+page.server.ts
new file mode 100644
index 000000000..3830fc09a
--- /dev/null
+++ b/src/routes/agents/+page.server.ts
@@ -0,0 +1,40 @@
+import type { PageServerLoad } from './$types';
+import { listAgents } from '$lib/services/agent/agent-manager';
+import { error } from '@sveltejs/kit';
+
+export const load: PageServerLoad = async ({ locals }) => {
+ // Check if user has admin role
+ if (!locals.user?.roles.includes('admin')) {
+ throw error(403, {
+ message: 'Unauthorized access'
+ });
+ }
+
+ try {
+ // Load agents with actual status calculation
+ const agents = await listAgents();
+
+ // Calculate actual status on server side
+ const now = new Date();
+ const timeout = 5 * 60 * 1000; // 5 minutes
+
+ const agentsWithStatus = agents.map((agent) => {
+ const lastSeen = new Date(agent.lastSeen);
+ const timeSinceLastSeen = now.getTime() - lastSeen.getTime();
+
+ return {
+ ...agent,
+ status: timeSinceLastSeen > timeout ? 'offline' : agent.status
+ };
+ });
+
+ return {
+ agents: agentsWithStatus
+ };
+ } catch (err) {
+ console.error('SSR: Failed to load agents:', err);
+ throw error(500, {
+ message: err instanceof Error ? err.message : 'Failed to load agents'
+ });
+ }
+};
diff --git a/src/routes/agents/+page.svelte b/src/routes/agents/+page.svelte
new file mode 100644
index 000000000..da315e236
--- /dev/null
+++ b/src/routes/agents/+page.svelte
@@ -0,0 +1,254 @@
+<script lang="ts">
+ import { onMount } from 'svelte';
+ import { goto } from '$app/navigation';
+ import type { Agent } from '$lib/types/agent.type';
+ import { formatDistanceToNow } from 'date-fns';
+ import { RefreshCw, AlertCircle, Loader2, Monitor, CheckCircle, Eye, Send, Container, HardDrive, Layers } from '@lucide/svelte';
+ import type { PageData } from './$types';
+ import { getActualAgentStatus } from '$lib/utils/agent-status.utils';
+
+ let { data } = $props();
+
+ // Initialize from SSR data
+ let agents: Agent[] = $state(data.agents || []);
+ let loading = $state(false);
+ let error = $state('');
+
+ onMount(() => {
+ // Refresh every 30 seconds for real-time updates (less frequent since we have SSR)
+ const interval = setInterval(refreshAgents, 30000);
+ return () => clearInterval(interval);
+ });
+
+ // Simplified refresh function - only for periodic updates
+ async function refreshAgents() {
+ if (loading) return;
+
+ try {
+ loading = true;
+ const response = await fetch('/api/agents');
+
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
+
+ const responseData = await response.json();
+ agents = responseData.agents || [];
+ error = '';
+ } catch (err) {
+ console.error('Failed to refresh agents:', err);
+ // Don't show error for background refresh failures
+ } finally {
+ loading = false;
+ }
+ }
+
+ // Manual refresh triggered by user
+ async function loadAgents() {
+ try {
+ loading = true;
+ error = '';
+
+ const response = await fetch('/api/agents');
+
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
+
+ const responseData = await response.json();
+ agents = responseData.agents || [];
+ } catch (err) {
+ console.error('Failed to load agents:', err);
+ error = err instanceof Error ? err.message : 'Unknown error';
+ } finally {
+ loading = false;
+ }
+ }
+
+ function getStatusColor(agent: Agent) {
+ const actualStatus = getActualAgentStatus(agent);
+ if (actualStatus === 'online') return 'bg-green-500';
+ return 'bg-red-500';
+ }
+
+ function getStatusText(agent: Agent) {
+ const actualStatus = getActualAgentStatus(agent);
+ if (actualStatus === 'online') return 'Online';
+ return 'Offline';
+ }
+
+ function viewAgentDetails(agentId: string) {
+ goto(`/agents/${agentId}`);
+ }
+</script>
+
+<div class="container mx-auto px-6 py-8">
+ <!-- Header -->
+ <div class="flex justify-between items-center mb-8">
+ <div>
+ <h1 class="text-3xl font-bold text-gray-900 dark:text-white">Agent Management</h1>
+ <p class="text-gray-600 dark:text-gray-400 mt-1">Manage and monitor your remote agents</p>
+ </div>
+ <button onclick={loadAgents} class="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed" disabled={loading}>
+ {#if loading}
+ <Loader2 class="h-4 w-4 animate-spin" />
+ {:else}
+ <RefreshCw class="h-4 w-4" />
+ {/if}
+ {loading ? 'Loading...' : 'Refresh'}
+ </button>
+ </div>
+
+ <!-- Error Message -->
+ {#if error}
+ <div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-400 px-4 py-3 rounded-lg mb-6">
+ <div class="flex items-center gap-2">
+ <AlertCircle class="h-5 w-5" />
+ <strong>Error:</strong>
+ {error}
+ </div>
+ </div>
+ {/if}
+
+ <!-- Agents content - data is immediately available from SSR -->
+ {#if agents.length === 0}
+ <!-- Empty State -->
+ <div class="text-center py-16">
+ <Monitor class="h-16 w-16 text-gray-400 mx-auto mb-4" />
+ <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-2">No agents registered</h3>
+ <p class="text-gray-600 dark:text-gray-400 mb-4">Get started by connecting your first agent</p>
+ <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 max-w-md mx-auto">
+ <p class="text-sm text-gray-600 dark:text-gray-400">Make sure your Go agent is running and connecting to:</p>
+ <code class="text-sm font-mono bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 px-2 py-1 rounded mt-2 inline-block"> http://localhost:3000/agent/register </code>
+ </div>
+ </div>
+ {:else}
+ <!-- Agents Grid -->
+ <div class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
+ {#each agents as agent}
+ <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 hover:shadow-lg transition-shadow">
+ <!-- Agent Header -->
+ <div class="flex items-start justify-between mb-4">
+ <div class="flex items-center gap-3">
+ <div class="relative">
+ <div class="w-12 h-12 bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center">
+ <Monitor class="h-6 w-6 text-gray-600 dark:text-gray-400" />
+ </div>
+ <div class="absolute -top-1 -right-1 w-4 h-4 {getStatusColor(agent)} rounded-full border-2 border-white dark:border-gray-800"></div>
+ </div>
+ <div>
+ <h3 class="font-semibold text-gray-900 dark:text-white">{agent.hostname}</h3>
+ <p class="text-xs text-gray-500 dark:text-gray-400 font-mono">{agent.id}</p>
+ </div>
+ </div>
+ <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {getActualAgentStatus(agent) === 'online' ? 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400' : 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400'}">
+ {getStatusText(agent)}
+ </span>
+ </div>
+
+ <!-- Agent Details -->
+ <div class="space-y-3">
+ <div class="grid grid-cols-2 gap-4 text-sm">
+ <div>
+ <span class="text-gray-500 dark:text-gray-400">Platform</span>
+ <p class="font-medium text-gray-900 dark:text-white capitalize">{agent.platform}</p>
+ </div>
+ <div>
+ <span class="text-gray-500 dark:text-gray-400">Version</span>
+ <p class="font-medium text-gray-900 dark:text-white">{agent.version}</p>
+ </div>
+ </div>
+
+ <!-- Resource Metrics -->
+ {#if agent.metrics}
+ <div class="grid grid-cols-3 gap-2 py-3 border-t border-gray-100 dark:border-gray-700">
+ <div class="text-center">
+ <div class="flex items-center justify-center gap-1 mb-1">
+ <Container class="h-3 w-3 text-blue-600 dark:text-blue-400" />
+ <span class="text-xs text-gray-500 dark:text-gray-400">Containers</span>
+ </div>
+ <p class="text-sm font-semibold text-gray-900 dark:text-white">
+ {agent.metrics.containerCount ?? 0}
+ </p>
+ </div>
+ <div class="text-center">
+ <div class="flex items-center justify-center gap-1 mb-1">
+ <HardDrive class="h-3 w-3 text-green-600 dark:text-green-400" />
+ <span class="text-xs text-gray-500 dark:text-gray-400">Images</span>
+ </div>
+ <p class="text-sm font-semibold text-gray-900 dark:text-white">
+ {agent.metrics.imageCount ?? 0}
+ </p>
+ </div>
+ <div class="text-center">
+ <div class="flex items-center justify-center gap-1 mb-1">
+ <Layers class="h-3 w-3 text-purple-600 dark:text-purple-400" />
+ <span class="text-xs text-gray-500 dark:text-gray-400">Stacks</span>
+ </div>
+ <p class="text-sm font-semibold text-gray-900 dark:text-white">
+ {agent.metrics.stackCount ?? 0}
+ </p>
+ </div>
+ </div>
+ {:else}
+ <div class="py-3 border-t border-gray-100 dark:border-gray-700">
+ <p class="text-xs text-gray-400 text-center">No metrics data available</p>
+ </div>
+ {/if}
+
+ <div>
+ <span class="text-gray-500 dark:text-gray-400 text-sm">Capabilities</span>
+ <div class="flex flex-wrap gap-1 mt-1">
+ {#each agent.capabilities as capability}
+ <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
+ {capability}
+ </span>
+ {:else}
+ <span class="text-gray-400 dark:text-gray-500 text-sm">None</span>
+ {/each}
+ </div>
+ </div>
+
+ <div class="pt-3 border-t border-gray-100 dark:border-gray-700">
+ <p class="text-xs text-gray-500 dark:text-gray-400">
+ Last seen: {formatDistanceToNow(new Date(agent.lastSeen))} ago
+ </p>
+ </div>
+ </div>
+
+ <!-- Connected Status -->
+ {#if getActualAgentStatus(agent) === 'online'}
+ <div class="mt-4 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg border border-green-200 dark:border-green-800">
+ <div class="flex items-center gap-2">
+ <CheckCircle class="h-4 w-4 text-green-600 dark:text-green-400" />
+ <p class="text-sm font-medium text-green-700 dark:text-green-400">Ready to receive commands</p>
+ </div>
+ </div>
+ {/if}
+
+ <!-- Action Buttons -->
+ <div class="mt-4 flex gap-2">
+ <button onclick={() => viewAgentDetails(agent.id)} class="flex-1 px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors flex items-center justify-center gap-2">
+ <Eye class="h-4 w-4" />
+ View Details
+ </button>
+ {#if getActualAgentStatus(agent) === 'online'}
+ <button onclick={() => viewAgentDetails(agent.id)} class="flex-1 px-3 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors flex items-center justify-center gap-2">
+ <Send class="h-4 w-4" />
+ Manage
+ </button>
+ {/if}
+ </div>
+ </div>
+ {/each}
+ </div>
+ {/if}
+
+ <!-- Show subtle loading indicator during background refresh -->
+ {#if loading && agents.length > 0}
+ <div class="fixed bottom-4 right-4 bg-blue-600 text-white px-3 py-2 rounded-lg shadow-lg flex items-center gap-2">
+ <Loader2 class="h-4 w-4 animate-spin" />
+ <span class="text-sm">Refreshing...</span>
+ </div>
+ {/if}
+</div>
diff --git a/src/routes/agents/[agentId]/+page.server.ts b/src/routes/agents/[agentId]/+page.server.ts
new file mode 100644
index 000000000..c0515002c
--- /dev/null
+++ b/src/routes/agents/[agentId]/+page.server.ts
@@ -0,0 +1,43 @@
+import type { PageServerLoad } from './$types';
+import { getAgent, getAgentTasks } from '$lib/services/agent/agent-manager';
+import { getDeployments } from '$lib/services/deployment-service';
+import { error } from '@sveltejs/kit';
+
+export const load: PageServerLoad = async ({ params }) => {
+ const { agentId } = params;
+
+ try {
+ // Load all data in parallel
+ const [agent, tasks, deployments] = await Promise.allSettled([getAgent(agentId), getAgentTasks(agentId), getDeployments(agentId)]);
+
+ // Handle agent not found
+ if (agent.status === 'rejected' || !agent.value) {
+ throw error(404, {
+ message: 'Agent not found'
+ });
+ }
+
+ // Calculate actual status (move this logic to server)
+ const now = new Date();
+ const timeout = 5 * 60 * 1000; // 5 minutes
+ const lastSeen = new Date(agent.value.lastSeen);
+ const timeSinceLastSeen = now.getTime() - lastSeen.getTime();
+
+ const agentWithStatus = {
+ ...agent.value,
+ status: timeSinceLastSeen > timeout ? 'offline' : agent.value.status
+ };
+
+ return {
+ agent: agentWithStatus,
+ tasks: tasks.status === 'fulfilled' ? tasks.value : [],
+ deployments: deployments.status === 'fulfilled' ? deployments.value : [],
+ agentId
+ };
+ } catch (err) {
+ console.error('SSR: Failed to load agent data:', err);
+ throw error(500, {
+ message: err instanceof Error ? err.message : 'Failed to load agent data'
+ });
+ }
+};
diff --git a/src/routes/agents/[agentId]/+page.svelte b/src/routes/agents/[agentId]/+page.svelte
new file mode 100644
index 000000000..020887d37
--- /dev/null
+++ b/src/routes/agents/[agentId]/+page.svelte
@@ -0,0 +1,1134 @@
+<script lang="ts">
+ import { onMount } from 'svelte';
+ import { goto } from '$app/navigation';
+ import { formatDistanceToNow } from 'date-fns';
+ import { toast } from 'svelte-sonner';
+ import type { Agent, AgentTask } from '$lib/types/agent.type';
+ import type { Deployment } from '$lib/types/deployment.type';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
+ import * as Alert from '$lib/components/ui/alert/index.js';
+ import * as Dialog from '$lib/components/ui/dialog/index.js';
+ import * as Select from '$lib/components/ui/select/index.js';
+ import * as Tabs from '$lib/components/ui/tabs/index.js';
+ import DropdownCard from '$lib/components/dropdown-card.svelte';
+ import UniversalTable from '$lib/components/universal-table.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { Input } from '$lib/components/ui/input/index.js';
+ import { Label } from '$lib/components/ui/label/index.js';
+ import { Monitor, Terminal, Clock, Settings, Activity, AlertCircle, Server, RefreshCw, Play, ArrowLeft, Container, HardDrive, Layers, Network, Database, Loader2, Download } from '@lucide/svelte';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import ImagePullForm from '$lib/components/forms/ImagePullForm.svelte';
+ import StackDeploymentForm from '$lib/components/forms/StackDeploymentForm.svelte';
+ import QuickContainerForm from '$lib/components/forms/QuickContainerForm.svelte';
+ import { getActualAgentStatus } from '$lib/utils/agent-status.utils';
+
+ let { data } = $props();
+
+ // Initialize from SSR data
+ let agent: Agent | null = $state(data.agent);
+ let tasks: AgentTask[] = $state(data.tasks);
+ let deployments: Deployment[] = $state(data.deployments);
+ let agentId = data.agentId;
+
+ // Remove most of the initial loading states since data comes from SSR
+ let loading = $state(false);
+ let error = $state('');
+
+ // Resource data states
+ let resourcesLoading = $state(false);
+ let resourcesError = $state('');
+ let resourcesData = $state<{
+ containers: any[];
+ images: any[];
+ networks: any[];
+ volumes: any[];
+ stacks: any[];
+ }>({
+ containers: [],
+ images: [],
+ networks: [],
+ volumes: [],
+ stacks: []
+ });
+
+ // Command form state
+ let selectedCommand = $state<{ value: string; label: string } | undefined>(undefined);
+ let commandArgs = $state('');
+ let customCommand = $state('');
+
+ // Add missing state variables
+ let commandDialogOpen = $state(false);
+ let taskExecuting = $state(false);
+
+ // Deployment states with proper typing
+ let deployDialogOpen = $state(false);
+ let imageDialogOpen = $state(false);
+ let containerDialogOpen = $state(false);
+ let deploying = $state(false);
+
+ // Predefined commands
+ const predefinedCommands = [
+ { value: 'docker_version', label: 'Docker Version' },
+ { value: 'docker_info', label: 'Docker System Info' },
+ { value: 'docker_ps', label: 'List Containers' },
+ { value: 'docker_images', label: 'List Images' },
+ { value: 'system_info', label: 'System Information' },
+ { value: 'agent_upgrade', label: 'Upgrade Agent' },
+ { value: 'docker_prune', label: 'Docker Cleanup' },
+ { value: 'custom', label: 'Custom Command' }
+ ];
+
+ // Keep only periodic refresh logic
+ onMount(() => {
+ // Refresh every 10 seconds for real-time updates
+ const interval = setInterval(() => {
+ refreshAgentData();
+ }, 10000);
+ return () => clearInterval(interval);
+ });
+
+ // Simplified refresh function - only for periodic updates
+ async function refreshAgentData() {
+ if (loading) return;
+
+ try {
+ loading = true;
+
+ // Use parallel requests for updates
+ const [agentResponse, tasksResponse, deploymentsResponse] = await Promise.allSettled([fetch(`/api/agents/${agentId}`), fetch(`/api/agents/${agentId}/tasks?admin=true`), fetch(`/api/agents/${agentId}/deployments`)]);
+
+ // Update agent data
+ if (agentResponse.status === 'fulfilled' && agentResponse.value.ok) {
+ const agentData = await agentResponse.value.json();
+ agent = agentData.agent;
+ }
+
+ // Update tasks
+ if (tasksResponse.status === 'fulfilled' && tasksResponse.value.ok) {
+ const tasksData = await tasksResponse.value.json();
+ tasks = tasksData.tasks || [];
+ }
+
+ // Update deployments
+ if (deploymentsResponse.status === 'fulfilled' && deploymentsResponse.value.ok) {
+ const deploymentsData = await deploymentsResponse.value.json();
+ deployments = deploymentsData.deployments || [];
+ }
+
+ error = '';
+ } catch (err) {
+ console.error('Failed to refresh agent data:', err);
+ // Don't set error for refresh failures - keep showing existing data
+ } finally {
+ loading = false;
+ }
+ }
+
+ async function loadResourcesData() {
+ if (!agent || getActualAgentStatus(agent) !== 'online') {
+ resourcesError = 'Agent must be online to load resource data';
+ return;
+ }
+
+ resourcesLoading = true;
+ resourcesError = '';
+
+ try {
+ const commands = [
+ { type: 'docker_command', payload: { command: 'ps', args: ['-a', '--format', 'json'] } },
+ { type: 'docker_command', payload: { command: 'images', args: ['--format', 'json'] } },
+ { type: 'docker_command', payload: { command: 'network', args: ['ls', '--format', 'json'] } },
+ { type: 'docker_command', payload: { command: 'volume', args: ['ls', '--format', 'json'] } },
+ { type: 'docker_command', payload: { command: 'compose', args: ['ls', '--format', 'json'] } }
+ ];
+
+ const results = await Promise.allSettled(
+ commands.map(async (cmd, index) => {
+ const response = await fetch(`/api/agents/${agentId}/tasks`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(cmd)
+ });
+
+ if (!response.ok) throw new Error(`Failed to execute ${cmd.payload.command}`);
+ const result = await response.json();
+
+ console.log('Task creation response:', result);
+
+ // The task ID should be in result.task.id based on the API endpoint
+ if (!result.task?.id) {
+ throw new Error(`No task ID returned for ${cmd.payload.command}`);
+ }
+
+ const taskId = result.task.id;
+ return pollTaskCompletion(taskId, ['containers', 'images', 'networks', 'volumes', 'composes'][index]);
+ })
+ );
+
+ // Process results
+ results.forEach((result, index) => {
+ if (result.status === 'fulfilled' && result.value) {
+ const resourceType = ['containers', 'images', 'networks', 'volumes', 'stacks'][index] as keyof typeof resourcesData;
+ resourcesData[resourceType] = result.value;
+ }
+ });
+ } catch (err) {
+ console.error('Failed to load resources data:', err);
+ resourcesError = err instanceof Error ? err.message : 'Failed to load resource data';
+ toast.error('Failed to load resource data');
+ } finally {
+ resourcesLoading = false;
+ }
+ }
+
+ async function pollTaskCompletion(taskId: string, resourceType: string): Promise<any[]> {
+ const maxAttempts = 30; // 30 seconds max
+ const delay = 1000; // 1 second
+
+ console.log(`Polling task ${taskId} for ${resourceType}`);
+
+ for (let i = 0; i < maxAttempts; i++) {
+ await new Promise((resolve) => setTimeout(resolve, delay));
+
+ try {
+ const response = await fetch(`/api/agents/${agentId}/tasks/${taskId}`, {
+ credentials: 'include'
+ });
+
+ console.log(`Task ${taskId} polling attempt ${i + 1}: ${response.status}`);
+
+ if (!response.ok) {
+ if (response.status === 403) {
+ console.error(`Authentication failed for task ${taskId}`);
+ }
+ console.error(`Failed to fetch task ${taskId}: ${response.status} ${response.statusText}`);
+ continue;
+ }
+
+ const responseData = await response.json();
+ console.log(`Task ${taskId} response:`, responseData);
+
+ const task = responseData.task;
+
+ if (!task) {
+ console.error(`No task data in response for ${taskId}`);
+ continue;
+ }
+
+ console.log(`Task ${taskId} status: ${task.status}`);
+
+ if (task.status === 'completed') {
+ console.log(`Task ${taskId} completed with result:`, task.result);
+
+ if (!task.result) {
+ console.warn(`Task ${taskId} completed but has no result`);
+ return [];
+ }
+
+ // Parse the result - the actual Docker output is in task.result.output
+ let data: any[] = [];
+ let outputString = '';
+
+ // Extract the output string from the nested result structure
+ if (task.result && typeof task.result === 'object' && task.result.output) {
+ outputString = task.result.output;
+ } else if (typeof task.result === 'string') {
+ outputString = task.result;
+ } else {
+ console.warn(`Unexpected result format for task ${taskId}:`, task.result);
+ return [];
+ }
+
+ console.log(`Raw output for ${resourceType}:`, outputString);
+
+ if (outputString) {
+ // Split by lines and parse each line as JSON
+ const lines = outputString.split('\n').filter((line: string) => line.trim());
+ console.log(`Task ${taskId} has ${lines.length} lines to parse`);
+
+ for (const line of lines) {
+ try {
+ const parsed = JSON.parse(line.trim());
+ data.push(parsed);
+ } catch (parseError) {
+ console.warn(`Failed to parse line as JSON:`, line, parseError);
+ // Skip invalid JSON lines
+ }
+ }
+ }
+
+ console.log(`Parsed data for ${resourceType}:`, data);
+ return data;
+ } else if (task.status === 'failed') {
+ console.error(`Task ${taskId} failed:`, task.error);
+ throw new Error(task.error || 'Task failed');
+ } else if (task.status === 'running') {
+ console.log(`Task ${taskId} is still running...`);
+ } else {
+ console.log(`Task ${taskId} is ${task.status}, continuing to poll...`);
+ }
+ } catch (err) {
+ console.error(`Error polling task ${taskId}:`, err);
+ // Don't break the loop on network errors, continue polling
+ }
+ }
+
+ console.error(`Task ${taskId} timed out after ${maxAttempts} seconds`);
+ throw new Error(`Task ${taskId} timed out after ${maxAttempts} seconds`);
+ }
+
+ async function sendCommand() {
+ if (!selectedCommand || taskExecuting) return;
+
+ taskExecuting = true;
+ try {
+ let payload: any = {};
+
+ switch (selectedCommand.value) {
+ case 'docker_version':
+ payload = { command: 'version' };
+ break;
+ case 'docker_info':
+ payload = { command: 'info' };
+ break;
+ case 'docker_ps':
+ payload = { command: 'ps', args: ['-a'] };
+ break;
+ case 'docker_images':
+ payload = { command: 'images' };
+ break;
+ case 'system_info':
+ payload = { command: 'system', args: ['info'] };
+ break;
+ case 'agent_upgrade':
+ payload = { action: 'upgrade' };
+ break;
+ case 'docker_prune':
+ payload = { command: 'system', args: ['prune', '-f'] };
+ break;
+ case 'custom':
+ if (!customCommand.trim()) {
+ toast.error('Please enter a custom command');
+ return;
+ }
+ const parts = customCommand.trim().split(' ');
+ payload = {
+ command: parts[0],
+ args: parts.slice(1).concat(commandArgs ? commandArgs.split(' ') : [])
+ };
+ break;
+ }
+
+ const taskType = selectedCommand.value === 'agent_upgrade' ? 'agent_upgrade' : 'docker_command';
+
+ const response = await fetch(`/api/agents/${agentId}/tasks`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ type: taskType,
+ payload
+ })
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to send command: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ toast.success('Command sent successfully');
+ commandDialogOpen = false;
+
+ // Reset form
+ selectedCommand = undefined;
+ commandArgs = '';
+ customCommand = '';
+
+ // Refresh tasks
+ setTimeout(refreshAgentData, 1000);
+ } catch (err) {
+ console.error('Failed to send command:', err);
+ toast.error(err instanceof Error ? err.message : 'Failed to send command');
+ } finally {
+ taskExecuting = false;
+ }
+ }
+
+ function getStatusClasses(agent: Agent) {
+ const actualStatus = getActualAgentStatus(agent);
+ if (actualStatus === 'online') return 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400';
+ return 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400';
+ }
+
+ function getStatusText(agent: Agent) {
+ const actualStatus = getActualAgentStatus(agent);
+ if (actualStatus === 'online') return 'Online';
+ return 'Offline';
+ }
+
+ function canSendCommands(agent: Agent) {
+ return getActualAgentStatus(agent) === 'online';
+ }
+
+ function getTaskStatusClasses(status: string) {
+ switch (status) {
+ case 'completed':
+ return 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400';
+ case 'failed':
+ return 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400';
+ case 'running':
+ return 'bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400';
+ case 'pending':
+ return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-400';
+ default:
+ return 'bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400';
+ }
+ }
+
+ function formatBytes(bytes: number): string {
+ if (bytes === 0) return '0 Bytes';
+ const k = 1024;
+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+ }
+
+ function getContainerStatus(status: string): string {
+ if (!status) return 'unknown';
+ const statusLower = status.toLowerCase();
+ if (statusLower.includes('up')) return 'running';
+ if (statusLower.includes('exit')) return 'stopped';
+ return statusLower;
+ }
+
+ async function handleStackDeploy(data: any) {
+ try {
+ const response = await fetch(`/api/agents/${agentId}/deploy/stack`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(data),
+ credentials: 'include'
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || `Failed to deploy stack: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ toast.success(`Stack deployment started: ${result.task?.id || 'Unknown task'}`);
+
+ // Refresh deployments list
+ setTimeout(() => refreshAgentData(), 1000);
+ } catch (err) {
+ console.error('Stack deploy error:', err);
+ throw err;
+ }
+ }
+
+ async function handleImagePull(imageName: string) {
+ try {
+ const response = await fetch(`/api/agents/${agentId}/deploy/image`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ imageName }),
+ credentials: 'include'
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || `Failed to pull image: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ toast.success(`Image pull started: ${result.task?.id || 'Unknown task'}`);
+ } catch (err) {
+ console.error('Image pull error:', err);
+ throw err;
+ }
+ }
+
+ async function handleContainerRun(data: any) {
+ try {
+ const response = await fetch(`/api/agents/${agentId}/deploy/container`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(data),
+ credentials: 'include'
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || `Failed to run container: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ toast.success(`Container started: ${result.task?.id || 'Unknown task'}`);
+ } catch (err) {
+ console.error('Container run error:', err);
+ throw err;
+ }
+ }
+</script>
+
+<svelte:head>
+ <title>Agent {agent?.hostname || agentId} - Arcane</title>
+</svelte:head>
+
+<div class="space-y-6">
+ <!-- Breadcrumb -->
+ <Breadcrumb.Root>
+ <Breadcrumb.List>
+ <Breadcrumb.Item>
+ <Breadcrumb.Link href="/agents">Agents</Breadcrumb.Link>
+ </Breadcrumb.Item>
+ <Breadcrumb.Separator />
+ <Breadcrumb.Item>
+ <Breadcrumb.Page>{agent?.hostname || agentId}</Breadcrumb.Page>
+ </Breadcrumb.Item>
+ </Breadcrumb.List>
+ </Breadcrumb.Root>
+
+ <!-- Header -->
+ <div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">
+ <div>
+ <h1 class="text-3xl font-bold tracking-tight">
+ {agent?.hostname || 'Agent Details'}
+ </h1>
+ <p class="text-sm text-muted-foreground mt-1">
+ {agent ? `Agent ID: ${agent.id}` : 'Loading agent information...'}
+ </p>
+ </div>
+ <div class="flex items-center gap-2">
+ <Button variant="outline" onclick={() => goto('/agents')}>
+ <ArrowLeft class="size-4 mr-2" />
+ Back to Agents
+ </Button>
+ {#if agent && getActualAgentStatus(agent) === 'online'}
+ <Button onclick={() => (commandDialogOpen = true)} disabled={taskExecuting}>
+ <Terminal class="size-4 mr-2" />
+ Send Command
+ </Button>
+ {/if}
+ </div>
+ </div>
+
+ <!-- Error State -->
+ {#if error}
+ <Alert.Root variant="destructive">
+ <AlertCircle class="size-4" />
+ <Alert.Title>Error</Alert.Title>
+ <Alert.Description>{error}</Alert.Description>
+ </Alert.Root>
+ {:else if agent}
+ <!-- Agent Overview -->
+ <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
+ <Card.Root>
+ <Card.Content class="p-4 flex items-center space-x-3">
+ <div class="bg-blue-500/10 p-2 rounded-full">
+ <Server class="size-5 text-blue-500" />
+ </div>
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">Status</p>
+ <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {getStatusClasses(agent)}">
+ {getStatusText(agent)}
+ </span>
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root>
+ <Card.Content class="p-4 flex items-center space-x-3">
+ <div class="bg-green-500/10 p-2 rounded-full">
+ <Monitor class="size-5 text-green-500" />
+ </div>
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">Platform</p>
+ <p class="font-semibold capitalize">{agent.platform}</p>
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root>
+ <Card.Content class="p-4 flex items-center space-x-3">
+ <div class="bg-purple-500/10 p-2 rounded-full">
+ <Settings class="size-5 text-purple-500" />
+ </div>
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">Version</p>
+ <p class="font-semibold">{agent.version}</p>
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root>
+ <Card.Content class="p-4 flex items-center space-x-3">
+ <div class="bg-amber-500/10 p-2 rounded-full">
+ <Clock class="size-5 text-amber-500" />
+ </div>
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">Last Seen</p>
+ <p class="font-semibold text-sm">{formatDistanceToNow(new Date(agent.lastSeen))} ago</p>
+ </div>
+ </Card.Content>
+ </Card.Root>
+ </div>
+
+ <!-- Resource Metrics -->
+ {#if agent.metrics}
+ <DropdownCard id="agent-metrics" title="Resource Metrics" description="View detailed Docker resource information" defaultExpanded={false} icon={Activity}>
+ <!-- Metrics Overview -->
+ <div class="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6">
+ <div class="text-center p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
+ <Container class="size-6 text-blue-600 dark:text-blue-400 mx-auto mb-1" />
+ <p class="text-2xl font-bold text-blue-600 dark:text-blue-400">{agent.metrics.containerCount ?? 0}</p>
+ <p class="text-sm text-blue-600/80 dark:text-blue-400/80">Containers</p>
+ </div>
+ <div class="text-center p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
+ <HardDrive class="size-6 text-green-600 dark:text-green-400 mx-auto mb-1" />
+ <p class="text-2xl font-bold text-green-600 dark:text-green-400">{agent.metrics.imageCount ?? 0}</p>
+ <p class="text-sm text-green-600/80 dark:text-green-400/80">Images</p>
+ </div>
+ <div class="text-center p-3 bg-purple-50 dark:bg-purple-900/20 rounded-lg">
+ <Layers class="size-6 text-purple-600 dark:text-purple-400 mx-auto mb-1" />
+ <p class="text-2xl font-bold text-purple-600 dark:text-purple-400">{agent.metrics.stackCount ?? 0}</p>
+ <p class="text-sm text-purple-600/80 dark:text-purple-400/80">Stacks</p>
+ </div>
+ <div class="text-center p-3 bg-orange-50 dark:bg-orange-900/20 rounded-lg">
+ <Network class="size-6 text-orange-600 dark:text-orange-400 mx-auto mb-1" />
+ <p class="text-2xl font-bold text-orange-600 dark:text-orange-400">{agent.metrics.networkCount ?? 0}</p>
+ <p class="text-sm text-orange-600/80 dark:text-orange-400/80">Networks</p>
+ </div>
+ <div class="text-center p-3 bg-cyan-50 dark:bg-cyan-900/20 rounded-lg">
+ <Database class="size-6 text-cyan-600 dark:text-cyan-400 mx-auto mb-1" />
+ <p class="text-2xl font-bold text-cyan-600 dark:text-cyan-400">{agent.metrics.volumeCount ?? 0}</p>
+ <p class="text-sm text-cyan-600/80 dark:text-cyan-400/80">Volumes</p>
+ </div>
+ </div>
+
+ <!-- Resources Data Section -->
+ {#if agent.status === 'online'}
+ <div class="space-y-4 pt-4 border-t border-border">
+ <div class="flex items-center justify-between">
+ <div>
+ <h4 class="font-medium mb-1">Resource Details</h4>
+ <p class="text-sm text-muted-foreground">View detailed information about Docker resources</p>
+ </div>
+ <Button variant="outline" size="sm" onclick={loadResourcesData} disabled={resourcesLoading}>
+ {#if resourcesLoading}
+ <Loader2 class="size-4 mr-2 animate-spin" />
+ Loading...
+ {:else}
+ <RefreshCw class="size-4 mr-2" />
+ Load Resources
+ {/if}
+ </Button>
+ </div>
+
+ {#if resourcesError}
+ <Alert.Root variant="destructive">
+ <AlertCircle class="size-4" />
+ <Alert.Title>Error Loading Resources</Alert.Title>
+ <Alert.Description>{resourcesError}</Alert.Description>
+ </Alert.Root>
+ {/if}
+
+ <!-- Resource Tables -->
+ <!-- Always show tabs if any resource loading has been attempted -->
+ {#if resourcesData.containers.length > 0 || resourcesData.images.length > 0 || resourcesData.networks.length > 0 || resourcesData.volumes.length > 0 || resourcesData.stacks.length > 0}
+ <Tabs.Root value="containers" class="w-full">
+ <Tabs.List class="grid w-full grid-cols-5">
+ <Tabs.Trigger value="containers" class="flex items-center gap-2">
+ <Container class="size-4" />
+ Containers ({resourcesData.containers.length})
+ </Tabs.Trigger>
+ <Tabs.Trigger value="images" class="flex items-center gap-2">
+ <HardDrive class="size-4" />
+ Images ({resourcesData.images.length})
+ </Tabs.Trigger>
+ <Tabs.Trigger value="networks" class="flex items-center gap-2">
+ <Network class="size-4" />
+ Networks ({resourcesData.networks.length})
+ </Tabs.Trigger>
+ <Tabs.Trigger value="volumes" class="flex items-center gap-2">
+ <Database class="size-4" />
+ Volumes ({resourcesData.volumes.length})
+ </Tabs.Trigger>
+ <Tabs.Trigger value="stacks" class="flex items-center gap-2">
+ <Layers class="size-4" />
+ Stacks ({resourcesData.stacks.length})
+ </Tabs.Trigger>
+ </Tabs.List>
+
+ <!-- Containers Tab -->
+ <Tabs.Content value="containers" class="mt-4">
+ {#if resourcesData.containers.length > 0}
+ <UniversalTable
+ data={resourcesData.containers}
+ columns={[
+ { accessorKey: 'Names', header: 'Name' },
+ { accessorKey: 'Image', header: 'Image' },
+ { accessorKey: 'Status', header: 'Status' },
+ { accessorKey: 'Ports', header: 'Ports' },
+ { accessorKey: 'CreatedAt', header: 'Created' }
+ ]}
+ idKey="ID"
+ features={{ selection: false }}
+ display={{
+ filterPlaceholder: 'Search containers...',
+ noResultsMessage: 'No containers found'
+ }}
+ pagination={{ pageSize: 10 }}
+ />
+ {:else}
+ <div class="text-center py-8 text-muted-foreground">
+ <Container class="size-12 mx-auto mb-4 opacity-50" />
+ <p>No containers found</p>
+ </div>
+ {/if}
+ </Tabs.Content>
+
+ <!-- Images Tab -->
+ <Tabs.Content value="images" class="mt-4">
+ {#if resourcesData.images.length > 0}
+ <UniversalTable
+ data={resourcesData.images}
+ columns={[
+ { accessorKey: 'Repository', header: 'Repository' },
+ { accessorKey: 'Tag', header: 'Tag' },
+ { accessorKey: 'ID', header: 'Image ID' },
+ { accessorKey: 'CreatedAt', header: 'Created' },
+ { accessorKey: 'Size', header: 'Size' }
+ ]}
+ idKey="ID"
+ features={{ selection: false }}
+ display={{
+ filterPlaceholder: 'Search images...',
+ noResultsMessage: 'No images found'
+ }}
+ pagination={{ pageSize: 10 }}
+ />
+ {:else}
+ <div class="text-center py-8 text-muted-foreground">
+ <HardDrive class="size-12 mx-auto mb-4 opacity-50" />
+ <p>No images found</p>
+ </div>
+ {/if}
+ </Tabs.Content>
+
+ <!-- Networks Tab -->
+ <Tabs.Content value="networks" class="mt-4">
+ {#if resourcesData.networks.length > 0}
+ <UniversalTable
+ data={resourcesData.networks}
+ columns={[
+ { accessorKey: 'Name', header: 'Name' },
+ { accessorKey: 'Driver', header: 'Driver' },
+ { accessorKey: 'Scope', header: 'Scope' },
+ { accessorKey: 'ID', header: 'Network ID' },
+ { accessorKey: 'CreatedAt', header: 'Created' }
+ ]}
+ idKey="ID"
+ features={{ selection: false }}
+ display={{
+ filterPlaceholder: 'Search networks...',
+ noResultsMessage: 'No networks found'
+ }}
+ pagination={{ pageSize: 10 }}
+ />
+ {:else}
+ <div class="text-center py-8 text-muted-foreground">
+ <Network class="size-12 mx-auto mb-4 opacity-50" />
+ <p>No networks found</p>
+ </div>
+ {/if}
+ </Tabs.Content>
+
+ <!-- Volumes Tab -->
+ <Tabs.Content value="volumes" class="mt-4">
+ {#if resourcesData.volumes.length > 0}
+ <UniversalTable
+ data={resourcesData.volumes}
+ columns={[
+ { accessorKey: 'Name', header: 'Name' },
+ { accessorKey: 'Driver', header: 'Driver' },
+ { accessorKey: 'Mountpoint', header: 'Mountpoint' },
+ { accessorKey: 'CreatedAt', header: 'Created' }
+ ]}
+ idKey="Name"
+ features={{ selection: false }}
+ display={{
+ filterPlaceholder: 'Search volumes...',
+ noResultsMessage: 'No volumes found'
+ }}
+ pagination={{ pageSize: 10 }}
+ />
+ {:else}
+ <div class="text-center py-8 text-muted-foreground">
+ <Database class="size-12 mx-auto mb-4 opacity-50" />
+ <p>No volumes found</p>
+ </div>
+ {/if}
+ </Tabs.Content>
+
+ <!-- Stacks Tab -->
+ <Tabs.Content value="stacks" class="mt-4">
+ {#if resourcesData.stacks.length > 0}
+ <UniversalTable
+ data={resourcesData.stacks}
+ columns={[
+ { accessorKey: 'Name', header: 'Project Name' },
+ { accessorKey: 'Status', header: 'Status' },
+ { accessorKey: 'ConfigFiles', header: 'Config Files' },
+ { accessorKey: 'Services', header: 'Services' }
+ ]}
+ idKey="Name"
+ features={{ selection: false }}
+ display={{
+ filterPlaceholder: 'Search compose projects...',
+ noResultsMessage: 'No compose projects found'
+ }}
+ pagination={{ pageSize: 10 }}
+ />
+ {:else}
+ <div class="text-center py-8 text-muted-foreground">
+ <Layers class="size-12 mx-auto mb-4 opacity-50" />
+ <p>No compose projects found</p>
+ </div>
+ {/if}
+ </Tabs.Content>
+ </Tabs.Root>
+ {:else}
+ <!-- Show this only when no data has been loaded yet -->
+ <div class="text-center py-8 text-muted-foreground">
+ <Database class="size-12 mx-auto mb-4 opacity-50" />
+ <p class="font-medium">No Resource Data Loaded</p>
+ <p class="text-sm">Click "Load Resources" to fetch Docker resource information</p>
+ </div>
+ {/if}
+ </div>
+ {/if}
+
+ {#if getActualAgentStatus(agent) === 'online'}
+ <div class="space-y-4 pt-4 border-t border-border">
+ <div class="flex items-center justify-between">
+ <div>
+ <h4 class="font-medium mb-1">Deploy Resources</h4>
+ <p class="text-sm text-muted-foreground">Deploy stacks, containers, or images to this agent</p>
+ </div>
+ </div>
+
+ <!-- Quick Deploy Cards -->
+ <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
+ <!-- Deploy Stack Card -->
+ <Card.Root class="cursor-pointer hover:border-primary/50 transition-colors" onclick={() => (deployDialogOpen = true)}>
+ <Card.Content class="p-4">
+ <div class="flex items-center space-x-3">
+ <div class="bg-blue-500/10 p-2 rounded-lg">
+ <Layers class="size-5 text-blue-500" />
+ </div>
+ <div>
+ <h5 class="font-medium">Deploy Stack</h5>
+ <p class="text-sm text-muted-foreground">Deploy a complete application stack</p>
+ </div>
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <!-- Pull Image Card -->
+ <Card.Root class="cursor-pointer hover:border-primary/50 transition-colors" onclick={() => (imageDialogOpen = true)}>
+ <Card.Content class="p-4">
+ <div class="flex items-center space-x-3">
+ <div class="bg-green-500/10 p-2 rounded-lg">
+ <Download class="size-5 text-green-500" />
+ </div>
+ <div>
+ <h5 class="font-medium">Pull Image</h5>
+ <p class="text-sm text-muted-foreground">Download a Docker image</p>
+ </div>
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <!-- Quick Container Card -->
+ <Card.Root class="cursor-pointer hover:border-primary/50 transition-colors" onclick={() => (containerDialogOpen = true)}>
+ <Card.Content class="p-4">
+ <div class="flex items-center space-x-3">
+ <div class="bg-purple-500/10 p-2 rounded-lg">
+ <Container class="size-5 text-purple-500" />
+ </div>
+ <div>
+ <h5 class="font-medium">Run Container</h5>
+ <p class="text-sm text-muted-foreground">Start a single container</p>
+ </div>
+ </div>
+ </Card.Content>
+ </Card.Root>
+ </div>
+
+ <!-- Recent Deployments -->
+ {#if deployments.length > 0}
+ <div class="space-y-2">
+ <h5 class="font-medium">Recent Deployments</h5>
+ <div class="space-y-2">
+ {#each deployments.slice(0, 3) as deployment}
+ <div class="flex items-center justify-between p-3 bg-muted/30 rounded-lg">
+ <div class="flex items-center space-x-3">
+ <div class="bg-blue-500/10 p-1.5 rounded">
+ {#if deployment.type === 'stack'}
+ <Layers class="size-4 text-blue-500" />
+ {:else if deployment.type === 'image'}
+ <Download class="size-4 text-green-500" />
+ {:else}
+ <Container class="size-4 text-purple-500" />
+ {/if}
+ </div>
+ <div>
+ <p class="font-medium text-sm">{deployment.name}</p>
+ <p class="text-xs text-muted-foreground">
+ {deployment.type} β€’ {formatDistanceToNow(new Date(deployment.createdAt))} ago
+ </p>
+ </div>
+ </div>
+ <StatusBadge variant={deployment.status === 'running' ? 'green' : deployment.status === 'failed' ? 'red' : 'amber'} text={deployment.status} />
+ </div>
+ {/each}
+ </div>
+ </div>
+ {/if}
+ </div>
+ {/if}
+ </DropdownCard>
+ {/if}
+
+ <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
+ <!-- Agent Information -->
+ <Card.Root>
+ <Card.Header>
+ <Card.Title>Agent Information</Card.Title>
+ </Card.Header>
+ <Card.Content class="space-y-4">
+ <div class="grid grid-cols-2 gap-4 text-sm">
+ <div>
+ <span class="text-muted-foreground">Hostname</span>
+ <p class="font-medium">{agent.hostname}</p>
+ </div>
+ <div>
+ <span class="text-muted-foreground">Agent ID</span>
+ <p class="font-mono text-xs">{agent.id}</p>
+ </div>
+ <div>
+ <span class="text-muted-foreground">Created</span>
+ <p class="font-medium">{new Date(agent.createdAt).toLocaleDateString()}</p>
+ </div>
+ <div>
+ <span class="text-muted-foreground">Updated</span>
+ <p class="font-medium">{agent.updatedAt ? new Date(agent.updatedAt).toLocaleDateString() : 'Never'}</p>
+ </div>
+ </div>
+
+ <div>
+ <span class="text-muted-foreground text-sm">Capabilities</span>
+ <div class="flex flex-wrap gap-1 mt-1">
+ {#each agent.capabilities as capability}
+ <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
+ {capability}
+ </span>
+ {:else}
+ <span class="text-muted-foreground text-sm">None</span>
+ {/each}
+ </div>
+ </div>
+
+ {#if agent.dockerInfo}
+ <div class="pt-4 border-t">
+ <h4 class="font-medium mb-3">Docker Information</h4>
+ <div class="grid grid-cols-2 gap-4 text-sm">
+ <div>
+ <span class="text-muted-foreground">Docker Version</span>
+ <p class="font-medium">{agent.dockerInfo.version}</p>
+ </div>
+ <div>
+ <span class="text-muted-foreground">Containers</span>
+ <p class="font-medium">{agent.dockerInfo.containers}</p>
+ </div>
+ <div>
+ <span class="text-muted-foreground">Images</span>
+ <p class="font-medium">{agent.dockerInfo.images}</p>
+ </div>
+ </div>
+ </div>
+ {/if}
+ </Card.Content>
+ </Card.Root>
+
+ <!-- Recent Tasks -->
+ <Card.Root>
+ <Card.Header>
+ <div class="flex items-center justify-between">
+ <Card.Title>Recent Tasks</Card.Title>
+ <Button variant="outline" size="sm" onclick={refreshAgentData}>
+ <RefreshCw class="size-4" />
+ </Button>
+ </div>
+ </Card.Header>
+ <Card.Content>
+ {#if tasks.length > 0}
+ <div class="space-y-3 max-h-96 overflow-y-auto">
+ {#each tasks.slice(0, 10) as task}
+ <div class="border rounded-lg p-3">
+ <div class="flex items-center justify-between mb-2">
+ <div class="flex items-center gap-2">
+ <p class="font-medium text-sm">{task.type.replace('_', ' ').replace(/\b\w/g, (l) => l.toUpperCase())}</p>
+ <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {getTaskStatusClasses(task.status)}">
+ {task.status}
+ </span>
+ </div>
+ <p class="text-xs text-muted-foreground">
+ {formatDistanceToNow(new Date(task.createdAt))} ago
+ </p>
+ </div>
+
+ <!-- Show command details -->
+ {#if task.payload?.command}
+ <div class="text-xs text-muted-foreground mb-2">
+ <code class="bg-muted px-1 rounded">
+ {task.payload.command}
+ {#if task.payload.args?.length > 0}
+ {task.payload.args.join(' ')}
+ {/if}
+ </code>
+ </div>
+ {/if}
+
+ <!-- Show results for completed tasks -->
+ {#if task.status === 'completed' && task.result}
+ <details class="mt-2">
+ <summary class="cursor-pointer text-xs text-green-600 hover:text-green-500"> View Output </summary>
+ <div class="mt-2 p-2 bg-muted rounded text-xs font-mono whitespace-pre-wrap max-h-32 overflow-y-auto">
+ {typeof task.result === 'string' ? task.result : JSON.stringify(task.result, null, 2)}
+ </div>
+ </details>
+ {/if}
+
+ <!-- Show errors for failed tasks -->
+ {#if task.error}
+ <details class="mt-2">
+ <summary class="cursor-pointer text-xs text-red-600 hover:text-red-500"> View Error </summary>
+ <div class="mt-2 p-2 bg-red-50 dark:bg-red-900/20 rounded text-xs text-red-600 dark:text-red-400 max-h-32 overflow-y-auto">
+ {task.error}
+ </div>
+ </details>
+ {/if}
+ </div>
+ {/each}
+ </div>
+ {:else}
+ <div class="text-center py-8 text-muted-foreground">
+ <Activity class="size-12 mx-auto mb-4 opacity-50" />
+ <p>No tasks executed yet</p>
+ </div>
+ {/if}
+ </Card.Content>
+ </Card.Root>
+ </div>
+
+ <!-- Connection Status Banner -->
+ {#if agent && !canSendCommands(agent)}
+ <Alert.Root variant="destructive">
+ <AlertCircle class="size-4" />
+ <Alert.Title>Agent Offline</Alert.Title>
+ <Alert.Description>This agent is not currently connected. Commands cannot be sent until the agent reconnects.</Alert.Description>
+ </Alert.Root>
+ {/if}
+ {/if}
+</div>
+
+<!-- Send Command Dialog -->
+<Dialog.Root bind:open={commandDialogOpen}>
+ <Dialog.Content class="sm:max-w-md">
+ <Dialog.Header>
+ <Dialog.Title>Send Command to Agent</Dialog.Title>
+ <Dialog.Description>
+ Execute a command on {agent?.hostname}
+ </Dialog.Description>
+ </Dialog.Header>
+ <div class="space-y-4">
+ <div>
+ <Label for="command-select">Command</Label>
+ <Select.Root type="single" value={selectedCommand?.value} onValueChange={(v) => (selectedCommand = predefinedCommands.find((cmd) => cmd.value === v))}>
+ <Select.Trigger>
+ <span>{selectedCommand?.label || 'Select a command'}</span>
+ </Select.Trigger>
+ <Select.Content>
+ {#each predefinedCommands as command}
+ <Select.Item value={command.value}>{command.label}</Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ </div>
+
+ {#if selectedCommand?.value === 'custom'}
+ <div>
+ <Label for="custom-command">Custom Command</Label>
+ <Input id="custom-command" bind:value={customCommand} placeholder="docker ps -a" disabled={taskExecuting} />
+ </div>
+ {/if}
+
+ {#if selectedCommand && selectedCommand.value !== 'agent_upgrade'}
+ <div>
+ <Label for="command-args">Additional Arguments (optional)</Label>
+ <Input id="command-args" bind:value={commandArgs} placeholder="--format table" disabled={taskExecuting} />
+ </div>
+ {/if}
+ </div>
+ <Dialog.Footer>
+ <Button variant="outline" onclick={() => (commandDialogOpen = false)} disabled={taskExecuting}>Cancel</Button>
+ <Button onclick={sendCommand} disabled={!selectedCommand || taskExecuting}>
+ {#if taskExecuting}
+ <RefreshCw class="size-4 mr-2 animate-spin" />
+ Sending...
+ {:else}
+ <Play class="size-4 mr-2" />
+ Send Command
+ {/if}
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+</Dialog.Root>
+
+<!-- Stack Deployment Dialog -->
+<Dialog.Root bind:open={deployDialogOpen}>
+ <Dialog.Content class="sm:max-w-2xl">
+ <Dialog.Header>
+ <Dialog.Title>Deploy Stack to {agent?.hostname}</Dialog.Title>
+ <Dialog.Description>Choose a stack to deploy or create a new one</Dialog.Description>
+ </Dialog.Header>
+
+ <StackDeploymentForm {agentId} onClose={() => (deployDialogOpen = false)} onDeploy={handleStackDeploy} />
+ </Dialog.Content>
+</Dialog.Root>
+
+<!-- Image Pull Dialog -->
+<Dialog.Root bind:open={imageDialogOpen}>
+ <Dialog.Content class="sm:max-w-md">
+ <Dialog.Header>
+ <Dialog.Title>Pull Image to {agent?.hostname}</Dialog.Title>
+ <Dialog.Description>Enter the image name to download</Dialog.Description>
+ </Dialog.Header>
+
+ <ImagePullForm {agentId} onClose={() => (imageDialogOpen = false)} onPull={handleImagePull} />
+ </Dialog.Content>
+</Dialog.Root>
+
+<!-- Quick Container Dialog -->
+<Dialog.Root bind:open={containerDialogOpen}>
+ <Dialog.Content class="sm:max-w-xl">
+ <Dialog.Header>
+ <Dialog.Title>Run Container on {agent?.hostname}</Dialog.Title>
+ <Dialog.Description>Quickly start a container from an image</Dialog.Description>
+ </Dialog.Header>
+
+ <QuickContainerForm {agentId} onClose={() => (containerDialogOpen = false)} onRun={handleContainerRun} />
+ </Dialog.Content>
+</Dialog.Root>
diff --git a/src/routes/api/agents/+server.ts b/src/routes/api/agents/+server.ts
new file mode 100644
index 000000000..703ef2953
--- /dev/null
+++ b/src/routes/api/agents/+server.ts
@@ -0,0 +1,25 @@
+import { json } from '@sveltejs/kit';
+import { listAgents } from '$lib/services/agent/agent-manager';
+import type { RequestHandler } from './$types';
+
+export const GET: RequestHandler = async () => {
+ try {
+ const agents = await listAgents();
+
+ return json({
+ success: true,
+ agents,
+ count: agents.length
+ });
+ } catch (error) {
+ console.error('API: Failed to list agents:', error);
+ return json(
+ {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ agents: []
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/api/agents/[agentId]/+server.ts b/src/routes/api/agents/[agentId]/+server.ts
new file mode 100644
index 000000000..765171dd2
--- /dev/null
+++ b/src/routes/api/agents/[agentId]/+server.ts
@@ -0,0 +1,64 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { getAgent } from '$lib/services/agent/agent-manager';
+import { updateAgentHeartbeat } from '$lib/services/agent/agent-manager';
+
+export const GET: RequestHandler = async ({ locals, params }) => {
+ if (!locals.user?.roles.includes('admin')) {
+ return json({ error: 'Unauthorized' }, { status: 403 });
+ }
+
+ try {
+ const agent = await getAgent(params.agentId);
+ if (!agent) {
+ return json({ error: 'Agent not found' }, { status: 404 });
+ }
+
+ // Just return the agent as-is, since status already indicates if it's online
+ return json({ agent });
+ } catch (error) {
+ console.error('Error fetching agent:', error);
+ return json({ error: 'Failed to fetch agent' }, { status: 500 });
+ }
+};
+
+export const DELETE: RequestHandler = async ({ locals, params }) => {
+ if (!locals.user?.roles.includes('admin')) {
+ return json({ error: 'Unauthorized' }, { status: 403 });
+ }
+
+ try {
+ // TODO: Implement agent deletion
+ return json({ success: true });
+ } catch (error) {
+ console.error('Error deleting agent:', error);
+ return json({ error: 'Failed to delete agent' }, { status: 500 });
+ }
+};
+
+export const POST: RequestHandler = async ({ request }) => {
+ try {
+ const { agent_id, status, timestamp } = await request.json();
+
+ if (!agent_id) {
+ return json({ error: 'agent_id is required' }, { status: 400 });
+ }
+
+ await updateAgentHeartbeat(agent_id);
+ console.log(`πŸ’“ Heartbeat received from ${agent_id}`);
+
+ return json({
+ success: true,
+ message: 'Heartbeat received'
+ });
+ } catch (error) {
+ console.error('Failed to process heartbeat:', error);
+ return json(
+ {
+ error: 'Failed to process heartbeat',
+ details: error instanceof Error ? error.message : 'Unknown error'
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/api/agents/[agentId]/command/+server.ts b/src/routes/api/agents/[agentId]/command/+server.ts
new file mode 100644
index 000000000..7eb804970
--- /dev/null
+++ b/src/routes/api/agents/[agentId]/command/+server.ts
@@ -0,0 +1,49 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { sendTaskToAgent, getAgent } from '$lib/services/agent/agent-manager';
+
+export const POST: RequestHandler = async ({ locals, params, request }) => {
+ if (!locals.user?.roles.includes('admin')) {
+ return json({ error: 'Unauthorized' }, { status: 403 });
+ }
+
+ try {
+ const data = await request.json();
+ const agentId = params.agentId;
+ const { command, args } = data;
+
+ if (!command) {
+ return json({ error: 'Command is required' }, { status: 400 });
+ }
+
+ // Verify agent exists and is online
+ const agent = await getAgent(agentId);
+ if (!agent) {
+ return json({ error: 'Agent not found' }, { status: 404 });
+ }
+
+ if (agent.status !== 'online') {
+ return json({ error: `Agent is not online (status: ${agent.status})` }, { status: 400 });
+ }
+
+ // Send the command to the agent
+ const task = await sendTaskToAgent(agentId, 'docker_command', {
+ command,
+ args
+ });
+
+ return json({
+ success: true,
+ task,
+ message: `Command sent to agent ${agent.hostname}`
+ });
+ } catch (error) {
+ console.error('Error sending command to agent:', error);
+ return json(
+ {
+ error: error instanceof Error ? error.message : 'Failed to send command to agent'
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/api/agents/[agentId]/deploy/container/+server.ts b/src/routes/api/agents/[agentId]/deploy/container/+server.ts
new file mode 100644
index 000000000..3bad1e714
--- /dev/null
+++ b/src/routes/api/agents/[agentId]/deploy/container/+server.ts
@@ -0,0 +1,111 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { sendTaskToAgent, getAgent } from '$lib/services/agent/agent-manager';
+import { createContainerDeployment } from '$lib/services/deployment-service';
+
+export const POST: RequestHandler = async ({ locals, params, request }) => {
+ if (!locals.user?.roles.includes('admin')) {
+ return json({ error: 'Unauthorized' }, { status: 403 });
+ }
+
+ try {
+ const data = await request.json();
+ const agentId = params.agentId;
+
+ const { imageName, containerName, ports = [], volumes = [], envVars = [], detached = true, autoRemove = false, restartPolicy = 'no' } = data;
+
+ if (!imageName) {
+ return json({ error: 'Image name is required' }, { status: 400 });
+ }
+
+ // Verify agent exists and is online
+ const agent = await getAgent(agentId);
+ if (!agent) {
+ return json({ error: 'Agent not found' }, { status: 404 });
+ }
+
+ if (agent.status !== 'online') {
+ return json({ error: `Agent is not online (status: ${agent.status})` }, { status: 400 });
+ }
+
+ // Build Docker run command arguments
+ const args = ['run'];
+
+ // Add detached flag
+ if (detached) {
+ args.push('-d');
+ }
+
+ // Add auto remove flag
+ if (autoRemove) {
+ args.push('--rm');
+ }
+
+ // Add restart policy
+ if (restartPolicy && restartPolicy !== 'no') {
+ args.push('--restart', restartPolicy);
+ }
+
+ // Add container name
+ if (containerName) {
+ args.push('--name', containerName);
+ }
+
+ // Add port mappings
+ ports.forEach((port: { host: string; container: string }) => {
+ if (port.host && port.container) {
+ args.push('-p', `${port.host}:${port.container}`);
+ }
+ });
+
+ // Add volume mounts
+ volumes.forEach((volume: { host: string; container: string }) => {
+ if (volume.host && volume.container) {
+ args.push('-v', `${volume.host}:${volume.container}`);
+ }
+ });
+
+ // Add environment variables
+ envVars.forEach((env: { key: string; value: string }) => {
+ if (env.key && env.value) {
+ args.push('-e', `${env.key}=${env.value}`);
+ }
+ });
+
+ // Add image name
+ args.push(imageName);
+
+ // Create the container run task
+ const task = await sendTaskToAgent(agentId, 'docker_command', {
+ command: 'run',
+ args: args.slice(1) // Remove 'run' since it's the command
+ });
+
+ // Create deployment record
+ const deployment = await createContainerDeployment(
+ agentId,
+ containerName || imageName,
+ imageName,
+ ports.map((p: any) => `${p.host}:${p.container}`),
+ volumes.map((v: any) => `${v.host}:${v.container}`),
+ task.id
+ );
+
+ console.log(`🐳 Container deployment task ${task.id} created for agent ${agentId}: ${containerName || imageName}`);
+
+ return json({
+ success: true,
+ task,
+ deployment,
+ message: `Container deployment task created: ${containerName || imageName}`
+ });
+ } catch (error) {
+ console.error('Error creating container deployment task:', error);
+ return json(
+ {
+ error: error instanceof Error ? error.message : 'Failed to create container deployment task'
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/api/agents/[agentId]/deploy/image/+server.ts b/src/routes/api/agents/[agentId]/deploy/image/+server.ts
new file mode 100644
index 000000000..4c1837c88
--- /dev/null
+++ b/src/routes/api/agents/[agentId]/deploy/image/+server.ts
@@ -0,0 +1,47 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { pullImageOnAgent, getAgent } from '$lib/services/agent/agent-manager';
+
+export const POST: RequestHandler = async ({ locals, params, request }) => {
+ if (!locals.user?.roles.includes('admin')) {
+ return json({ error: 'Unauthorized' }, { status: 403 });
+ }
+
+ try {
+ const { imageName } = await request.json();
+ const agentId = params.agentId;
+
+ if (!imageName) {
+ return json({ error: 'Image name is required' }, { status: 400 });
+ }
+
+ // Verify agent exists and is online
+ const agent = await getAgent(agentId);
+ if (!agent) {
+ return json({ error: 'Agent not found' }, { status: 404 });
+ }
+
+ if (agent.status !== 'online') {
+ return json({ error: `Agent is not online (status: ${agent.status})` }, { status: 400 });
+ }
+
+ // Create the image pull task
+ const task = await pullImageOnAgent(agentId, imageName);
+
+ console.log(`πŸ“‹ Image pull task ${task.id} created for agent ${agentId}: ${imageName}`);
+
+ return json({
+ success: true,
+ task,
+ message: `Image pull task created: ${imageName}`
+ });
+ } catch (error) {
+ console.error('Error creating image pull task:', error);
+ return json(
+ {
+ error: error instanceof Error ? error.message : 'Failed to create image pull task'
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/api/agents/[agentId]/deploy/stack/+server.ts b/src/routes/api/agents/[agentId]/deploy/stack/+server.ts
new file mode 100644
index 000000000..bedaf77e8
--- /dev/null
+++ b/src/routes/api/agents/[agentId]/deploy/stack/+server.ts
@@ -0,0 +1,78 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { sendTaskToAgent, getAgent } from '$lib/services/agent/agent-manager';
+import { createStackDeployment } from '$lib/services/deployment-service';
+
+export const POST: RequestHandler = async ({ locals, params, request }) => {
+ if (!locals.user?.roles.includes('admin')) {
+ return json({ error: 'Unauthorized' }, { status: 403 });
+ }
+
+ try {
+ const data = await request.json();
+ const agentId = params.agentId;
+
+ const { stackName, composeContent, envContent, mode } = data;
+
+ if (!stackName || !composeContent) {
+ return json({ error: 'Stack name and compose content are required' }, { status: 400 });
+ }
+
+ const agent = await getAgent(agentId);
+ if (!agent) {
+ return json({ error: 'Agent not found' }, { status: 404 });
+ }
+
+ if (agent.status !== 'online') {
+ return json({ error: `Agent is not online (status: ${agent.status})` }, { status: 400 });
+ }
+
+ const envVars: Record<string, string> = {};
+ if (envContent) {
+ envContent.split('\n').forEach((line: string) => {
+ const trimmedLine = line.trim();
+ if (trimmedLine && !trimmedLine.startsWith('#')) {
+ const [key, ...valueParts] = trimmedLine.split('=');
+ if (key && valueParts.length > 0) {
+ envVars[key.trim()] = valueParts.join('=').trim();
+ }
+ }
+ });
+ }
+
+ // Step 1: Create the project with compose content and env vars
+ const createTask = await sendTaskToAgent(agentId, 'compose_create_project', {
+ project_name: stackName,
+ compose_content: composeContent,
+ env_vars: envVars
+ });
+
+ console.log(`πŸ“‹ Stack creation task ${createTask.id} created for agent ${agentId}: ${stackName}`);
+
+ // Step 2: Start the project with compose_up
+ const startTask = await sendTaskToAgent(agentId, 'compose_up', {
+ project_name: stackName
+ });
+
+ console.log(`πŸš€ Stack start task ${startTask.id} created for agent ${agentId}: ${stackName}`);
+
+ // Create deployment record (using the start task ID as the primary reference)
+ const deployment = await createStackDeployment(agentId, stackName, composeContent, envContent, startTask.id);
+
+ return json({
+ success: true,
+ createTask,
+ startTask,
+ deployment,
+ message: `Stack "${stackName}" created and started on agent`
+ });
+ } catch (error) {
+ console.error('Error creating and starting stack:', error);
+ return json(
+ {
+ error: error instanceof Error ? error.message : 'Failed to create and start stack'
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/api/agents/[agentId]/deployments/+server.ts b/src/routes/api/agents/[agentId]/deployments/+server.ts
new file mode 100644
index 000000000..1abab1cb3
--- /dev/null
+++ b/src/routes/api/agents/[agentId]/deployments/+server.ts
@@ -0,0 +1,36 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { getAgent } from '$lib/services/agent/agent-manager';
+import { getDeployments } from '$lib/services/deployment-service';
+
+export const GET: RequestHandler = async ({ locals, params }) => {
+ if (!locals.user?.roles.includes('admin')) {
+ return json({ error: 'Unauthorized' }, { status: 403 });
+ }
+
+ try {
+ const agentId = params.agentId;
+
+ // Verify agent exists
+ const agent = await getAgent(agentId);
+ if (!agent) {
+ return json({ error: 'Agent not found' }, { status: 404 });
+ }
+
+ // Get real deployments from the service
+ const deployments = await getDeployments(agentId);
+
+ return json({
+ success: true,
+ deployments
+ });
+ } catch (error) {
+ console.error('Error fetching deployments:', error);
+ return json(
+ {
+ error: error instanceof Error ? error.message : 'Failed to fetch deployments'
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/api/agents/[agentId]/stacks/+server.ts b/src/routes/api/agents/[agentId]/stacks/+server.ts
new file mode 100644
index 000000000..343c6d38d
--- /dev/null
+++ b/src/routes/api/agents/[agentId]/stacks/+server.ts
@@ -0,0 +1,41 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { sendTaskToAgent, getAgent } from '$lib/services/agent/agent-manager';
+import { getStacksFromAgent } from '$lib/services/agent/agent-stack-service';
+
+export const GET: RequestHandler = async ({ locals, params, fetch }) => {
+ if (!locals.user?.roles.includes('admin')) {
+ return json({ error: 'Unauthorized' }, { status: 403 });
+ }
+
+ try {
+ const agentId = params.agentId;
+
+ // Verify agent exists and is online
+ const agent = await getAgent(agentId);
+ if (!agent) {
+ return json({ error: 'Agent not found' }, { status: 404 });
+ }
+
+ if (agent.status !== 'online') {
+ return json({ error: `Agent is not online (status: ${agent.status})` }, { status: 400 });
+ }
+
+ // Use the agent-stack-service to get stacks
+ // Pass the fetch context to use event.fetch
+ const stacks = await getStacksFromAgent(agent, { fetch });
+
+ return json({
+ success: true,
+ stacks
+ });
+ } catch (error) {
+ console.error('Error fetching agent stacks:', error);
+ return json(
+ {
+ error: error instanceof Error ? error.message : 'Failed to fetch agent stacks'
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/api/agents/[agentId]/tasks/+server.ts b/src/routes/api/agents/[agentId]/tasks/+server.ts
new file mode 100644
index 000000000..f36f7548a
--- /dev/null
+++ b/src/routes/api/agents/[agentId]/tasks/+server.ts
@@ -0,0 +1,71 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { getAgent, listTasks, sendTaskToAgent } from '$lib/services/agent/agent-manager';
+
+// GET - Agent requests pending tasks (no auth required for agents)
+export const GET: RequestHandler = async ({ params, url }) => {
+ try {
+ const agentId = params.agentId;
+
+ // Check if this is an admin request (has auth) vs agent request (no auth)
+ const isAdminRequest = url.searchParams.has('admin') || url.searchParams.has('include_results');
+
+ if (isAdminRequest) {
+ // This is an admin request from the UI - return full task data
+ const allTasks = await listTasks(agentId);
+ return json({ tasks: allTasks });
+ } else {
+ // This is an agent request - return only pending tasks for execution
+ const allTasks = await listTasks(agentId);
+ const pendingTasks = allTasks.filter((task) => task.status === 'pending');
+
+ const formattedTasks = pendingTasks.map((task) => ({
+ id: task.id,
+ type: task.type,
+ payload: task.payload
+ }));
+
+ console.log(`πŸ“‹ Agent ${agentId} requested tasks, returning ${formattedTasks.length} pending tasks`);
+ return json(formattedTasks);
+ }
+ } catch (error) {
+ console.error('Error fetching tasks:', error);
+ return json({ error: 'Failed to fetch tasks' }, { status: 500 });
+ }
+};
+
+// POST - Admin/UI creates new tasks (requires auth)
+// This will require authentication since it's not covered by the regex patterns
+export const POST: RequestHandler = async ({ locals, params, request }) => {
+ if (!locals.user?.roles.includes('admin')) {
+ return json({ error: 'Unauthorized' }, { status: 403 });
+ }
+
+ try {
+ const { type, payload } = await request.json();
+
+ const agent = await getAgent(params.agentId);
+ if (!agent) {
+ return json({ error: 'Agent not found' }, { status: 404 });
+ }
+
+ if (agent.status !== 'online') {
+ return json({ error: `Agent is not online (status: ${agent.status})` }, { status: 400 });
+ }
+
+ // Create the task - it will be picked up by the agent on next poll
+ const task = await sendTaskToAgent(params.agentId, type, payload);
+
+ console.log(`πŸ“‹ Task ${task.id} created for agent ${params.agentId}`);
+
+ return json({ success: true, task });
+ } catch (error) {
+ console.error('Error creating task:', error);
+ return json(
+ {
+ error: error instanceof Error ? error.message : 'Failed to create task'
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/api/agents/[agentId]/tasks/[taskId]/+server.ts b/src/routes/api/agents/[agentId]/tasks/[taskId]/+server.ts
new file mode 100644
index 000000000..f1da54f89
--- /dev/null
+++ b/src/routes/api/agents/[agentId]/tasks/[taskId]/+server.ts
@@ -0,0 +1,26 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { getTask } from '$lib/services/agent/agent-manager';
+
+// GET - Get individual task details including results
+export const GET: RequestHandler = async ({ locals, params }) => {
+ if (!locals.user?.roles.includes('admin')) {
+ return json({ error: 'Unauthorized' }, { status: 403 });
+ }
+
+ try {
+ const task = await getTask(params.taskId);
+ if (!task) {
+ return json({ error: 'Task not found' }, { status: 404 });
+ }
+
+ if (task.agentId !== params.agentId) {
+ return json({ error: 'Task does not belong to this agent' }, { status: 400 });
+ }
+
+ return json({ task });
+ } catch (error) {
+ console.error('Error fetching task:', error);
+ return json({ error: 'Failed to fetch task' }, { status: 500 });
+ }
+};
diff --git a/src/routes/api/agents/[agentId]/tasks/[taskId]/result/+server.ts b/src/routes/api/agents/[agentId]/tasks/[taskId]/result/+server.ts
new file mode 100644
index 000000000..b94fafc2c
--- /dev/null
+++ b/src/routes/api/agents/[agentId]/tasks/[taskId]/result/+server.ts
@@ -0,0 +1,40 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { updateTaskStatus } from '$lib/services/agent/agent-manager';
+
+// POST - Agent submits task results (no auth required for agents)
+export const POST: RequestHandler = async ({ params, request }) => {
+ try {
+ const { task_id, status, result, error: taskError } = await request.json();
+ const agentId = params.agentId;
+ const taskId = params.taskId;
+
+ // Validate that task_id matches the URL parameter
+ if (task_id && task_id !== taskId) {
+ return json({ error: 'Task ID mismatch' }, { status: 400 });
+ }
+
+ if (!status || !['completed', 'failed', 'running'].includes(status)) {
+ return json({ error: 'Invalid status' }, { status: 400 });
+ }
+
+ // Update the task status
+ await updateTaskStatus(taskId, status, result, taskError);
+
+ console.log(`πŸ“‹ Task ${taskId} result received from agent ${agentId}: ${status}`);
+
+ return json({
+ success: true,
+ message: 'Task result received'
+ });
+ } catch (error) {
+ console.error('Failed to update task result:', error);
+ return json(
+ {
+ error: 'Failed to update task result',
+ details: error instanceof Error ? error.message : 'Unknown error'
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/api/agents/heartbeat/+server.ts b/src/routes/api/agents/heartbeat/+server.ts
new file mode 100644
index 000000000..abc4139cd
--- /dev/null
+++ b/src/routes/api/agents/heartbeat/+server.ts
@@ -0,0 +1,35 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { updateAgent } from '$lib/services/agent/agent-manager';
+
+export const POST: RequestHandler = async ({ request }) => {
+ try {
+ const { agent_id, status, timestamp, metrics } = await request.json();
+
+ if (!agent_id) {
+ return json({ error: 'agent_id is required' }, { status: 400 });
+ }
+
+ await updateAgent(agent_id, {
+ status: 'online',
+ lastSeen: new Date().toISOString(),
+ ...(metrics && { metrics })
+ });
+
+ console.log(`πŸ’“ Heartbeat received from ${agent_id}${metrics ? ' (with metrics)' : ''}`);
+
+ return json({
+ success: true,
+ message: 'Heartbeat received'
+ });
+ } catch (error) {
+ console.error('Failed to process heartbeat:', error);
+ return json(
+ {
+ error: 'Failed to process heartbeat',
+ details: error instanceof Error ? error.message : 'Unknown error'
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/api/agents/register/+server.ts b/src/routes/api/agents/register/+server.ts
new file mode 100644
index 000000000..4825b84e0
--- /dev/null
+++ b/src/routes/api/agents/register/+server.ts
@@ -0,0 +1,43 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { registerAgent } from '$lib/services/agent/agent-manager';
+
+export const POST: RequestHandler = async ({ request }) => {
+ try {
+ const { agent_id, hostname, platform, version, capabilities } = await request.json();
+
+ if (!agent_id || !hostname) {
+ return json({ error: 'agent_id and hostname are required' }, { status: 400 });
+ }
+
+ const agent = await registerAgent({
+ id: agent_id,
+ hostname,
+ platform: platform || 'unknown',
+ version: version || '1.0.0',
+ capabilities: capabilities || [],
+ status: 'online',
+ lastSeen: new Date().toISOString(),
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ registeredAt: new Date().toISOString()
+ });
+
+ console.log(`βœ… Agent ${agent_id} registered successfully`);
+
+ return json({
+ success: true,
+ agent_id,
+ message: 'Agent registered successfully'
+ });
+ } catch (error) {
+ console.error('Failed to register agent:', error);
+ return json(
+ {
+ error: 'Failed to register agent',
+ details: error instanceof Error ? error.message : 'Unknown error'
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/containers/+page.server.ts b/src/routes/containers/+page.server.ts
index 8e998dc9d..bdfc3a134 100644
--- a/src/routes/containers/+page.server.ts
+++ b/src/routes/containers/+page.server.ts
@@ -7,7 +7,6 @@ import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async () => {
try {
const [containers, volumes, networks, images] = await Promise.all([listContainers(true), listVolumes(), listNetworks(), listImages()]);
-
return {
containers,
volumes,
diff --git a/src/routes/stacks/+page.server.ts b/src/routes/stacks/+page.server.ts
index 02f3edad9..6e7ead86b 100644
--- a/src/routes/stacks/+page.server.ts
+++ b/src/routes/stacks/+page.server.ts
@@ -1,9 +1,12 @@
import { loadComposeStacks, discoverExternalStacks } from '$lib/services/docker/stack-service';
+import { listAgents } from '$lib/services/agent/agent-manager';
+import { getAllAgentStacks } from '$lib/services/agent/agent-stack-service';
import type { PageServerLoad } from './$types';
import { tryCatch } from '$lib/utils/try-catch';
-export const load: PageServerLoad = async () => {
- const [managedResult, externalResult] = await Promise.all([tryCatch(loadComposeStacks()), tryCatch(discoverExternalStacks())]);
+export const load: PageServerLoad = async ({ fetch }) => {
+ // Get managed stacks, external stacks, and agents in parallel
+ const [managedResult, externalResult, agentsResult] = await Promise.all([tryCatch(loadComposeStacks()), tryCatch(discoverExternalStacks()), tryCatch(listAgents())]);
if (managedResult.error || externalResult.error) {
console.error('Failed to load stacks:', managedResult.error || externalResult.error);
@@ -16,15 +19,55 @@ export const load: PageServerLoad = async () => {
const managedStacks = managedResult.data;
const externalStacks = externalResult.data;
+ const agents = agentsResult.data || [];
+
+ // Filter for online agents
+ const onlineAgents = agents.filter((agent) => {
+ const now = new Date();
+ const lastSeen = new Date(agent.lastSeen);
+ const timeSinceLastSeen = now.getTime() - lastSeen.getTime();
+ const timeout = 5 * 60 * 1000; // 5 minutes
+ return timeSinceLastSeen <= timeout && agent.status === 'online';
+ });
+
+ // Get stacks from all online agents - pass the fetch context
+ const agentStacksResult = await tryCatch(getAllAgentStacks(onlineAgents, { fetch }));
+ const agentStacks = agentStacksResult.data || [];
+
+ // Create a set of agent stack names to filter out duplicates from external stacks
+ const agentStackNames = new Set(agentStacks.map((stack) => stack.name));
+
+ // Merge all stacks together
const combinedStacks = [...managedStacks];
+ // Add external stacks if they don't already exist in combined stacks
+ // AND they're not agent stacks (to prevent duplicates)
for (const externalStack of externalStacks) {
- if (!combinedStacks.some((stack) => stack.id === externalStack.id)) {
+ const isDuplicate = combinedStacks.some((stack) => stack.id === externalStack.id) || agentStackNames.has(externalStack.name);
+
+ if (!isDuplicate) {
combinedStacks.push(externalStack);
}
}
+ // Add agent stacks if they don't already exist in combined stacks
+ for (const agentStack of agentStacks) {
+ // Create a unique ID for agent stacks that won't collide with local stacks
+ const uniqueId = `agent:${agentStack.agentId}:${agentStack.name || agentStack.id}`;
+
+ // Only add if not already in the combined stack list
+ if (!combinedStacks.some((stack) => stack.id === uniqueId || (stack.name === agentStack.name && stack.agentId === agentStack.agentId))) {
+ combinedStacks.push({
+ ...agentStack,
+ id: uniqueId, // Ensure unique ID
+ status: agentStack.status || 'unknown' // Ensure status is always defined
+ });
+ }
+ }
+
return {
- stacks: combinedStacks
+ stacks: combinedStacks,
+ agents: onlineAgents,
+ agentError: agentStacksResult.error ? `Failed to fetch agent stacks: ${agentStacksResult.error.message}` : null
};
};
diff --git a/src/routes/stacks/+page.svelte b/src/routes/stacks/+page.svelte
index d60b25972..f005f43b2 100644
--- a/src/routes/stacks/+page.svelte
+++ b/src/routes/stacks/+page.svelte
@@ -2,7 +2,7 @@
import type { PageData } from './$types';
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import { AlertCircle, Layers, FileStack, Loader2, Play, RotateCcw, StopCircle, Trash2, Ellipsis, Pen } from '@lucide/svelte';
+ import { AlertCircle, Layers, FileStack, Loader2, Play, RotateCcw, StopCircle, Trash2, Ellipsis, Pen, Inspect } from '@lucide/svelte';
import UniversalTable from '$lib/components/universal-table.svelte';
import { openConfirmDialog } from '$lib/components/confirm-dialog';
import * as Table from '$lib/components/ui/table';
@@ -19,11 +19,14 @@
import type { StackActions } from '$lib/types/actions.type';
import ArcaneButton from '$lib/components/arcane-button.svelte';
import { tablePersistence } from '$lib/stores/table-store';
+ import type { Agent } from '$lib/types/agent.type';
let { data }: { data: PageData } = $props();
let stacks = $derived(data.stacks);
- let selectedIds = $state<string[]>([]);
- let isLoading = $state({
+ let agents = $derived(data.agents || []);
+ let loadingAgentStacks = $state(false);
+
+ const isLoading = $state({
start: false,
stop: false,
restart: false,
@@ -38,9 +41,13 @@
const stackApi = new StackAPIService();
- const totalStacks = $derived(stacks?.length || 0);
- const runningStacks = $derived(stacks?.filter((s) => s.status === 'running').length || 0);
- const partialStacks = $derived(stacks?.filter((s) => s.status === 'partially running').length || 0);
+ const allStacks = $derived(stacks);
+ const totalStacks = $derived(allStacks?.length || 0);
+ const runningStacks = $derived(allStacks?.filter((s) => s.status === 'running').length || 0);
+ const partialStacks = $derived(allStacks?.filter((s) => s.status === 'partially running').length || 0);
+
+ // Add this variable to track loading state for remote stack actions
+ let isRemoteActionLoading = $state<string | null>(null);
async function performStackAction(action: StackActions, id: string) {
isLoading[action] = true;
@@ -144,6 +151,218 @@
await invalidateAll();
isLoading['import'] = false;
}
+
+ async function handleRemoveRemoteStack(agentId: string, stackName: string) {
+ openConfirmDialog({
+ title: `Confirm Stack Removal`,
+ message: `Are you sure you want to remove the stack "${stackName}" from agent "${agentId}"? This action cannot be undone.`,
+ confirm: {
+ label: 'Remove',
+ destructive: true,
+ action: async () => {
+ isRemoteActionLoading = `${agentId}:${stackName}:remove`;
+
+ try {
+ // Send the stack_destroy task to the agent
+ const response = await fetch(`/api/agents/${agentId}/tasks`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ type: 'stack_destroy',
+ payload: {
+ project_name: stackName
+ }
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to remove stack');
+ }
+
+ toast.success(`Stack ${stackName} destroyed successfully`);
+ await invalidateAll();
+ } catch (error) {
+ console.error(`Failed to remove remote stack:`, error);
+ toast.error(`Failed to remove stack: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ } finally {
+ isRemoteActionLoading = null;
+ }
+ }
+ }
+ });
+ }
+
+ // Function to load stacks from agents
+ async function loadAgentStacks() {
+ if (agents.length === 0) return;
+
+ loadingAgentStacks = true;
+ try {
+ const agentStackPromises = agents.map(async (agent) => {
+ try {
+ const response = await fetch(`/api/agents/${agent.id}/stacks`);
+ if (!response.ok) throw new Error(`Failed to fetch stacks from ${agent.hostname}`);
+
+ const data = await response.json();
+ return (data.stacks || []).map((stack: any) => ({
+ ...stack,
+ agentId: agent.id,
+ agentHostname: agent.hostname,
+ isRemote: true,
+ id: `${agent.id}:${stack.Name || stack.id}`,
+ name: stack.Name || stack.name,
+ status: stack.Status?.toLowerCase() || 'unknown',
+ serviceCount: stack.ServiceCount || 0,
+ source: 'Remote',
+ createdAt: stack.CreatedAt || new Date().toISOString()
+ }));
+ } catch (error) {
+ console.error(`Failed to load stacks from agent ${agent.hostname}:`, error);
+ return [];
+ }
+ });
+
+ await invalidateAll();
+ toast.success('Remote stacks refreshed');
+ } catch (error) {
+ console.error('Failed to load agent stacks:', error);
+ toast.error('Failed to load some remote stacks');
+ } finally {
+ loadingAgentStacks = false;
+ }
+ }
+
+ // Function to handle remote stack actions
+ async function handleRemoteStackAction(agentId: string, stackName: string, action: 'up' | 'down' | 'restart' | 'pull' | 'remove') {
+ const actionId = `${agentId}:${stackName}:${action}`;
+ isRemoteActionLoading = actionId;
+
+ try {
+ let taskType: string;
+ let payload: any;
+
+ switch (action) {
+ case 'up':
+ taskType = 'compose_up';
+ payload = { project_name: stackName };
+ break;
+ case 'down':
+ taskType = 'compose_down';
+ payload = { project_name: stackName };
+ break;
+ case 'restart':
+ taskType = 'compose_restart';
+ payload = { project_name: stackName };
+ break;
+ case 'remove':
+ taskType = 'compose_remove';
+ payload = { project_name: stackName };
+ break;
+ case 'pull':
+ taskType = 'compose_pull';
+ payload = { project_name: stackName };
+ break;
+ }
+
+ // Send the task to the agent
+ const response = await fetch(`/api/agents/${agentId}/tasks`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ type: taskType,
+ payload: payload
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || `Failed to ${action} stack`);
+ }
+
+ const result = await response.json();
+ const taskId = result.task?.id;
+
+ if (!taskId) {
+ throw new Error('No task ID returned from agent');
+ }
+
+ // Poll for task completion
+ const pollTask = async (taskId: string): Promise<boolean> => {
+ const maxAttempts = 30; // 30 seconds timeout
+ const delay = 1000; // 1 second between polls
+
+ for (let i = 0; i < maxAttempts; i++) {
+ await new Promise((resolve) => setTimeout(resolve, delay));
+
+ try {
+ const taskResponse = await fetch(`/api/agents/${agentId}/tasks/${taskId}`);
+ if (!taskResponse.ok) continue;
+
+ const taskData = await taskResponse.json();
+ const taskStatus = taskData.task?.status;
+
+ if (taskStatus === 'completed') {
+ return true;
+ } else if (taskStatus === 'failed') {
+ throw new Error(taskData.task?.error || 'Task failed');
+ }
+ // Continue polling if still pending/running
+ } catch (pollError) {
+ console.warn(`Polling attempt ${i + 1} failed:`, pollError);
+ }
+ }
+
+ throw new Error('Task polling timed out');
+ };
+
+ // Wait for the task to complete
+ await pollTask(taskId);
+
+ // Handle pull action with follow-up
+ if (action === 'pull') {
+ toast.success(`Images pulled for ${stackName}`);
+
+ // Execute the up command after pull
+ const upResponse = await fetch(`/api/agents/${agentId}/tasks`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ type: 'compose_up',
+ payload: { project_name: stackName }
+ })
+ });
+
+ if (upResponse.ok) {
+ const upResult = await upResponse.json();
+ if (upResult.task?.id) {
+ await pollTask(upResult.task.id);
+ }
+ }
+
+ toast.success(`Stack ${stackName} redeployed with new images`);
+ } else if (action === 'remove') {
+ toast.success(`Stack ${stackName} destroyed successfully`);
+ } else {
+ toast.success(`Stack ${stackName} ${action === 'up' ? 'started' : action === 'down' ? 'stopped' : 'restarted'} successfully`);
+ }
+
+ // Refresh the list of stacks after the action actually completes
+ await invalidateAll();
+ } catch (error) {
+ console.error(`Failed to ${action} remote stack:`, error);
+ toast.error(`Failed to ${action} stack: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ } finally {
+ isRemoteActionLoading = null;
+ }
+ }
+
+ // // Load agent stacks on component mount
+ // $effect(() => {
+ // if (agents.length > 0) {
+ // loadAgentStacks();
+ // }
+ // });
</script>
<div class="space-y-6">
@@ -205,18 +424,27 @@
<div class="flex items-center justify-between">
<div>
<Card.Title>Stack List</Card.Title>
+ {#if loadingAgentStacks}
+ <p class="text-sm text-muted-foreground">Loading remote stacks...</p>
+ {/if}
</div>
<div class="flex items-center gap-2">
+ <Button variant="outline" size="sm" onclick={loadAgentStacks} disabled={loadingAgentStacks}>
+ {#if loadingAgentStacks}
+ <Loader2 class="size-4 animate-spin mr-2" />
+ {/if}
+ Refresh Remote
+ </Button>
<ArcaneButton action="create" customLabel="Create Stack" onClick={() => goto(`/stacks/new`)} />
</div>
</div>
</Card.Header>
<Card.Content>
- {#if stacks && stacks.length > 0}
+ {#if allStacks && allStacks.length > 0}
<UniversalTable
- data={stacks}
+ data={allStacks}
columns={[
- { accessorKey: 'Name', header: 'Name' },
+ { accessorKey: 'name', header: 'Name' },
{ accessorKey: 'serviceCount', header: 'Services' },
{ accessorKey: 'status', header: 'Status' },
{ accessorKey: 'source', header: 'Source' },
@@ -236,18 +464,28 @@
filterPlaceholder: 'Search stacks...',
noResultsMessage: 'No stacks found'
}}
- bind:selectedIds
>
{#snippet rows({ item })}
- {@const stateVariant = statusVariantMap[item.status.toLowerCase()]}
+ {@const stateVariant = item.status ? statusVariantMap[item.status.toLowerCase()] : 'gray'}
<Table.Cell>
{#if item.isExternal}
- {item.name}
+ <div class="flex items-center gap-2">
+ {item.name}
+ </div>
{:else}
<div class="flex items-center gap-2">
- <a class="font-medium hover:underline" href="/stacks/{item.id}/">
- {item.name}
- </a>
+ {#if item.isRemote}
+ <a class="font-medium hover:underline" href="/stacks/agent/{item.agentId}/{item.name}">
+ {item.name}
+ </a>
+ <span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded-full">
+ On {item.agentId}
+ </span>
+ {:else}
+ <a class="font-medium hover:underline" href="/stacks/{item.id}/">
+ {item.name}
+ </a>
+ {/if}
{#if item.isLegacy}
<span title="This stack uses the legacy layout. Migrate to the new layout from the dropdown menu." class="ml-1 flex items-center" style="filter: drop-shadow(0 0 4px #fbbf24);">
<AlertCircle class="text-amber-400 animate-pulse size-4" />
@@ -258,11 +496,87 @@
</Table.Cell>
<Table.Cell>{item.serviceCount}</Table.Cell>
<Table.Cell><StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.status)} /></Table.Cell>
- <Table.Cell><StatusBadge variant={item.isExternal ? 'amber' : 'green'} text={item.isExternal ? 'External' : 'Managed'} /></Table.Cell>
+ <Table.Cell>
+ <StatusBadge variant={item.isExternal ? 'amber' : item.isRemote ? 'blue' : 'green'} text={item.isExternal ? 'External' : item.isRemote ? 'Remote' : 'Managed'} />
+ </Table.Cell>
<Table.Cell>{item.createdAt}</Table.Cell>
<Table.Cell>
{#if item.isExternal}
<ArcaneButton action="pull" customLabel="Import" onClick={() => handleImportStack(item.id, item.name)} loading={isLoading.import} disabled={isLoading.import} />
+ {:else if item.isRemote}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
+ <span class="sr-only">Open menu</span>
+ <Ellipsis />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item onclick={() => goto(`/stacks/agent/${item.agentId}/${item.name}`)} disabled={!!isRemoteActionLoading}>
+ <Pen class="size-4" />
+ Edit
+ </DropdownMenu.Item>
+
+ {#if item.status !== 'running'}
+ <DropdownMenu.Item onclick={() => handleRemoteStackAction(item.agentId || '', item.name, 'up')} disabled={!!isRemoteActionLoading}>
+ {#if isRemoteActionLoading === `${item.agentId}:${item.name}:up`}
+ <Loader2 class="animate-spin size-4" />
+ {:else}
+ <Play class="size-4" />
+ {/if}
+ Start
+ </DropdownMenu.Item>
+ {:else}
+ <DropdownMenu.Item onclick={() => handleRemoteStackAction(item.agentId || '', item.name, 'restart')} disabled={!!isRemoteActionLoading}>
+ {#if isRemoteActionLoading === `${item.agentId}:${item.name}:restart`}
+ <Loader2 class="animate-spin size-4" />
+ {:else}
+ <RotateCcw class="size-4" />
+ {/if}
+ Restart
+ </DropdownMenu.Item>
+
+ <DropdownMenu.Item onclick={() => handleRemoteStackAction(item.agentId || '', item.name, 'down')} disabled={!!isRemoteActionLoading}>
+ {#if isRemoteActionLoading === `${item.agentId}:${item.name}:down`}
+ <Loader2 class="animate-spin size-4" />
+ {:else}
+ <StopCircle class="size-4" />
+ {/if}
+ Stop
+ </DropdownMenu.Item>
+ {/if}
+
+ <DropdownMenu.Item onclick={() => handleRemoteStackAction(item.agentId || '', item.name, 'pull')} disabled={!!isRemoteActionLoading}>
+ {#if isRemoteActionLoading === `${item.agentId}:${item.name}:pull`}
+ <Loader2 class="animate-spin size-4" />
+ {:else}
+ <RotateCcw class="size-4" />
+ {/if}
+ Pull & Redeploy
+ </DropdownMenu.Item>
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleRemoveRemoteStack(item.agentId || '', item.name)} disabled={!!isRemoteActionLoading}>
+ {#if isRemoteActionLoading}
+ <Loader2 class="animate-spin size-4" />
+ {:else}
+ <Trash2 class="size-4" />
+ {/if}
+ Remove
+ </DropdownMenu.Item>
+
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item onclick={() => goto(`/agents/${item.agentId}`)}>
+ <Inspect class="size-4" />
+ View Agent
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
{:else}
<DropdownMenu.Root>
<DropdownMenu.Trigger>
diff --git a/src/routes/stacks/[stackId]/+page.server.ts b/src/routes/stacks/[stackId]/+page.server.ts
index 303c981bc..015ade5c0 100644
--- a/src/routes/stacks/[stackId]/+page.server.ts
+++ b/src/routes/stacks/[stackId]/+page.server.ts
@@ -1,6 +1,7 @@
import { getStack } from '$lib/services/docker/stack-service';
import { getSettings } from '$lib/services/settings-service';
import { getContainer } from '$lib/services/docker/container-service';
+import { listAgents } from '$lib/services/agent/agent-manager';
import type { PageServerLoad } from './$types';
import { tryCatch } from '$lib/utils/try-catch';
import type { PortBinding, ContainerInspectInfo } from 'dockerode';
@@ -8,6 +9,7 @@ import type { PortBinding, ContainerInspectInfo } from 'dockerode';
export const load: PageServerLoad = async ({ params }) => {
const { stackId } = params;
+ // Handle local stacks only
const stackResult = await tryCatch(getStack(stackId));
if (stackResult.error || !stackResult.data) {
console.error(`Error loading stack ${stackId}:`, stackResult.error);
@@ -23,7 +25,8 @@ export const load: PageServerLoad = async ({ params }) => {
originalComposeContent: '',
originalEnvContent: '',
autoUpdate: false
- }
+ },
+ isAgentStack: false
};
}
const stack = stackResult.data;
@@ -73,35 +76,28 @@ export const load: PageServerLoad = async ({ params }) => {
}
}
+ const agents = await listAgents();
+
+ // Calculate actual status on server side
+ const now = new Date();
+ const timeout = 5 * 60 * 1000; // 5 minutes
+
+ const agentsWithStatus = agents.map((agent) => {
+ const lastSeen = new Date(agent.lastSeen);
+ const timeSinceLastSeen = now.getTime() - lastSeen.getTime();
+
+ return {
+ ...agent,
+ status: timeSinceLastSeen > timeout ? 'offline' : agent.status
+ };
+ });
+
return {
stack,
servicePorts,
editorState,
- settings
+ settings,
+ agents: agentsWithStatus,
+ isAgentStack: false
};
};
-
-// export const actions: Actions = {
-// update: async ({ params, request }) => {
-// const { stackId } = params;
-// const formData = await request.formData();
-
-// const name = formData.get('name')?.toString() || '';
-// const composeContent = formData.get('composeContent')?.toString() || '';
-// const autoUpdate = formData.get('autoUpdate') === 'on';
-
-// const result = await tryCatch(updateStack(stackId, { name, composeContent, autoUpdate }));
-// if (!result.error) {
-// return {
-// success: true,
-// message: 'Stack updated successfully'
-// };
-// } else {
-// console.error('Error updating stack:', result.error);
-// return {
-// success: false,
-// error: result.error instanceof Error ? result.error.message : 'Failed to update stack'
-// };
-// }
-// }
-// };
diff --git a/src/routes/stacks/[stackId]/+page.svelte b/src/routes/stacks/[stackId]/+page.svelte
index 03e268bdf..a5900a791 100644
--- a/src/routes/stacks/[stackId]/+page.svelte
+++ b/src/routes/stacks/[stackId]/+page.svelte
@@ -3,7 +3,7 @@
import type { Stack, StackService, StackPort } from '$lib/types/docker/stack.type';
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import { ArrowLeft, AlertCircle, FileStack, Layers, ArrowRight, ExternalLink, RefreshCw, Terminal, Settings, Activity, FileText, Play, Square, RotateCcw, Trash2 } from '@lucide/svelte';
+ import { ArrowLeft, AlertCircle, FileStack, Layers, ArrowRight, ExternalLink, RefreshCw, Terminal, Settings, Activity, FileText, Play, Square, RotateCcw, Trash2, Send, Users, Loader2 } from '@lucide/svelte';
import * as Alert from '$lib/components/ui/alert/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { Label } from '$lib/components/ui/label/index.js';
@@ -20,6 +20,8 @@
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import ArcaneButton from '$lib/components/arcane-button.svelte';
import LogViewer from '$lib/components/LogViewer.svelte';
+ import * as Dialog from '$lib/components/ui/dialog/index.js';
+ import * as Select from '$lib/components/ui/select/index.js';
const stackApi = new StackAPIService();
@@ -54,6 +56,13 @@
let isStackLogsStreaming = $state(false);
let stackLogViewer = $state<LogViewer>();
+ let deployDialogOpen = $state(false);
+ let deploying = $state(false);
+ let selectedAgentId = $state('');
+
+ // Get online agents for deployment
+ const onlineAgents = $derived((data.agents || []).filter((agent) => agent.status === 'online'));
+
$effect(() => {
isLoading.deploying = false;
isLoading.stopping = false;
@@ -91,6 +100,53 @@
});
}
+ async function handleDeployToAgent() {
+ if (!selectedAgentId) {
+ toast.error('Please select an agent for deployment');
+ return;
+ }
+
+ const selectedAgent = onlineAgents.find((agent) => agent.id === selectedAgentId);
+ if (!selectedAgent) {
+ toast.error('Selected agent not found or offline');
+ return;
+ }
+
+ if (!data.stack) {
+ toast.error('Stack data not available');
+ return;
+ }
+
+ deploying = true;
+ try {
+ const response = await fetch(`/api/agents/${selectedAgentId}/deploy/stack`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ stackName: data.stack.name,
+ composeContent: data.stack.composeContent,
+ envContent: data.stack.envContent,
+ mode: 'compose'
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || `Failed to deploy stack: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ toast.success(`Stack "${data.stack?.name || 'Unknown'}" deployed to agent ${selectedAgent.hostname}!`);
+ deployDialogOpen = false;
+ selectedAgentId = '';
+ } catch (error) {
+ console.error('Deploy error:', error);
+ toast.error(error instanceof Error ? error.message : 'Failed to deploy stack');
+ } finally {
+ deploying = false;
+ }
+ }
+
function getHostForService(service: StackService): string {
if (!service || !service.networkSettings?.Networks) return baseServerUrl;
@@ -204,6 +260,12 @@
}}
onActionComplete={() => invalidateAll()}
/>
+ {#if onlineAgents.length > 0}
+ <Button variant="outline" size="sm" onclick={() => (deployDialogOpen = true)} disabled={Object.values(isLoading).some(Boolean)}>
+ <Send class="size-4 mr-2" />
+ Deploy to Agent
+ </Button>
+ {/if}
</div>
</div>
</div>
@@ -506,3 +568,47 @@
</div>
{/if}
</div>
+
+<Dialog.Root bind:open={deployDialogOpen}>
+ <Dialog.Content>
+ <Dialog.Header>
+ <Dialog.Title>Deploy Stack to Agent</Dialog.Title>
+ <Dialog.Description>
+ Deploy "{data.stack?.name || 'Unknown Stack'}" to a remote agent
+ </Dialog.Description>
+ </Dialog.Header>
+ <div class="space-y-4 py-4">
+ <div class="space-y-2">
+ <Label for="agent-select">Select Agent</Label>
+ <Select.Root type="single" bind:value={selectedAgentId} disabled={deploying}>
+ <Select.Trigger>
+ {selectedAgentId}
+ </Select.Trigger>
+ <Select.Content>
+ {#each onlineAgents as agent}
+ <Select.Item value={agent.id}>
+ <div class="flex items-center gap-2">
+ <div class="size-2 rounded-full bg-green-500"></div>
+ <span>{agent.hostname}</span>
+ <span class="text-xs text-muted-foreground">({agent.platform})</span>
+ </div>
+ </Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ <p class="text-xs text-muted-foreground">This will deploy the current stack configuration to the selected agent.</p>
+ </div>
+ </div>
+ <Dialog.Footer>
+ <Button variant="outline" onclick={() => (deployDialogOpen = false)} disabled={deploying}>Cancel</Button>
+ <Button onclick={handleDeployToAgent} disabled={!selectedAgentId || deploying}>
+ {#if deploying}
+ <Loader2 class="size-4 mr-2 animate-spin" />
+ {:else}
+ <Send class="size-4 mr-2" />
+ {/if}
+ Deploy
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+</Dialog.Root>
diff --git a/src/routes/stacks/agent/[agentId]/[stackName]/+page.server.ts b/src/routes/stacks/agent/[agentId]/[stackName]/+page.server.ts
new file mode 100644
index 000000000..8f7bc984f
--- /dev/null
+++ b/src/routes/stacks/agent/[agentId]/[stackName]/+page.server.ts
@@ -0,0 +1,37 @@
+import { error } from '@sveltejs/kit';
+import type { PageServerLoad } from './$types';
+import { getAgent } from '$lib/services/agent/agent-manager';
+import { getStacksFromAgent } from '$lib/services/agent/agent-stack-service';
+
+export const load: PageServerLoad = async ({ params, fetch }) => {
+ const { agentId, stackName } = params;
+
+ try {
+ // Get the agent
+ const agent = await getAgent(agentId);
+ if (!agent) {
+ throw error(404, 'Agent not found');
+ }
+
+ if (agent.status !== 'online') {
+ throw error(400, `Agent is not online (status: ${agent.status})`);
+ }
+
+ // Get the specific stack from the agent
+ const stacks = await getStacksFromAgent(agent, { fetch });
+ const stack = stacks.find((s) => s.name === stackName);
+
+ if (!stack) {
+ throw error(404, 'Stack not found on agent');
+ }
+
+ return {
+ agent,
+ stack,
+ stackName
+ };
+ } catch (err) {
+ console.error('Error loading agent stack:', err);
+ throw error(500, 'Failed to load agent stack');
+ }
+};
diff --git a/src/routes/stacks/agent/[agentId]/[stackName]/+page.svelte b/src/routes/stacks/agent/[agentId]/[stackName]/+page.svelte
new file mode 100644
index 000000000..95546301c
--- /dev/null
+++ b/src/routes/stacks/agent/[agentId]/[stackName]/+page.svelte
@@ -0,0 +1,397 @@
+<script lang="ts">
+ import type { PageData } from './$types';
+ import * as Card from '$lib/components/ui/card';
+ import { Button } from '$lib/components/ui/button';
+ import { Input } from '$lib/components/ui/input';
+ import { Label } from '$lib/components/ui/label';
+ import { ArrowLeft, AlertCircle, FileStack, Layers, Terminal, Settings, Activity, Users, Play, Square, RotateCcw, Loader2 } from '@lucide/svelte';
+ import * as Alert from '$lib/components/ui/alert';
+ import { goto, invalidateAll } from '$app/navigation';
+ import { toast } from 'svelte-sonner';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { statusVariantMap } from '$lib/types/statuses';
+ import { capitalizeFirstLetter } from '$lib/utils/string.utils';
+ import YamlEditor from '$lib/components/yaml-editor.svelte';
+ import EnvEditor from '$lib/components/env-editor.svelte';
+ import ArcaneButton from '$lib/components/arcane-button.svelte';
+
+ let { data }: { data: PageData } = $props();
+ let { agent, stack, stackName } = data;
+
+ let name = $state(stackName);
+ let composeContent = $state(stack.composeContent || '');
+ let envContent = $state(stack.envContent || '');
+ let originalName = stackName;
+ let originalComposeContent = stack.composeContent || '';
+ let originalEnvContent = stack.envContent || '';
+
+ let isLoading = $state({
+ deploying: false,
+ stopping: false,
+ restarting: false,
+ saving: false
+ });
+
+ let hasChanges = $derived(name !== originalName || composeContent !== originalComposeContent || envContent !== originalEnvContent);
+
+ let activeSection = $state<string>('overview');
+
+ async function handleSaveChanges() {
+ if (!hasChanges) return;
+
+ isLoading.saving = true;
+ try {
+ const response = await fetch(`/api/agents/${agent.id}/tasks`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ type: 'stack_update',
+ payload: {
+ project_name: stackName,
+ compose_content: composeContent,
+ env_content: envContent
+ }
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to save stack');
+ }
+
+ toast.success('Stack updated successfully!');
+
+ // Update original values to reflect saved state
+ originalComposeContent = composeContent;
+ originalEnvContent = envContent;
+
+ await invalidateAll();
+ } catch (error) {
+ console.error('Failed to save stack:', error);
+ toast.error(`Failed to save stack: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ } finally {
+ isLoading.saving = false;
+ }
+ }
+
+ async function handleStackAction(action: 'up' | 'down' | 'restart') {
+ const actionKey = action === 'up' ? 'deploying' : action === 'down' ? 'stopping' : 'restarting';
+ isLoading[actionKey] = true;
+
+ try {
+ let taskType: string;
+ switch (action) {
+ case 'up':
+ taskType = 'compose_up';
+ break;
+ case 'down':
+ taskType = 'compose_down';
+ break;
+ case 'restart':
+ taskType = 'compose_restart';
+ break;
+ }
+
+ const response = await fetch(`/api/agents/${agent.id}/tasks`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ type: taskType,
+ payload: { project_name: stackName }
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || `Failed to ${action} stack`);
+ }
+
+ toast.success(`Stack ${action === 'up' ? 'started' : action === 'down' ? 'stopped' : 'restarted'} successfully`);
+ await invalidateAll();
+ } catch (error) {
+ console.error(`Failed to ${action} stack:`, error);
+ toast.error(`Failed to ${action} stack: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ } finally {
+ isLoading[actionKey] = false;
+ }
+ }
+
+ // Navigation sections for single-page layout
+ const navigationSections = [
+ { id: 'overview', label: 'Overview', icon: FileStack },
+ { id: 'services', label: 'Services', icon: Layers },
+ { id: 'config', label: 'Configuration', icon: Settings }
+ ] as const;
+
+ type SectionId = (typeof navigationSections)[number]['id'];
+
+ function scrollToSection(sectionId: SectionId) {
+ activeSection = sectionId;
+ const element = document.getElementById(sectionId);
+ if (element) {
+ element.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ }
+ }
+</script>
+
+<div class="min-h-screen bg-background">
+ {#if stack}
+ <!-- Fixed Header -->
+ <div class="sticky top-0 z-10 bg-background/95 backdrop-blur border-b">
+ <div class="max-w-full px-4 py-3">
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-3">
+ <Button variant="ghost" size="sm" href="/stacks">
+ <ArrowLeft class="size-4 mr-2" />
+ Back
+ </Button>
+ <div class="h-4 w-px bg-border"></div>
+ <div class="flex items-center gap-2">
+ <h1 class="text-lg font-semibold truncate max-w-[300px]" title={stack.name}>
+ {stack.name}
+ </h1>
+ <span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded-full">
+ {agent.hostname}
+ </span>
+ {#if stack.status}
+ <StatusBadge variant={statusVariantMap[stack.status.toLowerCase()] || 'gray'} text={capitalizeFirstLetter(stack.status)} />
+ {/if}
+ </div>
+ </div>
+
+ <div class="flex items-center gap-2">
+ <!-- Agent Stack Actions -->
+ <Button variant="outline" size="sm" onclick={() => handleStackAction('up')} disabled={Object.values(isLoading).some(Boolean) || stack.status === 'running'}>
+ {#if isLoading.deploying}
+ <Loader2 class="size-4 mr-2 animate-spin" />
+ {:else}
+ <Play class="size-4 mr-2" />
+ {/if}
+ Start
+ </Button>
+
+ <Button variant="outline" size="sm" onclick={() => handleStackAction('restart')} disabled={Object.values(isLoading).some(Boolean)}>
+ {#if isLoading.restarting}
+ <Loader2 class="size-4 mr-2 animate-spin" />
+ {:else}
+ <RotateCcw class="size-4 mr-2" />
+ {/if}
+ Restart
+ </Button>
+
+ <Button variant="outline" size="sm" onclick={() => handleStackAction('down')} disabled={Object.values(isLoading).some(Boolean) || stack.status !== 'running'}>
+ {#if isLoading.stopping}
+ <Loader2 class="size-4 mr-2 animate-spin" />
+ {:else}
+ <Square class="size-4 mr-2" />
+ {/if}
+ Stop
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="flex h-[calc(100vh-64px)]">
+ <!-- Fixed Sidebar Navigation -->
+ <div class="w-48 shrink-0 border-r bg-background/50">
+ <div class="sticky top-16 p-3">
+ <nav class="space-y-1">
+ {#each navigationSections as section}
+ {@const IconComponent = section.icon}
+ <button
+ onclick={() => scrollToSection(section.id)}
+ class="w-full flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-md transition-colors
+ {activeSection === section.id ? 'bg-primary/10 text-primary border border-primary/20' : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'}"
+ >
+ <IconComponent class="size-4 shrink-0" />
+ <span class="truncate">{section.label}</span>
+ {#if section.id === 'services' && stack.serviceCount}
+ <span class="ml-auto text-xs bg-muted px-1.5 py-0.5 rounded shrink-0">
+ {stack.serviceCount}
+ </span>
+ {/if}
+ </button>
+ {/each}
+ </nav>
+ </div>
+ </div>
+
+ <!-- Main Content -->
+ <div class="flex-1 overflow-y-auto">
+ <div class="p-6 max-w-none">
+ <div class="space-y-8">
+ <!-- Overview Section -->
+ <section id="overview" class="scroll-mt-20">
+ <h2 class="text-xl font-semibold mb-6 flex items-center gap-2">
+ <FileStack class="size-5" />
+ Overview
+ <span class="text-sm font-normal text-muted-foreground">(Remote Agent)</span>
+ </h2>
+
+ <!-- Summary Cards -->
+ <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
+ <Card.Root class="border">
+ <Card.Content class="p-6 flex items-center justify-between">
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">Services</p>
+ <p class="text-2xl font-bold">{stack.serviceCount || 0}</p>
+ </div>
+ <div class="bg-primary/10 p-3 rounded-full">
+ <Layers class="text-primary size-5" />
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root class="border">
+ <Card.Content class="p-6 flex items-center justify-between">
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">Running</p>
+ <p class="text-2xl font-bold">{stack.runningCount || 0}</p>
+ </div>
+ <div class="bg-green-500/10 p-3 rounded-full">
+ <Activity class="text-green-500 size-5" />
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root class="border">
+ <Card.Content class="p-6 flex items-center justify-between">
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">Agent</p>
+ <p class="text-lg font-medium">{agent.hostname}</p>
+ </div>
+ <div class="bg-blue-500/10 p-3 rounded-full">
+ <Users class="text-blue-500 size-5" />
+ </div>
+ </Card.Content>
+ </Card.Root>
+ </div>
+ </section>
+
+ <!-- Services Section -->
+ <section id="services" class="scroll-mt-20">
+ <h2 class="text-xl font-semibold mb-6 flex items-center gap-2">
+ <Layers class="size-5" />
+ Services ({stack.serviceCount || 0})
+ </h2>
+
+ <Card.Root class="border">
+ <Card.Content class="p-6">
+ {#if stack.services && stack.services.length > 0}
+ <div class="space-y-4">
+ {#each stack.services as service (service.id || service.name)}
+ {@const status = service.state?.Status || 'unknown'}
+ {@const variant = statusVariantMap[status.toLowerCase()] || 'gray'}
+
+ <!-- Agent Service (not clickable) -->
+ <div class="flex items-center justify-between p-4 border rounded-lg bg-muted/20">
+ <div class="flex items-center gap-3">
+ <div class="bg-muted/50 p-2 rounded-full">
+ <Layers class="text-muted-foreground size-4" />
+ </div>
+ <div>
+ <p class="font-medium">{service.name}</p>
+ <p class="text-sm text-muted-foreground">Remote service</p>
+ </div>
+ </div>
+ <StatusBadge {variant} text={capitalizeFirstLetter(status)} />
+ </div>
+ {/each}
+ </div>
+ {:else}
+ <div class="text-center py-12">
+ <div class="mb-4 rounded-full bg-muted/50 flex items-center justify-center mx-auto size-16">
+ <Layers class="size-6 text-muted-foreground" />
+ </div>
+ <div class="text-muted-foreground">No services defined in this stack</div>
+ </div>
+ {/if}
+ </Card.Content>
+ </Card.Root>
+ </section>
+
+ <!-- Configuration Section -->
+ <section id="config" class="scroll-mt-20">
+ <div class="flex items-center justify-between mb-6">
+ <h2 class="text-xl font-semibold flex items-center gap-2">
+ <Settings class="size-5" />
+ Configuration
+ <span class="text-sm font-normal text-muted-foreground">(Remote)</span>
+ </h2>
+ <!-- Save Button -->
+ {#if hasChanges}
+ <ArcaneButton action="save" loading={isLoading.saving} onClick={handleSaveChanges} disabled={!hasChanges} label="Save Changes" loadingLabel="Saving..." class="bg-green-600 hover:bg-green-700 text-white" />
+ {/if}
+ </div>
+
+ <!-- Stack Name Field -->
+ <Card.Root class="border mb-6">
+ <Card.Header class="pb-4">
+ <Card.Title>Stack Settings</Card.Title>
+ </Card.Header>
+ <Card.Content>
+ <div class="max-w-md">
+ <Label for="name" class="mb-2 block">Stack Name</Label>
+ <Input type="text" id="name" name="name" bind:value={name} required disabled={true} />
+ <p class="text-sm text-muted-foreground mt-2">Agent stack names cannot be changed from the web interface.</p>
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <!-- Editors -->
+ <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
+ <!-- Compose Editor -->
+ <div class="xl:col-span-2">
+ <Card.Root class="border">
+ <Card.Header class="pb-4">
+ <Card.Title>Docker Compose File</Card.Title>
+ </Card.Header>
+ <Card.Content>
+ <div class="border rounded-lg overflow-hidden h-[600px]">
+ <YamlEditor bind:value={composeContent} readOnly={Object.values(isLoading).some(Boolean)} />
+ </div>
+ <p class="text-sm text-muted-foreground mt-2">
+ Edit your <span class="font-medium">compose.yaml</span> file directly. Changes will be applied to the remote agent.
+ </p>
+ </Card.Content>
+ </Card.Root>
+ </div>
+
+ <!-- Environment Editor -->
+ <div>
+ <Card.Root class="border">
+ <Card.Header class="pb-4">
+ <Card.Title>Environment (.env)</Card.Title>
+ </Card.Header>
+ <Card.Content>
+ <div class="border rounded-lg overflow-hidden h-[600px]">
+ <EnvEditor bind:value={envContent} readOnly={Object.values(isLoading).some(Boolean)} />
+ </div>
+ <p class="text-sm text-muted-foreground mt-2">Define environment variables in KEY=value format. Variables will be applied on the remote agent.</p>
+ </Card.Content>
+ </Card.Root>
+ </div>
+ </div>
+ </section>
+ </div>
+ </div>
+ </div>
+ </div>
+ {:else}
+ <!-- Not Found State -->
+ <div class="min-h-screen flex items-center justify-center">
+ <div class="text-center">
+ <div class="rounded-full bg-muted/50 p-6 mb-6 inline-flex">
+ <FileStack class="text-muted-foreground size-10" />
+ </div>
+ <h2 class="text-2xl font-medium mb-3">Stack Not Found</h2>
+ <p class="text-center text-muted-foreground max-w-md mb-8">Could not load agent stack data. The stack may not exist on the agent or the agent may be offline.</p>
+ <Button variant="outline" href="/stacks">
+ <ArrowLeft class="mr-2 size-4" />
+ Back to Stacks
+ </Button>
+ </div>
+ </div>
+ {/if}
+</div>
diff --git a/src/routes/stacks/new/+page.server.ts b/src/routes/stacks/new/+page.server.ts
index e45c73d51..0176bbabe 100644
--- a/src/routes/stacks/new/+page.server.ts
+++ b/src/routes/stacks/new/+page.server.ts
@@ -1,17 +1,35 @@
import { TemplateService } from '$lib/services/template-service';
import { defaultComposeTemplate } from '$lib/constants';
import type { PageServerLoad } from './$types';
+import { listAgents } from '$lib/services/agent/agent-manager';
-export const load = (async () => {
+export const load: PageServerLoad = async () => {
try {
const templateService = new TemplateService();
const [allTemplates, envTemplate] = await Promise.all([templateService.loadAllTemplates(), TemplateService.getEnvTemplate()]);
+ const agents = await listAgents();
+
+ // Calculate actual status on server side
+ const now = new Date();
+ const timeout = 5 * 60 * 1000; // 5 minutes
+
+ const agentsWithStatus = agents.map((agent) => {
+ const lastSeen = new Date(agent.lastSeen);
+ const timeSinceLastSeen = now.getTime() - lastSeen.getTime();
+
+ return {
+ ...agent,
+ status: timeSinceLastSeen > timeout ? 'offline' : agent.status
+ };
+ });
+
return {
composeTemplates: allTemplates,
envTemplate,
- defaultTemplate: defaultComposeTemplate
+ defaultTemplate: defaultComposeTemplate,
+ agents: agentsWithStatus
};
} catch (error) {
console.error('Error loading templates:', error);
@@ -20,7 +38,8 @@ export const load = (async () => {
return {
composeTemplates: [],
envTemplate: defaultComposeTemplate,
- defaultTemplate: defaultComposeTemplate
+ defaultTemplate: defaultComposeTemplate,
+ agents: []
};
}
-}) satisfies PageServerLoad;
+};
diff --git a/src/routes/stacks/new/+page.svelte b/src/routes/stacks/new/+page.svelte
index 654386420..aa92e3e6c 100644
--- a/src/routes/stacks/new/+page.svelte
+++ b/src/routes/stacks/new/+page.svelte
@@ -1,7 +1,7 @@
<script lang="ts">
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import { ArrowLeft, FileStack, Terminal, Copy, Loader2, Wand } from '@lucide/svelte';
+ import { ArrowLeft, FileStack, Terminal, Copy, Loader2, Wand, Send } from '@lucide/svelte';
import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { Label } from '$lib/components/ui/label/index.js';
@@ -21,6 +21,8 @@
import TemplateSelectionDialog from '$lib/components/template-selection-dialog.svelte';
import type { ComposeTemplate } from '$lib/services/template-service';
import type { PageData } from './$types';
+ import * as Select from '$lib/components/ui/select/index.js';
+ import type { Agent } from '$lib/types/agent.type';
let { data }: { data: PageData } = $props();
@@ -28,12 +30,17 @@
let saving = $state(false);
let converting = $state(false);
let showTemplateDialog = $state(false);
+ let deployToAgent = $state(false);
+ let selectedAgentId = $state('');
+ let selectedAgent: Agent | undefined = $state();
let name = $state('');
let composeContent = $state(defaultComposeTemplate);
let envContent = $state(data.envTemplate || defaultEnvTemplate);
let dockerRunCommand = $state('');
+ // Get online agents for deployment
+ const onlineAgents = $derived(data.agents || []);
// Initialize with default template if available
$effect(() => {
if (data.defaultTemplate && !composeContent) {
@@ -41,7 +48,20 @@
}
});
+ // Update selectedAgentId when selectedAgent changes
+ $effect(() => {
+ selectedAgentId = selectedAgent?.id || '';
+ });
+
async function handleSubmit() {
+ if (deployToAgent && selectedAgentId) {
+ await handleDeployToAgent();
+ } else {
+ await handleCreateStack();
+ }
+ }
+
+ async function handleCreateStack() {
handleApiResultWithCallbacks({
result: await tryCatch(stackApi.create(name, composeContent, envContent)),
message: 'Failed to Create Stack',
@@ -54,6 +74,47 @@
});
}
+ async function handleDeployToAgent() {
+ if (!selectedAgentId) {
+ toast.error('Please select an agent for deployment');
+ return;
+ }
+
+ const selectedAgent = onlineAgents.find((agent) => agent.id === selectedAgentId);
+ if (!selectedAgent) {
+ toast.error('Selected agent not found or offline');
+ return;
+ }
+
+ saving = true;
+ try {
+ const response = await fetch(`/api/agents/${selectedAgentId}/deploy/stack`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ stackName: name,
+ composeContent,
+ envContent,
+ mode: 'compose'
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || `Failed to deploy stack: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ toast.success(`Stack "${name}" deployed to agent ${selectedAgent.hostname}!`);
+ goto(`/agents/${selectedAgentId}`);
+ } catch (error) {
+ console.error('Deploy error:', error);
+ toast.error(error instanceof Error ? error.message : 'Failed to deploy stack');
+ } finally {
+ saving = false;
+ }
+ }
+
async function handleConvertDockerRun() {
if (!dockerRunCommand.trim()) {
toast.error('Please enter a docker run command');
@@ -176,8 +237,43 @@
</div>
</div>
<div class="flex items-center gap-2">
+ <!-- Agent Selection moved here -->
+ {#if onlineAgents.length > 0}
+ <div class="flex items-center gap-2">
+ <input type="checkbox" id="deployToAgent" bind:checked={deployToAgent} disabled={saving} class="rounded border-gray-300" />
+ <Label for="deployToAgent" class="text-sm font-medium whitespace-nowrap">Deploy to Agent</Label>
+ {#if deployToAgent}
+ <Select.Root type="single" bind:value={selectedAgentId} disabled={saving}>
+ <Select.Trigger class="w-[180px]">
+ <span class="text-sm">
+ {onlineAgents.find((agent) => agent.id === selectedAgentId)?.hostname || 'Select agent...'}
+ </span>
+ </Select.Trigger>
+ <Select.Content>
+ {#each onlineAgents as agent}
+ <Select.Item value={agent.id}>
+ {agent.hostname} ({agent.platform})
+ </Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ {/if}
+ </div>
+ {/if}
+
<ArcaneButton action="template" onClick={() => (showTemplateDialog = true)} loading={saving} disabled={saving || converting} />
- <ArcaneButton action="create" onClick={handleSubmit} loading={saving} disabled={!name || !composeContent} />
+ {#if deployToAgent}
+ <Button type="submit" disabled={!name || !composeContent || !selectedAgentId || saving}>
+ {#if saving}
+ <Loader2 class="size-4 mr-2 animate-spin" />
+ {:else}
+ <Send class="size-4 mr-2" />
+ {/if}
+ Deploy to Agent
+ </Button>
+ {:else}
+ <ArcaneButton action="create" onClick={handleSubmit} loading={saving} disabled={!name || !composeContent} />
+ {/if}
</div>
</div>
</Card.Header>