Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: upgrade all environments button (#2941)
Kyle Mendellb58621877155
diff --git a/backend/api/api.go b/backend/api/api.goindex 9fe9934e4..93c4e6d9c 100644--- a/backend/api/api.go+++ b/backend/api/api.go@@ -304,7 +304,7 @@ func registerHandlersInternal(api huma.API, svc *di.Services, handlerAppCtx handhandlers.RegisterNotifications(api, svc.Notification, cfg)handlers.RegisterUpdater(api, svc.Updater, handlerAppCtx)handlers.RegisterCustomize(api, svc.CustomizeSearch)- handlers.RegisterSystem(api, svc.Docker, svc.System, svc.SystemUpgrade, cfg, svc.Activity, handlerAppCtx)+ handlers.RegisterSystem(api, svc.Docker, svc.System, svc.SystemUpgrade, svc.Environment, cfg, svc.Activity, handlerAppCtx)handlers.RegisterDiagnostics(api, svc.Diagnostics)handlers.RegisterGitRepositories(api, svc.GitRepository)handlers.RegisterGitOpsSyncs(api, svc.GitOpsSync)diff --git a/backend/api/handlers/system.go b/backend/api/handlers/system.goindex 389c0604d..f751b638a 100644--- a/backend/api/handlers/system.go+++ b/backend/api/handlers/system.go@@ -10,6 +10,7 @@ import (humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"@@ -25,12 +26,13 @@ import (// SystemHandler handles system management endpoints.type SystemHandler struct {- dockerService *services.DockerClientService- systemService *services.SystemService- upgradeService *services.SystemUpgradeService- activityService *services.ActivityService- cfg *config.Config- appCtx context.Context+ dockerService *services.DockerClientService+ systemService *services.SystemService+ upgradeService *services.SystemUpgradeService+ environmentService *services.EnvironmentService+ activityService *services.ActivityService+ cfg *config.Config+ appCtx context.Context}// --- Input/Output Types ---@@ -116,16 +118,33 @@ type TriggerUpgradeOutput struct {Body base.ApiResponse[base.MessageResponse]}+type TriggerUpdateAllInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type TriggerUpdateAllOutput struct {+ Body base.ApiResponse[models.EnvironmentUpdateJob]+}++type UpdateAllStatusInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type UpdateAllStatusOutput struct {+ Body base.ApiResponse[models.EnvironmentUpdateJob]+}+// RegisterSystem registers system management endpoints using Huma.// Note: WebSocket endpoints (stats) remain in the Gin handler.-func RegisterSystem(api huma.API, dockerService *services.DockerClientService, systemService *services.SystemService, upgradeService *services.SystemUpgradeService, cfg *config.Config, activityService *services.ActivityService, appCtx ActivityAppContext) {+func RegisterSystem(api huma.API, dockerService *services.DockerClientService, systemService *services.SystemService, upgradeService *services.SystemUpgradeService, environmentService *services.EnvironmentService, cfg *config.Config, activityService *services.ActivityService, appCtx ActivityAppContext) {h := &SystemHandler{- dockerService: dockerService,- systemService: systemService,- upgradeService: upgradeService,- activityService: activityService,- cfg: cfg,- appCtx: appCtx.contextInternal(),+ dockerService: dockerService,+ systemService: systemService,+ upgradeService: upgradeService,+ environmentService: environmentService,+ activityService: activityService,+ cfg: cfg,+ appCtx: appCtx.contextInternal(),}huma.Register(api, huma.Operation{@@ -254,6 +273,43 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s},Middlewares: humamw.RequirePermission(api, authz.PermSystemUpgrade),}, h.TriggerUpgrade)++ huma.Register(api, huma.Operation{+ OperationID: "trigger-update-all",+ Method: http.MethodPost,+ Path: "/environments/{id}/system/upgrade/all",+ Summary: "Update all environments",+ Description: "Upgrade every Arcane environment, starting with the manager",+ DefaultStatus: http.StatusAccepted,+ Tags: []string{"System"},+ Security: []map[string][]string{+ {"BearerAuth": {}},+ {"ApiKeyAuth": {}},+ },+ Middlewares: humamw.RequirePermission(api, authz.PermSystemUpgrade),+ }, h.TriggerUpdateAll)++ huma.Register(api, huma.Operation{+ OperationID: "update-all-status",+ Method: http.MethodGet,+ Path: "/environments/{id}/system/upgrade/all/status",+ Summary: "Get update-all status",+ Description: "Get the status of the latest update-all-environments job",+ Tags: []string{"System"},+ Security: []map[string][]string{+ {"BearerAuth": {}},+ {"ApiKeyAuth": {}},+ },+ Middlewares: humamw.RequirePermission(api, authz.PermSystemRead),+ }, h.GetUpdateAllStatus)+}++// rejectIfAgentModeInternal blocks manager-only operations when running as an agent.+func (h *SystemHandler) rejectIfAgentModeInternal() error {+ if h.cfg != nil && h.cfg.AgentMode {+ return huma.Error400BadRequest("update-all is managed on the Arcane manager")+ }+ return nil}// Health checks if the Docker daemon is responsive.@@ -539,3 +595,65 @@ func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgrad},}, nil}++// TriggerUpdateAll starts a fleet-wide update, upgrading the manager first and then+// the remote agents (the latter resume after the manager restarts).+func (h *SystemHandler) TriggerUpdateAll(ctx context.Context, input *TriggerUpdateAllInput) (*TriggerUpdateAllOutput, error) {+ if h.upgradeService == nil || h.environmentService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := h.rejectIfAgentModeInternal(); err != nil {+ return nil, err+ }++ user, err := requireUserInternal(ctx)+ if err != nil {+ return nil, err+ }++ slog.Info("Update-all environments triggered", "user", user.Username, "userId", user.ID)++ // Use a runtime context so the agents phase can outlive the request when the+ // manager is already up to date.+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)++ job, err := h.upgradeService.StartUpdateAll(runtimeCtx, *user, h.environmentService)+ if err != nil {+ if common.IsUpdateAllInProgressError(err) {+ return nil, huma.Error409Conflict(err.Error())+ }+ return nil, huma.Error500InternalServerError((&common.UpgradeTriggerError{Err: err}).Error())+ }++ return &TriggerUpdateAllOutput{+ Body: base.ApiResponse[models.EnvironmentUpdateJob]{+ Success: true,+ Data: *job,+ },+ }, nil+}++// GetUpdateAllStatus returns the latest update-all job for live progress polling.+func (h *SystemHandler) GetUpdateAllStatus(ctx context.Context, input *UpdateAllStatusInput) (*UpdateAllStatusOutput, error) {+ if h.upgradeService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := h.rejectIfAgentModeInternal(); err != nil {+ return nil, err+ }++ job, err := h.upgradeService.GetLatestUpdateAllJob(ctx)+ if err != nil {+ return nil, huma.Error500InternalServerError(err.Error())+ }+ if job == nil {+ return nil, huma.Error404NotFound("no update-all job found")+ }++ return &UpdateAllStatusOutput{+ Body: base.ApiResponse[models.EnvironmentUpdateJob]{+ Success: true,+ Data: *job,+ },+ }, nil+}diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.goindex 90d39d371..bcd65df28 100644--- a/backend/internal/bootstrap/jobs_bootstrap.go+++ b/backend/internal/bootstrap/jobs_bootstrap.go@@ -33,6 +33,13 @@ func registerJobs(appCtx context.Context, newScheduler *pkg_scheduler.JobSchedul}}+ // Resume a fleet-wide update-all job interrupted by the manager's own upgrade+ // restart (manager only). Runs off the app context so it can upgrade agents+ // without blocking bootstrap.+ if !appConfig.AgentMode && appServices.SystemUpgrade != nil && appServices.Environment != nil {+ go appServices.SystemUpgrade.ResumeUpdateAllOnStartup(appCtx, appServices.Environment)+ }+newScheduler.RegisterJob(jobs.AutoUpdate)newScheduler.RegisterJob(jobs.ImagePolling)newScheduler.RegisterJob(jobs.DockerClientRefresh)diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex 64dd048aa..60ccc9129 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -1091,6 +1091,16 @@ func IsUpgradeInProgressError(err error) bool {return isErrorTypeInternal[*UpgradeInProgressError](err)}+type UpdateAllInProgressError struct{}++func (e *UpdateAllInProgressError) Error() string {+ return "an update-all job is already in progress"+}++func IsUpdateAllInProgressError(err error) bool {+ return isErrorTypeInternal[*UpdateAllInProgressError](err)+}+type DockerSocketAccessError struct{}func (e *DockerSocketAccessError) Error() string {diff --git a/backend/internal/di/wire_gen.go b/backend/internal/di/wire_gen.goindex 4734de85d..3cff01377 100644--- a/backend/internal/di/wire_gen.go+++ b/backend/internal/di/wire_gen.go@@ -59,7 +59,7 @@ func InitializeServices(ctx context.Context, db *database.DB, cfg *config.ConfigtemplateService := services.NewTemplateService(ctx, db, httpClient, settingsService)systemService := services.NewSystemService(db, dockerClientService, containerService, imageService, volumeService, networkService, settingsService, activityService)versionService := provideVersionServiceInternal(httpClient, cfg, containerRegistryService, dockerClientService, imageUpdateService)- systemUpgradeService := services.NewSystemUpgradeService(dockerClientService, versionService, eventService, settingsService)+ systemUpgradeService := services.NewSystemUpgradeService(db, dockerClientService, versionService, eventService, settingsService)diagnosticsService := services.NewDiagnosticsService()updaterService := provideUpdaterServiceInternal(db, settingsService, dockerClientService, projectService, imageUpdateService, containerRegistryService, eventService, imageService, notificationService, systemUpgradeService, activityService)federatedCredentialService := provideFederatedCredentialServiceInternal(db, authService, userService, settingsService, eventService, httpClient, roleService)diff --git a/backend/internal/models/environment_update_job.go b/backend/internal/models/environment_update_job.gonew file mode 100644index 000000000..74a63d70c--- /dev/null+++ b/backend/internal/models/environment_update_job.go@@ -0,0 +1,106 @@+package models++import (+ "database/sql/driver"+ "encoding/json"+ "fmt"+ "time"+)++// EnvironmentUpdateJobStatus is the lifecycle status of a fleet-wide "update all+// environments" job.+type EnvironmentUpdateJobStatus string++const (+ // EnvironmentUpdateJobStatusPendingRestart means the manager has triggered its+ // own self-upgrade and is waiting to restart on the new version, after which+ // the job resumes to upgrade the remote agents.+ EnvironmentUpdateJobStatusPendingRestart EnvironmentUpdateJobStatus = "pending_restart"+ // EnvironmentUpdateJobStatusRunning means the agents phase is in progress.+ EnvironmentUpdateJobStatusRunning EnvironmentUpdateJobStatus = "running"+ // EnvironmentUpdateJobStatusCompleted means every environment has been processed.+ EnvironmentUpdateJobStatusCompleted EnvironmentUpdateJobStatus = "completed"+ // EnvironmentUpdateJobStatusFailed means the job stopped before completing.+ EnvironmentUpdateJobStatusFailed EnvironmentUpdateJobStatus = "failed"+)++// EnvironmentUpdateResultStatus is the per-environment outcome within a job.+type EnvironmentUpdateResultStatus string++const (+ // EnvironmentUpdateResultStatusPending is the initial state recorded for the+ // manager entry while its self-upgrade is in flight.+ EnvironmentUpdateResultStatusPending EnvironmentUpdateResultStatus = "pending"+ // EnvironmentUpdateResultStatusUpdated means the upgrade was triggered and the+ // new version was confirmed.+ EnvironmentUpdateResultStatusUpdated EnvironmentUpdateResultStatus = "updated"+ // EnvironmentUpdateResultStatusTriggered means the upgrade was triggered but not+ // confirmed within the wait window (still likely succeeding in the background).+ EnvironmentUpdateResultStatusTriggered EnvironmentUpdateResultStatus = "triggered"+ // EnvironmentUpdateResultStatusSkippedUpToDate means no update was available.+ EnvironmentUpdateResultStatusSkippedUpToDate EnvironmentUpdateResultStatus = "skipped_up_to_date"+ // EnvironmentUpdateResultStatusSkippedOffline means the environment was unreachable.+ EnvironmentUpdateResultStatusSkippedOffline EnvironmentUpdateResultStatus = "skipped_offline"+ // EnvironmentUpdateResultStatusFailed means the upgrade trigger failed.+ EnvironmentUpdateResultStatusFailed EnvironmentUpdateResultStatus = "failed"+)++// EnvironmentUpdateResult is the outcome for a single environment within a job.+// The manager appears as the first entry with EnvironmentID "0".+type EnvironmentUpdateResult struct {+ EnvironmentID string `json:"environmentId"`+ EnvironmentName string `json:"environmentName"`+ Status EnvironmentUpdateResultStatus `json:"status"`+ FromVersion string `json:"fromVersion,omitempty"`+ ToVersion string `json:"toVersion,omitempty"`+ Error string `json:"error,omitempty"`+}++// EnvironmentUpdateResults is a JSON-serialized slice of per-environment results,+// stored in a single TEXT column.+//+//nolint:recvcheck+type EnvironmentUpdateResults []EnvironmentUpdateResult++func (r EnvironmentUpdateResults) Value() (driver.Value, error) {+ if r == nil {+ return nil, nil+ }+ return json.Marshal(r)+}++func (r *EnvironmentUpdateResults) Scan(value any) error {+ if value == nil {+ *r = nil+ return nil+ }+ switch v := value.(type) {+ case []byte:+ return json.Unmarshal(v, r)+ case string:+ return json.Unmarshal([]byte(v), r)+ default:+ return fmt.Errorf("unsupported scan type for EnvironmentUpdateResults: %T", value)+ }+}++// EnvironmentUpdateJob is a persisted fleet-wide update orchestration record. It+// survives the manager's self-upgrade restart so the agents phase can resume on+// the next boot. See [EnvironmentUpdateJobStatus].+type EnvironmentUpdateJob struct {+ BaseModel++ Status EnvironmentUpdateJobStatus `json:"status" gorm:"column:status"`+ UserID string `json:"userId" gorm:"column:user_id"`+ Username string `json:"username" gorm:"column:username"`+ ManagerVersionAtStart string `json:"managerVersionAtStart" gorm:"column:manager_version_at_start"`+ ManagerDigestAtStart string `json:"managerDigestAtStart" gorm:"column:manager_digest_at_start"`+ ManagerTargetVersion string `json:"managerTargetVersion" gorm:"column:manager_target_version"`+ Results EnvironmentUpdateResults `json:"results,omitempty" gorm:"column:results;type:text"`+ Error *string `json:"error,omitempty" gorm:"column:error"`+ CompletedAt *time.Time `json:"completedAt,omitempty" gorm:"column:completed_at"`+}++func (EnvironmentUpdateJob) TableName() string {+ return "environment_update_jobs"+}diff --git a/backend/internal/services/system_upgrade_service.go b/backend/internal/services/system_upgrade_service.goindex e00f857d5..b97625951 100644--- a/backend/internal/services/system_upgrade_service.go+++ b/backend/internal/services/system_upgrade_service.go@@ -5,6 +5,7 @@ import ("errors""fmt""log/slog"+ "net/http""os""slices""strings"@@ -12,11 +13,13 @@ import ("time""github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"vuln "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln"+ "github.com/getarcaneapp/arcane/types/v2/version"containertypes "github.com/moby/moby/api/types/container"mounttypes "github.com/moby/moby/api/types/mount""github.com/moby/moby/client"@@ -28,6 +31,8 @@ const defaultArcaneUpgraderImageInternal = "ghcr.io/getarcaneapp/arcane:latest"type SystemUpgradeService struct {upgrading atomic.Bool+ updatingAll atomic.Bool+ db *database.DBdockerService *DockerClientServiceversionService *VersionServiceeventService *EventService@@ -41,12 +46,14 @@ type upgraderRuntimeOptionsInternal struct {}func NewSystemUpgradeService(+ db *database.DB,dockerService *DockerClientService,versionService *VersionService,eventService *EventService,settingsService *SettingsService,) *SystemUpgradeService {return &SystemUpgradeService{+ db: db,dockerService: dockerService,versionService: versionService,eventService: eventService,@@ -396,3 +403,380 @@ func (s *SystemUpgradeService) findArcaneContainerInternal(ctx context.Context,return containertypes.InspectResponse{}, &common.ArcaneContainerNotFoundError{}}++// --- Fleet-wide "update all environments" orchestration ---+//+// The manager upgrades itself first, which recreates its own container. Because+// the browser loses the backend across that restart, the orchestration is a+// persisted EnvironmentUpdateJob: StartUpdateAll triggers the manager self-upgrade+// and leaves the job in pending_restart; on the next boot ResumeUpdateAllOnStartup+// picks the job back up and upgrades each remote agent sequentially.++const (+ localEnvironmentIDInternal = "0"+ managerEnvironmentNameInternal = "Local"++ updateAllStaleThresholdInternal = time.Hour+ updateAllAgentRequestTimeoutInternal = 15 * time.Second+ updateAllConfirmPollIntervalInternal = 10 * time.Second+ updateAllConfirmTimeoutInternal = 2 * time.Minute+ updateAllErrorMaxLenInternal = 500+)++// StartUpdateAll begins a fleet-wide update. If the manager has an update available+// it self-upgrades first (job left pending_restart, resumed at next boot); otherwise+// the agents phase runs immediately in the background.+func (s *SystemUpgradeService) StartUpdateAll(ctx context.Context, user models.User, env *EnvironmentService) (*models.EnvironmentUpdateJob, error) {+ // Guard the check-then-create against concurrent callers (e.g. a double-click).+ // A dedicated flag rather than s.upgrading, because the manager branch below+ // calls TriggerUpgradeViaCLI which acquires s.upgrading itself. The persisted+ // job row is the durable guard once committed; this only closes the in-process+ // window before that row exists.+ if !s.updatingAll.CompareAndSwap(false, true) {+ return nil, &common.UpdateAllInProgressError{}+ }+ defer s.updatingAll.Store(false)++ active, err := s.activeUpdateAllJobInternal(ctx)+ if err != nil {+ return nil, fmt.Errorf("check for active update-all job: %w", err)+ }+ if active != nil {+ return nil, &common.UpdateAllInProgressError{}+ }++ info := s.versionService.GetAppVersionInfo(ctx)++ managerResult := models.EnvironmentUpdateResult{+ EnvironmentID: localEnvironmentIDInternal,+ EnvironmentName: managerEnvironmentNameInternal,+ FromVersion: info.CurrentVersion,+ }++ job := &models.EnvironmentUpdateJob{+ UserID: user.ID,+ Username: user.Username,+ ManagerVersionAtStart: info.CurrentVersion,+ ManagerDigestAtStart: info.CurrentDigest,+ ManagerTargetVersion: updateAllTargetVersionInternal(info),+ }++ if info.UpdateAvailable {+ managerResult.Status = models.EnvironmentUpdateResultStatusPending+ managerResult.ToVersion = job.ManagerTargetVersion+ job.Status = models.EnvironmentUpdateJobStatusPendingRestart+ job.Results = models.EnvironmentUpdateResults{managerResult}++ if err := s.db.WithContext(ctx).Create(job).Error; err != nil {+ return nil, fmt.Errorf("create update-all job: %w", err)+ }++ // Trigger the manager self-upgrade. The manager restarts shortly after and+ // the job resumes on the next boot via ResumeUpdateAllOnStartup.+ if err := s.TriggerUpgradeViaCLI(ctx, user, updatertypes.SelfUpdateTarget{}); err != nil {+ s.markUpdateAllFailedInternal(ctx, job, fmt.Sprintf("manager upgrade trigger failed: %v", err))+ return nil, err+ }++ slog.InfoContext(ctx, "Update-all started; manager self-upgrade triggered", "jobId", job.ID, "user", user.Username)+ return job, nil+ }++ // Manager already up to date — go straight to the agents phase.+ managerResult.Status = models.EnvironmentUpdateResultStatusSkippedUpToDate+ job.Status = models.EnvironmentUpdateJobStatusRunning+ job.Results = models.EnvironmentUpdateResults{managerResult}++ if err := s.db.WithContext(ctx).Create(job).Error; err != nil {+ return nil, fmt.Errorf("create update-all job: %w", err)+ }++ slog.InfoContext(ctx, "Update-all started; manager up to date, upgrading agents", "jobId", job.ID, "user", user.Username)+ go s.runAgentsPhaseInternal(context.WithoutCancel(ctx), job.ID, env)++ return job, nil+}++// ResumeUpdateAllOnStartup is called once at manager startup. It transitions any+// non-terminal update-all job out of its waiting state and, when appropriate, runs+// the agents phase. It is a no-op when there is nothing pending.+func (s *SystemUpgradeService) ResumeUpdateAllOnStartup(ctx context.Context, env *EnvironmentService) {+ job, err := s.activeUpdateAllJobInternal(ctx)+ if err != nil {+ slog.WarnContext(ctx, "Failed to load pending update-all job on startup", "error", err)+ return+ }+ if job == nil {+ return+ }++ // A job left running means the manager died mid-agents-phase; we can't safely+ // resume partial progress, so fail it.+ if job.Status == models.EnvironmentUpdateJobStatusRunning {+ s.markUpdateAllFailedInternal(ctx, job, "interrupted by manager restart")+ return+ }++ info := s.versionService.GetAppVersionInfo(ctx)+ action := resolveResumeActionInternal(job, info.CurrentVersion, info.CurrentDigest, time.Now())++ if action.markStale {+ s.markUpdateAllFailedInternal(ctx, job, "update-all job is stale; manager did not restart in time")+ return+ }++ s.recordManagerResultInternal(job, action.managerSucceeded, info.CurrentVersion)+ job.Status = models.EnvironmentUpdateJobStatusRunning+ if err := s.persistUpdateAllJobInternal(ctx, job); err != nil {+ slog.WarnContext(ctx, "Failed to mark resumed update-all job as running", "jobId", job.ID, "error", err)+ return+ }++ slog.InfoContext(ctx, "Resuming update-all job after manager restart", "jobId", job.ID, "managerUpgraded", action.managerSucceeded)+ s.runAgentsPhaseInternal(ctx, job.ID, env)+}++type resumeActionInternal struct {+ markStale bool+ managerSucceeded bool+}++// resolveResumeActionInternal is the pure decision for a resumed pending_restart+// job: stale if it has waited too long, otherwise the manager upgrade is considered+// successful when either the version or the digest changed from the at-start values+// (digest covers non-semver, digest-pinned installs).+func resolveResumeActionInternal(job *models.EnvironmentUpdateJob, currentVersion, currentDigest string, now time.Time) resumeActionInternal {+ if now.Sub(job.CreatedAt) > updateAllStaleThresholdInternal {+ return resumeActionInternal{markStale: true}+ }++ versionChanged := job.ManagerVersionAtStart != "" && currentVersion != job.ManagerVersionAtStart+ digestChanged := job.ManagerDigestAtStart != "" && currentDigest != job.ManagerDigestAtStart++ return resumeActionInternal{managerSucceeded: versionChanged || digestChanged}+}++// runAgentsPhaseInternal upgrades every online remote environment that has an update+// available, sequentially, persisting progress after each one so the status endpoint+// can report live progress.+func (s *SystemUpgradeService) runAgentsPhaseInternal(ctx context.Context, jobID string, env *EnvironmentService) {+ job, err := s.getUpdateAllJobByIDInternal(ctx, jobID)+ if err != nil || job == nil {+ slog.WarnContext(ctx, "update-all: failed to reload job for agents phase", "jobId", jobID, "error", err)+ return+ }++ envs, err := env.ListRemoteEnvironments(ctx)+ if err != nil {+ s.markUpdateAllFailedInternal(ctx, job, fmt.Sprintf("failed to list remote environments: %v", err))+ return+ }++ for _, remote := range envs {+ result := models.EnvironmentUpdateResult{+ EnvironmentID: remote.ID,+ EnvironmentName: remote.Name,+ }+ s.upgradeAgentInternal(ctx, env, remote.ID, &result)++ job.Results = append(job.Results, result)+ if err := s.persistUpdateAllJobInternal(ctx, job); err != nil {+ slog.WarnContext(ctx, "update-all: failed to persist progress", "jobId", job.ID, "environmentId", remote.ID, "error", err)+ }+ }++ completedAt := time.Now()+ job.Status = models.EnvironmentUpdateJobStatusCompleted+ job.CompletedAt = &completedAt+ if err := s.persistUpdateAllJobInternal(ctx, job); err != nil {+ slog.WarnContext(ctx, "update-all: failed to mark job completed", "jobId", job.ID, "error", err)+ }++ s.logUpdateAllEventInternal(ctx, job)+ slog.InfoContext(ctx, "Update-all job completed", "jobId", job.ID, "environments", len(job.Results))+}++// upgradeAgentInternal checks, triggers, and confirms a single remote environment's+// self-upgrade, recording the outcome on result.+func (s *SystemUpgradeService) upgradeAgentInternal(ctx context.Context, env *EnvironmentService, envID string, result *models.EnvironmentUpdateResult) {+ versionCtx, cancel := context.WithTimeout(ctx, updateAllAgentRequestTimeoutInternal)+ var info version.Info+ err := env.ProxyJSONRequest(versionCtx, envID, http.MethodGet, "/api/app-version", nil, &info)+ cancel()+ if err != nil {+ result.Status = models.EnvironmentUpdateResultStatusSkippedOffline+ result.Error = truncateUpdateAllErrorInternal(err)+ return+ }+ result.FromVersion = info.CurrentVersion++ if !info.UpdateAvailable {+ result.Status = models.EnvironmentUpdateResultStatusSkippedUpToDate+ return+ }+ result.ToVersion = updateAllTargetVersionInternal(&info)++ triggerCtx, cancel := context.WithTimeout(ctx, updateAllAgentRequestTimeoutInternal)+ resp, err := env.ExecuteRemoteRequest(triggerCtx, envID, http.MethodPost, "/api/environments/0/system/upgrade", nil)+ cancel()+ if err != nil {+ result.Status = models.EnvironmentUpdateResultStatusFailed+ result.Error = truncateUpdateAllErrorInternal(err)+ return+ }+ if err := resp.RequireSuccess(); err != nil {+ result.Status = models.EnvironmentUpdateResultStatusFailed+ result.Error = truncateUpdateAllErrorInternal(err)+ return+ }++ if s.confirmAgentUpgradedInternal(ctx, env, envID, info.CurrentVersion, info.CurrentDigest) {+ result.Status = models.EnvironmentUpdateResultStatusUpdated+ } else {+ // Upgrade fired but the new version was not confirmed within the wait window.+ result.Status = models.EnvironmentUpdateResultStatusTriggered+ }+}++// confirmAgentUpgradedInternal polls the agent's version until it changes from the+// pre-upgrade baseline or the wait window elapses.+func (s *SystemUpgradeService) confirmAgentUpgradedInternal(ctx context.Context, env *EnvironmentService, envID, baselineVersion, baselineDigest string) bool {+ deadline := time.Now().Add(updateAllConfirmTimeoutInternal)+ ticker := time.NewTicker(updateAllConfirmPollIntervalInternal)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return false+ case <-ticker.C:+ reqCtx, cancel := context.WithTimeout(ctx, updateAllAgentRequestTimeoutInternal)+ var info version.Info+ err := env.ProxyJSONRequest(reqCtx, envID, http.MethodGet, "/api/app-version", nil, &info)+ cancel()+ if err == nil {+ versionChanged := baselineVersion != "" && info.CurrentVersion != baselineVersion+ digestChanged := baselineDigest != "" && info.CurrentDigest != baselineDigest+ if versionChanged || digestChanged {+ return true+ }+ }+ if time.Now().After(deadline) {+ return false+ }+ }+ }+}++// GetLatestUpdateAllJob returns the most recently created update-all job, or nil.+func (s *SystemUpgradeService) GetLatestUpdateAllJob(ctx context.Context) (*models.EnvironmentUpdateJob, error) {+ var jobs []models.EnvironmentUpdateJob+ if err := s.db.WithContext(ctx).+ Order("created_at DESC").+ Limit(1).+ Find(&jobs).Error; err != nil {+ return nil, err+ }+ if len(jobs) == 0 {+ return nil, nil+ }+ return &jobs[0], nil+}++func (s *SystemUpgradeService) activeUpdateAllJobInternal(ctx context.Context) (*models.EnvironmentUpdateJob, error) {+ var jobs []models.EnvironmentUpdateJob+ if err := s.db.WithContext(ctx).+ Where("status IN ?", []string{+ string(models.EnvironmentUpdateJobStatusPendingRestart),+ string(models.EnvironmentUpdateJobStatusRunning),+ }).+ Order("created_at DESC").+ Limit(1).+ Find(&jobs).Error; err != nil {+ return nil, err+ }+ if len(jobs) == 0 {+ return nil, nil+ }+ return &jobs[0], nil+}++func (s *SystemUpgradeService) getUpdateAllJobByIDInternal(ctx context.Context, id string) (*models.EnvironmentUpdateJob, error) {+ var jobs []models.EnvironmentUpdateJob+ if err := s.db.WithContext(ctx).+ Where("id = ?", id).+ Limit(1).+ Find(&jobs).Error; err != nil {+ return nil, err+ }+ if len(jobs) == 0 {+ return nil, nil+ }+ return &jobs[0], nil+}++func (s *SystemUpgradeService) persistUpdateAllJobInternal(ctx context.Context, job *models.EnvironmentUpdateJob) error {+ return s.db.WithContext(ctx).Save(job).Error+}++func (s *SystemUpgradeService) markUpdateAllFailedInternal(ctx context.Context, job *models.EnvironmentUpdateJob, reason string) {+ completedAt := time.Now()+ job.Status = models.EnvironmentUpdateJobStatusFailed+ job.Error = &reason+ job.CompletedAt = &completedAt+ if err := s.persistUpdateAllJobInternal(ctx, job); err != nil {+ slog.WarnContext(ctx, "update-all: failed to mark job failed", "jobId", job.ID, "error", err)+ }+ slog.WarnContext(ctx, "Update-all job failed", "jobId", job.ID, "reason", reason)+}++// recordManagerResultInternal updates the manager (env "0") entry after the restart.+func (s *SystemUpgradeService) recordManagerResultInternal(job *models.EnvironmentUpdateJob, succeeded bool, currentVersion string) {+ for i := range job.Results {+ if job.Results[i].EnvironmentID != localEnvironmentIDInternal {+ continue+ }+ if succeeded {+ job.Results[i].Status = models.EnvironmentUpdateResultStatusUpdated+ job.Results[i].ToVersion = currentVersion+ } else {+ job.Results[i].Status = models.EnvironmentUpdateResultStatusFailed+ job.Results[i].Error = "manager version did not change after upgrade"+ }+ return+ }+}++func (s *SystemUpgradeService) logUpdateAllEventInternal(ctx context.Context, job *models.EnvironmentUpdateJob) {+ metadata := models.JSON{+ "action": "update_all_environments",+ "jobId": job.ID,+ "environments": len(job.Results),+ }+ if err := s.eventService.LogUserEvent(ctx, models.EventTypeSystemUpgrade, job.UserID, job.Username, metadata); err != nil {+ slog.WarnContext(ctx, "Failed to log update-all event", "jobId", job.ID, "error", err)+ }+}++// updateAllTargetVersionInternal picks the best human-readable target identifier:+// the newest version tag if known, otherwise the newest digest.+func updateAllTargetVersionInternal(info *version.Info) string {+ if info == nil {+ return ""+ }+ if info.NewestVersion != "" {+ return info.NewestVersion+ }+ return info.NewestDigest+}++func truncateUpdateAllErrorInternal(err error) string {+ if err == nil {+ return ""+ }+ msg := err.Error()+ if len(msg) > updateAllErrorMaxLenInternal {+ return msg[:updateAllErrorMaxLenInternal]+ }+ return msg+}diff --git a/backend/internal/services/system_upgrade_service_test.go b/backend/internal/services/system_upgrade_service_test.goindex a0ccca229..acd8e10e1 100644--- a/backend/internal/services/system_upgrade_service_test.go+++ b/backend/internal/services/system_upgrade_service_test.go@@ -15,7 +15,7 @@ import (// TestSystemUpgradeService_UpgradeFlag tests the upgrading flag behaviorfunc TestSystemUpgradeService_UpgradeFlag(t *testing.T) {- s := NewSystemUpgradeService(nil, nil, nil, nil)+ s := NewSystemUpgradeService(nil, nil, nil, nil, nil)// Initially should be falserequire.False(t, s.upgrading.Load())@@ -31,7 +31,7 @@ func TestSystemUpgradeService_UpgradeFlag(t *testing.T) {// TestSystemUpgradeService_Initialization tests proper initializationfunc TestSystemUpgradeService_Initialization(t *testing.T) {- s := NewSystemUpgradeService(nil, nil, nil, nil)+ s := NewSystemUpgradeService(nil, nil, nil, nil, nil)require.NotNil(t, s)require.False(t, s.upgrading.Load())@@ -55,7 +55,7 @@ func TestSystemUpgradeService_ErrorVariables(t *testing.T) {// TestSystemUpgradeService_UpgradingFlag_ConcurrentAccess tests upgrading flagfunc TestSystemUpgradeService_UpgradingFlag_ConcurrentAccess(t *testing.T) {- s := NewSystemUpgradeService(nil, nil, nil, nil)+ s := NewSystemUpgradeService(nil, nil, nil, nil, nil)// Test initial staterequire.False(t, s.upgrading.Load(), "upgrading flag should start as false")@@ -71,7 +71,7 @@ func TestSystemUpgradeService_UpgradingFlag_ConcurrentAccess(t *testing.T) {// TestSystemUpgradeService_CompareAndSwap tests atomic CompareAndSwap operationfunc TestSystemUpgradeService_CompareAndSwap(t *testing.T) {- s := NewSystemUpgradeService(nil, nil, nil, nil)+ s := NewSystemUpgradeService(nil, nil, nil, nil, nil)// Test successful CompareAndSwap from false to trueswapped := s.upgrading.CompareAndSwap(false, true)@@ -92,7 +92,7 @@ func TestSystemUpgradeService_CompareAndSwap(t *testing.T) {// TestSystemUpgradeService_Services tests that services are stored correctlyfunc TestSystemUpgradeService_Services(t *testing.T) {// Create upgrade service with nil services (valid for testing initialization)- s := NewSystemUpgradeService(nil, nil, nil, nil)+ s := NewSystemUpgradeService(nil, nil, nil, nil, nil)// Verify service is created and initialized properlyrequire.NotNil(t, s)@@ -101,7 +101,7 @@ func TestSystemUpgradeService_Services(t *testing.T) {// TestSystemUpgradeService_ConcurrentUpgradeAttempts tests that concurrent upgrade attempts are preventedfunc TestSystemUpgradeService_ConcurrentUpgradeAttempts(t *testing.T) {- s := NewSystemUpgradeService(nil, nil, nil, nil)+ s := NewSystemUpgradeService(nil, nil, nil, nil, nil)// Simulate first upgrade startingsuccess := s.upgrading.CompareAndSwap(false, true)@@ -132,7 +132,7 @@ func TestSystemUpgradeService_UpgradeInProgressError(t *testing.T) {// TestSystemUpgradeService_AtomicOperations tests atomic.Bool operationsfunc TestSystemUpgradeService_AtomicOperations(t *testing.T) {- s := NewSystemUpgradeService(nil, nil, nil, nil)+ s := NewSystemUpgradeService(nil, nil, nil, nil, nil)// Test Loadrequire.False(t, s.upgrading.Load())diff --git a/backend/internal/services/system_upgrade_update_all_test.go b/backend/internal/services/system_upgrade_update_all_test.gonew file mode 100644index 000000000..a7bdba857--- /dev/null+++ b/backend/internal/services/system_upgrade_update_all_test.go@@ -0,0 +1,71 @@+package services++import (+ "testing"+ "time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/models"+)++func TestUpdateAllResolveResumeAction(t *testing.T) {+ now := time.Now()++ newJob := func(createdAt time.Time, versionAtStart, digestAtStart string) *models.EnvironmentUpdateJob {+ job := &models.EnvironmentUpdateJob{+ ManagerVersionAtStart: versionAtStart,+ ManagerDigestAtStart: digestAtStart,+ }+ job.CreatedAt = createdAt+ return job+ }++ tests := []struct {+ name string+ job *models.EnvironmentUpdateJob+ currentVersion string+ currentDigest string+ wantStale bool+ wantManagerOK bool+ }{+ {+ name: "stale job is failed regardless of version",+ job: newJob(now.Add(-2*time.Hour), "1.0.0", "sha256:a"),+ currentVersion: "1.1.0",+ currentDigest: "sha256:b",+ wantStale: true,+ },+ {+ name: "version changed means manager upgraded",+ job: newJob(now.Add(-5*time.Minute), "1.0.0", "sha256:a"),+ currentVersion: "1.1.0",+ currentDigest: "sha256:a",+ wantManagerOK: true,+ },+ {+ name: "digest changed means manager upgraded (digest-pinned install)",+ job: newJob(now.Add(-5*time.Minute), "latest", "sha256:a"),+ currentVersion: "latest",+ currentDigest: "sha256:b",+ wantManagerOK: true,+ },+ {+ name: "nothing changed means manager upgrade did not take",+ job: newJob(now.Add(-5*time.Minute), "1.0.0", "sha256:a"),+ currentVersion: "1.0.0",+ currentDigest: "sha256:a",+ wantManagerOK: false,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := resolveResumeActionInternal(tt.job, tt.currentVersion, tt.currentDigest, now)+ if got.markStale != tt.wantStale {+ t.Fatalf("markStale = %v, want %v", got.markStale, tt.wantStale)+ }+ if !tt.wantStale && got.managerSucceeded != tt.wantManagerOK {+ t.Fatalf("managerSucceeded = %v, want %v", got.managerSucceeded, tt.wantManagerOK)+ }+ })+ }+}diff --git a/backend/resources/migrations/postgres/060_add_environment_update_jobs.sql b/backend/resources/migrations/postgres/060_add_environment_update_jobs.sqlnew file mode 100644index 000000000..b8ec9803d--- /dev/null+++ b/backend/resources/migrations/postgres/060_add_environment_update_jobs.sql@@ -0,0 +1,20 @@+-- +goose Up+CREATE TABLE environment_update_jobs (+ id TEXT PRIMARY KEY,+ created_at TIMESTAMPTZ NOT NULL,+ updated_at TIMESTAMPTZ,+ status TEXT NOT NULL,+ user_id TEXT,+ username TEXT,+ manager_version_at_start TEXT,+ manager_digest_at_start TEXT,+ manager_target_version TEXT,+ results TEXT,+ error TEXT,+ completed_at TIMESTAMPTZ+);++CREATE INDEX idx_environment_update_jobs_status ON environment_update_jobs(status);++-- +goose Down+DROP TABLE IF EXISTS environment_update_jobs;diff --git a/backend/resources/migrations/sqlite/060_add_environment_update_jobs.sql b/backend/resources/migrations/sqlite/060_add_environment_update_jobs.sqlnew file mode 100644index 000000000..db8e57344--- /dev/null+++ b/backend/resources/migrations/sqlite/060_add_environment_update_jobs.sql@@ -0,0 +1,20 @@+-- +goose Up+CREATE TABLE environment_update_jobs (+ id TEXT PRIMARY KEY,+ created_at DATETIME NOT NULL,+ updated_at DATETIME,+ status TEXT NOT NULL,+ user_id TEXT,+ username TEXT,+ manager_version_at_start TEXT,+ manager_digest_at_start TEXT,+ manager_target_version TEXT,+ results TEXT,+ error TEXT,+ completed_at DATETIME+);++CREATE INDEX idx_environment_update_jobs_status ON environment_update_jobs(status);++-- +goose Down+DROP TABLE IF EXISTS environment_update_jobs;diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex a8f5dacfa..2ed5e5b21 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -1316,6 +1316,21 @@"environments_new_agent_mtls_assets_unavailable": "Manager mTLS assets are not available. Showing the standard edge agent config instead.","environments_download_edge_ca": "Download Edge CA","environments_download_edge_ca_failed": "Failed to download Edge CA",+ "environments_update_all_button": "Update All",+ "environments_update_all_title": "Update all environments",+ "environments_update_all_message": "This upgrades Arcane itself on every environment, starting with this manager. The manager will restart if an update is available; environments that are offline or already up to date are skipped.",+ "environments_update_all_confirm": "Update All",+ "environments_update_all_manager_restarting": "Manager is restarting, reconnecting…",+ "environments_update_all_in_progress": "Updating environments…",+ "environments_update_all_completed": "All environments processed",+ "environments_update_all_failed": "Update all failed",+ "environments_update_all_trigger_failed": "Failed to start update all",+ "environments_update_all_status_pending": "Pending",+ "environments_update_all_status_updated": "Updated",+ "environments_update_all_status_triggered": "Update triggered",+ "environments_update_all_status_skipped_up_to_date": "Already up to date",+ "environments_update_all_status_skipped_offline": "Offline — skipped",+ "environments_update_all_status_failed": "Failed","environments_edge_control_plane_label": "Control Plane","environments_edge_polling_active": "Polling Active","environments_edge_polling_standby": "Polling Standby",diff --git a/frontend/src/lib/services/api/environment-upgrade-service.ts b/frontend/src/lib/services/api/environment-upgrade-service.tsdeleted file mode 100644index de9a5acd1..000000000--- a/frontend/src/lib/services/api/environment-upgrade-service.ts+++ /dev/null@@ -1,38 +0,0 @@-import { apiClient } from '../api-service';--export interface EnvironmentUpgradeCheckResponse {- canUpgrade: boolean;- error: boolean;- message: string;-}--export interface EnvironmentUpgradeResponse {- message: string;- success: boolean;- error?: string;-}--/**- * Check if a remote environment can perform a self-upgrade- * @param environmentId - The ID of the environment to check- * @returns Promise with upgrade availability status- */-async function checkEnvironmentUpgradeAvailable(environmentId: string): Promise<EnvironmentUpgradeCheckResponse> {- const res = await apiClient.get<EnvironmentUpgradeCheckResponse>(`/environments/${environmentId}/system/upgrade/check`);- return res.data;-}--/**- * Trigger a self-upgrade on a remote environment- * @param environmentId - The ID of the environment to upgrade- * @returns Promise with upgrade initiation result- */-async function triggerEnvironmentUpgrade(environmentId: string): Promise<EnvironmentUpgradeResponse> {- const res = await apiClient.post<EnvironmentUpgradeResponse>(`/environments/${environmentId}/system/upgrade`);- return res.data;-}--export default {- checkEnvironmentUpgradeAvailable,- triggerEnvironmentUpgrade-};diff --git a/frontend/src/lib/services/api/system-upgrade-service.ts b/frontend/src/lib/services/api/system-upgrade-service.tsindex 1016d8ce5..2e1578dc4 100644--- a/frontend/src/lib/services/api/system-upgrade-service.ts+++ b/frontend/src/lib/services/api/system-upgrade-service.ts@@ -17,6 +17,34 @@ export interface HealthCheckResult {healthy: boolean;}+export type UpdateAllEnvironmentStatus =+ | 'pending'+ | 'updated'+ | 'triggered'+ | 'skipped_up_to_date'+ | 'skipped_offline'+ | 'failed';++export interface UpdateAllEnvironmentResult {+ environmentId: string;+ environmentName: string;+ status: UpdateAllEnvironmentStatus;+ fromVersion?: string;+ toVersion?: string;+ error?: string;+}++export type UpdateAllJobStatus = 'pending_restart' | 'running' | 'completed' | 'failed';++export interface UpdateAllJob {+ id: string;+ status: UpdateAllJobStatus;+ results?: UpdateAllEnvironmentResult[];+ error?: string;+ createdAt: string;+ completedAt?: string;+}+type ApiResponse<T> = {success: boolean;data: T;@@ -24,23 +52,43 @@ type ApiResponse<T> = {};/**- * Check if the system can perform a self-upgrade- * @returns Promise with upgrade availability status+ * Check if an environment can perform a self-upgrade.+ * @param environmentId - Environment ID (defaults to the local manager, '0')*/-async function checkUpgradeAvailable(): Promise<UpgradeCheckResponse> {- const res = await apiClient.get<UpgradeCheckResponse>('/environments/0/system/upgrade/check');+async function checkUpgradeAvailable(environmentId: string = '0'): Promise<UpgradeCheckResponse> {+ const res = await apiClient.get<UpgradeCheckResponse>(`/environments/${environmentId}/system/upgrade/check`);return res.data;}/**- * Trigger a system self-upgrade- * @returns Promise with upgrade initiation result+ * Trigger a self-upgrade on an environment.+ * @param environmentId - Environment ID (defaults to the local manager, '0')*/-async function triggerUpgrade(): Promise<UpgradeResponse> {- const res = await apiClient.post<UpgradeResponse>('/environments/0/system/upgrade');+async function triggerUpgrade(environmentId: string = '0'): Promise<UpgradeResponse> {+ const res = await apiClient.post<UpgradeResponse>(`/environments/${environmentId}/system/upgrade`);return res.data;}+/**+ * Trigger a fleet-wide update, upgrading the manager first and then every online+ * remote environment that has an update available. No client timeout is set: the+ * manager pulls the upgrader image before responding.+ */+async function triggerUpdateAll(): Promise<UpdateAllJob> {+ const res = await apiClient.post<ApiResponse<UpdateAllJob>>('/environments/0/system/upgrade/all');+ return res.data.data;+}++/**+ * Fetch the latest update-all job for live progress polling.+ */+async function getUpdateAllStatus(): Promise<UpdateAllJob> {+ const res = await apiClient.get<ApiResponse<UpdateAllJob>>('/environments/0/system/upgrade/all/status', {+ timeout: 5000+ });+ return res.data.data;+}+/*** Check system health* @param environmentId - Optional environment ID for remote environments (defaults to local system)@@ -77,6 +125,8 @@ async function getVersionInfo(environmentId: string = '0'): Promise<AppVersionInexport default {checkUpgradeAvailable,triggerUpgrade,+ triggerUpdateAll,+ getUpdateAllStatus,checkHealth,getVersionInfo};diff --git a/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte b/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelteindex 962e6f552..316e8a5d4 100644--- a/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte+++ b/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte@@ -5,7 +5,6 @@import UpdateCenterDialog from '$lib/components/dialogs/update-center-dialog.svelte';import { m } from '$lib/paraglide/messages';import { queryKeys } from '$lib/query/query-keys';- import environmentUpgradeService from '$lib/services/api/environment-upgrade-service';import systemUpgradeService from '$lib/services/api/system-upgrade-service';import type { AppVersionInformation } from '$lib/types/settings';import type { Environment } from '$lib/types/environment';@@ -40,10 +39,7 @@const upgradeAvailabilityQuery = createQuery(() => ({queryKey: queryKeys.system.environmentUpgradeAvailable(environment.id),- queryFn: () =>- environment.id === '0'- ? systemUpgradeService.checkUpgradeAvailable()- : environmentUpgradeService.checkEnvironmentUpgradeAvailable(environment.id),+ queryFn: () => systemUpgradeService.checkUpgradeAvailable(environment.id),enabled: shouldCheckUpgrade,staleTime: 0}));@@ -99,20 +95,8 @@});async function handleConfirmUpgradeInternal() {- if (isLocalEnvironment) {- try {- await systemUpgradeService.triggerUpgrade();- toast.success(m.upgrade_success());- } catch (error) {- const errorMessage = extractApiErrorMessage(error);- toast.error(m.upgrade_failed({ error: errorMessage }));- throw error;- }- return;- }-try {- const result = await environmentUpgradeService.triggerEnvironmentUpgrade(environment.id);+ const result = await systemUpgradeService.triggerUpgrade(environment.id);if (!result.success) {throw new Error(result.error || result.message || m.common_unknown());}diff --git a/frontend/src/routes/(app)/environments/+page.svelte b/frontend/src/routes/(app)/environments/+page.svelteindex 37874fac9..1a22a5e40 100644--- a/frontend/src/routes/(app)/environments/+page.svelte+++ b/frontend/src/routes/(app)/environments/+page.svelte@@ -12,7 +12,8 @@import { environmentStore } from '$lib/stores/environment.store.svelte';import { simpleRefresh } from '$lib/utils/api';import { hasPermission } from '$lib/utils/auth';- import { DownloadIcon } from '$lib/icons';+ import { DownloadIcon, UpdateIcon } from '$lib/icons';+ import UpdateAllDialog from './update-all-dialog.svelte';let { data } = $props();@@ -20,6 +21,7 @@let selectedIds = $state<string[]>([]);let requestOptions = $state(untrack(() => data.environmentRequestOptions));let showEnvironmentSheet = $state(false);+ let showUpdateAllDialog = $state(false);let isLoading = $state({ refresh: false, creating: false, deleting: false });async function refresh() {@@ -33,6 +35,7 @@const canCreateEnvironment = $derived(hasPermission('environments:create'));const canDeleteEnvironment = $derived(hasPermission('environments:delete'));+ const canUpdateEnvironments = $derived(hasPermission('system:upgrade'));async function handleBulkDelete() {if (selectedIds.length === 0) return;@@ -118,6 +121,17 @@}]: []),+ ...(canUpdateEnvironments+ ? [+ {+ id: 'update-all',+ action: 'update' as const,+ label: m.environments_update_all_button(),+ icon: UpdateIcon,+ onclick: () => (showUpdateAllDialog = true)+ }+ ]+ : []),{id: 'refresh',action: 'restart' as const,@@ -136,5 +150,6 @@{#snippet additionalContent()}<NewEnvironmentSheet bind:open={showEnvironmentSheet} {onEnvironmentCreated} />+ <UpdateAllDialog bind:open={showUpdateAllDialog} onFinished={refresh} />{/snippet}</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/environments/environment-table.svelte b/frontend/src/routes/(app)/environments/environment-table.svelteindex 4a28180be..e88544a79 100644--- a/frontend/src/routes/(app)/environments/environment-table.svelte+++ b/frontend/src/routes/(app)/environments/environment-table.svelte@@ -17,7 +17,7 @@import type { Environment } from '$lib/types/environment';import { m } from '$lib/paraglide/messages';import { environmentManagementService } from '$lib/services/env-mgmt-service';- import environmentUpgradeService from '$lib/services/api/environment-upgrade-service';+ import systemUpgradeService from '$lib/services/api/system-upgrade-service';import UpdateCenterDialog from '$lib/components/dialogs/update-center-dialog.svelte';import EnvironmentUpgradeMenuItem from './environment-upgrade-menu-item.svelte';import type { AppVersionInformation } from '$lib/types/settings';@@ -170,7 +170,7 @@upgradingEnvironmentId = envId;try {- const result = await environmentUpgradeService.triggerEnvironmentUpgrade(envId);+ const result = await systemUpgradeService.triggerUpgrade(envId);if (!result.success) {throw new Error(result.error || m.upgrade_failed({ error: 'Unknown error' }));}diff --git a/frontend/src/routes/(app)/environments/update-all-dialog.svelte b/frontend/src/routes/(app)/environments/update-all-dialog.sveltenew file mode 100644index 000000000..b9c1456eb--- /dev/null+++ b/frontend/src/routes/(app)/environments/update-all-dialog.svelte@@ -0,0 +1,205 @@+<script lang="ts">+ import * as Dialog from '$lib/components/ui/dialog';+ import * as ScrollArea from '$lib/components/ui/scroll-area';+ import { Button } from '$lib/components/ui/button';+ import Spinner from '$lib/components/ui/spinner/spinner.svelte';+ import { m } from '$lib/paraglide/messages';+ import { toast } from 'svelte-sonner';+ import { onDestroy } from 'svelte';+ import systemUpgradeService, {+ type UpdateAllJob,+ type UpdateAllEnvironmentStatus+ } from '$lib/services/api/system-upgrade-service';+ import { SuccessIcon, CheckIcon, ClockIcon, AlertIcon, AlertTriangleIcon } from '$lib/icons';++ // open has no $bindable fallback: upstream binds can start out undefined, and+ // binding undefined to a $bindable with a fallback throws props_invalid_value.+ let { open = $bindable(undefined), onFinished }: { open?: boolean; onFinished?: () => void | Promise<void> } = $props();++ type Phase = 'confirm' | 'running' | 'finished';++ const POLL_INTERVAL_MS = 3000;++ let phase = $state<Phase>('confirm');+ let job = $state<UpdateAllJob | null>(null);+ let reconnecting = $state(false);+ let pollActive = false;+ let pollTimer: ReturnType<typeof setTimeout> | null = null;++ function stopPolling() {+ pollActive = false;+ if (pollTimer) {+ clearTimeout(pollTimer);+ pollTimer = null;+ }+ }++ // Reset on close (not on open) so a reopened dialog always starts at the confirm+ // step, without mutating $state from inside an $effect. The confirm step never+ // renders job/reconnecting, so clearing them here is safe.+ function resetState() {+ stopPolling();+ phase = 'confirm';+ job = null;+ reconnecting = false;+ }++ function schedulePoll() {+ if (!pollActive) return;+ pollTimer = setTimeout(poll, POLL_INTERVAL_MS);+ }++ async function poll() {+ if (!pollActive) return;+ try {+ const next = await systemUpgradeService.getUpdateAllStatus();+ reconnecting = false;+ job = next;+ if (next.status === 'completed' || next.status === 'failed') {+ stopPolling();+ phase = 'finished';+ return;+ }+ } catch {+ // The manager is likely restarting after its own upgrade — keep retrying+ // until the backend answers again.+ reconnecting = true;+ }+ schedulePoll();+ }++ async function handleConfirm() {+ phase = 'running';+ reconnecting = false;+ try {+ job = await systemUpgradeService.triggerUpdateAll();+ } catch {+ toast.error(m.environments_update_all_trigger_failed());+ resetState();+ return;+ }++ if (phase !== 'running') return;++ if (job && (job.status === 'completed' || job.status === 'failed')) {+ phase = 'finished';+ return;+ }++ pollActive = true;+ schedulePoll();+ }++ async function handleClose() {+ resetState();+ open = false;+ await onFinished?.();+ }++ onDestroy(stopPolling);++ const title = $derived.by(() => {+ if (phase === 'confirm') return m.environments_update_all_title();+ if (phase === 'finished') {+ return job?.status === 'failed' ? m.environments_update_all_failed() : m.environments_update_all_completed();+ }+ return m.environments_update_all_in_progress();+ });++ function statusLabel(status: UpdateAllEnvironmentStatus): string {+ switch (status) {+ case 'updated':+ return m.environments_update_all_status_updated();+ case 'triggered':+ return m.environments_update_all_status_triggered();+ case 'skipped_up_to_date':+ return m.environments_update_all_status_skipped_up_to_date();+ case 'skipped_offline':+ return m.environments_update_all_status_skipped_offline();+ case 'failed':+ return m.environments_update_all_status_failed();+ default:+ return m.environments_update_all_status_pending();+ }+ }+</script>++<Dialog.Root+ {open}+ onOpenChange={(next) => {+ if (!next) {+ resetState();+ }+ open = next;+ }}+>+ <Dialog.Content+ class="sm:max-w-[520px]"+ onInteractOutside={(e: Event) => {+ if (phase === 'running') e.preventDefault();+ }}+ >+ <Dialog.Header>+ <Dialog.Title>{title}</Dialog.Title>+ {#if phase === 'confirm'}+ <Dialog.Description>{m.environments_update_all_message()}</Dialog.Description>+ {/if}+ </Dialog.Header>++ {#if phase !== 'confirm'}+ <div class="space-y-3">+ {#if reconnecting}+ <div class="text-muted-foreground flex items-center gap-2 text-sm">+ <Spinner class="size-4" />+ <span>{m.environments_update_all_manager_restarting()}</span>+ </div>+ {/if}++ {#if job?.results?.length}+ <ScrollArea.Root class="max-h-72">+ <ul class="divide-border divide-y">+ {#each job.results as result (result.environmentId)}+ <li class="flex items-center justify-between gap-3 py-2 text-sm">+ <div class="flex min-w-0 flex-col">+ <span class="truncate font-medium">{result.environmentName}</span>+ {#if result.error}+ <span class="text-muted-foreground truncate text-xs">{result.error}</span>+ {/if}+ </div>+ <div class="flex shrink-0 items-center gap-2">+ {#if result.status === 'updated'}+ <SuccessIcon class="size-4 text-green-500" />+ {:else if result.status === 'skipped_up_to_date'}+ <CheckIcon class="text-muted-foreground size-4" />+ {:else if result.status === 'skipped_offline'}+ <AlertIcon class="size-4 text-amber-500" />+ {:else if result.status === 'failed'}+ <AlertTriangleIcon class="text-destructive size-4" />+ {:else}+ <ClockIcon class="text-muted-foreground size-4" />+ {/if}+ <span class="text-muted-foreground">{statusLabel(result.status)}</span>+ </div>+ </li>+ {/each}+ </ul>+ </ScrollArea.Root>+ {:else}+ <div class="text-muted-foreground flex items-center gap-2 py-2 text-sm">+ <Spinner class="size-4" />+ <span>{m.environments_update_all_in_progress()}</span>+ </div>+ {/if}+ </div>+ {/if}++ <Dialog.Footer>+ {#if phase === 'confirm'}+ <Button variant="outline" onclick={() => (open = false)}>{m.common_cancel()}</Button>+ <Button onclick={handleConfirm}>{m.environments_update_all_confirm()}</Button>+ {:else}+ <Button variant="outline" onclick={handleClose}>{m.common_close()}</Button>+ {/if}+ </Dialog.Footer>+ </Dialog.Content>+</Dialog.Root>