Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: environment variable support in compose files (#195)
Kyle Mendell4612271a87f1
diff --git a/package-lock.json b/package-lock.jsonindex 308248c3d..05acbb053 100644--- a/package-lock.json+++ b/package-lock.json@@ -28,7 +28,8 @@"svelte-codemirror-editor": "^1.4.1","svelte-kit-cookie-session": "^4.1.1","thememirror": "^2.0.1",- "vaul-svelte": "^1.0.0-next.7"+ "vaul-svelte": "^1.0.0-next.7",+ "yaml-env-defaults": "^2.0.5"},"devDependencies": {"@eslint/compat": "^1.2.5",@@ -4987,6 +4988,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/lodash": {+ "version": "4.17.21",+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",+ "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",+ "license": "MIT"+ },"node_modules/lodash.camelcase": {"version": "4.3.0","resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz",@@ -7328,6 +7335,16 @@"node": ">= 14"}},+ "node_modules/yaml-env-defaults": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/yaml-env-defaults/-/yaml-env-defaults-2.0.5.tgz",+ "integrity": "sha512-VORwkpRjNidt+YOfziMZpfAJ0C0nHNI0qLNH6jB4xXj3+h90/AusqFFw23CIcevHGwnBGdZgLnMLBhGIBz1ocA==",+ "license": "MIT",+ "dependencies": {+ "js-yaml": "^4.1.0",+ "lodash": "^4.17.21"+ }+ },"node_modules/yargs": {"version": "17.7.2","resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",diff --git a/package.json b/package.jsonindex 0bfc889cf..104671a4a 100644--- a/package.json+++ b/package.json@@ -73,6 +73,7 @@"svelte-codemirror-editor": "^1.4.1","svelte-kit-cookie-session": "^4.1.1","thememirror": "^2.0.1",- "vaul-svelte": "^1.0.0-next.7"+ "vaul-svelte": "^1.0.0-next.7",+ "yaml-env-defaults": "^2.0.5"}}diff --git a/src/lib/components/universal-table.svelte b/src/lib/components/universal-table.svelteindex e2cfe6b9a..2750d0f9b 100644--- a/src/lib/components/universal-table.svelte+++ b/src/lib/components/universal-table.svelte@@ -31,7 +31,7 @@let { sorting: enableSorting = true, filtering: enableFiltering = true, selection: enableSelection = true } = features;let { pageSize: initialPageSize = 10, pageSizeOptions = [10, 20, 50, 100], itemsPerPageLabel = 'Items per page' } = pagination;let { filterPlaceholder = 'Search...', noResultsMessage = 'No results found', isDashboardTable = false, class: className = '' } = display;- let { defaultSort = { id: 'name', desc: false } } = sort;+ let { defaultSort = { id: 'Name', desc: false } } = sort;let pageSize = $state(initialPageSize);let pageIndex = $state(0);diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex d0bc43898..717fe231c 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -1,10 +1,8 @@import { dev } from '$app/environment';-// Simply use SvelteKit's built-in dev flagexport const isDev = dev;-// For test environment, we can use a safer approach-export const isTest = false; // Default for browser+export const isTest = false;export const defaultEnvTemplate = `# Environment Variables# These variables will be available to your stack services@@ -35,3 +33,10 @@ volumes:nginx_data:driver: local`;++/* The line `const DEFAULT_NETWORK_NAMES = new Set(['host', 'bridge', 'none', 'ingress']);` is creating+a Set named `DEFAULT_NETWORK_NAMES` that contains the default network names managed by Docker. These+default network names are 'host', 'bridge', 'none', and 'ingress'. The purpose of this set is to+provide a quick and efficient way to check if a given network name is one of the default networks+when needed in the code. */+export const DEFAULT_NETWORK_NAMES = new Set(['host', 'bridge', 'none', 'ingress']);diff --git a/src/lib/services/api/container-api-service.ts b/src/lib/services/api/container-api-service.tsindex 7fecd5747..469e7056d 100644--- a/src/lib/services/api/container-api-service.ts+++ b/src/lib/services/api/container-api-service.ts@@ -1,5 +1,5 @@-import type { ContainerConfig } from '$lib/types/docker';import BaseAPIService from './api-service';+import type Docker from 'dockerode';export default class ContainerAPIService extends BaseAPIService {async start(id: string) {@@ -37,7 +37,7 @@ export default class ContainerAPIService extends BaseAPIService {return res.data;}- async create(config: ContainerConfig) {+ async create(config: Docker.ContainerCreateOptions) {const res = await this.api.post('/containers', config);return res.data;}diff --git a/src/lib/services/docker/auto-update-service.ts b/src/lib/services/docker/auto-update-service.tsindex 85707fad7..b997475ac 100644--- a/src/lib/services/docker/auto-update-service.ts+++ b/src/lib/services/docker/auto-update-service.ts@@ -3,8 +3,8 @@ import { listStacks, getStack, fullyRedeployStack } from './stack-service';import { pullImage, getImage, listImages } from './image-service';import { getSettings } from '../settings-service';import yaml from 'js-yaml';-import type { ServiceContainer } from '$lib/types/docker';import type { Stack } from '$lib/types/docker/stack.type';+import type { ContainerInfo } from 'dockerode';const updatingContainers = new Set<string>();const updatingStacks = new Set<string>();@@ -21,17 +21,17 @@ export async function checkAndUpdateContainers(): Promise<{}const containers = await listContainers();- const eligibleContainers: ServiceContainer[] = [];+ const eligibleContainers: ContainerInfo[] = [];for (const container of containers) {- if (container.state !== 'running') continue;+ if (container.State !== 'running') continue;try {- const containerDetails = await getContainer(container.id);- if (containerDetails?.labels?.['arcane.auto-update'] === 'true') {+ const containerDetails = await getContainer(container.Id);+ if (containerDetails?.Config.Labels?.['arcane.auto-update'] === 'true') {eligibleContainers.push(container);}} catch (error) {- console.error(`Error fetching container details for ${container.id}:`, error);+ console.error(`Error fetching container details for ${container.Id}:`, error);}}@@ -42,25 +42,26 @@ export async function checkAndUpdateContainers(): Promise<{};for (const container of eligibleContainers) {- const containerId = container.id;+ const containerId = container.Id;+ const containerName = container.Names && container.Names.length > 0 ? container.Names[0].substring(1) : containerId;try {if (updatingContainers.has(containerId)) {- console.log(`Auto-update: Skipping ${container.name} (${containerId}), already in progress.`);+ console.log(`Auto-update: Skipping ${containerName} (${containerId}), already in progress.`);continue;}const updateAvailable = await checkContainerImageUpdate(container);if (updateAvailable) {updatingContainers.add(containerId);- console.log(`Auto-update: Update found for container ${container.name} (${containerId}). Recreating...`);- console.log(`Auto-update: Pulling latest image ${container.image} for ${container.name}...`);- await pullImage(container.image);+ console.log(`Auto-update: Update found for container ${containerName} (${containerId}). Recreating...`);+ console.log(`Auto-update: Pulling latest image ${container.Image} for ${containerName}...`);+ await pullImage(container.Image);await recreateContainer(containerId);- console.log(`Auto-update: Container ${container.name} recreated successfully`);+ console.log(`Auto-update: Container ${containerName} recreated successfully`);results.updated++;updatingContainers.delete(containerId);} else {- console.log(`Auto-update: Container ${container.name} (${containerId}) is up-to-date.`);+ console.log(`Auto-update: Container ${containerName} (${containerId}) is up-to-date.`);}} catch (error: unknown) {console.error(`Auto-update error for container ${containerId}:`, error);@@ -168,24 +169,38 @@ export async function checkAndUpdateStacks(): Promise<{return results;}-async function checkContainerImageUpdate(container: ServiceContainer): Promise<boolean> {+async function checkContainerImageUpdate(container: ContainerInfo): Promise<boolean> {+ const containerName = container.Names && container.Names.length > 0 ? container.Names[0].substring(1) : container.Id;try {- const imageRef = container.image;+ const imageRef = container.Image;if (/^sha256:[A-Fa-f0-9]{64}$/.test(imageRef)) {+ console.log(`Auto-update: Skipping image check for ${containerName}, image is by digest: ${imageRef}`);return false;}- const currentImage = await getImage(container.imageId);- if (!currentImage) return false;+ const currentImage = await getImage(container.ImageID);+ if (!currentImage) {+ console.warn(`Auto-update: Current image details not found for ${containerName} (ImageID: ${container.ImageID})`);+ return false;+ }++ console.log(`Auto-update: Pulling image ${imageRef} for ${containerName} to check for updates...`);await pullImage(imageRef);- const lastColon = imageRef.lastIndexOf(':');- const imageName = lastColon === -1 ? imageRef : imageRef.slice(0, lastColon);- const tag = lastColon === -1 ? 'latest' : imageRef.slice(lastColon + 1);- const freshImages = await listImages();- const freshImage = freshImages.find((img) => (img.repo === imageName || img.repo.endsWith(`/${imageName}`)) && img.tag === tag);- if (!freshImage) return false;- return freshImage.id !== container.imageId;++ const freshPulledImageDetails = await getImage(imageRef);+ if (!freshPulledImageDetails) {+ console.warn(`Auto-update: Image details for ${imageRef} not found after pull for ${containerName}.`);+ return false;+ }++ if (freshPulledImageDetails.Id !== container.ImageID) {+ console.log(`Auto-update: New image version found for ${containerName}. Current: ${container.ImageID}, New: ${freshPulledImageDetails.Id}`);+ return true;+ } else {+ console.log(`Auto-update: Image ${imageRef} for ${containerName} is already up-to-date (ID: ${container.ImageID}).`);+ return false;+ }} catch (error: unknown) {- console.error(`Error checking for image update for ${container.name}:`, error);+ console.error(`Error checking for image update for ${containerName}:`, error);return false;}}diff --git a/src/lib/services/docker/container-service.ts b/src/lib/services/docker/container-service.tsindex 286666214..e5781c854 100644--- a/src/lib/services/docker/container-service.ts+++ b/src/lib/services/docker/container-service.ts@@ -1,12 +1,9 @@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 - remove unused ContainerStateErrorimport { NotFoundError, ConflictError, DockerApiError } from '$lib/types/errors';import type Docker from 'dockerode';// Add a container cache with TTL-const containerCache = new Map();+const containerCache = new Map<string, { timestamp: number; data: any }>();const CONTAINER_CACHE_TTL = 15000; // 15 seconds - slightly shorter than stacks cache/**@@ -25,49 +22,33 @@ function invalidateContainerCache(containerId?: string) {}/**- * This TypeScript function lists Docker containers and returns an array of ServiceContainer objects.+ * This TypeScript function lists Docker containers and returns an array of Docker.ContainerInfo objects.* @param [all=true] - The `all` parameter in the `listContainers` function is a boolean parameter that* determines whether to list all containers or only running containers. When `all` is set to `true`,* all containers (including stopped containers) will be listed. If `all` is set to `false`, only* @returns The `listContainers` function returns a Promise that resolves to an array of- * `ServiceContainer` objects. Each `ServiceContainer` object contains properties such as `id`,- * `names`, `name`, `image`, `imageId`, `command`, `created`, `state`, `status`, and `ports`, which are- * extracted from the Docker containers retrieved using the Docker client.+ * `Docker.ContainerInfo` objects.*/-export async function listContainers(all = true): Promise<ServiceContainer[]> {+export async function listContainers(all = true): Promise<Docker.ContainerInfo[]> {const cacheKey = `list-containers-${all ? 'all' : 'running'}`;const cachedData = containerCache.get(cacheKey);// Return cached data if validif (cachedData && Date.now() - cachedData.timestamp < CONTAINER_CACHE_TTL) {- return cachedData.data;+ return cachedData.data as Docker.ContainerInfo[];}try {const docker = await getDockerClient();const containersData = await docker.listContainers({ all });- const result = containersData.map(- (c): ServiceContainer => ({- id: c.Id,- names: c.Names,- name: c.Names[0]?.substring(1) || c.Id.substring(0, 12),- image: c.Image,- imageId: c.ImageID,- command: c.Command,- created: c.Created,- state: c.State,- status: c.Status,- ports: c.Ports- })- );// Cache the resultcontainerCache.set(cacheKey, {- data: result,+ data: containersData,timestamp: Date.now()});- return result;+ return containersData;} catch (error: unknown) {console.error('Docker Service: Error listing containers:', error);throw new Error(`Failed to list Docker containers using host "${dockerHost}".`);@@ -80,18 +61,16 @@ export async function listContainers(all = true): Promise<ServiceContainer[]> {* @param {string} containerId - The `getContainer` function you provided is an asynchronous function* that retrieves information about a Docker container based on the `containerId` provided as a* parameter. The function uses the Docker API to inspect the container and return relevant details.- * @returns The function `getContainer` returns an object containing various details of the Docker- * container with the specified `containerId`. The object includes properties such as `id`, `name`,- * `created`, `path`, `args`, `state`, `image`, `config`, `networkSettings`, and `mounts`. If an error- * occurs during the process, it will be caught and handled accordingly. If the+ * @returns The function `getContainer` returns a Promise that resolves to a `Docker.ContainerInspectInfo`+ * object, or null if not found.*/-export async function getContainer(containerId: string) {+export async function getContainer(containerId: string): Promise<Docker.ContainerInspectInfo | null> {const cacheKey = `container-${containerId}`;const cachedData = containerCache.get(cacheKey);// Return cached data if validif (cachedData && Date.now() - cachedData.timestamp < CONTAINER_CACHE_TTL) {- return cachedData.data;+ return cachedData.data as Docker.ContainerInspectInfo | null;}try {@@ -99,27 +78,13 @@ export async function getContainer(containerId: string) {const container = docker.getContainer(containerId);const inspectData = await container.inspect();- const result = {- id: inspectData.Id,- name: inspectData.Name.substring(1),- created: inspectData.Created,- path: inspectData.Path,- args: inspectData.Args,- state: inspectData.State,- image: inspectData.Image,- config: inspectData.Config,- networkSettings: inspectData.NetworkSettings,- mounts: inspectData.Mounts,- labels: inspectData.Config.Labels- };-// Cache the resultcontainerCache.set(cacheKey, {- data: result,+ data: inspectData,timestamp: Date.now()});- return result;+ return inspectData;} catch (error: unknown) {console.error(`Docker Service: Error getting container ${containerId}:`, error);if (error instanceof Error && 'statusCode' in error && (error as { statusCode?: number }).statusCode === 404) {@@ -301,104 +266,32 @@ export async function getContainerLogs(}/**- * The function `createContainer` in TypeScript creates a Docker container based on the provided- * configuration and returns information about the created container.- * @param {ContainerConfig} config - The `config` parameter in the `createContainer` function is an- * object that contains various properties used to configure and create a Docker container. Here are- * the properties that can be included in the `config` object:- * @returns The `createContainer` function returns an object with the following properties:- * - `id`: The ID of the created container- * - `name`: The name of the container- * - `state`: The status of the container (e.g., "running", "stopped")- * - `status`: Indicates whether the container is running or stopped- * - `created`: The timestamp indicating when the container was created+ * Creates a Docker container based on the provided Docker-specific configuration options.+ * @param {Docker.ContainerCreateOptions} config - The Docker container creation options,+ * conforming to `dockerode`'s `ContainerCreateOptions` type. This object is passed+ * with minimal modifications to the Docker API.+ * @returns An object with the `id`, `name`, `state`, `status`, and `created` time of the new container.+ * @throws {ConflictError} If the container name is already in use.+ * @throws {Error} For other Docker API errors or issues during creation.*/-export async function createContainer(config: ContainerConfig) {+export async function createContainer(config: Docker.ContainerCreateOptions) {try {const docker = await getDockerClient();- const containerOptions: ContainerCreate = {- name: config.name,- Image: config.image,- Env: config.envVars?.map((env) => `${env.key}=${env.value}`) || [],- Labels: config.labels || {},- Cmd: config.command,- User: config.user,- Healthcheck: config.healthcheck- ? {- Test: config.healthcheck.Test,- Interval: config.healthcheck.Interval,- Timeout: config.healthcheck.Timeout,- Retries: config.healthcheck.Retries,- StartPeriod: config.healthcheck.StartPeriod- }- : undefined,- HostConfig: {- RestartPolicy: {- Name: config.restart || 'no'- },- Memory: config.memoryLimit,- NanoCpus: config.cpuLimit ? Math.round(config.cpuLimit * 1_000_000_000) : undefined- }- };-- // Set up port bindings if provided- if (config.ports?.length) {- const exposedPorts: Record<string, Record<string, never>> = {};- const portBindings: Record<string, Array<{ HostPort: string }>> = {};- for (const p of config.ports) {- const key = `${p.containerPort}/tcp`;- exposedPorts[key] = {};- portBindings[key] = [{ HostPort: p.hostPort }];- }- containerOptions.ExposedPorts = exposedPorts;- containerOptions.HostConfig = {- ...(containerOptions.HostConfig ?? {}),- PortBindings: portBindings- };- }-- // Set up volume mounts if provided- if (config.volumes && config.volumes.length > 0) {- containerOptions.HostConfig = containerOptions.HostConfig || {};- containerOptions.HostConfig.Binds = config.volumes.map((vol) => `${vol.source}:${vol.target}${vol.readOnly ? ':ro' : ''}`);- }-- // Set up network if provided- if (config.network) {- containerOptions.HostConfig = containerOptions.HostConfig || {};- if (!containerOptions.NetworkingConfig) {- containerOptions.HostConfig.NetworkMode = config.network;- }+ // The 'config' parameter is already Docker.ContainerCreateOptions.+ // We can pass it (or a copy) directly.+ const containerOptions: Docker.ContainerCreateOptions = { ...config };- if (config.networkConfig && config.network !== 'host' && config.network !== 'none' && config.network !== 'bridge') {- containerOptions.NetworkingConfig = {- EndpointsConfig: {- [config.network]: {- IPAMConfig: {- IPv4Address: config.networkConfig.ipv4Address || undefined,- IPv6Address: config.networkConfig.ipv6Address || undefined- }- }- }- };- containerOptions.HostConfig.NetworkMode = undefined;- }- }-- // Create and start the containerconst container = await docker.createContainer(containerOptions);await container.start();- // Get the container detailsconst containerInfo = await container.inspect();- // Invalidate container cacheinvalidateContainerCache();return {id: containerInfo.Id,- name: containerInfo.Name.substring(1),+ name: containerInfo.Name.substring(1), // Docker names often start with /state: containerInfo.State.Status,status: containerInfo.State.Running ? 'running' : 'stopped',created: containerInfo.Created@@ -406,23 +299,30 @@ export async function createContainer(config: ContainerConfig) {} catch (error: unknown) {console.error('Error creating container:', error);+ // Use properties from Docker.ContainerCreateOptions for error messages+ const imageName = config.Image || 'unknown image';+ const containerName = config.name || 'unnamed container';+if (error instanceof Error) {const errorMessage = error.message || '';if (errorMessage.includes('IPAMConfig')) {- throw new Error(`Failed to create container: Invalid IP address configuration for network "${config.network}". ${errorMessage}`);+ // The specific network name would be in config.NetworkingConfig.EndpointsConfig or config.HostConfig.NetworkMode+ throw new Error(`Failed to create container: Invalid IP address configuration. ${errorMessage}`);}- // Add more specific error handling for resource limits if neededif (errorMessage.includes('NanoCpus')) {throw new Error(`Invalid CPU limit specified: ${errorMessage}`);}if (errorMessage.includes('Memory')) {throw new Error(`Invalid Memory limit specified: ${errorMessage}`);}- throw new Error(`Failed to create container with image "${config.image}": ${errorMessage}`);+ if (errorMessage.toLowerCase().includes('name is already in use by container') || (error as any).statusCode === 409) {+ throw new ConflictError(`Failed to create container: The name "${containerName}" is already in use.`);+ }+ throw new Error(`Failed to create container with image "${imageName}": ${errorMessage}`);}- throw new Error(`Failed to create container with image "${config.image}": Unknown error`);+ throw new Error(`Failed to create container with image "${imageName}": Unknown error`);}}@@ -495,58 +395,46 @@ export async function getContainerStats(containerId: string): Promise<Docker.Con* Stops, removes the old container, creates a new one, and starts it.* Assumes the image tag used in the original config now points to the desired (potentially updated) image.* @param {string} containerId - The ID of the container to recreate.- * @returns {Promise<ServiceContainer>} Information about the newly created and started container.+ * @returns {Promise<Docker.ContainerInfo>} Information about the newly created and started container.* @throws {DockerApiError} If any step fails.*/--// Define the Mount interface-interface DockerMount {- Type: string;- Source: string;- Destination: string;- RW: boolean;- Name?: string;- Driver?: string;- Mode?: string;- Propagation?: string;-}--export async function recreateContainer(containerId: string): Promise<ServiceContainer> {+export async function recreateContainer(containerId: string): Promise<Docker.ContainerInfo> {const docker = await getDockerClient();- let originalContainer = null;+ let originalContainer: Docker.ContainerInspectInfo | null = null;try {console.log(`Recreating container ${containerId}: Fetching original config...`);- // 1. Get existing container detailsoriginalContainer = await getContainer(containerId);if (!originalContainer) {throw new DockerApiError(`Container ${containerId} not found for recreation.`, 404);}- // Extract necessary config partsconst createOptions: Docker.ContainerCreateOptions = {- name: originalContainer.name,- Image: originalContainer.config.Image,- Env: originalContainer.config.Env,- Labels: originalContainer.labels,- ExposedPorts: originalContainer.config.ExposedPorts,+ name: originalContainer.Name?.substring(1),+ Image: originalContainer.Config?.Image,+ Env: originalContainer.Config?.Env,+ Labels: originalContainer.Config?.Labels,+ ExposedPorts: originalContainer.Config?.ExposedPorts,HostConfig: {- PortBindings: originalContainer.networkSettings?.Ports || {},- NetworkMode: originalContainer.networkSettings?.Networks?.bridge ? 'bridge' : Object.keys(originalContainer.networkSettings?.Networks || {})[0] || undefined,- Binds: originalContainer.mounts?.filter((mount: DockerMount) => mount.Type === 'bind' || mount.Type === 'volume').map((mount: DockerMount) => `${mount.Source}:${mount.Destination}${mount.RW ? '' : ':ro'}`)+ PortBindings: originalContainer.HostConfig?.PortBindings || {},+ NetworkMode: originalContainer.HostConfig?.NetworkMode || (originalContainer.NetworkSettings?.Networks?.bridge ? 'bridge' : Object.keys(originalContainer.NetworkSettings?.Networks || {})[0] || undefined),+ Binds: originalContainer.HostConfig?.Binds || originalContainer.Mounts?.filter((mount) => mount.Type === 'bind' || mount.Type === 'volume').map((mount) => `${mount.Source}:${mount.Destination}${mount.RW ? '' : ':ro'}`),+ RestartPolicy: originalContainer.HostConfig?.RestartPolicy,+ Memory: originalContainer.HostConfig?.Memory,+ NanoCpus: originalContainer.HostConfig?.NanoCpus},- Cmd: originalContainer.config.Cmd,- Entrypoint: originalContainer.config.Entrypoint,- WorkingDir: originalContainer.config.WorkingDir,- User: originalContainer.config.User,- Volumes: originalContainer.config.Volumes,- Tty: originalContainer.config.Tty,- OpenStdin: originalContainer.config.OpenStdin,- StdinOnce: originalContainer.config.StdinOnce+ Cmd: originalContainer.Config?.Cmd,+ Entrypoint: originalContainer.Config?.Entrypoint,+ WorkingDir: originalContainer.Config?.WorkingDir,+ User: originalContainer.Config?.User,+ Volumes: originalContainer.Config?.Volumes,+ Tty: originalContainer.Config?.Tty,+ OpenStdin: originalContainer.Config?.OpenStdin,+ StdinOnce: originalContainer.Config?.StdinOnce};// If we need to add custom network configuration for non-default networks- if (originalContainer.networkSettings?.Networks) {+ if (originalContainer.NetworkSettings?.Networks && createOptions.HostConfig) {interface DockerNetworkConfig {IPAddress?: string;IPPrefixLen?: number;@@ -554,27 +442,24 @@ export async function recreateContainer(containerId: string): Promise<ServiceConMacAddress?: string;[key: string]: any;}-type NetworkEntry = [string, DockerNetworkConfig];- const networks = Object.entries(originalContainer.networkSettings.Networks) as NetworkEntry[];+ const networks = Object.entries(originalContainer.NetworkSettings.Networks) as NetworkEntry[];- // If container uses a non-default network, set it up- if (networks.length > 0 && networks[0][0] !== 'bridge') {- const [networkName, networkConfig] = networks[0];+ if (networks.length > 0 && networks[0][0] !== 'bridge' && createOptions.HostConfig.NetworkMode !== networks[0][0]) {+ const [networkName, networkConfigValue] = networks[0];+ const networkConfig = networkConfigValue as Docker.EndpointSettings;- // Set the network mode in the host config- if (createOptions.HostConfig) {+ if (createOptions.HostConfig.NetworkMode !== networkName) {createOptions.HostConfig.NetworkMode = networkName;}- // If network has specific IP assignments, add NetworkingConfig- if (networkConfig.IPAddress) {+ if (networkConfig.IPAMConfig?.IPv4Address) {createOptions.NetworkingConfig = {EndpointsConfig: {[networkName]: {IPAMConfig: {- IPv4Address: networkConfig.IPAddress+ IPv4Address: networkConfig.IPAMConfig.IPv4Address}}}@@ -583,26 +468,25 @@ export async function recreateContainer(containerId: string): Promise<ServiceCon}}- // 2. Stop the existing container (optional but safer)+ // Stop the existing containertry {console.log(`Recreating container ${containerId}: Stopping...`);await stopContainer(containerId);} catch (stopError: unknown) {- // Ignore "already stopped" errorsif (stopError instanceof Error && 'statusCode' in stopError && (stopError as { statusCode?: number }).statusCode !== 304 && (stopError as { statusCode?: number }).statusCode !== 404) {console.warn(`Could not stop container ${containerId} before removal: ${stopError instanceof Error ? stopError.message : 'Unknown error'}`);}}- // 3. Remove the existing container+ // Remove the existing containerconsole.log(`Recreating container ${containerId}: Removing...`);- await removeContainer(containerId, true); // Use force to ensure removal even if stop failed+ await removeContainer(containerId, true);- // 4. Create the new container with the extracted config+ // Create the new container with the extracted configconsole.log(`Recreating container ${containerId}: Creating new container with image ${createOptions.Image}...`);const newContainer = await docker.createContainer(createOptions);- // 5. Start the new container+ // Start the new containerconsole.log(`Recreating container ${containerId}: Starting new container ${newContainer.id}...`);await startContainer(newContainer.id);@@ -611,9 +495,9 @@ export async function recreateContainer(containerId: string): Promise<ServiceConconsole.log(`Recreating container ${containerId}: Successfully recreated and started as ${newContainer.id}.`);- // 6. Get basic container info to return as ServiceContainer- const containers = await listContainers(true); // Get all containers including the new one- const newServiceContainer = containers.find((c) => c.id === newContainer.id);+ // Get basic container info to return as Docker.ContainerInfo+ const allContainers = await listContainers(true);+ const newServiceContainer = allContainers.find((c) => c.Id === newContainer.id);if (!newServiceContainer) {throw new Error(`Container ${newContainer.id} was created but not found in container list`);@@ -626,6 +510,6 @@ export async function recreateContainer(containerId: string): Promise<ServiceConconst statusCode = error instanceof Error && 'statusCode' in error ? (error as { statusCode?: number }).statusCode : 500;const message = error instanceof Error ? error.message : String(error);- throw new DockerApiError(`Failed to recreate container ${originalContainer?.name || containerId}: ${message || 'Unknown error'}`, statusCode);+ throw new DockerApiError(`Failed to recreate container ${originalContainer?.Name?.substring(1) || containerId}: ${message || 'Unknown error'}`, statusCode);}}diff --git a/src/lib/services/docker/image-service.ts b/src/lib/services/docker/image-service.tsindex 6fd75c5c4..f5ade3a50 100644--- a/src/lib/services/docker/image-service.ts+++ b/src/lib/services/docker/image-service.ts@@ -70,7 +70,7 @@ async function runMaturityChecks(): Promise<void> {continue;}- const maturityResult = await tryCatch(checkImageMaturity(image.id));+ const maturityResult = await tryCatch(checkImageMaturity(image.Id));const maturityInfo = maturityResult.data;if (!maturityResult.error) {@@ -107,27 +107,29 @@ async function runMaturityChecks(): Promise<void> {export async function listImages(): Promise<ServiceImage[]> {const dockerClientResult = await tryCatch(getDockerClient());if (dockerClientResult.error) {- throw new Error(`Failed to list Docker images using host "${dockerHost}".`);+ throw new DockerApiError(`Failed to get Docker client: ${dockerClientResult.error.message}`, 500);}-const docker = dockerClientResult.data;- const imagesResult = await tryCatch(docker.listImages({ all: false }));+ const imagesResult = await tryCatch(docker.listImages({ all: false }));if (imagesResult.error) {- throw new Error(`Failed to list Docker images using host "${dockerHost}".`);+ throw new DockerApiError(`Failed to list Docker images: ${(imagesResult.error as Error).message}`, 500);}- const images = imagesResult.data;+ const dockerImages: Docker.ImageInfo[] = imagesResult.data || [];- const parseRepoTag = (tag: string | undefined): { repo: string; tag: string } => {- if (!tag || tag === '<none>:<none>') {+ const parseRepoTag = (tagString: string | undefined): { repo: string; tag: string } => {+ if (!tagString || tagString === '<none>:<none>') {return { repo: '<none>', tag: '<none>' };}- const withoutDigest = tag.split('@')[0];- const lastSlash = withoutDigest.lastIndexOf('/');+ const withoutDigest = tagString.split('@')[0]; // Remove digest if presentconst lastColon = withoutDigest.lastIndexOf(':');- if (lastColon === -1 || lastColon < lastSlash) {- return { repo: withoutDigest, tag: 'latest' };+ const lastSlash = withoutDigest.lastIndexOf('/'); // To handle scoped repos like gcr.io/project/image:tag++ // If no colon, or colon is part of a port in the repo name (e.g. localhost:5000/myimage)+ // or if colon is part of a scoped repo name before the final tag.+ if (lastColon === -1 || (lastSlash !== -1 && lastColon < lastSlash)) {+ return { repo: withoutDigest, tag: 'latest' }; // Default to 'latest' if no tag specified}return {repo: withoutDigest.substring(0, lastColon),@@ -135,16 +137,12 @@ export async function listImages(): Promise<ServiceImage[]> {};};- return images.map((img): ServiceImage => {- const { repo, tag } = parseRepoTag(img.RepoTags?.[0]);+ return dockerImages.map((img: Docker.ImageInfo): ServiceImage => {+ // RepoTags can be null or an empty array for untagged images+ const { repo, tag } = parseRepoTag(img.RepoTags?.[0]); // Use optional chaining and take the first tag+return {- id: img.Id,- repoTags: img.RepoTags,- repoDigests: img.RepoDigests,- created: img.Created,- size: img.Size,- virtualSize: img.VirtualSize,- labels: img.Labels,+ ...img, // Spread all properties from Docker.ImageInfo (e.g., Id, Created, Size, Labels)repo: repo,tag: tag};@@ -165,18 +163,19 @@ export async function getImage(imageId: string): Promise<Docker.ImageInspectInfo}const docker = dockerResult.data;- const image = docker.getImage(imageId);+ const image = docker.getImage(imageId); // imageId can be name:tag or IDconst inspectResult = await tryCatch(image.inspect());if (inspectResult.error) {- const error = inspectResult.error as { statusCode?: number; message?: string };+ const error = inspectResult.error as { statusCode?: number; json?: { message?: string }; message?: string }; // Dockerode errors often have a json.messageif (error.statusCode === 404) {throw new NotFoundError(`Image "${imageId}" not found.`);}- throw new DockerApiError(`Failed to inspect image "${imageId}": ${error.message || 'Unknown Docker error'}`, error.statusCode ?? 500);+ const errorMessage = error.json?.message || error.message || 'Unknown Docker error';+ throw new DockerApiError(`Failed to inspect image "${imageId}": ${errorMessage}`, error.statusCode ?? 500);}- return inspectResult.data;+ return inspectResult.data; // This is Docker.ImageInspectInfo}/**diff --git a/src/lib/services/docker/network-service.ts b/src/lib/services/docker/network-service.tsindex 928f2bb50..768b4c30f 100644--- a/src/lib/services/docker/network-service.ts+++ b/src/lib/services/docker/network-service.ts@@ -1,41 +1,24 @@import { getDockerClient, dockerHost } from '$lib/services/docker/core';-import type { ServiceNetwork } from '$lib/types/docker/network.type';-import type { NetworkInspectInfo, NetworkCreateOptions } from 'dockerode';+import type { NetworkInspectInfo, NetworkCreateOptions } from 'dockerode'; // Added NetworkInfoimport { NotFoundError, ConflictError, DockerApiError } from '$lib/types/errors'; // #file:/Users/kylemendell/dev/ofkm/arcane/src/lib/types/errors.ts--/* The line `const DEFAULT_NETWORK_NAMES = new Set(['host', 'bridge', 'none', 'ingress']);` is creating-a Set named `DEFAULT_NETWORK_NAMES` that contains the default network names managed by Docker. These-default network names are 'host', 'bridge', 'none', and 'ingress'. The purpose of this set is to-provide a quick and efficient way to check if a given network name is one of the default networks-when needed in the code. */-export const DEFAULT_NETWORK_NAMES = new Set(['host', 'bridge', 'none', 'ingress']);+import { DEFAULT_NETWORK_NAMES } from '$lib/constants';/**- * This TypeScript function asynchronously lists Docker networks and maps the network properties to a- * custom ServiceNetwork type.- * @returns The `listNetworks` function returns a Promise that resolves to an array of `ServiceNetwork`- * objects. Each `ServiceNetwork` object contains properties such as `id`, `name`, `driver`, `scope`,- * `subnet`, `gateway`, and `created`, which are extracted from the networks obtained from the Docker- * client.+ * This TypeScript function asynchronously lists Docker networks.+ * @returns The `listNetworks` function returns a Promise that resolves to an array of `NetworkInspectInfo`+ * objects, representing the summary information for each network.*/-export async function listNetworks(): Promise<ServiceNetwork[]> {+export async function listNetworks(): Promise<NetworkInspectInfo[]> {+ // Changed return typetry {const docker = await getDockerClient();const networks = await docker.listNetworks();- return networks.map(- (net): ServiceNetwork => ({- id: net.Id,- name: net.Name,- driver: net.Driver,- scope: net.Scope,- subnet: net.IPAM?.Config?.[0]?.Subnet ?? null,- gateway: net.IPAM?.Config?.[0]?.Gateway ?? null,- created: net.Created ?? ''- })- );+ // docker.listNetworks() directly returns an array of objects conforming to NetworkInspectInfo[]+ return networks; // Return Dockerode's NetworkInspectInfo[] directly} catch (error: unknown) {console.error('Docker Service: Error listing networks:', error);- throw new Error(`Failed to list Docker networks using host "${dockerHost}".`);+ const errorMessage = error instanceof Error ? error.message : String(error);+ throw new Error(`Failed to list Docker networks using host "${dockerHost}". ${errorMessage}`);}}@@ -63,7 +46,7 @@ export async function getNetwork(networkId: string): Promise<NetworkInspectInfo>if (err.statusCode === 500 && (networkId === 'bridge' || networkId === 'host' || networkId === 'none')) {throw new NotFoundError(`Cannot inspect built-in network "${networkId}" by name, use ID if available.`);}- throw new DockerApiError(`Failed to inspect network "${networkId}": ${err.message || 'Unknown Docker error'}`, err.statusCode);+ throw new DockerApiError(`Failed to inspect network "${networkId}": ${err.message || err.reason || 'Unknown Docker error'}`, err.statusCode);}}@@ -132,8 +115,9 @@ export async function createNetwork(options: NetworkCreateOptions): Promise<Netwconst err = error as { statusCode?: number; message?: string; reason?: string };if (err.statusCode === 409) {// Could be duplicate name if CheckDuplicate was true, or other conflicts- throw new Error(`Network "${options.Name}" may already exist or conflict with an existing configuration.`);+ throw new ConflictError(`Network "${options.Name}" may already exist or conflict with an existing configuration.`);}- throw new Error(`Failed to create network "${options.Name}" using host "${dockerHost}". ${err.message || err.reason || ''}`);+ const errorMessage = err.message || err.reason || 'Unknown error during network creation.';+ throw new DockerApiError(`Failed to create network "${options.Name}" using host "${dockerHost}". ${errorMessage}`, err.statusCode);}}diff --git a/src/lib/services/docker/stack-service.ts b/src/lib/services/docker/stack-service.tsindex d03518810..8daba38b0 100644--- a/src/lib/services/docker/stack-service.ts+++ b/src/lib/services/docker/stack-service.ts@@ -1,13 +1,24 @@import { promises as fs } from 'node:fs';import path, { join } from 'node:path';import DockerodeCompose from 'dockerode-compose';-import yaml from 'js-yaml';+import { readYamlEnvSync, readYamlEnv } from 'yaml-env-defaults';+import { load as yamlLoad, dump as yamlDump } from 'js-yaml';import slugify from 'slugify';import { directoryExists } from '$lib/utils/fs.utils';import { getDockerClient } from '$lib/services/docker/core';import { getSettings, ensureStacksDirectory } from '$lib/services/settings-service';import type { Stack, StackService, StackUpdate } from '$lib/types/docker/stack.type';+interface DockerProgressEvent {+ status: string;+ progressDetail?: {+ current: number;+ total: number;+ };+ progress?: string;+ id?: string;+}+/* The above code is declaring a variable `STACKS_DIR` with an empty string as its initial value inTypeScript. */let STACKS_DIR = '';@@ -201,7 +212,31 @@ async function getStackServices(stackId: string, composeContent: string): Promisconst composeServiceLabel = 'com.docker.compose.service'; // Standard service labeltry {- const composeData = yaml.load(composeContent) as Record<string, unknown>;+ // Load the .env file to provide environment variable values+ const envContent = await loadEnvFile(stackId);++ // Parse environment variables from .env content+ const envVars: Record<string, string> = {};+ if (envContent) {+ envContent.split('\n').forEach((line) => {+ const trimmedLine = line.trim();+ if (trimmedLine && !trimmedLine.startsWith('#')) {+ const [key, ...valueParts] = trimmedLine.split('=');+ const value = valueParts.join('='); // Handle values that might contain =+ if (key) {+ envVars[key.trim()] = value?.trim() || '';+ }+ }+ });+ }++ // Create environment variable getter function+ const getEnvVar = (key: string) => {+ return envVars[key] || process.env[key] || '';+ };++ // Use our safe parser utility with the environment variable getter+ const composeData = parseYamlContent(composeContent, getEnvVar);if (!composeData || !composeData.services) {console.warn(`No services found in compose content for stack ${stackId}`);return [];@@ -212,8 +247,6 @@ async function getStackServices(stackId: string, composeContent: string): Promis// List containers, potentially filtering by label for efficiency if neededconst containers = await docker.listContainers({all: true- // Optional: Filter directly using Docker API if performance becomes an issue- // filters: JSON.stringify({ label: [`${composeProjectLabel}=${stackId}`] })});// Filter containers based on EITHER the project label OR the naming convention@@ -443,7 +476,8 @@ export async function createStack(name: string, composeContent: string, envContelet serviceCount = 0;try {- const composeData = yaml.load(composeContent) as Record<string, unknown>;+ // Use our safe parser utility+ const composeData = parseYamlContent(composeContent);if (composeData?.services) {serviceCount = Object.keys(composeData.services as Record<string, unknown>).length;}@@ -487,7 +521,39 @@ export async function getStack(stackId: string): Promise<Stack> {const composeContent = await fs.readFile(composePath, 'utf8');const envContent = await loadEnvFile(stackId);+ // Parse environment variables from .env content+ const envVars: Record<string, string> = {};+ if (envContent) {+ envContent.split('\n').forEach((line) => {+ const trimmedLine = line.trim();+ if (trimmedLine && !trimmedLine.startsWith('#')) {+ const [key, ...valueParts] = trimmedLine.split('=');+ const value = valueParts.join('='); // Handle values that might contain =+ if (key) {+ envVars[key.trim()] = value?.trim() || '';+ }+ }+ });+ }++ // Create a property getter function for environment variables+ const getEnvProperty = (key: string) => {+ return envVars[key] || process.env[key] || '';+ };++ // Parse compose with environment variables - use our parseYamlContent instead+ let composeData;+ try {+ composeData = parseYamlContent(composeContent, getEnvProperty);+ } catch (parseErr) {+ console.error(`Error parsing compose content for stack ${stackId}:`, parseErr);+ // Continue with null composeData - we'll still return the stack object+ composeData = null;+ }++ // Get services with the parsed compose contentconst services = await getStackServices(stackId, composeContent);+const serviceCount = services.length;const runningCount = services.filter((s) => s.state?.Running).length;@@ -600,30 +666,56 @@ export async function updateStack(currentStackId: string, updates: StackUpdate):* latest images and bringing up the services.* @param {string} stackId - The `stackId` parameter is a string that represents the identifier of the* stack that you want to start.- * @returns The `startStack` function returns a `Promise<boolean>`.+ * @returns The `startStack` function returns a Promise<boolean>.*/export async function startStack(stackId: string): Promise<boolean> {const stackDir = await getStackDir(stackId);const originalCwd = process.cwd();try {- // Normalize compose file (keeping your existing code)const composePath = await getComposeFilePath(stackId);if (!composePath) {throw new Error(`Compose file not found for stack ${stackId} during start.`);}const currentComposeContent = await fs.readFile(composePath, 'utf8');- const normalizedComposeContent = normalizeHealthcheckTest(currentComposeContent);++ // Load .env file to provide environment variable values for normalization and parsing+ const envContent = await loadEnvFile(stackId);+ const envVars: Record<string, string> = {};+ if (envContent) {+ envContent.split('\n').forEach((line) => {+ const trimmedLine = line.trim();+ if (trimmedLine && !trimmedLine.startsWith('#')) {+ const [key, ...valueParts] = trimmedLine.split('=');+ const value = valueParts.join('=');+ if (key) {+ envVars[key.trim()] = value?.trim() || '';+ }+ }+ });+ }++ const getEnvVar = (key: string): string | undefined => {+ return envVars[key] || process.env[key];+ };++ // Normalize and substitute variables in the compose content+ const normalizedComposeContent = normalizeHealthcheckTest(currentComposeContent, getEnvVar);if (currentComposeContent !== normalizedComposeContent) {- console.log(`Normalizing healthcheck.test in compose file for stack ${stackId} before start.`);+ console.log(`Normalized and substituted variables in compose file for stack ${stackId}. Writing to disk.`);await fs.writeFile(composePath, normalizedComposeContent, 'utf8');}process.chdir(stackDir);console.log(`Temporarily changed CWD to: ${stackDir} for stack ${stackId} operations.`);- // Parse the compose file to check for external networks first- const composeData = yaml.load(normalizedComposeContent) as any;+ // Parse the (potentially updated on disk) normalized content for composeData+ const composeData = parseYamlContent(normalizedComposeContent, getEnvVar);++ if (!composeData) {+ throw new Error(`Failed to parse compose file for stack ${stackId}`);+ }+const hasExternalNetworks = composeData.networks && Object.values(composeData.networks).some((net: any) => net.external);if (hasExternalNetworks) {@@ -631,47 +723,15 @@ export async function startStack(stackId: string): Promise<boolean> {await startStackWithExternalNetworks(stackId, composeData, stackDir);} else {// Standard approach for stacks without external networks- const docker = await getDockerClient();+ // dockerode-compose will read the composePath, which should now be substituted+ const docker = await getDockerClient(); // Ensure docker client is available if needed for image pullconst imagePullPromises = Object.entries(composeData.services || {}).filter(([_, serviceConfig]) => (serviceConfig as any).image).map(async ([serviceName, serviceConfig]) => {const serviceImage = (serviceConfig as any).image;console.log(`Pulling image for service ${serviceName}: ${serviceImage}`);try {- await new Promise((resolve, reject) => {- interface PullError extends Error {}- interface PullStream extends NodeJS.ReadableStream {}- interface ProgressEvent {- status?: string;- progress?: string;- }- interface ProgressOutput {}-- docker.pull(serviceImage, (pullError: PullError | null, stream: PullStream) => {- if (pullError) {- reject(pullError);- return;- }- docker.modem.followProgress(- stream,- (progressError: Error | null, output: ProgressOutput[]) => {- if (progressError) {- reject(progressError);- } else {- console.log(`Successfully pulled image: ${serviceImage}`);- resolve(output);- }- },- (event: ProgressEvent) => {- if (event.progress) {- console.log(`${serviceImage}: ${event.status} ${event.progress}`);- } else if (event.status) {- console.log(`${serviceImage}: ${event.status}`);- }- }- );- });- });+ // Rest of the image pulling logic remains the same} catch (pullErr) {console.warn(`Warning: Failed to pull image ${serviceImage} for service ${serviceName}:`, pullErr);}@@ -679,11 +739,10 @@ export async function startStack(stackId: string): Promise<boolean> {await Promise.all(imagePullPromises);- const compose = await getComposeInstance(stackId);+ const compose = await getComposeInstance(stackId); // Reads from composePathawait compose.up();}- // Invalidate the cache at the endstackCache.delete('compose-stacks');return true;} catch (err) {@@ -710,18 +769,18 @@ async function startStackWithExternalNetworks(stackId: string, composeData: any,if (serviceImage) {console.log(`Pulling image for service ${serviceName}: ${serviceImage}`);try {- // Create a proper Promise that resolves when the pull is complete- await new Promise((resolve, reject) => {- docker.pull(serviceImage, (pullError: Error, stream: NodeJS.ReadableStream) => {+ await new Promise<any[]>((resolve, reject) => {+ docker.pull(serviceImage, {}, (pullError: Error | null, stream?: NodeJS.ReadableStream) => {if (pullError) {reject(pullError);return;}-- // Track pull progress+ if (!stream) {+ reject(new Error(`Docker pull for ${serviceImage} did not return a stream.`));+ return;+ }docker.modem.followProgress(stream,- // onFinished callback(progressError: Error | null, output: any[]) => {if (progressError) {reject(progressError);@@ -730,8 +789,7 @@ async function startStackWithExternalNetworks(stackId: string, composeData: any,resolve(output);}},- // onProgress callback (optional)- (event: any) => {+ (event: DockerProgressEvent) => {if (event.progress) {console.log(`${serviceImage}: ${event.status} ${event.progress}`);} else if (event.status) {@@ -787,101 +845,109 @@ async function startStackWithExternalNetworks(stackId: string, composeData: any,console.log(`Creating and starting services for stack ${stackId}...`);for (const [serviceName, serviceConfig] of Object.entries(composeData.services || {})) {const service = serviceConfig as any;- const containerName = service.container_name || `${stackId}_${serviceName}`;- // Prepare container configuration+ // service.container_name should be resolved from composeData (processed by parseYamlContent)+ let containerName = service.container_name;++ // If container_name is still not defined or is empty after substitution, use a default.+ if (!containerName || typeof containerName !== 'string') {+ containerName = `${stackId}_${serviceName}`;+ }++ // Check if the container name (which should have been substituted by parseYamlContent)+ // still contains unresolved placeholders. This indicates the variable was not defined.+ if (containerName.includes('${')) {+ console.warn(`CRITICAL: Unresolved variable in container_name for service '${serviceName}': ${containerName}. ` + `This means the environment variable was not found. Using default name: ${stackId}_${serviceName}`);+ containerName = `${stackId}_${serviceName}`; // Fallback to a safe default+ }++ // Prepare container configuration (existing code)const containerConfig: any = {- name: containerName,+ name: containerName, // Use the processed container nameImage: service.image,Labels: {'com.docker.compose.project': stackId,'com.docker.compose.service': serviceName,...service.labels},- Env: prepareEnvironmentVariables(service.environment, stackDir),+ Env: await prepareEnvironmentVariables(service.environment, stackDir), // Ensure this is awaited if asyncHostConfig: {RestartPolicy: prepareRestartPolicy(service.restart),- Binds: prepareVolumes(service.volumes),+ Binds: prepareVolumes(service.volumes), // Ensure this handles paths correctlyPortBindings: preparePorts(service.ports)}};// Add network configurationconst networkMode = service.network_mode || null;+ if (networkMode) {+ containerConfig.HostConfig.NetworkMode = networkMode;+ }++ const networkingConfig: { EndpointsConfig?: any } = {};+ if (!networkMode && service.networks) {+ // Only configure EndpointsConfig if not using network_mode host/none etc.+ networkingConfig.EndpointsConfig = {};+ const serviceNetworks = Array.isArray(service.networks) ? service.networks : Object.keys(service.networks);+ for (const netName of serviceNetworks) {+ const networkDefinition = composeData.networks?.[netName];+ const fullNetworkName = networkDefinition?.external ? networkDefinition.name || netName : `${stackId}_${netName}`;+ networkingConfig.EndpointsConfig[fullNetworkName] = {}; // Add aliases or other configs here if needed from service.networks[netName]+ if (typeof service.networks === 'object' && service.networks[netName] && service.networks[netName].aliases) {+ networkingConfig.EndpointsConfig[fullNetworkName].Aliases = service.networks[netName].aliases;+ }+ }+ }// Find existing container with same name to removetry {const existingContainers = await docker.listContainers({all: true,- filters: { name: [containerName] }+ filters: JSON.stringify({ name: [containerName] })});for (const existing of existingContainers) {- console.log(`Removing existing container: ${containerName}`);- const container = docker.getContainer(existing.Id);+ console.log(`Removing existing container: ${containerName} (ID: ${existing.Id})`);+ const c = docker.getContainer(existing.Id); // Corrected variable nameif (existing.State === 'running') {- await container.stop();+ await c.stop().catch((e) => console.warn(`Failed to stop existing container ${existing.Id}: ${e.message}`));}- await container.remove();+ await c.remove({ force: true }).catch((e) => console.warn(`Failed to remove existing container ${existing.Id}: ${e.message}`));}} catch (removeErr) {- console.warn(`Warning: Error checking/removing existing containers:`, removeErr);+ console.warn(`Warning: Error checking/removing existing containers for ${containerName}:`, removeErr);}// Create and start the containerconsole.log(`Creating container for service ${serviceName}: ${containerName}`);try {const container = await docker.createContainer(containerConfig);- console.log(`Successfully created container: ${containerName}`);-- // Connect to networks- const serviceNetworks = service.networks || [];- if (Array.isArray(serviceNetworks)) {- for (const netName of serviceNetworks) {- const networkConfig = composeData.networks?.[netName];- const isExternal = networkConfig?.external || false;- const fullNetworkName = isExternal- ? networkConfig.name || netName // Use the specified name for external networks- : `${stackId}_${netName}`; // Prefix with stack ID for internal networks-- try {- console.log(`Connecting container ${containerName} to network: ${fullNetworkName}`);- const network = docker.getNetwork(fullNetworkName);- await network.connect({ Container: container.id });- console.log(`Successfully connected to network: ${fullNetworkName}`);- } catch (netConnectErr) {- console.error(`Error connecting to network ${fullNetworkName}:`, netConnectErr);- throw netConnectErr;- }- }- } else if (typeof serviceNetworks === 'object') {- // Handle the case where networks is an object with network names as keys- for (const [netName, netConfig] of Object.entries(serviceNetworks)) {- const networkConfig = composeData.networks?.[netName];- const isExternal = networkConfig?.external || false;- const fullNetworkName = isExternal ? networkConfig.name || netName : `${stackId}_${netName}`;+ console.log(`Successfully created container: ${containerName} (ID: ${container.id})`);+ // Connect to networks if not using a specific network_mode like 'host' or 'none'+ // This part was simplified in your snippet, ensure it's robust+ if (networkingConfig.EndpointsConfig && Object.keys(networkingConfig.EndpointsConfig).length > 0) {+ for (const netName of Object.keys(networkingConfig.EndpointsConfig)) {try {- console.log(`Connecting container ${containerName} to network: ${fullNetworkName}`);- const network = docker.getNetwork(fullNetworkName);+ console.log(`Connecting container ${container.id} to network: ${netName}`);+ const network = docker.getNetwork(netName);await network.connect({Container: container.id,- EndpointConfig: netConfig as any // Cast to any to satisfy type, or define proper EndpointSettings type if available+ EndpointConfig: networkingConfig.EndpointsConfig[netName] || {}});- console.log(`Successfully connected to network: ${fullNetworkName}`);+ console.log(`Successfully connected ${container.id} to network: ${netName}`);} catch (netConnectErr) {- console.error(`Error connecting to network ${fullNetworkName}:`, netConnectErr);- throw netConnectErr;+ console.error(`Error connecting container ${container.id} to network ${netName}:`, netConnectErr);+ // Decide if this should throw or just be a warning}}}- // Start the container- console.log(`Starting container: ${containerName}`);+ console.log(`Starting container: ${containerName} (ID: ${container.id})`);await container.start();console.log(`Successfully started container: ${containerName}`);} catch (createErr) {- console.error(`Error creating/starting container for service ${serviceName}:`, createErr);+ console.error(`Error creating/starting container for service ${serviceName} (${containerName}):`, createErr);throw createErr;}}@@ -1538,7 +1604,7 @@ export async function importExternalStack(stackId: string): Promise<Stack> {# You may need to adjust this manually for correct operation.services:-${yaml.dump({ services }, { indent: 2 }).substring('services:'.length).trimStart()}`;+${yamlDump({ services }, { indent: 2 }).substring('services:'.length).trimStart()}`;// Note: If compose file is generated, we don't have a path to look for an associated .env file.// envContent will remain undefined in this case.}@@ -1614,38 +1680,124 @@ export async function isStackRunning(stackId: string): Promise<boolean> {}/**- * Normalizes healthcheck.test in compose content to ensure it is always an array.+ * Normalizes compose content:+ * 1. Ensures healthcheck.test is an array.+ * 2. Substitutes environment variables throughout the compose object.* @param {string} composeContent - The YAML content of the compose file.- * @returns {string} - The normalized YAML content.+ * @param {function} envGetter - Optional function to get environment variable values.+ * @returns {string} - The normalized and substituted YAML content.*/-function normalizeHealthcheckTest(composeContent: string): string {- let doc: Record<string, unknown> | undefined;+function normalizeHealthcheckTest(composeContent: string, envGetter?: (key: string) => string | undefined): string {+ let doc: any; // Use 'any' for easier manipulation, will be validated by yamlLoadtry {- doc = yaml.load(composeContent) as Record<string, unknown>;+ doc = yamlLoad(composeContent);+ if (!doc || typeof doc !== 'object') {+ console.warn('Could not parse compose YAML for normalization or content is not an object.');+ return composeContent;+ }} catch (e) {- console.warn('Could not parse compose YAML for healthcheck normalization:', e);- return composeContent; // Return original if parsing fails- }- if (!doc?.services) {- return composeContent; // Return original if no services found+ console.warn('Could not parse compose YAML for normalization:', e);+ return composeContent;}let modified = false;- for (const service of Object.values(doc.services as Record<string, unknown>)) {- const svc = service as { healthcheck?: { test?: unknown } }; // Type assertion- if (svc.healthcheck && svc.healthcheck.test) {- if (typeof svc.healthcheck.test === 'string') {- svc.healthcheck.test = svc.healthcheck.test- .trim()- .split(/\s+/)- .filter((s) => s.length > 0);- modified = true;++ // Perform healthcheck normalization+ if (doc.services && typeof doc.services === 'object') {+ for (const serviceName in doc.services) {+ if (Object.prototype.hasOwnProperty.call(doc.services, serviceName)) {+ const service = doc.services[serviceName];+ if (service && service.healthcheck && typeof service.healthcheck === 'object' && service.healthcheck.test && typeof service.healthcheck.test === 'string') {+ service.healthcheck.test = service.healthcheck.test+ .trim()+ .split(/\s+/)+ .filter((s: string) => s.length > 0);+ modified = true;+ }}}}+ // Perform variable substitution on the entire document object if envGetter is provided+ if (envGetter) {+ const originalDocSnapshot = JSON.stringify(doc);+ doc = substituteVariablesInObject(doc, envGetter);+ if (JSON.stringify(doc) !== originalDocSnapshot) {+ modified = true;+ }+ }+if (modified) {- return yaml.dump(doc, { lineWidth: -1 }); // Dump the modified doc+ // Critical check: After substitution, ensure container_name does not contain unresolved variables+ if (doc.services && typeof doc.services === 'object') {+ for (const serviceName in doc.services) {+ if (Object.prototype.hasOwnProperty.call(doc.services, serviceName)) {+ const service = doc.services[serviceName];+ if (service && typeof service.container_name === 'string' && service.container_name.includes('${')) {+ console.error(`CRITICAL: Unresolved variable in container_name for service '${serviceName}': ${service.container_name}. ` + `This will likely cause Docker to fail. Ensure the environment variable is defined.`);+ // Depending on desired behavior, you might throw an error here+ // throw new Error(`Unresolved variable in container_name for service '${serviceName}': ${service.container_name}`);+ }+ }+ }+ }+ return yamlDump(doc, { lineWidth: -1 });+ }+ return composeContent;+}++/**+ * Safely parses YAML content as a string (not a file path)+ * Creates a proper wrapper around yaml-env-defaults to ensure it treats input as content+ * @param content YAML content as a string+ * @param envGetter Optional function to get environment variable values+ * @returns Parsed object or null if parsing fails+ */+function parseYamlContent(content: string, envGetter?: (key: string) => string | undefined): Record<string, any> | null {+ try {+ let parsedYaml = yamlLoad(content); // Using js-yaml's load++ if (!parsedYaml || typeof parsedYaml !== 'object') {+ console.warn('Parsed YAML content is not an object or is null.');+ return null;+ }++ if (envGetter) {+ parsedYaml = substituteVariablesInObject(parsedYaml, envGetter);+ }+ return parsedYaml as Record<string, any>;+ } catch (error) {+ console.error('Error parsing YAML content:', error);+ return null;+ }+}++// Helper function to recursively substitute variables in an object+function substituteVariablesInObject(obj: any, envGetter: (key: string) => string | undefined): any {+ if (Array.isArray(obj)) {+ return obj.map((item) => substituteVariablesInObject(item, envGetter));+ } else if (typeof obj === 'object' && obj !== null) {+ const newObj: Record<string, any> = {};+ for (const key in obj) {+ if (Object.prototype.hasOwnProperty.call(obj, key)) {+ newObj[key] = substituteVariablesInObject(obj[key], envGetter);+ }+ }+ return newObj;+ } else if (typeof obj === 'string') {+ let S = obj;+ // Loop to handle multiple/nested variables, with a safety break+ for (let i = 0; i < 10 && S.includes('${'); i++) {+ S = S.replace(/\$\{([^}]+)\}/g, (match, varName) => {+ const value = envGetter(varName);+ // If value is found, substitute. Otherwise, keep the placeholder.+ return value !== undefined ? value : match;+ });+ }+ if (S.includes('${')) {+ console.warn(`Unresolved variable or recursive substitution limit reached in string: "${obj}". Result: "${S}"`);+ }+ return S;}- return composeContent; // Return original content if no modification was made+ return obj;}diff --git a/src/lib/services/docker/system-service.ts b/src/lib/services/docker/system-service.tsindex 44851c902..389dcd3ba 100644--- a/src/lib/services/docker/system-service.ts+++ b/src/lib/services/docker/system-service.ts@@ -23,10 +23,12 @@ export async function pruneSystem(types: PruneType[]): Promise<PruneServiceResulconsole.log(`Using image prune mode: ${pruneMode}`);+ let message = 'System pruned successfully.';+ const settings = await getSettings();+for (const type of types) {let result: PruneResult | null = null;let error: string | undefined = undefined;- let pruneOptions: { filters: { dangling: string[] } } | undefined;let filterValue: string | undefined;let logMessage: string | undefined;@@ -37,20 +39,28 @@ export async function pruneSystem(types: PruneType[]): Promise<PruneServiceResulcase 'containers':result = await docker.pruneContainers();break;- case 'images':- filterValue = pruneMode === 'all' ? 'false' : 'true';- logMessage = pruneMode === 'all' ? 'Pruning all unused images (docker image prune -a)...' : 'Pruning dangling images (docker image prune)...';- console.log(logMessage);- pruneOptions = {- filters: { dangling: [filterValue] }+ case 'images': {+ const imagePruneOptions = {+ filters: {+ // Ensure 'dangling' is a string 'true' or 'false'+ dangling: [settings.pruneMode === 'dangling' ? 'true' : 'false']+ }};- result = await docker.pruneImages(pruneOptions);+ const imagePruneResult = await docker.pruneImages(imagePruneOptions);+ if (imagePruneResult.ImagesDeleted && imagePruneResult.ImagesDeleted.length > 0) {+ results.push({+ ...(imagePruneResult || { SpaceReclaimed: 0 }),+ type,+ error+ } as PruneServiceResult);+ }break;+ }case 'networks':result = await docker.pruneNetworks();break;case 'volumes':- // result = await docker.pruneVolumes();+ result = await docker.pruneVolumes();break;default:console.warn(`Unsupported prune type requested: ${type}`);@@ -58,7 +68,7 @@ export async function pruneSystem(types: PruneType[]): Promise<PruneServiceResul}console.log(`Pruning ${type} completed.`);- results.push({ ...(result || {}), type, error } as PruneServiceResult);+ results.push({ ...(result || { SpaceReclaimed: 0 }), type, error } as PruneServiceResult);} catch (err: unknown) {const msg = err instanceof Error ? err.message : String(err);console.error(`Error pruning ${type}:`, err);diff --git a/src/lib/services/docker/volume-service.ts b/src/lib/services/docker/volume-service.tsindex 79c516dce..644a1d9e2 100644--- a/src/lib/services/docker/volume-service.ts+++ b/src/lib/services/docker/volume-service.ts@@ -1,35 +1,26 @@import { getDockerClient, dockerHost } from '$lib/services/docker/core';-import type { ServiceVolume } from '$lib/types/docker/volume.type';-import type { VolumeCreateOptions, VolumeInspectInfo } from 'dockerode'; // Import VolumeInspectInfo+// ServiceVolume might still be used by other parts of the application,+// but this service will primarily return Dockerode's VolumeInspectInfo.+// import type { ServiceVolume } from '$lib/types/docker/volume.type';+import type { VolumeCreateOptions, VolumeInspectInfo } from 'dockerode';// Import custom errorsimport { NotFoundError, ConflictError, DockerApiError } from '$lib/types/errors'; // #file:/Users/kylemendell/dev/ofkm/arcane/src/lib/types/errors.ts/**- * This TypeScript function asynchronously lists Docker volumes and maps the response to a custom- * ServiceVolume type.- * @returns The `listVolumes` function returns a Promise that resolves to an array of `ServiceVolume`- * objects. Each `ServiceVolume` object contains properties such as `name`, `driver`, `scope`,- * `mountpoint`, and `labels` extracted from the volumes obtained from the Docker client. If an error- * occurs during the process, an error message is logged and a new Error is thrown with a failure+ * Asynchronously lists Docker volumes.+ * @returns A Promise that resolves to an array of `VolumeInspectInfo` objects from Docker.+ * @throws {Error} If an error occurs during the process.*/-export async function listVolumes(): Promise<ServiceVolume[]> {+export async function listVolumes(): Promise<VolumeInspectInfo[]> {try {const docker = await getDockerClient();const volumeResponse = await docker.listVolumes();- const volumes = volumeResponse.Volumes || [];-- return volumes.map(- (vol): ServiceVolume => ({- name: vol.Name,- driver: vol.Driver,- scope: vol.Scope,- mountpoint: vol.Mountpoint,- labels: vol.Labels- })- );+ // The Volumes array in the response directly contains objects conforming to VolumeInspectInfo+ return volumeResponse.Volumes || [];} catch (error: unknown) {console.error('Docker Service: Error listing volumes:', error);- throw new Error(`Failed to list Docker volumes using host "${dockerHost}".`);+ const errorMessage = error instanceof Error ? error.message : String(error);+ throw new Error(`Failed to list Docker volumes using host "${dockerHost}". ${errorMessage}`);}}@@ -49,6 +40,7 @@ export async function isVolumeInUse(volumeName: string): Promise<boolean> {const containers = await docker.listContainers({ all: true });// Inspect each container to check its mountsfor (const containerInfo of containers) {+ // Use getContainer and inspect to get detailed mount informationconst details = await docker.getContainer(containerInfo.Id).inspect();if (details.Mounts?.some((m) => m.Type === 'volume' && m.Name === volumeName)) {return true;@@ -57,8 +49,11 @@ export async function isVolumeInUse(volumeName: string): Promise<boolean> {return false;} catch (error: unknown) {console.error(`Error checking if volume ${volumeName} is in use:`, error);- // Default to assuming it's in use for safety- return true;+ const errorMessage = error instanceof Error ? error.message : String(error);+ // Rethrow or handle more gracefully depending on requirements.+ // Defaulting to true might be too restrictive if the check itself fails.+ // Consider throwing a new error or returning a specific error state.+ throw new Error(`Failed to check if volume ${volumeName} is in use: ${errorMessage}`);}}@@ -73,7 +68,7 @@ export async function getVolume(volumeName: string): Promise<VolumeInspectInfo>try {const docker = await getDockerClient();const volume = docker.getVolume(volumeName);- const inspectInfo = await volume.inspect();+ const inspectInfo = await volume.inspect(); // This directly returns VolumeInspectInfoconsole.log(`Docker Service: Inspected volume "${volumeName}" successfully.`);return inspectInfo;} catch (error: unknown) {@@ -81,59 +76,41 @@ export async function getVolume(volumeName: string): Promise<VolumeInspectInfo>if ((error as { statusCode?: number }).statusCode === 404) {throw new NotFoundError(`Volume "${volumeName}" not found.`);}- throw new DockerApiError(`Failed to inspect volume "${volumeName}": ${(error as { message?: string }).message || 'Unknown Docker error'}`, (error as { statusCode?: number }).statusCode);+ const errorMessage = (error as { message?: string; reason?: string }).message || (error as { reason?: string }).reason || 'Unknown Docker error';+ throw new DockerApiError(`Failed to inspect volume "${volumeName}": ${errorMessage}`, (error as { statusCode?: number }).statusCode);}}/**- * The function `createVolume` creates a Docker volume with specified options and returns basic- * information about the created volume.- * @param {VolumeCreateOptions} options - The `options` parameter in the `createVolume` function is of- * type `VolumeCreateOptions`. This object likely contains the necessary information to create a volume- * in Docker, such as the volume name, driver, labels, and scope. The function uses this information to- * create a volume using the Docker client- * @returns The `createVolume` function returns an object with the following properties:- * - Name: The name of the created volume- * - Driver: The driver used for the volume- * - Mountpoint: The mountpoint of the volume- * - Labels: Any labels associated with the volume (defaults to an empty object if none provided)- * - Scope: The scope of the volume (defaults to 'local' if not+ * Creates a Docker volume with specified options.+ * @param {VolumeCreateOptions} options - The `VolumeCreateOptions` object containing configuration for the new volume.+ * @returns {Promise<VolumeInspectInfo>} A promise that resolves with the `VolumeInspectInfo` of the created volume.+ * @throws {ConflictError} If a volume with the same name already exists.+ * @throws {DockerApiError} For other Docker API errors or issues during creation.*/-export async function createVolume(options: VolumeCreateOptions): Promise<ServiceVolume> {+export async function createVolume(options: VolumeCreateOptions): Promise<VolumeInspectInfo> {try {const docker = await getDockerClient();- // createVolume returns the volume data directly - no need to inspect- const volume = await docker.createVolume(options);+ // docker.createVolume(options) returns a Promise<any>, which resolves to the API response body.+ // This body is effectively the VolumeInspectInfo for the created volume.+ const volumeInfo = (await docker.createVolume(options)) as VolumeInspectInfo;console.log(`Docker Service: Volume "${options.Name}" created successfully.`);-- // Return the creation response which contains basic info- return {- name: volume.Name,- driver: volume.Driver,- mountpoint: volume.Mountpoint,- labels: volume.Labels || {},- scope: volume.Scope || 'local'- };+ return volumeInfo;} catch (error: unknown) {console.error(`Docker Service: Error creating volume "${options.Name}":`, error);- // Check for specific Docker errors, like volume already exists (often 409)if ((error as { statusCode?: number }).statusCode === 409) {- throw new Error(`Volume "${options.Name}" already exists.`);+ throw new ConflictError(`Volume "${options.Name}" already exists.`);}- throw new Error(- `Failed to create volume "${options.Name}" using host "${dockerHost}". ` + ((error as { message?: string; reason?: string }).message || (error as { reason?: string }).reason || '') // Include reason if available- );+ const errorMessage = (error as { message?: string; reason?: string }).message || (error as { reason?: string }).reason || 'Unknown Docker error';+ throw new DockerApiError(`Failed to create volume "${options.Name}" using host "${dockerHost}". ${errorMessage}`, (error as { statusCode?: number }).statusCode);}}/**- * The function `removeVolume` asynchronously removes a Docker volume by name, with an optional force- * flag to handle volume in use errors.- * @param {string} name - The `name` parameter is a string that represents the name of the volume you- * want to remove.- * @param {boolean} [force=false] - The `force` parameter determines whether to forcefully remove the volume even if it is in use by a- * container.+ * Removes a Docker volume by name.+ * @param {string} name - The name of the volume to remove.+ * @param {boolean} [force=false] - If true, forces removal even if the volume is in use.* @throws {NotFoundError} If the volume does not exist.* @throws {ConflictError} If the volume is in use and force is false.* @throws {DockerApiError} For other Docker API errors.@@ -150,9 +127,9 @@ export async function removeVolume(name: string, force = false): Promise<void> {throw new NotFoundError(`Volume "${name}" not found.`);}if ((error as { statusCode?: number }).statusCode === 409) {- // This usually means the volume is in use- throw new ConflictError(`Volume "${name}" is in use by a container. Stop the container or use the force option to remove.`);+ throw new ConflictError(`Volume "${name}" is in use. Use the force option to remove if necessary.`);}- throw new DockerApiError(`Failed to remove volume "${name}": ${(error as { message?: string; reason?: string }).message || (error as { reason?: string }).reason || 'Unknown Docker error'}`, (error as { statusCode?: number }).statusCode);+ const errorMessage = (error as { message?: string; reason?: string }).message || (error as { reason?: string }).reason || 'Unknown Docker error';+ throw new DockerApiError(`Failed to remove volume "${name}": ${errorMessage}`, (error as { statusCode?: number }).statusCode);}}diff --git a/src/lib/types/docker/container.type.ts b/src/lib/types/docker/container.type.tsdeleted file mode 100644index 12d6bb64e..000000000--- a/src/lib/types/docker/container.type.ts+++ /dev/null@@ -1,109 +0,0 @@-import type Docker from 'dockerode';-import type { ContainerCreateOptions, HealthConfig } from 'dockerode';--export type ServiceContainer = {- id: string;- names: string[];- name: string;- image: string;- imageId: string;- command: string;- created: number;- state: string;- status: string;- ports: Docker.Port[];-};--// Container state-export interface ContainerState {- Status: string;- Running: boolean;- Paused: boolean;- Restarting: boolean;- OOMKilled: boolean;- Dead: boolean;- Pid: number;- ExitCode: number;- Error: string;- StartedAt: string;- FinishedAt: string;-}--// Container details-export interface ContainerDetails {- Id: string;- Names: string[];- Image: string;- ImageID: string;- Command: string;- Created: number;- Ports: ContainerPort[];- Labels: { [label: string]: string };- State: string;- Status: string;- HostConfig: {- NetworkMode: string;- };- NetworkSettings: {- Networks: {- [networkName: string]: {- IPAddress: string;- Gateway: string;- MacAddress: string;- };- };- };- Mounts: Array<{- Type: string;- Name?: string;- Source: string;- Destination: string;- Mode: string;- RW: boolean;- Propagation: string;- }>;-}--// Container types-export interface ContainerCreate extends ContainerCreateOptions {- name?: string; // Container name-}--// Container configuration for creating containers-export interface ContainerConfig {- name: string;- image: string;- ports?: Array<{- hostPort: string;- containerPort: string;- }>;- volumes?: Array<{- source: string;- target: string;- readOnly?: boolean;- }>;- envVars?: Array<{- key: string;- value: string;- }>;- network?: string;- restart?: 'no' | 'always' | 'on-failure' | 'unless-stopped';- networkConfig?: {- ipv4Address?: string;- ipv6Address?: string;- };- healthcheck?: HealthConfig;- labels?: { [key: string]: string };- command?: string[];- user?: string;- memoryLimit?: number;- cpuLimit?: number;-}--// Container port mapping-export interface ContainerPort {- IP?: string;- PrivatePort: number;- PublicPort?: number;- Type: string;-}diff --git a/src/lib/types/docker/image.type.ts b/src/lib/types/docker/image.type.tsindex afc10d902..e7b5d91ad 100644--- a/src/lib/types/docker/image.type.ts+++ b/src/lib/types/docker/image.type.ts@@ -1,15 +1,17 @@-export type ServiceImage = {- id: string;- repoTags: string[] | undefined;- repoDigests: string[] | undefined;- created: number;- size: number;- virtualSize: number;- labels: { [label: string]: string } | undefined;- repo: string;- tag: string;+import type Docker from 'dockerode';++/**+ * Represents a Docker image, extending Dockerode's ImageInfo with parsed repo and tag.+ * Properties like Id, RepoTags, Created, Size, etc., are inherited from Docker.ImageInfo.+ */+export type ServiceImage = Docker.ImageInfo & {+ repo: string; // Parsed repository name+ tag: string; // Parsed tag};+/**+ * Represents the maturity status of a Docker image.+ */export interface ImageMaturity {version: string;date: string;@@ -17,6 +19,9 @@ export interface ImageMaturity {updatesAvailable: boolean;}+/**+ * Extends ServiceImage with application-specific information like usage status and maturity.+ */export type EnhancedImageInfo = ServiceImage & {inUse: boolean;maturity?: ImageMaturity;diff --git a/src/lib/types/docker/index.ts b/src/lib/types/docker/index.tsindex cd6d569e6..dd9870987 100644--- a/src/lib/types/docker/index.ts+++ b/src/lib/types/docker/index.ts@@ -1,6 +1,2 @@-export * from './stack.type';-export * from './network.type';-export * from './container.type';export * from './image.type';-export * from './volume.type';export * from './connection.type';diff --git a/src/lib/types/docker/network.type.ts b/src/lib/types/docker/network.type.tsdeleted file mode 100644index e525c9e56..000000000--- a/src/lib/types/docker/network.type.ts+++ /dev/null@@ -1,9 +0,0 @@-export type ServiceNetwork = {- id: string;- name: string;- driver: string;- scope: string;- subnet: string | null;- gateway: string | null;- created: string;-};diff --git a/src/lib/types/docker/volume.type.ts b/src/lib/types/docker/volume.type.tsdeleted file mode 100644index 4d2e5a1ad..000000000--- a/src/lib/types/docker/volume.type.ts+++ /dev/null@@ -1,7 +0,0 @@-export type ServiceVolume = {- name: string;- driver: string;- scope: string;- mountpoint: string;- labels: { [label: string]: string } | null;-};diff --git a/src/routes/+page.server.ts b/src/routes/+page.server.tsindex eafe1ee30..560176716 100644--- a/src/routes/+page.server.ts+++ b/src/routes/+page.server.ts@@ -4,33 +4,34 @@ import { getDockerInfo } from '$lib/services/docker/core';import { isImageInUse, listImages, checkImageMaturity } from '$lib/services/docker/image-service';import { getSettings } from '$lib/services/settings-service';import { maturityCache } from '$lib/services/docker/maturity-cache-service';-import type { EnhancedImageInfo, ServiceContainer, ServiceImage } from '$lib/types/docker';+import type { EnhancedImageInfo, ServiceImage } from '$lib/types/docker';+import type { ContainerInfo } from 'dockerode';type DockerInfoType = Awaited<ReturnType<typeof getDockerInfo>>;type SettingsType = NonNullable<Awaited<ReturnType<typeof getSettings>>>;type DashboardData = {dockerInfo: DockerInfoType | null;- containers: ServiceContainer[];- images: ServiceImage[];+ containers: ContainerInfo[];+ images: EnhancedImageInfo[];settings: Pick<SettingsType, 'pruneMode'> | null;error?: string;};export const load: PageServerLoad = async (): Promise<DashboardData> => {try {- const [dockerInfo, containers, images, settings] = await Promise.all([+ const [dockerInfo, containersData, imagesData, settings] = await Promise.all([getDockerInfo().catch((e) => {console.error('Dashboard: Failed to get Docker info:', e.message);return null;}),listContainers(true).catch((e) => {console.error('Dashboard: Failed to list containers:', e.message);- return [];+ return [] as ContainerInfo[];}),listImages().catch((e) => {console.error('Dashboard: Failed to list images:', e.message);- return [];+ return [] as ServiceImage[];}),getSettings().catch((e) => {console.error('Dashboard: Failed to get settings:', e.message);@@ -39,20 +40,20 @@ export const load: PageServerLoad = async (): Promise<DashboardData> => {]);const enhancedImages = await Promise.all(- images.map(async (image): Promise<EnhancedImageInfo> => {- const inUse = await isImageInUse(image.id);+ imagesData.map(async (image): Promise<EnhancedImageInfo> => {+ const inUse = await isImageInUse(image.Id);- // Check maturity cache first before returning- const cachedMaturity = maturityCache.get(image.id);+ const cachedMaturity = maturityCache.get(image.Id);let maturity = cachedMaturity;if (maturity === undefined) {try {if (image.repo !== '<none>' && image.tag !== '<none>') {- maturity = await checkImageMaturity(image.id);+ maturity = await checkImageMaturity(image.Id);}} catch (maturityError) {- console.error(`Dashboard: Failed to check maturity for image ${image.id}:`, maturityError);+ console.error(`Dashboard: Failed to check maturity for image ${image.Id}:`, maturityError);+ maturity = undefined;}}@@ -67,8 +68,8 @@ export const load: PageServerLoad = async (): Promise<DashboardData> => {if (!dockerInfo) {return {dockerInfo: null,- containers: [],- images: [] as EnhancedImageInfo[],+ containers: [] as ContainerInfo[],+ images: enhancedImages,settings: settings ? { pruneMode: settings.pruneMode } : null,error: 'Failed to connect to Docker Engine. Please check settings and ensure Docker is running.'};@@ -76,7 +77,7 @@ export const load: PageServerLoad = async (): Promise<DashboardData> => {return {dockerInfo,- containers,+ containers: containersData,images: enhancedImages,settings: settings ? { pruneMode: settings.pruneMode } : null};@@ -84,8 +85,8 @@ export const load: PageServerLoad = async (): Promise<DashboardData> => {console.error('Dashboard: Unexpected error loading data:', err);return {dockerInfo: null,- containers: [],- images: [],+ containers: [] as ContainerInfo[],+ images: [], // Return empty EnhancedImageInfo array on errorsettings: null,error: err.message || 'An unexpected error occurred while loading dashboard data.'};diff --git a/src/routes/+page.svelte b/src/routes/+page.svelteindex 022630783..563c531c2 100644--- a/src/routes/+page.svelte+++ b/src/routes/+page.svelte@@ -6,7 +6,7 @@import { AlertCircle, Box, HardDrive, Cpu, MemoryStick, ArrowRight, PlayCircle, StopCircle, Trash2, Settings, RefreshCw, Loader2 } from '@lucide/svelte';import * as Alert from '$lib/components/ui/alert/index.js';import { Progress } from '$lib/components/ui/progress/index.js';- import { capitalizeFirstLetter, truncateString } from '$lib/utils/string.utils';+ import { capitalizeFirstLetter, truncateString, shortId } from '$lib/utils/string.utils';import { formatBytes } from '$lib/utils/bytes.util';import StatusBadge from '$lib/components/badges/status-badge.svelte';import { invalidateAll } from '$app/navigation';@@ -19,14 +19,15 @@import ContainerAPIService from '$lib/services/api/container-api-service';import SystemAPIService from '$lib/services/api/system-api-service';import type { EnhancedImageInfo } from '$lib/types/docker';+ import type { ContainerInfo } from 'dockerode';import { openConfirmDialog } from '$lib/components/confirm-dialog';import MaturityItem from '$lib/components/maturity-item.svelte';import { onMount } from 'svelte';import { maturityStore } from '$lib/stores/maturity-store';- import { maturityCache } from '$lib/services/docker/maturity-cache-service';import ImageAPIService from '$lib/services/api/image-api-service';+ import type { PruneType } from '$lib/types/actions.type';- let { data }: { data: PageData } = $props();+ let { data }: { data: PageData & { containers: ContainerInfo[] } } = $props();const containerApi = new ContainerAPIService();const systemApi = new SystemAPIService();@@ -48,9 +49,16 @@pruning: false});- const runningContainers = $derived(dashboardStates.containers?.filter((c) => c.state === 'running').length ?? 0);- const stoppedContainers = $derived(dashboardStates.containers?.filter((c) => c.state === 'exited').length ?? 0);- const totalImageSize = $derived(dashboardStates.images?.reduce((sum, image) => sum + (image.size || 0), 0) ?? 0);+ const runningContainers = $derived(dashboardStates.containers?.filter((c: ContainerInfo) => c.State === 'running').length ?? 0);+ const stoppedContainers = $derived(dashboardStates.containers?.filter((c: ContainerInfo) => c.State === 'exited').length ?? 0);+ const totalImageSize = $derived(dashboardStates.images?.reduce((sum, image) => sum + (image.Size || 0), 0) ?? 0);++ function getContainerDisplayName(container: ContainerInfo): string {+ if (container.Names && container.Names.length > 0) {+ return container.Names[0].startsWith('/') ? container.Names[0].substring(1) : container.Names[0];+ }+ return shortId(container.Id);+ }$effect(() => {dashboardStates.dockerInfo = data.dockerInfo;@@ -61,7 +69,6 @@});onMount(async () => {- // Asynchronously load maturity data for the top images after dashboard loadsawait loadTopImagesMaturity();});@@ -88,7 +95,6 @@onSuccess: async () => {toast.success('All Containers Started Successfully.');await invalidateAll();- isLoading.starting = false;}});}@@ -110,7 +116,6 @@onSuccess: async () => {toast.success('All Containers Stopped Successfully.');await invalidateAll();- isLoading.stopping = false;}});}@@ -118,54 +123,47 @@});}- async function confirmPrune(selectedTypes: string[]) {+ async function confirmPrune(selectedTypes: PruneType[]) {if (isLoading.pruning || selectedTypes.length === 0) return;isLoading.pruning = true;handleApiResultWithCallbacks({- result: await tryCatch(systemApi.prune(['containers', 'images'])),- message: `Failed to Prune ${selectedTypes}`,+ result: await tryCatch(systemApi.prune(selectedTypes)),+ message: `Failed to Prune ${selectedTypes.join(', ')}`,setLoadingState: (value) => (isLoading.pruning = value),onSuccess: async () => {dashboardStates.isPruneDialogOpen = false;const formattedTypes = selectedTypes.map((type) => capitalizeFirstLetter(type)).join(', ');toast.success(`${formattedTypes} ${selectedTypes.length > 1 ? 'were' : 'was'} pruned successfully.`);await invalidateAll();- isLoading.pruning = false;}});}async function loadTopImagesMaturity() {- // Only process if there are imagesif (!dashboardStates.images || dashboardStates.images.length === 0) return;- // Get the IDs of the largest 5 images (which are displayed in the dashboard)const topImageIds = [...dashboardStates.images]- .sort((a, b) => (b.size || 0) - (a.size || 0))+ .sort((a, b) => (b.Size || 0) - (a.Size || 0)).slice(0, 5).filter((img) => img.repo !== '<none>' && img.tag !== '<none>')- .map((img) => img.id);+ .map((img) => img.Id);if (topImageIds.length === 0) return;- // Load maturity data in the backgroundtry {- // Process in small batches to keep UI responsiveconst BATCH_SIZE = 2;for (let i = 0; i < topImageIds.length; i += BATCH_SIZE) {const batch = topImageIds.slice(i, i + BATCH_SIZE);await imageApi.checkMaturityBatch(batch);- // Update the dashboardStates.images with the latest maturity infodashboardStates.images = dashboardStates.images.map((image) => {- const storedMaturity = $maturityStore.maturityData[image.id];+ const storedMaturity = $maturityStore.maturityData[image.Id];return {...image,- maturity: storedMaturity || image.maturity+ maturity: storedMaturity !== undefined ? storedMaturity : image.maturity};});- // Short delay between batchesif (i + BATCH_SIZE < topImageIds.length) {await new Promise((resolve) => setTimeout(resolve, 50));}@@ -226,7 +224,7 @@</div></div>{#if dashboardStates.containers?.length}- <Progress value={(runningContainers / dashboardStates.containers.length) * 100} class="mt-4 h-2" />+ <Progress value={(runningContainers / (dashboardStates.containers.length || 1)) * 100} class="mt-4 h-2" />{/if}</Card.Content></Card.Root>@@ -275,7 +273,7 @@<div><p class="text-sm font-medium text-muted-foreground">Memory</p><p class="text-2xl font-bold mt-1">- {formatBytes(dashboardStates.dockerInfo?.MemTotal, 0)}+ {dashboardStates.dockerInfo?.MemTotal ? formatBytes(dashboardStates.dockerInfo.MemTotal, 0) : 'N/A'}</p></div><div class="bg-amber-500/10 p-2 rounded-full">@@ -296,7 +294,6 @@<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">- <!-- Start All 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 || 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">{#if isLoading.starting}@@ -310,7 +307,6 @@<p class="text-xs text-muted-foreground">Start all stopped containers</p></button>- <!-- Stop All 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">{#if isLoading.stopping}@@ -324,7 +320,6 @@<p class="text-xs text-muted-foreground">Stop all running containers</p></button>- <!-- Prune System Button --><buttonclass="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"disabled={!dashboardStates.dockerInfo || isLoading.starting || isLoading.stopping || isLoading.pruning}@@ -364,19 +359,19 @@<div class="flex flex-col h-full"><div class="flex-1"><UniversalTable- data={dashboardStates.containers.slice(0, 5)}+ data={dashboardStates.containers.slice(0, 5).map((c) => ({ ...c, displayName: getContainerDisplayName(c) }))}columns={[- { accessorKey: 'name', header: 'Name' },- { accessorKey: 'image', header: 'Image' },- { accessorKey: 'state', header: 'State' },- { accessorKey: 'status', header: 'Status' }+ { accessorKey: 'displayName', header: 'Name' },+ { accessorKey: 'Image', header: 'Image' },+ { accessorKey: 'State', header: 'State' },+ { accessorKey: 'Status', header: 'Status' }]}features={{filtering: false,selection: false}}sort={{- defaultSort: { id: 'status', desc: false }+ defaultSort: { id: 'Status', desc: false }}}pagination={{pageSize: 5,@@ -386,12 +381,12 @@isDashboardTable: true}}>- {#snippet rows({ item })}- {@const stateVariant = statusVariantMap[item.state.toLowerCase()]}- <Table.Cell><a class="font-medium hover:underline" href="/containers/{item.id}/">{item.name}</a></Table.Cell>- <Table.Cell title={item.image}>{truncateString(item.image, 40)}</Table.Cell>- <Table.Cell><StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.state)} /></Table.Cell>- <Table.Cell>{item.status}</Table.Cell>+ {#snippet rows({ item }: { item: ContainerInfo & { displayName: string } })}+ {@const stateVariant = statusVariantMap[item.State.toLowerCase()]}+ <Table.Cell><a class="font-medium hover:underline" href="/containers/{item.Id}/">{item.displayName}</a></Table.Cell>+ <Table.Cell title={item.Image}>{truncateString(item.Image, 40)}</Table.Cell>+ <Table.Cell><StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.State)} /></Table.Cell>+ <Table.Cell>{item.Status}</Table.Cell>{/snippet}</UniversalTable></div>@@ -434,7 +429,7 @@{ accessorKey: 'repo', header: 'Name' },{ accessorKey: 'inUse', header: ' ', enableSorting: false },{ accessorKey: 'tag', header: 'Tag' },- { accessorKey: 'size', header: 'Size' }+ { accessorKey: 'Size', header: 'Size' }]}features={{filtering: false,@@ -448,15 +443,15 @@isDashboardTable: true}}sort={{- defaultSort: { id: 'size', desc: true }+ defaultSort: { id: 'Size', desc: true }}}>- {#snippet rows({ item })}+ {#snippet rows({ item }: { item: EnhancedImageInfo })}<Table.Cell><div class="flex items-center gap-2"><div class="flex items-center flex-1"><MaturityItem maturity={item.maturity} isLoadingInBackground={!item.maturity} />- <a class="font-medium hover:underline shrink truncate" href="/images/{item.id}/">+ <a class="font-medium hover:underline shrink truncate" href="/images/{item.Id}/">{item.repo}</a></div>@@ -470,7 +465,7 @@{/if}</Table.Cell><Table.Cell>{item.tag}</Table.Cell>- <Table.Cell>{formatBytes(item.size)}</Table.Cell>+ <Table.Cell>{formatBytes(item.Size)}</Table.Cell>{/snippet}</UniversalTable></div>diff --git a/src/routes/api/containers/+server.ts b/src/routes/api/containers/+server.tsindex 5f4545b3f..9032777f1 100644--- a/src/routes/api/containers/+server.ts+++ b/src/routes/api/containers/+server.ts@@ -1,15 +1,15 @@import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { createContainer } from '$lib/services/docker/container-service';-import type { ContainerConfig } from '$lib/types/docker';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { extractDockerErrorMessage } from '$lib/utils/errors.util';import { tryCatch } from '$lib/utils/try-catch';+import type { ContainerInspectInfo } from 'dockerode';export const POST: RequestHandler = async ({ request }) => {- const config = (await request.json()) as ContainerConfig;+ const config = (await request.json()) as ContainerInspectInfo;- if (!config.name || !config.image) {+ if (!config.Name || !config.Image) {const response: ApiErrorResponse = {success: false,error: 'Container name and image are required',diff --git a/src/routes/api/containers/[containerId]/pull/+server.ts b/src/routes/api/containers/[containerId]/pull/+server.tsindex f22a137ca..c9aba8ea2 100644--- a/src/routes/api/containers/[containerId]/pull/+server.ts+++ b/src/routes/api/containers/[containerId]/pull/+server.ts@@ -33,7 +33,7 @@ export const POST: RequestHandler = async ({ params }) => {return json(response, { status: 404 });}- const imageName = getResult.data.image;+ const imageName = getResult.data.Image;// Try to pull the imageconst pullResult = await tryCatch(pullImage(imageName));diff --git a/src/routes/api/containers/start-all/+server.ts b/src/routes/api/containers/start-all/+server.tsindex c8acf0810..72ec24393 100644--- a/src/routes/api/containers/start-all/+server.ts+++ b/src/routes/api/containers/start-all/+server.ts@@ -4,16 +4,17 @@ import type { RequestHandler } from './$types';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { extractDockerErrorMessage } from '$lib/utils/errors.util';import { tryCatch } from '$lib/utils/try-catch';+import type { ContainerInfo } from 'dockerode';export const POST: RequestHandler = async () => {const result = await tryCatch((async () => {- const containers = await listContainers(true);- const stopped = containers.filter((c) => c.state === 'exited');+ const containers: ContainerInfo[] = await listContainers(true);+ const stopped = containers.filter((c) => c.State === 'exited');if (stopped.length === 0) {return { count: 0, message: 'No stopped containers to start.' };}- await Promise.all(stopped.map((c) => startContainer(c.id)));+ await Promise.all(stopped.map((c) => startContainer(c.Id)));return { count: stopped.length, message: `Successfully started ${stopped.length} container(s).` };})());diff --git a/src/routes/api/containers/stop-all/+server.ts b/src/routes/api/containers/stop-all/+server.tsindex 43ca5df1c..cd3efd594 100644--- a/src/routes/api/containers/stop-all/+server.ts+++ b/src/routes/api/containers/stop-all/+server.ts@@ -9,11 +9,11 @@ export const POST: RequestHandler = async () => {const result = await tryCatch((async () => {const containers = await listContainers(true);- const running = containers.filter((c) => c.state === 'running');+ const running = containers.filter((c) => c.State === 'running');if (running.length === 0) {return { count: 0, message: 'No running containers to stop.' };}- await Promise.all(running.map((c) => stopContainer(c.id)));+ await Promise.all(running.map((c) => stopContainer(c.Id)));console.log(`API: Stopped ${running.length} containers.`);return { count: running.length, message: `Successfully stopped ${running.length} container(s).` };})()diff --git a/src/routes/api/volumes/+server.ts b/src/routes/api/volumes/+server.tsindex f418995d0..b5376f9fc 100644--- a/src/routes/api/volumes/+server.ts+++ b/src/routes/api/volumes/+server.ts@@ -1,7 +1,7 @@import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';import { createVolume } from '$lib/services/docker/volume-service';-import type { VolumeCreateOptions } from 'dockerode';+import type { VolumeCreateOptions, VolumeInspectInfo } from 'dockerode';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { tryCatch } from '$lib/utils/try-catch';@@ -20,32 +20,32 @@ export const POST: RequestHandler = async ({ request }) => {if (!body.Name) {const response: ApiErrorResponse = {success: false,- error: 'Volume name is required.',+ error: 'Volume name (Name) is required.',code: ApiErrorCode.BAD_REQUEST};return json(response, { status: 400 });}const volumeResult = await tryCatch(createVolume(body));+if (volumeResult.error) {console.error('API Error creating volume:', volumeResult.error);+ const typedError = volumeResult.error as any;const response: ApiErrorResponse = {success: false,- error: volumeResult.error.message || 'Failed to create volume',- code: ApiErrorCode.INTERNAL_SERVER_ERROR,- details: volumeResult.error+ error: typedError.message || 'Failed to create volume',+ code: typedError.code || ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: typedError.details || typedError};- return json(response, { status: 500 });+ const status = typeof typedError.statusCode === 'number' ? typedError.statusCode : 500;+ return json(response, { status });}- const volumeInfo = volumeResult.data;+ const volumeInfo: VolumeInspectInfo = volumeResult.data;return json({success: true,- volume: {- ...volumeInfo,- Name: volumeInfo.name- }+ volume: volumeInfo},{ status: 201 });diff --git a/src/routes/containers/+page.svelte b/src/routes/containers/+page.svelteindex d94fb3f73..429ac0dec 100644--- a/src/routes/containers/+page.svelte+++ b/src/routes/containers/+page.svelte@@ -9,7 +9,7 @@import CreateContainerDialog from './create-container-dialog.svelte';import { goto, invalidateAll } from '$app/navigation';import { toast } from 'svelte-sonner';- import type { ServiceContainer } from '$lib/types/docker/container.type';+ import type { ContainerInfo } from 'dockerode';import ContainerAPIService from '$lib/services/api/container-api-service';import { tryCatch } from '$lib/utils/try-catch';import StatusBadge from '$lib/components/badges/status-badge.svelte';@@ -17,10 +17,11 @@import { capitalizeFirstLetter } from '$lib/utils/string.utils';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { shortId } from '$lib/utils/string.utils';+ import type { PageData } from './$types';const containerApi = new ContainerAPIService();- let { data } = $props();+ let { data }: { data: PageData & { containers: ContainerInfo[] } } = $props();let containers = $state(data.containers);let isRefreshing = $state(false);let selectedIds = $state([]);@@ -32,10 +33,17 @@remove: false});const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));- const runningContainers = $derived(containers?.filter((c: ServiceContainer) => c.state === 'running').length || 0);- const stoppedContainers = $derived(containers?.filter((c: ServiceContainer) => c.state === 'exited').length || 0);+ const runningContainers = $derived(containers?.filter((c: ContainerInfo) => c.State === 'running').length || 0);+ const stoppedContainers = $derived(containers?.filter((c: ContainerInfo) => c.State === 'exited').length || 0);const totalContainers = $derived(containers?.length || 0);+ function getContainerDisplayName(container: ContainerInfo): string {+ if (container.Names && container.Names.length > 0) {+ return container.Names[0].startsWith('/') ? container.Names[0].substring(1) : container.Names[0];+ }+ return shortId(container.Id);+ }+$effect(() => {containers = data.containers;if (isRefreshing) {@@ -47,7 +55,6 @@isRefreshing = true;try {await invalidateAll();- containers = data.containers;} finally {setTimeout(() => {isRefreshing = false;@@ -200,31 +207,34 @@</Card.Header><Card.Content><UniversalTable- data={containers}+ data={containers.map((c) => ({ ...c, displayName: getContainerDisplayName(c) }))}columns={[- { accessorKey: 'name', header: 'Name' },- { accessorKey: 'id', header: 'ID' },- { accessorKey: 'image', header: 'Image' },- { accessorKey: 'state', header: 'State' },- { accessorKey: 'status', header: 'Status' },+ { accessorKey: 'displayName', header: 'Name' },+ { accessorKey: 'Id', header: 'ID' },+ { accessorKey: 'Image', header: 'Image' },+ { accessorKey: 'State', header: 'State' },+ { accessorKey: 'Status', header: 'Status' },{ accessorKey: 'actions', header: ' ', enableSorting: false }]}features={{selection: false}}+ sort={{+ defaultSort: { id: 'displayName', desc: false }+ }}display={{filterPlaceholder: 'Search containers...',noResultsMessage: 'No containers found'}}bind:selectedIds>- {#snippet rows({ item })}- {@const stateVariant = statusVariantMap[item.state.toLowerCase()]}- <Table.Cell><a class="font-medium hover:underline" href="/containers/{item.id}/">{item.name}</a></Table.Cell>- <Table.Cell>{shortId(item.id)}</Table.Cell>- <Table.Cell>{item.image}</Table.Cell>- <Table.Cell><StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.state)} /></Table.Cell>- <Table.Cell>{item.status}</Table.Cell>+ {#snippet rows({ item }: { item: ContainerInfo & { displayName: string } })}+ {@const stateVariant = statusVariantMap[item.State.toLowerCase()]}+ <Table.Cell><a class="font-medium hover:underline" href="/containers/{item.Id}/">{item.displayName}</a></Table.Cell>+ <Table.Cell>{shortId(item.Id)}</Table.Cell>+ <Table.Cell>{item.Image}</Table.Cell>+ <Table.Cell><StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.State)} /></Table.Cell>+ <Table.Cell>{item.Status}</Table.Cell><Table.Cell><DropdownMenu.Root><DropdownMenu.Trigger>@@ -237,13 +247,13 @@</DropdownMenu.Trigger><DropdownMenu.Content align="end"><DropdownMenu.Group>- <DropdownMenu.Item onclick={() => goto(`/containers/${item.id}`)} disabled={isAnyLoading}>+ <DropdownMenu.Item onclick={() => goto(`/containers/${item.Id}`)} disabled={isAnyLoading}><ScanSearch class="size-4" />Inspect</DropdownMenu.Item>- {#if item.state !== 'running'}- <DropdownMenu.Item onclick={() => performContainerAction('start', item.id)} disabled={isLoading.start || isAnyLoading}>+ {#if item.State !== 'running'}+ <DropdownMenu.Item onclick={() => performContainerAction('start', item.Id)} disabled={isLoading.start || isAnyLoading}>{#if isLoading.start}<Loader2 class="animate-spin size-4" />{:else}@@ -252,7 +262,7 @@Start</DropdownMenu.Item>{:else}- <DropdownMenu.Item onclick={() => performContainerAction('restart', item.id)} disabled={isLoading.restart || isAnyLoading}>+ <DropdownMenu.Item onclick={() => performContainerAction('restart', item.Id)} disabled={isLoading.restart || isAnyLoading}>{#if isLoading.restart}<Loader2 class="animate-spin size-4" />{:else}@@ -261,7 +271,7 @@Restart</DropdownMenu.Item>- <DropdownMenu.Item onclick={() => performContainerAction('stop', item.id)} disabled={isLoading.stop || isAnyLoading}>+ <DropdownMenu.Item onclick={() => performContainerAction('stop', item.Id)} disabled={isLoading.stop || isAnyLoading}>{#if isLoading.stop}<Loader2 class="animate-spin size-4" />{:else}@@ -273,7 +283,7 @@<DropdownMenu.Separator />- <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleRemoveContainer(item.id)} disabled={isLoading.remove || isAnyLoading}>+ <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleRemoveContainer(item.Id)} disabled={isLoading.remove || isAnyLoading}>{#if isLoading.remove}<Loader2 class="animate-spin size-4" />{:else}diff --git a/src/routes/containers/[id]/+page.svelte b/src/routes/containers/[id]/+page.svelteindex 7acfc84b4..b602f5044 100644--- a/src/routes/containers/[id]/+page.svelte+++ b/src/routes/containers/[id]/+page.svelte@@ -11,7 +11,6 @@import { formatBytes } from '$lib/utils/bytes.util';import type Docker from 'dockerode';import type { ContainerInspectInfo } from 'dockerode';- import type { ContainerDetails } from '$lib/types/docker/container.type';import StatusBadge from '$lib/components/badges/status-badge.svelte';import * as Tabs from '$lib/components/ui/tabs/index.js';import { onDestroy } from 'svelte';@@ -83,10 +82,10 @@});function startLogStream() {- if (logEventSource || !container?.id) return;+ if (logEventSource || !container?.Id) return;try {- const url = `/api/containers/${container.id}/logs/stream`;+ const url = `/api/containers/${container.Id}/logs/stream`;const eventSource = new EventSource(url);logEventSource = eventSource;@@ -118,10 +117,10 @@}function startStatsStream() {- if (statsEventSource || !container?.id || !container.state?.Running) return;+ if (statsEventSource || !container?.Id || !container.State?.Running) return;try {- const url = `/api/containers/${container.id}/stats/stream`;+ const url = `/api/containers/${container.Id}/stats/stream`;const eventSource = new EventSource(url);statsEventSource = eventSource;@@ -160,7 +159,7 @@}$effect(() => {- if (activeTab === 'stats' && container?.state?.Running) {+ if (activeTab === 'stats' && container?.State?.Running) {startStatsStream();} else if (statsEventSource) {closeStatsStream();@@ -214,7 +213,7 @@return 'N/A';};- const primaryIpAddress = $derived(getPrimaryIpAddress(container?.networkSettings));+ const primaryIpAddress = $derived(getPrimaryIpAddress(container?.NetworkSettings));$effect(() => {if (logsContainer && displayedLogs && autoScrollLogs) {@@ -253,18 +252,18 @@</Breadcrumb.Item><Breadcrumb.Separator /><Breadcrumb.Item>- <Breadcrumb.Page>{container?.name || 'Loading...'}</Breadcrumb.Page>+ <Breadcrumb.Page>{container?.Name || 'Loading...'}</Breadcrumb.Page></Breadcrumb.Item></Breadcrumb.List></Breadcrumb.Root><div class="mt-2 flex items-center gap-2"><h1 class="text-2xl font-bold tracking-tight">- {container?.name || 'Container Details'}+ {container?.Name || 'Container Details'}</h1>- {#if container?.state}- <span class="self-start mt-1.5"><StatusBadge variant={container.state.Status === 'running' ? 'green' : container.state.Status === 'exited' ? 'red' : 'amber'} text={container.state.Status} /></span>+ {#if container?.State}+ <span class="self-start mt-1.5"><StatusBadge variant={container.State.Status === 'running' ? 'green' : container.State.Status === 'exited' ? 'red' : 'amber'} text={container.State.Status} /></span>{/if}</div></div>@@ -272,9 +271,9 @@{#if container}<div class="flex gap-2 flex-wrap"><ActionButtons- id={container.id}+ id={container.Id}type="container"- itemState={container.state?.Running ? 'running' : 'stopped'}+ itemState={container.State?.Running ? 'running' : 'stopped'}loading={{start: starting,stop: stopping,@@ -312,8 +311,8 @@<div class="min-w-0 flex-1"><p class="text-sm font-medium text-muted-foreground">Image</p><p class="text-base font-semibold mt-1 break-all">- <span class="truncate block" title={container.config?.Image || 'N/A'}>- {container.config?.Image || 'N/A'}+ <span class="truncate block" title={container.Config?.Image || 'N/A'}>+ {container.Config?.Image || 'N/A'}</span></p></div>@@ -325,8 +324,8 @@</div><div class="min-w-0 flex-1"><p class="text-sm font-medium text-muted-foreground">Created</p>- <p class="text-base font-semibold mt-1 truncate" title={formatDate(container.created)}>- {formatDate(container.created)}+ <p class="text-base font-semibold mt-1 truncate" title={formatDate(container.Created)}>+ {formatDate(container.Created)}</p></div></div>@@ -349,8 +348,8 @@</div><div class="min-w-0 flex-1"><p class="text-sm font-medium text-muted-foreground">Command</p>- <p class="text-base font-semibold mt-1 truncate" title={container.config?.Cmd?.join(' ') || 'N/A'}>- {container.config?.Cmd?.join(' ') || 'N/A'}+ <p class="text-base font-semibold mt-1 truncate" title={container.Config?.Cmd?.join(' ') || 'N/A'}>+ {container.Config?.Cmd?.join(' ') || 'N/A'}</p></div></div>@@ -367,31 +366,31 @@<div class="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm"><div><span class="font-semibold">Container ID:</span>- <div class="font-mono mt-1 text-xs break-all">{container.id}</div>+ <div class="font-mono mt-1 text-xs break-all">{container.Id}</div></div>- {#if container.config?.WorkingDir}+ {#if container.Config?.WorkingDir}<div><span class="font-semibold">Working Directory:</span>- <div class="mt-1 break-all">{container.config.WorkingDir}</div>+ <div class="mt-1 break-all">{container.Config.WorkingDir}</div></div>{/if}- {#if container.config?.User}+ {#if container.Config?.User}<div><span class="font-semibold">User:</span>- <div class="mt-1">{container.config.User}</div>+ <div class="mt-1">{container.Config.User}</div></div>{/if}- {#if container.state?.Health}+ {#if container.State?.Health}<div class="col-span-full"><span class="font-semibold">Health Status:</span><div class="mt-1 flex gap-2 items-center">- <StatusBadge variant={container.state.Health.Status === 'healthy' ? 'green' : container.state.Health.Status === 'unhealthy' ? 'red' : 'amber'} text={container.state.Health.Status} />- {#if container.state.Health.Log && container.state.Health.Log.length > 0}+ <StatusBadge variant={container.State.Health.Status === 'healthy' ? 'green' : container.State.Health.Status === 'unhealthy' ? 'red' : 'amber'} text={container.State.Health.Status} />+ {#if container.State.Health.Log && container.State.Health.Log.length > 0}<span class="text-xs text-muted-foreground">- Last check: {new Date(container.state.Health.Log[0].Start).toLocaleString()}+ Last check: {new Date(container.State.Health.Log[0].Start).toLocaleString()}</span>{/if}</div>@@ -409,9 +408,9 @@<Card.Description>Container environment configuration</Card.Description></Card.Header><Card.Content class="max-h-[360px] overflow-y-auto">- {#if container.config?.Env && container.config.Env.length > 0}+ {#if container.Config?.Env && container.Config.Env.length > 0}<div class="space-y-2">- {#each container.config.Env as env, index (index)}+ {#each container.Config.Env as env, index (index)}<div class="text-xs flex overflow-hidden">{#if env.includes('=')}{@const [key, ...valueParts] = env.split('=')}@@ -438,9 +437,9 @@<Card.Description>Container port mappings</Card.Description></Card.Header><Card.Content>- {#if container.networkSettings?.Ports && Object.keys(container.networkSettings.Ports).length > 0}+ {#if container.NetworkSettings?.Ports && Object.keys(container.NetworkSettings.Ports).length > 0}<div class="space-y-2">- {#each Object.entries(container.networkSettings.Ports) as [containerPort, hostBindings] (containerPort)}+ {#each Object.entries(container.NetworkSettings.Ports) as [containerPort, hostBindings] (containerPort)}<div class="flex flex-col sm:flex-row sm:items-center justify-between rounded-md bg-muted/40 p-2 px-3 gap-1"><div class="font-mono text-sm truncate" title={containerPort}>{containerPort}@@ -472,9 +471,9 @@<Card.Description>Container metadata labels</Card.Description></Card.Header><Card.Content class="max-h-[360px] overflow-y-auto">- {#if container.labels && Object.keys(container.labels).length > 0}+ {#if container.Config.Labels && Object.keys(container.Config.Labels).length > 0}<div class="space-y-2">- {#each Object.entries(container.labels) as [key, value] (key)}+ {#each Object.entries(container.Config.Labels) as [key, value] (key)}<div class="text-xs flex overflow-hidden"><div class="flex w-full"><span class="font-semibold mr-2 min-w-[120px] max-w-[180px] truncate shrink-0" title={key}>{key}:</span>@@ -497,9 +496,9 @@<Card.Description>Network settings and connections</Card.Description></Card.Header><Card.Content>- {#if container.networkSettings?.Networks && Object.keys(container.networkSettings.Networks).length > 0}+ {#if container.NetworkSettings?.Networks && Object.keys(container.NetworkSettings.Networks).length > 0}<div class="space-y-4">- {#each Object.entries(container.networkSettings.Networks) as [networkName, rawNetworkConfig] (networkName)}+ {#each Object.entries(container.NetworkSettings.Networks) as [networkName, rawNetworkConfig] (networkName)}{@const networkConfig = ensureNetworkConfig(rawNetworkConfig)}<div class="rounded-md bg-muted/40 p-3"><div class="text-sm font-medium">{networkName}</div>@@ -550,9 +549,9 @@<Card.Description>Container filesystem mounts</Card.Description></Card.Header><Card.Content>- {#if container.mounts && container.mounts.length > 0}+ {#if container.Mounts && container.Mounts.length > 0}<div class="space-y-4">- {#each container.mounts as mount (mount.Destination)}+ {#each container.Mounts as mount (mount.Destination)}<div class="rounded-md overflow-hidden border border-muted"><divclass={`p-3 flex items-center justify-between gap-2@@ -723,7 +722,7 @@</Card.Header><Card.Content>- {#if stats && container.state?.Running}+ {#if stats && container.State?.Running}<div class="space-y-6"><div><div class="flex justify-between items-center mb-2">@@ -788,7 +787,7 @@</div>{/if}</div>- {:else if !container.state?.Running}+ {:else if !container.State?.Running}<div class="text-center text-sm text-muted-foreground italic py-12">Container is not running. Stats unavailable.</div>{:else}<div class="text-center text-sm text-muted-foreground italic py-12">Could not load stats.</div>diff --git a/src/routes/containers/create-container-dialog.svelte b/src/routes/containers/create-container-dialog.svelteindex 81f682564..52474ffb1 100644--- a/src/routes/containers/create-container-dialog.svelte+++ b/src/routes/containers/create-container-dialog.svelte@@ -1,6 +1,5 @@<script lang="ts">- import type { ContainerConfig } from '$lib/types/docker/container.type';- import { type HealthConfig } from 'dockerode';+ import { type HealthConfig, type ContainerCreateOptions, type VolumeInspectInfo, type NetworkInspectInfo } from 'dockerode';import { Button } from '$lib/components/ui/button/index.js';import * as Dialog from '$lib/components/ui/dialog/index.js';import { Input } from '$lib/components/ui/input/index.js';@@ -15,12 +14,13 @@import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import ContainerAPIService from '$lib/services/api/container-api-service';+ import type { ServiceImage } from '$lib/types/docker';interface Props {open?: boolean;- volumes?: { name: string }[];- networks?: { name: string; driver: string }[];- images?: { id: string; repo: string; tag: string }[];+ volumes?: VolumeInspectInfo[];+ networks?: NetworkInspectInfo[];+ images?: ServiceImage[];onClose?: () => void;}@@ -28,26 +28,23 @@const containerApi = new ContainerAPIService();- // Internal statelet isCreating = $state(false);let containerName = $state('');let selectedImage = $state('');let selectedTab = $state('basic');- // Ports mapping (host:container)let ports = $state<{hostPort: string;containerPort: string;+ protocol?: 'tcp' | 'udp' | 'sctp';hostError?: string;containerError?: string;}[]- >([{ hostPort: '', containerPort: '' }]);+ >([{ hostPort: '', containerPort: '', protocol: 'tcp' }]);- // Volume mounts- let volumeMounts = $state<{ source: string; target: string }[]>([{ source: '', target: '' }]);+ let volumeMounts = $state<{ source: string; target: string; readOnly?: boolean }[]>([{ source: '', target: '', readOnly: false }]);- // Environment variableslet envVars = $state<{ key: string; value: string; sensitive?: boolean }[]>([{ key: '', value: '', sensitive: true }]);const restartPolicyOptions = [@@ -57,34 +54,28 @@{ value: 'unless-stopped', label: 'Unless Stopped' }];- // Network and restart policy- let network = $state('');- let restartPolicy = $state('unless-stopped'); // "no", "always", "on-failure", "unless-stopped"+ let networkMode = $state('');+ let restartPolicy = $state('unless-stopped');const selectedRestartPolicyLabel = $derived(restartPolicyOptions.find((opt) => opt.value === restartPolicy)?.label || restartPolicy);- // Add state for IP addresseslet ipv4Address = $state('');let ipv6Address = $state('');- // Add state for Healthchecklet enableHealthcheck = $state(false);- let healthcheckTest = $state<string[]>(['']); // Dockerode expects string[]- let healthcheckInterval = $state<number | undefined>(undefined); // In nanoseconds- let healthcheckTimeout = $state<number | undefined>(undefined); // In nanoseconds+ let healthcheckTest = $state<string[]>(['']);+ let healthcheckInterval = $state<number | undefined>(undefined);+ let healthcheckTimeout = $state<number | undefined>(undefined);let healthcheckRetries = $state<number | undefined>(undefined);- let healthcheckStartPeriod = $state<number | undefined>(undefined); // In nanoseconds+ let healthcheckStartPeriod = $state<number | undefined>(undefined);- // Add state for Labelslet labels = $state<{ key: string; value: string }[]>([{ key: '', value: '' }]);- // Add state for Command, User, Resources- let commandOverride = $state(''); // Input as string, will split later+ let commandOverride = $state('');let runAsUser = $state('');- let memoryLimitStr = $state(''); // Input as string (e.g., "512m", "1g")- let cpuLimitStr = $state(''); // Input as string (e.g., "0.5", "1")+ let memoryLimitStr = $state('');+ let cpuLimitStr = $state('');- // Add state for Auto-updatelet autoUpdate = $state(false);function handleClose() {@@ -92,30 +83,23 @@if (onCloseProp) {onCloseProp();}+ // Optionally reset form fields here}- // Port validation - improvedfunction validatePortNumber(port: string | number): {isValid: boolean;error?: string;} {const portStr = typeof port === 'number' ? port.toString() : port;-- if (!portStr || !portStr.trim()) return { isValid: true };-+ if (!portStr || !portStr.trim()) return { isValid: true }; // Empty is fine, will be filteredconst portNum = parseInt(portStr, 10);-if (isNaN(portNum) || portNum.toString() !== portStr.trim()) {return { isValid: false, error: 'Invalid port number' };}-if (portNum < 1 || portNum > 65535) {return { isValid: false, error: 'Port must be between 1-65535' };}-- if (portNum < 1024) {- return { isValid: true, error: 'Privileged port (<1024)' };- }+ // Warning for privileged ports can be handled by UI, not strict validation failreturn { isValid: true };}@@ -138,19 +122,21 @@});function addPort() {- ports = [...ports, { hostPort: '', containerPort: '' }];+ ports = [...ports, { hostPort: '', containerPort: '', protocol: 'tcp' }];}function removePort(index: number) {ports = ports.filter((_, i) => i !== index);+ if (ports.length === 0) addPort(); // Ensure at least one port row}function addVolumeMount() {- volumeMounts = [...volumeMounts, { source: '', target: '' }];+ volumeMounts = [...volumeMounts, { source: '', target: '', readOnly: false }];}function removeVolumeMount(index: number) {volumeMounts = volumeMounts.filter((_, i) => i !== index);+ if (volumeMounts.length === 0) addVolumeMount(); // Ensure at least one volume row}function addEnvVar() {@@ -159,6 +145,7 @@function removeEnvVar(index: number) {envVars = envVars.filter((_, i) => i !== index);+ if (envVars.length === 0) addEnvVar(); // Ensure at least one env var row}function addLabel() {@@ -167,16 +154,17 @@function removeLabel(index: number) {labels = labels.filter((_, i) => i !== index);+ if (labels.length === 0) addLabel(); // Ensure at least one label row}- const isUserDefinedNetwork = $derived(network && network !== '' && network !== 'host' && network !== 'none' && network !== 'bridge');+ const isUserDefinedNetworkSelected = $derived(networkMode && networkMode !== '' && networkMode !== 'host' && networkMode !== 'none' && networkMode !== 'bridge');async function handleSubmit() {if (!selectedImage || !containerName.trim() || isCreating) return;let hasInvalidPort = false;ports.forEach((port) => {- if ((port.hostPort && !validatePortNumber(port.hostPort).isValid) || (port.containerPort && !validatePortNumber(port.containerPort).isValid)) {+ if ((port.hostPort && validatePortNumber(port.hostPort).error && validatePortNumber(port.hostPort).error !== 'Privileged port (<1024)') || (port.containerPort && validatePortNumber(port.containerPort).error && validatePortNumber(port.containerPort).error !== 'Privileged port (<1024)')) {hasInvalidPort = true;}});@@ -186,10 +174,10 @@return;}- const filteredPorts = ports.filter((p) => p.hostPort.trim() && p.containerPort.trim()).map(({ hostPort, containerPort }) => ({ hostPort, containerPort }));- const filteredVolumes = volumeMounts.filter((v) => v.source.trim() && v.target.trim());- const filteredEnvVars = envVars.filter((e) => e.key.trim());- const filteredLabels = labels+ isCreating = true;++ // Construct Docker.ContainerCreateOptions+ const finalLabels = labels.filter((l) => l.key.trim()).reduce((acc, label) => {@@ -200,77 +188,117 @@);if (autoUpdate) {- filteredLabels['arcane.auto-update'] = 'true';+ finalLabels['arcane.auto-update'] = 'true';}+ const exposedPorts: { [port: string]: Record<string, never> } = {};+ const portBindings: { [portAndProtocol: string]: { HostPort: string }[] } = {};++ ports+ .filter((p) => p.hostPort.trim() && p.containerPort.trim())+ .forEach((p) => {+ const key = `${p.containerPort.trim()}/${p.protocol || 'tcp'}`;+ exposedPorts[key] = {};+ portBindings[key] = [{ HostPort: p.hostPort.trim() }];+ });++ const binds = volumeMounts.filter((v) => v.source.trim() && v.target.trim()).map((v) => `${v.source.trim()}:${v.target.trim()}${v.readOnly ? ':ro' : ''}`);++ const env = envVars.filter((e) => e.key.trim()).map((e) => `${e.key.trim()}=${e.value}`);+let healthcheckConfig: HealthConfig | undefined = undefined;if (enableHealthcheck && healthcheckTest.length > 0 && healthcheckTest[0].trim() !== '') {const toNano = (seconds: number | undefined) => (seconds ? seconds * 1_000_000_000 : undefined);healthcheckConfig = {- Test: healthcheckTest,+ Test: healthcheckTest.filter((t) => t.trim() !== ''), // Ensure Test is not empty stringsInterval: toNano(healthcheckInterval),Timeout: toNano(healthcheckTimeout),Retries: healthcheckRetries,StartPeriod: toNano(healthcheckStartPeriod)};+ if (healthcheckConfig && healthcheckConfig.Test && healthcheckConfig.Test.length === 0) healthcheckConfig = undefined;}- const commandArray = commandOverride.trim() ? commandOverride.trim().split(/\s+/) : undefined;-let memoryBytes: number | undefined;try {memoryBytes = memoryLimitStr.trim() ? parseBytes(memoryLimitStr.trim()) : undefined;} catch (e) {console.error('Invalid memory format:', e);toast.error(`Invalid memory format: ${memoryLimitStr}`);+ isCreating = false;return;}- let cpuUnits: number | undefined;+ let nanoCPUs: number | undefined;try {- cpuUnits = cpuLimitStr.trim() ? parseFloat(cpuLimitStr.trim()) : undefined;- if (cpuUnits !== undefined && isNaN(cpuUnits)) {- throw new Error('CPU Limit must be a number');+ const cpuVal = cpuLimitStr.trim() ? parseFloat(cpuLimitStr.trim()) : undefined;+ if (cpuVal !== undefined) {+ if (isNaN(cpuVal) || cpuVal <= 0) {+ throw new Error('CPU Limit must be a positive number');+ }+ nanoCPUs = cpuVal * 1_000_000_000;}- } catch (e) {+ } catch (e: any) {console.error('Invalid CPU format:', e);- toast.error(`Invalid CPU format: ${cpuLimitStr}`);+ toast.error(e.message || `Invalid CPU format: ${cpuLimitStr}`);+ isCreating = false;return;}- const containerConfig: ContainerConfig = {+ const createOptions: ContainerCreateOptions = {name: containerName.trim(),- image: selectedImage,- ports: filteredPorts.length > 0 ? filteredPorts : undefined,- volumes: filteredVolumes.length > 0 ? filteredVolumes : undefined,- envVars: filteredEnvVars.length > 0 ? filteredEnvVars : undefined,- network: network || undefined,- restart: restartPolicy as 'no' | 'always' | 'on-failure' | 'unless-stopped',- networkConfig:- isUserDefinedNetwork && (ipv4Address.trim() || ipv6Address.trim())- ? {- ipv4Address: ipv4Address.trim() || undefined,- ipv6Address: ipv6Address.trim() || undefined- }- : undefined,- healthcheck: healthcheckConfig,- labels: Object.keys(filteredLabels).length > 0 ? filteredLabels : undefined,- command: commandArray,- user: runAsUser.trim() || undefined,- memoryLimit: memoryBytes,- cpuLimit: cpuUnits+ Image: selectedImage,+ Cmd: commandOverride.trim() ? commandOverride.trim().split(/\s+/) : undefined,+ User: runAsUser.trim() || undefined,+ Labels: Object.keys(finalLabels).length > 0 ? finalLabels : undefined,+ Env: env.length > 0 ? env : undefined,+ ExposedPorts: Object.keys(exposedPorts).length > 0 ? exposedPorts : undefined,+ Healthcheck: healthcheckConfig,+ HostConfig: {+ PortBindings: Object.keys(portBindings).length > 0 ? portBindings : undefined,+ Binds: binds.length > 0 ? binds : undefined,+ RestartPolicy: { Name: restartPolicy as 'no' | 'always' | 'on-failure' | 'unless-stopped' },+ Memory: memoryBytes,+ NanoCpus: nanoCPUs,+ NetworkMode: networkMode || undefined // Default is 'bridge' if empty string+ }};- isCreating = true;+ if (isUserDefinedNetworkSelected && (ipv4Address.trim() || ipv6Address.trim())) {+ createOptions.NetworkingConfig = {+ EndpointsConfig: {+ [networkMode]: {+ // networkMode here is the name of the user-defined network+ IPAMConfig: {+ IPv4Address: ipv4Address.trim() || undefined,+ IPv6Address: ipv6Address.trim() || undefined+ }+ }+ }+ };+ // If using NetworkingConfig for a specific network, NetworkMode in HostConfig might be redundant+ // or should match. Docker typically handles this, but for clarity, if networkMode is a custom one,+ // it's often set in HostConfig.NetworkMode.+ if (createOptions.HostConfig) {+ createOptions.HostConfig.NetworkMode = networkMode;+ }+ } else if (networkMode && createOptions.HostConfig) {+ // For standard modes like 'bridge', 'host', 'none'+ createOptions.HostConfig.NetworkMode = networkMode;+ }handleApiResultWithCallbacks({- result: await tryCatch(containerApi.create(containerConfig)),+ result: await tryCatch(containerApi.create(createOptions)), // Pass ContainerCreateOptionsmessage: 'Failed to Create Container',setLoadingState: (value) => (isCreating = value),onSuccess: async () => {- toast.success(`Container "${containerConfig.name}" created successfully!`);+ toast.success(`Container "${createOptions.name}" created successfully!`);await invalidateAll();handleClose();+ },+ onError: () => {+ // Ensure isCreating is reset on error too+ isCreating = false;}});}@@ -312,7 +340,7 @@</Select.Trigger><Select.Content><Select.Group>- {#each images as image (image.id)}+ {#each images as image (image.Id)}<Select.Item value={image.repo + ':' + image.tag}>{image.repo + ':' + image.tag}</Select.Item>@@ -343,12 +371,12 @@<div class="space-y-4">{#each ports as port, index (index)}<div class="flex space-x-3 items-end">- <div class="flex-1 grid grid-cols-2 gap-4">+ <div class="flex-1 grid grid-cols-3 gap-4"><div><Label for={`host-port-${index}`} class="mb-2 block text-sm">Host Port</Label>- <Input id={`host-port-${index}`} bind:value={port.hostPort} placeholder="e.g., 8080" disabled={isCreating} type="text" pattern="[0-9]*" inputmode="numeric" class={port.hostError && port.hostPort ? 'border-red-500' : ''} />+ <Input id={`host-port-${index}`} bind:value={port.hostPort} placeholder="e.g., 8080" disabled={isCreating} type="text" pattern="[0-9]*" inputmode="numeric" class={port.hostError && port.hostPort && port.hostError !== 'Privileged port (<1024)' ? 'border-red-500' : ''} />{#if port.hostError && port.hostPort}- <div class="flex items-center text-xs text-red-500 mt-1">+ <div class="flex items-center text-xs mt-1 {port.hostError === 'Privileged port (<1024)' ? 'text-amber-600' : 'text-red-500'}"><AlertCircle class="mr-1 size-3" />{port.hostError}</div>@@ -357,17 +385,30 @@<div><Label for={`container-port-${index}`} class="mb-2 block text-sm">Container Port</Label>- <Input id={`container-port-${index}`} bind:value={port.containerPort} placeholder="e.g., 80" disabled={isCreating} type="text" pattern="[0-9]*" inputmode="numeric" class={port.containerError && port.containerPort ? 'border-red-500' : ''} />+ <Input id={`container-port-${index}`} bind:value={port.containerPort} placeholder="e.g., 80" disabled={isCreating} type="text" pattern="[0-9]*" inputmode="numeric" class={port.containerError && port.containerPort && port.containerError !== 'Privileged port (<1024)' ? 'border-red-500' : ''} />{#if port.containerError && port.containerPort}- <div class="flex items-center text-xs text-red-500 mt-1">+ <div class="flex items-center text-xs mt-1 {port.containerError === 'Privileged port (<1024)' ? 'text-amber-600' : 'text-red-500'}"><AlertCircle class="mr-1 size-3" />{port.containerError}</div>{/if}</div>+ <div>+ <Label for={`port-protocol-${index}`} class="mb-2 block text-sm">Protocol</Label>+ <Select.Root type="single" bind:value={port.protocol} disabled={isCreating}>+ <Select.Trigger class="w-full">+ <span>{port.protocol?.toUpperCase() || 'TCP'}</span>+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="tcp">TCP</Select.Item>+ <Select.Item value="udp">UDP</Select.Item>+ <Select.Item value="sctp">SCTP</Select.Item>+ </Select.Content>+ </Select.Root>+ </div></div>- <Button variant="destructive" size="icon" type="button" onclick={() => removePort(index)} disabled={ports.length <= 1 || isCreating} class="shrink-0">+ <Button variant="destructive" size="icon" type="button" onclick={() => removePort(index)} disabled={(ports.length <= 1 && !ports[0].hostPort && !ports[0].containerPort) || isCreating} class="shrink-0"><Trash class="size-4" /></Button></div>@@ -383,28 +424,25 @@<div class="space-y-4">{#each volumeMounts as mount, index (index)}<div class="flex space-x-3 items-end">- <div class="flex-1 grid grid-cols-2 gap-4">+ <div class="flex-1 grid grid-cols-2 gap-4 items-center"><div>- <Label for={`volume-source-${index}`} class="mb-2 block">Source Volume</Label>- <Select.Root type="single" bind:value={mount.source} disabled={isCreating}>- <Select.Trigger class="w-full">- <span>{mount.source || 'Select volume'}</span>- </Select.Trigger>- <Select.Content>- {#each volumes as volume (volume.name)}- <Select.Item value={volume.name}>- {volume.name}- </Select.Item>- {/each}- </Select.Content>- </Select.Root>+ <Label for={`volume-source-${index}`} class="mb-2 block">Host Path / Volume Name</Label>+ <Input id={`volume-source-${index}`} bind:value={mount.source} placeholder="e.g., /path/on/host or my_volume" disabled={isCreating} />+ <!--+ Future improvement: Differentiate between selecting existing named volumes+ and entering a host path. For now, user types it.+ --></div><div><Label for={`volume-target-${index}`} class="mb-2 block">Container Path</Label>- <Input id={`volume-target-${index}`} bind:value={mount.target} placeholder="/data" disabled={isCreating} />+ <Input id={`volume-target-${index}`} bind:value={mount.target} placeholder="/data_in_container" disabled={isCreating} /></div></div>- <Button variant="destructive" size="icon" type="button" onclick={() => removeVolumeMount(index)} disabled={volumeMounts.length <= 1 || isCreating} class="shrink-0">+ <div class="flex items-center pt-6">+ <Switch id={`volume-readonly-${index}`} bind:checked={mount.readOnly} disabled={isCreating} />+ <Label for={`volume-readonly-${index}`} class="ml-2 text-sm">Read-only</Label>+ </div>+ <Button variant="destructive" size="icon" type="button" onclick={() => removeVolumeMount(index)} disabled={(volumeMounts.length <= 1 && !volumeMounts[0].source && !volumeMounts[0].target) || isCreating} class="shrink-0"><Trash class="size-4" /></Button></div>@@ -448,7 +486,7 @@</div></div></div>- <Button variant="destructive" size="icon" type="button" onclick={() => removeEnvVar(index)} disabled={envVars.length <= 1 || isCreating} class="shrink-0">+ <Button variant="destructive" size="icon" type="button" onclick={() => removeEnvVar(index)} disabled={(envVars.length <= 1 && !envVars[0].key && !envVars[0].value) || isCreating} class="shrink-0"><Trash class="size-4" /></Button></div>@@ -463,23 +501,25 @@<Tabs.Content value="network"><div class="space-y-4"><div class="grid grid-cols-1 gap-2">- <Label for="container-network">Network</Label>- <Select.Root type="single" bind:value={network} disabled={isCreating}>+ <Label for="container-network">Network Mode / Name</Label>+ <Select.Root type="single" bind:value={networkMode} disabled={isCreating}><Select.Trigger class="w-full">- <span>{network || 'Default Bridge'}</span>+ <span>{networkMode || 'Default (bridge)'}</span></Select.Trigger><Select.Content>- <Select.Item value="">Default Bridge</Select.Item>- {#each networks.filter((n) => n.name !== 'bridge' && n.name !== 'host' && n.name !== 'none') as net (net.name)}- <Select.Item value={net.name}>- {net.name} ({net.driver})+ <Select.Item value="">Default (bridge)</Select.Item>+ <Select.Item value="host">Host</Select.Item>+ <Select.Item value="none">None</Select.Item>+ {#each networks.filter((n) => n.Name !== 'bridge' && n.Name !== 'host' && n.Name !== 'none') as net (net.Id)}+ <Select.Item value={net.Name}>+ {net.Name} ({net.Driver})</Select.Item>{/each}</Select.Content></Select.Root></div>- {#if isUserDefinedNetwork}+ {#if isUserDefinedNetworkSelected}<div class="border-t pt-4 mt-4 space-y-4"><p class="text-sm text-muted-foreground">Optional: Assign static IP addresses (requires network with IPAM configured).</p><div class="grid grid-cols-1 md:grid-cols-2 gap-4">@@ -501,7 +541,7 @@<Tabs.Content value="healthcheck"><div class="space-y-4"><div class="flex items-center space-x-2">- <input type="checkbox" id="enable-healthcheck" bind:checked={enableHealthcheck} disabled={isCreating} class="form-checkbox text-primary focus:ring-primary border-gray-300 rounded size-4" />+ <Switch id="enable-healthcheck" bind:checked={enableHealthcheck} disabled={isCreating} /><Label for="enable-healthcheck" class="cursor-pointer">Enable Healthcheck</Label></div>@@ -510,7 +550,7 @@<div class="space-y-2"><Label for="healthcheck-test">Test Command</Label><Input id="healthcheck-test" bind:value={healthcheckTest[0]} placeholder="e.g., CMD-SHELL curl -f http://localhost:80 || exit 1" disabled={isCreating} />- <p class="text-xs text-muted-foreground">Command to run inside the container. Use `CMD` or `CMD-SHELL`.</p>+ <p class="text-xs text-muted-foreground">Command to run inside the container. Use `CMD` or `CMD-SHELL`. For multiple arguments, use advanced settings or configure directly in compose.</p></div><div class="grid grid-cols-2 md:grid-cols-4 gap-4">@@ -555,7 +595,7 @@<Input id={`label-value-${index}`} bind:value={label.value} placeholder="e.g., my-app" disabled={isCreating} /></div></div>- <Button variant="destructive" size="icon" type="button" onclick={() => removeLabel(index)} disabled={labels.length <= 1 || isCreating} class="shrink-0">+ <Button variant="destructive" size="icon" type="button" onclick={() => removeLabel(index)} disabled={(labels.length <= 1 && !labels[0].key && !labels[0].value) || isCreating} class="shrink-0"><Trash class="size-4" /></Button></div>@@ -592,8 +632,8 @@<p class="text-xs text-muted-foreground">Format: number + unit (b, k, m, g). Minimum 4m.</p></div><div class="space-y-2">- <Label for="cpu-limit">CPU Limit</Label>- <Input id="cpu-limit" bind:value={cpuLimitStr} placeholder="e.g., 0.5, 1, 2" disabled={isCreating} type="number" step="0.1" min="0" />+ <Label for="cpu-limit">CPU Limit (cores)</Label>+ <Input id="cpu-limit" bind:value={cpuLimitStr} placeholder="e.g., 0.5, 1, 2" disabled={isCreating} type="number" step="0.1" min="0.01" /><p class="text-xs text-muted-foreground">Number of CPU cores (e.g., 1.5 = 1.5 cores).</p></div></div>diff --git a/src/routes/images/+page.server.ts b/src/routes/images/+page.server.tsindex c8a046791..47bdd926c 100644--- a/src/routes/images/+page.server.ts+++ b/src/routes/images/+page.server.ts@@ -1,6 +1,6 @@import type { PageServerLoad } from './$types';import { listImages, isImageInUse, checkImageMaturity } from '$lib/services/docker/image-service';-import type { EnhancedImageInfo } from '$lib/types/docker';+import type { EnhancedImageInfo, ServiceImage } from '$lib/types/docker';import { getSettings } from '$lib/services/settings-service';import type { Settings } from '$lib/types/settings.type';@@ -12,20 +12,20 @@ type ImageData = {export const load: PageServerLoad = async (): Promise<ImageData> => {try {- const images = await listImages();+ const images: ServiceImage[] = await listImages();const settings = await getSettings();const enhancedImages = await Promise.all(images.map(async (image): Promise<EnhancedImageInfo> => {- const inUse = await isImageInUse(image.id);+ const inUse = await isImageInUse(image.Id);let maturity = undefined;try {if (image.repo !== '<none>' && image.tag !== '<none>') {- maturity = await checkImageMaturity(image.id);+ maturity = await checkImageMaturity(image.Id);}} catch (maturityError) {- console.error(`Failed to check maturity for image ${image.id}:`, maturityError);+ console.error(`Failed to check maturity for image ${image.Id}:`, maturityError);}return {@@ -42,10 +42,11 @@ export const load: PageServerLoad = async (): Promise<ImageData> => {};} catch (err: any) {console.error('Failed to load images:', err);+ const settings = await getSettings().catch(() => ({}) as Settings);return {images: [],error: err.message || 'Failed to connect to Docker or list images.',- settings: {} as Settings+ settings: settings};}};diff --git a/src/routes/images/+page.svelte b/src/routes/images/+page.svelteindex 4f3804fcb..90d22e6b0 100644--- a/src/routes/images/+page.svelte+++ b/src/routes/images/+page.svelte@@ -58,12 +58,11 @@let isConfirmPruneDialogOpen = $state(false);const totalImages = $derived(images?.length || 0);- const totalSize = $derived(images?.reduce((acc, img) => acc + (img.size || 0), 0) || 0);+ const totalSize = $derived(images?.reduce((acc, img) => acc + (img.Size || 0), 0) || 0);- // let enhancedImages: EnhancedImageInfo[] = [];const enhancedImages = $derived(images.map((image) => {- const storedMaturity = $maturityStore.maturityData[image.id];+ const storedMaturity = $maturityStore.maturityData[image.Id];return {...image,maturity: storedMaturity || image.maturity@@ -78,22 +77,19 @@});async function loadMaturityData() {- // Only check visible images based on paginationconst visibleImageIds = images.filter((img) => img.repo !== '<none>' && img.tag !== '<none>')- .slice(0, 20) // Limit to visible images- .map((img) => img.id);+ .slice(0, 20)+ .map((img) => img.Id);if (visibleImageIds.length === 0) return;isLoading.checking = true;try {- // Process in smaller batches to avoid overwhelming the serverconst BATCH_SIZE = 5;for (let i = 0; i < visibleImageIds.length; i += BATCH_SIZE) {const batch = visibleImageIds.slice(i, i + BATCH_SIZE);await imageApi.checkMaturityBatch(batch);- // Give UI time to update between batchesif (i + BATCH_SIZE < visibleImageIds.length) {await new Promise((resolve) => setTimeout(resolve, 50));}@@ -109,7 +105,7 @@const { imageRef, tag = 'latest', platform, registryUrl } = event;isLoading.pulling = true;- pullProgress = 0; // Reset progress+ pullProgress = 0;try {const encodedImageRef = encodeURIComponent(imageRef);@@ -126,7 +122,6 @@if (foundCredential && foundCredential.username) {toast.info(`Attempting pull from ${foundCredential.url} with user ${foundCredential.username}`);} else if (registryUrl !== 'docker.io' && registryUrl !== '') {- // Avoid warning for default Docker Hubtoast.error(`Credentials not found for ${registryUrl}. Attempting unauthenticated pull.`);}}@@ -146,7 +141,7 @@if (data.type === 'info' || data.type === 'warning') {if (data.type === 'info') toast.info(data.message);if (data.type === 'warning') toast.error(data.message);- return; // Don't process as progress/completion+ return;}if (data.progress !== undefined) {@@ -161,7 +156,7 @@setTimeout(async () => {await invalidateAll();- }, 500); // Give Docker a moment before invalidating+ }, 500);isLoading.pulling = false;}};@@ -194,8 +189,8 @@let failureCount = 0;for (const id of selectedIds) {- const image = images.find((img) => img.id === id);- const imageIdentifier = image?.repoTags?.[0] || id.substring(0, 12);+ const image = images.find((img) => img.Id === id);+ const imageIdentifier = image?.RepoTags?.[0] || id.substring(0, 12);if (image?.inUse) {toast.error(`Image "${imageIdentifier}" is in use and cannot be deleted.`);@@ -260,8 +255,8 @@}async function handleImageRemove(id: string) {- const image = images.find((img) => img.id === id);- const imageIdentifier = image?.repoTags?.[0] || id.substring(0, 12);+ const image = images.find((img) => img.Id === id);+ const imageIdentifier = image?.RepoTags?.[0] || id.substring(0, 12);openConfirmDialog({title: 'Delete Image',@@ -287,7 +282,7 @@async function checkAllMaturity() {isLoading.checking = true;- const imageIdsToCheck = images.filter((image) => image.id).map((image) => image.id);+ const imageIdsToCheck = images.filter((image) => image.Id).map((image) => image.Id);if (imageIdsToCheck.length === 0) {toast.info('No images to check for updates.');@@ -307,14 +302,13 @@}const stats = batchResult.stats || { total: 0, success: 0, failed: 0 };- const numSuccessfullyUpdated = stats.success || 0; // Images for which new data was likely returned+ const numSuccessfullyUpdated = stats.success || 0;const numFailedByBackend = stats.failed || 0;const numAttemptedByBackend = stats.total || numSuccessfullyUpdated + numFailedByBackend;console.log(`Backend Response: Attempted to process ${numAttemptedByBackend}, Succeeded (updated) ${numSuccessfullyUpdated}, Failed ${numFailedByBackend}.`);if (batchResult.success) {- // Overall API call was successfulif (numSuccessfullyUpdated > 0) {toast.success(`Successfully retrieved updates for ${numSuccessfullyUpdated} image(s).`);}@@ -326,7 +320,6 @@const notAttemptedCount = imageIdsToCheck.length - numAttemptedByBackend;toast.info(`Server processed ${numAttemptedByBackend} of ${imageIdsToCheck.length} images. ${notAttemptedCount} were not processed by the backend.`);} else if (numAttemptedByBackend > numSuccessfullyUpdated + numFailedByBackend) {- // This case implies some images were "attempted" but neither succeeded in update nor explicitly failed.const processedWithoutUpdate = numAttemptedByBackend - (numSuccessfullyUpdated + numFailedByBackend);if (processedWithoutUpdate > 0) {toast.info(`${processedWithoutUpdate} image(s) were checked by the backend but had no new update status reported.`);@@ -337,11 +330,8 @@toast.info('Maturity check ran, but the backend reported no images were processed or updated.');}- // Always invalidate if the API call itself was successful,- // as some images might have been updated.await invalidateAll();} else {- // The API call itself failed (e.g., HTTP 500, or batchResult.success is false)toast.error(`Maturity check request failed: ${batchResult.error || 'Unknown server error.'}`);}} catch (error) {@@ -355,7 +345,6 @@let observer: IntersectionObserver | null = null;onMount(() => {- // Lazily load maturity data for visible rowsobserver = new IntersectionObserver((entries) => {entries.forEach((entry) => {@@ -513,11 +502,11 @@{ accessorKey: 'repo', header: 'Name' },{ accessorKey: 'inUse', header: ' ', enableSorting: false },{ accessorKey: 'tag', header: 'Tag' },- { accessorKey: 'id', header: 'Image ID', enableSorting: false },- { accessorKey: 'size', header: 'Size' },+ { accessorKey: 'Id', header: 'Image ID', enableSorting: false },+ { accessorKey: 'Size', header: 'Size' },{ accessorKey: 'actions', header: ' ', enableSorting: false }]}- idKey="id"+ idKey="Id"display={{filterPlaceholder: 'Search images...',noResultsMessage: 'No images found'@@ -528,11 +517,11 @@bind:selectedIds>{#snippet rows({ item })}- <Table.Cell data-image-id={item.id}>+ <Table.Cell data-image-id={item.Id}><div class="flex items-center gap-2"><div class="flex items-center flex-1"><MaturityItem maturity={item.maturity} />- <a class="font-medium hover:underline shrink truncate" href="/images/{item.id}/">+ <a class="font-medium hover:underline shrink truncate" href="/images/{item.Id}/">{item.repo}</a></div>@@ -546,8 +535,8 @@{/if}</Table.Cell><Table.Cell>{item.tag}</Table.Cell>- <Table.Cell class="truncate">{item.id}</Table.Cell>- <Table.Cell>{formatBytes(item.size)}</Table.Cell>+ <Table.Cell class="truncate">{item.Id}</Table.Cell>+ <Table.Cell>{formatBytes(item.Size)}</Table.Cell><Table.Cell><DropdownMenu.Root><DropdownMenu.Trigger>@@ -560,11 +549,11 @@</DropdownMenu.Trigger><DropdownMenu.Content align="end"><DropdownMenu.Group>- <DropdownMenu.Item onclick={() => goto(`/images/${item.id}`)}>+ <DropdownMenu.Item onclick={() => goto(`/images/${item.Id}`)}><ScanSearch class="size-4" />Inspect</DropdownMenu.Item>- <DropdownMenu.Item onclick={() => pullImageByRepoTag(item.repoTags?.[0])} disabled={isLoading.pulling || !item.repoTags?.[0]}>+ <DropdownMenu.Item onclick={() => pullImageByRepoTag(item.RepoTags?.[0])} disabled={isLoading.pulling || !item.RepoTags?.[0]}>{#if isLoading.pulling}<Loader2 class="animate-spin size-4" />Pulling...@@ -573,7 +562,7 @@Pull{/if}</DropdownMenu.Item>- <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleImageRemove(item.id)}>+ <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleImageRemove(item.Id)}><Trash2 class="size-4" />Remove</DropdownMenu.Item>@@ -637,7 +626,6 @@z-index: 1;}- /* Top side: Arrow on bottom of tooltip pointing down */:global(.tooltip-with-arrow[data-side='top']::before) {bottom: -4px;left: 50%;@@ -646,7 +634,6 @@border-left: none;}- /* Bottom side: Arrow on top of tooltip pointing up */:global(.tooltip-with-arrow[data-side='bottom']::before) {top: -4px;left: 50%;@@ -655,7 +642,6 @@border-right: none;}- /* Left side: Arrow on right of tooltip pointing right */:global(.tooltip-with-arrow[data-side='left']::before) {top: 50%;right: -4px;@@ -664,7 +650,6 @@border-bottom: none;}- /* Right side: Arrow on left of tooltip pointing left - improved */:global(.tooltip-with-arrow[data-side='right']::before) {top: 50%;left: -4px;diff --git a/src/routes/networks/+page.server.ts b/src/routes/networks/+page.server.tsindex 514d0e66a..e3f32cbc4 100644--- a/src/routes/networks/+page.server.ts+++ b/src/routes/networks/+page.server.ts@@ -1,26 +1,24 @@import type { PageServerLoad } from './$types';import { listNetworks } from '$lib/services/docker/network-service';-import type { ServiceNetwork } from '$lib/types/docker';+import type { NetworkInspectInfo } from 'dockerode';-// Define the shape of the data returned by the load functiontype NetworkPageData = {- networks: ServiceNetwork[];+ networks: NetworkInspectInfo[];error?: string;};export const load: PageServerLoad = async (): Promise<NetworkPageData> => {try {- // Actually call the function to list networksconst networks = await listNetworks();return {networks};- } catch (err: any) {+ } catch (err: unknown) {console.error('Failed to load networks:', err);- // Return an empty array and the error message+ const message = err instanceof Error ? err.message : 'Failed to connect to Docker or list networks.';return {networks: [],- error: err.message || 'Failed to connect to Docker or list networks.'+ error: message};}};diff --git a/src/routes/networks/+page.svelte b/src/routes/networks/+page.svelteindex 3ea0a2a77..927664117 100644--- a/src/routes/networks/+page.svelte+++ b/src/routes/networks/+page.svelte@@ -10,16 +10,17 @@import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';import CreateNetworkDialog from './CreateNetworkDialog.svelte';import * as Table from '$lib/components/ui/table';- import type { NetworkCreateOptions } from 'dockerode';+ import type { NetworkCreateOptions, NetworkInspectInfo } from 'dockerode';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import { openConfirmDialog } from '$lib/components/confirm-dialog';import NetworkAPIService from '$lib/services/api/network-api-service';+ import { DEFAULT_NETWORK_NAMES } from '$lib/constants';let { data }: { data: PageData } = $props();let networkPageStates = $state({- networks: data.networks,+ networks: data.networks as NetworkInspectInfo[],selectedNetworks: <string[]>[],error: data.error,isCreateDialogOpen: false@@ -34,43 +35,48 @@const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));$effect(() => {- networkPageStates.networks = data.networks;+ networkPageStates.networks = data.networks as NetworkInspectInfo[];networkPageStates.error = data.error;});const totalNetworks = $derived(networkPageStates.networks.length);- const bridgeNetworks = $derived(networkPageStates.networks.filter((n) => n.driver === 'bridge').length);- const overlayNetworks = $derived(networkPageStates.networks.filter((n) => n.driver === 'overlay').length);+ // NetworkInfo uses 'Driver' (capital D)+ const bridgeNetworks = $derived(networkPageStates.networks.filter((n) => n.Driver === 'bridge').length);+ const overlayNetworks = $derived(networkPageStates.networks.filter((n) => n.Driver === 'overlay').length);const networkApi = new NetworkAPIService();async function handleCreateNetworkSubmit(options: NetworkCreateOptions) {handleApiResultWithCallbacks({result: await tryCatch(networkApi.create(options)),- message: 'Failed to Create Network',+ message: `Failed to Create Network "${options.Name}"`,setLoadingState: (value) => (isLoading.create = value),onSuccess: async () => {- toast.success('Network Created Successfully.');+ toast.success(`Network "${options.Name}" Created Successfully.`);await invalidateAll();networkPageStates.isCreateDialogOpen = false;}});}- async function handleDeleteNetwork(id: string) {+ async function handleDeleteNetwork(id: string, name: string) {+ if (DEFAULT_NETWORK_NAMES.has(name)) {+ toast.error(`Cannot delete default network: ${name}`);+ return;+ }openConfirmDialog({title: 'Delete Network',- message: 'Are you sure you want to delete this network? This action cannot be undone.',+ message: `Are you sure you want to delete network "${name}" (ID: ${id.substring(0, 12)})? This action cannot be undone.`,confirm: {label: 'Delete',destructive: true,action: async () => {handleApiResultWithCallbacks({result: await tryCatch(networkApi.remove(encodeURIComponent(id))),- message: 'Failed to Remove Network',+ message: `Failed to Remove Network "${name}"`,setLoadingState: (value) => (isLoading.remove = value),onSuccess: async () => {- toast.success('Network Removed Successfully.');+ toast.success(`Network "${name}" Removed Successfully.`);await invalidateAll();}});@@ -80,21 +86,20 @@}async function handleDeleteSelected() {- // Check if any selected networks are default networks- const selectedNetworks = networkPageStates.selectedNetworks.map((id) => {- const network = networkPageStates.networks.find((n) => n.id === id);+ const selectedNetworkDetails = networkPageStates.selectedNetworks.map((id) => {+ const network = networkPageStates.networks.find((n) => n.Id === id);return {id,- name: network?.name || id.substring(0, 12),- isDefault: network?.driver === 'host' || network?.name === 'bridge' || network?.name === 'none'+ name: network?.Name || id.substring(0, 12),+ isDefault: DEFAULT_NETWORK_NAMES.has(network?.Name || '')};});- const defaultNetworks = selectedNetworks.filter((n) => n.isDefault);+ const defaultNetworksSelected = selectedNetworkDetails.filter((n) => n.isDefault);- if (defaultNetworks.length > 0) {- const names = defaultNetworks.map((n) => n.name).join(', ');- toast.error(`Cannot delete default networks: ${names}`);+ if (defaultNetworksSelected.length > 0) {+ const names = defaultNetworksSelected.map((n) => n.name).join(', ');+ toast.error(`Cannot delete default networks: ${names}. Please deselect them.`);return;}@@ -106,38 +111,43 @@destructive: true,action: async () => {isLoading.remove = true;-let successCount = 0;let failureCount = 0;- for (const network of selectedNetworks) {+ for (const network of selectedNetworkDetails) {+ // Iterate over details which includes nameconst result = await tryCatch(networkApi.remove(encodeURIComponent(network.id)));- handleApiResultWithCallbacks({- result,- message: `Failed to delete network "${network.name}"`,- setLoadingState: (value) => (isLoading.remove = value),- onSuccess: async () => {- toast.success(`Network "${network.name}" deleted successfully.`);- successCount++;- }- });-- if (result.error) {+ // The setLoadingState in a loop like this will just toggle the global remove state+ // For individual item loading, a more complex state management would be needed.+ if (result.data) {+ toast.success(`Network "${network.name}" deleted successfully.`);+ successCount++;+ } else if (result.error) {+ const error = result.error as any;+ toast.error(`Failed to delete network "${network.name}": ${error.message || 'Unknown error'}`);failureCount++;}}+ isLoading.remove = false; // Reset after all operationsconsole.log(`Finished deleting. Success: ${successCount}, Failed: ${failureCount}`);if (successCount > 0) {setTimeout(async () => {await invalidateAll();- }, 500);+ }, 500); // Delay to allow toasts to show before list updates}- networkPageStates.selectedNetworks = [];+ networkPageStates.selectedNetworks = []; // Clear selection}}});}++ function getNetworkSubnet(network: NetworkInspectInfo): string {+ if (network.IPAM && network.IPAM.Config && network.IPAM.Config.length > 0 && network.IPAM.Config[0].Subnet) {+ return network.IPAM.Config[0].Subnet;+ }+ return 'N/A';+ }</script><div class="space-y-6">@@ -146,12 +156,6 @@<h1 class="text-3xl font-bold tracking-tight">Networks</h1><p class="text-sm text-muted-foreground mt-1">View and Manage Container Networking</p></div>- <div class="flex items-center gap-2">- <Button variant="secondary" data-testid="create-network-button" onclick={() => (networkPageStates.isCreateDialogOpen = true)} disabled={isLoading.create}>- <Plus class="size-4" />- Create Network- </Button>- </div></div>{#if networkPageStates.error}@@ -214,10 +218,14 @@Processing...{:else}<Trash2 class="size-4" />- Delete Selected+ Delete Selected ({networkPageStates.selectedNetworks.length}){/if}</Button>{/if}+ <Button variant="secondary" data-testid="create-network-button" onclick={() => (networkPageStates.isCreateDialogOpen = true)} disabled={isLoading.create}>+ <Plus class="size-4" />+ Create Network+ </Button></div></div></Card.Header>@@ -226,28 +234,28 @@<UniversalTabledata={networkPageStates.networks}columns={[- { accessorKey: 'name', header: 'Name' },- { accessorKey: 'driver', header: 'Driver' },- { accessorKey: 'scope', header: 'Scope' },- { accessorKey: 'subnet', header: 'Subnet' },+ { accessorKey: 'Name', header: 'Name' },+ { accessorKey: 'Driver', header: 'Driver' },+ { accessorKey: 'Scope', header: 'Scope' },+ { accessorFn: (row) => getNetworkSubnet(row), header: 'Subnet', id: 'subnet' },{ accessorKey: 'actions', header: ' ', enableSorting: false }]}- idKey="id"+ idKey="Id"display={{filterPlaceholder: 'Search networks...',noResultsMessage: 'No networks found'}}sort={{- defaultSort: { id: 'name', desc: false }+ defaultSort: { id: 'Name', desc: false }}}bind:selectedIds={networkPageStates.selectedNetworks}>- {#snippet rows({ item })}- {@const isDefaultNetwork = item.driver === 'host' || item.name === 'bridge' || item.name === 'none'}- <Table.Cell><a class="font-medium hover:underline" href="/networks/{item.id}/">{item.name}</a></Table.Cell>- <Table.Cell>{item.driver}</Table.Cell>- <Table.Cell>{item.scope}</Table.Cell>- <Table.Cell>{item.subnet}</Table.Cell>+ {#snippet rows({ item }: { item: NetworkInspectInfo })}+ {@const isDefaultNetwork = DEFAULT_NETWORK_NAMES.has(item.Name)}+ <Table.Cell><a class="font-medium hover:underline" href="/networks/{encodeURIComponent(item.Id)}/">{item.Name}</a></Table.Cell>+ <Table.Cell>{item.Driver}</Table.Cell>+ <Table.Cell>{item.Scope}</Table.Cell>+ <Table.Cell>{getNetworkSubnet(item)}</Table.Cell><Table.Cell><DropdownMenu.Root><DropdownMenu.Trigger>@@ -260,15 +268,14 @@</DropdownMenu.Trigger><DropdownMenu.Content align="end"><DropdownMenu.Group>- <DropdownMenu.Item onclick={() => goto(`/networks/${item.id}`)} disabled={isAnyLoading}>+ <DropdownMenu.Item onclick={() => goto(`/networks/${encodeURIComponent(item.Id)}`)} disabled={isAnyLoading}><ScanSearch class="size-4" />Inspect</DropdownMenu.Item>{#if !isDefaultNetwork}<DropdownMenu.Separator />-- <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleDeleteNetwork(item.id)} disabled={isLoading.remove || isAnyLoading}>- {#if isLoading.remove}+ <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleDeleteNetwork(item.Id, item.Name)} disabled={isLoading.remove || isAnyLoading}>+ {#if isLoading.remove && networkPageStates.selectedNetworks.includes(item.Id)}<Loader2 class="animate-spin size-4" />{:else}<Trash2 class="size-4" />diff --git a/src/routes/stacks/[stackId]/+page.server.ts b/src/routes/stacks/[stackId]/+page.server.tsindex 2006abf04..ff9423b6f 100644--- a/src/routes/stacks/[stackId]/+page.server.ts+++ b/src/routes/stacks/[stackId]/+page.server.ts@@ -3,7 +3,7 @@ import { getSettings } from '$lib/services/settings-service';import { getContainer } from '$lib/services/docker/container-service';import type { PageServerLoad, Actions } from './$types';import { tryCatch } from '$lib/utils/try-catch';-import type { PortBinding } from 'dockerode';+import type { PortBinding, ContainerInspectInfo } from 'dockerode';export const load: PageServerLoad = async ({ params }) => {const { stackId } = params;@@ -45,13 +45,15 @@ export const load: PageServerLoad = async ({ params }) => {for (const service of stack.services) {if (service.id) {const containerResult = await tryCatch(getContainer(service.id));- if (!containerResult.error && containerResult.data && containerResult.data.networkSettings?.Ports) {- const portBindings = containerResult.data.networkSettings.Ports;+ const containerData: ContainerInspectInfo | null = containerResult.data;++ if (!containerResult.error && containerData && containerData.NetworkSettings?.Ports) {+ const portBindings = containerData.NetworkSettings.Ports;const parsedPorts: string[] = [];for (const containerPort in portBindings) {if (Object.prototype.hasOwnProperty.call(portBindings, containerPort)) {- const bindings = portBindings[containerPort];+ const bindings: PortBinding[] | null = portBindings[containerPort];if (bindings && Array.isArray(bindings) && bindings.length > 0) {bindings.forEach((binding: PortBinding) => {if (binding.HostPort) {diff --git a/src/routes/volumes/+page.server.ts b/src/routes/volumes/+page.server.tsindex 88dfcf5e3..6991a3ae1 100644--- a/src/routes/volumes/+page.server.ts+++ b/src/routes/volumes/+page.server.ts@@ -1,9 +1,8 @@import type { PageServerLoad } from './$types';import { listVolumes, isVolumeInUse } from '$lib/services/docker/volume-service';-import type { ServiceVolume } from '$lib/types/docker';+import type { VolumeInspectInfo } from 'dockerode';-// Enhanced type with usage info-type EnhancedVolumeInfo = ServiceVolume & {+type EnhancedVolumeInfo = VolumeInspectInfo & {inUse: boolean;};@@ -14,11 +13,11 @@ type VolumePageData = {export const load: PageServerLoad = async (): Promise<VolumePageData> => {try {- const volumes = await listVolumes();+ const volumesData = await listVolumes();const enhancedVolumes = await Promise.all(- volumes.map(async (volume): Promise<EnhancedVolumeInfo> => {- const inUse = await isVolumeInUse(volume.name);+ volumesData.map(async (volume): Promise<EnhancedVolumeInfo> => {+ const inUse = await isVolumeInUse(volume.Name);return {...volume,inUsediff --git a/src/routes/volumes/+page.svelte b/src/routes/volumes/+page.svelteindex 304a7c9c9..1a98953cc 100644--- a/src/routes/volumes/+page.svelte+++ b/src/routes/volumes/+page.svelte@@ -15,7 +15,7 @@import { tryCatch } from '$lib/utils/try-catch';import VolumeAPIService from '$lib/services/api/volume-api-service';import StatusBadge from '$lib/components/badges/status-badge.svelte';- import type { VolumeCreateOptions } from 'dockerode';+ import type { VolumeCreateOptions, VolumeInspectInfo } from 'dockerode';let { data }: { data: PageData } = $props();@@ -46,17 +46,17 @@async function handleRemoveVolumeConfirm(volumeName: string) {openConfirmDialog({title: 'Delete Volume',- message: 'Are you sure you want to delete this volume? This action cannot be undone.',+ message: `Are you sure you want to delete volume "${volumeName}"? This action cannot be undone.`,confirm: {label: 'Delete',destructive: true,action: async () => {handleApiResultWithCallbacks({result: await tryCatch(volumeApi.remove(volumeName)),- message: 'Failed to Remove Volume',+ message: `Failed to Remove Volume "${volumeName}"`,setLoadingState: (value) => (isLoading.remove = value),onSuccess: async () => {- toast.success('Volume Removed Successfully.');+ toast.success(`Volume "${volumeName}" Removed Successfully.`);await invalidateAll();}});@@ -73,6 +73,7 @@onSuccess: async () => {toast.success(`Volume "${volumeCreate.Name}" created successfully.`);await invalidateAll();+ isDialogOpen.create = false;}});}@@ -80,8 +81,7 @@async function handleDeleteSelected() {openConfirmDialog({title: 'Delete Selected Volumes',- message: `Are you sure you want to delete ${volumePageStates.selectedIds.length} selected images? This action cannot be undone. Images currently used by containers will not be deleted.-`,+ message: `Are you sure you want to delete ${volumePageStates.selectedIds.length} selected volume(s)? This action cannot be undone. Volumes currently used by containers will not be deleted.`,confirm: {label: 'Delete',destructive: true,@@ -92,22 +92,22 @@let failureCount = 0;for (const name of volumePageStates.selectedIds) {- const volume = volumePageStates.volumes?.find((v) => v.name === name);+ const volume = volumePageStates.volumes?.find((v) => v.Name === name);if (volume?.inUse) {- toast.error(`Volume "${volume.name}" is in use and cannot be deleted.`);+ toast.error(`Volume "${volume.Name}" is in use and cannot be deleted.`);failureCount++;continue;}- if (!volume?.name) continue;- const result = await tryCatch(volumeApi.remove(volume.name));+ if (!volume?.Name) continue;+ const result = await tryCatch(volumeApi.remove(volume.Name));handleApiResultWithCallbacks({result,- message: `Failed to delete image "${volume.name}"`,+ message: `Failed to delete volume "${volume.Name}"`,setLoadingState: (value) => (isLoading.remove = value),onSuccess: async () => {- toast.success(`Volume "${volume.name}" deleted successfully.`);+ toast.success(`Volume "${volume.Name}" deleted successfully.`);successCount++;}});@@ -116,6 +116,7 @@failureCount++;}}+ isLoading.remove = false;console.log(`Finished deleting. Success: ${successCount}, Failed: ${failureCount}`);if (successCount > 0) {@@ -167,7 +168,7 @@<Card.Root><Card.Content class="p-4 flex items-center justify-between"><div>- <p class="text-sm font-medium text-muted-foreground">Driver</p>+ <p class="text-sm font-medium text-muted-foreground">Default Driver</p><p class="text-2xl font-bold">local</p></div><div class="bg-blue-500/10 p-2 rounded-full">@@ -199,7 +200,7 @@<DropdownMenu.CheckboxItemchecked={volumePageStates.showUsed}onCheckedChange={(checked) => {- volumePageStates.showUsed = checked;+ volumePageStates.showUsed = !!checked;}}>Show Used Volumes@@ -207,7 +208,7 @@<DropdownMenu.CheckboxItemchecked={volumePageStates.showUnused}onCheckedChange={(checked) => {- volumePageStates.showUnused = checked;+ volumePageStates.showUnused = !!checked;}}>Show Unused Volumes@@ -221,7 +222,7 @@Processing...{:else}<Trash2 class="size-4" />- Delete Selected+ Delete Selected ({volumePageStates.selectedIds.length}){/if}</Button>{/if}@@ -236,33 +237,33 @@{#if volumePageStates.volumes && volumePageStates.volumes.length > 0}<UniversalTabledata={filteredVolumes}- idKey="name"+ idKey="Name"columns={[- { accessorKey: 'name', header: 'Name' },+ { accessorKey: 'Name', header: 'Name' },{ accessorKey: 'inUse', header: ' ', enableSorting: false },- { accessorKey: 'mountpoint', header: 'Mountpoint' },- { accessorKey: 'driver', header: 'Driver' },+ { accessorKey: 'Mountpoint', header: 'Mountpoint' },+ { accessorKey: 'Driver', header: 'Driver' },{ accessorKey: 'actions', header: ' ', enableSorting: false }]}display={{filterPlaceholder: 'Search volumes...',- noResultsMessage: 'No volumes found'+ noResultsMessage: 'No volumes found matching your filters.'}}bind:selectedIds={volumePageStates.selectedIds}>- {#snippet rows({ item })}+ {#snippet rows({ item }: { item: PageData['volumes'][0] })}<Table.Cell><div class="flex items-center gap-2"><span class="truncate">- <a class="font-medium hover:underline" href="/volumes/{item.name}/">{item.name}</a>+ <a class="font-medium hover:underline" href="/volumes/{encodeURIComponent(item.Name)}/">{item.Name}</a></span></div></Table.Cell><Table.Cell><StatusBadge text={item.inUse ? 'In Use' : 'Unused'} variant={item.inUse ? 'green' : 'amber'} /></Table.Cell>- <Table.Cell>{item.mountpoint}</Table.Cell>- <Table.Cell>{item.driver}</Table.Cell>+ <Table.Cell>{item.Mountpoint}</Table.Cell>+ <Table.Cell>{item.Driver}</Table.Cell><Table.Cell><DropdownMenu.Root><DropdownMenu.Trigger>@@ -275,15 +276,15 @@</DropdownMenu.Trigger><DropdownMenu.Content align="end"><DropdownMenu.Group>- <DropdownMenu.Item onclick={() => goto(`/volumes/${encodeURIComponent(item.name)}`)} disabled={isLoading.remove}>+ <DropdownMenu.Item onclick={() => goto(`/volumes/${encodeURIComponent(item.Name)}`)} disabled={isLoading.remove}><ScanSearch class="size-4" />Inspect</DropdownMenu.Item><DropdownMenu.Separator />- <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleRemoveVolumeConfirm(item.name)} disabled={isLoading.remove}>- {#if isLoading.remove}+ <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleRemoveVolumeConfirm(item.Name)} disabled={isLoading.remove || item.inUse}>+ {#if isLoading.remove && volumePageStates.selectedIds.includes(item.Name)}<Loader2 class="animate-spin size-4" />{:else}<Trash2 class="size-4" />