Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: add ability to edit standalone containers (#3646)
Kyle Mendell24894fc7310b
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex ac28c08c6..d5a5e18b4 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -70,6 +70,8 @@ var (ErrGlobalVariableConflict = Classify(ErrConflict, errors.Sentinel("Global variable already exists"))ErrGlobalVariableScopeRequired = Classify(ErrValidation, errors.Sentinel("At least one environment is required when a variable is not scoped to all environments"))ErrGlobalVariableSecretValueRequired = Classify(ErrValidation, errors.Sentinel("A new value is required when making a secret variable readable"))+ ErrContainerComposeManaged = Classify(ErrConflict, errors.Sentinel("container is managed by a compose project; edit it via the project editor"))+ ErrContainerNameTaken = Classify(ErrConflict, errors.Sentinel("a container with this name already exists"))ErrSwarmNotEnabled = Classify(ErrBadRequest, errors.Sentinel("Swarm mode is not enabled"))ErrSwarmManagerRequired = Classify(ErrForbidden, errors.Sentinel("Swarm manager access required"))ErrRoleNotFound = Classify(ErrNotFound, errors.Sentinel("Role not found"))diff --git a/backend/internal/container/handler.go b/backend/internal/container/handler.goindex e542841dc..f9336f958 100644--- a/backend/internal/container/handler.go+++ b/backend/internal/container/handler.go@@ -141,6 +141,21 @@ type CommitContainerInput struct {Body containertypes.CommitRequest}+type GetContainerEditConfigInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ContainerID string `path:"containerId" doc:"Container ID"`+}++type GetContainerEditConfigOutput struct {+ Body base.ApiResponse[containertypes.EditConfig]+}++type EditContainerInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ContainerID string `path:"containerId" doc:"Container ID"`+ Body containertypes.Edit+}+type CommitContainerOutput struct {Body base.ApiResponse[containertypes.CommitResult]}@@ -266,6 +281,26 @@ func RegisterContainers(api huma.API, containerSvc *ContainerService, dockerSvcSecurity: handlerutil.DefaultOperationSecurity(),}, authz.PermContainersRedeploy, h.RedeployContainer)+ middleware.RegisterWithPermission(api, huma.Operation{+ OperationID: "get-container-edit-config",+ Method: http.MethodGet,+ Path: "/environments/{id}/containers/{containerId}/edit-config",+ Summary: "Get container edit config",+ Description: "Editable configuration snapshot backing the container edit form",+ Tags: []string{"Containers"},+ Security: handlerutil.DefaultOperationSecurity(),+ }, authz.PermContainersRead, h.GetContainerEditConfig)++ middleware.RegisterWithPermission(api, huma.Operation{+ OperationID: "edit-container",+ Method: http.MethodPost,+ Path: "/environments/{id}/containers/{containerId}/edit",+ Summary: "Edit container",+ Description: "Apply configuration changes and recreate the container",+ Tags: []string{"Containers"},+ Security: handlerutil.DefaultOperationSecurity(),+ }, authz.PermContainersEdit, h.EditContainer)+middleware.RegisterWithPermission(api, huma.Operation{OperationID: "delete-container",Method: http.MethodDelete,@@ -393,6 +428,7 @@ func buildContainerConfig(body containertypes.Create) *dockercontainer.Config {Env: resolveCreateEnv(body),ExposedPorts: network.PortSet{},Labels: buildCreateLabels(body),+ Healthcheck: healthConfigFromCreateInternal(body.Healthcheck),Hostname: body.Hostname,Domainname: body.Domainname,AttachStdout: body.AttachStdout,@@ -501,6 +537,15 @@ func applyHostConfigSettings(hostConfig *dockercontainer.HostConfig, input *contif input.CPUShares > 0 {hostConfig.CPUShares = input.CPUShares}+ if len(input.CapAdd) > 0 {+ hostConfig.CapAdd = input.CapAdd+ }+ if len(input.CapDrop) > 0 {+ hostConfig.CapDrop = input.CapDrop+ }+ if len(input.Mounts) > 0 {+ hostConfig.Mounts = mountsFromCreateInternal(input.Mounts)+ }}func applyHostConfigOverrides(body containertypes.Create, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig, portBindings network.PortMap) error {@@ -531,13 +576,17 @@ func applyLegacyResourceLimits(body containertypes.Create, hostConfig *dockercon}}-func buildNetworkingConfig(body containertypes.Create) *network.NetworkingConfig {+func buildNetworkingConfig(body containertypes.Create) (*network.NetworkingConfig, error) {if body.NetworkingConfig != nil && len(body.NetworkingConfig.EndpointsConfig) > 0 {networkingConfig := &network.NetworkingConfig{EndpointsConfig: make(map[string]*network.EndpointSettings)}for name, endpoint := range body.NetworkingConfig.EndpointsConfig {- networkingConfig.EndpointsConfig[name] = &network.EndpointSettings{Aliases: endpoint.Aliases}+ ipam, err := endpointIPAMFromCreateInternal(endpoint)+ if err != nil {+ return nil, err+ }+ networkingConfig.EndpointsConfig[name] = &network.EndpointSettings{Aliases: endpoint.Aliases, IPAMConfig: ipam}}- return networkingConfig+ return networkingConfig, nil}if len(body.Networks) > 0 {@@ -545,10 +594,10 @@ func buildNetworkingConfig(body containertypes.Create) *network.NetworkingConfigfor _, net := range body.Networks {networkingConfig.EndpointsConfig[net] = &network.EndpointSettings{}}- return networkingConfig+ return networkingConfig, nil}- return nil+ return nil, nil}func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateContainerInput) (*CreateContainerOutput, error) {@@ -572,7 +621,10 @@ func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateCon}applyLegacyResourceLimits(input.Body, hostConfig)- networkingConfig := buildNetworkingConfig(input.Body)+ networkingConfig, err := buildNetworkingConfig(input.Body)+ if err != nil {+ return nil, huma.Error400BadRequest(errors.WithMessage(err, "Invalid network configuration").Error())+ }containerJSON, err := h.containerService.CreateContainer(ctx, config, hostConfig, networkingConfig, input.Body.Name, *user, input.Body.Credentials)if err != nil {@@ -807,6 +859,77 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain}, nil}+func (h *ContainerHandler) GetContainerEditConfig(ctx context.Context, input *GetContainerEditConfigInput) (*GetContainerEditConfigOutput, error) {+ editConfig, err := h.containerService.GetContainerEditConfig(ctx, input.ContainerID)+ if err != nil {+ return nil, huma.Error404NotFound(errors.WithMessage(err, "Failed to retrieve container").Error())+ }++ return &GetContainerEditConfigOutput{+ Body: base.ApiResponse[containertypes.EditConfig]{+ Success: true,+ Data: editConfig,+ },+ }, nil+}++func editContainerHTTPErrorInternal(err error) error {+ switch {+ case errors.Is(err, common.ErrConflict):+ return huma.Error409Conflict(err.Error())+ case errors.Is(err, common.ErrValidation):+ return huma.Error400BadRequest(err.Error())+ default:+ return huma.Error500InternalServerError(errors.WithMessage(err, "Failed to edit container").Error())+ }+}++func (h *ContainerHandler) EditContainer(ctx context.Context, input *EditContainerInput) (*GetContainerOutput, error) {+ user, err := handlerutil.RequireUser(ctx)+ if err != nil {+ return nil, err+ }++ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)+ activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, activitytypes.TypeContainerEdit, "container", input.ContainerID, input.ContainerID, user, "Starting edit", "Container edit requested", database.JSON{"containerID": input.ContainerID}, true)+ activitylib.AwaitHandlerActivitySlot(runtimeCtx, h.activityService, activityID, input.EnvironmentID)+ activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Editing container")+ editCtx := context.WithValue(runtimeCtx, dockerutils.ProgressWriterKey{}, activityWriter)+ newContainerID, err := h.containerService.EditContainer(editCtx, input.ContainerID, input.Body, *user)+ if err != nil {+ activitylib.FlushWriter(activityWriter)+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container edit failed", err)+ return nil, editContainerHTTPErrorInternal(err)+ }+ activitylib.FlushWriter(activityWriter)+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container edited", nil)++ // Fetch full container details to return (consistent with redeploy)+ details, inspectErr := h.containerService.GetContainerDetails(runtimeCtx, newContainerID)+ if inspectErr == nil {+ details.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()++ return &GetContainerOutput{+ Body: base.ApiResponse[containertypes.Details]{+ Success: true,+ Data: details,+ },+ }, nil+ }++ // Container was recreated successfully, but we couldn't fetch full details.+ // Return minimal response with just the ID so frontend can still navigate.+ return &GetContainerOutput{+ Body: base.ApiResponse[containertypes.Details]{+ Success: true,+ Data: containertypes.Details{+ ID: newContainerID,+ ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer(),+ },+ },+ }, nil+}+func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteContainerInput) (*DeleteContainerOutput, error) {user, err := handlerutil.RequireUser(ctx)if err != nil {diff --git a/backend/internal/container/service.go b/backend/internal/container/service.goindex 218068813..c403e75bc 100644--- a/backend/internal/container/service.go+++ b/backend/internal/container/service.go@@ -12,6 +12,7 @@ import ("io""log/slog""maps"+ "net/netip""strings""sync""time"@@ -21,6 +22,7 @@ import (composetypes "github.com/compose-spec/compose-go/v2/types""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/events"+ "github.com/moby/moby/api/types/mount""github.com/moby/moby/api/types/network""github.com/moby/moby/client"@@ -160,14 +162,14 @@ func shouldStartRedeployedContainerInternal(containerInfo container.InspectResporeturn shouldStart}-func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerClient *client.Client, imageName, containerID, containerName string, user common.User) error {+func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerClient *client.Client, imageName, containerID, containerName, action string, credentials []containerregistry.Credential, user common.User) error {settings := s.settingsService.GetSettingsConfig()pullCtx, pullCancel := context.WithTimeout(ctx, timeouts.GetDuration(settings.DockerImagePullTimeout.AsInt(), timeouts.DefaultDockerImagePull))defer pullCancel()- pullOptions, authErr := s.imageService.PullOptionsWithAuth(ctx, imageName, nil)+ pullOptions, authErr := s.imageService.PullOptionsWithAuth(ctx, imageName, credentials)if authErr != nil {- slog.WarnContext(ctx, "failed to get registry authentication for container redeploy pull; proceeding without auth",+ slog.WarnContext(ctx, "failed to get registry authentication for container recreate pull; proceeding without auth","image", imageName,"error", authErr.Error(),)@@ -176,7 +178,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerreader, pullErr := dockerClient.ImagePull(pullCtx, imageName, pullOptions)if pullErr != nil && image.ShouldRetryAnonymousPull(pullOptions, pullErr) {- slog.WarnContext(ctx, "container redeploy image pull failed with registry auth; retrying anonymously",+ slog.WarnContext(ctx, "container recreate image pull failed with registry auth; retrying anonymously","image", imageName,"error", pullErr.Error(),)@@ -186,7 +188,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerif pullErr != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", pullErr, database.JSON{- "action": "redeploy",+ "action": action,"step": "pull_image_timeout","image": imageName,})@@ -194,7 +196,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, docker}s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", pullErr, database.JSON{- "action": "redeploy",+ "action": action,"step": "pull_image","image": imageName,})@@ -209,7 +211,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerstreamErr := dockerutils.RenderJSONMessageStream(reader, logWriter)if streamErr != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", streamErr, database.JSON{- "action": "redeploy",+ "action": action,"step": "complete_pull","image": imageName,})@@ -280,6 +282,80 @@ func (s *ContainerService) restoreContainerAfterRedeployFailureInternal(ctx cont}}+// restoreAutoRemoveContainerAfterStartFailureInternal recreates and starts the+// original container when a deferred-stop auto-remove recreate fails to start+// the replacement. Stopping the original already made the daemon delete it, so+// the only rollback left is rebuilding from the inspected configuration. The+// failed replacement must be removed first so the original name is free again.+// A returned error means the original container is gone and could not be+// restored; the caller must surface it alongside the replacement failure.+func (s *ContainerService) restoreAutoRemoveContainerAfterStartFailureInternal(ctx context.Context, dockerClient *client.Client, containerInfo container.InspectResponse, apiVersion string, user common.User) error {+ containerID := containerInfo.ID+ containerName := strings.TrimPrefix(containerInfo.Name, "/")++ originalConfig := *containerInfo.Config+ if len(containerID) >= 12 && originalConfig.Hostname == containerID[:12] {+ originalConfig.Hostname = ""+ }++ createResp, err := libarcane.ContainerCreateWithCompatibilityForAPIVersion(ctx, dockerClient, client.ContainerCreateOptions{+ Config: &originalConfig,+ HostConfig: containerInfo.HostConfig,+ NetworkingConfig: buildCleanNetworkingConfigInternal(containerInfo, apiVersion),+ Name: containerName,+ }, apiVersion)+ if err != nil {+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, database.JSON{+ "action": "redeploy",+ "step": "restore_create_original",+ })+ return errors.WrapIf(err, "failed to recreate original auto-remove container")+ }++ if _, err := dockerClient.ContainerStart(ctx, createResp.ID, client.ContainerStartOptions{}); err != nil {+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", createResp.ID, containerName, user.ID, user.Username, "0", err, database.JSON{+ "action": "redeploy",+ "step": "restore_start_original",+ })+ return errors.WrapIf(err, "failed to restart original auto-remove container")+ }++ slog.InfoContext(ctx, "restored auto-remove container after failed recreate",+ "oldContainerId", containerID,+ "restoredContainerId", createResp.ID,+ "containerName", containerName,+ )+ return nil+}++// rollbackFailedReplacementStartInternal removes the replacement that failed+// to start and rolls back to the original container. For a deferred-stop+// auto-remove original the rollback rebuilds it from the inspected+// configuration; a failed restore is combined into the start error so the+// caller learns the workload is down, not just that the replacement failed.+func (s *ContainerService) rollbackFailedReplacementStartInternal(ctx context.Context, dockerClient *client.Client, containerInfo container.InspectResponse, replacementID, action, backupName string, stopAfterCreate, wasRunning bool, apiVersion string, startErr error, user common.User) error {+ containerName := strings.TrimPrefix(containerInfo.Name, "/")++ var cleanupErr error+ if _, removeErr := dockerClient.ContainerRemove(ctx, replacementID, client.ContainerRemoveOptions{Force: true}); removeErr != nil {+ cleanupErr = errors.WrapIf(removeErr, "failed to remove replacement container")+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", replacementID, containerName, user.ID, user.Username, "0", removeErr, database.JSON{+ "action": action,+ "step": "cleanup_failed_start",+ })+ }++ if stopAfterCreate {+ if restoreErr := s.restoreAutoRemoveContainerAfterStartFailureInternal(ctx, dockerClient, containerInfo, apiVersion, user); restoreErr != nil {+ return errors.Combine(startErr, cleanupErr, restoreErr)+ }+ return startErr+ }++ s.restoreContainerAfterRedeployFailureInternal(ctx, dockerClient, containerInfo.ID, containerName, backupName, "start", wasRunning, user)+ return startErr+}+type containerLifecycleActionInternal struct {action stringeventType event.EventType@@ -591,7 +667,6 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID stcontainerName := strings.TrimPrefix(containerInfo.Name, "/")imageName := containerInfo.Config.Image- wasRunning := containerInfo.State != nil && containerInfo.State.RunningapiVersion := libarcane.DetectDockerAPIVersion(ctx, dockerClient)currentContainerID, currentContainerErr := cgroup.CurrentContainerID()@@ -616,59 +691,82 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID streturn newID, nil}- metadata := database.JSON{- "action": "redeploy",- "containerId": containerID,- "containerName": containerName,- "image": imageName,- }-if imageName != "" {- if err := s.pullRedeployImageInternal(ctx, dockerClient, imageName, containerID, containerName, user); err != nil {+ if err := s.pullRedeployImageInternal(ctx, dockerClient, imageName, containerID, containerName, "redeploy", nil, user); err != nil {return "", err}}+ networkingConfig := buildCleanNetworkingConfigInternal(containerInfo, apiVersion)+ newConfig := *containerInfo.Config++ return s.recreateContainerInternal(ctx, dockerClient, containerInfo, "redeploy", containerName, &newConfig, containerInfo.HostConfig, networkingConfig, apiVersion, event.EventTypeContainerDeploy, user)+}++// recreateContainerInternal replaces an existing container with one created+// from the supplied config, using rename-as-backup so the original can be+// restored when create or start fails. Shared by redeploy and edit.+func (s *ContainerService) recreateContainerInternal(ctx context.Context, dockerClient *client.Client, containerInfo container.InspectResponse, action, newName string, newConfig *container.Config, newHostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, apiVersion string, eventType event.EventType, user common.User) (string, error) {+ containerID := containerInfo.ID+ containerName := strings.TrimPrefix(containerInfo.Name, "/")+ wasRunning := containerInfo.State != nil && containerInfo.State.Running+ imageName := newConfig.Image++ // A running auto-remove container is deleted by the daemon the moment it+ // stops, which would make rollback impossible. For that case the stop is+ // deferred until the replacement has been created: the rename alone frees+ // the name, and a create failure rolls back to the untouched, still-running+ // original. Only a start failure can still lose the original.+ stopAfterCreate := wasRunning && containerInfo.HostConfig != nil && containerInfo.HostConfig.AutoRemove+backupName := buildRedeployBackupNameInternal(containerName, containerID)- if err := s.prepareContainerForRedeployInternal(ctx, dockerClient, containerID, containerName, backupName, wasRunning, user); err != nil {+ if err := s.prepareContainerForRedeployInternal(ctx, dockerClient, containerID, containerName, backupName, wasRunning && !stopAfterCreate, user); err != nil {return "", err}- networkingConfig := buildCleanNetworkingConfigInternal(containerInfo, apiVersion)-- newConfig := *containerInfo.Configif len(containerID) >= 12 && newConfig.Hostname == containerID[:12] {newConfig.Hostname = ""}createResp, err := libarcane.ContainerCreateWithCompatibilityForAPIVersion(ctx, dockerClient, client.ContainerCreateOptions{- Config: &newConfig,- HostConfig: containerInfo.HostConfig,+ Config: newConfig,+ HostConfig: newHostConfig,NetworkingConfig: networkingConfig,- Name: containerName,+ Name: newName,}, apiVersion)if err != nil {- s.restoreContainerAfterRedeployFailureInternal(ctx, dockerClient, containerID, containerName, backupName, "create", wasRunning, user)+ s.restoreContainerAfterRedeployFailureInternal(ctx, dockerClient, containerID, containerName, backupName, "create", wasRunning && !stopAfterCreate, user)s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, database.JSON{- "action": "redeploy",+ "action": action,"step": "create","image": imageName,})return "", errors.WrapIf(err, "failed to recreate container")}- if shouldStartRedeployedContainerInternal(containerInfo, wasRunning) {- _, err = dockerClient.ContainerStart(ctx, createResp.ID, client.ContainerStartOptions{})- if err != nil {+ if stopAfterCreate {+ if _, err := dockerClient.ContainerStop(ctx, containerID, client.ContainerStopOptions{Timeout: new(30)}); err != nil {if _, removeErr := dockerClient.ContainerRemove(ctx, createResp.ID, client.ContainerRemoveOptions{Force: true}); removeErr != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", createResp.ID, containerName, user.ID, user.Username, "0", removeErr, database.JSON{- "action": "redeploy",- "step": "cleanup_failed_start",+ "action": action,+ "step": "cleanup_failed_stop",})}- s.restoreContainerAfterRedeployFailureInternal(ctx, dockerClient, containerID, containerName, backupName, "start", wasRunning, user)+ s.restoreContainerAfterRedeployFailureInternal(ctx, dockerClient, containerID, containerName, backupName, "stop", false, user)+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, database.JSON{+ "action": action,+ "step": "stop",+ })+ return "", errors.WrapIf(err, "failed to stop container")+ }+ }++ if shouldStartRedeployedContainerInternal(containerInfo, wasRunning) {+ _, err = dockerClient.ContainerStart(ctx, createResp.ID, client.ContainerStartOptions{})+ if err != nil {+ err = s.rollbackFailedReplacementStartInternal(ctx, dockerClient, containerInfo, createResp.ID, action, backupName, stopAfterCreate, wasRunning, apiVersion, err, user)s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", createResp.ID, containerName, user.ID, user.Username, "0", err, database.JSON{- "action": "redeploy",+ "action": action,"step": "start","image": imageName,})@@ -676,32 +774,421 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st}}- slog.InfoContext(ctx, "container redeployed successfully",+ slog.InfoContext(ctx, "container recreated successfully",+ "action", action,"oldContainerId", containerID,"newContainerId", createResp.ID,- "containerName", containerName,+ "containerName", newName,"image", imageName,)- if _, err := dockerClient.ContainerRemove(ctx, containerID, client.ContainerRemoveOptions{- Force: true,- RemoveVolumes: false,- RemoveLinks: false,- }); err != nil {- slog.WarnContext(ctx, "failed to remove old container after successful redeploy",- "containerId", containerID,- "backupName", backupName,- "error", err,- )+ // After a deferred stop the daemon has already auto-removed the original.+ if !stopAfterCreate {+ if _, err := dockerClient.ContainerRemove(ctx, containerID, client.ContainerRemoveOptions{+ Force: true,+ RemoveVolumes: false,+ RemoveLinks: false,+ }); err != nil {+ slog.WarnContext(ctx, "failed to remove old container after successful recreate",+ "containerId", containerID,+ "backupName", backupName,+ "error", err,+ )+ }}- if logErr := s.eventService.LogContainerEvent(ctx, event.EventTypeContainerDeploy, createResp.ID, containerName, user.ID, user.Username, "0", metadata); logErr != nil {- slog.WarnContext(ctx, "failed to log deploy event", "err", logErr)+ metadata := database.JSON{+ "action": action,+ "containerId": containerID,+ "containerName": newName,+ "image": imageName,+ }+ if logErr := s.eventService.LogContainerEvent(ctx, eventType, createResp.ID, newName, user.ID, user.Username, "0", metadata); logErr != nil {+ slog.WarnContext(ctx, "failed to log recreate event", "err", logErr)}return createResp.ID, nil}+func healthConfigFromCreateInternal(hc *containertypes.HealthcheckCreate) *container.HealthConfig {+ if hc == nil {+ return nil+ }++ return &container.HealthConfig{+ Test: append([]string{}, hc.Test...),+ Interval: time.Duration(hc.Interval) * time.Second,+ Timeout: time.Duration(hc.Timeout) * time.Second,+ StartPeriod: time.Duration(hc.StartPeriod) * time.Second,+ StartInterval: time.Duration(hc.StartInterval) * time.Second,+ Retries: hc.Retries,+ }+}++// mergeEditMountsInternal builds the desired mount set for an edit. The edit+// form only carries the reduced {type, source, target, readOnly} view, so a+// requested mount that matches an existing one by type and target keeps the+// full original spec (bind/volume/tmpfs options, consistency, ...) with the+// source and read-only flag applied from the request; unmatched entries are+// new mounts built from the request.+func mergeEditMountsInternal(existing []mount.Mount, requested []containertypes.MountCreate) []mount.Mount {+ out := make([]mount.Mount, 0, len(requested))+ for _, req := range requested {+ merged := mount.Mount{+ Type: mount.Type(req.Type),+ Source: req.Source,+ Target: req.Target,+ ReadOnly: req.ReadOnly,+ }+ for _, prior := range existing {+ if string(prior.Type) == req.Type && prior.Target == req.Target {+ merged = prior+ merged.Source = req.Source+ merged.ReadOnly = req.ReadOnly+ break+ }+ }+ out = append(out, merged)+ }+ return out+}++func mountsFromCreateInternal(mounts []containertypes.MountCreate) []mount.Mount {+ out := make([]mount.Mount, 0, len(mounts))+ for _, m := range mounts {+ out = append(out, mount.Mount{+ Type: mount.Type(m.Type),+ Source: m.Source,+ Target: m.Target,+ ReadOnly: m.ReadOnly,+ })+ }+ return out+}++func portMapFromCreateInternal(bindings map[string][]containertypes.PortBindingCreate) (network.PortMap, error) {+ out := network.PortMap{}+ for portSpec, bindingList := range bindings {+ port, err := parsePortSpec(portSpec)+ if err != nil {+ return nil, errors.WrapIff(err, "invalid port %s", portSpec)+ }+ mapped := make([]network.PortBinding, 0, len(bindingList))+ for _, binding := range bindingList {+ pb := network.PortBinding{HostPort: binding.HostPort}+ if hostIP := strings.TrimSpace(binding.HostIP); hostIP != "" {+ parsedIP, err := netip.ParseAddr(hostIP)+ if err != nil {+ return nil, errors.WrapIff(err, "invalid host IP %s", hostIP)+ }+ pb.HostIP = parsedIP+ }+ mapped = append(mapped, pb)+ }+ out[port] = mapped+ }+ return out, nil+}++func endpointIPAMFromCreateInternal(ep containertypes.EndpointSettingsCreate) (*network.EndpointIPAMConfig, error) {+ ipv4 := strings.TrimSpace(ep.IPv4Address)+ ipv6 := strings.TrimSpace(ep.IPv6Address)+ if ipv4 == "" && ipv6 == "" {+ return nil, nil+ }++ cfg := &network.EndpointIPAMConfig{}+ if ipv4 != "" {+ addr, err := netip.ParseAddr(ipv4)+ if err != nil {+ return nil, errors.WrapIff(err, "invalid IPv4 address %s", ipv4)+ }+ cfg.IPv4Address = addr+ }+ if ipv6 != "" {+ addr, err := netip.ParseAddr(ipv6)+ if err != nil {+ return nil, errors.WrapIff(err, "invalid IPv6 address %s", ipv6)+ }+ cfg.IPv6Address = addr+ }+ return cfg, nil+}++// applyEditToContainerConfigInternal overwrites the non-nil form-owned Config+// sections of an edit request onto cfg. Settings the form does not own are+// left untouched. When port bindings are replaced, ExposedPorts is recomputed+// as the new binding keys plus any previously-exposed-but-unbound ports (image+// EXPOSE entries survive).+func applyEditToContainerConfigInternal(cfg *container.Config, previousBindings network.PortMap, req containertypes.Edit) error {+ if req.Image != nil && strings.TrimSpace(*req.Image) != "" {+ cfg.Image = strings.TrimSpace(*req.Image)+ }+ if req.WorkingDir != nil {+ cfg.WorkingDir = *req.WorkingDir+ }+ if req.User != nil {+ cfg.User = *req.User+ }+ if req.Command != nil {+ cfg.Cmd = append([]string{}, (*req.Command)...)+ }+ if req.Entrypoint != nil {+ cfg.Entrypoint = append([]string{}, (*req.Entrypoint)...)+ }+ if req.Environment != nil {+ cfg.Env = append([]string{}, (*req.Environment)...)+ }+ if req.Labels != nil {+ cfg.Labels = maps.Clone(*req.Labels)+ }++ switch {+ case req.ClearHealthcheck:+ cfg.Healthcheck = nil+ case req.Healthcheck != nil:+ cfg.Healthcheck = healthConfigFromCreateInternal(req.Healthcheck)+ }++ if req.HostConfig != nil && req.HostConfig.PortBindings != nil {+ newBindings, err := portMapFromCreateInternal(*req.HostConfig.PortBindings)+ if err != nil {+ return err+ }+ exposed := network.PortSet{}+ for port := range newBindings {+ exposed[port] = struct{}{}+ }+ for port := range cfg.ExposedPorts {+ if _, wasBound := previousBindings[port]; !wasBound {+ exposed[port] = struct{}{}+ }+ }+ cfg.ExposedPorts = exposed+ }++ return nil+}++// applyEditToHostConfigInternal overwrites the non-nil form-owned HostConfig+// sections of an edit request onto hc. Everything else (sysctls, ulimits, log+// drivers, devices, tmpfs, DNS, ...) carries over unchanged.+func applyEditToHostConfigInternal(hc *container.HostConfig, req containertypes.Edit) error {+ edit := req.HostConfig+ if edit == nil {+ return nil+ }++ if edit.Binds != nil {+ hc.Binds = append([]string{}, (*edit.Binds)...)+ }+ if edit.Mounts != nil {+ hc.Mounts = mergeEditMountsInternal(hc.Mounts, *edit.Mounts)+ }+ if edit.PortBindings != nil {+ newBindings, err := portMapFromCreateInternal(*edit.PortBindings)+ if err != nil {+ return err+ }+ hc.PortBindings = newBindings+ }+ if edit.RestartPolicy != nil {+ hc.RestartPolicy = container.RestartPolicy{+ Name: container.RestartPolicyMode(edit.RestartPolicy.Name),+ MaximumRetryCount: edit.RestartPolicy.MaximumRetryCount,+ }+ }+ if edit.Privileged != nil {+ hc.Privileged = *edit.Privileged+ }+ if edit.CapAdd != nil {+ hc.CapAdd = append([]string{}, (*edit.CapAdd)...)+ }+ if edit.CapDrop != nil {+ hc.CapDrop = append([]string{}, (*edit.CapDrop)...)+ }+ if edit.AutoRemove != nil {+ hc.AutoRemove = *edit.AutoRemove+ }+ if edit.ReadonlyRootfs != nil {+ hc.ReadonlyRootfs = *edit.ReadonlyRootfs+ }+ if edit.Memory != nil {+ hc.Memory = *edit.Memory+ }+ if edit.MemorySwap != nil {+ hc.MemorySwap = *edit.MemorySwap+ }+ if edit.NanoCPUs != nil {+ hc.NanoCPUs = *edit.NanoCPUs+ }+ if edit.CPUShares != nil {+ hc.CPUShares = *edit.CPUShares+ }++ return nil+}++// buildEditNetworkingConfigInternal builds the networking config for an edit+// recreate. A nil request preserves the existing attachments (same behavior as+// redeploy); otherwise the request is the full desired endpoint set, keeping+// the sanitized settings of endpoints that stay attached. Containers using+// host/none/container: network modes never get endpoint edits.+func buildEditNetworkingConfigInternal(containerInspect container.InspectResponse, req *containertypes.NetworkingConfigCreate, apiVersion string) (*network.NetworkingConfig, error) {+ if containerInspect.HostConfig != nil {+ mode := containerInspect.HostConfig.NetworkMode+ if mode.IsHost() || mode.IsNone() || mode.IsContainer() {+ return nil, nil+ }+ }++ if req == nil {+ return buildCleanNetworkingConfigInternal(containerInspect, apiVersion), nil+ }++ var existing map[string]*network.EndpointSettings+ if containerInspect.NetworkSettings != nil {+ existing = libarcane.SanitizeContainerCreateEndpointSettingsForDockerAPI(containerInspect.NetworkSettings.Networks, apiVersion)+ }++ endpoints := make(map[string]*network.EndpointSettings, len(req.EndpointsConfig))+ for name, epReq := range req.EndpointsConfig {+ endpoint := &network.EndpointSettings{}+ if prior := existing[name]; prior != nil {+ priorCopy := *prior+ priorCopy.IPAMConfig = nil+ endpoint = &priorCopy+ }+ endpoint.Aliases = append([]string{}, epReq.Aliases...)+ ipam, err := endpointIPAMFromCreateInternal(epReq)+ if err != nil {+ return nil, err+ }+ endpoint.IPAMConfig = ipam+ endpoints[name] = endpoint+ }++ if len(endpoints) == 0 {+ return nil, nil+ }++ return &network.NetworkingConfig{EndpointsConfig: endpoints}, nil+}++// GetContainerEditConfig returns the purpose-built DTO backing the container+// edit form.+func (s *ContainerService) GetContainerEditConfig(ctx context.Context, containerID string) (containertypes.EditConfig, error) {+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return containertypes.EditConfig{}, errors.WrapIf(err, "failed to connect to Docker")+ }++ containerJSON, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ if err != nil {+ return containertypes.EditConfig{}, errors.WrapIf(err, "failed to inspect container")+ }++ containerInfo := containerJSON.Container+ var containerLabels map[string]string+ if containerInfo.Config != nil {+ containerLabels = containerInfo.Config.Labels+ }++ isCompose := dockerutils.ComposeProjectLabel(containerLabels) != ""+ currentContainerID, currentContainerErr := cgroup.CurrentContainerID()+ editDisabled := labels.ShouldDisableArcaneServerRedeploy(containerLabels, containerInfo.ID, currentContainerID, currentContainerErr)++ return containertypes.NewEditConfigFromInspect(&containerInfo, isCompose, editDisabled), nil+}++// EditContainer applies a user-supplied config diff onto the container's+// inspected config and recreates it. Sections not owned by the edit form are+// preserved from the existing container.+func (s *ContainerService) EditContainer(ctx context.Context, containerID string, req containertypes.Edit, user common.User) (string, error) {+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{+ "action": "edit",+ "step": "get_client",+ })+ return "", errors.WrapIf(err, "failed to connect to Docker")+ }++ containerJSON, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ if err != nil {+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{+ "action": "edit",+ "step": "inspect",+ })+ return "", errors.WrapIf(err, "failed to inspect container")+ }++ containerInfo := containerJSON.Container+ if containerInfo.Config == nil {+ return "", errors.New("container config is nil")+ }++ containerName := strings.TrimPrefix(containerInfo.Name, "/")++ if project := dockerutils.ComposeProjectLabel(containerInfo.Config.Labels); project != "" {+ return "", errors.WrapIff(common.ErrContainerComposeManaged, "compose project %s", project)+ }++ currentContainerID, currentContainerErr := cgroup.CurrentContainerID()+ if labels.ShouldDisableArcaneServerRedeploy(containerInfo.Config.Labels, containerInfo.ID, currentContainerID, currentContainerErr) {+ err = errors.New("arcane cannot edit itself; use the system upgrade flow (Settings -> Updates) instead")+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, database.JSON{+ "action": "edit",+ "step": "self_edit_blocked",+ })+ return "", err+ }++ newName := containerName+ if req.Name != nil {+ if trimmed := strings.TrimPrefix(strings.TrimSpace(*req.Name), "/"); trimmed != "" {+ newName = trimmed+ }+ }+ if newName != containerName {+ if _, inspectErr := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, newName, client.ContainerInspectOptions{}); inspectErr == nil {+ return "", errors.WrapIff(common.ErrContainerNameTaken, "container name %s", newName)+ }+ }++ apiVersion := libarcane.DetectDockerAPIVersion(ctx, dockerClient)++ newConfig := *containerInfo.Config+ var newHostConfig container.HostConfig+ if containerInfo.HostConfig != nil {+ newHostConfig = *containerInfo.HostConfig+ }++ if err := applyEditToContainerConfigInternal(&newConfig, newHostConfig.PortBindings, req); err != nil {+ return "", common.Classify(common.ErrValidation, err)+ }+ if err := applyEditToHostConfigInternal(&newHostConfig, req); err != nil {+ return "", common.Classify(common.ErrValidation, err)+ }+ networkingConfig, err := buildEditNetworkingConfigInternal(containerInfo, req.NetworkingConfig, apiVersion)+ if err != nil {+ return "", common.Classify(common.ErrValidation, err)+ }++ // Unlike redeploy, edit only pulls when the effective image is missing+ // locally so an unrelated config change never surprise-upgrades the image.+ imageName := newConfig.Image+ if imageName != "" {+ if _, inspectErr := dockerClient.ImageInspect(ctx, imageName); inspectErr != nil {+ if err := s.pullRedeployImageInternal(ctx, dockerClient, imageName, containerID, containerName, "edit", req.Credentials, user); err != nil {+ return "", err+ }+ }+ }++ return s.recreateContainerInternal(ctx, dockerClient, containerInfo, "edit", newName, &newConfig, &newHostConfig, networkingConfig, apiVersion, event.EventTypeContainerUpdate, user)+}+func (s *ContainerService) GetContainerByReference(ctx context.Context, ref string) (*container.InspectResponse, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.goindex ba15bd75e..03ac6f16d 100644--- a/backend/internal/container/service_test.go+++ b/backend/internal/container/service_test.go@@ -26,6 +26,7 @@ import (imagetypes "github.com/getarcaneapp/arcane/types/v2/image""github.com/libtnb/sqlite""github.com/moby/moby/api/types/container"+ "github.com/moby/moby/api/types/mount""github.com/moby/moby/api/types/network""github.com/moby/moby/client""github.com/stretchr/testify/require"@@ -367,3 +368,149 @@ func setupProjectTestDBInternal(t *testing.T) *database.DB {}var dockerAPIVersionPrefixInternal = regexp.MustCompile(`^/v[0-9]+\.[0-9]+`)++func TestApplyEditPreservesUnmanagedSettingsInternal(t *testing.T) {+ cfg := container.Config{+ Image: "nginx:1.25",+ Env: []string{"OLD=1"},+ StopSignal: "SIGQUIT",+ ExposedPorts: network.PortSet{network.MustParsePort("80/tcp"): {}, network.MustParsePort("9000/tcp"): {}},+ }+ hc := container.HostConfig{+ Binds: []string{"/data:/data"},+ PortBindings: network.PortMap{network.MustParsePort("80/tcp"): {{HostPort: "8080"}}},+ Sysctls: map[string]string{"net.core.somaxconn": "1024"},+ LogConfig: container.LogConfig{Type: "json-file", Config: map[string]string{"max-size": "5m"}},+ }+ hc.Ulimits = []*container.Ulimit{{Name: "nofile", Soft: 1024, Hard: 2048}}++ env := []string{"NEW=1"}+ req := containertypes.Edit{Environment: &env}++ require.NoError(t, applyEditToContainerConfigInternal(&cfg, hc.PortBindings, req))+ require.NoError(t, applyEditToHostConfigInternal(&hc, req))++ require.Equal(t, []string{"NEW=1"}, cfg.Env)+ require.Equal(t, "SIGQUIT", cfg.StopSignal)+ require.Equal(t, map[string]string{"net.core.somaxconn": "1024"}, hc.Sysctls)+ require.Equal(t, "json-file", hc.LogConfig.Type)+ require.Len(t, hc.Ulimits, 1)+ require.Equal(t, []string{"/data:/data"}, hc.Binds)+ require.Contains(t, cfg.ExposedPorts, network.MustParsePort("80/tcp"))+}++func TestMergeEditMountsPreservesMountOptionsInternal(t *testing.T) {+ existing := []mount.Mount{+ {+ Type: mount.TypeVolume,+ Source: "data",+ Target: "/data",+ VolumeOptions: &mount.VolumeOptions{NoCopy: true, Labels: map[string]string{"keep": "me"}},+ },+ {Type: mount.TypeTmpfs, Target: "/tmp/scratch", TmpfsOptions: &mount.TmpfsOptions{SizeBytes: 1024}},+ }++ // Round-trip the volume mount (toggling read-only) and drop the tmpfs one.+ requested := []containertypes.MountCreate{{Type: "volume", Source: "data", Target: "/data", ReadOnly: true}}++ out := mergeEditMountsInternal(existing, requested)+ require.Len(t, out, 1)+ require.True(t, out[0].ReadOnly)+ require.NotNil(t, out[0].VolumeOptions)+ require.Equal(t, map[string]string{"keep": "me"}, out[0].VolumeOptions.Labels)+}++func TestMergeEditMountsAppliesSourceChangeInternal(t *testing.T) {+ existing := []mount.Mount{+ {+ Type: mount.TypeVolume,+ Source: "old-volume",+ Target: "/data",+ VolumeOptions: &mount.VolumeOptions{NoCopy: true, Labels: map[string]string{"keep": "me"}},+ },+ {+ Type: mount.TypeBind,+ Source: "/old/path",+ Target: "/config",+ BindOptions: &mount.BindOptions{Propagation: mount.PropagationRPrivate},+ },+ }++ // Same type and target but a different source must honor the new source+ // while retaining the original driver options.+ requested := []containertypes.MountCreate{+ {Type: "volume", Source: "new-volume", Target: "/data"},+ {Type: "bind", Source: "/new/path", Target: "/config", ReadOnly: true},+ }++ out := mergeEditMountsInternal(existing, requested)+ require.Len(t, out, 2)+ require.Equal(t, "new-volume", out[0].Source)+ require.NotNil(t, out[0].VolumeOptions)+ require.Equal(t, map[string]string{"keep": "me"}, out[0].VolumeOptions.Labels)+ require.Equal(t, "/new/path", out[1].Source)+ require.True(t, out[1].ReadOnly)+ require.NotNil(t, out[1].BindOptions)+ require.Equal(t, mount.PropagationRPrivate, out[1].BindOptions.Propagation)+}++func TestApplyEditRecomputesExposedPortsInternal(t *testing.T) {+ cfg := container.Config{+ ExposedPorts: network.PortSet{+ network.MustParsePort("80/tcp"): {},+ network.MustParsePort("9000/tcp"): {},+ },+ }+ hc := container.HostConfig{+ PortBindings: network.PortMap{network.MustParsePort("80/tcp"): {{HostPort: "8080"}}},+ }++ newBindings := map[string][]containertypes.PortBindingCreate{"443/tcp": {{HostPort: "8443"}}}+ req := containertypes.Edit{HostConfig: &containertypes.HostConfigEdit{PortBindings: &newBindings}}++ require.NoError(t, applyEditToContainerConfigInternal(&cfg, hc.PortBindings, req))+ require.NoError(t, applyEditToHostConfigInternal(&hc, req))++ // new binding key + previously-exposed-but-unbound port survive; the old bound port is gone+ require.Contains(t, cfg.ExposedPorts, network.MustParsePort("443/tcp"))+ require.Contains(t, cfg.ExposedPorts, network.MustParsePort("9000/tcp"))+ require.NotContains(t, cfg.ExposedPorts, network.MustParsePort("80/tcp"))+ require.Contains(t, hc.PortBindings, network.MustParsePort("443/tcp"))+}++func TestBuildEditNetworkingConfigInternal(t *testing.T) {+ containerInspect := container.InspectResponse{+ HostConfig: &container.HostConfig{NetworkMode: "my-net"},+ NetworkSettings: &container.NetworkSettings{+ Networks: map[string]*network.EndpointSettings{+ "my-net": {Aliases: []string{"svc"}, DNSNames: []string{"svc"}},+ },+ },+ }++ // nil request preserves existing attachments+ out, err := buildEditNetworkingConfigInternal(containerInspect, nil, "1.44")+ require.NoError(t, err)+ require.NotNil(t, out)+ require.Contains(t, out.EndpointsConfig, "my-net")++ // explicit desired set: keep my-net with new alias + static IP, add other-net+ req := &containertypes.NetworkingConfigCreate{+ EndpointsConfig: map[string]containertypes.EndpointSettingsCreate{+ "my-net": {Aliases: []string{"renamed"}, IPv4Address: "10.5.0.9"},+ "other-net": {},+ },+ }+ out, err = buildEditNetworkingConfigInternal(containerInspect, req, "1.44")+ require.NoError(t, err)+ require.Len(t, out.EndpointsConfig, 2)+ require.Equal(t, []string{"renamed"}, out.EndpointsConfig["my-net"].Aliases)+ require.Equal(t, netip.MustParseAddr("10.5.0.9"), out.EndpointsConfig["my-net"].IPAMConfig.IPv4Address)+ require.Equal(t, []string{"svc"}, out.EndpointsConfig["my-net"].DNSNames)++ // host network mode: endpoint edits are skipped entirely+ hostModeInspect := container.InspectResponse{HostConfig: &container.HostConfig{NetworkMode: "host"}}+ out, err = buildEditNetworkingConfigInternal(hostModeInspect, req, "1.44")+ require.NoError(t, err)+ require.Nil(t, out)+}diff --git a/backend/internal/event/model.go b/backend/internal/event/model.goindex 2dcd522d4..875a7750b 100644--- a/backend/internal/event/model.go+++ b/backend/internal/event/model.go@@ -71,9 +71,11 @@ const (EventTypeVolumeBackupRestoreFiles EventType = "volume.backup.restore_files"EventTypeVolumeBackupDownload EventType = "volume.backup.download"- EventTypeNetworkCreate EventType = "network.create"- EventTypeNetworkDelete EventType = "network.delete"- EventTypeNetworkError EventType = "network.error"+ EventTypeNetworkCreate EventType = "network.create"+ EventTypeNetworkDelete EventType = "network.delete"+ EventTypeNetworkConnect EventType = "network.connect"+ EventTypeNetworkDisconnect EventType = "network.disconnect"+ EventTypeNetworkError EventType = "network.error"EventTypeSystemPrune EventType = "system.prune"EventTypeUserLogin EventType = "user.login"diff --git a/backend/internal/event/service.go b/backend/internal/event/service.goindex a4157a2be..903b5cc25 100644--- a/backend/internal/event/service.go+++ b/backend/internal/event/service.go@@ -676,9 +676,11 @@ var eventDefinitions = map[EventType]eventDefinition{EventTypeVolumeBackupRestoreFiles: {"Volume backup files restored: %s", "Selected files were restored for volume '%s'", EventSeverityWarning},EventTypeVolumeBackupDownload: {"Volume backup downloaded: %s", "A backup was downloaded for volume '%s'", EventSeverityInfo},- EventTypeNetworkCreate: {"Network created: %s", "Network '%s' has been created", EventSeveritySuccess},- EventTypeNetworkDelete: {"Network deleted: %s", "Network '%s' has been deleted", EventSeverityWarning},- EventTypeNetworkError: {"Network error: %s", "An error occurred with network '%s'", EventSeverityError},+ EventTypeNetworkCreate: {"Network created: %s", "Network '%s' has been created", EventSeveritySuccess},+ EventTypeNetworkDelete: {"Network deleted: %s", "Network '%s' has been deleted", EventSeverityWarning},+ EventTypeNetworkConnect: {"Network connected: %s", "A container has been connected to network '%s'", EventSeveritySuccess},+ EventTypeNetworkDisconnect: {"Network disconnected: %s", "A container has been disconnected from network '%s'", EventSeverityInfo},+ EventTypeNetworkError: {"Network error: %s", "An error occurred with network '%s'", EventSeverityError},EventTypeSystemPrune: {"System prune completed", "System resources have been pruned", EventSeverityInfo},EventTypeSystemAutoUpdate: {"System auto-update completed", "System auto-update process has completed", EventSeverityInfo},diff --git a/backend/internal/network/handler.go b/backend/internal/network/handler.goindex 760973dd2..376e92f25 100644--- a/backend/internal/network/handler.go+++ b/backend/internal/network/handler.go@@ -15,6 +15,7 @@ import ("emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -98,6 +99,26 @@ type PruneNetworksInput struct {EnvironmentID string `path:"id" doc:"Environment ID"`}+type ConnectContainerInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NetworkID string `path:"networkId" doc:"Network ID"`+ Body networktypes.ConnectContainerRequest+}++type ConnectContainerOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}++type DisconnectContainerInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ NetworkID string `path:"networkId" doc:"Network ID"`+ Body networktypes.DisconnectContainerRequest+}++type DisconnectContainerOutput struct {+ Body base.ApiResponse[base.MessageResponse]+}+type PruneNetworksOutput struct {Body base.ApiResponse[networktypes.PruneReport]}@@ -173,6 +194,24 @@ func RegisterNetworks(api huma.API, networkSvc *NetworkService, dockerSvc *dockeTags: []string{"Networks"},Security: handlerutil.DefaultOperationSecurity(),}, authz.PermNetworksPrune, h.PruneNetworks)++ middleware.RegisterWithPermission(api, huma.Operation{+ OperationID: "connect-network-container",+ Method: http.MethodPost,+ Path: "/environments/{id}/networks/{networkId}/connect",+ Summary: "Connect container to network",+ Tags: []string{"Networks"},+ Security: handlerutil.DefaultOperationSecurity(),+ }, authz.PermNetworksConnect, h.ConnectContainer)++ middleware.RegisterWithPermission(api, huma.Operation{+ OperationID: "disconnect-network-container",+ Method: http.MethodPost,+ Path: "/environments/{id}/networks/{networkId}/disconnect",+ Summary: "Disconnect container from network",+ Tags: []string{"Networks"},+ Security: handlerutil.DefaultOperationSecurity(),+ }, authz.PermNetworksDisconnect, h.DisconnectContainer)}func (h *NetworkHandler) ListNetworks(ctx context.Context, input *ListNetworksInput) (*ListNetworksOutput, error) {@@ -399,6 +438,82 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetwork}, nil}+func (h *NetworkHandler) ConnectContainer(ctx context.Context, input *ConnectContainerInput) (*ConnectContainerOutput, error) {+ user, err := handlerutil.RequireUser(ctx)+ if err != nil {+ return nil, err+ }++ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{+ EnvironmentID: input.EnvironmentID,+ Type: activitytypes.TypeResourceAction,+ ResourceType: "network",+ ResourceID: input.NetworkID,+ ResourceName: input.NetworkID,+ User: user,+ Step: "Connecting container to network",+ Message: "Connecting container to network",+ SuccessMessage: "Container connected successfully",+ Metadata: database.JSON{+ "action": "connect_network",+ "containerId": input.Body.ContainerID,+ },+ }, func(runtimeCtx context.Context) error {+ return h.networkService.ConnectContainer(runtimeCtx, input.NetworkID, input.Body, *user)+ })+ if err != nil {+ if errors.Is(err, common.ErrValidation) {+ return nil, huma.Error400BadRequest(err.Error())+ }+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to connect container to network").Error())+ }++ return &ConnectContainerOutput{+ Body: base.ApiResponse[base.MessageResponse]{+ Success: true,+ Data: base.MessageResponse{Message: "Container connected successfully", ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},+ },+ }, nil+}++func (h *NetworkHandler) DisconnectContainer(ctx context.Context, input *DisconnectContainerInput) (*DisconnectContainerOutput, error) {+ user, err := handlerutil.RequireUser(ctx)+ if err != nil {+ return nil, err+ }++ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{+ EnvironmentID: input.EnvironmentID,+ Type: activitytypes.TypeResourceAction,+ ResourceType: "network",+ ResourceID: input.NetworkID,+ ResourceName: input.NetworkID,+ User: user,+ Step: "Disconnecting container from network",+ Message: "Disconnecting container from network",+ SuccessMessage: "Container disconnected successfully",+ Metadata: database.JSON{+ "action": "disconnect_network",+ "containerId": input.Body.ContainerID,+ "force": input.Body.Force,+ },+ }, func(runtimeCtx context.Context) error {+ return h.networkService.DisconnectContainer(runtimeCtx, input.NetworkID, input.Body, *user)+ })+ if err != nil {+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to disconnect container from network").Error())+ }++ return &DisconnectContainerOutput{+ Body: base.ApiResponse[base.MessageResponse]{+ Success: true,+ Data: base.MessageResponse{Message: "Container disconnected successfully", ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},+ },+ }, nil+}+func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworksInput) (*PruneNetworksOutput, error) {var report *dockernetwork.PruneReportruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)diff --git a/backend/internal/network/service.go b/backend/internal/network/service.goindex 7348ac0ec..321ae9b15 100644--- a/backend/internal/network/service.go+++ b/backend/internal/network/service.go@@ -6,6 +6,7 @@ import ("context""fmt""log/slog"+ "net/netip""sort""strings"@@ -243,6 +244,85 @@ func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user commreturn nil}+// ConnectContainer connects a container to a network without recreating it.+func (s *NetworkService) ConnectContainer(ctx context.Context, networkID string, req networktypes.ConnectContainerRequest, user common.User) error {+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", networkID, "", user.ID, user.Username, "0", err, database.JSON{"action": "connect", "containerId": req.ContainerID})+ return errors.WrapIf(err, "failed to connect to Docker")+ }++ endpoint := &network.EndpointSettings{Aliases: req.Aliases}+ ipv4 := strings.TrimSpace(req.IPv4Address)+ ipv6 := strings.TrimSpace(req.IPv6Address)+ if ipv4 != "" || ipv6 != "" {+ ipam := &network.EndpointIPAMConfig{}+ if ipv4 != "" {+ addr, parseErr := netip.ParseAddr(ipv4)+ if parseErr != nil {+ return common.Classify(common.ErrValidation, errors.WrapIff(parseErr, "invalid IPv4 address %s", ipv4))+ }+ ipam.IPv4Address = addr+ }+ if ipv6 != "" {+ addr, parseErr := netip.ParseAddr(ipv6)+ if parseErr != nil {+ return common.Classify(common.ErrValidation, errors.WrapIff(parseErr, "invalid IPv6 address %s", ipv6))+ }+ ipam.IPv6Address = addr+ }+ endpoint.IPAMConfig = ipam+ }++ if _, err := dockerClient.NetworkConnect(ctx, networkID, client.NetworkConnectOptions{+ Container: req.ContainerID,+ EndpointConfig: endpoint,+ }); err != nil {+ s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", networkID, "", user.ID, user.Username, "0", err, database.JSON{"action": "connect", "containerId": req.ContainerID})+ return errors.WrapIf(err, "failed to connect container to network")+ }++ metadata := database.JSON{+ "action": "connect",+ "networkId": networkID,+ "containerId": req.ContainerID,+ }+ if logErr := s.eventService.LogNetworkEvent(ctx, event.EventTypeNetworkConnect, networkID, networkID, user.ID, user.Username, "0", metadata); logErr != nil {+ slog.WarnContext(ctx, "could not log network connect action", "error", logErr)+ }++ return nil+}++// DisconnectContainer disconnects a container from a network.+func (s *NetworkService) DisconnectContainer(ctx context.Context, networkID string, req networktypes.DisconnectContainerRequest, user common.User) error {+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", networkID, "", user.ID, user.Username, "0", err, database.JSON{"action": "disconnect", "containerId": req.ContainerID})+ return errors.WrapIf(err, "failed to connect to Docker")+ }++ if _, err := dockerClient.NetworkDisconnect(ctx, networkID, client.NetworkDisconnectOptions{+ Container: req.ContainerID,+ Force: req.Force,+ }); err != nil {+ s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", networkID, "", user.ID, user.Username, "0", err, database.JSON{"action": "disconnect", "containerId": req.ContainerID})+ return errors.WrapIf(err, "failed to disconnect container from network")+ }++ metadata := database.JSON{+ "action": "disconnect",+ "networkId": networkID,+ "containerId": req.ContainerID,+ "force": req.Force,+ }+ if logErr := s.eventService.LogNetworkEvent(ctx, event.EventTypeNetworkDisconnect, networkID, networkID, user.ID, user.Username, "0", metadata); logErr != nil {+ slog.WarnContext(ctx, "could not log network disconnect action", "error", logErr)+ }++ return nil+}+func (s *NetworkService) PruneNetworks(ctx context.Context) (*network.PruneReport, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {diff --git a/backend/pkg/authz/catalog.go b/backend/pkg/authz/catalog.goindex 761daaded..0a880e3a2 100644--- a/backend/pkg/authz/catalog.go+++ b/backend/pkg/authz/catalog.go@@ -127,6 +127,7 @@ var permissionCatalog = []PermissionCatalogResource{{"stop", PermContainersStop, "Stop", ""},{"restart", PermContainersRestart, "Restart", ""},{"redeploy", PermContainersRedeploy, "Redeploy", ""},+ {"edit", PermContainersEdit, "Edit (recreate with changes)", ""},{"kill", PermContainersKill, "Kill (send signal)", ""},{"pause", PermContainersPause, "Pause / unpause", ""},{"delete", PermContainersDelete, "Delete", ""},@@ -172,6 +173,8 @@ var permissionCatalog = []PermissionCatalogResource{{"create", PermNetworksCreate, "Create", ""},{"delete", PermNetworksDelete, "Delete", ""},{"prune", PermNetworksPrune, "Prune", ""},+ {"connect", PermNetworksConnect, "Connect container", ""},+ {"disconnect", PermNetworksDisconnect, "Disconnect container", ""},}},{"swarm", "Swarm", PermissionScopeEnv, []PermissionCatalogAction{{"read", PermSwarmRead, "Read", ""},diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.goindex 07bd18d35..fc14310e8 100644--- a/backend/pkg/authz/permissions.go+++ b/backend/pkg/authz/permissions.go@@ -127,6 +127,7 @@ const (PermContainersStop = "containers:stop"PermContainersRestart = "containers:restart"PermContainersRedeploy = "containers:redeploy"+ PermContainersEdit = "containers:edit"PermContainersKill = "containers:kill"PermContainersPause = "containers:pause"PermContainersDelete = "containers:delete"@@ -163,11 +164,13 @@ const (PermVolumesUpload = "volumes:upload"PermVolumesBackup = "volumes:backup"- PermNetworksList = "networks:list"- PermNetworksRead = "networks:read"- PermNetworksCreate = "networks:create"- PermNetworksDelete = "networks:delete"- PermNetworksPrune = "networks:prune"+ PermNetworksList = "networks:list"+ PermNetworksRead = "networks:read"+ PermNetworksCreate = "networks:create"+ PermNetworksDelete = "networks:delete"+ PermNetworksPrune = "networks:prune"+ PermNetworksConnect = "networks:connect"+ PermNetworksDisconnect = "networks:disconnect"PermSwarmRead = "swarm:read"PermSwarmInit = "swarm:init"@@ -320,11 +323,11 @@ func BuiltInEditorPermissions() []string {PermS3DestinationsList, PermS3DestinationsRead,PermEventsRead,// Full env-scoped Docker management- PermContainersList, PermContainersRead, PermContainersLogs, PermContainersCreate, PermContainersStart, PermContainersStop, PermContainersRestart, PermContainersRedeploy, PermContainersKill, PermContainersPause, PermContainersDelete, PermContainersExec, PermContainersAutoUpdate,+ PermContainersList, PermContainersRead, PermContainersLogs, PermContainersCreate, PermContainersStart, PermContainersStop, PermContainersRestart, PermContainersRedeploy, PermContainersEdit, PermContainersKill, PermContainersPause, PermContainersDelete, PermContainersExec, PermContainersAutoUpdate,PermProjectsList, PermProjectsRead, PermProjectsLogs, PermProjectsCreate, PermProjectsUpdate, PermProjectsDeploy, PermProjectsDown, PermProjectsRestart, PermProjectsDelete, PermProjectsArchive,PermImagesList, PermImagesRead, PermImagesPull, PermImagesPush, PermImagesBuild, PermImagesTag, PermImagesCommit, PermImagesPrune, PermImagesDelete, PermImagesUpload,PermVolumesList, PermVolumesRead, PermVolumesCreate, PermVolumesDelete, PermVolumesPrune, PermVolumesUpload, PermVolumesBackup,- PermNetworksList, PermNetworksRead, PermNetworksCreate, PermNetworksDelete, PermNetworksPrune,+ PermNetworksList, PermNetworksRead, PermNetworksCreate, PermNetworksDelete, PermNetworksPrune, PermNetworksConnect, PermNetworksDisconnect,PermSwarmRead, PermSwarmSpec, PermSwarmNodes, PermSwarmServices, PermSwarmServicesLogs, PermSwarmStacks, PermSwarmConfigs, PermSwarmSecrets,PermGitOpsList, PermGitOpsRead, PermGitOpsCreate, PermGitOpsUpdate, PermGitOpsDelete, PermGitOpsSync,PermWebhooksList, PermWebhooksCreate, PermWebhooksUpdate, PermWebhooksDelete,@@ -347,7 +350,7 @@ func BuiltInDeployerPermissions() []string {PermTemplatesList, PermTemplatesRead,PermVariablesRead,PermEventsRead,- PermContainersList, PermContainersRead, PermContainersLogs, PermContainersStart, PermContainersStop, PermContainersRestart, PermContainersRedeploy, PermContainersKill, PermContainersPause,+ PermContainersList, PermContainersRead, PermContainersLogs, PermContainersStart, PermContainersStop, PermContainersRestart, PermContainersRedeploy, PermContainersEdit, PermContainersKill, PermContainersPause,PermProjectsList, PermProjectsRead, PermProjectsLogs, PermProjectsDeploy, PermProjectsDown, PermProjectsRestart,PermImagesList, PermImagesRead, PermImagesPull, PermImagesTag, PermImagesCommit,PermVolumesList, PermVolumesRead,diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 5aa551eb4..1f2cb89cb 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -751,11 +751,9 @@"io_open_stdin": "Open stdin","io_stdin_once": "Stdin once","env_dynamic_title": "Dynamic Environment Variables",- "add_env_var_button": "Add Environment Variable","env_text_placeholder": "KEY=value\nANOTHER_KEY=another_value","env_text_description": "Enter environment variables in KEY=value format, one per line","host": "Host",- "add_port_mapping_button": "Add Port Mapping","port_configuration_title": "Port Configuration","exposed_ports_placeholder": "80/tcp, 443/tcp","exposed_ports_description": "Comma-separated list of ports to expose",@@ -3266,5 +3264,37 @@"system_backups_discover_title": "Find existing S3 backups","system_backups_discover_description": "Open an Arcane system-recovery repository with its separate recovery key and add its snapshots to this table.","system_backups_discovered": "Found {count} new system backup(s).",- "system_backups_discover_failed": "Failed to discover system backups. Check the destination and recovery key."+ "system_backups_discover_failed": "Failed to discover system backups. Check the destination and recovery key.",+ "containers_status_dead": "Dead",+ "common_add": "Add",+ "common_custom": "Custom",+ "common_mode": "Mode",+ "common_general": "General",+ "common_resources": "Resources",+ "common_security": "Security",+ "cap_add": "Add capabilities",+ "cap_drop": "Drop capabilities",+ "memory_limit_mb": "Memory limit (MB)",+ "memory_swap_mb": "Memory + swap limit (MB)",+ "cpu_shares": "CPU shares",+ "static_ip": "Static IPv4 address",+ "aliases_note": "Comma-separated network aliases",+ "mount_options_note": "Options of existing mounts are preserved",+ "add_bind_mount_button": "Add Bind Mount",+ "image_pull_if_missing_note": "The image is only pulled if it is not present locally.",+ "edit_recreate_banner": "Applying changes recreates this container. It will briefly stop and come back with a new ID.",+ "edit_confirm_title": "Recreate container?",+ "edit_confirm_message": "\"{name}\" will be stopped, recreated with the new configuration, and restarted. It gets a new container ID. If it uses auto-remove, the original cannot be restored if recreation fails.",+ "edit_success": "Container updated",+ "edit_failed": "Failed to update container. If recreation failed, the original container was restored.",+ "network_connect": "Connect to network",+ "network_connect_success": "Container connected",+ "network_connect_failed": "Failed to connect container",+ "network_disconnect_confirm_title": "Disconnect from network?",+ "network_disconnect_confirm_message": "The container will be disconnected from \"{network}\" immediately.",+ "network_disconnect_success": "Container disconnected",+ "network_disconnect_failed": "Failed to disconnect container",+ "network_live_change_note": "Live network changes are lost when the container is recreated unless they are also saved via Edit.",+ "common_connect": "Connect",+ "common_disconnect": "Disconnect"}diff --git a/frontend/src/lib/components/containers/container-form/container-form-state.ts b/frontend/src/lib/components/containers/container-form/container-form-state.tsnew file mode 100644index 000000000..75bf8679f--- /dev/null+++ b/frontend/src/lib/components/containers/container-form/container-form-state.ts@@ -0,0 +1,401 @@+import { z } from 'zod/v4';+import { m } from '#lib/paraglide/messages';+import type {+ ContainerCreateRequest,+ ContainerEditConfigDto,+ ContainerEditRequest,+ ContainerHealthcheckCreate,+ ContainerHostConfigEdit,+ EndpointSettingsCreate,+ HostConfigCreate,+ MountDto,+ PortBinding+} from '#lib/types/docker';+import type { KeyValueRow } from '#lib/components/form/key-value-editor.svelte';+import type { PortMappingRow } from '#lib/components/form/port-mapping-editor.svelte';+import type { VolumeMountRow } from '#lib/components/form/volume-mount-editor.svelte';+import type { NetworkAttachmentRow } from '#lib/components/form/network-attachment-editor.svelte';++// Common Linux capabilities offered by the cap add/drop selectors.+export const LINUX_CAPABILITIES = [+ 'AUDIT_CONTROL',+ 'AUDIT_READ',+ 'AUDIT_WRITE',+ 'BLOCK_SUSPEND',+ 'BPF',+ 'CHECKPOINT_RESTORE',+ 'CHOWN',+ 'DAC_OVERRIDE',+ 'DAC_READ_SEARCH',+ 'FOWNER',+ 'FSETID',+ 'IPC_LOCK',+ 'IPC_OWNER',+ 'KILL',+ 'LEASE',+ 'LINUX_IMMUTABLE',+ 'MAC_ADMIN',+ 'MAC_OVERRIDE',+ 'MKNOD',+ 'NET_ADMIN',+ 'NET_BIND_SERVICE',+ 'NET_BROADCAST',+ 'NET_RAW',+ 'PERFMON',+ 'SETFCAP',+ 'SETGID',+ 'SETPCAP',+ 'SETUID',+ 'SYSLOG',+ 'SYS_ADMIN',+ 'SYS_BOOT',+ 'SYS_CHROOT',+ 'SYS_MODULE',+ 'SYS_NICE',+ 'SYS_PACCT',+ 'SYS_PTRACE',+ 'SYS_RAWIO',+ 'SYS_RESOURCE',+ 'SYS_TIME',+ 'SYS_TTY_CONFIG',+ 'WAKE_ALARM'+] as const;++export const containerFormSchema = z.object({+ name: z.string().min(1, m.container_name_required()),+ image: z.string().min(1, m.image_is_required()),+ command: z.string().optional().default(''),+ entrypoint: z.string().optional().default(''),+ workingDir: z.string().optional().default(''),+ user: z.string().optional().default(''),+ restartPolicy: z.string().default('no'),+ restartMaxRetries: z.coerce.number().min(0).default(0),+ memoryMb: z.coerce.number().min(0).default(0),+ memorySwapMb: z.coerce.number().default(0),+ cpus: z.coerce.number().min(0).default(0),+ cpuShares: z.coerce.number().min(0).default(0),+ privileged: z.boolean().default(false),+ readonlyRootfs: z.boolean().default(false),+ autoRemove: z.boolean().default(false),+ healthMode: z.enum(['inherit', 'custom', 'disable']).default('inherit'),+ healthTest: z.string().optional().default(''),+ healthInterval: z.coerce.number().min(0).default(0),+ healthTimeout: z.coerce.number().min(0).default(0),+ healthStartPeriod: z.coerce.number().min(0).default(0),+ healthRetries: z.coerce.number().min(0).default(0)+});++export type ContainerFormSchema = typeof containerFormSchema;+export type ContainerFormValues = z.infer<ContainerFormSchema>;++export type ContainerFormRows = {+ env: KeyValueRow[];+ labels: KeyValueRow[];+ ports: PortMappingRow[];+ volumes: VolumeMountRow[];+ networks: NetworkAttachmentRow[];+ capAdd: string[];+ capDrop: string[];+};++// Splits a command string into words, honoring single/double quotes so+// entries like `sh -c "echo hi"` survive the round-trip.+export function splitShellWords(input: string): string[] {+ const words: string[] = [];+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g;+ for (const match of input.matchAll(re)) {+ words.push(match[1] ?? match[2] ?? match[3] ?? '');+ }+ return words;+}++function joinShellWords(words: string[] | undefined): string {+ if (!words?.length) return '';+ return words.map((word) => (/\s/.test(word) ? `"${word}"` : word)).join(' ');+}++export function emptyContainerFormValues(): ContainerFormValues {+ return {+ name: '',+ image: '',+ command: '',+ entrypoint: '',+ workingDir: '',+ user: '',+ restartPolicy: 'no',+ restartMaxRetries: 0,+ memoryMb: 0,+ memorySwapMb: 0,+ cpus: 0,+ cpuShares: 0,+ privileged: false,+ readonlyRootfs: false,+ autoRemove: false,+ healthMode: 'inherit',+ healthTest: '',+ healthInterval: 0,+ healthTimeout: 0,+ healthStartPeriod: 0,+ healthRetries: 0+ };+}++export function emptyContainerFormRows(): ContainerFormRows {+ return { env: [], labels: [], ports: [], volumes: [], networks: [], capAdd: [], capDrop: [] };+}++function healthModeFromConfig(hc: ContainerHealthcheckCreate | undefined): ContainerFormValues['healthMode'] {+ if (!hc || !hc.test?.length) return 'inherit';+ if (hc.test[0] === 'NONE') return 'disable';+ return 'custom';+}++function healthTestToString(test: string[] | undefined): string {+ if (!test?.length) return '';+ if (test[0] === 'CMD-SHELL') return test.slice(1).join(' ');+ if (test[0] === 'CMD') return joinShellWords(test.slice(1));+ return joinShellWords(test);+}++export function formValuesFromEditConfig(cfg: ContainerEditConfigDto): ContainerFormValues {+ const hc = cfg.hostConfig;+ return {+ ...emptyContainerFormValues(),+ name: cfg.name,+ image: cfg.image,+ command: joinShellWords(cfg.command),+ entrypoint: joinShellWords(cfg.entrypoint),+ workingDir: cfg.workingDir ?? '',+ user: cfg.user ?? '',+ restartPolicy: hc.restartPolicy?.name || 'no',+ restartMaxRetries: hc.restartPolicy?.maximumRetryCount ?? 0,+ memoryMb: hc.memory ? Math.round(hc.memory / (1024 * 1024)) : 0,+ memorySwapMb: hc.memorySwap && hc.memorySwap > 0 ? Math.round(hc.memorySwap / (1024 * 1024)) : 0,+ cpus: hc.nanoCpus ? hc.nanoCpus / 1e9 : 0,+ cpuShares: hc.cpuShares ?? 0,+ privileged: !!hc.privileged,+ readonlyRootfs: !!hc.readonlyRootfs,+ autoRemove: !!hc.autoRemove,+ healthMode: healthModeFromConfig(cfg.healthcheck),+ healthTest: cfg.healthcheck?.test?.[0] === 'NONE' ? '' : healthTestToString(cfg.healthcheck?.test),+ healthInterval: cfg.healthcheck?.interval ?? 0,+ healthTimeout: cfg.healthcheck?.timeout ?? 0,+ healthStartPeriod: cfg.healthcheck?.startPeriod ?? 0,+ healthRetries: cfg.healthcheck?.retries ?? 0+ };+}++function parseBindString(bind: string): VolumeMountRow {+ const parts = bind.split(':');+ const source = parts[0] ?? '';+ const target = parts[1] ?? '';+ const optionTokens = (parts[2] ?? '').split(',').filter(Boolean);+ const readOnly = optionTokens.includes('ro');+ const rawOptions = optionTokens.filter((token) => token !== 'ro' && token !== 'rw').join(',');+ const kind = source.startsWith('/') || source.startsWith('.') || source.startsWith('~') ? 'bind' : 'volume';+ return { kind, source, target, readOnly, rawOptions: rawOptions || undefined };+}++function serializeBindRow(row: VolumeMountRow): string {+ const options = [...(row.rawOptions ? row.rawOptions.split(',').filter(Boolean) : [])];+ if (row.readOnly) options.push('ro');+ const suffix = options.length > 0 ? `:${options.join(',')}` : '';+ return `${row.source.trim()}:${row.target.trim()}${suffix}`;+}++export function rowsFromEditConfig(cfg: ContainerEditConfigDto): ContainerFormRows {+ const rows = emptyContainerFormRows();++ for (const entry of cfg.environment ?? []) {+ const eq = entry.indexOf('=');+ rows.env.push(eq === -1 ? { key: entry, value: '' } : { key: entry.slice(0, eq), value: entry.slice(eq + 1) });+ }++ for (const [key, value] of Object.entries(cfg.labels ?? {})) {+ rows.labels.push({ key, value });+ }++ for (const [portSpec, bindings] of Object.entries(cfg.hostConfig.portBindings ?? {})) {+ const [portPart, protocolPart] = portSpec.split('/');+ for (const binding of bindings) {+ rows.ports.push({+ hostIp: binding.hostIp ?? '',+ hostPort: binding.hostPort,+ containerPort: portPart ?? '',+ protocol: protocolPart === 'udp' ? 'udp' : 'tcp'+ });+ }+ }++ for (const bind of cfg.hostConfig.binds ?? []) {+ rows.volumes.push(parseBindString(bind));+ }+ for (const mount of cfg.hostConfig.mounts ?? []) {+ rows.volumes.push({+ kind: 'mount',+ mountType: mount.type,+ source: mount.source,+ target: mount.target,+ readOnly: !!mount.readOnly+ });+ }++ for (const [network, endpoint] of Object.entries(cfg.networks ?? {})) {+ rows.networks.push({+ network,+ aliases: (endpoint.aliases ?? []).join(', '),+ ipv4Address: endpoint.ipv4Address ?? ''+ });+ }++ rows.capAdd = [...(cfg.hostConfig.capAdd ?? [])];+ rows.capDrop = [...(cfg.hostConfig.capDrop ?? [])];++ return rows;+}++function buildHealthcheck(values: ContainerFormValues): ContainerHealthcheckCreate | undefined {+ if (values.healthMode === 'disable') return { test: ['NONE'] };+ if (values.healthMode !== 'custom' || !values.healthTest.trim()) return undefined;+ return {+ test: ['CMD-SHELL', values.healthTest.trim()],+ interval: values.healthInterval || undefined,+ timeout: values.healthTimeout || undefined,+ startPeriod: values.healthStartPeriod || undefined,+ retries: values.healthRetries || undefined+ };+}++function buildEnv(rows: ContainerFormRows): string[] {+ return rows.env.filter((row) => row.key.trim()).map((row) => `${row.key.trim()}=${row.value}`);+}++function buildLabels(rows: ContainerFormRows): Record<string, string> {+ const labels: Record<string, string> = {};+ for (const row of rows.labels) {+ if (row.key.trim()) labels[row.key.trim()] = row.value;+ }+ return labels;+}++function buildPortBindings(rows: ContainerFormRows): Record<string, PortBinding[]> {+ const bindings: Record<string, PortBinding[]> = {};+ for (const row of rows.ports) {+ if (!row.containerPort.trim()) continue;+ const key = `${row.containerPort.trim()}/${row.protocol}`;+ const binding: PortBinding = { hostPort: row.hostPort.trim() };+ if (row.hostIp.trim()) binding.hostIp = row.hostIp.trim();+ bindings[key] = [...(bindings[key] ?? []), binding];+ }+ return bindings;+}++function buildBinds(rows: ContainerFormRows): string[] {+ return rows.volumes.filter((row) => row.kind !== 'mount' && row.source.trim() && row.target.trim()).map(serializeBindRow);+}++function buildMounts(rows: ContainerFormRows): MountDto[] {+ return rows.volumes+ .filter((row) => row.kind === 'mount')+ .map((row) => ({+ type: row.mountType ?? 'volume',+ source: row.source,+ target: row.target,+ readOnly: row.readOnly+ }));+}++function buildEndpoints(rows: ContainerFormRows): Record<string, EndpointSettingsCreate> {+ const endpoints: Record<string, EndpointSettingsCreate> = {};+ for (const row of rows.networks) {+ if (!row.network.trim()) continue;+ const endpoint: EndpointSettingsCreate = {};+ const aliases = row.aliases+ .split(',')+ .map((alias) => alias.trim())+ .filter(Boolean);+ if (aliases.length > 0) endpoint.aliases = aliases;+ if (row.ipv4Address.trim()) endpoint.ipv4Address = row.ipv4Address.trim();+ endpoints[row.network.trim()] = endpoint;+ }+ return endpoints;+}++function buildRestartPolicy(values: ContainerFormValues) {+ return {+ name: values.restartPolicy as 'no' | 'always' | 'on-failure' | 'unless-stopped',+ maximumRetryCount: values.restartPolicy === 'on-failure' ? values.restartMaxRetries : undefined+ };+}++export function toCreateRequest(values: ContainerFormValues, rows: ContainerFormRows): ContainerCreateRequest {+ const env = buildEnv(rows);+ const labels = buildLabels(rows);+ const portBindings = buildPortBindings(rows);+ const binds = buildBinds(rows);+ const endpoints = buildEndpoints(rows);++ const hostConfig: HostConfigCreate = {+ binds: binds.length > 0 ? binds : undefined,+ portBindings: Object.keys(portBindings).length > 0 ? portBindings : undefined,+ restartPolicy: values.restartPolicy !== 'no' ? buildRestartPolicy(values) : undefined,+ privileged: values.privileged || undefined,+ readonlyRootfs: values.readonlyRootfs || undefined,+ autoRemove: values.autoRemove || undefined,+ memory: values.memoryMb > 0 ? Math.round(values.memoryMb * 1024 * 1024) : undefined,+ memorySwap: values.memorySwapMb > 0 ? Math.round(values.memorySwapMb * 1024 * 1024) : undefined,+ nanoCpus: values.cpus > 0 ? Math.round(values.cpus * 1e9) : undefined,+ cpuShares: values.cpuShares > 0 ? values.cpuShares : undefined,+ capAdd: rows.capAdd.length > 0 ? [...rows.capAdd] : undefined,+ capDrop: rows.capDrop.length > 0 ? [...rows.capDrop] : undefined+ };++ return {+ name: values.name.trim(),+ image: values.image.trim(),+ cmd: values.command.trim() ? splitShellWords(values.command.trim()) : undefined,+ entrypoint: values.entrypoint.trim() ? splitShellWords(values.entrypoint.trim()) : undefined,+ workingDir: values.workingDir.trim() || undefined,+ user: values.user.trim() || undefined,+ env: env.length > 0 ? env : undefined,+ labels: Object.keys(labels).length > 0 ? labels : undefined,+ healthcheck: buildHealthcheck(values),+ hostConfig,+ networkingConfig: Object.keys(endpoints).length > 0 ? { endpointsConfig: endpoints } : undefined+ };+}++// The edit request always carries every form-owned section (empty included);+// the backend preserves anything the form does not own.+export function toEditRequest(values: ContainerFormValues, rows: ContainerFormRows): ContainerEditRequest {+ const hostConfig: ContainerHostConfigEdit = {+ binds: buildBinds(rows),+ mounts: buildMounts(rows),+ portBindings: buildPortBindings(rows),+ restartPolicy: buildRestartPolicy(values),+ privileged: values.privileged,+ readonlyRootfs: values.readonlyRootfs,+ autoRemove: values.autoRemove,+ memory: Math.round(values.memoryMb * 1024 * 1024),+ memorySwap: values.memorySwapMb > 0 ? Math.round(values.memorySwapMb * 1024 * 1024) : 0,+ nanoCpus: Math.round(values.cpus * 1e9),+ cpuShares: values.cpuShares,+ capAdd: [...rows.capAdd],+ capDrop: [...rows.capDrop]+ };++ return {+ name: values.name.trim(),+ image: values.image.trim(),+ workingDir: values.workingDir.trim(),+ user: values.user.trim(),+ command: splitShellWords(values.command.trim()),+ entrypoint: splitShellWords(values.entrypoint.trim()),+ environment: buildEnv(rows),+ labels: buildLabels(rows),+ healthcheck: values.healthMode === 'inherit' ? undefined : buildHealthcheck(values),+ clearHealthcheck: values.healthMode === 'inherit',+ hostConfig,+ networkingConfig: { endpointsConfig: buildEndpoints(rows) }+ };+}diff --git a/frontend/src/lib/components/containers/container-form/container-form.svelte b/frontend/src/lib/components/containers/container-form/container-form.sveltenew file mode 100644index 000000000..775811d62--- /dev/null+++ b/frontend/src/lib/components/containers/container-form/container-form.svelte@@ -0,0 +1,455 @@+<script lang="ts">+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import * as Tabs from '#lib/components/ui/tabs/index.js';+ import { TabBar, type TabItem } from '#lib/components/tab-bar/index.js';+ import FormInput from '#lib/components/form/form-input.svelte';+ import SelectWithLabel from '#lib/components/form/select-with-label.svelte';+ import SearchableSelect from '#lib/components/form/searchable-select.svelte';+ import KeyValueEditor from '#lib/components/form/key-value-editor.svelte';+ import PortMappingEditor from '#lib/components/form/port-mapping-editor.svelte';+ import VolumeMountEditor from '#lib/components/form/volume-mount-editor.svelte';+ import NetworkAttachmentEditor from '#lib/components/form/network-attachment-editor.svelte';+ import { Checkbox } from '#lib/components/ui/checkbox/index.js';+ import { Label } from '#lib/components/ui/label/index.js';+ import { Input } from '#lib/components/ui/input/index.js';+ import { Badge } from '#lib/components/ui/badge/index.js';+ import { m } from '#lib/paraglide/messages';+ import { CloseIcon, ContainersIcon, NetworksIcon, SettingsIcon, VariableIcon, VolumesIcon } from '#lib/icons';+ import { preventDefault, createForm } from '#lib/utils/settings';+ import { createQuery } from '@tanstack/svelte-query';+ import { queryKeys } from '#lib/query/query-keys';+ import { volumeService } from '#lib/services/volume-service';+ import { networkService } from '#lib/services/network-service';+ import { imageService } from '#lib/services/image-service';+ import { environmentStore } from '#lib/stores/environment.store.svelte';+ import type { ImageSearchResultDto } from '#lib/types/docker';+ import { LINUX_CAPABILITIES, containerFormSchema, type ContainerFormRows } from './container-form-state';++ let {+ mode,+ form,+ rows = $bindable(),+ submitting = false,+ cancelHref = '/containers',+ onSubmit+ }: {+ mode: 'create' | 'edit';+ form: ReturnType<typeof createForm<typeof containerFormSchema>>;+ rows: ContainerFormRows;+ submitting?: boolean;+ cancelHref?: string;+ onSubmit: () => void;+ } = $props();++ // The form instance is created once by the page and never swapped.+ // svelte-ignore state_referenced_locally+ const inputs = form.inputs;+ const envId = $derived(environmentStore.selected?.id || '0');++ let selectedTab = $state('general');++ const tabItems: TabItem[] = [+ { value: 'general', label: m.common_general(), icon: ContainersIcon },+ { value: 'environment', label: m.resource_environment_cap(), icon: VariableIcon },+ { value: 'ports', label: m.common_ports(), icon: NetworksIcon },+ { value: 'volumes', label: m.resource_volumes_cap(), icon: VolumesIcon },+ { value: 'networks', label: m.resource_networks_cap(), icon: NetworksIcon },+ { value: 'advanced', label: m.common_advanced(), icon: SettingsIcon }+ ];++ const restartPolicies = [+ { value: 'no', label: m.common_no() },+ { value: 'always', label: m.common_always() },+ { value: 'unless-stopped', label: m.restart_policy_unless_stopped() },+ { value: 'on-failure', label: m.restart_policy_on_failure() }+ ];++ const healthModes = [+ { value: 'inherit', label: m.health_inherit_from_image() },+ { value: 'custom', label: m.common_custom() },+ { value: 'disable', label: m.common_disabled() }+ ];++ const listOptions = { pagination: { page: 1, limit: 500 } };+ const volumesQuery = createQuery(() => ({+ queryKey: queryKeys.volumes.table(envId, listOptions),+ queryFn: () => volumeService.getVolumes(listOptions)+ }));+ const networksQuery = createQuery(() => ({+ queryKey: queryKeys.networks.list(envId, listOptions),+ queryFn: () => networkService.getNetworks(listOptions)+ }));++ const volumeNames = $derived((volumesQuery.data?.data ?? []).map((volume) => volume.name));+ const networkNames = $derived(+ (networksQuery.data?.data ?? []).map((network) => network.name).filter((name) => name !== 'host' && name !== 'none')+ );++ // Image suggestions (debounced registry search); free text stays valid.+ let imageSuggestions = $state<ImageSearchResultDto[]>([]);+ let imageSearchTimer: ReturnType<typeof setTimeout> | undefined;+ function onImageInput() {+ clearTimeout(imageSearchTimer);+ const term = $inputs.image.value.trim();+ if (term.length < 2 || term.includes(':')) {+ imageSuggestions = [];+ return;+ }+ imageSearchTimer = setTimeout(async () => {+ try {+ imageSuggestions = (await imageService.searchImages(term)).slice(0, 6);+ } catch {+ imageSuggestions = [];+ }+ }, 350);+ }++ function applyImageSuggestion(name: string) {+ form.setValue('image', name);+ imageSuggestions = [];+ }++ function handleSubmit() {+ onSubmit();+ // Required fields live on the general tab; bring failed validation into view.+ if ($inputs.name.error || $inputs.image.error) {+ selectedTab = 'general';+ }+ }++ const availableCapAdd = $derived(+ LINUX_CAPABILITIES.map((cap) => ({ value: cap, label: cap })).filter((item) => !rows.capAdd.includes(item.value))+ );+ const availableCapDrop = $derived(+ [{ value: 'ALL', label: 'ALL' }, ...LINUX_CAPABILITIES.map((cap) => ({ value: cap, label: cap }))].filter(+ (item) => !rows.capDrop.includes(item.value)+ )+ );+</script>++{#snippet groupTitle(title: string, description?: string)}+ <div>+ <h3 class="text-base font-semibold">{title}</h3>+ {#if description}+ <p class="mt-1 text-xs text-muted-foreground">{description}</p>+ {/if}+ </div>+{/snippet}++<form class="flex min-h-0 flex-col" onsubmit={preventDefault(handleSubmit)}>+ <Tabs.Root value={selectedTab} class="flex min-h-0 flex-1 flex-col">+ <div class="border-b pb-3">+ <TabBar items={tabItems} value={selectedTab} onValueChange={(value) => (selectedTab = value)} />+ </div>++ <div class="flex-1 py-6">+ <!-- General -->+ <Tabs.Content value="general" class="mt-0 space-y-6">+ <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">+ <div class="space-y-2">+ <Label for="container-name" class="text-sm font-medium">+ {m.container_name_label()} <span class="text-destructive">*</span>+ </Label>+ <Input+ id="container-name"+ type="text"+ placeholder={m.container_name_placeholder()}+ disabled={submitting}+ bind:value={$inputs.name.value}+ class={$inputs.name.error ? 'border-destructive' : ''}+ />+ {#if $inputs.name.error}+ <p class="text-xs text-destructive">{$inputs.name.error}</p>+ {/if}+ </div>+ <div class="relative space-y-2">+ <Label for="container-image" class="text-sm font-medium">+ {m.common_image()} <span class="text-destructive">*</span>+ </Label>+ <Input+ id="container-image"+ type="text"+ placeholder={m.nginx_latest_placeholder()}+ disabled={submitting}+ bind:value={$inputs.image.value}+ oninput={onImageInput}+ class={$inputs.image.error ? 'border-destructive' : ''}+ autocomplete="off"+ />+ {#if imageSuggestions.length > 0}+ <div class="absolute z-10 w-full rounded-md border bg-popover shadow-md">+ {#each imageSuggestions as suggestion (suggestion.name)}+ <button+ type="button"+ class="block w-full px-3 py-2 text-left text-sm hover:bg-accent"+ onclick={() => applyImageSuggestion(suggestion.name)}+ >+ <span class="font-mono">{suggestion.name}</span>+ {#if suggestion.official}+ <Badge variant="secondary" class="ml-2 text-[10px]">official</Badge>+ {/if}+ </button>+ {/each}+ </div>+ {/if}+ {#if $inputs.image.error}+ <p class="text-xs text-destructive">{$inputs.image.error}</p>+ {/if}+ {#if mode === 'edit'}+ <p class="text-xs text-muted-foreground">{m.image_pull_if_missing_note()}</p>+ {/if}+ </div>+ <FormInput+ label={m.common_command()}+ type="text"+ placeholder={m.container_command_placeholder()}+ disabled={submitting}+ bind:input={$inputs.command}+ />+ <FormInput+ label={m.common_entrypoint()}+ type="text"+ placeholder="/docker-entrypoint.sh"+ disabled={submitting}+ bind:input={$inputs.entrypoint}+ />+ <FormInput+ label={m.common_working_directory()}+ type="text"+ placeholder={m.app_placeholder()}+ disabled={submitting}+ bind:input={$inputs.workingDir}+ />+ <FormInput+ label={m.common_user()}+ type="text"+ placeholder={m.container_user_placeholder()}+ disabled={submitting}+ bind:input={$inputs.user}+ />+ </div>+ </Tabs.Content>++ <!-- Environment (env vars + labels) -->+ <Tabs.Content value="environment" class="mt-0 space-y-8">+ <div class="space-y-4">+ {@render groupTitle(m.common_environment_variables())}+ <KeyValueEditor bind:rows={rows.env} disabled={submitting} />+ </div>+ <div class="space-y-4">+ {@render groupTitle(m.common_labels())}+ <KeyValueEditor+ bind:rows={rows.labels}+ disabled={submitting}+ keyPlaceholder="com.example.key"+ valuePlaceholder="value"+ />+ </div>+ </Tabs.Content>++ <!-- Ports -->+ <Tabs.Content value="ports" class="mt-0 space-y-4">+ {@render groupTitle(m.common_port_mappings())}+ <PortMappingEditor bind:rows={rows.ports} disabled={submitting} />+ </Tabs.Content>++ <!-- Volumes -->+ <Tabs.Content value="volumes" class="mt-0 space-y-4">+ {@render groupTitle(m.resource_volumes_cap(), mode === 'edit' ? m.mount_options_note() : undefined)}+ <VolumeMountEditor bind:rows={rows.volumes} volumes={volumeNames} disabled={submitting} />+ </Tabs.Content>++ <!-- Networks -->+ <Tabs.Content value="networks" class="mt-0 space-y-4">+ {@render groupTitle(m.resource_networks_cap(), m.aliases_note())}+ <NetworkAttachmentEditor bind:rows={rows.networks} networks={networkNames} disabled={submitting} />+ </Tabs.Content>++ <!-- Advanced (resources, security, healthcheck) -->+ <Tabs.Content value="advanced" class="mt-0 space-y-8">+ <div class="space-y-4">+ {@render groupTitle(m.common_resources())}+ <div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">+ <FormInput+ label={m.memory_limit_mb()}+ type="number"+ placeholder="0"+ disabled={submitting}+ bind:input={$inputs.memoryMb}+ />+ <FormInput+ label={m.memory_swap_mb()}+ type="number"+ placeholder="0"+ disabled={submitting}+ bind:input={$inputs.memorySwapMb}+ />+ <FormInput label={m.common_cpus()} type="number" placeholder="0" disabled={submitting} bind:input={$inputs.cpus} />+ <FormInput+ label={m.cpu_shares()}+ type="number"+ placeholder="0"+ disabled={submitting}+ bind:input={$inputs.cpuShares}+ />+ </div>+ <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">+ <SelectWithLabel+ id="restart-policy"+ bind:value={$inputs.restartPolicy.value}+ label={m.restart_policy_label()}+ options={restartPolicies}+ placeholder={m.container_select_restart_policy()}+ disabled={submitting}+ />+ {#if $inputs.restartPolicy.value === 'on-failure'}+ <FormInput+ label={m.max_retry_label()}+ type="number"+ placeholder={m.max_retry_placeholder()}+ disabled={submitting}+ bind:input={$inputs.restartMaxRetries}+ />+ {/if}+ </div>+ <div class="flex items-center space-x-2">+ <Checkbox id="auto-remove" bind:checked={$inputs.autoRemove.value} disabled={submitting} />+ <Label for="auto-remove" class="text-sm font-normal">{m.auto_remove_label()}</Label>+ </div>+ </div>++ <div class="space-y-4 border-t border-border/50 pt-6">+ {@render groupTitle(m.common_security())}+ <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">+ <div class="flex items-center space-x-2">+ <Checkbox id="privileged" bind:checked={$inputs.privileged.value} disabled={submitting} />+ <Label for="privileged" class="text-sm font-normal">{m.privileged_label()}</Label>+ </div>+ <div class="flex items-center space-x-2">+ <Checkbox id="readonly-rootfs" bind:checked={$inputs.readonlyRootfs.value} disabled={submitting} />+ <Label for="readonly-rootfs" class="text-sm font-normal">{m.readonly_rootfs_label()}</Label>+ </div>+ </div>+ <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">+ <div class="space-y-2">+ <Label class="text-sm font-medium">{m.cap_add()}</Label>+ <div class="flex flex-wrap gap-1.5">+ {#each rows.capAdd as cap (cap)}+ <Badge variant="secondary" class="gap-1 font-mono text-xs">+ {cap}+ <button+ type="button"+ onclick={() => (rows.capAdd = rows.capAdd.filter((c) => c !== cap))}+ disabled={submitting}+ >+ <CloseIcon class="size-3" />+ </button>+ </Badge>+ {/each}+ </div>+ <SearchableSelect+ items={availableCapAdd}+ showCheckboxes={false}+ disabled={submitting}+ onSelect={(cap) => {+ if (cap) rows.capAdd = [...rows.capAdd, cap];+ }}+ />+ </div>+ <div class="space-y-2">+ <Label class="text-sm font-medium">{m.cap_drop()}</Label>+ <div class="flex flex-wrap gap-1.5">+ {#each rows.capDrop as cap (cap)}+ <Badge variant="secondary" class="gap-1 font-mono text-xs">+ {cap}+ <button+ type="button"+ onclick={() => (rows.capDrop = rows.capDrop.filter((c) => c !== cap))}+ disabled={submitting}+ >+ <CloseIcon class="size-3" />+ </button>+ </Badge>+ {/each}+ </div>+ <SearchableSelect+ items={availableCapDrop}+ showCheckboxes={false}+ disabled={submitting}+ onSelect={(cap) => {+ if (cap) rows.capDrop = [...rows.capDrop, cap];+ }}+ />+ </div>+ </div>+ </div>++ <div class="space-y-4 border-t border-border/50 pt-6">+ {@render groupTitle(m.health_configuration())}+ <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">+ <SelectWithLabel+ id="health-mode"+ bind:value={$inputs.healthMode.value}+ label={m.common_mode()}+ options={healthModes}+ disabled={submitting}+ />+ {#if $inputs.healthMode.value === 'custom'}+ <FormInput+ label={m.health_test_command()}+ type="text"+ placeholder="curl -f http://localhost/ || exit 1"+ disabled={submitting}+ bind:input={$inputs.healthTest}+ />+ {/if}+ </div>+ {#if $inputs.healthMode.value === 'custom'}+ <div class="grid grid-cols-2 gap-6 lg:grid-cols-4">+ <FormInput+ label={`${m.health_interval()} (s)`}+ type="number"+ placeholder="30"+ disabled={submitting}+ bind:input={$inputs.healthInterval}+ />+ <FormInput+ label={`${m.health_timeout()} (s)`}+ type="number"+ placeholder="30"+ disabled={submitting}+ bind:input={$inputs.healthTimeout}+ />+ <FormInput+ label={`${m.health_start_period()} (s)`}+ type="number"+ placeholder="0"+ disabled={submitting}+ bind:input={$inputs.healthStartPeriod}+ />+ <FormInput+ label={m.health_retries()}+ type="number"+ placeholder="3"+ disabled={submitting}+ bind:input={$inputs.healthRetries}+ />+ </div>+ {/if}+ </div>+ </Tabs.Content>+ </div>+ </Tabs.Root>++ <div class="flex flex-col-reverse gap-2 border-t pt-4 pb-6 sm:flex-row sm:justify-end">+ <ArcaneButton action="cancel" tone="outline" href={cancelHref} disabled={submitting} class="w-full sm:w-auto" />+ <ArcaneButton+ action={mode === 'create' ? 'create' : 'save'}+ type="submit"+ disabled={submitting}+ loading={submitting}+ class="w-full sm:w-auto"+ customLabel={mode === 'create' ? m.common_create_button({ resource: m.container() }) : m.common_save()}+ />+ </div>+</form>diff --git a/frontend/src/lib/components/dialogs/create-container-dialog.svelte b/frontend/src/lib/components/dialogs/create-container-dialog.sveltedeleted file mode 100644index 856c84632..000000000--- a/frontend/src/lib/components/dialogs/create-container-dialog.svelte+++ /dev/null@@ -1,750 +0,0 @@-<script lang="ts">- import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';- import * as Tabs from '#lib/components/ui/tabs/index.js';- import { TabBar, type TabItem } from '#lib/components/tab-bar/index.js';- import { ArcaneButton } from '#lib/components/arcane-button/index.js';- import FormInput from '#lib/components/form/form-input.svelte';- import { Checkbox } from '#lib/components/ui/checkbox/index.js';- import { Label } from '#lib/components/ui/label/index.js';- import { Input } from '#lib/components/ui/input/index.js';- import { Textarea } from '#lib/components/ui/textarea/index.js';- import type { ContainerCreateRequest } from '#lib/types/docker';- import { z } from 'zod/v4';- import { createForm, preventDefault } from '#lib/utils/settings';- import { parseKeyValuePairs } from '#lib/utils/form-parsers';- import SelectWithLabel from '../form/select-with-label.svelte';- import { m } from '#lib/paraglide/messages';- import {- SettingsIcon,- SecurityIcon,- AddIcon,- NetworksIcon,- VolumesIcon,- CloseIcon,- VariableIcon,- ContainersIcon- } from '#lib/icons';-- type CreateContainerFormProps = {- open: boolean;- onSubmit: (data: ContainerCreateRequest) => void;- isLoading: boolean;- };-- let { open = $bindable(false), onSubmit, isLoading }: CreateContainerFormProps = $props();-- let selectedTab = $state('basic');-- const tabItems: TabItem[] = [- { value: 'basic', label: m.common_basic(), icon: ContainersIcon },- { value: 'environment', label: m.resource_environment_cap(), icon: VariableIcon },- { value: 'ports', label: m.common_ports(), icon: NetworksIcon },- { value: 'volumes', label: m.resource_volumes_cap(), icon: VolumesIcon },- { value: 'network', label: m.tabs_network_security(), icon: SecurityIcon },- { value: 'advanced', label: m.common_advanced(), icon: SettingsIcon }- ];-- const restartPolicies = [- { value: 'no', label: m.common_no() },- { value: 'always', label: m.common_always() },- { value: 'unless-stopped', label: m.restart_policy_unless_stopped() },- { value: 'on-failure', label: m.restart_policy_on_failure() }- ];-- const formSchema = z.object({- containerName: z.string().min(1, m.container_name_required()),- image: z.string().min(1, m.image_is_required()),- command: z.string().optional().default(''),- workingDir: z.string().optional().default(''),- user: z.string().optional().default(''),- hostname: z.string().optional().default(''),- domainname: z.string().optional().default(''),- attachStdout: z.boolean().default(true),- attachStderr: z.boolean().default(true),- attachStdin: z.boolean().default(false),- tty: z.boolean().default(false),- openStdin: z.boolean().default(false),- stdinOnce: z.boolean().default(false),- networkDisabled: z.boolean().default(false),- publishAllPorts: z.boolean().default(false),- privileged: z.boolean().default(false),- readonlyRootfs: z.boolean().default(false),- autoRemove: z.boolean().default(false),- restartPolicy: z.string().default('no'),- restartMaxRetries: z.number().min(0).optional().default(0),- environmentVars: z.string().optional().default(''),- labels: z.string().optional().default(''),- exposedPorts: z.string().optional().default(''),- portBindings: z.string().optional().default(''),- volumes: z.string().optional().default('')- });-- let formData = $derived({- containerName: '',- image: '',- command: '',- workingDir: '',- user: '',- hostname: '',- domainname: '',- attachStdout: true,- attachStderr: true,- attachStdin: false,- tty: false,- openStdin: false,- stdinOnce: false,- networkDisabled: false,- publishAllPorts: false,- privileged: false,- readonlyRootfs: false,- autoRemove: false,- restartPolicy: 'no',- restartMaxRetries: 0,- environmentVars: '',- labels: '',- exposedPorts: '',- portBindings: '',- volumes: ''- });-- let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));-- // Dynamic states for complex inputs- let envVars = $state<{ key: string; value: string }[]>([{ key: '', value: '' }]);- let portMappings = $state<{ container: string; host: string; protocol: string }[]>([- { container: '', host: '', protocol: 'tcp' }- ]);- let volumeMounts = $state<{ source: string; destination: string; readonly: boolean }[]>([- { source: '', destination: '', readonly: false }- ]);-- function parsePortList(text: string): Record<string, {}> {- if (!text?.trim()) return {};-- const result: Record<string, {}> = {};- const ports = text- .split(',')- .map((p) => p.trim())- .filter(Boolean);-- for (const port of ports) {- if (port.includes('/')) {- result[port] = {};- } else {- result[`${port}/tcp`] = {};- }- }-- return result;- }-- // fallow-ignore-next-line code-duplication -- add/remove row-editor; divergent state shape from customize/variables- function addEnvVar() {- envVars = [...envVars, { key: '', value: '' }];- }-- function removeEnvVar(index: number) {- envVars = envVars.filter((_, i) => i !== index);- }-- function addPortMapping() {- portMappings = [...portMappings, { container: '', host: '', protocol: 'tcp' }];- }-- function removePortMapping(index: number) {- portMappings = portMappings.filter((_, i) => i !== index);- }-- function addVolumeMount() {- volumeMounts = [...volumeMounts, { source: '', destination: '', readonly: false }];- }-- function removeVolumeMount(index: number) {- volumeMounts = volumeMounts.filter((_, i) => i !== index);- }-- function handleSubmit() {- const data = form.validate();- if (!data) return;-- // Parse environment variables- const textEnvVars = parseKeyValuePairs(data.environmentVars || '');- const dynamicEnvVars: string[] = [];-- envVars.forEach((env) => {- if (env.key.trim()) {- dynamicEnvVars.push(`${env.key.trim()}=${env.value.trim()}`);- }- });-- Object.entries(textEnvVars).forEach(([key, value]) => {- dynamicEnvVars.push(`${key}=${value}`);- });-- // Parse port bindings- const dynamicPortBindings: Record<string, Array<{ hostPort: string }>> = {};- portMappings.forEach((mapping) => {- if (mapping.container.trim() && mapping.host.trim()) {- const containerPort = `${mapping.container.trim()}/${mapping.protocol}`;- dynamicPortBindings[containerPort] = [{ hostPort: mapping.host.trim() }];- }- });-- // Parse volume bindings- const dynamicBinds: string[] = [];- volumeMounts.forEach((mount) => {- if (mount.source.trim() && mount.destination.trim()) {- const bind = mount.readonly- ? `${mount.source.trim()}:${mount.destination.trim()}:ro`- : `${mount.source.trim()}:${mount.destination.trim()}`;- dynamicBinds.push(bind);- }- });-- // Parse volume text input- const textVolumes =- data.volumes- ?.split('\n')- .map((v) => v.trim())- .filter(Boolean) || [];- const allBinds = [...dynamicBinds, ...textVolumes];-- const labels = parseKeyValuePairs(data.labels || '');- const exposedPorts = parsePortList(data.exposedPorts || '');-- const options: ContainerCreateRequest = {- name: data.containerName.trim(),- image: data.image.trim(),- cmd: data.command.trim() ? data.command.trim().split(' ') : undefined,- workingDir: data.workingDir.trim() || undefined,- user: data.user.trim() || undefined,- hostname: data.hostname.trim() || undefined,- domainname: data.domainname.trim() || undefined,- attachStdout: data.attachStdout,- attachStderr: data.attachStderr,- attachStdin: data.attachStdin,- networkDisabled: data.networkDisabled,- ...(data.tty && { tty: true }),- ...(data.openStdin && { openStdin: true }),- ...(data.stdinOnce && { stdinOnce: true }),- env: dynamicEnvVars.length > 0 ? dynamicEnvVars : undefined,- labels: Object.keys(labels).length > 0 ? labels : undefined,- exposedPorts: Object.keys(exposedPorts).length > 0 ? exposedPorts : undefined,- hostConfig: {- binds: allBinds.length > 0 ? allBinds : undefined,- portBindings: Object.keys(dynamicPortBindings).length > 0 ? dynamicPortBindings : undefined,- networkMode: data.networkDisabled ? 'none' : undefined,- ...(data.privileged && { privileged: true }),- ...(data.readonlyRootfs && { readonlyRootfs: true }),- ...(data.publishAllPorts && { publishAllPorts: true }),- ...(data.autoRemove && { autoRemove: true }),- ...(data.restartPolicy !== 'no' && {- restartPolicy: {- name: data.restartPolicy as 'no' | 'always' | 'on-failure' | 'unless-stopped',- maximumRetryCount: data.restartPolicy === 'on-failure' ? data.restartMaxRetries : undefined- }- })- }- };-- onSubmit(options);- }-- function handleOpenChange(newOpenState: boolean) {- open = newOpenState;- if (!newOpenState) {- // Reset form data- form.reset();- envVars = [{ key: '', value: '' }];- portMappings = [{ container: '', host: '', protocol: 'tcp' }];- volumeMounts = [{ source: '', destination: '', readonly: false }];- selectedTab = 'basic';- }- }-- function onTabChange(value: string) {- selectedTab = value;- }-</script>--<ResponsiveDialog- {open}- onOpenChange={handleOpenChange}- title={m.create_container_title()}- description={m.create_container_description()}- contentClass="sm:max-w-[95vw] md:max-w-[90vw] lg:max-w-[1200px]"- class="p-0"->- {#snippet children()}- <form id="create-container-form" onsubmit={preventDefault(handleSubmit)} class="flex min-h-0 flex-col">- <Tabs.Root value={selectedTab} class="flex min-h-0 flex-1 flex-col">- <!-- Tab Navigation -->- <div class="border-b px-2 py-3 sm:px-4">- <TabBar items={tabItems} value={selectedTab} onValueChange={onTabChange} />- </div>-- <!-- Tab Content -->- <div class="min-h-0 flex-1 overflow-y-auto px-4 py-6 sm:px-6">- <!-- Basic Tab -->- <Tabs.Content value="basic" class="mt-0 space-y-6">- <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">- <div class="space-y-3">- <Label for="container-name" class="text-sm font-medium">- {m.container_name_label()} <span class="text-destructive">*</span>- </Label>- <Input- id="container-name"- type="text"- placeholder={m.container_name_placeholder()}- disabled={isLoading}- bind:value={$inputs.containerName.value}- class={$inputs.containerName.error ? 'border-destructive' : ''}- />- {#if $inputs.containerName.error}- <p class="mt-1 text-xs text-destructive">{$inputs.containerName.error}</p>- {/if}- <p class="text-xs text-muted-foreground">{m.container_name_description()}</p>- </div>-- <div class="space-y-3">- <Label for="image" class="text-sm font-medium">- {m.common_image()} <span class="text-destructive">*</span>- </Label>- <Input- id="image"- type="text"- placeholder={m.nginx_latest_placeholder()}- disabled={isLoading}- bind:value={$inputs.image.value}- class={$inputs.image.error ? 'border-destructive' : ''}- />- {#if $inputs.image.error}- <p class="mt-1 text-xs text-destructive">{$inputs.image.error}</p>- {/if}- <p class="text-xs text-muted-foreground">{m.container_image_description()}</p>- </div>- </div>-- <div class="space-y-3">- <FormInput- label={m.common_command()}- type="text"- placeholder={m.container_command_placeholder()}- description={m.container_command_description()}- disabled={isLoading}- bind:input={$inputs.command}- />- </div>-- <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">- <div class="space-y-3">- <FormInput- label={m.common_working_directory()}- type="text"- placeholder={m.app_placeholder()}- description={m.container_working_directory_description()}- disabled={isLoading}- bind:input={$inputs.workingDir}- />- </div>-- <div class="space-y-3">- <FormInput- label={m.common_user()}- type="text"- placeholder={m.container_user_placeholder()}- description={m.container_user_description()}- disabled={isLoading}- bind:input={$inputs.user}- />- </div>-- <div class="space-y-3">- <FormInput- label={m.hostname()}- type="text"- placeholder={m.container_hostname_placeholder()}- disabled={isLoading}- bind:input={$inputs.hostname}- />- </div>-- <div class="space-y-3">- <FormInput- label={m.container_domain_label()}- type="text"- placeholder={m.container_domain_placeholder()}- disabled={isLoading}- bind:input={$inputs.domainname}- />- </div>- </div>-- <div class="space-y-4 rounded-lg border p-4 sm:p-6">- <h4 class="text-sm font-semibold">{m.io_settings_title()}</h4>- <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">- <div class="flex items-center space-x-2">- <Checkbox id="attach-stdout" bind:checked={$inputs.attachStdout.value} disabled={isLoading} />- <Label for="attach-stdout" class="text-sm font-normal">{m.io_attach_stdout()}</Label>- </div>- <div class="flex items-center space-x-2">- <Checkbox id="attach-stderr" bind:checked={$inputs.attachStderr.value} disabled={isLoading} />- <Label for="attach-stderr" class="text-sm font-normal">{m.io_attach_stderr()}</Label>- </div>- <div class="flex items-center space-x-2">- <Checkbox id="attach-stdin" bind:checked={$inputs.attachStdin.value} disabled={isLoading} />- <Label for="attach-stdin" class="text-sm font-normal">{m.io_attach_stdin()}</Label>- </div>- <div class="flex items-center space-x-2">- <Checkbox id="tty" bind:checked={$inputs.tty.value} disabled={isLoading} />- <Label for="tty" class="text-sm font-normal">{m.io_allocate_tty()}</Label>- </div>- <div class="flex items-center space-x-2">- <Checkbox id="open-stdin" bind:checked={$inputs.openStdin.value} disabled={isLoading} />- <Label for="open-stdin" class="text-sm font-normal">{m.io_open_stdin()}</Label>- </div>- <div class="flex items-center space-x-2">- <Checkbox id="stdin-once" bind:checked={$inputs.stdinOnce.value} disabled={isLoading} />- <Label for="stdin-once" class="text-sm font-normal">{m.io_stdin_once()}</Label>- </div>- </div>- </div>- </Tabs.Content>-- <!-- Environment Tab -->- <Tabs.Content value="environment" class="mt-0 space-y-6">- <div class="grid grid-cols-1 gap-6 xl:grid-cols-2">- <div class="space-y-6">- <div>- <h3 class="mb-4 text-base font-semibold sm:text-lg">{m.env_dynamic_title()}</h3>- <div class="space-y-3">- {#each envVars as env, index (index)}- <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">- <Input type="text" placeholder="KEY" bind:value={env.key} disabled={isLoading} class="flex-1" />- <span class="hidden font-mono text-muted-foreground sm:inline">=</span>- <Input type="text" placeholder="value" bind:value={env.value} disabled={isLoading} class="flex-1" />- <ArcaneButton- action="base"- tone="ghost"- size="icon"- onclick={() => removeEnvVar(index)}- disabled={isLoading || envVars.length <= 1}- class="shrink-0 text-destructive hover:text-destructive"- icon={CloseIcon}- />- </div>- {/each}- <ArcaneButton- action="base"- tone="outline"- size="sm"- onclick={addEnvVar}- disabled={isLoading}- class="w-full"- icon={AddIcon}- customLabel={m.add_env_var_button()}- />- </div>- </div>- </div>-- <div class="space-y-6">- <div>- <h3 class="mb-4 text-base font-semibold sm:text-lg">{m.text_format()}</h3>- <div class="space-y-3">- <Textarea- placeholder={m.env_text_placeholder()}- disabled={isLoading}- rows={12}- bind:value={$inputs.environmentVars.value}- class={$inputs.environmentVars.error ? 'border-destructive' : ''}- />- {#if $inputs.environmentVars.error}- <p class="text-xs text-destructive">{$inputs.environmentVars.error}</p>- {/if}- <p class="text-xs text-muted-foreground">{m.env_text_description()}</p>- </div>- </div>- </div>- </div>- </Tabs.Content>-- <!-- Ports Tab -->- <Tabs.Content value="ports" class="mt-0 space-y-6">- <div class="grid grid-cols-1 gap-6 xl:grid-cols-2">- <div class="space-y-6">- <div>- <h3 class="mb-4 text-base font-semibold sm:text-lg">{m.common_port_mappings()}</h3>- <div class="space-y-3">- {#each portMappings as mapping, index (index)}- <div class="space-y-2 rounded-lg border p-3 sm:space-y-0 sm:border-0 sm:p-0">- <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">- <div class="flex flex-1 items-center gap-2">- <div class="min-w-12 text-xs whitespace-nowrap text-muted-foreground sm:text-sm">- {m.host()}- </div>- <Input type="text" placeholder="8080" bind:value={mapping.host} disabled={isLoading} class="flex-1" />- </div>- <span class="hidden text-muted-foreground sm:inline">→</span>- <div class="flex flex-1 items-center gap-2">- <div class="min-w-16 text-xs whitespace-nowrap text-muted-foreground sm:min-w-20 sm:text-sm">- {m.container()}- </div>- <Input- type="text"- placeholder="80"- bind:value={mapping.container}- disabled={isLoading}- class="flex-1"- />- </div>- <div class="flex items-center gap-2">- <select- bind:value={mapping.protocol}- disabled={isLoading}- class="min-w-16 rounded-md border px-3 py-2 text-sm"- >- <option value="tcp">TCP</option>- <option value="udp">UDP</option>- </select>- <ArcaneButton- action="base"- tone="ghost"- size="icon"- onclick={() => removePortMapping(index)}- disabled={isLoading || portMappings.length <= 1}- class="shrink-0 text-destructive hover:text-destructive"- icon={CloseIcon}- />- </div>- </div>- </div>- {/each}- <ArcaneButton- action="base"- tone="outline"- size="sm"- onclick={addPortMapping}- disabled={isLoading}- class="w-full"- icon={AddIcon}- customLabel={m.add_port_mapping_button()}- />- </div>- </div>- </div>-- <div class="space-y-6">- <div>- <h3 class="mb-4 text-base font-semibold sm:text-lg">{m.port_configuration_title()}</h3>- <div class="space-y-4">- <FormInput- label={m.common_exposed_ports()}- type="text"- placeholder={m.exposed_ports_placeholder()}- description={m.exposed_ports_description()}- disabled={isLoading}- bind:input={$inputs.exposedPorts}- />-- <div class="flex items-center space-x-2 pt-2">- <Checkbox id="publish-all" bind:checked={$inputs.publishAllPorts.value} disabled={isLoading} />- <Label for="publish-all" class="text-sm font-normal">{m.publish_all_ports_label()}</Label>- </div>- </div>- </div>- </div>- </div>- </Tabs.Content>-- <!-- Volumes Tab -->- <Tabs.Content value="volumes" class="mt-0 space-y-6">- <div class="grid grid-cols-1 gap-6 xl:grid-cols-2">- <div class="space-y-6">- <div>- <h3 class="mb-4 text-base font-semibold sm:text-lg">{m.volume_mounts_title()}</h3>- <div class="space-y-3">- {#each volumeMounts as mount, index (index)}- <div class="space-y-2 rounded-lg border p-3 sm:border-0 sm:p-0">- <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">- <Input- type="text"- placeholder={m.container_source_path_or_volume()}- bind:value={mount.source}- disabled={isLoading}- class="flex-1"- />- <span class="hidden text-muted-foreground sm:inline">:</span>- <Input- type="text"- placeholder={m.container_path()}- bind:value={mount.destination}- disabled={isLoading}- class="flex-1"- />- <ArcaneButton- action="base"- tone="ghost"- size="icon"- onclick={() => removeVolumeMount(index)}- disabled={isLoading || volumeMounts.length <= 1}- class="shrink-0 self-end text-destructive hover:text-destructive sm:self-auto"- icon={CloseIcon}- />- </div>- <div class="flex items-center space-x-2 pl-0 sm:pl-3">- <Checkbox bind:checked={mount.readonly} disabled={isLoading} />- <Label class="text-sm font-normal">{m.read_only_label()}</Label>- </div>- </div>- {/each}- <ArcaneButton- action="base"- tone="outline"- size="sm"- onclick={addVolumeMount}- disabled={isLoading}- class="w-full"- icon={AddIcon}- customLabel={m.add_volume_mount_button()}- />- </div>- </div>- </div>-- <div class="space-y-6">- <div>- <h3 class="mb-4 text-base font-semibold sm:text-lg">{m.text_format()}</h3>- <div class="space-y-3">- <Textarea- placeholder={m.volumes_text_placeholder()}- disabled={isLoading}- rows={12}- bind:value={$inputs.volumes.value}- class={$inputs.volumes.error ? 'border-destructive' : ''}- />- {#if $inputs.volumes.error}- <p class="text-xs text-destructive">{$inputs.volumes.error}</p>- {/if}- <p class="text-xs text-muted-foreground">{m.volumes_text_description()}</p>- </div>- </div>- </div>- </div>- </Tabs.Content>-- <!-- Network & Security Tab -->- <Tabs.Content value="network" class="mt-0 space-y-6">- <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">- <div class="space-y-6">- <div class="rounded-lg border p-4 sm:p-6">- <h3 class="mb-4 text-base font-semibold sm:text-lg">{m.network_settings_title()}</h3>- <div class="space-y-4">- <div class="flex items-center space-x-3">- <Checkbox id="network-disabled" bind:checked={$inputs.networkDisabled.value} disabled={isLoading} />- <Label for="network-disabled" class="text-sm font-normal">{m.disable_network_label()}</Label>- </div>- <div class="flex items-center space-x-3">- <Checkbox id="publish-all-ports-net" bind:checked={$inputs.publishAllPorts.value} disabled={isLoading} />- <Label for="publish-all-ports-net" class="text-sm font-normal">{m.publish_all_ports_label()}</Label>- </div>- </div>- </div>- </div>-- <div class="space-y-6">- <div class="rounded-lg border p-4 sm:p-6">- <h3 class="mb-4 text-base font-semibold sm:text-lg">{m.security_settings_title()}</h3>- <div class="space-y-4">- <div class="flex items-center space-x-3">- <Checkbox id="privileged" bind:checked={$inputs.privileged.value} disabled={isLoading} />- <Label for="privileged" class="text-sm font-normal">{m.privileged_label()}</Label>- </div>- <div class="flex items-center space-x-3">- <Checkbox id="readonly-rootfs" bind:checked={$inputs.readonlyRootfs.value} disabled={isLoading} />- <Label for="readonly-rootfs" class="text-sm font-normal">{m.readonly_rootfs_label()}</Label>- </div>- <div class="flex items-center space-x-3">- <Checkbox id="auto-remove" bind:checked={$inputs.autoRemove.value} disabled={isLoading} />- <Label for="auto-remove" class="text-sm font-normal">{m.auto_remove_label()}</Label>- </div>- </div>- </div>- </div>- </div>- </Tabs.Content>-- <!-- Advanced Tab -->- <Tabs.Content value="advanced" class="mt-0 space-y-6">- <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">- <div class="space-y-6">- <div class="rounded-lg border p-4 sm:p-6">- <h3 class="mb-4 text-base font-semibold sm:text-lg">{m.common_restart_policy()}</h3>- <div class="space-y-4">- <SelectWithLabel- id="restart-policy"- bind:value={$inputs.restartPolicy.value}- label={m.restart_policy_label()}- description={m.restart_policy_description()}- options={restartPolicies}- placeholder={m.container_select_restart_policy()}- />-- {#if $inputs.restartPolicy.value === 'on-failure'}- <div class="space-y-3">- <Label for="max-retries" class="text-sm font-medium">{m.max_retry_label()}</Label>- <Input- id="max-retries"- type="number"- min="0"- placeholder={m.max_retry_placeholder()}- disabled={isLoading}- bind:value={$inputs.restartMaxRetries.value}- />- <p class="text-xs text-muted-foreground">{m.max_retry_description()}</p>- </div>- {/if}- </div>- </div>- </div>-- <div class="space-y-6">- <div class="rounded-lg border p-4 sm:p-6">- <h3 class="mb-4 text-base font-semibold sm:text-lg">{m.common_labels()}</h3>- <div class="space-y-3">- <Textarea- placeholder="com.example.description=My application com.example.version=1.0.0 [email protected]"- disabled={isLoading}- rows={8}- bind:value={$inputs.labels.value}- class={$inputs.labels.error ? 'border-destructive' : ''}- />- {#if $inputs.labels.error}- <p class="text-xs text-destructive">{$inputs.labels.error}</p>- {/if}- <p class="text-xs text-muted-foreground">{m.containers_labels_description()}</p>- </div>- </div>- </div>- </div>- </Tabs.Content>- </div>- </Tabs.Root>- </form>- {/snippet}-- {#snippet footer()}- <div class="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">- <ArcaneButton action="cancel" tone="outline" onclick={() => (open = false)} disabled={isLoading} class="w-full sm:w-auto" />- <ArcaneButton- action="create"- form="create-container-form"- type="submit"- disabled={isLoading}- loading={isLoading}- class="w-full sm:w-auto"- customLabel={m.common_create_button({ resource: m.container() })}- />- </div>- {/snippet}-</ResponsiveDialog>diff --git a/frontend/src/lib/components/form/key-value-editor.svelte b/frontend/src/lib/components/form/key-value-editor.sveltenew file mode 100644index 000000000..cea244c84--- /dev/null+++ b/frontend/src/lib/components/form/key-value-editor.svelte@@ -0,0 +1,61 @@+<script module lang="ts">+ export type KeyValueRow = { key: string; value: string };+</script>++<script lang="ts">+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import { Input } from '#lib/components/ui/input/index.js';+ import { m } from '#lib/paraglide/messages';+ import { AddIcon, CloseIcon } from '#lib/icons';++ let {+ rows = $bindable([]),+ keyPlaceholder = 'KEY',+ valuePlaceholder = 'value',+ addLabel,+ disabled = false+ }: {+ rows?: KeyValueRow[];+ keyPlaceholder?: string;+ valuePlaceholder?: string;+ addLabel?: string;+ disabled?: boolean;+ } = $props();++ function addRow() {+ rows.push({ key: '', value: '' });+ }++ function removeRow(index: number) {+ rows.splice(index, 1);+ }+</script>++<div class="space-y-3">+ {#each rows as row, index (index)}+ <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">+ <Input type="text" placeholder={keyPlaceholder} bind:value={row.key} {disabled} class="flex-1 font-mono" />+ <span class="hidden font-mono text-muted-foreground sm:inline">=</span>+ <Input type="text" placeholder={valuePlaceholder} bind:value={row.value} {disabled} class="flex-1 font-mono" />+ <ArcaneButton+ action="base"+ tone="ghost"+ size="icon"+ onclick={() => removeRow(index)}+ {disabled}+ class="shrink-0 text-destructive hover:text-destructive"+ icon={CloseIcon}+ />+ </div>+ {/each}+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ onclick={addRow}+ {disabled}+ class="w-fit"+ icon={AddIcon}+ customLabel={addLabel ?? m.common_add()}+ />+</div>diff --git a/frontend/src/lib/components/form/network-attachment-editor.svelte b/frontend/src/lib/components/form/network-attachment-editor.sveltenew file mode 100644index 000000000..42a418c90--- /dev/null+++ b/frontend/src/lib/components/form/network-attachment-editor.svelte@@ -0,0 +1,73 @@+<script module lang="ts">+ export type NetworkAttachmentRow = {+ network: string;+ // comma-separated aliases as typed by the user+ aliases: string;+ ipv4Address: string;+ };+</script>++<script lang="ts">+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import { Input } from '#lib/components/ui/input/index.js';+ import SearchableSelect from '#lib/components/form/searchable-select.svelte';+ import { m } from '#lib/paraglide/messages';+ import { AddIcon, CloseIcon } from '#lib/icons';++ let {+ rows = $bindable([]),+ networks = [],+ disabled = false+ }: {+ rows?: NetworkAttachmentRow[];+ networks?: string[];+ disabled?: boolean;+ } = $props();++ const attached = $derived(new Set(rows.map((row) => row.network)));+ const networkItems = $derived(networks.map((name) => ({ value: name, label: name, disabled: attached.has(name) })));++ function addRow() {+ rows.push({ network: '', aliases: '', ipv4Address: '' });+ }++ function removeRow(index: number) {+ rows.splice(index, 1);+ }+</script>++<div class="space-y-3">+ {#each rows as row, index (index)}+ <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">+ <SearchableSelect items={networkItems} bind:value={row.network} {disabled} class="min-w-40 flex-1" />+ <Input+ type="text"+ placeholder={m.containers_aliases()}+ bind:value={row.aliases}+ {disabled}+ class="flex-1 font-mono"+ title={m.aliases_note()}+ />+ <Input type="text" placeholder={m.static_ip()} bind:value={row.ipv4Address} {disabled} class="flex-1 font-mono" />+ <ArcaneButton+ action="base"+ tone="ghost"+ size="icon"+ onclick={() => removeRow(index)}+ {disabled}+ class="shrink-0 text-destructive hover:text-destructive"+ icon={CloseIcon}+ />+ </div>+ {/each}+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ onclick={addRow}+ {disabled}+ class="w-fit"+ icon={AddIcon}+ customLabel={m.common_add()}+ />+</div>diff --git a/frontend/src/lib/components/form/port-mapping-editor.svelte b/frontend/src/lib/components/form/port-mapping-editor.sveltenew file mode 100644index 000000000..1a7d1f3c4--- /dev/null+++ b/frontend/src/lib/components/form/port-mapping-editor.svelte@@ -0,0 +1,65 @@+<script module lang="ts">+ export type PortMappingRow = {+ hostIp: string;+ hostPort: string;+ containerPort: string;+ protocol: 'tcp' | 'udp';+ };+</script>++<script lang="ts">+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import { Input } from '#lib/components/ui/input/index.js';+ import { m } from '#lib/paraglide/messages';+ import { AddIcon, CloseIcon } from '#lib/icons';++ let {+ rows = $bindable([]),+ disabled = false+ }: {+ rows?: PortMappingRow[];+ disabled?: boolean;+ } = $props();++ function addRow() {+ rows.push({ hostIp: '', hostPort: '', containerPort: '', protocol: 'tcp' });+ }++ function removeRow(index: number) {+ rows.splice(index, 1);+ }+</script>++<div class="space-y-3">+ {#each rows as row, index (index)}+ <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">+ <Input type="text" placeholder="0.0.0.0" bind:value={row.hostIp} {disabled} class="flex-1 font-mono" title={m.host()} />+ <Input type="text" placeholder="8080" bind:value={row.hostPort} {disabled} class="flex-1 font-mono" />+ <span class="hidden text-muted-foreground sm:inline">→</span>+ <Input type="text" placeholder="80" bind:value={row.containerPort} {disabled} class="flex-1 font-mono" />+ <select bind:value={row.protocol} {disabled} class="min-w-16 rounded-md border bg-background px-3 py-2 text-sm">+ <option value="tcp">TCP</option>+ <option value="udp">UDP</option>+ </select>+ <ArcaneButton+ action="base"+ tone="ghost"+ size="icon"+ onclick={() => removeRow(index)}+ {disabled}+ class="shrink-0 text-destructive hover:text-destructive"+ icon={CloseIcon}+ />+ </div>+ {/each}+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ onclick={addRow}+ {disabled}+ class="w-fit"+ icon={AddIcon}+ customLabel={m.common_add()}+ />+</div>diff --git a/frontend/src/lib/components/form/volume-mount-editor.svelte b/frontend/src/lib/components/form/volume-mount-editor.sveltenew file mode 100644index 000000000..dd4f40bc0--- /dev/null+++ b/frontend/src/lib/components/form/volume-mount-editor.svelte@@ -0,0 +1,116 @@+<script module lang="ts">+ export type VolumeMountRow = {+ kind: 'bind' | 'volume' | 'mount';+ source: string;+ target: string;+ readOnly: boolean;+ // raw bind options beyond ro/rw (e.g. z, cached) preserved verbatim+ rawOptions?: string;+ // original mount type for kind === 'mount' rows (bind/volume/tmpfs/...)+ mountType?: string;+ };+</script>++<script lang="ts">+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import { Input } from '#lib/components/ui/input/index.js';+ import { Checkbox } from '#lib/components/ui/checkbox/index.js';+ import { Label } from '#lib/components/ui/label/index.js';+ import { Badge } from '#lib/components/ui/badge/index.js';+ import SearchableSelect from '#lib/components/form/searchable-select.svelte';+ import { m } from '#lib/paraglide/messages';+ import { AddIcon, CloseIcon } from '#lib/icons';++ let {+ rows = $bindable([]),+ volumes = [],+ disabled = false+ }: {+ rows?: VolumeMountRow[];+ volumes?: string[];+ disabled?: boolean;+ } = $props();++ const volumeItems = $derived(volumes.map((name) => ({ value: name, label: name })));++ function addRow(kind: 'bind' | 'volume') {+ rows.push({ kind, source: '', target: '', readOnly: false });+ }++ function removeRow(index: number) {+ rows.splice(index, 1);+ }+</script>++<div class="space-y-3">+ {#each rows as row, index (index)}+ <div class="space-y-2 rounded-lg border border-border/50 p-3">+ <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">+ <Badge variant="outline" class="w-fit shrink-0 font-mono text-xs">+ {row.kind === 'mount' ? (row.mountType ?? 'mount') : row.kind}+ </Badge>+ {#if row.kind === 'volume'}+ <SearchableSelect items={volumeItems} bind:value={row.source} {disabled} class="flex-1" />+ {:else}+ <Input+ type="text"+ placeholder={m.container_source_path_or_volume()}+ bind:value={row.source}+ disabled={disabled || row.kind === 'mount'}+ class="flex-1 font-mono"+ />+ {/if}+ <span class="hidden text-muted-foreground sm:inline">:</span>+ <Input+ type="text"+ placeholder={m.container_path()}+ bind:value={row.target}+ disabled={disabled || row.kind === 'mount'}+ class="flex-1 font-mono"+ />+ <ArcaneButton+ action="base"+ tone="ghost"+ size="icon"+ onclick={() => removeRow(index)}+ {disabled}+ class="shrink-0 text-destructive hover:text-destructive"+ icon={CloseIcon}+ />+ </div>+ <div class="flex items-center gap-4">+ <div class="flex items-center space-x-2">+ <Checkbox bind:checked={row.readOnly} {disabled} />+ <Label class="text-sm font-normal">{m.read_only_label()}</Label>+ </div>+ {#if row.rawOptions}+ <Badge variant="secondary" class="font-mono text-xs" title={m.mount_options_note()}>+ {row.rawOptions}+ </Badge>+ {/if}+ </div>+ </div>+ {/each}+ <div class="flex gap-2">+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ onclick={() => addRow('bind')}+ {disabled}+ class="w-fit"+ icon={AddIcon}+ customLabel={m.add_bind_mount_button()}+ />+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ onclick={() => addRow('volume')}+ {disabled}+ class="w-fit"+ icon={AddIcon}+ customLabel={m.add_volume_mount_button()}+ />+ </div>+</div>diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.tsindex a092fb691..b0c6aa904 100644--- a/frontend/src/lib/query/query-keys.ts+++ b/frontend/src/lib/query/query-keys.ts@@ -92,7 +92,8 @@ export const queryKeys = {checkUpdates: (environmentId: string) => ['containers', 'check-updates', environmentId] as const,create: (environmentId: string) => ['containers', 'create', environmentId] as const,statusCounts: (environmentId: string) => ['containers', 'status-counts', environmentId] as const,- detail: (environmentId: string, containerId: string) => ['container', environmentId, containerId] as const+ detail: (environmentId: string, containerId: string) => ['container', environmentId, containerId] as const,+ editConfig: (environmentId: string, containerId: string) => ['container', environmentId, containerId, 'edit-config'] as const},images: {all: ['images'] as const,diff --git a/frontend/src/lib/services/container-service.ts b/frontend/src/lib/services/container-service.tsindex 4c64c53ba..c612d4e66 100644--- a/frontend/src/lib/services/container-service.ts+++ b/frontend/src/lib/services/container-service.ts@@ -7,7 +7,9 @@ import type {ContainerCreateRequest,ContainerDetailsDto,ContainerCommitRequest,- ContainerCommitResult+ ContainerCommitResult,+ ContainerEditConfigDto,+ ContainerEditRequest} from '#lib/types/docker';import type { SearchPaginationSortRequest, Paginated } from '#lib/types/shared';import { transformPaginationParams } from '#lib/utils/tables';@@ -121,6 +123,16 @@ class ContainerService extends BaseAPIService {return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/redeploy`));}+ async getContainerEditConfig(containerId: string, environmentId?: string): Promise<ContainerEditConfigDto> {+ const envId = await this.resolveEnvironmentId(environmentId);+ return this.handleResponse(this.api.get(`/environments/${envId}/containers/${containerId}/edit-config`));+ }++ async editContainer(containerId: string, request: ContainerEditRequest): Promise<ContainerDetailsDto> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/edit`, request));+ }+async setAutoUpdate(containerId: string, enabled: boolean): Promise<{ success: boolean; data: { message: string } }> {const envId = await environmentStore.getCurrentEnvironmentId();return this.handleResponse(this.api.put(`/environments/${envId}/containers/${containerId}/auto-update`, { enabled }));diff --git a/frontend/src/lib/services/network-service.ts b/frontend/src/lib/services/network-service.tsindex 522b33409..2af37792a 100644--- a/frontend/src/lib/services/network-service.ts+++ b/frontend/src/lib/services/network-service.ts@@ -70,6 +70,19 @@ class NetworkService extends BaseAPIService {const envId = await environmentStore.getCurrentEnvironmentId();return this.handleResponse(this.api.delete(`/environments/${envId}/networks/${networkId}`));}++ async connectContainer(+ networkId: string,+ request: { containerId: string; aliases?: string[]; ipv4Address?: string; ipv6Address?: string }+ ): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/networks/${networkId}/connect`, request));+ }++ async disconnectContainer(networkId: string, request: { containerId: string; force?: boolean }): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/networks/${networkId}/disconnect`, request));+ }}export const networkService = new NetworkService();diff --git a/frontend/src/lib/types/docker.ts b/frontend/src/lib/types/docker.tsindex b7c3ea6de..1f8b7e980 100644--- a/frontend/src/lib/types/docker.ts+++ b/frontend/src/lib/types/docker.ts@@ -26,6 +26,22 @@ export interface RestartPolicy {maximumRetryCount?: number;}+export interface MountDto {+ type: string;+ source: string;+ target: string;+ readOnly?: boolean;+}++export interface ContainerHealthcheckCreate {+ test?: string[];+ interval?: number;+ timeout?: number;+ startPeriod?: number;+ startInterval?: number;+ retries?: number;+}+export interface HostConfigCreate {binds?: string[];portBindings?: Record<string, PortBinding[]>;@@ -39,10 +55,19 @@ export interface HostConfigCreate {memorySwap?: number;nanoCpus?: number;cpuShares?: number;+ capAdd?: string[];+ capDrop?: string[];+ mounts?: MountDto[];+}++export interface EndpointSettingsCreate {+ aliases?: string[];+ ipv4Address?: string;+ ipv6Address?: string;}export interface NetworkingConfig {- endpointsConfig?: Record<string, { aliases?: string[] }>;+ endpointsConfig?: Record<string, EndpointSettingsCreate>;}export interface ContainerCreateRequest {@@ -52,6 +77,7 @@ export interface ContainerCreateRequest {entrypoint?: string[];env?: string[];exposedPorts?: Record<string, {}>;+ healthcheck?: ContainerHealthcheckCreate;hostConfig?: HostConfigCreate;networkingConfig?: NetworkingConfig;labels?: Record<string, string>;@@ -68,6 +94,79 @@ export interface ContainerCreateRequest {stdinOnce?: boolean;}+export interface ContainerHostConfigEdit {+ binds?: string[];+ mounts?: MountDto[];+ portBindings?: Record<string, PortBinding[]>;+ restartPolicy?: RestartPolicy;+ privileged?: boolean;+ capAdd?: string[];+ capDrop?: string[];+ autoRemove?: boolean;+ readonlyRootfs?: boolean;+ memory?: number;+ memorySwap?: number;+ nanoCpus?: number;+ cpuShares?: number;+}++export interface ContainerEditRequest {+ name?: string;+ image?: string;+ workingDir?: string;+ user?: string;+ command?: string[];+ entrypoint?: string[];+ environment?: string[];+ labels?: Record<string, string>;+ healthcheck?: ContainerHealthcheckCreate;+ clearHealthcheck?: boolean;+ hostConfig?: ContainerHostConfigEdit;+ networkingConfig?: NetworkingConfig;+}++export interface ContainerEditConfigHostConfig {+ binds?: string[];+ mounts?: MountDto[];+ portBindings?: Record<string, PortBinding[]>;+ restartPolicy: { name?: string; maximumRetryCount?: number };+ networkMode?: string;+ privileged?: boolean;+ capAdd?: string[];+ capDrop?: string[];+ autoRemove?: boolean;+ readonlyRootfs?: boolean;+ memory?: number;+ memorySwap?: number;+ nanoCpus?: number;+ cpuShares?: number;+}++export interface ContainerEditConfigNetwork {+ aliases?: string[];+ ipv4Address?: string;+ ipv6Address?: string;+}++export interface ContainerEditConfigDto {+ id: string;+ name: string;+ image: string;+ command?: string[];+ entrypoint?: string[];+ workingDir?: string;+ user?: string;+ environment?: string[];+ labels?: Record<string, string>;+ healthcheck?: ContainerHealthcheckCreate;+ hostConfig: ContainerEditConfigHostConfig;+ networks?: Record<string, ContainerEditConfigNetwork>;+ isCompose?: boolean;+ composeProject?: string;+ editDisabled?: boolean;+ running: boolean;+}+export interface ContainerSummaryDto extends BaseContainer {ports: ContainerPorts[];hostConfig: ContainerHostConfig;diff --git a/frontend/src/routes/(app)/containers/+page.svelte b/frontend/src/routes/(app)/containers/+page.svelteindex af54fd502..4314ba0bd 100644--- a/frontend/src/routes/(app)/containers/+page.svelte+++ b/frontend/src/routes/(app)/containers/+page.svelte@@ -1,6 +1,6 @@<script lang="ts">- import CreateContainerDialog from '#lib/components/dialogs/create-container-dialog.svelte';import { toast } from 'svelte-sonner';+ import { goto } from '$app/navigation';import { containerService } from '#lib/services/container-service';import ContainerTable from './container-table.svelte';import { m } from '#lib/paraglide/messages';@@ -9,7 +9,7 @@import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index';import { environmentStore } from '#lib/stores/environment.store.svelte';import { hasPermission } from '#lib/utils/auth';- import type { ContainerCreateRequest, ContainerStatusCounts } from '#lib/types/docker';+ import type { ContainerStatusCounts } from '#lib/types/docker';import { createMutation } from '@tanstack/svelte-query';import { BoxIcon } from '#lib/icons';import { queryKeys } from '#lib/query/query-keys';@@ -22,7 +22,6 @@let requestOptions = $state(untrack(() => data.containerRequestOptions));let selectedIds = $state<string[]>([]);- let isCreateDialogOpen = $state(false);let containers = $state(untrack(() => data.containers));const envId = $derived(environmentStore.selected?.id || '0');let displayedEnvId = $state<string | null>(untrack(() => (data.envId === envId ? data.envId : null)));@@ -83,25 +82,6 @@}}));- const createContainerMutation = createMutation(() => ({- mutationKey: queryKeys.containers.create(envId),- mutationFn: async (options: ContainerCreateRequest) => {- const requestedEnvId = envId;- const result = await containerService.createContainer(options, requestedEnvId);- return { requestedEnvId, result };- },- onSuccess: async ({ requestedEnvId }) => {- toast.success(m.common_create_success({ resource: m.resource_container() }));- if (requestedEnvId === envId) {- await refreshContainers(buildRequestOptions(), requestedEnvId);- isCreateDialogOpen = false;- }- },- onError: () => {- toast.error(m.containers_create_failed());- }- }));-function handleEnvironmentChange() {if (!hasSeenEnvironmentSync) {hasSeenEnvironmentSync = true;@@ -114,7 +94,6 @@isRefreshing = false;displayedEnvId = null;selectedIds = [];- isCreateDialogOpen = false;const nextOptions: SearchPaginationSortRequest = {...requestOptions,@@ -145,9 +124,8 @@id: 'create',action: 'create',label: m.common_create_button({ resource: m.container() }),- onclick: () => (isCreateDialogOpen = true),- loading: createContainerMutation.isPending,- disabled: !resourcesReady || createContainerMutation.isPending+ onclick: () => goto('/containers/new'),+ disabled: !resourcesReady},canAutoUpdate? {@@ -219,12 +197,4 @@/>{/if}{/snippet}-- {#snippet additionalContent()}- <CreateContainerDialog- bind:open={isCreateDialogOpen}- isLoading={createContainerMutation.isPending}- onSubmit={(options) => createContainerMutation.mutate(options)}- />- {/snippet}</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelteindex a6d30bcfc..071d514a0 100644--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte@@ -46,7 +46,7 @@import { environmentStore } from '#lib/stores/environment.store.svelte';import { hasPermission } from '#lib/utils/auth';import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';- import { ImagesIcon, PauseIcon, PlayIcon, UpdateIcon, ZapIcon } from '#lib/icons';+ import { EditIcon, ImagesIcon, PauseIcon, PlayIcon, UpdateIcon, ZapIcon } from '#lib/icons';import { runContainerLifecycleAction, confirmAndUpdateContainer } from '#lib/utils/container-actions';import { imageService } from '#lib/services/image-service';import type { ImageUpdateInfoDto } from '#lib/types/docker';@@ -136,6 +136,9 @@const canExecShell = $derived(hasPermission('containers:exec', currentEnvId));const canPauseContainer = $derived(hasPermission('containers:pause', currentEnvId));const canUpdateContainer = $derived(hasPermission('containers:autoupdate', currentEnvId));+ const canEditContainer = $derived(+ hasPermission('containers:edit', currentEnvId) && !container?.composeInfo && !container?.redeployDisabled+ );const canKillContainer = $derived(hasPermission('containers:kill', currentEnvId));const canCommitImage = $derived(hasPermission('images:commit', currentEnvId));const containerStatus = $derived(container?.state?.status ?? '');@@ -373,6 +376,17 @@disableRedeploy={!!container.redeployDisabled}>{#snippet beforeRemoveActions(size, showLabel, actionButtonsLifecyclePending)}+ {#if canEditContainer}+ <ArcaneButton+ action="base"+ {size}+ {showLabel}+ customLabel={m.common_edit()}+ icon={EditIcon}+ disabled={actionButtonsLifecyclePending}+ href={`/containers/${container.id}/edit`}+ />+ {/if}{#if canUpdateContainer && updateInfo?.hasUpdate}<ArcaneButtonaction="base"diff --git a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.sveltenew file mode 100644index 000000000..a7004978e--- /dev/null+++ b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.svelte@@ -0,0 +1,94 @@+<script lang="ts">+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import ContainerForm from '#lib/components/containers/container-form/container-form.svelte';+ import {+ containerFormSchema,+ formValuesFromEditConfig,+ rowsFromEditConfig,+ toEditRequest+ } from '#lib/components/containers/container-form/container-form-state';+ import { createForm } from '#lib/utils/settings';+ import { containerService } from '#lib/services/container-service';+ import { queryKeys } from '#lib/query/query-keys';+ import { createMutation, useQueryClient } from '@tanstack/svelte-query';+ import { goto } from '$app/navigation';+ import { toast } from 'svelte-sonner';+ import { m } from '#lib/paraglide/messages';+ import { extractApiErrorMessage } from '#lib/utils/api';+ import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast';+ import { openConfirmDialog } from '#lib/components/confirm-dialog';+ import { untrack } from 'svelte';+ import { ArrowLeftIcon } from '#lib/icons';+ import type { ContainerEditRequest } from '#lib/types/docker';++ let { data } = $props();++ const queryClient = useQueryClient();+ // The form is intentionally seeded once from the load-time snapshot.+ // svelte-ignore state_referenced_locally+ const form = createForm<typeof containerFormSchema>(containerFormSchema, formValuesFromEditConfig(data.editConfig));+ let rows = $state(untrack(() => rowsFromEditConfig(data.editConfig)));++ const editContainerMutation = createMutation(() => ({+ mutationFn: (request: ContainerEditRequest) => containerService.editContainer(data.containerId, request),+ onSuccess: async (details) => {+ toast.success(m.edit_success(), activityToastOptions(extractActivityId(details)));+ await queryClient.invalidateQueries({ queryKey: queryKeys.containers.all });+ queryClient.removeQueries({ queryKey: queryKeys.containers.detail(data.envId, data.containerId) });+ queryClient.removeQueries({ queryKey: queryKeys.containers.editConfig(data.envId, data.containerId) });+ goto(`/containers/${details.id}`);+ },+ onError: (error) => {+ toast.error(m.edit_failed(), { description: extractApiErrorMessage(error) });+ }+ }));++ function handleSubmit() {+ const values = form.validate();+ if (!values) return;+ const request = toEditRequest(values, rows);+ openConfirmDialog({+ title: m.edit_confirm_title(),+ message: m.edit_confirm_message({ name: data.editConfig.name }),+ confirm: {+ label: m.common_save(),+ destructive: false,+ action: () => {+ editContainerMutation.mutate(request);+ }+ }+ });+ }+</script>++<div class="flex min-h-0 flex-col bg-background">+ <div class="sticky top-0 z-10 border-b bg-background">+ <div class="mx-auto flex h-16 w-full max-w-full items-center gap-4 px-6">+ <ArcaneButton+ action="base"+ tone="ghost"+ size="sm"+ href={`/containers/${data.containerId}`}+ class="gap-2 bg-transparent"+ icon={ArrowLeftIcon}+ customLabel={m.common_back()}+ />+ <div class="hidden h-4 w-px bg-border sm:block"></div>+ <h1 class="truncate text-base font-semibold">{m.common_edit()} · {data.editConfig.name}</h1>+ </div>+ </div>++ <div class="mx-auto w-full max-w-full px-6 py-6">+ <div class="mb-6 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm text-amber-600 dark:text-amber-400">+ {m.edit_recreate_banner()}+ </div>+ <ContainerForm+ mode="edit"+ {form}+ bind:rows+ cancelHref={`/containers/${data.containerId}`}+ submitting={editContainerMutation.isPending}+ onSubmit={handleSubmit}+ />+ </div>+</div>diff --git a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.tsnew file mode 100644index 000000000..f56336bb4--- /dev/null+++ b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts@@ -0,0 +1,29 @@+import type { PageLoad } from './$types';+import { redirect } from '@sveltejs/kit';+import { environmentStore } from '#lib/stores/environment.store.svelte';+import { hasPermission } from '#lib/utils/auth';+import { containerService } from '#lib/services/container-service';+import { queryKeys } from '#lib/query/query-keys';++export const load: PageLoad = async ({ params, parent }) => {+ const { queryClient } = await parent();+ const envId = await environmentStore.getCurrentEnvironmentId();+ const containerId = params.containerId;++ if (!hasPermission('containers:edit', envId)) {+ redirect(302, `/containers/${containerId}`);+ }++ const editConfig = await queryClient.fetchQuery({+ queryKey: queryKeys.containers.editConfig(envId, containerId),+ queryFn: () => containerService.getContainerEditConfig(containerId, envId)+ });++ // Compose-managed containers are edited via their project; self-managed+ // (Arcane server) containers cannot be edited at all.+ if (editConfig.isCompose || editConfig.editDisabled) {+ redirect(302, `/containers/${containerId}`);+ }++ return { editConfig, envId, containerId };+};diff --git a/frontend/src/routes/(app)/containers/components/ContainerNetwork.svelte b/frontend/src/routes/(app)/containers/components/ContainerNetwork.svelteindex d3cb67235..7bcbff87f 100644--- a/frontend/src/routes/(app)/containers/components/ContainerNetwork.svelte+++ b/frontend/src/routes/(app)/containers/components/ContainerNetwork.svelte@@ -1,15 +1,100 @@<script lang="ts">import * as Card from '#lib/components/ui/card';import { PortBadge } from '#lib/components/badges';+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import { Input } from '#lib/components/ui/input/index.js';+ import SearchableSelect from '#lib/components/form/searchable-select.svelte';+ import { openConfirmDialog } from '#lib/components/confirm-dialog';import { m } from '#lib/paraglide/messages';import type { ContainerDetailsDto } from '#lib/types/docker';import { NetworksIcon } from '#lib/icons';+ import { networkService } from '#lib/services/network-service';+ import { environmentStore } from '#lib/stores/environment.store.svelte';+ import { hasPermission } from '#lib/utils/auth';+ import { queryKeys } from '#lib/query/query-keys';+ import { createQuery } from '@tanstack/svelte-query';+ import { refreshAll } from '$app/navigation';+ import { toast } from 'svelte-sonner';+ import { extractApiErrorMessage } from '#lib/utils/api';interface Props {container: ContainerDetailsDto;}let { container }: Props = $props();++ const envId = $derived(environmentStore.selected?.id || '0');+ const canConnect = $derived(hasPermission('networks:connect', envId));+ const canDisconnect = $derived(hasPermission('networks:disconnect', envId));++ let connectNetwork = $state('');+ let connectAliases = $state('');+ let connectIp = $state('');+ let connectPending = $state(false);+ let disconnectPending = $state<Record<string, boolean>>({});++ const networkListOptions = { pagination: { page: 1, limit: 500 } };+ const networksQuery = createQuery(() => ({+ queryKey: queryKeys.networks.list(envId, networkListOptions),+ queryFn: () => networkService.getNetworks(networkListOptions),+ enabled: canConnect+ }));++ const attachedNetworks = $derived(new Set(Object.keys(container.networkSettings?.networks ?? {})));+ const connectableNetworks = $derived(+ (networksQuery.data?.data ?? [])+ .map((network) => network.name)+ .filter((name) => name !== 'host' && name !== 'none' && !attachedNetworks.has(name))+ .map((name) => ({ value: name, label: name }))+ );++ async function handleConnect() {+ if (!connectNetwork) return;+ connectPending = true;+ try {+ const aliases = connectAliases+ .split(',')+ .map((alias) => alias.trim())+ .filter(Boolean);+ await networkService.connectContainer(connectNetwork, {+ containerId: container.id,+ aliases: aliases.length > 0 ? aliases : undefined,+ ipv4Address: connectIp.trim() || undefined+ });+ toast.success(m.network_connect_success());+ connectNetwork = '';+ connectAliases = '';+ connectIp = '';+ await refreshAll();+ } catch (error) {+ toast.error(m.network_connect_failed(), { description: extractApiErrorMessage(error) });+ } finally {+ connectPending = false;+ }+ }++ function handleDisconnect(networkName: string, networkId: string) {+ openConfirmDialog({+ title: m.network_disconnect_confirm_title(),+ message: m.network_disconnect_confirm_message({ network: networkName }),+ confirm: {+ label: m.common_disconnect(),+ destructive: true,+ action: async () => {+ disconnectPending[networkName] = true;+ try {+ await networkService.disconnectContainer(networkId || networkName, { containerId: container.id, force: false });+ toast.success(m.network_disconnect_success());+ await refreshAll();+ } catch (error) {+ toast.error(m.network_disconnect_failed(), { description: extractApiErrorMessage(error) });+ } finally {+ disconnectPending[networkName] = false;+ }+ }+ }+ });+ }</script><div class="space-y-6">@@ -64,6 +149,18 @@</div><div class="text-xs text-muted-foreground">{m.network_interface()}</div></div>+ {#if canDisconnect}+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ customLabel={m.common_disconnect()}+ loading={disconnectPending[networkName]}+ disabled={disconnectPending[networkName]}+ onclick={() => handleDisconnect(networkName, rawNetworkConfig.networkId)}+ class="shrink-0 text-destructive hover:text-destructive"+ />+ {/if}</div><div class="grid grid-cols-1 gap-3 sm:grid-cols-2">@@ -176,6 +273,49 @@<div class="text-sm">{m.containers_no_networks_connected()}</div></div>{/if}++ {#if canConnect}+ <div class="mt-4 space-y-3 rounded-lg border border-border/50 p-4">+ <div>+ <h3 class="text-sm font-semibold">{m.network_connect()}</h3>+ <p class="mt-1 text-xs text-muted-foreground">{m.network_live_change_note()}</p>+ </div>+ <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">+ <SearchableSelect+ items={connectableNetworks}+ bind:value={connectNetwork}+ showCheckboxes={false}+ disabled={connectPending}+ class="min-w-44 flex-1"+ />+ <Input+ type="text"+ placeholder={m.containers_aliases()}+ bind:value={connectAliases}+ disabled={connectPending}+ class="flex-1 font-mono"+ title={m.aliases_note()}+ />+ <Input+ type="text"+ placeholder={m.static_ip()}+ bind:value={connectIp}+ disabled={connectPending}+ class="flex-1 font-mono"+ />+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ customLabel={m.common_connect()}+ loading={connectPending}+ disabled={connectPending || !connectNetwork}+ onclick={handleConnect}+ class="shrink-0"+ />+ </div>+ </div>+ {/if}</Card.Content></Card.Root></div>diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelteindex b9f13bce9..2bd695e70 100644--- a/frontend/src/routes/(app)/containers/container-table.svelte+++ b/frontend/src/routes/(app)/containers/container-table.svelte@@ -48,6 +48,7 @@TrashIcon,BoxIcon,ClockIcon,+ EditIcon,ImagesIcon,NetworksIcon,ProjectsIcon,@@ -190,6 +191,7 @@const currentEnvId = $derived(environmentStore.selected?.id || '0');const resourcesCurrent = $derived(environmentId === currentEnvId);const canUpdateContainers = $derived(hasPermission('containers:autoupdate', currentEnvId));+ const canEditContainers = $derived(hasPermission('containers:edit', currentEnvId));const canKillContainers = $derived(hasPermission('containers:kill', currentEnvId));const canPauseContainers = $derived(hasPermission('containers:pause', currentEnvId));@@ -634,6 +636,13 @@{m.common_inspect()}</DropdownMenu.Item>+ {#if canEditContainers && !item.redeployDisabled && !item.labels?.['com.docker.compose.project']}+ <DropdownMenu.Item onclick={() => goto(`/containers/${item.id}/edit`)} disabled={isAnyLoading}>+ <EditIcon class="size-4" />+ {m.common_edit()}+ </DropdownMenu.Item>+ {/if}+<DropdownMenu.Separator />{#if item.updateInfo?.hasUpdate && canUpdateContainers}diff --git a/frontend/src/routes/(app)/containers/new/+page.svelte b/frontend/src/routes/(app)/containers/new/+page.sveltenew file mode 100644index 000000000..9cba21dfa--- /dev/null+++ b/frontend/src/routes/(app)/containers/new/+page.svelte@@ -0,0 +1,66 @@+<script lang="ts">+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import ContainerForm from '#lib/components/containers/container-form/container-form.svelte';+ import {+ containerFormSchema,+ emptyContainerFormRows,+ emptyContainerFormValues,+ toCreateRequest+ } from '#lib/components/containers/container-form/container-form-state';+ import { createForm } from '#lib/utils/settings';+ import { containerService } from '#lib/services/container-service';+ import { queryKeys } from '#lib/query/query-keys';+ import { createMutation, useQueryClient } from '@tanstack/svelte-query';+ import { goto } from '$app/navigation';+ import { toast } from 'svelte-sonner';+ import { m } from '#lib/paraglide/messages';+ import { extractApiErrorMessage } from '#lib/utils/api';+ import { ArrowLeftIcon } from '#lib/icons';++ let { data } = $props();++ const queryClient = useQueryClient();+ const form = createForm<typeof containerFormSchema>(containerFormSchema, emptyContainerFormValues());+ let rows = $state(emptyContainerFormRows());++ const createContainerMutation = createMutation(() => ({+ mutationKey: queryKeys.containers.create(data.envId),+ mutationFn: (request: ReturnType<typeof toCreateRequest>) => containerService.createContainer(request, data.envId),+ onSuccess: async (created) => {+ toast.success(m.common_create_success({ resource: m.resource_container() }));+ await queryClient.invalidateQueries({ queryKey: queryKeys.containers.all });+ goto(`/containers/${created.id}`);+ },+ onError: (error) => {+ toast.error(m.containers_create_failed(), { description: extractApiErrorMessage(error) });+ }+ }));++ function handleSubmit() {+ const values = form.validate();+ if (!values) return;+ createContainerMutation.mutate(toCreateRequest(values, rows));+ }+</script>++<div class="flex min-h-0 flex-col bg-background">+ <div class="sticky top-0 z-10 border-b bg-background">+ <div class="mx-auto flex h-16 w-full max-w-full items-center gap-4 px-6">+ <ArcaneButton+ action="base"+ tone="ghost"+ size="sm"+ href="/containers"+ class="gap-2 bg-transparent"+ icon={ArrowLeftIcon}+ customLabel={m.common_back()}+ />+ <div class="hidden h-4 w-px bg-border sm:block"></div>+ <h1 class="text-base font-semibold">{m.create_container_title()}</h1>+ </div>+ </div>++ <div class="mx-auto w-full max-w-full px-6 py-6">+ <ContainerForm mode="create" {form} bind:rows submitting={createContainerMutation.isPending} onSubmit={handleSubmit} />+ </div>+</div>diff --git a/frontend/src/routes/(app)/containers/new/+page.ts b/frontend/src/routes/(app)/containers/new/+page.tsnew file mode 100644index 000000000..561dded0b--- /dev/null+++ b/frontend/src/routes/(app)/containers/new/+page.ts@@ -0,0 +1,13 @@+import type { PageLoad } from './$types';+import { redirect } from '@sveltejs/kit';+import { environmentStore } from '#lib/stores/environment.store.svelte';+import { hasPermission } from '#lib/utils/auth';++export const load: PageLoad = async () => {+ const envId = await environmentStore.getCurrentEnvironmentId();+ if (!hasPermission('containers:create', envId)) {+ redirect(302, '/containers');+ }++ return { envId };+};diff --git a/go.work.sum b/go.work.sumindex fbe20fb65..e4123154c 100644--- a/go.work.sum+++ b/go.work.sum@@ -893,6 +893,7 @@ github.com/docker/docker-credential-helpers v0.9.3/go.mod h1:x+4Gbw9aGmChi3qTLZjgithub.com/docker/go v1.5.1-1.0.20160303222718-d30aec9fd63c h1:lzqkGL9b3znc+ZUgi7FlLnqjQhcXxkNM/quxIjBVMD0=github.com/docker/go v1.5.1-1.0.20160303222718-d30aec9fd63c/go.mod h1:CADgU4DSXK5QUlFslkQu2yW2TKzFZcXq/leZfM0UH5Q=github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=+github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c h1:+pKlWGMw7gf6bQ+oDZB4KHQFypsfjYlq/C4rfL7D3g8=github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA=github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 h1:UhxFibDNY/bfvqU5CAUmr9zpesgbU6SWc8/B4mflAE4=@@ -1782,6 +1783,7 @@ github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWicgithub.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=github.com/sirupsen/logrus v1.9.4-0.20230606125235-dd1b4c2e81af/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=+github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=github.com/smallstep/pkcs7 v0.1.1 h1:x+rPdt2W088V9Vkjho4KtoggyktZJlMduZAtRHm68LU=github.com/smallstep/pkcs7 v0.1.1/go.mod h1:dL6j5AIz9GHjVEBTXtW+QliALcgM19RtXaTeyxI+AfA=github.com/snowflakedb/gosnowflake v1.6.19 h1:KSHXrQ5o7uso25hNIzi/RObXtnSGkFgie91X82KcvMY=@@ -2066,6 +2068,7 @@ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg=go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=go.opentelemetry.io/contrib/zpages v0.62.0 h1:9fUYTLmrK0x/lweM2uM+BOx069jLx8PxVqWhegGJ9Bo=go.opentelemetry.io/contrib/zpages v0.62.0/go.mod h1:C8kXoiC1Ytvereztus2R+kqdSa6W/MZ8FfS8Zwj+LiM=go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI=@@ -2077,6 +2080,7 @@ go.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlgo.opentelemetry.io/otel v1.41.0/go.mod h1:Yt4UwgEKeT05QbLwbyHXEwhnjxNO6D8L5PQP51/46dE=go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=+go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=go.opentelemetry.io/otel/exporters/jaeger v1.17.0 h1:D7UpUy2Xc2wsi1Ras6V40q806WM07rqoCWzXu7Sqy+4=go.opentelemetry.io/otel/exporters/jaeger v1.17.0/go.mod h1:nPCqOnEH9rNLKqH/+rrUjiMzHJdV1BlpKcTwRTyKkKI=go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0/go.mod h1:zjPK58DtkqQFn+YUMbx0M2XV3QgKU0gS9LeGohREyK4=@@ -2113,6 +2117,7 @@ go.opentelemetry.io/otel/metric v1.40.0/go.mod h1:ib/crwQH7N3r5kfiBZQbwrTge743UDgo.opentelemetry.io/otel/metric v1.41.0/go.mod h1:xPvCwd9pU0VN8tPZYzDZV/BMj9CM9vs00GuBjeKhJps=go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=+go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=go.opentelemetry.io/otel/sdk v1.40.0/go.mod h1:Ph7EFdYvxq72Y8Li9q8KebuYUr2KoeyHx0DRMKrYBUE=@@ -2129,6 +2134,7 @@ go.opentelemetry.io/otel/trace v1.40.0/go.mod h1:zeAhriXecNGP/s2SEG3+Y8X9ujcJOTqgo.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis=go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=+go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=go.opentelemetry.io/proto/otlp v1.5.0/go.mod h1:keN8WnHxOy8PG0rQZjJJ5A2ebUoafqWp0eVQ4yIXvJ4=go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE=go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=diff --git a/types/activity/activity.go b/types/activity/activity.goindex 0cb1c6f3b..fc2956068 100644--- a/types/activity/activity.go+++ b/types/activity/activity.go@@ -29,6 +29,7 @@ const (TypeContainerStop Type = "container_stop"TypeContainerRestart Type = "container_restart"TypeContainerRedeploy Type = "container_redeploy"+ TypeContainerEdit Type = "container_edit"TypeContainerDelete Type = "container_delete"TypeContainerKill Type = "container_kill"TypeContainerPause Type = "container_pause"diff --git a/types/container/container.go b/types/container/container.goindex fad3c59aa..d7e3eca5f 100644--- a/types/container/container.go+++ b/types/container/container.go@@ -99,6 +99,21 @@ type HostConfigCreate struct {//// Required: falsePublishAllPorts *bool `json:"publishAllPorts,omitempty"`++ // CapAdd is a list of kernel capabilities to add.+ //+ // Required: false+ CapAdd []string `json:"capAdd,omitempty"`++ // CapDrop is a list of kernel capabilities to drop.+ //+ // Required: false+ CapDrop []string `json:"capDrop,omitempty"`++ // Mounts is a list of typed mounts (bind or volume).+ //+ // Required: false+ Mounts []MountCreate `json:"mounts,omitempty"`}// EndpointSettingsCreate represents network endpoint settings for container creation.@@ -107,6 +122,73 @@ type EndpointSettingsCreate struct {//// Required: falseAliases []string `json:"aliases,omitempty"`++ // IPv4Address is a static IPv4 address for the container on this network.+ //+ // Required: false+ IPv4Address string `json:"ipv4Address,omitempty"`++ // IPv6Address is a static IPv6 address for the container on this network.+ //+ // Required: false+ IPv6Address string `json:"ipv6Address,omitempty"`+}++// MountCreate represents a typed mount (bind or volume) for container creation.+type MountCreate struct {+ // Type of the mount (bind or volume).+ //+ // Required: true+ Type string `json:"type"`++ // Source is the host path (bind) or volume name (volume).+ //+ // Required: true+ Source string `json:"source"`++ // Target path inside the container.+ //+ // Required: true+ Target string `json:"target"`++ // ReadOnly mounts the target read-only.+ //+ // Required: false+ ReadOnly bool `json:"readOnly,omitempty"`+}++// HealthcheckCreate represents a container healthcheck configuration for+// create/edit requests. Duration values are expressed in seconds on the wire.+type HealthcheckCreate struct {+ // Test is the probe command. ["NONE"] disables an image-defined healthcheck.+ //+ // Required: false+ Test []string `json:"test,omitempty"`++ // Interval between probes, in seconds.+ //+ // Required: false+ Interval int64 `json:"interval,omitempty"`++ // Timeout for a single probe, in seconds.+ //+ // Required: false+ Timeout int64 `json:"timeout,omitempty"`++ // StartPeriod is the initialization grace period, in seconds.+ //+ // Required: false+ StartPeriod int64 `json:"startPeriod,omitempty"`++ // StartInterval is the probe interval during the start period, in seconds.+ //+ // Required: false+ StartInterval int64 `json:"startInterval,omitempty"`++ // Retries is the number of consecutive failures before unhealthy.+ //+ // Required: false+ Retries int `json:"retries,omitempty"`}// NetworkingConfigCreate represents network configuration for container creation.@@ -174,6 +256,11 @@ type Create struct {// Required: falseExposedPorts map[string]struct{} `json:"exposedPorts,omitempty"`+ // Healthcheck overrides the image healthcheck. Test ["NONE"] disables it.+ //+ // Required: false+ Healthcheck *HealthcheckCreate `json:"healthcheck,omitempty"`+// HostConfig holds advanced host-level settings.//// Required: false@@ -1248,3 +1335,456 @@ func mapEndpointSettings(n *network.EndpointSettings) NetworkEndpoint {DNSNames: n.DNSNames,}}++// HostConfigEdit carries host-level configuration changes for a container+// edit. Each field is a pointer: nil preserves the existing value, non-nil+// (even empty) replaces it.+type HostConfigEdit struct {+ // Binds is the full desired list of volume bindings.+ //+ // Required: false+ Binds *[]string `json:"binds,omitempty"`++ // Mounts is the full desired list of typed mounts.+ //+ // Required: false+ Mounts *[]MountCreate `json:"mounts,omitempty"`++ // PortBindings is the full desired port binding map.+ //+ // Required: false+ PortBindings *map[string][]PortBindingCreate `json:"portBindings,omitempty"`++ // RestartPolicy for the container.+ //+ // Required: false+ RestartPolicy *RestartPolicyCreate `json:"restartPolicy,omitempty"`++ // Privileged indicates if the container runs in privileged mode.+ //+ // Required: false+ Privileged *bool `json:"privileged,omitempty"`++ // CapAdd is the full desired list of added kernel capabilities.+ //+ // Required: false+ CapAdd *[]string `json:"capAdd,omitempty"`++ // CapDrop is the full desired list of dropped kernel capabilities.+ //+ // Required: false+ CapDrop *[]string `json:"capDrop,omitempty"`++ // AutoRemove indicates if the container is removed when stopped.+ //+ // Required: false+ AutoRemove *bool `json:"autoRemove,omitempty"`++ // ReadonlyRootfs makes the root filesystem read-only.+ //+ // Required: false+ ReadonlyRootfs *bool `json:"readonlyRootfs,omitempty"`++ // Memory limit in bytes.+ //+ // Required: false+ Memory *int64 `json:"memory,omitempty"`++ // MemorySwap limits total memory usage (memory + swap) in bytes.+ //+ // Required: false+ MemorySwap *int64 `json:"memorySwap,omitempty"`++ // NanoCPUs is CPU allocation in nano CPUs.+ //+ // Required: false+ NanoCPUs *int64 `json:"nanoCpus,omitempty"`++ // CPUShares is the relative CPU share weight.+ //+ // Required: false+ CPUShares *int64 `json:"cpuShares,omitempty"`+}++// Edit describes configuration changes to apply when recreating a container.+// Each form-owned section is a pointer: nil preserves the inspected value,+// non-nil (even empty) replaces that section. Settings not represented here+// (sysctls, ulimits, log drivers, devices, tmpfs, DNS, ...) always carry over+// from the existing container untouched.+type Edit struct {+ // Name is the new container name.+ //+ // Required: false+ Name *string `json:"name,omitempty"`++ // Image reference to run.+ //+ // Required: false+ Image *string `json:"image,omitempty"`++ // WorkingDir is the working directory inside the container.+ //+ // Required: false+ WorkingDir *string `json:"workingDir,omitempty"`++ // User to run the container as.+ //+ // Required: false+ User *string `json:"user,omitempty"`++ // Command to run in the container.+ //+ // Required: false+ Command *[]string `json:"command,omitempty"`++ // Entrypoint for the container.+ //+ // Required: false+ Entrypoint *[]string `json:"entrypoint,omitempty"`++ // Environment variables for the container.+ //+ // Required: false+ Environment *[]string `json:"environment,omitempty"`++ // Labels to set on the container.+ //+ // Required: false+ Labels *map[string]string `json:"labels,omitempty"`++ // Healthcheck replaces the container healthcheck when set.+ //+ // Required: false+ Healthcheck *HealthcheckCreate `json:"healthcheck,omitempty"`++ // ClearHealthcheck reverts to the image-defined healthcheck.+ //+ // Required: false+ ClearHealthcheck bool `json:"clearHealthcheck,omitempty"`++ // HostConfig holds host-level configuration changes.+ //+ // Required: false+ HostConfig *HostConfigEdit `json:"hostConfig,omitempty"`++ // NetworkingConfig is the full desired network endpoint set. Nil preserves+ // the existing attachments.+ //+ // Required: false+ NetworkingConfig *NetworkingConfigCreate `json:"networkingConfig,omitempty"`++ // Credentials for pulling images from private registries.+ //+ // Required: false+ Credentials []containerregistry.Credential `json:"credentials,omitempty"`+}++// EditConfigNetwork describes one desired network attachment as shown in the+// edit form.+type EditConfigNetwork struct {+ // Aliases for the container on this network.+ //+ // Required: false+ Aliases []string `json:"aliases,omitempty"`++ // IPv4Address is the configured static IPv4 address, if any.+ //+ // Required: false+ IPv4Address string `json:"ipv4Address,omitempty"`++ // IPv6Address is the configured static IPv6 address, if any.+ //+ // Required: false+ IPv6Address string `json:"ipv6Address,omitempty"`+}++// EditConfigHostConfig is the host-config subset surfaced by the edit form.+type EditConfigHostConfig struct {+ // Binds is the list of volume bindings.+ //+ // Required: false+ Binds []string `json:"binds,omitempty"`++ // Mounts is the list of typed mounts.+ //+ // Required: false+ Mounts []MountCreate `json:"mounts,omitempty"`++ // PortBindings maps container ports to host bindings.+ //+ // Required: false+ PortBindings map[string][]PortBindingCreate `json:"portBindings,omitempty"`++ // RestartPolicy for the container.+ //+ // Required: false+ RestartPolicy RestartPolicyCreate `json:"restartPolicy"`++ // NetworkMode for the container.+ //+ // Required: false+ NetworkMode string `json:"networkMode,omitempty"`++ // Privileged indicates if the container runs in privileged mode.+ //+ // Required: false+ Privileged bool `json:"privileged,omitempty"`++ // CapAdd is the list of added kernel capabilities.+ //+ // Required: false+ CapAdd []string `json:"capAdd,omitempty"`++ // CapDrop is the list of dropped kernel capabilities.+ //+ // Required: false+ CapDrop []string `json:"capDrop,omitempty"`++ // AutoRemove indicates if the container is removed when stopped.+ //+ // Required: false+ AutoRemove bool `json:"autoRemove,omitempty"`++ // ReadonlyRootfs indicates a read-only root filesystem.+ //+ // Required: false+ ReadonlyRootfs bool `json:"readonlyRootfs,omitempty"`++ // Memory limit in bytes.+ //+ // Required: false+ Memory int64 `json:"memory,omitempty"`++ // MemorySwap limits total memory usage (memory + swap) in bytes.+ //+ // Required: false+ MemorySwap int64 `json:"memorySwap,omitempty"`++ // NanoCPUs is CPU allocation in nano CPUs.+ //+ // Required: false+ NanoCPUs int64 `json:"nanoCpus,omitempty"`++ // CPUShares is the relative CPU share weight.+ //+ // Required: false+ CPUShares int64 `json:"cpuShares,omitempty"`+}++// EditConfig is the read DTO backing the container edit form.+type EditConfig struct {+ // ID is the unique identifier of the container.+ //+ // Required: true+ ID string `json:"id"`++ // Name of the container.+ //+ // Required: true+ Name string `json:"name"`++ // Image reference the container was created from.+ //+ // Required: true+ Image string `json:"image"`++ // Command the container runs.+ //+ // Required: false+ Command []string `json:"command,omitempty"`++ // Entrypoint for the container.+ //+ // Required: false+ Entrypoint []string `json:"entrypoint,omitempty"`++ // WorkingDir is the working directory inside the container.+ //+ // Required: false+ WorkingDir string `json:"workingDir,omitempty"`++ // User the container runs as.+ //+ // Required: false+ User string `json:"user,omitempty"`++ // Environment variables of the container.+ //+ // Required: false+ Environment []string `json:"environment,omitempty"`++ // Labels set on the container.+ //+ // Required: false+ Labels map[string]string `json:"labels,omitempty"`++ // Healthcheck configuration (durations in seconds), if the container+ // defines one.+ //+ // Required: false+ Healthcheck *HealthcheckCreate `json:"healthcheck,omitempty"`++ // HostConfig is the host-config subset surfaced by the edit form.+ //+ // Required: true+ HostConfig EditConfigHostConfig `json:"hostConfig"`++ // Networks maps network names to their desired endpoint settings.+ //+ // Required: false+ Networks map[string]EditConfigNetwork `json:"networks,omitempty"`++ // IsCompose indicates the container is managed by a compose project.+ //+ // Required: false+ IsCompose bool `json:"isCompose,omitempty"`++ // ComposeProject is the owning compose project name, if any.+ //+ // Required: false+ ComposeProject string `json:"composeProject,omitempty"`++ // EditDisabled indicates edit actions are disabled for this container.+ //+ // Required: false+ EditDisabled bool `json:"editDisabled,omitempty"`++ // Running indicates whether the container is currently running.+ //+ // Required: true+ Running bool `json:"running"`+}++// NewEditConfigFromInspect builds an EditConfig from a docker inspect response.+func NewEditConfigFromInspect(c *container.InspectResponse, isCompose bool, editDisabled bool) EditConfig {+ cfg := EditConfig{+ ID: c.ID,+ Name: strings.TrimPrefix(c.Name, "/"),+ IsCompose: isCompose,+ EditDisabled: editDisabled,+ Running: c.State != nil && c.State.Running,+ }++ if c.Config != nil {+ cfg.Image = c.Config.Image+ cfg.Command = append([]string{}, c.Config.Cmd...)+ cfg.Entrypoint = append([]string{}, c.Config.Entrypoint...)+ cfg.WorkingDir = c.Config.WorkingDir+ cfg.User = c.Config.User+ cfg.Environment = append([]string{}, c.Config.Env...)+ cfg.Labels = c.Config.Labels+ cfg.ComposeProject = c.Config.Labels["com.docker.compose.project"]+ cfg.Healthcheck = mapEditHealthcheck(c.Config.Healthcheck)+ }++ cfg.HostConfig = mapEditHostConfig(c.HostConfig)+ cfg.Networks = mapEditNetworks(c)++ return cfg+}++func mapEditHealthcheck(hc *container.HealthConfig) *HealthcheckCreate {+ if hc == nil {+ return nil+ }++ return &HealthcheckCreate{+ Test: append([]string{}, hc.Test...),+ Interval: int64(hc.Interval / time.Second),+ Timeout: int64(hc.Timeout / time.Second),+ StartPeriod: int64(hc.StartPeriod / time.Second),+ StartInterval: int64(hc.StartInterval / time.Second),+ Retries: hc.Retries,+ }+}++func mapEditHostConfig(hc *container.HostConfig) EditConfigHostConfig {+ if hc == nil {+ return EditConfigHostConfig{}+ }++ out := EditConfigHostConfig{+ Binds: append([]string{}, hc.Binds...),+ RestartPolicy: RestartPolicyCreate{+ Name: string(hc.RestartPolicy.Name),+ MaximumRetryCount: hc.RestartPolicy.MaximumRetryCount,+ },+ NetworkMode: string(hc.NetworkMode),+ Privileged: hc.Privileged,+ CapAdd: append([]string{}, hc.CapAdd...),+ CapDrop: append([]string{}, hc.CapDrop...),+ AutoRemove: hc.AutoRemove,+ ReadonlyRootfs: hc.ReadonlyRootfs,+ Memory: hc.Memory,+ MemorySwap: hc.MemorySwap,+ NanoCPUs: hc.NanoCPUs,+ CPUShares: hc.CPUShares,+ }++ for _, m := range hc.Mounts {+ out.Mounts = append(out.Mounts, MountCreate{+ Type: string(m.Type),+ Source: m.Source,+ Target: m.Target,+ ReadOnly: m.ReadOnly,+ })+ }++ if len(hc.PortBindings) > 0 {+ out.PortBindings = make(map[string][]PortBindingCreate, len(hc.PortBindings))+ for port, bindings := range hc.PortBindings {+ mapped := make([]PortBindingCreate, 0, len(bindings))+ for _, b := range bindings {+ hostIP := ""+ if b.HostIP.IsValid() {+ hostIP = b.HostIP.String()+ }+ mapped = append(mapped, PortBindingCreate{+ HostIP: hostIP,+ HostPort: b.HostPort,+ })+ }+ out.PortBindings[port.String()] = mapped+ }+ }++ return out+}++func mapEditNetworks(c *container.InspectResponse) map[string]EditConfigNetwork {+ if c.NetworkSettings == nil || len(c.NetworkSettings.Networks) == 0 {+ return nil+ }++ shortID := ""+ if len(c.ID) >= 12 {+ shortID = c.ID[:12]+ }++ out := make(map[string]EditConfigNetwork, len(c.NetworkSettings.Networks))+ for name, endpoint := range c.NetworkSettings.Networks {+ mapped := EditConfigNetwork{}+ if endpoint != nil {+ // The daemon injects the container short ID as an implicit alias;+ // it is regenerated on recreate and must not round-trip as a+ // user-defined alias.+ for _, alias := range endpoint.Aliases {+ if alias == "" || alias == shortID {+ continue+ }+ mapped.Aliases = append(mapped.Aliases, alias)+ }+ if endpoint.IPAMConfig != nil {+ if endpoint.IPAMConfig.IPv4Address.IsValid() {+ mapped.IPv4Address = endpoint.IPAMConfig.IPv4Address.String()+ }+ if endpoint.IPAMConfig.IPv6Address.IsValid() {+ mapped.IPv6Address = endpoint.IPAMConfig.IPv6Address.String()+ }+ }+ }+ out[name] = mapped+ }++ return out+}diff --git a/types/network/network.go b/types/network/network.goindex 56206317f..b5d6dcd4a 100644--- a/types/network/network.go+++ b/types/network/network.go@@ -364,6 +364,44 @@ func parseAuxAddress(auxAddress map[string]string) map[string]netip.Addr {return aux}+// ConnectContainerRequest contains the parameters for connecting a container+// to a network.+type ConnectContainerRequest struct {+ // ContainerID is the container to connect.+ //+ // Required: true+ ContainerID string `json:"containerId" minLength:"1" doc:"Container ID or name"`++ // Aliases for the container on this network.+ //+ // Required: false+ Aliases []string `json:"aliases,omitempty" doc:"Network-scoped aliases"`++ // IPv4Address is a static IPv4 address for the container on this network.+ //+ // Required: false+ IPv4Address string `json:"ipv4Address,omitempty" doc:"Static IPv4 address"`++ // IPv6Address is a static IPv6 address for the container on this network.+ //+ // Required: false+ IPv6Address string `json:"ipv6Address,omitempty" doc:"Static IPv6 address"`+}++// DisconnectContainerRequest contains the parameters for disconnecting a+// container from a network.+type DisconnectContainerRequest struct {+ // ContainerID is the container to disconnect.+ //+ // Required: true+ ContainerID string `json:"containerId" minLength:"1" doc:"Container ID or name"`++ // Force disconnects even if the container is running.+ //+ // Required: false+ Force bool `json:"force,omitempty" doc:"Force the disconnect"`+}+type PruneReport struct {// NetworksDeleted is a list of network IDs that were deleted.//