Skip to content

Modern Docker Management, Designed for Everyone

feat: ui configuration from env variables (#526)

Kyle Mendellaa46e324c208
diff --git a/.env.dev b/.env.dev
new file mode 100644
index 000000000..57a5e6772
--- /dev/null
+++ b/.env.dev
@@ -0,0 +1,27 @@
+# Arcane Development Environment Configuration
+# Copy this file to .env and customize the values for your development setup
+# WARNING: These are development-only values, never use in production!
+
+# Application Settings
+GIN_MODE=debug
+ENVIRONMENT=development
+PORT=3552
+
+# User/Group IDs for file permissions
+PUID=1000
+PGID=1000
+
+# General Settings
+UI_CONFIGURATION_DISABLED=true
+
+# Security Settings
+# Generate secure values for production: openssl rand -base64 32
+ENCRYPTION_KEY=dev-encryption-key-replace-in-production-must-be-32-chars
+JWT_SECRET=dev-jwt-secret-replace-in-production-must-be-long-enough
+
+# Database Configuration
+DATABASE_URL=file:data/arcane.db?_pragma=journal_mode(WAL)&_pragma=busy_timeout(2500)&_txlock=immediate
+
+# Agent Configuration (for development agent service)
+AGENT_MODE=false
+AGENT_BOOTSTRAP_TOKEN=development-bootstrap-token
diff --git a/.gitignore b/.gitignore
index aba55c1c4..4ffff2bc7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -22,6 +22,7 @@ Thumbs.db
.env.*
!.env.example
!.env.test
+!.env.dev
# Vite
vite.config.js.timestamp-*
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
index 2aa5a31f3..587d2772b 100644
--- a/.vscode/tasks.json
+++ b/.vscode/tasks.json
@@ -107,6 +107,25 @@
},
"detail": "Select which service logs to view"
},
+ {
+ "label": "Env Vars",
+ "type": "shell",
+ "command": "./scripts/development/dev.sh",
+ "args": [
+ "env",
+ "${input:envService}"
+ ],
+ "group": "test",
+ "presentation": {
+ "echo": true,
+ "reveal": "always",
+ "focus": true,
+ "panel": "dedicated",
+ "showReuseMessage": false,
+ "clear": true
+ },
+ "detail": "Show current environment configuration from running container"
+ },
{
"label": "Open Frontend",
"type": "process",
@@ -145,9 +164,33 @@
{
"label": "Backend Only",
"value": "backend"
+ },
+ {
+ "label": "Agent Only",
+ "value": "agent"
}
],
"default": ""
+ },
+ {
+ "id": "envService",
+ "description": "Which service environment to view",
+ "type": "pickString",
+ "options": [
+ {
+ "label": "Backend",
+ "value": "backend"
+ },
+ {
+ "label": "Frontend",
+ "value": "frontend"
+ },
+ {
+ "label": "Agent",
+ "value": "arcane-agent"
+ }
+ ],
+ "default": "backend"
}
]
}
diff --git a/backend/.air.toml b/backend/.air.toml
index f38c78a25..15c6544e5 100644
--- a/backend/.air.toml
+++ b/backend/.air.toml
@@ -11,13 +11,13 @@ tmp_dir = ".bin"
exclude_unchanged = false
follow_symlink = false
include_ext = ["go", "tpl", "tmpl", "html"]
- kill_delay = "0s"
+ kill_delay = "2s"
log = "build-errors.log"
poll = false
poll_interval = 0
rerun = false
rerun_delay = 500
- send_interrupt = false
+ send_interrupt = true
stop_on_root = false
[color]
@@ -32,7 +32,7 @@ tmp_dir = ".bin"
time = false
[misc]
- clean_on_exit = false
+ clean_on_exit = true
[screen]
clear_on_rebuild = false
diff --git a/backend/go.mod b/backend/go.mod
index d322f27fa..3619e7a11 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -19,12 +19,14 @@ require (
github.com/golang-migrate/migrate/v4 v4.19.0
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674
+ github.com/hashicorp/go-uuid v1.0.3
github.com/jinzhu/copier v0.4.0
github.com/joho/godotenv v1.5.1
github.com/lmittmann/tint v1.1.2
github.com/orandin/slog-gorm v1.4.0
github.com/samber/slog-gin v1.17.2
github.com/shirou/gopsutil/v3 v3.24.5
+ github.com/stretchr/testify v1.11.1
go.yaml.in/yaml/v4 v4.0.0-rc.2
golang.org/x/crypto v0.42.0
golang.org/x/sync v0.17.0
@@ -195,7 +197,6 @@ require (
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect
github.com/spf13/cobra v1.10.1 // indirect
github.com/spf13/pflag v1.0.10 // indirect
- github.com/stretchr/testify v1.11.1 // indirect
github.com/theupdateframework/notary v0.7.0 // indirect
github.com/tilt-dev/fsnotify v1.4.8-0.20220602155310-fff9c274a375 // indirect
github.com/tklauser/go-sysconf v0.3.15 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index 5a93e7a78..982fc63c6 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -301,6 +301,8 @@ github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9n
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
+github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
+github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY=
github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec h1:qv2VnGeEQHchGaZ/u7lxST/RaJw+cv273q79D81Xbog=
diff --git a/backend/internal/api/settings_handler.go b/backend/internal/api/settings_handler.go
index a0148c86f..fde3e341d 100644
--- a/backend/internal/api/settings_handler.go
+++ b/backend/internal/api/settings_handler.go
@@ -2,8 +2,10 @@ package api
import (
"net/http"
+ "strconv"
"github.com/gin-gonic/gin"
+ "github.com/ofkm/arcane-backend/internal/config"
"github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/middleware"
"github.com/ofkm/arcane-backend/internal/services"
@@ -24,60 +26,47 @@ func NewSettingsHandler(group *gin.RouterGroup, settingsService *services.Settin
}
func (h *SettingsHandler) GetSettings(c *gin.Context) {
- settings, err := h.settingsService.GetSettings(c.Request.Context())
- if err != nil {
+ settings := h.settingsService.ListSettings(true)
+
+ var settingsDto []dto.PublicSettingDto
+ if err := dto.MapStructList(settings, &settingsDto); err != nil {
+ _ = c.Error(err)
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": "Failed to fetch settings",
+ "error": "Failed to map settings",
})
return
}
- settingsSlice := settings.ToSettingVariableSlice(true, true)
-
- settingDtos := make([]dto.SettingDto, 0, len(settingsSlice))
- for _, setting := range settingsSlice {
- _, isPublic, _, _ := settings.FieldByKey(setting.Key)
- settingDtos = append(settingDtos, dto.SettingDto{
- PublicSettingDto: dto.PublicSettingDto{
- Key: setting.Key,
- Type: "string",
- Value: setting.Value,
- IsPublic: isPublic,
- },
- })
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "settings": settingDtos,
+ settingsDto = append(settingsDto, dto.PublicSettingDto{
+ Key: "uiConfigDisabled",
+ Value: strconv.FormatBool(config.Load().UIConfigurationDisabled),
+ Type: "boolean",
})
+
+ c.JSON(http.StatusOK, settingsDto)
}
func (h *SettingsHandler) GetPublicSettings(c *gin.Context) {
- publicSettings, err := h.settingsService.GetPublicSettings(c.Request.Context())
- if err != nil {
+ settings := h.settingsService.ListSettings(false)
+
+ var settingsDto []dto.PublicSettingDto
+ if err := dto.MapStructList(settings, &settingsDto); err != nil {
+ _ = c.Error(err)
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": "Failed to fetch public settings",
+ "error": "Failed to map settings",
})
return
}
- settingDtos := make([]dto.PublicSettingDto, 0, len(publicSettings))
- for _, setting := range publicSettings {
- settingDtos = append(settingDtos, dto.PublicSettingDto{
- Key: setting.Key,
- Type: "string",
- Value: setting.Value,
- IsPublic: true,
- })
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "settings": settingDtos,
+ settingsDto = append(settingsDto, dto.PublicSettingDto{
+ Key: "uiConfigDisabled",
+ Value: strconv.FormatBool(config.Load().UIConfigurationDisabled),
+ Type: "boolean",
})
+
+ c.JSON(http.StatusOK, settingsDto)
}
func (h *SettingsHandler) UpdateSettings(c *gin.Context) {
@@ -99,15 +88,13 @@ func (h *SettingsHandler) UpdateSettings(c *gin.Context) {
return
}
- // Convert to DTO format
settingDtos := make([]dto.SettingDto, 0, len(updatedSettings))
for _, setting := range updatedSettings {
settingDtos = append(settingDtos, dto.SettingDto{
PublicSettingDto: dto.PublicSettingDto{
- Key: setting.Key,
- Type: "string",
- Value: setting.Value,
- IsPublic: false, // We'll determine this from the struct later if needed
+ Key: setting.Key,
+ Type: "string",
+ Value: setting.Value,
},
})
}
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 7929b6acd..2ebf7f857 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -52,7 +52,7 @@ func InitializeApp() (*App, error) {
httpClient := newHTTPClient()
- appServices, dockerClientService, err := initializeServices(db, cfg, httpClient)
+ appServices, dockerClientService, err := initializeServices(appCtx, db, cfg, httpClient)
if err != nil {
db.Close()
cancelApp()
@@ -79,8 +79,7 @@ func InitializeApp() (*App, error) {
// Ensure default settings but skip user bootstrap in agent mode
slog.InfoContext(appCtx, "Ensuring default settings are initialized")
if err := appServices.Settings.EnsureDefaultSettings(appCtx); err != nil {
- slog.WarnContext(appCtx, "Failed to initialize default settings",
- slog.String("error", err.Error()))
+ slog.WarnContext(appCtx, "Failed to initialize default settings", slog.String("error", err.Error()))
} else {
slog.InfoContext(appCtx, "Default settings initialized successfully")
}
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.go
index 09a22fea5..13e82b46d 100644
--- a/backend/internal/bootstrap/services_bootstrap.go
+++ b/backend/internal/bootstrap/services_bootstrap.go
@@ -1,6 +1,8 @@
package bootstrap
import (
+ "context"
+ "fmt"
"net/http"
"github.com/ofkm/arcane-backend/internal/config"
@@ -30,29 +32,32 @@ type Services struct {
Version *services.VersionService
}
-func initializeServices(db *database.DB, cfg *config.Config, httpClient *http.Client) (*Services, *services.DockerClientService, error) {
- svc := &Services{}
+func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config, httpClient *http.Client) (svcs *Services, dockerSrvice *services.DockerClientService, err error) {
+ svcs = &Services{}
- svc.Event = services.NewEventService(db)
- svc.Converter = services.NewConverterService()
- svc.Settings = services.NewSettingsService(db, cfg)
+ svcs.Event = services.NewEventService(db)
+ svcs.Converter = services.NewConverterService()
+ svcs.Settings, err = services.NewSettingsService(ctx, db)
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to settings service: %w", err)
+ }
dockerClient := services.NewDockerClientService(db)
- svc.Docker = dockerClient
- svc.User = services.NewUserService(db)
- svc.ContainerRegistry = services.NewContainerRegistryService(db)
- svc.ImageUpdate = services.NewImageUpdateService(db, svc.Settings, svc.ContainerRegistry, svc.Docker, svc.Event)
- svc.Image = services.NewImageService(db, svc.Docker, svc.ContainerRegistry, svc.ImageUpdate, svc.Event)
- svc.Project = services.NewProjectService(db, svc.Settings, svc.Event, svc.Image)
- svc.Environment = services.NewEnvironmentService(db, httpClient)
- svc.Container = services.NewContainerService(db, svc.Event, svc.Docker)
- svc.Volume = services.NewVolumeService(db, svc.Docker, svc.Event)
- svc.Network = services.NewNetworkService(db, svc.Docker, svc.Event)
- svc.Template = services.NewTemplateService(db, httpClient)
- svc.Auth = services.NewAuthService(svc.User, svc.Settings, svc.Event, cfg.JWTSecret, cfg)
- svc.Oidc = services.NewOidcService(svc.Auth, cfg, httpClient)
- svc.Updater = services.NewUpdaterService(db, svc.Settings, svc.Docker, svc.Project, svc.ImageUpdate, svc.ContainerRegistry, svc.Event, svc.Image)
- svc.System = services.NewSystemService(db, svc.Docker, svc.Container, svc.Image, svc.Volume, svc.Network, svc.Settings)
- svc.Version = services.NewVersionService(httpClient, cfg.UpdateCheckDisabled)
+ svcs.Docker = dockerClient
+ svcs.User = services.NewUserService(db)
+ svcs.ContainerRegistry = services.NewContainerRegistryService(db)
+ svcs.ImageUpdate = services.NewImageUpdateService(db, svcs.Settings, svcs.ContainerRegistry, svcs.Docker, svcs.Event)
+ svcs.Image = services.NewImageService(db, svcs.Docker, svcs.ContainerRegistry, svcs.ImageUpdate, svcs.Event)
+ svcs.Project = services.NewProjectService(db, svcs.Settings, svcs.Event, svcs.Image)
+ svcs.Environment = services.NewEnvironmentService(db, httpClient)
+ svcs.Container = services.NewContainerService(db, svcs.Event, svcs.Docker)
+ svcs.Volume = services.NewVolumeService(db, svcs.Docker, svcs.Event)
+ svcs.Network = services.NewNetworkService(db, svcs.Docker, svcs.Event)
+ svcs.Template = services.NewTemplateService(db, httpClient)
+ svcs.Auth = services.NewAuthService(svcs.User, svcs.Settings, svcs.Event, cfg.JWTSecret, cfg)
+ svcs.Oidc = services.NewOidcService(svcs.Auth, cfg, httpClient)
+ svcs.Updater = services.NewUpdaterService(db, svcs.Settings, svcs.Docker, svcs.Project, svcs.ImageUpdate, svcs.ContainerRegistry, svcs.Event, svcs.Image)
+ svcs.System = services.NewSystemService(db, svcs.Docker, svcs.Container, svcs.Image, svcs.Volume, svcs.Network, svcs.Settings)
+ svcs.Version = services.NewVersionService(httpClient, cfg.UpdateCheckDisabled)
- return svc, dockerClient, nil
+ return svcs, dockerClient, nil
}
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index 25e6aaca7..218148ac4 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -26,14 +26,14 @@ type Config struct {
OidcAdminClaim string
OidcAdminValue string
- LogJson bool
- LogLevel string
- AgentMode bool
- AgentToken string
- AgentBootstrapToken string
- UpdateCheckDisabled bool
-
- AnalyticsDisabled bool
+ LogJson bool
+ LogLevel string
+ AgentMode bool
+ AgentToken string
+ AgentBootstrapToken string
+ UpdateCheckDisabled bool
+ UIConfigurationDisabled bool
+ AnalyticsDisabled bool
}
func Load() *Config {
@@ -53,14 +53,14 @@ func Load() *Config {
OidcAdminClaim: getEnvOrDefault("OIDC_ADMIN_CLAIM", ""),
OidcAdminValue: getEnvOrDefault("OIDC_ADMIN_VALUE", ""),
- LogJson: getBoolEnvOrDefault("LOG_JSON", false),
- LogLevel: strings.ToLower(getEnvOrDefault("LOG_LEVEL", "info")),
- AgentMode: getBoolEnvOrDefault("AGENT_MODE", false),
- AgentToken: os.Getenv("AGENT_TOKEN"),
- AgentBootstrapToken: os.Getenv("AGENT_BOOTSTRAP_TOKEN"),
- UpdateCheckDisabled: getBoolEnvOrDefault("UPDATE_CHECK_DISABLED", false),
-
- AnalyticsDisabled: getBoolEnvOrDefault("ANALYTICS_DISABLED", false),
+ LogJson: getBoolEnvOrDefault("LOG_JSON", false),
+ LogLevel: strings.ToLower(getEnvOrDefault("LOG_LEVEL", "info")),
+ AgentMode: getBoolEnvOrDefault("AGENT_MODE", false),
+ AgentToken: os.Getenv("AGENT_TOKEN"),
+ AgentBootstrapToken: os.Getenv("AGENT_BOOTSTRAP_TOKEN"),
+ UpdateCheckDisabled: getBoolEnvOrDefault("UPDATE_CHECK_DISABLED", false),
+ UIConfigurationDisabled: getBoolEnvOrDefault("UI_CONFIGURATION_DISABLED", false),
+ AnalyticsDisabled: getBoolEnvOrDefault("ANALYTICS_DISABLED", false),
}
}
diff --git a/backend/internal/dto/dto_map.go b/backend/internal/dto/dto_map.go
index db789a8d3..37b94d5e0 100644
--- a/backend/internal/dto/dto_map.go
+++ b/backend/internal/dto/dto_map.go
@@ -29,3 +29,16 @@ func MapStruct(source any, destination any) error {
DeepCopy: true,
})
}
+
+// MapStructList maps a list of source structs to a list of destination structs
+func MapStructList[S any, D any](source []S, destination *[]D) (err error) {
+ *destination = make([]D, len(source))
+
+ for i, item := range source {
+ err = MapStruct(item, &((*destination)[i]))
+ if err != nil {
+ return fmt.Errorf("failed to map field %d: %w", i, err)
+ }
+ }
+ return nil
+}
diff --git a/backend/internal/dto/settings_dto.go b/backend/internal/dto/settings_dto.go
index f9f630bc4..3f837f362 100644
--- a/backend/internal/dto/settings_dto.go
+++ b/backend/internal/dto/settings_dto.go
@@ -1,14 +1,14 @@
package dto
type PublicSettingDto struct {
- Key string `json:"key"`
- Type string `json:"type"`
- Value string `json:"value"`
- IsPublic bool `json:"isPublic"`
+ Key string `json:"key"`
+ Type string `json:"type"`
+ Value string `json:"value"`
}
type SettingDto struct {
PublicSettingDto
+ IsPublic bool `json:"isPublic"`
}
type UpdateSettingsDto struct {
diff --git a/backend/internal/job/analytics_job.go b/backend/internal/job/analytics_job.go
index c43b1256e..3ca04e0ee 100644
--- a/backend/internal/job/analytics_job.go
+++ b/backend/internal/job/analytics_job.go
@@ -78,14 +78,6 @@ func (j *AnalyticsJob) Execute(parentCtx context.Context) error {
}
instanceID := j.settingsService.GetStringSetting(parentCtx, "instanceId", "")
- if instanceID == "" {
- if ensuredID, err := j.settingsService.EnsureInstanceID(parentCtx); err == nil {
- instanceID = ensuredID
- } else {
- slog.WarnContext(parentCtx, "failed to ensure instance ID; using 'unknown'", "error", err)
- instanceID = "unknown"
- }
- }
payload := struct {
Version string `json:"version"`
diff --git a/backend/internal/models/errors.go b/backend/internal/models/errors.go
index be72b6baa..873153a0f 100644
--- a/backend/internal/models/errors.go
+++ b/backend/internal/models/errors.go
@@ -149,3 +149,10 @@ func ToAPIError(err error) *APIError {
}
return NewInternalServerError(err.Error())
}
+
+type UiSettingsDisabledError struct{}
+
+func (e *UiSettingsDisabledError) Error() string {
+ return "The settings can't be changed since UI configuration is disabled"
+}
+func (e *UiSettingsDisabledError) HttpStatusCode() int { return http.StatusForbidden }
diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.go
index 16adef679..0c8110cf1 100644
--- a/backend/internal/services/settings_service.go
+++ b/backend/internal/services/settings_service.go
@@ -7,54 +7,70 @@ import (
"encoding/json"
"errors"
"fmt"
+ "os"
"reflect"
"strings"
+ "sync/atomic"
+ "time"
- "github.com/google/uuid"
+ "github.com/hashicorp/go-uuid"
"gorm.io/gorm"
- "gorm.io/gorm/clause"
"github.com/ofkm/arcane-backend/internal/config"
"github.com/ofkm/arcane-backend/internal/database"
"github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/models"
+ "github.com/ofkm/arcane-backend/internal/utils"
)
type SettingsService struct {
db *database.DB
- config *config.Config
+ config atomic.Pointer[models.Settings]
OnImagePollingSettingsChanged func(ctx context.Context)
OnAutoUpdateSettingsChanged func(ctx context.Context)
}
-func NewSettingsService(db *database.DB, cfg *config.Config) *SettingsService {
- return &SettingsService{
- db: db,
- config: cfg,
+func NewSettingsService(ctx context.Context, db *database.DB) (*SettingsService, error) {
+ svc := &SettingsService{
+ db: db,
}
-}
-func (s *SettingsService) GetSettings(ctx context.Context) (*models.Settings, error) {
- var settingVars []models.SettingVariable
- err := s.db.WithContext(ctx).Find(&settingVars).Error
+ err := svc.LoadDatabaseSettings(ctx)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("failed to load settings: %w", err)
}
- settings := &models.Settings{}
+ err = svc.setupInstanceID(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to setup instance ID: %w", err)
+ }
- for _, sv := range settingVars {
- if err := settings.UpdateField(sv.Key, sv.Value, false); err != nil {
- // If key not found, it's okay
- var notFoundErr models.SettingKeyNotFoundError
- if !errors.As(err, &notFoundErr) {
- return nil, fmt.Errorf("failed to load setting %s: %w", sv.Key, err)
- }
- }
+ if err = svc.LoadDatabaseSettings(ctx); err != nil {
+ return nil, fmt.Errorf("failed to reload settings after instance ID setup: %w", err)
}
- return settings, nil
+ return svc, nil
+}
+
+func (s *SettingsService) GetSettingsConfig() *models.Settings {
+ v := s.config.Load()
+ if v == nil {
+ panic("GetSettingsConfig called before Settings has been loaded")
+ }
+
+ return v
+}
+
+func (s *SettingsService) LoadDatabaseSettings(ctx context.Context) (err error) {
+ dst, err := s.loadDatabaseSettingsInternal(ctx, s.db)
+ if err != nil {
+ return err
+ }
+
+ s.config.Store(dst)
+
+ return nil
}
func (s *SettingsService) getDefaultSettings() *models.Settings {
@@ -65,7 +81,7 @@ func (s *SettingsService) getDefaultSettings() *models.Settings {
PollingEnabled: models.SettingVariable{Value: "true"},
PollingInterval: models.SettingVariable{Value: "60"},
PruneMode: models.SettingVariable{Value: "dangling"},
- BaseServerURL: models.SettingVariable{Value: ""},
+ BaseServerURL: models.SettingVariable{Value: "http://localhost"},
EnableGravatar: models.SettingVariable{Value: "true"},
AuthLocalEnabled: models.SettingVariable{Value: "true"},
AuthOidcEnabled: models.SettingVariable{Value: "false"},
@@ -79,70 +95,131 @@ func (s *SettingsService) getDefaultSettings() *models.Settings {
}
}
-func (s *SettingsService) SyncOidcEnvToDatabase(ctx context.Context) ([]models.SettingVariable, error) {
- if !s.config.OidcEnabled {
- return nil, errors.New("OIDC sync called but OIDC_ENABLED is false")
- }
+func (s *SettingsService) loadDatabaseSettingsInternal(ctx context.Context, db *database.DB) (*models.Settings, error) {
- if s.config.OidcClientID == "" || s.config.OidcIssuerURL == "" {
- return nil, errors.New("required OIDC environment variables are missing (OIDC_CLIENT_ID or OIDC_ISSUER_URL)")
- }
+ if config.Load().UIConfigurationDisabled || config.Load().AgentMode {
+ dst, err := s.loadDatabaseConfigFromEnv(ctx, db)
+
+ if config.Load().Environment != "testing" {
+ var onboardingVars []models.SettingVariable
+ if err := db.WithContext(ctx).
+ Where("key IN ?", []string{"onboardingCompleted", "onboardingSteps"}).
+ Find(&onboardingVars).Error; err == nil {
+ for _, v := range onboardingVars {
+ _ = dst.UpdateField(v.Key, v.Value, false)
+ }
+ }
+ }
- envOidcConfig := models.OidcConfig{
- ClientID: s.config.OidcClientID,
- ClientSecret: s.config.OidcClientSecret,
- IssuerURL: s.config.OidcIssuerURL,
- Scopes: s.config.OidcScopes,
- AdminClaim: s.config.OidcAdminClaim,
- AdminValue: s.config.OidcAdminValue,
+ return dst, err
}
- oidcConfigBytes, err := json.Marshal(envOidcConfig)
+ dest := s.getDefaultSettings()
+
+ var loaded []models.SettingVariable
+ queryCtx, queryCancel := context.WithTimeout(ctx, 10*time.Second)
+ defer queryCancel()
+ err := db.
+ WithContext(queryCtx).
+ Find(&loaded).Error
if err != nil {
- return nil, fmt.Errorf("failed to marshal OIDC config from env: %w", err)
+ return nil, fmt.Errorf("failed to load configuration from the database: %w", err)
}
- // Force update the settings directly to bypass empty value checks
- err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- // Force update AuthOidcEnabled
- if err := tx.Save(&models.SettingVariable{
- Key: "authOidcEnabled",
- Value: "true",
- }).Error; err != nil {
- return fmt.Errorf("failed to update authOidcEnabled: %w", err)
+ for _, v := range loaded {
+ err = dest.UpdateField(v.Key, v.Value, false)
+
+ if err != nil && !errors.Is(err, models.SettingKeyNotFoundError{}) {
+ return nil, fmt.Errorf("failed to process settings for key '%s': %w", v.Key, err)
}
+ }
- // Force update AuthOidcConfig
- if err := tx.Save(&models.SettingVariable{
- Key: "authOidcConfig",
- Value: string(oidcConfigBytes),
- }).Error; err != nil {
- return fmt.Errorf("failed to update authOidcConfig: %w", err)
+ return dest, nil
+
+}
+
+func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *database.DB) (*models.Settings, error) {
+ dest := s.getDefaultSettings()
+
+ rt := reflect.ValueOf(dest).Elem().Type()
+ rv := reflect.ValueOf(dest).Elem()
+ for i := range rt.NumField() {
+ field := rt.Field(i)
+
+ key, attrs, _ := strings.Cut(field.Tag.Get("key"), ",")
+
+ if attrs == "internal" {
+ var value string
+ err := db.WithContext(ctx).
+ Model(&models.SettingVariable{}).
+ Where("key = ?", key).
+ Select("value").
+ First(&value).Error
+ if err == nil {
+ rv.Field(i).FieldByName("Value").SetString(value)
+ }
+ continue
}
- return nil
- })
+ envVarName := utils.CamelCaseToScreamingSnakeCase(key)
- if err != nil {
- return nil, fmt.Errorf("failed to sync OIDC settings to database: %w", err)
+ value, ok := os.LookupEnv(envVarName)
+ if ok {
+ rv.Field(i).FieldByName("Value").SetString(value)
+ continue
+ }
}
- // Return the updated settings
- settings, err := s.GetSettings(ctx)
+ return dest, nil
+}
+
+func (s *SettingsService) GetSettings(ctx context.Context) (*models.Settings, error) {
+ var settingVars []models.SettingVariable
+ err := s.db.WithContext(ctx).Find(&settingVars).Error
if err != nil {
- return nil, fmt.Errorf("failed to retrieve updated settings: %w", err)
+ return nil, err
}
- return settings.ToSettingVariableSlice(false, false), nil
+ settings := &models.Settings{}
+
+ for _, sv := range settingVars {
+ if err := settings.UpdateField(sv.Key, sv.Value, false); err != nil {
+ var notFoundErr models.SettingKeyNotFoundError
+ if !errors.As(err, &notFoundErr) {
+ return nil, fmt.Errorf("failed to load setting %s: %w", sv.Key, err)
+ }
+ }
+ }
+
+ return settings, nil
}
-func (s *SettingsService) GetPublicSettings(ctx context.Context) ([]models.SettingVariable, error) {
- settings, err := s.GetSettings(ctx)
+func (s *SettingsService) SyncOidcEnvToDatabase(ctx context.Context) ([]models.SettingVariable, error) {
+ cfg := config.Load()
+ if cfg.OidcClientID == "" || cfg.OidcIssuerURL == "" {
+ return nil, errors.New("missing OIDC_CLIENT_ID or OIDC_ISSUER_URL")
+ }
+
+ envOidc := models.OidcConfig{
+ ClientID: cfg.OidcClientID,
+ ClientSecret: cfg.OidcClientSecret,
+ IssuerURL: cfg.OidcIssuerURL,
+ Scopes: cfg.OidcScopes,
+ AdminClaim: cfg.OidcAdminClaim,
+ AdminValue: cfg.OidcAdminValue,
+ }
+ b, err := json.Marshal(envOidc)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("marshal oidc config: %w", err)
}
- return settings.ToSettingVariableSlice(false, false), nil
+ trueStr := "true"
+ cfgStr := string(b)
+
+ return s.UpdateSettings(ctx, dto.UpdateSettingsDto{
+ AuthOidcEnabled: &trueStr,
+ AuthOidcConfig: &cfgStr,
+ })
}
func (s *SettingsService) UpdateSetting(ctx context.Context, key, value string) error {
@@ -305,50 +382,30 @@ func (s *SettingsService) EnsureDefaultSettings(ctx context.Context) error {
return err
}
- if _, err := s.EnsureInstanceID(ctx); err != nil {
- return err
- }
return nil
}
-func (s *SettingsService) EnsureInstanceID(ctx context.Context) (string, error) {
- const key = "instanceId"
-
- var newID string
- err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- var sv models.SettingVariable
-
- if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
- Where("key = ?", key).
- First(&sv).Error; err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- newID = uuid.New().String()
- if createErr := tx.Create(&models.SettingVariable{Key: key, Value: newID}).Error; createErr != nil {
- return fmt.Errorf("failed to persist %s: %w", key, createErr)
- }
- return nil
- }
- return fmt.Errorf("failed to load %s: %w", key, err)
- }
-
- if sv.Value != "" {
- newID = sv.Value
- return nil
- }
+func (s *SettingsService) ListSettings(all bool) []models.SettingVariable {
+ return s.GetSettingsConfig().ToSettingVariableSlice(all, true)
+}
- newID = uuid.New().String()
- if updErr := tx.Model(&models.SettingVariable{}).
- Where("key = ?", key).
- Update("value", newID).Error; updErr != nil {
- return fmt.Errorf("failed to update %s: %w", key, updErr)
- }
+func (s *SettingsService) setupInstanceID(ctx context.Context) error {
+ instanceID := s.GetSettingsConfig().InstanceID.Value
+ if instanceID != "" {
return nil
- })
+ }
+ createdInstanceID, err := uuid.GenerateUUID()
if err != nil {
- return "", err
+ return fmt.Errorf("failed to created a new instance ID: %w", err)
}
- return newID, nil
+
+ err = s.UpdateSetting(ctx, "instanceId", createdInstanceID)
+ if err != nil {
+ return fmt.Errorf("failed to set instance ID in database: %w", err)
+ }
+
+ return nil
}
func (s *SettingsService) GetBoolSetting(ctx context.Context, key string, defaultValue bool) bool {
@@ -379,15 +436,34 @@ func (s *SettingsService) GetStringSetting(ctx context.Context, key, defaultValu
}
func (s *SettingsService) SetBoolSetting(ctx context.Context, key string, value bool) error {
- return s.UpdateSetting(ctx, key, fmt.Sprintf("%t", value))
+ if err := s.UpdateSetting(ctx, key, fmt.Sprintf("%t", value)); err != nil {
+ return err
+ }
+ // Rebuild a fresh snapshot instead of mutating current pointer (avoids races)
+ if err := s.LoadDatabaseSettings(ctx); err != nil {
+ return fmt.Errorf("failed to refresh settings cache: %w", err)
+ }
+ return nil
}
func (s *SettingsService) SetIntSetting(ctx context.Context, key string, value int) error {
- return s.UpdateSetting(ctx, key, fmt.Sprintf("%d", value))
+ if err := s.UpdateSetting(ctx, key, fmt.Sprintf("%d", value)); err != nil {
+ return err
+ }
+ if err := s.LoadDatabaseSettings(ctx); err != nil {
+ return fmt.Errorf("failed to refresh settings cache: %w", err)
+ }
+ return nil
}
func (s *SettingsService) SetStringSetting(ctx context.Context, key, value string) error {
- return s.UpdateSetting(ctx, key, value)
+ if err := s.UpdateSetting(ctx, key, value); err != nil {
+ return err
+ }
+ if err := s.LoadDatabaseSettings(ctx); err != nil {
+ return fmt.Errorf("failed to refresh settings cache: %w", err)
+ }
+ return nil
}
func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, error) {
@@ -402,16 +478,22 @@ func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, erro
return "", fmt.Errorf("failed to load encryption key: %w", err)
}
+ // If already present and non-empty, return it
if sv.Value != "" {
return sv.Value, nil
}
- // Generate uuid -> sha256 -> base64 key (32 bytes)
- u := uuid.New().String()
+ notFound := errors.Is(err, gorm.ErrRecordNotFound)
+
+ // Generate uuid -> sha256 -> base64 key (32 bytes raw -> 44 chars base64)
+ u, genErr := uuid.GenerateUUID()
+ if genErr != nil {
+ return "", fmt.Errorf("failed to generate encryption key: %w", genErr)
+ }
sum := sha256.Sum256([]byte(u))
key := base64.StdEncoding.EncodeToString(sum[:])
- if errors.Is(err, gorm.ErrRecordNotFound) {
+ if notFound {
if createErr := s.db.WithContext(ctx).
Create(&models.SettingVariable{Key: keyName, Value: key}).Error; createErr != nil {
return "", fmt.Errorf("failed to persist encryption key: %w", createErr)
@@ -419,6 +501,7 @@ func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, erro
return key, nil
}
+ // Record existed but empty value; update it
if updErr := s.db.WithContext(ctx).
Model(&models.SettingVariable{}).
Where("key = ?", keyName).
diff --git a/backend/internal/services/settings_service_test.go b/backend/internal/services/settings_service_test.go
index be855b514..cfed5b76a 100644
--- a/backend/internal/services/settings_service_test.go
+++ b/backend/internal/services/settings_service_test.go
@@ -6,217 +6,159 @@ import (
"testing"
glsqlite "github.com/glebarez/sqlite"
+ "github.com/stretchr/testify/require"
+ "gorm.io/gorm"
+
"github.com/ofkm/arcane-backend/internal/config"
"github.com/ofkm/arcane-backend/internal/database"
"github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/models"
- "gorm.io/gorm"
)
func setupSettingsTestDB(t *testing.T) *database.DB {
t.Helper()
db, err := gorm.Open(glsqlite.Open(":memory:"), &gorm.Config{})
- if err != nil {
- t.Fatalf("open db: %v", err)
- }
- if err := db.AutoMigrate(&models.SettingVariable{}); err != nil {
- t.Fatalf("migrate: %v", err)
- }
+ require.NoError(t, err)
+ require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))
return &database.DB{DB: db}
}
func TestSettingsService_EnsureDefaultSettings_Idempotent(t *testing.T) {
ctx := context.Background()
db := setupSettingsTestDB(t)
- svc := NewSettingsService(db, &config.Config{})
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
- if err := svc.EnsureDefaultSettings(ctx); err != nil {
- t.Fatalf("EnsureDefaultSettings: %v", err)
- }
+ require.NoError(t, svc.EnsureDefaultSettings(ctx))
var count1 int64
- if err := svc.db.WithContext(ctx).Model(&models.SettingVariable{}).Count(&count1).Error; err != nil {
- t.Fatalf("count: %v", err)
- }
- if count1 == 0 {
- t.Fatalf("expected defaults inserted")
- }
+ require.NoError(t, svc.db.WithContext(ctx).Model(&models.SettingVariable{}).Count(&count1).Error)
+ require.Positive(t, count1)
- // Run again (should not duplicate)
- if err := svc.EnsureDefaultSettings(ctx); err != nil {
- t.Fatalf("EnsureDefaultSettings 2nd run: %v", err)
- }
+ require.NoError(t, svc.EnsureDefaultSettings(ctx))
var count2 int64
- if err := svc.db.WithContext(ctx).Model(&models.SettingVariable{}).Count(&count2).Error; err != nil {
- t.Fatalf("count2: %v", err)
- }
- if count2 != count1 {
- t.Fatalf("defaults not idempotent: first=%d second=%d", count1, count2)
- }
+ require.NoError(t, svc.db.WithContext(ctx).Model(&models.SettingVariable{}).Count(&count2).Error)
+ require.Equal(t, count1, count2)
// Spot-check a couple keys exist
for _, key := range []string{"authLocalEnabled", "projectsDirectory"} {
var sv models.SettingVariable
err := svc.db.WithContext(ctx).Where("key = ?", key).First(&sv).Error
- if err != nil {
- t.Fatalf("missing default key %s: %v", key, err)
- }
+ require.NoErrorf(t, err, "missing default key %s", key)
}
}
func TestSettingsService_GetSettings_UnknownKeysIgnored(t *testing.T) {
ctx := context.Background()
db := setupSettingsTestDB(t)
- svc := NewSettingsService(db, &config.Config{})
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
- // Unknown key should not break loading
- if err := svc.db.WithContext(ctx).Create(&models.SettingVariable{Key: "someUnknownKey", Value: "x"}).Error; err != nil {
- t.Fatalf("seed: %v", err)
- }
- if _, err := svc.GetSettings(ctx); err != nil {
- t.Fatalf("GetSettings should ignore unknown key: %v", err)
- }
+ require.NoError(t, svc.db.WithContext(ctx).
+ Create(&models.SettingVariable{Key: "someUnknownKey", Value: "x"}).Error)
+
+ _, err = svc.GetSettings(ctx)
+ require.NoError(t, err)
}
func TestSettingsService_GetSetHelpers(t *testing.T) {
ctx := context.Background()
db := setupSettingsTestDB(t)
- svc := NewSettingsService(db, &config.Config{})
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
// Defaults for missing keys
- if got := svc.GetBoolSetting(ctx, "nonexistentBool", true); got != true {
- t.Fatalf("GetBoolSetting default mismatch: got %v", got)
- }
- if got := svc.GetIntSetting(ctx, "nonexistentInt", 42); got != 42 {
- t.Fatalf("GetIntSetting default mismatch: got %v", got)
- }
- if got := svc.GetStringSetting(ctx, "nonexistentStr", "def"); got != "def" {
- t.Fatalf("GetStringSetting default mismatch: got %v", got)
- }
+ require.True(t, svc.GetBoolSetting(ctx, "nonexistentBool", true))
+ require.Equal(t, 42, svc.GetIntSetting(ctx, "nonexistentInt", 42))
+ require.Equal(t, "def", svc.GetStringSetting(ctx, "nonexistentStr", "def"))
// Set and read back
- if err := svc.SetBoolSetting(ctx, "enableGravatar", true); err != nil {
- t.Fatalf("SetBoolSetting: %v", err)
- }
- if got := svc.GetBoolSetting(ctx, "enableGravatar", false); !got {
- t.Fatalf("GetBoolSetting persisted mismatch")
- }
+ require.NoError(t, svc.SetBoolSetting(ctx, "enableGravatar", true))
+ require.True(t, svc.GetBoolSetting(ctx, "enableGravatar", false))
- if err := svc.SetIntSetting(ctx, "authSessionTimeout", 123); err != nil {
- t.Fatalf("SetIntSetting: %v", err)
- }
- if got := svc.GetIntSetting(ctx, "authSessionTimeout", 0); got != 123 {
- t.Fatalf("GetIntSetting persisted mismatch: %v", got)
- }
+ require.NoError(t, svc.SetIntSetting(ctx, "authSessionTimeout", 123))
+ require.Equal(t, 123, svc.GetIntSetting(ctx, "authSessionTimeout", 0))
- if err := svc.SetStringSetting(ctx, "baseServerUrl", "http://localhost"); err != nil {
- t.Fatalf("SetStringSetting: %v", err)
- }
- if got := svc.GetStringSetting(ctx, "baseServerUrl", ""); got != "http://localhost" {
- t.Fatalf("GetStringSetting persisted mismatch: %q", got)
- }
+ require.NoError(t, svc.SetStringSetting(ctx, "baseServerUrl", "http://localhost"))
+ require.Equal(t, "http://localhost", svc.GetStringSetting(ctx, "baseServerUrl", ""))
}
func TestSettingsService_UpdateSetting(t *testing.T) {
ctx := context.Background()
db := setupSettingsTestDB(t)
- svc := NewSettingsService(db, &config.Config{})
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ // Use an existing key ("pruneMode") instead of a non-existent one
+ require.NoError(t, svc.UpdateSetting(ctx, "pruneMode", "all"))
- if err := svc.UpdateSetting(ctx, "dockerPruneMode", "all"); err != nil {
- t.Fatalf("UpdateSetting: %v", err)
- }
var sv models.SettingVariable
- if err := svc.db.WithContext(ctx).Where("key = ?", "dockerPruneMode").First(&sv).Error; err != nil {
- t.Fatalf("query: %v", err)
- }
- if sv.Value != "all" {
- t.Fatalf("value mismatch: %q", sv.Value)
- }
+ require.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "pruneMode").First(&sv).Error)
+ require.Equal(t, "all", sv.Value)
}
func TestSettingsService_EnsureEncryptionKey(t *testing.T) {
ctx := context.Background()
db := setupSettingsTestDB(t)
- svc := NewSettingsService(db, &config.Config{})
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
k1, err := svc.EnsureEncryptionKey(ctx)
- if err != nil {
- t.Fatalf("EnsureEncryptionKey: %v", err)
- }
- if k1 == "" {
- t.Fatalf("empty key")
- }
+ require.NoError(t, err)
+ require.NotEmpty(t, k1)
- // Key should be persisted and reused
k2, err := svc.EnsureEncryptionKey(ctx)
- if err != nil {
- t.Fatalf("EnsureEncryptionKey 2nd: %v", err)
- }
- if k2 != k1 {
- t.Fatalf("key not stable: first=%q second=%q", k1, k2)
- }
+ require.NoError(t, err)
+ require.Equal(t, k1, k2, "encryption key should be stable between calls")
var sv models.SettingVariable
- if err := svc.db.WithContext(ctx).Where("key = ?", "encryptionKey").First(&sv).Error; err != nil {
- t.Fatalf("query encryptionKey: %v", err)
- }
- if sv.Value != k1 {
- t.Fatalf("stored key mismatch")
- }
+ require.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "encryptionKey").First(&sv).Error)
+ require.Equal(t, k1, sv.Value)
}
func TestSettingsService_SyncOidcEnvToDatabase(t *testing.T) {
+ // Set env BEFORE creating service so config loader (if any) sees them
+ t.Setenv("OIDC_ENABLED", "false")
+ t.Setenv("OIDC_CLIENT_ID", "cid")
+ t.Setenv("OIDC_CLIENT_SECRET", "csec")
+ t.Setenv("OIDC_ISSUER_URL", "https://issuer.example")
+ t.Setenv("OIDC_SCOPES", "openid profile email")
+ t.Setenv("OIDC_ADMIN_CLAIM", "roles")
+ t.Setenv("OIDC_ADMIN_VALUE", "admin")
+
ctx := context.Background()
db := setupSettingsTestDB(t)
- cfg := &config.Config{
- OidcEnabled: true,
- OidcClientID: "cid",
- OidcClientSecret: "csec",
- OidcIssuerURL: "https://issuer.example",
- OidcScopes: "openid profile email",
- OidcAdminClaim: "roles",
- OidcAdminValue: "admin",
- }
- svc := NewSettingsService(db, cfg)
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+ // (Re)load settings after env prepared
vars, err := svc.SyncOidcEnvToDatabase(ctx)
- if err != nil {
- t.Fatalf("SyncOidcEnvToDatabase: %v", err)
- }
- if len(vars) == 0 {
- t.Fatalf("expected settings slice returned")
- }
+ require.NoError(t, err)
+ require.NotEmpty(t, vars)
- // Verify persisted values
var enabled models.SettingVariable
- if err := svc.db.WithContext(ctx).Where("key = ?", "authOidcEnabled").First(&enabled).Error; err != nil {
- t.Fatalf("query authOidcEnabled: %v", err)
- }
- if enabled.Value != "true" {
- t.Fatalf("authOidcEnabled not true: %q", enabled.Value)
- }
+ require.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "authOidcEnabled").First(&enabled).Error)
+ require.Equal(t, "true", enabled.Value)
var cfgVar models.SettingVariable
- if err := svc.db.WithContext(ctx).Where("key = ?", "authOidcConfig").First(&cfgVar).Error; err != nil {
- t.Fatalf("query authOidcConfig: %v", err)
- }
+ require.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "authOidcConfig").First(&cfgVar).Error)
+
var oc models.OidcConfig
- if err := json.Unmarshal([]byte(cfgVar.Value), &oc); err != nil {
- t.Fatalf("unmarshal oidc cfg: %v", err)
- }
- if oc.ClientID != "cid" || oc.ClientSecret != "csec" || oc.IssuerURL != "https://issuer.example" {
- t.Fatalf("oidc cfg mismatch: %+v", oc)
- }
- if oc.Scopes != "openid profile email" || oc.AdminClaim != "roles" || oc.AdminValue != "admin" {
- t.Fatalf("oidc cfg extras mismatch: %+v", oc)
- }
+ require.NoError(t, json.Unmarshal([]byte(cfgVar.Value), &oc))
+ require.Equal(t, "cid", oc.ClientID)
+ require.Equal(t, "csec", oc.ClientSecret)
+ require.Equal(t, "https://issuer.example", oc.IssuerURL)
+ require.Equal(t, "openid profile email", oc.Scopes)
+ require.Equal(t, "roles", oc.AdminClaim)
+ require.Equal(t, "admin", oc.AdminValue)
}
func TestSettingsService_UpdateSettings_MergeOidcSecret(t *testing.T) {
ctx := context.Background()
db := setupSettingsTestDB(t)
- svc := NewSettingsService(db, &config.Config{})
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
// Seed existing OIDC config with a secret
existing := models.OidcConfig{
@@ -225,12 +167,8 @@ func TestSettingsService_UpdateSettings_MergeOidcSecret(t *testing.T) {
IssuerURL: "https://issuer",
}
b, err := json.Marshal(existing)
- if err != nil {
- t.Fatalf("marshal existing oidc config: %v", err)
- }
- if err := svc.UpdateSetting(ctx, "authOidcConfig", string(b)); err != nil {
- t.Fatalf("seed: %v", err)
- }
+ require.NoError(t, err)
+ require.NoError(t, svc.UpdateSetting(ctx, "authOidcConfig", string(b)))
// Incoming update missing clientSecret should preserve existing one
incoming := models.OidcConfig{
@@ -238,30 +176,61 @@ func TestSettingsService_UpdateSettings_MergeOidcSecret(t *testing.T) {
IssuerURL: "https://issuer",
}
nb, err := json.Marshal(incoming)
- if err != nil {
- t.Fatalf("marshal incoming oidc config: %v", err)
- }
+ require.NoError(t, err)
s := string(nb)
updates := dto.UpdateSettingsDto{
AuthOidcConfig: &s,
}
- if _, err := svc.UpdateSettings(ctx, updates); err != nil {
- t.Fatalf("UpdateSettings: %v", err)
- }
+ _, err = svc.UpdateSettings(ctx, updates)
+ require.NoError(t, err)
var cfgVar models.SettingVariable
- if err := svc.db.WithContext(ctx).Where("key = ?", "authOidcConfig").First(&cfgVar).Error; err != nil {
- t.Fatalf("query: %v", err)
- }
+ require.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "authOidcConfig").First(&cfgVar).Error)
+
var merged models.OidcConfig
- if err := json.Unmarshal([]byte(cfgVar.Value), &merged); err != nil {
- t.Fatalf("unmarshal merged: %v", err)
- }
- if merged.ClientID != "new" {
- t.Fatalf("clientId not updated: %q", merged.ClientID)
- }
- if merged.ClientSecret != "keep-this" {
- t.Fatalf("clientSecret not preserved: %q", merged.ClientSecret)
- }
+ require.NoError(t, json.Unmarshal([]byte(cfgVar.Value), &merged))
+ require.Equal(t, "new", merged.ClientID)
+ require.Equal(t, "keep-this", merged.ClientSecret)
+}
+
+func TestSettingsService_LoadDatabaseSettings_ReloadsChanges(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ // Initially empty DB -> defaults (not persisted yet)
+ require.NoError(t, svc.EnsureDefaultSettings(ctx))
+
+ // Update a value directly in DB
+ require.NoError(t, svc.UpdateSetting(ctx, "projectsDirectory", "custom/projects"))
+
+ // Force reload
+ require.NoError(t, svc.LoadDatabaseSettings(ctx))
+
+ cfg := svc.GetSettingsConfig()
+ require.Equal(t, "custom/projects", cfg.ProjectsDirectory.Value)
+}
+
+func TestSettingsService_LoadDatabaseSettings_UIConfigurationDisabled_Env(t *testing.T) {
+ // Set env + disable flag BEFORE service init
+ t.Setenv("UI_CONFIGURATION_DISABLED", "true")
+ t.Setenv("PROJECTS_DIRECTORY", "env/projects")
+ t.Setenv("BASE_SERVER_URL", "https://env.example")
+
+ c := config.Load()
+ c.UIConfigurationDisabled = true
+
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ // Reload explicitly (NewSettingsService already did, but explicit for clarity)
+ require.NoError(t, svc.LoadDatabaseSettings(ctx))
+
+ cfg := svc.GetSettingsConfig()
+ require.Equal(t, "env/projects", cfg.ProjectsDirectory.Value)
+ require.Equal(t, "https://env.example", cfg.BaseServerURL.Value)
}
diff --git a/backend/internal/utils/string_util.go b/backend/internal/utils/string_util.go
index ecbcbb25d..9ffaf1436 100644
--- a/backend/internal/utils/string_util.go
+++ b/backend/internal/utils/string_util.go
@@ -4,6 +4,7 @@ import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
+ "regexp"
"strings"
)
@@ -25,6 +26,16 @@ func CamelCaseToSnakeCase(str string) string {
return strings.ToLower(result.String())
}
+var camelCaseToScreamingSnakeCaseRe = regexp.MustCompile(`([a-z0-9])([A-Z])`)
+
+func CamelCaseToScreamingSnakeCase(s string) string {
+ // Insert underscores before uppercase letters (except the first one)
+ stringValue := camelCaseToScreamingSnakeCaseRe.ReplaceAllString(s, `${1}_${2}`)
+
+ // Convert to uppercase
+ return strings.ToUpper(stringValue)
+}
+
func GenerateRandomString(length int) string {
bytes := make([]byte, length)
if _, err := rand.Read(bytes); err != nil {
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 361079dde..34fab2d27 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -19,9 +19,11 @@ services:
# Anonymous volumes for node_modules to avoid conflicts
- /app/node_modules
- /app/frontend/node_modules
+ env_file:
+ - .env
environment:
- NODE_ENV=development
- - DEV_BACKEND_URL=http://backend:3552
+ - DEV_BACKEND_URL=${DEV_BACKEND_URL:-http://backend:3552}
depends_on:
- backend
networks:
@@ -53,14 +55,12 @@ services:
- /var/run/docker.sock:/var/run/docker.sock
# Persistent data storage
- arcane-dev-data:/app/data
+ env_file:
+ - .env
environment:
- - GIN_MODE=debug
- - PORT=3552
- - ENVIRONMENT=development
- - PUID=1000
- - PGID=1000
- - ENCRYPTION_KEY=dev-encryption-key-replace-in-production
- - JWT_SECRET=dev-jwt-secret-replace-in-production
+ - PORT=${PORT:-3552}
+ - PUID=${PUID:-1000}
+ - PGID=${PGID:-1000}
working_dir: /app
networks:
- arcane-dev
@@ -82,12 +82,12 @@ services:
container_name: arcane-agent
ports:
- '3553:3553'
+ env_file:
+ - .env
environment:
- - GIN_MODE=debug
- - ENVIRONMENT=development
- PORT=3553
- AGENT_MODE=true
- - AGENT_BOOTSTRAP_TOKEN=development-bootstrap-token
+ - AGENT_BOOTSTRAP_TOKEN=${AGENT_BOOTSTRAP_TOKEN:-development-bootstrap-token}
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- agent-dev-data:/app/data
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index c5e3d9dab..bf5832be1 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -1060,5 +1060,7 @@
"polling_weekly_description": "Check for new images every 10080 minutes",
"use_custom_polling_value": "Use a custom polling value between 5-10080 minutes",
"custom_polling_interval": "Custom Polling Interval (minutes)",
- "build_cache": "Build Cache"
+ "build_cache": "Build Cache",
+ "ui_config_disabled_title": "UI configuration is disabled",
+ "ui_config_disabled_description": "Settings must be managed via environment variables."
}
diff --git a/frontend/src/lib/components/sidebar/sidebar-user.svelte b/frontend/src/lib/components/sidebar/sidebar-user.svelte
index c7ce6f128..39c6fe88f 100644
--- a/frontend/src/lib/components/sidebar/sidebar-user.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar-user.svelte
@@ -83,6 +83,8 @@
sideOffset={12}
>
<div
+ role="group"
+ tabindex="-1"
onmouseenter={() => {
if (sidebar.state === 'collapsed') {
sidebar.setHovered(true);
@@ -93,55 +95,55 @@
}}
>
<DropdownMenu.Label class="px-3 pb-2 pt-2 font-normal">
- <div class="flex items-center gap-3 text-left text-sm">
- <Avatar.Root class="size-8 shrink-0 rounded-lg">
- {#if $settingsStore.enableGravatar}
- {#await getGravatarUrl(user?.email)}
- <Avatar.Image src="/img/profile.jpg" alt={user.displayName} />
- {:then url}
- <Avatar.Image src={url || '/img/profile.jpg'} alt={user.displayName} />
- {:catch _}
+ <div class="flex items-center gap-3 text-left text-sm">
+ <Avatar.Root class="size-8 shrink-0 rounded-lg">
+ {#if $settingsStore.enableGravatar}
+ {#await getGravatarUrl(user?.email)}
+ <Avatar.Image src="/img/profile.jpg" alt={user.displayName} />
+ {:then url}
+ <Avatar.Image src={url || '/img/profile.jpg'} alt={user.displayName} />
+ {:catch _}
+ <Avatar.Image src="/img/profile.jpg" alt={user.displayName} />
+ {/await}
+ {:else}
<Avatar.Image src="/img/profile.jpg" alt={user.displayName} />
- {/await}
- {:else}
- <Avatar.Image src="/img/profile.jpg" alt={user.displayName} />
- {/if}
- <Avatar.Fallback
- class="from-primary/20 to-primary/10 text-primary border-primary/20 rounded-lg border bg-gradient-to-br"
- >
- {user.displayName?.charAt(0).toUpperCase()}
- </Avatar.Fallback>
- </Avatar.Root>
- <div class="grid min-w-0 flex-1 text-left text-sm leading-tight">
- <span class="truncate font-medium">{user.displayName}</span>
- <span class="truncate text-xs">{user.email}</span>
+ {/if}
+ <Avatar.Fallback
+ class="from-primary/20 to-primary/10 text-primary border-primary/20 rounded-lg border bg-gradient-to-br"
+ >
+ {user.displayName?.charAt(0).toUpperCase()}
+ </Avatar.Fallback>
+ </Avatar.Root>
+ <div class="grid min-w-0 flex-1 text-left text-sm leading-tight">
+ <span class="truncate font-medium">{user.displayName}</span>
+ <span class="truncate text-xs">{user.email}</span>
+ </div>
</div>
- </div>
- </DropdownMenu.Label>
- <DropdownMenu.Separator />
+ </DropdownMenu.Label>
+ <DropdownMenu.Separator />
- <SidebarLocalePicker />
+ <SidebarLocalePicker />
- <DropdownMenu.Group class="px-3 pb-2">
- <Button.Root
- variant="ghost"
- class={cn(
- 'text-muted-foreground flex w-full items-center rounded-xl text-sm font-medium transition-all duration-200 hover:bg-gradient-to-br',
- 'h-11 justify-start gap-3 px-3 py-2.5'
- )}
- title={m.common_toggle_theme()}
- onclick={toggleMode}
- >
- <div class="group-hover:bg-muted-foreground/10 rounded-lg bg-transparent p-1 transition-colors duration-200">
- {#if mode.current === 'dark'}
- <Sun size={16} class="transition-transform duration-200" />
- {:else}
- <Moon size={16} class="transition-transform duration-200" />
- {/if}
- </div>
- <span class="font-medium">{m.common_toggle_theme()}</span>
- </Button.Root>
- </DropdownMenu.Group>
+ <DropdownMenu.Group class="px-3 pb-2">
+ <Button.Root
+ variant="ghost"
+ class={cn(
+ 'text-muted-foreground flex w-full items-center rounded-xl text-sm font-medium transition-all duration-200 hover:bg-gradient-to-br',
+ 'h-11 justify-start gap-3 px-3 py-2.5'
+ )}
+ title={m.common_toggle_theme()}
+ onclick={toggleMode}
+ >
+ <div class="group-hover:bg-muted-foreground/10 rounded-lg bg-transparent p-1 transition-colors duration-200">
+ {#if mode.current === 'dark'}
+ <Sun size={16} class="transition-transform duration-200" />
+ {:else}
+ <Moon size={16} class="transition-transform duration-200" />
+ {/if}
+ </div>
+ <span class="font-medium">{m.common_toggle_theme()}</span>
+ </Button.Root>
+ </DropdownMenu.Group>
</div>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/lib/components/ui-config-disabled-tag.svelte b/frontend/src/lib/components/ui-config-disabled-tag.svelte
new file mode 100644
index 000000000..c6e952e5a
--- /dev/null
+++ b/frontend/src/lib/components/ui-config-disabled-tag.svelte
@@ -0,0 +1,27 @@
+<script lang="ts">
+ import settingsStore from '$lib/stores/config-store';
+ import { m } from '$lib/paraglide/messages';
+ import LockIcon from '@lucide/svelte/icons/lock';
+ import * as Tooltip from '$lib/components/ui/tooltip';
+
+ const active = $derived.by(() => $settingsStore.uiConfigDisabled);
+</script>
+
+{#if active}
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <span
+ class="inline-flex items-center gap-1.5 rounded-full bg-amber-100 px-2.5 py-1 text-xs font-medium text-amber-800 ring-1 ring-amber-200 dark:bg-amber-900/50 dark:text-amber-200 dark:ring-amber-800"
+ >
+ <LockIcon class="size-3" />
+ Read-only
+ </span>
+ </Tooltip.Trigger>
+ <Tooltip.Content side="bottom" class="max-w-xs">
+ <div class="space-y-1">
+ <p class="font-medium">{m.ui_config_disabled_title()}</p>
+ <p class="text-xs opacity-90">{m.ui_config_disabled_description()}</p>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Root>
+{/if}
diff --git a/frontend/src/lib/services/api/settings-api-service.ts b/frontend/src/lib/services/api/settings-api-service.ts
index c56333c13..676373f38 100644
--- a/frontend/src/lib/services/api/settings-api-service.ts
+++ b/frontend/src/lib/services/api/settings-api-service.ts
@@ -4,14 +4,12 @@ import type { Settings, SettingRawResponse, OidcStatusInfo } from '$lib/types/se
export default class SettingsAPIService extends BaseAPIService {
async getSettings(): Promise<Settings> {
const response = await this.api.get('/settings');
- const parsed = this.parseConfigList(response.data.settings);
- return parsed;
+ return this.parseConfigList(response.data);
}
async getPublicSettings(): Promise<Settings> {
const response = await this.api.get('/settings/public');
- const parsed = this.parseConfigList(response.data.settings);
- return parsed;
+ return this.parseConfigList(response.data);
}
async updateSettings(settings: Settings) {
diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.ts
index 9f47dde0d..e0dc61787 100644
--- a/frontend/src/lib/types/settings.type.ts
+++ b/frontend/src/lib/types/settings.type.ts
@@ -16,6 +16,7 @@ export type Settings = {
dockerPruneMode: 'all' | 'dangling';
baseServerUrl: string;
enableGravatar: boolean;
+ uiConfigDisabled: boolean;
authLocalEnabled: boolean;
authOidcEnabled: boolean;
diff --git a/frontend/src/routes/settings/+layout.svelte b/frontend/src/routes/settings/+layout.svelte
index 6c7a2f804..bca0026d4 100644
--- a/frontend/src/routes/settings/+layout.svelte
+++ b/frontend/src/routes/settings/+layout.svelte
@@ -10,6 +10,7 @@
import RotateCcwIcon from '@lucide/svelte/icons/rotate-ccw';
import { useSidebar } from '$lib/components/ui/sidebar/context.svelte.js';
import { m } from '$lib/paraglide/messages';
+ import settingsStore from '$lib/stores/config-store';
interface Props {
children: import('svelte').Snippet;
@@ -22,6 +23,7 @@
let currentPageName = $derived(page.url.pathname.split('/').pop() || 'settings');
const sidebar = useSidebar();
+ const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);
// Calculate left position based on sidebar state to match sidebar spacing system
// Uses the same CSS variables and spacing as the sidebar component
@@ -116,38 +118,40 @@
<!-- Save Section - Desktop only -->
<div class="hidden shrink-0 items-center gap-3 sm:flex">
- {#if formState.hasChanges}
- <span class="text-xs text-orange-600 dark:text-orange-400"> Unsaved changes </span>
- {:else if !formState.hasChanges && formState.saveFunction}
- <span class="text-xs text-green-600 dark:text-green-400"> All changes saved </span>
- {/if}
+ {#if !isReadOnly}
+ {#if formState.hasChanges}
+ <span class="text-xs text-orange-600 dark:text-orange-400"> Unsaved changes </span>
+ {:else if !formState.hasChanges && formState.saveFunction}
+ <span class="text-xs text-green-600 dark:text-green-400"> All changes saved </span>
+ {/if}
+
+ {#if formState.hasChanges && formState.resetFunction}
+ <Button
+ variant="outline"
+ size="sm"
+ onclick={() => formState.resetFunction && formState.resetFunction()}
+ disabled={formState.isLoading}
+ class="gap-2"
+ >
+ {m.common_reset()}
+ </Button>
+ {/if}
- {#if formState.hasChanges && formState.resetFunction}
<Button
- variant="outline"
+ onclick={handleSave}
+ disabled={formState.isLoading || !formState.hasChanges || !formState.saveFunction}
size="sm"
- onclick={() => formState.resetFunction && formState.resetFunction()}
- disabled={formState.isLoading}
- class="gap-2"
+ class="min-w-[80px] gap-2"
>
- {m.common_reset()}
- </Button>
- {/if}
-
- <Button
- onclick={handleSave}
- disabled={formState.isLoading || !formState.hasChanges || !formState.saveFunction}
- size="sm"
- class="min-w-[80px] gap-2"
- >
- {#if formState.isLoading}
- <div class="border-background size-4 animate-spin rounded-full border-2 border-t-transparent"></div>
- {m.common_saving()}
- {:else}
- <SaveIcon class="size-4" />
+ {#if formState.isLoading}
+ <div class="border-background size-4 animate-spin rounded-full border-2 border-t-transparent"></div>
+ {m.common_saving()}
+ {:else}
+ <SaveIcon class="size-4" />
{m.common_save()}
{/if}
</Button>
+ {/if}
</div>
</div>
</div>
@@ -161,7 +165,7 @@
</div>
<!-- Mobile Floating Action Buttons -->
-{#if isSubPage}
+{#if isSubPage && !isReadOnly}
<div class="fixed bottom-4 right-4 z-50 flex flex-col gap-3 sm:hidden">
{#if formState.hasChanges && formState.resetFunction}
<Button
diff --git a/frontend/src/routes/settings/+page.svelte b/frontend/src/routes/settings/+page.svelte
index 36c2ac50b..48c13dd29 100644
--- a/frontend/src/routes/settings/+page.svelte
+++ b/frontend/src/routes/settings/+page.svelte
@@ -13,6 +13,7 @@
import type { Settings } from '$lib/types/settings.type';
import settingsStore from '$lib/stores/config-store';
import { settingsAPI } from '$lib/services/api';
+ import UiConfigDisabledTag from '$lib/components/ui-config-disabled-tag.svelte';
interface SettingMeta {
key: string;
@@ -268,14 +269,19 @@
<div class="bg-muted/40 pointer-events-none absolute -bottom-10 -left-10 size-40 rounded-full blur-3xl"></div>
<div class="relative">
<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
- <div class="flex items-start gap-3 sm:gap-4">
+ <div class="flex items-start gap-3 sm:gap-4 w-full">
<div
class="bg-primary/10 text-primary ring-primary/20 flex size-8 shrink-0 items-center justify-center rounded-lg ring-1 sm:size-10"
>
<SettingsIcon class="size-4 sm:size-5" />
</div>
- <div class="min-w-0">
- <h1 class="text-xl font-bold tracking-tight sm:text-2xl">{m.sidebar_settings()}</h1>
+ <div class="min-w-0 flex-1">
+ <div class="flex items-start justify-between gap-3">
+ <h1 class="text-xl font-bold tracking-tight sm:text-2xl min-w-0">{m.sidebar_settings()}</h1>
+ <div class="shrink-0">
+ <UiConfigDisabledTag />
+ </div>
+ </div>
<p class="text-muted-foreground mt-1 text-sm sm:text-base">Configure and customize your Arcane experience</p>
</div>
</div>
diff --git a/frontend/src/routes/settings/docker/+page.svelte b/frontend/src/routes/settings/docker/+page.svelte
index b8ea89c0f..b8a738271 100644
--- a/frontend/src/routes/settings/docker/+page.svelte
+++ b/frontend/src/routes/settings/docker/+page.svelte
@@ -2,6 +2,7 @@
import type { Settings } from '$lib/types/settings.type';
import settingsStore from '$lib/stores/config-store';
import { settingsAPI } from '$lib/services/api';
+ import UiConfigDisabledTag from '$lib/components/ui-config-disabled-tag.svelte';
import DockerSettingsForm from '../forms/docker-settings-form.svelte';
import BoxesIcon from '@lucide/svelte/icons/boxes';
import { m } from '$lib/paraglide/messages';
@@ -11,6 +12,8 @@
let currentSettings = $state<Settings>(data.settings);
let hasChanges = $state(false);
let isLoading = $state(false);
+
+ const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);
const formState = getContext('settingsFormState') as any;
@@ -42,17 +45,22 @@
>
<div class="bg-primary/10 pointer-events-none absolute -right-10 -top-10 size-40 rounded-full blur-3xl"></div>
<div class="bg-muted/40 pointer-events-none absolute -bottom-10 -left-10 size-40 rounded-full blur-3xl"></div>
- <div class="relative flex items-start justify-between gap-3 sm:gap-4">
- <div class="flex min-w-0 items-start gap-3 sm:gap-4">
- <div
- class="bg-primary/10 text-primary ring-primary/20 flex size-8 shrink-0 items-center justify-center rounded-lg ring-1 sm:size-10"
- >
- <BoxesIcon class="size-4 sm:size-5" />
- </div>
- <div class="min-w-0">
- <h1 class="settings-title text-xl sm:text-3xl">{m.docker_title()}</h1>
- <p class="settings-description text-sm sm:text-base">{m.docker_description()}</p>
+ <div class="relative flex items-start gap-3 sm:gap-4">
+ <div
+ class="bg-primary/10 text-primary ring-primary/20 flex size-8 shrink-0 items-center justify-center rounded-lg ring-1 sm:size-10"
+ >
+ <BoxesIcon class="size-4 sm:size-5" />
+ </div>
+ <div class="min-w-0 flex-1">
+ <div class="flex items-start justify-between gap-3">
+ <h1 class="settings-title text-xl sm:text-3xl min-w-0">{m.docker_title()}</h1>
+ {#if isReadOnly}
+ <div class="shrink-0">
+ <UiConfigDisabledTag />
+ </div>
+ {/if}
</div>
+ <p class="text-muted-foreground mt-1 text-sm sm:text-base">{m.docker_description()}</p>
</div>
</div>
</div>
@@ -61,3 +69,4 @@
<DockerSettingsForm settings={currentSettings} callback={updateSettingsConfig} bind:hasChanges bind:isLoading />
</div>
</div>
+
diff --git a/frontend/src/routes/settings/forms/docker-settings-form.svelte b/frontend/src/routes/settings/forms/docker-settings-form.svelte
index 854c27e60..c3cf524e7 100644
--- a/frontend/src/routes/settings/forms/docker-settings-form.svelte
+++ b/frontend/src/routes/settings/forms/docker-settings-form.svelte
@@ -14,6 +14,7 @@
import RefreshCwIcon from '@lucide/svelte/icons/refresh-cw';
import TrashIcon from '@lucide/svelte/icons/trash';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import settingsStore from '$lib/stores/config-store';
let {
callback,
@@ -28,6 +29,7 @@
} = $props();
let pruneMode = $state(settings.dockerPruneMode);
+ const uiConfigDisabled = $state($settingsStore.uiConfigDisabled);
type PollingIntervalMode = 'hourly' | 'daily' | 'weekly' | 'custom';
@@ -151,126 +153,128 @@
});
</script>
-<div class="space-y-4 sm:space-y-6">
- <!-- Image Polling Card -->
- <Card.Root class="overflow-hidden">
- <Card.Header class="py-4! bg-muted/20 border-b">
- <div class="flex items-center gap-3">
- <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
- <ActivityIcon class="size-4" />
- </div>
- <div>
- <Card.Title class="text-base">Image Polling</Card.Title>
- <Card.Description class="text-xs">Configure automatic image update checking</Card.Description>
- </div>
- </div>
- </Card.Header>
- <Card.Content class="px-3 py-4 sm:px-6">
- <div class="space-y-3">
- <SwitchWithLabel
- id="pollingEnabled"
- label={m.docker_enable_polling_label()}
- description={m.docker_enable_polling_description()}
- bind:checked={$formInputs.pollingEnabled.value}
- />
-
- {#if $formInputs.pollingEnabled.value}
- <div class="border-primary/20 space-y-3 border-l-2 pl-3">
- <SelectWithLabel
- id="pollingIntervalMode"
- name="pollingIntervalMode"
- bind:value={pollingIntervalMode}
- label={m.docker_polling_interval_label()}
- placeholder="Select interval"
- options={imagePollingOptions.map(({ value, label, description }) => ({ value, label, description }))}
- />
-
- {#if pollingIntervalMode === 'custom'}
- <TextInputWithLabel
- bind:value={$formInputs.pollingInterval.value}
- label={m.custom_polling_interval()}
- placeholder={m.docker_polling_interval_placeholder()}
- helpText={m.docker_polling_interval_description()}
- type="number"
- />
- {/if}
-
- {#if $formInputs.pollingInterval.value < 30}
- <Alert.Root variant="warning">
- <ZapIcon class="size-4" />
- <Alert.Title>{m.docker_rate_limit_warning_title()}</Alert.Title>
- <Alert.Description>{m.docker_rate_limit_warning_description()}</Alert.Description>
- </Alert.Root>
- {/if}
- </div>
- {/if}
- </div>
- </Card.Content>
- </Card.Root>
-
- <!-- Auto Update Card -->
- {#if $formInputs.pollingEnabled.value}
+<fieldset disabled={uiConfigDisabled} class="relative">
+ <div class="space-y-4 sm:space-y-6">
+ <!-- Image Polling Card -->
<Card.Root class="overflow-hidden">
<Card.Header class="py-4! bg-muted/20 border-b">
<div class="flex items-center gap-3">
<div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
- <RefreshCwIcon class="size-4" />
+ <ActivityIcon class="size-4" />
</div>
<div>
- <Card.Title class="text-base">Auto Updates</Card.Title>
- <Card.Description class="text-xs">Automatically update containers when new images are available</Card.Description>
+ <Card.Title class="text-base">Image Polling</Card.Title>
+ <Card.Description class="text-xs">Configure automatic image update checking</Card.Description>
</div>
</div>
</Card.Header>
<Card.Content class="px-3 py-4 sm:px-6">
<div class="space-y-3">
<SwitchWithLabel
- id="autoUpdateSwitch"
- label={m.docker_auto_update_label()}
- description={m.docker_auto_update_description()}
- bind:checked={$formInputs.autoUpdate.value}
+ id="pollingEnabled"
+ label={m.docker_enable_polling_label()}
+ description={m.docker_enable_polling_description()}
+ bind:checked={$formInputs.pollingEnabled.value}
/>
- {#if $formInputs.autoUpdate.value}
- <div class="border-primary/20 border-l-2 pl-3">
- <TextInputWithLabel
- bind:value={$formInputs.autoUpdateInterval.value}
- label={m.docker_auto_update_interval_label()}
- placeholder={m.docker_auto_update_interval_placeholder()}
- helpText={m.docker_auto_update_interval_description()}
- type="number"
+ {#if $formInputs.pollingEnabled.value}
+ <div class="border-primary/20 space-y-3 border-l-2 pl-3">
+ <SelectWithLabel
+ id="pollingIntervalMode"
+ name="pollingIntervalMode"
+ bind:value={pollingIntervalMode}
+ label={m.docker_polling_interval_label()}
+ placeholder="Select interval"
+ options={imagePollingOptions.map(({ value, label, description }) => ({ value, label, description }))}
/>
+
+ {#if pollingIntervalMode === 'custom'}
+ <TextInputWithLabel
+ bind:value={$formInputs.pollingInterval.value}
+ label={m.custom_polling_interval()}
+ placeholder={m.docker_polling_interval_placeholder()}
+ helpText={m.docker_polling_interval_description()}
+ type="number"
+ />
+ {/if}
+
+ {#if $formInputs.pollingInterval.value < 30}
+ <Alert.Root variant="warning">
+ <ZapIcon class="size-4" />
+ <Alert.Title>{m.docker_rate_limit_warning_title()}</Alert.Title>
+ <Alert.Description>{m.docker_rate_limit_warning_description()}</Alert.Description>
+ </Alert.Root>
+ {/if}
</div>
{/if}
</div>
</Card.Content>
</Card.Root>
- {/if}
- <!-- Cleanup Settings Card -->
- <Card.Root class="overflow-hidden">
- <Card.Header class="py-4! bg-muted/20 border-b">
- <div class="flex items-center gap-3">
- <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
- <TrashIcon class="size-4" />
- </div>
- <div>
- <Card.Title class="text-base">Cleanup Settings</Card.Title>
- <Card.Description class="text-xs">Configure how Docker images are pruned</Card.Description>
+ {#if $formInputs.pollingEnabled.value}
+ <!-- Auto Update Card -->
+ <Card.Root class="overflow-hidden">
+ <Card.Header class="py-4! bg-muted/20 border-b">
+ <div class="flex items-center gap-3">
+ <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
+ <RefreshCwIcon class="size-4" />
+ </div>
+ <div>
+ <Card.Title class="text-base">Auto Updates</Card.Title>
+ <Card.Description class="text-xs">Automatically update containers when new images are available</Card.Description>
+ </div>
+ </div>
+ </Card.Header>
+ <Card.Content class="px-3 py-4 sm:px-6">
+ <div class="space-y-3">
+ <SwitchWithLabel
+ id="autoUpdateSwitch"
+ label={m.docker_auto_update_label()}
+ description={m.docker_auto_update_description()}
+ bind:checked={$formInputs.autoUpdate.value}
+ />
+
+ {#if $formInputs.autoUpdate.value}
+ <div class="border-primary/20 border-l-2 pl-3">
+ <TextInputWithLabel
+ bind:value={$formInputs.autoUpdateInterval.value}
+ label={m.docker_auto_update_interval_label()}
+ placeholder={m.docker_auto_update_interval_placeholder()}
+ helpText={m.docker_auto_update_interval_description()}
+ type="number"
+ />
+ </div>
+ {/if}
+ </div>
+ </Card.Content>
+ </Card.Root>
+ {/if}
+
+ <!-- Cleanup Settings Card -->
+ <Card.Root class="overflow-hidden">
+ <Card.Header class="py-4! bg-muted/20 border-b">
+ <div class="flex items-center gap-3">
+ <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
+ <TrashIcon class="size-4" />
+ </div>
+ <div>
+ <Card.Title class="text-base">Cleanup Settings</Card.Title>
+ <Card.Description class="text-xs">Configure how Docker images are pruned</Card.Description>
+ </div>
</div>
- </div>
- </Card.Header>
- <Card.Content class="px-3 py-4 sm:px-6">
- <SelectWithLabel
- id="dockerPruneMode"
- name="pruneMode"
- bind:value={$formInputs.dockerPruneMode.value}
- label={m.docker_prune_action_label()}
- description={pruneModeDescription}
- placeholder={m.docker_prune_placeholder()}
- options={pruneModeOptions}
- onValueChange={(v) => (pruneMode = v as 'all' | 'dangling')}
- />
- </Card.Content>
- </Card.Root>
-</div>
+ </Card.Header>
+ <Card.Content class="px-3 py-4 sm:px-6">
+ <SelectWithLabel
+ id="dockerPruneMode"
+ name="pruneMode"
+ bind:value={$formInputs.dockerPruneMode.value}
+ label={m.docker_prune_action_label()}
+ description={pruneModeDescription}
+ placeholder={m.docker_prune_placeholder()}
+ options={pruneModeOptions}
+ onValueChange={(v) => (pruneMode = v as 'all' | 'dangling')}
+ />
+ </Card.Content>
+ </Card.Root>
+ </div>
+</fieldset>
diff --git a/frontend/src/routes/settings/forms/general-settings-form.svelte b/frontend/src/routes/settings/forms/general-settings-form.svelte
index 68a5aa976..e3447cbe9 100644
--- a/frontend/src/routes/settings/forms/general-settings-form.svelte
+++ b/frontend/src/routes/settings/forms/general-settings-form.svelte
@@ -10,6 +10,7 @@
import FolderIcon from '@lucide/svelte/icons/folder';
import UserIcon from '@lucide/svelte/icons/user';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import settingsStore from '$lib/stores/config-store';
let {
settings,
@@ -23,6 +24,8 @@
isLoading: boolean;
} = $props();
+ const uiConfigDisabled = $state($settingsStore.uiConfigDisabled);
+
const formSchema = z.object({
projectsDirectory: z.string().min(1, m.general_projects_directory_required()),
baseServerUrl: z.string().min(1, m.general_base_url_required()),
@@ -74,61 +77,63 @@
});
</script>
-<div class="space-y-4 sm:space-y-6">
- <!-- Projects Configuration Card -->
- <Card.Root class="overflow-hidden">
- <Card.Header class="py-4! bg-muted/20 border-b">
- <div class="flex items-center gap-3">
- <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
- <FolderIcon class="size-4" />
- </div>
- <div>
- <Card.Title class="text-base">{m.general_projects_heading()}</Card.Title>
- <Card.Description class="text-xs">{m.general_projects_description()}</Card.Description>
+<fieldset disabled={uiConfigDisabled} class="relative">
+ <div class="space-y-4 sm:space-y-6">
+ <!-- Projects Configuration Card -->
+ <Card.Root class="relative overflow-hidden">
+ <Card.Header class="py-4! bg-muted/20 border-b">
+ <div class="flex items-center gap-3">
+ <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
+ <FolderIcon class="size-4" />
+ </div>
+ <div>
+ <Card.Title class="text-base">{m.general_projects_heading()}</Card.Title>
+ <Card.Description class="text-xs">{m.general_projects_description()}</Card.Description>
+ </div>
</div>
- </div>
- </Card.Header>
- <Card.Content class="px-3 py-4 sm:px-6">
- <div class="space-y-3">
- <TextInputWithLabel
- bind:value={$formInputs.projectsDirectory.value}
- label={m.general_projects_directory_label()}
- placeholder={m.general_projects_directory_placeholder()}
- helpText={m.general_projects_directory_help()}
- type="text"
- />
+ </Card.Header>
+ <Card.Content class="px-3 py-4 sm:px-6">
+ <div class="space-y-3">
+ <TextInputWithLabel
+ bind:value={$formInputs.projectsDirectory.value}
+ label={m.general_projects_directory_label()}
+ placeholder={m.general_projects_directory_placeholder()}
+ helpText={m.general_projects_directory_help()}
+ type="text"
+ />
- <TextInputWithLabel
- bind:value={$formInputs.baseServerUrl.value}
- label={m.general_base_url_label()}
- placeholder={m.general_base_url_placeholder()}
- helpText={m.general_base_url_help()}
- type="text"
- />
- </div>
- </Card.Content>
- </Card.Root>
-
- <!-- User Preferences Card -->
- <Card.Root class="overflow-hidden">
- <Card.Header class="py-4! bg-muted/20 border-b">
- <div class="flex items-center gap-3">
- <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
- <UserIcon class="size-4" />
+ <TextInputWithLabel
+ bind:value={$formInputs.baseServerUrl.value}
+ label={m.general_base_url_label()}
+ placeholder={m.general_base_url_placeholder()}
+ helpText={m.general_base_url_help()}
+ type="text"
+ />
</div>
- <div>
- <Card.Title class="text-base">{m.general_user_avatars_heading()}</Card.Title>
- <Card.Description class="text-xs">{m.general_user_avatars_description()}</Card.Description>
+ </Card.Content>
+ </Card.Root>
+
+ <!-- User Preferences Card -->
+ <Card.Root class="relative overflow-hidden">
+ <Card.Header class="py-4! bg-muted/20 border-b">
+ <div class="flex items-center gap-3">
+ <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
+ <UserIcon class="size-4" />
+ </div>
+ <div>
+ <Card.Title class="text-base">{m.general_user_avatars_heading()}</Card.Title>
+ <Card.Description class="text-xs">{m.general_user_avatars_description()}</Card.Description>
+ </div>
</div>
- </div>
- </Card.Header>
- <Card.Content class="px-3 py-4 sm:px-6">
- <SwitchWithLabel
- id="enableGravatar"
- label={m.general_enable_gravatar_label()}
- description={m.general_enable_gravatar_description()}
- bind:checked={$formInputs.enableGravatar.value}
- />
- </Card.Content>
- </Card.Root>
-</div>
+ </Card.Header>
+ <Card.Content class="px-3 py-4 sm:px-6">
+ <SwitchWithLabel
+ id="enableGravatar"
+ label={m.general_enable_gravatar_label()}
+ description={m.general_enable_gravatar_description()}
+ bind:checked={$formInputs.enableGravatar.value}
+ />
+ </Card.Content>
+ </Card.Root>
+ </div>
+</fieldset>
diff --git a/frontend/src/routes/settings/forms/security-settings-form.svelte b/frontend/src/routes/settings/forms/security-settings-form.svelte
index 0862a8917..2bbcf53a6 100644
--- a/frontend/src/routes/settings/forms/security-settings-form.svelte
+++ b/frontend/src/routes/settings/forms/security-settings-form.svelte
@@ -15,6 +15,7 @@
import ClockIcon from '@lucide/svelte/icons/clock';
import KeyIcon from '@lucide/svelte/icons/key';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import settingsStore from '$lib/stores/config-store';
let {
settings,
@@ -198,155 +199,159 @@
isLoading = false;
}
}
+
+ const uiConfigDisabled = $state($settingsStore.uiConfigDisabled);
</script>
-<div class="space-y-4 sm:space-y-6">
- <!-- Authentication Methods Card -->
- <Card.Root class="overflow-hidden">
- <Card.Header class="py-4! bg-muted/20 border-b">
- <div class="flex items-center gap-3">
- <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
- <LockIcon class="size-4" />
- </div>
- <div>
- <Card.Title class="text-base">{m.security_authentication_heading()}</Card.Title>
- <Card.Description class="text-xs">Configure login methods for your application</Card.Description>
+<fieldset disabled={uiConfigDisabled} class="relative">
+ <div class="space-y-4 sm:space-y-6">
+ <!-- Authentication Methods Card -->
+ <Card.Root class="overflow-hidden">
+ <Card.Header class="py-4! bg-muted/20 border-b">
+ <div class="flex items-center gap-3">
+ <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
+ <LockIcon class="size-4" />
+ </div>
+ <div>
+ <Card.Title class="text-base">{m.security_authentication_heading()}</Card.Title>
+ <Card.Description class="text-xs">Configure login methods for your application</Card.Description>
+ </div>
</div>
- </div>
- </Card.Header>
- <Card.Content class="px-3 py-4 sm:px-6">
- <div class="space-y-3">
- <SwitchWithLabel
- id="localAuthSwitch"
- label={m.security_local_auth_label()}
- description={m.security_local_auth_description()}
- bind:checked={$formInputs.authLocalEnabled.value}
- onCheckedChange={handleLocalSwitchChange}
- />
-
- <div class="space-y-2">
+ </Card.Header>
+ <Card.Content class="px-3 py-4 sm:px-6">
+ <div class="space-y-3">
<SwitchWithLabel
- id="oidcAuthSwitch"
- label={m.security_oidc_auth_label()}
- description={oidcStatus.envForced ? m.security_oidc_auth_description_forced() : m.security_oidc_auth_description()}
- disabled={oidcStatus.envForced}
- bind:checked={$formInputs.authOidcEnabled.value}
- onCheckedChange={handleOidcSwitchChange}
+ id="localAuthSwitch"
+ label={m.security_local_auth_label()}
+ description={m.security_local_auth_description()}
+ bind:checked={$formInputs.authLocalEnabled.value}
+ onCheckedChange={handleLocalSwitchChange}
/>
- {#if isOidcActive()}
- <div class="pl-8 sm:pl-11">
- {#if oidcStatus.envForced}
- {#if !oidcStatus.envConfigured}
- <Button variant="link" class="text-destructive h-auto p-0 text-xs hover:underline" onclick={openOidcDialog}>
- {m.security_server_forces_oidc_missing_env()}
- </Button>
+ <div class="space-y-2">
+ <SwitchWithLabel
+ id="oidcAuthSwitch"
+ label={m.security_oidc_auth_label()}
+ description={oidcStatus.envForced ? m.security_oidc_auth_description_forced() : m.security_oidc_auth_description()}
+ disabled={oidcStatus.envForced}
+ bind:checked={$formInputs.authOidcEnabled.value}
+ onCheckedChange={handleOidcSwitchChange}
+ />
+
+ {#if isOidcActive()}
+ <div class="pl-8 sm:pl-11">
+ {#if oidcStatus.envForced}
+ {#if !oidcStatus.envConfigured}
+ <Button variant="link" class="text-destructive h-auto p-0 text-xs hover:underline" onclick={openOidcDialog}>
+ {m.security_server_forces_oidc_missing_env()}
+ </Button>
+ {:else}
+ <Button variant="link" class="h-auto p-0 text-xs text-sky-600 hover:underline" onclick={openOidcDialog}>
+ {m.security_oidc_configured_forced_view()}
+ </Button>
+ {/if}
{:else}
<Button variant="link" class="h-auto p-0 text-xs text-sky-600 hover:underline" onclick={openOidcDialog}>
- {m.security_oidc_configured_forced_view()}
+ {m.security_manage_oidc_config()}
</Button>
{/if}
- {:else}
- <Button variant="link" class="h-auto p-0 text-xs text-sky-600 hover:underline" onclick={openOidcDialog}>
- {m.security_manage_oidc_config()}
- </Button>
- {/if}
- </div>
- {/if}
- </div>
- </div>
- </Card.Content>
- </Card.Root>
-
- <!-- Session Settings Card -->
- <Card.Root class="overflow-hidden">
- <Card.Header class="py-4! bg-muted/20 border-b">
- <div class="flex items-center gap-3">
- <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
- <ClockIcon class="size-4" />
+ </div>
+ {/if}
+ </div>
</div>
- <div>
- <Card.Title class="text-base">{m.security_session_heading()}</Card.Title>
- <Card.Description class="text-xs">Configure session timeout and duration</Card.Description>
+ </Card.Content>
+ </Card.Root>
+
+ <!-- Session Settings Card -->
+ <Card.Root class="overflow-hidden">
+ <Card.Header class="py-4! bg-muted/20 border-b">
+ <div class="flex items-center gap-3">
+ <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
+ <ClockIcon class="size-4" />
+ </div>
+ <div>
+ <Card.Title class="text-base">{m.security_session_heading()}</Card.Title>
+ <Card.Description class="text-xs">Configure session timeout and duration</Card.Description>
+ </div>
</div>
- </div>
- </Card.Header>
- <Card.Content class="px-3 py-4 sm:px-6">
- <TextInputWithLabel
- bind:value={$formInputs.authSessionTimeout.value}
- label={m.security_session_timeout_label()}
- placeholder={m.security_session_timeout_placeholder()}
- helpText={m.security_session_timeout_description()}
- type="number"
- />
- </Card.Content>
- </Card.Root>
-
- <!-- Password Policy Card -->
- <Card.Root class="overflow-hidden">
- <Card.Header class="py-4! bg-muted/20 border-b">
- <div class="flex items-center gap-3">
- <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
- <KeyIcon class="size-4" />
- </div>
- <div>
- <Card.Title class="text-base">{m.security_password_policy_label()}</Card.Title>
- <Card.Description class="text-xs">Set password strength requirements</Card.Description>
- </div>
- </div>
- </Card.Header>
- <Card.Content class="px-3 py-4 sm:px-6">
- <Tooltip.Provider>
- <div class="grid grid-cols-1 gap-2 sm:grid-cols-3 sm:gap-3" role="group" aria-labelledby="passwordPolicyLabel">
- <Tooltip.Root>
- <Tooltip.Trigger>
- <Button
- variant={$formInputs.authPasswordPolicy.value === 'basic' ? 'default' : 'outline'}
- class={$formInputs.authPasswordPolicy.value === 'basic'
- ? 'arcane-button-create h-12 w-full text-xs sm:text-sm'
- : 'arcane-button-restart h-12 w-full text-xs sm:text-sm'}
- onclick={() => ($formInputs.authPasswordPolicy.value = 'basic')}
- type="button"
- >{m.security_password_policy_basic()}
- </Button>
- </Tooltip.Trigger>
- <Tooltip.Content side="top" align="center">{m.security_password_policy_basic_tooltip()}</Tooltip.Content>
- </Tooltip.Root>
-
- <Tooltip.Root>
- <Tooltip.Trigger>
- <Button
- variant={$formInputs.authPasswordPolicy.value === 'standard' ? 'default' : 'outline'}
- class={$formInputs.authPasswordPolicy.value === 'standard'
- ? 'arcane-button-create h-12 w-full text-xs sm:text-sm'
- : 'arcane-button-restart h-12 w-full text-xs sm:text-sm'}
- onclick={() => ($formInputs.authPasswordPolicy.value = 'standard')}
- type="button"
- >{m.security_password_policy_standard()}
- </Button>
- </Tooltip.Trigger>
- <Tooltip.Content side="top" align="center">{m.security_password_policy_standard_tooltip()}</Tooltip.Content>
- </Tooltip.Root>
-
- <Tooltip.Root>
- <Tooltip.Trigger>
- <Button
- variant={$formInputs.authPasswordPolicy.value === 'strong' ? 'default' : 'outline'}
- class={$formInputs.authPasswordPolicy.value === 'strong'
- ? 'arcane-button-create h-12 w-full text-xs sm:text-sm'
- : 'arcane-button-restart h-12 w-full text-xs sm:text-sm'}
- onclick={() => ($formInputs.authPasswordPolicy.value = 'strong')}
- type="button"
- >{m.security_password_policy_strong()}
- </Button>
- </Tooltip.Trigger>
- <Tooltip.Content side="top" align="center">{m.security_password_policy_strong_tooltip()}</Tooltip.Content>
- </Tooltip.Root>
+ </Card.Header>
+ <Card.Content class="px-3 py-4 sm:px-6">
+ <TextInputWithLabel
+ bind:value={$formInputs.authSessionTimeout.value}
+ label={m.security_session_timeout_label()}
+ placeholder={m.security_session_timeout_placeholder()}
+ helpText={m.security_session_timeout_description()}
+ type="number"
+ />
+ </Card.Content>
+ </Card.Root>
+
+ <!-- Password Policy Card -->
+ <Card.Root class="overflow-hidden">
+ <Card.Header class="py-4! bg-muted/20 border-b">
+ <div class="flex items-center gap-3">
+ <div class="bg-primary/10 text-primary ring-primary/20 flex size-8 items-center justify-center rounded-lg ring-1">
+ <KeyIcon class="size-4" />
+ </div>
+ <div>
+ <Card.Title class="text-base">{m.security_password_policy_label()}</Card.Title>
+ <Card.Description class="text-xs">Set password strength requirements</Card.Description>
+ </div>
</div>
- </Tooltip.Provider>
- </Card.Content>
- </Card.Root>
-</div>
+ </Card.Header>
+ <Card.Content class="px-3 py-4 sm:px-6">
+ <Tooltip.Provider>
+ <div class="grid grid-cols-1 gap-2 sm:grid-cols-3 sm:gap-3" role="group" aria-labelledby="passwordPolicyLabel">
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <Button
+ variant={$formInputs.authPasswordPolicy.value === 'basic' ? 'default' : 'outline'}
+ class={$formInputs.authPasswordPolicy.value === 'basic'
+ ? 'arcane-button-create h-12 w-full text-xs sm:text-sm'
+ : 'arcane-button-restart h-12 w-full text-xs sm:text-sm'}
+ onclick={() => ($formInputs.authPasswordPolicy.value = 'basic')}
+ type="button"
+ >{m.security_password_policy_basic()}
+ </Button>
+ </Tooltip.Trigger>
+ <Tooltip.Content side="top" align="center">{m.security_password_policy_basic_tooltip()}</Tooltip.Content>
+ </Tooltip.Root>
+
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <Button
+ variant={$formInputs.authPasswordPolicy.value === 'standard' ? 'default' : 'outline'}
+ class={$formInputs.authPasswordPolicy.value === 'standard'
+ ? 'arcane-button-create h-12 w-full text-xs sm:text-sm'
+ : 'arcane-button-restart h-12 w-full text-xs sm:text-sm'}
+ onclick={() => ($formInputs.authPasswordPolicy.value = 'standard')}
+ type="button"
+ >{m.security_password_policy_standard()}
+ </Button>
+ </Tooltip.Trigger>
+ <Tooltip.Content side="top" align="center">{m.security_password_policy_standard_tooltip()}</Tooltip.Content>
+ </Tooltip.Root>
+
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <Button
+ variant={$formInputs.authPasswordPolicy.value === 'strong' ? 'default' : 'outline'}
+ class={$formInputs.authPasswordPolicy.value === 'strong'
+ ? 'arcane-button-create h-12 w-full text-xs sm:text-sm'
+ : 'arcane-button-restart h-12 w-full text-xs sm:text-sm'}
+ onclick={() => ($formInputs.authPasswordPolicy.value = 'strong')}
+ type="button"
+ >{m.security_password_policy_strong()}
+ </Button>
+ </Tooltip.Trigger>
+ <Tooltip.Content side="top" align="center">{m.security_password_policy_strong_tooltip()}</Tooltip.Content>
+ </Tooltip.Root>
+ </div>
+ </Tooltip.Provider>
+ </Card.Content>
+ </Card.Root>
+ </div>
+</fieldset>
<OidcConfigDialog
bind:open={showOidcConfigDialog}
diff --git a/frontend/src/routes/settings/general/+page.svelte b/frontend/src/routes/settings/general/+page.svelte
index eaaecb174..593eeac4a 100644
--- a/frontend/src/routes/settings/general/+page.svelte
+++ b/frontend/src/routes/settings/general/+page.svelte
@@ -2,6 +2,7 @@
import type { Settings } from '$lib/types/settings.type';
import settingsStore from '$lib/stores/config-store';
import { settingsAPI } from '$lib/services/api';
+ import UiConfigDisabledTag from '$lib/components/ui-config-disabled-tag.svelte';
import GeneralSettingsForm from '../forms/general-settings-form.svelte';
import SettingsIcon from '@lucide/svelte/icons/settings';
import { m } from '$lib/paraglide/messages';
@@ -11,6 +12,8 @@
let currentSettings = $state(data.settings);
let hasChanges = $state(false);
let isLoading = $state(false);
+
+ const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);
const formState = getContext('settingsFormState') as any;
@@ -40,17 +43,22 @@
>
<div class="bg-primary/10 pointer-events-none absolute -right-10 -top-10 size-40 rounded-full blur-3xl"></div>
<div class="bg-muted/40 pointer-events-none absolute -bottom-10 -left-10 size-40 rounded-full blur-3xl"></div>
- <div class="relative flex items-start justify-between gap-3 sm:gap-4">
- <div class="flex min-w-0 items-start gap-3 sm:gap-4">
- <div
- class="bg-primary/10 text-primary ring-primary/20 flex size-8 shrink-0 items-center justify-center rounded-lg ring-1 sm:size-10"
- >
- <SettingsIcon class="size-4 sm:size-5" />
- </div>
- <div class="min-w-0">
- <h1 class="settings-title text-xl sm:text-3xl">{m.general_title()}</h1>
- <p class="settings-description text-sm sm:text-base">{m.general_description()}</p>
+ <div class="relative flex items-start gap-3 sm:gap-4">
+ <div
+ class="bg-primary/10 text-primary ring-primary/20 flex size-8 shrink-0 items-center justify-center rounded-lg ring-1 sm:size-10"
+ >
+ <SettingsIcon class="size-4 sm:size-5" />
+ </div>
+ <div class="min-w-0 flex-1">
+ <div class="flex items-start justify-between gap-3">
+ <h1 class="settings-title text-xl sm:text-3xl min-w-0">{m.general_title()}</h1>
+ {#if isReadOnly}
+ <div class="shrink-0">
+ <UiConfigDisabledTag />
+ </div>
+ {/if}
</div>
+ <p class="text-muted-foreground mt-1 text-sm sm:text-base">{m.general_description()}</p>
</div>
</div>
</div>
@@ -59,3 +67,4 @@
<GeneralSettingsForm settings={currentSettings} callback={updateSettingsConfig} bind:hasChanges bind:isLoading />
</div>
</div>
+
diff --git a/frontend/src/routes/settings/security/+page.svelte b/frontend/src/routes/settings/security/+page.svelte
index 4dd9d0d8e..b55930c58 100644
--- a/frontend/src/routes/settings/security/+page.svelte
+++ b/frontend/src/routes/settings/security/+page.svelte
@@ -3,6 +3,7 @@
import type { Settings } from '$lib/types/settings.type';
import settingsStore from '$lib/stores/config-store';
import { settingsAPI } from '$lib/services/api';
+ import UiConfigDisabledTag from '$lib/components/ui-config-disabled-tag.svelte';
import SecuritySettingsForm from '../forms/security-settings-form.svelte';
import LockIcon from '@lucide/svelte/icons/lock';
import { m } from '$lib/paraglide/messages';
@@ -12,6 +13,8 @@
let currentSettings = $state<Settings>(data.settings);
let hasChanges = $state(false);
let isLoading = $state(false);
+
+ const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);
const formState = getContext('settingsFormState') as any;
@@ -41,17 +44,22 @@
>
<div class="bg-primary/10 pointer-events-none absolute -right-10 -top-10 size-40 rounded-full blur-3xl"></div>
<div class="bg-muted/40 pointer-events-none absolute -bottom-10 -left-10 size-40 rounded-full blur-3xl"></div>
- <div class="relative flex items-start justify-between gap-3 sm:gap-4">
- <div class="flex min-w-0 items-start gap-3 sm:gap-4">
- <div
- class="bg-primary/10 text-primary ring-primary/20 flex size-8 shrink-0 items-center justify-center rounded-lg ring-1 sm:size-10"
- >
- <LockIcon class="size-4 sm:size-5" />
- </div>
- <div class="min-w-0">
- <h1 class="settings-title text-xl sm:text-3xl">{m.security_title()}</h1>
- <p class="settings-description text-sm sm:text-base">{m.security_description()}</p>
+ <div class="relative flex items-start gap-3 sm:gap-4">
+ <div
+ class="bg-primary/10 text-primary ring-primary/20 flex size-8 shrink-0 items-center justify-center rounded-lg ring-1 sm:size-10"
+ >
+ <LockIcon class="size-4 sm:size-5" />
+ </div>
+ <div class="min-w-0 flex-1">
+ <div class="flex items-start justify-between gap-3">
+ <h1 class="settings-title text-xl sm:text-3xl min-w-0">{m.security_title()}</h1>
+ {#if isReadOnly}
+ <div class="shrink-0">
+ <UiConfigDisabledTag />
+ </div>
+ {/if}
</div>
+ <p class="text-muted-foreground mt-1 text-sm sm:text-base">{m.security_description()}</p>
</div>
</div>
</div>
@@ -66,3 +74,4 @@
/>
</div>
</div>
+
diff --git a/frontend/src/routes/settings/users/+page.svelte b/frontend/src/routes/settings/users/+page.svelte
index 5ae0c6796..ce35aa696 100644
--- a/frontend/src/routes/settings/users/+page.svelte
+++ b/frontend/src/routes/settings/users/+page.svelte
@@ -114,7 +114,7 @@
<div class="flex flex-col justify-between gap-3 sm:gap-4 sm:flex-row sm:items-center">
<div class="min-w-0">
<h1 class="text-xl sm:text-3xl font-bold tracking-tight">{m.users_title()}</h1>
- <p class="text-muted-foreground mt-1 text-xs sm:text-sm">{m.users_subtitle()}</p>
+ <p class="text-muted-foreground mt-1 text-sm sm:text-base">{m.users_subtitle()}</p>
</div>
<div class="flex items-center gap-2 shrink-0">
<ArcaneButton
diff --git a/scripts/development/dev.sh b/scripts/development/dev.sh
index e130ce84c..efd022126 100755
--- a/scripts/development/dev.sh
+++ b/scripts/development/dev.sh
@@ -184,6 +184,34 @@ show_status() {
docker compose -f $COMPOSE_FILE -p $PROJECT_NAME ps
}
+show_env_config() {
+ local service="${1:-backend}"
+
+ log_info "Current environment configuration:"
+
+ # Check if the specified service container is running
+ if docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" ps "$service" | grep -q "Up"; then
+ log_info "Environment variables from running $service container:"
+ echo "----------------------------------------"
+ if docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" exec "$service" env | grep -E "^[A-Z_]+" | sort; then
+ echo "----------------------------------------"
+ else
+ log_error "Failed to retrieve environment variables from $service container"
+ return 1
+ fi
+ else
+ log_warning "$service container is not running."
+ if [[ -f ".env" ]]; then
+ log_info "Environment variables from .env file (container not started):"
+ echo "----------------------------------------"
+ grep -E "^[A-Z_]+" .env | sort
+ echo "----------------------------------------"
+ else
+ log_warning "No .env file found. Run 'start' to create one from .env.dev"
+ fi
+ fi
+}
+
show_logs() {
local service="${1:-}"
@@ -192,12 +220,17 @@ show_logs() {
docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" logs -f
else
# Validate service name
- if [[ ! "$service" =~ ^(frontend|backend)$ ]]; then
+ if [[ ! "$service" =~ ^(frontend|backend|arcane-agent|agent)$ ]]; then
log_error "Invalid service name: $service"
- log_error "Valid services: frontend, backend"
+ log_error "Valid services: frontend, backend, agent"
exit 1
fi
+ # Normalize agent service name
+ if [[ "$service" == "agent" ]]; then
+ service="arcane-agent"
+ fi
+
log_info "Showing logs for service: $service"
docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" logs -f "$service"
fi
@@ -205,24 +238,22 @@ show_logs() {
create_env_file() {
local env_file=".env"
+ local env_dev=".env.dev"
if [[ -f "$env_file" ]]; then
return 0
fi
- log_warning ".env file not found, creating basic development configuration..."
- cat > "$env_file" << 'EOF'
-# Development Environment Configuration
-# WARNING: These are development-only values, never use in production!
-
-ENCRYPTION_KEY=dev-encryption-key-replace-in-production-must-be-32-chars
-JWT_SECRET=dev-jwt-secret-replace-in-production-must-be-long-enough
-DATABASE_TYPE=sqlite
-DATABASE_PATH=/app/data/arcane.db
-GIN_MODE=debug
-ENVIRONMENT=development
-EOF
- log_success "Created .env file with development defaults"
+ if [[ ! -f "$env_dev" ]]; then
+ log_error ".env.dev file not found!"
+ log_error "Please ensure .env.dev exists in the project root"
+ exit 1
+ fi
+
+ log_warning ".env file not found, creating from .env.dev..."
+ cp "$env_dev" "$env_file"
+ log_success "Created .env file from .env.dev template"
+ log_info "You can customize the values in .env for your development setup"
}
start_dev() {
@@ -254,11 +285,31 @@ stop_dev() {
restart_dev() {
log_info "Restarting Arcane development environment..."
- if ! docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" restart; then
- log_error "Failed to restart development environment"
+
+ # Check if .env file exists and create if needed (to pick up any new changes)
+ create_env_file
+
+ # Stop containers gracefully to allow Air to clean up properly
+ log_info "Stopping containers gracefully..."
+ if ! docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" down; then
+ log_error "Failed to stop development environment"
exit 1
fi
- log_success "Development environment restarted!"
+
+ # Wait a moment for file locks to be released
+ log_info "Waiting for file locks to be released..."
+ sleep 2
+
+ # Start containers with fresh environment
+ log_info "Starting containers with updated environment..."
+ if ! docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" up -d; then
+ log_error "Failed to start development environment"
+ exit 1
+ fi
+
+ log_success "Development environment restarted with updated configuration!"
+ log_info "Frontend: http://localhost:3000"
+ log_info "Backend: http://localhost:3552"
}
clean_dev() {
@@ -285,39 +336,56 @@ clean_dev() {
rebuild_dev() {
log_info "Rebuilding development environment..."
+ # Stop containers
if ! docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" down; then
log_error "Failed to stop containers"
exit 1
fi
+ # Clean up any leftover build artifacts
+ log_info "Cleaning up build artifacts..."
+ if docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" exec backend rm -rf .bin 2>/dev/null; then
+ log_info "Cleaned backend build directory"
+ fi
+
+ # Rebuild with no cache
+ log_info "Rebuilding containers from scratch..."
if ! docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" build --no-cache; then
log_error "Failed to rebuild containers"
exit 1
fi
+ # Start fresh
if ! docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" up -d; then
log_error "Failed to start containers"
exit 1
fi
log_success "Development environment rebuilt and started!"
+ log_info "Frontend: http://localhost:3000"
+ log_info "Backend: http://localhost:3552"
}
shell_into() {
local service="${1:-}"
if [[ -z "$service" ]]; then
- log_error "Please specify a service: frontend or backend"
+ log_error "Please specify a service: frontend, backend, or agent"
exit 1
fi
# Validate service name
- if [[ ! "$service" =~ ^(frontend|backend)$ ]]; then
+ if [[ ! "$service" =~ ^(frontend|backend|arcane-agent|agent)$ ]]; then
log_error "Invalid service name: $service"
- log_error "Valid services: frontend, backend"
+ log_error "Valid services: frontend, backend, agent"
exit 1
fi
+ # Normalize agent service name
+ if [[ "$service" == "agent" ]]; then
+ service="arcane-agent"
+ fi
+
log_info "Opening shell in $service container..."
if ! docker compose -f "${COMPOSE_FILE}" -p "${PROJECT_NAME}" exec "$service" /bin/sh; then
log_error "Failed to open shell in $service container"
@@ -334,12 +402,13 @@ show_help() {
echo "Commands:"
echo " start Start the development environment"
echo " stop Stop the development environment"
- echo " restart Restart the development environment"
+ echo " restart Restart the development environment (reloads .env file)"
echo " status Show status of all services"
- echo " logs Show logs (optionally specify service: frontend, backend)"
+ echo " env Show current environment configuration (optionally specify service: backend, frontend)"
+ echo " logs Show logs (optionally specify service: frontend, backend, agent)"
echo " clean Remove all containers, networks, and volumes"
echo " rebuild Rebuild and restart the development environment"
- echo " shell Open shell in a service container (specify: frontend or backend)"
+ echo " shell Open shell in a service container (specify: frontend, backend, or agent)"
echo " help Show this help message"
echo
echo "Features:"
@@ -350,7 +419,9 @@ show_help() {
echo
echo "Examples:"
echo " $0 start"
+ echo " $0 env backend"
echo " $0 logs backend"
+ echo " $0 logs agent"
echo " $0 shell frontend"
echo
echo "Note: If Docker or Docker Compose are not installed, you'll be prompted"
@@ -378,6 +449,9 @@ main() {
status)
show_status
;;
+ env)
+ show_env_config "${2:-}"
+ ;;
logs)
show_logs "${2:-}"
;;
diff --git a/tests/setup/auth.setup.ts b/tests/setup/auth.setup.ts
index 02a94956c..62098427c 100644
--- a/tests/setup/auth.setup.ts
+++ b/tests/setup/auth.setup.ts
@@ -1,6 +1,6 @@
import { test as setup } from '@playwright/test';
import { skipOnboarding } from '../utils/onboarding.util';
-import authUtil from '../utils//auth.util';
+import authUtil from '../utils/auth.util';
const authFile = '.auth/login.json';
diff --git a/tests/spec/containers.spec.ts b/tests/spec/containers.spec.ts
index 6064ce597..2e6612a0d 100644
--- a/tests/spec/containers.spec.ts
+++ b/tests/spec/containers.spec.ts
@@ -1,53 +1,29 @@
import { test, expect, type Page } from '@playwright/test';
+import { fetchContainersWithRetry, type ContainerSummary, type Paginated } from '../utils/fetch.util';
-type ContainerSummary = {
- id: string;
- names?: string[];
- image?: string;
- state: string;
- status?: string;
- created?: number; // seconds
-};
-
-type Paginated<T> = { data: T[]; pagination?: { totalItems?: number } };
-
-async function fetchContainersWithRetry(page: Page, maxRetries = 3): Promise<Paginated<ContainerSummary>> {
- let retries = 0;
- while (retries < maxRetries) {
- try {
- const response = await page.request.get('/api/environments/0/containers');
- if (!response.ok()) throw new Error(`HTTP ${response.status()}`);
- const body = await response.json().catch(() => null as any);
- const data = Array.isArray(body?.data) ? (body.data as ContainerSummary[]) : [];
- const pagination = body?.pagination || { totalItems: data.length };
- return { data, pagination };
- } catch {
- retries++;
- if (retries >= maxRetries) break;
- await page.waitForTimeout(1000);
- }
- }
- return { data: [], pagination: { totalItems: 0 } };
+const CONTAINERS_ROUTE = '/containers';
+
+async function navigateToContainers(page: Page) {
+ await page.goto(CONTAINERS_ROUTE);
+ await page.waitForLoadState('networkidle');
}
let containersData: Paginated<ContainerSummary> = { data: [], pagination: { totalItems: 0 } };
test.beforeEach(async ({ page }) => {
- await page.goto('/containers');
- await page.waitForLoadState('networkidle');
+ await navigateToContainers(page);
containersData = await fetchContainersWithRetry(page);
- console.log(`Found ${containersData.data.length} containers (totalItems=${containersData.pagination?.totalItems ?? 0})`);
});
test.describe('Containers Page', () => {
test('should display the containers page title and description', async ({ page }) => {
- await page.goto('/containers');
+ await navigateToContainers(page);
await expect(page.getByRole('heading', { name: 'Containers', level: 1 })).toBeVisible();
await expect(page.getByText('View and Manage your Containers').first()).toBeVisible();
});
test('should display stat cards with correct counts', async ({ page }) => {
- await page.goto('/containers');
+ await navigateToContainers(page);
const total = containersData.pagination?.totalItems ?? containersData.data.length;
const running = containersData.data.filter((c) => c.state === 'running').length;
@@ -59,9 +35,7 @@ test.describe('Containers Page', () => {
});
test('should display the container table with columns', async ({ page }) => {
- await page.goto('/containers');
- await page.waitForLoadState('networkidle');
-
+ await navigateToContainers(page);
await expect(page.locator('table')).toBeVisible();
await expect(page.getByRole('button', { name: 'Name' })).toBeVisible();
await expect(page.getByRole('button', { name: 'ID' })).toBeVisible();
@@ -72,8 +46,7 @@ test.describe('Containers Page', () => {
test('should navigate to container details on Inspect', async ({ page }) => {
test.skip(containersData.data.length === 0, 'No containers available');
- await page.goto('/containers');
- await page.waitForLoadState('networkidle');
+ await navigateToContainers(page);
const firstRow = page.locator('tbody tr').first();
await firstRow.getByRole('button', { name: 'Open menu' }).click();
@@ -87,15 +60,14 @@ test.describe('Containers Page', () => {
const running = containersData.data.find((c) => c.state === 'running');
const stopped = containersData.data.find((c) => c.state !== 'running');
- await page.goto('/containers');
- await page.waitForLoadState('networkidle');
+ await navigateToContainers(page);
if (running) {
const row = page.locator(`tr:has(a[href="/containers/${running.id}/"])`);
await row.getByRole('button', { name: 'Open menu' }).click();
await expect(page.getByRole('menuitem', { name: 'Restart' })).toBeVisible();
await expect(page.getByRole('menuitem', { name: 'Stop' })).toBeVisible();
- await page.keyboard.press('Escape'); // close menu
+ await page.keyboard.press('Escape');
} else {
test.info().annotations.push({ type: 'note', description: 'No running container to validate actions' });
}
@@ -114,8 +86,7 @@ test.describe('Containers Page', () => {
test.skip(containersData.data.length === 0, 'No containers available');
const any = containersData.data[0];
- await page.goto('/containers');
- await page.waitForLoadState('networkidle');
+ await navigateToContainers(page);
const row = page.locator(`tr:has(a[href="/containers/${any.id}/"])`);
await row.getByRole('button', { name: 'Open menu' }).click();
@@ -124,7 +95,6 @@ test.describe('Containers Page', () => {
const dialog = page.locator('div[role="heading"][aria-level="2"][data-dialog-title]:has-text("Confirm Container Removal")');
await expect(dialog).toBeVisible();
- // Cancel removal (do not mutate)
await page.getByRole('button', { name: 'Cancel' }).click();
await expect(dialog).toBeHidden();
});
diff --git a/tests/spec/converter.spec.ts b/tests/spec/converter.spec.ts
index 1c80b4d42..4916d32a9 100644
--- a/tests/spec/converter.spec.ts
+++ b/tests/spec/converter.spec.ts
@@ -1,73 +1,87 @@
import { test, expect, type Page } from '@playwright/test';
+type ConvertResponse = {
+ success: boolean;
+ dockerCompose: string;
+ envVars: string;
+ serviceName: string;
+};
+
+const ROUTES = {
+ page: '/projects/new',
+ apiConvert: '/api/convert',
+};
+
+const SELECTORS = {
+ dropdownTrigger: '[data-slot="dropdown-button-trigger"]',
+ convertButton: (name = 'Convert to Compose') => ({ name }),
+ textareaPlaceholder: 'docker run -d --name my-app -p 8080:80 nginx:alpine',
+ stackNamePlaceholder: 'e.g., my-web-app',
+ exampleButtonName: /docker run -d --name nginx/,
+ successToast: 'Docker run command converted successfully!',
+ exampleCommandExpected: 'docker run -d --name nginx -p 8080:80 -v nginx_data:/usr/share/nginx/html nginx:alpine',
+ removeNewline: (s: string) => s.replace(/\r\n/g, '\n'),
+};
+
async function openConvertFromDockerRun(page: Page) {
- await page.locator('[data-slot="dropdown-button-trigger"]').first().click();
+ await page.locator(SELECTORS.dropdownTrigger).first().click();
await page.getByRole('menuitem', { name: 'Convert from Docker Run' }).click();
}
+async function setupMockConvert(page: Page, payload: ConvertResponse) {
+ await page.route(ROUTES.apiConvert, async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(payload),
+ });
+ });
+}
+
test.describe('Docker Run to Compose Converter', () => {
test.beforeEach(async ({ page }) => {
- await page.goto('/projects/new');
+ await page.goto(ROUTES.page);
await page.waitForLoadState('networkidle');
});
test('should convert simple docker run command', async ({ page }) => {
- await page.waitForLoadState('networkidle');
await openConvertFromDockerRun(page);
- // Enter a simple docker run command using the textarea
const dockerCommand = 'docker run -d --name nginx -p 8080:80 nginx:alpine';
- await page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine').fill(dockerCommand);
-
- // Mock the API response
- await page.route('/api/convert', async (route) => {
- await route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify({
- success: true,
- dockerCompose: `services:
+ await page.getByPlaceholder(SELECTORS.textareaPlaceholder).fill(dockerCommand);
+
+ await setupMockConvert(page, {
+ success: true,
+ dockerCompose: `services:
nginx:
image: nginx:alpine
container_name: nginx
ports:
- 8080:80`,
- envVars: '',
- serviceName: 'nginx',
- }),
- });
+ envVars: '',
+ serviceName: 'nginx',
});
- // Click convert button
- await page.getByRole('button', { name: 'Convert to Compose' }).click();
+ await page.getByRole('button', SELECTORS.convertButton()).click();
- // Wait for success toast
- await expect(page.getByText('Docker run command converted successfully!')).toBeVisible();
+ await expect(page.getByText(SELECTORS.successToast)).toBeVisible();
- // Check if stack name was populated
- await expect(page.getByPlaceholder('e.g., my-web-app')).toHaveValue('nginx');
+ await expect(page.getByPlaceholder(SELECTORS.stackNamePlaceholder)).toHaveValue('nginx');
- // Check if docker run command was cleared
- await expect(page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine')).toHaveValue('');
+ await expect(page.getByPlaceholder(SELECTORS.textareaPlaceholder)).toHaveValue('');
});
test('should convert docker run command with environment variables', async ({ page }) => {
await openConvertFromDockerRun(page);
await page.waitForTimeout(300);
- // Enter docker run command with environment variables
const dockerCommand =
'docker run -d --name postgres -e POSTGRES_DB=mydb -e POSTGRES_USER=user -e POSTGRES_PASSWORD=pass postgres:15';
- await page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine').fill(dockerCommand);
-
- // Mock the API response
- await page.route('/api/convert', async (route) => {
- await route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify({
- success: true,
- dockerCompose: `services:
+ await page.getByPlaceholder(SELECTORS.textareaPlaceholder).fill(dockerCommand);
+
+ await setupMockConvert(page, {
+ success: true,
+ dockerCompose: `services:
postgres:
image: postgres:15
container_name: postgres
@@ -75,85 +89,58 @@ test.describe('Docker Run to Compose Converter', () => {
- POSTGRES_DB=mydb
- POSTGRES_USER=user
- POSTGRES_PASSWORD=pass`,
- envVars: 'POSTGRES_DB=mydb\nPOSTGRES_USER=user\nPOSTGRES_PASSWORD=pass',
- serviceName: 'postgres',
- }),
- });
+ envVars: 'POSTGRES_DB=mydb\nPOSTGRES_USER=user\nPOSTGRES_PASSWORD=pass',
+ serviceName: 'postgres',
});
- // Click convert button
- await page.getByRole('button', { name: 'Convert to Compose' }).click();
+ await page.getByRole('button', SELECTORS.convertButton()).click();
- // Wait for success toast
- await expect(page.getByText('Docker run command converted successfully!')).toBeVisible();
+ await expect(page.getByText(SELECTORS.successToast)).toBeVisible();
- // Check if stack name was populated
- await expect(page.getByPlaceholder('e.g., my-web-app')).toHaveValue('postgres');
+ await expect(page.getByPlaceholder(SELECTORS.stackNamePlaceholder)).toHaveValue('postgres');
});
test('should use example commands', async ({ page }) => {
await openConvertFromDockerRun(page);
await page.waitForTimeout(300);
- // Click on the first example command (using a more specific selector)
- await page
- .getByRole('button', { name: /docker run -d --name nginx/ })
- .first()
- .click();
+ await page.getByRole('button', { name: SELECTORS.exampleButtonName }).first().click();
- // Check if the command was populated in the textarea
- const expectedCommand = 'docker run -d --name nginx -p 8080:80 -v nginx_data:/usr/share/nginx/html nginx:alpine';
- await expect(page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine')).toHaveValue(expectedCommand);
+ await expect(page.getByPlaceholder(SELECTORS.textareaPlaceholder)).toHaveValue(SELECTORS.exampleCommandExpected);
});
test('should disable convert button when no command is entered', async ({ page }) => {
await openConvertFromDockerRun(page);
await page.waitForTimeout(300);
- // Check that convert button is disabled when textarea is empty
- await expect(page.getByRole('button', { name: 'Convert to Compose' })).toBeDisabled();
+ const convertBtn = page.getByRole('button', SELECTORS.convertButton());
- // Enter some text
- await page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine').fill('docker run nginx');
+ await expect(convertBtn).toBeDisabled();
- // Check that convert button is now enabled
- await expect(page.getByRole('button', { name: 'Convert to Compose' })).toBeEnabled();
+ await page.getByPlaceholder(SELECTORS.textareaPlaceholder).fill('docker run nginx');
+ await expect(convertBtn).toBeEnabled();
- // Clear the text
- await page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine').clear();
-
- // Check that convert button is disabled again
- await expect(page.getByRole('button', { name: 'Convert to Compose' })).toBeDisabled();
+ await page.getByPlaceholder(SELECTORS.textareaPlaceholder).clear();
+ await expect(convertBtn).toBeDisabled();
});
test('should populate stack name only when empty', async ({ page }) => {
await openConvertFromDockerRun(page);
await page.waitForTimeout(300);
- // Enter docker run command with name
- await page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine').fill('docker run --name redis redis:alpine');
-
- // Mock the API response
- await page.route('/api/convert', async (route) => {
- await route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify({
- success: true,
- dockerCompose: 'services:\n redis:\n image: redis:alpine',
- envVars: '',
- serviceName: 'redis',
- }),
- });
+ await page.getByPlaceholder(SELECTORS.textareaPlaceholder).fill('docker run --name redis redis:alpine');
+
+ await setupMockConvert(page, {
+ success: true,
+ dockerCompose: 'services:\n redis:\n image: redis:alpine',
+ envVars: '',
+ serviceName: 'redis',
});
- // Click convert button
- await page.getByRole('button', { name: 'Convert to Compose' }).click();
+ await page.getByRole('button', SELECTORS.convertButton()).click();
- // Wait for success
- await expect(page.getByText('Docker run command converted successfully!')).toBeVisible();
+ await expect(page.getByText(SELECTORS.successToast)).toBeVisible();
- // Check that stack name was populated from service name
- await expect(page.getByPlaceholder('e.g., my-web-app')).toHaveValue('redis');
+ await expect(page.getByPlaceholder(SELECTORS.stackNamePlaceholder)).toHaveValue('redis');
});
});
diff --git a/tests/spec/images.spec.ts b/tests/spec/images.spec.ts
index f0af8ec13..47561f1d1 100644
--- a/tests/spec/images.spec.ts
+++ b/tests/spec/images.spec.ts
@@ -1,30 +1,20 @@
import { test, expect, type Page } from '@playwright/test';
+import { fetchImagesWithRetry } from '../utils/fetch.util';
-async function fetchImagesWithRetry(page: Page, maxRetries = 3): Promise<any[]> {
- let retries = 0;
- while (retries < maxRetries) {
- try {
- const response = await page.request.get('/api/environments/0/images');
- if (!response.ok()) {
- throw new Error(`HTTP ${response.status()}`);
- }
- const body = await response.json().catch(() => null as any);
- const data = Array.isArray(body?.data) ? body.data : [];
- return data;
- } catch (error) {
- retries++;
- if (retries >= maxRetries) return [];
- await page.waitForTimeout(1000);
- }
- }
- return [];
+const ROUTES = {
+ page: '/images',
+ apiImages: '/api/environments/0/images',
+};
+
+async function navigateToImages(page: Page) {
+ await page.goto(ROUTES.page);
+ await page.waitForLoadState('networkidle');
}
let realImages: any[] = [];
test.beforeEach(async ({ page }) => {
- await page.goto('/images');
- await page.waitForLoadState('networkidle');
+ await navigateToImages(page);
try {
const images = await fetchImagesWithRetry(page);
@@ -32,52 +22,44 @@ test.beforeEach(async ({ page }) => {
} catch {
realImages = [];
}
-
- console.log(`Found ${realImages.length} real images for testing`);
});
test.describe('Images Page', () => {
test('should display the images page title and description', async ({ page }) => {
- await page.goto('/images');
+ await navigateToImages(page);
await expect(page.getByRole('heading', { name: 'Images', level: 1 })).toBeVisible();
await expect(page.getByText('View and Manage your Container images').first()).toBeVisible();
});
test('should display stats cards with correct counts and size', async ({ page }) => {
- await page.goto('/images');
+ await navigateToImages(page);
await expect(page.locator('p:has-text("Total Images") + p')).toHaveText(realImages.length.toString());
await expect(page.locator('p:has-text("Total Size") + p')).not.toBeEmpty();
});
test('should display the image table when images exist', async ({ page }) => {
- await page.goto('/images');
-
- await page.waitForLoadState('networkidle');
+ await navigateToImages(page);
await expect(page.locator('table')).toBeVisible();
await expect(page.getByRole('button', { name: 'Repository' })).toBeVisible();
});
test('should open the Pull Image dialog', async ({ page }) => {
- await page.goto('/images');
- await page.waitForLoadState('networkidle');
+ await navigateToImages(page);
await page.locator('button:has-text("Pull Image")').first().click();
await expect(page.locator('div[role="heading"][aria-level="2"][data-dialog-title]:has-text("Pull Image")')).toBeVisible();
});
test('should open the Prune Unused Images dialog', async ({ page }) => {
- await page.goto('/images');
- await page.waitForLoadState('networkidle');
+ await navigateToImages(page);
await page.locator('button:has-text("Prune Unused")').click();
await expect(page.locator('div[role="heading"][aria-level="2"][data-dialog-title]:has-text("Prune Unused Images")')).toBeVisible();
});
test('should navigate to image details on inspect click', async ({ page }) => {
- await page.goto('/images');
-
- await page.waitForLoadState('networkidle');
+ await navigateToImages(page);
const firstRow = page.locator('tbody tr').first();
await firstRow.getByRole('button', { name: 'Open menu' }).click();
@@ -86,13 +68,10 @@ test.describe('Images Page', () => {
test('should pull image from dropdown menu', async ({ page }) => {
test.skip(!realImages.length, 'No images available for pull API test');
- await page.goto('/images');
-
- await page.waitForLoadState('networkidle');
+ await navigateToImages(page);
const firstRow = await page.getByRole('row', { name: 'ghcr.io/linuxserver/nginx' });
await firstRow.getByRole('button', { name: 'Open menu' }).click();
-
await page.getByRole('menuitem', { name: 'Pull' }).click();
await page.waitForLoadState('networkidle');
@@ -102,9 +81,7 @@ test.describe('Images Page', () => {
test('should call remove API on row action remove click and confirmation', async ({ page }) => {
test.skip(!realImages.length, 'No images available for remove API test');
- await page.goto('/images');
-
- await page.waitForLoadState('networkidle');
+ await navigateToImages(page);
const deleteableImage = realImages.find((img) => img.repoTags?.[0]?.includes('ghcr.io/linuxserver/radarr'));
test.skip(!deleteableImage, 'No deletable images available');
@@ -122,9 +99,7 @@ test.describe('Images Page', () => {
});
test('should call prune API on prune click and confirmation', async ({ page }) => {
- await page.goto('/images');
-
- await page.waitForLoadState('networkidle');
+ await navigateToImages(page);
await page.locator('button:has-text("Prune Unused")').click();
@@ -138,9 +113,7 @@ test.describe('Images Page', () => {
});
test('should pull image via form', async ({ page }) => {
- await page.goto('/images');
-
- await page.waitForLoadState('networkidle');
+ await navigateToImages(page);
await page.locator('button:has-text("Pull Image")').first().click();
const dialogHeading = page.locator('div[role="heading"][aria-level="2"][data-dialog-title]:has-text("Pull Image")');
diff --git a/tests/spec/network.spec.ts b/tests/spec/network.spec.ts
index 00f766b2b..5f02dba89 100644
--- a/tests/spec/network.spec.ts
+++ b/tests/spec/network.spec.ts
@@ -1,52 +1,34 @@
import { test, expect, type Page } from '@playwright/test';
+import { fetchNetworksWithRetry, type NetworkSummary } from '../utils/fetch.util';
-type NetworkSummary = { id: string; name: string; driver?: string; scope?: string };
-
-async function fetchNetworksWithRetry(page: Page, maxRetries = 3): Promise<NetworkSummary[]> {
- let retries = 0;
- while (retries < maxRetries) {
- try {
- const res = await page.request.get('/api/networks');
- const json = await res.json();
- const data = Array.isArray(json) ? json : json?.data?.data ?? json?.data ?? [];
- return (data ?? []) as NetworkSummary[];
- } catch {
- retries++;
- if (retries >= maxRetries) throw new Error('Failed to fetch networks');
- await new Promise((r) => setTimeout(r, 800));
- }
- }
- return [];
+async function navigateToNetworks(page: Page) {
+ await page.goto('/networks');
+ await page.waitForLoadState('networkidle');
}
let realNetworks: NetworkSummary[] = [];
test.beforeEach(async ({ page }) => {
- await page.goto('/networks');
- await page.waitForLoadState('networkidle');
- realNetworks = await fetchNetworksWithRetry(page);
+ await navigateToNetworks(page);
+ realNetworks = await fetchNetworksWithRetry(page).catch(() => []);
});
test.describe('Networks Page', () => {
test('Page renders with heading and subtitle', async ({ page }) => {
- await page.goto('/networks');
+ await navigateToNetworks(page);
await expect(page.getByRole('heading', { level: 1, name: 'Networks' })).toBeVisible();
await expect(page.getByText('Manage your Docker networks').first()).toBeVisible();
});
test('Stat cards show correct counts', async ({ page }) => {
- await page.goto('/networks');
-
+ await navigateToNetworks(page);
const total = realNetworks.length;
-
await expect(page.locator('p:has-text("Total Networks") + p')).toHaveText(String(total));
await expect(page.locator('p:has-text("Unused Networks") + p')).toBeVisible();
});
test('Table displays when networks exist, else empty state', async ({ page }) => {
- await page.goto('/networks');
- await page.waitForLoadState('networkidle');
-
+ await navigateToNetworks(page);
if (realNetworks.length > 0) {
await expect(page.locator('table')).toBeVisible();
await expect(page.getByRole('button', { name: 'Name' })).toBeVisible();
@@ -56,22 +38,17 @@ test.describe('Networks Page', () => {
});
test('Open Create Network sheet', async ({ page }) => {
- await page.goto('/networks');
- await page.waitForLoadState('networkidle');
-
+ await navigateToNetworks(page);
await page.locator('button:has-text("Create Network")').first().click();
await expect(page.getByRole('dialog')).toBeVisible();
});
test('Create Network', async ({ page }) => {
- await page.goto('/networks');
- await page.waitForLoadState('networkidle');
-
+ await navigateToNetworks(page);
await page.locator('button:has-text("Create Network")').first().click();
await expect(page.getByRole('dialog')).toBeVisible();
const networkName = `test-network-${Date.now()}`;
- // Prefer label "Name" if available
const nameInput = page.getByLabel('Name').first();
if (await nameInput.isVisible().catch(() => false)) {
await nameInput.fill(networkName);
@@ -80,27 +57,21 @@ test.describe('Networks Page', () => {
}
await page.getByRole('dialog').locator('button:has-text("Create Network")').click();
-
await expect(page.locator('li[data-sonner-toast][data-type="success"] div[data-title]')).toBeVisible();
});
test('Inspect Network from row actions', async ({ page }) => {
- await page.goto('/networks');
- await page.waitForLoadState('networkidle');
-
+ await navigateToNetworks(page);
const firstRow = page.locator('tbody tr').first();
await firstRow.getByRole('button', { name: 'Open menu' }).click();
await page.getByRole('menuitem', { name: 'Inspect' }).click();
-
await expect(page).toHaveURL(/\/networks\/.+/);
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
});
test('Remove Network from table', async ({ page }) => {
const networkName = 'my-test-network';
-
- await page.goto('/networks');
- await page.waitForLoadState('networkidle');
+ await navigateToNetworks(page);
const row = page.locator('tbody tr', { has: page.getByText(networkName) }).first();
await expect(row).toBeVisible();
@@ -110,13 +81,11 @@ test.describe('Networks Page', () => {
await expect(page.getByRole('heading', { name: 'Delete Network' })).toBeVisible();
await page.locator('button:has-text("Delete")').click();
-
await expect(page.locator('li[data-sonner-toast][data-type="success"] div[data-title]')).toBeVisible();
});
test('Default networks cannot be removed on details page', async ({ page }) => {
const bridge = realNetworks.find((n) => n.name === 'bridge');
-
await page.goto(`/networks/${bridge.id}`);
await page.waitForLoadState('networkidle');
diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.ts
index d0b9f5e92..9e2088b09 100644
--- a/tests/spec/project.spec.ts
+++ b/tests/spec/project.spec.ts
@@ -1,36 +1,27 @@
import { test, expect, type Page } from '@playwright/test';
+import { fetchProjectsWithRetry, type Project } from '../utils/fetch.util';
-async function fetchProjectsWithRetry(page: Page, maxRetries = 3): Promise<any[]> {
- let retries = 0;
- while (retries < maxRetries) {
- try {
- const response = await page.request.get('/api/environments/0/projects');
- const projects = await response.json();
- return Array.isArray(projects) ? projects : projects.data || [];
- } catch (error) {
- retries++;
- console.log(`Attempt ${retries} failed, ${maxRetries - retries} retries left`);
- if (retries >= maxRetries) throw error;
- await new Promise((resolve) => setTimeout(resolve, 1000));
- }
- }
- return [];
+const ROUTES = {
+ page: '/projects',
+ apiProjects: '/api/environments/0/projects',
+ newProject: '/projects/new',
+};
+
+async function navigateToProjects(page: Page) {
+ await page.goto(ROUTES.page);
+ await page.waitForLoadState('networkidle');
}
-let realProjects: any[] = [];
+let realProjects: Project[] = [];
test.beforeEach(async ({ page }) => {
- await page.goto('/projects');
- await page.waitForLoadState('networkidle');
+ await navigateToProjects(page);
try {
realProjects = await fetchProjectsWithRetry(page);
} catch (error) {
- console.warn('Could not fetch projects after multiple retries:', error);
realProjects = [];
}
-
- console.log(`Found ${realProjects.length} real projects for testing`);
});
test.describe('Projects Page', () => {
@@ -51,7 +42,7 @@ test.describe('Projects Page', () => {
test('should navigate to new project page when "Create Project" is clicked', async ({ page }) => {
await page.getByRole('button', { name: 'Create Project' }).click();
- await expect(page).toHaveURL('/projects/new');
+ await expect(page).toHaveURL(ROUTES.newProject);
await expect(page.getByRole('heading', { name: 'Create New Project' })).toBeVisible();
});
@@ -82,7 +73,7 @@ test.describe('Projects Page', () => {
const projectName = await firstProjectLink.textContent();
await firstProjectLink.click();
- await expect(page).toHaveURL(new RegExp(`/projects/.+`));
+ await expect(page).toHaveURL(/\/projects\/.+/);
await expect(page.getByRole('heading', { name: new RegExp(`.*${projectName}`) })).toBeVisible();
});
@@ -105,7 +96,6 @@ test.describe('Projects Page', () => {
await page.waitForLoadState('networkidle');
- // Look for status badges in the table
const runningProjects = realProjects.filter((p) => p.status === 'running');
const stoppedProjects = realProjects.filter((p) => p.status === 'stopped');
@@ -121,7 +111,7 @@ test.describe('Projects Page', () => {
test.describe('New Compose Project Page', () => {
test.beforeEach(async ({ page }) => {
- await page.goto('/projects/new');
+ await page.goto(ROUTES.newProject);
await page.waitForLoadState('networkidle');
});
@@ -154,10 +144,10 @@ test.describe('New Compose Project Page', () => {
const responseBody = await response.text();
try {
- const parsedResponse = JSON.parse(responseBody);
- createdProjectId = parsedResponse.id;
- } catch (error) {
- console.error('Failed to parse response:', error);
+ const parsed = JSON.parse(responseBody);
+ createdProjectId = parsed.id;
+ } catch {
+ createdProjectId = createdProjectId;
}
await route.fulfill({
@@ -165,13 +155,15 @@ test.describe('New Compose Project Page', () => {
headers: response.headers(),
body: responseBody,
});
+ } else {
+ await route.continue();
}
});
const createButton = page.getByRole('button', { name: 'Create' });
await createButton.click();
- await page.waitForURL(new RegExp(`/projects/.+`), { timeout: 10000 });
+ await page.waitForURL(/\/projects\/.+/, { timeout: 10000 });
if (createdProjectId) {
await expect(page).toHaveURL(new RegExp(`/projects/${createdProjectId}`));
@@ -242,7 +234,6 @@ test.describe('Project Detail Page', () => {
await page.getByRole('tab', { name: /Configuration|Config/i }).click();
- // Titles inside CodePanel components
await expect(page.getByText(/Compose File/i)).toBeVisible();
await expect(page.getByText(/Environment\s*\(.env\)/i)).toBeVisible();
});
@@ -260,7 +251,6 @@ test.describe('Project Detail Page', () => {
await expect(logsTab).toBeEnabled();
await logsTab.click();
- // StackLogsPanel heading
await expect(page.getByText(/Logs/i)).toBeVisible();
await expect(page.getByRole('button', { name: /Start|Stop/i })).toBeVisible();
await expect(page.getByRole('button', { name: /Clear/i })).toBeVisible();
diff --git a/tests/spec/registries.spec.ts b/tests/spec/registries.spec.ts
index 0db8dcb43..cb24a5357 100644
--- a/tests/spec/registries.spec.ts
+++ b/tests/spec/registries.spec.ts
@@ -72,11 +72,14 @@ test.describe('Container Registries', () => {
const firstRowCheckbox = page.locator('tbody tr input[type="checkbox"]').first();
if (await firstRowCheckbox.count()) {
await firstRowCheckbox.check();
+
const removeSelected = page.getByRole('button', { name: /Remove Selected/i });
if (await removeSelected.count()) {
await removeSelected.click();
+
const confirm = page.locator('div[role="heading"][aria-level="2"][data-dialog-title], [role="dialog"] >> text=Remove');
await expect(confirm).toBeVisible();
+
await page.getByRole('button', { name: 'Cancel' }).click();
await expect(confirm).toBeHidden();
}
diff --git a/tests/spec/volumes.spec.ts b/tests/spec/volumes.spec.ts
index 451ea7dd6..b56e50ba5 100644
--- a/tests/spec/volumes.spec.ts
+++ b/tests/spec/volumes.spec.ts
@@ -1,27 +1,10 @@
import { test, expect, type Page } from '@playwright/test';
-
-async function fetchVolumesWithRetry(page: Page, maxRetries = 3): Promise<any[]> {
- let retries = 0;
- while (retries < maxRetries) {
- try {
- const response = await page.request.get('/api/volumes');
- const volumes = await response.json();
- return volumes.data;
- } catch (error) {
- retries++;
- console.log(`Attempt ${retries} failed, ${maxRetries - retries} retries left`);
- if (retries >= maxRetries) throw error;
- await new Promise((resolve) => setTimeout(resolve, 1000));
- }
- }
- return [];
-}
+import { fetchVolumesWithRetry } from '../utils/fetch.util';
let realVolumes: any[] = [];
test.beforeEach(async ({ page }) => {
await page.goto('/volumes');
- await page.waitForLoadState('networkidle');
realVolumes = await fetchVolumesWithRetry(page);
});
@@ -45,92 +28,6 @@ async function ensureFacetOpen(page: Page, title: string) {
return { trigger, content };
}
-async function ensureUsageOpen(page: Page) {
- const trigger = page.getByTestId('facet-usage-trigger').first();
- const used = page.getByTestId('facet-usage-option-true').first();
- if (await used.isVisible().catch(() => false)) return;
- if ((await trigger.getAttribute('data-state')) !== 'open') await trigger.click();
- await used.waitFor({ state: 'visible' });
-}
-
-async function toggleUsageValue(page: Page, value: 'true' | 'false', desired: boolean) {
- // 'true' -> In Use, 'false' -> Unused
- const want = desired ? 'true' : 'false';
- const testId = `facet-usage-option-${value}`;
-
- for (let attempt = 0; attempt < 6; attempt++) {
- await ensureUsageOpen(page);
-
- const option = page.getByTestId(testId).first();
- await option.waitFor({ state: 'visible' });
-
- const current = (await option.getAttribute('aria-selected')) === 'true';
- if (current === desired) return;
-
- // Try 1: click the label span (avoids pointer-events-none on icons)
- const label = option.locator('span', { hasText: value === 'true' ? 'In Use' : 'Unused' }).first();
- if (await label.isVisible().catch(() => false)) {
- await label.click().catch(() => {});
- try {
- await expect(option).toHaveAttribute('aria-selected', want, { timeout: 400 });
- return;
- } catch {}
- }
-
- // Try 2: click the leading checkbox chip
- const chip = option.locator('div').first();
- await chip.click({ force: true }).catch(() => {});
- try {
- await expect(option).toHaveAttribute('aria-selected', want, { timeout: 400 });
- return;
- } catch {}
-
- // Try 3: click center of the option
- const box = await option.boundingBox();
- if (box) {
- await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
- try {
- await expect(option).toHaveAttribute('aria-selected', want, { timeout: 400 });
- return;
- } catch {}
- }
-
- // Try 4: keyboard activation via the item
- await option.focus().catch(() => {});
- await option.press('Enter').catch(() => {});
- try {
- await expect(option).toHaveAttribute('aria-selected', want, { timeout: 400 });
- return;
- } catch {}
-
- // Try 5: synthesize DOM events
- await option
- .evaluate((el) => {
- const fire = (type: string) => el.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
- fire('pointerdown');
- fire('pointerup');
- fire('click');
- })
- .catch(() => {});
- try {
- await expect(option).toHaveAttribute('aria-selected', want, { timeout: 400 });
- return;
- } catch {}
-
- await page.waitForTimeout(120);
- }
-
- // Final check
- await ensureUsageOpen(page);
- await expect(page.getByTestId(testId)).toHaveAttribute('aria-selected', want);
-}
-
-async function setUsage(page: Page, showUsed: boolean, showUnused: boolean) {
- // true -> "In Use", false -> "Unused"
- await toggleUsageValue(page, 'true', showUsed);
- await toggleUsageValue(page, 'false', showUnused);
-}
-
test.describe('Volumes Page', () => {
test('Volume Page Display', async ({ page }) => {
await page.goto('/volumes');
diff --git a/tests/utils/fetch.util.ts b/tests/utils/fetch.util.ts
new file mode 100644
index 000000000..480c2ef31
--- /dev/null
+++ b/tests/utils/fetch.util.ts
@@ -0,0 +1,93 @@
+import type { Page } from '@playwright/test';
+
+export type Project = {
+ id?: string;
+ name?: string;
+ status?: string;
+ serviceCount?: number;
+ [key: string]: any;
+};
+
+export type NetworkSummary = {
+ id: string;
+ name: string;
+ driver?: string;
+ scope?: string;
+};
+
+export type ContainerSummary = {
+ id: string;
+ names?: string[];
+ image?: string;
+ state: string;
+ status?: string;
+ created?: number;
+};
+
+export type Paginated<T> = { data: T[]; pagination?: { totalItems?: number } };
+
+async function retry<T>(fn: () => Promise<T>, maxRetries: number, delayMs = 1000): Promise<T> {
+ let attempt = 0;
+ while (true) {
+ try {
+ return await fn();
+ } catch (e) {
+ attempt++;
+ if (attempt >= maxRetries) throw e;
+ await new Promise((r) => setTimeout(r, delayMs));
+ }
+ }
+}
+
+export async function fetchVolumesWithRetry(page: Page, maxRetries = 1): Promise<any[]> {
+ return retry(async () => {
+ const res = await page.request.get('/api/volumes');
+ const json = await res.json();
+ return Array.isArray(json?.data) ? json.data : [];
+ }, maxRetries);
+}
+
+const PROJECTS_ENDPOINT = '/api/environments/0/projects';
+export async function fetchProjectsWithRetry(page: Page, maxRetries = 3): Promise<Project[]> {
+ return retry(async () => {
+ const res = await page.request.get(PROJECTS_ENDPOINT);
+ const body = await res.json().catch(() => null as any);
+ if (Array.isArray(body)) return body;
+ if (Array.isArray(body?.data)) return body.data;
+ if (Array.isArray(body?.projects)) return body.projects;
+ return [];
+ }, maxRetries);
+}
+
+export async function fetchNetworksWithRetry(page: Page, maxRetries = 3): Promise<NetworkSummary[]> {
+ return retry(
+ async () => {
+ const res = await page.request.get('/api/networks');
+ const json = await res.json().catch(() => null);
+ const data = Array.isArray(json) ? json : json?.data?.data ?? json?.data ?? [];
+ return (data ?? []) as NetworkSummary[];
+ },
+ maxRetries,
+ 800
+ );
+}
+
+export async function fetchImagesWithRetry(page: Page, maxRetries = 3): Promise<any[]> {
+ return retry(async () => {
+ const res = await page.request.get('/api/environments/0/images');
+ if (!res.ok()) throw new Error(`HTTP ${res.status()}`);
+ const body = await res.json().catch(() => null as any);
+ return Array.isArray(body?.data) ? body.data : [];
+ }, maxRetries);
+}
+
+export async function fetchContainersWithRetry(page: Page, maxRetries = 3): Promise<Paginated<ContainerSummary>> {
+ return retry(async () => {
+ const res = await page.request.get('/api/environments/0/containers');
+ if (!res.ok()) throw new Error(`HTTP ${res.status()}`);
+ const body = await res.json().catch(() => null as any);
+ const data = Array.isArray(body?.data) ? (body.data as ContainerSummary[]) : [];
+ const pagination = body?.pagination || { totalItems: data.length };
+ return { data, pagination };
+ }, maxRetries);
+}