Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: image update indicator (#340)
Kyle Mendell43ef157e4cd8
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mdindex 92ae240ce..2782c1caa 100644--- a/.github/copilot-instructions.md+++ b/.github/copilot-instructions.md@@ -1,3 +1,188 @@-Use Svelte 5 syntax for all frontend files.+# Arcane Docker Management UI - Copilot Instructions-Dont add un-needed comments in any file.+## Project Overview+Arcane is a modern, full-stack Docker management UI built with SvelteKit frontend and Go backend. It provides comprehensive Docker environment management including containers, images, volumes, networks, stacks, and image update tracking.++## Architecture & Tech Stack++### Backend (Go)+- **Framework**: Gin web framework with Go 1.24.3++- **Database**: GORM with PostgreSQL/SQLite support+- **Structure**: Clean architecture with bootstrap pattern+- **Authentication**: JWT + optional OIDC integration+- **Jobs**: gocron v2 for scheduled tasks+- **Docker**: Official Docker SDK integration++### Frontend (SvelteKit + TypeScript)+- **Framework**: SvelteKit with Svelte 5 syntax+- **UI**: shadcn-svelte components + Tailwind CSS+- **Icons**: Lucide Svelte+- **State**: Svelte 5 runes ($state, $effect, $derived)+- **API**: Axios for HTTP requests+- **Build**: Vite with static adapter++## Code Conventions & Patterns++### Backend (Go)++#### File Organization+```+backend/+├── cmd/main.go # Application entry point+├── internal/+│ ├── bootstrap/ # App initialization (DI container pattern)+│ ├── api/ # HTTP handlers (*_handler.go)+│ ├── services/ # Business logic (*_service.go)+│ ├── models/ # Database models+│ ├── dto/ # Data transfer objects+│ ├── database/ # DB connection & migrations+│ ├── config/ # Configuration management+│ ├── middleware/ # HTTP middleware+│ ├── utils/ # Utility functions+│ └── job/ # Background job scheduling+```++#### Naming Conventions+- **Handlers**: `*_handler.go` with methods like `List`, `Create`, `Update`, `Delete`+- **Services**: `*_service.go` with business logic implementation+- **Models**: Singular names (e.g., `Container`, `Image`, `Stack`)+- **Package names**: Lowercase, single word when possible++#### Database Models+- Use GORM annotations for relationships and constraints+- Include `BaseModel` for common fields (ID, CreatedAt, UpdatedAt)+- Implement `TableName()` method for custom table names+- Use proper foreign key relationships with preloading++#### API Patterns+- RESTful endpoints with proper HTTP status codes+- Use DTOs for request/response transformation+- Implement pagination with `SortedPaginationRequest`+- Return consistent JSON error responses+- Use Gin binding for request validation++#### Error Handling+- Return meaningful HTTP status codes+- Use structured logging with `slog`+- Wrap errors with context using `fmt.Errorf`+- Handle Docker API errors gracefully++### Frontend (SvelteKit + TypeScript)++#### File Organization+```+frontend/src/+├── routes/ # SvelteKit file-based routing+├── lib/+│ ├── components/ # Reusable Svelte components+│ ├── services/api/ # API service classes+│ ├── stores/ # Svelte stores+│ ├── types/ # TypeScript type definitions+│ ├── dto/ # Frontend DTOs+│ ├── utils/ # Utility functions+│ └── constants.ts # App constants+```++#### Svelte 5 Conventions+- **Props**: Use `let { prop1, prop2 } = $props()` destructuring+- **State**: Use `$state()` for reactive variables+- **Effects**: Use `$effect()` for side effects+- **Derived**: Use `$derived()` for computed values+- **Event handlers**: Use `on*` props or inline handlers++#### Component Patterns+- **Reusable components**: Place in `/lib/components/`+- **Page components**: Use `+page.svelte` in routes+- **Layout components**: Use `+layout.svelte` for shared layouts+- **Loading states**: Implement with `loading` props and spinners+- **Error boundaries**: Handle errors gracefully with user feedback++#### TypeScript Usage+- Define interfaces for all data structures+- Use strict type checking+- Export types from dedicated `*.type.ts` files+- Use generic types for reusable components++#### API Integration+- Create service classes in `/lib/services/api/`+- Use Axios with proper error handling+- Implement request/response DTOs+- Use async/await patterns consistently++#### Styling+- Use Tailwind CSS classes+- Follow shadcn-svelte component patterns+- Implement dark/light mode support+- Use CSS variables for theming++## Development Guidelines++### General Rules+- **No unnecessary comments**: Code should be self-documenting+- **Clean imports**: Group and sort imports logically+- **Error handling**: Always handle errors appropriately+- **Type safety**: Use TypeScript strictly on frontend+- **Performance**: Implement pagination, lazy loading, and efficient updates++### Backend Specific+- Use dependency injection through bootstrap pattern+- Implement proper service layer separation+- Use GORM relationships efficiently with preloading+- Handle Docker API rate limits and timeouts+- Implement proper logging with structured data++### Frontend Specific+- **Always use Svelte 5 syntax** (runes, new event handling)+- Implement proper loading and error states+- Use reactive patterns efficiently+- Follow SvelteKit best practices for SSR/hydration+- Implement proper form validation++### Database+- Use migrations for schema changes+- Implement proper indexing for performance+- Use foreign key constraints+- Handle soft deletes where appropriate++### Security+- Validate all user inputs+- Use proper authentication middleware+- Implement CORS correctly+- Encrypt sensitive configuration data+- Follow Docker security best practices++### Testing+- Write Playwright E2E tests for critical user flows+- Test API endpoints thoroughly+- Mock external Docker API calls in tests+- Use proper test data setup and teardown++## Anti-Patterns to Avoid++### Backend+- Don't put business logic in handlers+- Don't use global variables for state+- Don't ignore database transaction boundaries+- Don't hardcode registry-specific logic (use generic patterns)++### Frontend+- Don't use Svelte 4 syntax (no export let, on:click, etc.)+- Don't ignore loading/error states+- Don't create overly complex component hierarchies+- Don't bypass type checking with `any`++### General+- Don't add unnecessary comments or console.log statements+- Don't ignore error handling+- Don't create tight coupling between layers+- Don't commit sensitive configuration data++## Container Registry Integration+When working with container registries:+- Use generic authentication patterns, not registry-specific hardcoding+- Handle different authentication methods (bearer tokens, basic auth)+- Implement proper error handling for network timeouts+- Support multiple registry providers (Docker Hub, GHCR, custom OCI)+- Use case-insensitive header checking for registry responses++This codebase emphasizes clean architecture, type safety, and maintainable patterns. Follow these guidelines to ensure consistency and quality across all contributions.diff --git a/backend/internal/api/image_handler.go b/backend/internal/api/image_handler.goindex ccebef8aa..4d9bb50e3 100644--- a/backend/internal/api/image_handler.go+++ b/backend/internal/api/image_handler.go@@ -5,7 +5,6 @@ import ("log/slog""net/http""strings"- "time""github.com/gin-gonic/gin""github.com/ofkm/arcane-backend/internal/dto"@@ -14,14 +13,14 @@ import ()type ImageHandler struct {- imageService *services.ImageService- imageMaturityService *services.ImageMaturityService+ imageService *services.ImageService+ imageUpdateService *services.ImageUpdateService}-func NewImageHandler(imageService *services.ImageService, imageMaturityService *services.ImageMaturityService) *ImageHandler {+func NewImageHandler(imageService *services.ImageService, imageUpdateService *services.ImageUpdateService) *ImageHandler {return &ImageHandler{- imageService: imageService,- imageMaturityService: imageMaturityService,+ imageService: imageService,+ imageUpdateService: imageUpdateService,}}@@ -42,7 +41,7 @@ func (h *ImageHandler) List(c *gin.Context) {req.Pagination.Limit = 20}- images, pagination, err := h.imageService.ListImagesWithMaturityPaginated(c.Request.Context(), req)+ images, pagination, err := h.imageService.ListImagesWithUpdatesPaginated(c.Request.Context(), req)if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"success": false,@@ -173,100 +172,3 @@ func (h *ImageHandler) GetHistory(c *gin.Context) {"data": history,})}--func (h *ImageHandler) CheckMaturity(c *gin.Context) {- imageID := c.Param("id")- if imageID == "" {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Image ID is required",- })- return- }-- images, err := h.imageService.ListImages(c.Request.Context())- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to list images: " + err.Error(),- })- return- }-- var targetImage *struct {- ID string- RepoTags []string- Created int64- }-- for _, img := range images {- if img.ID == imageID {- targetImage = &struct {- ID string- RepoTags []string- Created int64- }{- ID: img.ID,- RepoTags: img.RepoTags,- Created: img.Created,- }- break- }- }-- if targetImage == nil {- c.JSON(http.StatusNotFound, gin.H{- "success": false,- "error": "Image not found",- })- return- }-- if len(targetImage.RepoTags) == 0 || targetImage.RepoTags[0] == "<none>:<none>" {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Image has no valid tags for maturity checking",- })- return- }-- repoTag := targetImage.RepoTags[0]- parts := strings.Split(repoTag, ":")- if len(parts) != 2 {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid repo tag format",- })- return- }-- repo := parts[0]- tag := parts[1]-- maturityData, err := h.imageMaturityService.CheckImageMaturity(c.Request.Context(), imageID, repo, tag, time.Unix(targetImage.Created, 0))- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to check maturity: " + err.Error(),- })- return- }-- errSet := h.imageMaturityService.SetImageMaturity(c.Request.Context(), imageID, repo, tag, *maturityData, map[string]interface{}{- "registryDomain": utils.ExtractRegistryDomain(repo),- "isPrivateRegistry": utils.IsPrivateRegistry(repo),- "currentImageDate": time.Unix(targetImage.Created, 0),- })- if errSet != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to set image maturity: " + errSet.Error(),- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": maturityData,- })-}diff --git a/backend/internal/api/image_maturity_handler.go b/backend/internal/api/image_maturity_handler.godeleted file mode 100644index ccbe2396f..000000000--- a/backend/internal/api/image_maturity_handler.go+++ /dev/null@@ -1,368 +0,0 @@-package api--import (- "net/http"- "strconv"- "time"-- "github.com/gin-gonic/gin"- "github.com/ofkm/arcane-backend/internal/dto"- "github.com/ofkm/arcane-backend/internal/models"- "github.com/ofkm/arcane-backend/internal/services"-)--type ImageMaturityHandler struct {- imageMaturityService *services.ImageMaturityService- imageService *services.ImageService-}--func NewImageMaturityHandler(imageMaturityService *services.ImageMaturityService, imageService *services.ImageService) *ImageMaturityHandler {- return &ImageMaturityHandler{- imageMaturityService: imageMaturityService,- imageService: imageService,- }-}--func (h *ImageMaturityHandler) MarkAsMatured(c *gin.Context) {- imageID := c.Param("imageId")- if imageID == "" {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "imageId is required",- })- return- }-- type MarkMaturedRequest struct {- DaysSinceCreation int `json:"daysSinceCreation" binding:"required"`- }-- var req MarkMaturedRequest- if err := c.ShouldBindJSON(&req); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid request format. daysSinceCreation is required",- })- return- }-- if req.DaysSinceCreation < 0 {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "daysSinceCreation must be a positive integer",- })- return- }-- err := h.imageMaturityService.MarkAsMatured(c.Request.Context(), imageID, req.DaysSinceCreation)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to mark image as matured: " + err.Error(),- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "message": "Image marked as matured successfully",- "imageId": imageID,- "daysSinceCreation": req.DaysSinceCreation,- })-}--func (h *ImageMaturityHandler) GetImageMaturity(c *gin.Context) {- imageID := c.Param("id")-- record, err := h.imageMaturityService.GetImageMaturity(c.Request.Context(), imageID)- if err != nil {- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": models.ImageMaturity{- Version: "unknown",- Date: time.Now().Format(time.RFC3339),- Status: models.ImageStatusUnknown,- UpdatesAvailable: false,- },- })- return- }-- maturity := models.ImageMaturity{- Version: record.CurrentVersion,- Date: record.LastChecked.Format(time.RFC3339),- Status: record.Status,- UpdatesAvailable: record.UpdatesAvailable,- }-- if record.LatestVersion != nil {- maturity.LatestVersion = *record.LatestVersion- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": maturity,- })-}--func (h *ImageMaturityHandler) SetImageMaturity(c *gin.Context) {- imageID := c.Param("imageId")-- var req dto.SetMaturityDto- if err := c.ShouldBindJSON(&req); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid request format",- })- return- }-- maturity := models.ImageMaturity{- Version: req.Version,- Date: req.Date,- Status: req.Status,- UpdatesAvailable: req.UpdatesAvailable,- }-- err := h.imageMaturityService.SetImageMaturity(- c.Request.Context(),- imageID,- req.Repository,- req.Tag,- maturity,- req.Metadata,- )- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to set image maturity",- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "message": "Image maturity updated successfully",- })-}--func (h *ImageMaturityHandler) ListMaturityRecords(c *gin.Context) {- records, err := h.imageMaturityService.ListMaturityRecords(c.Request.Context())- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to list maturity records",- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": records,- })-}--func (h *ImageMaturityHandler) GetImagesWithUpdates(c *gin.Context) {- records, err := h.imageMaturityService.GetImagesWithUpdates(c.Request.Context())- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to get images with updates",- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": records,- })-}--func (h *ImageMaturityHandler) GetMaturityStats(c *gin.Context) {- stats, err := h.imageMaturityService.GetMaturityStats(c.Request.Context())- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to get maturity stats",- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": stats,- })-}--func (h *ImageMaturityHandler) GetImagesNeedingCheck(c *gin.Context) {- maxAgeStr := c.DefaultQuery("maxAge", "1440")- limitStr := c.DefaultQuery("limit", "100")-- maxAge, err := strconv.Atoi(maxAgeStr)- if err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid maxAge parameter",- })- return- }-- limit, err := strconv.Atoi(limitStr)- if err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid limit parameter",- })- return- }-- records, err := h.imageMaturityService.GetImagesNeedingCheck(c.Request.Context(), maxAge, limit)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to get images needing check",- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": records,- })-}--func (h *ImageMaturityHandler) TriggerMaturityCheck(c *gin.Context) {- err := h.imageMaturityService.ProcessImagesForMaturityCheck(c.Request.Context(), h.imageService)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to trigger maturity check",- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "message": "Maturity check triggered successfully",- })-}--func (h *ImageMaturityHandler) GetMaturityByRepository(c *gin.Context) {- repository := c.Param("repository")-- records, err := h.imageMaturityService.GetMaturityByRepository(c.Request.Context(), repository)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to get maturity by repository",- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": records,- })-}--func (h *ImageMaturityHandler) UpdateCheckStatus(c *gin.Context) {- imageID := c.Param("imageId")-- type UpdateStatusRequest struct {- Status string `json:"status" binding:"required"`- Error *string `json:"error,omitempty"`- }-- var req UpdateStatusRequest- if err := c.ShouldBindJSON(&req); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid request format",- })- return- }-- err := h.imageMaturityService.UpdateCheckStatus(c.Request.Context(), imageID, req.Status, req.Error)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to update check status",- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "message": "Check status updated successfully",- })-}--func (h *ImageMaturityHandler) CleanupOrphanedRecords(c *gin.Context) {- type CleanupRequest struct {- ExistingImageIDs []string `json:"existingImageIds" binding:"required"`- }-- var req CleanupRequest- if err := c.ShouldBindJSON(&req); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid request format",- })- return- }-- deletedCount, err := h.imageMaturityService.CleanupOrphanedRecords(c.Request.Context(), req.ExistingImageIDs)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to cleanup orphaned records",- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "deletedCount": deletedCount,- "message": "Orphaned records cleaned up successfully",- })-}--func (h *ImageMaturityHandler) CheckMaturityBatch(c *gin.Context) {- type BatchRequest struct {- ImageIDs []string `json:"imageIds" binding:"required"`- Force bool `json:"force,omitempty"`- }-- var req BatchRequest- if err := c.ShouldBindJSON(&req); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid request format",- })- return- }-- if len(req.ImageIDs) == 0 {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "At least one imageId is required",- })- return- }-- result, err := h.imageMaturityService.CheckMaturityBatch(c.Request.Context(), req.ImageIDs)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to check maturity batch",- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "results": result["results"],- "summary": result["summary"],- "message": "Batch maturity check completed",- })-}diff --git a/backend/internal/api/image_update_handler.go b/backend/internal/api/image_update_handler.gonew file mode 100644index 000000000..fd4e4f267--- /dev/null+++ b/backend/internal/api/image_update_handler.go@@ -0,0 +1,282 @@+package api++import (+ "net/http"+ "strconv"++ "github.com/gin-gonic/gin"+ "github.com/ofkm/arcane-backend/internal/dto"+ "github.com/ofkm/arcane-backend/internal/services"+)++type ImageUpdateHandler struct {+ imageUpdateService *services.ImageUpdateService+}++func NewImageUpdateHandler(imageUpdateService *services.ImageUpdateService) *ImageUpdateHandler {+ return &ImageUpdateHandler{+ imageUpdateService: imageUpdateService,+ }+}++func (h *ImageUpdateHandler) CheckImageUpdate(c *gin.Context) {+ imageRef := c.Query("imageRef")+ if imageRef == "" {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "error": "imageRef query parameter is required",+ })+ return+ }++ result, err := h.imageUpdateService.CheckImageUpdate(c.Request.Context(), imageRef)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "error": "Failed to check image update: " + err.Error(),+ })+ return+ }++ response := &dto.ImageUpdateResponse{+ HasUpdate: result.HasUpdate,+ UpdateType: result.UpdateType,+ CurrentVersion: result.CurrentVersion,+ LatestVersion: result.LatestVersion,+ CurrentDigest: result.CurrentDigest,+ LatestDigest: result.LatestDigest,+ CheckTime: result.CheckTime,+ ResponseTimeMs: result.ResponseTimeMs,+ Error: result.Error,+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": response,+ })+}++func (h *ImageUpdateHandler) CheckImageUpdateByID(c *gin.Context) {+ imageID := c.Param("imageId")+ if imageID == "" {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "error": "imageId parameter is required",+ })+ return+ }++ result, err := h.imageUpdateService.CheckImageUpdateByID(c.Request.Context(), imageID)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "error": "Failed to check image update: " + err.Error(),+ })+ return+ }++ response := &dto.ImageUpdateResponse{+ HasUpdate: result.HasUpdate,+ UpdateType: result.UpdateType,+ CurrentVersion: result.CurrentVersion,+ LatestVersion: result.LatestVersion,+ CurrentDigest: result.CurrentDigest,+ LatestDigest: result.LatestDigest,+ CheckTime: result.CheckTime,+ ResponseTimeMs: result.ResponseTimeMs,+ Error: result.Error,+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": response,+ })+}++func (h *ImageUpdateHandler) CheckMultipleImages(c *gin.Context) {+ var req dto.BatchImageUpdateRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "error": "Invalid request format",+ })+ return+ }++ if len(req.ImageRefs) == 0 {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "error": "At least one imageRef is required",+ })+ return+ }++ results, err := h.imageUpdateService.CheckMultipleImages(c.Request.Context(), req.ImageRefs)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "error": "Failed to check image updates: " + err.Error(),+ })+ return+ }++ response := make(dto.BatchImageUpdateResponse)+ for imageRef, result := range results {+ response[imageRef] = &dto.ImageUpdateResponse{+ HasUpdate: result.HasUpdate,+ UpdateType: result.UpdateType,+ CurrentVersion: result.CurrentVersion,+ LatestVersion: result.LatestVersion,+ CurrentDigest: result.CurrentDigest,+ LatestDigest: result.LatestDigest,+ CheckTime: result.CheckTime,+ ResponseTimeMs: result.ResponseTimeMs,+ Error: result.Error,+ }+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": response,+ })+}++func (h *ImageUpdateHandler) CheckAllImages(c *gin.Context) {+ limitStr := c.DefaultQuery("limit", "50")+ limit, err := strconv.Atoi(limitStr)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "error": "Invalid limit parameter",+ })+ return+ }++ results, err := h.imageUpdateService.CheckAllImages(c.Request.Context(), limit)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "error": "Failed to check all images: " + err.Error(),+ })+ return+ }++ response := make(dto.BatchImageUpdateResponse)+ for imageRef, result := range results {+ response[imageRef] = &dto.ImageUpdateResponse{+ HasUpdate: result.HasUpdate,+ UpdateType: result.UpdateType,+ CurrentVersion: result.CurrentVersion,+ LatestVersion: result.LatestVersion,+ CurrentDigest: result.CurrentDigest,+ LatestDigest: result.LatestDigest,+ CheckTime: result.CheckTime,+ ResponseTimeMs: result.ResponseTimeMs,+ Error: result.Error,+ }+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": response,+ })+}++func (h *ImageUpdateHandler) GetUpdateSummary(c *gin.Context) {+ summary, err := h.imageUpdateService.GetUpdateSummary(c.Request.Context())+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "error": "Failed to get update summary: " + err.Error(),+ })+ return+ }++ response := &dto.ImageUpdateSummaryResponse{+ TotalImages: summary.TotalImages,+ ImagesWithUpdates: summary.ImagesWithUpdates,+ DigestUpdates: summary.DigestUpdates,+ TagUpdates: summary.TagUpdates,+ ErrorsCount: summary.ErrorsCount,+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": response,+ })+}++func (h *ImageUpdateHandler) GetImageVersions(c *gin.Context) {+ imageRef := c.Query("imageRef")+ if imageRef == "" {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "error": "imageRef query parameter is required",+ })+ return+ }++ limitStr := c.DefaultQuery("limit", "20")+ limit, err := strconv.Atoi(limitStr)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "error": "Invalid limit parameter",+ })+ return+ }++ versions, err := h.imageUpdateService.GetAvailableVersions(c.Request.Context(), imageRef, limit)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "error": "Failed to get image versions: " + err.Error(),+ })+ return+ }++ response := &dto.ImageVersionsResponse{+ ImageRef: versions.ImageRef,+ Current: versions.Current,+ Versions: versions.Versions,+ Latest: versions.Latest,+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": response,+ })+}++func (h *ImageUpdateHandler) CompareVersions(c *gin.Context) {+ var req dto.CompareVersionRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "error": "Invalid request format",+ })+ return+ }++ comparison, err := h.imageUpdateService.CompareVersions(c.Request.Context(), req.ImageRef, req.CurrentVersion, req.TargetVersion)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "error": "Failed to compare versions: " + err.Error(),+ })+ return+ }++ response := &dto.VersionComparisonResponse{+ CurrentVersion: comparison.CurrentVersion,+ TargetVersion: comparison.TargetVersion,+ IsNewer: comparison.IsNewer,+ UpdateType: comparison.UpdateType,+ ChangeLevel: comparison.ChangeLevel,+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": response,+ })+}diff --git a/backend/internal/api/routes.go b/backend/internal/api/routes.goindex 5533288e2..a66113423 100644--- a/backend/internal/api/routes.go+++ b/backend/internal/api/routes.go@@ -16,7 +16,7 @@ type Services struct {Image *services.ImageServiceVolume *services.VolumeServiceNetwork *services.NetworkService- ImageMaturity *services.ImageMaturityService+ ImageUpdate *services.ImageUpdateServiceAuth *services.AuthServiceOidc *services.OidcServiceDocker *services.DockerClientService@@ -35,7 +35,6 @@ func SetupRoutes(r *gin.Engine, services *Services, appConfig *config.Config) {setupStackRoutes(api, services)setupEnvironmentRoutes(api, services)setupSettingsRoutes(api, services, appConfig)- setupImageMaturityRoutes(api, services)setupSystemRoutes(api, services.Docker, services)setupContainerRoutes(api, services)setupImageRoutes(api, services)@@ -45,6 +44,7 @@ func SetupRoutes(r *gin.Engine, services *Services, appConfig *config.Config) {setupContainerRegistryRoutes(api, services)setupAutoUpdateRoutes(api, services)setupConverterRoutes(api, services)+ setupImageUpdateRoutes(api, services)}func setupContainerRegistryRoutes(api *gin.RouterGroup, services *Services) {@@ -62,6 +62,20 @@ func setupContainerRegistryRoutes(api *gin.RouterGroup, services *Services) {registries.POST("/:id/test", registryHandler.TestRegistry)}+func setupImageUpdateRoutes(api *gin.RouterGroup, services *Services) {+ imageUpdates := api.Group("/image-updates")+ imageUpdates.Use(middleware.AuthMiddleware(services.Auth))+ imageUpdateHandler := NewImageUpdateHandler(services.ImageUpdate)++ imageUpdates.GET("/check", imageUpdateHandler.CheckImageUpdate)+ imageUpdates.GET("/check/:imageId", imageUpdateHandler.CheckImageUpdateByID)+ imageUpdates.POST("/check-batch", imageUpdateHandler.CheckMultipleImages)+ imageUpdates.GET("/check-all", imageUpdateHandler.CheckAllImages)+ imageUpdates.GET("/summary", imageUpdateHandler.GetUpdateSummary)+ imageUpdates.GET("/versions", imageUpdateHandler.GetImageVersions)+ imageUpdates.POST("/compare", imageUpdateHandler.CompareVersions)+}+func setupAuthRoutes(api *gin.RouterGroup, services *Services, appConfig *config.Config) {auth := api.Group("/auth")@@ -217,21 +231,6 @@ func setupSettingsRoutes(api *gin.RouterGroup, services *Services, appConfig *cosettings.POST("/oidc/callback", oidcHandler.HandleOidcCallback)}-func setupImageMaturityRoutes(api *gin.RouterGroup, services *Services) {- imageMaturity := api.Group("/images/maturity")- imageMaturity.Use(middleware.AuthMiddleware(services.Auth))-- imageMaturityHandler := NewImageMaturityHandler(services.ImageMaturity, services.Image)-- imageMaturity.GET("", imageMaturityHandler.ListMaturityRecords)- imageMaturity.GET("/stats", imageMaturityHandler.GetMaturityStats)- imageMaturity.GET("/updates", imageMaturityHandler.GetImagesWithUpdates)- imageMaturity.GET("/needs-check", imageMaturityHandler.GetImagesNeedingCheck)- imageMaturity.POST("/check", imageMaturityHandler.TriggerMaturityCheck)- imageMaturity.GET("/repository/:repository", imageMaturityHandler.GetMaturityByRepository)- imageMaturity.GET("/:imageId", imageMaturityHandler.GetImageMaturity)-}-func setupSystemRoutes(api *gin.RouterGroup, dockerService *services.DockerClientService, services *Services) {system := api.Group("/system")system.Use(middleware.AuthMiddleware(services.Auth))@@ -283,7 +282,7 @@ func setupImageRoutes(api *gin.RouterGroup, services *Services) {images := api.Group("/images")images.Use(middleware.AuthMiddleware(services.Auth))- imageHandler := NewImageHandler(services.Image, services.ImageMaturity)+ imageHandler := NewImageHandler(services.Image, services.ImageUpdate)images.GET("", imageHandler.List)images.GET("/:id", imageHandler.GetByID)@@ -291,7 +290,6 @@ func setupImageRoutes(api *gin.RouterGroup, services *Services) {images.POST("/pull", imageHandler.Pull)images.POST("/prune", imageHandler.Prune)images.GET("/:id/history", imageHandler.GetHistory)- images.POST("/:id/maturity", imageHandler.CheckMaturity)}func setupVolumeRoutes(api *gin.RouterGroup, services *Services) {diff --git a/backend/internal/api/settings_handler.go b/backend/internal/api/settings_handler.goindex ea1a71fb2..974d2c475 100644--- a/backend/internal/api/settings_handler.go+++ b/backend/internal/api/settings_handler.go@@ -87,9 +87,6 @@ func (h *SettingsHandler) UpdateSettings(c *gin.Context) {if req.BaseServerURL != nil {settings.BaseServerURL = req.BaseServerURL}- if req.MaturityThresholdDays != nil {- settings.MaturityThresholdDays = *req.MaturityThresholdDays- }updatedSettings, err := h.settingsService.UpdateSettings(c.Request.Context(), settings)if err != nil {diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.goindex 496db9a05..6be2d9d91 100644--- a/backend/internal/bootstrap/jobs_bootstrap.go+++ b/backend/internal/bootstrap/jobs_bootstrap.go@@ -18,10 +18,6 @@ func initializeScheduler() (*job.Scheduler, error) {}func registerJobs(appCtx context.Context, scheduler *job.Scheduler, appServices *api.Services) {- if err := job.RegisterImageMaturityJob(appCtx, scheduler, appServices.Settings, appServices.ImageMaturity, appServices.Image); err != nil {- slog.Error("Failed to register image maturity job", slog.Any("error", err))- }-if err := job.RegisterAutoUpdateJob(appCtx, scheduler, appServices.AutoUpdate, appServices.Settings); err != nil {slog.Error("Failed to register auto-update job", slog.Any("error", err))}diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.goindex 59c5f5090..ba059f092 100644--- a/backend/internal/bootstrap/services_bootstrap.go+++ b/backend/internal/bootstrap/services_bootstrap.go@@ -19,10 +19,10 @@ func initializeServices(db *database.DB, cfg *config.Config) (*api.Services, *seenvironmentService := services.NewEnvironmentService(db)containerService := services.NewContainerService(db, dockerClientService)containerRegistry := services.NewContainerRegistryService(db)- imageService := services.NewImageService(db, dockerClientService, containerRegistry)+ imageUpdate := services.NewImageUpdateService(db, settingsService, containerRegistry, dockerClientService)+ imageService := services.NewImageService(db, dockerClientService, containerRegistry, imageUpdate)volumeService := services.NewVolumeService(db, dockerClientService)networkService := services.NewNetworkService(db, dockerClientService)- imageMaturityService := services.NewImageMaturityService(db, settingsService, containerRegistry)templateService := services.NewTemplateService(db)authService := services.NewAuthService(userService, settingsService, cfg.JWTSecret, cfg)oidcService := services.NewOidcService(authService)@@ -38,7 +38,6 @@ func initializeServices(db *database.DB, cfg *config.Config) (*api.Services, *seImage: imageService,Volume: volumeService,Network: networkService,- ImageMaturity: imageMaturityService,Auth: authService,Oidc: oidcService,Docker: dockerClientService,@@ -47,6 +46,7 @@ func initializeServices(db *database.DB, cfg *config.Config) (*api.Services, *seContainerRegistry: containerRegistry,System: systemService,AutoUpdate: autoUpdate,+ ImageUpdate: imageUpdate,}return appServices, dockerClientService, nildiff --git a/backend/internal/database/database.go b/backend/internal/database/database.goindex e10595bf3..707454f46 100644--- a/backend/internal/database/database.go+++ b/backend/internal/database/database.go@@ -90,7 +90,7 @@ func (db *DB) Migrate() error {&models.Image{},&models.Volume{},&models.Network{},- &models.ImageMaturityRecord{},+ &models.ImageUpdateRecord{},&models.TemplateRegistry{},&models.ComposeTemplate{},&models.ContainerRegistry{},diff --git a/backend/internal/dto/image_dto.go b/backend/internal/dto/image_dto.goindex d4b7fa922..05d47a7c1 100644--- a/backend/internal/dto/image_dto.go+++ b/backend/internal/dto/image_dto.go@@ -3,13 +3,3 @@ package dtotype ImagePullDto struct {ImageName string `json:"imageName" binding:"required"`}--type SetMaturityDto struct {- Repository string `json:"repository" binding:"required"`- Tag string `json:"tag" binding:"required"`- Version string `json:"version" binding:"required"`- Date string `json:"date"`- Status string `json:"status" binding:"required"`- UpdatesAvailable bool `json:"updatesAvailable"`- Metadata map[string]interface{} `json:"metadata,omitempty"`-}diff --git a/backend/internal/dto/image_update_dto.go b/backend/internal/dto/image_update_dto.gonew file mode 100644index 000000000..dd0edc535--- /dev/null+++ b/backend/internal/dto/image_update_dto.go@@ -0,0 +1,50 @@+package dto++import "time"++type ImageUpdateResponse struct {+ HasUpdate bool `json:"hasUpdate"`+ UpdateType string `json:"updateType"`+ CurrentVersion string `json:"currentVersion"`+ LatestVersion string `json:"latestVersion,omitempty"`+ CurrentDigest string `json:"currentDigest,omitempty"`+ LatestDigest string `json:"latestDigest,omitempty"`+ CheckTime time.Time `json:"checkTime"`+ ResponseTimeMs int `json:"responseTimeMs"`+ Error string `json:"error,omitempty"`+}++type ImageUpdateSummaryResponse struct {+ TotalImages int `json:"totalImages"`+ ImagesWithUpdates int `json:"imagesWithUpdates"`+ DigestUpdates int `json:"digestUpdates"`+ TagUpdates int `json:"tagUpdates"`+ ErrorsCount int `json:"errorsCount"`+}++type ImageVersionsResponse struct {+ ImageRef string `json:"imageRef"`+ Current string `json:"current"`+ Versions []string `json:"versions"`+ Latest string `json:"latest,omitempty"`+}++type VersionComparisonResponse struct {+ CurrentVersion string `json:"currentVersion"`+ TargetVersion string `json:"targetVersion"`+ IsNewer bool `json:"isNewer"`+ UpdateType string `json:"updateType"`+ ChangeLevel string `json:"changeLevel"`+}++type BatchImageUpdateRequest struct {+ ImageRefs []string `json:"imageRefs" binding:"required"`+}++type BatchImageUpdateResponse map[string]*ImageUpdateResponse++type CompareVersionRequest struct {+ CurrentVersion string `json:"currentVersion" binding:"required"`+ TargetVersion string `json:"targetVersion" binding:"required"`+ ImageRef string `json:"imageRef" binding:"required"`+}diff --git a/backend/internal/dto/settings_dto.go b/backend/internal/dto/settings_dto.goindex 5ec84a602..7ccdc7537 100644--- a/backend/internal/dto/settings_dto.go+++ b/backend/internal/dto/settings_dto.go@@ -3,16 +3,15 @@ package dtoimport "github.com/ofkm/arcane-backend/internal/models"type UpdateSettingsDto struct {- StacksDirectory *string `json:"stacksDirectory,omitempty"`- AutoUpdate *bool `json:"autoUpdate,omitempty"`- AutoUpdateInterval *int `json:"autoUpdateInterval,omitempty"`- PollingEnabled *bool `json:"pollingEnabled,omitempty"`- PollingInterval *int `json:"pollingInterval,omitempty"`- PruneMode *string `json:"pruneMode,omitempty"`- RegistryCredentials *models.JSON `json:"registryCredentials,omitempty"`- TemplateRegistries *models.JSON `json:"templateRegistries,omitempty"`- Auth *models.JSON `json:"auth,omitempty"`- Onboarding *models.JSON `json:"onboarding,omitempty"`- BaseServerURL *string `json:"baseServerUrl,omitempty"`- MaturityThresholdDays *int `json:"maturityThresholdDays,omitempty"`+ StacksDirectory *string `json:"stacksDirectory,omitempty"`+ AutoUpdate *bool `json:"autoUpdate,omitempty"`+ AutoUpdateInterval *int `json:"autoUpdateInterval,omitempty"`+ PollingEnabled *bool `json:"pollingEnabled,omitempty"`+ PollingInterval *int `json:"pollingInterval,omitempty"`+ PruneMode *string `json:"pruneMode,omitempty"`+ RegistryCredentials *models.JSON `json:"registryCredentials,omitempty"`+ TemplateRegistries *models.JSON `json:"templateRegistries,omitempty"`+ Auth *models.JSON `json:"auth,omitempty"`+ Onboarding *models.JSON `json:"onboarding,omitempty"`+ BaseServerURL *string `json:"baseServerUrl,omitempty"`}diff --git a/backend/internal/job/image_maturity_job.go b/backend/internal/job/image_maturity_job.godeleted file mode 100644index 62dae7424..000000000--- a/backend/internal/job/image_maturity_job.go+++ /dev/null@@ -1,84 +0,0 @@-package job--import (- "context"- "fmt"- "log/slog"- "time"-- "github.com/go-co-op/gocron/v2"- "github.com/ofkm/arcane-backend/internal/services"-)--const ImageMaturityJobName = "ImageMaturityCheck"--func RegisterImageMaturityJob(- ctx context.Context,- scheduler *Scheduler,- settingsService *services.SettingsService,- imageMaturityService *services.ImageMaturityService,- imageService *services.ImageService,-) error {- appSettings, err := settingsService.GetSettings(ctx)- if err != nil {- return fmt.Errorf("failed to get settings for image maturity job: %w", err)- }-- if !appSettings.PollingEnabled {- slog.Info("Image maturity polling is disabled in settings. Job not scheduled.", "jobName", ImageMaturityJobName)- return nil- }-- pollingIntervalMinutes := appSettings.PollingInterval- if pollingIntervalMinutes <= 0 {- slog.Warn(- "PollingInterval is not set to a positive value, defaulting image maturity job to 30 minutes",- "jobName", ImageMaturityJobName,- "configuredInterval", pollingIntervalMinutes,- "defaultInterval", 30,- )- pollingIntervalMinutes = 30- }-- slog.Info(- "Preparing to register image maturity job",- "jobName", ImageMaturityJobName,- "intervalMinutes", pollingIntervalMinutes,- )-- taskFunc := func(jobCtx context.Context) error {- slog.Info("Running image maturity check job", "jobName", ImageMaturityJobName)-- err := imageMaturityService.ProcessImagesForMaturityCheck(jobCtx, imageService)- if err != nil {- slog.Error("Image maturity check job failed", "jobName", ImageMaturityJobName, slog.Any("error", err))- return err- }- slog.Info("Image maturity check job completed successfully", "jobName", ImageMaturityJobName)- return nil- }-- jobDefinition := gocron.DurationJob(time.Duration(pollingIntervalMinutes) * time.Minute)-- runImmediately := true-- err = scheduler.RegisterJob(- ctx,- ImageMaturityJobName,- jobDefinition,- taskFunc,- runImmediately,- )-- if err != nil {- return fmt.Errorf("failed to register image maturity job %q: %w", ImageMaturityJobName, err)- }-- slog.Info(- "Image maturity job registered successfully",- "jobName", ImageMaturityJobName,- "intervalMinutes", pollingIntervalMinutes,- "runImmediately", runImmediately,- )- return nil-}diff --git a/backend/internal/models/docker.go b/backend/internal/models/docker.goindex 8499df168..eb6f9b262 100644--- a/backend/internal/models/docker.go+++ b/backend/internal/models/docker.go@@ -84,7 +84,7 @@ type Image struct {Tag string `json:"tag" gorm:"column:tag;index" sortable:"true"`InUse bool `json:"inUse" gorm:"column:in_use;default:false" sortable:"true"`- MaturityRecord *ImageMaturityRecord `json:"maturityRecord,omitempty" gorm:"foreignKey:ID;references:ID"`+ UpdateRecord *ImageUpdateRecord `json:"updateInfo,omitempty" gorm:"foreignKey:ID;references:ID"`BaseModel}diff --git a/backend/internal/models/image_maturity.go b/backend/internal/models/image_maturity.godeleted file mode 100644index a4f170bce..000000000--- a/backend/internal/models/image_maturity.go+++ /dev/null@@ -1,69 +0,0 @@-package models--import (- "fmt"- "time"-)--type ImageMaturityRecord struct {- ID string `json:"id" gorm:"primaryKey;type:text"`- Repository string `json:"repository" gorm:"not null;index"`- Tag string `json:"tag" gorm:"not null;index"`- CurrentVersion string `json:"currentVersion" gorm:"column:current_version"`- LatestVersion *string `json:"latestVersion,omitempty" gorm:"column:latest_version"`- Status string `json:"status" gorm:"not null;index"`- UpdatesAvailable bool `json:"updatesAvailable" gorm:"column:updates_available;default:false"`- CurrentImageDate *time.Time `json:"currentImageDate,omitempty" gorm:"column:current_image_date"`- LatestImageDate *time.Time `json:"latestImageDate,omitempty" gorm:"column:latest_image_date"`- DaysSinceCreation *int `json:"daysSinceCreation,omitempty" gorm:"column:days_since_creation"`- RegistryDomain *string `json:"registryDomain,omitempty" gorm:"column:registry_domain"`- IsPrivateRegistry bool `json:"isPrivateRegistry" gorm:"column:is_private_registry;default:false"`- LastChecked time.Time `json:"lastChecked" gorm:"column:last_checked;not null"`- CheckCount int `json:"checkCount" gorm:"column:check_count;default:0"`- LastError *string `json:"lastError,omitempty" gorm:"column:last_error"`- ResponseTimeMs *int `json:"responseTimeMs,omitempty" gorm:"column:response_time_ms"`-- Image *Image `json:"image,omitempty" gorm:"foreignKey:ID;references:ID"`-- BaseModel-}--func (i *ImageMaturityRecord) TableName() string {- return "image_maturity_table"-}--type ImageMaturity struct {- Version string `json:"version"`- Date string `json:"date"`- Status string `json:"status"`- UpdatesAvailable bool `json:"updatesAvailable"`- LatestVersion string `json:"latestVersion,omitempty"`-}--const (- ImageStatusMatured = "Matured"- ImageStatusNotMatured = "Not Matured"- ImageStatusUnknown = "Unknown"- ImageStatusChecking = "Checking"- ImageStatusError = "Error"-)--func (i *ImageMaturityRecord) IsMatured() bool {- return i.Status == ImageStatusMatured-}--func (i *ImageMaturityRecord) NeedsUpdate() bool {- return i.UpdatesAvailable-}--func (i *ImageMaturityRecord) GetFullImageName() string {- return fmt.Sprintf("%s:%s", i.Repository, i.Tag)-}--func (i *ImageMaturityRecord) GetDaysSinceLastCheck() int {- return int(time.Since(i.LastChecked).Hours() / 24)-}--func (i *ImageMaturityRecord) NeedsCheck(maxAgeHours int) bool {- return time.Since(i.LastChecked).Hours() > float64(maxAgeHours)-}diff --git a/backend/internal/models/image_update.go b/backend/internal/models/image_update.gonew file mode 100644index 000000000..890c1c7f9--- /dev/null+++ b/backend/internal/models/image_update.go@@ -0,0 +1,53 @@+package models++import (+ "time"+)++type ImageUpdateRecord struct {+ ID string `json:"id" gorm:"primaryKey;type:text"`+ Repository string `json:"repository" gorm:"not null;index"`+ Tag string `json:"tag" gorm:"not null;index"`+ HasUpdate bool `json:"hasUpdate" gorm:"column:has_update;default:false"`+ UpdateType string `json:"updateType" gorm:"column:update_type"`+ CurrentVersion string `json:"currentVersion" gorm:"column:current_version"`+ LatestVersion *string `json:"latestVersion,omitempty" gorm:"column:latest_version"`+ CurrentDigest *string `json:"currentDigest,omitempty" gorm:"column:current_digest"`+ LatestDigest *string `json:"latestDigest,omitempty" gorm:"column:latest_digest"`+ CheckTime time.Time `json:"checkTime" gorm:"column:check_time;not null"`+ ResponseTimeMs int `json:"responseTimeMs" gorm:"column:response_time_ms"`+ LastError *string `json:"lastError,omitempty" gorm:"column:last_error"`++ Image *Image `json:"image,omitempty" gorm:"foreignKey:ID;references:ID"`++ BaseModel+}++func (i *ImageUpdateRecord) TableName() string {+ return "image_update_table"+}++type ImageUpdate struct {+ HasUpdate bool `json:"hasUpdate"`+ UpdateType string `json:"updateType"`+ CurrentVersion string `json:"currentVersion"`+ LatestVersion string `json:"latestVersion,omitempty"`+ CheckTime string `json:"checkTime"`+}++const (+ UpdateTypeDigest = "digest"+ UpdateTypeTag = "tag"+)++func (i *ImageUpdateRecord) NeedsUpdate() bool {+ return i.HasUpdate+}++func (i *ImageUpdateRecord) IsDigestUpdate() bool {+ return i.UpdateType == UpdateTypeDigest+}++func (i *ImageUpdateRecord) IsTagUpdate() bool {+ return i.UpdateType == UpdateTypeTag+}diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.goindex 5aa1f7721..0a4bada4f 100644--- a/backend/internal/models/settings.go+++ b/backend/internal/models/settings.go@@ -44,20 +44,19 @@ type Onboarding struct {}type Settings struct {- ID uint `json:"id" gorm:"primaryKey;autoIncrement"`- DockerTLSCert string `json:"dockerTLSCert" gorm:"column:docker_tls_cert"`- StacksDirectory string `json:"stacksDirectory" gorm:"column:stacks_directory;not null"`- AutoUpdate bool `json:"autoUpdate" gorm:"column:auto_update;default:false"`- AutoUpdateInterval int `json:"autoUpdateInterval" gorm:"column:auto_update_interval;default:300"`- PollingEnabled bool `json:"pollingEnabled" gorm:"column:polling_enabled;default:true"`- PollingInterval int `json:"pollingInterval" gorm:"column:polling_interval;default:5"`- PruneMode *string `json:"pruneMode,omitempty" gorm:"column:prune_mode"`- RegistryCredentials JSON `json:"registryCredentials" gorm:"type:text;column:registry_credentials;default:'[]'"`- TemplateRegistries JSON `json:"templateRegistries" gorm:"type:text;column:template_registries;default:'[]'"`- Auth JSON `json:"auth" gorm:"type:text;not null"`- Onboarding JSON `json:"onboarding,omitempty" gorm:"type:text"`- BaseServerURL *string `json:"baseServerUrl,omitempty" gorm:"column:base_server_url"`- MaturityThresholdDays int `json:"maturityThresholdDays" gorm:"column:maturity_threshold_days;default:30"`+ ID uint `json:"id" gorm:"primaryKey;autoIncrement"`+ DockerTLSCert string `json:"dockerTLSCert" gorm:"column:docker_tls_cert"`+ StacksDirectory string `json:"stacksDirectory" gorm:"column:stacks_directory;not null"`+ AutoUpdate bool `json:"autoUpdate" gorm:"column:auto_update;default:false"`+ AutoUpdateInterval int `json:"autoUpdateInterval" gorm:"column:auto_update_interval;default:300"`+ PollingEnabled bool `json:"pollingEnabled" gorm:"column:polling_enabled;default:true"`+ PollingInterval int `json:"pollingInterval" gorm:"column:polling_interval;default:5"`+ PruneMode *string `json:"pruneMode,omitempty" gorm:"column:prune_mode"`+ RegistryCredentials JSON `json:"registryCredentials" gorm:"type:text;column:registry_credentials;default:'[]'"`+ TemplateRegistries JSON `json:"templateRegistries" gorm:"type:text;column:template_registries;default:'[]'"`+ Auth JSON `json:"auth" gorm:"type:text;not null"`+ Onboarding JSON `json:"onboarding,omitempty" gorm:"type:text"`+ BaseServerURL *string `json:"baseServerUrl,omitempty" gorm:"column:base_server_url"`BaseModel}diff --git a/backend/internal/services/auto_update_service.go b/backend/internal/services/auto_update_service.goindex 43e7da46c..b97520d99 100644--- a/backend/internal/services/auto_update_service.go+++ b/backend/internal/services/auto_update_service.go@@ -2,8 +2,6 @@ package servicesimport ("context"- "encoding/base64"- "encoding/json""fmt""log""slices"@@ -12,7 +10,6 @@ import ("time""github.com/docker/docker/api/types/container"- "github.com/docker/docker/api/types/image""github.com/docker/docker/api/types/network""github.com/docker/docker/api/types/registry""github.com/google/uuid"@@ -436,140 +433,78 @@ func (s *AutoUpdateService) checkImageForUpdate(return false, "", nil}- log.Printf("Pulling image to check for updates: %s", imageRef)- if err := s.pullImageWithAuth(ctx, imageRef, settings); err != nil {- return false, "", fmt.Errorf("failed to pull image: %w", err)- }-- newImageID, err := s.getImageID(ctx, imageRef)+ registryUtils := utils.NewRegistryUtils()+ registry, repository, tag, err := registryUtils.SplitImageReference(imageRef)if err != nil {- return false, "", fmt.Errorf("failed to get new image ID: %w", err)- }-- hasUpdate := newImageID != currentImageID- if hasUpdate {- log.Printf("Update available for %s: %s -> %s", imageRef, currentImageID[:12], newImageID[:12])+ return false, "", fmt.Errorf("failed to parse image reference: %w", err)}- return hasUpdate, newImageID, nil-}--func (s *AutoUpdateService) checkStackImagesForUpdates(- ctx context.Context,- stack models.Stack,- settings *models.Settings,-) (bool, map[string]string, error) {- composeContent, _, err := s.stackService.GetStackContent(ctx, stack.ID)+ authURL, err := registryUtils.CheckAuth(ctx, registry)if err != nil {- return false, nil, fmt.Errorf("failed to get stack content: %w", err)- }-- imageRefs := s.extractImageReferences(composeContent)- if len(imageRefs) == 0 {- return false, nil, nil+ return false, "", fmt.Errorf("failed to check registry auth: %w", err)}- hasUpdates := false- imageUpdates := make(map[string]string)-- for serviceName, imageRef := range imageRefs {- if s.isDigestBasedImage(imageRef) {- continue- }-- currentID, _ := s.getImageID(ctx, imageRef)- hasUpdate, newID, err := s.checkImageForUpdate(ctx, imageRef, currentID, settings)+ var token string+ if authURL != "" {+ authConfig, err := s.getAuthConfigForImage(ctx, imageRef)if err != nil {- log.Printf("Error checking image %s: %v", imageRef, err)- continue+ log.Printf("Warning: Failed to get auth config for image %s: %v", imageRef, err)+ // Continue without authentication - may work for public registries}- if hasUpdate {- hasUpdates = true- imageUpdates[serviceName] = fmt.Sprintf("%s@%s", imageRef, newID)+ var creds *utils.RegistryCredentials+ if authConfig != nil {+ creds = &utils.RegistryCredentials{+ Username: authConfig.Username,+ Token: authConfig.Password,+ }}- }- return hasUpdates, imageUpdates, nil-}--func (s *AutoUpdateService) pullImageWithAuth(ctx context.Context, imageRef string, settings *models.Settings) error {- dockerClient, err := s.dockerService.CreateConnection(ctx)- if err != nil {- return fmt.Errorf("failed to connect to Docker: %w", err)+ token, err = registryUtils.GetToken(ctx, authURL, repository, creds)+ if err != nil {+ return false, "", fmt.Errorf("failed to get registry token: %w", err)+ }}- defer dockerClient.Close()- authConfig, err := s.getAuthConfigForImage(ctx, imageRef)+ remoteDigest, err := registryUtils.GetLatestDigest(ctx, registry, repository, tag, token)if err != nil {- log.Printf("Failed to get auth config for %s: %v", imageRef, err)+ return false, "", fmt.Errorf("failed to get remote digest: %w", err)}- pullOptions := image.PullOptions{}- if authConfig != nil {- authJSON, _ := json.Marshal(authConfig)- pullOptions.RegistryAuth = base64.URLEncoding.EncodeToString(authJSON)- }-- reader, err := dockerClient.ImagePull(ctx, imageRef, pullOptions)+ localDigest, err := s.getImageDigest(ctx, imageRef)if err != nil {- return err+ return false, "", fmt.Errorf("failed to get local digest: %w", err)}- defer reader.Close()-- return nil-}-func (s *AutoUpdateService) getAuthConfigForImage(ctx context.Context, imageRef string) (*registry.AuthConfig, error) {- registryDomain := utils.ExtractRegistryDomain(imageRef)- normalizedImageDomain := s.normalizeRegistryURL(registryDomain)-- registries, err := s.registryService.GetAllRegistries(ctx)- if err != nil {- return nil, fmt.Errorf("failed to list registries: %w", err)- }-- for _, reg := range registries {- normalizedRegURL := s.normalizeRegistryURL(reg.URL)- if normalizedRegURL == normalizedImageDomain {- return ®istry.AuthConfig{- Username: reg.Username,- Password: reg.Token,- }, nil- }- }-- return nil, nil-}--func (s *AutoUpdateService) normalizeRegistryURL(url string) string {- url = strings.TrimSpace(url)- url = strings.ToLower(url)-- url = strings.TrimPrefix(url, "https://")- url = strings.TrimPrefix(url, "http://")-- url = strings.TrimSuffix(url, "/")-- if url == "docker.io" || url == "registry-1.docker.io" {- return "docker.io"+ hasUpdate := localDigest != remoteDigest+ if hasUpdate {+ log.Printf("Update available for %s: %s -> %s", imageRef, localDigest[:12], remoteDigest[:12])}- return url+ return hasUpdate, remoteDigest, nil}-func (s *AutoUpdateService) getImageID(ctx context.Context, imageRef string) (string, error) {+func (s *AutoUpdateService) getImageDigest(ctx context.Context, imageRef string) (string, error) {dockerClient, err := s.dockerService.CreateConnection(ctx)if err != nil {return "", fmt.Errorf("failed to connect to Docker: %w", err)}defer dockerClient.Close()- imageInfo, _, err := dockerClient.ImageInspectWithRaw(ctx, imageRef)+ imageInfo, err := dockerClient.ImageInspect(ctx, imageRef)if err != nil {return "", fmt.Errorf("failed to inspect image: %w", err)}+ for _, digest := range imageInfo.RepoDigests {+ if strings.Contains(digest, "@sha256:") {+ parts := strings.Split(digest, "@")+ if len(parts) == 2 {+ return parts[1], nil+ }+ }+ }+return imageInfo.ID, nil}@@ -769,20 +704,6 @@ func (s *AutoUpdateService) extractImageReferences(composeContent string) map[streturn images}-func (s *AutoUpdateService) extractRegistryDomain(imageRef string) string {- parts := strings.Split(imageRef, "/")- if len(parts) < 2 {- return "docker.io"- }-- domain := parts[0]- if strings.Contains(domain, ".") || strings.Contains(domain, ":") {- return domain- }-- return "docker.io"-}-func (s *AutoUpdateService) isDigestBasedImage(imageRef string) bool {return strings.Contains(imageRef, "@sha256:")}@@ -826,11 +747,100 @@ func (s *AutoUpdateService) getContainerName(cnt container.Summary) string {return cnt.ID[:12]}-func contains(slice []string, item string) bool {- for _, s := range slice {- if s == item {- return true+func (s *AutoUpdateService) getAuthConfigForImage(ctx context.Context, imageRef string) (*registry.AuthConfig, error) {+ registryDomain, err := utils.ExtractRegistryDomain(imageRef)+ if err != nil {+ return nil, fmt.Errorf("failed to extract domain: %w", err)+ }+ normalizedImageDomain := s.normalizeRegistryURL(registryDomain)++ registries, err := s.registryService.GetAllRegistries(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to list registries: %w", err)+ }++ for _, reg := range registries {+ normalizedRegURL := s.normalizeRegistryURL(reg.URL)+ if normalizedRegURL == normalizedImageDomain {+ decryptedToken, err := utils.Decrypt(reg.Token)+ if err != nil {+ log.Printf("Failed to decrypt token for registry %s: %v", reg.URL, err)+ continue+ }++ return ®istry.AuthConfig{+ Username: reg.Username,+ Password: decryptedToken,+ }, nil}}- return false++ return nil, nil+}++func (s *AutoUpdateService) normalizeRegistryURL(url string) string {+ url = strings.TrimSpace(url)+ url = strings.ToLower(url)+ url = strings.TrimPrefix(url, "https://")+ url = strings.TrimPrefix(url, "http://")+ url = strings.TrimSuffix(url, "/")++ if url == "docker.io" || url == "registry-1.docker.io" || url == "index.docker.io" {+ return "docker.io"+ }++ return url+}++func (s *AutoUpdateService) checkStackImagesForUpdates(ctx context.Context, stack models.Stack, settings *models.Settings) (bool, map[string]string, error) {+ composeContent, _, err := s.stackService.GetStackContent(ctx, stack.ID)+ if err != nil {+ return false, nil, err+ }++ images := s.extractImageReferences(composeContent)+ hasUpdates := false+ imageUpdates := make(map[string]string)++ // Get current service information to retrieve actual image IDs+ services, err := s.stackService.GetStackServices(ctx, stack.ID)+ if err != nil {+ return false, nil, fmt.Errorf("failed to get stack services: %w", err)+ }++ // Create a map of service name to current image ID for quick lookup+ serviceImageIDs := make(map[string]string)+ for _, svc := range services {+ if svc.Image != "" {+ // Extract the current image ID from the service+ currentImageID, err := s.getImageDigest(ctx, svc.Image)+ if err != nil {+ log.Printf("Warning: Failed to get current image digest for service %s: %v", svc.Name, err)+ continue+ }+ serviceImageIDs[svc.Name] = currentImageID+ }+ }++ for serviceName, imageRef := range images {+ if s.isDigestBasedImage(imageRef) {+ continue+ }++ // Get the current image ID for this service, or use empty string if not found+ currentImageID := serviceImageIDs[serviceName]++ hasUpdate, newDigest, err := s.checkImageForUpdate(ctx, imageRef, currentImageID, settings)+ if err != nil {+ log.Printf("Error checking updates for %s in stack %s: %v", imageRef, stack.Name, err)+ continue+ }++ if hasUpdate {+ hasUpdates = true+ imageUpdates[serviceName] = fmt.Sprintf("%s@%s", imageRef, newDigest)+ }+ }++ return hasUpdates, imageUpdates, nil}diff --git a/backend/internal/services/image_maturity_service.go b/backend/internal/services/image_maturity_service.godeleted file mode 100644index 660fdbb6a..000000000--- a/backend/internal/services/image_maturity_service.go+++ /dev/null@@ -1,733 +0,0 @@-package services--import (- "context"- "encoding/json"- "fmt"- "net/http"- "regexp"- "strconv"- "strings"- "time"-- "github.com/gin-gonic/gin"- "github.com/ofkm/arcane-backend/internal/database"- "github.com/ofkm/arcane-backend/internal/models"- "github.com/ofkm/arcane-backend/internal/utils"- "gorm.io/gorm"-)--type ImageMaturityService struct {- db *database.DB- settingsService *SettingsService- registryService *ContainerRegistryService-}--func NewImageMaturityService(db *database.DB, settingsService *SettingsService, registryService *ContainerRegistryService) *ImageMaturityService {- return &ImageMaturityService{- db: db,- settingsService: settingsService,- registryService: registryService,- }-}--func (s *ImageMaturityService) GetImageMaturity(ctx context.Context, imageID string) (*models.ImageMaturityRecord, error) {- var record models.ImageMaturityRecord- if err := s.db.WithContext(ctx).Where("id = ?", imageID).First(&record).Error; err != nil {- return nil, fmt.Errorf("failed to get image maturity: %w", err)- }- return &record, nil-}--func (s *ImageMaturityService) CheckImageMaturity(ctx context.Context, imageID, repository, tag string, imageCreatedAt time.Time) (*models.ImageMaturity, error) {- settings, err := s.settingsService.GetSettings(ctx)- if err != nil {- return nil, fmt.Errorf("failed to get settings: %w", err)- }-- hasUpdates := false- latestVersion := ""- var checkError error-- registry := s.getRegistryForImage(ctx, repository)- registryManifest, err := s.getImageManifest(ctx, repository, tag, registry)- if err != nil {- checkError = err- } else {- hasUpdates = s.hasTagUpdates(imageCreatedAt, registryManifest.CreatedAt)- }-- if checkError == nil && !s.isSpecialTag(tag) {- allTags, err := s.getImageTags(ctx, repository, registry)- if err == nil {- hasNewerVersions, newerVersion := s.hasNewerVersions(tag, allTags)- if hasNewerVersions {- hasUpdates = true- latestVersion = newerVersion- }- }- }-- // Pass settings to determine status- status := s.determineMaturityStatus(imageCreatedAt, hasUpdates, checkError, settings)-- maturity := &models.ImageMaturity{- Version: tag,- Date: imageCreatedAt.Format(time.RFC3339),- Status: status,- UpdatesAvailable: hasUpdates,- LatestVersion: latestVersion,- }-- // Calculate age for metadata- imageAge := time.Since(imageCreatedAt)- daysSinceCreation := int(imageAge.Hours() / 24)- isMaturedByAge := imageAge > time.Duration(settings.MaturityThresholdDays)*24*time.Hour-- metadata := map[string]interface{}{- "registryDomain": utils.ExtractRegistryDomain(repository),- "isPrivateRegistry": s.isPrivateRegistry(repository),- "currentImageDate": imageCreatedAt,- "daysSinceCreation": daysSinceCreation,- "isMaturedByAge": isMaturedByAge,- "maturityThreshold": settings.MaturityThresholdDays,- }-- if registryManifest != nil {- metadata["latestImageDate"] = registryManifest.CreatedAt- }- if checkError != nil {- metadata["error"] = checkError.Error()- }-- if err := s.SetImageMaturity(ctx, imageID, repository, tag, *maturity, metadata); err != nil {- return nil, fmt.Errorf("failed to save maturity: %w", err)- }-- return maturity, nil-}--func (s *ImageMaturityService) SetImageMaturity(ctx context.Context, imageID, repository, tag string, maturity models.ImageMaturity, metadata map[string]interface{}) error {- now := time.Now()-- record := &models.ImageMaturityRecord{- ID: imageID,- Repository: repository,- Tag: tag,- CurrentVersion: maturity.Version,- Status: maturity.Status,- UpdatesAvailable: maturity.UpdatesAvailable,- LatestVersion: &maturity.LatestVersion,- LastChecked: now,- BaseModel: models.BaseModel{CreatedAt: now},- }-- if registryDomain, ok := metadata["registryDomain"].(string); ok {- record.RegistryDomain = ®istryDomain- }- if isPrivate, ok := metadata["isPrivateRegistry"].(bool); ok {- record.IsPrivateRegistry = isPrivate- }- if responseTime, ok := metadata["responseTimeMs"].(int); ok {- record.ResponseTimeMs = &responseTime- }- if errorMsg, ok := metadata["error"].(string); ok {- record.LastError = &errorMsg- }- if latestVersion, ok := metadata["latestVersion"].(string); ok {- record.LatestVersion = &latestVersion- }- if currentDate, ok := metadata["currentImageDate"].(time.Time); ok {- record.CurrentImageDate = ¤tDate- }- if latestDate, ok := metadata["latestImageDate"].(time.Time); ok {- record.LatestImageDate = &latestDate- }- if days, ok := metadata["daysSinceCreation"].(int); ok {- record.DaysSinceCreation = &days- }-- existing, err := s.GetImageMaturity(ctx, imageID)- if err == nil {- record.CheckCount = existing.CheckCount + 1- record.CreatedAt = existing.CreatedAt- }-- if err := s.db.WithContext(ctx).Save(record).Error; err != nil {- return fmt.Errorf("failed to set image maturity: %w", err)- }-- return nil-}--func (s *ImageMaturityService) getRegistryForImage(ctx context.Context, repository string) *models.ContainerRegistry {- registryDomain := utils.ExtractRegistryDomain(repository)- normalizedImageDomain := s.normalizeRegistryURL(registryDomain)-- registries, err := s.registryService.GetAllRegistries(ctx)- if err != nil {- return nil- }-- for _, reg := range registries {- if !reg.Enabled {- continue- }-- normalizedRegURL := s.normalizeRegistryURL(reg.URL)- if normalizedRegURL == normalizedImageDomain {- return ®- }- }-- return nil-}--func (s *ImageMaturityService) normalizeRegistryURL(url string) string {- url = strings.TrimSpace(url)- url = strings.ToLower(url)-- url = strings.TrimPrefix(url, "https://")- url = strings.TrimPrefix(url, "http://")-- url = strings.TrimSuffix(url, "/")-- if url == "docker.io" || url == "registry-1.docker.io" || url == "index.docker.io" {- return "docker.io"- }-- return url-}--func (s *ImageMaturityService) getImageManifest(ctx context.Context, repository, tag string, registry *models.ContainerRegistry) (*RegistryManifest, error) {- registryURL := s.buildRegistryURL(repository)- normalizedRepo := s.normalizeRepository(repository)-- manifestURL := fmt.Sprintf("%s/v2/%s/manifests/%s", registryURL, normalizedRepo, tag)-- client := &http.Client{Timeout: 30 * time.Second}- req, err := http.NewRequestWithContext(ctx, http.MethodGet, manifestURL, nil)- if err != nil {- return nil, fmt.Errorf("failed to create manifest request: %w", err)- }-- if registry != nil {- token, err := s.getRegistryToken(ctx, repository, registry)- if err == nil && token != "" {- req.Header.Set("Authorization", "Bearer "+token)- }- }-- req.Header.Set("Accept", "application/vnd.docker.distribution.manifest.v2+json")- req.Header.Set("Accept", "application/vnd.docker.distribution.manifest.v1+json")-- resp, err := client.Do(req)- if err != nil {- return nil, fmt.Errorf("failed to get manifest: %w", err)- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("manifest request failed with status: %d", resp.StatusCode)- }-- digest := resp.Header.Get("Docker-Content-Digest")-- var manifest map[string]interface{}- if err := json.NewDecoder(resp.Body).Decode(&manifest); err != nil {- return nil, fmt.Errorf("failed to decode manifest: %w", err)- }-- createdAt := time.Now()- if history, ok := manifest["history"].([]interface{}); ok && len(history) > 0 {- if firstHistory, ok := history[0].(map[string]interface{}); ok {- if v1Compat, ok := firstHistory["v1Compatibility"].(string); ok {- var compat V1Compatibility- if err := json.Unmarshal([]byte(v1Compat), &compat); err == nil {- createdAt = compat.Created- }- }- }- }-- return &RegistryManifest{- Digest: digest,- CreatedAt: createdAt,- }, nil-}--func (s *ImageMaturityService) getImageTags(ctx context.Context, repository string, registry *models.ContainerRegistry) ([]string, error) {- registryURL := s.buildRegistryURL(repository)- normalizedRepo := s.normalizeRepository(repository)-- tagsURL := fmt.Sprintf("%s/v2/%s/tags/list", registryURL, normalizedRepo)-- client := &http.Client{Timeout: 30 * time.Second}- req, err := http.NewRequestWithContext(ctx, http.MethodGet, tagsURL, nil)- if err != nil {- return nil, fmt.Errorf("failed to create tags request: %w", err)- }-- if registry != nil {- token, err := s.getRegistryToken(ctx, repository, registry)- if err == nil && token != "" {- req.Header.Set("Authorization", "Bearer "+token)- }- }-- resp, err := client.Do(req)- if err != nil {- return nil, fmt.Errorf("failed to get tags: %w", err)- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("tags request failed with status: %d", resp.StatusCode)- }-- var tagsResp struct {- Tags []string `json:"tags"`- }- if err := json.NewDecoder(resp.Body).Decode(&tagsResp); err != nil {- return nil, fmt.Errorf("failed to decode tags response: %w", err)- }-- return tagsResp.Tags, nil-}--func (s *ImageMaturityService) getRegistryToken(ctx context.Context, repository string, registry *models.ContainerRegistry) (string, error) {- domain := s.extractRegistryDomain(repository)-- switch domain {- case "docker.io", "registry-1.docker.io", "index.docker.io":- return utils.GetDockerHubToken(ctx, repository)- default:- if registry != nil {- creds := &utils.RegistryCredentials{- Username: registry.Username,- Token: registry.Token,- }- return utils.GetRegistryToken(ctx, domain, repository, creds)- }- return utils.GetGenericRegistryToken(ctx, domain, repository)- }-}--func (s *ImageMaturityService) buildRegistryURL(repository string) string {- domain := utils.ExtractRegistryDomain(repository)-- if domain == "docker.io" {- return "https://registry-1.docker.io"- }-- if !strings.HasPrefix(domain, "http") {- return "https://" + domain- }-- return domain-}--func (s *ImageMaturityService) normalizeRepository(repository string) string {- domain := utils.ExtractRegistryDomain(repository)-- if domain == "docker.io" {- if !strings.Contains(repository, "/") {- return "library/" + repository- }-- if utils.ExtractRegistryDomain(repository) == "docker.io" || utils.ExtractRegistryDomain(repository) == "registry-1.docker.io" {- repoWithoutRegistry := strings.TrimPrefix(repository, utils.ExtractRegistryDomain(repository)+"/")- if !strings.Contains(repoWithoutRegistry, "/") {- return "library/" + repoWithoutRegistry- }- return repoWithoutRegistry- }- }-- return repository-}--func (s *ImageMaturityService) extractRegistryDomain(repository string) string {- if !strings.Contains(repository, "/") {- return "docker.io"- }-- parts := strings.Split(repository, "/")- domain := parts[0]-- if strings.Contains(domain, ".") || strings.Contains(domain, ":") {- return domain- }-- return "docker.io"-}--func (s *ImageMaturityService) isPrivateRegistry(repository string) bool {- domain := utils.ExtractRegistryDomain(repository)- publicRegistries := []string{"docker.io", "registry-1.docker.io", "index.docker.io", "ghcr.io", "quay.io", "gcr.io"}-- for _, public := range publicRegistries {- if domain == public {- return false- }- }- return true-}--func (s *ImageMaturityService) hasTagUpdates(currentImageCreated, registryImageCreated time.Time) bool {- return registryImageCreated.After(currentImageCreated)-}--func (s *ImageMaturityService) hasNewerVersions(currentTag string, allTags []string) (bool, string) {- if s.isSpecialTag(currentTag) {- return false, ""- }-- currentPattern := s.getTagPattern(currentTag)- if currentPattern.Version == "" {- return false, ""- }-- var newestVersion string- var newestTag string- hasNewer := false-- for _, tag := range allTags {- if tag == currentTag {- continue- }-- tagPattern := s.getTagPattern(tag)- if tagPattern.Pattern != currentPattern.Pattern || tagPattern.Version == "" {- continue- }-- if s.isNewerVersion(tagPattern.Version, currentPattern.Version) {- if !hasNewer || (newestVersion != "" && s.isNewerVersion(tagPattern.Version, newestVersion)) {- newestVersion = tagPattern.Version- newestTag = tag- hasNewer = true- }- }- }-- return hasNewer, newestTag-}--func (s *ImageMaturityService) determineMaturityStatus(imageCreatedAt time.Time, hasUpdates bool, checkError error, settings *models.Settings) string {- maturityThresholdDays := settings.MaturityThresholdDays- if maturityThresholdDays == 0 {- maturityThresholdDays = 30 // Default fallback- }-- imageAge := time.Since(imageCreatedAt)- isMaturedByAge := imageAge > time.Duration(maturityThresholdDays)*24*time.Hour-- // If there's a check error, return Unknown- if checkError != nil {- return models.ImageStatusUnknown- }-- // If image is matured by age threshold, it's matured regardless of updates- if isMaturedByAge {- return models.ImageStatusMatured- }-- // If image hasn't reached maturity threshold but has updates, it's still not matured- if hasUpdates {- return models.ImageStatusNotMatured- }-- // Image is within threshold and no updates available- return models.ImageStatusNotMatured-}--func (s *ImageMaturityService) isSpecialTag(tag string) bool {- specialTags := []string{- "latest", "stable", "unstable", "dev", "devel", "development",- "test", "testing", "prod", "production", "main", "master",- "stage", "staging", "canary", "nightly", "edge", "next",- }-- for _, special := range specialTags {- if tag == special {- return true- }- }- return false-}--func (s *ImageMaturityService) getTagPattern(tag string) struct{ Pattern, Version string } {- if matches := regexp.MustCompile(`^(\d+)\.(\d+)(?:\.(\d+))?$`).FindStringSubmatch(tag); matches != nil {- majorVersion := matches[1]- return struct{ Pattern, Version string }{Pattern: majorVersion, Version: tag}- }-- if matches := regexp.MustCompile(`^([a-z][\w-]*?)[.-]?(\d+(?:\.\d+)*)$`).FindStringSubmatch(tag); matches != nil {- prefix := matches[1]- version := matches[2]- versionParts := strings.Split(version, ".")- if len(versionParts) > 0 {- majorVersion := versionParts[0]- return struct{ Pattern, Version string }{Pattern: prefix + "-" + majorVersion, Version: version}- }- return struct{ Pattern, Version string }{Pattern: prefix, Version: version}- }-- if matches := regexp.MustCompile(`^(\d+(?:\.\d+)*)$`).FindStringSubmatch(tag); matches != nil {- version := matches[1]- versionParts := strings.Split(version, ".")- if len(versionParts) > 0 {- majorVersion := versionParts[0]- return struct{ Pattern, Version string }{Pattern: "v" + majorVersion, Version: version}- }- return struct{ Pattern, Version string }{Pattern: "version", Version: version}- }-- return struct{ Pattern, Version string }{Pattern: tag, Version: ""}-}--func (s *ImageMaturityService) isNewerVersion(newer, current string) bool {- newerParts := s.parseVersion(newer)- currentParts := s.parseVersion(current)-- maxLen := len(newerParts)- if len(currentParts) > maxLen {- maxLen = len(currentParts)- }-- for i := 0; i < maxLen; i++ {- newerVal := 0- currentVal := 0-- if i < len(newerParts) {- newerVal = newerParts[i]- }- if i < len(currentParts) {- currentVal = currentParts[i]- }-- if newerVal > currentVal {- return true- }- if newerVal < currentVal {- return false- }- }-- return false-}--func (s *ImageMaturityService) parseVersion(version string) []int {- parts := strings.Split(version, ".")- result := make([]int, 0, len(parts))-- for _, part := range parts {- if num, err := strconv.Atoi(strings.TrimSpace(part)); err == nil {- result = append(result, num)- }- }-- return result-}--func (s *ImageMaturityService) ProcessImagesForMaturityCheck(ctx context.Context, imageService *ImageService) error {- dockerImages, err := imageService.ListImages(ctx)- if err != nil {- return fmt.Errorf("failed to list Docker images: %w", err)- }-- for _, img := range dockerImages {- if len(img.RepoTags) == 0 || img.RepoTags[0] == "<none>:<none>" {- continue- }-- repoTag := img.RepoTags[0]- parts := strings.Split(repoTag, ":")- if len(parts) != 2 {- continue- }- repo := parts[0]- tag := parts[1]-- imageCreatedAt := time.Unix(img.Created, 0)- _, err := s.CheckImageMaturity(ctx, img.ID, repo, tag, imageCreatedAt)- if err != nil {- continue- }- }-- return nil-}--func (s *ImageMaturityService) MarkAsMatured(ctx context.Context, imageID string, daysSinceCreation int) error {- updates := map[string]interface{}{- "status": models.ImageStatusMatured,- "days_since_creation": daysSinceCreation,- "last_checked": time.Now(),- "updated_at": time.Now(),- }-- if err := s.db.WithContext(ctx).Model(&models.ImageMaturityRecord{}).- Where("id = ?", imageID).- Updates(updates).Error; err != nil {- return fmt.Errorf("failed to mark image as matured: %w", err)- }-- return nil-}--func (s *ImageMaturityService) ListMaturityRecords(ctx context.Context) ([]*models.ImageMaturityRecord, error) {- var records []*models.ImageMaturityRecord- if err := s.db.WithContext(ctx).Find(&records).Error; err != nil {- return nil, fmt.Errorf("failed to list maturity records: %w", err)- }- return records, nil-}--func (s *ImageMaturityService) GetImagesWithUpdates(ctx context.Context) ([]*models.ImageMaturityRecord, error) {- var records []*models.ImageMaturityRecord- if err := s.db.WithContext(ctx).- Where("updates_available = ?", true).- Order("last_checked DESC").- Find(&records).Error; err != nil {- return nil, fmt.Errorf("failed to get images with updates: %w", err)- }- return records, nil-}--func (s *ImageMaturityService) GetMaturityStats(ctx context.Context) (map[string]interface{}, error) {- var total int64- var withUpdates int64- var matured int64- var notMatured int64-- s.db.WithContext(ctx).Model(&models.ImageMaturityRecord{}).Count(&total)- s.db.WithContext(ctx).Model(&models.ImageMaturityRecord{}).Where("updates_available = ?", true).Count(&withUpdates)- s.db.WithContext(ctx).Model(&models.ImageMaturityRecord{}).Where("status = ?", models.ImageStatusMatured).Count(&matured)- s.db.WithContext(ctx).Model(&models.ImageMaturityRecord{}).Where("status = ?", models.ImageStatusNotMatured).Count(¬Matured)-- return map[string]interface{}{- "total": total,- "withUpdates": withUpdates,- "matured": matured,- "notMatured": notMatured,- }, nil-}--func (s *ImageMaturityService) GetImagesNeedingCheck(ctx context.Context, maxAge int, limit int) ([]*models.ImageMaturityRecord, error) {- cutoff := time.Now().Add(-time.Duration(maxAge) * time.Minute)- var records []*models.ImageMaturityRecord-- if err := s.db.WithContext(ctx).- Where("last_checked < ?", cutoff).- Order("last_checked ASC").- Limit(limit).- Find(&records).Error; err != nil {- return nil, fmt.Errorf("failed to get images needing check: %w", err)- }-- return records, nil-}--func (s *ImageMaturityService) GetMaturityByRepository(ctx context.Context, repository string) ([]*models.ImageMaturityRecord, error) {- var records []*models.ImageMaturityRecord- if err := s.db.WithContext(ctx).- Where("repository = ?", repository).- Order("tag ASC").- Find(&records).Error; err != nil {- return nil, fmt.Errorf("failed to get maturity by repository: %w", err)- }- return records, nil-}--func (s *ImageMaturityService) UpdateCheckStatus(ctx context.Context, imageID string, status string, errorMsg *string) error {- updates := map[string]interface{}{- "status": status,- "last_checked": time.Now(),- "updated_at": time.Now(),- }-- if errorMsg != nil {- updates["last_error"] = *errorMsg- } else {- updates["last_error"] = nil- }-- if err := s.db.WithContext(ctx).Model(&models.ImageMaturityRecord{}).- Where("id = ?", imageID).- Updates(updates).Error; err != nil {- return fmt.Errorf("failed to update check status: %w", err)- }-- return nil-}--func (s *ImageMaturityService) CleanupOrphanedRecords(ctx context.Context, existingImageIDs []string) (int64, error) {- var result *gorm.DB- if len(existingImageIDs) == 0 {- result = s.db.WithContext(ctx).Delete(&models.ImageMaturityRecord{})- } else {- result = s.db.WithContext(ctx).Where("id NOT IN ?", existingImageIDs).Delete(&models.ImageMaturityRecord{})- }-- if result.Error != nil {- return 0, fmt.Errorf("failed to cleanup orphaned records: %w", result.Error)- }-- return result.RowsAffected, nil-}--func (s *ImageMaturityService) CheckMaturityBatch(ctx context.Context, imageIDs []string) (map[string]interface{}, error) {- results := make(map[string]interface{})- successCount := 0-- for _, imageID := range imageIDs {- updates := map[string]interface{}{- "status": models.ImageStatusChecking,- "last_checked": time.Now(),- "updated_at": time.Now(),- }-- err := s.db.WithContext(ctx).- Model(&models.ImageMaturityRecord{}).- Where("id = ?", imageID).- Updates(updates).Error- if err != nil {- results[imageID] = gin.H{- "success": false,- "error": err.Error(),- }- } else {- results[imageID] = gin.H{- "success": true,- "status": models.ImageStatusChecking,- "checked_at": time.Now(),- }- successCount++- }- }-- return map[string]interface{}{- "results": results,- "summary": map[string]interface{}{- "total": len(imageIDs),- "successful": successCount,- "failed": len(imageIDs) - successCount,- },- }, nil-}--type RegistryManifest struct {- Digest string- CreatedAt time.Time- Size int64-}--type ManifestV1History struct {- V1Compatibility string `json:"v1Compatibility"`-}--type V1Compatibility struct {- Created time.Time `json:"created"`-}diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.goindex 5cfcbdd15..3e7c4471a 100644--- a/backend/internal/services/image_service.go+++ b/backend/internal/services/image_service.go@@ -25,17 +25,18 @@ import ()type ImageService struct {- db *database.DB- dockerService *DockerClientService- imageMaturityService *ImageMaturityService- registryService *ContainerRegistryService+ db *database.DB+ dockerService *DockerClientService+ imageUpdateService *ImageUpdateService+ registryService *ContainerRegistryService}-func NewImageService(db *database.DB, dockerService *DockerClientService, registryService *ContainerRegistryService) *ImageService {+func NewImageService(db *database.DB, dockerService *DockerClientService, registryService *ContainerRegistryService, imageUpdateService *ImageUpdateService) *ImageService {return &ImageService{- db: db,- dockerService: dockerService,- registryService: registryService,+ db: db,+ dockerService: dockerService,+ registryService: registryService,+ imageUpdateService: imageUpdateService,}}@@ -224,7 +225,6 @@ func (s *ImageService) extractRegistryHost(imageRef string) string {return "docker.io"}-// isRegistryMatch checks if a credential URL matches a registry hostfunc (s *ImageService) isRegistryMatch(credURL, registryHost string) bool {normalizedCred := s.normalizeRegistryForComparison(credURL)normalizedHost := s.normalizeRegistryForComparison(registryHost)@@ -232,7 +232,6 @@ func (s *ImageService) isRegistryMatch(credURL, registryHost string) bool {return normalizedCred == normalizedHost}-// normalizeRegistryForComparison normalizes registry URLs for comparisonfunc (s *ImageService) normalizeRegistryForComparison(url string) string {url = strings.TrimPrefix(url, "https://")url = strings.TrimPrefix(url, "http://")@@ -245,7 +244,6 @@ func (s *ImageService) normalizeRegistryForComparison(url string) string {return url}-// normalizeRegistryURL normalizes registry URL for Docker clientfunc (s *ImageService) normalizeRegistryURL(url string) string {normalized := s.normalizeRegistryForComparison(url)if normalized == "docker.io" {@@ -433,29 +431,22 @@ func (s *ImageService) GetImagesByRepository(ctx context.Context, repo string) (return images, nil}-func (s *ImageService) ListImagesWithMaturity(ctx context.Context) ([]*models.Image, error) {- _, err := s.ListImages(ctx)- if err != nil {- return nil, fmt.Errorf("failed to list and sync Docker images: %w", err)- }-- var images []*models.Image- if err := s.db.WithContext(ctx).Preload("MaturityRecord").Find(&images).Error; err != nil {- return nil, fmt.Errorf("failed to get images with maturity data from DB: %w", err)- }-- return images, nil-}--func (s *ImageService) UpdateImageMaturity(ctx context.Context, imageID string, maturityData *models.ImageMaturityRecord) error {+func (s *ImageService) UpdateImageUpdate(ctx context.Context, imageID string, updateData *models.ImageUpdateRecord) error {var image models.Imageif err := s.db.WithContext(ctx).Where("id = ?", imageID).First(&image).Error; err != nil {return fmt.Errorf("image not found in database: %w", err)}- maturityData.ID = imageID- if err := s.db.WithContext(ctx).Where("id = ?", imageID).FirstOrCreate(maturityData).Error; err != nil {- return fmt.Errorf("failed to update image maturity: %w", err)+ updateData.ID = imageID+ if err := s.db.WithContext(ctx).Clauses(clause.OnConflict{+ Columns: []clause.Column{{Name: "id"}},+ DoUpdates: clause.AssignmentColumns([]string{+ "repository", "tag", "has_update", "update_type",+ "current_version", "latest_version", "current_digest",+ "latest_digest", "check_time", "response_time_ms", "last_error",+ }),+ }).Create(updateData).Error; err != nil {+ return fmt.Errorf("failed to update image update record: %w", err)}return nil@@ -477,49 +468,34 @@ func (s *ImageService) GetImagesNeedingMaturityCheck(ctx context.Context, olderTreturn images, nil}-func (s *ImageService) GetImagesWithMaturity(ctx context.Context) ([]map[string]interface{}, error) {- images, err := s.dockerService.CreateConnection(ctx)- if err != nil {- return nil, fmt.Errorf("failed to connect to Docker: %w", err)- }- defer images.Close()+func (s *ImageService) GetImagesNeedingUpdateCheck(ctx context.Context, olderThan time.Duration) ([]*models.Image, error) {+ cutoff := time.Now().Add(-olderThan)- dockerImages, err := images.ImageList(ctx, image.ListOptions{})- if err != nil {- return nil, fmt.Errorf("failed to list images: %w", err)- }+ var images []*models.Image+ query := s.db.WithContext(ctx).+ Preload("UpdateRecord").+ Where("repo != ? AND tag != ?", "<none>", "<none>").+ Where("id NOT IN (SELECT id FROM image_update_table WHERE check_time > ?)", cutoff)- var result []map[string]interface{}+ if err := query.Find(&images).Error; err != nil {+ return nil, fmt.Errorf("failed to get images needing update check: %w", err)+ }- for _, img := range dockerImages {- imageData := map[string]interface{}{- "Id": img.ID,- "ParentId": img.ParentID,- "RepoTags": img.RepoTags,- "RepoDigests": img.RepoDigests,- "Created": img.Created,- "Size": img.Size,- "SharedSize": img.SharedSize,- "Labels": img.Labels,- "Containers": img.Containers,- }+ return images, nil+}- if s.imageMaturityService != nil {- maturityRecord, err := s.imageMaturityService.GetImageMaturity(ctx, img.ID)- if err == nil {- imageData["maturity"] = map[string]interface{}{- "updatesAvailable": maturityRecord.UpdatesAvailable,- "status": maturityRecord.Status,- "version": maturityRecord.CurrentVersion,- "date": maturityRecord.CurrentImageDate,- }- }- }+func (s *ImageService) ListImagesWithUpdates(ctx context.Context) ([]*models.Image, error) {+ _, err := s.ListImages(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to list and sync Docker images: %w", err)+ }- result = append(result, imageData)+ var images []*models.Image+ if err := s.db.WithContext(ctx).Preload("UpdateRecord").Find(&images).Error; err != nil {+ return nil, fmt.Errorf("failed to get images with update data from DB: %w", err)}- return result, nil+ return images, nil}func (s *ImageService) DeleteImageByDockerID(ctx context.Context, dockerImageID string) error {@@ -539,14 +515,14 @@ func (s *ImageService) DeleteImageByDockerID(ctx context.Context, dockerImageIDreturn nil}-func (s *ImageService) ListImagesWithMaturityPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]map[string]interface{}, utils.PaginationResponse, error) {+func (s *ImageService) ListImagesWithUpdatesPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]map[string]interface{}, utils.PaginationResponse, error) {_, err := s.ListImages(ctx)if err != nil {return nil, utils.PaginationResponse{}, fmt.Errorf("failed to list and sync Docker images: %w", err)}var images []*models.Image- query := s.db.WithContext(ctx).Model(&models.Image{}).Preload("MaturityRecord")+ query := s.db.WithContext(ctx).Model(&models.Image{}).Preload("UpdateRecord")pagination, err := utils.PaginateAndSort(req, query, &images)if err != nil {@@ -568,12 +544,17 @@ func (s *ImageService) ListImagesWithMaturityPaginated(ctx context.Context, req"Tag": img.Tag,}- if img.MaturityRecord != nil {- imageData["maturity"] = map[string]interface{}{- "updatesAvailable": img.MaturityRecord.UpdatesAvailable,- "status": img.MaturityRecord.Status,- "version": img.MaturityRecord.CurrentVersion,- "date": img.MaturityRecord.CurrentImageDate,+ if img.UpdateRecord != nil {+ imageData["updateInfo"] = map[string]interface{}{+ "hasUpdate": img.UpdateRecord.HasUpdate,+ "updateType": img.UpdateRecord.UpdateType,+ "currentVersion": img.UpdateRecord.CurrentVersion,+ "latestVersion": img.UpdateRecord.LatestVersion,+ "currentDigest": img.UpdateRecord.CurrentDigest,+ "latestDigest": img.UpdateRecord.LatestDigest,+ "checkTime": img.UpdateRecord.CheckTime,+ "responseTimeMs": img.UpdateRecord.ResponseTimeMs,+ "error": img.UpdateRecord.LastError,}}@@ -582,3 +563,18 @@ func (s *ImageService) ListImagesWithMaturityPaginated(ctx context.Context, reqreturn result, pagination, nil}++func (s *ImageService) CleanupOrphanedUpdateRecords(ctx context.Context, existingImageIDs []string) (int64, error) {+ var result *gorm.DB+ if len(existingImageIDs) == 0 {+ result = s.db.WithContext(ctx).Delete(&models.ImageUpdateRecord{})+ } else {+ result = s.db.WithContext(ctx).Where("id NOT IN ?", existingImageIDs).Delete(&models.ImageUpdateRecord{})+ }++ if result.Error != nil {+ return 0, fmt.Errorf("failed to cleanup orphaned update records: %w", result.Error)+ }++ return result.RowsAffected, nil+}diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.gonew file mode 100644index 000000000..c64b06219--- /dev/null+++ b/backend/internal/services/image_update_service.go@@ -0,0 +1,837 @@+package services++import (+ "context"+ "fmt"+ "strconv"+ "strings"+ "time"++ "github.com/docker/docker/api/types/image"+ "github.com/ofkm/arcane-backend/internal/database"+ "github.com/ofkm/arcane-backend/internal/models"+ "github.com/ofkm/arcane-backend/internal/utils"+)++type ImageUpdateService struct {+ db *database.DB+ settingsService *SettingsService+ registryService *ContainerRegistryService+ dockerService *DockerClientService+}++type UpdateResult struct {+ HasUpdate bool `json:"hasUpdate"`+ UpdateType string `json:"updateType"` // "tag" or "digest"+ CurrentVersion string `json:"currentVersion"`+ LatestVersion string `json:"latestVersion,omitempty"`+ CurrentDigest string `json:"currentDigest,omitempty"`+ LatestDigest string `json:"latestDigest,omitempty"`+ CheckTime time.Time `json:"checkTime"`+ ResponseTimeMs int `json:"responseTimeMs"`+ Error string `json:"error,omitempty"`+}++type UpdateSummary struct {+ TotalImages int `json:"totalImages"`+ ImagesWithUpdates int `json:"imagesWithUpdates"`+ DigestUpdates int `json:"digestUpdates"`+ TagUpdates int `json:"tagUpdates"`+ ErrorsCount int `json:"errorsCount"`+}++type ImageParts struct {+ Registry string+ Repository string+ Tag string+}++type VersionInfo struct {+ Major *int `json:"major"`+ Minor *int `json:"minor"`+ Patch *int `json:"patch"`+ FormatStr string `json:"formatStr"`+}++type VersionComparison struct {+ CurrentVersion string `json:"currentVersion"`+ TargetVersion string `json:"targetVersion"`+ IsNewer bool `json:"isNewer"`+ UpdateType string `json:"updateType"`+ ChangeLevel string `json:"changeLevel"`+}++type AvailableVersions struct {+ ImageRef string `json:"imageRef"`+ Current string `json:"current"`+ Versions []string `json:"versions"`+ Latest string `json:"latest,omitempty"`+}++func NewImageUpdateService(db *database.DB, settingsService *SettingsService, registryService *ContainerRegistryService, dockerService *DockerClientService) *ImageUpdateService {+ return &ImageUpdateService{+ db: db,+ settingsService: settingsService,+ registryService: registryService,+ dockerService: dockerService,+ }+}++func (s *ImageUpdateService) CheckImageUpdate(ctx context.Context, imageRef string) (*UpdateResult, error) {+ startTime := time.Now()++ parts := s.parseImageReference(imageRef)+ if parts == nil {+ return &UpdateResult{+ Error: "Invalid image reference format",+ CheckTime: time.Now(),+ ResponseTimeMs: int(time.Since(startTime).Milliseconds()),+ }, nil+ }++ registry := s.getRegistryForImage(ctx, parts.Registry)++ digestResult, err := s.checkDigestUpdate(ctx, parts, registry)+ if err != nil {+ result := &UpdateResult{+ Error: err.Error(),+ CheckTime: time.Now(),+ ResponseTimeMs: int(time.Since(startTime).Milliseconds()),+ }+ s.saveUpdateResult(ctx, imageRef, result)+ return result, nil+ }++ if !digestResult.HasUpdate && !s.isSpecialTag(parts.Tag) {+ tagResult, err := s.checkTagUpdate(ctx, parts, registry)+ if err != nil {+ result := &UpdateResult{+ Error: err.Error(),+ CheckTime: time.Now(),+ ResponseTimeMs: int(time.Since(startTime).Milliseconds()),+ }+ s.saveUpdateResult(ctx, imageRef, result)+ return result, nil+ }+ if tagResult.HasUpdate {+ tagResult.ResponseTimeMs = int(time.Since(startTime).Milliseconds())+ s.saveUpdateResult(ctx, imageRef, tagResult)+ return tagResult, nil+ }+ }++ digestResult.ResponseTimeMs = int(time.Since(startTime).Milliseconds())+ s.saveUpdateResult(ctx, imageRef, digestResult)+ return digestResult, nil+}++func (s *ImageUpdateService) getRegistryToken(ctx context.Context, registry, repository string, reg *models.ContainerRegistry) (string, error) {+ registryUtils := utils.NewRegistryUtils()++ authURL, err := registryUtils.CheckAuth(ctx, registry)+ if err != nil {+ return "", fmt.Errorf("failed to check auth: %w", err)+ }++ if authURL == "" {+ return "", nil+ }++ var creds *utils.RegistryCredentials+ if reg != nil && reg.Username != "" && reg.Token != "" {+ creds = &utils.RegistryCredentials{+ Username: reg.Username,+ Token: reg.Token,+ }+ }++ return registryUtils.GetToken(ctx, authURL, repository, creds)+}++func (s *ImageUpdateService) checkDigestUpdate(ctx context.Context, parts *ImageParts, registry *models.ContainerRegistry) (*UpdateResult, error) {+ startTime := time.Now()+ registryUtils := utils.NewRegistryUtils()++ token, err := s.getRegistryToken(ctx, parts.Registry, parts.Repository, registry)+ if err != nil {+ return nil, fmt.Errorf("failed to get registry token: %w", err)+ }++ normalizedRepo := s.normalizeRepository(parts.Registry, parts.Repository)+ remoteDigest, err := registryUtils.GetLatestDigest(ctx, parts.Registry, normalizedRepo, parts.Tag, token)+ if err != nil {+ return nil, fmt.Errorf("failed to get remote digest: %w", err)+ }++ localDigest, err := s.getLocalImageDigest(ctx, fmt.Sprintf("%s/%s:%s", parts.Registry, parts.Repository, parts.Tag))+ if err != nil {+ return nil, fmt.Errorf("failed to get local digest: %w", err)+ }++ hasUpdate := localDigest != remoteDigest++ return &UpdateResult{+ HasUpdate: hasUpdate,+ UpdateType: "digest",+ CurrentDigest: localDigest,+ LatestDigest: remoteDigest,+ CheckTime: time.Now(),+ ResponseTimeMs: int(time.Since(startTime).Milliseconds()),+ }, nil+}++func (s *ImageUpdateService) checkTagUpdate(ctx context.Context, parts *ImageParts, registry *models.ContainerRegistry) (*UpdateResult, error) {+ startTime := time.Now()++ currentVersion := s.parseVersion(parts.Tag)+ if currentVersion == nil {+ return &UpdateResult{+ HasUpdate: false,+ UpdateType: "tag",+ CurrentVersion: parts.Tag,+ CheckTime: time.Now(),+ ResponseTimeMs: int(time.Since(startTime).Milliseconds()),+ }, nil+ }++ tags, err := s.getImageTags(ctx, parts, registry)+ if err != nil {+ return nil, fmt.Errorf("failed to get tags: %w", err)+ }++ latestVersion := s.findLatestCompatibleVersion(currentVersion, tags)+ if latestVersion == nil {+ return &UpdateResult{+ HasUpdate: false,+ UpdateType: "tag",+ CurrentVersion: parts.Tag,+ CheckTime: time.Now(),+ ResponseTimeMs: int(time.Since(startTime).Milliseconds()),+ }, nil+ }++ hasUpdate := s.isNewerVersion(latestVersion, currentVersion)++ return &UpdateResult{+ HasUpdate: hasUpdate,+ UpdateType: "tag",+ CurrentVersion: parts.Tag,+ LatestVersion: s.versionToString(latestVersion),+ CheckTime: time.Now(),+ ResponseTimeMs: int(time.Since(startTime).Milliseconds()),+ }, nil+}++func (s *ImageUpdateService) getImageTags(ctx context.Context, parts *ImageParts, registry *models.ContainerRegistry) ([]string, error) {+ registryUtils := utils.NewRegistryUtils()++ token, err := s.getRegistryToken(ctx, parts.Registry, parts.Repository, registry)+ if err != nil {+ return nil, fmt.Errorf("failed to get registry token: %w", err)+ }++ normalizedRepo := s.normalizeRepository(parts.Registry, parts.Repository)+ return registryUtils.GetImageTags(ctx, parts.Registry, normalizedRepo, token)+}++func (s *ImageUpdateService) parseVersion(tag string) *VersionInfo {+ // Handle semantic versioning patterns+ if matches := utils.SemanticVersionRegex.FindStringSubmatch(tag); matches != nil {+ major, _ := strconv.Atoi(matches[1])+ minor, _ := strconv.Atoi(matches[2])+ patch, _ := strconv.Atoi(matches[3])++ return &VersionInfo{+ Major: &major,+ Minor: &minor,+ Patch: &patch,+ FormatStr: "semantic",+ }+ }++ // Handle date-based versioning (YYYY.MM.DD)+ if matches := utils.DateVersionRegex.FindStringSubmatch(tag); matches != nil {+ year, _ := strconv.Atoi(matches[1])+ month, _ := strconv.Atoi(matches[2])+ day, _ := strconv.Atoi(matches[3])++ return &VersionInfo{+ Major: &year,+ Minor: &month,+ Patch: &day,+ FormatStr: "date",+ }+ }++ // Handle simple numeric versioning+ if matches := utils.NumericVersionRegex.FindStringSubmatch(tag); matches != nil {+ major, _ := strconv.Atoi(matches[1])+ var minor, patch *int+ if len(matches) > 2 && matches[2] != "" {+ m, _ := strconv.Atoi(matches[2])+ minor = &m+ }+ if len(matches) > 3 && matches[3] != "" {+ p, _ := strconv.Atoi(matches[3])+ patch = &p+ }++ return &VersionInfo{+ Major: &major,+ Minor: minor,+ Patch: patch,+ FormatStr: "numeric",+ }+ }++ return nil+}++func (s *ImageUpdateService) findLatestCompatibleVersion(current *VersionInfo, tags []string) *VersionInfo {+ var latest *VersionInfo++ for _, tag := range tags {+ version := s.parseVersion(tag)+ if version == nil || version.FormatStr != current.FormatStr {+ continue+ }++ // Check compatibility based on semantic versioning rules+ if !s.isCompatibleVersion(current, version) {+ continue+ }++ if latest == nil || s.isNewerVersion(version, latest) {+ latest = version+ }+ }++ return latest+}++func (s *ImageUpdateService) isCompatibleVersion(base, candidate *VersionInfo) bool {+ // Same format is required+ if base.FormatStr != candidate.FormatStr {+ return false+ }++ // For semantic versioning, ensure major version compatibility+ if base.FormatStr == "semantic" {+ return base.Major != nil && candidate.Major != nil && *base.Major == *candidate.Major+ }++ // For other formats, allow any newer version+ return true+}++func (s *ImageUpdateService) isNewerVersion(newer, current *VersionInfo) bool {+ if newer.Major != nil && current.Major != nil {+ if *newer.Major > *current.Major {+ return true+ }+ if *newer.Major < *current.Major {+ return false+ }+ }++ if newer.Minor != nil && current.Minor != nil {+ if *newer.Minor > *current.Minor {+ return true+ }+ if *newer.Minor < *current.Minor {+ return false+ }+ }++ if newer.Patch != nil && current.Patch != nil {+ return *newer.Patch > *current.Patch+ }++ return false+}++func (s *ImageUpdateService) parseImageReference(imageRef string) *ImageParts {+ var registry, repository, tag string++ if strings.Contains(imageRef, "@sha256:") {+ digestParts := strings.Split(imageRef, "@")+ if len(digestParts) != 2 {+ return nil+ }++ repoWithRegistry := digestParts[0]+ parts := strings.Split(repoWithRegistry, "/")++ if strings.Contains(parts[0], ".") || strings.Contains(parts[0], ":") {+ registry = parts[0]+ repository = strings.Join(parts[1:], "/")+ } else {+ registry = "docker.io"+ if len(parts) == 1 {+ repository = "library/" + parts[0]+ } else {+ repository = repoWithRegistry+ }+ }++ tag = "latest"+ } else {+ parts := strings.Split(imageRef, "/")++ if len(parts) == 1 {+ registry = "docker.io"+ if strings.Contains(parts[0], ":") {+ repoParts := strings.Split(parts[0], ":")+ repository = "library/" + repoParts[0]+ tag = repoParts[1]+ } else {+ repository = "library/" + parts[0]+ tag = "latest"+ }+ } else if strings.Contains(parts[0], ".") || strings.Contains(parts[0], ":") {+ registry = parts[0]+ repository = strings.Join(parts[1:], "/")++ if strings.Contains(repository, ":") {+ repoParts := strings.Split(repository, ":")+ repository = repoParts[0]+ tag = repoParts[1]+ } else {+ tag = "latest"+ }+ } else {+ registry = "docker.io"+ repository = imageRef++ if strings.Contains(repository, ":") {+ repoParts := strings.Split(repository, ":")+ repository = repoParts[0]+ tag = repoParts[1]+ } else {+ tag = "latest"+ }+ }+ }++ return &ImageParts{+ Registry: registry,+ Repository: repository,+ Tag: tag,+ }+}++func (s *ImageUpdateService) getImageRefByID(ctx context.Context, imageID string) (string, error) {+ dockerClient, err := s.dockerService.CreateConnection(ctx)+ if err != nil {+ return "", fmt.Errorf("failed to connect to Docker: %w", err)+ }+ defer dockerClient.Close()++ imageID = strings.TrimPrefix(imageID, "sha256:")++ inspectResponse, err := dockerClient.ImageInspect(ctx, imageID)+ if err != nil {+ return "", fmt.Errorf("image not found: %w", err)+ }++ fmt.Printf("DEBUG: RepoTags: %v\n", inspectResponse.RepoTags)+ fmt.Printf("DEBUG: RepoDigests: %v\n", inspectResponse.RepoDigests)++ if len(inspectResponse.RepoTags) > 0 {+ for _, tag := range inspectResponse.RepoTags {+ if tag != "<none>:<none>" {+ fmt.Printf("DEBUG: Using RepoTag: %s\n", tag)+ return tag, nil+ }+ }+ }++ if len(inspectResponse.RepoDigests) > 0 {+ for _, digest := range inspectResponse.RepoDigests {+ if digest != "<none>@<none>" {+ digestParts := strings.Split(digest, "@")+ if len(digestParts) == 2 {+ imageRef := digestParts[0] + ":latest"+ fmt.Printf("DEBUG: Using RepoDigest as: %s\n", imageRef)+ return imageRef, nil+ }+ }+ }+ }++ return "", fmt.Errorf("no valid repository tags or digests found for image")+}++func (s *ImageUpdateService) getAllImageRefs(ctx context.Context, limit int) ([]string, error) {+ dockerClient, err := s.dockerService.CreateConnection(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }+ defer dockerClient.Close()++ images, err := dockerClient.ImageList(ctx, image.ListOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to list Docker images: %w", err)+ }++ var imageRefs []string+ for _, img := range images {+ for _, tag := range img.RepoTags {+ if tag != "<none>:<none>" {+ imageRefs = append(imageRefs, tag)+ }+ }++ if limit > 0 && len(imageRefs) >= limit {+ break+ }+ }++ if limit > 0 && len(imageRefs) > limit {+ imageRefs = imageRefs[:limit]+ }++ return imageRefs, nil+}++func (s *ImageUpdateService) getLocalImageDigest(ctx context.Context, imageRef string) (string, error) {+ dockerClient, err := s.dockerService.CreateConnection(ctx)+ if err != nil {+ return "", fmt.Errorf("failed to connect to Docker: %w", err)+ }+ defer dockerClient.Close()++ inspectResponse, err := dockerClient.ImageInspect(ctx, imageRef)+ if err != nil {+ return "", fmt.Errorf("failed to inspect image: %w", err)+ }++ if len(inspectResponse.RepoDigests) > 0 {+ digestParts := strings.Split(inspectResponse.RepoDigests[0], "@")+ if len(digestParts) == 2 {+ return digestParts[1], nil+ }+ }++ return inspectResponse.ID, nil+}++func (s *ImageUpdateService) versionToString(version *VersionInfo) string {+ result := ""+ if version.Major != nil {+ result = strconv.Itoa(*version.Major)+ }+ if version.Minor != nil {+ result += "." + strconv.Itoa(*version.Minor)+ }+ if version.Patch != nil {+ result += "." + strconv.Itoa(*version.Patch)+ }+ return result+}++// Helper methods that can reuse existing logic from ImageMaturityService+func (s *ImageUpdateService) getRegistryForImage(ctx context.Context, registry string) *models.ContainerRegistry {+ normalizedDomain := s.normalizeRegistryURL(registry)++ registries, err := s.registryService.GetAllRegistries(ctx)+ if err != nil {+ return nil+ }++ for _, reg := range registries {+ if !reg.Enabled {+ continue+ }++ normalizedRegURL := s.normalizeRegistryURL(reg.URL)+ if normalizedRegURL == normalizedDomain {+ return ®+ }+ }++ return nil+}++func (s *ImageUpdateService) normalizeRegistryURL(url string) string {+ url = strings.TrimSpace(url)+ url = strings.ToLower(url)+ url = strings.TrimPrefix(url, "https://")+ url = strings.TrimPrefix(url, "http://")+ url = strings.TrimSuffix(url, "/")++ if url == "docker.io" || url == "registry-1.docker.io" || url == "index.docker.io" {+ return "docker.io"+ }++ return url+}++func (s *ImageUpdateService) normalizeRepository(registry, repository string) string {+ if registry == "docker.io" {+ if !strings.Contains(repository, "/") {+ return "library/" + repository+ }+ }+ return repository+}++func (s *ImageUpdateService) isSpecialTag(tag string) bool {+ specialTags := []string{+ "latest", "stable", "unstable", "dev", "devel", "development",+ "test", "testing", "prod", "production", "main", "master",+ "stage", "staging", "canary", "nightly", "edge", "next",+ }++ for _, special := range specialTags {+ if tag == special {+ return true+ }+ }+ return false+}++func (s *ImageUpdateService) CheckImageUpdateByID(ctx context.Context, imageID string) (*UpdateResult, error) {+ imageRef, err := s.getImageRefByID(ctx, imageID)+ if err != nil {+ return nil, fmt.Errorf("failed to get image reference: %w", err)+ }++ result, err := s.CheckImageUpdate(ctx, imageRef)+ if err != nil {+ return nil, err+ }++ s.saveUpdateResultByID(ctx, imageID, result)+ return result, nil+}++func (s *ImageUpdateService) saveUpdateResult(ctx context.Context, imageRef string, result *UpdateResult) error {+ parts := s.parseImageReference(imageRef)+ if parts == nil {+ return fmt.Errorf("invalid image reference")+ }++ imageID, err := s.getImageIDByRef(ctx, imageRef)+ if err != nil {+ return fmt.Errorf("failed to get image ID: %w", err)+ }++ return s.saveUpdateResultByID(ctx, imageID, result)+}++func (s *ImageUpdateService) saveUpdateResultByID(ctx context.Context, imageID string, result *UpdateResult) error {+ var lastError *string+ if result.Error != "" {+ lastError = &result.Error+ }++ var latestVersion *string+ if result.LatestVersion != "" {+ latestVersion = &result.LatestVersion+ }++ var currentDigest *string+ if result.CurrentDigest != "" {+ currentDigest = &result.CurrentDigest+ }++ var latestDigest *string+ if result.LatestDigest != "" {+ latestDigest = &result.LatestDigest+ }++ var image models.Image+ if err := s.db.WithContext(ctx).Where("id = ?", imageID).First(&image).Error; err != nil {+ return fmt.Errorf("image not found: %w", err)+ }++ currentVersion := result.CurrentVersion+ if currentVersion == "" {+ currentVersion = image.Tag+ }++ updateRecord := &models.ImageUpdateRecord{+ ID: imageID,+ Repository: image.Repo,+ Tag: image.Tag,+ HasUpdate: result.HasUpdate,+ UpdateType: result.UpdateType,+ CurrentVersion: currentVersion,+ LatestVersion: latestVersion,+ CurrentDigest: currentDigest,+ LatestDigest: latestDigest,+ CheckTime: result.CheckTime,+ ResponseTimeMs: result.ResponseTimeMs,+ LastError: lastError,+ }++ return s.db.WithContext(ctx).Save(updateRecord).Error+}++func (s *ImageUpdateService) getImageIDByRef(ctx context.Context, imageRef string) (string, error) {+ dockerClient, err := s.dockerService.CreateConnection(ctx)+ if err != nil {+ return "", fmt.Errorf("failed to connect to Docker: %w", err)+ }+ defer dockerClient.Close()++ inspectResponse, err := dockerClient.ImageInspect(ctx, imageRef)+ if err != nil {+ return "", fmt.Errorf("image not found: %w", err)+ }++ return inspectResponse.ID, nil+}++func (s *ImageUpdateService) CheckMultipleImages(ctx context.Context, imageRefs []string) (map[string]*UpdateResult, error) {+ results := make(map[string]*UpdateResult)++ for _, imageRef := range imageRefs {+ result, err := s.CheckImageUpdate(ctx, imageRef)+ if err != nil {+ results[imageRef] = &UpdateResult{+ Error: err.Error(),+ CheckTime: time.Now(),+ }+ } else {+ results[imageRef] = result+ }+ }++ return results, nil+}++func (s *ImageUpdateService) CheckAllImages(ctx context.Context, limit int) (map[string]*UpdateResult, error) {+ imageRefs, err := s.getAllImageRefs(ctx, limit)+ if err != nil {+ return nil, fmt.Errorf("failed to get image references: %w", err)+ }++ return s.CheckMultipleImages(ctx, imageRefs)+}++func (s *ImageUpdateService) TriggerBulkUpdateCheck(ctx context.Context, imageIDs []string) error {+ for _, imageID := range imageIDs {+ _, err := s.CheckImageUpdateByID(ctx, imageID)+ if err != nil {+ continue+ }+ }+ return nil+}++func (s *ImageUpdateService) GetUpdateRecordByImageID(ctx context.Context, imageID string) (*models.ImageUpdateRecord, error) {+ var record models.ImageUpdateRecord+ err := s.db.WithContext(ctx).Where("id = ?", imageID).First(&record).Error+ if err != nil {+ return nil, err+ }+ return &record, nil+}++func (s *ImageUpdateService) DeleteUpdateRecord(ctx context.Context, imageID string) error {+ return s.db.WithContext(ctx).Where("id = ?", imageID).Delete(&models.ImageUpdateRecord{}).Error+}++func (s *ImageUpdateService) CleanupOrphanedRecords(ctx context.Context) error {+ subQuery := s.db.WithContext(ctx).Model(&models.Image{}).Select("id")++ return s.db.WithContext(ctx).+ Where("id NOT IN (?)", subQuery).+ Delete(&models.ImageUpdateRecord{}).Error+}++func (s *ImageUpdateService) GetUpdateSummary(ctx context.Context) (*UpdateSummary, error) {+ var totalImages int64+ var imagesWithUpdates int64+ var digestUpdates int64+ var tagUpdates int64+ var errorsCount int64++ s.db.WithContext(ctx).Model(&models.ImageUpdateRecord{}).Count(&totalImages)+ s.db.WithContext(ctx).Model(&models.ImageUpdateRecord{}).Where("has_update = ?", true).Count(&imagesWithUpdates)+ s.db.WithContext(ctx).Model(&models.ImageUpdateRecord{}).Where("has_update = ? AND update_type = ?", true, "digest").Count(&digestUpdates)+ s.db.WithContext(ctx).Model(&models.ImageUpdateRecord{}).Where("has_update = ? AND update_type = ?", true, "tag").Count(&tagUpdates)+ s.db.WithContext(ctx).Model(&models.ImageUpdateRecord{}).Where("last_error IS NOT NULL").Count(&errorsCount)++ return &UpdateSummary{+ TotalImages: int(totalImages),+ ImagesWithUpdates: int(imagesWithUpdates),+ DigestUpdates: int(digestUpdates),+ TagUpdates: int(tagUpdates),+ ErrorsCount: int(errorsCount),+ }, nil+}++func (s *ImageUpdateService) GetAvailableVersions(ctx context.Context, imageRef string, limit int) (*AvailableVersions, error) {+ parts := s.parseImageReference(imageRef)+ if parts == nil {+ return nil, fmt.Errorf("invalid image reference format")+ }++ registry := s.getRegistryForImage(ctx, parts.Registry)++ tags, err := s.getImageTags(ctx, parts, registry)+ if err != nil {+ return nil, fmt.Errorf("failed to get tags: %w", err)+ }++ if limit > 0 && len(tags) > limit {+ tags = tags[:limit]+ }++ var latest string+ currentVersion := s.parseVersion(parts.Tag)+ if currentVersion != nil {+ latestVersion := s.findLatestCompatibleVersion(currentVersion, tags)+ if latestVersion != nil {+ latest = s.versionToString(latestVersion)+ }+ }++ return &AvailableVersions{+ ImageRef: imageRef,+ Current: parts.Tag,+ Versions: tags,+ Latest: latest,+ }, nil+}++func (s *ImageUpdateService) CompareVersions(ctx context.Context, imageRef, currentVersion, targetVersion string) (*VersionComparison, error) {+ currentVer := s.parseVersion(currentVersion)+ targetVer := s.parseVersion(targetVersion)++ if currentVer == nil || targetVer == nil {+ return &VersionComparison{+ CurrentVersion: currentVersion,+ TargetVersion: targetVersion,+ IsNewer: false,+ UpdateType: "unknown",+ ChangeLevel: "unknown",+ }, nil+ }++ isNewer := s.isNewerVersion(targetVer, currentVer)++ var changeLevel string+ if currentVer.Major != nil && targetVer.Major != nil {+ if *targetVer.Major > *currentVer.Major {+ changeLevel = "major"+ } else if targetVer.Minor != nil && currentVer.Minor != nil && *targetVer.Minor > *currentVer.Minor {+ changeLevel = "minor"+ } else {+ changeLevel = "patch"+ }+ } else {+ changeLevel = "unknown"+ }++ return &VersionComparison{+ CurrentVersion: currentVersion,+ TargetVersion: targetVersion,+ IsNewer: isNewer,+ UpdateType: currentVer.FormatStr,+ ChangeLevel: changeLevel,+ }, nil+}diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.goindex 79ea22296..edb24df5c 100644--- a/backend/internal/services/settings_service.go+++ b/backend/internal/services/settings_service.go@@ -52,16 +52,15 @@ func (s *SettingsService) createDefaultSettings(ctx context.Context) (*models.SedefaultPruneMode := "dangling"settings := &models.Settings{- StacksDirectory: "data/stacks",- AutoUpdate: false,- AutoUpdateInterval: 300,- PollingEnabled: true,- PollingInterval: 5,- PruneMode: &defaultPruneMode,- RegistryCredentials: models.JSON{},- TemplateRegistries: models.JSON{},- Auth: defaultAuth,- MaturityThresholdDays: 30,+ StacksDirectory: "data/stacks",+ AutoUpdate: false,+ AutoUpdateInterval: 300,+ PollingEnabled: true,+ PollingInterval: 5,+ PruneMode: &defaultPruneMode,+ RegistryCredentials: models.JSON{},+ TemplateRegistries: models.JSON{},+ Auth: defaultAuth,BaseModel: models.BaseModel{CreatedAt: time.Now(),},diff --git a/backend/internal/utils/registry_utils.go b/backend/internal/utils/registry_utils.goindex 707764505..e883f1fc8 100644--- a/backend/internal/utils/registry_utils.go+++ b/backend/internal/utils/registry_utils.go@@ -9,336 +9,344 @@ import ("time")-type DockerHubTokenResponse struct {- Token string `json:"token"`- ExpiresIn int `json:"expires_in"`- IssuedAt string `json:"issued_at"`-}+const DEFAULT_REGISTRY = "registry-1.docker.io"-type DockerHubTagsResponse struct {- Name string `json:"name"`- Tags []struct {- Name string `json:"name"`- FullSize int `json:"full_size"`- LastUpdated time.Time `json:"last_updated"`- } `json:"tags"`-}+type RegistryUtils struct{}type RegistryCredentials struct {Username stringToken string}-func BuildRegistryURL(domain string) string {- switch domain {- case "docker.io", "index.docker.io", "":- return "https://registry-1.docker.io/v2"- case "gcr.io":- return "https://gcr.io/v2"- case "ghcr.io":- return "https://ghcr.io/v2"- case "quay.io":- return "https://quay.io/v2"+type RegistryTestResult struct {+ OverallSuccess bool `json:"overall_success"`+ PingSuccess bool `json:"ping_success"`+ AuthSuccess bool `json:"auth_success"`+ CatalogSuccess bool `json:"catalog_success"`+ URL string `json:"url"`+ Domain string `json:"domain"`+ Timestamp time.Time `json:"timestamp"`+ Errors []string `json:"errors"`+}++func NewRegistryUtils() *RegistryUtils {+ return &RegistryUtils{}+}++func (r *RegistryUtils) SplitImageReference(reference string) (string, string, string, error) {+ if reference == "" {+ return "", "", "", fmt.Errorf("empty reference provided")+ }++ splits := strings.Split(reference, "/")+ var registry, repositoryAndTag string++ switch len(splits) {+ case 1:+ registry = DEFAULT_REGISTRY+ repositoryAndTag = referencedefault:- if strings.HasPrefix(domain, "http://") || strings.HasPrefix(domain, "https://") {- return domain + "/v2"+ if splits[0] == "docker.io" {+ registry = DEFAULT_REGISTRY+ repositoryAndTag = strings.Join(splits[1:], "/")+ } else if splits[0] == "localhost" || strings.Contains(splits[0], ".") || strings.Contains(splits[0], ":") {+ registry = splits[0]+ repositoryAndTag = strings.Join(splits[1:], "/")+ } else {+ registry = DEFAULT_REGISTRY+ repositoryAndTag = reference}- // Default to HTTPS for custom domains- return "https://" + domain + "/v2"}++ repositoryAndTag = strings.Split(repositoryAndTag, "@")[0]++ tagSplits := strings.Split(repositoryAndTag, ":")+ var repository, tag string++ switch len(tagSplits) {+ case 1:+ repository = tagSplits[0]+ tag = "latest"+ case 2:+ repository = tagSplits[0]+ tag = tagSplits[1]+ default:+ return "", "", "", fmt.Errorf("invalid reference format: too many colons in %s", repositoryAndTag)+ }++ repositoryComponents := strings.Split(repository, "/")+ if len(repositoryComponents) == 1 && registry == DEFAULT_REGISTRY {+ repository = "library/" + repository+ }++ return registry, repository, tag, nil}-// GetRegistryToken gets an authentication token for the specified registry-func GetRegistryToken(ctx context.Context, domain, repo string, creds *RegistryCredentials) (string, error) {- switch domain {- case "docker.io", "index.docker.io", "registry-1.docker.io":- return getDockerHubToken(ctx, repo, creds)- case "gcr.io":- return getGCRToken(ctx, repo, creds)- case "ghcr.io":- return getGHCRToken(ctx, repo, creds)- case "quay.io":- return getQuayToken(ctx, repo, creds)+func (r *RegistryUtils) GetRegistryURL(registry string) string {+ switch registry {+ case DEFAULT_REGISTRY, "docker.io":+ return "https://index.docker.io"default:- return getGenericRegistryToken(ctx, domain, repo, creds)+ if !strings.HasPrefix(registry, "http") {+ return "https://" + registry+ }+ return registry}}-func getGenericRegistryToken(ctx context.Context, domain, repo string, creds *RegistryCredentials) (string, error) {- authURL := fmt.Sprintf("https://%s/v2/", domain)+func (r *RegistryUtils) CheckAuth(ctx context.Context, registry string) (string, error) {+ url := fmt.Sprintf("%s/v2/", r.GetRegistryURL(registry))- client := &http.Client{Timeout: 30 * time.Second}- req, err := http.NewRequestWithContext(ctx, http.MethodGet, authURL, nil)+ client := &http.Client{Timeout: 10 * time.Second}+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)if err != nil {- return "", fmt.Errorf("failed to create auth request: %w", err)- }-- if creds != nil && creds.Username != "" {- req.SetBasicAuth(creds.Username, creds.Token)+ return "", err}resp, err := client.Do(req)if err != nil {- return "", fmt.Errorf("failed to authenticate: %w", err)+ return "", err}defer resp.Body.Close()- if resp.StatusCode == http.StatusOK {- return "", nil+ if resp.StatusCode == http.StatusUnauthorized {+ authHeader := resp.Header.Get("WWW-Authenticate")+ if authHeader != "" {+ authURL := r.parseWWWAuthenticate(authHeader)+ return authURL, nil+ }}- if resp.StatusCode != http.StatusUnauthorized {- return "", fmt.Errorf("unexpected auth response: %d", resp.StatusCode)- }+ return "", nil+}- authHeader := resp.Header.Get("Www-Authenticate")- if authHeader == "" {- return "", fmt.Errorf("no auth challenge")+func (r *RegistryUtils) parseWWWAuthenticate(header string) string {+ if strings.HasPrefix(header, "Bearer ") {+ parts := strings.Split(header[7:], ",")+ for _, part := range parts {+ part = strings.TrimSpace(part)+ if strings.HasPrefix(part, "realm=") {+ realm := strings.Trim(part[6:], `"`)+ return realm+ }+ }}-- return parseAndGetToken(ctx, authHeader, creds)+ return ""}-// getDockerHubToken gets a token for Docker Hub-func getDockerHubToken(ctx context.Context, repo string, creds *RegistryCredentials) (string, error) {- normalizedRepo := repo- if !strings.Contains(repo, "/") {- normalizedRepo = "library/" + repo- } else if strings.HasPrefix(repo, "docker.io/") {- normalizedRepo = strings.TrimPrefix(repo, "docker.io/")+func (r *RegistryUtils) getServiceName(authURL string) string {+ if strings.Contains(authURL, "auth.docker.io") {+ return "registry.docker.io"+ }++ urlParts := strings.Split(strings.TrimPrefix(authURL, "https://"), "/")+ if len(urlParts) > 0 {+ return urlParts[0]}+ return "registry"+}- authURL := fmt.Sprintf("https://auth.docker.io/token?service=registry.docker.io&scope=repository:%s:pull", normalizedRepo)+func (r *RegistryUtils) GetToken(ctx context.Context, authURL, repository string, credentials *RegistryCredentials) (string, error) {+ serviceName := r.getServiceName(authURL)+ tokenURL := fmt.Sprintf("%s?service=%s&scope=repository:%s:pull", authURL, serviceName, repository)client := &http.Client{Timeout: 30 * time.Second}- req, err := http.NewRequestWithContext(ctx, http.MethodGet, authURL, nil)+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, tokenURL, nil)if err != nil {- return "", fmt.Errorf("failed to create auth request: %w", err)+ return "", err}- // Add credentials if provided- if creds != nil && creds.Username != "" && creds.Token != "" {- req.SetBasicAuth(creds.Username, creds.Token)+ if credentials != nil && credentials.Username != "" && credentials.Token != "" {+ req.SetBasicAuth(credentials.Username, credentials.Token)}resp, err := client.Do(req)if err != nil {- return "", fmt.Errorf("failed to get auth token: %w", err)+ return "", err}defer resp.Body.Close()if resp.StatusCode != http.StatusOK {- return "", fmt.Errorf("auth request failed with status: %d", resp.StatusCode)+ return "", fmt.Errorf("token request failed with status: %d", resp.StatusCode)+ }++ var tokenResp struct {+ Token string `json:"token"`}- var tokenResp DockerHubTokenResponseif err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {- return "", fmt.Errorf("failed to decode auth response: %w", err)+ return "", err}return tokenResp.Token, nil}-// getGCRToken gets a token for Google Container Registry-func getGCRToken(ctx context.Context, repo string, creds *RegistryCredentials) (string, error) {- return getGenericRegistryToken(ctx, "gcr.io", repo, creds)-}--// getGitHubRegistryToken gets a token for GitHub Container Registry-func getGHCRToken(ctx context.Context, repo string, creds *RegistryCredentials) (string, error) {- return getGenericRegistryToken(ctx, "ghcr.io", repo, creds)-}--// getQuayToken gets a token for Quay.io-func getQuayToken(ctx context.Context, repo string, creds *RegistryCredentials) (string, error) {- return getGenericRegistryToken(ctx, "quay.io", repo, creds)-}+func (r *RegistryUtils) GetLatestDigest(ctx context.Context, registry, repository, tag string, token string) (string, error) {+ url := fmt.Sprintf("%s/v2/%s/manifests/%s", r.GetRegistryURL(registry), repository, tag)-func parseAndGetToken(ctx context.Context, authHeader string, creds *RegistryCredentials) (string, error) {- return "", fmt.Errorf("token parsing not implemented")-}+ client := &http.Client{Timeout: 30 * time.Second}+ req, err := http.NewRequestWithContext(ctx, http.MethodHead, url, nil)+ if err != nil {+ return "", err+ }-// TestRegistryConnection tests connectivity to a registry with credentials-func TestRegistryConnection(ctx context.Context, domain string, creds *RegistryCredentials) (*RegistryTestResult, error) {- registryURL := BuildRegistryURL(domain)+ req.Header.Set("Accept", "application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.index.v1+json")- client := &http.Client{- Timeout: 30 * time.Second,+ if token != "" {+ req.Header.Set("Authorization", "Bearer "+token)}- result := &RegistryTestResult{- Domain: domain,- URL: registryURL,- Timestamp: time.Now().UTC(),+ resp, err := client.Do(req)+ if err != nil {+ return "", err}+ defer resp.Body.Close()- // Test 1: Ping test- pingErr := testPing(ctx, client, registryURL, creds)- result.PingSuccess = pingErr == nil- if pingErr != nil {- result.Errors = append(result.Errors, fmt.Sprintf("Ping failed: %s", pingErr.Error()))+ if resp.StatusCode != http.StatusOK {+ return "", fmt.Errorf("manifest request failed with status: %d", resp.StatusCode)}- // Test 2: Auth test- authErr := testAuth(ctx, client, registryURL, creds)- result.AuthSuccess = authErr == nil- if authErr != nil {- result.Errors = append(result.Errors, fmt.Sprintf("Auth failed: %s", authErr.Error()))+ digest := resp.Header.Get("Docker-Content-Digest")+ if digest == "" {+ digest = resp.Header.Get("docker-content-digest")}-- // Test 3: Catalog test- catalogErr := testCatalog(ctx, client, registryURL, creds)- result.CatalogSuccess = catalogErr == nil- if catalogErr != nil {- result.Errors = append(result.Errors, fmt.Sprintf("Catalog failed: %s", catalogErr.Error()))+ if digest == "" {+ etag := resp.Header.Get("Etag")+ if etag != "" && strings.HasPrefix(etag, "sha256:") {+ digest = strings.Trim(etag, `"`)+ }}- // Determine overall success- result.OverallSuccess = result.PingSuccess && (result.AuthSuccess || creds == nil)+ if digest == "" {+ return "", fmt.Errorf("no digest header found in response")+ }- return result, nil+ return digest, nil}-type RegistryTestResult struct {- Domain string `json:"domain"`- URL string `json:"url"`- Timestamp time.Time `json:"timestamp"`- OverallSuccess bool `json:"overall_success"`- PingSuccess bool `json:"ping_success"`- AuthSuccess bool `json:"auth_success"`- CatalogSuccess bool `json:"catalog_success"`- Errors []string `json:"errors,omitempty"`-}+func (r *RegistryUtils) GetImageTags(ctx context.Context, registry, repository string, token string) ([]string, error) {+ url := fmt.Sprintf("%s/v2/%s/tags/list", r.GetRegistryURL(registry), repository)-func testPing(ctx context.Context, client *http.Client, registryURL string, creds *RegistryCredentials) error {- req, err := http.NewRequestWithContext(ctx, http.MethodGet, registryURL+"/", nil)- if err != nil {- return err- }+ var allTags []string+ nextURL := url- if creds != nil && creds.Username != "" && creds.Token != "" {- req.SetBasicAuth(creds.Username, creds.Token)- }+ for nextURL != "" {+ client := &http.Client{Timeout: 30 * time.Second}+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, nextURL, nil)+ if err != nil {+ return nil, err+ }- req.Header.Set("User-Agent", "Arcane-Registry-Test/1.0")+ req.Header.Set("Accept", "application/json")- resp, err := client.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()+ if token != "" {+ req.Header.Set("Authorization", "Bearer "+token)+ }- // Accept 200 (OK) or 401/403 (registry exists but needs auth)- if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden {- return fmt.Errorf("unexpected status code: %d", resp.StatusCode)- }+ resp, err := client.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()- return nil-}+ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("tags request failed with status: %d", resp.StatusCode)+ }-func testAuth(ctx context.Context, client *http.Client, registryURL string, creds *RegistryCredentials) error {- if creds == nil {- return nil // Skip auth test if no credentials- }+ var tagsResp struct {+ Tags []string `json:"tags"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&tagsResp); err != nil {+ return nil, err+ }- req, err := http.NewRequestWithContext(ctx, http.MethodGet, registryURL+"/_catalog?n=1", nil)- if err != nil {- return err+ allTags = append(allTags, tagsResp.Tags...)++ linkHeader := resp.Header.Get("Link")+ nextURL = r.parseLinkHeader(linkHeader, url)}- req.SetBasicAuth(creds.Username, creds.Token)- req.Header.Set("User-Agent", "Arcane-Registry-Test/1.0")+ return allTags, nil+}- resp, err := client.Do(req)- if err != nil {- return err+func (r *RegistryUtils) parseLinkHeader(linkHeader, baseURL string) string {+ if linkHeader == "" {+ return ""}- defer resp.Body.Close()- if resp.StatusCode == http.StatusOK {- return nil+ parts := strings.Split(linkHeader, ",")+ for _, part := range parts {+ part = strings.TrimSpace(part)+ if strings.Contains(part, `rel="next"`) {+ start := strings.Index(part, "<")+ end := strings.Index(part, ">")+ if start != -1 && end != -1 && end > start {+ return part[start+1 : end]+ }+ }}- return fmt.Errorf("authentication failed with status: %d", resp.StatusCode)+ return ""}-func testCatalog(ctx context.Context, client *http.Client, registryURL string, creds *RegistryCredentials) error {- req, err := http.NewRequestWithContext(ctx, http.MethodGet, registryURL+"/_catalog?n=5", nil)- if err != nil {- return err- }+func TestRegistryConnection(ctx context.Context, registryURL string, credentials *RegistryCredentials) (*RegistryTestResult, error) {+ registryUtils := NewRegistryUtils()- if creds != nil && creds.Username != "" && creds.Token != "" {- req.SetBasicAuth(creds.Username, creds.Token)+ result := &RegistryTestResult{+ URL: registryURL,+ Domain: registryURL,+ Timestamp: time.Now(),+ Errors: []string{},}- req.Header.Set("User-Agent", "Arcane-Registry-Test/1.0")-- resp, err := client.Do(req)- if err != nil {- return err+ registry := strings.TrimPrefix(strings.TrimPrefix(registryURL, "https://"), "http://")+ if registry == "docker.io" {+ registry = DEFAULT_REGISTRY}- defer resp.Body.Close()- // Accept 200 (OK), 401 (needs auth), or 403 (forbidden but accessible)- if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden {- return fmt.Errorf("catalog request failed with status: %d", resp.StatusCode)+ authURL, err := registryUtils.CheckAuth(ctx, registry)+ if err != nil {+ result.Errors = append(result.Errors, fmt.Sprintf("Ping failed: %v", err))+ result.PingSuccess = false+ } else {+ result.PingSuccess = true+ }++ if authURL != "" && credentials != nil {+ token, err := registryUtils.GetToken(ctx, authURL, "library/hello-world", credentials)+ if err != nil {+ result.Errors = append(result.Errors, fmt.Sprintf("Auth failed: %v", err))+ result.AuthSuccess = false+ } else {+ result.AuthSuccess = token != ""+ }+ } else {+ result.AuthSuccess = authURL == ""}- return nil-}--// Legacy functions for backward compatibility-func GetGenericRegistryToken(ctx context.Context, domain, repo string) (string, error) {- return GetRegistryToken(ctx, domain, repo, nil)-}--func IsPrivateRegistry(repo string) bool {- domain := ExtractRegistryDomain(repo)-- publicRegistries := []string{- "docker.io",- "registry-1.docker.io",- "index.docker.io",- "gcr.io",- "ghcr.io",- "quay.io",+ tags, err := registryUtils.GetImageTags(ctx, registry, "library/hello-world", "")+ if err != nil {+ result.Errors = append(result.Errors, fmt.Sprintf("Catalog access failed: %v", err))+ result.CatalogSuccess = false+ } else {+ result.CatalogSuccess = len(tags) > 0}- for _, publicRegistry := range publicRegistries {- if domain == publicRegistry {- return false- }- }+ result.OverallSuccess = result.PingSuccess && result.AuthSuccess && result.CatalogSuccess- return true+ return result, nil}-func ExtractRegistryDomain(repo string) string {- // Handle different image name formats:- // - nginx (Docker Hub official)- // - user/repo (Docker Hub user)- // - registry.example.com/user/repo- // - registry.example.com:5000/user/repo- // - localhost:5000/user/repo-- if !strings.Contains(repo, "/") {- // Official Docker Hub image (e.g., "nginx")- return "docker.io"+func ExtractRegistryDomain(imageRef string) (string, error) {+ registryUtils := NewRegistryUtils()+ registry, _, _, err := registryUtils.SplitImageReference(imageRef)+ if err != nil {+ return "", fmt.Errorf("failed to extract registry domain: %w", err)}- parts := strings.Split(repo, "/")- firstPart := parts[0]-- // Check if first part looks like a registry domain- if strings.Contains(firstPart, ".") || strings.Contains(firstPart, ":") || firstPart == "localhost" {- return firstPart+ if registry == DEFAULT_REGISTRY {+ return "docker.io", nil}- // If no domain detected, assume Docker Hub- return "docker.io"-}--func GetDockerHubToken(ctx context.Context, repo string) (string, error) {- return getDockerHubToken(ctx, repo, nil)+ return registry, nil}diff --git a/backend/internal/utils/version.go b/backend/internal/utils/version.gonew file mode 100644index 000000000..12bb0ad8b--- /dev/null+++ b/backend/internal/utils/version.go@@ -0,0 +1,9 @@+package utils++import "regexp"++var (+ SemanticVersionRegex = regexp.MustCompile(`^(\d+)\.(\d+)\.(\d+)(?:-.*)?$`)+ DateVersionRegex = regexp.MustCompile(`^(\d{4})\.(\d{1,2})\.(\d{1,2})$`)+ NumericVersionRegex = regexp.MustCompile(`^(\d+)(?:\.(\d+))?(?:\.(\d+))?$`)+)diff --git a/frontend/src/lib/components/dropdown-card.svelte b/frontend/src/lib/components/dropdown-card.svelteindex e05355d9d..45b007d06 100644--- a/frontend/src/lib/components/dropdown-card.svelte+++ b/frontend/src/lib/components/dropdown-card.svelte@@ -63,7 +63,9 @@{/if}</div><Button class="ml-10 h-8 p-3" variant="ghost" aria-label="Expand Card">- <LucideChevronDown class={cn('size-5 transition-transform duration-200', expanded && 'rotate-180 transform')} />+ <LucideChevronDown+ class={cn('size-5 transition-transform duration-200', expanded && 'rotate-180 transform')}+ /></Button></div></Card.Header>diff --git a/frontend/src/lib/components/image-update-item.svelte b/frontend/src/lib/components/image-update-item.sveltenew file mode 100644index 000000000..6f3c9cf8e--- /dev/null+++ b/frontend/src/lib/components/image-update-item.svelte@@ -0,0 +1,403 @@+<script lang="ts">+ import * as Tooltip from '$lib/components/ui/tooltip/index.js';+ import {+ CircleCheck,+ CircleFadingArrowUp,+ CircleArrowUp,+ Loader2,+ Clock,+ Package,+ Calendar,+ AlertTriangle,+ RefreshCw,+ ArrowRight+ } from '@lucide/svelte';+ import { imageUpdateAPI } from '$lib/services/api';+ import { toast } from 'svelte-sonner';+ import { invalidateAll } from '$app/navigation';+ import { formatDate } from '$lib/utils/string.utils';+ import type { ImageUpdateData } from '$lib/services/api/image-update-api-service';++ interface Props {+ updateInfo?: ImageUpdateData | undefined;+ isLoadingInBackground?: boolean;+ imageId: string;+ repo?: string;+ tag?: string;+ }++ let {+ updateInfo = undefined,+ isLoadingInBackground = false,+ imageId,+ repo,+ tag+ }: Props = $props();++ let isChecking = $state(false);++ const canCheckUpdate = $derived(repo && tag && repo !== '<none>' && tag !== '<none>');++ const displayCurrentVersion = $derived(() => {+ if (updateInfo?.currentVersion && updateInfo.currentVersion.trim() !== '') {+ return updateInfo.currentVersion;+ }+ return tag || 'Unknown';+ });++ const displayLatestVersion = $derived(() => {+ if (updateInfo?.latestVersion && updateInfo.latestVersion.trim() !== '') {+ return updateInfo.latestVersion;+ }+ if (updateInfo?.updateType === 'digest' && updateInfo?.latestDigest) {+ return updateInfo.latestDigest.slice(7, 19) + '...';+ }+ return null;+ });++ async function checkImageUpdate() {+ if (!canCheckUpdate || isChecking) return;++ isChecking = true;+ try {+ const result = await imageUpdateAPI.checkImageUpdateByID(imageId);+ if (result && !result.error) {+ toast.success('Update check completed');+ await invalidateAll();+ } else {+ toast.error(result?.error || 'Update check failed');+ }+ } catch (error) {+ console.error('Error checking update:', error);+ toast.error('Failed to check for updates');+ } finally {+ isChecking = false;+ }+ }++ function getUpdatePriority(updateInfo: ImageUpdateData): {+ level: string;+ color: string;+ description: string;+ } {+ if (!updateInfo.hasUpdate) {+ return { level: 'None', color: 'text-green-500', description: 'Image is up to date' };+ }++ if (updateInfo.updateType === 'digest') {+ return {+ level: 'Security/Bug Fix',+ color: 'text-blue-500',+ description: 'Digest update - likely security or bug fixes'+ };+ }++ if (updateInfo.updateType === 'tag') {+ let description = 'Update available';+ if (updateInfo.latestVersion) {+ description = `Update to ${updateInfo.latestVersion} available`;+ }+ return {+ level: 'Version Update',+ color: 'text-yellow-500',+ description+ };+ }++ return { level: 'Unknown', color: 'text-gray-500', description: 'Update type unknown' };+ }+</script>++{#if updateInfo}+ {@const priority = getUpdatePriority(updateInfo)}+ <Tooltip.Provider>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <span class="mr-2 inline-flex size-4 items-center justify-center align-middle">+ {#if !updateInfo.hasUpdate}+ <CircleCheck class="size-4 text-green-500" />+ {:else if updateInfo.updateType === 'digest'}+ <CircleArrowUp class="size-4 text-blue-500" />+ {:else}+ <CircleFadingArrowUp class="size-4 text-yellow-500" />+ {/if}+ </span>+ </Tooltip.Trigger>+ <Tooltip.Content+ side="right"+ class="tooltip-with-arrow relative max-w-[280px] rounded-xl border border-gray-200/50 bg-white/95 p-0 shadow-2xl shadow-black/10 backdrop-blur-sm dark:border-gray-800/50 dark:bg-gray-950/95 dark:shadow-black/30"+ align="center"+ >+ <div class="overflow-hidden rounded-xl">+ {#if !updateInfo.hasUpdate}+ <!-- Success State -->+ <div+ class="bg-gradient-to-br from-emerald-50 to-green-50/30 p-4 dark:from-emerald-950/20 dark:to-green-950/10"+ >+ <div class="flex items-center gap-3">+ <div+ class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-emerald-500 to-green-500 shadow-lg shadow-emerald-500/25"+ >+ <CircleCheck class="size-5 text-white" />+ </div>+ <div>+ <div class="text-sm font-semibold text-emerald-900 dark:text-emerald-100">+ Up to Date+ </div>+ <div class="text-xs text-emerald-700/80 dark:text-emerald-300/80">+ No updates available+ </div>+ </div>+ </div>+ </div>+ <div class="bg-white/90 p-4 dark:bg-gray-950/90">+ <div class="text-center">+ <div class="mb-2 text-xs text-gray-600 dark:text-gray-400">+ Running <span+ class="rounded bg-gray-100 px-1.5 py-0.5 font-mono text-xs font-medium dark:bg-gray-800"+ >{displayCurrentVersion()}</span+ >+ </div>+ <div class="text-xs leading-relaxed text-gray-500 dark:text-gray-400">+ This image is running the latest available version.+ </div>+ </div>+ </div>+ {:else if updateInfo.updateType === 'digest'}+ <!-- Digest Update State -->+ <div+ class="bg-gradient-to-br from-blue-50 to-cyan-50/30 p-4 dark:from-blue-950/20 dark:to-cyan-950/10"+ >+ <div class="flex items-center gap-3">+ <div+ class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-blue-500 to-cyan-500 shadow-lg shadow-blue-500/25"+ >+ <CircleArrowUp class="size-5 text-white" />+ </div>+ <div>+ <div class="text-sm font-semibold text-blue-900 dark:text-blue-100">+ Digest Update+ </div>+ <div class="text-xs text-blue-700/80 dark:text-blue-300/80">+ Security or bug fixes available+ </div>+ </div>+ </div>+ </div>+ <div class="bg-white/90 p-4 dark:bg-gray-950/90">+ <div class="space-y-3">+ <div class="space-y-2 text-xs">+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-1.5 text-gray-500 dark:text-gray-400">+ <Package class="size-3" />+ <span>Current</span>+ </div>+ <span+ class="rounded bg-gray-100 px-1.5 py-0.5 font-mono font-medium dark:bg-gray-800"+ >{displayCurrentVersion()}</span+ >+ </div>+ {#if displayLatestVersion()}+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-1.5 text-gray-500 dark:text-gray-400">+ <ArrowRight class="size-3" />+ <span>Latest Digest</span>+ </div>+ <span+ class="rounded bg-blue-100 px-1.5 py-0.5 font-mono font-medium text-blue-700 dark:bg-blue-900/30 dark:text-blue-300"+ >+ {displayLatestVersion()}+ </span>+ </div>+ {/if}+ </div>+ <div class="rounded-lg bg-blue-50 p-3 dark:bg-blue-950/30">+ <div+ class="text-xs text-center leading-relaxed text-blue-700 dark:text-blue-300 font-medium"+ >+ {priority.description}+ </div>+ </div>+ </div>+ </div>+ {:else}+ <!-- Version Update State -->+ <div+ class="bg-gradient-to-br from-amber-50 to-yellow-50/30 p-4 dark:from-amber-950/20 dark:to-yellow-950/10"+ >+ <div class="flex items-center gap-3">+ <div+ class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-amber-500 to-yellow-500 shadow-lg shadow-amber-500/25"+ >+ <CircleFadingArrowUp class="size-5 text-white" />+ </div>+ <div>+ <div class="text-sm font-semibold text-amber-900 dark:text-amber-100">+ Version Update+ </div>+ <div class="text-xs text-amber-700/80 dark:text-amber-300/80">+ New version available+ </div>+ </div>+ </div>+ </div>+ <div class="bg-white/90 p-4 dark:bg-gray-950/90">+ <div class="space-y-3">+ <div class="space-y-2 text-xs">+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-1.5 text-gray-500 dark:text-gray-400">+ <Package class="size-3" />+ <span>Current</span>+ </div>+ <span+ class="rounded bg-gray-100 px-1.5 py-0.5 font-mono font-medium dark:bg-gray-800"+ >{displayCurrentVersion()}</span+ >+ </div>+ {#if displayLatestVersion()}+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-1.5 text-gray-500 dark:text-gray-400">+ <ArrowRight class="size-3" />+ <span>Latest</span>+ </div>+ <span+ class="rounded bg-amber-100 px-1.5 py-0.5 font-mono font-medium text-amber-700 dark:bg-amber-900/30 dark:text-amber-300"+ >+ {displayLatestVersion()}+ </span>+ </div>+ {/if}+ </div>+ <div class="rounded-lg bg-amber-50 p-3 dark:bg-amber-950/30">+ <div+ class="text-xs text-center leading-relaxed text-amber-700 dark:text-amber-300 font-medium"+ >+ {priority.description}+ </div>+ </div>+ </div>+ </div>+ {/if}++ {#if canCheckUpdate}+ <div+ class="border-t border-gray-200/50 bg-gray-50/50 p-3 dark:border-gray-800/50 dark:bg-gray-900/50"+ >+ <button+ onclick={checkImageUpdate}+ disabled={isChecking}+ class="group flex w-full items-center justify-center gap-2 rounded-lg bg-white/80 px-3 py-2 text-xs font-medium text-gray-700 shadow-sm transition-all hover:bg-white hover:shadow-md disabled:cursor-not-allowed disabled:opacity-50 dark:bg-gray-800/80 dark:text-gray-300 dark:hover:bg-gray-800"+ >+ {#if isChecking}+ <Loader2 class="size-3 animate-spin" />+ Checking...+ {:else}+ <RefreshCw class="size-3 transition-transform group-hover:rotate-45" />+ Re-check Updates+ {/if}+ </button>+ </div>+ {/if}+ </div>+ </Tooltip.Content>+ </Tooltip.Root>+ </Tooltip.Provider>+{:else if isLoadingInBackground || isChecking}+ <Tooltip.Provider>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <span class="mr-2 inline-flex size-4 items-center justify-center align-middle">+ <Loader2 class="size-4 animate-spin text-blue-400" />+ </span>+ </Tooltip.Trigger>+ <Tooltip.Content+ side="right"+ class="tooltip-with-arrow relative max-w-[220px] rounded-xl border border-gray-200/50 bg-white/95 p-0 shadow-2xl shadow-black/10 backdrop-blur-sm dark:border-gray-800/50 dark:bg-gray-950/95 dark:shadow-black/30"+ align="center"+ >+ <div class="overflow-hidden rounded-xl">+ <div+ class="bg-gradient-to-br from-blue-50 to-cyan-50/30 p-4 dark:from-blue-950/20 dark:to-cyan-950/10"+ >+ <div class="flex items-center gap-3">+ <div+ class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-blue-500 to-cyan-500 shadow-lg shadow-blue-500/25"+ >+ <Loader2 class="size-5 animate-spin text-white" />+ </div>+ <div>+ <div class="text-sm font-semibold text-blue-900 dark:text-blue-100">+ Checking Updates+ </div>+ <div class="text-xs text-blue-700/80 dark:text-blue-300/80">+ Querying registry for latest version...+ </div>+ </div>+ </div>+ </div>+ </div>+ </Tooltip.Content>+ </Tooltip.Root>+ </Tooltip.Provider>+{:else}+ <Tooltip.Provider>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <span class="mr-2 inline-flex size-4 items-center justify-center">+ {#if canCheckUpdate}+ <button+ onclick={checkImageUpdate}+ disabled={isChecking}+ class="group flex h-4 w-4 items-center justify-center rounded-full border-2 border-dashed border-gray-400 transition-colors hover:border-blue-400 hover:bg-blue-50 disabled:cursor-not-allowed dark:hover:bg-blue-950"+ >+ {#if isChecking}+ <Loader2 class="h-2 w-2 animate-spin text-blue-400" />+ {:else}+ <div+ class="h-1.5 w-1.5 rounded-full bg-gray-400 transition-colors group-hover:bg-blue-400"+ ></div>+ {/if}+ </button>+ {:else}+ <div+ class="flex h-4 w-4 items-center justify-center rounded-full border-2 border-dashed border-gray-400 opacity-30"+ >+ <div class="h-1.5 w-1.5 rounded-full bg-gray-400"></div>+ </div>+ {/if}+ </span>+ </Tooltip.Trigger>+ <Tooltip.Content+ side="right"+ class="tooltip-with-arrow relative max-w-[240px] rounded-xl border border-gray-200/50 bg-white/95 p-0 shadow-2xl shadow-black/10 backdrop-blur-sm dark:border-gray-800/50 dark:bg-gray-950/95 dark:shadow-black/30"+ align="center"+ >+ <div class="overflow-hidden rounded-xl">+ <div+ class="bg-gradient-to-br from-gray-50 to-slate-50/30 p-4 dark:from-gray-900/20 dark:to-slate-900/10"+ >+ <div class="flex items-center gap-3">+ <div+ class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-gray-400 to-slate-500 shadow-lg shadow-gray-400/25"+ >+ <AlertTriangle class="size-5 text-white" />+ </div>+ <div>+ <div class="text-sm font-semibold text-gray-900 dark:text-gray-100">+ Status Unknown+ </div>+ <div class="text-xs text-gray-700/80 dark:text-gray-300/80">+ {#if canCheckUpdate}+ Click to check for updates from registry.+ {:else}+ Unable to check updates for images without proper tags.+ {/if}+ </div>+ </div>+ </div>+ </div>+ </div>+ </Tooltip.Content>+ </Tooltip.Root>+ </Tooltip.Provider>+{/if}diff --git a/frontend/src/lib/components/maturity-item.svelte b/frontend/src/lib/components/maturity-item.sveltedeleted file mode 100644index 6e17a4fa3..000000000--- a/frontend/src/lib/components/maturity-item.svelte+++ /dev/null@@ -1,353 +0,0 @@-<script lang="ts">- import * as Tooltip from '$lib/components/ui/tooltip/index.js';- import {- CircleCheck,- CircleFadingArrowUp,- CircleArrowUp,- Loader2,- Clock,- Package,- Calendar,- AlertTriangle,- RefreshCw,- ArrowRight- } from '@lucide/svelte';- import { environmentAPI } from '$lib/services/api';- import { toast } from 'svelte-sonner';- import { invalidateAll } from '$app/navigation';- import { formatDate } from '$lib/utils/string.utils';-- interface MaturityData {- updatesAvailable: boolean;- status: string;- version?: string;- date?: string;- latestVersion?: string;- }-- interface Props {- maturity?: MaturityData | undefined;- isLoadingInBackground?: boolean;- imageId: string;- repo?: string;- tag?: string;- }-- let { maturity = undefined, isLoadingInBackground = false, imageId, repo, tag }: Props = $props();-- let isChecking = $state(false);-- const canCheckMaturity = $derived(repo && tag && repo !== '<none>' && tag !== '<none>');-- async function checkImageMaturity() {- if (!canCheckMaturity || isChecking) return;-- isChecking = true;- try {- const result = await environmentAPI.triggerMaturityCheck([imageId]);-- if (result.success) {- toast.success('Maturity check completed');- await invalidateAll();- } else {- toast.error('Maturity check failed');- }- } catch (error) {- console.error('Error checking maturity:', error);- toast.error('Failed to check maturity');- } finally {- isChecking = false;- }- }-- function getStatusColor(status: string): string {- switch (status) {- case 'Matured':- return 'text-green-500';- case 'Not Matured':- return 'text-amber-500';- case 'Unknown':- return 'text-gray-500';- default:- return 'text-gray-500';- }- }-- function getUpdatePriority(maturity: MaturityData): {- level: string;- color: string;- description: string;- } {- if (!maturity.updatesAvailable) {- return { level: 'None', color: 'text-green-500', description: 'Image is up to date' };- }-- let description = 'Stable update available';- if (maturity.latestVersion) {- description = `Update to ${maturity.latestVersion} available`;- }-- if (maturity.status === 'Matured') {- return { level: 'Recommended', color: 'text-blue-500', description };- }-- if (maturity.status === 'Not Matured') {- return {- level: 'Optional',- color: 'text-yellow-500',- description: maturity.latestVersion- ? `${maturity.latestVersion} available, but not yet matured`- : 'Recent update, may be unstable'- };- }-- return { level: 'Unknown', color: 'text-gray-500', description: 'Update status unclear' };- }-</script>--{#if maturity}- {@const priority = getUpdatePriority(maturity)}- <Tooltip.Provider>- <Tooltip.Root>- <Tooltip.Trigger>- <span class="mr-2 inline-flex size-4 items-center justify-center align-middle">- {#if !maturity.updatesAvailable}- <CircleCheck- class="size-4 text-green-500"- fill="none"- stroke="currentColor"- strokeWidth="2"- />- {:else if maturity.status === 'Not Matured'}- <CircleFadingArrowUp- class="size-4 text-yellow-500"- fill="none"- stroke="currentColor"- stroke-width="2"- />- {:else}- <CircleArrowUp- class="size-4 text-blue-500"- fill="none"- stroke="currentColor"- stroke-width="2"- />- {/if}- </span>- </Tooltip.Trigger>- <Tooltip.Content- side="right"- class="bg-popover text-popover-foreground border-border tooltip-with-arrow maturity-tooltip relative max-w-[280px] border p-4 shadow-lg"- align="center"- >- <div class="space-y-3">- <!-- Header with icon and status -->- <div class="border-border flex items-center gap-3 border-b pb-2">- {#if !maturity.updatesAvailable}- <div- class="flex h-8 w-8 items-center justify-center rounded-full border border-green-500/20 bg-green-500/10"- >- <CircleCheck- class="size-5 text-green-500"- fill="none"- stroke="currentColor"- strokeWidth="2"- />- </div>- <div>- <div class="text-sm font-semibold">Up to Date</div>- <div class="text-muted-foreground text-xs">No updates available</div>- </div>- {:else if maturity.status === 'Not Matured'}- <div- class="flex h-8 w-8 items-center justify-center rounded-full border border-yellow-500/20 bg-yellow-500/10"- >- <CircleFadingArrowUp- class="size-5 text-yellow-500"- fill="none"- stroke="currentColor"- stroke-width="2"- />- </div>- <div>- <div class="text-sm font-semibold">Update Available</div>- <div class="flex items-center gap-1 text-xs text-yellow-600 dark:text-yellow-400">- <AlertTriangle class="size-3" />- Not yet matured- </div>- </div>- {:else}- <div- class="flex h-8 w-8 items-center justify-center rounded-full border border-blue-500/20 bg-blue-500/10"- >- <CircleArrowUp- class="size-5 text-blue-500"- fill="none"- stroke="currentColor"- stroke-width="2"- />- </div>- <div>- <div class="text-sm font-semibold">Stable Update</div>- <div class="text-xs text-blue-600 dark:text-blue-400">Recommended for update</div>- </div>- {/if}- </div>-- <!-- Details grid -->- <div class="grid gap-2 text-xs">- <div class="flex items-center justify-between">- <div class="text-muted-foreground flex items-center gap-1.5">- <Package class="size-3" />- <span>Current</span>- </div>- <span class="font-mono font-medium">{maturity.version || 'Unknown'}</span>- </div>-- <!-- Show latest version if updates are available -->- {#if maturity.updatesAvailable && maturity.latestVersion}- <div class="flex items-center justify-between">- <div class="text-muted-foreground flex items-center gap-1.5">- <ArrowRight class="size-3" />- <span>Latest</span>- </div>- <span class="font-mono font-medium text-blue-600 dark:text-blue-400"- >{maturity.latestVersion}</span- >- </div>- {/if}-- <div class="flex items-center justify-between">- <div class="text-muted-foreground flex items-center gap-1.5">- <Calendar class="size-3" />- <span>Released</span>- </div>- <span class="font-medium">{formatDate(maturity.date)}</span>- </div>-- <div class="flex items-center justify-between">- <div class="text-muted-foreground flex items-center gap-1.5">- <Clock class="size-3" />- <span>Status</span>- </div>- <span class="font-medium {getStatusColor(maturity.status)}">- {maturity.status || 'Unknown'}- </span>- </div>-- <div class="flex items-center justify-between">- <div class="text-muted-foreground flex items-center gap-1.5">- <span>Priority</span>- </div>- <span class="font-medium {priority.color}">- {priority.level}- </span>- </div>- </div>-- <!-- Update recommendation -->- <div class="border-border border-t pt-2">- <div class="text-muted-foreground text-xs leading-relaxed">- {priority.description}- </div>- </div>-- <!-- Re-check button -->- {#if canCheckMaturity}- <div class="border-border border-t pt-2">- <button- onclick={checkImageMaturity}- disabled={isChecking}- class="flex items-center gap-1.5 text-xs text-blue-600 hover:text-blue-700 disabled:cursor-not-allowed disabled:opacity-50 dark:text-blue-400 dark:hover:text-blue-300"- >- {#if isChecking}- <Loader2 class="size-3 animate-spin" />- Checking...- {:else}- <RefreshCw class="size-3" />- Re-check Updates- {/if}- </button>- </div>- {/if}- </div>- </Tooltip.Content>- </Tooltip.Root>- </Tooltip.Provider>-{:else if isLoadingInBackground || isChecking}- <Tooltip.Provider>- <Tooltip.Root>- <Tooltip.Trigger>- <span class="mr-2 inline-flex size-4 items-center justify-center align-middle">- <Loader2 class="size-4 animate-spin text-blue-400" />- </span>- </Tooltip.Trigger>- <Tooltip.Content- side="right"- class="bg-popover text-popover-foreground border-border tooltip-with-arrow relative max-w-[220px] border p-3 shadow-lg"- align="center"- >- <div class="flex items-center gap-2">- <Loader2 class="size-4 animate-spin text-blue-400" />- <div>- <div class="text-sm font-medium">Checking Updates</div>- <div class="text-muted-foreground text-xs">Querying registry for latest version...</div>- </div>- </div>- </Tooltip.Content>- </Tooltip.Root>- </Tooltip.Provider>-{:else}- <Tooltip.Provider>- <Tooltip.Root>- <Tooltip.Trigger>- <span class="mr-2 inline-flex size-4 items-center justify-center">- {#if canCheckMaturity}- <button- onclick={checkImageMaturity}- disabled={isChecking}- class="group flex h-4 w-4 items-center justify-center rounded-full border-2 border-dashed border-gray-400 transition-colors hover:border-blue-400 hover:bg-blue-50 disabled:cursor-not-allowed dark:hover:bg-blue-950"- >- {#if isChecking}- <Loader2 class="h-2 w-2 animate-spin text-blue-400" />- {:else}- <div- class="h-1.5 w-1.5 rounded-full bg-gray-400 transition-colors group-hover:bg-blue-400"- ></div>- {/if}- </button>- {:else}- <div- class="flex h-4 w-4 items-center justify-center rounded-full border-2 border-dashed border-gray-400 opacity-30"- >- <div class="h-1.5 w-1.5 rounded-full bg-gray-400"></div>- </div>- {/if}- </span>- </Tooltip.Trigger>- <Tooltip.Content- side="right"- class="bg-popover text-popover-foreground border-border tooltip-with-arrow relative max-w-[240px] border p-3 shadow-lg"- align="center"- >- <div class="flex items-center gap-2">- <div- class="bg-muted border-border flex h-6 w-6 items-center justify-center rounded-full border"- >- <AlertTriangle class="text-muted-foreground size-3" />- </div>- <div>- <div class="text-sm font-medium">Status Unknown</div>- <div class="text-muted-foreground text-xs leading-relaxed">- {#if canCheckMaturity}- Click to check for updates from registry.- {:else}- Unable to check maturity for images without proper tags.- {/if}- </div>- </div>- </div>- </Tooltip.Content>- </Tooltip.Root>- </Tooltip.Provider>-{/if}diff --git a/frontend/src/lib/components/meter-metric.svelte b/frontend/src/lib/components/meter-metric.svelteindex bcf4282b3..2b7a529ad 100644--- a/frontend/src/lib/components/meter-metric.svelte+++ b/frontend/src/lib/components/meter-metric.svelte@@ -33,28 +33,47 @@</script><div- class="group relative overflow-hidden rounded-lg border border-white/10 bg-gradient-to-br from-white/5 to-white/2 backdrop-blur-sm transition-all duration-300 hover:border-white/20 hover:bg-gradient-to-br hover:from-white/10 hover:to-white/5"+ class="group relative overflow-hidden rounded-xl border border-gray-200/50 bg-white/95 shadow-2xl shadow-black/10 backdrop-blur-sm transition-all duration-300 hover:border-gray-300/60 hover:shadow-3xl hover:shadow-black/15 dark:border-gray-800/50 dark:bg-gray-950/95 dark:shadow-black/30 dark:hover:border-gray-700/60">+ <!-- Header Section with Gradient --><div- class="absolute inset-0 bg-gradient-to-br from-white/5 via-transparent to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100"- ></div>-- <div class="relative z-10 p-4">- <div class="mb-3 text-center">- <h3 class="text-sm font-medium text-white/90">{title}</h3>- {#if description}- <p class="text-xs text-white/60">{description}</p>- {/if}+ class="bg-gradient-to-br from-gray-50 to-slate-50/30 p-4 dark:from-gray-900/20 dark:to-slate-900/10"+ >+ <div class="flex items-center gap-3">+ <div+ class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-primary to-primary/80 shadow-lg shadow-primary/25"+ >+ <div class="text-sm font-bold text-primary-foreground">📊</div>+ </div>+ <div>+ <div class="text-sm font-semibold text-gray-900 dark:text-gray-100">{title}</div>+ {#if description}+ <div class="text-xs text-gray-700/80 dark:text-gray-300/80">{description}</div>+ {/if}+ </div></div>+ </div>- <div class="flex flex-col items-center space-y-3">- <div class="text-2xl font-bold text-white/95">{formatValue(currentValue)}</div>+ <!-- Content Section -->+ <div class="bg-white/90 p-4 dark:bg-gray-950/90">+ <div class="space-y-3">+ <div class="text-center">+ <div class="text-2xl font-bold text-gray-900 dark:text-gray-100">+ {formatValue(currentValue)}+ </div>+ </div>- <div class="w-full max-w-[100px]">- <Meter value={percentage} class="h-1.5 bg-white/10" />+ <div class="flex justify-center">+ <div class="w-full max-w-[120px]">+ <Meter value={percentage} class="h-2 bg-gray-200 dark:bg-gray-800" />+ </div></div>- <div class="text-xs font-medium text-white/70">{percentage.toFixed(1)}%</div>+ <div class="rounded-lg bg-primary/10 p-3 dark:bg-primary/20">+ <div class="text-xs text-center font-medium leading-relaxed text-primary dark:text-primary">+ {percentage.toFixed(1)}% of maximum capacity+ </div>+ </div></div></div></div>diff --git a/frontend/src/lib/components/universal-table.svelte b/frontend/src/lib/components/universal-table.sveltedeleted file mode 100644index fd82e4443..000000000--- a/frontend/src/lib/components/universal-table.svelte+++ /dev/null@@ -1,247 +0,0 @@-<script lang="ts" generics="TData extends Record<string, any>">- import { Checkbox } from '$lib/components/ui/checkbox/index.js';- import { Input } from '$lib/components/ui/input/index.js';- import * as Pagination from '$lib/components/ui/pagination/index.js';- import * as Select from '$lib/components/ui/select/index.js';- import * as Table from '$lib/components/ui/table/index.js';- import { Button } from '$lib/components/ui/button/index.js';- import { ChevronDown } from '@lucide/svelte';- import { cn } from '$lib/utils';- import { debounced } from '$lib/utils';- import type { Snippet } from 'svelte';- import type { ExternalPagination } from '$lib/types/pagination.type';-- let {- data,- externalPagination,- selectedIds = $bindable(),- withoutSearch = false,- selectionDisabled = false,- onRefresh,- onPageChange,- onPageSizeChange,- onSort,- columns,- rows,- idKey = 'id',- filterPlaceholder = 'Search...',- noResultsMessage = 'No results found',- itemsPerPageLabel = 'Items per page',- class: className = ''- }: {- data: TData[];- externalPagination?: ExternalPagination;- selectedIds?: string[];- withoutSearch?: boolean;- selectionDisabled?: boolean;- onRefresh?: () => Promise<void>;- onPageChange?: (page: number) => void;- onPageSizeChange?: (size: number) => void;- onSort?: (column: string, direction: 'asc' | 'desc') => void;- columns: { label: string; hidden?: boolean; sortColumn?: string }[];- rows: Snippet<[{ item: TData; index?: number }]>;- idKey?: string;- filterPlaceholder?: string;- noResultsMessage?: string;- itemsPerPageLabel?: string;- class?: string;- } = $props();-- let searchValue = $state('');- let availablePageSizes: number[] = [10, 20, 50, 100];- let sortColumn = $state<string>('');- let sortDirection = $state<'asc' | 'desc'>('asc');-- const isExternalPagination = $derived(!!externalPagination);-- let allChecked = $derived.by(() => {- if (!selectedIds || data.length === 0) return false;- for (const item of data) {- const itemId = String(item[idKey]);- if (!selectedIds.includes(itemId)) {- return false;- }- }- return true;- });-- const onSearch = debounced(async (search: string) => {- searchValue = search;- if (onRefresh) {- await onRefresh();- }- }, 300);-- const filteredData = $derived(() => {- if (!searchValue || isExternalPagination) return data;-- return data.filter((item) => {- return Object.values(item).some((value) =>- String(value).toLowerCase().includes(searchValue.toLowerCase())- );- });- });-- async function onAllCheck(checked: boolean) {- if (checked) {- selectedIds = data.map((item) => String(item[idKey]));- } else {- selectedIds = [];- }- }-- async function onCheck(checked: boolean, id: string) {- if (!selectedIds) return;- if (checked) {- selectedIds = [...selectedIds, id];- } else {- selectedIds = selectedIds.filter((selectedId) => selectedId !== id);- }- }-- async function handlePageChange(page: number) {- onPageChange?.(page);- }-- async function handlePageSizeChange(size: number) {- onPageSizeChange?.(size);- }-- async function handleSort(column?: string, direction: 'asc' | 'desc' = 'asc') {- if (!column) return;-- sortColumn = column;- sortDirection = direction;- onSort?.(column, direction);- }-- const currentPageSize = $derived(externalPagination?.pageSize || 10);-- const currentPage = $derived(externalPagination?.currentPage || 1);-- const totalItems = $derived(externalPagination?.totalItems || filteredData.length);-</script>--<div class={cn('space-y-4', className)}>- {#if !withoutSearch}- <Input- value={searchValue}- class={cn('relative z-50 max-w-sm', data.length == 0 && searchValue == '' && 'hidden')}- placeholder={filterPlaceholder}- type="text"- oninput={(e) => onSearch(e.currentTarget.value)}- />- {/if}-- {#if data.length === 0 && searchValue === ''}- <div class="my-5 flex flex-col items-center">- <p class="text-muted-foreground mt-3 text-sm">{noResultsMessage}</p>- </div>- {:else}- <div class="rounded-md border">- <Table.Root class="min-w-full table-auto overflow-x-auto">- <Table.Header>- <Table.Row>- {#if selectedIds !== undefined}- <Table.Head class="w-12">- <Checkbox- disabled={selectionDisabled}- checked={allChecked}- onCheckedChange={(c) => onAllCheck(c as boolean)}- />- </Table.Head>- {/if}- {#each columns as column}- <Table.Head class={cn(column.hidden && 'sr-only', column.sortColumn && 'px-0')}>- {#if column.sortColumn}- <Button- variant="ghost"- class="flex items-center"- onclick={() =>- handleSort(- column.sortColumn,- sortColumn === column.sortColumn && sortDirection === 'asc' ? 'desc' : 'asc'- )}- >- {column.label}- {#if sortColumn === column.sortColumn}- <ChevronDown- class={cn('ml-2 size-4', sortDirection === 'asc' ? 'rotate-180' : '')}- />- {/if}- </Button>- {:else}- {column.label}- {/if}- </Table.Head>- {/each}- </Table.Row>- </Table.Header>- <Table.Body>- {#each filteredData as item, index}- {@const itemId = String(item[idKey])}- <Table.Row class={selectedIds?.includes(itemId) ? 'bg-muted/20' : ''}>- {#if selectedIds !== undefined}- <Table.Cell class="w-12">- <Checkbox- disabled={selectionDisabled}- checked={selectedIds.includes(itemId)}- onCheckedChange={(c) => onCheck(c as boolean, itemId)}- />- </Table.Cell>- {/if}- {@render rows({ item, index })}- </Table.Row>- {/each}- </Table.Body>- </Table.Root>- </div>-- <div class="mt-5 flex flex-col-reverse items-center justify-between gap-3 sm:flex-row">- <div class="flex items-center space-x-2">- <p class="text-sm font-medium">{itemsPerPageLabel}</p>- <Select.Root- type="single"- value={currentPageSize.toString()}- onValueChange={(v) => handlePageSizeChange(Number(v))}- >- <Select.Trigger class="h-9 w-[80px]">- {currentPageSize}- </Select.Trigger>- <Select.Content>- {#each availablePageSizes as size}- <Select.Item value={size.toString()}>{size}</Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>- <Pagination.Root- class="mx-0 w-auto"- count={totalItems}- perPage={currentPageSize}- onPageChange={handlePageChange}- page={currentPage}- >- {#snippet children({ pages })}- <Pagination.Content class="flex justify-end">- <Pagination.Item>- <Pagination.PrevButton />- </Pagination.Item>- {#each pages as page (page.key)}- {#if page.type !== 'ellipsis' && page.value != 0}- <Pagination.Item>- <Pagination.Link {page} isActive={currentPage === page.value}>- {page.value}- </Pagination.Link>- </Pagination.Item>- {/if}- {/each}- <Pagination.Item>- <Pagination.NextButton />- </Pagination.Item>- </Pagination.Content>- {/snippet}- </Pagination.Root>- </div>- {/if}-</div>diff --git a/frontend/src/lib/models/image.type.ts b/frontend/src/lib/models/image.type.tsindex fd953b083..63ac2c43b 100644--- a/frontend/src/lib/models/image.type.ts+++ b/frontend/src/lib/models/image.type.ts@@ -1,44 +1,49 @@import type Docker from 'dockerode';export type ServiceImage = Docker.ImageInfo & {- repo: string;- tag: string;- Architecture?: string;- Os?: string;- Config?: {- User?: string;- ExposedPorts?: Record<string, any>;- Env?: string[];- Entrypoint?: string[];- WorkingDir?: string;- Labels?: Record<string, string>;- };- GraphDriver?: {- Data: any;- Name: string;- };- RootFS?: {- Type: string;- Layers: string[];- };- Metadata?: {- LastTagTime?: string;- };- Descriptor?: {- mediaType: string;- digest: string;- size: number;- };+ repo: string;+ tag: string;+ Architecture?: string;+ Os?: string;+ Config?: {+ User?: string;+ ExposedPorts?: Record<string, any>;+ Env?: string[];+ Entrypoint?: string[];+ WorkingDir?: string;+ Labels?: Record<string, string>;+ };+ GraphDriver?: {+ Data: any;+ Name: string;+ };+ RootFS?: {+ Type: string;+ Layers: string[];+ };+ Metadata?: {+ LastTagTime?: string;+ };+ Descriptor?: {+ mediaType: string;+ digest: string;+ size: number;+ };};-export interface ImageMaturity {- version: string;- date: string;- status: 'Matured' | 'Not Matured' | 'Unknown';- updatesAvailable: boolean;+export interface ImageUpdateInfo {+ hasUpdate: boolean;+ updateType: string;+ currentVersion: string;+ latestVersion?: string;+ currentDigest?: string;+ latestDigest?: string;+ checkTime: string;+ responseTimeMs: number;+ error?: string;}export type EnhancedImageInfo = ServiceImage & {- InUse: boolean;- maturity?: ImageMaturity;+ InUse: boolean;+ updateInfo?: ImageUpdateInfo;};diff --git a/frontend/src/lib/services/api/image-maturity-api-service.ts b/frontend/src/lib/services/api/image-maturity-api-service.tsdeleted file mode 100644index 04809dab6..000000000--- a/frontend/src/lib/services/api/image-maturity-api-service.ts+++ /dev/null@@ -1,135 +0,0 @@-import BaseAPIService from './api-service';-import type { ImageMaturity } from '$lib/models/image.type';--export interface ImageMaturityRecord {- id: string;- repository: string;- tag: string;- currentVersion: string;- latestVersion: string | null;- status: 'Matured' | 'Not Matured' | 'Unknown';- updatesAvailable: boolean;- currentImageDate: Date | null;- latestImageDate: Date | null;- daysSinceCreation: number | null;- registryDomain: string | null;- isPrivateRegistry: boolean;- lastChecked: Date;- checkCount: number;- lastError: string | null;- responseTimeMs: number | null;- createdAt: Date;- updatedAt: Date;-}--export interface MaturityStats {- total: number;- withUpdates: number;- matured: number;- notMatured: number;- unknown: number;- averageAge: number;- recentlyChecked: number;-}--export interface BatchMaturityResult {- success: boolean;- results: Record<string, ImageMaturity>;- errors: Record<string, string>;- stats: {- total: number;- success: number;- failed: number;- };-}--export interface ManualCheckResult {- success: boolean;- message: string;- stats: MaturityStats & {- total: number;- checked: number;- updated: number;- };-}--export default class ImageMaturityAPIService extends BaseAPIService {- async checkMaturity(id: string): Promise<ImageMaturity> {- const res = await this.api.get(`/images/maturity/${id}`);- return res.data;- }-- // Get all maturity records- async listMaturityRecords(): Promise<ImageMaturityRecord[]> {- const res = await this.api.get('/images/maturity');- return res.data;- }-- // Get maturity statistics- async getMaturityStats(): Promise<MaturityStats> {- const res = await this.api.get('/images/maturity/stats');- return res.data;- }-- // Get images with available updates- async getImagesWithUpdates(): Promise<ImageMaturityRecord[]> {- const res = await this.api.get('/images/maturity/updates');- return res.data;- }-- // Get images needing check- async getImagesNeedingCheck(maxAge: number = 1440, limit: number = 100): Promise<ImageMaturityRecord[]> {- const res = await this.api.get('/images/maturity/needs-check', {- params: { maxAge, limit }- });- return res.data;- }-- // Trigger maturity check for all images- async triggerMaturityCheck(imageIds?: string[]): Promise<{ success: boolean; message: string }> {- const payload = imageIds && imageIds.length > 0 ? { imageIds } : {};- const res = await this.api.post('/images/maturity/check', payload);- return res.data;- }-- // Get maturity records by repository- async getMaturityByRepository(repository: string): Promise<ImageMaturityRecord[]> {- const encodedRepository = encodeURIComponent(repository);- const res = await this.api.get(`/images/maturity/repository/${encodedRepository}`);- return res.data;- }-- // Legacy methods - keeping for backward compatibility but marking as deprecated-- /**- * @deprecated Use triggerMaturityCheck() instead- */- async triggerManualMaturityCheck(force: boolean = false): Promise<ManualCheckResult> {- console.warn('triggerManualMaturityCheck is deprecated, use triggerMaturityCheck instead');- const res = await this.api.post('/images/maturity/check', { force });- return res.data;- }-- /**- * @deprecated Use triggerMaturityCheck() instead - batch checking is now handled automatically- */- async checkMaturityBatch(imageIds: string[]): Promise<BatchMaturityResult> {- console.warn('checkMaturityBatch is deprecated, use triggerMaturityCheck for all images');- if (!imageIds || imageIds.length === 0) {- throw new Error('No image IDs provided for batch check');- }-- // Fallback: trigger general maturity check- const result = await this.triggerMaturityCheck();- return {- success: result.success,- results: {},- errors: {},- stats: {- total: imageIds.length,- success: result.success ? imageIds.length : 0,- failed: result.success ? 0 : imageIds.length- }- };- }-}diff --git a/frontend/src/lib/services/api/image-update-api-service.ts b/frontend/src/lib/services/api/image-update-api-service.tsnew file mode 100644index 000000000..895468d87--- /dev/null+++ b/frontend/src/lib/services/api/image-update-api-service.ts@@ -0,0 +1,83 @@+import BaseAPIService from './api-service';++export interface ImageUpdateData {+ hasUpdate: boolean;+ updateType: string;+ currentVersion: string;+ latestVersion?: string;+ currentDigest?: string;+ latestDigest?: string;+ checkTime: string;+ responseTimeMs: number;+ error?: string;+}++export interface ImageUpdateSummary {+ totalImages: number;+ imagesWithUpdates: number;+ digestUpdates: number;+ tagUpdates: number;+ errorsCount: number;+}++export interface ImageVersions {+ imageRef: string;+ current: string;+ versions: string[];+ latest?: string;+}++export interface VersionComparison {+ currentVersion: string;+ targetVersion: string;+ isNewer: boolean;+ updateType: string;+ changeLevel: string;+}++export interface BatchImageUpdateRequest {+ imageRefs: string[];+}++export interface CompareVersionRequest {+ currentVersion: string;+ targetVersion: string;+ imageRef: string;+}++export default class ImageUpdateAPIService extends BaseAPIService {+ async checkImageUpdate(imageRef: string): Promise<ImageUpdateData> {+ const res = await this.api.get(`/image-updates/check?imageRef=${encodeURIComponent(imageRef)}`);+ return this.handleResponse(res.data);+ }++ async checkImageUpdateByID(imageId: string): Promise<ImageUpdateData> {+ const res = await this.api.get(`/image-updates/check/${imageId}`);+ return this.handleResponse(res.data);+ }++ async checkMultipleImages(imageRefs: string[]): Promise<Record<string, ImageUpdateData>> {+ const res = await this.api.post('/image-updates/check-batch', { imageRefs });+ return this.handleResponse(res.data);+ }++ async checkAllImages(limit: number = 50): Promise<Record<string, ImageUpdateData>> {+ const res = await this.api.get(`/image-updates/check-all?limit=${limit}`);+ return this.handleResponse(res.data);+ }++ async getUpdateSummary(): Promise<ImageUpdateSummary> {+ const res = await this.api.get('/image-updates/summary');+ return this.handleResponse(res.data);+ }++ async getImageVersions(imageRef: string, limit: number = 20): Promise<ImageVersions> {+ const res = await this.api.get(`/image-updates/versions?imageRef=${encodeURIComponent(imageRef)}&limit=${limit}`);+ return this.handleResponse(res.data);+ }++ async compareVersions(request: CompareVersionRequest): Promise<VersionComparison> {+ const res = await this.api.post('/image-updates/compare', request);+ return this.handleResponse(res.data);+ }+}\ No newline at end of filediff --git a/frontend/src/lib/services/api/index.ts b/frontend/src/lib/services/api/index.tsindex 72955c8e1..6e6d0d5ca 100644--- a/frontend/src/lib/services/api/index.ts+++ b/frontend/src/lib/services/api/index.ts@@ -1,5 +1,5 @@import ImageAPIService from './image-api-service';-import ImageMaturityAPIService from './image-maturity-api-service';+import ImageUpdateAPIService from './image-update-api-service';import SystemAPIService from './system-api-service';import TemplateAPIService from './template-api-service';import UserAPIService from './user-api-service';@@ -14,7 +14,7 @@ import { EnvironmentAPIService } from './environment-api-service';import EnvironmentManagementAPIService from './environment-management-api-service';export const imageAPI = new ImageAPIService();-export const imageMaturityAPI = new ImageMaturityAPIService();+export const imageUpdateAPI = new ImageUpdateAPIService();export const systemAPI = new SystemAPIService();export const templateAPI = new TemplateAPIService();export const userAPI = new UserAPIService();@@ -30,7 +30,7 @@ export const environmentManagementAPI = new EnvironmentManagementAPIService();interface APIServices {image: ImageAPIService;- imageMaturity: ImageMaturityAPIService;+ imageUpdate: ImageUpdateAPIService;system: SystemAPIService;template: TemplateAPIService;user: UserAPIService;@@ -47,7 +47,7 @@ interface APIServices {const apiServices: APIServices = {image: imageAPI,- imageMaturity: imageMaturityAPI,+ imageUpdate: imageUpdateAPI,system: systemAPI,template: templateAPI,user: userAPI,diff --git a/frontend/src/lib/stores/maturity-store.ts b/frontend/src/lib/stores/maturity-store.tsdeleted file mode 100644index b3f25c168..000000000--- a/frontend/src/lib/stores/maturity-store.ts+++ /dev/null@@ -1,148 +0,0 @@-import { writable } from 'svelte/store';-import type { ImageMaturity } from '$lib/models/image.type';-import { environmentAPI } from '$lib/services/api';--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);--export function updateImageMaturity(imageId: string, maturity: ImageMaturity | undefined): void {- maturityStore.update((state) => {- const newData = { ...state.maturityData };-- if (maturity) {- const processedMaturity = {- ...maturity,- date: normalizeDate(maturity.date)- };- newData[imageId] = processedMaturity;- } else {- delete newData[imageId];- }-- return {- ...state,- maturityData: newData- };- });-}--function normalizeDate(dateString: string): string {- try {- const date = new Date(dateString);- if (isNaN(date.getTime())) {- return new Date().toISOString();- }- return date.toISOString();- } catch {- return new Date().toISOString();- }-}--export function setMaturityChecking(isChecking: boolean): void {- maturityStore.update((state) => ({- ...state,- isChecking,- lastChecked: isChecking ? state.lastChecked : new Date()- }));-}--export async function loadImageMaturityBatch(imageIds: string[]): Promise<void> {- if (imageIds.length === 0) return;-- try {- const BATCH_SIZE = 2;- for (let i = 0; i < imageIds.length; i += BATCH_SIZE) {- const batch = imageIds.slice(i, i + BATCH_SIZE);-- for (const imageId of batch) {- try {- const response = await environmentAPI.getImageMaturity(imageId);- if (response && response.data) {- updateImageMaturity(imageId, response.data);- }- } catch (error) {- console.error(`Failed to load maturity for image ${imageId}:`, error);- updateImageMaturity(imageId, {- version: 'unknown',- date: new Date().toISOString(),- status: 'Unknown',- updatesAvailable: false- });- }- }-- if (i + BATCH_SIZE < imageIds.length) {- await new Promise((resolve) => setTimeout(resolve, 50));- }- }- } catch (error) {- console.error('Error loading maturity data batch:', error);- }-}--export async function loadTopImagesMaturity(images: any[]): Promise<void> {- if (!images || images.length === 0) return;-- const topImageIds = [...images]- .sort((a, b) => (b.Size || 0) - (a.Size || 0))- .slice(0, 5)- .filter((img) => {- if (!img.RepoTags || img.RepoTags.length === 0) return false;- const repoTag = img.RepoTags[0];- return repoTag !== '<none>:<none>';- })- .map((img) => img.Id);-- await loadImageMaturityBatch(topImageIds);-}--export async function triggerBulkMaturityCheck(imageIds?: string[]): Promise<{ success: boolean; message: string }> {- setMaturityChecking(true);-- try {- const result = await environmentAPI.triggerMaturityCheck(imageIds);- return result;- } catch (error) {- console.error('Bulk maturity check error:', error);- return { success: false, message: 'Failed to trigger maturity check' };- } finally {- setMaturityChecking(false);- }-}--export function enhanceImagesWithMaturity(images: any[], maturityData: Record<string, ImageMaturity>): any[] {- return images.map((image) => {- let repo = '<none>';- let tag = '<none>';- if (image.RepoTags && image.RepoTags.length > 0) {- const repoTag = image.RepoTags[0];- if (repoTag !== '<none>:<none>' && repoTag.includes(':')) {- [repo, tag] = repoTag.split(':');- } else if (repoTag !== '<none>:<none>') {- repo = repoTag;- tag = 'latest';- }- }-- const storedMaturity = maturityData[image.Id];-- return {- ...image,- repo,- tag,- inUse: image.Containers > 0,- maturity: storedMaturity !== undefined ? storedMaturity : image.maturity- };- });-}diff --git a/frontend/src/lib/types/auto-update.type.ts b/frontend/src/lib/types/auto-update.type.tsdeleted file mode 100644index f062c33bb..000000000--- a/frontend/src/lib/types/auto-update.type.ts+++ /dev/null@@ -1,54 +0,0 @@-export interface AutoUpdateCheck {- type?: 'containers' | 'stacks' | 'all';- resourceIds?: string[];- forceUpdate?: boolean;- dryRun?: boolean;-}--export interface AutoUpdateResult {- success: boolean;- checked: number;- updated: number;- skipped: number;- failed: number;- startTime: string;- endTime: string;- duration: string;- results: AutoUpdateResourceResult[];-}--export interface AutoUpdateResourceResult {- resourceId: string;- resourceName: string;- resourceType: 'container' | 'stack';- status: 'checked' | 'up_to_date' | 'update_available' | 'updated' | 'failed' | 'skipped';- updateAvailable: boolean;- updateApplied: boolean;- oldImages?: Record<string, string>;- newImages?: Record<string, string>;- error?: string;- details?: Record<string, any>;-}--export interface AutoUpdateRecord {- id: string;- resourceId: string;- resourceType: string;- resourceName: string;- status: string;- startTime: string;- endTime?: string;- updateAvailable: boolean;- updateApplied: boolean;- oldImageVersions?: Record<string, string>;- newImageVersions?: Record<string, string>;- error?: string;- details?: Record<string, any>;-}--export interface AutoUpdateStatus {- updatingContainers: number;- updatingStacks: number;- containerIds: string[];- stackIds: string[];-}\ No newline at end of filediff --git a/frontend/src/lib/types/errors.ts b/frontend/src/lib/types/errors.tsdeleted file mode 100644index e956ca493..000000000--- a/frontend/src/lib/types/errors.ts+++ /dev/null@@ -1,94 +0,0 @@-/**- * Defines standard error codes for API responses.- */-export const ApiErrorCode = {- // Client-side errors (4xx)- VALIDATION_ERROR: 'VALIDATION_ERROR', // Input data failed validation (400)- UNAUTHENTICATED: 'UNAUTHENTICATED', // Missing or invalid authentication (401)- FORBIDDEN: 'FORBIDDEN', // User does not have permission (403)- NOT_FOUND: 'NOT_FOUND', // Resource not found (404)- CONFLICT: 'CONFLICT', // Resource already exists or state conflict (409)- BAD_REQUEST: 'BAD_REQUEST', // General bad request, often for config/state issues (400)-- // Server-side errors (5xx)- DOCKER_API_ERROR: 'DOCKER_API_ERROR', // Error interacting with Docker daemon (500/503)- SERVICE_ERROR: 'SERVICE_ERROR', // General error in backend service logic (500)- INTERNAL_SERVER_ERROR: 'INTERNAL_SERVER_ERROR' // Unexpected server error (500)-} as const; // Use 'as const' for stricter typing--// Base Service Error-export class ServiceError extends Error {- public readonly code: string;- public readonly status: number;-- constructor(message: string, code: string = ApiErrorCode.SERVICE_ERROR, status: number = 500) {- super(message);- this.name = 'ServiceError';- this.code = code;- this.status = status;- Object.setPrototypeOf(this, ServiceError.prototype);- }-}--// Not Found Error-export class NotFoundError extends ServiceError {- constructor(message: string = 'Resource not found') {- super(message, ApiErrorCode.NOT_FOUND, 404);- this.name = 'NotFoundError';- Object.setPrototypeOf(this, NotFoundError.prototype);- }-}--// Validation Error-export class ValidationError extends ServiceError {- public readonly details?: Record<string, string> | string;-- constructor(message: string = 'Input validation failed', details?: Record<string, string> | string) {- super(message, ApiErrorCode.VALIDATION_ERROR, 400);- this.name = 'ValidationError';- this.details = details;- Object.setPrototypeOf(this, ValidationError.prototype);- }-}--// Docker API Error-export class DockerApiError extends ServiceError {- public readonly dockerStatusCode?: number;-- constructor(message: string, dockerStatusCode?: number) {- const status = dockerStatusCode && dockerStatusCode >= 400 && dockerStatusCode < 500 ? dockerStatusCode : 503;- super(message, ApiErrorCode.DOCKER_API_ERROR, status);- this.name = 'DockerApiError';- this.dockerStatusCode = dockerStatusCode;- Object.setPrototypeOf(this, DockerApiError.prototype);- }-}--// Conflict Error (e.g., resource already exists, or removing running container without force)-export class ConflictError extends ServiceError {- constructor(message: string = 'Resource conflict') {- super(message, ApiErrorCode.CONFLICT, 409);- this.name = 'ConflictError';- Object.setPrototypeOf(this, ConflictError.prototype);- }-}--// NEW: Container State Error (e.g., trying to stop a stopped container)-export class ContainerStateError extends ServiceError {- constructor(message: string) {- // Using 409 Conflict as the state prevents the action- super(message, ApiErrorCode.CONFLICT, 409);- this.name = 'ContainerStateError';- Object.setPrototypeOf(this, ContainerStateError.prototype);- }-}--// NEW: Configuration Error (e.g., invalid settings during creation)-export class ConfigurationError extends ServiceError {- constructor(message: string) {- // Using 400 Bad Request as the provided config is invalid- super(message, ApiErrorCode.BAD_REQUEST, 400);- this.name = 'ConfigurationError';- Object.setPrototypeOf(this, ConfigurationError.prototype);- }-}diff --git a/frontend/src/lib/types/errors.type.ts b/frontend/src/lib/types/errors.type.tsdeleted file mode 100644index faacbc048..000000000--- a/frontend/src/lib/types/errors.type.ts+++ /dev/null@@ -1,125 +0,0 @@-//This file replaces errors.ts--export enum ApiErrorCode {- NOT_FOUND = 'NOT_FOUND',- BAD_REQUEST = 'BAD_REQUEST',- UNAUTHORIZED = 'UNAUTHORIZED',- 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;-}--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);- }-}--export interface APIError {- code: string;- message: string;- details?: Record<string, any>;- timestamp: string;- path?: string;- method?: string;-}--export interface ValidationAPIError extends APIError {- field?: string;- value?: any;- constraint?: string;-}--export interface AuthenticationError extends APIError {- authType: 'local' | 'oidc' | 'session';- remainingAttempts?: number;-}--export interface AuthorizationError extends APIError {- requiredPermission: string;- userPermissions: string[];-}--export interface DockerError extends APIError {- dockerCode?: string;- containerId?: string;- serviceName?: string;-}diff --git a/frontend/src/lib/types/loading-states.type.ts b/frontend/src/lib/types/loading-states.type.tsdeleted file mode 100644index 9b1a44e38..000000000--- a/frontend/src/lib/types/loading-states.type.ts+++ /dev/null@@ -1,10 +0,0 @@-export type LoadingStates = {- start?: boolean;- stop?: boolean;- restart?: boolean;- pull?: boolean;- deploy?: boolean;- redeploy?: boolean;- remove?: boolean;- validating?: boolean;-};diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.tsindex 1a3a3612c..d05a81a87 100644--- a/frontend/src/lib/types/settings.type.ts+++ b/frontend/src/lib/types/settings.type.ts@@ -66,7 +66,6 @@ export interface Settings {auth: AuthSettings;onboarding?: Onboarding;baseServerUrl?: string;- maturityThresholdDays: number;createdAt: string;updatedAt: string;}diff --git a/frontend/src/routes/dashboard/+page.svelte b/frontend/src/routes/dashboard/+page.svelteindex bfed5d710..c8a9218bf 100644--- a/frontend/src/routes/dashboard/+page.svelte+++ b/frontend/src/routes/dashboard/+page.svelte@@ -20,10 +20,9 @@import PruneConfirmationDialog from '$lib/components/dialogs/prune-confirmation-dialog.svelte';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';- import { systemAPI, imageAPI, environmentAPI, settingsAPI } from '$lib/services/api';+ import { systemAPI, environmentAPI, settingsAPI } from '$lib/services/api';import { openConfirmDialog } from '$lib/components/confirm-dialog';import { onMount } from 'svelte';- import { maturityStore } from '$lib/stores/maturity-store';import type { PruneType } from '$lib/types/actions.type';import DropdownCard from '$lib/components/dropdown-card.svelte';import MeterMetric from '$lib/components/meter-metric.svelte';@@ -53,7 +52,6 @@refreshing: false,pruning: false,loadingStats: true,- loadingMaturity: true,loadingContainers: false,loadingDockerInfo: false,loadingImages: false@@ -82,12 +80,6 @@dashboardStates.images?.reduce((sum, image) => sum + (image.Size || 0), 0) ?? 0);- const containerUsagePercent = $derived(- dashboardStates.containers?.length- ? (runningContainers / dashboardStates.containers.length) * 100- : 0- );-const currentStats = $derived(dashboardStates.systemStats || liveSystemStats);function addToHistoricalData(stats: SystemStats) {@@ -223,50 +215,6 @@}}- async function loadTopImagesMaturity() {- if (!dashboardStates.images || dashboardStates.images.length === 0) {- isLoading.loadingMaturity = false;- return;- }-- isLoading.loadingMaturity = true;-- const topImageIds = [...dashboardStates.images]- .sort((a, b) => (b.Size || 0) - (a.Size || 0))- .slice(0, 5)- .filter((img) => img.RepoTags && img.RepoTags[0] !== '<none>:<none>')- .map((img) => img.Id);-- if (topImageIds.length === 0) {- isLoading.loadingMaturity = false;- return;- }-- try {- const BATCH_SIZE = 1;- for (let i = 0; i < topImageIds.length; i += BATCH_SIZE) {- const batch = topImageIds.slice(i, i + BATCH_SIZE);- await imageAPI.checkMaturityBatch(batch);-- dashboardStates.images = dashboardStates.images.map((image) => {- const storedMaturity = $maturityStore.maturityData[image.Id];- return {- ...image,- maturity: storedMaturity !== undefined ? storedMaturity : image.maturity- };- });-- if (i + BATCH_SIZE < topImageIds.length) {- await new Promise((resolve) => setTimeout(resolve, 100));- }- }- } catch (error) {- console.error('Error loading maturity data for dashboard images:', error);- } finally {- isLoading.loadingMaturity = false;- }- }-async function refreshData() {if (isLoading.refreshing) return;isLoading.refreshing = true;@@ -314,11 +262,6 @@}await fetchLiveSystemStats();-- if (dashboardStates.images && dashboardStates.images.length > 0) {- loadTopImagesMaturity();- }-isLoading.refreshing = false;}@@ -327,12 +270,6 @@fetchLiveSystemStats();- if (dashboardStates.images && dashboardStates.images.length > 0) {- loadTopImagesMaturity();- } else {- isLoading.loadingMaturity = false;- }-if (!statsInterval) {statsInterval = setInterval(() => {if (mounted) {@@ -660,7 +597,6 @@<DashboardImageTableimages={dashboardStates.images}isLoading={isLoading.loadingImages}- isLoadingMaturity={isLoading.loadingMaturity}onRefresh={onImageRefresh}/></div>diff --git a/frontend/src/routes/dashboard/+page.ts b/frontend/src/routes/dashboard/+page.tsindex 109be49fb..cca3419cb 100644--- a/frontend/src/routes/dashboard/+page.ts+++ b/frontend/src/routes/dashboard/+page.ts@@ -3,69 +3,69 @@ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { PageLoad } from './$types';export const load: PageLoad = async () => {- const containerRequestOptions: SearchPaginationSortRequest = {- pagination: {- page: 1,- limit: 5- },- sort: {- column: 'created',- direction: 'desc' as const- }- },- imageRequestOptions: SearchPaginationSortRequest = {- pagination: {- page: 1,- limit: 5- },- sort: {- column: 'Created',- direction: 'desc' as const- }- };+ const containerRequestOptions: SearchPaginationSortRequest = {+ pagination: {+ page: 1,+ limit: 5+ },+ sort: {+ column: 'created',+ direction: 'desc' as const+ }+ },+ imageRequestOptions: SearchPaginationSortRequest = {+ pagination: {+ page: 1,+ limit: 5+ },+ sort: {+ column: 'Created',+ direction: 'desc' as const+ }+ };- try {- const [dockerInfoResult, containersResult, imagesResult, settingsResult] =- await Promise.allSettled([- systemAPI.getDockerInfo(),- environmentAPI.getContainers(- containerRequestOptions.pagination,- containerRequestOptions.sort,- containerRequestOptions.search,- containerRequestOptions.filters- ),- environmentAPI.getImages(- imageRequestOptions.pagination,- imageRequestOptions.sort,- imageRequestOptions.search,- imageRequestOptions.filters- ),- settingsAPI.getSettings()- ]);+ try {+ const [dockerInfoResult, containersResult, imagesResult, settingsResult] =+ await Promise.allSettled([+ systemAPI.getDockerInfo(),+ environmentAPI.getContainers(+ containerRequestOptions.pagination,+ containerRequestOptions.sort,+ containerRequestOptions.search,+ containerRequestOptions.filters+ ),+ environmentAPI.getImages(+ imageRequestOptions.pagination,+ imageRequestOptions.sort,+ imageRequestOptions.search,+ imageRequestOptions.filters+ ),+ settingsAPI.getSettings()+ ]);- const dockerInfo = dockerInfoResult.status === 'fulfilled' ? dockerInfoResult.value : null;- const containers = containersResult.status === 'fulfilled' ? containersResult.value : [];- const images = imagesResult.status === 'fulfilled' ? imagesResult.value : [];- const settings = settingsResult.status === 'fulfilled' ? settingsResult.value : null;+ const dockerInfo = dockerInfoResult.status === 'fulfilled' ? dockerInfoResult.value : null;+ const containers = containersResult.status === 'fulfilled' ? containersResult.value : [];+ const images = imagesResult.status === 'fulfilled' ? imagesResult.value : [];+ const settings = settingsResult.status === 'fulfilled' ? settingsResult.value : null;- return {- dockerInfo,- containers,- images,- settings,- containerRequestOptions,- imageRequestOptions- };- } catch (error) {- console.error('Error loading dashboard data:', error);- return {- dockerInfo: null,- containers: [],- images: [],- settings: null,- containerRequestOptions,- imageRequestOptions,- error: error instanceof Error ? error.message : String(error)- };- }+ return {+ dockerInfo,+ containers,+ images,+ settings,+ containerRequestOptions,+ imageRequestOptions+ };+ } catch (error) {+ console.error('Error loading dashboard data:', error);+ return {+ dockerInfo: null,+ containers: [],+ images: [],+ settings: null,+ containerRequestOptions,+ imageRequestOptions,+ error: error instanceof Error ? error.message : String(error)+ };+ }};diff --git a/frontend/src/routes/dashboard/dash-image-table.svelte b/frontend/src/routes/dashboard/dash-image-table.svelteindex c57cfabec..edd7f00aa 100644--- a/frontend/src/routes/dashboard/dash-image-table.svelte+++ b/frontend/src/routes/dashboard/dash-image-table.svelte@@ -6,7 +6,6 @@import * as Card from '$lib/components/ui/card/index.js';import * as Table from '$lib/components/ui/table';import StatusBadge from '$lib/components/badges/status-badge.svelte';- import MaturityItem from '$lib/components/maturity-item.svelte';import { formatBytes } from '$lib/utils/bytes.util';import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';@@ -17,12 +16,10 @@let {images,isLoading,- isLoadingMaturity,onRefresh}: {images: EnhancedImageInfo[];isLoading: boolean;- isLoadingMaturity: boolean;onRefresh: (options: SearchPaginationSortRequest) => Promise<Paginated<ImageWithId>>;} = $props();@@ -96,15 +93,6 @@<Table.Cell><div class="flex items-center gap-2"><div class="flex flex-1 items-center">- {#if isLoadingMaturity}- <div class="bg-muted size-4 animate-pulse rounded-full mr-2"></div>- {:else}- <MaturityItem- maturity={item.maturity}- isLoadingInBackground={!item.maturity}- imageId={item.Id}- />- {/if}<a class="shrink truncate font-medium hover:underline" href="/images/{item.Id}/">{#if item.RepoTags && item.RepoTags.length > 0 && item.RepoTags[0] !== '<none>:<none>'}{item.RepoTags[0].split(':')[0]}diff --git a/frontend/src/routes/environments/+page.svelte b/frontend/src/routes/environments/+page.svelteindex a93758fec..0f7e04470 100644--- a/frontend/src/routes/environments/+page.svelte+++ b/frontend/src/routes/environments/+page.svelte@@ -1,22 +1,33 @@<script lang="ts">import { onMount } from 'svelte';- import { goto, invalidateAll } from '$app/navigation';+ import { goto } from '$app/navigation';import type { Environment } from '$lib/stores/environment.store';- import type { ColumnDef } from '@tanstack/table-core';import { formatDistanceToNow } from 'date-fns';- import { RefreshCw, AlertCircle, Loader2, Monitor, Eye, Trash2, Terminal, Key, Server, Ellipsis, Plus } from '@lucide/svelte';+ import {+ RefreshCw,+ AlertCircle,+ Loader2,+ Monitor,+ Eye,+ Trash2,+ Terminal,+ Server,+ Ellipsis,+ Plus+ } from '@lucide/svelte';import { toast } from 'svelte-sonner';import { openConfirmDialog } from '$lib/components/confirm-dialog/index.js';import { handleApiResultWithCallbacks } from '$lib/utils/api.util.js';import { tryCatch } from '$lib/utils/try-catch.js';import { Button } from '$lib/components/ui/button/index.js';import * as Card from '$lib/components/ui/card/index.js';- import UniversalTable from '$lib/components/universal-table.svelte';+ import ArcaneTable from '$lib/components/arcane-table.svelte';import * as Table from '$lib/components/ui/table';import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';import StatusBadge from '$lib/components/badges/status-badge.svelte';import NewEnvironmentSheet from '$lib/components/sheets/new-environment-sheet.svelte';import { environmentManagementAPI } from '$lib/services/api';+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';let { data } = $props();@@ -27,15 +38,97 @@let showEnvironmentSheet = $state(false);let refreshInProgress = false;- const columns: ColumnDef<Environment>[] = [- { accessorKey: 'hostname', header: 'Environment' },- { accessorKey: 'status', header: 'Status' },- { accessorKey: 'apiUrl', header: 'API URL' },- { accessorKey: 'enabled', header: 'Enabled' },- { accessorKey: 'lastSeen', header: 'Last Seen' },- { accessorKey: 'actions', header: ' ' }+ // Convert environments array to Paginated structure for ArcaneTable+ let paginatedEnvironments = $derived<Paginated<Environment & { id: string }>>({+ data: environments.map((env) => ({ ...env, id: env.id })),+ pagination: {+ totalPages: 1,+ totalItems: environments.length,+ currentPage: 1,+ itemsPerPage: environments.length+ }+ });++ let requestOptions = $state<SearchPaginationSortRequest>({+ search: '',+ pagination: { page: 1, limit: 100 },+ sort: { column: 'lastSeen', direction: 'desc' }+ });++ const columns = [+ { label: 'Environment', sortColumn: 'hostname' },+ { label: 'Status', sortColumn: 'status' },+ { label: 'API URL' },+ { label: 'Enabled', sortColumn: 'enabled' },+ { label: 'Last Seen', sortColumn: 'lastSeen' },+ { label: ' ' }];+ // Define valid sortable keys for Environment+ const validSortColumns: (keyof Environment)[] = [+ 'hostname',+ 'status',+ 'enabled',+ 'lastSeen',+ 'apiUrl',+ 'id'+ ];++ function isValidEnvironmentKey(key: string): key is keyof Environment {+ return validSortColumns.includes(key as keyof Environment);+ }++ function sortEnvironments(+ data: Environment[],+ column: keyof Environment,+ direction: 'asc' | 'desc'+ ): Environment[] {+ return [...data].sort((a, b) => {+ const aVal = a[column];+ const bVal = b[column];++ // Handle date fields+ if (column === 'lastSeen') {+ const aTime = aVal ? new Date(aVal as string).getTime() : 0;+ const bTime = bVal ? new Date(bVal as string).getTime() : 0;+ return direction === 'asc' ? aTime - bTime : bTime - aTime;+ }++ // Handle string comparison+ if (typeof aVal === 'string' && typeof bVal === 'string') {+ const comparison = aVal.toLowerCase().localeCompare(bVal.toLowerCase());+ return direction === 'asc' ? comparison : -comparison;+ }++ // Handle boolean comparison+ if (typeof aVal === 'boolean' && typeof bVal === 'boolean') {+ if (aVal === bVal) return 0;+ const comparison = aVal ? 1 : -1;+ return direction === 'asc' ? comparison : -comparison;+ }++ // Handle undefined values+ const aComp = aVal ?? '';+ const bComp = bVal ?? '';++ if (aComp < bComp) return direction === 'asc' ? -1 : 1;+ if (aComp > bComp) return direction === 'asc' ? 1 : -1;+ return 0;+ });+ }++ function filterEnvironments(data: Environment[], searchTerm: string): Environment[] {+ if (!searchTerm) return data;++ const term = searchTerm.toLowerCase();+ return data.filter(+ (env) =>+ env.hostname.toLowerCase().includes(term) ||+ env.apiUrl.toLowerCase().includes(term) ||+ env.status.toLowerCase().includes(term)+ );+ }+onMount(() => {const interval = setInterval(refreshEnvironments, 30000);return () => clearInterval(interval);@@ -70,6 +163,39 @@}}+ /**+ * Handle local filtering and sorting of environments data+ * Used by ArcaneTable for client-side data manipulation+ */+ async function handleLocalFilter(+ options: SearchPaginationSortRequest+ ): Promise<Paginated<Environment & { id: string }>> {+ // Apply search filter+ let filteredData = filterEnvironments(environments, options.search || '');++ // Apply sorting if provided+ if (options.sort) {+ const { column, direction } = options.sort;++ // Validate column is a valid Environment key before sorting+ if (!isValidEnvironmentKey(column)) {+ console.warn(`Invalid sort column: ${column}. Skipping sort.`);+ } else {+ filteredData = sortEnvironments(filteredData, column, direction);+ }+ }++ return {+ data: filteredData.map((env) => ({ ...env, id: env.id })),+ pagination: {+ totalPages: 1,+ totalItems: filteredData.length,+ currentPage: 1,+ itemsPerPage: filteredData.length+ }+ };+ }+async function deleteEnvironment(environmentId: string, hostname: string) {openConfirmDialog({title: `Confirm Removal`,@@ -117,13 +243,29 @@destructive: true,action: async () => {try {- await Promise.all(selectedEnvironmentIds.map((id) => environmentManagementAPI.delete(id)));- toast.success(`${selectedEnvironmentIds.length} environment(s) removed successfully`);+ const results = await Promise.allSettled(+ selectedEnvironmentIds.map((id) => environmentManagementAPI.delete(id))+ );++ const successful = results.filter((result) => result.status === 'fulfilled');+ const failed = results.filter((result) => result.status === 'rejected');++ if (successful.length > 0) {+ toast.success(`${successful.length} environment(s) removed successfully`);+ }++ if (failed.length > 0) {+ console.error('Failed delete operations:', failed);+ toast.error(+ `Failed to remove ${failed.length} environment(s). Check console for details.`+ );+ }+selectedEnvironmentIds = [];await loadEnvironments();} catch (err) {- console.error('Failed to remove environments:', err);- toast.error('Failed to remove some environments');+ console.error('Unexpected error during bulk delete:', err);+ toast.error('An unexpected error occurred during bulk deletion');}}}@@ -132,7 +274,9 @@function handleEnvironmentCreated() {showEnvironmentSheet = false;- toast.success('Environment added successfully! You can now select it from the environment switcher.');+ toast.success(+ 'Environment added successfully! You can now select it from the environment switcher.'+ );loadEnvironments();}</script>@@ -144,7 +288,9 @@</div>{#if error}- <div class="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-red-700 dark:border-red-800 dark:bg-red-900/20 dark:text-red-400">+ <div+ class="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-red-700 dark:border-red-800 dark:bg-red-900/20 dark:text-red-400"+ ><div class="flex items-center gap-2"><AlertCircle class="h-5 w-5" /><strong>Error:</strong>@@ -190,10 +336,16 @@{#if environments.length === 0 && !loading}<div class="py-16 text-center"><Monitor class="mx-auto mb-4 h-16 w-16 text-gray-400" />- <h3 class="mb-2 text-lg font-medium text-gray-900 dark:text-white">No environments registered</h3>- <p class="mb-4 text-gray-600 dark:text-gray-400">Get started by adding your first environment</p>+ <h3 class="mb-2 text-lg font-medium text-gray-900 dark:text-white">+ No environments registered+ </h3>+ <p class="mb-4 text-gray-600 dark:text-gray-400">+ Get started by adding your first environment+ </p><div class="mx-auto max-w-md rounded-lg bg-gray-50 p-4 dark:bg-gray-800">- <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">Add a new environment to connect to an Arcane agent running as an API server.</p>+ <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">+ Add a new environment to connect to an Arcane agent running as an API server.+ </p><Button onclick={() => (showEnvironmentSheet = true)} class="w-full"><Plus class="mr-2 h-4 w-4" />Add Environment@@ -202,55 +354,59 @@</div>{:else if environments.length > 0}<div class="flex h-full flex-1 flex-col">- <UniversalTable- data={environments}- {columns}- idKey="id"+ <ArcaneTable+ items={paginatedEnvironments}+ bind:requestOptionsbind:selectedIds={selectedEnvironmentIds}- features={{- sorting: true,- filtering: true,- selection: true- }}- display={{- filterPlaceholder: 'Search environments...',- noResultsMessage: 'No environments found'- }}- pagination={{- pageSize: 10,- pageSizeOptions: [10, 20, 50]- }}- sort={{- defaultSort: { id: 'lastSeen', desc: true }- }}+ withoutPagination={true}+ onRefresh={handleLocalFilter}+ {columns}+ filterPlaceholder="Search environments..."+ noResultsMessage="No environments found">{#snippet rows({ item })}<Table.Cell><div class="flex items-center gap-3"><div class="relative">- <div class="flex size-8 items-center justify-center rounded-lg bg-gray-100 dark:bg-gray-700">+ <div+ class="flex size-8 items-center justify-center rounded-lg bg-gray-100 dark:bg-gray-700"+ ><Monitor class="size-4 text-gray-600 dark:text-gray-400" /></div>- <div class="absolute -top-1 -right-1 size-3 {item.status === 'online' ? 'bg-green-500' : 'bg-red-500'} rounded-full border-2 border-white dark:border-gray-800"></div>+ <div+ class="absolute -top-1 -right-1 size-3 {item.status === 'online'+ ? 'bg-green-500'+ : 'bg-red-500'} rounded-full border-2 border-white dark:border-gray-800"+ ></div></div><div><div class="font-medium text-gray-900 dark:text-white">{item.hostname}</div>- <div class="text-xs text-gray-500 dark:text-gray-400 font-mono">{item.id}</div>+ <div class="text-xs text-gray-500 dark:text-gray-400 font-mono">+ {item.id}+ </div></div></div></Table.Cell><Table.Cell>- <StatusBadge text={item.status === 'online' ? 'Online' : 'Offline'} variant={item.status === 'online' ? 'green' : 'red'} />+ <StatusBadge+ text={item.status === 'online' ? 'Online' : 'Offline'}+ variant={item.status === 'online' ? 'green' : 'red'}+ /></Table.Cell><Table.Cell><span class="text-sm font-mono text-muted-foreground">{item.apiUrl}</span></Table.Cell><Table.Cell>- <StatusBadge text={item.enabled ? 'Enabled' : 'Disabled'} variant={item.enabled ? 'green' : 'gray'} />+ <StatusBadge+ text={item.enabled ? 'Enabled' : 'Disabled'}+ variant={item.enabled ? 'green' : 'gray'}+ /></Table.Cell><Table.Cell>{#if item.lastSeen}- <span class="text-sm text-gray-600 dark:text-gray-400">{formatDistanceToNow(new Date(item.lastSeen))} ago</span>+ <span class="text-sm text-gray-600 dark:text-gray-400"+ >{formatDistanceToNow(new Date(item.lastSeen))} ago</span+ >{:else}<span class="text-sm text-gray-400">Never</span>{/if}@@ -273,7 +429,10 @@<Eye class="size-4" />View Details</DropdownMenu.Item>- <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => deleteEnvironment(item.id, item.hostname)}>+ <DropdownMenu.Item+ class="text-red-500 focus:text-red-700!"+ onclick={() => deleteEnvironment(item.id, item.hostname)}+ ><Trash2 class="size-4" />Delete Environment</DropdownMenu.Item>@@ -282,7 +441,7 @@</DropdownMenu.Root></Table.Cell>{/snippet}- </UniversalTable>+ </ArcaneTable></div>{:else}<div class="text-muted-foreground py-8 text-center italic">Loading environments...</div>@@ -292,11 +451,16 @@</div>{#if loading && environments.length > 0}- <div class="fixed right-4 bottom-4 flex items-center gap-2 rounded-lg bg-blue-600 px-3 py-2 text-white shadow-lg">+ <div+ class="fixed right-4 bottom-4 flex items-center gap-2 rounded-lg bg-blue-600 px-3 py-2 text-white shadow-lg"+ ><Loader2 class="h-4 w-4 animate-spin" /><span class="text-sm">Refreshing...</span></div>{/if}</div>-<NewEnvironmentSheet bind:open={showEnvironmentSheet} onEnvironmentCreated={handleEnvironmentCreated} />+<NewEnvironmentSheet+ bind:open={showEnvironmentSheet}+ onEnvironmentCreated={handleEnvironmentCreated}+/>diff --git a/frontend/src/routes/images/+page.svelte b/frontend/src/routes/images/+page.svelteindex db6f1ff94..724476d4f 100644--- a/frontend/src/routes/images/+page.svelte+++ b/frontend/src/routes/images/+page.svelte@@ -12,12 +12,7 @@import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import ArcaneButton from '$lib/components/arcane-button.svelte';- import {- maturityStore,- triggerBulkMaturityCheck,- enhanceImagesWithMaturity- } from '$lib/stores/maturity-store';- import { environmentAPI } from '$lib/services/api';+ import { environmentAPI, imageUpdateAPI } from '$lib/services/api';import StatCard from '$lib/components/stat-card.svelte';import ImageTable from './image-table.svelte';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';@@ -35,14 +30,14 @@let isLoading = $state({pulling: false,refreshing: false,- pruning: false+ pruning: false,+ checking: false});let isPullDialogOpen = $state(false);let isConfirmPruneDialogOpen = $state(false);const totalSize = $derived(images?.reduce((acc, img) => acc + (img.Size || 0), 0) || 0);- const enhancedImages = $derived(enhanceImagesWithMaturity(images, $maturityStore.maturityData));async function loadImages() {try {@@ -90,12 +85,18 @@});}- async function handleTriggerBulkMaturityCheck() {- const result = await triggerBulkMaturityCheck(images.map((img) => img.Id));- if (result.success) {- toast.success(result.message);- } else {- toast.error(result.message);+ async function handleTriggerBulkUpdateCheck() {+ isLoading.checking = true;+ try {+ const imageRefs = images.map((img) => img.RepoTags?.[0] || `image:${img.Id}`);+ await imageUpdateAPI.checkMultipleImages(imageRefs);+ toast.success('Update check completed');+ await loadImages();+ } catch (error) {+ console.error('Failed to check for updates:', error);+ toast.error('Failed to check for updates');+ } finally {+ isLoading.checking = false;}}@@ -103,10 +104,10 @@requestOptions = options;await loadImages();return {- data: enhancedImages,+ data: images,pagination: {- totalPages: Math.ceil(enhancedImages.length / (requestOptions.pagination?.limit || 20)),- totalItems: enhancedImages.length,+ totalPages: Math.ceil(images.length / (requestOptions.pagination?.limit || 20)),+ totalItems: images.length,currentPage: requestOptions.pagination?.page || 1,itemsPerPage: requestOptions.pagination?.limit || 20}@@ -187,13 +188,13 @@</div><ImageTable- images={enhancedImages}+ {images}bind:selectedIds{requestOptions}{onRefresh}onImagesChanged={loadImages}onPullDialogOpen={() => (isPullDialogOpen = true)}- onTriggerBulkMaturityCheck={handleTriggerBulkMaturityCheck}+ onTriggerBulkUpdateCheck={handleTriggerBulkUpdateCheck}/><ImagePullSheet bind:open={isPullDialogOpen} onPullFinished={() => loadImages()} />diff --git a/frontend/src/routes/images/image-table.svelte b/frontend/src/routes/images/image-table.svelteindex 2583e936d..2de1cc078 100644--- a/frontend/src/routes/images/image-table.svelte+++ b/frontend/src/routes/images/image-table.svelte@@ -23,7 +23,7 @@import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import ArcaneButton from '$lib/components/arcane-button.svelte';- import MaturityItem from '$lib/components/maturity-item.svelte';+ import ImageUpdateItem from '$lib/components/image-update-item.svelte';import { environmentAPI } from '$lib/services/api';import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';@@ -38,7 +38,7 @@onRefresh,onImagesChanged,onPullDialogOpen,- onTriggerBulkMaturityCheck+ onTriggerBulkUpdateCheck}: {images: EnhancedImageInfo[];selectedIds: string[];@@ -46,12 +46,14 @@onRefresh: (options: SearchPaginationSortRequest) => Promise<any>;onImagesChanged: () => Promise<void>;onPullDialogOpen: () => void;- onTriggerBulkMaturityCheck: () => Promise<void>;+ onTriggerBulkUpdateCheck: () => Promise<void>;} = $props();let imageFilters = $state({showUsed: true,- showUnused: true+ showUnused: true,+ showWithUpdates: true,+ showWithoutUpdates: true});let isLoading = $state({@@ -72,7 +74,14 @@imagesWithId.filter((img) => {const showBecauseUsed = imageFilters.showUsed && img.InUse;const showBecauseUnused = imageFilters.showUnused && !img.InUse;- return showBecauseUsed || showBecauseUnused;+ const usageMatch = showBecauseUsed || showBecauseUnused;++ const hasUpdates = img.updateInfo?.hasUpdate || false;+ const showBecauseHasUpdates = imageFilters.showWithUpdates && hasUpdates;+ const showBecauseNoUpdates = imageFilters.showWithoutUpdates && !hasUpdates;+ const updateMatch = showBecauseHasUpdates || showBecauseNoUpdates;++ return usageMatch && updateMatch;}));@@ -157,11 +166,29 @@isPullingInline[imageId] = false;}- async function handleTriggerBulkMaturityCheckInternal() {+ async function handleTriggerBulkUpdateCheckInternal() {isLoading.checking = true;- await onTriggerBulkMaturityCheck();+ await onTriggerBulkUpdateCheck();isLoading.checking = false;}++ function extractRepoAndTag(repoTags: string[] | undefined) {+ if (!repoTags || repoTags.length === 0 || repoTags[0] === '<none>:<none>') {+ return { repo: '<none>', tag: '<none>' };+ }++ const repoTag = repoTags[0];+ const lastColonIndex = repoTag.lastIndexOf(':');++ if (lastColonIndex === -1) {+ return { repo: repoTag, tag: 'latest' };+ }++ const repo = repoTag.substring(0, lastColonIndex);+ const tag = repoTag.substring(lastColonIndex + 1);++ return { repo: repo || '<none>', tag: tag || '<none>' };+ }</script>{#if filteredImages.length > 0}@@ -200,6 +227,24 @@>Show Unused Images</DropdownMenu.CheckboxItem>+ <DropdownMenu.Separator />+ <DropdownMenu.Label>Update Status</DropdownMenu.Label>+ <DropdownMenu.CheckboxItem+ checked={imageFilters.showWithUpdates}+ onCheckedChange={(checked) => {+ imageFilters.showWithUpdates = checked;+ }}+ >+ Show Images with Updates+ </DropdownMenu.CheckboxItem>+ <DropdownMenu.CheckboxItem+ checked={imageFilters.showWithoutUpdates}+ onCheckedChange={(checked) => {+ imageFilters.showWithoutUpdates = checked;+ }}+ >+ Show Images without Updates+ </DropdownMenu.CheckboxItem></DropdownMenu.Content></DropdownMenu.Root>{#if selectedIds.length > 0}@@ -213,8 +258,8 @@<ArcaneButton action="pull" label="Pull Image" onClick={onPullDialogOpen} /><ArcaneButtonaction="inspect"- label="Recheck Maturities"- onClick={handleTriggerBulkMaturityCheckInternal}+ label="Check Updates"+ onClick={handleTriggerBulkUpdateCheckInternal}loading={isLoading.checking}loadingLabel="Checking..."disabled={isLoading.checking}@@ -234,13 +279,14 @@{ label: 'Size', sortColumn: 'Size' },{ label: 'Created', sortColumn: 'Created' },{ label: 'Status', sortColumn: 'InUse' },- { label: 'Maturity' },+ { label: 'Updates' },{ label: ' ' }]}filterPlaceholder="Search images..."noResultsMessage="No images found">{#snippet rows({ item })}+ {@const { repo, tag } = extractRepoAndTag(item.RepoTags)}<Table.Cell>{#if item.RepoTags && item.RepoTags.length > 0 && item.RepoTags[0] !== '<none>:<none>'}{item.RepoTags[0]}@@ -263,11 +309,7 @@{/if}</Table.Cell><Table.Cell>- {#if item.maturity}- <MaturityItem maturity={item.maturity} imageId={item.Id} />- {:else}- <span class="text-muted-foreground text-sm">N/A</span>- {/if}+ <ImageUpdateItem updateInfo={item.updateInfo} imageId={item.Id} {repo} {tag} /></Table.Cell><Table.Cell><DropdownMenu.Root>diff --git a/frontend/src/routes/onboarding/settings/+page.svelte b/frontend/src/routes/onboarding/settings/+page.svelteindex 68c5779d3..84aaae81a 100644--- a/frontend/src/routes/onboarding/settings/+page.svelte+++ b/frontend/src/routes/onboarding/settings/+page.svelte@@ -28,7 +28,6 @@autoUpdate: appSettings.autoUpdate,autoUpdateInterval: parseInt(appSettings.autoUpdateInterval),pruneMode: appSettings.pruneMode,- maturityThresholdDays: appSettings.maturityThresholdDays,baseServerUrl: appSettings.baseServerUrl,onboarding: {completed: false,@@ -117,20 +116,6 @@How aggressive to be when pruning unused resources</p></div>-- <div class="space-y-2">- <Label for="maturity-threshold">Image Maturity Threshold (days)</Label>- <Input- id="maturity-threshold"- type="number"- bind:value={appSettings.maturityThresholdDays}- min="1"- max="365"- />- <p class="text-xs text-muted-foreground">- Consider images older than this as potentially outdated- </p>- </div></Card.Content></Card.Root>diff --git a/frontend/src/routes/settings/general/+page.svelte b/frontend/src/routes/settings/general/+page.svelteindex 14d222a89..bd36b479f 100644--- a/frontend/src/routes/settings/general/+page.svelte+++ b/frontend/src/routes/settings/general/+page.svelte@@ -2,7 +2,7 @@import * as Card from '$lib/components/ui/card/index.js';import FormInput from '$lib/components/form/form-input.svelte';import { Button } from '$lib/components/ui/button/index.js';- import { Save, RefreshCw, Folder, Globe, Calendar } from '@lucide/svelte';+ import { Save, RefreshCw, Folder, Globe } from '@lucide/svelte';import type { FormInput as FormInputType } from '$lib/utils/form.utils';import { toast } from 'svelte-sonner';import { invalidateAll } from '$app/navigation';@@ -25,8 +25,7 @@isLoading.saving = true;updateSettingsConfig({stacksDirectory: stacksDirectoryInput.value,- baseServerUrl: baseServerUrlInput.value,- maturityThresholdDays: maturityThresholdInput.value+ baseServerUrl: baseServerUrlInput.value}).then(async () => {toast.success(`Settings Saved Successfully`);@@ -47,11 +46,6 @@error: null});- let maturityThresholdInput = $state<FormInputType<number>>({- value: 30,- error: null- });-let isLoading = $state({saving: false});@@ -59,7 +53,6 @@$effect(() => {stacksDirectoryInput.value = currentSettings.stacksDirectory;baseServerUrlInput.value = currentSettings.baseServerUrl || 'localhost';- maturityThresholdInput.value = currentSettings.maturityThresholdDays;});</script>@@ -135,29 +128,5 @@/></Card.Content></Card.Root>-- <!-- Container Management -->- <Card.Root>- <Card.Header>- <div class="flex items-center gap-3">- <div class="rounded-lg bg-purple-500/10 p-2">- <Calendar class="size-5 text-purple-600" />- </div>- <div>- <Card.Title>Container Management</Card.Title>- <Card.Description>Configure container lifecycle and update policies</Card.Description>- </div>- </div>- </Card.Header>- <Card.Content>- <FormInput- type="number"- label="Image Maturity Threshold (Days)"- placeholder="30"- bind:input={maturityThresholdInput}- helpText="Number of days to wait before considering an image update stable"- />- </Card.Content>- </Card.Root></div></div>