Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
chore: code review fixes"
Kyle Mendellc374480c537c
diff --git a/scripts/docker/entrypoint.sh b/scripts/docker/entrypoint.shindex 419b4439a..35bb721d7 100644--- a/scripts/docker/entrypoint.sh+++ b/scripts/docker/entrypoint.sh@@ -97,5 +97,4 @@ mkdir -p "$DATA_DIR"chown -R "${PUID}:${PGID}" "$DATA_DIR"echo "Entrypoint: Setup complete. Executing command as user ${APP_USER} (UID: ${PUID}, GID: ${PGID})..."-# exec su-exec "$APP_USER" "npx drizzle-kit push --force"exec su-exec "$APP_USER" "$@"diff --git a/src/db/index.ts b/src/db/index.tsindex d11947316..6cdf19d9f 100644--- a/src/db/index.ts+++ b/src/db/index.ts@@ -1,13 +1,75 @@-import 'dotenv/config';import { drizzle } from 'drizzle-orm/libsql';-let dbConnString: string;+/**+ * Determines the appropriate database connection string based on the runtime environment+ */+async function getDatabaseConnectionString(): Promise<string> {+ const fallbackConnection = 'file:data/arcane.db';-try {- const { env } = await import('$env/dynamic/private');- dbConnString = env.DB_CONN_STRING || 'file:data/arcane.db';-} catch {- dbConnString = process.env.DB_CONN_STRING || 'file:data/arcane.db';+ // Check if we're in a SvelteKit environment (browser or server-side)+ if (typeof window !== 'undefined') {+ // Browser environment - should not access database directly+ console.warn('Database connection attempted in browser environment');+ return fallbackConnection;+ }++ // Server-side environment detection+ try {+ // Try SvelteKit dynamic environment first (preferred in SvelteKit apps)+ const { env } = await import('$env/dynamic/private');+ const connectionString = env.DB_CONN_STRING;++ if (connectionString) {+ console.log('Using database connection from SvelteKit environment');+ return connectionString;+ } else {+ console.log('DB_CONN_STRING not found in SvelteKit environment, checking process.env');+ }+ } catch (error) {+ console.log('SvelteKit environment not available, falling back to process.env');+ console.debug('SvelteKit import error:', error instanceof Error ? error.message : String(error));+ }++ // Fallback to Node.js process.env+ try {+ const connectionString = process.env.DB_CONN_STRING;++ if (connectionString) {+ console.log('Using database connection from process.env');+ return connectionString;+ } else {+ console.log('DB_CONN_STRING not found in process.env, using default connection');+ }+ } catch (error) {+ console.error('Error accessing process.env:', error instanceof Error ? error.message : String(error));+ }++ console.log(`Using fallback database connection: ${fallbackConnection}`);+ return fallbackConnection;}-export const db = drizzle(dbConnString);+/**+ * Initialize database connection+ */+async function initializeDatabase() {+ try {+ const connectionString = await getDatabaseConnectionString();+ return drizzle(connectionString);+ } catch (error) {+ console.error('Failed to initialize database connection:', error instanceof Error ? error.message : String(error));+ console.log('Falling back to default SQLite database');+ return drizzle('file:data/arcane.db');+ }+}++// Create a promise that resolves to the database instance+const dbPromise = initializeDatabase();++// Export the database instance (will be a promise initially, then resolves to the actual db)+export const db = await dbPromise;++// Alternative export for cases where you need to explicitly wait for initialization+export const getDatabase = () => dbPromise;++// Export type for the database instance+export type Database = typeof db;diff --git a/src/db/schema.ts b/src/db/schema.tsindex 6ab8da97e..0e5ad108e 100644--- a/src/db/schema.ts+++ b/src/db/schema.ts@@ -37,7 +37,7 @@ export const usersTable = sqliteTable('users_table', {lastLogin: int('last_login', { mode: 'timestamp' }),createdAt: int('created_at', { mode: 'timestamp' }).notNull()- .default(sql`(unixepoch()`),+ .default(sql`(unixepoch())`),updatedAt: int('updated_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)diff --git a/src/lib/components/forms/ImagePullForm.svelte b/src/lib/components/forms/ImagePullForm.svelteindex a223fc8bb..8dc40c505 100644--- a/src/lib/components/forms/ImagePullForm.svelte+++ b/src/lib/components/forms/ImagePullForm.svelte@@ -17,6 +17,24 @@let imageRef = $state('');let tag = $state('latest');+ function buildFullImageName(imageRef: string, tag: string): string {+ const trimmedImageRef = imageRef.trim();+ const trimmedTag = tag.trim();++ // If the image already includes a tag (contains ':'), use it as-is+ if (trimmedImageRef.includes(':')) {+ return trimmedImageRef;+ }++ // If no tag specified or tag is 'latest', append ':latest'+ if (!trimmedTag || trimmedTag === 'latest') {+ return `${trimmedImageRef}:latest`;+ }++ // Otherwise, append the specified tag+ return `${trimmedImageRef}:${trimmedTag}`;+ }+async function handlePull() {if (!imageRef.trim()) {toast.error('Please enter an image name');@@ -25,8 +43,7 @@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`;+ const fullImageName = buildFullImageName(imageRef, tag);await onPull(fullImageName);onClose();diff --git a/src/lib/components/forms/QuickContainerForm.svelte b/src/lib/components/forms/QuickContainerForm.svelteindex 0009f2f50..755d4378b 100644--- a/src/lib/components/forms/QuickContainerForm.svelte+++ b/src/lib/components/forms/QuickContainerForm.svelte@@ -2,28 +2,53 @@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 PortMapping {+ host: string;+ container: string;+ }++ interface VolumeMount {+ host: string;+ container: string;+ }++ interface EnvironmentVariable {+ key: string;+ value: string;+ }++ interface ContainerConfiguration {+ imageName: string;+ containerName?: string;+ ports: PortMapping[];+ volumes: VolumeMount[];+ envVars: EnvironmentVariable[];+ detached: boolean;+ autoRemove: boolean;+ restartPolicy: 'no' | 'always' | 'unless-stopped' | 'on-failure';+ }+interface Props {agentId: string;onClose: () => void;- onRun: (data: any) => Promise<void>;+ onRun: (data: ContainerConfiguration) => Promise<void>;}- let { agentId, onClose, onRun }: Props = $props();+ let { 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 ports = $state<PortMapping[]>([]);+ let volumes = $state<VolumeMount[]>([]);+ let envVars = $state<EnvironmentVariable[]>([]);let detached = $state(true);let autoRemove = $state(false);- let restartPolicy = $state('no');+ let restartPolicy = $state<ContainerConfiguration['restartPolicy']>('no');function addPort() {ports = [...ports, { host: '', container: '' }];@@ -50,14 +75,145 @@}async function handleRun() {+ // Basic validationif (!imageName.trim()) {toast.error('Please enter an image name');return;}+ // Validate container name if provided+ if (containerName.trim()) {+ const containerNameRegex = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;+ if (!containerNameRegex.test(containerName.trim())) {+ toast.error('Container name must start with alphanumeric character and can only contain letters, numbers, underscores, periods, and hyphens');+ return;+ }+ }++ // Validate ports+ for (let i = 0; i < ports.length; i++) {+ const port = ports[i];++ // Skip empty port mappings+ if (!port.host && !port.container) continue;++ // Both host and container ports must be provided+ if (!port.host || !port.container) {+ toast.error(`Port mapping ${i + 1}: Both host and container ports must be specified`);+ return;+ }++ // Validate host port+ const hostPort = parseInt(port.host);+ if (isNaN(hostPort) || hostPort < 1 || hostPort > 65535) {+ toast.error(`Port mapping ${i + 1}: Host port must be a number between 1 and 65535`);+ return;+ }++ // Validate container port+ const containerPort = parseInt(port.container);+ if (isNaN(containerPort) || containerPort < 1 || containerPort > 65535) {+ toast.error(`Port mapping ${i + 1}: Container port must be a number between 1 and 65535`);+ return;+ }+ }++ // Check for duplicate host ports+ const hostPorts = ports.filter((p) => p.host && p.container).map((p) => parseInt(p.host));+ const uniqueHostPorts = new Set(hostPorts);+ if (hostPorts.length !== uniqueHostPorts.size) {+ toast.error('Duplicate host ports are not allowed');+ return;+ }++ // Validate volumes+ for (let i = 0; i < volumes.length; i++) {+ const volume = volumes[i];++ // Skip empty volume mappings+ if (!volume.host && !volume.container) continue;++ // Both host and container paths must be provided+ if (!volume.host || !volume.container) {+ toast.error(`Volume mapping ${i + 1}: Both host and container paths must be specified`);+ return;+ }++ // Validate host path format+ if (!volume.host.trim()) {+ toast.error(`Volume mapping ${i + 1}: Host path cannot be empty`);+ return;+ }++ // Basic path validation (should start with / on Unix systems or contain : on Windows)+ const hostPath = volume.host.trim();+ if (!hostPath.startsWith('/') && !hostPath.match(/^[a-zA-Z]:/)) {+ toast.error(`Volume mapping ${i + 1}: Host path should be an absolute path (e.g., /path/to/dir or C:/path/to/dir)`);+ return;+ }++ // Validate container path format+ const containerPath = volume.container.trim();+ if (!containerPath.startsWith('/')) {+ toast.error(`Volume mapping ${i + 1}: Container path must be an absolute path starting with /`);+ return;+ }++ // Check for reserved container paths+ const reservedPaths = ['/proc', '/sys', '/dev'];+ if (reservedPaths.some((reserved) => containerPath.startsWith(reserved))) {+ toast.error(`Volume mapping ${i + 1}: Cannot mount to reserved system path ${containerPath}`);+ return;+ }+ }++ // Check for duplicate container mount points+ const containerPaths = volumes.filter((v) => v.host && v.container).map((v) => v.container.trim());+ const uniqueContainerPaths = new Set(containerPaths);+ if (containerPaths.length !== uniqueContainerPaths.size) {+ toast.error('Duplicate container mount points are not allowed');+ return;+ }++ // Validate environment variables+ for (let i = 0; i < envVars.length; i++) {+ const envVar = envVars[i];++ // Skip empty environment variables+ if (!envVar.key && !envVar.value) continue;++ // Both key and value must be provided+ if (!envVar.key || !envVar.value) {+ toast.error(`Environment variable ${i + 1}: Both key and value must be specified`);+ return;+ }++ // Validate environment variable key format+ const envKeyRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;+ if (!envKeyRegex.test(envVar.key.trim())) {+ toast.error(`Environment variable ${i + 1}: Key must start with letter or underscore and contain only letters, numbers, and underscores`);+ return;+ }++ // Check for reserved environment variables+ const reservedEnvVars = ['PATH', 'HOME', 'USER', 'SHELL'];+ if (reservedEnvVars.includes(envVar.key.trim().toUpperCase())) {+ toast.error(`Environment variable ${i + 1}: Cannot override reserved variable ${envVar.key}`);+ return;+ }+ }++ // Check for duplicate environment variable keys+ const envKeys = envVars.filter((e) => e.key && e.value).map((e) => e.key.trim().toUpperCase());+ const uniqueEnvKeys = new Set(envKeys);+ if (envKeys.length !== uniqueEnvKeys.size) {+ toast.error('Duplicate environment variable keys are not allowed');+ return;+ }+running = true;try {- const data = {+ const data: ContainerConfiguration = {imageName: imageName.trim(),containerName: containerName.trim() || undefined,ports: ports.filter((p) => p.host && p.container),diff --git a/src/lib/components/forms/StackDeploymentForm.svelte b/src/lib/components/forms/StackDeploymentForm.svelteindex d9a1c14b9..c3bbe5bf4 100644--- a/src/lib/components/forms/StackDeploymentForm.svelte+++ b/src/lib/components/forms/StackDeploymentForm.svelte@@ -3,27 +3,41 @@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 StackDeploymentData {+ mode: 'compose' | 'template' | 'existing';+ stackName: string;+ composeContent: string;+ envContent: string;+ selectedStack?: string;+ }++ interface StackTemplate {+ id: string;+ name: string;+ description: string;+ compose: string;+ }+interface Props {agentId: string;onClose: () => void;- onDeploy: (data: any) => Promise<void>;+ onDeploy: (data: StackDeploymentData) => Promise<void>;}let { agentId, onClose, onDeploy }: Props = $props();let deploying = $state(false);- let deploymentMode = $state('compose'); // 'compose' | 'existing' | 'template'+ let deploymentMode = $state<StackDeploymentData['mode']>('compose');let stackName = $state('');let composeContent = $state('');let envContent = $state('');let selectedStack = $state('');// Pre-made templates for easy deployment- const templates = [+ const templates: StackTemplate[] = [{id: 'nginx',name: 'Nginx Web Server',@@ -79,37 +93,208 @@ volumes:}];- function useTemplate(template: any) {+ function useTemplate(template: StackTemplate) {stackName = template.name.toLowerCase().replace(/\s+/g, '-');composeContent = template.compose;deploymentMode = 'compose';}async function handleDeploy() {+ // Comprehensive validationif (!stackName.trim()) {toast.error('Please enter a stack name');return;}- if (deploymentMode === 'compose' && !composeContent.trim()) {- toast.error('Please enter compose content');+ // Validate stack name format+ const stackNameRegex = /^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$/;+ const trimmedStackName = stackName.trim().toLowerCase();+ if (!stackNameRegex.test(trimmedStackName)) {+ toast.error('Stack name must start with a letter, contain only lowercase letters, numbers, and hyphens, and not end with a hyphen');return;}+ if (trimmedStackName.length > 63) {+ toast.error('Stack name must be 63 characters or less');+ return;+ }++ // Reserved stack names+ const reservedNames = ['system', 'docker', 'default', 'admin', 'root', 'api'];+ if (reservedNames.includes(trimmedStackName)) {+ toast.error(`"${trimmedStackName}" is a reserved name. Please choose a different stack name`);+ return;+ }++ // Mode-specific validation+ if (deploymentMode === 'compose') {+ if (!composeContent.trim()) {+ toast.error('Please enter Docker Compose content');+ return;+ }++ // Basic YAML validation+ try {+ // Check if it looks like valid YAML (basic structure check)+ const lines = composeContent.trim().split('\n');+ const firstLine = lines[0].trim();++ // Should have version or services+ if (!firstLine.startsWith('version:') && !composeContent.includes('services:')) {+ toast.error('Compose content should include a version and services section');+ return;+ }++ // Check for common YAML issues+ if (composeContent.includes('\t')) {+ toast.error('Compose content contains tabs. Please use spaces for indentation');+ return;+ }++ // Check for required services section+ if (!composeContent.includes('services:')) {+ toast.error('Compose content must include a "services:" section');+ return;+ }++ // Basic service definition check+ const servicesMatch = composeContent.match(/services:\s*\n([\s\S]*?)(?=\n\w|\n$|$)/);+ if (servicesMatch) {+ const servicesSection = servicesMatch[1];+ const serviceLines = servicesSection.split('\n').filter((line) => line.trim() && !line.startsWith(' '));++ if (serviceLines.length === 0) {+ toast.error('At least one service must be defined in the services section');+ return;+ }+ }+ } catch (error) {+ toast.error('Invalid Docker Compose format. Please check your YAML syntax');+ return;+ }++ // Validate environment variables format if provided+ if (envContent.trim()) {+ const envLines = envContent.trim().split('\n');+ for (let i = 0; i < envLines.length; i++) {+ const line = envLines[i].trim();+ if (!line) continue; // Skip empty lines++ // Should be in KEY=VALUE format+ if (!line.includes('=')) {+ toast.error(`Environment variable line ${i + 1} must be in KEY=VALUE format`);+ return;+ }++ const [key, ...valueParts] = line.split('=');+ if (!key.trim()) {+ toast.error(`Environment variable line ${i + 1} is missing a key`);+ return;+ }++ // Validate environment variable key format+ const envKeyRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;+ if (!envKeyRegex.test(key.trim())) {+ toast.error(`Environment variable "${key}" must start with letter or underscore and contain only letters, numbers, and underscores`);+ return;+ }+ }+ }+ } else if (deploymentMode === 'template') {+ // For template mode, ensure a template was selected (composeContent should be populated)+ if (!composeContent.trim()) {+ toast.error('Please select a template first');+ return;+ }+ } else if (deploymentMode === 'existing') {+ if (!selectedStack.trim()) {+ toast.error('Please select an existing stack');+ return;+ }+ }+deploying = true;try {- await onDeploy({+ const data: StackDeploymentData = {mode: deploymentMode,- stackName: stackName.trim(),+ stackName: trimmedStackName,composeContent: composeContent.trim(),envContent: envContent.trim(),- selectedStack- });+ selectedStack: selectedStack.trim() || undefined+ };++ console.log(`🚀 Deploying stack "${trimmedStackName}" with mode "${deploymentMode}"`);+ await onDeploy(data);onClose();- toast.success(`Stack "${stackName}" deployed successfully`);+ toast.success(`Stack "${trimmedStackName}" deployed successfully`);} catch (err) {console.error('Deploy error:', err);- toast.error(err instanceof Error ? err.message : 'Failed to deploy stack');++ // Enhanced error handling with specific error types+ if (err instanceof Error) {+ const errorMessage = err.message.toLowerCase();++ // Network/connectivity errors+ if (errorMessage.includes('network') || errorMessage.includes('connection') || errorMessage.includes('timeout')) {+ toast.error('Network error: Unable to connect to the deployment service. Please check your connection and try again.');+ return;+ }++ // Permission/authentication errors+ if (errorMessage.includes('unauthorized') || errorMessage.includes('forbidden') || errorMessage.includes('permission')) {+ toast.error('Permission denied: You may not have sufficient permissions to deploy stacks.');+ return;+ }++ // Stack already exists+ if (errorMessage.includes('already exists') || errorMessage.includes('conflict')) {+ toast.error(`Stack "${trimmedStackName}" already exists. Please choose a different name or remove the existing stack first.`);+ return;+ }++ // Docker/compose specific errors+ if (errorMessage.includes('yaml') || errorMessage.includes('compose') || errorMessage.includes('invalid')) {+ toast.error('Invalid Docker Compose configuration. Please check your compose content and try again.');+ return;+ }++ // Resource errors+ if (errorMessage.includes('memory') || errorMessage.includes('disk') || errorMessage.includes('resource')) {+ toast.error('Insufficient resources: The deployment requires more memory, disk space, or other resources than available.');+ return;+ }++ // Image pull errors+ if (errorMessage.includes('pull') || errorMessage.includes('image') || errorMessage.includes('registry')) {+ toast.error('Image error: Unable to pull required Docker images. Please check image names and registry availability.');+ return;+ }++ // Port binding errors+ if (errorMessage.includes('port') || errorMessage.includes('bind') || errorMessage.includes('address already in use')) {+ toast.error('Port conflict: One or more ports are already in use. Please check your port mappings.');+ return;+ }++ // Volume/mount errors+ if (errorMessage.includes('volume') || errorMessage.includes('mount') || errorMessage.includes('path')) {+ toast.error('Volume error: There was an issue with volume mounts or paths. Please check your volume configurations.');+ return;+ }++ // Agent-specific errors+ if (errorMessage.includes('agent') || errorMessage.includes('offline')) {+ toast.error('Agent error: The target agent is offline or unavailable. Please try again later.');+ return;+ }++ // Generic error with the actual message+ toast.error(`Deployment failed: ${err.message}`);+ } else {+ // Non-Error objects+ console.error('Unknown error type:', err);+ toast.error('An unexpected error occurred during deployment. Please try again.');+ }} finally {deploying = false;}diff --git a/src/lib/components/maturity-item.svelte b/src/lib/components/maturity-item.svelteindex 2fdb364b6..fab1e9ae2 100644--- a/src/lib/components/maturity-item.svelte+++ b/src/lib/components/maturity-item.svelte@@ -2,15 +2,15 @@import * as Tooltip from '$lib/components/ui/tooltip/index.js';import { CircleCheck, CircleFadingArrowUp, CircleArrowUp, Loader2, Clock, Package, Calendar, AlertTriangle } from '@lucide/svelte';+ interface MaturityData {+ updatesAvailable: boolean;+ status: string;+ version?: string;+ date?: string;+ }+interface Props {- maturity?:- | {- updatesAvailable: boolean;- status: string;- version?: string;- date?: string;- }- | undefined;+ maturity?: MaturityData | undefined;isLoadingInBackground?: boolean;}@@ -27,15 +27,74 @@if (isNaN(date.getTime())) return 'Unknown';const now = new Date();- const diffTime = Math.abs(now.getTime() - date.getTime());+ const diffTime = date.getTime() - now.getTime(); // Remove Math.abs()const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));+ const absDiffDays = Math.abs(diffDays);++ // Handle same day (within 24 hours)+ if (absDiffDays === 0) {+ const diffHours = Math.floor(Math.abs(diffTime) / (1000 * 60 * 60));+ if (diffHours === 0) return 'Now';+ return diffTime > 0 ? `In ${diffHours} hours` : `${diffHours} hours ago`;+ }++ // Future dates+ if (diffTime > 0) {+ if (diffDays === 1) return 'Tomorrow';+ if (diffDays < 7) return `In ${diffDays} days`;+ if (diffDays < 30) {+ const weeks = Math.floor(diffDays / 7);+ return weeks === 1 ? 'In 1 week' : `In ${weeks} weeks`;+ }++ // More accurate month/year calculation for future dates+ const futureDate = new Date(date);+ const currentDate = new Date(now);++ let monthsDiff = (futureDate.getFullYear() - currentDate.getFullYear()) * 12;+ monthsDiff += futureDate.getMonth() - currentDate.getMonth();++ if (monthsDiff < 12) {+ return monthsDiff === 1 ? 'In 1 month' : `In ${monthsDiff} months`;+ }++ const yearsDiff = Math.floor(monthsDiff / 12);+ const remainingMonths = monthsDiff % 12;++ if (remainingMonths === 0) {+ return yearsDiff === 1 ? 'In 1 year' : `In ${yearsDiff} years`;+ } else {+ return `In ${yearsDiff} years, ${remainingMonths} months`;+ }+ }++ // Past dates (diffTime < 0)+ if (absDiffDays === 1) return 'Yesterday';+ if (absDiffDays < 7) return `${absDiffDays} days ago`;+ if (absDiffDays < 30) {+ const weeks = Math.floor(absDiffDays / 7);+ return weeks === 1 ? '1 week ago' : `${weeks} weeks ago`;+ }++ // More accurate month/year calculation for past dates+ const pastDate = new Date(date);+ const currentDate = new Date(now);++ let monthsDiff = (currentDate.getFullYear() - pastDate.getFullYear()) * 12;+ monthsDiff += currentDate.getMonth() - pastDate.getMonth();++ if (monthsDiff < 12) {+ return monthsDiff === 1 ? '1 month ago' : `${monthsDiff} months ago`;+ }++ const yearsDiff = Math.floor(monthsDiff / 12);+ const remainingMonths = monthsDiff % 12;- if (diffDays === 0) return 'Today';- if (diffDays === 1) return 'Yesterday';- if (diffDays < 7) return `${diffDays} days ago`;- if (diffDays < 30) return `${Math.floor(diffDays / 7)} weeks ago`;- if (diffDays < 365) return `${Math.floor(diffDays / 30)} months ago`;- return `${Math.floor(diffDays / 365)} years ago`;+ if (remainingMonths === 0) {+ return yearsDiff === 1 ? '1 year ago' : `${yearsDiff} years ago`;+ } else {+ return `${yearsDiff} years, ${remainingMonths} months ago`;+ }} catch {return 'Unknown';}@@ -56,7 +115,7 @@}// Helper function to get update priority level- function getUpdatePriority(maturity: any): { level: string; color: string; description: string } {+ function getUpdatePriority(maturity: MaturityData): { level: string; color: string; description: string } {if (!maturity.updatesAvailable) {return { level: 'None', color: 'text-green-500', description: 'Image is up to date' };}@@ -165,8 +224,12 @@<div class="text-xs text-muted-foreground leading-relaxed">{priority.description}</div>- {#if maturity.updatesAvailable && maturity.status === 'Not Matured'}- <div class="mt-1 text-xs text-amber-600 dark:text-amber-400 leading-relaxed">Consider waiting for the update to mature before upgrading.</div>+ {#if maturity.updatesAvailable}+ {#if priority.level === 'Optional'}+ <div class="mt-1 text-xs text-amber-600 dark:text-amber-400 leading-relaxed">Consider waiting for the update to mature before upgrading.</div>+ {:else if priority.level === 'Unknown'}+ <div class="mt-1 text-xs text-gray-600 dark:text-gray-400 leading-relaxed">Verify update stability before proceeding with upgrade.</div>+ {/if}{/if}</div></div>diff --git a/src/lib/services/agent/agent-manager.ts b/src/lib/services/agent/agent-manager.tsindex 1b3c5c2c4..e9b2cda13 100644--- a/src/lib/services/agent/agent-manager.ts+++ b/src/lib/services/agent/agent-manager.ts@@ -3,6 +3,9 @@ import { nanoid } from 'nanoid';import { updateDeploymentFromTask } from '$lib/services/deployment-service';import { registerAgentInDb, getAgentByIdFromDb, updateAgentInDb, updateAgentHeartbeatInDb, listAgentsFromDb, deleteAgentFromDb, createTaskInDb, getTaskByIdFromDb, updateTaskStatusInDb, listTasksFromDb, getPendingTasksFromDb, getAgentTasksFromDb, updateAgentMetricsInDb, updateAgentDockerInfoInDb } from '$lib/services/database/agent-db-service';+// Extract the task type from AgentTask to ensure type safety+type AgentTaskType = AgentTask['type'];+/*** Register a new agent or update existing one*/@@ -98,7 +101,7 @@ export async function deleteAgent(agentId: string): Promise<void> {/*** Send a task to an agent*/-export async function sendTaskToAgent(agentId: string, taskType: string, payload: any): Promise<AgentTask> {+export async function sendTaskToAgent(agentId: string, taskType: AgentTaskType, payload: any): Promise<AgentTask> {try {const agent = await getAgent(agentId);if (!agent) {@@ -113,7 +116,7 @@ export async function sendTaskToAgent(agentId: string, taskType: string, payloadconst task: AgentTask = {id: nanoid(),agentId,- type: taskType as any,+ type: taskType, // No casting needed anymore!payload,status: 'pending',createdAt: new Date().toISOString()diff --git a/src/lib/services/agent/agent-stack-service.ts b/src/lib/services/agent/agent-stack-service.tsindex 8462c453b..eedaf93a1 100644--- a/src/lib/services/agent/agent-stack-service.ts+++ b/src/lib/services/agent/agent-stack-service.ts@@ -58,7 +58,8 @@ export async function getStacksFromAgent(agent: Agent, context?: ServerFetchCont}// Handle if the output is nested in a result.output field- if (!stacksData && updatedTask.task.result.output) {+ // Add null check for updatedTask.task.result before accessing .output+ if (!stacksData && updatedTask.task.result && updatedTask.task.result.output) {if (typeof updatedTask.task.result.output === 'object') {stacksData = updatedTask.task.result.output;} else if (typeof updatedTask.task.result.output === 'string') {diff --git a/src/lib/types/agent.type.ts b/src/lib/types/agent.type.tsindex dbd7fcc71..5a0968fbc 100644--- a/src/lib/types/agent.type.ts+++ b/src/lib/types/agent.type.ts@@ -29,7 +29,7 @@ export interface Agent {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';+ type: 'docker_command' | 'stack_deploy' | 'image_pull' | 'health_check' | 'container_start' | 'stack_list' | 'container_stop' | 'container_restart' | 'container_remove' | 'agent_upgrade';payload: Record<string, any>;status: 'pending' | 'running' | 'completed' | 'failed';result?: any;