Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: support for docker swarm (#1493)
Kyle Mendell6c75a7a08c4f
diff --git a/Justfile b/Justfileindex 875a5fb42..4c87ea15c 100644--- a/Justfile+++ b/Justfile@@ -37,6 +37,174 @@ _dev-logs:dev target="docker":@just "_dev-{{ target }}"+# --- Deploy ---+# Deploy a local swarm worker plus a locally built Arcane edge agent into DinD.+#+# Usage:++# just deploy swarm agent [agent_token] [manager_url] [node_name] [agent_name] [dind_image] [local_image]+[group('deploy')]+_deploy-swarm-agent agent_token="" manager_url="http://host.docker.internal:3552" node_name="swarm-worker-1" agent_name="arcane-edge-agent" dind_image="docker:29-dind" local_image="arcane-headless:swarm-local":+ #!/usr/bin/env bash+ set -euo pipefail++ if ! command -v docker >/dev/null 2>&1; then+ echo "docker is required"+ exit 1+ fi++ if ! docker info >/dev/null 2>&1; then+ echo "docker daemon is not running"+ exit 1+ fi++ swarm_state="$(docker info 2>/dev/null | awk -F': ' '/Swarm:/{print tolower($2); exit}')"+ swarm_control="$(docker info 2>/dev/null | awk -F': ' '/Is Manager:/{print tolower($2); exit}')"+ if [ "$swarm_state" != "active" ] || [ "$swarm_control" != "true" ]; then+ echo "host docker must already be an active swarm manager"+ exit 1+ fi++ echo "Building local agent image {{ local_image }}..."+ docker build -f docker/Dockerfile-agent -t "{{ local_image }}" .++ if docker inspect "{{ node_name }}" >/dev/null 2>&1; then+ echo "Reusing existing DinD worker {{ node_name }}..."+ docker start "{{ node_name }}" >/dev/null 2>&1 || true+ else+ echo "Starting DinD worker {{ node_name }} from {{ dind_image }}..."+ docker run -d \+ --privileged \+ --name "{{ node_name }}" \+ --hostname "{{ node_name }}" \+ --restart unless-stopped \+ --add-host=host.docker.internal:host-gateway \+ -e DOCKER_TLS_CERTDIR= \+ "{{ dind_image }}"+ fi++ echo "Waiting for inner Docker daemon..."+ for _ in $(seq 1 30); do+ if docker exec "{{ node_name }}" docker info >/dev/null 2>&1; then+ break+ fi+ sleep 1+ done++ if ! docker exec "{{ node_name }}" docker info >/dev/null 2>&1; then+ echo "inner docker daemon did not become ready"+ exit 1+ fi++ local_node_state="$(docker exec "{{ node_name }}" docker info --format '{{ "{{.Swarm.LocalNodeState}}" }}')"+ if [ "$local_node_state" != "active" ]; then+ join_token="$(docker swarm join-token -q worker)"+ echo "Joining {{ node_name }} to host swarm..."+ docker exec "{{ node_name }}" docker swarm join --token "$join_token" host.docker.internal:2377+ else+ echo "{{ node_name }} is already part of the swarm."+ fi++ current_node_id="$(docker exec "{{ node_name }}" docker info --format '{{ "{{.Swarm.NodeID}}" }}')"+ echo "Current swarm node ID: $current_node_id"++ if [ -n "{{ agent_token }}" ] && command -v sqlite3 >/dev/null 2>&1 && [ -f backend/data/arcane.db ]; then+ expected_node_id="$(sqlite3 backend/data/arcane.db "SELECT COALESCE(swarm_node_id, '') FROM environments WHERE access_token = '{{ agent_token }}' LIMIT 1;")"+ if [ -n "$expected_node_id" ] && [ "$expected_node_id" != "$current_node_id" ]; then+ echo "agent token belongs to swarm node $expected_node_id, but {{ node_name }} is $current_node_id"+ echo "Generate a fresh Arcane agent token from the Deploy Agent dialog for node {{ node_name }}, then rerun this command."+ exit 1+ fi+ fi++ if [ -z "{{ agent_token }}" ]; then+ echo ""+ echo "Swarm worker {{ node_name }} is ready, but no Arcane agent token was provided."+ echo "Open Arcane, click Deploy Agent for node {{ node_name }} (node ID: $current_node_id), copy the generated token, and rerun:"+ echo " just deploy swarm agent <arcane_agent_token> {{ manager_url }} {{ node_name }} {{ agent_name }} {{ dind_image }} {{ local_image }}"+ exit 0+ fi++ echo "Loading local agent image into {{ node_name }}..."+ docker save "{{ local_image }}" | docker exec -i "{{ node_name }}" docker load >/dev/null++ echo "Starting agent container {{ agent_name }} inside {{ node_name }}..."+ docker exec "{{ node_name }}" sh -lc '+ docker rm -f "{{ agent_name }}" >/dev/null 2>&1 || true+ docker run -d \+ --name "{{ agent_name }}" \+ --restart unless-stopped \+ -e EDGE_AGENT=true \+ -e EDGE_TRANSPORT=poll \+ -e AGENT_TOKEN="{{ agent_token }}" \+ -e MANAGER_API_URL="{{ manager_url }}" \+ -v /var/run/docker.sock:/var/run/docker.sock \+ -v arcane-data:/app/data \+ "{{ local_image }}"+ '++ echo ""+ echo "Swarm worker {{ node_name }} and local agent {{ agent_name }} are up."+ echo "Verify:"+ echo " docker node ls"+ echo " docker exec {{ node_name }} docker ps"+ echo " docker exec {{ node_name }} docker logs {{ agent_name }}"++# Remove a local swarm worker plus its Arcane edge agent from DinD.+#+# Usage:+#++# just remove swarm agent [node_name] [agent_name]+[group('deploy')]+_remove-swarm-agent node_name="swarm-worker-1" agent_name="arcane-edge-agent":+ #!/usr/bin/env bash+ set -euo pipefail++ if ! command -v docker >/dev/null 2>&1; then+ echo "docker is required"+ exit 1+ fi++ if ! docker info >/dev/null 2>&1; then+ echo "docker daemon is not running"+ exit 1+ fi++ if ! docker inspect "{{ node_name }}" >/dev/null 2>&1; then+ echo "container {{ node_name }} does not exist"+ exit 1+ fi++ echo "Stopping inner agent container {{ agent_name }} inside {{ node_name }}..."+ docker exec "{{ node_name }}" sh -lc 'docker rm -f "{{ agent_name }}" >/dev/null 2>&1 || true'++ node_id=""+ if docker exec "{{ node_name }}" docker info >/dev/null 2>&1; then+ local_node_state="$(docker exec "{{ node_name }}" docker info --format '{{ "{{.Swarm.LocalNodeState}}" }}' 2>/dev/null || true)"+ if [ "$local_node_state" = "active" ]; then+ node_id="$(docker exec "{{ node_name }}" docker info --format '{{ "{{.Swarm.NodeID}}" }}' 2>/dev/null || true)"+ echo "Leaving swarm from {{ node_name }}..."+ docker exec "{{ node_name }}" docker swarm leave -f >/dev/null 2>&1 || true+ fi+ fi++ if [ -n "$node_id" ]; then+ echo "Removing swarm node $node_id from host manager..."+ docker node rm -f "$node_id" >/dev/null 2>&1 || true+ fi++ echo "Removing DinD worker container {{ node_name }} from host..."+ docker rm -f "{{ node_name }}" >/dev/null++ echo ""+ echo "Removed swarm worker {{ node_name }} and inner agent {{ agent_name }}."++# Deploy targets. Example: just deploy swarm agent [agent_token]+[group('deploy')]+deploy scope kind *args:+ @just "_deploy-{{ scope }}-{{ kind }}" {{ args }}+# Generate edge tunnel protobuf/gRPC code.[group('proto')]proto-backend:diff --git a/backend/internal/api/ws_handler.go b/backend/internal/api/ws_handler.goindex 28c871053..adacf4a49 100644--- a/backend/internal/api/ws_handler.go+++ b/backend/internal/api/ws_handler.go@@ -54,6 +54,7 @@ type WebSocketMetrics struct {containerStats atomic.Int64containerExec atomic.Int64systemStats atomic.Int64+ serviceLogsActive atomic.Int64seq atomic.Uint64mu sync.RWMutexconnections map[string]systemtypes.WebSocketConnectionInfo@@ -74,6 +75,7 @@ func (m *WebSocketMetrics) Snapshot() systemtypes.WebSocketMetricsSnapshot {ContainerStats: m.containerStats.Load(),ContainerExec: m.containerExec.Load(),SystemStats: m.systemStats.Load(),+ ServiceLogsActive: m.serviceLogsActive.Load(),}}@@ -134,6 +136,8 @@ func (m *WebSocketMetrics) applyDelta(kind string, delta int64) {m.containerExec.Add(delta)case systemtypes.WSKindSystemStats:m.systemStats.Add(delta)+ case systemtypes.WSKindServiceLogs:+ m.serviceLogsActive.Add(delta)}}@@ -153,6 +157,7 @@ func DefaultWebSocketMetrics() *WebSocketMetrics {type WebSocketHandler struct {projectService *services.ProjectServicecontainerService *services.ContainerService+ swarmService *services.SwarmServicesystemService *services.SystemServicewsUpgrader websocket.UpgraderwsMetrics *WebSocketMetrics@@ -335,6 +340,7 @@ func NewWebSocketHandler(group *gin.RouterGroup,projectService *services.ProjectService,containerService *services.ContainerService,+ swarmService *services.SwarmService,systemService *services.SystemService,authMiddleware *middleware.AuthMiddleware,cfg *config.Config,@@ -342,6 +348,7 @@ func NewWebSocketHandler(handler := &WebSocketHandler{projectService: projectService,containerService: containerService,+ swarmService: swarmService,systemService: systemService,wsMetrics: defaultWebSocketMetrics,logStreams: make(map[string]*wsLogStream),@@ -361,6 +368,7 @@ func NewWebSocketHandler(wsGroup.GET("/containers/:containerId/logs", handler.ContainerLogs)wsGroup.GET("/containers/:containerId/stats", handler.ContainerStats)wsGroup.GET("/containers/:containerId/terminal", handler.ContainerExec)+ wsGroup.GET("/swarm/services/:serviceId/logs", handler.ServiceLogs)wsGroup.GET("/system/stats", handler.SystemStats)}}@@ -706,6 +714,147 @@ func (h *WebSocketHandler) broadcastContainerLogStreamErrorInternal(containerID,ls.hub.Broadcast([]byte("Failed to stream container logs: " + err.Error()))}+// ============================================================================+// Swarm Service WebSocket/Streaming Endpoints+// ============================================================================++// ServiceLogs streams swarm service logs over WebSocket.+//+// @Summary Get swarm service logs via WebSocket+// @Description Stream swarm service logs over WebSocket connection+// @Tags WebSocket+// @Param id path string true "Environment ID"+// @Param serviceId path string true "Service ID"+// @Param follow query bool false "Follow log output" default(true)+// @Param tail query string false "Number of lines to show from the end" default(100)+// @Param since query string false "Show logs since timestamp"+// @Param timestamps query bool false "Show timestamps" default(false)+// @Param format query string false "Output format (text or json)" default(text)+// @Param batched query bool false "Batch log messages" default(false)+// @Router /api/environments/{id}/ws/swarm/services/{serviceId}/logs [get]+func (h *WebSocketHandler) ServiceLogs(c *gin.Context) {+ environmentID := c.Param("id")+ serviceID := c.Param("serviceId")+ if strings.TrimSpace(serviceID) == "" {+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "Service ID is required"})+ return+ }++ follow := c.DefaultQuery("follow", "true") == "true"+ tail, _ := httputil.GetQueryParam(c, "tail", false)+ if tail == "" {+ tail = "100"+ }+ since, _ := httputil.GetQueryParam(c, "since", false)+ timestamps := c.DefaultQuery("timestamps", "false") == "true"+ format, _ := httputil.GetQueryParam(c, "format", false)+ if format == "" {+ format = "text"+ }+ batched := c.DefaultQuery("batched", "false") == "true"++ conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)+ if err != nil {+ return+ }++ streamKey := buildLogStreamKeyInternal(environmentID, systemtypes.WSKindServiceLogs, serviceID, format, batched, follow, tail, since, timestamps)+ connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindServiceLogs, serviceID))+ stream := h.getOrCreateLogStreamInternal(streamKey, func(onEmpty func(*wsLogStream)) *wsLogStream {+ return h.startServiceLogHub(streamKey, serviceID, format, batched, follow, tail, since, timestamps, onEmpty)+ })+ // WebSocket connections use context.Background() because they are long-lived and should not+ // be tied to the HTTP request context. Cleanup is handled via the hub's OnEmpty callback+ // which triggers when all clients disconnect.+ ws.ServeClientWithOnRemove(context.Background(), stream.hub, conn, func() {+ h.wsMetrics.UnregisterConnection(connID)+ h.releaseLogStreamInternal(streamKey, stream)+ })+}++func (h *WebSocketHandler) startServiceLogHub(key, serviceID, format string, batched, follow bool, tail, since string, timestamps bool, onEmptyHook func(*wsLogStream)) *wsLogStream {+ ls, ctx := newWSLogStreamInternal(key, format)++ ls.hub.SetOnEmpty(func() {+ if onEmptyHook != nil {+ onEmptyHook(ls)+ }+ slog.Debug("client disconnected, cleaning up service log hub", "serviceID", serviceID)+ })++ lines := make(chan string, 256)+ go func() {+ defer close(lines)+ if !waitForLogStreamSubscriberInternal(ctx, ls.firstSubscriber) {+ return+ }++ if err := h.swarmService.StreamServiceLogs(ctx, serviceID, lines, follow, tail, since, timestamps); err != nil {+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {+ return+ }++ h.broadcastServiceLogStreamErrorInternal(serviceID, format, err, ls)+ h.markLogStreamDoneInternal(key, ls)+ return+ }++ if ctx.Err() == nil {+ h.markLogStreamDoneInternal(key, ls)+ }+ }()++ if format == "json" {+ msgs := make(chan ws.LogMessage, 256)+ go func() {+ defer close(msgs)+ for line := range lines {+ level, msg, ts := ws.NormalizeContainerLine(line)+ seq := ls.seq.Add(1)+ timestamp := ts+ if timestamp == "" {+ timestamp = ws.NowRFC3339()+ }+ msgs <- ws.LogMessage{+ Seq: seq,+ Level: level,+ Message: msg,+ Timestamp: timestamp,+ }+ }+ }()+ if batched {+ go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)+ } else {+ go ws.ForwardLogJSON(ctx, ls.hub, msgs)+ }+ } else {+ go ws.ForwardLines(ctx, ls.hub, lines)+ }++ return ls+}++func (h *WebSocketHandler) broadcastServiceLogStreamErrorInternal(serviceID, format string, err error, ls *wsLogStream) {+ slog.Warn("service log stream failed", "serviceID", serviceID, "error", err)++ if format == "json" {+ msg := ws.LogMessage{+ Seq: ls.seq.Add(1),+ Level: "error",+ Message: "Failed to stream service logs: " + err.Error(),+ Service: "arcane",+ Timestamp: ws.NowRFC3339(),+ }+ if b, marshalErr := json.Marshal(msg); marshalErr == nil {+ ls.hub.Broadcast(b)+ }+ return+ }++ ls.hub.Broadcast([]byte("Failed to stream service logs: " + err.Error()))+}+// ContainerStats streams container stats over WebSocket.//// @Summary Get container stats via WebSocket@@ -800,7 +949,11 @@ func (h *WebSocketHandler) ContainerExec(c *gin.Context) {}connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindContainerExec, containerID))defer h.wsMetrics.UnregisterConnection(connID)- defer conn.Close()+ defer func() {+ if err := conn.Close(); err != nil {+ slog.Debug("Failed to close container exec websocket connection", "containerID", containerID, "error", err)+ }+ }()ctx, cancel := context.WithCancel(c.Request.Context())defer cancel()@@ -1277,7 +1430,11 @@ func (h *WebSocketHandler) SystemStats(c *gin.Context) {}connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindSystemStats, ""))defer h.wsMetrics.UnregisterConnection(connID)- defer conn.Close()+ defer func() {+ if err := conn.Close(); err != nil {+ slog.Debug("Failed to close system stats websocket connection", "clientIP", clientIP, "error", err)+ }+ }()interval, _ := httputil.GetIntQueryParam(c, "interval", false)if interval <= 0 {diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex bf1d398c6..0cff77fae 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -145,6 +145,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)Volume: appServices.Volume,Container: appServices.Container,Network: appServices.Network,+ Swarm: appServices.Swarm,Notification: appServices.Notification,Apprise: appServices.Apprise,Updater: appServices.Updater,@@ -167,7 +168,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)api.RegisterDiagnosticsRoutes(apiGroup, authMiddleware, api.DefaultWebSocketMetrics()) //nolint:contextcheck// Remaining Gin handlers (WebSocket/streaming)- api.NewWebSocketHandler(apiGroup, appServices.Project, appServices.Container, appServices.System, authMiddleware, cfg) //nolint:contextcheck+ api.NewWebSocketHandler(apiGroup, appServices.Project, appServices.Container, appServices.Swarm, appServices.System, authMiddleware, cfg) //nolint:contextcheck// Register edge tunnel endpoint for manager to accept agent connections// This is only registered when NOT in agent mode (i.e., running as manager)diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.goindex 0b9722ae6..602651c8d 100644--- a/backend/internal/bootstrap/services_bootstrap.go+++ b/backend/internal/bootstrap/services_bootstrap.go@@ -27,6 +27,7 @@ type Services struct {BuildWorkspace *services.BuildWorkspaceServiceVolume *services.VolumeServiceNetwork *services.NetworkService+ Swarm *services.SwarmServiceImageUpdate *services.ImageUpdateServiceAuth *services.AuthServiceOidc *services.OidcService@@ -65,10 +66,11 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.ConfigdockerClient := services.NewDockerClientService(db, cfg, svcs.Settings)svcs.Docker = dockerClientsvcs.User = services.NewUserService(db)+ svcs.ApiKey = services.NewApiKeyService(db, svcs.User)svcs.ContainerRegistry = services.NewContainerRegistryService(db, func(ctx context.Context) (services.RegistryDaemonClient, error) {return dockerClient.GetClient(ctx)})- svcs.Environment = services.NewEnvironmentService(db, httpClient, svcs.Docker, svcs.Event, svcs.Settings)+ svcs.Environment = services.NewEnvironmentService(db, httpClient, svcs.Docker, svcs.Event, svcs.Settings, svcs.ApiKey)svcs.Notification = services.NewNotificationService(db, cfg, svcs.Environment)svcs.Apprise = services.NewAppriseService(db, cfg)svcs.Vulnerability = services.NewVulnerabilityService(db, svcs.Docker, svcs.Event, svcs.Settings, svcs.Notification)@@ -82,10 +84,10 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Configsvcs.Dashboard = services.NewDashboardService(db, svcs.Docker, svcs.Container, svcs.Settings, svcs.Vulnerability)svcs.Volume = services.NewVolumeService(db, svcs.Docker, svcs.Event, svcs.Settings, svcs.Container, svcs.Image, cfg.BackupVolumeName)svcs.Network = services.NewNetworkService(db, svcs.Docker, svcs.Event)+ svcs.Swarm = services.NewSwarmService(svcs.Docker, svcs.Settings, svcs.ContainerRegistry, svcs.Environment)svcs.Template = services.NewTemplateService(ctx, db, httpClient, svcs.Settings)svcs.Auth = services.NewAuthService(svcs.User, svcs.Settings, svcs.Event, cfg.JWTSecret, cfg)svcs.Oidc = services.NewOidcService(svcs.Auth, cfg, httpClient)- svcs.ApiKey = services.NewApiKeyService(db, svcs.User)svcs.System = services.NewSystemService(db, svcs.Docker, svcs.Container, svcs.Image, svcs.Volume, svcs.Network, svcs.Settings)svcs.Version = services.NewVersionService(httpClient, cfg.UpdateCheckDisabled, config.Version, config.Revision, svcs.ContainerRegistry, svcs.Docker)svcs.SystemUpgrade = services.NewSystemUpgradeService(svcs.Docker, svcs.Version, svcs.Event, svcs.Settings)diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex a02b75912..755e2d1e5 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -1340,3 +1340,103 @@ type VulnerabilityScanRetrievalError struct {func (e *VulnerabilityScanRetrievalError) Error() string {return fmt.Sprintf("Failed to retrieve vulnerability scan: %v", e.Err)}++type SwarmNotEnabledError struct{}++func (e *SwarmNotEnabledError) Error() string {+ return "Swarm mode is not enabled"+}++type SwarmManagerRequiredError struct{}++func (e *SwarmManagerRequiredError) Error() string {+ return "Swarm manager access required"+}++type SwarmServiceListError struct {+ Err error+}++func (e *SwarmServiceListError) Error() string {+ return fmt.Sprintf("Failed to list swarm services: %v", e.Err)+}++type SwarmServiceNotFoundError struct {+ Err error+}++func (e *SwarmServiceNotFoundError) Error() string {+ return fmt.Sprintf("Swarm service not found: %v", e.Err)+}++type SwarmServiceCreateError struct {+ Err error+}++func (e *SwarmServiceCreateError) Error() string {+ return fmt.Sprintf("Failed to create swarm service: %v", e.Err)+}++type SwarmServiceUpdateError struct {+ Err error+}++func (e *SwarmServiceUpdateError) Error() string {+ return fmt.Sprintf("Failed to update swarm service: %v", e.Err)+}++type SwarmServiceRemoveError struct {+ Err error+}++func (e *SwarmServiceRemoveError) Error() string {+ return fmt.Sprintf("Failed to remove swarm service: %v", e.Err)+}++type SwarmNodeListError struct {+ Err error+}++func (e *SwarmNodeListError) Error() string {+ return fmt.Sprintf("Failed to list swarm nodes: %v", e.Err)+}++type SwarmNodeNotFoundError struct {+ Err error+}++func (e *SwarmNodeNotFoundError) Error() string {+ return fmt.Sprintf("Swarm node not found: %v", e.Err)+}++type SwarmTaskListError struct {+ Err error+}++func (e *SwarmTaskListError) Error() string {+ return fmt.Sprintf("Failed to list swarm tasks: %v", e.Err)+}++type SwarmStackListError struct {+ Err error+}++func (e *SwarmStackListError) Error() string {+ return fmt.Sprintf("Failed to list swarm stacks: %v", e.Err)+}++type SwarmStackDeployError struct {+ Err error+}++func (e *SwarmStackDeployError) Error() string {+ return fmt.Sprintf("Failed to deploy swarm stack: %v", e.Err)+}++type SwarmInspectError struct {+ Err error+}++func (e *SwarmInspectError) Error() string {+ return fmt.Sprintf("Failed to inspect swarm: %v", e.Err)+}diff --git a/backend/internal/huma/handlers/notifications_test.go b/backend/internal/huma/handlers/notifications_test.goindex ac1790296..d4c13fdf9 100644--- a/backend/internal/huma/handlers/notifications_test.go+++ b/backend/internal/huma/handlers/notifications_test.go@@ -26,7 +26,7 @@ func setupNotificationHandlerTestService(t *testing.T) (*database.DB, *services.require.NoError(t, db.AutoMigrate(&models.NotificationSettings{}, &models.SettingVariable{}, &models.NotificationLog{}, &models.Environment{}, &models.AppriseSettings{}))databaseDB := &database.DB{DB: db}- envSvc := services.NewEnvironmentService(databaseDB, nil, nil, nil, nil)+ envSvc := services.NewEnvironmentService(databaseDB, nil, nil, nil, nil, nil)return databaseDB, services.NewNotificationService(databaseDB, &config.Config{}, envSvc)}diff --git a/backend/internal/huma/handlers/settings.go b/backend/internal/huma/handlers/settings.goindex 21c8c54ea..7a3285102 100644--- a/backend/internal/huma/handlers/settings.go+++ b/backend/internal/huma/handlers/settings.go@@ -94,6 +94,20 @@ func validateProjectsDirectoryValue(path string) error {}}+// validateAbsoluteDirectoryPath validates a plain absolute directory path allowing:+// - Unix absolute paths (/...)+// - Windows drive paths (C:/..., C:\...)+func validateAbsoluteDirectoryPath(path string) error {+ switch {+ case projects.IsWindowsDrivePath(path):+ return nil+ case strings.HasPrefix(path, "/"):+ return nil+ default:+ return errors.New("must be an absolute path")+ }+}+// RegisterSettings registers settings management routes using Huma.func RegisterSettings(api huma.API, settingsService *services.SettingsService, settingsSearchService *services.SettingsSearchService, environmentService *services.EnvironmentService, cfg *config.Config) {h := &SettingsHandler{@@ -306,58 +320,76 @@ func (h *SettingsHandler) UpdateSettings(ctx context.Context, input *UpdateSettireturn nil, err}+ if err := h.validateSettingsUpdateInput(input.Body); err != nil {+ return nil, err+ }++ if input.EnvironmentID != "0" {+ return h.updateSettingsForRemoteEnvironment(ctx, input)+ }++ return h.updateSettingsForLocalEnvironment(ctx, input.Body)+}++func (h *SettingsHandler) validateSettingsUpdateInput(input settings.Update) error {+// Validate projects directory if provided and changed from current value.// Skip validation when the value matches the current (possibly env-overridden) setting// so that saving unrelated settings doesn't fail due to env-provided directory formats.- if input.Body.ProjectsDirectory != nil && *input.Body.ProjectsDirectory != "" {+ if input.ProjectsDirectory != nil && *input.ProjectsDirectory != "" {currentDir := h.settingsService.GetSettingsConfig().ProjectsDirectory.Value- if *input.Body.ProjectsDirectory != currentDir {- if err := validateProjectsDirectoryValue(*input.Body.ProjectsDirectory); err != nil {- return nil, huma.Error400BadRequest(err.Error())+ if *input.ProjectsDirectory != currentDir {+ if err := validateProjectsDirectoryValue(*input.ProjectsDirectory); err != nil {+ return huma.Error400BadRequest(err.Error())}}}- if input.EnvironmentID != "0" {- if h.environmentService == nil {- return nil, huma.Error500InternalServerError("environment service not available")+ if input.SwarmStackSourcesDirectory != nil && *input.SwarmStackSourcesDirectory != "" {+ currentDir := h.settingsService.GetSettingsConfig().SwarmStackSourcesDirectory.Value+ if *input.SwarmStackSourcesDirectory != currentDir {+ if err := validateAbsoluteDirectoryPath(*input.SwarmStackSourcesDirectory); err != nil {+ return huma.Error400BadRequest("swarmStackSourcesDirectory " + err.Error())+ }}+ }- // Check if trying to update auth settings on non-local environment- req := input.Body- if req.AuthLocalEnabled != nil || req.OidcEnabled != nil ||- req.AuthSessionTimeout != nil || req.AuthPasswordPolicy != nil ||- req.AuthOidcConfig != nil || req.OidcClientId != nil ||- req.OidcClientSecret != nil || req.OidcIssuerUrl != nil ||- req.OidcScopes != nil || req.OidcAdminClaim != nil ||- req.OidcAdminValue != nil || req.OidcMergeAccounts != nil ||- req.OidcSkipTlsVerify != nil || req.OidcAutoRedirectToProvider != nil ||- req.OidcProviderName != nil || req.OidcProviderLogoUrl != nil {- return nil, huma.Error403Forbidden((&common.AuthSettingsUpdateError{}).Error())- }+ return nil+}- body, err := json.Marshal(input.Body)- if err != nil {- return nil, huma.Error500InternalServerError("failed to marshal request body: " + err.Error())- }+func (h *SettingsHandler) updateSettingsForRemoteEnvironment(ctx context.Context, input *UpdateSettingsInput) (*UpdateSettingsOutput, error) {+ if h.environmentService == nil {+ return nil, huma.Error500InternalServerError("environment service not available")+ }- respBody, statusCode, err := h.environmentService.ProxyRequest(ctx, input.EnvironmentID, http.MethodPut, "/api/environments/0/settings", body)- if err != nil {- return nil, huma.Error502BadGateway("failed to proxy request to environment: " + err.Error())- }- if statusCode != http.StatusOK {- return nil, huma.NewError(statusCode, "environment returned error: "+string(respBody), nil)- }+ // Check if trying to update auth settings on non-local environment.+ if hasAuthSettingsUpdate(input.Body) {+ return nil, huma.Error403Forbidden((&common.AuthSettingsUpdateError{}).Error())+ }- var apiResp base.ApiResponse[[]settings.SettingDto]- if err := json.Unmarshal(respBody, &apiResp); err != nil {- return nil, huma.Error500InternalServerError("failed to decode environment response: " + err.Error())- }+ body, err := json.Marshal(input.Body)+ if err != nil {+ return nil, huma.Error500InternalServerError("failed to marshal request body: " + err.Error())+ }++ respBody, statusCode, err := h.environmentService.ProxyRequest(ctx, input.EnvironmentID, http.MethodPut, "/api/environments/0/settings", body)+ if err != nil {+ return nil, huma.Error502BadGateway("failed to proxy request to environment: " + err.Error())+ }+ if statusCode != http.StatusOK {+ return nil, huma.NewError(statusCode, "environment returned error: "+string(respBody), nil)+ }- return &UpdateSettingsOutput{Body: apiResp}, nil+ var apiResp base.ApiResponse[[]settings.SettingDto]+ if err := json.Unmarshal(respBody, &apiResp); err != nil {+ return nil, huma.Error500InternalServerError("failed to decode environment response: " + err.Error())}- updatedSettings, err := h.settingsService.UpdateSettings(ctx, input.Body)+ return &UpdateSettingsOutput{Body: apiResp}, nil+}++func (h *SettingsHandler) updateSettingsForLocalEnvironment(ctx context.Context, input settings.Update) (*UpdateSettingsOutput, error) {+ updatedSettings, err := h.settingsService.UpdateSettings(ctx, input)if err != nil {return nil, huma.Error500InternalServerError((&common.SettingsUpdateError{Err: err}).Error())}@@ -381,6 +413,17 @@ func (h *SettingsHandler) UpdateSettings(ctx context.Context, input *UpdateSetti}, nil}+func hasAuthSettingsUpdate(req settings.Update) bool {+ return req.AuthLocalEnabled != nil || req.OidcEnabled != nil ||+ req.AuthSessionTimeout != nil || req.AuthPasswordPolicy != nil ||+ req.AuthOidcConfig != nil || req.OidcClientId != nil ||+ req.OidcClientSecret != nil || req.OidcIssuerUrl != nil ||+ req.OidcScopes != nil || req.OidcAdminClaim != nil ||+ req.OidcAdminValue != nil || req.OidcMergeAccounts != nil ||+ req.OidcSkipTlsVerify != nil || req.OidcAutoRedirectToProvider != nil ||+ req.OidcProviderName != nil || req.OidcProviderLogoUrl != nil+}+// Search searches settings by query.func (h *SettingsHandler) Search(ctx context.Context, input *SearchSettingsInput) (*SearchSettingsOutput, error) {if h.settingsSearchService == nil {diff --git a/backend/internal/huma/handlers/swarm.go b/backend/internal/huma/handlers/swarm.gonew file mode 100644index 000000000..f4730d3e9--- /dev/null+++ b/backend/internal/huma/handlers/swarm.go@@ -0,0 +1,2022 @@+package handlers++import (+ "context"+ "errors"+ "log/slog"+ "maps"+ "net/http"+ "strings"++ "github.com/containerd/errdefs"+ "github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/internal/common"+ "github.com/getarcaneapp/arcane/backend/internal/config"+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"+ "github.com/getarcaneapp/arcane/backend/internal/models"+ "github.com/getarcaneapp/arcane/backend/internal/services"+ "github.com/getarcaneapp/arcane/backend/pkg/pagination"+ "github.com/getarcaneapp/arcane/types/base"+ swarmtypes "github.com/getarcaneapp/arcane/types/swarm"+)++type SwarmHandler struct {+ swarmService *services.SwarmService+ environmentService *services.EnvironmentService+ eventService *services.EventService+ cfg *config.Config+}++type SwarmPaginatedResponse[T any] struct {+ Success bool `json:"success"`+ Data []T `json:"data"`+ Pagination base.PaginationResponse `json:"pagination"`+}++type ListSwarmServicesInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`+}++type ListSwarmServicesOutput struct {+ Body SwarmPaginatedResponse[swarmtypes.ServiceSummary]+}++type GetSwarmServiceInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ServiceID string `path:"serviceId" doc:"Service ID"`+}++type GetSwarmServiceOutput struct {+ Body base.ApiResponse[swarmtypes.ServiceInspect]+}++type CreateSwarmServiceInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.ServiceCreateRequest `doc:"Service creation request"`+}++type CreateSwarmServiceOutput struct {+ Body base.ApiResponse[swarmtypes.ServiceCreateResponse]+}++type UpdateSwarmServiceInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ServiceID string `path:"serviceId" doc:"Service ID"`+ Body swarmtypes.ServiceUpdateRequest+}++type UpdateSwarmServiceOutput struct {+ Body base.ApiResponse[swarmtypes.ServiceUpdateResponse]+}++type DeleteSwarmServiceInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ServiceID string `path:"serviceId" doc:"Service ID"`+}++type DeleteSwarmServiceOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type ListSwarmServiceTasksInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ServiceID string `path:"serviceId" doc:"Service ID"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`+}++type ListSwarmServiceTasksOutput struct {+ Body SwarmPaginatedResponse[swarmtypes.TaskSummary]+}++type RollbackSwarmServiceInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ServiceID string `path:"serviceId" doc:"Service ID"`+}++type RollbackSwarmServiceOutput struct {+ Body base.ApiResponse[swarmtypes.ServiceUpdateResponse]+}++type ScaleSwarmServiceInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ServiceID string `path:"serviceId" doc:"Service ID"`+ Body swarmtypes.ServiceScaleRequest+}++type ScaleSwarmServiceOutput struct {+ Body base.ApiResponse[swarmtypes.ServiceUpdateResponse]+}++type ListSwarmNodesInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`+}++type ListSwarmNodesOutput struct {+ Body SwarmPaginatedResponse[swarmtypes.NodeSummary]+}++type GetSwarmNodeInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NodeID string `path:"nodeId" doc:"Node ID"`+}++type GetSwarmNodeOutput struct {+ Body base.ApiResponse[swarmtypes.NodeSummary]+}++type GetSwarmNodeAgentDeploymentInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NodeID string `path:"nodeId" doc:"Node ID"`+ Body struct {+ Rotate bool `json:"rotate,omitempty" doc:"Rotate the environment token before generating snippets"`+ }+}++type SwarmNodeAgentDeployment struct {+ DeploymentSnippet+ EnvironmentID string `json:"environmentId"`+ Agent swarmtypes.NodeAgentStatus `json:"agent"`+}++type GetSwarmNodeAgentDeploymentOutput struct {+ Body base.ApiResponse[SwarmNodeAgentDeployment]+}++type GetSwarmNodeIdentityInput struct{}++type GetSwarmNodeIdentityOutput struct {+ Body base.ApiResponse[services.SwarmNodeIdentity]+}++type UpdateSwarmNodeInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NodeID string `path:"nodeId" doc:"Node ID"`+ Body swarmtypes.NodeUpdateRequest+}++type UpdateSwarmNodeOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type DeleteSwarmNodeInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NodeID string `path:"nodeId" doc:"Node ID"`+ Force bool `query:"force" default:"false" doc:"Force node removal"`+}++type DeleteSwarmNodeOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type PromoteSwarmNodeInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NodeID string `path:"nodeId" doc:"Node ID"`+}++type PromoteSwarmNodeOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type DemoteSwarmNodeInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NodeID string `path:"nodeId" doc:"Node ID"`+}++type DemoteSwarmNodeOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type ListSwarmNodeTasksInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NodeID string `path:"nodeId" doc:"Node ID"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`+}++type ListSwarmNodeTasksOutput struct {+ Body SwarmPaginatedResponse[swarmtypes.TaskSummary]+}++type ListSwarmTasksInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`+}++type ListSwarmTasksOutput struct {+ Body SwarmPaginatedResponse[swarmtypes.TaskSummary]+}++type ListSwarmStacksInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`+}++type ListSwarmStacksOutput struct {+ Body SwarmPaginatedResponse[swarmtypes.StackSummary]+}++type DeploySwarmStackInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.StackDeployRequest+}++type DeploySwarmStackOutput struct {+ Body base.ApiResponse[swarmtypes.StackDeployResponse]+}++type GetSwarmStackInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Name string `path:"name" doc:"Stack name"`+}++type GetSwarmStackOutput struct {+ Body base.ApiResponse[swarmtypes.StackInspect]+}++type GetSwarmStackSourceInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Name string `path:"name" doc:"Stack name"`+}++type GetSwarmStackSourceOutput struct {+ Body base.ApiResponse[swarmtypes.StackSource]+}++type DeleteSwarmStackInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Name string `path:"name" doc:"Stack name"`+}++type DeleteSwarmStackOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type ListSwarmStackServicesInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Name string `path:"name" doc:"Stack name"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`+}++type ListSwarmStackServicesOutput struct {+ Body SwarmPaginatedResponse[swarmtypes.ServiceSummary]+}++type ListSwarmStackTasksInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Name string `path:"name" doc:"Stack name"`+ Search string `query:"search" doc:"Search query"`+ Sort string `query:"sort" doc:"Column to sort by"`+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`+ Start int `query:"start" default:"0" doc:"Start index for pagination"`+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`+}++type ListSwarmStackTasksOutput struct {+ Body SwarmPaginatedResponse[swarmtypes.TaskSummary]+}++type RenderSwarmStackConfigInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.StackRenderConfigRequest+}++type RenderSwarmStackConfigOutput struct {+ Body base.ApiResponse[swarmtypes.StackRenderConfigResponse]+}++type GetSwarmInfoInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type GetSwarmInfoOutput struct {+ Body base.ApiResponse[swarmtypes.SwarmInfo]+}++type InitSwarmInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.SwarmInitRequest+}++type InitSwarmOutput struct {+ Body base.ApiResponse[swarmtypes.SwarmInitResponse]+}++type JoinSwarmInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.SwarmJoinRequest+}++type JoinSwarmOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type LeaveSwarmInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.SwarmLeaveRequest+}++type LeaveSwarmOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type UnlockSwarmInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.SwarmUnlockRequest+}++type UnlockSwarmOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type GetSwarmUnlockKeyInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type GetSwarmUnlockKeyOutput struct {+ Body base.ApiResponse[swarmtypes.SwarmUnlockKeyResponse]+}++type GetSwarmJoinTokensInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type GetSwarmJoinTokensOutput struct {+ Body base.ApiResponse[swarmtypes.SwarmJoinTokensResponse]+}++type RotateSwarmJoinTokensInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.SwarmRotateJoinTokensRequest+}++type RotateSwarmJoinTokensOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type UpdateSwarmSpecInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.SwarmUpdateRequest+}++type UpdateSwarmSpecOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type ListSwarmConfigsInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type ListSwarmConfigsOutput struct {+ Body base.ApiResponse[[]swarmtypes.ConfigSummary]+}++type GetSwarmConfigInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ConfigID string `path:"configId" doc:"Config ID"`+}++type GetSwarmConfigOutput struct {+ Body base.ApiResponse[swarmtypes.ConfigSummary]+}++type CreateSwarmConfigInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.ConfigCreateRequest+}++type CreateSwarmConfigOutput struct {+ Body base.ApiResponse[swarmtypes.ConfigSummary]+}++type UpdateSwarmConfigInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ConfigID string `path:"configId" doc:"Config ID"`+ Body swarmtypes.ConfigUpdateRequest+}++type UpdateSwarmConfigOutput struct {+ Body base.ApiResponse[swarmtypes.ConfigSummary]+}++type DeleteSwarmConfigInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ConfigID string `path:"configId" doc:"Config ID"`+}++type DeleteSwarmConfigOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type ListSwarmSecretsInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type ListSwarmSecretsOutput struct {+ Body base.ApiResponse[[]swarmtypes.SecretSummary]+}++type GetSwarmSecretInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ SecretID string `path:"secretId" doc:"Secret ID"`+}++type GetSwarmSecretOutput struct {+ Body base.ApiResponse[swarmtypes.SecretSummary]+}++type CreateSwarmSecretInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.SecretCreateRequest+}++type CreateSwarmSecretOutput struct {+ Body base.ApiResponse[swarmtypes.SecretSummary]+}++type UpdateSwarmSecretInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ SecretID string `path:"secretId" doc:"Secret ID"`+ Body swarmtypes.SecretUpdateRequest+}++type UpdateSwarmSecretOutput struct {+ Body base.ApiResponse[swarmtypes.SecretSummary]+}++type DeleteSwarmSecretInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ SecretID string `path:"secretId" doc:"Secret ID"`+}++type DeleteSwarmSecretOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++// RegisterSwarm registers the Docker Swarm HTTP operations on the provided Huma API.+//+// It wires a SwarmHandler with the supplied services and publishes the full+// swarm route set for services, nodes, tasks, stacks, lifecycle operations,+// configs, and secrets.+//+// api is the Huma API instance that receives the swarm operations.+// swarmSvc provides the underlying swarm business logic.+// environmentSvc provides environment and agent-deployment helpers used by node endpoints.+// eventSvc records audit events for mutating operations when available.+// cfg provides application configuration needed by deployment-snippet endpoints.+func RegisterSwarm(api huma.API, swarmSvc *services.SwarmService, environmentSvc *services.EnvironmentService, eventSvc *services.EventService, cfg *config.Config) {+ h := &SwarmHandler{+ swarmService: swarmSvc,+ environmentService: environmentSvc,+ eventService: eventSvc,+ cfg: cfg,+ }++ huma.Register(api, huma.Operation{OperationID: "list-swarm-services", Method: http.MethodGet, Path: "/environments/{id}/swarm/services", Summary: "List swarm services", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListServices)+ huma.Register(api, huma.Operation{OperationID: "get-swarm-service", Method: http.MethodGet, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Get swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetService)+ huma.Register(api, huma.Operation{OperationID: "create-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services", Summary: "Create swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.CreateService)+ huma.Register(api, huma.Operation{OperationID: "update-swarm-service", Method: http.MethodPut, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Update swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.UpdateService)+ huma.Register(api, huma.Operation{OperationID: "delete-swarm-service", Method: http.MethodDelete, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Delete swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.DeleteService)+ huma.Register(api, huma.Operation{OperationID: "list-swarm-service-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/services/{serviceId}/tasks", Summary: "List tasks for a swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListServiceTasks)+ huma.Register(api, huma.Operation{OperationID: "rollback-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services/{serviceId}/rollback", Summary: "Rollback a swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.RollbackService)+ huma.Register(api, huma.Operation{OperationID: "scale-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services/{serviceId}/scale", Summary: "Scale a swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ScaleService)++ huma.Register(api, huma.Operation{OperationID: "list-swarm-nodes", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes", Summary: "List swarm nodes", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListNodes)+ huma.Register(api, huma.Operation{OperationID: "get-swarm-node", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Get swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetNode)+ huma.Register(api, huma.Operation{OperationID: "get-swarm-node-agent-deployment", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/deployment", Summary: "Get swarm node agent deployment snippets", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetNodeAgentDeployment)+ huma.Register(api, huma.Operation{OperationID: "update-swarm-node", Method: http.MethodPatch, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Update swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.UpdateNode)+ huma.Register(api, huma.Operation{OperationID: "delete-swarm-node", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Delete swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.DeleteNode)+ huma.Register(api, huma.Operation{OperationID: "promote-swarm-node", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/promote", Summary: "Promote swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.PromoteNode)+ huma.Register(api, huma.Operation{OperationID: "demote-swarm-node", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/demote", Summary: "Demote swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.DemoteNode)+ huma.Register(api, huma.Operation{OperationID: "list-swarm-node-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes/{nodeId}/tasks", Summary: "List tasks for a swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListNodeTasks)+ huma.Register(api, huma.Operation{OperationID: "get-swarm-node-identity", Method: http.MethodGet, Path: "/swarm/node-identity", Summary: "Get local swarm node identity", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetNodeIdentity)++ huma.Register(api, huma.Operation{OperationID: "list-swarm-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/tasks", Summary: "List swarm tasks", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListTasks)++ huma.Register(api, huma.Operation{OperationID: "list-swarm-stacks", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks", Summary: "List swarm stacks", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListStacks)+ huma.Register(api, huma.Operation{OperationID: "deploy-swarm-stack", Method: http.MethodPost, Path: "/environments/{id}/swarm/stacks", Summary: "Deploy swarm stack", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.DeployStack)+ huma.Register(api, huma.Operation{OperationID: "get-swarm-stack", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}", Summary: "Get swarm stack", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetStack)+ huma.Register(api, huma.Operation{OperationID: "get-swarm-stack-source", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/source", Summary: "Get swarm stack source", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetStackSource)+ huma.Register(api, huma.Operation{OperationID: "delete-swarm-stack", Method: http.MethodDelete, Path: "/environments/{id}/swarm/stacks/{name}", Summary: "Delete swarm stack", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.DeleteStack)+ huma.Register(api, huma.Operation{OperationID: "list-swarm-stack-services", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/services", Summary: "List swarm stack services", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListStackServices)+ huma.Register(api, huma.Operation{OperationID: "list-swarm-stack-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/tasks", Summary: "List swarm stack tasks", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListStackTasks)+ huma.Register(api, huma.Operation{OperationID: "render-swarm-stack-config", Method: http.MethodPost, Path: "/environments/{id}/swarm/stacks/config/render", Summary: "Render/validate swarm stack config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.RenderStackConfig)++ huma.Register(api, huma.Operation{OperationID: "get-swarm-info", Method: http.MethodGet, Path: "/environments/{id}/swarm/info", Summary: "Get swarm info", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetSwarmInfo)+ huma.Register(api, huma.Operation{OperationID: "init-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/init", Summary: "Initialize swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.InitSwarm)+ huma.Register(api, huma.Operation{OperationID: "join-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/join", Summary: "Join swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.JoinSwarm)+ huma.Register(api, huma.Operation{OperationID: "leave-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/leave", Summary: "Leave swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.LeaveSwarm)+ huma.Register(api, huma.Operation{OperationID: "unlock-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/unlock", Summary: "Unlock swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.UnlockSwarm)+ huma.Register(api, huma.Operation{OperationID: "get-swarm-unlock-key", Method: http.MethodGet, Path: "/environments/{id}/swarm/unlock-key", Summary: "Get swarm unlock key", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetUnlockKey)+ huma.Register(api, huma.Operation{OperationID: "get-swarm-join-tokens", Method: http.MethodGet, Path: "/environments/{id}/swarm/join-tokens", Summary: "Get swarm join tokens", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetJoinTokens)+ huma.Register(api, huma.Operation{OperationID: "rotate-swarm-join-tokens", Method: http.MethodPost, Path: "/environments/{id}/swarm/join-tokens/rotate", Summary: "Rotate swarm join tokens", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.RotateJoinTokens)+ huma.Register(api, huma.Operation{OperationID: "update-swarm-spec", Method: http.MethodPut, Path: "/environments/{id}/swarm/spec", Summary: "Update swarm spec", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.UpdateSwarmSpec)++ huma.Register(api, huma.Operation{OperationID: "list-swarm-configs", Method: http.MethodGet, Path: "/environments/{id}/swarm/configs", Summary: "List swarm configs", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListConfigs)+ huma.Register(api, huma.Operation{OperationID: "get-swarm-config", Method: http.MethodGet, Path: "/environments/{id}/swarm/configs/{configId}", Summary: "Get swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetConfig)+ huma.Register(api, huma.Operation{OperationID: "create-swarm-config", Method: http.MethodPost, Path: "/environments/{id}/swarm/configs", Summary: "Create swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.CreateConfig)+ huma.Register(api, huma.Operation{OperationID: "update-swarm-config", Method: http.MethodPut, Path: "/environments/{id}/swarm/configs/{configId}", Summary: "Update swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.UpdateConfig)+ huma.Register(api, huma.Operation{OperationID: "delete-swarm-config", Method: http.MethodDelete, Path: "/environments/{id}/swarm/configs/{configId}", Summary: "Delete swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.DeleteConfig)++ huma.Register(api, huma.Operation{OperationID: "list-swarm-secrets", Method: http.MethodGet, Path: "/environments/{id}/swarm/secrets", Summary: "List swarm secrets", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListSecrets)+ huma.Register(api, huma.Operation{OperationID: "get-swarm-secret", Method: http.MethodGet, Path: "/environments/{id}/swarm/secrets/{secretId}", Summary: "Get swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetSecret)+ huma.Register(api, huma.Operation{OperationID: "create-swarm-secret", Method: http.MethodPost, Path: "/environments/{id}/swarm/secrets", Summary: "Create swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.CreateSecret)+ huma.Register(api, huma.Operation{OperationID: "update-swarm-secret", Method: http.MethodPut, Path: "/environments/{id}/swarm/secrets/{secretId}", Summary: "Update swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.UpdateSecret)+ huma.Register(api, huma.Operation{OperationID: "delete-swarm-secret", Method: http.MethodDelete, Path: "/environments/{id}/swarm/secrets/{secretId}", Summary: "Delete swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.DeleteSecret)+}++// ListServices lists swarm services for an environment and returns a paginated response.+//+// It normalizes the search, sort, and pagination fields from input, delegates+// the lookup to the swarm service, and returns an empty slice instead of nil+// when no services are found.+//+// ctx carries request-scoped cancellation and auth context.+// input supplies the environment ID plus optional search, sorting, and pagination values.+//+// Returns a successful response containing service summaries and pagination metadata.+// Returns an HTTP-shaped error if the swarm service is unavailable or if the+// underlying swarm lookup fails.+func (h *SwarmHandler) ListServices(ctx context.Context, input *ListSwarmServicesInput) (*ListSwarmServicesOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)+ items, paginationResp, err := h.swarmService.ListServicesPaginated(ctx, params)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmServiceListError{Err: err}).Error())+ }+ if items == nil {+ items = []swarmtypes.ServiceSummary{}+ }++ return &ListSwarmServicesOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil+}++// GetService returns detailed information for a single swarm service.+//+// It loads the service by ID through the swarm service and converts lookup+// failures into the HTTP errors expected by the API.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the environment and the swarm service to inspect.+//+// Returns a successful response containing the service inspection payload.+// Returns `404 Not Found` when the service does not exist and other mapped HTTP+// errors when the inspection fails.+func (h *SwarmHandler) GetService(ctx context.Context, input *GetSwarmServiceInput) (*GetSwarmServiceOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ service, err := h.swarmService.GetService(ctx, input.ServiceID)+ if err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound((&common.SwarmServiceNotFoundError{Err: err}).Error())+ }+ return nil, mapSwarmServiceError(err, (&common.SwarmServiceNotFoundError{Err: err}).Error())+ }++ return &GetSwarmServiceOutput{Body: base.ApiResponse[swarmtypes.ServiceInspect]{Success: true, Data: *service}}, nil+}++// CreateService creates a new swarm service in the target environment.+//+// It requires admin privileges, forwards the create request to the swarm+// service, and records an audit event after a successful mutation.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input contains the environment ID and the requested service specification.+//+// Returns a successful response containing the created service ID and any Docker warnings.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when validation or creation fails.+func (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServiceInput) (*CreateSwarmServiceOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ resp, err := h.swarmService.CreateService(ctx, input.Body)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmServiceCreateError{Err: err}).Error())+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "service.create", "swarm_service", resp.ID, "", map[string]any{"serviceId": resp.ID})++ return &CreateSwarmServiceOutput{Body: base.ApiResponse[swarmtypes.ServiceCreateResponse]{Success: true, Data: *resp}}, nil+}++// UpdateService updates an existing swarm service.+//+// It requires admin privileges, submits the requested versioned update to the+// swarm service, and emits an audit event when the update succeeds.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the service to update and provides the replacement specification and options.+//+// Returns a successful response containing any Docker warnings.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when the update request is invalid or the underlying update fails.+func (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServiceInput) (*UpdateSwarmServiceOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ resp, err := h.swarmService.UpdateService(ctx, input.ServiceID, input.Body)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "service.update", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})++ return &UpdateSwarmServiceOutput{Body: base.ApiResponse[swarmtypes.ServiceUpdateResponse]{Success: true, Data: *resp}}, nil+}++// DeleteService removes a swarm service.+//+// It requires admin privileges, asks the swarm service to remove the service,+// translates missing-service conditions to `404 Not Found`, and records an+// audit event after removal.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and service to remove.+//+// Returns a successful response with a confirmation message.+// Returns an authorization error for non-admin callers, `404 Not Found` when+// the service does not exist, or another mapped HTTP error when removal fails.+func (h *SwarmHandler) DeleteService(ctx context.Context, input *DeleteSwarmServiceInput) (*DeleteSwarmServiceOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.RemoveService(ctx, input.ServiceID); err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound((&common.SwarmServiceNotFoundError{Err: err}).Error())+ }+ return nil, mapSwarmServiceError(err, (&common.SwarmServiceRemoveError{Err: err}).Error())+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "service.delete", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})++ return &DeleteSwarmServiceOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm service removed successfully"}}}, nil+}++// ListServiceTasks lists tasks belonging to a specific swarm service.+//+// It applies the requested search, sort, and pagination values, delegates the+// lookup to the swarm service, and normalizes nil task slices to empty arrays.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the service and supplies optional filtering and pagination fields.+//+// Returns a paginated list of task summaries for the service.+// Returns a mapped HTTP error when the swarm task lookup fails.+func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmServiceTasksInput) (*ListSwarmServiceTasksOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)+ items, paginationResp, err := h.swarmService.ListServiceTasksPaginated(ctx, input.ServiceID, params)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmTaskListError{Err: err}).Error())+ }+ if items == nil {+ items = []swarmtypes.TaskSummary{}+ }++ return &ListSwarmServiceTasksOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil+}++// RollbackService requests a server-side rollback for a swarm service.+//+// It requires admin privileges, delegates the rollback to the swarm service,+// and records an audit event describing the mutation.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and service to roll back.+//+// Returns a successful response containing any warnings reported by Docker.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when the rollback cannot be performed.+func (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarmServiceInput) (*RollbackSwarmServiceOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ resp, err := h.swarmService.RollbackService(ctx, input.ServiceID)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "service.rollback", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID})++ return &RollbackSwarmServiceOutput{Body: base.ApiResponse[swarmtypes.ServiceUpdateResponse]{Success: true, Data: *resp}}, nil+}++// ScaleService changes the replica count of a swarm service.+//+// It requires admin privileges, forwards the requested replica count to the+// swarm service, and records the new replica target in the audit metadata.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the service and supplies the desired replica count.+//+// Returns a successful response containing any warnings reported by Docker.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when scaling is invalid or the update fails.+func (h *SwarmHandler) ScaleService(ctx context.Context, input *ScaleSwarmServiceInput) (*ScaleSwarmServiceOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ resp, err := h.swarmService.ScaleService(ctx, input.ServiceID, input.Body.Replicas)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "service.scale", "swarm_service", input.ServiceID, "", map[string]any{"serviceId": input.ServiceID, "replicas": input.Body.Replicas})++ return &ScaleSwarmServiceOutput{Body: base.ApiResponse[swarmtypes.ServiceUpdateResponse]{Success: true, Data: *resp}}, nil+}++// ListNodes lists swarm nodes for an environment and returns a paginated response.+//+// It applies the requested search, sort, and pagination values and guarantees a+// non-nil node slice in the response body.+//+// ctx carries request-scoped cancellation and auth context.+// input supplies the environment ID plus optional filtering and pagination values.+//+// Returns a paginated list of node summaries.+// Returns a mapped HTTP error when node enumeration fails.+func (h *SwarmHandler) ListNodes(ctx context.Context, input *ListSwarmNodesInput) (*ListSwarmNodesOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)+ items, paginationResp, err := h.swarmService.ListNodesPaginated(ctx, input.EnvironmentID, params)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmNodeListError{Err: err}).Error())+ }+ if items == nil {+ items = []swarmtypes.NodeSummary{}+ }++ return &ListSwarmNodesOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil+}++// GetNode returns detailed information for a single swarm node.+//+// It loads the node through the swarm service and translates not-found+// conditions into the HTTP error returned by the API.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the environment and swarm node to inspect.+//+// Returns a successful response containing the node summary.+// Returns `404 Not Found` when the node does not exist or another mapped HTTP+// error when the inspection fails.+func (h *SwarmHandler) GetNode(ctx context.Context, input *GetSwarmNodeInput) (*GetSwarmNodeOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ node, err := h.swarmService.GetNode(ctx, input.EnvironmentID, input.NodeID)+ if err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound((&common.SwarmNodeNotFoundError{Err: err}).Error())+ }+ return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ }++ return &GetSwarmNodeOutput{Body: base.ApiResponse[swarmtypes.NodeSummary]{Success: true, Data: *node}}, nil+}++// GetNodeAgentDeployment returns deployment snippets for attaching an Arcane agent to a swarm node.+//+// It requires admin privileges, ensures a hidden node-agent environment exists+// for the target node, optionally rotates the environment token, generates edge+// deployment snippets, and refreshes the node summary so the response includes+// the latest agent status.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and node and optionally requests token rotation.+//+// Returns deployment snippets, the backing environment ID, and the refreshed agent status.+// Returns an authorization error for non-admin callers, `401 Unauthorized`+// when the current user cannot be resolved, `404 Not Found` when the node does+// not exist, or `500 Internal Server Error` when environment provisioning or+// snippet generation fails.+func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwarmNodeAgentDeploymentInput) (*GetSwarmNodeAgentDeploymentOutput, error) {+ if h.swarmService == nil || h.environmentService == nil || h.cfg == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ node, err := h.swarmService.GetNode(ctx, input.EnvironmentID, input.NodeID)+ if err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound((&common.SwarmNodeNotFoundError{Err: err}).Error())+ }+ return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ }++ user, ok := humamw.GetCurrentUserFromContext(ctx)+ if !ok || user == nil {+ return nil, huma.Error401Unauthorized("Unauthorized")+ }++ env, apiKey, err := h.environmentService.EnsureSwarmNodeAgentEnvironment(+ ctx,+ input.EnvironmentID,+ input.NodeID,+ node.Hostname,+ user.ID,+ user.Username,+ input.Body.Rotate,+ )+ if err != nil {+ return nil, huma.Error500InternalServerError(err.Error())+ }++ snippets, err := h.environmentService.GenerateEdgeDeploymentSnippets(ctx, env.ID, h.cfg.GetAppURL(), apiKey)+ if err != nil {+ return nil, huma.Error500InternalServerError(err.Error())+ }++ updatedNode, err := h.swarmService.GetNode(ctx, input.EnvironmentID, input.NodeID)+ if err != nil {+ return nil, huma.Error500InternalServerError(err.Error())+ }++ return &GetSwarmNodeAgentDeploymentOutput{+ Body: base.ApiResponse[SwarmNodeAgentDeployment]{+ Success: true,+ Data: SwarmNodeAgentDeployment{+ DeploymentSnippet: DeploymentSnippet{+ DockerRun: snippets.DockerRun,+ DockerCompose: snippets.DockerCompose,+ },+ EnvironmentID: env.ID,+ Agent: updatedNode.Agent,+ },+ },+ }, nil+}++// GetNodeIdentity returns the swarm identity of the node serving the current request.+//+// It is used by edge agents and local nodes to report their swarm node ID,+// hostname, role, engine version, and swarm participation state.+//+// ctx carries request-scoped cancellation and auth context.+// The input value is unused because the endpoint has no parameters.+//+// Returns the local swarm node identity when it can be determined.+// Returns `500 Internal Server Error` when the swarm service is unavailable or+// identity discovery fails.+func (h *SwarmHandler) GetNodeIdentity(ctx context.Context, _ *GetSwarmNodeIdentityInput) (*GetSwarmNodeIdentityOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ identity, err := h.swarmService.GetLocalNodeIdentity(ctx)+ if err != nil {+ return nil, huma.Error500InternalServerError(err.Error())+ }++ return &GetSwarmNodeIdentityOutput{+ Body: base.ApiResponse[services.SwarmNodeIdentity]{+ Success: true,+ Data: *identity,+ },+ }, nil+}++// UpdateNode updates mutable settings on a swarm node.+//+// It requires admin privileges, forwards the requested node changes to the+// swarm service, and records an audit event when the mutation succeeds.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the node to update and contains the requested changes.+//+// Returns a confirmation response when the update succeeds.+// Returns an authorization error for non-admin callers or a mapped HTTP error+// when the node update fails.+func (h *SwarmHandler) UpdateNode(ctx context.Context, input *UpdateSwarmNodeInput) (*UpdateSwarmNodeOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.UpdateNode(ctx, input.NodeID, input.Body); err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "node.update", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})++ return &UpdateSwarmNodeOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node updated successfully"}}}, nil+}++// DeleteNode removes a swarm node from the cluster.+//+// It requires admin privileges, supports forced removal when requested, and+// records the deletion parameters in the audit event metadata.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the node to remove and indicates whether removal should be forced.+//+// Returns a confirmation response when the node is removed.+// Returns an authorization error for non-admin callers or a mapped HTTP error+// when the node cannot be removed.+func (h *SwarmHandler) DeleteNode(ctx context.Context, input *DeleteSwarmNodeInput) (*DeleteSwarmNodeOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.RemoveNode(ctx, input.NodeID, input.Force); err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "node.delete", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID, "force": input.Force})++ return &DeleteSwarmNodeOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node removed successfully"}}}, nil+}++// PromoteNode promotes a swarm worker to manager.+//+// It requires admin privileges, performs the promotion through the swarm+// service, and records an audit event after the role change completes.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the node to promote.+//+// Returns a confirmation response when the promotion succeeds.+// Returns an authorization error for non-admin callers or a mapped HTTP error+// when the promotion fails.+func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeInput) (*PromoteSwarmNodeOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.PromoteNode(ctx, input.NodeID); err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "node.promote", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})++ return &PromoteSwarmNodeOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node promoted successfully"}}}, nil+}++// DemoteNode demotes a swarm manager to worker.+//+// It requires admin privileges, performs the demotion through the swarm+// service, and records an audit event after the role change completes.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the node to demote.+//+// Returns a confirmation response when the demotion succeeds.+// Returns an authorization error for non-admin callers or a mapped HTTP error+// when the demotion fails.+func (h *SwarmHandler) DemoteNode(ctx context.Context, input *DemoteSwarmNodeInput) (*DemoteSwarmNodeOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.DemoteNode(ctx, input.NodeID); err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "node.demote", "swarm_node", input.NodeID, "", map[string]any{"nodeId": input.NodeID})++ return &DemoteSwarmNodeOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node demoted successfully"}}}, nil+}++// ListNodeTasks lists tasks currently associated with a swarm node.+//+// It applies search, sort, and pagination inputs and normalizes nil task lists+// to empty arrays in the API response.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the node and provides optional filtering and pagination values.+//+// Returns a paginated list of node task summaries.+// Returns a mapped HTTP error when the underlying lookup fails.+func (h *SwarmHandler) ListNodeTasks(ctx context.Context, input *ListSwarmNodeTasksInput) (*ListSwarmNodeTasksOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)+ items, paginationResp, err := h.swarmService.ListNodeTasksPaginated(ctx, input.NodeID, params)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmTaskListError{Err: err}).Error())+ }+ if items == nil {+ items = []swarmtypes.TaskSummary{}+ }++ return &ListSwarmNodeTasksOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil+}++// ListTasks lists swarm tasks across the current environment.+//+// It applies the requested search, sort, and pagination fields and guarantees+// an empty task slice when no tasks are returned.+//+// ctx carries request-scoped cancellation and auth context.+// input supplies optional filtering and pagination values.+//+// Returns a paginated task listing for the environment.+// Returns a mapped HTTP error when task enumeration fails.+func (h *SwarmHandler) ListTasks(ctx context.Context, input *ListSwarmTasksInput) (*ListSwarmTasksOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)+ items, paginationResp, err := h.swarmService.ListTasksPaginated(ctx, params)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmTaskListError{Err: err}).Error())+ }+ if items == nil {+ items = []swarmtypes.TaskSummary{}+ }++ return &ListSwarmTasksOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil+}++// ListStacks lists swarm stacks for the current environment.+//+// It applies search, sort, and pagination values supplied by the caller and+// returns an empty stack slice instead of nil when no stacks are present.+//+// ctx carries request-scoped cancellation and auth context.+// input supplies optional filtering and pagination values.+//+// Returns a paginated list of stack summaries.+// Returns a mapped HTTP error when stack enumeration fails.+func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInput) (*ListSwarmStacksOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)+ items, paginationResp, err := h.swarmService.ListStacksPaginated(ctx, params)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmStackListError{Err: err}).Error())+ }+ if items == nil {+ items = []swarmtypes.StackSummary{}+ }++ return &ListSwarmStacksOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil+}++// DeployStack deploys or updates a swarm stack.+//+// It requires admin privileges, submits the stack deployment request to the+// swarm service, and records an audit event keyed by the stack name after the+// deployment succeeds.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the target environment and provides the stack deployment request body.+//+// Returns the deployment response reported by the swarm service.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when rendering, validation, or deployment fails.+func (h *SwarmHandler) DeployStack(ctx context.Context, input *DeploySwarmStackInput) (*DeploySwarmStackOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ resp, err := h.swarmService.DeployStack(ctx, input.EnvironmentID, input.Body)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmStackDeployError{Err: err}).Error())+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "stack.deploy", "swarm_stack", input.Body.Name, input.Body.Name, map[string]any{"stack": input.Body.Name})++ return &DeploySwarmStackOutput{Body: base.ApiResponse[swarmtypes.StackDeployResponse]{Success: true, Data: *resp}}, nil+}++// GetStack returns detailed information for a specific swarm stack.+//+// It looks up the stack by name through the swarm service and maps missing+// stacks to `404 Not Found`.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the environment and stack name to inspect.+//+// Returns the stack inspection payload when the stack exists.+// Returns `404 Not Found` when the stack does not exist or another mapped HTTP+// error when inspection fails.+func (h *SwarmHandler) GetStack(ctx context.Context, input *GetSwarmStackInput) (*GetSwarmStackOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ stack, err := h.swarmService.GetStack(ctx, input.EnvironmentID, input.Name)+ if err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound(("Swarm stack not found"))+ }+ return nil, mapSwarmServiceError(err, "Failed to inspect swarm stack")+ }++ return &GetSwarmStackOutput{Body: base.ApiResponse[swarmtypes.StackInspect]{Success: true, Data: *stack}}, nil+}++// GetStackSource returns the stored source content for a swarm stack.+//+// It requires admin privileges because stack source content can include+// sensitive configuration, and it maps missing stack sources to `404 Not Found`.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the environment and stack whose saved source should be loaded.+//+// Returns the stored compose and environment source for the stack.+// Returns an authorization error for non-admin callers, `404 Not Found` when+// no saved source exists, or another mapped HTTP error when loading fails.+func (h *SwarmHandler) GetStackSource(ctx context.Context, input *GetSwarmStackSourceInput) (*GetSwarmStackSourceOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ source, err := h.swarmService.GetStackSource(ctx, input.EnvironmentID, input.Name)+ if err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound("Swarm stack source not found")+ }+ return nil, mapSwarmServiceError(err, "Failed to load swarm stack source")+ }++ return &GetSwarmStackSourceOutput{Body: base.ApiResponse[swarmtypes.StackSource]{Success: true, Data: *source}}, nil+}++// DeleteStack removes a swarm stack and its managed resources.+//+// It requires admin privileges, delegates the removal to the swarm service,+// maps missing stacks to `404 Not Found`, and records an audit event after+// deletion completes.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and stack name to remove.+//+// Returns a confirmation response when the stack is removed.+// Returns an authorization error for non-admin callers, `404 Not Found` when+// the stack does not exist, or another mapped HTTP error when removal fails.+func (h *SwarmHandler) DeleteStack(ctx context.Context, input *DeleteSwarmStackInput) (*DeleteSwarmStackOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.RemoveStack(ctx, input.EnvironmentID, input.Name); err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound("Swarm stack not found")+ }+ return nil, mapSwarmServiceError(err, "Failed to remove swarm stack")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "stack.delete", "swarm_stack", input.Name, input.Name, map[string]any{"stack": input.Name})++ return &DeleteSwarmStackOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm stack removed successfully"}}}, nil+}++// ListStackServices lists services belonging to a swarm stack.+//+// It applies search, sort, and pagination options, ensures the response uses an+// empty slice instead of nil, and maps missing stacks to `404 Not Found`.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the stack and provides optional filtering and pagination fields.+//+// Returns a paginated list of service summaries for the stack.+// Returns `404 Not Found` when the stack does not exist or another mapped HTTP+// error when the lookup fails.+func (h *SwarmHandler) ListStackServices(ctx context.Context, input *ListSwarmStackServicesInput) (*ListSwarmStackServicesOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)+ items, paginationResp, err := h.swarmService.ListStackServicesPaginated(ctx, input.Name, params)+ if err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound("Swarm stack not found")+ }+ return nil, mapSwarmServiceError(err, "Failed to list swarm stack services")+ }+ if items == nil {+ items = []swarmtypes.ServiceSummary{}+ }++ return &ListSwarmStackServicesOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil+}++// ListStackTasks lists tasks belonging to a swarm stack.+//+// It applies search, sort, and pagination options, ensures the response uses an+// empty slice instead of nil, and maps missing stacks to `404 Not Found`.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the stack and provides optional filtering and pagination fields.+//+// Returns a paginated list of task summaries for the stack.+// Returns `404 Not Found` when the stack does not exist or another mapped HTTP+// error when the lookup fails.+func (h *SwarmHandler) ListStackTasks(ctx context.Context, input *ListSwarmStackTasksInput) (*ListSwarmStackTasksOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)+ items, paginationResp, err := h.swarmService.ListStackTasksPaginated(ctx, input.Name, params)+ if err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound("Swarm stack not found")+ }+ return nil, mapSwarmServiceError(err, "Failed to list swarm stack tasks")+ }+ if items == nil {+ items = []swarmtypes.TaskSummary{}+ }++ return &ListSwarmStackTasksOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil+}++// RenderStackConfig renders and validates a swarm stack configuration without deploying it.+//+// It delegates to the swarm service to parse the provided compose and+// environment content and returns the normalized render result.+//+// ctx carries request-scoped cancellation and auth context.+// input provides the stack render request body.+//+// Returns the rendered compose content together with discovered resource names.+// Returns a mapped HTTP error when parsing, interpolation, or rendering fails.+func (h *SwarmHandler) RenderStackConfig(ctx context.Context, input *RenderSwarmStackConfigInput) (*RenderSwarmStackConfigOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ resp, err := h.swarmService.RenderStackConfig(ctx, input.Body)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to render swarm stack config")+ }++ return &RenderSwarmStackConfigOutput{Body: base.ApiResponse[swarmtypes.StackRenderConfigResponse]{Success: true, Data: *resp}}, nil+}++// GetSwarmInfo returns the current swarm cluster metadata for an environment.+//+// It delegates to the swarm service to inspect the local swarm state and maps+// service-layer failures to the API's HTTP error model.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the environment whose swarm metadata should be returned.+//+// Returns the current swarm information when swarm mode is available.+// Returns a mapped HTTP error when swarm inspection fails.+func (h *SwarmHandler) GetSwarmInfo(ctx context.Context, input *GetSwarmInfoInput) (*GetSwarmInfoOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ info, err := h.swarmService.GetSwarmInfo(ctx)+ if err != nil {+ return nil, mapSwarmServiceError(err, (&common.SwarmInspectError{Err: err}).Error())+ }++ return &GetSwarmInfoOutput{Body: base.ApiResponse[swarmtypes.SwarmInfo]{Success: true, Data: *info}}, nil+}++// InitSwarm initializes swarm mode on the target engine.+//+// It requires admin privileges, delegates the initialization request to the+// swarm service, and records an audit event that includes the created node ID.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and contains the swarm initialization request body.+//+// Returns the initialized swarm node ID and any other initialization details.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when initialization fails.+func (h *SwarmHandler) InitSwarm(ctx context.Context, input *InitSwarmInput) (*InitSwarmOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ resp, err := h.swarmService.InitSwarm(ctx, input.Body)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to initialize swarm")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.init", "swarm", "cluster", "cluster", map[string]any{"nodeId": resp.NodeID})++ return &InitSwarmOutput{Body: base.ApiResponse[swarmtypes.SwarmInitResponse]{Success: true, Data: *resp}}, nil+}++// JoinSwarm joins the target engine to an existing swarm cluster.+//+// It requires admin privileges, forwards the join request to the swarm service,+// and records the remote manager addresses in the audit metadata.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and contains the join request body.+//+// Returns a confirmation response when the engine joins successfully.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when the join operation fails.+func (h *SwarmHandler) JoinSwarm(ctx context.Context, input *JoinSwarmInput) (*JoinSwarmOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.JoinSwarm(ctx, input.Body); err != nil {+ return nil, mapSwarmServiceError(err, "Failed to join swarm")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.join", "swarm", "cluster", "cluster", map[string]any{"remoteAddrs": input.Body.RemoteAddrs})++ return &JoinSwarmOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Joined swarm successfully"}}}, nil+}++// LeaveSwarm removes the target engine from its current swarm cluster.+//+// It requires admin privileges, forwards the leave request to the swarm+// service, and records whether forced removal was requested.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and contains the leave request body.+//+// Returns a confirmation response when the engine leaves successfully.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when the leave operation fails.+func (h *SwarmHandler) LeaveSwarm(ctx context.Context, input *LeaveSwarmInput) (*LeaveSwarmOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.LeaveSwarm(ctx, input.Body); err != nil {+ return nil, mapSwarmServiceError(err, "Failed to leave swarm")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.leave", "swarm", "cluster", "cluster", map[string]any{"force": input.Body.Force})++ return &LeaveSwarmOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Left swarm successfully"}}}, nil+}++// UnlockSwarm unlocks a swarm manager using the supplied unlock key.+//+// It requires admin privileges, delegates the unlock request to the swarm+// service, and emits an audit event after success.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and contains the unlock request body.+//+// Returns a confirmation response when the manager is unlocked.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when the unlock operation fails.+func (h *SwarmHandler) UnlockSwarm(ctx context.Context, input *UnlockSwarmInput) (*UnlockSwarmOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.UnlockSwarm(ctx, input.Body); err != nil {+ return nil, mapSwarmServiceError(err, "Failed to unlock swarm")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.unlock", "swarm", "cluster", "cluster", map[string]any{})++ return &UnlockSwarmOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm unlocked successfully"}}}, nil+}++// GetUnlockKey returns the current swarm manager unlock key.+//+// It delegates to the swarm service and exposes the unlock key in the standard+// API response envelope.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the environment whose unlock key should be returned.+//+// Returns the current manager unlock key.+// Returns a mapped HTTP error when the unlock key cannot be retrieved.+func (h *SwarmHandler) GetUnlockKey(ctx context.Context, input *GetSwarmUnlockKeyInput) (*GetSwarmUnlockKeyOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ resp, err := h.swarmService.GetSwarmUnlockKey(ctx)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to get swarm unlock key")+ }++ return &GetSwarmUnlockKeyOutput{Body: base.ApiResponse[swarmtypes.SwarmUnlockKeyResponse]{Success: true, Data: *resp}}, nil+}++// GetJoinTokens returns the current swarm worker and manager join tokens.+//+// It delegates to the swarm service and wraps the returned tokens in the+// standard API response shape.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the environment whose join tokens should be returned.+//+// Returns the current worker and manager join tokens.+// Returns a mapped HTTP error when token lookup fails.+func (h *SwarmHandler) GetJoinTokens(ctx context.Context, input *GetSwarmJoinTokensInput) (*GetSwarmJoinTokensOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ resp, err := h.swarmService.GetSwarmJoinTokens(ctx)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to get swarm join tokens")+ }++ return &GetSwarmJoinTokensOutput{Body: base.ApiResponse[swarmtypes.SwarmJoinTokensResponse]{Success: true, Data: *resp}}, nil+}++// RotateJoinTokens rotates the swarm worker and or manager join tokens.+//+// It requires admin privileges, delegates the rotation request to the swarm+// service, and records which token classes were rotated.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and contains the requested token-rotation flags.+//+// Returns a confirmation response when rotation succeeds.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when token rotation fails.+func (h *SwarmHandler) RotateJoinTokens(ctx context.Context, input *RotateSwarmJoinTokensInput) (*RotateSwarmJoinTokensOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.RotateSwarmJoinTokens(ctx, input.Body); err != nil {+ return nil, mapSwarmServiceError(err, "Failed to rotate swarm join tokens")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.rotate_tokens", "swarm", "cluster", "cluster", map[string]any{"rotateWorker": input.Body.RotateWorkerToken, "rotateManager": input.Body.RotateManagerToken})++ return &RotateSwarmJoinTokensOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm join tokens rotated successfully"}}}, nil+}++// UpdateSwarmSpec updates the swarm cluster specification.+//+// It requires admin privileges, forwards the request to the swarm service, and+// records an audit event after the spec change succeeds.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and contains the replacement swarm spec.+//+// Returns a confirmation response when the spec update succeeds.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when the spec update fails.+func (h *SwarmHandler) UpdateSwarmSpec(ctx context.Context, input *UpdateSwarmSpecInput) (*UpdateSwarmSpecOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.UpdateSwarmSpec(ctx, input.Body); err != nil {+ return nil, mapSwarmServiceError(err, "Failed to update swarm spec")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.update_spec", "swarm", "cluster", "cluster", map[string]any{})++ return &UpdateSwarmSpecOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm spec updated successfully"}}}, nil+}++// ListConfigs lists swarm configs in the current environment.+//+// It delegates to the swarm service and normalizes nil config slices to empty+// arrays in the response body.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the environment whose configs should be listed.+//+// Returns the current swarm configs.+// Returns a mapped HTTP error when config enumeration fails.+func (h *SwarmHandler) ListConfigs(ctx context.Context, input *ListSwarmConfigsInput) (*ListSwarmConfigsOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ items, err := h.swarmService.ListConfigs(ctx)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to list swarm configs")+ }+ if items == nil {+ items = []swarmtypes.ConfigSummary{}+ }++ return &ListSwarmConfigsOutput{Body: base.ApiResponse[[]swarmtypes.ConfigSummary]{Success: true, Data: items}}, nil+}++// GetConfig returns details for a single swarm config.+//+// It delegates to the swarm service and maps missing configs to+// `404 Not Found`.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the environment and swarm config to inspect.+//+// Returns the config summary when the config exists.+// Returns `404 Not Found` when the config does not exist or another mapped HTTP+// error when inspection fails.+func (h *SwarmHandler) GetConfig(ctx context.Context, input *GetSwarmConfigInput) (*GetSwarmConfigOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ cfg, err := h.swarmService.GetConfig(ctx, input.ConfigID)+ if err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound("Swarm config not found")+ }+ return nil, mapSwarmServiceError(err, "Failed to inspect swarm config")+ }++ return &GetSwarmConfigOutput{Body: base.ApiResponse[swarmtypes.ConfigSummary]{Success: true, Data: *cfg}}, nil+}++// CreateConfig creates a new swarm config.+//+// It requires admin privileges, delegates the creation request to the swarm+// service, and records an audit event containing the created config ID and name.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and contains the config specification.+//+// Returns the created config summary.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when validation or creation fails.+func (h *SwarmHandler) CreateConfig(ctx context.Context, input *CreateSwarmConfigInput) (*CreateSwarmConfigOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ cfg, err := h.swarmService.CreateConfig(ctx, input.Body)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to create swarm config")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "config.create", "swarm_config", cfg.ID, cfg.Spec.Name, map[string]any{"configId": cfg.ID, "name": cfg.Spec.Name})++ return &CreateSwarmConfigOutput{Body: base.ApiResponse[swarmtypes.ConfigSummary]{Success: true, Data: *cfg}}, nil+}++// UpdateConfig updates an existing swarm config.+//+// It requires admin privileges, delegates the update to the swarm service, and+// records an audit event containing the config ID and updated name.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the config to update and contains the replacement specification.+//+// Returns the updated config summary.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when the update fails.+func (h *SwarmHandler) UpdateConfig(ctx context.Context, input *UpdateSwarmConfigInput) (*UpdateSwarmConfigOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ cfg, err := h.swarmService.UpdateConfig(ctx, input.ConfigID, input.Body)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to update swarm config")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "config.update", "swarm_config", input.ConfigID, cfg.Spec.Name, map[string]any{"configId": input.ConfigID, "name": cfg.Spec.Name})++ return &UpdateSwarmConfigOutput{Body: base.ApiResponse[swarmtypes.ConfigSummary]{Success: true, Data: *cfg}}, nil+}++// DeleteConfig removes a swarm config.+//+// It requires admin privileges, delegates removal to the swarm service, maps+// missing configs to `404 Not Found`, and records an audit event on success.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the config to remove.+//+// Returns a confirmation response when the config is removed.+// Returns an authorization error for non-admin callers, `404 Not Found` when+// the config does not exist, or another mapped HTTP error when removal fails.+func (h *SwarmHandler) DeleteConfig(ctx context.Context, input *DeleteSwarmConfigInput) (*DeleteSwarmConfigOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.RemoveConfig(ctx, input.ConfigID); err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound("Swarm config not found")+ }+ return nil, mapSwarmServiceError(err, "Failed to remove swarm config")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "config.delete", "swarm_config", input.ConfigID, "", map[string]any{"configId": input.ConfigID})++ return &DeleteSwarmConfigOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm config removed successfully"}}}, nil+}++// ListSecrets lists swarm secrets in the current environment.+//+// It delegates to the swarm service and normalizes nil secret slices to empty+// arrays in the response body.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the environment whose secrets should be listed.+//+// Returns the current swarm secrets.+// Returns a mapped HTTP error when secret enumeration fails.+func (h *SwarmHandler) ListSecrets(ctx context.Context, input *ListSwarmSecretsInput) (*ListSwarmSecretsOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ items, err := h.swarmService.ListSecrets(ctx)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to list swarm secrets")+ }+ if items == nil {+ items = []swarmtypes.SecretSummary{}+ }++ return &ListSwarmSecretsOutput{Body: base.ApiResponse[[]swarmtypes.SecretSummary]{Success: true, Data: items}}, nil+}++// GetSecret returns details for a single swarm secret.+//+// It delegates to the swarm service and maps missing secrets to+// `404 Not Found`.+//+// ctx carries request-scoped cancellation and auth context.+// input identifies the environment and secret to inspect.+//+// Returns the secret summary when the secret exists.+// Returns `404 Not Found` when the secret does not exist or another mapped HTTP+// error when inspection fails.+func (h *SwarmHandler) GetSecret(ctx context.Context, input *GetSwarmSecretInput) (*GetSwarmSecretOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ secret, err := h.swarmService.GetSecret(ctx, input.SecretID)+ if err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound("Swarm secret not found")+ }+ return nil, mapSwarmServiceError(err, "Failed to inspect swarm secret")+ }++ return &GetSwarmSecretOutput{Body: base.ApiResponse[swarmtypes.SecretSummary]{Success: true, Data: *secret}}, nil+}++// CreateSecret creates a new swarm secret.+//+// It requires admin privileges, delegates the creation request to the swarm+// service, and records an audit event containing the created secret ID and name.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the environment and contains the secret specification.+//+// Returns the created secret summary.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when validation or creation fails.+func (h *SwarmHandler) CreateSecret(ctx context.Context, input *CreateSwarmSecretInput) (*CreateSwarmSecretOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ secret, err := h.swarmService.CreateSecret(ctx, input.Body)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to create swarm secret")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "secret.create", "swarm_secret", secret.ID, secret.Spec.Name, map[string]any{"secretId": secret.ID, "name": secret.Spec.Name})++ return &CreateSwarmSecretOutput{Body: base.ApiResponse[swarmtypes.SecretSummary]{Success: true, Data: *secret}}, nil+}++// UpdateSecret updates an existing swarm secret.+//+// It requires admin privileges, delegates the update to the swarm service, and+// records an audit event containing the secret ID and updated name.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the secret to update and contains the replacement specification.+//+// Returns the updated secret summary.+// Returns an authorization error for non-admin callers or mapped HTTP errors+// when the update fails.+func (h *SwarmHandler) UpdateSecret(ctx context.Context, input *UpdateSwarmSecretInput) (*UpdateSwarmSecretOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ secret, err := h.swarmService.UpdateSecret(ctx, input.SecretID, input.Body)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to update swarm secret")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "secret.update", "swarm_secret", input.SecretID, secret.Spec.Name, map[string]any{"secretId": input.SecretID, "name": secret.Spec.Name})++ return &UpdateSwarmSecretOutput{Body: base.ApiResponse[swarmtypes.SecretSummary]{Success: true, Data: *secret}}, nil+}++// DeleteSecret removes a swarm secret.+//+// It requires admin privileges, delegates removal to the swarm service, maps+// missing secrets to `404 Not Found`, and records an audit event on success.+//+// ctx carries request-scoped cancellation, auth, and audit context.+// input identifies the secret to remove.+//+// Returns a confirmation response when the secret is removed.+// Returns an authorization error for non-admin callers, `404 Not Found` when+// the secret does not exist, or another mapped HTTP error when removal fails.+func (h *SwarmHandler) DeleteSecret(ctx context.Context, input *DeleteSwarmSecretInput) (*DeleteSwarmSecretOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := checkAdmin(ctx); err != nil {+ return nil, err+ }++ if err := h.swarmService.RemoveSecret(ctx, input.SecretID); err != nil {+ if errdefs.IsNotFound(err) {+ return nil, huma.Error404NotFound("Swarm secret not found")+ }+ return nil, mapSwarmServiceError(err, "Failed to remove swarm secret")+ }++ h.auditSwarmMutation(ctx, input.EnvironmentID, "secret.delete", "swarm_secret", input.SecretID, "", map[string]any{"secretId": input.SecretID})++ return &DeleteSwarmSecretOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm secret removed successfully"}}}, nil+}++// toSwarmPaginatedResponse wraps items and pagination metadata in the standard swarm list envelope.+//+// items is the collection to include in the response body.+// p provides the pagination metadata produced by the pagination package.+//+// Returns a SwarmPaginatedResponse with `Success` set to true.+func toSwarmPaginatedResponse[T any](items []T, p pagination.Response) SwarmPaginatedResponse[T] {+ return SwarmPaginatedResponse[T]{+ Success: true,+ Data: items,+ Pagination: base.PaginationResponse{+ TotalPages: p.TotalPages,+ TotalItems: p.TotalItems,+ CurrentPage: p.CurrentPage,+ ItemsPerPage: p.ItemsPerPage,+ GrandTotalItems: p.GrandTotalItems,+ },+ }+}++// auditSwarmMutation writes an informational event for a completed swarm mutation.+//+// It enriches the event with the current user when available, normalizes blank+// environment IDs to the local environment, and logs a warning instead of+// failing the request when event creation is unsuccessful.+//+// ctx carries request-scoped cancellation and user context.+// environmentID identifies the environment associated with the mutation.+// action names the performed swarm action.+// resourceType classifies the mutated resource for the audit trail.+// resourceID identifies the mutated resource when one exists.+// resourceName provides a human-readable resource name when one exists.+// metadata supplies additional structured audit fields to attach to the event.+func (h *SwarmHandler) auditSwarmMutation(ctx context.Context, environmentID, action, resourceType, resourceID, resourceName string, metadata map[string]any) {+ if h.eventService == nil {+ return+ }++ var userID *string+ var username *string+ if user, ok := humamw.GetCurrentUserFromContext(ctx); ok {+ uid := user.ID+ uname := user.Username+ userID = &uid+ username = &uname+ }++ var resourceTypePtr *string+ if strings.TrimSpace(resourceType) != "" {+ rt := resourceType+ resourceTypePtr = &rt+ }+ var resourceIDPtr *string+ if strings.TrimSpace(resourceID) != "" {+ rid := resourceID+ resourceIDPtr = &rid+ }+ var resourceNamePtr *string+ if strings.TrimSpace(resourceName) != "" {+ rn := resourceName+ resourceNamePtr = &rn+ }++ env := strings.TrimSpace(environmentID)+ if env == "" {+ env = "0"+ }+ envPtr := &env++ meta := models.JSON{"action": action}+ maps.Copy(meta, metadata)++ _, err := h.eventService.CreateEvent(ctx, services.CreateEventRequest{+ Type: models.EventType("swarm." + action),+ Severity: models.EventSeverityInfo,+ Title: "Swarm operation: " + action,+ Description: "Swarm operation '" + action + "' completed",+ ResourceType: resourceTypePtr,+ ResourceID: resourceIDPtr,+ ResourceName: resourceNamePtr,+ UserID: userID,+ Username: username,+ EnvironmentID: envPtr,+ Metadata: meta,+ })+ if err != nil {+ slog.WarnContext(ctx, "failed to audit swarm mutation", "action", action, "error", err)+ }+}++// buildSwarmQueryParams converts raw request values into pagination query parameters.+//+// It trims string inputs, applies the default limit used by the swarm API, and+// preserves the requested start offset.+//+// search is the free-text search term.+// sort is the requested sort column.+// order is the requested sort direction.+// start is the zero-based pagination offset.+// limit is the requested page size.+//+// Returns normalized pagination.QueryParams for downstream service calls.+func buildSwarmQueryParams(search, sort, order string, start, limit int) pagination.QueryParams {+ if limit == 0 {+ limit = 20+ }++ return pagination.QueryParams{+ SearchQuery: pagination.SearchQuery{+ Search: strings.TrimSpace(search),+ },+ SortParams: pagination.SortParams{+ Sort: strings.TrimSpace(sort),+ Order: pagination.SortOrder(order),+ },+ PaginationParams: pagination.PaginationParams{+ Start: start,+ Limit: limit,+ },+ }+}++// mapSwarmServiceError converts swarm-service errors into Huma HTTP errors.+//+// It recognizes Arcane's swarm sentinel errors, common Docker error classes,+// and a small set of validation-like substrings before falling back to an+// internal-server-error response.+//+// err is the original service-layer error to translate.+// fallback is the generic message returned when no specific mapping applies.+//+// Returns an HTTP-shaped error suitable for returning from a Huma handler.+func mapSwarmServiceError(err error, fallback string) error {+ if errors.Is(err, services.ErrSwarmNotEnabled) {+ return huma.Error409Conflict((&common.SwarmNotEnabledError{}).Error())+ }+ if errors.Is(err, services.ErrSwarmManagerRequired) {+ return huma.Error403Forbidden((&common.SwarmManagerRequiredError{}).Error())+ }+ if errdefs.IsNotFound(err) {+ return huma.Error404NotFound(err.Error())+ }+ if errdefs.IsInvalidArgument(err) {+ return huma.Error400BadRequest(err.Error())+ }+ if errdefs.IsConflict(err) {+ return huma.Error409Conflict(err.Error())+ }+ errText := strings.ToLower(err.Error())+ if strings.Contains(errText, "required") || strings.Contains(errText, "invalid") || strings.Contains(errText, "immutable") {+ return huma.Error400BadRequest(err.Error())+ }+ return huma.Error500InternalServerError(fallback)+}diff --git a/backend/internal/huma/handlers/templates.go b/backend/internal/huma/handlers/templates.goindex 8f1bb901d..b2f51c0de 100644--- a/backend/internal/huma/handlers/templates.go+++ b/backend/internal/huma/handlers/templates.go@@ -639,14 +639,18 @@ func (h *TemplateHandler) GetDefaultTemplates(ctx context.Context, _ *GetDefault}composeTemplate := h.templateService.GetComposeTemplate()+ swarmStackTemplate := h.templateService.GetSwarmStackTemplate()+ swarmStackEnvTemplate := h.templateService.GetSwarmStackEnvTemplate()envTemplate := h.templateService.GetEnvTemplate()return &GetDefaultTemplatesOutput{Body: base.ApiResponse[template.DefaultTemplatesResponse]{Success: true,Data: template.DefaultTemplatesResponse{- ComposeTemplate: composeTemplate,- EnvTemplate: envTemplate,+ ComposeTemplate: composeTemplate,+ SwarmStackTemplate: swarmStackTemplate,+ SwarmStackEnvTemplate: swarmStackEnvTemplate,+ EnvTemplate: envTemplate,},},}, nildiff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.goindex 0db6c4f59..db156f220 100644--- a/backend/internal/huma/huma.go+++ b/backend/internal/huma/huma.go@@ -160,6 +160,7 @@ type Services struct {Volume *services.VolumeServiceContainer *services.ContainerServiceNetwork *services.NetworkService+ Swarm *services.SwarmServiceNotification *services.NotificationServiceApprise *services.AppriseService //nolint:staticcheck // Apprise still functional, deprecated in favor of ShoutrrrUpdater *services.UpdaterService@@ -322,6 +323,7 @@ func registerHandlers(api huma.API, svc *Services) {var volumeSvc *services.VolumeServicevar containerSvc *services.ContainerServicevar networkSvc *services.NetworkService+ var swarmSvc *services.SwarmServicevar notificationSvc *services.NotificationServicevar appriseSvc *services.AppriseService //nolint:staticcheck // Apprise still functional, deprecated in favor of Shoutrrrvar updaterSvc *services.UpdaterService@@ -358,6 +360,7 @@ func registerHandlers(api huma.API, svc *Services) {volumeSvc = svc.VolumecontainerSvc = svc.ContainernetworkSvc = svc.Network+ swarmSvc = svc.SwarmnotificationSvc = svc.NotificationappriseSvc = svc.AppriseupdaterSvc = svc.Updater@@ -391,6 +394,7 @@ func registerHandlers(api huma.API, svc *Services) {handlers.RegisterVolumes(api, dockerSvc, volumeSvc)handlers.RegisterContainers(api, containerSvc, dockerSvc)handlers.RegisterNetworks(api, networkSvc, dockerSvc)+ handlers.RegisterSwarm(api, swarmSvc, environmentSvc, eventSvc, cfg)handlers.RegisterNotifications(api, notificationSvc, appriseSvc, cfg)handlers.RegisterUpdater(api, updaterSvc)handlers.RegisterCustomize(api, customizeSearchSvc)diff --git a/backend/internal/models/environment.go b/backend/internal/models/environment.goindex 0a4a77ec7..ecd7b388d 100644--- a/backend/internal/models/environment.go+++ b/backend/internal/models/environment.go@@ -3,14 +3,17 @@ package modelsimport "time"type Environment struct {- Name string `json:"name" sortable:"true"`- ApiUrl string `json:"apiUrl" gorm:"column:api_url" sortable:"true"`- Status string `json:"status" sortable:"true"`- Enabled bool `json:"enabled" sortable:"true"`- IsEdge bool `json:"isEdge" gorm:"column:is_edge;default:false"`- LastSeen *time.Time `json:"lastSeen" gorm:"column:last_seen"`- AccessToken *string `json:"-" gorm:"column:access_token"`- ApiKeyID *string `json:"-" gorm:"column:api_key_id"`+ Name string `json:"name" sortable:"true"`+ ApiUrl string `json:"apiUrl" gorm:"column:api_url" sortable:"true"`+ Status string `json:"status" sortable:"true"`+ Enabled bool `json:"enabled" sortable:"true"`+ IsEdge bool `json:"isEdge" gorm:"column:is_edge;default:false"`+ Hidden bool `json:"hidden" gorm:"column:hidden;default:false"`+ LastSeen *time.Time `json:"lastSeen" gorm:"column:last_seen"`+ AccessToken *string `json:"-" gorm:"column:access_token"`+ ApiKeyID *string `json:"-" gorm:"column:api_key_id"`+ ParentEnvironmentID *string `json:"-" gorm:"column:parent_environment_id"`+ SwarmNodeID *string `json:"-" gorm:"column:swarm_node_id"`BaseModel}diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.goindex 8afd685de..fe3febe7e 100644--- a/backend/internal/models/settings.go+++ b/backend/internal/models/settings.go@@ -59,16 +59,17 @@ func (s SettingVariable) AsDurationSeconds() time.Duration {type Settings struct {// General category- ProjectsDirectory SettingVariable `key:"projectsDirectory,envOverride" meta:"label=Projects Directory;type=text;keywords=projects,directory,path,folder,location,storage,files,compose,docker-compose;category=internal;description=Configure where project files are stored"`- FollowProjectSymlinks SettingVariable `key:"followProjectSymlinks,envOverride" meta:"label=Follow Project Symlinks;type=boolean;keywords=projects,symlink,symlinks,symbolic links,compose,directory,discovery;category=general;description=Treat symlinked child directories inside the projects directory as Docker Compose projects"`- DiskUsagePath SettingVariable `key:"diskUsagePath" meta:"label=Disk Usage Path;type=text;keywords=disk,usage,path,storage,folder,files;category=general;description=Path used for disk usage calculations"`- BaseServerURL SettingVariable `key:"baseServerUrl" meta:"label=Base Server URL;type=text;keywords=base,url,server,domain,host,endpoint,address,link;category=general;description=Set the base URL for the application"`- EnableGravatar SettingVariable `key:"enableGravatar" meta:"label=Enable Gravatar;type=boolean;keywords=gravatar,avatar,profile,picture,image,user,photo;category=general;description=Enable Gravatar profile pictures for users"`- DefaultShell SettingVariable `key:"defaultShell" meta:"label=Default Shell;type=text;keywords=shell,default,shellpath,path,login;category=general;description=Default shell to use for commands"`- EnvironmentHealthInterval SettingVariable `key:"environmentHealthInterval" meta:"label=Environment Health Check Interval;type=cron;keywords=environment,health,check,interval,frequency,heartbeat,status,monitoring,uptime,jobs,schedule;description=How often to check environment connectivity (cron expression)" catmeta:"id=jobschedule;title=Job Schedule;icon=jobs;url=/settings/jobs;description=Configure how often Arcane background jobs run"`- ApplicationTheme SettingVariable `key:"applicationTheme,public,local" meta:"label=Application Theme;type=select;keywords=theme,appearance,style,visual,palette,background,interface,ui;category=appearance;description=Choose the overall visual theme for the application"`- AccentColor SettingVariable `key:"accentColor,public,local" meta:"label=Accent Color;type=text;keywords=color,accent,theme,css,appearance,ui;category=general;description=Primary accent color for UI"`- OledMode SettingVariable `key:"oledMode,public,local" meta:"label=OLED Mode;type=boolean;keywords=oled,dark,theme,black,amoled,appearance,display;category=general;description=Use true-black backgrounds for OLED displays (only active in dark mode)"`+ ProjectsDirectory SettingVariable `key:"projectsDirectory,envOverride" meta:"label=Projects Directory;type=text;keywords=projects,directory,path,folder,location,storage,files,compose,docker-compose;category=internal;description=Configure where project files are stored"`+ FollowProjectSymlinks SettingVariable `key:"followProjectSymlinks,envOverride" meta:"label=Follow Project Symlinks;type=boolean;keywords=projects,symlink,symlinks,symbolic links,compose,directory,discovery;category=general;description=Treat symlinked child directories inside the projects directory as Docker Compose projects"`+ SwarmStackSourcesDirectory SettingVariable `key:"swarmStackSourcesDirectory,envOverride" meta:"label=Swarm Stack Sources Directory;type=text;keywords=swarm,stacks,stack,source,sources,directory,path,folder,location,storage,compose,env;category=internal;description=Configure where swarm stack source files are stored"`+ DiskUsagePath SettingVariable `key:"diskUsagePath" meta:"label=Disk Usage Path;type=text;keywords=disk,usage,path,storage,folder,files;category=general;description=Path used for disk usage calculations"`+ BaseServerURL SettingVariable `key:"baseServerUrl" meta:"label=Base Server URL;type=text;keywords=base,url,server,domain,host,endpoint,address,link;category=general;description=Set the base URL for the application"`+ EnableGravatar SettingVariable `key:"enableGravatar" meta:"label=Enable Gravatar;type=boolean;keywords=gravatar,avatar,profile,picture,image,user,photo;category=general;description=Enable Gravatar profile pictures for users"`+ DefaultShell SettingVariable `key:"defaultShell" meta:"label=Default Shell;type=text;keywords=shell,default,shellpath,path,login;category=general;description=Default shell to use for commands"`+ EnvironmentHealthInterval SettingVariable `key:"environmentHealthInterval" meta:"label=Environment Health Check Interval;type=cron;keywords=environment,health,check,interval,frequency,heartbeat,status,monitoring,uptime,jobs,schedule;description=How often to check environment connectivity (cron expression)" catmeta:"id=jobschedule;title=Job Schedule;icon=jobs;url=/settings/jobs;description=Configure how often Arcane background jobs run"`+ ApplicationTheme SettingVariable `key:"applicationTheme,public,local" meta:"label=Application Theme;type=select;keywords=theme,appearance,style,visual,palette,background,interface,ui;category=appearance;description=Choose the overall visual theme for the application"`+ AccentColor SettingVariable `key:"accentColor,public,local" meta:"label=Accent Color;type=text;keywords=color,accent,theme,css,appearance,ui;category=general;description=Primary accent color for UI"`+ OledMode SettingVariable `key:"oledMode,public,local" meta:"label=OLED Mode;type=boolean;keywords=oled,dark,theme,black,amoled,appearance,display;category=general;description=Use true-black backgrounds for OLED displays (only active in dark mode)"`// Docker categoryAutoUpdate SettingVariable `key:"autoUpdate" meta:"label=Auto Update;type=boolean;keywords=auto,update,automatic,upgrade,refresh,restart,deploy;category=internal;description=Automatically update containers when new images are available"`diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.goindex 069ef39f7..344b5e769 100644--- a/backend/internal/services/container_service.go+++ b/backend/internal/services/container_service.go@@ -658,7 +658,7 @@ func (s *ContainerService) streamContainerLogsInternal(ctx context.Context, logsreturn s.streamRawLogsInternal(ctx, logs, logsChan)}if follow {- return s.streamMultiplexedLogs(ctx, logs, logsChan)+ return streamMultiplexedLogs(ctx, logs, logsChan)}return s.readAllLogs(ctx, logs, logsChan)}@@ -667,59 +667,6 @@ func (s *ContainerService) streamRawLogsInternal(ctx context.Context, logs io.Rereturn s.readLogsFromReader(ctx, logs, logsChan, "")}-func (s *ContainerService) streamMultiplexedLogs(ctx context.Context, logs io.Reader, logsChan chan<- string) error {- // Use stdcopy to demultiplex Docker's stream format- // Docker multiplexes stdout and stderr in a special format- stdoutReader, stdoutWriter := io.Pipe()- stderrReader, stderrWriter := io.Pipe()- errCh := make(chan error, 3)-- // Start demultiplexing in a goroutine- go func() {- _, err := stdcopy.StdCopy(stdoutWriter, stderrWriter, logs)- if err != nil && !errors.Is(err, io.EOF) {- _ = stdoutWriter.CloseWithError(err)- _ = stderrWriter.CloseWithError(err)- errCh <- fmt.Errorf("failed to demultiplex logs: %w", err)- return- }- _ = stdoutWriter.Close()- _ = stderrWriter.Close()- errCh <- nil- }()-- // Read from both stdout and stderr concurrently- go func() {- defer func() { _ = stdoutReader.Close() }()- errCh <- s.readLogsFromReader(ctx, stdoutReader, logsChan, "")- }()-- go func() {- defer func() { _ = stderrReader.Close() }()- errCh <- s.readLogsFromReader(ctx, stderrReader, logsChan, "[STDERR] ")- }()-- var firstErr error- for range 3 {- err := <-errCh- switch {- case err == nil:- case errors.Is(err, io.EOF):- case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):- default:- if firstErr == nil {- firstErr = err- }- }- }-- if err := ctx.Err(); err != nil {- return err- }-- return firstErr-}-// readLogsFromReader reads logs line by line from a readerfunc (s *ContainerService) readLogsFromReader(ctx context.Context, reader io.Reader, logsChan chan<- string, prefix string) error {bufferedReader := bufio.NewReader(reader)diff --git a/backend/internal/services/container_service_test.go b/backend/internal/services/container_service_test.goindex 4ec73acad..2c4d2a7af 100644--- a/backend/internal/services/container_service_test.go+++ b/backend/internal/services/container_service_test.go@@ -187,14 +187,13 @@ func TestStreamMultiplexedLogs_ContextCancelDoesNotDeadlock(t *testing.T) {writeDockerLogFrameInternal(t, &stream, 1, "line 2\n")writeDockerLogFrameInternal(t, &stream, 1, "line 3\n")- service := &ContainerService{}logsChan := make(chan string, 1)ctx, cancel := context.WithCancel(context.Background())defer cancel()done := make(chan error, 1)go func() {- done <- service.streamMultiplexedLogs(ctx, io.NopCloser(bytes.NewReader(stream.Bytes())), logsChan)+ done <- streamMultiplexedLogs(ctx, io.NopCloser(bytes.NewReader(stream.Bytes())), logsChan)}()require.Eventually(t, func() bool {diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.goindex 900ccf56c..658d3fd11 100644--- a/backend/internal/services/environment_service.go+++ b/backend/internal/services/environment_service.go@@ -33,6 +33,7 @@ type EnvironmentService struct {dockerService *DockerClientServiceeventService *EventServicesettingsService *SettingsService+ apiKeyService *ApiKeyServicetokenCacheMu sync.RWMutextokenCache map[string]edgeTokenCacheEntrytokenByEnvID map[string]string@@ -50,7 +51,7 @@ var (ErrInvalidEnvironmentAccessToken = errors.New("invalid environment access token"))-func NewEnvironmentService(db *database.DB, httpClient *http.Client, dockerService *DockerClientService, eventService *EventService, settingsService *SettingsService) *EnvironmentService {+func NewEnvironmentService(db *database.DB, httpClient *http.Client, dockerService *DockerClientService, eventService *EventService, settingsService *SettingsService, apiKeyService *ApiKeyService) *EnvironmentService {if httpClient == nil {httpClient = http.DefaultClient}@@ -60,6 +61,7 @@ func NewEnvironmentService(db *database.DB, httpClient *http.Client, dockerServidockerService: dockerService,eventService: eventService,settingsService: settingsService,+ apiKeyService: apiKeyService,tokenCache: make(map[string]edgeTokenCacheEntry),tokenByEnvID: make(map[string]string),}@@ -242,6 +244,169 @@ func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environmentreturn environment, nil}+func (s *EnvironmentService) ListSwarmNodeAgentEnvironments(ctx context.Context, parentEnvironmentID string) ([]models.Environment, error) {+ var envs []models.Environment+ if err := s.db.WithContext(ctx).+ Model(&models.Environment{}).+ Where("hidden = ?", true).+ Where("parent_environment_id = ?", parentEnvironmentID).+ Find(&envs).Error; err != nil {+ return nil, fmt.Errorf("failed to list swarm node agent environments: %w", err)+ }++ return envs, nil+}++func buildSwarmNodeAgentNameInternal(hostname, nodeID string) string {+ trimmedHostname := strings.TrimSpace(hostname)+ if trimmedHostname != "" {+ return fmt.Sprintf("Swarm Node Agent - %s", trimmedHostname)+ }+ if len(nodeID) > 12 {+ nodeID = nodeID[:12]+ }+ return fmt.Sprintf("Swarm Node Agent - %s", nodeID)+}++func buildSwarmNodeAgentURLInternal(nodeID string) string {+ shortNodeID := nodeID+ if len(shortNodeID) > 12 {+ shortNodeID = shortNodeID[:12]+ }+ return "edge://swarm-node-" + shortNodeID+}++func (s *EnvironmentService) applySwarmNodeAgentApiKeyInternal(+ ctx context.Context,+ env *models.Environment,+ userID, username string,+ rotate bool,+) (string, error) {+ if env == nil {+ return "", fmt.Errorf("environment is required")+ }++ if !rotate && env.AccessToken != nil && strings.TrimSpace(*env.AccessToken) != "" {+ return strings.TrimSpace(*env.AccessToken), nil+ }++ if s.apiKeyService == nil {+ return "", fmt.Errorf("api key service not configured")+ }++ apiKeyDto, err := s.apiKeyService.CreateEnvironmentApiKey(ctx, env.ID, userID)+ if err != nil {+ return "", fmt.Errorf("failed to create environment API key: %w", err)+ }++ if err := s.RegenerateEnvironmentApiKey(ctx, env.ID, apiKeyDto.ID, apiKeyDto.Key, userID, username, env.Name); err != nil {+ return "", err+ }++ return apiKeyDto.Key, nil+}++func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(+ ctx context.Context,+ parentEnvironmentID, nodeID, hostname, userID, username string,+ rotate bool,+) (*models.Environment, string, error) {+ if strings.TrimSpace(parentEnvironmentID) == "" {+ return nil, "", fmt.Errorf("parent environment ID is required")+ }+ if strings.TrimSpace(nodeID) == "" {+ return nil, "", fmt.Errorf("swarm node ID is required")+ }++ var env models.Environment+ err := s.db.WithContext(ctx).+ Where("hidden = ?", true).+ Where("parent_environment_id = ?", parentEnvironmentID).+ Where("swarm_node_id = ?", nodeID).+ First(&env).Error+ if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, "", fmt.Errorf("failed to load swarm node agent environment: %w", err)+ }++ if errors.Is(err, gorm.ErrRecordNotFound) {+ parentEnvironmentIDCopy := parentEnvironmentID+ nodeIDCopy := nodeID+ createdEnv := &models.Environment{+ Name: buildSwarmNodeAgentNameInternal(hostname, nodeID),+ ApiUrl: buildSwarmNodeAgentURLInternal(nodeID),+ Status: string(models.EnvironmentStatusPending),+ Enabled: true,+ IsEdge: true,+ Hidden: true,+ ParentEnvironmentID: &parentEnvironmentIDCopy,+ SwarmNodeID: &nodeIDCopy,+ }++ userIDCopy := userID+ usernameCopy := username+ if _, createErr := s.CreateEnvironment(ctx, createdEnv, &userIDCopy, &usernameCopy); createErr != nil {+ return nil, "", fmt.Errorf("failed to create swarm node agent environment: %w", createErr)+ }+ env = *createdEnv+ } else {+ updates := map[string]any{}+ expectedName := buildSwarmNodeAgentNameInternal(hostname, nodeID)+ if env.Name != expectedName {+ updates["name"] = expectedName+ }+ if !env.Hidden {+ updates["hidden"] = true+ }+ if !env.IsEdge {+ updates["is_edge"] = true+ }+ if !env.Enabled {+ updates["enabled"] = true+ }+ if env.ParentEnvironmentID == nil || *env.ParentEnvironmentID != parentEnvironmentID {+ updates["parent_environment_id"] = parentEnvironmentID+ }+ if env.SwarmNodeID == nil || *env.SwarmNodeID != nodeID {+ updates["swarm_node_id"] = nodeID+ }+ if len(updates) > 0 {+ userIDCopy := userID+ usernameCopy := username+ updatedEnv, updateErr := s.UpdateEnvironment(ctx, env.ID, updates, &userIDCopy, &usernameCopy)+ if updateErr != nil {+ return nil, "", fmt.Errorf("failed to update swarm node agent environment: %w", updateErr)+ }+ env = *updatedEnv+ }+ }++ apiKey, err := s.applySwarmNodeAgentApiKeyInternal(ctx, &env, userID, username, rotate)+ if err != nil {+ return nil, "", err+ }++ refreshedEnv, err := s.GetEnvironmentByID(ctx, env.ID)+ if err != nil {+ return nil, "", fmt.Errorf("failed to refresh swarm node agent environment: %w", err)+ }++ return refreshedEnv, apiKey, nil+}++func (s *EnvironmentService) UpdateSwarmNodeIdentity(ctx context.Context, envID, swarmNodeID string) error {+ now := time.Now()+ updates := map[string]any{+ "swarm_node_id": swarmNodeID,+ "updated_at": &now,+ }++ if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", envID).Updates(updates).Error; err != nil {+ return fmt.Errorf("failed to update swarm node identity: %w", err)+ }++ return nil+}+func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string) (*models.Environment, error) {var environment models.Environmentif err := s.db.WithContext(ctx).Where("id = ?", id).First(&environment).Error; err != nil {@@ -255,7 +420,7 @@ func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string)func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, params pagination.QueryParams) ([]environment.Environment, pagination.Response, error) {var envs []models.Environment- q := s.db.WithContext(ctx).Model(&models.Environment{})+ q := s.db.WithContext(ctx).Model(&models.Environment{}).Where("hidden = ?", false)if term := strings.TrimSpace(params.Search); term != "" {searchPattern := "%" + term + "%"@@ -288,6 +453,7 @@ func (s *EnvironmentService) ListRemoteEnvironments(ctx context.Context) ([]modeModel(&models.Environment{}).Where("id != ?", "0").Where("enabled = ?", true).+ Where("hidden = ?", false).Find(&envs).Errorif err != nil {return nil, fmt.Errorf("failed to list remote environments: %w", err)diff --git a/backend/internal/services/environment_service_test.go b/backend/internal/services/environment_service_test.goindex 6e6e3b498..ce4a5aba8 100644--- a/backend/internal/services/environment_service_test.go+++ b/backend/internal/services/environment_service_test.go@@ -3,6 +3,7 @@ package servicesimport ("context""encoding/json"+ "fmt""net/http""net/http/httptest""strings"@@ -18,15 +19,28 @@ import ("github.com/getarcaneapp/arcane/backend/internal/database""github.com/getarcaneapp/arcane/backend/internal/models""github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto"+ "github.com/getarcaneapp/arcane/backend/pkg/pagination""github.com/getarcaneapp/arcane/types/containerregistry")func setupEnvironmentServiceTestDB(t *testing.T) *database.DB {t.Helper()- db, err := gorm.Open(glsqlite.Open(":memory:"), &gorm.Config{})+ dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", strings.NewReplacer("/", "_", " ", "_").Replace(t.Name()))+ db, err := gorm.Open(glsqlite.Open(dsn), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.Environment{}, &models.ContainerRegistry{}, &models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(+ &models.Environment{},+ &models.ContainerRegistry{},+ &models.SettingVariable{},+ &models.User{},+ &models.ApiKey{},+ ))++ sqlDB, err := db.DB()+ require.NoError(t, err)+ sqlDB.SetMaxOpenConns(1)+ sqlDB.SetMaxIdleConns(1)testCfg := &config.Config{EncryptionKey: "test-encryption-key-for-testing-32bytes-min",@@ -41,6 +55,20 @@ func setupEnvironmentServiceTestDB(t *testing.T) *database.DB {return &database.DB{DB: db}}+func createTestEnvironmentServiceUser(t *testing.T, ctx context.Context, userService *UserService, id string) *models.User {+ t.Helper()++ user := &models.User{+ BaseModel: models.BaseModel{ID: id},+ Username: fmt.Sprintf("user-%s", id),+ Roles: models.StringSlice{"admin"},+ }++ created, err := userService.CreateUser(ctx, user)+ require.NoError(t, err)+ return created+}+func createTestEnvironment(t *testing.T, db *database.DB, id string, apiURL string, accessToken *string) {t.Helper()createNamedTestEnvironmentInternal(t, db, id, "env-"+id, apiURL, accessToken)@@ -142,7 +170,7 @@ func createTestECRRegistry(t *testing.T, db *database.DB, id string) {func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SyncsEligibleRemotes(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)- svc := NewEnvironmentService(db, nil, nil, nil, nil)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)createTestRegistry(t, db, "reg-1")@@ -195,7 +223,7 @@ func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SyncsEligibleRemofunc TestEnvironmentService_SyncRegistriesToEnvironment_IncludesECRFields(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)- svc := NewEnvironmentService(db, nil, nil, nil, nil)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)createTestECRRegistry(t, db, "reg-ecr")@@ -231,7 +259,7 @@ func TestEnvironmentService_SyncRegistriesToEnvironment_IncludesECRFields(t *tesfunc TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SkipsRemoteWithoutAccessToken(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)- svc := NewEnvironmentService(db, nil, nil, nil, nil)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)createTestRegistry(t, db, "reg-1")@@ -255,7 +283,7 @@ func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SkipsRemoteWithoufunc TestEnvironmentService_SyncRegistriesToRemoteEnvironments_ReportsFailuresButContinues(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)- svc := NewEnvironmentService(db, nil, nil, nil, nil)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)createTestRegistry(t, db, "reg-1")@@ -281,7 +309,7 @@ func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_ReportsFailuresBufunc TestEnvironmentService_ReconcileEdgeStatusesOnStartup(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)- svc := NewEnvironmentService(db, nil, nil, nil, nil)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)createTestEnvironmentWithState(t, db, "edge-online", "edge://online", string(models.EnvironmentStatusOnline), true, nil)createTestEnvironmentWithState(t, db, "edge-error", "edge://error", string(models.EnvironmentStatusError), true, nil)@@ -311,7 +339,7 @@ func TestEnvironmentService_ReconcileEdgeStatusesOnStartup(t *testing.T) {func TestEnvironmentService_UpdateEnvironmentConnectionState(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)- svc := NewEnvironmentService(db, nil, nil, nil, nil)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)createTestEnvironmentWithState(t, db, "edge-runtime", "edge://runtime", string(models.EnvironmentStatusOffline), true, nil)@@ -337,7 +365,7 @@ func TestEnvironmentService_UpdateEnvironmentConnectionState(t *testing.T) {func TestEnvironmentService_ResolveEdgeEnvironmentByToken_CachesAndInvalidatesOnUpdate(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)- svc := NewEnvironmentService(db, nil, nil, nil, nil)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)oldToken := "edge-token-old"newToken := "edge-token-new"@@ -367,7 +395,7 @@ func TestEnvironmentService_ResolveEdgeEnvironmentByToken_CachesAndInvalidatesOnfunc TestEnvironmentService_UpdateEnvironment_ClearingAccessTokenInvalidatesCache(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)- svc := NewEnvironmentService(db, nil, nil, nil, nil)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)oldToken := "edge-token-clear"createTestEnvironmentWithState(t, db, "edge-auth-clear", "edge://auth-clear", string(models.EnvironmentStatusPending), true, &oldToken)@@ -397,7 +425,7 @@ func TestEnvironmentService_UpdateEnvironment_ClearingAccessTokenInvalidatesCach}func TestEnvironmentService_getCachedEnvironmentIDForTokenInternal_ExpiresAndCleansReverseIndex(t *testing.T) {- svc := NewEnvironmentService(nil, nil, nil, nil, nil)+ svc := NewEnvironmentService(nil, nil, nil, nil, nil, nil)now := time.Now()svc.cacheEnvironmentTokenInternal("env-expired", "expired-token", now.Add(-2*edgeTokenCacheTTL))@@ -418,7 +446,7 @@ func TestEnvironmentService_getCachedEnvironmentIDForTokenInternal_ExpiresAndClefunc TestEnvironmentService_ResolveEnvironmentByAccessToken(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)- svc := NewEnvironmentService(db, nil, nil, nil, nil)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)accessToken := "remote-token"createNamedTestEnvironmentInternal(t, db, "env-remote", "Remote Alpha", "http://remote.example", &accessToken)@@ -435,7 +463,7 @@ func TestEnvironmentService_ResolveEnvironmentByAccessToken(t *testing.T) {}func TestEnvironmentService_GenerateDeploymentSnippets_ExplicitlyUsePollTransport(t *testing.T) {- svc := NewEnvironmentService(nil, nil, nil, nil, nil)+ svc := NewEnvironmentService(nil, nil, nil, nil, nil, nil)standard, err := svc.GenerateDeploymentSnippets(context.Background(), "env-1", "https://manager.example.com", "token-123")require.NoError(t, err)@@ -461,3 +489,113 @@ func TestEnvironmentService_GenerateDeploymentSnippets_ExplicitlyUsePollTransporrequire.Contains(t, edgeSnippets.DockerCompose, "- arcane-data:/app/data")require.NotContains(t, edgeSnippets.DockerRun, "-v arcane-data:/data")}++func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesHiddenChildAndReusesToken(t *testing.T) {+ ctx := context.Background()+ db := setupEnvironmentServiceTestDB(t)+ userService := NewUserService(db)+ apiKeyService := NewApiKeyService(db, userService)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, apiKeyService)+ user := createTestEnvironmentServiceUser(t, ctx, userService, "swarm-admin")++ createdEnv, createdToken, err := svc.EnsureSwarmNodeAgentEnvironment(+ ctx,+ "manager-env",+ "node-1234567890abcdef",+ "worker-1",+ user.ID,+ user.Username,+ false,+ )+ require.NoError(t, err)+ require.NotNil(t, createdEnv)+ require.NotEmpty(t, createdToken)+ require.Equal(t, "Swarm Node Agent - worker-1", createdEnv.Name)+ require.Equal(t, "edge://swarm-node-node-1234567", createdEnv.ApiUrl)+ require.True(t, createdEnv.Hidden)+ require.True(t, createdEnv.IsEdge)+ require.True(t, createdEnv.Enabled)+ require.Equal(t, string(models.EnvironmentStatusPending), createdEnv.Status)+ require.NotNil(t, createdEnv.ParentEnvironmentID)+ require.Equal(t, "manager-env", *createdEnv.ParentEnvironmentID)+ require.NotNil(t, createdEnv.SwarmNodeID)+ require.Equal(t, "node-1234567890abcdef", *createdEnv.SwarmNodeID)+ require.NotNil(t, createdEnv.AccessToken)+ require.Equal(t, createdToken, *createdEnv.AccessToken)+ require.NotNil(t, createdEnv.ApiKeyID)++ var childEnvironments []models.Environment+ require.NoError(t, db.WithContext(ctx).+ Where("parent_environment_id = ?", "manager-env").+ Where("swarm_node_id = ?", "node-1234567890abcdef").+ Find(&childEnvironments).Error)+ require.Len(t, childEnvironments, 1)++ var apiKeys []models.ApiKey+ require.NoError(t, db.WithContext(ctx).+ Where("environment_id = ?", createdEnv.ID).+ Order("created_at asc").+ Find(&apiKeys).Error)+ require.Len(t, apiKeys, 1)+ require.Equal(t, user.ID, apiKeys[0].UserID)++ reusedEnv, reusedToken, err := svc.EnsureSwarmNodeAgentEnvironment(+ ctx,+ "manager-env",+ "node-1234567890abcdef",+ "worker-1",+ user.ID,+ user.Username,+ false,+ )+ require.NoError(t, err)+ require.NotNil(t, reusedEnv)+ require.Equal(t, createdEnv.ID, reusedEnv.ID)+ require.Equal(t, createdToken, reusedToken)+ require.Equal(t, createdEnv.ApiKeyID, reusedEnv.ApiKeyID)++ var apiKeysAfterReuse []models.ApiKey+ require.NoError(t, db.WithContext(ctx).+ Where("environment_id = ?", createdEnv.ID).+ Order("created_at asc").+ Find(&apiKeysAfterReuse).Error)+ require.Len(t, apiKeysAfterReuse, 1)+}++func TestEnvironmentService_ListMethods_ExcludeHiddenEnvironments(t *testing.T) {+ ctx := context.Background()+ db := setupEnvironmentServiceTestDB(t)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)++ createTestEnvironment(t, db, "0", "http://localhost:3552", nil)+ visibleToken := "visible-token"+ hiddenToken := "hidden-token"++ createNamedTestEnvironmentInternal(t, db, "env-visible", "Visible Remote", "http://visible.example", &visibleToken)+ createNamedTestEnvironmentInternal(t, db, "env-hidden", "Hidden Node Agent", "edge://swarm-node-hidden", &hiddenToken)++ require.NoError(t, db.WithContext(ctx).+ Model(&models.Environment{}).+ Where("id = ?", "env-hidden").+ Updates(map[string]any{+ "hidden": true,+ "is_edge": true,+ "parent_environment_id": "0",+ "swarm_node_id": "node-hidden",+ }).Error)++ listedEnvironments, _, err := svc.ListEnvironmentsPaginated(ctx, pagination.QueryParams{+ PaginationParams: pagination.PaginationParams{Start: 0, Limit: 20},+ Filters: map[string]string{},+ })+ require.NoError(t, err)+ require.Len(t, listedEnvironments, 2)+ for _, env := range listedEnvironments {+ require.NotEqual(t, "env-hidden", env.ID)+ }++ remoteEnvironments, err := svc.ListRemoteEnvironments(ctx)+ require.NoError(t, err)+ require.Len(t, remoteEnvironments, 1)+ require.Equal(t, "env-visible", remoteEnvironments[0].ID)+}diff --git a/backend/internal/services/gitops_sync_service.go b/backend/internal/services/gitops_sync_service.goindex 8252b0e44..2f3f03fa4 100644--- a/backend/internal/services/gitops_sync_service.go+++ b/backend/internal/services/gitops_sync_service.go@@ -981,7 +981,7 @@ func (s *GitOpsSyncService) writeSyncFilesToProject(ctx context.Context, sync *m// updateSyncStatusWithFiles updates sync status including the list of synced filesfunc (s *GitOpsSyncService) updateSyncStatusWithFiles(ctx context.Context, id, status, errorMsg, commitHash string, syncedFiles []string) {now := time.Now()- updates := map[string]interface{}{+ updates := map[string]any{"last_sync_at": now,"last_sync_status": status,"synced_files": marshalSyncedFiles(syncedFiles),diff --git a/backend/internal/services/log_stream_util.go b/backend/internal/services/log_stream_util.gonew file mode 100644index 000000000..64ada4488--- /dev/null+++ b/backend/internal/services/log_stream_util.go@@ -0,0 +1,112 @@+package services++import (+ "bufio"+ "context"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "strings"++ "github.com/moby/moby/api/pkg/stdcopy"+)++// streamMultiplexedLogs demultiplexes a Docker log stream (stdout/stderr)+// and sends lines to logsChan. Used by both container and swarm service logs.+func streamMultiplexedLogs(ctx context.Context, logs io.ReadCloser, logsChan chan<- string) error {+ stdoutReader, stdoutWriter := io.Pipe()+ stderrReader, stderrWriter := io.Pipe()++ go func() {+ defer func() { _ = stdoutWriter.Close() }()+ defer func() { _ = stderrWriter.Close() }()+ _, err := stdcopy.StdCopy(stdoutWriter, stderrWriter, logs)+ if err != nil && !errors.Is(err, io.EOF) {+ slog.Error("error demultiplexing logs", "error", err)+ }+ }()++ done := make(chan error, 2)++ go func() {+ done <- readLogsFromReader(ctx, stdoutReader, logsChan, "stdout")+ }()++ go func() {+ done <- readLogsFromReader(ctx, stderrReader, logsChan, "stderr")+ }()++ select {+ case <-ctx.Done():+ return ctx.Err()+ case err := <-done:+ if err != nil && !errors.Is(err, io.EOF) {+ return err+ }+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-done:+ return nil+ }+ }+}++// readLogsFromReader reads logs line by line from a reader and sends them to logsChan.+func readLogsFromReader(ctx context.Context, reader io.Reader, logsChan chan<- string, source string) error {+ scanner := bufio.NewScanner(reader)++ for scanner.Scan() {+ select {+ case <-ctx.Done():+ return ctx.Err()+ default:+ line := scanner.Text()+ if line != "" {+ if source == "stderr" {+ line = "[STDERR] " + line+ }++ select {+ case logsChan <- line:+ case <-ctx.Done():+ return ctx.Err()+ }+ }+ }+ }++ return scanner.Err()+}++// readAllLogs reads all logs at once (non-follow mode) and sends them to logsChan.+func readAllLogs(logs io.ReadCloser, logsChan chan<- string) error {+ stdoutBuf := &strings.Builder{}+ stderrBuf := &strings.Builder{}++ _, err := stdcopy.StdCopy(stdoutBuf, stderrBuf, logs)+ if err != nil && !errors.Is(err, io.EOF) {+ return fmt.Errorf("failed to demultiplex logs: %w", err)+ }++ if stdoutBuf.Len() > 0 {+ lines := strings.SplitSeq(strings.TrimRight(stdoutBuf.String(), "\n"), "\n")+ for line := range lines {+ if line != "" {+ logsChan <- line+ }+ }+ }++ if stderrBuf.Len() > 0 {+ lines := strings.SplitSeq(strings.TrimRight(stderrBuf.String(), "\n"), "\n")+ for line := range lines {+ if line != "" {+ logsChan <- "[STDERR] " + line+ }+ }+ }++ return nil+}diff --git a/backend/internal/services/notification_service_test.go b/backend/internal/services/notification_service_test.goindex 3d9e95752..3811fb61d 100644--- a/backend/internal/services/notification_service_test.go+++ b/backend/internal/services/notification_service_test.go@@ -51,7 +51,7 @@ func setupNotificationTestServiceInternal(t *testing.T) (*database.DB, *Environmt.Helper()db := setupNotificationTestDB(t)- envSvc := NewEnvironmentService(db, nil, nil, nil, nil)+ envSvc := NewEnvironmentService(db, nil, nil, nil, nil, nil)cfg := &config.Config{AppUrl: "http://localhost:3552",@@ -463,7 +463,7 @@ func TestNotificationService_DispatchNotification_LogsManagerDispatchForAgent(tfunc TestNotificationService_SendImageUpdateNotification_AgentModeDispatchesToManager(t *testing.T) {ctx := context.Background()db := setupNotificationTestDB(t)- envSvc := NewEnvironmentService(db, nil, nil, nil, nil)+ envSvc := NewEnvironmentService(db, nil, nil, nil, nil, nil)var calls atomic.Int32var dispatched notificationdto.DispatchRequest@@ -495,7 +495,7 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeDispatchesToMafunc TestNotificationService_SendImageUpdateNotification_AgentModeRequiresUpdateInfo(t *testing.T) {ctx := context.Background()db := setupNotificationTestDB(t)- envSvc := NewEnvironmentService(db, nil, nil, nil, nil)+ envSvc := NewEnvironmentService(db, nil, nil, nil, nil, nil)svc := NewNotificationService(db, &config.Config{AppUrl: "http://localhost:3552",@@ -510,7 +510,7 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeRequiresUpdatefunc TestNotificationService_SendBatchImageUpdateNotification_AgentModeSkipsNoOpDispatchInternal(t *testing.T) {ctx := context.Background()db := setupNotificationTestDB(t)- envSvc := NewEnvironmentService(db, nil, nil, nil, nil)+ envSvc := NewEnvironmentService(db, nil, nil, nil, nil, nil)var calls atomic.Int32server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.goindex a4728e355..452978f82 100644--- a/backend/internal/services/project_service.go+++ b/backend/internal/services/project_service.go@@ -10,6 +10,7 @@ import ("maps""os""path/filepath"+ "slices""strings""sync""time"@@ -747,16 +748,8 @@ func (s *ProjectService) collectDirectoryFiles(}func isBinaryProjectFileContent(content []byte) bool {- checkSize := len(content)- if checkSize > 512 {- checkSize = 512- }- for _, b := range content[:checkSize] {- if b == 0 {- return true- }- }- return false+ checkSize := min(len(content), 512)+ return slices.Contains(content[:checkSize], 0)}func (s *ProjectService) enrichWithGitOpsInfo(ctx context.Context, proj *models.Project, resp *project.Details) {diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.goindex ea1d1df20..994bb4e53 100644--- a/backend/internal/services/settings_service.go+++ b/backend/internal/services/settings_service.go@@ -92,6 +92,7 @@ func (s *SettingsService) getDefaultSettings() *models.Settings {return &models.Settings{ProjectsDirectory: models.SettingVariable{Value: "/app/data/projects"},FollowProjectSymlinks: models.SettingVariable{Value: "false"},+ SwarmStackSourcesDirectory: models.SettingVariable{Value: "/app/data/swarm/sources"},DiskUsagePath: models.SettingVariable{Value: "/app/data/projects"},AutoUpdate: models.SettingVariable{Value: "false"},AutoUpdateInterval: models.SettingVariable{Value: "0 0 0 * * *"},diff --git a/backend/internal/services/swarm_service.go b/backend/internal/services/swarm_service.gonew file mode 100644index 000000000..382e3395d--- /dev/null+++ b/backend/internal/services/swarm_service.go@@ -0,0 +1,2128 @@+package services++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "net/netip"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "syscall"+ "time"++ cerrdefs "github.com/containerd/errdefs"+ "github.com/getarcaneapp/arcane/backend/internal/common"+ "github.com/getarcaneapp/arcane/backend/internal/models"+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"+ libswarm "github.com/getarcaneapp/arcane/backend/pkg/libarcane/swarm"+ "github.com/getarcaneapp/arcane/backend/pkg/pagination"+ appfs "github.com/getarcaneapp/arcane/backend/pkg/projects"+ swarmtypes "github.com/getarcaneapp/arcane/types/swarm"+ networktypes "github.com/moby/moby/api/types/network"+ "github.com/moby/moby/api/types/swarm"+ "github.com/moby/moby/api/types/system"+ dockerclient "github.com/moby/moby/client"+ "golang.org/x/sync/errgroup"+)++var ErrSwarmNotEnabled = errors.New("swarm mode is not enabled")+var ErrSwarmManagerRequired = errors.New("swarm manager access required")++const swarmNodeIdentityProbeConcurrency = 5++// SwarmService provides Docker Swarm related operations.+type SwarmService struct {+ dockerService *DockerClientService+ settingsService *SettingsService+ registryService *ContainerRegistryService+ environmentService *EnvironmentService+}++func NewSwarmService(+ dockerService *DockerClientService,+ settingsService *SettingsService,+ registryService *ContainerRegistryService,+ environmentService *EnvironmentService,+) *SwarmService {+ return &SwarmService{+ dockerService: dockerService,+ settingsService: settingsService,+ registryService: registryService,+ environmentService: environmentService,+ }+}++type SwarmNodeIdentity struct {+ SwarmNodeID string `json:"swarmNodeId"`+ Hostname string `json:"hostname"`+ Role string `json:"role"`+ EngineVersion string `json:"engineVersion"`+ SwarmActive bool `json:"swarmActive"`+}++type swarmNodeAgentRuntime struct {+ connected bool+ lastHeartbeat *time.Time+ lastPollAt *time.Time+ identity *SwarmNodeIdentity+}++func (s *SwarmService) ListServicesPaginated(ctx context.Context, params pagination.QueryParams) ([]swarmtypes.ServiceSummary, pagination.Response, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, pagination.Response{}, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{Status: true})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)+ }+ services := servicesResult.Items++ // Fetch nodes to resolve node IDs to hostnames+ nodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)+ }+ nodes := nodesResult.Items+ nodeNameByID := make(map[string]string, len(nodes))+ for _, node := range nodes {+ nodeNameByID[node.ID] = node.Description.Hostname+ }++ // Fetch networks to resolve network IDs to names+ networksResult, err := dockerClient.NetworkList(ctx, dockerclient.NetworkListOptions{})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list networks: %w", err)+ }+ networks := networksResult.Items+ networkNameByID := make(map[string]string, len(networks))+ for _, n := range networks {+ networkNameByID[n.ID] = n.Name+ }++ // Fetch tasks and group running tasks by service ID+ tasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm tasks: %w", err)+ }+ tasks := tasksResult.Items+ serviceNodes := make(map[string]map[string]struct{})+ for _, task := range tasks {+ if string(task.Status.State) != "running" {+ continue+ }+ if _, ok := serviceNodes[task.ServiceID]; !ok {+ serviceNodes[task.ServiceID] = make(map[string]struct{})+ }+ if nodeName, ok := nodeNameByID[task.NodeID]; ok {+ serviceNodes[task.ServiceID][nodeName] = struct{}{}+ }+ }++ items := make([]swarmtypes.ServiceSummary, 0, len(services))+ for _, service := range services {+ var nodeNames []string+ if nodeSet, ok := serviceNodes[service.ID]; ok {+ nodeNames = make([]string, 0, len(nodeSet))+ for name := range nodeSet {+ nodeNames = append(nodeNames, name)+ }+ sort.Strings(nodeNames)+ }+ items = append(items, swarmtypes.NewServiceSummary(service, nodeNames, networkNameByID))+ }++ config := s.buildServicePaginationConfigInternal()+ result := pagination.SearchOrderAndPaginate(items, params, config)+ paginationResp := buildPaginationResponseInternal(result, params)++ return result.Items, paginationResp, nil+}++func (s *SwarmService) GetService(ctx context.Context, serviceID string) (*swarmtypes.ServiceInspect, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to inspect swarm service: %w", err)+ }+ service := serviceResult.Service++ inspect := swarmtypes.NewServiceInspect(service)+ inspect.Nodes = s.resolveServiceNodeNamesInternal(ctx, dockerClient, serviceID)+ inspect.NetworkDetails = s.enrichServiceNetworkDetailsInternal(ctx, dockerClient, service.Spec.TaskTemplate.Networks)+ inspect.Mounts = s.enrichServiceMountsInternal(ctx, dockerClient, service.Spec.TaskTemplate.ContainerSpec)++ return &inspect, nil+}++func (s *SwarmService) resolveServiceNodeNamesInternal(ctx context.Context, dockerClient *dockerclient.Client, serviceID string) []string {+ nodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})+ if err != nil {+ return nil+ }++ nodeNameByID := make(map[string]string, len(nodesResult.Items))+ for _, node := range nodesResult.Items {+ nodeNameByID[node.ID] = node.Description.Hostname+ }++ tasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{})+ if err != nil {+ return nil+ }++ nodeSet := make(map[string]struct{})+ for _, task := range tasksResult.Items {+ if task.ServiceID != serviceID || task.Status.State != swarm.TaskStateRunning {+ continue+ }+ if name, ok := nodeNameByID[task.NodeID]; ok {+ nodeSet[name] = struct{}{}+ }+ }++ nodeNames := make([]string, 0, len(nodeSet))+ for name := range nodeSet {+ nodeNames = append(nodeNames, name)+ }+ sort.Strings(nodeNames)+ return nodeNames+}++func (s *SwarmService) enrichServiceNetworkDetailsInternal(+ ctx context.Context,+ dockerClient *dockerclient.Client,+ networkConfigs []swarm.NetworkAttachmentConfig,+) map[string]swarmtypes.ServiceNetworkDetail {+ if len(networkConfigs) == 0 {+ return nil+ }++ details := make(map[string]swarmtypes.ServiceNetworkDetail, len(networkConfigs))+ for _, networkConfig := range networkConfigs {+ networkID := networkConfig.Target+ netInspectResult, err := dockerClient.NetworkInspect(ctx, networkID, dockerclient.NetworkInspectOptions{})+ if err != nil {+ continue+ }++ networkInfo := netInspectResult.Network+ detail := swarmtypes.ServiceNetworkDetail{+ ID: networkInfo.ID,+ Name: networkInfo.Name,+ Driver: networkInfo.Driver,+ Scope: networkInfo.Scope,+ Internal: networkInfo.Internal,+ Attachable: networkInfo.Attachable,+ Ingress: networkInfo.Ingress,+ EnableIPv4: networkInfo.EnableIPv4,+ EnableIPv6: networkInfo.EnableIPv6,+ ConfigOnly: networkInfo.ConfigOnly,+ Options: networkInfo.Options,+ }+ if networkInfo.ConfigFrom.Network != "" {+ detail.ConfigFrom = networkInfo.ConfigFrom.Network+ }++ for _, ipamCfg := range networkInfo.IPAM.Config {+ detail.IPAMConfigs = append(detail.IPAMConfigs, toServiceNetworkIPAMConfigInternal(ipamCfg))+ }++ if detail.ConfigFrom != "" {+ configInspectResult, err := dockerClient.NetworkInspect(ctx, detail.ConfigFrom, dockerclient.NetworkInspectOptions{})+ if err == nil {+ configNetwork := configInspectResult.Network+ configDetail := &swarmtypes.ServiceNetworkConfigDetail{+ Name: configNetwork.Name,+ Driver: configNetwork.Driver,+ Scope: configNetwork.Scope,+ EnableIPv4: configNetwork.EnableIPv4,+ EnableIPv6: configNetwork.EnableIPv6,+ Options: configNetwork.Options,+ }+ for _, ipamCfg := range configNetwork.IPAM.Config {+ converted := toServiceNetworkIPAMConfigInternal(ipamCfg)+ if ipamCfg.Subnet.IsValid() && ipamCfg.Subnet.Addr().Is6() {+ configDetail.IPv6Configs = append(configDetail.IPv6Configs, converted)+ continue+ }+ configDetail.IPv4Configs = append(configDetail.IPv4Configs, converted)+ }+ detail.ConfigNetwork = configDetail+ }+ }++ details[networkID] = detail+ }++ return details+}++func (s *SwarmService) enrichServiceMountsInternal(+ ctx context.Context,+ dockerClient *dockerclient.Client,+ containerSpec *swarm.ContainerSpec,+) []swarmtypes.ServiceMount {+ if containerSpec == nil {+ return nil+ }++ mounts := make([]swarmtypes.ServiceMount, 0, len(containerSpec.Mounts))+ for _, serviceMount := range containerSpec.Mounts {+ mount := swarmtypes.ServiceMount{+ Type: string(serviceMount.Type),+ Source: serviceMount.Source,+ Target: serviceMount.Target,+ ReadOnly: serviceMount.ReadOnly,+ }+ if serviceMount.Type == "volume" && serviceMount.Source != "" {+ volInspectResult, err := dockerClient.VolumeInspect(ctx, serviceMount.Source, dockerclient.VolumeInspectOptions{})+ if err == nil {+ volume := volInspectResult.Volume+ mount.VolumeDriver = volume.Driver+ mount.VolumeOptions = volume.Options+ mount.DevicePath = volume.Mountpoint+ }+ }+ mounts = append(mounts, mount)+ }++ return mounts+}++func (s *SwarmService) CreateService(ctx context.Context, req swarmtypes.ServiceCreateRequest) (*swarmtypes.ServiceCreateResponse, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ // Unmarshal spec from JSON+ var spec swarm.ServiceSpec+ if err := json.Unmarshal(req.Spec, &spec); err != nil {+ return nil, fmt.Errorf("failed to parse service spec: %w", err)+ }++ optionsPayload := swarmtypes.ServiceCreateOptions{}+ if req.Options != nil {+ optionsPayload = *req.Options+ }++ resp, err := dockerClient.ServiceCreate(ctx, dockerclient.ServiceCreateOptions{+ Spec: spec,+ EncodedRegistryAuth: optionsPayload.EncodedRegistryAuth,+ QueryRegistry: optionsPayload.QueryRegistry,+ })+ if err != nil {+ return nil, fmt.Errorf("failed to create swarm service: %w", err)+ }++ return &swarmtypes.ServiceCreateResponse{+ ID: resp.ID,+ Warnings: resp.Warnings,+ }, nil+}++func (s *SwarmService) UpdateService(ctx context.Context, serviceID string, req swarmtypes.ServiceUpdateRequest) (*swarmtypes.ServiceUpdateResponse, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ versionIndex := req.Version+ if versionIndex == 0 {+ serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to inspect swarm service: %w", err)+ }+ versionIndex = serviceResult.Service.Version.Index+ }++ optionsPayload := swarmtypes.ServiceUpdateOptions{}+ if req.Options != nil {+ optionsPayload = *req.Options+ }++ resp, err := dockerClient.ServiceUpdate(ctx, serviceID, dockerclient.ServiceUpdateOptions{+ Version: swarm.Version{Index: versionIndex},+ Spec: req.Spec,+ EncodedRegistryAuth: optionsPayload.EncodedRegistryAuth,+ RegistryAuthFrom: optionsPayload.RegistryAuthFrom,+ Rollback: optionsPayload.Rollback,+ QueryRegistry: optionsPayload.QueryRegistry,+ })+ if err != nil {+ return nil, fmt.Errorf("failed to update swarm service: %w", err)+ }++ return &swarmtypes.ServiceUpdateResponse{+ Warnings: resp.Warnings,+ }, nil+}++func (s *SwarmService) RemoveService(ctx context.Context, serviceID string) error {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ if _, err := dockerClient.ServiceRemove(ctx, serviceID, dockerclient.ServiceRemoveOptions{}); err != nil {+ return fmt.Errorf("failed to remove swarm service: %w", err)+ }++ return nil+}++func (s *SwarmService) StreamServiceLogs(ctx context.Context, serviceID string, logsChan chan<- string, follow bool, tail, since string, timestamps bool) error {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ options := dockerclient.ServiceLogsOptions{+ ShowStdout: true,+ ShowStderr: true,+ Follow: follow,+ Tail: tail,+ Since: since,+ Timestamps: timestamps,+ Details: true,+ }++ logs, err := dockerClient.ServiceLogs(ctx, serviceID, options)+ if err != nil {+ return fmt.Errorf("failed to get service logs: %w", err)+ }+ defer func() { _ = logs.Close() }()++ if follow {+ return streamMultiplexedLogs(ctx, logs, logsChan)+ }++ return readAllLogs(logs, logsChan)+}++func (s *SwarmService) ListNodesPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]swarmtypes.NodeSummary, pagination.Response, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, pagination.Response{}, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ nodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)+ }+ nodes := nodesResult.Items++ items := make([]swarmtypes.NodeSummary, 0, len(nodes))+ for _, node := range nodes {+ items = append(items, swarmtypes.NewNodeSummary(node))+ }++ s.enrichNodeAgentStatusesInternal(ctx, environmentID, items)++ config := s.buildNodePaginationConfigInternal()+ result := pagination.SearchOrderAndPaginate(items, params, config)+ paginationResp := buildPaginationResponseInternal(result, params)++ return result.Items, paginationResp, nil+}++func (s *SwarmService) GetNode(ctx context.Context, environmentID, nodeID string) (*swarmtypes.NodeSummary, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ nodeResult, err := dockerClient.NodeInspect(ctx, nodeID, dockerclient.NodeInspectOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to inspect swarm node: %w", err)+ }++ items := []swarmtypes.NodeSummary{swarmtypes.NewNodeSummary(nodeResult.Node)}+ s.enrichNodeAgentStatusesInternal(ctx, environmentID, items)+ out := items[0]+ return &out, nil+}++func (s *SwarmService) GetLocalNodeIdentity(ctx context.Context) (*SwarmNodeIdentity, error) {+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ infoResult, err := dockerClient.Info(ctx, dockerclient.InfoOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to inspect local Docker engine: %w", err)+ }++ swarmInfo := infoResult.Info+ swarmActive := swarmInfo.Swarm.LocalNodeState == swarm.LocalNodeStateActive && strings.TrimSpace(swarmInfo.Swarm.NodeID) != ""+ role := ""+ if swarmActive {+ if swarmInfo.Swarm.ControlAvailable {+ role = "manager"+ } else {+ role = "worker"+ }+ }++ return &SwarmNodeIdentity{+ SwarmNodeID: strings.TrimSpace(swarmInfo.Swarm.NodeID),+ Hostname: strings.TrimSpace(swarmInfo.Name),+ Role: role,+ EngineVersion: strings.TrimSpace(swarmInfo.ServerVersion),+ SwarmActive: swarmActive,+ }, nil+}++func (s *SwarmService) enrichNodeAgentStatusesInternal(ctx context.Context, environmentID string, items []swarmtypes.NodeSummary) {+ if s.environmentService == nil || len(items) == 0 || strings.TrimSpace(environmentID) == "" {+ return+ }++ agentEnvs, err := s.environmentService.ListSwarmNodeAgentEnvironments(ctx, environmentID)+ if err != nil {+ slog.WarnContext(ctx, "failed to load swarm node agent environments", "environmentID", environmentID, "error", err.Error())+ return+ }++ runtimeByEnvID := make(map[string]swarmNodeAgentRuntime, len(agentEnvs))+ envByNodeID := make(map[string]models.Environment, len(agentEnvs))+ var runtimeMu sync.Mutex+ g, groupCtx := errgroup.WithContext(ctx)+ g.SetLimit(swarmNodeIdentityProbeConcurrency)+ for i := range agentEnvs {+ env := agentEnvs[i]+ g.Go(func() error {+ runtime := s.resolveSwarmNodeAgentRuntimeInternal(groupCtx, &env)+ runtimeMu.Lock()+ runtimeByEnvID[env.ID] = runtime+ runtimeMu.Unlock()+ return nil+ })+ }+ if err := g.Wait(); err != nil {+ slog.WarnContext(ctx, "failed to resolve swarm node agent runtimes", "environmentID", environmentID, "error", err.Error())+ return+ }++ for i := range agentEnvs {+ env := agentEnvs[i]+ runtime := runtimeByEnvID[env.ID]+ if env.SwarmNodeID == nil || strings.TrimSpace(*env.SwarmNodeID) == "" {+ if runtime.connected && runtime.identity != nil && strings.TrimSpace(runtime.identity.SwarmNodeID) != "" {+ resolvedNodeID := strings.TrimSpace(runtime.identity.SwarmNodeID)+ if err := s.environmentService.UpdateSwarmNodeIdentity(ctx, env.ID, resolvedNodeID); err != nil {+ slog.WarnContext(ctx, "failed to persist swarm node identity", "environmentID", env.ID, "swarmNodeID", resolvedNodeID, "error", err.Error())+ } else {+ env.SwarmNodeID = &resolvedNodeID+ agentEnvs[i].SwarmNodeID = &resolvedNodeID+ }+ }+ }++ if env.SwarmNodeID != nil && strings.TrimSpace(*env.SwarmNodeID) != "" {+ envByNodeID[strings.TrimSpace(*env.SwarmNodeID)] = env+ }+ }++ for i := range items {+ nodeID := strings.TrimSpace(items[i].ID)+ env, ok := envByNodeID[nodeID]+ if !ok {+ items[i].Agent = swarmtypes.NodeAgentStatus{State: swarmtypes.NodeAgentStateNone}+ continue+ }++ runtime := runtimeByEnvID[env.ID]+ items[i].Agent = s.buildNodeAgentStatusInternal(nodeID, &env, runtime)+ }+}++func (s *SwarmService) resolveSwarmNodeAgentRuntimeInternal(ctx context.Context, env *models.Environment) swarmNodeAgentRuntime {+ if env == nil {+ return swarmNodeAgentRuntime{}+ }++ runtime := swarmNodeAgentRuntime{+ connected: edge.HasActiveTunnel(env.ID),+ }++ if tunnelState, ok := edge.GetTunnelRuntimeState(env.ID); ok {+ runtime.lastHeartbeat = tunnelState.LastHeartbeat+ }++ if pollState, ok := edge.GetPollRuntimeRegistry().Get(env.ID, time.Now()); ok {+ runtime.lastPollAt = pollState.LastPollAt+ }++ if !runtime.connected {+ return runtime+ }++ identity, err := s.fetchSwarmNodeIdentityViaEdgeInternal(ctx, env.ID)+ if err != nil {+ slog.DebugContext(ctx, "failed to probe swarm node identity", "environmentID", env.ID, "error", err.Error())+ return runtime+ }++ runtime.identity = identity+ return runtime+}++func (s *SwarmService) fetchSwarmNodeIdentityViaEdgeInternal(ctx context.Context, environmentID string) (*SwarmNodeIdentity, error) {+ reqCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()++ body, statusCode, err := s.environmentService.ProxyRequest(reqCtx, environmentID, http.MethodGet, "/api/swarm/node-identity", nil)+ if err != nil {+ return nil, err+ }+ if statusCode != http.StatusOK {+ return nil, fmt.Errorf("unexpected status code: %d", statusCode)+ }++ var parsed struct {+ Success bool `json:"success"`+ Data SwarmNodeIdentity `json:"data"`+ }+ if err := json.Unmarshal(body, &parsed); err != nil {+ return nil, fmt.Errorf("failed to decode swarm node identity response: %w", err)+ }+ if !parsed.Success {+ return nil, fmt.Errorf("swarm node identity probe failed")+ }++ return &parsed.Data, nil+}++func (s *SwarmService) buildNodeAgentStatusInternal(nodeID string, env *models.Environment, runtime swarmNodeAgentRuntime) swarmtypes.NodeAgentStatus {+ if env == nil {+ return swarmtypes.NodeAgentStatus{State: swarmtypes.NodeAgentStateNone}+ }++ status := swarmtypes.NodeAgentStatus{+ State: swarmtypes.NodeAgentStateOffline,+ EnvironmentID: &env.ID,+ Connected: &runtime.connected,+ LastHeartbeat: runtime.lastHeartbeat,+ LastPollAt: runtime.lastPollAt,+ }++ if runtime.identity != nil {+ if reportedNodeID := strings.TrimSpace(runtime.identity.SwarmNodeID); reportedNodeID != "" {+ status.ReportedNodeID = &reportedNodeID+ }+ if reportedHostname := strings.TrimSpace(runtime.identity.Hostname); reportedHostname != "" {+ status.ReportedHostname = &reportedHostname+ }+ }++ if runtime.connected && runtime.identity != nil {+ if !runtime.identity.SwarmActive || strings.TrimSpace(runtime.identity.SwarmNodeID) != strings.TrimSpace(nodeID) {+ status.State = swarmtypes.NodeAgentStateMismatched+ return status+ }+ status.State = swarmtypes.NodeAgentStateConnected+ return status+ }++ if env.Status == string(models.EnvironmentStatusPending) || (env.LastSeen == nil && runtime.lastHeartbeat == nil && runtime.lastPollAt == nil) {+ status.State = swarmtypes.NodeAgentStatePending+ return status+ }++ status.State = swarmtypes.NodeAgentStateOffline+ return status+}++func (s *SwarmService) ListTasksPaginated(ctx context.Context, params pagination.QueryParams) ([]swarmtypes.TaskSummary, pagination.Response, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, pagination.Response{}, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)+ }+ services := servicesResult.Items++ serviceNameByID := make(map[string]string, len(services))+ for _, service := range services {+ serviceNameByID[service.ID] = service.Spec.Name+ }++ nodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)+ }+ nodes := nodesResult.Items++ nodeNameByID := make(map[string]string, len(nodes))+ for _, node := range nodes {+ nodeNameByID[node.ID] = node.Description.Hostname+ }++ tasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm tasks: %w", err)+ }+ tasks := tasksResult.Items++ items := make([]swarmtypes.TaskSummary, 0, len(tasks))+ for _, task := range tasks {+ items = append(items, swarmtypes.NewTaskSummary(task, serviceNameByID[task.ServiceID], nodeNameByID[task.NodeID]))+ }++ config := s.buildTaskPaginationConfigInternal()+ result := pagination.SearchOrderAndPaginate(items, params, config)+ paginationResp := buildPaginationResponseInternal(result, params)++ return result.Items, paginationResp, nil+}++func (s *SwarmService) ListStacksPaginated(ctx context.Context, params pagination.QueryParams) ([]swarmtypes.StackSummary, pagination.Response, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, pagination.Response{}, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)+ }+ services := servicesResult.Items++ stacks := make(map[string]*swarmtypes.StackSummary)+ for _, service := range services {+ stackName := service.Spec.Labels[swarmtypes.StackNamespaceLabel]+ if stackName == "" {+ continue+ }++ entry, exists := stacks[stackName]+ if !exists {+ stacks[stackName] = &swarmtypes.StackSummary{+ ID: stackName,+ Name: stackName,+ Namespace: stackName,+ Services: 1,+ CreatedAt: service.CreatedAt,+ UpdatedAt: service.UpdatedAt,+ }+ continue+ }++ entry.Services+++ if service.CreatedAt.Before(entry.CreatedAt) {+ entry.CreatedAt = service.CreatedAt+ }+ if service.UpdatedAt.After(entry.UpdatedAt) {+ entry.UpdatedAt = service.UpdatedAt+ }+ }++ items := make([]swarmtypes.StackSummary, 0, len(stacks))+ for _, stack := range stacks {+ items = append(items, *stack)+ }++ config := s.buildStackPaginationConfigInternal()+ result := pagination.SearchOrderAndPaginate(items, params, config)+ paginationResp := buildPaginationResponseInternal(result, params)++ return result.Items, paginationResp, nil+}++func (s *SwarmService) DeployStack(ctx context.Context, environmentID string, req swarmtypes.StackDeployRequest) (*swarmtypes.StackDeployResponse, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ stackName := strings.TrimSpace(req.Name)+ if stackName == "" {+ return nil, errors.New("stack name is required")+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ if err := libswarm.DeployStack(ctx, dockerClient, libswarm.StackDeployOptions{+ Name: stackName,+ ComposeContent: req.ComposeContent,+ EnvContent: req.EnvContent,+ WithRegistryAuth: req.WithRegistryAuth,+ RegistryAuthForImage: func(ctx context.Context, imageRef string) (string, error) {+ if s.registryService == nil {+ return "", nil+ }+ return s.registryService.GetRegistryAuthForImage(ctx, imageRef)+ },+ Prune: req.Prune,+ ResolveImage: req.ResolveImage,+ }); err != nil {+ return nil, err+ }++ if err := s.upsertStackSourceInternal(ctx, environmentID, stackName, req.ComposeContent, req.EnvContent); err != nil {+ slog.WarnContext(ctx, "failed to persist swarm stack source", "environmentID", normalizeSwarmEnvironmentIDInternal(environmentID), "stackName", stackName, "error", err)+ }++ return &swarmtypes.StackDeployResponse{Name: stackName}, nil+}++func (s *SwarmService) GetSwarmInfo(ctx context.Context) (*swarmtypes.SwarmInfo, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to inspect swarm: %w", err)+ }++ out := swarmtypes.NewSwarmInfo(infoResult.Swarm)+ return &out, nil+}++func (s *SwarmService) InitSwarm(ctx context.Context, req swarmtypes.SwarmInitRequest) (*swarmtypes.SwarmInitResponse, error) {+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ defaultAddrPool := make([]netip.Prefix, 0, len(req.DefaultAddrPool))+ for _, raw := range req.DefaultAddrPool {+ prefix, err := netip.ParsePrefix(raw)+ if err != nil {+ return nil, fmt.Errorf("failed to parse default address pool %q: %w", raw, err)+ }+ defaultAddrPool = append(defaultAddrPool, prefix.Masked())+ }++ initResult, err := dockerClient.SwarmInit(ctx, dockerclient.SwarmInitOptions{+ ListenAddr: req.ListenAddr,+ AdvertiseAddr: req.AdvertiseAddr,+ DataPathAddr: req.DataPathAddr,+ DataPathPort: req.DataPathPort,+ ForceNewCluster: req.ForceNewCluster,+ Spec: req.Spec,+ AutoLockManagers: req.AutoLockManagers,+ Availability: req.Availability,+ DefaultAddrPool: defaultAddrPool,+ SubnetSize: req.SubnetSize,+ })+ if err != nil {+ return nil, fmt.Errorf("failed to initialize swarm: %w", err)+ }++ return &swarmtypes.SwarmInitResponse{NodeID: initResult.NodeID}, nil+}++func (s *SwarmService) JoinSwarm(ctx context.Context, req swarmtypes.SwarmJoinRequest) error {+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ if _, err := dockerClient.SwarmJoin(ctx, dockerclient.SwarmJoinOptions{+ ListenAddr: req.ListenAddr,+ AdvertiseAddr: req.AdvertiseAddr,+ DataPathAddr: req.DataPathAddr,+ RemoteAddrs: req.RemoteAddrs,+ JoinToken: req.JoinToken,+ Availability: req.Availability,+ }); err != nil {+ return fmt.Errorf("failed to join swarm: %w", err)+ }++ return nil+}++func (s *SwarmService) LeaveSwarm(ctx context.Context, req swarmtypes.SwarmLeaveRequest) error {+ if err := s.ensureSwarmActiveInternal(ctx); err != nil {+ return err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ if _, err := dockerClient.SwarmLeave(ctx, dockerclient.SwarmLeaveOptions{Force: req.Force}); err != nil {+ return fmt.Errorf("failed to leave swarm: %w", err)+ }++ return nil+}++func (s *SwarmService) UnlockSwarm(ctx context.Context, req swarmtypes.SwarmUnlockRequest) error {+ if err := s.ensureSwarmActiveInternal(ctx); err != nil {+ return err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ if _, err := dockerClient.SwarmUnlock(ctx, dockerclient.SwarmUnlockOptions{Key: req.Key}); err != nil {+ return fmt.Errorf("failed to unlock swarm: %w", err)+ }++ return nil+}++func (s *SwarmService) GetSwarmUnlockKey(ctx context.Context) (*swarmtypes.SwarmUnlockKeyResponse, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ unlockResult, err := dockerClient.SwarmGetUnlockKey(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to get swarm unlock key: %w", err)+ }++ return &swarmtypes.SwarmUnlockKeyResponse{UnlockKey: unlockResult.Key}, nil+}++func (s *SwarmService) GetSwarmJoinTokens(ctx context.Context) (*swarmtypes.SwarmJoinTokensResponse, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to inspect swarm: %w", err)+ }++ return &swarmtypes.SwarmJoinTokensResponse{+ Worker: infoResult.Swarm.JoinTokens.Worker,+ Manager: infoResult.Swarm.JoinTokens.Manager,+ }, nil+}++func (s *SwarmService) RotateSwarmJoinTokens(ctx context.Context, req swarmtypes.SwarmRotateJoinTokensRequest) error {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})+ if err != nil {+ return fmt.Errorf("failed to inspect swarm: %w", err)+ }++ rotateWorker := req.RotateWorkerToken+ rotateManager := req.RotateManagerToken+ if !rotateWorker && !rotateManager {+ rotateWorker = true+ rotateManager = true+ }++ if _, err := dockerClient.SwarmUpdate(ctx, dockerclient.SwarmUpdateOptions{+ Version: infoResult.Swarm.Version,+ Spec: infoResult.Swarm.Spec,+ RotateWorkerToken: rotateWorker,+ RotateManagerToken: rotateManager,+ }); err != nil {+ return fmt.Errorf("failed to rotate swarm join tokens: %w", err)+ }++ return nil+}++func (s *SwarmService) UpdateSwarmSpec(ctx context.Context, req swarmtypes.SwarmUpdateRequest) error {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ version := req.Version+ if version == 0 {+ infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})+ if err != nil {+ return fmt.Errorf("failed to inspect swarm: %w", err)+ }+ version = infoResult.Swarm.Version.Index+ }++ if _, err := dockerClient.SwarmUpdate(ctx, dockerclient.SwarmUpdateOptions{+ Version: swarm.Version{Index: version},+ Spec: req.Spec,+ RotateWorkerToken: req.RotateWorkerToken,+ RotateManagerToken: req.RotateManagerToken,+ RotateManagerUnlockKey: req.RotateManagerUnlockKey,+ }); err != nil {+ return fmt.Errorf("failed to update swarm spec: %w", err)+ }++ return nil+}++func (s *SwarmService) ListServiceTasksPaginated(ctx context.Context, serviceID string, params pagination.QueryParams) ([]swarmtypes.TaskSummary, pagination.Response, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, pagination.Response{}, err+ }++ filters := make(dockerclient.Filters)+ filters.Add("service", serviceID)+ return s.listTasksPaginatedWithFiltersInternal(ctx, filters, params)+}++func (s *SwarmService) RollbackService(ctx context.Context, serviceID string) (*swarmtypes.ServiceUpdateResponse, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to inspect swarm service: %w", err)+ }++ updateResult, err := dockerClient.ServiceUpdate(ctx, serviceID, dockerclient.ServiceUpdateOptions{+ Version: serviceResult.Service.Version,+ Spec: serviceResult.Service.Spec,+ Rollback: "previous",+ })+ if err != nil {+ return nil, fmt.Errorf("failed to rollback swarm service: %w", err)+ }++ return &swarmtypes.ServiceUpdateResponse{Warnings: updateResult.Warnings}, nil+}++func (s *SwarmService) ScaleService(ctx context.Context, serviceID string, replicas uint64) (*swarmtypes.ServiceUpdateResponse, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to inspect swarm service: %w", err)+ }+ service := serviceResult.Service++ if service.Spec.Mode.Global != nil {+ return nil, errors.New("cannot scale global service")+ }+ if service.Spec.Mode.Replicated == nil {+ service.Spec.Mode.Replicated = &swarm.ReplicatedService{}+ }+ service.Spec.Mode.Replicated.Replicas = &replicas++ updateResult, err := dockerClient.ServiceUpdate(ctx, serviceID, dockerclient.ServiceUpdateOptions{+ Version: service.Version,+ Spec: service.Spec,+ })+ if err != nil {+ return nil, fmt.Errorf("failed to scale swarm service: %w", err)+ }++ return &swarmtypes.ServiceUpdateResponse{Warnings: updateResult.Warnings}, nil+}++func (s *SwarmService) UpdateNode(ctx context.Context, nodeID string, req swarmtypes.NodeUpdateRequest) error {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ nodeResult, err := dockerClient.NodeInspect(ctx, nodeID, dockerclient.NodeInspectOptions{})+ if err != nil {+ return fmt.Errorf("failed to inspect swarm node: %w", err)+ }++ version := req.Version+ if version == 0 {+ version = nodeResult.Node.Version.Index+ }++ spec := nodeResult.Node.Spec+ if req.Name != nil {+ spec.Name = *req.Name+ }+ if req.Labels != nil {+ spec.Labels = req.Labels+ }+ if req.Role != nil {+ spec.Role = *req.Role+ }+ if req.Availability != nil {+ spec.Availability = *req.Availability+ }++ if _, err := dockerClient.NodeUpdate(ctx, nodeID, dockerclient.NodeUpdateOptions{+ Version: swarm.Version{Index: version},+ Spec: spec,+ }); err != nil {+ return fmt.Errorf("failed to update swarm node: %w", err)+ }++ return nil+}++func (s *SwarmService) RemoveNode(ctx context.Context, nodeID string, force bool) error {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ if _, err := dockerClient.NodeRemove(ctx, nodeID, dockerclient.NodeRemoveOptions{Force: force}); err != nil {+ return fmt.Errorf("failed to remove swarm node: %w", err)+ }++ return nil+}++func (s *SwarmService) PromoteNode(ctx context.Context, nodeID string) error {+ role := swarm.NodeRoleManager+ return s.UpdateNode(ctx, nodeID, swarmtypes.NodeUpdateRequest{Role: &role})+}++func (s *SwarmService) DemoteNode(ctx context.Context, nodeID string) error {+ role := swarm.NodeRoleWorker+ return s.UpdateNode(ctx, nodeID, swarmtypes.NodeUpdateRequest{Role: &role})+}++func (s *SwarmService) ListNodeTasksPaginated(ctx context.Context, nodeID string, params pagination.QueryParams) ([]swarmtypes.TaskSummary, pagination.Response, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, pagination.Response{}, err+ }++ filters := make(dockerclient.Filters)+ filters.Add("node", nodeID)+ return s.listTasksPaginatedWithFiltersInternal(ctx, filters, params)+}++func (s *SwarmService) GetStack(ctx context.Context, environmentID, stackName string) (*swarmtypes.StackInspect, error) {+ _ = environmentID+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)+ if err != nil {+ return nil, err+ }+ if len(services) == 0 {+ return nil, cerrdefs.ErrNotFound+ }++ createdAt := services[0].CreatedAt+ updatedAt := services[0].UpdatedAt+ for _, service := range services[1:] {+ if service.CreatedAt.Before(createdAt) {+ createdAt = service.CreatedAt+ }+ if service.UpdatedAt.After(updatedAt) {+ updatedAt = service.UpdatedAt+ }+ }++ return &swarmtypes.StackInspect{+ Name: stackName,+ Namespace: stackName,+ Services: len(services),+ CreatedAt: createdAt,+ UpdatedAt: updatedAt,+ }, nil+}++func (s *SwarmService) GetStackSource(ctx context.Context, environmentID, stackName string) (*swarmtypes.StackSource, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ stackName = strings.TrimSpace(stackName)+ if stackName == "" {+ return nil, errors.New("stack name is required")+ }++ _, stackSourceDir, err := s.resolveSwarmStackSourceDirInternal(ctx, environmentID, stackName)+ if err != nil {+ return nil, err+ }++ composeContent, err := os.ReadFile(filepath.Join(stackSourceDir, swarmStackComposeFilename))+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return nil, cerrdefs.ErrNotFound+ }+ return nil, fmt.Errorf("failed to read swarm stack compose source: %w", err)+ }++ envContent := ""+ envBytes, err := os.ReadFile(filepath.Join(stackSourceDir, swarmStackEnvFilename))+ if err == nil {+ envContent = string(envBytes)+ } else if !errors.Is(err, os.ErrNotExist) {+ return nil, fmt.Errorf("failed to read swarm stack env source: %w", err)+ }++ return &swarmtypes.StackSource{+ Name: stackName,+ ComposeContent: string(composeContent),+ EnvContent: envContent,+ }, nil+}++func (s *SwarmService) RemoveStack(ctx context.Context, environmentID, stackName string) error {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return err+ }++ stackName = strings.TrimSpace(stackName)+ if stackName == "" {+ return errors.New("stack name is required")+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)+ if err != nil {+ return err+ }+ if len(services) == 0 {+ return cerrdefs.ErrNotFound+ }++ serviceIDs := make(map[string]struct{}, len(services))+ for _, service := range services {+ serviceIDs[service.ID] = struct{}{}+ if _, err := dockerClient.ServiceRemove(ctx, service.ID, dockerclient.ServiceRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {+ return fmt.Errorf("failed to remove swarm service %s: %w", service.Spec.Name, err)+ }+ }++ if err := s.waitForRemovedServiceTasksInternal(ctx, dockerClient, serviceIDs, 30*time.Second); err != nil {+ return err+ }++ stackLabel := fmt.Sprintf("%s=%s", swarmtypes.StackNamespaceLabel, stackName)++ configFilter := make(dockerclient.Filters).Add("label", stackLabel)+ configsResult, err := dockerClient.ConfigList(ctx, dockerclient.ConfigListOptions{Filters: configFilter})+ if err != nil {+ return fmt.Errorf("failed to list stack configs: %w", err)+ }+ for _, cfg := range configsResult.Items {+ if _, err := dockerClient.ConfigRemove(ctx, cfg.ID, dockerclient.ConfigRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {+ return fmt.Errorf("failed to remove stack config %s: %w", cfg.Spec.Name, err)+ }+ }++ secretFilter := make(dockerclient.Filters).Add("label", stackLabel)+ secretsResult, err := dockerClient.SecretList(ctx, dockerclient.SecretListOptions{Filters: secretFilter})+ if err != nil {+ return fmt.Errorf("failed to list stack secrets: %w", err)+ }+ for _, secret := range secretsResult.Items {+ if _, err := dockerClient.SecretRemove(ctx, secret.ID, dockerclient.SecretRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {+ return fmt.Errorf("failed to remove stack secret %s: %w", secret.Spec.Name, err)+ }+ }++ networkFilter := make(dockerclient.Filters).Add("label", stackLabel)+ networksResult, err := dockerClient.NetworkList(ctx, dockerclient.NetworkListOptions{Filters: networkFilter})+ if err != nil {+ return fmt.Errorf("failed to list stack networks: %w", err)+ }+ for _, network := range networksResult.Items {+ if network.Ingress {+ continue+ }+ if _, err := dockerClient.NetworkRemove(ctx, network.ID, dockerclient.NetworkRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {+ return fmt.Errorf("failed to remove stack network %s: %w", network.Name, err)+ }+ }++ if err := s.deleteStackSourceInternal(ctx, environmentID, stackName); err != nil {+ slog.WarnContext(ctx, "failed to remove persisted swarm stack source", "environmentID", normalizeSwarmEnvironmentIDInternal(environmentID), "stackName", stackName, "error", err)+ }++ return nil+}++func (s *SwarmService) ListStackServicesPaginated(ctx context.Context, stackName string, params pagination.QueryParams) ([]swarmtypes.ServiceSummary, pagination.Response, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, pagination.Response{}, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)+ if err != nil {+ return nil, pagination.Response{}, err+ }+ if len(services) == 0 {+ return nil, pagination.Response{}, cerrdefs.ErrNotFound+ }++ summaries, err := s.summarizeServicesInternal(ctx, dockerClient, services)+ if err != nil {+ return nil, pagination.Response{}, err+ }++ config := s.buildServicePaginationConfigInternal()+ result := pagination.SearchOrderAndPaginate(summaries, params, config)+ paginationResp := buildPaginationResponseInternal(result, params)+ return result.Items, paginationResp, nil+}++func (s *SwarmService) ListStackTasksPaginated(ctx context.Context, stackName string, params pagination.QueryParams) ([]swarmtypes.TaskSummary, pagination.Response, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, pagination.Response{}, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ services, err := s.listStackServicesRawInternal(ctx, dockerClient, stackName)+ if err != nil {+ return nil, pagination.Response{}, err+ }+ if len(services) == 0 {+ return nil, pagination.Response{}, cerrdefs.ErrNotFound+ }++ filters := make(dockerclient.Filters)+ for _, service := range services {+ filters.Add("service", service.ID)+ }++ return s.listTasksPaginatedWithFiltersInternal(ctx, filters, params)+}++func (s *SwarmService) RenderStackConfig(ctx context.Context, req swarmtypes.StackRenderConfigRequest) (*swarmtypes.StackRenderConfigResponse, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ result, err := libswarm.RenderStackConfig(ctx, libswarm.StackRenderOptions{+ Name: req.Name,+ ComposeContent: req.ComposeContent,+ EnvContent: req.EnvContent,+ })+ if err != nil {+ return nil, err+ }++ return &swarmtypes.StackRenderConfigResponse{+ Name: result.Name,+ RenderedCompose: result.RenderedCompose,+ Services: result.Services,+ Networks: result.Networks,+ Volumes: result.Volumes,+ Configs: result.Configs,+ Secrets: result.Secrets,+ }, nil+}++func (s *SwarmService) ListConfigs(ctx context.Context) ([]swarmtypes.ConfigSummary, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ configsResult, err := dockerClient.ConfigList(ctx, dockerclient.ConfigListOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to list swarm configs: %w", err)+ }++ items := make([]swarmtypes.ConfigSummary, 0, len(configsResult.Items))+ for _, cfg := range configsResult.Items {+ items = append(items, swarmtypes.NewConfigSummary(cfg))+ }+ return items, nil+}++func (s *SwarmService) GetConfig(ctx context.Context, configID string) (*swarmtypes.ConfigSummary, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ cfgResult, err := dockerClient.ConfigInspect(ctx, configID, dockerclient.ConfigInspectOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to inspect swarm config: %w", err)+ }++ item := swarmtypes.NewConfigSummary(cfgResult.Config)+ return &item, nil+}++func (s *SwarmService) CreateConfig(ctx context.Context, req swarmtypes.ConfigCreateRequest) (*swarmtypes.ConfigSummary, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ spec, err := decodeConfigSpecInternal(req.Spec)+ if err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ createResult, err := dockerClient.ConfigCreate(ctx, dockerclient.ConfigCreateOptions{Spec: spec})+ if err != nil {+ return nil, fmt.Errorf("failed to create swarm config: %w", err)+ }++ return s.GetConfig(ctx, createResult.ID)+}++func (s *SwarmService) UpdateConfig(ctx context.Context, configID string, req swarmtypes.ConfigUpdateRequest) (*swarmtypes.ConfigSummary, error) {+ _ = configID+ _ = req+ return nil, errors.New("swarm configs are immutable; create a new config and update services to use it")+}++func (s *SwarmService) RemoveConfig(ctx context.Context, configID string) error {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ if _, err := dockerClient.ConfigRemove(ctx, configID, dockerclient.ConfigRemoveOptions{}); err != nil {+ return fmt.Errorf("failed to remove swarm config: %w", err)+ }++ return nil+}++func (s *SwarmService) ListSecrets(ctx context.Context) ([]swarmtypes.SecretSummary, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ secretsResult, err := dockerClient.SecretList(ctx, dockerclient.SecretListOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to list swarm secrets: %w", err)+ }++ items := make([]swarmtypes.SecretSummary, 0, len(secretsResult.Items))+ for _, secret := range secretsResult.Items {+ items = append(items, swarmtypes.NewSecretSummary(secret))+ }+ return items, nil+}++func (s *SwarmService) GetSecret(ctx context.Context, secretID string) (*swarmtypes.SecretSummary, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ secretResult, err := dockerClient.SecretInspect(ctx, secretID, dockerclient.SecretInspectOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to inspect swarm secret: %w", err)+ }++ item := swarmtypes.NewSecretSummary(secretResult.Secret)+ return &item, nil+}++func (s *SwarmService) CreateSecret(ctx context.Context, req swarmtypes.SecretCreateRequest) (*swarmtypes.SecretSummary, error) {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return nil, err+ }++ spec, err := decodeSecretSpecInternal(req.Spec)+ if err != nil {+ return nil, err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ createResult, err := dockerClient.SecretCreate(ctx, dockerclient.SecretCreateOptions{Spec: spec})+ if err != nil {+ return nil, fmt.Errorf("failed to create swarm secret: %w", err)+ }++ return s.GetSecret(ctx, createResult.ID)+}++func (s *SwarmService) UpdateSecret(ctx context.Context, secretID string, req swarmtypes.SecretUpdateRequest) (*swarmtypes.SecretSummary, error) {+ _ = secretID+ _ = req+ return nil, errors.New("swarm secrets are immutable; create a new secret and update services to use it")+}++func (s *SwarmService) RemoveSecret(ctx context.Context, secretID string) error {+ if err := s.ensureSwarmManagerInternal(ctx); err != nil {+ return err+ }++ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }++ if _, err := dockerClient.SecretRemove(ctx, secretID, dockerclient.SecretRemoveOptions{}); err != nil {+ return fmt.Errorf("failed to remove swarm secret: %w", err)+ }++ return nil+}++func (s *SwarmService) listTasksPaginatedWithFiltersInternal(ctx context.Context, filters dockerclient.Filters, params pagination.QueryParams) ([]swarmtypes.TaskSummary, pagination.Response, error) {+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm services: %w", err)+ }++ serviceNameByID := make(map[string]string, len(servicesResult.Items))+ for _, service := range servicesResult.Items {+ serviceNameByID[service.ID] = service.Spec.Name+ }++ nodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm nodes: %w", err)+ }++ nodeNameByID := make(map[string]string, len(nodesResult.Items))+ for _, node := range nodesResult.Items {+ nodeNameByID[node.ID] = node.Description.Hostname+ }++ if filters == nil {+ filters = make(dockerclient.Filters)+ }+ tasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{Filters: filters})+ if err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list swarm tasks: %w", err)+ }++ items := make([]swarmtypes.TaskSummary, 0, len(tasksResult.Items))+ for _, task := range tasksResult.Items {+ items = append(items, swarmtypes.NewTaskSummary(task, serviceNameByID[task.ServiceID], nodeNameByID[task.NodeID]))+ }++ config := s.buildTaskPaginationConfigInternal()+ result := pagination.SearchOrderAndPaginate(items, params, config)+ paginationResp := buildPaginationResponseInternal(result, params)+ return result.Items, paginationResp, nil+}++func (s *SwarmService) summarizeServicesInternal(ctx context.Context, dockerClient *dockerclient.Client, services []swarm.Service) ([]swarmtypes.ServiceSummary, error) {+ nodesResult, err := dockerClient.NodeList(ctx, dockerclient.NodeListOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to list swarm nodes: %w", err)+ }++ nodeNameByID := make(map[string]string, len(nodesResult.Items))+ for _, node := range nodesResult.Items {+ nodeNameByID[node.ID] = node.Description.Hostname+ }++ networksResult, err := dockerClient.NetworkList(ctx, dockerclient.NetworkListOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to list networks: %w", err)+ }++ networkNameByID := make(map[string]string, len(networksResult.Items))+ for _, network := range networksResult.Items {+ networkNameByID[network.ID] = network.Name+ }++ serviceIDs := make(map[string]struct{}, len(services))+ for _, service := range services {+ serviceIDs[service.ID] = struct{}{}+ }++ tasksResult, err := dockerClient.TaskList(ctx, dockerclient.TaskListOptions{})+ if err != nil {+ return nil, fmt.Errorf("failed to list swarm tasks: %w", err)+ }++ serviceNodes := make(map[string]map[string]struct{})+ for _, task := range tasksResult.Items {+ if string(task.Status.State) != "running" {+ continue+ }+ if _, ok := serviceIDs[task.ServiceID]; !ok {+ continue+ }+ if _, ok := serviceNodes[task.ServiceID]; !ok {+ serviceNodes[task.ServiceID] = make(map[string]struct{})+ }+ if nodeName, ok := nodeNameByID[task.NodeID]; ok {+ serviceNodes[task.ServiceID][nodeName] = struct{}{}+ }+ }++ summaries := make([]swarmtypes.ServiceSummary, 0, len(services))+ for _, service := range services {+ var nodeNames []string+ if nodeSet, ok := serviceNodes[service.ID]; ok {+ nodeNames = make([]string, 0, len(nodeSet))+ for nodeName := range nodeSet {+ nodeNames = append(nodeNames, nodeName)+ }+ sort.Strings(nodeNames)+ }+ summaries = append(summaries, swarmtypes.NewServiceSummary(service, nodeNames, networkNameByID))+ }++ return summaries, nil+}++func (s *SwarmService) listStackServicesRawInternal(ctx context.Context, dockerClient *dockerclient.Client, stackName string) ([]swarm.Service, error) {+ stackName = strings.TrimSpace(stackName)+ if stackName == "" {+ return nil, errors.New("stack name is required")+ }++ stackFilter := make(dockerclient.Filters).Add("label", fmt.Sprintf("%s=%s", swarmtypes.StackNamespaceLabel, stackName))+ servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{+ Filters: stackFilter,+ Status: true,+ })+ if err != nil {+ return nil, fmt.Errorf("failed to list stack services: %w", err)+ }++ return servicesResult.Items, nil+}++func (s *SwarmService) waitForRemovedServiceTasksInternal(ctx context.Context, dockerClient *dockerclient.Client, serviceIDs map[string]struct{}, timeout time.Duration) error {+ if len(serviceIDs) == 0 {+ return nil+ }++ waitCtx, cancel := context.WithTimeout(ctx, timeout)+ defer cancel()++ ticker := time.NewTicker(time.Second)+ defer ticker.Stop()++ taskFilters := make(dockerclient.Filters)+ for serviceID := range serviceIDs {+ taskFilters.Add("service", serviceID)+ }++ for {+ tasksResult, err := dockerClient.TaskList(waitCtx, dockerclient.TaskListOptions{Filters: taskFilters})+ if err != nil {+ return fmt.Errorf("failed to list tasks while waiting for stack removal: %w", err)+ }++ hasActiveTasks := false+ for _, task := range tasksResult.Items {+ if !isTaskTerminalInternal(task.Status.State) {+ hasActiveTasks = true+ break+ }+ }+ if !hasActiveTasks {+ return nil+ }++ select {+ case <-waitCtx.Done():+ return fmt.Errorf("timed out waiting for stack task convergence: %w", waitCtx.Err())+ case <-ticker.C:+ }+ }+}++func isTaskTerminalInternal(state swarm.TaskState) bool {+ switch state {+ case swarm.TaskStateComplete,+ swarm.TaskStateShutdown,+ swarm.TaskStateFailed,+ swarm.TaskStateRejected,+ swarm.TaskStateRemove,+ swarm.TaskStateOrphaned:+ return true+ case swarm.TaskStateNew,+ swarm.TaskStateAllocated,+ swarm.TaskStatePending,+ swarm.TaskStateAssigned,+ swarm.TaskStateAccepted,+ swarm.TaskStatePreparing,+ swarm.TaskStateReady,+ swarm.TaskStateStarting,+ swarm.TaskStateRunning:+ return false+ }++ return false+}++func decodeConfigSpecInternal(raw json.RawMessage) (swarm.ConfigSpec, error) {+ if len(raw) == 0 || strings.TrimSpace(string(raw)) == "" || strings.TrimSpace(string(raw)) == "null" {+ return swarm.ConfigSpec{}, errors.New("config spec is required")+ }++ var spec swarm.ConfigSpec+ if err := json.Unmarshal(raw, &spec); err != nil {+ return swarm.ConfigSpec{}, fmt.Errorf("failed to parse config spec: %w", err)+ }++ if strings.TrimSpace(spec.Name) == "" {+ return swarm.ConfigSpec{}, errors.New("config spec name is required")+ }++ return spec, nil+}++func decodeSecretSpecInternal(raw json.RawMessage) (swarm.SecretSpec, error) {+ if len(raw) == 0 || strings.TrimSpace(string(raw)) == "" || strings.TrimSpace(string(raw)) == "null" {+ return swarm.SecretSpec{}, errors.New("secret spec is required")+ }++ var spec swarm.SecretSpec+ if err := json.Unmarshal(raw, &spec); err != nil {+ return swarm.SecretSpec{}, fmt.Errorf("failed to parse secret spec: %w", err)+ }++ if strings.TrimSpace(spec.Name) == "" {+ return swarm.SecretSpec{}, errors.New("secret spec name is required")+ }++ return spec, nil+}++func (s *SwarmService) upsertStackSourceInternal(ctx context.Context, environmentID, stackName, composeContent, envContent string) error {+ stackName = strings.TrimSpace(stackName)+ if stackName == "" {+ return errors.New("stack name is required")+ }++ _, stackSourceDir, err := s.resolveSwarmStackSourceDirInternal(ctx, environmentID, stackName)+ if err != nil {+ return err+ }++ if err := os.MkdirAll(stackSourceDir, common.DirPerm); err != nil {+ return fmt.Errorf("failed to create swarm stack source directory: %w", err)+ }++ if err := os.WriteFile(filepath.Join(stackSourceDir, swarmStackComposeFilename), []byte(composeContent), common.FilePerm); err != nil {+ return fmt.Errorf("failed to write swarm stack compose source: %w", err)+ }++ envPath := filepath.Join(stackSourceDir, swarmStackEnvFilename)+ if envContent == "" {+ if err := os.Remove(envPath); err != nil && !errors.Is(err, os.ErrNotExist) {+ return fmt.Errorf("failed to clear swarm stack env source: %w", err)+ }+ return nil+ }++ if err := os.WriteFile(envPath, []byte(envContent), common.FilePerm); err != nil {+ return fmt.Errorf("failed to write swarm stack env source: %w", err)+ }++ return nil+}++func (s *SwarmService) deleteStackSourceInternal(ctx context.Context, environmentID, stackName string) error {+ if strings.TrimSpace(stackName) == "" {+ return errors.New("stack name is required")+ }++ rootDir, stackSourceDir, err := s.resolveSwarmStackSourceDirInternal(ctx, environmentID, stackName)+ if err != nil {+ return err+ }++ if err := os.RemoveAll(stackSourceDir); err != nil {+ return fmt.Errorf("failed to remove swarm stack source directory: %w", err)+ }++ // Best-effort cleanup of now-empty environment directory.+ environmentDir := filepath.Dir(stackSourceDir)+ if environmentDir != rootDir {+ if err := os.Remove(environmentDir); err != nil && !errors.Is(err, os.ErrNotExist) {+ var errno syscall.Errno+ if errors.As(err, &errno) && (errno == syscall.ENOTEMPTY || errno == syscall.EACCES) {+ slog.DebugContext(ctx, "swarm stack source environment directory cleanup skipped", "dir", environmentDir, "error", err)+ return nil+ }++ if errors.Is(err, os.ErrPermission) {+ slog.DebugContext(ctx, "swarm stack source environment directory cleanup skipped", "dir", environmentDir, "error", err)+ return nil+ }++ slog.DebugContext(ctx, "swarm stack source environment directory cleanup skipped", "dir", environmentDir, "error", err)+ }+ }++ return nil+}++func normalizeSwarmEnvironmentIDInternal(environmentID string) string {+ envID := strings.TrimSpace(environmentID)+ if envID == "" {+ return "0"+ }+ return envID+}++const (+ defaultSwarmStackSourceRootDir = "/app/data/swarm/sources"+ swarmStackComposeFilename = "compose.yaml"+ swarmStackEnvFilename = ".env"+)++func (s *SwarmService) resolveSwarmStackSourceDirInternal(ctx context.Context, environmentID, stackName string) (string, string, error) {+ normalizedStackName := appfs.SanitizeProjectName(strings.TrimSpace(stackName))+ if normalizedStackName == "" || strings.Trim(normalizedStackName, "_") == "" {+ return "", "", errors.New("invalid stack name")+ }++ normalizedEnvironmentID := appfs.SanitizeProjectName(normalizeSwarmEnvironmentIDInternal(environmentID))+ if normalizedEnvironmentID == "" || strings.Trim(normalizedEnvironmentID, "_") == "" {+ normalizedEnvironmentID = "0"+ }++ configuredRootDir := defaultSwarmStackSourceRootDir+ if s.settingsService != nil {+ configuredRootDir = s.settingsService.GetStringSetting(ctx, "swarmStackSourcesDirectory", defaultSwarmStackSourceRootDir)+ }+ rootDir := appfs.ResolveConfiguredContainerDirectory(configuredRootDir, defaultSwarmStackSourceRootDir)++ stackSourceDir := filepath.Clean(filepath.Join(rootDir, normalizedEnvironmentID, normalizedStackName))+ if !appfs.IsSafeSubdirectory(rootDir, stackSourceDir) {+ return "", "", errors.New("swarm stack source path escapes storage root")+ }++ return rootDir, stackSourceDir, nil+}++func (s *SwarmService) ensureSwarmManagerInternal(ctx context.Context) error {+ info, err := s.getDockerInfoInternal(ctx)+ if err != nil {+ return err+ }++ if info.Swarm.LocalNodeState != swarm.LocalNodeStateActive {+ return ErrSwarmNotEnabled+ }+ if !info.Swarm.ControlAvailable {+ return ErrSwarmManagerRequired+ }++ return nil+}++func (s *SwarmService) ensureSwarmActiveInternal(ctx context.Context) error {+ info, err := s.getDockerInfoInternal(ctx)+ if err != nil {+ return err+ }++ if info.Swarm.LocalNodeState != swarm.LocalNodeStateActive {+ return ErrSwarmNotEnabled+ }++ return nil+}++func (s *SwarmService) getDockerInfoInternal(ctx context.Context) (system.Info, error) {+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return system.Info{}, fmt.Errorf("failed to connect to Docker: %w", err)+ }++ infoResult, err := dockerClient.Info(ctx, dockerclient.InfoOptions{})+ if err != nil {+ return system.Info{}, fmt.Errorf("failed to get Docker info: %w", err)+ }++ return infoResult.Info, nil+}++func (s *SwarmService) buildServicePaginationConfigInternal() pagination.Config[swarmtypes.ServiceSummary] {+ return pagination.Config[swarmtypes.ServiceSummary]{+ SearchAccessors: []pagination.SearchAccessor[swarmtypes.ServiceSummary]{+ func(svc swarmtypes.ServiceSummary) (string, error) { return svc.Name, nil },+ func(svc swarmtypes.ServiceSummary) (string, error) { return svc.Image, nil },+ func(svc swarmtypes.ServiceSummary) (string, error) { return svc.ID, nil },+ func(svc swarmtypes.ServiceSummary) (string, error) { return svc.StackName, nil },+ func(svc swarmtypes.ServiceSummary) (string, error) { return svc.Mode, nil },+ func(svc swarmtypes.ServiceSummary) (string, error) {+ return strings.Join(svc.Networks, " "), nil+ },+ func(svc swarmtypes.ServiceSummary) (string, error) {+ return strings.Join(svc.Nodes, " "), nil+ },+ },+ SortBindings: []pagination.SortBinding[swarmtypes.ServiceSummary]{+ {Key: "name", Fn: func(a, b swarmtypes.ServiceSummary) int { return strings.Compare(a.Name, b.Name) }},+ {Key: "image", Fn: func(a, b swarmtypes.ServiceSummary) int { return strings.Compare(a.Image, b.Image) }},+ {Key: "mode", Fn: func(a, b swarmtypes.ServiceSummary) int { return strings.Compare(a.Mode, b.Mode) }},+ {Key: "replicas", Fn: func(a, b swarmtypes.ServiceSummary) int {+ if cmp := compareUint64Internal(a.Replicas, b.Replicas); cmp != 0 {+ return cmp+ }+ return compareUint64Internal(a.RunningReplicas, b.RunningReplicas)+ }},+ {Key: "created", Fn: func(a, b swarmtypes.ServiceSummary) int { return compareTimeInternal(a.CreatedAt, b.CreatedAt) }},+ {Key: "updated", Fn: func(a, b swarmtypes.ServiceSummary) int { return compareTimeInternal(a.UpdatedAt, b.UpdatedAt) }},+ },+ }+}++func (s *SwarmService) buildNodePaginationConfigInternal() pagination.Config[swarmtypes.NodeSummary] {+ return pagination.Config[swarmtypes.NodeSummary]{+ SearchAccessors: []pagination.SearchAccessor[swarmtypes.NodeSummary]{+ func(node swarmtypes.NodeSummary) (string, error) { return node.Hostname, nil },+ func(node swarmtypes.NodeSummary) (string, error) { return node.ID, nil },+ func(node swarmtypes.NodeSummary) (string, error) { return node.Role, nil },+ func(node swarmtypes.NodeSummary) (string, error) { return node.Status, nil },+ func(node swarmtypes.NodeSummary) (string, error) { return node.Availability, nil },+ },+ SortBindings: []pagination.SortBinding[swarmtypes.NodeSummary]{+ {Key: "hostname", Fn: func(a, b swarmtypes.NodeSummary) int { return strings.Compare(a.Hostname, b.Hostname) }},+ {Key: "role", Fn: func(a, b swarmtypes.NodeSummary) int { return strings.Compare(a.Role, b.Role) }},+ {Key: "status", Fn: func(a, b swarmtypes.NodeSummary) int { return strings.Compare(a.Status, b.Status) }},+ {Key: "availability", Fn: func(a, b swarmtypes.NodeSummary) int { return strings.Compare(a.Availability, b.Availability) }},+ {Key: "created", Fn: func(a, b swarmtypes.NodeSummary) int { return compareTimeInternal(a.CreatedAt, b.CreatedAt) }},+ {Key: "updated", Fn: func(a, b swarmtypes.NodeSummary) int { return compareTimeInternal(a.UpdatedAt, b.UpdatedAt) }},+ },+ }+}++func (s *SwarmService) buildTaskPaginationConfigInternal() pagination.Config[swarmtypes.TaskSummary] {+ return pagination.Config[swarmtypes.TaskSummary]{+ SearchAccessors: []pagination.SearchAccessor[swarmtypes.TaskSummary]{+ func(task swarmtypes.TaskSummary) (string, error) { return task.Name, nil },+ func(task swarmtypes.TaskSummary) (string, error) { return task.ServiceName, nil },+ func(task swarmtypes.TaskSummary) (string, error) { return task.NodeName, nil },+ func(task swarmtypes.TaskSummary) (string, error) { return task.ID, nil },+ func(task swarmtypes.TaskSummary) (string, error) { return task.CurrentState, nil },+ },+ SortBindings: []pagination.SortBinding[swarmtypes.TaskSummary]{+ {Key: "service", Fn: func(a, b swarmtypes.TaskSummary) int { return strings.Compare(a.ServiceName, b.ServiceName) }},+ {Key: "node", Fn: func(a, b swarmtypes.TaskSummary) int { return strings.Compare(a.NodeName, b.NodeName) }},+ {Key: "state", Fn: func(a, b swarmtypes.TaskSummary) int { return strings.Compare(a.CurrentState, b.CurrentState) }},+ {Key: "created", Fn: func(a, b swarmtypes.TaskSummary) int { return compareTimeInternal(a.CreatedAt, b.CreatedAt) }},+ {Key: "updated", Fn: func(a, b swarmtypes.TaskSummary) int { return compareTimeInternal(a.UpdatedAt, b.UpdatedAt) }},+ },+ }+}++func (s *SwarmService) buildStackPaginationConfigInternal() pagination.Config[swarmtypes.StackSummary] {+ return pagination.Config[swarmtypes.StackSummary]{+ SearchAccessors: []pagination.SearchAccessor[swarmtypes.StackSummary]{+ func(stack swarmtypes.StackSummary) (string, error) { return stack.Name, nil },+ func(stack swarmtypes.StackSummary) (string, error) { return stack.Namespace, nil },+ },+ SortBindings: []pagination.SortBinding[swarmtypes.StackSummary]{+ {Key: "name", Fn: func(a, b swarmtypes.StackSummary) int { return strings.Compare(a.Name, b.Name) }},+ {Key: "services", Fn: func(a, b swarmtypes.StackSummary) int { return compareIntInternal(a.Services, b.Services) }},+ {Key: "created", Fn: func(a, b swarmtypes.StackSummary) int { return compareTimeInternal(a.CreatedAt, b.CreatedAt) }},+ {Key: "updated", Fn: func(a, b swarmtypes.StackSummary) int { return compareTimeInternal(a.UpdatedAt, b.UpdatedAt) }},+ },+ }+}++func buildPaginationResponseInternal[T any](result pagination.FilterResult[T], params pagination.QueryParams) pagination.Response {+ totalPages := int64(0)+ if params.Limit > 0 {+ totalPages = (int64(result.TotalCount) + int64(params.Limit) - 1) / int64(params.Limit)+ }++ page := 1+ if params.Limit > 0 {+ page = (params.Start / params.Limit) + 1+ }++ return pagination.Response{+ TotalPages: totalPages,+ TotalItems: int64(result.TotalCount),+ CurrentPage: page,+ ItemsPerPage: params.Limit,+ GrandTotalItems: int64(result.TotalAvailable),+ }+}++func toServiceNetworkIPAMConfigInternal(cfg networktypes.IPAMConfig) swarmtypes.ServiceNetworkIPAMConfig {+ out := swarmtypes.ServiceNetworkIPAMConfig{}+ if cfg.Subnet.IsValid() {+ out.Subnet = cfg.Subnet.String()+ }+ if cfg.Gateway.IsValid() {+ out.Gateway = cfg.Gateway.String()+ }+ if cfg.IPRange.IsValid() {+ out.IPRange = cfg.IPRange.String()+ }+ return out+}++func compareTimeInternal(a, b time.Time) int {+ if a.Before(b) {+ return -1+ }+ if a.After(b) {+ return 1+ }+ return 0+}++func compareUint64Internal(a, b uint64) int {+ if a < b {+ return -1+ }+ if a > b {+ return 1+ }+ return 0+}++func compareIntInternal(a, b int) int {+ if a < b {+ return -1+ }+ if a > b {+ return 1+ }+ return 0+}diff --git a/backend/internal/services/swarm_service_test.go b/backend/internal/services/swarm_service_test.gonew file mode 100644index 000000000..b7d5c7072--- /dev/null+++ b/backend/internal/services/swarm_service_test.go@@ -0,0 +1,52 @@+package services++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/getarcaneapp/arcane/backend/internal/models"+ "github.com/stretchr/testify/require"+)++func TestSwarmService_FetchSwarmNodeIdentityViaEdgeInternal_UsesEnvironmentAccessToken(t *testing.T) {+ ctx := context.Background()+ db := setupEnvironmentServiceTestDB(t)+ settingsSvc, err := NewSettingsService(ctx, db)+ require.NoError(t, err)+ envSvc := NewEnvironmentService(db, nil, nil, nil, settingsSvc, nil)++ accessToken := "token-123"+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ require.Equal(t, http.MethodGet, r.Method)+ require.Equal(t, "/api/swarm/node-identity", r.URL.Path)+ require.Equal(t, accessToken, r.Header.Get("X-API-Key"))+ require.Equal(t, accessToken, r.Header.Get("X-Arcane-Agent-Token"))++ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"success":true,"data":{"swarmNodeId":"node-1","hostname":"worker-1","role":"worker","engineVersion":"29.3.1","swarmActive":true}}`))+ }))+ defer server.Close()++ createTestEnvironmentWithState(+ t,+ db,+ "env-1",+ server.URL,+ string(models.EnvironmentStatusOnline),+ false,+ &accessToken,+ )++ svc := NewSwarmService(nil, nil, nil, envSvc)++ identity, err := svc.fetchSwarmNodeIdentityViaEdgeInternal(ctx, "env-1")+ require.NoError(t, err)+ require.NotNil(t, identity)+ require.Equal(t, "node-1", identity.SwarmNodeID)+ require.Equal(t, "worker-1", identity.Hostname)+ require.Equal(t, "worker", identity.Role)+ require.Equal(t, "29.3.1", identity.EngineVersion)+ require.True(t, identity.SwarmActive)+}diff --git a/backend/internal/services/template_service.go b/backend/internal/services/template_service.goindex f6ae63585..b0f294e78 100644--- a/backend/internal/services/template_service.go+++ b/backend/internal/services/template_service.go@@ -348,6 +348,26 @@ func (s *TemplateService) GetComposeTemplate() string {return string(content)}+func (s *TemplateService) GetSwarmStackTemplate() string {+ swarmStackPath := filepath.Join("data", "templates", ".swarm-stack.template")+ content, err := os.ReadFile(swarmStackPath)+ if err != nil {+ slog.Warn("failed to read swarm stack template", "error", err)+ return projects.DefaultSwarmStackTemplate()+ }+ return string(content)+}++func (s *TemplateService) GetSwarmStackEnvTemplate() string {+ swarmStackEnvPath := filepath.Join("data", "templates", ".swarm-stack.env.template")+ content, err := os.ReadFile(swarmStackEnvPath)+ if err != nil {+ slog.Warn("failed to read swarm stack env template", "error", err)+ return projects.DefaultSwarmStackEnvTemplate()+ }+ return string(content)+}+func (s *TemplateService) SaveComposeTemplate(content string) error {templateDir := filepath.Join("data", "templates")composePath := filepath.Join(templateDir, ".compose.template")diff --git a/backend/internal/services/vulnerability_service_test.go b/backend/internal/services/vulnerability_service_test.goindex 46bbfe0f1..0f11d2e6f 100644--- a/backend/internal/services/vulnerability_service_test.go+++ b/backend/internal/services/vulnerability_service_test.go@@ -318,9 +318,9 @@ func TestBuildTrivyHostConfig_ExcludesResourcesWhenLimitsDisabled(t *testing.T)false,)require.Equal(t, containertypes.NetworkMode("bridge"), hostConfig.NetworkMode)- require.Equal(t, int64(0), hostConfig.Resources.NanoCPUs)- require.Equal(t, int64(0), hostConfig.Resources.Memory)- require.Equal(t, int64(0), hostConfig.Resources.MemorySwap)+ require.Equal(t, int64(0), hostConfig.NanoCPUs)+ require.Equal(t, int64(0), hostConfig.Memory)+ require.Equal(t, int64(0), hostConfig.MemorySwap)require.Empty(t, hostConfig.SecurityOpt)require.False(t, hostConfig.Privileged)}@@ -343,9 +343,9 @@ func TestBuildTrivyHostConfig_IncludesResourcesWhenLimitsEnabled(t *testing.T) {false,)require.Equal(t, containertypes.NetworkMode("arcane-external"), hostConfig.NetworkMode)- require.Equal(t, resources.NanoCPUs, hostConfig.Resources.NanoCPUs)- require.Equal(t, resources.Memory, hostConfig.Resources.Memory)- require.Equal(t, resources.MemorySwap, hostConfig.Resources.MemorySwap)+ require.Equal(t, resources.NanoCPUs, hostConfig.NanoCPUs)+ require.Equal(t, resources.Memory, hostConfig.Memory)+ require.Equal(t, resources.MemorySwap, hostConfig.MemorySwap)}func TestBuildTrivyHostConfig_UsesCPUSetAndClearsNanoCPUs(t *testing.T) {@@ -366,10 +366,10 @@ func TestBuildTrivyHostConfig_UsesCPUSetAndClearsNanoCPUs(t *testing.T) {false,)require.Equal(t, containertypes.NetworkMode("bridge"), hostConfig.NetworkMode)- require.Equal(t, int64(0), hostConfig.Resources.NanoCPUs)- require.Equal(t, "0-1", hostConfig.Resources.CpusetCpus)- require.Equal(t, resources.Memory, hostConfig.Resources.Memory)- require.Equal(t, resources.MemorySwap, hostConfig.Resources.MemorySwap)+ require.Equal(t, int64(0), hostConfig.NanoCPUs)+ require.Equal(t, "0-1", hostConfig.CpusetCpus)+ require.Equal(t, resources.Memory, hostConfig.Memory)+ require.Equal(t, resources.MemorySwap, hostConfig.MemorySwap)}func TestParseTrivySecurityOptsInternal(t *testing.T) {diff --git a/backend/pkg/gitutil/git.go b/backend/pkg/gitutil/git.goindex 7057531c8..9803fb3c1 100644--- a/backend/pkg/gitutil/git.go+++ b/backend/pkg/gitutil/git.go@@ -10,6 +10,7 @@ import (nethttp "net/http""os""path/filepath"+ "slices""sort""strings""time"@@ -676,10 +677,7 @@ func isBinaryContent(content []byte) bool {}// Check first 512 bytes (or less if file is smaller)- checkSize := 512- if len(content) < checkSize {- checkSize = len(content)- }+ checkSize := min(len(content), 512)// Use net/http's content type detectioncontentType := detectContentType(content[:checkSize])@@ -708,13 +706,7 @@ func isBinaryContent(content []byte) bool {// For application/octet-stream, do additional null-byte check// Text files rarely have null bytes, so their presence indicates binaryif contentType == "application/octet-stream" {- for _, b := range content[:checkSize] {- if b == 0 {- return true- }- }- // No null bytes found, likely a text file (Dockerfile, Makefile, etc.)- return false+ return slices.Contains(content[:checkSize], 0)}// Everything else is considered binarydiff --git a/backend/pkg/libarcane/containerstats/history_test.go b/backend/pkg/libarcane/containerstats/history_test.goindex c8c61ada1..c723674cc 100644--- a/backend/pkg/libarcane/containerstats/history_test.go+++ b/backend/pkg/libarcane/containerstats/history_test.go@@ -37,7 +37,7 @@ func TestStoreRecordCapsAndPreservesOrder(t *testing.T) {var store StorebaseTime := time.Date(2026, 3, 26, 12, 0, 0, 0, time.UTC)- for i := 0; i < HistoryCapacity+5; i++ {+ for i := range HistoryCapacity + 5 {store.Record("container-1",containertypes.StatsHistorySample{diff --git a/backend/pkg/libarcane/swarm/stack_deploy_engine.go b/backend/pkg/libarcane/swarm/stack_deploy_engine.gonew file mode 100644index 000000000..a373bd336--- /dev/null+++ b/backend/pkg/libarcane/swarm/stack_deploy_engine.go@@ -0,0 +1,1316 @@+package swarm++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "fmt"+ "maps"+ "net/netip"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "time"++ composegoloader "github.com/compose-spec/compose-go/v2/loader"+ composegotypes "github.com/compose-spec/compose-go/v2/types"+ cerrdefs "github.com/containerd/errdefs"+ "github.com/docker/compose/v5/pkg/api"+ "github.com/getarcaneapp/arcane/backend/pkg/projects"+ swarmtypes "github.com/getarcaneapp/arcane/types/swarm"+ "github.com/moby/moby/api/types/mount"+ "github.com/moby/moby/api/types/network"+ "github.com/moby/moby/api/types/swarm"+ dockerclient "github.com/moby/moby/client"+)++type resourceMeta struct {+ ID string+ Name string+}++const (+ resolveImageAlways = "always"+ resolveImageChanged = "changed"+ resolveImageNever = "never"+ stackImageLabel = "com.docker.stack.image"+ resourceTypeLabel = "io.getarcane.swarm.resource.type"+ resourceNameLabel = "io.getarcane.swarm.resource.name"+ resourceHashLabel = "io.getarcane.swarm.resource.hash"+ resourceNameMaxHash = 12+)++// StackDeployOptions controls how a swarm stack is deployed.+type StackDeployOptions struct {+ Name string+ ComposeContent string+ EnvContent string+ WithRegistryAuth bool+ RegistryAuthForImage func(context.Context, string) (string, error)+ Prune bool+ ResolveImage string+}++type StackRenderOptions struct {+ Name string+ ComposeContent string+ EnvContent string+}++type StackRenderResult struct {+ Name string+ RenderedCompose string+ Services []string+ Networks []string+ Volumes []string+ Configs []string+ Secrets []string+}++// DeployStack deploys a Compose-defined stack to Docker Swarm using the Engine API.+//+// It validates the stack name, loads the Compose project with environment+// interpolation, ensures required swarm-scoped networks, configs, and secrets+// exist, creates or updates services to match the desired state, optionally+// prunes services no longer declared by the stack, and removes stale managed+// configs and secrets after reconciliation.+//+// ctx controls cancellation for Compose loading and Docker API calls.+// dockerClient must target a swarm manager capable of creating and updating stack resources.+// opts provides the stack name, compose content, optional env content, registry-auth behavior, pruning, and image-resolution mode.+//+// Returns nil when the stack has been reconciled successfully.+// Returns an error if the stack name is empty, the compose or env content is+// invalid, a referenced resource cannot be inspected or created, or any Docker+// API call required to reconcile the stack fails.+func DeployStack(ctx context.Context, dockerClient *dockerclient.Client, opts StackDeployOptions) error {+ stackName := strings.TrimSpace(opts.Name)+ if stackName == "" {+ return errors.New("stack name is required")+ }+ resolveMode, err := normalizeResolveImageMode(opts.ResolveImage)+ if err != nil {+ return err+ }++ project, err := loadComposeProject(ctx, stackName, opts.ComposeContent, opts.EnvContent)+ if err != nil {+ return err+ }+ if project.Name == "" {+ project.Name = stackName+ }++ stackLabels := map[string]string{swarmtypes.StackNamespaceLabel: stackName}++ networkNameByKey, err := ensureSwarmNetworks(ctx, dockerClient, project, stackName, stackLabels)+ if err != nil {+ return err+ }++ configMetaByKey, err := ensureSwarmConfigs(ctx, dockerClient, project, stackName, stackLabels)+ if err != nil {+ return err+ }++ secretMetaByKey, err := ensureSwarmSecrets(ctx, dockerClient, project, stackName, stackLabels)+ if err != nil {+ return err+ }++ existingServices, err := listStackServices(ctx, dockerClient, stackName)+ if err != nil {+ return err+ }++ desiredServices, err := reconcileStackServices(+ ctx,+ dockerClient,+ project,+ stackName,+ stackLabels,+ networkNameByKey,+ configMetaByKey,+ secretMetaByKey,+ existingServices,+ opts,+ resolveMode,+ )+ if err != nil {+ return err+ }++ if opts.Prune {+ for name, svc := range existingServices {+ if _, ok := desiredServices[name]; ok {+ continue+ }+ if _, err := dockerClient.ServiceRemove(ctx, svc.ID, dockerclient.ServiceRemoveOptions{}); err != nil {+ return fmt.Errorf("failed to remove swarm service %s: %w", name, err)+ }+ }+ }++ if err := cleanupStackResources(ctx, dockerClient, stackName, configMetaByKey, secretMetaByKey); err != nil {+ return err+ }++ return nil+}++func reconcileStackServices(+ ctx context.Context,+ dockerClient *dockerclient.Client,+ project *composegotypes.Project,+ stackName string,+ stackLabels map[string]string,+ networkNameByKey map[string]string,+ configMetaByKey map[string]resourceMeta,+ secretMetaByKey map[string]resourceMeta,+ existingServices map[string]swarm.Service,+ opts StackDeployOptions,+ resolveMode string,+) (map[string]struct{}, error) {+ desiredServices := map[string]struct{}{}++ for key, service := range project.Services {+ if service.Name == "" {+ service.Name = key+ }+ spec, err := buildServiceSpec(service, stackName, stackLabels, networkNameByKey, configMetaByKey, secretMetaByKey)+ if err != nil {+ return nil, err+ }+ desiredServices[spec.Name] = struct{}{}++ if existing, ok := existingServices[spec.Name]; ok {+ if err := updateSwarmService(ctx, dockerClient, existing, spec, opts.WithRegistryAuth, opts.RegistryAuthForImage, resolveMode); err != nil {+ return nil, err+ }+ continue+ }++ if err := createSwarmService(ctx, dockerClient, spec, opts.WithRegistryAuth, opts.RegistryAuthForImage, resolveMode); err != nil {+ return nil, err+ }+ }++ return desiredServices, nil+}++func cleanupStackResources(+ ctx context.Context,+ dockerClient *dockerclient.Client,+ stackName string,+ configMetaByKey map[string]resourceMeta,+ secretMetaByKey map[string]resourceMeta,+) error {+ desiredConfigNames := make(map[string]struct{}, len(configMetaByKey))+ for _, meta := range configMetaByKey {+ desiredConfigNames[meta.Name] = struct{}{}+ }+ if err := cleanupStaleConfigs(ctx, dockerClient, stackName, desiredConfigNames); err != nil {+ return err+ }++ desiredSecretNames := make(map[string]struct{}, len(secretMetaByKey))+ for _, meta := range secretMetaByKey {+ desiredSecretNames[meta.Name] = struct{}{}+ }+ if err := cleanupStaleSecrets(ctx, dockerClient, stackName, desiredSecretNames); err != nil {+ return err+ }++ return nil+}++// RenderStackConfig renders a Compose-defined stack without deploying it.+//+// It validates the stack name, loads and interpolates the Compose project using+// the provided environment content, marshals the normalized project back to+// YAML, and reports the discovered service, network, volume, config, and secret+// names that would participate in deployment.+//+// ctx controls cancellation for Compose loading.+// opts provides the stack name, compose content, and optional env content to render.+//+// Returns the rendered compose YAML and related resource names.+// Returns an error if the stack name is empty, the compose or env content is+// invalid, or the normalized Compose project cannot be marshaled.+func RenderStackConfig(ctx context.Context, opts StackRenderOptions) (*StackRenderResult, error) {+ stackName := strings.TrimSpace(opts.Name)+ if stackName == "" {+ return nil, errors.New("stack name is required")+ }++ project, err := loadComposeProject(ctx, stackName, opts.ComposeContent, opts.EnvContent)+ if err != nil {+ return nil, err+ }+ if project.Name == "" {+ project.Name = stackName+ }++ rendered, err := project.MarshalYAML()+ if err != nil {+ return nil, fmt.Errorf("failed to render compose project: %w", err)+ }++ return &StackRenderResult{+ Name: stackName,+ RenderedCompose: string(rendered),+ Services: project.ServiceNames(),+ Networks: project.NetworkNames(),+ Volumes: project.VolumeNames(),+ Configs: project.ConfigNames(),+ Secrets: project.SecretNames(),+ }, nil+}++func loadComposeProject(ctx context.Context, projectName, composeContent, envContent string) (*composegotypes.Project, error) {+ composeContent = strings.TrimSpace(composeContent)+ if composeContent == "" {+ return nil, errors.New("compose content is required")+ }++ envMap, err := parseEnvContent(envContent)+ if err != nil {+ return nil, fmt.Errorf("failed to parse env content: %w", err)+ }++ workingDir, err := os.Getwd()+ if err != nil {+ workingDir = "/tmp"+ }+ envMap["PWD"] = workingDir++ configDetails := composegotypes.ConfigDetails{+ Version: api.ComposeVersion,+ WorkingDir: workingDir,+ ConfigFiles: []composegotypes.ConfigFile{+ {Content: []byte(composeContent)},+ },+ Environment: composegotypes.Mapping(envMap),+ }++ project, err := composegoloader.LoadWithContext(ctx, configDetails, func(opts *composegoloader.Options) {+ if strings.TrimSpace(projectName) != "" {+ opts.SetProjectName(strings.TrimSpace(projectName), true)+ }+ })+ if err != nil {+ return nil, fmt.Errorf("failed to load compose project: %w", err)+ }++ project = project.WithoutUnnecessaryResources()+ return project, nil+}++func listStackServices(ctx context.Context, dockerClient *dockerclient.Client, stackName string) (map[string]swarm.Service, error) {+ filter := make(dockerclient.Filters).Add("label", fmt.Sprintf("%s=%s", swarmtypes.StackNamespaceLabel, stackName))+ servicesResult, err := dockerClient.ServiceList(ctx, dockerclient.ServiceListOptions{Filters: filter})+ if err != nil {+ return nil, fmt.Errorf("failed to list swarm services: %w", err)+ }+ services := servicesResult.Items++ byName := make(map[string]swarm.Service, len(services))+ for _, service := range services {+ byName[service.Spec.Name] = service+ }+ return byName, nil+}++func ensureSwarmNetworks(ctx context.Context, dockerClient *dockerclient.Client, project *composegotypes.Project, stackName string, stackLabels map[string]string) (map[string]string, error) {+ result := make(map[string]string, len(project.Networks))+ for key, cfg := range project.Networks {+ networkName := strings.TrimSpace(cfg.Name)+ if networkName == "" {+ networkName = key+ }++ if bool(cfg.External) {+ result[key] = networkName+ continue+ }++ stackedName := stackScopedName(stackName, networkName)+ result[key] = stackedName++ _, err := dockerClient.NetworkInspect(ctx, stackedName, dockerclient.NetworkInspectOptions{Scope: "swarm"})+ if err == nil {+ continue+ }+ if !cerrdefs.IsNotFound(err) {+ return nil, fmt.Errorf("failed to inspect network %s: %w", stackedName, err)+ }++ driver := strings.TrimSpace(cfg.Driver)+ if driver == "" {+ driver = "overlay"+ }++ labels := mergeLabels(cfg.Labels, stackLabels)+ createOpts := dockerclient.NetworkCreateOptions{+ Driver: driver,+ Scope: "swarm",+ EnableIPv4: cfg.EnableIPv4,+ EnableIPv6: cfg.EnableIPv6,+ Internal: cfg.Internal,+ Attachable: cfg.Attachable,+ Options: cfg.DriverOpts,+ Labels: labels,+ IPAM: convertIPAM(cfg.Ipam),+ }++ if _, err := dockerClient.NetworkCreate(ctx, stackedName, createOpts); err != nil {+ return nil, fmt.Errorf("failed to create network %s: %w", stackedName, err)+ }+ }++ return result, nil+}++func ensureSwarmConfigs(ctx context.Context, dockerClient *dockerclient.Client, project *composegotypes.Project, stackName string, stackLabels map[string]string) (map[string]resourceMeta, error) {+ result := make(map[string]resourceMeta, len(project.Configs))+ for key, cfg := range project.Configs {+ name := resolveResourceName(stackName, key, cfg.Name, cfg.External)+ if cfg.External {+ meta, err := inspectConfig(ctx, dockerClient, name)+ if err != nil {+ return nil, err+ }+ result[key] = meta+ continue+ }++ meta, err := ensureConfig(ctx, dockerClient, name, cfg, stackLabels, project.WorkingDir)+ if err != nil {+ return nil, err+ }+ result[key] = meta+ }+ return result, nil+}++func ensureSwarmSecrets(ctx context.Context, dockerClient *dockerclient.Client, project *composegotypes.Project, stackName string, stackLabels map[string]string) (map[string]resourceMeta, error) {+ result := make(map[string]resourceMeta, len(project.Secrets))+ for key, cfg := range project.Secrets {+ name := resolveResourceName(stackName, key, cfg.Name, cfg.External)+ if cfg.External {+ meta, err := inspectSecret(ctx, dockerClient, name)+ if err != nil {+ return nil, err+ }+ result[key] = meta+ continue+ }++ meta, err := ensureSecret(ctx, dockerClient, name, cfg, stackLabels, project.WorkingDir)+ if err != nil {+ return nil, err+ }+ result[key] = meta+ }+ return result, nil+}++func ensureConfig(ctx context.Context, dockerClient *dockerclient.Client, name string, cfg composegotypes.ConfigObjConfig, stackLabels map[string]string, workingDir string) (resourceMeta, error) {+ data, err := resolveFileObjectContent(composegotypes.FileObjectConfig(cfg), workingDir)+ if err != nil {+ return resourceMeta{}, fmt.Errorf("failed to load config %s: %w", name, err)+ }++ hash := hashManagedResource(data)+ managedName := managedResourceName(name, hash)+ if meta, err := inspectConfig(ctx, dockerClient, managedName); err == nil {+ return meta, nil+ } else if !cerrdefs.IsNotFound(err) {+ return resourceMeta{}, fmt.Errorf("failed to inspect config %s: %w", managedName, err)+ }++ labels := mergeLabels(cfg.Labels, stackLabels)+ labels[resourceTypeLabel] = "config"+ labels[resourceNameLabel] = name+ labels[resourceHashLabel] = hash+ spec := swarm.ConfigSpec{+ Annotations: swarm.Annotations{+ Name: managedName,+ Labels: labels,+ },+ Data: data,+ }++ resp, err := dockerClient.ConfigCreate(ctx, dockerclient.ConfigCreateOptions{Spec: spec})+ if err != nil {+ return resourceMeta{}, fmt.Errorf("failed to create config %s: %w", managedName, err)+ }+ return resourceMeta{ID: resp.ID, Name: managedName}, nil+}++func ensureSecret(ctx context.Context, dockerClient *dockerclient.Client, name string, cfg composegotypes.SecretConfig, stackLabels map[string]string, workingDir string) (resourceMeta, error) {+ data, err := resolveFileObjectContent(composegotypes.FileObjectConfig(cfg), workingDir)+ if err != nil {+ return resourceMeta{}, fmt.Errorf("failed to load secret %s: %w", name, err)+ }++ hash := hashManagedResource(data)+ managedName := managedResourceName(name, hash)+ if meta, err := inspectSecret(ctx, dockerClient, managedName); err == nil {+ return meta, nil+ } else if !cerrdefs.IsNotFound(err) {+ return resourceMeta{}, fmt.Errorf("failed to inspect secret %s: %w", managedName, err)+ }++ labels := mergeLabels(cfg.Labels, stackLabels)+ labels[resourceTypeLabel] = "secret"+ labels[resourceNameLabel] = name+ labels[resourceHashLabel] = hash+ spec := swarm.SecretSpec{+ Annotations: swarm.Annotations{+ Name: managedName,+ Labels: labels,+ },+ Data: data,+ }++ resp, err := dockerClient.SecretCreate(ctx, dockerclient.SecretCreateOptions{Spec: spec})+ if err != nil {+ return resourceMeta{}, fmt.Errorf("failed to create secret %s: %w", managedName, err)+ }+ return resourceMeta{ID: resp.ID, Name: managedName}, nil+}++func inspectConfig(ctx context.Context, dockerClient *dockerclient.Client, name string) (resourceMeta, error) {+ configResult, err := dockerClient.ConfigInspect(ctx, name, dockerclient.ConfigInspectOptions{})+ if err != nil {+ return resourceMeta{}, err+ }+ config := configResult.Config+ return resourceMeta{ID: config.ID, Name: config.Spec.Name}, nil+}++func inspectSecret(ctx context.Context, dockerClient *dockerclient.Client, name string) (resourceMeta, error) {+ secretResult, err := dockerClient.SecretInspect(ctx, name, dockerclient.SecretInspectOptions{})+ if err != nil {+ return resourceMeta{}, err+ }+ secret := secretResult.Secret+ return resourceMeta{ID: secret.ID, Name: secret.Spec.Name}, nil+}++func resolveResourceName(stackName, key, resourceName string, external composegotypes.External) string {+ name := strings.TrimSpace(resourceName)+ if name == "" {+ name = key+ }+ if bool(external) {+ return name+ }+ return stackScopedName(stackName, name)+}++func buildServiceSpec(+ service composegotypes.ServiceConfig,+ stackName string,+ stackLabels map[string]string,+ networkNameByKey map[string]string,+ configMetaByKey map[string]resourceMeta,+ secretMetaByKey map[string]resourceMeta,+) (swarm.ServiceSpec, error) {+ serviceName := stackScopedName(stackName, service.Name)+ serviceLabels := mergeLabels(nil, stackLabels)+ if service.Deploy != nil {+ serviceLabels = mergeLabels(service.Deploy.Labels, serviceLabels)+ }+ if service.Image != "" {+ serviceLabels[stackImageLabel] = service.Image+ }++ spec := swarm.ServiceSpec{+ Annotations: swarm.Annotations{+ Name: serviceName,+ Labels: serviceLabels,+ },+ TaskTemplate: swarm.TaskSpec{+ ContainerSpec: &swarm.ContainerSpec{+ Image: service.Image,+ Command: toStringSlice(service.Entrypoint),+ Args: toStringSlice(service.Command),+ Env: convertEnv(service.Environment),+ Dir: service.WorkingDir,+ User: service.User,+ Groups: service.GroupAdd,+ Hostname: service.Hostname,+ Init: service.Init,+ StopSignal: service.StopSignal,+ StopGracePeriod: convertDurationPtr(service.StopGracePeriod),+ ReadOnly: service.ReadOnly,+ TTY: service.Tty,+ OpenStdin: service.StdinOpen,+ Labels: mergeLabels(service.Labels, stackLabels),+ Mounts: convertServiceMounts(service.Volumes),+ Secrets: convertServiceSecretRefs(service.Secrets, secretMetaByKey),+ Configs: convertServiceConfigRefs(service.Configs, configMetaByKey),+ },+ Networks: buildServiceNetworks(service, networkNameByKey),+ },+ }++ if len(service.ExtraHosts) > 0 {+ spec.TaskTemplate.ContainerSpec.Hosts = service.ExtraHosts.AsList(":")+ }++ if len(service.DNS) > 0 || len(service.DNSSearch) > 0 || len(service.DNSOpts) > 0 {+ spec.TaskTemplate.ContainerSpec.DNSConfig = &swarm.DNSConfig{+ Nameservers: parseIPList(service.DNS),+ Search: []string(service.DNSSearch),+ Options: service.DNSOpts,+ }+ }++ applyDeployConfig(&spec, service.Deploy, service.Scale)+ applyServicePorts(&spec, service.Ports)++ return spec, nil+}++func createSwarmService(+ ctx context.Context,+ dockerClient *dockerclient.Client,+ spec swarm.ServiceSpec,+ withRegistryAuth bool,+ registryAuthForImage func(context.Context, string) (string, error),+ resolveMode string,+) error {+ encodedRegistryAuth, err := resolveRegistryAuthForSpec(ctx, spec, withRegistryAuth, registryAuthForImage)+ if err != nil {+ return err+ }+ queryRegistry := encodedRegistryAuth != "" || shouldQueryRegistryOnCreate(resolveMode)+ opts := dockerclient.ServiceCreateOptions{+ Spec: spec,+ QueryRegistry: queryRegistry,+ }+ if encodedRegistryAuth != "" {+ opts.EncodedRegistryAuth = encodedRegistryAuth+ }+ if _, err := dockerClient.ServiceCreate(ctx, opts); err != nil {+ return fmt.Errorf("failed to create swarm service %s: %w", spec.Name, err)+ }+ return nil+}++func updateSwarmService(+ ctx context.Context,+ dockerClient *dockerclient.Client,+ existing swarm.Service,+ spec swarm.ServiceSpec,+ withRegistryAuth bool,+ registryAuthForImage func(context.Context, string) (string, error),+ resolveMode string,+) error {+ encodedRegistryAuth, err := resolveRegistryAuthForSpec(ctx, spec, withRegistryAuth, registryAuthForImage)+ if err != nil {+ return err+ }+ queryRegistry := encodedRegistryAuth != "" || shouldQueryRegistryOnUpdate(resolveMode, existing, spec)+ if !queryRegistry {+ preserveExistingResolvedImage(&spec, existing)+ }+ // Do not force task rescheduling on no-op updates.+ spec.TaskTemplate.ForceUpdate = existing.Spec.TaskTemplate.ForceUpdate++ opts := dockerclient.ServiceUpdateOptions{+ Version: existing.Version,+ Spec: spec,+ QueryRegistry: queryRegistry,+ }+ if encodedRegistryAuth != "" {+ opts.EncodedRegistryAuth = encodedRegistryAuth+ opts.RegistryAuthFrom = swarm.RegistryAuthFromSpec+ } else {+ opts.RegistryAuthFrom = swarm.RegistryAuthFromPreviousSpec+ }++ if _, err := dockerClient.ServiceUpdate(ctx, existing.ID, opts); err != nil {+ return fmt.Errorf("failed to update swarm service %s: %w", spec.Name, err)+ }+ return nil+}++func applyDeployConfig(spec *swarm.ServiceSpec, deploy *composegotypes.DeployConfig, scale *int) {+ if deploy == nil {+ applyServiceMode(spec, "", scale)+ return+ }++ applyServiceMode(spec, deploy.Mode, scale)+ if deploy.Replicas != nil && spec.Mode.Replicated != nil {+ spec.Mode.Replicated.Replicas = toUint64Pointer(*deploy.Replicas)+ }++ if deploy.EndpointMode != "" {+ if spec.EndpointSpec == nil {+ spec.EndpointSpec = &swarm.EndpointSpec{}+ }+ spec.EndpointSpec.Mode = swarm.ResolutionMode(deploy.EndpointMode)+ }++ if deploy.UpdateConfig != nil {+ spec.UpdateConfig = &swarm.UpdateConfig{+ Parallelism: valueOrZero(deploy.UpdateConfig.Parallelism),+ Delay: time.Duration(deploy.UpdateConfig.Delay),+ FailureAction: swarm.FailureAction(deploy.UpdateConfig.FailureAction),+ Monitor: time.Duration(deploy.UpdateConfig.Monitor),+ MaxFailureRatio: deploy.UpdateConfig.MaxFailureRatio,+ Order: swarm.UpdateOrder(deploy.UpdateConfig.Order),+ }+ }+ if deploy.RollbackConfig != nil {+ spec.RollbackConfig = &swarm.UpdateConfig{+ Parallelism: valueOrZero(deploy.RollbackConfig.Parallelism),+ Delay: time.Duration(deploy.RollbackConfig.Delay),+ FailureAction: swarm.FailureAction(deploy.RollbackConfig.FailureAction),+ Monitor: time.Duration(deploy.RollbackConfig.Monitor),+ MaxFailureRatio: deploy.RollbackConfig.MaxFailureRatio,+ Order: swarm.UpdateOrder(deploy.RollbackConfig.Order),+ }+ }++ if deploy.RestartPolicy != nil {+ spec.TaskTemplate.RestartPolicy = &swarm.RestartPolicy{+ Condition: swarm.RestartPolicyCondition(deploy.RestartPolicy.Condition),+ Delay: convertDurationPtr(deploy.RestartPolicy.Delay),+ Window: convertDurationPtr(deploy.RestartPolicy.Window),+ }+ if deploy.RestartPolicy.MaxAttempts != nil {+ spec.TaskTemplate.RestartPolicy.MaxAttempts = deploy.RestartPolicy.MaxAttempts+ }+ }++ if deploy.Resources.Limits != nil || deploy.Resources.Reservations != nil {+ spec.TaskTemplate.Resources = &swarm.ResourceRequirements{}+ }+ if deploy.Resources.Limits != nil {+ spec.TaskTemplate.Resources.Limits = &swarm.Limit{+ NanoCPUs: int64(deploy.Resources.Limits.NanoCPUs),+ MemoryBytes: int64(deploy.Resources.Limits.MemoryBytes),+ Pids: deploy.Resources.Limits.Pids,+ }+ }+ if deploy.Resources.Reservations != nil {+ spec.TaskTemplate.Resources.Reservations = &swarm.Resources{+ NanoCPUs: int64(deploy.Resources.Reservations.NanoCPUs),+ MemoryBytes: int64(deploy.Resources.Reservations.MemoryBytes),+ }+ }++ if len(deploy.Placement.Constraints) > 0 || len(deploy.Placement.Preferences) > 0 || deploy.Placement.MaxReplicas > 0 {+ spec.TaskTemplate.Placement = &swarm.Placement{+ Constraints: deploy.Placement.Constraints,+ MaxReplicas: deploy.Placement.MaxReplicas,+ }+ if len(deploy.Placement.Preferences) > 0 {+ preferences := make([]swarm.PlacementPreference, 0, len(deploy.Placement.Preferences))+ for _, preference := range deploy.Placement.Preferences {+ if spread := strings.TrimSpace(preference.Spread); spread != "" {+ preferences = append(preferences, swarm.PlacementPreference{+ Spread: &swarm.SpreadOver{SpreadDescriptor: spread},+ })+ }+ }+ spec.TaskTemplate.Placement.Preferences = preferences+ }+ }+}++func applyServiceMode(spec *swarm.ServiceSpec, mode string, scale *int) {+ mode = strings.ToLower(strings.TrimSpace(mode))+ switch mode {+ case "global":+ spec.Mode = swarm.ServiceMode{Global: &swarm.GlobalService{}}+ default:+ replicas := uint64(1)+ if scale != nil {+ if *scale <= 0 {+ replicas = 0+ } else {+ replicas = uint64(*scale)+ }+ }+ spec.Mode = swarm.ServiceMode{Replicated: &swarm.ReplicatedService{Replicas: &replicas}}+ }+}++func applyServicePorts(spec *swarm.ServiceSpec, ports []composegotypes.ServicePortConfig) {+ if len(ports) == 0 {+ return+ }++ endpoint := spec.EndpointSpec+ if endpoint == nil {+ endpoint = &swarm.EndpointSpec{}+ }++ converted := make([]swarm.PortConfig, 0, len(ports))+ for _, port := range ports {+ entry := swarm.PortConfig{+ Name: port.Name,+ Protocol: network.IPProtocol(strings.ToLower(port.Protocol)),+ TargetPort: port.Target,+ }+ if port.Mode != "" {+ entry.PublishMode = swarm.PortConfigPublishMode(strings.ToLower(port.Mode))+ }+ if port.Published != "" {+ if published, err := strconv.ParseUint(port.Published, 10, 32); err == nil {+ entry.PublishedPort = uint32(published)+ }+ }+ converted = append(converted, entry)+ }++ endpoint.Ports = converted+ spec.EndpointSpec = endpoint+}++func buildServiceNetworks(service composegotypes.ServiceConfig, networkNameByKey map[string]string) []swarm.NetworkAttachmentConfig {+ var attachments []swarm.NetworkAttachmentConfig+ if len(service.Networks) == 0 {+ if defaultNetwork, ok := networkNameByKey["default"]; ok {+ attachments = append(attachments, swarm.NetworkAttachmentConfig{Target: defaultNetwork})+ }+ return attachments+ }++ for name, cfg := range service.Networks {+ networkName := networkNameByKey[name]+ if networkName == "" {+ networkName = name+ }+ if cfg == nil {+ attachments = append(attachments, swarm.NetworkAttachmentConfig{Target: networkName})+ continue+ }+ attachments = append(attachments, swarm.NetworkAttachmentConfig{+ Target: networkName,+ Aliases: cfg.Aliases,+ DriverOpts: cfg.DriverOpts,+ })+ }+ return attachments+}++func convertServiceMounts(volumes []composegotypes.ServiceVolumeConfig) []mount.Mount {+ if len(volumes) == 0 {+ return nil+ }+ result := make([]mount.Mount, 0, len(volumes))+ for _, vol := range volumes {+ mountType := mapVolumeType(vol.Type)+ entry := mount.Mount{+ Type: mountType,+ Source: vol.Source,+ Target: vol.Target,+ ReadOnly: vol.ReadOnly,+ Consistency: mount.Consistency(vol.Consistency),+ }+ if vol.Bind != nil {+ entry.BindOptions = &mount.BindOptions{+ Propagation: mount.Propagation(vol.Bind.Propagation),+ CreateMountpoint: bool(vol.Bind.CreateHostPath),+ }+ }+ if vol.Volume != nil {+ entry.VolumeOptions = &mount.VolumeOptions{+ NoCopy: vol.Volume.NoCopy,+ Labels: vol.Volume.Labels,+ Subpath: vol.Volume.Subpath,+ }+ }+ if vol.Tmpfs != nil {+ entry.TmpfsOptions = &mount.TmpfsOptions{+ SizeBytes: int64(vol.Tmpfs.Size),+ Mode: os.FileMode(vol.Tmpfs.Mode),+ }+ }+ if vol.Image != nil {+ entry.ImageOptions = &mount.ImageOptions{Subpath: vol.Image.SubPath}+ }+ result = append(result, entry)+ }+ return result+}++func convertServiceSecretRefs(secrets []composegotypes.ServiceSecretConfig, secretMetaByKey map[string]resourceMeta) []*swarm.SecretReference {+ if len(secrets) == 0 {+ return nil+ }+ result := make([]*swarm.SecretReference, 0, len(secrets))+ for _, secret := range secrets {+ meta, ok := secretMetaByKey[secret.Source]+ if !ok {+ continue+ }+ ref := &swarm.SecretReference{+ SecretID: meta.ID,+ SecretName: meta.Name,+ }+ target := secret.Target+ if target == "" {+ target = meta.Name+ }+ ref.File = &swarm.SecretReferenceFileTarget{+ Name: target,+ UID: secret.UID,+ GID: secret.GID,+ Mode: fileModeOrDefault(secret.Mode),+ }+ result = append(result, ref)+ }+ return result+}++func convertServiceConfigRefs(configs []composegotypes.ServiceConfigObjConfig, configMetaByKey map[string]resourceMeta) []*swarm.ConfigReference {+ if len(configs) == 0 {+ return nil+ }+ result := make([]*swarm.ConfigReference, 0, len(configs))+ for _, cfg := range configs {+ meta, ok := configMetaByKey[cfg.Source]+ if !ok {+ continue+ }+ ref := &swarm.ConfigReference{+ ConfigID: meta.ID,+ ConfigName: meta.Name,+ }+ target := cfg.Target+ if target == "" {+ target = meta.Name+ }+ ref.File = &swarm.ConfigReferenceFileTarget{+ Name: target,+ UID: cfg.UID,+ GID: cfg.GID,+ Mode: fileModeOrDefault(cfg.Mode),+ }+ result = append(result, ref)+ }+ return result+}++func resolveFileObjectContent(fileConfig composegotypes.FileObjectConfig, workingDir string) ([]byte, error) {+ if fileConfig.Content != "" {+ return []byte(fileConfig.Content), nil+ }+ if fileConfig.Environment != "" {+ value, ok := os.LookupEnv(fileConfig.Environment)+ if !ok {+ return nil, fmt.Errorf("environment variable %s not set", fileConfig.Environment)+ }+ return []byte(value), nil+ }+ if fileConfig.File != "" {+ path, err := resolvePathWithinWorkingDirInternal(workingDir, fileConfig.File)+ if err != nil {+ return nil, err+ }+ return os.ReadFile(path)+ }+ return nil, errors.New("config or secret content is required")+}++func resolvePathWithinWorkingDirInternal(workingDir, path string) (string, error) {+ baseDir := filepath.Clean(workingDir)+ if !filepath.IsAbs(baseDir) {+ absBaseDir, err := filepath.Abs(baseDir)+ if err != nil {+ return "", fmt.Errorf("failed to resolve working directory %q: %w", workingDir, err)+ }+ baseDir = absBaseDir+ }++ resolvedPath := path+ if !filepath.IsAbs(resolvedPath) {+ resolvedPath = filepath.Join(baseDir, resolvedPath)+ }+ resolvedPath = filepath.Clean(resolvedPath)+ if !filepath.IsAbs(resolvedPath) {+ absResolvedPath, err := filepath.Abs(resolvedPath)+ if err != nil {+ return "", fmt.Errorf("failed to resolve config file path %q: %w", path, err)+ }+ resolvedPath = absResolvedPath+ }++ relativePath, err := filepath.Rel(baseDir, resolvedPath)+ if err != nil {+ return "", fmt.Errorf("failed to validate config file path %q: %w", path, err)+ }+ if relativePath == ".." || strings.HasPrefix(relativePath, ".."+string(filepath.Separator)) {+ return "", fmt.Errorf("config file path %q escapes the working directory", path)+ }++ return resolvedPath, nil+}++func convertIPAM(cfg composegotypes.IPAMConfig) *network.IPAM {+ if cfg.Driver == "" && len(cfg.Config) == 0 {+ return nil+ }+ result := &network.IPAM{+ Driver: cfg.Driver,+ }+ if len(cfg.Config) > 0 {+ pools := make([]network.IPAMConfig, 0, len(cfg.Config))+ for _, pool := range cfg.Config {+ if pool == nil {+ continue+ }+ subnet, _ := parsePrefix(pool.Subnet)+ ipRange, _ := parsePrefix(pool.IPRange)+ gateway, _ := parseAddr(pool.Gateway)+ pools = append(pools, network.IPAMConfig{+ Subnet: subnet,+ Gateway: gateway,+ IPRange: ipRange,+ AuxAddress: parseAuxAddresses(pool.AuxiliaryAddresses),+ })+ }+ result.Config = pools+ }+ return result+}++func parseIPList(values []string) []netip.Addr {+ if len(values) == 0 {+ return nil+ }+ out := make([]netip.Addr, 0, len(values))+ for _, value := range values {+ addr, ok := parseAddr(value)+ if ok {+ out = append(out, addr)+ }+ }+ return out+}++func parseAddr(value string) (netip.Addr, bool) {+ value = strings.TrimSpace(value)+ if value == "" {+ return netip.Addr{}, false+ }+ addr, err := netip.ParseAddr(value)+ if err != nil {+ return netip.Addr{}, false+ }+ return addr, true+}++func parsePrefix(value string) (netip.Prefix, bool) {+ value = strings.TrimSpace(value)+ if value == "" {+ return netip.Prefix{}, false+ }+ prefix, err := netip.ParsePrefix(value)+ if err != nil {+ return netip.Prefix{}, false+ }+ return prefix, true+}++func parseAuxAddresses(values map[string]string) map[string]netip.Addr {+ if len(values) == 0 {+ return nil+ }+ out := make(map[string]netip.Addr, len(values))+ for key, value := range values {+ if addr, ok := parseAddr(value); ok {+ out[key] = addr+ }+ }+ return out+}++func convertEnv(env composegotypes.MappingWithEquals) []string {+ if env == nil {+ return nil+ }+ result := make([]string, 0, len(env))+ for key, value := range env {+ if value == nil {+ result = append(result, key)+ continue+ }+ result = append(result, fmt.Sprintf("%s=%s", key, *value))+ }+ return result+}++func toStringSlice(command composegotypes.ShellCommand) []string {+ if len(command) == 0 {+ return nil+ }+ return []string(command)+}++func convertDurationPtr(duration *composegotypes.Duration) *time.Duration {+ if duration == nil {+ return nil+ }+ value := time.Duration(*duration)+ return &value+}++func toUint64Pointer(value int) *uint64 {+ if value < 0 {+ return nil+ }+ converted := uint64(value)+ return &converted+}++func fileModeOrDefault(mode *composegotypes.FileMode) os.FileMode {+ if mode == nil {+ return 0444+ }+ converted := fileModeToUint32(mode)+ if converted == nil {+ return 0444+ }+ return os.FileMode(*converted)+}++func fileModeToUint32(mode *composegotypes.FileMode) *uint32 {+ return convertFileMode(mode)+}++func valueOrZero(value *uint64) uint64 {+ if value == nil {+ return 0+ }+ return *value+}++func mergeLabels(primary map[string]string, secondary map[string]string) map[string]string {+ out := map[string]string{}+ maps.Copy(out, primary)+ maps.Copy(out, secondary)+ return out+}++func stackScopedName(stackName, resourceName string) string {+ resourceName = strings.TrimSpace(resourceName)+ if resourceName == "" {+ return stackName+ }+ return fmt.Sprintf("%s_%s", stackName, resourceName)+}++func mapVolumeType(value string) mount.Type {+ switch strings.ToLower(value) {+ case "bind":+ return mount.TypeBind+ case "tmpfs":+ return mount.TypeTmpfs+ case "npipe":+ return mount.TypeNamedPipe+ case "cluster":+ return mount.TypeCluster+ case "image":+ return mount.TypeImage+ case "volume", "":+ return mount.TypeVolume+ default:+ return mount.TypeVolume+ }+}++func convertFileMode(mode *composegotypes.FileMode) *uint32 {+ if mode == nil {+ return nil+ }+ if result, ok := toUint32FromInt64(int64(*mode)); ok {+ return &result+ }+ return nil+}++func toUint32FromInt64(value int64) (uint32, bool) {+ if value < 0 || value > int64(^uint32(0)) {+ return 0, false+ }+ return uint32(value), true+}++func normalizeResolveImageMode(value string) (string, error) {+ mode := strings.ToLower(strings.TrimSpace(value))+ if mode == "" {+ return resolveImageAlways, nil+ }+ switch mode {+ case resolveImageAlways, resolveImageChanged, resolveImageNever:+ return mode, nil+ default:+ return "", fmt.Errorf("invalid resolve image mode %q: expected always, changed, or never", value)+ }+}++func shouldQueryRegistryOnCreate(resolveMode string) bool {+ return resolveMode == resolveImageAlways || resolveMode == resolveImageChanged+}++func shouldQueryRegistryOnUpdate(resolveMode string, existing swarm.Service, desired swarm.ServiceSpec) bool {+ switch resolveMode {+ case resolveImageAlways:+ return true+ case resolveImageChanged:+ desiredImage := resolveServiceImage(desired)+ existingImage := existing.Spec.Labels[stackImageLabel]+ return desiredImage != "" && desiredImage != existingImage+ default:+ return false+ }+}++func resolveServiceImage(spec swarm.ServiceSpec) string {+ if spec.TaskTemplate.ContainerSpec == nil {+ return ""+ }+ return spec.TaskTemplate.ContainerSpec.Image+}++func preserveExistingResolvedImage(spec *swarm.ServiceSpec, existing swarm.Service) {+ if spec.TaskTemplate.ContainerSpec == nil || existing.Spec.TaskTemplate.ContainerSpec == nil {+ return+ }+ if resolveServiceImage(*spec) == existing.Spec.Labels[stackImageLabel] {+ spec.TaskTemplate.ContainerSpec.Image = existing.Spec.TaskTemplate.ContainerSpec.Image+ }+}++func parseEnvContent(envContent string) (map[string]string, error) {+ env := make(projects.EnvMap)+ for _, entry := range os.Environ() {+ key, value, ok := strings.Cut(entry, "=")+ if !ok || key == "" {+ continue+ }+ env[key] = value+ }++ if strings.TrimSpace(envContent) == "" {+ return env, nil+ }++ parsedEnv, err := projects.ParseProjectEnvContent(envContent, env)+ if err != nil {+ return nil, err+ }++ maps.Copy(env, parsedEnv)+ return env, nil+}++func hashManagedResource(data []byte) string {+ sum := sha256.Sum256(data)+ return hex.EncodeToString(sum[:])+}++func managedResourceName(logicalName, hash string) string {+ hash = strings.TrimSpace(hash)+ if len(hash) > resourceNameMaxHash {+ hash = hash[:resourceNameMaxHash]+ }+ if hash == "" {+ return logicalName+ }+ return fmt.Sprintf("%s_%s", logicalName, hash)+}++func resolveRegistryAuthForSpec(+ ctx context.Context,+ spec swarm.ServiceSpec,+ withRegistryAuth bool,+ registryAuthForImage func(context.Context, string) (string, error),+) (string, error) {+ if !withRegistryAuth || registryAuthForImage == nil {+ return "", nil+ }++ image := resolveServiceImage(spec)+ if strings.TrimSpace(image) == "" {+ return "", nil+ }++ encodedRegistryAuth, err := registryAuthForImage(ctx, image)+ if err != nil {+ return "", fmt.Errorf("failed to resolve registry auth for image %s: %w", image, err)+ }++ return encodedRegistryAuth, nil+}++func cleanupStaleConfigs(ctx context.Context, dockerClient *dockerclient.Client, stackName string, desiredNames map[string]struct{}) error {+ filters := make(dockerclient.Filters)+ filters.Add("label", fmt.Sprintf("%s=%s", swarmtypes.StackNamespaceLabel, stackName))+ filters.Add("label", resourceTypeLabel+"=config")++ configsResult, err := dockerClient.ConfigList(ctx, dockerclient.ConfigListOptions{Filters: filters})+ if err != nil {+ return fmt.Errorf("failed to list stack configs: %w", err)+ }++ for _, cfg := range configsResult.Items {+ if _, ok := desiredNames[cfg.Spec.Name]; ok {+ continue+ }+ if _, err := dockerClient.ConfigRemove(ctx, cfg.ID, dockerclient.ConfigRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {+ if isStaleSwarmResourceStillInUse(err) {+ continue+ }+ return fmt.Errorf("failed to remove stale stack config %s: %w", cfg.Spec.Name, err)+ }+ }++ return nil+}++func cleanupStaleSecrets(ctx context.Context, dockerClient *dockerclient.Client, stackName string, desiredNames map[string]struct{}) error {+ filters := make(dockerclient.Filters)+ filters.Add("label", fmt.Sprintf("%s=%s", swarmtypes.StackNamespaceLabel, stackName))+ filters.Add("label", resourceTypeLabel+"=secret")++ secretsResult, err := dockerClient.SecretList(ctx, dockerclient.SecretListOptions{Filters: filters})+ if err != nil {+ return fmt.Errorf("failed to list stack secrets: %w", err)+ }++ for _, secret := range secretsResult.Items {+ if _, ok := desiredNames[secret.Spec.Name]; ok {+ continue+ }+ if _, err := dockerClient.SecretRemove(ctx, secret.ID, dockerclient.SecretRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {+ if isStaleSwarmResourceStillInUse(err) {+ continue+ }+ return fmt.Errorf("failed to remove stale stack secret %s: %w", secret.Spec.Name, err)+ }+ }++ return nil+}++func isStaleSwarmResourceStillInUse(err error) bool {+ if cerrdefs.IsConflict(err) {+ return true+ }++ message := strings.ToLower(err.Error())+ return strings.Contains(message, "in use")+}diff --git a/backend/pkg/libarcane/swarm/stack_deploy_engine_test.go b/backend/pkg/libarcane/swarm/stack_deploy_engine_test.gonew file mode 100644index 000000000..b01bfc6b0--- /dev/null+++ b/backend/pkg/libarcane/swarm/stack_deploy_engine_test.go@@ -0,0 +1,24 @@+package swarm++import (+ "path/filepath"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestResolvePathWithinWorkingDirInternal_AllowsPathsWithinWorkingDir(t *testing.T) {+ workingDir := filepath.Join(string(filepath.Separator), "tmp", "stack")++ path, err := resolvePathWithinWorkingDirInternal(workingDir, filepath.Join("configs", "app.env"))+ require.NoError(t, err)+ require.Equal(t, filepath.Join(workingDir, "configs", "app.env"), path)+}++func TestResolvePathWithinWorkingDirInternal_RejectsEscapingPaths(t *testing.T) {+ workingDir := filepath.Join(string(filepath.Separator), "tmp", "stack")++ _, err := resolvePathWithinWorkingDirInternal(workingDir, filepath.Join("..", "..", "etc", "shadow"))+ require.Error(t, err)+ require.Contains(t, err.Error(), "escapes the working directory")+}diff --git a/backend/pkg/projects/fs_templates.go b/backend/pkg/projects/fs_templates.goindex 17ea68869..f1682161e 100644--- a/backend/pkg/projects/fs_templates.go+++ b/backend/pkg/projects/fs_templates.go@@ -92,6 +92,8 @@ func EnsureDefaultTemplates(ctx context.Context) error {}composePath := filepath.Join(templatesDir, ".compose.template")+ swarmStackPath := filepath.Join(templatesDir, ".swarm-stack.template")+ swarmStackEnvPath := filepath.Join(templatesDir, ".swarm-stack.env.template")envPath := filepath.Join(templatesDir, ".env.template")// Write default compose template if it doesn't exist@@ -101,6 +103,20 @@ func EnsureDefaultTemplates(ctx context.Context) error {}}+ // Write default swarm stack template if it doesn't exist+ if _, err := os.Stat(swarmStackPath); os.IsNotExist(err) {+ if err := WriteTemplateFile(swarmStackPath, DefaultSwarmStackTemplate()); err != nil {+ return fmt.Errorf("write default swarm stack template: %w", err)+ }+ }++ // Write default swarm stack env template if it doesn't exist+ if _, err := os.Stat(swarmStackEnvPath); os.IsNotExist(err) {+ if err := WriteTemplateFile(swarmStackEnvPath, DefaultSwarmStackEnvTemplate()); err != nil {+ return fmt.Errorf("write default swarm stack env template: %w", err)+ }+ }+// Write default env template if it doesn't existif _, err := os.Stat(envPath); os.IsNotExist(err) {if err := WriteTemplateFile(envPath, getDefaultEnvTemplate()); err != nil {@@ -130,6 +146,72 @@ volumes:`}+func DefaultSwarmStackTemplate() string {+ return `services:+ web:+ image: ${STACK_WEB_IMAGE:-nginx}:${STACK_WEB_TAG:-alpine}+ ports:+ - target: 80+ published: ${STACK_WEB_PUBLISHED_PORT:-8080}+ protocol: tcp+ mode: ingress+ deploy:+ mode: replicated+ replicas: ${STACK_WEB_REPLICAS:-2}+ update_config:+ parallelism: ${STACK_UPDATE_PARALLELISM:-1}+ delay: ${STACK_UPDATE_DELAY:-10s}+ order: start-first+ rollback_config:+ parallelism: ${STACK_ROLLBACK_PARALLELISM:-1}+ delay: ${STACK_ROLLBACK_DELAY:-5s}+ order: stop-first+ restart_policy:+ condition: on-failure+ delay: ${STACK_RESTART_DELAY:-5s}+ networks:+ - web++networks:+ web:+ driver: overlay+ name: ${STACK_OVERLAY_NETWORK:-web}+`+}++func DefaultSwarmStackEnvTemplate() string {+ return `# Docker Swarm stack variables+# These values are interpolated into the stack file before deployment.+# Example syntax in compose.yaml:+# image: ${STACK_WEB_IMAGE:-nginx}:${STACK_WEB_TAG:-alpine}+# replicas: ${STACK_WEB_REPLICAS:-2}++# Service image+STACK_WEB_IMAGE=nginx+STACK_WEB_TAG=alpine++# Published ingress port for the web service+STACK_WEB_PUBLISHED_PORT=8080++# Replica count for deploy.mode=replicated+STACK_WEB_REPLICAS=2++# Actual Docker overlay network name created for the stack+STACK_OVERLAY_NETWORK=web++# Rolling update behavior+STACK_UPDATE_PARALLELISM=1+STACK_UPDATE_DELAY=10s++# Rollback behavior+STACK_ROLLBACK_PARALLELISM=1+STACK_ROLLBACK_DELAY=5s++# Restart policy+STACK_RESTART_DELAY=5s+`+}+func getDefaultEnvTemplate() string {return `# Environment Variables# These variables will be available to your project servicesdiff --git a/backend/pkg/projects/fs_util.go b/backend/pkg/projects/fs_util.goindex fddc5308a..6de6081e9 100644--- a/backend/pkg/projects/fs_util.go+++ b/backend/pkg/projects/fs_util.go@@ -11,20 +11,24 @@ import (pkgutils "github.com/getarcaneapp/arcane/backend/pkg/utils")-func GetProjectsDirectory(ctx context.Context, projectsDir string) (string, error) {- projectsDirectory := projectsDir- if projectsDirectory == "" {- projectsDirectory = "/app/data/projects"+func ResolveConfiguredContainerDirectory(configuredPath, defaultPath string) string {+ directory := strings.TrimSpace(configuredPath)+ if directory == "" {+ directory = defaultPath}// Handle mapping format: "container_path:host_path"- if parts := strings.SplitN(projectsDirectory, ":", 2); len(parts) == 2 {- if !IsWindowsDrivePath(projectsDirectory) && strings.HasPrefix(parts[0], "/") { // First part must be absolute container path- projectsDirectory = parts[0]+ if parts := strings.SplitN(directory, ":", 2); len(parts) == 2 {+ if !IsWindowsDrivePath(directory) && strings.HasPrefix(parts[0], "/") {+ directory = parts[0]}}- projectsDirectory = resolveProjectsDirectoryPath(projectsDirectory)+ return resolveProjectsDirectoryPath(directory)+}++func GetProjectsDirectory(ctx context.Context, projectsDir string) (string, error) {+ projectsDirectory := ResolveConfiguredContainerDirectory(projectsDir, "/app/data/projects")if _, err := os.Stat(projectsDirectory); os.IsNotExist(err) {if err := os.MkdirAll(projectsDirectory, pkgutils.DirPerm); err != nil {diff --git a/backend/pkg/projects/fs_util_test.go b/backend/pkg/projects/fs_util_test.goindex 60d960390..2d4872a6f 100644--- a/backend/pkg/projects/fs_util_test.go+++ b/backend/pkg/projects/fs_util_test.go@@ -39,3 +39,28 @@ func TestGetProjectsDirectory_ResolvesRelativePathFromBackendWorkingDirectory(trequire.NoError(t, err)assert.Equal(t, filepath.Join(backendRoot, "data", "projects"), resolved)}++func TestResolveConfiguredContainerDirectory(t *testing.T) {+ t.Run("uses default when empty", func(t *testing.T) {+ got := ResolveConfiguredContainerDirectory("", "/app/data/swarm/sources")+ assert.Equal(t, "/app/data/swarm/sources", got)+ })++ t.Run("preserves plain absolute path", func(t *testing.T) {+ got := ResolveConfiguredContainerDirectory("/app/data/custom/stacks", "/app/data/swarm/sources")+ assert.Equal(t, "/app/data/custom/stacks", got)+ })++ t.Run("extracts container path from bind mapping", func(t *testing.T) {+ got := ResolveConfiguredContainerDirectory("/app/data/swarm/sources:/srv/arcane/swarm", "/app/data/swarm/sources")+ assert.Equal(t, "/app/data/swarm/sources", got)+ })++ t.Run("normalizes relative path", func(t *testing.T) {+ cwd := t.TempDir()+ t.Chdir(cwd)++ got := ResolveConfiguredContainerDirectory("data/swarm/sources", "/app/data/swarm/sources")+ assert.Equal(t, filepath.Join(cwd, "data", "swarm", "sources"), got)+ })+}diff --git a/backend/resources/migrations/postgres/043_add_hidden_swarm_node_agents.down.sql b/backend/resources/migrations/postgres/043_add_hidden_swarm_node_agents.down.sqlnew file mode 100644index 000000000..2c64f302b--- /dev/null+++ b/backend/resources/migrations/postgres/043_add_hidden_swarm_node_agents.down.sql@@ -0,0 +1,8 @@+DROP INDEX IF EXISTS idx_environments_parent_swarm_node;+DROP INDEX IF EXISTS idx_environments_swarm_node_id;+DROP INDEX IF EXISTS idx_environments_parent_environment_id;+DROP INDEX IF EXISTS idx_environments_hidden;++ALTER TABLE environments DROP COLUMN swarm_node_id;+ALTER TABLE environments DROP COLUMN parent_environment_id;+ALTER TABLE environments DROP COLUMN hidden;diff --git a/backend/resources/migrations/postgres/043_add_hidden_swarm_node_agents.up.sql b/backend/resources/migrations/postgres/043_add_hidden_swarm_node_agents.up.sqlnew file mode 100644index 000000000..05162ea43--- /dev/null+++ b/backend/resources/migrations/postgres/043_add_hidden_swarm_node_agents.up.sql@@ -0,0 +1,8 @@+ALTER TABLE environments ADD COLUMN hidden BOOLEAN NOT NULL DEFAULT false;+ALTER TABLE environments ADD COLUMN parent_environment_id TEXT;+ALTER TABLE environments ADD COLUMN swarm_node_id TEXT;++CREATE INDEX IF NOT EXISTS idx_environments_hidden ON environments(hidden);+CREATE INDEX IF NOT EXISTS idx_environments_parent_environment_id ON environments(parent_environment_id);+CREATE INDEX IF NOT EXISTS idx_environments_swarm_node_id ON environments(swarm_node_id);+CREATE INDEX IF NOT EXISTS idx_environments_parent_swarm_node ON environments(parent_environment_id, swarm_node_id);diff --git a/backend/resources/migrations/sqlite/043_add_hidden_swarm_node_agents.down.sql b/backend/resources/migrations/sqlite/043_add_hidden_swarm_node_agents.down.sqlnew file mode 100644index 000000000..2c64f302b--- /dev/null+++ b/backend/resources/migrations/sqlite/043_add_hidden_swarm_node_agents.down.sql@@ -0,0 +1,8 @@+DROP INDEX IF EXISTS idx_environments_parent_swarm_node;+DROP INDEX IF EXISTS idx_environments_swarm_node_id;+DROP INDEX IF EXISTS idx_environments_parent_environment_id;+DROP INDEX IF EXISTS idx_environments_hidden;++ALTER TABLE environments DROP COLUMN swarm_node_id;+ALTER TABLE environments DROP COLUMN parent_environment_id;+ALTER TABLE environments DROP COLUMN hidden;diff --git a/backend/resources/migrations/sqlite/043_add_hidden_swarm_node_agents.up.sql b/backend/resources/migrations/sqlite/043_add_hidden_swarm_node_agents.up.sqlnew file mode 100644index 000000000..1669437d6--- /dev/null+++ b/backend/resources/migrations/sqlite/043_add_hidden_swarm_node_agents.up.sql@@ -0,0 +1,8 @@+ALTER TABLE environments ADD COLUMN hidden INTEGER NOT NULL DEFAULT 0;+ALTER TABLE environments ADD COLUMN parent_environment_id TEXT;+ALTER TABLE environments ADD COLUMN swarm_node_id TEXT;++CREATE INDEX IF NOT EXISTS idx_environments_hidden ON environments(hidden);+CREATE INDEX IF NOT EXISTS idx_environments_parent_environment_id ON environments(parent_environment_id);+CREATE INDEX IF NOT EXISTS idx_environments_swarm_node_id ON environments(swarm_node_id);+CREATE INDEX IF NOT EXISTS idx_environments_parent_swarm_node ON environments(parent_environment_id, swarm_node_id);diff --git a/frontend/messages/de.json b/frontend/messages/de.jsonindex c50bed511..dfdcb2015 100644--- a/frontend/messages/de.json+++ b/frontend/messages/de.json@@ -68,6 +68,9 @@"common_gateway": "Gateway","common_driver_required": "Treiber ist erforderlich","common_command": "Befehl",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "Prozessoren","common_basic": "Basis","common_architecture": "Architektur",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Möchtest du das Netzwerk {name} wirklich entfernen?","networks_remove_failed": "Netzwerk {name} konnte nicht entfernt werden","networks_remove_success": "Netzwerk {name} erfolgreich entfernt",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJEKTE (COMPOSE) ===","projects_title": "Projekte","projects_col_provider": "Anbieter",diff --git a/frontend/messages/el.json b/frontend/messages/el.jsonindex 2ffe8a760..208d6a507 100644--- a/frontend/messages/el.json+++ b/frontend/messages/el.json@@ -68,6 +68,9 @@"common_gateway": "Πύλη","common_driver_required": "Απαιτείται οδηγός","common_command": "Εντολή",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "Επεξεργαστές","common_basic": "Βασικό","common_architecture": "Αρχιτεκτονική",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Are you sure you want to remove network {name}?","networks_remove_failed": "Failed to remove network {name}","networks_remove_success": "Network {name} removed successfully",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "Projects","projects_col_provider": "Πάροχος",diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex cc9ca3cd2..109fb138a 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -44,6 +44,7 @@"common_status": "Status","common_driver": "Driver","common_created": "Created",+ "common_updated": "Updated","common_in_use": "In Use","common_unused": "Unused","common_total": "Total",@@ -68,6 +69,9 @@"common_gateway": "Gateway","common_driver_required": "Driver is required","common_command": "Command",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPUs","common_basic": "Basic","common_architecture": "Architecture",@@ -129,6 +133,10 @@"common_loading": "Loading…","common_enabled": "Enabled","common_disabled": "Disabled",+ "common_available": "Available",+ "common_unavailable": "Unavailable",+ "common_click_to_select": "Click to select",+ "common_anonymous": "(anonymous)","common_error": "Error","common_enable": "Enable","common_disable": "Disable",@@ -789,6 +797,251 @@"networks_remove_confirm_message": "Are you sure you want to remove network {name}?","networks_remove_failed": "Failed to remove network {name}","networks_remove_success": "Network {name} removed successfully",+ "_comment_swarm": "=== SWARM ===",+ "swarm_title": "Swarm",+ "swarm_services_title": "Services",+ "swarm_services_subtitle": "Manage your Swarm services",+ "swarm_services_total": "Total Services",+ "swarm_service_create_title": "Create Service",+ "swarm_service_create_description": "Create a new Docker Swarm service with a name and image.",+ "swarm_service_form_basic_info": "Service Configuration",+ "swarm_service_form_image_label": "Container Image",+ "swarm_service_form_image_placeholder": "nginx:latest",+ "swarm_service_form_image_required": "Image is required",+ "swarm_service_form_ports": "Ports",+ "swarm_service_form_env_vars": "Environment Variables",+ "swarm_service_form_mounts": "Mounts",+ "swarm_service_form_labels": "Labels",+ "swarm_service_form_advanced": "Advanced Options",+ "swarm_service_form_add_port": "Add Port",+ "swarm_service_form_add_variable": "Add Variable",+ "swarm_service_form_add_mount": "Add Mount",+ "swarm_service_form_add_label": "Add Label",+ "swarm_service_form_command": "Command",+ "swarm_service_form_arguments": "Arguments",+ "swarm_service_form_working_dir": "Working Directory",+ "swarm_service_form_user": "User",+ "swarm_service_form_name_placeholder": "my-service",+ "swarm_service_form_target_port_placeholder": "8080",+ "swarm_service_form_published_port_placeholder": "80",+ "swarm_service_form_protocol_tcp": "TCP",+ "swarm_service_form_protocol_udp": "UDP",+ "swarm_service_form_env_key_placeholder": "KEY",+ "swarm_service_form_key_placeholder": "key",+ "swarm_service_form_value_placeholder": "value",+ "swarm_service_form_mount_type_volume": "Volume",+ "swarm_service_form_mount_type_bind": "Bind",+ "swarm_service_form_source_placeholder": "source",+ "swarm_service_form_target_placeholder": "/target",+ "swarm_service_form_command_placeholder": "/bin/sh",+ "swarm_service_form_arguments_placeholder": "-c echo hello",+ "swarm_service_form_working_dir_placeholder": "/app",+ "swarm_service_form_user_placeholder": "1000:1000",+ "swarm_service_form_hostname_placeholder": "my-service",+ "swarm_service_mode_replicated": "Replicated",+ "swarm_service_mode_global": "Global",+ "swarm_service_replica_singular": "replica",+ "swarm_service_replica_plural": "replicas",+ "swarm_service_env_var": "ENV_VAR",+ "swarm_service_update_status": "Update Status",+ "swarm_service_storage_mount_bind": "bind mount",+ "swarm_service_storage_mount_tmpfs": "tmpfs mount",+ "swarm_service_storage_mount_volume_bind_backed": "volume (bind-backed)",+ "swarm_service_storage_mount_volume": "volume mount",+ "swarm_service_storage_tmpfs": "tmpfs",+ "swarm_service_storage_device": "Device:",+ "swarm_service_storage_volume_path": "Volume Path:",+ "swarm_service_network_config_from": "config: {name}",+ "swarm_service_network_virtual_ip": "Virtual IP",+ "swarm_service_network_id": "Network ID",+ "swarm_service_network_parent": "parent: {name}",+ "swarm_service_network_ipv4": "IPv4",+ "swarm_service_network_ipv6": "IPv6",+ "swarm_service_network_range": "Range",+ "swarm_service_edit_title": "Edit Service",+ "swarm_service_edit_description": "Update the service spec JSON for {name}.",+ "swarm_service_delete_confirm": "Are you sure you want to delete service {name}?",+ "swarm_service_spec_label": "Service Spec (JSON)",+ "swarm_service_spec_description": "Paste a Docker Swarm ServiceSpec JSON payload.",+ "swarm_service_options_label": "Service Options (JSON, optional)",+ "swarm_service_options_description": "Optional create/update options for the service.",+ "swarm_service_spec_required": "Service spec JSON is required",+ "swarm_service_json_invalid": "Invalid JSON: {error}",+ "swarm_service_options_invalid": "Options JSON is invalid: {error}",+ "swarm_nodes_title": "Nodes",+ "swarm_nodes_subtitle": "Manage your Swarm nodes",+ "swarm_nodes_total": "Total Nodes",+ "swarm_tasks_title": "Tasks",+ "swarm_tasks_subtitle": "Monitor Swarm tasks",+ "swarm_tasks_total": "Total Tasks",+ "swarm_stacks_title": "Stacks",+ "swarm_stacks_subtitle": "View deployed Swarm stacks",+ "swarm_stacks_total": "Total Stacks",+ "swarm_mode": "Mode",+ "swarm_replicas": "Replicas",+ "swarm_stack": "Stack",+ "swarm_hostname": "Hostname",+ "swarm_availability": "Availability",+ "swarm_engine_version": "Engine Version",+ "swarm_service": "Service",+ "swarm_node": "Node",+ "swarm_node_agent_column": "Agent",+ "swarm_current_state": "Current State",+ "swarm_desired_state": "Desired State",+ "swarm_nodes_column": "Nodes",+ "swarm_networks": "Networks",+ "swarm_full_name": "Full Name",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs",+ "swarm_service_scale": "Scale",+ "swarm_service_scale_success": "Scaled \"{name}\" to {replicas} replicas",+ "swarm_tasks_subtitle_node_scoped": "Monitor Swarm tasks (node scoped)",+ "swarm_cluster_title": "Cluster",+ "swarm_cluster_subtitle": "Lifecycle and security operations",+ "swarm_cluster_stat_cluster": "Cluster",+ "swarm_cluster_stat_tokens": "Tokens",+ "swarm_cluster_stat_unlock_key": "Unlock Key",+ "swarm_cluster_not_initialized": "Not initialized",+ "swarm_cluster_status_title": "Cluster Status",+ "swarm_cluster_status_subtitle": "Current swarm state and metadata",+ "swarm_cluster_id_label": "Cluster ID",+ "swarm_cluster_join_tokens_title": "Join Tokens",+ "swarm_cluster_join_tokens_subtitle": "Manager and worker enrollment tokens",+ "swarm_cluster_manager_token_label": "Manager",+ "swarm_cluster_worker_token_label": "Worker",+ "swarm_cluster_rotate_tokens": "Rotate Tokens",+ "swarm_cluster_initialize_title": "Initialize Cluster",+ "swarm_cluster_initialize_subtitle": "Initialize swarm on this engine",+ "swarm_cluster_initialize_action": "Initialize",+ "swarm_cluster_join_title": "Join Existing Cluster",+ "swarm_cluster_join_subtitle": "Attach this engine to a manager",+ "swarm_cluster_join_action": "Join",+ "swarm_cluster_initialized_title": "Cluster Already Initialized",+ "swarm_cluster_initialized_subtitle": "This engine is already a swarm member.",+ "swarm_cluster_initialized_notice": "Initialization and join are hidden while swarm is active. Use Leave Cluster first if you need to reinitialize or join another cluster.",+ "swarm_cluster_unlock_leave_title": "Unlock / Leave",+ "swarm_cluster_unlock_leave_subtitle": "Security unlock and cluster detach",+ "swarm_cluster_unlock_action": "Unlock",+ "swarm_cluster_force_leave": "Force leave",+ "swarm_cluster_leave_action": "Leave Cluster",+ "swarm_cluster_update_spec_title": "Update Swarm Spec",+ "swarm_cluster_update_spec_subtitle": "Apply changes to cluster scheduling and security settings",+ "swarm_cluster_update_spec_action": "Update Spec",+ "swarm_cluster_load_current_spec": "Load current spec",+ "swarm_cluster_rotate_worker_token": "Rotate worker token",+ "swarm_cluster_rotate_manager_token": "Rotate manager token",+ "swarm_cluster_rotate_unlock_key": "Rotate unlock key",+ "swarm_cluster_listen_addr_placeholder": "Listen address (optional)",+ "swarm_cluster_advertise_addr_placeholder": "Advertise address (optional)",+ "swarm_cluster_spec_placeholder": "Swarm spec JSON",+ "swarm_cluster_auto_lock_managers": "Auto-lock managers",+ "swarm_cluster_force_new_cluster": "Force new cluster",+ "swarm_cluster_join_remote_addrs_placeholder": "Remote manager addrs (comma separated)",+ "swarm_cluster_join_token_placeholder": "Join token",+ "swarm_cluster_unlock_key_placeholder": "Unlock key",+ "swarm_cluster_version_placeholder": "Version (optional)",+ "swarm_cluster_init_spec_label": "Init spec",+ "swarm_cluster_spec_label": "Swarm spec",+ "swarm_cluster_json_object_error": "{label} must be a JSON object",+ "swarm_cluster_json_invalid_error": "{label} is not valid JSON",+ "swarm_cluster_join_required_error": "Remote address and join token are required",+ "swarm_cluster_unlock_key_required": "Unlock key is required",+ "swarm_cluster_init_failed": "Failed to initialize swarm",+ "swarm_cluster_init_success": "Swarm initialized",+ "swarm_cluster_join_failed": "Failed to join swarm",+ "swarm_cluster_join_success": "Joined swarm",+ "swarm_cluster_leave_failed": "Failed to leave swarm",+ "swarm_cluster_leave_success": "Left swarm",+ "swarm_cluster_unlock_failed": "Failed to unlock swarm",+ "swarm_cluster_unlock_success": "Swarm unlocked",+ "swarm_cluster_rotate_tokens_failed": "Failed to rotate join tokens",+ "swarm_cluster_rotate_tokens_success": "Join tokens rotated",+ "swarm_cluster_update_spec_failed": "Failed to update swarm spec",+ "swarm_cluster_update_spec_success": "Swarm spec updated",+ "swarm_config": "config",+ "swarm_secret": "secret",+ "swarm_configs_title": "Configs",+ "swarm_configs_subtitle": "Manage cluster config objects",+ "swarm_configs_create_title": "Create Config",+ "swarm_configs_create_subtitle": "Create a swarm config with name and data",+ "swarm_configs_create_button": "Create Config",+ "swarm_configs_list_title": "Existing Configs",+ "swarm_configs_list_subtitle": "Select one to edit or remove",+ "swarm_configs_edit_title": "Edit Config",+ "swarm_configs_name_placeholder": "Config name",+ "swarm_configs_data_placeholder": "Config data",+ "swarm_configs_update_button": "Update Config",+ "swarm_configs_delete_button": "Delete Config",+ "swarm_configs_empty": "No configs found.",+ "swarm_configs_immutable_notice": "Swarm configs are immutable. Create a new config and update services to use it instead.",+ "swarm_configs_name_required": "Config name is required",+ "swarm_configs_delete_confirm": "Delete config \"{name}\"?",+ "swarm_configs_create_failed": "Failed to create config",+ "swarm_configs_create_success": "Config \"{name}\" created",+ "swarm_configs_update_failed": "Failed to update config \"{name}\"",+ "swarm_configs_update_success": "Config \"{name}\" updated",+ "swarm_configs_delete_failed": "Failed to delete config \"{name}\"",+ "swarm_configs_delete_success": "Config \"{name}\" deleted",+ "swarm_secrets_title": "Secrets",+ "swarm_secrets_subtitle": "Manage cluster secret objects",+ "swarm_secrets_create_title": "Create Secret",+ "swarm_secrets_create_subtitle": "Create a swarm secret with name and data",+ "swarm_secrets_create_button": "Create Secret",+ "swarm_secrets_list_title": "Existing Secrets",+ "swarm_secrets_list_subtitle": "Select one to edit or remove",+ "swarm_secrets_edit_title": "Edit Secret",+ "swarm_secrets_name_placeholder": "Secret name",+ "swarm_secrets_data_placeholder": "Secret data",+ "swarm_secrets_update_button": "Update Secret",+ "swarm_secrets_delete_button": "Delete Secret",+ "swarm_secrets_empty": "No secrets found.",+ "swarm_secrets_immutable_notice": "Swarm secrets are immutable. Create a new secret and update services to use it instead.",+ "swarm_secrets_name_required": "Secret name is required",+ "swarm_secrets_delete_confirm": "Delete secret \"{name}\"?",+ "swarm_secrets_create_failed": "Failed to create secret",+ "swarm_secrets_create_success": "Secret \"{name}\" created",+ "swarm_secrets_update_failed": "Failed to update secret \"{name}\"",+ "swarm_secrets_update_success": "Secret \"{name}\" updated",+ "swarm_secrets_delete_failed": "Failed to delete secret \"{name}\"",+ "swarm_secrets_delete_success": "Secret \"{name}\" deleted",+ "swarm_stack_namespace": "Namespace: {namespace}",+ "swarm_node_promote": "Promote",+ "swarm_node_demote": "Demote",+ "swarm_node_drain": "Drain",+ "swarm_node_activate": "Activate",+ "swarm_node_agent_deploy": "Deploy Agent",+ "swarm_node_agent_view": "View Agent",+ "swarm_node_agent_dialog_title": "Node Agent: {name}",+ "swarm_node_agent_dialog_description": "Generate or review the Arcane agent install commands for this Swarm node, then refresh the status after deployment.",+ "swarm_node_agent_dialog_blurb_title": "Node-local coverage",+ "swarm_node_agent_dialog_blurb_description": "Arcane needs an agent on each Swarm node before it can manage that node's local containers, images, volumes, and networks.",+ "swarm_node_agent_warning_title": "Some Swarm nodes are missing verified agent coverage",+ "swarm_node_agent_warning_description": "{count} node(s) are not connected to Arcane yet. Deploy the agent on each node to unlock node-local resource management across the cluster.",+ "swarm_node_agent_status_none": "Not deployed",+ "swarm_node_agent_status_pending": "Pending",+ "swarm_node_agent_status_offline": "Offline",+ "swarm_node_agent_status_connected": "Connected",+ "swarm_node_agent_status_mismatched": "Mismatched",+ "swarm_node_agent_environment_id": "Agent Environment ID",+ "swarm_node_agent_refresh_status": "Refresh Status",+ "swarm_node_update_failed": "Failed to update node \"{name}\"",+ "swarm_node_promote_success": "Node \"{name}\" promoted to manager",+ "swarm_node_promote_failed": "Failed to promote node \"{name}\"",+ "swarm_node_demote_success": "Node \"{name}\" demoted to worker",+ "swarm_node_demote_failed": "Failed to demote node \"{name}\"",+ "swarm_node_remove_success": "Node \"{name}\" removed",+ "swarm_node_remove_failed": "Failed to remove node \"{name}\"",+ "swarm_node_availability_update_success": "Node \"{name}\" set to {availability}",+ "swarm_service_tasks_count": "{count} task(s) for this service",+ "swarm_service_tasks_loading": "Loading tasks...",+ "swarm_service_tasks_empty": "No tasks found for this service",+ "swarm_service_tasks_load_failed_log": "Failed to load tasks","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "Projects","projects_col_provider": "Provider",diff --git a/frontend/messages/eo.json b/frontend/messages/eo.jsonindex e6cb37309..fe200c74b 100644--- a/frontend/messages/eo.json+++ b/frontend/messages/eo.json@@ -68,6 +68,9 @@"common_gateway": "Kluzo","common_driver_required": "Pelilo bezonata","common_command": "Komando",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "Ĉefprocesoroj","common_basic": "Baza","common_architecture": "Arkitekturo",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Ĉu vi certas, ke vi volas forigi reton «{name}»?","networks_remove_failed": "Malsukcesis forigi reton «{name}»","networks_remove_success": "Reto «{name}» estis sukcese forigita",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJEKTOJ (COMPOSE) ===","projects_title": "Projektoj","projects_col_provider": "Provizanto",diff --git a/frontend/messages/es.json b/frontend/messages/es.jsonindex 5eb620484..52415e0eb 100644--- a/frontend/messages/es.json+++ b/frontend/messages/es.json@@ -68,6 +68,9 @@"common_gateway": "Pasarela","common_driver_required": "El conductor es obligatorio","common_command": "Comando",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPUs","common_basic": "Básico","common_architecture": "Arquitectura",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "¿Estás seguro de que quieres eliminar la red {name}?","networks_remove_failed": "Error al eliminar la red {name}","networks_remove_success": "Red {name} eliminada con éxito",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTOS (COMPOSE) ===","projects_title": "Proyectos","projects_col_provider": "Proveedor",diff --git a/frontend/messages/fr.json b/frontend/messages/fr.jsonindex 4ad891434..9b56d7f4a 100644--- a/frontend/messages/fr.json+++ b/frontend/messages/fr.json@@ -68,6 +68,9 @@"common_gateway": "Passerelle","common_driver_required": "Le chauffeur est requis","common_command": "Commandes",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "Processeurs","common_basic": "Basique","common_architecture": "Architecture",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Êtes-vous sûr de vouloir supprimer le réseau {name}?","networks_remove_failed": "Impossible de supprimer le réseau {name}","networks_remove_success": "Réseau {name} supprimé avec succès",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJETS (COMPOSE) ===","projects_title": "Projets","projects_col_provider": "Fournisseur",diff --git a/frontend/messages/it.json b/frontend/messages/it.jsonindex a049763f2..8ab8f99a9 100644--- a/frontend/messages/it.json+++ b/frontend/messages/it.json@@ -68,6 +68,9 @@"common_gateway": "Gateway","common_driver_required": "Il driver è obbligatorio","common_command": "Comando",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPU","common_basic": "Base","common_architecture": "Architettura",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Are you sure you want to remove network {name}?","networks_remove_failed": "Failed to remove network {name}","networks_remove_success": "Network {name} removed successfully",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "Progetti","projects_col_provider": "Provider",diff --git a/frontend/messages/ja.json b/frontend/messages/ja.jsonindex 72ff084a6..24421a9bc 100644--- a/frontend/messages/ja.json+++ b/frontend/messages/ja.json@@ -68,6 +68,9 @@"common_gateway": "Gateway","common_driver_required": "Driver is required","common_command": "Command",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPUs","common_basic": "Basic","common_architecture": "Architecture",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Are you sure you want to remove network {name}?","networks_remove_failed": "Failed to remove network {name}","networks_remove_success": "Network {name} removed successfully",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "Projects","projects_col_provider": "プロバイダー",diff --git a/frontend/messages/ko.json b/frontend/messages/ko.jsonindex bfc7bc7b4..a3a80bf32 100644--- a/frontend/messages/ko.json+++ b/frontend/messages/ko.json@@ -68,6 +68,9 @@"common_gateway": "게이트웨이","common_driver_required": "드라이버가 필요합니다","common_command": "명령(Command)",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPU","common_basic": "기본","common_architecture": "아키텍처",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "네트워크 {name}을(를) 제거하시겠습니까?","networks_remove_failed": "네트워크 {name} 제거 실패","networks_remove_success": "네트워크 {name} 제거 완료",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "프로젝트","projects_col_provider": "유형",diff --git a/frontend/messages/nl.json b/frontend/messages/nl.jsonindex 2fc3c25d2..a7e2d019b 100644--- a/frontend/messages/nl.json+++ b/frontend/messages/nl.json@@ -68,6 +68,9 @@"common_gateway": "Gateway","common_driver_required": "Chauffeur is vereist","common_command": "Opdracht",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPU's","common_basic": "Eenvoudig","common_architecture": "Architectuur",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Weet u zeker dat u netwerk {name} wilt verwijderen?","networks_remove_failed": "Kan netwerk {name} niet verwijderen","networks_remove_success": "Netwerk {name} succesvol verwijderd",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "Projecten","projects_col_provider": "Provider",diff --git a/frontend/messages/pt-BR.json b/frontend/messages/pt-BR.jsonindex 8adb03cf0..e78cc5053 100644--- a/frontend/messages/pt-BR.json+++ b/frontend/messages/pt-BR.json@@ -68,6 +68,9 @@"common_gateway": "Gateway","common_driver_required": "Requer driver","common_command": "Comando",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "Processadores","common_basic": "Básico","common_architecture": "Arquitetura",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Deseja mesmo remover a rede {name}?","networks_remove_failed": "Falha ao remover a rede \"{name}\"","networks_remove_success": "Network {name} removed successfully",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJETOS (COMPOSE) ===","projects_title": "Projetos","projects_col_provider": "Fornecedor",diff --git a/frontend/messages/pt.json b/frontend/messages/pt.jsonindex 9f980e6e1..a108df104 100644--- a/frontend/messages/pt.json+++ b/frontend/messages/pt.json@@ -44,6 +44,9 @@"common_gateway": "Gateway","common_driver_required": "Requer driver","common_command": "Comando",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "Processadores","common_basic": "Básico","common_architecture": "Arquitetura",@@ -577,6 +580,14 @@"networks_remove_confirm_message": "Are you sure you want to remove network {name}?","networks_remove_failed": "Failed to remove network {name}","networks_remove_success": "Network {name} removed successfully",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "Projects","compose_subtitle": "View and Manage Compose Projects",diff --git a/frontend/messages/ru.json b/frontend/messages/ru.jsonindex 96698df0b..8c8f02994 100644--- a/frontend/messages/ru.json+++ b/frontend/messages/ru.json@@ -68,6 +68,9 @@"common_gateway": "Шлюз","common_driver_required": "Требуется драйвер","common_command": "Команды",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPUs","common_basic": "Основной","common_architecture": "Архитектура",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Вы уверены, что хотите удалить сеть {name}?","networks_remove_failed": "Не удалось удалить сеть {name}","networks_remove_success": "Сеть {name} успешно удалена",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "Проекты","projects_col_provider": "Поставщик",diff --git a/frontend/messages/sv.json b/frontend/messages/sv.jsonindex dc1c90841..3a84783d8 100644--- a/frontend/messages/sv.json+++ b/frontend/messages/sv.json@@ -68,6 +68,9 @@"common_gateway": "Gateway","common_driver_required": "Drivrutin krävs","common_command": "Command",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPUs","common_basic": "Basic","common_architecture": "Architecture",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Are you sure you want to remove network {name}?","networks_remove_failed": "Failed to remove network {name}","networks_remove_success": "Network {name} removed successfully",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "Projects","projects_col_provider": "Leverantör",diff --git a/frontend/messages/uk.json b/frontend/messages/uk.jsonindex 0c6727374..078dc2a2a 100644--- a/frontend/messages/uk.json+++ b/frontend/messages/uk.json@@ -68,6 +68,9 @@"common_gateway": "Gateway","common_driver_required": "Driver is required","common_command": "Command",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPUs","common_basic": "Basic","common_architecture": "Architecture",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Are you sure you want to remove network {name}?","networks_remove_failed": "Failed to remove network {name}","networks_remove_success": "Network {name} removed successfully",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "Projects","projects_col_provider": "Provider",diff --git a/frontend/messages/vi.json b/frontend/messages/vi.jsonindex 233bb30f4..2497a62c4 100644--- a/frontend/messages/vi.json+++ b/frontend/messages/vi.json@@ -68,6 +68,9 @@"common_gateway": "Gateway","common_driver_required": "Yêu cầu cần có Driver","common_command": "Command",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPUs","common_basic": "Cơ bản","common_architecture": "Kiến trúc",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "Bạn có chắc chắn muốn gỡ bỏ Network {name}?","networks_remove_failed": "Gỡ bỏ Network {name} thất bại","networks_remove_success": "Đã gỡ bỏ Network {name} thành công",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "Projects","projects_col_provider": "Nhà cung cấp",diff --git a/frontend/messages/zh-CN.json b/frontend/messages/zh-CN.jsonindex 3747d4f11..ee7ba2c49 100644--- a/frontend/messages/zh-CN.json+++ b/frontend/messages/zh-CN.json@@ -68,6 +68,9 @@"common_gateway": "网关","common_driver_required": "需要驱动程序","common_command": "命令",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPU","common_basic": "基础","common_architecture": "结构",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "您确定要移除网络“{name}”吗?","networks_remove_failed": "移除网络{name}失败","networks_remove_success": "移除网络{name}成功",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== 项目 (编排) ===","projects_title": "项目","projects_col_provider": "来源",diff --git a/frontend/messages/zh-TW.json b/frontend/messages/zh-TW.jsonindex 474feb933..b57e354a2 100644--- a/frontend/messages/zh-TW.json+++ b/frontend/messages/zh-TW.json@@ -68,6 +68,9 @@"common_gateway": "閘道","common_driver_required": "驅動為必填欄位","common_command": "命令",+ "common_args": "Arguments",+ "common_advanced": "Advanced",+ "common_version": "Version","common_cpus": "CPUs","common_basic": "基本","common_architecture": "架構",@@ -789,6 +792,14 @@"networks_remove_confirm_message": "確定要移除 {name} 網路?","networks_remove_failed": "移除 {name} 網路時失敗","networks_remove_success": "{name} 網路移除成功",+ "swarm_n_more": "+{count} more",+ "swarm_service_rollback": "Rollback",+ "swarm_service_rollback_title": "Rollback Service",+ "swarm_service_rollback_confirm": "Are you sure you want to rollback service \"{name}\" to its previous configuration?",+ "swarm_service_rollback_success": "Rollback initiated for \"{name}\"",+ "swarm_service_rollback_failed": "Failed to rollback service \"{name}\"",+ "swarm_service_view_tasks": "Tasks",+ "swarm_service_logs_title": "Service Logs","_comment_projects": "=== PROJECTS (COMPOSE) ===","projects_title": "專案","projects_col_provider": "提供者",diff --git a/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelte b/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelteindex 311b77011..bc3ece014 100644--- a/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelte+++ b/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { type Table as TableType, type Cell } from '@tanstack/table-core';+ import { type Table as TableType, type Cell, type Row } from '@tanstack/table-core';import * as Table from '$lib/components/ui/table/index.js';import * as Empty from '$lib/components/ui/empty/index.js';import FlexRender from '$lib/components/ui/data-table/flex-render.svelte';@@ -8,7 +8,10 @@import { cn } from '$lib/utils';import type { ColumnWidth, ColumnAlign, GroupedData, GroupSelectionState } from './arcane-table.types.svelte.ts';import TableCheckbox from './arcane-table-checkbox.svelte';- import type { Component } from 'svelte';+ import type { Component, Snippet } from 'svelte';+ import { slide } from 'svelte/transition';++ void slide;let {table,@@ -22,7 +25,10 @@getGroupSelectionState,onToggleGroupSelection,onToggleRowSelection,- unstyled = false+ unstyled = false,+ expandedRowContent,+ expandedRows,+ onToggleRowExpanded}: {table: TableType<any>;selectedIds: string[];@@ -36,8 +42,13 @@onToggleGroupSelection?: (groupItems: any[]) => void;onToggleRowSelection?: (id: string, selected: boolean) => void;unstyled?: boolean;+ expandedRowContent?: Snippet<[{ row: Row<any>; item: any }]>;+ expandedRows?: Set<string>;+ onToggleRowExpanded?: (rowId: string) => void;} = $props();+ const hasExpand = $derived(!!expandedRowContent);+// Get column width class from metafunction getWidthClass(width?: ColumnWidth): string {if (!width || width === 'auto') return '';@@ -64,7 +75,12 @@}function handleRowClick(event: MouseEvent, rowId: string) {- if (selectionDisabled || shouldIgnoreRowClick(event)) return;+ if (shouldIgnoreRowClick(event)) return;+ if (hasExpand) {+ onToggleRowExpanded?.(rowId);+ return;+ }+ if (selectionDisabled) return;const isSelected = (selectedIds ?? []).includes(rowId);onToggleRowSelection?.(rowId, !isSelected);}@@ -103,6 +119,9 @@<Table.Header>{#each table.getHeaderGroups() as headerGroup (headerGroup.id)}<Table.Row>+ {#if hasExpand}+ <Table.Head class="w-8 px-2"></Table.Head>+ {/if}{#each headerGroup.headers as header (header.id)}<Table.Headcolspan={header.colSpan}@@ -166,10 +185,27 @@{#if !isCollapsed}{#each groupRows as row (row.id)}{@const rowId = (row.original as any).id}+ {@const isExpanded = expandedRows?.has(rowId) ?? false}<Table.Rowdata-state={(selectedIds ?? []).includes(rowId) && 'selected'}onclick={(event) => handleRowClick(event, rowId)}+ class={cn(hasExpand && 'cursor-pointer', isExpanded && 'bg-primary/15')}>+ {#if hasExpand}+ <Table.Cell class="w-8 px-2" data-row-select-ignore>+ <button+ class="text-muted-foreground hover:text-foreground flex items-center justify-center transition-transform duration-200"+ class:rotate-90={isExpanded}+ onclick={(e) => {+ e.stopPropagation();+ onToggleRowExpanded?.(rowId);+ }}+ aria-label={isExpanded ? 'Collapse row' : 'Expand row'}+ >+ <ArrowRightIcon class="size-4" />+ </button>+ </Table.Cell>+ {/if}{#each row.getVisibleCells() as cell, cellIndex (cell.id)}{@const isFirstDataCell = !selectionDisabled ? cellIndex === 1 : cellIndex === 0}<Table.Cell class={getCellClasses(cell, true, isFirstDataCell)}>@@ -190,6 +226,18 @@</Table.Cell>{/each}</Table.Row>++ {#if hasExpand && isExpanded && expandedRowContent}+ <Table.Row class="bg-primary/10 hover:bg-primary/10">+ <Table.Cell colspan={columnsCount} class="p-0">+ <div transition:slide={{ duration: 200 }}>+ <div class="px-6 py-4">+ {@render expandedRowContent({ row, item: row.original })}+ </div>+ </div>+ </Table.Cell>+ </Table.Row>+ {/if}{/each}{/if}{/each}@@ -215,10 +263,27 @@{:else}{#each table.getRowModel().rows as row (row.id)}{@const rowId = (row.original as any).id}+ {@const isExpanded = expandedRows?.has(rowId) ?? false}<Table.Rowdata-state={(selectedIds ?? []).includes(rowId) && 'selected'}onclick={(event) => handleRowClick(event, rowId)}+ class={cn(hasExpand && 'cursor-pointer', isExpanded && 'bg-primary/15')}>+ {#if hasExpand}+ <Table.Cell class="w-8 px-2" data-row-select-ignore>+ <button+ class="text-muted-foreground hover:text-foreground flex items-center justify-center transition-transform duration-200"+ class:rotate-90={isExpanded}+ onclick={(e) => {+ e.stopPropagation();+ onToggleRowExpanded?.(rowId);+ }}+ aria-label={isExpanded ? 'Collapse row' : 'Expand row'}+ >+ <ArrowRightIcon class="size-4" />+ </button>+ </Table.Cell>+ {/if}{#each row.getVisibleCells() as cell (cell.id)}<Table.Cell class={getCellClasses(cell, false, false)}>{#if cell.column.id === 'actions'}@@ -238,6 +303,18 @@</Table.Cell>{/each}</Table.Row>++ {#if hasExpand && isExpanded && expandedRowContent}+ <Table.Row class="bg-primary/10 hover:bg-primary/10">+ <Table.Cell colspan={columnsCount} class="p-0">+ <div transition:slide={{ duration: 200 }}>+ <div class="px-6 py-4">+ {@render expandedRowContent({ row, item: row.original })}+ </div>+ </div>+ </Table.Cell>+ </Table.Row>+ {/if}{:else}<Table.Row><Table.Cell colspan={columnsCount} class="h-48">diff --git a/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelte b/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelteindex 120cf04d0..474f6316f 100644--- a/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelte+++ b/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { type Table as TableType } from '@tanstack/table-core';+ import { type Table as TableType, type Row } from '@tanstack/table-core';import * as Empty from '$lib/components/ui/empty/index.js';import DropdownCard from '$lib/components/dropdown-card.svelte';import { FolderXIcon } from '$lib/icons';@@ -7,6 +7,9 @@import { cn } from '$lib/utils';import type { Snippet, Component } from 'svelte';import type { GroupedData } from './arcane-table.types.svelte.ts';+ import { slide } from 'svelte/transition';++ void slide;let {table,@@ -14,7 +17,10 @@mobileFieldVisibility,groupedRows = null,groupIcon,- unstyled = false+ unstyled = false,+ expandedRowContent,+ expandedRows,+ onToggleRowExpanded}: {table: TableType<any>;mobileCard: Snippet<[{ row: any; item: any; mobileFieldVisibility: Record<string, boolean> }]>;@@ -22,8 +28,23 @@groupedRows?: GroupedData<any>[] | null;groupIcon?: (groupName: string) => Component;unstyled?: boolean;+ expandedRowContent?: Snippet<[{ row: Row<any>; item: any }]>;+ expandedRows?: Set<string>;+ onToggleRowExpanded?: (rowId: string) => void;} = $props();+ const hasExpand = $derived(!!expandedRowContent);++ function shouldIgnoreRowClick(event: MouseEvent): boolean {+ const target = event.target as HTMLElement | null;+ return !!target?.closest('a, button, input, [role="checkbox"], [data-slot="checkbox"], [data-row-select-ignore]');+ }++ function handleRowClick(event: MouseEvent, rowId: string) {+ if (shouldIgnoreRowClick(event)) return;+ if (hasExpand) onToggleRowExpanded?.(rowId);+ }+// Get rows for a specific group from the table modelfunction getRowsForGroup(groupItems: any[]) {const groupIds = new Set(groupItems.map((item) => item.id));@@ -49,7 +70,18 @@><div class="divide-border/30 divide-y">{#each groupRows as row (row.id)}- {@render mobileCard({ row, item: row.original as any, mobileFieldVisibility })}+ {@const rowId = (row.original as any).id}+ {@const isExpanded = expandedRows?.has(rowId) ?? false}+ <!-- svelte-ignore a11y_click_events_have_key_events -->+ <!-- svelte-ignore a11y_no_static_element_interactions -->+ <div class={cn(hasExpand && 'cursor-pointer')} onclick={(e) => handleRowClick(e, rowId)}>+ {@render mobileCard({ row, item: row.original as any, mobileFieldVisibility })}+ </div>+ {#if hasExpand && isExpanded && expandedRowContent}+ <div class="bg-muted/30 px-4 py-3" transition:slide={{ duration: 200 }}>+ {@render expandedRowContent({ row, item: row.original })}+ </div>+ {/if}{:else}<div class="text-muted-foreground flex h-24 items-center justify-center text-center">{m.common_no_results_found()}@@ -79,7 +111,18 @@{:else}<!-- Non-grouped view (original behavior) -->{#each table.getRowModel().rows as row (row.id)}- {@render mobileCard({ row, item: row.original as any, mobileFieldVisibility })}+ {@const rowId = (row.original as any).id}+ {@const isExpanded = expandedRows?.has(rowId) ?? false}+ <!-- svelte-ignore a11y_click_events_have_key_events -->+ <!-- svelte-ignore a11y_no_static_element_interactions -->+ <div class={cn(hasExpand && 'cursor-pointer')} onclick={(e) => handleRowClick(e, rowId)}>+ {@render mobileCard({ row, item: row.original as any, mobileFieldVisibility })}+ </div>+ {#if hasExpand && isExpanded && expandedRowContent}+ <div class="bg-muted/30 px-4 py-3" transition:slide={{ duration: 200 }}>+ {@render expandedRowContent({ row, item: row.original })}+ </div>+ {/if}{:else}<div class="p-4"><Empty.Rootdiff --git a/frontend/src/lib/components/arcane-table/arcane-table.svelte b/frontend/src/lib/components/arcane-table/arcane-table.svelteindex 3860c66ce..2d9b642f9 100644--- a/frontend/src/lib/components/arcane-table/arcane-table.svelte+++ b/frontend/src/lib/components/arcane-table/arcane-table.svelte@@ -67,7 +67,9 @@groupIcon,groupCollapsedState = $bindable<Record<string, boolean>>({}),onGroupToggle,- imageNameFilterOptions+ imageNameFilterOptions,+ // Expandable row props+ expandedRowContent}: {items: Paginated<TData>;requestOptions: SearchPaginationSortRequest;@@ -105,6 +107,8 @@groupCollapsedState?: Record<string, boolean>;onGroupToggle?: (groupName: string) => void;imageNameFilterOptions?: string[];+ // Expandable row props+ expandedRowContent?: Snippet<[{ row: Row<TData>; item: TData }]>;} = $props();// Default page size constant@@ -113,12 +117,25 @@let rowSelection = $state<RowSelectionState>({});let columnFilters = $state<ColumnFiltersState>([]);let sorting = $state<SortingState>([]);- let globalFilter = $state<string>('');+ let globalFilter = $state<string>(requestOptions?.search ?? '');const enablePersist = $derived(!!persistKey);const getEffectiveLimit = () => requestOptions?.pagination?.limit ?? items?.pagination?.itemsPerPage ?? DEFAULT_LIMIT;let prefs = $state<PersistedState<CompactTablePrefs> | null>(null);+ // Expandable row state+ let expandedRows = $state<Set<string>>(new Set());++ function toggleRowExpanded(rowId: string) {+ const next = new Set(expandedRows);+ if (next.has(rowId)) {+ next.delete(rowId);+ } else {+ next.add(rowId);+ }+ expandedRows = next;+ }+const passAllGlobal: (row: unknown, columnId: string, filterValue: unknown) => boolean = () => true;const currentPage = $derived(items.pagination?.currentPage ?? requestOptions?.pagination?.page ?? 1);@@ -171,22 +188,15 @@const persistedSearch = snapshot.search;const currentSearch = (requestOptions?.search ?? '').trim();- if (persistedSearch !== globalFilter) {- globalFilter = persistedSearch;+ // Incoming requestOptions.search (e.g. from URL param) takes priority over persisted state+ const effectiveSearch = currentSearch || persistedSearch;+ if (effectiveSearch !== globalFilter) {+ globalFilter = effectiveSearch;}- if (persistedSearch) {- if (persistedSearch !== currentSearch) {- requestOptions = {- ...requestOptions,- search: persistedSearch,- pagination: { page: 1, limit: requestOptions?.pagination?.limit ?? getEffectiveLimit() }- };- shouldRefresh = true;- }- } else if (currentSearch) {+ if (effectiveSearch !== currentSearch) {requestOptions = {...requestOptions,- search: undefined,+ search: effectiveSearch || undefined,pagination: { page: 1, limit: requestOptions?.pagination?.limit ?? getEffectiveLimit() }};shouldRefresh = true;@@ -387,6 +397,9 @@const columnsDef = $derived(cachedColumnsDef.length > 0 ? cachedColumnsDef : buildColumns(columns, selectionDisabled));+ // Compute effective column count (add 1 for expand chevron column when expandable)+ const effectiveColumnsCount = $derived(columnsDef.length + (expandedRowContent ? 1 : 0));+const table = createSvelteTable({get data() {return items.data ?? [];@@ -662,7 +675,7 @@<ArcaneTableDesktopView{table}{selectedIds}- columnsCount={columnsDef.length}+ columnsCount={effectiveColumnsCount}groupedRows={effectiveGroupedRows}{groupIcon}{groupCollapsedState}@@ -672,6 +685,9 @@{onToggleGroupSelection}onToggleRowSelection={(id, selected) => onToggleRow(selected, id)}{unstyled}+ {expandedRowContent}+ {expandedRows}+ onToggleRowExpanded={toggleRowExpanded}/></div>@@ -684,6 +700,9 @@groupedRows={effectiveGroupedRows}{groupIcon}{unstyled}+ {expandedRowContent}+ {expandedRows}+ onToggleRowExpanded={toggleRowExpanded}/></div></div>@@ -716,7 +735,7 @@<ArcaneTableDesktopView{table}{selectedIds}- columnsCount={columnsDef.length}+ columnsCount={effectiveColumnsCount}groupedRows={effectiveGroupedRows}{groupIcon}{groupCollapsedState}@@ -725,11 +744,23 @@{getGroupSelectionState}{onToggleGroupSelection}onToggleRowSelection={(id, selected) => onToggleRow(selected, id)}+ {expandedRowContent}+ {expandedRows}+ onToggleRowExpanded={toggleRowExpanded}/></div><div class="block flex-1 overflow-auto md:hidden">- <ArcaneTableMobileView {table} {mobileCard} {mobileFieldVisibility} groupedRows={effectiveGroupedRows} {groupIcon} />+ <ArcaneTableMobileView+ {table}+ {mobileCard}+ {mobileFieldVisibility}+ groupedRows={effectiveGroupedRows}+ {groupIcon}+ {expandedRowContent}+ {expandedRows}+ onToggleRowExpanded={toggleRowExpanded}+ /></div>{#if !withoutPagination}diff --git a/frontend/src/lib/components/dialogs/create-service-dialog.svelte b/frontend/src/lib/components/dialogs/create-service-dialog.sveltenew file mode 100644index 000000000..03c5c4863--- /dev/null+++ b/frontend/src/lib/components/dialogs/create-service-dialog.svelte@@ -0,0 +1,374 @@+<script lang="ts">+ import { ResponsiveDialog } from '$lib/components/ui/responsive-dialog/index.js';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { Input } from '$lib/components/ui/input/index.js';+ import * as Select from '$lib/components/ui/select/index.js';+ import { z } from 'zod/v4';+ import { createForm, preventDefault } from '$lib/utils/form.utils';+ import { m } from '$lib/paraglide/messages';+ import { AddIcon, TrashIcon } from '$lib/icons';+ import * as Accordion from '$lib/components/ui/accordion/index.js';+ import FormInput from '$lib/components/form/form-input.svelte';+ import type { SwarmServiceCreateSpec } from '$lib/types/swarm.type';++ type CreateServiceDialogProps = {+ open: boolean;+ onSubmit: (spec: SwarmServiceCreateSpec) => void;+ isLoading: boolean;+ };++ let { open = $bindable(false), onSubmit, isLoading }: CreateServiceDialogProps = $props();++ const formSchema = z.object({+ name: z.string().min(1, m.common_name_required()),+ image: z.string().min(1, m.swarm_service_form_image_required()),+ replicas: z.coerce.number().int().min(0).default(1)+ });++ const formData = {+ name: '',+ image: '',+ replicas: 1+ };++ let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));+ let mode = $state<'replicated' | 'global'>('replicated');+ let command = $state({ value: '', error: '' });+ let args = $state({ value: '', error: '' });+ let workingDir = $state({ value: '', error: '' });+ let user = $state({ value: '', error: '' });+ let hostname = $state({ value: '', error: '' });+ let ports = $state<Array<{ target: string; published: string; protocol: 'tcp' | 'udp' }>>([]);+ let envVars = $state<Array<{ key: string; value: string }>>([]);+ let mounts = $state<Array<{ type: 'volume' | 'bind'; source: string; target: string }>>([]);+ let labels = $state<Array<{ key: string; value: string }>>([]);++ function addPort() {+ ports = [...ports, { target: '', published: '', protocol: 'tcp' }];+ }++ function removePort(index: number) {+ ports = ports.filter((_, i) => i !== index);+ }++ function addEnvVar() {+ envVars = [...envVars, { key: '', value: '' }];+ }++ function removeEnvVar(index: number) {+ envVars = envVars.filter((_, i) => i !== index);+ }++ function addMount() {+ mounts = [...mounts, { type: 'volume', source: '', target: '' }];+ }++ function removeMount(index: number) {+ mounts = mounts.filter((_, i) => i !== index);+ }++ function addLabel() {+ labels = [...labels, { key: '', value: '' }];+ }++ function removeLabel(index: number) {+ labels = labels.filter((_, i) => i !== index);+ }++ function handleSubmit() {+ const validated = form.validate();+ if (!validated) return;++ const { name, image, replicas } = validated;++ const spec: SwarmServiceCreateSpec = {+ Name: name,+ TaskTemplate: {+ ContainerSpec: {+ Image: image+ }+ },+ Mode: mode === 'replicated' ? { Replicated: { Replicas: replicas } } : { Global: {} }+ };++ // Add optional container config+ if (command.value.trim()) {+ spec.TaskTemplate.ContainerSpec.Command = command.value.trim().split(' ').filter(Boolean);+ }+ if (args.value.trim()) {+ spec.TaskTemplate.ContainerSpec.Args = args.value.trim().split(' ').filter(Boolean);+ }+ if (workingDir.value.trim()) {+ spec.TaskTemplate.ContainerSpec.Dir = workingDir.value.trim();+ }+ if (user.value.trim()) {+ spec.TaskTemplate.ContainerSpec.User = user.value.trim();+ }+ if (hostname.value.trim()) {+ spec.TaskTemplate.ContainerSpec.Hostname = hostname.value.trim();+ }++ // Add environment variables+ if (envVars.length > 0) {+ const filtered = envVars.filter((e) => e.key.trim());+ if (filtered.length > 0) {+ spec.TaskTemplate.ContainerSpec.Env = filtered.map((e) => `${e.key}=${e.value}`);+ }+ }++ // Add mounts+ if (mounts.length > 0) {+ const filtered = mounts.filter((m) => m.source.trim() && m.target.trim());+ if (filtered.length > 0) {+ spec.TaskTemplate.ContainerSpec.Mounts = filtered.map((m) => ({+ Type: m.type,+ Source: m.source,+ Target: m.target+ }));+ }+ }++ // Add labels+ if (labels.length > 0) {+ const filtered = labels.filter((l) => l.key.trim());+ if (filtered.length > 0) {+ const labelsRecord: Record<string, string> = {};+ filtered.forEach((l) => {+ labelsRecord[l.key] = l.value;+ });+ spec.Labels = labelsRecord;+ }+ }++ // Add ports+ if (ports.length > 0) {+ const filtered = ports.filter((p) => p.target.trim());+ if (filtered.length > 0) {+ spec.EndpointSpec = {+ Ports: filtered.map((p) => ({+ TargetPort: parseInt(p.target),+ PublishedPort: p.published ? parseInt(p.published) : undefined,+ Protocol: p.protocol+ }))+ };+ }+ }++ onSubmit(spec);+ }++ function handleOpenChange(newOpenState: boolean) {+ open = newOpenState;+ if (!newOpenState) {+ form.reset();+ mode = 'replicated';+ command.value = '';+ args.value = '';+ workingDir.value = '';+ user.value = '';+ hostname.value = '';+ ports = [];+ envVars = [];+ mounts = [];+ labels = [];+ }+ }+</script>++<ResponsiveDialog+ {open}+ onOpenChange={handleOpenChange}+ variant="sheet"+ title={m.swarm_service_create_title()}+ description={m.swarm_service_create_description()}+ contentClass="sm:max-w-[600px]"+>+ {#snippet children()}+ <form onsubmit={preventDefault(handleSubmit)} class="space-y-6 py-4">+ <!-- Basic Config -->+ <div class="space-y-4">+ <FormInput input={$inputs.name} label={m.common_name()} placeholder="my-service" disabled={isLoading} />+ <FormInput+ input={$inputs.image}+ label={m.swarm_service_form_image_label()}+ placeholder={m.swarm_service_form_image_placeholder()}+ disabled={isLoading}+ />+ </div>++ <div class="grid grid-cols-2 gap-4">+ <FormInput label={m.swarm_mode()}>+ {#snippet children()}+ <Select.Root type="single" bind:value={mode} disabled={isLoading}>+ <Select.Trigger class="w-full">+ <span class="capitalize"+ >{mode === 'replicated' ? m.swarm_service_mode_replicated() : m.swarm_service_mode_global()}</span+ >+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="replicated" label={m.swarm_service_mode_replicated()}+ >{m.swarm_service_mode_replicated()}</Select.Item+ >+ <Select.Item value="global" label={m.swarm_service_mode_global()}>{m.swarm_service_mode_global()}</Select.Item>+ </Select.Content>+ </Select.Root>+ {/snippet}+ </FormInput>++ {#if mode === 'replicated'}+ <FormInput input={$inputs.replicas} label={m.swarm_replicas()} type="number" disabled={isLoading} />+ {/if}+ </div>++ <Accordion.Root class="w-full space-y-5" type="multiple">+ <Accordion.Item value="ports">+ <Accordion.Trigger class="text-sm font-medium">{m.swarm_service_form_ports()}</Accordion.Trigger>+ <Accordion.Content class="pt-6 pb-5">+ <div class="space-y-4">+ {#each ports as port, i (i)}+ <div class="flex items-center gap-4">+ <Input placeholder="8080" bind:value={port.target} disabled={isLoading} class="flex-1" />+ <span class="text-muted-foreground">:</span>+ <Input placeholder="80" bind:value={port.published} disabled={isLoading} class="flex-1" />+ <Select.Root type="single" bind:value={port.protocol} disabled={isLoading}>+ <Select.Trigger class="w-20">+ <span class="uppercase">{port.protocol}</span>+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="tcp" label="TCP">TCP</Select.Item>+ <Select.Item value="udp" label="UDP">UDP</Select.Item>+ </Select.Content>+ </Select.Root>+ <ArcaneButton action="remove" size="sm" onclick={() => removePort(i)} disabled={isLoading} icon={TrashIcon} />+ </div>+ {/each}+ <ArcaneButton+ action="create"+ size="sm"+ onclick={addPort}+ disabled={isLoading}+ icon={AddIcon}+ customLabel={m.swarm_service_form_add_port()}+ />+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <Accordion.Item value="env">+ <Accordion.Trigger class="text-sm font-medium">{m.swarm_service_form_env_vars()}</Accordion.Trigger>+ <Accordion.Content class="pt-6 pb-5">+ <div class="space-y-4">+ {#each envVars as env, i (i)}+ <div class="flex items-center gap-4">+ <Input placeholder="KEY" bind:value={env.key} disabled={isLoading} class="flex-1" />+ <span class="text-muted-foreground">=</span>+ <Input placeholder="value" bind:value={env.value} disabled={isLoading} class="flex-1" />+ <ArcaneButton action="remove" size="sm" onclick={() => removeEnvVar(i)} disabled={isLoading} icon={TrashIcon} />+ </div>+ {/each}+ <ArcaneButton+ action="create"+ size="sm"+ onclick={addEnvVar}+ disabled={isLoading}+ icon={AddIcon}+ customLabel={m.swarm_service_form_add_variable()}+ />+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <Accordion.Item value="mounts">+ <Accordion.Trigger class="text-sm font-medium">{m.swarm_service_form_mounts()}</Accordion.Trigger>+ <Accordion.Content class="pt-6 pb-5">+ <div class="space-y-4">+ {#each mounts as mount, i (i)}+ <div class="flex items-center gap-4">+ <Select.Root type="single" bind:value={mount.type} disabled={isLoading}>+ <Select.Trigger class="w-24">+ <span class="capitalize">{mount.type}</span>+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="volume" label="Volume">Volume</Select.Item>+ <Select.Item value="bind" label="Bind">Bind</Select.Item>+ </Select.Content>+ </Select.Root>+ <Input placeholder="source" bind:value={mount.source} disabled={isLoading} class="flex-1" />+ <span class="text-muted-foreground">→</span>+ <Input placeholder="/target" bind:value={mount.target} disabled={isLoading} class="flex-1" />+ <ArcaneButton action="remove" size="sm" onclick={() => removeMount(i)} disabled={isLoading} icon={TrashIcon} />+ </div>+ {/each}+ <ArcaneButton+ action="create"+ size="sm"+ onclick={addMount}+ disabled={isLoading}+ icon={AddIcon}+ customLabel={m.swarm_service_form_add_mount()}+ />+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <Accordion.Item value="labels">+ <Accordion.Trigger class="text-sm font-medium">{m.swarm_service_form_labels()}</Accordion.Trigger>+ <Accordion.Content class="pt-6 pb-5">+ <div class="space-y-4">+ {#each labels as label, i (i)}+ <div class="flex items-center gap-4">+ <Input placeholder="key" bind:value={label.key} disabled={isLoading} class="flex-1" />+ <span class="text-muted-foreground">=</span>+ <Input placeholder="value" bind:value={label.value} disabled={isLoading} class="flex-1" />+ <ArcaneButton action="remove" size="sm" onclick={() => removeLabel(i)} disabled={isLoading} icon={TrashIcon} />+ </div>+ {/each}+ <ArcaneButton+ action="create"+ size="sm"+ onclick={addLabel}+ disabled={isLoading}+ icon={AddIcon}+ customLabel={m.swarm_service_form_add_label()}+ />+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <Accordion.Item value="advanced">+ <Accordion.Trigger class="text-sm font-medium">{m.swarm_service_form_advanced()}</Accordion.Trigger>+ <Accordion.Content class="pt-6 pb-5">+ <div class="space-y-5">+ <FormInput input={command} label={m.swarm_service_form_command()} placeholder="/bin/sh" disabled={isLoading} />+ <FormInput input={args} label={m.swarm_service_form_arguments()} placeholder="-c echo hello" disabled={isLoading} />+ <FormInput input={workingDir} label={m.swarm_service_form_working_dir()} placeholder="/app" disabled={isLoading} />+ <FormInput input={user} label={m.swarm_service_form_user()} placeholder="1000:1000" disabled={isLoading} />+ <FormInput input={hostname} label={m.swarm_hostname()} placeholder="my-service" disabled={isLoading} />+ </div>+ </Accordion.Content>+ </Accordion.Item>+ </Accordion.Root>+ </form>+ {/snippet}++ {#snippet footer()}+ <div class="flex w-full flex-row gap-2">+ <ArcaneButton+ action="cancel"+ tone="ghost"+ type="button"+ class="flex-1"+ onclick={() => (open = false)}+ disabled={isLoading}+ />+ <ArcaneButton+ action="create"+ type="button"+ class="flex-1"+ disabled={isLoading}+ loading={isLoading}+ onclick={handleSubmit}+ />+ </div>+ {/snippet}+</ResponsiveDialog>diff --git a/frontend/src/lib/components/logs/log-viewer.svelte b/frontend/src/lib/components/logs/log-viewer.svelteindex 0e4daf93d..4ab370b19 100644--- a/frontend/src/lib/components/logs/log-viewer.svelte+++ b/frontend/src/lib/components/logs/log-viewer.svelte@@ -22,7 +22,8 @@class?: string;containerId?: string | null;projectId?: string | null;- type?: 'container' | 'project';+ serviceId?: string | null;+ type?: 'container' | 'project' | 'service';maxLines?: number;autoScroll?: boolean;showTimestamps?: boolean;@@ -39,6 +40,7 @@class: className,containerId = null,projectId = null,+ serviceId = null,type = 'container',maxLines = 1000,autoScroll = $bindable(true),@@ -152,11 +154,12 @@let streamSession = 0;let currentStreamSession = 0;function streamKey() {- return type === 'project' ? (projectId ? `project:${projectId}` : null) : containerId ? `ctr:${containerId}` : null;+ if (type === 'project') return projectId ? `project:${projectId}` : null;+ if (type === 'service') return serviceId ? `svc:${serviceId}` : null;+ return containerId ? `ctr:${containerId}` : null;}- const humanType = $derived(type === 'project' ? m.project() : m.container());- const selectedTargetId = $derived(type === 'project' ? projectId : containerId);+ const humanType = $derived(type === 'project' ? m.project() : type === 'service' ? m.swarm_service() : m.container());const fillParent = $derived(height === '100%');const minHeight = $derived(height === '100%' ? '0' : '300px');const viewportStyle = $derived(fillParent ? 'min-height: 0;' : `height: ${height}; min-height: ${minHeight};`);@@ -171,12 +174,14 @@const basePath =type === 'project'? `/api/environments/${envId}/ws/projects/${projectId}/logs`- : `/api/environments/${envId}/ws/containers/${containerId}/logs`;+ : type === 'service'+ ? `/api/environments/${envId}/ws/swarm/services/${serviceId}/logs`+ : `/api/environments/${envId}/ws/containers/${containerId}/logs`;return buildWebSocketEndpoint(`${basePath}?follow=true&tail=${tailLines}×tamps=true&format=json&batched=true`);}export async function startLogStream() {- const targetId = type === 'project' ? projectId : containerId;+ const targetId = type === 'project' ? projectId : type === 'service' ? serviceId : containerId;if (!targetId) {error = type === 'project' ? m.log_stream_no_project_selected() : m.log_stream_no_container_selected();@@ -534,7 +539,7 @@>{#if displayLogs.length === 0}<div class="p-4 text-center text-gray-500">- {#if !selectedTargetId}+ {#if !(containerId || projectId || serviceId)}{m.log_viewer_no_selection({ type: humanType })}{:else if !isStreaming}{m.log_viewer_no_logs_available()}diff --git a/frontend/src/lib/components/logs/log-viewer.utils.ts b/frontend/src/lib/components/logs/log-viewer.utils.tsindex f1dbd9076..5ef7c47ce 100644--- a/frontend/src/lib/components/logs/log-viewer.utils.ts+++ b/frontend/src/lib/components/logs/log-viewer.utils.ts@@ -23,7 +23,7 @@ export function buildLogDisplayEntries(logs: LogViewerEntry[],options: {groupAdjacentLines?: boolean;- type: 'container' | 'project';+ type: 'container' | 'project' | 'service';}): LogViewerDisplayEntry[] {if (!options.groupAdjacentLines || options.type !== 'container') {diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelteindex afc142021..7d247545e 100644--- a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte+++ b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte@@ -22,11 +22,13 @@open = $bindable(false),user = null,versionInformation,+ swarmEnabled = false,debug = false}: {open: boolean;user?: any;versionInformation?: AppVersionInformation;+ swarmEnabled?: boolean;debug?: boolean;} = $props();@@ -248,6 +250,34 @@</div></section>+ {#if swarmEnabled}+ <section>+ <h4 class="text-muted-foreground/70 mb-4 px-3 text-[11px] font-bold tracking-widest uppercase">+ {m.swarm_title()}+ </h4>+ <div class="space-y-2">+ {#each navigationItems.swarmItems as item}+ {@const IconComponent = item.icon}+ <a+ href={item.url}+ onclick={handleItemClick}+ class={cn(+ 'flex items-center gap-3 rounded-2xl px-4 py-3 text-sm font-medium transition-all duration-200 ease-out',+ 'focus-visible:ring-muted-foreground/50 hover:scale-[1.01] focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:ring-offset-transparent',+ isActiveItem(item)+ ? 'bg-muted text-foreground hover:bg-muted/70 shadow-sm'+ : 'text-foreground hover:bg-muted/50'+ )}+ aria-current={isActiveItem(item) ? 'page' : undefined}+ >+ <IconComponent size={20} />+ <span>{item.title}</span>+ </a>+ {/each}+ </div>+ </section>+ {/if}+{#if isAdmin}{#if navigationItems.settingsItems}<section>diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav.svelteindex 2467dd94e..73957cf98 100644--- a/frontend/src/lib/components/mobile-nav/mobile-nav.svelte+++ b/frontend/src/lib/components/mobile-nav/mobile-nav.svelte@@ -8,6 +8,7 @@import MobileNavSheet from './mobile-nav-sheet.svelte';import { m } from '$lib/paraglide/messages';import { MobileNavGestures } from './gestures.svelte';+ import type { DockerInfo } from '$lib/types/docker-info.type';import './styles.css';import type { AppVersionInformation } from '$lib/types/application-configuration';@@ -15,17 +16,21 @@navigationSettings,user = null,versionInformation,+ dockerInfo = null,class: className = ''}: {navigationSettings: MobileNavigationSettings;user?: any;versionInformation?: AppVersionInformation;+ dockerInfo?: DockerInfo | null;class?: string;} = $props();+ const swarmEnabled = $derived(dockerInfo?.Swarm?.LocalNodeState === 'active');+const pinnedItems = $derived.by(() => {if (!navigationSettings?.pinnedItems) return [];- const availableItems = getAvailableMobileNavItems();+ const availableItems = getAvailableMobileNavItems({ includeSwarm: swarmEnabled });return navigationSettings.pinnedItems.map((url) => availableItems.find((item) => item.url === url)).filter((item) => item !== undefined);@@ -184,4 +189,4 @@{/if}</nav>-<MobileNavSheet bind:open={menuOpen} {user} {versionInformation} />+<MobileNavSheet bind:open={menuOpen} {user} {versionInformation} {swarmEnabled} />diff --git a/frontend/src/lib/components/sidebar/sidebar-itemgroup.svelte b/frontend/src/lib/components/sidebar/sidebar-itemgroup.svelteindex 601792a64..744135fed 100644--- a/frontend/src/lib/components/sidebar/sidebar-itemgroup.svelte+++ b/frontend/src/lib/components/sidebar/sidebar-itemgroup.svelte@@ -76,9 +76,9 @@const shortcutsEnabled = $derived($settingsStore?.keyboardShortcutsEnabled ?? true);</script>-<Sidebar.Group>- <Sidebar.GroupLabel>{label}</Sidebar.GroupLabel>- <Sidebar.Menu>+<Sidebar.Group class="p-1.5">+ <Sidebar.GroupLabel class="h-7 px-1.5">{label}</Sidebar.GroupLabel>+ <Sidebar.Menu class="gap-0.5">{#each enhancedItems as item (item.title)}{#if (item.items?.length ?? 0) > 0}{#if sidebar.state === 'collapsed' && !sidebar.hoverExpansionEnabled}@@ -131,7 +131,7 @@>{#each item.items ?? [] as subItem (subItem.title)}<Sidebar.MenuSubItem>- <Sidebar.MenuSubButton isActive={subItem.isActive}>+ <Sidebar.MenuSubButton isActive={subItem.isActive} size="md">{#snippet child({ props })}{@const SubIcon = subItem.icon}<a href={subItem.url} {...props}>diff --git a/frontend/src/lib/components/sidebar/sidebar.svelte b/frontend/src/lib/components/sidebar/sidebar.svelteindex d6c8519be..fdd4d3da1 100644--- a/frontend/src/lib/components/sidebar/sidebar.svelte+++ b/frontend/src/lib/components/sidebar/sidebar.svelte@@ -12,6 +12,7 @@import type { ComponentProps } from 'svelte';import type { User } from '$lib/types/user.type';import type { AppVersionInformation } from '$lib/types/application-configuration';+ import type { DockerInfo } from '$lib/types/docker-info.type';import SidebarLogo from './sidebar-logo.svelte';import SidebarUpdatebanner from './sidebar-updatebanner.svelte';import SidebarPinButton from './sidebar-pin-button.svelte';@@ -30,10 +31,12 @@variant = 'floating',user,versionInformation,+ dockerInfo = null,...restProps}: ComponentProps<typeof Sidebar.Root> & {versionInformation: AppVersionInformation;user?: User | null;+ dockerInfo?: DockerInfo | null;} = $props();let autoLoginEnabled = $state(false);@@ -64,6 +67,7 @@const currentEnvId = $derived(environmentStore.selected?.id || '0');const buildDeploymentItems = $derived(getBuildAndDeploymentItems(currentEnvId));+ const swarmEnabled = $derived(dockerInfo?.Swarm?.LocalNodeState === 'active');</script><VersionInfoDialog@@ -101,6 +105,9 @@<SidebarItemGroup label={m.sidebar_management()} items={navigationItems.managementItems} /><SidebarItemGroup label={m.sidebar_resources()} items={navigationItems.resourceItems} /><SidebarItemGroup label={m.builds_and_deployments()} items={buildDeploymentItems} />+ {#if swarmEnabled}+ <SidebarItemGroup label={m.swarm_title()} items={navigationItems.swarmItems} />+ {/if}<SidebarItemGroup label={m.security_title()} items={navigationItems.securityItems} />{#if isAdmin}<SidebarItemGroup label={m.sidebar_administration()} items={desktopSettingsItems} />diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-context.ts b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-context.tsnew file mode 100644index 000000000..deaf51177--- /dev/null+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-context.ts@@ -0,0 +1,5 @@+export type DropdownMenuContext = {+ close: () => void;+};++export const dropdownMenuContextKey = Symbol('dropdown-menu');diff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-item.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-item.svelteindex 38bc45bf0..495189f6d 100644--- a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-item.svelte+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-item.svelte@@ -1,17 +1,32 @@<script lang="ts">import { cn } from '$lib/utils.js';import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';+ import { getContext } from 'svelte';+ import { dropdownMenuContextKey, type DropdownMenuContext } from './dropdown-menu-context';let {ref = $bindable(null),class: className,inset,variant = 'default',+ closeOnSelect = true,+ onclick,...restProps}: DropdownMenuPrimitive.ItemProps & {inset?: boolean;variant?: 'default' | 'destructive';+ closeOnSelect?: boolean;+ onclick?: (event: MouseEvent) => void;} = $props();++ const menuContext = getContext<DropdownMenuContext | null>(dropdownMenuContextKey);++ function handleClick(event: MouseEvent) {+ onclick?.(event);+ if (closeOnSelect) {+ menuContext?.close();+ }+ }</script><DropdownMenuPrimitive.Item@@ -19,6 +34,7 @@data-slot="dropdown-menu-item"data-inset={inset}data-variant={variant}+ onclick={handleClick}class={cn("data-highlighted:bg-accent data-highlighted:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:data-highlighted:bg-destructive/10 dark:data-[variant=destructive]:data-highlighted:bg-destructive/20 data-[variant=destructive]:data-highlighted:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",classNamediff --git a/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-root.svelte b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-root.sveltenew file mode 100644index 000000000..6ff6ef561--- /dev/null+++ b/frontend/src/lib/components/ui/dropdown-menu/dropdown-menu-root.svelte@@ -0,0 +1,15 @@+<script lang="ts">+ import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui';+ import { setContext } from 'svelte';+ import { dropdownMenuContextKey } from './dropdown-menu-context';++ let { open = $bindable(false), ...restProps }: DropdownMenuPrimitive.RootProps = $props();++ setContext(dropdownMenuContextKey, {+ close: () => {+ open = false;+ }+ });+</script>++<DropdownMenuPrimitive.Root bind:open {...restProps} />diff --git a/frontend/src/lib/components/ui/dropdown-menu/index.ts b/frontend/src/lib/components/ui/dropdown-menu/index.tsindex aeb398e06..6170f0b37 100644--- a/frontend/src/lib/components/ui/dropdown-menu/index.ts+++ b/frontend/src/lib/components/ui/dropdown-menu/index.ts@@ -12,8 +12,8 @@ import Trigger from './dropdown-menu-trigger.svelte';import SubContent from './dropdown-menu-sub-content.svelte';import SubTrigger from './dropdown-menu-sub-trigger.svelte';import GroupHeading from './dropdown-menu-group-heading.svelte';+import Root from './dropdown-menu-root.svelte';const Sub = DropdownMenuPrimitive.Sub;-const Root = DropdownMenuPrimitive.Root;export {CheckboxItem,diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.tsindex fc69f602e..ef5573bb4 100644--- a/frontend/src/lib/config/navigation-config.ts+++ b/frontend/src/lib/config/navigation-config.ts@@ -1,7 +1,6 @@import {ApiKeyIcon,ApperanceIcon,- JobsIcon,UsersIcon,LockIcon,NotificationsIcon,@@ -13,11 +12,15 @@ import {ImagesIcon,NetworksIcon,VolumesIcon,+ DockIcon,+ JobsIcon,+ LayersIcon,EventsIcon,SettingsIcon,GitBranchIcon,ShieldAlertIcon,- HammerIcon+ HammerIcon,+ TemplateIcon} from '$lib/icons';import { m } from '$lib/paraglide/messages';import type { ShortcutKey } from '$lib/utils/keyboard-shortcut.utils';@@ -34,6 +37,7 @@ export type NavigationSections = {managementItems: NavigationItem[];resourceItems: NavigationItem[];deploymentItems: NavigationItem[];+ swarmItems: NavigationItem[];securityItems: NavigationItem[];settingsItems: NavigationItem[];};@@ -52,6 +56,15 @@ export const navigationItems: NavigationSections = {{ title: m.volumes_title(), url: '/volumes', icon: VolumesIcon, shortcut: ['mod', '8'] }],deploymentItems: [{ title: m.builds(), url: '/images/builds', icon: HammerIcon, shortcut: ['mod', 'b'] }],+ swarmItems: [+ { title: 'Services', url: '/swarm/services', icon: DockIcon },+ { title: 'Nodes', url: '/swarm/nodes', icon: UsersIcon },+ { title: 'Tasks', url: '/swarm/tasks', icon: JobsIcon },+ { title: 'Stacks', url: '/swarm/stacks', icon: LayersIcon },+ { title: 'Cluster', url: '/swarm/cluster', icon: SettingsIcon },+ { title: 'Configs', url: '/swarm/configs', icon: TemplateIcon },+ { title: 'Secrets', url: '/swarm/secrets', icon: LockIcon }+ ],securityItems: [{ title: m.vuln_title(), url: '/security', icon: ShieldAlertIcon, shortcut: ['mod', 's'] }],settingsItems: [{@@ -102,21 +115,36 @@ export type MobileNavigationSettings = {scrollToHide: boolean;};-export function getAvailableMobileNavItems(): NavigationItem[] {- const flatItems: NavigationItem[] = [- ...navigationItems.managementItems,- ...navigationItems.resourceItems,- ...navigationItems.deploymentItems,- ...navigationItems.securityItems- ];+export function getAvailableMobileNavItems(options?: { includeSwarm?: boolean }): NavigationItem[] {+ const flatItems: NavigationItem[] = [];+ if (navigationItems.managementItems) {+ flatItems.push(...navigationItems.managementItems);+ }- const settingsTopLevel = navigationItems.settingsItems.filter((item) => !item.items);- flatItems.push(...settingsTopLevel);+ if (navigationItems.resourceItems) {+ flatItems.push(...navigationItems.resourceItems);+ }- // Also add the main settings item itself if it has children, as it's a valid navigation target- const settingsMain = navigationItems.settingsItems.find((item) => item.items);- if (settingsMain) {- flatItems.push(settingsMain);+ if (navigationItems.deploymentItems) {+ flatItems.push(...navigationItems.deploymentItems);+ }++ if (options?.includeSwarm && navigationItems.swarmItems) {+ flatItems.push(...navigationItems.swarmItems);+ }++ if (navigationItems.securityItems) {+ flatItems.push(...navigationItems.securityItems);+ }++ if (navigationItems.settingsItems) {+ const settingsTopLevel = navigationItems.settingsItems.filter((item) => !item.items);+ flatItems.push(...settingsTopLevel);++ const settingsMain = navigationItems.settingsItems.find((item) => item.items);+ if (settingsMain) {+ flatItems.push(settingsMain);+ }}return flatItems;diff --git a/frontend/src/lib/services/swarm-service.ts b/frontend/src/lib/services/swarm-service.tsnew file mode 100644index 000000000..a7c11bdfb--- /dev/null+++ b/frontend/src/lib/services/swarm-service.ts@@ -0,0 +1,285 @@+import BaseAPIService from './api-service';+import { environmentStore } from '$lib/stores/environment.store.svelte';+import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';+import { transformPaginationParams } from '$lib/utils/params.util';+import type {+ SwarmServiceSummary,+ SwarmNodeSummary,+ SwarmTaskSummary,+ SwarmStackSummary,+ SwarmInfo,+ SwarmNodeAgentDeployment,+ SwarmServiceCreateRequest,+ SwarmServiceUpdateRequest,+ SwarmServiceCreateResponse,+ SwarmServiceUpdateResponse,+ SwarmServiceInspect,+ SwarmStackDeployRequest,+ SwarmStackDeployResponse,+ SwarmServiceScaleRequest,+ SwarmNodeUpdateRequest,+ SwarmStackInspect,+ SwarmStackRenderConfigRequest,+ SwarmStackRenderConfigResponse,+ SwarmStackSource,+ SwarmInitRequest,+ SwarmInitResponse,+ SwarmJoinRequest,+ SwarmLeaveRequest,+ SwarmUnlockRequest,+ SwarmUnlockKeyResponse,+ SwarmJoinTokensResponse,+ SwarmRotateJoinTokensRequest,+ SwarmUpdateRequest,+ SwarmConfigSummary,+ SwarmSecretSummary,+ SwarmConfigCreateRequest,+ SwarmConfigUpdateRequest,+ SwarmSecretCreateRequest,+ SwarmSecretUpdateRequest+} from '$lib/types/swarm.type';++export type SwarmServicesPaginatedResponse = Paginated<SwarmServiceSummary>;+export type SwarmNodesPaginatedResponse = Paginated<SwarmNodeSummary>;+export type SwarmTasksPaginatedResponse = Paginated<SwarmTaskSummary>;+export type SwarmStacksPaginatedResponse = Paginated<SwarmStackSummary>;++export class SwarmService extends BaseAPIService {+ async getServices(options?: SearchPaginationSortRequest): Promise<SwarmServicesPaginatedResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const params = transformPaginationParams(options);+ const res = await this.api.get(`/environments/${envId}/swarm/services`, { params });+ return res.data;+ }++ async getService(serviceId: string): Promise<SwarmServiceInspect> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/services/${serviceId}`));+ }++ async createService(request: SwarmServiceCreateRequest): Promise<SwarmServiceCreateResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/services`, request));+ }++ async updateService(serviceId: string, request: SwarmServiceUpdateRequest): Promise<SwarmServiceUpdateResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.put(`/environments/${envId}/swarm/services/${serviceId}`, request));+ }++ async getServiceTasks(serviceId: string, options?: SearchPaginationSortRequest): Promise<SwarmTasksPaginatedResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const params = transformPaginationParams(options);+ const res = await this.api.get(`/environments/${envId}/swarm/services/${serviceId}/tasks`, { params });+ return res.data;+ }++ async rollbackService(serviceId: string): Promise<SwarmServiceUpdateResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/services/${serviceId}/rollback`, {}));+ }++ async scaleService(serviceId: string, request: SwarmServiceScaleRequest): Promise<SwarmServiceUpdateResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/services/${serviceId}/scale`, request));+ }++ async removeService(serviceId: string): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.delete(`/environments/${envId}/swarm/services/${serviceId}`));+ }++ async getNodes(options?: SearchPaginationSortRequest): Promise<SwarmNodesPaginatedResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const params = transformPaginationParams(options);+ const res = await this.api.get(`/environments/${envId}/swarm/nodes`, { params });+ return res.data;+ }++ async getNode(nodeId: string): Promise<SwarmNodeSummary> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/nodes/${nodeId}`));+ }++ async getNodeAgentDeployment(nodeId: string, rotate = false): Promise<SwarmNodeAgentDeployment> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/nodes/${nodeId}/agent/deployment`, { rotate }));+ }++ async updateNode(nodeId: string, request: SwarmNodeUpdateRequest): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.patch(`/environments/${envId}/swarm/nodes/${nodeId}`, request));+ }++ async removeNode(nodeId: string, force = false): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.delete(`/environments/${envId}/swarm/nodes/${nodeId}`, { params: { force } }));+ }++ async promoteNode(nodeId: string): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.post(`/environments/${envId}/swarm/nodes/${nodeId}/promote`, {}));+ }++ async demoteNode(nodeId: string): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.post(`/environments/${envId}/swarm/nodes/${nodeId}/demote`, {}));+ }++ async getNodeTasks(nodeId: string, options?: SearchPaginationSortRequest): Promise<SwarmTasksPaginatedResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const params = transformPaginationParams(options);+ const res = await this.api.get(`/environments/${envId}/swarm/nodes/${nodeId}/tasks`, { params });+ return res.data;+ }++ async getTasks(options?: SearchPaginationSortRequest): Promise<SwarmTasksPaginatedResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const params = transformPaginationParams(options);+ const res = await this.api.get(`/environments/${envId}/swarm/tasks`, { params });+ return res.data;+ }++ async getStacks(options?: SearchPaginationSortRequest): Promise<SwarmStacksPaginatedResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const params = transformPaginationParams(options);+ const res = await this.api.get(`/environments/${envId}/swarm/stacks`, { params });+ return res.data;+ }++ async deployStack(request: SwarmStackDeployRequest): Promise<SwarmStackDeployResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/stacks`, request));+ }++ async getStack(name: string): Promise<SwarmStackInspect> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/stacks/${name}`));+ }++ async getStackSource(name: string): Promise<SwarmStackSource> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/stacks/${name}/source`));+ }++ async removeStack(name: string): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.delete(`/environments/${envId}/swarm/stacks/${name}`));+ }++ async getStackServices(name: string, options?: SearchPaginationSortRequest): Promise<SwarmServicesPaginatedResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const params = transformPaginationParams(options);+ const res = await this.api.get(`/environments/${envId}/swarm/stacks/${name}/services`, { params });+ return res.data;+ }++ async getStackTasks(name: string, options?: SearchPaginationSortRequest): Promise<SwarmTasksPaginatedResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const params = transformPaginationParams(options);+ const res = await this.api.get(`/environments/${envId}/swarm/stacks/${name}/tasks`, { params });+ return res.data;+ }++ async renderStackConfig(request: SwarmStackRenderConfigRequest): Promise<SwarmStackRenderConfigResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/stacks/config/render`, request));+ }++ async getSwarmInfo(): Promise<SwarmInfo> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/info`));+ }++ async initSwarm(request: SwarmInitRequest): Promise<SwarmInitResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/init`, request));+ }++ async joinSwarm(request: SwarmJoinRequest): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.post(`/environments/${envId}/swarm/join`, request));+ }++ async leaveSwarm(request: SwarmLeaveRequest): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.post(`/environments/${envId}/swarm/leave`, request));+ }++ async unlockSwarm(request: SwarmUnlockRequest): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.post(`/environments/${envId}/swarm/unlock`, request));+ }++ async getSwarmUnlockKey(): Promise<SwarmUnlockKeyResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/unlock-key`));+ }++ async getSwarmJoinTokens(): Promise<SwarmJoinTokensResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/join-tokens`));+ }++ async rotateSwarmJoinTokens(request: SwarmRotateJoinTokensRequest = {}): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.post(`/environments/${envId}/swarm/join-tokens/rotate`, request));+ }++ async updateSwarmSpec(request: SwarmUpdateRequest): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.put(`/environments/${envId}/swarm/spec`, request));+ }++ async getConfigs(): Promise<SwarmConfigSummary[]> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/configs`));+ }++ async getConfig(configId: string): Promise<SwarmConfigSummary> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/configs/${configId}`));+ }++ async createConfig(request: SwarmConfigCreateRequest): Promise<SwarmConfigSummary> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/configs`, request));+ }++ async updateConfig(configId: string, request: SwarmConfigUpdateRequest): Promise<SwarmConfigSummary> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.put(`/environments/${envId}/swarm/configs/${configId}`, request));+ }++ async removeConfig(configId: string): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.delete(`/environments/${envId}/swarm/configs/${configId}`));+ }++ async getSecrets(): Promise<SwarmSecretSummary[]> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/secrets`));+ }++ async getSecret(secretId: string): Promise<SwarmSecretSummary> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/secrets/${secretId}`));+ }++ async createSecret(request: SwarmSecretCreateRequest): Promise<SwarmSecretSummary> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/secrets`, request));+ }++ async updateSecret(secretId: string, request: SwarmSecretUpdateRequest): Promise<SwarmSecretSummary> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.put(`/environments/${envId}/swarm/secrets/${secretId}`, request));+ }++ async removeSecret(secretId: string): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.delete(`/environments/${envId}/swarm/secrets/${secretId}`));+ }+}++export const swarmService = new SwarmService();diff --git a/frontend/src/lib/services/template-service.ts b/frontend/src/lib/services/template-service.tsindex f4650e971..2d3e80d5b 100644--- a/frontend/src/lib/services/template-service.ts+++ b/frontend/src/lib/services/template-service.ts@@ -27,11 +27,18 @@ export default class TemplateService extends BaseAPIService {return response.data?.data;}- async getDefaultTemplates(): Promise<{ composeTemplate: string; envTemplate: string }> {+ async getDefaultTemplates(): Promise<{+ composeTemplate: string;+ swarmStackTemplate: string;+ swarmStackEnvTemplate: string;+ envTemplate: string;+ }> {const response = await this.api.get('/templates/default');const data = response.data?.data;return {composeTemplate: data?.composeTemplate ?? '',+ swarmStackTemplate: data?.swarmStackTemplate ?? '',+ swarmStackEnvTemplate: data?.swarmStackEnvTemplate ?? '',envTemplate: data?.envTemplate ?? ''};}diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.tsindex ec5641d40..7bd165914 100644--- a/frontend/src/lib/types/settings.type.ts+++ b/frontend/src/lib/types/settings.type.ts@@ -5,6 +5,7 @@ export type ApplicationTheme = 'default' | 'graphite' | 'ocean' | 'amber' | 'gitexport type Settings = {projectsDirectory: string;followProjectSymlinks: boolean;+ swarmStackSourcesDirectory: string;diskUsagePath: string;autoUpdate: boolean;autoUpdateInterval: number;diff --git a/frontend/src/lib/types/swarm.type.ts b/frontend/src/lib/types/swarm.type.tsnew file mode 100644index 000000000..e39e4af0e--- /dev/null+++ b/frontend/src/lib/types/swarm.type.ts@@ -0,0 +1,415 @@+export interface SwarmServicePort {+ protocol: string;+ targetPort: number;+ publishedPort?: number;+ publishMode?: string;+}++export interface RawSwarmServicePort {+ protocol?: string;+ Protocol?: string;+ targetPort?: number;+ TargetPort?: number;+ publishedPort?: number;+ PublishedPort?: number;+ publishMode?: string;+ PublishMode?: string;+}++export interface SwarmServiceMount {+ type: string;+ source?: string;+ target: string;+ readOnly?: boolean;+ volumeDriver?: string;+ volumeOptions?: Record<string, string>;+ devicePath?: string;+}++export interface RawSwarmServiceMount {+ type?: string;+ Type?: string;+ source?: string;+ Source?: string;+ target?: string;+ Target?: string;+ readOnly?: boolean;+ ReadOnly?: boolean;+ volumeDriver?: string;+ VolumeDriver?: string;+ volumeOptions?: Record<string, string>;+ VolumeOptions?: Record<string, string>;+ devicePath?: string;+ DevicePath?: string;+}++export interface ServiceNetworkAttachment {+ target: string;+ aliases: string[];+}++export interface RawServiceNetworkAttachment {+ Target?: string;+ target?: string;+ Aliases?: string[];+ aliases?: string[];+}++export interface ServiceVirtualIP {+ networkID: string;+ addr: string;+}++export interface RawServiceVirtualIP {+ NetworkID?: string;+ networkID?: string;+ Addr?: string;+ addr?: string;+}++export interface SwarmServiceSummary {+ id: string;+ name: string;+ image: string;+ mode: string;+ replicas: number;+ runningReplicas: number;+ ports: SwarmServicePort[];+ createdAt: string;+ updatedAt: string;+ labels?: Record<string, string> | null;+ stackName?: string | null;+ nodes: string[];+ networks: string[];+ mounts: SwarmServiceMount[];+}++export interface ServiceNetworkIPAMConfig {+ subnet?: string;+ gateway?: string;+ ipRange?: string;+}++export interface ServiceNetworkConfigDetail {+ name: string;+ driver: string;+ scope: string;+ enableIPv4: boolean;+ enableIPv6: boolean;+ options?: Record<string, string>;+ ipv4Configs?: ServiceNetworkIPAMConfig[];+ ipv6Configs?: ServiceNetworkIPAMConfig[];+}++export interface ServiceNetworkDetail {+ id: string;+ name: string;+ driver: string;+ scope: string;+ internal: boolean;+ attachable: boolean;+ ingress: boolean;+ enableIPv4: boolean;+ enableIPv6: boolean;+ configFrom?: string;+ configOnly: boolean;+ options?: Record<string, string>;+ ipamConfigs?: ServiceNetworkIPAMConfig[];+ configNetwork?: ServiceNetworkConfigDetail | null;+}++export interface SwarmServiceInspect {+ id: string;+ version: { index?: number; Index?: number };+ createdAt: string;+ updatedAt: string;+ spec: Record<string, unknown>;+ endpoint: Record<string, unknown>;+ updateStatus?: Record<string, unknown> | null;+ nodes?: string[];+ networkDetails?: Record<string, ServiceNetworkDetail>;+ mounts?: SwarmServiceMount[];+}++export interface SwarmServiceCreateOptions {+ encodedRegistryAuth?: string;+ queryRegistry?: boolean;+}++export interface SwarmServiceCreateMountSpec {+ Type: 'volume' | 'bind';+ Source: string;+ Target: string;+}++export interface SwarmServiceCreatePortSpec {+ TargetPort: number;+ PublishedPort?: number;+ Protocol: 'tcp' | 'udp';+}++export interface SwarmServiceCreateContainerSpec {+ Image: string;+ Command?: string[];+ Args?: string[];+ Dir?: string;+ User?: string;+ Hostname?: string;+ Env?: string[];+ Mounts?: SwarmServiceCreateMountSpec[];+}++export interface SwarmServiceCreateSpec {+ Name: string;+ TaskTemplate: {+ ContainerSpec: SwarmServiceCreateContainerSpec;+ };+ Mode: { Replicated: { Replicas: number } } | { Global: Record<string, never> };+ Labels?: Record<string, string>;+ EndpointSpec?: {+ Ports: SwarmServiceCreatePortSpec[];+ };+}++export interface SwarmServiceUpdateOptions {+ encodedRegistryAuth?: string;+ registryAuthFrom?: 'spec' | 'previous-spec';+ rollback?: 'previous' | 'none' | string;+ queryRegistry?: boolean;+}++export interface SwarmServiceCreateRequest {+ spec: SwarmServiceCreateSpec;+ options?: SwarmServiceCreateOptions;+}++export interface SwarmServiceUpdateRequest {+ version: number;+ spec: Record<string, unknown>;+ options?: SwarmServiceUpdateOptions;+}++export interface SwarmServiceScaleRequest {+ replicas: number;+}++export interface SwarmServiceCreateResponse {+ id: string;+ warnings?: string[];+}++export interface SwarmServiceUpdateResponse {+ warnings?: string[];+}++export interface SwarmTaskSummary {+ id: string;+ name: string;+ serviceId: string;+ serviceName: string;+ nodeId: string;+ nodeName: string;+ desiredState: string;+ currentState: string;+ error?: string | null;+ containerId?: string | null;+ image?: string | null;+ slot?: number | null;+ createdAt: string;+ updatedAt: string;+}++export interface SwarmNodeSummary {+ id: string;+ hostname: string;+ role: string;+ availability: string;+ status: string;+ agent: SwarmNodeAgentStatus;+ address?: string | null;+ managerStatus?: string | null;+ reachability?: string | null;+ labels?: Record<string, string> | null;+ engineVersion?: string | null;+ platform?: string | null;+ createdAt: string;+ updatedAt: string;+}++export type SwarmNodeAgentState = 'none' | 'pending' | 'offline' | 'connected' | 'mismatched';++export interface SwarmNodeAgentStatus {+ state: SwarmNodeAgentState;+ environmentId?: string | null;+ connected?: boolean | null;+ lastHeartbeat?: string | null;+ lastPollAt?: string | null;+ reportedNodeId?: string | null;+ reportedHostname?: string | null;+}++export interface SwarmNodeAgentDeployment {+ environmentId: string;+ agent: SwarmNodeAgentStatus;+ dockerRun: string;+ dockerCompose: string;+}++export interface SwarmNodeUpdateRequest {+ version?: number;+ name?: string;+ labels?: Record<string, string>;+ role?: 'manager' | 'worker';+ availability?: 'active' | 'pause' | 'drain';+}++export interface SwarmStackSummary {+ id: string;+ name: string;+ namespace: string;+ services: number;+ createdAt: string;+ updatedAt: string;+}++export interface SwarmStackInspect {+ name: string;+ namespace: string;+ services: number;+ createdAt: string;+ updatedAt: string;+}++export interface SwarmStackDeployRequest {+ name: string;+ composeContent: string;+ envContent?: string;+ withRegistryAuth?: boolean;+ prune?: boolean;+ resolveImage?: string;+}++export interface SwarmStackDeployResponse {+ name: string;+}++export interface SwarmStackRenderConfigRequest {+ name: string;+ composeContent: string;+ envContent?: string;+}++export interface SwarmStackRenderConfigResponse {+ name: string;+ renderedCompose: string;+ services: string[];+ networks: string[];+ volumes: string[];+ configs: string[];+ secrets: string[];+ warnings?: string[];+}++export interface SwarmStackSource {+ name: string;+ composeContent: string;+ envContent?: string;+}++export interface SwarmInfo {+ id: string;+ createdAt: string;+ updatedAt: string;+ spec: Record<string, unknown>;+ rootRotationInProgress: boolean;+}++export interface SwarmInitRequest {+ listenAddr?: string;+ advertiseAddr?: string;+ dataPathAddr?: string;+ dataPathPort?: number;+ forceNewCluster?: boolean;+ spec: Record<string, unknown>;+ autoLockManagers?: boolean;+ availability?: 'active' | 'pause' | 'drain';+ defaultAddrPool?: string[];+ subnetSize?: number;+}++export interface SwarmInitResponse {+ nodeId: string;+}++export interface SwarmJoinRequest {+ listenAddr?: string;+ advertiseAddr?: string;+ dataPathAddr?: string;+ remoteAddrs: string[];+ joinToken: string;+ availability?: 'active' | 'pause' | 'drain';+}++export interface SwarmLeaveRequest {+ force?: boolean;+}++export interface SwarmUnlockRequest {+ key: string;+}++export interface SwarmUnlockKeyResponse {+ unlockKey: string;+}++export interface SwarmJoinTokensResponse {+ worker: string;+ manager: string;+}++export interface SwarmRotateJoinTokensRequest {+ rotateWorkerToken?: boolean;+ rotateManagerToken?: boolean;+}++export interface SwarmUpdateRequest {+ version?: number;+ spec: Record<string, unknown>;+ rotateWorkerToken?: boolean;+ rotateManagerToken?: boolean;+ rotateManagerUnlockKey?: boolean;+}++export interface SwarmConfigSummary {+ id: string;+ version: { index?: number; Index?: number };+ createdAt: string;+ updatedAt: string;+ spec: Record<string, unknown>;+}++export interface SwarmSecretSummary {+ id: string;+ version: { index?: number; Index?: number };+ createdAt: string;+ updatedAt: string;+ spec: Record<string, unknown>;+}++export interface SwarmConfigCreateRequest {+ spec: Record<string, unknown>;+}++export interface SwarmConfigUpdateRequest {+ version?: number;+ spec: Record<string, unknown>;+}++export interface SwarmSecretCreateRequest {+ spec: Record<string, unknown>;+}++export interface SwarmSecretUpdateRequest {+ version?: number;+ spec: Record<string, unknown>;+}diff --git a/frontend/src/lib/utils/string.utils.ts b/frontend/src/lib/utils/string.utils.tsindex a7d605829..55b0f57c2 100644--- a/frontend/src/lib/utils/string.utils.ts+++ b/frontend/src/lib/utils/string.utils.ts@@ -15,3 +15,7 @@ export function truncateString(str: string | undefined, maxLength: number): stri}return str.substring(0, maxLength - 3) + '...';}++export function truncateImageDigest(image: string): string {+ return image.replace(/@sha256:([a-f0-9]{7})[a-f0-9]+/g, '@sha256:$1');+}diff --git a/frontend/src/routes/(app)/+layout.svelte b/frontend/src/routes/(app)/+layout.svelteindex 22e38f753..636713671 100644--- a/frontend/src/routes/(app)/+layout.svelte+++ b/frontend/src/routes/(app)/+layout.svelte@@ -27,6 +27,7 @@const versionInformation = $derived(data.versionInformation);const user = $derived(data.user);const settings = $derived(data.settings);+ const dockerInfo = $derived(data.dockerInfo);const isMobile = new IsMobile();const isTablet = new IsTablet();@@ -108,10 +109,10 @@{@render children()}</section></main>- <MobileNav {navigationSettings} {user} {versionInformation} />+ <MobileNav {navigationSettings} {user} {versionInformation} {dockerInfo} />{:else}<Sidebar.Provider>- <AppSidebar {versionInformation} {user} />+ <AppSidebar {versionInformation} {user} {dockerInfo} /><main class="h-dvh flex-1"><section class="h-full p-3 sm:p-5">{@render children()}diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelteindex 0d9ab89d9..05b73f028 100644--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte@@ -154,6 +154,7 @@defaultDeployPullPolicy: z.enum(['missing', 'always', 'never']),defaultShell: z.string(),projectsDirectory: z.string(),+ swarmStackSourcesDirectory: z.string(),diskUsagePath: z.string(),maxImageUploadSize: z.coerce.number(),gitSyncMaxFiles: z.coerce.number().int().nonnegative(),@@ -196,6 +197,7 @@defaultDeployPullPolicy: (settings?.defaultDeployPullPolicy as 'missing' | 'always' | 'never') || 'missing',defaultShell: settings?.defaultShell || '/bin/sh',projectsDirectory: settings?.projectsDirectory || '/app/data/projects',+ swarmStackSourcesDirectory: settings?.swarmStackSourcesDirectory || '/app/data/swarm/sources',diskUsagePath: settings?.diskUsagePath || '/app/data/projects',maxImageUploadSize: settings?.maxImageUploadSize || 500,gitSyncMaxFiles: settings?.gitSyncMaxFiles ?? 500,@@ -245,6 +247,7 @@defaultDeployPullPolicy: formData.defaultDeployPullPolicy,defaultShell: formData.defaultShell,projectsDirectory: formData.projectsDirectory,+ swarmStackSourcesDirectory: formData.swarmStackSourcesDirectory,diskUsagePath: formData.diskUsagePath,maxImageUploadSize: formData.maxImageUploadSize,gitSyncMaxFiles: formData.gitSyncMaxFiles,diff --git a/frontend/src/routes/(app)/environments/[id]/components/GeneralTab.svelte b/frontend/src/routes/(app)/environments/[id]/components/GeneralTab.svelteindex a247a13ee..605d853db 100644--- a/frontend/src/routes/(app)/environments/[id]/components/GeneralTab.svelte+++ b/frontend/src/routes/(app)/environments/[id]/components/GeneralTab.svelte@@ -38,6 +38,15 @@helpText={m.disk_usage_settings_description()}/></div>+ <div class="space-y-2">+ <TextInputWithLabel+ id="swarm-stack-sources-directory"+ label="Swarm Stack Sources Directory"+ bind:value={$formInputs.swarmStackSourcesDirectory.value}+ error={$formInputs.swarmStackSourcesDirectory.error}+ helpText="Directory where original compose/env sources for Swarm stack deploys are stored. Supports the same container:host bind-mount format as Projects Directory."+ />+ </div><div class="space-y-2"><TextInputWithLabelid="base-server-url"diff --git a/frontend/src/routes/(app)/images/image-table.svelte b/frontend/src/routes/(app)/images/image-table.svelteindex f9b434487..aa24e28c1 100644--- a/frontend/src/routes/(app)/images/image-table.svelte+++ b/frontend/src/routes/(app)/images/image-table.svelte@@ -25,6 +25,7 @@import { imageService } from '$lib/services/image-service';import { vulnerabilityService } from '$lib/services/vulnerability-service';import { isLikelyStaleFailedSummary, isVulnerabilityScanInProgress } from '$lib/utils/vulnerability-scan.util';+import {DownloadIcon,TrashIcon,diff --git a/frontend/src/routes/(app)/projects/components/CodePanel.svelte b/frontend/src/routes/(app)/projects/components/CodePanel.svelteindex ba000fe3d..ba477a80f 100644--- a/frontend/src/routes/(app)/projects/components/CodePanel.svelte+++ b/frontend/src/routes/(app)/projects/components/CodePanel.svelte@@ -4,9 +4,7 @@import CodeEditor from '$lib/components/code-editor/editor.svelte';import { CodeIcon, FileTextIcon, SearchIcon, ArrowsUpDownIcon } from '$lib/icons';import { IsMobile } from '$lib/hooks/is-mobile.svelte.js';- import type { DiagnosticSummary, EditorContext } from '$lib/components/code-editor/analysis/types';-- type CodeLanguage = 'yaml' | 'env';+ import type { CodeLanguage, DiagnosticSummary, EditorContext } from '$lib/components/code-editor/analysis/types';let {title,diff --git a/frontend/src/routes/(app)/swarm/cluster/+page.svelte b/frontend/src/routes/(app)/swarm/cluster/+page.sveltenew file mode 100644index 000000000..475d5c022--- /dev/null+++ b/frontend/src/routes/(app)/swarm/cluster/+page.svelte@@ -0,0 +1,567 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { Input } from '$lib/components/ui/input/index.js';+ import * as InputGroup from '$lib/components/ui/input-group/index.js';+ import { ResponsiveDialog } from '$lib/components/ui/responsive-dialog/index.js';+ import { Switch } from '$lib/components/ui/switch/index.js';+ import { Textarea } from '$lib/components/ui/textarea/index.js';+ import { CopyButton } from '$lib/components/ui/copy-button';+ import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';+ import { EyeOffIcon, EyeOnIcon, LockIcon, SettingsIcon, UsersIcon } from '$lib/icons';+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import userStore from '$lib/stores/user-store';+ import type {+ SwarmInfo,+ SwarmInitRequest,+ SwarmJoinRequest,+ SwarmJoinTokensResponse,+ SwarmUpdateRequest+ } from '$lib/types/swarm.type';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';+ import { fromStore } from 'svelte/store';+ import { toast } from 'svelte-sonner';++ const storeUser = fromStore(userStore);+ const isAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));++ let swarmInfo = $state<SwarmInfo | null>(null);+ let joinTokens = $state<SwarmJoinTokensResponse | null>(null);+ let unlockKey = $state('');+ let showManagerToken = $state(false);+ let showWorkerToken = $state(false);+ let securityDialogOpen = $state(false);+ const isSwarmInitialized = $derived(!!swarmInfo?.id);++ let initForm = $state({+ listenAddr: '',+ advertiseAddr: '',+ spec: '{}',+ autoLockManagers: false,+ forceNewCluster: false+ });++ let joinForm = $state({+ remoteAddrs: '',+ joinToken: '',+ listenAddr: '',+ advertiseAddr: ''+ });++ let leaveForce = $state(false);+ let unlockInput = $state('');+ let updateForm = $state({+ version: '',+ spec: '{}',+ rotateWorkerToken: false,+ rotateManagerToken: false,+ rotateManagerUnlockKey: false+ });++ let isLoading = $state({+ refresh: false,+ init: false,+ join: false,+ leave: false,+ unlock: false,+ rotateTokens: false,+ updateSpec: false+ });++ function parseObjectJSON(raw: string, label: string): Record<string, unknown> | null {+ try {+ const parsed = JSON.parse(raw || '{}');+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ toast.error(m.swarm_cluster_json_object_error({ label }));+ return null;+ }+ return parsed as Record<string, unknown>;+ } catch {+ toast.error(m.swarm_cluster_json_invalid_error({ label }));+ return null;+ }+ }++ function splitCsv(input: string): string[] {+ return input+ .split(',')+ .map((value) => value.trim())+ .filter(Boolean);+ }++ function loadCurrentSpec() {+ const currentSpec = swarmInfo?.spec ?? {};+ updateForm.spec = JSON.stringify(currentSpec, null, 2);+ }++ async function refresh() {+ isLoading.refresh = true;+ try {+ const [infoRes, tokensRes, unlockRes] = await Promise.allSettled([+ swarmService.getSwarmInfo(),+ swarmService.getSwarmJoinTokens(),+ swarmService.getSwarmUnlockKey()+ ]);++ swarmInfo = infoRes.status === 'fulfilled' ? infoRes.value : null;+ joinTokens = tokensRes.status === 'fulfilled' ? tokensRes.value : null;+ unlockKey = unlockRes.status === 'fulfilled' ? unlockRes.value.unlockKey : '';+ showManagerToken = false;+ showWorkerToken = false;++ if (swarmInfo && updateForm.spec === '{}') {+ loadCurrentSpec();+ }+ } finally {+ isLoading.refresh = false;+ }+ }++ useEnvironmentRefresh(refresh);++ $effect(() => {+ refresh();+ });++ async function handleInit() {+ const spec = parseObjectJSON(initForm.spec, m.swarm_cluster_init_spec_label());+ if (!spec) return;++ const request: SwarmInitRequest = { spec };+ if (initForm.listenAddr.trim()) request.listenAddr = initForm.listenAddr.trim();+ if (initForm.advertiseAddr.trim()) request.advertiseAddr = initForm.advertiseAddr.trim();+ request.autoLockManagers = initForm.autoLockManagers;+ request.forceNewCluster = initForm.forceNewCluster;++ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.initSwarm(request)),+ message: m.swarm_cluster_init_failed(),+ setLoadingState: (value) => (isLoading.init = value),+ onSuccess: async () => {+ toast.success(m.swarm_cluster_init_success());+ await refresh();+ }+ });+ }++ async function handleJoin() {+ const remoteAddrs = splitCsv(joinForm.remoteAddrs);+ if (remoteAddrs.length === 0 || !joinForm.joinToken.trim()) {+ toast.error(m.swarm_cluster_join_required_error());+ return;+ }++ const request: SwarmJoinRequest = {+ remoteAddrs,+ joinToken: joinForm.joinToken.trim()+ };+ if (joinForm.listenAddr.trim()) request.listenAddr = joinForm.listenAddr.trim();+ if (joinForm.advertiseAddr.trim()) request.advertiseAddr = joinForm.advertiseAddr.trim();++ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.joinSwarm(request)),+ message: m.swarm_cluster_join_failed(),+ setLoadingState: (value) => (isLoading.join = value),+ onSuccess: async () => {+ toast.success(m.swarm_cluster_join_success());+ await refresh();+ }+ });+ }++ async function handleLeave() {+ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.leaveSwarm({ force: leaveForce })),+ message: m.swarm_cluster_leave_failed(),+ setLoadingState: (value) => (isLoading.leave = value),+ onSuccess: async () => {+ toast.success(m.swarm_cluster_leave_success());+ securityDialogOpen = false;+ await refresh();+ }+ });+ }++ async function handleUnlock() {+ if (!unlockInput.trim()) {+ toast.error(m.swarm_cluster_unlock_key_required());+ return;+ }++ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.unlockSwarm({ key: unlockInput.trim() })),+ message: m.swarm_cluster_unlock_failed(),+ setLoadingState: (value) => (isLoading.unlock = value),+ onSuccess: async () => {+ toast.success(m.swarm_cluster_unlock_success());+ unlockInput = '';+ securityDialogOpen = false;+ await refresh();+ }+ });+ }++ async function handleRotateTokens() {+ handleApiResultWithCallbacks({+ result: await tryCatch(+ swarmService.rotateSwarmJoinTokens({+ rotateManagerToken: true,+ rotateWorkerToken: true+ })+ ),+ message: m.swarm_cluster_rotate_tokens_failed(),+ setLoadingState: (value) => (isLoading.rotateTokens = value),+ onSuccess: async () => {+ toast.success(m.swarm_cluster_rotate_tokens_success());+ await refresh();+ }+ });+ }++ async function handleUpdateSpec() {+ const spec = parseObjectJSON(updateForm.spec, m.swarm_cluster_spec_label());+ if (!spec) return;++ const parsedVersion = Number.parseInt(updateForm.version, 10);+ const request: SwarmUpdateRequest = {+ spec,+ rotateWorkerToken: updateForm.rotateWorkerToken,+ rotateManagerToken: updateForm.rotateManagerToken,+ rotateManagerUnlockKey: updateForm.rotateManagerUnlockKey+ };++ if (Number.isFinite(parsedVersion) && parsedVersion > 0) {+ request.version = parsedVersion;+ }++ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.updateSwarmSpec(request)),+ message: m.swarm_cluster_update_spec_failed(),+ setLoadingState: (value) => (isLoading.updateSpec = value),+ onSuccess: async () => {+ toast.success(m.swarm_cluster_update_spec_success());+ await refresh();+ }+ });+ }++ const actionButtons: ActionButton[] = $derived([+ {+ id: 'refresh',+ action: 'restart',+ label: m.common_refresh(),+ onclick: refresh,+ loading: isLoading.refresh,+ disabled: isLoading.refresh+ }+ ]);++ const statCards: StatCardConfig[] = $derived([+ {+ title: m.swarm_cluster_stat_cluster(),+ value: swarmInfo?.id ? swarmInfo.id.slice(0, 12) : m.swarm_cluster_not_initialized(),+ icon: SettingsIcon,+ iconColor: 'text-blue-500'+ },+ {+ title: m.swarm_cluster_stat_tokens(),+ value: joinTokens ? 2 : 0,+ icon: UsersIcon,+ iconColor: 'text-emerald-500'+ },+ {+ title: m.swarm_cluster_stat_unlock_key(),+ value: unlockKey ? m.common_available() : m.common_unavailable(),+ icon: LockIcon,+ iconColor: 'text-amber-500'+ }+ ]);+</script>++<ResourcePageLayout+ title={m.swarm_cluster_title()}+ subtitle={m.swarm_cluster_subtitle()}+ icon={SettingsIcon}+ class="pb-6"+ {actionButtons}+ {statCards}+>+ {#snippet mainContent()}+ <div class="space-y-6 pb-6">+ <div class="grid gap-6 xl:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]">+ <Card.Root class="pt-0">+ <Card.Header>+ <Card.Title>{m.swarm_cluster_status_title()}</Card.Title>+ <Card.Description>{m.swarm_cluster_status_subtitle()}</Card.Description>+ <Card.Action>+ <ArcaneButton+ action="inspect"+ size="sm"+ customLabel={m.common_actions()}+ onclick={() => (securityDialogOpen = true)}+ disabled={!isAdmin}+ />+ </Card.Action>+ </Card.Header>+ <Card.Content class="pb-6">+ <div class="divide-border/60 divide-y text-sm">+ <div class="grid gap-1 py-3 sm:grid-cols-[140px_minmax(0,1fr)] sm:gap-4">+ <span class="text-muted-foreground">{m.swarm_cluster_id_label()}</span>+ <span class="font-mono break-all sm:text-right">{swarmInfo?.id ?? m.swarm_cluster_not_initialized()}</span>+ </div>+ <div class="grid gap-1 py-3 sm:grid-cols-[140px_minmax(0,1fr)] sm:gap-4">+ <span class="text-muted-foreground">{m.common_created()}</span>+ <span class="sm:text-right">{swarmInfo?.createdAt ?? m.common_na()}</span>+ </div>+ <div class="grid gap-1 pt-3 sm:grid-cols-[140px_minmax(0,1fr)] sm:gap-4">+ <span class="text-muted-foreground">{m.common_updated()}</span>+ <span class="sm:text-right">{swarmInfo?.updatedAt ?? m.common_na()}</span>+ </div>+ </div>+ </Card.Content>+ </Card.Root>++ <Card.Root class="pt-0">+ <Card.Header>+ <Card.Title>{m.swarm_cluster_join_tokens_title()}</Card.Title>+ <Card.Description>{m.swarm_cluster_join_tokens_subtitle()}</Card.Description>+ <Card.Action>+ <ArcaneButton+ action="restart"+ size="sm"+ customLabel={m.swarm_cluster_rotate_tokens()}+ onclick={handleRotateTokens}+ disabled={!isAdmin || !isSwarmInitialized || isLoading.rotateTokens}+ loading={isLoading.rotateTokens}+ />+ </Card.Action>+ </Card.Header>+ <Card.Content class="space-y-4 pb-6">+ <div class="space-y-2">+ <div class="text-muted-foreground text-xs font-medium">{m.swarm_cluster_manager_token_label()}</div>+ <div class="flex items-center gap-2">+ <InputGroup.Root class="flex-1">+ <InputGroup.Input+ type={showManagerToken ? 'text' : 'password'}+ value={joinTokens?.manager ?? ''}+ readonly+ class="font-mono text-xs"+ />+ <InputGroup.Addon align="inline-end">+ <InputGroup.Button+ type="button"+ size="icon-xs"+ onclick={() => (showManagerToken = !showManagerToken)}+ disabled={!joinTokens?.manager}+ aria-label={showManagerToken ? m.common_hide() : m.common_show()}+ >+ {#if showManagerToken}+ <EyeOffIcon />+ {:else}+ <EyeOnIcon />+ {/if}+ </InputGroup.Button>+ </InputGroup.Addon>+ </InputGroup.Root>+ {#if joinTokens?.manager}+ <CopyButton text={joinTokens.manager} />+ {/if}+ </div>+ </div>+ <div class="space-y-2">+ <div class="text-muted-foreground text-xs font-medium">{m.swarm_cluster_worker_token_label()}</div>+ <div class="flex items-center gap-2">+ <InputGroup.Root class="flex-1">+ <InputGroup.Input+ type={showWorkerToken ? 'text' : 'password'}+ value={joinTokens?.worker ?? ''}+ readonly+ class="font-mono text-xs"+ />+ <InputGroup.Addon align="inline-end">+ <InputGroup.Button+ type="button"+ size="icon-xs"+ onclick={() => (showWorkerToken = !showWorkerToken)}+ disabled={!joinTokens?.worker}+ aria-label={showWorkerToken ? m.common_hide() : m.common_show()}+ >+ {#if showWorkerToken}+ <EyeOffIcon />+ {:else}+ <EyeOnIcon />+ {/if}+ </InputGroup.Button>+ </InputGroup.Addon>+ </InputGroup.Root>+ {#if joinTokens?.worker}+ <CopyButton text={joinTokens.worker} />+ {/if}+ </div>+ </div>+ </Card.Content>+ </Card.Root>+ </div>++ {#if !isSwarmInitialized}+ <div class="grid gap-6 xl:grid-cols-2">+ <Card.Root class="pt-0">+ <Card.Header>+ <Card.Title>{m.swarm_cluster_initialize_title()}</Card.Title>+ <Card.Description>{m.swarm_cluster_initialize_subtitle()}</Card.Description>+ </Card.Header>+ <Card.Content class="space-y-4 pb-6">+ <div class="grid gap-3 sm:grid-cols-2">+ <Input placeholder={m.swarm_cluster_listen_addr_placeholder()} bind:value={initForm.listenAddr} />+ <Input placeholder={m.swarm_cluster_advertise_addr_placeholder()} bind:value={initForm.advertiseAddr} />+ </div>+ <Textarea+ rows={8}+ placeholder={m.swarm_cluster_spec_placeholder()}+ bind:value={initForm.spec}+ class="font-mono text-xs"+ />+ <div class="grid gap-2 sm:grid-cols-2">+ <label class="flex items-center gap-2 text-sm">+ <input type="checkbox" bind:checked={initForm.autoLockManagers} />+ {m.swarm_cluster_auto_lock_managers()}+ </label>+ <label class="flex items-center gap-2 text-sm">+ <input type="checkbox" bind:checked={initForm.forceNewCluster} />+ {m.swarm_cluster_force_new_cluster()}+ </label>+ </div>+ <ArcaneButton+ action="create"+ customLabel={m.swarm_cluster_initialize_action()}+ onclick={handleInit}+ disabled={!isAdmin || isLoading.init}+ loading={isLoading.init}+ />+ </Card.Content>+ </Card.Root>++ <Card.Root class="pt-0">+ <Card.Header>+ <Card.Title>{m.swarm_cluster_join_title()}</Card.Title>+ <Card.Description>{m.swarm_cluster_join_subtitle()}</Card.Description>+ </Card.Header>+ <Card.Content class="space-y-4 pb-6">+ <Input placeholder={m.swarm_cluster_join_remote_addrs_placeholder()} bind:value={joinForm.remoteAddrs} />+ <Input+ placeholder={m.swarm_cluster_join_token_placeholder()}+ bind:value={joinForm.joinToken}+ class="font-mono text-xs"+ />+ <div class="grid gap-3 sm:grid-cols-2">+ <Input placeholder={m.swarm_cluster_listen_addr_placeholder()} bind:value={joinForm.listenAddr} />+ <Input placeholder={m.swarm_cluster_advertise_addr_placeholder()} bind:value={joinForm.advertiseAddr} />+ </div>+ <ArcaneButton+ action="create"+ customLabel={m.swarm_cluster_join_action()}+ onclick={handleJoin}+ disabled={!isAdmin || isLoading.join}+ loading={isLoading.join}+ />+ </Card.Content>+ </Card.Root>+ </div>+ {/if}++ <Card.Root class="pt-0">+ <Card.Header>+ <Card.Title>{m.swarm_cluster_update_spec_title()}</Card.Title>+ <Card.Description>{m.swarm_cluster_update_spec_subtitle()}</Card.Description>+ <Card.Action class="flex flex-wrap items-center justify-end gap-4">+ <label class="flex items-center gap-2 text-sm whitespace-nowrap">+ <Switch id="rotate-worker-token" bind:checked={updateForm.rotateWorkerToken} />+ <span>{m.swarm_cluster_rotate_worker_token()}</span>+ </label>+ <label class="flex items-center gap-2 text-sm whitespace-nowrap">+ <Switch id="rotate-manager-token" bind:checked={updateForm.rotateManagerToken} />+ <span>{m.swarm_cluster_rotate_manager_token()}</span>+ </label>+ <label class="flex items-center gap-2 text-sm whitespace-nowrap">+ <Switch id="rotate-unlock-key" bind:checked={updateForm.rotateManagerUnlockKey} />+ <span>{m.swarm_cluster_rotate_unlock_key()}</span>+ </label>+ <ArcaneButton+ action="inspect"+ size="sm"+ customLabel={m.swarm_cluster_load_current_spec()}+ onclick={loadCurrentSpec}+ />+ </Card.Action>+ </Card.Header>+ <Card.Content class="space-y-4 pb-6">+ <Input placeholder={m.swarm_cluster_version_placeholder()} bind:value={updateForm.version} class="max-w-sm" />+ <Textarea+ rows={22}+ placeholder={m.swarm_cluster_spec_placeholder()}+ bind:value={updateForm.spec}+ class="min-h-[34rem] font-mono text-xs"+ />+ <div class="flex justify-end border-t pt-4">+ <ArcaneButton+ action="save"+ customLabel={m.swarm_cluster_update_spec_action()}+ onclick={handleUpdateSpec}+ disabled={!isAdmin || isLoading.updateSpec}+ loading={isLoading.updateSpec}+ />+ </div>+ </Card.Content>+ </Card.Root>+ </div>++ <ResponsiveDialog+ bind:open={securityDialogOpen}+ title={m.swarm_cluster_unlock_leave_title()}+ description={m.swarm_cluster_unlock_leave_subtitle()}+ contentClass="sm:max-w-lg"+ >+ {#snippet children()}+ <div class="space-y-6 py-4">+ <div class="space-y-3">+ {#if unlockKey}+ <div+ class="border-border/60 bg-muted/15 flex items-center justify-between gap-3 rounded-lg border px-3 py-2 text-sm"+ >+ <span class="text-muted-foreground">{m.swarm_cluster_stat_unlock_key()}</span>+ <CopyButton text={unlockKey} />+ </div>+ {/if}+ <Input placeholder={m.swarm_cluster_unlock_key_placeholder()} bind:value={unlockInput} class="font-mono text-xs" />+ <div class="flex items-center gap-2">+ <ArcaneButton+ action="save"+ customLabel={m.swarm_cluster_unlock_action()}+ onclick={handleUnlock}+ disabled={!isAdmin || isLoading.unlock}+ loading={isLoading.unlock}+ />+ </div>+ </div>++ <div class="space-y-3 border-t pt-4">+ <label class="flex items-center gap-2 text-sm">+ <input type="checkbox" bind:checked={leaveForce} />+ {m.swarm_cluster_force_leave()}+ </label>+ <ArcaneButton+ action="remove"+ customLabel={m.swarm_cluster_leave_action()}+ onclick={handleLeave}+ disabled={!isAdmin || isLoading.leave}+ loading={isLoading.leave}+ />+ </div>+ </div>+ {/snippet}+ </ResponsiveDialog>+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/swarm/configs/+page.svelte b/frontend/src/routes/(app)/swarm/configs/+page.sveltenew file mode 100644index 000000000..f69695d94--- /dev/null+++ b/frontend/src/routes/(app)/swarm/configs/+page.svelte@@ -0,0 +1,269 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { Input } from '$lib/components/ui/input/index.js';+ import { Textarea } from '$lib/components/ui/textarea/index.js';+ import { CopyButton } from '$lib/components/ui/copy-button';+ import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';+ import { TemplateIcon, TrashIcon } from '$lib/icons';+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import userStore from '$lib/stores/user-store';+ import type { SwarmConfigSummary } from '$lib/types/swarm.type';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';+ import { fromStore } from 'svelte/store';+ import { toast } from 'svelte-sonner';+ import { formatDistanceToNow } from 'date-fns';+ import { openConfirmDialog } from '$lib/components/confirm-dialog';++ const storeUser = fromStore(userStore);+ const isAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));++ let configs = $state<SwarmConfigSummary[]>([]);+ let selectedConfigId = $state('');+ let createName = $state('');+ let createData = $state('');+ let editName = $state('');+ let editData = $state('');+ let isLoading = $state({+ refresh: false,+ create: false,+ delete: false+ });++ const selectedConfig = $derived(configs.find((config) => config.id === selectedConfigId) ?? null);++ function getSpecName(spec: Record<string, unknown> | null | undefined, fallback: string): string {+ const name = spec && typeof spec === 'object' ? (spec as Record<string, unknown>).Name : undefined;+ return typeof name === 'string' && name.trim() ? name : fallback.slice(0, 12);+ }++ function decodeBase64ToText(base64Value: string): string {+ try {+ const binary = atob(base64Value);+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));+ return new TextDecoder().decode(bytes);+ } catch {+ return '';+ }+ }++ function encodeTextToBase64(value: string): string {+ const bytes = new TextEncoder().encode(value);+ let binary = '';+ for (const byte of bytes) {+ binary += String.fromCharCode(byte);+ }+ return btoa(binary);+ }++ function formatTimestamp(timestamp: string): string {+ if (!timestamp) return m.common_unknown();+ return formatDistanceToNow(new Date(timestamp), { addSuffix: true });+ }++ function selectConfig(config: SwarmConfigSummary) {+ selectedConfigId = config.id;+ const spec = (config.spec ?? {}) as Record<string, unknown>;+ editName = typeof spec.Name === 'string' ? spec.Name : '';+ editData = typeof spec.Data === 'string' ? decodeBase64ToText(spec.Data) : '';+ }++ function clearSelectedConfig() {+ selectedConfigId = '';+ editName = '';+ editData = '';+ }++ function toggleConfig(config: SwarmConfigSummary) {+ if (selectedConfigId === config.id) {+ clearSelectedConfig();+ return;+ }++ selectConfig(config);+ }++ async function refresh() {+ isLoading.refresh = true;+ try {+ configs = await swarmService.getConfigs();+ if (selectedConfigId && !configs.some((config) => config.id === selectedConfigId)) {+ clearSelectedConfig();+ }+ } finally {+ isLoading.refresh = false;+ }+ }++ useEnvironmentRefresh(refresh);++ $effect(() => {+ refresh();+ });++ async function createConfig() {+ const name = createName.trim();+ if (!name) {+ toast.error(m.swarm_configs_name_required());+ return;+ }+ const spec: Record<string, unknown> = {+ Name: name,+ Data: encodeTextToBase64(createData)+ };++ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.createConfig({ spec })),+ message: m.swarm_configs_create_failed(),+ setLoadingState: (value) => (isLoading.create = value),+ onSuccess: async (created) => {+ toast.success(m.swarm_configs_create_success({ name: getSpecName(created.spec, created.id) }));+ createName = '';+ createData = '';+ await refresh();+ selectConfig(created);+ }+ });+ }++ function removeConfig(config: SwarmConfigSummary) {+ const name = getSpecName(config.spec, config.id);+ openConfirmDialog({+ title: m.common_delete_title({ resource: m.swarm_config() }),+ message: m.swarm_configs_delete_confirm({ name }),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.removeConfig(config.id)),+ message: m.swarm_configs_delete_failed({ name }),+ setLoadingState: (value) => (isLoading.delete = value),+ onSuccess: async () => {+ toast.success(m.swarm_configs_delete_success({ name }));+ await refresh();+ }+ });+ }+ }+ });+ }++ const actionButtons: ActionButton[] = $derived([+ {+ id: 'refresh',+ action: 'restart',+ label: m.common_refresh(),+ onclick: refresh,+ loading: isLoading.refresh,+ disabled: isLoading.refresh+ }+ ]);++ const statCards: StatCardConfig[] = $derived([+ {+ title: m.swarm_configs_title(),+ value: configs.length,+ icon: TemplateIcon,+ iconColor: 'text-blue-500'+ }+ ]);+</script>++<ResourcePageLayout+ title={m.swarm_configs_title()}+ subtitle={m.swarm_configs_subtitle()}+ icon={TemplateIcon}+ {actionButtons}+ {statCards}+>+ {#snippet mainContent()}+ <div class="grid gap-4 lg:grid-cols-[1fr,1.1fr]">+ <Card.Root class="pt-0">+ <Card.Header>+ <Card.Title>{m.swarm_configs_create_title()}</Card.Title>+ <Card.Description>{m.swarm_configs_create_subtitle()}</Card.Description>+ </Card.Header>+ <Card.Content class="space-y-3 pb-6">+ <Input placeholder={m.swarm_configs_name_placeholder()} bind:value={createName} />+ <Textarea+ rows={10}+ bind:value={createData}+ placeholder={m.swarm_configs_data_placeholder()}+ class="font-mono text-xs"+ />+ <ArcaneButton+ action="create"+ customLabel={m.swarm_configs_create_button()}+ onclick={createConfig}+ disabled={!isAdmin || isLoading.create}+ loading={isLoading.create}+ />+ </Card.Content>+ </Card.Root>++ <div class="space-y-4">+ <Card.Root class="pt-0">+ <Card.Header>+ <Card.Title>{m.swarm_configs_list_title()}</Card.Title>+ <Card.Description>{m.swarm_configs_list_subtitle()}</Card.Description>+ </Card.Header>+ <Card.Content class="space-y-3 pb-6">+ {#if configs.length === 0}+ <div class="text-muted-foreground py-8 text-center text-sm">{m.swarm_configs_empty()}</div>+ {:else}+ {#each configs as config (config.id)}+ <Card.Root class="overflow-hidden border py-0">+ <button+ type="button"+ class={`w-full px-4 py-3 text-left transition-colors ${selectedConfigId === config.id ? 'bg-muted/50' : 'hover:bg-muted/40'}`}+ onclick={() => toggleConfig(config)}+ >+ <div class="flex items-center justify-between gap-2">+ <div class="min-w-0">+ <div class="truncate font-medium">{getSpecName(config.spec, config.id)}</div>+ <div class="text-muted-foreground font-mono text-xs">{config.id}</div>+ </div>+ <div class="text-muted-foreground shrink-0 text-xs">{formatTimestamp(config.updatedAt)}</div>+ </div>+ </button>++ {#if selectedConfigId === config.id}+ <div class="space-y-3 border-t px-4 pt-4 pb-5">+ <div class="flex items-center gap-2">+ <div class="text-muted-foreground font-mono text-xs">{config.id}</div>+ <CopyButton text={config.id} />+ </div>+ <p class="text-muted-foreground text-sm">{m.swarm_configs_immutable_notice()}</p>+ <Input placeholder={m.swarm_configs_name_placeholder()} bind:value={editName} readonly />+ <Textarea+ rows={12}+ bind:value={editData}+ placeholder={m.swarm_configs_data_placeholder()}+ class="font-mono text-xs"+ readonly+ />+ <div class="flex flex-wrap items-center gap-2 pt-1">+ <ArcaneButton+ action="remove"+ customLabel={m.swarm_configs_delete_button()}+ icon={TrashIcon}+ onclick={() => removeConfig(config)}+ disabled={!isAdmin || isLoading.delete}+ loading={isLoading.delete}+ />+ </div>+ </div>+ {/if}+ </Card.Root>+ {/each}+ {/if}+ </Card.Content>+ </Card.Root>+ </div>+ </div>+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/swarm/nodes/+page.svelte b/frontend/src/routes/(app)/swarm/nodes/+page.sveltenew file mode 100644index 000000000..22d33a84f--- /dev/null+++ b/frontend/src/routes/(app)/swarm/nodes/+page.svelte@@ -0,0 +1,74 @@+<script lang="ts">+ import * as Alert from '$lib/components/ui/alert';+ import { AlertTriangleIcon, UsersIcon } from '$lib/icons';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import { untrack } from 'svelte';+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';+ import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';+ import { parallelRefresh } from '$lib/utils/refresh.util';+ import SwarmNodesTable from './nodes-table.svelte';++ let { data } = $props();++ let nodes = $state(untrack(() => data.nodes));+ let requestOptions = $state(untrack(() => data.requestOptions));+ let isLoading = $state({ refresh: false });++ async function refresh() {+ await parallelRefresh(+ {+ nodes: {+ fetch: () => swarmService.getNodes(requestOptions),+ onSuccess: (data) => {+ nodes = data;+ },+ errorMessage: m.common_refresh_failed({ resource: m.swarm_nodes_title() })+ }+ },+ (v) => (isLoading.refresh = v)+ );+ }++ useEnvironmentRefresh(refresh);++ const totalNodes = $derived(nodes?.pagination?.totalItems ?? nodes?.data?.length ?? 0);+ const uncoveredNodes = $derived((nodes?.data ?? []).filter((node) => node.agent?.state !== 'connected'));+ const uncoveredNodeCount = $derived(uncoveredNodes.length);++ const actionButtons: ActionButton[] = $derived([+ {+ id: 'refresh',+ action: 'restart',+ label: m.common_refresh(),+ onclick: refresh,+ loading: isLoading.refresh,+ disabled: isLoading.refresh+ }+ ]);++ const statCards: StatCardConfig[] = $derived([+ {+ title: m.swarm_nodes_total(),+ value: totalNodes,+ icon: UsersIcon,+ iconColor: 'text-blue-500'+ }+ ]);+</script>++<ResourcePageLayout title={m.swarm_nodes_title()} subtitle={m.swarm_nodes_subtitle()} {actionButtons} {statCards}>+ {#snippet mainContent()}+ <div class="space-y-4">+ {#if uncoveredNodeCount > 0}+ <Alert.Root class="border-amber-500/30 bg-amber-500/10 text-amber-900 dark:text-amber-100">+ <AlertTriangleIcon class="size-4 text-amber-600 dark:text-amber-300" />+ <Alert.Title>{m.swarm_node_agent_warning_title()}</Alert.Title>+ <Alert.Description>{m.swarm_node_agent_warning_description({ count: uncoveredNodeCount })}</Alert.Description>+ </Alert.Root>+ {/if}++ <SwarmNodesTable bind:nodes bind:requestOptions />+ </div>+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/swarm/nodes/+page.ts b/frontend/src/routes/(app)/swarm/nodes/+page.tsnew file mode 100644index 000000000..4dbd2c98f--- /dev/null+++ b/frontend/src/routes/(app)/swarm/nodes/+page.ts@@ -0,0 +1,24 @@+import { swarmService } from '$lib/services/swarm-service';+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';+import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';+import type { PageLoad } from './$types';++export const load: PageLoad = async () => {+ const requestOptions = resolveInitialTableRequest('arcane-swarm-nodes-table', {+ pagination: {+ page: 1,+ limit: 20+ },+ sort: {+ column: 'hostname',+ direction: 'asc'+ }+ } satisfies SearchPaginationSortRequest);++ const nodes = await swarmService.getNodes(requestOptions);++ return {+ nodes,+ requestOptions+ };+};diff --git a/frontend/src/routes/(app)/swarm/nodes/agent-status.ts b/frontend/src/routes/(app)/swarm/nodes/agent-status.tsnew file mode 100644index 000000000..08e91cd4b--- /dev/null+++ b/frontend/src/routes/(app)/swarm/nodes/agent-status.ts@@ -0,0 +1,37 @@+import { m } from '$lib/paraglide/messages';+import type { SwarmNodeAgentState } from '$lib/types/swarm.type';++export function getSwarmNodeAgentLabel(state: SwarmNodeAgentState | null | undefined): string {+ switch (state) {+ case 'pending':+ return m.swarm_node_agent_status_pending();+ case 'offline':+ return m.swarm_node_agent_status_offline();+ case 'connected':+ return m.swarm_node_agent_status_connected();+ case 'mismatched':+ return m.swarm_node_agent_status_mismatched();+ case 'none':+ default:+ return m.swarm_node_agent_status_none();+ }+}++export function getSwarmNodeAgentVariant(state: SwarmNodeAgentState | null | undefined): 'green' | 'red' | 'amber' | 'gray' {+ switch (state) {+ case 'connected':+ return 'green';+ case 'offline':+ return 'red';+ case 'pending':+ case 'mismatched':+ return 'amber';+ case 'none':+ default:+ return 'gray';+ }+}++export function getSwarmNodeAgentActionLabel(state: SwarmNodeAgentState | null | undefined): string {+ return state === 'connected' ? m.swarm_node_agent_view() : m.swarm_node_agent_deploy();+}diff --git a/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte b/frontend/src/routes/(app)/swarm/nodes/nodes-table.sveltenew file mode 100644index 000000000..4d53462be--- /dev/null+++ b/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte@@ -0,0 +1,340 @@+<script lang="ts">+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';+ import type { ColumnSpec, MobileFieldVisibility } from '$lib/components/arcane-table';+ import { UniversalMobileCard } from '$lib/components/arcane-table';+ import { UsersIcon, EnvironmentsIcon, EllipsisIcon, InspectIcon, TrashIcon, EdgeConnectionIcon } from '$lib/icons';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import type { SwarmNodeAgentDeployment, SwarmNodeSummary } from '$lib/types/swarm.type';+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import { capitalizeFirstLetter } from '$lib/utils/string.utils';+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { openConfirmDialog } from '$lib/components/confirm-dialog';+ import { toast } from 'svelte-sonner';+ import { tryCatch } from '$lib/utils/try-catch';+ import { extractApiErrorMessage, handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { goto } from '$app/navigation';+ import userStore from '$lib/stores/user-store';+ import { fromStore } from 'svelte/store';+ import SwarmNodeAgentDialog from './swarm-node-agent-dialog.svelte';+ import { getSwarmNodeAgentActionLabel, getSwarmNodeAgentLabel, getSwarmNodeAgentVariant } from './agent-status';++ let {+ nodes = $bindable(),+ requestOptions = $bindable()+ }: {+ nodes: Paginated<SwarmNodeSummary>;+ requestOptions: SearchPaginationSortRequest;+ } = $props();++ const storeUser = fromStore(userStore);+ const isAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));+ let isLoading = $state(false);+ let isAgentDialogOpen = $state(false);+ let selectedNode = $state<SwarmNodeSummary | null>(null);+ let agentDeploymentError = $state('');+ let agentDeployment = $state<SwarmNodeAgentDeployment | null>(null);+ let isAgentDeploymentLoading = $state(false);++ function statusVariant(state: string): 'green' | 'red' | 'amber' | 'gray' {+ if (state === 'ready') return 'green';+ if (state === 'down') return 'red';+ if (state === 'unknown') return 'amber';+ return 'gray';+ }++ function availabilityVariant(state: string): 'green' | 'amber' | 'red' | 'gray' {+ if (state === 'active') return 'green';+ if (state === 'pause') return 'amber';+ if (state === 'drain') return 'red';+ return 'gray';+ }++ async function refreshNodes() {+ nodes = await swarmService.getNodes(requestOptions);+ if (selectedNode) {+ selectedNode = nodes.data.find((node) => node.id === selectedNode?.id) ?? selectedNode;+ }+ }++ async function loadAgentDeployment(node: SwarmNodeSummary, rotate = false) {+ if (isAgentDeploymentLoading) return;++ isAgentDeploymentLoading = true;+ agentDeploymentError = '';++ try {+ agentDeployment = await swarmService.getNodeAgentDeployment(node.id, rotate);+ await refreshNodes();+ } catch (error) {+ agentDeployment = null;+ agentDeploymentError = extractApiErrorMessage(error);+ throw error;+ } finally {+ isAgentDeploymentLoading = false;+ }+ }++ function openAgentDialog(node: SwarmNodeSummary) {+ selectedNode = node;+ agentDeployment = null;+ agentDeploymentError = '';+ isAgentDialogOpen = true;+ void loadAgentDeployment(node).catch(() => undefined);+ }++ function refreshAgentDeployment() {+ if (!selectedNode) return;+ void loadAgentDeployment(selectedNode).catch(() => undefined);+ }++ function regenerateAgentDeployment() {+ if (!selectedNode) return;++ openConfirmDialog({+ title: m.environments_regenerate_dialog_title(),+ message: m.environments_regenerate_dialog_message(),+ confirm: {+ label: m.environments_regenerate_api_key(),+ destructive: true,+ action: async () => {+ try {+ await loadAgentDeployment(selectedNode, true);+ toast.success(m.environments_regenerate_key_success());+ } catch {+ toast.error(m.environments_regenerate_key_failed());+ }+ }+ }+ });+ }++ function inspectNodeTasks(node: SwarmNodeSummary) {+ goto(`/swarm/tasks?nodeId=${encodeURIComponent(node.id)}&search=${encodeURIComponent(node.hostname)}`);+ }++ async function mutateNode(action: () => Promise<void>, successMessage: string, failureMessage: string) {+ handleApiResultWithCallbacks({+ result: await tryCatch(action()),+ message: failureMessage,+ setLoadingState: (v) => (isLoading = v),+ onSuccess: async () => {+ toast.success(successMessage);+ await refreshNodes();+ }+ });+ }++ function setAvailability(node: SwarmNodeSummary, availability: 'active' | 'pause' | 'drain') {+ mutateNode(+ () => swarmService.updateNode(node.id, { availability }),+ m.swarm_node_availability_update_success({ name: node.hostname, availability }),+ m.swarm_node_update_failed({ name: node.hostname })+ );+ }++ function promoteNode(node: SwarmNodeSummary) {+ mutateNode(+ () => swarmService.promoteNode(node.id),+ m.swarm_node_promote_success({ name: node.hostname }),+ m.swarm_node_promote_failed({ name: node.hostname })+ );+ }++ function demoteNode(node: SwarmNodeSummary) {+ mutateNode(+ () => swarmService.demoteNode(node.id),+ m.swarm_node_demote_success({ name: node.hostname }),+ m.swarm_node_demote_failed({ name: node.hostname })+ );+ }++ function removeNode(node: SwarmNodeSummary) {+ openConfirmDialog({+ title: m.common_delete_title({ resource: m.swarm_node() }),+ message: m.common_delete_confirm({ resource: m.swarm_node() }),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ mutateNode(+ () => swarmService.removeNode(node.id, true),+ m.swarm_node_remove_success({ name: node.hostname }),+ m.swarm_node_remove_failed({ name: node.hostname })+ );+ }+ }+ });+ }++ const columns = [+ { accessorKey: 'id', title: m.common_id(), hidden: true },+ { accessorKey: 'hostname', title: m.swarm_hostname(), sortable: true },+ { accessorKey: 'role', title: m.common_role(), sortable: true, cell: RoleCell },+ { accessorKey: 'status', title: m.common_status(), sortable: true, cell: StatusCell },+ { accessorKey: 'availability', title: m.swarm_availability(), sortable: true, cell: AvailabilityCell },+ {+ id: 'agent',+ title: m.swarm_node_agent_column(),+ accessorFn: (node) => node.agent?.state ?? 'none',+ cell: AgentCell+ },+ { accessorKey: 'engineVersion', title: m.swarm_engine_version(), sortable: true }+ ] satisfies ColumnSpec<SwarmNodeSummary>[];++ const mobileFields = [+ { id: 'role', label: m.common_role(), defaultVisible: true },+ { id: 'status', label: m.common_status(), defaultVisible: true },+ { id: 'availability', label: m.swarm_availability(), defaultVisible: true },+ { id: 'agent', label: m.swarm_node_agent_column(), defaultVisible: true },+ { id: 'engineVersion', label: m.swarm_engine_version(), defaultVisible: false }+ ];++ let mobileFieldVisibility = $state<Record<string, boolean>>({});+</script>++{#snippet RoleCell({ value }: { value: unknown })}+ <span class="text-sm">{capitalizeFirstLetter(String(value ?? ''))}</span>+{/snippet}++{#snippet StatusCell({ value }: { value: unknown })}+ <StatusBadge text={String(value ?? m.common_unknown())} variant={statusVariant(String(value ?? ''))} />+{/snippet}++{#snippet AvailabilityCell({ value }: { value: unknown })}+ <StatusBadge text={String(value ?? m.common_unknown())} variant={availabilityVariant(String(value ?? ''))} />+{/snippet}++{#snippet AgentCell({ value }: { value: unknown })}+ <StatusBadge+ text={getSwarmNodeAgentLabel(String(value ?? 'none') as SwarmNodeSummary['agent']['state'])}+ variant={getSwarmNodeAgentVariant(String(value ?? 'none') as SwarmNodeSummary['agent']['state'])}+ />+{/snippet}++{#snippet NodeMobileCardSnippet({+ item,+ mobileFieldVisibility+}: {+ item: SwarmNodeSummary;+ mobileFieldVisibility: MobileFieldVisibility;+})}+ <UniversalMobileCard+ {item}+ icon={() => ({+ component: UsersIcon,+ variant: item.role === 'manager' ? 'purple' : 'blue'+ })}+ title={(item: SwarmNodeSummary) => item.hostname}+ subtitle={(item: SwarmNodeSummary) => ((mobileFieldVisibility.engineVersion ?? false) ? (item.engineVersion ?? '') : null)}+ badges={[+ (item: SwarmNodeSummary) =>+ (mobileFieldVisibility.status ?? true) ? { variant: statusVariant(item.status), text: item.status } : null,+ (item: SwarmNodeSummary) =>+ (mobileFieldVisibility.agent ?? true)+ ? {+ variant: getSwarmNodeAgentVariant(item.agent?.state),+ text: getSwarmNodeAgentLabel(item.agent?.state)+ }+ : null+ ]}+ fields={[+ {+ label: m.common_role(),+ getValue: (item: SwarmNodeSummary) => capitalizeFirstLetter(item.role),+ icon: EnvironmentsIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.role ?? true+ },+ {+ label: m.swarm_availability(),+ getValue: (item: SwarmNodeSummary) => capitalizeFirstLetter(item.availability),+ icon: EnvironmentsIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.availability ?? true+ },+ {+ label: m.swarm_node_agent_column(),+ getValue: (item: SwarmNodeSummary) => getSwarmNodeAgentLabel(item.agent?.state),+ icon: EdgeConnectionIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.agent ?? true+ }+ ]}+ rowActions={RowActions}+ />+{/snippet}++{#snippet RowActions({ item }: { item: SwarmNodeSummary })}+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ {#snippet child({ props })}+ <ArcaneButton {...props} action="base" tone="ghost" size="icon" class="relative size-8 p-0">+ <span class="sr-only">{m.common_open_menu()}</span>+ <EllipsisIcon />+ </ArcaneButton>+ {/snippet}+ </DropdownMenu.Trigger>+ <DropdownMenu.Content align="end">+ <DropdownMenu.Group>+ <DropdownMenu.Item onclick={() => inspectNodeTasks(item)}>+ <InspectIcon class="size-4" />+ {m.common_inspect()}+ </DropdownMenu.Item>+ <DropdownMenu.Item onclick={() => openAgentDialog(item)} disabled={!isAdmin}>+ <EdgeConnectionIcon class="size-4" />+ {getSwarmNodeAgentActionLabel(item.agent?.state)}+ </DropdownMenu.Item>+ <DropdownMenu.Separator />+ <DropdownMenu.Item onclick={() => promoteNode(item)} disabled={!isAdmin || isLoading || item.role === 'manager'}>+ {m.swarm_node_promote()}+ </DropdownMenu.Item>+ <DropdownMenu.Item onclick={() => demoteNode(item)} disabled={!isAdmin || isLoading || item.role !== 'manager'}>+ {m.swarm_node_demote()}+ </DropdownMenu.Item>+ <DropdownMenu.Item+ onclick={() => setAvailability(item, 'drain')}+ disabled={!isAdmin || isLoading || item.availability === 'drain'}+ >+ {m.swarm_node_drain()}+ </DropdownMenu.Item>+ <DropdownMenu.Item+ onclick={() => setAvailability(item, 'active')}+ disabled={!isAdmin || isLoading || item.availability === 'active'}+ >+ {m.swarm_node_activate()}+ </DropdownMenu.Item>+ <DropdownMenu.Separator />+ <DropdownMenu.Item variant="destructive" onclick={() => removeNode(item)} disabled={!isAdmin || isLoading}>+ <TrashIcon class="size-4" />+ {m.common_delete()}+ </DropdownMenu.Item>+ </DropdownMenu.Group>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+{/snippet}++<ArcaneTable+ persistKey="arcane-swarm-nodes-table"+ items={nodes}+ bind:requestOptions+ bind:mobileFieldVisibility+ selectionDisabled={true}+ onRefresh={async (options) => (nodes = await swarmService.getNodes(options))}+ {columns}+ {mobileFields}+ rowActions={RowActions}+ mobileCard={NodeMobileCardSnippet}+/>++<SwarmNodeAgentDialog+ bind:open={isAgentDialogOpen}+ node={selectedNode}+ deployment={agentDeployment}+ errorMessage={agentDeploymentError}+ isLoading={isAgentDeploymentLoading}+ onRefresh={refreshAgentDeployment}+ onRegenerate={regenerateAgentDeployment}+/>diff --git a/frontend/src/routes/(app)/swarm/nodes/swarm-node-agent-dialog.svelte b/frontend/src/routes/(app)/swarm/nodes/swarm-node-agent-dialog.sveltenew file mode 100644index 000000000..c6cadc427--- /dev/null+++ b/frontend/src/routes/(app)/swarm/nodes/swarm-node-agent-dialog.svelte@@ -0,0 +1,116 @@+<script lang="ts">+ import * as Alert from '$lib/components/ui/alert';+ import { ArcaneButton } from '$lib/components/arcane-button';+ import * as ResponsiveDialog from '$lib/components/ui/responsive-dialog';+ import { Snippet } from '$lib/components/ui/snippet';+ import { Spinner } from '$lib/components/ui/spinner';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import { AlertTriangleIcon, EdgeConnectionIcon } from '$lib/icons';+ import { m } from '$lib/paraglide/messages';+ import type { SwarmNodeAgentDeployment, SwarmNodeSummary } from '$lib/types/swarm.type';+ import { getSwarmNodeAgentLabel, getSwarmNodeAgentVariant } from './agent-status';++ type SwarmNodeAgentDialogProps = {+ open: boolean;+ node: SwarmNodeSummary | null;+ deployment: SwarmNodeAgentDeployment | null;+ errorMessage?: string;+ isLoading?: boolean;+ onRefresh?: () => void | Promise<void>;+ onRegenerate?: () => void | Promise<void>;+ };++ let {+ open = $bindable(false),+ node = null,+ deployment = null,+ errorMessage = '',+ isLoading = false,+ onRefresh,+ onRegenerate+ }: SwarmNodeAgentDialogProps = $props();++ const agentStatus = $derived(deployment?.agent ?? node?.agent ?? { state: 'none' as const });+ const agentStatusLabel = $derived(getSwarmNodeAgentLabel(agentStatus.state));+ const isReady = $derived(!!deployment && !isLoading);+</script>++<ResponsiveDialog.Root+ bind:open+ title={node ? m.swarm_node_agent_dialog_title({ name: node.hostname }) : m.swarm_node_agent_deploy()}+ description={m.swarm_node_agent_dialog_description()}+ contentClass="sm:max-w-3xl"+>+ {#snippet children()}+ <div class="space-y-5 py-6">+ <Alert.Root class="border-primary/20 bg-primary/5">+ <EdgeConnectionIcon class="size-4" />+ <Alert.Title>{m.swarm_node_agent_dialog_blurb_title()}</Alert.Title>+ <Alert.Description>{m.swarm_node_agent_dialog_blurb_description()}</Alert.Description>+ </Alert.Root>++ <div class="grid gap-3 sm:grid-cols-2">+ <div class="bg-muted/40 rounded-lg border p-4">+ <div class="text-muted-foreground text-xs font-medium tracking-wide uppercase">{m.common_status()}</div>+ <div class="mt-2 flex items-center gap-2">+ <StatusBadge text={agentStatusLabel} variant={getSwarmNodeAgentVariant(agentStatus.state)} />+ </div>+ </div>++ <div class="bg-muted/40 rounded-lg border p-4">+ <div class="text-muted-foreground text-xs font-medium tracking-wide uppercase">+ {m.swarm_node_agent_environment_id()}+ </div>+ <div class="mt-2 font-mono text-sm break-all">{deployment?.environmentId ?? agentStatus.environmentId ?? '—'}</div>+ </div>+ </div>++ {#if errorMessage}+ <Alert.Root variant="destructive">+ <AlertTriangleIcon class="size-4" />+ <Alert.Title>{m.common_action_failed()}</Alert.Title>+ <Alert.Description>{errorMessage}</Alert.Description>+ </Alert.Root>+ {/if}++ {#if isLoading && !deployment}+ <div class="flex items-center justify-center py-10">+ <Spinner class="size-6" />+ </div>+ {:else if isReady && deployment}+ <div class="space-y-4">+ <div class="space-y-2">+ <div class="text-sm font-medium">{m.environments_docker_run_command()}</div>+ <Snippet text={deployment.dockerRun} />+ </div>++ <div class="space-y-2">+ <div class="text-sm font-medium">{m.environments_docker_compose()}</div>+ <Snippet text={deployment.dockerCompose} />+ </div>+ </div>+ {/if}+ </div>+ {/snippet}++ {#snippet footer()}+ <div class="flex w-full flex-col gap-2 sm:flex-row sm:justify-end">+ <ArcaneButton+ action="base"+ tone="outline"+ customLabel={m.environments_regenerate_api_key()}+ onclick={onRegenerate}+ loading={isLoading}+ disabled={!node || isLoading}+ />+ <ArcaneButton+ action="base"+ customLabel={m.swarm_node_agent_refresh_status()}+ onclick={onRefresh}+ loading={isLoading}+ disabled={!node || isLoading}+ />+ <ArcaneButton action="base" customLabel={m.common_done()} onclick={() => (open = false)} />+ </div>+ {/snippet}+</ResponsiveDialog.Root>diff --git a/frontend/src/routes/(app)/swarm/secrets/+page.svelte b/frontend/src/routes/(app)/swarm/secrets/+page.sveltenew file mode 100644index 000000000..5ce1a03ed--- /dev/null+++ b/frontend/src/routes/(app)/swarm/secrets/+page.svelte@@ -0,0 +1,269 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { Input } from '$lib/components/ui/input/index.js';+ import { Textarea } from '$lib/components/ui/textarea/index.js';+ import { CopyButton } from '$lib/components/ui/copy-button';+ import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';+ import { LockIcon, TrashIcon } from '$lib/icons';+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import userStore from '$lib/stores/user-store';+ import type { SwarmSecretSummary } from '$lib/types/swarm.type';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';+ import { fromStore } from 'svelte/store';+ import { toast } from 'svelte-sonner';+ import { formatDistanceToNow } from 'date-fns';+ import { openConfirmDialog } from '$lib/components/confirm-dialog';++ const storeUser = fromStore(userStore);+ const isAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));++ let secrets = $state<SwarmSecretSummary[]>([]);+ let selectedSecretId = $state('');+ let createName = $state('');+ let createData = $state('');+ let editName = $state('');+ let editData = $state('');+ let isLoading = $state({+ refresh: false,+ create: false,+ delete: false+ });++ const selectedSecret = $derived(secrets.find((secret) => secret.id === selectedSecretId) ?? null);++ function getSpecName(spec: Record<string, unknown> | null | undefined, fallback: string): string {+ const name = spec && typeof spec === 'object' ? (spec as Record<string, unknown>).Name : undefined;+ return typeof name === 'string' && name.trim() ? name : fallback.slice(0, 12);+ }++ function decodeBase64ToText(base64Value: string): string {+ try {+ const binary = atob(base64Value);+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));+ return new TextDecoder().decode(bytes);+ } catch {+ return '';+ }+ }++ function encodeTextToBase64(value: string): string {+ const bytes = new TextEncoder().encode(value);+ let binary = '';+ for (const byte of bytes) {+ binary += String.fromCharCode(byte);+ }+ return btoa(binary);+ }++ function formatTimestamp(timestamp: string): string {+ if (!timestamp) return m.common_unknown();+ return formatDistanceToNow(new Date(timestamp), { addSuffix: true });+ }++ function selectSecret(secret: SwarmSecretSummary) {+ selectedSecretId = secret.id;+ const spec = (secret.spec ?? {}) as Record<string, unknown>;+ editName = typeof spec.Name === 'string' ? spec.Name : '';+ editData = typeof spec.Data === 'string' ? decodeBase64ToText(spec.Data) : '';+ }++ function clearSelectedSecret() {+ selectedSecretId = '';+ editName = '';+ editData = '';+ }++ function toggleSecret(secret: SwarmSecretSummary) {+ if (selectedSecretId === secret.id) {+ clearSelectedSecret();+ return;+ }++ selectSecret(secret);+ }++ async function refresh() {+ isLoading.refresh = true;+ try {+ secrets = await swarmService.getSecrets();+ if (selectedSecretId && !secrets.some((secret) => secret.id === selectedSecretId)) {+ clearSelectedSecret();+ }+ } finally {+ isLoading.refresh = false;+ }+ }++ useEnvironmentRefresh(refresh);++ $effect(() => {+ refresh();+ });++ async function createSecret() {+ const name = createName.trim();+ if (!name) {+ toast.error(m.swarm_secrets_name_required());+ return;+ }+ const spec: Record<string, unknown> = {+ Name: name,+ Data: encodeTextToBase64(createData)+ };++ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.createSecret({ spec })),+ message: m.swarm_secrets_create_failed(),+ setLoadingState: (value) => (isLoading.create = value),+ onSuccess: async (created) => {+ toast.success(m.swarm_secrets_create_success({ name: getSpecName(created.spec, created.id) }));+ createName = '';+ createData = '';+ await refresh();+ selectSecret(created);+ }+ });+ }++ function removeSecret(secret: SwarmSecretSummary) {+ const name = getSpecName(secret.spec, secret.id);+ openConfirmDialog({+ title: m.common_delete_title({ resource: m.swarm_secret() }),+ message: m.swarm_secrets_delete_confirm({ name }),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.removeSecret(secret.id)),+ message: m.swarm_secrets_delete_failed({ name }),+ setLoadingState: (value) => (isLoading.delete = value),+ onSuccess: async () => {+ toast.success(m.swarm_secrets_delete_success({ name }));+ await refresh();+ }+ });+ }+ }+ });+ }++ const actionButtons: ActionButton[] = $derived([+ {+ id: 'refresh',+ action: 'restart',+ label: m.common_refresh(),+ onclick: refresh,+ loading: isLoading.refresh,+ disabled: isLoading.refresh+ }+ ]);++ const statCards: StatCardConfig[] = $derived([+ {+ title: m.swarm_secrets_title(),+ value: secrets.length,+ icon: LockIcon,+ iconColor: 'text-blue-500'+ }+ ]);+</script>++<ResourcePageLayout+ title={m.swarm_secrets_title()}+ subtitle={m.swarm_secrets_subtitle()}+ icon={LockIcon}+ {actionButtons}+ {statCards}+>+ {#snippet mainContent()}+ <div class="grid gap-4 lg:grid-cols-[1fr,1.1fr]">+ <Card.Root class="pt-0">+ <Card.Header>+ <Card.Title>{m.swarm_secrets_create_title()}</Card.Title>+ <Card.Description>{m.swarm_secrets_create_subtitle()}</Card.Description>+ </Card.Header>+ <Card.Content class="space-y-3 pb-6">+ <Input placeholder={m.swarm_secrets_name_placeholder()} bind:value={createName} />+ <Textarea+ rows={10}+ bind:value={createData}+ placeholder={m.swarm_secrets_data_placeholder()}+ class="font-mono text-xs"+ />+ <ArcaneButton+ action="create"+ customLabel={m.swarm_secrets_create_button()}+ onclick={createSecret}+ disabled={!isAdmin || isLoading.create}+ loading={isLoading.create}+ />+ </Card.Content>+ </Card.Root>++ <div class="space-y-4">+ <Card.Root class="pt-0">+ <Card.Header>+ <Card.Title>{m.swarm_secrets_list_title()}</Card.Title>+ <Card.Description>{m.swarm_secrets_list_subtitle()}</Card.Description>+ </Card.Header>+ <Card.Content class="space-y-3 pb-6">+ {#if secrets.length === 0}+ <div class="text-muted-foreground py-8 text-center text-sm">{m.swarm_secrets_empty()}</div>+ {:else}+ {#each secrets as secret (secret.id)}+ <Card.Root class="overflow-hidden border py-0">+ <button+ type="button"+ class={`w-full px-4 py-3 text-left transition-colors ${selectedSecretId === secret.id ? 'bg-muted/50' : 'hover:bg-muted/40'}`}+ onclick={() => toggleSecret(secret)}+ >+ <div class="flex items-center justify-between gap-2">+ <div class="min-w-0">+ <div class="truncate font-medium">{getSpecName(secret.spec, secret.id)}</div>+ <div class="text-muted-foreground font-mono text-xs">{secret.id}</div>+ </div>+ <div class="text-muted-foreground shrink-0 text-xs">{formatTimestamp(secret.updatedAt)}</div>+ </div>+ </button>++ {#if selectedSecretId === secret.id}+ <div class="space-y-3 border-t px-4 pt-4 pb-5">+ <div class="flex items-center gap-2">+ <div class="text-muted-foreground font-mono text-xs">{secret.id}</div>+ <CopyButton text={secret.id} />+ </div>+ <p class="text-muted-foreground text-sm">{m.swarm_secrets_immutable_notice()}</p>+ <Input placeholder={m.swarm_secrets_name_placeholder()} bind:value={editName} readonly />+ <Textarea+ rows={12}+ bind:value={editData}+ placeholder={m.swarm_secrets_data_placeholder()}+ class="font-mono text-xs"+ readonly+ />+ <div class="flex flex-wrap items-center gap-2 pt-1">+ <ArcaneButton+ action="remove"+ customLabel={m.swarm_secrets_delete_button()}+ icon={TrashIcon}+ onclick={() => removeSecret(secret)}+ disabled={!isAdmin || isLoading.delete}+ loading={isLoading.delete}+ />+ </div>+ </div>+ {/if}+ </Card.Root>+ {/each}+ {/if}+ </Card.Content>+ </Card.Root>+ </div>+ </div>+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/swarm/services/+page.svelte b/frontend/src/routes/(app)/swarm/services/+page.sveltenew file mode 100644index 000000000..5ff38bd63--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/+page.svelte@@ -0,0 +1,88 @@+<script lang="ts">+ import { DockIcon } from '$lib/icons';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import { toast } from 'svelte-sonner';+ import { untrack } from 'svelte';+ import { tryCatch } from '$lib/utils/try-catch';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';+ import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';+ import { parallelRefresh } from '$lib/utils/refresh.util';+ import type { SwarmServiceCreateSpec } from '$lib/types/swarm.type';+ import SwarmServicesTable from './services-table.svelte';+ import CreateServiceDialog from '$lib/components/dialogs/create-service-dialog.svelte';++ let { data } = $props();++ let services = $state(untrack(() => data.services));+ let requestOptions = $state(untrack(() => data.requestOptions));+ let isLoading = $state({ refresh: false, creating: false });+ let showCreateDialog = $state(false);++ async function refresh() {+ await parallelRefresh(+ {+ services: {+ fetch: () => swarmService.getServices(requestOptions),+ onSuccess: (data) => {+ services = data;+ },+ errorMessage: m.common_refresh_failed({ resource: m.swarm_services_title() })+ }+ },+ (v) => (isLoading.refresh = v)+ );+ }++ useEnvironmentRefresh(refresh);++ const totalServices = $derived(services?.pagination?.totalItems ?? services?.data?.length ?? 0);++ async function handleCreateService(spec: SwarmServiceCreateSpec) {+ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.createService({ spec })),+ message: m.common_create_failed({ resource: `${m.swarm_service()} "${spec.Name}"` }),+ setLoadingState: (v) => (isLoading.creating = v),+ onSuccess: async () => {+ toast.success(m.common_create_success({ resource: `${m.swarm_service()} "${spec.Name}"` }));+ showCreateDialog = false;+ await refresh();+ }+ });+ }++ const actionButtons: ActionButton[] = $derived([+ {+ id: 'create',+ action: 'create',+ label: m.common_create_button({ resource: m.swarm_service() }),+ onclick: () => (showCreateDialog = true)+ },+ {+ id: 'refresh',+ action: 'restart',+ label: m.common_refresh(),+ onclick: refresh,+ loading: isLoading.refresh,+ disabled: isLoading.refresh+ }+ ]);++ const statCards: StatCardConfig[] = $derived([+ {+ title: m.swarm_services_total(),+ value: totalServices,+ icon: DockIcon,+ iconColor: 'text-blue-500'+ }+ ]);+</script>++<CreateServiceDialog bind:open={showCreateDialog} onSubmit={handleCreateService} isLoading={isLoading.creating} />++<ResourcePageLayout title={m.swarm_services_title()} subtitle={m.swarm_services_subtitle()} {actionButtons} {statCards}>+ {#snippet mainContent()}+ <SwarmServicesTable bind:services bind:requestOptions />+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/swarm/services/+page.ts b/frontend/src/routes/(app)/swarm/services/+page.tsnew file mode 100644index 000000000..67ecc8112--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/+page.ts@@ -0,0 +1,24 @@+import { swarmService } from '$lib/services/swarm-service';+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';+import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';+import type { PageLoad } from './$types';++export const load: PageLoad = async () => {+ const requestOptions = resolveInitialTableRequest('arcane-swarm-services-table', {+ pagination: {+ page: 1,+ limit: 20+ },+ sort: {+ column: 'name',+ direction: 'asc'+ }+ } satisfies SearchPaginationSortRequest);++ const services = await swarmService.getServices(requestOptions);++ return {+ services,+ requestOptions+ };+};diff --git a/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.svelte b/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.sveltenew file mode 100644index 000000000..c570d12b5--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.svelte@@ -0,0 +1,419 @@+<script lang="ts">+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { invalidateAll, goto } from '$app/navigation';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import { m } from '$lib/paraglide/messages';+ import TabbedPageLayout from '$lib/layouts/tabbed-page-layout.svelte';+ import { type TabItem } from '$lib/components/tab-bar/index.js';+ import * as Tabs from '$lib/components/ui/tabs/index.js';+ 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 { swarmService } from '$lib/services/swarm-service';+ import type {+ RawServiceNetworkAttachment,+ RawServiceVirtualIP,+ RawSwarmServiceMount,+ RawSwarmServicePort,+ ServiceNetworkAttachment,+ ServiceNetworkDetail,+ ServiceVirtualIP,+ SwarmServiceInspect,+ SwarmServiceMount,+ SwarmServicePort+ } from '$lib/types/swarm.type';+ import ServiceEditorDialog from '../service-editor-dialog.svelte';+ import ServiceOverview from '../components/ServiceOverview.svelte';+ import ServiceLogsPanel from '../components/ServiceLogsPanel.svelte';+ import ServiceTasksPanel from '../components/ServiceTasksPanel.svelte';+ import ServiceConfiguration from '../components/ServiceConfiguration.svelte';+ import ServiceNetwork from '../components/ServiceNetwork.svelte';+ import ServiceStorage from '../components/ServiceStorage.svelte';+ import { Input } from '$lib/components/ui/input/index.js';+ import {+ ArrowLeftIcon,+ AlertIcon,+ DockIcon,+ FileTextIcon,+ JobsIcon,+ SettingsIcon,+ NetworksIcon,+ VolumesIcon,+ EditIcon,+ RedeployIcon,+ TrashIcon+ } from '$lib/icons';++ let { data } = $props();+ let service = $derived(data?.service as SwarmServiceInspect);++ let userSelectedTab = $state<string>('overview');+ let userScaleReplicas = $state<number | null>(null);+ let userScaleReplicasServiceId = $state<string | null>(null);+ let isRefreshing = $state(false);+ let isLoading = $state({ update: false, rollback: false, remove: false, scale: false });++ // Editor state+ let editOpen = $state(false);++ type ServiceContainerSpecShape = {+ Image?: string;+ Env?: string[];+ Mounts?: RawSwarmServiceMount[];+ Command?: string[];+ Args?: string[];+ Dir?: string;+ User?: string;+ Hostname?: string;+ };++ type ServiceSpecShape = {+ Name?: string;+ Labels?: Record<string, string>;+ Mode?: {+ Replicated?: { Replicas?: number };+ Global?: unknown;+ };+ TaskTemplate?: {+ ContainerSpec?: ServiceContainerSpecShape;+ Networks?: RawServiceNetworkAttachment[];+ };+ };++ // Parse spec fields+ const spec = $derived(service?.spec as ServiceSpecShape | undefined);+ const containerSpec = $derived(spec?.TaskTemplate?.ContainerSpec);+ const serviceName = $derived(spec?.Name || '');+ const serviceImage = $derived(containerSpec?.Image || '');++ const serviceMode = $derived.by(() => {+ if (spec?.Mode?.Replicated) return 'replicated';+ if (spec?.Mode?.Global !== undefined) return 'global';+ return 'unknown';+ });++ const desiredReplicas = $derived.by(() => {+ if (serviceMode === 'global') return 0;+ return spec?.Mode?.Replicated?.Replicas ?? 1;+ });+ const scaleReplicas = $derived.by(() => {+ if (userScaleReplicasServiceId === service?.id && userScaleReplicas !== null) return userScaleReplicas;+ return desiredReplicas;+ });++ const envVars = $derived(containerSpec?.Env || []);+ const labels = $derived(spec?.Labels || {});++ function normalizeMount(mount: RawSwarmServiceMount): SwarmServiceMount {+ return {+ type: mount.type ?? mount.Type ?? 'volume',+ source: mount.source ?? mount.Source ?? '',+ target: mount.target ?? mount.Target ?? '',+ readOnly: mount.readOnly ?? mount.ReadOnly ?? false,+ volumeDriver: mount.volumeDriver ?? mount.VolumeDriver,+ volumeOptions: mount.volumeOptions ?? mount.VolumeOptions,+ devicePath: mount.devicePath ?? mount.DevicePath+ };+ }++ function normalizePort(port: RawSwarmServicePort): SwarmServicePort {+ return {+ protocol: port.protocol ?? port.Protocol ?? 'tcp',+ targetPort: port.targetPort ?? port.TargetPort ?? 0,+ publishedPort: port.publishedPort ?? port.PublishedPort ?? undefined,+ publishMode: port.publishMode ?? port.PublishMode ?? undefined+ };+ }++ function normalizeNetworkAttachment(network: RawServiceNetworkAttachment): ServiceNetworkAttachment {+ return {+ target: network.target ?? network.Target ?? '',+ aliases: network.aliases ?? network.Aliases ?? []+ };+ }++ function normalizeVirtualIP(vip: RawServiceVirtualIP): ServiceVirtualIP {+ return {+ networkID: vip.networkID ?? vip.NetworkID ?? '',+ addr: vip.addr ?? vip.Addr ?? ''+ };+ }++ const mounts = $derived<SwarmServiceMount[]>(service?.mounts ?? (containerSpec?.Mounts ?? []).map(normalizeMount));+ const command = $derived(containerSpec?.Command || []);+ const args = $derived(containerSpec?.Args || []);+ const workingDir = $derived(containerSpec?.Dir || '');+ const user = $derived(containerSpec?.User || '');+ const hostname = $derived(containerSpec?.Hostname || '');++ const endpointPorts = $derived<SwarmServicePort[]>(+ ((service?.endpoint?.Ports as RawSwarmServicePort[] | undefined) ?? []).map(normalizePort)+ );+ const specNetworks = $derived<ServiceNetworkAttachment[]>((spec?.TaskTemplate?.Networks ?? []).map(normalizeNetworkAttachment));+ const virtualIPs = $derived<ServiceVirtualIP[]>(+ ((service?.endpoint?.VirtualIPs as RawServiceVirtualIP[] | undefined) ?? []).map(normalizeVirtualIP)+ );+ const networkDetails = $derived<Record<string, ServiceNetworkDetail>>(service?.networkDetails ?? {});++ const hasEnvVars = $derived(envVars.length > 0);+ const hasLabels = $derived(Object.keys(labels).length > 0);+ const hasAdvancedConfig = $derived(command.length > 0 || args.length > 0 || !!workingDir || !!user || !!hostname);+ const showConfiguration = $derived(hasEnvVars || hasLabels || hasAdvancedConfig);+ const hasPorts = $derived(endpointPorts.length > 0);+ const hasNetworks = $derived(specNetworks.length > 0 || virtualIPs.length > 0);+ const showNetworkTab = $derived(hasPorts || hasNetworks);+ const hasMounts = $derived(mounts.length > 0);++ const tabItems = $derived<TabItem[]>([+ { value: 'overview', label: m.common_overview(), icon: DockIcon },+ { value: 'logs', label: m.common_logs(), icon: FileTextIcon },+ { value: 'tasks', label: m.swarm_tasks_title(), icon: JobsIcon },+ ...(showConfiguration ? [{ value: 'config', label: m.common_configuration(), icon: SettingsIcon }] : []),+ ...(showNetworkTab ? [{ value: 'network', label: m.containers_nav_networks(), icon: NetworksIcon }] : []),+ ...(hasMounts ? [{ value: 'storage', label: m.containers_nav_storage(), icon: VolumesIcon }] : [])+ ]);++ const selectedTab = $derived.by(() => {+ if (tabItems.some((tab) => tab.value === userSelectedTab)) return userSelectedTab;+ return tabItems[0]?.value ?? 'overview';+ });++ function onTabChange(value: string) {+ userSelectedTab = value;+ }++ function onScaleReplicasInput(event: Event) {+ const input = event.currentTarget as HTMLInputElement;+ userScaleReplicasServiceId = service?.id ?? null;+ userScaleReplicas = Number(input.value);+ }++ async function refreshData() {+ isRefreshing = true;+ await invalidateAll();+ setTimeout(() => {+ isRefreshing = false;+ }, 500);+ }++ // Editor+ const editVersion = $derived(service?.version?.index ?? service?.version?.Index ?? 0);+ const editSpec = $derived(JSON.stringify(spec ?? {}, null, 2));++ function openEdit() {+ editOpen = true;+ }++ async function handleUpdate(payload: { spec: Record<string, unknown>; options?: Record<string, unknown> }) {+ if (!service?.id) return;+ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.updateService(service.id, { version: editVersion, ...payload })),+ message: m.common_update_failed({ resource: `${m.swarm_service()} "${serviceName}"` }),+ setLoadingState: (v) => (isLoading.update = v),+ onSuccess: async () => {+ toast.success(m.common_update_success({ resource: `${m.swarm_service()} "${serviceName}"` }));+ editOpen = false;+ await refreshData();+ }+ });+ }++ function handleRollback() {+ openConfirmDialog({+ title: m.swarm_service_rollback_title(),+ message: m.swarm_service_rollback_confirm({ name: serviceName }),+ confirm: {+ label: m.swarm_service_rollback(),+ destructive: false,+ action: async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.rollbackService(service.id)),+ message: m.swarm_service_rollback_failed({ name: serviceName }),+ setLoadingState: (v) => (isLoading.rollback = v),+ onSuccess: async () => {+ toast.success(m.swarm_service_rollback_success({ name: serviceName }));+ await refreshData();+ }+ });+ }+ }+ });+ }++ function handleDelete() {+ openConfirmDialog({+ title: m.common_delete_title({ resource: m.swarm_service() }),+ message: m.common_delete_confirm({ resource: m.swarm_service() }),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.removeService(service.id)),+ message: m.common_delete_failed({ resource: `${m.swarm_service()} "${serviceName}"` }),+ setLoadingState: (v) => (isLoading.remove = v),+ onSuccess: async () => {+ toast.success(m.common_delete_success({ resource: `${m.swarm_service()} "${serviceName}"` }));+ goto('/swarm/services');+ }+ });+ }+ }+ });+ }++ async function handleScale() {+ if (!service?.id || serviceMode !== 'replicated') return;+ const replicas = Math.max(0, Number(scaleReplicas) || 0);+ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.scaleService(service.id, { replicas })),+ message: m.common_update_failed({ resource: `${m.swarm_service()} "${serviceName}"` }),+ setLoadingState: (v) => (isLoading.scale = v),+ onSuccess: async () => {+ toast.success(m.swarm_service_scale_success({ name: serviceName, replicas }));+ await refreshData();+ }+ });+ }+</script>++{#if service}+ <TabbedPageLayout backUrl="/swarm/services" backLabel={m.common_back()} {tabItems} {selectedTab} {onTabChange}>+ {#snippet headerInfo()}+ <div class="flex items-center gap-2">+ <div class="bg-primary/10 flex size-9 items-center justify-center rounded-full">+ <DockIcon class="text-primary size-5" />+ </div>+ <h1 class="max-w-[300px] truncate text-lg font-semibold" title={serviceName}>+ {serviceName}+ </h1>+ <StatusBadge+ variant={serviceMode === 'replicated' ? 'blue' : serviceMode === 'global' ? 'green' : 'gray'}+ text={serviceMode}+ />+ {#if serviceMode === 'replicated'}+ <span class="text-muted-foreground font-mono text-sm">+ {desiredReplicas}+ {m.swarm_replicas()}+ </span>+ {/if}+ </div>+ {/snippet}++ {#snippet headerActions()}+ <div class="flex items-center gap-2">+ {#if serviceMode === 'replicated'}+ <div class="flex items-center gap-2">+ <Input+ type="number"+ min="0"+ step="1"+ value={scaleReplicas}+ oninput={onScaleReplicasInput}+ class="h-8 w-20"+ disabled={isLoading.scale}+ />+ <ArcaneButton action="base" tone="outline" size="sm" onclick={handleScale} disabled={isLoading.scale}>+ {m.swarm_service_scale()}+ </ArcaneButton>+ </div>+ {/if}+ <ArcaneButton action="base" tone="outline" size="sm" onclick={openEdit} disabled={isLoading.update}>+ <EditIcon class="size-4" />+ <span class="hidden sm:inline">{m.common_edit()}</span>+ </ArcaneButton>+ <ArcaneButton action="base" tone="outline" size="sm" onclick={handleRollback} disabled={isLoading.rollback}>+ <RedeployIcon class="size-4" />+ <span class="hidden sm:inline">{m.swarm_service_rollback()}</span>+ </ArcaneButton>+ <ArcaneButton action="base" tone="outline-destructive" size="sm" onclick={handleDelete} disabled={isLoading.remove}>+ <TrashIcon class="size-4" />+ <span class="hidden sm:inline">{m.common_delete()}</span>+ </ArcaneButton>+ </div>+ {/snippet}++ {#snippet tabContent(activeTab)}+ <Tabs.Content value="overview" class="h-full">+ <ServiceOverview {service} {serviceName} {serviceImage} {serviceMode} {desiredReplicas} {labels} />+ </Tabs.Content>++ <Tabs.Content value="logs" class="h-full">+ {#if selectedTab === 'logs'}+ <ServiceLogsPanel serviceId={service.id} />+ {/if}+ </Tabs.Content>++ <Tabs.Content value="tasks" class="h-full">+ {#if selectedTab === 'tasks'}+ <ServiceTasksPanel {serviceName} serviceId={service.id} />+ {/if}+ </Tabs.Content>++ {#if showConfiguration}+ <Tabs.Content value="config" class="h-full">+ <ServiceConfiguration+ {envVars}+ {labels}+ {command}+ {args}+ {workingDir}+ {user}+ {hostname}+ {hasEnvVars}+ {hasLabels}+ {hasAdvancedConfig}+ />+ </Tabs.Content>+ {/if}++ {#if showNetworkTab}+ <Tabs.Content value="network" class="h-full">+ <ServiceNetwork ports={endpointPorts} networks={specNetworks} {virtualIPs} {networkDetails} />+ </Tabs.Content>+ {/if}++ {#if hasMounts}+ <Tabs.Content value="storage" class="h-full">+ <ServiceStorage {mounts} />+ </Tabs.Content>+ {/if}+ {/snippet}+ </TabbedPageLayout>++ {#if editOpen}+ <ServiceEditorDialog+ bind:open={editOpen}+ title={`${m.common_edit()} ${m.swarm_service()}`}+ description={m.common_edit_description()}+ submitLabel={m.common_save()}+ initialSpec={editSpec}+ isLoading={isLoading.update}+ onSubmit={handleUpdate}+ />+ {/if}+{:else}+ <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">+ <AlertIcon class="text-muted-foreground size-10" />+ </div>+ <h2 class="mb-3 text-2xl font-medium">+ {m.common_not_found_title({ resource: m.swarm_service() })}+ </h2>+ <p class="text-muted-foreground mb-8 max-w-md text-center">+ {m.common_not_found_description({ resource: m.swarm_service().toLowerCase() })}+ </p>+ <div class="flex justify-center gap-4">+ <ArcaneButton action="base" href="/swarm/services">+ <ArrowLeftIcon class="size-4" />+ {m.common_back_to({ resource: m.swarm_services_title() })}+ </ArcaneButton>+ <ArcaneButton action="refresh" onclick={refreshData}>+ {m.common_retry()}+ </ArcaneButton>+ </div>+ </div>+ </div>+{/if}diff --git a/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.ts b/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.tsnew file mode 100644index 000000000..e0e9ae94b--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.ts@@ -0,0 +1,23 @@+import type { PageLoad } from './$types';+import { error } from '@sveltejs/kit';+import { swarmService } from '$lib/services/swarm-service';++export const load: PageLoad = async ({ params }) => {+ const serviceId = params.serviceId;++ try {+ const service = await swarmService.getService(serviceId);++ if (!service) {+ throw error(404, 'Service not found');+ }++ return { service };+ } catch (err: any) {+ console.error('Failed to load service:', err);+ if (err.status === 404) {+ throw err;+ }+ throw error(500, err.message || 'Failed to load service details');+ }+};diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceConfiguration.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceConfiguration.sveltenew file mode 100644index 000000000..b7a761ef1--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceConfiguration.svelte@@ -0,0 +1,170 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card';+ import { m } from '$lib/paraglide/messages';+ import { SettingsIcon, TagIcon } from '$lib/icons';++ interface Props {+ envVars: string[];+ labels: Record<string, string>;+ command: string[];+ args: string[];+ workingDir: string;+ user: string;+ hostname: string;+ hasEnvVars: boolean;+ hasLabels: boolean;+ hasAdvancedConfig: boolean;+ }++ let { envVars, labels, command, args, workingDir, user, hostname, hasEnvVars, hasLabels, hasAdvancedConfig }: Props = $props();+</script>++<div class="space-y-6">+ {#if hasEnvVars}+ <Card.Root>+ <Card.Header icon={SettingsIcon}>+ <div class="flex flex-col space-y-1.5">+ <Card.Title>+ <h2>{m.common_environment_variables()}</h2>+ </Card.Title>+ </div>+ </Card.Header>+ <Card.Content class="p-4">+ <div class="grid grid-cols-1 gap-3 lg:grid-cols-2 2xl:grid-cols-3">+ {#each envVars as env, index (index)}+ {#if env.includes('=')}+ {@const [key, ...valueParts] = env.split('=')}+ {@const value = valueParts.join('=')}+ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide break-all uppercase">+ {key}+ </div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {value}+ </div>+ </Card.Content>+ </Card.Root>+ {:else}+ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">{m.common_name()}</div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {env}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}+ {/each}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}++ {#if hasLabels}+ <Card.Root>+ <Card.Header icon={TagIcon}>+ <div class="flex flex-col space-y-1.5">+ <Card.Title>+ <h2>{m.common_labels()}</h2>+ </Card.Title>+ <Card.Description>{m.common_labels_description({ resource: m.swarm_service() })}</Card.Description>+ </div>+ </Card.Header>+ <Card.Content class="p-4">+ <div class="grid grid-cols-1 gap-3 lg:grid-cols-2 2xl:grid-cols-3">+ {#each Object.entries(labels) as [key, value] (key)}+ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide break-all uppercase">+ {key}+ </div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {value?.toString() || ''}+ </div>+ </Card.Content>+ </Card.Root>+ {/each}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}++ {#if hasAdvancedConfig}+ <Card.Root>+ <Card.Header icon={SettingsIcon}>+ <div class="flex flex-col space-y-1.5">+ <Card.Title>+ <h2>{m.common_advanced()}</h2>+ </Card.Title>+ </div>+ </Card.Header>+ <Card.Content class="p-4">+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ {#if command.length > 0}+ <Card.Root variant="subtle" class="sm:col-span-2 lg:col-span-3 xl:col-span-4">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">+ {m.common_command()}+ </div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {command.join(' ')}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}++ {#if args.length > 0}+ <Card.Root variant="subtle" class="sm:col-span-2 lg:col-span-3 xl:col-span-4">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">+ {m.common_args()}+ </div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {args.join(' ')}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}++ {#if workingDir}+ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">+ {m.common_working_directory()}+ </div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {workingDir}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}++ {#if user}+ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">+ {m.resource_user_cap()}+ </div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium select-all">+ {user}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}++ {#if hostname}+ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">{m.swarm_hostname()}</div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium select-all">+ {hostname}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}+</div>diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceLogsPanel.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceLogsPanel.sveltenew file mode 100644index 000000000..d367c0df2--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceLogsPanel.svelte@@ -0,0 +1,97 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card';+ import LogViewer from '$lib/components/logs/log-viewer.svelte';+ import LogControls from '$lib/components/logs/log-controls.svelte';+ import { m } from '$lib/paraglide/messages';+ import { FileTextIcon } from '$lib/icons';++ let {+ serviceId+ }: {+ serviceId: string | undefined;+ } = $props();++ let isStreaming = $state(false);+ let viewer = $state<LogViewer>();+ let autoScroll = $state(true);+ let autoStartLogs = $state(false);+ let showParsedJson = $state(false);++ function handleStart() {+ viewer?.startLogStream();+ }++ function handleStop() {+ viewer?.stopLogStream();+ }++ function handleClear() {+ viewer?.clearLogs();+ }++ async function handleRefresh() {+ await viewer?.clearLogs({ hard: true, restart: true });+ }++ function handleStreamStart() {+ isStreaming = true;+ }++ function handleStreamStop() {+ isStreaming = false;+ }++ $effect(() => {+ if (autoStartLogs && !isStreaming && serviceId && viewer) {+ viewer.startLogStream();+ }+ });+</script>++<Card.Root>+ <Card.Header icon={FileTextIcon}>+ <div class="flex flex-1 flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">+ <div class="flex flex-col gap-1.5">+ <div class="flex items-center gap-2">+ <Card.Title>+ <h2>{m.swarm_service_logs_title()}</h2>+ </Card.Title>+ {#if isStreaming}+ <div class="flex items-center gap-2">+ <div class="size-2 animate-pulse rounded-full bg-green-500"></div>+ <span class="text-xs font-semibold text-green-600 sm:text-sm">{m.common_live()}</span>+ </div>+ {/if}+ </div>+ </div>+ <LogControls+ bind:autoScroll+ bind:autoStartLogs+ bind:showParsedJson+ {isStreaming}+ disabled={!serviceId}+ onStart={handleStart}+ onStop={handleStop}+ onClear={handleClear}+ onRefresh={handleRefresh}+ />+ </div>+ </Card.Header>+ <Card.Content class="p-0">+ <div class="bg-card/90 rounded-lg border p-0 backdrop-blur-sm">+ <LogViewer+ bind:this={viewer}+ bind:autoScroll+ type="service"+ {serviceId}+ {showParsedJson}+ maxLines={500}+ showTimestamps={true}+ height="calc(100vh - 320px)"+ onStart={handleStreamStart}+ onStop={handleStreamStop}+ onClear={handleClear}+ />+ </div>+ </Card.Content>+</Card.Root>diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceNetwork.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceNetwork.sveltenew file mode 100644index 000000000..6881152e1--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceNetwork.svelte@@ -0,0 +1,307 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import { m } from '$lib/paraglide/messages';+ import { NetworksIcon, GlobeIcon } from '$lib/icons';+ import type { ServiceNetworkAttachment, ServiceNetworkDetail, ServiceVirtualIP, SwarmServicePort } from '$lib/types/swarm.type';++ interface Props {+ ports: SwarmServicePort[];+ networks: ServiceNetworkAttachment[];+ virtualIPs: ServiceVirtualIP[];+ networkDetails: Record<string, ServiceNetworkDetail>;+ }++ let { ports, networks, virtualIPs, networkDetails }: Props = $props();++ function formatPort(port: SwarmServicePort): string {+ const protocol = port.protocol || 'tcp';+ const target = port.targetPort || 0;+ const published = port.publishedPort || 0;+ const mode = port.publishMode || '';+ if (published) {+ return `${published}:${target}/${protocol}${mode ? ` (${mode})` : ''}`;+ }+ return `${target}/${protocol}`;+ }++ // Match the network detail page's color convention for driver badges+ function driverVariant(driver: string): 'blue' | 'purple' | 'amber' | 'green' | 'gray' {+ if (driver === 'overlay') return 'blue';+ if (driver === 'macvlan') return 'purple';+ if (driver === 'bridge') return 'green';+ if (driver === 'host') return 'amber';+ return 'gray';+ }++ // Build a map of network ID → VIP address+ const vipMap = $derived.by(() => {+ const map: Record<string, string> = {};+ for (const vip of virtualIPs) {+ const id = vip.networkID;+ const addr = vip.addr;+ if (id && addr) map[id] = addr;+ }+ return map;+ });+</script>++<div class="space-y-6">+ <Card.Root>+ <Card.Header icon={GlobeIcon}>+ <div class="flex flex-col space-y-1.5">+ <Card.Title>+ <h2>{m.common_port_mappings()}</h2>+ </Card.Title>+ </div>+ </Card.Header>+ <Card.Content class="p-4">+ {#if ports.length > 0}+ <div class="flex flex-wrap gap-2">+ {#each ports as port (`${port.publishedPort ?? 'internal'}:${port.targetPort}/${port.protocol}:${port.publishMode ?? ''}`)}+ <StatusBadge text={formatPort(port)} variant="gray" size="md" minWidth="none" />+ {/each}+ </div>+ {:else}+ <div class="text-muted-foreground rounded-lg border border-dashed py-12 text-center">+ <div class="text-sm">{m.containers_no_ports()}</div>+ </div>+ {/if}+ </Card.Content>+ </Card.Root>++ <Card.Root>+ <Card.Header icon={NetworksIcon}>+ <div class="flex flex-col space-y-1.5">+ <Card.Title>+ <h2>{m.swarm_networks()}</h2>+ </Card.Title>+ </div>+ </Card.Header>+ <Card.Content class="p-4">+ {#if networks.length > 0 || virtualIPs.length > 0}+ <div class="grid grid-cols-1 gap-4">+ {#each networks as network (network.target)}+ {@const networkId = network.target}+ {@const aliases = network.aliases}+ {@const vip = vipMap[networkId]}+ {@const info = networkDetails[networkId]}+ <Card.Root variant="subtle">+ <Card.Content class="p-4">+ <div class="border-border mb-4 flex items-center gap-3 border-b pb-4">+ <div class="rounded-lg bg-blue-500/10 p-2">+ <NetworksIcon class="size-5 text-blue-500" />+ </div>+ <div class="min-w-0 flex-1">+ <div class="text-foreground text-base font-semibold break-all">+ {info?.name ?? (aliases.length > 0 ? aliases[0] : networkId.slice(0, 12))}+ </div>+ <div class="mt-1 flex flex-wrap items-center gap-2">+ {#if info?.driver}+ <StatusBadge text={info.driver} variant={driverVariant(info.driver)} />+ {/if}+ {#if info?.scope}+ <StatusBadge text={info.scope} variant="gray" />+ {/if}+ {#if info?.internal}+ <StatusBadge text={m.internal()} variant="blue" />+ {/if}+ {#if info?.attachable}+ <StatusBadge text={m.attachable()} variant="green" />+ {/if}+ {#if info?.ingress}+ <StatusBadge text={m.ingress()} variant="cyan" />+ {/if}+ {#if info?.configOnly}+ <StatusBadge text={m.config_only()} variant="pink" />+ {/if}+ {#if info?.configFrom}+ <span class="text-muted-foreground text-xs">{info.configFrom}</span>+ {/if}+ </div>+ </div>+ </div>++ <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">+ {#if vip}+ <Card.Root variant="outlined">+ <Card.Content class="flex flex-col p-3">+ <div class="text-muted-foreground mb-2 text-xs font-semibold">{m.networks_service_vip_label()}</div>+ <code+ class="bg-muted text-muted-foreground cursor-pointer rounded px-1.5 py-0.5 font-mono text-sm break-all select-all"+ >+ {vip}+ </code>+ </Card.Content>+ </Card.Root>+ {/if}++ <Card.Root variant="outlined">+ <Card.Content class="flex flex-col p-3">+ <div class="text-muted-foreground mb-2 text-xs font-semibold">{m.common_id()}</div>+ <code+ class="bg-muted text-muted-foreground cursor-pointer rounded px-1.5 py-0.5 font-mono text-xs break-all select-all sm:text-sm"+ >+ {networkId}+ </code>+ </Card.Content>+ </Card.Root>++ {#if aliases.length > 0}+ <Card.Root variant="outlined">+ <Card.Content class="flex flex-col p-3">+ <div class="text-muted-foreground mb-2 text-xs font-semibold">+ {m.containers_aliases()}+ </div>+ <div class="space-y-1">+ {#each aliases as alias (alias)}+ <code+ class="bg-muted text-muted-foreground cursor-pointer rounded px-1.5 py-0.5 font-mono text-xs break-all select-all sm:text-sm"+ >+ {alias}+ </code>+ {/each}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}++ {#if info?.configNetwork}+ <Card.Root variant="outlined" class="sm:col-span-2">+ <Card.Content class="p-3">+ <div class="border-border mb-3 flex items-center justify-between border-b pb-3">+ <div>+ <div class="text-foreground text-sm font-semibold">+ {m.config_only()}: {info.configNetwork.name}+ </div>+ <div class="mt-1 flex flex-wrap items-center gap-1.5">+ {#if info.configNetwork.driver}+ <StatusBadge text={info.configNetwork.driver} variant="gray" size="sm" minWidth="none" />+ {/if}+ {#if info.configNetwork.scope}+ <StatusBadge text={info.configNetwork.scope} variant="gray" size="sm" minWidth="none" />+ {/if}+ {#if info.configNetwork.options?.parent}+ <span class="text-muted-foreground text-xs">{info.configNetwork.options.parent}</span>+ {/if}+ </div>+ </div>+ <div class="flex items-center gap-2">+ <StatusBadge+ text={info.configNetwork.enableIPv4 ? m.ipv4_enabled() : m.common_disabled()}+ variant={info.configNetwork.enableIPv4 ? 'indigo' : 'gray'}+ size="sm"+ minWidth="none"+ />+ <StatusBadge+ text={info.configNetwork.enableIPv6 ? m.ipv6_enabled() : m.common_disabled()}+ variant={info.configNetwork.enableIPv6 ? 'indigo' : 'gray'}+ size="sm"+ minWidth="none"+ />+ </div>+ </div>+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">+ {#if info.configNetwork.ipv4Configs && info.configNetwork.ipv4Configs.length > 0}+ {#each info.configNetwork.ipv4Configs as cfg (`${cfg.subnet ?? ''}:${cfg.gateway ?? ''}:${cfg.ipRange ?? ''}`)}+ <div class="bg-muted/30 space-y-1 rounded-lg p-2.5">+ <div class="text-muted-foreground mb-1 text-xs font-semibold">{m.ipv4_enabled()}</div>+ {#if cfg.subnet}+ <div class="flex flex-col sm:flex-row sm:items-center">+ <span class="text-muted-foreground w-full text-sm font-medium sm:w-16"+ >{m.common_subnet()}:</span+ >+ <code+ class="bg-muted text-muted-foreground cursor-pointer rounded px-1.5 py-0.5 font-mono text-xs break-all select-all sm:text-sm"+ >+ {cfg.subnet}+ </code>+ </div>+ {/if}+ {#if cfg.gateway}+ <div class="flex flex-col sm:flex-row sm:items-center">+ <span class="text-muted-foreground w-full text-sm font-medium sm:w-16"+ >{m.common_gateway()}:</span+ >+ <code+ class="bg-muted text-muted-foreground cursor-pointer rounded px-1.5 py-0.5 font-mono text-xs break-all select-all sm:text-sm"+ >+ {cfg.gateway}+ </code>+ </div>+ {/if}+ {#if cfg.ipRange}+ <div class="flex flex-col sm:flex-row sm:items-center">+ <span class="text-muted-foreground w-full text-sm font-medium sm:w-16"+ >{m.networks_ipam_iprange_label()}:</span+ >+ <code+ class="bg-muted text-muted-foreground cursor-pointer rounded px-1.5 py-0.5 font-mono text-xs break-all select-all sm:text-sm"+ >+ {cfg.ipRange}+ </code>+ </div>+ {/if}+ </div>+ {/each}+ {/if}+ {#if info.configNetwork.ipv6Configs && info.configNetwork.ipv6Configs.length > 0}+ {#each info.configNetwork.ipv6Configs as cfg (`${cfg.subnet ?? ''}:${cfg.gateway ?? ''}:${cfg.ipRange ?? ''}`)}+ <div class="bg-muted/30 space-y-1 rounded-lg p-2.5">+ <div class="text-muted-foreground mb-1 text-xs font-semibold">{m.ipv6_enabled()}</div>+ {#if cfg.subnet}+ <div class="flex flex-col sm:flex-row sm:items-center">+ <span class="text-muted-foreground w-full text-sm font-medium sm:w-16"+ >{m.common_subnet()}:</span+ >+ <code+ class="bg-muted text-muted-foreground cursor-pointer rounded px-1.5 py-0.5 font-mono text-xs break-all select-all sm:text-sm"+ >+ {cfg.subnet}+ </code>+ </div>+ {/if}+ {#if cfg.gateway}+ <div class="flex flex-col sm:flex-row sm:items-center">+ <span class="text-muted-foreground w-full text-sm font-medium sm:w-16"+ >{m.common_gateway()}:</span+ >+ <code+ class="bg-muted text-muted-foreground cursor-pointer rounded px-1.5 py-0.5 font-mono text-xs break-all select-all sm:text-sm"+ >+ {cfg.gateway}+ </code>+ </div>+ {/if}+ {#if cfg.ipRange}+ <div class="flex flex-col sm:flex-row sm:items-center">+ <span class="text-muted-foreground w-full text-sm font-medium sm:w-16"+ >{m.networks_ipam_iprange_label()}:</span+ >+ <code+ class="bg-muted text-muted-foreground cursor-pointer rounded px-1.5 py-0.5 font-mono text-xs break-all select-all sm:text-sm"+ >+ {cfg.ipRange}+ </code>+ </div>+ {/if}+ </div>+ {/each}+ {/if}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}+ </div>+ </Card.Content>+ </Card.Root>+ {/each}+ </div>+ {:else}+ <div class="text-muted-foreground rounded-lg border border-dashed py-12 text-center">+ <div class="text-sm">{m.containers_no_networks_connected()}</div>+ </div>+ {/if}+ </Card.Content>+ </Card.Root>+</div>diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceOverview.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceOverview.sveltenew file mode 100644index 000000000..f00fadf93--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceOverview.svelte@@ -0,0 +1,204 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import { m } from '$lib/paraglide/messages';+ import type { SwarmServiceInspect } from '$lib/types/swarm.type';+ import { format, formatDistanceToNow } from 'date-fns';+ import { InfoIcon, ConnectionIcon } from '$lib/icons';+ import { truncateImageDigest } from '$lib/utils/string.utils';++ interface Props {+ service: SwarmServiceInspect;+ serviceName: string;+ serviceImage: string;+ serviceMode: string;+ desiredReplicas: number;+ labels: Record<string, string>;+ }++ let { service, serviceName, serviceImage, serviceMode, desiredReplicas, labels }: Props = $props();++ function formatDate(input: string | undefined | null, fmt = 'PP p'): string {+ if (!input) return m.common_na();+ try {+ return format(new Date(input), fmt);+ } catch {+ return m.common_na();+ }+ }++ function formatRelative(input: string | undefined | null): string {+ if (!input) return m.common_na();+ try {+ return formatDistanceToNow(new Date(input), { addSuffix: true });+ } catch {+ return m.common_na();+ }+ }++ const stackName = $derived(labels?.['com.docker.stack.namespace'] || '');+ const nodes = $derived((service?.nodes as string[]) || []);+ const versionIndex = $derived(service?.version?.index ?? service?.version?.Index ?? 0);+ const updateStatus = $derived(service?.updateStatus as Record<string, any> | null | undefined);+</script>++<Card.Root>+ <Card.Header icon={InfoIcon}>+ <div class="flex flex-col space-y-1.5">+ <Card.Title>+ <h2>{m.common_overview()}</h2>+ </Card.Title>+ <Card.Description>{m.common_details_description({ resource: m.swarm_service() })}</Card.Description>+ </div>+ </Card.Header>+ <Card.Content class="p-4">+ <div class="mb-6 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">+ <div>+ <div class="text-muted-foreground mb-2 text-xs font-semibold tracking-wide uppercase">+ {m.common_name()}+ </div>+ <div class="text-foreground cursor-pointer text-base font-semibold break-all select-all">+ {serviceName}+ </div>+ </div>++ <div>+ <div class="text-muted-foreground mb-2 text-xs font-semibold tracking-wide uppercase">+ {m.swarm_stack()}+ </div>+ <div class="text-foreground text-base font-semibold">+ {stackName || m.common_na()}+ </div>+ </div>++ <div>+ <div class="text-muted-foreground mb-2 text-xs font-semibold tracking-wide uppercase">+ {m.swarm_mode()} / {m.swarm_replicas()}+ </div>+ <div class="flex items-center gap-2">+ <StatusBadge+ variant={serviceMode === 'replicated' ? 'blue' : serviceMode === 'global' ? 'green' : 'gray'}+ text={serviceMode}+ />+ {#if serviceMode === 'replicated'}+ <span class="text-foreground font-mono text-sm">+ {desiredReplicas}+ {m.swarm_replicas()}+ </span>+ {/if}+ </div>+ </div>+ </div>++ <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">+ {m.common_image()}+ </div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {truncateImageDigest(serviceImage) || m.common_na()}+ </div>+ </Card.Content>+ </Card.Root>++ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">+ {m.common_version()}+ </div>+ <div class="text-foreground font-mono text-sm font-medium">+ {versionIndex}+ </div>+ </Card.Content>+ </Card.Root>++ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">+ {m.common_id()}+ </div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {service.id}+ </div>+ </Card.Content>+ </Card.Root>++ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">+ {m.common_created()}+ </div>+ <div class="text-foreground text-sm font-medium">+ {formatRelative(service.createdAt)}+ </div>+ <div class="text-muted-foreground text-xs">+ {formatDate(service.createdAt)}+ </div>+ </Card.Content>+ </Card.Root>++ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">+ {m.common_updated()}+ </div>+ <div class="text-foreground text-sm font-medium">+ {formatRelative(service.updatedAt)}+ </div>+ <div class="text-muted-foreground text-xs">+ {formatDate(service.updatedAt)}+ </div>+ </Card.Content>+ </Card.Root>++ <Card.Root variant="subtle">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">+ {m.swarm_nodes_column()}+ </div>+ {#if nodes.length > 0}+ <div class="flex flex-wrap gap-1.5">+ {#each nodes as node}+ <div class="flex items-center gap-1">+ <ConnectionIcon class="text-muted-foreground size-3" />+ <span class="text-foreground text-sm font-medium">{node}</span>+ </div>+ {/each}+ </div>+ {:else}+ <span class="text-muted-foreground text-sm">{m.common_na()}</span>+ {/if}+ </Card.Content>+ </Card.Root>++ {#if updateStatus?.State}+ <Card.Root variant="subtle" class="sm:col-span-2">+ <Card.Content class="flex flex-col gap-2 p-4">+ <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">{m.common_status()}</div>+ <div class="flex items-center gap-2">+ <StatusBadge+ variant={updateStatus.State === 'completed'+ ? 'green'+ : updateStatus.State === 'updating'+ ? 'amber'+ : updateStatus.State === 'paused'+ ? 'amber'+ : 'red'}+ text={updateStatus.State}+ />+ {#if updateStatus.Message}+ <span class="text-muted-foreground text-sm">{updateStatus.Message}</span>+ {/if}+ </div>+ {#if updateStatus.CompletedAt}+ <div class="text-muted-foreground text-xs">+ {formatRelative(updateStatus.CompletedAt)}+ </div>+ {/if}+ </Card.Content>+ </Card.Root>+ {/if}+ </div>+ </Card.Content>+</Card.Root>diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceStorage.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceStorage.sveltenew file mode 100644index 000000000..c54fa5b01--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceStorage.svelte@@ -0,0 +1,163 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card';+ import { Badge } from '$lib/components/ui/badge';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import { m } from '$lib/paraglide/messages';+ import { VolumesIcon, TerminalIcon, FolderOpenIcon } from '$lib/icons';+ import type { SwarmServiceMount } from '$lib/types/swarm.type';++ interface Props {+ mounts: SwarmServiceMount[];+ }++ let { mounts }: Props = $props();++ function getMountType(mount: SwarmServiceMount): string {+ return mount.type || 'volume';+ }++ function getMountSource(mount: SwarmServiceMount): string {+ return mount.source || '';+ }++ function getMountTarget(mount: SwarmServiceMount): string {+ return mount.target || '';+ }++ function getMountReadOnly(mount: SwarmServiceMount): boolean {+ return mount.readOnly || false;+ }++ function isBindBackedVolume(mount: SwarmServiceMount): boolean {+ const opts = mount.volumeOptions;+ return opts?.type === 'none' && opts?.o === 'bind';+ }++ function getMountLabel(type: string): string {+ if (type === 'bind') return m.containers_mount_type_bind();+ if (type === 'tmpfs') return m.containers_mount_type_tmpfs();+ return m.containers_mount_type_volume();+ }++ function getMountIconColor(type: string, mount: SwarmServiceMount): { bg: string; text: string } {+ if (type === 'bind' || (type === 'volume' && isBindBackedVolume(mount))) {+ return { bg: 'bg-blue-500/10', text: 'text-blue-500' };+ }+ if (type === 'volume') return { bg: 'bg-purple-500/10', text: 'text-purple-500' };+ return { bg: 'bg-amber-500/10', text: 'text-amber-500' };+ }+</script>++<div class="space-y-6">+ <Card.Root>+ <Card.Header icon={VolumesIcon}>+ <div class="flex flex-col space-y-1.5">+ <Card.Title>+ <h2>{m.containers_nav_storage()}</h2>+ </Card.Title>+ </div>+ </Card.Header>+ <Card.Content class="p-4">+ {#if mounts.length > 0}+ <div class="grid grid-cols-1 gap-4 lg:grid-cols-2 xl:grid-cols-3">+ {#each mounts as mount, i (i)}+ {@const type = getMountType(mount)}+ {@const source = getMountSource(mount)}+ {@const target = getMountTarget(mount)}+ {@const readOnly = getMountReadOnly(mount)}+ {@const iconColor = getMountIconColor(type, mount)}+ {@const bindBacked = type === 'volume' && isBindBackedVolume(mount)}+ <Card.Root variant="subtle">+ <Card.Content class="p-4">+ <div class="border-border mb-4 flex items-center justify-between border-b pb-4">+ <div class="flex items-center gap-3">+ <div class="rounded-lg p-2 {iconColor.bg}">+ {#if type === 'volume' && !bindBacked}+ <VolumesIcon class="size-5 {iconColor.text}" />+ {:else if type === 'bind' || bindBacked}+ <FolderOpenIcon class="size-5 {iconColor.text}" />+ {:else}+ <TerminalIcon class="size-5 {iconColor.text}" />+ {/if}+ </div>+ <div class="min-w-0 flex-1">+ <div class="text-foreground text-base font-semibold break-all">+ {type === 'tmpfs' ? m.containers_mount_type_tmpfs() : source || m.image_update_auth_anonymous()}+ </div>+ <div class="mt-1 flex flex-wrap items-center gap-1.5">+ <span class="text-muted-foreground text-xs">{getMountLabel(type)}</span>+ {#if mount.volumeDriver}+ <StatusBadge text={mount.volumeDriver} variant="gray" size="sm" minWidth="none" />+ {/if}+ </div>+ </div>+ </div>+ <Badge variant={readOnly ? 'secondary' : 'outline'} class="text-xs font-semibold">+ {readOnly ? m.common_ro() : m.common_rw()}+ </Badge>+ </div>++ <div class="grid grid-cols-1 gap-3">+ <Card.Root variant="outlined">+ <Card.Content class="flex flex-col p-3">+ <div class="text-muted-foreground mb-2 text-xs font-semibold">+ {m.containers_mount_label_container()}+ </div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {target}+ </div>+ </Card.Content>+ </Card.Root>++ {#if source && type !== 'tmpfs'}+ <Card.Root variant="outlined">+ <Card.Content class="flex flex-col p-3">+ <div class="text-muted-foreground mb-2 text-xs font-semibold">+ {type === 'volume' ? m.containers_mount_label_volume() : m.containers_mount_label_host()}+ </div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {source}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}++ {#if bindBacked && mount.volumeOptions?.device}+ <Card.Root variant="outlined">+ <Card.Content class="flex flex-col p-3">+ <div class="text-muted-foreground mb-2 text-xs font-semibold">{m.dashboard_meter_gpu_device()}:</div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {mount.volumeOptions.device}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}++ {#if mount.devicePath}+ <Card.Root variant="outlined">+ <Card.Content class="flex flex-col p-3">+ <div class="text-muted-foreground mb-2 text-xs font-semibold">+ {bindBacked ? m.containers_mount_label_volume() : m.containers_mount_label_host()}+ </div>+ <div class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all">+ {mount.devicePath}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}+ </div>+ </Card.Content>+ </Card.Root>+ {/each}+ </div>+ {:else}+ <div class="rounded-lg border border-dashed py-12 text-center">+ <div class="bg-muted/30 mx-auto mb-4 flex size-16 items-center justify-center rounded-full">+ <VolumesIcon class="text-muted-foreground size-6" />+ </div>+ <div class="text-muted-foreground text-sm">{m.containers_no_mounts_configured()}</div>+ </div>+ {/if}+ </Card.Content>+ </Card.Root>+</div>diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.sveltenew file mode 100644index 000000000..e7001e3cb--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte@@ -0,0 +1,142 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import type { SwarmTaskSummary } from '$lib/types/swarm.type';+ import { JobsIcon, ConnectionIcon } from '$lib/icons';++ let {+ serviceName,+ serviceId+ }: {+ serviceName: string;+ serviceId: string;+ } = $props();++ let tasks = $state<SwarmTaskSummary[]>([]);+ let isLoading = $state(false);+ let hasLoaded = $state(false);++ const STATE_ORDER: Record<string, number> = {+ running: 0,+ starting: 1,+ pending: 2,+ ready: 3,+ complete: 4,+ shutdown: 5,+ failed: 6,+ rejected: 7,+ orphaned: 8,+ remove: 9+ };++ function stateVariant(state: string): 'green' | 'amber' | 'red' | 'gray' {+ if (state === 'running') return 'green';+ if (state === 'pending' || state === 'starting') return 'amber';+ if (state === 'failed' || state === 'rejected' || state === 'shutdown') return 'red';+ return 'gray';+ }++ function sortTasks(raw: SwarmTaskSummary[]): SwarmTaskSummary[] {+ return [...raw].sort((a, b) => {+ const stateA = STATE_ORDER[a.currentState] ?? 99;+ const stateB = STATE_ORDER[b.currentState] ?? 99;+ if (stateA !== stateB) return stateA - stateB;+ return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();+ });+ }++ async function loadTasks() {+ isLoading = true;+ try {+ const result = await swarmService.getServiceTasks(serviceId, {+ pagination: { page: 1, limit: 100 }+ });+ tasks = sortTasks(result.data ?? []);+ } catch (err) {+ console.error(m.swarm_service_tasks_load_failed_log(), err);+ } finally {+ isLoading = false;+ hasLoaded = true;+ }+ }++ $effect(() => {+ if (serviceName && serviceId && !hasLoaded) {+ loadTasks();+ }+ });+</script>++<Card.Root>+ <Card.Header icon={JobsIcon}>+ <div class="flex flex-1 items-center justify-between">+ <div class="flex flex-col gap-1.5">+ <Card.Title>+ <h2>{m.swarm_tasks_title()}</h2>+ </Card.Title>+ <Card.Description>+ {m.swarm_service_tasks_count({ count: tasks.length })}+ </Card.Description>+ </div>+ <ArcaneButton action="refresh" size="sm" onclick={loadTasks} disabled={isLoading}>+ {m.common_refresh()}+ </ArcaneButton>+ </div>+ </Card.Header>+ <Card.Content class="p-4">+ {#if isLoading && !hasLoaded}+ <div class="text-muted-foreground py-12 text-center text-sm">{m.swarm_service_tasks_loading()}</div>+ {:else if tasks.length === 0}+ <div class="text-muted-foreground rounded-lg border border-dashed py-12 text-center">+ <div class="bg-muted/30 mx-auto mb-4 flex size-16 items-center justify-center rounded-full">+ <JobsIcon class="text-muted-foreground size-6" />+ </div>+ <div class="text-sm">{m.swarm_service_tasks_empty()}</div>+ </div>+ {:else}+ <div class="grid grid-cols-1 gap-3 lg:grid-cols-2 xl:grid-cols-3">+ {#each tasks as task (task.id)}+ <Card.Root variant="subtle">+ <Card.Content class="p-4">+ <div class="border-border mb-3 flex items-center justify-between border-b pb-3">+ <div class="min-w-0 flex-1">+ <div class="text-foreground truncate text-sm font-semibold" title={task.name}>+ {task.name}+ </div>+ <div class="text-muted-foreground font-mono text-xs">{task.id.slice(0, 12)}</div>+ </div>+ <StatusBadge text={task.currentState} variant={stateVariant(task.currentState)} />+ </div>+ <div class="grid grid-cols-2 gap-2">+ <div>+ <div class="text-muted-foreground mb-1 text-xs font-semibold">+ {m.swarm_node()}+ </div>+ <div class="flex items-center gap-1">+ <ConnectionIcon class="text-muted-foreground size-3" />+ <span class="text-foreground truncate text-sm">{task.nodeName || m.common_na()}</span>+ </div>+ </div>+ <div>+ <div class="text-muted-foreground mb-1 text-xs font-semibold">+ {m.swarm_desired_state()}+ </div>+ <StatusBadge text={task.desiredState} variant={stateVariant(task.desiredState)} size="sm" />+ </div>+ {#if task.error}+ <div class="col-span-2">+ <div class="text-muted-foreground mb-1 text-xs font-semibold">{m.common_error()}</div>+ <div class="text-sm break-all text-red-400">{task.error}</div>+ </div>+ {/if}+ </div>+ </Card.Content>+ </Card.Root>+ {/each}+ </div>+ {/if}+ </Card.Content>+</Card.Root>diff --git a/frontend/src/routes/(app)/swarm/services/service-editor-dialog.svelte b/frontend/src/routes/(app)/swarm/services/service-editor-dialog.sveltenew file mode 100644index 000000000..73f0d1a3e--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/service-editor-dialog.svelte@@ -0,0 +1,564 @@+<script lang="ts">+ import { ResponsiveDialog } from '$lib/components/ui/responsive-dialog/index.js';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { Input } from '$lib/components/ui/input/index.js';+ import * as Select from '$lib/components/ui/select/index.js';+ import { preventDefault } from '$lib/utils/form.utils';+ import { m } from '$lib/paraglide/messages';+ import { AddIcon, TrashIcon } from '$lib/icons';+ import * as Accordion from '$lib/components/ui/accordion/index.js';+ import FormInput from '$lib/components/form/form-input.svelte';+ import { untrack } from 'svelte';++ type ServiceEditorPayload = {+ spec: Record<string, unknown>;+ options?: Record<string, unknown>;+ };++ type ServiceEditorDialogProps = {+ open: boolean;+ title: string;+ description: string;+ submitLabel: string;+ submitAction?: 'save' | 'create' | 'update';+ initialSpec: string;+ isLoading: boolean;+ onSubmit: (payload: ServiceEditorPayload) => void;+ };++ type TextFieldState = {+ value: string;+ error: string;+ };++ type ServiceEditorMode = 'replicated' | 'global';++ type ServicePortDraft = {+ target: string;+ published: string;+ protocol: 'tcp' | 'udp';+ };++ type ServiceEnvDraft = {+ key: string;+ value: string;+ };++ type ServiceMountDraft = {+ type: 'volume' | 'bind';+ source: string;+ target: string;+ };++ type ServiceLabelDraft = {+ key: string;+ value: string;+ };++ type SwarmServiceMountRaw = {+ Type?: string;+ Source?: string;+ Target?: string;+ };++ type SwarmServicePortRaw = {+ TargetPort?: number;+ PublishedPort?: number;+ Protocol?: string;+ };++ type SwarmServiceSpecRaw = {+ Name?: string;+ Mode?: {+ Replicated?: {+ Replicas?: number;+ };+ Global?: Record<string, unknown>;+ };+ TaskTemplate?: {+ ContainerSpec?: {+ Image?: string;+ Command?: string[];+ Args?: string[];+ Dir?: string;+ User?: string;+ Hostname?: string;+ Env?: string[];+ Mounts?: SwarmServiceMountRaw[];+ };+ };+ Labels?: Record<string, string>;+ EndpointSpec?: {+ Ports?: SwarmServicePortRaw[];+ };+ };++ type ServiceEditorFormState = {+ name: TextFieldState;+ image: TextFieldState;+ mode: ServiceEditorMode;+ replicas: TextFieldState;+ command: TextFieldState;+ args: TextFieldState;+ workingDir: TextFieldState;+ user: TextFieldState;+ hostname: TextFieldState;+ ports: ServicePortDraft[];+ envVars: ServiceEnvDraft[];+ mounts: ServiceMountDraft[];+ labels: ServiceLabelDraft[];+ baseSpec: Record<string, unknown>;+ };++ let {+ open = $bindable(false),+ title,+ description,+ submitLabel,+ submitAction = 'save',+ initialSpec,+ isLoading,+ onSubmit+ }: ServiceEditorDialogProps = $props();++ function asRecord(value: unknown): Record<string, unknown> | undefined {+ return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;+ }++ function createTextField(value = ''): TextFieldState {+ return { value, error: '' };+ }++ function createEmptyFormState(): ServiceEditorFormState {+ return {+ name: createTextField(),+ image: createTextField(),+ mode: 'replicated',+ replicas: createTextField('1'),+ command: createTextField(),+ args: createTextField(),+ workingDir: createTextField(),+ user: createTextField(),+ hostname: createTextField(),+ ports: [],+ envVars: [],+ mounts: [],+ labels: [],+ baseSpec: {}+ };+ }++ function normalizeMountType(value: string | undefined): 'volume' | 'bind' {+ return value === 'bind' ? 'bind' : 'volume';+ }++ function normalizePortProtocol(value: string | undefined): 'tcp' | 'udp' {+ return value === 'udp' ? 'udp' : 'tcp';+ }++ function parseInitialSpec(specText: string): SwarmServiceSpecRaw | null {+ if (!specText.trim()) return null;++ try {+ const parsed = JSON.parse(specText) as unknown;+ return asRecord(parsed) as SwarmServiceSpecRaw;+ } catch (error) {+ console.error('Failed to parse service spec:', error);+ return null;+ }+ }++ function createFormState(spec: SwarmServiceSpecRaw | null): ServiceEditorFormState {+ if (!spec) return createEmptyFormState();++ const containerSpec = spec.TaskTemplate?.ContainerSpec;+ const mode: ServiceEditorMode = spec.Mode?.Global ? 'global' : 'replicated';++ return {+ name: createTextField(spec.Name ?? ''),+ image: createTextField(containerSpec?.Image ?? ''),+ mode,+ replicas: createTextField(String(spec.Mode?.Replicated?.Replicas ?? 1)),+ command: createTextField(containerSpec?.Command?.join(' ') ?? ''),+ args: createTextField(containerSpec?.Args?.join(' ') ?? ''),+ workingDir: createTextField(containerSpec?.Dir ?? ''),+ user: createTextField(containerSpec?.User ?? ''),+ hostname: createTextField(containerSpec?.Hostname ?? ''),+ ports:+ spec.EndpointSpec?.Ports?.map((port) => ({+ target: String(port.TargetPort ?? ''),+ published: port.PublishedPort ? String(port.PublishedPort) : '',+ protocol: normalizePortProtocol(port.Protocol)+ })) ?? [],+ envVars:+ containerSpec?.Env?.map((envEntry) => {+ const [key, ...valueParts] = envEntry.split('=');+ return { key, value: valueParts.join('=') };+ }) ?? [],+ mounts:+ containerSpec?.Mounts?.map((mount) => ({+ type: normalizeMountType(mount.Type),+ source: mount.Source ?? '',+ target: mount.Target ?? ''+ })) ?? [],+ labels: spec.Labels ? Object.entries(spec.Labels).map(([key, value]) => ({ key, value: String(value) })) : [],+ baseSpec: structuredClone(spec as Record<string, unknown>)+ };+ }++ let form = $state<ServiceEditorFormState>(untrack(() => createFormState(parseInitialSpec(initialSpec))));++ function ensureRecord(parent: Record<string, unknown>, key: string): Record<string, unknown> {+ const existing = asRecord(parent[key]);+ if (existing) return existing;+ const created: Record<string, unknown> = {};+ parent[key] = created;+ return created;+ }++ function assignOptional(target: Record<string, unknown>, key: string, value: string) {+ const trimmed = value.trim();+ if (trimmed) {+ target[key] = trimmed;+ return;+ }+ delete target[key];+ }++ function addPort() {+ form.ports = [...form.ports, { target: '', published: '', protocol: 'tcp' }];+ }++ function removePort(index: number) {+ form.ports = form.ports.filter((_, i) => i !== index);+ }++ function addEnvVar() {+ form.envVars = [...form.envVars, { key: '', value: '' }];+ }++ function removeEnvVar(index: number) {+ form.envVars = form.envVars.filter((_, i) => i !== index);+ }++ function addMount() {+ form.mounts = [...form.mounts, { type: 'volume', source: '', target: '' }];+ }++ function removeMount(index: number) {+ form.mounts = form.mounts.filter((_, i) => i !== index);+ }++ function addLabel() {+ form.labels = [...form.labels, { key: '', value: '' }];+ }++ function removeLabel(index: number) {+ form.labels = form.labels.filter((_, i) => i !== index);+ }++ function handleSubmit() {+ // Validation+ if (!form.name.value.trim()) {+ form.name.error = m.common_name_required();+ return;+ }+ if (!form.image.value.trim()) {+ form.image.error = m.swarm_service_form_image_required();+ return;+ }++ const spec = structuredClone(form.baseSpec ?? {});+ spec.Name = form.name.value.trim();++ const taskTemplate = ensureRecord(spec, 'TaskTemplate');+ const containerSpec = ensureRecord(taskTemplate, 'ContainerSpec');+ containerSpec.Image = form.image.value.trim();++ spec.Mode =+ form.mode === 'replicated'+ ? { Replicated: { Replicas: Math.max(0, parseInt(form.replicas.value, 10) || 1) } }+ : { Global: {} };++ // Add optional container config+ const commandParts = form.command.value.trim().split(' ').filter(Boolean);+ if (commandParts.length > 0) {+ containerSpec.Command = commandParts;+ } else {+ delete containerSpec.Command;+ }++ const argParts = form.args.value.trim().split(' ').filter(Boolean);+ if (argParts.length > 0) {+ containerSpec.Args = argParts;+ } else {+ delete containerSpec.Args;+ }++ assignOptional(containerSpec, 'Dir', form.workingDir.value);+ assignOptional(containerSpec, 'User', form.user.value);+ assignOptional(containerSpec, 'Hostname', form.hostname.value);++ // Add environment variables+ const filteredEnvVars = form.envVars.filter((entry) => entry.key.trim());+ if (filteredEnvVars.length > 0) {+ containerSpec.Env = filteredEnvVars.map((entry) => `${entry.key}=${entry.value}`);+ } else {+ delete containerSpec.Env;+ }++ // Add mounts+ const filteredMounts = form.mounts.filter((mount) => mount.source.trim() && mount.target.trim());+ if (filteredMounts.length > 0) {+ containerSpec.Mounts = filteredMounts.map((mount) => ({+ Type: mount.type,+ Source: mount.source,+ Target: mount.target+ }));+ } else {+ delete containerSpec.Mounts;+ }++ // Add labels+ const filteredLabels = form.labels.filter((label) => label.key.trim());+ if (filteredLabels.length > 0) {+ const nextLabels: Record<string, string> = {};+ filteredLabels.forEach((label) => {+ nextLabels[label.key] = label.value;+ });+ spec.Labels = nextLabels;+ } else {+ delete spec.Labels;+ }++ // Add ports+ const filteredPorts = form.ports.filter((port) => port.target.trim());+ if (filteredPorts.length > 0) {+ const endpointSpec = ensureRecord(spec, 'EndpointSpec');+ endpointSpec.Ports = filteredPorts.map((port) => ({+ TargetPort: parseInt(port.target, 10),+ PublishedPort: port.published ? parseInt(port.published, 10) : undefined,+ Protocol: port.protocol+ }));+ } else {+ const endpointSpec = asRecord(spec.EndpointSpec);+ if (endpointSpec) {+ delete endpointSpec.Ports;+ }+ }++ onSubmit({ spec });+ }++ function handleOpenChange(newOpenState: boolean) {+ open = newOpenState;+ }+</script>++<ResponsiveDialog bind:open onOpenChange={handleOpenChange} variant="sheet" {title} {description} contentClass="sm:max-w-[600px]">+ {#snippet children()}+ <form onsubmit={preventDefault(handleSubmit)} class="space-y-6 py-4">+ <!-- Basic Config -->+ <div class="space-y-4">+ <FormInput input={form.name} label={m.common_name()} placeholder="my-service" disabled={isLoading} />+ <FormInput+ input={form.image}+ label={m.swarm_service_form_image_label()}+ placeholder={m.swarm_service_form_image_placeholder()}+ disabled={isLoading}+ />+ </div>++ <div class="grid grid-cols-2 gap-4">+ <FormInput label={m.swarm_mode()}>+ {#snippet children()}+ <Select.Root type="single" bind:value={form.mode} disabled={isLoading}>+ <Select.Trigger class="w-full">+ <span class="capitalize"+ >{form.mode === 'replicated' ? m.swarm_service_mode_replicated() : m.swarm_service_mode_global()}</span+ >+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="replicated" label={m.swarm_service_mode_replicated()}+ >{m.swarm_service_mode_replicated()}</Select.Item+ >+ <Select.Item value="global" label={m.swarm_service_mode_global()}>{m.swarm_service_mode_global()}</Select.Item>+ </Select.Content>+ </Select.Root>+ {/snippet}+ </FormInput>++ {#if form.mode === 'replicated'}+ <FormInput input={form.replicas} label={m.swarm_replicas()} type="number" disabled={isLoading} />+ {/if}+ </div>++ <!-- Advanced Options -->+ <Accordion.Root class="w-full space-y-5" type="multiple">+ <!-- Ports -->+ <Accordion.Item value="ports">+ <Accordion.Trigger class="text-sm font-medium">{m.swarm_service_form_ports()}</Accordion.Trigger>+ <Accordion.Content class="pt-6 pb-5">+ <div class="space-y-4">+ {#each form.ports as port, i (i)}+ <div class="flex items-center gap-4">+ <Input placeholder="8080" bind:value={port.target} disabled={isLoading} class="flex-1" />+ <span class="text-muted-foreground">:</span>+ <Input placeholder="80" bind:value={port.published} disabled={isLoading} class="flex-1" />+ <Select.Root type="single" bind:value={port.protocol} disabled={isLoading}>+ <Select.Trigger class="w-20">+ <span class="uppercase">{port.protocol}</span>+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="tcp" label="TCP">TCP</Select.Item>+ <Select.Item value="udp" label="UDP">UDP</Select.Item>+ </Select.Content>+ </Select.Root>+ <ArcaneButton action="remove" size="sm" onclick={() => removePort(i)} disabled={isLoading} icon={TrashIcon} />+ </div>+ {/each}+ <ArcaneButton+ action="create"+ size="sm"+ onclick={addPort}+ disabled={isLoading}+ icon={AddIcon}+ customLabel={m.swarm_service_form_add_port()}+ />+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <!-- Environment Variables -->+ <Accordion.Item value="env">+ <Accordion.Trigger class="text-sm font-medium">{m.swarm_service_form_env_vars()}</Accordion.Trigger>+ <Accordion.Content class="pt-6 pb-5">+ <div class="space-y-4">+ {#each form.envVars as env, i (i)}+ <div class="flex items-center gap-4">+ <Input placeholder="KEY" bind:value={env.key} disabled={isLoading} class="flex-1" />+ <span class="text-muted-foreground">=</span>+ <Input placeholder="value" bind:value={env.value} disabled={isLoading} class="flex-1" />+ <ArcaneButton action="remove" size="sm" onclick={() => removeEnvVar(i)} disabled={isLoading} icon={TrashIcon} />+ </div>+ {/each}+ <ArcaneButton+ action="create"+ size="sm"+ onclick={addEnvVar}+ disabled={isLoading}+ icon={AddIcon}+ customLabel={m.swarm_service_form_add_variable()}+ />+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <!-- Mounts -->+ <Accordion.Item value="mounts">+ <Accordion.Trigger class="text-sm font-medium">{m.swarm_service_form_mounts()}</Accordion.Trigger>+ <Accordion.Content class="pt-6 pb-5">+ <div class="space-y-4">+ {#each form.mounts as mount, i (i)}+ <div class="flex items-center gap-4">+ <Select.Root type="single" bind:value={mount.type} disabled={isLoading}>+ <Select.Trigger class="w-24">+ <span class="capitalize">{mount.type}</span>+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="volume" label="Volume">Volume</Select.Item>+ <Select.Item value="bind" label="Bind">Bind</Select.Item>+ </Select.Content>+ </Select.Root>+ <Input placeholder="source" bind:value={mount.source} disabled={isLoading} class="flex-1" />+ <span class="text-muted-foreground">→</span>+ <Input placeholder="/target" bind:value={mount.target} disabled={isLoading} class="flex-1" />+ <ArcaneButton action="remove" size="sm" onclick={() => removeMount(i)} disabled={isLoading} icon={TrashIcon} />+ </div>+ {/each}+ <ArcaneButton+ action="create"+ size="sm"+ onclick={addMount}+ disabled={isLoading}+ icon={AddIcon}+ customLabel={m.swarm_service_form_add_mount()}+ />+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <!-- Labels -->+ <Accordion.Item value="labels">+ <Accordion.Trigger class="text-sm font-medium">{m.swarm_service_form_labels()}</Accordion.Trigger>+ <Accordion.Content class="pt-6 pb-5">+ <div class="space-y-4">+ {#each form.labels as label, i (i)}+ <div class="flex items-center gap-4">+ <Input placeholder="key" bind:value={label.key} disabled={isLoading} class="flex-1" />+ <span class="text-muted-foreground">=</span>+ <Input placeholder="value" bind:value={label.value} disabled={isLoading} class="flex-1" />+ <ArcaneButton action="remove" size="sm" onclick={() => removeLabel(i)} disabled={isLoading} icon={TrashIcon} />+ </div>+ {/each}+ <ArcaneButton+ action="create"+ size="sm"+ onclick={addLabel}+ disabled={isLoading}+ icon={AddIcon}+ customLabel={m.swarm_service_form_add_label()}+ />+ </div>+ </Accordion.Content>+ </Accordion.Item>++ <!-- Advanced Container Config -->+ <Accordion.Item value="advanced">+ <Accordion.Trigger class="text-sm font-medium">{m.swarm_service_form_advanced()}</Accordion.Trigger>+ <Accordion.Content class="pt-6 pb-5">+ <div class="space-y-5">+ <FormInput input={form.command} label={m.swarm_service_form_command()} placeholder="/bin/sh" disabled={isLoading} />+ <FormInput+ input={form.args}+ label={m.swarm_service_form_arguments()}+ placeholder="-c echo hello"+ disabled={isLoading}+ />+ <FormInput+ input={form.workingDir}+ label={m.swarm_service_form_working_dir()}+ placeholder="/app"+ disabled={isLoading}+ />+ <FormInput input={form.user} label={m.swarm_service_form_user()} placeholder="1000:1000" disabled={isLoading} />+ <FormInput input={form.hostname} label={m.swarm_hostname()} placeholder="my-service" disabled={isLoading} />+ </div>+ </Accordion.Content>+ </Accordion.Item>+ </Accordion.Root>+ </form>+ {/snippet}++ {#snippet footer()}+ <div class="flex w-full flex-row gap-2">+ <ArcaneButton+ action="cancel"+ tone="ghost"+ type="button"+ class="flex-1"+ onclick={() => (open = false)}+ disabled={isLoading}+ />+ <ArcaneButton+ action={submitAction}+ type="button"+ class="flex-1"+ disabled={isLoading}+ loading={isLoading}+ onclick={handleSubmit}+ customLabel={submitLabel}+ />+ </div>+ {/snippet}+</ResponsiveDialog>diff --git a/frontend/src/routes/(app)/swarm/services/services-table.svelte b/frontend/src/routes/(app)/swarm/services/services-table.sveltenew file mode 100644index 000000000..2a728aa45--- /dev/null+++ b/frontend/src/routes/(app)/swarm/services/services-table.svelte@@ -0,0 +1,266 @@+<script lang="ts">+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';+ import type { ColumnSpec, MobileFieldVisibility } from '$lib/components/arcane-table';+ import { UniversalMobileCard } from '$lib/components/arcane-table';+ import { DockIcon, GlobeIcon, EllipsisIcon, TrashIcon, NetworksIcon, InspectIcon } from '$lib/icons';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import type { SwarmServiceSummary, SwarmServicePort } from '$lib/types/swarm.type';+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ 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 { goto } from '$app/navigation';++ let {+ services = $bindable(),+ requestOptions = $bindable(),+ fetchServices = (options: SearchPaginationSortRequest) => swarmService.getServices(options),+ persistKey = 'arcane-swarm-services-table'+ }: {+ services: Paginated<SwarmServiceSummary>;+ requestOptions: SearchPaginationSortRequest;+ fetchServices?: (options: SearchPaginationSortRequest) => Promise<Paginated<SwarmServiceSummary>>;+ persistKey?: string;+ } = $props();++ const MAX_OVERFLOW_ITEMS = 3;++ function formatPort(port: SwarmServicePort): string {+ const protocol = port.protocol || 'tcp';+ if (port.publishedPort) {+ return `${port.publishedPort}:${port.targetPort}/${protocol}`;+ }+ return `${port.targetPort}/${protocol}`;+ }++ function formatPortsList(ports?: SwarmServicePort[]): string[] {+ if (!ports || ports.length === 0) return [];+ return ports.map(formatPort);+ }++ function getShortName(name: string, stackName?: string | null): string {+ if (stackName && name.startsWith(`${stackName}_`)) {+ return name.slice(stackName.length + 1);+ }+ return name;+ }++ function modeVariant(mode: string): 'green' | 'blue' | 'amber' | 'gray' {+ if (mode === 'replicated') return 'blue';+ if (mode === 'global') return 'green';+ return 'gray';+ }++ let isLoading = $state({ remove: false });++ const isAnyLoading = $derived(Object.values(isLoading).some(Boolean));++ function inspectService(service: SwarmServiceSummary) {+ goto(`/swarm/services/${service.id}`);+ }++ function handleDelete(service: SwarmServiceSummary) {+ openConfirmDialog({+ title: m.common_delete_title({ resource: m.swarm_service() }),+ message: m.common_delete_confirm({ resource: m.swarm_service() }),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.removeService(service.id)),+ message: m.common_delete_failed({ resource: `${m.swarm_service()} "${service.name}"` }),+ setLoadingState: (v) => (isLoading.remove = v),+ onSuccess: async () => {+ toast.success(m.common_delete_success({ resource: `${m.swarm_service()} "${service.name}"` }));+ services = await fetchServices(requestOptions);+ }+ });+ }+ }+ });+ }++ const columns = [+ { accessorKey: 'id', title: m.common_id(), hidden: true },+ { accessorKey: 'stackName', title: m.swarm_stack(), sortable: true, cell: StackCell },+ { accessorKey: 'name', title: m.swarm_service(), sortable: true, cell: NameCell },+ { accessorKey: 'mode', title: m.swarm_mode(), sortable: true, cell: ModeCell },+ { accessorKey: 'replicas', title: m.swarm_replicas(), sortable: true, cell: ReplicasCell },+ {+ id: 'nodes',+ accessorFn: (item: SwarmServiceSummary) => item.nodes,+ title: m.swarm_nodes_column(),+ cell: NodesCell+ },+ {+ id: 'networks',+ accessorFn: (item: SwarmServiceSummary) => item.networks,+ title: m.swarm_networks(),+ cell: NetworksCell+ },+ { accessorKey: 'ports', title: m.common_ports(), cell: PortsCell }+ ] satisfies ColumnSpec<SwarmServiceSummary>[];++ const mobileFields = [+ { id: 'stackName', label: m.swarm_stack(), defaultVisible: true },+ { id: 'mode', label: m.swarm_mode(), defaultVisible: true },+ { id: 'replicas', label: m.swarm_replicas(), defaultVisible: true },+ { id: 'nodes', label: m.swarm_nodes_column(), defaultVisible: true },+ { id: 'networks', label: m.swarm_networks(), defaultVisible: false },+ { id: 'ports', label: m.common_ports(), defaultVisible: false }+ ];++ let mobileFieldVisibility = $state<Record<string, boolean>>({});+</script>++{#snippet NameCell({ item }: { item: SwarmServiceSummary })}+ <a href="/swarm/services/{item.id}" class="text-primary text-sm font-medium hover:underline">+ {getShortName(item.name, item.stackName)}+ </a>+{/snippet}++{#snippet ModeCell({ value }: { value: unknown })}+ <StatusBadge text={String(value ?? m.common_unknown())} variant={modeVariant(String(value ?? ''))} />+{/snippet}++{#snippet StackCell({ value }: { value: unknown })}+ {#if value}+ <span class="text-sm">{String(value)}</span>+ {:else}+ <span class="text-muted-foreground text-sm">{m.common_na()}</span>+ {/if}+{/snippet}++{#snippet ReplicasCell({ item }: { item: SwarmServiceSummary })}+ <span class="font-mono text-sm">{item.runningReplicas} / {item.replicas}</span>+{/snippet}++{#snippet OverflowCell({ items }: { items: string[] })}+ {#if !items || items.length === 0}+ <span class="text-muted-foreground text-sm">{m.common_na()}</span>+ {:else}+ <div class="flex flex-col gap-0.5">+ {#each items.slice(0, MAX_OVERFLOW_ITEMS) as item}+ <span class="max-w-45 truncate font-mono text-sm">{item}</span>+ {/each}+ {#if items.length > MAX_OVERFLOW_ITEMS}+ <span class="text-muted-foreground text-xs font-medium">+ {m.swarm_n_more({ count: items.length - MAX_OVERFLOW_ITEMS })}+ </span>+ {/if}+ </div>+ {/if}+{/snippet}++{#snippet NodesCell({ item }: { item: SwarmServiceSummary })}+ {@render OverflowCell({ items: item.nodes })}+{/snippet}++{#snippet NetworksCell({ item }: { item: SwarmServiceSummary })}+ {@render OverflowCell({ items: item.networks })}+{/snippet}++{#snippet PortsCell({ item }: { item: SwarmServiceSummary })}+ {@render OverflowCell({ items: formatPortsList(item.ports) })}+{/snippet}++{#snippet ServiceMobileCardSnippet({+ item,+ mobileFieldVisibility+}: {+ item: SwarmServiceSummary;+ mobileFieldVisibility: MobileFieldVisibility;+})}+ <UniversalMobileCard+ {item}+ icon={() => ({+ component: DockIcon,+ variant: item.mode === 'global' ? 'emerald' : 'blue'+ })}+ title={(item: SwarmServiceSummary) => getShortName(item.name, item.stackName)}+ subtitle={(item: SwarmServiceSummary) => ((mobileFieldVisibility.stackName ?? true) ? (item.stackName ?? null) : null)}+ badges={[+ (item: SwarmServiceSummary) =>+ (mobileFieldVisibility.mode ?? true) ? { variant: modeVariant(item.mode), text: item.mode } : null+ ]}+ fields={[+ {+ label: m.swarm_replicas(),+ getValue: (item: SwarmServiceSummary) => `${item.runningReplicas} / ${item.replicas}`,+ icon: GlobeIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.replicas ?? true+ },+ {+ label: m.swarm_nodes_column(),+ getValue: (item: SwarmServiceSummary) =>+ item.nodes?.length+ ? item.nodes.slice(0, 3).join(', ') + (item.nodes.length > 3 ? ` +${item.nodes.length - 3}` : '')+ : m.common_na(),+ icon: NetworksIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.nodes ?? true+ },+ {+ label: m.swarm_networks(),+ getValue: (item: SwarmServiceSummary) => (item.networks?.length ? item.networks.join(', ') : m.common_na()),+ icon: NetworksIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.networks ?? false+ },+ {+ label: m.common_ports(),+ getValue: (item: SwarmServiceSummary) => formatPortsList(item.ports).join(', ') || m.common_na(),+ icon: GlobeIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.ports ?? false+ }+ ]}+ rowActions={RowActions}+ />+{/snippet}++{#snippet RowActions({ item }: { item: SwarmServiceSummary })}+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ {#snippet child({ props })}+ <ArcaneButton {...props} action="base" tone="ghost" size="icon" class="relative size-8 p-0">+ <span class="sr-only">{m.common_open_menu()}</span>+ <EllipsisIcon />+ </ArcaneButton>+ {/snippet}+ </DropdownMenu.Trigger>+ <DropdownMenu.Content align="end">+ <DropdownMenu.Group>+ <DropdownMenu.Item onclick={() => inspectService(item)}>+ <InspectIcon class="size-4" />+ {m.common_inspect()}+ </DropdownMenu.Item>+ <DropdownMenu.Separator />+ <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)} disabled={isAnyLoading}>+ <TrashIcon class="size-4" />+ {m.common_delete()}+ </DropdownMenu.Item>+ </DropdownMenu.Group>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+{/snippet}++<ArcaneTable+ {persistKey}+ items={services}+ bind:requestOptions+ bind:mobileFieldVisibility+ selectionDisabled={true}+ onRefresh={async (options) => (services = await fetchServices(options))}+ {columns}+ {mobileFields}+ rowActions={RowActions}+ mobileCard={ServiceMobileCardSnippet}+/>diff --git a/frontend/src/routes/(app)/swarm/stacks/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/+page.sveltenew file mode 100644index 000000000..897214e9a--- /dev/null+++ b/frontend/src/routes/(app)/swarm/stacks/+page.svelte@@ -0,0 +1,68 @@+<script lang="ts">+ import { LayersIcon } from '$lib/icons';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import { untrack } from 'svelte';+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';+ import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';+ import { parallelRefresh } from '$lib/utils/refresh.util';+ import SwarmStacksTable from './stacks-table.svelte';+ import { goto } from '$app/navigation';++ let { data } = $props();++ let stacks = $state(untrack(() => data.stacks));+ let requestOptions = $state(untrack(() => data.requestOptions));+ let isLoading = $state({ refresh: false });++ async function refresh() {+ await parallelRefresh(+ {+ stacks: {+ fetch: () => swarmService.getStacks(requestOptions),+ onSuccess: (data) => {+ stacks = data;+ },+ errorMessage: m.common_refresh_failed({ resource: m.swarm_stacks_title() })+ }+ },+ (v) => (isLoading.refresh = v)+ );+ }++ useEnvironmentRefresh(refresh);++ const totalStacks = $derived(stacks?.pagination?.totalItems ?? stacks?.data?.length ?? 0);++ const actionButtons: ActionButton[] = $derived([+ {+ id: 'create',+ action: 'create',+ label: m.common_create_button({ resource: m.swarm_stack() }),+ onclick: () => goto('/swarm/stacks/new')+ },+ {+ id: 'refresh',+ action: 'restart',+ label: m.common_refresh(),+ onclick: refresh,+ loading: isLoading.refresh,+ disabled: isLoading.refresh+ }+ ]);++ const statCards: StatCardConfig[] = $derived([+ {+ title: m.swarm_stacks_total(),+ value: totalStacks,+ icon: LayersIcon,+ iconColor: 'text-blue-500'+ }+ ]);+</script>++<ResourcePageLayout title={m.swarm_stacks_title()} subtitle={m.swarm_stacks_subtitle()} {actionButtons} {statCards}>+ {#snippet mainContent()}+ <SwarmStacksTable bind:stacks bind:requestOptions />+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/swarm/stacks/+page.ts b/frontend/src/routes/(app)/swarm/stacks/+page.tsnew file mode 100644index 000000000..d013b529e--- /dev/null+++ b/frontend/src/routes/(app)/swarm/stacks/+page.ts@@ -0,0 +1,24 @@+import { swarmService } from '$lib/services/swarm-service';+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';+import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';+import type { PageLoad } from './$types';++export const load: PageLoad = async () => {+ const requestOptions = resolveInitialTableRequest('arcane-swarm-stacks-table', {+ pagination: {+ page: 1,+ limit: 20+ },+ sort: {+ column: 'name',+ direction: 'asc'+ }+ } satisfies SearchPaginationSortRequest);++ const stacks = await swarmService.getStacks(requestOptions);++ return {+ stacks,+ requestOptions+ };+};diff --git a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.sveltenew file mode 100644index 000000000..f0bfc5949--- /dev/null+++ b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte@@ -0,0 +1,176 @@+<script lang="ts">+ import { goto } from '$app/navigation';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { TabBar, type TabItem } from '$lib/components/tab-bar';+ import * as Tabs from '$lib/components/ui/tabs';+ import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';+ import { LayersIcon, DockIcon, JobsIcon, TrashIcon, EditIcon } from '$lib/icons';+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { parallelRefresh } from '$lib/utils/refresh.util';+ import { tryCatch } from '$lib/utils/try-catch';+ import { untrack } from 'svelte';+ import { toast } from 'svelte-sonner';+ import { openConfirmDialog } from '$lib/components/confirm-dialog';+ import SwarmServicesTable from '../../services/services-table.svelte';+ import SwarmTasksTable from '../../tasks/tasks-table.svelte';++ let { data } = $props();++ let stack = $state(untrack(() => data.stack));+ let services = $state(untrack(() => data.services));+ let tasks = $state(untrack(() => data.tasks));+ let servicesRequestOptions = $state(untrack(() => data.servicesRequestOptions));+ let tasksRequestOptions = $state(untrack(() => data.tasksRequestOptions));+ let selectedTab = $state<'services' | 'tasks'>('services');+ let isLoading = $state({ refresh: false, remove: false });++ const stackName = $derived(stack?.name ?? data.stackName);+ const tabItems = $derived<TabItem[]>([+ { value: 'services', label: m.swarm_services_title(), icon: DockIcon },+ { value: 'tasks', label: m.swarm_tasks_title(), icon: JobsIcon }+ ]);+ const totalServices = $derived(services?.pagination?.totalItems ?? services?.data?.length ?? 0);+ const totalTasks = $derived(tasks?.pagination?.totalItems ?? tasks?.data?.length ?? 0);++ async function fetchStackServices(options: typeof servicesRequestOptions) {+ return swarmService.getStackServices(stackName, options);+ }++ async function fetchStackTasks(options: typeof tasksRequestOptions) {+ return swarmService.getStackTasks(stackName, options);+ }++ async function refresh() {+ await parallelRefresh(+ {+ stack: {+ fetch: () => swarmService.getStack(stackName),+ onSuccess: (value) => {+ stack = value;+ },+ errorMessage: m.common_refresh_failed({ resource: `${m.swarm_stack()} "${stackName}"` })+ },+ services: {+ fetch: () => swarmService.getStackServices(stackName, servicesRequestOptions),+ onSuccess: (value) => {+ services = value;+ },+ errorMessage: m.common_refresh_failed({ resource: `${m.swarm_services_title()} (${stackName})` })+ },+ tasks: {+ fetch: () => swarmService.getStackTasks(stackName, tasksRequestOptions),+ onSuccess: (value) => {+ tasks = value;+ },+ errorMessage: m.common_refresh_failed({ resource: `${m.swarm_tasks_title()} (${stackName})` })+ }+ },+ (v) => (isLoading.refresh = v)+ );+ }++ useEnvironmentRefresh(refresh);++ function handleDelete() {+ openConfirmDialog({+ title: m.common_delete_title({ resource: m.swarm_stack() }),+ message: m.common_delete_confirm({ resource: m.swarm_stack() }),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.removeStack(stackName)),+ message: m.common_delete_failed({ resource: `${m.swarm_stack()} "${stackName}"` }),+ setLoadingState: (v) => (isLoading.remove = v),+ onSuccess: async () => {+ toast.success(m.common_delete_success({ resource: `${m.swarm_stack()} "${stackName}"` }));+ goto('/swarm/stacks');+ }+ });+ }+ }+ });+ }++ const actionButtons: ActionButton[] = $derived([+ {+ id: 'edit',+ action: 'base',+ label: m.common_edit(),+ icon: EditIcon,+ onclick: () => goto(`/swarm/stacks/new?fromStack=${encodeURIComponent(stackName)}`),+ disabled: isLoading.remove+ },+ {+ id: 'remove',+ action: 'remove',+ label: m.common_delete(),+ icon: TrashIcon,+ onclick: handleDelete,+ loading: isLoading.remove,+ disabled: isLoading.remove+ },+ {+ id: 'refresh',+ action: 'restart',+ label: m.common_refresh(),+ onclick: refresh,+ loading: isLoading.refresh,+ disabled: isLoading.refresh+ }+ ]);++ const statCards: StatCardConfig[] = $derived([+ {+ title: m.swarm_services_title(),+ value: totalServices,+ icon: DockIcon,+ iconColor: 'text-blue-500'+ },+ {+ title: m.swarm_tasks_title(),+ value: totalTasks,+ icon: JobsIcon,+ iconColor: 'text-indigo-500'+ }+ ]);+</script>++<ResourcePageLayout+ title={stackName}+ subtitle={m.swarm_stack_namespace({ namespace: stack?.namespace ?? stackName })}+ icon={LayersIcon}+ {actionButtons}+ {statCards}+>+ {#snippet mainContent()}+ <div class="space-y-4">+ <Tabs.Root value={selectedTab}>+ <div class="w-fit pb-3">+ <TabBar items={tabItems} value={selectedTab} onValueChange={(value) => (selectedTab = value as 'services' | 'tasks')} />+ </div>++ <Tabs.Content value="services">+ <SwarmServicesTable+ bind:services+ bind:requestOptions={servicesRequestOptions}+ fetchServices={fetchStackServices}+ persistKey={`arcane-swarm-stack-services-table-${stackName}`}+ />+ </Tabs.Content>+ <Tabs.Content value="tasks">+ <SwarmTasksTable+ bind:tasks+ bind:requestOptions={tasksRequestOptions}+ fetchTasks={fetchStackTasks}+ persistKey={`arcane-swarm-stack-tasks-table-${stackName}`}+ />+ </Tabs.Content>+ </Tabs.Root>+ </div>+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.ts b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.tsnew file mode 100644index 000000000..3e153106b--- /dev/null+++ b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.ts@@ -0,0 +1,52 @@+import { error } from '@sveltejs/kit';+import { swarmService } from '$lib/services/swarm-service';+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';+import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';+import type { PageLoad } from './$types';++export const load: PageLoad = async ({ params }) => {+ const stackName = decodeURIComponent(params.name);+ const servicesRequestOptions = resolveInitialTableRequest(`arcane-swarm-stack-services-table-${stackName}`, {+ pagination: {+ page: 1,+ limit: 20+ },+ sort: {+ column: 'name',+ direction: 'asc'+ }+ } satisfies SearchPaginationSortRequest);+ const tasksRequestOptions = resolveInitialTableRequest(`arcane-swarm-stack-tasks-table-${stackName}`, {+ pagination: {+ page: 1,+ limit: 20+ },+ sort: {+ column: 'name',+ direction: 'asc'+ }+ } satisfies SearchPaginationSortRequest);++ try {+ const [stack, services, tasks] = await Promise.all([+ swarmService.getStack(stackName),+ swarmService.getStackServices(stackName, servicesRequestOptions),+ swarmService.getStackTasks(stackName, tasksRequestOptions)+ ]);++ return {+ stack,+ stackName,+ services,+ tasks,+ servicesRequestOptions,+ tasksRequestOptions+ };+ } catch (err: any) {+ console.error('Failed to load stack details:', err);+ if (err.status === 404) {+ throw err;+ }+ throw error(500, err.message || 'Failed to load stack details');+ }+};diff --git a/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/new/+page.sveltenew file mode 100644index 000000000..6c2db07e3--- /dev/null+++ b/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte@@ -0,0 +1,391 @@+<script lang="ts">+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { Spinner } from '$lib/components/ui/spinner/index.js';+ import { Label } from '$lib/components/ui/label/index.js';+ import { goto, invalidateAll } from '$app/navigation';+ import { toast } from 'svelte-sonner';+ import { preventDefault, createForm } from '$lib/utils/form.utils';+ import { tryCatch } from '$lib/utils/try-catch';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { Textarea } from '$lib/components/ui/textarea/index.js';+ import * as Dialog from '$lib/components/ui/dialog/index.js';+ import * as ArcaneTooltip from '$lib/components/arcane-tooltip';+ import TemplateSelectionDialog from '$lib/components/dialogs/template-selection-dialog.svelte';+ import type { Template } from '$lib/types/template.type';+ import { z } from 'zod/v4';+ import { arcaneButtonVariants, actionConfigs } from '$lib/components/arcane-button/variants';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service.js';+ import { systemService } from '$lib/services/system-service.js';+ import { templateService } from '$lib/services/template-service.js';+ import * as ButtonGroup from '$lib/components/ui/button-group/index.js';+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';+ import { ArrowLeftIcon, TerminalIcon, CopyIcon, TemplateIcon, AddIcon, ArrowDownIcon as ChevronDown } from '$lib/icons';+ import CodePanel from '../../../projects/components/CodePanel.svelte';+ import EditableName from '../../../projects/components/EditableName.svelte';++ let { data } = $props();++ let saving = $state(false);+ let converting = $state(false);+ let creatingTemplate = $state(false);+ let showTemplateDialog = $state(false);+ let showConverterDialog = $state(false);+ let isLoadingTemplateContent = $state(false);++ const formSchema = z.object({+ name: z+ .string()+ .min(1, m.common_name_required())+ .regex(/^[a-z0-9-_]+$/i, m.compose_project_name_invalid()),+ composeContent: z.string().min(1, m.compose_compose_content_required()),+ envContent: z.string().optional().default('')+ });++ const initialName = $derived(+ data.sourceStackName+ ? data.sourceStackName+ : data.selectedTemplate+ ? data.selectedTemplate.name.toLowerCase().replace(/[^a-z0-9-_]/g, '-')+ : ''+ );++ let formData = $derived({+ name: initialName,+ composeContent: data.defaultTemplate || '',+ envContent: data.envTemplate || ''+ });++ let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));++ let dockerRunCommand = $state('');+ let composeOpen = $state(true);+ let envOpen = $state(true);+ let nameInputRef = $state<HTMLInputElement | null>(null);++ const globalVariableMap = $derived.by(() =>+ Object.fromEntries((data.globalVariables ?? []).map((item) => [item.key, item.value]))+ );++ async function handleSubmit() {+ await handleDeployStack();+ }++ async function handleDeployStack() {+ const validated = form.validate();+ if (!validated) return;++ const { name, composeContent, envContent } = validated;++ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.deployStack({ name, composeContent, envContent })),+ message: m.common_create_failed({ resource: `${m.swarm_stack()} "${name}"` }),+ setLoadingState: (value) => (saving = value),+ onSuccess: async () => {+ toast.success(m.common_create_success({ resource: `${m.swarm_stack()} "${name}"` }));+ goto('/swarm/stacks', { invalidateAll: true });+ }+ });+ }++ async function handleConvertDockerRun() {+ if (!dockerRunCommand.trim()) {+ toast.error(m.compose_enter_docker_run_command());+ return;+ }++ handleApiResultWithCallbacks({+ result: await tryCatch(systemService.convert(dockerRunCommand)),+ message: m.compose_convert_failed(),+ setLoadingState: (value) => (converting = value),+ onSuccess: (data) => {+ $inputs.composeContent.value = data.dockerCompose;+ $inputs.envContent.value = data.envVars;+ $inputs.name.value = data.serviceName;++ toast.success(m.compose_convert_success());+ dockerRunCommand = '';+ showConverterDialog = false;+ }+ });+ }++ async function handleTemplateSelect(template: Template) {+ showTemplateDialog = false;++ $inputs.composeContent.value = template.content ?? '';+ $inputs.envContent.value = template.envContent ?? '';++ if (!$inputs.name.value?.trim()) {+ $inputs.name.value = template.name.toLowerCase().replace(/[^a-z0-9-_]/g, '-');+ }+ toast.success(m.compose_template_loaded({ name: template.name }));+ }++ const exampleCommands = [m.compose_example_command_1(), m.compose_example_command_2(), m.compose_example_command_3()];++ function useExample(command: string) {+ dockerRunCommand = command;+ }++ async function handleCreateTemplate() {+ const validated = form.validate();+ if (!validated) return;++ const { name, composeContent, envContent } = validated;++ handleApiResultWithCallbacks({+ result: await tryCatch(+ templateService.createTemplate({+ name,+ content: composeContent,+ envContent+ })+ ),+ message: m.common_create_failed({ resource: `${m.resource_template()} "${name}"` }),+ setLoadingState: (value) => (creatingTemplate = value),+ onSuccess: async () => {+ toast.success(m.common_create_success({ resource: `${m.resource_template()} "${name}"` }));+ }+ });+ }++ const templateBtnClass = arcaneButtonVariants({+ tone: actionConfigs.template?.tone ?? 'outline-primary',+ size: 'default',+ hoverEffect: 'none'+ });++ const dropdownContentClass =+ 'arcane-dd-content min-w-[220px] overflow-visible rounded-lg border border-primary/30 bg-background/95 ' ++ 'backdrop-blur supports-[backdrop-filter]:bg-background/80 ring-1 ring-inset ring-primary/20 shadow-sm p-1';++ const dropdownItemClass =+ 'flex cursor-pointer select-none items-center gap-2 rounded-md px-3 py-2 text-sm ' ++ 'text-foreground/90 outline-none transition-colors ' ++ 'hover:bg-primary/10 focus:bg-primary/10 ' ++ 'data-[disabled]:opacity-50 data-[disabled]:pointer-events-none';++ const canSubmit = $derived(+ !!$inputs.name.value && !!$inputs.composeContent.value && !saving && !converting && !isLoadingTemplateContent+ );+</script>++<div class="bg-background flex h-full min-h-0 flex-col">+ <div class="sticky top-0 mb-2 border-b">+ <div class="mx-auto flex h-16 max-w-full items-center justify-between gap-4 px-6">+ <div class="flex items-center gap-4">+ <ArcaneButton+ action="base"+ tone="ghost"+ size="sm"+ href="/swarm/stacks"+ class="gap-2 bg-transparent"+ icon={ArrowLeftIcon}+ customLabel={m.common_back()}+ />+ <div class="bg-border hidden h-4 w-px sm:block"></div>+ <div class="hidden items-center gap-3 sm:flex">+ <EditableName+ bind:value={$inputs.name.value}+ bind:ref={nameInputRef}+ variant="inline"+ error={$inputs.name.error ?? undefined}+ originalValue=""+ placeholder={m.compose_project_name_placeholder?.() || 'Enter name...'}+ canEdit={!saving && !isLoadingTemplateContent}+ class="hidden sm:block"+ />+ </div>+ </div>++ <div class="flex items-center gap-2">+ <ButtonGroup.Root>+ <ArcaneTooltip.Root+ open={!$inputs.name.value && !saving && !converting && !isLoadingTemplateContent ? undefined : false}+ >+ <ArcaneTooltip.Trigger>+ <span>+ <ArcaneButton+ action="create"+ tone="ghost"+ disabled={!canSubmit}+ onclick={() => handleSubmit()}+ class={`${templateBtnClass} gap-2 rounded-r-none`}+ loading={saving}+ customLabel={m.common_create_button({ resource: m.swarm_stack() })}+ loadingLabel={m.common_action_creating()}+ />+ </span>+ </ArcaneTooltip.Trigger>+ <ArcaneTooltip.Content class="arcane-tooltip-content max-w-[280px]">+ {#if $inputs.name.value === ''}+ <p class="mb-1 text-sm font-medium">{m.compose_project_name_tooltip_title()}</p>+ <p class="text-muted-foreground text-xs">{m.compose_project_name_tooltip_description()}</p>+ <p class="bg-muted mt-1.5 inline-block rounded px-1.5 py-0.5 font-mono text-xs">+ {m.compose_project_name_tooltip_example()}+ </p>+ {/if}+ </ArcaneTooltip.Content>+ </ArcaneTooltip.Root>++ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ {#snippet child({ props })}+ <ArcaneButton+ {...props}+ action="base"+ tone="ghost"+ class={`${templateBtnClass} -ml-px rounded-l-none px-2`}+ icon={ChevronDown}+ />+ {/snippet}+ </DropdownMenu.Trigger>+ <DropdownMenu.Content align="end" class={dropdownContentClass}>+ <DropdownMenu.Group>+ <DropdownMenu.Item+ class={dropdownItemClass}+ disabled={saving || converting || isLoadingTemplateContent}+ onclick={() => (showTemplateDialog = true)}+ >+ <TemplateIcon class="size-4" />+ {m.common_use_template()}+ </DropdownMenu.Item>+ <DropdownMenu.Item class={dropdownItemClass} onclick={() => (showConverterDialog = true)}>+ <TerminalIcon class="size-4" />+ {m.compose_convert_from_docker_run()}+ </DropdownMenu.Item>+ <DropdownMenu.Separator />+ <DropdownMenu.Item+ class={dropdownItemClass}+ disabled={!canSubmit || creatingTemplate}+ onclick={handleCreateTemplate}+ >+ {#if creatingTemplate}+ <Spinner class="size-4" />+ {:else}+ <AddIcon class="size-4" />+ {/if}+ {m.templates_create_template()}+ </DropdownMenu.Item>+ </DropdownMenu.Group>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ </ButtonGroup.Root>+ </div>+ </div>+ </div>++ <div class="flex min-h-0 flex-1 overflow-hidden">+ <div class="mx-auto h-full w-full max-w-full min-w-0">+ <div class="flex h-full min-h-0 flex-col">+ <div class="block flex-shrink-0 px-2 py-4 sm:hidden sm:px-6">+ <EditableName+ bind:value={$inputs.name.value}+ bind:ref={nameInputRef}+ variant="block"+ error={$inputs.name.error ?? undefined}+ originalValue=""+ placeholder={m.compose_project_name_placeholder()}+ canEdit={!saving && !isLoadingTemplateContent}+ />+ </div>++ <form+ class="flex h-full min-h-0 flex-1 flex-col gap-4 px-2 sm:px-6 lg:grid lg:grid-cols-5 lg:grid-rows-1 lg:items-stretch"+ onsubmit={preventDefault(handleSubmit)}+ >+ <div class="flex min-h-0 flex-1 flex-col lg:col-span-3">+ <CodePanel+ bind:open={composeOpen}+ title={m.compose_compose_file_title()}+ language="yaml"+ bind:value={$inputs.composeContent.value}+ error={$inputs.composeContent.error ?? undefined}+ fileId="swarm:stacks:new:compose"+ editorContext={{+ envContent: $inputs.envContent.value,+ composeContents: [$inputs.composeContent.value],+ globalVariables: globalVariableMap+ }}+ />+ </div>++ <div class="flex min-h-0 flex-1 flex-col lg:col-span-2">+ <CodePanel+ bind:open={envOpen}+ title={m.compose_env_title()}+ language="env"+ bind:value={$inputs.envContent.value}+ error={$inputs.envContent.error ?? undefined}+ fileId="swarm:stacks:new:env"+ editorContext={{+ envContent: $inputs.envContent.value,+ composeContents: [$inputs.composeContent.value],+ globalVariables: globalVariableMap+ }}+ />+ </div>+ </form>+ </div>+ </div>+ </div>+</div>++<Dialog.Root bind:open={showConverterDialog}>+ <Dialog.Content class="max-h-[80vh] sm:max-w-[800px]">+ <Dialog.Header>+ <Dialog.Title>{m.compose_converter_title()}</Dialog.Title>+ <Dialog.Description>{m.compose_converter_description()}</Dialog.Description>+ </Dialog.Header>++ <div class="max-h-[60vh] space-y-4 overflow-y-auto">+ <div class="space-y-2">+ <Label for="dockerRunCommand">{m.compose_docker_run_command_label()}</Label>+ <Textarea+ id="dockerRunCommand"+ bind:value={dockerRunCommand}+ placeholder={m.compose_docker_run_placeholder()}+ rows={3}+ disabled={converting}+ class="font-mono text-sm"+ />+ </div>++ <div class="space-y-2">+ <Label class="text-muted-foreground text-xs">{m.compose_example_commands_label()}</Label>+ <div class="space-y-1">+ {#each exampleCommands as command}+ <ArcaneButton+ action="base"+ tone="ghost"+ size="sm"+ class="h-auto w-full justify-start p-2 text-left font-mono text-xs break-all whitespace-normal"+ onclick={() => useExample(command)}+ icon={CopyIcon}+ customLabel={command}+ />+ {/each}+ </div>+ </div>+ </div>++ <div class="flex w-full justify-end pt-4">+ <ArcaneButton+ action="create"+ disabled={!dockerRunCommand.trim() || converting}+ onclick={handleConvertDockerRun}+ loading={converting}+ customLabel={m.compose_convert_action()}+ loadingLabel={m.compose_converting()}+ />+ </div>+ </Dialog.Content>+</Dialog.Root>++<TemplateSelectionDialog+ bind:open={showTemplateDialog}+ templates={data.composeTemplates || []}+ onSelect={handleTemplateSelect}+ onDownloadSuccess={invalidateAll}+/>diff --git a/frontend/src/routes/(app)/swarm/stacks/new/+page.ts b/frontend/src/routes/(app)/swarm/stacks/new/+page.tsnew file mode 100644index 000000000..7f72a00c8--- /dev/null+++ b/frontend/src/routes/(app)/swarm/stacks/new/+page.ts@@ -0,0 +1,45 @@+import { templateService } from '$lib/services/template-service';+import { swarmService } from '$lib/services/swarm-service';+import type { PageLoad } from './$types';++export const load: PageLoad = async ({ url }) => {+ const templateId = url.searchParams.get('templateId');+ const fromStack = url.searchParams.get('fromStack');+ const sourceStackName = fromStack ? decodeURIComponent(fromStack) : null;++ const [allTemplates, defaultTemplates, selectedTemplate, sourceStack, globalVariables] = await Promise.all([+ templateService.getAllTemplates().catch((err) => {+ console.warn('Failed to load templates:', err);+ return [];+ }),+ templateService.getDefaultTemplates().catch((err) => {+ console.warn('Failed to load default templates:', err);+ return { composeTemplate: '', swarmStackTemplate: '', swarmStackEnvTemplate: '', envTemplate: '' };+ }),+ templateId+ ? templateService.getTemplateContent(templateId).catch((err) => {+ console.warn('Failed to load selected template:', err);+ return null;+ })+ : Promise.resolve(null),+ sourceStackName+ ? swarmService.getStackSource(sourceStackName).catch((err) => {+ console.warn('Failed to load source stack content:', err);+ return null;+ })+ : Promise.resolve(null),+ templateService.getGlobalVariables().catch((err) => {+ console.warn('Failed to load global variables:', err);+ return [];+ })+ ]);++ return {+ composeTemplates: allTemplates,+ envTemplate: selectedTemplate?.envContent ?? sourceStack?.envContent ?? defaultTemplates.swarmStackEnvTemplate,+ defaultTemplate: selectedTemplate?.content ?? sourceStack?.composeContent ?? defaultTemplates.swarmStackTemplate,+ selectedTemplate: selectedTemplate?.template || null,+ sourceStackName: sourceStack?.name || sourceStackName || null,+ globalVariables+ };+};diff --git a/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte b/frontend/src/routes/(app)/swarm/stacks/stacks-table.sveltenew file mode 100644index 000000000..c755a1406--- /dev/null+++ b/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte@@ -0,0 +1,163 @@+<script lang="ts">+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';+ import type { ColumnSpec, MobileFieldVisibility } from '$lib/components/arcane-table';+ import { UniversalMobileCard } from '$lib/components/arcane-table';+ import { LayersIcon, EllipsisIcon, InspectIcon, TrashIcon } from '$lib/icons';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import type { SwarmStackSummary } from '$lib/types/swarm.type';+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';+ import { formatDistanceToNow } from 'date-fns';+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ 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 { goto } from '$app/navigation';++ let {+ stacks = $bindable(),+ requestOptions = $bindable()+ }: {+ stacks: Paginated<SwarmStackSummary>;+ requestOptions: SearchPaginationSortRequest;+ } = $props();++ let isLoading = $state(false);++ function formatTimestamp(timestamp: string) {+ if (!timestamp) return m.common_unknown();+ return formatDistanceToNow(new Date(timestamp), { addSuffix: true });+ }++ function inspectStack(stack: SwarmStackSummary) {+ goto(`/swarm/stacks/${encodeURIComponent(stack.name)}`);+ }++ function handleDelete(stack: SwarmStackSummary) {+ openConfirmDialog({+ title: m.common_delete_title({ resource: m.swarm_stack() }),+ message: m.common_delete_confirm({ resource: m.swarm_stack() }),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(swarmService.removeStack(stack.name)),+ message: m.common_delete_failed({ resource: `${m.swarm_stack()} "${stack.name}"` }),+ setLoadingState: (v) => (isLoading = v),+ onSuccess: async () => {+ toast.success(m.common_delete_success({ resource: `${m.swarm_stack()} "${stack.name}"` }));+ stacks = await swarmService.getStacks(requestOptions);+ }+ });+ }+ }+ });+ }++ const columns = [+ { accessorKey: 'id', title: m.common_id(), hidden: true },+ { accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },+ { accessorKey: 'services', title: m.services(), sortable: true },+ { accessorKey: 'createdAt', title: m.common_created(), sortable: true, cell: CreatedCell },+ { accessorKey: 'updatedAt', title: m.common_updated(), sortable: true, cell: UpdatedCell }+ ] satisfies ColumnSpec<SwarmStackSummary>[];++ const mobileFields = [+ { id: 'services', label: m.services(), defaultVisible: true },+ { id: 'createdAt', label: m.common_created(), defaultVisible: true },+ { id: 'updatedAt', label: m.common_updated(), defaultVisible: false }+ ];++ let mobileFieldVisibility = $state<Record<string, boolean>>({});+</script>++{#snippet NameCell({ item }: { item: SwarmStackSummary })}+ <a href="/swarm/stacks/{encodeURIComponent(item.name)}" class="text-primary text-sm font-medium hover:underline">+ {item.name}+ </a>+{/snippet}++{#snippet CreatedCell({ value }: { value: unknown })}+ <span class="text-sm">{formatTimestamp(String(value ?? ''))}</span>+{/snippet}++{#snippet UpdatedCell({ value }: { value: unknown })}+ <span class="text-sm">{formatTimestamp(String(value ?? ''))}</span>+{/snippet}++{#snippet StackMobileCardSnippet({+ item,+ mobileFieldVisibility+}: {+ item: SwarmStackSummary;+ mobileFieldVisibility: MobileFieldVisibility;+})}+ <UniversalMobileCard+ {item}+ icon={() => ({+ component: LayersIcon,+ variant: 'purple'+ })}+ title={(item: SwarmStackSummary) => item.name}+ subtitle={(item: SwarmStackSummary) => ((mobileFieldVisibility.createdAt ?? true) ? formatTimestamp(item.createdAt) : null)}+ fields={[+ {+ label: m.services(),+ getValue: (item: SwarmStackSummary) => String(item.services),+ icon: LayersIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.services ?? true+ },+ {+ label: m.common_updated(),+ getValue: (item: SwarmStackSummary) => formatTimestamp(item.updatedAt),+ icon: LayersIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.updatedAt ?? false+ }+ ]}+ rowActions={RowActions}+ />+{/snippet}++{#snippet RowActions({ item }: { item: SwarmStackSummary })}+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ {#snippet child({ props })}+ <ArcaneButton {...props} action="base" tone="ghost" size="icon" class="relative size-8 p-0">+ <span class="sr-only">{m.common_open_menu()}</span>+ <EllipsisIcon />+ </ArcaneButton>+ {/snippet}+ </DropdownMenu.Trigger>+ <DropdownMenu.Content align="end">+ <DropdownMenu.Group>+ <DropdownMenu.Item onclick={() => inspectStack(item)}>+ <InspectIcon class="size-4" />+ {m.common_inspect()}+ </DropdownMenu.Item>+ <DropdownMenu.Separator />+ <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)} disabled={isLoading}>+ <TrashIcon class="size-4" />+ {m.common_delete()}+ </DropdownMenu.Item>+ </DropdownMenu.Group>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+{/snippet}++<ArcaneTable+ persistKey="arcane-swarm-stacks-table"+ items={stacks}+ bind:requestOptions+ bind:mobileFieldVisibility+ selectionDisabled={true}+ onRefresh={async (options) => (stacks = await swarmService.getStacks(options))}+ {columns}+ {mobileFields}+ rowActions={RowActions}+ mobileCard={StackMobileCardSnippet}+/>diff --git a/frontend/src/routes/(app)/swarm/tasks/+page.svelte b/frontend/src/routes/(app)/swarm/tasks/+page.sveltenew file mode 100644index 000000000..ea866e7f9--- /dev/null+++ b/frontend/src/routes/(app)/swarm/tasks/+page.svelte@@ -0,0 +1,74 @@+<script lang="ts">+ import { JobsIcon } from '$lib/icons';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import { untrack } from 'svelte';+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';+ import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';+ import { parallelRefresh } from '$lib/utils/refresh.util';+ import SwarmTasksTable from './tasks-table.svelte';++ let { data } = $props();++ let tasks = $state(untrack(() => data.tasks));+ let requestOptions = $state(untrack(() => data.requestOptions));+ let nodeId = $state(untrack(() => data.nodeId ?? ''));+ let isLoading = $state({ refresh: false });++ async function fetchTasks(options: typeof requestOptions) {+ if (nodeId) {+ return swarmService.getNodeTasks(nodeId, options);+ }+ return swarmService.getTasks(options);+ }++ async function refresh() {+ await parallelRefresh(+ {+ tasks: {+ fetch: () => fetchTasks(requestOptions),+ onSuccess: (data) => {+ tasks = data;+ },+ errorMessage: m.common_refresh_failed({ resource: m.swarm_tasks_title() })+ }+ },+ (v) => (isLoading.refresh = v)+ );+ }++ useEnvironmentRefresh(refresh);++ const totalTasks = $derived(tasks?.pagination?.totalItems ?? tasks?.data?.length ?? 0);++ const actionButtons: ActionButton[] = $derived([+ {+ id: 'refresh',+ action: 'restart',+ label: m.common_refresh(),+ onclick: refresh,+ loading: isLoading.refresh,+ disabled: isLoading.refresh+ }+ ]);++ const statCards: StatCardConfig[] = $derived([+ {+ title: m.swarm_tasks_total(),+ value: totalTasks,+ icon: JobsIcon,+ iconColor: 'text-blue-500'+ }+ ]);+</script>++<ResourcePageLayout+ title={m.swarm_tasks_title()}+ subtitle={nodeId ? m.swarm_tasks_subtitle_node_scoped() : m.swarm_tasks_subtitle()}+ {actionButtons}+ {statCards}+>+ {#snippet mainContent()}+ <SwarmTasksTable bind:tasks bind:requestOptions {fetchTasks} />+ {/snippet}+</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/swarm/tasks/+page.ts b/frontend/src/routes/(app)/swarm/tasks/+page.tsnew file mode 100644index 000000000..eb223093e--- /dev/null+++ b/frontend/src/routes/(app)/swarm/tasks/+page.ts@@ -0,0 +1,31 @@+import { swarmService } from '$lib/services/swarm-service';+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';+import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';+import type { PageLoad } from './$types';++export const load: PageLoad = async ({ url }) => {+ const searchParam = url.searchParams.get('search') || '';+ const nodeId = url.searchParams.get('nodeId') || '';+ const requestOptions = resolveInitialTableRequest('arcane-swarm-tasks-table', {+ pagination: {+ page: 1,+ limit: 20+ },+ sort: {+ column: 'service',+ direction: 'asc'+ }+ } satisfies SearchPaginationSortRequest);++ if (searchParam) {+ requestOptions.search = searchParam;+ }++ const tasks = nodeId ? await swarmService.getNodeTasks(nodeId, requestOptions) : await swarmService.getTasks(requestOptions);++ return {+ tasks,+ requestOptions,+ nodeId+ };+};diff --git a/frontend/src/routes/(app)/swarm/tasks/tasks-table.svelte b/frontend/src/routes/(app)/swarm/tasks/tasks-table.sveltenew file mode 100644index 000000000..842186f82--- /dev/null+++ b/frontend/src/routes/(app)/swarm/tasks/tasks-table.svelte@@ -0,0 +1,115 @@+<script lang="ts">+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';+ import type { ColumnSpec, MobileFieldVisibility } from '$lib/components/arcane-table';+ import { UniversalMobileCard } from '$lib/components/arcane-table';+ import { JobsIcon, ConnectionIcon } from '$lib/icons';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import type { SwarmTaskSummary } from '$lib/types/swarm.type';+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';++ let {+ tasks = $bindable(),+ requestOptions = $bindable(),+ fetchTasks = (options: SearchPaginationSortRequest) => swarmService.getTasks(options),+ persistKey = 'arcane-swarm-tasks-table'+ }: {+ tasks: Paginated<SwarmTaskSummary>;+ requestOptions: SearchPaginationSortRequest;+ fetchTasks?: (options: SearchPaginationSortRequest) => Promise<Paginated<SwarmTaskSummary>>;+ persistKey?: string;+ } = $props();++ function stateVariant(state: string): 'green' | 'amber' | 'red' | 'gray' {+ if (state === 'running') return 'green';+ if (state === 'pending' || state === 'starting') return 'amber';+ if (state === 'failed' || state === 'rejected' || state === 'shutdown') return 'red';+ return 'gray';+ }++ function iconVariant(state: string): 'emerald' | 'amber' | 'red' | 'gray' {+ if (state === 'running') return 'emerald';+ if (state === 'pending' || state === 'starting') return 'amber';+ if (state === 'failed' || state === 'rejected' || state === 'shutdown') return 'red';+ return 'gray';+ }++ const columns = [+ { accessorKey: 'id', title: m.common_id(), hidden: true },+ { accessorKey: 'name', title: m.common_name(), sortable: true },+ { accessorKey: 'serviceName', title: m.swarm_service(), sortable: true },+ { accessorKey: 'nodeName', title: m.swarm_node(), sortable: true },+ { accessorKey: 'currentState', title: m.swarm_current_state(), sortable: true, cell: StateCell },+ { accessorKey: 'desiredState', title: m.swarm_desired_state(), sortable: true, cell: DesiredStateCell }+ ] satisfies ColumnSpec<SwarmTaskSummary>[];++ const mobileFields = [+ { id: 'serviceName', label: m.swarm_service(), defaultVisible: true },+ { id: 'nodeName', label: m.swarm_node(), defaultVisible: true },+ { id: 'currentState', label: m.swarm_current_state(), defaultVisible: true },+ { id: 'desiredState', label: m.swarm_desired_state(), defaultVisible: false }+ ];++ let mobileFieldVisibility = $state<Record<string, boolean>>({});+</script>++{#snippet StateCell({ value }: { value: unknown })}+ <StatusBadge text={String(value ?? m.common_unknown())} variant={stateVariant(String(value ?? ''))} />+{/snippet}++{#snippet DesiredStateCell({ value }: { value: unknown })}+ <StatusBadge text={String(value ?? m.common_unknown())} variant={stateVariant(String(value ?? ''))} />+{/snippet}++{#snippet TaskMobileCardSnippet({+ item,+ mobileFieldVisibility+}: {+ item: SwarmTaskSummary;+ mobileFieldVisibility: MobileFieldVisibility;+})}+ <UniversalMobileCard+ {item}+ icon={() => ({+ component: JobsIcon,+ variant: iconVariant(item.currentState)+ })}+ title={(item: SwarmTaskSummary) => item.name}+ subtitle={(item: SwarmTaskSummary) => ((mobileFieldVisibility.serviceName ?? true) ? item.serviceName : null)}+ badges={[+ (item: SwarmTaskSummary) =>+ (mobileFieldVisibility.currentState ?? true)+ ? { variant: stateVariant(item.currentState), text: item.currentState }+ : null+ ]}+ fields={[+ {+ label: m.swarm_node(),+ getValue: (item: SwarmTaskSummary) => item.nodeName,+ icon: ConnectionIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.nodeName ?? true+ },+ {+ label: m.swarm_desired_state(),+ getValue: (item: SwarmTaskSummary) => item.desiredState,+ icon: ConnectionIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.desiredState ?? false+ }+ ]}+ />+{/snippet}++<ArcaneTable+ {persistKey}+ items={tasks}+ bind:requestOptions+ bind:mobileFieldVisibility+ selectionDisabled={true}+ onRefresh={async (options) => (tasks = await fetchTasks(options))}+ {columns}+ {mobileFields}+ mobileCard={TaskMobileCardSnippet}+/>diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.tsindex 067f95ce1..bd1a556ba 100644--- a/frontend/src/routes/+layout.ts+++ b/frontend/src/routes/+layout.ts@@ -12,6 +12,8 @@ import { authService } from '$lib/services/auth-service';import { tryCatch } from '$lib/utils/try-catch';import { QueryClient } from '@tanstack/svelte-query';import { queryKeys } from '$lib/query/query-keys';+import { systemService } from '$lib/services/system-service';+import type { DockerInfo } from '$lib/types/docker-info.type';export const ssr = false;@@ -61,6 +63,7 @@ export const load = async () => {// Step 2: Only fetch authenticated data if user is logged inlet settings = null;+ let dockerInfo: DockerInfo | null = null;if (user) {// Initialize environment store (required for settings service)@@ -81,6 +84,7 @@ export const load = async () => {// Fetch settings after environment store is initialized// Settings service depends on environmentStore.getCurrentEnvironmentId()settings = await settingsService.getSettings().catch(() => null);+ dockerInfo = await systemService.getDockerInfo().catch(() => null);} else {// Initialize empty environment store for unauthenticated usersawait environmentStore.initialize([]);@@ -133,6 +137,7 @@ export const load = async () => {user,settings,versionInformation,- queryClient+ queryClient,+ dockerInfo};};diff --git a/go.work.sum b/go.work.sumindex f2059a29b..8a28cd7b8 100644--- a/go.work.sum+++ b/go.work.sum@@ -25,6 +25,8 @@ cloud.google.com/go/spanner v1.85.0 h1:VVO3yW+0+Yx9tg4SQaZvJHGAnU6qCnGXQ3NX4E3+scloud.google.com/go/spanner v1.85.0/go.mod h1:9zhmtOEoYV06nE4Orbin0dc/ugHzZW9yXuvaM61rpxs=cloud.google.com/go/storage v1.56.0 h1:iixmq2Fse2tqxMbWhLWC9HfBj1qdxqAmiK8/eqtsLxI=cloud.google.com/go/storage v1.56.0/go.mod h1:Tpuj6t4NweCLzlNbw9Z9iwxEkrSem20AetIeH/shgVU=+code.cloudfoundry.org/clock v1.1.0 h1:XLzC6W3Ah/Y7ht1rmZ6+QfPdt1iGWEAAtIZXgiaj57c=+code.cloudfoundry.org/clock v1.1.0/go.mod h1:yA3fxddT9RINQL2XHS7PS+OXxKCGhfrZmlNUCIM6AKo=filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs=@@ -75,6 +77,8 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemappgithub.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=github.com/Microsoft/go-winio v0.4.21/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84=+github.com/Shopify/logrus-bugsnag v0.0.0-20170309145241-6dbc35f2c30d h1:hi6J4K6DKrR4/ljxn6SF6nURyu785wKMuQcjt7H3VCQ=+github.com/Shopify/logrus-bugsnag v0.0.0-20170309145241-6dbc35f2c30d/go.mod h1:HI8ITrYtUY+O+ZhtlqUnD8+KwNPOyugEhfP9fdUIaEQ=github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk=github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=github.com/VividCortex/ewma v1.2.0 h1:f58SaIzcDXrSy3kWaHNvuJgJ3Nmz59Zji6XoJR/q1ow=@@ -89,6 +93,7 @@ github.com/alecthomas/kingpin/v2 v2.4.0 h1:f48lwail6p8zpO1bC4TxtqACaGqHYA22qkHjHgithub.com/alecthomas/kingpin/v2 v2.4.0/go.mod h1:0gyi0zQnjuFk8xrkNKamJoyUo382HRL7ATRpFZCw6tE=github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc h1:cAKDfWh5VpdgMhJosfJnn5/FoN2SRZ4p7fJNX58YPaU=github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=+github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf h1:qet1QNfXsQxTZqLG4oE62mJzwPIB8+Tee4RNCL9ulrY=github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc=github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE=@@ -214,21 +219,32 @@ github.com/aws/smithy-go v1.23.2 h1:Crv0eatJUQhaManss33hS5r40CG3ZFH+21XSkqMrIUM=github.com/aws/smithy-go v1.23.2/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk=github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=+github.com/aymanbagabas/go-udiff v0.4.0/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w=github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=github.com/bitly/go-hostpool v0.1.0 h1:XKmsF6k5el6xHG3WPJ8U0Ku/ye7njX7W81Ng7O2ioR0=+github.com/bitly/go-hostpool v0.1.0/go.mod h1:4gOCgp6+NZnVqlKyZ/iBZFTAJKembaVENUpMkpg42fw=github.com/bitly/go-simplejson v0.5.0 h1:6IH+V8/tVMab511d5bn4M7EwGXZf9Hj6i2xSwkNEM+Y=+github.com/bitly/go-simplejson v0.5.0/go.mod h1:cXHtHw4XUPsvGaxgjIAn8PhEWG9NfngEKAMDJEczWVA=github.com/bits-and-blooms/bitset v1.24.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=github.com/bits-and-blooms/bitset v1.24.3 h1:Bte86SlO3lwPQqww+7BE9ZuUCKIjfqnG5jtEyqA9y9Y=github.com/bits-and-blooms/bitset v1.24.3/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=github.com/bits-and-blooms/bitset v1.24.4 h1:95H15Og1clikBrKr/DuzMXkQzECs1M6hhoGXLwLQOZE=github.com/bits-and-blooms/bitset v1.24.4/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=+github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=+github.com/bugsnag/bugsnag-go v1.0.5-0.20150529004307-13fd6b8acda0 h1:s7+5BfS4WFJoVF9pnB8kBk03S7pZXRdKamnV0FOl5Sc=+github.com/bugsnag/bugsnag-go v1.0.5-0.20150529004307-13fd6b8acda0/go.mod h1:2oa8nejYd4cQ/b0hMIopN0lCRxU0bueqREvZLWFrtK8=+github.com/bugsnag/osext v0.0.0-20130617224835-0dd3f918b21b h1:otBG+dV+YK+Soembjv71DPz3uX/V/6MMlSyD9JBQ6kQ=+github.com/bugsnag/osext v0.0.0-20130617224835-0dd3f918b21b/go.mod h1:obH5gd0BsqsP2LwDJ9aOkm/6J86V6lyAXCoQWGw3K50=+github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0 h1:nvj0OLI3YqYXer/kZD8Ri1aaunCxIEsOst1BVJswV0o=+github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0/go.mod h1:D/8v3kj0zr8ZAKg1AQ6crr+5VwKN5eIywRkfhyM/+dE=github.com/bwesterb/go-ristretto v1.2.3 h1:1w53tCkGhCQ5djbat3+MH0BAQ5Kfgbt56UZQ/JMzngw=github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=+github.com/certifi/gocertifi v0.0.0-20200922220541-2c3bb06c6054 h1:uH66TXeswKn5PW5zdZ39xEwfS9an067BirqA+P4QaLI=github.com/charmbracelet/x/ansi v0.11.3/go.mod h1:yI7Zslym9tCJcedxz5+WBq+eUGMJT0bM06Fqy1/Y4dI=github.com/checkpoint-restore/checkpointctl v1.4.0 h1:3kRns56TArwiyHOMakaumUgSZZlB1hZBkjVgR6IeZ3E=github.com/checkpoint-restore/checkpointctl v1.4.0/go.mod h1:ynQ52zQBazgcTZuxpwTFzRinIcAf0haDTC1X1LA/FKA=@@ -251,6 +267,9 @@ github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfagithub.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=+github.com/cloudflare/cfssl v0.0.0-20180223231731-4e2dcbde5004/go.mod h1:yMWuSON2oQp+43nFtAV/uvKQIFpSPerB57DCt9t8sSA=+github.com/cloudflare/cfssl v1.6.4 h1:NMOvfrEjFfC63K3SGXgAnFdsgkmiq4kATme5BfcqrO8=+github.com/cloudflare/cfssl v1.6.4/go.mod h1:8b3CQMxfWPAeom3zBnGJ6sd+G1NkL5TXqmDXacb+1J0=github.com/cloudflare/circl v1.6.0 h1:cr5JKic4HI+LkINy2lg3W2jF8sHCVTBncJr5gIIq7qk=github.com/cloudflare/circl v1.6.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 h1:F1EaeKL/ta07PY/k9Os/UFtwERei2/XzGemhpGnBKNg=@@ -264,7 +283,12 @@ github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tgithub.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI=github.com/cockroachdb/cockroach-go/v2 v2.1.1 h1:3XzfSMuUT0wBe1a3o5C0eOTcArhmmFAg2Jzh/7hhKqo=github.com/cockroachdb/cockroach-go/v2 v2.1.1/go.mod h1:7NtUnP6eK+l6k483WSYNrq3Kb23bWV10IRV1TyeSpwM=+github.com/cockroachdb/datadriven v0.0.0-20200714090401-bf6692d28da5 h1:xD/lrqdvwsc+O2bjSSi3YqY73Ke3LAiSCx49aCesA0E=+github.com/cockroachdb/errors v1.2.4 h1:Lap807SXTH5tri2TivECb/4abUkMZC9zRoLarvcKDqs=+github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f h1:o/kfcElHqOiXqcou5a3rIlMc7oJbMQkeLk0VQJ7zgqY=github.com/compose-spec/compose-go/v2 v2.9.1/go.mod h1:Oky9AZGTRB4E+0VbTPZTUu4Kp+oEMMuwZXZtPPVT1iE=+github.com/container-storage-interface/spec v1.2.0 h1:bD9KIVgaVKKkQ/UbVUY9kCaH/CJbhNxe0eeB4JeJV2s=+github.com/container-storage-interface/spec v1.2.0/go.mod h1:6URME8mwIBbpVyZV93Ce5St17xBiQJQY67NDsuohiy4=github.com/containerd/accelerated-container-image v1.3.0 h1:sFbTgSuMboeKHa9f7MY11hWF1XxVWjFoiTsXYtOtvdU=github.com/containerd/accelerated-container-image v1.3.0/go.mod h1:EvKVWor6ZQNUyYp0MZm5hw4k21ropuz7EegM+m/Jb/Q=github.com/containerd/btrfs/v2 v2.0.0 h1:FN4wsx7KQrYoLXN7uLP0vBV4oVWHOIKDRQ1G2Z0oL5M=@@ -314,8 +338,6 @@ github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSjgithub.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w=github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo=github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=-github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=-github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=github.com/cznic/mathutil v0.0.0-20180504122225-ca4c9f2c1369 h1:XNT/Zf5l++1Pyg08/HV04ppB0gKxAqtZQBRYiYrUuYk=github.com/cznic/mathutil v0.0.0-20180504122225-ca4c9f2c1369/go.mod h1:e6NPNENfs9mPDVNRekM7lKScauxd5kXTr1Mfyig6TDM=github.com/danielgtaylor/huma/v2 v2.35.0 h1:FRg3FgVKcMogVhbNY7FjyTwk+p/orLBR3hQBvXXg7dw=@@ -329,6 +351,7 @@ github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=github.com/denisenkom/go-mssqldb v0.0.0-20191128021309-1d7a30a10f73 h1:OGNva6WhsKst5OZf7eZOklDztV3hwtTHovdrLHV+MsA=+github.com/denisenkom/go-mssqldb v0.0.0-20191128021309-1d7a30a10f73/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=github.com/digitorus/pkcs7 v0.0.0-20230713084857-e76b763bdc49/go.mod h1:SKVExuS+vpu2l9IoOc0RwqE7NYnb0JlcFHFnEJkVDzc=github.com/dimchansky/utfbom v1.1.1 h1:vV6w1AhK4VMnhBno/TPVCoK9U/LP0PkLCS9tbxHdi/U=github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE=@@ -340,12 +363,15 @@ github.com/docker/cli-docs-tool v0.10.0/go.mod h1:5EM5zPnT2E7yCLERZmrDA234Vwn09fgithub.com/docker/cli-docs-tool v0.11.0 h1:7d8QARFb7QEobizqxmEM7fOteZEHwH/zWgHQtHZEcfE=github.com/docker/cli-docs-tool v0.11.0/go.mod h1:ma8BKiisUo8D6W05XEYIh3oa1UbgrZhi1nowyKFJa8Q=github.com/docker/compose/v5 v5.0.0/go.mod h1:BurapGv8zmYnsbSmlpCz5EU2Pi3YFV/PjeUnoFpcw64=-github.com/docker/docker-credential-helpers v0.9.3/go.mod h1:x+4Gbw9aGmChi3qTLZj8Dfn0TD20M/fuWy0E5+WDeCo=-github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc=+github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=+github.com/docker/go v1.5.1-1.0.20160303222718-d30aec9fd63c h1:lzqkGL9b3znc+ZUgi7FlLnqjQhcXxkNM/quxIjBVMD0=+github.com/docker/go v1.5.1-1.0.20160303222718-d30aec9fd63c/go.mod h1:CADgU4DSXK5QUlFslkQu2yW2TKzFZcXq/leZfM0UH5Q=+github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c h1:+pKlWGMw7gf6bQ+oDZB4KHQFypsfjYlq/C4rfL7D3g8=github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA=github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 h1:UhxFibDNY/bfvqU5CAUmr9zpesgbU6SWc8/B4mflAE4=github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7/go.mod h1:cyGadeNEkKy96OOhEzfZl+yxihPEzKnqJwvfuSUqbZE=+github.com/dvsekhvalnov/jose2go v0.0.0-20170216131308-f21a8cedbbae/go.mod h1:7BvyPhdbLxMXIYTFPLsyJRFMsKmOZnQmzh6Gb+uquuM=github.com/dvsekhvalnov/jose2go v1.7.0 h1:bnQc8+GMnidJZA8zc6lLEAb4xNrIqHwO+9TzqvtQZPo=github.com/dvsekhvalnov/jose2go v1.7.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU=github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712 h1:aaQcKT9WumO6JEJcRyTqFVq4XUZiUcKR2/GI31TOcz8=@@ -371,21 +397,22 @@ github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2Tgithub.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4=github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA=github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y=+github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0=github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU=github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM=github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g=github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw=+github.com/fernet/fernet-go v0.0.0-20211208181803-9f70042a33ee h1:v6Eju/FhxsACGNipFEPBZZAzGr1F/jlRQr1qiBw2nEE=+github.com/fernet/fernet-go v0.0.0-20211208181803-9f70042a33ee/go.mod h1:2H9hjfbpSMHwY503FclkV/lZTBh2YlOmLLSda12uL8c=github.com/form3tech-oss/jwt-go v3.2.5+incompatible h1:/l4kBbb4/vGSsdtB5nUe8L7B9mImVMaBPw9L/0TBHU8=github.com/form3tech-oss/jwt-go v3.2.5+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k=github.com/francoispqt/gojay v1.2.13 h1:d2m3sFjloqoIUQU3TsHBgj6qg/BVGlTBeHDUmyJnXKk=github.com/francoispqt/gojay v1.2.13/go.mod h1:ehT5mTG4ua4581f1++1WLG0vPdaA9HaiDsoyrBGkyDY=-github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=-github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=-github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU=github.com/fsouza/fake-gcs-server v1.17.0 h1:OeH75kBZcZa3ZE+zz/mFdJ2btt9FgqfjI7gIh9+5fvk=github.com/fsouza/fake-gcs-server v1.17.0/go.mod h1:D1rTE4YCyHFNa99oyJJ5HyclvN/0uQR+pM/VdlL83bw=github.com/getarcaneapp/arcane/types v0.0.0-20251219045603-8a9960a2bf04/go.mod h1:7Wj+0JnpYq4RQS+otyM6e4zkyJKDC01wxkWPyFCHwZA=-github.com/getarcaneapp/arcane/types v0.0.0-20260209233421-0952125a149f/go.mod h1:oTa9ugCyTbytH0YTl8Wzlh1mtlMSTT8s4exVzd7zaUo=+github.com/getsentry/raven-go v0.2.0 h1:no+xWJRb5ZI7eE8TWgIq1jLulQiIoLG0IfYxv5JYMGs=+github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ=github.com/go-chi/chi/v5 v5.2.2 h1:CMwsvRVTbXVytCk1Wd72Zy1LAsAh9GxMmSNWLHCG618=github.com/go-chi/chi/v5 v5.2.2/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=@@ -410,6 +437,7 @@ github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+Grgithub.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=github.com/go-rod/rod v0.116.2 h1:A5t2Ky2A+5eD/ZJQr1EfsQSe5rms5Xof/qj296e+ZqA=github.com/go-rod/rod v0.116.2/go.mod h1:H+CMO9SCNc2TJ2WfrG+pKhITz57uGNYU43qYHh438Mg=+github.com/go-sql-driver/mysql v1.3.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=@@ -433,9 +461,10 @@ github.com/gofiber/fiber/v2 v2.52.9 h1:YjKl5DOiyP3j0mO61u3NTmK7or8GzzWzCFzkboyP5github.com/gofiber/fiber/v2 v2.52.9/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=github.com/gofiber/fiber/v2 v2.52.11 h1:5f4yzKLcBcF8ha1GQTWB+mpblWz3Vz6nSAbTL31HkWs=github.com/gofiber/fiber/v2 v2.52.11/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=+github.com/gofiber/fiber/v2 v2.52.12 h1:0LdToKclcPOj8PktUdIKo9BUohjjwfnQl42Dhw8/WUw=+github.com/gofiber/fiber/v2 v2.52.12/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=github.com/gogo/googleapis v1.4.1 h1:1Yx4Myt7BxzvUr5ldGSbwYiZG6t9wGBZ+8/fX3Wvtq0=github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4=-github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=@@ -457,12 +486,11 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqgithub.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=-github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=-github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=github.com/google/cel-go v0.25.0/go.mod h1:hjEb6r5SuOSlhCHmFoLzu8HGCERvIsDAbxDAyNU/MmI=+github.com/google/certificate-transparency-go v1.1.4/go.mod h1:D6lvbfwckhNrbM9WVl1EVeMOyzC19mpIjMOI4nxBHtQ=github.com/google/certtostore v1.0.6 h1:LlCIgyTvDxTlcncMPTSYZGo6lCsiHzO6Dy7ff6ltk/0=github.com/google/certtostore v1.0.6/go.mod h1:2N0ZPLkGvQWhYvXaiBGq02r71fnSLfq78VKIWQHr1wo=github.com/google/deck v0.0.0-20230104221208-105ad94aa8ae h1:Iy1Ad7L9qPtNAFJad+Ch2kwDXrcwu7QUBR0bfChjnEM=@@ -477,7 +505,6 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywgithub.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=-github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=github.com/google/go-containerregistry v0.20.6/go.mod h1:T0x8MuoAoKX/873bkeSfLD2FAkwCDf9/HZgsFJ02E2Y=@@ -491,8 +518,6 @@ github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw=github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg=github.com/google/pprof v0.0.0-20250820193118-f64d9cf942d6/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U=-github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc h1:VBbFa1lDYWEeV5FZKUiYKYT0VxCp9twUmmaq9eb8sXw=-github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI=github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=github.com/google/trillian v1.7.2 h1:EPBxc4YWY4Ak8tcuhyFleY+zYlbCDCa4Sn24e1Ka8Js=@@ -505,6 +530,7 @@ github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc=github.com/gorilla/handlers v1.4.2 h1:0QniY0USkHQ1RGCLfKxeNHK9bkDHGRYGNDFBCS+YARg=github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ=+github.com/gorilla/mux v1.7.0/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc h1:GN2Lv3MGO7AS6PrRoT6yV5+wkrOpcszoIsO4+4ds248=github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk=github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw=@@ -514,6 +540,8 @@ github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0/go.modgithub.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0 h1:pRhl55Yx1eC7BZ1N+BBWwnKaMyD8uC+34TLdndZMAKk=github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0/go.mod h1:XKMd7iuf/RGPSMJ/U4HP0zS2Z9Fh8Ps9a+6X26m/tmI=github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3/go.mod h1:NbCUVmiS4foBGBHOYlCT25+YmGpJ32dZPi75pGEUpj4=+github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho=+github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1/go.mod h1:tIxuGz/9mpox++sgp9fJjHO0+q1X9/UOWd798aAm22M=github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs=github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU=@@ -526,10 +554,16 @@ github.com/hanwen/go-fuse/v2 v2.9.0 h1:0AOGUkHtbOVeyGLr0tXupiid1Vg7QB7M6YUcdmVdCgithub.com/hanwen/go-fuse/v2 v2.9.0/go.mod h1:yE6D2PqWwm3CbYRxFXV9xUd8Md5d6NG0WBs5spCswmI=github.com/hashicorp/go-cty-funcs v0.0.0-20250818135842-6aab67130928 h1:NFpfJOqEV8DUhomtXx9A0FfcMg7OCYRugdyw6Ar/Y7s=github.com/hashicorp/go-cty-funcs v0.0.0-20250818135842-6aab67130928/go.mod h1:YC9ASYt9Z9sQEAtzCe+yaAzi3E7wcxfRphDXtwZoWC0=+github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc=+github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=github.com/hashicorp/go-immutable-radix/v2 v2.1.0 h1:CUW5RYIcysz+D3B+l1mDeXrQ7fUvGGCwJfdASSzbrfo=github.com/hashicorp/go-immutable-radix/v2 v2.1.0/go.mod h1:hgdqLXA4f6NIjRVisM1TJ9aOJVNRqKZj+xDGF6m7PBw=+github.com/hashicorp/go-memdb v1.3.2 h1:RBKHOsnSszpU6vxq80LzC2BaQjuuvoyaQbkLTf7V7g8=+github.com/hashicorp/go-memdb v1.3.2/go.mod h1:Mluclgwib3R93Hk5fxEfiRhB+6Dar64wWh71LpNSe3g=github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48=github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw=+github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc=+github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4=github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=@@ -539,10 +573,9 @@ github.com/hashicorp/hcl/v2 v2.24.0/go.mod h1:oGoO1FIQYfn/AgyOhlg9qLC6/nOJPX3qGbgithub.com/hiddeco/sshsig v0.2.0 h1:gMWllgKCITXdydVkDL+Zro0PU96QI55LwUwebSwNTSw=github.com/hiddeco/sshsig v0.2.0/go.mod h1:nJc98aGgiH6Yql2doqH4CTBVHexQA40Q+hMMLHP4EqE=github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=-github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=-github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=github.com/ianlancetaylor/demangle v0.0.0-20210905161508-09a460cdf81d/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w=github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=+github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=github.com/intel/goresctrl v0.10.0 h1:Q94PBhLtQM/aVxVTKzB1j/ooMuV+9XleTN1fq2OGsSo=github.com/intel/goresctrl v0.10.0/go.mod h1:1S8GDqL46GuKb525bxNhIEEkhf4rhVcbSf9DuKhp7mw=github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8=@@ -561,8 +594,14 @@ github.com/jackc/pgx/v4 v4.18.2 h1:xVpYkNR5pk5bMCZGfClbO962UIqVABcAGt7ha1s/FeU=github.com/jackc/pgx/v4 v4.18.2/go.mod h1:Ey4Oru5tH5sB6tV7hDmfWFahwF15Eb7DNXlRKx2CkVw=github.com/jedisct1/go-minisign v0.0.0-20211028175153-1c139d1cc84b h1:ZGiXF8sz7PDk6RgkP+A/SFfUD0ZR/AgG6SpRNEDKZy8=github.com/jedisct1/go-minisign v0.0.0-20211028175153-1c139d1cc84b/go.mod h1:hQmNrgofl+IY/8L+n20H6E6PWBBTokdsv+q49j0QhsU=+github.com/jinzhu/gorm v0.0.0-20170222002820-5409931a1bb8 h1:CZkYfurY6KGhVtlalI4QwQ6T0Cu6iuY3e0x5RLu96WE=+github.com/jinzhu/gorm v0.0.0-20170222002820-5409931a1bb8/go.mod h1:Vla75njaFJ8clLU1W44h34PjIkijhjHIYnZxMqCdxqo=+github.com/jinzhu/inflection v0.0.0-20170102125226-1c35d901db3d/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=+github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=+github.com/jmoiron/sqlx v1.3.3 h1:j82X0bf7oQ27XeqxicSZsTU5suPwKElg3oyxNn43iTk=+github.com/jmoiron/sqlx v1.3.3/go.mod h1:2BljVx/86SuTyjE+aPYlHCTNvZrnJXghYGpNiXLBMCQ=github.com/jordanlewis/gcassert v0.0.0-20250430164644-389ef753e22e h1:a+PGEeXb+exwBS3NboqXHyxarD9kaboBbrSp+7GuBuc=github.com/jordanlewis/gcassert v0.0.0-20250430164644-389ef753e22e/go.mod h1:ZybsQk6DWyN5t7An1MuPm1gtSZ1xDaTXS9ZjIOxvQrk=github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=@@ -572,7 +611,6 @@ github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FXgithub.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=github.com/juju/loggo v0.0.0-20190526231331-6e530bcce5d8 h1:UUHMLvzt/31azWTN/ifGWef4WUqvXk0iRqdhdy/2uzI=-github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213 h1:qGQQKEcAR99REcMpsXCp3lJ03zYT1PkRd3kQGPn9GVg=@@ -599,6 +637,7 @@ github.com/knqyf263/go-plugin v0.9.0/go.mod h1:2z5lCO1/pez6qGo8CvCxSlBFSEat4MEp1github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s=+github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515 h1:T+h1c/A9Gawja4Y9mFVWj2vyii2bbUNDw3kt9VxK2EY=github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=@@ -632,8 +671,9 @@ github.com/letsencrypt/boulder v0.0.0-20240620165639-de9c06129bec h1:2tTW6cDth2Tgithub.com/letsencrypt/boulder v0.0.0-20240620165639-de9c06129bec/go.mod h1:TmwEoGCwIti7BCeJ9hescZgRtatxRE+A72pCoPfmcfk=github.com/letsencrypt/boulder v0.20251110.0 h1:J8MnKICeilO91dyQ2n5eBbab24neHzUpYMUIOdOtbjc=github.com/letsencrypt/boulder v0.20251110.0/go.mod h1:ogKCJQwll82m7OVHWyTuf8eeFCjuzdRQlgnZcCl0V+8=-github.com/lmittmann/tint v1.1.2 h1:2CQzrL6rslrsyjqLDwD11bZ5OpLBPU+g3G/r5LSfS8w=-github.com/lmittmann/tint v1.1.2/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=+github.com/lib/pq v0.0.0-20150723085316-0dad96c0b94f/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=+github.com/magiconair/properties v1.5.3 h1:C8fxWnhYyME3n0klPOhVM7PtYUB3eV1W3DeFmN3j53Y=+github.com/magiconair/properties v1.5.3/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=github.com/magiconair/properties v1.8.9 h1:nWcCbLq1N2v/cpNsy5WvQ37Fb+YElfq20WJ/a8RkpQM=@@ -647,9 +687,11 @@ github.com/markbates/pkger v0.15.1/go.mod h1:0JoVlrol20BSywW79rN3kdFFsE5xYM+rSCQgithub.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=github.com/mattn/go-runewidth v0.0.17/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=-github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=+github.com/mattn/go-sqlite3 v1.6.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=+github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=+github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=github.com/mdlayher/vsock v1.2.1 h1:pC1mTJTvjo1r9n9fbm7S1j04rCgCzhCOS5DY0zqHlnQ=@@ -658,6 +700,7 @@ github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fgithub.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=github.com/microsoft/go-mssqldb v1.0.0 h1:k2p2uuG8T5T/7Hp7/e3vMGTnnR0sU4h8d1CcC71iLHU=github.com/microsoft/go-mssqldb v1.0.0/go.mod h1:+4wZTUnz/SV6nffv+RRRB/ss8jPng5Sho2SmM1l2ts4=+github.com/miekg/pkcs11 v1.0.2/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs=github.com/miekg/pkcs11 v1.1.1 h1:Ugu9pdy6vAYku5DEpVWVFPYnzV+bxB+iRdbuFSu7TvU=github.com/miekg/pkcs11 v1.1.1/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs=github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8 h1:AMFGa4R4MiIpspGNG7Z948v4n35fFGB3RR3G/ry4FWs=@@ -672,6 +715,7 @@ github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjcgithub.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=+github.com/mitchellh/mapstructure v0.0.0-20150613213606-2caf8efc9366/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=@@ -696,14 +740,12 @@ github.com/moby/sys/mount v0.3.4 h1:yn5jq4STPztkkzSKpZkLcmjue+bZJ0u2AuQY1iNI1Ww=github.com/moby/sys/mount v0.3.4/go.mod h1:KcQJMbQdJHPlq5lcYT+/CjatWM4PuxKe+XLSVS4J6Os=github.com/moby/sys/reexec v0.1.0 h1:RrBi8e0EBTLEgfruBOFcxtElzRGTEUkeIFaVXgU7wok=github.com/moby/sys/reexec v0.1.0/go.mod h1:EqjBg8F3X7iZe5pU6nRZnYCMUTXoxsjiIfHup5wYIN8=-github.com/moby/term v0.0.0-20221205130635-1aeaba878587/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=-github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=-github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs=github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns=github.com/mutecomm/go-sqlcipher/v4 v4.4.0 h1:sV1tWCWGAVlPhNGT95Q+z/txFxuhAYWwHD1afF5bMZg=github.com/mutecomm/go-sqlcipher/v4 v4.4.0/go.mod h1:PyN04SaWalavxRGH9E8ZftG6Ju7rsPrGmQRjrEaVpiY=+github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223 h1:F9x/1yl3T2AeKLr2AMdilSD8+f9bvMnNN8VS5iDtovc=github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+SVif2QVs3tOP0zanoHgBEVAwHxUSIzRqU=github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=@@ -713,38 +755,39 @@ github.com/nakagami/firebirdsql v0.0.0-20190310045651-3c02a58cfed8 h1:P48LjvUQpTgithub.com/nakagami/firebirdsql v0.0.0-20190310045651-3c02a58cfed8/go.mod h1:86wM1zFnC6/uDBfZGNwB65O+pR2OFi5q/YQaEUid1qA=github.com/neo4j/neo4j-go-driver v1.8.1-0.20200803113522-b626aa943eba h1:fhFP5RliM2HW/8XdcO5QngSfFli9GcRIpMXvypTQt6E=github.com/neo4j/neo4j-go-driver v1.8.1-0.20200803113522-b626aa943eba/go.mod h1:ncO5VaFWh0Nrt+4KT4mOZboaczBZcLuHrG+/sUeP8gI=-github.com/nicholas-fedor/shoutrrr v0.14.1 h1:6sx4cJNfNuUtD6ygGlB0dqcCQ+abfsUh+b+6jgujf6A=-github.com/nicholas-fedor/shoutrrr v0.14.1/go.mod h1:U7IywBkLpBV7rgn8iLbQ9/LklJG1gm24bFv5cXXsDKs=github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=-github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=+github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=+github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=-github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=-github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=+github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=-github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=-github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=+github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA=github.com/onsi/gomega v1.15.0 h1:WjP/FQ/sk43MRmnEcT+MlDw2TFvkrXlprrPST/IudjU=github.com/onsi/gomega v1.15.0/go.mod h1:cIuvLEne0aoVhAgh/O6ac0Op8WWw9H6eYCriF+tEHG0=github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro=github.com/open-policy-agent/opa v1.10.1 h1:haIvxZSPky8HLjRrvQwWAjCPLg8JDFSZMbbG4yyUHgY=github.com/open-policy-agent/opa v1.10.1/go.mod h1:7uPI3iRpOalJ0BhK6s1JALWPU9HvaV1XeBSSMZnr/PM=+github.com/opencontainers/go-digest v0.0.0-20170106003457-a6d0ee40d420/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s=+github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0=github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=github.com/opencontainers/runtime-tools v0.9.1-0.20250523060157-0ea5ed0382a2 h1:2xZEHOdeQBV6PW8ZtimN863bIOl7OCW/X10K0cnxKeA=github.com/opencontainers/runtime-tools v0.9.1-0.20250523060157-0ea5ed0382a2/go.mod h1:MXdPzqAA8pHC58USHqNCSjyLnRQ6D+NjbpP+02Z1U/0=github.com/opencontainers/runtime-tools v0.9.1-0.20251114084447-edf4cb3d2116 h1:tAKu3NkKWZYpqBSOJKwTxT1wIGueiF7gcmcNgr5pNTY=github.com/opencontainers/runtime-tools v0.9.1-0.20251114084447-edf4cb3d2116/go.mod h1:DKDEfzxvRkoQ6n9TGhxQgg2IM1lY4aM0eaQP4e3oElw=+github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU=+github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=github.com/otiai10/copy v1.14.1 h1:5/7E6qsUMBaH5AnQ0sSLzzTg1oTECmcCmT6lvF45Na8=github.com/otiai10/copy v1.14.1/go.mod h1:oQwrEDDOci3IM8dJF0d8+jnbfPDllW6vUjNc3DoZm9I=github.com/otiai10/mint v1.6.3 h1:87qsV/aw1F5as1eH1zS/yqHY85ANKVMgkDrf9rcxbQs=github.com/otiai10/mint v1.6.3/go.mod h1:MJm72SBthJjz8qhefc4z1PYEieWmy8Bku7CjcAqyUSM=-github.com/pelletier/go-toml/v2 v2.3.0 h1:k59bC/lIZREW0/iVaQR8nDHxVq8OVlIzYCOJf421CaM=-github.com/pelletier/go-toml/v2 v2.3.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 h1:Dx7Ovyv/SFnMFw3fD4oEoeorXc6saIiQ23LrGLth0Gw=github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=+github.com/phayes/permbits v0.0.0-20190612203442-39d7c581d2ee h1:P6U24L02WMfj9ymZTxl7CxS73JC99x3ukk+DBkgQGQs=+github.com/phayes/permbits v0.0.0-20190612203442-39d7c581d2ee/go.mod h1:3uODdxMgOaPYeWU7RzZLxVtJHZ/x1f/iHkBZuKJDzuY=github.com/pierrec/lz4/v4 v4.1.16 h1:kQPfno+wyx6C5572ABwV+Uo3pDFzQ7yhyGchSyRda0c=github.com/pierrec/lz4/v4 v4.1.16/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI=@@ -759,20 +802,11 @@ github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjgithub.com/planetscale/vtprotobuf v0.6.0/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=github.com/proglottis/gpgme v0.1.5 h1:KCGyOw8sQ+SI96j6G8D8YkOGn+1TwbQTT9/zQXoVlz0=github.com/proglottis/gpgme v0.1.5/go.mod h1:5LoXMgpE4bttgwwdv9bLs/vwqv3qV7F4glEEZ7mRKrM=-github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=-github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=-github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g=-github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=-github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=-github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=-github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc=github.com/prometheus/otlptranslator v0.0.2 h1:+1CdeLVrRQ6Psmhnobldo0kTp96Rj80DRXRd5OSnMEQ=github.com/prometheus/otlptranslator v0.0.2/go.mod h1:P8AwMgdD7XEr6QRUJ2QWLpiAZTgTE2UYgjlu3svompI=-github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=-github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=-github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ=github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=+github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 h1:bsUq1dX0N8AOIL7EB/X911+m4EHsnWEHeJ0c+3TTBrg=github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=@@ -811,8 +845,6 @@ github.com/sigstore/protobuf-specs v0.4.1 h1:5SsMqZbdkcO/DNHudaxuCUEjj6x29tS2Xbygithub.com/sigstore/protobuf-specs v0.4.1/go.mod h1:+gXR+38nIa2oEupqDdzg4qSBT0Os+sP7oYv6alWewWc=github.com/sigstore/sigstore v1.9.5 h1:Wm1LT9yF4LhQdEMy5A2JeGRHTrAWGjT3ubE5JUSrGVU=github.com/sigstore/sigstore v1.9.5/go.mod h1:VtxgvGqCmEZN9X2zhFSOkfXxvKUjpy8RpUW39oCtoII=-github.com/sigstore/sigstore v1.10.0/go.mod h1:Ygq+L/y9Bm3YnjpJTlQrOk/gXyrjkpn3/AEJpmk1n9Y=-github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=@@ -822,18 +854,13 @@ github.com/snowflakedb/gosnowflake v1.6.19 h1:KSHXrQ5o7uso25hNIzi/RObXtnSGkFgie9github.com/snowflakedb/gosnowflake v1.6.19/go.mod h1:FM1+PWUdwB9udFDsXdfD58NONC0m+MlOSmQRvimobSM=github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=-github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0=github.com/spf13/jwalterweatherman v0.0.0-20141219030609-3d60171a6431 h1:XTHrT015sxHyJ5FnQ0AeemSspZWaDq7DoTRW0EVsDCE=-github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6 h1:pnnLyeX7o/5aX8qUQ69P/mLojDqwda8hFOCBTmP/6hw=github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6/go.mod h1:39R/xuhNgVhi+K0/zst4TLrJrVmbm6LVgl4A0+ZFS5M=github.com/stoewer/go-strcase v1.3.0/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo=-github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=-github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=-github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=@@ -851,6 +878,8 @@ github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+Cgithub.com/tetratelabs/wazero v1.10.1 h1:2DugeJf6VVk58KTPszlNfeeN8AhhpwcZqkJj2wwFuH8=github.com/tetratelabs/wazero v1.10.1/go.mod h1:DRm5twOQ5Gr1AoEdSi0CLjDQF1J9ZAuyqFIjl1KKfQU=github.com/theupdateframework/go-tuf v0.7.0/go.mod h1:uEB7WSY+7ZIugK6R1hiBMBjQftaFzn7ZCDJcp1tCUug=+github.com/theupdateframework/notary v0.7.0 h1:QyagRZ7wlSpjT5N2qQAh/pN+DVqgekv4DzbAiAiEL3c=+github.com/theupdateframework/notary v0.7.0/go.mod h1:c9DRxcmhHmVLDay4/2fUYdISnHqbFDGRSlXPO0AhYWw=github.com/tink-crypto/tink-go/v2 v2.5.0 h1:B8KLF6AofxdBIE4UJIaFbmoj5/1ehEtt7/MmzfI4Zpw=github.com/tink-crypto/tink-go/v2 v2.5.0/go.mod h1:2WbBA6pfNsAfBwDCggboaHeB2X29wkU8XHtGwh2YIk8=github.com/titanous/rocacheck v0.0.0-20171023193734-afe73141d399 h1:e/5i7d4oYZ+C1wj2THlRK+oAhjeS/TRQwMfkIuet3w0=@@ -889,6 +918,8 @@ github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJWgithub.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=+github.com/weppos/publicsuffix-go v0.15.1-0.20210511084619-b1f36a2d6c0b h1:FsyNrX12e5BkplJq7wKOLk0+C6LZ+KGXvuEcKUYm5ss=+github.com/weppos/publicsuffix-go v0.15.1-0.20210511084619-b1f36a2d6c0b/go.mod h1:HYux0V0Zi04bHNwOHy4cXJVz/TQjYonnF6aoYhj+3QE=github.com/xanzy/go-gitlab v0.15.0 h1:rWtwKTgEnXyNUGrOArN7yyc3THRkpYcKXIXia9abywQ=github.com/xanzy/go-gitlab v0.15.0/go.mod h1:8zdQa/ri1dfn8eS3Ir1SyfvOKlw7WBJ8DVThkpGiXrs=github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=@@ -935,10 +966,19 @@ github.com/zeebo/errs v1.4.0 h1:XNdoD/RRMKP7HD0UhJnIzUy74ISdGGxURlYG8HSWSfM=github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4=github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=+github.com/zmap/zcrypto v0.0.0-20210511125630-18f1e0152cfc h1:zkGwegkOW709y0oiAraH/3D8njopUR/pARHv4tZZ6pw=+github.com/zmap/zcrypto v0.0.0-20210511125630-18f1e0152cfc/go.mod h1:FM4U1E3NzlNMRnSUTU3P1UdukWhYGifqEsjk9fn7BCk=+github.com/zmap/zlint/v3 v3.1.0 h1:WjVytZo79m/L1+/Mlphl09WBob6YTGljN5IGWZFpAv0=+github.com/zmap/zlint/v3 v3.1.0/go.mod h1:L7t8s3sEKkb0A2BxGy1IWrxt1ZATa1R4QfJZaQOD3zU=gitlab.com/nyarla/go-crypt v0.0.0-20160106005555-d9a5dc2b789b h1:7gd+rd8P3bqcn/96gOZa3F5dpJr/vEiDQYlNb/y2uNs=gitlab.com/nyarla/go-crypt v0.0.0-20160106005555-d9a5dc2b789b/go.mod h1:T3BPAOm2cqquPa0MKWeNkmOM5RQsRhkrwMWonFMN7fE=go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo=go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E=+go.etcd.io/etcd/client/pkg/v3 v3.5.6 h1:TXQWYceBKqLp4sa87rcPs11SXxUA/mHwH975v+BDvLU=+go.etcd.io/etcd/pkg/v3 v3.5.6 h1:k1GZrGrfMHy5/cg2bxNGsmLTFisatyhDYCFLRuaavWg=+go.etcd.io/etcd/pkg/v3 v3.5.6/go.mod h1:qATwUzDb6MLyGWq2nUj+jwXqZJcxkCuabh0P7Cuff3k=+go.etcd.io/etcd/server/v3 v3.5.6 h1:RXuwaB8AMiV62TqcqIt4O4bG8NWjsxOkDJVT3MZI5Ds=+go.etcd.io/etcd/server/v3 v3.5.6/go.mod h1:6/Gfe8XTGXQJgLYQ65oGKMfPivb2EASLUSMSWN9Sroo=go.mongodb.org/mongo-driver v1.7.5 h1:ny3p0reEpgsR2cfA5cjgwFZg3Cv/ofFh/8jbhGtz9VI=go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4xhp5Zvxng=go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=@@ -982,10 +1022,13 @@ go.opentelemetry.io/proto/otlp v1.5.0/go.mod h1:keN8WnHxOy8PG0rQZjJJ5A2ebUoafqWpgo.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE=go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=+go.uber.org/multierr v1.8.0 h1:dg6GjLku4EH+249NNmoIciG9N/jURbDG+pFlTkhzIC8=+go.uber.org/multierr v1.8.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak=go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=+go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8=+go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw=go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=-golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=@@ -1019,8 +1062,6 @@ golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rgolang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=-golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=-golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=@@ -1059,16 +1100,6 @@ golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=-golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=-golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=-golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=-golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=@@ -1105,6 +1136,7 @@ golang.org/x/telemetry v0.0.0-20260109210033-bd525da824e2 h1:O1cMQHRfwNpDfDJerqRgolang.org/x/telemetry v0.0.0-20260109210033-bd525da824e2/go.mod h1:b7fPSJ0pKZ3ccUh8gnTONJxhn3c/PS6tyzQvyqw4iA8=golang.org/x/telemetry v0.0.0-20260209163413-e7419c687ee4 h1:bTLqdHv7xrGlFbvf5/TXNxy/iUwwdkjhqQTJDjW7aj0=golang.org/x/telemetry v0.0.0-20260209163413-e7419c687ee4/go.mod h1:g5NllXBEermZrmR51cJDQxmJUHUOfRAaNyWBM+R+548=+golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=@@ -1146,8 +1178,6 @@ golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbgolang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0=golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w=golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=-golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s=-golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM=golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM=@@ -1203,8 +1233,6 @@ google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=-google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=-google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=@@ -1213,20 +1241,23 @@ google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=gopkg.in/airbrake/gobrake.v2 v2.0.9 h1:7z2uVWwn7oVeeugY1DtlPAy5H+KYgB1KeKTnqjNatLo=+gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U=gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc=gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=+gopkg.in/cenkalti/backoff.v2 v2.2.1 h1:eJ9UAg01/HIHG987TwxvnzK2MgxXq97YY6rYDpY9aII=+gopkg.in/cenkalti/backoff.v2 v2.2.1/go.mod h1:S0QdOvT2AlerfSBkp0O+dk+bbIMaNbEmVk876gPCthU=+gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSPG+6V4=gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M=gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 h1:OAj3g0cR6Dx/R07QgQe8wkA9RNjB2u4i700xBkIT4e0=+gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo=gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=+gopkg.in/rethinkdb/rethinkdb-go.v6 v6.2.1 h1:d4KQkxAaAiRY2h5Zqis161Pv91A37uZyJOx73duwUwM=+gopkg.in/rethinkdb/rethinkdb-go.v6 v6.2.1/go.mod h1:WbjuEoo1oadwzQ4apSDU+JTvmllEHtsNHS6y7vFc7iw=gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=-gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=-gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=-gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=-gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=diff --git a/tests/setup/auth.setup.ts b/tests/setup/auth.setup.tsindex 0e9b40737..643cd8b7b 100644--- a/tests/setup/auth.setup.ts+++ b/tests/setup/auth.setup.ts@@ -4,11 +4,11 @@ import authUtil from '../utils/auth.util';const authFile = '.auth/login.json';setup('authenticate', async ({ page }) => {- await authUtil.login(page);+ const currentPassword = await authUtil.login(page);await page.waitForURL('/dashboard');- await authUtil.changeDefaultPassword(page, 'test-password-123');+ await authUtil.changeDefaultPassword(page, currentPassword, authUtil.TEST_PASSWORD);await page.context().storageState({ path: authFile });});diff --git a/tests/spec/swarm-ui.spec.ts b/tests/spec/swarm-ui.spec.tsnew file mode 100644index 000000000..733009f2d--- /dev/null+++ b/tests/spec/swarm-ui.spec.ts@@ -0,0 +1,82 @@+import { test, expect, type Page } from '@playwright/test';++async function mockConfigs(page: Page) {+ await page.route('**/api/environments/*/swarm/configs', async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: []+ })+ });+ });+}++async function mockSecrets(page: Page) {+ await page.route('**/api/environments/*/swarm/secrets', async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: []+ })+ });+ });+}++test.describe('Swarm UI', () => {+ test('cluster page renders correct lifecycle controls for current swarm state', async ({+ page+ }) => {+ await page.goto('/swarm/cluster');+ await page.waitForLoadState('networkidle');++ await expect(page.getByRole('heading', { name: 'Cluster', level: 1 })).toBeVisible();++ const initializedBanner = page.getByText('Cluster Already Initialized');+ if ((await initializedBanner.count()) > 0) {+ await expect(initializedBanner).toBeVisible();+ await expect(page.getByRole('button', { name: 'Leave Cluster' })).toBeVisible();+ await expect(page.getByText('Initialize Cluster')).toHaveCount(0);+ await expect(page.getByText('Join Existing Cluster')).toHaveCount(0);+ } else {+ await expect(page.getByText('Initialize Cluster')).toBeVisible();+ await expect(page.getByText('Join Existing Cluster')).toBeVisible();+ await expect(page.getByPlaceholder('Listen address (optional)').first()).toBeVisible();+ await expect(page.getByRole('button', { name: 'Initialize' })).toBeVisible();+ await expect(page.getByRole('button', { name: 'Join' })).toBeVisible();+ }+ });++ test('configs page renders name/data fields and empty state', async ({ page }) => {+ await mockConfigs(page);+ await page.goto('/swarm/configs');+ await page.waitForLoadState('networkidle');++ await expect(page.getByRole('heading', { name: 'Configs', level: 1 })).toBeVisible();+ await expect(+ page.locator('[data-slot="card-title"]').filter({ hasText: 'Create Config' })+ ).toBeVisible();+ await expect(page.getByPlaceholder('Config name')).toBeVisible();+ await expect(page.getByPlaceholder('Config data')).toBeVisible();+ await expect(page.getByRole('button', { name: 'Create Config' })).toBeVisible();+ await expect(page.getByText('No configs found.')).toBeVisible();+ });++ test('secrets page renders name/data fields and empty state', async ({ page }) => {+ await mockSecrets(page);+ await page.goto('/swarm/secrets');+ await page.waitForLoadState('networkidle');++ await expect(page.getByRole('heading', { name: 'Secrets', level: 1 })).toBeVisible();+ await expect(+ page.locator('[data-slot="card-title"]').filter({ hasText: 'Create Secret' })+ ).toBeVisible();+ await expect(page.getByPlaceholder('Secret name')).toBeVisible();+ await expect(page.getByPlaceholder('Secret data')).toBeVisible();+ await expect(page.getByRole('button', { name: 'Create Secret' })).toBeVisible();+ await expect(page.getByText('No secrets found.')).toBeVisible();+ });+});diff --git a/tests/utils/auth.util.ts b/tests/utils/auth.util.tsindex cfa28e297..b38f8279b 100644--- a/tests/utils/auth.util.ts+++ b/tests/utils/auth.util.ts@@ -1,16 +1,41 @@import type { Page } from '@playwright/test';-async function login(page: Page) {+const DEFAULT_PASSWORD = 'arcane-admin';+const TEST_PASSWORD = 'test-password-123';++async function login(page: Page): Promise<string> {await page.goto('/login');await page.getByLabel('Username').fill('arcane');- await page.getByLabel('Password').fill('arcane-admin');- await page.getByRole('button', { name: 'Sign in to Arcane', exact: true }).click();++ for (const password of [DEFAULT_PASSWORD, TEST_PASSWORD]) {+ await page.getByLabel('Password').fill(password);+ await page.getByRole('button', { name: 'Sign in to Arcane', exact: true }).click();++ try {+ await page.waitForURL('/dashboard', { timeout: 5000 });+ return password;+ } catch {+ const invalidCredentialsAlert = page+ .getByRole('alert')+ .filter({ hasText: 'Invalid username or password' });+ if (await invalidCredentialsAlert.isVisible().catch(() => false)) {+ continue;+ }+ }+ }++ throw new Error('Unable to authenticate with known E2E credentials');}-async function changeDefaultPassword(page: Page, newPassword: string) {+async function changeDefaultPassword(page: Page, currentPassword: string, newPassword: string) {const dialog = page.getByRole('dialog', { name: 'Change Default Password' });++ if (!(await dialog.isVisible().catch(() => false))) {+ return;+ }+await dialog.waitFor({ state: 'visible' });- await dialog.getByRole('textbox', { name: 'Current Password' }).fill('arcane-admin');+ await dialog.getByRole('textbox', { name: 'Current Password' }).fill(currentPassword);await dialog.getByRole('textbox', { name: 'New Password', exact: true }).fill(newPassword);await dialog.getByRole('textbox', { name: 'Confirm New Password' }).fill(newPassword);await dialog.getByRole('button', { name: 'Change Password' }).click();@@ -20,4 +45,4 @@ async function changeDefaultPassword(page: Page, newPassword: string) {.waitFor({ state: 'visible' });}-export default { login, changeDefaultPassword };+export default { login, changeDefaultPassword, DEFAULT_PASSWORD, TEST_PASSWORD };diff --git a/types/go.sum b/types/go.sumindex a695cbc6a..e7035a936 100644--- a/types/go.sum+++ b/types/go.sum@@ -68,6 +68,7 @@ go.yaml.in/yaml/v4 v4.0.0-rc.4/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPgolang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=+golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=diff --git a/types/network/network.go b/types/network/network.goindex ab33fbbcf..17c1a129c 100644--- a/types/network/network.go+++ b/types/network/network.go@@ -140,7 +140,7 @@ type Inspect struct {// IPAM contains IP address management configuration.//// Required: true- IPAM network.IPAM `json:"ipam"`+ IPAM IPAM `json:"ipam"`// Internal indicates if the network is internal.//diff --git a/types/settings/settings.go b/types/settings/settings.goindex 7a2097c02..1ef53ec53 100644--- a/types/settings/settings.go+++ b/types/settings/settings.go@@ -42,6 +42,12 @@ type Update struct {// Required: falseFollowProjectSymlinks *string `json:"followProjectSymlinks,omitempty"`+ // SwarmStackSourcesDirectory is the directory path where swarm stack source files are stored.+ // Must be an absolute path.+ //+ // Required: false+ SwarmStackSourcesDirectory *string `json:"swarmStackSourcesDirectory,omitempty"`+// DiskUsagePath is the path to monitor for disk usage.//// Required: falsediff --git a/types/swarm/config_secret.go b/types/swarm/config_secret.gonew file mode 100644index 000000000..d6855aea9--- /dev/null+++ b/types/swarm/config_secret.go@@ -0,0 +1,78 @@+package swarm++import (+ "encoding/json"+ "time"++ "github.com/moby/moby/api/types/swarm"+)++type ConfigSummary struct {+ ID string `json:"id"`+ Version swarm.Version `json:"version"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`+ Spec swarm.ConfigSpec `json:"spec"`+}++type SecretSummary struct {+ ID string `json:"id"`+ Version swarm.Version `json:"version"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`+ Spec swarm.SecretSpec `json:"spec"`+}++type ConfigCreateRequest struct {+ Spec json.RawMessage `json:"spec" doc:"Config specification"`+}++type ConfigUpdateRequest struct {+ Version uint64 `json:"version,omitempty"`+ Spec json.RawMessage `json:"spec" doc:"Updated config specification"`+}++type SecretCreateRequest struct {+ Spec json.RawMessage `json:"spec" doc:"Secret specification"`+}++type SecretUpdateRequest struct {+ Version uint64 `json:"version,omitempty"`+ Spec json.RawMessage `json:"spec" doc:"Updated secret specification"`+}++// NewConfigSummary converts a Docker swarm config into the API-facing ConfigSummary shape.+//+// It copies the config identity, version, timestamps, and spec from the Docker+// SDK type without modifying the source value.+//+// cfg is the Docker swarm config to summarize.+//+// Returns the serialized config summary used by the API.+func NewConfigSummary(cfg swarm.Config) ConfigSummary {+ return ConfigSummary{+ ID: cfg.ID,+ Version: cfg.Version,+ CreatedAt: cfg.CreatedAt,+ UpdatedAt: cfg.UpdatedAt,+ Spec: cfg.Spec,+ }+}++// NewSecretSummary converts a Docker swarm secret into the API-facing SecretSummary shape.+//+// It copies the secret identity, version, timestamps, and spec from the Docker+// SDK type without modifying the source value.+//+// secret is the Docker swarm secret to summarize.+//+// Returns the serialized secret summary used by the API.+func NewSecretSummary(secret swarm.Secret) SecretSummary {+ return SecretSummary{+ ID: secret.ID,+ Version: secret.Version,+ CreatedAt: secret.CreatedAt,+ UpdatedAt: secret.UpdatedAt,+ Spec: secret.Spec,+ }+}diff --git a/types/swarm/lifecycle.go b/types/swarm/lifecycle.gonew file mode 100644index 000000000..daf6eac1e--- /dev/null+++ b/types/swarm/lifecycle.go@@ -0,0 +1,61 @@+package swarm++import (+ "github.com/moby/moby/api/types/swarm"+)++type SwarmInitRequest struct {+ ListenAddr string `json:"listenAddr,omitempty"`+ AdvertiseAddr string `json:"advertiseAddr,omitempty"`+ DataPathAddr string `json:"dataPathAddr,omitempty"`+ DataPathPort uint32 `json:"dataPathPort,omitempty"`+ ForceNewCluster bool `json:"forceNewCluster,omitempty"`+ Spec swarm.Spec `json:"spec"`+ AutoLockManagers bool `json:"autoLockManagers,omitempty"`+ Availability swarm.NodeAvailability `json:"availability,omitempty"`+ DefaultAddrPool []string `json:"defaultAddrPool,omitempty"`+ SubnetSize uint32 `json:"subnetSize,omitempty"`+}++type SwarmInitResponse struct {+ NodeID string `json:"nodeId"`+}++type SwarmJoinRequest struct {+ ListenAddr string `json:"listenAddr,omitempty"`+ AdvertiseAddr string `json:"advertiseAddr,omitempty"`+ DataPathAddr string `json:"dataPathAddr,omitempty"`+ RemoteAddrs []string `json:"remoteAddrs"`+ JoinToken string `json:"joinToken"`+ Availability swarm.NodeAvailability `json:"availability,omitempty"`+}++type SwarmLeaveRequest struct {+ Force bool `json:"force,omitempty"`+}++type SwarmUnlockRequest struct {+ Key string `json:"key"`+}++type SwarmUnlockKeyResponse struct {+ UnlockKey string `json:"unlockKey"`+}++type SwarmJoinTokensResponse struct {+ Worker string `json:"worker"`+ Manager string `json:"manager"`+}++type SwarmRotateJoinTokensRequest struct {+ RotateWorkerToken bool `json:"rotateWorkerToken,omitempty"`+ RotateManagerToken bool `json:"rotateManagerToken,omitempty"`+}++type SwarmUpdateRequest struct {+ Version uint64 `json:"version,omitempty"`+ Spec swarm.Spec `json:"spec"`+ RotateWorkerToken bool `json:"rotateWorkerToken,omitempty"`+ RotateManagerToken bool `json:"rotateManagerToken,omitempty"`+ RotateManagerUnlockKey bool `json:"rotateManagerUnlockKey,omitempty"`+}diff --git a/types/swarm/node.go b/types/swarm/node.gonew file mode 100644index 000000000..f9b6f787a--- /dev/null+++ b/types/swarm/node.go@@ -0,0 +1,173 @@+package swarm++import (+ "fmt"+ "time"++ "github.com/moby/moby/api/types/swarm"+)++type NodeAgentState string++const (+ NodeAgentStateNone NodeAgentState = "none"+ NodeAgentStatePending NodeAgentState = "pending"+ NodeAgentStateOffline NodeAgentState = "offline"+ NodeAgentStateConnected NodeAgentState = "connected"+ NodeAgentStateMismatched NodeAgentState = "mismatched"+)++type NodeAgentStatus struct {+ State NodeAgentState `json:"state"`+ EnvironmentID *string `json:"environmentId,omitempty"`+ Connected *bool `json:"connected,omitempty"`+ LastHeartbeat *time.Time `json:"lastHeartbeat,omitempty"`+ LastPollAt *time.Time `json:"lastPollAt,omitempty"`+ ReportedNodeID *string `json:"reportedNodeId,omitempty"`+ ReportedHostname *string `json:"reportedHostname,omitempty"`+}++type NodeSummary struct {+ // ID is the unique identifier of the node.+ //+ // Required: true+ ID string `json:"id"`++ // Hostname is the node hostname.+ //+ // Required: true+ Hostname string `json:"hostname"`++ // Role indicates whether the node is a manager or worker.+ //+ // Required: true+ Role string `json:"role"`++ // Availability indicates if the node is active, paused, or drained.+ //+ // Required: true+ Availability string `json:"availability"`++ // Status is the node readiness state.+ //+ // Required: true+ Status string `json:"status"`++ // Address is the node address.+ //+ // Required: false+ Address string `json:"address,omitempty"`++ // ManagerStatus is the manager status string if applicable.+ //+ // Required: false+ ManagerStatus string `json:"managerStatus,omitempty"`++ // Reachability is the manager reachability if applicable.+ //+ // Required: false+ Reachability string `json:"reachability,omitempty"`++ // Labels contains node labels.+ //+ // Required: false+ Labels map[string]string `json:"labels,omitempty"`++ // EngineVersion is the Docker engine version.+ //+ // Required: false+ EngineVersion string `json:"engineVersion,omitempty"`++ // Platform is the node platform string.+ //+ // Required: false+ Platform string `json:"platform,omitempty"`++ // CreatedAt is when the node was created.+ //+ // Required: true+ CreatedAt time.Time `json:"createdAt"`++ // UpdatedAt is when the node was last updated.+ //+ // Required: true+ UpdatedAt time.Time `json:"updatedAt"`++ // Agent describes Arcane node-agent coverage for this swarm node.+ //+ // Required: true+ Agent NodeAgentStatus `json:"agent"`+}++type NodeUpdateRequest struct {+ // Version is the node version index to update.+ //+ // Required: false+ Version uint64 `json:"version,omitempty"`++ // Name overrides the node name annotation.+ //+ // Required: false+ Name *string `json:"name,omitempty"`++ // Labels updates node labels.+ //+ // Required: false+ Labels map[string]string `json:"labels,omitempty"`++ // Role updates node role (manager or worker).+ //+ // Required: false+ Role *swarm.NodeRole `json:"role,omitempty"`++ // Availability updates node availability (active, pause, drain).+ //+ // Required: false+ Availability *swarm.NodeAvailability `json:"availability,omitempty"`+}++// NewNodeSummary converts a Docker swarm node into the API-facing NodeSummary shape.+//+// It derives manager role labels, reachability, platform strings, and default+// node-agent state from the Docker SDK value so callers can return a stable,+// JSON-friendly representation.+//+// node is the Docker swarm node to summarize.+//+// Returns a NodeSummary populated from node.+func NewNodeSummary(node swarm.Node) NodeSummary {+ managerStatus := ""+ reachability := ""+ if node.ManagerStatus != nil {+ if node.ManagerStatus.Leader {+ managerStatus = "leader"+ } else {+ managerStatus = "manager"+ }+ reachability = string(node.ManagerStatus.Reachability)+ }++ platform := ""+ if node.Description.Platform.OS != "" || node.Description.Platform.Architecture != "" {+ platform = fmt.Sprintf("%s/%s", node.Description.Platform.OS, node.Description.Platform.Architecture)+ }++ return NodeSummary{+ ID: node.ID,+ Hostname: node.Description.Hostname,+ Role: string(node.Spec.Role),+ Availability: string(node.Spec.Availability),+ Status: string(node.Status.State),+ Address: node.Status.Addr,+ ManagerStatus: managerStatus,+ Reachability: reachability,+ Labels: node.Spec.Labels,+ EngineVersion: node.Description.Engine.EngineVersion,+ Platform: platform,+ CreatedAt: node.CreatedAt,+ UpdatedAt: node.UpdatedAt,+ Agent: NodeAgentStatus{+ State: NodeAgentStateNone,+ },+ }+}diff --git a/types/swarm/service.go b/types/swarm/service.gonew file mode 100644index 000000000..db83dab45--- /dev/null+++ b/types/swarm/service.go@@ -0,0 +1,427 @@+package swarm++import (+ "encoding/json"+ "time"++ "github.com/moby/moby/api/types/swarm"+)++const StackNamespaceLabel = "com.docker.stack.namespace"++type ServicePort struct {+ // Protocol is the transport protocol used by the port.+ //+ // Required: true+ Protocol string `json:"protocol"`++ // TargetPort is the port inside the container.+ //+ // Required: true+ TargetPort uint32 `json:"targetPort"`++ // PublishedPort is the port exposed on the host.+ //+ // Required: false+ PublishedPort uint32 `json:"publishedPort,omitempty"`++ // PublishMode is the publish mode used for the port.+ //+ // Required: false+ PublishMode string `json:"publishMode,omitempty"`+}++type ServiceMount struct {+ // Type of the mount (bind, volume, tmpfs, npipe, cluster).+ Type string `json:"type"`++ // Source is the host path or volume name.+ Source string `json:"source,omitempty"`++ // Target is the container-internal path.+ Target string `json:"target"`++ // ReadOnly indicates if the mount is read-only.+ ReadOnly bool `json:"readOnly,omitempty"`++ // VolumeDriver is the volume driver name (only for volume mounts).+ VolumeDriver string `json:"volumeDriver,omitempty"`++ // VolumeOptions contains driver-specific options (only for volume mounts).+ VolumeOptions map[string]string `json:"volumeOptions,omitempty"`++ // DevicePath is the host device path for bind-backed volumes (driver_opts type=none, o=bind).+ DevicePath string `json:"devicePath,omitempty"`+}++type ServiceSummary struct {+ // ID is the unique identifier of the service.+ //+ // Required: true+ ID string `json:"id"`++ // Name is the service name.+ //+ // Required: true+ Name string `json:"name"`++ // Image is the container image used by the service.+ //+ // Required: true+ Image string `json:"image"`++ // Mode is the service mode (replicated or global).+ //+ // Required: true+ Mode string `json:"mode"`++ // Replicas is the desired replica count.+ // For replicated services this comes from the spec.+ // For global services this is the number of eligible nodes (from ServiceStatus.DesiredTasks).+ //+ // Required: true+ Replicas uint64 `json:"replicas"`++ // RunningReplicas is the number of tasks currently in the Running state.+ //+ // Required: true+ RunningReplicas uint64 `json:"runningReplicas"`++ // Ports is the list of published ports for the service.+ //+ // Required: true+ Ports []ServicePort `json:"ports"`++ // CreatedAt is the time when the service was created.+ //+ // Required: true+ CreatedAt time.Time `json:"createdAt"`++ // UpdatedAt is the time when the service was last updated.+ //+ // Required: true+ UpdatedAt time.Time `json:"updatedAt"`++ // Labels contains user-defined metadata for the service.+ //+ // Required: true+ Labels map[string]string `json:"labels"`++ // StackName is the stack namespace if the service belongs to a stack.+ //+ // Required: false+ StackName string `json:"stackName,omitempty"`++ // Nodes is the list of node hostnames running tasks for this service.+ //+ // Required: true+ Nodes []string `json:"nodes"`++ // Networks is the list of network names attached to this service.+ //+ // Required: true+ Networks []string `json:"networks"`++ // Mounts is the list of volume/bind mounts configured on this service.+ //+ // Required: true+ Mounts []ServiceMount `json:"mounts"`+}++type ServiceInspect struct {+ // ID is the unique identifier of the service.+ //+ // Required: true+ ID string `json:"id"`++ // Version is the service version metadata.+ //+ // Required: true+ Version swarm.Version `json:"version"`++ // CreatedAt is the time when the service was created.+ //+ // Required: true+ CreatedAt time.Time `json:"createdAt"`++ // UpdatedAt is the time when the service was last updated.+ //+ // Required: true+ UpdatedAt time.Time `json:"updatedAt"`++ // Spec is the full service specification.+ //+ // Required: true+ Spec swarm.ServiceSpec `json:"spec"`++ // Endpoint is the service endpoint configuration.+ //+ // Required: true+ Endpoint swarm.Endpoint `json:"endpoint"`++ // UpdateStatus is the current update status, if any.+ UpdateStatus *swarm.UpdateStatus `json:"updateStatus,omitempty"`++ // Nodes is a list of node hostnames running this service.+ Nodes []string `json:"nodes,omitempty"`++ // NetworkDetails contains enriched network information keyed by network ID.+ NetworkDetails map[string]ServiceNetworkDetail `json:"networkDetails,omitempty"`++ // Mounts contains enriched mount information with volume driver details.+ Mounts []ServiceMount `json:"mounts,omitempty"`+}++// ServiceNetworkIPAMConfig represents a single IPAM configuration entry with camelCase JSON tags.+type ServiceNetworkIPAMConfig struct {+ Subnet string `json:"subnet,omitempty"`+ Gateway string `json:"gateway,omitempty"`+ IPRange string `json:"ipRange,omitempty"`+}++// ServiceNetworkConfigDetail holds details about a config-only network referenced by configFrom.+type ServiceNetworkConfigDetail struct {+ Name string `json:"name"`+ Driver string `json:"driver"`+ Scope string `json:"scope"`+ EnableIPv4 bool `json:"enableIPv4"`+ EnableIPv6 bool `json:"enableIPv6"`+ Options map[string]string `json:"options,omitempty"`+ IPv4Configs []ServiceNetworkIPAMConfig `json:"ipv4Configs,omitempty"`+ IPv6Configs []ServiceNetworkIPAMConfig `json:"ipv6Configs,omitempty"`+}++// ServiceNetworkDetail holds enriched network information for a service's attached network.+type ServiceNetworkDetail struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Driver string `json:"driver"`+ Scope string `json:"scope"`+ Internal bool `json:"internal"`+ Attachable bool `json:"attachable"`+ Ingress bool `json:"ingress"`+ EnableIPv4 bool `json:"enableIPv4"`+ EnableIPv6 bool `json:"enableIPv6"`+ ConfigFrom string `json:"configFrom,omitempty"`+ ConfigOnly bool `json:"configOnly"`+ Options map[string]string `json:"options,omitempty"`+ IPAMConfigs []ServiceNetworkIPAMConfig `json:"ipamConfigs,omitempty"`+ ConfigNetwork *ServiceNetworkConfigDetail `json:"configNetwork,omitempty"`+}++type ServiceCreateRequest struct {+ // Spec is the service specification as a JSON object.+ //+ // Required: true+ Spec json.RawMessage `json:"spec" doc:"Service specification"`++ // Options are additional create options for the service.+ //+ // Required: false+ Options *ServiceCreateOptions `json:"options,omitempty" doc:"Additional create options"`+}++type ServiceUpdateRequest struct {+ // Version is the service version index to update.+ //+ // Required: true+ Version uint64 `json:"version"`++ // Spec is the updated service specification.+ //+ // Required: true+ Spec swarm.ServiceSpec `json:"spec"`++ // Options are additional update options for the service.+ //+ // Required: false+ Options *ServiceUpdateOptions `json:"options,omitempty"`+}++type ServiceCreateResponse struct {+ // ID is the created service ID.+ //+ // Required: true+ ID string `json:"id"`++ // Warnings are any warnings returned by the Docker API.+ //+ // Required: false+ Warnings []string `json:"warnings,omitempty"`+}++type ServiceUpdateResponse struct {+ // Warnings are any warnings returned by the Docker API.+ //+ // Required: false+ Warnings []string `json:"warnings,omitempty"`+}++type ServiceCreateOptions struct {+ // EncodedRegistryAuth is the encoded registry authorization credentials.+ //+ // Required: false+ EncodedRegistryAuth string `json:"encodedRegistryAuth,omitempty"`++ // QueryRegistry indicates if registry metadata should be queried.+ //+ // Required: false+ QueryRegistry bool `json:"queryRegistry,omitempty"`+}++type ServiceUpdateOptions struct {+ // EncodedRegistryAuth is the encoded registry authorization credentials.+ //+ // Required: false+ EncodedRegistryAuth string `json:"encodedRegistryAuth,omitempty"`++ // RegistryAuthFrom specifies where to find registry auth credentials.+ //+ // Required: false+ RegistryAuthFrom swarm.RegistryAuthSource `json:"registryAuthFrom,omitempty"`++ // Rollback requests a server-side rollback ("previous" or "none").+ //+ // Required: false+ Rollback string `json:"rollback,omitempty"`++ // QueryRegistry indicates if registry metadata should be queried.+ //+ // Required: false+ QueryRegistry bool `json:"queryRegistry,omitempty"`+}++type ServiceScaleRequest struct {+ // Replicas is the desired replica count.+ //+ // Required: true+ Replicas uint64 `json:"replicas"`+}++// NewServiceSummary converts a Docker swarm service into the API-facing ServiceSummary shape.+//+// It derives the service mode, replica counts, running task counts, published+// ports, stack namespace label, attached network names, and container mounts.+// Network IDs are resolved through networkNameByID when possible, then fall+// back to the attachment alias or raw target value. A nil nodeNames slice is+// normalized to an empty slice for stable JSON output.+//+// service is the Docker swarm service to summarize.+// nodeNames lists the node hostnames currently running tasks for the service.+// networkNameByID maps attached network IDs to human-readable names.+//+// Returns a ServiceSummary populated from service and the supplied enrichment data.+func NewServiceSummary(service swarm.Service, nodeNames []string, networkNameByID map[string]string) ServiceSummary {+ spec := service.Spec++ mode := "unknown"+ replicas := uint64(0)+ runningReplicas := uint64(0)+ if spec.Mode.Replicated != nil {+ mode = "replicated"+ if spec.Mode.Replicated.Replicas != nil {+ replicas = *spec.Mode.Replicated.Replicas+ }+ } else if spec.Mode.Global != nil {+ mode = "global"+ if service.ServiceStatus != nil {+ replicas = service.ServiceStatus.DesiredTasks+ }+ }++ if service.ServiceStatus != nil {+ runningReplicas = service.ServiceStatus.RunningTasks+ }++ image := ""+ if spec.TaskTemplate.ContainerSpec != nil {+ image = spec.TaskTemplate.ContainerSpec.Image+ }++ ports := make([]ServicePort, 0)+ portSpecs := service.Endpoint.Spec.Ports+ if len(portSpecs) == 0 {+ portSpecs = service.Endpoint.Ports+ }+ for _, port := range portSpecs {+ ports = append(ports, ServicePort{+ Protocol: string(port.Protocol),+ TargetPort: port.TargetPort,+ PublishedPort: port.PublishedPort,+ PublishMode: string(port.PublishMode),+ })+ }++ stackName := ""+ if spec.Labels != nil {+ stackName = spec.Labels[StackNamespaceLabel]+ }++ // Extract networks from task template, resolving IDs to names+ networkConfigs := spec.TaskTemplate.Networks+ networks := make([]string, 0, len(networkConfigs))+ for _, n := range networkConfigs {+ if name, ok := networkNameByID[n.Target]; ok {+ networks = append(networks, name)+ } else if len(n.Aliases) > 0 {+ networks = append(networks, n.Aliases[0])+ } else {+ networks = append(networks, n.Target)+ }+ }++ // Extract mounts from container spec+ mounts := make([]ServiceMount, 0)+ if spec.TaskTemplate.ContainerSpec != nil {+ for _, m := range spec.TaskTemplate.ContainerSpec.Mounts {+ mounts = append(mounts, ServiceMount{+ Type: string(m.Type),+ Source: m.Source,+ Target: m.Target,+ ReadOnly: m.ReadOnly,+ })+ }+ }++ if nodeNames == nil {+ nodeNames = []string{}+ }++ return ServiceSummary{+ ID: service.ID,+ Name: spec.Name,+ Image: image,+ Mode: mode,+ Replicas: replicas,+ RunningReplicas: runningReplicas,+ Ports: ports,+ CreatedAt: service.CreatedAt,+ UpdatedAt: service.UpdatedAt,+ Labels: spec.Labels,+ StackName: stackName,+ Nodes: nodeNames,+ Networks: networks,+ Mounts: mounts,+ }+}++// NewServiceInspect converts a Docker swarm service into the API-facing ServiceInspect shape.+//+// It copies the core inspection fields directly from the Docker SDK type.+// Callers can enrich the returned value with node, network, or mount details+// after construction when needed.+//+// service is the Docker swarm service to convert.+//+// Returns the base inspection payload for service.+func NewServiceInspect(service swarm.Service) ServiceInspect {+ return ServiceInspect{+ ID: service.ID,+ Version: service.Version,+ CreatedAt: service.CreatedAt,+ UpdatedAt: service.UpdatedAt,+ Spec: service.Spec,+ Endpoint: service.Endpoint,+ UpdateStatus: service.UpdateStatus,+ }+}diff --git a/types/swarm/stack.go b/types/swarm/stack.gonew file mode 100644index 000000000..895bddffa--- /dev/null+++ b/types/swarm/stack.go@@ -0,0 +1,138 @@+package swarm++import "time"++type StackSummary struct {+ // ID is the unique identifier for the stack (uses namespace).+ //+ // Required: true+ ID string `json:"id"`++ // Name is the stack name.+ //+ // Required: true+ Name string `json:"name"`++ // Namespace is the stack namespace label value.+ //+ // Required: true+ Namespace string `json:"namespace"`++ // Services is the number of services in the stack.+ //+ // Required: true+ Services int `json:"services"`++ // CreatedAt is the earliest service creation time in the stack.+ //+ // Required: true+ CreatedAt time.Time `json:"createdAt"`++ // UpdatedAt is the latest service update time in the stack.+ //+ // Required: true+ UpdatedAt time.Time `json:"updatedAt"`+}++type StackInspect struct {+ // Name is the stack name.+ //+ // Required: true+ Name string `json:"name"`++ // Namespace is the stack namespace label value.+ //+ // Required: true+ Namespace string `json:"namespace"`++ // Services is the number of services in the stack.+ //+ // Required: true+ Services int `json:"services"`++ // CreatedAt is the earliest service creation time in the stack.+ //+ // Required: true+ CreatedAt time.Time `json:"createdAt"`++ // UpdatedAt is the latest service update time in the stack.+ //+ // Required: true+ UpdatedAt time.Time `json:"updatedAt"`+}++type StackRenderConfigRequest struct {+ // Name is the stack name (namespace).+ //+ // Required: true+ Name string `json:"name"`++ // ComposeContent is the Docker Compose YAML content.+ //+ // Required: true+ ComposeContent string `json:"composeContent"`++ // EnvContent is the optional environment file content.+ //+ // Required: false+ EnvContent string `json:"envContent,omitempty"`+}++type StackRenderConfigResponse struct {+ // Name is the stack name.+ //+ // Required: true+ Name string `json:"name"`++ // RenderedCompose is the normalized compose config output.+ //+ // Required: true+ RenderedCompose string `json:"renderedCompose"`++ // Services contains service names discovered in the compose file.+ //+ // Required: true+ Services []string `json:"services"`++ // Networks contains network names discovered in the compose file.+ //+ // Required: true+ Networks []string `json:"networks"`++ // Volumes contains volume names discovered in the compose file.+ //+ // Required: true+ Volumes []string `json:"volumes"`++ // Configs contains config names discovered in the compose file.+ //+ // Required: true+ Configs []string `json:"configs"`++ // Secrets contains secret names discovered in the compose file.+ //+ // Required: true+ Secrets []string `json:"secrets"`++ // Warnings contains non-fatal warnings.+ //+ // Required: false+ Warnings []string `json:"warnings,omitempty"`+}++type StackSource struct {+ // Name is the stack name.+ //+ // Required: true+ Name string `json:"name"`++ // ComposeContent is the original Docker Compose YAML content used for deployment.+ //+ // Required: true+ ComposeContent string `json:"composeContent"`++ // EnvContent is the optional original environment file content used for deployment.+ //+ // Required: false+ EnvContent string `json:"envContent,omitempty"`+}diff --git a/types/swarm/stack_deploy.go b/types/swarm/stack_deploy.gonew file mode 100644index 000000000..ad4c99a4a--- /dev/null+++ b/types/swarm/stack_deploy.go@@ -0,0 +1,42 @@+package swarm++// StackDeployRequest is used to deploy a Swarm stack from a Compose file.+type StackDeployRequest struct {+ // Name is the stack name (namespace).+ //+ // Required: true+ Name string `json:"name"`++ // ComposeContent is the Docker Compose YAML content.+ //+ // Required: true+ ComposeContent string `json:"composeContent"`++ // EnvContent is the optional environment file content.+ //+ // Required: false+ EnvContent string `json:"envContent,omitempty"`++ // WithRegistryAuth sends registry auth details to Swarm agents.+ //+ // Required: false+ WithRegistryAuth bool `json:"withRegistryAuth,omitempty"`++ // Prune removes services that are no longer referenced in the stack.+ //+ // Required: false+ Prune bool `json:"prune,omitempty"`++ // ResolveImage controls how image digests are resolved (always, changed, never).+ //+ // Required: false+ ResolveImage string `json:"resolveImage,omitempty"`+}++// StackDeployResponse represents the result of a stack deployment.+type StackDeployResponse struct {+ // Name is the deployed stack name.+ //+ // Required: true+ Name string `json:"name"`+}diff --git a/types/swarm/swarm.go b/types/swarm/swarm.gonew file mode 100644index 000000000..7801766f8--- /dev/null+++ b/types/swarm/swarm.go@@ -0,0 +1,52 @@+package swarm++import (+ "time"++ "github.com/moby/moby/api/types/swarm"+)++type SwarmInfo struct {+ // ID is the swarm ID.+ //+ // Required: true+ ID string `json:"id"`++ // CreatedAt is when the swarm was created.+ //+ // Required: true+ CreatedAt time.Time `json:"createdAt"`++ // UpdatedAt is when the swarm was last updated.+ //+ // Required: true+ UpdatedAt time.Time `json:"updatedAt"`++ // Spec is the swarm specification.+ //+ // Required: true+ Spec swarm.Spec `json:"spec"`++ // RootRotationInProgress indicates if a root rotation is in progress.+ //+ // Required: true+ RootRotationInProgress bool `json:"rootRotationInProgress"`+}++// NewSwarmInfo converts a Docker swarm inspection result into the API-facing SwarmInfo shape.+//+// It copies the cluster identifiers, timestamps, spec, and root-rotation state+// from the Docker SDK type without mutating the source value.+//+// s is the Docker swarm value returned by the Docker client.+//+// Returns the serialized swarm metadata used by the Arcane API.+func NewSwarmInfo(s swarm.Swarm) SwarmInfo {+ return SwarmInfo{+ ID: s.ID,+ CreatedAt: s.CreatedAt,+ UpdatedAt: s.UpdatedAt,+ Spec: s.Spec,+ RootRotationInProgress: s.RootRotationInProgress,+ }+}diff --git a/types/swarm/task.go b/types/swarm/task.gonew file mode 100644index 000000000..8294d7f1f--- /dev/null+++ b/types/swarm/task.go@@ -0,0 +1,131 @@+package swarm++import (+ "time"++ "github.com/moby/moby/api/types/swarm"+)++type TaskSummary struct {+ // ID is the unique identifier of the task.+ //+ // Required: true+ ID string `json:"id"`++ // Name is the task name.+ //+ // Required: true+ Name string `json:"name"`++ // ServiceID is the service ID the task belongs to.+ //+ // Required: true+ ServiceID string `json:"serviceId"`++ // ServiceName is the service name the task belongs to.+ //+ // Required: true+ ServiceName string `json:"serviceName"`++ // NodeID is the node ID running the task.+ //+ // Required: true+ NodeID string `json:"nodeId"`++ // NodeName is the node name running the task.+ //+ // Required: true+ NodeName string `json:"nodeName"`++ // DesiredState is the desired state for the task.+ //+ // Required: true+ DesiredState string `json:"desiredState"`++ // CurrentState is the current runtime state for the task.+ //+ // Required: true+ CurrentState string `json:"currentState"`++ // Error is any error message reported by the task.+ //+ // Required: false+ Error string `json:"error,omitempty"`++ // ContainerID is the container ID backing the task.+ //+ // Required: false+ ContainerID string `json:"containerId,omitempty"`++ // Image is the container image used by the task.+ //+ // Required: false+ Image string `json:"image,omitempty"`++ // Slot is the task slot for replicated services.+ //+ // Required: false+ Slot int `json:"slot,omitempty"`++ // CreatedAt is when the task was created.+ //+ // Required: true+ CreatedAt time.Time `json:"createdAt"`++ // UpdatedAt is when the task was last updated.+ //+ // Required: true+ UpdatedAt time.Time `json:"updatedAt"`+}++// NewTaskSummary converts a Docker swarm task into the API-facing TaskSummary shape.+//+// It extracts task identity, service and node names supplied by the caller,+// container image and container ID details when available, and falls back from+// the Docker task error field to the task status message when necessary.+//+// task is the Docker swarm task to summarize.+// serviceName is the human-readable service name associated with task.+// nodeName is the human-readable node name associated with task.+//+// Returns a TaskSummary populated from task and the supplied display names.+func NewTaskSummary(task swarm.Task, serviceName, nodeName string) TaskSummary {+ name := ""+ if task.Name != "" {+ name = task.Name+ }++ image := ""+ if task.Spec.ContainerSpec != nil {+ image = task.Spec.ContainerSpec.Image+ }++ containerID := ""+ if task.Status.ContainerStatus != nil {+ containerID = task.Status.ContainerStatus.ContainerID+ }++ errorMessage := task.Status.Err+ if errorMessage == "" {+ errorMessage = task.Status.Message+ }++ slot := task.Slot++ return TaskSummary{+ ID: task.ID,+ Name: name,+ ServiceID: task.ServiceID,+ ServiceName: serviceName,+ NodeID: task.NodeID,+ NodeName: nodeName,+ DesiredState: string(task.DesiredState),+ CurrentState: string(task.Status.State),+ Error: errorMessage,+ ContainerID: containerID,+ Image: image,+ Slot: slot,+ CreatedAt: task.CreatedAt,+ UpdatedAt: task.UpdatedAt,+ }+}diff --git a/types/system/websocket.go b/types/system/websocket.goindex ea41d414d..f42648b0d 100644--- a/types/system/websocket.go+++ b/types/system/websocket.go@@ -9,6 +9,7 @@ const (WSKindContainerStats = "container_stats"WSKindContainerExec = "container_exec"WSKindSystemStats = "system_stats"+ WSKindServiceLogs = "service_logs")// WebSocketConnectionInfo describes a single active WebSocket connection.@@ -50,4 +51,6 @@ type WebSocketMetricsSnapshot struct {ContainerExec int64 `json:"containerExec"`// SystemStats is the number of active system-stats streams.SystemStats int64 `json:"systemStats"`+ // ServiceLogsActive is the number of active swarm service-log streams.+ ServiceLogsActive int64 `json:"serviceLogsActive"`}diff --git a/types/template/template.go b/types/template/template.goindex 8d0ad0b62..b0813ca3e 100644--- a/types/template/template.go+++ b/types/template/template.go@@ -230,13 +230,23 @@ type UpdateRequest struct {EnvContent string `json:"envContent"`}-// DefaultTemplatesResponse contains the default compose and env templates.+// DefaultTemplatesResponse contains the default compose, swarm stack, and env templates.type DefaultTemplatesResponse struct {// ComposeTemplate is the default Docker Compose template content.//// Required: trueComposeTemplate string `json:"composeTemplate"`+ // SwarmStackTemplate is the default Docker Swarm stack template content.+ //+ // Required: true+ SwarmStackTemplate string `json:"swarmStackTemplate"`++ // SwarmStackEnvTemplate is the default environment template content for Docker Swarm stacks.+ //+ // Required: true+ SwarmStackEnvTemplate string `json:"swarmStackEnvTemplate"`+// EnvTemplate is the default environment template content.//// Required: true