Skip to content

Modern Docker Management, Designed for Everyone

fix: consolidate dashboard into one api call, add missing indexes to database (#2138)

Kyle Mendellf8ccb7ae3feb
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.go
index d1d4aaa26..2100c4e08 100644
--- a/backend/internal/bootstrap/services_bootstrap.go
+++ b/backend/internal/bootstrap/services_bootstrap.go
@@ -72,7 +72,6 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config
svcs.Notification = services.NewNotificationService(db, cfg, svcs.Environment)
svcs.Apprise = services.NewAppriseService(db, cfg)
svcs.Vulnerability = services.NewVulnerabilityService(db, svcs.Docker, svcs.Event, svcs.Settings, svcs.Notification)
- svcs.Dashboard = services.NewDashboardService(db, svcs.Docker, svcs.Vulnerability)
svcs.ImageUpdate = services.NewImageUpdateService(db, svcs.Settings, svcs.ContainerRegistry, svcs.Docker, svcs.Event, svcs.Notification)
svcs.Image = services.NewImageService(db, svcs.Docker, svcs.ContainerRegistry, svcs.ImageUpdate, svcs.Vulnerability, svcs.Event)
svcs.GitRepository = services.NewGitRepositoryService(db, cfg.GitWorkDir, svcs.Event, svcs.Settings)
@@ -80,6 +79,7 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config
svcs.BuildWorkspace = services.NewBuildWorkspaceService(svcs.Settings)
svcs.Project = services.NewProjectService(db, svcs.Settings, svcs.Event, svcs.Image, svcs.Docker, svcs.Build)
svcs.Container = services.NewContainerService(db, svcs.Event, svcs.Docker, svcs.Image, svcs.Settings)
+ svcs.Dashboard = services.NewDashboardService(db, svcs.Docker, svcs.Container, svcs.Settings, svcs.Vulnerability)
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.Template = services.NewTemplateService(ctx, db, httpClient, svcs.Settings)
diff --git a/backend/internal/database/database_test.go b/backend/internal/database/database_test.go
index 940b4fc88..f0bbf6cbd 100644
--- a/backend/internal/database/database_test.go
+++ b/backend/internal/database/database_test.go
@@ -182,8 +182,92 @@ func TestInitialize_AllowsMigrationOptions(t *testing.T) {
require.NoError(t, db.Close())
}
+func TestInitialize_CreatesQueryPerformanceIndexes(t *testing.T) {
+ ctx := context.Background()
+ dsn := "file:" + filepath.Join(t.TempDir(), "arcane-indexes.db")
+
+ db, err := Initialize(ctx, dsn, MigrationOptions{})
+ require.NoError(t, err)
+ t.Cleanup(func() {
+ require.NoError(t, db.Close())
+ })
+
+ indexes := []string{
+ "idx_environments_access_token_not_null",
+ "idx_environments_enabled_true",
+ "idx_api_keys_expires_at_not_null",
+ "idx_api_keys_user_managed_by_created_at",
+ "idx_git_repositories_enabled_url",
+ "idx_git_repositories_auth_type",
+ "idx_gitops_syncs_environment_auto_sync",
+ "idx_gitops_syncs_auto_sync_true",
+ "idx_gitops_syncs_environment_last_sync_status",
+ "idx_gitops_syncs_environment_repository_id",
+ "idx_gitops_syncs_environment_project_id",
+ "idx_projects_path",
+ "idx_projects_dir_name_not_null",
+ "idx_compose_templates_lookup_name",
+ "idx_compose_templates_lookup_description",
+ "idx_volume_backups_volume_name_created_at",
+ "idx_image_builds_environment_created_at",
+ "idx_image_builds_environment_status",
+ "idx_events_environment_timestamp",
+ "idx_image_updates_repository_tag",
+ "idx_vulnerability_scans_status_total_count",
+ "idx_vulnerability_ignores_env_created_at",
+ "idx_vulnerability_ignores_env_vulnerability_id",
+ }
+
+ for _, indexName := range indexes {
+ assertSQLiteIndexExistsInternal(t, db, indexName)
+ }
+
+ removedIndexes := []string{
+ "idx_api_keys_user_id",
+ "idx_events_environment_id",
+ "idx_image_update_repository",
+ "idx_image_update_tag",
+ "idx_volume_backups_volume_name",
+ "idx_vulnerability_ignores_env",
+ "idx_vulnerability_ignores_vuln",
+ "idx_vulnerability_scans_status",
+ }
+
+ for _, indexName := range removedIndexes {
+ assertSQLiteIndexMissingInternal(t, db, indexName)
+ }
+}
+
func TestMigrationOptions_GitHubRefUsesBuildRevision(t *testing.T) {
assert.Equal(t, "abc123def456", githubRefForRevisionInternal(MigrationOptions{}, "abc123def456"))
assert.Equal(t, "custom-ref", githubRefForRevisionInternal(MigrationOptions{githubRef: "custom-ref"}, "abc123def456"))
assert.Equal(t, migrationRepositoryRefFallback, githubRefForRevisionInternal(MigrationOptions{}, "unknown"))
}
+
+func assertSQLiteIndexExistsInternal(t *testing.T, db *DB, indexName string) {
+ t.Helper()
+
+ var result struct {
+ Name string
+ }
+
+ err := db.Raw(
+ "SELECT name FROM sqlite_master WHERE type = 'index' AND name = ?",
+ indexName,
+ ).Scan(&result).Error
+ require.NoError(t, err)
+ assert.Equal(t, indexName, result.Name)
+}
+
+func assertSQLiteIndexMissingInternal(t *testing.T, db *DB, indexName string) {
+ t.Helper()
+
+ var count int64
+
+ err := db.Raw(
+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = ?",
+ indexName,
+ ).Scan(&count).Error
+ require.NoError(t, err)
+ assert.Zero(t, count, "expected index %s to be removed", indexName)
+}
diff --git a/backend/internal/huma/handlers/dashboard.go b/backend/internal/huma/handlers/dashboard.go
index 78e543068..0421c552b 100644
--- a/backend/internal/huma/handlers/dashboard.go
+++ b/backend/internal/huma/handlers/dashboard.go
@@ -14,6 +14,15 @@ type DashboardHandler struct {
dashboardService *services.DashboardService
}
+type GetDashboardInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ DebugAllGood bool `query:"debugAllGood" default:"false" doc:"Debug mode: force an empty action item list"`
+}
+
+type GetDashboardOutput struct {
+ Body base.ApiResponse[dashboardtypes.Snapshot]
+}
+
type GetDashboardActionItemsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
DebugAllGood bool `query:"debugAllGood" default:"false" doc:"Debug mode: force an empty action item list"`
@@ -26,6 +35,19 @@ type GetDashboardActionItemsOutput struct {
func RegisterDashboard(api huma.API, dashboardService *services.DashboardService) {
h := &DashboardHandler{dashboardService: dashboardService}
+ huma.Register(api, huma.Operation{
+ OperationID: "get-dashboard",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/dashboard",
+ Summary: "Get dashboard snapshot",
+ Description: "Returns the dashboard first-paint snapshot in a single response",
+ Tags: []string{"Dashboard"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetDashboard)
+
huma.Register(api, huma.Operation{
OperationID: "get-dashboard-action-items",
Method: http.MethodGet,
@@ -40,6 +62,33 @@ func RegisterDashboard(api huma.API, dashboardService *services.DashboardService
}, h.GetActionItems)
}
+func (h *DashboardHandler) GetDashboard(ctx context.Context, input *GetDashboardInput) (*GetDashboardOutput, error) {
+ if h.dashboardService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ // EnvironmentID is consumed by env proxy/auth middleware for routing/validation.
+ _ = input.EnvironmentID
+
+ snapshot, err := h.dashboardService.GetSnapshot(ctx, services.DashboardActionItemsOptions{
+ DebugAllGood: input.DebugAllGood,
+ })
+ if err != nil {
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+
+ if snapshot == nil {
+ return nil, huma.Error500InternalServerError("dashboard snapshot not available")
+ }
+
+ return &GetDashboardOutput{
+ Body: base.ApiResponse[dashboardtypes.Snapshot]{
+ Success: true,
+ Data: *snapshot,
+ },
+ }, nil
+}
+
func (h *DashboardHandler) GetActionItems(ctx context.Context, input *GetDashboardActionItemsInput) (*GetDashboardActionItemsOutput, error) {
if h.dashboardService == nil {
return nil, huma.Error500InternalServerError("service not available")
diff --git a/backend/internal/huma/handlers/dashboard_test.go b/backend/internal/huma/handlers/dashboard_test.go
new file mode 100644
index 000000000..a7dbaf46b
--- /dev/null
+++ b/backend/internal/huma/handlers/dashboard_test.go
@@ -0,0 +1,134 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/database"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ dashboardtypes "github.com/getarcaneapp/arcane/types/dashboard"
+ glsqlite "github.com/glebarez/sqlite"
+ dockercontainer "github.com/moby/moby/api/types/container"
+ dockerimage "github.com/moby/moby/api/types/image"
+ "github.com/stretchr/testify/require"
+ "gorm.io/gorm"
+)
+
+func setupDashboardHandlerTestDB(t *testing.T) (*database.DB, *services.SettingsService) {
+ t.Helper()
+
+ 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{}))
+
+ databaseDB := &database.DB{DB: db}
+ settingsSvc, err := services.NewSettingsService(context.Background(), databaseDB)
+ require.NoError(t, err)
+
+ return databaseDB, settingsSvc
+}
+
+func newDashboardHandlerTestDockerService(
+ t *testing.T,
+ settingsSvc *services.SettingsService,
+ containers []dockercontainer.Summary,
+ images []dockerimage.Summary,
+) *services.DockerClientService {
+ t.Helper()
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/_ping"):
+ w.Header().Set("API-Version", "1.41")
+ w.WriteHeader(http.StatusOK)
+ case strings.HasSuffix(r.URL.Path, "/containers/json"):
+ require.NoError(t, json.NewEncoder(w).Encode(containers))
+ case strings.HasSuffix(r.URL.Path, "/images/json"):
+ require.NoError(t, json.NewEncoder(w).Encode(images))
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(server.Close)
+
+ return services.NewDockerClientService(
+ nil,
+ &config.Config{DockerHost: server.URL},
+ settingsSvc,
+ )
+}
+
+func TestDashboardHandlerGetDashboardReturnsSnapshot(t *testing.T) {
+ db, settingsSvc := setupDashboardHandlerTestDB(t)
+
+ containers := []dockercontainer.Summary{
+ {
+ ID: "container-running",
+ Names: []string{"/running-app"},
+ Image: "repo/app:stable",
+ ImageID: "sha256:image-a",
+ Created: 1700000000,
+ State: "running",
+ Status: "Up 2 hours",
+ Labels: map[string]string{},
+ },
+ {
+ ID: "container-stopped",
+ Names: []string{"/stopped-app"},
+ Image: "repo/worker:latest",
+ ImageID: "sha256:image-b",
+ Created: 1800000000,
+ State: "exited",
+ Status: "Exited (0) 1 hour ago",
+ Labels: map[string]string{},
+ },
+ }
+ images := []dockerimage.Summary{
+ {ID: "sha256:image-a", RepoTags: []string{"repo/app:stable"}, Created: 1710000000, Size: 100},
+ {ID: "sha256:image-b", RepoTags: []string{"repo/worker:latest"}, Created: 1720000000, Size: 250},
+ }
+
+ expiresSoon := time.Now().Add(12 * time.Hour)
+ require.NoError(t, db.WithContext(context.Background()).Create(&models.ImageUpdateRecord{
+ ID: "sha256:image-b",
+ HasUpdate: true,
+ }).Error)
+ require.NoError(t, db.WithContext(context.Background()).Create(&models.ApiKey{
+ Name: "expiring-soon",
+ KeyHash: "hash-soon",
+ KeyPrefix: "arc_test_handler",
+ UserID: "user-1",
+ ExpiresAt: &expiresSoon,
+ }).Error)
+
+ dockerSvc := newDashboardHandlerTestDockerService(t, settingsSvc, containers, images)
+ handler := &DashboardHandler{
+ dashboardService: services.NewDashboardService(db, dockerSvc, nil, settingsSvc, nil),
+ }
+
+ output, err := handler.GetDashboard(context.Background(), &GetDashboardInput{EnvironmentID: "0"})
+ require.NoError(t, err)
+ require.NotNil(t, output)
+ require.True(t, output.Body.Success)
+
+ snapshot := output.Body.Data
+ require.Len(t, snapshot.Containers.Data, 2)
+ require.Len(t, snapshot.Images.Data, 2)
+ require.Equal(t, 1, snapshot.Containers.Counts.RunningContainers)
+ require.Equal(t, 1, snapshot.Containers.Counts.StoppedContainers)
+ require.Equal(t, "dangling", snapshot.Settings.DockerPruneMode)
+ require.ElementsMatch(t, []dashboardtypes.ActionItem{
+ {Kind: dashboardtypes.ActionItemKindStoppedContainers, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},
+ {Kind: dashboardtypes.ActionItemKindImageUpdates, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},
+ {Kind: dashboardtypes.ActionItemKindExpiringKeys, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},
+ }, snapshot.ActionItems.Items)
+}
diff --git a/backend/internal/middleware/environment_middleware_test.go b/backend/internal/middleware/environment_middleware_test.go
index d9f989260..4c032caa8 100644
--- a/backend/internal/middleware/environment_middleware_test.go
+++ b/backend/internal/middleware/environment_middleware_test.go
@@ -53,6 +53,30 @@ func TestEnvironmentMiddleware_ReturnsBadGatewayForEdgeResourcesWithoutTunnel(t
assert.False(t, localHandlerHit)
}
+func TestEnvironmentMiddleware_ProxiesDashboardResourcesForRemoteEnvironments(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ middleware := newTestEnvironmentMiddleware()
+ router := gin.New()
+ api := router.Group("/api")
+ api.Use(middleware.Handle)
+
+ localHandlerHit := false
+ api.GET("/environments/:id/dashboard", func(c *gin.Context) {
+ localHandlerHit = true
+ c.JSON(http.StatusOK, gin.H{"success": true})
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/dashboard", nil)
+ recorder := httptest.NewRecorder()
+
+ router.ServeHTTP(recorder, req)
+
+ assert.Equal(t, http.StatusBadGateway, recorder.Code)
+ assert.Contains(t, recorder.Body.String(), "Edge agent is not connected")
+ assert.False(t, localHandlerHit)
+}
+
func TestEnvironmentMiddleware_KeepsEdgeManagementEndpointsLocal(t *testing.T) {
gin.SetMode(gin.TestMode)
diff --git a/backend/internal/services/dashboard_service.go b/backend/internal/services/dashboard_service.go
index dd9b022b3..3a3c49070 100644
--- a/backend/internal/services/dashboard_service.go
+++ b/backend/internal/services/dashboard_service.go
@@ -3,20 +3,31 @@ package services
import (
"context"
"fmt"
+ "sort"
"time"
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane"
+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/timeouts"
+ "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"
+ dockercontainer "github.com/moby/moby/api/types/container"
+ dockerimage "github.com/moby/moby/api/types/image"
+ "github.com/moby/moby/client"
"golang.org/x/sync/errgroup"
)
const defaultDashboardAPIKeyExpiryWindow = 14 * 24 * time.Hour
+const dashboardSnapshotPreloadLimit = 50
type DashboardService struct {
db *database.DB
dockerService *DockerClientService
+ containerService *ContainerService
+ settingsService *SettingsService
vulnerabilityService *VulnerabilityService
}
@@ -27,15 +38,124 @@ type DashboardActionItemsOptions struct {
func NewDashboardService(
db *database.DB,
dockerService *DockerClientService,
+ containerService *ContainerService,
+ settingsService *SettingsService,
vulnerabilityService *VulnerabilityService,
) *DashboardService {
return &DashboardService{
db: db,
dockerService: dockerService,
+ containerService: containerService,
+ settingsService: settingsService,
vulnerabilityService: vulnerabilityService,
}
}
+func (s *DashboardService) GetSnapshot(ctx context.Context, options DashboardActionItemsOptions) (*dashboardtypes.Snapshot, error) {
+ if s.dockerService == nil {
+ return nil, fmt.Errorf("docker service not available")
+ }
+
+ var (
+ dockerContainers []dockercontainer.Summary
+ dockerImages []dockerimage.Summary
+ )
+
+ g, groupCtx := errgroup.WithContext(ctx)
+
+ g.Go(func() error {
+ containers, err := s.listDashboardContainersInternal(groupCtx)
+ if err != nil {
+ return fmt.Errorf("failed to load dashboard containers: %w", err)
+ }
+ dockerContainers = containers
+ return nil
+ })
+
+ g.Go(func() error {
+ images, err := s.listDashboardImagesInternal(groupCtx)
+ if err != nil {
+ return fmt.Errorf("failed to load dashboard images: %w", err)
+ }
+ dockerImages = images
+ return nil
+ })
+
+ if err := g.Wait(); err != nil {
+ return nil, err
+ }
+
+ filteredContainers := filterInternalContainers(dockerContainers, false)
+ containerItems := make([]containertypes.Summary, 0, len(filteredContainers))
+ if s.containerService != nil {
+ containerItems = s.containerService.buildContainerSummaries(filteredContainers, nil)
+ } else {
+ for _, container := range filteredContainers {
+ containerItems = append(containerItems, containertypes.NewSummary(container))
+ }
+ }
+
+ containerCounts := containertypes.StatusCounts{TotalContainers: len(containerItems)}
+ if s.containerService != nil {
+ containerCounts = s.containerService.calculateContainerStatusCounts(containerItems)
+ } else {
+ for _, item := range containerItems {
+ if item.State == "running" {
+ containerCounts.RunningContainers++
+ } else {
+ containerCounts.StoppedContainers++
+ }
+ }
+ }
+
+ sort.Slice(containerItems, func(i, j int) bool {
+ if containerItems[i].Created == containerItems[j].Created {
+ return containerItems[i].ID < containerItems[j].ID
+ }
+ return containerItems[i].Created > containerItems[j].Created
+ })
+ containerPage := limitDashboardItemsInternal(containerItems, dashboardSnapshotPreloadLimit)
+
+ projectIDByName := buildProjectIDMapInternal(ctx, s.db, filteredContainers)
+ imageUsageMap := buildUsageMapInternal(filteredContainers, projectIDByName)
+ imageItems := mapDockerImagesToDTOs(dockerImages, imageUsageMap, nil, nil)
+ sort.Slice(imageItems, func(i, j int) bool {
+ if imageItems[i].Size == imageItems[j].Size {
+ return imageItems[i].ID < imageItems[j].ID
+ }
+ return imageItems[i].Size > imageItems[j].Size
+ })
+ imagePage := limitDashboardItemsInternal(imageItems, dashboardSnapshotPreloadLimit)
+
+ imageUsageCounts := imagetypes.UsageCounts{}
+ imageUsageCounts.Inuse, imageUsageCounts.Unused, imageUsageCounts.Total = countImageUsageInternal(dockerImages, filteredContainers)
+ for _, img := range dockerImages {
+ imageUsageCounts.TotalSize += img.Size
+ }
+
+ actionItems, err := s.buildActionItemsForSnapshotInternal(ctx, options, filteredContainers, dockerImages)
+ if err != nil {
+ return nil, err
+ }
+
+ return &dashboardtypes.Snapshot{
+ Containers: dashboardtypes.SnapshotContainers{
+ Data: containerPage,
+ Counts: containerCounts,
+ Pagination: buildDashboardPaginationResponseInternal(len(containerItems), dashboardSnapshotPreloadLimit),
+ },
+ Images: dashboardtypes.SnapshotImages{
+ Data: imagePage,
+ Pagination: buildDashboardPaginationResponseInternal(len(imageItems), dashboardSnapshotPreloadLimit),
+ },
+ ImageUsageCounts: imageUsageCounts,
+ ActionItems: *actionItems,
+ Settings: dashboardtypes.SnapshotSettings{
+ DockerPruneMode: s.getDashboardDockerPruneModeInternal(ctx),
+ },
+ }, nil
+}
+
func (s *DashboardService) GetActionItems(ctx context.Context, options DashboardActionItemsOptions) (*dashboardtypes.ActionItems, error) {
if options.DebugAllGood {
return &dashboardtypes.ActionItems{Items: []dashboardtypes.ActionItem{}}, nil
@@ -127,6 +247,108 @@ func (s *DashboardService) GetActionItems(ctx context.Context, options Dashboard
return &dashboardtypes.ActionItems{Items: actionItems}, nil
}
+func (s *DashboardService) buildActionItemsForSnapshotInternal(
+ ctx context.Context,
+ options DashboardActionItemsOptions,
+ containers []dockercontainer.Summary,
+ images []dockerimage.Summary,
+) (*dashboardtypes.ActionItems, error) {
+ if options.DebugAllGood {
+ return &dashboardtypes.ActionItems{Items: []dashboardtypes.ActionItem{}}, nil
+ }
+
+ var (
+ pendingImageUpdates int
+ actionableVulnerabilities int
+ expiringAPIKeys int
+ )
+
+ g, groupCtx := errgroup.WithContext(ctx)
+
+ g.Go(func() error {
+ count, err := s.getPendingImageUpdatesCountForImageIDs(groupCtx, extractDockerImageIDsInternal(images))
+ if err != nil {
+ return err
+ }
+ pendingImageUpdates = count
+ return nil
+ })
+
+ g.Go(func() error {
+ count, err := s.getActionableVulnerabilitiesCountInternal(groupCtx)
+ if err != nil {
+ return err
+ }
+ actionableVulnerabilities = count
+ return nil
+ })
+
+ g.Go(func() error {
+ count, err := s.getExpiringAPIKeysCountInternal(groupCtx)
+ if err != nil {
+ return err
+ }
+ expiringAPIKeys = count
+ return nil
+ })
+
+ if err := g.Wait(); err != nil {
+ return nil, err
+ }
+
+ stoppedContainers := 0
+ for _, container := range containers {
+ if container.State != "running" {
+ stoppedContainers++
+ }
+ }
+
+ return buildDashboardActionItemsInternal(stoppedContainers, pendingImageUpdates, actionableVulnerabilities, expiringAPIKeys), nil
+}
+
+func buildDashboardActionItemsInternal(
+ stoppedContainers int,
+ pendingImageUpdates int,
+ actionableVulnerabilities int,
+ expiringAPIKeys int,
+) *dashboardtypes.ActionItems {
+ actionItems := make([]dashboardtypes.ActionItem, 0, 4)
+
+ if stoppedContainers > 0 {
+ actionItems = append(actionItems, dashboardtypes.ActionItem{
+ Kind: dashboardtypes.ActionItemKindStoppedContainers,
+ Count: stoppedContainers,
+ Severity: dashboardtypes.ActionItemSeverityWarning,
+ })
+ }
+
+ if pendingImageUpdates > 0 {
+ actionItems = append(actionItems, dashboardtypes.ActionItem{
+ Kind: dashboardtypes.ActionItemKindImageUpdates,
+ Count: pendingImageUpdates,
+ Severity: dashboardtypes.ActionItemSeverityWarning,
+ })
+ }
+
+ if actionableVulnerabilities > 0 {
+ actionItems = append(actionItems, dashboardtypes.ActionItem{
+ Kind: dashboardtypes.ActionItemKindActionableVulnerabilities,
+ Count: actionableVulnerabilities,
+ Severity: dashboardtypes.ActionItemSeverityCritical,
+ })
+ }
+
+ if expiringAPIKeys > 0 {
+ actionItems = append(actionItems, dashboardtypes.ActionItem{
+ Kind: dashboardtypes.ActionItemKindExpiringKeys,
+ Count: expiringAPIKeys,
+ Severity: dashboardtypes.ActionItemSeverityWarning,
+ })
+ }
+
+ return &dashboardtypes.ActionItems{Items: actionItems}
+}
+
func (s *DashboardService) getStoppedContainersCountInternal(ctx context.Context) (int, error) {
if s.dockerService == nil {
return 0, nil
@@ -161,17 +383,16 @@ func (s *DashboardService) getPendingImageUpdatesCountInternal(ctx context.Conte
return 0, fmt.Errorf("failed to load images for update counts: %w", err)
}
- if len(images) == 0 {
- return 0, nil
- }
+ return s.getPendingImageUpdatesCountForImageIDs(ctx, extractDockerImageIDsInternal(images))
+}
- imageIDs := make([]string, 0, len(images))
- for _, img := range images {
- imageIDs = append(imageIDs, img.ID)
+func (s *DashboardService) getPendingImageUpdatesCountForImageIDs(ctx context.Context, imageIDs []string) (int, error) {
+ if s.db == nil || len(imageIDs) == 0 {
+ return 0, nil
}
var count int64
- err = s.db.WithContext(ctx).
+ err := s.db.WithContext(ctx).
Model(&models.ImageUpdateRecord{}).
Where("id IN ? AND has_update = ?", imageIDs, true).
Count(&count).Error
@@ -182,6 +403,14 @@ func (s *DashboardService) getPendingImageUpdatesCountInternal(ctx context.Conte
return int(count), nil
}
+func (s *DashboardService) getDashboardDockerPruneModeInternal(ctx context.Context) string {
+ if s.settingsService == nil {
+ return "dangling"
+ }
+
+ return s.settingsService.GetStringSetting(ctx, "dockerPruneMode", "dangling")
+}
+
func (s *DashboardService) getActionableVulnerabilitiesCountInternal(ctx context.Context) (int, error) {
if s.vulnerabilityService == nil {
return 0, nil
@@ -216,3 +445,96 @@ func (s *DashboardService) getExpiringAPIKeysCountInternal(ctx context.Context)
return int(count), nil
}
+
+func extractDockerImageIDsInternal(images []dockerimage.Summary) []string {
+ if len(images) == 0 {
+ return nil
+ }
+
+ imageIDs := make([]string, 0, len(images))
+ for _, img := range images {
+ if img.ID == "" {
+ continue
+ }
+ imageIDs = append(imageIDs, img.ID)
+ }
+
+ return imageIDs
+}
+
+func (s *DashboardService) listDashboardContainersInternal(ctx context.Context) ([]dockercontainer.Summary, error) {
+ if s.dockerService == nil {
+ return nil, fmt.Errorf("docker service not available")
+ }
+
+ dockerClient, err := s.dockerService.GetClient(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+
+ apiCtx, cancel := timeouts.WithTimeout(ctx, s.getDockerAPITimeoutSecondsInternal(ctx), timeouts.DefaultDockerAPI)
+ defer cancel()
+
+ containerList, err := dockerClient.ContainerList(apiCtx, client.ContainerListOptions{All: true})
+ if err != nil {
+ return nil, fmt.Errorf("failed to list Docker containers: %w", err)
+ }
+
+ return containerList.Items, nil
+}
+
+func (s *DashboardService) listDashboardImagesInternal(ctx context.Context) ([]dockerimage.Summary, error) {
+ if s.dockerService == nil {
+ return nil, fmt.Errorf("docker service not available")
+ }
+
+ dockerClient, err := s.dockerService.GetClient(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+
+ apiCtx, cancel := timeouts.WithTimeout(ctx, s.getDockerAPITimeoutSecondsInternal(ctx), timeouts.DefaultDockerAPI)
+ defer cancel()
+
+ imageList, err := dockerClient.ImageList(apiCtx, client.ImageListOptions{All: true})
+ if err != nil {
+ return nil, fmt.Errorf("failed to list Docker images: %w", err)
+ }
+
+ return imageList.Items, nil
+}
+
+func (s *DashboardService) getDockerAPITimeoutSecondsInternal(ctx context.Context) int {
+ if s.settingsService == nil {
+ return 0
+ }
+
+ return s.settingsService.GetIntSetting(ctx, "dockerApiTimeout", 0)
+}
+
+func buildDashboardPaginationResponseInternal(totalItems int, limit int) base.PaginationResponse {
+ if limit <= 0 {
+ limit = dashboardSnapshotPreloadLimit
+ }
+
+ totalPages := 1
+ if totalItems > 0 {
+ totalPages = (totalItems + limit - 1) / limit
+ }
+
+ return base.PaginationResponse{
+ TotalPages: int64(totalPages),
+ TotalItems: int64(totalItems),
+ CurrentPage: 1,
+ ItemsPerPage: limit,
+ GrandTotalItems: int64(totalItems),
+ }
+}
+
+func limitDashboardItemsInternal[T any](items []T, limit int) []T {
+ if limit <= 0 || len(items) <= limit {
+ return items
+ }
+
+ return items[:limit]
+}
diff --git a/backend/internal/services/dashboard_service_test.go b/backend/internal/services/dashboard_service_test.go
index 48856d85e..3516f496e 100644
--- a/backend/internal/services/dashboard_service_test.go
+++ b/backend/internal/services/dashboard_service_test.go
@@ -2,6 +2,10 @@ package services
import (
"context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
"testing"
"time"
@@ -9,18 +13,25 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/models"
dashboardtypes "github.com/getarcaneapp/arcane/types/dashboard"
glsqlite "github.com/glebarez/sqlite"
+ dockercontainer "github.com/moby/moby/api/types/container"
+ dockerimage "github.com/moby/moby/api/types/image"
+ "github.com/moby/moby/client"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
-func setupDashboardServiceTestDB(t *testing.T) *database.DB {
+func setupDashboardServiceTestDB(t *testing.T) (*database.DB, *SettingsService) {
t.Helper()
- db, err := gorm.Open(glsqlite.Open(":memory:"), &gorm.Config{})
+ 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{}))
+ require.NoError(t, db.AutoMigrate(&models.ApiKey{}, &models.ImageUpdateRecord{}, &models.Project{}, &models.SettingVariable{}))
- return &database.DB{DB: db}
+ databaseDB := &database.DB{DB: db}
+ settingsSvc, err := NewSettingsService(context.Background(), databaseDB)
+ require.NoError(t, err)
+
+ return databaseDB, settingsSvc
}
func createDashboardTestAPIKey(t *testing.T, db *database.DB, key models.ApiKey) {
@@ -28,9 +39,51 @@ func createDashboardTestAPIKey(t *testing.T, db *database.DB, key models.ApiKey)
require.NoError(t, db.WithContext(context.Background()).Create(&key).Error)
}
+func createDashboardTestImageUpdateRecord(t *testing.T, db *database.DB, record models.ImageUpdateRecord) {
+ t.Helper()
+ require.NoError(t, db.WithContext(context.Background()).Create(&record).Error)
+}
+
+func newDashboardTestDockerService(
+ t *testing.T,
+ settingsSvc *SettingsService,
+ containers []dockercontainer.Summary,
+ images []dockerimage.Summary,
+) *DockerClientService {
+ t.Helper()
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/containers/json"):
+ require.NoError(t, json.NewEncoder(w).Encode(containers))
+ case strings.HasSuffix(r.URL.Path, "/images/json"):
+ require.NoError(t, json.NewEncoder(w).Encode(images))
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(server.Close)
+
+ dockerClient, err := client.NewClientWithOpts(
+ client.WithHost(server.URL),
+ client.WithVersion("1.41"),
+ )
+ require.NoError(t, err)
+ t.Cleanup(func() {
+ _ = dockerClient.Close()
+ })
+
+ return &DockerClientService{
+ client: dockerClient,
+ settingsService: settingsSvc,
+ }
+}
+
func TestDashboardService_GetActionItems_IncludesExpiringAPIKeys(t *testing.T) {
- db := setupDashboardServiceTestDB(t)
- svc := NewDashboardService(db, nil, nil)
+ db, settingsSvc := setupDashboardServiceTestDB(t)
+ svc := NewDashboardService(db, nil, nil, settingsSvc, nil)
now := time.Now()
expiringSoon := now.Add(24 * time.Hour)
@@ -77,8 +130,8 @@ func TestDashboardService_GetActionItems_IncludesExpiringAPIKeys(t *testing.T) {
}
func TestDashboardService_GetActionItems_DebugAllGoodReturnsNoItems(t *testing.T) {
- db := setupDashboardServiceTestDB(t)
- svc := NewDashboardService(db, nil, nil)
+ db, settingsSvc := setupDashboardServiceTestDB(t)
+ svc := NewDashboardService(db, nil, nil, settingsSvc, nil)
expiresAt := time.Now().Add(2 * time.Hour)
createDashboardTestAPIKey(t, db, models.ApiKey{
@@ -96,3 +149,121 @@ func TestDashboardService_GetActionItems_DebugAllGoodReturnsNoItems(t *testing.T
require.NotNil(t, actionItems)
require.Empty(t, actionItems.Items)
}
+
+func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {
+ db, settingsSvc := setupDashboardServiceTestDB(t)
+
+ containers := []dockercontainer.Summary{
+ {
+ ID: "container-running",
+ Names: []string{"/running-app"},
+ Image: "repo/app:stable",
+ ImageID: "sha256:image-a",
+ Created: 1700000000,
+ State: "running",
+ Status: "Up 2 hours",
+ Labels: map[string]string{},
+ },
+ {
+ ID: "container-stopped",
+ Names: []string{"/stopped-app"},
+ Image: "repo/worker:latest",
+ ImageID: "sha256:image-b",
+ Created: 1800000000,
+ State: "exited",
+ Status: "Exited (0) 1 hour ago",
+ Labels: map[string]string{},
+ },
+ {
+ ID: "container-internal",
+ Names: []string{"/arcane"},
+ Image: "ghcr.io/getarcaneapp/arcane:latest",
+ ImageID: "sha256:image-c",
+ Created: 1900000000,
+ State: "running",
+ Status: "Up 10 minutes",
+ Labels: map[string]string{
+ "com.getarcaneapp.internal.resource": "true",
+ },
+ },
+ }
+ images := []dockerimage.Summary{
+ {ID: "sha256:image-a", RepoTags: []string{"repo/app:stable"}, Created: 1710000000, Size: 100},
+ {ID: "sha256:image-b", RepoTags: []string{"repo/worker:latest"}, Created: 1720000000, Size: 250},
+ {ID: "sha256:image-c", RepoTags: []string{"ghcr.io/getarcaneapp/arcane:latest"}, Created: 1730000000, Size: 175},
+ }
+
+ createDashboardTestImageUpdateRecord(t, db, models.ImageUpdateRecord{ID: "sha256:image-b", HasUpdate: true})
+
+ expiresSoon := time.Now().Add(12 * time.Hour)
+ createDashboardTestAPIKey(t, db, models.ApiKey{
+ Name: "expiring-soon",
+ KeyHash: "hash-soon",
+ KeyPrefix: "arc_test_snapshot",
+ UserID: "user-1",
+ ExpiresAt: &expiresSoon,
+ })
+
+ dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images)
+ svc := NewDashboardService(db, dockerSvc, nil, settingsSvc, nil)
+
+ snapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{})
+ require.NoError(t, err)
+ require.NotNil(t, snapshot)
+
+ require.Len(t, snapshot.Containers.Data, 2)
+ require.Equal(t, "container-stopped", snapshot.Containers.Data[0].ID)
+ require.Equal(t, 1, snapshot.Containers.Counts.RunningContainers)
+ require.Equal(t, 1, snapshot.Containers.Counts.StoppedContainers)
+ require.Equal(t, 2, snapshot.Containers.Counts.TotalContainers)
+ require.EqualValues(t, 2, snapshot.Containers.Pagination.TotalItems)
+
+ require.Len(t, snapshot.Images.Data, 3)
+ require.Equal(t, "sha256:image-b", snapshot.Images.Data[0].ID)
+ require.Equal(t, 2, snapshot.ImageUsageCounts.Inuse)
+ require.Equal(t, 1, snapshot.ImageUsageCounts.Unused)
+ require.Equal(t, 3, snapshot.ImageUsageCounts.Total)
+ require.EqualValues(t, 525, snapshot.ImageUsageCounts.TotalSize)
+ require.Equal(t, "dangling", snapshot.Settings.DockerPruneMode)
+
+ require.ElementsMatch(t, []dashboardtypes.ActionItem{
+ {Kind: dashboardtypes.ActionItemKindStoppedContainers, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},
+ {Kind: dashboardtypes.ActionItemKindImageUpdates, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},
+ {Kind: dashboardtypes.ActionItemKindExpiringKeys, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},
+ }, snapshot.ActionItems.Items)
+}
+
+func TestDashboardService_GetSnapshot_DebugAllGoodOnlyClearsActionItems(t *testing.T) {
+ db, settingsSvc := setupDashboardServiceTestDB(t)
+
+ containers := []dockercontainer.Summary{
+ {
+ ID: "container-stopped",
+ Names: []string{"/stopped-app"},
+ Image: "repo/worker:latest",
+ ImageID: "sha256:image-b",
+ Created: 1800000000,
+ State: "exited",
+ Status: "Exited (0) 1 hour ago",
+ Labels: map[string]string{},
+ },
+ }
+ images := []dockerimage.Summary{
+ {ID: "sha256:image-b", RepoTags: []string{"repo/worker:latest"}, Created: 1720000000, Size: 250},
+ }
+
+ createDashboardTestImageUpdateRecord(t, db, models.ImageUpdateRecord{ID: "sha256:image-b", HasUpdate: true})
+
+ dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images)
+ svc := NewDashboardService(db, dockerSvc, nil, settingsSvc, nil)
+
+ snapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{DebugAllGood: true})
+ require.NoError(t, err)
+ require.NotNil(t, snapshot)
+
+ require.Len(t, snapshot.Containers.Data, 1)
+ require.Len(t, snapshot.Images.Data, 1)
+ require.Equal(t, 1, snapshot.Containers.Counts.StoppedContainers)
+ require.Equal(t, 1, snapshot.ImageUsageCounts.Inuse)
+ require.Empty(t, snapshot.ActionItems.Items)
+}
diff --git a/backend/internal/services/gitops_sync_service.go b/backend/internal/services/gitops_sync_service.go
index 14b6ed970..d049916f4 100644
--- a/backend/internal/services/gitops_sync_service.go
+++ b/backend/internal/services/gitops_sync_service.go
@@ -29,6 +29,13 @@ type GitOpsSyncService struct {
const defaultGitSyncTimeout = 5 * time.Minute
+type scheduledGitOpsSync struct {
+ ID string
+ EnvironmentID string
+ SyncInterval int
+ LastSyncAt *time.Time
+}
+
func NewGitOpsSyncService(db *database.DB, repoService *GitRepositoryService, projectService *ProjectService, eventService *EventService) *GitOpsSyncService {
return &GitOpsSyncService{
db: db,
@@ -458,10 +465,10 @@ func (s *GitOpsSyncService) GetSyncStatus(ctx context.Context, environmentID, id
}
func (s *GitOpsSyncService) SyncAllEnabled(ctx context.Context) error {
- var syncs []models.GitOpsSync
+ var syncs []scheduledGitOpsSync
if err := s.db.WithContext(ctx).
- Preload("Repository").
- Preload("Project").
+ Table("gitops_syncs").
+ Select("id", "environment_id", "sync_interval", "last_sync_at").
Where("auto_sync = ?", true).
Find(&syncs).Error; err != nil {
return fmt.Errorf("failed to get auto-sync enabled syncs: %w", err)
diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.go
index 6d522e02d..8d7508462 100644
--- a/backend/internal/services/project_service.go
+++ b/backend/internal/services/project_service.go
@@ -744,6 +744,12 @@ func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPa
Where("path = ? OR dir_name = ?", dirPath, dirName).
First(&existing).Error
+ filesystemProject := models.Project{
+ Name: dirName,
+ Path: dirPath,
+ }
+ serviceCount, serviceCountErr := s.countServicesFromCompose(ctx, filesystemProject)
+
if errors.Is(err, gorm.ErrRecordNotFound) {
// Create a minimal project entry
reason := "Project discovered from filesystem, status pending Docker service query"
@@ -753,13 +759,16 @@ func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPa
Path: dirPath,
Status: models.ProjectStatusUnknown,
StatusReason: new(reason),
- ServiceCount: 0,
+ ServiceCount: serviceCount,
RunningCount: 0,
}
slog.InfoContext(ctx, "Discovered new project with unknown status",
"project", dirName,
"path", dirPath,
"reason", reason)
+ if serviceCountErr != nil {
+ slog.WarnContext(ctx, "failed to read compose service count during project discovery", "project", dirName, "path", dirPath, "error", serviceCountErr)
+ }
if cerr := s.db.WithContext(ctx).Create(proj).Error; cerr != nil {
return fmt.Errorf("create project for %q failed: %w", dirPath, cerr)
}
@@ -776,6 +785,11 @@ func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPa
if existing.DirName == nil || *existing.DirName != dirName {
updates["dir_name"] = dirName
}
+ if serviceCountErr == nil && existing.ServiceCount != serviceCount {
+ updates["service_count"] = serviceCount
+ } else if serviceCountErr != nil {
+ slog.WarnContext(ctx, "failed to refresh compose service count during project sync", "projectID", existing.ID, "path", dirPath, "error", serviceCountErr)
+ }
if len(updates) == 0 {
return nil
}
@@ -2943,6 +2957,13 @@ func (s *ProjectService) mapProjectToDto(ctx context.Context, p models.Project,
// since we are not parsing the YAML here.
resp.ServiceCount = p.ServiceCount
resp.RunningCount = runningCount
+ if resp.ServiceCount == 0 && len(services) > 0 {
+ resp.ServiceCount = len(services)
+ // Persist the inferred count so later list loads do not need compose parsing.
+ go func(ctx context.Context, pid string, count int) {
+ s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", pid).Update("service_count", count)
+ }(context.WithoutCancel(ctx), p.ID, resp.ServiceCount)
+ }
// Fix for missing service count (e.g. newly discovered projects)
if resp.ServiceCount == 0 {
diff --git a/backend/internal/services/project_service_test.go b/backend/internal/services/project_service_test.go
index 77062ec10..ad177c7d4 100644
--- a/backend/internal/services/project_service_test.go
+++ b/backend/internal/services/project_service_test.go
@@ -1794,6 +1794,33 @@ func TestProjectService_SyncProjectsFromFileSystem_RemovesSymlinkedProjectsWhenD
require.NoError(t, statErr)
}
+func TestProjectService_SyncProjectsFromFileSystem_RefreshesServiceCountOnComposeChange(t *testing.T) {
+ db := setupProjectTestDB(t)
+ ctx := context.Background()
+
+ settingsService, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ projectsRoot := t.TempDir()
+ projectPath := createComposeProjectDir(t, projectsRoot, "demo")
+
+ require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsRoot))
+
+ svc := NewProjectService(db, settingsService, nil, nil, nil, nil)
+ require.NoError(t, svc.SyncProjectsFromFileSystem(ctx))
+
+ var project models.Project
+ require.NoError(t, db.WithContext(ctx).Where("path = ?", projectPath).First(&project).Error)
+ assert.Equal(t, 1, project.ServiceCount)
+
+ updatedCompose := "services:\n app:\n image: nginx:alpine\n worker:\n image: busybox:latest\n"
+ require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte(updatedCompose), 0o644))
+
+ require.NoError(t, svc.SyncProjectsFromFileSystem(ctx))
+ require.NoError(t, db.WithContext(ctx).Where("id = ?", project.ID).First(&project).Error)
+ assert.Equal(t, 2, project.ServiceCount)
+}
+
func TestProjectService_UpdateProject_WritesThroughSymlinkedProjectPath(t *testing.T) {
db := setupProjectTestDB(t)
ctx := context.Background()
diff --git a/backend/pkg/fswatch/watcher.go b/backend/pkg/fswatch/watcher.go
index e395e564e..96e71d637 100644
--- a/backend/pkg/fswatch/watcher.go
+++ b/backend/pkg/fswatch/watcher.go
@@ -210,8 +210,8 @@ func (fw *Watcher) shouldHandleEvent(event fsnotify.Event) bool {
name := filepath.Base(event.Name)
// Watch for new directories, compose files, .env being manipulated.
- if event.Has(fsnotify.Write) || event.Has(fsnotify.Create) || event.Has(fsnotify.Rename) || event.Has(fsnotify.Remove) {
- if fw.isWatchableDirectory(event.Name) || projects.IsProjectFile(name) {
+ if event.Has(fsnotify.Write) || event.Has(fsnotify.Create) || event.Has(fsnotify.Rename) || event.Has(fsnotify.Remove) || event.Has(fsnotify.Chmod) {
+ if fw.isWatchableDirectory(event.Name) || projects.IsProjectFile(name) || fw.isWatchablePath(event.Name) {
return true
}
}
@@ -327,3 +327,17 @@ func (fw *Watcher) isWatchableDirectory(path string) bool {
return resolvedInfo.IsDir()
}
+
+func (fw *Watcher) isWatchablePath(path string) bool {
+ cleanPath := filepath.Clean(path)
+ if cleanPath == fw.watchedPath {
+ return true
+ }
+
+ parent := filepath.Dir(cleanPath)
+ if parent == "." {
+ return false
+ }
+
+ return fw.shouldWatchDir(parent)
+}
diff --git a/backend/pkg/fswatch/watcher_test.go b/backend/pkg/fswatch/watcher_test.go
index a82c7b2fd..512b028f8 100644
--- a/backend/pkg/fswatch/watcher_test.go
+++ b/backend/pkg/fswatch/watcher_test.go
@@ -48,6 +48,75 @@ func TestWatcher_StartWatchesExistingSymlinkDirectoriesWhenEnabled(t *testing.T)
}
}
+func TestWatcher_StartTriggersOnAtomicSaveTempFileInsideProjectDir(t *testing.T) {
+ root := t.TempDir()
+ projectDir := filepath.Join(root, "demo")
+ require.NoError(t, os.MkdirAll(projectDir, 0o755))
+
+ changeCh := make(chan struct{}, 1)
+ ctx := t.Context()
+
+ watcher, err := NewWatcher(root, WatcherOptions{
+ Debounce: 25 * time.Millisecond,
+ MaxDepth: 1,
+ OnChange: func(context.Context) {
+ select {
+ case changeCh <- struct{}{}:
+ default:
+ }
+ },
+ })
+ require.NoError(t, err)
+ require.NoError(t, watcher.Start(ctx))
+ defer func() {
+ require.NoError(t, watcher.Stop())
+ }()
+
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, ".compose.yaml.tmp"), []byte("services: {}\n"), 0o644))
+
+ select {
+ case <-changeCh:
+ case <-time.After(2 * time.Second):
+ t.Fatal("expected temp file change inside project directory to trigger watcher callback")
+ }
+}
+
+func TestWatcher_StartTriggersOnChmodInsideProjectDir(t *testing.T) {
+ root := t.TempDir()
+ projectDir := filepath.Join(root, "demo")
+ require.NoError(t, os.MkdirAll(projectDir, 0o755))
+
+ targetFile := filepath.Join(projectDir, "notes.tmp")
+ require.NoError(t, os.WriteFile(targetFile, []byte("demo\n"), 0o644))
+
+ changeCh := make(chan struct{}, 1)
+ ctx := t.Context()
+
+ watcher, err := NewWatcher(root, WatcherOptions{
+ Debounce: 25 * time.Millisecond,
+ MaxDepth: 1,
+ OnChange: func(context.Context) {
+ select {
+ case changeCh <- struct{}{}:
+ default:
+ }
+ },
+ })
+ require.NoError(t, err)
+ require.NoError(t, watcher.Start(ctx))
+ defer func() {
+ require.NoError(t, watcher.Stop())
+ }()
+
+ require.NoError(t, os.Chmod(targetFile, 0o600))
+
+ select {
+ case <-changeCh:
+ case <-time.After(2 * time.Second):
+ t.Fatal("expected chmod inside project directory to trigger watcher callback")
+ }
+}
+
func TestWatcher_StartSkipsExistingSymlinkDirectoriesWhenDisabled(t *testing.T) {
root := t.TempDir()
targetRoot := t.TempDir()
diff --git a/backend/pkg/projects/fs_util.go b/backend/pkg/projects/fs_util.go
index c9cd0221e..fddc5308a 100644
--- a/backend/pkg/projects/fs_util.go
+++ b/backend/pkg/projects/fs_util.go
@@ -24,15 +24,7 @@ func GetProjectsDirectory(ctx context.Context, projectsDir string) (string, erro
}
}
- // Always resolve to an absolute, cleaned path so downstream code and DB
- // store a canonical location (prevents relative paths like "data/projects").
- absDir, err := filepath.Abs(projectsDirectory)
- if err == nil {
- projectsDirectory = filepath.Clean(absDir)
- } else {
- // If Abs fails for any reason, still clean the provided value
- projectsDirectory = filepath.Clean(projectsDirectory)
- }
+ projectsDirectory = resolveProjectsDirectoryPath(projectsDirectory)
if _, err := os.Stat(projectsDirectory); os.IsNotExist(err) {
if err := os.MkdirAll(projectsDirectory, pkgutils.DirPerm); err != nil {
@@ -44,6 +36,56 @@ func GetProjectsDirectory(ctx context.Context, projectsDir string) (string, erro
return projectsDirectory, nil
}
+func resolveProjectsDirectoryPath(projectsDirectory string) string {
+ if filepath.IsAbs(projectsDirectory) {
+ return filepath.Clean(projectsDirectory)
+ }
+
+ if backendRoot, ok := findBackendModuleRoot(); ok {
+ return filepath.Clean(filepath.Join(backendRoot, projectsDirectory))
+ }
+
+ absDir, err := filepath.Abs(projectsDirectory)
+ if err == nil {
+ return filepath.Clean(absDir)
+ }
+
+ return filepath.Clean(projectsDirectory)
+}
+
+func findBackendModuleRoot() (string, bool) {
+ cwd, err := os.Getwd()
+ if err != nil {
+ return "", false
+ }
+
+ candidates := []string{
+ cwd,
+ filepath.Join(cwd, "backend"),
+ }
+
+ for _, candidate := range candidates {
+ if isBackendModuleRoot(candidate) {
+ return candidate, true
+ }
+ }
+
+ return "", false
+}
+
+func isBackendModuleRoot(path string) bool {
+ if _, err := os.Stat(filepath.Join(path, "go.mod")); err != nil {
+ return false
+ }
+ if _, err := os.Stat(filepath.Join(path, "internal")); err != nil {
+ return false
+ }
+ if _, err := os.Stat(filepath.Join(path, "pkg")); err != nil {
+ return false
+ }
+ return true
+}
+
func ReadProjectFiles(projectPath string) (composeContent, envContent string, err error) {
if composeFile, derr := DetectComposeFile(projectPath); derr == nil && composeFile != "" {
if content, rerr := os.ReadFile(composeFile); rerr == nil {
diff --git a/backend/pkg/projects/fs_util_test.go b/backend/pkg/projects/fs_util_test.go
new file mode 100644
index 000000000..60d960390
--- /dev/null
+++ b/backend/pkg/projects/fs_util_test.go
@@ -0,0 +1,41 @@
+package projects
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestGetProjectsDirectory_ResolvesRelativePathAgainstBackendModuleRoot(t *testing.T) {
+ repoRoot := t.TempDir()
+ backendRoot := filepath.Join(repoRoot, "backend")
+ require.NoError(t, os.MkdirAll(filepath.Join(repoRoot, "data", "projects"), 0o755))
+ require.NoError(t, os.MkdirAll(filepath.Join(backendRoot, "internal"), 0o755))
+ require.NoError(t, os.MkdirAll(filepath.Join(backendRoot, "pkg"), 0o755))
+ require.NoError(t, os.MkdirAll(filepath.Join(backendRoot, "data", "projects"), 0o755))
+ require.NoError(t, os.WriteFile(filepath.Join(backendRoot, "go.mod"), []byte("module example.com/backend\n"), 0o644))
+
+ t.Chdir(repoRoot)
+
+ resolved, err := GetProjectsDirectory(context.Background(), "data/projects")
+ require.NoError(t, err)
+ assert.Equal(t, filepath.Join(backendRoot, "data", "projects"), resolved)
+}
+
+func TestGetProjectsDirectory_ResolvesRelativePathFromBackendWorkingDirectory(t *testing.T) {
+ backendRoot := t.TempDir()
+ require.NoError(t, os.MkdirAll(filepath.Join(backendRoot, "internal"), 0o755))
+ require.NoError(t, os.MkdirAll(filepath.Join(backendRoot, "pkg"), 0o755))
+ require.NoError(t, os.MkdirAll(filepath.Join(backendRoot, "data", "projects"), 0o755))
+ require.NoError(t, os.WriteFile(filepath.Join(backendRoot, "go.mod"), []byte("module example.com/backend\n"), 0o644))
+
+ t.Chdir(backendRoot)
+
+ resolved, err := GetProjectsDirectory(context.Background(), "data/projects")
+ require.NoError(t, err)
+ assert.Equal(t, filepath.Join(backendRoot, "data", "projects"), resolved)
+}
diff --git a/backend/pkg/scheduler/environment_health_job.go b/backend/pkg/scheduler/environment_health_job.go
index b992227f5..514ac798f 100644
--- a/backend/pkg/scheduler/environment_health_job.go
+++ b/backend/pkg/scheduler/environment_health_job.go
@@ -18,9 +18,8 @@ const (
)
type healthEnvironment struct {
- ID string
- Name string
- Enabled bool
+ ID string
+ Name string
}
type EnvironmentHealthJob struct {
@@ -80,6 +79,7 @@ func (j *EnvironmentHealthJob) Run(ctx context.Context) {
if err := db.WithContext(ctx).
Model(&healthEnvironment{}).
Table("environments").
+ Select("id", "name").
Where("enabled = ?", true).
Find(&environments).Error; err != nil {
slog.ErrorContext(ctx, "failed to list environments for health check", "error", err)
diff --git a/backend/resources/migrations/postgres/041_add_query_performance_indexes.down.sql b/backend/resources/migrations/postgres/041_add_query_performance_indexes.down.sql
new file mode 100644
index 000000000..6573189cc
--- /dev/null
+++ b/backend/resources/migrations/postgres/041_add_query_performance_indexes.down.sql
@@ -0,0 +1,32 @@
+CREATE INDEX IF NOT EXISTS idx_api_keys_user_id ON api_keys(user_id);
+CREATE INDEX IF NOT EXISTS idx_events_environment_id ON events(environment_id);
+CREATE INDEX IF NOT EXISTS idx_image_update_repository ON image_updates(repository);
+CREATE INDEX IF NOT EXISTS idx_image_update_tag ON image_updates(tag);
+CREATE INDEX IF NOT EXISTS idx_volume_backups_volume_name ON volume_backups(volume_name);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_env ON vulnerability_ignores(environment_id);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_vuln ON vulnerability_ignores(vulnerability_id);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_scans_status ON vulnerability_scans(status);
+
+DROP INDEX IF EXISTS idx_vulnerability_ignores_env_vulnerability_id;
+DROP INDEX IF EXISTS idx_events_environment_timestamp;
+DROP INDEX IF EXISTS idx_image_updates_repository_tag;
+DROP INDEX IF EXISTS idx_image_builds_environment_status;
+DROP INDEX IF EXISTS idx_image_builds_environment_created_at;
+DROP INDEX IF EXISTS idx_volume_backups_volume_name_created_at;
+DROP INDEX IF EXISTS idx_compose_templates_lookup_description;
+DROP INDEX IF EXISTS idx_compose_templates_lookup_name;
+DROP INDEX IF EXISTS idx_projects_dir_name_not_null;
+DROP INDEX IF EXISTS idx_projects_path;
+DROP INDEX IF EXISTS idx_gitops_syncs_environment_project_id;
+DROP INDEX IF EXISTS idx_gitops_syncs_environment_repository_id;
+DROP INDEX IF EXISTS idx_gitops_syncs_environment_last_sync_status;
+DROP INDEX IF EXISTS idx_gitops_syncs_auto_sync_true;
+DROP INDEX IF EXISTS idx_gitops_syncs_environment_auto_sync;
+DROP INDEX IF EXISTS idx_git_repositories_auth_type;
+DROP INDEX IF EXISTS idx_git_repositories_enabled_url;
+DROP INDEX IF EXISTS idx_vulnerability_ignores_env_created_at;
+DROP INDEX IF EXISTS idx_vulnerability_scans_status_total_count;
+DROP INDEX IF EXISTS idx_api_keys_user_managed_by_created_at;
+DROP INDEX IF EXISTS idx_api_keys_expires_at_not_null;
+DROP INDEX IF EXISTS idx_environments_enabled_true;
+DROP INDEX IF EXISTS idx_environments_access_token_not_null;
diff --git a/backend/resources/migrations/postgres/041_add_query_performance_indexes.up.sql b/backend/resources/migrations/postgres/041_add_query_performance_indexes.up.sql
new file mode 100644
index 000000000..639cdb800
--- /dev/null
+++ b/backend/resources/migrations/postgres/041_add_query_performance_indexes.up.sql
@@ -0,0 +1,82 @@
+CREATE INDEX IF NOT EXISTS idx_environments_access_token_not_null
+ON environments (access_token)
+WHERE access_token IS NOT NULL;
+
+CREATE INDEX IF NOT EXISTS idx_environments_enabled_true
+ON environments (id, name)
+WHERE enabled = true;
+
+CREATE INDEX IF NOT EXISTS idx_api_keys_expires_at_not_null
+ON api_keys (expires_at)
+WHERE expires_at IS NOT NULL;
+
+CREATE INDEX IF NOT EXISTS idx_api_keys_user_managed_by_created_at
+ON api_keys (user_id, managed_by, created_at, id);
+
+CREATE INDEX IF NOT EXISTS idx_git_repositories_enabled_url
+ON git_repositories (enabled, url);
+
+CREATE INDEX IF NOT EXISTS idx_git_repositories_auth_type
+ON git_repositories (auth_type);
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_environment_auto_sync
+ON gitops_syncs (environment_id, auto_sync);
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_auto_sync_true
+ON gitops_syncs (id, environment_id, sync_interval, last_sync_at)
+WHERE auto_sync = true;
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_environment_last_sync_status
+ON gitops_syncs (environment_id, last_sync_status);
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_environment_repository_id
+ON gitops_syncs (environment_id, repository_id);
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_environment_project_id
+ON gitops_syncs (environment_id, project_id);
+
+CREATE INDEX IF NOT EXISTS idx_projects_path
+ON projects (path);
+
+CREATE INDEX IF NOT EXISTS idx_projects_dir_name_not_null
+ON projects (dir_name)
+WHERE dir_name IS NOT NULL;
+
+CREATE INDEX IF NOT EXISTS idx_compose_templates_lookup_name
+ON compose_templates (is_remote, registry_id, name);
+
+CREATE INDEX IF NOT EXISTS idx_compose_templates_lookup_description
+ON compose_templates (is_remote, registry_id, description);
+
+CREATE INDEX IF NOT EXISTS idx_volume_backups_volume_name_created_at
+ON volume_backups (volume_name, created_at);
+
+CREATE INDEX IF NOT EXISTS idx_image_builds_environment_created_at
+ON image_builds (environment_id, created_at);
+
+CREATE INDEX IF NOT EXISTS idx_image_builds_environment_status
+ON image_builds (environment_id, status);
+
+CREATE INDEX IF NOT EXISTS idx_events_environment_timestamp
+ON events (environment_id, timestamp);
+
+CREATE INDEX IF NOT EXISTS idx_image_updates_repository_tag
+ON image_updates (repository, tag);
+
+CREATE INDEX IF NOT EXISTS idx_vulnerability_scans_status_total_count
+ON vulnerability_scans (status, total_count);
+
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_env_created_at
+ON vulnerability_ignores (environment_id, created_at);
+
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_env_vulnerability_id
+ON vulnerability_ignores (environment_id, vulnerability_id);
+
+DROP INDEX IF EXISTS idx_api_keys_user_id;
+DROP INDEX IF EXISTS idx_events_environment_id;
+DROP INDEX IF EXISTS idx_image_update_repository;
+DROP INDEX IF EXISTS idx_image_update_tag;
+DROP INDEX IF EXISTS idx_volume_backups_volume_name;
+DROP INDEX IF EXISTS idx_vulnerability_ignores_env;
+DROP INDEX IF EXISTS idx_vulnerability_ignores_vuln;
+DROP INDEX IF EXISTS idx_vulnerability_scans_status;
diff --git a/backend/resources/migrations/sqlite/041_add_query_performance_indexes.down.sql b/backend/resources/migrations/sqlite/041_add_query_performance_indexes.down.sql
new file mode 100644
index 000000000..6573189cc
--- /dev/null
+++ b/backend/resources/migrations/sqlite/041_add_query_performance_indexes.down.sql
@@ -0,0 +1,32 @@
+CREATE INDEX IF NOT EXISTS idx_api_keys_user_id ON api_keys(user_id);
+CREATE INDEX IF NOT EXISTS idx_events_environment_id ON events(environment_id);
+CREATE INDEX IF NOT EXISTS idx_image_update_repository ON image_updates(repository);
+CREATE INDEX IF NOT EXISTS idx_image_update_tag ON image_updates(tag);
+CREATE INDEX IF NOT EXISTS idx_volume_backups_volume_name ON volume_backups(volume_name);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_env ON vulnerability_ignores(environment_id);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_vuln ON vulnerability_ignores(vulnerability_id);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_scans_status ON vulnerability_scans(status);
+
+DROP INDEX IF EXISTS idx_vulnerability_ignores_env_vulnerability_id;
+DROP INDEX IF EXISTS idx_events_environment_timestamp;
+DROP INDEX IF EXISTS idx_image_updates_repository_tag;
+DROP INDEX IF EXISTS idx_image_builds_environment_status;
+DROP INDEX IF EXISTS idx_image_builds_environment_created_at;
+DROP INDEX IF EXISTS idx_volume_backups_volume_name_created_at;
+DROP INDEX IF EXISTS idx_compose_templates_lookup_description;
+DROP INDEX IF EXISTS idx_compose_templates_lookup_name;
+DROP INDEX IF EXISTS idx_projects_dir_name_not_null;
+DROP INDEX IF EXISTS idx_projects_path;
+DROP INDEX IF EXISTS idx_gitops_syncs_environment_project_id;
+DROP INDEX IF EXISTS idx_gitops_syncs_environment_repository_id;
+DROP INDEX IF EXISTS idx_gitops_syncs_environment_last_sync_status;
+DROP INDEX IF EXISTS idx_gitops_syncs_auto_sync_true;
+DROP INDEX IF EXISTS idx_gitops_syncs_environment_auto_sync;
+DROP INDEX IF EXISTS idx_git_repositories_auth_type;
+DROP INDEX IF EXISTS idx_git_repositories_enabled_url;
+DROP INDEX IF EXISTS idx_vulnerability_ignores_env_created_at;
+DROP INDEX IF EXISTS idx_vulnerability_scans_status_total_count;
+DROP INDEX IF EXISTS idx_api_keys_user_managed_by_created_at;
+DROP INDEX IF EXISTS idx_api_keys_expires_at_not_null;
+DROP INDEX IF EXISTS idx_environments_enabled_true;
+DROP INDEX IF EXISTS idx_environments_access_token_not_null;
diff --git a/backend/resources/migrations/sqlite/041_add_query_performance_indexes.up.sql b/backend/resources/migrations/sqlite/041_add_query_performance_indexes.up.sql
new file mode 100644
index 000000000..55d9059dd
--- /dev/null
+++ b/backend/resources/migrations/sqlite/041_add_query_performance_indexes.up.sql
@@ -0,0 +1,82 @@
+CREATE INDEX IF NOT EXISTS idx_environments_access_token_not_null
+ON environments(access_token)
+WHERE access_token IS NOT NULL;
+
+CREATE INDEX IF NOT EXISTS idx_environments_enabled_true
+ON environments(id, name)
+WHERE enabled = 1;
+
+CREATE INDEX IF NOT EXISTS idx_api_keys_expires_at_not_null
+ON api_keys(expires_at)
+WHERE expires_at IS NOT NULL;
+
+CREATE INDEX IF NOT EXISTS idx_api_keys_user_managed_by_created_at
+ON api_keys(user_id, managed_by, created_at, id);
+
+CREATE INDEX IF NOT EXISTS idx_git_repositories_enabled_url
+ON git_repositories(enabled, url);
+
+CREATE INDEX IF NOT EXISTS idx_git_repositories_auth_type
+ON git_repositories(auth_type);
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_environment_auto_sync
+ON gitops_syncs(environment_id, auto_sync);
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_auto_sync_true
+ON gitops_syncs(id, environment_id, sync_interval, last_sync_at)
+WHERE auto_sync = 1;
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_environment_last_sync_status
+ON gitops_syncs(environment_id, last_sync_status);
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_environment_repository_id
+ON gitops_syncs(environment_id, repository_id);
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_environment_project_id
+ON gitops_syncs(environment_id, project_id);
+
+CREATE INDEX IF NOT EXISTS idx_projects_path
+ON projects(path);
+
+CREATE INDEX IF NOT EXISTS idx_projects_dir_name_not_null
+ON projects(dir_name)
+WHERE dir_name IS NOT NULL;
+
+CREATE INDEX IF NOT EXISTS idx_compose_templates_lookup_name
+ON compose_templates(is_remote, registry_id, name);
+
+CREATE INDEX IF NOT EXISTS idx_compose_templates_lookup_description
+ON compose_templates(is_remote, registry_id, description);
+
+CREATE INDEX IF NOT EXISTS idx_volume_backups_volume_name_created_at
+ON volume_backups(volume_name, created_at);
+
+CREATE INDEX IF NOT EXISTS idx_image_builds_environment_created_at
+ON image_builds(environment_id, created_at);
+
+CREATE INDEX IF NOT EXISTS idx_image_builds_environment_status
+ON image_builds(environment_id, status);
+
+CREATE INDEX IF NOT EXISTS idx_events_environment_timestamp
+ON events(environment_id, timestamp);
+
+CREATE INDEX IF NOT EXISTS idx_image_updates_repository_tag
+ON image_updates(repository, tag);
+
+CREATE INDEX IF NOT EXISTS idx_vulnerability_scans_status_total_count
+ON vulnerability_scans(status, total_count);
+
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_env_created_at
+ON vulnerability_ignores(environment_id, created_at);
+
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_env_vulnerability_id
+ON vulnerability_ignores(environment_id, vulnerability_id);
+
+DROP INDEX IF EXISTS idx_api_keys_user_id;
+DROP INDEX IF EXISTS idx_events_environment_id;
+DROP INDEX IF EXISTS idx_image_update_repository;
+DROP INDEX IF EXISTS idx_image_update_tag;
+DROP INDEX IF EXISTS idx_volume_backups_volume_name;
+DROP INDEX IF EXISTS idx_vulnerability_ignores_env;
+DROP INDEX IF EXISTS idx_vulnerability_ignores_vuln;
+DROP INDEX IF EXISTS idx_vulnerability_scans_status;
diff --git a/frontend/src/lib/components/dialogs/docker-info-dialog.svelte b/frontend/src/lib/components/dialogs/docker-info-dialog.svelte
index 68a3fe226..467dfde47 100644
--- a/frontend/src/lib/components/dialogs/docker-info-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/docker-info-dialog.svelte
@@ -3,6 +3,7 @@
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import { Badge } from '$lib/components/ui/badge';
import { CopyButton } from '$lib/components/ui/copy-button';
+ import { Spinner } from '$lib/components/ui/spinner';
import type { DockerInfo } from '$lib/types/docker-info.type';
import { m } from '$lib/paraglide/messages';
import bytes from '$lib/utils/bytes';
@@ -10,12 +11,11 @@
interface Props {
open: boolean;
dockerInfo: DockerInfo | null;
+ dockerInfoPromise?: Promise<DockerInfo> | null;
+ errorMessage?: string | null;
}
- let { open = $bindable(), dockerInfo }: Props = $props();
-
- const shortGitCommit = $derived(dockerInfo?.gitCommit?.slice(0, 8) ?? '-');
- const formattedMemory = $derived(dockerInfo?.MemTotal ? bytes.format(dockerInfo.MemTotal) : '-');
+ let { open = $bindable(), dockerInfo, dockerInfoPromise = null, errorMessage = null }: Props = $props();
function handleClose() {
open = false;
@@ -37,26 +37,29 @@
title={m.docker_engine_title({ engine: dockerInfo?.Name ?? 'Docker Engine' })}
description={m.docker_info_dialog_description()}
contentClass="sm:max-w-[1100px]"
+ showCloseButton={false}
>
{#snippet children()}
- <div class="space-y-6 pt-4">
- <div class="grid gap-6">
- {@render statsSection()}
- {@render resourcesSection()}
+ {#if dockerInfo}
+ {@render dialogBody(dockerInfo)}
+ {:else if dockerInfoPromise}
+ {#await dockerInfoPromise then resolvedDockerInfo}
+ {@render dialogBody(resolvedDockerInfo)}
+ {:catch}
+ <div class="flex min-h-56 flex-col items-center justify-center gap-3 pt-4">
+ <p class="text-sm font-medium">{errorMessage ?? m.common_failed()}</p>
+ </div>
+ {/await}
+ {:else if errorMessage}
+ <div class="flex min-h-56 flex-col items-center justify-center gap-3 pt-4">
+ <p class="text-sm font-medium">{errorMessage}</p>
</div>
-
- <div class="grid gap-6 lg:grid-cols-2 xl:grid-cols-3">
- {@render systemSection()}
- {@render versionSection()}
- {@render configurationSection()}
+ {:else}
+ <div class="flex min-h-56 flex-col items-center justify-center gap-3 pt-4">
+ <Spinner class="size-5" />
+ <p class="text-muted-foreground text-sm">{m.common_loading()}</p>
</div>
-
- <div class="grid gap-6 lg:grid-cols-2 xl:grid-cols-3">
- {@render networkSection()}
- {@render securitySection()}
- {@render pluginsSection()}
- </div>
- </div>
+ {/if}
{/snippet}
{#snippet footer()}
@@ -64,63 +67,84 @@
{/snippet}
</ResponsiveDialog>
-{#snippet statsSection()}
+{#snippet dialogBody(info: DockerInfo)}
+ <div class="space-y-6 pt-4">
+ <div class="grid gap-6">
+ {@render statsSection(info)}
+ {@render resourcesSection(info)}
+ </div>
+
+ <div class="grid gap-6 lg:grid-cols-2 xl:grid-cols-3">
+ {@render systemSection(info)}
+ {@render versionSection(info)}
+ {@render configurationSection(info)}
+ </div>
+
+ <div class="grid gap-6 lg:grid-cols-2 xl:grid-cols-3">
+ {@render networkSection(info)}
+ {@render securitySection(info)}
+ {@render pluginsSection(info)}
+ </div>
+ </div>
+{/snippet}
+
+{#snippet statsSection(info: DockerInfo)}
<div>
<h3 class="text-muted-foreground mb-2 text-xs font-semibold tracking-wider uppercase">
{m.docker_info_stats_section()}
</h3>
<div class="grid gap-3 sm:grid-cols-4">
- {@render statCard(m.common_running(), dockerInfo?.ContainersRunning ?? 0, 'emerald')}
- {@render statCard(m.docker_info_paused_label(), dockerInfo?.ContainersPaused ?? 0, 'amber')}
- {@render statCard(m.common_stopped(), dockerInfo?.ContainersStopped ?? 0, 'red')}
- {@render statCard(m.docker_info_images_label(), dockerInfo?.Images ?? 0, 'blue')}
+ {@render statCard(m.common_running(), info.ContainersRunning ?? 0, 'emerald')}
+ {@render statCard(m.docker_info_paused_label(), info.ContainersPaused ?? 0, 'amber')}
+ {@render statCard(m.common_stopped(), info.ContainersStopped ?? 0, 'red')}
+ {@render statCard(m.docker_info_images_label(), info.Images ?? 0, 'blue')}
</div>
</div>
{/snippet}
-{#snippet systemSection()}
+{#snippet systemSection(info: DockerInfo)}
<div class="space-y-2">
<h3 class="text-muted-foreground text-xs font-semibold tracking-wider uppercase">
{m.docker_info_system_section()}
</h3>
<div class="space-y-1.5 rounded-lg border p-3">
- {@render infoRow(m.common_name(), dockerInfo?.Name)}
- {@render infoRow(m.common_id(), dockerInfo?.ID, true)}
- {@render infoRow(m.docker_info_os_label(), dockerInfo?.OperatingSystem)}
- {@render infoRow(m.docker_info_os_type_label(), dockerInfo?.OSType)}
- {@render infoRow(m.common_architecture(), dockerInfo?.Architecture)}
- {@render infoRow(m.docker_info_kernel_version_label(), dockerInfo?.KernelVersion)}
- {@render infoRow(m.docker_info_system_time(), formatTime(dockerInfo?.SystemTime), false)}
- {@render infoRow(m.docker_info_root_dir(), dockerInfo?.DockerRootDir, true)}
+ {@render infoRow(m.common_name(), info.Name)}
+ {@render infoRow(m.common_id(), info.ID, true)}
+ {@render infoRow(m.docker_info_os_label(), info.OperatingSystem)}
+ {@render infoRow(m.docker_info_os_type_label(), info.OSType)}
+ {@render infoRow(m.common_architecture(), info.Architecture)}
+ {@render infoRow(m.docker_info_kernel_version_label(), info.KernelVersion)}
+ {@render infoRow(m.docker_info_system_time(), formatTime(info.SystemTime), false)}
+ {@render infoRow(m.docker_info_root_dir(), info.DockerRootDir, true)}
</div>
</div>
{/snippet}
-{#snippet versionSection()}
+{#snippet versionSection(info: DockerInfo)}
<div class="space-y-2">
<h3 class="text-muted-foreground text-xs font-semibold tracking-wider uppercase">
{m.docker_info_version_section()}
</h3>
<div class="space-y-1.5 rounded-lg border p-3">
- {@render infoRow(m.docker_info_server_version_label(), dockerInfo?.ServerVersion)}
- {@render infoRow(m.docker_info_api_version_label(), dockerInfo?.apiVersion)}
- {@render infoRow(m.docker_info_go_version_label(), dockerInfo?.goVersion)}
+ {@render infoRow(m.docker_info_server_version_label(), info.ServerVersion)}
+ {@render infoRow(m.docker_info_api_version_label(), info.apiVersion)}
+ {@render infoRow(m.docker_info_go_version_label(), info.goVersion)}
<div class="flex items-center justify-between gap-4">
<span class="text-muted-foreground text-xs">{m.docker_info_git_commit_label()}</span>
<div class="flex items-center gap-2">
- <code class="bg-muted rounded px-1.5 py-0.5 text-xs">{shortGitCommit}</code>
- {#if dockerInfo?.gitCommit}
- <CopyButton text={dockerInfo.gitCommit} size="icon" class="size-6" title="Copy full commit hash" />
+ <code class="bg-muted rounded px-1.5 py-0.5 text-xs">{info.gitCommit?.slice(0, 8) ?? '-'}</code>
+ {#if info.gitCommit}
+ <CopyButton text={info.gitCommit} size="icon" class="size-6" title="Copy full commit hash" />
{/if}
</div>
</div>
- {@render infoRow(m.docker_info_build_time_label(), formatTime(dockerInfo?.buildTime), false)}
- {@render infoRow(m.docker_info_experimental(), dockerInfo?.ExperimentalBuild ? m.common_yes() : m.common_no(), false)}
+ {@render infoRow(m.docker_info_build_time_label(), formatTime(info.buildTime), false)}
+ {@render infoRow(m.docker_info_experimental(), info.ExperimentalBuild ? m.common_yes() : m.common_no(), false)}
</div>
</div>
{/snippet}
-{#snippet resourcesSection()}
+{#snippet resourcesSection(info: DockerInfo)}
<div>
<h3 class="text-muted-foreground mb-2 text-xs font-semibold tracking-wider uppercase">
{m.docker_info_resources_section()}
@@ -129,63 +153,59 @@
<div class="rounded-lg border p-3">
<div class="text-muted-foreground mb-1 text-[10px] tracking-tight uppercase">{m.common_cpus()}</div>
<div class="flex items-center gap-2">
- <Badge variant="outline" class="text-sm font-bold">{dockerInfo?.NCPU ?? 0}</Badge>
+ <Badge variant="outline" class="text-sm font-bold">{info.NCPU ?? 0}</Badge>
<span class="text-muted-foreground text-[10px]">cores</span>
</div>
</div>
<div class="rounded-lg border p-3">
<div class="text-muted-foreground mb-1 text-[10px] tracking-tight uppercase">{m.docker_info_memory_label()}</div>
- <Badge variant="outline" class="text-sm font-bold">{formattedMemory}</Badge>
+ <Badge variant="outline" class="text-sm font-bold">{info.MemTotal ? bytes.format(info.MemTotal) : '-'}</Badge>
</div>
<div class="rounded-lg border p-3">
<div class="text-muted-foreground mb-1 text-[10px] tracking-tight uppercase">{m.docker_info_goroutines()}</div>
- <Badge variant="outline" class="text-sm font-bold">{dockerInfo?.NGoroutines ?? 0}</Badge>
+ <Badge variant="outline" class="text-sm font-bold">{info.NGoroutines ?? 0}</Badge>
</div>
<div class="rounded-lg border p-3">
<div class="text-muted-foreground mb-1 text-[10px] tracking-tight uppercase">{m.docker_info_file_descriptors()}</div>
- <Badge variant="outline" class="text-sm font-bold">{dockerInfo?.NFd ?? 0}</Badge>
+ <Badge variant="outline" class="text-sm font-bold">{info.NFd ?? 0}</Badge>
</div>
</div>
</div>
{/snippet}
-{#snippet configurationSection()}
+{#snippet configurationSection(info: DockerInfo)}
<div class="space-y-2">
<h3 class="text-muted-foreground text-xs font-semibold tracking-wider uppercase">
{m.common_configuration()}
</h3>
<div class="space-y-1.5 rounded-lg border p-3">
- {@render infoRow(m.docker_info_storage_driver_label(), dockerInfo?.Driver)}
- {@render infoRow(m.docker_info_logging_driver_label(), dockerInfo?.LoggingDriver)}
- {@render infoRow(m.docker_info_cgroup_driver_label(), dockerInfo?.CgroupDriver)}
- {@render infoRow(m.docker_info_cgroup_version_label(), dockerInfo?.CgroupVersion)}
- {@render infoRow(m.docker_info_isolation(), dockerInfo?.Isolation)}
- {@render infoRow(m.docker_info_init_binary(), dockerInfo?.InitBinary)}
- {@render infoRow(m.docker_info_default_runtime(), dockerInfo?.DefaultRuntime)}
+ {@render infoRow(m.docker_info_storage_driver_label(), info.Driver)}
+ {@render infoRow(m.docker_info_logging_driver_label(), info.LoggingDriver)}
+ {@render infoRow(m.docker_info_cgroup_driver_label(), info.CgroupDriver)}
+ {@render infoRow(m.docker_info_cgroup_version_label(), info.CgroupVersion)}
+ {@render infoRow(m.docker_info_isolation(), info.Isolation)}
+ {@render infoRow(m.docker_info_init_binary(), info.InitBinary)}
+ {@render infoRow(m.docker_info_default_runtime(), info.DefaultRuntime)}
</div>
</div>
{/snippet}
-{#snippet networkSection()}
+{#snippet networkSection(info: DockerInfo)}
<div class="space-y-2">
<h3 class="text-muted-foreground text-xs font-semibold tracking-wider uppercase">
{m.resource_networks_cap()} & {m.docker_info_proxy_label()}
</h3>
<div class="space-y-1.5 rounded-lg border p-3">
- {@render infoRow(
- m.docker_info_ipv4_forwarding(),
- dockerInfo?.IPv4Forwarding ? m.common_enabled() : m.common_disabled(),
- false
- )}
- {@render infoRow(m.docker_info_http_proxy(), dockerInfo?.HttpProxy)}
- {@render infoRow(m.docker_info_https_proxy(), dockerInfo?.HttpsProxy)}
- {@render infoRow(m.docker_info_no_proxy(), dockerInfo?.NoProxy)}
- {@render infoRow(m.docker_info_bridge_ip(), dockerInfo?.DefaultAddressPools?.[0]?.Base)}
+ {@render infoRow(m.docker_info_ipv4_forwarding(), info.IPv4Forwarding ? m.common_enabled() : m.common_disabled(), false)}
+ {@render infoRow(m.docker_info_http_proxy(), info.HttpProxy)}
+ {@render infoRow(m.docker_info_https_proxy(), info.HttpsProxy)}
+ {@render infoRow(m.docker_info_no_proxy(), info.NoProxy)}
+ {@render infoRow(m.docker_info_bridge_ip(), info.DefaultAddressPools?.[0]?.Base)}
</div>
</div>
{/snippet}
-{#snippet pluginsSection()}
+{#snippet pluginsSection(info: DockerInfo)}
<div class="space-y-2">
<h3 class="text-muted-foreground text-xs font-semibold tracking-wider uppercase">
{m.docker_info_plugins_section()}
@@ -194,7 +214,7 @@
<div>
<div class="text-muted-foreground mb-1 text-[10px] tracking-tight uppercase">{m.resource_volumes_cap()}</div>
<div class="flex flex-wrap gap-1">
- {#each dockerInfo?.Plugins?.Volume ?? [] as plugin}
+ {#each info.Plugins?.Volume ?? [] as plugin}
<Badge variant="outline" class="px-1.5 py-0 text-[10px]">{plugin}</Badge>
{:else}
<span class="text-muted-foreground text-xs">-</span>
@@ -204,7 +224,7 @@
<div>
<div class="text-muted-foreground mb-1 text-[10px] tracking-tight uppercase">{m.resource_networks_cap()}</div>
<div class="flex flex-wrap gap-1">
- {#each dockerInfo?.Plugins?.Network ?? [] as plugin}
+ {#each info.Plugins?.Network ?? [] as plugin}
<Badge variant="outline" class="px-1.5 py-0 text-[10px]">{plugin}</Badge>
{:else}
<span class="text-muted-foreground text-xs">-</span>
@@ -214,7 +234,7 @@
<div>
<div class="text-muted-foreground mb-1 text-[10px] tracking-tight uppercase">{m.docker_info_logs_plugin()}</div>
<div class="flex flex-wrap gap-1">
- {#each dockerInfo?.Plugins?.Log ?? [] as plugin}
+ {#each info.Plugins?.Log ?? [] as plugin}
<Badge variant="outline" class="px-1.5 py-0 text-[10px]">{plugin}</Badge>
{:else}
<span class="text-muted-foreground text-xs">-</span>
@@ -225,7 +245,7 @@
</div>
{/snippet}
-{#snippet securitySection()}
+{#snippet securitySection(info: DockerInfo)}
<div class="space-y-2">
<h3 class="text-muted-foreground text-xs font-semibold tracking-wider uppercase">
{m.security_title()} & {m.docker_info_runtimes()}
@@ -234,7 +254,7 @@
<div>
<div class="text-muted-foreground mb-1 text-[10px] tracking-tight uppercase">{m.docker_info_security_options()}</div>
<div class="flex flex-wrap gap-1">
- {#each dockerInfo?.SecurityOptions ?? [] as opt}
+ {#each info.SecurityOptions ?? [] as opt}
<Badge variant="outline" class="px-1.5 py-0 text-[10px]">{opt}</Badge>
{:else}
<span class="text-muted-foreground text-xs">-</span>
@@ -244,7 +264,7 @@
<div>
<div class="text-muted-foreground mb-1 text-[10px] tracking-tight uppercase">{m.docker_info_runtimes()}</div>
<div class="flex flex-wrap gap-1">
- {#each Object.keys(dockerInfo?.Runtimes ?? {}) as runtime}
+ {#each Object.keys(info.Runtimes ?? {}) as runtime}
<Badge variant="outline" class="px-1.5 py-0 text-[10px]">{runtime}</Badge>
{:else}
<span class="text-muted-foreground text-xs">-</span>
diff --git a/frontend/src/lib/components/quick-actions.svelte b/frontend/src/lib/components/quick-actions.svelte
index 955c17e62..db320c0be 100644
--- a/frontend/src/lib/components/quick-actions.svelte
+++ b/frontend/src/lib/components/quick-actions.svelte
@@ -2,7 +2,6 @@
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import { ActionButtonGroup, type ActionButton } from '$lib/components/action-button-group/index.js';
import { m } from '$lib/paraglide/messages';
- import type { DockerInfo } from '$lib/types/docker-info.type';
import { StartIcon, StopIcon, TrashIcon } from '$lib/icons';
import { cn } from '$lib/utils';
import type { User } from '$lib/types/user.type';
@@ -15,10 +14,8 @@
let {
user = null,
- dockerInfo,
stoppedContainers,
runningContainers,
- loadingDockerInfo = false,
isLoading,
onStartAll,
onStopAll,
@@ -29,10 +26,8 @@
class: className
}: {
user?: User | null;
- dockerInfo: DockerInfo | null;
stoppedContainers: number;
runningContainers: number;
- loadingDockerInfo?: boolean;
isLoading: IsLoadingFlags;
onStartAll: () => void;
onStopAll: () => void;
@@ -55,7 +50,7 @@
label: m.quick_actions_start_all(),
onclick: onStartAll,
loading: isLoading.starting,
- disabled: !dockerInfo || stoppedContainers === 0 || isAnyActionLoading,
+ disabled: stoppedContainers === 0 || isAnyActionLoading,
badge: stoppedContainers
},
{
@@ -64,7 +59,7 @@
label: m.quick_actions_stop_all(),
onclick: onStopAll,
loading: isLoading.stopping,
- disabled: !dockerInfo || (dockerInfo?.ContainersRunning ?? 0) === 0 || isAnyActionLoading,
+ disabled: runningContainers === 0 || isAnyActionLoading,
badge: runningContainers
},
{
@@ -73,7 +68,7 @@
label: m.quick_actions_prune_system(),
onclick: onOpenPruneDialog,
loading: isLoading.pruning,
- disabled: !dockerInfo || isAnyActionLoading
+ disabled: isAnyActionLoading
},
{
id: 'refresh',
@@ -89,118 +84,95 @@
<section class={cn(compact ? 'flex min-w-0 flex-1 items-center justify-end' : '', className)}>
{#if compact}
- {#if loadingDockerInfo}
- <div class="hidden flex-wrap items-center gap-2 sm:flex">
- {#each Array(4) as _}
- <div class="bg-card/60 h-9 w-28 animate-pulse rounded-lg backdrop-blur-sm"></div>
- {/each}
- </div>
- <div class="bg-card/60 size-9 animate-pulse rounded-lg backdrop-blur-sm sm:hidden"></div>
- {:else}
- <ActionButtonGroup buttons={actionButtons} />
- {/if}
+ <ActionButtonGroup buttons={actionButtons} />
{:else if currentUserIsAdmin}
<h2 class="mb-3 text-lg font-semibold tracking-tight">{m.quick_actions_title()}</h2>
- {#if loadingDockerInfo}
- <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
- {#each Array(3) as _}
- <div class="bg-card/90 flex items-center rounded-lg border p-3 backdrop-blur-sm">
- <div class="bg-muted mr-3 size-6 animate-pulse rounded-full"></div>
- <div class="flex-1">
- <div class="bg-muted mb-1 h-3 w-16 animate-pulse rounded"></div>
- <div class="bg-muted h-2 w-12 animate-pulse rounded"></div>
+ <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
+ <div class="group hover-lift rounded-2xl bg-gradient-to-br from-emerald-500/20 to-emerald-500/0 p-[1px]">
+ <ArcaneButton
+ action="start_all"
+ size="card"
+ tone="outline-success"
+ class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
+ onclick={onStartAll}
+ loading={isLoading.starting}
+ disabled={stoppedContainers === 0 || isAnyActionLoading}
+ icon={null}
+ showLabel={false}
+ >
+ <div class="relative">
+ <div class="flex size-10 items-center justify-center rounded-lg bg-emerald-500/10 ring-1 ring-emerald-500/30">
+ <StartIcon class="size-5 text-emerald-400" />
</div>
+ <div
+ class="pointer-events-none absolute -inset-1 rounded-lg bg-emerald-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
+ ></div>
</div>
- {/each}
- </div>
- {:else}
- <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
- <div class="group hover-lift rounded-2xl bg-gradient-to-br from-emerald-500/20 to-emerald-500/0 p-[1px]">
- <ArcaneButton
- action="start_all"
- size="card"
- tone="outline-success"
- class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
- onclick={onStartAll}
- loading={isLoading.starting}
- disabled={!dockerInfo || stoppedContainers === 0 || isAnyActionLoading}
- icon={null}
- showLabel={false}
- >
- <div class="relative">
- <div class="flex size-10 items-center justify-center rounded-lg bg-emerald-500/10 ring-1 ring-emerald-500/30">
- <StartIcon class="size-5 text-emerald-400" />
- </div>
- <div
- class="pointer-events-none absolute -inset-1 rounded-lg bg-emerald-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
- ></div>
- </div>
- <div class="flex-1 text-left">
- <div class="text-sm font-medium">{m.quick_actions_start_all()}</div>
- <div class="text-muted-foreground text-xs">
- <span class="rounded-full border px-1.5 py-0.5">{m.quick_actions_containers({ count: stoppedContainers })}</span>
- </div>
+ <div class="flex-1 text-left">
+ <div class="text-sm font-medium">{m.quick_actions_start_all()}</div>
+ <div class="text-muted-foreground text-xs">
+ <span class="rounded-full border px-1.5 py-0.5">{m.quick_actions_containers({ count: stoppedContainers })}</span>
</div>
- </ArcaneButton>
- </div>
+ </div>
+ </ArcaneButton>
+ </div>
- <div class="group hover-lift rounded-2xl bg-gradient-to-br from-sky-500/20 to-sky-500/0 p-[1px]">
- <ArcaneButton
- action="stop_all"
- size="card"
- tone="outline-info"
- class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
- onclick={onStopAll}
- loading={isLoading.stopping}
- disabled={!dockerInfo || (dockerInfo?.ContainersRunning ?? 0) === 0 || isAnyActionLoading}
- icon={null}
- showLabel={false}
- >
- <div class="relative">
- <div class="flex size-10 items-center justify-center rounded-lg bg-sky-500/10 ring-1 ring-sky-500/30">
- <StopIcon class="size-5 text-sky-400" />
- </div>
- <div
- class="pointer-events-none absolute -inset-1 rounded-lg bg-sky-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
- ></div>
+ <div class="group hover-lift rounded-2xl bg-gradient-to-br from-sky-500/20 to-sky-500/0 p-[1px]">
+ <ArcaneButton
+ action="stop_all"
+ size="card"
+ tone="outline-info"
+ class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
+ onclick={onStopAll}
+ loading={isLoading.stopping}
+ disabled={runningContainers === 0 || isAnyActionLoading}
+ icon={null}
+ showLabel={false}
+ >
+ <div class="relative">
+ <div class="flex size-10 items-center justify-center rounded-lg bg-sky-500/10 ring-1 ring-sky-500/30">
+ <StopIcon class="size-5 text-sky-400" />
</div>
- <div class="flex-1 text-left">
- <div class="text-sm font-medium">{m.quick_actions_stop_all()}</div>
- <div class="text-muted-foreground text-xs">
- <span class="rounded-full border px-1.5 py-0.5">{m.quick_actions_containers({ count: runningContainers })}</span>
- </div>
+ <div
+ class="pointer-events-none absolute -inset-1 rounded-lg bg-sky-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
+ ></div>
+ </div>
+ <div class="flex-1 text-left">
+ <div class="text-sm font-medium">{m.quick_actions_stop_all()}</div>
+ <div class="text-muted-foreground text-xs">
+ <span class="rounded-full border px-1.5 py-0.5">{m.quick_actions_containers({ count: runningContainers })}</span>
</div>
- </ArcaneButton>
- </div>
+ </div>
+ </ArcaneButton>
+ </div>
- <div class="group hover-lift rounded-2xl bg-gradient-to-br from-red-500/20 to-red-500/0 p-[1px]">
- <ArcaneButton
- action="prune"
- size="card"
- tone="outline-destructive"
- class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
- onclick={onOpenPruneDialog}
- loading={isLoading.pruning}
- disabled={!dockerInfo || isAnyActionLoading}
- icon={null}
- showLabel={false}
- >
- <div class="relative">
- <div class="flex size-10 items-center justify-center rounded-lg bg-red-500/10 ring-1 ring-red-500/30">
- <TrashIcon class="size-5 text-red-400" />
- </div>
- <div
- class="pointer-events-none absolute -inset-1 rounded-lg bg-red-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
- ></div>
- </div>
- <div class="flex-1 text-left">
- <div class="text-sm font-medium">{m.quick_actions_prune_system()}</div>
- <div class="text-muted-foreground text-xs">{m.quick_actions_prune_description()}</div>
+ <div class="group hover-lift rounded-2xl bg-gradient-to-br from-red-500/20 to-red-500/0 p-[1px]">
+ <ArcaneButton
+ action="prune"
+ size="card"
+ tone="outline-destructive"
+ class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
+ onclick={onOpenPruneDialog}
+ loading={isLoading.pruning}
+ disabled={isAnyActionLoading}
+ icon={null}
+ showLabel={false}
+ >
+ <div class="relative">
+ <div class="flex size-10 items-center justify-center rounded-lg bg-red-500/10 ring-1 ring-red-500/30">
+ <TrashIcon class="size-5 text-red-400" />
</div>
- </ArcaneButton>
- </div>
+ <div
+ class="pointer-events-none absolute -inset-1 rounded-lg bg-red-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
+ ></div>
+ </div>
+ <div class="flex-1 text-left">
+ <div class="text-sm font-medium">{m.quick_actions_prune_system()}</div>
+ <div class="text-muted-foreground text-xs">{m.quick_actions_prune_description()}</div>
+ </div>
+ </ArcaneButton>
</div>
- {/if}
+ </div>
{/if}
</section>
diff --git a/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.svelte b/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.svelte
index 498fcb21f..21ff7310f 100644
--- a/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.svelte
+++ b/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.svelte
@@ -16,6 +16,7 @@
footer,
class: className,
contentClass,
+ showCloseButton = true,
variant = 'dialog'
}: ResponsiveDialogProps = $props();
@@ -78,6 +79,7 @@
'max-h-[calc(100vh-2rem)] grid-rows-[auto_minmax(0,1fr)_auto]! overflow-hidden p-0!',
contentClass ?? 'sm:max-w-[425px]'
)}
+ {showCloseButton}
>
{#if title || description}
<Dialog.Header class="shrink-0 px-6 pt-6">
diff --git a/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.type.ts b/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.type.ts
index 336c32c02..7e3d8819d 100644
--- a/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.type.ts
+++ b/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.type.ts
@@ -52,6 +52,12 @@ export interface ResponsiveDialogProps {
*/
contentClass?: string;
+ /**
+ * Whether to show the default desktop dialog close button
+ * @default true
+ */
+ showCloseButton?: boolean;
+
/**
* The variant of the dialog on desktop
* @default 'dialog'
diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.ts
index 5e3fd1194..7c4a96703 100644
--- a/frontend/src/lib/query/query-keys.ts
+++ b/frontend/src/lib/query/query-keys.ts
@@ -75,6 +75,8 @@ export const queryKeys = {
dockerInfo: (environmentId: string) => ['system', 'docker-info', environmentId] as const
},
dashboard: {
+ 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
},
diff --git a/frontend/src/lib/services/dashboard-service.ts b/frontend/src/lib/services/dashboard-service.ts
index 84a353e89..3cb610e68 100644
--- a/frontend/src/lib/services/dashboard-service.ts
+++ b/frontend/src/lib/services/dashboard-service.ts
@@ -1,12 +1,22 @@
import BaseAPIService from './api-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
-import type { DashboardActionItems } from '$lib/types/dashboard.type';
+import type { DashboardActionItems, DashboardSnapshot } from '$lib/types/dashboard.type';
interface GetDashboardActionItemsOptions {
debugAllGood?: boolean;
}
export class DashboardService extends BaseAPIService {
+ async getDashboard(options?: GetDashboardActionItemsOptions): Promise<DashboardSnapshot> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ return this.getDashboardForEnvironment(envId, options);
+ }
+
+ async getDashboardForEnvironment(environmentId: string, options?: GetDashboardActionItemsOptions): Promise<DashboardSnapshot> {
+ const params = options?.debugAllGood ? { debugAllGood: 'true' } : undefined;
+ return this.handleResponse(this.api.get(`/environments/${environmentId}/dashboard`, { params }));
+ }
+
async getActionItems(): Promise<DashboardActionItems> {
const envId = await environmentStore.getCurrentEnvironmentId();
return this.getActionItemsForEnvironment(envId);
diff --git a/frontend/src/lib/types/dashboard.type.ts b/frontend/src/lib/types/dashboard.type.ts
index 166788c97..c15ca7b7c 100644
--- a/frontend/src/lib/types/dashboard.type.ts
+++ b/frontend/src/lib/types/dashboard.type.ts
@@ -1,3 +1,7 @@
+import type { ContainerStatusCounts, ContainerSummaryDto } from './container.type';
+import type { ImageSummaryDto, ImageUsageCounts } from './image.type';
+import type { Paginated } from './pagination.type';
+
export type DashboardActionItemKind = 'stopped_containers' | 'image_updates' | 'actionable_vulnerabilities' | 'expiring_keys';
export type DashboardActionItemSeverity = 'warning' | 'critical';
@@ -11,3 +15,15 @@ export interface DashboardActionItem {
export interface DashboardActionItems {
items: DashboardActionItem[];
}
+
+export interface DashboardSnapshotSettings {
+ dockerPruneMode: 'all' | 'dangling';
+}
+
+export interface DashboardSnapshot {
+ containers: Paginated<ContainerSummaryDto, ContainerStatusCounts>;
+ images: Paginated<ImageSummaryDto>;
+ imageUsageCounts: ImageUsageCounts;
+ actionItems: DashboardActionItems;
+ settings: DashboardSnapshotSettings;
+}
diff --git a/frontend/src/routes/(app)/dashboard/+page.svelte b/frontend/src/routes/(app)/dashboard/+page.svelte
index fffc692d6..665f4a0f7 100644
--- a/frontend/src/routes/(app)/dashboard/+page.svelte
+++ b/frontend/src/routes/(app)/dashboard/+page.svelte
@@ -19,10 +19,12 @@
import DashboardMetricTile from './dash-metric-tile.svelte';
import DashboardContainerTable from './dash-container-table.svelte';
import DashboardImageTable from './dash-image-table.svelte';
+ import type { PageData } from './$types';
import { m } from '$lib/paraglide/messages';
import { 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 {
CpuIcon,
MemoryStickIcon,
@@ -38,32 +40,24 @@
CheckIcon
} from '$lib/icons';
- let { data } = $props();
- let containers = $derived(data.containers);
- let images = $derived(data.images);
- let dockerInfo = $derived(data.dockerInfo);
- let containerStatusCounts = $derived(data.containerStatusCounts);
- let settings = $derived(data.settings);
- let imageUsageCounts = $derived(
- (
- data as {
- imageUsageCounts?: { imagesInuse?: number; imagesUnused?: number } | null;
- }
- ).imageUsageCounts
- );
- let dashboardActionItems = $derived(
- (
- data as {
- dashboardActionItems?: { items?: Array<{ kind: string; count: number }> } | null;
- }
- ).dashboardActionItems
+ let { data }: { data: PageData } = $props();
+ let containers = $derived(data.dashboard.containers);
+ let images = $derived(data.dashboard.images);
+ let containerStatusCounts = $derived(
+ data.dashboard.containers.counts ?? { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 }
);
- let debugAllGood = $derived((data as { debugAllGood?: boolean }).debugAllGood ?? false);
+ let settings = $derived(data.dashboard.settings);
+ let imageUsageCounts = $derived(data.dashboard.imageUsageCounts);
+ let dashboardActionItems = $derived(data.dashboard.actionItems);
+ let debugAllGood = $derived(data.debugAllGood ?? false);
let currentUser = $state<User | null>(null);
let systemStats = $state<SystemStats | null>(null);
let isPruneDialogOpen = $state(false);
let dockerInfoDialogOpen = $state(false);
+ 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';
@@ -72,10 +66,7 @@
stopping: false,
refreshing: false,
pruning: false,
- loadingStats: true,
- loadingDockerInfo: false,
- loadingContainers: false,
- loadingImages: false
+ loadingStats: true
});
let statsWSClient: ReconnectingWebSocket<SystemStats> | null = null;
@@ -117,7 +108,6 @@
const imagesInUseCount = $derived(imageUsageCounts?.imagesInuse ?? 0);
const imagesUnusedCount = $derived(imageUsageCounts?.imagesUnused ?? 0);
- const containerHealthPercent = $derived(totalContainers > 0 ? Math.round((runningContainers / totalContainers) * 100) : 100);
const diskUsagePercent = $derived.by(() => {
if (!currentStats?.diskTotal || currentStats.diskTotal <= 0 || currentStats.diskUsage === undefined) return null;
return (currentStats.diskUsage / currentStats.diskTotal) * 100;
@@ -144,14 +134,6 @@
return 'gray';
});
const hasDiskPressureAlert = $derived(!debugAllGood && (diskRisk === 'critical' || diskRisk === 'high'));
- const showNeedsAttention = $derived(
- !debugAllGood &&
- (stoppedContainersAttentionCount > 0 ||
- imageUpdatesAttentionCount > 0 ||
- actionableVulnerabilitiesAttentionCount > 0 ||
- expiringApiKeysAttentionCount > 0 ||
- hasDiskPressureAlert)
- );
const attentionItemsCount = $derived(
debugAllGood
? 0
@@ -165,7 +147,6 @@
const imageUpdatesBadgeText = $derived(`${imageUpdatesAttentionCount} ${m.common_pending()}`);
const actionableVulnerabilitiesBadgeText = $derived(`${m.vuln_severity_critical()} + ${m.vuln_severity_high()}`);
const expiringApiKeysBadgeText = $derived(`${expiringApiKeysAttentionCount} ${m.common_pending()}`);
- const containerHealthLabel = $derived(`${runningContainers}/${totalContainers} ${m.common_running()}`);
const imageUsageLabel = $derived(`${imagesInUseCount} ${m.common_in_use()} · ${imagesUnusedCount} ${m.common_unused()}`);
const diskPressureValue = $derived(diskUsagePercent === null ? '--' : `${diskUsagePercent.toFixed(1)}%`);
const diskPressureDescription = $derived.by(() => {
@@ -209,7 +190,10 @@
const count = currentStats?.gpuCount ?? 0;
return count > 0 ? `${count} ${count === 1 ? m.dashboard_meter_gpu_device() : m.dashboard_meter_gpu_devices()}` : '--';
});
- const dashboardUser = $derived.by(() => currentUser ?? (data as { user?: User | null }).user ?? null);
+ 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 dashboardUser = $derived.by(() => currentUser ?? data.user ?? null);
const greetingBase = $derived.by(() => {
const hour = new Date().getHours();
if (hour >= 5 && hour < 12) return m.dashboard_greeting_morning();
@@ -275,6 +259,9 @@
function resetStats() {
systemStats = null;
hasInitialStatsLoaded = false;
+ dockerInfo = null;
+ dockerInfoPromise = null;
+ dockerInfoError = null;
}
function closeStatsWS() {
@@ -305,8 +292,32 @@
statsWSClient.connect();
}
+ async function loadDockerInfo(): Promise<DockerInfo> {
+ try {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ const info = await systemService.getDockerInfoForEnvironment(envId);
+ dockerInfo = info;
+ return info;
+ } catch (error) {
+ console.error('Failed to load docker info:', error);
+ dockerInfoError = m.common_failed();
+ toast.error(dockerInfoError);
+ throw error;
+ } finally {
+ dockerInfoPromise = null;
+ }
+ }
+
+ function openDockerInfoDialog() {
+ dockerInfoDialogOpen = true;
+ if (dockerInfo || dockerInfoPromise) return;
+
+ dockerInfoError = null;
+ dockerInfoPromise = loadDockerInfo();
+ }
+
async function handleStartAll() {
- if (isLoading.starting || !dockerInfo || stoppedContainers === 0) return;
+ if (isLoading.starting || stoppedContainers === 0) return;
isLoading.starting = true;
handleApiResultWithCallbacks({
result: await tryCatch(systemService.startAllStoppedContainers()),
@@ -320,7 +331,7 @@
}
async function handleStopAll() {
- if (isLoading.stopping || !dockerInfo || dockerInfo?.ContainersRunning === 0) return;
+ if (isLoading.stopping || runningContainers === 0) return;
openConfirmDialog({
title: m.dashboard_stop_all_title(),
message: m.dashboard_stop_all_confirm(),
@@ -381,9 +392,9 @@
}
</script>
-<div class="flex min-h-full flex-col gap-4 pt-3 md:gap-5 md:pt-4">
+<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 rounded-xl border border-white/80 bg-white/10 p-4 shadow-sm backdrop-blur-sm sm:p-5"
+ 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">
@@ -395,10 +406,8 @@
class="w-full justify-start lg:w-auto lg:justify-end"
compact
user={data.user}
- {dockerInfo}
{stoppedContainers}
{runningContainers}
- loadingDockerInfo={isLoading.loadingDockerInfo}
isLoading={{ starting: isLoading.starting, stopping: isLoading.stopping, pruning: isLoading.pruning }}
onStartAll={handleStartAll}
onStopAll={handleStopAll}
@@ -409,7 +418,7 @@
</div>
</header>
- <section class="space-y-1.5">
+ <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>
@@ -493,7 +502,7 @@
{/if}
</section>
- <header>
+ <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">
@@ -544,7 +553,7 @@
<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: dockerInfo?.Name ?? m.common_unknown() })}</div>
+ <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" />
@@ -561,28 +570,27 @@
<span class="text-muted-foreground/50">•</span>
<span>{imageUsageLabel}</span>
<span class="text-muted-foreground/50">•</span>
- <span class="font-mono">{dockerInfo?.OperatingSystem ?? '-'} / {dockerInfo?.Architecture ?? '-'}</span>
+ <span class="font-mono">{overviewPlatform} / {overviewArchitecture}</span>
</div>
</div>
- {#if dockerInfo}
- <ArcaneButton
- action="base"
- tone="ghost"
- size="sm"
- icon={InfoIcon}
- showLabel={false}
- customLabel={m.common_inspect()}
- class="h-7 px-2.5 text-xs"
- onclick={() => (dockerInfoDialogOpen = true)}
- />
- {/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 min-h-0 flex-1 flex-col">
+ <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_resource_tables_title()}</h2>
<div class="hidden items-center gap-2 md:flex">
@@ -594,13 +602,15 @@
</ArcaneButton>
</div>
</div>
- <div class="grid min-h-0 flex-1 grid-cols-1 gap-4 lg:grid-cols-2">
- <DashboardContainerTable bind:containers isLoading={isLoading.loadingContainers} />
- <DashboardImageTable bind:images isLoading={isLoading.loadingImages} />
+ <div class="grid min-h-0 flex-1 grid-cols-1 gap-4 overflow-hidden lg:grid-cols-2">
+ <DashboardContainerTable bind:containers isLoading={false} />
+ <DashboardImageTable bind:images isLoading={false} />
</div>
</section>
- <DockerInfoDialog bind:open={dockerInfoDialogOpen} {dockerInfo} />
+ {#if dockerInfoDialogOpen}
+ <DockerInfoDialog bind:open={dockerInfoDialogOpen} {dockerInfo} {dockerInfoPromise} errorMessage={dockerInfoError} />
+ {/if}
<PruneConfirmationDialog
bind:open={isPruneDialogOpen}
diff --git a/frontend/src/routes/(app)/dashboard/+page.ts b/frontend/src/routes/(app)/dashboard/+page.ts
index 54448129d..1e624f3c4 100644
--- a/frontend/src/routes/(app)/dashboard/+page.ts
+++ b/frontend/src/routes/(app)/dashboard/+page.ts
@@ -1,11 +1,6 @@
-import { containerService } from '$lib/services/container-service';
import { dashboardService } from '$lib/services/dashboard-service';
-import { imageService } from '$lib/services/image-service';
-import { settingsService } from '$lib/services/settings-service';
-import { systemService } from '$lib/services/system-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { queryKeys } from '$lib/query/query-keys';
-import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
import { throwPageLoadError } from '$lib/utils/page-load-error.util';
import type { PageLoad } from './$types';
@@ -14,83 +9,17 @@ export const load: PageLoad = async ({ parent, url }) => {
const envId = await environmentStore.getCurrentEnvironmentId();
const debugAllGood = url.searchParams.get('debugAllGood') === 'true';
- const containerRequestOptions: SearchPaginationSortRequest = {
- pagination: {
- page: 1,
- limit: 5
- },
- sort: {
- column: 'created',
- direction: 'desc' as const
- }
- },
- imageRequestOptions: SearchPaginationSortRequest = {
- pagination: {
- page: 1,
- limit: 5
- },
- sort: {
- column: 'size',
- direction: 'desc' as const
- }
- };
-
- let containers;
- let images;
- let containerStatusCounts;
try {
- [containers, images, containerStatusCounts] = await Promise.all([
- queryClient.fetchQuery({
- queryKey: queryKeys.containers.list(envId, containerRequestOptions),
- queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.images.list(envId, imageRequestOptions),
- queryFn: () => imageService.getImagesForEnvironment(envId, imageRequestOptions)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.containers.statusCounts(envId),
- queryFn: () => containerService.getContainerStatusCountsForEnvironment(envId)
- })
- ]);
+ const dashboard = await queryClient.fetchQuery({
+ queryKey: queryKeys.dashboard.snapshot(envId, debugAllGood),
+ queryFn: () => dashboardService.getDashboardForEnvironment(envId, { debugAllGood })
+ });
+
+ return {
+ dashboard,
+ debugAllGood
+ };
} catch (err) {
throwPageLoadError(err, 'Failed to load dashboard data');
}
-
- const [dockerInfoResult, settingsResult, imageUsageCountsResult, dashboardActionItemsResult] = await Promise.allSettled([
- queryClient.fetchQuery({
- queryKey: queryKeys.system.dockerInfo(envId),
- queryFn: () => systemService.getDockerInfoForEnvironment(envId)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.settings.byEnvironment(envId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.images.usageCounts(envId),
- queryFn: () => imageService.getImageUsageCountsForEnvironment(envId)
- }),
- queryClient.fetchQuery({
- queryKey: queryKeys.dashboard.actionItems(envId, debugAllGood),
- queryFn: () => dashboardService.getActionItemsForEnvironment(envId, { debugAllGood })
- })
- ]);
-
- const dockerInfo = dockerInfoResult.status === 'fulfilled' ? dockerInfoResult.value : null;
- const settings = settingsResult.status === 'fulfilled' ? settingsResult.value : null;
- const imageUsageCounts = imageUsageCountsResult.status === 'fulfilled' ? imageUsageCountsResult.value : null;
- const dashboardActionItems = dashboardActionItemsResult.status === 'fulfilled' ? dashboardActionItemsResult.value : null;
-
- return {
- dockerInfo,
- containers,
- images,
- settings,
- imageUsageCounts,
- dashboardActionItems,
- debugAllGood,
- containerRequestOptions,
- imageRequestOptions,
- containerStatusCounts
- };
};
diff --git a/frontend/src/routes/(app)/dashboard/dash-container-table.svelte b/frontend/src/routes/(app)/dashboard/dash-container-table.svelte
index 533f336c2..36b8059dc 100644
--- a/frontend/src/routes/(app)/dashboard/dash-container-table.svelte
+++ b/frontend/src/routes/(app)/dashboard/dash-container-table.svelte
@@ -28,14 +28,11 @@
const isMobile = new IsMobile();
let selectedIds = $state<string[]>([]);
let displayLimit = $state(containers.pagination?.itemsPerPage ?? 5);
- let lastFetchedLimit = $state(containers.pagination?.itemsPerPage ?? 5);
- let resizeDebounceTimer: ReturnType<typeof setTimeout> | null = null;
let lastMeasuredHeight = $state(0);
- // Estimate row height: ~57px per row (including borders/padding), plus ~145px for header
const ROW_HEIGHT = 57;
const HEADER_HEIGHT = 145;
- const FOOTER_HEIGHT = 48; // Reserve space for the "showing" footer overlay
+ const FOOTER_HEIGHT = 48;
const MIN_ROWS = 3;
const MAX_ROWS = 50;
@@ -64,50 +61,29 @@
return Math.max(MIN_ROWS, Math.min(MAX_ROWS, rows));
}
- async function syncLimit(limit: number) {
- displayLimit = limit;
-
- const pagination = requestOptions.pagination;
- const currentLimit = containers.pagination?.itemsPerPage;
- if (!pagination || (limit === lastFetchedLimit && (currentLimit === undefined || currentLimit === limit))) {
- return;
- }
-
- if (resizeDebounceTimer) {
- clearTimeout(resizeDebounceTimer);
- }
-
- resizeDebounceTimer = setTimeout(async () => {
- try {
- lastFetchedLimit = limit;
- requestOptions = {
- ...requestOptions,
- pagination: {
- page: pagination.page ?? 1,
- limit
- }
- };
- containers = await containerService.getContainers(requestOptions);
- void handleLayoutChange(lastMeasuredHeight);
- } catch (error) {
- console.error('Failed to sync container limit:', error);
- } finally {
- resizeDebounceTimer = null;
+ function updateRequestLimit(limit: number) {
+ requestOptions = {
+ ...requestOptions,
+ pagination: {
+ page: requestOptions.pagination?.page ?? 1,
+ limit
}
- }, 300);
+ };
}
- async function handleLayoutChange(height: number) {
+ function handleLayoutChange(height: number) {
lastMeasuredHeight = height;
const nextLimit = calculateLimitForHeight(height);
- await syncLimit(nextLimit);
+ displayLimit = nextLimit;
+ updateRequestLimit(nextLimit);
}
async function refreshContainers(options: SearchPaginationSortRequest) {
requestOptions = options;
const result = await containerService.getContainers(options);
containers = result;
- await handleLayoutChange(lastMeasuredHeight);
+ displayLimit = result.pagination?.itemsPerPage ?? displayLimit;
+ handleLayoutChange(lastMeasuredHeight);
return result;
}
@@ -174,7 +150,7 @@
/>
{/snippet}
-<div class="flex h-full min-h-0 flex-col" bind:clientHeight={() => lastMeasuredHeight, (value) => void handleLayoutChange(value)}>
+<div class="flex h-full min-h-0 flex-col" bind:clientHeight={() => lastMeasuredHeight, (value) => handleLayoutChange(value)}>
<Card.Root class="flex h-full min-h-0 flex-col">
<Card.Header icon={ContainersIcon} class="shrink-0">
<div class="flex flex-1 items-center justify-between">
diff --git a/frontend/src/routes/(app)/dashboard/dash-image-table.svelte b/frontend/src/routes/(app)/dashboard/dash-image-table.svelte
index 2d9aa6ca0..d9132aa7d 100644
--- a/frontend/src/routes/(app)/dashboard/dash-image-table.svelte
+++ b/frontend/src/routes/(app)/dashboard/dash-image-table.svelte
@@ -24,13 +24,11 @@
const isMobile = new IsMobile();
let displayLimit = $state(images.pagination?.itemsPerPage ?? 5);
- let resizeDebounceTimer: ReturnType<typeof setTimeout> | null = null;
let lastMeasuredHeight = $state(0);
- // Estimate row height: ~57px per row (including borders/padding), plus ~145px for header
const ROW_HEIGHT = 57;
const HEADER_HEIGHT = 145;
- const FOOTER_HEIGHT = 48; // Reserve space for the "showing" footer overlay
+ const FOOTER_HEIGHT = 48;
const MIN_ROWS = 3;
const MAX_ROWS = 50;
@@ -39,6 +37,8 @@
sort: { column: 'size', direction: 'desc' }
});
+ let selectedIds = $state<string[]>([]);
+
function shouldReserveFooter(limit: number) {
const totalItems = images.pagination?.totalItems ?? 0;
return totalItems > limit;
@@ -59,53 +59,29 @@
return Math.max(MIN_ROWS, Math.min(MAX_ROWS, rows));
}
- let selectedIds = $state<string[]>([]);
- let lastFetchedLimit = $state(images.pagination?.itemsPerPage ?? 5);
-
- async function syncLimit(limit: number) {
- displayLimit = limit;
-
- const pagination = requestOptions.pagination;
- const currentLimit = images.pagination?.itemsPerPage;
- if (!pagination || (limit === lastFetchedLimit && (currentLimit === undefined || currentLimit === limit))) {
- return;
- }
-
- if (resizeDebounceTimer) {
- clearTimeout(resizeDebounceTimer);
- }
-
- resizeDebounceTimer = setTimeout(async () => {
- try {
- lastFetchedLimit = limit;
- requestOptions = {
- ...requestOptions,
- pagination: {
- page: pagination.page ?? 1,
- limit
- }
- };
- images = await imageService.getImages(requestOptions);
- void handleLayoutChange(lastMeasuredHeight);
- } catch (error) {
- console.error('Failed to sync image limit:', error);
- } finally {
- resizeDebounceTimer = null;
+ function updateRequestLimit(limit: number) {
+ requestOptions = {
+ ...requestOptions,
+ pagination: {
+ page: requestOptions.pagination?.page ?? 1,
+ limit
}
- }, 300);
+ };
}
- async function handleLayoutChange(height: number) {
+ function handleLayoutChange(height: number) {
lastMeasuredHeight = height;
const nextLimit = calculateLimitForHeight(height);
- await syncLimit(nextLimit);
+ displayLimit = nextLimit;
+ updateRequestLimit(nextLimit);
}
async function refreshImages(options: SearchPaginationSortRequest) {
requestOptions = options;
const result = await imageService.getImages(options);
images = result;
- await handleLayoutChange(lastMeasuredHeight);
+ displayLimit = result.pagination?.itemsPerPage ?? displayLimit;
+ handleLayoutChange(lastMeasuredHeight);
return result;
}
@@ -179,7 +155,7 @@
/>
{/snippet}
-<div class="flex h-full min-h-0 flex-col" bind:clientHeight={() => lastMeasuredHeight, (value) => void handleLayoutChange(value)}>
+<div class="flex h-full min-h-0 flex-col" bind:clientHeight={() => lastMeasuredHeight, (value) => handleLayoutChange(value)}>
<Card.Root class="flex h-full min-h-0 flex-col">
<Card.Header icon={ImagesIcon} class="shrink-0">
<div class="flex flex-1 items-center justify-between">
diff --git a/frontend/src/routes/(app)/projects/+page.svelte b/frontend/src/routes/(app)/projects/+page.svelte
index 3c13771bc..29a72020d 100644
--- a/frontend/src/routes/(app)/projects/+page.svelte
+++ b/frontend/src/routes/(app)/projects/+page.svelte
@@ -28,13 +28,15 @@
const projectsQuery = createQuery(() => ({
queryKey: queryKeys.projects.list(envId, projectRequestOptions),
queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions),
- initialData: data.projects
+ initialData: data.projects,
+ refetchOnMount: false
}));
const projectStatusCountsQuery = createQuery(() => ({
queryKey: queryKeys.projects.statusCounts(envId),
queryFn: () => projectService.getProjectStatusCountsForEnvironment(envId),
- initialData: data.projectStatusCounts
+ initialData: data.projectStatusCounts,
+ refetchOnMount: false
}));
const checkUpdatesMutation = createMutation(() => ({
diff --git a/tests/spec/dashboard-system-stats.spec.ts b/tests/spec/dashboard-system-stats.spec.ts
index 484dccae8..f3b41141f 100644
--- a/tests/spec/dashboard-system-stats.spec.ts
+++ b/tests/spec/dashboard-system-stats.spec.ts
@@ -99,6 +99,23 @@ async function mockDashboardStatsWebSocket(page: Page) {
}, mockedStats);
}
+function collectEnvironmentRequestPaths(page: Page): string[] {
+ const requestPaths: string[] = [];
+
+ page.on('request', (request) => {
+ const pathname = new URL(request.url()).pathname;
+ if (pathname.startsWith('/api/environments/')) {
+ requestPaths.push(pathname);
+ }
+ });
+
+ return requestPaths;
+}
+
+function countMatchingRequests(paths: string[], pattern: RegExp): number {
+ return paths.filter((path) => pattern.test(path)).length;
+}
+
test.describe('Dashboard system stats websocket', () => {
test('renders metrics from the system stats websocket stream', async ({ page }) => {
await mockDashboardStatsWebSocket(page);
@@ -113,4 +130,71 @@ test.describe('Dashboard system stats websocket', () => {
await expect(page.getByText('512 MB / 1 GB', { exact: true })).toBeVisible();
await expect(page.getByText('256 MB / 1 GB', { exact: true })).toBeVisible();
});
+
+ test('loads dashboard content from the snapshot endpoint without dashboard REST fan-out', async ({
+ page
+ }) => {
+ await mockDashboardStatsWebSocket(page);
+ const requestPaths = collectEnvironmentRequestPaths(page);
+
+ await page.goto('/dashboard');
+ await page.waitForLoadState('networkidle');
+
+ expect(
+ requestPaths.some((path) => /\/api\/environments\/[^/]+\/dashboard$/.test(path))
+ ).toBeTruthy();
+
+ for (const blockedPattern of [
+ /\/api\/environments\/[^/]+\/containers$/,
+ /\/api\/environments\/[^/]+\/containers\/counts$/,
+ /\/api\/environments\/[^/]+\/images$/,
+ /\/api\/environments\/[^/]+\/images\/counts$/,
+ /\/api\/environments\/[^/]+\/dashboard\/action-items$/,
+ /\/api\/environments\/[^/]+\/system\/docker\/info$/
+ ]) {
+ expect(countMatchingRequests(requestPaths, blockedPattern)).toBe(0);
+ }
+ });
+
+ test('lazy loads docker info when the inspect dialog opens and reuses the cached result', async ({
+ page
+ }) => {
+ await mockDashboardStatsWebSocket(page);
+ const requestPaths = collectEnvironmentRequestPaths(page);
+
+ await page.goto('/dashboard');
+ await page.waitForLoadState('networkidle');
+
+ expect(
+ countMatchingRequests(requestPaths, /\/api\/environments\/[^/]+\/system\/docker\/info$/)
+ ).toBe(0);
+
+ const dockerInfoRequest = page.waitForRequest((request) =>
+ /\/api\/environments\/[^/]+\/system\/docker\/info$/.test(new URL(request.url()).pathname)
+ );
+ await page
+ .getByRole('button', { name: /^Inspect$/ })
+ .first()
+ .click();
+ await dockerInfoRequest;
+ await expect(page.getByRole('dialog')).toBeVisible();
+ await expect
+ .poll(() =>
+ countMatchingRequests(requestPaths, /\/api\/environments\/[^/]+\/system\/docker\/info$/)
+ )
+ .toBe(1);
+
+ await page.getByRole('button', { name: /^Close$/ }).click();
+ await expect(page.getByRole('dialog')).not.toBeVisible();
+
+ await page
+ .getByRole('button', { name: /^Inspect$/ })
+ .first()
+ .click();
+ await page.waitForTimeout(300);
+
+ expect(
+ countMatchingRequests(requestPaths, /\/api\/environments\/[^/]+\/system\/docker\/info$/)
+ ).toBe(1);
+ });
});
diff --git a/types/dashboard/dashboard.go b/types/dashboard/dashboard.go
index dea064ac7..f65860716 100644
--- a/types/dashboard/dashboard.go
+++ b/types/dashboard/dashboard.go
@@ -1,5 +1,11 @@
package dashboard
+import (
+ "github.com/getarcaneapp/arcane/types/base"
+ containertypes "github.com/getarcaneapp/arcane/types/container"
+ imagetypes "github.com/getarcaneapp/arcane/types/image"
+)
+
type ActionItemKind string
const (
@@ -39,3 +45,66 @@ type ActionItems struct {
// Required: true
Items []ActionItem `json:"items"`
}
+
+type SnapshotSettings struct {
+ // DockerPruneMode controls whether prune defaults to all or dangling images.
+ //
+ // Required: true
+ DockerPruneMode string `json:"dockerPruneMode"`
+}
+
+type SnapshotContainers struct {
+ // Data is the first dashboard page of container summaries.
+ //
+ // Required: true
+ Data []containertypes.Summary `json:"data"`
+
+ // Counts is the full-environment container status summary.
+ //
+ // Required: true
+ Counts containertypes.StatusCounts `json:"counts"`
+
+ // Pagination describes the fixed first dashboard page.
+ //
+ // Required: true
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type SnapshotImages struct {
+ // Data is the first dashboard page of image summaries.
+ //
+ // Required: true
+ Data []imagetypes.Summary `json:"data"`
+
+ // Pagination describes the fixed first dashboard page.
+ //
+ // Required: true
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type Snapshot struct {
+ // Containers is the dashboard container table payload.
+ //
+ // Required: true
+ Containers SnapshotContainers `json:"containers"`
+
+ // Images is the dashboard image table payload.
+ //
+ // Required: true
+ Images SnapshotImages `json:"images"`
+
+ // ImageUsageCounts is the dashboard image usage summary.
+ //
+ // Required: true
+ ImageUsageCounts imagetypes.UsageCounts `json:"imageUsageCounts"`
+
+ // ActionItems is the dashboard attention summary.
+ //
+ // Required: true
+ ActionItems ActionItems `json:"actionItems"`
+
+ // Settings is the minimal settings payload needed by the dashboard.
+ //
+ // Required: true
+ Settings SnapshotSettings `json:"settings"`
+}