Skip to content

Modern Docker Management, Designed for Everyone

feat: resource updates overview page (#2204)

Kyle Mendellf8173ddd46f5
diff --git a/.vscode/settings.json b/.vscode/settings.json
index cb951988b..76c7b99e1 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -11,5 +11,7 @@
"prettier.documentSelectors": ["**/*.svelte"],
"tasks.statusbar.default.hide": true,
"tasks.statusbar.limit": 8,
- "github.copilot.chat.summarizeAgentConversationHistory.enabled": false
+ "github.copilot.chat.summarizeAgentConversationHistory.enabled": false,
+ "snyk.advanced.organization": "a7adead1-b200-490f-91c5-8fa0e410d62c",
+ "snyk.advanced.autoSelectOrganization": true
}
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.go
index 1153a79ea..c76c9e59d 100644
--- a/backend/internal/bootstrap/services_bootstrap.go
+++ b/backend/internal/bootstrap/services_bootstrap.go
@@ -84,7 +84,16 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config
svcs.BuildWorkspace = services.NewBuildWorkspaceService(svcs.Settings)
svcs.Project = services.NewProjectService(db, svcs.Settings, svcs.Event, svcs.Image, svcs.Docker, svcs.Build, cfg)
svcs.Container = services.NewContainerService(db, svcs.Event, svcs.Docker, svcs.Image, svcs.Settings, svcs.Project)
- svcs.Dashboard = services.NewDashboardService(db, svcs.Docker, svcs.Container, svcs.Settings, svcs.Vulnerability, svcs.Environment, svcs.Version)
+ svcs.Dashboard = services.NewDashboardService(
+ db,
+ svcs.Docker,
+ svcs.Container,
+ svcs.Project,
+ svcs.Settings,
+ svcs.Vulnerability,
+ svcs.Environment,
+ svcs.Version,
+ )
svcs.Volume = services.NewVolumeService(db, svcs.Docker, svcs.Event, svcs.Settings, svcs.Container, svcs.Image, cfg.BackupVolumeName)
svcs.Network = services.NewNetworkService(db, svcs.Docker, svcs.Event)
svcs.Port = services.NewPortService(svcs.Docker)
diff --git a/backend/internal/huma/handlers/containers.go b/backend/internal/huma/handlers/containers.go
index 6bbbc4e7c..3aaff6448 100644
--- a/backend/internal/huma/handlers/containers.go
+++ b/backend/internal/huma/handlers/containers.go
@@ -44,6 +44,7 @@ type ListContainersInput struct {
GroupBy string `query:"groupBy" doc:"Optional grouping mode (for example: project)"`
IncludeInternal bool `query:"includeInternal" default:"false" doc:"Include internal containers"`
Updates string `query:"updates" doc:"Filter by update status (has_update, up_to_date, error, unknown)"`
+ Standalone string `query:"standalone" doc:"Filter standalone containers only (true/false)"`
}
type ListContainersOutput struct {
@@ -244,6 +245,9 @@ func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContai
if input.Updates != "" {
filters["updates"] = input.Updates
}
+ if input.Standalone != "" {
+ filters["standalone"] = input.Standalone
+ }
params := pagination.QueryParams{
SearchQuery: pagination.SearchQuery{Search: input.Search},
diff --git a/backend/internal/huma/handlers/dashboard_test.go b/backend/internal/huma/handlers/dashboard_test.go
index f1a96a125..6410e4d90 100644
--- a/backend/internal/huma/handlers/dashboard_test.go
+++ b/backend/internal/huma/handlers/dashboard_test.go
@@ -111,7 +111,7 @@ func TestDashboardHandlerGetDashboardReturnsSnapshot(t *testing.T) {
dockerSvc := newDashboardHandlerTestDockerService(t, settingsSvc, containers, images)
handler := &DashboardHandler{
- dashboardService: services.NewDashboardService(db, dockerSvc, nil, settingsSvc, nil, nil, nil),
+ dashboardService: services.NewDashboardService(db, dockerSvc, nil, nil, settingsSvc, nil, nil, nil),
}
output, err := handler.GetDashboard(context.Background(), &GetDashboardInput{EnvironmentID: "0"})
@@ -144,7 +144,16 @@ func TestDashboardHandlerGetEnvironmentsOverviewReturnsAggregateSummary(t *testi
}).Error)
handler := &DashboardHandler{
- dashboardService: services.NewDashboardService(db, nil, nil, settingsSvc, nil, services.NewEnvironmentService(db, http.DefaultClient, nil, nil, settingsSvc, nil), services.NewVersionService(nil, true, "1.2.3", "abcdef1234567890", nil, nil)),
+ dashboardService: services.NewDashboardService(
+ db,
+ nil,
+ nil,
+ nil,
+ settingsSvc,
+ nil,
+ services.NewEnvironmentService(db, http.DefaultClient, nil, nil, settingsSvc, nil),
+ services.NewVersionService(nil, true, "1.2.3", "abcdef1234567890", nil, nil),
+ ),
}
output, err := handler.GetEnvironmentsOverview(context.Background(), &GetDashboardEnvironmentsOverviewInput{})
diff --git a/backend/internal/huma/handlers/image_updates.go b/backend/internal/huma/handlers/image_updates.go
index c0449b428..79a482207 100644
--- a/backend/internal/huma/handlers/image_updates.go
+++ b/backend/internal/huma/handlers/image_updates.go
@@ -3,16 +3,19 @@ package handlers
import (
"context"
"net/http"
+ "strings"
"github.com/danielgtaylor/huma/v2"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/types/base"
+ imagetypes "github.com/getarcaneapp/arcane/types/image"
"github.com/getarcaneapp/arcane/types/imageupdate"
)
type ImageUpdateHandler struct {
imageUpdateService *services.ImageUpdateService
+ imageService *services.ImageService
}
type CheckImageUpdateInput struct {
@@ -51,6 +54,15 @@ type CheckAllImagesOutput struct {
Body base.ApiResponse[imageupdate.BatchResponse]
}
+type GetUpdateInfoByRefsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ImageRefs string `query:"imageRefs" doc:"Comma-separated image references"`
+}
+
+type GetUpdateInfoByRefsOutput struct {
+ Body base.ApiResponse[map[string]*imagetypes.UpdateInfo]
+}
+
type GetUpdateSummaryInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
@@ -60,8 +72,11 @@ type GetUpdateSummaryOutput struct {
}
// RegisterImageUpdates registers image update endpoints.
-func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateService) {
- h := &ImageUpdateHandler{imageUpdateService: imageUpdateSvc}
+func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateService, imageSvc *services.ImageService) {
+ h := &ImageUpdateHandler{
+ imageUpdateService: imageUpdateSvc,
+ imageService: imageSvc,
+ }
huma.Register(api, huma.Operation{
OperationID: "check-image-update",
@@ -108,6 +123,15 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
}, h.CheckAllImages)
+ huma.Register(api, huma.Operation{
+ OperationID: "get-update-info-by-refs",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/image-updates/by-refs",
+ Summary: "Get persisted update info for image references",
+ Tags: []string{"Image Updates"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.GetUpdateInfoByRefs)
+
huma.Register(api, huma.Operation{
OperationID: "get-update-summary",
Method: http.MethodGet,
@@ -192,6 +216,30 @@ func (h *ImageUpdateHandler) CheckAllImages(ctx context.Context, input *CheckAll
}, nil
}
+func (h *ImageUpdateHandler) GetUpdateInfoByRefs(ctx context.Context, input *GetUpdateInfoByRefsInput) (*GetUpdateInfoByRefsOutput, error) {
+ imageRefs := parseImageRefsQueryInternal(input.ImageRefs)
+ if len(imageRefs) == 0 {
+ return &GetUpdateInfoByRefsOutput{
+ Body: base.ApiResponse[map[string]*imagetypes.UpdateInfo]{
+ Success: true,
+ Data: map[string]*imagetypes.UpdateInfo{},
+ },
+ }, nil
+ }
+
+ result, err := h.imageService.GetUpdateInfoByImageRefs(ctx, imageRefs)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.BatchImageUpdateCheckError{Err: err}).Error())
+ }
+
+ return &GetUpdateInfoByRefsOutput{
+ Body: base.ApiResponse[map[string]*imagetypes.UpdateInfo]{
+ Success: true,
+ Data: result,
+ },
+ }, nil
+}
+
func (h *ImageUpdateHandler) GetUpdateSummary(ctx context.Context, input *GetUpdateSummaryInput) (*GetUpdateSummaryOutput, error) {
summary, err := h.imageUpdateService.GetUpdateSummary(ctx)
if err != nil {
@@ -205,3 +253,26 @@ func (h *ImageUpdateHandler) GetUpdateSummary(ctx context.Context, input *GetUpd
},
}, nil
}
+
+func parseImageRefsQueryInternal(raw string) []string {
+ if strings.TrimSpace(raw) == "" {
+ return nil
+ }
+
+ parts := strings.Split(raw, ",")
+ result := make([]string, 0, len(parts))
+ seen := make(map[string]struct{}, len(parts))
+ for _, part := range parts {
+ ref := strings.TrimSpace(part)
+ if ref == "" {
+ continue
+ }
+ if _, exists := seen[ref]; exists {
+ continue
+ }
+ seen[ref] = struct{}{}
+ result = append(result, ref)
+ }
+
+ return result
+}
diff --git a/backend/internal/huma/handlers/projects.go b/backend/internal/huma/handlers/projects.go
index 08ed1b28a..09be87b6f 100644
--- a/backend/internal/huma/handlers/projects.go
+++ b/backend/internal/huma/handlers/projects.go
@@ -42,6 +42,7 @@ type ListProjectsInput struct {
Start int `query:"start" default:"0" doc:"Start index for pagination"`
Limit int `query:"limit" default:"20" doc:"Number of items per page"`
Status string `query:"status" doc:"Filter by status (comma-separated: running,stopped,partially running)"`
+ Updates string `query:"updates" doc:"Filter by update status (has_update, up_to_date, error, unknown)"`
}
type ListProjectsOutput struct {
@@ -375,6 +376,14 @@ func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsIn
return nil, huma.Error500InternalServerError("service not available")
}
+ filters := map[string]string{}
+ if input.Status != "" {
+ filters["status"] = input.Status
+ }
+ if input.Updates != "" {
+ filters["updates"] = input.Updates
+ }
+
params := pagination.QueryParams{
SearchQuery: pagination.SearchQuery{
Search: input.Search,
@@ -387,9 +396,7 @@ func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsIn
Start: input.Start,
Limit: input.Limit,
},
- Filters: map[string]string{
- "status": input.Status,
- },
+ Filters: filters,
}
projects, paginationResp, err := h.projectService.ListProjects(ctx, params)
diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.go
index 515ec000a..ce58f405a 100644
--- a/backend/internal/huma/huma.go
+++ b/backend/internal/huma/huma.go
@@ -402,7 +402,7 @@ func registerHandlers(api huma.API, svc *Services) {
handlers.RegisterTemplates(api, templateSvc, environmentSvc)
handlers.RegisterImages(api, dockerSvc, imageSvc, imageUpdateSvc, settingsSvc, buildSvc)
handlers.RegisterBuildWorkspaces(api, buildWorkspaceSvc)
- handlers.RegisterImageUpdates(api, imageUpdateSvc)
+ handlers.RegisterImageUpdates(api, imageUpdateSvc, imageSvc)
handlers.RegisterSettings(api, settingsSvc, settingsSearchSvc, environmentSvc, cfg)
handlers.RegisterJobSchedules(api, jobScheduleSvc, environmentSvc)
handlers.RegisterVolumes(api, dockerSvc, volumeSvc)
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index b8daab919..64a7af3aa 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -1287,6 +1287,20 @@ func (s *ContainerService) buildContainerFilterAccessors() []pagination.FilterAc
}
},
},
+ {
+ Key: "standalone",
+ Fn: func(c containertypes.Summary, filterValue string) bool {
+ isStandalone := strings.TrimSpace(c.Labels["com.docker.compose.project"]) == ""
+ switch filterValue {
+ case "true", "1":
+ return isStandalone
+ case "false", "0":
+ return !isStandalone
+ default:
+ return true
+ }
+ },
+ },
}
}
diff --git a/backend/internal/services/container_service_test.go b/backend/internal/services/container_service_test.go
index fcca58cc2..c9a4f2477 100644
--- a/backend/internal/services/container_service_test.go
+++ b/backend/internal/services/container_service_test.go
@@ -80,6 +80,24 @@ func TestGroupContainersByProjectUsesNoProjectBucket(t *testing.T) {
require.Equal(t, containerNoProjectGroup, getContainerProjectNameInternal(groups[1].Items[1]))
}
+func TestBuildContainerFilterAccessors_FiltersStandaloneContainers(t *testing.T) {
+ service := &ContainerService{}
+ items := []containertypes.Summary{
+ {ID: "standalone", Labels: map[string]string{}},
+ {ID: "compose", Labels: map[string]string{"com.docker.compose.project": "alpha"}},
+ }
+
+ result := pagination.SearchOrderAndPaginate(
+ items,
+ pagination.QueryParams{Filters: map[string]string{"standalone": "true"}},
+ pagination.Config[containertypes.Summary]{FilterAccessors: service.buildContainerFilterAccessors()},
+ )
+
+ require.Len(t, result.Items, 1)
+ require.Equal(t, "standalone", result.Items[0].ID)
+ require.Equal(t, int64(1), result.TotalCount)
+}
+
func TestBuildCleanNetworkingConfigInternalPreservesEndpointSettings(t *testing.T) {
containerInspect := container.InspectResponse{
NetworkSettings: &container.NetworkSettings{
diff --git a/backend/internal/services/dashboard_service.go b/backend/internal/services/dashboard_service.go
index 3b7561842..42a05b20c 100644
--- a/backend/internal/services/dashboard_service.go
+++ b/backend/internal/services/dashboard_service.go
@@ -34,6 +34,7 @@ type DashboardService struct {
db *database.DB
dockerService *DockerClientService
containerService *ContainerService
+ projectService *ProjectService
settingsService *SettingsService
vulnerabilityService *VulnerabilityService
environmentService *EnvironmentService
@@ -48,6 +49,7 @@ func NewDashboardService(
db *database.DB,
dockerService *DockerClientService,
containerService *ContainerService,
+ projectService *ProjectService,
settingsService *SettingsService,
vulnerabilityService *VulnerabilityService,
environmentService *EnvironmentService,
@@ -57,6 +59,7 @@ func NewDashboardService(
db: db,
dockerService: dockerService,
containerService: containerService,
+ projectService: projectService,
settingsService: settingsService,
vulnerabilityService: vulnerabilityService,
environmentService: environmentService,
@@ -174,7 +177,7 @@ func (s *DashboardService) GetActionItems(ctx context.Context, options Dashboard
var (
stoppedContainers int
- pendingImageUpdates int
+ pendingResourceUpdates int
actionableVulnerabilities int
expiringAPIKeys int
)
@@ -191,11 +194,11 @@ func (s *DashboardService) GetActionItems(ctx context.Context, options Dashboard
})
g.Go(func() error {
- count, err := s.getPendingImageUpdatesCountInternal(groupCtx)
+ count, err := s.getPendingResourceUpdatesCountInternal(groupCtx)
if err != nil {
return err
}
- pendingImageUpdates = count
+ pendingResourceUpdates = count
return nil
})
@@ -231,10 +234,10 @@ func (s *DashboardService) GetActionItems(ctx context.Context, options Dashboard
})
}
- if pendingImageUpdates > 0 {
+ if pendingResourceUpdates > 0 {
actionItems = append(actionItems, dashboardtypes.ActionItem{
Kind: dashboardtypes.ActionItemKindImageUpdates,
- Count: pendingImageUpdates,
+ Count: pendingResourceUpdates,
Severity: dashboardtypes.ActionItemSeverityWarning,
})
}
@@ -312,14 +315,14 @@ func (s *DashboardService) buildActionItemsForSnapshotInternal(
ctx context.Context,
options DashboardActionItemsOptions,
containers []dockercontainer.Summary,
- images []dockerimage.Summary,
+ _ []dockerimage.Summary,
) (*dashboardtypes.ActionItems, error) {
if options.DebugAllGood {
return &dashboardtypes.ActionItems{Items: []dashboardtypes.ActionItem{}}, nil
}
var (
- pendingImageUpdates int
+ pendingResourceUpdates int
actionableVulnerabilities int
expiringAPIKeys int
)
@@ -327,11 +330,11 @@ func (s *DashboardService) buildActionItemsForSnapshotInternal(
g, groupCtx := errgroup.WithContext(ctx)
g.Go(func() error {
- count, err := s.getPendingImageUpdatesCountForImageIDs(groupCtx, extractDockerImageIDsInternal(images))
+ count, err := s.getPendingResourceUpdatesCountInternal(groupCtx)
if err != nil {
return err
}
- pendingImageUpdates = count
+ pendingResourceUpdates = count
return nil
})
@@ -364,12 +367,12 @@ func (s *DashboardService) buildActionItemsForSnapshotInternal(
}
}
- return buildDashboardActionItemsInternal(stoppedContainers, pendingImageUpdates, actionableVulnerabilities, expiringAPIKeys), nil
+ return buildDashboardActionItemsInternal(stoppedContainers, pendingResourceUpdates, actionableVulnerabilities, expiringAPIKeys), nil
}
func buildDashboardActionItemsInternal(
stoppedContainers int,
- pendingImageUpdates int,
+ pendingResourceUpdates int,
actionableVulnerabilities int,
expiringAPIKeys int,
) *dashboardtypes.ActionItems {
@@ -383,10 +386,10 @@ func buildDashboardActionItemsInternal(
})
}
- if pendingImageUpdates > 0 {
+ if pendingResourceUpdates > 0 {
actionItems = append(actionItems, dashboardtypes.ActionItem{
Kind: dashboardtypes.ActionItemKindImageUpdates,
- Count: pendingImageUpdates,
+ Count: pendingResourceUpdates,
Severity: dashboardtypes.ActionItemSeverityWarning,
})
}
@@ -630,20 +633,31 @@ func summarizeEnvironmentOverviewInternal(items []dashboardtypes.EnvironmentOver
return summary
}
-func (s *DashboardService) getPendingImageUpdatesCountInternal(ctx context.Context) (int, error) {
+func (s *DashboardService) getPendingResourceUpdatesCountInternal(ctx context.Context) (int, error) {
if s.db == nil || s.dockerService == nil {
return 0, nil
}
- images, _, _, _, err := s.dockerService.GetAllImages(ctx)
+ containers, _, _, _, err := s.dockerService.GetAllContainers(ctx)
+ if err != nil {
+ return 0, fmt.Errorf("failed to load containers for update counts: %w", err)
+ }
+
+ filteredContainers := filterInternalContainers(containers, false)
+ containerCount, err := s.getPendingContainerUpdatesCountForImageIDsInternal(ctx, collectImageIDs(filteredContainers))
+ if err != nil {
+ return 0, err
+ }
+
+ projectCount, err := s.getPendingProjectUpdatesCountInternal(ctx)
if err != nil {
- return 0, fmt.Errorf("failed to load images for update counts: %w", err)
+ return 0, err
}
- return s.getPendingImageUpdatesCountForImageIDs(ctx, extractDockerImageIDsInternal(images))
+ return containerCount + projectCount, nil
}
-func (s *DashboardService) getPendingImageUpdatesCountForImageIDs(ctx context.Context, imageIDs []string) (int, error) {
+func (s *DashboardService) getPendingContainerUpdatesCountForImageIDsInternal(ctx context.Context, imageIDs []string) (int, error) {
if s.db == nil || len(imageIDs) == 0 {
return 0, nil
}
@@ -654,12 +668,24 @@ func (s *DashboardService) getPendingImageUpdatesCountForImageIDs(ctx context.Co
Where("id IN ? AND has_update = ?", imageIDs, true).
Count(&count).Error
if err != nil {
- return 0, fmt.Errorf("failed to count pending image updates: %w", err)
+ return 0, fmt.Errorf("failed to count pending container updates: %w", err)
}
return int(count), nil
}
+func (s *DashboardService) getPendingProjectUpdatesCountInternal(ctx context.Context) (int, error) {
+ if s.projectService == nil {
+ return 0, nil
+ }
+
+ count, err := s.projectService.countProjectsByUpdateStatusInternal(ctx, "has_update")
+ if err != nil {
+ return 0, fmt.Errorf("failed to count projects with updates: %w", err)
+ }
+
+ return count, nil
+}
func (s *DashboardService) getActionableVulnerabilitiesCountInternal(ctx context.Context) (int, error) {
if s.vulnerabilityService == nil {
return 0, nil
@@ -686,22 +712,6 @@ func (s *DashboardService) getExpiringAPIKeysCountInternal(ctx context.Context)
return int(count), nil
}
-func extractDockerImageIDsInternal(images []dockerimage.Summary) []string {
- if len(images) == 0 {
- return nil
- }
-
- imageIDs := make([]string, 0, len(images))
- for _, img := range images {
- if img.ID == "" {
- continue
- }
- imageIDs = append(imageIDs, img.ID)
- }
-
- return imageIDs
-}
-
func (s *DashboardService) listDashboardContainersInternal(ctx context.Context) ([]dockercontainer.Summary, error) {
if s.dockerService == nil {
return nil, fmt.Errorf("docker service not available")
diff --git a/backend/internal/services/dashboard_service_test.go b/backend/internal/services/dashboard_service_test.go
index 253f1042f..e0a0dd46a 100644
--- a/backend/internal/services/dashboard_service_test.go
+++ b/backend/internal/services/dashboard_service_test.go
@@ -5,10 +5,13 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"strings"
"testing"
"time"
+ "github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/types/base"
@@ -20,6 +23,7 @@ import (
dockercontainer "github.com/moby/moby/api/types/container"
dockerimage "github.com/moby/moby/api/types/image"
"github.com/moby/moby/client"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
@@ -96,7 +100,7 @@ func newDashboardTestVersionServiceInternal() *VersionService {
func TestDashboardService_GetActionItems_IncludesExpiringAPIKeys(t *testing.T) {
db, settingsSvc := setupDashboardServiceTestDB(t)
- svc := NewDashboardService(db, nil, nil, settingsSvc, nil, nil, nil)
+ svc := NewDashboardService(db, nil, nil, nil, settingsSvc, nil, nil, nil)
now := time.Now()
createDashboardTestAPIKey(t, db, models.ApiKey{
@@ -140,7 +144,7 @@ func TestDashboardService_GetActionItems_IncludesExpiringAPIKeys(t *testing.T) {
func TestDashboardService_GetActionItems_DebugAllGoodReturnsNoItems(t *testing.T) {
db, settingsSvc := setupDashboardServiceTestDB(t)
- svc := NewDashboardService(db, nil, nil, settingsSvc, nil, nil, nil)
+ svc := NewDashboardService(db, nil, nil, nil, settingsSvc, nil, nil, nil)
createDashboardTestAPIKey(t, db, models.ApiKey{
Name: "expiring-soon",
@@ -201,7 +205,12 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {
{ID: "sha256:image-c", RepoTags: []string{"ghcr.io/getarcaneapp/arcane:latest"}, Created: 1730000000, Size: 175},
}
- createDashboardTestImageUpdateRecord(t, db, models.ImageUpdateRecord{ID: "sha256:image-b", HasUpdate: true})
+ createDashboardTestImageUpdateRecord(t, db, models.ImageUpdateRecord{
+ ID: "sha256:image-b",
+ Repository: "docker.io/repo/worker",
+ Tag: "latest",
+ HasUpdate: true,
+ })
createDashboardTestAPIKey(t, db, models.ApiKey{
Name: "expiring-soon",
@@ -212,7 +221,20 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {
})
dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images)
- svc := NewDashboardService(db, dockerSvc, nil, settingsSvc, nil, nil, nil)
+ projectsDir := t.TempDir()
+ t.Setenv("PROJECTS_DIRECTORY", projectsDir)
+ require.NoError(t, settingsSvc.SetStringSetting(context.Background(), "projectsDirectory", projectsDir))
+ projectPath := createComposeProjectDir(t, projectsDir, "project-with-update")
+ require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: repo/worker:latest\n"), 0o644))
+ require.NoError(t, db.WithContext(context.Background()).Create(&models.Project{
+ BaseModel: models.BaseModel{ID: "project-with-update"},
+ Name: "project-with-update",
+ DirName: ptr("project-with-update"),
+ Path: projectPath,
+ Status: models.ProjectStatusStopped,
+ }).Error)
+ projectSvc := NewProjectService(db, settingsSvc, nil, &ImageService{db: db}, nil, nil, config.Load())
+ svc := NewDashboardService(db, dockerSvc, nil, projectSvc, settingsSvc, nil, nil, nil)
snapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{})
require.NoError(t, err)
@@ -235,7 +257,7 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {
require.ElementsMatch(t, []dashboardtypes.ActionItem{
{Kind: dashboardtypes.ActionItemKindStoppedContainers, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},
- {Kind: dashboardtypes.ActionItemKindImageUpdates, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},
+ {Kind: dashboardtypes.ActionItemKindImageUpdates, Count: 2, Severity: dashboardtypes.ActionItemSeverityWarning},
{Kind: dashboardtypes.ActionItemKindExpiringKeys, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},
}, snapshot.ActionItems.Items)
}
@@ -262,7 +284,7 @@ func TestDashboardService_GetSnapshot_DebugAllGoodOnlyClearsActionItems(t *testi
createDashboardTestImageUpdateRecord(t, db, models.ImageUpdateRecord{ID: "sha256:image-b", HasUpdate: true})
dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images)
- svc := NewDashboardService(db, dockerSvc, nil, settingsSvc, nil, nil, nil)
+ svc := NewDashboardService(db, dockerSvc, nil, nil, settingsSvc, nil, nil, nil)
snapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{DebugAllGood: true})
require.NoError(t, err)
@@ -359,7 +381,7 @@ func TestDashboardService_GetEnvironmentsOverview_ReturnsLocalAndRemoteSummaries
dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images)
envSvc := NewEnvironmentService(db, remoteServer.Client(), nil, nil, settingsSvc, nil)
- svc := NewDashboardService(db, dockerSvc, nil, settingsSvc, nil, envSvc, newDashboardTestVersionServiceInternal())
+ svc := NewDashboardService(db, dockerSvc, nil, nil, settingsSvc, nil, envSvc, newDashboardTestVersionServiceInternal())
overview, err := svc.GetEnvironmentsOverview(context.Background(), DashboardActionItemsOptions{})
require.NoError(t, err)
@@ -405,7 +427,7 @@ func TestDashboardService_GetEnvironmentsOverview_HandlesRemoteSnapshotFailure(t
})
envSvc := NewEnvironmentService(db, http.DefaultClient, nil, nil, settingsSvc, nil)
- svc := NewDashboardService(db, nil, nil, settingsSvc, nil, envSvc, newDashboardTestVersionServiceInternal())
+ svc := NewDashboardService(db, nil, nil, nil, settingsSvc, nil, envSvc, newDashboardTestVersionServiceInternal())
overview, err := svc.GetEnvironmentsOverview(context.Background(), DashboardActionItemsOptions{})
require.NoError(t, err)
@@ -471,7 +493,7 @@ func TestDashboardService_GetEnvironmentsOverview_OmitsVersionInfoWhenFetchFails
})
envSvc := NewEnvironmentService(db, remoteServer.Client(), nil, nil, settingsSvc, nil)
- svc := NewDashboardService(db, nil, nil, settingsSvc, nil, envSvc, newDashboardTestVersionServiceInternal())
+ svc := NewDashboardService(db, nil, nil, nil, settingsSvc, nil, envSvc, newDashboardTestVersionServiceInternal())
overview, err := svc.GetEnvironmentsOverview(context.Background(), DashboardActionItemsOptions{})
require.NoError(t, err)
@@ -482,3 +504,63 @@ func TestDashboardService_GetEnvironmentsOverview_OmitsVersionInfoWhenFetchFails
require.Equal(t, 1, overview.Environments[0].Containers.TotalContainers)
require.Nil(t, overview.Environments[0].VersionInfo)
}
+
+func TestDashboardService_GetActionItems_CountsAffectedResources(t *testing.T) {
+ db, settingsSvc := setupDashboardServiceTestDB(t)
+ ctx := context.Background()
+
+ containers := []dockercontainer.Summary{
+ {
+ ID: "container-updated",
+ Names: []string{"/updated-app"},
+ Image: "repo/app:latest",
+ ImageID: "sha256:image-a",
+ Created: 1700000000,
+ State: "running",
+ Status: "Up 2 hours",
+ Labels: map[string]string{},
+ },
+ }
+ images := []dockerimage.Summary{
+ {ID: "sha256:image-a", RepoTags: []string{"repo/app:latest"}, Created: 1710000000, Size: 100},
+ {ID: "sha256:image-unused", RepoTags: []string{"repo/unused:latest"}, Created: 1710000001, Size: 50},
+ }
+
+ createDashboardTestImageUpdateRecord(t, db, models.ImageUpdateRecord{
+ ID: "sha256:image-a",
+ Repository: "docker.io/repo/app",
+ Tag: "latest",
+ HasUpdate: true,
+ })
+ createDashboardTestImageUpdateRecord(t, db, models.ImageUpdateRecord{
+ ID: "sha256:image-unused",
+ Repository: "docker.io/repo/unused",
+ Tag: "latest",
+ HasUpdate: true,
+ })
+
+ projectsDir := t.TempDir()
+ t.Setenv("PROJECTS_DIRECTORY", projectsDir)
+ require.NoError(t, settingsSvc.SetStringSetting(ctx, "projectsDirectory", projectsDir))
+ projectPath := createComposeProjectDir(t, projectsDir, "project-with-update")
+ require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: repo/app:latest\n"), 0o644))
+ require.NoError(t, db.WithContext(ctx).Create(&models.Project{
+ BaseModel: models.BaseModel{ID: "project-with-update"},
+ Name: "project-with-update",
+ DirName: ptr("project-with-update"),
+ Path: projectPath,
+ Status: models.ProjectStatusStopped,
+ }).Error)
+
+ dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images)
+ projectSvc := NewProjectService(db, settingsSvc, nil, &ImageService{db: db}, nil, nil, config.Load())
+ svc := NewDashboardService(db, dockerSvc, nil, projectSvc, settingsSvc, nil, nil, nil)
+
+ actionItems, err := svc.GetActionItems(ctx, DashboardActionItemsOptions{})
+ require.NoError(t, err)
+ require.NotNil(t, actionItems)
+
+ require.Len(t, actionItems.Items, 1)
+ assert.Equal(t, dashboardtypes.ActionItemKindImageUpdates, actionItems.Items[0].Kind)
+ assert.Equal(t, 2, actionItems.Items[0].Count)
+}
diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.go
index 30c6159df..2ff77fe0b 100644
--- a/backend/internal/services/image_service.go
+++ b/backend/internal/services/image_service.go
@@ -485,6 +485,65 @@ func (s *ImageService) GetUpdateInfoByImageIDs(ctx context.Context, imageIDs []s
return result, nil
}
+type imageRefUpdateLookup struct {
+ originalRef string
+ tag string
+ repositoryCandidates map[string]struct{}
+}
+
+// GetUpdateInfoByImageRefs returns persisted update information keyed by the
+// original image reference string.
+func (s *ImageService) GetUpdateInfoByImageRefs(ctx context.Context, imageRefs []string) (map[string]*imagetypes.UpdateInfo, error) {
+ result := make(map[string]*imagetypes.UpdateInfo)
+ if s.db == nil || len(imageRefs) == 0 {
+ return result, nil
+ }
+
+ lookups := buildImageRefUpdateLookupsInternal(imageRefs)
+ if len(lookups) == 0 {
+ return result, nil
+ }
+
+ repositoryCandidates := make([]string, 0)
+ repositorySeen := make(map[string]struct{})
+ tags := make([]string, 0, len(lookups))
+ tagSeen := make(map[string]struct{})
+
+ for _, lookup := range lookups {
+ if _, exists := tagSeen[lookup.tag]; !exists {
+ tagSeen[lookup.tag] = struct{}{}
+ tags = append(tags, lookup.tag)
+ }
+ for repo := range lookup.repositoryCandidates {
+ if _, exists := repositorySeen[repo]; exists {
+ continue
+ }
+ repositorySeen[repo] = struct{}{}
+ repositoryCandidates = append(repositoryCandidates, repo)
+ }
+ }
+
+ if len(repositoryCandidates) == 0 || len(tags) == 0 {
+ return result, nil
+ }
+
+ var updateRecords []models.ImageUpdateRecord
+ if err := s.db.WithContext(ctx).
+ Where("tag IN ? AND repository IN ?", tags, repositoryCandidates).
+ Order("check_time DESC").
+ Find(&updateRecords).Error; err != nil {
+ return nil, fmt.Errorf("failed to fetch update records by image refs: %w", err)
+ }
+
+ for _, lookup := range lookups {
+ if record := selectLatestMatchingImageUpdateRecordInternal(lookup, updateRecords); record != nil {
+ result[lookup.originalRef] = buildUpdateInfo(record)
+ }
+ }
+
+ return result, nil
+}
+
func (s *ImageService) ListImagesPaginated(ctx context.Context, params pagination.QueryParams) ([]imagetypes.Summary, pagination.Response, error) {
dockerClient, err := s.dockerService.GetClient(ctx)
if err != nil {
@@ -560,6 +619,94 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatio
return result.Items, paginationResp, nil
}
+func buildImageRefUpdateLookupsInternal(imageRefs []string) []imageRefUpdateLookup {
+ lookups := make([]imageRefUpdateLookup, 0, len(imageRefs))
+ seen := make(map[string]struct{}, len(imageRefs))
+
+ for _, rawRef := range imageRefs {
+ lookup, ok := parseImageRefUpdateLookupInternal(rawRef)
+ if !ok {
+ continue
+ }
+ if _, exists := seen[lookup.originalRef]; exists {
+ continue
+ }
+ seen[lookup.originalRef] = struct{}{}
+ lookups = append(lookups, lookup)
+ }
+
+ return lookups
+}
+
+func parseImageRefUpdateLookupInternal(imageRef string) (imageRefUpdateLookup, bool) {
+ trimmedRef := strings.TrimSpace(imageRef)
+ if trimmedRef == "" {
+ return imageRefUpdateLookup{}, false
+ }
+
+ named, err := ref.ParseNormalizedNamed(trimmedRef)
+ if err != nil {
+ return imageRefUpdateLookup{}, false
+ }
+
+ tag := "latest"
+ if tagged, ok := named.(ref.NamedTagged); ok {
+ tag = strings.TrimSpace(tagged.Tag())
+ }
+ if tag == "" {
+ tag = "latest"
+ }
+
+ registryHost := utilsregistry.NormalizeRegistryForComparison(ref.Domain(named))
+ repositoryPath := strings.TrimSpace(ref.Path(named))
+ familiarRepository := strings.TrimSpace(ref.FamiliarName(named))
+
+ repositoryCandidates := map[string]struct{}{}
+ for _, candidate := range []string{
+ repositoryPath,
+ familiarRepository,
+ fmt.Sprintf("%s/%s", registryHost, repositoryPath),
+ } {
+ candidate = strings.TrimSpace(candidate)
+ if candidate == "" {
+ continue
+ }
+ repositoryCandidates[candidate] = struct{}{}
+ }
+
+ if registryHost == "docker.io" && strings.HasPrefix(repositoryPath, "library/") {
+ repositoryCandidates[strings.TrimPrefix(repositoryPath, "library/")] = struct{}{}
+ }
+
+ return imageRefUpdateLookup{
+ originalRef: trimmedRef,
+ tag: tag,
+ repositoryCandidates: repositoryCandidates,
+ }, true
+}
+
+func selectLatestMatchingImageUpdateRecordInternal(
+ lookup imageRefUpdateLookup,
+ updateRecords []models.ImageUpdateRecord,
+) *models.ImageUpdateRecord {
+ var latest *models.ImageUpdateRecord
+
+ for i := range updateRecords {
+ record := &updateRecords[i]
+ if !strings.EqualFold(strings.TrimSpace(record.Tag), lookup.tag) {
+ continue
+ }
+ if _, exists := lookup.repositoryCandidates[strings.TrimSpace(record.Repository)]; !exists {
+ continue
+ }
+ if latest == nil || record.CheckTime.After(latest.CheckTime) {
+ latest = record
+ }
+ }
+
+ return latest
+}
+
func convertLabels(labels map[string]string) map[string]any {
if labels == nil {
return nil
diff --git a/backend/internal/services/image_service_test.go b/backend/internal/services/image_service_test.go
index 3a4ace342..5a09e1d0b 100644
--- a/backend/internal/services/image_service_test.go
+++ b/backend/internal/services/image_service_test.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"testing"
+ "time"
glsqlite "github.com/glebarez/sqlite"
"github.com/stretchr/testify/require"
@@ -53,6 +54,54 @@ func TestApplyVulnerabilitySummariesToItemsInternal(t *testing.T) {
assert.Nil(t, items[1].VulnerabilityScan)
}
+func TestImageService_GetUpdateInfoByImageRefs_MatchesCanonicalAndFamiliarRepos(t *testing.T) {
+ db, err := gorm.Open(glsqlite.Open(":memory:"), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, db.AutoMigrate(&models.ImageUpdateRecord{}))
+
+ svc := &ImageService{db: &database.DB{DB: db}}
+ now := time.Now().UTC()
+
+ records := []models.ImageUpdateRecord{
+ {
+ ID: "sha256:nginx-latest",
+ Repository: "docker.io/library/nginx",
+ Tag: "latest",
+ HasUpdate: true,
+ UpdateType: "digest",
+ CurrentVersion: "latest",
+ CheckTime: now,
+ },
+ {
+ ID: "sha256:redis-seven",
+ Repository: "library/redis",
+ Tag: "7",
+ HasUpdate: false,
+ UpdateType: "digest",
+ CurrentVersion: "7",
+ CheckTime: now.Add(-time.Minute),
+ },
+ }
+
+ for i := range records {
+ require.NoError(t, db.Create(&records[i]).Error)
+ }
+
+ updates, err := svc.GetUpdateInfoByImageRefs(context.Background(), []string{
+ "nginx:latest",
+ "docker.io/library/nginx:latest",
+ "redis:7",
+ })
+ require.NoError(t, err)
+
+ require.Contains(t, updates, "nginx:latest")
+ require.Contains(t, updates, "docker.io/library/nginx:latest")
+ require.Contains(t, updates, "redis:7")
+ assert.True(t, updates["nginx:latest"].HasUpdate)
+ assert.True(t, updates["docker.io/library/nginx:latest"].HasUpdate)
+ assert.False(t, updates["redis:7"].HasUpdate)
+}
+
func setupImageServiceAuthTest(t *testing.T) (*ImageService, *database.DB) {
t.Helper()
diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.go
index 3df84de08..1f04365cf 100644
--- a/backend/internal/services/image_update_service.go
+++ b/backend/internal/services/image_update_service.go
@@ -450,11 +450,58 @@ func (s *ImageUpdateService) saveUpdateResultWithSnapshotInternal(ctx context.Co
}
imageID, err := s.getImageIDByRef(ctx, imageRef)
if err != nil {
- return fmt.Errorf("failed to get image ID: %w", err)
+ repository := buildImageUpdateRepositoryInternal(parts)
+ syntheticID := buildSyntheticImageUpdateRecordIDInternal(repository, parts.Tag)
+ slog.DebugContext(ctx, "Saving image update result with synthetic ref ID",
+ "imageRef", imageRef,
+ "error", err.Error(),
+ "repository", repository,
+ "tag", parts.Tag,
+ "syntheticID", syntheticID)
+ // Persist registry results even when the local image no longer exists. This keeps
+ // project/image update status available for pruned images using a ref-scoped record.
+ return s.savePreparedUpdateResultInternal(ctx, syntheticID, repository, parts.Tag, result)
}
+
return s.saveUpdateResultByIDInternal(ctx, imageID, result)
}
+func buildImageUpdateRepositoryInternal(parts *ImageParts) string {
+ if parts == nil {
+ return ""
+ }
+
+ repository := strings.TrimSpace(parts.Repository)
+ if parts.Registry == "docker.io" && repository != "" && !strings.Contains(repository, "/") {
+ repository = "library/" + repository
+ }
+ if strings.TrimSpace(parts.Registry) == "" {
+ return repository
+ }
+
+ return fmt.Sprintf("%s/%s", strings.TrimSpace(parts.Registry), repository)
+}
+
+func buildSyntheticImageUpdateRecordIDInternal(repository, tag string) string {
+ return fmt.Sprintf("ref::%s@%s", strings.ToLower(strings.TrimSpace(repository)), strings.TrimSpace(tag))
+}
+
+func countBatchResultOutcomesInternal(imageRefs []string, results map[string]*imageupdate.Response) (int, int) {
+ successCount := 0
+ errorCount := 0
+
+ for _, imageRef := range imageRefs {
+ result := results[imageRef]
+ if result != nil && strings.TrimSpace(result.Error) == "" {
+ successCount++
+ continue
+ }
+ errorCount++
+ }
+
+ return successCount, errorCount
+}
+
func extractRepoAndTagFromImage(dockerImage image.InspectResponse) (repo, tag string) {
if len(dockerImage.RepoTags) > 0 && dockerImage.RepoTags[0] != "<none>:<none>" {
if named, err := ref.ParseNormalizedNamed(dockerImage.RepoTags[0]); err == nil {
@@ -814,9 +861,11 @@ func (s *ImageUpdateService) CheckMultipleImages(ctx context.Context, imageRefs
slog.ErrorContext(ctx, "Batch check error", "error", err)
}
+ successCount, errorCount := countBatchResultOutcomesInternal(imageRefs, results)
slog.InfoContext(ctx, "Batch image update check completed",
"totalImages", len(imageRefs),
- "successCount", len(results),
+ "successCount", successCount,
+ "errorCount", errorCount,
"duration", time.Since(startBatch))
if s.notificationService != nil {
diff --git a/backend/internal/services/image_update_service_test.go b/backend/internal/services/image_update_service_test.go
index 94abeaef2..2eb196dee 100644
--- a/backend/internal/services/image_update_service_test.go
+++ b/backend/internal/services/image_update_service_test.go
@@ -404,6 +404,32 @@ func newImageUpdateFallbackServer(t *testing.T, repositoryTag, localDigest, remo
}))
}
+func newImageUpdateRegistryOnlyServer(t *testing.T, repositoryTag, remoteDigest string) *httptest.Server {
+ t.Helper()
+
+ repository := repositoryTag
+ tag := "latest"
+ if tagIndex := strings.LastIndex(repositoryTag, ":"); tagIndex > strings.LastIndex(repositoryTag, "/") {
+ repository = repositoryTag[:tagIndex]
+ tag = repositoryTag[tagIndex+1:]
+ }
+ manifestPath := fmt.Sprintf("/v2/%s/manifests/%s", repository, tag)
+
+ return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):
+ http.Error(w, "not found", http.StatusNotFound)
+ return
+ case r.URL.Path == manifestPath:
+ w.Header().Set("Docker-Content-Digest", remoteDigest)
+ w.WriteHeader(http.StatusOK)
+ return
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+}
+
func newImageRefResolutionServer(t *testing.T, containers []dockertypescontainer.Summary) *httptest.Server {
t.Helper()
@@ -554,6 +580,86 @@ func TestImageUpdateService_CheckMultipleImages_UsesRegistryFallback(t *testing.
assert.Equal(t, remoteDigest, stringPtrToString(saved.LatestDigest))
}
+func TestImageUpdateService_CheckMultipleImages_PersistsRefScopedErrorsWhenLocalImageMissing(t *testing.T) {
+ db := setupImageUpdateTestDB(t)
+ remoteDigest := digest.FromString("registry-only-remote").String()
+
+ server := newImageUpdateRegistryOnlyServer(t, "library/nginx:alpine", remoteDigest)
+ defer server.Close()
+
+ serverURL, err := url.Parse(server.URL)
+ require.NoError(t, err)
+ imageRef := serverURL.Host + "/library/nginx:alpine"
+
+ registryService := NewContainerRegistryService(db, func(context.Context) (RegistryDaemonClient, error) {
+ return &fakeRegistryDaemonClient{
+ distributionInspectFn: func(ctx context.Context, imageRef string, options client.DistributionInspectOptions) (client.DistributionInspectResult, error) {
+ return client.DistributionInspectResult{}, errors.New("Error response from daemon: Not Found")
+ },
+ }, nil
+ })
+ registryService.distributionHTTPClient = server.Client()
+
+ dockerService := &DockerClientService{client: newTestDockerClient(t, server)}
+ eventService := NewEventService(db, nil, nil)
+ svc := NewImageUpdateService(db, nil, registryService, dockerService, eventService, nil)
+
+ results, err := svc.CheckMultipleImages(context.Background(), []string{imageRef}, nil)
+ require.NoError(t, err)
+ require.Contains(t, results, imageRef)
+ require.NotNil(t, results[imageRef])
+ assert.Contains(t, results[imageRef].Error, "failed to inspect image")
+
+ var saved models.ImageUpdateRecord
+ repository := fmt.Sprintf("%s/library/nginx", serverURL.Host)
+ require.NoError(t, db.WithContext(context.Background()).Where("id = ?", buildSyntheticImageUpdateRecordIDInternal(repository, "alpine")).First(&saved).Error)
+ assert.Equal(t, repository, saved.Repository)
+ assert.Equal(t, "alpine", saved.Tag)
+ require.NotNil(t, saved.LastError)
+ assert.Contains(t, *saved.LastError, "failed to inspect image")
+}
+
+func TestImageUpdateService_SaveUpdateResultWithSnapshotInternal_PersistsRegistryOnlySuccessWithSyntheticID(t *testing.T) {
+ db := setupImageUpdateTestDB(t)
+ remoteDigest := digest.FromString("registry-only-success-remote").String()
+
+ server := newImageUpdateRegistryOnlyServer(t, "library/nginx:alpine", remoteDigest)
+ defer server.Close()
+
+ serverURL, err := url.Parse(server.URL)
+ require.NoError(t, err)
+ imageRef := serverURL.Host + "/library/nginx:alpine"
+
+ svc := NewImageUpdateService(db, nil, nil, &DockerClientService{client: newTestDockerClient(t, server)}, nil, nil)
+ result := &imageupdate.Response{
+ HasUpdate: true,
+ UpdateType: "digest",
+ CurrentVersion: "alpine",
+ LatestVersion: "alpine",
+ CurrentDigest: digest.FromString("registry-only-success-local").String(),
+ LatestDigest: remoteDigest,
+ CheckTime: time.Now(),
+ ResponseTimeMs: 25,
+ }
+
+ require.NoError(t, svc.saveUpdateResultWithSnapshotInternal(context.Background(), imageRef, result, nil))
+
+ var saved models.ImageUpdateRecord
+ repository := fmt.Sprintf("%s/library/nginx", serverURL.Host)
+ require.NoError(t, db.WithContext(context.Background()).Where("id = ?", buildSyntheticImageUpdateRecordIDInternal(repository, "alpine")).First(&saved).Error)
+ assert.Equal(t, repository, saved.Repository)
+ assert.Equal(t, "alpine", saved.Tag)
+ assert.True(t, saved.HasUpdate)
+ assert.Equal(t, remoteDigest, stringPtrToString(saved.LatestDigest))
+ assert.Nil(t, saved.LastError)
+}
+
+func TestBuildSyntheticImageUpdateRecordIDInternal_UsesUnambiguousSeparator(t *testing.T) {
+ id := buildSyntheticImageUpdateRecordIDInternal("docker.io/library/nginx", "sha256:abcdef")
+
+ require.Equal(t, "ref::docker.io/library/nginx@sha256:abcdef", id)
+}
+
// TestNotificationSentLogic tests the notification_sent flag behavior
func TestImageUpdateService_NotificationSentLogic(t *testing.T) {
db := setupImageUpdateTestDB(t)
diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.go
index 4694e9d9d..f38089acc 100644
--- a/backend/internal/services/project_service.go
+++ b/backend/internal/services/project_service.go
@@ -717,6 +717,8 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID string
resp.RuntimeServices = runtimeServices
}
+ s.enrichProjectUpdateInfoInternal(ctx, &resp)
+
return resp, nil
}
@@ -823,6 +825,229 @@ func (s *ProjectService) enrichWithIncludeFiles(ctx context.Context, composeFile
}
}
+func (s *ProjectService) enrichProjectUpdateInfoInternal(ctx context.Context, resp *project.Details) {
+ if resp == nil {
+ return
+ }
+
+ imageRefs := buildProjectImageRefsFromComposeConfigsInternal(resp.Services)
+ if len(imageRefs) == 0 {
+ imageRefs = buildProjectImageRefsFromRuntimeServicesInternal(resp.RuntimeServices)
+ }
+
+ var updateInfoByRef map[string]*imagetypes.UpdateInfo
+ if len(imageRefs) > 0 && s.imageService != nil {
+ lookupResult, err := s.imageService.GetUpdateInfoByImageRefs(ctx, imageRefs)
+ if err != nil {
+ slog.WarnContext(ctx, "failed to fetch project update info", "projectID", resp.ID, "projectName", resp.Name, "error", err)
+ } else {
+ updateInfoByRef = lookupResult
+ }
+ }
+
+ resp.UpdateInfo = buildProjectUpdateInfoSummaryInternal(imageRefs, updateInfoByRef)
+}
+
+func (s *ProjectService) enrichProjectsWithUpdateInfoInternal(
+ ctx context.Context,
+ projectsList []models.Project,
+ details []project.Details,
+) {
+ if len(projectsList) == 0 || len(details) == 0 {
+ return
+ }
+
+ imageRefsByProjectID := make(map[string][]string, len(projectsList))
+ allImageRefs := make([]string, 0)
+
+ const maxConcurrentComposeReads = 8
+ type imageRefsResult struct {
+ projectID string
+ refs []string
+ }
+
+ sem := make(chan struct{}, maxConcurrentComposeReads)
+ resultsCh := make(chan imageRefsResult, len(projectsList))
+
+ var wg sync.WaitGroup
+ for _, proj := range projectsList {
+ wg.Add(1)
+ go func(proj models.Project) {
+ defer wg.Done()
+
+ select {
+ case sem <- struct{}{}:
+ case <-ctx.Done():
+ return
+ }
+ defer func() { <-sem }()
+
+ refs, err := s.getProjectImageRefsFromComposeInternal(ctx, proj)
+ if err != nil {
+ slog.WarnContext(ctx, "failed to resolve project image refs for update summary", "projectID", proj.ID, "projectName", proj.Name, "error", err)
+ return
+ }
+
+ resultsCh <- imageRefsResult{projectID: proj.ID, refs: refs}
+ }(proj)
+ }
+
+ wg.Wait()
+ close(resultsCh)
+
+ for result := range resultsCh {
+ imageRefsByProjectID[result.projectID] = result.refs
+ allImageRefs = append(allImageRefs, result.refs...)
+ }
+
+ var updateInfoByRef map[string]*imagetypes.UpdateInfo
+ if len(allImageRefs) > 0 && s.imageService != nil {
+ lookupResult, err := s.imageService.GetUpdateInfoByImageRefs(ctx, allImageRefs)
+ if err != nil {
+ slog.WarnContext(ctx, "failed to fetch project list update info", "error", err)
+ } else {
+ updateInfoByRef = lookupResult
+ }
+ }
+
+ for i := range details {
+ details[i].UpdateInfo = buildProjectUpdateInfoSummaryInternal(imageRefsByProjectID[details[i].ID], updateInfoByRef)
+ }
+}
+
+func (s *ProjectService) getProjectImageRefsFromComposeInternal(ctx context.Context, proj models.Project) ([]string, error) {
+ projectsDir, err := s.getProjectsDirectoryInternal(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ pathMapper, pmErr := s.getPathMapper(ctx)
+ if pmErr != nil {
+ slog.WarnContext(ctx, "failed to create path mapper while resolving project image refs", "projectID", proj.ID, "projectName", proj.Name, "error", pmErr)
+ }
+
+ autoInjectEnv := s.settingsService.GetBoolSetting(ctx, "autoInjectEnv", false)
+ composeProject, _, loadErr := projects.LoadComposeProjectFromDir(
+ ctx,
+ proj.Path,
+ normalizeComposeProjectName(proj.Name),
+ projectsDir,
+ autoInjectEnv,
+ pathMapper,
+ )
+ if loadErr != nil {
+ return nil, fmt.Errorf("load compose project: %w", loadErr)
+ }
+
+ return buildProjectImageRefsFromComposeServicesInternal(composeProject.Services), nil
+}
+
+func buildProjectImageRefsFromComposeServicesInternal(services composetypes.Services) []string {
+ serviceConfigs := make([]composetypes.ServiceConfig, 0, len(services))
+ for _, svc := range services {
+ serviceConfigs = append(serviceConfigs, svc)
+ }
+
+ return buildProjectImageRefsFromComposeConfigsInternal(serviceConfigs)
+}
+
+func buildProjectImageRefsFromComposeConfigsInternal(services []composetypes.ServiceConfig) []string {
+ refs := make([]string, 0, len(services))
+ seen := make(map[string]struct{}, len(services))
+
+ for _, svc := range services {
+ ref := strings.TrimSpace(svc.Image)
+ if ref == "" {
+ continue
+ }
+ if _, exists := seen[ref]; exists {
+ continue
+ }
+ seen[ref] = struct{}{}
+ refs = append(refs, ref)
+ }
+
+ return refs
+}
+
+func buildProjectImageRefsFromRuntimeServicesInternal(services []project.RuntimeService) []string {
+ refs := make([]string, 0, len(services))
+ seen := make(map[string]struct{}, len(services))
+
+ for _, svc := range services {
+ ref := strings.TrimSpace(svc.Image)
+ if ref == "" {
+ continue
+ }
+ if _, exists := seen[ref]; exists {
+ continue
+ }
+ seen[ref] = struct{}{}
+ refs = append(refs, ref)
+ }
+
+ return refs
+}
+
+func buildProjectUpdateInfoSummaryInternal(
+ imageRefs []string,
+ updateInfoByRef map[string]*imagetypes.UpdateInfo,
+) *project.UpdateInfo {
+ imageCount := len(imageRefs)
+ summary := &project.UpdateInfo{
+ Status: "unknown",
+ HasUpdate: false,
+ ImageCount: imageCount,
+ ImageRefs: append([]string(nil), imageRefs...),
+ }
+
+ if imageCount == 0 {
+ return summary
+ }
+
+ var latestCheckTime *time.Time
+
+ for _, imageRef := range imageRefs {
+ info := updateInfoByRef[imageRef]
+ if info == nil {
+ continue
+ }
+
+ summary.CheckedImageCount++
+ if info.HasUpdate {
+ summary.HasUpdate = true
+ summary.ImagesWithUpdates++
+ summary.UpdatedImageRefs = append(summary.UpdatedImageRefs, imageRef)
+ }
+ if strings.TrimSpace(info.Error) != "" {
+ summary.ErrorCount++
+ if summary.ErrorMessage == nil {
+ errMsg := strings.TrimSpace(info.Error)
+ summary.ErrorMessage = &errMsg
+ }
+ }
+ if !info.CheckTime.IsZero() && (latestCheckTime == nil || info.CheckTime.After(*latestCheckTime)) {
+ checkTime := info.CheckTime
+ latestCheckTime = &checkTime
+ }
+ }
+
+ summary.LastCheckedAt = latestCheckTime
+
+ switch {
+ case summary.ImagesWithUpdates > 0:
+ summary.Status = "has_update"
+ case summary.ErrorCount > 0:
+ summary.Status = "error"
+ case summary.CheckedImageCount == imageCount:
+ summary.Status = "up_to_date"
+ default:
+ summary.Status = "unknown"
+ }
+
+ return summary
+}
+
func (s *ProjectService) enrichWithDirectoryFiles(ctx context.Context, projectPath string, resp *project.Details) {
if projectPath == "" {
return
@@ -2801,11 +3026,13 @@ func (s *ProjectService) StreamProjectLogs(ctx context.Context, projectID string
func (s *ProjectService) ListProjects(ctx context.Context, params pagination.QueryParams) ([]project.Details, pagination.Response, error) {
query := s.db.WithContext(ctx).Model(&models.Project{})
statusFilter := ""
+ updatesFilter := ""
if params.Filters != nil {
statusFilter = strings.TrimSpace(params.Filters["status"])
+ updatesFilter = strings.TrimSpace(params.Filters["updates"])
}
- if statusFilter != "" {
- return s.listProjectsByStatus(ctx, params, query)
+ if statusFilter != "" || updatesFilter != "" {
+ return s.listProjectsWithDerivedFiltersInternal(ctx, params, query)
}
if term := strings.TrimSpace(params.Search); term != "" {
@@ -2829,6 +3056,7 @@ func (s *ProjectService) ListProjects(ctx context.Context, params pagination.Que
// Fetch live status concurrently for all projects
result := s.fetchProjectStatusConcurrently(ctx, projectsArray)
+ s.enrichProjectsWithUpdateInfoInternal(ctx, projectsArray, result)
slog.DebugContext(ctx, "Completed ListProjects request",
"result_count", len(result))
@@ -2836,11 +3064,37 @@ func (s *ProjectService) ListProjects(ctx context.Context, params pagination.Que
return result, paginationResp, nil
}
-func (s *ProjectService) listProjectsByStatus(
+func (s *ProjectService) listProjectsWithDerivedFiltersInternal(
ctx context.Context,
params pagination.QueryParams,
query *gorm.DB,
) ([]project.Details, pagination.Response, error) {
+ limit := params.Limit
+ switch {
+ case limit == -1:
+ // Public API contract: exact -1 means "all" (used by the table page-size selector).
+ case limit <= 0:
+ limit = 20
+ case limit > 100:
+ limit = 100
+ }
+ params.Limit = limit
+
+ result, err := s.filterProjectsWithDerivedFiltersInternal(ctx, params, query)
+ if err != nil {
+ return nil, pagination.Response{}, err
+ }
+ paginationResp := pagination.BuildResponseFromFilterResult(result, params)
+
+ return result.Items, paginationResp, nil
+
+}
+
+func (s *ProjectService) filterProjectsWithDerivedFiltersInternal(
+ ctx context.Context,
+ params pagination.QueryParams,
+ query *gorm.DB,
+) (pagination.FilterResult[project.Details], error) {
var projectsArray []models.Project
if term := strings.TrimSpace(params.Search); term != "" {
searchPattern := "%" + term + "%"
@@ -2850,20 +3104,17 @@ func (s *ProjectService) listProjectsByStatus(
)
}
if err := query.Find(&projectsArray).Error; err != nil {
- return nil, pagination.Response{}, fmt.Errorf("failed to list projects: %w", err)
+ return pagination.FilterResult[project.Details]{}, fmt.Errorf("failed to list projects: %w", err)
}
items := s.fetchProjectStatusConcurrently(ctx, projectsArray)
+ s.enrichProjectsWithUpdateInfoInternal(ctx, projectsArray, items)
- limit := params.Limit
- if limit <= 0 {
- limit = 20
- } else if limit > 100 {
- limit = 100
- }
- params.Limit = limit
+ return pagination.SearchOrderAndPaginate(items, params, s.buildProjectDerivedPaginationConfigInternal()), nil
+}
- config := pagination.Config[project.Details]{
+func (s *ProjectService) buildProjectDerivedPaginationConfigInternal() pagination.Config[project.Details] {
+ return pagination.Config[project.Details]{
SearchAccessors: []pagination.SearchAccessor[project.Details]{
func(p project.Details) (string, error) { return p.Name, nil },
func(p project.Details) (string, error) { return p.Path, nil },
@@ -2921,19 +3172,57 @@ func (s *ProjectService) listProjectsByStatus(
},
},
FilterAccessors: []pagination.FilterAccessor[project.Details]{
- {
- Key: "status",
- Fn: func(p project.Details, filterValue string) bool {
- return strings.EqualFold(strings.TrimSpace(p.Status), strings.TrimSpace(filterValue))
- },
- },
+ s.buildProjectStatusFilterAccessorInternal(),
+ s.buildProjectUpdatesFilterAccessorInternal(),
},
}
+}
- result := pagination.SearchOrderAndPaginate(items, params, config)
- paginationResp := pagination.BuildResponseFromFilterResult(result, params)
+func (s *ProjectService) buildProjectStatusFilterAccessorInternal() pagination.FilterAccessor[project.Details] {
+ return pagination.FilterAccessor[project.Details]{
+ Key: "status",
+ Fn: func(p project.Details, filterValue string) bool {
+ return strings.EqualFold(strings.TrimSpace(p.Status), strings.TrimSpace(filterValue))
+ },
+ }
+}
- return result.Items, paginationResp, nil
+func (s *ProjectService) buildProjectUpdatesFilterAccessorInternal() pagination.FilterAccessor[project.Details] {
+ return pagination.FilterAccessor[project.Details]{
+ Key: "updates",
+ Fn: func(p project.Details, filterValue string) bool {
+ return strings.EqualFold(strings.TrimSpace(getProjectUpdateStatusInternal(p.UpdateInfo)), strings.TrimSpace(filterValue))
+ },
+ }
+}
+
+func getProjectUpdateStatusInternal(updateInfo *project.UpdateInfo) string {
+ if updateInfo == nil || strings.TrimSpace(updateInfo.Status) == "" {
+ return "unknown"
+ }
+
+ return updateInfo.Status
+}
+
+func (s *ProjectService) countProjectsByUpdateStatusInternal(ctx context.Context, status string) (int, error) {
+ if strings.TrimSpace(status) == "" {
+ return 0, nil
+ }
+
+ result, err := s.filterProjectsWithDerivedFiltersInternal(ctx, pagination.QueryParams{
+ Filters: map[string]string{
+ "updates": status,
+ },
+ PaginationParams: pagination.PaginationParams{
+ Start: 0,
+ Limit: 0,
+ },
+ }, s.db.WithContext(ctx).Model(&models.Project{}))
+ if err != nil {
+ return 0, err
+ }
+
+ return int(result.TotalCount), nil
}
// fetchProjectStatusConcurrently fetches live Docker status for multiple projects in parallel
diff --git a/backend/internal/services/project_service_test.go b/backend/internal/services/project_service_test.go
index 803271211..787a2a4ed 100644
--- a/backend/internal/services/project_service_test.go
+++ b/backend/internal/services/project_service_test.go
@@ -3,6 +3,7 @@ package services
import (
"context"
"errors"
+ "fmt"
"io"
"os"
"path/filepath"
@@ -42,7 +43,7 @@ func setupProjectTestDB(t *testing.T) *database.DB {
t.Helper()
db, err := gorm.Open(glsqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
- require.NoError(t, db.AutoMigrate(&models.Project{}, &models.SettingVariable{}))
+ require.NoError(t, db.AutoMigrate(&models.Project{}, &models.SettingVariable{}, &models.ImageUpdateRecord{}))
return &database.DB{DB: db}
}
@@ -1334,11 +1335,301 @@ func TestProjectService_GetProjectDetails_ReturnsEffectiveEnvContent(t *testing.
assert.Equal(t, "BASE=git\nTOKEN=secret\n", details.EnvContent)
}
+func TestBuildProjectUpdateInfoSummaryInternal(t *testing.T) {
+ now := time.Now().UTC()
+
+ tests := []struct {
+ name string
+ imageRefs []string
+ updates map[string]*imagetypes.UpdateInfo
+ wantStatus string
+ wantCount int
+ wantChecked int
+ wantErrors int
+ wantUpdates int
+ wantError string
+ }{
+ {
+ name: "unknown when no checks exist",
+ imageRefs: []string{"nginx:latest"},
+ updates: nil,
+ wantStatus: "unknown",
+ wantCount: 1,
+ wantChecked: 0,
+ wantErrors: 0,
+ wantUpdates: 0,
+ },
+ {
+ name: "has update when any image has update",
+ imageRefs: []string{"nginx:latest", "redis:7"},
+ updates: map[string]*imagetypes.UpdateInfo{
+ "nginx:latest": {HasUpdate: true, CheckTime: now},
+ "redis:7": {HasUpdate: false, CheckTime: now.Add(-time.Minute)},
+ },
+ wantStatus: "has_update",
+ wantCount: 2,
+ wantChecked: 2,
+ wantErrors: 0,
+ wantUpdates: 1,
+ },
+ {
+ name: "error when no updates but a check failed",
+ imageRefs: []string{"nginx:latest"},
+ updates: map[string]*imagetypes.UpdateInfo{
+ "nginx:latest": {HasUpdate: false, CheckTime: now, Error: "rate limited"},
+ },
+ wantStatus: "error",
+ wantCount: 1,
+ wantChecked: 1,
+ wantErrors: 1,
+ wantUpdates: 0,
+ wantError: "rate limited",
+ },
+ {
+ name: "up to date when all images checked without updates",
+ imageRefs: []string{"nginx:latest", "redis:7"},
+ updates: map[string]*imagetypes.UpdateInfo{
+ "nginx:latest": {HasUpdate: false, CheckTime: now},
+ "redis:7": {HasUpdate: false, CheckTime: now.Add(-time.Minute)},
+ },
+ wantStatus: "up_to_date",
+ wantCount: 2,
+ wantChecked: 2,
+ wantErrors: 0,
+ wantUpdates: 0,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ summary := buildProjectUpdateInfoSummaryInternal(tt.imageRefs, tt.updates)
+ require.NotNil(t, summary)
+ assert.Equal(t, tt.wantStatus, summary.Status)
+ assert.Equal(t, tt.wantCount, summary.ImageCount)
+ assert.Equal(t, tt.wantChecked, summary.CheckedImageCount)
+ assert.Equal(t, tt.wantErrors, summary.ErrorCount)
+ assert.Equal(t, tt.wantUpdates, summary.ImagesWithUpdates)
+ assert.Equal(t, tt.wantUpdates > 0, summary.HasUpdate)
+ assert.Equal(t, tt.imageRefs, summary.ImageRefs)
+ if tt.wantError != "" {
+ require.NotNil(t, summary.ErrorMessage)
+ assert.Equal(t, tt.wantError, *summary.ErrorMessage)
+ } else {
+ assert.Nil(t, summary.ErrorMessage)
+ }
+ if tt.wantUpdates > 0 {
+ assert.Equal(t, []string{tt.imageRefs[0]}, summary.UpdatedImageRefs)
+ } else {
+ assert.Empty(t, summary.UpdatedImageRefs)
+ }
+ })
+ }
+}
+
+func TestProjectService_GetProjectDetails_IncludesUpdateInfo(t *testing.T) {
+ db := setupProjectTestDB(t)
+ ctx := context.Background()
+
+ projectsDir := t.TempDir()
+ t.Setenv("PROJECTS_DIRECTORY", projectsDir)
+
+ settingsService, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+ require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsDir))
+
+ imageService := &ImageService{db: db}
+ svc := NewProjectService(db, settingsService, nil, imageService, nil, nil, config.Load())
+
+ projectPath := createComposeProjectDir(t, projectsDir, "updates-demo")
+ require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: nginx:latest\n"), 0o644))
+
+ projectRecord := &models.Project{
+ BaseModel: models.BaseModel{ID: "proj-update-info"},
+ Name: "updates-demo",
+ DirName: ptr("updates-demo"),
+ Path: projectPath,
+ Status: models.ProjectStatusStopped,
+ }
+ require.NoError(t, db.Create(projectRecord).Error)
+
+ require.NoError(t, db.Create(&models.ImageUpdateRecord{
+ ID: "sha256:update-demo",
+ Repository: "docker.io/library/nginx",
+ Tag: "latest",
+ HasUpdate: true,
+ UpdateType: "digest",
+ CurrentVersion: "latest",
+ CheckTime: time.Now().UTC(),
+ }).Error)
+
+ details, err := svc.GetProjectDetails(ctx, projectRecord.ID)
+ require.NoError(t, err)
+ require.NotNil(t, details.UpdateInfo)
+ assert.Equal(t, "has_update", details.UpdateInfo.Status)
+ assert.True(t, details.UpdateInfo.HasUpdate)
+ assert.Equal(t, 1, details.UpdateInfo.ImageCount)
+ assert.Equal(t, 1, details.UpdateInfo.CheckedImageCount)
+ assert.Equal(t, 1, details.UpdateInfo.ImagesWithUpdates)
+ assert.Equal(t, []string{"nginx:latest"}, details.UpdateInfo.ImageRefs)
+ assert.Equal(t, []string{"nginx:latest"}, details.UpdateInfo.UpdatedImageRefs)
+}
+
+func TestProjectService_ListProjects_FiltersByUpdateStatus(t *testing.T) {
+ db := setupProjectTestDB(t)
+ ctx := context.Background()
+
+ projectsDir := t.TempDir()
+ t.Setenv("PROJECTS_DIRECTORY", projectsDir)
+
+ settingsService, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+ require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsDir))
+
+ imageService := &ImageService{db: db}
+ svc := NewProjectService(db, settingsService, nil, imageService, nil, nil, config.Load())
+
+ updatedPath := createComposeProjectDir(t, projectsDir, "updated-demo")
+ require.NoError(t, os.WriteFile(filepath.Join(updatedPath, "compose.yaml"), []byte("services:\n app:\n image: nginx:latest\n"), 0o644))
+ upToDatePath := createComposeProjectDir(t, projectsDir, "current-demo")
+ require.NoError(t, os.WriteFile(filepath.Join(upToDatePath, "compose.yaml"), []byte("services:\n app:\n image: redis:7\n"), 0o644))
+ errorPath := createComposeProjectDir(t, projectsDir, "error-demo")
+ require.NoError(t, os.WriteFile(filepath.Join(errorPath, "compose.yaml"), []byte("services:\n app:\n image: busybox:latest\n"), 0o644))
+ unknownPath := createComposeProjectDir(t, projectsDir, "unknown-demo")
+ require.NoError(t, os.WriteFile(filepath.Join(unknownPath, "compose.yaml"), []byte("services:\n app:\n image: alpine:latest\n"), 0o644))
+
+ require.NoError(t, db.Create(&models.Project{
+ BaseModel: models.BaseModel{ID: "project-updated"},
+ Name: "updated-demo",
+ DirName: ptr("updated-demo"),
+ Path: updatedPath,
+ Status: models.ProjectStatusStopped,
+ }).Error)
+ require.NoError(t, db.Create(&models.Project{
+ BaseModel: models.BaseModel{ID: "project-current"},
+ Name: "current-demo",
+ DirName: ptr("current-demo"),
+ Path: upToDatePath,
+ Status: models.ProjectStatusStopped,
+ }).Error)
+ require.NoError(t, db.Create(&models.Project{
+ BaseModel: models.BaseModel{ID: "project-error"},
+ Name: "error-demo",
+ DirName: ptr("error-demo"),
+ Path: errorPath,
+ Status: models.ProjectStatusStopped,
+ }).Error)
+ require.NoError(t, db.Create(&models.Project{
+ BaseModel: models.BaseModel{ID: "project-unknown"},
+ Name: "unknown-demo",
+ DirName: ptr("unknown-demo"),
+ Path: unknownPath,
+ Status: models.ProjectStatusStopped,
+ }).Error)
+
+ now := time.Now().UTC()
+ require.NoError(t, db.Create(&models.ImageUpdateRecord{
+ ID: "sha256:updated-image",
+ Repository: "docker.io/library/nginx",
+ Tag: "latest",
+ HasUpdate: true,
+ UpdateType: "digest",
+ CurrentVersion: "latest",
+ CheckTime: now,
+ }).Error)
+ require.NoError(t, db.Create(&models.ImageUpdateRecord{
+ ID: "sha256:current-image",
+ Repository: "docker.io/library/redis",
+ Tag: "7",
+ HasUpdate: false,
+ UpdateType: "tag",
+ CurrentVersion: "7",
+ CheckTime: now.Add(-time.Minute),
+ }).Error)
+ require.NoError(t, db.Create(&models.ImageUpdateRecord{
+ ID: "sha256:error-image",
+ Repository: "docker.io/library/busybox",
+ Tag: "latest",
+ HasUpdate: false,
+ UpdateType: "error",
+ CurrentVersion: "latest",
+ CheckTime: now.Add(-2 * time.Minute),
+ LastError: ptr("registry timeout"),
+ }).Error)
+
+ tests := []struct {
+ name string
+ filter string
+ expected []string
+ }{
+ {name: "has update", filter: "has_update", expected: []string{"updated-demo"}},
+ {name: "up to date", filter: "up_to_date", expected: []string{"current-demo"}},
+ {name: "error", filter: "error", expected: []string{"error-demo"}},
+ {name: "unknown", filter: "unknown", expected: []string{"unknown-demo"}},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ items, page, err := svc.ListProjects(ctx, pagination.QueryParams{
+ Filters: map[string]string{
+ "updates": tt.filter,
+ },
+ PaginationParams: pagination.PaginationParams{Limit: -1},
+ SortParams: pagination.SortParams{Sort: "name", Order: pagination.SortAsc},
+ })
+ require.NoError(t, err)
+ require.EqualValues(t, len(tt.expected), page.TotalItems)
+
+ names := make([]string, 0, len(items))
+ for _, item := range items {
+ names = append(names, item.Name)
+ }
+ assert.Equal(t, tt.expected, names)
+ })
+ }
+}
+
func TestProjectService_MergeBuildTags(t *testing.T) {
tags := mergeBuildTags("example/app:latest", []string{"example/app:sha", "example/app:latest", " "})
assert.Equal(t, []string{"example/app:latest", "example/app:sha"}, tags)
}
+func TestProjectService_ListProjects_WithDerivedStatusFilter_AllowsAllPageSizeSentinel(t *testing.T) {
+ db := setupProjectTestDB(t)
+ ctx := context.Background()
+
+ settingsService, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ projectsRoot := t.TempDir()
+ require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsRoot))
+
+ for i := 0; i < 25; i++ {
+ projectPath := createComposeProjectDir(t, projectsRoot, fmt.Sprintf("stopped-%02d", i))
+ require.NoError(t, db.Create(&models.Project{
+ BaseModel: models.BaseModel{ID: fmt.Sprintf("project-%02d", i)},
+ Name: fmt.Sprintf("stopped-%02d", i),
+ DirName: ptr(fmt.Sprintf("stopped-%02d", i)),
+ Path: projectPath,
+ Status: models.ProjectStatusStopped,
+ }).Error)
+ }
+
+ svc := NewProjectService(db, settingsService, nil, nil, nil, nil, config.Load())
+
+ items, page, err := svc.ListProjects(ctx, pagination.QueryParams{
+ Filters: map[string]string{
+ "status": string(models.ProjectStatusStopped),
+ },
+ PaginationParams: pagination.PaginationParams{Limit: -1},
+ SortParams: pagination.SortParams{Sort: "name", Order: pagination.SortAsc},
+ })
+ require.NoError(t, err)
+ assert.EqualValues(t, 25, page.TotalItems)
+ require.Len(t, items, 25)
+ assert.Equal(t, "stopped-00", items[0].Name)
+ assert.Equal(t, "stopped-24", items[len(items)-1].Name)
+}
+
func TestProjectService_BuildPlatformsFromCompose(t *testing.T) {
t.Run("uses service platform when build platforms missing", func(t *testing.T) {
svc := composetypes.ServiceConfig{
diff --git a/cli/internal/integrationtest/updates_commands_test.go b/cli/internal/integrationtest/updates_commands_test.go
new file mode 100644
index 000000000..0e73f75e9
--- /dev/null
+++ b/cli/internal/integrationtest/updates_commands_test.go
@@ -0,0 +1,209 @@
+package integrationtest
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestContainersListUpdatesJSONContract(t *testing.T) {
+ seenUpdatesFilter := ""
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/environments/0/containers" {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ return
+ }
+
+ seenUpdatesFilter = r.URL.Query().Get("updates")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [
+ {
+ "id":"abc123",
+ "names":["/nginx"],
+ "image":"nginx:latest",
+ "state":"running",
+ "status":"Up 1 hour",
+ "updateInfo":{"hasUpdate":true,"latestVersion":"1.28.0"}
+ }
+ ],
+ "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
+ outBuf, errOut, err := executeCLIIntegrationCommandInternal(
+ t,
+ []string{"--config", configPath, "containers", "list", "--updates", "has_update", "--json"},
+ )
+ if err != nil {
+ t.Fatalf("execute: %v (%s)", err, errOut)
+ }
+ if seenUpdatesFilter != "has_update" {
+ t.Fatalf("expected updates filter query param, got %q", seenUpdatesFilter)
+ }
+
+ var got map[string]any
+ if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got); err != nil {
+ t.Fatalf("json parse failed: %v\noutput=%s", err, outBuf)
+ }
+ for _, key := range []string{"success", "data", "pagination"} {
+ if _, ok := got[key]; !ok {
+ t.Fatalf("missing key %q in output: %v", key, got)
+ }
+ }
+}
+
+func TestContainersUpdatesCommandUsesHasUpdateFilter(t *testing.T) {
+ seenUpdatesFilter := ""
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/environments/0/containers" {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ return
+ }
+
+ seenUpdatesFilter = r.URL.Query().Get("updates")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [
+ {
+ "id":"abc123",
+ "names":["/nginx"],
+ "image":"nginx:latest",
+ "state":"running",
+ "status":"Up 1 hour",
+ "updateInfo":{"hasUpdate":true,"latestVersion":"1.28.0"}
+ }
+ ],
+ "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
+ outBuf, errOut, err := executeCLIIntegrationCommandInternal(
+ t,
+ []string{"--config", configPath, "--output", "text", "containers", "updates"},
+ )
+ if err != nil {
+ t.Fatalf("execute: %v (%s)", err, errOut)
+ }
+ if seenUpdatesFilter != "has_update" {
+ t.Fatalf("expected updates filter query param, got %q", seenUpdatesFilter)
+ }
+ if strings.TrimSpace(outBuf) == "" {
+ t.Fatal("expected output from containers updates command")
+ }
+}
+
+func TestProjectsListUpdatesJSONContract(t *testing.T) {
+ seenUpdatesFilter := ""
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/environments/0/projects" {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ return
+ }
+
+ seenUpdatesFilter = r.URL.Query().Get("updates")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [
+ {
+ "id":"project-1",
+ "name":"demo",
+ "path":"/tmp/demo",
+ "status":"running",
+ "serviceCount":1,
+ "runningCount":1,
+ "createdAt":"2026-04-02T00:00:00Z",
+ "updatedAt":"2026-04-02T00:00:00Z",
+ "updateInfo":{"status":"has_update","hasUpdate":true,"imageCount":1,"checkedImageCount":1,"imagesWithUpdates":1,"errorCount":0}
+ }
+ ],
+ "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
+ outBuf, errOut, err := executeCLIIntegrationCommandInternal(
+ t,
+ []string{"--config", configPath, "projects", "list", "--updates", "has_update", "--json"},
+ )
+ if err != nil {
+ t.Fatalf("execute: %v (%s)", err, errOut)
+ }
+ if seenUpdatesFilter != "has_update" {
+ t.Fatalf("expected updates filter query param, got %q", seenUpdatesFilter)
+ }
+
+ var got map[string]any
+ if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got); err != nil {
+ t.Fatalf("json parse failed: %v\noutput=%s", err, outBuf)
+ }
+ for _, key := range []string{"success", "data", "pagination"} {
+ if _, ok := got[key]; !ok {
+ t.Fatalf("missing key %q in output: %v", key, got)
+ }
+ }
+}
+
+func TestProjectsUpdatesCommandUsesHasUpdateFilter(t *testing.T) {
+ seenUpdatesFilter := ""
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/environments/0/projects" {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ return
+ }
+
+ seenUpdatesFilter = r.URL.Query().Get("updates")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [
+ {
+ "id":"project-1",
+ "name":"demo",
+ "path":"/tmp/demo",
+ "status":"running",
+ "serviceCount":1,
+ "runningCount":1,
+ "createdAt":"2026-04-02T00:00:00Z",
+ "updatedAt":"2026-04-02T00:00:00Z",
+ "updateInfo":{"status":"has_update","hasUpdate":true,"imageCount":1,"checkedImageCount":1,"imagesWithUpdates":1,"errorCount":0}
+ }
+ ],
+ "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
+ outBuf, errOut, err := executeCLIIntegrationCommandInternal(
+ t,
+ []string{"--config", configPath, "--output", "text", "projects", "updates"},
+ )
+ if err != nil {
+ t.Fatalf("execute: %v (%s)", err, errOut)
+ }
+ if seenUpdatesFilter != "has_update" {
+ t.Fatalf("expected updates filter query param, got %q", seenUpdatesFilter)
+ }
+ if strings.TrimSpace(outBuf) == "" {
+ t.Fatal("expected output from projects updates command")
+ }
+}
diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.go
index 8f831cdbb..40b1ffa84 100644
--- a/cli/pkg/containers/cmd.go
+++ b/cli/pkg/containers/cmd.go
@@ -22,11 +22,12 @@ import (
)
var (
- containersLimit int
- containersStart int
- containersAll bool
- forceFlag bool
- jsonOutput bool
+ containersLimit int
+ containersStart int
+ containersAll bool
+ containersUpdatesFilter string
+ forceFlag bool
+ jsonOutput bool
containerCreateFile string
containerCreateName string
@@ -62,64 +63,148 @@ var containersListCmd = &cobra.Command{
Short: "List containers",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
+ return runContainersList(cmd, false)
+ },
+}
- path := types.Endpoints.Containers(c.EnvID())
- if containersAll {
- if cmd.Flags().Changed("limit") || cmd.Flags().Changed("start") {
- return fmt.Errorf("--all cannot be combined with explicit pagination flags")
- }
- path = fmt.Sprintf("%s?all=true", path)
- } else {
- path, err = cmdutil.ApplyPaginationParams(cmd, path, "containers", "limit", containersLimit, 20, "start", containersStart)
- if err != nil {
- return fmt.Errorf("failed to build pagination query: %w", err)
- }
- }
+var containersUpdatesCmd = &cobra.Command{
+ Use: "updates",
+ Short: "List containers with available updates",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runContainersList(cmd, true)
+ },
+}
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to list containers: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
+func runContainersList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- var result base.Paginated[container.Summary]
- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
- }
+ path, err := buildContainersListPath(cmd, c, forceHasUpdateFilter)
+ if err != nil {
+ return err
+ }
+ resp, err := c.Get(cmd.Context(), path)
+ if err != nil {
+ return fmt.Errorf("failed to list containers: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return fmt.Errorf("failed to marshal JSON: %w", err)
- }
- fmt.Println(string(resultBytes))
- return nil
+ var result base.Paginated[container.Summary]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ if jsonOutput {
+ resultBytes, err := json.MarshalIndent(result, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
}
+ fmt.Println(string(resultBytes))
+ return nil
+ }
- headers := []string{"ID", "NAME", "IMAGE", "STATE", "STATUS"}
+ effectiveUpdatesFilter := strings.TrimSpace(containersUpdatesFilter)
+ if forceHasUpdateFilter {
+ effectiveUpdatesFilter = "has_update"
+ }
+ if effectiveUpdatesFilter != "" {
+ output.Header("Container Updates")
+ headers := []string{"ID", "NAME", "IMAGE", "STATE", "UPDATES", "LATEST"}
rows := make([][]string, len(result.Data))
- for i, container := range result.Data {
- name := ""
- if len(container.Names) > 0 {
- name = strings.TrimPrefix(container.Names[0], "/")
- }
+ for i, item := range result.Data {
rows[i] = []string{
- shortID(container.ID),
- name,
- container.Image,
- container.State,
- container.Status,
+ shortID(item.ID),
+ containerSummaryName(item),
+ item.Image,
+ item.State,
+ containerUpdateStatus(item),
+ containerUpdateLatest(item),
}
}
-
output.Table(headers, rows)
output.Showing(len(result.Data), result.Pagination.TotalItems, "containers")
return nil
- },
+ }
+
+ headers := []string{"ID", "NAME", "IMAGE", "STATE", "STATUS"}
+ rows := make([][]string, len(result.Data))
+ for i, item := range result.Data {
+ rows[i] = []string{
+ shortID(item.ID),
+ containerSummaryName(item),
+ item.Image,
+ item.State,
+ item.Status,
+ }
+ }
+
+ output.Table(headers, rows)
+ output.Showing(len(result.Data), result.Pagination.TotalItems, "containers")
+ return nil
+}
+
+func buildContainersListPath(cmd *cobra.Command, c *client.Client, forceHasUpdateFilter bool) (string, error) {
+ path := types.Endpoints.Containers(c.EnvID())
+ if containersAll {
+ if cmd != nil && (cmd.Flags().Changed("limit") || cmd.Flags().Changed("start")) {
+ return "", fmt.Errorf("--all cannot be combined with explicit pagination flags")
+ }
+ } else {
+ var err error
+ path, err = cmdutil.ApplyPaginationParams(cmd, path, "containers", "limit", containersLimit, 20, "start", containersStart)
+ if err != nil {
+ return "", fmt.Errorf("failed to build pagination query: %w", err)
+ }
+ }
+
+ parsed, err := url.Parse(path)
+ if err != nil {
+ return "", fmt.Errorf("failed to parse path: %w", err)
+ }
+
+ query := parsed.Query()
+ if containersAll {
+ query.Set("all", "true")
+ }
+ updatesFilter := strings.TrimSpace(containersUpdatesFilter)
+ if forceHasUpdateFilter {
+ updatesFilter = "has_update"
+ }
+ if updatesFilter != "" {
+ query.Set("updates", updatesFilter)
+ }
+
+ parsed.RawQuery = query.Encode()
+ return parsed.String(), nil
+}
+
+func containerUpdateStatus(item container.Summary) string {
+ switch {
+ case item.UpdateInfo == nil:
+ return "unknown"
+ case item.UpdateInfo.Error != "":
+ return "error"
+ case item.UpdateInfo.HasUpdate:
+ return "has_update"
+ default:
+ return "up_to_date"
+ }
+}
+
+func containerUpdateLatest(item container.Summary) string {
+ if item.UpdateInfo == nil {
+ return "-"
+ }
+ if strings.TrimSpace(item.UpdateInfo.LatestVersion) != "" {
+ return item.UpdateInfo.LatestVersion
+ }
+ if strings.TrimSpace(item.UpdateInfo.LatestDigest) != "" {
+ return item.UpdateInfo.LatestDigest
+ }
+ return "-"
}
var containersGetCmd = &cobra.Command{
@@ -622,6 +707,7 @@ var containersCreateCmd = &cobra.Command{
func init() {
ContainersCmd.AddCommand(containersListCmd)
+ ContainersCmd.AddCommand(containersUpdatesCmd)
ContainersCmd.AddCommand(containersGetCmd)
ContainersCmd.AddCommand(containersStartCmd)
ContainersCmd.AddCommand(containersStopCmd)
@@ -656,7 +742,11 @@ func init() {
containersListCmd.Flags().IntVarP(&containersLimit, "limit", "n", 20, "Number of containers to show")
containersListCmd.Flags().IntVar(&containersStart, "start", 0, "Offset for pagination")
containersListCmd.Flags().BoolVarP(&containersAll, "all", "a", false, "Show all containers (including stopped)")
+ containersListCmd.Flags().StringVar(&containersUpdatesFilter, "updates", "", "Filter by update status (has_update, up_to_date, error, unknown)")
containersListCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ containersUpdatesCmd.Flags().IntVarP(&containersLimit, "limit", "n", 20, "Number of containers to show")
+ containersUpdatesCmd.Flags().IntVar(&containersStart, "start", 0, "Offset for pagination")
+ containersUpdatesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
// Delete command flags
containersDeleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.go
index 684a74f74..039a59073 100644
--- a/cli/pkg/projects/cmd.go
+++ b/cli/pkg/projects/cmd.go
@@ -23,10 +23,11 @@ import (
)
var (
- limitFlag int
- startFlag int
- forceFlag bool
- jsonOutput bool
+ limitFlag int
+ startFlag int
+ projectsUpdatesFilter string
+ forceFlag bool
+ jsonOutput bool
createName string
createFile string
@@ -52,54 +53,127 @@ var listCmd = &cobra.Command{
Short: "List projects",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
+ return runProjectsList(cmd, false)
+ },
+}
- path := types.Endpoints.Projects(c.EnvID())
- path, err = cmdutil.ApplyPaginationParams(cmd, path, "projects", "limit", limitFlag, 20, "start", startFlag)
- if err != nil {
- return fmt.Errorf("failed to build pagination query: %w", err)
- }
+var updatesCmd = &cobra.Command{
+ Use: "updates",
+ Short: "List projects with available updates",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runProjectsList(cmd, true)
+ },
+}
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to list projects: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
+func runProjectsList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- var result base.Paginated[project.Details]
- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
- }
+ path, err := buildProjectsListPath(cmd, c, forceHasUpdateFilter)
+ if err != nil {
+ return err
+ }
+ resp, err := c.Get(cmd.Context(), path)
+ if err != nil {
+ return fmt.Errorf("failed to list projects: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
- if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return fmt.Errorf("failed to marshal JSON: %w", err)
- }
- fmt.Println(string(resultBytes))
- return nil
+ var result base.Paginated[project.Details]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ if jsonOutput {
+ resultBytes, err := json.MarshalIndent(result, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
}
+ fmt.Println(string(resultBytes))
+ return nil
+ }
- headers := []string{"ID", "NAME", "STATUS", "SERVICES", "RUNNING", "CREATED"}
+ effectiveUpdatesFilter := strings.TrimSpace(projectsUpdatesFilter)
+ if forceHasUpdateFilter {
+ effectiveUpdatesFilter = "has_update"
+ }
+ if effectiveUpdatesFilter != "" {
+ output.Header("Project Updates")
+ headers := []string{"ID", "NAME", "STATUS", "UPDATES", "IMAGES", "UPDATED"}
rows := make([][]string, len(result.Data))
for i, proj := range result.Data {
+ imageCount := 0
+ updatedCount := 0
+ if proj.UpdateInfo != nil {
+ imageCount = proj.UpdateInfo.ImageCount
+ updatedCount = proj.UpdateInfo.ImagesWithUpdates
+ }
rows[i] = []string{
proj.ID,
proj.Name,
proj.Status,
- fmt.Sprintf("%d", proj.ServiceCount),
- fmt.Sprintf("%d", proj.RunningCount),
- proj.CreatedAt,
+ projectUpdateStatus(proj),
+ fmt.Sprintf("%d", imageCount),
+ fmt.Sprintf("%d", updatedCount),
}
}
-
output.Table(headers, rows)
output.Showing(len(result.Data), result.Pagination.TotalItems, "projects")
return nil
- },
+ }
+
+ headers := []string{"ID", "NAME", "STATUS", "SERVICES", "RUNNING", "CREATED"}
+ rows := make([][]string, len(result.Data))
+ for i, proj := range result.Data {
+ rows[i] = []string{
+ proj.ID,
+ proj.Name,
+ proj.Status,
+ fmt.Sprintf("%d", proj.ServiceCount),
+ fmt.Sprintf("%d", proj.RunningCount),
+ proj.CreatedAt,
+ }
+ }
+
+ output.Table(headers, rows)
+ output.Showing(len(result.Data), result.Pagination.TotalItems, "projects")
+ return nil
+}
+
+func buildProjectsListPath(cmd *cobra.Command, c *client.Client, forceHasUpdateFilter bool) (string, error) {
+ path := types.Endpoints.Projects(c.EnvID())
+ var err error
+ path, err = cmdutil.ApplyPaginationParams(cmd, path, "projects", "limit", limitFlag, 20, "start", startFlag)
+ if err != nil {
+ return "", fmt.Errorf("failed to build pagination query: %w", err)
+ }
+
+ parsed, err := url.Parse(path)
+ if err != nil {
+ return "", fmt.Errorf("failed to parse path: %w", err)
+ }
+
+ query := parsed.Query()
+ updatesFilter := strings.TrimSpace(projectsUpdatesFilter)
+ if forceHasUpdateFilter {
+ updatesFilter = "has_update"
+ }
+ if updatesFilter != "" {
+ query.Set("updates", updatesFilter)
+ }
+
+ parsed.RawQuery = query.Encode()
+ return parsed.String(), nil
+}
+
+func projectUpdateStatus(item project.Details) string {
+ if item.UpdateInfo == nil || strings.TrimSpace(item.UpdateInfo.Status) == "" {
+ return "unknown"
+ }
+ return item.UpdateInfo.Status
}
var destroyCmd = &cobra.Command{
@@ -576,6 +650,7 @@ var countsCmd = &cobra.Command{
func init() {
ProjectsCmd.AddCommand(listCmd)
+ ProjectsCmd.AddCommand(updatesCmd)
ProjectsCmd.AddCommand(getCmd)
ProjectsCmd.AddCommand(upCmd)
ProjectsCmd.AddCommand(downCmd)
@@ -591,7 +666,11 @@ func init() {
// List command flags
listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of projects to show")
listCmd.Flags().IntVar(&startFlag, "start", 0, "Offset for pagination")
+ listCmd.Flags().StringVar(&projectsUpdatesFilter, "updates", "", "Filter by update status (has_update, up_to_date, error, unknown)")
listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ updatesCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of projects to show")
+ updatesCmd.Flags().IntVar(&startFlag, "start", 0, "Offset for pagination")
+ updatesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
// Get command flags
getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
index 7c8f42cf5..91cfc96b3 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
@@ -24,6 +24,7 @@
selectedIds = [],
selectionDisabled = false,
bulkActions = [],
+ withoutFilters = false,
mobileFields = [],
onToggleMobileField,
customViewOptions,
@@ -35,6 +36,7 @@
selectedIds?: string[];
selectionDisabled?: boolean;
bulkActions?: BulkAction[];
+ withoutFilters?: boolean;
mobileFields?: { id: string; label: string; visible: boolean }[];
onToggleMobileField?: (fieldId: string) => void;
customViewOptions?: Snippet;
@@ -70,13 +72,14 @@
// Check if any filter columns exist
const hasFilterColumns = $derived(
- !!(typeColumn && !severityColumn && !vulnSeverityColumn) ||
- !!usageColumn ||
- !!updatesColumn ||
- !!severityColumn ||
- !!vulnSeverityColumn ||
- !!(imageNameColumn && imageNameFilterOptions.length > 0) ||
- !!(statusColumn && serviceCountColumn)
+ !withoutFilters &&
+ (!!(typeColumn && !severityColumn && !vulnSeverityColumn) ||
+ !!usageColumn ||
+ !!updatesColumn ||
+ !!severityColumn ||
+ !!vulnSeverityColumn ||
+ !!(imageNameColumn && imageNameFilterOptions.length > 0) ||
+ !!(statusColumn && serviceCountColumn))
);
const activeFilterCount = $derived(table.getState().columnFilters.length);
</script>
diff --git a/frontend/src/lib/components/arcane-table/arcane-table.svelte b/frontend/src/lib/components/arcane-table/arcane-table.svelte
index 2d9b642f9..bbadc17cb 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table.svelte
@@ -44,6 +44,7 @@
items,
requestOptions = $bindable(),
withoutSearch = $bindable(),
+ withoutFilters = false,
withoutPagination = false,
selectionDisabled = false,
unstyled = false,
@@ -74,6 +75,7 @@
items: Paginated<TData>;
requestOptions: SearchPaginationSortRequest;
withoutSearch?: boolean;
+ withoutFilters?: boolean;
withoutPagination?: boolean;
selectionDisabled?: boolean;
unstyled?: boolean;
@@ -662,6 +664,7 @@
{selectedIds}
{selectionDisabled}
{bulkActions}
+ {withoutFilters}
mobileFields={mobileFieldsForOptions}
{onToggleMobileField}
{customViewOptions}
@@ -722,6 +725,7 @@
{selectedIds}
{selectionDisabled}
{bulkActions}
+ {withoutFilters}
mobileFields={mobileFieldsForOptions}
{onToggleMobileField}
{customViewOptions}
diff --git a/frontend/src/lib/components/image-update-item.svelte b/frontend/src/lib/components/image-update-item.svelte
index 1bb73d229..9b032a8ba 100644
--- a/frontend/src/lib/components/image-update-item.svelte
+++ b/frontend/src/lib/components/image-update-item.svelte
@@ -1,5 +1,4 @@
<script lang="ts">
- import * as ArcaneTooltip from '$lib/components/arcane-tooltip';
import { Spinner } from '$lib/components/ui/spinner/index.js';
import { toast } from 'svelte-sonner';
import type { ImageUpdateData } from '$lib/types/image.type';
@@ -10,6 +9,7 @@
import type { Component } from 'svelte';
import { ArrowRightIcon, RefreshIcon, AlertIcon, VerifiedCheckIcon, ApiKeyIcon, CircleArrowUpIcon, BoxIcon } from '$lib/icons';
import { createQuery } from '@tanstack/svelte-query';
+ import UpdateStatusPopover from '$lib/components/update-status-popover.svelte';
interface Props {
updateInfo?: ImageUpdateData;
@@ -436,8 +436,8 @@
{/snippet}
{#if effectiveUpdateInfo}
- <ArcaneTooltip.Root bind:open={isOpen}>
- <ArcaneTooltip.Trigger>
+ <UpdateStatusPopover bind:open={isOpen} contentClass="max-w-[280px] p-0">
+ {#snippet trigger()}
<span class="mr-2 inline-flex size-4 items-center justify-center align-middle" data-testid="image-update-trigger">
{#if hasError}
<AlertIcon class="size-4 text-red-500" />
@@ -449,8 +449,9 @@
<CircleArrowUpIcon class="size-4 text-yellow-500" />
{/if}
</span>
- </ArcaneTooltip.Trigger>
- <ArcaneTooltip.Content side="right" class="max-w-[280px] p-0">
+ {/snippet}
+
+ {#snippet content()}
<div class="overflow-hidden rounded-xl">
{#if hasError}
{@render errorState()}
@@ -462,24 +463,25 @@
{@render versionUpdateState()}
{/if}
</div>
- </ArcaneTooltip.Content>
- </ArcaneTooltip.Root>
+ {/snippet}
+ </UpdateStatusPopover>
{:else if isLoadingInBackground || isChecking}
- <ArcaneTooltip.Root>
- <ArcaneTooltip.Trigger>
+ <UpdateStatusPopover contentClass="max-w-[220px] p-0">
+ {#snippet trigger()}
<span class="mr-2 inline-flex size-4 items-center justify-center" data-testid="image-update-trigger">
<Spinner class="size-4 text-blue-400" />
</span>
- </ArcaneTooltip.Trigger>
- <ArcaneTooltip.Content side="right" class="max-w-[220px] p-0">
+ {/snippet}
+
+ {#snippet content()}
<div class="overflow-hidden rounded-xl">
{@render loadingState()}
</div>
- </ArcaneTooltip.Content>
- </ArcaneTooltip.Root>
+ {/snippet}
+ </UpdateStatusPopover>
{:else}
- <ArcaneTooltip.Root interactive>
- <ArcaneTooltip.Trigger>
+ <UpdateStatusPopover interactive contentClass="max-w-[240px] p-0">
+ {#snippet trigger()}
<span class="mr-2 inline-flex size-4 items-center justify-center" data-testid="image-update-trigger">
{#if canCheckUpdate}
<button
@@ -499,11 +501,12 @@
</div>
{/if}
</span>
- </ArcaneTooltip.Trigger>
- <ArcaneTooltip.Content side="right" class="max-w-[240px] p-0">
+ {/snippet}
+
+ {#snippet content()}
<div class="overflow-hidden rounded-xl">
{@render unknownState()}
</div>
- </ArcaneTooltip.Content>
- </ArcaneTooltip.Root>
+ {/snippet}
+ </UpdateStatusPopover>
{/if}
diff --git a/frontend/src/lib/components/project-update-item.svelte b/frontend/src/lib/components/project-update-item.svelte
new file mode 100644
index 000000000..b851906ce
--- /dev/null
+++ b/frontend/src/lib/components/project-update-item.svelte
@@ -0,0 +1,281 @@
+<script lang="ts">
+ import type { ProjectUpdateInfo } from '$lib/types/project.type';
+ import { getProjectUpdateStatus, getProjectUpdateText } from '$lib/utils/project-update.util';
+ import { m } from '$lib/paraglide/messages';
+ import UpdateStatusPopover from '$lib/components/update-status-popover.svelte';
+ import { Spinner } from '$lib/components/ui/spinner/index.js';
+ import { AlertIcon, CircleArrowUpIcon, ClockIcon, ImagesIcon, RefreshIcon, VerifiedCheckIcon } from '$lib/icons';
+ import type { Component } from 'svelte';
+ import { format } from 'date-fns';
+
+ interface Props {
+ updateInfo?: ProjectUpdateInfo;
+ class?: string;
+ onCheck?: () => void | Promise<void>;
+ checking?: boolean;
+ }
+
+ let { updateInfo, class: className = '', onCheck, checking = false }: Props = $props();
+ let isOpen = $state(false);
+
+ const status = $derived(getProjectUpdateStatus(updateInfo));
+ const indicatorLabel = $derived(checking ? m.common_action_checking() : getProjectUpdateText(updateInfo));
+ const imageCount = $derived(updateInfo?.imageCount ?? 0);
+ const checkedImageCount = $derived(updateInfo?.checkedImageCount ?? 0);
+ const errorCount = $derived(updateInfo?.errorCount ?? 0);
+ const errorMessage = $derived(updateInfo?.errorMessage?.trim() || '');
+ const imageRefs = $derived(updateInfo?.imageRefs ?? []);
+ const updatedImageRefs = $derived(updateInfo?.updatedImageRefs ?? []);
+ const canCheck = $derived(!!onCheck && imageRefs.length > 0);
+ const directCheckFromTrigger = $derived(canCheck && (status === 'unknown' || status === 'error'));
+
+ const summaryText = $derived.by(() => {
+ if (imageCount <= 0) return null;
+ return `${checkedImageCount} / ${imageCount} ${String(m.images_title()).toLowerCase()}`;
+ });
+
+ const lastCheckedAtLabel = $derived.by(() => {
+ if (!updateInfo?.lastCheckedAt) return null;
+ const parsed = new Date(updateInfo.lastCheckedAt);
+ if (Number.isNaN(parsed.getTime())) return null;
+ return format(parsed, 'PP p');
+ });
+
+ const stateMeta = $derived.by(
+ (): {
+ icon: Component;
+ gradientFrom: string;
+ gradientTo: string;
+ shadowColor: string;
+ headerClass: string;
+ titleClass: string;
+ descriptionClass: string;
+ title: string;
+ description: string;
+ } => {
+ switch (status) {
+ case 'has_update':
+ return {
+ icon: CircleArrowUpIcon,
+ gradientFrom: 'from-blue-500',
+ gradientTo: 'to-cyan-500',
+ shadowColor: 'shadow-blue-500/25',
+ headerClass: 'bg-linear-to-br from-blue-50 to-cyan-50/30 dark:from-blue-950/20 dark:to-cyan-950/10',
+ titleClass: 'text-blue-950 dark:text-blue-100',
+ descriptionClass: 'text-blue-900/80 dark:text-blue-300/80',
+ title: m.images_has_updates(),
+ description: summaryText ?? m.images_has_updates()
+ };
+ case 'up_to_date':
+ return {
+ icon: VerifiedCheckIcon,
+ gradientFrom: 'from-emerald-500',
+ gradientTo: 'to-green-500',
+ shadowColor: 'shadow-emerald-500/25',
+ headerClass: 'bg-linear-to-br from-emerald-50 to-green-50/30 dark:from-emerald-950/20 dark:to-green-950/10',
+ titleClass: 'text-emerald-950 dark:text-emerald-100',
+ descriptionClass: 'text-emerald-900/80 dark:text-emerald-300/80',
+ title: m.image_update_up_to_date_title(),
+ description: m.image_update_up_to_date_desc()
+ };
+ case 'error':
+ return {
+ icon: AlertIcon,
+ gradientFrom: 'from-rose-500',
+ gradientTo: 'to-red-500',
+ shadowColor: 'shadow-red-500/25',
+ headerClass: 'bg-linear-to-br from-rose-50 to-red-50/40 dark:from-rose-950/20 dark:to-red-950/10',
+ titleClass: 'text-red-950 dark:text-red-100',
+ descriptionClass: 'text-red-900/80 dark:text-red-300/80',
+ title: m.image_update_check_failed_title(),
+ description: errorMessage || m.image_update_could_not_query_registry()
+ };
+ default:
+ return {
+ icon: AlertIcon,
+ gradientFrom: 'from-gray-400',
+ gradientTo: 'to-slate-500',
+ shadowColor: 'shadow-gray-400/25',
+ headerClass: 'bg-linear-to-br from-gray-50 to-slate-50/30 dark:from-gray-900/20 dark:to-slate-900/10',
+ titleClass: 'text-gray-950 dark:text-gray-100',
+ descriptionClass: 'text-gray-800 dark:text-gray-300/80',
+ title: m.image_update_status_unknown(),
+ description: m.image_update_click_to_check()
+ };
+ }
+ }
+ );
+
+ async function handleCheckClick(event?: MouseEvent) {
+ event?.preventDefault();
+ event?.stopPropagation();
+ if (!canCheck || checking) {
+ return;
+ }
+
+ isOpen = false;
+ await onCheck?.();
+ }
+</script>
+
+{#snippet iconCircle(Icon: Component, gradientFrom: string, gradientTo: string, shadowColor: string)}
+ <div
+ class="flex h-10 w-10 items-center justify-center rounded-full bg-linear-to-br {gradientFrom} {gradientTo} shadow-lg {shadowColor}"
+ >
+ <Icon class="size-5 text-white" />
+ </div>
+{/snippet}
+
+{#snippet recheckButton()}
+ {#if canCheck}
+ <div class="border-border/50 bg-muted/50 border-t p-3">
+ <button
+ onclick={handleCheckClick}
+ disabled={checking}
+ class="group bg-secondary/80 text-secondary-foreground hover:bg-secondary flex w-full items-center justify-center gap-2 rounded-lg px-3 py-2 text-xs font-medium shadow-sm transition-all hover:shadow-md disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ {#if checking}
+ <Spinner class="size-3" />
+ {m.common_action_checking()}
+ {:else}
+ <RefreshIcon class="size-3 transition-transform group-hover:rotate-45" />
+ {m.image_update_recheck_button()}
+ {/if}
+ </button>
+ </div>
+ {/if}
+{/snippet}
+
+<UpdateStatusPopover bind:open={isOpen} interactive={canCheck} contentClass="max-w-[320px] p-0">
+ {#snippet trigger()}
+ {#if checking}
+ <span
+ class="inline-flex size-4 items-center justify-center align-middle {className}"
+ aria-label={indicatorLabel}
+ data-testid="project-update-trigger"
+ >
+ <Spinner class="size-4 text-blue-400" />
+ </span>
+ {:else if directCheckFromTrigger}
+ <span
+ class="inline-flex size-4 items-center justify-center align-middle {className}"
+ aria-label={indicatorLabel}
+ data-testid="project-update-trigger"
+ >
+ <button
+ onclick={handleCheckClick}
+ disabled={checking}
+ aria-label={m.image_update_recheck_button()}
+ title={m.image_update_recheck_button()}
+ class="group flex h-4 w-4 items-center justify-center rounded-full transition-colors disabled:cursor-not-allowed dark:hover:bg-blue-950"
+ >
+ {#if status === 'error'}
+ <AlertIcon class="size-4 text-red-500 transition-colors group-hover:text-blue-400" />
+ {:else}
+ <div
+ class="flex h-4 w-4 items-center justify-center rounded-full border-2 border-dashed border-gray-400 transition-colors group-hover:border-blue-400 group-hover:bg-blue-50"
+ >
+ <div class="h-1.5 w-1.5 rounded-full bg-gray-400 transition-colors group-hover:bg-blue-400"></div>
+ </div>
+ {/if}
+ </button>
+ </span>
+ {:else}
+ <span
+ class="inline-flex size-4 items-center justify-center align-middle {className}"
+ aria-label={indicatorLabel}
+ data-testid="project-update-trigger"
+ >
+ {#if status === 'error'}
+ <AlertIcon class="size-4 text-red-500" />
+ {:else if status === 'up_to_date'}
+ <VerifiedCheckIcon class="size-4 text-green-500" />
+ {:else if status === 'has_update'}
+ <CircleArrowUpIcon class="size-4 text-blue-500" />
+ {:else}
+ <div class="flex h-4 w-4 items-center justify-center rounded-full border-2 border-dashed border-gray-400 opacity-60">
+ <div class="h-1.5 w-1.5 rounded-full bg-gray-400"></div>
+ </div>
+ {/if}
+ </span>
+ {/if}
+ {/snippet}
+
+ {#snippet content()}
+ <div class="overflow-hidden rounded-xl">
+ {#if checking}
+ <div class="bg-linear-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">
+ {@render iconCircle(Spinner, 'from-blue-500', 'to-cyan-500', 'shadow-blue-500/25')}
+ <div>
+ <div class="text-sm font-semibold text-blue-950 dark:text-blue-100">{m.image_update_checking_title()}</div>
+ <div class="text-xs text-blue-900/80 dark:text-blue-300/80">{m.image_update_querying_registry()}</div>
+ </div>
+ </div>
+ </div>
+ {:else}
+ <div class="p-4 {stateMeta.headerClass}">
+ <div class="flex items-start gap-3">
+ {@render iconCircle(stateMeta.icon, stateMeta.gradientFrom, stateMeta.gradientTo, stateMeta.shadowColor)}
+ <div class="flex-1">
+ <div class="text-sm font-semibold {stateMeta.titleClass}">{stateMeta.title}</div>
+ <div class="text-xs {stateMeta.descriptionClass}">{stateMeta.description}</div>
+ </div>
+ </div>
+ </div>
+ <div class="bg-transparent p-4">
+ <div class="space-y-3">
+ {#if summaryText}
+ <div class="text-muted-foreground flex items-center gap-2 text-xs">
+ <ImagesIcon class="size-3.5" />
+ <span>{summaryText}</span>
+ </div>
+ {/if}
+
+ {#if status === 'has_update' && updatedImageRefs.length > 0}
+ <div class="space-y-2">
+ <div class="text-foreground text-[11px] font-medium tracking-wide uppercase">{m.images_has_updates()}</div>
+ <div class="max-h-40 space-y-1 overflow-auto">
+ {#each updatedImageRefs as imageRef}
+ <div class="bg-muted text-foreground rounded-md px-2 py-1 font-mono text-xs break-all">
+ {imageRef}
+ </div>
+ {/each}
+ </div>
+ </div>
+ {:else if status === 'up_to_date'}
+ <div class="text-muted-foreground text-xs leading-relaxed">{m.image_update_up_to_date_desc()}</div>
+ {:else if status === 'error'}
+ <div class="text-muted-foreground text-xs leading-relaxed">
+ {errorMessage || m.image_update_could_not_query_registry()}
+ </div>
+ {:else}
+ <div class="text-muted-foreground text-xs leading-relaxed">
+ {#if canCheck}
+ {m.image_update_click_to_check()}
+ {:else}
+ {m.image_update_unable_check_tags()}
+ {/if}
+ </div>
+ {/if}
+
+ {#if errorCount > 0 && status !== 'error'}
+ <div class="text-muted-foreground flex items-center gap-2 text-xs">
+ <AlertIcon class="size-3.5 text-red-500" />
+ <span>{errorCount} {m.common_error()}</span>
+ </div>
+ {/if}
+
+ {#if lastCheckedAtLabel}
+ <div class="text-muted-foreground flex items-center gap-2 text-xs">
+ <ClockIcon class="size-3.5" />
+ <span>{lastCheckedAtLabel}</span>
+ </div>
+ {/if}
+ </div>
+ </div>
+ {@render recheckButton()}
+ {/if}
+ </div>
+ {/snippet}
+</UpdateStatusPopover>
diff --git a/frontend/src/lib/components/update-status-popover.svelte b/frontend/src/lib/components/update-status-popover.svelte
new file mode 100644
index 000000000..7ce0d3581
--- /dev/null
+++ b/frontend/src/lib/components/update-status-popover.svelte
@@ -0,0 +1,33 @@
+<script lang="ts">
+ import * as ArcaneTooltip from '$lib/components/arcane-tooltip';
+ import type { Snippet } from 'svelte';
+
+ type TooltipSide = 'top' | 'right' | 'bottom' | 'left';
+
+ interface Props {
+ open?: boolean;
+ interactive?: boolean;
+ side?: TooltipSide;
+ contentClass?: string;
+ trigger: Snippet;
+ content: Snippet;
+ }
+
+ let {
+ open = $bindable(false),
+ interactive = false,
+ side = 'right',
+ contentClass = 'max-w-[280px] p-0',
+ trigger,
+ content
+ }: Props = $props();
+</script>
+
+<ArcaneTooltip.Root bind:open {interactive}>
+ <ArcaneTooltip.Trigger>
+ {@render trigger()}
+ </ArcaneTooltip.Trigger>
+ <ArcaneTooltip.Content {side} class={contentClass} data-open={open ? 'true' : 'false'}>
+ {@render content()}
+ </ArcaneTooltip.Content>
+</ArcaneTooltip.Root>
diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.ts
index fd0f870ef..bc6df9567 100644
--- a/frontend/src/lib/config/navigation-config.ts
+++ b/frontend/src/lib/config/navigation-config.ts
@@ -22,7 +22,8 @@ import {
ShieldAlertIcon,
HammerIcon,
TemplateIcon,
- GlobeIcon
+ GlobeIcon,
+ UpdateIcon
} from '$lib/icons';
import { m } from '$lib/paraglide/messages';
import type { ShortcutKey } from '$lib/utils/keyboard-shortcut.utils';
@@ -54,6 +55,7 @@ export const navigationItems: NavigationSections = {
resourceItems: [
{ title: m.containers_title(), url: '/containers', icon: ContainersIcon, shortcut: ['mod', '5'] },
{ title: m.images_title(), url: '/images', icon: ImagesIcon, shortcut: ['mod', '6'] },
+ { title: m.images_updates(), url: '/updates', icon: UpdateIcon, shortcut: ['mod', 'u'] },
{
title: m.networks_title(),
url: '/networks',
diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.ts
index 68279382b..38025a2b3 100644
--- a/frontend/src/lib/query/query-keys.ts
+++ b/frontend/src/lib/query/query-keys.ts
@@ -109,6 +109,9 @@ export const queryKeys = {
all: ['projects'] as const,
list: (environmentId: string, options: SearchPaginationSortRequest) =>
['projects', environmentId, stableSerialize(options)] as const,
+ checkUpdates: (environmentId: string) => ['projects', 'check-updates', environmentId] as const,
+ detailCheckUpdates: (environmentId: string, projectId: string) =>
+ ['project', 'check-updates', environmentId, projectId] as const,
statusCounts: (environmentId: string) => ['projects', 'status-counts', environmentId] as const,
detail: (environmentId: string, projectId: string) => ['project', environmentId, projectId] as const
},
diff --git a/frontend/src/lib/services/image-service.ts b/frontend/src/lib/services/image-service.ts
index 3f8e777b2..e149d82d7 100644
--- a/frontend/src/lib/services/image-service.ts
+++ b/frontend/src/lib/services/image-service.ts
@@ -69,6 +69,24 @@ export class ImageService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/image-updates/check-all`, {}));
}
+ async checkMultipleImages(imageRefs: string[]): Promise<Record<string, ImageUpdateInfoDto>> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/image-updates/check-batch`, { imageRefs }));
+ }
+
+ async getUpdateInfoByRefs(imageRefs: string[]): Promise<Record<string, ImageUpdateInfoDto>> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ if (imageRefs.length === 0) {
+ return {};
+ }
+
+ return this.handleResponse(
+ this.api.get(`/environments/${envId}/image-updates/by-refs`, {
+ params: { imageRefs: imageRefs.join(',') }
+ })
+ );
+ }
+
async runAutoUpdate(options?: AutoUpdateCheck): Promise<AutoUpdateResult> {
const envId = await environmentStore.getCurrentEnvironmentId();
return this.handleResponse(this.api.post(`/environments/${envId}/updater/run`, options));
diff --git a/frontend/src/lib/types/project.type.ts b/frontend/src/lib/types/project.type.ts
index b89192128..6d34db2c0 100644
--- a/frontend/src/lib/types/project.type.ts
+++ b/frontend/src/lib/types/project.type.ts
@@ -64,6 +64,19 @@ export interface RuntimeService {
serviceConfig?: ProjectService;
}
+export interface ProjectUpdateInfo {
+ status: 'has_update' | 'up_to_date' | 'unknown' | 'error';
+ hasUpdate: boolean;
+ imageCount: number;
+ checkedImageCount: number;
+ imagesWithUpdates: number;
+ errorCount: number;
+ errorMessage?: string;
+ imageRefs?: string[];
+ updatedImageRefs?: string[];
+ lastCheckedAt?: string;
+}
+
export interface Project {
id: string;
name: string;
@@ -82,6 +95,7 @@ export interface Project {
lastSyncCommit?: string;
gitRepositoryURL?: string;
hasBuildDirective?: boolean;
+ updateInfo?: ProjectUpdateInfo;
services?: ProjectService[];
runtimeServices?: RuntimeService[];
composeContent?: string;
diff --git a/frontend/src/lib/utils/project-update.util.ts b/frontend/src/lib/utils/project-update.util.ts
new file mode 100644
index 000000000..2449dbaa5
--- /dev/null
+++ b/frontend/src/lib/utils/project-update.util.ts
@@ -0,0 +1,46 @@
+import { m } from '$lib/paraglide/messages';
+import type { ProjectUpdateInfo } from '$lib/types/project.type';
+
+type ProjectUpdateStatus = ProjectUpdateInfo['status'];
+export type ProjectUpdateBadgeVariant = 'blue' | 'green' | 'gray' | 'red';
+
+export function getProjectUpdateStatus(updateInfo?: ProjectUpdateInfo): ProjectUpdateStatus {
+ return updateInfo?.status ?? 'unknown';
+}
+
+export function getProjectUpdateText(updateInfo?: ProjectUpdateInfo): string {
+ switch (getProjectUpdateStatus(updateInfo)) {
+ case 'has_update':
+ return m.images_has_updates();
+ case 'up_to_date':
+ return m.image_update_up_to_date_title();
+ case 'error':
+ return m.common_error();
+ default:
+ return m.image_update_status_unknown();
+ }
+}
+
+export function getProjectUpdateVariant(updateInfo?: ProjectUpdateInfo): ProjectUpdateBadgeVariant {
+ switch (getProjectUpdateStatus(updateInfo)) {
+ case 'has_update':
+ return 'blue';
+ case 'up_to_date':
+ return 'green';
+ case 'error':
+ return 'red';
+ default:
+ return 'gray';
+ }
+}
+
+export function getProjectUpdateTooltip(updateInfo?: ProjectUpdateInfo): string | undefined {
+ switch (getProjectUpdateStatus(updateInfo)) {
+ case 'error':
+ return m.image_update_check_failed_title();
+ case 'unknown':
+ return m.image_update_click_to_check();
+ default:
+ return undefined;
+ }
+}
diff --git a/frontend/src/lib/utils/updates-filter.util.ts b/frontend/src/lib/utils/updates-filter.util.ts
new file mode 100644
index 000000000..a84074eeb
--- /dev/null
+++ b/frontend/src/lib/utils/updates-filter.util.ts
@@ -0,0 +1,24 @@
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+
+export const updatesFilter = 'has_update';
+
+export function ensureUpdatesFilter<T extends SearchPaginationSortRequest>(options: T): T {
+ return {
+ ...options,
+ filters: {
+ ...(options.filters ?? {}),
+ updates: updatesFilter
+ }
+ };
+}
+
+export function ensureStandaloneContainerUpdatesFilter<T extends SearchPaginationSortRequest>(options: T): T {
+ const next = ensureUpdatesFilter(options);
+ return {
+ ...next,
+ filters: {
+ ...(next.filters ?? {}),
+ standalone: true
+ }
+ };
+}
diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelte
index bc0e6ba2d..ea3ee2fba 100644
--- a/frontend/src/routes/(app)/containers/container-table.svelte
+++ b/frontend/src/routes/(app)/containers/container-table.svelte
@@ -61,12 +61,14 @@
selectedIds = $bindable(),
requestOptions = $bindable(),
groupByProject = $bindable(false),
+ withoutFilters = false,
onRefreshData
}: {
containers: ContainersPaginatedResponse;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
groupByProject?: boolean;
+ withoutFilters?: boolean;
onRefreshData?: (options: ContainerListRequestOptions) => Promise<ContainersPaginatedResponse>;
} = $props();
@@ -680,6 +682,7 @@
bind:mobileFieldVisibility
bind:customSettings
bind:columnVisibility
+ {withoutFilters}
onRefresh={refreshContainers}
{columns}
{mobileFields}
diff --git a/frontend/src/routes/(app)/dashboard/+page.svelte b/frontend/src/routes/(app)/dashboard/+page.svelte
index c6ef24769..185087153 100644
--- a/frontend/src/routes/(app)/dashboard/+page.svelte
+++ b/frontend/src/routes/(app)/dashboard/+page.svelte
@@ -492,7 +492,7 @@
value={imageUpdatesAttentionCount}
description={m.image_update_tag_description()}
ctaLabel={m.common_view_all()}
- href="/images"
+ href="/updates"
/>
{/if}
diff --git a/frontend/src/routes/(app)/projects/+page.svelte b/frontend/src/routes/(app)/projects/+page.svelte
index 58e89f3ee..35f6fbac6 100644
--- a/frontend/src/routes/(app)/projects/+page.svelte
+++ b/frontend/src/routes/(app)/projects/+page.svelte
@@ -40,7 +40,7 @@
}));
const checkUpdatesMutation = createMutation(() => ({
- mutationKey: ['projects', 'check-updates', envId],
+ mutationKey: queryKeys.projects.checkUpdates(envId),
mutationFn: async () => {
// Refresh update info for all images, then use the image->project usage
// map to narrow the redeploy to projects that actually have updates.
@@ -88,11 +88,11 @@
} else {
toast.success(m.compose_update_success());
}
- await projectsQuery.refetch();
+ await Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : m.containers_check_updates_failed());
- projectsQuery.refetch();
+ void Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);
}
}));
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
index c9ad19eab..76c9b2dba 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
@@ -32,12 +32,14 @@
import { IsTablet } from '$lib/hooks/is-tablet.svelte.js';
import { untrack } from 'svelte';
import { projectService } from '$lib/services/project-service';
+ import { imageService } from '$lib/services/image-service';
import { gitOpsSyncService } from '$lib/services/gitops-sync-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { queryKeys } from '$lib/query/query-keys';
import { RefreshIcon } from '$lib/icons';
import IconImage from '$lib/components/icon-image.svelte';
- import { createQuery, useQueryClient } from '@tanstack/svelte-query';
+ import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
+ import ProjectUpdateItem from '$lib/components/project-update-item.svelte';
let { data } = $props();
let projectId = $derived(data.projectId);
@@ -108,6 +110,7 @@
}
const project = $derived.by(() => withLoadedProjectFileContent(projectDetailQuery.data ?? data.project));
+ const projectImageRefs = $derived.by(() => getProjectImageRefs(project));
const serverName = $derived(project?.name ?? '');
const serverComposeContent = $derived(project?.composeContent ?? '');
const serverEnvContent = $derived(project?.envContent ?? '');
@@ -251,6 +254,28 @@
}
}
+ function getProjectImageRefs(details?: Project | null): string[] {
+ const refs = new Set<string>();
+
+ for (const service of details?.services ?? []) {
+ const imageRef = service.image?.trim();
+ if (imageRef) {
+ refs.add(imageRef);
+ }
+ }
+
+ if (refs.size === 0) {
+ for (const service of details?.runtimeServices ?? []) {
+ const imageRef = service.image?.trim();
+ if (imageRef) {
+ refs.add(imageRef);
+ }
+ }
+ }
+
+ return [...refs];
+ }
+
function rebaseEditorDraft(details: Project) {
const normalizedProject = withLoadedProjectFileContent(details);
if (!normalizedProject) return;
@@ -275,6 +300,36 @@
]);
}
+ const checkProjectUpdatesMutation = createMutation(() => ({
+ mutationKey: queryKeys.projects.detailCheckUpdates(envId ?? '0', projectId),
+ mutationFn: async () => {
+ if (projectImageRefs.length === 0) {
+ return {};
+ }
+ return imageService.checkMultipleImages(projectImageRefs);
+ },
+ onSuccess: async (results) => {
+ const currentEnvId = envId ?? (await environmentStore.getCurrentEnvironmentId());
+ const firstError = Object.values(results)
+ .find((result) => !!result?.error?.trim())
+ ?.error?.trim();
+ const hasErrors = !!firstError;
+ if (hasErrors) {
+ toast.error(firstError || m.containers_check_updates_failed());
+ } else {
+ toast.success(m.images_update_check_completed());
+ }
+ await Promise.all([
+ refreshProjectDetails(),
+ queryClient.invalidateQueries({ queryKey: ['projects', currentEnvId] }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.projects.statusCounts(currentEnvId) })
+ ]);
+ },
+ onError: () => {
+ toast.error(m.containers_check_updates_failed());
+ }
+ }));
+
$effect(() => {
if (!project?.id) return;
if (lastPrefsProjectId === project.id) return;
@@ -510,6 +565,10 @@
});
}
+ async function handleCheckProjectUpdates() {
+ await checkProjectUpdatesMutation.mutateAsync();
+ }
+
function formatUrlLabel(raw: string): string {
const trimmed = raw.trim();
if (!trimmed) return raw;
@@ -573,6 +632,11 @@
tooltip={showTooltip ? project.statusReason : undefined}
/>
{/if}
+ <ProjectUpdateItem
+ updateInfo={project.updateInfo}
+ onCheck={handleCheckProjectUpdates}
+ checking={checkProjectUpdatesMutation.isPending}
+ />
{#if project.urls && project.urls.length > 0}
<div class="flex min-w-0 flex-wrap items-center gap-2">
{#each project.urls as url, i (i)}
diff --git a/frontend/src/routes/(app)/projects/projects-table.svelte b/frontend/src/routes/(app)/projects/projects-table.svelte
index 409de8d37..bf518f15a 100644
--- a/frontend/src/routes/(app)/projects/projects-table.svelte
+++ b/frontend/src/routes/(app)/projects/projects-table.svelte
@@ -6,6 +6,7 @@
import { EditIcon, StartIcon, RestartIcon, StopIcon, TrashIcon, RedeployIcon, EllipsisIcon } from '$lib/icons';
import { Spinner } from '$lib/components/ui/spinner/index.js';
import { goto } from '$app/navigation';
+ import { toast } from 'svelte-sonner';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
import { getStatusVariant } from '$lib/utils/status.utils';
@@ -14,26 +15,37 @@
import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '$lib/components/arcane-table';
import { UniversalMobileCard } from '$lib/components/arcane-table';
import { m } from '$lib/paraglide/messages';
+ import { imageService } from '$lib/services/image-service';
import { projectService } from '$lib/services/project-service';
import { FolderOpenIcon, LayersIcon, CalendarIcon, ProjectsIcon, GitBranchIcon, RefreshIcon } from '$lib/icons';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import IconImage from '$lib/components/icon-image.svelte';
import type { ActionStatus } from './projects-table.helpers';
import { createProjectActions } from './projects-table.actions';
+ import ProjectUpdateItem from '$lib/components/project-update-item.svelte';
+ import {
+ getProjectUpdateStatus,
+ getProjectUpdateText,
+ getProjectUpdateTooltip,
+ getProjectUpdateVariant
+ } from '$lib/utils/project-update.util';
let {
projects = $bindable(),
selectedIds = $bindable(),
requestOptions = $bindable(),
+ withoutFilters = false,
onRefreshData
}: {
projects: Paginated<Project>;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
+ withoutFilters?: boolean;
onRefreshData?: (options: SearchPaginationSortRequest) => Promise<void>;
} = $props();
let actionStatus = $state<Record<string, ActionStatus>>({});
+ let checkingProjectIds = $state<Record<string, boolean>>({});
let isBulkLoading = $state({
up: false,
@@ -49,6 +61,39 @@
projects = await projectService.getProjects(options);
}
+ async function handleCheckProjectUpdates(project: Project) {
+ const imageRefs = project.updateInfo?.imageRefs ?? [];
+ if (imageRefs.length === 0 || checkingProjectIds[project.id]) {
+ return;
+ }
+
+ checkingProjectIds = {
+ ...checkingProjectIds,
+ [project.id]: true
+ };
+
+ try {
+ const results = await imageService.checkMultipleImages(imageRefs);
+ const firstError = Object.values(results)
+ .find((result) => !!result?.error?.trim())
+ ?.error?.trim();
+ const hasErrors = !!firstError;
+ if (hasErrors) {
+ toast.error(firstError || m.containers_check_updates_failed());
+ } else {
+ toast.success(m.images_update_check_completed());
+ }
+ await refreshProjects(requestOptions);
+ } catch {
+ toast.error(m.containers_check_updates_failed());
+ } finally {
+ checkingProjectIds = {
+ ...checkingProjectIds,
+ [project.id]: false
+ };
+ }
+ }
+
function getStatusTooltip(project: Project): string | undefined {
return project.status.toLowerCase() === 'unknown' && project.statusReason ? project.statusReason : undefined;
}
@@ -75,18 +120,26 @@
const columns = [
{ accessorKey: 'id', title: m.common_id(), hidden: true },
{ accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },
- { accessorKey: 'path', title: m.projects_col_directory(), sortable: true, cell: DirectoryCell },
+ { accessorKey: 'path', title: m.common_working_directory(), sortable: true, cell: DirectoryCell },
{ accessorKey: 'gitOpsManagedBy', title: m.projects_col_provider(), cell: ProviderCell },
{ accessorKey: 'status', title: m.common_status(), sortable: true, cell: StatusCell },
+ {
+ id: 'updates',
+ accessorFn: (row) => getProjectUpdateStatus(row.updateInfo),
+ title: m.containers_update_column(),
+ sortable: false,
+ cell: UpdatesCell
+ },
{ accessorKey: 'createdAt', title: m.common_created(), sortable: true, cell: CreatedCell },
{ accessorKey: 'serviceCount', title: m.compose_services(), sortable: true }
] satisfies ColumnSpec<Project>[];
const mobileFields = [
{ id: 'id', label: m.common_id(), defaultVisible: false },
- { id: 'directory', label: m.projects_col_directory(), defaultVisible: true },
+ { id: 'directory', label: m.common_working_directory(), defaultVisible: true },
{ id: 'provider', label: m.projects_col_provider(), defaultVisible: true },
{ id: 'status', label: m.common_status(), defaultVisible: true },
+ { id: 'updates', label: m.containers_update_column(), defaultVisible: true },
{ id: 'serviceCount', label: m.compose_services(), defaultVisible: true },
{ id: 'createdAt', label: m.common_created(), defaultVisible: true }
];
@@ -163,16 +216,23 @@
/>
{/snippet}
+{#snippet UpdatesCell({ item }: { item: Project })}
+ <ProjectUpdateItem
+ updateInfo={item.updateInfo}
+ onCheck={() => handleCheckProjectUpdates(item)}
+ checking={!!checkingProjectIds[item.id]}
+ class="mr-2"
+ />
+{/snippet}
+
{#snippet CreatedCell({ value }: { value: unknown })}
{#if value}{format(new Date(String(value)), 'PP p')}{/if}
{/snippet}
{#snippet ProjectMobileCardSnippet({
- row,
item,
mobileFieldVisibility
}: {
- row: any;
item: Project;
mobileFieldVisibility: MobileFieldVisibility;
})}
@@ -185,24 +245,32 @@
alt: item.name
})}
title={(item: Project) => item.name}
- subtitle={(item: Project) => ((mobileFieldVisibility.id ?? true) ? item.id : null)}
+ subtitle={(item: Project) => ((mobileFieldVisibility['id'] ?? true) ? item.id : null)}
badges={[
(item: Project) =>
- (mobileFieldVisibility.status ?? true)
+ (mobileFieldVisibility['status'] ?? true)
? {
variant: getStatusVariant(item.status),
text: capitalizeFirstLetter(item.status),
tooltip: getStatusTooltip(item)
}
+ : null,
+ (item: Project) =>
+ (mobileFieldVisibility['updates'] ?? true)
+ ? {
+ variant: getProjectUpdateVariant(item.updateInfo),
+ text: getProjectUpdateText(item.updateInfo),
+ tooltip: getProjectUpdateTooltip(item.updateInfo)
+ }
: null
]}
fields={[
{
- label: m.projects_col_directory(),
+ label: m.common_working_directory(),
getValue: (item: Project) => item.relativePath ?? item.dirName ?? item.path,
icon: FolderOpenIcon,
iconVariant: 'gray' as const,
- show: mobileFieldVisibility.directory ?? true
+ show: mobileFieldVisibility['directory'] ?? true
},
{
label: m.projects_col_provider(),
@@ -212,7 +280,7 @@
text: item.gitOpsManagedBy ? m.projects_provider_git() : m.projects_provider_local()
}),
component: ProviderField,
- show: mobileFieldVisibility.provider ?? true
+ show: mobileFieldVisibility['provider'] ?? true
},
{
label: m.compose_services(),
@@ -222,10 +290,10 @@
},
icon: LayersIcon,
iconVariant: 'gray' as const,
- show: mobileFieldVisibility.serviceCount ?? true
+ show: mobileFieldVisibility['serviceCount'] ?? true
}
]}
- footer={(mobileFieldVisibility.createdAt ?? true) && item.createdAt
+ footer={(mobileFieldVisibility['createdAt'] ?? true) && item.createdAt
? {
label: m.common_created(),
getValue: (item: Project) => format(new Date(item.createdAt), 'PP p'),
@@ -346,6 +414,7 @@
bind:requestOptions
bind:selectedIds
bind:mobileFieldVisibility
+ {withoutFilters}
onRefresh={async (options) => {
requestOptions = options;
await refreshProjects(options);
diff --git a/frontend/src/routes/(app)/updates/+page.svelte b/frontend/src/routes/(app)/updates/+page.svelte
new file mode 100644
index 000000000..34d9039ca
--- /dev/null
+++ b/frontend/src/routes/(app)/updates/+page.svelte
@@ -0,0 +1,251 @@
+<script lang="ts">
+ import { createMutation, createQuery } from '@tanstack/svelte-query';
+ import { untrack } from 'svelte';
+ import { m } from '$lib/paraglide/messages';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { queryKeys } from '$lib/query/query-keys';
+ import * as Tabs from '$lib/components/ui/tabs/index.js';
+ import { TabBar, type TabItem } from '$lib/components/tab-bar';
+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
+ import ContainerUpdatesTable from './container-updates-table.svelte';
+ import ProjectUpdatesTable from './project-updates-table.svelte';
+ import { imageService } from '$lib/services/image-service';
+ import { containerService, type ContainerListRequestOptions } from '$lib/services/container-service';
+ import { projectService } from '$lib/services/project-service';
+ import type { ContainersPaginatedResponse } from '$lib/services/container-service';
+ import type { ImageUpdateInfoDto } from '$lib/types/image.type';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import type { Project } from '$lib/types/project.type';
+ import { ContainersIcon, ProjectsIcon, UpdateIcon } from '$lib/icons';
+ import { toast } from 'svelte-sonner';
+ import { ensureStandaloneContainerUpdatesFilter, ensureUpdatesFilter } from '$lib/utils/updates-filter.util';
+
+ let { data } = $props();
+
+ const initialContainers = untrack(() => data.containers as ContainersPaginatedResponse);
+ const initialProjects = untrack(() => data.projects as Paginated<Project>);
+ const emptyContainers = untrack(
+ () =>
+ ({
+ ...initialContainers,
+ data: [],
+ counts: undefined,
+ groups: [],
+ pagination: {
+ ...initialContainers.pagination,
+ totalItems: 0,
+ totalPages: 0,
+ currentPage: 1
+ }
+ }) satisfies ContainersPaginatedResponse
+ );
+ const emptyProjects = untrack(
+ () =>
+ ({
+ ...initialProjects,
+ data: [],
+ counts: undefined,
+ pagination: {
+ ...initialProjects.pagination,
+ totalItems: 0,
+ totalPages: 0,
+ currentPage: 1
+ }
+ }) satisfies Paginated<Project>
+ );
+
+ let containerSnapshot = $state<{ envId: string; value: ContainersPaginatedResponse } | null>(null);
+ let projectSnapshot = $state<{ envId: string; value: Paginated<Project> } | null>(null);
+ let containerRequestOptions = $state(untrack(() => data.containerRequestOptions as ContainerListRequestOptions));
+ let projectRequestOptions = $state(untrack(() => data.projectRequestOptions as SearchPaginationSortRequest));
+ let activeTab = $state<'containers' | 'projects'>(
+ untrack(() =>
+ (data.containers.pagination?.totalItems ?? 0) > 0 || (data.projects.pagination?.totalItems ?? 0) === 0
+ ? 'containers'
+ : 'projects'
+ )
+ );
+ const envId = $derived(environmentStore.selected?.id || '0');
+ const containers = $derived(
+ (containerSnapshot?.envId === envId ? containerSnapshot.value : null) ??
+ containersQuery.data ??
+ (envId === data.envId ? initialContainers : emptyContainers)
+ );
+ const projects = $derived(
+ (projectSnapshot?.envId === envId ? projectSnapshot.value : null) ??
+ projectsQuery.data ??
+ (envId === data.envId ? initialProjects : emptyProjects)
+ );
+
+ const containersQuery = createQuery(() => ({
+ queryKey: queryKeys.containers.list(envId, ensureStandaloneContainerUpdatesFilter(containerRequestOptions)),
+ queryFn: () =>
+ containerService.getContainersForEnvironment(envId, ensureStandaloneContainerUpdatesFilter(containerRequestOptions)),
+ initialData: envId === data.envId ? data.containers : undefined,
+ refetchOnMount: false
+ }));
+
+ const projectsQuery = createQuery(() => ({
+ queryKey: queryKeys.projects.list(envId, ensureUpdatesFilter(projectRequestOptions)),
+ queryFn: () => projectService.getProjectsForEnvironment(envId, ensureUpdatesFilter(projectRequestOptions)),
+ initialData: envId === data.envId ? data.projects : undefined,
+ refetchOnMount: false
+ }));
+
+ const projectUpdatedImageRefs = $derived.by(() => {
+ const refs = new Set<string>();
+ for (const project of projects.data ?? []) {
+ for (const imageRef of project.updateInfo?.updatedImageRefs ?? []) {
+ refs.add(imageRef);
+ }
+ }
+ return Array.from(refs).sort();
+ });
+
+ const projectUpdateDetailsQuery = createQuery<Record<string, ImageUpdateInfoDto>>(() => ({
+ queryKey: ['updates', 'projects', 'details', envId, projectUpdatedImageRefs],
+ queryFn: () =>
+ projectUpdatedImageRefs.length > 0 ? imageService.getUpdateInfoByRefs(projectUpdatedImageRefs) : Promise.resolve({}),
+ initialData: {},
+ enabled: projectUpdatedImageRefs.length > 0,
+ refetchOnMount: false
+ }));
+
+ const checkUpdatesMutation = createMutation(() => ({
+ mutationKey: ['updates', 'check-all', envId],
+ mutationFn: () => imageService.checkAllImages(),
+ onSuccess: async () => {
+ toast.success(m.images_update_check_completed());
+ await Promise.all([containersQuery.refetch(), projectsQuery.refetch()]);
+ if (projectUpdatedImageRefs.length > 0) {
+ await projectUpdateDetailsQuery.refetch();
+ }
+ },
+ onError: () => {
+ toast.error(m.images_update_check_failed());
+ }
+ }));
+
+ const isRefreshing = $derived(
+ (containersQuery.isFetching && !containersQuery.isPending) || (projectsQuery.isFetching && !projectsQuery.isPending)
+ );
+ const isChecking = $derived(checkUpdatesMutation.isPending);
+ const containerCount = $derived(containers.pagination?.totalItems ?? 0);
+ const projectCount = $derived(projects.pagination?.totalItems ?? 0);
+ const totalAffectedResources = $derived(containerCount + projectCount);
+ const tabItems: TabItem[] = $derived([
+ {
+ value: 'containers',
+ label: m.containers_title(),
+ icon: ContainersIcon
+ },
+ {
+ value: 'projects',
+ label: m.projects_title(),
+ icon: ProjectsIcon
+ }
+ ]);
+ const effectiveTab = $derived(
+ activeTab === 'containers' && containerCount === 0 && projectCount > 0
+ ? 'projects'
+ : activeTab === 'projects' && projectCount === 0 && containerCount > 0
+ ? 'containers'
+ : activeTab
+ );
+
+ async function refresh() {
+ containerSnapshot = null;
+ projectSnapshot = null;
+ await Promise.all([containersQuery.refetch(), projectsQuery.refetch()]);
+ if (projectUpdatedImageRefs.length > 0) {
+ await projectUpdateDetailsQuery.refetch();
+ }
+ }
+
+ function handleTabChange(value: string) {
+ activeTab = value === 'projects' ? 'projects' : 'containers';
+ }
+
+ const actionButtons: ActionButton[] = $derived([
+ {
+ id: 'check-updates',
+ action: 'inspect',
+ label: m.images_check_updates(),
+ loadingLabel: m.common_action_checking(),
+ onclick: () => checkUpdatesMutation.mutate(),
+ loading: isChecking,
+ disabled: isChecking
+ },
+ {
+ id: 'refresh',
+ action: 'restart',
+ label: m.common_refresh(),
+ onclick: refresh,
+ loading: isRefreshing,
+ disabled: isRefreshing
+ }
+ ]);
+
+ const statCards: StatCardConfig[] = $derived([
+ {
+ title: m.common_total(),
+ value: totalAffectedResources,
+ icon: UpdateIcon,
+ iconColor: 'text-blue-500'
+ },
+ {
+ title: m.containers_title(),
+ value: containerCount,
+ icon: ContainersIcon,
+ iconColor: 'text-emerald-500'
+ },
+ {
+ title: m.projects_title(),
+ value: projects.pagination?.totalItems ?? 0,
+ icon: ProjectsIcon,
+ iconColor: 'text-amber-500'
+ }
+ ]);
+</script>
+
+<ResourcePageLayout title={m.images_updates()} icon={UpdateIcon} {actionButtons} {statCards}>
+ {#snippet mainContent()}
+ <div class="space-y-6">
+ <Tabs.Root value={effectiveTab}>
+ <TabBar items={tabItems} value={effectiveTab} onValueChange={handleTabChange} />
+
+ <Tabs.Content value="containers" class="mt-4">
+ {#key `${envId}-containers`}
+ <ContainerUpdatesTable
+ bind:containers={() => containers, (value) => (containerSnapshot = { envId, value })}
+ bind:requestOptions={containerRequestOptions}
+ onRefreshData={async (options) => {
+ containerRequestOptions = ensureStandaloneContainerUpdatesFilter(options);
+ const next = await containerService.getContainersForEnvironment(envId, containerRequestOptions);
+ containerSnapshot = { envId, value: next };
+ return next;
+ }}
+ />
+ {/key}
+ </Tabs.Content>
+
+ <Tabs.Content value="projects" class="mt-4">
+ {#key `${envId}-projects`}
+ <ProjectUpdatesTable
+ bind:projects={() => projects, (value) => (projectSnapshot = { envId, value })}
+ bind:requestOptions={projectRequestOptions}
+ updateInfoByRef={projectUpdateDetailsQuery.data}
+ onRefreshData={async (options) => {
+ projectRequestOptions = ensureUpdatesFilter(options);
+ projectSnapshot = {
+ envId,
+ value: await projectService.getProjectsForEnvironment(envId, projectRequestOptions)
+ };
+ }}
+ />
+ {/key}
+ </Tabs.Content>
+ </Tabs.Root>
+ </div>
+ {/snippet}
+</ResourcePageLayout>
diff --git a/frontend/src/routes/(app)/updates/+page.ts b/frontend/src/routes/(app)/updates/+page.ts
new file mode 100644
index 000000000..fe1d94a5e
--- /dev/null
+++ b/frontend/src/routes/(app)/updates/+page.ts
@@ -0,0 +1,53 @@
+import { containerService, type ContainerListRequestOptions } from '$lib/services/container-service';
+import { projectService } from '$lib/services/project-service';
+import { queryKeys } from '$lib/query/query-keys';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';
+import { throwPageLoadError } from '$lib/utils/page-load-error.util';
+import { ensureStandaloneContainerUpdatesFilter, ensureUpdatesFilter } from '$lib/utils/updates-filter.util';
+import type { PageLoad } from './$types';
+import { environmentStore } from '$lib/stores/environment.store.svelte';
+
+export const load: PageLoad = async ({ parent }) => {
+ const { queryClient } = await parent();
+ const envId = await environmentStore.getCurrentEnvironmentId();
+
+ const containerRequestOptions = ensureStandaloneContainerUpdatesFilter(
+ resolveInitialTableRequest('arcane-updates-container-table', {
+ pagination: { page: 1, limit: 100 },
+ sort: { column: 'created', direction: 'desc' }
+ } satisfies SearchPaginationSortRequest)
+ ) as ContainerListRequestOptions;
+
+ const projectRequestOptions = ensureUpdatesFilter(
+ resolveInitialTableRequest('arcane-updates-project-table', {
+ pagination: { page: 1, limit: 20 },
+ sort: { column: 'name', direction: 'asc' }
+ } satisfies SearchPaginationSortRequest)
+ );
+
+ let containers;
+ let projects;
+ try {
+ [containers, projects] = await Promise.all([
+ queryClient.fetchQuery({
+ queryKey: queryKeys.containers.list(envId, containerRequestOptions),
+ queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)
+ }),
+ queryClient.fetchQuery({
+ queryKey: queryKeys.projects.list(envId, projectRequestOptions),
+ queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions)
+ })
+ ]);
+ } catch (err) {
+ throwPageLoadError(err, 'Failed to load updates');
+ }
+
+ return {
+ envId,
+ containers,
+ projects,
+ containerRequestOptions,
+ projectRequestOptions
+ };
+};
diff --git a/frontend/src/routes/(app)/updates/container-updates-table.svelte b/frontend/src/routes/(app)/updates/container-updates-table.svelte
new file mode 100644
index 000000000..5faa955a2
--- /dev/null
+++ b/frontend/src/routes/(app)/updates/container-updates-table.svelte
@@ -0,0 +1,226 @@
+<script lang="ts">
+ import { format } from 'date-fns';
+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import { UniversalMobileCard, type ColumnSpec, type MobileFieldVisibility } from '$lib/components/arcane-table';
+ import { m } from '$lib/paraglide/messages';
+ import { toast } from 'svelte-sonner';
+ import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
+ import type { ContainerSummaryDto } from '$lib/types/container.type';
+ import type { ImageUpdateInfoDto } from '$lib/types/image.type';
+ import {
+ containerService,
+ type ContainersPaginatedResponse,
+ type ContainerListRequestOptions
+ } from '$lib/services/container-service';
+ import { ContainersIcon, UpdateIcon } from '$lib/icons';
+ import { getContainerDisplayName } from '../containers/container-table.helpers';
+
+ type ContainerUpdateRow = {
+ id: string;
+ containerId: string;
+ name: string;
+ imageRef: string;
+ currentValue: string;
+ latestValue: string;
+ checkedAt: string;
+ updateInfo?: ImageUpdateInfoDto;
+ container: ContainerSummaryDto;
+ };
+
+ interface Props {
+ containers: ContainersPaginatedResponse;
+ requestOptions: SearchPaginationSortRequest;
+ onRefreshData: (options: ContainerListRequestOptions) => Promise<ContainersPaginatedResponse>;
+ }
+
+ let { containers = $bindable(), requestOptions = $bindable(), onRefreshData }: Props = $props();
+
+ let selectedIds = $state<string[]>([]);
+ let mobileFieldVisibility = $state<MobileFieldVisibility>({});
+ let updatingContainerIds = $state<Record<string, boolean>>({});
+
+ function formatUpdateValue(updateInfo: ImageUpdateInfoDto | undefined, mode: 'current' | 'latest') {
+ if (!updateInfo) return '-';
+
+ const digest = mode === 'current' ? updateInfo.currentDigest : updateInfo.latestDigest;
+ if (digest?.trim()) return digest.trim();
+
+ const version = mode === 'current' ? updateInfo.currentVersion : updateInfo.latestVersion;
+ if (version?.trim()) return version.trim();
+
+ return '-';
+ }
+
+ function formatCheckedAt(value: string) {
+ if (!value) return '-';
+ const parsed = new Date(value);
+ if (Number.isNaN(parsed.getTime())) return '-';
+ return format(parsed, 'PP p');
+ }
+
+ function mapContainerRow(container: ContainerSummaryDto): ContainerUpdateRow {
+ return {
+ id: container.id,
+ containerId: container.id,
+ name: getContainerDisplayName(container),
+ imageRef: container.image,
+ currentValue: formatUpdateValue(container.updateInfo, 'current'),
+ latestValue: formatUpdateValue(container.updateInfo, 'latest'),
+ checkedAt: container.updateInfo?.checkTime ?? '',
+ updateInfo: container.updateInfo,
+ container
+ };
+ }
+
+ const tableItems = $derived<Paginated<ContainerUpdateRow, ContainersPaginatedResponse['counts']>>({
+ ...containers,
+ data: (containers.data ?? []).map(mapContainerRow)
+ });
+
+ const columns = [
+ { accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },
+ { accessorKey: 'imageRef', title: m.common_image(), sortable: true, cell: ImageCell },
+ { accessorKey: 'currentValue', title: m.image_update_current_label(), sortable: false, cell: DigestCell },
+ { accessorKey: 'latestValue', title: m.image_update_latest_digest_label(), sortable: false, cell: DigestCell },
+ { accessorKey: 'checkedAt', title: m.common_updated(), sortable: false, cell: CheckedAtCell },
+ { id: 'actions', title: m.common_actions(), sortable: false, cell: ActionsCell }
+ ] satisfies ColumnSpec<ContainerUpdateRow>[];
+
+ const mobileFields = [
+ { id: 'imageRef', label: m.common_image(), defaultVisible: true },
+ { id: 'currentValue', label: m.image_update_current_label(), defaultVisible: true },
+ { id: 'latestValue', label: m.image_update_latest_digest_label(), defaultVisible: true },
+ { id: 'checkedAt', label: m.common_updated(), defaultVisible: true },
+ { id: 'actions', label: m.common_actions(), defaultVisible: true }
+ ];
+
+ async function handleUpdateContainer(container: ContainerSummaryDto) {
+ const containerName = getContainerDisplayName(container);
+
+ openConfirmDialog({
+ title: m.containers_update_confirm_title(),
+ message: m.containers_update_confirm_message({ name: containerName }),
+ confirm: {
+ label: m.containers_update_container(),
+ destructive: false,
+ action: async () => {
+ updatingContainerIds = { ...updatingContainerIds, [container.id]: true };
+ try {
+ toast.info(m.containers_update_pulling_image());
+
+ const result = await containerService.updateContainer(container.id);
+
+ if (result.failed > 0) {
+ const failedItem = result.items?.find((item: { status?: string; error?: string }) => item.status === 'failed');
+ toast.error(
+ m.containers_update_failed({ name: containerName }) + (failedItem?.error ? `: ${failedItem.error}` : '')
+ );
+ } else if (result.updated > 0) {
+ toast.success(m.containers_update_success({ name: containerName }));
+ } else {
+ toast.info(m.image_update_up_to_date_title());
+ }
+
+ const next = await onRefreshData(requestOptions as ContainerListRequestOptions);
+ containers = next;
+ } catch (error) {
+ console.error('Container update failed:', error);
+ toast.error(m.containers_update_failed({ name: containerName }));
+ } finally {
+ updatingContainerIds = { ...updatingContainerIds, [container.id]: false };
+ }
+ }
+ }
+ });
+ }
+</script>
+
+{#snippet NameCell({ item }: { item: ContainerUpdateRow })}
+ <a class="font-medium hover:underline" href={`/containers/${item.containerId}`}>
+ {item.name}
+ </a>
+{/snippet}
+
+{#snippet ImageCell({ item }: { item: ContainerUpdateRow })}
+ <code class="text-xs">{item.imageRef}</code>
+{/snippet}
+
+{#snippet DigestCell({ value }: { value: unknown })}
+ {@const text = typeof value === 'string' ? value : '-'}
+ <span class="font-mono text-xs break-all whitespace-normal" title={text !== '-' ? text : undefined}>
+ {text}
+ </span>
+{/snippet}
+
+{#snippet CheckedAtCell({ value }: { value: unknown })}
+ <span class="text-sm">{formatCheckedAt(typeof value === 'string' ? value : '')}</span>
+{/snippet}
+
+{#snippet ActionsCell({ item }: { item: ContainerUpdateRow })}
+ <ArcaneButton
+ action="update"
+ size="sm"
+ customLabel={m.containers_update_container()}
+ onclick={() => handleUpdateContainer(item.container)}
+ loading={!!updatingContainerIds[item.containerId]}
+ disabled={!!updatingContainerIds[item.containerId]}
+ icon={UpdateIcon}
+ />
+{/snippet}
+
+{#snippet ContainerUpdatesMobileCard({ item }: { item: ContainerUpdateRow })}
+ <UniversalMobileCard
+ {item}
+ icon={() => ({
+ component: ContainersIcon,
+ variant: 'blue' as const
+ })}
+ title={(item: ContainerUpdateRow) => item.name}
+ subtitle={(item: ContainerUpdateRow) => item.imageRef}
+ fields={[
+ {
+ label: m.image_update_current_label(),
+ getValue: (item: ContainerUpdateRow) => item.currentValue
+ },
+ {
+ label: m.image_update_latest_digest_label(),
+ getValue: (item: ContainerUpdateRow) => item.latestValue
+ },
+ {
+ label: m.common_updated(),
+ getValue: (item: ContainerUpdateRow) => formatCheckedAt(item.checkedAt)
+ },
+ {
+ label: m.common_actions(),
+ getValue: () => m.containers_update_container()
+ }
+ ]}
+ onclick={(item: ContainerUpdateRow) => {
+ window.location.href = `/containers/${item.containerId}`;
+ }}
+ />
+{/snippet}
+
+<ArcaneTable
+ persistKey="arcane-updates-container-table"
+ items={tableItems}
+ bind:requestOptions
+ bind:selectedIds
+ bind:mobileFieldVisibility
+ onRefresh={async (options) => {
+ requestOptions = options;
+ const next = await onRefreshData(options as ContainerListRequestOptions);
+ containers = next;
+ return {
+ ...next,
+ data: (next.data ?? []).map(mapContainerRow)
+ };
+ }}
+ {columns}
+ {mobileFields}
+ mobileCard={ContainerUpdatesMobileCard}
+ withoutFilters
+ selectionDisabled
+/>
diff --git a/frontend/src/routes/(app)/updates/project-updates-table.svelte b/frontend/src/routes/(app)/updates/project-updates-table.svelte
new file mode 100644
index 000000000..6ea23e69f
--- /dev/null
+++ b/frontend/src/routes/(app)/updates/project-updates-table.svelte
@@ -0,0 +1,183 @@
+<script lang="ts">
+ import { format } from 'date-fns';
+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';
+ import { UniversalMobileCard, type ColumnSpec, type MobileFieldVisibility } from '$lib/components/arcane-table';
+ import { m } from '$lib/paraglide/messages';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import type { Project } from '$lib/types/project.type';
+ import type { ImageUpdateInfoDto } from '$lib/types/image.type';
+ import { ProjectsIcon, ImagesIcon } from '$lib/icons';
+
+ type ProjectUpdateRow = {
+ id: string;
+ projectId: string;
+ name: string;
+ imageSummary: string;
+ currentValue: string;
+ latestValue: string;
+ checkedAt: string;
+ project: Project;
+ };
+
+ interface Props {
+ projects: Paginated<Project>;
+ requestOptions: SearchPaginationSortRequest;
+ updateInfoByRef?: Record<string, ImageUpdateInfoDto>;
+ onRefreshData: (options: SearchPaginationSortRequest) => Promise<void>;
+ }
+
+ let { projects = $bindable(), requestOptions = $bindable(), updateInfoByRef = {}, onRefreshData }: Props = $props();
+
+ let selectedIds = $state<string[]>([]);
+ let mobileFieldVisibility = $state<MobileFieldVisibility>({});
+
+ function formatCheckedAt(value: string) {
+ if (!value) return '-';
+ const parsed = new Date(value);
+ if (Number.isNaN(parsed.getTime())) return '-';
+ return format(parsed, 'PP p');
+ }
+
+ function summarizeImageRefs(imageRefs: string[]) {
+ if (imageRefs.length === 0) return '-';
+ if (imageRefs.length === 1) return imageRefs[0];
+ return `${imageRefs[0]} +${imageRefs.length - 1} more`;
+ }
+
+ function resolveProjectValue(project: Project, mode: 'current' | 'latest') {
+ const updatedRefs = project.updateInfo?.updatedImageRefs ?? [];
+ if (updatedRefs.length === 0) return '-';
+ if (updatedRefs.length > 1) {
+ return m.images_has_updates();
+ }
+
+ const info = updateInfoByRef[updatedRefs[0]];
+ if (!info) return '-';
+
+ const digest = mode === 'current' ? info.currentDigest : info.latestDigest;
+ if (digest?.trim()) return digest.trim();
+
+ const version = mode === 'current' ? info.currentVersion : info.latestVersion;
+ if (version?.trim()) return version.trim();
+
+ return '-';
+ }
+
+ function resolveCheckedAt(project: Project) {
+ const updatedRefs = project.updateInfo?.updatedImageRefs ?? [];
+ if (updatedRefs.length === 1) {
+ return updateInfoByRef[updatedRefs[0]]?.checkTime ?? project.updateInfo?.lastCheckedAt ?? '';
+ }
+ return project.updateInfo?.lastCheckedAt ?? '';
+ }
+
+ function mapProjectRow(project: Project): ProjectUpdateRow {
+ const updatedRefs = project.updateInfo?.updatedImageRefs ?? project.updateInfo?.imageRefs ?? [];
+ return {
+ id: project.id,
+ projectId: project.id,
+ name: project.name,
+ imageSummary: summarizeImageRefs(updatedRefs),
+ currentValue: resolveProjectValue(project, 'current'),
+ latestValue: resolveProjectValue(project, 'latest'),
+ checkedAt: resolveCheckedAt(project),
+ project
+ };
+ }
+
+ const tableItems = $derived<Paginated<ProjectUpdateRow>>({
+ ...projects,
+ data: (projects.data ?? []).map(mapProjectRow)
+ });
+
+ const columns = [
+ { accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },
+ { accessorKey: 'imageSummary', title: m.common_image(), sortable: false, cell: ImageCell },
+ { accessorKey: 'currentValue', title: m.image_update_current_label(), sortable: false, cell: DigestCell },
+ { accessorKey: 'latestValue', title: m.image_update_latest_digest_label(), sortable: false, cell: DigestCell },
+ { accessorKey: 'checkedAt', title: m.common_updated(), sortable: false, cell: CheckedAtCell }
+ ] satisfies ColumnSpec<ProjectUpdateRow>[];
+
+ const mobileFields = [
+ { id: 'imageSummary', label: m.common_image(), defaultVisible: true },
+ { id: 'currentValue', label: m.image_update_current_label(), defaultVisible: true },
+ { id: 'latestValue', label: m.image_update_latest_digest_label(), defaultVisible: true },
+ { id: 'checkedAt', label: m.common_updated(), defaultVisible: true }
+ ];
+</script>
+
+{#snippet NameCell({ item }: { item: ProjectUpdateRow })}
+ <a class="font-medium hover:underline" href={`/projects/${item.projectId}`}>
+ {item.name}
+ </a>
+{/snippet}
+
+{#snippet ImageCell({ item }: { item: ProjectUpdateRow })}
+ <div class="flex items-center gap-2">
+ <ImagesIcon class="text-muted-foreground size-3.5 shrink-0" />
+ <span class="truncate text-sm" title={item.imageSummary !== '-' ? item.imageSummary : undefined}>
+ {item.imageSummary}
+ </span>
+ </div>
+{/snippet}
+
+{#snippet DigestCell({ value }: { value: unknown })}
+ {@const text = typeof value === 'string' ? value : '-'}
+ <span class="font-mono text-xs break-all whitespace-normal" title={text !== '-' ? text : undefined}>
+ {text}
+ </span>
+{/snippet}
+
+{#snippet CheckedAtCell({ value }: { value: unknown })}
+ <span class="text-sm">{formatCheckedAt(typeof value === 'string' ? value : '')}</span>
+{/snippet}
+
+{#snippet ProjectUpdatesMobileCard({ item }: { item: ProjectUpdateRow })}
+ <UniversalMobileCard
+ {item}
+ icon={() => ({
+ component: ProjectsIcon,
+ variant: 'amber' as const
+ })}
+ title={(item: ProjectUpdateRow) => item.name}
+ subtitle={(item: ProjectUpdateRow) => item.imageSummary}
+ fields={[
+ {
+ label: m.image_update_current_label(),
+ getValue: (item: ProjectUpdateRow) => item.currentValue
+ },
+ {
+ label: m.image_update_latest_digest_label(),
+ getValue: (item: ProjectUpdateRow) => item.latestValue
+ },
+ {
+ label: m.common_updated(),
+ getValue: (item: ProjectUpdateRow) => formatCheckedAt(item.checkedAt)
+ }
+ ]}
+ onclick={(item: ProjectUpdateRow) => {
+ window.location.href = `/projects/${item.projectId}`;
+ }}
+ />
+{/snippet}
+
+<ArcaneTable
+ persistKey="arcane-updates-project-table"
+ items={tableItems}
+ bind:requestOptions
+ bind:selectedIds
+ bind:mobileFieldVisibility
+ onRefresh={async (options) => {
+ requestOptions = options;
+ await onRefreshData(options);
+ return {
+ ...projects,
+ data: (projects.data ?? []).map(mapProjectRow)
+ };
+ }}
+ {columns}
+ {mobileFields}
+ mobileCard={ProjectUpdatesMobileCard}
+ withoutFilters
+ selectionDisabled
+/>
diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.ts
index 86bd7356d..c981bdfe6 100644
--- a/tests/spec/project.spec.ts
+++ b/tests/spec/project.spec.ts
@@ -6,6 +6,9 @@ import { TEST_COMPOSE_YAML, TEST_ENV_FILE } from '../setup/project.data';
const ROUTES = {
page: '/projects',
apiProjects: '/api/environments/0/projects',
+ apiImageUpdatesCheckAll: '/api/environments/0/image-updates/check-all',
+ apiImageUpdatesCheckBatch: '/api/environments/0/image-updates/check-batch',
+ apiUpdaterRun: '/api/environments/0/updater/run',
newProject: '/projects/new'
};
@@ -48,6 +51,69 @@ async function openDropdownMenu(page: Page, trigger: Locator) {
return menu;
}
+async function clickProjectsPageUpdateAction(page: Page) {
+ const updateProjectsButton = page.getByRole('button', { name: 'Update Projects', exact: true });
+ if (await updateProjectsButton.isVisible().catch(() => false)) {
+ await updateProjectsButton.click();
+ return;
+ }
+
+ const moreActionsButton = page.getByRole('button', { name: 'More actions', exact: true });
+ await expect(moreActionsButton).toBeVisible();
+ await moreActionsButton.click();
+ await page.getByRole('menuitem', { name: 'Update Projects', exact: true }).click();
+}
+
+async function clickProjectDetailUpdateAction(page: Page) {
+ const recheckButton = page.getByRole('button', { name: 'Re-check Updates', exact: true }).first();
+ if (await recheckButton.isVisible().catch(() => false)) {
+ await recheckButton.click();
+ return true;
+ }
+
+ const updateTrigger = page.getByTestId('project-update-trigger').first();
+ if (!(await updateTrigger.isVisible().catch(() => false))) {
+ return false;
+ }
+ await updateTrigger.click();
+
+ if (!(await recheckButton.isVisible().catch(() => false))) {
+ return false;
+ }
+
+ await recheckButton.click();
+ return true;
+}
+
+async function fetchProjectDetail(page: Page, projectId: string): Promise<Project | null> {
+ const res = await page.request.get(`/api/environments/0/projects/${projectId}`);
+ if (!res.ok()) {
+ return null;
+ }
+
+ const body = await res.json().catch(() => null as any);
+ if (!body) return null;
+ if (body.project) return body.project as Project;
+ if (body.data?.project) return body.data.project as Project;
+ if (body.data) return body.data as Project;
+ return body as Project;
+}
+
+async function findProjectWithDetailUpdateAction(page: Page): Promise<Project | null> {
+ for (const project of realProjects) {
+ if (Number(project.serviceCount ?? 0) <= 0) {
+ continue;
+ }
+
+ const detail = await fetchProjectDetail(page, project.id || project.name);
+ if ((detail?.updateInfo?.imageRefs?.length ?? 0) > 0) {
+ return detail;
+ }
+ }
+
+ return null;
+}
+
function getPathname(url: string): string {
return url.replace(/^[a-z]+:\/\/[^/]+/i, '').split(/[?#]/)[0] || '/';
}
@@ -185,6 +251,10 @@ test.describe('Projects Page', () => {
await expect(page.locator('table')).toBeVisible();
});
+ test('should display the updates column', async ({ page }) => {
+ await expect(page.getByRole('columnheader', { name: 'Updates' })).toBeVisible();
+ });
+
test('should show project actions menu', async ({ page }) => {
test.skip(!realProjects.length, 'No projects available for actions menu test');
@@ -239,6 +309,34 @@ test.describe('Projects Page', () => {
}
});
+ test('should check project updates without triggering updater run', async ({ page }) => {
+ let checkAllRequests = 0;
+ let updaterRunRequests = 0;
+
+ await page.route('**/api/environments/*/image-updates/check-all', async (route) => {
+ checkAllRequests += 1;
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ success: true, data: {} })
+ });
+ });
+
+ await page.route('**/api/environments/*/updater/run', async (route) => {
+ updaterRunRequests += 1;
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ success: true, data: { items: [] } })
+ });
+ });
+
+ await clickProjectsPageUpdateAction(page);
+
+ await expect.poll(() => checkAllRequests).toBe(1);
+ expect(updaterRunRequests).toBe(0);
+ });
+
test('should display project status badges', async ({ page }) => {
test.skip(!realProjects.length, 'No projects available for status badge test');
@@ -886,6 +984,50 @@ test.describe('Project Detail Page', () => {
await expect(page.getByRole('tab', { name: /Logs/i })).toBeVisible();
});
+ test('should check updates for the current project via the image batch endpoint', async ({
+ page
+ }) => {
+ const projectWithServices = await findProjectWithDetailUpdateAction(page);
+ test.skip(
+ !projectWithServices,
+ 'No project with detail-page update action available for project update check test'
+ );
+
+ let batchRequests = 0;
+ let updaterRunRequests = 0;
+
+ await page.route('**/api/environments/*/image-updates/check-batch', async (route) => {
+ batchRequests += 1;
+ const body = route.request().postDataJSON() as { imageRefs?: string[] } | null;
+ expect(Array.isArray(body?.imageRefs)).toBe(true);
+ expect((body?.imageRefs?.length ?? 0) > 0).toBe(true);
+
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ success: true, data: {} })
+ });
+ });
+
+ await page.route('**/api/environments/*/updater/run', async (route) => {
+ updaterRunRequests += 1;
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ success: true, data: { items: [] } })
+ });
+ });
+
+ await page.goto(`/projects/${projectWithServices!.id || projectWithServices!.name}`);
+ await page.waitForLoadState('networkidle');
+
+ const clicked = await clickProjectDetailUpdateAction(page);
+ test.skip(!clicked, 'Current project detail view has no clickable update action');
+
+ await expect.poll(() => batchRequests).toBe(1);
+ expect(updaterRunRequests).toBe(0);
+ });
+
test('should display services tab content', async ({ page }) => {
test.skip(!realProjects.length, 'No projects available for services test');
diff --git a/types/project/project.go b/types/project/project.go
index 3ea44b6c4..62f2399a5 100644
--- a/types/project/project.go
+++ b/types/project/project.go
@@ -1,6 +1,8 @@
package project
import (
+ "time"
+
composetypes "github.com/compose-spec/compose-go/v2/types"
"github.com/getarcaneapp/arcane/types/containerregistry"
)
@@ -141,6 +143,60 @@ type RuntimeService struct {
ServiceConfig *composetypes.ServiceConfig `json:"serviceConfig,omitempty"`
}
+// UpdateInfo contains aggregated image update status for a project.
+type UpdateInfo struct {
+ // Status is the aggregate update status for the project.
+ //
+ // Values: has_update | up_to_date | unknown | error
+ // Required: true
+ Status string `json:"status"`
+
+ // HasUpdate indicates whether any project image has an available update.
+ //
+ // Required: true
+ HasUpdate bool `json:"hasUpdate"`
+
+ // ImageCount is the total number of unique checkable image references in the project.
+ //
+ // Required: true
+ ImageCount int `json:"imageCount"`
+
+ // CheckedImageCount is the number of project image references with persisted update-check results.
+ //
+ // Required: true
+ CheckedImageCount int `json:"checkedImageCount"`
+
+ // ImagesWithUpdates is the number of project image references with available updates.
+ //
+ // Required: true
+ ImagesWithUpdates int `json:"imagesWithUpdates"`
+
+ // ErrorCount is the number of project image references whose latest check failed.
+ //
+ // Required: true
+ ErrorCount int `json:"errorCount"`
+
+ // ErrorMessage is the first available error message from the latest project image checks.
+ //
+ // Required: false
+ ErrorMessage *string `json:"errorMessage,omitempty"`
+
+ // ImageRefs is the list of unique image references detected for the project.
+ //
+ // Required: false
+ ImageRefs []string `json:"imageRefs,omitempty"`
+
+ // UpdatedImageRefs is the subset of project image references with available updates.
+ //
+ // Required: false
+ UpdatedImageRefs []string `json:"updatedImageRefs,omitempty"`
+
+ // LastCheckedAt is the latest successful or failed image update check time for this project.
+ //
+ // Required: false
+ LastCheckedAt *time.Time `json:"lastCheckedAt,omitempty"`
+}
+
// CreateReponse is the response when a project is created.
type CreateReponse struct {
// ID is the unique identifier of the project.
@@ -307,6 +363,11 @@ type Details struct {
// Required: false
RuntimeServices []RuntimeService `json:"runtimeServices,omitempty"`
+ // UpdateInfo contains aggregated image update status for the project.
+ //
+ // Required: false
+ UpdateInfo *UpdateInfo `json:"updateInfo,omitempty"`
+
// HasBuildDirective indicates whether any Compose service defines a build directive.
//
// Required: false