Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: resolve pending update status consistently across containers, projects, and dashboard (#4189)
Kyle Mendellaaac10a0d5e1
diff --git a/backend/internal/container/service.go b/backend/internal/container/service.goindex f02d5978a..959ad75dc 100644--- a/backend/internal/container/service.go+++ b/backend/internal/container/service.go@@ -36,7 +36,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/iconcatalog"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref"containertypes "github.com/getarcaneapp/arcane/types/v2/container""github.com/getarcaneapp/arcane/types/v2/containerregistry"imagetypes "github.com/getarcaneapp/arcane/types/v2/image"@@ -1188,6 +1187,8 @@ func (s *ContainerService) GetContainerDetails(ctx context.Context, id string) (excluded = dockerutils.ExcludedContainerNameSet(s.settingsService.GetStringSetting(ctx, "autoUpdateExcludedContainers", ""))}details.AutoUpdateEnabled = !labels.IsUpdateDisabled(details.Labels) && !dockerutils.ContainerNameExcluded([]string{details.Name}, excluded)+ updates := s.lookupContainerUpdateInfoInternal(ctx, []container.Summary{{ID: details.ID, Image: details.Image, ImageID: details.ImageID, Labels: details.Labels}})+ details.UpdateInfo = updates[details.ID]s.applyContainerDetailsIconInternal(ctx, &details)return details, nil@@ -1457,7 +1458,7 @@ func (s *ContainerService) ListContainersPaginated(}dockerContainers = FilterExcludedContainers(dockerContainers, includeInternal, includeHidden)- updateInfoMap := s.getUpdateInfoMapInternal(ctx, dockerContainers)+ updateInfoMap := s.lookupContainerUpdateInfoInternal(ctx, dockerContainers)currentContainerID, currentContainerErr := cgroup.CurrentContainerID()items := s.BuildSummaries(ctx, dockerContainers, updateInfoMap, currentContainerID, currentContainerErr)@@ -1615,41 +1616,18 @@ func FilterExcludedContainers(containers []container.Summary, includeInternal, ireturn filtered}-func CollectImageIDs(containers []container.Summary) []string {- imageIDSet := make(map[string]struct{}, len(containers))- for _, dc := range containers {- if dc.ImageID != "" {- imageIDSet[dc.ImageID] = struct{}{}- }- }-- imageIDs := make([]string, 0, len(imageIDSet))- for id := range imageIDSet {- imageIDs = append(imageIDs, id)- }- return imageIDs-}--func (s *ContainerService) getUpdateInfoMapInternal(ctx context.Context, containers []container.Summary) map[string]*imagetypes.UpdateInfo {- result := make(map[string]*imagetypes.UpdateInfo)+// lookupContainerUpdateInfoInternal resolves stored update checks keyed by+// container ID; lookup failures degrade to missing status rather than a failed list.+func (s *ContainerService) lookupContainerUpdateInfoInternal(ctx context.Context, containers []container.Summary) map[string]*imagetypes.UpdateInfo {if s.imageService == nil || len(containers) == 0 {- return result- }- updates, err := s.imageService.GetUpdateInfoByImageIDs(ctx, CollectImageIDs(containers))- if err != nil {- slog.WarnContext(ctx, "Failed to fetch image update info for containers", "error", err)- } else {- maps.Copy(result, updates)+ return map[string]*imagetypes.UpdateInfo{}}- scoped, err := s.imageService.GetUpdateInfoByContainers(ctx, containers)+ updates, err := s.imageService.GetUpdateInfoByContainers(ctx, containers)if err != nil {- slog.WarnContext(ctx, "Failed to fetch container tag update info", "error", err)- return result+ slog.WarnContext(ctx, "Failed to fetch container update info", "error", err)+ return map[string]*imagetypes.UpdateInfo{}}- for id, info := range scoped {- result["container::"+id] = info- }- return result+ return updates}func (s *ContainerService) BuildSummaries(ctx context.Context, containers []container.Summary, updateInfoMap map[string]*imagetypes.UpdateInfo, currentContainerID string, currentContainerErr error) []containertypes.Summary {@@ -1660,7 +1638,6 @@ func (s *ContainerService) BuildSummaries(ctx context.Context, containers []cont}for _, dc := range containers {summary := containertypes.NewSummary(dc)- key := dc.ImageIDpolicy := updater.DefaultLabelPolicy().TagPolicy(dc.Labels)resolved, policyErr := tagpolicy.Resolve(dc.Image, policy)summary.UpdateStrategy = resolved.Strategy@@ -1670,13 +1647,7 @@ func (s *ContainerService) BuildSummaries(ctx context.Context, containers []contsummary.UpdateStrategy = "auto"}}- if policyErr != nil || resolved.Strategy == "tag" {- key = "container::" + dc.ID- }- // A shared image result must not surface for a container that opted out of checks.- if info, exists := updateInfoMap[key]; exists && !imageref.IsUpdateCheckDisabled(dc.Labels) {- summary.UpdateInfo = info- }+ summary.UpdateInfo = updateInfoMap[dc.ID]summary.RedeployDisabled = labels.ShouldDisableArcaneServerRedeploy(summary.Labels, summary.ID, currentContainerID, currentContainerErr)summary.AutoUpdateEnabled = !labels.IsUpdateDisabled(dc.Labels) && !dockerutils.ContainerNameExcluded(dc.Names, excluded)summary.Hidden, _ = utils.ParseBool(dc.Labels[libarcane.HiddenResourceLabel])diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.goindex 2a4b033fd..650697ce4 100644--- a/backend/internal/container/service_test.go+++ b/backend/internal/container/service_test.go@@ -607,9 +607,12 @@ func TestBuildSummariesUsesContainerTagPolicyUpdates(t *testing.T) {{ID: "opted-out", Names: []string{"/opted-out"}, Image: "app:3.1.0", ImageID: "shared-image", Labels: map[string]string{"com.getarcaneapp.arcane.updater": "false"}},{ID: "unmonitored", Image: "app:3.1.0", ImageID: "shared-image", Labels: map[string]string{"com.getarcaneapp.arcane.update-check": "false"}},}+ // The lookup keys results by container ID; containers opted out of checks have no entry.updates := map[string]*imagetypes.UpdateInfo{- "shared-image": {HasUpdate: true, UpdateType: "digest"},- "container::second": {HasUpdate: true, UpdateType: "tag", LatestVersion: "4.0.0"},+ "first": {HasUpdate: true, UpdateType: "digest"},+ "second": {HasUpdate: true, UpdateType: "tag", LatestVersion: "4.0.0"},+ "digest": {HasUpdate: true, UpdateType: "digest"},+ "opted-out": {HasUpdate: true, UpdateType: "digest"},}items := service.BuildSummaries(t.Context(), containers, updates, "", nil)require.Equal(t, "digest", items[0].UpdateStrategy, "an unlabeled container follows the digest")@@ -623,7 +626,7 @@ func TestBuildSummariesUsesContainerTagPolicyUpdates(t *testing.T) {require.True(t, items[0].AutoUpdateEnabled, "containers without opt-out are eligible")require.False(t, items[4].AutoUpdateEnabled, "the updater label disables auto-update")require.Equal(t, "digest", items[4].UpdateInfo.UpdateType, "disabling automatic updates keeps check results visible")- require.Nil(t, items[5].UpdateInfo, "the update-check label hides the shared image result")+ require.Nil(t, items[5].UpdateInfo, "a container without a lookup result reports no status")require.True(t, items[5].AutoUpdateEnabled, "the update-check label does not affect installation eligibility")encoded, err := json.Marshal(items[4])require.NoError(t, err)diff --git a/backend/internal/dashboard/service.go b/backend/internal/dashboard/service.goindex db2727ffb..c46b2f4c3 100644--- a/backend/internal/dashboard/service.go+++ b/backend/internal/dashboard/service.go@@ -3,8 +3,6 @@ package dashboardimport ("github.com/getarcaneapp/arcane/backend/v2/internal/apikey"- "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"-"context""sort""strconv"@@ -37,9 +35,7 @@ import (versiontypes "github.com/getarcaneapp/arcane/types/v2/version"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""go.getarcane.app/sys/cgroup"- "go.getarcane.app/updater""go.getarcane.app/updater/labels"- "go.getarcane.app/updater/pkg/utils/tagpolicy")const (@@ -419,29 +415,24 @@ func filterStandaloneDockerContainersInternal(containers []dockercontainer.Summareturn filtered}+// getPendingContainerUpdatesCountInternal counts standalone containers whose+// stored check reports an update, through the same lookup the container list+// uses. Containers sharing one image each count once.func (s *DashboardService) getPendingContainerUpdatesCountInternal(ctx context.Context, containers []dockercontainer.Summary) (int, error) {- if s.db == nil || len(containers) == 0 {+ if s.imageService == nil || len(containers) == 0 {return 0, nil}- var imageIDs, containerIDs []string- for _, c := range containers {- if labels.IsUpdateDisabled(c.Labels) {- continue- }- policy, policyErr := tagpolicy.Resolve(c.Image, updater.DefaultLabelPolicy().TagPolicy(c.Labels))- if policyErr != nil || policy.Strategy == "tag" {- containerIDs = append(containerIDs, c.ID)- } else {- imageIDs = append(imageIDs, c.ImageID)- }- }- var count int64- err := s.db.WithContext(ctx).Model(&imageupdate.ImageUpdateRecord{}).- Where("has_update = ? AND ((container_id = ? AND id IN ?) OR container_id IN ?)", true, "", imageIDs, containerIDs).Count(&count).Error+ updates, err := s.imageService.GetUpdateInfoByContainers(ctx, containers)if err != nil {- return 0, errors.WrapIf(err, "failed to count pending container updates")+ return 0, errors.WrapIf(err, "failed to resolve pending container updates")}- return int(count), nil+ count := 0+ for _, info := range updates {+ if info != nil && info.HasUpdate {+ count+++ }+ }+ return count, nil}func (s *DashboardService) getPendingProjectUpdatesCountInternal(ctx context.Context, allContainers []dockercontainer.Summary) (int, error) {diff --git a/backend/internal/dashboard/service_test.go b/backend/internal/dashboard/service_test.goindex 385d9b558..8f4058cb5 100644--- a/backend/internal/dashboard/service_test.go+++ b/backend/internal/dashboard/service_test.go@@ -28,6 +28,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/volume"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref"dashboardtypes "github.com/getarcaneapp/arcane/types/v2/dashboard"usertypes "github.com/getarcaneapp/arcane/types/v2/user"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"@@ -163,6 +164,14 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {Tag: "latest",HasUpdate: true,})+ // Recorded under another local tag of the running container's image.+ createDashboardTestImageUpdateRecord(t, db, imageupdate.ImageUpdateRecord{+ ID: "sha256:image-a",+ Repository: "docker.io/repo/app",+ Tag: "edge",+ HasUpdate: true,+ UpdateType: "digest",+ })createDashboardTestAPIKey(t, db, apikey.ApiKey{Name: "expiring-soon",@@ -192,8 +201,9 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {Path: projectPath,Status: project.ProjectStatusStopped,}).Error)- projectSvc := project.NewProjectService(db, settingsSvc, nil, image.NewImageService(db, nil, nil, nil, nil, nil), nil, nil, nil, nil, config.Load())- svc := NewDashboardService(db, dockerSvc, nil, projectSvc, nil, settingsSvc, nil, nil, nil, volume.NewVolumeService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil))+ imageSvc := image.NewImageService(db, nil, nil, nil, nil, nil)+ projectSvc := project.NewProjectService(db, settingsSvc, nil, imageSvc, nil, nil, nil, nil, config.Load())+ svc := NewDashboardService(db, dockerSvc, nil, projectSvc, imageSvc, settingsSvc, nil, nil, nil, volume.NewVolumeService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil))snapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{}, true)require.NoError(t, err)@@ -221,9 +231,9 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {require.ElementsMatch(t, []dashboardtypes.ActionItem{{Kind: dashboardtypes.ActionItemKindStoppedContainers, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},- {Kind: dashboardtypes.ActionItemKindImageUpdates, Count: 2, Severity: dashboardtypes.ActionItemSeverityWarning},+ {Kind: dashboardtypes.ActionItemKindImageUpdates, Count: 3, Severity: dashboardtypes.ActionItemSeverityWarning},{Kind: dashboardtypes.ActionItemKindExpiringKeys, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},- }, snapshot.ActionItems.Items)+ }, snapshot.ActionItems.Items, "the excluded stopped container, the moving-tag container, and the project each count once")}func TestDashboardService_GetSnapshot_DebugAllGoodOnlyClearsActionItems(t *testing.T) {@@ -437,13 +447,15 @@ func TestDashboardService_GetSnapshot_CachesFullSnapshotsPerIconCatalog(t *testifunc TestPendingContainerCountUsesScopedTagRecords(t *testing.T) {db, _ := setupDashboardServiceTestDB(t)+ tagLabels := map[string]string{labels.LabelUpdateStrategy: "auto"}records := []imageupdate.ImageUpdateRecord{- {ID: "shared", HasUpdate: true},- {ID: "container::first", ContainerID: "first", ImageID: "shared", HasUpdate: true},- {ID: "container::other-project", ContainerID: "other-project", ImageID: "shared", HasUpdate: true},+ // A digest record recorded under another local tag of the shared image.+ {ID: "shared", Repository: "docker.io/library/app", Tag: "stable", HasUpdate: true, UpdateType: "digest"},+ {ID: "container::first", PolicyKey: imageref.UpdatePolicyKey("app:1.2.3", tagLabels), ContainerID: "first", ImageID: "shared", HasUpdate: true, UpdateType: "tag"},+ {ID: "container::other-project", PolicyKey: imageref.UpdatePolicyKey("app:1.2.3", tagLabels), ContainerID: "other-project", ImageID: "shared", HasUpdate: true, UpdateType: "tag"},}require.NoError(t, db.Create(&records).Error)- service := &DashboardService{db: db}+ service := &DashboardService{db: db, imageService: image.NewImageService(db, nil, nil, nil, nil, nil)}containers := []dockercontainer.Summary{{ID: "first", Image: "app:1.2.3", ImageID: "shared", Labels: map[string]string{labels.LabelUpdateStrategy: "auto"}},{ID: "unchecked", Image: "app:1.2.3", ImageID: "shared", Labels: map[string]string{labels.LabelUpdateStrategy: "auto"}},@@ -454,9 +466,21 @@ func TestPendingContainerCountUsesScopedTagRecords(t *testing.T) {containers = append(containers, dockercontainer.Summary{ID: "digest", Image: "app:latest", ImageID: "shared"})count, err = service.getPendingContainerUpdatesCountInternal(t.Context(), containers)require.NoError(t, err)- require.Equal(t, 2, count)+ require.Equal(t, 2, count, "a digest record under another tag of the running image counts")+ containers = append(containers, dockercontainer.Summary{ID: "digest-twin", Image: "app:latest", ImageID: "shared"})+ count, err = service.getPendingContainerUpdatesCountInternal(t.Context(), containers)+ require.NoError(t, err)+ require.Equal(t, 3, count, "separate containers sharing one image each count once")containers[0].Labels[labels.LabelUpdater] = "off"count, err = service.getPendingContainerUpdatesCountInternal(t.Context(), containers)require.NoError(t, err)- require.Equal(t, 1, count)+ require.Equal(t, 3, count, "disabling automatic installation keeps the pending update visible")+ containers[0].Labels[imageref.UpdateCheckLabel] = "false"+ count, err = service.getPendingContainerUpdatesCountInternal(t.Context(), containers)+ require.NoError(t, err)+ require.Equal(t, 2, count, "disabling update checks suppresses the result")+ containers[2].ImageID = ""+ count, err = service.getPendingContainerUpdatesCountInternal(t.Context(), containers)+ require.NoError(t, err)+ require.Equal(t, 1, count, "a missing runtime image ID inherits no digest check")}diff --git a/backend/internal/image/image.go b/backend/internal/image/image.goindex c8176587c..a9e54df6d 100644--- a/backend/internal/image/image.go+++ b/backend/internal/image/image.go@@ -663,27 +663,63 @@ func (s *ImageService) GetUpdateInfoByImageIDs(ctx context.Context, imageIDs []sreturn result, nil}-// GetUpdateInfoByContainers returns checks matching each container's current policy.+// GetUpdateInfoByContainers returns the stored check matching each container's+// current policy, keyed by container ID. Digest policies read the image-level+// record for the container's runtime image ID, so a check recorded under another+// local tag of the same image still applies. Tag policies read the container's+// own record and require an exact policy key. Containers that opted out of update+// checks are omitted; disabling automatic installation does not hide results.func (s *ImageService) GetUpdateInfoByContainers(ctx context.Context, containers []container.Summary) (map[string]*imagetypes.UpdateInfo, error) {result := make(map[string]*imagetypes.UpdateInfo)if s.db == nil || len(containers) == 0 {return result, nil}- containerIDs := make([]string, 0, len(containers))+ digestImageIDs := make(map[string]string, len(containers))+ tagContainerIDs := make([]string, 0, len(containers))policies := make(map[string]string, len(containers))for _, cnt := range containers {+ if cnt.ID == "" || imageref.IsUpdateCheckDisabled(cnt.Labels) {+ continue+ }policy, policyErr := tagpolicy.Resolve(cnt.Image, updater.DefaultLabelPolicy().TagPolicy(cnt.Labels))- if (policyErr == nil && policy.Strategy == "digest") || imageref.IsUpdateCheckDisabled(cnt.Labels) {+ if policyErr == nil && policy.Strategy == "digest" {+ if imageID := strings.TrimSpace(cnt.ImageID); imageID != "" {+ digestImageIDs[cnt.ID] = imageID+ }continue}- containerIDs = append(containerIDs, cnt.ID)+ tagContainerIDs = append(tagContainerIDs, cnt.ID)policies[cnt.ID] = imageref.UpdatePolicyKey(cnt.Image, cnt.Labels)}- if len(containerIDs) == 0 {++ if len(digestImageIDs) > 0 {+ imageIDs := make([]string, 0, len(digestImageIDs))+ seen := make(map[string]struct{}, len(digestImageIDs))+ for _, imageID := range digestImageIDs {+ if _, exists := seen[imageID]; exists {+ continue+ }+ seen[imageID] = struct{}{}+ imageIDs = append(imageIDs, imageID)+ }+ byImageID, err := s.GetUpdateInfoByImageIDs(ctx, imageIDs)+ if err != nil {+ return nil, err+ }+ for containerID, imageID := range digestImageIDs {+ if info := byImageID[imageID]; info != nil {+ // Each container gets its own copy so aggregation never mutates a shared record.+ scoped := *info+ result[containerID] = &scoped+ }+ }+ }++ if len(tagContainerIDs) == 0 {return result, nil}var records []imageupdate.ImageUpdateRecord- if err := s.db.WithContext(ctx).Where("container_id IN ?", containerIDs).Find(&records).Error; err != nil {+ if err := s.db.WithContext(ctx).Where("container_id IN ?", tagContainerIDs).Find(&records).Error; err != nil {return nil, errors.WrapIf(err, "failed to fetch container update records")}for i := range records {diff --git a/backend/internal/image/service_test.go b/backend/internal/image/service_test.goindex d1ee4c5ea..454236c6e 100644--- a/backend/internal/image/service_test.go+++ b/backend/internal/image/service_test.go@@ -712,4 +712,23 @@ func TestImageServiceContainerTagUpdatesStayScoped(t *testing.T) {checks, err := svc.GetUpdateInfoByContainers(t.Context(), []container.Summary{{ID: "first", Image: "example:3.1.0", Labels: installExcluded}})require.NoError(t, err)require.Equal(t, firstTarget, checks["first"].LatestVersion)++ // A digest check recorded under another local tag of the running image+ // applies to every digest-policy container using that image ID.+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "moving-image", Repository: "docker.io/library/app", Tag: "stable", CurrentVersion: "stable", HasUpdate: true, UpdateType: "digest", CheckTime: now}).Error)+ digestContainers := []container.Summary{+ {ID: "moving", Image: "app:latest", ImageID: "moving-image"},+ {ID: "moving-twin", Image: "app:latest", ImageID: "moving-image", Labels: map[string]string{"com.getarcaneapp.arcane.updater": "false"}},+ {ID: "moving-unmonitored", Image: "app:latest", ImageID: "moving-image", Labels: map[string]string{imageref.UpdateCheckLabel: "false"}},+ {ID: "moving-tag", Image: "app:latest", ImageID: "moving-image", Labels: map[string]string{"com.getarcaneapp.arcane.updater.strategy": "tag"}},+ {ID: "moving-no-id", Image: "app:latest"},+ }+ checks, err = svc.GetUpdateInfoByContainers(t.Context(), digestContainers)+ require.NoError(t, err)+ require.True(t, checks["moving"].HasUpdate)+ require.True(t, checks["moving-twin"].HasUpdate, "disabling automatic installation keeps the check visible")+ require.NotContains(t, checks, "moving-unmonitored", "disabling update checks suppresses the result")+ require.NotContains(t, checks, "moving-tag", "a tag policy never falls back to the shared digest check")+ require.NotContains(t, checks, "moving-no-id", "a missing runtime image ID matches nothing")+ require.NotSame(t, checks["moving"], checks["moving-twin"], "each container receives its own copy")}diff --git a/backend/internal/project/project_details.go b/backend/internal/project/project_details.goindex 6db6e9350..64e76a69e 100644--- a/backend/internal/project/project_details.go+++ b/backend/internal/project/project_details.go@@ -48,6 +48,8 @@ type ProjectServiceInfo struct {ServiceConfig *composetypes.ServiceConfig `json:"service_config,omitempty"`Labels map[string]string `json:"labels,omitempty"`RedeployDisabled bool `json:"redeploy_disabled,omitempty"`+ // ImageID is the runtime image ID; it never leaves the server.+ ImageID string `json:"-"`}func getServiceCounts(services []ProjectServiceInfo) (total int, running int) {@@ -126,6 +128,7 @@ func (s *ProjectService) GetProjectServices(ctx context.Context, projectID strinslog.Error("compose ps error", "projectName", composeProject.Name, "error", err)return nil, errors.WrapIf(err, "failed to get compose services status")}+ imageIDs := s.runtimeImageIDsByContainerInternal(ctx, composeProject.Name)currentContainerID, currentContainerErr := cgroup.CurrentContainerID()have := map[string]bool{}@@ -166,6 +169,7 @@ func (s *ProjectService) GetProjectServices(ctx context.Context, projectID strinServiceConfig: svcConfig,Labels: c.Labels,RedeployDisabled: labels.ShouldDisableArcaneServerRedeploy(c.Labels, c.ID, currentContainerID, currentContainerErr),+ ImageID: imageIDs[c.ID],})have[c.Service] = true}@@ -191,6 +195,27 @@ func (s *ProjectService) GetProjectServices(ctx context.Context, projectID strinreturn services, nil}+// runtimeImageIDsByContainerInternal maps a Compose project's container IDs to+// their runtime image IDs. Compose ps omits image IDs, so one batched container+// list supplies them; a listing failure only leaves image-level checks unmatched.+func (s *ProjectService) runtimeImageIDsByContainerInternal(ctx context.Context, projectName string) map[string]string {+ imageIDs := make(map[string]string)+ if s.dockerService == nil {+ return imageIDs+ }+ containers, err := s.listGlobalComposeContainersInternal(ctx)+ if err != nil {+ slog.WarnContext(ctx, "failed to list containers for project image identity", "projectName", projectName, "error", err)+ return imageIDs+ }+ for _, c := range containers {+ if dockerutil.ComposeProjectLabel(c.Labels) == projectName && c.ImageID != "" {+ imageIDs[c.ID] = c.ImageID+ }+ }+ return imageIDs+}+func (s *ProjectService) GetProjectContent(ctx context.Context, projectID string) (composeContent, envContent, overrideContent string, err error) {proj, err := s.GetProjectFromDatabaseByID(ctx, projectID)if err != nil {@@ -412,6 +437,7 @@ func buildProjectRuntimeServicesInternal(services []ProjectServiceInfo) []projecIconDarkURL: svc.IconDarkURL,ServiceConfig: svc.ServiceConfig,RedeployDisabled: svc.RedeployDisabled,+ ImageID: svc.ImageID,}}return runtimeServices@@ -709,7 +735,7 @@ func (s *ProjectService) getProjectContainerUpdateInfoInternal(ctx context.Contefor _, detail := range details {for _, service := range detail.RuntimeServices {if service.ContainerID != "" {- containers = append(containers, container.Summary{ID: service.ContainerID, Image: service.Image, Labels: service.ContainerLabels})+ containers = append(containers, container.Summary{ID: service.ContainerID, Image: service.Image, ImageID: service.ImageID, Labels: service.ContainerLabels})}}}diff --git a/backend/internal/project/project_listing.go b/backend/internal/project/project_listing.goindex 49b0b1456..0e59d937d 100644--- a/backend/internal/project/project_listing.go+++ b/backend/internal/project/project_listing.go@@ -121,6 +121,7 @@ func projectServiceInfoFromContainerInternal(ctx context.Context, c container.SuIconDarkURL: resolvedIcon.IconDarkURL,Labels: c.Labels,RedeployDisabled: labels.ShouldDisableArcaneServerRedeploy(c.Labels, c.ID, currentContainerID, currentContainerErr),+ ImageID: c.ImageID,}}@@ -549,7 +550,6 @@ func buildDiscoveredComposeProjectUpdateRowsInternal(return nil}- updateInfoByRef := getRuntimeContainerUpdateInfoByRefInternal(ctx, composeContainers, imageService)scoped := getRuntimeContainerUpdateInfoByContainerIDInternal(ctx, composeContainers, imageService)rows := make([]project.Details, 0, len(containersByProject))for projectName, projectContainers := range containersByProject {@@ -557,9 +557,9 @@ func buildDiscoveredComposeProjectUpdateRowsInternal(imageRefs := projects.ImageRefsFromRuntimeServices(runtimeServices)checkServices := make([]project.RuntimeService, 0, len(projectContainers))for _, c := range projectContainers {- checkServices = append(checkServices, project.RuntimeService{Name: dockerutil.ComposeServiceLabel(c.Labels), ContainerID: c.ID, Image: c.Image, ContainerLabels: c.Labels})+ checkServices = append(checkServices, project.RuntimeService{Name: dockerutil.ComposeServiceLabel(c.Labels), ContainerID: c.ID, Image: c.Image, ImageID: c.ImageID, ContainerLabels: c.Labels})}- updateInfo := BuildUpdateInfoSummary(imageRefs, mergeProjectContainerUpdateInfoInternal(updateInfoByRef, checkServices, scoped))+ updateInfo := BuildUpdateInfoSummary(imageRefs, mergeProjectContainerUpdateInfoInternal(nil, checkServices, scoped))if updateInfo == nil || !updateInfo.HasUpdate {continue}@@ -606,74 +606,6 @@ func getRuntimeContainerUpdateInfoByContainerIDInternal(ctx context.Context, conreturn scoped}-func getRuntimeContainerUpdateInfoByRefInternal(- ctx context.Context,- composeContainers []container.Summary,- imageService *image.ImageService,-) map[string]*imagetypes.UpdateInfo {- if imageService == nil || len(composeContainers) == 0 {- return nil- }-- imageRefs := make([]string, 0, len(composeContainers))- imageIDsByRef := make(map[string][]string, len(composeContainers))- seenRefs := make(map[string]struct{}, len(composeContainers))- for _, c := range composeContainers {- imageRef := strings.TrimSpace(c.Image)- if imageRef == "" {- continue- }- if _, exists := seenRefs[imageRef]; !exists {- seenRefs[imageRef] = struct{}{}- imageRefs = append(imageRefs, imageRef)- }- if imageID := strings.TrimSpace(c.ImageID); imageID != "" {- imageIDsByRef[imageRef] = append(imageIDsByRef[imageRef], imageID)- }- }-- updateInfoByRef := make(map[string]*imagetypes.UpdateInfo, len(imageRefs))- if len(imageRefs) > 0 {- if refResults, err := imageService.GetUpdateInfoByImageRefs(ctx, imageRefs); err == nil {- maps.Copy(updateInfoByRef, refResults)- } else {- slog.WarnContext(ctx, "failed to fetch compose project update info by image ref", "error", err)- }- }-- missingImageIDs := make([]string, 0)- for _, imageRef := range imageRefs {- if updateInfoByRef[imageRef] != nil {- continue- }- missingImageIDs = append(missingImageIDs, imageIDsByRef[imageRef]...)- }-- if len(missingImageIDs) == 0 {- return updateInfoByRef- }-- updateInfoByID, err := imageService.GetUpdateInfoByImageIDs(ctx, missingImageIDs)- if err != nil {- slog.WarnContext(ctx, "failed to fetch compose project update info by image id", "error", err)- return updateInfoByRef- }-- for imageRef, imageIDs := range imageIDsByRef {- if updateInfoByRef[imageRef] != nil {- continue- }- for _, imageID := range imageIDs {- if info := updateInfoByID[imageID]; info != nil {- updateInfoByRef[imageRef] = info- break- }- }- }-- return updateInfoByRef-}-func buildDiscoveredRuntimeServicesInternal(containers []container.Summary, iconCatalog string) []project.RuntimeService {runtimeServices := make([]project.RuntimeService, 0, len(containers))seenServices := make(map[string]struct{}, len(containers))@@ -701,6 +633,7 @@ func buildDiscoveredRuntimeServicesInternal(containers []container.Summary, iconImage: imageRef,Status: string(c.State),ContainerID: c.ID,+ ImageID: c.ImageID,ContainerLabels: c.Labels,ContainerName: containerName,Ports: projects.FormatDockerPorts(c.Ports),@@ -901,7 +834,7 @@ func (s *ProjectService) CountProjectsWithPendingUpdates(ctx context.Context, alfor i, proj := range activeProjects {details[i].ID = proj.IDfor _, c := range lookupProjectContainersInternal(proj, containersByProject) {- details[i].RuntimeServices = append(details[i].RuntimeServices, project.RuntimeService{Name: dockerutil.ComposeServiceLabel(c.Labels), ContainerID: c.ID, Image: c.Image, ContainerLabels: c.Labels})+ details[i].RuntimeServices = append(details[i].RuntimeServices, project.RuntimeService{Name: dockerutil.ComposeServiceLabel(c.Labels), ContainerID: c.ID, Image: c.Image, ImageID: c.ImageID, ContainerLabels: c.Labels})}}s.enrichProjectsWithUpdateInfoInternal(ctx, activeProjects, details, false, nil)diff --git a/backend/internal/project/service_test.go b/backend/internal/project/service_test.goindex a5795a3e2..986390cde 100644--- a/backend/internal/project/service_test.go+++ b/backend/internal/project/service_test.go@@ -3960,7 +3960,7 @@ func TestBuildDiscoveredComposeProjectUpdateRowsInternal_FallsBackToImageID(t *tCheckTime: time.Now().UTC(),}).Error)- rows := buildDiscoveredComposeProjectUpdateRowsInternal(ctx, []container.Summary{+ containers := []container.Summary{{ID: "media-web",Image: "nginx:latest",@@ -3971,10 +3971,44 @@ func TestBuildDiscoveredComposeProjectUpdateRowsInternal_FallsBackToImageID(t *t"com.docker.compose.service": "web",},},- }, map[string]struct{}{}, imageService, iconcatalog.DefaultCatalog)+ {+ ID: "media-web-replica",+ Image: "nginx:latest",+ ImageID: "sha256:media-image",+ State: "running",+ Labels: map[string]string{+ "com.docker.compose.project": "media",+ "com.docker.compose.service": "web",+ labels.LabelUpdater: "false",+ },+ },+ {+ ID: "pinned-web",+ Image: "nginx:1.25.0",+ ImageID: "sha256:media-image",+ State: "running",+ Labels: map[string]string{+ "com.docker.compose.project": "pinned",+ "com.docker.compose.service": "web",+ labels.LabelUpdateStrategy: "tag",+ },+ },+ }+ rows := buildDiscoveredComposeProjectUpdateRowsInternal(ctx, containers, map[string]struct{}{}, imageService, iconcatalog.DefaultCatalog)- require.Len(t, rows, 1)+ require.Len(t, rows, 1, "replicas count once and a tag policy never inherits the digest check")+ assert.Equal(t, "compose:media", rows[0].ID)assert.Equal(t, []string{"nginx:latest"}, rows[0].UpdateInfo.UpdatedImageRefs)++ // The tracked-project path resolves the same record through the runtime image ID.+ service := &ProjectService{imageService: imageService}+ detail := projecttypes.Details{ID: "tracked", RuntimeServices: []projecttypes.RuntimeService{{Name: "web", ContainerID: "media-web", Image: "nginx:latest", ImageID: "sha256:media-image", ContainerLabels: containers[0].Labels}}}+ service.enrichProjectUpdateInfoInternal(ctx, &detail)+ require.True(t, detail.UpdateInfo.HasUpdate)+ assert.Equal(t, []string{"nginx:latest"}, detail.UpdateInfo.UpdatedImageRefs)+ detail.RuntimeServices[0].ImageID = ""+ service.enrichProjectUpdateInfoInternal(ctx, &detail)+ require.False(t, detail.UpdateInfo.HasUpdate, "a missing runtime image ID inherits nothing")}func TestProjectService_ListProjects_FiltersArchivedProjects(t *testing.T) {@@ -7552,6 +7586,23 @@ func TestCountProjectsWithPendingTagUpdatesUsesRuntimeContainers(t *testing.T) {count, err = service.CountProjectsWithPendingUpdates(t.Context(), containers)require.NoError(t, err)require.Zero(t, count)++ // A digest check stored under another local tag of the running image marks+ // the project once, however many replicas share the image.+ require.NoError(t, db.Create(&Project{Name: "third", Path: "third", ImageRefsJSON: `["app:latest"]`}).Error)+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "moving-image", Repository: "docker.io/library/app", Tag: "stable", HasUpdate: true, UpdateType: "digest"}).Error)+ containers = append(containers,+ container.Summary{ID: "third-one", Image: "app:latest", ImageID: "moving-image", Labels: map[string]string{"com.docker.compose.project": "third", "com.docker.compose.service": "web"}},+ container.Summary{ID: "third-two", Image: "app:latest", ImageID: "moving-image", Labels: map[string]string{"com.docker.compose.project": "third", "com.docker.compose.service": "web", labels.LabelUpdater: "false"}},+ )+ count, err = service.CountProjectsWithPendingUpdates(t.Context(), containers)+ require.NoError(t, err)+ require.Equal(t, 1, count)+ containers[2].Labels[imageref.UpdateCheckLabel] = "false"+ containers[3].Labels[imageref.UpdateCheckLabel] = "false"+ count, err = service.CountProjectsWithPendingUpdates(t.Context(), containers)+ require.NoError(t, err)+ require.Zero(t, count, "disabling update checks on every replica suppresses the project")}type serviceTagTransportInternal struct {@@ -7801,6 +7852,14 @@ func TestConfiguredProjectAggregatesReplicaAndPreviewChecks(t *testing.T) {require.Empty(t, summary.ServiceUpdates["web"].UpdateInfo.LatestVersion)require.Empty(t, summary.UpdateInfoByRef["example:3.1.0"].LatestVersion)require.Equal(t, "3.2.0", scoped["two"].LatestVersion, "aggregation must not modify shared checks")++ // A configured check reporting no update does not hide a pending replica.+ records[0].HasUpdate = false+ records[0].LatestVersion = nil+ summary = BuildConfiguredUpdateInfo("project", configs, nil, records, runtimeUpdates)+ require.True(t, summary.HasUpdate)+ require.True(t, summary.ServiceUpdates["web"].UpdateInfo.HasUpdate)+ require.Equal(t, "3.2.0", scoped["two"].LatestVersion)}func TestPrepareProjectBindDirectoriesInternal(t *testing.T) {diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.tsindex 1b93f6af5..98d572824 100644--- a/frontend/src/lib/query/query-keys.ts+++ b/frontend/src/lib/query/query-keys.ts@@ -121,7 +121,6 @@ export const queryKeys = {usageCounts: (environmentId: string) => ['images', 'usage-counts', environmentId] as const,history: (environmentId: string, imageId: string) => ['image', environmentId, imageId, 'history'] as const,detail: (environmentId: string, imageId: string) => ['image', environmentId, imageId] as const,- updateInfoByRef: (environmentId: string, imageRef: string) => ['image-update-info', environmentId, imageRef] as const,updateCheck: (environmentId: string, imageId: string) => ['image-update', environmentId, imageId] as const,builds: (environmentId: string) => ['images', environmentId, 'builds'] as const,buildsList: (environmentId: string, options: SearchPaginationSortRequest) =>diff --git a/frontend/src/lib/services/image-service.ts b/frontend/src/lib/services/image-service.tsindex 363c6c69f..a418759d6 100644--- a/frontend/src/lib/services/image-service.ts+++ b/frontend/src/lib/services/image-service.ts@@ -208,19 +208,6 @@ class ImageService extends BaseAPIService {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, environmentId?: string): Promise<AutoUpdateResult> {const envId = await this.resolveEnvironmentId(environmentId);return this.handleResponse(this.api.post(`/environments/${envId}/updater/run`, options));diff --git a/frontend/src/lib/types/docker.ts b/frontend/src/lib/types/docker.tsindex 8694ebcfa..e8b51e120 100644--- a/frontend/src/lib/types/docker.ts+++ b/frontend/src/lib/types/docker.ts@@ -313,6 +313,8 @@ export interface ContainerDetailsDto {redeployDisabled?: boolean;/** Eligibility under the updater label and exclusion setting; absent on older agents. */autoUpdateEnabled?: boolean;+ /** Stored update check for the container's current policy; absent on older agents. */+ updateInfo?: ImageUpdateInfoDto;}export interface ContainerCommitRequest {diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelteindex 7e52a6c65..bcb036edc 100644--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte@@ -53,8 +53,7 @@import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';import { EditIcon, ImagesIcon, PauseIcon, PlayIcon, ProjectsIcon, UpdateIcon, ZapIcon } from '#lib/icons/index.js';import { runContainerLifecycleAction, confirmAndUpdateContainer } from '#lib/utils/container-actions.js';- import { imageService } from '#lib/services/image-service.js';- import { createQuery, useQueryClient } from '@tanstack/svelte-query';+ import { useQueryClient } from '@tanstack/svelte-query';import { queryKeys } from '#lib/query/query-keys.js';import { activityStore } from '#lib/stores/activity.store.svelte.js';import { createContainerUpdateActivityTracker } from '#lib/utils/container-update-activities.js';@@ -62,7 +61,6 @@import { containerService } from '#lib/services/container-service.js';import { extractApiErrorMessage } from '#lib/utils/api.js';import { toast } from 'svelte-sonner';- import userStore from '#lib/stores/user-store.svelte.js';import { isAutoUpdateLabelDisabled } from '#lib/utils/container-auto-update.js';import KillContainerDialog from '../components/kill-container-dialog.svelte';import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';@@ -176,23 +174,9 @@let lifecycleStatus = $state<'pausing' | 'unpausing' | ''>('');const isLifecycleActionPending = $derived(lifecycleStatus !== '');- const imageUpdateQuery = createQuery(() => {- const environmentId = environmentStore.selected?.id;- const image = container?.image;- userStore.current;- return {- queryKey: queryKeys.images.updateInfoByRef(environmentId ?? '', image ?? ''),- queryFn: async () => {- await environmentStore.ready;- return imageService.getUpdateInfoByRefs([image!]);- },- enabled: !!environmentId && !!image && hasPermission('containers:autoupdate', environmentId)- };- });- const updateInfo = $derived.by(() => {- if (container?.image) return imageUpdateQuery.data?.[container.image] ?? null;- return null;- });+ // The details response carries the stored check for this container's current+ // policy; an older agent that omits it reports no status rather than "up to date".+ const updateInfo = $derived(canUpdateContainer ? (container?.updateInfo ?? null) : null);let updateLoading = $state(false);let updateViewMounted = false;const updateActivities = createContainerUpdateActivityTracker(@@ -230,7 +214,6 @@}await Promise.all([queryClient.invalidateQueries({ queryKey: ['containers', environmentId] }),- queryClient.invalidateQueries({ queryKey: queryKeys.images.updateInfoByRef(environmentId, container.image) }),queryClient.invalidateQueries({ queryKey: queryKeys.containers.detail(environmentId, containerId) })]);if (updateViewMounted && environmentId === currentEnvId && containerId === container.id) await refreshAll();diff --git a/frontend/src/routes/(app)/updates/+page.svelte b/frontend/src/routes/(app)/updates/+page.svelteindex f94d79b50..aa7cdfe1b 100644--- a/frontend/src/routes/(app)/updates/+page.svelte+++ b/frontend/src/routes/(app)/updates/+page.svelte@@ -1,11 +1,12 @@<script lang="ts">- import { createMutation, createQuery, keepPreviousData, useQueryClient } from '@tanstack/svelte-query';- import { untrack } from 'svelte';+ import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';import { m } from '#lib/paraglide/messages.js';import { environmentStore } from '#lib/stores/environment.store.svelte.js';import { queryKeys } from '#lib/query/query-keys.js';import * as Tabs from '#lib/components/ui/tabs/index.js';import { TabBar, type TabItem } from '#lib/components/tab-bar/index.js';+ import EmptyState from '#lib/components/states/empty-state.svelte';+ import Spinner from '#lib/components/ui/spinner/spinner.svelte';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';@@ -13,9 +14,8 @@import { containerService, type ContainerListRequestOptions } from '#lib/services/container-service.js';import { projectService } from '#lib/services/project-service.js';import { confirmAndApplyAllUpdates } from '#lib/utils/update-actions.js';- import type { ContainersPaginatedResponse } from '#lib/services/container-service.js';- import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';- import type { Project } from '#lib/types/swarm.js';+ import { extractApiErrorMessage } from '#lib/utils/api.js';+ import type { SearchPaginationSortRequest } from '#lib/types/shared.js';import { ContainersIcon, ProjectsIcon, UpdateIcon } from '#lib/icons/index.js';import { toast } from 'svelte-sonner';import { ensureStandaloneContainerUpdatesFilter, ensureUpdatesFilter } from '#lib/utils/docker.js';@@ -24,91 +24,95 @@let { data } = $props();const queryClient = useQueryClient();- 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 = $derived(data.containerRequestOptions as ContainerListRequestOptions);let projectRequestOptions = $derived(data.projectRequestOptions as SearchPaginationSortRequest);const envId = $derived(environmentStore.selected?.id || '0');- const containersQuery = createQuery(() => ({- queryKey: queryKeys.containers.list(envId, ensureStandaloneContainerUpdatesFilter(containerRequestOptions)),- queryFn: () =>- containerService.getContainersForEnvironment(envId, ensureStandaloneContainerUpdatesFilter(containerRequestOptions)),- placeholderData: keepPreviousData,- initialData: envId === data.envId ? data.containers : undefined,- refetchOnMount: false- }));+ // The page loader already populated these keys, so no initialData is needed.+ // Previous rows are kept only within the same environment, and results are+ // tagged with their environment so a switch never shows another's rows.+ const containersQuery = createQuery(() => {+ const queryEnvId = envId;+ const options = ensureStandaloneContainerUpdatesFilter(containerRequestOptions);+ return {+ queryKey: queryKeys.containers.list(queryEnvId, options),+ queryFn: () => containerService.getContainersForEnvironment(queryEnvId, options),+ placeholderData: (previous, query) => {+ if (query?.queryKey[1] === queryEnvId) return previous;+ return undefined;+ },+ select: (value) => ({ envId: queryEnvId, value }),+ refetchOnMount: false+ };+ });- const projectsQuery = createQuery(() => ({- queryKey: queryKeys.projects.list(envId, ensureUpdatesFilter(projectRequestOptions)),- queryFn: () => projectService.getProjectsForEnvironment(envId, ensureUpdatesFilter(projectRequestOptions)),- placeholderData: keepPreviousData,- initialData: envId === data.envId ? data.projects : undefined,- refetchOnMount: false- }));+ const projectsQuery = createQuery(() => {+ const queryEnvId = envId;+ const options = ensureUpdatesFilter(projectRequestOptions);+ return {+ queryKey: queryKeys.projects.list(queryEnvId, options),+ queryFn: () => projectService.getProjectsForEnvironment(queryEnvId, options),+ placeholderData: (previous, query) => {+ if (query?.queryKey[1] === queryEnvId) return previous;+ return undefined;+ },+ select: (value) => ({ envId: queryEnvId, value }),+ refetchOnMount: false+ };+ });- 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 containers = $derived(containersQuery.data?.envId === envId ? containersQuery.data.value : null);+ const projects = $derived(projectsQuery.data?.envId === envId ? projectsQuery.data.value : null);++ // Table refreshes write into the cache entry for the environment and request+ // they were issued for, so a late response never replaces another+ // environment's active table. Failures reject so callers can report them;+ // the query's error state also renders inline.+ async function refreshContainers(options: ContainerListRequestOptions) {+ const requestedEnvId = envId;+ const requestedOptions = ensureStandaloneContainerUpdatesFilter(options);+ await queryClient.fetchQuery({+ queryKey: queryKeys.containers.list(requestedEnvId, requestedOptions),+ queryFn: () => containerService.getContainersForEnvironment(requestedEnvId, requestedOptions)+ });+ }++ async function refreshProjects(options: SearchPaginationSortRequest) {+ const requestedEnvId = envId;+ const requestedOptions = ensureUpdatesFilter(options);+ await queryClient.fetchQuery({+ queryKey: queryKeys.projects.list(requestedEnvId, requestedOptions),+ queryFn: () => projectService.getProjectsForEnvironment(requestedEnvId, requestedOptions)+ });+ }// Ignoring a container changes its `autoUpdateEnabled` on every container- // response, so cached lists and details for this environment go stale.+ // response for this environment. The table refetches its own rows afterwards,+ // so other cached lists are only marked stale here.async function invalidateContainerQueries() {- containerSnapshot = null;+ const requestedEnvId = envId;await Promise.all([- queryClient.invalidateQueries({ queryKey: queryKeys.containers.all }),- queryClient.invalidateQueries({ queryKey: ['container', envId] })+ queryClient.invalidateQueries({ queryKey: ['containers', requestedEnvId], refetchType: 'none' }),+ queryClient.invalidateQueries({ queryKey: ['container', requestedEnvId] })]);}const checkUpdatesMutation = createMutation(() => ({mutationKey: ['updates', 'check-all', envId],- mutationFn: () => imageService.checkAllImages(),- onSuccess: async () => {+ mutationFn: (requestedEnvId: string) => imageService.checkAllImages(requestedEnvId),+ onSuccess: async (_result, requestedEnvId) => {toast.success(m.images_update_check_completed());- await Promise.all([containersQuery.refetch(), projectsQuery.refetch()]);+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ['containers', requestedEnvId] }),+ queryClient.invalidateQueries({ queryKey: ['container', requestedEnvId] }),+ queryClient.invalidateQueries({ queryKey: ['projects', requestedEnvId] }),+ queryClient.invalidateQueries({ queryKey: queryKeys.projects.environment(requestedEnvId) }),+ queryClient.invalidateQueries({ queryKey: ['images', requestedEnvId] }),+ queryClient.invalidateQueries({ queryKey: ['image', requestedEnvId] })+ ]);},- onError: () => {- toast.error(m.images_update_check_failed());+ onError: (error) => {+ toast.error(m.images_update_check_failed(), { description: extractApiErrorMessage(error) });}}));@@ -116,8 +120,8 @@(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 containerCount = $derived(containers?.pagination?.totalItems ?? 0);+ const projectCount = $derived(projects?.pagination?.totalItems ?? 0);const totalAffectedResources = $derived(containerCount + projectCount);const tabItems: TabItem[] = $derived([{@@ -143,8 +147,6 @@const effectiveTab = $derived(urlTab.value);async function refresh() {- containerSnapshot = null;- projectSnapshot = null;await Promise.all([containersQuery.refetch(), projectsQuery.refetch()]);}@@ -169,7 +171,7 @@action: 'inspect',label: m.images_check_updates(),loadingLabel: m.common_action_checking(),- onclick: () => checkUpdatesMutation.mutate(),+ onclick: () => checkUpdatesMutation.mutate(envId),loading: isChecking,disabled: isChecking},@@ -207,13 +209,20 @@},{title: m.projects_title(),- value: projects.pagination?.totalItems ?? 0,+ value: projectCount,icon: ProjectsIcon,iconColor: 'text-warning'}]);</script>+{#snippet loadingState()}+ <div class="flex items-center justify-center gap-2 py-12 text-sm text-muted-foreground" role="status" aria-live="polite">+ <Spinner tone="muted" />+ <span>{m.common_loading()}</span>+ </div>+{/snippet}+<ResourcePageLayout title={m.updates()} icon={UpdateIcon} {actionButtons} {statCards}>{#snippet mainContent()}<div class="space-y-6">@@ -222,37 +231,42 @@<Tabs.Content value="containers" class="mt-4">{#key `${envId}-containers`}- <ContainerUpdatesTable- {containers}- bind:requestOptions={containerRequestOptions}- onAutoUpdateChanged={invalidateContainerQueries}- onRefreshData={async (options) => {- const requestedEnvId = envId;- const requestedOptions = ensureStandaloneContainerUpdatesFilter(options);- const next = await containerService.getContainersForEnvironment(requestedEnvId, requestedOptions);- if (requestedEnvId === envId) {- containerRequestOptions = requestedOptions;- containerSnapshot = { envId: requestedEnvId, value: next };- }- return next;- }}- />+ {#if containersQuery.isError}+ <EmptyState+ icon={ContainersIcon}+ title={m.common_load_failed({ resource: m.standalone_containers() })}+ description={extractApiErrorMessage(containersQuery.error)}+ actionLabel={m.common_retry()}+ onAction={() => containersQuery.refetch()}+ />+ {:else if containers}+ <ContainerUpdatesTable+ {containers}+ bind:requestOptions={containerRequestOptions}+ onAutoUpdateChanged={invalidateContainerQueries}+ onRefreshData={refreshContainers}+ />+ {:else}+ {@render loadingState()}+ {/if}{/key}</Tabs.Content><Tabs.Content value="projects" class="mt-4">{#key `${envId}-projects`}- <ProjectUpdatesTable- {projects}- bind:requestOptions={projectRequestOptions}- onRefreshData={async (options) => {- projectRequestOptions = ensureUpdatesFilter(options);- projectSnapshot = {- envId,- value: await projectService.getProjectsForEnvironment(envId, projectRequestOptions)- };- }}- />+ {#if projectsQuery.isError}+ <EmptyState+ icon={ProjectsIcon}+ title={m.common_load_failed({ resource: m.projects_title() })}+ description={extractApiErrorMessage(projectsQuery.error)}+ actionLabel={m.common_retry()}+ onAction={() => projectsQuery.refetch()}+ />+ {:else if projects}+ <ProjectUpdatesTable {projects} bind:requestOptions={projectRequestOptions} onRefreshData={refreshProjects} />+ {:else}+ {@render loadingState()}+ {/if}{/key}</Tabs.Content></Tabs.Root>diff --git a/frontend/src/routes/(app)/updates/container-updates-table.svelte b/frontend/src/routes/(app)/updates/container-updates-table.svelteindex b1af83dbc..e88ebf8ba 100644--- a/frontend/src/routes/(app)/updates/container-updates-table.svelte+++ b/frontend/src/routes/(app)/updates/container-updates-table.svelte@@ -56,11 +56,12 @@interface Props {containers: ContainersPaginatedResponse;requestOptions: SearchPaginationSortRequest;- onRefreshData: (options: ContainerListRequestOptions) => Promise<ContainersPaginatedResponse>;+ // Refreshed rows arrive through the `containers` prop once the parent's query updates.+ onRefreshData: (options: ContainerListRequestOptions) => Promise<void>;onAutoUpdateChanged?: () => Promise<unknown> | unknown;}- let { containers = $bindable(), requestOptions = $bindable(), onRefreshData, onAutoUpdateChanged }: Props = $props();+ let { containers, requestOptions = $bindable(), onRefreshData, onAutoUpdateChanged }: Props = $props();let selectedIds = $state<string[]>([]);let mobileFieldVisibility = $state<MobileFieldVisibility>({});@@ -135,9 +136,7 @@];async function refreshRows() {- const requestedEnvId = currentEnvironmentId;- const next = await onRefreshData(requestOptions as ContainerListRequestOptions);- if (updateTableMounted && requestedEnvId === currentEnvironmentId) containers = next;+ await onRefreshData(requestOptions as ContainerListRequestOptions);}async function handleUpdateContainer(container: ContainerSummaryDto) {@@ -333,12 +332,8 @@bind:mobileFieldVisibilityonRefresh={async (options) => {requestOptions = options;- const next = await onRefreshData(options as ContainerListRequestOptions);- containers = next;- return {- ...next,- data: (next.data ?? []).map(mapContainerRow)- };+ await onRefreshData(options as ContainerListRequestOptions);+ return tableItems;}}{columns}{mobileFields}diff --git a/frontend/src/routes/(app)/updates/project-updates-table.svelte b/frontend/src/routes/(app)/updates/project-updates-table.svelteindex 2cea72817..c48956eaf 100644--- a/frontend/src/routes/(app)/updates/project-updates-table.svelte+++ b/frontend/src/routes/(app)/updates/project-updates-table.svelte@@ -38,7 +38,7 @@onRefreshData: (options: SearchPaginationSortRequest) => Promise<void>;}- let { projects = $bindable(), requestOptions = $bindable(), onRefreshData }: Props = $props();+ let { projects, requestOptions = $bindable(), onRefreshData }: Props = $props();let selectedIds = $state<string[]>([]);let mobileFieldVisibility = $state<MobileFieldVisibility>({});@@ -236,10 +236,7 @@onRefresh={async (options) => {requestOptions = options;await onRefreshData(options);- return {- ...projects,- data: (projects.data ?? []).map(mapProjectRow)- };+ return tableItems;}}{columns}{mobileFields}diff --git a/tests/spec/backup-file-picker.spec.ts b/tests/spec/backup-file-picker.spec.tsindex 9063b0358..f715eb885 100644--- a/tests/spec/backup-file-picker.spec.ts+++ b/tests/spec/backup-file-picker.spec.ts@@ -1,4 +1,5 @@-import { expect, test, type Locator, type Page, type Route } from '../fixtures/test.fixture';+import { expect, test, type Page, type Route } from '../fixtures/test.fixture';+import { setCodeMirrorValue } from '../utils/playwright.util';const VOLUME_NAME = 'backup-picker-e2e';const BACKUP_ID = 'backup-picker-snapshot';@@ -283,12 +284,6 @@ async function openVolumeWorkspaceEditor(page: Page) {return editor;}-async function replaceEditorText(page: Page, editor: Locator, content: string) {- await editor.click({ position: { x: 10, y: 10 } });- await editor.press('ControlOrMeta+A');- await page.keyboard.insertText(content);-}-async function mockProjectWorkspacePage(page: Page,workspaceState: () => { content: string; revision: number }@@ -534,7 +529,7 @@ test.describe('Backup file picker', () => {await page.keyboard.press('Escape');const editor = await openVolumeWorkspaceEditor(page);- await replaceEditorText(page, editor, 'local draft');+ await setCodeMirrorValue(editor, 'local draft');await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(1);await openVolumeRestoreFilesDialog(page);@@ -600,7 +595,7 @@ test.describe('Backup file picker', () => {await page.keyboard.press('Escape');const editor = await openVolumeWorkspaceEditor(page);- await replaceEditorText(page, editor, 'local draft');+ await setCodeMirrorValue(editor, 'local draft');await page.getByRole('tab', { name: 'Backups', exact: true }).click();const backupRow = page.getByRole('row').filter({ hasText: BACKUP_ID }).first();await backupRow.getByRole('button', { name: 'Open menu' }).click();diff --git a/tests/spec/customization.spec.ts b/tests/spec/customization.spec.tsindex 0a003ccf9..3b994fd1d 100644--- a/tests/spec/customization.spec.ts+++ b/tests/spec/customization.spec.ts@@ -1,5 +1,5 @@-import { waitForDialogReady } from '../utils/playwright.util';-import { expect, test, type Locator, type Page } from '../fixtures/test.fixture';+import { setCodeMirrorValue, waitForDialogReady } from '../utils/playwright.util';+import { expect, test, type Page } from '../fixtures/test.fixture';import { removeApiResource, readApiData } from '../utils/fetch.util';import { openRowActionsMenu } from '../utils/table-actions.util';@@ -34,14 +34,6 @@ type ContainerDetails = {config: { env?: string[] };};-async function setCodeMirrorValue(page: Page, editor: Locator, text: string) {- const content = editor.locator('.cm-content').first();- await expect(content).toBeVisible();- await content.click({ position: { x: 10, y: 10 } });- await content.press('ControlOrMeta+A');- await page.keyboard.insertText(text);-}-async function listVariables(page: Page): Promise<GlobalVariable[]> {return readApiData<GlobalVariable[]>(await page.request.get('/api/variables'),@@ -220,12 +212,12 @@ test('manages variables and deploys an edited template with real substitution',const editors = page.locator('.cm-editor').filter({ visible: true });const composeEditor = editors.first();const envEditor = editors.nth(1);- await setCodeMirrorValue(page, composeEditor, 'services:\n broken: [\n');- await setCodeMirrorValue(page, envEditor, 'NOT VALID ENV');+ await setCodeMirrorValue(composeEditor, 'services:\n broken: [\n');+ await setCodeMirrorValue(envEditor, 'NOT VALID ENV');await expect(page.getByRole('button', { name: 'Create Template', exact: true })).toBeDisabled();- await setCodeMirrorValue(page, composeEditor, composeContent);- await setCodeMirrorValue(page, envEditor, 'TEMPLATE_LOCAL=value\n');+ await setCodeMirrorValue(composeEditor, composeContent);+ await setCodeMirrorValue(envEditor, 'TEMPLATE_LOCAL=value\n');const createTemplateButton = page.getByRole('button', { name: 'Create Template', exact: true });await expect(createTemplateButton).toBeEnabled({ timeout: 20_000 });const templateCreateResponsePromise = page.waitForResponse(diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.tsindex eeb6684d3..6368fcbe4 100644--- a/tests/spec/project.spec.ts+++ b/tests/spec/project.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Locator, type Page, type Response } from '../fixtures/test.fixture';+import { test, expect, type Page, type Response } from '../fixtures/test.fixture';import {readApiData,removeApiResource,@@ -9,6 +9,7 @@ import type { Activity } from '../types/activity.type';import { Project, ProjectStatusCounts } from 'types/project.type';import { TEST_COMPOSE_YAML, TEST_ENV_FILE } from '../setup/project.data';import { openRowActionsMenu } from '../utils/table-actions.util';+import { getCodeMirrorValue, setCodeMirrorValue } from '../utils/playwright.util';const ROUTES = {page: '/projects',@@ -28,27 +29,6 @@ async function navigateToProjects(page: Page) {await page.waitForLoadState('load');}-async function setCodeMirrorValue(page: Page, editor: Locator, text: string) {- const content = editor.locator('.cm-content').first();- await expect(content).toBeVisible();- await content.click({ position: { x: 10, y: 10 } });- await content.press('ControlOrMeta+A');- await page.keyboard.insertText(text);-}--async function getCodeMirrorValue(editor: Locator) {- const content = editor.locator('.cm-content').first();- await expect(content).toBeVisible();- return content.evaluate((node) => {- const lineNodes = Array.from(node.querySelectorAll('.cm-line'));- if (lineNodes.length > 0) {- return lineNodes.map((line) => line.textContent ?? '').join('\n');- }-- return (node as { textContent?: string | null }).textContent ?? '';- });-}-async function clickProjectsPageUpdateAction(page: Page) {const updateProjectsButton = page.getByRole('button', { name: 'Update Projects', exact: true })@@ -166,8 +146,8 @@ async function createProjectViaUI(await expect(composeEditor).toBeVisible();await expect(envEditor).toBeVisible();- await setCodeMirrorValue(page, composeEditor, composeContent);- await setCodeMirrorValue(page, envEditor, envFile);+ await setCodeMirrorValue(composeEditor, composeContent);+ await setCodeMirrorValue(envEditor, envFile);await expect.poll(async () => (await getCodeMirrorValue(composeEditor)).trimEnd(), {message: 'Expected compose editor to contain the exact test compose fixture before creation'@@ -513,9 +493,9 @@ test.describe('New Compose Project Page', () => {const composeEditor = page.locator('.cm-editor').filter({ visible: true }).first();const composeContent = composeEditor.locator('.cm-content').first();- await expect(composeContent).toBeVisible();+ await setCodeMirrorValue(composeEditor, '');await composeContent.click({ position: { x: 10, y: 10 } });- await composeContent.press('ControlOrMeta+A');+ await expect(composeContent).toBeFocused();await page.keyboard.type('services:', { delay: 0 });await page.keyboard.press('Enter');await page.keyboard.type('web:', { delay: 0 });@@ -574,10 +554,10 @@ test.describe('New Compose Project Page', () => {const composeEditor = page.locator('.cm-editor').filter({ visible: true }).first();await expect(composeEditor).toBeVisible();- await setCodeMirrorValue(page, composeEditor, 'services:\n\tredis:\n\t\timage: redis:latest\n');+ await setCodeMirrorValue(composeEditor, 'services:\n\tredis:\n\t\timage: redis:latest\n');await expect(page.locator('button[data-action="create"]')).toHaveCount(0);- await setCodeMirrorValue(page, composeEditor, TEST_COMPOSE_YAML);+ await setCodeMirrorValue(composeEditor, TEST_COMPOSE_YAML);const createButton = page.locator('button[data-action="create"]');await expect(createButton).toBeVisible();await expect(createButton).toBeEnabled();@@ -596,11 +576,11 @@ test.describe('New Compose Project Page', () => {await expect(composeEditor).toBeVisible();await expect(envEditor).toBeVisible();- await setCodeMirrorValue(page, composeEditor, TEST_COMPOSE_YAML);- await setCodeMirrorValue(page, envEditor, 'NOT VALID LINE');+ await setCodeMirrorValue(composeEditor, TEST_COMPOSE_YAML);+ await setCodeMirrorValue(envEditor, 'NOT VALID LINE');await expect(page.locator('button[data-action="create"]')).toHaveCount(0);- await setCodeMirrorValue(page, envEditor, TEST_ENV_FILE);+ await setCodeMirrorValue(envEditor, TEST_ENV_FILE);const createButton = page.locator('button[data-action="create"]');await expect(createButton).toBeVisible();await expect(createButton).toBeEnabled();@@ -622,7 +602,7 @@ test.describe('New Compose Project Page', () => {const composeEditor = page.locator('.cm-editor').filter({ visible: true }).first();await expect(composeEditor).toBeVisible();- await setCodeMirrorValue(page, composeEditor, TEST_COMPOSE_YAML);+ await setCodeMirrorValue(composeEditor, TEST_COMPOSE_YAML);await expect(composeEditor).toContainText('nginx');await expect.poll(async () => (await getCodeMirrorValue(composeEditor)).trimEnd(), {@@ -633,7 +613,7 @@ test.describe('New Compose Project Page', () => {const envEditor = page.locator('.cm-editor').filter({ visible: true }).nth(1);await expect(envEditor).toBeVisible();- await setCodeMirrorValue(page, envEditor, envFile);+ await setCodeMirrorValue(envEditor, envFile);await expect(envEditor).toContainText('nginx');await page.route('/api/environments/*/projects', async (route) => {@@ -1142,7 +1122,7 @@ test.describe('GitOps Managed Project', () => {const updatedEnv = `${originalEnv.trimEnd()}\n${marker}=1\n`;await expect(envContent).not.toHaveAttribute('aria-readonly', 'true');- await setCodeMirrorValue(page, envEditor, updatedEnv);+ await setCodeMirrorValue(envEditor, updatedEnv);await expect(envEditor).toContainText(marker);await expect(page.getByRole('button', { name: 'Save', exact: true }).first()).toBeEnabled();@@ -1522,7 +1502,7 @@ test.describe('Project Detail Page', () => {const marker = `ARCANE_TREE_SAVE_${Date.now()}`;const originalCompose = await getCodeMirrorValue(treeComposeEditor);const updatedCompose = `${originalCompose.trimEnd()}\n# ${marker}\n`;- await setCodeMirrorValue(page, treeComposeEditor, updatedCompose);+ await setCodeMirrorValue(treeComposeEditor, updatedCompose);const saveButton = page.getByRole('button', { name: 'Save', exact: true }).first();await expect(saveButton).toBeVisible();diff --git a/tests/spec/rbac.spec.ts b/tests/spec/rbac.spec.tsindex 0627df3f5..177d5bee3 100644--- a/tests/spec/rbac.spec.ts+++ b/tests/spec/rbac.spec.ts@@ -11,6 +11,7 @@ import {import { TEST_COMPOSE_YAML } from '../setup/project.data';import { removeApiResource, readApiData } from '../utils/fetch.util';import { openRowActionsMenu } from '../utils/table-actions.util';+import { setCodeMirrorValue } from '../utils/playwright.util';type TestRole = {id: string;@@ -785,11 +786,7 @@ test('administers scoped identities and enforces their browser access immediatel.locator('.cm-editor').filter({ visible: true }).first();- const composeContent = composeEditor.locator('.cm-content').first();- await expect(composeContent).toBeVisible();- await composeContent.click({ position: { x: 10, y: 10 } });- await composeContent.press('ControlOrMeta+A');- await environmentAdminPage.keyboard.insertText(TEST_COMPOSE_YAML);+ await setCodeMirrorValue(composeEditor, TEST_COMPOSE_YAML);await expect(environmentAdminPage.locator('button[data-action="create"]')).toBeVisible();environmentAdminPage.off('request', recordOptionalRequest);expect(optionalRequests).toEqual([]);diff --git a/tests/utils/playwright.util.ts b/tests/utils/playwright.util.tsindex 129c8abbf..d0d000bc6 100644--- a/tests/utils/playwright.util.ts+++ b/tests/utils/playwright.util.ts@@ -43,3 +43,51 @@ export async function waitForDialogReady(dialog: Locator) {).toBe(true);}++// Accepts either a `.cm-editor` root or its `.cm-content` element.+function codeMirrorContent(editor: Locator) {+ return editor+ .locator('.cm-content')+ .first()+ .or(editor.and(editor.page().locator('.cm-content')))+ .first();+}++function normalizeEditorText(text: string) {+ return text.replace(/\r/g, '').trimEnd();+}++export async function getCodeMirrorValue(editor: Locator) {+ const content = codeMirrorContent(editor);+ await expect(content).toBeVisible();+ return content.evaluate((node) => {+ const lineNodes = Array.from(node.querySelectorAll('.cm-line'));+ if (lineNodes.length > 0) {+ return lineNodes.map((line) => line.textContent ?? '').join('\n');+ }+ return node.textContent ?? '';+ });+}++// Replaces the editor document. Select-all can race the editor's focus and+// lint re-renders, so the clear step is verified and retried before typing.+export async function setCodeMirrorValue(editor: Locator, text: string) {+ const content = codeMirrorContent(editor);+ await expect(content).toBeVisible();+ await expect(content).not.toHaveAttribute('aria-readonly', 'true');+ await expect(async () => {+ await content.click({ position: { x: 10, y: 10 } });+ await expect(content).toBeFocused();+ await content.press('ControlOrMeta+A');+ await content.press('Backspace');+ expect(await getCodeMirrorValue(editor)).toBe('');+ }).toPass({ timeout: 10_000 });+ if (text.length > 0) {+ await content.page().keyboard.insertText(text);+ }+ await expect+ .poll(async () => normalizeEditorText(await getCodeMirrorValue(editor)), {+ message: 'Editor content must match the inserted text'+ })+ .toBe(normalizeEditorText(text));+}diff --git a/types/container/container.go b/types/container/container.goindex 23976928a..29a0c4720 100644--- a/types/container/container.go+++ b/types/container/container.go@@ -1065,6 +1065,11 @@ type Details struct {// Required: trueAutoUpdateEnabled bool `json:"autoUpdateEnabled"`+ // UpdateInfo is the stored update check matching this container's current policy.+ //+ // Required: false+ UpdateInfo *imagetypes.UpdateInfo `json:"updateInfo,omitempty"`+// ActivityID is the background activity that tracked the action returning these details.//// Required: falsediff --git a/types/project/project.go b/types/project/project.goindex 5390af89e..c27f8a4de 100644--- a/types/project/project.go+++ b/types/project/project.go@@ -166,6 +166,9 @@ type RuntimeService struct {// ContainerLabels carries runtime policy inputs for server-side update aggregation.ContainerLabels map[string]string `json:"-"`+ // ImageID is the runtime image ID used to match image-level update checks.+ ImageID string `json:"-"`+// Name is the service name from the compose file.//// Required: true