Skip to content

Modern Docker Management, Designed for Everyone

feat!: remote environments (#305)

Kyle Mendell8fb5815c8b86
diff --git a/.env.example b/.env.example
index 90583411f..73a07c5d2 100644
--- a/.env.example
+++ b/.env.example
@@ -6,7 +6,7 @@ DATABASE_URL=sqlite://data/arcane.db
# Encryption key for sensitive data (must be exactly 32 characters)
# Generate a secure key for production: openssl rand -base64 32 | head -c 32
-ENCRYPTION_KEY=xxx
+ENCRYPTION_KEY=f00V7L3pqj+yMtfUkpFAyaRTxoGo+600
# JWT Secret (generate a secure one in production)
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
@@ -15,7 +15,7 @@ OIDC_ENABLED=true
OIDC_CLIENT_ID=""
OIDC_CLIENT_SECRET=""
OIDC_REDIRECT_URI="http://localhost:8080/auth/oidc/callback"
-OIDC_AUTHORIZATION_ENDPOINT="https://id.ofkm.us/authorize"
-OIDC_TOKEN_ENDPOINT="https://id.ofkm.us/api/oidc/token"
-OIDC_USERINFO_ENDPOINT="https://id.ofkm.us/api/oidc/userinfo"
+OIDC_AUTHORIZATION_ENDPOINT="https://example.com/authorize"
+OIDC_TOKEN_ENDPOINT="https://example.com/api/oidc/token"
+OIDC_USERINFO_ENDPOINT="https://example.com/api/oidc/userinfo"
OIDC_SCOPES="openid email profile" # Space separated list of scopes
\ No newline at end of file
diff --git a/backend/internal/api/agent_handler.go b/backend/internal/api/agent_handler.go
deleted file mode 100644
index 23fbeebf2..000000000
--- a/backend/internal/api/agent_handler.go
+++ /dev/null
@@ -1,411 +0,0 @@
-package api
-
-import (
- "net/http"
-
- "github.com/gin-gonic/gin"
- "github.com/ofkm/arcane-backend/internal/models"
- "github.com/ofkm/arcane-backend/internal/services"
-)
-
-type AgentHandler struct {
- agentService *services.AgentService
- deploymentService *services.DeploymentService
-}
-
-func NewAgentHandler(agentService *services.AgentService, deploymentService *services.DeploymentService) *AgentHandler {
- return &AgentHandler{
- agentService: agentService,
- deploymentService: deploymentService,
- }
-}
-
-type AgentResponse struct {
- *models.Agent
- Status string `json:"status"`
-}
-
-func (h *AgentHandler) ListAgents(c *gin.Context) {
- agents, err := h.agentService.ListAgents(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to fetch agents",
- })
- return
- }
-
- timeoutMinutes := 5
- agentResponses := make([]*AgentResponse, len(agents))
- for i, agent := range agents {
- status := "offline"
- if h.agentService.IsAgentOnline(agent, timeoutMinutes) {
- status = "online"
- }
-
- agentResponses[i] = &AgentResponse{
- Agent: agent,
- Status: status,
- }
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "agents": agentResponses,
- "count": len(agentResponses),
- })
-}
-
-func (h *AgentHandler) GetAgent(c *gin.Context) {
- agentID := c.Param("agentId")
-
- agent, err := h.agentService.GetAgentByID(c.Request.Context(), agentID)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "error": "Agent not found",
- })
- return
- }
-
- timeoutMinutes := 5
- status := "offline"
- if h.agentService.IsAgentOnline(agent, timeoutMinutes) {
- status = "online"
- }
-
- agentResponse := &AgentResponse{
- Agent: agent,
- Status: status,
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "agent": agentResponse,
- })
-}
-
-func (h *AgentHandler) DeleteAgent(c *gin.Context) {
- agentID := c.Param("agentId")
-
- err := h.agentService.DeleteAgent(c.Request.Context(), agentID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to delete agent",
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "Agent deleted successfully",
- })
-}
-
-type CreateTaskRequest struct {
- Type models.AgentTaskType `json:"type" binding:"required"`
- Payload map[string]interface{} `json:"payload" binding:"required"`
-}
-
-func (h *AgentHandler) GetAgentTasks(c *gin.Context) {
- agentID := c.Param("agentId")
-
- tasks, err := h.agentService.ListTasks(c.Request.Context(), &agentID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to fetch tasks",
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "tasks": tasks,
- "count": len(tasks),
- })
-}
-
-func (h *AgentHandler) CreateTask(c *gin.Context) {
- agentID := c.Param("agentId")
-
- var req CreateTaskRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": "Invalid request format",
- })
- return
- }
-
- task, err := h.agentService.CreateTask(c.Request.Context(), agentID, req.Type, req.Payload)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to create task",
- })
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "task": task,
- })
-}
-
-func (h *AgentHandler) GetTask(c *gin.Context) {
- taskID := c.Param("taskId")
-
- task, err := h.agentService.GetTaskByID(c.Request.Context(), taskID)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "error": "Task not found",
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "task": task,
- })
-}
-
-type SubmitTaskResultRequest struct {
- Status models.AgentTaskStatus `json:"status" binding:"required"`
- Result map[string]interface{} `json:"result,omitempty"`
- Error *string `json:"error,omitempty"`
-}
-
-func (h *AgentHandler) SubmitTaskResult(c *gin.Context) {
- taskID := c.Param("taskId")
-
- var req SubmitTaskResultRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": "Invalid request format",
- })
- return
- }
-
- err := h.agentService.UpdateTaskStatus(c.Request.Context(), taskID, req.Status, req.Result, req.Error)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to update task status",
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "Task result submitted successfully",
- })
-}
-
-func (h *AgentHandler) GetAgentDeployments(c *gin.Context) {
- agentID := c.Param("agentId")
-
- deployments, err := h.deploymentService.ListDeployments(c.Request.Context(), &agentID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to fetch deployments",
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "deployments": deployments,
- "count": len(deployments),
- })
-}
-
-type DeployStackRequest struct {
- StackName string `json:"stackName" binding:"required"`
- ComposeContent string `json:"composeContent" binding:"required"`
- EnvContent *string `json:"envContent,omitempty"`
-}
-
-func (h *AgentHandler) DeployStack(c *gin.Context) {
- agentID := c.Param("agentId")
-
- var req DeployStackRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": "Invalid request format",
- })
- return
- }
-
- task, err := h.agentService.DeployStackToAgent(c.Request.Context(), agentID, req.StackName, req.ComposeContent, req.EnvContent)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to create deployment task",
- })
- return
- }
-
- deployment, err := h.deploymentService.CreateStackDeployment(c.Request.Context(), agentID, req.StackName, req.ComposeContent, req.EnvContent, &task.ID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to create deployment record",
- })
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "deployment": deployment,
- "task": task,
- })
-}
-
-type DeployContainerRequest struct {
- ContainerName string `json:"containerName" binding:"required"`
- ImageName string `json:"imageName" binding:"required"`
- Ports []string `json:"ports,omitempty"`
- Volumes []string `json:"volumes,omitempty"`
- Environment []string `json:"environment,omitempty"`
-}
-
-func (h *AgentHandler) DeployContainer(c *gin.Context) {
- agentID := c.Param("agentId")
-
- var req DeployContainerRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": "Invalid request format",
- })
- return
- }
-
- payload := map[string]interface{}{
- "containerName": req.ContainerName,
- "imageName": req.ImageName,
- "ports": req.Ports,
- "volumes": req.Volumes,
- "environment": req.Environment,
- }
-
- task, err := h.agentService.CreateTask(c.Request.Context(), agentID, models.TaskContainerStart, payload)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to create deployment task",
- })
- return
- }
-
- deployment, err := h.deploymentService.CreateContainerDeployment(c.Request.Context(), agentID, req.ContainerName, req.ImageName, req.Ports, req.Volumes, &task.ID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to create deployment record",
- })
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "deployment": deployment,
- "task": task,
- })
-}
-
-type DeployImageRequest struct {
- ImageName string `json:"imageName" binding:"required"`
-}
-
-func (h *AgentHandler) DeployImage(c *gin.Context) {
- agentID := c.Param("agentId")
-
- var req DeployImageRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": "Invalid request format",
- })
- return
- }
-
- task, err := h.agentService.PullImageOnAgent(c.Request.Context(), agentID, req.ImageName)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to create image pull task",
- })
- return
- }
-
- deployment, err := h.deploymentService.CreateImageDeployment(c.Request.Context(), agentID, req.ImageName, &task.ID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to create deployment record",
- })
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "deployment": deployment,
- "task": task,
- })
-}
-
-func (h *AgentHandler) GetAgentStacks(c *gin.Context) {
- agentID := c.Param("agentId")
-
- stacks := []interface{}{}
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "stacks": stacks,
- "count": len(stacks),
- "agentId": agentID,
- })
-}
-
-func (h *AgentHandler) SendHealthCheck(c *gin.Context) {
- agentID := c.Param("agentId")
-
- task, err := h.agentService.SendHealthCheck(c.Request.Context(), agentID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to send health check",
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "task": task,
- })
-}
-
-func (h *AgentHandler) GetStackList(c *gin.Context) {
- agentID := c.Param("agentId")
-
- task, err := h.agentService.GetStackList(c.Request.Context(), agentID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to request stack list",
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "task": task,
- })
-}
diff --git a/backend/internal/api/container_handler.go b/backend/internal/api/container_handler.go
index 1ede8d447..63c38f6b8 100644
--- a/backend/internal/api/container_handler.go
+++ b/backend/internal/api/container_handler.go
@@ -15,14 +15,53 @@ import (
type ContainerHandler struct {
containerService *services.ContainerService
+ imageService *services.ImageService
}
-func NewContainerHandler(containerService *services.ContainerService) *ContainerHandler {
+func NewContainerHandler(containerService *services.ContainerService, imageService *services.ImageService) *ContainerHandler {
return &ContainerHandler{
containerService: containerService,
+ imageService: imageService,
}
}
+func (h *ContainerHandler) PullImage(c *gin.Context) {
+ id := c.Param("containerId")
+
+ container, err := h.containerService.GetContainerByID(c.Request.Context(), id)
+ if err != nil {
+ c.JSON(http.StatusNotFound, gin.H{
+ "success": false,
+ "error": "Container not found: " + err.Error(),
+ })
+ return
+ }
+
+ imageName := container.Image
+ if imageName == "" {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "error": "Container has no image to pull",
+ })
+ return
+ }
+
+ err = h.imageService.PullImage(c.Request.Context(), imageName, c.Writer)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to pull image: " + err.Error(),
+ })
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "Image pulled successfully",
+ "image": imageName,
+ })
+}
+
func (h *ContainerHandler) List(c *gin.Context) {
includeAll := c.Query("all") == "true"
@@ -42,7 +81,7 @@ func (h *ContainerHandler) List(c *gin.Context) {
}
func (h *ContainerHandler) GetByID(c *gin.Context) {
- id := c.Param("id")
+ id := c.Param("containerId")
container, err := h.containerService.GetContainerByID(c.Request.Context(), id)
if err != nil {
@@ -60,7 +99,7 @@ func (h *ContainerHandler) GetByID(c *gin.Context) {
}
func (h *ContainerHandler) Start(c *gin.Context) {
- id := c.Param("id")
+ id := c.Param("containerId")
if err := h.containerService.StartContainer(c.Request.Context(), id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
@@ -77,7 +116,7 @@ func (h *ContainerHandler) Start(c *gin.Context) {
}
func (h *ContainerHandler) Stop(c *gin.Context) {
- id := c.Param("id")
+ id := c.Param("containerId")
if err := h.containerService.StopContainer(c.Request.Context(), id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
@@ -94,7 +133,7 @@ func (h *ContainerHandler) Stop(c *gin.Context) {
}
func (h *ContainerHandler) Restart(c *gin.Context) {
- id := c.Param("id")
+ id := c.Param("containerId")
if err := h.containerService.RestartContainer(c.Request.Context(), id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
@@ -149,7 +188,7 @@ func (h *ContainerHandler) Delete(c *gin.Context) {
}
func (h *ContainerHandler) IsImageInUse(c *gin.Context) {
- imageID := c.Param("id")
+ imageID := c.Param("imageId")
if imageID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
@@ -278,7 +317,7 @@ func (h *ContainerHandler) Create(c *gin.Context) {
// GetStats returns container resource usage statistics
func (h *ContainerHandler) GetStats(c *gin.Context) {
- containerID := c.Param("id")
+ containerID := c.Param("containerId")
if containerID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
@@ -306,7 +345,7 @@ func (h *ContainerHandler) GetStats(c *gin.Context) {
}
func (h *ContainerHandler) GetStatsStream(c *gin.Context) {
- containerID := c.Param("id")
+ containerID := c.Param("containerId")
if containerID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
@@ -352,7 +391,7 @@ func (h *ContainerHandler) GetStatsStream(c *gin.Context) {
}
func (h *ContainerHandler) GetLogsStream(c *gin.Context) {
- containerID := c.Param("id")
+ containerID := c.Param("containerId")
if containerID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
diff --git a/backend/internal/api/deployment_handler.go b/backend/internal/api/deployment_handler.go
deleted file mode 100644
index b8aa9efde..000000000
--- a/backend/internal/api/deployment_handler.go
+++ /dev/null
@@ -1,231 +0,0 @@
-package api
-
-import (
- "net/http"
- "strconv"
- "time"
-
- "github.com/gin-gonic/gin"
- "github.com/ofkm/arcane-backend/internal/models"
- "github.com/ofkm/arcane-backend/internal/services"
-)
-
-type DeploymentHandler struct {
- deploymentService *services.DeploymentService
-}
-
-func NewDeploymentHandler(deploymentService *services.DeploymentService) *DeploymentHandler {
- return &DeploymentHandler{
- deploymentService: deploymentService,
- }
-}
-
-func (h *DeploymentHandler) ListDeployments(c *gin.Context) {
- var agentID *string
- if agentParam := c.Query("agentId"); agentParam != "" {
- agentID = &agentParam
- }
-
- page := 1
- limit := 50
- if pageParam := c.Query("page"); pageParam != "" {
- if p, err := strconv.Atoi(pageParam); err == nil && p > 0 {
- page = p
- }
- }
- if limitParam := c.Query("limit"); limitParam != "" {
- if l, err := strconv.Atoi(limitParam); err == nil && l > 0 && l <= 100 {
- limit = l
- }
- }
-
- deployments, err := h.deploymentService.ListDeployments(c.Request.Context(), agentID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to fetch deployments",
- })
- return
- }
-
- total := len(deployments)
- start := (page - 1) * limit
- end := start + limit
-
- if start >= total {
- deployments = []*models.Deployment{}
- } else {
- if end > total {
- end = total
- }
- deployments = deployments[start:end]
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "deployments": deployments,
- "pagination": gin.H{
- "page": page,
- "limit": limit,
- "total": total,
- "pages": (total + limit - 1) / limit,
- },
- })
-}
-
-func (h *DeploymentHandler) GetDeployment(c *gin.Context) {
- deploymentID := c.Param("deploymentId")
-
- deployment, err := h.deploymentService.GetDeploymentByID(c.Request.Context(), deploymentID)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "error": "Deployment not found",
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "deployment": deployment,
- })
-}
-
-func (h *DeploymentHandler) DeleteDeployment(c *gin.Context) {
- deploymentID := c.Param("deploymentId")
-
- err := h.deploymentService.DeleteDeployment(c.Request.Context(), deploymentID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to delete deployment",
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "Deployment deleted successfully",
- })
-}
-
-func (h *DeploymentHandler) UpdateDeploymentStatus(c *gin.Context) {
- deploymentID := c.Param("deploymentId")
-
- type UpdateStatusRequest struct {
- Status string `json:"status" binding:"required"`
- Error *string `json:"error,omitempty"`
- }
-
- var req UpdateStatusRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": "Invalid request format",
- })
- return
- }
-
- var status models.DeploymentStatus
- switch req.Status {
- case "pending":
- status = models.DeploymentStatusPending
- case "running":
- status = models.DeploymentStatusRunning
- case "stopped":
- status = models.DeploymentStatusStopped
- case "failed":
- status = models.DeploymentStatusFailed
- case "completed":
- status = models.DeploymentStatusCompleted
- default:
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": "Invalid deployment status",
- })
- return
- }
-
- err := h.deploymentService.UpdateDeploymentStatus(c.Request.Context(), deploymentID, status, req.Error)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to update deployment status",
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "Deployment status updated successfully",
- })
-}
-
-func (h *DeploymentHandler) GetDeploymentStats(c *gin.Context) {
- deployments, err := h.deploymentService.ListDeployments(c.Request.Context(), nil)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to fetch deployment statistics",
- })
- return
- }
-
- stats := map[string]int{
- "total": len(deployments),
- "pending": 0,
- "running": 0,
- "stopped": 0,
- "failed": 0,
- "completed": 0,
- }
-
- typeStats := map[string]int{
- "stack": 0,
- "container": 0,
- "image": 0,
- }
-
- for _, deployment := range deployments {
- stats[string(deployment.Status)]++
- typeStats[string(deployment.Type)]++
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "stats": gin.H{
- "total": stats["total"],
- "byStatus": stats,
- "byType": typeStats,
- "timestamp": time.Now().Unix(),
- },
- })
-}
-
-func (h *DeploymentHandler) GetRecentDeployments(c *gin.Context) {
- limit := 10
- if limitParam := c.Query("limit"); limitParam != "" {
- if l, err := strconv.Atoi(limitParam); err == nil && l > 0 && l <= 50 {
- limit = l
- }
- }
-
- deployments, err := h.deploymentService.ListDeployments(c.Request.Context(), nil)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": "Failed to fetch recent deployments",
- })
- return
- }
-
- if len(deployments) > limit {
- deployments = deployments[:limit]
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "deployments": deployments,
- "count": len(deployments),
- })
-}
diff --git a/backend/internal/api/environment_handler.go b/backend/internal/api/environment_handler.go
new file mode 100644
index 000000000..79244b48b
--- /dev/null
+++ b/backend/internal/api/environment_handler.go
@@ -0,0 +1,690 @@
+package api
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/ofkm/arcane-backend/internal/dto"
+ "github.com/ofkm/arcane-backend/internal/models"
+ "github.com/ofkm/arcane-backend/internal/services"
+)
+
+const LOCAL_DOCKER_ENVIRONMENT_ID = "0"
+
+type EnvironmentHandler struct {
+ environmentService *services.EnvironmentService
+ containerService *services.ContainerService
+ imageService *services.ImageService
+ networkService *services.NetworkService
+ volumeService *services.VolumeService
+ stackService *services.StackService
+}
+
+func NewEnvironmentHandler(
+ environmentService *services.EnvironmentService,
+ containerService *services.ContainerService,
+ imageService *services.ImageService,
+ networkService *services.NetworkService,
+ volumeService *services.VolumeService,
+ stackService *services.StackService,
+) *EnvironmentHandler {
+ return &EnvironmentHandler{
+ environmentService: environmentService,
+ containerService: containerService,
+ imageService: imageService,
+ networkService: networkService,
+ volumeService: volumeService,
+ stackService: stackService,
+ }
+}
+
+func (h *EnvironmentHandler) routeRequest(c *gin.Context, endpoint string) {
+ environmentID := c.Param("id")
+
+ if environmentID == LOCAL_DOCKER_ENVIRONMENT_ID {
+ h.handleLocalRequest(c, endpoint)
+ return
+ }
+
+ h.handleRemoteRequest(c, environmentID, endpoint)
+}
+
+func (h *EnvironmentHandler) handleLocalRequest(c *gin.Context, endpoint string) {
+ switch {
+ case endpoint == "/containers" && c.Request.Method == "GET":
+ containerHandler := NewContainerHandler(h.containerService, h.imageService)
+ containerHandler.List(c)
+ case endpoint == "/containers" && c.Request.Method == "POST":
+ containerHandler := NewContainerHandler(h.containerService, h.imageService)
+ containerHandler.Create(c)
+ case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/start"):
+ containerHandler := NewContainerHandler(h.containerService, h.imageService)
+ containerHandler.Start(c)
+ case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/stop"):
+ containerHandler := NewContainerHandler(h.containerService, h.imageService)
+ containerHandler.Stop(c)
+ case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/restart"):
+ containerHandler := NewContainerHandler(h.containerService, h.imageService)
+ containerHandler.Restart(c)
+ case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/pull"):
+ containerHandler := NewContainerHandler(h.containerService, h.imageService)
+ containerHandler.PullImage(c)
+ case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/logs"):
+ containerHandler := NewContainerHandler(h.containerService, h.imageService)
+ containerHandler.GetLogs(c)
+ case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/stats/stream"):
+ containerHandler := NewContainerHandler(h.containerService, h.imageService)
+ containerHandler.GetStatsStream(c)
+ case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/stats"):
+ containerHandler := NewContainerHandler(h.containerService, h.imageService)
+ containerHandler.GetStats(c)
+ case strings.HasPrefix(endpoint, "/containers/") && c.Request.Method == "GET":
+ containerHandler := NewContainerHandler(h.containerService, h.imageService)
+ containerHandler.GetByID(c)
+ case strings.HasPrefix(endpoint, "/containers/") && c.Request.Method == "DELETE":
+ containerHandler := NewContainerHandler(h.containerService, h.imageService)
+ containerHandler.Delete(c)
+
+ case endpoint == "/images" && c.Request.Method == "GET":
+ imageHandler := NewImageHandler(h.imageService, nil)
+ imageHandler.List(c)
+ case endpoint == "/images/pull" && c.Request.Method == "POST":
+ imageHandler := NewImageHandler(h.imageService, nil)
+ imageHandler.Pull(c)
+ case endpoint == "/images/prune" && c.Request.Method == "POST":
+ imageHandler := NewImageHandler(h.imageService, nil)
+ imageHandler.Prune(c)
+ case strings.HasPrefix(endpoint, "/images/") && c.Request.Method == "GET":
+ imageHandler := NewImageHandler(h.imageService, nil)
+ imageHandler.GetByID(c)
+ case strings.HasPrefix(endpoint, "/images/") && c.Request.Method == "DELETE":
+ imageHandler := NewImageHandler(h.imageService, nil)
+ imageHandler.Remove(c)
+
+ case endpoint == "/networks" && c.Request.Method == "GET":
+ networkHandler := NewNetworkHandler(h.networkService)
+ networkHandler.List(c)
+ case endpoint == "/networks" && c.Request.Method == "POST":
+ networkHandler := NewNetworkHandler(h.networkService)
+ networkHandler.Create(c)
+ case strings.HasPrefix(endpoint, "/networks/") && c.Request.Method == "GET":
+ networkHandler := NewNetworkHandler(h.networkService)
+ networkHandler.GetByID(c)
+ case strings.HasPrefix(endpoint, "/networks/") && c.Request.Method == "DELETE":
+ networkHandler := NewNetworkHandler(h.networkService)
+ networkHandler.Remove(c)
+
+ case endpoint == "/volumes" && c.Request.Method == "GET":
+ volumeHandler := NewVolumeHandler(h.volumeService)
+ volumeHandler.List(c)
+ case endpoint == "/volumes" && c.Request.Method == "POST":
+ volumeHandler := NewVolumeHandler(h.volumeService)
+ volumeHandler.Create(c)
+ case endpoint == "/volumes/prune" && c.Request.Method == "POST":
+ volumeHandler := NewVolumeHandler(h.volumeService)
+ volumeHandler.Prune(c)
+ case strings.HasPrefix(endpoint, "/volumes/") && c.Request.Method == "GET":
+ volumeHandler := NewVolumeHandler(h.volumeService)
+ volumeHandler.GetByName(c)
+ case strings.HasPrefix(endpoint, "/volumes/") && c.Request.Method == "DELETE":
+ volumeHandler := NewVolumeHandler(h.volumeService)
+ volumeHandler.Remove(c)
+ case strings.HasPrefix(endpoint, "/volumes/") && strings.HasSuffix(endpoint, "/usage"):
+ volumeHandler := NewVolumeHandler(h.volumeService)
+ volumeHandler.GetUsage(c)
+
+ case endpoint == "/stacks" && c.Request.Method == "GET":
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.ListStacks(c)
+ case endpoint == "/stacks" && c.Request.Method == "POST":
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.CreateStack(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && strings.HasSuffix(endpoint, "/deploy"):
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.DeployStack(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && strings.HasSuffix(endpoint, "/start"):
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.StartStack(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && strings.HasSuffix(endpoint, "/stop"):
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.StopStack(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && strings.HasSuffix(endpoint, "/restart"):
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.RestartStack(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && strings.HasSuffix(endpoint, "/services"):
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.GetStackServices(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && strings.HasSuffix(endpoint, "/pull"):
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.PullImages(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && strings.HasSuffix(endpoint, "/redeploy"):
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.RedeployStack(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && strings.HasSuffix(endpoint, "/down"):
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.DownStack(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && strings.HasSuffix(endpoint, "/destroy"):
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.DestroyStack(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && strings.HasSuffix(endpoint, "/logs/stream"):
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.GetStackLogsStream(c)
+ case endpoint == "/stacks/convert" && c.Request.Method == "POST":
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.ConvertDockerRun(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && c.Request.Method == "GET":
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.GetStack(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && c.Request.Method == "PUT":
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.UpdateStack(c)
+ case strings.HasPrefix(endpoint, "/stacks/") && c.Request.Method == "DELETE":
+ stackHandler := NewStackHandler(h.stackService)
+ stackHandler.DeleteStack(c)
+ default:
+ c.JSON(http.StatusNotFound, gin.H{
+ "success": false,
+ "error": "Endpoint not found",
+ })
+ }
+}
+
+func (h *EnvironmentHandler) handleRemoteRequest(c *gin.Context, environmentID string, endpoint string) {
+ environment, err := h.environmentService.GetEnvironmentByID(c.Request.Context(), environmentID)
+ if err != nil {
+ c.JSON(http.StatusNotFound, gin.H{
+ "success": false,
+ "error": "Environment not found",
+ })
+ return
+ }
+
+ if !environment.Enabled {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "error": "Environment is disabled",
+ })
+ return
+ }
+
+ client := &http.Client{Timeout: 30 * time.Second}
+ url := environment.ApiUrl + "/api" + endpoint
+
+ var reqBody io.Reader
+ if c.Request.Body != nil {
+ bodyBytes, err := io.ReadAll(c.Request.Body)
+ if err == nil && len(bodyBytes) > 0 {
+ reqBody = bytes.NewBuffer(bodyBytes)
+ }
+ }
+
+ req, err := http.NewRequest(c.Request.Method, url, reqBody)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to create request",
+ })
+ return
+ }
+
+ skipHeaders := map[string]struct{}{
+ "Host": {},
+ "Content-Length": {},
+ "Connection": {},
+ }
+
+ for key, values := range c.Request.Header {
+ upperKey := http.CanonicalHeaderKey(key)
+ if _, skip := skipHeaders[upperKey]; skip {
+ continue
+ }
+ if strings.HasPrefix(upperKey, "X-Forwarded-") {
+ continue
+ }
+ if upperKey == "Authorization" {
+ if auth := c.GetHeader("Authorization"); auth != "" {
+ req.Header.Set("Authorization", auth)
+ }
+ continue
+ }
+ for _, value := range values {
+ req.Header.Add(key, value)
+ }
+ }
+
+ req.Header.Set("X-Forwarded-For", c.ClientIP())
+ req.Header.Set("X-Forwarded-Host", c.Request.Host)
+ req.Header.Set("X-Forwarded-Proto", c.Request.URL.Scheme)
+
+ for key, values := range c.Request.URL.Query() {
+ for _, value := range values {
+ q := req.URL.Query()
+ q.Add(key, value)
+ req.URL.RawQuery = q.Encode()
+ }
+ }
+
+ resp, err := client.Do(req)
+ if err != nil {
+ h.environmentService.UpdateEnvironmentStatus(c.Request.Context(), environmentID, "offline")
+ c.JSON(http.StatusServiceUnavailable, gin.H{
+ "success": false,
+ "error": fmt.Sprintf("Failed to connect to environment: %v", err),
+ })
+ return
+ }
+ defer resp.Body.Close()
+
+ h.environmentService.UpdateEnvironmentHeartbeat(c.Request.Context(), environmentID)
+
+ responseBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to read response",
+ })
+ return
+ }
+
+ for key, values := range resp.Header {
+ for _, value := range values {
+ c.Header(key, value)
+ }
+ }
+
+ c.Status(resp.StatusCode)
+ c.Writer.Write(responseBody)
+}
+
+func (h *EnvironmentHandler) CreateEnvironment(c *gin.Context) {
+ var req dto.CreateEnvironmentDto
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "error": "Invalid request format: " + err.Error(),
+ })
+ return
+ }
+
+ environment := &models.Environment{
+ Hostname: req.Hostname,
+ ApiUrl: req.ApiUrl,
+ Description: req.Description,
+ Enabled: true,
+ }
+
+ if req.Enabled != nil {
+ environment.Enabled = *req.Enabled
+ }
+
+ createdEnvironment, err := h.environmentService.CreateEnvironment(c.Request.Context(), environment)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to create environment: " + err.Error(),
+ })
+ return
+ }
+
+ c.JSON(http.StatusCreated, gin.H{
+ "success": true,
+ "environment": createdEnvironment,
+ "message": "Environment created successfully",
+ })
+}
+
+func (h *EnvironmentHandler) ListEnvironments(c *gin.Context) {
+ environments, err := h.environmentService.ListEnvironments(c.Request.Context())
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to fetch environments",
+ })
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "environments": environments,
+ "count": len(environments),
+ })
+}
+
+func (h *EnvironmentHandler) GetEnvironment(c *gin.Context) {
+ environmentID := c.Param("id")
+
+ environment, err := h.environmentService.GetEnvironmentByID(c.Request.Context(), environmentID)
+ if err != nil {
+ c.JSON(http.StatusNotFound, gin.H{
+ "success": false,
+ "error": "Environment not found",
+ })
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "environment": environment,
+ })
+}
+
+func (h *EnvironmentHandler) UpdateEnvironment(c *gin.Context) {
+ environmentID := c.Param("id")
+
+ var req dto.UpdateEnvironmentDto
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "error": "Invalid request format: " + err.Error(),
+ })
+ return
+ }
+
+ updates := make(map[string]interface{})
+ if req.Hostname != nil {
+ updates["hostname"] = *req.Hostname
+ }
+ if req.ApiUrl != nil {
+ updates["api_url"] = *req.ApiUrl
+ }
+ if req.Description != nil {
+ updates["description"] = *req.Description
+ }
+ if req.Enabled != nil {
+ updates["enabled"] = *req.Enabled
+ }
+
+ if len(updates) == 0 {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "error": "No fields to update",
+ })
+ return
+ }
+
+ updatedEnvironment, err := h.environmentService.UpdateEnvironment(c.Request.Context(), environmentID, updates)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to update environment: " + err.Error(),
+ })
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "environment": updatedEnvironment,
+ "message": "Environment updated successfully",
+ })
+}
+
+func (h *EnvironmentHandler) DeleteEnvironment(c *gin.Context) {
+ environmentID := c.Param("id")
+
+ err := h.environmentService.DeleteEnvironment(c.Request.Context(), environmentID)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to delete environment: " + err.Error(),
+ })
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "Environment deleted successfully",
+ })
+}
+
+func (h *EnvironmentHandler) TestConnection(c *gin.Context) {
+ environmentID := c.Param("id")
+
+ status, err := h.environmentService.TestConnection(c.Request.Context(), environmentID)
+
+ response := dto.TestConnectionDto{
+ Status: status,
+ }
+
+ if err != nil {
+ response.Message = func() *string { s := err.Error(); return &s }()
+ }
+
+ httpStatus := http.StatusOK
+ if status == "error" {
+ httpStatus = http.StatusServiceUnavailable
+ }
+
+ c.JSON(httpStatus, response)
+}
+
+func (h *EnvironmentHandler) UpdateHeartbeat(c *gin.Context) {
+ environmentID := c.Param("id")
+
+ err := h.environmentService.UpdateEnvironmentHeartbeat(c.Request.Context(), environmentID)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to update heartbeat",
+ })
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "Heartbeat updated successfully",
+ })
+}
+
+func (h *EnvironmentHandler) GetContainers(c *gin.Context) {
+ h.routeRequest(c, "/containers")
+}
+
+func (h *EnvironmentHandler) GetImages(c *gin.Context) {
+ h.routeRequest(c, "/images")
+}
+
+func (h *EnvironmentHandler) GetNetworks(c *gin.Context) {
+ h.routeRequest(c, "/networks")
+}
+
+func (h *EnvironmentHandler) GetVolumes(c *gin.Context) {
+ h.routeRequest(c, "/volumes")
+}
+
+func (h *EnvironmentHandler) GetStacks(c *gin.Context) {
+ h.routeRequest(c, "/stacks")
+}
+
+func (h *EnvironmentHandler) CreateNetwork(c *gin.Context) {
+ h.routeRequest(c, "/networks")
+}
+
+func (h *EnvironmentHandler) CreateVolume(c *gin.Context) {
+ h.routeRequest(c, "/volumes")
+}
+
+func (h *EnvironmentHandler) CreateStack(c *gin.Context) {
+ h.routeRequest(c, "/stacks")
+}
+
+//Containers
+
+func (h *EnvironmentHandler) GetContainer(c *gin.Context) {
+ containerID := c.Param("containerId")
+ h.routeRequest(c, "/containers/"+containerID)
+}
+
+func (h *EnvironmentHandler) StartContainer(c *gin.Context) {
+ containerID := c.Param("containerId")
+ h.routeRequest(c, "/containers/"+containerID+"/start")
+}
+
+func (h *EnvironmentHandler) StopContainer(c *gin.Context) {
+ containerID := c.Param("containerId")
+ h.routeRequest(c, "/containers/"+containerID+"/stop")
+}
+
+func (h *EnvironmentHandler) CreateContainer(c *gin.Context) {
+ h.routeRequest(c, "/containers")
+}
+
+func (h *EnvironmentHandler) PullContainerImage(c *gin.Context) {
+ containerID := c.Param("containerId")
+ h.routeRequest(c, "/containers/"+containerID+"/pull")
+}
+
+func (h *EnvironmentHandler) RestartContainer(c *gin.Context) {
+ containerID := c.Param("containerId")
+ h.routeRequest(c, "/containers/"+containerID+"/restart")
+}
+
+func (h *EnvironmentHandler) RemoveContainer(c *gin.Context) {
+ containerID := c.Param("containerId")
+ h.routeRequest(c, "/containers/"+containerID)
+}
+
+func (h *EnvironmentHandler) GetContainerLogs(c *gin.Context) {
+ containerID := c.Param("containerId")
+ h.routeRequest(c, "/containers/"+containerID+"/logs")
+}
+
+func (h *EnvironmentHandler) GetContainerStats(c *gin.Context) {
+ containerID := c.Param("containerId")
+ h.routeRequest(c, "/containers/"+containerID+"/stats")
+}
+
+func (h *EnvironmentHandler) GetContainerStatsStream(c *gin.Context) {
+ containerID := c.Param("containerId")
+ h.routeRequest(c, "/containers/"+containerID+"/stats/stream")
+}
+
+// End Containers
+
+//Images
+
+func (h *EnvironmentHandler) GetImage(c *gin.Context) {
+ imageID := c.Param("imageId")
+ h.routeRequest(c, "/images/"+imageID)
+}
+
+func (h *EnvironmentHandler) RemoveImage(c *gin.Context) {
+ imageID := c.Param("imageId")
+ h.routeRequest(c, "/images/"+imageID)
+}
+
+func (h *EnvironmentHandler) PullImage(c *gin.Context) {
+ h.routeRequest(c, "/images/pull")
+}
+
+func (h *EnvironmentHandler) PruneImages(c *gin.Context) {
+ h.routeRequest(c, "/images/prune")
+}
+
+//End Images
+
+func (h *EnvironmentHandler) GetNetwork(c *gin.Context) {
+ networkID := c.Param("networkId")
+ h.routeRequest(c, "/networks/"+networkID)
+}
+
+func (h *EnvironmentHandler) RemoveNetwork(c *gin.Context) {
+ networkID := c.Param("networkId")
+ h.routeRequest(c, "/networks/"+networkID)
+}
+
+func (h *EnvironmentHandler) GetVolume(c *gin.Context) {
+ volumeName := c.Param("volumeName")
+ h.routeRequest(c, "/volumes/"+volumeName)
+}
+
+func (h *EnvironmentHandler) RemoveVolume(c *gin.Context) {
+ volumeName := c.Param("volumeName")
+ h.routeRequest(c, "/volumes/"+volumeName)
+}
+
+func (h *EnvironmentHandler) PruneVolumes(c *gin.Context) {
+ h.routeRequest(c, "/volumes/prune")
+}
+
+func (h *EnvironmentHandler) GetStack(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId)
+}
+
+func (h *EnvironmentHandler) StartStack(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId+"/start")
+}
+
+func (h *EnvironmentHandler) UpdateStack(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId)
+}
+
+func (h *EnvironmentHandler) DeleteStack(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId)
+}
+
+func (h *EnvironmentHandler) StopStack(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId+"/stop")
+}
+
+func (h *EnvironmentHandler) RestartStack(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId+"/restart")
+}
+
+func (h *EnvironmentHandler) GetStackLogs(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId+"/logs")
+}
+
+func (h *EnvironmentHandler) GetVolumeUsage(c *gin.Context) {
+ h.routeRequest(c, "/volumes/"+c.Param("volumeName")+"/usage")
+}
+
+func (h *EnvironmentHandler) DeployStack(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId+"/deploy")
+}
+
+func (h *EnvironmentHandler) GetStackServices(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId+"/services")
+}
+
+func (h *EnvironmentHandler) PullStackImages(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId+"/pull")
+}
+
+func (h *EnvironmentHandler) RedeployStack(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId+"/redeploy")
+}
+
+func (h *EnvironmentHandler) DownStack(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId+"/down")
+}
+
+func (h *EnvironmentHandler) DestroyStack(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId+"/destroy")
+}
+
+func (h *EnvironmentHandler) GetStackLogsStream(c *gin.Context) {
+ stackId := c.Param("stackId")
+ h.routeRequest(c, "/stacks/"+stackId+"/logs/stream")
+}
+
+func (h *EnvironmentHandler) ConvertDockerRun(c *gin.Context) {
+ h.routeRequest(c, "/stacks/convert")
+}
diff --git a/backend/internal/api/image_handler.go b/backend/internal/api/image_handler.go
index f5091b484..463ab3b9e 100644
--- a/backend/internal/api/image_handler.go
+++ b/backend/internal/api/image_handler.go
@@ -86,7 +86,7 @@ func (h *ImageHandler) List(c *gin.Context) {
}
func (h *ImageHandler) GetByID(c *gin.Context) {
- id := c.Param("id")
+ id := c.Param("imageId")
image, err := h.imageService.GetImageByID(c.Request.Context(), id)
if err != nil {
@@ -104,7 +104,7 @@ func (h *ImageHandler) GetByID(c *gin.Context) {
}
func (h *ImageHandler) Remove(c *gin.Context) {
- id := c.Param("id")
+ id := c.Param("imageId")
force := c.Query("force") == "true"
if err := h.imageService.RemoveImage(c.Request.Context(), id, force); err != nil {
diff --git a/backend/internal/api/network_handler.go b/backend/internal/api/network_handler.go
index 5bff72b7c..63a852a8a 100644
--- a/backend/internal/api/network_handler.go
+++ b/backend/internal/api/network_handler.go
@@ -102,7 +102,7 @@ func (h *NetworkHandler) Create(c *gin.Context) {
}
func (h *NetworkHandler) Remove(c *gin.Context) {
- id := c.Param("id")
+ id := c.Param("networkId")
if err := h.networkService.RemoveNetwork(c.Request.Context(), id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
@@ -119,7 +119,7 @@ func (h *NetworkHandler) Remove(c *gin.Context) {
}
func (h *NetworkHandler) ConnectContainer(c *gin.Context) {
- networkID := c.Param("id")
+ networkID := c.Param("networkId")
var req struct {
ContainerID string `json:"containerId" binding:"required"`
diff --git a/backend/internal/api/routes.go b/backend/internal/api/routes.go
index 36e583ef0..f588bc074 100644
--- a/backend/internal/api/routes.go
+++ b/backend/internal/api/routes.go
@@ -10,9 +10,8 @@ import (
type Services struct {
User *services.UserService
Stack *services.StackService
- Agent *services.AgentService
+ Environment *services.EnvironmentService
Settings *services.SettingsService
- Deployment *services.DeploymentService
Container *services.ContainerService
Image *services.ImageService
Volume *services.VolumeService
@@ -34,9 +33,8 @@ func SetupRoutes(r *gin.Engine, services *Services, appConfig *config.Config) {
setupAuthRoutes(api, services, appConfig)
setupUserRoutes(api, services)
setupStackRoutes(api, services)
- setupAgentRoutes(api, services)
+ setupEnvironmentRoutes(api, services)
setupSettingsRoutes(api, services, appConfig)
- setupDeploymentRoutes(api, services)
setupImageMaturityRoutes(api, services)
setupSystemRoutes(api, services.Docker, services)
setupContainerRoutes(api, services)
@@ -121,24 +119,75 @@ func setupStackRoutes(router *gin.RouterGroup, services *Services) {
stacks.POST("/convert", stackHandler.ConvertDockerRun)
}
-func setupAgentRoutes(api *gin.RouterGroup, services *Services) {
- agents := api.Group("/agents")
-
- agentHandler := NewAgentHandler(services.Agent, services.Deployment)
- agents.GET("", middleware.AuthMiddleware(services.Auth), agentHandler.ListAgents)
- agents.GET("/:agentId", middleware.AuthMiddleware(services.Auth), agentHandler.GetAgent)
- agents.DELETE("/:agentId", middleware.AuthMiddleware(services.Auth), agentHandler.DeleteAgent)
- agents.GET("/:agentId/tasks", middleware.AuthMiddleware(services.Auth), agentHandler.GetAgentTasks)
- agents.POST("/:agentId/tasks", middleware.AuthMiddleware(services.Auth), agentHandler.CreateTask)
- agents.GET("/:agentId/tasks/:taskId", middleware.AuthMiddleware(services.Auth), agentHandler.GetTask)
- agents.POST("/:agentId/tasks/:taskId/result", middleware.AuthMiddleware(services.Auth), agentHandler.SubmitTaskResult)
- agents.GET("/:agentId/deployments", middleware.AuthMiddleware(services.Auth), agentHandler.GetAgentDeployments)
- agents.POST("/:agentId/deploy/stack", middleware.AuthMiddleware(services.Auth), agentHandler.DeployStack)
- agents.POST("/:agentId/deploy/container", middleware.AuthMiddleware(services.Auth), agentHandler.DeployContainer)
- agents.POST("/:agentId/deploy/image", middleware.AuthMiddleware(services.Auth), agentHandler.DeployImage)
- agents.GET("/:agentId/stacks", middleware.AuthMiddleware(services.Auth), agentHandler.GetAgentStacks)
- agents.POST("/:agentId/health-check", middleware.AuthMiddleware(services.Auth), agentHandler.SendHealthCheck)
- agents.POST("/:agentId/stack-list", middleware.AuthMiddleware(services.Auth), agentHandler.GetStackList)
+func setupEnvironmentRoutes(api *gin.RouterGroup, services *Services) {
+ environments := api.Group("/environments")
+ environments.Use(middleware.AuthMiddleware(services.Auth))
+
+ environmentHandler := NewEnvironmentHandler(
+ services.Environment,
+ services.Container,
+ services.Image,
+ services.Network,
+ services.Volume,
+ services.Stack,
+ )
+
+ environments.GET("", environmentHandler.ListEnvironments)
+ environments.POST("", environmentHandler.CreateEnvironment)
+ environments.GET("/:id", environmentHandler.GetEnvironment)
+ environments.PUT("/:id", environmentHandler.UpdateEnvironment)
+ environments.DELETE("/:id", environmentHandler.DeleteEnvironment)
+ environments.POST("/:id/test", environmentHandler.TestConnection)
+ environments.POST("/:id/heartbeat", environmentHandler.UpdateHeartbeat)
+
+ environments.POST("/:id/containers", environmentHandler.CreateContainer)
+ environments.GET("/:id/containers", environmentHandler.GetContainers)
+ environments.GET("/:id/containers/:containerId", environmentHandler.GetContainer)
+ environments.POST("/:id/containers/:containerId/pull", environmentHandler.PullContainerImage)
+ environments.POST("/:id/containers/:containerId/start", environmentHandler.StartContainer)
+ environments.POST("/:id/containers/:containerId/stop", environmentHandler.StopContainer)
+ environments.POST("/:id/containers/:containerId/restart", environmentHandler.RestartContainer)
+ environments.DELETE("/:id/containers/:containerId", environmentHandler.RemoveContainer)
+ environments.GET("/:id/containers/:containerId/logs", environmentHandler.GetContainerLogs)
+ environments.GET("/:id/containers/:containerId/stats", environmentHandler.GetContainerStats)
+ environments.GET("/:id/containers/:containerId/stats/stream", environmentHandler.GetContainerStatsStream)
+
+ environments.GET("/:id/images", environmentHandler.GetImages)
+ environments.GET("/:id/images/:imageId", environmentHandler.GetImage)
+ environments.DELETE("/:id/images/:imageId", environmentHandler.RemoveImage)
+ environments.POST("/:id/images/pull", environmentHandler.PullImage)
+ environments.POST("/:id/images/prune", environmentHandler.PruneImages)
+
+ environments.GET("/:id/networks", environmentHandler.GetNetworks)
+ environments.POST("/:id/networks", environmentHandler.CreateNetwork)
+ environments.GET("/:id/networks/:networkId", environmentHandler.GetNetwork)
+ environments.DELETE("/:id/networks/:networkId", environmentHandler.RemoveNetwork)
+
+ environments.GET("/:id/volumes", environmentHandler.GetVolumes)
+ environments.POST("/:id/volumes", environmentHandler.CreateVolume)
+ environments.GET("/:id/volumes/:volumeName", environmentHandler.GetVolume)
+ environments.DELETE("/:id/volumes/:volumeName", environmentHandler.RemoveVolume)
+ environments.GET("/:id/volumes/:volumeName/usage", environmentHandler.GetVolumeUsage)
+
+ environments.POST("/:id/volumes/prune", environmentHandler.PruneVolumes)
+
+ environments.GET("/:id/stacks", environmentHandler.GetStacks)
+ environments.POST("/:id/stacks", environmentHandler.CreateStack)
+ environments.GET("/:id/stacks/:stackId", environmentHandler.GetStack)
+ environments.PUT("/:id/stacks/:stackId", environmentHandler.UpdateStack)
+ environments.DELETE("/:id/stacks/:stackId", environmentHandler.DeleteStack)
+ environments.POST("/:id/stacks/:stackId/start", environmentHandler.StartStack)
+ environments.POST("/:id/stacks/:stackId/deploy", environmentHandler.DeployStack)
+ environments.POST("/:id/stacks/:stackId/stop", environmentHandler.StopStack)
+ environments.POST("/:id/stacks/:stackId/restart", environmentHandler.RestartStack)
+ environments.GET("/:id/stacks/:stackId/services", environmentHandler.GetStackServices)
+ environments.POST("/:id/stacks/:stackId/pull", environmentHandler.PullStackImages)
+ environments.POST("/:id/stacks/:stackId/redeploy", environmentHandler.RedeployStack)
+ environments.POST("/:id/stacks/:stackId/down", environmentHandler.DownStack)
+ environments.DELETE("/:id/stacks/:stackId/destroy", environmentHandler.DestroyStack)
+ environments.GET("/:id/stacks/:stackId/logs/stream", environmentHandler.GetStackLogsStream)
+ environments.POST("/:id/stacks/convert", environmentHandler.ConvertDockerRun)
+
}
func setupSettingsRoutes(api *gin.RouterGroup, services *Services, appConfig *config.Config) {
@@ -158,20 +207,6 @@ func setupSettingsRoutes(api *gin.RouterGroup, services *Services, appConfig *co
settings.POST("/oidc/callback", oidcHandler.HandleOidcCallback)
}
-func setupDeploymentRoutes(api *gin.RouterGroup, services *Services) {
- deployments := api.Group("/deployments")
- deployments.Use(middleware.AuthMiddleware(services.Auth))
-
- deploymentHandler := NewDeploymentHandler(services.Deployment)
-
- deployments.GET("", deploymentHandler.ListDeployments)
- deployments.GET("/recent", deploymentHandler.GetRecentDeployments)
- deployments.GET("/stats", deploymentHandler.GetDeploymentStats)
- deployments.GET("/:deploymentId", deploymentHandler.GetDeployment)
- deployments.PUT("/:deploymentId/status", deploymentHandler.UpdateDeploymentStatus)
- deployments.DELETE("/:deploymentId", deploymentHandler.DeleteDeployment)
-}
-
func setupImageMaturityRoutes(api *gin.RouterGroup, services *Services) {
imageMaturity := api.Group("/images/maturity")
imageMaturity.Use(middleware.AuthMiddleware(services.Auth))
@@ -217,7 +252,7 @@ func setupContainerRoutes(api *gin.RouterGroup, services *Services) {
containers := api.Group("/containers")
containers.Use(middleware.AuthMiddleware(services.Auth))
- containerHandler := NewContainerHandler(services.Container)
+ containerHandler := NewContainerHandler(services.Container, services.Image)
containers.GET("", containerHandler.List)
containers.POST("", containerHandler.Create)
@@ -254,11 +289,11 @@ func setupVolumeRoutes(api *gin.RouterGroup, services *Services) {
volumeHandler := NewVolumeHandler(services.Volume)
volumes.GET("", volumeHandler.List)
- volumes.GET("/:name", volumeHandler.GetByName)
+ volumes.GET("/:volumeName", volumeHandler.GetByName)
volumes.POST("", volumeHandler.Create)
- volumes.DELETE("/:name", volumeHandler.Remove)
+ volumes.DELETE("/:volumeName", volumeHandler.Remove)
volumes.POST("/prune", volumeHandler.Prune)
- volumes.GET("/:name/usage", volumeHandler.GetUsage)
+ volumes.GET("/:volumeName/usage", volumeHandler.GetUsage)
}
func setupNetworkRoutes(api *gin.RouterGroup, services *Services) {
diff --git a/backend/internal/api/stack_handler.go b/backend/internal/api/stack_handler.go
index 3c7d7b3a6..8de017ee9 100644
--- a/backend/internal/api/stack_handler.go
+++ b/backend/internal/api/stack_handler.go
@@ -110,7 +110,7 @@ func (h *StackHandler) CreateStack(c *gin.Context) {
}
func (h *StackHandler) GetStack(c *gin.Context) {
- stackID := c.Param("id")
+ stackID := c.Param("stackId")
stack, err := h.stackService.GetStackByID(c.Request.Context(), stackID)
if err != nil {
diff --git a/backend/internal/api/volume_handler.go b/backend/internal/api/volume_handler.go
index 2956d3ceb..7e01df73c 100644
--- a/backend/internal/api/volume_handler.go
+++ b/backend/internal/api/volume_handler.go
@@ -42,7 +42,7 @@ func (h *VolumeHandler) List(c *gin.Context) {
}
func (h *VolumeHandler) GetByName(c *gin.Context) {
- name := c.Param("name")
+ name := c.Param("volumeName")
volume, err := h.volumeService.GetVolumeByName(c.Request.Context(), name)
if err != nil {
@@ -96,7 +96,7 @@ func (h *VolumeHandler) Create(c *gin.Context) {
}
func (h *VolumeHandler) Remove(c *gin.Context) {
- name := c.Param("name")
+ name := c.Param("volumeName")
force := c.Query("force") == "true"
if err := h.volumeService.DeleteVolume(c.Request.Context(), name, force); err != nil {
@@ -129,7 +129,7 @@ func (h *VolumeHandler) Prune(c *gin.Context) {
}
func (h *VolumeHandler) GetUsage(c *gin.Context) {
- name := c.Param("name")
+ name := c.Param("volumeName")
inUse, containers, err := h.volumeService.GetVolumeUsage(c.Request.Context(), name)
if err != nil {
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.go
index d0a61a769..859f09266 100644
--- a/backend/internal/bootstrap/services_bootstrap.go
+++ b/backend/internal/bootstrap/services_bootstrap.go
@@ -16,8 +16,7 @@ func initializeServices(db *database.DB, cfg *config.Config) (*api.Services, *se
dockerClientService := services.NewDockerClientService(db)
userService := services.NewUserService(db)
stackService := services.NewStackService(db, settingsService)
- agentService := services.NewAgentService(db)
- deploymentService := services.NewDeploymentService(db)
+ environmentService := services.NewEnvironmentService(db)
containerService := services.NewContainerService(db, dockerClientService)
containerRegistry := services.NewContainerRegistryService(db)
imageService := services.NewImageService(db, dockerClientService, containerRegistry)
@@ -33,9 +32,8 @@ func initializeServices(db *database.DB, cfg *config.Config) (*api.Services, *se
appServices := &api.Services{
User: userService,
Stack: stackService,
- Agent: agentService,
+ Environment: environmentService,
Settings: settingsService,
- Deployment: deploymentService,
Container: containerService,
Image: imageService,
Volume: volumeService,
@@ -50,5 +48,6 @@ func initializeServices(db *database.DB, cfg *config.Config) (*api.Services, *se
System: systemService,
AutoUpdate: autoUpdate,
}
+
return appServices, dockerClientService, nil
}
diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go
index 63681b094..eb5e1148d 100644
--- a/backend/internal/database/database.go
+++ b/backend/internal/database/database.go
@@ -77,10 +77,7 @@ func (db *DB) Migrate() error {
&models.User{},
&models.UserSession{},
&models.Stack{},
- &models.Agent{},
- &models.AgentTask{},
- &models.AgentToken{},
- &models.Deployment{},
+ &models.Environment{},
&models.Container{},
&models.Image{},
&models.Volume{},
@@ -92,10 +89,9 @@ func (db *DB) Migrate() error {
)
if err != nil {
- return fmt.Errorf("failed to run migrations: %w", err)
+ return fmt.Errorf("failed to migrate database: %w", err)
}
- log.Println("Database migration completed successfully")
return nil
}
diff --git a/backend/internal/dto/environment_dto.go b/backend/internal/dto/environment_dto.go
new file mode 100644
index 000000000..569616424
--- /dev/null
+++ b/backend/internal/dto/environment_dto.go
@@ -0,0 +1,20 @@
+package dto
+
+type CreateEnvironmentDto struct {
+ Hostname string `json:"hostname" binding:"required"`
+ ApiUrl string `json:"apiUrl" binding:"required,url"`
+ Description *string `json:"description"`
+ Enabled *bool `json:"enabled"`
+}
+
+type UpdateEnvironmentDto struct {
+ Hostname *string `json:"hostname"`
+ ApiUrl *string `json:"apiUrl"`
+ Description *string `json:"description"`
+ Enabled *bool `json:"enabled"`
+}
+
+type TestConnectionDto struct {
+ Status string `json:"status"`
+ Message *string `json:"message,omitempty"`
+}
diff --git a/backend/internal/models/actions.go b/backend/internal/models/actions.go
index 80d99c81d..350bd7eb3 100644
--- a/backend/internal/models/actions.go
+++ b/backend/internal/models/actions.go
@@ -43,7 +43,6 @@ type LoadingStates struct {
Validating *bool `json:"validating,omitempty"`
}
-// PruneResult represents the result of a Docker prune operation
type PruneResult struct {
ContainersDeleted []string `json:"containersDeleted,omitempty"`
ImagesDeleted []any `json:"imagesDeleted,omitempty"`
diff --git a/backend/internal/models/agent.go b/backend/internal/models/agent.go
deleted file mode 100644
index 4ffce9941..000000000
--- a/backend/internal/models/agent.go
+++ /dev/null
@@ -1,106 +0,0 @@
-package models
-
-import (
- "time"
-)
-
-type AgentMetrics struct {
- ContainerCount *int `json:"containerCount,omitempty" gorm:"column:container_count"`
- ImageCount *int `json:"imageCount,omitempty" gorm:"column:image_count"`
- StackCount *int `json:"stackCount,omitempty" gorm:"column:stack_count"`
- NetworkCount *int `json:"networkCount,omitempty" gorm:"column:network_count"`
- VolumeCount *int `json:"volumeCount,omitempty" gorm:"column:volume_count"`
-}
-
-type DockerInfo struct {
- Version string `json:"version"`
- Containers int `json:"containers"`
- Images int `json:"images"`
-}
-
-type Agent struct {
- ID string `json:"id" gorm:"primaryKey"`
- Name string `json:"name" gorm:"not null"`
- URL string `json:"url" gorm:"not null"`
- Token string `json:"token"`
- IsActive bool `json:"is_active" gorm:"default:true"`
- LastPing *time.Time `json:"last_ping,omitempty"`
- Version string `json:"version,omitempty"`
-
- Stacks []Stack `json:"stacks,omitempty" gorm:"foreignKey:AgentID"`
-
- BaseModel
-}
-
-type AgentStatus string
-
-const (
- AgentStatusOnline AgentStatus = "online"
- AgentStatusOffline AgentStatus = "offline"
- AgentStatusError AgentStatus = "error"
-)
-
-type AgentTaskType string
-
-const (
- TaskDockerCommand AgentTaskType = "docker_command"
- TaskStackDeploy AgentTaskType = "stack_deploy"
- TaskComposeCreateProject AgentTaskType = "compose_create_project"
- TaskComposeUp AgentTaskType = "compose_up"
- TaskImagePull AgentTaskType = "image_pull"
- TaskHealthCheck AgentTaskType = "health_check"
- TaskContainerStart AgentTaskType = "container_start"
- TaskStackList AgentTaskType = "stack_list"
- TaskContainerStop AgentTaskType = "container_stop"
- TaskContainerRestart AgentTaskType = "container_restart"
- TaskContainerRemove AgentTaskType = "container_remove"
- TaskAgentUpgrade AgentTaskType = "agent_upgrade"
-)
-
-type AgentTaskStatus string
-
-const (
- TaskStatusPending AgentTaskStatus = "pending"
- TaskStatusRunning AgentTaskStatus = "running"
- TaskStatusCompleted AgentTaskStatus = "completed"
- TaskStatusFailed AgentTaskStatus = "failed"
-)
-
-type AgentTask struct {
- ID string `json:"id" gorm:"primaryKey;type:text"`
- AgentID string `json:"agentId" gorm:"column:agent_id;not null;index"`
- Type AgentTaskType `json:"type" gorm:"not null"`
- Payload JSON `json:"payload" gorm:"type:text;not null"`
- Status AgentTaskStatus `json:"status" gorm:"default:'pending'"`
- Result JSON `json:"result,omitempty" gorm:"type:text"`
- Error *string `json:"error,omitempty"`
- StartedAt *int64 `json:"startedAt,omitempty" gorm:"column:started_at"`
- CompletedAt *int64 `json:"completedAt,omitempty" gorm:"column:completed_at"`
-
- Agent Agent `json:"agent" gorm:"foreignKey:AgentID;references:ID"`
-
- BaseModel
-}
-
-func (AgentTask) TableName() string {
- return "agent_tasks_table"
-}
-
-type AgentToken struct {
- ID string `json:"id" gorm:"primaryKey;type:text"`
- AgentID string `json:"agentId" gorm:"column:agent_id;not null;index"`
- Token string `json:"token" gorm:"uniqueIndex;not null"`
- Name *string `json:"name,omitempty"`
- Permissions StringSlice `json:"permissions" gorm:"type:text;default:'[]'"`
- LastUsed *int64 `json:"lastUsed,omitempty" gorm:"column:last_used"`
- ExpiresAt *int64 `json:"expiresAt,omitempty" gorm:"column:expires_at"`
- IsActive bool `json:"isActive" gorm:"column:is_active;default:true"`
-
- Agent Agent `json:"agent" gorm:"foreignKey:AgentID;references:ID"`
-
- BaseModel
-}
-
-func (AgentToken) TableName() string {
- return "agent_tokens_table"
-}
diff --git a/backend/internal/models/deployment.go b/backend/internal/models/deployment.go
deleted file mode 100644
index 3191b4412..000000000
--- a/backend/internal/models/deployment.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package models
-
-type DeploymentType string
-
-const (
- DeploymentTypeStack DeploymentType = "stack"
- DeploymentTypeContainer DeploymentType = "container"
- DeploymentTypeImage DeploymentType = "image"
-)
-
-type DeploymentStatus string
-
-const (
- DeploymentStatusPending DeploymentStatus = "pending"
- DeploymentStatusRunning DeploymentStatus = "running"
- DeploymentStatusStopped DeploymentStatus = "stopped"
- DeploymentStatusFailed DeploymentStatus = "failed"
- DeploymentStatusCompleted DeploymentStatus = "completed"
-)
-
-type DeploymentMetadata struct {
- StackName *string `json:"stackName,omitempty"`
- ImageName *string `json:"imageName,omitempty"`
- ContainerName *string `json:"containerName,omitempty"`
- ComposeContent *string `json:"composeContent,omitempty"`
- EnvContent *string `json:"envContent,omitempty"`
- Ports []string `json:"ports,omitempty"`
- Volumes []string `json:"volumes,omitempty"`
-}
-
-type Deployment struct {
- ID string `json:"id" gorm:"primaryKey;type:text"`
- Name string `json:"name" gorm:"not null"`
- Type DeploymentType `json:"type" gorm:"not null"`
- Status DeploymentStatus `json:"status" gorm:"default:'pending'"`
- AgentID string `json:"agentId" gorm:"column:agent_id;not null;index"`
- TaskID *string `json:"taskId,omitempty" gorm:"column:task_id;index"`
- Error *string `json:"error,omitempty"`
- Metadata JSON `json:"metadata,omitempty" gorm:"type:text"`
-
- // Relationships
- Agent Agent `json:"agent" gorm:"foreignKey:AgentID;references:ID"`
- Task *AgentTask `json:"task,omitempty" gorm:"foreignKey:TaskID;references:ID"`
-
- BaseModel
-}
-
-func (Deployment) TableName() string {
- return "deployments_table"
-}
diff --git a/backend/internal/models/environment.go b/backend/internal/models/environment.go
new file mode 100644
index 000000000..069c215df
--- /dev/null
+++ b/backend/internal/models/environment.go
@@ -0,0 +1,29 @@
+package models
+
+import (
+ "time"
+)
+
+type Environment struct {
+ ID string `json:"id" gorm:"primaryKey"`
+ Hostname string `json:"hostname" gorm:"not null"`
+ ApiUrl string `json:"apiUrl" gorm:"column:api_url;not null"`
+ Description *string `json:"description"`
+ Status string `json:"status" gorm:"default:offline"`
+ Enabled bool `json:"enabled" gorm:"default:true"`
+ LastSeen *time.Time `json:"lastSeen" gorm:"column:last_seen"`
+ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`
+ UpdatedAt *time.Time `json:"updatedAt" gorm:"column:updated_at"`
+}
+
+func (Environment) TableName() string {
+ return "environments"
+}
+
+type EnvironmentStatus string
+
+const (
+ EnvironmentStatusOnline EnvironmentStatus = "online"
+ EnvironmentStatusOffline EnvironmentStatus = "offline"
+ EnvironmentStatusError EnvironmentStatus = "error"
+)
diff --git a/backend/internal/models/stack.go b/backend/internal/models/stack.go
index b05c12d78..b3fea6a17 100644
--- a/backend/internal/models/stack.go
+++ b/backend/internal/models/stack.go
@@ -53,9 +53,6 @@ type Stack struct {
IsLegacy bool `json:"is_legacy"`
IsRemote bool `json:"is_remote"`
- AgentID *string `json:"agent_id,omitempty" gorm:"index"`
- Agent *Agent `json:"agent,omitempty" gorm:"foreignKey:AgentID"`
-
BaseModel
}
diff --git a/backend/internal/services/agent_service.go b/backend/internal/services/agent_service.go
deleted file mode 100644
index f0b1f2dd3..000000000
--- a/backend/internal/services/agent_service.go
+++ /dev/null
@@ -1,341 +0,0 @@
-package services
-
-import (
- "context"
- "errors"
- "fmt"
- "strings"
- "time"
-
- "github.com/google/uuid"
- "github.com/ofkm/arcane-backend/internal/database"
- "github.com/ofkm/arcane-backend/internal/models"
- "gorm.io/gorm"
-)
-
-type AgentService struct {
- db *database.DB
-}
-
-func NewAgentService(db *database.DB) *AgentService {
- return &AgentService{db: db}
-}
-
-// Agent management
-func (s *AgentService) RegisterAgent(ctx context.Context, agent *models.Agent) (*models.Agent, error) {
- existing, err := s.GetAgentByID(ctx, agent.ID)
- if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, fmt.Errorf("failed to check existing agent: %w", err)
- }
-
- now := time.Now()
- if existing != nil {
- // Update existing agent - fix field names
- existing.IsActive = true
- existing.LastPing = &now
- updateTime := time.Now()
- existing.UpdatedAt = &updateTime
-
- if err := s.db.WithContext(ctx).Save(existing).Error; err != nil {
- return nil, fmt.Errorf("failed to update agent: %w", err)
- }
- return existing, nil
- } else {
- // Create new agent - fix field names
- agent.IsActive = true
- agent.LastPing = &now
- agent.BaseModel = models.BaseModel{CreatedAt: time.Now()}
-
- if err := s.db.WithContext(ctx).Create(agent).Error; err != nil {
- return nil, fmt.Errorf("failed to create agent: %w", err)
- }
- return agent, nil
- }
-}
-
-func (s *AgentService) GetAgentByID(ctx context.Context, id string) (*models.Agent, error) {
- var agent models.Agent
- if err := s.db.WithContext(ctx).Where("id = ?", id).First(&agent).Error; err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, fmt.Errorf("agent not found")
- }
- return nil, fmt.Errorf("failed to get agent: %w", err)
- }
- return &agent, nil
-}
-
-func (s *AgentService) ListAgents(ctx context.Context) ([]*models.Agent, error) {
- var agents []*models.Agent
- if err := s.db.WithContext(ctx).Order("created_at DESC").Find(&agents).Error; err != nil {
- return nil, fmt.Errorf("failed to list agents: %w", err)
- }
- return agents, nil
-}
-
-func (s *AgentService) UpdateAgentHeartbeat(ctx context.Context, agentID string) error {
- now := time.Now()
- if err := s.db.WithContext(ctx).Model(&models.Agent{}).Where("id = ?", agentID).Updates(map[string]interface{}{
- "last_ping": &now,
- "is_active": true,
- }).Error; err != nil {
- return fmt.Errorf("failed to update agent heartbeat: %w", err)
- }
- return nil
-}
-
-func (s *AgentService) UpdateAgentMetrics(ctx context.Context, agentID string, metrics *models.AgentMetrics, dockerInfo *models.DockerInfo) error {
- now := time.Now()
- updates := map[string]interface{}{
- "last_ping": &now,
- }
-
- if dockerInfo != nil {
- updates["version"] = dockerInfo.Version
- }
-
- if err := s.db.WithContext(ctx).Model(&models.Agent{}).Where("id = ?", agentID).Updates(updates).Error; err != nil {
- return fmt.Errorf("failed to update agent metrics: %w", err)
- }
- return nil
-}
-
-func (s *AgentService) DeleteAgent(ctx context.Context, agentID string) error {
- // Delete all related tasks first
- if err := s.db.WithContext(ctx).Where("agent_id = ?", agentID).Delete(&models.AgentTask{}).Error; err != nil {
- return fmt.Errorf("failed to delete agent tasks: %w", err)
- }
-
- // Delete all related tokens
- if err := s.db.WithContext(ctx).Where("agent_id = ?", agentID).Delete(&models.AgentToken{}).Error; err != nil {
- return fmt.Errorf("failed to delete agent tokens: %w", err)
- }
-
- // Update stacks to remove agent reference (don't delete the stacks)
- if err := s.db.WithContext(ctx).Model(&models.Stack{}).Where("agent_id = ?", agentID).Update("agent_id", nil).Error; err != nil {
- return fmt.Errorf("failed to update stacks: %w", err)
- }
-
- // Delete the agent
- if err := s.db.WithContext(ctx).Delete(&models.Agent{}, "id = ?", agentID).Error; err != nil {
- return fmt.Errorf("failed to delete agent: %w", err)
- }
-
- return nil
-}
-
-// Task management
-func (s *AgentService) CreateTask(ctx context.Context, agentID string, taskType models.AgentTaskType, payload map[string]interface{}) (*models.AgentTask, error) {
- // Verify agent exists and is online
- agent, err := s.GetAgentByID(ctx, agentID)
- if err != nil {
- return nil, fmt.Errorf("agent %s not found: %w", agentID, err)
- }
-
- if !s.IsAgentOnline(agent, 5) { // 5 is a default timeout in minutes, adjust as needed
- return nil, fmt.Errorf("agent %s is not online", agentID)
- }
-
- task := &models.AgentTask{
- ID: uuid.New().String(),
- AgentID: agentID,
- Type: taskType,
- Payload: payload,
- Status: models.TaskStatusPending,
- BaseModel: models.BaseModel{
- CreatedAt: time.Now(),
- },
- }
-
- if err := s.db.WithContext(ctx).Create(task).Error; err != nil {
- return nil, fmt.Errorf("failed to create task: %w", err)
- }
-
- return task, nil
-}
-
-func (s *AgentService) GetTaskByID(ctx context.Context, taskID string) (*models.AgentTask, error) {
- var task models.AgentTask
- if err := s.db.WithContext(ctx).Where("id = ?", taskID).First(&task).Error; err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, fmt.Errorf("task not found")
- }
- return nil, fmt.Errorf("failed to get task: %w", err)
- }
- return &task, nil
-}
-
-func (s *AgentService) ListTasks(ctx context.Context, agentID *string) ([]*models.AgentTask, error) {
- query := s.db.WithContext(ctx).Order("created_at DESC")
-
- if agentID != nil {
- query = query.Where("agent_id = ?", *agentID)
- }
-
- var tasks []*models.AgentTask
- if err := query.Find(&tasks).Error; err != nil {
- return nil, fmt.Errorf("failed to list tasks: %w", err)
- }
- return tasks, nil
-}
-
-func (s *AgentService) GetPendingTasks(ctx context.Context, agentID string) ([]*models.AgentTask, error) {
- var tasks []*models.AgentTask
- if err := s.db.WithContext(ctx).
- Where("agent_id = ? AND status = ?", agentID, models.TaskStatusPending).
- Order("created_at ASC").
- Find(&tasks).Error; err != nil {
- return nil, fmt.Errorf("failed to get pending tasks: %w", err)
- }
- return tasks, nil
-}
-
-func (s *AgentService) UpdateTaskStatus(ctx context.Context, taskID string, status models.AgentTaskStatus, result map[string]interface{}, taskError *string) error {
- updates := map[string]interface{}{
- "status": status,
- "updated_at": time.Now(),
- }
-
- if result != nil {
- updates["result"] = result
- }
-
- if taskError != nil {
- updates["error"] = *taskError
- }
-
- now := time.Now().Unix()
- if status == models.TaskStatusRunning && updates["started_at"] == nil {
- updates["started_at"] = now
- }
-
- if status == models.TaskStatusCompleted || status == models.TaskStatusFailed {
- updates["completed_at"] = now
- }
-
- if err := s.db.WithContext(ctx).Model(&models.AgentTask{}).Where("id = ?", taskID).Updates(updates).Error; err != nil {
- return fmt.Errorf("failed to update task status: %w", err)
- }
-
- return nil
-}
-
-// Convenience methods for specific task types
-func (s *AgentService) SendDockerCommand(ctx context.Context, agentID, command string, args []string) (*models.AgentTask, error) {
- payload := map[string]interface{}{
- "command": command,
- "args": args,
- }
- return s.CreateTask(ctx, agentID, models.TaskDockerCommand, payload)
-}
-
-func (s *AgentService) DeployStackToAgent(ctx context.Context, agentID, stackName, composeContent string, envContent *string) (*models.AgentTask, error) {
- payload := map[string]interface{}{
- "project_name": stackName,
- "compose_content": composeContent,
- }
-
- if envContent != nil {
- // Parse env content into key-value pairs
- envVars := make(map[string]string)
- lines := strings.Split(*envContent, "\n")
- for _, line := range lines {
- line = strings.TrimSpace(line)
- if line != "" && !strings.HasPrefix(line, "#") {
- parts := strings.SplitN(line, "=", 2)
- if len(parts) == 2 {
- envVars[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
- }
- }
- }
- payload["env_vars"] = envVars
- }
-
- return s.CreateTask(ctx, agentID, models.TaskComposeCreateProject, payload)
-}
-
-func (s *AgentService) StartStackOnAgent(ctx context.Context, agentID, stackName string) (*models.AgentTask, error) {
- payload := map[string]interface{}{
- "project_name": stackName,
- }
- return s.CreateTask(ctx, agentID, models.TaskComposeUp, payload)
-}
-
-func (s *AgentService) PullImageOnAgent(ctx context.Context, agentID, imageName string) (*models.AgentTask, error) {
- payload := map[string]interface{}{
- "imageName": imageName,
- }
- return s.CreateTask(ctx, agentID, models.TaskImagePull, payload)
-}
-
-func (s *AgentService) SendHealthCheck(ctx context.Context, agentID string) (*models.AgentTask, error) {
- return s.CreateTask(ctx, agentID, models.TaskHealthCheck, map[string]interface{}{})
-}
-
-func (s *AgentService) GetStackList(ctx context.Context, agentID string) (*models.AgentTask, error) {
- return s.CreateTask(ctx, agentID, models.TaskStackList, map[string]interface{}{})
-}
-
-// Token management
-func (s *AgentService) CreateAgentToken(ctx context.Context, agentID, token, name string, permissions []string) (*models.AgentToken, error) {
- agentToken := &models.AgentToken{
- ID: uuid.New().String(),
- AgentID: agentID,
- Token: token,
- Name: &name,
- Permissions: permissions,
- IsActive: true,
- BaseModel: models.BaseModel{CreatedAt: time.Now()},
- }
-
- if err := s.db.WithContext(ctx).Create(agentToken).Error; err != nil {
- return nil, fmt.Errorf("failed to create agent token: %w", err)
- }
-
- return agentToken, nil
-}
-
-func (s *AgentService) GetAgentByToken(ctx context.Context, token string) (*models.Agent, error) {
- var agentToken models.AgentToken
- if err := s.db.WithContext(ctx).Preload("Agent").Where("token = ? AND is_active = ?", token, true).First(&agentToken).Error; err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, fmt.Errorf("invalid token")
- }
- return nil, fmt.Errorf("failed to get agent by token: %w", err)
- }
-
- // Update last used
- now := time.Now().Unix()
- s.db.WithContext(ctx).Model(&agentToken).Update("last_used", now)
-
- return &agentToken.Agent, nil
-}
-
-// Online status checking
-func (s *AgentService) IsAgentOnline(agent *models.Agent, timeoutMinutes int) bool {
- if !agent.IsActive {
- return false
- }
-
- if agent.LastPing == nil {
- return false
- }
-
- timeoutDuration := time.Duration(timeoutMinutes) * time.Minute
- return time.Since(*agent.LastPing) < timeoutDuration
-}
-
-func (s *AgentService) GetOnlineAgents(ctx context.Context, timeoutMinutes int) ([]*models.Agent, error) {
- allAgents, err := s.ListAgents(ctx)
- if err != nil {
- return nil, err
- }
-
- var onlineAgents []*models.Agent
- for _, agent := range allAgents {
- if s.IsAgentOnline(agent, timeoutMinutes) {
- onlineAgents = append(onlineAgents, agent)
- }
- }
-
- return onlineAgents, nil
-}
diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.go
index 8cd6432cd..070cd2dd1 100644
--- a/backend/internal/services/auth_service.go
+++ b/backend/internal/services/auth_service.go
@@ -94,8 +94,6 @@ func NewAuthService(userService *UserService, settingsService *SettingsService,
}
}
-// SyncOidcEnvToDatabase updates the OIDC settings in the database from environment variables
-// if PUBLIC_OIDC_ENABLED is true.
func (s *AuthService) SyncOidcEnvToDatabase(ctx context.Context) error {
if !s.config.PublicOidcEnabled {
return errors.New("OIDC sync called but PUBLIC_OIDC_ENABLED is false")
@@ -106,10 +104,8 @@ func (s *AuthService) SyncOidcEnvToDatabase(ctx context.Context) error {
return fmt.Errorf("failed to get settings for OIDC sync: %w", err)
}
- // settings.Auth is already a models.JSON (map[string]interface{})
var currentAuthMap map[string]interface{}
- if settings.Auth != nil && len(settings.Auth) > 0 {
- // settings.Auth is already a map[string]interface{}, no need to marshal/unmarshal
+ if len(settings.Auth) > 0 {
currentAuthMap = make(map[string]interface{})
for k, v := range settings.Auth {
currentAuthMap[k] = v
@@ -118,7 +114,6 @@ func (s *AuthService) SyncOidcEnvToDatabase(ctx context.Context) error {
currentAuthMap = make(map[string]interface{})
}
- // Prepare OIDC config from environment variables
envOidcConfig := models.OidcConfig{
ClientID: s.config.OidcClientID,
ClientSecret: s.config.OidcClientSecret,
@@ -129,7 +124,6 @@ func (s *AuthService) SyncOidcEnvToDatabase(ctx context.Context) error {
Scopes: s.config.OidcScopes,
}
- // Convert struct to map for consistency
oidcConfigBytes, err := json.Marshal(envOidcConfig)
if err != nil {
return fmt.Errorf("failed to marshal OIDC config from env: %w", err)
@@ -158,8 +152,6 @@ func (s *AuthService) SyncOidcEnvToDatabase(ctx context.Context) error {
return nil
}
-// getAuthSettings retrieves and parses auth settings from the settings service.
-// The database is now the single source of truth for OIDC config values after initial sync.
func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error) {
dbSettings, err := s.settingsService.GetSettings(ctx)
if err != nil {
@@ -167,8 +159,7 @@ func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error
}
var effectiveAuthSettings AuthSettings
- if dbSettings.Auth != nil && len(dbSettings.Auth) > 0 {
- // dbSettings.Auth is already a map[string]interface{}, just marshal and unmarshal to struct
+ if len(dbSettings.Auth) > 0 {
authBytes, err := json.Marshal(dbSettings.Auth)
if err != nil {
log.Printf("Error marshalling auth settings from DB: %v. DB Auth: %v", err, dbSettings.Auth)
@@ -180,11 +171,10 @@ func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error
}
} else {
log.Println("Auth settings not found or empty in DB, returning default auth settings.")
- // Provide comprehensive defaults if Auth settings are missing
return &AuthSettings{
LocalAuthEnabled: true,
OidcEnabled: false,
- SessionTimeout: 60, // Default session timeout
+ SessionTimeout: 60,
Oidc: nil,
}, nil
}
@@ -196,7 +186,6 @@ func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error
return &effectiveAuthSettings, nil
}
-// GetOidcConfigurationStatus returns detailed status about OIDC configuration sources.
func (s *AuthService) GetOidcConfigurationStatus(ctx context.Context) (*OidcStatusInfo, error) {
status := &OidcStatusInfo{}
diff --git a/backend/internal/services/auto_update_service.go b/backend/internal/services/auto_update_service.go
index ad1a851c1..e2d8af724 100644
--- a/backend/internal/services/auto_update_service.go
+++ b/backend/internal/services/auto_update_service.go
@@ -13,7 +13,6 @@ import (
"sync"
"time"
- "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
@@ -199,8 +198,7 @@ func (s *AutoUpdateService) CheckAndUpdateContainers(ctx context.Context) (*Upda
return result, nil
}
-// recreateStandaloneContainer recreates a standalone container preserving its configuration
-func (s *AutoUpdateService) recreateStandaloneContainer(ctx context.Context, container types.Container) error {
+func (s *AutoUpdateService) recreateStandaloneContainer(ctx context.Context, container container.Summary) error {
containerName := s.getContainerName(container)
dockerClient, err := s.dockerService.CreateConnection(ctx)
@@ -513,7 +511,7 @@ func (s *AutoUpdateService) consumeDockerResponse(reader io.ReadCloser) error {
}
// checkContainerForUpdate checks if a container has an image update available
-func (s *AutoUpdateService) checkContainerForUpdate(ctx context.Context, container types.Container, settings *models.Settings) (bool, error) {
+func (s *AutoUpdateService) checkContainerForUpdate(ctx context.Context, container container.Summary, settings *models.Settings) (bool, error) {
containerName := s.getContainerName(container)
dockerClient, err := s.dockerService.CreateConnection(ctx)
@@ -830,7 +828,7 @@ func (s *AutoUpdateService) getImageID(ctx context.Context, imageRef string) (st
}
// getContainerName gets a friendly name for a container
-func (s *AutoUpdateService) getContainerName(container types.Container) string {
+func (s *AutoUpdateService) getContainerName(container container.Summary) string {
if len(container.Names) > 0 {
name := container.Names[0]
if strings.HasPrefix(name, "/") {
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index f99fb872f..ab4e852c2 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -9,8 +9,8 @@ import (
"strings"
"time"
- "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/pkg/stdcopy"
"github.com/ofkm/arcane-backend/internal/database"
@@ -26,7 +26,34 @@ func NewContainerService(db *database.DB, dockerService *DockerClientService) *C
return &ContainerService{db: db, dockerService: dockerService}
}
-func (s *ContainerService) ListContainers(ctx context.Context, includeAll bool) ([]types.Container, error) {
+func (s *ContainerService) PullContainerImage(ctx context.Context, containerID string) error {
+ dockerClient, err := s.dockerService.CreateConnection(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+ defer dockerClient.Close()
+
+ container, err := s.GetContainerByID(ctx, containerID)
+ if err != nil {
+ return fmt.Errorf("failed to get container: %w", err)
+ }
+
+ imageName := container.Image
+ if imageName == "" {
+ return fmt.Errorf("container has no image to pull")
+ }
+
+ reader, err := dockerClient.ImagePull(ctx, imageName, image.PullOptions{})
+ if err != nil {
+ return fmt.Errorf("failed to pull image %s: %w", imageName, err)
+ }
+ defer reader.Close()
+
+ _, err = io.Copy(io.Discard, reader)
+ return err
+}
+
+func (s *ContainerService) ListContainers(ctx context.Context, includeAll bool) ([]container.Summary, error) {
dockerClient, err := s.dockerService.CreateConnection(ctx)
if err != nil {
return nil, fmt.Errorf("failed to connect to Docker: %w", err)
@@ -99,7 +126,7 @@ func (s *ContainerService) GetContainerLogs(ctx context.Context, containerID str
return string(logBytes), nil
}
-func (s *ContainerService) GetContainerByID(ctx context.Context, id string) (*types.ContainerJSON, error) {
+func (s *ContainerService) GetContainerByID(ctx context.Context, id string) (*container.InspectResponse, error) {
dockerClient, err := s.dockerService.CreateConnection(ctx)
if err != nil {
return nil, fmt.Errorf("failed to connect to Docker: %w", err)
@@ -164,13 +191,27 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID stri
return nil
}
-func (s *ContainerService) CreateContainer(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string) (*types.ContainerJSON, error) {
+func (s *ContainerService) CreateContainer(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string) (*container.InspectResponse, error) {
dockerClient, err := s.dockerService.CreateConnection(ctx)
if err != nil {
return nil, fmt.Errorf("failed to connect to Docker: %w", err)
}
defer dockerClient.Close()
+ _, err = dockerClient.ImageInspect(ctx, config.Image)
+ if err != nil {
+ reader, pullErr := dockerClient.ImagePull(ctx, config.Image, image.PullOptions{})
+ if pullErr != nil {
+ return nil, fmt.Errorf("failed to pull image %s: %w", config.Image, pullErr)
+ }
+ defer reader.Close()
+
+ _, copyErr := io.Copy(io.Discard, reader)
+ if copyErr != nil {
+ return nil, fmt.Errorf("failed to complete image pull: %w", copyErr)
+ }
+ }
+
resp, err := dockerClient.ContainerCreate(ctx, config, hostConfig, networkingConfig, nil, containerName)
if err != nil {
return nil, fmt.Errorf("failed to create container: %w", err)
diff --git a/backend/internal/services/deployment_service.go b/backend/internal/services/deployment_service.go
deleted file mode 100644
index a0e5d50d7..000000000
--- a/backend/internal/services/deployment_service.go
+++ /dev/null
@@ -1,141 +0,0 @@
-package services
-
-import (
- "context"
- "errors"
- "fmt"
- "time"
-
- "github.com/google/uuid"
- "github.com/ofkm/arcane-backend/internal/database"
- "github.com/ofkm/arcane-backend/internal/models"
- "gorm.io/gorm"
-)
-
-type DeploymentService struct {
- db *database.DB
-}
-
-func NewDeploymentService(db *database.DB) *DeploymentService {
- return &DeploymentService{db: db}
-}
-
-func (s *DeploymentService) CreateDeployment(ctx context.Context, deployment *models.Deployment) (*models.Deployment, error) {
- deployment.ID = uuid.New().String()
- deployment.BaseModel = models.BaseModel{CreatedAt: time.Now()}
-
- if err := s.db.WithContext(ctx).Create(deployment).Error; err != nil {
- return nil, fmt.Errorf("failed to create deployment: %w", err)
- }
-
- return deployment, nil
-}
-
-func (s *DeploymentService) GetDeploymentByID(ctx context.Context, id string) (*models.Deployment, error) {
- var deployment models.Deployment
- if err := s.db.WithContext(ctx).Preload("Agent").Preload("Task").Where("id = ?", id).First(&deployment).Error; err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, fmt.Errorf("deployment not found")
- }
- return nil, fmt.Errorf("failed to get deployment: %w", err)
- }
- return &deployment, nil
-}
-
-func (s *DeploymentService) ListDeployments(ctx context.Context, agentID *string) ([]*models.Deployment, error) {
- query := s.db.WithContext(ctx).Preload("Agent").Preload("Task").Order("created_at DESC")
-
- if agentID != nil {
- query = query.Where("agent_id = ?", *agentID)
- }
-
- var deployments []*models.Deployment
- if err := query.Find(&deployments).Error; err != nil {
- return nil, fmt.Errorf("failed to list deployments: %w", err)
- }
- return deployments, nil
-}
-
-func (s *DeploymentService) UpdateDeploymentStatus(ctx context.Context, id string, status models.DeploymentStatus, error *string) error {
- updates := map[string]interface{}{
- "status": status,
- "updated_at": time.Now(),
- }
-
- if error != nil {
- updates["error"] = *error
- }
-
- if err := s.db.WithContext(ctx).Model(&models.Deployment{}).Where("id = ?", id).Updates(updates).Error; err != nil {
- return fmt.Errorf("failed to update deployment status: %w", err)
- }
-
- return nil
-}
-
-func (s *DeploymentService) DeleteDeployment(ctx context.Context, id string) error {
- if err := s.db.WithContext(ctx).Delete(&models.Deployment{}, "id = ?", id).Error; err != nil {
- return fmt.Errorf("failed to delete deployment: %w", err)
- }
- return nil
-}
-
-// Helper methods for creating specific deployment types
-func (s *DeploymentService) CreateStackDeployment(ctx context.Context, agentID, stackName, composeContent string, envContent *string, taskID *string) (*models.Deployment, error) {
- metadata := models.JSON{
- "stackName": stackName,
- "composeContent": composeContent,
- }
-
- if envContent != nil {
- metadata["envContent"] = *envContent
- }
-
- deployment := &models.Deployment{
- Name: stackName,
- Type: models.DeploymentTypeStack,
- Status: models.DeploymentStatusPending,
- AgentID: agentID,
- TaskID: taskID,
- Metadata: metadata,
- }
-
- return s.CreateDeployment(ctx, deployment)
-}
-
-func (s *DeploymentService) CreateContainerDeployment(ctx context.Context, agentID, containerName, imageName string, ports, volumes []string, taskID *string) (*models.Deployment, error) {
- metadata := models.JSON{
- "containerName": containerName,
- "imageName": imageName,
- "ports": ports,
- "volumes": volumes,
- }
-
- deployment := &models.Deployment{
- Name: containerName,
- Type: models.DeploymentTypeContainer,
- Status: models.DeploymentStatusPending,
- AgentID: agentID,
- TaskID: taskID,
- Metadata: metadata,
- }
-
- return s.CreateDeployment(ctx, deployment)
-}
-
-func (s *DeploymentService) CreateImageDeployment(ctx context.Context, agentID, imageName string, taskID *string) (*models.Deployment, error) {
- metadata := models.JSON{
- "imageName": imageName,
- }
-
- deployment := &models.Deployment{
- Name: imageName,
- Type: models.DeploymentTypeImage,
- Status: models.DeploymentStatusPending,
- AgentID: agentID,
- TaskID: taskID,
- Metadata: metadata,
- }
-
- return s.CreateDeployment(ctx, deployment)
-}
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
new file mode 100644
index 000000000..c143a4784
--- /dev/null
+++ b/backend/internal/services/environment_service.go
@@ -0,0 +1,168 @@
+package services
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/ofkm/arcane-backend/internal/database"
+ "github.com/ofkm/arcane-backend/internal/models"
+ "gorm.io/gorm"
+)
+
+type EnvironmentService struct {
+ db *database.DB
+}
+
+func NewEnvironmentService(db *database.DB) *EnvironmentService {
+ return &EnvironmentService{db: db}
+}
+
+func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environment *models.Environment) (*models.Environment, error) {
+ environment.ID = uuid.New().String()
+ environment.Status = string(models.EnvironmentStatusOffline)
+ now := time.Now()
+ environment.CreatedAt = now
+ environment.UpdatedAt = &now
+
+ if err := s.db.WithContext(ctx).Create(environment).Error; err != nil {
+ return nil, fmt.Errorf("failed to create environment: %w", err)
+ }
+
+ return environment, nil
+}
+
+func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string) (*models.Environment, error) {
+ var environment models.Environment
+ if err := s.db.WithContext(ctx).Where("id = ?", id).First(&environment).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, fmt.Errorf("environment not found")
+ }
+ return nil, fmt.Errorf("failed to get environment: %w", err)
+ }
+ return &environment, nil
+}
+
+func (s *EnvironmentService) ListEnvironments(ctx context.Context) ([]*models.Environment, error) {
+ var environments []*models.Environment
+ if err := s.db.WithContext(ctx).Order("created_at DESC").Find(&environments).Error; err != nil {
+ return nil, fmt.Errorf("failed to list environments: %w", err)
+ }
+ return environments, nil
+}
+
+func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, updates map[string]interface{}) (*models.Environment, error) {
+ now := time.Now()
+ updates["updated_at"] = &now
+
+ if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {
+ return nil, fmt.Errorf("failed to update environment: %w", err)
+ }
+
+ return s.GetEnvironmentByID(ctx, id)
+}
+
+func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, id string) error {
+ if err := s.db.WithContext(ctx).Delete(&models.Environment{}, "id = ?", id).Error; err != nil {
+ return fmt.Errorf("failed to delete environment: %w", err)
+ }
+ return nil
+}
+
+func (s *EnvironmentService) TestConnection(ctx context.Context, id string) (string, error) {
+ environment, err := s.GetEnvironmentByID(ctx, id)
+ if err != nil {
+ return "error", err
+ }
+
+ client := &http.Client{Timeout: 10 * time.Second}
+ resp, err := client.Get(environment.ApiUrl + "/health")
+ if err != nil {
+ s.updateEnvironmentStatus(ctx, id, string(models.EnvironmentStatusOffline))
+ return "offline", fmt.Errorf("connection failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode == http.StatusOK {
+ s.updateEnvironmentStatus(ctx, id, string(models.EnvironmentStatusOnline))
+ return "online", nil
+ }
+
+ s.updateEnvironmentStatus(ctx, id, string(models.EnvironmentStatusError))
+ return "error", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+}
+
+func (s *EnvironmentService) updateEnvironmentStatus(ctx context.Context, id, status string) error {
+ now := time.Now()
+ updates := map[string]interface{}{
+ "status": status,
+ "last_seen": &now,
+ "updated_at": &now,
+ }
+ if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {
+ return fmt.Errorf("failed to update environment status: %w", err)
+ }
+ return nil
+}
+
+func (s *EnvironmentService) UpdateEnvironmentStatus(ctx context.Context, id, status string) error {
+ now := time.Now()
+ updates := map[string]interface{}{
+ "status": status,
+ "updated_at": &now,
+ }
+
+ if status == string(models.EnvironmentStatusOnline) {
+ updates["last_seen"] = &now
+ }
+
+ return s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(updates).Error
+}
+
+func (s *EnvironmentService) UpdateEnvironmentHeartbeat(ctx context.Context, id string) error {
+ now := time.Now()
+ if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(map[string]interface{}{
+ "last_seen": &now,
+ "status": string(models.EnvironmentStatusOnline),
+ "updated_at": &now,
+ }).Error; err != nil {
+ return fmt.Errorf("failed to update environment heartbeat: %w", err)
+ }
+ return nil
+}
+
+func (s *EnvironmentService) GetOnlineEnvironments(ctx context.Context, timeoutMinutes int) ([]*models.Environment, error) {
+ allEnvironments, err := s.ListEnvironments(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ var onlineEnvironments []*models.Environment
+ for _, env := range allEnvironments {
+ if s.IsEnvironmentOnline(env, timeoutMinutes) {
+ onlineEnvironments = append(onlineEnvironments, env)
+ }
+ }
+
+ return onlineEnvironments, nil
+}
+
+func (s *EnvironmentService) IsEnvironmentOnline(environment *models.Environment, timeoutMinutes int) bool {
+ if !environment.Enabled {
+ return false
+ }
+
+ if environment.Status != string(models.EnvironmentStatusOnline) {
+ return false
+ }
+
+ if environment.LastSeen == nil {
+ return false
+ }
+
+ timeoutDuration := time.Duration(timeoutMinutes) * time.Minute
+ return time.Since(*environment.LastSeen) < timeoutDuration
+}
diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.go
index ffb7c2e3d..1cdb44184 100644
--- a/backend/internal/services/image_service.go
+++ b/backend/internal/services/image_service.go
@@ -317,7 +317,6 @@ func (s *ImageService) syncImagesToDatabase(ctx context.Context, dockerImages []
RepoTags: models.StringSlice(di.RepoTags),
RepoDigests: models.StringSlice(di.RepoDigests),
Size: di.Size,
- VirtualSize: di.VirtualSize,
Created: time.Unix(di.Created, 0),
InUse: isInUse,
}
@@ -476,7 +475,6 @@ func (s *ImageService) GetImagesWithMaturity(ctx context.Context) ([]map[string]
"RepoDigests": img.RepoDigests,
"Created": img.Created,
"Size": img.Size,
- "VirtualSize": img.VirtualSize,
"SharedSize": img.SharedSize,
"Labels": img.Labels,
"Containers": img.Containers,
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 9a825305e..274da86a6 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -12,25 +12,21 @@
"@codemirror/legacy-modes": "^6.5.1",
"@lucide/svelte": "^0.513.0",
"@sveltejs/adapter-static": "^3.0.8",
- "@swimlane/docker-reference": "^2.0.1",
"@tanstack/table-core": "^8.21.3",
"axios": "^1.9.0",
"codemirror": "^6.0.1",
"date-fns": "^4.1.0",
"js-yaml": "^4.1.0",
- "nanoid": "^5.1.5",
"prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.4.0",
"prettier-plugin-tailwindcss": "^0.6.12",
"runed": "^0.28.0",
- "slugify": "^1.6.6",
"svelte-codemirror-editor": "^1.4.1",
"thememirror": "^2.0.1"
},
"devDependencies": {
"@eslint/compat": "^1.2.5",
"@eslint/js": "^9.18.0",
- "@internationalized/date": "^3.8.2",
"@playwright/test": "^1.52.0",
"@sveltejs/kit": "^2.21.3",
"@sveltejs/vite-plugin-svelte": "^5.1.0",
@@ -932,6 +928,7 @@
"integrity": "sha512-/wENk7CbvLbkUvX1tu0mwq49CVkkWpkXubGel6birjRPyo6uQ4nQpnq5xZu823zRCwwn82zgHrvgF1vZyvmVgA==",
"dev": true,
"license": "Apache-2.0",
+ "peer": true,
"dependencies": {
"@swc/helpers": "^0.5.0"
}
@@ -1515,16 +1512,11 @@
"integrity": "sha512-5IKx/Y13RsYd+sauPb2x+U/xZikHjolzfuDgTAl/Tdf3Q8rslRvC19NKDLgAJQ6wsqADk10ntlv08nPFw/gO/A==",
"dev": true,
"license": "Apache-2.0",
+ "peer": true,
"dependencies": {
"tslib": "^2.8.0"
}
},
- "node_modules/@swimlane/docker-reference": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/@swimlane/docker-reference/-/docker-reference-2.0.1.tgz",
- "integrity": "sha512-+mxOe4TwtZJHmvVwq8CnY21wYpYbLXS3IXOWQbgolyfwJhS2vEsNKmNHGdWHd7KUkJTYLs7nmJFVx9OZ2qEVbA==",
- "license": "MIT"
- },
"node_modules/@tailwindcss/node": {
"version": "4.1.8",
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.8.tgz",
@@ -4221,24 +4213,6 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
- "node_modules/nanoid": {
- "version": "5.1.5",
- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.5.tgz",
- "integrity": "sha512-Ir/+ZpE9fDsNH0hQ3C68uyThDXzYcim2EqcZ8zn8Chtt1iylPT9xXJB0kPCnqzgcEGikO9RxSrh63MsmVCU7Fw==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/ai"
- }
- ],
- "license": "MIT",
- "bin": {
- "nanoid": "bin/nanoid.js"
- },
- "engines": {
- "node": "^18 || >=20"
- }
- },
"node_modules/natural-compare": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
@@ -4945,15 +4919,6 @@
"node": ">=18"
}
},
- "node_modules/slugify": {
- "version": "1.6.6",
- "resolved": "https://registry.npmjs.org/slugify/-/slugify-1.6.6.tgz",
- "integrity": "sha512-h+z7HKHYXj6wJU+AnS/+IH8Uh9fdcX1Lrhg1/VMdf9PwoBQXFcXiAdsy2tSK0P6gKwJLXp02r90ahUCqHk9rrw==",
- "license": "MIT",
- "engines": {
- "node": ">=8.0.0"
- }
- },
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
@@ -5482,7 +5447,8 @@
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
- "license": "0BSD"
+ "license": "0BSD",
+ "peer": true
},
"node_modules/tsx": {
"version": "4.19.4",
diff --git a/frontend/package.json b/frontend/package.json
index 9e664ab3e..2e248d587 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -26,25 +26,21 @@
"@codemirror/legacy-modes": "^6.5.1",
"@lucide/svelte": "^0.513.0",
"@sveltejs/adapter-static": "^3.0.8",
- "@swimlane/docker-reference": "^2.0.1",
"@tanstack/table-core": "^8.21.3",
"axios": "^1.9.0",
"codemirror": "^6.0.1",
"date-fns": "^4.1.0",
"js-yaml": "^4.1.0",
- "nanoid": "^5.1.5",
"prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.4.0",
"prettier-plugin-tailwindcss": "^0.6.12",
"runed": "^0.28.0",
- "slugify": "^1.6.6",
"svelte-codemirror-editor": "^1.4.1",
"thememirror": "^2.0.1"
},
"devDependencies": {
"@eslint/compat": "^1.2.5",
"@eslint/js": "^9.18.0",
- "@internationalized/date": "^3.8.2",
"@playwright/test": "^1.52.0",
"@sveltejs/kit": "^2.21.3",
"@sveltejs/vite-plugin-svelte": "^5.1.0",
diff --git a/frontend/src/app.d.ts b/frontend/src/app.d.ts
index 7b12d3230..a8c0ee8d3 100644
--- a/frontend/src/app.d.ts
+++ b/frontend/src/app.d.ts
@@ -1,4 +1,3 @@
-import type { VolumeInspectInfo as OriginalVolumeInspectInfo } from 'dockerode';
import type { User } from '$lib/types/user.type';
declare global {
@@ -9,7 +8,6 @@ declare global {
}
interface Locals {
user?: User | null;
- session: Session<SessionData>;
}
// interface PageData {}
// interface PageState {}
@@ -17,11 +15,4 @@ declare global {
}
}
-declare module 'dockerode' {
- // Re-declare the interface adding the missing property
- interface VolumeInspectInfo extends OriginalVolumeInspectInfo {
- CreatedAt: string;
- }
-}
-
export {};
diff --git a/frontend/src/hooks.client.ts b/frontend/src/hooks.client.ts
index 9dc7aa42b..4adef9acd 100644
--- a/frontend/src/hooks.client.ts
+++ b/frontend/src/hooks.client.ts
@@ -2,9 +2,9 @@ import { sequence } from '@sveltejs/kit/hooks';
import type { Handle } from '@sveltejs/kit';
import { redirect } from '@sveltejs/kit';
import { building, dev } from '$app/environment';
-import SessionAPIService from '$lib/services/api/session-api-service';
-import { settingsAPI, sessionAPI } from '$lib/services/api';
+import { settingsAPI } from '$lib/services/api';
import settingsStore from '$lib/stores/config-store';
+import { authService } from '$lib/services/api/auth-api-service';
const isTestEnvironment = process.env.APP_ENV === 'TEST';
@@ -38,20 +38,9 @@ const authHandler: Handle = async ({ event, resolve }) => {
const { url } = event;
const path = url.pathname;
- const publicPaths = ['/auth/login', '/auth/logout', '/img', '/auth/oidc/login', '/auth/oidc/callback', '/api/agents/register', '/api/agents/heartbeat', '/api/health', '/api/version', '/favicon.ico', '/_app'];
-
- const agentPollingPattern = /^\/api\/agents\/[^\/]+\/tasks$/;
- const agentResultPattern = /^\/api\/agents\/[^\/]+\/tasks\/[^\/]+\/result$/;
- const agentTaskStatusPattern = /^\/api\/agents\/[^\/]+\/tasks\/[^\/]+\/status$/;
+ const publicPaths = ['/auth/login', '/auth/logout', '/img', '/auth/oidc/login', '/auth/oidc/callback', '/api/health', '/api/version', '/favicon.ico', '/_app'];
const isPublicPath = publicPaths.some((p) => path.startsWith(p));
- const isAgentPolling = agentPollingPattern.test(path) && event.request.method === 'GET';
- const isAgentResult = agentResultPattern.test(path) && event.request.method === 'POST';
- const isAgentTaskStatus = agentTaskStatusPattern.test(path) && event.request.method === 'PUT';
-
- if (isPublicPath || isAgentPolling || isAgentResult || isAgentTaskStatus) {
- return await resolve(event);
- }
if (path.startsWith('/api/')) {
return await resolve(event);
@@ -59,7 +48,7 @@ const authHandler: Handle = async ({ event, resolve }) => {
if (dev && !isTestEnvironment) {
try {
- const isValidSession = await sessionAPI.validateSession();
+ const isValidSession = await authService.validateSession();
if (!isValidSession) {
throw redirect(302, `/auth/login?redirect=${encodeURIComponent(path)}`);
diff --git a/frontend/src/lib/components/action-buttons.svelte b/frontend/src/lib/components/action-buttons.svelte
index 57a06255b..2dfbdd057 100644
--- a/frontend/src/lib/components/action-buttons.svelte
+++ b/frontend/src/lib/components/action-buttons.svelte
@@ -3,7 +3,7 @@
import { goto, invalidateAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
import type { LoadingStates } from '$lib/types/loading-states.type';
- import { stackAPI, containerAPI } from '$lib/services/api';
+ import { environmentAPI } from '$lib/services/api';
import { tryCatch } from '$lib/utils/try-catch';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import ArcaneButton from './arcane-button.svelte';
@@ -65,7 +65,7 @@
isLoading.remove = true;
handleApiResultWithCallbacks({
- result: await tryCatch(type === 'container' ? containerAPI.remove(id) : stackAPI.destroy(id, removeVolumes, removeFiles)),
+ result: await tryCatch(type === 'container' ? environmentAPI.deleteContainer(id) : environmentAPI.destroyStack(id, removeVolumes, removeFiles)),
message: `Failed to ${type === 'stack' ? 'Destroy' : 'Remove'} ${type}`,
setLoadingState: (value) => (isLoading.remove = value),
onSuccess: async () => {
@@ -94,7 +94,7 @@
action: async () => {
isLoading.redeploy = true;
handleApiResultWithCallbacks({
- result: await tryCatch(stackAPI.redeploy(id)),
+ result: await tryCatch(environmentAPI.redeployStack(id)),
message: `Failed to Redeploy ${type}`,
setLoadingState: (value) => (isLoading.redeploy = value),
onSuccess: async () => {
@@ -111,7 +111,7 @@
async function handleStart() {
isLoading.start = true;
handleApiResultWithCallbacks({
- result: await tryCatch(type === 'container' ? containerAPI.start(id) : stackAPI.deploy(id)),
+ result: await tryCatch(type === 'container' ? environmentAPI.startContainer(id) : environmentAPI.startStack(id)),
message: `Failed to Start ${type}`,
setLoadingState: (value) => (isLoading.start = value),
onSuccess: async () => {
@@ -124,7 +124,7 @@
async function handleDeploy() {
isLoading.start = true;
handleApiResultWithCallbacks({
- result: await tryCatch(stackAPI.deploy(id)),
+ result: await tryCatch(environmentAPI.startStack(id)),
message: `Failed to Start ${type}`,
setLoadingState: (value) => (isLoading.start = value),
onSuccess: async () => {
@@ -137,7 +137,7 @@
async function handleStop() {
isLoading.stop = true;
handleApiResultWithCallbacks({
- result: await tryCatch(type === 'container' ? containerAPI.stop(id) : stackAPI.down(id)),
+ result: await tryCatch(type === 'container' ? environmentAPI.stopContainer(id) : environmentAPI.stopStack(id)),
message: `Failed to Stop ${type}`,
setLoadingState: (value) => (isLoading.stop = value),
onSuccess: async () => {
@@ -150,7 +150,7 @@
async function handleRestart() {
isLoading.restart = true;
handleApiResultWithCallbacks({
- result: await tryCatch(type === 'container' ? containerAPI.restart(id) : stackAPI.restart(id)),
+ result: await tryCatch(type === 'container' ? environmentAPI.restartContainer(id) : environmentAPI.restartStack(id)),
message: `Failed to Restart ${type}`,
setLoadingState: (value) => (isLoading.restart = value),
onSuccess: async () => {
@@ -163,7 +163,7 @@
async function handlePull() {
isLoading.pulling = true;
handleApiResultWithCallbacks({
- result: await tryCatch(type === 'container' ? containerAPI.pull(id) : stackAPI.pull(id)),
+ result: await tryCatch(type === 'container' ? environmentAPI.pullContainerImage(id) : environmentAPI.pullStackImages(id)),
message: 'Failed to Pull Image(s)',
setLoadingState: (value) => (isLoading.pulling = value),
onSuccess: async () => {
diff --git a/frontend/src/lib/components/template-selection-dialog.svelte b/frontend/src/lib/components/dialogs/template-selection-dialog.svelte
similarity index 100%
rename from frontend/src/lib/components/template-selection-dialog.svelte
rename to frontend/src/lib/components/dialogs/template-selection-dialog.svelte
diff --git a/frontend/src/lib/components/env-editor.svelte b/frontend/src/lib/components/env-editor.svelte
index 679506ca2..f48385a63 100644
--- a/frontend/src/lib/components/env-editor.svelte
+++ b/frontend/src/lib/components/env-editor.svelte
@@ -17,8 +17,7 @@
styles={{
'&': {
height: '550px',
- fontSize: '12px',
- fontFamily: 'JetBrains Mono, Menlo, Monaco, Consolas, monospace'
+ fontSize: '11px'
},
'&.cm-editor[contenteditable=false]': {
cursor: 'not-allowed'
diff --git a/frontend/src/lib/components/forms/ImagePullForm.svelte b/frontend/src/lib/components/forms/ImagePullForm.svelte
deleted file mode 100644
index 71107a55a..000000000
--- a/frontend/src/lib/components/forms/ImagePullForm.svelte
+++ /dev/null
@@ -1,88 +0,0 @@
-<script lang="ts">
- import { Button } from '$lib/components/ui/button';
- import { Label } from '$lib/components/ui/label';
- import { Input } from '$lib/components/ui/input';
- import { toast } from 'svelte-sonner';
- import { Loader2 } from '@lucide/svelte';
-
- interface Props {
- agentId: string;
- onClose: () => void;
- onPull: (imageName: string) => Promise<void>;
- }
-
- let { agentId, onClose, onPull }: Props = $props();
-
- let pulling = $state(false);
- let imageRef = $state('');
- let tag = $state('latest');
-
- function buildFullImageName(imageRef: string, tag: string): string {
- const trimmedImageRef = imageRef.trim();
- const trimmedTag = tag.trim();
-
- // If the image already includes a tag (contains ':'), use it as-is
- if (trimmedImageRef.includes(':')) {
- return trimmedImageRef;
- }
-
- // If no tag specified or tag is 'latest', append ':latest'
- if (!trimmedTag || trimmedTag === 'latest') {
- return `${trimmedImageRef}:latest`;
- }
-
- // Otherwise, append the specified tag
- return `${trimmedImageRef}:${trimmedTag}`;
- }
-
- async function handlePull() {
- if (!imageRef.trim()) {
- toast.error('Please enter an image name');
- return;
- }
-
- pulling = true;
- try {
- const fullImageName = buildFullImageName(imageRef, tag);
-
- await onPull(fullImageName);
- onClose();
- toast.success(`Started pulling image: ${fullImageName}`);
- } catch (err) {
- console.error('Pull error:', err);
- toast.error(err instanceof Error ? err.message : 'Failed to pull image');
- } finally {
- pulling = false;
- }
- }
-
- function handleKeyPress(event: KeyboardEvent) {
- if (event.key === 'Enter' && !pulling) {
- handlePull();
- }
- }
-</script>
-
-<div class="space-y-4">
- <div class="space-y-2">
- <Label for="imageRef">Image Name</Label>
- <Input id="imageRef" bind:value={imageRef} placeholder="nginx, redis, ubuntu, etc." disabled={pulling} onkeypress={handleKeyPress} />
- <p class="text-muted-foreground text-xs">Enter the image name (e.g., nginx, redis, ubuntu)</p>
- </div>
-
- <div class="space-y-2">
- <Label for="tag">Tag (Optional)</Label>
- <Input id="tag" bind:value={tag} placeholder="latest" disabled={pulling} onkeypress={handleKeyPress} />
- <p class="text-muted-foreground text-xs">Specify a tag version (defaults to 'latest')</p>
- </div>
-
- <div class="flex justify-end space-x-2">
- <Button variant="outline" onclick={onClose} disabled={pulling}>Cancel</Button>
- <Button onclick={handlePull} disabled={pulling || !imageRef.trim()}>
- {#if pulling}
- <Loader2 class="mr-2 size-4 animate-spin" />
- {/if}
- Pull Image
- </Button>
- </div>
-</div>
diff --git a/frontend/src/lib/components/forms/QuickContainerForm.svelte b/frontend/src/lib/components/forms/QuickContainerForm.svelte
deleted file mode 100644
index 83c6edabb..000000000
--- a/frontend/src/lib/components/forms/QuickContainerForm.svelte
+++ /dev/null
@@ -1,355 +0,0 @@
-<script lang="ts">
- import { Button } from '$lib/components/ui/button';
- import { Label } from '$lib/components/ui/label';
- import { Input } from '$lib/components/ui/input';
- import { Switch } from '$lib/components/ui/switch/index.js';
- import { toast } from 'svelte-sonner';
- import { Loader2, Plus, Trash2 } from '@lucide/svelte';
-
- interface PortMapping {
- host: string;
- container: string;
- }
-
- interface VolumeMount {
- host: string;
- container: string;
- }
-
- interface EnvironmentVariable {
- key: string;
- value: string;
- }
-
- interface ContainerConfiguration {
- imageName: string;
- containerName?: string;
- ports: PortMapping[];
- volumes: VolumeMount[];
- envVars: EnvironmentVariable[];
- detached: boolean;
- autoRemove: boolean;
- restartPolicy: 'no' | 'always' | 'unless-stopped' | 'on-failure';
- }
-
- interface Props {
- agentId: string;
- onClose: () => void;
- onRun: (data: ContainerConfiguration) => Promise<void>;
- }
-
- let { onClose, onRun }: Props = $props();
-
- let running = $state(false);
- let containerName = $state('');
- let imageName = $state('');
- let ports = $state<PortMapping[]>([]);
- let volumes = $state<VolumeMount[]>([]);
- let envVars = $state<EnvironmentVariable[]>([]);
- let detached = $state(true);
- let autoRemove = $state(false);
- let restartPolicy = $state<ContainerConfiguration['restartPolicy']>('no');
-
- function addPort() {
- ports = [...ports, { host: '', container: '' }];
- }
-
- function removePort(index: number) {
- ports = ports.filter((_, i) => i !== index);
- }
-
- function addVolume() {
- volumes = [...volumes, { host: '', container: '' }];
- }
-
- function removeVolume(index: number) {
- volumes = volumes.filter((_, i) => i !== index);
- }
-
- function addEnvVar() {
- envVars = [...envVars, { key: '', value: '' }];
- }
-
- function removeEnvVar(index: number) {
- envVars = envVars.filter((_, i) => i !== index);
- }
-
- async function handleRun() {
- // Basic validation
- if (!imageName.trim()) {
- toast.error('Please enter an image name');
- return;
- }
-
- // Validate container name if provided
- if (containerName.trim()) {
- const containerNameRegex = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
- if (!containerNameRegex.test(containerName.trim())) {
- toast.error('Container name must start with alphanumeric character and can only contain letters, numbers, underscores, periods, and hyphens');
- return;
- }
- }
-
- // Validate ports
- for (let i = 0; i < ports.length; i++) {
- const port = ports[i];
-
- // Skip empty port mappings
- if (!port.host && !port.container) continue;
-
- // Both host and container ports must be provided
- if (!port.host || !port.container) {
- toast.error(`Port mapping ${i + 1}: Both host and container ports must be specified`);
- return;
- }
-
- // Validate host port
- const hostPort = parseInt(port.host);
- if (isNaN(hostPort) || hostPort < 1 || hostPort > 65535) {
- toast.error(`Port mapping ${i + 1}: Host port must be a number between 1 and 65535`);
- return;
- }
-
- // Validate container port
- const containerPort = parseInt(port.container);
- if (isNaN(containerPort) || containerPort < 1 || containerPort > 65535) {
- toast.error(`Port mapping ${i + 1}: Container port must be a number between 1 and 65535`);
- return;
- }
- }
-
- // Check for duplicate host ports
- const hostPorts = ports.filter((p) => p.host && p.container).map((p) => parseInt(p.host));
- const uniqueHostPorts = new Set(hostPorts);
- if (hostPorts.length !== uniqueHostPorts.size) {
- toast.error('Duplicate host ports are not allowed');
- return;
- }
-
- // Validate volumes
- for (let i = 0; i < volumes.length; i++) {
- const volume = volumes[i];
-
- // Skip empty volume mappings
- if (!volume.host && !volume.container) continue;
-
- // Both host and container paths must be provided
- if (!volume.host || !volume.container) {
- toast.error(`Volume mapping ${i + 1}: Both host and container paths must be specified`);
- return;
- }
-
- // Validate host path format
- if (!volume.host.trim()) {
- toast.error(`Volume mapping ${i + 1}: Host path cannot be empty`);
- return;
- }
-
- // Basic path validation (should start with / on Unix systems or contain : on Windows)
- const hostPath = volume.host.trim();
- if (!hostPath.startsWith('/') && !hostPath.match(/^[a-zA-Z]:/)) {
- toast.error(`Volume mapping ${i + 1}: Host path should be an absolute path (e.g., /path/to/dir or C:/path/to/dir)`);
- return;
- }
-
- // Validate container path format
- const containerPath = volume.container.trim();
- if (!containerPath.startsWith('/')) {
- toast.error(`Volume mapping ${i + 1}: Container path must be an absolute path starting with /`);
- return;
- }
-
- // Check for reserved container paths
- const reservedPaths = ['/proc', '/sys', '/dev'];
- if (reservedPaths.some((reserved) => containerPath.startsWith(reserved))) {
- toast.error(`Volume mapping ${i + 1}: Cannot mount to reserved system path ${containerPath}`);
- return;
- }
- }
-
- // Check for duplicate container mount points
- const containerPaths = volumes.filter((v) => v.host && v.container).map((v) => v.container.trim());
- const uniqueContainerPaths = new Set(containerPaths);
- if (containerPaths.length !== uniqueContainerPaths.size) {
- toast.error('Duplicate container mount points are not allowed');
- return;
- }
-
- // Validate environment variables
- for (let i = 0; i < envVars.length; i++) {
- const envVar = envVars[i];
-
- // Skip empty environment variables
- if (!envVar.key && !envVar.value) continue;
-
- // Both key and value must be provided
- if (!envVar.key || !envVar.value) {
- toast.error(`Environment variable ${i + 1}: Both key and value must be specified`);
- return;
- }
-
- // Validate environment variable key format
- const envKeyRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
- if (!envKeyRegex.test(envVar.key.trim())) {
- toast.error(`Environment variable ${i + 1}: Key must start with letter or underscore and contain only letters, numbers, and underscores`);
- return;
- }
-
- // Check for reserved environment variables
- const reservedEnvVars = ['PATH', 'HOME', 'USER', 'SHELL'];
- if (reservedEnvVars.includes(envVar.key.trim().toUpperCase())) {
- toast.error(`Environment variable ${i + 1}: Cannot override reserved variable ${envVar.key}`);
- return;
- }
- }
-
- // Check for duplicate environment variable keys
- const envKeys = envVars.filter((e) => e.key && e.value).map((e) => e.key.trim().toUpperCase());
- const uniqueEnvKeys = new Set(envKeys);
- if (envKeys.length !== uniqueEnvKeys.size) {
- toast.error('Duplicate environment variable keys are not allowed');
- return;
- }
-
- running = true;
- try {
- const data: ContainerConfiguration = {
- imageName: imageName.trim(),
- containerName: containerName.trim() || undefined,
- ports: ports.filter((p) => p.host && p.container),
- volumes: volumes.filter((v) => v.host && v.container),
- envVars: envVars.filter((e) => e.key && e.value),
- detached,
- autoRemove,
- restartPolicy
- };
-
- await onRun(data);
- onClose();
- toast.success(`Started container from ${imageName}`);
- } catch (err) {
- console.error('Run error:', err);
- toast.error(err instanceof Error ? err.message : 'Failed to run container');
- } finally {
- running = false;
- }
- }
-</script>
-
-<div class="space-y-6">
- <!-- Basic Configuration -->
- <div class="space-y-4">
- <div class="space-y-2">
- <Label for="imageName">Image Name *</Label>
- <Input id="imageName" bind:value={imageName} placeholder="nginx:alpine" disabled={running} />
- </div>
-
- <div class="space-y-2">
- <Label for="containerName">Container Name (Optional)</Label>
- <Input id="containerName" bind:value={containerName} placeholder="my-container" disabled={running} />
- </div>
- </div>
-
- <!-- Port Mappings -->
- <div class="space-y-3">
- <div class="flex items-center justify-between">
- <Label>Port Mappings</Label>
- <Button variant="outline" size="sm" onclick={addPort} disabled={running}>
- <Plus class="mr-1 size-4" />
- Add Port
- </Button>
- </div>
- {#each ports as port, index}
- <div class="flex items-center gap-2">
- <Input bind:value={port.host} placeholder="8080" disabled={running} class="flex-1" />
- <span class="text-muted-foreground">:</span>
- <Input bind:value={port.container} placeholder="80" disabled={running} class="flex-1" />
- <Button variant="outline" size="sm" onclick={() => removePort(index)} disabled={running}>
- <Trash2 class="size-4" />
- </Button>
- </div>
- {/each}
- </div>
-
- <!-- Volume Mounts -->
- <div class="space-y-3">
- <div class="flex items-center justify-between">
- <Label>Volume Mounts</Label>
- <Button variant="outline" size="sm" onclick={addVolume} disabled={running}>
- <Plus class="mr-1 size-4" />
- Add Volume
- </Button>
- </div>
- {#each volumes as volume, index}
- <div class="flex items-center gap-2">
- <Input bind:value={volume.host} placeholder="/host/path" disabled={running} class="flex-1" />
- <span class="text-muted-foreground">:</span>
- <Input bind:value={volume.container} placeholder="/container/path" disabled={running} class="flex-1" />
- <Button variant="outline" size="sm" onclick={() => removeVolume(index)} disabled={running}>
- <Trash2 class="size-4" />
- </Button>
- </div>
- {/each}
- </div>
-
- <!-- Environment Variables -->
- <div class="space-y-3">
- <div class="flex items-center justify-between">
- <Label>Environment Variables</Label>
- <Button variant="outline" size="sm" onclick={addEnvVar} disabled={running}>
- <Plus class="mr-1 size-4" />
- Add Variable
- </Button>
- </div>
- {#each envVars as envVar, index}
- <div class="flex items-center gap-2">
- <Input bind:value={envVar.key} placeholder="VARIABLE_NAME" disabled={running} class="flex-1" />
- <span class="text-muted-foreground">=</span>
- <Input bind:value={envVar.value} placeholder="value" disabled={running} class="flex-1" />
- <Button variant="outline" size="sm" onclick={() => removeEnvVar(index)} disabled={running}>
- <Trash2 class="size-4" />
- </Button>
- </div>
- {/each}
- </div>
-
- <!-- Container Options -->
- <div class="space-y-4">
- <div class="flex items-center justify-between">
- <div>
- <Label>Run in Background</Label>
- <p class="text-muted-foreground text-sm">Run container in detached mode</p>
- </div>
- <Switch bind:checked={detached} disabled={running} />
- </div>
-
- <div class="flex items-center justify-between">
- <div>
- <Label>Auto Remove</Label>
- <p class="text-muted-foreground text-sm">Remove container when it stops</p>
- </div>
- <Switch bind:checked={autoRemove} disabled={running} />
- </div>
-
- <div class="space-y-2">
- <Label for="restartPolicy">Restart Policy</Label>
- <select id="restartPolicy" bind:value={restartPolicy} disabled={running} class="border-input bg-background w-full rounded-md border px-3 py-2">
- <option value="no">No</option>
- <option value="always">Always</option>
- <option value="unless-stopped">Unless Stopped</option>
- <option value="on-failure">On Failure</option>
- </select>
- </div>
- </div>
-
- <!-- Actions -->
- <div class="flex justify-end space-x-2">
- <Button variant="outline" onclick={onClose} disabled={running}>Cancel</Button>
- <Button onclick={handleRun} disabled={running || !imageName.trim()}>
- {#if running}
- <Loader2 class="mr-2 size-4 animate-spin" />
- {/if}
- Run Container
- </Button>
- </div>
-</div>
diff --git a/frontend/src/lib/components/forms/StackDeploymentForm.svelte b/frontend/src/lib/components/forms/StackDeploymentForm.svelte
deleted file mode 100644
index b3ad57797..000000000
--- a/frontend/src/lib/components/forms/StackDeploymentForm.svelte
+++ /dev/null
@@ -1,369 +0,0 @@
-<script lang="ts">
- import { Button } from '$lib/components/ui/button';
- import { Label } from '$lib/components/ui/label';
- import { Textarea } from '$lib/components/ui/textarea';
- import { Input } from '$lib/components/ui/input';
- import { toast } from 'svelte-sonner';
- import { Loader2, Upload, FileText } from '@lucide/svelte';
-
- interface StackDeploymentData {
- mode: 'compose' | 'template' | 'existing';
- stackName: string;
- composeContent: string;
- envContent: string;
- selectedStack?: string;
- }
-
- interface StackTemplate {
- id: string;
- name: string;
- description: string;
- compose: string;
- }
-
- interface Props {
- agentId: string;
- onClose: () => void;
- onDeploy: (data: StackDeploymentData) => Promise<void>;
- }
-
- let { agentId, onClose, onDeploy }: Props = $props();
-
- let deploying = $state(false);
- let deploymentMode = $state<StackDeploymentData['mode']>('compose');
- let stackName = $state('');
- let composeContent = $state('');
- let envContent = $state('');
- let selectedStack = $state('');
-
- // Pre-made templates for easy deployment
- const templates: StackTemplate[] = [
- {
- id: 'nginx',
- name: 'Nginx Web Server',
- description: 'Simple Nginx web server',
- compose: `version: '3.8'
-services:
- nginx:
- image: nginx:alpine
- ports:
- - "80:80"
- volumes:
- - ./html:/usr/share/nginx/html:ro
- restart: unless-stopped`
- },
- {
- id: 'redis',
- name: 'Redis Cache',
- description: 'Redis in-memory database',
- compose: `version: '3.8'
-services:
- redis:
- image: redis:alpine
- ports:
- - "6379:6379"
- volumes:
- - redis_data:/data
- restart: unless-stopped
- command: redis-server --appendonly yes
-
-volumes:
- redis_data:`
- },
- {
- id: 'postgres',
- name: 'PostgreSQL Database',
- description: 'PostgreSQL database server',
- compose: `version: '3.8'
-services:
- postgres:
- image: postgres:15-alpine
- environment:
- POSTGRES_DB: myapp
- POSTGRES_USER: admin
- POSTGRES_PASSWORD: changeme
- ports:
- - "5432:5432"
- volumes:
- - postgres_data:/var/lib/postgresql/data
- restart: unless-stopped
-
-volumes:
- postgres_data:`
- }
- ];
-
- function useTemplate(template: StackTemplate) {
- stackName = template.name.toLowerCase().replace(/\s+/g, '-');
- composeContent = template.compose;
- deploymentMode = 'compose';
- }
-
- async function handleDeploy() {
- // Comprehensive validation
- if (!stackName.trim()) {
- toast.error('Please enter a stack name');
- return;
- }
-
- // Validate stack name format
- const stackNameRegex = /^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$/;
- const trimmedStackName = stackName.trim().toLowerCase();
- if (!stackNameRegex.test(trimmedStackName)) {
- toast.error('Stack name must start with a letter, contain only lowercase letters, numbers, and hyphens, and not end with a hyphen');
- return;
- }
-
- if (trimmedStackName.length > 63) {
- toast.error('Stack name must be 63 characters or less');
- return;
- }
-
- // Reserved stack names
- const reservedNames = ['system', 'docker', 'default', 'admin', 'root', 'api'];
- if (reservedNames.includes(trimmedStackName)) {
- toast.error(`"${trimmedStackName}" is a reserved name. Please choose a different stack name`);
- return;
- }
-
- // Mode-specific validation
- if (deploymentMode === 'compose') {
- if (!composeContent.trim()) {
- toast.error('Please enter Docker Compose content');
- return;
- }
-
- // Basic YAML validation
- try {
- // Check if it looks like valid YAML (basic structure check)
- const lines = composeContent.trim().split('\n');
- const firstLine = lines[0].trim();
-
- // Should have version or services
- if (!firstLine.startsWith('version:') && !composeContent.includes('services:')) {
- toast.error('Compose content should include a version and services section');
- return;
- }
-
- // Check for common YAML issues
- if (composeContent.includes('\t')) {
- toast.error('Compose content contains tabs. Please use spaces for indentation');
- return;
- }
-
- // Check for required services section
- if (!composeContent.includes('services:')) {
- toast.error('Compose content must include a "services:" section');
- return;
- }
-
- // Basic service definition check
- const servicesMatch = composeContent.match(/services:\s*\n([\s\S]*?)(?=\n\w|\n$|$)/);
- if (servicesMatch) {
- const servicesSection = servicesMatch[1];
- const serviceLines = servicesSection.split('\n').filter((line) => line.trim() && !line.startsWith(' '));
-
- if (serviceLines.length === 0) {
- toast.error('At least one service must be defined in the services section');
- return;
- }
- }
- } catch (error) {
- toast.error('Invalid Docker Compose format. Please check your YAML syntax');
- return;
- }
-
- // Validate environment variables format if provided
- if (envContent.trim()) {
- const envLines = envContent.trim().split('\n');
- for (let i = 0; i < envLines.length; i++) {
- const line = envLines[i].trim();
- if (!line) continue; // Skip empty lines
-
- // Should be in KEY=VALUE format
- if (!line.includes('=')) {
- toast.error(`Environment variable line ${i + 1} must be in KEY=VALUE format`);
- return;
- }
-
- const [key, ...valueParts] = line.split('=');
- if (!key.trim()) {
- toast.error(`Environment variable line ${i + 1} is missing a key`);
- return;
- }
-
- // Validate environment variable key format
- const envKeyRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
- if (!envKeyRegex.test(key.trim())) {
- toast.error(`Environment variable "${key}" must start with letter or underscore and contain only letters, numbers, and underscores`);
- return;
- }
- }
- }
- } else if (deploymentMode === 'template') {
- // For template mode, ensure a template was selected (composeContent should be populated)
- if (!composeContent.trim()) {
- toast.error('Please select a template first');
- return;
- }
- } else if (deploymentMode === 'existing') {
- if (!selectedStack.trim()) {
- toast.error('Please select an existing stack');
- return;
- }
- }
-
- deploying = true;
- try {
- const data: StackDeploymentData = {
- mode: deploymentMode,
- stackName: trimmedStackName,
- composeContent: composeContent.trim(),
- envContent: envContent.trim(),
- selectedStack: selectedStack.trim() || undefined
- };
-
- console.log(`🚀 Deploying stack "${trimmedStackName}" with mode "${deploymentMode}"`);
- await onDeploy(data);
- onClose();
- toast.success(`Stack "${trimmedStackName}" deployed successfully`);
- } catch (err) {
- console.error('Deploy error:', err);
-
- // Enhanced error handling with specific error types
- if (err instanceof Error) {
- const errorMessage = err.message.toLowerCase();
-
- // Network/connectivity errors
- if (errorMessage.includes('network') || errorMessage.includes('connection') || errorMessage.includes('timeout')) {
- toast.error('Network error: Unable to connect to the deployment service. Please check your connection and try again.');
- return;
- }
-
- // Permission/authentication errors
- if (errorMessage.includes('unauthorized') || errorMessage.includes('forbidden') || errorMessage.includes('permission')) {
- toast.error('Permission denied: You may not have sufficient permissions to deploy stacks.');
- return;
- }
-
- // Stack already exists
- if (errorMessage.includes('already exists') || errorMessage.includes('conflict')) {
- toast.error(`Stack "${trimmedStackName}" already exists. Please choose a different name or remove the existing stack first.`);
- return;
- }
-
- // Docker/compose specific errors
- if (errorMessage.includes('yaml') || errorMessage.includes('compose') || errorMessage.includes('invalid')) {
- toast.error('Invalid Docker Compose configuration. Please check your compose content and try again.');
- return;
- }
-
- // Resource errors
- if (errorMessage.includes('memory') || errorMessage.includes('disk') || errorMessage.includes('resource')) {
- toast.error('Insufficient resources: The deployment requires more memory, disk space, or other resources than available.');
- return;
- }
-
- // Image pull errors
- if (errorMessage.includes('pull') || errorMessage.includes('image') || errorMessage.includes('registry')) {
- toast.error('Image error: Unable to pull required Docker images. Please check image names and registry availability.');
- return;
- }
-
- // Port binding errors
- if (errorMessage.includes('port') || errorMessage.includes('bind') || errorMessage.includes('address already in use')) {
- toast.error('Port conflict: One or more ports are already in use. Please check your port mappings.');
- return;
- }
-
- // Volume/mount errors
- if (errorMessage.includes('volume') || errorMessage.includes('mount') || errorMessage.includes('path')) {
- toast.error('Volume error: There was an issue with volume mounts or paths. Please check your volume configurations.');
- return;
- }
-
- // Agent-specific errors
- if (errorMessage.includes('agent') || errorMessage.includes('offline')) {
- toast.error('Agent error: The target agent is offline or unavailable. Please try again later.');
- return;
- }
-
- // Generic error with the actual message
- toast.error(`Deployment failed: ${err.message}`);
- } else {
- // Non-Error objects
- console.error('Unknown error type:', err);
- toast.error('An unexpected error occurred during deployment. Please try again.');
- }
- } finally {
- deploying = false;
- }
- }
-</script>
-
-<div class="space-y-6">
- <!-- Deployment Mode Selection -->
- <div class="space-y-3">
- <Label>How would you like to deploy?</Label>
- <div class="grid grid-cols-3 gap-2">
- <Button variant={deploymentMode === 'compose' ? 'default' : 'outline'} size="sm" onclick={() => (deploymentMode = 'compose')} class="flex h-auto flex-col p-3">
- <FileText class="mb-1 size-4" />
- <span class="text-xs">Write Compose</span>
- </Button>
- <Button variant={deploymentMode === 'template' ? 'default' : 'outline'} size="sm" onclick={() => (deploymentMode = 'template')} class="flex h-auto flex-col p-3">
- <Upload class="mb-1 size-4" />
- <span class="text-xs">Use Template</span>
- </Button>
- <Button variant={deploymentMode === 'existing' ? 'default' : 'outline'} size="sm" onclick={() => (deploymentMode = 'existing')} class="flex h-auto flex-col p-3" disabled>
- <FileText class="mb-1 size-4" />
- <span class="text-xs">Existing Stack</span>
- </Button>
- </div>
- </div>
-
- {#if deploymentMode === 'template'}
- <!-- Template Selection -->
- <div class="space-y-3">
- <Label>Choose a template</Label>
- <div class="grid gap-2">
- {#each templates as template}
- <button class="hover:border-primary/50 rounded-lg border p-3 text-left transition-colors" onclick={() => useTemplate(template)}>
- <div class="text-sm font-medium">{template.name}</div>
- <div class="text-muted-foreground text-xs">{template.description}</div>
- </button>
- {/each}
- </div>
- </div>
- {/if}
-
- <!-- Stack Name -->
- <div class="space-y-2">
- <Label for="stackName">Stack Name</Label>
- <Input id="stackName" bind:value={stackName} placeholder="my-awesome-app" disabled={deploying} />
- </div>
-
- {#if deploymentMode === 'compose'}
- <!-- Compose Content -->
- <div class="space-y-2">
- <Label for="compose">Docker Compose Content</Label>
- <Textarea id="compose" bind:value={composeContent} placeholder="version: '3.8'&#10;services:&#10; web:&#10; image: nginx:alpine&#10; ports:&#10; - '80:80'" class="min-h-[200px] font-mono text-sm" disabled={deploying} />
- </div>
-
- <!-- Environment Variables (Optional) -->
- <div class="space-y-2">
- <Label for="env">Environment Variables (Optional)</Label>
- <Textarea id="env" bind:value={envContent} placeholder="DATABASE_URL=postgres://user:pass@db:5432/myapp&#10;REDIS_URL=redis://redis:6379" class="min-h-[80px] font-mono text-sm" disabled={deploying} />
- </div>
- {/if}
-
- <!-- Actions -->
- <div class="flex justify-end space-x-2">
- <Button variant="outline" onclick={onClose} disabled={deploying}>Cancel</Button>
- <Button onclick={handleDeploy} disabled={deploying || !stackName.trim()}>
- {#if deploying}
- <Loader2 class="mr-2 size-4 animate-spin" />
- {/if}
- Deploy Stack
- </Button>
- </div>
-</div>
diff --git a/frontend/src/lib/components/sheets/create-network-sheet.svelte b/frontend/src/lib/components/sheets/create-network-sheet.svelte
index 2e546734b..cb5454b80 100644
--- a/frontend/src/lib/components/sheets/create-network-sheet.svelte
+++ b/frontend/src/lib/components/sheets/create-network-sheet.svelte
@@ -1,7 +1,6 @@
<script lang="ts">
import * as Sheet from '$lib/components/ui/sheet/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import FormInput from '$lib/components/form/form-input.svelte';
import * as Accordion from '$lib/components/ui/accordion/index.js';
import { Checkbox } from '$lib/components/ui/checkbox/index.js';
import { Label } from '$lib/components/ui/label/index.js';
diff --git a/frontend/src/lib/components/sheets/image-pull-sheet.svelte b/frontend/src/lib/components/sheets/image-pull-sheet.svelte
index 7535dfdea..21c8db8f6 100644
--- a/frontend/src/lib/components/sheets/image-pull-sheet.svelte
+++ b/frontend/src/lib/components/sheets/image-pull-sheet.svelte
@@ -6,6 +6,8 @@
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/form.utils';
import { toast } from 'svelte-sonner';
+ import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '$lib/stores/environment.store';
+ import { get } from 'svelte/store';
type ImagePullFormProps = {
open: boolean;
@@ -64,6 +66,14 @@
}
}
+ function buildApiUrl(fullImageName: string): string {
+ const envId = getCurrentEnvironmentId();
+ if (envId === LOCAL_DOCKER_ENVIRONMENT_ID) {
+ return '/api/images/pull';
+ }
+ return `/api/environments/${envId}/images/pull`;
+ }
+
async function handleSubmit() {
const data = form.validate();
if (!data) return;
@@ -87,7 +97,7 @@
pullStatusText = `Pulling ${fullImageName}...`;
try {
- const response = await fetch('/api/images/pull', {
+ const response = await fetch(buildApiUrl(fullImageName), {
method: 'POST',
headers: {
'Content-Type': 'application/json'
@@ -194,6 +204,11 @@
$inputs.tag.value = 'latest';
}
}
+
+ function getCurrentEnvironmentId(): string {
+ const env = get(environmentStore.selected);
+ return env?.id || LOCAL_DOCKER_ENVIRONMENT_ID;
+ }
</script>
<Sheet.Root bind:open onOpenChange={handleOpenChange}>
diff --git a/frontend/src/lib/components/sheets/new-environment-sheet.svelte b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
new file mode 100644
index 000000000..18f797ac2
--- /dev/null
+++ b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
@@ -0,0 +1,201 @@
+<script lang="ts">
+ import { onMount } from 'svelte';
+ import { toast } from 'svelte-sonner';
+ import * as Sheet from '$lib/components/ui/sheet/index.js';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import FormInput from '$lib/components/form/form-input.svelte';
+ import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
+ import { Loader2, Server, Trash2, TestTube } from '@lucide/svelte';
+ import * as Card from '$lib/components/ui/card';
+ import { environmentManagementAPI } from '$lib/services/api';
+ import type { Environment } from '$lib/stores/environment.store';
+ import type { CreateEnvironmentDTO } from '$lib/dto/environment-dto';
+ import { z } from 'zod/v4';
+ import { createForm, preventDefault } from '$lib/utils/form.utils';
+
+ type NewEnvironmentSheetProps = {
+ open: boolean;
+ onEnvironmentCreated?: () => void;
+ };
+
+ let { open = $bindable(false), onEnvironmentCreated }: NewEnvironmentSheetProps = $props();
+
+ let environments = $state<Environment[]>([]);
+ let loading = $state(false);
+ let isSubmitting = $state(false);
+
+ const formSchema = z.object({
+ hostname: z.string().min(1, 'Hostname is required').max(100, 'Hostname too long'),
+ apiUrl: z.string().url('Must be a valid URL').min(1, 'API URL is required'),
+ description: z.string().optional(),
+ enabled: z.boolean().default(true)
+ });
+
+ let formData = $state({
+ hostname: '',
+ apiUrl: '',
+ description: '',
+ enabled: true
+ });
+
+ let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
+
+ onMount(async () => {
+ await loadEnvironments();
+ });
+
+ async function loadEnvironments() {
+ try {
+ loading = true;
+ environments = await environmentManagementAPI.list();
+ } catch (error) {
+ toast.error('Failed to load environments');
+ console.error(error);
+ } finally {
+ loading = false;
+ }
+ }
+
+ async function handleSubmit() {
+ const data = form.validate();
+ if (!data) return;
+
+ try {
+ isSubmitting = true;
+ const dto: CreateEnvironmentDTO = {
+ hostname: data.hostname,
+ apiUrl: data.apiUrl,
+ description: data.description
+ };
+
+ await environmentManagementAPI.create(dto);
+ toast.success('Environment created successfully');
+
+ form.reset();
+ await loadEnvironments();
+ onEnvironmentCreated?.();
+ } catch (error) {
+ toast.error('Failed to create environment');
+ console.error(error);
+ } finally {
+ isSubmitting = false;
+ }
+ }
+
+ async function deleteEnvironment(environmentId: string) {
+ if (!confirm('Are you sure you want to delete this environment?')) {
+ return;
+ }
+
+ try {
+ await environmentManagementAPI.delete(environmentId);
+ toast.success('Environment deleted successfully');
+ await loadEnvironments();
+ } catch (error) {
+ toast.error('Failed to delete environment');
+ console.error(error);
+ }
+ }
+
+ async function testConnection(environmentId: string) {
+ try {
+ const result = await environmentManagementAPI.testConnection(environmentId);
+ if (result.status === 'online') {
+ toast.success('Connection successful');
+ } else {
+ toast.error(`Connection failed: ${result.message || 'Unknown error'}`);
+ }
+ } catch (error) {
+ toast.error('Failed to test connection');
+ console.error(error);
+ }
+ }
+
+ function handleOpenChange(newOpenState: boolean) {
+ open = newOpenState;
+ if (!newOpenState) {
+ form.reset();
+ }
+ }
+</script>
+
+<Sheet.Root bind:open onOpenChange={handleOpenChange}>
+ <Sheet.Content class="p-6 w-full sm:max-w-lg">
+ <Sheet.Header class="space-y-3 pb-6 border-b">
+ <div class="flex items-center gap-3">
+ <div class="flex size-10 items-center justify-center rounded-lg bg-primary/10 shrink-0">
+ <Server class="size-5 text-primary" />
+ </div>
+ <div>
+ <Sheet.Title class="text-xl font-semibold">Manage Environments</Sheet.Title>
+ <Sheet.Description class="text-sm text-muted-foreground mt-1">Add and manage remote Docker environments. Each environment should be an Arcane agent running as an API server.</Sheet.Description>
+ </div>
+ </div>
+ </Sheet.Header>
+
+ <div class="space-y-6 py-6">
+ <Card.Root>
+ <Card.Header>
+ <Card.Title class="text-lg">Add New Environment</Card.Title>
+ </Card.Header>
+ <Card.Content>
+ <form onsubmit={preventDefault(handleSubmit)} class="space-y-4">
+ <FormInput label="Hostname *" type="text" placeholder="docker-host-1" description="Display name for this environment" bind:input={$inputs.hostname} />
+
+ <FormInput label="API URL *" type="text" placeholder="http://192.168.1.100:3552" description="Full URL to the agent's API endpoint" bind:input={$inputs.apiUrl} />
+
+ <FormInput label="Description" type="text" placeholder="Production Docker host" description="Optional description for this environment" bind:input={$inputs.description} />
+
+ <SwitchWithLabel id="enabledSwitch" label="Enabled" description="Enable this environment for use" bind:checked={$inputs.enabled.value} />
+
+ <Button type="submit" class="w-full" disabled={isSubmitting}>
+ {#if isSubmitting}
+ <Loader2 class="mr-2 size-4 animate-spin" />
+ {/if}
+ Add Environment
+ </Button>
+ </form>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root>
+ <Card.Header>
+ <Card.Title class="text-lg">Existing Environments</Card.Title>
+ </Card.Header>
+ <Card.Content>
+ {#if loading}
+ <div class="text-center py-4">
+ <Loader2 class="size-4 animate-spin mx-auto" />
+ </div>
+ {:else if environments.length === 0}
+ <div class="text-center py-4 text-muted-foreground">No environments configured</div>
+ {:else}
+ <div class="space-y-3">
+ {#each environments as environment}
+ <div class="flex items-center justify-between p-3 border rounded-lg">
+ <div class="flex-1 min-w-0">
+ <div class="font-medium truncate">{environment.hostname}</div>
+ <div class="text-sm text-muted-foreground truncate">{environment.apiUrl}</div>
+ <div class="flex items-center gap-2 mt-1">
+ <span class="text-xs px-2 py-1 rounded-full {environment.status === 'online' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">
+ {environment.status}
+ </span>
+ </div>
+ </div>
+ <div class="flex items-center gap-2 ml-2">
+ <Button variant="outline" size="sm" onclick={() => testConnection(environment.id)}>
+ <TestTube class="h-4 w-4" />
+ </Button>
+ <Button variant="destructive" size="sm" onclick={() => deleteEnvironment(environment.id)}>
+ <Trash2 class="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ {/each}
+ </div>
+ {/if}
+ </Card.Content>
+ </Card.Root>
+ </div>
+ </Sheet.Content>
+</Sheet.Root>
diff --git a/frontend/src/lib/components/sidebar/sidebar-agent-switcher.svelte b/frontend/src/lib/components/sidebar/sidebar-agent-switcher.svelte
index 39b348017..7a8b2bb5d 100644
--- a/frontend/src/lib/components/sidebar/sidebar-agent-switcher.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar-agent-switcher.svelte
@@ -6,82 +6,109 @@
import PlusIcon from '@lucide/svelte/icons/plus';
import { GalleryVerticalEndIcon } from '@lucide/svelte';
import ServerIcon from '@lucide/svelte/icons/server';
- import type { Agent } from '$lib/types/agent.type';
+ import { environmentStore, type Environment } from '$lib/stores/environment.store';
+ import { goto } from '$app/navigation';
+ import { toast } from 'svelte-sonner';
- // Extend the Agent type to include isLocal for the local Docker option
- type ExtendedAgent = Agent & { isLocal?: boolean };
-
- let { agents, hasLocalDocker = false }: { agents: Agent[]; hasLocalDocker?: boolean } = $props();
const sidebar = useSidebar();
- const localDockerAgent: ExtendedAgent = {
- id: 'local',
- hostname: 'Local Docker',
- platform: 'local',
- version: 'N/A',
- capabilities: [],
- status: 'online' as const,
- lastSeen: new Date().toISOString(),
- registeredAt: new Date().toISOString(),
- createdAt: new Date().toISOString(),
- isLocal: true
- };
+ let currentSelectedEnvironment = $state<Environment | null>(null);
+ let availableEnvironments = $state<Environment[]>([]);
+
+ $effect(() => {
+ const unsubscribeSelected = environmentStore.selected.subscribe((value) => {
+ currentSelectedEnvironment = value;
+ });
+ const unsubscribeAvailable = environmentStore.available.subscribe((value) => {
+ availableEnvironments = value;
+ });
+ return () => {
+ unsubscribeSelected();
+ unsubscribeAvailable();
+ };
+ });
- const allAgents: ExtendedAgent[] = $derived(hasLocalDocker ? [localDockerAgent, ...agents] : agents);
- let activeAgent = $derived(allAgents[0]);
+ function handleSelect(env: Environment) {
+ try {
+ environmentStore.setEnvironment(env);
+ } catch (error) {
+ console.error('Failed to set environment:', error);
+ toast.error('Failed to Connect to Environment');
+ }
+ }
</script>
<Sidebar.Menu>
<Sidebar.MenuItem>
<DropdownMenu.Root>
<DropdownMenu.Trigger>
- {#snippet child({ props })}
- <Sidebar.MenuButton {...props} size="lg" class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground">
- <div class="bg-sidebar-primary text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
- {#if activeAgent?.isLocal}
+ {#snippet child({ props: childProps })}
+ <Sidebar.MenuButton {...childProps} size="lg" class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground">
+ {#if currentSelectedEnvironment}
+ <div class="bg-sidebar-primary text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
+ {#if currentSelectedEnvironment.isLocal}
+ <ServerIcon class="size-4" />
+ {:else}
+ <GalleryVerticalEndIcon class="size-4" />
+ {/if}
+ </div>
+ <div class="grid flex-1 text-left text-sm leading-tight">
+ <span class="truncate font-medium">
+ {currentSelectedEnvironment.hostname}
+ </span>
+ <span class="truncate text-xs">
+ {currentSelectedEnvironment.isLocal ? 'Local Docker' : currentSelectedEnvironment.apiUrl}
+ </span>
+ </div>
+ {:else}
+ <div class="bg-sidebar-primary text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
<ServerIcon class="size-4" />
- {:else}
- <GalleryVerticalEndIcon class="size-4" />
- {/if}
- </div>
- <div class="grid flex-1 text-left text-sm leading-tight">
- <span class="truncate font-medium">
- {activeAgent?.hostname}
- </span>
- <span class="truncate text-xs">
- {activeAgent?.isLocal ? 'Local Socket' : activeAgent?.id}
- </span>
- </div>
+ </div>
+ <div class="grid flex-1 text-left text-sm leading-tight">
+ <span class="truncate font-medium">No Environment</span>
+ <span class="truncate text-xs">Select one</span>
+ </div>
+ {/if}
<ChevronsUpDownIcon class="ml-auto" />
</Sidebar.MenuButton>
{/snippet}
</DropdownMenu.Trigger>
- <DropdownMenu.Content class="w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg" align="start" side={sidebar.isMobile ? 'bottom' : 'right'} sideOffset={4}>
- <DropdownMenu.Label class="text-muted-foreground text-xs">Docker Instances</DropdownMenu.Label>
- {#each allAgents as agent, index (agent.id)}
- <DropdownMenu.Item onSelect={() => (activeAgent = agent)} class="gap-2 p-2">
+ <DropdownMenu.Content class="w-[var(--bits-dropdown-menu-anchor-width)] min-w-56 rounded-lg" align="start" side={sidebar.isMobile ? 'bottom' : 'right'} sideOffset={4}>
+ <DropdownMenu.Label class="text-muted-foreground text-xs">Select Environment</DropdownMenu.Label>
+ {#if availableEnvironments.length === 0}
+ <DropdownMenu.Item disabled class="gap-2 p-2">
<div class="flex size-6 items-center justify-center rounded-md border">
- {#if agent.isLocal}
- <ServerIcon class="size-3.5 shrink-0" />
- {:else}
- <GalleryVerticalEndIcon class="size-3.5 shrink-0" />
- {/if}
- </div>
- <div class="flex flex-col">
- <span>{agent.hostname}</span>
- {#if agent.isLocal}
- <span class="text-muted-foreground text-xs">Local Socket</span>
- {/if}
+ <ServerIcon class="size-3.5 shrink-0" />
</div>
- <DropdownMenu.Shortcut>⌘{index + 1}</DropdownMenu.Shortcut>
+ <span>No environments available</span>
</DropdownMenu.Item>
- {/each}
+ {:else}
+ {#each availableEnvironments as env (env.id)}
+ <DropdownMenu.Item onSelect={() => handleSelect(env)} class="gap-2 p-2">
+ <div class="flex size-6 items-center justify-center rounded-md border">
+ {#if env.isLocal}
+ <ServerIcon class="size-3.5 shrink-0" />
+ {:else}
+ <GalleryVerticalEndIcon class="size-3.5 shrink-0" />
+ {/if}
+ </div>
+ <div class="flex flex-col">
+ <span>{env.hostname}</span>
+ {#if env.isLocal}
+ <span class="text-muted-foreground text-xs">Local Docker</span>
+ {:else}
+ <span class="text-muted-foreground text-xs truncate max-w-32">{env.apiUrl}</span>
+ {/if}
+ </div>
+ </DropdownMenu.Item>
+ {/each}
+ {/if}
<DropdownMenu.Separator />
- <DropdownMenu.Item class="gap-2 p-2">
+ <DropdownMenu.Item class="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="text-muted-foreground font-medium">Add Agent</div>
+ <div class="text-muted-foreground font-medium">Manage Environments</div>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/lib/components/sidebar/sidebar.svelte b/frontend/src/lib/components/sidebar/sidebar.svelte
index 5bee6aa5d..35dcd3bca 100644
--- a/frontend/src/lib/components/sidebar/sidebar.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar.svelte
@@ -12,7 +12,7 @@
{ title: 'Docker', url: '/settings/docker', icon: DatabaseIcon },
{ title: 'Users', url: '/settings/users', icon: UserIcon },
{ title: 'Security', url: '/settings/security', icon: Shield },
- { title: 'Agents (Preview)', url: '/agents', icon: ComputerIcon }
+ { title: 'Environments', url: '/environments', icon: ComputerIcon }
]
}
],
@@ -50,21 +50,16 @@
import type { AppVersionInformation } from '$lib/types/application-configuration';
import SidebarLogo from './sidebar-logo.svelte';
import SidebarUpdatebanner from './sidebar-updatebanner.svelte';
- import type { Agent } from '$lib/types/agent.type';
let {
ref = $bindable(null),
collapsible = 'icon',
user,
versionInformation,
- hasLocalDocker,
- agents,
...restProps
}: ComponentProps<typeof Sidebar.Root> & {
versionInformation: AppVersionInformation;
- hasLocalDocker: boolean;
user?: User | null;
- agents: Agent[];
} = $props();
const sidebar = useSidebar();
@@ -75,8 +70,7 @@
<Sidebar.Root {collapsible} {...restProps}>
<Sidebar.Header>
<SidebarLogo {isCollapsed} {versionInformation} />
- <!-- Add back once we add in better agent switching -->
- <!-- <SidebarAgentSwitcher {hasLocalDocker} {agents} /> -->
+ <SidebarAgentSwitcher />
</Sidebar.Header>
<Sidebar.Content>
<SidebarItemGroup label="Management" items={staticData.managementItems} />
diff --git a/frontend/src/lib/components/yaml-editor.svelte b/frontend/src/lib/components/yaml-editor.svelte
index 2ec4e0f2e..df1f4debe 100644
--- a/frontend/src/lib/components/yaml-editor.svelte
+++ b/frontend/src/lib/components/yaml-editor.svelte
@@ -43,8 +43,7 @@
styles={{
'&': {
height: '550px',
- fontSize: '12px',
- fontFamily: 'JetBrains Mono, Menlo, Monaco, Consolas, monospace'
+ fontSize: '11px'
},
'&.cm-editor[contenteditable=false]': {
cursor: 'not-allowed'
diff --git a/frontend/src/lib/constants.ts b/frontend/src/lib/constants.ts
index 717fe231c..4379b7e35 100644
--- a/frontend/src/lib/constants.ts
+++ b/frontend/src/lib/constants.ts
@@ -1,20 +1,5 @@
-import { dev } from '$app/environment';
-
-export const isDev = dev;
-
-export const isTest = false;
-
export const defaultEnvTemplate = `# Environment Variables
-# These variables will be available to your stack services
# Format: VARIABLE_NAME=value
-
-NGINX_HOST=localhost
-NGINX_PORT=80
-
-# Example Database Configuration
-# DB_USER=myuser
-# DB_PASSWORD=mypassword
-# DB_NAME=mydatabase
`;
export const defaultComposeTemplate = `services:
diff --git a/frontend/src/lib/dto/agent-dto.ts b/frontend/src/lib/dto/agent-dto.ts
new file mode 100644
index 000000000..3cd1e82b0
--- /dev/null
+++ b/frontend/src/lib/dto/agent-dto.ts
@@ -0,0 +1,74 @@
+import type { Agent, AgentStats, AgentTask, AgentTaskType, AgentTaskStatus, AgentMetrics, DockerInfo } from '$lib/types/agent.type';
+
+export interface CreateAgentDTO {
+ agent_id: string;
+ hostname: string;
+ platform?: string;
+ version?: string;
+ capabilities?: string[];
+}
+
+export interface UpdateAgentDTO {
+ hostname?: string;
+ platform?: string;
+ version?: string;
+ capabilities?: string[];
+ status?: Agent['status'];
+ metadata?: Record<string, any>;
+}
+
+export interface CreateTaskDTO {
+ type: AgentTaskType;
+ payload: Record<string, any>;
+}
+
+export interface UpdateTaskStatusDTO {
+ status: AgentTaskStatus;
+ result?: any;
+ error?: string;
+}
+
+export interface UpdateMetricsDTO {
+ containerCount: number;
+ imageCount: number;
+ stackCount: number;
+ networkCount: number;
+ volumeCount: number;
+}
+
+export interface UpdateDockerInfoDTO {
+ version: string;
+ containers: number;
+ images: number;
+}
+
+export interface HeartbeatDTO {
+ agent_id: string;
+ status: string;
+ timestamp: string;
+}
+
+export interface DockerCommandDTO {
+ command: string;
+ args: string[];
+}
+
+export interface StackDeployDTO {
+ stackId: string;
+ composeContent: string;
+ envContent?: string;
+}
+
+export interface ImagePullDTO {
+ imageName: string;
+}
+
+export interface ContainerActionDTO {
+ containerId: string;
+ force?: boolean;
+}
+
+export interface AgentUpgradeDTO {
+ action: 'upgrade';
+ version?: string;
+}
diff --git a/frontend/src/lib/dto/environment-dto.ts b/frontend/src/lib/dto/environment-dto.ts
new file mode 100644
index 000000000..f365ec4c1
--- /dev/null
+++ b/frontend/src/lib/dto/environment-dto.ts
@@ -0,0 +1,24 @@
+import type { Environment } from '$lib/stores/environment.store';
+
+export interface CreateEnvironmentDTO {
+ hostname: string;
+ apiUrl: string;
+ description?: string;
+}
+
+export interface UpdateEnvironmentDTO {
+ hostname?: string;
+ apiUrl?: string;
+ description?: string;
+}
+
+export interface EnvironmentResponse {
+ environment: Environment;
+ success: boolean;
+ message?: string;
+}
+
+export interface EnvironmentsListResponse {
+ environments: Environment[];
+ success: boolean;
+}
diff --git a/frontend/src/lib/types/docker/image.type.ts b/frontend/src/lib/models/image.type.ts
similarity index 100%
rename from frontend/src/lib/types/docker/image.type.ts
rename to frontend/src/lib/models/image.type.ts
diff --git a/frontend/src/lib/types/docker/stack.type.ts b/frontend/src/lib/models/stack.type.ts
similarity index 100%
rename from frontend/src/lib/types/docker/stack.type.ts
rename to frontend/src/lib/models/stack.type.ts
diff --git a/frontend/src/lib/services/agent/agent-manager.ts b/frontend/src/lib/services/agent/agent-manager.ts
deleted file mode 100644
index 629d38bc6..000000000
--- a/frontend/src/lib/services/agent/agent-manager.ts
+++ /dev/null
@@ -1,382 +0,0 @@
-import type { Agent, AgentTask } from '$lib/types/agent.type';
-import { nanoid } from 'nanoid';
-import { updateDeploymentFromTask } from '$lib/services/deployment-service';
-import { agentAPI } from '../api';
-
-// Extract the task type from AgentTask to ensure type safety
-type AgentTaskType = AgentTask['type'];
-
-/**
- * Register a new agent or update existing one
- */
-export async function registerAgent(agent: Agent): Promise<Agent> {
- try {
- const existing = await getAgent(agent.id);
-
- if (existing) {
- // Update existing agent
- return await updateAgent(agent.id, {
- ...agent,
- status: 'online',
- lastSeen: new Date().toISOString(),
- updatedAt: new Date().toISOString()
- });
- } else {
- // Create new agent
- const newAgent: Agent = {
- ...agent,
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString()
- };
-
- return await agentAPI.register(newAgent);
- }
- } catch (error) {
- console.error('Failed to register agent:', error);
- throw error;
- }
-}
-
-/**
- * Get agent by ID
- */
-export async function getAgent(agentId: string): Promise<Agent | null> {
- try {
- return await agentAPI.get(agentId);
- } catch (error) {
- console.error('Failed to get agent:', error);
- return null;
- }
-}
-
-/**
- * Update agent information
- */
-export async function updateAgent(agentId: string, updates: Partial<Agent>): Promise<Agent> {
- try {
- return await agentAPI.update(agentId, updates);
- } catch (error) {
- console.error('Failed to update agent:', error);
- throw error;
- }
-}
-
-/**
- * Update agent heartbeat (called by agents to indicate they're online)
- */
-export async function updateAgentHeartbeat(agentId: string): Promise<void> {
- try {
- await agentAPI.heartbeat(agentId);
- } catch (error) {
- console.error('Failed to update agent heartbeat:', error);
- // Don't throw here as this is called frequently by agents
- }
-}
-
-/**
- * List all agents
- */
-export async function listAgents(): Promise<Agent[]> {
- try {
- return await agentAPI.list();
- } catch (error) {
- console.error('Failed to list agents:', error);
- return [];
- }
-}
-
-/**
- * Delete an agent and all its tasks
- */
-export async function deleteAgent(agentId: string): Promise<void> {
- try {
- await agentAPI.delete(agentId);
- console.log(`Agent ${agentId} deleted successfully`);
- } catch (error) {
- console.error('Failed to delete agent:', error);
- throw error;
- }
-}
-
-/**
- * Send a task to an agent
- */
-export async function sendTaskToAgent(agentId: string, taskType: AgentTaskType, payload: any): Promise<AgentTask> {
- try {
- const agent = await getAgent(agentId);
- if (!agent) {
- throw new Error(`Agent ${agentId} not found`);
- }
-
- if (agent.status !== 'online') {
- throw new Error(`Agent ${agentId} is not online (status: ${agent.status})`);
- }
-
- // Create task using the API
- const task = await agentAPI.createTask(agentId, {
- type: taskType,
- payload
- });
-
- console.log(`📋 Task ${task.id} created for agent ${agentId} (will be picked up on next poll)`);
-
- return task;
- } catch (error) {
- console.error('Failed to send task to agent:', error);
- throw error;
- }
-}
-
-/**
- * Update task status (called when agents complete tasks)
- */
-export async function updateTaskStatus(taskId: string, status: string, result?: any, error?: string): Promise<void> {
- try {
- await agentAPI.updateTaskStatus(taskId, {
- status,
- result,
- error
- });
-
- await updateDeploymentFromTask(taskId, status, result, error);
-
- console.log(`Task ${taskId} status updated to: ${status}`);
- } catch (dbError) {
- console.error('Error updating task status:', dbError);
- // Don't throw here as agents rely on this endpoint
- }
-}
-
-/**
- * Get a single task by ID
- */
-export async function getTask(taskId: string): Promise<AgentTask | null> {
- try {
- return await agentAPI.getTask(taskId);
- } catch (error) {
- console.error('Failed to get task:', error);
- return null;
- }
-}
-
-/**
- * List tasks (optionally filtered by agent)
- */
-export async function listTasks(agentId?: string): Promise<AgentTask[]> {
- try {
- if (agentId) {
- return await agentAPI.listTasks(agentId);
- } else {
- return await agentAPI.listAllTasks();
- }
- } catch (error) {
- console.error('Failed to list tasks:', error);
- return [];
- }
-}
-
-/**
- * Get tasks for a specific agent (alias for listTasks)
- */
-export async function getAgentTasks(agentId: string): Promise<AgentTask[]> {
- try {
- return await agentAPI.listTasks(agentId);
- } catch (error) {
- console.error('Failed to get agent tasks:', error);
- return [];
- }
-}
-
-/**
- * Get pending tasks for an agent (called by agents)
- */
-export async function getPendingTasks(agentId: string): Promise<AgentTask[]> {
- try {
- return await agentAPI.getPendingTasks(agentId);
- } catch (error) {
- console.error('Failed to get pending tasks:', error);
- return [];
- }
-}
-
-/**
- * Update agent metrics
- */
-export async function updateAgentMetrics(
- agentId: string,
- metrics: {
- containerCount?: number;
- imageCount?: number;
- stackCount?: number;
- networkCount?: number;
- volumeCount?: number;
- }
-): Promise<void> {
- try {
- await agentAPI.updateMetrics(agentId, metrics);
- } catch (error) {
- console.error('Failed to update agent metrics:', error);
- // Don't throw as this is not critical
- }
-}
-
-/**
- * Update agent Docker information
- */
-export async function updateAgentDockerInfo(
- agentId: string,
- dockerInfo: {
- version?: string;
- containers?: number;
- images?: number;
- }
-): Promise<void> {
- try {
- await agentAPI.updateDockerInfo(agentId, dockerInfo);
- } catch (error) {
- console.error('Failed to update agent Docker info:', error);
- // Don't throw as this is not critical
- }
-}
-
-// ===== CONVENIENCE HELPER FUNCTIONS =====
-
-/**
- * Send Docker command to agent
- */
-export async function sendDockerCommand(agentId: string, command: string, args: string[] = []): Promise<AgentTask> {
- return sendTaskToAgent(agentId, 'docker_command', {
- command,
- args
- });
-}
-
-/**
- * Deploy stack to agent
- */
-export async function deployStackToAgent(agentId: string, stackId: string, composeContent: string, envContent?: string): Promise<AgentTask> {
- return sendTaskToAgent(agentId, 'stack_deploy', {
- stackId,
- composeContent,
- envContent
- });
-}
-
-/**
- * Pull image on agent
- */
-export async function pullImageOnAgent(agentId: string, imageName: string): Promise<AgentTask> {
- return sendTaskToAgent(agentId, 'image_pull', {
- imageName
- });
-}
-
-/**
- * Send health check to agent
- */
-export async function sendHealthCheck(agentId: string): Promise<AgentTask> {
- return sendTaskToAgent(agentId, 'health_check', {});
-}
-
-/**
- * Send upgrade command to agent
- */
-export async function upgradeAgent(agentId: string, version?: string): Promise<AgentTask> {
- return sendTaskToAgent(agentId, 'agent_upgrade', {
- version: version || 'latest'
- });
-}
-
-/**
- * Process agent message (for WebSocket or other real-time communication)
- */
-export async function processAgentMessage(agentId: string, message: any): Promise<void> {
- console.log(`Processing message from agent ${agentId}:`, message);
-
- try {
- if (message.type === 'task_result') {
- const { task_id, status, result, error } = message.data;
- await updateTaskStatus(task_id, status, result, error);
- } else if (message.type === 'heartbeat') {
- await updateAgentHeartbeat(agentId);
- } else if (message.type === 'metrics') {
- await updateAgentMetrics(agentId, message.data);
- } else if (message.type === 'docker_info') {
- await updateAgentDockerInfo(agentId, message.data);
- }
- } catch (error) {
- console.error('Failed to process agent message:', error);
- }
-}
-
-/**
- * Check if agent is online (with timeout consideration)
- */
-export function isAgentOnline(agent: Agent, timeoutMinutes = 5): boolean {
- if (agent.status !== 'online') return false;
-
- const now = new Date();
- const lastSeen = new Date(agent.lastSeen);
- const timeoutMs = timeoutMinutes * 60 * 1000;
-
- return now.getTime() - lastSeen.getTime() < timeoutMs;
-}
-
-/**
- * Get agents that are actually online (considering timeout)
- */
-export async function getOnlineAgents(timeoutMinutes = 5): Promise<Agent[]> {
- const allAgents = await listAgents();
- return allAgents.filter((agent) => isAgentOnline(agent, timeoutMinutes));
-}
-
-/**
- * Get agent statistics
- */
-export async function getAgentStats(): Promise<{
- total: number;
- online: number;
- offline: number;
- totalTasks: number;
- pendingTasks: number;
- runningTasks: number;
- completedTasks: number;
- failedTasks: number;
-}> {
- try {
- const [agents, allTasks] = await Promise.all([listAgents(), listTasks()]);
-
- const onlineAgents = agents.filter((agent) => isAgentOnline(agent));
-
- const taskStats = allTasks.reduce(
- (acc, task) => {
- acc[task.status]++;
- return acc;
- },
- { pending: 0, running: 0, completed: 0, failed: 0 } as Record<string, number>
- );
-
- return {
- total: agents.length,
- online: onlineAgents.length,
- offline: agents.length - onlineAgents.length,
- totalTasks: allTasks.length,
- pendingTasks: taskStats.pending,
- runningTasks: taskStats.running,
- completedTasks: taskStats.completed,
- failedTasks: taskStats.failed
- };
- } catch (error) {
- console.error('Failed to get agent stats:', error);
- return {
- total: 0,
- online: 0,
- offline: 0,
- totalTasks: 0,
- pendingTasks: 0,
- runningTasks: 0,
- completedTasks: 0,
- failedTasks: 0
- };
- }
-}
diff --git a/frontend/src/lib/services/agent/agent-stack-service.ts b/frontend/src/lib/services/agent/agent-stack-service.ts
deleted file mode 100644
index f48c061a8..000000000
--- a/frontend/src/lib/services/agent/agent-stack-service.ts
+++ /dev/null
@@ -1,307 +0,0 @@
-import { sendTaskToAgent } from '$lib/services/agent/agent-manager';
-import type { Agent, AgentStack, StackStatus } from '$lib/types/agent.type';
-import type { Stack } from '$lib/types/docker/stack.type';
-import { agentStackAPI } from '../api';
-
-// Add this interface to handle server-side request context
-export interface ServerFetchContext {
- fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
-}
-
-export async function getStacksFromAgent(agent: Agent, context?: ServerFetchContext): Promise<AgentStack[]> {
- try {
- // Send a task to get compose projects from the agent
- const task = await sendTaskToAgent(agent.id, 'stack_list', {});
-
- // Poll for task completion
- const maxAttempts = 30; // 30 seconds timeout
- const delay = 1000; // 1 second between polls
-
- console.log(`Polling for stack data from agent ${agent.hostname} (task ${task.id})`);
-
- for (let i = 0; i < maxAttempts; i++) {
- await new Promise((resolve) => setTimeout(resolve, delay));
-
- // Fetch the task status - use context.fetch if provided, otherwise use global fetch
- const fetchFunc = context?.fetch || fetch;
- const apiUrl = `/api/agents/${agent.id}/tasks/${task.id}`;
-
- // Use absolute URL if needed (for server context)
- const updatedTask = await fetchFunc(apiUrl, {
- credentials: 'include'
- }).then((res) => (res.ok ? res.json() : null));
-
- if (!updatedTask || !updatedTask.task) {
- console.log(`Polling attempt ${i + 1}: No task data received`);
- continue;
- }
-
- const taskStatus = updatedTask.task.status;
- console.log(`Polling attempt ${i + 1}: Task status is ${taskStatus}`);
-
- if (taskStatus === 'completed' && updatedTask.task.result) {
- console.log(`Task completed, processing stack data`);
-
- // Parse the result
- let stacksData;
- try {
- // Handle if the result is already parsed JSON or a string that needs parsing
- if (typeof updatedTask.task.result === 'object') {
- stacksData = updatedTask.task.result;
- } else if (typeof updatedTask.task.result === 'string') {
- stacksData = JSON.parse(updatedTask.task.result);
- }
-
- // Handle if the output is nested in a result.output field
- // Add null check for updatedTask.task.result before accessing .output
- if (!stacksData && updatedTask.task.result && updatedTask.task.result.output) {
- if (typeof updatedTask.task.result.output === 'object') {
- stacksData = updatedTask.task.result.output;
- } else if (typeof updatedTask.task.result.output === 'string') {
- stacksData = JSON.parse(updatedTask.task.result.output);
- }
- }
- } catch (parseError) {
- console.error(`Failed to parse stack data: ${parseError}`);
- return [];
- }
-
- if (!stacksData || !stacksData.stacks || !Array.isArray(stacksData.stacks)) {
- console.log(`No valid stacks data found in task result`);
- return [];
- }
-
- // Convert agent stacks to AgentStack format
- const stacks: AgentStack[] = stacksData.stacks.map((stack: Stack) => ({
- ...stack,
- agentId: agent.id,
- agentHostname: agent.hostname,
- isRemote: true,
- // Ensure the important fields are always set
- id: stack.id || `${agent.id}_${stack.name}`,
- name: stack.name,
- status: stack.status || 'unknown',
- serviceCount: stack.serviceCount || stack.services?.length || 0
- }));
-
- console.log(`Retrieved ${stacks.length} stacks from agent ${agent.hostname}`);
- return stacks;
- } else if (taskStatus === 'failed') {
- console.error(`Task failed: ${updatedTask.task.error || 'Unknown error'}`);
- return [];
- }
- // Continue polling if task is still pending or running
- }
-
- console.error(`Polling timed out after ${maxAttempts} seconds`);
- return [];
- } catch (error) {
- console.error(`Failed to get stacks from agent ${agent.hostname}:`, error);
- return [];
- }
-}
-
-export async function getAllAgentStacks(agents: Agent[], context?: ServerFetchContext): Promise<AgentStack[]> {
- const agentStacks: AgentStack[] = [];
-
- for (const agent of agents) {
- try {
- const stacks = await getStacksFromAgent(agent, context);
- agentStacks.push(...stacks);
- } catch (error) {
- console.error(`Failed to get stacks from agent ${agent.hostname}:`, error);
- }
- }
-
- return agentStacks;
-}
-
-/**
- * Get all stacks managed by agents
- */
-export async function listAgentStacks(): Promise<AgentStack[]> {
- try {
- return await agentStackAPI.list();
- } catch (error) {
- console.error('Failed to list agent stacks:', error);
- return [];
- }
-}
-
-/**
- * Get stacks for a specific agent
- */
-export async function getAgentStacks(agentId: string): Promise<AgentStack[]> {
- try {
- return await agentStackAPI.listByAgent(agentId);
- } catch (error) {
- console.error('Failed to get agent stacks:', error);
- return [];
- }
-}
-
-/**
- * Get a specific stack by ID
- */
-export async function getAgentStack(stackId: string): Promise<AgentStack | null> {
- try {
- return await agentStackAPI.get(stackId);
- } catch (error) {
- console.error('Failed to get agent stack:', error);
- return null;
- }
-}
-
-/**
- * Deploy a stack to an agent
- */
-export async function deployAgentStack(
- agentId: string,
- stackData: {
- name: string;
- composeContent: string;
- envContent?: string;
- description?: string;
- }
-): Promise<AgentStack> {
- try {
- return await agentStackAPI.deploy(agentId, stackData);
- } catch (error) {
- console.error('Failed to deploy agent stack:', error);
- throw error;
- }
-}
-
-/**
- * Update a stack configuration
- */
-export async function updateAgentStack(
- stackId: string,
- updates: {
- composeContent?: string;
- envContent?: string;
- description?: string;
- }
-): Promise<AgentStack> {
- try {
- return await agentStackAPI.update(stackId, updates);
- } catch (error) {
- console.error('Failed to update agent stack:', error);
- throw error;
- }
-}
-
-/**
- * Start a stack
- */
-export async function startAgentStack(stackId: string): Promise<void> {
- try {
- await agentStackAPI.start(stackId);
- } catch (error) {
- console.error('Failed to start agent stack:', error);
- throw error;
- }
-}
-
-/**
- * Stop a stack
- */
-export async function stopAgentStack(stackId: string): Promise<void> {
- try {
- await agentStackAPI.stop(stackId);
- } catch (error) {
- console.error('Failed to stop agent stack:', error);
- throw error;
- }
-}
-
-/**
- * Restart a stack
- */
-export async function restartAgentStack(stackId: string): Promise<void> {
- try {
- await agentStackAPI.restart(stackId);
- } catch (error) {
- console.error('Failed to restart agent stack:', error);
- throw error;
- }
-}
-
-/**
- * Remove/delete a stack
- */
-export async function removeAgentStack(stackId: string, removeVolumes = false): Promise<void> {
- try {
- await agentStackAPI.remove(stackId, removeVolumes);
- } catch (error) {
- console.error('Failed to remove agent stack:', error);
- throw error;
- }
-}
-
-/**
- * Get stack logs
- */
-export async function getAgentStackLogs(
- stackId: string,
- options?: {
- tail?: number;
- since?: string;
- follow?: boolean;
- }
-): Promise<string> {
- try {
- return await agentStackAPI.getLogs(stackId, options);
- } catch (error) {
- console.error('Failed to get agent stack logs:', error);
- return '';
- }
-}
-
-/**
- * Get stack status and health
- */
-export async function getAgentStackStatus(stackId: string): Promise<StackStatus | null> {
- try {
- return await agentStackAPI.getStatus(stackId);
- } catch (error) {
- console.error('Failed to get agent stack status:', error);
- return null;
- }
-}
-
-/**
- * Pull latest images for a stack
- */
-export async function pullAgentStackImages(stackId: string): Promise<void> {
- try {
- await agentStackAPI.pullImages(stackId);
- } catch (error) {
- console.error('Failed to pull agent stack images:', error);
- throw error;
- }
-}
-
-/**
- * Get stack resource usage (CPU, memory, etc.)
- */
-export async function getAgentStackResources(stackId: string): Promise<any> {
- try {
- return await agentStackAPI.getResources(stackId);
- } catch (error) {
- console.error('Failed to get agent stack resources:', error);
- return null;
- }
-}
-
-/**
- * Scale a service within a stack
- */
-export async function scaleAgentStackService(stackId: string, serviceName: string, replicas: number): Promise<void> {
- try {
- await agentStackAPI.scaleService(stackId, serviceName, replicas);
- } catch (error) {
- console.error('Failed to scale agent stack service:', error);
- throw error;
- }
-}
diff --git a/frontend/src/lib/services/api/agent-api-service.ts b/frontend/src/lib/services/api/agent-api-service.ts
deleted file mode 100644
index 579bf57ae..000000000
--- a/frontend/src/lib/services/api/agent-api-service.ts
+++ /dev/null
@@ -1,311 +0,0 @@
-import BaseAPIService from './api-service';
-import type { Agent, AgentTask } from '$lib/types/agent.type';
-
-export interface CreateTaskRequest {
- type: string;
- payload: any;
-}
-
-export interface UpdateTaskStatusRequest {
- status: string;
- result?: any;
- error?: string;
-}
-
-export interface AgentMetrics {
- containerCount?: number;
- imageCount?: number;
- stackCount?: number;
- networkCount?: number;
- volumeCount?: number;
-}
-
-export interface DockerInfo {
- version?: string;
- containers?: number;
- images?: number;
-}
-
-export default class AgentAPIService extends BaseAPIService {
- // ===== AGENT MANAGEMENT =====
-
- /**
- * Register a new agent
- */
- async register(agent: Agent): Promise<Agent> {
- return this.handleResponse(this.api.post('/agents/register', agent));
- }
-
- /**
- * Get agent by ID
- */
- async get(agentId: string): Promise<Agent> {
- return this.handleResponse(this.api.get(`/agents/${agentId}`));
- }
-
- /**
- * Update agent information
- */
- async update(agentId: string, updates: Partial<Agent>): Promise<Agent> {
- return this.handleResponse(this.api.put(`/agents/${agentId}`, updates));
- }
-
- /**
- * List all agents
- */
- async list(): Promise<Agent[]> {
- return this.handleResponse(this.api.get('/agents'));
- }
-
- /**
- * Delete an agent
- */
- async delete(agentId: string): Promise<void> {
- return this.handleResponse(this.api.delete(`/agents/${agentId}`));
- }
-
- /**
- * Update agent heartbeat
- */
- async heartbeat(agentId: string): Promise<void> {
- return this.handleResponse(this.api.post(`/agents/${agentId}/heartbeat`));
- }
-
- /**
- * Update agent metrics
- */
- async updateMetrics(agentId: string, metrics: AgentMetrics): Promise<void> {
- return this.handleResponse(this.api.put(`/agents/${agentId}/metrics`, metrics));
- }
-
- /**
- * Update agent Docker information
- */
- async updateDockerInfo(agentId: string, dockerInfo: DockerInfo): Promise<void> {
- return this.handleResponse(this.api.put(`/agents/${agentId}/docker-info`, dockerInfo));
- }
-
- // ===== TASK MANAGEMENT =====
-
- /**
- * Create a new task for an agent
- */
- async createTask(agentId: string, taskData: CreateTaskRequest): Promise<AgentTask> {
- return this.handleResponse(this.api.post(`/agents/${agentId}/tasks`, taskData));
- }
-
- /**
- * Get a specific task by ID
- */
- async getTask(taskId: string): Promise<AgentTask> {
- return this.handleResponse(this.api.get(`/tasks/${taskId}`));
- }
-
- /**
- * Update task status
- */
- async updateTaskStatus(taskId: string, statusData: UpdateTaskStatusRequest): Promise<void> {
- return this.handleResponse(this.api.put(`/tasks/${taskId}/status`, statusData));
- }
-
- /**
- * List tasks for a specific agent
- */
- async listTasks(agentId: string): Promise<AgentTask[]> {
- return this.handleResponse(this.api.get(`/agents/${agentId}/tasks`));
- }
-
- /**
- * List all tasks across all agents
- */
- async listAllTasks(): Promise<AgentTask[]> {
- return this.handleResponse(this.api.get('/tasks'));
- }
-
- /**
- * Get pending tasks for an agent
- */
- async getPendingTasks(agentId: string): Promise<AgentTask[]> {
- return this.handleResponse(this.api.get(`/agents/${agentId}/tasks/pending`));
- }
-
- /**
- * Cancel a task
- */
- async cancelTask(taskId: string): Promise<void> {
- return this.handleResponse(this.api.post(`/tasks/${taskId}/cancel`));
- }
-
- /**
- * Delete a task
- */
- async deleteTask(taskId: string): Promise<void> {
- return this.handleResponse(this.api.delete(`/tasks/${taskId}`));
- }
-
- /**
- * Get task logs
- */
- async getTaskLogs(taskId: string): Promise<string> {
- return this.handleResponse(this.api.get(`/tasks/${taskId}/logs`));
- }
-
- // ===== AGENT STATISTICS =====
-
- /**
- * Get agent statistics
- */
- async getAgentStats(agentId: string): Promise<{
- containerCount: number;
- imageCount: number;
- stackCount: number;
- networkCount: number;
- volumeCount: number;
- cpuUsage?: number;
- memoryUsage?: number;
- diskUsage?: number;
- }> {
- return this.handleResponse(this.api.get(`/agents/${agentId}/stats`));
- }
-
- /**
- * Get overall system statistics
- */
- async getSystemStats(): Promise<{
- totalAgents: number;
- onlineAgents: number;
- offlineAgents: number;
- totalTasks: number;
- pendingTasks: number;
- runningTasks: number;
- completedTasks: number;
- failedTasks: number;
- }> {
- return this.handleResponse(this.api.get('/agents/stats'));
- }
-
- // ===== DOCKER OPERATIONS =====
-
- /**
- * Execute Docker command on agent
- */
- async executeDockerCommand(agentId: string, command: string, args: string[] = []): Promise<AgentTask> {
- return this.createTask(agentId, {
- type: 'docker_command',
- payload: { command, args }
- });
- }
-
- /**
- * Pull Docker image on agent
- */
- async pullImage(agentId: string, imageName: string): Promise<AgentTask> {
- return this.createTask(agentId, {
- type: 'image_pull',
- payload: { imageName }
- });
- }
-
- /**
- * Deploy stack on agent
- */
- async deployStack(agentId: string, stackId: string, composeContent: string, envContent?: string): Promise<AgentTask> {
- return this.createTask(agentId, {
- type: 'stack_deploy',
- payload: { stackId, composeContent, envContent }
- });
- }
-
- /**
- * Health check agent
- */
- async healthCheck(agentId: string): Promise<AgentTask> {
- return this.createTask(agentId, {
- type: 'health_check',
- payload: {}
- });
- }
-
- /**
- * Upgrade agent
- */
- async upgradeAgent(agentId: string, version = 'latest'): Promise<AgentTask> {
- return this.createTask(agentId, {
- type: 'agent_upgrade',
- payload: { version }
- });
- }
-
- // ===== REAL-TIME OPERATIONS =====
-
- /**
- * Process agent message (for WebSocket communication)
- */
- async processMessage(agentId: string, message: any): Promise<void> {
- return this.handleResponse(this.api.post(`/agents/${agentId}/messages`, message));
- }
-
- /**
- * Get agent logs
- */
- async getAgentLogs(
- agentId: string,
- options?: {
- tail?: number;
- since?: string;
- follow?: boolean;
- }
- ): Promise<string> {
- const params = new URLSearchParams();
- if (options?.tail) params.append('tail', options.tail.toString());
- if (options?.since) params.append('since', options.since);
- if (options?.follow) params.append('follow', options.follow.toString());
-
- const query = params.toString() ? `?${params.toString()}` : '';
- return this.handleResponse(this.api.get(`/agents/${agentId}/logs${query}`));
- }
-
- // ===== AGENT CONFIGURATION =====
-
- /**
- * Get agent configuration
- */
- async getAgentConfig(agentId: string): Promise<any> {
- return this.handleResponse(this.api.get(`/agents/${agentId}/config`));
- }
-
- /**
- * Update agent configuration
- */
- async updateAgentConfig(agentId: string, config: any): Promise<void> {
- return this.handleResponse(this.api.put(`/agents/${agentId}/config`, config));
- }
-
- // ===== BULK OPERATIONS =====
-
- /**
- * Bulk update multiple agents
- */
- async bulkUpdate(updates: Array<{ agentId: string; data: Partial<Agent> }>): Promise<Agent[]> {
- return this.handleResponse(this.api.put('/agents/bulk', { updates }));
- }
-
- /**
- * Bulk delete multiple agents
- */
- async bulkDelete(agentIds: string[]): Promise<void> {
- return this.handleResponse(this.api.delete('/agents/bulk', { data: { agentIds } }));
- }
-
- /**
- * Send task to multiple agents
- */
- async bulkCreateTasks(agentIds: string[], taskData: CreateTaskRequest): Promise<AgentTask[]> {
- return this.handleResponse(
- this.api.post('/agents/bulk/tasks', {
- agentIds,
- taskData
- })
- );
- }
-}
diff --git a/frontend/src/lib/services/api/agent-stack-api-service.ts b/frontend/src/lib/services/api/agent-stack-api-service.ts
deleted file mode 100644
index df53882d1..000000000
--- a/frontend/src/lib/services/api/agent-stack-api-service.ts
+++ /dev/null
@@ -1,203 +0,0 @@
-import BaseAPIService from './api-service';
-import type { AgentStack, StackStatus } from '$lib/types/agent.type';
-
-export interface DeployStackRequest {
- name: string;
- composeContent: string;
- envContent?: string;
- description?: string;
-}
-
-export interface UpdateStackRequest {
- composeContent?: string;
- envContent?: string;
- description?: string;
-}
-
-export interface StackLogsOptions {
- tail?: number;
- since?: string;
- follow?: boolean;
-}
-
-export default class AgentStackAPIService extends BaseAPIService {
- /**
- * List all stacks across all agents
- */
- async list(): Promise<AgentStack[]> {
- return this.handleResponse(this.api.get('/agent-stacks'));
- }
-
- /**
- * List stacks for a specific agent
- */
- async listByAgent(agentId: string): Promise<AgentStack[]> {
- return this.handleResponse(this.api.get(`/agents/${agentId}/stacks`));
- }
-
- /**
- * Get a specific stack by ID
- */
- async get(stackId: string): Promise<AgentStack> {
- return this.handleResponse(this.api.get(`/agent-stacks/${stackId}`));
- }
-
- /**
- * Deploy a new stack to an agent
- */
- async deploy(agentId: string, stackData: DeployStackRequest): Promise<AgentStack> {
- return this.handleResponse(this.api.post(`/agents/${agentId}/stacks`, stackData));
- }
-
- /**
- * Update a stack configuration
- */
- async update(stackId: string, updates: UpdateStackRequest): Promise<AgentStack> {
- return this.handleResponse(this.api.put(`/agent-stacks/${stackId}`, updates));
- }
-
- /**
- * Start a stack
- */
- async start(stackId: string): Promise<void> {
- return this.handleResponse(this.api.post(`/agent-stacks/${stackId}/start`));
- }
-
- /**
- * Stop a stack
- */
- async stop(stackId: string): Promise<void> {
- return this.handleResponse(this.api.post(`/agent-stacks/${stackId}/stop`));
- }
-
- /**
- * Restart a stack
- */
- async restart(stackId: string): Promise<void> {
- return this.handleResponse(this.api.post(`/agent-stacks/${stackId}/restart`));
- }
-
- /**
- * Remove/delete a stack
- */
- async remove(stackId: string, removeVolumes = false): Promise<void> {
- return this.handleResponse(this.api.delete(`/agent-stacks/${stackId}?removeVolumes=${removeVolumes}`));
- }
-
- /**
- * Get stack logs
- */
- async getLogs(stackId: string, options?: StackLogsOptions): Promise<string> {
- const params = new URLSearchParams();
- if (options?.tail) params.append('tail', options.tail.toString());
- if (options?.since) params.append('since', options.since);
- if (options?.follow) params.append('follow', options.follow.toString());
-
- const query = params.toString() ? `?${params.toString()}` : '';
- return this.handleResponse(this.api.get(`/agent-stacks/${stackId}/logs${query}`));
- }
-
- /**
- * Get stack status and health
- */
- async getStatus(stackId: string): Promise<StackStatus> {
- return this.handleResponse(this.api.get(`/agent-stacks/${stackId}/status`));
- }
-
- /**
- * Pull latest images for a stack
- */
- async pullImages(stackId: string): Promise<void> {
- return this.handleResponse(this.api.post(`/agent-stacks/${stackId}/pull`));
- }
-
- /**
- * Get stack resource usage
- */
- async getResources(stackId: string): Promise<{
- cpuUsage: number;
- memoryUsage: number;
- networkIO: { rx: number; tx: number };
- blockIO: { read: number; write: number };
- containers: Array<{
- name: string;
- cpuUsage: number;
- memoryUsage: number;
- status: string;
- }>;
- }> {
- return this.handleResponse(this.api.get(`/agent-stacks/${stackId}/resources`));
- }
-
- /**
- * Scale a service within a stack
- */
- async scaleService(stackId: string, serviceName: string, replicas: number): Promise<void> {
- return this.handleResponse(
- this.api.post(`/agent-stacks/${stackId}/services/${serviceName}/scale`, {
- replicas
- })
- );
- }
-
- /**
- * Get stack services
- */
- async getServices(stackId: string): Promise<
- Array<{
- name: string;
- image: string;
- status: string;
- replicas: number;
- ports: string[];
- }>
- > {
- return this.handleResponse(this.api.get(`/agent-stacks/${stackId}/services`));
- }
-
- /**
- * Get service logs
- */
- async getServiceLogs(stackId: string, serviceName: string, options?: StackLogsOptions): Promise<string> {
- const params = new URLSearchParams();
- if (options?.tail) params.append('tail', options.tail.toString());
- if (options?.since) params.append('since', options.since);
- if (options?.follow) params.append('follow', options.follow.toString());
-
- const query = params.toString() ? `?${params.toString()}` : '';
- return this.handleResponse(this.api.get(`/agent-stacks/${stackId}/services/${serviceName}/logs${query}`));
- }
-
- /**
- * Update stack environment variables
- */
- async updateEnvironment(stackId: string, envContent: string): Promise<void> {
- return this.handleResponse(
- this.api.put(`/agent-stacks/${stackId}/environment`, {
- envContent
- })
- );
- }
-
- /**
- * Get stack environment variables
- */
- async getEnvironment(stackId: string): Promise<string> {
- return this.handleResponse(this.api.get(`/agent-stacks/${stackId}/environment`));
- }
-
- /**
- * Validate stack compose file
- */
- async validateCompose(composeContent: string): Promise<{
- valid: boolean;
- errors?: string[];
- warnings?: string[];
- }> {
- return this.handleResponse(
- this.api.post('/agent-stacks/validate', {
- composeContent
- })
- );
- }
-}
diff --git a/frontend/src/lib/services/api/container-api-service.ts b/frontend/src/lib/services/api/container-api-service.ts
deleted file mode 100644
index 67f4009d9..000000000
--- a/frontend/src/lib/services/api/container-api-service.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import BaseAPIService from './api-service';
-
-export interface CreateContainerRequest {
- name: string;
- image: string;
- command?: string[];
- entrypoint?: string[];
- workingDir?: string;
- user?: string;
- environment?: string[];
- ports?: Record<string, string>;
- volumes?: string[];
- networks?: string[];
- restartPolicy?: 'no' | 'always' | 'unless-stopped' | 'on-failure';
- privileged?: boolean;
- autoRemove?: boolean;
- memory?: number;
- cpus?: number;
-}
-
-export default class ContainerAPIService extends BaseAPIService {
- async list(all: boolean = false) {
- return this.handleResponse(this.api.get('/containers', { params: { all } }));
- }
-
- async get(id: string) {
- return this.handleResponse(this.api.get(`/containers/${id}`));
- }
-
- async create(options: CreateContainerRequest) {
- return this.handleResponse(this.api.post('/containers', options));
- }
-
- async inspect(id: string) {
- return this.handleResponse(this.api.get(`/containers/${id}`));
- }
-
- async start(id: string) {
- return this.handleResponse(this.api.post(`/containers/${id}/start`));
- }
-
- async stop(id: string) {
- return this.handleResponse(this.api.post(`/containers/${id}/stop`));
- }
-
- async restart(id: string) {
- return this.handleResponse(this.api.post(`/containers/${id}/restart`));
- }
-
- async remove(id: string, options?: { force?: boolean; volumes?: boolean }) {
- return this.handleResponse(
- this.api.delete(`/containers/${id}`, {
- params: options
- })
- );
- }
-
- async logs(
- id: string,
- options?: {
- tail?: number;
- timestamps?: boolean;
- follow?: boolean;
- since?: string;
- until?: string;
- }
- ) {
- return this.handleResponse(
- this.api.get(`/containers/${id}/logs`, {
- params: options
- })
- );
- }
-
- async stats(id: string, stream: boolean = false) {
- return this.handleResponse(
- this.api.get(`/containers/${id}/stats`, {
- params: { stream }
- })
- );
- }
-
- async isImageInUse(imageId: string): Promise<boolean> {
- const response = await this.api.get(`/containers/image-usage/${imageId}`);
- return response.data.inUse;
- }
-
- async prune(filters?: Record<string, string>) {
- return this.handleResponse(this.api.post('/containers/prune', { filters }));
- }
-
- async exec(id: string, command: string[]) {
- return this.handleResponse(
- this.api.post(`/containers/${id}/exec`, {
- command
- })
- );
- }
-}
diff --git a/frontend/src/lib/services/api/deployment-api-service.ts b/frontend/src/lib/services/api/deployment-api-service.ts
deleted file mode 100644
index 67ae9b63f..000000000
--- a/frontend/src/lib/services/api/deployment-api-service.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import BaseAPIService from './api-service';
-import type { Deployment } from '$lib/types/deployment.type';
-
-export interface CreateDeploymentRequest {
- name: string;
- type: 'stack' | 'container' | 'image';
- status: 'pending' | 'running' | 'stopped' | 'failed' | 'completed';
- agentId: string;
- taskId?: string;
- metadata?: Record<string, any>;
-}
-
-export interface UpdateDeploymentRequest {
- name?: string;
- status?: 'pending' | 'running' | 'stopped' | 'failed' | 'completed';
- error?: string;
- metadata?: Record<string, any>;
-}
-
-export interface CreateStackDeploymentRequest {
- agentId: string;
- stackName: string;
- composeContent: string;
- envContent?: string;
- taskId?: string;
-}
-
-export interface CreateContainerDeploymentRequest {
- agentId: string;
- containerName: string;
- imageName: string;
- ports?: string[];
- volumes?: string[];
- taskId?: string;
-}
-
-export interface CreateImageDeploymentRequest {
- agentId: string;
- imageName: string;
- taskId?: string;
-}
-
-export default class DeploymentAPIService extends BaseAPIService {
- /**
- * Create a new deployment
- */
- async create(deployment: CreateDeploymentRequest): Promise<Deployment> {
- return this.handleResponse(this.api.post('/deployments', deployment));
- }
-
- /**
- * Get a deployment by ID
- */
- async get(deploymentId: string): Promise<Deployment> {
- return this.handleResponse(this.api.get(`/deployments/${deploymentId}`));
- }
-
- /**
- * List deployments, optionally filtered by agent
- */
- async list(agentId?: string): Promise<Deployment[]> {
- const params = agentId ? `?agentId=${encodeURIComponent(agentId)}` : '';
- return this.handleResponse(this.api.get(`/deployments${params}`));
- }
-
- /**
- * Update a deployment
- */
- async update(deploymentId: string, updates: UpdateDeploymentRequest): Promise<Deployment> {
- return this.handleResponse(this.api.put(`/deployments/${deploymentId}`, updates));
- }
-
- /**
- * Delete a deployment
- */
- async delete(deploymentId: string): Promise<void> {
- return this.handleResponse(this.api.delete(`/deployments/${deploymentId}`));
- }
-
- /**
- * Update deployment status
- */
- async updateStatus(deploymentId: string, status: string, error?: string): Promise<void> {
- return this.handleResponse(
- this.api.put(`/deployments/${deploymentId}/status`, {
- status,
- error
- })
- );
- }
-
- /**
- * Get deployment by task ID
- */
- async getByTaskId(taskId: string): Promise<Deployment | null> {
- try {
- return this.handleResponse(this.api.get(`/deployments/by-task/${taskId}`));
- } catch (error: unknown) {
- // Return null if not found instead of throwing
- if (typeof error === 'object' && error !== null && 'response' in error && typeof (error as any).response === 'object' && (error as any).response?.status === 404) {
- return null;
- }
- throw error;
- }
- }
-
- /**
- * Create a stack deployment
- */
- async createStackDeployment(data: CreateStackDeploymentRequest): Promise<Deployment> {
- return this.handleResponse(this.api.post('/deployments/stack', data));
- }
-
- /**
- * Create a container deployment
- */
- async createContainerDeployment(data: CreateContainerDeploymentRequest): Promise<Deployment> {
- return this.handleResponse(this.api.post('/deployments/container', data));
- }
-
- /**
- * Create an image deployment
- */
- async createImageDeployment(data: CreateImageDeploymentRequest): Promise<Deployment> {
- return this.handleResponse(this.api.post('/deployments/image', data));
- }
-
- /**
- * Get deployments by agent
- */
- async getByAgent(agentId: string): Promise<Deployment[]> {
- return this.handleResponse(this.api.get(`/agents/${agentId}/deployments`));
- }
-
- /**
- * Get deployment logs
- */
- async getLogs(deploymentId: string): Promise<string> {
- return this.handleResponse(this.api.get(`/deployments/${deploymentId}/logs`));
- }
-
- /**
- * Get deployment statistics
- */
- async getStats(): Promise<{
- total: number;
- pending: number;
- running: number;
- completed: number;
- failed: number;
- byAgent: Record<string, number>;
- byType: Record<string, number>;
- }> {
- return this.handleResponse(this.api.get('/deployments/stats'));
- }
-}
diff --git a/frontend/src/lib/services/api/encryption-api-service.ts b/frontend/src/lib/services/api/encryption-api-service.ts
deleted file mode 100644
index f2502a289..000000000
--- a/frontend/src/lib/services/api/encryption-api-service.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import BaseAPIService from './api-service';
-
-export default class EncryptionAPIService extends BaseAPIService {
- async encrypt(data: any): Promise<string> {
- const response = await this.api.post('/encrypt', { data });
- return response.data.encrypted;
- }
-
- async decrypt(encryptedData: string): Promise<any> {
- const response = await this.api.post('/decrypt', { encrypted: encryptedData });
- return response.data.data;
- }
-}
diff --git a/frontend/src/lib/services/api/environment-api-service.ts b/frontend/src/lib/services/api/environment-api-service.ts
new file mode 100644
index 000000000..ba416355b
--- /dev/null
+++ b/frontend/src/lib/services/api/environment-api-service.ts
@@ -0,0 +1,318 @@
+import BaseAPIService from './api-service';
+import { get } from 'svelte/store';
+import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '$lib/stores/environment.store';
+import type { ContainerCreateOptions, NetworkCreateOptions, VolumeCreateOptions } from 'dockerode';
+import type { Stack, StackService } from '$lib/models/stack.type';
+
+import { browser } from '$app/environment';
+
+export class EnvironmentAPIService extends BaseAPIService {
+ private async getCurrentEnvironmentId(): Promise<string> {
+ if (browser) {
+ await environmentStore.ready;
+ }
+ const currentEnvironment = get(environmentStore.selected);
+ if (!currentEnvironment) {
+ return LOCAL_DOCKER_ENVIRONMENT_ID;
+ }
+ return currentEnvironment.id;
+ }
+
+ async getContainers(): Promise<any[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ const response = await this.handleResponse<{ containers?: any[] }>(this.api.get(`/environments/${envId}/containers`));
+ return Array.isArray(response.containers) ? response.containers : Array.isArray(response) ? response : [];
+ }
+
+ async getContainer(containerId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/containers/${containerId}`));
+ }
+
+ async startContainer(containerId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/start`));
+ }
+
+ async createContainer(options: ContainerCreateOptions): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/containers`, options));
+ }
+
+ async getContainerStats(containerId: string, stream: boolean = false) {
+ const envId = await this.getCurrentEnvironmentId();
+ const url = `/environments/${envId}/containers/${containerId}/stats${stream ? '?stream=true' : ''}`;
+ return this.handleResponse(this.api.get(url));
+ }
+
+ async stopContainer(containerId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/stop`));
+ }
+
+ async restartContainer(containerId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/restart`));
+ }
+
+ async deleteContainer(containerId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.delete(`/environments/${envId}/containers/${containerId}`));
+ }
+
+ async pullContainerImage(containerId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/pull`));
+ }
+
+ async getImages(): Promise<any[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ const response = await this.handleResponse<{ images?: any[] }>(this.api.get(`/environments/${envId}/images`));
+ return Array.isArray(response.images) ? response.images : Array.isArray(response) ? response : [];
+ }
+
+ async getImage(imageId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}`));
+ }
+
+ async getNetworks(): Promise<any[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ const response = await this.handleResponse<{ networks?: any[] }>(this.api.get(`/environments/${envId}/networks`));
+ return Array.isArray(response.networks) ? response.networks : Array.isArray(response) ? response : [];
+ }
+
+ async getNetwork(networkId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/networks/${networkId}`));
+ }
+
+ async createNetwork(options: NetworkCreateOptions): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/networks`, options));
+ }
+
+ async deleteNetwork(networkId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.delete(`/environments/${envId}/networks/${networkId}`));
+ }
+
+ async getVolumes(): Promise<any[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ const response = await this.handleResponse<{ volumes?: any[] }>(this.api.get(`/environments/${envId}/volumes`));
+ return Array.isArray(response.volumes) ? response.volumes : Array.isArray(response) ? response : [];
+ }
+
+ async getVolume(volumeName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}`));
+ }
+
+ async getVolumeUsage(volumeName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}/usage`));
+ }
+
+ async createVolume(options: VolumeCreateOptions): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/volumes`, options));
+ }
+
+ async deleteVolume(volumeName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.delete(`/environments/${envId}/volumes/${volumeName}`));
+ }
+
+ async pruneVolumes(): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/volumes/prune`));
+ }
+
+ async getAllResources(): Promise<Record<string, any>> {
+ const envId = await this.getCurrentEnvironmentId();
+ const [containers, images, networks, volumes] = await Promise.all([this.getContainers(), this.getImages(), this.getNetworks(), this.getVolumes()]);
+
+ return {
+ containers,
+ images,
+ networks,
+ volumes
+ };
+ }
+
+ async syncResources(): Promise<void> {
+ const envId = await this.getCurrentEnvironmentId();
+ await this.handleResponse(this.api.post(`/environments/${envId}/sync`));
+ }
+
+ async executeDockerCommand(command: string, args: string[] = []): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/execute`, { command, args }));
+ }
+
+ async getStacks(): Promise<Stack[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ const response = await this.handleResponse<{ stacks?: Stack[] }>(this.api.get(`/environments/${envId}/stacks`));
+ return Array.isArray(response.stacks) ? response.stacks : Array.isArray(response) ? response : [];
+ }
+
+ async getStack(stackName: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ const response = await this.handleResponse<{ stack?: Stack; success?: boolean }>(this.api.get(`/environments/${envId}/stacks/${stackName}`));
+
+ if (response.stack) {
+ return response.stack;
+ }
+
+ return response as Stack;
+ }
+
+ async deployStack(stackName: string, composeContent: string, envContent?: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ const payload = {
+ name: stackName,
+ composeContent,
+ envContent
+ };
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks`, payload));
+ }
+
+ async updateStack(stackName: string, composeContent: string, envContent?: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ const payload = {
+ composeContent,
+ envContent
+ };
+ return this.handleResponse(this.api.put(`/environments/${envId}/stacks/${stackName}`, payload));
+ }
+
+ async deleteStack(stackName: string): Promise<void> {
+ const envId = await this.getCurrentEnvironmentId();
+ await this.handleResponse(this.api.delete(`/environments/${envId}/stacks/${stackName}`));
+ }
+
+ async startStack(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/start`));
+ }
+
+ async stopStack(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/stop`));
+ }
+
+ async restartStack(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/restart`));
+ }
+
+ async getStackLogs(stackId: string): Promise<string> {
+ const envId = await this.getCurrentEnvironmentId();
+ const response = await this.handleResponse<{ logs?: string }>(this.api.get(`/environments/${envId}/stacks/${stackId}/logs`));
+ return response.logs || '';
+ }
+
+ async deployStackWithOptions(stackId: string, options?: { profiles?: string[]; envOverrides?: Record<string, string> }): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/deploy`, options || {}));
+ }
+
+ async downStack(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/down`));
+ }
+
+ async redeployStack(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/redeploy`));
+ }
+
+ async pullStackImages(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/pull`));
+ }
+
+ async destroyStack(stackId: string, removeVolumes = false, removeFiles = false): Promise<void> {
+ const envId = await this.getCurrentEnvironmentId();
+ await this.handleResponse(
+ this.api.delete(`/environments/${envId}/stacks/${stackId}/destroy`, {
+ data: {
+ removeVolumes,
+ removeFiles
+ }
+ })
+ );
+ }
+
+ async getStackServices(stackName: string): Promise<StackService[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/services`));
+ }
+
+ async getStackProfiles(stackName: string): Promise<string[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/profiles`));
+ }
+
+ async getStackChanges(stackName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/changes`));
+ }
+
+ async getStackStats(stackName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/stats`));
+ }
+
+ async validateStack(stackName: string): Promise<{ valid: boolean; errors?: string[] }> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/validate`));
+ }
+
+ async convertDockerRun(command: string): Promise<{ composeContent: string }> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/convert`, { command }));
+ }
+
+ async discoverExternalStacks(): Promise<Stack[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/discover-external`));
+ }
+
+ async importStack(stackId: string, stackName?: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(
+ this.api.post(`/environments/${envId}/stacks/import`, {
+ stackId,
+ stackName
+ })
+ );
+ }
+
+ async migrateStack(stackName: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackName}/migrate`));
+ }
+
+ async getStackLogsStream(stackName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/logs/stream`));
+ }
+
+ async pullImage(imageName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/images/pull`, { imageName }));
+ }
+
+ async deleteImage(imageId: string, options?: { force?: boolean; noprune?: boolean }): Promise<void> {
+ const envId = await this.getCurrentEnvironmentId();
+ await this.handleResponse(this.api.delete(`/environments/${envId}/images/${imageId}`, { params: options }));
+ }
+
+ async pruneImages(): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/images/prune`));
+ }
+}
+
+export const environmentAPI = new EnvironmentAPIService();
diff --git a/frontend/src/lib/services/api/environment-management-api-service.ts b/frontend/src/lib/services/api/environment-management-api-service.ts
new file mode 100644
index 000000000..0e17eeeef
--- /dev/null
+++ b/frontend/src/lib/services/api/environment-management-api-service.ts
@@ -0,0 +1,34 @@
+import BaseAPIService from './api-service';
+import type { Environment } from '$lib/stores/environment.store';
+import type { CreateEnvironmentDTO, UpdateEnvironmentDTO, EnvironmentResponse, EnvironmentsListResponse } from '$lib/dto/environment-dto';
+
+export default class EnvironmentManagementAPIService extends BaseAPIService {
+ async create(dto: CreateEnvironmentDTO): Promise<Environment> {
+ const response = await this.handleResponse<EnvironmentResponse>(this.api.post('/environments', dto));
+ return response.environment;
+ }
+
+ async list(): Promise<Environment[]> {
+ const response = await this.handleResponse<EnvironmentsListResponse>(this.api.get('/environments'));
+ return response.environments;
+ }
+
+ async get(environmentId: string): Promise<Environment> {
+ const response = await this.handleResponse<EnvironmentResponse>(this.api.get(`/environments/${environmentId}`));
+ return response.environment;
+ }
+
+ async update(environmentId: string, dto: UpdateEnvironmentDTO): Promise<Environment> {
+ const response = await this.handleResponse<EnvironmentResponse>(this.api.put(`/environments/${environmentId}`, dto));
+ return response.environment;
+ }
+
+ async delete(environmentId: string): Promise<void> {
+ await this.handleResponse(this.api.delete(`/environments/${environmentId}`));
+ }
+
+ async testConnection(environmentId: string): Promise<{ status: 'online' | 'offline'; message?: string }> {
+ const response = await this.handleResponse<{ status: 'online' | 'offline'; message?: string }>(this.api.post(`/environments/${environmentId}/test`));
+ return response;
+ }
+}
diff --git a/frontend/src/lib/services/api/image-maturity-api-service.ts b/frontend/src/lib/services/api/image-maturity-api-service.ts
index 452ee46fe..6d7739356 100644
--- a/frontend/src/lib/services/api/image-maturity-api-service.ts
+++ b/frontend/src/lib/services/api/image-maturity-api-service.ts
@@ -1,5 +1,5 @@
import BaseAPIService from './api-service';
-import type { ImageMaturity } from '$lib/types/docker/image.type';
+import type { ImageMaturity } from '$lib/models/image.type';
export interface ImageMaturityRecord {
id: string;
diff --git a/frontend/src/lib/services/api/index.ts b/frontend/src/lib/services/api/index.ts
index de5cda632..72955c8e1 100644
--- a/frontend/src/lib/services/api/index.ts
+++ b/frontend/src/lib/services/api/index.ts
@@ -1,95 +1,65 @@
-import ContainerAPIService from './container-api-service';
import ImageAPIService from './image-api-service';
import ImageMaturityAPIService from './image-maturity-api-service';
-import VolumeAPIService from './volume-api-service';
-import NetworkAPIService from './network-api-service';
-import StackAPIService from './stack-api-service';
import SystemAPIService from './system-api-service';
import TemplateAPIService from './template-api-service';
import UserAPIService from './user-api-service';
-import SessionAPIService from './session-api-service';
import SettingsAPIService from './settings-api-service';
import TemplateRegistryAPIService from './template-registry-api-service';
import OidcAPIService from './oidc-api-service';
-import EncryptionAPIService from './encryption-api-service';
-import DeploymentAPIService from './deployment-api-service';
-import ValidationAPIService from './validation-api-service';
import AppConfigAPIService from './appconfig-api-service';
-import AgentAPIService from './agent-api-service';
-import AgentStackAPIService from './agent-stack-api-service';
import AutoUpdateAPIService from './autoupdate-api-service';
import ConverterAPIService from './converter-api-service';
import ContainerRegistryAPIService from './container-registry-api-service';
+import { EnvironmentAPIService } from './environment-api-service';
+import EnvironmentManagementAPIService from './environment-management-api-service';
-export const containerAPI = new ContainerAPIService();
export const imageAPI = new ImageAPIService();
export const imageMaturityAPI = new ImageMaturityAPIService();
-export const volumeAPI = new VolumeAPIService();
-export const networkAPI = new NetworkAPIService();
-export const stackAPI = new StackAPIService();
export const systemAPI = new SystemAPIService();
export const templateAPI = new TemplateAPIService();
export const userAPI = new UserAPIService();
-export const sessionAPI = new SessionAPIService();
export const settingsAPI = new SettingsAPIService();
export const templateRegistryAPI = new TemplateRegistryAPIService();
export const oidcAPI = new OidcAPIService();
-export const encryptionAPI = new EncryptionAPIService();
-export const deploymentAPI = new DeploymentAPIService();
-export const validationAPI = new ValidationAPIService();
export const appConfigAPI = new AppConfigAPIService();
-export const agentAPI = new AgentAPIService();
-export const agentStackAPI = new AgentStackAPIService();
export const converterAPI = new ConverterAPIService();
export const containerRegistryAPI = new ContainerRegistryAPIService();
export const autoUpdateAPI = new AutoUpdateAPIService();
+export const environmentAPI = new EnvironmentAPIService();
+export const environmentManagementAPI = new EnvironmentManagementAPIService();
interface APIServices {
- container: ContainerAPIService;
image: ImageAPIService;
imageMaturity: ImageMaturityAPIService;
- volume: VolumeAPIService;
- network: NetworkAPIService;
- stack: StackAPIService;
system: SystemAPIService;
template: TemplateAPIService;
user: UserAPIService;
- session: SessionAPIService;
settings: SettingsAPIService;
templateRegistry: TemplateRegistryAPIService;
oidc: OidcAPIService;
- encryption: EncryptionAPIService;
- deployment: DeploymentAPIService;
- validation: ValidationAPIService;
appConfig: AppConfigAPIService;
- agent: AgentAPIService;
converter: ConverterAPIService;
containerRegistry: ContainerRegistryAPIService;
autoUpdate: AutoUpdateAPIService;
+ environment: EnvironmentAPIService;
+ environmentManagement: EnvironmentManagementAPIService;
}
const apiServices: APIServices = {
- container: containerAPI,
image: imageAPI,
imageMaturity: imageMaturityAPI,
- volume: volumeAPI,
- network: networkAPI,
- stack: stackAPI,
system: systemAPI,
template: templateAPI,
user: userAPI,
- session: sessionAPI,
settings: settingsAPI,
templateRegistry: templateRegistryAPI,
oidc: oidcAPI,
- encryption: encryptionAPI,
- deployment: deploymentAPI,
- validation: validationAPI,
appConfig: appConfigAPI,
- agent: agentAPI,
converter: converterAPI,
containerRegistry: containerRegistryAPI,
- autoUpdate: autoUpdateAPI
+ autoUpdate: autoUpdateAPI,
+ environment: environmentAPI,
+ environmentManagement: environmentManagementAPI
};
export default apiServices;
diff --git a/frontend/src/lib/services/api/network-api-service.ts b/frontend/src/lib/services/api/network-api-service.ts
deleted file mode 100644
index 38e180b8b..000000000
--- a/frontend/src/lib/services/api/network-api-service.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import BaseAPIService from './api-service';
-
-export default class NetworkAPIService extends BaseAPIService {
- async list(filters?: Record<string, string>) {
- return this.handleResponse(this.api.get('/networks', { params: { filters } }));
- }
-
- async get(id: string) {
- return this.handleResponse(this.api.get(`/networks/${id}`));
- }
-
- async inspect(id: string) {
- return this.handleResponse(this.api.get(`/networks/${id}/inspect`));
- }
-
- async create(networkConfig: {
- name: string;
- driver?: string;
- options?: Record<string, string>;
- ipam?: {
- driver?: string;
- config?: Array<{
- subnet?: string;
- gateway?: string;
- ipRange?: string;
- }>;
- };
- labels?: Record<string, string>;
- enableIPv6?: boolean;
- internal?: boolean;
- attachable?: boolean;
- ingress?: boolean;
- }) {
- return this.handleResponse(this.api.post('/networks', networkConfig));
- }
-
- async remove(id: string, force: boolean = false) {
- return this.handleResponse(
- this.api.delete(`/networks/${id}`, {
- params: { force }
- })
- );
- }
-
- async connect(
- networkId: string,
- containerId: string,
- config?: {
- aliases?: string[];
- ipv4Address?: string;
- ipv6Address?: string;
- }
- ) {
- return this.handleResponse(
- this.api.post(`/networks/${networkId}/connect`, {
- container: containerId,
- endpointConfig: config
- })
- );
- }
-
- async disconnect(networkId: string, containerId: string, force: boolean = false) {
- return this.handleResponse(
- this.api.post(`/networks/${networkId}/disconnect`, {
- container: containerId,
- force
- })
- );
- }
-
- async prune(filters?: Record<string, string>) {
- return this.handleResponse(this.api.post('/networks/prune', { filters }));
- }
-}
diff --git a/frontend/src/lib/services/api/session-api-service.ts b/frontend/src/lib/services/api/session-api-service.ts
deleted file mode 100644
index 824fb35d7..000000000
--- a/frontend/src/lib/services/api/session-api-service.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { authService, type AuthSession } from './auth-api-service';
-import type { LoginRequest } from '$lib/types/session.type';
-
-export default class SessionAPIService {
- async login(credentials: LoginRequest): Promise<AuthSession> {
- return authService.login(credentials.username, credentials.password);
- }
-
- async logout(): Promise<void> {
- return authService.logout();
- }
-
- async getCurrentSession(): Promise<AuthSession | null> {
- return authService.getCurrentSession();
- }
-
- async validateSession(): Promise<boolean> {
- return authService.validateSession();
- }
-
- async refreshSession(): Promise<AuthSession | null> {
- return authService.refreshSession();
- }
-}
diff --git a/frontend/src/lib/services/api/stack-api-service.ts b/frontend/src/lib/services/api/stack-api-service.ts
deleted file mode 100644
index 815ca3684..000000000
--- a/frontend/src/lib/services/api/stack-api-service.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import BaseAPIService from './api-service';
-
-export default class StackAPIService extends BaseAPIService {
- async list() {
- const res = await this.api.get('/stacks');
- return res.data;
- }
-
- async get(id: string) {
- const res = await this.api.get(`/stacks/${id}`);
- return res.data;
- }
-
- async discoverExternal() {
- const res = await this.api.get('/stacks/discover-external');
- return res.data;
- }
-
- async create(data: { name: string; composeContent: string; envContent?: string; agentId?: string }) {
- const response = await this.api.post('/stacks', {
- name: data.name,
- composeContent: data.composeContent,
- envContent: data.envContent || '',
- agentId: data.agentId
- });
- return response.data;
- }
-
- async save(id: string, name: string, content: string, envContent?: string) {
- const res = await this.api.put(`/stacks/${id}`, {
- name,
- composeContent: content,
- envContent
- });
- return res.data;
- }
-
- async deploy(id: string, options?: { profiles?: string[]; envOverrides?: Record<string, string> }) {
- const res = await this.api.post(`/stacks/${id}/deploy`, options || {});
- return res.data;
- }
-
- async down(id: string) {
- const res = await this.api.post(`/stacks/${id}/down`);
- return res.data;
- }
-
- async restart(id: string) {
- const res = await this.api.post(`/stacks/${id}/restart`);
- return res.data;
- }
-
- async redeploy(id: string) {
- const res = await this.api.post(`/stacks/${id}/redeploy`);
- return res.data;
- }
-
- async pull(id: string) {
- const res = await this.api.post(`/stacks/${id}/pull`);
- return res.data;
- }
-
- async destroy(id: string, removeVolumes = false, removeFiles = false) {
- const res = await this.api.delete(`/stacks/${id}/destroy`, {
- data: {
- removeVolumes,
- removeFiles
- }
- });
- return res.data;
- }
-
- async import(id: string, name: string) {
- const res = await this.api.post('/stacks/import', {
- stackId: id,
- stackName: name || undefined
- });
- return res.data;
- }
-
- async migrate(id: string) {
- const res = await this.api.post(`/stacks/${id}/migrate`);
- return res.data;
- }
-
- async validate(id: string) {
- const res = await this.api.get(`/stacks/${id}/validate`);
- return res.data;
- }
-
- async getLogs(id: string, options?: { tail?: number; timestamps?: boolean; follow?: boolean }) {
- const params = new URLSearchParams();
- if (options?.tail) params.append('tail', options.tail.toString());
- if (options?.timestamps !== undefined) params.append('timestamps', options.timestamps.toString());
- if (options?.follow !== undefined) params.append('follow', options.follow.toString());
-
- const url = `/stacks/${id}/logs${params.toString() ? '?' + params.toString() : ''}`;
- const res = await this.api.get(url);
- return res.data;
- }
-
- async getProfiles(id: string) {
- const res = await this.api.get(`/stacks/${id}/profiles`);
- return res.data;
- }
-
- async getChanges(id: string) {
- const res = await this.api.get(`/stacks/${id}/changes`);
- return res.data;
- }
-
- async getStats(id: string) {
- const res = await this.api.get(`/stacks/${id}/stats`);
- return res.data;
- }
-}
diff --git a/frontend/src/lib/services/api/validation-api-service.ts b/frontend/src/lib/services/api/validation-api-service.ts
deleted file mode 100644
index e5c3e9ac0..000000000
--- a/frontend/src/lib/services/api/validation-api-service.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import BaseAPIService from './api-service';
-import type { ValidationResult } from '$lib/types/validation.type';
-
-export default class ValidationAPIService extends BaseAPIService {
- async validateDockerCompose(content: string): Promise<ValidationResult> {
- return this.handleResponse(this.api.post('/validate/docker-compose', { content }));
- }
-
- async validateEnvironmentFile(content: string): Promise<ValidationResult> {
- return this.handleResponse(this.api.post('/validate/env-file', { content }));
- }
-
- async validateStackName(name: string): Promise<ValidationResult> {
- return this.handleResponse(this.api.post('/validate/stack-name', { name }));
- }
-
- async validatePort(port: number): Promise<ValidationResult> {
- return this.handleResponse(this.api.post('/validate/port', { port }));
- }
-}
diff --git a/frontend/src/lib/services/api/volume-api-service.ts b/frontend/src/lib/services/api/volume-api-service.ts
deleted file mode 100644
index 35a202089..000000000
--- a/frontend/src/lib/services/api/volume-api-service.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import BaseAPIService from './api-service';
-
-export default class VolumeAPIService extends BaseAPIService {
- async list(filters?: Record<string, string>) {
- return this.handleResponse(this.api.get('/volumes', { params: { filters } }));
- }
-
- async get(name: string) {
- return this.handleResponse(this.api.get(`/volumes/${name}`));
- }
-
- async inspect(name: string) {
- return this.handleResponse(this.api.get(`/volumes/${name}/inspect`));
- }
-
- async isInUse(name: string): Promise<boolean> {
- const response = await this.api.get(`/volumes/${name}/usage`);
- return response.data.inUse;
- }
-
- async create(volumeConfig: { name?: string; driver?: string; driverOpts?: Record<string, string>; labels?: Record<string, string> }) {
- return this.handleResponse(this.api.post('/volumes', volumeConfig));
- }
-
- async remove(name: string, force: boolean = false) {
- return this.handleResponse(
- this.api.delete(`/volumes/${name}`, {
- params: { force }
- })
- );
- }
-
- async prune(filters?: Record<string, string>) {
- return this.handleResponse(this.api.post('/volumes/prune', { filters }));
- }
-
- async usage(name: string) {
- return this.handleResponse(this.api.get(`/volumes/${name}/usage`));
- }
-
- async backup(name: string, destination: string) {
- return this.handleResponse(
- this.api.post(`/volumes/${name}/backup`, {
- destination
- })
- );
- }
-
- async restore(name: string, source: string) {
- return this.handleResponse(
- this.api.post(`/volumes/${name}/restore`, {
- source
- })
- );
- }
-
- async getContainers(name: string) {
- return this.handleResponse(this.api.get(`/volumes/${name}/containers`));
- }
-}
diff --git a/frontend/src/lib/services/deployment-service.ts b/frontend/src/lib/services/deployment-service.ts
deleted file mode 100644
index 5dc0e9582..000000000
--- a/frontend/src/lib/services/deployment-service.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-import { deploymentAPI } from './api';
-import type { Deployment } from '$lib/types/deployment.type';
-
-/**
- * Create a new deployment
- */
-export async function createDeployment(deployment: Omit<Deployment, 'id' | 'createdAt' | 'updatedAt'>): Promise<Deployment> {
- try {
- return await deploymentAPI.create({
- name: deployment.name,
- type: deployment.type,
- status: deployment.status,
- agentId: deployment.agentId,
- taskId: deployment.taskId,
- metadata: deployment.metadata
- });
- } catch (error) {
- console.error('Error creating deployment:', error);
- throw error;
- }
-}
-
-/**
- * Update a deployment
- */
-export async function updateDeployment(deploymentId: string, updates: Partial<Deployment>): Promise<Deployment | null> {
- try {
- return await deploymentAPI.update(deploymentId, {
- name: updates.name,
- status: updates.status,
- error: updates.error,
- metadata: updates.metadata
- });
- } catch (error) {
- console.error('Error updating deployment:', error);
- return null;
- }
-}
-
-/**
- * Get a deployment by ID
- */
-export async function getDeployment(deploymentId: string): Promise<Deployment | null> {
- try {
- return await deploymentAPI.get(deploymentId);
- } catch (error) {
- console.error('Error getting deployment:', error);
- return null;
- }
-}
-
-/**
- * Get deployments, optionally filtered by agent
- */
-export async function getDeployments(agentId?: string): Promise<Deployment[]> {
- try {
- return await deploymentAPI.list(agentId);
- } catch (error) {
- console.error('Error getting deployments:', error);
- return [];
- }
-}
-
-/**
- * Delete a deployment
- */
-export async function deleteDeployment(deploymentId: string): Promise<boolean> {
- try {
- await deploymentAPI.delete(deploymentId);
- return true;
- } catch (error) {
- console.error('Error deleting deployment:', error);
- return false;
- }
-}
-
-/**
- * Create a stack deployment
- */
-export async function createStackDeployment(agentId: string, stackName: string, composeContent: string, envContent?: string, taskId?: string): Promise<Deployment> {
- try {
- return await deploymentAPI.createStackDeployment({
- agentId,
- stackName,
- composeContent,
- envContent,
- taskId
- });
- } catch (error) {
- console.error('Error creating stack deployment:', error);
- throw error;
- }
-}
-
-/**
- * Create a container deployment
- */
-export async function createContainerDeployment(agentId: string, containerName: string, imageName: string, ports?: string[], volumes?: string[], taskId?: string): Promise<Deployment> {
- try {
- return await deploymentAPI.createContainerDeployment({
- agentId,
- containerName,
- imageName,
- ports,
- volumes,
- taskId
- });
- } catch (error) {
- console.error('Error creating container deployment:', error);
- throw error;
- }
-}
-
-/**
- * Create an image deployment
- */
-export async function createImageDeployment(agentId: string, imageName: string, taskId?: string): Promise<Deployment> {
- try {
- return await deploymentAPI.createImageDeployment({
- agentId,
- imageName,
- taskId
- });
- } catch (error) {
- console.error('Error creating image deployment:', error);
- throw error;
- }
-}
-
-/**
- * Update deployment status based on task completion
- */
-export async function updateDeploymentFromTask(taskId: string, status: string, result?: any, error?: string): Promise<void> {
- try {
- // Find deployment linked to this task
- const deployment = await deploymentAPI.getByTaskId(taskId);
-
- if (!deployment) {
- // No deployment linked to this task, nothing to update
- return;
- }
-
- // Map task status to deployment status
- let deploymentStatus: 'pending' | 'running' | 'stopped' | 'failed' | 'completed';
-
- switch (status) {
- case 'running':
- deploymentStatus = 'running';
- break;
- case 'completed':
- deploymentStatus = 'completed';
- break;
- case 'failed':
- deploymentStatus = 'failed';
- break;
- default:
- deploymentStatus = 'pending';
- }
-
- // Update deployment status
- await deploymentAPI.updateStatus(deployment.id, deploymentStatus, error);
-
- console.log(`Deployment ${deployment.id} updated to status: ${deploymentStatus}`);
- } catch (updateError) {
- console.error('Failed to update deployment from task:', updateError);
- // Don't throw as this shouldn't break the task update
- }
-}
-
-/**
- * Get deployments for a specific agent
- */
-export async function getAgentDeployments(agentId: string): Promise<Deployment[]> {
- try {
- return await deploymentAPI.getByAgent(agentId);
- } catch (error) {
- console.error('Error getting agent deployments:', error);
- return [];
- }
-}
-
-/**
- * Get deployment logs
- */
-export async function getDeploymentLogs(deploymentId: string): Promise<string> {
- try {
- return await deploymentAPI.getLogs(deploymentId);
- } catch (error) {
- console.error('Error getting deployment logs:', error);
- return '';
- }
-}
-
-/**
- * Get deployment statistics
- */
-export async function getDeploymentStats(): Promise<{
- total: number;
- pending: number;
- running: number;
- completed: number;
- failed: number;
- byAgent: Record<string, number>;
- byType: Record<string, number>;
-}> {
- try {
- return await deploymentAPI.getStats();
- } catch (error) {
- console.error('Error getting deployment stats:', error);
- return {
- total: 0,
- pending: 0,
- running: 0,
- completed: 0,
- failed: 0,
- byAgent: {},
- byType: {}
- };
- }
-}
diff --git a/frontend/src/lib/services/settings-service.ts b/frontend/src/lib/services/settings-service.ts
deleted file mode 100644
index ae3624de3..000000000
--- a/frontend/src/lib/services/settings-service.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { settingsAPI } from './api';
-import type { Settings } from '$lib/types/settings.type';
-
-// Simple wrapper around the API service for backward compatibility
-export async function getSettings(): Promise<Settings> {
- return await settingsAPI.getSettings();
-}
-
-export async function saveSettings(settings: Partial<Settings>): Promise<Settings> {
- return await settingsAPI.updateSettings(settings);
-}
-
-export async function resetSettings(): Promise<Settings> {
- return await settingsAPI.resetSettings();
-}
-
-// OIDC specific functions
-export async function getOidcConfig() {
- return await settingsAPI.getOidcConfig();
-}
-
-export async function updateOidcConfig(config: any) {
- return await settingsAPI.updateOidcConfig(config);
-}
-
-export async function getOidcStatus() {
- return await settingsAPI.getOidcStatus();
-}
-
-export async function testOidcConfig() {
- return await settingsAPI.testOidcConfig();
-}
-
-export async function getOidcAuthUrl(redirectUri: string) {
- return await settingsAPI.getOidcAuthUrl(redirectUri);
-}
-
-// Utility functions that might be needed
-export function ensureStacksDirectory(): Promise<void> {
- // This would typically be handled by the backend
- return Promise.resolve();
-}
-
-export function getBasePath(): string {
- if (typeof window !== 'undefined') {
- return window.location.origin;
- }
- return process.env.BASE_URL || 'http://localhost:5173';
-}
-
-// Default settings for fallback - fixed to match Onboarding interface
-export const DEFAULT_SETTINGS: Partial<Settings> = {
- onboarding: {
- completed: false,
- steps: {
- welcome: false,
- password: false,
- settings: false
- }
- },
- auth: {
- localAuthEnabled: true,
- oidcEnabled: false,
- sessionTimeout: 1440, // 24 hours in minutes
- passwordPolicy: 'basic',
- rbacEnabled: false
- },
- dockerHost: 'unix:///var/run/docker.sock',
- stacksDirectory: '/data/stacks',
- autoUpdate: false,
- autoUpdateInterval: 24,
- pollingEnabled: true,
- pollingInterval: 30,
- pruneMode: undefined,
- registryCredentials: [],
- templateRegistries: [],
- maturityThresholdDays: 30
-};
diff --git a/frontend/src/lib/services/user-service.ts b/frontend/src/lib/services/user-service.ts
deleted file mode 100644
index 7c0a2268c..000000000
--- a/frontend/src/lib/services/user-service.ts
+++ /dev/null
@@ -1,233 +0,0 @@
-import { userAPI } from './api';
-import type { User } from '$lib/types/user.type';
-import type { Role } from './api/user-api-service';
-
-// Simple wrapper around the API service for backward compatibility
-export async function getUserById(id: string): Promise<User | null> {
- try {
- return await userAPI.get(id);
- } catch (error) {
- console.error('Error getting user by ID:', error);
- return null;
- }
-}
-
-export async function getUserByUsername(username: string): Promise<User | null> {
- try {
- // Since the API doesn't have a direct getUserByUsername endpoint,
- // we'll need to get all users and filter (or add this endpoint to the backend)
- const users = await userAPI.list();
- return users.find((user) => user.username.toLowerCase() === username.toLowerCase()) || null;
- } catch (error) {
- console.error('Error getting user by username:', error);
- return null;
- }
-}
-
-export async function getUserByOidcSubjectId(oidcSubjectId: string): Promise<User | null> {
- try {
- // Similar to getUserByUsername, we'll filter from the list
- // In the future, you might want to add a specific API endpoint for this
- const users = await userAPI.list();
- return users.find((user) => user.oidcSubjectId === oidcSubjectId) || null;
- } catch (error) {
- console.error('Error getting user by OIDC subject ID:', error);
- return null;
- }
-}
-
-export async function listUsers(): Promise<User[]> {
- try {
- return await userAPI.list();
- } catch (error) {
- console.error('Error listing users:', error);
- return [];
- }
-}
-
-export async function saveUser(user: User): Promise<User | null> {
- try {
- if (user.id) {
- // Update existing user
- return await userAPI.update(user.id, user);
- } else {
- // Create new user
- return await userAPI.create(user);
- }
- } catch (error) {
- console.error('Error saving user:', error);
- return null;
- }
-}
-
-export async function createUser(user: Omit<User, 'id' | 'createdAt' | 'updatedAt'>): Promise<User | null> {
- try {
- return await userAPI.create(user);
- } catch (error) {
- console.error('Error creating user:', error);
- return null;
- }
-}
-
-export async function updateUser(id: string, updates: Partial<User>): Promise<User | null> {
- try {
- return await userAPI.update(id, updates);
- } catch (error) {
- console.error('Error updating user:', error);
- return null;
- }
-}
-
-export async function deleteUser(id: string): Promise<boolean> {
- try {
- await userAPI.delete(id);
- return true;
- } catch (error) {
- console.error('Error deleting user:', error);
- return false;
- }
-}
-
-// Authentication functions
-export async function login(credentials: { username: string; password: string; rememberMe?: boolean }) {
- try {
- return await userAPI.login(credentials);
- } catch (error) {
- console.error('Error during login:', error);
- throw error;
- }
-}
-
-export async function logout(): Promise<void> {
- try {
- await userAPI.logout();
- } catch (error) {
- console.error('Error during logout:', error);
- throw error;
- }
-}
-
-export async function changePassword(userId: string, currentPassword: string, newPassword: string): Promise<boolean> {
- try {
- await userAPI.changePassword(userId, { currentPassword, newPassword });
- return true;
- } catch (error) {
- console.error('Error changing password:', error);
- return false;
- }
-}
-
-export async function resetPassword(userId: string, newPassword: string): Promise<boolean> {
- try {
- await userAPI.resetPassword(userId, newPassword);
- return true;
- } catch (error) {
- console.error('Error resetting password:', error);
- return false;
- }
-}
-
-// RBAC functions
-export async function getRoles(): Promise<Role[]> {
- try {
- return await userAPI.getRoles();
- } catch (error) {
- console.error('Error getting roles:', error);
- return [];
- }
-}
-
-export async function getRole(id: string): Promise<Role | null> {
- try {
- return await userAPI.getRole(id);
- } catch (error) {
- console.error('Error getting role:', error);
- return null;
- }
-}
-
-export async function createRole(role: Omit<Role, 'id'>): Promise<Role | null> {
- try {
- return await userAPI.createRole(role);
- } catch (error) {
- console.error('Error creating role:', error);
- return null;
- }
-}
-
-export async function updateRole(id: string, updates: Partial<Role>): Promise<Role | null> {
- try {
- return await userAPI.updateRole(id, updates);
- } catch (error) {
- console.error('Error updating role:', error);
- return null;
- }
-}
-
-export async function deleteRole(id: string): Promise<boolean> {
- try {
- await userAPI.deleteRole(id);
- return true;
- } catch (error) {
- console.error('Error deleting role:', error);
- return false;
- }
-}
-
-export async function assignRole(userId: string, roleId: string): Promise<boolean> {
- try {
- await userAPI.assignRole(userId, roleId);
- return true;
- } catch (error) {
- console.error('Error assigning role:', error);
- return false;
- }
-}
-
-export async function removeRole(userId: string, roleId: string): Promise<boolean> {
- try {
- await userAPI.removeRole(userId, roleId);
- return true;
- } catch (error) {
- console.error('Error removing role:', error);
- return false;
- }
-}
-
-export async function getUserRoles(userId: string): Promise<Role[]> {
- try {
- return await userAPI.getUserRoles(userId);
- } catch (error) {
- console.error('Error getting user roles:', error);
- return [];
- }
-}
-
-export async function getPermissions(): Promise<string[]> {
- try {
- return await userAPI.getPermissions();
- } catch (error) {
- console.error('Error getting permissions:', error);
- return [];
- }
-}
-
-// Password utilities - these can be moved to the backend eventually
-export async function verifyPassword(user: User, password: string): Promise<boolean> {
- // This should ideally be handled by the backend during login
- // For now, we'll return false and let the backend handle verification
- console.warn('verifyPassword should be handled by the backend during login');
- return false;
-}
-
-export async function hashPassword(password: string): Promise<string> {
- // This should be handled by the backend
- console.warn('hashPassword should be handled by the backend');
- return password; // Return as-is, let backend handle hashing
-}
-
-export async function deriveKeyFromPassword(password: string, salt: string): Promise<string> {
- // This should be handled by the backend for security
- console.warn('deriveKeyFromPassword should be handled by the backend');
- return '';
-}
diff --git a/frontend/src/lib/stores/environment.store.ts b/frontend/src/lib/stores/environment.store.ts
new file mode 100644
index 000000000..29ccb445e
--- /dev/null
+++ b/frontend/src/lib/stores/environment.store.ts
@@ -0,0 +1,120 @@
+import { writable, get } from 'svelte/store';
+import { browser } from '$app/environment';
+
+export type Environment = {
+ id: string;
+ hostname: string;
+ apiUrl: string;
+ description?: string;
+ status: 'online' | 'offline' | 'error';
+ enabled: boolean;
+ lastSeen?: string;
+ createdAt: string;
+ updatedAt?: string;
+ isLocal?: boolean;
+};
+
+export const LOCAL_DOCKER_ENVIRONMENT_ID = '0';
+
+export const localDockerEnvironment: Environment = {
+ id: LOCAL_DOCKER_ENVIRONMENT_ID,
+ hostname: 'Local Docker',
+ apiUrl: 'http://localhost',
+ status: 'online',
+ enabled: true,
+ lastSeen: new Date().toISOString(),
+ createdAt: new Date().toISOString(),
+ isLocal: true
+};
+
+function createEnvironmentManagementStore() {
+ const _selectedEnvironment = writable<Environment | null>(null);
+ const _availableEnvironments = writable<Environment[]>([]);
+ let _initialized = false;
+
+ let _resolveReadyPromiseFunction: () => void;
+ const _readyPromise = new Promise<void>((resolve) => {
+ _resolveReadyPromiseFunction = resolve;
+ });
+
+ function _updateAvailable(environments: Environment[], hasLocalDocker: boolean) {
+ const newAvailable: Environment[] = [];
+
+ if (hasLocalDocker) {
+ newAvailable.push(localDockerEnvironment);
+ }
+
+ newAvailable.push(...environments.map((env) => ({ ...env, isLocal: false })));
+ _availableEnvironments.set(newAvailable);
+ return newAvailable;
+ }
+
+ function _getSavedEnvironmentId(): string | null {
+ if (browser && localStorage) {
+ return localStorage.getItem('selectedEnvironmentId');
+ }
+ return null;
+ }
+
+ function _selectInitialEnvironment(available: Environment[]): Environment | null {
+ const savedId = _getSavedEnvironmentId();
+
+ if (savedId) {
+ const found = available.find((env) => env.id === savedId);
+ if (found) {
+ _selectedEnvironment.set(found);
+ return found;
+ }
+ }
+
+ if (available.includes(localDockerEnvironment)) {
+ _selectedEnvironment.set(localDockerEnvironment);
+ return localDockerEnvironment;
+ }
+
+ if (available.length > 0) {
+ _selectedEnvironment.set(available[0]);
+ return available[0];
+ }
+
+ _selectedEnvironment.set(null);
+ return null;
+ }
+
+ return {
+ selected: {
+ subscribe: _selectedEnvironment.subscribe
+ },
+ available: {
+ subscribe: _availableEnvironments.subscribe
+ },
+ initialize: async (environmentsData: Environment[], hasLocalDocker: boolean) => {
+ const available = _updateAvailable(environmentsData, hasLocalDocker);
+
+ if (!_initialized) {
+ _selectInitialEnvironment(available);
+ _initialized = true;
+ _resolveReadyPromiseFunction(); // Resolve ready promise on first successful initialization
+ } else {
+ // If already initialized, ensure the selected environment is still valid
+ const currentSelected = get(_selectedEnvironment);
+ if (currentSelected && !available.find((env) => env.id === currentSelected.id)) {
+ _selectInitialEnvironment(available);
+ } else if (!currentSelected && available.length > 0) {
+ _selectInitialEnvironment(available);
+ }
+ }
+ },
+ setEnvironment: (environment: Environment) => {
+ _selectedEnvironment.set(environment);
+ if (browser && localStorage) {
+ localStorage.setItem('selectedEnvironmentId', environment.id);
+ }
+ },
+ isInitialized: () => _initialized,
+ getLocalEnvironment: () => localDockerEnvironment,
+ ready: _readyPromise
+ };
+}
+
+export const environmentStore = createEnvironmentManagementStore();
diff --git a/frontend/src/lib/stores/maturity-store.ts b/frontend/src/lib/stores/maturity-store.ts
index 59810dd8e..2b0f902e6 100644
--- a/frontend/src/lib/stores/maturity-store.ts
+++ b/frontend/src/lib/stores/maturity-store.ts
@@ -1,5 +1,5 @@
import { writable } from 'svelte/store';
-import type { ImageMaturity } from '$lib/types/docker/image.type';
+import type { ImageMaturity } from '$lib/models/image.type';
import ImageAPIService from '$lib/services/api/image-api-service';
import ImageMaturityAPIService from '$lib/services/api/image-maturity-api-service';
diff --git a/frontend/src/lib/stores/settings-store.ts b/frontend/src/lib/stores/settings-store.ts
deleted file mode 100644
index ab8042163..000000000
--- a/frontend/src/lib/stores/settings-store.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import { writable, get as getStore } from 'svelte/store';
-import type { Settings } from '$lib/types/settings.type';
-import { settingsAPI } from '$lib/services/api';
-
-function deepClone<T>(obj: T): T {
- if (obj === null || typeof obj !== 'object') {
- return obj;
- }
-
- if (obj instanceof Date) {
- return new Date(obj.getTime()) as unknown as T;
- }
-
- if (Array.isArray(obj)) {
- return obj.map((item) => deepClone(item)) as unknown as T;
- }
-
- const clonedObj = {} as T;
- for (const key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
- clonedObj[key] = deepClone(obj[key]);
- }
- }
-
- return clonedObj;
-}
-
-// Initialize with proper defaults that match the backend structure
-export const settingsStore = writable<Settings>({
- stacksDirectory: 'data/stacks',
- autoUpdate: false,
- autoUpdateInterval: 60,
- pollingEnabled: false,
- pollingInterval: 10,
- pruneMode: 'all',
- registryCredentials: [],
- templateRegistries: [],
- auth: {
- localAuthEnabled: true,
- oidcEnabled: false,
- sessionTimeout: 30,
- passwordPolicy: 'strong',
- rbacEnabled: false
- },
- maturityThresholdDays: 30,
- onboarding: {
- completed: false,
- completedAt: '',
- steps: {
- welcome: false,
- password: false,
- settings: false
- }
- }
-});
-
-export function updateSettingsStore(serverData: Partial<Settings>) {
- const dataToUpdate = deepClone(serverData);
-
- settingsStore.update((current) => {
- return {
- ...current,
- ...dataToUpdate,
- auth: {
- ...(current.auth || {}),
- ...(dataToUpdate.auth || {})
- },
- onboarding: {
- ...(current.onboarding || {}),
- ...(dataToUpdate.onboarding || {}),
- steps: {
- ...(current.onboarding?.steps || {}),
- ...(dataToUpdate.onboarding?.steps || {})
- }
- }
- } as Settings;
- });
-}
-
-export function getSettings(): Settings {
- return getStore(settingsStore);
-}
-
-export async function saveSettingsToServer(): Promise<Settings> {
- try {
- const settings = getSettings();
- console.log('Settings store - attempting to save:', settings);
-
- const updatedSettings = await settingsAPI.updateSettings(settings);
- console.log('Settings store - received from server:', updatedSettings);
-
- // For now, just update the store directly without cleaning
- updateSettingsStore(updatedSettings);
-
- return updatedSettings;
- } catch (error) {
- console.error('Settings store - failed to save:', error);
- throw error;
- }
-}
-
-export async function loadSettingsFromServer(): Promise<Settings> {
- try {
- console.log('Settings store - loading from server...');
- const settings = await settingsAPI.getSettings();
- console.log('Settings store - loaded from server:', settings);
-
- settingsStore.set(settings);
- return settings;
- } catch (error) {
- console.error('Settings store - failed to load:', error);
- throw error;
- }
-}
-
-export async function resetSettingsOnServer(): Promise<Settings> {
- try {
- const settings = await settingsAPI.resetSettings();
- settingsStore.set(settings);
- return settings;
- } catch (error) {
- console.error('Failed to reset settings:', error);
- throw error;
- }
-}
-
-export function initializeSettingsStore() {
- updateSettingsStore({
- onboarding: {
- completed: false,
- completedAt: '',
- steps: {
- welcome: false,
- password: false,
- settings: false
- }
- }
- });
-}
diff --git a/frontend/src/lib/types/agent.type.ts b/frontend/src/lib/types/agent.type.ts
deleted file mode 100644
index cc971c704..000000000
--- a/frontend/src/lib/types/agent.type.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-export interface AgentMetrics {
- containerCount?: number;
- imageCount?: number;
- stackCount?: number;
- networkCount?: number;
- volumeCount?: number;
-}
-
-export interface Agent {
- id: string;
- hostname: string;
- platform: string;
- version: string;
- capabilities: string[];
- status: 'online' | 'offline';
- lastSeen: string;
- registeredAt: string;
- metrics?: AgentMetrics;
- dockerInfo?: {
- version: string;
- containers: number;
- images: number;
- };
- metadata?: Record<string, any>;
- createdAt: string;
- updatedAt?: string;
-}
-
-export interface AgentTask {
- id: string;
- agentId: string;
- type: 'docker_command' | 'stack_deploy' | 'compose_create_project' | 'compose_up' | 'image_pull' | 'health_check' | 'container_start' | 'stack_list' | 'container_stop' | 'container_restart' | 'container_remove' | 'agent_upgrade';
- payload: Record<string, any>;
- status: 'pending' | 'running' | 'completed' | 'failed';
- result?: any;
- error?: string;
- createdAt: string;
- updatedAt?: string;
-}
-
-// Stack-related types for agents
-export interface AgentStack {
- id: string;
- name: string;
- agentId: string;
- agentHostname: string;
- isRemote: true;
- services?: StackService[];
- serviceCount?: number;
- runningCount?: number;
- status: StackStatus;
- isExternal?: boolean;
- createdAt?: string;
- updatedAt?: string;
- composeContent?: string;
- envContent?: string;
- description?: string;
- lastPolled?: string;
- path?: string;
-}
-
-export interface StackService {
- id: string;
- name: string;
- state?: {
- Running: boolean;
- Status: string;
- ExitCode: number;
- };
- ports?: StackPort[];
- networkSettings?: {
- Networks?: Record<string, NetworkConfig>;
- };
-}
-
-export interface StackPort {
- PublicPort?: number;
- PrivatePort?: number;
- Type?: string;
-}
-
-export interface NetworkConfig {
- IPAddress?: string;
- Gateway?: string;
- MacAddress?: string;
- Driver?: string;
-}
-
-export type StackStatus = 'running' | 'stopped' | 'partially running' | 'unknown';
-
-// Specific payload types for different task types
-export interface DockerCommandPayload {
- command: string;
- args: string[];
-}
-
-export interface StackDeployPayload {
- stackId: string;
- composeContent: string;
- envContent?: string;
-}
-
-export interface ImagePullPayload {
- imageName: string;
-}
-
-export interface ContainerActionPayload {
- containerId: string;
- force?: boolean;
-}
-
-export interface AgentUpgradePayload {
- action: 'upgrade';
- version?: string;
-}
diff --git a/frontend/src/lib/types/compose.spec.type.ts b/frontend/src/lib/types/compose.spec.type.ts
deleted file mode 100644
index d9c98cb63..000000000
--- a/frontend/src/lib/types/compose.spec.type.ts
+++ /dev/null
@@ -1,1152 +0,0 @@
-export type Include =
- | string
- | {
- path?: string | ListOfStrings;
-
- env_file?: string | ListOfStrings;
-
- project_directory?: string;
- };
-
-export type ListOfStrings = string[];
-
-export type Development = {
- watch?: {
- ignore?: string | ListOfStrings;
-
- include?: string | ListOfStrings;
-
- path: string;
-
- action: 'rebuild' | 'sync' | 'restart' | 'sync+restart' | 'sync+exec';
-
- target?: string;
- exec?: ServiceHook;
-
- [k: string]: unknown;
- }[];
-
- [k: string]: unknown;
-} & Development1;
-export type Development1 = {
- watch?: {
- ignore?: string | ListOfStrings;
-
- include?: string | ListOfStrings;
-
- path: string;
-
- action: 'rebuild' | 'sync' | 'restart' | 'sync+restart' | 'sync+exec';
-
- target?: string;
- exec?: ServiceHook;
-
- [k: string]: unknown;
- }[];
-
- [k: string]: unknown;
-} | null;
-
-export type Deployment = {
- mode?: string;
-
- endpoint_mode?: string;
-
- replicas?: number | string;
-
- labels?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- rollback_config?: {
- parallelism?: number | string;
-
- delay?: string;
-
- failure_action?: string;
-
- monitor?: string;
-
- max_failure_ratio?: number | string;
-
- order?: 'start-first' | 'stop-first';
-
- [k: string]: unknown;
- };
-
- update_config?: {
- parallelism?: number | string;
-
- delay?: string;
-
- failure_action?: string;
-
- monitor?: string;
-
- max_failure_ratio?: number | string;
-
- order?: 'start-first' | 'stop-first';
-
- [k: string]: unknown;
- };
-
- resources?: {
- limits?: {
- cpus?: number | string;
-
- memory?: string;
-
- pids?: number | string;
-
- [k: string]: unknown;
- };
-
- reservations?: {
- cpus?: number | string;
-
- memory?: string;
- generic_resources?: GenericResources;
- devices?: Devices;
-
- [k: string]: unknown;
- };
-
- [k: string]: unknown;
- };
-
- restart_policy?: {
- condition?: string;
-
- delay?: string;
-
- max_attempts?: number | string;
-
- window?: string;
-
- [k: string]: unknown;
- };
-
- placement?: {
- constraints?: string[];
-
- preferences?: {
- spread?: string;
-
- [k: string]: unknown;
- }[];
-
- max_replicas_per_node?: number | string;
-
- [k: string]: unknown;
- };
-
- [k: string]: unknown;
-} & Deployment1;
-
-export type GenericResources = {
- discrete_resource_spec?: {
- kind?: string;
-
- value?: number | string;
-
- [k: string]: unknown;
- };
-
- [k: string]: unknown;
-}[];
-
-export type ListOfStrings1 = string[];
-
-export type ListOfStrings2 = string[];
-
-export type Devices = {
- capabilities: ListOfStrings1;
-
- count?: string | number;
- device_ids?: ListOfStrings2;
-
- driver?: string;
-
- options?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- [k: string]: unknown;
-}[];
-export type Deployment1 = {
- mode?: string;
-
- endpoint_mode?: string;
-
- replicas?: number | string;
-
- labels?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- rollback_config?: {
- parallelism?: number | string;
-
- delay?: string;
-
- failure_action?: string;
-
- monitor?: string;
-
- max_failure_ratio?: number | string;
-
- order?: 'start-first' | 'stop-first';
-
- [k: string]: unknown;
- };
-
- update_config?: {
- parallelism?: number | string;
-
- delay?: string;
-
- failure_action?: string;
-
- monitor?: string;
-
- max_failure_ratio?: number | string;
-
- order?: 'start-first' | 'stop-first';
-
- [k: string]: unknown;
- };
-
- resources?: {
- limits?: {
- cpus?: number | string;
-
- memory?: string;
-
- pids?: number | string;
-
- [k: string]: unknown;
- };
-
- reservations?: {
- cpus?: number | string;
-
- memory?: string;
- generic_resources?: GenericResources;
- devices?: Devices;
-
- [k: string]: unknown;
- };
-
- [k: string]: unknown;
- };
-
- restart_policy?: {
- condition?: string;
-
- delay?: string;
-
- max_attempts?: number | string;
-
- window?: string;
-
- [k: string]: unknown;
- };
-
- placement?: {
- constraints?: string[];
-
- preferences?: {
- spread?: string;
-
- [k: string]: unknown;
- }[];
-
- max_replicas_per_node?: number | string;
-
- [k: string]: unknown;
- };
-
- [k: string]: unknown;
-} | null;
-
-export type ListOrDict =
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
-export type ServiceConfigOrSecret = (
- | string
- | {
- source?: string;
-
- target?: string;
-
- uid?: string;
-
- gid?: string;
-
- mode?: number | string;
-
- [k: string]: unknown;
- }
-)[];
-
-export type ServiceConfigOrSecret1 = (
- | string
- | {
- source?: string;
-
- target?: string;
-
- uid?: string;
-
- gid?: string;
-
- mode?: number | string;
-
- [k: string]: unknown;
- }
-)[];
-
-export type ListOfStrings3 = string[];
-
-export type ListOfStrings4 = string[];
-
-export type ListOfStrings5 = string[];
-
-export type ListOfStrings6 = string[];
-
-export type ListOfStrings7 = string[];
-
-export type ListOfStrings8 = string[];
-
-export type ListOfStrings9 = string[];
-
-export type ServiceConfigOrSecret2 = (
- | string
- | {
- source?: string;
-
- target?: string;
-
- uid?: string;
-
- gid?: string;
-
- mode?: number | string;
-
- [k: string]: unknown;
- }
-)[];
-
-export type Network = {
- name?: string;
-
- driver?: string;
-
- driver_opts?: {
- [k: string]: string | number;
- };
-
- ipam?: {
- driver?: string;
-
- config?: {
- subnet?: string;
-
- ip_range?: string;
-
- gateway?: string;
-
- aux_addresses?: {
- [k: string]: string;
- };
-
- [k: string]: unknown;
- }[];
-
- options?: {
- [k: string]: string;
- };
-
- [k: string]: unknown;
- };
-
- external?:
- | boolean
- | string
- | {
- name?: string;
-
- [k: string]: unknown;
- };
-
- internal?: boolean | string;
-
- enable_ipv4?: boolean | string;
-
- enable_ipv6?: boolean | string;
-
- attachable?: boolean | string;
-
- labels?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- [k: string]: unknown;
-} & Network1;
-export type Network1 = {
- name?: string;
-
- driver?: string;
-
- driver_opts?: {
- [k: string]: string | number;
- };
-
- ipam?: {
- driver?: string;
-
- config?: {
- subnet?: string;
-
- ip_range?: string;
-
- gateway?: string;
-
- aux_addresses?: {
- [k: string]: string;
- };
-
- [k: string]: unknown;
- }[];
-
- options?: {
- [k: string]: string;
- };
-
- [k: string]: unknown;
- };
-
- external?:
- | boolean
- | string
- | {
- name?: string;
-
- [k: string]: unknown;
- };
-
- internal?: boolean | string;
-
- enable_ipv4?: boolean | string;
-
- enable_ipv6?: boolean | string;
-
- attachable?: boolean | string;
-
- labels?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- [k: string]: unknown;
-} | null;
-
-export type Volume = {
- name?: string;
-
- driver?: string;
-
- driver_opts?: {
- [k: string]: string | number;
- };
-
- external?:
- | boolean
- | string
- | {
- name?: string;
-
- [k: string]: unknown;
- };
-
- labels?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- [k: string]: unknown;
-} & Volume1;
-export type Volume1 = {
- name?: string;
-
- driver?: string;
-
- driver_opts?: {
- [k: string]: string | number;
- };
-
- external?:
- | boolean
- | string
- | {
- name?: string;
-
- [k: string]: unknown;
- };
-
- labels?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- [k: string]: unknown;
-} | null;
-
-export interface ComposeSpecification {
- version?: string;
-
- name?: string;
-
- include?: Include[];
-
- services?: {
- [k: string]: Service;
- };
-
- networks?: {
- [k: string]: Network;
- };
-
- volumes?: {
- [k: string]: Volume;
- };
-
- secrets?: {
- [k: string]: Secret;
- };
-
- configs?: {
- [k: string]: Config;
- };
-
- [k: string]: unknown;
-}
-
-export interface Service {
- develop?: Development;
- deploy?: Deployment;
- annotations?: ListOrDict;
- attach?: boolean | string;
-
- build?:
- | string
- | {
- context?: string;
-
- dockerfile?: string;
-
- dockerfile_inline?: string;
-
- entitlements?: string[];
-
- args?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- ssh?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- labels?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- cache_from?: string[];
-
- cache_to?: string[];
-
- no_cache?: boolean | string;
-
- additional_contexts?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- network?: string;
-
- pull?: boolean | string;
-
- target?: string;
-
- shm_size?: number | string;
-
- extra_hosts?:
- | {
- [k: string]: string | string[];
- }
- | string[];
-
- isolation?: string;
-
- privileged?: boolean | string;
- secrets?: ServiceConfigOrSecret;
-
- tags?: string[];
- ulimits?: Ulimits;
-
- platforms?: string[];
-
- [k: string]: unknown;
- };
-
- blkio_config?: {
- device_read_bps?: BlkioLimit[];
-
- device_read_iops?: BlkioLimit[];
-
- device_write_bps?: BlkioLimit[];
-
- device_write_iops?: BlkioLimit[];
-
- weight?: number | string;
-
- weight_device?: BlkioWeight[];
- };
-
- cap_add?: string[];
-
- cap_drop?: string[];
-
- cgroup?: 'host' | 'private';
-
- cgroup_parent?: string;
-
- command?: null | string | string[];
- configs?: ServiceConfigOrSecret1;
-
- container_name?: string;
-
- cpu_count?: string | number;
-
- cpu_percent?: string | number;
-
- cpu_shares?: number | string;
-
- cpu_quota?: number | string;
-
- cpu_period?: number | string;
-
- cpu_rt_period?: number | string;
-
- cpu_rt_runtime?: number | string;
-
- cpus?: number | string;
-
- cpuset?: string;
-
- credential_spec?: {
- config?: string;
-
- file?: string;
-
- registry?: string;
-
- [k: string]: unknown;
- };
-
- depends_on?:
- | ListOfStrings3
- | {
- [k: string]: {
- restart?: boolean | string;
-
- required?: boolean;
-
- condition: 'service_started' | 'service_healthy' | 'service_completed_successfully';
-
- [k: string]: unknown;
- };
- };
- device_cgroup_rules?: ListOfStrings4;
-
- devices?: (
- | string
- | {
- source: string;
-
- target?: string;
-
- permissions?: string;
-
- [k: string]: unknown;
- }
- )[];
-
- dns?: string | ListOfStrings;
-
- dns_opt?: string[];
-
- dns_search?: string | ListOfStrings;
-
- domainname?: string;
-
- entrypoint?: null | string | string[];
-
- env_file?:
- | string
- | (
- | string
- | {
- path: string;
-
- format?: string;
-
- required?: boolean | string;
- }
- )[];
-
- label_file?: string | string[];
-
- environment?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- expose?: (string | number)[];
-
- extends?:
- | string
- | {
- service: string;
-
- file?: string;
- };
-
- provider?: {
- type: string;
-
- options?: {
- [k: string]: (string | number | boolean) | (string | number | boolean)[];
- };
-
- configs?: {
- [k: string]: string;
- };
-
- [k: string]: unknown;
- };
-
- external_links?: string[];
-
- extra_hosts?:
- | {
- [k: string]: string | string[];
- }
- | string[];
-
- gpus?:
- | 'all'
- | {
- capabilities?: ListOfStrings5;
-
- count?: string | number;
- device_ids?: ListOfStrings6;
-
- driver?: string;
-
- options?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
- [k: string]: unknown;
- }[];
-
- group_add?: (string | number)[];
- healthcheck?: Healthcheck;
-
- hostname?: string;
-
- image?: string;
-
- init?: boolean | string;
-
- ipc?: string;
-
- isolation?: string;
-
- labels?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- links?: string[];
-
- logging?: {
- driver?: string;
-
- options?: {
- [k: string]: string | number | null;
- };
-
- [k: string]: unknown;
- };
-
- mac_address?: string;
-
- mem_limit?: number | string;
-
- mem_reservation?: string | number;
-
- mem_swappiness?: number | string;
-
- memswap_limit?: number | string;
-
- network_mode?: string;
-
- networks?:
- | ListOfStrings3
- | {
- [k: string]: {
- aliases?: ListOfStrings7;
-
- interface_name?: string;
-
- ipv4_address?: string;
-
- ipv6_address?: string;
- link_local_ips?: ListOfStrings8;
-
- mac_address?: string;
-
- driver_opts?: {
- [k: string]: string | number;
- };
-
- priority?: number;
-
- gw_priority?: number;
-
- [k: string]: unknown;
- } | null;
- };
-
- oom_kill_disable?: boolean | string;
-
- oom_score_adj?: string | number;
-
- pid?: string | null;
-
- pids_limit?: number | string;
-
- platform?: string;
-
- ports?: (
- | number
- | string
- | {
- name?: string;
-
- mode?: string;
-
- host_ip?: string;
-
- target?: number | string;
-
- published?: string | number;
-
- protocol?: string;
-
- app_protocol?: string;
-
- [k: string]: unknown;
- }
- )[];
-
- post_start?: ServiceHook1[];
-
- pre_stop?: ServiceHook1[];
-
- privileged?: boolean | string;
- profiles?: ListOfStrings9;
-
- pull_policy?: string;
-
- pull_refresh_after?: string;
-
- read_only?: boolean | string;
-
- restart?: string;
-
- runtime?: string;
-
- scale?: number | string;
-
- security_opt?: string[];
-
- shm_size?: number | string;
- secrets?: ServiceConfigOrSecret2;
-
- sysctls?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- stdin_open?: boolean | string;
-
- stop_grace_period?: string;
-
- stop_signal?: string;
-
- storage_opt?: {
- [k: string]: unknown;
- };
-
- tmpfs?: string | ListOfStrings;
-
- tty?: boolean | string;
- ulimits?: Ulimits1;
-
- user?: string;
-
- uts?: string;
-
- userns_mode?: string;
-
- volumes?: (
- | string
- | {
- type: 'bind' | 'volume' | 'tmpfs' | 'cluster' | 'npipe' | 'image';
-
- source?: string;
-
- target?: string;
-
- read_only?: boolean | string;
-
- consistency?: string;
-
- bind?: {
- propagation?: string;
-
- create_host_path?: boolean | string;
-
- recursive?: 'enabled' | 'disabled' | 'writable' | 'readonly';
-
- selinux?: 'z' | 'Z';
-
- [k: string]: unknown;
- };
-
- volume?: {
- labels?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- nocopy?: boolean | string;
-
- subpath?: string;
-
- [k: string]: unknown;
- };
-
- tmpfs?: {
- size?: number | string;
-
- mode?: number | string;
-
- [k: string]: unknown;
- };
-
- image?: {
- subpath?: string;
-
- [k: string]: unknown;
- };
-
- [k: string]: unknown;
- }
- )[];
-
- volumes_from?: string[];
-
- working_dir?: string;
-
- [k: string]: unknown;
-}
-
-export interface ServiceHook {
- command: null | string | string[];
-
- user?: string;
-
- privileged?: boolean | string;
-
- working_dir?: string;
-
- environment?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- [k: string]: unknown;
-}
-
-export interface Ulimits {
- [k: string]:
- | (number | string)
- | {
- hard: number | string;
-
- soft: number | string;
-
- [k: string]: unknown;
- };
-}
-
-export interface BlkioLimit {
- path?: string;
-
- rate?: number | string;
-}
-
-export interface BlkioWeight {
- path?: string;
-
- weight?: number | string;
-}
-
-export interface Healthcheck {
- disable?: boolean | string;
-
- interval?: string;
-
- retries?: number | string;
-
- test?: string | string[];
-
- timeout?: string;
-
- start_period?: string;
-
- start_interval?: string;
-
- [k: string]: unknown;
-}
-
-export interface ServiceHook1 {
- command: null | string | string[];
-
- user?: string;
-
- privileged?: boolean | string;
-
- working_dir?: string;
-
- environment?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- [k: string]: unknown;
-}
-
-export interface Ulimits1 {
- [k: string]:
- | (number | string)
- | {
- hard: number | string;
-
- soft: number | string;
-
- [k: string]: unknown;
- };
-}
-
-export interface Secret {
- name?: string;
-
- environment?: string;
-
- file?: string;
-
- external?:
- | boolean
- | string
- | {
- name?: string;
- [k: string]: unknown;
- };
-
- labels?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- driver?: string;
-
- driver_opts?: {
- [k: string]: string | number;
- };
-
- template_driver?: string;
-
- [k: string]: unknown;
-}
-
-export interface Config {
- name?: string;
-
- content?: string;
-
- environment?: string;
-
- file?: string;
-
- external?:
- | boolean
- | string
- | {
- name?: string;
- [k: string]: unknown;
- };
-
- labels?:
- | {
- [k: string]: string | number | boolean | null;
- }
- | string[];
-
- template_driver?: string;
-
- [k: string]: unknown;
-}
diff --git a/frontend/src/lib/types/deployment.type.ts b/frontend/src/lib/types/deployment.type.ts
deleted file mode 100644
index a35f297c3..000000000
--- a/frontend/src/lib/types/deployment.type.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-export interface Deployment {
- id: string;
- name: string;
- type: 'stack' | 'container' | 'image';
- status: 'pending' | 'running' | 'stopped' | 'failed' | 'completed';
- agentId: string;
- createdAt: string;
- updatedAt?: string;
- metadata?: {
- stackName?: string;
- imageName?: string;
- containerName?: string;
- composeContent?: string;
- envContent?: string;
- ports?: string[];
- volumes?: string[];
- };
- taskId?: string;
- error?: string;
-}
-
-export interface DeploymentTask {
- deploymentId: string;
- taskId: string;
- status: 'pending' | 'running' | 'completed' | 'failed';
- result?: any;
- error?: string;
-}
-
-export interface DeploymentStatus {
- id: string;
- stackName: string;
- status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
- progress: number;
- startTime: string;
- endTime?: string;
- logs: string[];
- error?: string;
- config: DeploymentConfig;
-}
-
-export interface DeploymentConfig {
- stackName: string;
- composeContent: string;
- envVars?: Record<string, string>;
- pullImages?: boolean;
- recreateContainers?: boolean;
- removeOrphans?: boolean;
- timeout?: number;
- template?: {
- id: string;
- name: string;
- variables: Record<string, string>;
- };
-}
-
-export interface DeploymentLog {
- timestamp: string;
- level: 'info' | 'warn' | 'error' | 'debug';
- message: string;
- service?: string;
-}
diff --git a/frontend/src/lib/types/docker/connection.type.ts b/frontend/src/lib/types/docker/connection.type.ts
deleted file mode 100644
index 29a30b44f..000000000
--- a/frontend/src/lib/types/docker/connection.type.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-export interface DockerConnectionOptions {
- socketPath?: string;
- host?: string;
- port?: number;
- ca?: string;
- cert?: string;
- key?: string;
-}
diff --git a/frontend/src/lib/types/docker/index.ts b/frontend/src/lib/types/docker/index.ts
deleted file mode 100644
index dd9870987..000000000
--- a/frontend/src/lib/types/docker/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from './image.type';
-export * from './connection.type';
diff --git a/frontend/src/lib/types/docker/prune.type.ts b/frontend/src/lib/types/docker/prune.type.ts
deleted file mode 100644
index 832fe91fb..000000000
--- a/frontend/src/lib/types/docker/prune.type.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/**
- * Interface for Docker prune operation results
- */
-export interface PruneResult {
- ContainersDeleted?: string[];
- ImagesDeleted?: any[];
- NetworksDeleted?: string[];
- VolumesDeleted?: string[];
- SpaceReclaimed?: number;
-}
diff --git a/frontend/src/lib/types/form.type.ts b/frontend/src/lib/types/form.type.ts
deleted file mode 100644
index 2f3433445..000000000
--- a/frontend/src/lib/types/form.type.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export type FormInput<T> = {
- value: T;
- valid: boolean;
- touched: boolean;
- error: string | null;
- errors: string[];
-};
diff --git a/frontend/src/lib/types/session.type.ts b/frontend/src/lib/types/session.type.ts
deleted file mode 100644
index aba3e86fa..000000000
--- a/frontend/src/lib/types/session.type.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import type { User } from './user.type';
-
-export type UserSession = {
- userId: string;
- username: string;
- createdAt: number;
- lastAccessed: number;
- expires?: number;
-};
-
-export interface Session {
- id: string;
- userId: string;
- user: User;
- token: string;
- refreshToken?: string;
- expiresAt: string;
- createdAt: string;
- lastActivity: string;
- ipAddress?: string;
- userAgent?: string;
- isActive: boolean;
-}
-
-export interface LoginRequest {
- username: string;
- password: string;
- rememberMe?: boolean;
-}
-
-export interface LoginResponse {
- session: Session;
- redirectUrl?: string;
-}
-
-export interface RefreshTokenRequest {
- refreshToken: string;
-}
-
-export interface OAuthLoginRequest {
- provider: 'oidc' | 'github' | 'google';
- code: string;
- state: string;
- redirectUri: string;
-}
diff --git a/frontend/src/lib/types/validation.type.ts b/frontend/src/lib/types/validation.type.ts
deleted file mode 100644
index ef4fc102f..000000000
--- a/frontend/src/lib/types/validation.type.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-export interface ValidationResult {
- valid: boolean;
- errors: ValidationError[];
- warnings: ValidationWarning[];
-}
-
-export interface ValidationError {
- field?: string;
- message: string;
- code?: string;
- line?: number;
- column?: number;
-}
-
-export interface ValidationWarning {
- field?: string;
- message: string;
- code?: string;
- line?: number;
- column?: number;
-}
-
-export interface DockerComposeValidation extends ValidationResult {
- services?: ServiceValidation[];
- networks?: NetworkValidation[];
- volumes?: VolumeValidation[];
-}
-
-export interface ServiceValidation {
- name: string;
- valid: boolean;
- errors: ValidationError[];
- warnings: ValidationWarning[];
-}
-
-export interface NetworkValidation {
- name: string;
- valid: boolean;
- errors: ValidationError[];
-}
-
-export interface VolumeValidation {
- name: string;
- valid: boolean;
- errors: ValidationError[];
-}
diff --git a/frontend/src/lib/utils/agent-status.utils.ts b/frontend/src/lib/utils/agent-status.utils.ts
deleted file mode 100644
index 93d91772e..000000000
--- a/frontend/src/lib/utils/agent-status.utils.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import type { Agent } from '$lib/types/agent.type';
-
-const AGENT_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
-
-export function isAgentOffline(agent: Agent): boolean {
- if (!agent.lastSeen) return true;
-
- const now = new Date();
- const lastSeen = new Date(agent.lastSeen);
- const timeSinceLastSeen = now.getTime() - lastSeen.getTime();
-
- return timeSinceLastSeen > AGENT_TIMEOUT_MS;
-}
-
-export function getActualAgentStatus(agent: Agent): 'online' | 'offline' {
- return isAgentOffline(agent) ? 'offline' : agent.status;
-}
-
-export function getAgentStatusClasses(agent: Agent): string {
- const actualStatus = getActualAgentStatus(agent);
- if (actualStatus === 'online') {
- return 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400';
- }
- return 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400';
-}
-
-export function getAgentStatusText(agent: Agent): string {
- const actualStatus = getActualAgentStatus(agent);
- return actualStatus === 'online' ? 'Online' : 'Offline';
-}
-
-export function canSendCommandsToAgent(agent: Agent): boolean {
- return getActualAgentStatus(agent) === 'online';
-}
diff --git a/frontend/src/lib/utils/bytes.util.ts b/frontend/src/lib/utils/bytes.util.ts
index e23312338..9e4cca1de 100644
--- a/frontend/src/lib/utils/bytes.util.ts
+++ b/frontend/src/lib/utils/bytes.util.ts
@@ -1,4 +1,3 @@
-// filepath: /Users/kylemendell/dev/ofkm/arcane/src/lib/utils/bytes.ts
const units: { [key: string]: number } = {
b: 1,
k: 1024,
diff --git a/frontend/src/lib/utils/compose-parser.ts b/frontend/src/lib/utils/compose-parser.ts
deleted file mode 100644
index b3c418c26..000000000
--- a/frontend/src/lib/utils/compose-parser.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { load as yamlLoad } from 'js-yaml';
-import type { ComposeSpecification } from '$lib/types/compose.spec.type';
-
-/**
- * Type-safe compose file parser with comprehensive validation
- */
-export function parseComposeFile(content: string): {
- data: ComposeSpecification | null;
- errors: string[];
- warnings: string[];
-} {
- const errors: string[] = [];
- const warnings: string[] = [];
-
- try {
- const parsed = yamlLoad(content) as ComposeSpecification;
-
- // Validate against the spec
- if (!parsed || typeof parsed !== 'object') {
- errors.push('Invalid YAML: must be an object');
- return { data: null, errors, warnings };
- }
-
- // Check required fields per spec
- if (!parsed.services) {
- errors.push('Missing required "services" section');
- return { data: null, errors, warnings };
- }
-
- // Validate service configurations
- for (const [serviceName, service] of Object.entries(parsed.services)) {
- if (!service.image && !service.build) {
- errors.push(`Service "${serviceName}" must have either "image" or "build"`);
- }
-
- // Type-safe validation of service properties
- if (service.depends_on) {
- if (Array.isArray(service.depends_on)) {
- for (const dep of service.depends_on) {
- if (!parsed.services[dep]) {
- errors.push(`Service "${serviceName}" depends on non-existent service "${dep}"`);
- }
- }
- } else if (typeof service.depends_on === 'object') {
- for (const [dep, config] of Object.entries(service.depends_on)) {
- if (!parsed.services[dep]) {
- errors.push(`Service "${serviceName}" depends on non-existent service "${dep}"`);
- }
- // Validate condition values per spec
- if (config.condition && !['service_started', 'service_healthy', 'service_completed_successfully'].includes(config.condition)) {
- errors.push(`Service "${serviceName}" has invalid dependency condition "${config.condition}"`);
- }
- }
- }
- }
- }
-
- // Validate networks
- if (parsed.networks) {
- for (const [networkName, network] of Object.entries(parsed.networks)) {
- if (network && network.driver && !['bridge', 'host', 'overlay', 'macvlan', 'none', 'null'].includes(network.driver)) {
- warnings.push(`Network "${networkName}" uses uncommon driver "${network.driver}"`);
- }
- }
- }
-
- return {
- data: parsed as ComposeSpecification,
- errors,
- warnings
- };
- } catch (parseError) {
- errors.push(`YAML parsing error: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
- return { data: null, errors, warnings };
- }
-}
diff --git a/frontend/src/lib/utils/compose-validate.utils.ts b/frontend/src/lib/utils/compose-validate.utils.ts
deleted file mode 100644
index 8189845af..000000000
--- a/frontend/src/lib/utils/compose-validate.utils.ts
+++ /dev/null
@@ -1,485 +0,0 @@
-import { promises as fs } from 'node:fs';
-import * as path from 'node:path';
-import { load as yamlLoad } from 'js-yaml'; // Add this import at the top
-
-/**
- * Validation modes for Docker Compose specification compliance
- */
-export type ValidationMode = 'default' | 'strict' | 'loose';
-
-/**
- * Validate unknown fields according to Compose spec
- */
-export function validateUnknownFields(data: any, knownFields: string[], context: string, mode: ValidationMode = 'default'): string[] {
- const warnings: string[] = [];
-
- if (mode === 'loose') return warnings;
-
- for (const key of Object.keys(data || {})) {
- if (!knownFields.includes(key) && !key.startsWith('x-')) {
- const message = `Unknown field "${key}" in ${context}`;
- if (mode === 'strict') {
- throw new Error(message);
- } else {
- warnings.push(message);
- }
- }
- }
-
- return warnings;
-}
-
-/**
- * Known top-level fields per Compose spec
- */
-export const KNOWN_TOP_LEVEL_FIELDS = ['version', 'name', 'services', 'networks', 'volumes', 'configs', 'secrets', 'include'];
-
-/**
- * Known service-level fields per Compose spec
- */
-export const KNOWN_SERVICE_FIELDS = [
- 'image',
- 'build',
- 'command',
- 'entrypoint',
- 'environment',
- 'env_file',
- 'ports',
- 'expose',
- 'volumes',
- 'networks',
- 'depends_on',
- 'restart',
- 'healthcheck',
- 'labels',
- 'container_name',
- 'hostname',
- 'domainname',
- 'user',
- 'working_dir',
- 'privileged',
- 'init',
- 'tty',
- 'stdin_open',
- 'profiles',
- 'scale',
- 'deploy',
- 'develop',
- 'configs',
- 'secrets',
- 'platform',
- 'pull_policy',
- 'runtime',
- 'stop_signal',
- 'stop_grace_period',
- 'sysctls',
- 'ulimits',
- 'cap_add',
- 'cap_drop',
- 'security_opt',
- 'devices',
- 'dns',
- 'dns_search',
- 'dns_opt',
- 'extra_hosts',
- 'external_links',
- 'isolation',
- 'links',
- 'logging',
- 'network_mode',
- 'pid',
- 'ipc',
- 'uts',
- 'read_only',
- 'shm_size',
- 'tmpfs',
- 'volumes_from',
- 'mac_address',
- 'storage_opt',
- 'userns_mode',
- 'credential_spec',
- 'device_cgroup_rules',
- 'group_add',
- 'mem_limit',
- 'mem_reservation',
- 'mem_swappiness',
- 'memswap_limit',
- 'oom_kill_disable',
- 'oom_score_adj',
- 'pids_limit',
- 'annotations',
- 'attach',
- 'blkio_config',
- 'cpu_count',
- 'cpu_percent',
- 'cpu_shares',
- 'cpu_period',
- 'cpu_quota',
- 'cpu_rt_runtime',
- 'cpu_rt_period',
- 'cpus',
- 'cpuset',
- 'cgroup',
- 'cgroup_parent',
- 'gpus',
- 'post_start',
- 'pre_stop',
- 'provider',
- 'label_file'
-];
-
-/**
- * Known network-level fields per Compose spec
- */
-export const KNOWN_NETWORK_FIELDS = ['driver', 'driver_opts', 'external', 'name', 'ipam', 'enable_ipv6', 'labels', 'attachable', 'scope', 'internal'];
-
-/**
- * Known volume-level fields per Compose spec
- */
-export const KNOWN_VOLUME_FIELDS = ['driver', 'driver_opts', 'external', 'name', 'labels'];
-
-/**
- * Validate container name format and conflicts per Compose spec
- */
-export function validateContainerName(serviceName: string, serviceConfig: any, stackId: string): string {
- let containerName = serviceConfig.container_name;
-
- if (containerName) {
- // Validate container_name format per spec
- const containerNameRegex = /^[a-zA-Z0-9][a-zA-Z0-9_.-]+$/;
- if (!containerNameRegex.test(containerName)) {
- throw new Error(`Invalid container_name "${containerName}" for service "${serviceName}". ` + `Must match pattern [a-zA-Z0-9][a-zA-Z0-9_.-]+`);
- }
-
- // Check for scaling conflicts - service with container_name cannot be scaled
- if (serviceConfig.scale && serviceConfig.scale > 1) {
- throw new Error(`Service "${serviceName}" cannot use both "container_name" and "scale > 1"`);
- }
-
- return containerName;
- }
-
- // Use Docker Compose naming convention
- return `${stackId}_${serviceName}_1`;
-}
-
-/**
- * Validate external resource configuration per Compose spec
- */
-export function validateExternalResource(name: string, config: any, type: 'network' | 'volume'): void {
- if (config.external === true) {
- // External resources should not have other configuration attributes
- const allowedFields = ['name', 'external'];
- const otherFields = Object.keys(config).filter((key) => !allowedFields.includes(key));
-
- if (otherFields.length > 0) {
- throw new Error(`External ${type} "${name}" cannot have additional attributes: ${otherFields.join(', ')}`);
- }
- }
-}
-
-/**
- * Enhanced environment file loading with new format support
- */
-export async function loadEnvFiles(envFiles: string | string[] | Array<{ path: string; required?: boolean; format?: string }>, stackDir: string): Promise<Record<string, string>> {
- const envVars: Record<string, string> = {};
- const files = Array.isArray(envFiles) ? envFiles : [envFiles];
-
- for (const envFile of files) {
- if (typeof envFile === 'string') {
- // Legacy format
- const content = await loadSingleEnvFile(envFile, stackDir);
- Object.assign(envVars, parseEnvContent(content));
- } else {
- // New format with options
- const { path: filePath, required = true, format = 'default' } = envFile;
-
- try {
- const content = await loadSingleEnvFile(filePath, stackDir);
-
- if (format === 'raw') {
- // Raw format - no interpolation
- Object.assign(envVars, parseEnvContentRaw(content));
- } else {
- // Default format with interpolation
- Object.assign(envVars, parseEnvContent(content));
- }
- } catch (error) {
- if (required) {
- throw new Error(`Required env file not found: ${filePath}`);
- }
- // Silently ignore missing non-required files
- }
- }
- }
-
- return envVars;
-}
-
-/**
- * Load a single environment file
- */
-async function loadSingleEnvFile(filePath: string, stackDir: string): Promise<string> {
- const fullPath = path.isAbsolute(filePath) ? filePath : path.join(stackDir, filePath);
- return await fs.readFile(fullPath, 'utf8');
-}
-
-/**
- * Parse environment content without variable interpolation (raw format)
- */
-export function parseEnvContentRaw(content: string): Record<string, string> {
- const envVars: Record<string, string> = {};
- const lines = content.split('\n');
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed || trimmed.startsWith('#')) continue;
-
- const equalIndex = trimmed.indexOf('=');
- if (equalIndex === -1) continue;
-
- const key = trimmed.substring(0, equalIndex);
- const value = trimmed.substring(equalIndex + 1);
-
- // Raw format - use value as-is without any processing
- envVars[key] = value;
- }
-
- return envVars;
-}
-
-/**
- * Basic environment content parser (for compatibility)
- */
-function parseEnvContent(content: string): Record<string, string> {
- const envVars: Record<string, string> = {};
- const lines = content.split('\n');
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed || trimmed.startsWith('#')) continue;
-
- const equalIndex = trimmed.indexOf('=');
- if (equalIndex === -1) continue;
-
- const key = trimmed.substring(0, equalIndex);
- let value = trimmed.substring(equalIndex + 1);
-
- // Remove quotes if present
- if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
- value = value.slice(1, -1);
- }
-
- envVars[key] = value;
- }
-
- return envVars;
-}
-
-/**
- * Validate service attributes for newer Compose spec features
- */
-export function validateServiceAttributes(serviceName: string, serviceConfig: any): string[] {
- const warnings: string[] = [];
-
- // Validate pull_policy
- if (serviceConfig.pull_policy) {
- const validPullPolicies = ['always', 'never', 'missing', 'build'];
- if (!validPullPolicies.includes(serviceConfig.pull_policy)) {
- warnings.push(`Service "${serviceName}" has invalid pull_policy "${serviceConfig.pull_policy}". ` + `Valid values: ${validPullPolicies.join(', ')}`);
- }
- }
-
- // Validate platform format
- if (serviceConfig.platform) {
- const platformRegex = /^[a-z0-9]+\/[a-z0-9]+$/;
- if (!platformRegex.test(serviceConfig.platform)) {
- warnings.push(`Service "${serviceName}" has invalid platform format "${serviceConfig.platform}". ` + `Expected format: os/arch (e.g., linux/amd64)`);
- }
- }
-
- // Validate init attribute
- if (serviceConfig.init !== undefined && typeof serviceConfig.init !== 'boolean') {
- warnings.push(`Service "${serviceName}" init attribute must be a boolean, got: ${typeof serviceConfig.init}`);
- }
-
- return warnings;
-}
-
-/**
- * Enhanced validation for compose structure with unknown field checking
- */
-export function validateComposeStructureEnhanced(composeData: any, mode: ValidationMode = 'default'): { valid: boolean; errors: string[]; warnings: string[] } {
- const errors: string[] = [];
- const warnings: string[] = [];
-
- if (!composeData || typeof composeData !== 'object') {
- errors.push('Compose file must be a valid YAML object');
- return { valid: false, errors, warnings };
- }
-
- // Validate unknown fields at top level
- try {
- warnings.push(...validateUnknownFields(composeData, KNOWN_TOP_LEVEL_FIELDS, 'top-level', mode));
- } catch (error) {
- errors.push(error instanceof Error ? error.message : String(error));
- return { valid: false, errors, warnings };
- }
-
- // Validate services section
- if (composeData.services) {
- for (const [serviceName, serviceConfig] of Object.entries(composeData.services)) {
- // Validate unknown fields in service
- try {
- warnings.push(...validateUnknownFields(serviceConfig, KNOWN_SERVICE_FIELDS, `service "${serviceName}"`, mode));
- } catch (error) {
- errors.push(error instanceof Error ? error.message : String(error));
- continue;
- }
-
- // Additional service attribute validation
- warnings.push(...validateServiceAttributes(serviceName, serviceConfig));
- }
- }
-
- // Validate networks section
- if (composeData.networks) {
- for (const [networkName, networkConfig] of Object.entries(composeData.networks)) {
- if (!networkConfig) continue;
-
- try {
- warnings.push(...validateUnknownFields(networkConfig, KNOWN_NETWORK_FIELDS, `network "${networkName}"`, mode));
-
- // Validate external networks
- validateExternalResource(networkName, networkConfig, 'network');
- } catch (error) {
- errors.push(error instanceof Error ? error.message : String(error));
- }
- }
- }
-
- // Validate volumes section
- if (composeData.volumes) {
- for (const [volumeName, volumeConfig] of Object.entries(composeData.volumes)) {
- if (!volumeConfig) continue;
-
- try {
- warnings.push(...validateUnknownFields(volumeConfig, KNOWN_VOLUME_FIELDS, `volume "${volumeName}"`, mode));
-
- // Validate external volumes
- validateExternalResource(volumeName, volumeConfig, 'volume');
- } catch (error) {
- errors.push(error instanceof Error ? error.message : String(error));
- }
- }
- }
-
- return {
- valid: errors.length === 0,
- errors,
- warnings
- };
-}
-
-/**
- * Validate compose content with enhanced field checking
- */
-function validateComposeContentEnhanced(content: string, mode: ValidationMode = 'default'): { valid: boolean; errors: string[]; warnings: string[] } {
- try {
- // Remove the require and use the imported yamlLoad directly
- const parsed = yamlLoad(content);
- return validateComposeStructureEnhanced(parsed, mode);
- } catch (parseError) {
- return {
- valid: false,
- errors: [`YAML parsing error: ${parseError instanceof Error ? parseError.message : String(parseError)}`],
- warnings: []
- };
- }
-}
-
-/**
- * Enhanced container configuration for newer Compose spec features
- */
-export function enhanceContainerConfig(containerConfig: any, serviceConfig: any): any {
- const enhanced = { ...containerConfig };
-
- // Add init support
- if (serviceConfig.init) {
- enhanced.HostConfig.Init = serviceConfig.init;
- }
-
- // Add platform support
- if (serviceConfig.platform) {
- enhanced.Platform = serviceConfig.platform;
- }
-
- // Add annotations to labels
- if (serviceConfig.annotations) {
- const annotations = Array.isArray(serviceConfig.annotations)
- ? serviceConfig.annotations.reduce((acc: any, annotation: string) => {
- const [key, value = ''] = annotation.split('=');
- acc[key] = value;
- return acc;
- }, {})
- : serviceConfig.annotations;
-
- Object.assign(enhanced.Labels, annotations);
- }
-
- // Store pull policy for use during image pulling
- if (serviceConfig.pull_policy) {
- enhanced._pullPolicy = serviceConfig.pull_policy;
- }
-
- return enhanced;
-}
-
-/**
- * Validate all compose configuration with comprehensive checks
- */
-export async function validateComposeConfiguration(composeContent: string, envContent: string = '', mode: ValidationMode = 'default'): Promise<{ valid: boolean; errors: string[]; warnings: string[] }> {
- const errors: string[] = [];
- const warnings: string[] = [];
-
- try {
- // Parse environment variables
- const envVars = parseEnvContent(envContent);
- const getEnvVar = (key: string): string | undefined => envVars[key] || process.env[key];
-
- // Validate compose content format with enhanced checking
- const contentValidation = validateComposeContentEnhanced(composeContent, mode);
- if (!contentValidation.valid) {
- return contentValidation;
- }
-
- warnings.push(...contentValidation.warnings);
-
- // Parse with variable substitution (import the function)
- const { parseYamlContent } = await import('./compose.utils');
- const composeData = parseYamlContent(composeContent, getEnvVar);
-
- if (!composeData) {
- errors.push('Failed to parse compose file with variable substitution');
- return { valid: false, errors, warnings };
- }
-
- // Validate dependencies if services exist
- if (composeData.services) {
- const { validateAllDependencies } = await import('./compose.utils');
- const dependencyValidation = validateAllDependencies(composeData.services);
-
- errors.push(...dependencyValidation.errors);
- warnings.push(...dependencyValidation.warnings);
- }
-
- return {
- valid: errors.length === 0,
- errors,
- warnings
- };
- } catch (error) {
- errors.push(`Validation failed: ${error instanceof Error ? error.message : String(error)}`);
- return { valid: false, errors, warnings };
- }
-}
diff --git a/frontend/src/lib/utils/compose.utils.ts b/frontend/src/lib/utils/compose.utils.ts
deleted file mode 100644
index 0e107b17f..000000000
--- a/frontend/src/lib/utils/compose.utils.ts
+++ /dev/null
@@ -1,2021 +0,0 @@
-import { load as yamlLoad, dump as yamlDump } from 'js-yaml';
-import { promises as fs, existsSync } from 'node:fs';
-import * as path from 'node:path';
-// Add the import for the ComposeSpecification type
-import type { ComposeSpecification, Service as ServiceConfig } from '../types/compose.spec.type.js';
-
-// Compose specification constants
-export const SUPPORTED_COMPOSE_VERSIONS = ['3.0', '3.1', '3.2', '3.3', '3.4', '3.5', '3.6', '3.7', '3.8', '3.9'];
-export const DEFAULT_COMPOSE_VERSION = '3.8';
-
-/**
- * Docker Compose profile-related types
- */
-export interface ProfileConfig {
- description?: string;
- depends_on?: string[];
- conflicts?: string[];
-}
-
-export interface ServiceProfile {
- service: string;
- profiles: string[];
-}
-
-export interface ProfileDeploymentCheck {
- shouldDeploy: boolean;
- reason: string;
-}
-
-export interface ProfileServiceFiltering {
- deployableServices: Record<string, any>;
- skippedServices: Array<{ name: string; reason: string }>;
- profileSummary: {
- totalServices: number;
- deployableServices: number;
- skippedServices: number;
- activeProfiles: string[];
- };
-}
-
-export interface ProfileResolution {
- resolvedProfiles: string[];
- warnings: string[];
- errors: string[];
-}
-
-export interface ProfileDeploymentPlan {
- plan: {
- servicesToDeploy: string[];
- servicesToSkip: Array<{ name: string; reason: string }>;
- volumesToCreate: string[];
- networksToCreate: string[];
- };
- summary: {
- totalServices: number;
- deployableServices: number;
- skippedServices: number;
- activeProfiles: string[];
- allDefinedProfiles: string[];
- };
- warnings: string[];
- errors: string[];
-}
-
-export interface ProfileUsageStats {
- totalProfiles: number;
- profilesWithServices: Array<{ profile: string; serviceCount: number; services: string[] }>;
- servicesWithoutProfiles: string[];
- servicesWithProfiles: ServiceProfile[];
-}
-
-/**
- * Parse environment file content with proper .env spec support
- */
-export function parseEnvContent(envContent: string | null): Record<string, string> {
- const envVars: Record<string, string> = {};
- if (envContent) {
- const lines = envContent.split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i].trim();
-
- // Skip empty lines and comments
- if (!line || line.startsWith('#')) continue;
-
- // Handle quoted values and escaping
- const equalIndex = line.indexOf('=');
- if (equalIndex === -1) continue;
-
- const key = line.substring(0, equalIndex).trim();
- let value = line.substring(equalIndex + 1);
-
- // Handle quoted values
- if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
- value = value.slice(1, -1);
- // Handle escaped quotes within double quotes
- if (value.includes('\\"')) {
- value = value.replace(/\\"/g, '"');
- }
- if (value.includes("\\'")) {
- value = value.replace(/\\'/g, "'");
- }
- }
-
- // Handle special characters and newlines
- value = value.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
-
- if (key) {
- envVars[key] = value;
- }
- }
- }
- return envVars;
-}
-
-/**
- * Validate compose file version and structure according to spec
- */
-export function validateComposeStructure(composeData: ComposeSpecification): {
- valid: boolean;
- errors: string[];
- warnings: string[];
-} {
- const errors: string[] = [];
- const warnings: string[] = [];
-
- if (!composeData || typeof composeData !== 'object') {
- errors.push('Compose file must be a valid YAML object');
- return { valid: false, errors, warnings };
- }
-
- // Check version
- if (composeData.version) {
- if (!SUPPORTED_COMPOSE_VERSIONS.includes(composeData.version)) {
- warnings.push(`Compose version ${composeData.version} may not be fully supported. Supported versions: ${SUPPORTED_COMPOSE_VERSIONS.join(', ')}`);
- }
- } else {
- warnings.push('No version specified in compose file. Consider adding a version field.');
- }
-
- // Services are required
- if (!composeData.services || typeof composeData.services !== 'object') {
- errors.push('Compose file must have a services section');
- return { valid: false, errors, warnings };
- }
-
- // Validate each service
- for (const [serviceName, serviceConfig] of Object.entries(composeData.services)) {
- // Each service must have image or build
- if (!serviceConfig.image && !serviceConfig.build) {
- errors.push(`Service '${serviceName}' must have either 'image' or 'build' field`);
- }
-
- // Validate service name format
- if (!/^[a-zA-Z0-9._-]+$/.test(serviceName)) {
- errors.push(`Service name '${serviceName}' contains invalid characters. Use only letters, numbers, dots, hyphens, and underscores.`);
- }
-
- // Validate depends_on
- if (serviceConfig.depends_on) {
- if (Array.isArray(serviceConfig.depends_on)) {
- for (const dep of serviceConfig.depends_on) {
- if (!composeData.services[dep]) {
- errors.push(`Service '${serviceName}' depends on '${dep}' which doesn't exist`);
- }
- }
- } else if (typeof serviceConfig.depends_on === 'object') {
- for (const dep of Object.keys(serviceConfig.depends_on)) {
- if (!composeData.services[dep]) {
- errors.push(`Service '${serviceName}' depends on '${dep}' which doesn't exist`);
- }
- }
- }
- }
-
- // Validate networks
- if (serviceConfig.networks) {
- if (Array.isArray(serviceConfig.networks)) {
- for (const network of serviceConfig.networks) {
- if (typeof network === 'string' && composeData.networks && !composeData.networks[network]) {
- warnings.push(`Service '${serviceName}' references network '${network}' which is not defined`);
- }
- }
- } else if (typeof serviceConfig.networks === 'object') {
- for (const network of Object.keys(serviceConfig.networks)) {
- if (composeData.networks && !composeData.networks[network]) {
- warnings.push(`Service '${serviceName}' references network '${network}' which is not defined`);
- }
- }
- }
- }
-
- // Validate volumes
- if (serviceConfig.volumes) {
- for (const volume of serviceConfig.volumes) {
- if (typeof volume === 'object' && volume.source && volume.type === 'volume') {
- if (composeData.volumes && !composeData.volumes[volume.source]) {
- warnings.push(`Service '${serviceName}' references volume '${volume.source}' which is not defined`);
- }
- }
- }
- }
-
- // Validate ports format
- if (serviceConfig.ports) {
- for (const port of serviceConfig.ports) {
- if (typeof port === 'string') {
- const portRegex = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:)?(\d+:)?\d+(\/[a-z]+)?$/;
- if (!portRegex.test(port)) {
- errors.push(`Service '${serviceName}' has invalid port format: '${port}'`);
- }
- }
- }
- }
- }
-
- // Validate networks section
- if (composeData.networks) {
- for (const [networkName, networkConfig] of Object.entries(composeData.networks)) {
- // NULL CHECK - networks can be null in the spec
- if (!networkConfig) {
- continue; // Skip null/undefined network configs
- }
-
- if (networkConfig.external && typeof networkConfig.external === 'object' && !networkConfig.external.name) {
- warnings.push(`External network '${networkName}' should have a name specified`);
- }
-
- if (networkConfig.driver && !['bridge', 'host', 'overlay', 'macvlan', 'none'].includes(networkConfig.driver)) {
- warnings.push(`Network '${networkName}' uses uncommon driver '${networkConfig.driver}'`);
- }
- }
- }
-
- // Validate volumes section
- if (composeData.volumes) {
- for (const [volumeName, volumeConfig] of Object.entries(composeData.volumes)) {
- // NULL CHECK - volumes can be null in the spec
- if (!volumeConfig) {
- continue; // Skip null/undefined volume configs
- }
-
- if (volumeConfig.external && typeof volumeConfig.external === 'object' && !volumeConfig.external.name) {
- warnings.push(`External volume '${volumeName}' should have a name specified`);
- }
- }
- }
-
- return {
- valid: errors.length === 0,
- errors,
- warnings
- };
-}
-
-/**
- * Normalize healthcheck according to Compose spec
- */
-export function normalizeHealthcheckTest(composeContent: string, envGetter?: (key: string) => string | undefined): string {
- let doc: any;
- try {
- doc = yamlLoad(composeContent);
- if (!doc || typeof doc !== 'object') {
- return composeContent;
- }
- } catch (e) {
- console.warn('Could not parse compose YAML for normalization:', e);
- return composeContent;
- }
-
- let modified = false;
-
- if (doc.services && typeof doc.services === 'object') {
- for (const serviceName in doc.services) {
- const service = doc.services[serviceName];
- if (service?.healthcheck) {
- // Normalize healthcheck test format
- if (service.healthcheck.test) {
- if (typeof service.healthcheck.test === 'string') {
- if (service.healthcheck.test.startsWith('CMD-SHELL ')) {
- service.healthcheck.test = ['CMD-SHELL', service.healthcheck.test.substring(11)];
- } else if (service.healthcheck.test.startsWith('CMD ')) {
- service.healthcheck.test = service.healthcheck.test.substring(4).split(' ');
- service.healthcheck.test.unshift('CMD');
- } else if (!service.healthcheck.test.startsWith('NONE')) {
- service.healthcheck.test = ['CMD-SHELL', service.healthcheck.test];
- }
- modified = true;
- } else if (Array.isArray(service.healthcheck.test)) {
- if (service.healthcheck.test.length > 0 && !['CMD', 'CMD-SHELL', 'NONE'].includes(service.healthcheck.test[0])) {
- service.healthcheck.test.unshift('CMD');
- modified = true;
- }
- }
- }
-
- // Normalize interval, timeout, start_period, retries
- if (service.healthcheck.interval && typeof service.healthcheck.interval === 'number') {
- service.healthcheck.interval = `${service.healthcheck.interval}s`;
- modified = true;
- }
- if (service.healthcheck.timeout && typeof service.healthcheck.timeout === 'number') {
- service.healthcheck.timeout = `${service.healthcheck.timeout}s`;
- modified = true;
- }
- if (service.healthcheck.start_period && typeof service.healthcheck.start_period === 'number') {
- service.healthcheck.start_period = `${service.healthcheck.start_period}s`;
- modified = true;
- }
- }
- }
- }
-
- // Perform variable substitution if envGetter is provided
- if (envGetter) {
- const originalDocSnapshot = JSON.stringify(doc);
- doc = substituteVariablesInObject(doc, envGetter);
- if (JSON.stringify(doc) !== originalDocSnapshot) {
- modified = true;
- }
- }
-
- if (modified) {
- return yamlDump(doc, { lineWidth: -1, quotingType: '"', forceQuotes: false });
- }
- return composeContent;
-}
-
-/**
- * Parse YAML content with proper Compose spec validation
- */
-export function parseYamlContent(content: string, envGetter?: (key: string) => string | undefined): ComposeSpecification | null {
- try {
- const parsedYaml = yamlLoad(content);
-
- if (!parsedYaml || typeof parsedYaml !== 'object') {
- console.warn('Parsed YAML content is not an object or is null.');
- return null;
- }
-
- // Validate structure
- const validation = validateComposeStructure(parsedYaml as ComposeSpecification);
- if (!validation.valid) {
- console.error('Compose validation errors:', validation.errors);
- }
- if (validation.warnings.length > 0) {
- console.warn('Compose validation warnings:', validation.warnings);
- }
-
- let result = parsedYaml as ComposeSpecification;
-
- // Apply environment variable substitution
- if (envGetter) {
- result = substituteVariablesInObject(result, envGetter) as ComposeSpecification;
- }
-
- // Ensure we have a default network if none specified
- if (!result.networks) {
- result.networks = {
- default: {
- driver: 'bridge'
- }
- };
- }
-
- return result;
- } catch (error) {
- console.error('Error parsing YAML content:', error);
- return null;
- }
-}
-
-/**
- * Enhanced variable substitution with Compose spec compliance
- */
-export function substituteVariablesInObject(obj: any, envGetter: (key: string) => string | undefined): any {
- if (Array.isArray(obj)) {
- return obj.map((item) => substituteVariablesInObject(item, envGetter));
- } else if (typeof obj === 'object' && obj !== null) {
- const newObj: Record<string, any> = {};
- for (const key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
- newObj[key] = substituteVariablesInObject(obj[key], envGetter);
- }
- }
- return newObj;
- } else if (typeof obj === 'string') {
- let result = obj;
-
- // Handle ${VAR} format
- result = result.replace(/\$\{([^}]+)\}/g, (match, varExpression) => {
- // Handle default values: ${VAR:-default} or ${VAR-default}
- const colonDefaultMatch = varExpression.match(/^([^:]+):-(.*)$/);
- const defaultMatch = varExpression.match(/^([^-]+)-(.*)$/);
-
- if (colonDefaultMatch) {
- const [, varName, defaultValue] = colonDefaultMatch;
- const value = envGetter(varName);
- return value !== undefined && value !== '' ? value : defaultValue;
- } else if (defaultMatch) {
- const [, varName, defaultValue] = defaultMatch;
- const value = envGetter(varName);
- return value !== undefined ? value : defaultValue;
- } else {
- // Simple variable substitution
- const value = envGetter(varExpression);
- return value !== undefined ? value : match; // Keep original if not found
- }
- });
-
- // Handle $VAR format (without braces)
- result = result.replace(/\$([A-Z_][A-Z0-9_]*)/g, (match, varName) => {
- const value = envGetter(varName);
- return value !== undefined ? value : match;
- });
-
- return result;
- }
- return obj;
-}
-
-/**
- * Enhanced volume preparation with full Docker Compose specification support
- * Handles short syntax, long syntax, bind mounts, named volumes, tmpfs, and all volume options
- */
-export function prepareVolumes(volumes: any[], composeData: any, stackId: string): string[] {
- if (!Array.isArray(volumes)) {
- return [];
- }
-
- const binds: string[] = [];
- const tmpfsMounts: string[] = [];
-
- for (const volume of volumes) {
- if (typeof volume === 'string') {
- // Short syntax: "source:target" or "source:target:mode"
- const bind = processShortVolumeString(volume, composeData, stackId);
- if (bind) binds.push(bind);
- } else if (typeof volume === 'object' && volume !== null) {
- // Long syntax object
- const result = processLongVolumeObject(volume, composeData, stackId);
- if (result.bind) binds.push(result.bind);
- if (result.tmpfs) tmpfsMounts.push(result.tmpfs);
- }
- }
-
- // Note: tmpfs mounts need to be handled separately in container creation
- // For now, we'll store them in a way that can be retrieved later
- return binds.filter(Boolean);
-}
-
-/**
- * Process short volume syntax strings
- * Examples: "/host/path:/container/path", "volume-name:/data", "/path:/data:ro"
- */
-function processShortVolumeString(volumeString: string, composeData: any, stackId: string): string | null {
- const parts = volumeString.split(':');
-
- if (parts.length < 2) {
- console.warn(`Invalid volume syntax: ${volumeString}. Expected at least "source:target"`);
- return null;
- }
-
- let source = parts[0];
- const target = parts[1];
- const options = parts.slice(2);
-
- // Convert relative paths to absolute paths
- if (source.startsWith('./') || source.startsWith('../')) {
- source = path.resolve(process.cwd(), source);
- }
-
- // Check if this is a bind mount and validate source exists
- if (source.startsWith('/') || source.includes('/')) {
- // This is a bind mount - check if source exists
- if (!existsSync(source)) {
- console.warn(`Bind mount source does not exist: ${source}`);
- console.warn(`Skipping volume mount: ${volumeString}`);
- console.warn(`Make sure to create the file/directory before deploying the stack`);
- return null;
- }
-
- // Bind mount
- return formatBindMount(source, target, options);
- } else {
- // Named volume logic...
- const isNamedVolume = composeData.volumes && composeData.volumes[source];
-
- if (isNamedVolume || !source.includes('/')) {
- const volumeName = `${stackId}_${source}`;
- return formatVolumeMount(volumeName, target, options);
- } else {
- return formatBindMount(source, target, options);
- }
- }
-}
-
-/**
- * Process long volume syntax objects
- * Supports all Docker Compose volume options
- */
-function processLongVolumeObject(volume: any, composeData: any, stackId: string): { bind?: string; tmpfs?: string } {
- const { type, source, target, read_only, consistency, bind, volume: volumeOpts, tmpfs } = volume;
-
- if (!target) {
- console.warn(`Volume missing required 'target' field:`, volume);
- return {};
- }
-
- switch (type) {
- case 'bind':
- return { bind: processBindMount(source, target, { read_only, consistency, bind }) };
-
- case 'volume':
- return {
- bind: processVolumeMount(source, target, stackId, composeData, {
- read_only,
- volume: volumeOpts
- })
- };
-
- case 'tmpfs':
- return { tmpfs: processTmpfsMount(target, { tmpfs }) };
-
- default:
- console.warn(`Unsupported volume type: ${type}`);
- return {};
- }
-}
-
-/**
- * Process bind mount with all options
- */
-function processBindMount(source: string, target: string, options: any = {}): string {
- if (!source) {
- throw new Error('Bind mount requires a source path');
- }
-
- const parts = [source, target];
- const mountOptions: string[] = [];
-
- // Read-only option
- if (options.read_only) {
- mountOptions.push('ro');
- }
-
- // Bind-specific options
- if (options.bind) {
- if (options.bind.propagation) {
- // Docker bind propagation: shared, slave, private, rshared, rslave, rprivate
- mountOptions.push(`bind-propagation=${options.bind.propagation}`);
- }
-
- if (options.bind.create_host_path !== false) {
- // Default behavior - Docker creates host path if it doesn't exist
- mountOptions.push('bind-nonrecursive=false');
- }
- }
-
- // Consistency option (mainly for Docker Desktop)
- if (options.consistency) {
- // cached, delegated, consistent
- mountOptions.push(`consistency=${options.consistency}`);
- }
-
- if (mountOptions.length > 0) {
- parts.push(mountOptions.join(','));
- }
-
- return parts.join(':');
-}
-
-/**
- * Process named volume mount with all options
- */
-function processVolumeMount(source: string, target: string, stackId: string, composeData: any, options: any = {}): string {
- let volumeName = '';
-
- if (source) {
- // Check if it's a defined volume in the compose file
- if (composeData.volumes && composeData.volumes[source]) {
- volumeName = `${stackId}_${source}`;
- } else {
- // External volume or absolute volume name
- volumeName = source;
- }
- } else {
- // Anonymous volume - Docker will generate a name
- volumeName = '';
- }
-
- const parts = [volumeName, target];
- const mountOptions: string[] = [];
-
- // Read-only option
- if (options.read_only) {
- mountOptions.push('ro');
- }
-
- // Volume-specific options
- if (options.volume) {
- if (options.volume.nocopy) {
- mountOptions.push('nocopy');
- }
- }
-
- if (mountOptions.length > 0) {
- parts.push(mountOptions.join(','));
- }
-
- return parts.join(':');
-}
-
-/**
- * Process tmpfs mount with all options
- * Note: tmpfs mounts need special handling in container creation
- */
-function processTmpfsMount(target: string, options: any = {}): string {
- const mountOptions: string[] = [];
-
- if (options.tmpfs) {
- if (options.tmpfs.size) {
- // Size in bytes or with suffix (100m, 1g)
- mountOptions.push(`size=${options.tmpfs.size}`);
- }
-
- if (options.tmpfs.mode) {
- // File mode in octal
- mountOptions.push(`mode=${options.tmpfs.mode}`);
- }
-
- if (options.tmpfs.uid !== undefined) {
- mountOptions.push(`uid=${options.tmpfs.uid}`);
- }
-
- if (options.tmpfs.gid !== undefined) {
- mountOptions.push(`gid=${options.tmpfs.gid}`);
- }
-
- if (options.tmpfs.noexec) {
- mountOptions.push('noexec');
- }
-
- if (options.tmpfs.nosuid) {
- mountOptions.push('nosuid');
- }
-
- if (options.tmpfs.nodev) {
- mountOptions.push('nodev');
- }
- }
-
- // Return in format that can be processed later for tmpfs creation
- return `${target}:${mountOptions.join(',')}`;
-}
-
-/**
- * Format bind mount string
- */
-function formatBindMount(source: string, target: string, options: string[] = []): string {
- const parts = [source, target];
-
- if (options.length > 0) {
- parts.push(options.join(','));
- }
-
- return parts.join(':');
-}
-
-/**
- * Format volume mount string
- */
-function formatVolumeMount(volumeName: string, target: string, options: string[] = []): string {
- const parts = [volumeName, target];
-
- if (options.length > 0) {
- parts.push(options.join(','));
- }
-
- return parts.join(':');
-}
-
-/**
- * Extract tmpfs mounts from volume definitions
- * This should be called during container creation to handle tmpfs mounts separately
- */
-export function extractTmpfsMounts(volumes: any[]): Array<{ target: string; options: any }> {
- if (!Array.isArray(volumes)) {
- return [];
- }
-
- const tmpfsMounts: Array<{ target: string; options: any }> = [];
-
- for (const volume of volumes) {
- if (typeof volume === 'object' && volume !== null && volume.type === 'tmpfs') {
- tmpfsMounts.push({
- target: volume.target,
- options: volume.tmpfs || {}
- });
- }
- }
-
- return tmpfsMounts;
-}
-
-/**
- * Create Docker volume definitions for named volumes
- * This should be called before creating containers to ensure named volumes exist
- */
-export function createVolumeDefinitions(composeData: any, stackId: string): Array<{ name: string; config: any }> {
- if (!composeData.volumes) {
- return [];
- }
-
- const volumeDefinitions: Array<{ name: string; config: any }> = [];
-
- for (const [volumeName, volumeConfig] of Object.entries(composeData.volumes)) {
- // Skip external volumes
- if (volumeConfig && typeof volumeConfig === 'object' && (volumeConfig as any).external) {
- continue;
- }
-
- const config = volumeConfig || {};
- const fullVolumeName = `${stackId}_${volumeName}`;
-
- volumeDefinitions.push({
- name: fullVolumeName,
- config: {
- Driver: (config as any).driver || 'local',
- DriverOpts: (config as any).driver_opts || {},
- Labels: {
- 'com.docker.compose.project': stackId,
- 'com.docker.compose.volume': volumeName,
- ...((config as any).labels || {})
- }
- }
- });
- }
-
- return volumeDefinitions;
-}
-
-/**
- * Validate volume configuration
- */
-export function validateVolumeConfiguration(volumes: any[]): { valid: boolean; errors: string[] } {
- const errors: string[] = [];
-
- if (!Array.isArray(volumes)) {
- return { valid: true, errors: [] }; // No volumes is valid
- }
-
- for (let i = 0; i < volumes.length; i++) {
- const volume = volumes[i];
-
- if (typeof volume === 'string') {
- // Validate short syntax
- if (!volume.includes(':')) {
- errors.push(`Volume ${i}: Invalid short syntax "${volume}". Expected "source:target" format.`);
- }
- } else if (typeof volume === 'object' && volume !== null) {
- // Validate long syntax
- if (!volume.target) {
- errors.push(`Volume ${i}: Missing required 'target' field in long syntax.`);
- }
-
- if (volume.type && !['bind', 'volume', 'tmpfs', 'npipe'].includes(volume.type)) {
- errors.push(`Volume ${i}: Invalid type "${volume.type}". Must be one of: bind, volume, tmpfs, npipe.`);
- }
-
- if (volume.type === 'bind' && !volume.source) {
- errors.push(`Volume ${i}: Bind mount requires 'source' field.`);
- }
- } else {
- errors.push(`Volume ${i}: Invalid volume definition. Must be string or object.`);
- }
- }
-
- return {
- valid: errors.length === 0,
- errors
- };
-}
-
-/**
- * Enhanced port preparation with full Compose spec support
- */
-export function preparePorts(ports: any[]): any {
- if (!Array.isArray(ports)) {
- return {};
- }
-
- const portBindings: any = {};
-
- for (const port of ports) {
- if (typeof port === 'string') {
- // Handle various string formats
- if (port.includes(':')) {
- const parts = port.split(':');
- let hostIP = '';
- let hostPort = '';
- let containerPort = '';
-
- if (parts.length === 2) {
- // "hostPort:containerPort"
- hostPort = parts[0];
- containerPort = parts[1];
- } else if (parts.length === 3) {
- // "hostIP:hostPort:containerPort"
- hostIP = parts[0];
- hostPort = parts[1];
- containerPort = parts[2];
- }
-
- // Handle protocol specification
- let protocol = 'tcp';
- if (containerPort.includes('/')) {
- [containerPort, protocol] = containerPort.split('/');
- }
-
- const containerPortKey = `${containerPort}/${protocol}`;
- portBindings[containerPortKey] = [
- {
- HostIp: hostIP,
- HostPort: hostPort
- }
- ];
- } else {
- // Just container port
- let containerPort = port;
- let protocol = 'tcp';
-
- if (port.includes('/')) {
- [containerPort, protocol] = port.split('/');
- }
-
- const containerPortKey = `${containerPort}/${protocol}`;
- portBindings[containerPortKey] = [{}]; // Let Docker assign
- }
- } else if (typeof port === 'object') {
- // Long syntax
- const containerPort = port.target.toString();
- const protocol = port.protocol || 'tcp';
- const containerPortKey = `${containerPort}/${protocol}`;
-
- const binding: any = {};
- if (port.published) {
- binding.HostPort = port.published.toString();
- }
- if (port.host_ip) {
- binding.HostIp = port.host_ip;
- }
-
- portBindings[containerPortKey] = [binding];
- }
- }
-
- return portBindings;
-}
-
-/**
- * Enhanced environment variable preparation
- */
-export async function prepareEnvironmentVariables(environment: any, stackDir: string): Promise<string[]> {
- const envArray: string[] = [];
- const envMap = new Map<string, string>();
-
- // Load .env file first (lowest priority)
- try {
- const envFilePath = path.join(stackDir, '.env');
- const envFileContent = await fs.readFile(envFilePath, 'utf8');
- const envVars = parseEnvContent(envFileContent);
-
- for (const [key, value] of Object.entries(envVars)) {
- envMap.set(key, value);
- }
- } catch (envError) {
- // .env file doesn't exist, that's okay
- }
-
- // Add process environment (medium priority)
- for (const [key, value] of Object.entries(process.env)) {
- if (value !== undefined) {
- envMap.set(key, value);
- }
- }
-
- // Add compose environment (highest priority)
- if (Array.isArray(environment)) {
- // Array format: ['KEY=value', 'KEY2=value2']
- for (const env of environment) {
- if (typeof env === 'string' && env.includes('=')) {
- const [key, ...valueParts] = env.split('=');
- envMap.set(key, valueParts.join('='));
- }
- }
- } else if (typeof environment === 'object' && environment !== null) {
- // Object format: { KEY: 'value', KEY2: 'value2' }
- for (const [key, value] of Object.entries(environment)) {
- if (value !== null && value !== undefined) {
- envMap.set(key, value.toString());
- }
- }
- }
-
- // Convert map to array
- for (const [key, value] of envMap) {
- envArray.push(`${key}=${value}`);
- }
-
- return envArray;
-}
-
-/**
- * Enhanced restart policy with full spec support
- */
-export function prepareRestartPolicy(restart: string | undefined): any {
- if (!restart || restart === 'no') {
- return { Name: 'no' };
- }
-
- switch (restart) {
- case 'always':
- return { Name: 'always' };
- case 'unless-stopped':
- return { Name: 'unless-stopped' };
- case 'on-failure':
- return { Name: 'on-failure', MaximumRetryCount: 0 };
- default:
- // Handle on-failure:5 format
- if (restart.startsWith('on-failure:')) {
- const retryCount = parseInt(restart.split(':')[1]) || 0;
- return { Name: 'on-failure', MaximumRetryCount: retryCount };
- }
- return { Name: 'no' };
- }
-}
-
-/**
- * Resolve dependency order for services
- */
-export function resolveDependencyOrder(services: Record<string, any>): string[] {
- const resolved: string[] = [];
- const resolving: Set<string> = new Set();
-
- function resolve(serviceName: string) {
- if (resolved.includes(serviceName)) return;
- if (resolving.has(serviceName)) {
- throw new Error(`Circular dependency detected involving ${serviceName}`);
- }
-
- resolving.add(serviceName);
-
- const service = services[serviceName];
- if (service.depends_on) {
- const dependencies = Array.isArray(service.depends_on) ? service.depends_on : Object.keys(service.depends_on);
-
- for (const dep of dependencies) {
- if (services[dep]) {
- resolve(dep);
- }
- }
- }
-
- resolving.delete(serviceName);
- resolved.push(serviceName);
- }
-
- for (const serviceName of Object.keys(services)) {
- resolve(serviceName);
- }
-
- return resolved;
-}
-
-/**
- * Generate config hash for service changes
- */
-export function generateConfigHash(service: any): string {
- const configString = JSON.stringify(service);
- let hash = 0;
- for (let i = 0; i < configString.length; i++) {
- const char = configString.charCodeAt(i);
- hash = (hash << 5) - hash + char;
- hash = hash & hash; // Convert to 32bit integer
- }
- return Math.abs(hash).toString(16);
-}
-
-/**
- * Prepare extra hosts
- */
-export function prepareExtraHosts(extraHosts: any[]): string[] {
- if (!Array.isArray(extraHosts)) return [];
-
- return extraHosts
- .map((host) => {
- if (typeof host === 'string') {
- return host;
- } else if (typeof host === 'object') {
- return `${host.hostname}:${host.ip}`;
- }
- return '';
- })
- .filter((h) => h);
-}
-
-/**
- * Prepare ulimits
- */
-export function prepareUlimits(ulimits: any): any[] {
- // Handle null, undefined, or non-object values
- if (!ulimits || typeof ulimits !== 'object') {
- return [];
- }
-
- // Handle array format (already in Docker format)
- if (Array.isArray(ulimits)) {
- return ulimits;
- }
-
- // Handle object format (Docker Compose format)
- return Object.entries(ulimits).map(([name, value]) => {
- if (typeof value === 'number') {
- return {
- Name: name,
- Soft: value,
- Hard: value
- };
- } else if (typeof value === 'object' && value !== null) {
- const limit = value as any;
- return {
- Name: name,
- Soft: limit.soft || limit.Soft || 0,
- Hard: limit.hard || limit.Hard || 0
- };
- } else {
- return {
- Name: name,
- Soft: 0,
- Hard: 0
- };
- }
- });
-}
-
-/**
- * Prepare log config
- */
-export function prepareLogConfig(logging: any): any {
- if (!logging || !logging.driver) {
- return { Type: 'json-file' };
- }
-
- return {
- Type: logging.driver,
- Config: logging.options || {}
- };
-}
-
-/**
- * Prepare healthcheck
- */
-export function prepareHealthcheck(healthcheck: any): any {
- if (!healthcheck) return undefined;
-
- const config: any = {};
-
- if (healthcheck.test) {
- if (Array.isArray(healthcheck.test)) {
- config.Test = healthcheck.test;
- } else if (typeof healthcheck.test === 'string') {
- if (healthcheck.test === 'NONE') {
- config.Test = ['NONE'];
- } else {
- config.Test = ['CMD-SHELL', healthcheck.test];
- }
- }
- }
-
- if (healthcheck.interval) {
- config.Interval = parseTimeToNanoseconds(healthcheck.interval);
- }
-
- if (healthcheck.timeout) {
- config.Timeout = parseTimeToNanoseconds(healthcheck.timeout);
- }
-
- if (healthcheck.start_period) {
- config.StartPeriod = parseTimeToNanoseconds(healthcheck.start_period);
- }
-
- if (healthcheck.retries) {
- config.Retries = parseInt(healthcheck.retries);
- }
-
- return config;
-}
-
-/**
- * Parse memory string to bytes
- */
-export function parseMemory(memStr: string | number): number {
- if (typeof memStr === 'number') return memStr;
-
- const str = memStr.toString().toLowerCase();
- const num = parseFloat(str);
-
- if (str.includes('k')) return Math.round(num * 1024);
- if (str.includes('m')) return Math.round(num * 1024 * 1024);
- if (str.includes('g')) return Math.round(num * 1024 * 1024 * 1024);
-
- return Math.round(num);
-}
-
-/**
- * Parse time string to nanoseconds
- */
-export function parseTimeToNanoseconds(timeStr: string | number): number {
- if (typeof timeStr === 'number') return timeStr * 1000000000; // assume seconds
-
- const str = timeStr.toString().toLowerCase();
- const num = parseFloat(str);
-
- if (str.includes('ns')) return Math.round(num);
- if (str.includes('us') || str.includes('μs')) return Math.round(num * 1000);
- if (str.includes('ms')) return Math.round(num * 1000000);
- if (str.includes('s')) return Math.round(num * 1000000000);
- if (str.includes('m')) return Math.round(num * 60 * 1000000000);
- if (str.includes('h')) return Math.round(num * 60 * 60 * 1000000000);
-
- return Math.round(num * 1000000000); // assume seconds
-}
-
-/**
- * Validate compose content
- */
-export function validateComposeContent(content: string): {
- valid: boolean;
- errors: string[];
- warnings: string[];
-} {
- try {
- const parsed = yamlLoad(content);
- return validateComposeStructure(parsed as ComposeSpecification);
- } catch (parseError) {
- return {
- valid: false,
- errors: [`YAML parsing error: ${parseError instanceof Error ? parseError.message : String(parseError)}`],
- warnings: []
- };
- }
-}
-
-/**
- * Parse and validate depends_on configuration
- * Supports both short and long syntax as per Docker Compose spec
- */
-export function parseDependsOn(dependsOn: any): Array<{ service: string; condition: string; restart?: boolean }> {
- if (!dependsOn) {
- return [];
- }
-
- const dependencies: Array<{ service: string; condition: string; restart?: boolean }> = [];
-
- if (Array.isArray(dependsOn)) {
- // Short syntax: depends_on: [service1, service2]
- for (const serviceName of dependsOn) {
- if (typeof serviceName === 'string') {
- dependencies.push({
- service: serviceName,
- condition: 'service_started',
- restart: false
- });
- }
- }
- } else if (typeof dependsOn === 'object' && dependsOn !== null) {
- // Long syntax: depends_on: { service1: { condition: "service_healthy" } }
- for (const [serviceName, config] of Object.entries(dependsOn)) {
- const depConfig = config as any;
-
- dependencies.push({
- service: serviceName,
- condition: depConfig?.condition || 'service_started',
- restart: depConfig?.restart || false
- });
- }
- }
-
- return dependencies;
-}
-
-/**
- * Validate dependency conditions according to Docker Compose spec
- */
-export function validateDependencyConditions(dependencies: Array<{ service: string; condition: string }>): { valid: boolean; errors: string[] } {
- const errors: string[] = [];
- const validConditions = ['service_started', 'service_healthy', 'service_completed_successfully'];
-
- for (const dep of dependencies) {
- if (!dep.service || typeof dep.service !== 'string') {
- errors.push(`Invalid service name in dependency: ${dep.service}`);
- }
-
- if (!validConditions.includes(dep.condition)) {
- errors.push(`Invalid dependency condition '${dep.condition}' for service '${dep.service}'. Valid conditions: ${validConditions.join(', ')}`);
- }
- }
-
- return {
- valid: errors.length === 0,
- errors
- };
-}
-
-/**
- * Check if a service has a healthcheck defined
- */
-export function hasHealthcheck(serviceConfig: any): boolean {
- return !!(serviceConfig?.healthcheck && serviceConfig.healthcheck !== false && serviceConfig.healthcheck.disable !== true);
-}
-
-/**
- * Get service dependency chain for debugging
- */
-export function getDependencyChain(services: Record<string, any>, startService: string, visited = new Set<string>()): string[] {
- if (visited.has(startService)) {
- return []; // Circular dependency detected
- }
-
- visited.add(startService);
- const chain = [startService];
-
- const serviceConfig = services[startService];
- if (serviceConfig?.depends_on) {
- const dependencies = parseDependsOn(serviceConfig.depends_on);
-
- for (const dep of dependencies) {
- if (services[dep.service]) {
- const subChain = getDependencyChain(services, dep.service, new Set(visited));
- chain.unshift(...subChain);
- }
- }
- }
-
- return [...new Set(chain)]; // Remove duplicates while preserving order
-}
-
-/**
- * Detect circular dependencies in compose services
- */
-export function detectCircularDependencies(services: Record<string, any>): {
- hasCircular: boolean;
- cycles: string[][];
-} {
- const visited = new Set<string>();
- const recursionStack = new Set<string>();
- const cycles: string[][] = [];
-
- function dfs(serviceName: string, path: string[]): boolean {
- if (recursionStack.has(serviceName)) {
- // Found a cycle
- const cycleStart = path.indexOf(serviceName);
- if (cycleStart !== -1) {
- cycles.push([...path.slice(cycleStart), serviceName]);
- }
- return true;
- }
-
- if (visited.has(serviceName)) {
- return false;
- }
-
- visited.add(serviceName);
- recursionStack.add(serviceName);
- path.push(serviceName);
-
- const serviceConfig = services[serviceName];
- if (serviceConfig?.depends_on) {
- const dependencies = parseDependsOn(serviceConfig.depends_on);
-
- for (const dep of dependencies) {
- if (services[dep.service] && dfs(dep.service, [...path])) {
- // Continue checking other dependencies to find all cycles
- }
- }
- }
-
- recursionStack.delete(serviceName);
- path.pop();
- return false;
- }
-
- for (const serviceName of Object.keys(services)) {
- if (!visited.has(serviceName)) {
- dfs(serviceName, []);
- }
- }
-
- return {
- hasCircular: cycles.length > 0,
- cycles
- };
-}
-
-/**
- * Enhanced dependency order resolution with condition awareness
- */
-export function resolveDependencyOrderWithConditions(services: Record<string, any>): {
- order: string[];
- batches: string[][];
- warnings: string[];
-} {
- const warnings: string[] = [];
-
- // First check for circular dependencies
- const circularCheck = detectCircularDependencies(services);
- if (circularCheck.hasCircular) {
- warnings.push(`Circular dependencies detected: ${circularCheck.cycles.map((cycle) => cycle.join(' -> ')).join(', ')}`);
- }
-
- // Build dependency graph
- const graph: Record<string, Set<string>> = {};
- const inDegree: Record<string, number> = {};
- const healthyServices = new Set<string>();
- const completionServices = new Set<string>();
-
- // Initialize graph
- for (const serviceName of Object.keys(services)) {
- graph[serviceName] = new Set();
- inDegree[serviceName] = 0;
-
- // Track services that need health checks or completion
- const serviceConfig = services[serviceName];
- if (hasHealthcheck(serviceConfig)) {
- healthyServices.add(serviceName);
- }
- }
-
- // Build edges and track dependency types
- for (const [serviceName, serviceConfig] of Object.entries(services)) {
- if (serviceConfig?.depends_on) {
- const dependencies = parseDependsOn(serviceConfig.depends_on);
-
- for (const dep of dependencies) {
- if (services[dep.service]) {
- graph[dep.service].add(serviceName);
- inDegree[serviceName]++;
-
- // Track completion dependencies
- if (dep.condition === 'service_completed_successfully') {
- completionServices.add(dep.service);
- }
- } else {
- warnings.push(`Service '${serviceName}' depends on undefined service '${dep.service}'`);
- }
- }
- }
- }
-
- // Topological sort with batching
- const result: string[] = [];
- const batches: string[][] = [];
- const queue: string[] = [];
- const tempInDegree = { ...inDegree };
-
- // Find initial services with no dependencies
- for (const [serviceName, degree] of Object.entries(tempInDegree)) {
- if (degree === 0) {
- queue.push(serviceName);
- }
- }
-
- while (queue.length > 0) {
- const batch: string[] = [...queue];
- batches.push(batch);
- queue.length = 0;
-
- for (const serviceName of batch) {
- result.push(serviceName);
-
- // Process neighbors
- for (const neighbor of graph[serviceName]) {
- tempInDegree[neighbor]--;
- if (tempInDegree[neighbor] === 0) {
- queue.push(neighbor);
- }
- }
- }
- }
-
- // Check if all services were processed (detect remaining cycles)
- if (result.length !== Object.keys(services).length) {
- const remaining = Object.keys(services).filter((name) => !result.includes(name));
- warnings.push(`Could not resolve dependencies for services: ${remaining.join(', ')} (possible circular dependencies)`);
- // Add remaining services to the end
- result.push(...remaining);
- }
-
- return {
- order: result,
- batches,
- warnings
- };
-}
-
-/**
- * Create dependency wait configuration for a service
- */
-export function createDependencyWaitConfig(
- serviceName: string,
- serviceConfig: any
-): {
- dependencies: Array<{ service: string; condition: string; timeout: number; restart?: boolean }>;
- warnings: string[];
-} {
- const warnings: string[] = [];
- const dependencies: Array<{
- service: string;
- condition: string;
- timeout: number;
- restart?: boolean;
- }> = [];
-
- if (!serviceConfig?.depends_on) {
- return { dependencies, warnings };
- }
-
- const parsedDeps = parseDependsOn(serviceConfig.depends_on);
- const validation = validateDependencyConditions(parsedDeps);
-
- if (!validation.valid) {
- warnings.push(...validation.errors);
- }
-
- for (const dep of parsedDeps) {
- let timeout = 30000; // Default 30 seconds
-
- // Adjust timeout based on condition type
- switch (dep.condition) {
- case 'service_healthy':
- timeout = 60000; // Health checks may take longer
- break;
- case 'service_completed_successfully':
- timeout = 120000; // Completion may take much longer
- break;
- case 'service_started':
- default:
- timeout = 30000; // Standard startup timeout
- break;
- }
-
- dependencies.push({
- service: dep.service,
- condition: dep.condition,
- timeout,
- restart: dep.restart
- });
- }
-
- return { dependencies, warnings };
-}
-
-/**
- * Check if a dependency condition can be satisfied
- */
-export function canSatisfyDependencyCondition(condition: string, serviceConfig: any): { canSatisfy: boolean; reason?: string } {
- switch (condition) {
- case 'service_started':
- return { canSatisfy: true };
-
- case 'service_healthy':
- if (!hasHealthcheck(serviceConfig)) {
- return {
- canSatisfy: false,
- reason: 'Service has no healthcheck defined but dependency requires service_healthy condition'
- };
- }
- return { canSatisfy: true };
-
- case 'service_completed_successfully':
- // Any service can potentially complete successfully
- return { canSatisfy: true };
-
- default:
- return {
- canSatisfy: false,
- reason: `Unknown dependency condition: ${condition}`
- };
- }
-}
-
-/**
- * Validate all dependency configurations in a compose file
- */
-export function validateAllDependencies(services: Record<string, any>): {
- valid: boolean;
- errors: string[];
- warnings: string[];
-} {
- const errors: string[] = [];
- const warnings: string[] = [];
-
- // Check for circular dependencies
- const circularCheck = detectCircularDependencies(services);
- if (circularCheck.hasCircular) {
- errors.push(`Circular dependencies detected: ${circularCheck.cycles.map((cycle) => cycle.join(' -> ')).join(', ')}`);
- }
-
- // Validate each service's dependencies
- for (const [serviceName, serviceConfig] of Object.entries(services)) {
- if (serviceConfig?.depends_on) {
- const { dependencies, warnings: depWarnings } = createDependencyWaitConfig(serviceName, serviceConfig);
- warnings.push(...depWarnings);
-
- // Check if dependency services exist and can satisfy conditions
- for (const dep of dependencies) {
- if (!services[dep.service]) {
- errors.push(`Service '${serviceName}' depends on undefined service '${dep.service}'`);
- continue;
- }
-
- const dependencyServiceConfig = services[dep.service];
- const satisfyCheck = canSatisfyDependencyCondition(dep.condition, dependencyServiceConfig);
-
- if (!satisfyCheck.canSatisfy) {
- warnings.push(`Service '${serviceName}' dependency on '${dep.service}' with condition '${dep.condition}': ${satisfyCheck.reason}`);
- }
- }
- }
- }
-
- return {
- valid: errors.length === 0,
- errors,
- warnings
- };
-}
-
-/**
- * Parse profiles from command line arguments or environment
- * Handles Docker Compose profile specification: --profile prof1 --profile prof2
- */
-export function parseActiveProfiles(args?: string[], env?: Record<string, string>): string[] {
- const profiles = new Set<string>();
-
- // Parse from command line arguments
- if (args) {
- for (let i = 0; i < args.length; i++) {
- if (args[i] === '--profile' && i + 1 < args.length) {
- profiles.add(args[i + 1]);
- i++; // Skip the profile value
- }
- }
- }
-
- // Parse from environment variables
- if (env) {
- // COMPOSE_PROFILES environment variable (comma-separated)
- const composeProfiles = env['COMPOSE_PROFILES'];
- if (composeProfiles) {
- composeProfiles.split(',').forEach((profile) => {
- const trimmed = profile.trim();
- if (trimmed) profiles.add(trimmed);
- });
- }
- }
-
- // Default profile if none specified
- const profilesArray = Array.from(profiles);
- return profilesArray.length > 0 ? profilesArray : ['default'];
-}
-
-/**
- * Validate profile configuration in compose data
- */
-export function validateProfiles(composeData: ComposeSpecification): {
- valid: boolean;
- errors: string[];
- warnings: string[];
-} {
- const errors: string[] = [];
- const warnings: string[] = [];
-
- if (!composeData || typeof composeData !== 'object') {
- return { valid: true, errors, warnings };
- }
-
- // Check if profiles are defined at top level
- const topLevelProfiles = composeData.profiles;
- if (topLevelProfiles && !Array.isArray(topLevelProfiles) && typeof topLevelProfiles !== 'object') {
- errors.push('Top-level profiles must be an array or object');
- }
-
- // Validate service profiles
- if (composeData.services) {
- for (const [serviceName, serviceConfig] of Object.entries(composeData.services)) {
- if (serviceConfig && typeof serviceConfig === 'object') {
- if (serviceConfig.profiles) {
- // Profiles can be string, array of strings, or not present
- if (typeof serviceConfig.profiles === 'string') {
- // Single profile as string is valid
- continue;
- } else if (Array.isArray(serviceConfig.profiles)) {
- // Array of profiles
- for (const profile of serviceConfig.profiles) {
- if (typeof profile !== 'string') {
- errors.push(`Service '${serviceName}' has invalid profile type. Profiles must be strings.`);
- }
- if (!profile.trim()) {
- errors.push(`Service '${serviceName}' has empty profile name.`);
- }
- }
- } else {
- errors.push(`Service '${serviceName}' profiles must be a string or array of strings.`);
- }
- }
- }
- }
- }
-
- return {
- valid: errors.length === 0,
- errors,
- warnings
- };
-}
-
-/**
- * Get all profiles defined in the compose file
- */
-export function getAllDefinedProfiles(composeData: ComposeSpecification): string[] {
- const allProfiles = new Set<string>();
-
- if (!composeData || typeof composeData !== 'object') {
- return [];
- }
-
- // Add top-level defined profiles
- if (composeData.profiles) {
- if (Array.isArray(composeData.profiles)) {
- composeData.profiles.forEach((profile) => {
- if (typeof profile === 'string') {
- allProfiles.add(profile);
- }
- });
- } else if (typeof composeData.profiles === 'object') {
- Object.keys(composeData.profiles).forEach((profile) => {
- allProfiles.add(profile);
- });
- }
- }
-
- // Extract profiles from services
- if (composeData.services) {
- for (const serviceConfig of Object.values(composeData.services)) {
- if (serviceConfig && typeof serviceConfig === 'object') {
- if (serviceConfig.profiles) {
- if (typeof serviceConfig.profiles === 'string') {
- allProfiles.add(serviceConfig.profiles);
- } else if (Array.isArray(serviceConfig.profiles)) {
- serviceConfig.profiles.forEach((profile: string) => {
- if (typeof profile === 'string') {
- allProfiles.add(profile);
- }
- });
- }
- }
- }
- }
- }
-
- return Array.from(allProfiles).sort();
-}
-
-/**
- * Check if a service should be deployed based on active profiles
- */
-export function shouldDeployService(serviceConfig: ServiceConfig, activeProfiles: string[], defaultBehavior: 'include' | 'exclude' = 'include'): ProfileDeploymentCheck {
- // If no profiles are specified on the service, use default behavior
- if (!serviceConfig.profiles) {
- return {
- shouldDeploy: defaultBehavior === 'include',
- reason: defaultBehavior === 'include' ? 'No profiles specified, included by default' : 'No profiles specified, excluded by default'
- };
- }
-
- // Normalize service profiles to array
- const serviceProfiles = Array.isArray(serviceConfig.profiles) ? serviceConfig.profiles : [serviceConfig.profiles];
-
- // Check if any of the service's profiles are in the active profiles
- const matchingProfiles = serviceProfiles.filter((profile) => activeProfiles.includes(profile));
-
- if (matchingProfiles.length > 0) {
- return {
- shouldDeploy: true,
- reason: `Service profiles [${serviceProfiles.join(', ')}] match active profiles [${matchingProfiles.join(', ')}]`
- };
- }
-
- return {
- shouldDeploy: false,
- reason: `Service profiles [${serviceProfiles.join(', ')}] do not match active profiles [${activeProfiles.join(', ')}]`
- };
-}
-
-/**
- * Filter services based on profiles
- */
-export function filterServicesByProfiles(services: Record<string, ServiceConfig>, activeProfiles: string[]): ProfileServiceFiltering {
- const deployableServices: Record<string, ServiceConfig> = {};
- const skippedServices: Array<{ name: string; reason: string }> = [];
-
- for (const [serviceName, serviceConfig] of Object.entries(services)) {
- const deploymentCheck = shouldDeployService(serviceConfig, activeProfiles);
-
- if (deploymentCheck.shouldDeploy) {
- deployableServices[serviceName] = serviceConfig;
- } else {
- skippedServices.push({
- name: serviceName,
- reason: deploymentCheck.reason
- });
- }
- }
-
- return {
- deployableServices,
- skippedServices,
- profileSummary: {
- totalServices: Object.keys(services).length,
- deployableServices: Object.keys(deployableServices).length,
- skippedServices: skippedServices.length,
- activeProfiles
- }
- };
-}
-
-/**
- * Resolve profile dependencies and conflicts
- */
-export function resolveProfileDependencies(composeData: ComposeSpecification, requestedProfiles: string[]): ProfileResolution {
- const warnings: string[] = [];
- const errors: string[] = [];
- const resolvedProfiles = new Set(requestedProfiles);
-
- // If no profiles requested, use default
- if (requestedProfiles.length === 0) {
- resolvedProfiles.add('default');
- }
-
- // Check for profile definitions and dependencies
- if (composeData.profiles && typeof composeData.profiles === 'object' && !Array.isArray(composeData.profiles)) {
- for (const [profileName, profileConfig] of Object.entries(composeData.profiles)) {
- if (resolvedProfiles.has(profileName) && profileConfig && typeof profileConfig === 'object') {
- // Handle profile dependencies
- if (profileConfig.depends_on && Array.isArray(profileConfig.depends_on)) {
- for (const dependency of profileConfig.depends_on) {
- if (typeof dependency === 'string') {
- resolvedProfiles.add(dependency);
- warnings.push(`Profile '${profileName}' requires profile '${dependency}' - added automatically`);
- }
- }
- }
-
- // Handle profile conflicts
- if (profileConfig.conflicts && Array.isArray(profileConfig.conflicts)) {
- for (const conflict of profileConfig.conflicts) {
- if (typeof conflict === 'string' && resolvedProfiles.has(conflict)) {
- errors.push(`Profile '${profileName}' conflicts with profile '${conflict}'`);
- }
- }
- }
- }
- }
- }
-
- // Validate that all resolved profiles exist
- const definedProfiles = getAllDefinedProfiles(composeData);
- for (const profile of resolvedProfiles) {
- if (profile !== 'default' && !definedProfiles.includes(profile)) {
- warnings.push(`Profile '${profile}' is not defined in the compose file`);
- }
- }
-
- return {
- resolvedProfiles: Array.from(resolvedProfiles).sort(),
- warnings,
- errors
- };
-}
-
-/**
- * Create deployment plan based on profiles
- */
-export function createProfileDeploymentPlan(composeData: ComposeSpecification, activeProfiles: string[]): ProfileDeploymentPlan {
- const warnings: string[] = [];
- const errors: string[] = [];
-
- // Validate profiles
- const profileValidation = validateProfiles(composeData);
- warnings.push(...profileValidation.warnings);
- errors.push(...profileValidation.errors);
-
- // Resolve profile dependencies
- const resolution = resolveProfileDependencies(composeData, activeProfiles);
- warnings.push(...resolution.warnings);
- errors.push(...resolution.errors);
-
- const finalActiveProfiles = resolution.resolvedProfiles;
-
- // Filter services by profiles
- const serviceFiltering = filterServicesByProfiles(composeData.services || {}, finalActiveProfiles);
-
- // Determine volumes and networks needed for deployable services
- const volumesToCreate = new Set<string>();
- const networksToCreate = new Set<string>();
-
- // Add volumes used by deployable services
- for (const serviceName of Object.keys(serviceFiltering.deployableServices)) {
- const serviceConfig = serviceFiltering.deployableServices[serviceName];
-
- // Collect volume references
- if (serviceConfig.volumes) {
- const volumes = Array.isArray(serviceConfig.volumes) ? serviceConfig.volumes : [];
- for (const volume of volumes) {
- if (typeof volume === 'string') {
- // Short syntax: extract volume name
- const parts = volume.split(':');
- const source = parts[0];
- if (!source.startsWith('/') && !source.startsWith('./') && !source.startsWith('../')) {
- // It's a named volume
- volumesToCreate.add(source);
- }
- } else if (typeof volume === 'object' && volume.source && volume.type === 'volume') {
- // Long syntax: volume mount
- volumesToCreate.add(volume.source);
- }
- }
- }
-
- // Collect network references
- if (serviceConfig.networks) {
- if (Array.isArray(serviceConfig.networks)) {
- serviceConfig.networks.forEach((network: string) => networksToCreate.add(network));
- } else if (typeof serviceConfig.networks === 'object') {
- Object.keys(serviceConfig.networks).forEach((network) => networksToCreate.add(network));
- }
- }
- }
-
- // Only include volumes that are actually defined in the compose file
- const definedVolumes = composeData.volumes ? Object.keys(composeData.volumes) : [];
- const filteredVolumes = Array.from(volumesToCreate).filter((vol) => definedVolumes.includes(vol));
-
- // Only include networks that are actually defined in the compose file
- const definedNetworks = composeData.networks ? Object.keys(composeData.networks) : [];
- const filteredNetworks = Array.from(networksToCreate).filter((net) => definedNetworks.includes(net));
-
- return {
- plan: {
- servicesToDeploy: Object.keys(serviceFiltering.deployableServices),
- servicesToSkip: serviceFiltering.skippedServices,
- volumesToCreate: filteredVolumes,
- networksToCreate: filteredNetworks
- },
- summary: {
- totalServices: serviceFiltering.profileSummary.totalServices,
- deployableServices: serviceFiltering.profileSummary.deployableServices,
- skippedServices: serviceFiltering.profileSummary.skippedServices,
- activeProfiles: finalActiveProfiles,
- allDefinedProfiles: getAllDefinedProfiles(composeData)
- },
- warnings,
- errors
- };
-}
-
-/**
- * Apply profile filtering to compose data
- * Returns a new compose data object with only the services that should be deployed
- */
-export function applyProfileFiltering(
- composeData: ComposeSpecification,
- activeProfiles: string[]
-): {
- filteredComposeData: ComposeSpecification;
- deploymentPlan: ProfileDeploymentPlan;
-} {
- const deploymentPlan = createProfileDeploymentPlan(composeData, activeProfiles);
-
- // Create filtered compose data
- const filteredComposeData: ComposeSpecification = {
- ...composeData,
- services: {},
- volumes: {},
- networks: {}
- };
-
- // Add deployable services
- for (const serviceName of deploymentPlan.plan.servicesToDeploy) {
- if (composeData.services && composeData.services[serviceName]) {
- filteredComposeData.services![serviceName] = composeData.services[serviceName];
- }
- }
-
- // Add required volumes
- for (const volumeName of deploymentPlan.plan.volumesToCreate) {
- if (composeData.volumes && composeData.volumes[volumeName]) {
- filteredComposeData.volumes![volumeName] = composeData.volumes[volumeName];
- }
- }
-
- // Add required networks
- for (const networkName of deploymentPlan.plan.networksToCreate) {
- if (composeData.networks && composeData.networks[networkName]) {
- filteredComposeData.networks![networkName] = composeData.networks[networkName];
- }
- }
-
- // Always ensure default network exists if no networks specified
- if (Object.keys(filteredComposeData.networks!).length === 0 && Object.keys(filteredComposeData.services!).length > 0) {
- filteredComposeData.networks!.default = {
- driver: 'bridge'
- };
- }
-
- return {
- filteredComposeData,
- deploymentPlan
- };
-}
-
-/**
- * Get profile usage statistics from a compose file
- */
-export function getProfileUsageStats(composeData: ComposeSpecification): ProfileUsageStats {
- const allProfiles = getAllDefinedProfiles(composeData);
- const profileServiceMap = new Map<string, string[]>();
- const servicesWithoutProfiles: string[] = [];
- const servicesWithProfiles: ServiceProfile[] = [];
-
- // Initialize profile map
- allProfiles.forEach((profile) => {
- profileServiceMap.set(profile, []);
- });
-
- // Process services
- if (composeData.services) {
- for (const [serviceName, serviceConfig] of Object.entries(composeData.services)) {
- if (serviceConfig && typeof serviceConfig === 'object') {
- if (serviceConfig.profiles) {
- const serviceProfiles = Array.isArray(serviceConfig.profiles) ? serviceConfig.profiles : [serviceConfig.profiles];
-
- servicesWithProfiles.push({
- service: serviceName,
- profiles: serviceProfiles
- });
-
- // Add service to each of its profiles
- serviceProfiles.forEach((profile) => {
- if (!profileServiceMap.has(profile)) {
- profileServiceMap.set(profile, []);
- }
- profileServiceMap.get(profile)!.push(serviceName);
- });
- } else {
- servicesWithoutProfiles.push(serviceName);
- }
- }
- }
- }
-
- const profilesWithServices = Array.from(profileServiceMap.entries()).map(([profile, services]) => ({
- profile,
- serviceCount: services.length,
- services: services.sort()
- }));
-
- return {
- totalProfiles: allProfiles.length,
- profilesWithServices,
- servicesWithoutProfiles: servicesWithoutProfiles.sort(),
- servicesWithProfiles
- };
-}
-
-/**
- * Generate profile documentation/help text
- */
-export function generateProfileHelp(composeData: ComposeSpecification): string {
- const stats = getProfileUsageStats(composeData);
- const allProfiles = getAllDefinedProfiles(composeData);
-
- let help = 'Docker Compose Profiles Available:\n\n';
-
- if (allProfiles.length === 0) {
- help += 'No profiles are defined in this compose file.\n';
- help += 'All services will be deployed by default.\n';
- return help;
- }
-
- help += `Total profiles defined: ${stats.totalProfiles}\n\n`;
-
- // List profiles with their services
- for (const profileInfo of stats.profilesWithServices) {
- help += `Profile: ${profileInfo.profile}\n`;
- help += ` Services (${profileInfo.serviceCount}): ${profileInfo.services.join(', ')}\n\n`;
- }
-
- // Show services without profiles
- if (stats.servicesWithoutProfiles.length > 0) {
- help += `Services without profiles (always deployed): ${stats.servicesWithoutProfiles.join(', ')}\n\n`;
- }
-
- help += 'Usage:\n';
- help += ' Deploy specific profile: --profile <profile-name>\n';
- help += ' Deploy multiple profiles: --profile prof1 --profile prof2\n';
- help += ' Environment variable: COMPOSE_PROFILES=prof1,prof2\n';
-
- return help;
-}
diff --git a/frontend/src/lib/utils/fs.utils.ts b/frontend/src/lib/utils/fs.utils.ts
deleted file mode 100644
index b6270299a..000000000
--- a/frontend/src/lib/utils/fs.utils.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { promises as fs } from 'node:fs';
-
-export async function fileExists(filePath: string): Promise<boolean> {
- try {
- const stats = await fs.stat(filePath);
- return stats.isFile();
- } catch {
- return false;
- }
-}
-
-export async function directoryExists(dir: string): Promise<boolean> {
- try {
- const stats = await fs.stat(dir);
- return stats.isDirectory();
- } catch {
- return false;
- }
-}
diff --git a/frontend/src/lib/utils/onboarding.utils.ts b/frontend/src/lib/utils/onboarding.utils.ts
deleted file mode 100644
index f471c73e7..000000000
--- a/frontend/src/lib/utils/onboarding.utils.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { listUsers, saveUser, hashPassword } from '$lib/services/user-service';
-
-// First-run check to create admin user if needed
-export async function checkFirstRun() {
- try {
- // getBasePath from settings-service should already handle dev vs prod
- const users = await listUsers();
-
- if (users.length === 0) {
- console.log('No users found. Creating default admin user...');
-
- // Create a default admin user
- const passwordHash = await hashPassword('arcane-admin'); // Default password
-
- await saveUser({
- id: crypto.randomUUID(),
- username: 'arcane',
- passwordHash,
- displayName: 'Arcane Admin',
- email: 'arcane@local',
- roles: ['admin'],
- createdAt: new Date().toISOString()
- });
-
- console.log('Default admin user created successfully');
- console.log('Username: arcane');
- console.log('Password: arcane-admin');
- console.log('IMPORTANT: Please change this password immediately after first login!');
- }
- } catch (error) {
- console.error('Error during first-run check:', error);
- }
-}
diff --git a/frontend/src/lib/utils/registry.utils.ts b/frontend/src/lib/utils/registry.utils.ts
deleted file mode 100644
index 0d7bd6fbb..000000000
--- a/frontend/src/lib/utils/registry.utils.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { parseAll } from '@swimlane/docker-reference';
-
-export function parseImageNameForRegistry(imageName: string): { registry: string } {
- try {
- const parsed = parseAll(imageName);
- return { registry: parsed.domain ?? 'docker.io' };
- } catch (error) {
- // Fallback to Docker Hub if parsing fails
- console.error(`Failed to parse image name: ${imageName}`, error);
- return { registry: 'docker.io' };
- }
-}
-
-export function areRegistriesEquivalent(url1: string, url2: string): boolean {
- const normalize = (url: string) => {
- let normalized = url.toLowerCase();
- if (normalized.startsWith('http://')) normalized = normalized.substring(7);
- if (normalized.startsWith('https://')) normalized = normalized.substring(8);
- if (normalized.endsWith('/')) normalized = normalized.slice(0, -1);
- // Common Docker Hub aliases
- if (normalized === 'index.docker.io' || normalized === 'registry-1.docker.io' || normalized === 'auth.docker.io') {
- return 'docker.io';
- }
- return normalized;
- };
- return normalize(url1) === normalize(url2);
-}
diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte
index 16b427fc0..959d2a71a 100644
--- a/frontend/src/routes/+layout.svelte
+++ b/frontend/src/routes/+layout.svelte
@@ -15,7 +15,6 @@
const versionInformation = data.versionInformation;
const user = $derived(data.user);
- const agents = $derived(data.agents);
const isNavigating = $derived(navigating.type !== null);
const isAuthenticated = $derived(!!user);
const isOnboardingPage = $derived(page.url.pathname.startsWith('/onboarding'));
@@ -44,7 +43,6 @@
}
});
- // Update user store when user data changes
$effect(() => {
if (user) {
userStore.setUser(user);
@@ -74,7 +72,7 @@
<div class="bg-background flex min-h-screen">
{#if showSidebar}
<Sidebar.Provider>
- <AppSidebar hasLocalDocker={data.hasLocalDocker || false} agents={agents || []} {versionInformation} {user} />
+ <AppSidebar {versionInformation} {user} />
<main class="flex-1">
<section class="p-6">
{@render children()}
diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.ts
index 92df31c8d..bc20fb7c6 100644
--- a/frontend/src/routes/+layout.ts
+++ b/frontend/src/routes/+layout.ts
@@ -2,8 +2,8 @@ import { browser } from '$app/environment';
import { env } from '$env/dynamic/public';
import { redirect } from '@sveltejs/kit';
import type { AppVersionInformation } from '$lib/types/application-configuration';
-import settingsStore from '$lib/stores/config-store';
-import { settingsAPI, userAPI } from '$lib/services/api';
+import { settingsAPI, userAPI, environmentManagementAPI } from '$lib/services/api';
+import { environmentStore } from '$lib/stores/environment.store';
let versionInformation: AppVersionInformation;
let versionInformationLastUpdated: number;
@@ -18,17 +18,14 @@ export const load = async ({ fetch, url }) => {
const updateCheckDisabled = env.PUBLIC_UPDATE_CHECK_DISABLED === 'true';
- let agents: any[] = [];
- let hasLocalDocker = false;
let isAuthenticated = false;
let user = null;
+ let settings: any = null;
const path = url.pathname;
-
const publicPaths = ['/auth/login', '/auth/logout', '/auth/oidc/login', '/auth/oidc/callback', '/img', '/favicon.ico'];
const isPublicPath = publicPaths.some((p) => path.startsWith(p));
- let settings: any = null;
try {
settings = await settingsAPI.getSettings();
} catch (e: any) {
@@ -37,7 +34,7 @@ export const load = async ({ fetch, url }) => {
const publicSettingsResponse = await fetch('/api/settings/public');
if (publicSettingsResponse.ok) {
const publicData = await publicSettingsResponse.json();
- settings = publicData.data;
+ if (publicData.success) settings = publicData.data;
}
} catch (publicError) {
console.warn('Could not fetch public settings:', publicError);
@@ -51,7 +48,6 @@ export const load = async ({ fetch, url }) => {
isAuthenticated = true;
}
} catch (e: any) {
- console.error(`Error while checking user authentication status: ${e.message}`);
user = null;
isAuthenticated = false;
}
@@ -61,59 +57,48 @@ export const load = async ({ fetch, url }) => {
}
if (isAuthenticated && !isPublicPath) {
- const isOnboardingPath = path.startsWith('/onboarding');
-
- if (!isOnboardingPath && settings && settings.onboarding && !settings.onboarding.completed) {
- throw redirect(302, '/onboarding/welcome');
- }
- }
-
- if (isAuthenticated && user) {
- try {
- // Fetch agents
- const agentsResponse = await fetch('/api/agents', {
- credentials: 'include'
- });
- if (agentsResponse.ok) {
- const agentsData = await agentsResponse.json();
- agents = agentsData.data || [];
+ if (!environmentStore.isInitialized()) {
+ try {
+ const environments = await environmentManagementAPI.list();
+ let hasLocalDocker = false;
+ if (browser) {
+ // Check for local Docker only in browser context
+ try {
+ const localDockerCheckUrl = '/api/environments/0/containers?limit=1';
+ const dockerResponse = await fetch(localDockerCheckUrl);
+ hasLocalDocker = dockerResponse.ok;
+ } catch (e) {
+ console.warn('Failed to check for local Docker:', e);
+ hasLocalDocker = false;
+ }
+ }
+ await environmentStore.initialize(environments, hasLocalDocker);
+ } catch (error) {
+ console.error('Failed to load and initialize environments in layout load:', error);
+ await environmentStore.initialize([], false); // Initialize with empty state
}
- } catch (error) {
- console.log('Could not fetch agents:', error);
}
- try {
- // Check if local Docker is available
- const dockerResponse = await fetch('/api/containers?limit=1', {
- credentials: 'include'
- });
- hasLocalDocker = dockerResponse.ok;
- } catch (error) {
- console.log('Docker not available:', error);
+ const isOnboardingPath = path.startsWith('/onboarding');
+ if (!isOnboardingPath && settings && settings.onboarding && !settings.onboarding.completed) {
+ throw redirect(302, '/onboarding/welcome');
}
}
- // Handle version information
if (updateCheckDisabled) {
- versionInformation = {
- currentVersion: '0.15.0'
- } as AppVersionInformation;
+ versionInformation = { currentVersion: '0.15.0' } as AppVersionInformation;
} else {
const cacheExpired = versionInformationLastUpdated && Date.now() - versionInformationLastUpdated > 1000 * 60 * 60 * 3;
-
if (!versionInformation || cacheExpired) {
try {
const versionResponse = await fetch('/_app/version.json');
if (versionResponse.ok) {
const versionData = await versionResponse.json();
- versionInformation = {
- currentVersion: versionData.version
- } as AppVersionInformation;
+ versionInformation = { currentVersion: versionData.version } as AppVersionInformation;
+ versionInformationLastUpdated = Date.now();
} else {
- console.error('Version endpoint returned status:', versionResponse.status);
throw new Error('Version endpoint not available');
}
- versionInformationLastUpdated = Date.now();
} catch (error) {
console.error('Error fetching version information:', error);
versionInformation = { currentVersion: 'Unknown' } as AppVersionInformation;
@@ -126,8 +111,6 @@ export const load = async ({ fetch, url }) => {
user,
isAuthenticated,
settings,
- agents,
- hasLocalDocker,
versionInformation,
updateCheckDisabled
};
diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelte
index 2d556466e..46641cc67 100644
--- a/frontend/src/routes/+page.svelte
+++ b/frontend/src/routes/+page.svelte
@@ -15,7 +15,7 @@
import { statusVariantMap } from '$lib/types/statuses';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
- import { systemAPI, imageAPI } from '$lib/services/api';
+ import { systemAPI, imageAPI, environmentAPI } from '$lib/services/api';
import { openConfirmDialog } from '$lib/components/confirm-dialog';
import MaturityItem from '$lib/components/maturity-item.svelte';
import { onMount } from 'svelte';
@@ -96,7 +96,6 @@
async function fetchLiveSystemStats() {
try {
const response = await systemAPI.getStats();
- console.log('System stats response:', response); // Debug log
let stats: SystemStats | null = null;
@@ -113,7 +112,6 @@
if (stats) {
liveSystemStats = stats;
dashboardStates.systemStats = stats;
- console.log('System stats updated:', stats); // Debug log
} else {
console.warn('Invalid system stats response format:', response);
}
diff --git a/frontend/src/routes/+page.ts b/frontend/src/routes/+page.ts
index 0c44d1c96..21907ecd8 100644
--- a/frontend/src/routes/+page.ts
+++ b/frontend/src/routes/+page.ts
@@ -1,14 +1,13 @@
-import { containerAPI, imageAPI, systemAPI, settingsAPI } from '$lib/services/api';
+import { systemAPI, settingsAPI, environmentAPI } from '$lib/services/api';
export const load = async () => {
try {
- // Remove systemStats from initial load for faster dashboard loading
- const [dockerInfo, containers, images, settings] = await Promise.all([systemAPI.getDockerInfo(), containerAPI.list(true), imageAPI.list(), settingsAPI.getSettings()]);
+ const [dockerInfo, resources, settings] = await Promise.all([systemAPI.getDockerInfo(), environmentAPI.getAllResources(), settingsAPI.getSettings()]);
return {
dockerInfo,
- containers,
- images,
+ containers: resources.containers || [],
+ images: resources.images || [],
settings
};
} catch (error) {
diff --git a/frontend/src/routes/agents/+page.svelte b/frontend/src/routes/agents/+page.svelte
deleted file mode 100644
index 8df3e5dcf..000000000
--- a/frontend/src/routes/agents/+page.svelte
+++ /dev/null
@@ -1,271 +0,0 @@
-<script lang="ts">
- import { onMount } from 'svelte';
- import { goto, invalidateAll } from '$app/navigation';
- import type { Agent } from '$lib/types/agent.type';
- import { formatDistanceToNow } from 'date-fns';
- import { RefreshCw, AlertCircle, Loader2, Monitor, CheckCircle, Eye, Send, Container, HardDrive, Trash2 } from '@lucide/svelte';
- import { toast } from 'svelte-sonner';
- import { getActualAgentStatus } from '$lib/utils/agent-status.utils';
- import { openConfirmDialog } from '$lib/components/confirm-dialog/index.js';
- import { handleApiResultWithCallbacks } from '$lib/utils/api.util.js';
- import { tryCatch } from '$lib/utils/try-catch.js';
- import Button from '$lib/components/ui/button/button.svelte';
- import ArcaneButton from '$lib/components/arcane-button.svelte';
-
- let { data } = $props();
-
- // Initialize from SSR data
- let agents: Agent[] = $state(data.agents || []);
- let loading = $state(false);
- let error = $state('');
-
- onMount(() => {
- // Refresh every 30 seconds for real-time updates (less frequent since we have SSR)
- const interval = setInterval(refreshAgents, 30000);
- return () => clearInterval(interval);
- });
-
- // Simplified refresh function - only for periodic updates
- async function refreshAgents() {
- if (loading) return;
-
- try {
- loading = true;
- const response = await fetch('/api/agents');
-
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
- }
-
- const responseData = await response.json();
- agents = responseData.agents || [];
- error = '';
- } catch (err) {
- console.error('Failed to refresh agents:', err);
- // Don't show error for background refresh failures
- } finally {
- loading = false;
- }
- }
-
- // Manual refresh triggered by user
- async function loadAgents() {
- try {
- loading = true;
- error = '';
-
- const response = await fetch('/api/agents');
-
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
- }
-
- const responseData = await response.json();
- agents = responseData.agents || [];
- } catch (err) {
- console.error('Failed to load agents:', err);
- error = err instanceof Error ? err.message : 'Unknown error';
- } finally {
- loading = false;
- }
- }
-
- async function deleteAgent(agentId: string, hostname: string) {
- openConfirmDialog({
- title: `Confirm Removal`,
- message: `Are you sure you want to remove this Agent? This action cannot be undone.`,
- confirm: {
- label: 'Remove',
- destructive: true,
- action: async () => {
- handleApiResultWithCallbacks({
- result: await tryCatch(
- fetch(`/api/agents/${agentId}`, {
- method: 'DELETE',
- credentials: 'include'
- })
- ),
- message: 'Failed to Remove Agent',
- onSuccess: async () => {
- toast.success('Agent Removed Successfully');
- await invalidateAll();
- }
- });
- }
- }
- });
- }
-
- function getStatusColor(agent: Agent) {
- const actualStatus = getActualAgentStatus(agent);
- if (actualStatus === 'online') return 'bg-green-500';
- return 'bg-red-500';
- }
-
- function getStatusText(agent: Agent) {
- const actualStatus = getActualAgentStatus(agent);
- if (actualStatus === 'online') return 'Online';
- return 'Offline';
- }
-
- function viewAgentDetails(agentId: string) {
- goto(`/agents/${agentId}`);
- }
-</script>
-
-<div class="container mx-auto px-6 py-8">
- <!-- Header -->
- <div class="mb-8 flex items-center justify-between">
- <div>
- <h1 class="text-3xl font-bold text-gray-900 dark:text-white">Agent Management</h1>
- <p class="mt-1 text-gray-600 dark:text-gray-400">Manage and monitor your remote agents</p>
- </div>
- <button onclick={loadAgents} class="flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50" disabled={loading}>
- {#if loading}
- <Loader2 class="h-4 w-4 animate-spin" />
- {:else}
- <RefreshCw class="h-4 w-4" />
- {/if}
- {loading ? 'Loading...' : 'Refresh'}
- </button>
- </div>
-
- <!-- Error Message -->
- {#if error}
- <div class="mb-6 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-red-700 dark:border-red-800 dark:bg-red-900/20 dark:text-red-400">
- <div class="flex items-center gap-2">
- <AlertCircle class="h-5 w-5" />
- <strong>Error:</strong>
- {error}
- </div>
- </div>
- {/if}
-
- <!-- Agents content - data is immediately available from SSR -->
- {#if agents.length === 0}
- <!-- Empty State -->
- <div class="py-16 text-center">
- <Monitor class="mx-auto mb-4 h-16 w-16 text-gray-400" />
- <h3 class="mb-2 text-lg font-medium text-gray-900 dark:text-white">No agents registered</h3>
- <p class="mb-4 text-gray-600 dark:text-gray-400">Get started by connecting your first agent</p>
- <div class="mx-auto max-w-md rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
- <p class="text-sm text-gray-600 dark:text-gray-400">Make sure your Go agent is running and connecting to:</p>
- <code class="mt-2 inline-block rounded bg-gray-100 px-2 py-1 font-mono text-sm text-gray-800 dark:bg-gray-700 dark:text-gray-200"> http://localhost:3000/agent/register </code>
- </div>
- </div>
- {:else}
- <!-- Agents Grid -->
- <div class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
- {#each agents as agent}
- <div class="rounded-xl border border-gray-200 bg-white p-6 transition-shadow hover:shadow-lg dark:border-gray-700 dark:bg-gray-800">
- <!-- Agent Header -->
- <div class="mb-4 flex items-start justify-between">
- <div class="flex items-center gap-3">
- <div class="relative">
- <div class="flex h-12 w-12 items-center justify-center rounded-lg bg-gray-100 dark:bg-gray-700">
- <Monitor class="h-6 w-6 text-gray-600 dark:text-gray-400" />
- </div>
- <div class="absolute -top-1 -right-1 h-4 w-4 {getStatusColor(agent)} rounded-full border-2 border-white dark:border-gray-800"></div>
- </div>
- <div>
- <h3 class="font-semibold text-gray-900 dark:text-white">{agent.hostname}</h3>
- <p class="font-mono text-xs text-gray-500 dark:text-gray-400">{agent.id}</p>
- </div>
- </div>
- <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium {getActualAgentStatus(agent) === 'online' ? 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400' : 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400'}">
- {getStatusText(agent)}
- </span>
- </div>
-
- <!-- Agent Details -->
- <div class="space-y-3">
- <div class="grid grid-cols-2 gap-4 text-sm">
- <div>
- <span class="text-gray-500 dark:text-gray-400">Platform</span>
- <p class="font-medium text-gray-900 capitalize dark:text-white">{agent.platform}</p>
- </div>
- <div>
- <span class="text-gray-500 dark:text-gray-400">Version</span>
- <p class="font-medium text-gray-900 dark:text-white">{agent.version}</p>
- </div>
- </div>
-
- <!-- Resource Metrics -->
- {#if agent.metrics}
- <div class="grid grid-cols-2 gap-2 border-t border-gray-100 py-3 dark:border-gray-700">
- <div class="text-center">
- <div class="mb-1 flex items-center justify-center gap-1">
- <Container class="h-3 w-3 text-blue-600 dark:text-blue-400" />
- <span class="text-xs text-gray-500 dark:text-gray-400">Containers</span>
- </div>
- <p class="text-sm font-semibold text-gray-900 dark:text-white">
- {agent.metrics.containerCount ?? 0}
- </p>
- </div>
- <div class="text-center">
- <div class="mb-1 flex items-center justify-center gap-1">
- <HardDrive class="h-3 w-3 text-green-600 dark:text-green-400" />
- <span class="text-xs text-gray-500 dark:text-gray-400">Images</span>
- </div>
- <p class="text-sm font-semibold text-gray-900 dark:text-white">
- {agent.metrics.imageCount ?? 0}
- </p>
- </div>
- </div>
- {:else}
- <div class="border-t border-gray-100 py-3 dark:border-gray-700">
- <p class="text-center text-xs text-gray-400">No metrics data available</p>
- </div>
- {/if}
-
- <div>
- <span class="text-sm text-gray-500 dark:text-gray-400">Capabilities</span>
- <div class="mt-1 flex flex-wrap gap-1">
- {#each agent.capabilities as capability}
- <span class="inline-flex items-center rounded bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
- {capability}
- </span>
- {:else}
- <span class="text-gray-400 dark:text-gray-500 text-sm">None</span>
- {/each}
- </div>
- </div>
-
- <div class="border-t border-gray-100 pt-3 dark:border-gray-700">
- <p class="text-xs text-gray-500 dark:text-gray-400">
- Last seen: {formatDistanceToNow(new Date(agent.lastSeen))} ago
- </p>
- </div>
- </div>
-
- <!-- Connected Status -->
- {#if getActualAgentStatus(agent) === 'online'}
- <div class="mt-4 rounded-lg border border-green-200 bg-green-50 p-3 dark:border-green-800 dark:bg-green-900/20">
- <div class="flex items-center gap-2">
- <CheckCircle class="h-4 w-4 text-green-600 dark:text-green-400" />
- <p class="text-sm font-medium text-green-700 dark:text-green-400">Ready to receive commands</p>
- </div>
- </div>
- {/if}
-
- <!-- Action Buttons -->
- <div class="mt-4 flex gap-2">
- <ArcaneButton action="inspect" onClick={() => viewAgentDetails(agent.id)} label="View Details" class="flex-1" />
- {#if getActualAgentStatus(agent) === 'online'}
- <ArcaneButton action="edit" onClick={() => viewAgentDetails(agent.id)} label="Manage" class="flex-1" />
- {/if}
- <ArcaneButton action="remove" onClick={() => deleteAgent(agent.id, agent.hostname)} label="Delete" loadingLabel="Deleting..." class="flex-1" />
- </div>
- </div>
- {/each}
- </div>
- {/if}
-
- <!-- Show subtle loading indicator during background refresh -->
- {#if loading && agents.length > 0}
- <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">
- <Loader2 class="h-4 w-4 animate-spin" />
- <span class="text-sm">Refreshing...</span>
- </div>
- {/if}
-</div>
diff --git a/frontend/src/routes/agents/+page.ts b/frontend/src/routes/agents/+page.ts
deleted file mode 100644
index 5f4b3f0f5..000000000
--- a/frontend/src/routes/agents/+page.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import type { PageLoad } from './$types';
-import { agentAPI, sessionAPI } from '$lib/services/api';
-import { error } from '@sveltejs/kit';
-
-export const load: PageLoad = async () => {
- try {
- // Check authentication and authorization via API
- const session = await sessionAPI.getCurrentSession();
-
- if (!session) {
- throw error(401, {
- message: 'Authentication required'
- });
- }
-
- // Check if user has admin role
- if (!session.user?.roles?.includes('admin')) {
- throw error(403, {
- message: 'Unauthorized access'
- });
- }
-
- // Load agents with status from API
- const agents = await agentAPI.listWithStatus();
-
- return {
- agents
- };
- } catch (err) {
- console.error('Failed to load agents:', err);
-
- // Re-throw SvelteKit errors
- if (err && typeof err === 'object' && 'status' in err) {
- throw err;
- }
-
- throw error(500, {
- message: err instanceof Error ? err.message : 'Failed to load agents'
- });
- }
-};
diff --git a/frontend/src/routes/agents/[agentId]/+page.svelte b/frontend/src/routes/agents/[agentId]/+page.svelte
deleted file mode 100644
index b9e620e22..000000000
--- a/frontend/src/routes/agents/[agentId]/+page.svelte
+++ /dev/null
@@ -1,1221 +0,0 @@
-<script lang="ts">
- import { onMount } from 'svelte';
- import { goto, invalidateAll } from '$app/navigation';
- import { formatDistanceToNow } from 'date-fns';
- import { toast } from 'svelte-sonner';
- import type { Agent, AgentTask } from '$lib/types/agent.type';
- import type { Deployment } from '$lib/types/deployment.type';
- import * as Card from '$lib/components/ui/card/index.js';
- import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
- import * as Alert from '$lib/components/ui/alert/index.js';
- import * as Dialog from '$lib/components/ui/dialog/index.js';
- import * as Select from '$lib/components/ui/select/index.js';
- import * as Tabs from '$lib/components/ui/tabs/index.js';
- import DropdownCard from '$lib/components/dropdown-card.svelte';
- import UniversalTable from '$lib/components/universal-table.svelte';
- import { Button } from '$lib/components/ui/button/index.js';
- import { Input } from '$lib/components/ui/input/index.js';
- import { Label } from '$lib/components/ui/label/index.js';
- import { Monitor, Terminal, Clock, Settings, Activity, AlertCircle, Server, RefreshCw, Play, ArrowLeft, Container, HardDrive, Layers, Network, Database, Loader2, Download, Trash2 } from '@lucide/svelte';
- import StatusBadge from '$lib/components/badges/status-badge.svelte';
- import ImagePullForm from '$lib/components/forms/ImagePullForm.svelte';
- import StackDeploymentForm from '$lib/components/forms/StackDeploymentForm.svelte';
- import QuickContainerForm from '$lib/components/forms/QuickContainerForm.svelte';
- import { getActualAgentStatus } from '$lib/utils/agent-status.utils';
- import { openConfirmDialog } from '$lib/components/confirm-dialog/index.js';
- import { handleApiResultWithCallbacks } from '$lib/utils/api.util.js';
- import { tryCatch } from '$lib/utils/try-catch.js';
- let { data } = $props();
-
- // Initialize from SSR data
- let agent: Agent | null = $state(data.agent);
- let tasks: AgentTask[] = $state(data.tasks);
- let deployments: Deployment[] = $state(data.deployments);
- let agentId = data.agentId;
-
- // Remove most of the initial loading states since data comes from SSR
- let loading = $state(false);
- let error = $state('');
-
- // Resource data states
- let resourcesLoading = $state(false);
- let resourcesError = $state('');
- let resourcesData = $state<{
- containers: any[];
- images: any[];
- networks: any[];
- volumes: any[];
- stacks: any[];
- }>({
- containers: [],
- images: [],
- networks: [],
- volumes: [],
- stacks: []
- });
-
- // Command form state
- let selectedCommand = $state<{ value: string; label: string } | undefined>(undefined);
- let commandArgs = $state('');
- let customCommand = $state('');
-
- // Add missing state variables
- let commandDialogOpen = $state(false);
- let taskExecuting = $state(false);
-
- // Deployment states with proper typing
- let deployDialogOpen = $state(false);
- let imageDialogOpen = $state(false);
- let containerDialogOpen = $state(false);
- let deploying = $state(false);
-
- // Add delete dialog state
- let deleteDialogOpen = $state(false);
- let deleting = $state(false);
-
- // Predefined commands
- const predefinedCommands = [
- { value: 'docker_version', label: 'Docker Version' },
- { value: 'docker_info', label: 'Docker System Info' },
- { value: 'docker_ps', label: 'List Containers' },
- { value: 'docker_images', label: 'List Images' },
- { value: 'system_info', label: 'System Information' },
- { value: 'agent_upgrade', label: 'Upgrade Agent' },
- { value: 'docker_prune', label: 'Docker Cleanup' },
- { value: 'custom', label: 'Custom Command' }
- ];
-
- // Keep only periodic refresh logic
- onMount(() => {
- // Refresh every 10 seconds for real-time updates
- const interval = setInterval(() => {
- refreshAgentData();
- }, 10000);
- return () => clearInterval(interval);
- });
-
- // Simplified refresh function - only for periodic updates
- async function refreshAgentData() {
- if (loading) return;
-
- try {
- loading = true;
-
- // Use parallel requests for updates
- const [agentResponse, tasksResponse, deploymentsResponse] = await Promise.allSettled([fetch(`/api/agents/${agentId}`), fetch(`/api/agents/${agentId}/tasks?admin=true`), fetch(`/api/agents/${agentId}/deployments`)]);
-
- // Update agent data
- if (agentResponse.status === 'fulfilled' && agentResponse.value.ok) {
- const agentData = await agentResponse.value.json();
- agent = agentData.agent;
- }
-
- // Update tasks
- if (tasksResponse.status === 'fulfilled' && tasksResponse.value.ok) {
- const tasksData = await tasksResponse.value.json();
- tasks = tasksData.tasks || [];
- }
-
- // Update deployments
- if (deploymentsResponse.status === 'fulfilled' && deploymentsResponse.value.ok) {
- const deploymentsData = await deploymentsResponse.value.json();
- deployments = deploymentsData.deployments || [];
- }
-
- error = '';
- } catch (err) {
- console.error('Failed to refresh agent data:', err);
- // Don't set error for refresh failures - keep showing existing data
- } finally {
- loading = false;
- }
- }
-
- async function loadResourcesData() {
- if (!agent || getActualAgentStatus(agent) !== 'online') {
- resourcesError = 'Agent must be online to load resource data';
- return;
- }
-
- resourcesLoading = true;
- resourcesError = '';
-
- try {
- const commands = [
- { type: 'docker_command', payload: { command: 'ps', args: ['-a', '--format', 'json'] } },
- { type: 'docker_command', payload: { command: 'images', args: ['--format', 'json'] } },
- {
- type: 'docker_command',
- payload: { command: 'network', args: ['ls', '--format', 'json'] }
- },
- {
- type: 'docker_command',
- payload: { command: 'volume', args: ['ls', '--format', 'json'] }
- },
- {
- type: 'docker_command',
- payload: { command: 'compose', args: ['ls', '--format', 'json'] }
- }
- ];
-
- const results = await Promise.allSettled(
- commands.map(async (cmd, index) => {
- const response = await fetch(`/api/agents/${agentId}/tasks`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(cmd)
- });
-
- if (!response.ok) throw new Error(`Failed to execute ${cmd.payload.command}`);
- const result = await response.json();
-
- console.log('Task creation response:', result);
-
- // The task ID should be in result.task.id based on the API endpoint
- if (!result.task?.id) {
- throw new Error(`No task ID returned for ${cmd.payload.command}`);
- }
-
- const taskId = result.task.id;
- return pollTaskCompletion(taskId, ['containers', 'images', 'networks', 'volumes', 'stacks'][index]);
- })
- );
-
- // Process results - replace the forEach loop
- const newResourcesData: {
- containers: any[];
- images: any[];
- networks: any[];
- volumes: any[];
- stacks: any[];
- } = {
- containers: [],
- images: [],
- networks: [],
- volumes: [],
- stacks: []
- };
-
- results.forEach((result, index) => {
- if (result.status === 'fulfilled' && result.value) {
- const resourceType = ['containers', 'images', 'networks', 'volumes', 'stacks'][index] as keyof typeof newResourcesData;
- console.log(`Assigning ${result.value.length} items to ${resourceType}:`, result.value);
- newResourcesData[resourceType] = result.value;
- } else {
- console.log(`Result ${index} failed:`, result);
- }
- });
-
- // Update the state with the new object
- resourcesData = newResourcesData;
- } catch (err) {
- console.error('Failed to load resources data:', err);
- resourcesError = err instanceof Error ? err.message : 'Failed to load resource data';
- toast.error('Failed to load resource data');
- } finally {
- resourcesLoading = false;
- }
- }
-
- async function pollTaskCompletion(taskId: string, resourceType: string): Promise<any[]> {
- const maxAttempts = 30; // 30 seconds max
- const delay = 1000; // 1 second
-
- console.log(`Polling task ${taskId} for ${resourceType}`);
-
- for (let i = 0; i < maxAttempts; i++) {
- await new Promise((resolve) => setTimeout(resolve, delay));
-
- try {
- const response = await fetch(`/api/agents/${agentId}/tasks/${taskId}`, {
- credentials: 'include'
- });
-
- console.log(`Task ${taskId} polling attempt ${i + 1}: ${response.status}`);
-
- if (!response.ok) {
- if (response.status === 403) {
- console.error(`Authentication failed for task ${taskId}`);
- }
- console.error(`Failed to fetch task ${taskId}: ${response.status} ${response.statusText}`);
- continue;
- }
-
- const responseData = await response.json();
- console.log(`Task ${taskId} response:`, responseData);
-
- const task = responseData.task;
-
- if (!task) {
- console.error(`No task data in response for ${taskId}`);
- continue;
- }
-
- console.log(`Task ${taskId} status: ${task.status}`);
-
- if (task.status === 'completed') {
- console.log(`Task ${taskId} completed with result:`, task.result);
-
- if (!task.result) {
- console.warn(`Task ${taskId} completed but has no result`);
- return [];
- }
-
- // Parse the result - the actual Docker output is in task.result.output
- let data: any[] = [];
- let outputString = '';
-
- // Extract the output string from the nested result structure
- if (task.result && typeof task.result === 'object' && task.result.output) {
- outputString = task.result.output;
- } else if (typeof task.result === 'string') {
- outputString = task.result;
- } else {
- console.warn(`Unexpected result format for task ${taskId}:`, task.result);
- return [];
- }
-
- console.log(`Raw output for ${resourceType}:`, outputString);
-
- if (outputString) {
- try {
- // First try to parse the entire output as JSON (for cases like compose ls that return an array)
- const parsed = JSON.parse(outputString);
- if (Array.isArray(parsed)) {
- data = parsed;
- console.log(`Parsed entire output as JSON array for ${resourceType}:`, data);
- } else {
- data.push(parsed);
- }
- } catch (parseError) {
- // If that fails, try parsing line by line
- const lines = outputString.split('\n').filter((line: string) => line.trim());
- console.log(`Task ${taskId} has ${lines.length} lines to parse`);
-
- for (const line of lines) {
- try {
- const parsed = JSON.parse(line.trim());
- data.push(parsed);
- } catch (lineParseError) {
- console.warn(`Failed to parse line as JSON:`, line, lineParseError);
- // Skip invalid JSON lines
- }
- }
- }
- }
- console.log(`Parsed data for ${resourceType}:`, data);
- return data;
- } else if (task.status === 'failed') {
- console.error(`Task ${taskId} failed:`, task.error);
- throw new Error(task.error || 'Task failed');
- } else if (task.status === 'running') {
- console.log(`Task ${taskId} is still running...`);
- } else {
- console.log(`Task ${taskId} is ${task.status}, continuing to poll...`);
- }
- } catch (err) {
- console.error(`Error polling task ${taskId}:`, err);
- // Don't break the loop on network errors, continue polling
- }
- }
-
- console.error(`Task ${taskId} timed out after ${maxAttempts} seconds`);
- throw new Error(`Task ${taskId} timed out after ${maxAttempts} seconds`);
- }
-
- async function sendCommand() {
- if (!selectedCommand || taskExecuting) return;
-
- taskExecuting = true;
- try {
- let payload: any = {};
-
- switch (selectedCommand.value) {
- case 'docker_version':
- payload = { command: 'version' };
- break;
- case 'docker_info':
- payload = { command: 'info' };
- break;
- case 'docker_ps':
- payload = { command: 'ps', args: ['-a'] };
- break;
- case 'docker_images':
- payload = { command: 'images' };
- break;
- case 'system_info':
- payload = { command: 'system', args: ['info'] };
- break;
- case 'agent_upgrade':
- payload = { action: 'upgrade' };
- break;
- case 'docker_prune':
- payload = { command: 'system', args: ['prune', '-f'] };
- break;
- case 'custom':
- if (!customCommand.trim()) {
- toast.error('Please enter a custom command');
- return;
- }
- const parts = customCommand.trim().split(' ');
- payload = {
- command: parts[0],
- args: parts.slice(1).concat(commandArgs ? commandArgs.split(' ') : [])
- };
- break;
- }
-
- const taskType = selectedCommand.value === 'agent_upgrade' ? 'agent_upgrade' : 'docker_command';
-
- const response = await fetch(`/api/agents/${agentId}/tasks`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- type: taskType,
- payload
- })
- });
-
- if (!response.ok) {
- throw new Error(`Failed to send command: ${response.statusText}`);
- }
-
- const result = await response.json();
- toast.success('Command sent successfully');
- commandDialogOpen = false;
-
- // Reset form
- selectedCommand = undefined;
- commandArgs = '';
- customCommand = '';
-
- // Refresh tasks
- setTimeout(refreshAgentData, 1000);
- } catch (err) {
- console.error('Failed to send command:', err);
- toast.error(err instanceof Error ? err.message : 'Failed to send command');
- } finally {
- taskExecuting = false;
- }
- }
-
- async function deleteAgentHandler() {
- if (!agent || deleting) return;
-
- openConfirmDialog({
- title: `Confirm Removal`,
- message: `Are you sure you want to remove this Agent? This action cannot be undone.`,
- confirm: {
- label: 'Remove',
- destructive: true,
- action: async () => {
- handleApiResultWithCallbacks({
- result: await tryCatch(
- fetch(`/api/agents/${agentId}`, {
- method: 'DELETE',
- credentials: 'include'
- })
- ),
- setLoadingState: (value) => (deleting = value),
- message: 'Failed to Remove Agent',
- onSuccess: async () => {
- toast.success('Agent Removed Successfully');
- await invalidateAll();
- goto('/agents');
- }
- });
- }
- }
- });
- }
-
- function getStatusClasses(agent: Agent) {
- const actualStatus = getActualAgentStatus(agent);
- if (actualStatus === 'online') return 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400';
- return 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400';
- }
-
- function getStatusText(agent: Agent) {
- const actualStatus = getActualAgentStatus(agent);
- if (actualStatus === 'online') return 'Online';
- return 'Offline';
- }
-
- function canSendCommands(agent: Agent) {
- return getActualAgentStatus(agent) === 'online';
- }
-
- function getTaskStatusClasses(status: string) {
- switch (status) {
- case 'completed':
- return 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400';
- case 'failed':
- return 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400';
- case 'running':
- return 'bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400';
- case 'pending':
- return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-400';
- default:
- return 'bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400';
- }
- }
-
- function formatBytes(bytes: number): string {
- if (bytes === 0) return '0 Bytes';
- const k = 1024;
- const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
- }
-
- function getContainerStatus(status: string): string {
- if (!status) return 'unknown';
- const statusLower = status.toLowerCase();
- if (statusLower.includes('up')) return 'running';
- if (statusLower.includes('exit')) return 'stopped';
- return statusLower;
- }
-
- async function handleStackDeploy(data: any) {
- try {
- const response = await fetch(`/api/agents/${agentId}/deploy/stack`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(data),
- credentials: 'include'
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.error || `Failed to deploy stack: ${response.statusText}`);
- }
-
- const result = await response.json();
- toast.success(`Stack deployment started: ${result.task?.id || 'Unknown task'}`);
-
- // Refresh deployments list
- setTimeout(() => refreshAgentData(), 1000);
- } catch (err) {
- console.error('Stack deploy error:', err);
- throw err;
- }
- }
-
- async function handleImagePull(imageName: string) {
- try {
- const response = await fetch(`/api/agents/${agentId}/deploy/image`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ imageName }),
- credentials: 'include'
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.error || `Failed to pull image: ${response.statusText}`);
- }
-
- const result = await response.json();
- toast.success(`Image pull started: ${result.task?.id || 'Unknown task'}`);
- } catch (err) {
- console.error('Image pull error:', err);
- throw err;
- }
- }
-
- async function handleContainerRun(data: any) {
- try {
- const response = await fetch(`/api/agents/${agentId}/deploy/container`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(data),
- credentials: 'include'
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.error || `Failed to run container: ${response.statusText}`);
- }
-
- const result = await response.json();
- toast.success(`Container started: ${result.task?.id || 'Unknown task'}`);
- } catch (err) {
- console.error('Container run error:', err);
- throw err;
- }
- }
-</script>
-
-<svelte:head>
- <title>Agent {agent?.hostname || agentId} - Arcane</title>
-</svelte:head>
-
-<div class="space-y-6">
- <!-- Breadcrumb -->
- <Breadcrumb.Root>
- <Breadcrumb.List>
- <Breadcrumb.Item>
- <Breadcrumb.Link href="/agents">Agents</Breadcrumb.Link>
- </Breadcrumb.Item>
- <Breadcrumb.Separator />
- <Breadcrumb.Item>
- <Breadcrumb.Page>{agent?.hostname || agentId}</Breadcrumb.Page>
- </Breadcrumb.Item>
- </Breadcrumb.List>
- </Breadcrumb.Root>
-
- <!-- Header -->
- <div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
- <div>
- <h1 class="text-3xl font-bold tracking-tight">
- {agent?.hostname || 'Agent Details'}
- </h1>
- <p class="text-muted-foreground mt-1 text-sm">
- {agent ? `Agent ID: ${agent.id}` : 'Loading agent information...'}
- </p>
- </div>
- <div class="flex items-center gap-2">
- <Button variant="outline" onclick={() => goto('/agents')}>
- <ArrowLeft class="mr-2 size-4" />
- Back to Agents
- </Button>
- {#if agent}
- <Button variant="destructive" onclick={deleteAgentHandler} disabled={deleting}>
- <Trash2 class="mr-2 size-4" />
- Delete Agent
- </Button>
- {#if getActualAgentStatus(agent) === 'online'}
- <Button onclick={() => (commandDialogOpen = true)} disabled={taskExecuting}>
- <Terminal class="mr-2 size-4" />
- Send Command
- </Button>
- {/if}
- {/if}
- </div>
- </div>
-
- <!-- Error State -->
- {#if error}
- <Alert.Root variant="destructive">
- <AlertCircle class="size-4" />
- <Alert.Title>Error</Alert.Title>
- <Alert.Description>{error}</Alert.Description>
- </Alert.Root>
- {:else if agent}
- <!-- Agent Overview -->
- <div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
- <Card.Root>
- <Card.Content class="flex items-center space-x-3 p-4">
- <div class="rounded-full bg-blue-500/10 p-2">
- <Server class="size-5 text-blue-500" />
- </div>
- <div>
- <p class="text-muted-foreground text-sm font-medium">Status</p>
- <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium {getStatusClasses(agent)}">
- {getStatusText(agent)}
- </span>
- </div>
- </Card.Content>
- </Card.Root>
-
- <Card.Root>
- <Card.Content class="flex items-center space-x-3 p-4">
- <div class="rounded-full bg-green-500/10 p-2">
- <Monitor class="size-5 text-green-500" />
- </div>
- <div>
- <p class="text-muted-foreground text-sm font-medium">Platform</p>
- <p class="font-semibold capitalize">{agent.platform}</p>
- </div>
- </Card.Content>
- </Card.Root>
-
- <Card.Root>
- <Card.Content class="flex items-center space-x-3 p-4">
- <div class="rounded-full bg-purple-500/10 p-2">
- <Settings class="size-5 text-purple-500" />
- </div>
- <div>
- <p class="text-muted-foreground text-sm font-medium">Version</p>
- <p class="font-semibold">{agent.version}</p>
- </div>
- </Card.Content>
- </Card.Root>
-
- <Card.Root>
- <Card.Content class="flex items-center space-x-3 p-4">
- <div class="rounded-full bg-amber-500/10 p-2">
- <Clock class="size-5 text-amber-500" />
- </div>
- <div>
- <p class="text-muted-foreground text-sm font-medium">Last Seen</p>
- <p class="text-sm font-semibold">{formatDistanceToNow(new Date(agent.lastSeen))} ago</p>
- </div>
- </Card.Content>
- </Card.Root>
- </div>
-
- <!-- Resource Metrics -->
- {#if agent.metrics}
- <DropdownCard id="agent-metrics" title="Resource Metrics" description="View detailed Docker resource information" defaultExpanded={false} icon={Activity}>
- <!-- Metrics Overview -->
- <div class="mb-6 grid grid-cols-2 gap-4 md:grid-cols-4">
- <div class="rounded-lg bg-blue-50 p-3 text-center dark:bg-blue-900/20">
- <Container class="mx-auto mb-1 size-6 text-blue-600 dark:text-blue-400" />
- <p class="text-2xl font-bold text-blue-600 dark:text-blue-400">
- {agent.metrics.containerCount ?? 0}
- </p>
- <p class="text-sm text-blue-600/80 dark:text-blue-400/80">Containers</p>
- </div>
- <div class="rounded-lg bg-green-50 p-3 text-center dark:bg-green-900/20">
- <HardDrive class="mx-auto mb-1 size-6 text-green-600 dark:text-green-400" />
- <p class="text-2xl font-bold text-green-600 dark:text-green-400">
- {agent.metrics.imageCount ?? 0}
- </p>
- <p class="text-sm text-green-600/80 dark:text-green-400/80">Images</p>
- </div>
- <div class="rounded-lg bg-orange-50 p-3 text-center dark:bg-orange-900/20">
- <Network class="mx-auto mb-1 size-6 text-orange-600 dark:text-orange-400" />
- <p class="text-2xl font-bold text-orange-600 dark:text-orange-400">
- {agent.metrics.networkCount ?? 0}
- </p>
- <p class="text-sm text-orange-600/80 dark:text-orange-400/80">Networks</p>
- </div>
- <div class="rounded-lg bg-cyan-50 p-3 text-center dark:bg-cyan-900/20">
- <Database class="mx-auto mb-1 size-6 text-cyan-600 dark:text-cyan-400" />
- <p class="text-2xl font-bold text-cyan-600 dark:text-cyan-400">
- {agent.metrics.volumeCount ?? 0}
- </p>
- <p class="text-sm text-cyan-600/80 dark:text-cyan-400/80">Volumes</p>
- </div>
- </div>
-
- <!-- Resources Data Section -->
- {#if agent.status === 'online'}
- <div class="border-border space-y-4 border-t pt-4">
- <div class="flex items-center justify-between">
- <div>
- <h4 class="mb-1 font-medium">Resource Details</h4>
- <p class="text-muted-foreground text-sm">View detailed information about Docker resources</p>
- </div>
- <Button variant="outline" size="sm" onclick={loadResourcesData} disabled={resourcesLoading}>
- {#if resourcesLoading}
- <Loader2 class="mr-2 size-4 animate-spin" />
- Loading...
- {:else}
- <RefreshCw class="mr-2 size-4" />
- Load Resources
- {/if}
- </Button>
- </div>
-
- {#if resourcesError}
- <Alert.Root variant="destructive">
- <AlertCircle class="size-4" />
- <Alert.Title>Error Loading Resources</Alert.Title>
- <Alert.Description>{resourcesError}</Alert.Description>
- </Alert.Root>
- {/if}
-
- <!-- Resource Tables -->
- <!-- Always show tabs if any resource loading has been attempted -->
- {#if resourcesData.containers.length > 0 || resourcesData.images.length > 0 || resourcesData.networks.length > 0 || resourcesData.volumes.length > 0 || resourcesData.stacks.length > 0}
- <Tabs.Root value="containers" class="w-full">
- <Tabs.List class="grid w-full grid-cols-5">
- <Tabs.Trigger value="containers" class="flex items-center gap-2">
- <Container class="size-4" />
- Containers ({resourcesData.containers.length})
- </Tabs.Trigger>
- <Tabs.Trigger value="images" class="flex items-center gap-2">
- <HardDrive class="size-4" />
- Images ({resourcesData.images.length})
- </Tabs.Trigger>
- <Tabs.Trigger value="networks" class="flex items-center gap-2">
- <Network class="size-4" />
- Networks ({resourcesData.networks.length})
- </Tabs.Trigger>
- <Tabs.Trigger value="volumes" class="flex items-center gap-2">
- <Database class="size-4" />
- Volumes ({resourcesData.volumes.length})
- </Tabs.Trigger>
- <Tabs.Trigger value="stacks" class="flex items-center gap-2">
- <Layers class="size-4" />
- Compose Projects ({resourcesData.stacks.length})
- </Tabs.Trigger>
- </Tabs.List>
-
- <!-- Containers Tab -->
- <Tabs.Content value="containers" class="mt-4">
- {#if resourcesData.containers.length > 0}
- <UniversalTable
- data={resourcesData.containers}
- columns={[
- { accessorKey: 'Names', header: 'Name' },
- { accessorKey: 'Image', header: 'Image' },
- { accessorKey: 'Status', header: 'Status' },
- { accessorKey: 'Ports', header: 'Ports' },
- { accessorKey: 'CreatedAt', header: 'Created' }
- ]}
- idKey="ID"
- features={{ selection: false }}
- display={{
- filterPlaceholder: 'Search containers...',
- noResultsMessage: 'No containers found'
- }}
- pagination={{ pageSize: 10 }}
- />
- {:else}
- <div class="text-muted-foreground py-8 text-center">
- <Container class="mx-auto mb-4 size-12 opacity-50" />
- <p>No containers found</p>
- </div>
- {/if}
- </Tabs.Content>
-
- <!-- Images Tab -->
- <Tabs.Content value="images" class="mt-4">
- {#if resourcesData.images.length > 0}
- <UniversalTable
- data={resourcesData.images}
- columns={[
- { accessorKey: 'Repository', header: 'Repository' },
- { accessorKey: 'Tag', header: 'Tag' },
- { accessorKey: 'ID', header: 'Image ID' },
- { accessorKey: 'CreatedAt', header: 'Created' },
- { accessorKey: 'Size', header: 'Size' }
- ]}
- idKey="ID"
- features={{ selection: false }}
- display={{
- filterPlaceholder: 'Search images...',
- noResultsMessage: 'No images found'
- }}
- pagination={{ pageSize: 10 }}
- />
- {:else}
- <div class="text-muted-foreground py-8 text-center">
- <HardDrive class="mx-auto mb-4 size-12 opacity-50" />
- <p>No images found</p>
- </div>
- {/if}
- </Tabs.Content>
-
- <!-- Networks Tab -->
- <Tabs.Content value="networks" class="mt-4">
- {#if resourcesData.networks.length > 0}
- <UniversalTable
- data={resourcesData.networks}
- columns={[
- { accessorKey: 'Name', header: 'Name' },
- { accessorKey: 'Driver', header: 'Driver' },
- { accessorKey: 'Scope', header: 'Scope' },
- { accessorKey: 'ID', header: 'Network ID' },
- { accessorKey: 'CreatedAt', header: 'Created' }
- ]}
- idKey="ID"
- features={{ selection: false }}
- display={{
- filterPlaceholder: 'Search networks...',
- noResultsMessage: 'No networks found'
- }}
- pagination={{ pageSize: 10 }}
- />
- {:else}
- <div class="text-muted-foreground py-8 text-center">
- <Network class="mx-auto mb-4 size-12 opacity-50" />
- <p>No networks found</p>
- </div>
- {/if}
- </Tabs.Content>
-
- <!-- Volumes Tab -->
- <Tabs.Content value="volumes" class="mt-4">
- {#if resourcesData.volumes.length > 0}
- <UniversalTable
- data={resourcesData.volumes}
- columns={[
- { accessorKey: 'Name', header: 'Name' },
- { accessorKey: 'Driver', header: 'Driver' },
- { accessorKey: 'Mountpoint', header: 'Mountpoint' },
- { accessorKey: 'CreatedAt', header: 'Created' }
- ]}
- idKey="Name"
- features={{ selection: false }}
- display={{
- filterPlaceholder: 'Search volumes...',
- noResultsMessage: 'No volumes found'
- }}
- pagination={{ pageSize: 10 }}
- />
- {:else}
- <div class="text-muted-foreground py-8 text-center">
- <Database class="mx-auto mb-4 size-12 opacity-50" />
- <p>No volumes found</p>
- </div>
- {/if}
- </Tabs.Content>
-
- <!-- Stacks Tab -->
- <Tabs.Content value="stacks" class="mt-4">
- {#if resourcesData.stacks.length > 0}
- <UniversalTable
- data={resourcesData.stacks}
- columns={[
- { accessorKey: 'Name', header: 'Project Name' },
- { accessorKey: 'Status', header: 'Status' },
- { accessorKey: 'ConfigFiles', header: 'Config Files' }
- ]}
- idKey="Name"
- features={{ selection: false }}
- display={{
- filterPlaceholder: 'Search compose projects...',
- noResultsMessage: 'No compose projects found'
- }}
- pagination={{ pageSize: 10 }}
- />
- {:else}
- <div class="text-muted-foreground py-8 text-center">
- <Layers class="mx-auto mb-4 size-12 opacity-50" />
- <p>No compose projects found</p>
- </div>
- {/if}
- </Tabs.Content>
- </Tabs.Root>
- {:else}
- <!-- Show this only when no data has been loaded yet -->
- <div class="text-muted-foreground py-8 text-center">
- <Database class="mx-auto mb-4 size-12 opacity-50" />
- <p class="font-medium">No Resource Data Loaded</p>
- <p class="text-sm">Click "Load Resources" to fetch Docker resource information</p>
- </div>
- {/if}
- </div>
- {/if}
-
- {#if getActualAgentStatus(agent) === 'online'}
- <div class="border-border space-y-4 border-t pt-4">
- <div class="flex items-center justify-between">
- <div>
- <h4 class="mb-1 font-medium">Deploy Resources</h4>
- <p class="text-muted-foreground text-sm">Deploy stacks, containers, or images to this agent</p>
- </div>
- </div>
-
- <!-- Quick Deploy Cards -->
- <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
- <!-- Deploy Stack Card -->
- <Card.Root class="hover:border-primary/50 cursor-pointer transition-colors" onclick={() => (deployDialogOpen = true)}>
- <Card.Content class="p-4">
- <div class="flex items-center space-x-3">
- <div class="rounded-lg bg-blue-500/10 p-2">
- <Layers class="size-5 text-blue-500" />
- </div>
- <div>
- <h5 class="font-medium">Deploy Stack</h5>
- <p class="text-muted-foreground text-sm">Deploy a complete application stack</p>
- </div>
- </div>
- </Card.Content>
- </Card.Root>
-
- <!-- Pull Image Card -->
- <Card.Root class="hover:border-primary/50 cursor-pointer transition-colors" onclick={() => (imageDialogOpen = true)}>
- <Card.Content class="p-4">
- <div class="flex items-center space-x-3">
- <div class="rounded-lg bg-green-500/10 p-2">
- <Download class="size-5 text-green-500" />
- </div>
- <div>
- <h5 class="font-medium">Pull Image</h5>
- <p class="text-muted-foreground text-sm">Download a Docker image</p>
- </div>
- </div>
- </Card.Content>
- </Card.Root>
-
- <!-- Quick Container Card -->
- <Card.Root class="hover:border-primary/50 cursor-pointer transition-colors" onclick={() => (containerDialogOpen = true)}>
- <Card.Content class="p-4">
- <div class="flex items-center space-x-3">
- <div class="rounded-lg bg-purple-500/10 p-2">
- <Container class="size-5 text-purple-500" />
- </div>
- <div>
- <h5 class="font-medium">Run Container</h5>
- <p class="text-muted-foreground text-sm">Start a single container</p>
- </div>
- </div>
- </Card.Content>
- </Card.Root>
- </div>
-
- <!-- Recent Deployments -->
- {#if deployments.length > 0}
- <div class="space-y-2">
- <h5 class="font-medium">Recent Deployments</h5>
- <div class="space-y-2">
- {#each deployments.slice(0, 3) as deployment}
- <div class="bg-muted/30 flex items-center justify-between rounded-lg p-3">
- <div class="flex items-center space-x-3">
- <div class="rounded bg-blue-500/10 p-1.5">
- {#if deployment.type === 'stack'}
- <Layers class="size-4 text-blue-500" />
- {:else if deployment.type === 'image'}
- <Download class="size-4 text-green-500" />
- {:else}
- <Container class="size-4 text-purple-500" />
- {/if}
- </div>
- <div>
- <p class="text-sm font-medium">{deployment.name}</p>
- <p class="text-muted-foreground text-xs">
- {deployment.type} • {formatDistanceToNow(new Date(deployment.createdAt))} ago
- </p>
- </div>
- </div>
- <StatusBadge variant={deployment.status === 'running' ? 'green' : deployment.status === 'failed' ? 'red' : 'amber'} text={deployment.status} />
- </div>
- {/each}
- </div>
- </div>
- {/if}
- </div>
- {/if}
- </DropdownCard>
- {/if}
-
- <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
- <!-- Agent Information -->
- <Card.Root>
- <Card.Header>
- <Card.Title>Agent Information</Card.Title>
- </Card.Header>
- <Card.Content class="space-y-4">
- <div class="grid grid-cols-2 gap-4 text-sm">
- <div>
- <span class="text-muted-foreground">Hostname</span>
- <p class="font-medium">{agent.hostname}</p>
- </div>
- <div>
- <span class="text-muted-foreground">Agent ID</span>
- <p class="font-mono text-xs">{agent.id}</p>
- </div>
- <div>
- <span class="text-muted-foreground">Created</span>
- <p class="font-medium">{new Date(agent.createdAt).toLocaleDateString()}</p>
- </div>
- <div>
- <span class="text-muted-foreground">Updated</span>
- <p class="font-medium">
- {agent.updatedAt ? new Date(agent.updatedAt).toLocaleDateString() : 'Never'}
- </p>
- </div>
- </div>
-
- <div>
- <span class="text-muted-foreground text-sm">Capabilities</span>
- <div class="mt-1 flex flex-wrap gap-1">
- {#each agent.capabilities as capability}
- <span class="inline-flex items-center rounded bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
- {capability}
- </span>
- {:else}
- <span class="text-muted-foreground text-sm">None</span>
- {/each}
- </div>
- </div>
-
- {#if agent.dockerInfo}
- <div class="border-t pt-4">
- <h4 class="mb-3 font-medium">Docker Information</h4>
- <div class="grid grid-cols-2 gap-4 text-sm">
- <div>
- <span class="text-muted-foreground">Docker Version</span>
- <p class="font-medium">{agent.dockerInfo.version}</p>
- </div>
- <div>
- <span class="text-muted-foreground">Containers</span>
- <p class="font-medium">{agent.dockerInfo.containers}</p>
- </div>
- <div>
- <span class="text-muted-foreground">Images</span>
- <p class="font-medium">{agent.dockerInfo.images}</p>
- </div>
- </div>
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
-
- <!-- Recent Tasks -->
- <Card.Root>
- <Card.Header>
- <div class="flex items-center justify-between">
- <Card.Title>Recent Tasks</Card.Title>
- <Button variant="outline" size="sm" onclick={refreshAgentData}>
- <RefreshCw class="size-4" />
- </Button>
- </div>
- </Card.Header>
- <Card.Content>
- {#if tasks.length > 0}
- <div class="max-h-96 space-y-3 overflow-y-auto">
- {#each tasks.slice(0, 10) as task}
- <div class="rounded-lg border p-3">
- <div class="mb-2 flex items-center justify-between">
- <div class="flex items-center gap-2">
- <p class="text-sm font-medium">
- {task.type.replace('_', ' ').replace(/\b\w/g, (l) => l.toUpperCase())}
- </p>
- <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium {getTaskStatusClasses(task.status)}">
- {task.status}
- </span>
- </div>
- <p class="text-muted-foreground text-xs">
- {formatDistanceToNow(new Date(task.createdAt))} ago
- </p>
- </div>
-
- <!-- Show command details -->
- {#if task.payload?.command}
- <div class="text-muted-foreground mb-2 text-xs">
- <code class="bg-muted rounded px-1">
- {task.payload.command}
- {#if task.payload.args?.length > 0}
- {task.payload.args.join(' ')}
- {/if}
- </code>
- </div>
- {/if}
-
- <!-- Show results for completed tasks -->
- {#if task.status === 'completed' && task.result}
- <details class="mt-2">
- <summary class="cursor-pointer text-xs text-green-600 hover:text-green-500"> View Output </summary>
- <div class="bg-muted mt-2 max-h-32 overflow-y-auto rounded p-2 font-mono text-xs whitespace-pre-wrap">
- {typeof task.result === 'string' ? task.result : JSON.stringify(task.result, null, 2)}
- </div>
- </details>
- {/if}
-
- <!-- Show errors for failed tasks -->
- {#if task.error}
- <details class="mt-2">
- <summary class="cursor-pointer text-xs text-red-600 hover:text-red-500"> View Error </summary>
- <div class="mt-2 max-h-32 overflow-y-auto rounded bg-red-50 p-2 text-xs text-red-600 dark:bg-red-900/20 dark:text-red-400">
- {task.error}
- </div>
- </details>
- {/if}
- </div>
- {/each}
- </div>
- {:else}
- <div class="text-muted-foreground py-8 text-center">
- <Activity class="mx-auto mb-4 size-12 opacity-50" />
- <p>No tasks executed yet</p>
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
- </div>
-
- <!-- Connection Status Banner -->
- {#if agent && !canSendCommands(agent)}
- <Alert.Root variant="destructive">
- <AlertCircle class="size-4" />
- <Alert.Title>Agent Offline</Alert.Title>
- <Alert.Description>This agent is not currently connected. Commands cannot be sent until the agent reconnects.</Alert.Description>
- </Alert.Root>
- {/if}
- {/if}
-</div>
-
-<!-- Send Command Dialog -->
-<Dialog.Root bind:open={commandDialogOpen}>
- <Dialog.Content class="sm:max-w-md">
- <Dialog.Header>
- <Dialog.Title>Send Command to Agent</Dialog.Title>
- <Dialog.Description>
- Execute a command on {agent?.hostname}
- </Dialog.Description>
- </Dialog.Header>
- <div class="space-y-4">
- <div>
- <Label for="command-select">Command</Label>
- <Select.Root type="single" value={selectedCommand?.value} onValueChange={(v) => (selectedCommand = predefinedCommands.find((cmd) => cmd.value === v))}>
- <Select.Trigger>
- <span>{selectedCommand?.label || 'Select a command'}</span>
- </Select.Trigger>
- <Select.Content>
- {#each predefinedCommands as command}
- <Select.Item value={command.value}>{command.label}</Select.Item>
- {/each}
- </Select.Content>
- </Select.Root>
- </div>
-
- {#if selectedCommand?.value === 'custom'}
- <div>
- <Label for="custom-command">Custom Command</Label>
- <Input id="custom-command" bind:value={customCommand} placeholder="docker ps -a" disabled={taskExecuting} />
- </div>
- {/if}
-
- {#if selectedCommand && selectedCommand.value !== 'agent_upgrade'}
- <div>
- <Label for="command-args">Additional Arguments (optional)</Label>
- <Input id="command-args" bind:value={commandArgs} placeholder="--format table" disabled={taskExecuting} />
- </div>
- {/if}
- </div>
- <Dialog.Footer>
- <Button variant="outline" onclick={() => (commandDialogOpen = false)} disabled={taskExecuting}>Cancel</Button>
- <Button onclick={sendCommand} disabled={!selectedCommand || taskExecuting}>
- {#if taskExecuting}
- <RefreshCw class="mr-2 size-4 animate-spin" />
- Sending...
- {:else}
- <Play class="mr-2 size-4" />
- Send Command
- {/if}
- </Button>
- </Dialog.Footer>
- </Dialog.Content>
-</Dialog.Root>
-
-<!-- Stack Deployment Dialog -->
-<Dialog.Root bind:open={deployDialogOpen}>
- <Dialog.Content class="sm:max-w-2xl">
- <Dialog.Header>
- <Dialog.Title>Deploy Stack to {agent?.hostname}</Dialog.Title>
- <Dialog.Description>Choose a stack to deploy or create a new one</Dialog.Description>
- </Dialog.Header>
-
- <StackDeploymentForm {agentId} onClose={() => (deployDialogOpen = false)} onDeploy={handleStackDeploy} />
- </Dialog.Content>
-</Dialog.Root>
-
-<!-- Image Pull Dialog -->
-<Dialog.Root bind:open={imageDialogOpen}>
- <Dialog.Content class="sm:max-w-md">
- <Dialog.Header>
- <Dialog.Title>Pull Image to {agent?.hostname}</Dialog.Title>
- <Dialog.Description>Enter the image name to download</Dialog.Description>
- </Dialog.Header>
-
- <ImagePullForm {agentId} onClose={() => (imageDialogOpen = false)} onPull={handleImagePull} />
- </Dialog.Content>
-</Dialog.Root>
-
-<!-- Quick Container Dialog -->
-<Dialog.Root bind:open={containerDialogOpen}>
- <Dialog.Content class="sm:max-w-xl">
- <Dialog.Header>
- <Dialog.Title>Run Container on {agent?.hostname}</Dialog.Title>
- <Dialog.Description>Quickly start a container from an image</Dialog.Description>
- </Dialog.Header>
-
- <QuickContainerForm {agentId} onClose={() => (containerDialogOpen = false)} onRun={handleContainerRun} />
- </Dialog.Content>
-</Dialog.Root>
diff --git a/frontend/src/routes/agents/[agentId]/+page.ts b/frontend/src/routes/agents/[agentId]/+page.ts
deleted file mode 100644
index bcb231a6b..000000000
--- a/frontend/src/routes/agents/[agentId]/+page.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import type { PageLoad } from './$types';
-import { agentAPI, deploymentAPI } from '$lib/services/api';
-import { error } from '@sveltejs/kit';
-
-export const load: PageLoad = async ({ params }) => {
- const { agentId } = params;
-
- try {
- // Load all data in parallel using API services
- const [agent, tasks, deployments] = await Promise.allSettled([agentAPI.get(agentId), agentAPI.getTasks(agentId), deploymentAPI.getByAgent(agentId)]);
-
- // Handle agent not found
- if (agent.status === 'rejected' || !agent.value) {
- throw error(404, {
- message: 'Agent not found'
- });
- }
-
- // Get agent status from API (this now includes the timeout logic)
- let agentStatus = { status: 'unknown' };
- try {
- agentStatus = await agentAPI.getStatus(agentId);
- } catch (statusError) {
- console.warn('Failed to get agent status:', statusError);
- }
-
- const agentWithStatus = {
- ...agent.value,
- status: agentStatus.status
- };
-
- return {
- agent: agentWithStatus,
- tasks: tasks.status === 'fulfilled' ? tasks.value : [],
- deployments: deployments.status === 'fulfilled' ? deployments.value : [],
- agentId
- };
- } catch (err) {
- console.error('Failed to load agent data:', err);
- throw error(500, {
- message: err instanceof Error ? err.message : 'Failed to load agent data'
- });
- }
-};
diff --git a/frontend/src/routes/compose/+page.svelte b/frontend/src/routes/compose/+page.svelte
index c15742f01..809a1dfce 100644
--- a/frontend/src/routes/compose/+page.svelte
+++ b/frontend/src/routes/compose/+page.svelte
@@ -14,13 +14,12 @@
import { statusVariantMap } from '$lib/types/statuses';
import { toast } from 'svelte-sonner';
import { tryCatch } from '$lib/utils/try-catch';
- import StackAPIService from '$lib/services/api/stack-api-service';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import type { StackActions } from '$lib/types/actions.type';
import ArcaneButton from '$lib/components/arcane-button.svelte';
import { tablePersistence } from '$lib/stores/table-store';
import { formatFriendlyDate } from '$lib/utils/date.utils';
- import { autoUpdateAPI } from '$lib/services/api';
+ import { autoUpdateAPI, environmentAPI } from '$lib/services/api';
let { data }: { data: PageData } = $props();
@@ -37,8 +36,6 @@
});
const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
- const stackApi = new StackAPIService();
-
const totalStacks = $derived(stacks.length);
const runningStacks = $derived(stacks.filter((s) => s.status === 'running').length);
const stoppedStacks = $derived(stacks.filter((s) => s.status === 'stopped').length);
@@ -49,7 +46,7 @@
try {
if (action === 'start') {
handleApiResultWithCallbacks({
- result: await tryCatch(stackApi.deploy(id)),
+ result: await tryCatch(environmentAPI.startStack(id)),
message: 'Failed to Start Stack',
setLoadingState: (value) => (isLoading.start = value),
onSuccess: async () => {
@@ -59,7 +56,7 @@
});
} else if (action === 'stop') {
handleApiResultWithCallbacks({
- result: await tryCatch(stackApi.down(id)),
+ result: await tryCatch(environmentAPI.downStack(id)),
message: 'Failed to Stop Stack',
setLoadingState: (value) => (isLoading.stop = value),
onSuccess: async () => {
@@ -69,7 +66,7 @@
});
} else if (action === 'restart') {
handleApiResultWithCallbacks({
- result: await tryCatch(stackApi.restart(id)),
+ result: await tryCatch(environmentAPI.restartStack(id)),
message: 'Failed to Restart Stack',
setLoadingState: (value) => (isLoading.restart = value),
onSuccess: async () => {
@@ -79,7 +76,7 @@
});
} else if (action === 'pull') {
handleApiResultWithCallbacks({
- result: await tryCatch(stackApi.pull(id)),
+ result: await tryCatch(environmentAPI.pullStackImages(id)),
message: 'Failed to pull Stack',
setLoadingState: (value) => (isLoading.pull = value),
onSuccess: async () => {
@@ -96,7 +93,7 @@
destructive: true,
action: async () => {
handleApiResultWithCallbacks({
- result: await tryCatch(stackApi.destroy(id)),
+ result: await tryCatch(environmentAPI.destroyStack(id)),
message: 'Failed to Remove Stack',
setLoadingState: (value) => (isLoading.destroy = value),
onSuccess: async () => {
diff --git a/frontend/src/routes/compose/+page.ts b/frontend/src/routes/compose/+page.ts
index b2b8259b6..d6874d5ac 100644
--- a/frontend/src/routes/compose/+page.ts
+++ b/frontend/src/routes/compose/+page.ts
@@ -1,12 +1,12 @@
-import { stackAPI } from '$lib/services/api';
+import { environmentAPI } from '$lib/services/api';
export const load = async () => {
try {
// Load managed stacks
- const response = await stackAPI.list();
+ const response = await environmentAPI.getStacks();
// Extract stacks from the API response structure
- const stacks = response.stacks || [];
+ const stacks = response || [];
return {
stacks,
diff --git a/frontend/src/routes/compose/[composeId]/+page.svelte b/frontend/src/routes/compose/[composeId]/+page.svelte
index 21b00cd1e..88b487c66 100644
--- a/frontend/src/routes/compose/[composeId]/+page.svelte
+++ b/frontend/src/routes/compose/[composeId]/+page.svelte
@@ -1,9 +1,9 @@
<script lang="ts">
import type { PageData } from './$types';
- import type { Stack, StackService, StackPort } from '$lib/types/docker/stack.type';
+ import type { Stack, StackService, StackPort } from '$lib/models/stack.type';
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import { ArrowLeft, AlertCircle, FileStack, Layers, ArrowRight, ExternalLink, RefreshCw, Terminal, Settings, Activity, FileText, Play, Square, RotateCcw, Trash2, Send, Users, Loader2, TicketCheck } from '@lucide/svelte';
+ import { ArrowLeft, AlertCircle, FileStack, Layers, ArrowRight, ExternalLink, RefreshCw, Terminal, Settings, Activity } from '@lucide/svelte';
import * as Alert from '$lib/components/ui/alert/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { Label } from '$lib/components/ui/label/index.js';
@@ -16,14 +16,10 @@
import YamlEditor from '$lib/components/yaml-editor.svelte';
import EnvEditor from '$lib/components/env-editor.svelte';
import { tryCatch } from '$lib/utils/try-catch';
- import StackAPIService from '$lib/services/api/stack-api-service';
+ import { environmentAPI } from '$lib/services/api';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import ArcaneButton from '$lib/components/arcane-button.svelte';
import LogViewer from '$lib/components/LogViewer.svelte';
- import * as Dialog from '$lib/components/ui/dialog/index.js';
- import * as Select from '$lib/components/ui/select/index.js';
-
- const stackApi = new StackAPIService();
let { data }: { data: PageData } = $props();
let { stack, editorState, servicePorts, settings } = $derived(data);
@@ -56,13 +52,6 @@
let isStackLogsStreaming = $state(false);
let stackLogViewer = $state<LogViewer>();
- let deployDialogOpen = $state(false);
- let deploying = $state(false);
- let selectedAgentId = $state('');
-
- // Get online agents for deployment
- const onlineAgents = $derived((data.agents || []).filter((agent) => agent.status === 'online'));
-
$effect(() => {
isLoading.deploying = false;
isLoading.stopping = false;
@@ -77,7 +66,7 @@
const currentStackId = stack.id;
handleApiResultWithCallbacks({
- result: await tryCatch(stackApi.save(currentStackId, name, composeContent, envContent)),
+ result: await tryCatch(environmentAPI.updateStack(currentStackId, composeContent, envContent)),
message: 'Failed to Save Compose Project',
setLoadingState: (value) => (isLoading.saving = value),
onSuccess: async (updatedStack: Stack) => {
@@ -100,53 +89,6 @@
});
}
- async function handleDeployToAgent() {
- if (!selectedAgentId) {
- toast.error('Please select an agent for deployment');
- return;
- }
-
- const selectedAgent = onlineAgents.find((agent) => agent.id === selectedAgentId);
- if (!selectedAgent) {
- toast.error('Selected agent not found or offline');
- return;
- }
-
- if (!data.stack) {
- toast.error('Stack data not available');
- return;
- }
-
- deploying = true;
- try {
- const response = await fetch(`/api/agents/${selectedAgentId}/deploy/stack`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- stackName: data.stack.name,
- composeContent: data.stack.composeContent,
- envContent: data.stack.envContent,
- mode: 'compose'
- })
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.error || `Failed to deploy stack: ${response.statusText}`);
- }
-
- const result = await response.json();
- toast.success(`Stack "${data.stack?.name || 'Unknown'}" deployed to agent ${selectedAgent.hostname}!`);
- deployDialogOpen = false;
- selectedAgentId = '';
- } catch (error) {
- console.error('Deploy error:', error);
- toast.error(error instanceof Error ? error.message : 'Failed to deploy stack');
- } finally {
- deploying = false;
- }
- }
-
function getHostForService(service: StackService): string {
if (!service || !service.networkSettings?.Networks) return baseServerUrl;
@@ -198,15 +140,10 @@
isStackLogsStreaming = false;
}
- function handleStackLogClear() {
- // Custom logic when logs are cleared if needed
- }
+ function handleStackLogClear() {}
- function handleToggleStackAutoScroll() {
- // Custom logic when auto-scroll is toggled if needed
- }
+ function handleToggleStackAutoScroll() {}
- // Navigation sections for single-page layout
const navigationSections = [
{ id: 'overview', label: 'Overview', icon: FileStack },
{ id: 'services', label: 'Services', icon: Layers },
@@ -227,7 +164,6 @@
<div class="bg-background min-h-screen">
{#if stack}
- <!-- Fixed Header -->
<div class="bg-background/95 sticky top-0 z-10 border-b backdrop-blur">
<div class="max-w-full px-4 py-3">
<div class="flex items-center justify-between">
@@ -260,18 +196,11 @@
}}
onActionComplete={() => invalidateAll()}
/>
- {#if onlineAgents.length > 0}
- <Button variant="outline" size="sm" onclick={() => (deployDialogOpen = true)} disabled={Object.values(isLoading).some(Boolean)}>
- <Send class="mr-2 size-4" />
- Deploy to Agent
- </Button>
- {/if}
</div>
</div>
</div>
</div>
- <!-- Error Alert -->
{#if data.error}
<div class="max-w-full px-4 py-4">
<Alert.Root variant="destructive">
@@ -283,7 +212,6 @@
{/if}
<div class="flex h-[calc(100vh-64px)]">
- <!-- Fixed Sidebar Navigation - Narrower -->
<div class="bg-background/50 w-48 shrink-0 border-r">
<div class="sticky top-16 p-3">
<nav class="space-y-1">
@@ -292,7 +220,7 @@
<button
onclick={() => scrollToSection(section.id)}
class="flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors
- {activeSection === section.id ? 'bg-primary/10 text-primary border-primary/20 border' : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'}"
+ {activeSection === section.id ? 'bg-primary/10 text-primary border-primary/20 border' : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'}"
>
<IconComponent class="size-4 shrink-0" />
<span class="truncate">{section.label}</span>
@@ -307,18 +235,15 @@
</div>
</div>
- <!-- Main Content - Full width usage -->
<div class="flex-1 overflow-y-auto">
<div class="max-w-none p-6">
<div class="space-y-8">
- <!-- Overview Section -->
<section id="overview" class="scroll-mt-20">
<h2 class="mb-6 flex items-center gap-2 text-xl font-semibold">
<FileStack class="size-5" />
Overview
</h2>
- <!-- Summary Cards -->
<div class="mb-6 grid grid-cols-1 gap-6 md:grid-cols-3">
<Card.Root class="border">
<Card.Content class="flex items-center justify-between p-6">
@@ -359,7 +284,6 @@
</Card.Root>
</div>
- <!-- Port Information -->
{#if servicePorts && Object.keys(servicePorts).length > 0}
{@const allUniquePorts = [...new Set(Object.values(servicePorts).flat())]}
<Card.Root class="border">
@@ -369,7 +293,8 @@
<Card.Content>
<div class="flex flex-wrap gap-2">
{#each allUniquePorts as port (port)}
- <a href={getServicePortUrl(stack, port)} target="_blank" rel="noopener noreferrer" class="inline-flex items-center rounded-md bg-blue-500/10 px-3 py-2 font-medium text-blue-600 transition-colors hover:bg-blue-500/20 dark:text-blue-400">
+ {@const portValue = typeof port === 'string' || typeof port === 'number' || (typeof port === 'object' && port !== null) ? port : String(port)}
+ <a href={getServicePortUrl(stack, portValue)} target="_blank" rel="noopener noreferrer" class="inline-flex items-center rounded-md bg-blue-500/10 px-3 py-2 font-medium text-blue-600 transition-colors hover:bg-blue-500/20 dark:text-blue-400">
Port {port}
<ExternalLink class="ml-2 size-4" />
</a>
@@ -380,7 +305,6 @@
{/if}
</section>
- <!-- Services Section -->
<section id="services" class="scroll-mt-20">
<h2 class="mb-6 flex items-center gap-2 text-xl font-semibold">
<Layers class="size-5" />
@@ -396,7 +320,6 @@
{@const variant = statusVariantMap[status.toLowerCase()] || 'gray'}
{#if service.container_id}
- <!-- Service with Container ID (clickable) -->
<a href={`/containers/${service.container_id}`} class="hover:bg-muted/50 flex items-center justify-between rounded-lg border p-4 transition-colors">
<div class="flex items-center gap-3">
<div class="bg-primary/10 rounded-full p-2">
@@ -420,7 +343,6 @@
</div>
</a>
{:else}
- <!-- Service without Container ID (not clickable) -->
<div class="bg-muted/20 flex items-center justify-between rounded-lg border p-4">
<div class="flex items-center gap-3">
<div class="bg-muted/50 rounded-full p-2">
@@ -453,7 +375,6 @@
</Card.Root>
</section>
- <!-- Configuration Section -->
<section id="config" class="scroll-mt-20">
<div class="mb-6 flex items-center justify-between">
<h2 class="flex items-center gap-2 text-xl font-semibold">
@@ -465,7 +386,6 @@
{/if}
</div>
- <!-- Stack Name Field -->
<Card.Root class="mb-6 border">
<Card.Header class="pb-4">
<Card.Title>Stack Settings</Card.Title>
@@ -481,9 +401,7 @@
</Card.Content>
</Card.Root>
- <!-- Editors - Fixed Layout -->
<div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
- <!-- Compose Editor - Spans 2 columns -->
<div class="lg:col-span-2">
<Card.Root class="h-full border">
<Card.Header class="flex-shrink-0 pb-4">
@@ -500,7 +418,6 @@
</Card.Root>
</div>
- <!-- Environment Editor - Spans 1 column -->
<div class="lg:col-span-1">
<Card.Root class="h-full border">
<Card.Header class="flex-shrink-0 pb-4">
@@ -517,7 +434,6 @@
</div>
</section>
- <!-- Logs Section -->
<section id="logs" class="scroll-mt-20">
<div class="mb-6 flex items-center justify-between">
<h2 class="flex items-center gap-2 text-xl font-semibold">
@@ -575,7 +491,6 @@
</div>
</div>
{:else if !data.error}
- <!-- Not Found State -->
<div class="flex min-h-screen items-center justify-center">
<div class="text-center">
<div class="bg-muted/50 mb-6 inline-flex rounded-full p-6">
@@ -591,47 +506,3 @@
</div>
{/if}
</div>
-
-<Dialog.Root bind:open={deployDialogOpen}>
- <Dialog.Content>
- <Dialog.Header>
- <Dialog.Title>Deploy Stack to Agent</Dialog.Title>
- <Dialog.Description>
- Deploy "{data.stack?.name || 'Unknown Stack'}" to a remote agent
- </Dialog.Description>
- </Dialog.Header>
- <div class="space-y-4 py-4">
- <div class="space-y-2">
- <Label for="agent-select">Select Agent</Label>
- <Select.Root type="single" bind:value={selectedAgentId} disabled={deploying}>
- <Select.Trigger>
- {selectedAgentId}
- </Select.Trigger>
- <Select.Content>
- {#each onlineAgents as agent}
- <Select.Item value={agent.id}>
- <div class="flex items-center gap-2">
- <div class="size-2 rounded-full bg-green-500"></div>
- <span>{agent.hostname}</span>
- <span class="text-muted-foreground text-xs">({agent.platform})</span>
- </div>
- </Select.Item>
- {/each}
- </Select.Content>
- </Select.Root>
- <p class="text-muted-foreground text-xs">This will deploy the current stack configuration to the selected agent.</p>
- </div>
- </div>
- <Dialog.Footer>
- <Button variant="outline" onclick={() => (deployDialogOpen = false)} disabled={deploying}>Cancel</Button>
- <Button onclick={handleDeployToAgent} disabled={!selectedAgentId || deploying}>
- {#if deploying}
- <Loader2 class="mr-2 size-4 animate-spin" />
- {:else}
- <Send class="mr-2 size-4" />
- {/if}
- Deploy
- </Button>
- </Dialog.Footer>
- </Dialog.Content>
-</Dialog.Root>
diff --git a/frontend/src/routes/compose/[composeId]/+page.ts b/frontend/src/routes/compose/[composeId]/+page.ts
index 4c8d84445..dd6516fbe 100644
--- a/frontend/src/routes/compose/[composeId]/+page.ts
+++ b/frontend/src/routes/compose/[composeId]/+page.ts
@@ -1,13 +1,12 @@
-import { stackAPI } from '$lib/services/api';
+import { environmentAPI } from '$lib/services/api';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({ params }) => {
try {
- // Get the stack by ID
- const response = await stackAPI.get(params.composeId);
+ const stackReponse = await environmentAPI.getStack(params.composeId);
// Extract stack from the API response
- const stack = response.stack || response;
+ const stack = stackReponse;
if (!stack) {
return {
diff --git a/frontend/src/routes/compose/agent/[agentId]/[composeName]/+page.svelte b/frontend/src/routes/compose/agent/[agentId]/[composeName]/+page.svelte
deleted file mode 100644
index 617803fe1..000000000
--- a/frontend/src/routes/compose/agent/[agentId]/[composeName]/+page.svelte
+++ /dev/null
@@ -1,396 +0,0 @@
-<script lang="ts">
- import type { PageData } from './$types';
- import * as Card from '$lib/components/ui/card';
- import { Button } from '$lib/components/ui/button';
- import { Input } from '$lib/components/ui/input';
- import { Label } from '$lib/components/ui/label';
- import { ArrowLeft, FileStack, Layers, Settings, Activity, Users, Play, Square, RotateCcw, Loader2 } from '@lucide/svelte';
- import { invalidateAll } from '$app/navigation';
- import { toast } from 'svelte-sonner';
- import StatusBadge from '$lib/components/badges/status-badge.svelte';
- import { statusVariantMap } from '$lib/types/statuses';
- import { capitalizeFirstLetter } from '$lib/utils/string.utils';
- import YamlEditor from '$lib/components/yaml-editor.svelte';
- import EnvEditor from '$lib/components/env-editor.svelte';
- import ArcaneButton from '$lib/components/arcane-button.svelte';
-
- let { data }: { data: PageData } = $props();
- let { agent, stack, composeName } = data;
-
- let name = $state(composeName);
- let composeContent = $state(stack.composeContent || '');
- let envContent = $state(stack.envContent || '');
- let originalName = composeName;
- let originalComposeContent = stack.composeContent || '';
- let originalEnvContent = stack.envContent || '';
-
- let isLoading = $state({
- deploying: false,
- stopping: false,
- restarting: false,
- saving: false
- });
-
- let hasChanges = $derived(name !== originalName || composeContent !== originalComposeContent || envContent !== originalEnvContent);
-
- let activeSection = $state<string>('overview');
-
- async function handleSaveChanges() {
- if (!hasChanges) return;
-
- isLoading.saving = true;
- try {
- const response = await fetch(`/api/agents/${agent.id}/tasks`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- type: 'stack_update',
- payload: {
- project_name: composeName,
- compose_content: composeContent,
- env_content: envContent
- }
- })
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- throw new Error(errorData.error || 'Failed to save stack');
- }
-
- toast.success('Stack updated successfully!');
-
- // Update original values to reflect saved state
- originalComposeContent = composeContent;
- originalEnvContent = envContent;
-
- await invalidateAll();
- } catch (error) {
- console.error('Failed to save stack:', error);
- toast.error(`Failed to save stack: ${error instanceof Error ? error.message : 'Unknown error'}`);
- } finally {
- isLoading.saving = false;
- }
- }
-
- async function handleStackAction(action: 'up' | 'down' | 'restart') {
- const actionKey = action === 'up' ? 'deploying' : action === 'down' ? 'stopping' : 'restarting';
- isLoading[actionKey] = true;
-
- try {
- let taskType: string;
- switch (action) {
- case 'up':
- taskType = 'compose_up';
- break;
- case 'down':
- taskType = 'compose_down';
- break;
- case 'restart':
- taskType = 'compose_restart';
- break;
- }
-
- const response = await fetch(`/api/agents/${agent.id}/tasks`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- type: taskType,
- payload: { project_name: composeName }
- })
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- throw new Error(errorData.error || `Failed to ${action} stack`);
- }
-
- toast.success(`Stack ${action === 'up' ? 'started' : action === 'down' ? 'stopped' : 'restarted'} successfully`);
- await invalidateAll();
- } catch (error) {
- console.error(`Failed to ${action} stack:`, error);
- toast.error(`Failed to ${action} stack: ${error instanceof Error ? error.message : 'Unknown error'}`);
- } finally {
- isLoading[actionKey] = false;
- }
- }
-
- // Navigation sections for single-page layout
- const navigationSections = [
- { id: 'overview', label: 'Overview', icon: FileStack },
- { id: 'services', label: 'Services', icon: Layers },
- { id: 'config', label: 'Configuration', icon: Settings }
- ] as const;
-
- type SectionId = (typeof navigationSections)[number]['id'];
-
- function scrollToSection(sectionId: SectionId) {
- activeSection = sectionId;
- const element = document.getElementById(sectionId);
- if (element) {
- element.scrollIntoView({ behavior: 'smooth', block: 'start' });
- }
- }
-</script>
-
-<div class="bg-background min-h-screen">
- {#if stack}
- <!-- Fixed Header -->
- <div class="bg-background/95 sticky top-0 z-10 border-b backdrop-blur">
- <div class="max-w-full px-4 py-3">
- <div class="flex items-center justify-between">
- <div class="flex items-center gap-3">
- <Button variant="ghost" size="sm" href="/compose">
- <ArrowLeft class="mr-2 size-4" />
- Back
- </Button>
- <div class="bg-border h-4 w-px"></div>
- <div class="flex items-center gap-2">
- <h1 class="max-w-[300px] truncate text-lg font-semibold" title={stack.name}>
- {stack.name}
- </h1>
- <span class="rounded-full bg-blue-100 px-2 py-1 text-xs text-blue-800">
- {agent.hostname}
- </span>
- {#if stack.status}
- <StatusBadge variant={statusVariantMap[stack.status.toLowerCase()] || 'gray'} text={capitalizeFirstLetter(stack.status)} />
- {/if}
- </div>
- </div>
-
- <div class="flex items-center gap-2">
- <!-- Agent Stack Actions -->
- <Button variant="outline" size="sm" onclick={() => handleStackAction('up')} disabled={Object.values(isLoading).some(Boolean) || stack.status === 'running'}>
- {#if isLoading.deploying}
- <Loader2 class="mr-2 size-4 animate-spin" />
- {:else}
- <Play class="mr-2 size-4" />
- {/if}
- Start
- </Button>
-
- <Button variant="outline" size="sm" onclick={() => handleStackAction('restart')} disabled={Object.values(isLoading).some(Boolean)}>
- {#if isLoading.restarting}
- <Loader2 class="mr-2 size-4 animate-spin" />
- {:else}
- <RotateCcw class="mr-2 size-4" />
- {/if}
- Restart
- </Button>
-
- <Button variant="outline" size="sm" onclick={() => handleStackAction('down')} disabled={Object.values(isLoading).some(Boolean) || stack.status !== 'running'}>
- {#if isLoading.stopping}
- <Loader2 class="mr-2 size-4 animate-spin" />
- {:else}
- <Square class="mr-2 size-4" />
- {/if}
- Stop
- </Button>
- </div>
- </div>
- </div>
- </div>
-
- <div class="flex h-[calc(100vh-64px)]">
- <!-- Fixed Sidebar Navigation -->
- <div class="bg-background/50 w-48 shrink-0 border-r">
- <div class="sticky top-16 p-3">
- <nav class="space-y-1">
- {#each navigationSections as section}
- {@const IconComponent = section.icon}
- <button
- onclick={() => scrollToSection(section.id)}
- class="flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors
- {activeSection === section.id ? 'bg-primary/10 text-primary border-primary/20 border' : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'}"
- >
- <IconComponent class="size-4 shrink-0" />
- <span class="truncate">{section.label}</span>
- {#if section.id === 'services' && stack.serviceCount}
- <span class="bg-muted ml-auto shrink-0 rounded px-1.5 py-0.5 text-xs">
- {stack.serviceCount}
- </span>
- {/if}
- </button>
- {/each}
- </nav>
- </div>
- </div>
-
- <!-- Main Content -->
- <div class="flex-1 overflow-y-auto">
- <div class="max-w-none p-6">
- <div class="space-y-8">
- <!-- Overview Section -->
- <section id="overview" class="scroll-mt-20">
- <h2 class="mb-6 flex items-center gap-2 text-xl font-semibold">
- <FileStack class="size-5" />
- Overview
- <span class="text-muted-foreground text-sm font-normal">(Remote Agent)</span>
- </h2>
-
- <!-- Summary Cards -->
- <div class="mb-6 grid grid-cols-1 gap-6 md:grid-cols-3">
- <Card.Root class="border">
- <Card.Content class="flex items-center justify-between p-6">
- <div>
- <p class="text-muted-foreground text-sm font-medium">Services</p>
- <p class="text-2xl font-bold">{stack.serviceCount || 0}</p>
- </div>
- <div class="bg-primary/10 rounded-full p-3">
- <Layers class="text-primary size-5" />
- </div>
- </Card.Content>
- </Card.Root>
-
- <Card.Root class="border">
- <Card.Content class="flex items-center justify-between p-6">
- <div>
- <p class="text-muted-foreground text-sm font-medium">Running</p>
- <p class="text-2xl font-bold">{stack.runningCount || 0}</p>
- </div>
- <div class="rounded-full bg-green-500/10 p-3">
- <Activity class="size-5 text-green-500" />
- </div>
- </Card.Content>
- </Card.Root>
-
- <Card.Root class="border">
- <Card.Content class="flex items-center justify-between p-6">
- <div>
- <p class="text-muted-foreground text-sm font-medium">Agent</p>
- <p class="text-lg font-medium">{agent.hostname}</p>
- </div>
- <div class="rounded-full bg-blue-500/10 p-3">
- <Users class="size-5 text-blue-500" />
- </div>
- </Card.Content>
- </Card.Root>
- </div>
- </section>
-
- <!-- Services Section -->
- <section id="services" class="scroll-mt-20">
- <h2 class="mb-6 flex items-center gap-2 text-xl font-semibold">
- <Layers class="size-5" />
- Services ({stack.serviceCount || 0})
- </h2>
-
- <Card.Root class="border">
- <Card.Content class="p-6">
- {#if stack.services && stack.services.length > 0}
- <div class="space-y-4">
- {#each stack.services as service (service.id || service.name)}
- {@const status = service.state?.Status || 'unknown'}
- {@const variant = statusVariantMap[status.toLowerCase()] || 'gray'}
-
- <!-- Agent Service (not clickable) -->
- <div class="bg-muted/20 flex items-center justify-between rounded-lg border p-4">
- <div class="flex items-center gap-3">
- <div class="bg-muted/50 rounded-full p-2">
- <Layers class="text-muted-foreground size-4" />
- </div>
- <div>
- <p class="font-medium">{service.name}</p>
- <p class="text-muted-foreground text-sm">Remote service</p>
- </div>
- </div>
- <StatusBadge {variant} text={capitalizeFirstLetter(status)} />
- </div>
- {/each}
- </div>
- {:else}
- <div class="py-12 text-center">
- <div class="bg-muted/50 mx-auto mb-4 flex size-16 items-center justify-center rounded-full">
- <Layers class="text-muted-foreground size-6" />
- </div>
- <div class="text-muted-foreground">No services defined in this stack</div>
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
- </section>
-
- <!-- Configuration Section -->
- <section id="config" class="scroll-mt-20">
- <div class="mb-6 flex items-center justify-between">
- <h2 class="flex items-center gap-2 text-xl font-semibold">
- <Settings class="size-5" />
- Configuration
- <span class="text-muted-foreground text-sm font-normal">(Remote)</span>
- </h2>
- <!-- Save Button -->
- {#if hasChanges}
- <ArcaneButton action="save" loading={isLoading.saving} onClick={handleSaveChanges} disabled={!hasChanges} label="Save Changes" loadingLabel="Saving..." class="bg-green-600 text-white hover:bg-green-700" />
- {/if}
- </div>
-
- <!-- Stack Name Field -->
- <Card.Root class="mb-6 border">
- <Card.Header class="pb-4">
- <Card.Title>Stack Settings</Card.Title>
- </Card.Header>
- <Card.Content>
- <div class="max-w-md">
- <Label for="name" class="mb-2 block">Stack Name</Label>
- <Input type="text" id="name" name="name" bind:value={name} required disabled={true} />
- <p class="text-muted-foreground mt-2 text-sm">Agent stack names cannot be changed from the web interface.</p>
- </div>
- </Card.Content>
- </Card.Root>
-
- <!-- Editors -->
- <div class="grid grid-cols-1 gap-6 xl:grid-cols-3">
- <!-- Compose Editor -->
- <div class="xl:col-span-2">
- <Card.Root class="border">
- <Card.Header class="pb-4">
- <Card.Title>Docker Compose File</Card.Title>
- </Card.Header>
- <Card.Content>
- <div class="h-[600px] overflow-hidden rounded-lg border">
- <YamlEditor bind:value={composeContent} readOnly={Object.values(isLoading).some(Boolean)} />
- </div>
- <p class="text-muted-foreground mt-2 text-sm">
- Edit your <span class="font-medium">compose.yaml</span> file directly. Changes will be applied to the remote agent.
- </p>
- </Card.Content>
- </Card.Root>
- </div>
-
- <!-- Environment Editor -->
- <div>
- <Card.Root class="border">
- <Card.Header class="pb-4">
- <Card.Title>Environment (.env)</Card.Title>
- </Card.Header>
- <Card.Content>
- <div class="h-[600px] overflow-hidden rounded-lg border">
- <EnvEditor bind:value={envContent} readOnly={Object.values(isLoading).some(Boolean)} />
- </div>
- <p class="text-muted-foreground mt-2 text-sm">Define environment variables in KEY=value format. Variables will be applied on the remote agent.</p>
- </Card.Content>
- </Card.Root>
- </div>
- </div>
- </section>
- </div>
- </div>
- </div>
- </div>
- {:else}
- <!-- Not Found State -->
- <div class="flex min-h-screen items-center justify-center">
- <div class="text-center">
- <div class="bg-muted/50 mb-6 inline-flex rounded-full p-6">
- <FileStack class="text-muted-foreground size-10" />
- </div>
- <h2 class="mb-3 text-2xl font-medium">Stack Not Found</h2>
- <p class="text-muted-foreground mb-8 max-w-md text-center">Could not load agent stack data. The stack may not exist on the agent or the agent may be offline.</p>
- <Button variant="outline" href="/compose">
- <ArrowLeft class="mr-2 size-4" />
- Back to Stacks
- </Button>
- </div>
- </div>
- {/if}
-</div>
diff --git a/frontend/src/routes/compose/agent/[agentId]/[composeName]/+page.ts b/frontend/src/routes/compose/agent/[agentId]/[composeName]/+page.ts
deleted file mode 100644
index 030f26a6b..000000000
--- a/frontend/src/routes/compose/agent/[agentId]/[composeName]/+page.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { error } from '@sveltejs/kit';
-import type { PageLoad } from './$types';
-import { agentAPI, stackAPI } from '$lib/services/api';
-
-export const load: PageLoad = async ({ params }) => {
- const { agentId, composeName } = params;
-
- try {
- // Get the agent via API
- const agent = await agentAPI.get(agentId).catch((err) => {
- console.error(`Failed to get agent ${agentId}:`, err);
- throw error(404, 'Agent not found');
- });
-
- if (!agent) {
- throw error(404, 'Agent not found');
- }
-
- // Check agent status via API
- const agentStatus = await agentAPI.getStatus(agentId).catch(() => ({ status: 'offline' }));
-
- if (agentStatus.status !== 'online') {
- throw error(400, `Agent is not online (status: ${agentStatus.status})`);
- }
-
- // Get stacks from the agent via API
- const stacks = await agentAPI.getStacks(agentId).catch((err) => {
- console.error(`Failed to get stacks from agent ${agentId}:`, err);
- return [];
- });
-
- // Find the specific stack
- const stack = stacks.find((s) => s.name === composeName);
-
- if (!stack) {
- throw error(404, 'Stack not found on agent');
- }
-
- // Get detailed stack information if needed
- let detailedStack = stack;
- if (stack.id) {
- try {
- detailedStack = await stackAPI.get(stack.id);
- } catch (err) {
- console.warn('Failed to get detailed stack info, using basic info:', err);
- }
- }
-
- return {
- agent: {
- ...agent,
- status: agentStatus.status
- },
- stack: detailedStack,
- composeName
- };
- } catch (err) {
- console.error('Error loading agent stack:', err);
-
- // Re-throw SvelteKit errors
- if (err && typeof err === 'object' && 'status' in err) {
- throw err;
- }
-
- throw error(500, 'Failed to load agent stack');
- }
-};
diff --git a/frontend/src/routes/compose/new/+page.svelte b/frontend/src/routes/compose/new/+page.svelte
index b2f9d75ec..4cc59d4d1 100644
--- a/frontend/src/routes/compose/new/+page.svelte
+++ b/frontend/src/routes/compose/new/+page.svelte
@@ -1,14 +1,13 @@
<script lang="ts">
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import { ArrowLeft, FileStack, Terminal, Copy, Loader2, Wand, Send } from '@lucide/svelte';
+ import { ArrowLeft, FileStack, Terminal, Copy, Loader2, Wand } from '@lucide/svelte';
import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { Label } from '$lib/components/ui/label/index.js';
import { goto, invalidateAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
import YamlEditor from '$lib/components/yaml-editor.svelte';
- import StackAPIService from '$lib/services/api/stack-api-service';
import { preventDefault } from '$lib/utils/form.utils';
import { tryCatch } from '$lib/utils/try-catch';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
@@ -18,115 +17,39 @@
import { Textarea } from '$lib/components/ui/textarea/index.js';
import DropdownCard from '$lib/components/dropdown-card.svelte';
import * as Resizable from '$lib/components/ui/resizable/index.js';
- import TemplateSelectionDialog from '$lib/components/template-selection-dialog.svelte';
- import * as DropdownButton from '$lib/components/ui/dropdown-button/index.js';
- import { converterAPI } from '$lib/services/api';
+ import TemplateSelectionDialog from '$lib/components/dialogs/template-selection-dialog.svelte';
+ import { environmentAPI } from '$lib/services/api';
import type { Template } from '$lib/types/template.type';
import type { PageProps } from './+page';
let { data }: { data: PageProps } = $props();
- const stackApi = new StackAPIService();
let saving = $state(false);
let converting = $state(false);
let showTemplateDialog = $state(false);
- let selectedAgentId = $state('');
let name = $state('');
let composeContent = $state(data.defaultTemplate || defaultComposeTemplate);
let envContent = $state(data.envTemplate || defaultEnvTemplate);
let dockerRunCommand = $state('');
- const onlineAgents = $derived(data.agents || []);
-
- const agentOptions = $derived(
- onlineAgents.map((agent) => ({
- id: agent.id,
- label: `${agent.hostname} (${agent.platform})`,
- disabled: false
- }))
- );
-
- const selectedAgent = $derived(onlineAgents.find((agent) => agent.id === selectedAgentId));
-
async function handleSubmit() {
- if (selectedAgentId) {
- await handleDeployToAgent();
- } else {
- await handleCreateStack();
- }
+ await handleCreateStack();
}
async function handleCreateStack() {
handleApiResultWithCallbacks({
- result: await tryCatch(
- stackApi.create({
- name: name,
- composeContent: composeContent,
- envContent: envContent,
- agentId: undefined
- })
- ),
+ result: await tryCatch(environmentAPI.deployStack(name, composeContent, envContent)),
message: 'Failed to Create Stack',
setLoadingState: (value) => (saving = value),
- onSuccess: async (data) => {
+ onSuccess: async (stack) => {
toast.success(`Stack "${name}" created successfully.`);
await invalidateAll();
- // Use the returned stack ID instead of name for navigation
- goto(`/compose/${data.stack?.name}`);
+ goto(`/compose/${stack.name}`);
}
});
}
- async function handleDeployToAgent() {
- if (!selectedAgentId) {
- toast.error('Please select an agent for deployment');
- return;
- }
-
- const agent = onlineAgents.find((agent) => agent.id === selectedAgentId);
- if (!agent) {
- toast.error('Selected agent not found or offline');
- return;
- }
-
- saving = true;
- try {
- const response = await fetch(`/api/agents/${selectedAgentId}/deploy/stack`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- stackName: name,
- composeContent,
- envContent,
- mode: 'compose'
- })
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.error || `Failed to deploy Compose Project: ${response.statusText}`);
- }
-
- const result = await response.json();
- toast.success(`Compose Project "${name}" deployed to agent ${agent.hostname}!`);
- goto(`/agents/${selectedAgentId}`);
- } catch (error) {
- console.error('Deploy error:', error);
- toast.error(error instanceof Error ? error.message : 'Failed to deploy Compose Project');
- } finally {
- saving = false;
- }
- }
-
- function handleDeployButtonClick() {
- handleSubmit();
- }
-
- function handleAgentSelect(option: { id: string; label: string }) {
- selectedAgentId = option.id;
- }
-
async function handleConvertDockerRun() {
if (!dockerRunCommand.trim()) {
toast.error('Please enter a docker run command');
@@ -134,18 +57,17 @@
}
handleApiResultWithCallbacks({
- result: await tryCatch(converterAPI.convert(dockerRunCommand)),
+ result: await tryCatch(environmentAPI.convertDockerRun(dockerRunCommand)),
message: 'Failed to Convert Docker Run Command',
setLoadingState: (value) => (converting = value),
onSuccess: (data) => {
- const { dockerCompose, envVars, serviceName } = data;
+ composeContent = data.composeContent;
- composeContent = dockerCompose;
- if (envVars) {
- envContent = envVars;
- }
- if (serviceName && !name) {
- name = serviceName;
+ if (!name.trim() && dockerRunCommand.includes('--name ')) {
+ const nameMatch = dockerRunCommand.match(/--name\s+(\S+)/);
+ if (nameMatch) {
+ name = nameMatch[1];
+ }
}
toast.success('Docker run command converted successfully!');
@@ -251,40 +173,7 @@
</div>
<div class="flex items-center gap-2">
<ArcaneButton action="template" onClick={() => (showTemplateDialog = true)} loading={saving} disabled={saving || converting} />
-
- {#if onlineAgents.length > 0}
- <DropdownButton.DropdownRoot>
- <DropdownButton.Root>
- <DropdownButton.Main variant="default" disabled={!name || !composeContent || saving} onclick={handleDeployButtonClick}>
- {#if saving}
- <Loader2 class="mr-2 size-4 animate-spin" />
- {:else}
- <Send class="mr-2 size-4" />
- {/if}
- {selectedAgent ? `Deploy to ${selectedAgent.hostname}` : 'Deploy Locally'}
- </DropdownButton.Main>
-
- <DropdownButton.DropdownTrigger>
- <DropdownButton.Trigger variant="default" disabled={!name || !composeContent || saving} />
- </DropdownButton.DropdownTrigger>
- </DropdownButton.Root>
-
- <DropdownButton.Content align="end" class="min-w-[200px]">
- <DropdownButton.Item onclick={() => handleAgentSelect({ id: '', label: 'Deploy Locally' })}>Deploy Locally</DropdownButton.Item>
-
- {#if agentOptions.length > 0}
- <DropdownButton.Separator />
- {#each agentOptions as option}
- <DropdownButton.Item onclick={() => handleAgentSelect(option)}>
- {option.label}
- </DropdownButton.Item>
- {/each}
- {/if}
- </DropdownButton.Content>
- </DropdownButton.DropdownRoot>
- {:else}
- <ArcaneButton action="create" onClick={handleSubmit} loading={saving} disabled={!name || !composeContent} />
- {/if}
+ <ArcaneButton action="create" onClick={handleSubmit} loading={saving} disabled={!name || !composeContent} />
</div>
</div>
</Card.Header>
diff --git a/frontend/src/routes/compose/new/+page.ts b/frontend/src/routes/compose/new/+page.ts
index b663181e8..f6c3e8ba9 100644
--- a/frontend/src/routes/compose/new/+page.ts
+++ b/frontend/src/routes/compose/new/+page.ts
@@ -1,17 +1,17 @@
-import { templateAPI, agentAPI } from '$lib/services/api';
+import { templateAPI, environmentManagementAPI } from '$lib/services/api';
import { defaultComposeTemplate, defaultEnvTemplate } from '$lib/constants';
import type { Template } from '$lib/types/template.type';
-import type { Agent } from '$lib/types/agent.type';
+import type { Environment } from '$lib/stores/environment.store';
export interface PageProps {
composeTemplates: Template[];
envTemplate: string;
defaultTemplate: string;
- agents: Agent[];
+ environments: Environment[];
}
export const load = async (): Promise<PageProps> => {
- const [allTemplates, envTemplate] = await Promise.all([
+ const [allTemplates, envTemplate, environments] = await Promise.all([
templateAPI.loadAll().catch((err) => {
console.warn('Failed to load templates:', err);
return [];
@@ -19,6 +19,10 @@ export const load = async (): Promise<PageProps> => {
templateAPI.getEnvTemplate().catch((err) => {
console.warn('Failed to load env template:', err);
return defaultEnvTemplate;
+ }),
+ environmentManagementAPI.list().catch((err) => {
+ console.warn('Failed to load environments:', err);
+ return [];
})
]);
@@ -26,6 +30,6 @@ export const load = async (): Promise<PageProps> => {
composeTemplates: allTemplates,
envTemplate,
defaultTemplate: defaultComposeTemplate,
- agents: []
+ environments
};
};
diff --git a/frontend/src/routes/containers/+page.svelte b/frontend/src/routes/containers/+page.svelte
index 5994c85da..b9330b221 100644
--- a/frontend/src/routes/containers/+page.svelte
+++ b/frontend/src/routes/containers/+page.svelte
@@ -9,7 +9,6 @@
import CreateContainerSheet from '$lib/components/sheets/create-container-sheet.svelte';
import { goto, invalidateAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
- import { containerAPI, imageAPI } from '$lib/services/api';
import { tryCatch } from '$lib/utils/try-catch';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import { statusVariantMap } from '$lib/types/statuses';
@@ -22,7 +21,7 @@
import StatCard from '$lib/components/stat-card.svelte';
import { parseStatusTime } from '$lib/utils/string.utils';
import type { ContainerInfo } from 'dockerode';
- import { autoUpdateAPI } from '$lib/services/api';
+ import { autoUpdateAPI, environmentAPI } from '$lib/services/api';
let { data }: { data: PageData & { containers: ContainerInfo[] } } = $props();
let containers = $state(data.containers);
@@ -34,7 +33,8 @@
stop: false,
restart: false,
remove: false,
- checking: false
+ checking: false,
+ create: false
});
const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
const runningContainers = $derived(containers?.filter((c: ContainerInfo) => c.State === 'running').length || 0);
@@ -79,7 +79,7 @@
destructive: true,
action: async () => {
handleApiResultWithCallbacks({
- result: await tryCatch(containerAPI.remove(id)),
+ result: await tryCatch(environmentAPI.deleteContainer(id)),
message: 'Failed to Remove Container',
setLoadingState: (value) => (isLoading.remove = value),
onSuccess: async () => {
@@ -97,7 +97,7 @@
if (action === 'start') {
handleApiResultWithCallbacks({
- result: await tryCatch(containerAPI.start(id)),
+ result: await tryCatch(environmentAPI.startContainer(id)),
message: 'Failed to Start Container',
setLoadingState: (value) => (isLoading.start = value),
async onSuccess() {
@@ -107,7 +107,7 @@
});
} else if (action === 'stop') {
handleApiResultWithCallbacks({
- result: await tryCatch(containerAPI.stop(id)),
+ result: await tryCatch(environmentAPI.stopContainer(id)),
message: 'Failed to Stop Container',
setLoadingState: (value) => (isLoading.stop = value),
async onSuccess() {
@@ -117,7 +117,7 @@
});
} else if (action === 'restart') {
handleApiResultWithCallbacks({
- result: await tryCatch(containerAPI.restart(id)),
+ result: await tryCatch(environmentAPI.restartContainer(id)),
message: 'Failed to Restart Container',
setLoadingState: (value) => (isLoading.restart = value),
async onSuccess() {
@@ -187,7 +187,7 @@
</Card.Header>
<Card.Content>
<UniversalTable
- data={containers.map((c) => ({
+ data={containers.map((c: any) => ({
...c,
displayName: getContainerDisplayName(c),
statusSortValue: parseStatusTime(c.Status)
@@ -298,10 +298,19 @@
availableVolumes={Array.isArray(data.volumes) ? data.volumes : []}
availableNetworks={Array.isArray(data.networks) ? data.networks : []}
availableImages={Array.isArray(data.images) ? data.images : []}
- onSubmit={async () => {
- await invalidateAll();
- isCreateDialogOpen = false;
+ isLoading={isLoading.create}
+ onSubmit={async (options) => {
+ isLoading.create = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.createContainer(options)),
+ message: 'Failed to Create Container',
+ setLoadingState: (value) => (isLoading.create = value),
+ onSuccess: async () => {
+ toast.success('Container Created Successfully.');
+ await invalidateAll();
+ isCreateDialogOpen = false;
+ }
+ });
}}
- isLoading={false}
/>
</div>
diff --git a/frontend/src/routes/containers/+page.ts b/frontend/src/routes/containers/+page.ts
index 5ae7410a0..12104e1b5 100644
--- a/frontend/src/routes/containers/+page.ts
+++ b/frontend/src/routes/containers/+page.ts
@@ -1,15 +1,15 @@
-import { containerAPI, imageAPI, networkAPI, volumeAPI } from '$lib/services/api';
+import { environmentAPI } from '$lib/services/api';
import type { PageLoad } from './$types';
export const load: PageLoad = async () => {
try {
- const [containers, volumes, networks, images] = await Promise.all([containerAPI.list(true), volumeAPI.list(), networkAPI.list(), imageAPI.list()]);
+ const resources = await environmentAPI.getAllResources();
return {
- containers,
- volumes,
- networks,
- images
+ containers: resources.containers || [],
+ volumes: resources.volumes || [],
+ networks: resources.networks || [],
+ images: resources.images || []
};
} catch (error) {
console.error('Error loading container data:', error);
diff --git a/frontend/src/routes/containers/[id]/+page.svelte b/frontend/src/routes/containers/[containerId]/+page.svelte
similarity index 100%
rename from frontend/src/routes/containers/[id]/+page.svelte
rename to frontend/src/routes/containers/[containerId]/+page.svelte
diff --git a/frontend/src/routes/containers/[containerId]/+page.ts b/frontend/src/routes/containers/[containerId]/+page.ts
new file mode 100644
index 000000000..f7dde7442
--- /dev/null
+++ b/frontend/src/routes/containers/[containerId]/+page.ts
@@ -0,0 +1,27 @@
+import type { PageLoad } from './$types';
+import { environmentAPI } from '$lib/services/api';
+import { error } from '@sveltejs/kit';
+
+export const load: PageLoad = async ({ params }) => {
+ const containerId = params.containerId;
+
+ try {
+ const container = await environmentAPI.getContainer(containerId);
+ const containerStats = await environmentAPI.getContainerStats(containerId);
+
+ if (!container) {
+ throw error(404, 'Container not found');
+ }
+
+ return {
+ container,
+ stats: containerStats
+ };
+ } catch (err: any) {
+ console.error('Failed to load container:', err);
+ if (err.status === 404) {
+ throw err;
+ }
+ throw error(500, err.message || 'Failed to load container details');
+ }
+};
diff --git a/frontend/src/routes/containers/[id]/+page.ts b/frontend/src/routes/containers/[id]/+page.ts
deleted file mode 100644
index 9cc55d2bc..000000000
--- a/frontend/src/routes/containers/[id]/+page.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import type { PageLoad } from './$types';
-import { containerAPI } from '$lib/services/api';
-import { error } from '@sveltejs/kit';
-
-export const load: PageLoad = async ({ params }) => {
- const containerId = params.id;
-
- try {
- const [container, logs, stats] = await Promise.all([
- containerAPI.inspect(containerId),
- containerAPI.logs(containerId, { tail: 100 }).catch((err) => {
- console.error(`Failed to retrieve logs for ${containerId}:`, err);
- return 'Failed to load logs. Container might not be running or logs are unavailable.';
- }),
- containerAPI.stats(containerId).catch((err) => {
- console.error(`Failed to retrieve stats for ${containerId}:`, err);
- return null;
- })
- ]);
-
- if (!container) {
- error(404, {
- message: `Container with ID "${containerId}" not found.`
- });
- }
-
- return {
- container,
- logs,
- stats
- };
- } catch (err: any) {
- console.error(`Failed to load container ${containerId}:`, err);
- if (err.name === 'NotFoundError' || err.status === 404) {
- error(404, { message: err.message || `Container with ID "${containerId}" not found.` });
- } else {
- error(500, {
- message: err.message || `Failed to load container details for "${containerId}".`
- });
- }
- }
-};
diff --git a/frontend/src/routes/environments/+page.svelte b/frontend/src/routes/environments/+page.svelte
new file mode 100644
index 000000000..69e738dfc
--- /dev/null
+++ b/frontend/src/routes/environments/+page.svelte
@@ -0,0 +1,306 @@
+<script lang="ts">
+ import { onMount } from 'svelte';
+ import { goto, invalidateAll } from '$app/navigation';
+ import type { Environment } from '$lib/stores/environment.store';
+ import type { ColumnDef } from '@tanstack/table-core';
+ import { formatDistanceToNow } from 'date-fns';
+ import { RefreshCw, AlertCircle, Loader2, Monitor, Eye, Trash2, Terminal, Key, Server, Ellipsis, Plus } from '@lucide/svelte';
+ import { toast } from 'svelte-sonner';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog/index.js';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util.js';
+ import { tryCatch } from '$lib/utils/try-catch.js';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import UniversalTable from '$lib/components/universal-table.svelte';
+ import * as Table from '$lib/components/ui/table';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import NewEnvironmentSheet from '$lib/components/sheets/new-environment-sheet.svelte';
+ import { environmentManagementAPI } from '$lib/services/api';
+
+ let { data } = $props();
+
+ let environments: Environment[] = $state(data.environments || []);
+ let loading = $state(false);
+ let error = $state('');
+ let selectedEnvironmentIds = $state<string[]>([]);
+ let showEnvironmentSheet = $state(false);
+ let refreshInProgress = false;
+
+ const columns: ColumnDef<Environment>[] = [
+ { accessorKey: 'hostname', header: 'Environment' },
+ { accessorKey: 'status', header: 'Status' },
+ { accessorKey: 'apiUrl', header: 'API URL' },
+ { accessorKey: 'enabled', header: 'Enabled' },
+ { accessorKey: 'lastSeen', header: 'Last Seen' },
+ { accessorKey: 'actions', header: ' ' }
+ ];
+
+ onMount(() => {
+ const interval = setInterval(refreshEnvironments, 30000);
+ return () => clearInterval(interval);
+ });
+
+ async function refreshEnvironments() {
+ if (refreshInProgress) return;
+ refreshInProgress = true;
+
+ try {
+ loading = true;
+ environments = await environmentManagementAPI.list();
+ error = '';
+ } catch (err) {
+ console.error('Failed to refresh environments:', err);
+ } finally {
+ loading = false;
+ refreshInProgress = false;
+ }
+ }
+
+ async function loadEnvironments() {
+ try {
+ loading = true;
+ error = '';
+ environments = await environmentManagementAPI.list();
+ } catch (err) {
+ console.error('Failed to load environments:', err);
+ error = err instanceof Error ? err.message : 'Unknown error';
+ } finally {
+ loading = false;
+ }
+ }
+
+ async function deleteEnvironment(environmentId: string, hostname: string) {
+ openConfirmDialog({
+ title: `Confirm Removal`,
+ message: `Are you sure you want to remove environment "${hostname}"? This action cannot be undone.`,
+ confirm: {
+ label: 'Remove',
+ destructive: true,
+ action: async () => {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentManagementAPI.delete(environmentId)),
+ message: 'Failed to Remove Environment',
+ onSuccess: async () => {
+ toast.success('Environment Removed Successfully');
+ await loadEnvironments();
+ }
+ });
+ }
+ }
+ });
+ }
+
+ async function testConnection(environmentId: string) {
+ try {
+ const result = await environmentManagementAPI.testConnection(environmentId);
+ if (result.status === 'online') {
+ toast.success('Connection successful');
+ } else {
+ toast.error(`Connection failed: ${result.message || 'Unknown error'}`);
+ }
+ await loadEnvironments();
+ } catch (error) {
+ toast.error('Failed to test connection');
+ console.error(error);
+ }
+ }
+
+ async function handleBulkDelete() {
+ if (selectedEnvironmentIds.length === 0) return;
+
+ openConfirmDialog({
+ title: 'Confirm Bulk Removal',
+ message: `Are you sure you want to remove ${selectedEnvironmentIds.length} environment(s)? This action cannot be undone.`,
+ confirm: {
+ label: 'Remove All',
+ destructive: true,
+ action: async () => {
+ try {
+ await Promise.all(selectedEnvironmentIds.map((id) => environmentManagementAPI.delete(id)));
+ toast.success(`${selectedEnvironmentIds.length} environment(s) removed successfully`);
+ selectedEnvironmentIds = [];
+ await loadEnvironments();
+ } catch (err) {
+ console.error('Failed to remove environments:', err);
+ toast.error('Failed to remove some environments');
+ }
+ }
+ }
+ });
+ }
+
+ function handleEnvironmentCreated() {
+ showEnvironmentSheet = false;
+ toast.success('Environment added successfully! You can now select it from the environment switcher.');
+ loadEnvironments();
+ }
+</script>
+
+<svelte:head>
+ <title>Environment Management - Arcane</title>
+</svelte:head>
+
+<div class="space-y-6">
+ <div>
+ <h1 class="text-3xl font-bold tracking-tight">Environment Management</h1>
+ <p class="text-muted-foreground mt-1 text-sm">Manage and monitor your arcane environments</p>
+ </div>
+
+ {#if error}
+ <div class="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-red-700 dark:border-red-800 dark:bg-red-900/20 dark:text-red-400">
+ <div class="flex items-center gap-2">
+ <AlertCircle class="h-5 w-5" />
+ <strong>Error:</strong>
+ {error}
+ </div>
+ </div>
+ {/if}
+
+ <div class="grid h-full grid-cols-1 gap-6">
+ <Card.Root class="flex flex-col border shadow-sm">
+ <Card.Header class="flex flex-row items-center justify-between space-y-0 pb-3">
+ <div class="flex items-center gap-2">
+ <div class="rounded-full bg-blue-500/10 p-2">
+ <Server class="size-5 text-blue-500" />
+ </div>
+ <div>
+ <Card.Title>Environments</Card.Title>
+ <Card.Description>Created Environments</Card.Description>
+ </div>
+ </div>
+ <div class="flex items-center gap-2">
+ {#if selectedEnvironmentIds.length > 0}
+ <Button variant="destructive" onclick={handleBulkDelete}>
+ <Trash2 class="mr-2 h-4 w-4" />
+ Delete Selected ({selectedEnvironmentIds.length})
+ </Button>
+ {/if}
+ <Button onclick={() => (showEnvironmentSheet = true)}>
+ <Plus class="mr-2 h-4 w-4" />
+ Add Environment
+ </Button>
+ <Button onclick={loadEnvironments} disabled={loading}>
+ {#if loading}
+ <Loader2 class="mr-2 h-4 w-4 animate-spin" />
+ {:else}
+ <RefreshCw class="mr-2 h-4 w-4" />
+ {/if}
+ {loading ? 'Loading...' : 'Refresh'}
+ </Button>
+ </div>
+ </Card.Header>
+ <Card.Content class="flex flex-1 flex-col">
+ {#if environments.length === 0 && !loading}
+ <div class="py-16 text-center">
+ <Monitor class="mx-auto mb-4 h-16 w-16 text-gray-400" />
+ <h3 class="mb-2 text-lg font-medium text-gray-900 dark:text-white">No environments registered</h3>
+ <p class="mb-4 text-gray-600 dark:text-gray-400">Get started by adding your first environment</p>
+ <div class="mx-auto max-w-md rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
+ <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">Add a new environment to connect to an Arcane agent running as an API server.</p>
+ <Button onclick={() => (showEnvironmentSheet = true)} class="w-full">
+ <Plus class="mr-2 h-4 w-4" />
+ Add Environment
+ </Button>
+ </div>
+ </div>
+ {:else if environments.length > 0}
+ <div class="flex h-full flex-1 flex-col">
+ <UniversalTable
+ data={environments}
+ {columns}
+ idKey="id"
+ bind:selectedIds={selectedEnvironmentIds}
+ features={{
+ sorting: true,
+ filtering: true,
+ selection: true
+ }}
+ display={{
+ filterPlaceholder: 'Search environments...',
+ noResultsMessage: 'No environments found'
+ }}
+ pagination={{
+ pageSize: 10,
+ pageSizeOptions: [10, 20, 50]
+ }}
+ sort={{
+ defaultSort: { id: 'lastSeen', desc: true }
+ }}
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ <div class="flex items-center gap-3">
+ <div class="relative">
+ <div class="flex size-8 items-center justify-center rounded-lg bg-gray-100 dark:bg-gray-700">
+ <Monitor class="size-4 text-gray-600 dark:text-gray-400" />
+ </div>
+ <div class="absolute -top-1 -right-1 size-3 {item.status === 'online' ? 'bg-green-500' : 'bg-red-500'} rounded-full border-2 border-white dark:border-gray-800"></div>
+ </div>
+ <div>
+ <div class="font-medium text-gray-900 dark:text-white">{item.hostname}</div>
+ <div class="text-xs text-gray-500 dark:text-gray-400 font-mono">{item.id}</div>
+ </div>
+ </div>
+ </Table.Cell>
+ <Table.Cell>
+ <StatusBadge text={item.status === 'online' ? 'Online' : 'Offline'} variant={item.status === 'online' ? 'green' : 'red'} />
+ </Table.Cell>
+ <Table.Cell>
+ <span class="text-sm font-mono text-muted-foreground">{item.apiUrl}</span>
+ </Table.Cell>
+ <Table.Cell>
+ <StatusBadge text={item.enabled ? 'Enabled' : 'Disabled'} variant={item.enabled ? 'green' : 'gray'} />
+ </Table.Cell>
+ <Table.Cell>
+ {#if item.lastSeen}
+ <span class="text-sm text-gray-600 dark:text-gray-400">{formatDistanceToNow(new Date(item.lastSeen))} ago</span>
+ {:else}
+ <span class="text-sm text-gray-400">Never</span>
+ {/if}
+ </Table.Cell>
+ <Table.Cell>
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <Button variant="ghost" size="icon" class="size-8">
+ <Ellipsis class="size-4" />
+ <span class="sr-only">Open menu</span>
+ </Button>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item onclick={() => testConnection(item.id)}>
+ <Terminal class="size-4" />
+ Test Connection
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => goto(`/environments/${item.id}`)}>
+ <Eye class="size-4" />
+ View Details
+ </DropdownMenu.Item>
+ <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => deleteEnvironment(item.id, item.hostname)}>
+ <Trash2 class="size-4" />
+ Delete Environment
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </UniversalTable>
+ </div>
+ {:else}
+ <div class="text-muted-foreground py-8 text-center italic">Loading environments...</div>
+ {/if}
+ </Card.Content>
+ </Card.Root>
+ </div>
+
+ {#if loading && environments.length > 0}
+ <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">
+ <Loader2 class="h-4 w-4 animate-spin" />
+ <span class="text-sm">Refreshing...</span>
+ </div>
+ {/if}
+</div>
+
+<NewEnvironmentSheet bind:open={showEnvironmentSheet} onEnvironmentCreated={handleEnvironmentCreated} />
diff --git a/frontend/src/routes/environments/+page.ts b/frontend/src/routes/environments/+page.ts
new file mode 100644
index 000000000..6f84a5cfc
--- /dev/null
+++ b/frontend/src/routes/environments/+page.ts
@@ -0,0 +1,23 @@
+import type { PageLoad } from './$types';
+import { environmentManagementAPI } from '$lib/services/api';
+import { error } from '@sveltejs/kit';
+
+export const load: PageLoad = async () => {
+ try {
+ const environments = await environmentManagementAPI.list();
+
+ return {
+ environments
+ };
+ } catch (err) {
+ console.error('Failed to load environments:', err);
+
+ if (err && typeof err === 'object' && 'status' in err) {
+ throw err;
+ }
+
+ throw error(500, {
+ message: err instanceof Error ? err.message : 'Failed to load environments'
+ });
+ }
+};
diff --git a/frontend/src/routes/environments/[id]/+page.svelte b/frontend/src/routes/environments/[id]/+page.svelte
new file mode 100644
index 000000000..9a7f5e454
--- /dev/null
+++ b/frontend/src/routes/environments/[id]/+page.svelte
@@ -0,0 +1,270 @@
+<script lang="ts">
+ import type { PageData } from './$types';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { ArrowLeft, RefreshCw, Monitor, Terminal, Settings, Activity, Globe, Database } from '@lucide/svelte';
+ import { goto, invalidateAll } from '$app/navigation';
+ import { formatDate } from '$lib/utils/string.utils';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { environmentManagementAPI } from '$lib/services/api';
+ import { toast } from 'svelte-sonner';
+ import { onMount } from 'svelte';
+ import Label from '$lib/components/ui/label/label.svelte';
+
+ let { data }: { data: PageData } = $props();
+ let { environment } = $derived(data);
+
+ let isRefreshing = $state(false);
+ let isTestingConnection = $state(false);
+ let activeSection = $state<string>('overview');
+
+ const sections = [
+ { id: 'overview', Label: 'Overview', icon: Monitor },
+ { id: 'connection', Label: 'Connection', icon: Globe },
+ { id: 'activity', Label: 'Activity', icon: Activity }
+ ];
+
+ onMount(() => {
+ const interval = setInterval(refreshEnvironment, 30000);
+ return () => clearInterval(interval);
+ });
+
+ async function refreshEnvironment() {
+ if (isRefreshing) return;
+
+ try {
+ isRefreshing = true;
+ await invalidateAll();
+ } catch (err) {
+ console.error('Failed to refresh environment:', err);
+ toast.error('Failed to refresh environment data');
+ } finally {
+ isRefreshing = false;
+ }
+ }
+
+ async function testConnection() {
+ if (isTestingConnection) return;
+
+ try {
+ isTestingConnection = true;
+ const result = await environmentManagementAPI.testConnection(environment.id);
+
+ if (result.status === 'online') {
+ toast.success('Connection successful');
+ } else {
+ toast.error(`Connection failed: ${result.message || 'Unknown error'}`);
+ }
+
+ await refreshEnvironment();
+ } catch (error) {
+ toast.error('Failed to test connection');
+ console.error(error);
+ } finally {
+ isTestingConnection = false;
+ }
+ }
+
+ const environmentDisplayName = $derived(environment?.hostname || 'Environment Details');
+</script>
+
+<svelte:head>
+ <title>{environmentDisplayName} - Arcane</title>
+</svelte:head>
+
+<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')}>
+ <ArrowLeft class="h-4 w-4" />
+ </Button>
+ <div>
+ <h1 class="text-3xl font-bold tracking-tight">{environmentDisplayName}</h1>
+ <p class="text-muted-foreground mt-1 text-sm">Environment details and management</p>
+ </div>
+ </div>
+ <div class="flex items-center gap-2">
+ <Button variant="outline" onclick={testConnection} disabled={isTestingConnection}>
+ {#if isTestingConnection}
+ <RefreshCw class="mr-2 h-4 w-4 animate-spin" />
+ {:else}
+ <Terminal class="mr-2 h-4 w-4" />
+ {/if}
+ Test Connection
+ </Button>
+ <Button onclick={refreshEnvironment} disabled={isRefreshing}>
+ {#if isRefreshing}
+ <RefreshCw class="mr-2 h-4 w-4 animate-spin" />
+ {:else}
+ <RefreshCw class="mr-2 h-4 w-4" />
+ {/if}
+ Refresh
+ </Button>
+ </div>
+ </div>
+
+ <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
+ <div class="lg:col-span-1">
+ <Card.Root>
+ <Card.Header>
+ <Card.Title class="text-lg">Sections</Card.Title>
+ </Card.Header>
+ <Card.Content class="p-0">
+ <nav class="space-y-1">
+ {#each sections as section}
+ {@const Icon = section.icon}
+ <button onclick={() => (activeSection = section.id)} class="w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-muted transition-colors {activeSection === section.id ? 'bg-muted border-r-2 border-primary' : ''}">
+ <Icon class="size-4" />
+ {section.Label}
+ </button>
+ {/each}
+ </nav>
+ </Card.Content>
+ </Card.Root>
+ </div>
+
+ <div class="lg:col-span-3">
+ {#if activeSection === 'overview'}
+ <div class="space-y-6">
+ <Card.Root>
+ <Card.Header>
+ <Card.Title class="flex items-center gap-2">
+ <Monitor class="size-5" />
+ Environment Overview
+ </Card.Title>
+ </Card.Header>
+ <Card.Content class="space-y-6">
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
+ <div class="space-y-4">
+ <div>
+ <Label class="text-sm font-medium text-muted-foreground">Hostname</Label>
+ <div class="mt-1 text-lg font-semibold">{environment.hostname}</div>
+ </div>
+ <div>
+ <Label class="text-sm font-medium text-muted-foreground">Status</Label>
+ <div class="mt-1">
+ <StatusBadge text={environment.status === 'online' ? 'Online' : 'Offline'} variant={environment.status === 'online' ? 'green' : 'red'} />
+ </div>
+ </div>
+ <div>
+ <Label class="text-sm font-medium text-muted-foreground">Enabled</Label>
+ <div class="mt-1">
+ <StatusBadge text={environment.enabled ? 'Enabled' : 'Disabled'} variant={environment.enabled ? 'green' : 'gray'} />
+ </div>
+ </div>
+ </div>
+ <div class="space-y-4">
+ <div>
+ <Label class="text-sm font-medium text-muted-foreground">Environment ID</Label>
+ <div class="mt-1 font-mono text-sm bg-muted px-2 py-1 rounded">{environment.id}</div>
+ </div>
+ <div>
+ <Label class="text-sm font-medium text-muted-foreground">Created</Label>
+ <div class="mt-1 text-sm">{formatDate(environment.createdAt)}</div>
+ </div>
+ {#if environment.updatedAt}
+ <div>
+ <Label class="text-sm font-medium text-muted-foreground">Last Updated</Label>
+ <div class="mt-1 text-sm">{formatDate(environment.updatedAt)}</div>
+ </div>
+ {/if}
+ </div>
+ </div>
+ {#if environment.description}
+ <div>
+ <Label class="text-sm font-medium text-muted-foreground">Description</Label>
+ <div class="mt-1 text-sm">{environment.description}</div>
+ </div>
+ {/if}
+ </Card.Content>
+ </Card.Root>
+ </div>
+ {:else if activeSection === 'connection'}
+ <div class="space-y-6">
+ <Card.Root>
+ <Card.Header>
+ <Card.Title class="flex items-center gap-2">
+ <Globe class="h-5 w-5" />
+ Connection Details
+ </Card.Title>
+ </Card.Header>
+ <Card.Content class="space-y-4">
+ <div>
+ <Label class="text-sm font-medium text-muted-foreground">API URL</Label>
+ <div class="mt-1 font-mono text-sm bg-muted px-3 py-2 rounded-md break-all">{environment.apiUrl}</div>
+ </div>
+ {#if environment.lastSeen}
+ <div>
+ <Label class="text-sm font-medium text-muted-foreground">Last Seen</Label>
+ <div class="mt-1 text-sm">{formatDate(environment.lastSeen)}</div>
+ </div>
+ {:else}
+ <div>
+ <Label class="text-sm font-medium text-muted-foreground">Last Seen</Label>
+ <div class="mt-1 text-sm text-muted-foreground">Never</div>
+ </div>
+ {/if}
+ <div class="pt-4">
+ <Button onclick={testConnection} disabled={isTestingConnection} class="w-full">
+ {#if isTestingConnection}
+ <RefreshCw class="mr-2 h-4 w-4 animate-spin" />
+ Testing Connection...
+ {:else}
+ <Terminal class="mr-2 h-4 w-4" />
+ Test Connection
+ {/if}
+ </Button>
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root>
+ <Card.Header>
+ <Card.Title class="flex items-center gap-2">
+ <Settings class="h-5 w-5" />
+ Connection Health
+ </Card.Title>
+ </Card.Header>
+ <Card.Content>
+ <div class="space-y-3">
+ <div class="flex items-center justify-between">
+ <span class="text-sm">Connection Status</span>
+ <StatusBadge text={environment.status === 'online' ? 'Connected' : 'Disconnected'} variant={environment.status === 'online' ? 'green' : 'red'} />
+ </div>
+ <div class="flex items-center justify-between">
+ <span class="text-sm">Environment Enabled</span>
+ <StatusBadge text={environment.enabled ? 'Yes' : 'No'} variant={environment.enabled ? 'green' : 'gray'} />
+ </div>
+ </div>
+ </Card.Content>
+ </Card.Root>
+ </div>
+ {:else if activeSection === 'activity'}
+ <div class="space-y-6">
+ <Card.Root>
+ <Card.Header>
+ <Card.Title class="flex items-center gap-2">
+ <Activity class="h-5 w-5" />
+ Activity Log
+ </Card.Title>
+ </Card.Header>
+ <Card.Content>
+ <div class="text-center py-8 text-muted-foreground">
+ <Database class="mx-auto h-12 w-12 mb-3 opacity-50" />
+ <p>Activity logging coming soon</p>
+ <p class="text-sm">Environment activity and logs will be displayed here</p>
+ </div>
+ </Card.Content>
+ </Card.Root>
+ </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">
+ <RefreshCw class="h-4 w-4 animate-spin" />
+ <span class="text-sm">Refreshing...</span>
+ </div>
+ {/if}
+</div>
diff --git a/frontend/src/routes/environments/[id]/+page.ts b/frontend/src/routes/environments/[id]/+page.ts
new file mode 100644
index 000000000..3a0741f3a
--- /dev/null
+++ b/frontend/src/routes/environments/[id]/+page.ts
@@ -0,0 +1,23 @@
+import type { PageLoad } from './$types';
+import { environmentManagementAPI } from '$lib/services/api';
+import { error } from '@sveltejs/kit';
+
+export const load: PageLoad = async ({ params }) => {
+ try {
+ const environment = await environmentManagementAPI.get(params.id);
+
+ return {
+ environment
+ };
+ } catch (err) {
+ console.error('Failed to load environment:', err);
+
+ if (err && typeof err === 'object' && 'status' in err) {
+ throw err;
+ }
+
+ throw error(404, {
+ message: err instanceof Error ? err.message : 'Environment not found'
+ });
+ }
+};
diff --git a/frontend/src/routes/images/+page.svelte b/frontend/src/routes/images/+page.svelte
index bad4fc3dd..4cf625def 100644
--- a/frontend/src/routes/images/+page.svelte
+++ b/frontend/src/routes/images/+page.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import type { PageData } from './$types';
- import type { EnhancedImageInfo } from '$lib/types/docker';
+ import type { EnhancedImageInfo } from '$lib/models/image.type';
import UniversalTable from '$lib/components/universal-table.svelte';
import { Button } from '$lib/components/ui/button/index.js';
import { Download, AlertCircle, HardDrive, Trash2, Loader2, ChevronDown, Ellipsis, ScanSearch, Funnel } from '@lucide/svelte';
@@ -15,16 +15,18 @@
import * as Table from '$lib/components/ui/table';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
- import ImageAPIService from '$lib/services/api/image-api-service';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import ArcaneButton from '$lib/components/arcane-button.svelte';
import { tablePersistence } from '$lib/stores/table-store';
import MaturityItem from '$lib/components/maturity-item.svelte';
import { maturityStore, triggerBulkMaturityCheck, enhanceImagesWithMaturity, loadImageMaturityBatch } from '$lib/stores/maturity-store';
+ import { environmentAPI } from '$lib/services/api';
let { data }: { data: PageData } = $props();
- let images = $derived(data.images || []);
+
+ // Make images reactive to data changes
+ let images = $derived(Array.isArray(data.images) ? data.images : []);
let error = $state(data.error);
let selectedIds = $state<string[]>([]);
@@ -43,8 +45,6 @@
let isPullingInline = $state<Record<string, boolean>>({});
- const imageApi = new ImageAPIService();
-
let isPullDialogOpen = $state(false);
let isConfirmPruneDialogOpen = $state(false);
@@ -61,6 +61,18 @@
}
});
+ async function refreshImages() {
+ isLoading.refreshing = true;
+ try {
+ await invalidateAll();
+ } catch (error) {
+ console.error('Failed to refresh images:', error);
+ toast.error('Failed to refresh images');
+ } finally {
+ isLoading.refreshing = false;
+ }
+ }
+
async function loadImagesMaturity() {
const imageIds = images
.filter((img) => {
@@ -103,6 +115,33 @@
}
});
+ async function handleImageRemove(id: string) {
+ const image = images.find((img) => img.Id === id);
+ const imageIdentifier = image?.RepoTags?.[0] || id.substring(0, 12);
+
+ openConfirmDialog({
+ title: 'Delete Image',
+ message: `Are you sure you want to delete ${imageIdentifier}? This action cannot be undone.`,
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+ await handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.deleteImage(id)),
+ message: 'Failed to Remove Image',
+ setLoadingState: (value) => (isLoading.removing = value),
+ onSuccess: async () => {
+ toast.success(`Image "${imageIdentifier}" deleted successfully.`);
+ await invalidateAll();
+ }
+ });
+ isLoading.removing = false;
+ }
+ }
+ });
+ }
+
async function handleDeleteSelected() {
openConfirmDialog({
title: 'Delete Selected Images',
@@ -127,7 +166,7 @@
}
await handleApiResultWithCallbacks({
- result: await tryCatch(imageApi.remove(id)),
+ result: await tryCatch(environmentAPI.deleteImage(id)),
message: `Failed to delete image "${imageIdentifier}"`,
setLoadingState: (value) => (isLoading.removing = value),
onSuccess: async () => {
@@ -138,11 +177,8 @@
}
isLoading.removing = false;
- console.log(`Finished deleting. Success: ${successCount}, Failed: ${failureCount}`);
if (successCount > 0) {
- setTimeout(async () => {
- await invalidateAll();
- }, 500);
+ await invalidateAll();
}
selectedIds = [];
}
@@ -153,7 +189,7 @@
async function handlePruneImages() {
isLoading.pruning = true;
await handleApiResultWithCallbacks({
- result: await tryCatch(imageApi.prune() as Promise<{ message?: string }>),
+ result: await tryCatch(environmentAPI.pruneImages() as Promise<{ message?: string }>),
message: 'Failed to Prune Images',
setLoadingState: (value) => (isLoading.pruning = value),
onSuccess: async (result: { message?: string }) => {
@@ -176,54 +212,10 @@
toast.info(lastStatusText, { id: `pull-${imageIdentifier}` });
try {
- const response = await fetch('/api/images/pull', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({ imageName: fullImageName })
- });
+ const result = await environmentAPI.pullImage(fullImageName);
- if (!response.ok || !response.body) {
- const errorData = await response.json().catch(() => ({ error: 'Failed to pull image. Server returned an error.' }));
- const errorMessage = typeof errorData.error === 'string' ? errorData.error : errorData.message || `HTTP error ${response.status}`;
- throw new Error(errorMessage);
- }
-
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
-
- for (const line of lines) {
- if (line.trim() === '') continue;
- try {
- const data = JSON.parse(line);
- if (data.error) {
- console.error('Error in stream:', data.error);
- pullError = typeof data.error === 'string' ? data.error : data.error.message || 'An error occurred during pull.';
- lastStatusText = `Error: ${pullError}`;
- toast.error(lastStatusText, { id: `pull-${imageIdentifier}` });
- continue;
- }
- if (data.status) {
- lastStatusText = data.status;
- }
- } catch (e: any) {
- console.warn('Failed to parse stream line:', line, e);
- }
- }
- }
-
- if (pullError) {
- throw new Error(pullError);
+ if (result.error) {
+ throw new Error(result.error);
}
toast.success(`Image "${fullImageName}" pulled successfully.`, {
@@ -238,33 +230,6 @@
isPullingInline = { ...isPullingInline, [imageIdentifier]: false };
}
}
-
- async function handleImageRemove(id: string) {
- const image = images.find((img) => img.Id === id);
- const imageIdentifier = image?.RepoTags?.[0] || id.substring(0, 12);
-
- openConfirmDialog({
- title: 'Delete Image',
- message: `Are you sure you want to delete ${imageIdentifier}? This action cannot be undone.`,
- confirm: {
- label: 'Delete',
- destructive: true,
- action: async () => {
- isLoading.removing = true;
- await handleApiResultWithCallbacks({
- result: await tryCatch(imageApi.remove(id)),
- message: 'Failed to Remove Image',
- setLoadingState: (value) => (isLoading.removing = value),
- onSuccess: async () => {
- toast.success(`Image "${imageIdentifier}" deleted successfully.`);
- await invalidateAll();
- }
- });
- isLoading.removing = false;
- }
- }
- });
- }
</script>
<div class="space-y-6">
@@ -273,6 +238,9 @@
<h1 class="text-3xl font-bold tracking-tight">Container Images</h1>
<p class="text-muted-foreground mt-1 text-sm">View and Manage your Container Images</p>
</div>
+ <div class="flex items-center gap-2">
+ <ArcaneButton action="restart" onClick={refreshImages} label="Refresh" loading={isLoading.refreshing} disabled={isLoading.refreshing} />
+ </div>
</div>
{#if error}
@@ -469,7 +437,7 @@
<Button variant="outline" onclick={() => (isConfirmPruneDialogOpen = false)} disabled={isLoading.pruning}>Cancel</Button>
<Button variant="destructive" onclick={handlePruneImages} disabled={isLoading.pruning}>
{#if isLoading.pruning}
- <Loader2 class="mr-2 size-4 animate-spin" /> Pruning...
+ <Loader2 class="mr-2 size-4 animate-spin" /> Prune Images
{:else}
Prune Images
{/if}
diff --git a/frontend/src/routes/images/+page.ts b/frontend/src/routes/images/+page.ts
index eee27afda..1db40c7b4 100644
--- a/frontend/src/routes/images/+page.ts
+++ b/frontend/src/routes/images/+page.ts
@@ -1,5 +1,5 @@
-import { imageAPI, containerAPI, settingsAPI } from '$lib/services/api';
-import type { EnhancedImageInfo } from '$lib/types/docker';
+import { environmentAPI, settingsAPI } from '$lib/services/api';
+import type { EnhancedImageInfo } from '$lib/models/image.type';
import type { Settings } from '$lib/types/settings.type';
type ImageData = {
@@ -10,7 +10,7 @@ type ImageData = {
export const load = async (): Promise<ImageData> => {
try {
- const [images, settings] = await Promise.all([imageAPI.list() as Promise<EnhancedImageInfo[]>, settingsAPI.getSettings()]);
+ const [images, settings] = await Promise.all([environmentAPI.getImages(), settingsAPI.getSettings()]);
const enhancedImages = await Promise.all(
images.map(async (image): Promise<EnhancedImageInfo> => {
diff --git a/frontend/src/routes/images/[imageId]/+page.svelte b/frontend/src/routes/images/[imageId]/+page.svelte
index 4f5908207..809bf29ce 100644
--- a/frontend/src/routes/images/[imageId]/+page.svelte
+++ b/frontend/src/routes/images/[imageId]/+page.svelte
@@ -1,8 +1,7 @@
<script lang="ts">
import type { PageData } from './$types';
import * as Card from '$lib/components/ui/card/index.js';
- import { Button } from '$lib/components/ui/button/index.js';
- import { ArrowLeft, HardDrive, Clock, Tag, Layers, Hash, Trash2, Loader2, Cpu } from '@lucide/svelte';
+ import { HardDrive, Clock, Tag, Layers, Hash, Cpu } from '@lucide/svelte';
import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
import { goto } from '$app/navigation';
import { Separator } from '$lib/components/ui/separator/index.js';
@@ -12,13 +11,12 @@
import { openConfirmDialog } from '$lib/components/confirm-dialog';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
- import ImageAPIService from '$lib/services/api/image-api-service';
import { toast } from 'svelte-sonner';
import ArcaneButton from '$lib/components/arcane-button.svelte';
+ import { environmentAPI } from '$lib/services/api';
let { data }: { data: PageData } = $props();
let { image } = $derived(data);
- const imageApi = new ImageAPIService();
let isLoading = $state({
pulling: false,
@@ -39,7 +37,7 @@
destructive: true,
action: async () => {
await handleApiResultWithCallbacks({
- result: await tryCatch(imageApi.remove(id)),
+ result: await tryCatch(environmentAPI.deleteImage(id)),
message: 'Failed to Remove Image',
setLoadingState: (value) => (isLoading.removing = value),
onSuccess: async () => {
diff --git a/frontend/src/routes/images/[imageId]/+page.ts b/frontend/src/routes/images/[imageId]/+page.ts
index 5ec469b9b..c4f264c20 100644
--- a/frontend/src/routes/images/[imageId]/+page.ts
+++ b/frontend/src/routes/images/[imageId]/+page.ts
@@ -1,28 +1,46 @@
-import type { PageLoad } from './$types';
-import { imageAPI } from '$lib/services/api';
+import { environmentAPI } from '$lib/services/api';
+import type { EnhancedImageInfo } from '$lib/models/image.type';
import { error } from '@sveltejs/kit';
-export const load: PageLoad = async ({ params }) => {
- const imageId = params.imageId;
+type ImageDetailData = {
+ image: EnhancedImageInfo;
+ error?: string;
+};
+
+export const load = async ({ params }): Promise<ImageDetailData> => {
+ const { imageId } = params;
try {
- const image = await imageAPI.get(imageId);
+ const image = await environmentAPI.getImage(imageId);
+
+ if (!image) {
+ throw error(404, 'Image not found');
+ }
+
+ let repo = '<none>';
+ let tag = '<none>';
+ if (image.RepoTags && image.RepoTags.length > 0) {
+ const repoTag = image.RepoTags[0];
+ if (repoTag.includes(':')) {
+ [repo, tag] = repoTag.split(':');
+ } else {
+ repo = repoTag;
+ tag = 'latest';
+ }
+ }
return {
- image
+ image: {
+ ...image,
+ repo,
+ tag
+ }
};
} catch (err: any) {
- console.error(`Failed to load image ${imageId}:`, err);
-
- // Handle API errors
- if (err.status === 404 || err.name === 'NotFoundError') {
- error(404, {
- message: err.message || `Image with ID "${imageId}" not found.`
- });
- } else {
- error(err.status || 500, {
- message: err.message || `Failed to load image details for "${imageId}".`
- });
+ console.error('Failed to load image:', err);
+ if (err.status === 404) {
+ throw err;
}
+ throw error(500, err.message || 'Failed to load image details');
}
};
diff --git a/frontend/src/routes/networks/+page.svelte b/frontend/src/routes/networks/+page.svelte
index a2cab1951..bb5c90c15 100644
--- a/frontend/src/routes/networks/+page.svelte
+++ b/frontend/src/routes/networks/+page.svelte
@@ -1,20 +1,20 @@
<script lang="ts">
- import * as Card from '$lib/components/ui/card/index.js';
+ import { Trash2, Plus, Network, Ellipsis, ScanSearch } from '@lucide/svelte';
import { Button } from '$lib/components/ui/button/index.js';
- import { Plus, AlertCircle, Network, Trash2, Loader2, ScanSearch, Ellipsis } from '@lucide/svelte';
- import UniversalTable from '$lib/components/universal-table.svelte';
- import type { PageData } from './$types';
+ import * as Card from '$lib/components/ui/card/index.js';
import * as Alert from '$lib/components/ui/alert/index.js';
- import { goto, invalidateAll } from '$app/navigation';
- import { toast } from 'svelte-sonner';
- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import CreateNetworkSheet from '$lib/components/sheets/create-network-sheet.svelte';
import * as Table from '$lib/components/ui/table';
- import type { NetworkCreateOptions, NetworkInspectInfo } from 'dockerode';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import { toast } from 'svelte-sonner';
+ import { goto, invalidateAll } from '$app/navigation';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import type { PageData } from './$types';
+ import type { NetworkCreateOptions } from 'dockerode';
+ import UniversalTable from '$lib/components/universal-table.svelte';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
- import { networkAPI } from '$lib/services/api';
+ import CreateNetworkSheet from '$lib/components/sheets/create-network-sheet.svelte';
+ import { environmentAPI } from '$lib/services/api';
import { DEFAULT_NETWORK_NAMES } from '$lib/constants';
import ArcaneButton from '$lib/components/arcane-button.svelte';
import { tablePersistence } from '$lib/stores/table-store';
@@ -22,7 +22,7 @@
let { data }: { data: PageData } = $props();
let networkPageStates = $state({
- networks: data.networks as NetworkInspectInfo[],
+ networks: Array.isArray(data.networks) ? data.networks : [],
selectedNetworks: <string[]>[],
error: data.error,
isCreateDialogOpen: false
@@ -34,21 +34,32 @@
refresh: false
});
- const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
-
$effect(() => {
- networkPageStates.networks = data.networks as NetworkInspectInfo[];
+ networkPageStates.networks = Array.isArray(data.networks) ? data.networks : [];
networkPageStates.error = data.error;
});
const totalNetworks = $derived(networkPageStates.networks.length);
- // NetworkInfo uses 'Driver' (capital D)
const bridgeNetworks = $derived(networkPageStates.networks.filter((n) => n.Driver === 'bridge').length);
const overlayNetworks = $derived(networkPageStates.networks.filter((n) => n.Driver === 'overlay').length);
+ async function refreshNetworks() {
+ isLoading.refresh = true;
+ try {
+ const refreshedNetworks = await environmentAPI.getNetworks();
+ networkPageStates.networks = Array.isArray(refreshedNetworks) ? refreshedNetworks : [];
+ } catch (error) {
+ console.error('Failed to refresh networks:', error);
+ toast.error('Failed to refresh networks');
+ } finally {
+ isLoading.refresh = false;
+ }
+ }
+
async function handleCreateNetworkSubmit(options: NetworkCreateOptions) {
+ isLoading.create = true;
handleApiResultWithCallbacks({
- result: await tryCatch(networkAPI.create(options)),
+ result: await tryCatch(environmentAPI.createNetwork(options)),
message: `Failed to Create Network "${options.Name}"`,
setLoadingState: (value) => (isLoading.create = value),
onSuccess: async () => {
@@ -66,13 +77,13 @@
}
openConfirmDialog({
title: 'Delete Network',
- message: `Are you sure you want to delete network "${name}" (ID: ${id.substring(0, 12)})? This action cannot be undone.`,
+ message: `Are you sure you want to delete network "${name}"? This action cannot be undone.`,
confirm: {
label: 'Delete',
destructive: true,
action: async () => {
handleApiResultWithCallbacks({
- result: await tryCatch(networkAPI.remove(encodeURIComponent(id))),
+ result: await tryCatch(environmentAPI.deleteNetwork(id)),
message: `Failed to Remove Network "${name}"`,
setLoadingState: (value) => (isLoading.remove = value),
onSuccess: async () => {
@@ -85,82 +96,67 @@
});
}
- async function handleDeleteSelected() {
- const selectedNetworkDetails = networkPageStates.selectedNetworks.map((id) => {
- const network = networkPageStates.networks.find((n) => n.Id === id);
- return {
- id,
- name: network?.Name || id.substring(0, 12),
- isDefault: DEFAULT_NETWORK_NAMES.has(network?.Name || '')
- };
- });
-
- const defaultNetworksSelected = selectedNetworkDetails.filter((n) => n.isDefault);
+ async function handleDeleteSelectedNetworks() {
+ const selectedNetworks = networkPageStates.networks.filter((network) => networkPageStates.selectedNetworks.includes(network.Id));
+ const defaultNetworks = selectedNetworks.filter((network) => DEFAULT_NETWORK_NAMES.has(network.Name));
- if (defaultNetworksSelected.length > 0) {
- const names = defaultNetworksSelected.map((n) => n.name).join(', ');
- toast.error(`Cannot delete default networks: ${names}. Please deselect them.`);
+ if (defaultNetworks.length > 0) {
+ toast.error(`Cannot delete default networks: ${defaultNetworks.map((n) => n.Name).join(', ')}`);
return;
}
openConfirmDialog({
title: 'Delete Selected Networks',
- message: `Are you sure you want to delete ${networkPageStates.selectedNetworks.length} selected network(s)? This action cannot be undone. Networks currently in use by containers cannot be deleted.`,
+ message: `Are you sure you want to delete ${networkPageStates.selectedNetworks.length} selected network(s)? This action cannot be undone.`,
confirm: {
label: 'Delete',
destructive: true,
action: async () => {
isLoading.remove = true;
+
let successCount = 0;
let failureCount = 0;
- for (const network of selectedNetworkDetails) {
- // Iterate over details which includes name
- const result = await tryCatch(networkAPI.remove(encodeURIComponent(network.id)));
- // The setLoadingState in a loop like this will just toggle the global remove state
- // For individual item loading, a more complex state management would be needed.
- if (result.data) {
- toast.success(`Network "${network.name}" deleted successfully.`);
- successCount++;
- } else if (result.error) {
- const error = result.error as any;
- toast.error(`Failed to delete network "${network.name}": ${error.message || 'Unknown error'}`);
+ for (const networkId of networkPageStates.selectedNetworks) {
+ const network = networkPageStates.networks.find((n) => n.Id === networkId);
+ if (!network) continue;
+
+ const result = await tryCatch(environmentAPI.deleteNetwork(networkId));
+ if (result.error) {
failureCount++;
+ toast.error(`Failed to delete network "${network.Name}": ${result.error.message}`);
+ } else {
+ successCount++;
+ toast.success(`Network "${network.Name}" deleted successfully.`);
}
}
- isLoading.remove = false; // Reset after all operations
- console.log(`Finished deleting. Success: ${successCount}, Failed: ${failureCount}`);
+ isLoading.remove = false;
if (successCount > 0) {
setTimeout(async () => {
await invalidateAll();
- }, 500); // Delay to allow toasts to show before list updates
+ }, 500);
}
- networkPageStates.selectedNetworks = []; // Clear selection
+ networkPageStates.selectedNetworks = [];
}
}
});
}
-
- function getNetworkSubnet(network: NetworkInspectInfo): string {
- if (network.IPAM && network.IPAM.Config && network.IPAM.Config.length > 0 && network.IPAM.Config[0].Subnet) {
- return network.IPAM.Config[0].Subnet;
- }
- return 'N/A';
- }
</script>
<div class="space-y-6">
<div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
<div>
<h1 class="text-3xl font-bold tracking-tight">Networks</h1>
- <p class="text-muted-foreground mt-1 text-sm">View and Manage Container Networking</p>
+ <p class="text-muted-foreground mt-1 text-sm">Manage your Docker networks</p>
+ </div>
+ <div class="flex items-center gap-2">
+ <ArcaneButton action="restart" onClick={refreshNetworks} loading={isLoading.refresh} disabled={isLoading.refresh} />
</div>
</div>
{#if networkPageStates.error}
<Alert.Root variant="destructive">
- <AlertCircle class="mr-2 size-4" />
<Alert.Title>Error Loading Networks</Alert.Title>
<Alert.Description>{networkPageStates.error}</Alert.Description>
</Alert.Root>
@@ -173,8 +169,8 @@
<p class="text-muted-foreground text-sm font-medium">Total Networks</p>
<p class="text-2xl font-bold">{totalNetworks}</p>
</div>
- <div class="bg-primary/10 rounded-full p-2">
- <Network class="text-primary size-5" />
+ <div class="rounded-full bg-blue-500/10 p-2">
+ <Network class="size-5 text-blue-500" />
</div>
</Card.Content>
</Card.Root>
@@ -185,8 +181,8 @@
<p class="text-muted-foreground text-sm font-medium">Bridge Networks</p>
<p class="text-2xl font-bold">{bridgeNetworks}</p>
</div>
- <div class="rounded-full bg-blue-500/10 p-2">
- <Network class="size-5 text-blue-500" />
+ <div class="rounded-full bg-green-500/10 p-2">
+ <Network class="size-5 text-green-500" />
</div>
</Card.Content>
</Card.Root>
@@ -204,29 +200,28 @@
</Card.Root>
</div>
- <Card.Root class="border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <div>
+ {#if networkPageStates.networks && networkPageStates.networks.length > 0}
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
<Card.Title>Network List</Card.Title>
+ <div class="flex items-center gap-2">
+ {#if networkPageStates.selectedNetworks.length > 0}
+ <ArcaneButton action="remove" onClick={handleDeleteSelectedNetworks} loading={isLoading.remove} disabled={isLoading.remove} />
+ {/if}
+ <ArcaneButton action="create" label="Create Network" onClick={() => (networkPageStates.isCreateDialogOpen = true)} loading={isLoading.create} disabled={isLoading.create} />
+ </div>
</div>
- <div class="flex items-center gap-2">
- {#if networkPageStates.selectedNetworks.length > 0}
- <ArcaneButton action="remove" customLabel="Delete Selected ({networkPageStates.selectedNetworks.length})" onClick={() => handleDeleteSelected()} loading={isLoading.remove} loadingLabel="Processing..." disabled={isLoading.remove} />
- {/if}
- <ArcaneButton action="create" customLabel="Create Network" onClick={() => (networkPageStates.isCreateDialogOpen = true)} disabled={isLoading.create} />
- </div>
- </div>
- </Card.Header>
- <Card.Content>
- {#if networkPageStates.networks && networkPageStates.networks.length > 0}
+ </Card.Header>
+
+ <Card.Content>
<UniversalTable
data={networkPageStates.networks}
columns={[
{ accessorKey: 'Name', header: 'Name' },
+ { accessorKey: 'Id', header: 'Network ID', enableSorting: false },
{ accessorKey: 'Driver', header: 'Driver' },
{ accessorKey: 'Scope', header: 'Scope' },
- { accessorFn: (row) => getNetworkSubnet(row), header: 'Subnet', id: 'subnet' },
{ accessorKey: 'actions', header: ' ', enableSorting: false }
]}
idKey="Id"
@@ -245,12 +240,13 @@
}}
bind:selectedIds={networkPageStates.selectedNetworks}
>
- {#snippet rows({ item }: { item: NetworkInspectInfo })}
- {@const isDefaultNetwork = DEFAULT_NETWORK_NAMES.has(item.Name)}
- <Table.Cell><a class="font-medium hover:underline" href="/networks/{encodeURIComponent(item.Id)}/">{item.Name}</a></Table.Cell>
+ {#snippet rows({ item })}
+ <Table.Cell>
+ <a class="font-medium hover:underline" href="/networks/{item.Id}/">{item.Name}</a>
+ </Table.Cell>
+ <Table.Cell class="truncate font-mono text-sm">{item.Id}</Table.Cell>
<Table.Cell>{item.Driver}</Table.Cell>
<Table.Cell>{item.Scope}</Table.Cell>
- <Table.Cell>{getNetworkSubnet(item)}</Table.Cell>
<Table.Cell>
<DropdownMenu.Root>
<DropdownMenu.Trigger>
@@ -263,39 +259,35 @@
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
- <DropdownMenu.Item onclick={() => goto(`/networks/${encodeURIComponent(item.Id)}`)} disabled={isAnyLoading}>
+ <DropdownMenu.Item onclick={() => goto(`/networks/${item.Id}`)}>
<ScanSearch class="size-4" />
Inspect
</DropdownMenu.Item>
- {#if !isDefaultNetwork}
- <DropdownMenu.Separator />
- <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleDeleteNetwork(item.Id, item.Name)} disabled={isLoading.remove || isAnyLoading}>
- {#if isLoading.remove && networkPageStates.selectedNetworks.includes(item.Id)}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <Trash2 class="size-4" />
- {/if}
- Remove
- </DropdownMenu.Item>
- {/if}
+ <DropdownMenu.Item class="focus:text-red-700! text-red-500" onclick={() => handleDeleteNetwork(item.Id, item.Name)} disabled={DEFAULT_NETWORK_NAMES.has(item.Name)}>
+ <Trash2 class="size-4" />
+ Remove
+ </DropdownMenu.Item>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
</Table.Cell>
{/snippet}
</UniversalTable>
- {:else if !networkPageStates.error}
- <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
- <Network class="text-muted-foreground mb-4 size-12 opacity-40" />
- <p class="text-lg font-medium">No networks found</p>
- <p class="text-muted-foreground mt-1 max-w-md text-sm">Create a new network using the "Create Network" button above or use the Docker CLI</p>
- <div class="mt-4 flex gap-3">
- <ArcaneButton action="create" customLabel="Create Network" onClick={() => (networkPageStates.isCreateDialogOpen = true)} size="sm" />
- </div>
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
+ </Card.Content>
+ </Card.Root>
+ {:else if !networkPageStates.error}
+ <div class="bg-card flex flex-col items-center justify-center rounded-lg border px-6 py-12 text-center">
+ <Network class="text-muted-foreground mb-4 size-12 opacity-40" />
+ <p class="text-lg font-medium">No networks found</p>
+ <p class="text-muted-foreground mt-1 max-w-md text-sm">Create a new network using the "Create Network" button above or use the Docker CLI</p>
+ <div class="mt-4 flex gap-3">
+ <Button variant="outline" size="sm" onclick={() => (networkPageStates.isCreateDialogOpen = true)}>
+ <Plus class="size-4" />
+ Create Network
+ </Button>
+ </div>
+ </div>
+ {/if}
<CreateNetworkSheet bind:open={networkPageStates.isCreateDialogOpen} isLoading={isLoading.create} onSubmit={handleCreateNetworkSubmit} />
</div>
diff --git a/frontend/src/routes/networks/+page.ts b/frontend/src/routes/networks/+page.ts
index 1248535b9..9a0a5c9b7 100644
--- a/frontend/src/routes/networks/+page.ts
+++ b/frontend/src/routes/networks/+page.ts
@@ -1,5 +1,5 @@
import type { PageLoad } from './$types';
-import { networkAPI } from '$lib/services/api';
+import { environmentAPI } from '$lib/services/api';
import type { NetworkInspectInfo } from 'dockerode';
type NetworkPageData = {
@@ -9,9 +9,9 @@ type NetworkPageData = {
export const load: PageLoad = async (): Promise<NetworkPageData> => {
try {
- const networks = await networkAPI.list();
+ const networks = await environmentAPI.getNetworks();
return {
- networks: networks as NetworkInspectInfo[]
+ networks: Array.isArray(networks) ? networks : []
};
} catch (err: unknown) {
console.error('Failed to load networks:', err);
diff --git a/frontend/src/routes/networks/[networkId]/+page.svelte b/frontend/src/routes/networks/[networkId]/+page.svelte
index dd355e7ab..b80a53dfe 100644
--- a/frontend/src/routes/networks/[networkId]/+page.svelte
+++ b/frontend/src/routes/networks/[networkId]/+page.svelte
@@ -13,14 +13,13 @@
import { goto } from '$app/navigation';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
- import NetworkAPIService from '$lib/services/api/network-api-service';
+ import { environmentAPI } from '$lib/services/api';
let { data }: { data: PageData } = $props();
let { network }: { network: NetworkInspectInfo | null | undefined } = $derived(data);
let errorMessage = $state('');
let isRemoving = $state(false);
- const networkApi = new NetworkAPIService();
const shortId = $derived(network?.Id?.substring(0, 12) || 'N/A');
const createdDate = $derived(network?.Created ? formatDate(network.Created) : 'N/A');
@@ -48,7 +47,7 @@
destructive: true,
action: async () => {
handleApiResultWithCallbacks({
- result: await tryCatch(networkApi.remove(network.Id)),
+ result: await tryCatch(environmentAPI.deleteNetwork(network.Id)),
message: 'Failed to remove network',
setLoadingState: (value) => (isRemoving = value),
onSuccess: async () => {
diff --git a/frontend/src/routes/networks/[networkId]/+page.ts b/frontend/src/routes/networks/[networkId]/+page.ts
index 6fc2bf0f0..65d8f6330 100644
--- a/frontend/src/routes/networks/[networkId]/+page.ts
+++ b/frontend/src/routes/networks/[networkId]/+page.ts
@@ -1,28 +1,25 @@
import type { PageLoad } from './$types';
-import { networkAPI } from '$lib/services/api';
+import { environmentAPI } from '$lib/services/api';
import { error } from '@sveltejs/kit';
export const load: PageLoad = async ({ params }) => {
- const networkId = params.networkId;
+ const { networkId } = params;
try {
- const network = await networkAPI.get(networkId);
+ const network = await environmentAPI.getNetwork(networkId);
+
+ if (!network) {
+ throw error(404, 'Network not found');
+ }
return {
network
};
} catch (err: any) {
- console.error(`Failed to load network ${networkId}:`, err);
-
- // Handle API errors
- if (err.status === 404 || err.name === 'NotFoundError') {
- error(404, {
- message: err.message || `Network with ID "${networkId}" not found.`
- });
- } else {
- error(err.status || 500, {
- message: err.message || `Failed to load network details for "${networkId}".`
- });
+ console.error('Failed to load network:', err);
+ if (err.status === 404) {
+ throw err;
}
+ throw error(500, err.message || 'Failed to load network details');
}
};
diff --git a/frontend/src/routes/settings/general/+page.svelte b/frontend/src/routes/settings/general/+page.svelte
index 82a92c8e7..ff958be08 100644
--- a/frontend/src/routes/settings/general/+page.svelte
+++ b/frontend/src/routes/settings/general/+page.svelte
@@ -3,7 +3,7 @@
import FormInput from '$lib/components/form/form-input.svelte';
import { Button } from '$lib/components/ui/button/index.js';
import { Cog, Save, RefreshCw, Folder, Globe, Calendar } from '@lucide/svelte';
- import type { FormInput as FormInputType } from '$lib/types/form.type';
+ import type { FormInput as FormInputType } from '$lib/utils/form.utils';
import { toast } from 'svelte-sonner';
import { invalidateAll } from '$app/navigation';
import type { Settings } from '$lib/types/settings.type';
@@ -39,26 +39,17 @@
let stacksDirectoryInput = $state<FormInputType<string>>({
value: '',
- valid: true,
- touched: false,
- error: null,
- errors: []
+ error: null
});
let baseServerUrlInput = $state<FormInputType<string>>({
value: '',
- valid: true,
- touched: false,
- error: null,
- errors: []
+ error: null
});
let maturityThresholdInput = $state<FormInputType<number>>({
value: 30,
- valid: true,
- touched: false,
- error: null,
- errors: []
+ error: null
});
let isLoading = $state({
diff --git a/frontend/src/routes/volumes/+page.svelte b/frontend/src/routes/volumes/+page.svelte
index 1c3d647bb..97689d00b 100644
--- a/frontend/src/routes/volumes/+page.svelte
+++ b/frontend/src/routes/volumes/+page.svelte
@@ -1,28 +1,29 @@
<script lang="ts">
- import type { PageData } from './$types';
- import * as Card from '$lib/components/ui/card/index.js';
+ import { HardDrive, Trash2, Plus, Funnel, ChevronDown, Ellipsis, ScanSearch } from '@lucide/svelte';
import { Button } from '$lib/components/ui/button/index.js';
- import { toast } from 'svelte-sonner';
- import { AlertCircle, HardDrive, Database, Trash2, Loader2, ChevronDown, Ellipsis, ScanSearch, Funnel } from '@lucide/svelte';
- import UniversalTable from '$lib/components/universal-table.svelte';
+ import * as Card from '$lib/components/ui/card/index.js';
import * as Alert from '$lib/components/ui/alert/index.js';
- import { goto, invalidateAll } from '$app/navigation';
- import CreateVolumeSheet from '$lib/components/sheets/create-volume-sheet.svelte';
- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
import * as Table from '$lib/components/ui/table';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import { toast } from 'svelte-sonner';
+ import { goto, invalidateAll } from '$app/navigation';
import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import type { PageData } from './$types';
+ import UniversalTable from '$lib/components/universal-table.svelte';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
- import VolumeAPIService from '$lib/services/api/volume-api-service';
+ import CreateVolumeSheet from '$lib/components/sheets/create-volume-sheet.svelte';
+ import { formatFriendlyDate } from '$lib/utils/date.utils';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import type { VolumeCreateOptions, VolumeInspectInfo } from 'dockerode';
import ArcaneButton from '$lib/components/arcane-button.svelte';
import { tablePersistence } from '$lib/stores/table-store';
+ import { environmentAPI } from '$lib/services/api';
let { data }: { data: PageData } = $props();
let volumePageStates = $state({
- volumes: data.volumes,
+ volumes: Array.isArray(data.volumes) ? data.volumes : [],
selectedIds: <string[]>[],
error: data.error,
showUsed: true,
@@ -38,12 +39,33 @@
let isLoading = $state({
remove: false,
- creating: false
+ creating: false,
+ refresh: false
});
const totalVolumes = $derived(volumePageStates.volumes.length);
- const volumeApi = new VolumeAPIService();
+ async function refreshVolumes() {
+ isLoading.refresh = true;
+ try {
+ const refreshedVolumes = await environmentAPI.getVolumes();
+ const volumes = Array.isArray(refreshedVolumes) ? refreshedVolumes : [];
+
+ const enhancedVolumes = await Promise.all(
+ volumes.map(async (volume) => {
+ const inUse = await environmentAPI.getVolumeUsage(volume.Name).catch(() => true);
+ return { ...volume, inUse };
+ })
+ );
+
+ volumePageStates.volumes = enhancedVolumes;
+ } catch (error) {
+ console.error('Failed to refresh volumes:', error);
+ toast.error('Failed to refresh volumes');
+ } finally {
+ isLoading.refresh = false;
+ }
+ }
async function handleRemoveVolumeConfirm(volumeName: string) {
openConfirmDialog({
@@ -54,7 +76,7 @@
destructive: true,
action: async () => {
handleApiResultWithCallbacks({
- result: await tryCatch(volumeApi.remove(volumeName)),
+ result: await tryCatch(environmentAPI.deleteVolume(volumeName)),
message: `Failed to Remove Volume "${volumeName}"`,
setLoadingState: (value) => (isLoading.remove = value),
onSuccess: async () => {
@@ -69,7 +91,7 @@
async function handleCreateVolume(volumeCreate: VolumeCreateOptions) {
handleApiResultWithCallbacks({
- result: await tryCatch(volumeApi.create(volumeCreate)),
+ result: await tryCatch(environmentAPI.createVolume(volumeCreate)),
message: `Failed to Create Volume "${volumeCreate.Name}"`,
setLoadingState: (value) => (isLoading.creating = value),
onSuccess: async () => {
@@ -103,7 +125,7 @@
}
if (!volume?.Name) continue;
- const result = await tryCatch(volumeApi.remove(volume.Name));
+ const result = await tryCatch(environmentAPI.deleteVolume(volume.Name));
handleApiResultWithCallbacks({
result,
message: `Failed to delete volume "${volume.Name}"`,
@@ -120,7 +142,6 @@
}
isLoading.remove = false;
- console.log(`Finished deleting. Success: ${successCount}, Failed: ${failureCount}`);
if (successCount > 0) {
setTimeout(async () => {
await invalidateAll();
@@ -133,7 +154,7 @@
}
$effect(() => {
- volumePageStates.volumes = data.volumes;
+ volumePageStates.volumes = Array.isArray(data.volumes) ? data.volumes : [];
});
</script>
@@ -141,14 +162,15 @@
<div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
<div>
<h1 class="text-3xl font-bold tracking-tight">Volumes</h1>
- <p class="text-muted-foreground mt-1 text-sm">Manage persistent data storage for containers</p>
+ <p class="text-muted-foreground mt-1 text-sm">Manage your Docker volumes</p>
+ </div>
+ <div class="flex items-center gap-2">
+ <ArcaneButton action="restart" onClick={refreshVolumes} label="Refresh" loading={isLoading.refresh} disabled={isLoading.refresh} />
</div>
- <div class="flex gap-2"></div>
</div>
{#if volumePageStates.error}
<Alert.Root variant="destructive">
- <AlertCircle class="mr-2 size-4" />
<Alert.Title>Error Loading Volumes</Alert.Title>
<Alert.Description>{volumePageStates.error}</Alert.Description>
</Alert.Root>
@@ -161,8 +183,8 @@
<p class="text-muted-foreground text-sm font-medium">Total Volumes</p>
<p class="text-2xl font-bold">{totalVolumes}</p>
</div>
- <div class="rounded-full bg-amber-500/10 p-2">
- <Database class="size-5 text-amber-500" />
+ <div class="rounded-full bg-blue-500/10 p-2">
+ <HardDrive class="size-5 text-blue-500" />
</div>
</Card.Content>
</Card.Root>
@@ -170,72 +192,75 @@
<Card.Root>
<Card.Content class="flex items-center justify-between p-4">
<div>
- <p class="text-muted-foreground text-sm font-medium">Default Driver</p>
- <p class="text-2xl font-bold">local</p>
+ <p class="text-muted-foreground text-sm font-medium">In Use</p>
+ <p class="text-2xl font-bold">{volumePageStates.volumes.filter((v) => v.inUse).length}</p>
</div>
- <div class="rounded-full bg-blue-500/10 p-2">
- <HardDrive class="size-5 text-blue-500" />
+ <div class="rounded-full bg-green-500/10 p-2">
+ <HardDrive class="size-5 text-green-500" />
</div>
</Card.Content>
</Card.Root>
</div>
- <Card.Root class="border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <div>
+ {#if volumePageStates.volumes && volumePageStates.volumes.length > 0}
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
<Card.Title>Volume List</Card.Title>
+ <div class="flex items-center gap-2">
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="outline">
+ <Funnel class="size-4" />
+ Filter
+ <ChevronDown class="size-4" />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content>
+ <DropdownMenu.Label>Volume Usage</DropdownMenu.Label>
+ <DropdownMenu.CheckboxItem
+ checked={volumePageStates.showUsed}
+ onCheckedChange={(checked) => {
+ volumePageStates.showUsed = checked;
+ }}
+ >
+ Show Used Volumes
+ </DropdownMenu.CheckboxItem>
+ <DropdownMenu.CheckboxItem
+ checked={volumePageStates.showUnused}
+ onCheckedChange={(checked) => {
+ volumePageStates.showUnused = checked;
+ }}
+ >
+ Show Unused Volumes
+ </DropdownMenu.CheckboxItem>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {#if volumePageStates.selectedIds.length > 0}
+ <ArcaneButton action="remove" onClick={handleDeleteSelected} loading={isLoading.remove} disabled={isLoading.remove} />
+ {/if}
+ <ArcaneButton action="create" label="Create Volume" onClick={() => (isDialogOpen.create = true)} loading={isLoading.creating} disabled={isLoading.creating} />
+ </div>
</div>
- <div class="flex items-center gap-2">
- <DropdownMenu.Root>
- <DropdownMenu.Trigger>
- {#snippet child({ props })}
- <Button {...props} variant="outline">
- <Funnel class="size-4" />
- Filter
- <ChevronDown class="size-4" />
- </Button>
- {/snippet}
- </DropdownMenu.Trigger>
- <DropdownMenu.Content>
- <DropdownMenu.Label>Volume Usage</DropdownMenu.Label>
- <DropdownMenu.CheckboxItem
- checked={volumePageStates.showUsed}
- onCheckedChange={(checked) => {
- volumePageStates.showUsed = !!checked;
- }}
- >
- Show Used Volumes
- </DropdownMenu.CheckboxItem>
- <DropdownMenu.CheckboxItem
- checked={volumePageStates.showUnused}
- onCheckedChange={(checked) => {
- volumePageStates.showUnused = !!checked;
- }}
- >
- Show Unused Volumes
- </DropdownMenu.CheckboxItem>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- {#if volumePageStates.selectedIds.length > 0}
- <ArcaneButton action="remove" customLabel="Delete Selected ({volumePageStates.selectedIds.length})" onClick={handleDeleteSelected} loading={isLoading.remove} loadingLabel="Processing..." disabled={isLoading.remove} />
- {/if}
- <ArcaneButton action="create" customLabel="Create Volume" onClick={() => (isDialogOpen.create = true)} />
- </div>
- </div>
- </Card.Header>
- <Card.Content>
- {#if volumePageStates.volumes && volumePageStates.volumes.length > 0}
+ </Card.Header>
+
+ <Card.Content>
<UniversalTable
data={filteredVolumes}
- idKey="Name"
columns={[
{ accessorKey: 'Name', header: 'Name' },
- { accessorKey: 'inUse', header: ' ', enableSorting: false },
- { accessorKey: 'Mountpoint', header: 'Mountpoint' },
+ { accessorKey: 'inUse', header: 'Status', enableSorting: false },
{ accessorKey: 'Driver', header: 'Driver' },
+ { accessorKey: 'CreatedAt', header: 'Created' },
{ accessorKey: 'actions', header: ' ', enableSorting: false }
]}
+ idKey="Name"
+ display={{
+ filterPlaceholder: 'Search volumes...',
+ noResultsMessage: 'No volumes found'
+ }}
pagination={{
pageSize: tablePersistence.getPageSize('volumes')
}}
@@ -245,25 +270,21 @@
sort={{
defaultSort: { id: 'Name', desc: false }
}}
- display={{
- filterPlaceholder: 'Search volumes...',
- noResultsMessage: 'No volumes found matching your filters.'
- }}
bind:selectedIds={volumePageStates.selectedIds}
>
- {#snippet rows({ item }: { item: PageData['volumes'][0] })}
+ {#snippet rows({ item })}
<Table.Cell>
- <div class="flex items-center gap-2">
- <span class="truncate">
- <a class="font-medium hover:underline" href="/volumes/{encodeURIComponent(item.Name)}/">{item.Name}</a>
- </span>
- </div>
+ <a class="font-medium hover:underline" href="/volumes/{item.Name}/">{item.Name}</a>
</Table.Cell>
<Table.Cell>
- <StatusBadge text={item.inUse ? 'In Use' : 'Unused'} variant={item.inUse ? 'green' : 'amber'} />
+ {#if item.inUse}
+ <StatusBadge text="In Use" variant="green" />
+ {:else}
+ <StatusBadge text="Unused" variant="amber" />
+ {/if}
</Table.Cell>
- <Table.Cell>{item.Mountpoint}</Table.Cell>
<Table.Cell>{item.Driver}</Table.Cell>
+ <Table.Cell>{formatFriendlyDate(item.CreatedAt)}</Table.Cell>
<Table.Cell>
<DropdownMenu.Root>
<DropdownMenu.Trigger>
@@ -276,20 +297,13 @@
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
- <DropdownMenu.Item onclick={() => goto(`/volumes/${encodeURIComponent(item.Name)}`)} disabled={isLoading.remove}>
+ <DropdownMenu.Item onclick={() => goto(`/volumes/${item.Name}`)}>
<ScanSearch class="size-4" />
Inspect
</DropdownMenu.Item>
-
- <DropdownMenu.Separator />
-
- <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleRemoveVolumeConfirm(item.Name)} disabled={isLoading.remove || item.inUse}>
- {#if isLoading.remove && volumePageStates.selectedIds.includes(item.Name)}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <Trash2 class="size-4" />
- {/if}
- Delete
+ <DropdownMenu.Item class="focus:text-red-700! text-red-500" onclick={() => handleRemoveVolumeConfirm(item.Name)}>
+ <Trash2 class="size-4" />
+ Remove
</DropdownMenu.Item>
</DropdownMenu.Group>
</DropdownMenu.Content>
@@ -297,18 +311,21 @@
</Table.Cell>
{/snippet}
</UniversalTable>
- {:else if !volumePageStates.error}
- <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
- <Database class="text-muted-foreground mb-4 size-12 opacity-40" />
- <p class="text-lg font-medium">No volumes found</p>
- <p class="text-muted-foreground mt-1 max-w-md text-sm">Create a new volume using the "Create Volume" button above or use the Docker CLI</p>
- <div class="mt-4 flex gap-3">
- <ArcaneButton action="create" customLabel="Create Volume" onClick={() => (isDialogOpen.create = true)} size="sm" />
- </div>
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
+ </Card.Content>
+ </Card.Root>
+ {:else if !volumePageStates.error}
+ <div class="bg-card flex flex-col items-center justify-center rounded-lg border px-6 py-12 text-center">
+ <HardDrive class="text-muted-foreground mb-4 size-12 opacity-40" />
+ <p class="text-lg font-medium">No volumes found</p>
+ <p class="text-muted-foreground mt-1 max-w-md text-sm">Create a new volume using the "Create Volume" button above or use the Docker CLI</p>
+ <div class="mt-4 flex gap-3">
+ <Button variant="outline" size="sm" onclick={() => (isDialogOpen.create = true)}>
+ <Plus class="size-4" />
+ Create Volume
+ </Button>
+ </div>
+ </div>
+ {/if}
<CreateVolumeSheet bind:open={isDialogOpen.create} isLoading={isLoading.creating} onSubmit={(volumeCreateData) => handleCreateVolume(volumeCreateData)} />
</div>
diff --git a/frontend/src/routes/volumes/+page.ts b/frontend/src/routes/volumes/+page.ts
index 2ae01883c..23bada858 100644
--- a/frontend/src/routes/volumes/+page.ts
+++ b/frontend/src/routes/volumes/+page.ts
@@ -1,5 +1,5 @@
+import { environmentAPI } from '$lib/services/api';
import type { PageLoad } from './$types';
-import { volumeAPI } from '$lib/services/api';
import type { VolumeInspectInfo } from 'dockerode';
type EnhancedVolumeInfo = VolumeInspectInfo & {
@@ -13,18 +13,16 @@ type VolumePageData = {
export const load: PageLoad = async (): Promise<VolumePageData> => {
try {
- const volumesData = (await volumeAPI.list()) as VolumeInspectInfo[];
+ const volumesData = await environmentAPI.getVolumes();
+ const volumes = Array.isArray(volumesData) ? volumesData : [];
const enhancedVolumes = await Promise.all(
- volumesData.map(async (volume): Promise<EnhancedVolumeInfo> => {
- const inUse = await volumeAPI.isInUse(volume.Name).catch((err) => {
- console.error(`Failed to check if volume ${volume.Name} is in use:`, err);
- return true; // Default to true for safety
- });
+ volumes.map(async (volume): Promise<EnhancedVolumeInfo> => {
+ const inUse = await environmentAPI.getVolumeUsage(volume.Name);
return {
...volume,
- inUse
+ inUse: inUse.data ? inUse.data.inUse : false
};
})
);
diff --git a/frontend/src/routes/volumes/[volumeName]/+page.svelte b/frontend/src/routes/volumes/[volumeName]/+page.svelte
index 4d8205fdc..1307f58e0 100644
--- a/frontend/src/routes/volumes/[volumeName]/+page.svelte
+++ b/frontend/src/routes/volumes/[volumeName]/+page.svelte
@@ -1,27 +1,24 @@
<script lang="ts">
- import type { PageData, ActionData } from './$types';
+ import type { PageData } from './$types';
import * as Card from '$lib/components/ui/card/index.js';
- import { AlertCircle, HardDrive, Clock, Tag, Layers, Database, Globe, Info } from '@lucide/svelte';
+ import { HardDrive, Clock, Tag, Layers, Database, Globe, Info } from '@lucide/svelte';
import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
import { goto } from '$app/navigation';
- import * as Alert from '$lib/components/ui/alert/index.js';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import { formatDate } from '$lib/utils/string.utils';
import { openConfirmDialog } from '$lib/components/confirm-dialog/';
import { toast } from 'svelte-sonner';
import { tryCatch } from '$lib/utils/try-catch';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
- import VolumeAPIService from '$lib/services/api/volume-api-service';
import ArcaneButton from '$lib/components/arcane-button.svelte';
+ import { environmentAPI } from '$lib/services/api';
- let { data, form }: { data: PageData; form: ActionData } = $props();
+ let { data }: { data: PageData } = $props();
let { volume, inUse } = $derived(data);
let isLoading = $state({ remove: false });
const createdDate = $derived(volume?.CreatedAt ? formatDate(volume.CreatedAt) : 'N/A');
- const volumeApi = new VolumeAPIService();
-
async function handleRemoveVolumeConfirm(volumeName: string) {
let message = 'Are you sure you want to delete this volume? This action cannot be undone.';
@@ -37,7 +34,7 @@
destructive: true,
action: async () => {
handleApiResultWithCallbacks({
- result: await tryCatch(volumeApi.remove(volumeName)),
+ result: await tryCatch(environmentAPI.deleteVolume(volumeName)),
message: 'Failed to Remove Volume',
setLoadingState: (value) => (isLoading.remove = value),
onSuccess: async () => {
@@ -52,7 +49,6 @@
</script>
<div class="space-y-6 pb-8">
- <!-- Improved Header with Better Visual Hierarchy -->
<div class="flex flex-col space-y-4">
<Breadcrumb.Root>
<Breadcrumb.List>
@@ -74,7 +70,6 @@
</h1>
</div>
- <!-- Status badges in a row -->
<div class="mt-2 flex gap-2">
{#if inUse}
<StatusBadge variant="green" text="In Use" />
@@ -92,25 +87,14 @@
</div>
</div>
- <!-- Action Buttons - Replace with ArcaneButton -->
<div class="flex gap-2 self-start">
<ArcaneButton action="remove" customLabel="Remove Volume" onClick={() => handleRemoveVolumeConfirm(volume?.Name)} loading={isLoading.remove} disabled={isLoading.remove} />
</div>
</div>
</div>
- <!-- Error Alert -->
- {#if form?.error}
- <Alert.Root variant="destructive">
- <AlertCircle class="mr-2 size-4" />
- <Alert.Title>Action Failed</Alert.Title>
- <Alert.Description>{form.error}</Alert.Description>
- </Alert.Root>
- {/if}
-
{#if volume}
<div class="space-y-6">
- <!-- Volume Details Card: Improved Layout -->
<Card.Root class="border shadow-sm">
<Card.Header class="pb-0">
<Card.Title class="flex items-center gap-2 text-lg">
@@ -121,7 +105,6 @@
</Card.Header>
<Card.Content class="pt-6">
<div class="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-2 lg:grid-cols-3">
- <!-- Name -->
<div class="flex items-start gap-3">
<div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-gray-500/10 p-2">
<Database class="size-5 text-gray-500" />
@@ -132,7 +115,6 @@
</div>
</div>
- <!-- Driver -->
<div class="flex items-start gap-3">
<div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-blue-500/10 p-2">
<HardDrive class="size-5 text-blue-500" />
@@ -143,7 +125,6 @@
</div>
</div>
- <!-- Created -->
<div class="flex items-start gap-3">
<div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-green-500/10 p-2">
<Clock class="size-5 text-green-500" />
@@ -154,7 +135,6 @@
</div>
</div>
- <!-- Scope -->
<div class="flex items-start gap-3">
<div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-purple-500/10 p-2">
<Globe class="size-5 text-purple-500" />
@@ -165,7 +145,6 @@
</div>
</div>
- <!-- In Use -->
<div class="flex items-start gap-3">
<div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-amber-500/10 p-2">
<Info class="size-5 text-amber-500" />
@@ -182,7 +161,6 @@
</div>
</div>
- <!-- Mountpoint - Full width -->
<div class="col-span-1 flex items-start gap-3 sm:col-span-2 lg:col-span-3">
<div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-teal-500/10 p-2">
<Layers class="size-5 text-teal-500" />
@@ -198,7 +176,6 @@
</Card.Content>
</Card.Root>
- <!-- Labels Card - Enhanced -->
{#if volume.Labels && Object.keys(volume.Labels).length > 0}
<Card.Root class="border shadow-sm">
<Card.Header class="pb-0">
@@ -225,7 +202,6 @@
</Card.Root>
{/if}
- <!-- Driver Options Card - Enhanced -->
{#if volume.Options && Object.keys(volume.Options).length > 0}
<Card.Root class="border shadow-sm">
<Card.Header class="pb-0">
@@ -252,7 +228,6 @@
</Card.Root>
{/if}
- <!-- If no labels or options, we can show this note -->
{#if (!volume.Labels || Object.keys(volume.Labels).length === 0) && (!volume.Options || Object.keys(volume.Options).length === 0)}
<Card.Root class="bg-muted/10 border shadow-sm">
<Card.Content class="pt-6 pb-6 text-center">
@@ -267,7 +242,6 @@
{/if}
</div>
{:else}
- <!-- Volume Not Found with improved styling -->
<div class="flex flex-col items-center justify-center px-4 py-16 text-center">
<div class="bg-muted/30 mb-4 rounded-full p-4">
<Database class="text-muted-foreground size-10 opacity-70" />
diff --git a/frontend/src/routes/volumes/[volumeName]/+page.ts b/frontend/src/routes/volumes/[volumeName]/+page.ts
index e9e30dbe6..38f3416c3 100644
--- a/frontend/src/routes/volumes/[volumeName]/+page.ts
+++ b/frontend/src/routes/volumes/[volumeName]/+page.ts
@@ -1,35 +1,27 @@
import type { PageLoad } from './$types';
-import { volumeAPI } from '$lib/services/api';
+import { environmentAPI } from '$lib/services/api';
import { error } from '@sveltejs/kit';
export const load: PageLoad = async ({ params }) => {
- const volumeName = params.volumeName;
+ const { volumeName } = params;
try {
- const [volume, inUse] = await Promise.all([
- volumeAPI.get(volumeName),
- volumeAPI.isInUse(volumeName).catch((err: unknown) => {
- console.error(`Failed to check if volume ${volumeName} is in use:`, err);
- return true; // Default to true for safety
- })
- ]);
+ const volume = await environmentAPI.getVolume(volumeName);
+
+ if (!volume) {
+ throw error(404, 'Volume not found');
+ }
+ const inUseResponse = await environmentAPI.getVolumeUsage(volumeName);
return {
volume,
- inUse
+ inUse: inUseResponse.data ? inUseResponse.data.inUse : false
};
} catch (err: any) {
- console.error(`Failed to load volume ${volumeName}:`, err);
-
- // Handle API errors
- if (err.status === 404 || err.name === 'NotFoundError') {
- error(404, {
- message: err.message || `Volume with name "${volumeName}" not found.`
- });
- } else {
- error(err.status || 500, {
- message: err.message || `Failed to load volume details for "${volumeName}".`
- });
+ console.error('Failed to load volume:', err);
+ if (err.status === 404) {
+ throw err;
}
+ throw error(500, err.message || 'Failed to load volume details');
}
};
diff --git a/frontend/static/favicon.png b/frontend/static/favicon.png
deleted file mode 100644
index 825b9e65a..000000000
Binary files a/frontend/static/favicon.png and /dev/null differ
diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json
index 0b2d8865f..a8f10c8e3 100644
--- a/frontend/tsconfig.json
+++ b/frontend/tsconfig.json
@@ -11,9 +11,4 @@
"strict": true,
"moduleResolution": "bundler"
}
- // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
- // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
- //
- // If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
- // from the referenced tsconfig.json - TypeScript does not merge them in
}