Skip to content

Modern Docker Management, Designed for Everyone

feat: edit environments and show/edit local environment (#915)

Chase Baucome7cdc66fbd17
diff --git a/backend/internal/api/environment_handler.go b/backend/internal/api/environment_handler.go
index 81d84849e..875ea0890 100644
--- a/backend/internal/api/environment_handler.go
+++ b/backend/internal/api/environment_handler.go
@@ -1,6 +1,7 @@
package api
import (
+ "context"
"log/slog"
"net/http"
"time"
@@ -179,6 +180,7 @@ func (h *EnvironmentHandler) GetEnvironment(c *gin.Context) {
// Update
func (h *EnvironmentHandler) UpdateEnvironment(c *gin.Context) {
environmentID := c.Param("id")
+ isLocalEnv := environmentID == LOCAL_DOCKER_ENVIRONMENT_ID
var req dto.UpdateEnvironmentDto
if err := c.ShouldBindJSON(&req); err != nil {
@@ -187,34 +189,42 @@ func (h *EnvironmentHandler) UpdateEnvironment(c *gin.Context) {
}
updates := map[string]interface{}{}
- if req.ApiUrl != nil {
- updates["api_url"] = *req.ApiUrl
+
+ // For local environment, only allow name
+ if !isLocalEnv {
+ if req.ApiUrl != nil {
+ updates["api_url"] = *req.ApiUrl
+ }
+ if req.Enabled != nil {
+ updates["enabled"] = *req.Enabled
+ }
}
+
if req.Name != nil {
updates["name"] = *req.Name
}
- if req.Enabled != nil {
- updates["enabled"] = *req.Enabled
- }
- // If caller asked to pair (bootstrapToken present) and no accessToken provided in the request,
- // resolve apiUrl (current or updated) and let the service pair and persist the token.
- if (req.AccessToken == nil) && req.BootstrapToken != nil && *req.BootstrapToken != "" {
- current, err := h.environmentService.GetEnvironmentByID(c.Request.Context(), environmentID)
- if err != nil || current == nil {
- c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Environment not found"}})
- return
- }
- apiUrl := current.ApiUrl
- if req.ApiUrl != nil && *req.ApiUrl != "" {
- apiUrl = *req.ApiUrl
- }
- if _, err := h.environmentService.PairAndPersistAgentToken(c.Request.Context(), environmentID, apiUrl, *req.BootstrapToken); err != nil {
- c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": "Agent pairing failed: " + err.Error()}})
- return
+ // Local environment cannot be paired or have access token updated
+ if !isLocalEnv {
+ // If caller asked to pair (bootstrapToken present) and no accessToken provided in the request,
+ // resolve apiUrl (current or updated) and let the service pair and persist the token.
+ if (req.AccessToken == nil) && req.BootstrapToken != nil && *req.BootstrapToken != "" {
+ current, err := h.environmentService.GetEnvironmentByID(c.Request.Context(), environmentID)
+ if err != nil || current == nil {
+ c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Environment not found"}})
+ return
+ }
+ apiUrl := current.ApiUrl
+ if req.ApiUrl != nil && *req.ApiUrl != "" {
+ apiUrl = *req.ApiUrl
+ }
+ if _, err := h.environmentService.PairAndPersistAgentToken(c.Request.Context(), environmentID, apiUrl, *req.BootstrapToken); err != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": "Agent pairing failed: " + err.Error()}})
+ return
+ }
+ } else if req.AccessToken != nil {
+ updates["access_token"] = *req.AccessToken
}
- } else if req.AccessToken != nil {
- updates["access_token"] = *req.AccessToken
}
updated, err := h.environmentService.UpdateEnvironment(c.Request.Context(), environmentID, updates)
@@ -223,6 +233,20 @@ func (h *EnvironmentHandler) UpdateEnvironment(c *gin.Context) {
return
}
+ // Trigger health check after update to verify new configuration
+ // This runs in background and doesn't block the response
+ if updated.Enabled {
+ go func() {
+ ctx := context.Background()
+ status, err := h.environmentService.TestConnection(ctx, environmentID, nil)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to test connection after environment update", "environment_id", environmentID, "environment_name", updated.Name, "status", status, "error", err)
+ } else {
+ slog.InfoContext(ctx, "Environment health check completed after update", "environment_id", environmentID, "environment_name", updated.Name, "status", status)
+ }
+ }()
+ }
+
out, mapErr := dto.MapOne[*models.Environment, dto.EnvironmentDto](updated)
if mapErr != nil {
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to map environment"}})
@@ -236,6 +260,12 @@ func (h *EnvironmentHandler) UpdateEnvironment(c *gin.Context) {
func (h *EnvironmentHandler) DeleteEnvironment(c *gin.Context) {
environmentID := c.Param("id")
+ // Prevent deletion of local environment
+ if environmentID == LOCAL_DOCKER_ENVIRONMENT_ID {
+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Cannot delete local environment"}})
+ return
+ }
+
err := h.environmentService.DeleteEnvironment(c.Request.Context(), environmentID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to delete environment: " + err.Error()}})
@@ -252,7 +282,13 @@ func (h *EnvironmentHandler) DeleteEnvironment(c *gin.Context) {
func (h *EnvironmentHandler) TestConnection(c *gin.Context) {
environmentID := c.Param("id")
- status, err := h.environmentService.TestConnection(c.Request.Context(), environmentID)
+ // Allow optional apiUrl in request body to test without saving
+ var req struct {
+ ApiUrl *string `json:"apiUrl"`
+ }
+ _ = c.ShouldBindJSON(&req)
+
+ status, err := h.environmentService.TestConnection(c.Request.Context(), environmentID, req.ApiUrl)
resp := dto.TestConnectionDto{Status: status}
if err != nil {
msg := err.Error()
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 70cb60d84..77044b9dc 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -54,6 +54,10 @@ func Bootstrap(ctx context.Context) error {
utils.InitEncryption(cfg)
utils.InitializeDefaultSettings(appCtx, cfg, appServices.Settings)
+ if err := appServices.Environment.EnsureLocalEnvironment(appCtx, cfg.AppUrl); err != nil {
+ slog.WarnContext(appCtx, "Failed to ensure local environment", "error", err)
+ }
+
utils.TestDockerConnection(appCtx, func(ctx context.Context) error {
dockerClient, err := dockerClientService.CreateConnection(ctx)
if err != nil {
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index b0a9f837b..449ddda6a 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -28,6 +28,11 @@ func registerJobs(appCtx context.Context, scheduler *job.Scheduler, appServices
slog.ErrorContext(appCtx, "Failed to register image polling job", slog.Any("error", err))
}
+ environmentHealthJob := job.NewEnvironmentHealthJob(scheduler, appServices.Environment, appServices.Settings)
+ if err := environmentHealthJob.Register(appCtx); err != nil {
+ slog.ErrorContext(appCtx, "Failed to register environment health check job", slog.Any("error", err))
+ }
+
analyticsJob := job.NewAnalyticsJob(scheduler, appServices.Settings, nil, appConfig)
if err := analyticsJob.Register(appCtx); err != nil {
slog.ErrorContext(appCtx, "Failed to register analytics heartbeat job", slog.Any("error", err))
@@ -48,6 +53,9 @@ func registerJobs(appCtx context.Context, scheduler *job.Scheduler, appServices
if err := autoUpdateJob.Reschedule(ctx); err != nil {
slog.WarnContext(ctx, "Failed to reschedule auto-update job", slog.Any("error", err))
}
+ if err := environmentHealthJob.Reschedule(ctx); err != nil {
+ slog.WarnContext(ctx, "Failed to reschedule environment-health job", slog.Any("error", err))
+ }
}
appServices.Settings.OnAutoUpdateSettingsChanged = func(ctx context.Context) {
if err := autoUpdateJob.Reschedule(ctx); err != nil {
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.go
index ce11418c9..00e64a0ce 100644
--- a/backend/internal/bootstrap/services_bootstrap.go
+++ b/backend/internal/bootstrap/services_bootstrap.go
@@ -58,7 +58,7 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config
svcs.ImageUpdate = services.NewImageUpdateService(db, svcs.Settings, svcs.ContainerRegistry, svcs.Docker, svcs.Event, svcs.Notification)
svcs.Image = services.NewImageService(db, svcs.Docker, svcs.ContainerRegistry, svcs.ImageUpdate, svcs.Event)
svcs.Project = services.NewProjectService(db, svcs.Settings, svcs.Event, svcs.Image)
- svcs.Environment = services.NewEnvironmentService(db, httpClient)
+ svcs.Environment = services.NewEnvironmentService(db, httpClient, svcs.Docker)
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)
diff --git a/backend/internal/dto/environment_dto.go b/backend/internal/dto/environment_dto.go
index 8e9b3ca6c..b9d5d0ee5 100644
--- a/backend/internal/dto/environment_dto.go
+++ b/backend/internal/dto/environment_dto.go
@@ -22,11 +22,9 @@ type TestConnectionDto struct {
}
type EnvironmentDto struct {
- ID string `json:"id"`
- Name string `json:"name,omitempty"`
- ApiUrl string `json:"apiUrl"`
- Status string `json:"status"`
- Enabled bool `json:"enabled"`
- CreatedAt string `json:"createdAt"`
- UpdatedAt *string `json:"updatedAt,omitempty"`
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+ ApiUrl string `json:"apiUrl"`
+ Status string `json:"status"`
+ Enabled bool `json:"enabled"`
}
diff --git a/backend/internal/dto/settings_dto.go b/backend/internal/dto/settings_dto.go
index 398ac587f..b03013248 100644
--- a/backend/internal/dto/settings_dto.go
+++ b/backend/internal/dto/settings_dto.go
@@ -18,6 +18,7 @@ type UpdateSettingsDto struct {
AutoUpdateInterval *string `json:"autoUpdateInterval,omitempty"`
PollingEnabled *string `json:"pollingEnabled,omitempty"`
PollingInterval *string `json:"pollingInterval,omitempty"`
+ EnvironmentHealthInterval *string `json:"environmentHealthInterval,omitempty"`
PruneMode *string `json:"dockerPruneMode,omitempty" binding:"omitempty,oneof=all dangling"`
MaxImageUploadSize *string `json:"maxImageUploadSize,omitempty"`
BaseServerURL *string `json:"baseServerUrl,omitempty"`
diff --git a/backend/internal/job/environment_health_job.go b/backend/internal/job/environment_health_job.go
new file mode 100644
index 000000000..026f10ecd
--- /dev/null
+++ b/backend/internal/job/environment_health_job.go
@@ -0,0 +1,110 @@
+package job
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/go-co-op/gocron/v2"
+ "github.com/ofkm/arcane-backend/internal/services"
+)
+
+type EnvironmentHealthJob struct {
+ environmentService *services.EnvironmentService
+ settingsService *services.SettingsService
+ scheduler *Scheduler
+}
+
+func NewEnvironmentHealthJob(scheduler *Scheduler, environmentService *services.EnvironmentService, settingsService *services.SettingsService) *EnvironmentHealthJob {
+ return &EnvironmentHealthJob{
+ environmentService: environmentService,
+ settingsService: settingsService,
+ scheduler: scheduler,
+ }
+}
+
+func (j *EnvironmentHealthJob) Register(ctx context.Context) error {
+ healthCheckInterval := j.settingsService.GetIntSetting(ctx, "environmentHealthInterval", 2)
+ interval := time.Duration(healthCheckInterval) * time.Minute
+
+ // Ensure minimum interval of 1 minute
+ if interval < 1*time.Minute {
+ slog.WarnContext(ctx, "environment health check interval too low; using minimum", "requested_minutes", healthCheckInterval, "effective_interval", "1m")
+ interval = 1 * time.Minute
+ }
+
+ slog.InfoContext(ctx, "registering environment health check job", "interval", interval.String())
+
+ j.scheduler.RemoveJobByName("environment-health")
+
+ jobDefinition := gocron.DurationJob(interval)
+ return j.scheduler.RegisterJob(
+ ctx,
+ "environment-health",
+ jobDefinition,
+ j.Execute,
+ true, // Run immediately on startup
+ )
+}
+
+func (j *EnvironmentHealthJob) Reschedule(ctx context.Context) error {
+ healthCheckInterval := j.settingsService.GetIntSetting(ctx, "environmentHealthInterval", 2)
+ interval := time.Duration(healthCheckInterval) * time.Minute
+
+ if interval < 1*time.Minute {
+ interval = 1 * time.Minute
+ }
+
+ slog.InfoContext(ctx, "environment health check settings changed; rescheduling", "interval", interval.String())
+
+ return j.scheduler.RescheduleDurationJobByName(ctx, "environment-health", interval, j.Execute, false)
+}
+
+func (j *EnvironmentHealthJob) Execute(ctx context.Context) error {
+ slog.InfoContext(ctx, "environment health check started")
+
+ // Get all environments using the DB directly
+ db := j.environmentService.GetDB()
+ var environments []struct {
+ ID string
+ Name string
+ Enabled bool
+ }
+
+ if err := db.WithContext(ctx).
+ Model(&struct {
+ ID string `gorm:"column:id"`
+ Name string `gorm:"column:name"`
+ Enabled bool `gorm:"column:enabled"`
+ }{}).
+ Table("environments").
+ Where("enabled = ?", true).
+ Find(&environments).Error; err != nil {
+ slog.ErrorContext(ctx, "failed to list environments for health check", "error", err)
+ return err
+ }
+
+ checkedCount := 0
+ onlineCount := 0
+ offlineCount := 0
+
+ for _, env := range environments {
+ checkedCount++
+
+ // Test connection without custom URL (will update DB status)
+ status, err := j.environmentService.TestConnection(ctx, env.ID, nil)
+ switch {
+ case err != nil:
+ slog.WarnContext(ctx, "environment health check failed", "environment_id", env.ID, "environment_name", env.Name, "status", status, "error", err)
+ offlineCount++
+ case status == "online":
+ onlineCount++
+ default:
+ offlineCount++
+ }
+ }
+
+ slog.InfoContext(ctx, "environment health check completed", "checked", checkedCount, "online", onlineCount, "offline", offlineCount)
+
+ return nil
+}
diff --git a/backend/internal/models/base.go b/backend/internal/models/base.go
index 9f39f69ee..68b292bbe 100644
--- a/backend/internal/models/base.go
+++ b/backend/internal/models/base.go
@@ -11,8 +11,8 @@ import (
type BaseModel struct {
ID string `json:"id" gorm:"primaryKey;type:text"`
- CreatedAt time.Time `json:"createdAt" sortable:"true"`
- UpdatedAt *time.Time `json:"updatedAt,omitempty"`
+ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at" sortable:"true"`
+ UpdatedAt *time.Time `json:"updatedAt,omitempty" gorm:"column:updated_at"`
}
func (m *BaseModel) BeforeCreate(_ *gorm.DB) (err error) {
diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.go
index 12732dc53..316dbfac4 100644
--- a/backend/internal/models/settings.go
+++ b/backend/internal/models/settings.go
@@ -44,12 +44,13 @@ func (s SettingVariable) AsDurationSeconds() time.Duration {
type Settings struct {
// General category
- ProjectsDirectory SettingVariable `key:"projectsDirectory" meta:"label=Projects Directory;type=text;keywords=projects,directory,path,folder,location,storage,files,compose,docker-compose;category=general;description=Configure where project files are stored" catmeta:"id=general;title=General;icon=settings;url=/settings/general;description=Core application settings and configuration"`
- DiskUsagePath SettingVariable `key:"diskUsagePath" meta:"label=Disk Usage Path;type=text;keywords=disk,usage,path,storage,folder,files;category=general;description=Path used for disk usage calculations"`
- BaseServerURL SettingVariable `key:"baseServerUrl" meta:"label=Base Server URL;type=text;keywords=base,url,server,domain,host,endpoint,address,link;category=general;description=Set the base URL for the application"`
- EnableGravatar SettingVariable `key:"enableGravatar" meta:"label=Enable Gravatar;type=boolean;keywords=gravatar,avatar,profile,picture,image,user,photo;category=general;description=Enable Gravatar profile pictures for users"`
- DefaultShell SettingVariable `key:"defaultShell" meta:"label=Default Shell;type=text;keywords=shell,default,shellpath,path,login;category=general;description=Default shell to use for commands"`
- AccentColor SettingVariable `key:"accentColor,public,local" meta:"label=Accent Color;type=text;keywords=color,accent,theme,css,appearance,ui;category=general;description=Primary accent color for UI"`
+ ProjectsDirectory SettingVariable `key:"projectsDirectory" meta:"label=Projects Directory;type=text;keywords=projects,directory,path,folder,location,storage,files,compose,docker-compose;category=general;description=Configure where project files are stored" catmeta:"id=general;title=General;icon=settings;url=/settings/general;description=Core application settings and configuration"`
+ DiskUsagePath SettingVariable `key:"diskUsagePath" meta:"label=Disk Usage Path;type=text;keywords=disk,usage,path,storage,folder,files;category=general;description=Path used for disk usage calculations"`
+ BaseServerURL SettingVariable `key:"baseServerUrl" meta:"label=Base Server URL;type=text;keywords=base,url,server,domain,host,endpoint,address,link;category=general;description=Set the base URL for the application"`
+ EnableGravatar SettingVariable `key:"enableGravatar" meta:"label=Enable Gravatar;type=boolean;keywords=gravatar,avatar,profile,picture,image,user,photo;category=general;description=Enable Gravatar profile pictures for users"`
+ DefaultShell SettingVariable `key:"defaultShell" meta:"label=Default Shell;type=text;keywords=shell,default,shellpath,path,login;category=general;description=Default shell to use for commands"`
+ EnvironmentHealthInterval SettingVariable `key:"environmentHealthInterval" meta:"label=Environment Health Check Interval;type=number;keywords=environment,health,check,interval,frequency,heartbeat,status,monitoring,uptime;category=general;description=How often to check environment connectivity in minutes (default: 2)"`
+ AccentColor SettingVariable `key:"accentColor,public,local" meta:"label=Accent Color;type=text;keywords=color,accent,theme,css,appearance,ui;category=general;description=Primary accent color for UI"`
// Deprecated: OnboardingCompleted is no longer used as of the onboarding removal.
// This field is kept for backward compatibility and is automatically set to true on startup.
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 1a1780e59..44dd6fd60 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -23,15 +23,53 @@ import (
)
type EnvironmentService struct {
- db *database.DB
- httpClient *http.Client
+ db *database.DB
+ httpClient *http.Client
+ dockerService *DockerClientService
}
-func NewEnvironmentService(db *database.DB, httpClient *http.Client) *EnvironmentService {
+func NewEnvironmentService(db *database.DB, httpClient *http.Client, dockerService *DockerClientService) *EnvironmentService {
if httpClient == nil {
httpClient = http.DefaultClient
}
- return &EnvironmentService{db: db, httpClient: httpClient}
+ return &EnvironmentService{db: db, httpClient: httpClient, dockerService: dockerService}
+}
+
+func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl string) error {
+ const localEnvID = "0"
+
+ var existingEnv models.Environment
+ err := s.db.WithContext(ctx).Where("id = ?", localEnvID).First(&existingEnv).Error
+
+ if err == nil {
+ // Local environment already exists
+ return nil
+ }
+
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return fmt.Errorf("failed to check for local environment: %w", err)
+ }
+
+ // Create the local environment
+ now := time.Now()
+ localEnv := &models.Environment{
+ BaseModel: models.BaseModel{
+ ID: localEnvID,
+ CreatedAt: now,
+ UpdatedAt: &now,
+ },
+ Name: "Local Docker",
+ ApiUrl: appUrl,
+ Status: string(models.EnvironmentStatusOnline),
+ Enabled: true,
+ }
+
+ if err := s.db.WithContext(ctx).Create(localEnv).Error; err != nil {
+ return fmt.Errorf("failed to create local environment: %w", err)
+ }
+
+ slog.InfoContext(ctx, "created local environment record", "id", localEnvID)
+ return nil
}
func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environment *models.Environment) (*models.Environment, error) {
@@ -114,36 +152,76 @@ func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, id string) e
return nil
}
-func (s *EnvironmentService) TestConnection(ctx context.Context, id string) (string, error) {
+func (s *EnvironmentService) TestConnection(ctx context.Context, id string, customApiUrl *string) (string, error) {
environment, err := s.GetEnvironmentByID(ctx, id)
if err != nil {
return "error", err
}
+ // Special handling for local Docker environment (ID "0")
+ if id == "0" && customApiUrl == nil {
+ return s.testLocalDockerConnection(ctx, id)
+ }
+
+ apiUrl := environment.ApiUrl
+ if customApiUrl != nil && *customApiUrl != "" {
+ apiUrl = *customApiUrl
+ }
+
reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
- url := strings.TrimRight(environment.ApiUrl, "/") + "/api/health"
+ url := strings.TrimRight(apiUrl, "/") + "/api/health"
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, url, nil)
if err != nil {
- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))
+ if customApiUrl == nil {
+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))
+ }
return "offline", fmt.Errorf("failed to create request: %w", err)
}
resp, err := s.httpClient.Do(req)
if err != nil {
- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))
+ if customApiUrl == nil {
+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))
+ }
return "offline", fmt.Errorf("connection failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOnline))
+ if customApiUrl == nil {
+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOnline))
+ }
return "online", nil
}
- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusError))
+ if customApiUrl == nil {
+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusError))
+ }
return "error", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
+func (s *EnvironmentService) testLocalDockerConnection(ctx context.Context, id string) (string, error) {
+ // Test local Docker socket by pinging Docker
+ reqCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+
+ dockerClient, err := s.dockerService.CreateConnection(reqCtx)
+ if err != nil {
+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))
+ return "offline", fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+ defer dockerClient.Close()
+
+ _, err = dockerClient.Ping(reqCtx)
+ if err != nil {
+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))
+ return "offline", fmt.Errorf("docker ping failed: %w", err)
+ }
+
+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOnline))
+ return "online", nil
+}
+
func (s *EnvironmentService) updateEnvironmentStatusInternal(ctx context.Context, id, status string) error {
now := time.Now()
updates := map[string]interface{}{
diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.go
index 6c4deb4c2..707e40c12 100644
--- a/backend/internal/services/settings_service.go
+++ b/backend/internal/services/settings_service.go
@@ -101,6 +101,7 @@ func (s *SettingsService) getDefaultSettings() *models.Settings {
GlassEffectEnabled: models.SettingVariable{Value: "false"},
AccentColor: models.SettingVariable{Value: "oklch(0.606 0.25 292.717)"},
MaxImageUploadSize: models.SettingVariable{Value: "500"},
+ EnvironmentHealthInterval: models.SettingVariable{Value: "2"},
InstanceID: models.SettingVariable{Value: ""},
}
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 2bf606312..b2b50ac76 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -112,6 +112,8 @@
"common_loading": "Loading…",
"common_enabled": "Enabled",
"common_disabled": "Disabled",
+ "common_enable": "Enable",
+ "common_disable": "Disable",
"common_online": "Online",
"common_offline": "Offline",
"common_copy": "Copy",
@@ -749,6 +751,32 @@
"environments_switch_to_edit_title": "Switch Environment",
"environments_switch_to_edit_message": "In order to change these settings, you must first switch to this environment. Would you like to switch now?",
"environments_switch_and_edit": "Switch & Edit Settings",
+ "environments_unsaved_changes": "Unsaved changes",
+ "environments_all_changes_saved": "All changes saved",
+ "environments_basic_info_description": "Basic environment information and settings",
+ "environments_enable_disable_description": "Enable or disable this environment",
+ "environments_last_seen_label": "Last Seen",
+ "environments_local_badge": "Local",
+ "environments_docker_settings_title": "Docker Settings",
+ "environments_config_description": "Configuration for this environment",
+ "environments_connection_description": "API endpoint and connection testing",
+ "environments_api_url_help": "The base URL for the environment's API",
+ "environments_bootstrap_required": "Bootstrap token is required",
+ "environments_agent_paired_success": "Agent paired successfully",
+ "environments_agent_pair_failed": "Failed to pair/rotate agent token",
+ "environments_changes_reset": "Changes reset",
+ "environments_warning_disabled": "This environment is disabled. You can edit its configuration, but you won't be able to access its resources until it's re-enabled.",
+ "environments_warning_offline": "This environment is offline or unreachable. You can still edit its configuration and test the connection to diagnose the issue.",
+ "environments_warning_no_settings": "Unable to load settings for this environment. It may be offline, disabled, or have an invalid URL. You can still edit basic environment details.",
+ "environments_local_setting_disabled": "This setting cannot be changed for the local environment",
+ "environments_health_check_title": "Environment Health Monitoring",
+ "environments_health_check_description": "Automatic monitoring of environment connectivity and status",
+ "environments_health_check_interval_label": "Health Check Interval",
+ "environments_health_check_interval_description": "How often to check environment connectivity (in minutes). Default: 2 minutes.",
+ "environments_use_environment": "Use Environment",
+ "environments_current_environment": "Current Environment",
+ "environments_switched_to": "Switched to {name}",
+ "environments_cannot_switch_disabled": "Cannot switch to a disabled environment",
"_comment_users": "=== USERS ===",
"users_title": "Users",
diff --git a/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte b/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte
index d64ddaf08..4b63665ff 100644
--- a/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte
+++ b/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte
@@ -35,8 +35,7 @@
async function handleEnvSelect(envId: string) {
const env = environmentStore.available.find((e) => e.id === envId);
- if (!env) return;
-
+ if (!env || !env.enabled) return;
try {
await environmentStore.setEnvironment(env);
} catch (error) {
@@ -45,16 +44,8 @@
}
}
- function getEnvLabel(env: Environment): string {
- if (env.isLocal) {
- return 'Local Docker';
- } else {
- return env.name;
- }
- }
-
function getConnectionString(env: Environment): string {
- if (env.isLocal) {
+ if (env.id === '0') {
return $settingsStore.dockerHost || 'unix:///var/run/docker.sock';
} else {
return env.apiUrl;
@@ -108,7 +99,7 @@
<div class="space-y-3">
<div class="flex items-start gap-3">
<div class="bg-primary/10 text-primary flex aspect-square size-8 shrink-0 items-center justify-center rounded-lg">
- {#if environmentStore.selected?.isLocal}
+ {#if environmentStore.selected?.id === '0'}
<ServerIcon class="size-4" />
{:else}
<RouterIcon class="size-4" />
@@ -119,7 +110,7 @@
{m.sidebar_environment_label()}
</div>
<div class="text-foreground text-sm font-medium">
- {environmentStore.selected ? getEnvLabel(environmentStore.selected) : m.sidebar_no_environment()}
+ {environmentStore.selected ? environmentStore.selected.name : m.sidebar_no_environment()}
</div>
{#if environmentStore.selected}
<div class="text-muted-foreground/60 text-xs">
@@ -135,8 +126,8 @@
</Select.Trigger>
<Select.Content class="max-w-[280px] min-w-[160px]">
{#each environmentStore.available as env (env.id)}
- <Select.Item value={env.id} class="text-sm">
- {getEnvLabel(env)}
+ <Select.Item value={env.id} disabled={!env.enabled} class="text-sm">
+ {env.name}
</Select.Item>
{/each}
</Select.Content>
diff --git a/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte b/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte
index 04305df74..774143b8f 100644
--- a/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte
@@ -32,6 +32,7 @@
});
async function handleSelect(env: Environment) {
+ if (!env || !env.enabled) return;
try {
await environmentStore.setEnvironment(env);
} catch (error) {
@@ -40,16 +41,8 @@
}
}
- function getEnvLabel(env: Environment): string {
- if (env.isLocal) {
- return 'Local Docker';
- } else {
- return env.name;
- }
- }
-
function getConnectionString(env: Environment): string {
- if (env.isLocal) {
+ if (env.id === '0') {
return $settingsStore.dockerHost || 'unix:///var/run/docker.sock';
} else {
return env.apiUrl;
@@ -65,12 +58,12 @@
<Sidebar.MenuButton
{...childProps}
size="lg"
- tooltipContent={environmentStore.selected ? getEnvLabel(environmentStore.selected) : m.sidebar_no_environment()}
+ tooltipContent={environmentStore.selected ? environmentStore.selected.name : m.sidebar_no_environment()}
class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
>
{#if environmentStore.selected}
<div class="bg-primary text-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
- {#if environmentStore.selected.isLocal}
+ {#if environmentStore.selected.id === '0'}
<ServerIcon class="size-4" />
{:else}
<RouterIcon class="size-4" />
@@ -78,7 +71,7 @@
</div>
<div class="grid flex-1 text-left text-sm leading-tight">
<span class="truncate font-medium">
- {getEnvLabel(environmentStore.selected)}
+ {environmentStore.selected.name}
</span>
<span class="truncate text-xs">
{getConnectionString(environmentStore.selected)}
@@ -125,13 +118,16 @@
<span>{m.sidebar_no_environments()}</span>
</DropdownMenu.Item>
{:else}
- {#each environmentStore.available as env (env.id)}
+ {#each environmentStore.available.slice(0, 5) as env (env.id)}
{@const isActive = environmentStore.selected?.id === env.id}
+ {@const isDisabled = !env.enabled}
<DropdownMenu.Item
- onSelect={() => !isActive && handleSelect(env)}
+ onSelect={() => !isActive && !isDisabled && handleSelect(env)}
+ disabled={isDisabled}
class={cn(
'gap-2 p-2',
- isActive && 'bg-sidebar-accent text-sidebar-accent-foreground pointer-events-none font-medium'
+ isActive && 'bg-sidebar-accent text-sidebar-accent-foreground pointer-events-none font-medium',
+ isDisabled && 'cursor-not-allowed opacity-50'
)}
>
<div
@@ -140,20 +136,29 @@
isActive ? 'bg-primary border-primary' : 'border-border'
)}
>
- {#if env.isLocal}
+ {#if env.id === '0'}
<ServerIcon class={cn('size-3.5 shrink-0', isActive && 'text-primary-foreground')} />
{:else}
<RouterIcon class={cn('size-3.5 shrink-0', isActive && 'text-primary-foreground')} />
{/if}
</div>
<div class="flex flex-col">
- <span>{getEnvLabel(env)}</span>
+ <span>{env.name}</span>
<span class={cn('text-xs', isActive ? 'text-sidebar-accent-foreground/70' : 'text-muted-foreground')}>
{getConnectionString(env)}
</span>
</div>
</DropdownMenu.Item>
{/each}
+ {#if environmentStore.available.length > 5}
+ <DropdownMenu.Separator />
+ <DropdownMenu.Item class="text-muted-foreground gap-2 p-2" onSelect={() => goto('/environments')}>
+ <div class="flex size-6 items-center justify-center rounded-md border bg-transparent">
+ <PlusIcon class="size-4" />
+ </div>
+ <div class="font-medium">View all {environmentStore.available.length} environments</div>
+ </DropdownMenu.Item>
+ {/if}
{/if}
{#if isAdmin}
<DropdownMenu.Separator />
diff --git a/frontend/src/lib/services/env-mgmt-service.ts b/frontend/src/lib/services/env-mgmt-service.ts
index 6edb143fe..73def4448 100644
--- a/frontend/src/lib/services/env-mgmt-service.ts
+++ b/frontend/src/lib/services/env-mgmt-service.ts
@@ -30,8 +30,8 @@ export default class EnvironmentManagementService extends BaseAPIService {
await this.api.delete(`/environments/${environmentId}`);
}
- async testConnection(environmentId: string): Promise<{ status: 'online' | 'offline'; message?: string }> {
- const res = await this.api.post(`/environments/${environmentId}/test`);
+ async testConnection(environmentId: string, apiUrl?: string): Promise<{ status: 'online' | 'offline'; message?: string }> {
+ const res = await this.api.post(`/environments/${environmentId}/test`, apiUrl ? { apiUrl } : undefined);
return res.data.data as { status: 'online' | 'offline'; message?: string };
}
}
diff --git a/frontend/src/lib/stores/environment.store.svelte.ts b/frontend/src/lib/stores/environment.store.svelte.ts
index a3a816bab..22166d10f 100644
--- a/frontend/src/lib/stores/environment.store.svelte.ts
+++ b/frontend/src/lib/stores/environment.store.svelte.ts
@@ -4,17 +4,6 @@ import type { Environment } from '$lib/types/environment.type';
export const LOCAL_DOCKER_ENVIRONMENT_ID = '0';
-export const localDockerEnvironment: Environment = {
- id: LOCAL_DOCKER_ENVIRONMENT_ID,
- name: 'Local Docker',
- apiUrl: 'http://localhost',
- status: 'online',
- enabled: true,
- lastSeen: new Date().toISOString(),
- createdAt: new Date().toISOString(),
- isLocal: true
-};
-
function createEnvironmentManagementStore() {
const selectedEnvironmentId = new PersistedState<string | null>('selectedEnvironmentId', null);
@@ -28,16 +17,14 @@ function createEnvironmentManagementStore() {
_resolveReadyPromiseFunction = resolve;
});
- function _updateAvailable(environments: Environment[], hasLocalDocker: boolean): Environment[] {
- const newAvailable: Environment[] = [];
-
- if (hasLocalDocker) {
- newAvailable.push(localDockerEnvironment);
- }
-
- newAvailable.push(...environments.map((env) => ({ ...env, isLocal: false })));
- _availableEnvironments = newAvailable;
- return newAvailable;
+ function _updateAvailable(environments: Environment[]): Environment[] {
+ const sorted = [...environments].sort((a, b) => {
+ if (a.id === LOCAL_DOCKER_ENVIRONMENT_ID) return -1;
+ if (b.id === LOCAL_DOCKER_ENVIRONMENT_ID) return 1;
+ return 0;
+ });
+ _availableEnvironments = sorted;
+ return sorted;
}
function _selectInitialEnvironment(available: Environment[]): Environment | null {
@@ -45,20 +32,22 @@ function createEnvironmentManagementStore() {
if (savedId) {
const found = available.find((env) => env.id === savedId);
- if (found) {
+ if (found && found.enabled) {
_selectedEnvironment = found;
return found;
}
}
- if (available.some((env) => env.id === localDockerEnvironment.id)) {
- _selectedEnvironment = localDockerEnvironment;
- return localDockerEnvironment;
+ const localEnv = available.find((env) => env.id === LOCAL_DOCKER_ENVIRONMENT_ID);
+ if (localEnv && localEnv.enabled) {
+ _selectedEnvironment = localEnv;
+ return localEnv;
}
- if (available.length > 0) {
- _selectedEnvironment = available[0];
- return available[0];
+ const firstEnabled = available.find((env) => env.enabled);
+ if (firstEnabled) {
+ _selectedEnvironment = firstEnabled;
+ return firstEnabled;
}
_selectedEnvironment = null;
@@ -72,8 +61,8 @@ function createEnvironmentManagementStore() {
get available(): Environment[] {
return _availableEnvironments;
},
- initialize: async (environmentsData: Environment[], hasLocalDocker: boolean) => {
- const available = _updateAvailable(environmentsData, hasLocalDocker);
+ initialize: async (environmentsData: Environment[]) => {
+ const available = _updateAvailable(environmentsData);
const hasRealEnvironments = environmentsData.length > 0;
if (!_initialized) {
@@ -87,14 +76,26 @@ function createEnvironmentManagementStore() {
_selectInitialEnvironment(available);
_initializedWithData = true;
} else {
- if (_selectedEnvironment && !available.find((env) => env.id === _selectedEnvironment!.id)) {
- _selectInitialEnvironment(available);
- } else if (!_selectedEnvironment && available.length > 0) {
+ // Update the selected environment's data if it exists
+ if (_selectedEnvironment) {
+ const updated = available.find((env) => env.id === _selectedEnvironment!.id);
+ if (updated) {
+ _selectedEnvironment = updated;
+ // If the current environment was disabled, switch to an enabled one
+ if (!updated.enabled) {
+ _selectInitialEnvironment(available);
+ }
+ } else {
+ // Environment no longer exists, select a new one
+ _selectInitialEnvironment(available);
+ }
+ } else if (available.length > 0) {
_selectInitialEnvironment(available);
}
}
},
setEnvironment: async (environment: Environment) => {
+ if (!environment.enabled) return;
if (_selectedEnvironment?.id !== environment.id) {
_selectedEnvironment = environment;
selectedEnvironmentId.current = environment.id;
@@ -102,7 +103,7 @@ function createEnvironmentManagementStore() {
}
},
isInitialized: () => _initialized,
- getLocalEnvironment: () => localDockerEnvironment,
+ getLocalEnvironment: () => _availableEnvironments.find((env) => env.id === LOCAL_DOCKER_ENVIRONMENT_ID) || null,
ready: _readyPromise,
getCurrentEnvironmentId: async (): Promise<string> => {
await _readyPromise;
diff --git a/frontend/src/lib/types/environment.type.ts b/frontend/src/lib/types/environment.type.ts
index 225e4fd3e..cb2e8cb92 100644
--- a/frontend/src/lib/types/environment.type.ts
+++ b/frontend/src/lib/types/environment.type.ts
@@ -1,16 +1,13 @@
export type EnvironmentStatus = 'online' | 'offline' | 'error';
-export interface Environment {
+export type Environment = {
id: string;
name: string;
apiUrl: string;
status: EnvironmentStatus;
enabled: boolean;
lastSeen?: string;
- createdAt: string;
- updatedAt?: string;
- isLocal?: boolean;
-}
+};
export interface CreateEnvironmentDTO {
apiUrl: string;
diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.ts
index 44813c2d6..f23291d01 100644
--- a/frontend/src/lib/types/settings.type.ts
+++ b/frontend/src/lib/types/settings.type.ts
@@ -14,6 +14,7 @@ export type Settings = {
autoUpdateInterval: number;
pollingEnabled: boolean;
pollingInterval: number;
+ environmentHealthInterval: number;
dockerPruneMode: 'all' | 'dangling';
maxImageUploadSize: number;
baseServerUrl: string;
diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.ts
index fe12a785f..4f8bf7d5e 100644
--- a/frontend/src/routes/+layout.ts
+++ b/frontend/src/routes/+layout.ts
@@ -13,7 +13,7 @@ export const ssr = false;
export const load = async () => {
if (!environmentStore.isInitialized()) {
- await environmentStore.initialize([], true);
+ await environmentStore.initialize([]);
}
const userPromise = userService.getCurrentUser().catch(() => null);
@@ -33,7 +33,7 @@ export const load = async () => {
if (user) {
const environments = await tryCatch(environmentManagementService.getEnvironments(environmentRequestOptions));
if (!environments.error) {
- await environmentStore.initialize(environments.data.data, true);
+ await environmentStore.initialize(environments.data.data);
}
}
return null;
diff --git a/frontend/src/routes/dashboard/+page.svelte b/frontend/src/routes/dashboard/+page.svelte
index da44cb84b..1889d4a8d 100644
--- a/frontend/src/routes/dashboard/+page.svelte
+++ b/frontend/src/routes/dashboard/+page.svelte
@@ -193,11 +193,17 @@
statsWSClient.connect();
}
+ let lastEnvId: string | null = null;
$effect(() => {
const env = environmentStore.selected;
if (!env) return;
- if (statsWSClient) {
- statsWSClient.close();
+ if (lastEnvId === null) {
+ lastEnvId = env.id;
+ return;
+ }
+ if (env.id !== lastEnvId) {
+ lastEnvId = env.id;
+ statsWSClient?.close();
statsWSClient = null;
resetStats();
setupStatsWS();
diff --git a/frontend/src/routes/environments/+page.svelte b/frontend/src/routes/environments/+page.svelte
index 756b443f1..83fd87577 100644
--- a/frontend/src/routes/environments/+page.svelte
+++ b/frontend/src/routes/environments/+page.svelte
@@ -69,7 +69,7 @@
const msg = m.common_bulk_remove_success({ count: successCount, resource: m.environments_title() });
toast.success(msg);
await refresh();
- await environmentStore.initialize(environments.data, true);
+ await environmentStore.initialize(environments.data);
}
if (failureCount > 0) {
const msg = m.common_bulk_remove_failed({ count: failureCount, resource: m.environments_title() });
@@ -85,7 +85,7 @@
async function onEnvironmentCreated() {
showEnvironmentSheet = false;
environments = await environmentManagementService.getEnvironments(requestOptions);
- await environmentStore.initialize(environments.data, true);
+ await environmentStore.initialize(environments.data);
toast.success(m.common_create_success({ resource: m.resource_environment() }));
refresh();
}
diff --git a/frontend/src/routes/environments/[id]/+page.svelte b/frontend/src/routes/environments/[id]/+page.svelte
index 25d1c4eba..777a1b695 100644
--- a/frontend/src/routes/environments/[id]/+page.svelte
+++ b/frontend/src/routes/environments/[id]/+page.svelte
@@ -2,16 +2,23 @@
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
import * as AlertDialog from '$lib/components/ui/alert-dialog';
+ import * as Tooltip from '$lib/components/ui/tooltip/index.js';
import ArrowLeftIcon from '@lucide/svelte/icons/arrow-left';
import RefreshCwIcon from '@lucide/svelte/icons/refresh-cw';
import MonitorIcon from '@lucide/svelte/icons/monitor';
import TerminalIcon from '@lucide/svelte/icons/terminal';
import SettingsIcon from '@lucide/svelte/icons/settings';
import GlobeIcon from '@lucide/svelte/icons/globe';
+ import SaveIcon from '@lucide/svelte/icons/save';
+ import RotateCcwIcon from '@lucide/svelte/icons/rotate-ccw';
+ import AlertTriangleIcon from '@lucide/svelte/icons/alert-triangle';
import { goto, invalidateAll } from '$app/navigation';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import { toast } from 'svelte-sonner';
import Label from '$lib/components/ui/label/label.svelte';
+ import { Input } from '$lib/components/ui/input/index.js';
+ import { Switch } from '$lib/components/ui/switch/index.js';
+ import { Badge } from '$lib/components/ui/badge/index.js';
import { m } from '$lib/paraglide/messages';
import { environmentManagementService } from '$lib/services/env-mgmt-service.js';
import { environmentStore } from '$lib/stores/environment.store.svelte';
@@ -26,24 +33,45 @@
let isRefreshing = $state(false);
let isTestingConnection = $state(false);
let isPairing = $state(false);
+ let isSaving = $state(false);
let bootstrapToken = $state('');
- let activeSection = $state<string>('overview');
+ // Form state
+ let formName = $state('');
+ let formEnabled = $state(false);
+ let formApiUrl = $state('');
- const sections = [
- { id: 'overview', Label: m.environments_section_overview, icon: MonitorIcon },
- { id: 'connection', Label: m.environments_section_connection, icon: GlobeIcon },
- { id: 'pairing', Label: m.environments_section_pairing, icon: SettingsIcon }
- ];
+ // Track current status separately from environment data
+ let currentStatus = $state<'online' | 'offline' | 'error'>('offline');
+
+ // Initialize form values and status
+ $effect(() => {
+ formName = environment.name;
+ formEnabled = environment.enabled;
+ formApiUrl = environment.apiUrl;
+ currentStatus = environment.status;
+ });
+
+ // Track changes
+ let hasChanges = $derived(
+ formName !== environment.name ||
+ formEnabled !== environment.enabled ||
+ (environment.id !== '0' && formApiUrl !== environment.apiUrl)
+ );
async function refreshEnvironment() {
if (isRefreshing) return;
try {
isRefreshing = true;
await invalidateAll();
+ // Update form values after refresh
+ formName = environment.name;
+ formEnabled = environment.enabled;
+ formApiUrl = environment.apiUrl;
+ currentStatus = environment.status;
} catch (err) {
console.error('Failed to refresh environment:', err);
- toast.error('Failed to refresh environment data');
+ toast.error(m.common_refresh_failed({ resource: m.resource_environment() }));
} finally {
isRefreshing = false;
}
@@ -53,41 +81,89 @@
if (isTestingConnection) return;
try {
isTestingConnection = true;
- const result = await environmentManagementService.testConnection(environment.id);
+ const customUrl = formApiUrl !== environment.apiUrl ? formApiUrl : undefined;
+ const result = await environmentManagementService.testConnection(environment.id, customUrl);
+
+ // Update current status based on test result
+ currentStatus = result.status;
+
if (result.status === 'online') {
- toast.success('Connection successful');
+ toast.success(m.environments_test_connection_success());
} else {
- toast.error(`Connection failed: ${result.message || 'Unknown error'}`);
+ toast.error(m.environments_test_connection_error());
+ }
+
+ // If testing with saved URL (not custom), refresh to get backend's updated status
+ if (!customUrl) {
+ await invalidateAll();
}
- await refreshEnvironment();
} catch (error) {
- toast.error('Failed to test connection');
+ // Update status to offline on error
+ currentStatus = 'offline';
+ toast.error(m.environments_test_connection_failed());
console.error(error);
} finally {
isTestingConnection = false;
}
}
-
async function pairOrRotate() {
if (!bootstrapToken) {
- toast.error('Bootstrap token is required');
+ toast.error(m.environments_bootstrap_required());
return;
}
try {
isPairing = true;
await environmentManagementService.update(environment.id, { bootstrapToken });
- toast.success('Agent paired successfully');
+ toast.success(m.environments_agent_paired_success());
bootstrapToken = '';
- await refreshEnvironment();
+ await invalidateAll();
} catch (e) {
console.error(e);
- toast.error('Failed to pair/rotate agent token');
+ toast.error(m.environments_agent_pair_failed());
} finally {
isPairing = false;
}
}
- const environmentDisplayName = $derived(() => environment?.name ?? m.common_unknown());
+ async function handleSave() {
+ if (!hasChanges || isSaving) return;
+
+ try {
+ isSaving = true;
+
+ await environmentManagementService.update(environment.id, {
+ name: formName,
+ enabled: formEnabled,
+ apiUrl: formApiUrl
+ });
+
+ toast.success(m.common_update_success({ resource: m.resource_environment_cap() }));
+ await refreshEnvironment();
+
+ // Update environment store if this is the current environment
+ if (currentEnvironment?.id === environment.id) {
+ await environmentStore.initialize(
+ (
+ await environmentManagementService.getEnvironments({
+ pagination: { page: 1, limit: 1000 }
+ })
+ ).data
+ );
+ }
+ } catch (error) {
+ console.error('Failed to save environment:', error);
+ toast.error(m.common_update_failed({ resource: m.resource_environment() }));
+ } finally {
+ isSaving = false;
+ }
+ }
+
+ function handleReset() {
+ formName = environment.name;
+ formEnabled = environment.enabled;
+ formApiUrl = environment.apiUrl;
+ toast.info(m.environments_changes_reset());
+ }
const needsEnvironmentSwitch = $derived(() => {
return currentEnvironment?.id !== environment?.id;
@@ -108,351 +184,292 @@
goto('/settings');
} catch (error) {
console.error('Failed to switch environment:', error);
- toast.error('Failed to switch environment');
+ toast.error(m.common_action_failed());
}
}
</script>
-<div class="space-y-6 pb-16">
- <div class="flex items-center justify-between">
- <div class="flex items-center gap-4">
- <Button variant="ghost" size="icon" onclick={() => goto('/environments')}>
- <ArrowLeftIcon class="size-4" />
- </Button>
- <div>
- <h1 class="text-3xl font-bold tracking-tight">{environmentDisplayName()}</h1>
- <p class="text-muted-foreground mt-1 text-sm">{m.environments_page_subtitle()}</p>
+<div class="container mx-auto max-w-full space-y-6 overflow-hidden p-2 pb-16 sm:p-6">
+ <div class="space-y-3 sm:space-y-4">
+ <Button variant="ghost" onclick={() => goto('/environments')} class="w-fit gap-2">
+ <ArrowLeftIcon class="size-4" />
+ <span>{m.common_back_to({ resource: m.environments_title() })}</span>
+ </Button>
+
+ <div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
+ <div class="flex-1">
+ <h1 class="text-xl font-bold wrap-break-word sm:text-2xl">{environment.name}</h1>
+ <p class="text-muted-foreground mt-1.5 text-sm wrap-break-word sm:text-base">{m.environments_page_subtitle()}</p>
</div>
- </div>
- <div class="flex items-center gap-2">
- <Button variant="outline" onclick={testConnection} disabled={isTestingConnection}>
- {#if isTestingConnection}
- <RefreshCwIcon class="mr-2 size-4 animate-spin" />
- {m.environments_testing_connection()}
+
+ <div class="flex flex-wrap items-center gap-2">
+ {#if hasChanges}
+ <span class="text-xs text-orange-600 dark:text-orange-400">{m.environments_unsaved_changes()}</span>
{:else}
- <TerminalIcon class="mr-2 size-4" />
- {m.environments_test_connection()}
+ <span class="text-xs text-green-600 dark:text-green-400">{m.environments_all_changes_saved()}</span>
{/if}
- </Button>
- <Button onclick={refreshEnvironment} disabled={isRefreshing}>
- {#if isRefreshing}
- <RefreshCwIcon class="mr-2 size-4 animate-spin" />
- {:else}
- <RefreshCwIcon class="mr-2 size-4" />
+
+ {#if hasChanges}
+ <Button variant="outline" size="sm" onclick={handleReset} disabled={isSaving}>
+ <RotateCcwIcon class="mr-2 size-4" />
+ {m.common_reset()}
+ </Button>
{/if}
- {m.common_refresh()}
- </Button>
+
+ <Button size="sm" onclick={handleSave} disabled={!hasChanges || isSaving}>
+ {#if isSaving}
+ <div class="border-background mr-2 size-4 animate-spin rounded-full border-2 border-t-transparent"></div>
+ {m.common_saving()}
+ {:else}
+ <SaveIcon class="mr-2 size-4" />
+ {m.common_save()}
+ {/if}
+ </Button>
+
+ <Button variant="outline" onclick={refreshEnvironment} disabled={isRefreshing}>
+ {#if isRefreshing}
+ <RefreshCwIcon class="mr-2 size-4 animate-spin" />
+ {:else}
+ <RefreshCwIcon class="mr-2 size-4" />
+ {/if}
+ {m.common_refresh()}
+ </Button>
+ </div>
</div>
- </div>
- <div class="grid grid-cols-1 gap-6 lg:grid-cols-4">
- <div class="lg:col-span-1">
- <Card.Root class="flex flex-col gap-6 py-3">
- <Card.Header
- class="@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6"
- >
- <Card.Title class="text-lg">{m.environments_sections_title()}</Card.Title>
- </Card.Header>
- <Card.Content class="p-0 px-6">
- <nav class="space-y-1">
- {#each sections as section}
- {@const Icon = section.icon}
- <button
- onclick={() => (activeSection = section.id)}
- class="hover:bg-muted flex w-full items-center gap-3 px-4 py-3 text-left transition-colors {activeSection ===
- section.id
- ? 'bg-muted border-primary border-r-2'
- : ''}"
- >
- <Icon class="size-4" />
- {section.Label()}
- </button>
- {/each}
- </nav>
- </Card.Content>
- </Card.Root>
+ <div class="flex flex-wrap items-center gap-2">
+ <Badge variant="outline" class="gap-1">
+ <div class="size-2 rounded-full {currentStatus === 'online' ? 'bg-green-500' : 'bg-red-500'}"></div>
+ {currentStatus === 'online' ? m.common_online() : m.common_offline()}
+ </Badge>
+ <Badge variant="outline" class="gap-1">
+ {environment.enabled ? m.common_enabled() : m.common_disabled()}
+ </Badge>
+ {#if environment.id === '0'}
+ <Badge variant="outline">{m.environments_local_badge()}</Badge>
+ {/if}
</div>
- <div class="lg:col-span-3">
- {#if activeSection === 'overview'}
- <div class="space-y-6">
- <Card.Root class="flex flex-col gap-6 py-3">
- <Card.Header
- class="@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6"
- >
- <Card.Title class="flex items-center gap-2">
- <MonitorIcon class="size-5" />
- {m.environments_overview_title()}
- </Card.Title>
- </Card.Header>
- <Card.Content class="space-y-6 px-6">
- <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
- <div class="space-y-4">
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.common_name()}</Label>
- <div class="mt-1 text-lg font-semibold">{environmentDisplayName()}</div>
- </div>
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.common_status()}</Label>
- <div class="mt-1">
- <StatusBadge
- text={environment.status === 'online' ? m.common_online() : m.common_offline()}
- variant={environment.status === 'online' ? 'green' : 'red'}
- />
- </div>
- </div>
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.common_enabled()}</Label>
- <div class="mt-1">
- <StatusBadge
- text={environment.enabled ? m.common_enabled() : m.common_disabled()}
- variant={environment.enabled ? 'green' : 'gray'}
- />
- </div>
- </div>
- </div>
- <div class="space-y-4">
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.environments_environment_id_label()}</Label>
- <div class="bg-muted mt-1 rounded px-2 py-1 font-mono text-sm">{environment.id}</div>
- </div>
- </div>
- </div>
+ {#if !environment.enabled || currentStatus === 'offline' || !settings}
+ <div
+ class="flex items-start gap-3 rounded-lg border border-amber-500/30 bg-amber-500/10 p-4 text-amber-900 dark:text-amber-200"
+ >
+ <AlertTriangleIcon class="mt-0.5 size-5 shrink-0 text-amber-600 dark:text-amber-400" />
+ <div class="flex-1 space-y-1">
+ <p class="text-sm font-medium">
+ {#if !environment.enabled}
+ {m.environments_warning_disabled()}
+ {:else if currentStatus === 'offline'}
+ {m.environments_warning_offline()}
+ {:else if !settings}
+ {m.environments_warning_no_settings()}
+ {/if}
+ </p>
+ </div>
+ </div>
+ {/if}
+ </div>
- {#if settings}
- <div class="border-t pt-6">
- <div class="mb-4 flex items-center justify-between">
- <h3 class="text-lg font-semibold">
- {environment.id === '0' ? m.sidebar_settings() : 'Docker & Operational Settings'}
- </h3>
- {#if environment.id === '0'}
- <Button variant="outline" size="sm" onclick={handleEditSettings}>
- <SettingsIcon class="mr-2 size-4" />
- {m.common_edit()}
- </Button>
- {/if}
- </div>
-
- <!-- Docker Settings -->
- <div class="mb-6">
- <h4 class="text-muted-foreground mb-3 text-sm font-semibold tracking-wide uppercase">{m.docker_title()}</h4>
- <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.docker_enable_polling_label()}</Label>
- <div class="mt-1">
- <StatusBadge
- text={settings.pollingEnabled ? m.common_enabled() : m.common_disabled()}
- variant={settings.pollingEnabled ? 'green' : 'gray'}
- />
- </div>
- </div>
- {#if settings.pollingEnabled}
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.docker_polling_interval_label()}</Label>
- <div class="mt-1 text-sm">{settings.pollingInterval} min</div>
- </div>
- {/if}
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.docker_auto_update_label()}</Label>
- <div class="mt-1">
- <StatusBadge
- text={settings.autoUpdate ? m.common_enabled() : m.common_disabled()}
- variant={settings.autoUpdate ? 'green' : 'gray'}
- />
- </div>
- </div>
- {#if settings.autoUpdate}
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.docker_auto_update_interval_label()}</Label>
- <div class="mt-1 text-sm">{settings.autoUpdateInterval} min</div>
- </div>
- {/if}
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.docker_prune_action_label()}</Label>
- <div class="mt-1 text-sm capitalize">{settings.dockerPruneMode || 'dangling'}</div>
- </div>
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.docker_default_shell_label()}</Label>
- <div class="bg-muted mt-1 rounded px-2 py-1 font-mono text-sm">{settings.defaultShell || '/bin/sh'}</div>
- </div>
- </div>
- </div>
-
- <!-- General Settings -->
- <div class="mb-6">
- <h4 class="text-muted-foreground mb-3 text-sm font-semibold tracking-wide uppercase">{m.general_title()}</h4>
- <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.general_projects_directory_label()}</Label>
- <div class="bg-muted mt-1 rounded px-2 py-1 font-mono text-sm">
- {settings.projectsDirectory || 'data/projects'}
- </div>
- </div>
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.general_base_url_label()}</Label>
- <div class="bg-muted mt-1 rounded px-2 py-1 font-mono text-sm">
- {settings.baseServerUrl || 'http://localhost'}
- </div>
- </div>
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.general_enable_gravatar_label()}</Label>
- <div class="mt-1">
- <StatusBadge
- text={settings.enableGravatar ? m.common_enabled() : m.common_disabled()}
- variant={settings.enableGravatar ? 'green' : 'gray'}
- />
- </div>
- </div>
- </div>
- </div>
-
- <!-- Security Settings -->
- {#if environment.id === '0' && settings.authLocalEnabled !== undefined}
- <div class="mb-6">
- <h4 class="text-muted-foreground mb-3 text-sm font-semibold tracking-wide uppercase">
- {m.security_title()}
- </h4>
- <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.security_local_auth_label()}</Label>
- <div class="mt-1">
- <StatusBadge
- text={settings.authLocalEnabled ? m.common_enabled() : m.common_disabled()}
- variant={settings.authLocalEnabled ? 'green' : 'gray'}
- />
- </div>
- </div>
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.security_oidc_auth_label()}</Label>
- <div class="mt-1">
- <StatusBadge
- text={settings.authOidcEnabled ? m.common_enabled() : m.common_disabled()}
- variant={settings.authOidcEnabled ? 'green' : 'gray'}
- />
- </div>
- </div>
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.security_session_timeout_label()}</Label>
- <div class="mt-1 text-sm">{settings.authSessionTimeout || 1440} min</div>
- </div>
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.security_password_policy_label()}</Label>
- <div class="mt-1 text-sm capitalize">{settings.authPasswordPolicy || 'strong'}</div>
- </div>
- </div>
- </div>
- {/if}
-
- <!-- Navigation Settings -->
- {#if environment.id === '0' && settings.mobileNavigationMode !== undefined}
- <div>
- <h4 class="text-muted-foreground mb-3 text-sm font-semibold tracking-wide uppercase">
- {m.navigation_title()}
- </h4>
- <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.navigation_mode_label()}</Label>
- <div class="mt-1 text-sm capitalize">{settings.mobileNavigationMode || 'floating'}</div>
- </div>
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.navigation_show_labels_label()}</Label>
- <div class="mt-1">
- <StatusBadge
- text={settings.mobileNavigationShowLabels ? m.common_enabled() : m.common_disabled()}
- variant={settings.mobileNavigationShowLabels ? 'green' : 'gray'}
- />
- </div>
- </div>
- </div>
- </div>
- {/if}
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
+ <div class="grid gap-6 gap-x-6 gap-y-6 lg:grid-cols-2">
+ <Card.Root class="flex flex-col">
+ <Card.Header icon={MonitorIcon}>
+ <div class="flex flex-col space-y-1.5">
+ <Card.Title>
+ <h2>{m.environments_overview_title()}</h2>
+ </Card.Title>
+ <Card.Description>{m.environments_basic_info_description()}</Card.Description>
</div>
- {:else if activeSection === 'connection'}
- <div class="space-y-6">
- <Card.Root class="flex flex-col gap-6 py-3">
- <Card.Header
- class="@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6"
- >
- <Card.Title class="flex items-center gap-2">
- <GlobeIcon class="h-5 w-5" />
- {m.environments_connection_title()}
- </Card.Title>
- </Card.Header>
- <Card.Content class="space-y-4 px-6">
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.common_name()}</Label>
- <div class="mt-1 text-sm">{environmentDisplayName()}</div>
+ </Card.Header>
+ <Card.Content class="space-y-4 p-4">
+ <div>
+ <Label for="env-name" class="text-sm font-medium">{m.common_name()}</Label>
+ <Input id="env-name" type="text" bind:value={formName} class="mt-1.5" placeholder={m.environments_name_placeholder()} />
+ </div>
+
+ <div class="flex items-center justify-between rounded-lg border p-4">
+ <div class="space-y-0.5">
+ <Label for="env-enabled" class="text-sm font-medium">{m.common_enabled()}</Label>
+ <div class="text-muted-foreground text-xs">{m.environments_enable_disable_description()}</div>
+ </div>
+ {#if environment.id === '0'}
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <Switch id="env-enabled" disabled={true} bind:checked={formEnabled} />
+ </Tooltip.Trigger>
+ <Tooltip.Content>
+ <p>{m.environments_local_setting_disabled()}</p>
+ </Tooltip.Content>
+ </Tooltip.Root>
+ {:else}
+ <Switch id="env-enabled" bind:checked={formEnabled} />
+ {/if}
+ </div>
+
+ <div class="grid grid-cols-2 gap-4 rounded-lg border p-4">
+ <div>
+ <Label class="text-muted-foreground text-xs font-medium">{m.environments_environment_id_label()}</Label>
+ <div class="mt-1 font-mono text-sm">{environment.id}</div>
+ </div>
+ <div>
+ <Label class="text-muted-foreground text-xs font-medium">Status</Label>
+ <div class="mt-1">
+ <StatusBadge
+ text={currentStatus === 'online' ? m.common_online() : m.common_offline()}
+ variant={currentStatus === 'online' ? 'green' : 'red'}
+ />
+ </div>
+ </div>
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ {#if settings}
+ <Card.Root class="flex flex-col">
+ <Card.Header icon={SettingsIcon}>
+ <div class="flex flex-col space-y-1.5">
+ <Card.Title>
+ <h2>{m.environments_docker_settings_title()}</h2>
+ </Card.Title>
+ <Card.Description>{m.environments_config_description()}</Card.Description>
+ </div>
+ </Card.Header>
+ <Card.Content class="space-y-4 p-4">
+ <div class="grid grid-cols-2 gap-4">
+ <div>
+ <Label class="text-muted-foreground text-xs font-medium">{m.docker_enable_polling_label()}</Label>
+ <div class="mt-1">
+ <StatusBadge
+ text={settings.pollingEnabled ? m.common_enabled() : m.common_disabled()}
+ variant={settings.pollingEnabled ? 'green' : 'gray'}
+ />
</div>
+ </div>
+ {#if settings.pollingEnabled}
<div>
- <Label class="text-muted-foreground text-sm font-medium">{m.environments_api_url()}</Label>
- <div class="bg-muted mt-1 rounded-md px-3 py-2 font-mono text-sm break-all">{environment.apiUrl}</div>
+ <Label class="text-muted-foreground text-xs font-medium">{m.docker_polling_interval_label()}</Label>
+ <div class="mt-1 text-sm">{settings.pollingInterval} min</div>
</div>
- <div class="pt-4">
- <Button onclick={testConnection} disabled={isTestingConnection} class="w-full">
- {#if isTestingConnection}
- <RefreshCwIcon class="mr-2 h-4 w-4 animate-spin" />
- {m.environments_testing_connection()}
- {:else}
- <TerminalIcon class="mr-2 h-4 w-4" />
- {m.environments_test_connection()}
- {/if}
- </Button>
- </div>
- </Card.Content>
- </Card.Root>
- </div>
- {:else if activeSection === 'pairing'}
- <div class="space-y-6">
- <Card.Root class="flex flex-col gap-6 py-3">
- <Card.Header
- class="@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6"
- >
- <Card.Title class="flex items-center gap-2">
- <SettingsIcon class="h-5 w-5" />
- {m.environments_pair_rotate_title()}
- </Card.Title>
- <Card.Description>
- {m.environments_pair_rotate_description()}
- </Card.Description>
- </Card.Header>
- <Card.Content class="space-y-4 px-6">
- <div>
- <Label class="text-muted-foreground text-sm font-medium">{m.environments_bootstrap_label()}</Label>
- <input
- class="bg-background focus:ring-primary mt-1 w-full rounded-md border px-3 py-2 text-sm outline-none focus:ring-2"
- type="password"
- placeholder={m.environments_bootstrap_placeholder()}
- bind:value={bootstrapToken}
+ {/if}
+ <div>
+ <Label class="text-muted-foreground text-xs font-medium">{m.docker_auto_update_label()}</Label>
+ <div class="mt-1">
+ <StatusBadge
+ text={settings.autoUpdate ? m.common_enabled() : m.common_disabled()}
+ variant={settings.autoUpdate ? 'green' : 'gray'}
/>
</div>
- <div class="flex gap-2">
- <Button onclick={pairOrRotate} disabled={isPairing || !bootstrapToken}>
- {#if isPairing}
- <RefreshCwIcon class="mr-2 h-4 w-4 animate-spin" />
- {:else}
- <SettingsIcon class="mr-2 h-4 w-4" />
- {/if}
- {m.environments_pair_rotate_action()}
- </Button>
- <Button variant="outline" onclick={() => (bootstrapToken = '')} disabled={isPairing}>{m.common_clear()}</Button>
+ </div>
+ {#if settings.autoUpdate}
+ <div>
+ <Label class="text-muted-foreground text-xs font-medium">{m.docker_auto_update_interval_label()}</Label>
+ <div class="mt-1 text-sm">{settings.autoUpdateInterval} min</div>
</div>
- </Card.Content>
- </Card.Root>
+ {/if}
+ <div>
+ <Label class="text-muted-foreground text-xs font-medium">{m.docker_prune_action_label()}</Label>
+ <div class="mt-1 text-sm capitalize">{settings.dockerPruneMode || 'dangling'}</div>
+ </div>
+ <div>
+ <Label class="text-muted-foreground text-xs font-medium">{m.docker_default_shell_label()}</Label>
+ <div class="mt-1 font-mono text-sm">{settings.defaultShell || '/bin/sh'}</div>
+ </div>
+ </div>
+ </Card.Content>
+ </Card.Root>
+ {/if}
+
+ <Card.Root class="flex flex-col">
+ <Card.Header icon={GlobeIcon}>
+ <div class="flex flex-col space-y-1.5">
+ <Card.Title>
+ <h2>{m.environments_connection_title()}</h2>
+ </Card.Title>
+ <Card.Description>{m.environments_connection_description()}</Card.Description>
+ </div>
+ </Card.Header>
+ <Card.Content class="space-y-4 p-4">
+ <div>
+ <Label for="api-url" class="text-sm font-medium">{m.environments_api_url()}</Label>
+ {#if environment.id === '0'}
+ <Tooltip.Root>
+ <Tooltip.Trigger class="w-full">
+ <Input
+ id="api-url"
+ type="url"
+ bind:value={formApiUrl}
+ class="mt-1.5 font-mono"
+ placeholder={m.environments_api_url_placeholder()}
+ disabled={true}
+ required
+ />
+ </Tooltip.Trigger>
+ <Tooltip.Content>
+ <p>{m.environments_local_setting_disabled()}</p>
+ </Tooltip.Content>
+ </Tooltip.Root>
+ {:else}
+ <Input
+ id="api-url"
+ type="url"
+ bind:value={formApiUrl}
+ class="mt-1.5 font-mono"
+ placeholder={m.environments_api_url_placeholder()}
+ required
+ />
+ {/if}
+ <p class="text-muted-foreground mt-1.5 text-xs">{m.environments_api_url_help()}</p>
</div>
- {/if}
- </div>
- </div>
- {#if isRefreshing}
- <div class="fixed right-4 bottom-4 flex items-center gap-2 rounded-lg bg-blue-600 px-3 py-2 text-white shadow-lg">
- <RefreshCwIcon class="h-4 w-4 animate-spin" />
- <span class="text-sm">{m.environments_refreshing()}</span>
- </div>
- {/if}
+ <Button onclick={testConnection} disabled={isTestingConnection} class="w-full">
+ {#if isTestingConnection}
+ <RefreshCwIcon class="mr-2 size-4 animate-spin" />
+ {m.environments_testing_connection()}
+ {:else}
+ <TerminalIcon class="mr-2 size-4" />
+ {m.environments_test_connection()}
+ {/if}
+ </Button>
+ </Card.Content>
+ </Card.Root>
+
+ {#if environment.id !== '0'}
+ <Card.Root class="flex flex-col">
+ <Card.Header icon={SettingsIcon}>
+ <div class="flex flex-col space-y-1.5">
+ <Card.Title>
+ <h2>{m.environments_pair_rotate_title()}</h2>
+ </Card.Title>
+ <Card.Description>{m.environments_pair_rotate_description()}</Card.Description>
+ </div>
+ </Card.Header>
+ <Card.Content class="space-y-4 p-4">
+ <div>
+ <Label for="bootstrap-token" class="text-sm font-medium">{m.environments_bootstrap_label()}</Label>
+ <Input
+ id="bootstrap-token"
+ type="password"
+ placeholder={m.environments_bootstrap_placeholder()}
+ bind:value={bootstrapToken}
+ class="mt-1.5"
+ />
+ </div>
+ <div class="flex gap-2">
+ <Button onclick={pairOrRotate} disabled={isPairing || !bootstrapToken} class="flex-1">
+ {#if isPairing}
+ <RefreshCwIcon class="mr-2 size-4 animate-spin" />
+ {:else}
+ <SettingsIcon class="mr-2 size-4" />
+ {/if}
+ {m.environments_pair_rotate_action()}
+ </Button>
+ <Button variant="outline" onclick={() => (bootstrapToken = '')} disabled={isPairing}>
+ {m.common_clear()}
+ </Button>
+ </div>
+ </Card.Content>
+ </Card.Root>
+ {/if}
+ </div>
<AlertDialog.Root bind:open={showSwitchDialog}>
<AlertDialog.Content>
diff --git a/frontend/src/routes/environments/[id]/+page.ts b/frontend/src/routes/environments/[id]/+page.ts
index 26d01e05c..9ea5a8b36 100644
--- a/frontend/src/routes/environments/[id]/+page.ts
+++ b/frontend/src/routes/environments/[id]/+page.ts
@@ -6,7 +6,10 @@ export const load: PageLoad = async ({ params }) => {
try {
const environment = await environmentManagementService.get(params.id);
- const settings = await settingsService.getSettingsForEnvironment(params.id);
+ let settings = null;
+ try {
+ settings = await settingsService.getSettingsForEnvironment(params.id);
+ } catch {}
return {
environment,
diff --git a/frontend/src/routes/environments/environment-table.svelte b/frontend/src/routes/environments/environment-table.svelte
index f88216e9d..4c56245b5 100644
--- a/frontend/src/routes/environments/environment-table.svelte
+++ b/frontend/src/routes/environments/environment-table.svelte
@@ -21,9 +21,11 @@
import { m } from '$lib/paraglide/messages';
import { environmentManagementService } from '$lib/services/env-mgmt-service';
import CloudIcon from '@lucide/svelte/icons/cloud';
+ import PowerIcon from '@lucide/svelte/icons/power';
import environmentUpgradeService from '$lib/services/api/environment-upgrade-service';
import UpgradeConfirmationDialog from '$lib/components/dialogs/upgrade-confirmation-dialog.svelte';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { capitalizeFirstLetter } from '$lib/utils/string.utils';
let {
environments = $bindable(),
@@ -35,7 +37,7 @@
requestOptions: SearchPaginationSortRequest;
} = $props();
- let isLoading = $state({ removing: false, testing: false, upgrading: false });
+ let isLoading = $state({ removing: false, testing: false, upgrading: false, toggling: false });
let upgradingEnvironmentId = $state<string | null>(null);
let showUpgradeDialog = $state(false);
let selectedEnvironmentForUpgrade = $state<Environment | null>(null);
@@ -73,7 +75,7 @@
const msg = m.common_bulk_remove_success({ count: successCount, resource: m.environments_title() });
toast.success(msg);
environments = await environmentManagementService.getEnvironments(requestOptions);
- await environmentStore.initialize(environments.data, true);
+ await environmentStore.initialize(environments.data);
}
if (failureCount > 0) {
const msg = m.common_bulk_remove_failed({ count: failureCount, resource: m.environments_title() });
@@ -103,7 +105,7 @@
onSuccess: async () => {
toast.success(m.common_delete_success({ resource: `${m.resource_environment()} "${hostname}"` }));
environments = await environmentManagementService.getEnvironments(requestOptions);
- await environmentStore.initialize(environments.data, true);
+ await environmentStore.initialize(environments.data);
}
});
isLoading.removing = false;
@@ -119,10 +121,12 @@
result,
message: m.environments_test_connection_failed(),
setLoadingState: () => {},
- onSuccess: (resp) => {
+ onSuccess: async (resp) => {
const status = (resp as { status: string; message?: string }).status;
if (status === 'online') toast.success(m.environments_test_connection_success());
else toast.error(m.environments_test_connection_error());
+ // Refresh to get updated status from backend
+ environments = await environmentManagementService.getEnvironments(requestOptions);
}
});
isLoading.testing = false;
@@ -162,6 +166,30 @@
}
}
+ async function handleToggleEnabled(environment: Environment) {
+ const newEnabled = !environment.enabled;
+ isLoading.toggling = true;
+
+ const result = await tryCatch(environmentManagementService.update(environment.id, { enabled: newEnabled }));
+
+ handleApiResultWithCallbacks({
+ result,
+ message: m.common_update_failed({ resource: m.resource_environment() }),
+ setLoadingState: () => {},
+ onSuccess: async () => {
+ toast.success(
+ m.common_update_success({
+ resource: `${m.resource_environment()} "${environment.name}"`
+ })
+ );
+ environments = await environmentManagementService.getEnvironments(requestOptions);
+ await environmentStore.initialize(environments.data);
+ }
+ });
+
+ isLoading.toggling = false;
+ }
+
const columns = [
{ accessorKey: 'id', title: m.common_id(), hidden: true },
{
@@ -210,23 +238,28 @@
: 'bg-red-500'}"
></div>
</div>
- <div>
- <div class="font-medium">{item.name}</div>
- <div class="text-muted-foreground font-mono text-xs">{item.id}</div>
+ <div class="flex flex-col gap-0.5 leading-tight">
+ <button
+ class="text-foreground-primary h-auto min-h-0 cursor-pointer p-0 text-left text-sm leading-tight font-medium hover:underline"
+ onclick={() => goto(`/environments/${item.id}`)}
+ >
+ {item.name}
+ </button>
+ <div class="text-muted-foreground font-mono text-xs leading-tight">{item.apiUrl}</div>
</div>
</div>
{/snippet}
{#snippet StatusCell({ value }: { value: unknown })}
- <StatusBadge text={String(value ?? m.common_offline())} variant={String(value) === 'online' ? 'green' : 'red'} />
+ <StatusBadge text={capitalizeFirstLetter(String(value)) || m.common_unknown()} variant={value === 'online' ? 'green' : 'red'} />
{/snippet}
{#snippet ApiCell({ value }: { value: unknown })}
- <span class="text-muted-foreground font-mono text-sm">{String(value ?? '')}</span>
+ <span class="text-muted-foreground font-mono text-sm">{String(value)}</span>
{/snippet}
{#snippet EnabledCell({ value }: { value: unknown })}
- <StatusBadge text={Boolean(value) ? 'Enabled' : 'Disabled'} variant={Boolean(value) ? 'green' : 'gray'} />
+ <StatusBadge text={value ? m.common_enabled() : m.common_disabled()} variant={value ? 'green' : 'red'} />
{/snippet}
{#snippet EnvironmentMobileCardSnippet({
@@ -254,6 +287,7 @@
}
]}
rowActions={RowActions}
+ onclick={(item: Environment) => goto(`/environments/${item.id}`)}
/>
{/snippet}
@@ -269,33 +303,58 @@
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
- <DropdownMenu.Item onclick={() => handleTest(item.id)} disabled={isLoading.testing}>
- <TerminalIcon class="size-4" />
- {m.environments_test_connection()}
+ <DropdownMenu.Item
+ onclick={async () => {
+ if (!item.enabled) {
+ toast.error(m.environments_cannot_switch_disabled());
+ return;
+ }
+ try {
+ await environmentStore.setEnvironment(item);
+ toast.success(m.environments_switched_to({ name: item.name }));
+ } catch (error) {
+ console.error('Failed to set environment:', error);
+ }
+ }}
+ disabled={!item.enabled || environmentStore.selected?.id === item.id}
+ >
+ <MonitorIcon class="size-4" />
+ {environmentStore.selected?.id === item.id ? m.environments_current_environment() : m.environments_use_environment()}
</DropdownMenu.Item>
+ <DropdownMenu.Separator />
<DropdownMenu.Item onclick={() => goto(`/environments/${item.id}`)}>
<EyeIcon class="size-4" />
{m.common_view_details()}
</DropdownMenu.Item>
- {#if item.status === 'online'}
+ <DropdownMenu.Item onclick={() => handleTest(item.id)} disabled={isLoading.testing}>
+ <TerminalIcon class="size-4" />
+ {m.environments_test_connection()}
+ </DropdownMenu.Item>
+ {#if item.id !== '0'}
+ {#if item.status === 'online'}
+ <DropdownMenu.Separator />
+ <DropdownMenu.Item
+ onclick={() => handleUpgradeClick(item)}
+ disabled={isLoading.upgrading || upgradingEnvironmentId === item.id}
+ >
+ <DownloadIcon class="size-4" />
+ {upgradingEnvironmentId === item.id ? m.upgrade_in_progress() : m.upgrade_to_version({ version: 'Latest' })}
+ </DropdownMenu.Item>
+ {/if}
+ <DropdownMenu.Item onclick={() => handleToggleEnabled(item)} disabled={isLoading.toggling}>
+ <PowerIcon class="size-4" />
+ {item.enabled ? m.common_disable() : m.common_enable()}
+ </DropdownMenu.Item>
<DropdownMenu.Separator />
<DropdownMenu.Item
- onclick={() => handleUpgradeClick(item)}
- disabled={isLoading.upgrading || upgradingEnvironmentId === item.id}
+ variant="destructive"
+ onclick={() => handleDeleteOne(item.id, item.name)}
+ disabled={isLoading.removing}
>
- <DownloadIcon class="size-4" />
- {upgradingEnvironmentId === item.id ? m.upgrade_in_progress() : m.upgrade_to_version({ version: 'Latest' })}
+ <Trash2Icon class="size-4" />
+ {m.common_delete()}
</DropdownMenu.Item>
{/if}
- <DropdownMenu.Separator />
- <DropdownMenu.Item
- variant="destructive"
- onclick={() => handleDeleteOne(item.id, item.name)}
- disabled={isLoading.removing}
- >
- <Trash2Icon class="size-4" />
- {m.common_delete()}
- </DropdownMenu.Item>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/settings/general/+page.svelte b/frontend/src/routes/settings/general/+page.svelte
index 14543397f..3889bbc45 100644
--- a/frontend/src/routes/settings/general/+page.svelte
+++ b/frontend/src/routes/settings/general/+page.svelte
@@ -28,6 +28,7 @@
projectsDirectory: z.string().min(1, m.general_projects_directory_required()),
baseServerUrl: z.string().min(1, m.general_base_url_required()),
enableGravatar: z.boolean(),
+ environmentHealthInterval: z.number().int().min(1).max(60),
accentColor: z.string(),
glassEffectEnabled: z.boolean()
});
@@ -39,6 +40,7 @@
$formInputs.projectsDirectory.value !== currentSettings.projectsDirectory ||
$formInputs.baseServerUrl.value !== currentSettings.baseServerUrl ||
$formInputs.enableGravatar.value !== currentSettings.enableGravatar ||
+ $formInputs.environmentHealthInterval.value !== currentSettings.environmentHealthInterval ||
$formInputs.accentColor.value !== currentSettings.accentColor ||
$formInputs.glassEffectEnabled.value !== currentSettings.glassEffectEnabled
});
@@ -65,6 +67,7 @@
$formInputs.projectsDirectory.value = currentSettings.projectsDirectory;
$formInputs.baseServerUrl.value = currentSettings.baseServerUrl;
$formInputs.enableGravatar.value = currentSettings.enableGravatar;
+ $formInputs.environmentHealthInterval.value = currentSettings.environmentHealthInterval;
$formInputs.accentColor.value = currentSettings.accentColor;
$formInputs.glassEffectEnabled.value = currentSettings.glassEffectEnabled;
applyAccentColor(currentSettings.accentColor);
@@ -133,6 +136,25 @@
</Card.Content>
</Card.Root>
+ <Card.Root>
+ <Card.Header icon={SettingsIcon}>
+ <div class="flex flex-col space-y-1.5">
+ <Card.Title>{m.environments_health_check_title()}</Card.Title>
+ <Card.Description>{m.environments_health_check_description()}</Card.Description>
+ </div>
+ </Card.Header>
+ <Card.Content class="px-3 py-4 sm:px-6">
+ <TextInputWithLabel
+ bind:value={$formInputs.environmentHealthInterval.value}
+ error={$formInputs.environmentHealthInterval.error}
+ label={m.environments_health_check_interval_label()}
+ placeholder="2"
+ helpText={m.environments_health_check_interval_description()}
+ type="number"
+ />
+ </Card.Content>
+ </Card.Root>
+
<Card.Root>
<Card.Header icon={PaletteIcon}>
<div class="flex flex-col space-y-1.5">