Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: universal environment dashboard (#2241)
Kyle Mendell93cbbdccc5e5
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.goindex 907a4e4a0..bf82cc58e 100644--- a/backend/internal/bootstrap/services_bootstrap.go+++ b/backend/internal/bootstrap/services_bootstrap.go@@ -83,7 +83,7 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Configsvcs.BuildWorkspace = services.NewBuildWorkspaceService(svcs.Settings)svcs.Project = services.NewProjectService(db, svcs.Settings, svcs.Event, svcs.Image, svcs.Docker, svcs.Build, cfg)svcs.Container = services.NewContainerService(db, svcs.Event, svcs.Docker, svcs.Image, svcs.Settings, svcs.Project)- svcs.Dashboard = services.NewDashboardService(db, svcs.Docker, svcs.Container, svcs.Settings, svcs.Vulnerability)+ svcs.Dashboard = services.NewDashboardService(db, svcs.Docker, svcs.Container, svcs.Settings, svcs.Vulnerability, svcs.Environment)svcs.Volume = services.NewVolumeService(db, svcs.Docker, svcs.Event, svcs.Settings, svcs.Container, svcs.Image, cfg.BackupVolumeName)svcs.Network = services.NewNetworkService(db, svcs.Docker, svcs.Event)svcs.Port = services.NewPortService(svcs.Docker)diff --git a/backend/internal/huma/handlers/dashboard.go b/backend/internal/huma/handlers/dashboard.goindex 0421c552b..742240bda 100644--- a/backend/internal/huma/handlers/dashboard.go+++ b/backend/internal/huma/handlers/dashboard.go@@ -32,6 +32,14 @@ type GetDashboardActionItemsOutput struct {Body base.ApiResponse[dashboardtypes.ActionItems]}+type GetDashboardEnvironmentsOverviewInput struct {+ DebugAllGood bool `query:"debugAllGood" default:"false" doc:"Debug mode: force empty action item lists"`+}++type GetDashboardEnvironmentsOverviewOutput struct {+ Body base.ApiResponse[dashboardtypes.EnvironmentsOverview]+}+func RegisterDashboard(api huma.API, dashboardService *services.DashboardService) {h := &DashboardHandler{dashboardService: dashboardService}@@ -60,6 +68,19 @@ func RegisterDashboard(api huma.API, dashboardService *services.DashboardService{"ApiKeyAuth": {}},},}, h.GetActionItems)++ huma.Register(api, huma.Operation{+ OperationID: "get-dashboard-environments-overview",+ Method: http.MethodGet,+ Path: "/dashboard/environments",+ Summary: "Get aggregate environments dashboard overview",+ Description: "Returns dashboard summary data for all visible environments",+ Tags: []string{"Dashboard"},+ Security: []map[string][]string{+ {"BearerAuth": {}},+ {"ApiKeyAuth": {}},+ },+ }, h.GetEnvironmentsOverview)}func (h *DashboardHandler) GetDashboard(ctx context.Context, input *GetDashboardInput) (*GetDashboardOutput, error) {@@ -117,3 +138,30 @@ func (h *DashboardHandler) GetActionItems(ctx context.Context, input *GetDashboa},}, nil}++func (h *DashboardHandler) GetEnvironmentsOverview(+ ctx context.Context,+ input *GetDashboardEnvironmentsOverviewInput,+) (*GetDashboardEnvironmentsOverviewOutput, error) {+ if h.dashboardService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ overview, err := h.dashboardService.GetEnvironmentsOverview(ctx, services.DashboardActionItemsOptions{+ DebugAllGood: input.DebugAllGood,+ })+ if err != nil {+ return nil, huma.Error500InternalServerError(err.Error())+ }++ if overview == nil {+ return nil, huma.Error500InternalServerError("dashboard environments overview not available")+ }++ return &GetDashboardEnvironmentsOverviewOutput{+ Body: base.ApiResponse[dashboardtypes.EnvironmentsOverview]{+ Success: true,+ Data: *overview,+ },+ }, nil+}diff --git a/backend/internal/huma/handlers/dashboard_test.go b/backend/internal/huma/handlers/dashboard_test.goindex 20b8f3d41..d8769e9a1 100644--- a/backend/internal/huma/handlers/dashboard_test.go+++ b/backend/internal/huma/handlers/dashboard_test.go@@ -26,7 +26,7 @@ func setupDashboardHandlerTestDB(t *testing.T) (*database.DB, *services.Settingsdb, err := gorm.Open(glsqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.ApiKey{}, &models.ImageUpdateRecord{}, &models.Project{}, &models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&models.ApiKey{}, &models.Environment{}, &models.ImageUpdateRecord{}, &models.Project{}, &models.SettingVariable{}))databaseDB := &database.DB{DB: db}settingsSvc, err := services.NewSettingsService(context.Background(), databaseDB)@@ -111,7 +111,7 @@ func TestDashboardHandlerGetDashboardReturnsSnapshot(t *testing.T) {dockerSvc := newDashboardHandlerTestDockerService(t, settingsSvc, containers, images)handler := &DashboardHandler{- dashboardService: services.NewDashboardService(db, dockerSvc, nil, settingsSvc, nil),+ dashboardService: services.NewDashboardService(db, dockerSvc, nil, settingsSvc, nil, nil),}output, err := handler.GetDashboard(context.Background(), &GetDashboardInput{EnvironmentID: "0"})@@ -131,3 +131,28 @@ func TestDashboardHandlerGetDashboardReturnsSnapshot(t *testing.T) {{Kind: dashboardtypes.ActionItemKindExpiringKeys, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},}, snapshot.ActionItems.Items)}++func TestDashboardHandlerGetEnvironmentsOverviewReturnsAggregateSummary(t *testing.T) {+ db, settingsSvc := setupDashboardHandlerTestDB(t)++ require.NoError(t, db.WithContext(context.Background()).Create(&models.Environment{+ BaseModel: models.BaseModel{ID: "0", CreatedAt: time.Now()},+ Name: "Local Docker",+ ApiUrl: "http://local.test",+ Status: string(models.EnvironmentStatusOffline),+ Enabled: true,+ }).Error)++ handler := &DashboardHandler{+ dashboardService: services.NewDashboardService(db, nil, nil, settingsSvc, nil, services.NewEnvironmentService(db, http.DefaultClient, nil, nil, settingsSvc, nil)),+ }++ output, err := handler.GetEnvironmentsOverview(context.Background(), &GetDashboardEnvironmentsOverviewInput{})+ require.NoError(t, err)+ require.NotNil(t, output)+ require.True(t, output.Body.Success)+ require.Equal(t, 1, output.Body.Data.Summary.TotalEnvironments)+ require.Len(t, output.Body.Data.Environments, 1)+ require.Equal(t, "0", output.Body.Data.Environments[0].Environment.ID)+ require.Equal(t, dashboardtypes.EnvironmentSnapshotStateSkipped, output.Body.Data.Environments[0].SnapshotState)+}diff --git a/backend/internal/huma/handlers/environments.go b/backend/internal/huma/handlers/environments.goindex d85d5bf4b..7906d7b1d 100644--- a/backend/internal/huma/handlers/environments.go+++ b/backend/internal/huma/handlers/environments.go@@ -619,43 +619,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat}func (h *EnvironmentHandler) applyEdgeRuntimeState(env *environment.Environment) {- if env == nil || !env.IsEdge {- return- }-- connected := false- env.Connected = &connected- env.ConnectedAt = nil- env.LastHeartbeat = nil- env.LastPollAt = nil- env.EdgeTransport = nil-- if pollState, ok := edge.GetPollRuntimeRegistry().Get(env.ID, time.Now()); ok {- env.LastPollAt = pollState.LastPollAt- }-- if runtimeState, ok := edge.GetTunnelRuntimeState(env.ID); ok {- connected = true- env.Connected = &connected- env.Status = string(models.EnvironmentStatusOnline)- env.ConnectedAt = runtimeState.ConnectedAt- env.LastHeartbeat = runtimeState.LastHeartbeat- if transport, ok := edge.GetActiveTunnelTransport(env.ID); ok {- env.EdgeTransport = &transport- } else if runtimeState.Transport != "" {- env.EdgeTransport = &runtimeState.Transport- }- return- }-- if env.LastPollAt != nil {- env.Status = string(models.EnvironmentStatusStandby)- return- }-- if env.Status != string(models.EnvironmentStatusPending) {- env.Status = string(models.EnvironmentStatusOffline)- }+ services.ApplyEnvironmentRuntimeState(env)}// DeleteEnvironment deletes an environment.diff --git a/backend/internal/services/dashboard_service.go b/backend/internal/services/dashboard_service.goindex 1273af099..bb7c35994 100644--- a/backend/internal/services/dashboard_service.go+++ b/backend/internal/services/dashboard_service.go@@ -2,6 +2,7 @@ package servicesimport ("context"+ "encoding/json""fmt""sort""time"@@ -13,6 +14,7 @@ import ("github.com/getarcaneapp/arcane/types/base"containertypes "github.com/getarcaneapp/arcane/types/container"dashboardtypes "github.com/getarcaneapp/arcane/types/dashboard"+ environmenttypes "github.com/getarcaneapp/arcane/types/environment"imagetypes "github.com/getarcaneapp/arcane/types/image"dockercontainer "github.com/moby/moby/api/types/container"dockerimage "github.com/moby/moby/api/types/image"@@ -22,6 +24,9 @@ import (const defaultDashboardAPIKeyExpiryWindow = 14 * 24 * time.Hourconst dashboardSnapshotPreloadLimit = 50+const defaultAggregateDashboardConcurrency = 4+const defaultAggregateDashboardTimeout = 20 * time.Second+const localEnvironmentID = "0"type DashboardService struct {db *database.DB@@ -29,6 +34,7 @@ type DashboardService struct {containerService *ContainerServicesettingsService *SettingsServicevulnerabilityService *VulnerabilityService+ environmentService *EnvironmentService}type DashboardActionItemsOptions struct {@@ -41,6 +47,7 @@ func NewDashboardService(containerService *ContainerService,settingsService *SettingsService,vulnerabilityService *VulnerabilityService,+ environmentService *EnvironmentService,) *DashboardService {return &DashboardService{db: db,@@ -48,6 +55,7 @@ func NewDashboardService(containerService: containerService,settingsService: settingsService,vulnerabilityService: vulnerabilityService,+ environmentService: environmentService,}}@@ -245,6 +253,56 @@ func (s *DashboardService) GetActionItems(ctx context.Context, options Dashboardreturn &dashboardtypes.ActionItems{Items: actionItems}, nil}+func (s *DashboardService) GetEnvironmentsOverview(+ ctx context.Context,+ options DashboardActionItemsOptions,+) (*dashboardtypes.EnvironmentsOverview, error) {+ if s.environmentService == nil {+ return nil, fmt.Errorf("environment service not available")+ }++ environments, err := s.environmentService.ListVisibleEnvironments(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to list environments: %w", err)+ }++ overview := &dashboardtypes.EnvironmentsOverview{+ Environments: make([]dashboardtypes.EnvironmentOverview, len(environments)),+ }++ g, groupCtx := errgroup.WithContext(ctx)+ g.SetLimit(defaultAggregateDashboardConcurrency)++ for i := range environments {+ index := i+ env := environments[i]++ g.Go(func() error {+ overview.Environments[index] = s.buildEnvironmentOverviewInternal(groupCtx, env, options)+ return nil+ })+ }++ if err := g.Wait(); err != nil {+ return nil, fmt.Errorf("failed to build environments overview: %w", err)+ }++ sort.SliceStable(overview.Environments, func(i, j int) bool {+ left := overview.Environments[i].Environment+ right := overview.Environments[j].Environment+ if left.ID == localEnvironmentID {+ return true+ }+ if right.ID == localEnvironmentID {+ return false+ }+ return left.Name < right.Name+ })++ overview.Summary = summarizeEnvironmentOverviewInternal(overview.Environments)+ return overview, nil+}+func (s *DashboardService) buildActionItemsForSnapshotInternal(ctx context.Context,options DashboardActionItemsOptions,@@ -347,6 +405,95 @@ func buildDashboardActionItemsInternal(return &dashboardtypes.ActionItems{Items: actionItems}}+func (s *DashboardService) buildEnvironmentOverviewInternal(+ ctx context.Context,+ env environmenttypes.Environment,+ options DashboardActionItemsOptions,+) dashboardtypes.EnvironmentOverview {+ overview := dashboardtypes.EnvironmentOverview{+ Environment: env,+ Containers: containertypes.StatusCounts{},+ ImageUsageCounts: imagetypes.UsageCounts{},+ ActionItems: dashboardtypes.ActionItems{Items: []dashboardtypes.ActionItem{}},+ Settings: dashboardtypes.SnapshotSettings{},+ SnapshotState: dashboardtypes.EnvironmentSnapshotStateSkipped,+ }++ if !env.Enabled || !shouldFetchEnvironmentSnapshotInternal(env) {+ return overview+ }++ snapshot, err := s.getSnapshotForEnvironmentInternal(ctx, env, options)+ if err != nil {+ message := err.Error()+ overview.SnapshotState = dashboardtypes.EnvironmentSnapshotStateError+ overview.SnapshotError = &message+ return overview+ }++ overview.Containers = snapshot.Containers.Counts+ overview.ImageUsageCounts = snapshot.ImageUsageCounts+ overview.ActionItems = snapshot.ActionItems+ overview.Settings = snapshot.Settings+ overview.SnapshotState = dashboardtypes.EnvironmentSnapshotStateReady++ return overview+}++func shouldFetchEnvironmentSnapshotInternal(env environmenttypes.Environment) bool {+ switch env.Status {+ case string(models.EnvironmentStatusOnline), string(models.EnvironmentStatusStandby):+ return true+ default:+ return false+ }+}++func (s *DashboardService) getSnapshotForEnvironmentInternal(+ ctx context.Context,+ env environmenttypes.Environment,+ options DashboardActionItemsOptions,+) (*dashboardtypes.Snapshot, error) {+ reqCtx, cancel := context.WithTimeout(ctx, defaultAggregateDashboardTimeout)+ defer cancel()++ if env.ID == localEnvironmentID {+ return s.GetSnapshot(reqCtx, options)+ }++ respBody, statusCode, err := s.environmentService.ProxyRequest(+ reqCtx,+ env.ID,+ "GET",+ buildEnvironmentDashboardProxyPathInternal(options),+ nil,+ )+ if err != nil {+ return nil, fmt.Errorf("failed to proxy dashboard snapshot: %w", err)+ }+ if statusCode < 200 || statusCode >= 300 {+ return nil, fmt.Errorf("unexpected dashboard status code: %d", statusCode)+ }++ var response base.ApiResponse[dashboardtypes.Snapshot]+ if err := json.Unmarshal(respBody, &response); err != nil {+ return nil, fmt.Errorf("failed to decode dashboard snapshot: %w", err)+ }+ if !response.Success {+ return nil, fmt.Errorf("dashboard snapshot request was not successful")+ }++ return &response.Data, nil+}++func buildEnvironmentDashboardProxyPathInternal(options DashboardActionItemsOptions) string {+ if options.DebugAllGood {+ return fmt.Sprintf("/api/environments/%s/dashboard?debugAllGood=true", localEnvironmentID)+ }++ return fmt.Sprintf("/api/environments/%s/dashboard", localEnvironmentID)+}+func (s *DashboardService) getStoppedContainersCountInternal(ctx context.Context) (int, error) {if s.dockerService == nil {return 0, nil@@ -371,6 +518,46 @@ func (s *DashboardService) getStoppedContainersCountInternal(ctx context.Contextreturn stoppedCount, nil}+func summarizeEnvironmentOverviewInternal(items []dashboardtypes.EnvironmentOverview) dashboardtypes.EnvironmentsSummary {+ summary := dashboardtypes.EnvironmentsSummary{}++ for _, item := range items {+ summary.TotalEnvironments++++ if !item.Environment.Enabled {+ summary.DisabledEnvironments+++ } else {+ switch item.Environment.Status {+ case string(models.EnvironmentStatusOnline):+ summary.OnlineEnvironments+++ case string(models.EnvironmentStatusStandby):+ summary.StandbyEnvironments+++ case string(models.EnvironmentStatusPending):+ summary.PendingEnvironments+++ case string(models.EnvironmentStatusError):+ summary.ErrorEnvironments+++ default:+ summary.OfflineEnvironments+++ }+ }++ summary.Containers.RunningContainers += item.Containers.RunningContainers+ summary.Containers.StoppedContainers += item.Containers.StoppedContainers+ summary.Containers.TotalContainers += item.Containers.TotalContainers++ summary.ImageUsageCounts.Inuse += item.ImageUsageCounts.Inuse+ summary.ImageUsageCounts.Unused += item.ImageUsageCounts.Unused+ summary.ImageUsageCounts.Total += item.ImageUsageCounts.Total+ summary.ImageUsageCounts.TotalSize += item.ImageUsageCounts.TotalSize++ if len(item.ActionItems.Items) > 0 {+ summary.EnvironmentsWithActionItems+++ }+ }++ return summary+}+func (s *DashboardService) getPendingImageUpdatesCountInternal(ctx context.Context) (int, error) {if s.db == nil || s.dockerService == nil {return 0, nildiff --git a/backend/internal/services/dashboard_service_test.go b/backend/internal/services/dashboard_service_test.goindex aff473afb..1943208b6 100644--- a/backend/internal/services/dashboard_service_test.go+++ b/backend/internal/services/dashboard_service_test.go@@ -11,7 +11,10 @@ import ("github.com/getarcaneapp/arcane/backend/internal/database""github.com/getarcaneapp/arcane/backend/internal/models"+ "github.com/getarcaneapp/arcane/types/base"+ containertypes "github.com/getarcaneapp/arcane/types/container"dashboardtypes "github.com/getarcaneapp/arcane/types/dashboard"+ imagetypes "github.com/getarcaneapp/arcane/types/image"glsqlite "github.com/glebarez/sqlite"dockercontainer "github.com/moby/moby/api/types/container"dockerimage "github.com/moby/moby/api/types/image"@@ -25,7 +28,7 @@ func setupDashboardServiceTestDB(t *testing.T) (*database.DB, *SettingsService)db, err := gorm.Open(glsqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.ApiKey{}, &models.ImageUpdateRecord{}, &models.Project{}, &models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&models.ApiKey{}, &models.Environment{}, &models.ImageUpdateRecord{}, &models.Project{}, &models.SettingVariable{}))databaseDB := &database.DB{DB: db}settingsSvc, err := NewSettingsService(context.Background(), databaseDB)@@ -44,6 +47,11 @@ func createDashboardTestImageUpdateRecord(t *testing.T, db *database.DB, recordrequire.NoError(t, db.WithContext(context.Background()).Create(&record).Error)}+func createDashboardTestEnvironment(t *testing.T, db *database.DB, env models.Environment) {+ t.Helper()+ require.NoError(t, db.WithContext(context.Background()).Create(&env).Error)+}+func newDashboardTestDockerService(t *testing.T,settingsSvc *SettingsService,@@ -83,7 +91,7 @@ func newDashboardTestDockerService(func TestDashboardService_GetActionItems_IncludesExpiringAPIKeys(t *testing.T) {db, settingsSvc := setupDashboardServiceTestDB(t)- svc := NewDashboardService(db, nil, nil, settingsSvc, nil)+ svc := NewDashboardService(db, nil, nil, settingsSvc, nil, nil)now := time.Now()createDashboardTestAPIKey(t, db, models.ApiKey{@@ -127,7 +135,7 @@ func TestDashboardService_GetActionItems_IncludesExpiringAPIKeys(t *testing.T) {func TestDashboardService_GetActionItems_DebugAllGoodReturnsNoItems(t *testing.T) {db, settingsSvc := setupDashboardServiceTestDB(t)- svc := NewDashboardService(db, nil, nil, settingsSvc, nil)+ svc := NewDashboardService(db, nil, nil, settingsSvc, nil, nil)createDashboardTestAPIKey(t, db, models.ApiKey{Name: "expiring-soon",@@ -199,7 +207,7 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {})dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images)- svc := NewDashboardService(db, dockerSvc, nil, settingsSvc, nil)+ svc := NewDashboardService(db, dockerSvc, nil, settingsSvc, nil, nil)snapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{})require.NoError(t, err)@@ -249,7 +257,7 @@ func TestDashboardService_GetSnapshot_DebugAllGoodOnlyClearsActionItems(t *testicreateDashboardTestImageUpdateRecord(t, db, models.ImageUpdateRecord{ID: "sha256:image-b", HasUpdate: true})dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images)- svc := NewDashboardService(db, dockerSvc, nil, settingsSvc, nil)+ svc := NewDashboardService(db, dockerSvc, nil, settingsSvc, nil, nil)snapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{DebugAllGood: true})require.NoError(t, err)@@ -261,3 +269,135 @@ func TestDashboardService_GetSnapshot_DebugAllGoodOnlyClearsActionItems(t *testirequire.Equal(t, 1, snapshot.ImageUsageCounts.Inuse)require.Empty(t, snapshot.ActionItems.Items)}++func TestDashboardService_GetEnvironmentsOverview_ReturnsLocalAndRemoteSummaries(t *testing.T) {+ db, settingsSvc := setupDashboardServiceTestDB(t)++ containers := []dockercontainer.Summary{+ {+ ID: "local-running",+ Names: []string{"/local-running"},+ Image: "repo/local:stable",+ ImageID: "sha256:local-image",+ Created: 1700000000,+ State: "running",+ Status: "Up 1 hour",+ Labels: map[string]string{},+ },+ }+ images := []dockerimage.Summary{+ {ID: "sha256:local-image", RepoTags: []string{"repo/local:stable"}, Created: 1710000000, Size: 150},+ }++ remoteSnapshot := base.ApiResponse[dashboardtypes.Snapshot]{+ Success: true,+ Data: dashboardtypes.Snapshot{+ Containers: dashboardtypes.SnapshotContainers{+ Counts: containertypes.StatusCounts{+ RunningContainers: 2,+ StoppedContainers: 1,+ TotalContainers: 3,+ },+ },+ ImageUsageCounts: imagetypes.UsageCounts{+ Inuse: 2,+ Unused: 3,+ Total: 5,+ TotalSize: 900,+ },+ ActionItems: dashboardtypes.ActionItems{+ Items: []dashboardtypes.ActionItem{+ {Kind: dashboardtypes.ActionItemKindStoppedContainers, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},+ },+ },+ },+ }++ remoteServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/environments/0/dashboard":+ require.NoError(t, json.NewEncoder(w).Encode(remoteSnapshot))+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(remoteServer.Close)++ createDashboardTestEnvironment(t, db, models.Environment{+ BaseModel: models.BaseModel{ID: "0", CreatedAt: time.Now()},+ Name: "Local Docker",+ ApiUrl: "http://local.test",+ Status: string(models.EnvironmentStatusOnline),+ Enabled: true,+ })+ createDashboardTestEnvironment(t, db, models.Environment{+ BaseModel: models.BaseModel{ID: "env-remote", CreatedAt: time.Now()},+ Name: "Remote Alpha",+ ApiUrl: remoteServer.URL,+ Status: string(models.EnvironmentStatusOnline),+ Enabled: true,+ })++ dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images)+ envSvc := NewEnvironmentService(db, remoteServer.Client(), nil, nil, settingsSvc, nil)+ svc := NewDashboardService(db, dockerSvc, nil, settingsSvc, nil, envSvc)++ overview, err := svc.GetEnvironmentsOverview(context.Background(), DashboardActionItemsOptions{})+ require.NoError(t, err)+ require.NotNil(t, overview)+ require.Len(t, overview.Environments, 2)++ require.Equal(t, 2, overview.Summary.TotalEnvironments)+ require.Equal(t, 2, overview.Summary.OnlineEnvironments)+ require.Equal(t, 4, overview.Summary.Containers.TotalContainers)+ require.Equal(t, 6, overview.Summary.ImageUsageCounts.Total)+ require.Equal(t, 1, overview.Summary.EnvironmentsWithActionItems)++ require.Equal(t, "0", overview.Environments[0].Environment.ID)+ require.Equal(t, dashboardtypes.EnvironmentSnapshotStateReady, overview.Environments[0].SnapshotState)+ require.Equal(t, 1, overview.Environments[0].Containers.TotalContainers)++ require.Equal(t, "env-remote", overview.Environments[1].Environment.ID)+ require.Equal(t, dashboardtypes.EnvironmentSnapshotStateReady, overview.Environments[1].SnapshotState)+ require.Equal(t, 3, overview.Environments[1].Containers.TotalContainers)+ require.Len(t, overview.Environments[1].ActionItems.Items, 1)+}++func TestDashboardService_GetEnvironmentsOverview_HandlesRemoteSnapshotFailure(t *testing.T) {+ db, settingsSvc := setupDashboardServiceTestDB(t)++ createDashboardTestEnvironment(t, db, models.Environment{+ BaseModel: models.BaseModel{ID: "env-offline", CreatedAt: time.Now()},+ Name: "Offline Env",+ ApiUrl: "http://offline.test",+ Status: string(models.EnvironmentStatusOffline),+ Enabled: true,+ })+ createDashboardTestEnvironment(t, db, models.Environment{+ BaseModel: models.BaseModel{ID: "env-error", CreatedAt: time.Now()},+ Name: "Broken Env",+ ApiUrl: "http://127.0.0.1:1",+ Status: string(models.EnvironmentStatusOnline),+ Enabled: true,+ })++ envSvc := NewEnvironmentService(db, http.DefaultClient, nil, nil, settingsSvc, nil)+ svc := NewDashboardService(db, nil, nil, settingsSvc, nil, envSvc)++ overview, err := svc.GetEnvironmentsOverview(context.Background(), DashboardActionItemsOptions{})+ require.NoError(t, err)+ require.NotNil(t, overview)+ require.Len(t, overview.Environments, 2)++ byID := make(map[string]dashboardtypes.EnvironmentOverview, len(overview.Environments))+ for _, item := range overview.Environments {+ byID[item.Environment.ID] = item+ }++ require.Equal(t, dashboardtypes.EnvironmentSnapshotStateSkipped, byID["env-offline"].SnapshotState)+ require.Nil(t, byID["env-offline"].SnapshotError)++ require.Equal(t, dashboardtypes.EnvironmentSnapshotStateError, byID["env-error"].SnapshotState)+ require.NotNil(t, byID["env-error"].SnapshotError)+ require.Contains(t, *byID["env-error"].SnapshotError, "failed to proxy dashboard snapshot")+}diff --git a/backend/internal/services/environment_runtime_state.go b/backend/internal/services/environment_runtime_state.gonew file mode 100644index 000000000..7f62abd0e--- /dev/null+++ b/backend/internal/services/environment_runtime_state.go@@ -0,0 +1,51 @@+package services++import (+ "time"++ "github.com/getarcaneapp/arcane/backend/internal/models"+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"+ environmenttypes "github.com/getarcaneapp/arcane/types/environment"+)++// ApplyEnvironmentRuntimeState normalizes edge environment runtime status using+// in-memory tunnel and poll registries without mutating persisted state.+func ApplyEnvironmentRuntimeState(env *environmenttypes.Environment) {+ if env == nil || !env.IsEdge {+ return+ }++ connected := false+ env.Connected = &connected+ env.ConnectedAt = nil+ env.LastHeartbeat = nil+ env.LastPollAt = nil+ env.EdgeTransport = nil++ if pollState, ok := edge.GetPollRuntimeRegistry().Get(env.ID, time.Now()); ok {+ env.LastPollAt = pollState.LastPollAt+ }++ if runtimeState, ok := edge.GetTunnelRuntimeState(env.ID); ok {+ connected = true+ env.Connected = &connected+ env.Status = string(models.EnvironmentStatusOnline)+ env.ConnectedAt = runtimeState.ConnectedAt+ env.LastHeartbeat = runtimeState.LastHeartbeat+ if transport, ok := edge.GetActiveTunnelTransport(env.ID); ok {+ env.EdgeTransport = &transport+ } else if runtimeState.Transport != "" {+ env.EdgeTransport = &runtimeState.Transport+ }+ return+ }++ if env.LastPollAt != nil {+ env.Status = string(models.EnvironmentStatusStandby)+ return+ }++ if env.Status != string(models.EnvironmentStatusPending) {+ env.Status = string(models.EnvironmentStatusOffline)+ }+}diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.goindex abc20af6f..578a95ce1 100644--- a/backend/internal/services/environment_service.go+++ b/backend/internal/services/environment_service.go@@ -439,6 +439,28 @@ func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, parareturn out, paginationResp, nil}+func (s *EnvironmentService) ListVisibleEnvironments(ctx context.Context) ([]environment.Environment, error) {+ var envs []models.Environment+ if err := s.db.WithContext(ctx).+ Model(&models.Environment{}).+ Where("hidden = ?", false).+ Order("created_at asc, id asc").+ Find(&envs).Error; err != nil {+ return nil, fmt.Errorf("failed to list visible environments: %w", err)+ }++ out, mapErr := mapper.MapSlice[models.Environment, environment.Environment](envs)+ if mapErr != nil {+ return nil, fmt.Errorf("failed to map environments: %w", mapErr)+ }++ for i := range out {+ ApplyEnvironmentRuntimeState(&out[i])+ }++ return out, nil+}+// ListRemoteEnvironments returns all non-local, enabled environments for syncing purposes.func (s *EnvironmentService) ListRemoteEnvironments(ctx context.Context) ([]models.Environment, error) {var envs []models.Environmentdiff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 1e9a90673..03858f1a4 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -435,6 +435,28 @@"dashboard_meter_gpu_devices": "devices","dashboard_meter_usage": "Usage","dashboard_meter_capacity": "Capacity",+ "dashboard_all_transport_http": "HTTP",+ "dashboard_all_transport_edge": "Edge",+ "dashboard_all_transport_websocket": "WebSocket",+ "dashboard_all_transport_grpc": "gRPC",+ "dashboard_all_last_seen": "Last seen",+ "dashboard_all_activity": "Activity",+ "dashboard_all_no_visible_environments": "No visible environments",+ "dashboard_all_reachable_summary": "{count} reachable",+ "dashboard_all_unavailable_summary": "{count} unavailable",+ "dashboard_all_disabled_summary": "{count} disabled",+ "dashboard_all_no_containers": "No containers found",+ "dashboard_all_container_summary": "{running} Running · {stopped} Stopped",+ "dashboard_all_no_images": "No images tracked",+ "dashboard_all_image_summary": "{inUse} In Use · {unused} Unused",+ "dashboard_all_storage_title": "Storage",+ "dashboard_all_no_storage": "No image storage reported",+ "dashboard_all_unused_images_summary": "{count} unused images",+ "dashboard_all_images_tracked_summary": "{count} images tracked",+ "dashboard_all_environment_board_title": "Environment Board",+ "dashboard_all_environment_unavailable_title": "Environment unavailable",+ "dashboard_all_environment_unavailable_description": "This environment is offline, pending, or otherwise unreachable right now.",+ "dashboard_all_summary_unavailable": "Environment summary unavailable. {error}","_comment_containers": "=== CONTAINERS ===","containers_title": "Containers","containers_subtitle": "View and Manage your Containers",diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.tsindex 023bf8bb4..2370a890f 100644--- a/frontend/src/lib/query/query-keys.ts+++ b/frontend/src/lib/query/query-keys.ts@@ -78,7 +78,8 @@ export const queryKeys = {snapshot: (environmentId: string, debugAllGood = false) =>['dashboard', 'snapshot', environmentId, debugAllGood ? 'debug-all-good' : 'normal'] as const,actionItems: (environmentId: string, debugAllGood = false) =>- ['dashboard', 'action-items', environmentId, debugAllGood ? 'debug-all-good' : 'normal'] as const+ ['dashboard', 'action-items', environmentId, debugAllGood ? 'debug-all-good' : 'normal'] as const,+ environments: (debugAllGood = false) => ['dashboard', 'environments', debugAllGood ? 'debug-all-good' : 'normal'] as const},containers: {all: ['containers'] as const,diff --git a/frontend/src/lib/services/dashboard-service.ts b/frontend/src/lib/services/dashboard-service.tsindex 3cb610e68..c9300a626 100644--- a/frontend/src/lib/services/dashboard-service.ts+++ b/frontend/src/lib/services/dashboard-service.ts@@ -1,6 +1,6 @@import BaseAPIService from './api-service';import { environmentStore } from '$lib/stores/environment.store.svelte';-import type { DashboardActionItems, DashboardSnapshot } from '$lib/types/dashboard.type';+import type { DashboardActionItems, DashboardEnvironmentsOverview, DashboardSnapshot } from '$lib/types/dashboard.type';interface GetDashboardActionItemsOptions {debugAllGood?: boolean;@@ -29,6 +29,11 @@ export class DashboardService extends BaseAPIService {const params = options?.debugAllGood ? { debugAllGood: 'true' } : undefined;return this.handleResponse(this.api.get(`/environments/${environmentId}/dashboard/action-items`, { params }));}++ async getDashboardEnvironmentsOverview(options?: GetDashboardActionItemsOptions): Promise<DashboardEnvironmentsOverview> {+ const params = options?.debugAllGood ? { debugAllGood: 'true' } : undefined;+ return this.handleResponse(this.api.get('/dashboard/environments', { params }));+ }}export const dashboardService = new DashboardService();diff --git a/frontend/src/lib/services/system-service.ts b/frontend/src/lib/services/system-service.tsindex e3535b31b..53f8fb880 100644--- a/frontend/src/lib/services/system-service.ts+++ b/frontend/src/lib/services/system-service.ts@@ -6,7 +6,11 @@ import type { SystemPruneRequest } from '$lib/types/prune.type';export class SystemService extends BaseAPIService {async pruneAll(options: SystemPruneRequest) {const envId = await environmentStore.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/system/prune`, options));+ return this.pruneAllForEnvironment(envId, options);+ }++ async pruneAllForEnvironment(environmentId: string, options: SystemPruneRequest) {+ return this.handleResponse(this.api.post(`/environments/${environmentId}/system/prune`, options));}async startAllStoppedContainers() {diff --git a/frontend/src/lib/types/dashboard.type.ts b/frontend/src/lib/types/dashboard.type.tsindex d84e7f131..9c2de921a 100644--- a/frontend/src/lib/types/dashboard.type.ts+++ b/frontend/src/lib/types/dashboard.type.ts@@ -1,4 +1,5 @@import type { ContainerStatusCounts, ContainerSummaryDto } from './container.type';+import type { Environment } from './environment.type';import type { ImageSummaryDto, ImageUsageCounts } from './image.type';import type { Paginated } from './pagination.type';@@ -25,3 +26,52 @@ export interface DashboardSnapshot {actionItems: DashboardActionItems;settings: DashboardSnapshotSettings;}++export type EnvironmentDashboardSnapshotState = 'ready' | 'skipped' | 'error';++export interface DashboardEnvironmentOverview {+ environment: Environment;+ containers: ContainerStatusCounts;+ imageUsageCounts: ImageUsageCounts;+ actionItems: DashboardActionItems;+ settings: DashboardSnapshotSettings;+ snapshotState: EnvironmentDashboardSnapshotState;+ snapshotError?: string;+}++export interface DashboardEnvironmentsSummary {+ totalEnvironments: number;+ onlineEnvironments: number;+ standbyEnvironments: number;+ offlineEnvironments: number;+ pendingEnvironments: number;+ errorEnvironments: number;+ disabledEnvironments: number;+ containers: ContainerStatusCounts;+ imageUsageCounts: ImageUsageCounts;+ environmentsWithActionItems: number;+}++export interface DashboardEnvironmentsOverview {+ summary: DashboardEnvironmentsSummary;+ environments: DashboardEnvironmentOverview[];+}++export interface DashboardOverviewSummary {+ totalEnvironments: number;+ reachableEnvironments: number;+ unavailableEnvironments: number;+ disabledEnvironments: number;+ totalContainers: number;+ runningContainers: number;+ stoppedContainers: number;+ totalImages: number;+ imagesInUse: number;+ imagesUnused: number;+ totalImageSize: number;+}++export interface DashboardEnvironmentCardState {+ environment: Environment;+ loadPromise: Promise<DashboardEnvironmentOverview> | null;+}diff --git a/frontend/src/lib/types/prune.type.ts b/frontend/src/lib/types/prune.type.tsindex 0262aeb8f..d15d22a73 100644--- a/frontend/src/lib/types/prune.type.ts+++ b/frontend/src/lib/types/prune.type.ts@@ -35,3 +35,5 @@ export interface SystemPruneRequest {networks?: PruneNetworksOptions;buildCache?: PruneBuildCacheOptions;}++export type PruneType = 'containers' | 'images' | 'networks' | 'volumes' | 'buildCache';diff --git a/frontend/src/routes/(app)/dashboard/+page.svelte b/frontend/src/routes/(app)/dashboard/+page.svelteindex 3484ec52a..d5598a23d 100644--- a/frontend/src/routes/(app)/dashboard/+page.svelte+++ b/frontend/src/routes/(app)/dashboard/+page.svelte@@ -1,4 +1,7 @@<script lang="ts">+ import * as Tabs from '$lib/components/ui/tabs/index.js';+ import { TabBar, type TabItem } from '$lib/components/tab-bar';+ import { page } from '$app/state';import { toast } from 'svelte-sonner';import PruneConfirmationDialog from '$lib/components/dialogs/prune-confirmation-dialog.svelte';import DockerInfoDialog from '$lib/components/dialogs/docker-info-dialog.svelte';@@ -7,7 +10,6 @@import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import { openConfirmDialog } from '$lib/components/confirm-dialog';- import { onMount } from 'svelte';import { environmentStore } from '$lib/stores/environment.store.svelte';import userStore from '$lib/stores/user-store';import { createStatsWebSocket } from '$lib/utils/ws';@@ -19,13 +21,15 @@import DashboardMetricTile from './dash-metric-tile.svelte';import DashboardContainerTable from './dash-container-table.svelte';import DashboardImageTable from './dash-image-table.svelte';+ import DashboardAllEnvironmentsView from './dashboard-all-environments-view.svelte';import type { PageData } from './$types';import { m } from '$lib/paraglide/messages';- import { invalidateAll } from '$app/navigation';+ import { goto, invalidateAll } from '$app/navigation';import { systemService } from '$lib/services/system-service';import bytes from '$lib/utils/bytes';import type { DockerInfo } from '$lib/types/docker-info.type';- import type { SystemPruneRequest } from '$lib/types/prune.type';+ import type { DashboardSnapshot } from '$lib/types/dashboard.type';+ import type { SystemPruneRequest, PruneType } from '$lib/types/prune.type';import {CpuIcon,MemoryStickIcon,@@ -42,16 +46,37 @@} from '$lib/icons';let { data }: { data: PageData } = $props();- let containers = $derived(data.dashboard.containers);- let images = $derived(data.dashboard.images);- let settings = $derived(data.settings);+ const emptyDashboard: DashboardSnapshot = {+ containers: {+ data: [],+ counts: { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 },+ pagination: { totalPages: 1, totalItems: 0, currentPage: 1, itemsPerPage: 50, grandTotalItems: 0 }+ },+ images: {+ data: [],+ pagination: { totalPages: 1, totalItems: 0, currentPage: 1, itemsPerPage: 50, grandTotalItems: 0 }+ },+ imageUsageCounts: { imagesInuse: 0, imagesUnused: 0, totalImages: 0, totalImageSize: 0 },+ actionItems: { items: [] },+ settings: {}+ };++ let activeView = $derived(data.view === 'current' ? 'current' : 'all');+ let currentDashboard = $derived(data.dashboard ?? emptyDashboard);+ let containers = $derived(currentDashboard.containers);+ let images = $derived(currentDashboard.images);+ let settings = $derived(data.settings ?? null);let containerStatusCounts = $derived(- data.dashboard.containers.counts ?? { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 }+ currentDashboard.containers.counts ?? { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 });- let imageUsageCounts = $derived(data.dashboard.imageUsageCounts);- let dashboardActionItems = $derived(data.dashboard.actionItems);+ let imageUsageCounts = $derived(currentDashboard.imageUsageCounts);+ let dashboardActionItems = $derived(currentDashboard.actionItems);let debugAllGood = $derived(data.debugAllGood ?? false);let currentUser = $state<User | null>(null);+ const viewTabs = $derived.by((): TabItem[] => [+ { value: 'all', label: m.common_all(), icon: ContainersIcon },+ { value: 'current', label: m.common_current(), icon: StatsIcon }+ ]);let systemStats = $state<SystemStats | null>(null);let isPruneDialogOpen = $state(false);@@ -59,9 +84,6 @@let dockerInfo = $state<DockerInfo | null>(null);let dockerInfoPromise = $state<Promise<DockerInfo> | null>(null);let dockerInfoError = $state<string | null>(null);-- type PruneType = 'containers' | 'images' | 'networks' | 'volumes' | 'buildCache';-let isLoading = $state({starting: false,stopping: false,@@ -194,6 +216,7 @@const overviewHost = $derived(currentStats?.hostname?.trim() || dockerInfo?.Name || m.common_unknown());const overviewPlatform = $derived(currentStats?.platform ?? dockerInfo?.OperatingSystem ?? '-');const overviewArchitecture = $derived(currentStats?.architecture ?? dockerInfo?.Architecture ?? '-');+ const currentEnvironmentName = $derived(environmentStore.selected?.name?.trim() || m.common_unknown());const dashboardUser = $derived.by(() => currentUser ?? data.user ?? null);const greetingBase = $derived.by(() => {const hour = new Date().getHours();@@ -212,6 +235,19 @@: m.dashboard_greeting_without_name({ greeting: greetingBase }));+ async function handleViewChange(nextView: string) {+ if (nextView === activeView) return;++ const nextUrl = new URL(page.url);+ if (nextView === 'current') {+ nextUrl.searchParams.set('view', 'current');+ } else {+ nextUrl.searchParams.delete('view');+ }++ await goto(nextUrl.toString(), { keepFocus: true });+ }+function formatPercent(value: number | null): string {return value === null ? '--' : `${value.toFixed(1)}%`;}@@ -222,7 +258,12 @@isLoading.refreshing = false;}- onMount(() => {+ $effect(() => {+ if (activeView !== 'current') {+ closeStatsWS();+ return;+ }+let mounted = true;let currentEnvId: string | null = null;const unsubscribeUser = userStore.subscribe((user) => {@@ -385,231 +426,246 @@}</script>-<div class="flex h-full min-h-0 flex-col gap-4 overflow-hidden pt-3 md:gap-5 md:pt-4">- <header- class="dark:border-surface/80 dark:bg-surface/10 shrink-0 rounded-xl border border-white/80 bg-white/10 p-4 shadow-sm backdrop-blur-sm sm:p-5"- >- <div class="relative flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">- <div class="space-y-1.5">- <p class="text-muted-foreground text-[11px] font-semibold tracking-[0.14em] uppercase">{m.dashboard_title()}</p>- <h1 class="text-2xl font-bold tracking-tight sm:text-3xl">{dashboardHeroGreeting}</h1>- </div>-- <QuickActions- class="w-full justify-start lg:w-auto lg:justify-end"- compact- user={data.user}- {stoppedContainers}- {runningContainers}- isLoading={{ starting: isLoading.starting, stopping: isLoading.stopping, pruning: isLoading.pruning }}- onStartAll={handleStartAll}- onStopAll={handleStopAll}- onOpenPruneDialog={() => (isPruneDialogOpen = true)}- onRefresh={refreshData}- refreshing={isLoading.refreshing}- />- </div>- </header>-- <section class="shrink-0 space-y-1.5">- {#if attentionItemsCount > 0}- <div class="flex flex-col gap-1">- <h2 class="text-lg font-semibold tracking-tight">{m.dashboard_action_items_title()}</h2>- </div>- <div class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">- {#if stoppedContainersAttentionCount > 0}- <DashboardActionCard- title={m.containers_title()}- icon={ContainersIcon}- badgeText={stoppedContainersBadgeText}- badgeVariant="red"- value={`${runningContainers}/${totalContainers}`}- description={m.common_running()}- ctaLabel={m.common_view_all()}- href="/containers"- />- {/if}-- {#if imageUpdatesAttentionCount > 0}- <DashboardActionCard- title={m.images_updates()}- icon={UpdateIcon}- badgeText={imageUpdatesBadgeText}- badgeVariant="amber"- value={imageUpdatesAttentionCount}- description={m.image_update_tag_description()}- ctaLabel={m.common_view_all()}- href="/images"- />- {/if}-- {#if actionableVulnerabilitiesAttentionCount > 0}- <DashboardActionCard- title={m.security_title()}- icon={AlertTriangleIcon}- badgeText={actionableVulnerabilitiesBadgeText}- badgeVariant="red"- value={actionableVulnerabilitiesAttentionCount}- description={m.security_subtitle()}- ctaLabel={m.common_view()}- href="/security"- />- {/if}-- {#if hasDiskPressureAlert}- <DashboardActionCard- title={m.dashboard_meter_disk()}- icon={VolumesIcon}- badgeText={diskRiskLabel}- badgeVariant={diskRiskBadgeVariant}- value={diskPressureValue}- description={diskPressureDescription}- ctaLabel={m.common_view_all()}- href="/volumes"- />- {/if}-- {#if expiringApiKeysAttentionCount > 0}- <DashboardActionCard- title={m.api_key_page_title()}- icon={ApiKeyIcon}- badgeText={expiringApiKeysBadgeText}- badgeVariant="orange"- value={expiringApiKeysAttentionCount}- description={m.api_key_expires_at_description()}- ctaLabel={m.common_view_all()}- href="/settings/api-keys"- />- {/if}- </div>- {:else}- <Card.Root variant="outlined" class="border-emerald-500/30 bg-emerald-500/5 shadow-sm">- <Card.Content class="space-y-2.5 p-4">- <div class="flex items-center gap-2 text-sm font-semibold text-emerald-700 dark:text-emerald-300">- <CheckIcon class="size-4" />- <span>{m.progress_deploy_service_healthy({ service: m.environments_title() })}</span>- </div>- <p class="text-muted-foreground text-xs leading-relaxed">{m.dashboard_no_actionable_events()}</p>- </Card.Content>- </Card.Root>- {/if}- </section>-- <header class="shrink-0">- <Card.Root class="overflow-hidden">- <Card.Header icon={StatsIcon} class="items-start">- <div class="flex w-full min-w-0 flex-col gap-2">- <h2 class="text-lg font-semibold tracking-tight">{m.common_overview()}</h2>- <p class="text-muted-foreground text-sm">{m.dashboard_overview_caption()}</p>- </div>- </Card.Header>- <Card.Content class="space-y-2.5 pt-0 pb-3">- <div- class={`grid grid-cols-2 gap-1 md:grid-cols-3 md:gap-1.5 ${gpuMetric !== null ? 'xl:grid-cols-4' : 'xl:grid-cols-3'}`}+<Tabs.Root value={activeView} class="w-full">+ <div class="pt-3 md:pt-4">+ <TabBar items={viewTabs} value={activeView} onValueChange={handleViewChange} class="w-full" />+ </div>++ {#if activeView === 'all'}+ <Tabs.Content value="all">+ <DashboardAllEnvironmentsView heroGreeting={dashboardHeroGreeting} {debugAllGood} />+ </Tabs.Content>+ {:else}+ <Tabs.Content value="current">+ <div class="flex h-full min-h-0 flex-col gap-4 overflow-hidden pt-3 md:gap-5 md:pt-4">+ <header+ class="dark:border-surface/80 dark:bg-surface/10 shrink-0 rounded-xl border border-white/80 bg-white/10 p-4 shadow-sm backdrop-blur-sm sm:p-5">- <DashboardMetricTile- title={m.dashboard_meter_cpu()}- icon={CpuIcon}- value={formatPercent(cpuMetric)}- label={cpuMetricLabel}- meterValue={cpuMetric}- />-- <DashboardMetricTile- title={m.dashboard_meter_memory()}- icon={MemoryStickIcon}- value={formatPercent(memoryMetric)}- label={memoryMetricLabel}- labelClass="truncate"- meterValue={memoryMetric}- />-- <DashboardMetricTile- title={m.dashboard_meter_disk()}- icon={VolumesIcon}- value={formatPercent(diskMetric)}- label={diskMetricLabel}- labelClass="truncate"- meterValue={diskMetric}- />-- {#if gpuMetric !== null}- <DashboardMetricTile- title={m.dashboard_meter_gpu()}- icon={GpuIcon}- value={formatPercent(gpuMetric)}- label={gpuMetricLabel}- meterValue={gpuMetric}+ <div class="relative flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">+ <div class="space-y-1.5">+ <p class="text-muted-foreground text-[11px] font-semibold tracking-[0.14em] uppercase">{m.dashboard_title()}</p>+ <h1 class="text-2xl font-bold tracking-tight sm:text-3xl">{currentEnvironmentName}</h1>+ </div>++ <QuickActions+ class="w-full justify-start lg:w-auto lg:justify-end"+ compact+ user={data.user}+ {stoppedContainers}+ {runningContainers}+ isLoading={{ starting: isLoading.starting, stopping: isLoading.stopping, pruning: isLoading.pruning }}+ onStartAll={handleStartAll}+ onStopAll={handleStopAll}+ onOpenPruneDialog={() => (isPruneDialogOpen = true)}+ onRefresh={refreshData}+ refreshing={isLoading.refreshing}/>+ </div>+ </header>++ <section class="shrink-0 space-y-3">+ {#if attentionItemsCount > 0}+ <div class="flex flex-col gap-1">+ <h2 class="text-lg font-semibold tracking-tight">{m.dashboard_action_items_title()}</h2>+ </div>+ <div class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">+ {#if stoppedContainersAttentionCount > 0}+ <DashboardActionCard+ title={m.containers_title()}+ icon={ContainersIcon}+ badgeText={stoppedContainersBadgeText}+ badgeVariant="red"+ value={`${runningContainers}/${totalContainers}`}+ description={m.common_running()}+ ctaLabel={m.common_view_all()}+ href="/containers"+ />+ {/if}++ {#if imageUpdatesAttentionCount > 0}+ <DashboardActionCard+ title={m.images_updates()}+ icon={UpdateIcon}+ badgeText={imageUpdatesBadgeText}+ badgeVariant="amber"+ value={imageUpdatesAttentionCount}+ description={m.image_update_tag_description()}+ ctaLabel={m.common_view_all()}+ href="/images"+ />+ {/if}++ {#if actionableVulnerabilitiesAttentionCount > 0}+ <DashboardActionCard+ title={m.security_title()}+ icon={AlertTriangleIcon}+ badgeText={actionableVulnerabilitiesBadgeText}+ badgeVariant="red"+ value={actionableVulnerabilitiesAttentionCount}+ description={m.security_subtitle()}+ ctaLabel={m.common_view()}+ href="/security"+ />+ {/if}++ {#if hasDiskPressureAlert}+ <DashboardActionCard+ title={m.dashboard_meter_disk()}+ icon={VolumesIcon}+ badgeText={diskRiskLabel}+ badgeVariant={diskRiskBadgeVariant}+ value={diskPressureValue}+ description={diskPressureDescription}+ ctaLabel={m.common_view_all()}+ href="/volumes"+ />+ {/if}++ {#if expiringApiKeysAttentionCount > 0}+ <DashboardActionCard+ title={m.api_key_page_title()}+ icon={ApiKeyIcon}+ badgeText={expiringApiKeysBadgeText}+ badgeVariant="orange"+ value={expiringApiKeysAttentionCount}+ description={m.api_key_expires_at_description()}+ ctaLabel={m.common_view_all()}+ href="/settings/api-keys"+ />+ {/if}+ </div>+ {:else}+ <Card.Root variant="outlined" class="border-emerald-500/30 bg-emerald-500/5 shadow-sm">+ <Card.Content class="space-y-2.5 p-4">+ <div class="space-y-2.5">+ <div class="flex items-center gap-2 text-sm font-semibold text-emerald-700 dark:text-emerald-300">+ <CheckIcon class="size-4" />+ <span>{m.progress_deploy_service_healthy({ service: m.environments_title() })}</span>+ </div>+ <p class="text-muted-foreground text-xs leading-relaxed">{m.dashboard_no_actionable_events()}</p>+ </div>+ </Card.Content>+ </Card.Root>{/if}- </div>-- <div class="mt-1 flex flex-col gap-2 border-t pt-3 md:flex-row md:items-center md:justify-between">- <div class="min-w-0 space-y-1">- <div class="text-sm font-medium">{m.docker_engine_title({ engine: overviewHost })}</div>- <div class="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">- <span class="inline-flex items-center gap-1.5">- <ContainersIcon class="size-3" />- <span class="font-medium text-emerald-600">{runningContainers}</span>- <span class="text-muted-foreground/70">/</span>- <span>{totalContainers}</span>- </span>- <span class="text-muted-foreground/50">•</span>- <span class="inline-flex items-center gap-1.5">- <ImagesIcon class="size-3" />- <span>{images.pagination.totalItems}</span>- <span class="text-muted-foreground/70">{m.images_title()}</span>- </span>- <span class="text-muted-foreground/50">•</span>- <span>{imageUsageLabel}</span>- <span class="text-muted-foreground/50">•</span>- <span class="font-mono">{overviewPlatform} / {overviewArchitecture}</span>+ </section>++ <header class="shrink-0">+ <Card.Root class="overflow-hidden">+ <Card.Header icon={StatsIcon} class="items-start">+ <div class="flex w-full min-w-0 flex-col gap-2">+ <h2 class="text-lg font-semibold tracking-tight">{m.common_overview()}</h2>+ </div>+ </Card.Header>+ <Card.Content class="space-y-2.5 pt-0 pb-3">+ <div+ class={`grid grid-cols-2 gap-1 md:grid-cols-3 md:gap-1.5 ${gpuMetric !== null ? 'xl:grid-cols-4' : 'xl:grid-cols-3'}`}+ >+ <DashboardMetricTile+ title={m.dashboard_meter_cpu()}+ icon={CpuIcon}+ value={formatPercent(cpuMetric)}+ label={cpuMetricLabel}+ meterValue={cpuMetric}+ />++ <DashboardMetricTile+ title={m.dashboard_meter_memory()}+ icon={MemoryStickIcon}+ value={formatPercent(memoryMetric)}+ label={memoryMetricLabel}+ labelClass="truncate"+ meterValue={memoryMetric}+ />++ <DashboardMetricTile+ title={m.dashboard_meter_disk()}+ icon={VolumesIcon}+ value={formatPercent(diskMetric)}+ label={diskMetricLabel}+ labelClass="truncate"+ meterValue={diskMetric}+ />++ {#if gpuMetric !== null}+ <DashboardMetricTile+ title={m.dashboard_meter_gpu()}+ icon={GpuIcon}+ value={formatPercent(gpuMetric)}+ label={gpuMetricLabel}+ meterValue={gpuMetric}+ />+ {/if}+ </div>++ <div class="mt-1 flex flex-col gap-2 border-t pt-3 md:flex-row md:items-center md:justify-between">+ <div class="min-w-0 space-y-1">+ <div class="text-sm font-medium">{m.docker_engine_title({ engine: overviewHost })}</div>+ <div class="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">+ <span class="inline-flex items-center gap-1.5">+ <ContainersIcon class="size-3" />+ <span class="font-medium text-emerald-600">{runningContainers}</span>+ <span class="text-muted-foreground/70">/</span>+ <span>{totalContainers}</span>+ </span>+ <span class="text-muted-foreground/50">•</span>+ <span class="inline-flex items-center gap-1.5">+ <ImagesIcon class="size-3" />+ <span>{images.pagination.totalItems}</span>+ <span class="text-muted-foreground/70">{m.images_title()}</span>+ </span>+ <span class="text-muted-foreground/50">•</span>+ <span>{imageUsageLabel}</span>+ <span class="text-muted-foreground/50">•</span>+ <span class="font-mono">{overviewPlatform} / {overviewArchitecture}</span>+ </div>+ </div>++ <ArcaneButton+ action="base"+ tone="ghost"+ size="sm"+ icon={InfoIcon}+ showLabel={false}+ customLabel={m.common_inspect()}+ class="h-7 px-2.5 text-xs"+ loading={!!dockerInfoPromise}+ onclick={openDockerInfoDialog}+ />+ </div>+ </Card.Content>+ </Card.Root>+ </header>++ <section class="flex flex-col lg:min-h-0 lg:flex-1 lg:overflow-hidden">+ <div class="mb-3 flex items-center justify-between gap-3">+ <h2 class="text-lg font-semibold tracking-tight">{m.dashboard_resource_tables_title()}</h2>+ <div class="hidden items-center gap-2 md:flex">+ <ArcaneButton action="base" tone="ghost" size="sm" href="/containers">+ {m.containers_title()}+ </ArcaneButton>+ <ArcaneButton action="base" tone="ghost" size="sm" href="/images">+ {m.images_title()}+ </ArcaneButton></div></div>+ <div class="grid grid-cols-1 gap-4 lg:min-h-0 lg:flex-1 lg:grid-cols-2 lg:overflow-hidden">+ <DashboardContainerTable bind:containers isLoading={false} />+ <DashboardImageTable bind:images isLoading={false} />+ </div>+ </section>++ {#if dockerInfoDialogOpen}+ <DockerInfoDialog bind:open={dockerInfoDialogOpen} {dockerInfo} {dockerInfoPromise} errorMessage={dockerInfoError} />+ {/if}- <ArcaneButton- action="base"- tone="ghost"- size="sm"- icon={InfoIcon}- showLabel={false}- customLabel={m.common_inspect()}- class="h-7 px-2.5 text-xs"- loading={!!dockerInfoPromise}- onclick={openDockerInfoDialog}- />- </div>- </Card.Content>- </Card.Root>- </header>-- <section class="flex flex-col lg:min-h-0 lg:flex-1 lg:overflow-hidden">- <div class="mb-3 flex items-center justify-between gap-3">- <h2 class="text-lg font-semibold tracking-tight">{m.dashboard_resource_tables_title()}</h2>- <div class="hidden items-center gap-2 md:flex">- <ArcaneButton action="base" tone="ghost" size="sm" href="/containers">- {m.containers_title()}- </ArcaneButton>- <ArcaneButton action="base" tone="ghost" size="sm" href="/images">- {m.images_title()}- </ArcaneButton>+ <PruneConfirmationDialog+ bind:open={isPruneDialogOpen}+ defaults={settings}+ isPruning={isLoading.pruning}+ onConfirm={confirmPrune}+ onCancel={() => (isPruneDialogOpen = false)}+ /></div>- </div>- <div class="grid grid-cols-1 gap-4 lg:min-h-0 lg:flex-1 lg:grid-cols-2 lg:overflow-hidden">- <DashboardContainerTable bind:containers isLoading={false} />- <DashboardImageTable bind:images isLoading={false} />- </div>- </section>-- {#if dockerInfoDialogOpen}- <DockerInfoDialog bind:open={dockerInfoDialogOpen} {dockerInfo} {dockerInfoPromise} errorMessage={dockerInfoError} />+ </Tabs.Content>{/if}-- <PruneConfirmationDialog- bind:open={isPruneDialogOpen}- defaults={settings}- isPruning={isLoading.pruning}- onConfirm={confirmPrune}- onCancel={() => (isPruneDialogOpen = false)}- />-</div>+</Tabs.Root>diff --git a/frontend/src/routes/(app)/dashboard/+page.ts b/frontend/src/routes/(app)/dashboard/+page.tsindex bb51497ee..34cadf8e3 100644--- a/frontend/src/routes/(app)/dashboard/+page.ts+++ b/frontend/src/routes/(app)/dashboard/+page.ts@@ -1,16 +1,26 @@import { dashboardService } from '$lib/services/dashboard-service';import { settingsService } from '$lib/services/settings-service';-import { environmentStore } from '$lib/stores/environment.store.svelte';import { queryKeys } from '$lib/query/query-keys';+import { environmentStore } from '$lib/stores/environment.store.svelte';import { throwPageLoadError } from '$lib/utils/page-load-error.util';import type { PageLoad } from './$types';export const load: PageLoad = async ({ parent, url }) => {const { queryClient } = await parent();- const envId = await environmentStore.getCurrentEnvironmentId();const debugAllGood = url.searchParams.get('debugAllGood') === 'true';+ const requestedView = url.searchParams.get('view');+ const view = requestedView === 'current' ? 'current' : 'all';try {+ if (view === 'all') {+ return {+ view,+ dashboard: null,+ debugAllGood+ };+ }++ const envId = await environmentStore.getCurrentEnvironmentId();const [dashboard, settings] = await Promise.all([queryClient.fetchQuery({queryKey: queryKeys.dashboard.snapshot(envId, debugAllGood),@@ -23,6 +33,7 @@ export const load: PageLoad = async ({ parent, url }) => {]);return {+ view,dashboard,settings,debugAllGooddiff --git a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.sveltenew file mode 100644index 000000000..0f47fc6a7--- /dev/null+++ b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte@@ -0,0 +1,902 @@+<script lang="ts">+ import { goto, invalidateAll } from '$app/navigation';+ import { formatDistanceToNow } from 'date-fns';+ import { onDestroy } from 'svelte';+ import { toast } from 'svelte-sonner';+ import { ActionButtonGroup, type ActionButton } from '$lib/components/action-button-group/index.js';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import PruneConfirmationDialog from '$lib/components/dialogs/prune-confirmation-dialog.svelte';+ import { Skeleton } from '$lib/components/ui/skeleton';+ import * as Card from '$lib/components/ui/card/index.js';+ import { m } from '$lib/paraglide/messages';+ import { dashboardService } from '$lib/services/dashboard-service';+ import { systemService } from '$lib/services/system-service';+ import { environmentStore } from '$lib/stores/environment.store.svelte';+ import userStore from '$lib/stores/user-store';+ import type { SystemStats } from '$lib/types/system-stats.type';+ import type {+ DashboardActionItem,+ DashboardEnvironmentCardState,+ DashboardEnvironmentOverview,+ DashboardOverviewSummary,+ DashboardSnapshot+ } from '$lib/types/dashboard.type';+ import type { Environment } from '$lib/types/environment.type';+ import type { PruneType, SystemPruneRequest } from '$lib/types/prune.type';+ import { extractApiErrorMessage, handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { capitalizeFirstLetter } from '$lib/utils/string.utils';+ import { tryCatch } from '$lib/utils/try-catch';+ import { getEnvironmentStatusVariant, isEnvironmentOnline, resolveEnvironmentStatus } from '$lib/utils/environment-status';+ import { createStatsWebSocket, type ReconnectingWebSocket } from '$lib/utils/ws';+ import bytes from '$lib/utils/bytes';+ import { fromStore } from 'svelte/store';+ import {+ ContainersIcon,+ CpuIcon,+ EnvironmentsIcon,+ ImagesIcon,+ InspectIcon,+ MemoryStickIcon,+ RefreshIcon,+ TrashIcon,+ VolumesIcon+ } from '$lib/icons';+ import DashboardMetricTile from './dash-metric-tile.svelte';++ let {+ heroGreeting,+ debugAllGood = false+ }: {+ heroGreeting: string;+ debugAllGood?: boolean;+ } = $props();++ const emptySnapshotSettings: DashboardSnapshot['settings'] = {};++ type EnvironmentLiveStatsState = {+ stats: SystemStats | null;+ loading: boolean;+ hasLoaded: boolean;+ client: ReconnectingWebSocket<SystemStats> | null;+ };++ let isRefreshing = $state(false);+ let isPruneDialogOpen = $state(false);+ let pruneEnvironment = $state<DashboardEnvironmentOverview | null>(null);+ let pruningEnvironmentId = $state<string | null>(null);+ let reloadVersion = $state(0);+ let liveStatsByEnvironmentId = $state<Record<string, EnvironmentLiveStatsState>>({});++ const storeUser = fromStore(userStore);+ const availableEnvironments = $derived(environmentStore.available);+ const currentEnvironmentId = $derived(environmentStore.selected?.id ?? null);+ const currentUserIsAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));++ function shouldLoadEnvironment(environment: Environment): boolean {+ return environment.enabled && isEnvironmentOnline(environment);+ }++ function createBaseEnvironmentOverview(environment: Environment): DashboardEnvironmentOverview {+ return {+ environment,+ containers: { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 },+ imageUsageCounts: { imagesInuse: 0, imagesUnused: 0, totalImages: 0, totalImageSize: 0 },+ actionItems: { items: [] },+ settings: emptySnapshotSettings,+ snapshotState: 'skipped'+ };+ }++ function getEnvironmentCardSortRank(environment: Environment): number {+ if (shouldLoadEnvironment(environment)) {+ return 0;+ }++ if (environment.enabled) {+ return 1;+ }++ return 2;+ }++ function buildEnvironmentLoadPromise(+ environment: Environment,+ currentDebugFlag: boolean+ ): Promise<DashboardEnvironmentOverview> {+ return dashboardService+ .getDashboardForEnvironment(environment.id, {+ debugAllGood: currentDebugFlag+ })+ .then((snapshot) => ({+ environment,+ containers: snapshot.containers.counts ?? { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 },+ imageUsageCounts: snapshot.imageUsageCounts,+ actionItems: snapshot.actionItems,+ settings: snapshot.settings,+ snapshotState: 'ready' as const+ }))+ .catch((error) => ({+ environment,+ containers: { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 },+ imageUsageCounts: { imagesInuse: 0, imagesUnused: 0, totalImages: 0, totalImageSize: 0 },+ actionItems: { items: [] },+ settings: emptySnapshotSettings,+ snapshotState: 'error' as const,+ snapshotError: extractApiErrorMessage(error)+ }));+ }++ async function buildOverviewSummaryFromCards(): Promise<DashboardOverviewSummary> {+ const settledEnvironments = await Promise.all(+ environmentCards.map((item) => item.loadPromise ?? Promise.resolve(createBaseEnvironmentOverview(item.environment)))+ );++ return {+ totalEnvironments: settledEnvironments.length,+ reachableEnvironments: settledEnvironments.filter(+ (item) => item.environment.enabled && isEnvironmentOnline(item.environment)+ ).length,+ unavailableEnvironments: settledEnvironments.filter(+ (item) => item.environment.enabled && !isEnvironmentOnline(item.environment)+ ).length,+ disabledEnvironments: settledEnvironments.filter((item) => !item.environment.enabled).length,+ totalContainers: settledEnvironments.reduce((total, item) => total + item.containers.totalContainers, 0),+ runningContainers: settledEnvironments.reduce((total, item) => total + item.containers.runningContainers, 0),+ stoppedContainers: settledEnvironments.reduce((total, item) => total + item.containers.stoppedContainers, 0),+ totalImages: settledEnvironments.reduce((total, item) => total + item.imageUsageCounts.totalImages, 0),+ imagesInUse: settledEnvironments.reduce((total, item) => total + item.imageUsageCounts.imagesInuse, 0),+ imagesUnused: settledEnvironments.reduce((total, item) => total + item.imageUsageCounts.imagesUnused, 0),+ totalImageSize: settledEnvironments.reduce((total, item) => total + item.imageUsageCounts.totalImageSize, 0)+ };+ }++ function mapOverviewSummary(+ summary: import('$lib/types/dashboard.type').DashboardEnvironmentsSummary+ ): DashboardOverviewSummary {+ return {+ totalEnvironments: summary.totalEnvironments,+ reachableEnvironments: summary.onlineEnvironments + summary.standbyEnvironments,+ unavailableEnvironments: summary.offlineEnvironments + summary.pendingEnvironments + summary.errorEnvironments,+ disabledEnvironments: summary.disabledEnvironments,+ totalContainers: summary.containers.totalContainers,+ runningContainers: summary.containers.runningContainers,+ stoppedContainers: summary.containers.stoppedContainers,+ totalImages: summary.imageUsageCounts.totalImages,+ imagesInUse: summary.imageUsageCounts.imagesInuse,+ imagesUnused: summary.imageUsageCounts.imagesUnused,+ totalImageSize: summary.imageUsageCounts.totalImageSize+ };+ }++ function createEmptyLiveStatsState(): EnvironmentLiveStatsState {+ return {+ stats: null,+ loading: true,+ hasLoaded: false,+ client: null+ };+ }++ function ensureEnvironmentLiveStats(environment: Environment) {+ if (!shouldLoadEnvironment(environment)) {+ removeEnvironmentLiveStats(environment.id);+ return;+ }++ if (!liveStatsByEnvironmentId[environment.id]) {+ liveStatsByEnvironmentId[environment.id] = createEmptyLiveStatsState();+ }++ const liveStatsState = liveStatsByEnvironmentId[environment.id];+ if (liveStatsState.client) {+ return;+ }++ liveStatsState.loading = !liveStatsState.hasLoaded;+ liveStatsState.client = createStatsWebSocket({+ getEnvId: () => environment.id,+ onOpen: () => {+ if (!liveStatsState.hasLoaded) {+ liveStatsState.loading = true;+ }+ },+ onMessage: (stats) => {+ liveStatsState.stats = stats;+ liveStatsState.hasLoaded = true;+ liveStatsState.loading = false;+ },+ onError: (error) => {+ console.error(`Stats websocket error for environment ${environment.id}:`, error);+ }+ });+ liveStatsState.client.connect();+ }++ function removeEnvironmentLiveStats(environmentId: string) {+ const liveStatsState = liveStatsByEnvironmentId[environmentId];+ if (!liveStatsState) {+ return;+ }++ liveStatsState.client?.close();+ delete liveStatsByEnvironmentId[environmentId];+ }++ function cleanupEnvironmentLiveStats() {+ for (const environmentId of Object.keys(liveStatsByEnvironmentId)) {+ removeEnvironmentLiveStats(environmentId);+ }+ }++ const environmentCards = $derived.by((): DashboardEnvironmentCardState[] => {+ const refreshNonce = reloadVersion;+ void refreshNonce;++ return availableEnvironments+ .map((environment, index) => ({+ environment,+ index,+ sortRank: getEnvironmentCardSortRank(environment)+ }))+ .sort((a, b) => {+ if (a.sortRank !== b.sortRank) {+ return a.sortRank - b.sortRank;+ }++ return a.index - b.index;+ })+ .map(({ environment }) => ({+ environment,+ loadPromise: shouldLoadEnvironment(environment) ? buildEnvironmentLoadPromise(environment, debugAllGood) : null+ }));+ });++ const overviewSummaryPromise = $derived.by(async (): Promise<DashboardOverviewSummary> => {+ void reloadVersion;+ const result = await tryCatch(dashboardService.getDashboardEnvironmentsOverview({ debugAllGood }));+ if (!result.error) {+ return mapOverviewSummary(result.data.summary);+ }++ return buildOverviewSummaryFromCards();+ });++ $effect(() => {+ const reachableEnvironmentIds: string[] = [];++ for (const item of environmentCards) {+ if (!shouldLoadEnvironment(item.environment)) {+ continue;+ }++ reachableEnvironmentIds.push(item.environment.id);+ ensureEnvironmentLiveStats(item.environment);+ }++ for (const environmentId of Object.keys(liveStatsByEnvironmentId)) {+ if (!reachableEnvironmentIds.includes(environmentId)) {+ removeEnvironmentLiveStats(environmentId);+ }+ }+ });++ onDestroy(() => {+ cleanupEnvironmentLiveStats();+ });++ async function refreshOverview() {+ isRefreshing = true;+ try {+ await invalidateAll();+ reloadVersion += 1;+ } finally {+ isRefreshing = false;+ }+ }++ async function useEnvironment(environment: Environment) {+ if (!environment.enabled) {+ toast.error(m.environments_cannot_switch_disabled());+ return;+ }++ if (!isEnvironmentOnline(environment)) {+ toast.error(m.common_unavailable());+ return;+ }++ try {+ await environmentStore.setEnvironment(environment);+ toast.success(m.environments_switched_to({ name: environment.name }));+ } catch (error) {+ console.error('Failed to switch environment:', error);+ toast.error(m.common_update_failed({ resource: m.resource_environment() }));+ }+ }++ function getTransportBadge(environment: Environment): { text: string; variant: 'blue' | 'purple' | 'gray' } {+ if (!environment.isEdge) {+ return { text: m.dashboard_all_transport_http(), variant: 'gray' };+ }++ if (environment.lastPollAt) {+ return { text: m.environments_edge_polling_label(), variant: 'blue' };+ }++ if (!environment.connected || !environment.edgeTransport) {+ return { text: m.dashboard_all_transport_edge(), variant: 'gray' };+ }++ return environment.edgeTransport === 'websocket'+ ? { text: m.dashboard_all_transport_websocket(), variant: 'purple' }+ : { text: m.dashboard_all_transport_grpc(), variant: 'blue' };+ }++ function getResolvedStatusLabel(environment: Environment): string {+ switch (resolveEnvironmentStatus(environment)) {+ case 'online':+ return m.common_online();+ case 'standby':+ return m.common_standby();+ case 'pending':+ return m.common_pending();+ case 'error':+ return m.common_error();+ default:+ return m.common_offline();+ }+ }++ function getActionItemLabel(item: DashboardActionItem): string {+ switch (item.kind) {+ case 'stopped_containers':+ return m.containers_title();+ case 'image_updates':+ return m.images_updates();+ case 'actionable_vulnerabilities':+ return m.security_title();+ case 'expiring_keys':+ return m.api_key_page_title();+ default:+ return m.common_unknown();+ }+ }++ function getActionSummary(item: DashboardEnvironmentOverview): string {+ if (debugAllGood || item.actionItems.items.length === 0) {+ return m.dashboard_no_actionable_events();+ }++ return item.actionItems.items+ .slice(0, 2)+ .map((actionItem) => `${actionItem.count} ${getActionItemLabel(actionItem)}`)+ .join(' · ');+ }++ function getActivityMeta(environment: Environment): { label: string; value: string; title: string } {+ if (!isEnvironmentOnline(environment)) {+ const statusLabel = getResolvedStatusLabel(environment);+ return {+ label: m.dashboard_all_activity(),+ value: statusLabel,+ title: statusLabel+ };+ }++ const labelAndValue = environment.lastHeartbeat+ ? { label: m.environments_edge_last_heartbeat_label(), raw: environment.lastHeartbeat }+ : environment.lastPollAt+ ? { label: m.environments_edge_last_poll_label(), raw: environment.lastPollAt }+ : environment.connectedAt+ ? { label: m.environments_edge_connected_since_label(), raw: environment.connectedAt }+ : environment.lastSeen+ ? { label: m.dashboard_all_last_seen(), raw: environment.lastSeen }+ : null;++ if (!labelAndValue?.raw) {+ return { label: m.dashboard_all_activity(), value: m.common_never(), title: m.common_never() };+ }++ const parsed = new Date(labelAndValue.raw);+ if (Number.isNaN(parsed.getTime())) {+ return { label: labelAndValue.label, value: m.common_unknown(), title: m.common_unknown() };+ }++ return {+ label: labelAndValue.label,+ value: formatDistanceToNow(parsed, { addSuffix: true }),+ title: parsed.toLocaleString()+ };+ }++ function formatPercent(value: number | null | undefined): string {+ return value === null || value === undefined ? '--' : `${value.toFixed(1)}%`;+ }++ function getLiveStatsState(environmentId: string): EnvironmentLiveStatsState | null {+ return liveStatsByEnvironmentId[environmentId] ?? null;+ }++ function getCpuMetric(stats: SystemStats | null): number | null {+ return stats?.cpuUsage ?? null;+ }++ function getMemoryMetric(stats: SystemStats | null): number | null {+ if (stats?.memoryUsage === undefined || !stats.memoryTotal) {+ return null;+ }++ return (stats.memoryUsage / stats.memoryTotal) * 100;+ }++ function getDiskMetric(stats: SystemStats | null): number | null {+ if (stats?.diskUsage === undefined || !stats.diskTotal || stats.diskTotal <= 0) {+ return null;+ }++ return (stats.diskUsage / stats.diskTotal) * 100;+ }++ function getCpuMetricLabel(stats: SystemStats | null): string {+ if (!stats) {+ return '--';+ }++ return `${stats.cpuCount ?? 0} ${m.common_cpus()}`;+ }++ function getCapacityLabel(used: number | undefined, total: number | undefined): string {+ if (used === undefined || total === undefined || total <= 0) {+ return '--';+ }++ return `${bytes.format(used, { unitSeparator: ' ' }) ?? '-'} / ${bytes.format(total, { unitSeparator: ' ' }) ?? '-'}`;+ }++ function canPruneEnvironment(item: DashboardEnvironmentOverview): boolean {+ return (+ currentUserIsAdmin && item.environment.enabled && item.snapshotState === 'ready' && isEnvironmentOnline(item.environment)+ );+ }++ function getEnvironmentActionButtons(item: DashboardEnvironmentOverview, isCurrent: boolean): ActionButton[] {+ const buttons: ActionButton[] = [];++ if (currentUserIsAdmin) {+ buttons.push({+ id: `${item.environment.id}-prune`,+ action: 'prune',+ label: m.quick_actions_prune_system(),+ loading: pruningEnvironmentId === item.environment.id,+ disabled: !canPruneEnvironment(item) || !!pruningEnvironmentId,+ onclick: () => openPruneDialog(item),+ icon: TrashIcon+ });+ }++ buttons.push({+ id: `${item.environment.id}-use`,+ action: 'base',+ label: m.environments_use_environment(),+ disabled: !shouldLoadEnvironment(item.environment) || isCurrent,+ onclick: () => void useEnvironment(item.environment),+ icon: EnvironmentsIcon+ });++ buttons.push({+ id: `${item.environment.id}-details`,+ action: 'inspect',+ label: m.common_view_details(),+ onclick: () => void goto(`/environments/${item.environment.id}`),+ icon: InspectIcon+ });++ return buttons;+ }++ function formatEnvironmentOverviewLabel(summary: DashboardOverviewSummary): string {+ if (summary.totalEnvironments === 0) {+ return m.dashboard_all_no_visible_environments();+ }++ const parts = [m.dashboard_all_reachable_summary({ count: summary.reachableEnvironments })];++ if (summary.unavailableEnvironments > 0) {+ parts.push(m.dashboard_all_unavailable_summary({ count: summary.unavailableEnvironments }));+ }++ if (summary.disabledEnvironments > 0) {+ parts.push(m.dashboard_all_disabled_summary({ count: summary.disabledEnvironments }));+ }++ return parts.join(' · ');+ }++ function formatContainerOverviewLabel(summary: DashboardOverviewSummary): string {+ if (summary.totalContainers === 0) {+ return m.dashboard_all_no_containers();+ }++ return m.dashboard_all_container_summary({ running: summary.runningContainers, stopped: summary.stoppedContainers });+ }++ function formatImageOverviewLabel(summary: DashboardOverviewSummary): string {+ if (summary.totalImages === 0) {+ return m.dashboard_all_no_images();+ }++ return m.dashboard_all_image_summary({ inUse: summary.imagesInUse, unused: summary.imagesUnused });+ }++ function formatStorageOverviewLabel(summary: DashboardOverviewSummary): string {+ if (summary.totalImageSize === 0) {+ return m.dashboard_all_no_storage();+ }++ if (summary.imagesUnused > 0) {+ return m.dashboard_all_unused_images_summary({ count: summary.imagesUnused });+ }++ return m.dashboard_all_images_tracked_summary({ count: summary.totalImages });+ }++ function openPruneDialog(item: DashboardEnvironmentOverview) {+ if (!canPruneEnvironment(item)) {+ return;+ }++ pruneEnvironment = item;+ isPruneDialogOpen = true;+ }++ function closePruneDialog() {+ if (pruningEnvironmentId) {+ return;+ }++ isPruneDialogOpen = false;+ pruneEnvironment = null;+ }++ async function confirmPrune(pruneRequest: SystemPruneRequest) {+ const selectedTypes = Object.keys(pruneRequest) as PruneType[];+ if (!pruneEnvironment || pruningEnvironmentId || selectedTypes.length === 0) {+ return;+ }++ const targetEnvironment = pruneEnvironment;+ const environmentId = targetEnvironment.environment.id;++ const typeLabels: Record<PruneType, string> = {+ containers: m.prune_stopped_containers(),+ images: m.prune_unused_images(),+ networks: m.prune_unused_networks(),+ volumes: m.prune_unused_volumes(),+ buildCache: m.build_cache()+ };+ const typesString = selectedTypes.map((type) => typeLabels[type]).join(', ');++ pruningEnvironmentId = environmentId;++ handleApiResultWithCallbacks({+ result: await tryCatch(systemService.pruneAllForEnvironment(environmentId, pruneRequest)),+ message: m.dashboard_prune_failed({ types: typesString }),+ setLoadingState: (value) => {+ pruningEnvironmentId = value ? environmentId : null;+ },+ onSuccess: async () => {+ isPruneDialogOpen = false;+ pruneEnvironment = null;+ if (selectedTypes.length === 1) {+ toast.success(m.dashboard_prune_success_one({ types: typesString }), {+ description: targetEnvironment.environment.name+ });+ } else {+ toast.success(m.dashboard_prune_success_many({ types: typesString }), {+ description: targetEnvironment.environment.name+ });+ }+ await refreshOverview();+ }+ });+ }+</script>++<div class="flex h-full min-h-0 flex-col gap-4 overflow-hidden pt-3 md:gap-5 md:pt-4">+ <header+ class="dark:border-surface/80 dark:bg-surface/10 shrink-0 rounded-xl border border-white/80 bg-white/10 p-4 shadow-sm backdrop-blur-sm sm:p-5"+ >+ <div class="relative flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">+ <div class="space-y-1.5">+ <p class="text-muted-foreground text-[11px] font-semibold tracking-[0.14em] uppercase">{m.dashboard_title()}</p>+ <h1 class="text-2xl font-bold tracking-tight sm:text-3xl">{heroGreeting}</h1>+ </div>++ <ArcaneButton+ action="restart"+ size="sm"+ customLabel={m.common_refresh()}+ icon={RefreshIcon}+ loading={isRefreshing}+ onclick={refreshOverview}+ />+ </div>+ </header>++ <section class="shrink-0 space-y-3">+ <h2 class="text-lg font-semibold tracking-tight">{m.common_overview()}</h2>++ {#await overviewSummaryPromise}+ <div class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">+ {#each [1, 2, 3, 4] as tile (tile)}+ <div class="border-border/50 bg-background/50 rounded-xl border p-4">+ <Skeleton class="h-3 w-24" />+ <Skeleton class="mt-3 h-9 w-16" />+ <Skeleton class="mt-2 h-4 w-32" />+ </div>+ {/each}+ </div>+ {:then summary}+ <div class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">+ <div class="border-border/50 bg-background/50 rounded-xl border p-4">+ <div class="text-muted-foreground flex items-center gap-1.5 text-[11px] font-semibold tracking-wide uppercase">+ <EnvironmentsIcon class="size-3.5" />+ <span>{m.environments_title()}</span>+ </div>+ <div class="mt-3 text-3xl font-semibold tracking-tight tabular-nums">{summary.totalEnvironments}</div>+ <div class="text-muted-foreground mt-1 text-sm">{formatEnvironmentOverviewLabel(summary)}</div>+ </div>++ <div class="border-border/50 bg-background/50 rounded-xl border p-4">+ <div class="text-muted-foreground flex items-center gap-1.5 text-[11px] font-semibold tracking-wide uppercase">+ <ContainersIcon class="size-3.5" />+ <span>{m.containers_title()}</span>+ </div>+ <div class="mt-3 text-3xl font-semibold tracking-tight tabular-nums">{summary.totalContainers}</div>+ <div class="text-muted-foreground mt-1 text-sm">{formatContainerOverviewLabel(summary)}</div>+ </div>++ <div class="border-border/50 bg-background/50 rounded-xl border p-4">+ <div class="text-muted-foreground flex items-center gap-1.5 text-[11px] font-semibold tracking-wide uppercase">+ <ImagesIcon class="size-3.5" />+ <span>{m.images_title()}</span>+ </div>+ <div class="mt-3 text-3xl font-semibold tracking-tight tabular-nums">{summary.totalImages}</div>+ <div class="text-muted-foreground mt-1 text-sm">{formatImageOverviewLabel(summary)}</div>+ </div>++ <div class="border-border/50 bg-background/50 rounded-xl border p-4">+ <div class="text-muted-foreground flex items-center gap-1.5 text-[11px] font-semibold tracking-wide uppercase">+ <VolumesIcon class="size-3.5" />+ <span>{m.dashboard_all_storage_title()}</span>+ </div>+ <div class="mt-3 text-3xl font-semibold tracking-tight tabular-nums">{bytes.format(summary.totalImageSize)}</div>+ <div class="text-muted-foreground mt-1 text-sm">{formatStorageOverviewLabel(summary)}</div>+ </div>+ </div>+ {/await}+ </section>++ <section class="flex min-h-0 flex-1 flex-col overflow-hidden">+ <div class="mb-3 flex items-center justify-between gap-3">+ <h2 class="text-lg font-semibold tracking-tight">{m.dashboard_all_environment_board_title()}</h2>+ </div>++ {#if environmentCards.length === 0}+ <div class="border-border/60 rounded-xl border border-dashed px-4 py-8 text-center">+ <p class="text-muted-foreground text-sm">{m.dashboard_all_no_visible_environments()}</p>+ </div>+ {:else}+ <div class="grid grid-cols-1 gap-4 overflow-y-auto pb-2 xl:grid-cols-2">+ {#each environmentCards as item (item.environment.id)}+ {@const baseItem = createBaseEnvironmentOverview(item.environment)}+ {@const environment = baseItem.environment}+ {@const resolvedStatus = resolveEnvironmentStatus(environment)}+ {@const statusVariant = getEnvironmentStatusVariant(resolvedStatus)}+ {@const transportBadge = getTransportBadge(environment)}+ {@const activity = getActivityMeta(environment)}+ {@const isCurrent = currentEnvironmentId === environment.id}+ {@const liveStatsState = getLiveStatsState(environment.id)}+ {@const systemStats = liveStatsState?.stats ?? null}+ {@const liveStatsLoading = liveStatsState?.loading ?? shouldLoadEnvironment(environment)}+ {@const cpuMetric = getCpuMetric(systemStats)}+ {@const memoryMetric = getMemoryMetric(systemStats)}+ {@const diskMetric = getDiskMetric(systemStats)}++ <Card.Root+ variant="outlined"+ class={`overflow-hidden border transition-colors ${isCurrent ? 'border-blue-500/40 bg-blue-500/5' : 'border-border/60'}`}+ >+ <Card.Content class="space-y-4 p-4">+ <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">+ <div class="min-w-0 space-y-2">+ <div class="flex flex-wrap items-center gap-2">+ <div class="text-base font-semibold tracking-tight">{environment.name}</div>+ {#if isCurrent}+ <StatusBadge text={m.common_current()} variant="blue" size="sm" minWidth="none" />+ {/if}+ <StatusBadge+ text={capitalizeFirstLetter(getResolvedStatusLabel(environment))}+ variant={statusVariant}+ size="sm"+ minWidth="none"+ />+ <StatusBadge text={transportBadge.text} variant={transportBadge.variant} size="sm" minWidth="none" />+ </div>++ <div class="text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">+ <span class="font-mono">{environment.apiUrl}</span>+ <span>•</span>+ <span title={activity.title}>{activity.label}: {activity.value}</span>+ </div>+ </div>++ <div class="flex min-w-0 flex-1 justify-end">+ {#if item.loadPromise}+ {#await item.loadPromise}+ <ActionButtonGroup buttons={getEnvironmentActionButtons(baseItem, isCurrent)} size="sm" />+ {:then loadedItem}+ <ActionButtonGroup buttons={getEnvironmentActionButtons(loadedItem, isCurrent)} size="sm" />+ {/await}+ {:else}+ <ActionButtonGroup buttons={getEnvironmentActionButtons(baseItem, isCurrent)} size="sm" />+ {/if}+ </div>+ </div>++ {#if item.loadPromise || isEnvironmentOnline(environment)}+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-3">+ <div class="border-border/50 bg-background/50 rounded-lg border p-3">+ <div class="text-muted-foreground text-[11px] font-semibold tracking-wide uppercase">+ {m.containers_title()}+ </div>+ {#if item.loadPromise}+ {#await item.loadPromise}+ <div class="mt-2 space-y-2">+ <Skeleton class="h-6 w-20" />+ <Skeleton class="h-3 w-24" />+ </div>+ {:then loadedItem}+ <div class="mt-1 text-lg font-semibold">+ {loadedItem.containers.runningContainers}/{loadedItem.containers.totalContainers}+ </div>+ <div class="text-muted-foreground text-xs">+ {loadedItem.containers.stoppedContainers}+ {m.common_stopped()}+ </div>+ {/await}+ {:else}+ <div class="mt-1 text-lg font-semibold">+ {baseItem.containers.runningContainers}/{baseItem.containers.totalContainers}+ </div>+ <div class="text-muted-foreground text-xs">+ {baseItem.containers.stoppedContainers}+ {m.common_stopped()}+ </div>+ {/if}+ </div>++ <div class="border-border/50 bg-background/50 rounded-lg border p-3">+ <div class="text-muted-foreground text-[11px] font-semibold tracking-wide uppercase">{m.images_title()}</div>+ {#if item.loadPromise}+ {#await item.loadPromise}+ <div class="mt-2 space-y-2">+ <Skeleton class="h-6 w-14" />+ <Skeleton class="h-3 w-28" />+ </div>+ {:then loadedItem}+ <div class="mt-1 text-lg font-semibold">{loadedItem.imageUsageCounts.totalImages}</div>+ <div class="text-muted-foreground text-xs">+ {loadedItem.imageUsageCounts.imagesInuse}+ {m.common_in_use()} · {loadedItem.imageUsageCounts.imagesUnused}+ {m.common_unused()}+ </div>+ {/await}+ {:else}+ <div class="mt-1 text-lg font-semibold">{baseItem.imageUsageCounts.totalImages}</div>+ <div class="text-muted-foreground text-xs">+ {baseItem.imageUsageCounts.imagesInuse}+ {m.common_in_use()} · {baseItem.imageUsageCounts.imagesUnused}+ {m.common_unused()}+ </div>+ {/if}+ </div>++ <div class="border-border/50 bg-background/50 rounded-lg border p-3">+ <div class="text-muted-foreground text-[11px] font-semibold tracking-wide uppercase">+ {m.dashboard_action_items_title()}+ </div>+ {#if item.loadPromise}+ {#await item.loadPromise}+ <div class="mt-2 space-y-2">+ <Skeleton class="h-6 w-12" />+ <Skeleton class="h-3 w-32" />+ </div>+ {:then loadedItem}+ <div class="mt-1 text-lg font-semibold">{loadedItem.actionItems.items.length}</div>+ <div class="text-muted-foreground text-xs">{getActionSummary(loadedItem)}</div>+ {/await}+ {:else}+ <div class="mt-1 text-lg font-semibold">{baseItem.actionItems.items.length}</div>+ <div class="text-muted-foreground text-xs">{getActionSummary(baseItem)}</div>+ {/if}+ </div>+ </div>+ {:else}+ <div class="border-border/50 bg-background/50 rounded-lg border px-4 py-3 text-sm">+ <p class="font-medium">{m.dashboard_all_environment_unavailable_title()}</p>+ <p class="text-muted-foreground mt-1">{m.dashboard_all_environment_unavailable_description()}</p>+ </div>+ {/if}++ {#if shouldLoadEnvironment(environment)}+ <div class="border-border/50 bg-background/40 rounded-xl border p-1">+ <div class="grid grid-cols-1 gap-1 sm:grid-cols-3">+ {#if liveStatsLoading}+ {#each [1, 2, 3] as tile (tile)}+ <div class="min-w-0 px-2.5 py-2.5">+ <div class="flex items-start justify-between gap-2">+ <Skeleton class="h-3 w-20" />+ <Skeleton class="h-5 w-12" />+ </div>+ <Skeleton class="mt-2 h-3 w-24" />+ <Skeleton class="mt-3 h-1.5 w-full" />+ </div>+ {/each}+ {:else}+ <DashboardMetricTile+ title={m.dashboard_meter_cpu()}+ icon={CpuIcon}+ value={formatPercent(cpuMetric)}+ label={getCpuMetricLabel(systemStats)}+ meterValue={cpuMetric}+ />++ <DashboardMetricTile+ title={m.dashboard_meter_memory()}+ icon={MemoryStickIcon}+ value={formatPercent(memoryMetric)}+ label={getCapacityLabel(systemStats?.memoryUsage, systemStats?.memoryTotal)}+ labelClass="truncate"+ meterValue={memoryMetric}+ />++ <DashboardMetricTile+ title={m.dashboard_meter_disk()}+ icon={VolumesIcon}+ value={formatPercent(diskMetric)}+ label={getCapacityLabel(systemStats?.diskUsage, systemStats?.diskTotal)}+ labelClass="truncate"+ meterValue={diskMetric}+ />+ {/if}+ </div>+ </div>+ {/if}++ {#if item.loadPromise}+ {#await item.loadPromise then loadedItem}+ {#if loadedItem.snapshotState === 'error' && loadedItem.snapshotError}+ <div+ class="rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-xs text-red-700 dark:text-red-300"+ >+ {m.dashboard_all_summary_unavailable({ error: loadedItem.snapshotError })}+ </div>+ {/if}+ {/await}+ {/if}+ </Card.Content>+ </Card.Root>+ {/each}+ </div>+ {/if}+ </section>+</div>++<PruneConfirmationDialog+ open={isPruneDialogOpen}+ isPruning={!!pruningEnvironmentId}+ onConfirm={confirmPrune}+ onCancel={closePruneDialog}+/>diff --git a/tests/spec/dashboard-system-stats.spec.ts b/tests/spec/dashboard-system-stats.spec.tsindex 024157606..b02093049 100644--- a/tests/spec/dashboard-system-stats.spec.ts+++ b/tests/spec/dashboard-system-stats.spec.ts@@ -1,5 +1,8 @@import { test, expect, type Page } from '@playwright/test';+const defaultDashboardPath = '/dashboard';+const currentDashboardPath = '/dashboard?view=current';+const mockedStats = {cpuUsage: 12.3,memoryUsage: 512 * 1024 * 1024,@@ -120,16 +123,20 @@ test.describe('Dashboard system stats websocket', () => {test('renders metrics from the system stats websocket stream', async ({ page }) => {await mockDashboardStatsWebSocket(page);- await page.goto('/dashboard');+ await page.goto(defaultDashboardPath);await page.waitForLoadState('networkidle');+ await expect(page.getByRole('tab', { name: 'All' })).toHaveAttribute('data-state', 'active');+ await expect(page.getByRole('heading', { name: 'Overview' })).toBeVisible();+ await expect(page.getByRole('heading', { name: 'Environment Board' })).toBeVisible();await expect(page.getByText('12.3%', { exact: true })).toBeVisible();await expect(page.getByText('50.0%', { exact: true })).toBeVisible();await expect(page.getByText('25.0%', { exact: true })).toBeVisible();await expect(page.getByText('7 CPUs', { exact: true })).toBeVisible();await expect(page.getByText('512 MB / 1 GB', { exact: true })).toBeVisible();await expect(page.getByText('256 MB / 1 GB', { exact: true })).toBeVisible();- await expect(page.locator('a[href="/swarm/cluster"]').first()).toBeVisible();+ await expect(page.getByText('Current', { exact: true }).first()).toBeVisible();+ await expect(page.getByText('HTTP', { exact: true }).first()).toBeVisible();});test('loads dashboard content from the snapshot endpoint without dashboard REST fan-out', async ({@@ -138,7 +145,7 @@ test.describe('Dashboard system stats websocket', () => {await mockDashboardStatsWebSocket(page);const requestPaths = collectEnvironmentRequestPaths(page);- await page.goto('/dashboard');+ await page.goto(defaultDashboardPath);await page.waitForLoadState('networkidle');expect(@@ -166,7 +173,10 @@ test.describe('Dashboard system stats websocket', () => {await mockDashboardStatsWebSocket(page);const requestPaths = collectEnvironmentRequestPaths(page);- await page.goto('/dashboard');+ await page.goto(defaultDashboardPath);+ await page.waitForLoadState('networkidle');+ await page.getByRole('tab', { name: 'Current' }).click();+ await expect(page).toHaveURL(currentDashboardPath);await page.waitForLoadState('networkidle');expect(diff --git a/types/dashboard/dashboard.go b/types/dashboard/dashboard.goindex b82688659..0e5b0c8d3 100644--- a/types/dashboard/dashboard.go+++ b/types/dashboard/dashboard.go@@ -3,6 +3,7 @@ package dashboardimport ("github.com/getarcaneapp/arcane/types/base"containertypes "github.com/getarcaneapp/arcane/types/container"+ environmenttypes "github.com/getarcaneapp/arcane/types/environment"imagetypes "github.com/getarcaneapp/arcane/types/image")@@ -103,3 +104,112 @@ type Snapshot struct {// Required: trueSettings SnapshotSettings `json:"settings"`}++type EnvironmentSnapshotState string++const (+ EnvironmentSnapshotStateReady EnvironmentSnapshotState = "ready"+ EnvironmentSnapshotStateSkipped EnvironmentSnapshotState = "skipped"+ EnvironmentSnapshotStateError EnvironmentSnapshotState = "error"+)++type EnvironmentOverview struct {+ // Environment is the normalized runtime environment record.+ //+ // Required: true+ Environment environmenttypes.Environment `json:"environment"`++ // Containers is the summarized container status for the environment.+ //+ // Required: true+ Containers containertypes.StatusCounts `json:"containers"`++ // ImageUsageCounts is the summarized image usage for the environment.+ //+ // Required: true+ ImageUsageCounts imagetypes.UsageCounts `json:"imageUsageCounts"`++ // ActionItems is the environment attention summary.+ //+ // Required: true+ ActionItems ActionItems `json:"actionItems"`++ // Settings is the minimal dashboard settings payload needed for per-environment actions.+ //+ // Required: true+ Settings SnapshotSettings `json:"settings"`++ // SnapshotState indicates whether the environment snapshot was fetched.+ //+ // Required: true+ SnapshotState EnvironmentSnapshotState `json:"snapshotState"`++ // SnapshotError contains a non-fatal snapshot retrieval error.+ //+ // Required: false+ SnapshotError *string `json:"snapshotError,omitempty"`+}++type EnvironmentsSummary struct {+ // TotalEnvironments is the number of visible environments.+ //+ // Required: true+ TotalEnvironments int `json:"totalEnvironments"`++ // OnlineEnvironments is the number of online environments.+ //+ // Required: true+ OnlineEnvironments int `json:"onlineEnvironments"`++ // StandbyEnvironments is the number of standby environments.+ //+ // Required: true+ StandbyEnvironments int `json:"standbyEnvironments"`++ // OfflineEnvironments is the number of offline environments.+ //+ // Required: true+ OfflineEnvironments int `json:"offlineEnvironments"`++ // PendingEnvironments is the number of pending environments.+ //+ // Required: true+ PendingEnvironments int `json:"pendingEnvironments"`++ // ErrorEnvironments is the number of error environments.+ //+ // Required: true+ ErrorEnvironments int `json:"errorEnvironments"`++ // DisabledEnvironments is the number of disabled environments.+ //+ // Required: true+ DisabledEnvironments int `json:"disabledEnvironments"`++ // Containers is the aggregated container status counts.+ //+ // Required: true+ Containers containertypes.StatusCounts `json:"containers"`++ // ImageUsageCounts is the aggregated image usage.+ //+ // Required: true+ ImageUsageCounts imagetypes.UsageCounts `json:"imageUsageCounts"`++ // EnvironmentsWithActionItems is the number of environments with attention items.+ //+ // Required: true+ EnvironmentsWithActionItems int `json:"environmentsWithActionItems"`+}++type EnvironmentsOverview struct {+ // Summary is the aggregated fleet summary.+ //+ // Required: true+ Summary EnvironmentsSummary `json:"summary"`++ // Environments contains per-environment overview rows.+ //+ // Required: true+ Environments []EnvironmentOverview `json:"environments"`+}diff --git a/types/environment/environment.go b/types/environment/environment.goindex 53d6ada62..47a80189c 100644--- a/types/environment/environment.go+++ b/types/environment/environment.go@@ -123,6 +123,11 @@ type Environment struct {// Required: falseIsEdge bool `json:"isEdge"`+ // LastSeen is the last successful manager-side health/contact timestamp.+ //+ // Required: false+ LastSeen *time.Time `json:"lastSeen,omitempty"`+// EdgeTransport indicates the active tunnel transport for an edge environment.// Values are "grpc" or "websocket" when connected.//