Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: unify swarm node agent deployment and easy join swarm agent/nodes (#3279)
Kyle Mendellfcddb8367ea7
diff --git a/.gitignore b/.gitignoreindex 9e27a97d4..e1cbbe73c 100644--- a/.gitignore+++ b/.gitignore@@ -64,3 +64,4 @@ arcane-devclicli/arcane-clicompletions+coverage.txtdiff --git a/Justfile b/Justfileindex 7dac9b951..4e69435e4 100644--- a/Justfile+++ b/Justfile@@ -153,7 +153,7 @@ _build-image-manager tag="ghcr.io/getarcaneapp/arcane:development" flag='':# Build agent container image[group('build')]-_build-image-agent tag="ghcr.io/getarcaneapp/arcane-headless:development" flag='':+_build-image-agent tag="ghcr.io/getarcaneapp/agent:development" flag='':docker buildx build {{ if flag == "--push" { "--push" } else { "" } }} --platform linux/arm64,linux/amd64,linux/arm/v7 -f 'docker/Dockerfile-agent' --build-arg ENABLED_FEATURES="{{ env('ENABLED_FEATURES', env('BUILD_FEATURES', '')) }}" -t "{{ tag }}" .# Build + push both manager and agent multi-arch images for a beta release.@@ -710,13 +710,16 @@ bench-edge-tunnel-mem profile="edge_tunnel.mem.out" benchtime="5s":# Deploy# ------------------------------------------------------------------------------# Deploy a local swarm worker plus a locally built Arcane edge agent into DinD.+# Deploy a local DinD engine plus a locally built Arcane edge agent.+# The swarm form joins the engine to the host swarm; the normal agent form leaves+# it outside the swarm so Arcane Easy Join can perform the join later.## Usage:# just deploy swarm agent [agent_token] [manager_url] [node_name] [agent_name] [dind_image] [local_image]+# just deploy 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":+_deploy-agent join_swarm agent_token="" manager_url="http://host.docker.internal:3552" node_name="arcane-agent-1" agent_name="arcane-agent" dind_image="docker:29-dind" local_image="ghcr.io/getarcaneapp/agent:local":#!/usr/bin/env bashset -euo pipefail@@ -730,21 +733,23 @@ _deploy-swarm-agent agent_token="" manager_url="http://host.docker.internal:3552exit 1fi- 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+ if [ "{{ join_swarm }}" = "true" ]; then+ 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+ fifiecho "Building local agent image {{ local_image }}..."- docker build -f docker/Dockerfile-agent -t "{{ local_image }}" .+ docker buildx build --load -f docker/Dockerfile-agent -t "{{ local_image }}" .if docker inspect "{{ node_name }}" >/dev/null 2>&1; then- echo "Reusing existing DinD worker {{ node_name }}..."+ echo "Reusing existing DinD engine {{ node_name }}..."docker start "{{ node_name }}" >/dev/null 2>&1 || trueelse- echo "Starting DinD worker {{ node_name }} from {{ dind_image }}..."+ echo "Starting DinD engine {{ node_name }} from {{ dind_image }}..."docker run -d \--privileged \--name "{{ node_name }}" \@@ -769,31 +774,51 @@ _deploy-swarm-agent agent_token="" manager_url="http://host.docker.internal:3552filocal_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+ if [ "{{ join_swarm }}" = "true" ]; then+ 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."+ fielse- echo "{{ node_name }} is already part of the swarm."+ if [ "$local_node_state" = "active" ]; then+ echo "{{ node_name }} is already part of a swarm. Remove it first with: just remove agent {{ node_name }} {{ agent_name }}"+ exit 1+ fi+ echo "Leaving {{ node_name }} outside the swarm for Arcane Easy Join."ficurrent_node_id="$(docker exec "{{ node_name }}" docker info --format '{{ "{{.Swarm.NodeID}}" }}')"- echo "Current swarm node ID: $current_node_id"+ if [ -n "$current_node_id" ]; then+ echo "Current swarm node ID: $current_node_id"+ fiif [ -n "{{ agent_token }}" ] && command -v sqlite3 >/dev/null 2>&1 && [ -f backend/data/arcane.db ]; thenexpected_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" ]; thenecho "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."+ if [ "{{ join_swarm }}" = "true" ]; then+ echo "Create a fresh Remote Environment from the Connect Agent dialog for node {{ node_name }}, then rerun this command with its token."+ else+ echo "Create a fresh visible Edge Agent under Environments, then rerun this command with its token."+ fiexit 1fifiif [ -z "{{ agent_token }}" ]; thenecho ""- 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 }}"+ if [ "{{ join_swarm }}" = "true" ]; then+ echo "Swarm worker {{ node_name }} is ready, but no Arcane agent token was provided."+ echo "Open Arcane, click Connect Agent for node {{ node_name }} (node ID: $current_node_id), create its Remote Environment, copy the generated token, and rerun:"+ echo " just deploy swarm agent <arcane_agent_token> {{ manager_url }} {{ node_name }} {{ agent_name }} {{ dind_image }} {{ local_image }}"+ else+ echo "Docker engine {{ node_name }} is ready, but no Arcane agent token was provided."+ echo "Create a visible Edge Agent under Environments, copy its token, and rerun:"+ echo " just deploy agent <arcane_agent_token> {{ manager_url }} {{ node_name }} {{ agent_name }} {{ dind_image }} {{ local_image }}"+ fiexit 0fi@@ -816,20 +841,30 @@ _deploy-swarm-agent agent_token="" manager_url="http://host.docker.internal:3552'echo ""- echo "Swarm worker {{ node_name }} and local agent {{ agent_name }} are up."+ if [ "{{ join_swarm }}" = "true" ]; then+ echo "Swarm worker {{ node_name }} and local agent {{ agent_name }} are up."+ else+ echo "Docker engine {{ node_name }} and local agent {{ agent_name }} are up."+ echo "The engine is connected to Arcane and remains outside the swarm."+ fiecho "Verify:"- echo " docker node ls"+ if [ "{{ join_swarm }}" = "true" ]; then+ echo " docker node ls"+ else+ echo " docker exec {{ node_name }} docker info --format '{{ "{{.Swarm.LocalNodeState}}" }}'"+ fiecho " 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.+# Remove a local DinD engine plus its Arcane edge agent.## Usage:## just remove swarm agent [node_name] [agent_name]+# just remove agent [node_name] [agent_name][group('deploy')]-_remove-swarm-agent node_name="swarm-worker-1" agent_name="arcane-edge-agent":+_remove-agent node_name="arcane-agent-1" agent_name="arcane-agent":#!/usr/bin/env bashset -euo pipefail@@ -866,16 +901,59 @@ _remove-swarm-agent node_name="swarm-worker-1" agent_name="arcane-edge-agent":docker node rm -f "$node_id" >/dev/null 2>&1 || truefi- echo "Removing DinD worker container {{ node_name }} from host..."+ echo "Removing DinD engine container {{ node_name }} from host..."docker rm -f "{{ node_name }}" >/dev/nullecho ""- echo "Removed swarm worker {{ node_name }} and inner agent {{ agent_name }}."+ echo "Removed Docker engine {{ node_name }} and inner agent {{ agent_name }}."-# Deploy targets. Example: just deploy swarm agent [agent_token]+# Deploy targets. Examples: just deploy agent [agent_token], just deploy swarm agent [agent_token][group('deploy')]-deploy scope kind *args:- @just "_deploy-{{ scope }}-{{ kind }}" {{ args }}+deploy target *args:+ #!/usr/bin/env bash+ set -euo pipefail+ set -- {{ args }}+ case "{{ target }}" in+ agent)+ just _deploy-agent false "$@"+ ;;+ swarm)+ if [ "${1:-}" != "agent" ]; then+ echo "usage: just deploy swarm agent [agent_token] [manager_url] [node_name] [agent_name] [dind_image] [local_image]"+ exit 1+ fi+ shift+ just _deploy-agent true "$@"+ ;;+ *)+ echo "unknown deploy target: {{ target }}"+ exit 1+ ;;+ esac++# Remove deployed targets. Examples: just remove agent, just remove swarm agent+[group('deploy')]+remove target *args:+ #!/usr/bin/env bash+ set -euo pipefail+ set -- {{ args }}+ case "{{ target }}" in+ agent)+ just _remove-agent "$@"+ ;;+ swarm)+ if [ "${1:-}" != "agent" ]; then+ echo "usage: just remove swarm agent [node_name] [agent_name]"+ exit 1+ fi+ shift+ just _remove-agent "$@"+ ;;+ *)+ echo "unknown remove target: {{ target }}"+ exit 1+ ;;+ esac# -----------------------------------------------------------------------------# Releasediff --git a/backend/api/handlers/swarm.go b/backend/api/handlers/swarm.goindex f2efb07da..8a1d6e679 100644--- a/backend/api/handlers/swarm.go+++ b/backend/api/handlers/swarm.go@@ -158,6 +158,43 @@ type GetSwarmNodeAgentDeploymentOutput struct {Body base.ApiResponse[SwarmNodeAgentDeployment]}+type ReconcileSwarmNodeAgentsInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.NodeAgentReconcileRequest+}++type ReconcileSwarmNodeAgentsOutput struct {+ Body base.ApiResponse[swarmtypes.NodeAgentReconcileResponse]+}++type PutSwarmNodeAgentBindingInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NodeID string `path:"nodeId" doc:"Node ID"`+ Body swarmtypes.NodeAgentBindingRequest+}++type PutSwarmNodeAgentBindingOutput struct {+ Body base.ApiResponse[swarmtypes.NodeSummary]+}++type DeleteSwarmNodeAgentBindingInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NodeID string `path:"nodeId" doc:"Node ID"`+}++type DeleteSwarmNodeAgentBindingOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type DeleteSwarmNodeAgentDeploymentInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NodeID string `path:"nodeId" doc:"Node ID"`+}++type DeleteSwarmNodeAgentDeploymentOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}+type GetSwarmNodeIdentityInput struct{}type GetSwarmNodeIdentityOutput struct {@@ -359,6 +396,23 @@ type JoinSwarmOutput struct {Body base.ApiResponse[base.MessageResponse]}+type GetSwarmJoinCandidatesInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type GetSwarmJoinCandidatesOutput struct {+ Body base.ApiResponse[[]swarmtypes.SwarmJoinCandidate]+}++type JoinSwarmEnvironmentsInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body swarmtypes.SwarmJoinEnvironmentsRequest+}++type JoinSwarmEnvironmentsOutput struct {+ Body base.ApiResponse[swarmtypes.SwarmJoinEnvironmentsResponse]+}+type LeaveSwarmInput struct {EnvironmentID string `path:"id" doc:"Environment ID"`Body swarmtypes.SwarmLeaveRequest@@ -532,6 +586,10 @@ func RegisterSwarm(api huma.API, swarmSvc *services.SwarmService, environmentSvchumamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.ListNodes)humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.GetNode)humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmNodes, h.GetNodeAgentDeployment)+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "reconcile-swarm-node-agents", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/agents/reconcile", Summary: "Reconcile swarm node agent bindings", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.ReconcileNodeAgents)+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "put-swarm-node-agent-binding", Method: http.MethodPut, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/binding", Summary: "Attach a visible environment to a swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.PutNodeAgentBinding)+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-node-agent-binding", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/binding", Summary: "Detach a visible environment from a swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.DeleteNodeAgentBinding)+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-node-agent-deployment", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/deployment", Summary: "Remove a dedicated swarm node agent registration", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.DeleteNodeAgentDeployment)humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmNodes, h.UpdateNode)humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmNodes, h.DeleteNode)humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmNodes, h.PromoteNode)@@ -555,6 +613,8 @@ func RegisterSwarm(api huma.API, swarmSvc *services.SwarmService, environmentSvchumamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.GetSwarmInfo)humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmInit, h.InitSwarm)humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmJoin, h.JoinSwarm)+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-join-candidates", Method: http.MethodGet, Path: "/environments/{id}/swarm/join-candidates", Summary: "List environments available for Easy Join", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.GetJoinCandidates)+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "join-swarm-environments", Method: http.MethodPost, Path: "/environments/{id}/swarm/join-environments", Summary: "Join environments to a swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.JoinEnvironments)humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmLeave, h.LeaveSwarm)humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmUnlock, h.UnlockSwarm)humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmUnlock, h.GetUnlockKey)@@ -840,12 +900,13 @@ func (h *SwarmHandler) GetNode(ctx context.Context, input *GetSwarmNodeInput) (*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.+// GetNodeAgentDeployment returns deployment snippets for attaching an Arcane Remote Environment 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.+// It ensures a visible node-bound Remote Environment exists for new+// deployments, reuses legacy hidden registrations when present, optionally+// rotates the environment token, generates the appropriate 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.@@ -885,12 +946,17 @@ func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwareturn nil, huma.Error500InternalServerError(err.Error())}- snippets, err := h.environmentService.GenerateEdgeDeploymentSnippets(ctx, env.ID, h.cfg.GetAppURL(), apiKey, &edge.Config{- EdgeMTLSMode: h.cfg.EdgeMTLSMode,- EdgeMTLSCAFile: h.cfg.EdgeMTLSCAFile,- EdgeMTLSAssetsDir: h.cfg.EdgeMTLSAssetsDir,- AppURL: h.cfg.GetAppURL(),- })+ var snippets *services.DeploymentSnippets+ if env.IsEdge {+ snippets, err = h.environmentService.GenerateEdgeDeploymentSnippets(ctx, env.ID, h.cfg.GetAppURL(), apiKey, &edge.Config{+ EdgeMTLSMode: h.cfg.EdgeMTLSMode,+ EdgeMTLSCAFile: h.cfg.EdgeMTLSCAFile,+ EdgeMTLSAssetsDir: h.cfg.EdgeMTLSAssetsDir,+ AppURL: h.cfg.GetAppURL(),+ })+ } else {+ snippets, err = h.environmentService.GenerateDeploymentSnippets(ctx, env.ID, h.cfg.GetAppURL(), apiKey)+ }if err != nil {return nil, huma.Error500InternalServerError(err.Error())}@@ -915,6 +981,71 @@ func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwa}, nil}+// ReconcileNodeAgents verifies and persists unique visible-environment node bindings.+func (h *SwarmHandler) ReconcileNodeAgents(ctx context.Context, input *ReconcileSwarmNodeAgentsInput) (*ReconcileSwarmNodeAgentsOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ result, err := h.swarmService.ReconcileNodeAgents(ctx, input.EnvironmentID)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to reconcile swarm node agents")+ }+ return &ReconcileSwarmNodeAgentsOutput{Body: base.ApiResponse[swarmtypes.NodeAgentReconcileResponse]{Success: true, Data: *result}}, nil+}++// PutNodeAgentBinding verifies and attaches an existing visible environment.+func (h *SwarmHandler) PutNodeAgentBinding(ctx context.Context, input *PutSwarmNodeAgentBindingInput) (*PutSwarmNodeAgentBindingOutput, error) {+ if h.swarmService == nil || h.environmentService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ if _, err := h.swarmService.BindNodeAgent(ctx, input.EnvironmentID, input.NodeID, input.Body); err != nil {+ return nil, huma.Error400BadRequest(err.Error())+ }+ if input.Body.ReplaceDeployment {+ user, err := requireUserInternal(ctx)+ if err != nil {+ return nil, err+ }+ if err := h.environmentService.DeleteSwarmNodeAgentDeployment(ctx, input.EnvironmentID, input.NodeID, &user.ID, &user.Username); err != nil {+ return nil, huma.Error500InternalServerError(err.Error())+ }+ }++ node, err := h.swarmService.GetNode(ctx, input.EnvironmentID, input.NodeID)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to refresh swarm node binding")+ }+ return &PutSwarmNodeAgentBindingOutput{Body: base.ApiResponse[swarmtypes.NodeSummary]{Success: true, Data: *node}}, nil+}++// DeleteNodeAgentBinding detaches the visible environment currently bound to a node.+func (h *SwarmHandler) DeleteNodeAgentBinding(ctx context.Context, input *DeleteSwarmNodeAgentBindingInput) (*DeleteSwarmNodeAgentBindingOutput, error) {+ if h.environmentService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := h.environmentService.DetachSwarmNodeEnvironment(ctx, input.EnvironmentID, input.NodeID); err != nil {+ return nil, huma.Error500InternalServerError(err.Error())+ }+ return &DeleteSwarmNodeAgentBindingOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm node environment detached"}}}, nil+}++// DeleteNodeAgentDeployment removes a dedicated hidden node-agent registration.+func (h *SwarmHandler) DeleteNodeAgentDeployment(ctx context.Context, input *DeleteSwarmNodeAgentDeploymentInput) (*DeleteSwarmNodeAgentDeploymentOutput, error) {+ if h.environmentService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ user, err := requireUserInternal(ctx)+ if err != nil {+ return nil, err+ }+ if err := h.environmentService.DeleteSwarmNodeAgentDeployment(ctx, input.EnvironmentID, input.NodeID, &user.ID, &user.Username); err != nil {+ return nil, huma.Error500InternalServerError(err.Error())+ }+ return &DeleteSwarmNodeAgentDeploymentOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Dedicated swarm node agent registration removed"}}}, 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,@@ -1432,6 +1563,102 @@ func (h *SwarmHandler) JoinSwarm(ctx context.Context, input *JoinSwarmInput) (*Jreturn &JoinSwarmOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Joined swarm successfully"}}}, nil}+// GetJoinCandidates lists enabled visible environments the caller can join.+func (h *SwarmHandler) GetJoinCandidates(ctx context.Context, input *GetSwarmJoinCandidatesInput) (*GetSwarmJoinCandidatesOutput, error) {+ if h.environmentService == nil || h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := requireEasyJoinManagerPermissionsInternal(ctx, input.EnvironmentID); err != nil {+ return nil, err+ }+ nodes, _, err := h.swarmService.ListNodesPaginated(ctx, input.EnvironmentID, pagination.QueryParams{Params: pagination.Params{Limit: -1}})+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to list Easy Join candidates")+ }+ boundEnvironmentIDs := make(map[string]struct{}, len(nodes))+ for _, node := range nodes {+ if node.Agent.EnvironmentID != nil {+ boundEnvironmentIDs[*node.Agent.EnvironmentID] = struct{}{}+ }+ }++ permissions, _ := humamw.PermissionsFromContext(ctx)+ environments, err := h.environmentService.ListSwarmNodeCandidateEnvironments(ctx)+ if err != nil {+ return nil, huma.Error500InternalServerError(err.Error())+ }+ candidates := make([]swarmtypes.SwarmJoinCandidate, 0, len(environments))+ for _, environment := range environments {+ if environment.ID == input.EnvironmentID || permissions == nil || !permissions.Allows(authz.PermSwarmJoin, environment.ID) {+ continue+ }+ if _, bound := boundEnvironmentIDs[environment.ID]; bound {+ continue+ }+ environmentType := "direct"+ if environment.IsEdge {+ environmentType = "edge"+ }+ candidates = append(candidates, swarmtypes.SwarmJoinCandidate{+ EnvironmentID: environment.ID,+ EnvironmentName: environment.Name,+ EnvironmentType: environmentType,+ Status: environment.Status,+ })+ }++ return &GetSwarmJoinCandidatesOutput{Body: base.ApiResponse[[]swarmtypes.SwarmJoinCandidate]{Success: true, Data: candidates}}, nil+}++// JoinEnvironments performs Easy Join without returning manager join tokens.+func (h *SwarmHandler) JoinEnvironments(ctx context.Context, input *JoinSwarmEnvironmentsInput) (*JoinSwarmEnvironmentsOutput, error) {+ if h.swarmService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if err := requireEasyJoinManagerPermissionsInternal(ctx, input.EnvironmentID); err != nil {+ return nil, err+ }++ permissions, _ := humamw.PermissionsFromContext(ctx)+ for _, target := range input.Body.Targets {+ if target.EnvironmentID == input.EnvironmentID {+ return nil, huma.Error400BadRequest("selected swarm manager cannot also be a join target")+ }+ if target.Role != swarmtypes.SwarmJoinEnvironmentRoleWorker && target.Role != swarmtypes.SwarmJoinEnvironmentRoleManager {+ return nil, huma.Error400BadRequest("join target role must be worker or manager")+ }+ if permissions == nil || !permissions.Allows(authz.PermSwarmJoin, target.EnvironmentID) {+ return nil, huma.Error403Forbidden("swarm:join permission is required for every target environment")+ }+ }++ if len(input.Body.RemoteAddrs) == 0 {+ nodes, _, err := h.swarmService.ListNodesPaginated(ctx, input.EnvironmentID, pagination.QueryParams{Params: pagination.Params{Limit: -1}})+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to derive swarm manager addresses")+ }+ for _, node := range nodes {+ if node.ManagerAddress != "" {+ input.Body.RemoteAddrs = append(input.Body.RemoteAddrs, node.ManagerAddress)+ }+ }+ }++ result, err := h.swarmService.JoinEnvironments(ctx, input.EnvironmentID, input.Body)+ if err != nil {+ return nil, mapSwarmServiceError(err, "Failed to join swarm environments")+ }+ return &JoinSwarmEnvironmentsOutput{Body: base.ApiResponse[swarmtypes.SwarmJoinEnvironmentsResponse]{Success: true, Data: *result}}, nil+}++func requireEasyJoinManagerPermissionsInternal(ctx context.Context, environmentID string) error {+ permissions, _ := humamw.PermissionsFromContext(ctx)+ if permissions == nil || !permissions.Allows(authz.PermSwarmNodes, environmentID) || !permissions.Allows(authz.PermSwarmUnlock, environmentID) {+ return huma.Error403Forbidden("swarm:nodes and swarm:unlock permissions are required on the manager environment")+ }+ return nil+}+// LeaveSwarm removes the target engine from its current swarm cluster.//// It requires admin privileges, forwards the leave request to the swarmdiff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.goindex 5a22c3289..0cc3cf220 100644--- a/backend/internal/middleware/environment_middleware.go+++ b/backend/internal/middleware/environment_middleware.go@@ -263,10 +263,13 @@ func (m *EnvironmentMiddleware) hasResourcePath(c echo.Context, envID string) boif !ok || len(suffix) <= 1 || suffix[0] != '/' {return false}- return !isManagementPathInternal(suffix)+ return !isManagementPathInternal(c.Request().Method, suffix)}-func isManagementPathInternal(suffix string) bool {+func isManagementPathInternal(method, suffix string) bool {+ if isCentralSwarmManagementPathInternal(method, suffix) {+ return true+ }if suffix == "/activities" || strings.HasPrefix(suffix, "/activities/") {return true}@@ -289,6 +292,30 @@ func isManagementPathInternal(suffix string) bool {return isManagement}+func isCentralSwarmManagementPathInternal(method, suffix string) bool {+ if method == http.MethodGet && (suffix == "/swarm/join-candidates" || suffix == "/swarm/nodes") {+ return true+ }+ if method == http.MethodPost && (suffix == "/swarm/join-environments" || suffix == "/swarm/nodes/agents/reconcile") {+ return true+ }++ parts := strings.Split(strings.Trim(suffix, "/"), "/")+ if len(parts) == 3 && method == http.MethodGet && parts[0] == "swarm" && parts[1] == "nodes" {+ return true+ }+ if len(parts) == 5 && parts[0] == "swarm" && parts[1] == "nodes" && parts[3] == "agent" {+ if parts[4] == "binding" {+ return method == http.MethodPut || method == http.MethodDelete+ }+ if parts[4] == "deployment" {+ return method == http.MethodDelete+ }+ }++ return false+}+// extractEnvironmentID gets the environment ID from the request.func (m *EnvironmentMiddleware) extractEnvironmentID(c echo.Context) string {requestPath := c.Request().URL.Pathdiff --git a/backend/internal/middleware/environment_middleware_test.go b/backend/internal/middleware/environment_middleware_test.goindex 803cfef57..29a9e9f93 100644--- a/backend/internal/middleware/environment_middleware_test.go+++ b/backend/internal/middleware/environment_middleware_test.go@@ -367,3 +367,13 @@ func TestEnvironmentMiddleware_CreateProxyRequest_RejectsInvalidProxyTarget(t *tassert.Error(t, err)assert.Contains(t, err.Error(), "Invalid proxy target URL")}++func TestIsCentralSwarmManagementPathInternal_IsMethodAware(t *testing.T) {+ assert.True(t, isCentralSwarmManagementPathInternal(http.MethodGet, "/swarm/nodes"))+ assert.True(t, isCentralSwarmManagementPathInternal(http.MethodGet, "/swarm/nodes/node-1"))+ assert.False(t, isCentralSwarmManagementPathInternal(http.MethodPatch, "/swarm/nodes/node-1"))+ assert.False(t, isCentralSwarmManagementPathInternal(http.MethodPost, "/swarm/nodes/node-1/agent/deployment"))+ assert.True(t, isCentralSwarmManagementPathInternal(http.MethodDelete, "/swarm/nodes/node-1/agent/deployment"))+ assert.True(t, isCentralSwarmManagementPathInternal(http.MethodPut, "/swarm/nodes/node-1/agent/binding"))+ assert.True(t, isCentralSwarmManagementPathInternal(http.MethodDelete, "/swarm/nodes/node-1/agent/binding"))+}diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.goindex eb9b6f098..41bd84426 100644--- a/backend/internal/services/environment_service.go+++ b/backend/internal/services/environment_service.go@@ -555,7 +555,6 @@ func (s *EnvironmentService) ListSwarmNodeAgentEnvironments(ctx context.Context,var envs []models.Environmentif 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)@@ -564,15 +563,120 @@ func (s *EnvironmentService) ListSwarmNodeAgentEnvironments(ctx context.Context,return envs, nil}+// ListSwarmNodeCandidateEnvironments returns enabled visible environments that+// can provide swarm-node coverage for a manager environment.+func (s *EnvironmentService) ListSwarmNodeCandidateEnvironments(ctx context.Context) ([]models.Environment, error) {+ var envs []models.Environment+ if err := s.db.WithContext(ctx).+ Model(&models.Environment{}).+ Where("hidden = ?", false).+ Where("enabled = ?", true).+ Where("id <> ?", "0").+ Order("name ASC").+ Find(&envs).Error; err != nil {+ return nil, fmt.Errorf("failed to list swarm node candidate environments: %w", err)+ }++ return envs, nil+}++// BindSwarmNodeEnvironment binds an existing visible environment to a swarm+// node without modifying its connection details or agent token.+func (s *EnvironmentService) BindSwarmNodeEnvironment(+ ctx context.Context,+ parentEnvironmentID, nodeID, environmentID string,+ rebind bool,+) (*models.Environment, error) {+ var environment models.Environment+ err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {+ if err := tx.Where("id = ?", environmentID).First(&environment).Error; err != nil {+ return fmt.Errorf("failed to load environment for swarm node binding: %w", err)+ }+ if environment.Hidden {+ return errors.New("dedicated agent environments cannot be attached as visible environments")+ }+ if !environment.Enabled {+ return errors.New("disabled environments cannot be attached to swarm nodes")+ }++ boundElsewhere := environment.ParentEnvironmentID != nil && environment.SwarmNodeID != nil &&+ (strings.TrimSpace(*environment.ParentEnvironmentID) != parentEnvironmentID || strings.TrimSpace(*environment.SwarmNodeID) != nodeID)+ if boundElsewhere && !rebind {+ return errors.New("environment is already bound to another swarm node; explicit rebinding is required")+ }++ var existingVisibleBindings int64+ if err := tx.Model(&models.Environment{}).+ Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ? AND id <> ?", false, parentEnvironmentID, nodeID, environmentID).+ Count(&existingVisibleBindings).Error; err != nil {+ return fmt.Errorf("failed to inspect existing swarm node binding: %w", err)+ }+ if existingVisibleBindings > 0 && !rebind {+ return errors.New("swarm node already has a visible environment binding; explicit rebinding is required")+ }+ if rebind {+ if err := tx.Model(&models.Environment{}).+ Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ? AND id <> ?", false, parentEnvironmentID, nodeID, environmentID).+ Updates(map[string]any{"parent_environment_id": nil, "swarm_node_id": nil, "updated_at": new(time.Now())}).Error; err != nil {+ return fmt.Errorf("failed to clear previous swarm node binding: %w", err)+ }+ }++ if err := tx.Model(&models.Environment{}).Where("id = ?", environmentID).Updates(map[string]any{+ "parent_environment_id": parentEnvironmentID,+ "swarm_node_id": nodeID,+ "updated_at": new(time.Now()),+ }).Error; err != nil {+ return fmt.Errorf("failed to bind environment to swarm node: %w", err)+ }++ return tx.Where("id = ?", environmentID).First(&environment).Error+ })+ if err != nil {+ return nil, err+ }++ s.cacheRemoteEnvironmentSnapshotInternal(environment)+ return &environment, nil+}++// DetachSwarmNodeEnvironment clears a visible environment binding from a node.+func (s *EnvironmentService) DetachSwarmNodeEnvironment(ctx context.Context, parentEnvironmentID, nodeID string) error {+ now := time.Now()+ if err := s.db.WithContext(ctx).Model(&models.Environment{}).+ Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ?", false, parentEnvironmentID, nodeID).+ Updates(map[string]any{"parent_environment_id": nil, "swarm_node_id": nil, "updated_at": &now}).Error; err != nil {+ return fmt.Errorf("failed to detach swarm node environment: %w", err)+ }++ return nil+}++// DeleteSwarmNodeAgentDeployment removes a dedicated hidden agent registration+// while leaving visible remote environments untouched.+func (s *EnvironmentService) DeleteSwarmNodeAgentDeployment(ctx context.Context, parentEnvironmentID, nodeID string, userID, username *string) error {+ var environment models.Environment+ if err := s.db.WithContext(ctx).+ Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ?", true, parentEnvironmentID, nodeID).+ First(&environment).Error; err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil+ }+ return fmt.Errorf("failed to load swarm node agent deployment: %w", err)+ }++ return s.DeleteEnvironment(ctx, environment.ID, userID, username)+}+func buildSwarmNodeAgentNameInternal(hostname, nodeID string) string {trimmedHostname := strings.TrimSpace(hostname)if trimmedHostname != "" {- return "Swarm Node Agent - " + trimmedHostname+ return trimmedHostname}if len(nodeID) > 12 {nodeID = nodeID[:12]}- return "Swarm Node Agent - " + nodeID+ return "Swarm Node " + nodeID}func buildSwarmNodeAgentURLInternal(nodeID string) string {@@ -626,10 +730,13 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(}var env models.Environment+ // Prefer an existing visible binding. Legacy hidden registrations remain+ // reusable, but all newly provisioned node agents are normal Remote+ // Environments so one token and one agent can serve both use cases.err := s.db.WithContext(ctx).- Where("hidden = ?", true).Where("parent_environment_id = ?", parentEnvironmentID).Where("swarm_node_id = ?", nodeID).+ Order("hidden ASC").First(&env).Errorif err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, "", fmt.Errorf("failed to load swarm node agent environment: %w", err)@@ -642,7 +749,7 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(Status: string(models.EnvironmentStatusPending),Enabled: true,IsEdge: true,- Hidden: true,+ Hidden: false,ParentEnvironmentID: new(parentEnvironmentID),SwarmNodeID: new(nodeID),}@@ -651,34 +758,6 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(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 {- updatedEnv, updateErr := s.UpdateEnvironment(ctx, env.ID, updates, new(userID), new(username))- 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)@@ -1439,13 +1518,13 @@ func (s *EnvironmentService) GenerateDeploymentSnippets(ctx context.Context, env" -p 3553:3553 \\"," -v /var/run/docker.sock:/var/run/docker.sock \\",fmt.Sprintf(" -v arcane-data:%s \\", deploymentSnippetsDataPath),- " ghcr.io/getarcaneapp/arcane-headless:latest",+ " ghcr.io/getarcaneapp/agent:latest",}, "\n")dockerCompose := strings.Join([]string{"services:"," arcane-agent:",- " image: ghcr.io/getarcaneapp/arcane-headless:latest",+ " image: ghcr.io/getarcaneapp/agent:latest"," container_name: arcane-agent"," restart: unless-stopped"," environment:",@@ -1484,14 +1563,14 @@ func (s *EnvironmentService) GenerateEdgeDeploymentSnippets(ctx context.Context,fmt.Sprintf(" -e MANAGER_API_URL=%s \\", managerURL)," -v /var/run/docker.sock:/var/run/docker.sock \\",fmt.Sprintf(" -v arcane-data:%s \\", deploymentSnippetsDataPath),- " ghcr.io/getarcaneapp/arcane-headless:latest",+ " ghcr.io/getarcaneapp/agent:latest",}, "\n")dockerCompose := strings.Join([]string{"# Edge agent - connects outbound, no exposed ports required","services:"," arcane-edge-agent:",- " image: ghcr.io/getarcaneapp/arcane-headless:latest",+ " image: ghcr.io/getarcaneapp/agent:latest"," container_name: arcane-edge-agent"," restart: unless-stopped"," environment:",@@ -1586,14 +1665,14 @@ func buildMTLSDeploymentSnippetInternal(managerURL string, apiKey string, generafmt.Sprintf(" -e MANAGER_API_URL=%s \\", managerURL)," -v /var/run/docker.sock:/var/run/docker.sock \\",fmt.Sprintf(" -v arcane-data:%s \\", deploymentSnippetsDataPath),- " ghcr.io/getarcaneapp/arcane-headless:latest",+ " ghcr.io/getarcaneapp/agent:latest",}, "\n")mtlsDockerCompose := strings.Join([]string{"# Edge agent with automatic mTLS enrollment","services:"," arcane-edge-agent:",- " image: ghcr.io/getarcaneapp/arcane-headless:latest",+ " image: ghcr.io/getarcaneapp/agent:latest"," container_name: arcane-edge-agent"," restart: unless-stopped"," environment:",diff --git a/backend/internal/services/environment_service_test.go b/backend/internal/services/environment_service_test.goindex 9060d2f9d..75b46b263 100644--- a/backend/internal/services/environment_service_test.go+++ b/backend/internal/services/environment_service_test.go@@ -625,7 +625,7 @@ func TestEnvironmentService_GenerateDeploymentSnippets_ExplicitlyUsePollTransporrequire.NotContains(t, edgeSnippets.DockerRun, "-v arcane-data:/data")}-func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesHiddenChildAndReusesToken(t *testing.T) {+func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesVisibleEnvironmentAndReusesToken(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)userService := NewUserService(db)@@ -645,9 +645,9 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesHiddenChildAnrequire.NoError(t, err)require.NotNil(t, createdEnv)require.NotEmpty(t, createdToken)- require.Equal(t, "Swarm Node Agent - worker-1", createdEnv.Name)+ require.Equal(t, "worker-1", createdEnv.Name)require.Equal(t, "edge://swarm-node-node-1234567", createdEnv.ApiUrl)- require.True(t, createdEnv.Hidden)+ require.False(t, createdEnv.Hidden)require.True(t, createdEnv.IsEdge)require.True(t, createdEnv.Enabled)require.Equal(t, string(models.EnvironmentStatusPending), createdEnv.Status)@@ -697,6 +697,62 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesHiddenChildAnrequire.Len(t, apiKeysAfterReuse, 1)}+func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_ReusesLegacyHiddenRegistration(t *testing.T) {+ ctx := context.Background()+ db := setupEnvironmentServiceTestDB(t)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)+ parentEnvironmentID := "manager-env"+ nodeID := "legacy-node"+ token := "legacy-agent-token"+ legacy := &models.Environment{+ BaseModel: models.BaseModel{ID: "legacy-agent"},+ Name: "Legacy node agent",+ ApiUrl: "edge://legacy-node",+ Status: string(models.EnvironmentStatusOffline),+ Enabled: true,+ IsEdge: true,+ Hidden: true,+ AccessToken: &token,+ ParentEnvironmentID: &parentEnvironmentID,+ SwarmNodeID: &nodeID,+ }+ if err := db.WithContext(ctx).Create(legacy).Error; err != nil {+ t.Fatalf("create legacy environment: %v", err)+ }++ reused, reusedToken, err := svc.EnsureSwarmNodeAgentEnvironment(+ ctx,+ parentEnvironmentID,+ nodeID,+ "legacy-host",+ "user-id",+ "username",+ false,+ )+ if err != nil {+ t.Fatalf("EnsureSwarmNodeAgentEnvironment() error = %v", err)+ }+ if reused.ID != legacy.ID {+ t.Fatalf("environment ID = %q, want %q", reused.ID, legacy.ID)+ }+ if !reused.Hidden {+ t.Fatal("legacy environment was unexpectedly converted to visible")+ }+ if reusedToken != token {+ t.Fatalf("token = %q, want existing token", reusedToken)+ }++ var environments []models.Environment+ if err := db.WithContext(ctx).+ Where("parent_environment_id = ? AND swarm_node_id = ?", parentEnvironmentID, nodeID).+ Find(&environments).Error; err != nil {+ t.Fatalf("list node environments: %v", err)+ }+ if len(environments) != 1 {+ t.Fatalf("environment count = %d, want 1", len(environments))+ }+}+// TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_TokenResolvesEndToEnd// pins the agent token round-trip: the token returned from the swarm node// agent provisioning flow must resolve back to the same environment via@@ -758,6 +814,45 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_TokenResolvesEndToEnrequire.Contains(t, err.Error(), "invalid agent token")}+func TestEnvironmentService_BindSwarmNodeEnvironment_PreservesVisibleEnvironmentToken(t *testing.T) {+ ctx := context.Background()+ db := setupEnvironmentServiceTestDB(t)+ token := "existing-agent-token"+ createTestEnvironment(t, db, "visible-env", "http://visible.example", &token)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)++ bound, err := svc.BindSwarmNodeEnvironment(ctx, "manager-env", "node-1", "visible-env", false)+ require.NoError(t, err)+ require.False(t, bound.Hidden)+ require.Equal(t, "manager-env", *bound.ParentEnvironmentID)+ require.Equal(t, "node-1", *bound.SwarmNodeID)+ require.Equal(t, token, *bound.AccessToken)++ require.NoError(t, svc.DetachSwarmNodeEnvironment(ctx, "manager-env", "node-1"))+ detached, err := svc.GetEnvironmentByID(ctx, "visible-env")+ require.NoError(t, err)+ require.Nil(t, detached.ParentEnvironmentID)+ require.Nil(t, detached.SwarmNodeID)+ require.Equal(t, token, *detached.AccessToken)+}++func TestEnvironmentService_BindSwarmNodeEnvironment_RequiresExplicitRebind(t *testing.T) {+ ctx := context.Background()+ db := setupEnvironmentServiceTestDB(t)+ createTestEnvironment(t, db, "visible-env", "http://visible.example", nil)+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)++ _, err := svc.BindSwarmNodeEnvironment(ctx, "manager-a", "node-a", "visible-env", false)+ require.NoError(t, err)+ _, err = svc.BindSwarmNodeEnvironment(ctx, "manager-b", "node-b", "visible-env", false)+ require.ErrorContains(t, err, "explicit rebinding is required")++ rebound, err := svc.BindSwarmNodeEnvironment(ctx, "manager-b", "node-b", "visible-env", true)+ require.NoError(t, err)+ require.Equal(t, "manager-b", *rebound.ParentEnvironmentID)+ require.Equal(t, "node-b", *rebound.SwarmNodeID)+}+func TestEnvironmentService_ListMethods_ExcludeHiddenEnvironments(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)diff --git a/backend/internal/services/swarm_service.go b/backend/internal/services/swarm_service.goindex d0ad28f40..b38d42743 100644--- a/backend/internal/services/swarm_service.go+++ b/backend/internal/services/swarm_service.go@@ -37,6 +37,7 @@ import (const (swarmNodeIdentityProbeConcurrency = 5+ swarmNodeIdentityCacheTTL = 30 * time.SecondKVKeySwarmEnabled = "swarm.enabled"defaultSwarmListenAddr = "0.0.0.0:2377")@@ -48,6 +49,8 @@ type SwarmService struct {kvService *KVServiceregistryService *ContainerRegistryServiceenvironmentService *EnvironmentService+ identityCacheMu sync.RWMutex+ identityCache map[string]swarmNodeIdentityCacheEntry}func NewSwarmService(@@ -63,6 +66,7 @@ func NewSwarmService(kvService: kvService,registryService: registryService,environmentService: environmentService,+ identityCache: make(map[string]swarmNodeIdentityCacheEntry),}}@@ -81,6 +85,18 @@ type swarmNodeAgentRuntime struct {identity *SwarmNodeIdentity}+type swarmNodeIdentityCacheEntry struct {+ identity SwarmNodeIdentity+ expiresAt time.Time+}++type swarmNodeAgentCoverage struct {+ runtimeByEnvID map[string]swarmNodeAgentRuntime+ boundEnvsByNodeID map[string][]models.Environment+ candidatesByNodeID map[string][]models.Environment+ localIdentity *SwarmNodeIdentity+}+func (s *SwarmService) IsEnabled(ctx context.Context) (bool, error) {if s.kvService == nil {return false, nil@@ -464,6 +480,23 @@ func (s *SwarmService) StreamServiceLogs(ctx context.Context, serviceID string,}func (s *SwarmService) ListNodesPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]swarmtypes.NodeSummary, pagination.Response, error) {+ if environmentID != "0" && s.environmentService != nil {+ var remote struct {+ Success bool `json:"success"`+ Data []swarmtypes.NodeSummary `json:"data"`+ }+ if err := s.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, "/api/environments/0/swarm/nodes?limit=-1", nil, &remote); err != nil {+ return nil, pagination.Response{}, fmt.Errorf("failed to list remote swarm nodes: %w", err)+ }+ if !remote.Success {+ return nil, pagination.Response{}, errors.New("remote swarm node listing failed")+ }++ s.enrichNodeAgentStatusesInternal(ctx, environmentID, remote.Data)+ result := pagination.SearchOrderAndPaginate(remote.Data, params, s.buildNodePaginationConfigInternal())+ return result.Items, buildPaginationResponseInternal(result, params), nil+ }+if err := s.ensureSwarmManagerInternal(ctx); err != nil {return nil, pagination.Response{}, err}@@ -494,6 +527,23 @@ func (s *SwarmService) ListNodesPaginated(ctx context.Context, environmentID str}func (s *SwarmService) GetNode(ctx context.Context, environmentID, nodeID string) (*swarmtypes.NodeSummary, error) {+ if environmentID != "0" && s.environmentService != nil {+ var remote struct {+ Success bool `json:"success"`+ Data swarmtypes.NodeSummary `json:"data"`+ }+ remotePath := "/api/environments/0/swarm/nodes/" + nodeID+ if err := s.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, remotePath, nil, &remote); err != nil {+ return nil, fmt.Errorf("failed to inspect remote swarm node: %w", err)+ }+ if !remote.Success {+ return nil, errors.New("remote swarm node inspection failed")+ }+ items := []swarmtypes.NodeSummary{remote.Data}+ s.enrichNodeAgentStatusesInternal(ctx, environmentID, items)+ return &items[0], nil+ }+if err := s.ensureSwarmManagerInternal(ctx); err != nil {return nil, err}@@ -513,6 +563,70 @@ func (s *SwarmService) GetNode(ctx context.Context, environmentID, nodeID stringreturn new(items[0]), nil}+// ReconcileNodeAgents verifies visible environment identities and persists only+// unique node matches. Ambiguous and mismatched identities remain unchanged.+func (s *SwarmService) ReconcileNodeAgents(ctx context.Context, environmentID string) (*swarmtypes.NodeAgentReconcileResponse, error) {+ items, _, err := s.ListNodesPaginated(ctx, environmentID, pagination.QueryParams{Params: pagination.Params{Limit: -1}})+ if err != nil {+ return nil, err+ }++ results := make([]swarmtypes.NodeAgentReconcileResult, 0, len(items))+ for _, node := range items {+ result := swarmtypes.NodeAgentReconcileResult{+ NodeID: node.ID,+ State: node.Agent.State,+ EnvironmentID: node.Agent.EnvironmentID,+ Candidates: node.Agent.Candidates,+ }+ if node.Agent.State == swarmtypes.NodeAgentStateMismatched || len(node.Agent.Candidates) != 1 {+ results = append(results, result)+ continue+ }++ candidate := node.Agent.Candidates[0]+ bound, bindErr := s.environmentService.BindSwarmNodeEnvironment(ctx, environmentID, node.ID, candidate.EnvironmentID, false)+ if bindErr != nil {+ slog.WarnContext(ctx, "failed to persist reconciled swarm node binding", "environmentID", candidate.EnvironmentID, "nodeID", node.ID, "error", bindErr.Error())+ results = append(results, result)+ continue+ }++ result.State = swarmtypes.NodeAgentStateConnected+ result.EnvironmentID = &bound.ID+ result.Candidates = nil+ results = append(results, result)+ }++ return &swarmtypes.NodeAgentReconcileResponse{Results: results}, nil+}++// BindNodeAgent verifies that a visible environment currently reports the+// requested node identity before persisting the binding.+func (s *SwarmService) BindNodeAgent(ctx context.Context, parentEnvironmentID, nodeID string, request swarmtypes.NodeAgentBindingRequest) (*models.Environment, error) {+ environment, err := s.environmentService.GetEnvironmentByID(ctx, request.EnvironmentID)+ if err != nil {+ return nil, err+ }+ if environment.Hidden {+ return nil, errors.New("only visible environments can be attached")+ }++ runtime := s.resolveSwarmNodeAgentRuntimeInternal(ctx, environment)+ if runtime.identity == nil || !runtime.identity.SwarmActive {+ return nil, errors.New("environment did not report an active swarm identity")+ }+ if strings.TrimSpace(runtime.identity.SwarmNodeID) != strings.TrimSpace(nodeID) {+ return nil, fmt.Errorf("environment reports swarm node %s instead of %s", runtime.identity.SwarmNodeID, nodeID)+ }++ bound, err := s.environmentService.BindSwarmNodeEnvironment(ctx, parentEnvironmentID, nodeID, request.EnvironmentID, request.Rebind)+ if err != nil {+ return nil, err+ }+ return bound, nil+}+func (s *SwarmService) GetLocalNodeIdentity(ctx context.Context) (*SwarmNodeIdentity, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {@@ -548,20 +662,44 @@ func (s *SwarmService) enrichNodeAgentStatusesInternal(ctx context.Context, enviif s.environmentService == nil || len(items) == 0 || strings.TrimSpace(environmentID) == "" {return}+ coverage, err := s.resolveNodeAgentCoverageInternal(ctx, environmentID)+ if err != nil {+ slog.WarnContext(ctx, "failed to resolve swarm node agent coverage", "environmentID", environmentID, "error", err.Error())+ return+ }+ for index := range items {+ item := &items[index]+ s.applyNodeAgentCoverageInternal(environmentID, item, coverage)+ }+}++func (s *SwarmService) resolveNodeAgentCoverageInternal(ctx context.Context, environmentID string) (*swarmNodeAgentCoverage, error) {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+ return nil, err+ }++ candidateEnvs, err := s.environmentService.ListSwarmNodeCandidateEnvironments(ctx)+ if err != nil {+ slog.WarnContext(ctx, "failed to load swarm node agent candidates", "environmentID", environmentID, "error", err.Error())+ candidateEnvs = nil+ }++ probeEnvsByID := make(map[string]models.Environment, len(agentEnvs)+len(candidateEnvs))+ for _, env := range candidateEnvs {+ probeEnvsByID[env.ID] = env+ }+ for _, env := range agentEnvs {+ probeEnvsByID[env.ID] = env}- runtimeByEnvID := make(map[string]swarmNodeAgentRuntime, len(agentEnvs))- envByNodeID := make(map[string]models.Environment, len(agentEnvs))+ runtimeByEnvID := make(map[string]swarmNodeAgentRuntime, len(probeEnvsByID))var runtimeMu sync.Mutexg, groupCtx := errgroup.WithContext(ctx)g.SetLimit(swarmNodeIdentityProbeConcurrency)- for i := range agentEnvs {- env := agentEnvs[i]+ for _, candidate := range probeEnvsByID {+ env := candidateg.Go(func() error {runtime := s.resolveSwarmNodeAgentRuntimeInternal(groupCtx, &env)runtimeMu.Lock()@@ -571,41 +709,107 @@ func (s *SwarmService) enrichNodeAgentStatusesInternal(ctx context.Context, envi})}if err := g.Wait(); err != nil {- slog.WarnContext(ctx, "failed to resolve swarm node agent runtimes", "environmentID", environmentID, "error", err.Error())- return+ return nil, err+ }++ boundEnvsByNodeID := make(map[string][]models.Environment, len(agentEnvs))+ for _, env := range agentEnvs {+ if env.SwarmNodeID != nil && strings.TrimSpace(*env.SwarmNodeID) != "" {+ nodeID := strings.TrimSpace(*env.SwarmNodeID)+ boundEnvsByNodeID[nodeID] = append(boundEnvsByNodeID[nodeID], env)+ }}- for i := range agentEnvs {- env := agentEnvs[i]+ candidatesByNodeID := make(map[string][]models.Environment)+ for _, env := range candidateEnvs {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 runtime.identity == nil || !runtime.identity.SwarmActive {+ continue+ }+ nodeID := strings.TrimSpace(runtime.identity.SwarmNodeID)+ if nodeID != "" {+ candidatesByNodeID[nodeID] = append(candidatesByNodeID[nodeID], env)}+ }- if env.SwarmNodeID != nil && strings.TrimSpace(*env.SwarmNodeID) != "" {- envByNodeID[strings.TrimSpace(*env.SwarmNodeID)] = env+ coverage := &swarmNodeAgentCoverage{+ runtimeByEnvID: runtimeByEnvID,+ boundEnvsByNodeID: boundEnvsByNodeID,+ candidatesByNodeID: candidatesByNodeID,+ }+ if environmentID == "0" {+ identity, identityErr := s.GetLocalNodeIdentity(ctx)+ if identityErr == nil {+ coverage.localIdentity = identity}}+ return coverage, nil+}- 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+func (s *SwarmService) applyNodeAgentCoverageInternal(environmentID string, item *swarmtypes.NodeSummary, coverage *swarmNodeAgentCoverage) {+ if item == nil || coverage == nil {+ return+ }+ nodeID := strings.TrimSpace(item.ID)+ if environmentID == "0" && coverage.localIdentity != nil && coverage.localIdentity.SwarmActive && strings.TrimSpace(coverage.localIdentity.SwarmNodeID) == nodeID {+ connected := true+ bindingKind := swarmtypes.NodeAgentBindingKindLocal+ localID, localName, localType := "0", "Local", "local"+ item.Agent = swarmtypes.NodeAgentStatus{+ State: swarmtypes.NodeAgentStateConnected,+ BindingKind: &bindingKind,+ EnvironmentID: &localID,+ EnvironmentName: &localName,+ EnvironmentType: &localType,+ Connected: &connected,}+ return+ }- runtime := runtimeByEnvID[env.ID]- items[i].Agent = s.buildNodeAgentStatusInternal(nodeID, &env, runtime)+ boundEnvs := coverage.boundEnvsByNodeID[nodeID]+ if len(boundEnvs) > 0 {+ environment := preferredNodeAgentEnvironmentInternal(boundEnvs)+ item.Agent = s.buildNodeAgentStatusInternal(nodeID, &environment, coverage.runtimeByEnvID[environment.ID])+ return+ }++ candidates := coverage.candidatesByNodeID[nodeID]+ if len(candidates) > 1 {+ item.Agent = swarmtypes.NodeAgentStatus{State: swarmtypes.NodeAgentStateAmbiguous, Candidates: buildNodeAgentCandidatesInternal(candidates)}+ return+ }+ if len(candidates) == 1 {+ item.Agent.Candidates = buildNodeAgentCandidatesInternal(candidates)+ }+}++func preferredNodeAgentEnvironmentInternal(environments []models.Environment) models.Environment {+ var preferred models.Environment+ for index, environment := range environments {+ if index == 0 {+ preferred = environment+ }+ if !environment.Hidden {+ return environment+ }+ }+ return preferred+}++func buildNodeAgentCandidatesInternal(environments []models.Environment) []swarmtypes.NodeAgentCandidate {+ candidates := make([]swarmtypes.NodeAgentCandidate, 0, len(environments))+ for _, environment := range environments {+ environmentType := "direct"+ if environment.IsEdge {+ environmentType = "edge"+ }+ candidates = append(candidates, swarmtypes.NodeAgentCandidate{+ EnvironmentID: environment.ID,+ EnvironmentName: environment.Name,+ EnvironmentType: environmentType,+ })}+ return candidates}func (s *SwarmService) resolveSwarmNodeAgentRuntimeInternal(ctx context.Context, env *models.Environment) swarmNodeAgentRuntime {@@ -625,7 +829,9 @@ func (s *SwarmService) resolveSwarmNodeAgentRuntimeInternal(ctx context.Context,runtime.lastPollAt = pollState.LastPollAt}- if !runtime.connected {+ if identity := s.cachedSwarmNodeIdentityInternal(env.ID, time.Now()); identity != nil {+ runtime.connected = true+ runtime.identity = identityreturn runtime}@@ -635,10 +841,202 @@ func (s *SwarmService) resolveSwarmNodeAgentRuntimeInternal(ctx context.Context,return runtime}+ runtime.connected = trueruntime.identity = identity+ s.cacheSwarmNodeIdentityInternal(env.ID, *identity, time.Now())return runtime}+func (s *SwarmService) cachedSwarmNodeIdentityInternal(environmentID string, now time.Time) *SwarmNodeIdentity {+ s.identityCacheMu.RLock()+ entry, ok := s.identityCache[environmentID]+ s.identityCacheMu.RUnlock()+ if !ok || !now.Before(entry.expiresAt) {+ return nil+ }+ identity := entry.identity+ return &identity+}++func (s *SwarmService) cacheSwarmNodeIdentityInternal(environmentID string, identity SwarmNodeIdentity, now time.Time) {+ s.identityCacheMu.Lock()+ s.identityCache[environmentID] = swarmNodeIdentityCacheEntry{identity: identity, expiresAt: now.Add(swarmNodeIdentityCacheTTL)}+ s.identityCacheMu.Unlock()+}++func (s *SwarmService) invalidateSwarmNodeIdentityInternal(environmentID string) {+ s.identityCacheMu.Lock()+ delete(s.identityCache, environmentID)+ s.identityCacheMu.Unlock()+}++// JoinEnvironments joins visible remote environments to the selected swarm+// manager and returns an independent result for every target.+func (s *SwarmService) JoinEnvironments(ctx context.Context, managerEnvironmentID string, request swarmtypes.SwarmJoinEnvironmentsRequest) (*swarmtypes.SwarmJoinEnvironmentsResponse, error) {+ if len(request.Targets) == 0 {+ return &swarmtypes.SwarmJoinEnvironmentsResponse{Results: []swarmtypes.SwarmJoinEnvironmentResult{}}, nil+ }+ if len(request.RemoteAddrs) == 0 {+ return nil, errors.New("at least one swarm manager address is required")+ }++ tokens, err := s.getSwarmJoinTokensForEnvironmentInternal(ctx, managerEnvironmentID)+ if err != nil {+ return nil, err+ }+ nodes, _, err := s.ListNodesPaginated(ctx, managerEnvironmentID, pagination.QueryParams{Params: pagination.Params{Limit: -1}})+ if err != nil {+ return nil, err+ }+ memberNodeIDs := make(map[string]struct{}, len(nodes))+ for _, node := range nodes {+ memberNodeIDs[node.ID] = struct{}{}+ }++ results := make([]swarmtypes.SwarmJoinEnvironmentResult, len(request.Targets))+ processTargetInternal := func(index int) {+ target := request.Targets[index]+ results[index] = s.joinEnvironmentInternal(ctx, managerEnvironmentID, target, request.RemoteAddrs, tokens, memberNodeIDs)+ }++ for index, target := range request.Targets {+ if target.Role == swarmtypes.SwarmJoinEnvironmentRoleManager {+ processTargetInternal(index)+ }+ }++ group, groupCtx := errgroup.WithContext(ctx)+ group.SetLimit(swarmNodeIdentityProbeConcurrency)+ for index, target := range request.Targets {+ if target.Role != swarmtypes.SwarmJoinEnvironmentRoleWorker {+ continue+ }+ group.Go(func() error {+ if groupCtx.Err() == nil {+ processTargetInternal(index)+ }+ return nil+ })+ }+ _ = group.Wait()++ return &swarmtypes.SwarmJoinEnvironmentsResponse{Results: results}, nil+}++func (s *SwarmService) getSwarmJoinTokensForEnvironmentInternal(ctx context.Context, environmentID string) (*swarmtypes.SwarmJoinTokensResponse, error) {+ if environmentID == "0" {+ return s.GetSwarmJoinTokens(ctx)+ }++ var response struct {+ Success bool `json:"success"`+ Data swarmtypes.SwarmJoinTokensResponse `json:"data"`+ }+ if err := s.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, "/api/environments/0/swarm/join-tokens", nil, &response); err != nil {+ return nil, fmt.Errorf("failed to get remote swarm join tokens: %w", err)+ }+ if !response.Success {+ return nil, errors.New("remote swarm join-token request failed")+ }+ return &response.Data, nil+}++func (s *SwarmService) joinEnvironmentInternal(+ ctx context.Context,+ managerEnvironmentID string,+ target swarmtypes.SwarmJoinEnvironmentTarget,+ remoteAddrs []string,+ tokens *swarmtypes.SwarmJoinTokensResponse,+ memberNodeIDs map[string]struct{},+) swarmtypes.SwarmJoinEnvironmentResult {+ result := swarmtypes.SwarmJoinEnvironmentResult{EnvironmentID: target.EnvironmentID, State: swarmtypes.SwarmJoinEnvironmentResultFailed}+ environment, err := s.environmentService.GetEnvironmentByID(ctx, target.EnvironmentID)+ if err != nil || environment.Hidden || !environment.Enabled {+ message := "target environment is unavailable"+ if err != nil {+ message = err.Error()+ }+ result.Error = &message+ return result+ }++ runtime := s.resolveSwarmNodeAgentRuntimeInternal(ctx, environment)+ if runtime.identity != nil && runtime.identity.SwarmActive {+ nodeID := strings.TrimSpace(runtime.identity.SwarmNodeID)+ if _, member := memberNodeIDs[nodeID]; !member {+ message := "environment is active in another swarm cluster"+ result.Error = &message+ return result+ }+ if _, err := s.environmentService.BindSwarmNodeEnvironment(ctx, managerEnvironmentID, nodeID, target.EnvironmentID, true); err != nil {+ message := err.Error()+ result.Error = &message+ return result+ }+ result.State = swarmtypes.SwarmJoinEnvironmentResultAlreadyMember+ result.NodeID = &nodeID+ return result+ }++ joinToken := tokens.Worker+ if target.Role == swarmtypes.SwarmJoinEnvironmentRoleManager {+ joinToken = tokens.Manager+ }+ joinRequest := swarmtypes.SwarmJoinRequest{+ ListenAddr: target.ListenAddr,+ AdvertiseAddr: target.AdvertiseAddr,+ DataPathAddr: target.DataPathAddr,+ RemoteAddrs: remoteAddrs,+ JoinToken: joinToken,+ Availability: target.Availability,+ }+ body, err := json.Marshal(joinRequest)+ if err != nil {+ message := err.Error()+ result.Error = &message+ return result+ }+ var joinResponse struct {+ Success bool `json:"success"`+ }+ if err := s.environmentService.ProxyJSONRequest(ctx, target.EnvironmentID, http.MethodPost, "/api/environments/0/swarm/join", body, &joinResponse); err != nil || !joinResponse.Success {+ message := "swarm join failed"+ if err != nil {+ message = err.Error()+ }+ result.Error = &message+ return result+ }++ for range 6 {+ s.invalidateSwarmNodeIdentityInternal(target.EnvironmentID)+ verifiedRuntime := s.resolveSwarmNodeAgentRuntimeInternal(ctx, environment)+ if verifiedRuntime.identity != nil && verifiedRuntime.identity.SwarmActive {+ nodeID := strings.TrimSpace(verifiedRuntime.identity.SwarmNodeID)+ if _, err := s.GetNode(ctx, managerEnvironmentID, nodeID); err == nil {+ if _, bindErr := s.environmentService.BindSwarmNodeEnvironment(ctx, managerEnvironmentID, nodeID, target.EnvironmentID, true); bindErr == nil {+ result.State = swarmtypes.SwarmJoinEnvironmentResultJoined+ result.NodeID = &nodeID+ result.Error = nil+ return result+ }+ }+ }++ select {+ case <-ctx.Done():+ message := ctx.Err().Error()+ result.Error = &message+ return result+ case <-time.After(time.Second):+ }+ }++ result.State = swarmtypes.SwarmJoinEnvironmentResultJoinedUnverified+ result.Error = nil+ return result+}+func (s *SwarmService) fetchSwarmNodeIdentityViaEdgeInternal(ctx context.Context, environmentID string) (*SwarmNodeIdentity, error) {reqCtx, cancel := context.WithTimeout(ctx, 5*time.Second)defer cancel()@@ -676,6 +1074,17 @@ func (s *SwarmService) buildNodeAgentStatusInternal(nodeID string, env *models.ELastHeartbeat: runtime.lastHeartbeat,LastPollAt: runtime.lastPollAt,}+ status.EnvironmentName = &env.Name+ environmentType := "direct"+ if env.IsEdge {+ environmentType = "edge"+ }+ status.EnvironmentType = &environmentType+ bindingKind := swarmtypes.NodeAgentBindingKindEnvironment+ if env.Hidden {+ bindingKind = swarmtypes.NodeAgentBindingKindDedicated+ }+ status.BindingKind = &bindingKindif runtime.identity != nil {if reportedNodeID := strings.TrimSpace(runtime.identity.SwarmNodeID); reportedNodeID != "" {diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex ed840712c..1e96685fd 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -1140,10 +1140,17 @@"swarm_cluster_rotate_tokens": "Rotate Tokens","swarm_cluster_initialize_title": "Initialize Cluster","swarm_cluster_initialize_subtitle": "Initialize swarm on this engine",+ "swarm_cluster_initialize_description": "Create a new Swarm with this engine as its first manager.",+ "swarm_cluster_initialize_hint": "The default settings are suitable for a local or single-network cluster. Configure addresses or security options only when your network requires them.","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_description": "Connect this engine to a Swarm that is already running.","swarm_cluster_join_action": "Join",+ "swarm_cluster_setup_title": "Choose how to set up this engine",+ "swarm_cluster_setup_description": "Docker Swarm is not initialized here yet. Start a new cluster or join an existing one; cluster status, tokens, and security controls will appear after setup.",+ "swarm_cluster_advanced_settings": "Advanced settings",+ "swarm_cluster_manager_addresses_label": "Manager addresses","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.",@@ -1237,21 +1244,66 @@"swarm_node_demote": "Demote","swarm_node_drain": "Drain","swarm_node_activate": "Activate",- "swarm_node_agent_deploy": "Deploy Agent",+ "swarm_node_agent_deploy": "Connect 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_description": "Create or review the Remote Environment that provides this Swarm node's verified coverage and node-local resources.","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_dialog_blurb_description": "One Arcane Remote Environment agent can provide both normal environment management and verified coverage for this Swarm node.","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_warning_description": "{count} node(s) are not connected to an Arcane Remote Environment yet. Connect 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_status_ambiguous": "Ambiguous","swarm_node_agent_environment_id": "Agent Environment ID","swarm_node_agent_refresh_status": "Refresh Status",+ "swarm_node_agent_binding_kind": "Coverage type",+ "swarm_node_agent_binding_local": "Local manager",+ "swarm_node_agent_binding_environment": "Remote Environment",+ "swarm_node_agent_binding_dedicated": "Dedicated node agent",+ "swarm_node_agent_binding_none": "No binding",+ "swarm_node_agent_candidates_title": "Verified environment candidates",+ "swarm_node_agent_candidates_description": "Select the Remote Environment that should cover this node. Ambiguous matches are never attached automatically.",+ "swarm_node_agent_attach_action": "Attach environment",+ "swarm_node_agent_attach_success": "Remote Environment attached to the Swarm node",+ "swarm_node_agent_replace_title": "Replace dedicated registration?",+ "swarm_node_agent_replace_description": "The verified Remote Environment will cover this node and the obsolete dedicated agent registration and API key will be removed.",+ "swarm_node_agent_replace_action": "Replace registration",+ "swarm_node_agent_detach_title": "Detach Remote Environment?",+ "swarm_node_agent_detach_description": "This removes the node binding without deleting or changing the Remote Environment or its agent token.",+ "swarm_node_agent_detach_action": "Detach environment",+ "swarm_node_agent_remove_deployment_title": "Remove dedicated registration?",+ "swarm_node_agent_remove_deployment_description": "This deletes the hidden dedicated agent environment and its API key.",+ "swarm_node_agent_remove_deployment_action": "Remove registration",+ "swarm_node_agent_resources_title": "Node-local resources",+ "swarm_node_agent_resources_description": "Open this node's existing Remote Environment resource pages.",+ "swarm_node_agent_create_environment_title": "Create a Remote Environment",+ "swarm_node_agent_create_environment_description": "Create one visible Edge environment for this node, then deploy its agent with the generated command. The same environment provides Swarm coverage and node-local resources.",+ "swarm_node_agent_create_environment_action": "Create environment",+ "swarm_node_agent_deployment_title": "Remote Environment deployment",+ "swarm_node_agent_deployment_description": "Use the existing environment token to deploy or restore this node's agent without creating another registration.",+ "swarm_node_agent_legacy_deployment_title": "Legacy dedicated registration",+ "swarm_node_agent_legacy_deployment_description": "This existing hidden registration remains supported. New node agents are created as visible Remote Environments.",+ "swarm_node_agent_show_deployment": "Show deployment",+ "swarm_easy_join_title": "Easy Join environments",+ "swarm_easy_join_description": "Join one or more Remote Environments to this cluster without copying Swarm tokens.",+ "swarm_easy_join_action": "Easy Join",+ "swarm_easy_join_no_candidates": "No enabled Remote Environments with join permission are available.",+ "swarm_easy_join_targets_required": "Select at least one Remote Environment.",+ "swarm_easy_join_role_worker": "Worker",+ "swarm_easy_join_role_manager": "Manager",+ "swarm_easy_join_availability_active": "Active",+ "swarm_easy_join_availability_pause": "Pause",+ "swarm_easy_join_availability_drain": "Drain",+ "swarm_easy_join_data_path_placeholder": "Data-path address (optional)",+ "swarm_easy_join_results_title": "Join results",+ "swarm_easy_join_result_joined": "Joined and verified",+ "swarm_easy_join_result_already_member": "Already a member and verified",+ "swarm_easy_join_result_joined_unverified": "Joined; verification is still pending",+ "swarm_easy_join_result_failed": "Failed","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}\"",diff --git a/frontend/src/lib/hooks/use-easy-join-candidates.svelte.ts b/frontend/src/lib/hooks/use-easy-join-candidates.svelte.tsnew file mode 100644index 000000000..d9a4918b6--- /dev/null+++ b/frontend/src/lib/hooks/use-easy-join-candidates.svelte.ts@@ -0,0 +1,40 @@+import { swarmService } from '$lib/services/swarm-service';+import { environmentStore } from '$lib/stores/environment.store.svelte';+import type { SwarmJoinCandidate } from '$lib/types/swarm';++export function useEasyJoinCandidates() {+ let candidates = $state<SwarmJoinCandidate[]>([]);+ let managerEnvironmentId = $state<string | null>(null);+ let refreshVersion = $state(0);+ let requestVersion = 0;++ $effect(() => {+ const environmentId = environmentStore.selected?.id ?? null;+ void refreshVersion;+ managerEnvironmentId = environmentId;+ candidates = [];+ const currentRequest = ++requestVersion;+ if (!environmentId) return;++ void swarmService+ .getSwarmJoinCandidates(environmentId)+ .then((result) => {+ if (currentRequest === requestVersion) candidates = result;+ })+ .catch(() => {+ if (currentRequest === requestVersion) candidates = [];+ });+ });++ return {+ get managerEnvironmentId() {+ return managerEnvironmentId;+ },+ isCandidate(environmentId: string) {+ return candidates.some((candidate) => candidate.environmentId === environmentId);+ },+ refresh() {+ refreshVersion += 1;+ }+ };+}diff --git a/frontend/src/lib/services/swarm-service.ts b/frontend/src/lib/services/swarm-service.tsindex 241f3c837..7603a1437 100644--- a/frontend/src/lib/services/swarm-service.ts+++ b/frontend/src/lib/services/swarm-service.ts@@ -10,6 +10,8 @@ import type {SwarmInfo,SwarmRuntimeStatus,SwarmNodeAgentDeployment,+ SwarmNodeAgentBindingRequest,+ SwarmNodeAgentReconcileResponse,SwarmServiceCreateRequest,SwarmServiceUpdateRequest,SwarmServiceCreateResponse,@@ -38,7 +40,10 @@ import type {SwarmConfigCreateRequest,SwarmConfigUpdateRequest,SwarmSecretCreateRequest,- SwarmSecretUpdateRequest+ SwarmSecretUpdateRequest,+ SwarmJoinCandidate,+ SwarmJoinEnvironmentsRequest,+ SwarmJoinEnvironmentsResponse} from '$lib/types/swarm';export type SwarmServicesPaginatedResponse = Paginated<SwarmServiceSummary>;@@ -108,6 +113,26 @@ class SwarmService extends BaseAPIService {return this.handleResponse(this.api.post(`/environments/${envId}/swarm/nodes/${nodeId}/agent/deployment`, { rotate }));}+ async reconcileNodeAgents(): Promise<SwarmNodeAgentReconcileResponse> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/nodes/agents/reconcile`, {}));+ }++ async bindNodeAgent(nodeId: string, request: SwarmNodeAgentBindingRequest): Promise<SwarmNodeSummary> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.put(`/environments/${envId}/swarm/nodes/${nodeId}/agent/binding`, request));+ }++ async detachNodeAgent(nodeId: string): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.delete(`/environments/${envId}/swarm/nodes/${nodeId}/agent/binding`));+ }++ async removeNodeAgentDeployment(nodeId: string): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.delete(`/environments/${envId}/swarm/nodes/${nodeId}/agent/deployment`));+ }+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));@@ -213,6 +238,16 @@ class SwarmService extends BaseAPIService {await this.handleResponse(this.api.post(`/environments/${envId}/swarm/join`, request));}+ async getSwarmJoinCandidates(environmentId?: string): Promise<SwarmJoinCandidate[]> {+ const envId = environmentId ?? (await environmentStore.getCurrentEnvironmentId());+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/join-candidates`));+ }++ async joinEnvironments(request: SwarmJoinEnvironmentsRequest, environmentId?: string): Promise<SwarmJoinEnvironmentsResponse> {+ const envId = environmentId ?? (await environmentStore.getCurrentEnvironmentId());+ return this.handleResponse(this.api.post(`/environments/${envId}/swarm/join-environments`, request));+ }+async leaveSwarm(request: SwarmLeaveRequest): Promise<void> {const envId = await environmentStore.getCurrentEnvironmentId();await this.handleResponse(this.api.post(`/environments/${envId}/swarm/leave`, request));diff --git a/frontend/src/lib/types/swarm.ts b/frontend/src/lib/types/swarm.tsindex d5e596601..29b63b4f4 100644--- a/frontend/src/lib/types/swarm.ts+++ b/frontend/src/lib/types/swarm.ts@@ -254,6 +254,7 @@ export interface SwarmNodeSummary {agent: SwarmNodeAgentStatus;address?: string | null;managerStatus?: string | null;+ managerAddress?: string | null;reachability?: string | null;labels?: Record<string, string> | null;systemLabels?: Record<string, string> | null;@@ -263,16 +264,27 @@ export interface SwarmNodeSummary {updatedAt: string;}-export type SwarmNodeAgentState = 'none' | 'pending' | 'offline' | 'connected' | 'mismatched';+export type SwarmNodeAgentState = 'none' | 'pending' | 'offline' | 'connected' | 'mismatched' | 'ambiguous';+export type SwarmNodeAgentBindingKind = 'local' | 'environment' | 'dedicated';++export interface SwarmNodeAgentCandidate {+ environmentId: string;+ environmentName: string;+ environmentType: string;+}export interface SwarmNodeAgentStatus {state: SwarmNodeAgentState;+ bindingKind?: SwarmNodeAgentBindingKind | null;environmentId?: string | null;+ environmentName?: string | null;+ environmentType?: string | null;connected?: boolean | null;lastHeartbeat?: string | null;lastPollAt?: string | null;reportedNodeId?: string | null;reportedHostname?: string | null;+ candidates?: SwarmNodeAgentCandidate[];}export interface SwarmNodeAgentDeployment {@@ -282,6 +294,23 @@ export interface SwarmNodeAgentDeployment {dockerCompose: string;}+export interface SwarmNodeAgentBindingRequest {+ environmentId: string;+ rebind?: boolean;+ replaceDeployment?: boolean;+}++export interface SwarmNodeAgentReconcileResult {+ nodeId: string;+ state: SwarmNodeAgentState;+ environmentId?: string | null;+ candidates?: SwarmNodeAgentCandidate[];+}++export interface SwarmNodeAgentReconcileResponse {+ results: SwarmNodeAgentReconcileResult[];+}+export interface SwarmNodeUpdateRequest {version?: number;name?: string;@@ -382,6 +411,41 @@ export interface SwarmJoinRequest {availability?: 'active' | 'pause' | 'drain';}+export type SwarmJoinEnvironmentRole = 'worker' | 'manager';+export type SwarmJoinEnvironmentResultState = 'joined' | 'already_member' | 'joined_unverified' | 'failed';++export interface SwarmJoinCandidate {+ environmentId: string;+ environmentName: string;+ environmentType: string;+ status: string;+}++export interface SwarmJoinEnvironmentTarget {+ environmentId: string;+ role: SwarmJoinEnvironmentRole;+ availability?: 'active' | 'pause' | 'drain';+ listenAddr?: string;+ advertiseAddr?: string;+ dataPathAddr?: string;+}++export interface SwarmJoinEnvironmentsRequest {+ remoteAddrs: string[];+ targets: SwarmJoinEnvironmentTarget[];+}++export interface SwarmJoinEnvironmentResult {+ environmentId: string;+ state: SwarmJoinEnvironmentResultState;+ nodeId?: string | null;+ error?: string | null;+}++export interface SwarmJoinEnvironmentsResponse {+ results: SwarmJoinEnvironmentResult[];+}+export interface SwarmLeaveRequest {force?: boolean;}diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelteindex 57e03efca..931f5f806 100644--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte@@ -29,6 +29,8 @@import { environmentFormSchema, type EnvironmentFormValues } from './components/environment-form-schema';import TrivySecuritySettings from '$lib/components/settings/trivy-security-settings.svelte';import LifecycleSecuritySettings from '$lib/components/settings/lifecycle-security-settings.svelte';+ import { useEasyJoinCandidates } from '$lib/hooks/use-easy-join-candidates.svelte';+ import EasyJoinDialog from '../../swarm/cluster/easy-join-dialog.svelte';import {ArrowLeftIcon,AlertIcon,@@ -39,7 +41,8 @@SettingsIcon,GitBranchIcon,JobsIcon,- ResetIcon+ ResetIcon,+ ConnectionIcon} from '$lib/icons';let { data } = $props();@@ -60,6 +63,8 @@let isRegeneratingKey = $state(false);let showRegenerateDialog = $state(false);let regeneratedApiKey = $state<string | null>(null);+ let easyJoinDialogOpen = $state(false);+ const easyJoinCandidates = useEasyJoinCandidates();// Version statelet remoteVersion = $state<AppVersionInformation | null>(null);@@ -82,8 +87,23 @@let mtlsBundleDownloadHref = $derived(`/api/environments/${runtimeEnvironment.id}/deployment/mtls/bundle`);let mtlsCertificateDownloadHref = $derived(`/api/environments/${runtimeEnvironment.id}/deployment/mtls/agent.crt`);let mtlsKeyDownloadHref = $derived(`/api/environments/${runtimeEnvironment.id}/deployment/mtls/agent.key`);+ let canEasyJoin = $derived(+ runtimeEnvironment.id !== '0' &&+ runtimeEnvironment.enabled &&+ isCurrentlyOnline &&+ easyJoinCandidates.isCandidate(runtimeEnvironment.id)+ );let headerActions = $derived.by((): ActionButton[] => {const actions: ActionButton[] = [];+ if (canEasyJoin) {+ actions.push({+ id: 'easy-join',+ action: 'create',+ label: m.swarm_easy_join_action(),+ onclick: () => (easyJoinDialogOpen = true),+ icon: ConnectionIcon+ });+ }if (environment.id !== '0') {actions.push({@@ -700,6 +720,13 @@</AlertDialog.Root></div>+<EasyJoinDialog+ bind:open={easyJoinDialogOpen}+ managerEnvironmentId={easyJoinCandidates.managerEnvironmentId ?? undefined}+ targetEnvironmentId={runtimeEnvironment.id}+ onComplete={easyJoinCandidates.refresh}+/>+<MobileFloatingFormActionshasChanges={settingsForm.hasChanges}isLoading={settingsForm.isLoading}diff --git a/frontend/src/routes/(app)/environments/environment-table.svelte b/frontend/src/routes/(app)/environments/environment-table.svelteindex a07bff6aa..76f9b1018 100644--- a/frontend/src/routes/(app)/environments/environment-table.svelte+++ b/frontend/src/routes/(app)/environments/environment-table.svelte@@ -25,7 +25,18 @@import { environmentStore } from '$lib/stores/environment.store.svelte';import { capitalizeFirstLetter } from '$lib/utils/formatting';import { getEnvironmentStatusVariant, isEnvironmentOnline, resolveEnvironmentStatus } from '$lib/utils/docker';- import { EyeOnIcon, TrashIcon, EnvironmentsIcon, InspectIcon, StatsIcon, EyeOffIcon, TestIcon } from '$lib/icons';+ import {+ EyeOnIcon,+ TrashIcon,+ EnvironmentsIcon,+ InspectIcon,+ StatsIcon,+ EyeOffIcon,+ TestIcon,+ ConnectionIcon+ } from '$lib/icons';+ import { useEasyJoinCandidates } from '$lib/hooks/use-easy-join-candidates.svelte';+ import EasyJoinDialog from '../swarm/cluster/easy-join-dialog.svelte';let {environments = $bindable(),@@ -42,6 +53,9 @@let showUpgradeDialog = $state(false);let selectedEnvironmentForUpgrade = $state<Environment | null>(null);let selectedVersionInfoForUpgrade = $state<AppVersionInformation | null>(null);+ let easyJoinDialogOpen = $state(false);+ let easyJoinTarget = $state<Environment | null>(null);+ const easyJoinCandidates = useEasyJoinCandidates();const canInstallUpdates = $derived(hasPermission('environments:update'));@@ -66,6 +80,15 @@return m.environments_edge_grpc_label();}+ function canEasyJoin(item: Environment): boolean {+ return item.id !== '0' && item.enabled && isEnvironmentOnline(item) && easyJoinCandidates.isCandidate(item.id);+ }++ function openEasyJoin(item: Environment) {+ easyJoinTarget = item;+ easyJoinDialogOpen = true;+ }+async function handleDeleteSelected(ids: string[]) {if (!ids?.length) return;@@ -397,6 +420,13 @@{m.common_view_details()}</DropdownMenu.Item>+ {#if canEasyJoin(item)}+ <DropdownMenu.Item onclick={() => openEasyJoin(item)}>+ <ConnectionIcon class="size-4" />+ {m.swarm_easy_join_action()}+ </DropdownMenu.Item>+ {/if}+<DropdownMenu.Item onclick={() => handleTest(item.id)} disabled={isLoading.testing}><TestIcon class="size-4" />{m.environments_test_connection()}@@ -460,3 +490,10 @@environmentId={selectedEnvironmentForUpgrade?.id}bind:upgrading={isLoading.upgrading}/>++<EasyJoinDialog+ bind:open={easyJoinDialogOpen}+ managerEnvironmentId={easyJoinCandidates.managerEnvironmentId ?? undefined}+ targetEnvironmentId={easyJoinTarget?.id}+ onComplete={easyJoinCandidates.refresh}+/>diff --git a/frontend/src/routes/(app)/swarm/cluster/+page.svelte b/frontend/src/routes/(app)/swarm/cluster/+page.svelteindex 78cb2a16c..62d1217dc 100644--- a/frontend/src/routes/(app)/swarm/cluster/+page.svelte+++ b/frontend/src/routes/(app)/swarm/cluster/+page.svelte@@ -24,11 +24,13 @@import { handleApiResultWithCallbacks } from '$lib/utils/api';import { tryCatch } from '$lib/utils/api';import { toast } from 'svelte-sonner';+ import EasyJoinDialog from './easy-join-dialog.svelte';let {}: PageProps = $props();const currentEnvId = $derived(environmentStore.selected?.id);const canManageSwarm = $derived(hasPermission('swarm:nodes', currentEnvId));+ const canEasyJoin = $derived(hasPermission('swarm:nodes', currentEnvId) && hasPermission('swarm:unlock', currentEnvId));let swarmInfo = $state<SwarmInfo | null>(null);let joinTokens = $state<SwarmJoinTokensResponse | null>(null);@@ -36,6 +38,7 @@let showManagerToken = $state(false);let showWorkerToken = $state(false);let securityDialogOpen = $state(false);+ let easyJoinDialogOpen = $state(false);const isSwarmInitialized = $derived(!!swarmInfo?.id);let initForm = $state({@@ -251,6 +254,16 @@}const actionButtons: ActionButton[] = $derived([+ ...(isSwarmInitialized && canEasyJoin+ ? [+ {+ id: 'easy-join',+ action: 'create' as const,+ label: m.swarm_easy_join_action(),+ onclick: () => (easyJoinDialogOpen = true)+ }+ ]+ : []),{id: 'refresh',action: 'restart',@@ -261,26 +274,30 @@}]);- 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'- }- ]);+ const statCards: StatCardConfig[] = $derived(+ isSwarmInitialized+ ? [+ {+ 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@@ -293,231 +310,271 @@>{#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={!canManageSwarm}- />- </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>+ {#if isSwarmInitialized}+ <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={!canManageSwarm}+ />+ </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>- <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>+ </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={!canManageSwarm || !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="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 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>- </div>- </Card.Content>- </Card.Root>+ </Card.Content>+ </Card.Root>+ </div><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>+ <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="restart"+ action="inspect"size="sm"- customLabel={m.swarm_cluster_rotate_tokens()}- onclick={handleRotateTokens}- disabled={!canManageSwarm || !isSwarmInitialized || isLoading.rotateTokens}- loading={isLoading.rotateTokens}+ customLabel={m.swarm_cluster_load_current_spec()}+ onclick={loadCurrentSpec}/></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>+ <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={!canManageSwarm || isLoading.updateSpec}+ loading={isLoading.updateSpec}+ /></div></Card.Content></Card.Root>- </div>+ {:else}+ <div class="mx-auto w-full max-w-5xl space-y-5 pt-2">+ <div class="border-border/60 bg-muted/20 rounded-xl border px-5 py-4 sm:px-6">+ <p class="font-medium">{m.swarm_cluster_setup_title()}</p>+ <p class="text-muted-foreground mt-1 max-w-3xl text-sm leading-relaxed">+ {m.swarm_cluster_setup_description()}+ </p>+ </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()}+ <div class="grid items-stretch gap-5 lg:grid-cols-2">+ <Card.Root class="flex h-full flex-col" variant="outlined">+ <Card.Header icon={SettingsIcon} iconVariant="primary">+ <div class="min-w-0">+ <Card.Title>{m.swarm_cluster_initialize_title()}</Card.Title>+ <Card.Description class="mt-1">{m.swarm_cluster_initialize_description()}</Card.Description>+ </div>+ </Card.Header>+ <Card.Content class="flex flex-1 flex-col gap-5 pb-6">+ <p class="text-muted-foreground text-sm leading-relaxed">{m.swarm_cluster_initialize_hint()}</p>++ <details class="border-border/60 bg-muted/15 rounded-lg border">+ <summary class="cursor-pointer px-4 py-3 text-sm font-medium select-none">+ {m.swarm_cluster_advanced_settings()}+ </summary>+ <div class="space-y-4 border-t px-4 py-4">+ <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={5}+ placeholder={m.swarm_cluster_spec_placeholder()}+ bind:value={initForm.spec}+ class="font-mono text-xs"+ />+ <div class="grid gap-3 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>+ </div>+ </details>++ <div class="mt-auto border-t pt-5">+ <ArcaneButton+ action="create"+ customLabel={m.swarm_cluster_initialize_action()}+ onclick={handleInit}+ disabled={!canManageSwarm || isLoading.init}+ loading={isLoading.init}+ />+ </div>+ </Card.Content>+ </Card.Root>++ <Card.Root class="flex h-full flex-col" variant="outlined">+ <Card.Header icon={UsersIcon} iconVariant="emerald">+ <div class="min-w-0">+ <Card.Title>{m.swarm_cluster_join_title()}</Card.Title>+ <Card.Description class="mt-1">{m.swarm_cluster_join_description()}</Card.Description>+ </div>+ </Card.Header>+ <Card.Content class="flex flex-1 flex-col gap-4 pb-6">+ <label class="space-y-2">+ <span class="text-sm font-medium">{m.swarm_cluster_manager_addresses_label()}</span>+ <Input placeholder={m.swarm_cluster_join_remote_addrs_placeholder()} bind:value={joinForm.remoteAddrs} /></label>- <label class="flex items-center gap-2 text-sm">- <input type="checkbox" bind:checked={initForm.forceNewCluster} />- {m.swarm_cluster_force_new_cluster()}+ <label class="space-y-2">+ <span class="text-sm font-medium">{m.swarm_cluster_join_token_placeholder()}</span>+ <Input+ placeholder={m.swarm_cluster_join_token_placeholder()}+ bind:value={joinForm.joinToken}+ class="font-mono text-xs"+ /></label>- </div>- <ArcaneButton- action="create"- customLabel={m.swarm_cluster_initialize_action()}- onclick={handleInit}- disabled={!canManageSwarm || 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={!canManageSwarm || isLoading.join}- loading={isLoading.join}- />- </Card.Content>- </Card.Root>+ <details class="border-border/60 bg-muted/15 rounded-lg border">+ <summary class="cursor-pointer px-4 py-3 text-sm font-medium select-none">+ {m.swarm_cluster_advanced_settings()}+ </summary>+ <div class="grid gap-3 border-t px-4 py-4 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>+ </details>++ <div class="mt-auto border-t pt-5">+ <ArcaneButton+ action="create"+ customLabel={m.swarm_cluster_join_action()}+ onclick={handleJoin}+ disabled={!canManageSwarm || isLoading.join}+ loading={isLoading.join}+ />+ </div>+ </Card.Content>+ </Card.Root>+ </div></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={!canManageSwarm || isLoading.updateSpec}- loading={isLoading.updateSpec}- />- </div>- </Card.Content>- </Card.Root></div><ResponsiveDialog@@ -565,5 +622,7 @@</div>{/snippet}</ResponsiveDialog>++ <EasyJoinDialog bind:open={easyJoinDialogOpen} onComplete={refresh} />{/snippet}</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/swarm/cluster/easy-join-dialog.svelte b/frontend/src/routes/(app)/swarm/cluster/easy-join-dialog.sveltenew file mode 100644index 000000000..113c7acfb--- /dev/null+++ b/frontend/src/routes/(app)/swarm/cluster/easy-join-dialog.svelte@@ -0,0 +1,238 @@+<script lang="ts">+ import { ArcaneButton } from '$lib/components/arcane-button';+ import * as Alert from '$lib/components/ui/alert';+ import { Input } from '$lib/components/ui/input';+ import { ResponsiveDialog } from '$lib/components/ui/responsive-dialog';+ import { Spinner } from '$lib/components/ui/spinner';+ import { m } from '$lib/paraglide/messages';+ import { swarmService } from '$lib/services/swarm-service';+ import type { SwarmJoinCandidate, SwarmJoinEnvironmentResult, SwarmJoinEnvironmentTarget } from '$lib/types/swarm';+ import { extractApiErrorMessage } from '$lib/utils/api';++ type Props = {+ open: boolean;+ managerEnvironmentId?: string;+ targetEnvironmentId?: string;+ onComplete?: () => void | Promise<void>;+ };++ let { open = $bindable(false), managerEnvironmentId, targetEnvironmentId, onComplete }: Props = $props();+ let candidates = $state<SwarmJoinCandidate[]>([]);+ let targets = $state<Record<string, SwarmJoinEnvironmentTarget>>({});+ let results = $state<SwarmJoinEnvironmentResult[]>([]);+ let errorMessage = $state('');+ let isLoading = $state(false);+ let loaded = $state(false);++ $effect(() => {+ if (!open) {+ loaded = false;+ return;+ }+ if (loaded) return;+ loaded = true;+ void loadCandidates();+ });++ async function loadCandidates() {+ isLoading = true;+ errorMessage = '';+ candidates = [];+ targets = {};+ results = [];+ try {+ const candidateData = await swarmService.getSwarmJoinCandidates(managerEnvironmentId);+ candidates = targetEnvironmentId+ ? candidateData.filter((candidate) => candidate.environmentId === targetEnvironmentId)+ : candidateData;+ if (targetEnvironmentId && candidates[0]) toggleCandidate(candidates[0], true);+ } catch (error) {+ errorMessage = extractApiErrorMessage(error);+ } finally {+ isLoading = false;+ }+ }++ function toggleCandidate(candidate: SwarmJoinCandidate, selected: boolean) {+ if (selected) {+ targets = {+ ...targets,+ [candidate.environmentId]: {+ environmentId: candidate.environmentId,+ role: 'worker',+ availability: 'active'+ }+ };+ return;+ }+ const next = { ...targets };+ delete next[candidate.environmentId];+ targets = next;+ }++ function updateTarget(environmentId: string, update: Partial<SwarmJoinEnvironmentTarget>) {+ const current = targets[environmentId];+ if (!current) return;+ targets = { ...targets, [environmentId]: { ...current, ...update } };+ }++ async function joinSelected() {+ const selectedTargets = Object.values(targets);+ if (selectedTargets.length === 0) {+ errorMessage = m.swarm_easy_join_targets_required();+ return;+ }+ isLoading = true;+ errorMessage = '';+ results = [];+ try {+ const response = await swarmService.joinEnvironments({ remoteAddrs: [], targets: selectedTargets }, managerEnvironmentId);+ results = response.results;+ await onComplete?.();+ } catch (error) {+ errorMessage = extractApiErrorMessage(error);+ } finally {+ isLoading = false;+ }+ }++ function resultLabel(result: SwarmJoinEnvironmentResult): string {+ switch (result.state) {+ case 'joined':+ return m.swarm_easy_join_result_joined();+ case 'already_member':+ return m.swarm_easy_join_result_already_member();+ case 'joined_unverified':+ return m.swarm_easy_join_result_joined_unverified();+ case 'failed':+ default:+ return m.swarm_easy_join_result_failed();+ }+ }+</script>++<ResponsiveDialog+ bind:open+ title={m.swarm_easy_join_title()}+ description={m.swarm_easy_join_description()}+ contentClass="sm:max-w-3xl"+>+ {#snippet children()}+ <div class="space-y-5 py-4">+ {#if errorMessage}+ <Alert.Root variant="destructive">+ <Alert.Title>{m.common_action_failed()}</Alert.Title>+ <Alert.Description>{errorMessage}</Alert.Description>+ </Alert.Root>+ {/if}++ {#if isLoading && candidates.length === 0}+ <div class="flex justify-center py-10"><Spinner class="size-6" /></div>+ {:else if candidates.length === 0}+ <div class="text-muted-foreground rounded-lg border border-dashed p-6 text-center text-sm">+ {m.swarm_easy_join_no_candidates()}+ </div>+ {:else}+ <div class="space-y-3">+ {#each candidates as candidate (candidate.environmentId)}+ {@const target = targets[candidate.environmentId]}+ <div class="rounded-lg border p-4">+ <label class="flex items-start gap-3">+ <input+ type="checkbox"+ checked={!!target}+ onchange={(event) => toggleCandidate(candidate, event.currentTarget.checked)}+ />+ <span>+ <span class="block text-sm font-medium">{candidate.environmentName}</span>+ <span class="text-muted-foreground text-xs">{candidate.environmentType} · {candidate.status}</span>+ </span>+ </label>++ {#if target}+ <div class="mt-4 space-y-3 border-t pt-4">+ <div class="grid gap-3 sm:grid-cols-2">+ <label class="space-y-1 text-xs">+ <span class="text-muted-foreground">{m.common_role()}</span>+ <select+ class="border-input bg-background h-9 w-full rounded-md border px-3"+ value={target.role}+ onchange={(event) =>+ updateTarget(candidate.environmentId, {+ role: event.currentTarget.value as 'worker' | 'manager'+ })}+ >+ <option value="worker">{m.swarm_easy_join_role_worker()}</option>+ <option value="manager">{m.swarm_easy_join_role_manager()}</option>+ </select>+ </label>+ <label class="space-y-1 text-xs">+ <span class="text-muted-foreground">{m.swarm_availability()}</span>+ <select+ class="border-input bg-background h-9 w-full rounded-md border px-3"+ value={target.availability}+ onchange={(event) =>+ updateTarget(candidate.environmentId, {+ availability: event.currentTarget.value as 'active' | 'pause' | 'drain'+ })}+ >+ <option value="active">{m.swarm_easy_join_availability_active()}</option>+ <option value="pause">{m.swarm_easy_join_availability_pause()}</option>+ <option value="drain">{m.swarm_easy_join_availability_drain()}</option>+ </select>+ </label>+ </div>+ <div class="grid gap-3 sm:grid-cols-3">+ <Input+ placeholder={m.swarm_cluster_listen_addr_placeholder()}+ value={target.listenAddr ?? ''}+ oninput={(event) => updateTarget(candidate.environmentId, { listenAddr: event.currentTarget.value })}+ />+ <Input+ placeholder={m.swarm_cluster_advertise_addr_placeholder()}+ value={target.advertiseAddr ?? ''}+ oninput={(event) => updateTarget(candidate.environmentId, { advertiseAddr: event.currentTarget.value })}+ />+ <Input+ placeholder={m.swarm_easy_join_data_path_placeholder()}+ value={target.dataPathAddr ?? ''}+ oninput={(event) => updateTarget(candidate.environmentId, { dataPathAddr: event.currentTarget.value })}+ />+ </div>+ </div>+ {/if}+ </div>+ {/each}+ </div>+ {/if}++ {#if results.length > 0}+ <div class="space-y-2 rounded-lg border p-4">+ <div class="font-medium">{m.swarm_easy_join_results_title()}</div>+ {#each results as result (result.environmentId)}+ <div class="flex items-start justify-between gap-4 text-sm">+ <span+ >{candidates.find((candidate) => candidate.environmentId === result.environmentId)?.environmentName ??+ result.environmentId}</span+ >+ <span class={result.state === 'failed' ? 'text-destructive text-right' : 'text-muted-foreground text-right'}>+ {resultLabel(result)}{result.error ? `: ${result.error}` : ''}+ </span>+ </div>+ {/each}+ </div>+ {/if}++ <div class="flex justify-end gap-2 border-t pt-4">+ <ArcaneButton action="base" tone="outline" customLabel={m.common_cancel()} onclick={() => (open = false)} />+ <ArcaneButton+ action="create"+ customLabel={m.swarm_easy_join_action()}+ onclick={joinSelected}+ loading={isLoading}+ disabled={isLoading || Object.keys(targets).length === 0}+ />+ </div>+ </div>+ {/snippet}+</ResponsiveDialog>diff --git a/frontend/src/routes/(app)/swarm/nodes/+page.svelte b/frontend/src/routes/(app)/swarm/nodes/+page.svelteindex c1f951c89..6732f4648 100644--- a/frontend/src/routes/(app)/swarm/nodes/+page.svelte+++ b/frontend/src/routes/(app)/swarm/nodes/+page.svelte@@ -8,12 +8,17 @@import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';import { parallelRefresh } from '$lib/utils/api';import SwarmNodesTable from './nodes-table.svelte';+ import { hasPermission } from '$lib/utils/auth';+ import { environmentStore } from '$lib/stores/environment.store.svelte';let { data } = $props();let nodes = $state(untrack(() => data.nodes));let requestOptions = $state(untrack(() => data.requestOptions));let isLoading = $state({ refresh: false });+ let reconciledEnvironmentId = $state<string | null>(null);+ const currentEnvironmentId = $derived(environmentStore.selected?.id ?? null);+ const canManageNodes = $derived(hasPermission('swarm:nodes', currentEnvironmentId ?? undefined));async function refresh() {await parallelRefresh(@@ -32,8 +37,20 @@useEnvironmentRefresh(refresh);+ $effect(() => {+ const environmentId = currentEnvironmentId;+ if (!environmentId || !canManageNodes || reconciledEnvironmentId === environmentId) return;+ reconciledEnvironmentId = environmentId;+ void swarmService+ .reconcileNodeAgents()+ .then(refresh)+ .catch(() => undefined);+ });+const totalNodes = $derived(nodes?.pagination?.totalItems ?? nodes?.data?.length ?? 0);- const uncoveredNodes = $derived((nodes?.data ?? []).filter((node) => node.agent?.state !== 'connected'));+ const uncoveredNodes = $derived(+ (nodes?.data ?? []).filter((node) => node.agent?.state !== 'connected' || node.agent?.connected === false)+ );const uncoveredNodeCount = $derived(uncoveredNodes.length);const actionButtons: ActionButton[] = $derived([diff --git a/frontend/src/routes/(app)/swarm/nodes/agent-status.ts b/frontend/src/routes/(app)/swarm/nodes/agent-status.tsindex 79fcf9cb2..c310adaec 100644--- a/frontend/src/routes/(app)/swarm/nodes/agent-status.ts+++ b/frontend/src/routes/(app)/swarm/nodes/agent-status.ts@@ -11,6 +11,8 @@ export function getSwarmNodeAgentLabel(state: SwarmNodeAgentState | null | undefreturn m.swarm_node_agent_status_connected();case 'mismatched':return m.swarm_node_agent_status_mismatched();+ case 'ambiguous':+ return m.swarm_node_agent_status_ambiguous();case 'none':default:return m.swarm_node_agent_status_none();@@ -25,6 +27,7 @@ export function getSwarmNodeAgentVariant(state: SwarmNodeAgentState | null | undreturn 'red';case 'pending':case 'mismatched':+ case 'ambiguous':return 'amber';case 'none':default:diff --git a/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte b/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelteindex 222d8813a..5ddfbd96f 100644--- a/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte+++ b/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte@@ -94,7 +94,74 @@agentDeployment = null;agentDeploymentError = '';isAgentDialogOpen = true;- void loadAgentDeployment(node).catch(() => undefined);+ }++ function provisionNodeEnvironment() {+ if (!selectedNode) return;+ void loadAgentDeployment(selectedNode).catch(() => undefined);+ }++ async function attachEnvironment(environmentId: string) {+ const node = selectedNode;+ if (!node) return;+ const replaceDeployment = node.agent.bindingKind === 'dedicated';+ const attach = async () => {+ isAgentDeploymentLoading = true;+ try {+ await swarmService.bindNodeAgent(node.id, { environmentId, rebind: true, replaceDeployment });+ toast.success(m.swarm_node_agent_attach_success());+ await refreshNodes();+ } catch (error) {+ agentDeploymentError = extractApiErrorMessage(error);+ } finally {+ isAgentDeploymentLoading = false;+ }+ };++ if (!replaceDeployment) {+ await attach();+ return;+ }+ openConfirmDialog({+ title: m.swarm_node_agent_replace_title(),+ message: m.swarm_node_agent_replace_description(),+ confirm: { label: m.swarm_node_agent_replace_action(), destructive: true, action: attach }+ });+ }++ function detachEnvironment() {+ const node = selectedNode;+ if (!node) return;+ openConfirmDialog({+ title: m.swarm_node_agent_detach_title(),+ message: m.swarm_node_agent_detach_description(),+ confirm: {+ label: m.swarm_node_agent_detach_action(),+ destructive: true,+ action: async () => {+ await swarmService.detachNodeAgent(node.id);+ await refreshNodes();+ }+ }+ });+ }++ function removeDedicatedDeployment() {+ const node = selectedNode;+ if (!node) return;+ openConfirmDialog({+ title: m.swarm_node_agent_remove_deployment_title(),+ message: m.swarm_node_agent_remove_deployment_description(),+ confirm: {+ label: m.common_remove(),+ destructive: true,+ action: async () => {+ await swarmService.removeNodeAgentDeployment(node.id);+ agentDeployment = null;+ await refreshNodes();+ }+ }+ });}function refreshAgentDeployment() {@@ -418,6 +485,10 @@isLoading={isAgentDeploymentLoading}onRefresh={refreshAgentDeployment}onRegenerate={regenerateAgentDeployment}+ onProvision={provisionNodeEnvironment}+ onAttach={attachEnvironment}+ onDetach={detachEnvironment}+ onRemoveDeployment={removeDedicatedDeployment}/><SwarmNodeLabelDialog bind:open={isAddLabelDialogOpen} onAdd={addLabel} />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.svelteindex 4e6eec9cc..36576be2a 100644--- a/frontend/src/routes/(app)/swarm/nodes/swarm-node-agent-dialog.svelte+++ b/frontend/src/routes/(app)/swarm/nodes/swarm-node-agent-dialog.svelte@@ -9,6 +9,9 @@import { m } from '$lib/paraglide/messages';import type { SwarmNodeAgentDeployment, SwarmNodeSummary } from '$lib/types/swarm';import { getSwarmNodeAgentLabel, getSwarmNodeAgentVariant } from './agent-status';+ import { environmentStore } from '$lib/stores/environment.store.svelte';+ import { hasAnyPermission } from '$lib/utils/auth';+ import { goto } from '$app/navigation';type SwarmNodeAgentDialogProps = {open: boolean;@@ -18,6 +21,10 @@isLoading?: boolean;onRefresh?: () => void | Promise<void>;onRegenerate?: () => void | Promise<void>;+ onProvision?: () => void | Promise<void>;+ onAttach?: (environmentId: string) => void | Promise<void>;+ onDetach?: () => void | Promise<void>;+ onRemoveDeployment?: () => void | Promise<void>;};let {@@ -27,12 +34,42 @@errorMessage = '',isLoading = false,onRefresh,- onRegenerate+ onRegenerate,+ onProvision,+ onAttach,+ onDetach,+ onRemoveDeployment}: SwarmNodeAgentDialogProps = $props();const agentStatus = $derived(deployment?.agent ?? node?.agent ?? { state: 'none' as const });const agentStatusLabel = $derived(getSwarmNodeAgentLabel(agentStatus.state));const isReady = $derived(!!deployment && !isLoading);+ const isVisibleEnvironment = $derived(agentStatus.bindingKind === 'environment' && !!agentStatus.environmentId);+ const isDedicated = $derived(agentStatus.bindingKind === 'dedicated');+ const canCreateEnvironment = $derived(!agentStatus.bindingKind && !agentStatus.candidates?.length);+ const canShowDeployment = $derived(isVisibleEnvironment || isDedicated);+ const bindingLabel = $derived.by(() => {+ switch (agentStatus.bindingKind) {+ case 'local':+ return m.swarm_node_agent_binding_local();+ case 'environment':+ return m.swarm_node_agent_binding_environment();+ case 'dedicated':+ return m.swarm_node_agent_binding_dedicated();+ default:+ return m.swarm_node_agent_binding_none();+ }+ });++ async function navigateToResource(path: string, permissions: string[]) {+ const environmentId = agentStatus.environmentId;+ if (!environmentId || !hasAnyPermission(permissions, environmentId)) return;+ const environment = environmentStore.available.find((candidate) => candidate.id === environmentId);+ if (!environment) return;+ await environmentStore.setEnvironment(environment);+ await goto(path);+ open = false;+ }</script><ResponsiveDialog.Root@@ -49,7 +86,14 @@<Alert.Description>{m.swarm_node_agent_dialog_blurb_description()}</Alert.Description></Alert.Root>- <div class="grid gap-3 sm:grid-cols-2">+ <div class="grid gap-3 sm:grid-cols-3">+ <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_binding_kind()}+ </div>+ <div class="mt-2 text-sm font-medium">{bindingLabel}</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.common_status()}</div><div class="mt-2 flex items-center gap-2">@@ -61,10 +105,81 @@<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 class="mt-2 font-mono text-sm break-all">+ {agentStatus.environmentName ?? deployment?.environmentId ?? agentStatus.environmentId ?? m.common_na()}+ </div></div></div>+ {#if agentStatus.candidates?.length}+ <div class="space-y-3 rounded-lg border p-4">+ <div>+ <div class="font-medium">{m.swarm_node_agent_candidates_title()}</div>+ <div class="text-muted-foreground text-sm">{m.swarm_node_agent_candidates_description()}</div>+ </div>+ <div class="space-y-2">+ {#each agentStatus.candidates as candidate (candidate.environmentId)}+ <div class="bg-muted/30 flex items-center justify-between gap-3 rounded-md border px-3 py-2">+ <div>+ <div class="text-sm font-medium">{candidate.environmentName}</div>+ <div class="text-muted-foreground text-xs">{candidate.environmentType}</div>+ </div>+ <ArcaneButton+ action="save"+ size="sm"+ customLabel={m.swarm_node_agent_attach_action()}+ onclick={() => onAttach?.(candidate.environmentId)}+ disabled={isLoading}+ />+ </div>+ {/each}+ </div>+ </div>+ {/if}++ {#if isVisibleEnvironment && agentStatus.environmentId}+ <div class="space-y-3 rounded-lg border p-4">+ <div>+ <div class="font-medium">{m.swarm_node_agent_resources_title()}</div>+ <div class="text-muted-foreground text-sm">{m.swarm_node_agent_resources_description()}</div>+ </div>+ <div class="flex flex-wrap gap-2">+ {#if hasAnyPermission(['containers:list', 'containers:read'], agentStatus.environmentId)}+ <ArcaneButton+ action="base"+ tone="outline"+ customLabel={m.containers_title()}+ onclick={() => navigateToResource('/containers', ['containers:list', 'containers:read'])}+ />+ {/if}+ {#if hasAnyPermission(['images:list', 'images:read'], agentStatus.environmentId)}+ <ArcaneButton+ action="base"+ tone="outline"+ customLabel={m.images_title()}+ onclick={() => navigateToResource('/images', ['images:list', 'images:read'])}+ />+ {/if}+ {#if hasAnyPermission(['volumes:list', 'volumes:read'], agentStatus.environmentId)}+ <ArcaneButton+ action="base"+ tone="outline"+ customLabel={m.volumes_title()}+ onclick={() => navigateToResource('/volumes', ['volumes:list', 'volumes:read'])}+ />+ {/if}+ {#if hasAnyPermission(['networks:list', 'networks:read'], agentStatus.environmentId)}+ <ArcaneButton+ action="base"+ tone="outline"+ customLabel={m.networks_title()}+ onclick={() => navigateToResource('/networks', ['networks:list', 'networks:read'])}+ />+ {/if}+ </div>+ </div>+ {/if}+{#if errorMessage}<Alert.Root variant="destructive"><AlertTriangleIcon class="size-4" />@@ -87,26 +202,67 @@preClass="pr-12"/></div>+ {:else if canCreateEnvironment}+ <div class="rounded-lg border border-dashed p-4">+ <div class="font-medium">{m.swarm_node_agent_create_environment_title()}</div>+ <div class="text-muted-foreground mt-1 text-sm">{m.swarm_node_agent_create_environment_description()}</div>+ <ArcaneButton+ class="mt-3"+ action="create"+ customLabel={m.swarm_node_agent_create_environment_action()}+ onclick={onProvision}+ disabled={isLoading}+ />+ </div>+ {:else if canShowDeployment}+ <div class="rounded-lg border border-dashed p-4">+ <div class="font-medium">+ {isDedicated ? m.swarm_node_agent_legacy_deployment_title() : m.swarm_node_agent_deployment_title()}+ </div>+ <div class="text-muted-foreground mt-1 text-sm">+ {isDedicated ? m.swarm_node_agent_legacy_deployment_description() : m.swarm_node_agent_deployment_description()}+ </div>+ <ArcaneButton+ class="mt-3"+ action="inspect"+ customLabel={m.swarm_node_agent_show_deployment()}+ onclick={onProvision}+ disabled={isLoading}+ />+ </div>{/if}</div>{#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}- />+ {#if deployment}+ <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}+ />+ {/if}+ {#if isVisibleEnvironment}+ <ArcaneButton action="remove" customLabel={m.swarm_node_agent_detach_action()} onclick={onDetach} disabled={isLoading} />+ {/if}+ {#if isDedicated}+ <ArcaneButton+ action="remove"+ customLabel={m.swarm_node_agent_remove_deployment_action()}+ onclick={onRemoveDeployment}+ disabled={isLoading}+ />+ {/if}<ArcaneButton action="base" customLabel={m.common_done()} onclick={() => (open = false)} /></div>{/snippet}diff --git a/tests/spec/swarm-ui.spec.ts b/tests/spec/swarm-ui.spec.tsindex 53f5d82fd..28e10b04d 100644--- a/tests/spec/swarm-ui.spec.ts+++ b/tests/spec/swarm-ui.spec.ts@@ -48,6 +48,32 @@ test.describe('Swarm UI', () => {} else {await expect(initializeCard).toBeVisible();await expect(page.getByText('Join Existing Cluster')).toBeVisible();+ await expect(page.getByText('Choose how to set up this engine')).toBeVisible();+ await expect(+ page.locator('[data-slot="card-title"]').filter({ hasText: 'Cluster Status' })+ ).toHaveCount(0);+ await expect(+ page.locator('[data-slot="card-title"]').filter({ hasText: 'Join Tokens' })+ ).toHaveCount(0);+ await expect(+ page.locator('[data-slot="card-title"]').filter({ hasText: 'Update Swarm Spec' })+ ).toHaveCount(0);++ const initializeRoot = initializeCard.locator('xpath=ancestor::*[@data-slot="card"]');+ const joinRoot = page+ .locator('[data-slot="card-title"]')+ .filter({ hasText: 'Join Existing Cluster' })+ .locator('xpath=ancestor::*[@data-slot="card"]');+ const [initializeBox, joinBox] = await Promise.all([+ initializeRoot.boundingBox(),+ joinRoot.boundingBox()+ ]);+ expect(initializeBox?.y).toBe(joinBox?.y);+ expect(initializeBox?.height).toBe(joinBox?.height);++ await expect(page.getByPlaceholder('Remote manager addrs (comma separated)')).toBeVisible();+ await expect(page.getByPlaceholder('Listen address (optional)').first()).toBeHidden();+ await page.getByText('Advanced settings').first().click();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();diff --git a/types/go.sum b/types/go.sumindex 3360c21b7..14f0b959b 100644--- a/types/go.sum+++ b/types/go.sum@@ -45,8 +45,6 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=-github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=-github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=github.com/xhit/go-str2duration/v2 v2.1.0 h1:lxklc02Drh6ynqX+DdPyp5pCKLUQpRT8bp8Ydu2Bstc=github.com/xhit/go-str2duration/v2 v2.1.0/go.mod h1:ohY8p+0f07DiV6Em5LKB0s2YpLtXVyJfNt1+BlmyAsU=go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=diff --git a/types/swarm/lifecycle.go b/types/swarm/lifecycle.goindex 7cad4dc52..efedd7a91 100644--- a/types/swarm/lifecycle.go+++ b/types/swarm/lifecycle.go@@ -61,3 +61,70 @@ type SwarmUpdateRequest struct {RotateManagerToken bool `json:"rotateManagerToken,omitempty"`RotateManagerUnlockKey bool `json:"rotateManagerUnlockKey,omitempty"`}++type NodeAgentReconcileRequest struct{}++type NodeAgentReconcileResult struct {+ NodeID string `json:"nodeId"`+ State NodeAgentState `json:"state"`+ EnvironmentID *string `json:"environmentId,omitempty"`+ Candidates []NodeAgentCandidate `json:"candidates,omitempty"`+}++type NodeAgentReconcileResponse struct {+ Results []NodeAgentReconcileResult `json:"results"`+}++type NodeAgentBindingRequest struct {+ EnvironmentID string `json:"environmentId"`+ Rebind bool `json:"rebind,omitempty"`+ ReplaceDeployment bool `json:"replaceDeployment,omitempty"`+}++type SwarmJoinEnvironmentRole string++const (+ SwarmJoinEnvironmentRoleWorker SwarmJoinEnvironmentRole = "worker"+ SwarmJoinEnvironmentRoleManager SwarmJoinEnvironmentRole = "manager"+)++type SwarmJoinEnvironmentResultState string++const (+ SwarmJoinEnvironmentResultJoined SwarmJoinEnvironmentResultState = "joined"+ SwarmJoinEnvironmentResultAlreadyMember SwarmJoinEnvironmentResultState = "already_member"+ SwarmJoinEnvironmentResultJoinedUnverified SwarmJoinEnvironmentResultState = "joined_unverified"+ SwarmJoinEnvironmentResultFailed SwarmJoinEnvironmentResultState = "failed"+)++type SwarmJoinCandidate struct {+ EnvironmentID string `json:"environmentId"`+ EnvironmentName string `json:"environmentName"`+ EnvironmentType string `json:"environmentType"`+ Status string `json:"status"`+}++type SwarmJoinEnvironmentTarget struct {+ EnvironmentID string `json:"environmentId"`+ Role SwarmJoinEnvironmentRole `json:"role"`+ Availability swarm.NodeAvailability `json:"availability,omitempty"`+ ListenAddr string `json:"listenAddr,omitempty"`+ AdvertiseAddr string `json:"advertiseAddr,omitempty"`+ DataPathAddr string `json:"dataPathAddr,omitempty"`+}++type SwarmJoinEnvironmentsRequest struct {+ RemoteAddrs []string `json:"remoteAddrs"`+ Targets []SwarmJoinEnvironmentTarget `json:"targets"`+}++type SwarmJoinEnvironmentResult struct {+ EnvironmentID string `json:"environmentId"`+ State SwarmJoinEnvironmentResultState `json:"state"`+ NodeID *string `json:"nodeId,omitempty"`+ Error *string `json:"error,omitempty"`+}++type SwarmJoinEnvironmentsResponse struct {+ Results []SwarmJoinEnvironmentResult `json:"results"`+}diff --git a/types/swarm/node.go b/types/swarm/node.goindex 286219cb4..c5a100965 100644--- a/types/swarm/node.go+++ b/types/swarm/node.go@@ -9,22 +9,39 @@ import (type NodeAgentState string+type NodeAgentBindingKind string+const (NodeAgentStateNone NodeAgentState = "none"NodeAgentStatePending NodeAgentState = "pending"NodeAgentStateOffline NodeAgentState = "offline"NodeAgentStateConnected NodeAgentState = "connected"NodeAgentStateMismatched NodeAgentState = "mismatched"+ NodeAgentStateAmbiguous NodeAgentState = "ambiguous"++ NodeAgentBindingKindLocal NodeAgentBindingKind = "local"+ NodeAgentBindingKindEnvironment NodeAgentBindingKind = "environment"+ NodeAgentBindingKindDedicated NodeAgentBindingKind = "dedicated")+type NodeAgentCandidate struct {+ EnvironmentID string `json:"environmentId"`+ EnvironmentName string `json:"environmentName"`+ EnvironmentType string `json:"environmentType"`+}+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"`+ State NodeAgentState `json:"state"`+ BindingKind *NodeAgentBindingKind `json:"bindingKind,omitempty"`+ EnvironmentID *string `json:"environmentId,omitempty"`+ EnvironmentName *string `json:"environmentName,omitempty"`+ EnvironmentType *string `json:"environmentType,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"`+ Candidates []NodeAgentCandidate `json:"candidates,omitempty"`}type NodeSummary struct {@@ -63,6 +80,11 @@ type NodeSummary struct {// Required: falseManagerStatus string `json:"managerStatus,omitempty"`+ // ManagerAddress is the manager's reachable swarm control-plane address.+ //+ // Required: false+ ManagerAddress string `json:"managerAddress,omitempty"`+// Reachability is the manager reachability if applicable.//// Required: false@@ -142,6 +164,7 @@ type NodeUpdateRequest struct {// Returns a NodeSummary populated from node.func NewNodeSummary(node swarm.Node) NodeSummary {managerStatus := ""+ managerAddress := ""reachability := ""if node.ManagerStatus != nil {if node.ManagerStatus.Leader {@@ -150,6 +173,7 @@ func NewNodeSummary(node swarm.Node) NodeSummary {managerStatus = "manager"}reachability = string(node.ManagerStatus.Reachability)+ managerAddress = node.ManagerStatus.Addr}platform := ""@@ -158,20 +182,21 @@ func NewNodeSummary(node swarm.Node) NodeSummary {}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,- SystemLabels: node.Description.Engine.Labels,- EngineVersion: node.Description.Engine.EngineVersion,- Platform: platform,- CreatedAt: node.CreatedAt,- UpdatedAt: node.UpdatedAt,+ 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,+ ManagerAddress: managerAddress,+ Reachability: reachability,+ Labels: node.Spec.Labels,+ SystemLabels: node.Description.Engine.Labels,+ EngineVersion: node.Description.Engine.EngineVersion,+ Platform: platform,+ CreatedAt: node.CreatedAt,+ UpdatedAt: node.UpdatedAt,Agent: NodeAgentStatus{State: NodeAgentStateNone,},diff --git a/types/swarm/node_test.go b/types/swarm/node_test.gonew file mode 100644index 000000000..b32eb9d30--- /dev/null+++ b/types/swarm/node_test.go@@ -0,0 +1,64 @@+package swarm++import (+ "encoding/json"+ "reflect"+ "strings"+ "testing"+)++func TestNodeAgentStatusLegacyJSONCompatibility(t *testing.T) {+ var status NodeAgentStatus+ if err := json.Unmarshal([]byte(`{"state":"connected","environmentId":"env-1","connected":true}`), &status); err != nil {+ t.Fatalf("unmarshal legacy status: %v", err)+ }+ if status.State != NodeAgentStateConnected {+ t.Fatalf("state = %q, want %q", status.State, NodeAgentStateConnected)+ }+ if status.EnvironmentID == nil || *status.EnvironmentID != "env-1" {+ t.Fatalf("environmentId = %v, want env-1", status.EnvironmentID)+ }+ if status.BindingKind != nil {+ t.Fatalf("bindingKind = %v, want nil", *status.BindingKind)+ }+ if len(status.Candidates) != 0 {+ t.Fatalf("candidates = %v, want empty", status.Candidates)+ }+}++func TestNodeAgentStatusAmbiguousJSON(t *testing.T) {+ status := NodeAgentStatus{+ State: NodeAgentStateAmbiguous,+ Candidates: []NodeAgentCandidate{{+ EnvironmentID: "env-1",+ EnvironmentName: "worker-1",+ EnvironmentType: "edge",+ }},+ }++ encoded, err := json.Marshal(status)+ if err != nil {+ t.Fatalf("marshal ambiguous status: %v", err)+ }+ var actual, expected any+ if err := json.Unmarshal(encoded, &actual); err != nil {+ t.Fatalf("unmarshal actual JSON: %v", err)+ }+ if err := json.Unmarshal([]byte(`{"state":"ambiguous","candidates":[{"environmentId":"env-1","environmentName":"worker-1","environmentType":"edge"}]}`), &expected); err != nil {+ t.Fatalf("unmarshal expected JSON: %v", err)+ }+ if !reflect.DeepEqual(actual, expected) {+ t.Fatalf("JSON = %s, want ambiguous candidate payload", encoded)+ }+}++func TestSwarmJoinEnvironmentResultDoesNotExposeToken(t *testing.T) {+ result := SwarmJoinEnvironmentResult{EnvironmentID: "env-1", State: SwarmJoinEnvironmentResultJoined}+ encoded, err := json.Marshal(result)+ if err != nil {+ t.Fatalf("marshal join result: %v", err)+ }+ if string(encoded) == "" || strings.Contains(string(encoded), "token") {+ t.Fatalf("join result unexpectedly exposes a token field: %s", encoded)+ }+}