Skip to content

Modern Docker Management, Designed for Everyone

feat: auto pairing and new agent creation flow (#1114)

Kyle Mendell1684fd3dfe68
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 15888f273..48198b688 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -4,10 +4,12 @@ import (
"context"
"errors"
"fmt"
+ "io"
"log/slog"
"net/http"
"os"
"os/signal"
+ "strings"
"syscall"
"time"
@@ -75,6 +77,13 @@ func Bootstrap(ctx context.Context) error {
},
appServices.Settings.MigrateOidcConfigToFields)
+ // Handle agent auto-pairing with API key
+ if cfg.AgentMode && cfg.AgentToken != "" && cfg.ManagerApiUrl != "" {
+ if err := handleAgentBootstrapPairing(appCtx, cfg, httpClient); err != nil {
+ slog.WarnContext(appCtx, "Failed to auto-pair agent with manager", "error", err)
+ }
+ }
+
scheduler, err := initializeScheduler()
if err != nil {
return fmt.Errorf("failed to create job scheduler: %w", err)
@@ -92,6 +101,37 @@ func Bootstrap(ctx context.Context) error {
return nil
}
+func handleAgentBootstrapPairing(ctx context.Context, cfg *config.Config, httpClient *http.Client) error {
+ slog.InfoContext(ctx, "Agent mode detected with token, attempting auto-pairing", "managerUrl", cfg.ManagerApiUrl)
+
+ pairURL := strings.TrimRight(cfg.ManagerApiUrl, "/") + "/api/environments/pair"
+
+ reqCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+
+ req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, pairURL, nil)
+ if err != nil {
+ return fmt.Errorf("failed to create pairing request: %w", err)
+ }
+
+ req.Header.Set("X-API-Key", cfg.AgentToken)
+
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("pairing request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("pairing failed with status %d: %s", resp.StatusCode, string(body))
+ }
+
+ slog.InfoContext(ctx, "Successfully paired agent with manager", "managerUrl", cfg.ManagerApiUrl)
+
+ return nil
+}
+
func runServices(appCtx context.Context, cfg *config.Config, router http.Handler, scheduler interface{ Run(context.Context) error }) error {
go func() {
slog.InfoContext(appCtx, "Starting scheduler")
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.go
index df9fbb7d4..0395cae5b 100644
--- a/backend/internal/bootstrap/services_bootstrap.go
+++ b/backend/internal/bootstrap/services_bootstrap.go
@@ -61,7 +61,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.Docker)
+ svcs.Environment = services.NewEnvironmentService(db, httpClient, svcs.Docker, svcs.Event)
svcs.Container = services.NewContainerService(db, svcs.Event, svcs.Docker, svcs.Image)
svcs.Volume = services.NewVolumeService(db, svcs.Docker, svcs.Event)
svcs.Network = services.NewNetworkService(db, svcs.Docker, svcs.Event)
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index b92767a0b..19086a30f 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -36,7 +36,7 @@ type Config struct {
LogLevel string
AgentMode bool
AgentToken string
- AgentBootstrapToken string
+ ManagerApiUrl string
UpdateCheckDisabled bool
UIConfigurationDisabled bool
AnalyticsDisabled bool
@@ -66,7 +66,7 @@ func Load() *Config {
LogLevel: strings.ToLower(getEnvOrDefault("LOG_LEVEL", "info")),
AgentMode: getBoolEnvOrDefault("AGENT_MODE", false),
AgentToken: os.Getenv("AGENT_TOKEN"),
- AgentBootstrapToken: os.Getenv("AGENT_BOOTSTRAP_TOKEN"),
+ ManagerApiUrl: os.Getenv("MANAGER_API_URL"),
UpdateCheckDisabled: getBoolEnvOrDefault("UPDATE_CHECK_DISABLED", false),
UIConfigurationDisabled: getBoolEnvOrDefault("UI_CONFIGURATION_DISABLED", false),
AnalyticsDisabled: getBoolEnvOrDefault("ANALYTICS_DISABLED", false),
diff --git a/backend/internal/huma/handlers/environments.go b/backend/internal/huma/handlers/environments.go
index defac375f..2ab00f15f 100644
--- a/backend/internal/huma/handlers/environments.go
+++ b/backend/internal/huma/handlers/environments.go
@@ -7,6 +7,7 @@ import (
"github.com/danielgtaylor/huma/v2"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/config"
+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/internal/utils"
@@ -21,6 +22,8 @@ const localDockerEnvironmentID = "0"
type EnvironmentHandler struct {
environmentService *services.EnvironmentService
settingsService *services.SettingsService
+ apiKeyService *services.ApiKeyService
+ eventService *services.EventService
cfg *config.Config
}
@@ -50,8 +53,13 @@ type CreateEnvironmentInput struct {
Body environment.Create
}
+type EnvironmentWithApiKey struct {
+ environment.Environment
+ ApiKey *string `json:"apiKey,omitempty" doc:"API key for pairing (only shown once during creation)"`
+}
+
type CreateEnvironmentOutput struct {
- Body base.ApiResponse[environment.Environment]
+ Body base.ApiResponse[EnvironmentWithApiKey]
}
type GetEnvironmentInput struct {
@@ -113,15 +121,38 @@ type SyncRegistriesOutput struct {
Body base.ApiResponse[base.MessageResponse]
}
+type PairEnvironmentInput struct {
+ XAPIKey string `header:"X-API-Key" doc:"API key for environment pairing"`
+}
+
+type PairEnvironmentOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type DeploymentSnippet struct {
+ DockerRun string `json:"dockerRun" doc:"Docker run command snippet"`
+ DockerCompose string `json:"dockerCompose" doc:"Docker compose YAML snippet"`
+}
+
+type GetDeploymentSnippetsInput struct {
+ ID string `path:"id" doc:"Environment ID"`
+}
+
+type GetDeploymentSnippetsOutput struct {
+ Body base.ApiResponse[DeploymentSnippet]
+}
+
// ============================================================================
// Registration
// ============================================================================
// RegisterEnvironments registers all environment management endpoints.
-func RegisterEnvironments(api huma.API, environmentService *services.EnvironmentService, settingsService *services.SettingsService, cfg *config.Config) {
+func RegisterEnvironments(api huma.API, environmentService *services.EnvironmentService, settingsService *services.SettingsService, apiKeyService *services.ApiKeyService, eventService *services.EventService, cfg *config.Config) {
h := &EnvironmentHandler{
environmentService: environmentService,
settingsService: settingsService,
+ apiKeyService: apiKeyService,
+ eventService: eventService,
cfg: cfg,
}
@@ -182,7 +213,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Method: "DELETE",
Path: "/environments/{id}",
Summary: "Delete an environment",
- Description: "Delete a Docker environment",
+ Description: "Delete a Arcane environment",
Tags: []string{"Environments"},
Security: []map[string][]string{
{"BearerAuth": {}},
@@ -195,7 +226,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Method: "POST",
Path: "/environments/{id}/test",
Summary: "Test environment connection",
- Description: "Test connectivity to a Docker environment",
+ Description: "Test connectivity to a Arcane environment",
Tags: []string{"Environments"},
Security: []map[string][]string{
{"BearerAuth": {}},
@@ -241,6 +272,29 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"ApiKeyAuth": {}},
},
}, h.SyncRegistries)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "pairEnvironment",
+ Method: "POST",
+ Path: "/environments/pair",
+ Summary: "Pair agent with manager",
+ Description: "Agent sends API key to complete environment pairing",
+ Tags: []string{"Environments"},
+ MaxBodyBytes: 1024,
+ }, h.PairEnvironment)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getDeploymentSnippets",
+ Method: "GET",
+ Path: "/environments/{id}/deployment",
+ Summary: "Get deployment snippets",
+ Description: "Get Docker run and compose snippets for environment deployment",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetDeploymentSnippets)
}
// ============================================================================
@@ -277,10 +331,15 @@ func (h *EnvironmentHandler) ListEnvironments(ctx context.Context, input *ListEn
// CreateEnvironment creates a new environment.
func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *CreateEnvironmentInput) (*CreateEnvironmentOutput, error) {
- if h.environmentService == nil {
+ if h.environmentService == nil || h.apiKeyService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
env := &models.Environment{
ApiUrl: input.Body.ApiUrl,
Enabled: true,
@@ -292,6 +351,56 @@ func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *Creat
env.Enabled = *input.Body.Enabled
}
+ // Determine pairing method
+ useApiKey := input.Body.UseApiKey != nil && *input.Body.UseApiKey
+
+ if useApiKey {
+ // New API key-based pairing flow
+ env.Status = string(models.EnvironmentStatusPending)
+
+ created, err := h.environmentService.CreateEnvironment(ctx, env, &user.ID, &user.Username)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentCreationError{Err: err}).Error())
+ }
+
+ // Generate API key for environment
+ apiKeyDto, err := h.apiKeyService.CreateEnvironmentApiKey(ctx, created.ID, user.ID)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to create environment API key", "environmentID", created.ID, "error", err.Error())
+ return nil, huma.Error500InternalServerError("Failed to create environment API key")
+ }
+
+ // Store the API key in AccessToken field (encrypted) for manager-to-agent auth
+ encryptedKey := apiKeyDto.Key // Store the full key
+
+ // Link API key to environment and store encrypted key for manager use
+ updates := map[string]interface{}{
+ "api_key_id": apiKeyDto.ID,
+ "access_token": encryptedKey,
+ }
+ created, err = h.environmentService.UpdateEnvironment(ctx, created.ID, updates, &user.ID, &user.Username)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to link API key to environment", "environmentID", created.ID, "error", err.Error())
+ return nil, huma.Error500InternalServerError("Failed to link API key")
+ }
+
+ out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](created)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())
+ }
+
+ return &CreateEnvironmentOutput{
+ Body: base.ApiResponse[EnvironmentWithApiKey]{
+ Success: true,
+ Data: EnvironmentWithApiKey{
+ Environment: out,
+ ApiKey: &apiKeyDto.Key,
+ },
+ },
+ }, nil
+ }
+
+ // Legacy pairing flows
if (input.Body.AccessToken == nil || *input.Body.AccessToken == "") && input.Body.BootstrapToken != nil && *input.Body.BootstrapToken != "" {
token, err := h.environmentService.PairAgentWithBootstrap(ctx, input.Body.ApiUrl, *input.Body.BootstrapToken)
if err != nil {
@@ -303,7 +412,7 @@ func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *Creat
env.AccessToken = input.Body.AccessToken
}
- created, err := h.environmentService.CreateEnvironment(ctx, env)
+ created, err := h.environmentService.CreateEnvironment(ctx, env, &user.ID, &user.Username)
if err != nil {
return nil, huma.Error500InternalServerError((&common.EnvironmentCreationError{Err: err}).Error())
}
@@ -325,9 +434,11 @@ func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *Creat
}
return &CreateEnvironmentOutput{
- Body: base.ApiResponse[environment.Environment]{
+ Body: base.ApiResponse[EnvironmentWithApiKey]{
Success: true,
- Data: out,
+ Data: EnvironmentWithApiKey{
+ Environment: out,
+ },
},
}, nil
}
@@ -370,7 +481,13 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
return nil, err
}
- updated, updateErr := h.environmentService.UpdateEnvironment(ctx, input.ID, updates)
+ user, _ := humamw.GetCurrentUserFromContext(ctx)
+ var userID, username *string
+ if user != nil {
+ userID = &user.ID
+ username = &user.Username
+ }
+ updated, updateErr := h.environmentService.UpdateEnvironment(ctx, input.ID, updates, userID, username)
if updateErr != nil {
return nil, huma.Error500InternalServerError((&common.EnvironmentUpdateError{Err: updateErr}).Error())
}
@@ -382,6 +499,53 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())
}
+ // If regenerating API key, return the new key
+ var newApiKey *string
+ if input.Body.RegenerateApiKey != nil && *input.Body.RegenerateApiKey {
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized("Unauthorized")
+ }
+
+ // Delete existing API key if any
+ if updated.ApiKeyID != nil {
+ _ = h.apiKeyService.DeleteApiKey(ctx, *updated.ApiKeyID)
+ }
+
+ // Generate new API key
+ apiKeyDto, err := h.apiKeyService.CreateEnvironmentApiKey(ctx, input.ID, user.ID)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to create new environment API key", "environmentID", input.ID, "error", err.Error())
+ return nil, huma.Error500InternalServerError("Failed to regenerate API key")
+ }
+
+ // Use service method to update environment and create event
+ encryptedKey := apiKeyDto.Key
+ err = h.environmentService.RegenerateEnvironmentApiKey(ctx, input.ID, apiKeyDto.ID, encryptedKey, user.ID, user.Username, updated.Name)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to regenerate API key", "environmentID", input.ID, "error", err.Error())
+ return nil, huma.Error500InternalServerError("Failed to regenerate API key")
+ }
+
+ // Fetch updated environment
+ updated, err = h.environmentService.GetEnvironmentByID(ctx, input.ID)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to fetch updated environment", "environmentID", input.ID, "error", err.Error())
+ return nil, huma.Error500InternalServerError("Failed to fetch updated environment")
+ }
+
+ // Re-map with updated environment data
+ out, mapErr = mapper.MapOne[*models.Environment, environment.Environment](updated)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())
+ }
+
+ newApiKey = &apiKeyDto.Key
+ }
+
+ // Set the API key on the response if regenerated
+ out.ApiKey = newApiKey
+
return &UpdateEnvironmentOutput{
Body: base.ApiResponse[environment.Environment]{
Success: true,
@@ -400,7 +564,13 @@ func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *Delet
return nil, huma.Error400BadRequest((&common.LocalEnvironmentDeletionError{}).Error())
}
- if err := h.environmentService.DeleteEnvironment(ctx, input.ID); err != nil {
+ user, _ := humamw.GetCurrentUserFromContext(ctx)
+ var userID, username *string
+ if user != nil {
+ userID = &user.ID
+ username = &user.Username
+ }
+ if err := h.environmentService.DeleteEnvironment(ctx, input.ID, userID, username); err != nil {
return nil, huma.Error500InternalServerError((&common.EnvironmentDeletionError{Err: err}).Error())
}
@@ -589,3 +759,87 @@ func (h *EnvironmentHandler) triggerPostUpdateTasks(environmentID string, update
}(environmentID, updated.Name)
}
}
+
+// PairEnvironment handles agent pairing callback with API key.
+func (h *EnvironmentHandler) PairEnvironment(ctx context.Context, input *PairEnvironmentInput) (*PairEnvironmentOutput, error) {
+ if h.environmentService == nil || h.apiKeyService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.XAPIKey == "" {
+ return nil, huma.Error400BadRequest("X-API-Key header is required")
+ }
+
+ envID, err := h.apiKeyService.GetEnvironmentByApiKey(ctx, input.XAPIKey)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to validate API key for pairing", "error", err.Error())
+ return nil, huma.Error401Unauthorized("Invalid API key")
+ }
+
+ if envID == nil {
+ return nil, huma.Error400BadRequest("API key is not linked to an environment")
+ }
+
+ env, err := h.environmentService.GetEnvironmentByID(ctx, *envID)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to get environment", "environmentID", *envID, "error", err.Error())
+ return nil, huma.Error404NotFound("Environment not found")
+ }
+
+ if env.Status != string(models.EnvironmentStatusPending) {
+ return nil, huma.Error400BadRequest("Environment is not in pending status")
+ }
+
+ updates := map[string]interface{}{
+ "status": string(models.EnvironmentStatusOnline),
+ }
+ _, err = h.environmentService.UpdateEnvironment(ctx, *envID, updates, nil, nil)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to update environment status", "environmentID", *envID, "error", err.Error())
+ return nil, huma.Error500InternalServerError("Failed to complete pairing")
+ }
+
+ slog.InfoContext(ctx, "Environment pairing completed", "environmentID", *envID, "environmentName", env.Name)
+
+ return &PairEnvironmentOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Environment pairing completed successfully",
+ },
+ },
+ }, nil
+}
+
+// GetDeploymentSnippets returns deployment snippets for an environment.
+func (h *EnvironmentHandler) GetDeploymentSnippets(ctx context.Context, input *GetDeploymentSnippetsInput) (*GetDeploymentSnippetsOutput, error) {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ env, err := h.environmentService.GetEnvironmentByID(ctx, input.ID)
+ if err != nil {
+ return nil, huma.Error404NotFound("Environment not found")
+ }
+
+ if env.ApiKeyID == nil {
+ return nil, huma.Error400BadRequest("Environment does not have an API key configured")
+ }
+
+ // Generate snippets with placeholder for API key
+ snippets, err := h.environmentService.GenerateDeploymentSnippets(ctx, env.ID, h.cfg.AppUrl, "<YOUR_API_KEY>")
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to generate deployment snippets", "environmentID", input.ID, "error", err.Error())
+ return nil, huma.Error500InternalServerError("Failed to generate deployment snippets")
+ }
+
+ return &GetDeploymentSnippetsOutput{
+ Body: base.ApiResponse[DeploymentSnippet]{
+ Success: true,
+ Data: DeploymentSnippet{
+ DockerRun: snippets.DockerRun,
+ DockerCompose: snippets.DockerCompose,
+ },
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.go
index fdf4a835a..b1e1eccdd 100644
--- a/backend/internal/huma/huma.go
+++ b/backend/internal/huma/huma.go
@@ -336,7 +336,7 @@ func registerHandlers(api huma.API, svc *Services) {
handlers.RegisterVersion(api, versionSvc)
handlers.RegisterEvents(api, eventSvc)
handlers.RegisterOidc(api, authSvc, oidcSvc, cfg)
- handlers.RegisterEnvironments(api, environmentSvc, settingsSvc, cfg)
+ handlers.RegisterEnvironments(api, environmentSvc, settingsSvc, apiKeySvc, eventSvc, cfg)
handlers.RegisterContainerRegistries(api, containerRegistrySvc)
handlers.RegisterTemplates(api, templateSvc)
handlers.RegisterImages(api, dockerSvc, imageSvc, imageUpdateSvc, settingsSvc)
diff --git a/backend/internal/huma/middleware/auth.go b/backend/internal/huma/middleware/auth.go
index ba1855349..ec2757169 100644
--- a/backend/internal/huma/middleware/auth.go
+++ b/backend/internal/huma/middleware/auth.go
@@ -103,8 +103,8 @@ func tryAgentAuth(ctx huma.Context, cfg *config.Config) (*models.User, bool) {
// Check for agent bootstrap pairing
if strings.HasPrefix(path, agentPairingPrefix) &&
- cfg.AgentBootstrapToken != "" &&
- ctx.Header(headerAgentBootstrap) == cfg.AgentBootstrapToken {
+ cfg.AgentToken != "" &&
+ ctx.Header(headerAgentBootstrap) == cfg.AgentToken {
return createAgentSudoUser(), true
}
@@ -118,7 +118,7 @@ func tryAgentAuth(ctx huma.Context, cfg *config.Config) (*models.User, bool) {
// createAgentSudoUser creates a sudo user for agent authentication.
func createAgentSudoUser() *models.User {
- email := "[email protected]"
+ email := "[email protected]"
return &models.User{
BaseModel: models.BaseModel{ID: "agent"},
Email: &email,
diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.go
index e2494735e..018f06e0c 100644
--- a/backend/internal/middleware/auth_middleware.go
+++ b/backend/internal/middleware/auth_middleware.go
@@ -17,7 +17,7 @@ import (
const (
headerAgentBootstrap = "X-Arcane-Agent-Bootstrap"
headerAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential
- headerApiToken = "X-API-TOKEN" // #nosec G101: header name, not a credential
+ headerApiKey = "X-API-KEY" // #nosec G101: header name, not a credential
agentPairingPrefix = "/api/environments/0/agent/pair"
)
@@ -74,8 +74,8 @@ func (m *AuthMiddleware) agentAuth(c *gin.Context) {
}
if strings.HasPrefix(c.Request.URL.Path, agentPairingPrefix) &&
- m.cfg.AgentBootstrapToken != "" &&
- c.GetHeader(headerAgentBootstrap) == m.cfg.AgentBootstrapToken {
+ m.cfg.AgentToken != "" &&
+ c.GetHeader(headerAgentBootstrap) == m.cfg.AgentToken {
slog.Info("Agent auth: bootstrap pairing accepted", "path", c.Request.URL.Path, "method", c.Request.Method)
agentSudo(c)
return
@@ -100,9 +100,9 @@ func (m *AuthMiddleware) agentAuth(c *gin.Context) {
}
func (m *AuthMiddleware) managerAuth(c *gin.Context) {
- // First, check for API token in X-API-TOKEN header
- if apiToken := c.GetHeader(headerApiToken); apiToken != "" && m.apiKeyValidator != nil {
- user, err := m.apiKeyValidator.ValidateApiKey(c.Request.Context(), apiToken)
+ // First, check for API key in X-API-KEY header
+ if apiKey := c.GetHeader(headerApiKey); apiKey != "" && m.apiKeyValidator != nil {
+ user, err := m.apiKeyValidator.ValidateApiKey(c.Request.Context(), apiKey)
if err == nil && user != nil {
isAdmin := userHasRole(user, "admin")
if m.options.AdminRequired && !isAdmin {
@@ -188,7 +188,7 @@ func isPreflight(c *gin.Context) bool {
}
func agentSudo(c *gin.Context) {
- email := "[email protected]"
+ email := "[email protected]"
agentUser := &models.User{
BaseModel: models.BaseModel{ID: "agent"},
Email: &email,
diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.go
index 03e158ee7..31334c493 100644
--- a/backend/internal/middleware/environment_middleware.go
+++ b/backend/internal/middleware/environment_middleware.go
@@ -61,6 +61,14 @@ func (m *EnvironmentMiddleware) Handle(c *gin.Context) {
return
}
+ // Only proxy requests with additional path segments after the environment ID
+ // Examples: /api/environments/{id}/containers, /api/environments/{id}/projects
+ // Not proxied: /api/environments/{id} (management operations)
+ if !m.hasResourcePath(c, envID) {
+ c.Next()
+ return
+ }
+
// Resolve remote environment
apiURL, accessToken, enabled, err := m.resolver(c.Request.Context(), envID)
if err != nil || apiURL == "" {
@@ -91,6 +99,41 @@ func (m *EnvironmentMiddleware) Handle(c *gin.Context) {
}
}
+// hasResourcePath checks if the request has additional path segments after the environment ID.
+// Returns true for paths like /api/environments/{id}/containers (should be proxied)
+// Returns false for paths like /api/environments/{id} or management endpoints (should be handled locally)
+func (m *EnvironmentMiddleware) hasResourcePath(c *gin.Context, envID string) bool {
+ path := c.Request.URL.Path
+ prefix := "/api/environments/" + envID
+
+ // If there's content after the environment ID path, check if it's a management endpoint
+ suffix := strings.TrimPrefix(path, prefix)
+
+ // No suffix means it's exactly /api/environments/{id} - management endpoint
+ if len(suffix) <= 1 || !strings.HasPrefix(suffix, "/") {
+ return false
+ }
+
+ // Check if it's a management endpoint that should NOT be proxied
+ // These are environment management operations handled by the manager
+ managementEndpoints := []string{
+ "/test",
+ "/heartbeat",
+ "/sync-registries",
+ "/deployment",
+ "/agent/pair",
+ }
+
+ for _, endpoint := range managementEndpoints {
+ if suffix == endpoint {
+ return false
+ }
+ }
+
+ // It's a resource operation (e.g., "/containers", "/images") - should be proxied
+ return true
+}
+
// extractEnvironmentID gets the environment ID from the request.
// Only processes paths containing "/environments/" to avoid conflicts with other routes.
func (m *EnvironmentMiddleware) extractEnvironmentID(c *gin.Context) string {
diff --git a/backend/internal/models/api_key.go b/backend/internal/models/api_key.go
index ac527fb10..d37bce2d6 100644
--- a/backend/internal/models/api_key.go
+++ b/backend/internal/models/api_key.go
@@ -5,13 +5,14 @@ import (
)
type ApiKey struct {
- Name string `json:"name" gorm:"column:name;not null" sortable:"true"`
- Description *string `json:"description,omitempty" gorm:"column:description"`
- KeyHash string `json:"-" gorm:"column:key_hash;not null"`
- KeyPrefix string `json:"keyPrefix" gorm:"column:key_prefix;not null"`
- UserID string `json:"userId" gorm:"column:user_id;not null"`
- ExpiresAt *time.Time `json:"expiresAt,omitempty" gorm:"column:expires_at" sortable:"true"`
- LastUsedAt *time.Time `json:"lastUsedAt,omitempty" gorm:"column:last_used_at" sortable:"true"`
+ Name string `json:"name" gorm:"column:name;not null" sortable:"true"`
+ Description *string `json:"description,omitempty" gorm:"column:description"`
+ KeyHash string `json:"-" gorm:"column:key_hash;not null"`
+ KeyPrefix string `json:"keyPrefix" gorm:"column:key_prefix;not null"`
+ UserID string `json:"userId" gorm:"column:user_id;not null"`
+ EnvironmentID *string `json:"environmentId,omitempty" gorm:"column:environment_id"`
+ ExpiresAt *time.Time `json:"expiresAt,omitempty" gorm:"column:expires_at" sortable:"true"`
+ LastUsedAt *time.Time `json:"lastUsedAt,omitempty" gorm:"column:last_used_at" sortable:"true"`
BaseModel
}
diff --git a/backend/internal/models/environment.go b/backend/internal/models/environment.go
index 9bae999c5..4890251d0 100644
--- a/backend/internal/models/environment.go
+++ b/backend/internal/models/environment.go
@@ -9,6 +9,7 @@ type Environment struct {
Enabled bool `json:"enabled" sortable:"true"`
LastSeen *time.Time `json:"lastSeen" gorm:"column:last_seen"`
AccessToken *string `json:"-" gorm:"column:access_token"`
+ ApiKeyID *string `json:"-" gorm:"column:api_key_id"`
BaseModel
}
@@ -21,4 +22,5 @@ const (
EnvironmentStatusOnline EnvironmentStatus = "online"
EnvironmentStatusOffline EnvironmentStatus = "offline"
EnvironmentStatusError EnvironmentStatus = "error"
+ EnvironmentStatusPending EnvironmentStatus = "pending"
)
diff --git a/backend/internal/models/event.go b/backend/internal/models/event.go
index f5b235fdf..b5265871b 100644
--- a/backend/internal/models/event.go
+++ b/backend/internal/models/event.go
@@ -46,6 +46,11 @@ const (
EventTypeSystemAutoUpdate EventType = "system.auto_update"
EventTypeSystemUpgrade EventType = "system.upgrade"
+ EventTypeEnvironmentCreate EventType = "environment.create"
+ EventTypeEnvironmentUpdate EventType = "environment.update"
+ EventTypeEnvironmentDelete EventType = "environment.delete"
+ EventTypeEnvironmentApiKeyRegenerated EventType = "environment.api_key.regenerated"
+
// Event severities
EventSeverityInfo EventSeverity = "info"
EventSeverityWarning EventSeverity = "warning"
diff --git a/backend/internal/services/api_key_service.go b/backend/internal/services/api_key_service.go
index 888e91440..9ad43847c 100644
--- a/backend/internal/services/api_key_service.go
+++ b/backend/internal/services/api_key_service.go
@@ -100,6 +100,55 @@ func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, req api
}, nil
}
+func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environmentID string, userID string) (*apikey.ApiKeyCreatedDto, error) {
+ rawKey, err := s.generateApiKey()
+ if err != nil {
+ return nil, err
+ }
+
+ keyHash, err := s.hashApiKey(rawKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to hash API key: %w", err)
+ }
+
+ keyPrefix := rawKey[:len(apiKeyPrefix)+apiKeyPrefixLen]
+
+ envIDShort := environmentID
+ if len(environmentID) > 8 {
+ envIDShort = environmentID[:8]
+ }
+ name := fmt.Sprintf("Environment Bootstrap Key - %s", envIDShort)
+ description := "Auto-generated key for environment pairing"
+
+ ak := &models.ApiKey{
+ Name: name,
+ Description: &description,
+ KeyHash: keyHash,
+ KeyPrefix: keyPrefix,
+ UserID: userID,
+ EnvironmentID: &environmentID,
+ }
+
+ if err := s.db.WithContext(ctx).Create(ak).Error; err != nil {
+ return nil, fmt.Errorf("failed to create environment API key: %w", err)
+ }
+
+ return &apikey.ApiKeyCreatedDto{
+ ApiKey: apikey.ApiKey{
+ ID: ak.ID,
+ Name: ak.Name,
+ Description: ak.Description,
+ KeyPrefix: ak.KeyPrefix,
+ UserID: ak.UserID,
+ ExpiresAt: ak.ExpiresAt,
+ LastUsedAt: ak.LastUsedAt,
+ CreatedAt: ak.CreatedAt,
+ UpdatedAt: ak.UpdatedAt,
+ },
+ Key: rawKey,
+ }, nil
+}
+
func (s *ApiKeyService) GetApiKey(ctx context.Context, id string) (*apikey.ApiKey, error) {
var ak models.ApiKey
if err := s.db.WithContext(ctx).Where("id = ?", id).First(&ak).Error; err != nil {
@@ -240,3 +289,28 @@ func (s *ApiKeyService) ValidateApiKey(ctx context.Context, rawKey string) (*mod
return nil, ErrApiKeyInvalid
}
+
+func (s *ApiKeyService) GetEnvironmentByApiKey(ctx context.Context, rawKey string) (*string, error) {
+ if !strings.HasPrefix(rawKey, apiKeyPrefix) {
+ return nil, ErrApiKeyInvalid
+ }
+
+ keyPrefix := rawKey[:len(apiKeyPrefix)+apiKeyPrefixLen]
+
+ var apiKeys []models.ApiKey
+ if err := s.db.WithContext(ctx).Where("key_prefix = ?", keyPrefix).Find(&apiKeys).Error; err != nil {
+ return nil, fmt.Errorf("failed to find API keys: %w", err)
+ }
+
+ for _, apiKey := range apiKeys {
+ if err := s.validateApiKeyHash(apiKey.KeyHash, rawKey); err == nil {
+ if apiKey.ExpiresAt != nil && apiKey.ExpiresAt.Before(time.Now()) {
+ return nil, ErrApiKeyExpired
+ }
+
+ return apiKey.EnvironmentID, nil
+ }
+ }
+
+ return nil, ErrApiKeyInvalid
+}
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 0a2754875..ec17d35ca 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -26,13 +26,14 @@ type EnvironmentService struct {
db *database.DB
httpClient *http.Client
dockerService *DockerClientService
+ eventService *EventService
}
-func NewEnvironmentService(db *database.DB, httpClient *http.Client, dockerService *DockerClientService) *EnvironmentService {
+func NewEnvironmentService(db *database.DB, httpClient *http.Client, dockerService *DockerClientService, eventService *EventService) *EnvironmentService {
if httpClient == nil {
httpClient = http.DefaultClient
}
- return &EnvironmentService{db: db, httpClient: httpClient, dockerService: dockerService}
+ return &EnvironmentService{db: db, httpClient: httpClient, dockerService: dockerService, eventService: eventService}
}
func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl string) error {
@@ -78,9 +79,14 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl
return nil
}
-func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environment *models.Environment) (*models.Environment, error) {
+func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environment *models.Environment, userID, username *string) (*models.Environment, error) {
environment.ID = uuid.New().String()
- environment.Status = string(models.EnvironmentStatusOffline)
+
+ // Only set status to offline if not already set (e.g., API key flow sets it to pending)
+ if environment.Status == "" {
+ environment.Status = string(models.EnvironmentStatusOffline)
+ }
+
now := time.Now()
environment.CreatedAt = now
environment.UpdatedAt = &now
@@ -89,6 +95,9 @@ func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environment
return nil, fmt.Errorf("failed to create environment: %w", err)
}
+ // Create event in background
+ go s.createEnvironmentEvent(context.WithoutCancel(ctx), environment.ID, environment.Name, models.EventTypeEnvironmentCreate, "Environment Created", fmt.Sprintf("Environment '%s' was created", environment.Name), models.EventSeveritySuccess, userID, username)
+
return environment, nil
}
@@ -140,7 +149,7 @@ func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, para
return out, paginationResp, nil
}
-func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, updates map[string]interface{}) (*models.Environment, error) {
+func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, updates map[string]interface{}, userID, username *string) (*models.Environment, error) {
now := time.Now()
updates["updated_at"] = &now
@@ -148,13 +157,33 @@ func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, u
return nil, fmt.Errorf("failed to update environment: %w", err)
}
- return s.GetEnvironmentByID(ctx, id)
+ updated, err := s.GetEnvironmentByID(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+
+ // Create event in background (skip for local environment)
+ if id != "0" {
+ go s.createEnvironmentEvent(context.WithoutCancel(ctx), id, updated.Name, models.EventTypeEnvironmentUpdate, "Environment Updated", fmt.Sprintf("Environment '%s' was updated", updated.Name), models.EventSeverityInfo, userID, username)
+ }
+
+ return updated, nil
}
-func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, id string) error {
+func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, id string, userID, username *string) error {
+ // Get environment details before deletion
+ env, err := s.GetEnvironmentByID(ctx, id)
+ if err != nil {
+ return err
+ }
+
if err := s.db.WithContext(ctx).Delete(&models.Environment{}, "id = ?", id).Error; err != nil {
return fmt.Errorf("failed to delete environment: %w", err)
}
+
+ // Create event in background
+ go s.createEnvironmentEvent(context.WithoutCancel(ctx), id, env.Name, models.EventTypeEnvironmentDelete, "Environment Deleted", fmt.Sprintf("Environment '%s' was deleted", env.Name), models.EventSeverityWarning, userID, username)
+
return nil
}
@@ -228,6 +257,17 @@ func (s *EnvironmentService) testLocalDockerConnection(ctx context.Context, id s
}
func (s *EnvironmentService) updateEnvironmentStatusInternal(ctx context.Context, id, status string) error {
+ // Don't update status for pending environments - they're waiting for agent pairing
+ var currentEnv models.Environment
+ if err := s.db.WithContext(ctx).Select("status").Where("id = ?", id).First(&currentEnv).Error; err != nil {
+ return fmt.Errorf("failed to check environment status: %w", err)
+ }
+
+ if currentEnv.Status == string(models.EnvironmentStatusPending) {
+ slog.DebugContext(ctx, "skipping status update for pending environment", "environment_id", id)
+ return nil
+ }
+
now := time.Now()
updates := map[string]interface{}{
"status": status,
@@ -251,7 +291,44 @@ func (s *EnvironmentService) UpdateEnvironmentHeartbeat(ctx context.Context, id
}
return nil
}
+func (s *EnvironmentService) createEnvironmentEvent(ctx context.Context, envID, envName string, eventType models.EventType, title, description string, severity models.EventSeverity, userID, username *string) {
+ resourceType := "environment"
+ resourceID := envID
+ resourceName := envName
+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: eventType,
+ Severity: severity,
+ Title: title,
+ Description: description,
+ ResourceType: &resourceType,
+ ResourceID: &resourceID,
+ ResourceName: &resourceName,
+ UserID: userID,
+ Username: username,
+ EnvironmentID: &envID,
+ })
+}
+
+func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, envID string, newApiKeyID string, encryptedKey string, userID, username string, envName string) error {
+ // Update environment with new API key and set to pending status
+ updates := map[string]interface{}{
+ "api_key_id": newApiKeyID,
+ "access_token": encryptedKey,
+ "status": string(models.EnvironmentStatusPending),
+ "last_seen": nil, // Clear last seen time
+ }
+ if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", envID).Updates(updates).Error; err != nil {
+ return fmt.Errorf("failed to update environment with new API key: %w", err)
+ }
+
+ // Create event log in background
+ go s.createEnvironmentEvent(context.WithoutCancel(ctx), envID, envName, models.EventTypeEnvironmentApiKeyRegenerated, "API Key Regenerated", "Environment API key was regenerated and status set to pending", models.EventSeverityInfo, &userID, &username)
+
+ return nil
+}
+
+// Deprecated - Use the Api Key flow
func (s *EnvironmentService) PairAgentWithBootstrap(ctx context.Context, apiUrl, bootstrapToken string) (string, error) {
reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
@@ -338,6 +415,51 @@ func (s *EnvironmentService) GetEnabledRegistryCredentials(ctx context.Context)
return creds, nil
}
+// DeploymentSnippets contains deployment configuration snippets for an environment.
+type DeploymentSnippets struct {
+ DockerRun string
+ DockerCompose string
+}
+
+// GenerateDeploymentSnippets generates Docker deployment snippets for an environment.
+func (s *EnvironmentService) GenerateDeploymentSnippets(ctx context.Context, envID string, envAddress string, apiKey string) (*DeploymentSnippets, error) {
+ managerURL := strings.TrimRight(envAddress, "/")
+
+ dockerRun := fmt.Sprintf(`docker run -d \
+ --name arcane-agent \
+ --restart unless-stopped \
+ -e AGENT_MODE=true \
+ -e AGENT_TOKEN=%s \
+ -e MANAGER_API_URL=%s \
+ -p 3000:3000 \
+ -v /var/run/docker.sock:/var/run/docker.sock \
+ -v arcane-data:/data \
+ ghcr.io/getarcaneapp/arcane-headless:latest`, apiKey, managerURL)
+
+ dockerCompose := fmt.Sprintf(`services:
+ arcane-agent:
+ image: ghcr.io/getarcaneapp/arcane-headless:latest
+ container_name: arcane-agent
+ restart: unless-stopped
+ environment:
+ - AGENT_MODE=true
+ - AGENT_TOKEN=%s
+ - MANAGER_API_URL=%s
+ ports:
+ - "3000:3000"
+ volumes:
+ - /var/run/docker.sock:/var/run/docker.sock
+ - arcane-data:/data
+
+volumes:
+ arcane-data:`, apiKey, managerURL)
+
+ return &DeploymentSnippets{
+ DockerRun: dockerRun,
+ DockerCompose: dockerCompose,
+ }, nil
+}
+
// SyncRegistriesToEnvironment syncs all registries from this manager to a remote environment
func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, environmentID string) error {
// Get the environment
@@ -412,9 +534,18 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, en
}
req.Header.Set("Content-Type", "application/json")
+
+ // Use appropriate auth header based on environment type
if environment.AccessToken != nil && *environment.AccessToken != "" {
- req.Header.Set("X-Arcane-Agent-Token", *environment.AccessToken)
- slog.DebugContext(ctx, "Set agent token header for sync request")
+ // For API key-based environments, AccessToken contains the API key
+ if environment.ApiKeyID != nil && *environment.ApiKeyID != "" {
+ req.Header.Set("X-API-KEY", *environment.AccessToken)
+ slog.DebugContext(ctx, "Set API key header for sync request")
+ } else {
+ // Legacy bootstrap token-based environments
+ req.Header.Set("X-Arcane-Agent-Token", *environment.AccessToken)
+ slog.DebugContext(ctx, "Set agent token header for sync request")
+ }
} else {
slog.WarnContext(ctx, "No access token available for environment sync",
slog.String("environmentID", environmentID))
diff --git a/backend/resources/migrations/postgres/025_add_environment_api_key_pairing.down.sql b/backend/resources/migrations/postgres/025_add_environment_api_key_pairing.down.sql
new file mode 100644
index 000000000..d81f3a533
--- /dev/null
+++ b/backend/resources/migrations/postgres/025_add_environment_api_key_pairing.down.sql
@@ -0,0 +1,5 @@
+-- Remove environment_id column from api_keys table
+ALTER TABLE api_keys DROP COLUMN environment_id;
+
+-- Remove api_key_id column from environments table
+ALTER TABLE environments DROP COLUMN api_key_id;
diff --git a/backend/resources/migrations/postgres/025_add_environment_api_key_pairing.up.sql b/backend/resources/migrations/postgres/025_add_environment_api_key_pairing.up.sql
new file mode 100644
index 000000000..f81fe771c
--- /dev/null
+++ b/backend/resources/migrations/postgres/025_add_environment_api_key_pairing.up.sql
@@ -0,0 +1,5 @@
+-- Add api_key_id column to environments table for API key-based pairing
+ALTER TABLE environments ADD COLUMN api_key_id TEXT REFERENCES api_keys(id) ON DELETE SET NULL;
+
+-- Add environment_id column to api_keys table to link API keys to environments
+ALTER TABLE api_keys ADD COLUMN environment_id TEXT REFERENCES environments(id) ON DELETE CASCADE;
diff --git a/backend/resources/migrations/sqlite/025_add_environment_api_key_pairing.down.sql b/backend/resources/migrations/sqlite/025_add_environment_api_key_pairing.down.sql
new file mode 100644
index 000000000..d81f3a533
--- /dev/null
+++ b/backend/resources/migrations/sqlite/025_add_environment_api_key_pairing.down.sql
@@ -0,0 +1,5 @@
+-- Remove environment_id column from api_keys table
+ALTER TABLE api_keys DROP COLUMN environment_id;
+
+-- Remove api_key_id column from environments table
+ALTER TABLE environments DROP COLUMN api_key_id;
diff --git a/backend/resources/migrations/sqlite/025_add_environment_api_key_pairing.up.sql b/backend/resources/migrations/sqlite/025_add_environment_api_key_pairing.up.sql
new file mode 100644
index 000000000..f81fe771c
--- /dev/null
+++ b/backend/resources/migrations/sqlite/025_add_environment_api_key_pairing.up.sql
@@ -0,0 +1,5 @@
+-- Add api_key_id column to environments table for API key-based pairing
+ALTER TABLE environments ADD COLUMN api_key_id TEXT REFERENCES api_keys(id) ON DELETE SET NULL;
+
+-- Add environment_id column to api_keys table to link API keys to environments
+ALTER TABLE api_keys ADD COLUMN environment_id TEXT REFERENCES environments(id) ON DELETE CASCADE;
diff --git a/docker/compose.dev.yaml b/docker/compose.dev.yaml
index 0f1a1fdf4..5745e7aae 100644
--- a/docker/compose.dev.yaml
+++ b/docker/compose.dev.yaml
@@ -55,10 +55,10 @@ services:
- GIN_MODE=debug
- ENVIRONMENT=development
- PORT=3552
+ - LOG_LEVEL=debug
- APP_URL=http://localhost:3000
- PUID=1000
- PGID=1000
- - UI_CONFIGURATION_DISABLED=true
- 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_URL=file:data/arcane.db?_pragma=journal_mode(WAL)&_pragma=busy_timeout(2500)&_txlock=immediate
@@ -78,6 +78,7 @@ services:
start_period: 40s
arcane-agent:
+ profiles: ["agent"]
build:
context: ..
dockerfile: docker/Dockerfile.dev
@@ -92,7 +93,8 @@ services:
- ENVIRONMENT=development
- PORT=3553
- AGENT_MODE=true
- - AGENT_BOOTSTRAP_TOKEN=development-bootstrap-token
+ - AGENT_TOKEN=arc_Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+ - MANAGER_API_URL=http://backend:3552
- 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_URL=file:data/arcane.db?_pragma=journal_mode(WAL)&_pragma=busy_timeout(2500)&_txlock=immediate
@@ -125,15 +127,21 @@ networks:
arcane-dev:
driver: bridge
name: arcane-dev-network
+ external: true
volumes:
arcane-dev-data:
name: arcane-dev-data
+ external: true
agent-dev-data:
name: agent-dev-data
+ external: true
go-build-cache:
name: arcane-go-build-cache
+ external: true
go-mod-cache:
name: arcane-go-mod-cache
+ external: true
pnpm-cache:
name: arcane-pnpm-cache
+ external: true
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index b835c888b..6be8543e6 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -77,6 +77,7 @@
"common_no": "No",
"common_na": "N/A",
"common_cancel": "Cancel",
+ "common_dismiss": "Dismiss",
"common_confirm": "Confirm",
"common_image": "Image",
"common_state": "State",
@@ -682,6 +683,17 @@
"environments_current_environment": "Current Environment",
"environments_switched_to": "Switched to {name}",
"environments_cannot_switch_disabled": "Cannot switch to a disabled environment",
+ "environments_agent_config_title": "Agent Configuration",
+ "environments_agent_config_description": "Regenerate API key and deployment configuration for this agent",
+ "environments_new_api_key": "New API Key",
+ "environments_api_key_save_warning": "Save this API key - it won't be shown again. Update your agent with the new key.",
+ "environments_regenerate_warning_title": "Warning",
+ "environments_regenerate_warning_message": "Regenerating the API key will invalidate the current key. The agent will need to be updated with the new key to reconnect.",
+ "environments_regenerate_api_key": "Regenerate API Key",
+ "environments_regenerate_dialog_title": "Regenerate API Key?",
+ "environments_regenerate_dialog_message": "This will create a new API key for this environment. The current API key will be invalidated immediately, and the agent will lose connection until you update it with the new key.",
+ "environments_regenerate_key_success": "API key regenerated successfully",
+ "environments_regenerate_key_failed": "Failed to regenerate API key",
"_comment_users": "=== USERS ===",
"users_title": "Users",
"users_subtitle": "Manage system users and permissions",
@@ -1459,5 +1471,22 @@
"common_entrypoint": "Entrypoint",
"classic": "Classic",
"tree_view": "Tree View",
- "project_view_description": "Switch between classic side-by-side layout and tree view"
+ "project_view_description": "Switch between classic side-by-side layout and tree view",
+ "environments_created_title": "Environment Created Successfully",
+ "environments_created_description": "Use the API key and deployment snippets below to set up your agent.",
+ "environments_api_key": "API Key",
+ "environments_api_key_warning": "Save this API key securely. It will not be shown again.",
+ "environments_docker_run_command": "Docker Run Command",
+ "environments_docker_compose": "Docker Compose",
+ "environments_new_agent": "New Agent",
+ "environments_existing_agent": "Existing Agent",
+ "environments_create_new_agent": "Create New Agent Environment",
+ "environments_create_new_agent_description": "Generate an API key and deployment snippets for a new agent.",
+ "environments_production_docker": "Production Docker",
+ "environments_agent_address": "Agent Address",
+ "environments_agent_address_placeholder": "agent.example.com",
+ "environments_agent_address_description": "The URL where your agent will be accessible",
+ "environments_generate_config": "Generate Agent Configuration",
+ "environments_connect_existing_agent": "Connect to Existing Agent",
+ "environments_connect_existing_agent_description": "Connect to an already-running agent using a bootstrap token."
}
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
index 3119a1582..718e5da5c 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
@@ -62,9 +62,9 @@
<div class="md:hidden">
{#if mobileFields.length > 0 && onToggleMobileField}
- <DataTableViewOptions fields={mobileFields} onToggleField={onToggleMobileField} />
+ <DataTableViewOptions fields={mobileFields} onToggleField={onToggleMobileField} {customViewOptions} />
{:else}
- <DataTableViewOptions {table} />
+ <DataTableViewOptions {table} {customViewOptions} />
{/if}
</div>
</div>
diff --git a/frontend/src/lib/components/arcane-table/cards/universal-mobile-card.svelte b/frontend/src/lib/components/arcane-table/cards/universal-mobile-card.svelte
index 1c53c406d..dfc45a141 100644
--- a/frontend/src/lib/components/arcane-table/cards/universal-mobile-card.svelte
+++ b/frontend/src/lib/components/arcane-table/cards/universal-mobile-card.svelte
@@ -70,6 +70,8 @@
);
const visibleFields = $derived(fields.filter((f) => f.show !== false));
+ const subtitleValue = $derived(subtitle?.(item));
+ const hasSubtitle = $derived(!!subtitleValue);
function getIconBgClass(variant: IconVariant): string {
const map: Record<IconVariant, string> = {
@@ -100,7 +102,7 @@
}
</script>
-<div class={cn('group relative w-full px-3 py-3', className)}>
+<div class={cn('group relative w-full px-3 py-2', className)}>
<Card.Root
variant="subtle"
class={cn(
@@ -109,80 +111,81 @@
)}
onclick={onclick ? () => onclick(item) : undefined}
>
- <Card.Content class={cn('flex flex-col text-left', compact ? 'gap-3 p-3' : 'gap-4 p-4')}>
- <!-- Main Row -->
- <div class="flex items-start gap-4">
+ <Card.Content class={cn('flex flex-col text-left', compact ? 'gap-2 p-3' : 'gap-2.5 p-3')}>
+ <!-- Header Row: Icon + Title/Subtitle + Actions -->
+ <div class={cn('flex gap-2.5', hasSubtitle ? 'items-start' : 'items-center')}>
{#if resolvedIcon}
{@const IconComponent = resolvedIcon.component}
<div
class={cn(
- 'flex shrink-0 items-center justify-center rounded-xl ring-1 backdrop-blur-sm transition-transform duration-200 ring-inset group-hover:scale-105',
- compact ? 'size-9' : 'size-11',
+ 'flex shrink-0 items-center justify-center rounded-lg ring-1 backdrop-blur-sm transition-transform duration-200 ring-inset group-hover:scale-105',
+ compact ? 'size-8' : 'size-9',
getIconBgClass(resolvedIcon.variant),
'ring-white/5'
)}
>
- <IconComponent class={cn(getIconTextClass(resolvedIcon.variant), compact ? 'size-4.5' : 'size-5')} />
+ <IconComponent class={cn(getIconTextClass(resolvedIcon.variant), compact ? 'size-3.5' : 'size-4')} />
</div>
{/if}
<div class="min-w-0 flex-1">
- <h3 class={cn('truncate leading-snug font-semibold', compact ? 'text-sm' : 'text-[15px]')} title={title(item)}>
+ <h3
+ class={cn('leading-snug font-semibold', compact ? 'text-sm' : 'text-sm', hasSubtitle ? 'truncate' : 'line-clamp-2')}
+ title={title(item)}
+ >
{title(item)}
</h3>
- {#if subtitle}
- {@const subtitleValue = subtitle(item)}
- {#if subtitleValue}
- <p
- class={cn(
- 'text-muted-foreground mt-1.5 truncate leading-relaxed font-medium',
- compact ? 'text-[11px]' : 'text-xs'
- )}
- >
- {subtitleValue}
- </p>
- {/if}
+ {#if hasSubtitle}
+ <p class={cn('text-muted-foreground truncate font-mono', compact ? 'text-[10px]' : 'text-[11px]')}>
+ {subtitleValue}
+ </p>
{/if}
</div>
- <div class="flex shrink-0 items-center gap-2">
+ {#if rowActions}
+ <div class="shrink-0">
+ {@render rowActions({ item })}
+ </div>
+ {/if}
+ </div>
+
+ <!-- Badges Row -->
+ {#if resolvedBadges.length > 0}
+ <div class="flex flex-wrap items-center gap-1">
{#each resolvedBadges as badge}
<StatusBadge variant={badge.variant} text={badge.text} size="sm" />
{/each}
- {#if rowActions}
- {@render rowActions({ item })}
- {/if}
</div>
- </div>
+ {/if}
<!-- Additional Fields -->
{#if visibleFields.length > 0}
{#if !compact}
- <div class="-mx-4 flex flex-wrap gap-x-6 gap-y-4 px-4">
+ <div class="flex flex-wrap gap-x-4 gap-y-2">
{#each visibleFields as field}
{@const value = field.getValue(item)}
{#if value !== null && value !== undefined}
- <div class="flex min-w-0 flex-1 basis-[150px] items-start gap-3">
+ <div class="flex min-w-0 flex-1 basis-[140px] items-center gap-2">
{#if field.icon}
{@const FieldIcon = field.icon}
<div
class={cn(
- 'flex size-8 shrink-0 items-center justify-center rounded-lg ring-1 ring-white/5 backdrop-blur-sm ring-inset',
+ 'flex size-6 shrink-0 items-center justify-center rounded-md ring-1 ring-white/5 ring-inset',
field.iconVariant ? getIconBgClass(field.iconVariant) : 'bg-muted/40'
)}
>
<FieldIcon
- class={cn(field.iconVariant ? getIconTextClass(field.iconVariant) : 'text-muted-foreground', 'size-4')}
+ class={cn(field.iconVariant ? getIconTextClass(field.iconVariant) : 'text-muted-foreground', 'size-3')}
/>
</div>
{/if}
- <div class="min-w-0 flex-1 pt-0.5">
- <div class="text-muted-foreground/70 mb-1 text-[10px] leading-tight font-semibold tracking-wider uppercase">
+ <div class="min-w-0 flex-1">
+ <div class="text-muted-foreground/70 text-[9px] font-medium tracking-wide uppercase">
{field.label}
</div>
- <div class="text-sm leading-snug font-medium">
+ <div class="truncate text-xs leading-snug font-medium">
{#if field.type === 'badge' && field.badgeVariant}
- <StatusBadge variant={field.badgeVariant} text={String(value)} />
+ <StatusBadge variant={field.badgeVariant} text={String(value)} size="sm" />
{:else if field.type === 'mono'}
- <span class="font-mono text-xs">{value}</span>
+ <span class="font-mono text-[11px]">{value}</span>
{:else if field.type === 'component' && field.component}
{@render field.component(value)}
{:else}
@@ -229,12 +232,12 @@
{@const footerValue = footer.getValue(item)}
{#if footerValue}
{@const FooterIcon = footer.icon}
- <Card.Footer class="bg-muted/30 border-border/40 flex items-center gap-3 border-t px-4 py-3.5 backdrop-blur-sm">
- <FooterIcon class="text-muted-foreground size-4" />
- <span class="text-muted-foreground/70 text-[10px] font-semibold tracking-wider uppercase">
+ <Card.Footer class="bg-muted/30 border-border/40 flex items-center gap-2 border-t px-3 py-2">
+ <FooterIcon class="text-muted-foreground size-3.5" />
+ <span class="text-muted-foreground/70 text-[9px] font-medium tracking-wide uppercase">
{footer.label}
</span>
- <span class="text-foreground ml-auto font-mono text-xs font-medium">
+ <span class="text-foreground ml-auto font-mono text-[11px] font-medium">
{footerValue}
</span>
</Card.Footer>
diff --git a/frontend/src/lib/components/sheets/new-environment-sheet.svelte b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
index 457377a1f..1a5c8c23f 100644
--- a/frontend/src/lib/components/sheets/new-environment-sheet.svelte
+++ b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
@@ -5,7 +5,7 @@
import FormInput from '$lib/components/form/form-input.svelte';
import UrlInput from '$lib/components/form/url-input.svelte';
import { Spinner } from '$lib/components/ui/spinner/index.js';
- import * as Card from '$lib/components/ui/card';
+ import { CopyButton } from '$lib/components/ui/copy-button';
import type { CreateEnvironmentDTO } from '$lib/types/environment.type';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/form.utils';
@@ -19,130 +19,177 @@
let { open = $bindable(false), onEnvironmentCreated }: NewEnvironmentSheetProps = $props();
- let isSubmitting = $state(false);
+ let createdEnvironment = $state<{
+ id: string;
+ apiKey: string;
+ name: string;
+ apiUrl: string;
+ dockerRun?: string;
+ dockerCompose?: string;
+ } | null>(null);
- let urlProtocol = $state<'https' | 'http'>('https');
- let urlHost = $state('');
+ let isSubmittingNewAgent = $state(false);
+ let isLoadingSnippets = $state(false);
- $effect(() => {
- if (open) {
- urlProtocol = 'https';
- urlHost = '';
- formData.name = '';
- formData.apiUrl = '';
- formData.bootstrapToken = '';
- }
- });
+ let newAgentUrlProtocol = $state<'https' | 'http'>('http');
+ let newAgentUrlHost = $state('');
- const formSchema = z.object({
+ const newAgentFormSchema = z.object({
name: z.string().min(1, m.environments_name_required()).max(25, m.environments_name_too_long()),
- apiUrl: z.string().min(1, m.environments_server_url_required()),
- bootstrapToken: z.string()
+ apiUrl: z.string().min(1, m.environments_server_url_required())
});
- let formData = $state({
+ const { inputs: newAgentInputs, ...newAgentForm } = createForm<typeof newAgentFormSchema>(newAgentFormSchema, {
name: '',
- apiUrl: '',
- bootstrapToken: ''
+ apiUrl: ''
});
+ // Reset on open/close
$effect(() => {
- formData.apiUrl = urlHost;
+ if (open) {
+ createdEnvironment = null;
+ newAgentUrlProtocol = 'http';
+ newAgentUrlHost = '';
+ $newAgentInputs.name.value = '';
+ $newAgentInputs.apiUrl.value = '';
+ }
});
- let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
+ // Sync UrlInput value with form validation
+ $effect(() => {
+ $newAgentInputs.apiUrl.value = newAgentUrlHost;
+ });
- async function handleSubmit() {
- const data = form.validate();
+ async function handleNewAgentSubmit() {
+ const data = newAgentForm.validate();
if (!data) return;
try {
- isSubmitting = true;
-
- // Construct full URL from protocol and host
- const fullUrl = `${urlProtocol}://${urlHost}`;
+ isSubmittingNewAgent = true;
+ const fullUrl = `${newAgentUrlProtocol}://${newAgentUrlHost}`;
const dto: CreateEnvironmentDTO = {
name: data.name,
apiUrl: fullUrl,
- bootstrapToken: data.bootstrapToken
+ useApiKey: true
};
const created = await environmentManagementService.create(dto);
- try {
- const result = await environmentManagementService.testConnection(created.id);
- if (result.status === 'online') {
- toast.success(m.environments_test_connection_success());
- } else {
- toast.warning(m.environments_test_connection_error());
+ if (created.apiKey) {
+ createdEnvironment = {
+ id: created.id,
+ apiKey: created.apiKey,
+ name: created.name,
+ apiUrl: fullUrl
+ };
+
+ // Fetch deployment snippets from backend
+ isLoadingSnippets = true;
+ try {
+ const snippets = await environmentManagementService.getDeploymentSnippets(created.id);
+ createdEnvironment.dockerRun = snippets.dockerRun;
+ createdEnvironment.dockerCompose = snippets.dockerCompose;
+ } catch (err) {
+ console.error('Failed to fetch deployment snippets:', err);
+ } finally {
+ isLoadingSnippets = false;
}
- } catch (e) {
- console.error(e);
- toast.error(m.environments_test_connection_failed());
- }
-
- toast.success(m.environments_created_success());
- form.reset();
- onEnvironmentCreated?.();
+ toast.success(m.environments_created_success());
+ } else {
+ toast.error('Failed to generate API key');
+ }
} catch (error) {
toast.error(m.environments_create_failed());
console.error(error);
} finally {
- isSubmitting = false;
+ isSubmittingNewAgent = false;
}
}
+
+ function handleDone() {
+ onEnvironmentCreated?.();
+ open = false;
+ }
</script>
<ResponsiveDialog.Root
bind:open
variant="sheet"
- title={m.environments_title()}
- description={m.environments_manage_description()}
- contentClass="sm:max-w-lg"
+ title={createdEnvironment ? m.environments_created_title() : m.environments_create_new_agent()}
+ description={createdEnvironment ? m.environments_created_description() : m.environments_create_new_agent_description()}
+ contentClass="sm:max-w-2xl"
>
{#snippet children()}
- <div class="space-y-6 py-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="text-lg">{m.common_add_button({ resource: m.resource_environment_cap() })}</Card.Title>
- </Card.Header>
- <Card.Content class="px-6">
- <form onsubmit={preventDefault(handleSubmit)} class="space-y-4">
- <FormInput label={m.common_name()} placeholder={m.environments_name_placeholder()} bind:input={$inputs.name} />
-
- <UrlInput
- id="environment-api-url"
- label={m.environments_api_url()}
- placeholder={m.environments_api_url_placeholder()}
- description={m.environments_api_url_description()}
- bind:value={urlHost}
- bind:protocol={urlProtocol}
- disabled={isSubmitting}
- required
- error={$inputs.apiUrl.error ?? undefined}
- />
-
- <FormInput
- label={m.environments_bootstrap_label()}
- type="password"
- placeholder={m.environments_bootstrap_placeholder()}
- description={m.environments_pair_rotate_description()}
- bind:input={$inputs.bootstrapToken}
- />
-
- <Button type="submit" class="w-full" disabled={isSubmitting} onclick={handleSubmit}>
- {#if isSubmitting}
- <Spinner class="mr-2 size-4" />
+ <div class="space-y-6 px-6 py-6">
+ {#if createdEnvironment}
+ <div class="space-y-4">
+ <div class="space-y-2">
+ <div class="text-sm font-medium">{m.environments_api_key()}</div>
+ <div class="flex items-center gap-2">
+ <code class="bg-muted flex-1 rounded-md px-3 py-2 font-mono text-sm break-all">
+ {createdEnvironment.apiKey}
+ </code>
+ {#if createdEnvironment.apiKey}
+ <CopyButton text={createdEnvironment.apiKey} size="icon" class="size-7" />
{/if}
- {m.common_add_button({ resource: m.resource_environment_cap() })}
- </Button>
- </form>
- </Card.Content>
- </Card.Root>
+ </div>
+ <p class="text-muted-foreground text-xs">{m.environments_api_key_warning()}</p>
+ </div>
+
+ {#if isLoadingSnippets}
+ <div class="flex items-center justify-center py-8">
+ <Spinner class="size-6" />
+ </div>
+ {:else if createdEnvironment.dockerRun && createdEnvironment.dockerCompose}
+ <div class="space-y-2">
+ <div class="text-sm font-medium">{m.environments_docker_run_command()}</div>
+ <div class="relative">
+ <pre class="bg-muted overflow-x-auto rounded-md p-3 text-xs"><code>{createdEnvironment.dockerRun}</code></pre>
+ <div class="absolute top-2 right-2">
+ <CopyButton text={createdEnvironment.dockerRun} size="icon" class="size-7" />
+ </div>
+ </div>
+ </div>
+
+ <div class="space-y-2">
+ <div class="text-sm font-medium">{m.environments_docker_compose()}</div>
+ <div class="relative">
+ <pre class="bg-muted overflow-x-auto rounded-md p-3 text-xs"><code>{createdEnvironment.dockerCompose}</code></pre>
+ <div class="absolute top-2 right-2">
+ <CopyButton text={createdEnvironment.dockerCompose} size="icon" class="size-7" />
+ </div>
+ </div>
+ </div>
+ {/if}
+
+ <Button class="w-full" onclick={handleDone}>{m.common_done()}</Button>
+ </div>
+ {:else}
+ <form onsubmit={preventDefault(handleNewAgentSubmit)} class="space-y-4">
+ <FormInput label={m.common_name()} placeholder={m.environments_production_docker()} bind:input={$newAgentInputs.name} />
+
+ <UrlInput
+ id="new-agent-api-url"
+ label={m.environments_agent_address()}
+ placeholder={m.environments_agent_address_placeholder()}
+ description={m.environments_agent_address_description()}
+ bind:value={newAgentUrlHost}
+ bind:protocol={newAgentUrlProtocol}
+ disabled={isSubmittingNewAgent}
+ required
+ error={$newAgentInputs.apiUrl.error ?? undefined}
+ />
+
+ <Button type="submit" class="w-full" disabled={isSubmittingNewAgent}>
+ {#if isSubmittingNewAgent}
+ <Spinner class="mr-2 size-4" />
+ {/if}
+ {m.environments_generate_config()}
+ </Button>
+ </form>
+ {/if}
</div>
{/snippet}
</ResponsiveDialog.Root>
diff --git a/frontend/src/lib/services/env-mgmt-service.ts b/frontend/src/lib/services/env-mgmt-service.ts
index 86a046c81..254e0f8cd 100644
--- a/frontend/src/lib/services/env-mgmt-service.ts
+++ b/frontend/src/lib/services/env-mgmt-service.ts
@@ -38,6 +38,11 @@ export default class EnvironmentManagementService extends BaseAPIService {
async syncRegistries(environmentId: string): Promise<void> {
await this.api.post(`/environments/${environmentId}/sync-registries`);
}
+
+ async getDeploymentSnippets(environmentId: string): Promise<{ dockerRun: string; dockerCompose: string }> {
+ const res = await this.api.get(`/environments/${environmentId}/deployment`);
+ return res.data.data as { dockerRun: string; dockerCompose: string };
+ }
}
export const environmentManagementService = new EnvironmentManagementService();
diff --git a/frontend/src/lib/types/environment.type.ts b/frontend/src/lib/types/environment.type.ts
index cb2e8cb92..381fc2dd0 100644
--- a/frontend/src/lib/types/environment.type.ts
+++ b/frontend/src/lib/types/environment.type.ts
@@ -1,4 +1,4 @@
-export type EnvironmentStatus = 'online' | 'offline' | 'error';
+export type EnvironmentStatus = 'online' | 'offline' | 'error' | 'pending';
export type Environment = {
id: string;
@@ -7,12 +7,14 @@ export type Environment = {
status: EnvironmentStatus;
enabled: boolean;
lastSeen?: string;
+ apiKey?: string;
};
export interface CreateEnvironmentDTO {
apiUrl: string;
name: string;
bootstrapToken?: string;
+ useApiKey?: boolean;
}
export interface UpdateEnvironmentDTO {
@@ -20,4 +22,10 @@ export interface UpdateEnvironmentDTO {
name?: string;
enabled?: boolean;
bootstrapToken?: string;
+ regenerateApiKey?: boolean;
+}
+
+export interface DeploymentSnippets {
+ dockerRun: string;
+ dockerCompose: string;
}
diff --git a/frontend/src/routes/(app)/customize/templates/template-table.svelte b/frontend/src/routes/(app)/customize/templates/template-table.svelte
index 066cee9c7..635fbb0a1 100644
--- a/frontend/src/routes/(app)/customize/templates/template-table.svelte
+++ b/frontend/src/routes/(app)/customize/templates/template-table.svelte
@@ -4,7 +4,7 @@
import { Badge } from '$lib/components/ui/badge';
import { Spinner } from '$lib/components/ui/spinner/index.js';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import type { Table as TableType, Row } from '@tanstack/table-core';
+ import type { Table as TableType } from '@tanstack/table-core';
import * as Table from '$lib/components/ui/table/index.js';
import FlexRender from '$lib/components/ui/data-table/flex-render.svelte';
import { goto } from '$app/navigation';
@@ -20,7 +20,9 @@
import { templateService } from '$lib/services/template-service';
import { truncateString } from '$lib/utils/string.utils';
import DropdownCard from '$lib/components/dropdown-card.svelte';
- import { DataTableViewOptions } from '$lib/components/arcane-table/index.js';
+ import DataTableToolbar from '$lib/components/arcane-table/arcane-table-toolbar.svelte';
+ import { PersistedState } from 'runed';
+ import { onMount } from 'svelte';
import {
EllipsisIcon,
InspectIcon,
@@ -29,7 +31,10 @@
TrashIcon,
DownloadIcon,
TagIcon,
- MoveToFolderIcon
+ MoveToFolderIcon,
+ ArrowDownIcon,
+ ArrowRightIcon,
+ RegistryIcon
} from '$lib/icons';
type TemplateTable = TableType<Template>;
@@ -123,8 +128,38 @@
let mobileFieldVisibility = $state<Record<string, boolean>>({});
let customSettings = $state<Record<string, unknown>>({});
+ let collapsedGroupsState = $state<PersistedState<Record<string, boolean>> | null>(null);
+ let collapsedGroups = $derived(collapsedGroupsState?.current ?? {});
+
+ onMount(() => {
+ collapsedGroupsState = new PersistedState<Record<string, boolean>>('template-groups-collapsed', {});
+ });
+
let groupByRegistry = $derived((customSettings.groupByRegistry as boolean) ?? false);
+ function toggleGroup(groupName: string) {
+ if (!collapsedGroupsState) return;
+ collapsedGroupsState.current = {
+ ...collapsedGroupsState.current,
+ [groupName]: !collapsedGroupsState.current[groupName]
+ };
+ }
+
+ function onToggleMobileField(fieldId: string) {
+ mobileFieldVisibility = {
+ ...mobileFieldVisibility,
+ [fieldId]: !mobileFieldVisibility[fieldId]
+ };
+ }
+
+ const mobileFieldsForOptions = $derived(
+ mobileFields.map((field) => ({
+ id: field.id,
+ label: field.label,
+ visible: mobileFieldVisibility[field.id] ?? field.defaultVisible ?? true
+ }))
+ );
+
function getRegistryName(template: Template): string {
if (template.registry?.name) {
return template.registry.name;
@@ -329,68 +364,110 @@
</DropdownMenu.CheckboxItem>
{/snippet}
-{#snippet GroupedTableView({ table }: { table: TemplateTable })}
- <div class="mb-4 flex items-center justify-end border-b px-6 py-4">
- <DataTableViewOptions {table} customViewOptions={CustomViewOptions} />
- </div>
- <div class="space-y-4 px-6 pb-6">
- {#each groupedTemplates ?? [] as [registryName, registryTemplates] (registryName)}
- {@const registryTemplateIds = new Set(registryTemplates.map((t) => t.id))}
- {@const registryRows = table.getRowModel().rows.filter((row) => registryTemplateIds.has(row.original.id))}
-
- <DropdownCard
- id={`template-registry-${registryName}`}
- title={registryName}
- description={`${registryTemplates.length} ${registryTemplates.length === 1 ? m.resource_template() : m.resource_templates()}`}
- icon={registryName === m.templates_local_templates() ? FolderOpenIcon : GlobeIcon}
- >
- <div class="hidden md:block">
- <Table.Root
- class="**:data-[slot='table-container']:rounded-none **:data-[slot='table-container']:border-0 **:data-[slot='table-container']:bg-transparent **:data-[slot='table-container']:shadow-none **:data-[slot='table-container']:backdrop-filter-none"
- >
- <Table.Header class="border-border/40 border-t">
- {#each table.getHeaderGroups() as headerGroup (headerGroup.id)}
- <Table.Row>
- {#each headerGroup.headers as header (header.id)}
- <Table.Head colspan={header.colSpan}>
- {#if !header.isPlaceholder}
- <FlexRender content={header.column.columnDef.header} context={header.getContext()} />
- {/if}
- </Table.Head>
- {/each}
- </Table.Row>
- {/each}
- </Table.Header>
- <Table.Body>
- {#each registryRows as row (row.id)}
- <Table.Row data-state={(selectedIds ?? []).includes((row.original as Template).id) && 'selected'}>
- {#each row.getVisibleCells() as cell (cell.id)}
- <Table.Cell>
- <FlexRender content={cell.column.columnDef.cell} context={cell.getContext()} />
- </Table.Cell>
- {/each}
- </Table.Row>
- {:else}
- <Table.Row>
- <Table.Cell colspan={table.getAllColumns().length} class="h-24 text-center"
- >{m.common_no_results_found()}</Table.Cell
+{#snippet GroupedTableView({ table, renderPagination }: { table: TemplateTable; renderPagination: import('svelte').Snippet })}
+ <div class="flex h-full flex-col">
+ <div class="shrink-0 border-b">
+ <DataTableToolbar
+ {table}
+ {selectedIds}
+ selectionDisabled={true}
+ mobileFields={mobileFieldsForOptions}
+ {onToggleMobileField}
+ customViewOptions={CustomViewOptions}
+ />
+ </div>
+
+ <div class="hidden flex-1 overflow-auto px-6 py-8 md:block">
+ <div class="overflow-x-auto rounded-md border">
+ <Table.Root>
+ <Table.Header>
+ {#each table.getHeaderGroups() as headerGroup (headerGroup.id)}
+ <Table.Row>
+ {#each headerGroup.headers as header (header.id)}
+ <Table.Head colspan={header.colSpan}>
+ {#if !header.isPlaceholder}
+ <FlexRender content={header.column.columnDef.header} context={header.getContext()} />
+ {/if}
+ </Table.Head>
+ {/each}
+ </Table.Row>
+ {/each}
+ </Table.Header>
+ <Table.Body>
+ {#each groupedTemplates ?? [] as [registryName, registryTemplates] (registryName)}
+ <Table.Row
+ class="bg-muted/50 hover:bg-muted/60 cursor-pointer transition-colors"
+ onclick={() => toggleGroup(registryName)}
+ >
+ <Table.Cell colspan={table.getAllColumns().length} class="py-3 font-medium">
+ <div class="flex items-center gap-2">
+ {#if collapsedGroups[registryName]}
+ <ArrowRightIcon class="text-muted-foreground size-4" />
+ {:else}
+ <ArrowDownIcon class="text-muted-foreground size-4" />
+ {/if}
+ {#if registryName === m.templates_local_templates()}
+ <FolderOpenIcon class="text-muted-foreground size-4" />
+ {:else}
+ <RegistryIcon class="text-muted-foreground size-4" />
+ {/if}
+ <span>{registryName}</span>
+ <span class="text-muted-foreground text-xs font-normal">({registryTemplates.length})</span>
+ </div>
+ </Table.Cell>
+ </Table.Row>
+
+ {#if !collapsedGroups[registryName]}
+ {@const registryTemplateIds = new Set(registryTemplates.map((t) => t.id))}
+ {@const registryRows = table
+ .getRowModel()
+ .rows.filter((row) => registryTemplateIds.has((row.original as Template).id))}
+
+ {#each registryRows as row (row.id)}
+ <Table.Row
+ data-state={(selectedIds ?? []).includes((row.original as Template).id) && 'selected'}
+ class="hover:bg-primary/5 transition-colors"
>
- </Table.Row>
- {/each}
- </Table.Body>
- </Table.Root>
- </div>
+ {#each row.getVisibleCells() as cell, i (cell.id)}
+ <Table.Cell class={i === 0 ? 'pl-12' : ''}>
+ <FlexRender content={cell.column.columnDef.cell} context={cell.getContext()} />
+ </Table.Cell>
+ {/each}
+ </Table.Row>
+ {/each}
+ {/if}
+ {/each}
+ </Table.Body>
+ </Table.Root>
+ </div>
+ </div>
- <div class="space-y-3 md:hidden">
- {#each registryRows as row (row.id)}
- {@render TemplateMobileCardSnippet({ item: row.original as Template, mobileFieldVisibility })}
- {:else}
- <div class="flex h-24 items-center justify-center text-center text-muted-foreground">
- {m.common_no_results_found()}
- </div>
- {/each}
- </div>
- </DropdownCard>
- {/each}
+ <div class="space-y-4 px-6 py-2 md:hidden">
+ {#each groupedTemplates ?? [] as [registryName, registryTemplates] (registryName)}
+ {@const registryTemplateIds = new Set(registryTemplates.map((t) => t.id))}
+ {@const registryRows = table.getRowModel().rows.filter((row) => registryTemplateIds.has((row.original as Template).id))}
+
+ <DropdownCard
+ id={`template-registry-${registryName}`}
+ title={registryName}
+ description={`${registryTemplates.length} ${registryTemplates.length === 1 ? m.resource_template() : m.resource_templates()}`}
+ icon={registryName === m.templates_local_templates() ? FolderOpenIcon : RegistryIcon}
+ >
+ <div class="space-y-3">
+ {#each registryRows as row (row.id)}
+ {@render TemplateMobileCardSnippet({ item: row.original as Template, mobileFieldVisibility })}
+ {:else}
+ <div class="h-24 flex items-center justify-center text-center text-muted-foreground">
+ {m.common_no_results_found()}
+ </div>
+ {/each}
+ </div>
+ </DropdownCard>
+ {/each}
+ </div>
+
+ <div class="shrink-0 border-t px-2 py-4">
+ {@render renderPagination()}
+ </div>
</div>
{/snippet}
diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelte
index 8cfac450f..0ba2e0487 100644
--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte
@@ -14,17 +14,19 @@
import { environmentManagementService } from '$lib/services/env-mgmt-service.js';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { Spinner } from '$lib/components/ui/spinner/index.js';
+ import { CopyButton } from '$lib/components/ui/copy-button';
import {
ArrowLeftIcon,
RefreshIcon,
- SettingsIcon,
ConnectionIcon,
SaveIcon,
EnvironmentsIcon,
AlertIcon,
TestIcon,
RegistryIcon,
- ResetIcon
+ ResetIcon,
+ ApiKeyIcon,
+ DockerBrandIcon
} from '$lib/icons';
let { data } = $props();
@@ -36,10 +38,11 @@
let isRefreshing = $state(false);
let isTestingConnection = $state(false);
- let isPairing = $state(false);
let isSaving = $state(false);
let isSyncingRegistries = $state(false);
- let bootstrapToken = $state('');
+ let isRegeneratingKey = $state(false);
+ let showRegenerateDialog = $state(false);
+ let regeneratedApiKey = $state<string | null>(null);
// Form state
let formName = $state('');
@@ -47,7 +50,7 @@
let formApiUrl = $state('');
// Track current status separately from environment data
- let currentStatus = $state<'online' | 'offline' | 'error'>('offline');
+ let currentStatus = $state<'online' | 'offline' | 'error' | 'pending'>('offline');
// Initialize form values and status
$effect(() => {
@@ -125,24 +128,6 @@
isTestingConnection = false;
}
}
- async function pairOrRotate() {
- if (!bootstrapToken) {
- toast.error(m.environments_bootstrap_required());
- return;
- }
- try {
- isPairing = true;
- await environmentManagementService.update(environment.id, { bootstrapToken });
- toast.success(m.environments_agent_paired_success());
- bootstrapToken = '';
- await invalidateAll();
- } catch (e) {
- console.error(e);
- toast.error(m.environments_agent_pair_failed());
- } finally {
- isPairing = false;
- }
- }
async function handleSave() {
if (!hasChanges || isSaving) return;
@@ -184,6 +169,31 @@
toast.info(m.environments_changes_reset());
}
+ async function handleRegenerateApiKey() {
+ try {
+ isRegeneratingKey = true;
+
+ // Delete the old API key and create a new one
+ const result = await environmentManagementService.update(environment.id, {
+ regenerateApiKey: true
+ });
+
+ if (result.apiKey) {
+ regeneratedApiKey = result.apiKey;
+ toast.success(m.environments_regenerate_key_success());
+ await invalidateAll();
+ } else {
+ toast.error(m.environments_regenerate_key_failed());
+ }
+ } catch (error) {
+ console.error('Failed to regenerate API key:', error);
+ toast.error(m.environments_regenerate_key_failed());
+ } finally {
+ isRegeneratingKey = false;
+ showRegenerateDialog = false;
+ }
+ }
+
async function confirmSwitchAndEdit() {
try {
await environmentStore.setEnvironment(environment);
@@ -345,7 +355,7 @@
{#if settings}
<Card.Root class="flex flex-col">
- <Card.Header icon={SettingsIcon}>
+ <Card.Header icon={DockerBrandIcon}>
<div class="flex flex-col space-y-1.5">
<Card.Title>
<h2>{m.environments_docker_settings_title()}</h2>
@@ -456,43 +466,72 @@
{#if environment.id !== '0'}
<Card.Root class="flex flex-col">
- <Card.Header icon={SettingsIcon}>
+ <Card.Header icon={ApiKeyIcon}>
<div class="flex flex-col space-y-1.5">
<Card.Title>
- <h2>{m.environments_pair_rotate_title()}</h2>
+ <h2>{m.environments_agent_config_title()}</h2>
</Card.Title>
- <Card.Description>{m.environments_pair_rotate_description()}</Card.Description>
+ <Card.Description>{m.environments_agent_config_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}
+ {#if regeneratedApiKey}
+ <div class="space-y-4">
+ <div class="space-y-2">
+ <div class="text-sm font-medium">{m.environments_new_api_key()}</div>
+ <div class="flex items-center gap-2">
+ <code class="bg-muted flex-1 rounded-md px-3 py-2 font-mono text-sm break-all">
+ {regeneratedApiKey}
+ </code>
+ <CopyButton text={regeneratedApiKey} size="icon" class="size-7" />
+ </div>
+ <p class="text-muted-foreground text-xs">{m.environments_api_key_save_warning()}</p>
+ </div>
+ <Button variant="outline" onclick={() => (regeneratedApiKey = null)} class="w-full">
+ {m.common_dismiss()}
+ </Button>
+ </div>
+ {:else}
+ <div class="rounded-lg border border-amber-500/30 bg-amber-500/10 p-4 text-sm text-amber-900 dark:text-amber-200">
+ <p class="font-medium">{m.environments_regenerate_warning_title()}</p>
+ <p class="mt-1">{m.environments_regenerate_warning_message()}</p>
+ </div>
+ <Button
+ variant="destructive"
+ onclick={() => (showRegenerateDialog = true)}
+ disabled={isRegeneratingKey}
+ class="w-full"
+ >
+ {#if isRegeneratingKey}
<Spinner class="size-4" />
{:else}
- <SettingsIcon class="size-4" />
+ <ResetIcon class="size-4" />
{/if}
- {m.environments_pair_rotate_action()}
+ {m.environments_regenerate_api_key()}
</Button>
- <Button variant="outline" onclick={() => (bootstrapToken = '')} disabled={isPairing}>
- {m.common_clear()}
- </Button>
- </div>
+ {/if}
</Card.Content>
</Card.Root>
{/if}
</div>
+ <AlertDialog.Root bind:open={showRegenerateDialog}>
+ <AlertDialog.Content>
+ <AlertDialog.Header>
+ <AlertDialog.Title>{m.environments_regenerate_dialog_title()}</AlertDialog.Title>
+ <AlertDialog.Description>
+ {m.environments_regenerate_dialog_message()}
+ </AlertDialog.Description>
+ </AlertDialog.Header>
+ <AlertDialog.Footer>
+ <AlertDialog.Cancel>{m.common_cancel()}</AlertDialog.Cancel>
+ <AlertDialog.Action onclick={handleRegenerateApiKey}>
+ {m.environments_regenerate_api_key()}
+ </AlertDialog.Action>
+ </AlertDialog.Footer>
+ </AlertDialog.Content>
+ </AlertDialog.Root>
+
<AlertDialog.Root bind:open={showSwitchDialog}>
<AlertDialog.Content>
<AlertDialog.Header>
diff --git a/frontend/src/routes/(app)/environments/environment-table.svelte b/frontend/src/routes/(app)/environments/environment-table.svelte
index f27aa2329..24344ede2 100644
--- a/frontend/src/routes/(app)/environments/environment-table.svelte
+++ b/frontend/src/routes/(app)/environments/environment-table.svelte
@@ -260,7 +260,9 @@
{/snippet}
{#snippet StatusCell({ value }: { value: unknown })}
- <StatusBadge text={capitalizeFirstLetter(String(value)) || m.common_unknown()} variant={value === 'online' ? 'green' : 'red'} />
+ {@const statusValue = String(value)}
+ {@const variant = statusValue === 'online' ? 'green' : statusValue === 'pending' ? 'amber' : 'red'}
+ <StatusBadge text={capitalizeFirstLetter(statusValue) || m.common_unknown()} {variant} />
{/snippet}
{#snippet ApiCell({ value }: { value: unknown })}
diff --git a/frontend/src/routes/(app)/settings/+layout.svelte b/frontend/src/routes/(app)/settings/+layout.svelte
index 325fd90af..99f48726a 100644
--- a/frontend/src/routes/(app)/settings/+layout.svelte
+++ b/frontend/src/routes/(app)/settings/+layout.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import { page } from '$app/state';
- import { goto } from '$app/navigation';
+ import { goto, beforeNavigate } from '$app/navigation';
import { setContext } from 'svelte';
import { Button } from '$lib/components/ui/button';
import { SettingsIcon, ArrowRightIcon, ArrowLeftIcon, SaveIcon, ResetIcon } from '$lib/icons';
@@ -159,6 +159,14 @@
// Set context so forms can update the header state
setContext('settingsFormState', formState);
+ // Reset form state before navigating to a new page
+ beforeNavigate(() => {
+ formState.hasChanges = false;
+ formState.isLoading = false;
+ formState.saveFunction = null;
+ formState.resetFunction = null;
+ });
+
function goBackToSettings() {
goto('/settings');
}
@@ -240,7 +248,7 @@
</div>
<!-- Mobile Floating Action Buttons -->
-{#if isSubPage && !isReadOnly}
+{#if isSubPage && !isReadOnly && formState.saveFunction}
<div
class="fixed right-4 z-50 flex flex-col gap-3 transition-all duration-300 ease-out sm:hidden"
style="bottom: {scrollToHideEnabled && !mobileNavVisible
diff --git a/go.work.sum b/go.work.sum
index 4d05a6623..9c5e6f110 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -328,6 +328,7 @@ github.com/jackc/pgx/v4 v4.18.2 h1:xVpYkNR5pk5bMCZGfClbO962UIqVABcAGt7ha1s/FeU=
github.com/jackc/pgx/v4 v4.18.2/go.mod h1:Ey4Oru5tH5sB6tV7hDmfWFahwF15Eb7DNXlRKx2CkVw=
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
+github.com/jordanlewis/gcassert v0.0.0-20250430164644-389ef753e22e/go.mod h1:ZybsQk6DWyN5t7An1MuPm1gtSZ1xDaTXS9ZjIOxvQrk=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA=
diff --git a/types/environment/environment.go b/types/environment/environment.go
index 667c1d425..fff8e40a7 100644
--- a/types/environment/environment.go
+++ b/types/environment/environment.go
@@ -25,6 +25,11 @@ type Create struct {
//
// Required: false
BootstrapToken *string `json:"bootstrapToken,omitempty"`
+
+ // UseApiKey indicates if an API key should be generated for pairing.
+ //
+ // Required: false
+ UseApiKey *bool `json:"useApiKey,omitempty"`
}
type Update struct {
@@ -52,6 +57,11 @@ type Update struct {
//
// Required: false
BootstrapToken *string `json:"bootstrapToken,omitempty"`
+
+ // RegenerateApiKey indicates whether to regenerate the API key.
+ //
+ // Required: false
+ RegenerateApiKey *bool `json:"regenerateApiKey,omitempty"`
}
type Test struct {
@@ -100,6 +110,10 @@ type Environment struct {
//
// Required: true
Enabled bool `json:"enabled"`
+ // ApiKey is returned only when creating or regenerating
+ //
+ // Required: false
+ ApiKey *string `json:"apiKey,omitempty"`
}
// AgentPairRequest is the request body for pairing with an agent.