Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: image maturity indicator and image update indicators (#181)
Kyle Mendell2eff0689efec
diff --git a/src/hooks.server.ts b/src/hooks.server.tsindex 5e24718e2..9c284b43c 100644--- a/src/hooks.server.ts+++ b/src/hooks.server.ts@@ -6,13 +6,14 @@ import { getUserByUsername } from '$lib/services/user-service';import { getSettings } from '$lib/services/settings-service';import { checkFirstRun } from '$lib/utils/onboarding.utils';import { sessionHandler } from '$lib/services/session-handler';+import { initMaturityPollingScheduler } from '$lib/services/docker/image-service';// Get environment variableconst isTestEnvironment = process.env.APP_ENV === 'TEST';// Initialize needed servicestry {- await Promise.all([checkFirstRun(), initComposeService(), initAutoUpdateScheduler()]);+ await Promise.all([checkFirstRun(), initComposeService(), initAutoUpdateScheduler(), initMaturityPollingScheduler()]);} catch (err) {console.error('Critical service init failed, exiting:', err);process.exit(1);diff --git a/src/lib/components/form/form-input.svelte b/src/lib/components/form/form-input.sveltenew file mode 100644index 000000000..95a575e0e--- /dev/null+++ b/src/lib/components/form/form-input.svelte@@ -0,0 +1,60 @@+<!-- Originally From https://github.com/pocket-id/pocket-id/blob/main/frontend/src/lib/components/form/form-input.svelte -->+<script lang="ts">+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import type { Snippet } from 'svelte';+ import type { HTMLAttributes } from 'svelte/elements';+ import type { FormInput } from '$lib/types/form.type';++ let {+ input = $bindable(),+ label,+ description,+ helpText,+ warningText,+ placeholder,+ disabled = false,+ required = false,+ type = 'text',+ children,+ ...restProps+ }: HTMLAttributes<HTMLDivElement> & {+ input?: FormInput<string | boolean | number | Date | undefined>;+ label?: string;+ description?: string;+ helpText?: string;+ warningText?: string;+ placeholder?: string;+ disabled?: boolean;+ required?: boolean;+ type?: 'text' | 'password' | 'email' | 'number' | 'checkbox' | 'date';+ children?: Snippet;+ } = $props();++ const id = label?.toLowerCase().replace(/ /g, '-');+</script>++<div {...restProps}>+ {#if label}+ <Label class="mb-0" for={id}>{label}</Label>+ {/if}+ {#if description}+ <p class="text-muted-foreground mt-1 text-xs">{description}</p>+ {/if}+ <div class={label || description ? 'mt-2' : ''}>+ {#if children}+ {@render children()}+ {:else if input}+ <Input {id} {placeholder} {type} bind:value={input.value} {disabled} required />+ {/if}+ {#if input?.error}+ <p class="mt-1 text-sm text-red-500">{input.error}</p>+ {/if}+ {#if helpText}+ <p class="mt-1 text-xs text-muted-foreground">{helpText}</p>+ {/if}+ {#if warningText}+ <p class="mt-1 text-xs font-bold text-destructive">{warningText}</p>+ {/if}+ </div>+</div>diff --git a/src/lib/components/ui/tooltip/index.ts b/src/lib/components/ui/tooltip/index.tsnew file mode 100644index 000000000..e9e1fd739--- /dev/null+++ b/src/lib/components/ui/tooltip/index.ts@@ -0,0 +1,18 @@+import { Tooltip as TooltipPrimitive } from "bits-ui";+import Content from "./tooltip-content.svelte";++const Root = TooltipPrimitive.Root;+const Trigger = TooltipPrimitive.Trigger;+const Provider = TooltipPrimitive.Provider;++export {+ Root,+ Trigger,+ Content,+ Provider,+ //+ Root as Tooltip,+ Content as TooltipContent,+ Trigger as TooltipTrigger,+ Provider as TooltipProvider,+};diff --git a/src/lib/components/ui/tooltip/tooltip-content.svelte b/src/lib/components/ui/tooltip/tooltip-content.sveltenew file mode 100644index 000000000..68ff232ba--- /dev/null+++ b/src/lib/components/ui/tooltip/tooltip-content.svelte@@ -0,0 +1,21 @@+<script lang="ts">+ import { Tooltip as TooltipPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ sideOffset = 4,+ ...restProps+ }: TooltipPrimitive.ContentProps = $props();+</script>++<TooltipPrimitive.Content+ bind:ref+ {sideOffset}+ class={cn(+ "bg-popover text-popover-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 overflow-hidden rounded-md border px-3 py-1.5 text-sm shadow-md",+ className+ )}+ {...restProps}+/>diff --git a/src/lib/services/api/image-api-service.ts b/src/lib/services/api/image-api-service.tsindex cd6b81280..d449a9c47 100644--- a/src/lib/services/api/image-api-service.ts+++ b/src/lib/services/api/image-api-service.ts@@ -17,6 +17,24 @@ export default class ImageAPIService extends BaseAPIService {return res.data;}+ async checkMaturity(id: string) {+ // Change from POST to GET+ const res = await this.api.get(`/images/${id}/maturity`);+ return res.data;+ }++ async checkMaturityBatch(imageIds: string[]) {+ // Use the first image ID for the endpoint URL+ // This is a bit unusual, but following your requirement+ if (!imageIds || imageIds.length === 0) {+ throw new Error('No image IDs provided for batch check');+ }++ const firstId = imageIds[0];+ const res = await this.api.post(`/images/${firstId}/maturity`, { imageIds });+ return res.data;+ }+async list() {const res = await this.api.get('');return res.data;diff --git a/src/lib/services/docker/image-service.ts b/src/lib/services/docker/image-service.tsindex 43e9e5f55..4a28579fa 100644--- a/src/lib/services/docker/image-service.ts+++ b/src/lib/services/docker/image-service.ts@@ -1,8 +1,100 @@import { getDockerClient, dockerHost } from './core';import type { ServiceImage } from '$lib/types/docker/image.type';import type Docker from 'dockerode';-// Import custom errors-import { NotFoundError, ConflictError, DockerApiError } from '$lib/types/errors';+import { NotFoundError, DockerApiError, RegistryRateLimitError, PublicRegistryError, PrivateRegistryError, ApiErrorCode } from '$lib/types/errors.type';+import { parseImageNameForRegistry, areRegistriesEquivalent } from '$lib/utils/registry.utils';+import { getSettings } from '$lib/services/settings-service';+import { updateImageMaturity } from '$lib/stores/maturity-store';+import { tryCatch } from '$lib/utils/try-catch';+let maturityPollingInterval: NodeJS.Timeout | null = null;++/**+ * Starts the maturity polling scheduler based on user settings+ */+export async function initMaturityPollingScheduler(): Promise<void> {+ const settings = await getSettings();++ // Clear any existing timer+ if (maturityPollingInterval) {+ clearInterval(maturityPollingInterval);+ maturityPollingInterval = null;+ }++ // If polling is disabled, do nothing+ if (!settings.pollingEnabled) {+ console.log('Image maturity polling is disabled in settings');+ return;+ }++ // Use the configured polling interval (default to 10 minutes if not set)+ const intervalMinutes = settings.pollingInterval || 10;+ const intervalMs = intervalMinutes * 60 * 1000;++ console.log(`Starting image maturity polling with interval of ${intervalMinutes} minutes`);++ // Schedule regular checks+ maturityPollingInterval = setInterval(runMaturityChecks, intervalMs);+}++/**+ * Stops the maturity polling scheduler+ */+export async function stopMaturityPollingScheduler(): Promise<void> {+ if (maturityPollingInterval) {+ clearInterval(maturityPollingInterval);+ maturityPollingInterval = null;+ console.log('Image maturity polling scheduler stopped');+ }+}++/**+ * Run maturity checks for all images+ */+async function runMaturityChecks(): Promise<void> {+ console.log('Running scheduled image maturity checks...');++ const imagesResult = await tryCatch(listImages());+ if (imagesResult.error) {+ console.error('Error during scheduled maturity check:', imagesResult.error);+ return;+ }++ const images = imagesResult.data;+ let checkedCount = 0;+ let updatesFound = 0;++ // Check each image for maturity info, with a small delay between checks+ for (const image of images) {+ // Skip images without proper tags+ if (image.repo === '<none>' || image.tag === '<none>') {+ continue;+ }++ const maturityResult = await tryCatch(checkImageMaturity(image.id));+ const maturityInfo = maturityResult.data;++ if (!maturityResult.error) {+ checkedCount++;+ if (maturityInfo?.updatesAvailable) {+ updatesFound++;+ }+ }++ // Small delay to avoid overwhelming registries+ await new Promise((resolve) => setTimeout(resolve, 200));+ }++ console.log(`Maturity check completed: Checked ${checkedCount} images, found ${updatesFound} updates`);++ // Emit an event that the UI can listen to for updates+ if (typeof window !== 'undefined') {+ window.dispatchEvent(+ new CustomEvent('maturity-check-complete', {+ detail: { checkedCount, updatesFound }+ })+ );+ }+}/*** The function `listImages` retrieves a list of Docker images and parses their information into a@@ -13,44 +105,50 @@ import { NotFoundError, ConflictError, DockerApiError } from '$lib/types/errors'* from the Docker client and processed using the `parseRepoTag` function*/export async function listImages(): Promise<ServiceImage[]> {- try {- const docker = await getDockerClient();- const images = await docker.listImages({ all: false });+ const dockerClientResult = await tryCatch(getDockerClient());+ if (dockerClientResult.error) {+ throw new Error(`Failed to list Docker images using host "${dockerHost}".`);+ }- const parseRepoTag = (tag: string | undefined): { repo: string; tag: string } => {- if (!tag || tag === '<none>:<none>') {- return { repo: '<none>', tag: '<none>' };- }- const withoutDigest = tag.split('@')[0];- const lastSlash = withoutDigest.lastIndexOf('/');- const lastColon = withoutDigest.lastIndexOf(':');- if (lastColon === -1 || lastColon < lastSlash) {- return { repo: withoutDigest, tag: 'latest' };- }- return {- repo: withoutDigest.substring(0, lastColon),- tag: withoutDigest.substring(lastColon + 1)- };- };+ const docker = dockerClientResult.data;+ const imagesResult = await tryCatch(docker.listImages({ all: false }));- return images.map((img): ServiceImage => {- const { repo, tag } = parseRepoTag(img.RepoTags?.[0]);- return {- id: img.Id,- repoTags: img.RepoTags,- repoDigests: img.RepoDigests,- created: img.Created,- size: img.Size,- virtualSize: img.VirtualSize,- labels: img.Labels,- repo: repo,- tag: tag- };- });- } catch (error: any) {- console.error('Docker Service: Error listing images:', error);+ if (imagesResult.error) {throw new Error(`Failed to list Docker images using host "${dockerHost}".`);}++ const images = imagesResult.data;++ const parseRepoTag = (tag: string | undefined): { repo: string; tag: string } => {+ if (!tag || tag === '<none>:<none>') {+ return { repo: '<none>', tag: '<none>' };+ }+ const withoutDigest = tag.split('@')[0];+ const lastSlash = withoutDigest.lastIndexOf('/');+ const lastColon = withoutDigest.lastIndexOf(':');+ if (lastColon === -1 || lastColon < lastSlash) {+ return { repo: withoutDigest, tag: 'latest' };+ }+ return {+ repo: withoutDigest.substring(0, lastColon),+ tag: withoutDigest.substring(lastColon + 1)+ };+ };++ return images.map((img): ServiceImage => {+ const { repo, tag } = parseRepoTag(img.RepoTags?.[0]);+ return {+ id: img.Id,+ repoTags: img.RepoTags,+ repoDigests: img.RepoDigests,+ created: img.Created,+ size: img.Size,+ virtualSize: img.VirtualSize,+ labels: img.Labels,+ repo: repo,+ tag: tag+ };+ });}/**@@ -61,19 +159,24 @@ export async function listImages(): Promise<ServiceImage[]> {* @throws {DockerApiError} For other errors during the Docker API interaction.*/export async function getImage(imageId: string): Promise<Docker.ImageInspectInfo> {- try {- const docker = await getDockerClient();- const image = docker.getImage(imageId);- const inspectInfo = await image.inspect();- console.log(`Docker Service: Inspected image "${imageId}" successfully.`);- return inspectInfo;- } catch (error: any) {- console.error(`Docker Service: Error inspecting image "${imageId}":`, error);+ const dockerResult = await tryCatch(getDockerClient());+ if (dockerResult.error) {+ throw new DockerApiError(`Failed to get Docker client: ${dockerResult.error.message}`, 500);+ }++ const docker = dockerResult.data;+ const image = docker.getImage(imageId);++ const inspectResult = await tryCatch(image.inspect());+ if (inspectResult.error) {+ const error = inspectResult.error as any;if (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);}++ return inspectResult.data;}/**@@ -91,9 +194,7 @@ export async function removeImage(imageId: string, force: boolean = false): Promconst docker = await getDockerClient();const image = docker.getImage(imageId);await image.remove({ force });- console.log(`Docker Service: Image "${imageId}" removed successfully.`);} catch (error: any) {- console.error(`Docker Service: Error removing image "${imageId}":`, error);if (error.statusCode === 409) {throw new Error(`Image "${imageId}" is being used by a container. Use force option to remove.`);}@@ -118,7 +219,6 @@ export async function isImageInUse(imageId: string): Promise<boolean> {// Look for containers using this imagereturn containers.some((container) => container.ImageID === imageId || container.Image === imageId);} catch (error) {- console.error(`Error checking if image ${imageId} is in use:`, error);// Default to assuming it's in use for safetyreturn true;}@@ -140,20 +240,14 @@ export async function pruneImages(mode: 'all' | 'dangling' = 'all'): Promise<{try {const docker = await getDockerClient();const filterValue = mode === 'all' ? 'false' : 'true';- const logMessage = mode === 'all' ? 'Pruning all unused images (docker image prune -a)...' : 'Pruning dangling images (docker image prune)...';-- console.log(`Docker Service: ${logMessage}`);const pruneOptions = {filters: { dangling: [filterValue] }};const result = await docker.pruneImages(pruneOptions); // Use the options object-- console.log(`Docker Service: Image prune complete. Space reclaimed: ${result.SpaceReclaimed}`);return result;} catch (error: any) {- console.error('Docker Service: Error pruning images:', error);throw new Error(`Failed to prune images using host "${dockerHost}". ${error.message || error.reason || ''}`);}}@@ -182,3 +276,616 @@ export async function pullImage(imageRef: string, platform?: string, authConfig?await docker.pull(imageRef, pullOptions);}++/**+ * Checks if a newer version of an image is available in the registry+ * and returns maturity information.+ */+export async function checkImageMaturity(imageId: string): Promise<import('$lib/types/docker/image.type').ImageMaturity | undefined> {+ const imageResult = await tryCatch(getImage(imageId));+ if (imageResult.error) {+ console.warn(`checkImageMaturity: Failed to get image details for ${imageId}:`, imageResult.error);+ updateImageMaturity(imageId, undefined); // Ensure store is cleared if image details fail+ return undefined;+ }++ const imageDetails = imageResult.data;+ const repoTag = imageDetails.RepoTags?.[0];++ if (!repoTag || repoTag.includes('<none>')) {+ updateImageMaturity(imageId, undefined);+ return undefined;+ }++ const lastColon = repoTag.lastIndexOf(':');+ if (lastColon === -1) {+ updateImageMaturity(imageId, undefined);+ return undefined;+ }++ const repository = repoTag.substring(0, lastColon);+ const currentTag = repoTag.substring(lastColon + 1);++ let localCreatedDate: Date | undefined = undefined;+ if (imageDetails.Created) {+ // Directly parse the ISO 8601 date string+ const parsedDate = new Date(imageDetails.Created);+ if (!isNaN(parsedDate.getTime())) {+ localCreatedDate = parsedDate;+ } else {+ console.warn(`checkImageMaturity: Invalid Created date string for image ${imageId}: ${imageDetails.Created}`);+ }+ }++ const registryInfoResult = await tryCatch(getRegistryInfo(repository, currentTag, localCreatedDate));+ if (registryInfoResult.error) {+ if (registryInfoResult.error instanceof RegistryRateLimitError) {+ console.warn(`Registry rate limit hit for ${repository}:${currentTag}: ${registryInfoResult.error.message}`);+ } else if (registryInfoResult.error instanceof PublicRegistryError || registryInfoResult.error instanceof PrivateRegistryError) {+ console.warn(`Registry access error for ${repository}:${currentTag}: ${registryInfoResult.error.message}`);+ } else {+ console.error(`Error getting registry info for ${repository}:${currentTag}:`, registryInfoResult.error);+ }+ updateImageMaturity(imageId, undefined); // Clear maturity on error+ return undefined;+ }++ const registryInfo = registryInfoResult.data;++ updateImageMaturity(imageId, registryInfo);+ return registryInfo;+}++/**+ * Contacts the Docker registry to get latest version information+ */+async function getRegistryInfo(repository: string, currentTag: string, localCreatedDate?: Date): Promise<import('$lib/types/docker/image.type').ImageMaturity | undefined> {+ try {+ const { registry: registryDomain } = parseImageNameForRegistry(repository);++ // Attempt 1: Try public registry first+ try {+ const publicMaturityInfo = await checkPublicRegistry(repository, registryDomain, currentTag, localCreatedDate);+ if (publicMaturityInfo) {+ return publicMaturityInfo;+ }+ } catch (error: any) {+ if (error instanceof RegistryRateLimitError) {+ // If public check hits a rate limit, re-throw immediately.+ // It's unlikely trying private credentials for the same domain will bypass this.+ throw error;+ }+ // For other PublicRegistryErrors (e.g., 401/403 on a public endpoint for a private image),+ // or other general errors, log and proceed to try private credentials.+ console.warn(`Public registry check failed for ${repository}:${currentTag} (will try private if configured): ${error.message}`);+ }++ // Attempt 2: Try private registries if configured+ const settings = await getSettings();+ if (settings.registryCredentials && settings.registryCredentials.length > 0) {+ // Filter all credentials that match the current registry domain+ const matchingCredentials = settings.registryCredentials.filter((cred) => areRegistriesEquivalent(cred.url, registryDomain));++ if (matchingCredentials.length > 0) {+ console.log(`Found ${matchingCredentials.length} potential private credential(s) for domain ${registryDomain} for image ${repository}:${currentTag}.`);+ }++ for (const credential of matchingCredentials) {+ try {+ console.log(`Attempting private registry check for ${repository}:${currentTag} using credential for URL: ${credential.url}`);+ const privateMaturityInfo = await checkPrivateRegistry(repository, registryDomain, currentTag, credential, localCreatedDate);+ if (privateMaturityInfo) {+ // If a check with a credential succeeds, return the info+ return privateMaturityInfo;+ }+ // If privateMaturityInfo is undefined but no error, it means the check was "successful"+ // but no maturity info was determined (e.g. image/tag not found with these creds).+ // We should continue to try other credentials if any.+ } catch (error: any) {+ if (error instanceof RegistryRateLimitError) {+ // If a rate limit is hit with any private credential, re-throw.+ console.warn(`Private registry check for ${repository}:${currentTag} hit rate limit with credential for ${credential.url}.`);+ throw error;+ } else if (error instanceof PrivateRegistryError) {+ // Log specific private registry errors (like auth failure for *this* credential)+ // and continue to the next credential.+ console.warn(`Private registry check failed for ${repository}:${currentTag} with credential for ${credential.url}: ${error.message}. Trying next if available.`);+ } else {+ // For other unexpected errors during a specific private check, log and continue.+ console.error(`Unexpected error during private registry check for ${repository}:${currentTag} with credential for ${credential.url}:`, error);+ }+ }+ }+ }+ // If all attempts (public and all matching private credentials) fail to yield maturity info+ return undefined;+ } catch (error) {+ // Catch errors re-thrown from within (like critical RateLimitErrors)+ if (error instanceof RegistryRateLimitError || error instanceof PublicRegistryError || error instanceof PrivateRegistryError) {+ // These are "expected" errors that should have been handled or logged appropriately above,+ // but if they are re-thrown to here, it means we should stop processing for this image.+ // The calling function (checkImageMaturity) will handle this.+ throw error;+ }+ // For other unexpected errors in getRegistryInfo logic itself+ console.error(`Unexpected error in getRegistryInfo for ${repository}:${currentTag}:`, error);+ return undefined;+ }+}++/**+ * Check a public registry using Registry API v2+ */+async function checkPublicRegistry(repository: string, registryDomain: string, currentTag: string, localCreatedDate?: Date): Promise<import('$lib/types/docker/image.type').ImageMaturity | undefined> {+ return checkRegistryV2(repository, registryDomain, currentTag, undefined, localCreatedDate);+}++/**+ * Check a private registry using Registry API v2 with authentication+ */+async function checkPrivateRegistry(repository: string, registryDomain: string, currentTag: string, credentials: { username: string; password: string; url: string }, localCreatedDate?: Date): Promise<import('$lib/types/docker/image.type').ImageMaturity | undefined> {+ const auth = Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64');+ return checkRegistryV2(repository, registryDomain, currentTag, auth, localCreatedDate);+}++/**+ * Helper function to convert ghcr.io to docker.pkg.github.com+ */+function mapGitHubRegistry(domain: string): string {+ return domain === 'ghcr.io' ? 'ghcr.io' : domain;+}++/**+ * Check a registry using the Docker Registry HTTP API v2+ */+async function checkRegistryV2(repository: string, registryDomain: string, currentTag: string, auth?: string, localCreatedDate?: Date): Promise<import('$lib/types/docker/image.type').ImageMaturity | undefined> {+ try {+ const mappedDomain = mapGitHubRegistry(registryDomain);++ const repoPath = repository.replace(`${registryDomain}/`, '');+ const adjustedRepoPath = mappedDomain === 'docker.io' && !repoPath.includes('/') ? `library/${repoPath}` : repoPath;+ const baseUrl = mappedDomain === 'docker.io' ? 'https://registry-1.docker.io' : `https://${mappedDomain}`;+ const tagsUrl = `${baseUrl}/v2/${adjustedRepoPath}/tags/list`;++ const headers: Record<string, string> = {+ Accept: 'application/json'+ };++ if (auth) {+ headers['Authorization'] = `Basic ${auth}`;+ }++ const tagsResponse = await fetch(tagsUrl, { headers });++ if (tagsResponse.status === 401) {+ const authHeader = tagsResponse.headers.get('WWW-Authenticate');+ if (authHeader && authHeader.includes('Bearer')) {+ const realm = authHeader.match(/realm="([^"]+)"/)?.[1];+ const service = authHeader.match(/service="([^"]+)"/)?.[1];+ const scope = authHeader.match(/scope="([^"]+)"/)?.[1];++ if (realm) {+ const tokenUrl = `${realm}?service=${service || ''}&scope=${scope || ''}`;++ const tokenHeaders: Record<string, string> = {};+ if (auth) {+ tokenHeaders['Authorization'] = `Basic ${auth}`;+ }++ const tokenResponse = await fetch(tokenUrl, { headers: tokenHeaders });+ if (!tokenResponse.ok) {+ throw new PublicRegistryError(`Failed to authenticate with registry: ${tokenResponse.status}`, registryDomain, repository, tokenResponse.status);+ }++ const tokenData = await tokenResponse.json();+ const token = tokenData.token || tokenData.access_token;++ if (!token) {+ throw new PublicRegistryError('Registry authentication failed - no token', registryDomain, repository);+ }++ headers['Authorization'] = `Bearer ${token}`;+ const authenticatedResponse = await fetch(tagsUrl, { headers });++ if (!authenticatedResponse.ok) {+ throw new PublicRegistryError(`Registry API returned ${authenticatedResponse.status}`, registryDomain, repository, authenticatedResponse.status);+ }+ const tagsData = await authenticatedResponse.json();+ return processTagsData(tagsData, repository, registryDomain, currentTag, headers, localCreatedDate);+ }+ }+ throw new PublicRegistryError('Registry requires authentication', registryDomain, repository, 401);+ }++ if (!tagsResponse.ok) {+ throw new PublicRegistryError(`Registry API returned ${tagsResponse.status}`, registryDomain, repository, tagsResponse.status);+ }++ const tagsData = await tagsResponse.json();+ return processTagsData(tagsData, repository, registryDomain, currentTag, headers, localCreatedDate);+ } catch (error: any) {+ if (error instanceof PublicRegistryError || error instanceof PrivateRegistryError || error instanceof RegistryRateLimitError) {+ throw error;+ }+ throw new PublicRegistryError(`Registry API error for ${repository}: ${error.message}`, registryDomain, repository);+ }+}++/**+ * Process tags data from the registry API+ */+async function processTagsData(tagsData: any, repository: string, registryDomain: string, currentTag: string, headers: Record<string, string>, localCreatedDate?: Date): Promise<import('$lib/types/docker/image.type').ImageMaturity | undefined> {+ const tags = tagsData.tags || [];+ if (!Array.isArray(tags)) {+ console.warn(`processTagsData: tagsData.tags is not an array for ${repository}. Received:`, tagsData);+ return undefined;+ }+ const { newerTags } = findNewerVersionsOfSameTag(tags, currentTag);++ const settings = await getSettings();+ const maturityThreshold = settings.maturityThresholdDays || 30;++ const createMaturityObject = (version: string, dateSource: Date | { date: string; daysSince: number }, updatesAvailable: boolean): import('$lib/types/docker/image.type').ImageMaturity => {+ let dateString: string;+ let daysSince: number;+ const dateFormatOptions: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'short', day: 'numeric' };++ if (dateSource instanceof Date) {+ if (isNaN(dateSource.getTime())) {+ dateString = 'Invalid date';+ daysSince = -1;+ } else {+ dateString = dateSource.toLocaleDateString(undefined, dateFormatOptions);+ daysSince = getDaysSinceDate(dateSource);+ }+ } else {+ dateString = dateSource.date;+ daysSince = dateSource.daysSince;+ }++ const status: import('$lib/types/docker/image.type').ImageMaturity['status'] = daysSince === -1 || dateString === 'Invalid date' || dateString === 'Unknown date' ? 'Unknown' : daysSince > maturityThreshold ? 'Matured' : 'Not Matured';++ return {+ version,+ date: dateString,+ status,+ updatesAvailable+ };+ };++ if (newerTags.length > 0) {+ const newestTag = newerTags[0];+ try {+ const dateInfoFromRegistry = await getImageCreationDate(repository, registryDomain, newestTag, headers);+ return createMaturityObject(newestTag, dateInfoFromRegistry, true);+ } catch (error) {+ console.error(`Failed to get creation date from registry for newer tag ${repository}:${newestTag}:`, error);+ return createMaturityObject(newestTag, { date: 'Unknown date', daysSince: -1 }, true);+ }+ } else {+ if (localCreatedDate) {+ return createMaturityObject(currentTag, localCreatedDate, false);+ } else {+ try {+ const dateInfoFromRegistry = await getImageCreationDate(repository, registryDomain, currentTag, headers);+ return createMaturityObject(currentTag, dateInfoFromRegistry, false);+ } catch (error) {+ console.error(`Failed to get creation date from registry for current tag ${repository}:${currentTag}:`, error);+ return createMaturityObject(currentTag, { date: 'Unknown date', daysSince: -1 }, false);+ }+ }+ }+}++/**+ * Helper function to get image creation date from registry+ */+async function getImageCreationDate(repository: string, registryDomain: string, tag: string, headers: Record<string, string>): Promise<{ date: string; daysSince: number }> {+ const mappedDomain = mapGitHubRegistry(registryDomain);++ const baseUrl = mappedDomain === 'docker.io' ? 'https://registry-1.docker.io' : `https://${mappedDomain}`;+ const repoPath = repository.replace(`${registryDomain}/`, '');+ const adjustedRepoPath = mappedDomain === 'docker.io' && !repoPath.includes('/') ? `library/${repoPath}` : repoPath;++ const manifestUrl = `${baseUrl}/v2/${adjustedRepoPath}/manifests/${tag}`;++ const manifestResult = await tryCatch(+ fetch(manifestUrl, {+ headers: {+ ...headers,+ Accept: 'application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.oci.image.index.v1+json'+ }+ })+ );++ if (manifestResult.error || !manifestResult.data.ok) {+ if (registryDomain === 'docker.io' || registryDomain === 'registry-1.docker.io') {+ const dockerHubResult = await tryCatch(getDockerHubCreationDate(repoPath, tag));+ if (!dockerHubResult.error) {+ return dockerHubResult.data;+ }+ }++ return {+ date: 'Unknown date',+ daysSince: -1+ };+ }++ const manifestResponse = manifestResult.data;+ const manifestDataResult = await tryCatch(manifestResponse.json());++ if (manifestDataResult.error) {+ return {+ date: 'Unknown date',+ daysSince: -1+ };+ }++ const manifest = manifestDataResult.data;++ if (manifest.annotations && manifest.annotations['org.opencontainers.image.created']) {+ const createdDate = new Date(manifest.annotations['org.opencontainers.image.created']);++ if (!isNaN(createdDate.getTime())) {+ const daysSince = getDaysSinceDate(createdDate);+ const dateFormatOptions: Intl.DateTimeFormatOptions = {+ year: 'numeric',+ month: 'short',+ day: 'numeric'+ };++ return {+ date: createdDate.toLocaleDateString(undefined, dateFormatOptions),+ daysSince: daysSince+ };+ }+ }++ if (manifest.manifests && Array.isArray(manifest.manifests)) {+ for (const descriptor of manifest.manifests) {+ if (descriptor.annotations && descriptor.annotations['org.opencontainers.image.created']) {+ const createdDate = new Date(descriptor.annotations['org.opencontainers.image.created']);++ if (!isNaN(createdDate.getTime())) {+ const daysSince = getDaysSinceDate(createdDate);+ const dateFormatOptions: Intl.DateTimeFormatOptions = {+ year: 'numeric',+ month: 'short',+ day: 'numeric'+ };++ return {+ date: createdDate.toLocaleDateString(undefined, dateFormatOptions),+ daysSince: daysSince+ };+ }+ }+ }+ }++ const configDigest = manifest.config?.digest;++ if (!configDigest) {+ if (registryDomain === 'docker.io' || registryDomain === 'registry-1.docker.io') {+ const dockerHubResult = await tryCatch(getDockerHubCreationDate(repoPath, tag));+ if (!dockerHubResult.error) {+ return dockerHubResult.data;+ }+ }++ return {+ date: 'Unknown date',+ daysSince: -1+ };+ }++ const configUrl = `${baseUrl}/v2/${adjustedRepoPath}/blobs/${configDigest}`;+ const configResult = await tryCatch(fetch(configUrl, { headers }));++ if (configResult.error || !configResult.data.ok) {+ return {+ date: 'Unknown date',+ daysSince: -1+ };+ }++ const configResponse = configResult.data;+ const configDataResult = await tryCatch(configResponse.json());++ if (configDataResult.error) {+ return {+ date: 'Unknown date',+ daysSince: -1+ };+ }++ const configData = configDataResult.data;++ if (configData.created) {+ const creationDate = new Date(configData.created);++ if (!isNaN(creationDate.getTime())) {+ const daysSince = getDaysSinceDate(creationDate);+ const dateFormatOptions: Intl.DateTimeFormatOptions = {+ year: 'numeric',+ month: 'short',+ day: 'numeric'+ };++ return {+ date: creationDate.toLocaleDateString(undefined, dateFormatOptions),+ daysSince: daysSince+ };+ }+ }++ if (configData.config && configData.config.Labels && configData.config.Labels['org.opencontainers.image.created']) {+ const labelDate = new Date(configData.config.Labels['org.opencontainers.image.created']);++ if (!isNaN(labelDate.getTime())) {+ const daysSince = getDaysSinceDate(labelDate);+ const dateFormatOptions: Intl.DateTimeFormatOptions = {+ year: 'numeric',+ month: 'short',+ day: 'numeric'+ };++ return {+ date: labelDate.toLocaleDateString(undefined, dateFormatOptions),+ daysSince: daysSince+ };+ }+ }++ if (registryDomain === 'docker.io' || registryDomain === 'registry-1.docker.io') {+ const dockerHubResult = await tryCatch(getDockerHubCreationDate(repoPath, tag));+ if (!dockerHubResult.error) {+ return dockerHubResult.data;+ }+ }++ return {+ date: 'Unknown date',+ daysSince: -1+ };+}++/**+ * Fallback to get image creation date from Docker Hub API+ */+async function getDockerHubCreationDate(repository: string, tag: string): Promise<{ date: string; daysSince: number }> {+ const repoPath = repository.startsWith('library/') ? repository.substring(8) : repository;+ const url = `https://hub.docker.com/v2/repositories/${repoPath}/tags/${tag}`;++ const responseResult = await tryCatch(fetch(url));+ if (responseResult.error || !responseResult.data.ok) {+ return {+ date: 'Unknown date',+ daysSince: -1+ };+ }++ const response = responseResult.data;+ const dataResult = await tryCatch(response.json());++ if (dataResult.error || !dataResult.data.last_updated) {+ return {+ date: 'Unknown date',+ daysSince: -1+ };+ }++ const data = dataResult.data;+ const creationDate = new Date(data.last_updated);+ const daysSince = getDaysSinceDate(creationDate);++ const dateFormatOptions: Intl.DateTimeFormatOptions = {+ year: 'numeric',+ month: 'short',+ day: 'numeric'+ };++ return {+ date: creationDate.toLocaleDateString(undefined, dateFormatOptions),+ daysSince: daysSince+ };+}++/**+ * Get the tag pattern for semantic comparison between tags+ * This allows comparing similar versions while avoiding unrelated tags+ */+function getTagPattern(tag: string): { pattern: string; version: string | null } {+ const exactMatchTags = ['latest', 'stable', 'unstable', 'dev', 'devel', 'development', 'test', 'testing', 'prod', 'production', 'main', 'master', 'stage', 'staging', 'canary', 'nightly', 'edge', 'next', 'private-registries', 'data-path', 'env-fix', 'oidc'];++ const versionMatch = tag.match(/(\d+(?:\.\d+)*)/);+ const version = versionMatch ? versionMatch[1] : null;++ const prefixMatch = tag.match(/^([a-z][\w-]*?)[\.-]?\d/i);+ const prefix = prefixMatch ? prefixMatch[1] : null;++ if (exactMatchTags.includes(tag)) {+ return { pattern: tag, version: null };+ } else if (prefix && version) {+ return { pattern: prefix, version };+ } else if (version) {+ const majorVersion = version.split('.')[0];+ return { pattern: majorVersion, version };+ } else {+ return { pattern: tag, version: null };+ }+}++/**+ * Find newer versions of similar tags+ */+function findNewerVersionsOfSameTag(allTags: string[], currentTag: string): { newerTags: string[]; isSpecialTag: boolean } {+ const { pattern, version } = getTagPattern(currentTag);++ if (!version) {+ const exactMatches = allTags.filter((tag) => tag === currentTag);++ if (exactMatches.length > 0) {+ return { newerTags: [], isSpecialTag: true };+ }++ const specialTags = ['latest', 'stable', 'development', 'main', 'master'];+ const alternatives = allTags.filter((tag) => specialTags.includes(tag));++ if (alternatives.length > 0) {+ return { newerTags: alternatives, isSpecialTag: true };+ }++ return { newerTags: [], isSpecialTag: true };+ }++ const similarTags = allTags+ .filter((tag) => {+ const tagInfo = getTagPattern(tag);+ return tagInfo.pattern === pattern && tagInfo.version;+ })+ .filter((tag) => tag !== currentTag);++ const sortedTags = sortTagsByVersion([currentTag, ...similarTags]);+ const newerTags = sortedTags.filter((tag) => tag !== currentTag);++ return { newerTags, isSpecialTag: false };+}++/**+ * Sort tags by their semantic version+ */+function sortTagsByVersion(tags: string[]): string[] {+ return [...tags].sort((a, b) => {+ const getVersionParts = (tag: string) => {+ const verMatch = tag.match(/(\d+(?:\.\d+)*)/);+ if (!verMatch) return [0];++ return verMatch[1].split('.').map(Number);+ };++ const aVer = getVersionParts(a);+ const bVer = getVersionParts(b);++ for (let i = 0; i < Math.max(aVer.length, bVer.length); i++) {+ const aNum = aVer[i] || 0;+ const bNum = bVer[i] || 0;++ if (aNum !== bNum) {+ return bNum - aNum;+ }+ }++ return b.localeCompare(a);+ });+}++/**+ * Calculates days between now and a given date+ */+function getDaysSinceDate(date: Date): number {+ const now = new Date();+ const diffTime = Math.abs(now.getTime() - date.getTime());+ return Math.ceil(diffTime / (1000 * 60 * 60 * 24));+}diff --git a/src/lib/services/settings-service.ts b/src/lib/services/settings-service.tsindex 68e5436ae..eae44853e 100644--- a/src/lib/services/settings-service.ts+++ b/src/lib/services/settings-service.ts@@ -23,7 +23,8 @@ export const DEFAULT_SETTINGS: Settings = {sessionTimeout: 60,passwordPolicy: 'strong',rbacEnabled: false- }+ },+ maturityThresholdDays: 30};async function ensureSettingsDir() {diff --git a/src/lib/stores/maturity-store.ts b/src/lib/stores/maturity-store.tsnew file mode 100644index 000000000..98bca8089--- /dev/null+++ b/src/lib/stores/maturity-store.ts@@ -0,0 +1,43 @@+import { writable } from 'svelte/store';+import type { ImageMaturity } from '$lib/types/docker/image.type';++export type MaturityState = {+ lastChecked: Date | null;+ maturityData: Record<string, ImageMaturity>;+ isChecking: boolean;+};++const initialState: MaturityState = {+ lastChecked: null,+ maturityData: {},+ isChecking: false+};++export const maturityStore = writable<MaturityState>(initialState);++// Function to update maturity for a specific image+export function updateImageMaturity(imageId: string, maturity: ImageMaturity | undefined): void {+ maturityStore.update((state) => {+ const newData = { ...state.maturityData };++ if (maturity) {+ newData[imageId] = maturity;+ } else {+ delete newData[imageId];+ }++ return {+ ...state,+ maturityData: newData+ };+ });+}++// Update the checking status+export function setMaturityChecking(isChecking: boolean): void {+ maturityStore.update((state) => ({+ ...state,+ isChecking,+ lastChecked: isChecking ? state.lastChecked : new Date()+ }));+}diff --git a/src/lib/stores/settings-store.ts b/src/lib/stores/settings-store.tsindex 8f188e1ae..a5004af74 100644--- a/src/lib/stores/settings-store.ts+++ b/src/lib/stores/settings-store.ts@@ -39,7 +39,8 @@ export const settingsStore = writable<Settings>({sessionTimeout: 30,passwordPolicy: 'strong',rbacEnabled: false- }+ },+ maturityThresholdDays: 30});export function updateSettingsStore(serverData: Partial<Settings>) {diff --git a/src/lib/types/docker/image.type.ts b/src/lib/types/docker/image.type.tsindex 2208931c1..afc10d902 100644--- a/src/lib/types/docker/image.type.ts+++ b/src/lib/types/docker/image.type.ts@@ -10,6 +10,14 @@ export type ServiceImage = {tag: string;};+export interface ImageMaturity {+ version: string;+ date: string;+ status: 'Matured' | 'Not Matured' | 'Unknown';+ updatesAvailable: boolean;+}+export type EnhancedImageInfo = ServiceImage & {inUse: boolean;+ maturity?: ImageMaturity;};diff --git a/src/lib/types/errors.type.ts b/src/lib/types/errors.type.tsindex 43bb28aed..0d2f1136e 100644--- a/src/lib/types/errors.type.ts+++ b/src/lib/types/errors.type.ts@@ -1,20 +1,94 @@//This file replaces errors.tsexport enum ApiErrorCode {- VALIDATION_ERROR = 'VALIDATION_ERROR',NOT_FOUND = 'NOT_FOUND',- DOCKER_API_ERROR = 'DOCKER_API_ERROR',- CONFLICT = 'CONFLICT',BAD_REQUEST = 'BAD_REQUEST',- INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',UNAUTHORIZED = 'UNAUTHORIZED',- FORBIDDEN = 'FORBIDDEN'+ FORBIDDEN = 'FORBIDDEN',+ INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',+ SERVICE_UNAVAILABLE = 'SERVICE_UNAVAILABLE',+ VALIDATION_ERROR = 'VALIDATION_ERROR',+ DOCKER_API_ERROR = 'DOCKER_API_ERROR',+ CONFLICT = 'CONFLICT',+ REGISTRY_PUBLIC_ACCESS_ERROR = 'REGISTRY_PUBLIC_ACCESS_ERROR',+ REGISTRY_PRIVATE_ACCESS_ERROR = 'REGISTRY_PRIVATE_ACCESS_ERROR',+ REGISTRY_API_RATE_LIMIT = 'REGISTRY_API_RATE_LIMIT',+ REGISTRY_UNSUPPORTED = 'REGISTRY_UNSUPPORTED'}export interface ApiErrorResponse {success: false;error: string;code: ApiErrorCode;+ details?: any;failedCount?: number;- details?: unknown;+}++export class BaseError extends Error {+ constructor(message: string) {+ super(message);+ this.name = this.constructor.name;+ Error.captureStackTrace(this, this.constructor);+ }+}++export class NotFoundError extends BaseError {+ constructor(message: string) {+ super(message);+ // Object.setPrototypeOf(this, NotFoundError.prototype); might be needed here too.+ // However, the prompt is specific to the registry errors.+ }+}++export class DockerApiError extends BaseError {+ statusCode: number;++ constructor(message: string, statusCode: number) {+ super(message);+ this.statusCode = statusCode;+ // If targeting ES5 and BaseError directly extends Error,+ // Object.setPrototypeOf(this, DockerApiError.prototype); might be needed here too.+ }+}++export class RegistryRateLimitError extends BaseError {+ registry: string;+ repository: string;+ retryAfter?: Date;++ constructor(message: string, registry: string, repository: string, retryAfter?: Date) {+ super(message);+ this.registry = registry;+ this.repository = repository;+ this.retryAfter = retryAfter;+ Object.setPrototypeOf(this, RegistryRateLimitError.prototype);+ }+}++export class PublicRegistryError extends BaseError {+ registry: string;+ repository: string;+ statusCode?: number;++ constructor(message: string, registry: string, repository: string, statusCode?: number) {+ super(message);+ this.registry = registry;+ this.repository = repository;+ this.statusCode = statusCode;+ Object.setPrototypeOf(this, PublicRegistryError.prototype);+ }+}++export class PrivateRegistryError extends BaseError {+ registry: string;+ repository: string;+ statusCode?: number;++ constructor(message: string, registry: string, repository: string, statusCode?: number) {+ super(message);+ this.registry = registry;+ this.repository = repository;+ this.statusCode = statusCode;+ Object.setPrototypeOf(this, PrivateRegistryError.prototype);+ }}diff --git a/src/lib/types/form.type.ts b/src/lib/types/form.type.tsnew file mode 100644index 000000000..2f3433445--- /dev/null+++ b/src/lib/types/form.type.ts@@ -0,0 +1,7 @@+export type FormInput<T> = {+ value: T;+ valid: boolean;+ touched: boolean;+ error: string | null;+ errors: string[];+};diff --git a/src/lib/types/settings.type.ts b/src/lib/types/settings.type.tsindex 99b559418..f853140c3 100644--- a/src/lib/types/settings.type.ts+++ b/src/lib/types/settings.type.ts@@ -45,4 +45,5 @@ export interface Settings {auth: AuthSettings;onboarding?: Onboarding;baseServerUrl?: string;+ maturityThresholdDays: number;}diff --git a/src/routes/api/images/[id]/maturity/+server.ts b/src/routes/api/images/[id]/maturity/+server.tsnew file mode 100644index 000000000..85c47aca5--- /dev/null+++ b/src/routes/api/images/[id]/maturity/+server.ts@@ -0,0 +1,140 @@+import { json } from '@sveltejs/kit';+import type { RequestHandler } from './$types';+import { checkImageMaturity } from '$lib/services/docker/image-service';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { tryCatch } from '$lib/utils/try-catch';++export const POST: RequestHandler = async ({ request }) => {+ const body = await request.json().catch(() => ({}));+ const { imageIds } = body;++ if (!imageIds || !Array.isArray(imageIds) || imageIds.length === 0) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Image IDs array is required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }++ try {+ // Server-side promise pool with concurrency limit+ const concurrencyLimit = 5; // Process 5 images at a time+ const results: Record<string, any> = {};+ const pending = new Set();+ const errors: Record<string, string> = {};++ // Create a queue from all images that need checking+ const queue = [...imageIds];++ // Process queue with limited concurrency+ while (queue.length > 0 || pending.size > 0) {+ // Fill up the pending set until we reach the concurrency limit+ while (pending.size < concurrencyLimit && queue.length > 0) {+ const imageId = queue.shift();+ if (!imageId) continue;++ // Create the promise for this image check+ const promise = (async () => {+ try {+ console.log(`Server: Checking maturity for image ${imageId}`);+ const checkResult = await tryCatch(checkImageMaturity(imageId));++ if (checkResult.error) {+ return {+ imageId,+ success: false,+ error: extractDockerErrorMessage(checkResult.error)+ };+ }++ return { imageId, success: true, data: checkResult.data };+ } catch (error) {+ console.error(`Server: Failed to check maturity for ${imageId}:`, error);+ return {+ imageId,+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error'+ };+ }+ })();++ // Add to pending set and set up cleanup when done+ pending.add(promise);+ promise.then((result) => {+ pending.delete(promise);++ if (result.success) {+ results[result.imageId] = result.data;+ } else {+ errors[result.imageId] = result.error ?? 'Unknown error';+ }+ });+ }++ // Wait for at least one promise to resolve before continuing+ if (pending.size >= concurrencyLimit || (queue.length === 0 && pending.size > 0)) {+ await Promise.race(Array.from(pending));+ }+ }++ const successCount = Object.keys(results).length;+ const failCount = Object.keys(errors).length;++ console.log(`Server: Maturity check completed. ${successCount} successful, ${failCount} failed`);++ return json({+ success: true,+ results,+ errors,+ stats: {+ total: imageIds.length,+ success: successCount,+ failed: failCount+ }+ });+ } catch (error) {+ console.error('Server: Error in batch maturity check:', error);++ const response: ApiErrorResponse = {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error occurred',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: error+ };+ return json(response, { status: 500 });+ }+};++export const GET: RequestHandler = async ({ params }) => {+ const { id } = params;++ if (!id) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Image ID is required',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }++ const result = await tryCatch(checkImageMaturity(id));++ if (result.error) {+ console.error('Error checking image maturity:', result.error);++ const response: ApiErrorResponse = {+ success: false,+ error: extractDockerErrorMessage(result.error),+ code: ApiErrorCode.DOCKER_API_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });+ }++ return json({+ success: true,+ result+ });+};diff --git a/src/routes/api/settings/+server.ts b/src/routes/api/settings/+server.tsindex 15fa45502..b4e3d62d8 100644--- a/src/routes/api/settings/+server.ts+++ b/src/routes/api/settings/+server.ts@@ -115,6 +115,18 @@ export const PUT: RequestHandler = async ({ request }) => {newSettingsData.autoUpdateInterval = autoUpdateInterval;}+ // Validate maturity threshold days+ const maturityThresholdDays = parseInt(String(newSettingsData.maturityThresholdDays), 10);+ if (isNaN(maturityThresholdDays) || maturityThresholdDays < 1 || maturityThresholdDays > 365) {+ const response: ApiErrorResponse = {+ success: false,+ error: 'Maturity threshold must be between 1 and 365 days.',+ code: ApiErrorCode.BAD_REQUEST+ };+ return json(response, { status: 400 });+ }+ newSettingsData.maturityThresholdDays = maturityThresholdDays;+// Persist the validated new settings to diskconst saveResult = await tryCatch(persistSettings(newSettingsData));diff --git a/src/routes/images/+page.server.ts b/src/routes/images/+page.server.tsindex b5e0ec6a3..1d2cea1bf 100644--- a/src/routes/images/+page.server.ts+++ b/src/routes/images/+page.server.ts@@ -1,5 +1,5 @@import type { PageServerLoad } from './$types';-import { listImages, isImageInUse } from '$lib/services/docker/image-service';+import { listImages, isImageInUse, checkImageMaturity } from '$lib/services/docker/image-service';import type { EnhancedImageInfo } from '$lib/types/docker';import { getSettings } from '$lib/services/settings-service';import type { Settings } from '$lib/types/settings.type';@@ -18,9 +18,22 @@ export const load: PageServerLoad = async (): Promise<ImageData> => {const enhancedImages = await Promise.all(images.map(async (image): Promise<EnhancedImageInfo> => {const inUse = await isImageInUse(image.id);++ // Add maturity check without modifying existing logic+ let maturity = undefined;+ try {+ if (image.repo !== '<none>' && image.tag !== '<none>') {+ maturity = await checkImageMaturity(image.id);+ }+ } catch (maturityError) {+ console.error(`Failed to check maturity for image ${image.id}:`, maturityError);+ // Don't let maturity errors affect the main flow+ }+return {...image,- inUse+ inUse,+ maturity // Add maturity info if available};}));diff --git a/src/routes/images/+page.svelte b/src/routes/images/+page.svelteindex 61dda9a50..1fdddd426 100644--- a/src/routes/images/+page.svelte+++ b/src/routes/images/+page.svelte@@ -3,7 +3,7 @@import type { EnhancedImageInfo } from '$lib/types/docker';import UniversalTable from '$lib/components/universal-table.svelte';import { Button } from '$lib/components/ui/button/index.js';- import { Download, AlertCircle, HardDrive, Trash2, Loader2, ChevronDown, CopyX, Ellipsis, ScanSearch, Plus, Funnel } from '@lucide/svelte';+ import { Download, AlertCircle, HardDrive, Trash2, Loader2, ChevronDown, CopyX, Ellipsis, ScanSearch, CircleFadingArrowUp, Funnel, CircleCheck, CircleArrowUp } from '@lucide/svelte';import * as Alert from '$lib/components/ui/alert/index.js';import * as Card from '$lib/components/ui/card/index.js';import { goto, invalidateAll } from '$app/navigation';@@ -19,6 +19,7 @@import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import { settingsStore } from '$lib/stores/settings-store';+ import * as Tooltip from '$lib/components/ui/tooltip/index.js';let { data }: { data: PageData } = $props();let images = $state<EnhancedImageInfo[]>(data.images || []);@@ -37,7 +38,8 @@pulling: false,removing: false,refreshing: false,- pruning: false+ pruning: false,+ checking: false});$effect(() => {@@ -238,6 +240,74 @@});}+ async function checkAllMaturity() {+ isLoading.checking = true;++ const imageIdsToCheck = images.filter((image) => image.id).map((image) => image.id);++ if (imageIdsToCheck.length === 0) {+ toast.info('No images to check for updates.');+ isLoading.checking = false;+ return;+ }++ console.log(`Client: Attempting to check maturity for ${imageIdsToCheck.length} images.`);++ try {+ const batchResult = await imageApi.checkMaturityBatch(imageIdsToCheck);++ if (!batchResult || typeof batchResult.success !== 'boolean') {+ toast.error('Maturity check failed: Invalid response from server.');+ isLoading.checking = false;+ return;+ }++ const stats = batchResult.stats || { total: 0, success: 0, failed: 0 };+ const numSuccessfullyUpdated = stats.success || 0; // Images for which new data was likely returned+ 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 successful+ if (numSuccessfullyUpdated > 0) {+ toast.success(`Successfully retrieved updates for ${numSuccessfullyUpdated} image(s).`);+ }+ if (numFailedByBackend > 0) {+ toast.warning(`Backend failed to check updates for ${numFailedByBackend} image(s).`);+ }++ if (imageIdsToCheck.length > numAttemptedByBackend && numAttemptedByBackend >= 0) {+ 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.`);+ }+ }++ if (numSuccessfullyUpdated === 0 && numFailedByBackend === 0 && numAttemptedByBackend === 0 && imageIdsToCheck.length > 0) {+ 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) {+ console.error('Client-side error during checkAllMaturity:', error);+ toast.error(`Client-side error checking image updates: ${(error as Error).message}`);+ } finally {+ isLoading.checking = false;+ }+ }+$effect(() => {images = data.images;});@@ -349,14 +419,23 @@<Download class="w-4 h-4" /> Pull Image{/if}</Button>+ <Button variant="outline" onclick={() => checkAllMaturity()} disabled={isLoading.checking}>+ {#if isLoading.checking}+ <Loader2 class="w-4 h-4 mr-2 animate-spin" /> Checking...+ {:else}+ <ScanSearch class="w-4 h-4 mr-2" /> Check Updates+ {/if}+ </Button></div></div></Card.Header>+<Card.Content><UniversalTabledata={filteredImages}columns={[{ accessorKey: 'repo', header: 'Name' },+ { accessorKey: 'inUse', header: ' ', enableSorting: false },{ accessorKey: 'tag', header: 'Tag' },{ accessorKey: 'id', header: 'Image ID', enableSorting: false },{ accessorKey: 'size', header: 'Size' },@@ -375,16 +454,102 @@{#snippet rows({ item })}<Table.Cell><div class="flex items-center gap-2">- <span class="truncate">- <a class="font-medium hover:underline" href="/images/{item.id}/">+ <div class="flex items-center flex-1">+ <!-- Maturity Indicator with proper Tooltip -->+ {#if item.maturity}+ <Tooltip.Provider>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <span class="inline-flex items-center justify-center align-middle w-4 h-4 mr-2">+ {#if !item.maturity.updatesAvailable}+ <!-- Green checkmark for up-to-date images -->++ <CircleCheck class="w-10 h-10 text-green-500" fill="none" stroke="currentColor" strokeWidth="2" />+ <!-- <CircleFadingArrowUp class="w-4 h-4 text-green-500" fill="none" stroke="currentColor" strokeWidth="2" /> -->+ {:else if item.maturity.status === 'Not Matured'}+ <!-- Yellow warning icon for non-matured updates -->+ <CircleFadingArrowUp class="w-10 h-10 text-yellow-500" fill="none" stroke="currentColor" stroke-width="2" />+ {:else}+ <!-- Blue checkmark for matured updates -->+ <CircleArrowUp class="w-10 h-10 text-blue-500" fill="none" stroke="currentColor" stroke-width="2" />+ {/if}+ </span>+ </Tooltip.Trigger>+ <!-- Tooltip content updated -->+ <Tooltip.Content side="right" class="p-3 max-w-[200px] relative tooltip-with-arrow" align="center">+ <div class="space-y-2">+ <div class="flex items-center gap-2">+ {#if !item.maturity.updatesAvailable}+ <!-- Green checkmark in tooltip -->+ <CircleCheck class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" strokeWidth="2" />+ <span class="font-medium">Image Up to Date</span>+ {:else if item.maturity.status === 'Not Matured'}+ <!-- Yellow warning icon in tooltip -->+ <CircleFadingArrowUp class="w-5 h-5 text-yellow-500" fill="none" stroke="currentColor" stroke-width="2" />+ <span class="font-medium">Update Available (Not Matured)</span>+ {:else}+ <!-- Blue info icon in tooltip -->+ <CircleArrowUp class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" stroke-width="2" />+ <span class="font-medium">Matured Update Available</span>+ {/if}+ </div>++ <div class="pt-1 border-t border-gray-200 dark:border-gray-700 justify-between">+ <div class="flex justify-between text-xs">+ <span class="text-muted-foreground">Version:</span>+ <span class="font-medium">{item.maturity.version || 'N/A'}</span>+ </div>++ <div class="flex justify-between text-xs mt-1">+ <span class="text-muted-foreground">Released:</span>+ <span>{item.maturity.date || 'Unknown'}</span>+ </div>++ <div class="flex justify-between text-xs mt-1">+ <span class="text-muted-foreground">Status:</span>+ <span class={item.maturity.status === 'Matured' ? 'text-green-500' : 'text-amber-500'}>+ {item.maturity.status || 'Unknown'}+ </span>+ </div>+ </div>+ </div>+ </Tooltip.Content>+ </Tooltip.Root>+ </Tooltip.Provider>+ {:else}+ <!-- Tooltip for missing maturity info -->+ <Tooltip.Provider>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <span class="inline-flex items-center justify-center w-4 h-4 mr-2 opacity-30">+ <svg class="w-4 h-4 text-gray-500" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">+ <circle cx="12" cy="12" r="10" />+ <path d="M9 12l2 2 4-4" />+ </svg>+ </span>+ </Tooltip.Trigger>+ <Tooltip.Content side="right" class="p-2 relative tooltip-with-arrow" align="center">+ <span class="text-xs">Maturity status not available.</span>+ </Tooltip.Content>+ </Tooltip.Root>+ </Tooltip.Provider>+ {/if}+ <!-- End Maturity Indicator -->++ <!-- Repository name as a separate element -->+ <a class="font-medium hover:underline flex-shrink truncate" href="/images/{item.id}/">{item.repo}</a>- </span>- {#if !item.inUse}- <StatusBadge text="Unused" variant="amber" />- {/if}+ </div></div></Table.Cell>+ <Table.Cell>+ {#if !item.inUse}+ <StatusBadge text="Unused" variant="amber" />+ {:else}+ <StatusBadge text="In Use" variant="green" />+ {/if}+ </Table.Cell><Table.Cell>{item.tag}</Table.Cell><Table.Cell class="truncate">{item.id}</Table.Cell><Table.Cell>{formatBytes(item.size)}</Table.Cell>@@ -460,3 +625,57 @@</Dialog.Content></Dialog.Root></div>++<style>+ :global(.tooltip-with-arrow) {+ position: relative;+ overflow: visible;+ }++ :global(.tooltip-with-arrow::before) {+ content: '';+ position: absolute;+ width: 8px;+ height: 8px;+ background-color: hsl(var(--popover));+ border: 1px solid hsl(var(--border));+ z-index: 1;+ }++ /* Top side: Arrow on bottom of tooltip pointing down */+ :global(.tooltip-with-arrow[data-side='top']::before) {+ bottom: -4px;+ left: 50%;+ transform: translateX(-50%) rotate(45deg);+ border-top: none;+ border-left: none;+ }++ /* Bottom side: Arrow on top of tooltip pointing up */+ :global(.tooltip-with-arrow[data-side='bottom']::before) {+ top: -4px;+ left: 50%;+ transform: translateX(-50%) rotate(225deg);+ border-bottom: none;+ border-right: none;+ }++ /* Left side: Arrow on right of tooltip pointing right */+ :global(.tooltip-with-arrow[data-side='left']::before) {+ top: 50%;+ right: -4px;+ transform: translateY(-50%) rotate(-45deg);+ border-left: none;+ 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;+ transform: translateY(-50%) rotate(-45deg);+ border-left: none;+ border-top: none;+ box-shadow: -1px 1px 1px rgba(0, 0, 0, 0.05);+ }+</style>diff --git a/src/routes/images/pull-image-dialog.svelte b/src/routes/images/pull-image-dialog.svelteindex 2bbb101e7..dce03c30b 100644--- a/src/routes/images/pull-image-dialog.svelte+++ b/src/routes/images/pull-image-dialog.svelte@@ -6,7 +6,6 @@import { Loader2 } from '@lucide/svelte';import * as Accordion from '$lib/components/ui/accordion/index.js';import * as Select from '$lib/components/ui/select/index.js';- import type { RegistryCredential } from '$lib/types/settings.type';import { settingsStore } from '$lib/stores/settings-store';function preventDefault(handler: (event: SubmitEvent) => void) {@@ -50,13 +49,6 @@{ label: 'windows/amd64', value: 'windows/amd64' }];- function getRegistryLabel(url: string | undefined): string {- if (!url || url.toLowerCase() === 'docker.io') {- return 'Default (Docker Hub / Public)';- }- return url;- }-function handleSubmit() {if (!imageRef.trim()) return;@@ -81,8 +73,6 @@registryUrl: selectedRegistryUrl || undefined});}-- console.log($settingsStore.registryCredentials.length);</script><Dialog.Root bind:open>diff --git a/src/routes/settings/tabs/app-settings.svelte b/src/routes/settings/tabs/app-settings.svelteindex abbc94770..e0e9d9421 100644--- a/src/routes/settings/tabs/app-settings.svelte+++ b/src/routes/settings/tabs/app-settings.svelte@@ -1,20 +1,90 @@<script lang="ts">import * as Card from '$lib/components/ui/card/index.js';- import { Input } from '$lib/components/ui/input/index.js';+ import FormInput from '$lib/components/form/form-input.svelte';import { Cog } from '@lucide/svelte';import type { PageData } from '../$types';import { settingsStore } from '$lib/stores/settings-store';+ import type { FormInput as FormInputType } from '$lib/types/form.type';let { data } = $props<{ data: PageData }>();+ // Initialize settings from page data once+ let initialized = false;$effect(() => {- if (data.settings) {+ if (data.settings && !initialized) {settingsStore.update((current) => ({...current,...data.settings}));+ initialized = true;}});++ // Create local form state with initial values+ let stacksDirectoryInput = $state<FormInputType<string>>({+ value: $settingsStore.stacksDirectory || '',+ valid: true,+ touched: false,+ error: null,+ errors: []+ });++ let baseServerUrlInput = $state<FormInputType<string>>({+ value: $settingsStore.baseServerUrl || '',+ valid: true,+ touched: false,+ error: null,+ errors: []+ });++ let maturityThresholdInput = $state<FormInputType<number>>({+ value: $settingsStore.maturityThresholdDays || 30,+ valid: true,+ touched: false,+ error: null,+ errors: []+ });++ // No automatic syncing - just event handlers for changes+ function onStacksDirectoryChange() {+ stacksDirectoryInput.touched = true;+ settingsStore.update((settings) => ({+ ...settings,+ stacksDirectory: stacksDirectoryInput.value+ }));+ }++ function onBaseServerUrlChange() {+ baseServerUrlInput.touched = true;+ settingsStore.update((settings) => ({+ ...settings,+ baseServerUrl: baseServerUrlInput.value+ }));+ }++ function onMaturityThresholdChange() {+ maturityThresholdInput.touched = true;+ // The value from the input element (via bind:input) might be a string.+ const rawValue = maturityThresholdInput.value;+ const numericValue = parseInt(String(rawValue), 10);++ if (!isNaN(numericValue)) {+ // Update the local state's value to be a number for type consistency+ maturityThresholdInput.value = numericValue;+ settingsStore.update((settings) => ({+ ...settings,+ maturityThresholdDays: numericValue+ }));+ maturityThresholdInput.valid = true;+ maturityThresholdInput.error = null;+ } else {+ // If parsing fails (e.g., empty input), mark as invalid.+ // The maturityThresholdInput.value will remain the unparsed (e.g. empty string) value.+ maturityThresholdInput.valid = false;+ maturityThresholdInput.error = 'Please enter a valid whole number.';+ // The store is not updated with NaN.+ }+ }</script><div class="grid auto-cols-auto lg:auto-cols-auto gap-6">@@ -32,18 +102,29 @@</Card.Header><Card.Content><div class="space-y-6">- <div class="space-y-2">- <label for="stacksDirectory" class="text-sm font-medium block mb-1.5">Stack Projects Directory</label>- <Input type="text" id="stacksDirectory" name="stacksDirectory" bind:value={$settingsStore.stacksDirectory} placeholder="/opt/arcane/stacks" required />- <p class="text-xs text-muted-foreground">The primary folder where Arcane will store and manage your Docker Compose stack projects. This path is inside Arcane's container.</p>- <p class="text-xs font-bold text-destructive">Important: Changing this path will not automatically move existing stack projects.</p>- </div>+ <FormInput+ bind:input={stacksDirectoryInput}+ type="text"+ id="stacksDirectory"+ label="Stack Projects Directory"+ placeholder="/opt/arcane/stacks"+ required+ description="The primary folder where Arcane will store and manage your Docker Compose stack projects. This path is inside Arcane's container."+ warningText="Important: Changing this path will not automatically move existing stack projects."+ oninput={() => onStacksDirectoryChange()}+ />- <div class="space-y-2">- <label for="baseServerUrl" class="text-sm font-medium block mb-1.5">Default Service Access URL</label>- <Input type="text" id="baseServerUrl" name="baseServerUrl" bind:value={$settingsStore.baseServerUrl} placeholder="localhost" />- <p class="text-xs text-muted-foreground">When Arcane provides links to your services (e.g., web UIs), this URL (like 'localhost' or an IP address) is used as the default. This is primarily for services not on directly accessible networks (e.g., macvlan).</p>- </div>+ <FormInput+ bind:input={baseServerUrlInput}+ type="text"+ id="baseServerUrl"+ label="Default Service Access URL"+ placeholder="localhost"+ description="When Arcane provides links to your services (e.g., web UIs), this URL (like 'localhost' or an IP address) is used as the default. This is primarily for services not on directly accessible networks (e.g., macvlan)."+ oninput={() => onBaseServerUrlChange()}+ />++ <FormInput bind:input={maturityThresholdInput} type="number" id="maturityThresholdDays" label="Image Maturity Threshold (days)" placeholder="30" required description="The number of days after an image release before it's considered 'matured'." warningText="Higher values mean more caution with new images." oninput={() => onMaturityThresholdChange()} /></div></Card.Content></Card.Root>