Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: add api endpoints for stacks and container actions (#73)
Kyle Mendell6844e35153e6
diff --git a/src/lib/components/action-buttons.svelte b/src/lib/components/action-buttons.svelteindex f4098202c..a44aa3b4a 100644--- a/src/lib/components/action-buttons.svelte+++ b/src/lib/components/action-buttons.svelte@@ -1,6 +1,9 @@<script lang="ts">import { Button } from '$lib/components/ui/button/index.js';- import { Play, StopCircle, RotateCcw, Download, Trash2, Loader2 } from '@lucide/svelte';+ import { Play, StopCircle, RotateCcw, Download, Trash2, Loader2, RefreshCcwDot } from '@lucide/svelte';+ import ConfirmDialog from './confirm-dialog.svelte';+ import { invalidateAll } from '$app/navigation';+ import { toast } from 'svelte-sonner';type TargetType = 'container' | 'stack';type LoadingStates = {@@ -16,24 +19,113 @@let {id,type = 'container',- state = 'stopped',+ itemState = 'stopped',loading = {},- formAction = null+ onActionComplete = $bindable(() => {})}: {id: string;type?: TargetType;- state?: string;+ itemState?: string;loading?: LoadingStates;- formAction?: string | null;+ onActionComplete?: () => void;} = $props();- const isRunning = $derived(state === 'running' || (type === 'stack' && state === 'partially running'));+ // Track dialog states+ let showRemoveDialog = $state(false);+ let showRedeployDialog = $state(false);++ // Track loading states for each action+ let isStarting = $state(false);+ let isStopping = $state(false);+ let isRestarting = $state(false);+ let isRedeploying = $state(false);+ let isRemoving = $state(false);+ let isPulling = $state(false);++ const isRunning = $derived(itemState === 'running' || (type === 'stack' && itemState === 'partially running'));++ // Handle showing confirmation dialogs+ function confirmAction(action: string) {+ if (action === 'remove') {+ showRemoveDialog = true;+ } else if (action === 'redeploy') {+ showRedeployDialog = true;+ }+ }++ // Generic API call function+ async function callApi(action: string, loadingStateSetter: (value: boolean) => void) {+ loadingStateSetter(true);++ // Different endpoint format for stacks vs containers+ let endpoint;+ if (type === 'stack') {+ endpoint = `/api/stacks/${id}/${action}`; // No plural, no separator between "stack" and ID+ } else {+ endpoint = `/api/${type}s/${id}/${action}`; // Plural with separator for containers+ }++ const method = action === 'remove' ? 'DELETE' : 'POST';++ try {+ const response = await fetch(endpoint, { method });+ // Gracefully fallback when there is no JSON body+ let result: any = {};+ if (response.headers.get('content-type')?.includes('application/json')) {+ result = await response.json();+ }+ if (!response.ok) {+ throw new Error(result.error ?? `Failed to ${action} ${type}`);+ }+ toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} ${action}ed successfully`);+ await invalidateAll();+ onActionComplete();+ } catch (error: any) {+ console.error(`Error ${action}ing ${type}:`, error);+ toast.error(`Failed to ${action} ${type}: ${error.message}`);+ } finally {+ loadingStateSetter(false);+ }+ }++ // Action handlers+ async function handleStart() {+ await callApi('start', (value) => (isStarting = value));+ }++ async function handleStop() {+ await callApi('stop', (value) => (isStopping = value));+ }++ async function handleRestart() {+ await callApi('restart', (value) => (isRestarting = value));+ }++ async function handleRedeploy() {+ showRedeployDialog = false;+ await callApi('redeploy', (value) => (isRedeploying = value));+ }++ async function handleRemove() {+ showRemoveDialog = false;+ await callApi('remove', (value) => (isRemoving = value));+ }++ async function handlePull() {+ await callApi('pull', (value) => (isPulling = value));+ }</script>+<!-- Confirmation Dialogs -->+<ConfirmDialog bind:open={showRemoveDialog} title="Confirm Removal" description={`Are you sure you want to remove this ${type}? This action cannot be undone.`} confirmLabel="Remove" variant="destructive" onConfirm={handleRemove} />++<ConfirmDialog bind:open={showRedeployDialog} title="Confirm Redeploy" description={`Are you sure you want to redeploy this ${type}?`} confirmLabel="Redeploy" variant="default" onConfirm={handleRedeploy} />++<!-- Action buttons --><div class="flex items-center gap-2">{#if !isRunning}- <Button type="submit" variant="default" disabled={loading.start} class="font-medium " formaction={formAction || '?/start'}>- {#if loading.start}+ <Button type="button" variant="default" disabled={isStarting || loading.start} class="font-medium" onclick={handleStart}>+ {#if isStarting || loading.start}<Loader2 class="w-4 h-4 mr-2 animate-spin" />{:else}<Play class="w-4 h-4 mr-2" />@@ -41,8 +133,8 @@{type === 'stack' ? 'Deploy' : 'Start'}</Button>{:else}- <Button type="submit" variant="secondary" disabled={loading.stop} class="font-medium " formaction={formAction || '?/stop'}>- {#if loading.stop}+ <Button type="button" variant="secondary" disabled={isStopping || loading.stop} class="font-medium" onclick={handleStop}>+ {#if isStopping || loading.stop}<Loader2 class="w-4 h-4 animate-spin" />{:else}<StopCircle class="w-4 h-4" />@@ -50,8 +142,8 @@Stop</Button>- <Button type="submit" variant="outline" disabled={loading.restart} class="font-medium " formaction={formAction || '?/restart'} name="action" value="restart">- {#if loading.restart}+ <Button type="button" variant="outline" disabled={isRestarting || loading.restart} class="font-medium" onclick={handleRestart}>+ {#if isRestarting || loading.restart}<Loader2 class="w-4 h-4 animate-spin" />{:else}<RotateCcw class="w-4 h-4" />@@ -61,20 +153,8 @@{/if}{#if type === 'container'}- <Button- type="submit"- variant="destructive"- disabled={loading.remove}- class="font-medium "- formaction={formAction || '?/remove'}- onclick={(e) => {- if (!confirm(`Are you sure you want to remove this ${type}?`)) {- e.preventDefault();- return false;- }- }}- >- {#if loading.remove}+ <Button type="button" variant="destructive" disabled={isRemoving || loading.remove} class="font-medium" onclick={() => confirmAction('remove')}>+ {#if isRemoving || loading.remove}<Loader2 class="w-4 h-4 animate-spin" />{:else}<Trash2 class="w-4 h-4" />@@ -82,9 +162,17 @@Remove</Button>{:else}- <!-- Stack-specific actions -->- <Button type="submit" variant="outline" disabled={loading.pull} class="font-medium" formaction={formAction || '?/pull'}>- {#if loading.pull}+ <Button type="button" variant="secondary" disabled={isRedeploying || loading.redeploy} class="font-medium" onclick={() => confirmAction('redeploy')}>+ {#if isRedeploying || loading.redeploy}+ <Loader2 class="w-4 h-4 animate-spin" />+ {:else}+ <RefreshCcwDot class="w-4 h-4" />+ {/if}+ Redeploy+ </Button>++ <Button type="button" variant="outline" disabled={isPulling || loading.pull} class="font-medium" onclick={handlePull}>+ {#if isPulling || loading.pull}<Loader2 class="w-4 h-4 animate-spin" />{:else}<Download class="w-4 h-4" />@@ -92,20 +180,8 @@Pull</Button>- <Button- type="submit"- variant="destructive"- disabled={loading.remove}- class="font-medium "- formaction={formAction || '?/remove'}- onclick={(e) => {- if (!confirm(`Are you sure you want to remove this ${type}?`)) {- e.preventDefault();- return false;- }- }}- >- {#if loading.remove}+ <Button type="button" variant="destructive" disabled={isRemoving || loading.remove} class="font-medium" onclick={() => confirmAction('remove')}>+ {#if isRemoving || loading.remove}<Loader2 class="w-4 h-4 animate-spin" />{:else}<Trash2 class="w-4 h-4" />diff --git a/src/lib/components/confirm-dialog.svelte b/src/lib/components/confirm-dialog.sveltenew file mode 100644index 000000000..81197c7cd--- /dev/null+++ b/src/lib/components/confirm-dialog.svelte@@ -0,0 +1,71 @@+<script lang="ts">+ import * as Dialog from '$lib/components/ui/dialog/index.js';+ import { Button } from '$lib/components/ui/button/index.js';+ import { AlertTriangle } from '@lucide/svelte';+ import { Checkbox } from '$lib/components/ui/checkbox/index.js';+ import { Label } from '$lib/components/ui/label/index.js';++ type ButtonVariant = 'destructive' | 'link' | 'default' | 'outline' | 'secondary' | 'ghost';++ let {+ title = $bindable('Confirm Action'),+ description = $bindable('Are you sure you want to proceed?'),+ confirmLabel = $bindable('Confirm'),+ cancelLabel = $bindable('Cancel'),+ variant = $bindable<ButtonVariant>('destructive' as ButtonVariant),+ open = $bindable(false),+ onConfirm = $bindable((force?: boolean) => {}),+ itemType = $bindable<'container' | 'stack' | string | undefined>(undefined),+ isRunning = $bindable<boolean | undefined>(undefined)+ } = $props();++ let forceRemoveChecked = $state(false);++ const showForceRemoveCheckbox = $derived(itemType === 'container' && isRunning === true);+ const isConfirmDisabled = $derived(showForceRemoveCheckbox && !forceRemoveChecked);+ const finalDescription = $derived(showForceRemoveCheckbox ? `${description} The container is currently running and will be forcefully stopped and removed.` : description);++ $effect(() => {+ if (!open || !showForceRemoveCheckbox) {+ forceRemoveChecked = false;+ }+ });++ function handleConfirm() {+ onConfirm(showForceRemoveCheckbox && forceRemoveChecked);+ open = false;+ }+</script>++<Dialog.Root bind:open>+ <Dialog.Content class="max-w-md w-full">+ <Dialog.Header>+ <Dialog.Title class="flex items-center gap-2 text-lg font-semibold">+ <AlertTriangle class="h-5 w-5 text-destructive flex-shrink-0" />+ {title}+ </Dialog.Title>+ </Dialog.Header>++ <div class="mt-2 text-sm text-muted-foreground break-words min-w-0">+ {finalDescription}+ </div>++ {#if showForceRemoveCheckbox}+ <div class="flex items-center space-x-2 pt-4 pb-2 mt-4 border-t border-border">+ <Checkbox id="force-remove" bind:checked={forceRemoveChecked} />+ <Label for="force-remove" class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Force remove running container</Label>+ </div>+ {/if}++ <Dialog.Footer class="mt-6">+ <div class="flex justify-end gap-2">+ <Button variant="outline" onclick={() => (open = false)}>+ {cancelLabel}+ </Button>+ <Button {variant} onclick={handleConfirm} disabled={isConfirmDisabled}>+ {confirmLabel}+ </Button>+ </div>+ </Dialog.Footer>+ </Dialog.Content>+</Dialog.Root>diff --git a/src/lib/services/docker/container-service.ts b/src/lib/services/docker/container-service.tsindex b1068584e..662600eb3 100644--- a/src/lib/services/docker/container-service.ts+++ b/src/lib/services/docker/container-service.ts@@ -1,6 +1,8 @@import { getDockerClient, dockerHost } from './core';import type { ContainerConfig, ContainerCreate } from '$lib/types/docker';import type { ServiceContainer } from '$lib/types/docker/container.type';+// Import custom errors+import { NotFoundError, ConflictError, DockerApiError } from '$lib/types/errors';/*** This TypeScript function lists Docker containers and returns an array of ServiceContainer objects.@@ -125,29 +127,40 @@ export async function restartContainer(containerId: string): Promise<void> {/*** The function `removeContainer` asynchronously removes a Docker container by its ID, with an option- * to force removal if necessary.+ * to force removal if necessary. It throws specific errors for common issues like 'not found' or 'conflict'.* @param {string} containerId - The `containerId` parameter is a string that represents the unique- * identifier of the container that you want to remove. It is used to identify the specific container- * within the Docker environment.- * @param [force=false] - The `force` parameter in the `removeContainer` function is a boolean- * parameter that determines whether to forcefully remove the container if it is currently running. If- * `force` is set to `true`, the container will be removed even if it is running. If `force` is set to- * `false+ * identifier of the container that you want to remove.+ * @param {boolean} [force=false] - The `force` parameter determines whether to forcefully remove the+ * container if it is currently running. If `force` is set to `true`, the container will be stopped+ * (if running) and then removed. If `force` is set to `false` (default), an error will be thrown if+ * the container is running.+ * @throws {NotFoundError} If the container with the specified ID does not exist.+ * @throws {ConflictError} If trying to remove a running container without `force=true`.+ * @throws {DockerApiError} For other errors during the Docker API interaction.*/export async function removeContainer(containerId: string, force = false): Promise<void> {try {const docker = getDockerClient();const container = docker.getContainer(containerId);++ // Pass the force option directly to dockerode's remove methodawait container.remove({ force });++ console.log(`Docker Service: Container ${containerId} removed successfully (force=${force}).`);} catch (error: any) {- console.error(`Docker Service: Error removing container ${containerId}:`, error);+ console.error(`Docker Service: Error removing container ${containerId} (force=${force}):`, error);++ // Use custom error types for better handling in the API layerif (error.statusCode === 404) {- throw new Error(`Container ${containerId} not found.`);+ throw new NotFoundError(`Container ${containerId} not found.`);}+ // 409 Conflict typically means trying to remove a running container without forceif (error.statusCode === 409) {- throw new Error(`Cannot remove running container ${containerId}. Stop it first or use force.`);+ throw new ConflictError(`Cannot remove running container ${containerId}. Stop it first or use the force option.`);}- throw new Error(`Failed to remove container ${containerId} using host "${dockerHost}". ${error.message || ''}`);++ // Throw a more specific Docker API error for other cases+ throw new DockerApiError(`Failed to remove container ${containerId}: ${error.message || 'Unknown Docker error'}`, error.statusCode);}}diff --git a/src/lib/services/docker/stack-service.ts b/src/lib/services/docker/stack-service.tsindex b1529d41d..aacb66838 100644--- a/src/lib/services/docker/stack-service.ts+++ b/src/lib/services/docker/stack-service.ts@@ -4,6 +4,7 @@ import { basename } from 'node:path';import DockerodeCompose from 'dockerode-compose';import yaml from 'js-yaml';import { nanoid } from 'nanoid';+import Dockerode from 'dockerode';import { getDockerClient } from '$lib/services/docker/core';import { getSettings, ensureStacksDirectory } from '$lib/services/settings-service';@@ -142,58 +143,103 @@ async function getComposeInstance(stackId: string): Promise<DockerodeCompose> {*/async function getStackServices(stackId: string, composeContent: string): Promise<StackService[]> {const docker = getDockerClient();+ const composeProjectLabel = 'com.docker.compose.project'; // Standard label+ const composeServiceLabel = 'com.docker.compose.service'; // Standard service labeltry {const composeData = yaml.load(composeContent) as any;if (!composeData || !composeData.services) {+ console.warn(`No services found in compose content for stack ${stackId}`);return [];}const serviceNames = Object.keys(composeData.services);- const containers = await docker.listContainers({ all: true });+ // List containers, potentially filtering by label for efficiency if needed+ const containers = await docker.listContainers({+ all: true+ // Optional: Filter directly using Docker API if performance becomes an issue+ // filters: JSON.stringify({ label: [`${composeProjectLabel}=${stackId}`] })+ });- const stackPrefix = `${stackId}_`;+ // Filter containers based on EITHER the project label OR the naming conventionconst stackContainers = containers.filter((container) => {+ const labels = container.Labels || {};const names = container.Names || [];- return names.some((name) => name.startsWith(`/${stackPrefix}`));+ // Check if any name starts with the conventional prefix (e.g., /stackId_service_1)+ const nameStartsWithPrefix = names.some((name) => name.startsWith(`/${stackId}_`));+ // Check if the standard compose project label matches the stackId+ const hasCorrectLabel = labels[composeProjectLabel] === stackId;+ // Include the container if either condition is true+ return nameStartsWithPrefix || hasCorrectLabel;});+ if (stackContainers.length === 0) {+ console.log(`No running or stopped containers found for stack ${stackId} based on name prefix or label.`);+ }+const services: StackService[] = [];for (const containerData of stackContainers) {- let containerName = containerData.Names?.[0] || '';- containerName = containerName.substring(1);-- let serviceName = '';- for (const name of serviceNames) {- if (containerName.startsWith(`${stackId}_${name}_`) || containerName === `${stackId}_${name}`) {- serviceName = name;- break;+ const containerName = containerData.Names?.[0]?.substring(1) || ''; // Remove leading '/'+ const labels = containerData.Labels || {};+ // Prefer the standard compose service label for the service name+ let serviceName = labels[composeServiceLabel];++ // Fallback to parsing from container name if the service label is missing+ if (!serviceName) {+ console.warn(`Container ${containerData.Id} in stack ${stackId} is missing the '${composeServiceLabel}' label. Attempting to parse name.`);+ for (const name of serviceNames) {+ // Match patterns like stackId_serviceName_1 or stackId_serviceName+ // Ensure the match is precise to avoid partial overlaps (e.g., 'web' vs 'web-api')+ const servicePrefixWithUnderscore = `${stackId}_${name}_`;+ const servicePrefixExact = `${stackId}_${name}`;+ if (containerName.startsWith(servicePrefixWithUnderscore) || containerName === servicePrefixExact) {+ serviceName = name;+ break;+ }}}+ // Final fallback if still no match (less ideal)if (!serviceName) {- serviceName = containerName;+ serviceName = containerName; // Use the full container name as a last resort+ console.error(`Could not determine service name for container ${containerName} (ID: ${containerData.Id}) in stack ${stackId}. Using full container name.`);}const service: StackService = {id: containerData.Id,- name: serviceName,+ name: serviceName, // Use the determined service namestate: {Running: containerData.State === 'running',Status: containerData.State,- ExitCode: 0+ // Note: listContainers doesn't provide ExitCode reliably, need inspect for that if required later+ ExitCode: containerData.State === 'exited' ? -1 : 0 // Placeholder}};- services.push(service);+ // Avoid adding duplicates if multiple containers map to the same service (e.g., scaled services)+ // Check if a service with the same name already exists+ const existingServiceIndex = services.findIndex((s) => s.name === serviceName);+ if (existingServiceIndex !== -1) {+ // If the existing service is just a placeholder ('not created'), replace it+ if (!services[existingServiceIndex].id) {+ services[existingServiceIndex] = service;+ } else {+ // Handle scaled services - maybe add instance number or just log for now+ console.log(`Multiple containers found for service ${serviceName} in stack ${stackId}. Displaying first found.`);+ // Or potentially create a unique name like serviceName + '-' + instanceNumber+ }+ } else {+ services.push(service);+ }}+ // Add placeholders for services defined in compose but not found among listed containersfor (const name of serviceNames) {if (!services.some((s) => s.name === name)) {services.push({- id: '',+ id: '', // No container IDname: name,state: {Running: false,@@ -204,10 +250,13 @@ async function getStackServices(stackId: string, composeContent: string): Promis}}+ // Sort services alphabetically by name for consistent order+ services.sort((a, b) => a.name.localeCompare(b.name));+return services;} catch (err) {console.error(`Error getting services for stack ${stackId}:`, err);- return [];+ return []; // Return empty array on error}}@@ -468,7 +517,8 @@ export async function startStack(stackId: string): Promise<boolean> {/*** The function `stopStack` stops a Docker stack identified by its ID and returns a boolean indicating- * success.+ * success. It manually stops and removes containers associated with the stack due to potential+ * inconsistencies in `dockerode-compose`.* @param {string} stackId - The `stackId` parameter is a string that represents the identifier of the* stack that you want to stop.* @returns The `stopStack` function returns a Promise that resolves to a boolean value. If the stack@@ -477,14 +527,103 @@ export async function startStack(stackId: string): Promise<boolean> {* Promise will be rejected.*/export async function stopStack(stackId: string): Promise<boolean> {+ console.log(`Attempting to stop stack ${stackId} by manually stopping containers...`);+ const docker = getDockerClient();+ const composeProjectLabel = 'com.docker.compose.project';+ let stoppedCount = 0;+ let removedCount = 0;+try {- const compose = await getComposeInstance(stackId);- await compose.down();- return true;+ // 1. Find containers belonging to the stack (using label or name convention)+ const containers = await docker.listContainers({+ all: true, // Include stopped containers as well+ filters: JSON.stringify({+ // Primarily filter by the standard compose project label+ label: [`${composeProjectLabel}=${stackId}`]+ })+ });++ // Fallback: If label filter missed some, double-check by name (less reliable)+ // This part might be less necessary if the label is consistently applied by `up()`+ const allContainers = await docker.listContainers({ all: true });+ const nameFilteredContainers = allContainers.filter(+ (c) =>+ !containers.some((fc) => fc.Id === c.Id) && // Only check containers not already found by label+ (c.Labels?.[composeProjectLabel] === stackId || c.Names?.some((name) => name.startsWith(`/${stackId}_`)))+ );+ const seen = new Set<string>();+ const stackContainers = [...containers, ...nameFilteredContainers].filter((c) => {+ if (seen.has(c.Id)) return false;+ seen.add(c.Id);+ return true;+ });++ if (stackContainers.length === 0) {+ return true; // Nothing to stop+ }++ console.log(`Found ${stackContainers.length} containers for stack ${stackId}. Attempting to stop and remove...`);++ // 2. Stop and Remove each container+ for (const containerInfo of stackContainers) {+ console.log(`Processing container ${containerInfo.Names?.[0]} (ID: ${containerInfo.Id})...`);+ const container = docker.getContainer(containerInfo.Id);+ try {+ // Stop the container if it's running+ if (containerInfo.State === 'running') {+ console.log(`Stopping container ${containerInfo.Id}...`);+ await container.stop(); // Consider adding a timeout option: { t: 10 }+ console.log(`Container ${containerInfo.Id} stopped.`);+ stoppedCount++;+ } else {+ console.log(`Container ${containerInfo.Id} is already stopped (State: ${containerInfo.State}).`);+ }++ // Remove the container+ console.log(`Removing container ${containerInfo.Id}...`);+ await container.remove({ force: true }); // Use force to ensure removal even if stopped uncleanly+ console.log(`Container ${containerInfo.Id} removed.`);+ removedCount++;+ } catch (containerErr) {+ // Log error for specific container but continue with others+ console.error(`Error processing container ${containerInfo.Id} for stack ${stackId}:`, containerErr);+ // Optionally decide if this should cause the whole function to fail+ }+ }++ // 3. (Optional) Remove networks associated with the stack+ try {+ const networks = await docker.listNetworks({+ filters: JSON.stringify({+ label: [`${composeProjectLabel}=${stackId}`]+ })+ });+ if (networks.length > 0) {+ console.log(`Found ${networks.length} networks for stack ${stackId}. Attempting to remove...`);+ for (const networkInfo of networks) {+ console.log(`Removing network ${networkInfo.Name} (ID: ${networkInfo.Id})...`);+ const network = docker.getNetwork(networkInfo.Id);+ try {+ await network.remove();+ console.log(`Network ${networkInfo.Name} removed.`);+ } catch (networkErr) {+ console.error(`Error removing network ${networkInfo.Name} (ID: ${networkInfo.Id}):`, networkErr);+ }+ }+ } else {+ console.log(`No networks found specifically for stack ${stackId}.`);+ }+ } catch (networkListErr) {+ console.error(`Error listing networks for stack ${stackId}:`, networkListErr);+ }++ console.log(`Stack ${stackId} processing complete. Stopped: ${stoppedCount}, Removed: ${removedCount}.`);+ return true; // Indicate overall success even if some individual steps had errors (adjust if needed)} catch (err: unknown) {- console.error(`Error stopping stack ${stackId}:`, err);+ // Log the specific error+ console.error(`Error during manual stop/remove for stack ${stackId}:`, err);const errorMessage = err instanceof Error ? err.message : String(err);- throw new Error(`Failed to stop stack: ${errorMessage}`);+ throw new Error(`Failed to stop stack ${stackId}: ${errorMessage}`);}}@@ -496,10 +635,21 @@ export async function stopStack(stackId: string): Promise<boolean> {* @returns The `restartStack` function returns a `Promise<boolean>`.*/export async function restartStack(stackId: string): Promise<boolean> {+ console.log(`Attempting to restart stack ${stackId}...`);try {+ // Use the manual stop logic+ const stopped = await stopStack(stackId);+ if (!stopped) {+ // If stopStack indicates failure (if you modify it to return false on error)+ console.error(`Restart failed because stop step failed for stack ${stackId}.`);+ return false;+ }++ // Now start it again using compose.up()+ console.log(`Starting stack ${stackId} after stopping...`);const compose = await getComposeInstance(stackId);- await compose.down();- await compose.up();+ await compose.up(); // Assuming compose.up() works correctly+ console.log(`Stack ${stackId} started.`);return true;} catch (err: unknown) {console.error(`Error restarting stack ${stackId}:`, err);@@ -509,44 +659,46 @@ export async function restartStack(stackId: string): Promise<boolean> {}/**- * The function `fulllyRedployStack` asynchronously stops, pulls latest images, and restarts a+ * The function `fullyRedployStack` asynchronously stops, pulls latest images, and restarts a* specified stack, returning true if successful.- * @param {string} stackId - The `stackId` parameter in the `fulllyRedployStack` function is a string+ * @param {string} stackId - The `stackId` parameter in the `fullyRedeployStack` function is a string* that represents the identifier of the stack that you want to fully redeploy. This function stops the* stack, pulls the latest images, and then starts the stack again to ensure a full redeployment of the* specified- * @returns The `fulllyRedployStack` function returns a `Promise<boolean>`. The function attempts to+ * @returns The `fullyRedeployStack` function returns a `Promise<boolean>`. The function attempts to* fully redeploy a stack by stopping it, pulling the latest images, and then starting it again. If all* commands succeed, the function resolves the promise with a value of `true`. If an error occurs* during the process, the function catches the error, logs it, and then throws a new `*/-export async function fulllyRedployStack(stackId: string): Promise<boolean> {+export async function fullyRedeployStack(stackId: string): Promise<boolean> {+ console.log(`Attempting to fully redeploy stack ${stackId}...`);try {- const compose = await getComposeInstance(stackId);-- // Stop the stack- console.log(`Stopping stack ${stackId}...`);- await compose.down();- console.log(`Stack ${stackId} stopped.`);+ // Use the manual stop logic+ const stopped = await stopStack(stackId);+ if (!stopped) {+ console.error(`Redeploy failed because stop step failed for stack ${stackId}.`);+ return false;+ }// Pull the latest imagesconsole.log(`Pulling images for stack ${stackId}...`);+ const compose = await getComposeInstance(stackId); // Get instance again for pull/upawait compose.pull();console.log(`Images pulled for stack ${stackId}.`);// Start the stack again- console.log(`Starting stack ${stackId}...`);+ console.log(`Starting stack ${stackId} after pull...`);await compose.up();console.log(`Stack ${stackId} started.`);- // If all commands succeeded, return truereturn true;} catch (err: unknown) {- console.error(`Error restarting stack ${stackId}:`, err);+ console.error(`Error fully redeploying stack ${stackId}:`, err);const errorMessage = err instanceof Error ? err.message : String(err);- throw new Error(`Failed to restart stack: ${errorMessage}`);+ throw new Error(`Failed to fully redeploy stack: ${errorMessage}`);}}+/*** The function `removeStack` removes a Docker stack by stopping its services and deleting its* directory.@@ -558,23 +710,37 @@ export async function fulllyRedployStack(stackId: string): Promise<boolean> {* then throws a new `Error` with a message indicating the failure to remove the stack.*/export async function removeStack(stackId: string): Promise<boolean> {+ console.log(`Attempting to remove stack ${stackId}...`);try {- const compose = await getComposeInstance(stackId);- const stackDir = await getStackDir(stackId);+ // Manually stop and remove containers first+ const stopped = await stopStack(stackId);+ if (!stopped) {+ console.error(`Removal failed because stop/remove container step failed for stack ${stackId}.`);+ // Decide if you want to proceed with directory removal anyway+ // return false; // Option 1: Stop here+ } else {+ console.log(`Containers for stack ${stackId} stopped and removed.`);+ }- await compose.down();+ // Now remove the stack directory+ const stackDir = await getStackDir(stackId);+ console.log(`Removing stack directory ${stackDir}...`);try {await fs.rm(stackDir, { recursive: true, force: true });+ console.log(`Stack directory ${stackDir} removed.`);} catch (e) {console.error(`Failed to remove stack directory ${stackDir}:`, e);- return false;+ // Even if containers were removed, directory removal failed+ throw new Error(`Failed to remove stack directory: ${e instanceof Error ? e.message : String(e)}`);}return true;} catch (err: unknown) {+ // Catch errors from stopStack or directory removalconsole.error(`Error removing stack ${stackId}:`, err);const errorMessage = err instanceof Error ? err.message : String(err);- throw new Error(`Failed to remove stack: ${errorMessage}`);+ // Ensure a specific error message is thrown+ throw new Error(`Failed to remove stack ${stackId}: ${errorMessage}`);}}diff --git a/src/lib/types/errors.ts b/src/lib/types/errors.tsindex a1ccf08f7..e956ca493 100644--- a/src/lib/types/errors.ts+++ b/src/lib/types/errors.ts@@ -1,19 +1,94 @@-/* The `ServiceError` class in TypeScript extends the built-in `Error` class and sets its name to-'ServiceError'. */+/**+ * Defines standard error codes for API responses.+ */+export const ApiErrorCode = {+ // Client-side errors (4xx)+ VALIDATION_ERROR: 'VALIDATION_ERROR', // Input data failed validation (400)+ UNAUTHENTICATED: 'UNAUTHENTICATED', // Missing or invalid authentication (401)+ FORBIDDEN: 'FORBIDDEN', // User does not have permission (403)+ NOT_FOUND: 'NOT_FOUND', // Resource not found (404)+ CONFLICT: 'CONFLICT', // Resource already exists or state conflict (409)+ BAD_REQUEST: 'BAD_REQUEST', // General bad request, often for config/state issues (400)++ // Server-side errors (5xx)+ DOCKER_API_ERROR: 'DOCKER_API_ERROR', // Error interacting with Docker daemon (500/503)+ SERVICE_ERROR: 'SERVICE_ERROR', // General error in backend service logic (500)+ INTERNAL_SERVER_ERROR: 'INTERNAL_SERVER_ERROR' // Unexpected server error (500)+} as const; // Use 'as const' for stricter typing++// Base Service Errorexport class ServiceError extends Error {- constructor(message: string) {+ public readonly code: string;+ public readonly status: number;++ constructor(message: string, code: string = ApiErrorCode.SERVICE_ERROR, status: number = 500) {super(message);this.name = 'ServiceError';- // Ensure the prototype chain is correct+ this.code = code;+ this.status = status;Object.setPrototypeOf(this, ServiceError.prototype);}}-/* The NotFoundError class is a subclass of ServiceError that represents a resource not found error. */+// Not Found Errorexport class NotFoundError extends ServiceError {constructor(message: string = 'Resource not found') {- super(message);+ super(message, ApiErrorCode.NOT_FOUND, 404);this.name = 'NotFoundError';Object.setPrototypeOf(this, NotFoundError.prototype);}}++// Validation Error+export class ValidationError extends ServiceError {+ public readonly details?: Record<string, string> | string;++ constructor(message: string = 'Input validation failed', details?: Record<string, string> | string) {+ super(message, ApiErrorCode.VALIDATION_ERROR, 400);+ this.name = 'ValidationError';+ this.details = details;+ Object.setPrototypeOf(this, ValidationError.prototype);+ }+}++// Docker API Error+export class DockerApiError extends ServiceError {+ public readonly dockerStatusCode?: number;++ constructor(message: string, dockerStatusCode?: number) {+ const status = dockerStatusCode && dockerStatusCode >= 400 && dockerStatusCode < 500 ? dockerStatusCode : 503;+ super(message, ApiErrorCode.DOCKER_API_ERROR, status);+ this.name = 'DockerApiError';+ this.dockerStatusCode = dockerStatusCode;+ Object.setPrototypeOf(this, DockerApiError.prototype);+ }+}++// Conflict Error (e.g., resource already exists, or removing running container without force)+export class ConflictError extends ServiceError {+ constructor(message: string = 'Resource conflict') {+ super(message, ApiErrorCode.CONFLICT, 409);+ this.name = 'ConflictError';+ Object.setPrototypeOf(this, ConflictError.prototype);+ }+}++// NEW: Container State Error (e.g., trying to stop a stopped container)+export class ContainerStateError extends ServiceError {+ constructor(message: string) {+ // Using 409 Conflict as the state prevents the action+ super(message, ApiErrorCode.CONFLICT, 409);+ this.name = 'ContainerStateError';+ Object.setPrototypeOf(this, ContainerStateError.prototype);+ }+}++// NEW: Configuration Error (e.g., invalid settings during creation)+export class ConfigurationError extends ServiceError {+ constructor(message: string) {+ // Using 400 Bad Request as the provided config is invalid+ super(message, ApiErrorCode.BAD_REQUEST, 400);+ this.name = 'ConfigurationError';+ Object.setPrototypeOf(this, ConfigurationError.prototype);+ }+}diff --git a/src/routes/api/containers/[containerId]/pull/+server.ts b/src/routes/api/containers/[containerId]/pull/+server.tsnew file mode 100644index 000000000..2b86f62cb--- /dev/null+++ b/src/routes/api/containers/[containerId]/pull/+server.ts@@ -0,0 +1,53 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { getContainer } from '$lib/services/docker/container-service';+import { pullImage } from '$lib/services/docker/image-service';++/**+ * This TypeScript function handles a POST request to pull an image associated with a container and+ * returns success or error messages accordingly.+ * @param - The code snippet you provided is a TypeScript function that handles a POST request. It+ * takes a containerId from the request parameters, retrieves the container information using the+ * containerId, extracts the image name from the container, and then pulls the image. If successful, it+ * returns a success message with the pulled image+ * @returns The code snippet is an asynchronous function that handles a POST request. It attempts to+ * pull an image associated with a container identified by `containerId`. Here is what is being+ * returned based on the execution flow:+ */+export const POST: RequestHandler = async ({ params }) => {+ const containerId = params.containerId;++ try {+ // Get the container to find its image+ const container = await getContainer(containerId);+ if (!container) {+ return json(+ {+ success: false,+ error: `Container not found`+ },+ { status: 404 }+ );+ }++ // Extract the image name+ const imageName = container.image;++ // Pull the image+ await pullImage(imageName);++ return json({+ success: true,+ message: `Container image ${imageName} pulled successfully`+ });+ } catch (error: any) {+ console.error(`API Error pulling container image for ${containerId}:`, error);+ return json(+ {+ success: false,+ error: error.message || 'Failed to pull container image'+ },+ { status: 500 }+ );+ }+};diff --git a/src/routes/api/containers/[containerId]/remove/+server.ts b/src/routes/api/containers/[containerId]/remove/+server.tsnew file mode 100644index 000000000..c70a0a524--- /dev/null+++ b/src/routes/api/containers/[containerId]/remove/+server.ts@@ -0,0 +1,36 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { removeContainer } from '$lib/services/docker/container-service';++/**+ * This TypeScript function handles the deletion of a container with optional force parameter and+ * returns success or error messages accordingly.+ * @param - The code snippet you provided is an example of a DELETE request handler function in+ * JavaScript using an asynchronous function. Here's a breakdown of the key components:+ * @returns The DELETE request handler is returning a JSON response with either a success message if+ * the container was removed successfully or an error message if there was a failure in removing the+ * container. The response includes a `success` key indicating the operation's success status and a+ * `message` key with a corresponding message. If an error occurs, the response includes a `success`+ * key set to false, an `error`+ */+export const DELETE: RequestHandler = async ({ params, url }) => {+ const containerId = params.containerId;+ const force = url.searchParams.has('force') ? url.searchParams.get('force') === 'true' : false;++ try {+ await removeContainer(containerId, force);+ return json({+ success: true,+ message: `Container removed successfully`+ });+ } catch (error: any) {+ console.error(`API Error removing container ${containerId}:`, error);+ return json(+ {+ success: false,+ error: error.message || 'Failed to remove container'+ },+ { status: 409 }+ );+ }+};diff --git a/src/routes/api/containers/[containerId]/restart/+server.ts b/src/routes/api/containers/[containerId]/restart/+server.tsnew file mode 100644index 000000000..555ad058e--- /dev/null+++ b/src/routes/api/containers/[containerId]/restart/+server.ts@@ -0,0 +1,36 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { restartContainer } from '$lib/services/docker/container-service';++/**+ * The POST request handler restarts a container based on the provided containerId and returns a+ * success message or an error message if the restart fails.+ * @param - The code snippet you provided is a TypeScript function that handles a POST request. It+ * takes a `containerId` from the request parameters, attempts to restart a container with that ID+ * using the `restartContainer` function, and then returns a success message if the restart is+ * successful. If an error occurs during+ * @returns The code snippet is defining a POST request handler function that restarts a container+ * based on the provided `containerId`. If the container restart is successful, it returns a JSON+ * response with a success message. If an error occurs during the restart process, it logs the error+ * and returns a JSON response indicating the failure along with an error message.+ */+export const POST: RequestHandler = async ({ params }) => {+ const containerId = params.containerId;++ try {+ await restartContainer(containerId);+ return json({+ success: true,+ message: `Container restarted successfully`+ });+ } catch (error: any) {+ console.error(`API Error restarting container ${containerId}:`, error);+ return json(+ {+ success: false,+ error: error.message || 'Failed to restart container'+ },+ { status: 500 }+ );+ }+};diff --git a/src/routes/api/containers/[containerId]/start/+server.ts b/src/routes/api/containers/[containerId]/start/+server.tsnew file mode 100644index 000000000..49f1bbbba--- /dev/null+++ b/src/routes/api/containers/[containerId]/start/+server.ts@@ -0,0 +1,34 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { startContainer } from '$lib/services/docker/container-service';++/**+ * This TypeScript function handles a POST request to start a container and returns a success message+ * or an error message with appropriate status code.+ * @param - The code snippet you provided is a TypeScript function that handles a POST request. It+ * expects a parameter object with a `containerId` property. Inside the function, it attempts to start+ * a container using the `startContainer` function with the provided `containerId`. If the operation is+ * successful, it returns+ * @returns The code snippet is a TypeScript function that handles a POST request to start a container+ * based on the provided `containerId`.+ */+export const POST: RequestHandler = async ({ params }) => {+ const containerId = params.containerId;++ try {+ await startContainer(containerId);+ return json({+ success: true,+ message: `Container started successfully`+ });+ } catch (error: any) {+ console.error(`API Error starting container ${containerId}:`, error);+ return json(+ {+ success: false,+ error: error.message || 'Failed to start container'+ },+ { status: 500 }+ );+ }+};diff --git a/src/routes/api/containers/[containerId]/stop/+server.ts b/src/routes/api/containers/[containerId]/stop/+server.tsnew file mode 100644index 000000000..63a5fcb08--- /dev/null+++ b/src/routes/api/containers/[containerId]/stop/+server.ts@@ -0,0 +1,24 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { stopContainer } from '$lib/services/docker/container-service';++export const POST: RequestHandler = async ({ params }) => {+ const containerId = params.containerId;++ try {+ await stopContainer(containerId);+ return json({+ success: true,+ message: `Container stopped successfully`+ });+ } catch (error: any) {+ console.error(`API Error stopping container ${containerId}:`, error);+ return json(+ {+ success: false,+ error: error.message || 'Failed to stop container'+ },+ { status: 500 }+ );+ }+};diff --git a/src/routes/api/stacks/[stackId]/+server.ts b/src/routes/api/stacks/[stackId]/+server.tsindex d39955092..448785a39 100644--- a/src/routes/api/stacks/[stackId]/+server.ts+++ b/src/routes/api/stacks/[stackId]/+server.ts@@ -2,6 +2,7 @@ import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { updateStack } from '$lib/services/docker/stack-service';import { NotFoundError, ServiceError } from '$lib/types/errors';+import { startStack } from '$lib/services/docker/stack-service';export const PATCH: RequestHandler = async ({ params, request }) => {const stackId = params.stackId;diff --git a/src/routes/api/stacks/[stackId]/pull/+server.ts b/src/routes/api/stacks/[stackId]/pull/+server.tsnew file mode 100644index 000000000..e89ba5c86--- /dev/null+++ b/src/routes/api/stacks/[stackId]/pull/+server.ts@@ -0,0 +1,86 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { getStack } from '$lib/services/docker/stack-service';+import Docker from 'dockerode';++export const POST: RequestHandler = async ({ params }) => {+ const id = params.stackId;+ const docker = new Docker();++ try {+ // Get the stack to access its compose content+ const stack = await getStack(id);+ if (!stack || !stack.composeContent) {+ return json({ success: false, error: 'Stack not found or has no compose content' }, { status: 404 });+ }++ // Parse the compose file to extract image names+ // This is a simplified approach - you might need more robust parsing+ const composeLines = stack.composeContent.split('\n');+ const imageLines = composeLines.filter((line) => line.trim().startsWith('image:') || line.includes(' image:'));++ if (imageLines.length === 0) {+ return json({ success: false, error: 'No images found in stack compose file' }, { status: 400 });+ }++ // Extract image names+ const imageNames = imageLines.map((line) => {+ const imagePart = line.split('image:')[1].trim();+ // Remove any quotes or trailing characters+ return imagePart.replace(/['"]/g, '').split(' ')[0];+ });++ // Pull each image+ const pullResults = await Promise.all(+ imageNames.map(async (imageName) => {+ try {+ const stream = await docker.pull(imageName);++ // Process the stream+ return new Promise((resolve, reject) => {+ docker.modem.followProgress(+ stream,+ (err: any, output: any[]) => {+ if (err) {+ reject(err);+ } else {+ resolve({ image: imageName, success: true });+ }+ },+ (event: any) => {+ // Optional: handle progress events+ console.log(`Pull progress for ${imageName}:`, event);+ }+ );+ });+ } catch (error) {+ console.error(`Error pulling image ${imageName}:`, error);+ return { image: imageName, success: false, error };+ }+ })+ );++ // Check if all pulls were successful+ const allSuccessful = pullResults.every((result: any) => result.success);++ if (allSuccessful) {+ return json({+ success: true,+ message: `All images for stack pulled successfully`,+ details: pullResults+ });+ } else {+ return json(+ {+ success: false,+ error: 'Some images failed to pull',+ details: pullResults+ },+ { status: 500 }+ );+ }+ } catch (error: any) {+ console.error(`API Error pulling images for stack ${id}:`, error);+ return json({ success: false, error: error.message || 'Failed to pull stack images' }, { status: 500 });+ }+};diff --git a/src/routes/api/stacks/[stackId]/redeploy/+server.ts b/src/routes/api/stacks/[stackId]/redeploy/+server.tsnew file mode 100644index 000000000..1172b57d0--- /dev/null+++ b/src/routes/api/stacks/[stackId]/redeploy/+server.ts@@ -0,0 +1,19 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { fullyRedeployStack } from '$lib/services/docker/stack-service';++export const POST: RequestHandler = async ({ params }) => {+ const id = params.stackId;++ try {+ const success = await fullyRedeployStack(id);+ if (success) {+ return json({ success: true, message: `Stack redeployed successfully` });+ } else {+ return json({ success: false, error: 'Failed to redeploy stack' }, { status: 500 });+ }+ } catch (error: any) {+ console.error(`API Error redeploying stack ${id}:`, error);+ return json({ success: false, error: error.message || 'Failed to redeploy stack' }, { status: 500 });+ }+};diff --git a/src/routes/api/stacks/[stackId]/remove/+server.ts b/src/routes/api/stacks/[stackId]/remove/+server.tsnew file mode 100644index 000000000..d2db6a40d--- /dev/null+++ b/src/routes/api/stacks/[stackId]/remove/+server.ts@@ -0,0 +1,23 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { removeStack } from '$lib/services/docker/stack-service';++export const DELETE: RequestHandler = async ({ params }) => {+ const id = params.stackId;++ if (!id) {+ return json({ success: false, error: 'Stack ID is required' }, { status: 400 });+ }++ try {+ const success = await removeStack(id);+ if (success) {+ return json({ success: true, message: `Stack removed successfully` });+ } else {+ return json({ success: false, error: 'Failed to remove stack' }, { status: 400 });+ }+ } catch (error: any) {+ console.error(`API Error removing stack ${id}:`, error);+ return json({ success: false, error: error.message || 'Failed to remove stack' }, { status: 409 });+ }+};diff --git a/src/routes/api/stacks/[stackId]/restart/+server.ts b/src/routes/api/stacks/[stackId]/restart/+server.tsnew file mode 100644index 000000000..bcc2c5b9d--- /dev/null+++ b/src/routes/api/stacks/[stackId]/restart/+server.ts@@ -0,0 +1,19 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { restartStack } from '$lib/services/docker/stack-service';++export const POST: RequestHandler = async ({ params }) => {+ const id = params.stackId;++ try {+ const success = await restartStack(id);+ if (success) {+ return json({ success: true, message: `Stack restarted successfully` });+ } else {+ return json({ success: false, error: 'Failed to restart stack' }, { status: 500 });+ }+ } catch (error: any) {+ console.error(`API Error restarting stack ${id}:`, error);+ return json({ success: false, error: error.message || 'Failed to restart stack' }, { status: 500 });+ }+};diff --git a/src/routes/api/stacks/[stackId]/start/+server.ts b/src/routes/api/stacks/[stackId]/start/+server.tsnew file mode 100644index 000000000..dde9e1d63--- /dev/null+++ b/src/routes/api/stacks/[stackId]/start/+server.ts@@ -0,0 +1,15 @@+import { startStack } from '$lib/services/docker/stack-service';+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';++export const POST: RequestHandler = async ({ params }) => {+ const id = params.stackId;++ try {+ await startStack(id);+ return json({ success: true, message: `Stack started successfully` });+ } catch (error: any) {+ console.error(`API Error starting stack ${id}:`, error);+ return json({ success: false, error: error.message || 'Failed to start stack' }, { status: 500 });+ }+};diff --git a/src/routes/api/stacks/[stackId]/stop/+server.ts b/src/routes/api/stacks/[stackId]/stop/+server.tsnew file mode 100644index 000000000..11f0d03b6--- /dev/null+++ b/src/routes/api/stacks/[stackId]/stop/+server.ts@@ -0,0 +1,19 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { stopStack } from '$lib/services/docker/stack-service';++export const POST: RequestHandler = async ({ params }) => {+ const id = params.stackId;++ try {+ const success = await stopStack(id);+ if (success) {+ return json({ success: true, message: `Stack stopped successfully` });+ } else {+ return json({ success: false, error: 'Failed to stop stack' }, { status: 500 });+ }+ } catch (error: any) {+ console.error(`API Error stopping stack ${id}:`, error);+ return json({ success: false, error: error.message || 'Failed to stop stack' }, { status: 500 });+ }+};diff --git a/src/routes/containers/ContainerActions.svelte b/src/routes/containers/ContainerActions.svelteindex 8554d05f4..b73266fe5 100644--- a/src/routes/containers/ContainerActions.svelte+++ b/src/routes/containers/ContainerActions.svelte@@ -2,36 +2,87 @@import Ellipsis from '@lucide/svelte/icons/ellipsis';import { Button } from '$lib/components/ui/button/index.js';import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';- import { goto } from '$app/navigation';- import { Eye, Play, RotateCcw, StopCircle, Trash2 } from '@lucide/svelte';+ import { goto, invalidateAll } from '$app/navigation';+ import { Eye, Play, RotateCcw, StopCircle, Trash2, Loader2 } from '@lucide/svelte';+ import { toast } from 'svelte-sonner';+ import ConfirmDialog from '$lib/components/confirm-dialog.svelte';- let { id, state }: { id: string; state: string } = $props();+ let { id, itemState }: { id: string; itemState: string } = $props();++ let isLoading = $state({+ start: false,+ stop: false,+ restart: false,+ remove: false+ });+ let showRemoveConfirm = $state(false);function viewContainer() {goto(`/containers/${id}`);}- function performContainerAction(action: string) {- // Log the action for now - will be replaced with API call later- console.log(`Container ${id}: Performing action: ${action}`);-- /*- try {- // Will implement fetch call to backend API endpoint- // await fetch(`/api/containers/${id}/${action}`, {- // method: 'POST'- // });- console.log(`Successfully performed ${action} on container ${id}`);- } catch (error) {- console.error(`Failed to ${action} container ${id}:`, error);- }- */+ async function performContainerAction(action: 'start' | 'stop' | 'restart' | 'remove') {+ if (action === 'remove') {+ showRemoveConfirm = true;+ return;+ }++ isLoading[action] = true;+ const method = 'POST';+ const endpoint = `/api/containers/${id}/${action}`;++ try {+ const response = await fetch(endpoint, { method });+ const result = await response.json();++ if (!response.ok) {+ throw new Error(result.error?.message || `Failed to ${action} container`);+ }++ toast.success(`Container ${action}ed successfully.`);+ await invalidateAll();+ } catch (error: any) {+ console.error(`Failed to ${action} container ${id}:`, error);+ toast.error(`Failed to ${action} container: ${error.message}`);+ } finally {+ isLoading[action] = false;+ }}- // Determine if container is running- const isRunning = $derived(state === 'running');+ async function handleRemoveConfirm(force?: boolean) {+ showRemoveConfirm = false;+ isLoading.remove = true;+ const method = 'DELETE';+ const endpoint = `/api/containers/${id}/remove${force ? '?force=true' : ''}`;++ console.log(`Attempting to remove container ${id} at endpoint: ${endpoint}`);++ try {+ const response = await fetch(endpoint, { method });+ const result = await response.json();++ if (!response.ok) {+ throw new Error(result.error?.message || `Failed to remove container`);+ }++ toast.success(`Container removed successfully.`);+ await invalidateAll();+ } catch (error: any) {+ console.error(`Failed to remove container ${id}:`, error);+ toast.error(`Failed to remove container: ${error.message}`);+ } finally {+ isLoading.remove = false;+ }+ }++ const isRunning = $derived(itemState === 'running');+ const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));+ const removeDescription = $derived(`Are you sure you want to remove container ${id}? This action cannot be undone.`);</script>+<!-- Confirmation Dialog for Remove -->+<ConfirmDialog bind:open={showRemoveConfirm} itemType={'container'} {isRunning} title="Confirm Removal" description={removeDescription} confirmLabel="Remove" variant="destructive" onConfirm={handleRemoveConfirm} />+<DropdownMenu.Root><DropdownMenu.Trigger>{#snippet child({ props })}@@ -43,30 +94,48 @@</DropdownMenu.Trigger><DropdownMenu.Content><DropdownMenu.Group>- <DropdownMenu.Item onclick={() => viewContainer()}>+ <DropdownMenu.Item onclick={viewContainer} disabled={isAnyLoading}><Eye class="w-4 h-4" />View</DropdownMenu.Item>{#if !isRunning}- <DropdownMenu.Item onclick={() => performContainerAction('start')}>- <Play class="w-4 h-4" />+ <DropdownMenu.Item onclick={() => performContainerAction('start')} disabled={isLoading.start || isAnyLoading}>+ {#if isLoading.start}+ <Loader2 class="w-4 h-4 animate-spin" />+ {:else}+ <Play class="w-4 h-4" />+ {/if}Start</DropdownMenu.Item>{:else}- <DropdownMenu.Item onclick={() => performContainerAction('restart')}>- <RotateCcw class="w-4 h-4" />+ <DropdownMenu.Item onclick={() => performContainerAction('restart')} disabled={isLoading.restart || isAnyLoading}>+ {#if isLoading.restart}+ <Loader2 class="w-4 h-4 animate-spin" />+ {:else}+ <RotateCcw class="w-4 h-4" />+ {/if}Restart</DropdownMenu.Item>- <DropdownMenu.Item onclick={() => performContainerAction('stop')}>- <StopCircle class="w-4 h-4" />+ <DropdownMenu.Item onclick={() => performContainerAction('stop')} disabled={isLoading.stop || isAnyLoading}>+ {#if isLoading.stop}+ <Loader2 class="w-4 h-4 animate-spin" />+ {:else}+ <StopCircle class="w-4 h-4" />+ {/if}Stop</DropdownMenu.Item>{/if}- <DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={() => performContainerAction('remove')}>- <Trash2 class="w-4 h-4" />+ <DropdownMenu.Separator />++ <DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={() => performContainerAction('remove')} disabled={isLoading.remove || isAnyLoading}>+ {#if isLoading.remove}+ <Loader2 class="w-4 h-4 animate-spin" />+ {:else}+ <Trash2 class="w-4 h-4" />+ {/if}Remove</DropdownMenu.Item></DropdownMenu.Group>diff --git a/src/routes/containers/[id]/+page.svelte b/src/routes/containers/[id]/+page.svelteindex f6635145c..4896d0e73 100644--- a/src/routes/containers/[id]/+page.svelte+++ b/src/routes/containers/[id]/+page.svelte@@ -96,7 +96,7 @@<ActionButtonsid={container.id}type="container"- state={container.state?.Running ? 'running' : 'stopped'}+ itemState={container.state?.Running ? 'running' : 'stopped'}loading={{start: starting,stop: stopping,diff --git a/src/routes/containers/columns.ts b/src/routes/containers/columns.tsindex 17b0578e5..358f0a472 100644--- a/src/routes/containers/columns.ts+++ b/src/routes/containers/columns.ts@@ -53,7 +53,7 @@ export const columns: ColumnDef<ServiceContainer>[] = [cell: ({ row }) => {return renderComponent(DataTableActions, {id: row.original.id,- state: row.original.state+ itemState: row.original.state});},enableSorting: falsediff --git a/src/routes/stacks/[stackId]/+page.server.ts b/src/routes/stacks/[stackId]/+page.server.tsindex 60530e707..a4acb601d 100644--- a/src/routes/stacks/[stackId]/+page.server.ts+++ b/src/routes/stacks/[stackId]/+page.server.ts@@ -1,5 +1,5 @@import { error } from '@sveltejs/kit';-import { getStack, updateStack, startStack, stopStack, restartStack, removeStack } from '$lib/services/docker/stack-service';+import { getStack, updateStack, startStack, stopStack, restartStack, removeStack, fullyRedeployStack } from '$lib/services/docker/stack-service';/** @type {import('./$types').PageServerLoad} */export async function load({ params }) {@@ -123,5 +123,18 @@ export const actions = {error: err instanceof Error ? err.message : 'Failed to remove stack'};}+ },++ redeploy: async ({ params }) => {+ try {+ await fullyRedeployStack(params.stackId);+ return { success: true, message: 'Stack redeployment initiated' };+ } catch (err) {+ console.error('Error redeploying stack:', err);+ return {+ success: false,+ error: err instanceof Error ? err.message : 'Failed to redeploy stack'+ };+ }}};diff --git a/src/routes/stacks/[stackId]/+page.svelte b/src/routes/stacks/[stackId]/+page.svelteindex a17ca8858..644386b56 100644--- a/src/routes/stacks/[stackId]/+page.svelte+++ b/src/routes/stacks/[stackId]/+page.svelte@@ -121,7 +121,7 @@<ActionButtonsid={stack.id}type="stack"- state={stack.status}+ itemState={stack.status}loading={{start: depoloying,stop: stopping,diff --git a/src/routes/stacks/new/+page.svelte b/src/routes/stacks/new/+page.svelteindex 39916505e..bb984312d 100644--- a/src/routes/stacks/new/+page.svelte+++ b/src/routes/stacks/new/+page.svelte@@ -8,14 +8,9 @@import { Label } from '$lib/components/ui/label/index.js';import { goto, invalidateAll } from '$app/navigation';import { toast } from 'svelte-sonner';-- import { oneDark } from '@codemirror/theme-one-dark';- import { browser } from '$app/environment';-import YamlEditor from '$lib/components/yaml-editor.svelte';let saving = $state(false);- let darkMode = $state(false);let apiError = $state<string | null>(null);function preventDefault(fn: (event: Event) => any) {@@ -25,18 +20,6 @@};}- $effect(() => {- if (browser) {- darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches || document.documentElement.classList.contains('dark');- }- });-- let extensions = $state([oneDark]);-- $effect(() => {- extensions = darkMode ? [oneDark] : [];- });-const defaultComposeTemplate = `services:web:image: nginx:alpine