Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: add volume workspace (#3497)
Neureka6f6e2e2ac5cf
diff --git a/.env.example b/.env.exampleindex 62c65dec5..7ca340e7a 100644--- a/.env.example+++ b/.env.example@@ -57,6 +57,15 @@ ALLOW_DOWNGRADE=false# Run Trivy scan containers in privileged mode only when security options alone are not enough# TRIVY_PRIVILEGED=false+# Project and Volume Workspace limits+# File sizes use MiB units. Non-positive values fall back to 10 MiB.+# PROJECT_WORKSPACE_MAX_FILE_SIZE_MB=10+# PROJECT_WORKSPACE_MAX_DEPTH=20+# PROJECT_WORKSPACE_MAX_ENTRIES=2000+# VOLUME_WORKSPACE_MAX_FILE_SIZE_MB=10+# VOLUME_WORKSPACE_MAX_DEPTH=50+# VOLUME_WORKSPACE_MAX_ENTRIES=10000+# Agent Configuration (optional)# AGENT_MODE=true# AGENT_TOKEN=api-tokendiff --git a/backend/api/api_test.go b/backend/api/api_test.goindex 07923dd46..ad199c786 100644--- a/backend/api/api_test.go+++ b/backend/api/api_test.go@@ -28,6 +28,56 @@ import ("github.com/stretchr/testify/require")+func TestWorkspaceRoutesReplaceProjectAndVolumeLegacyRoutes(t *testing.T) {+ api := SetupAPIForSpec()+ paths := api.OpenAPI().Paths++ canonical := []struct {+ path string+ method string+ }{+ {path: "/environments/{id}/projects/{projectId}/workspace", method: http.MethodGet},+ {path: "/environments/{id}/projects/{projectId}/workspace", method: http.MethodPut},+ {path: "/environments/{id}/projects/{projectId}/workspace/file", method: http.MethodGet},+ {path: "/environments/{id}/projects/{projectId}/workspace/file/download", method: http.MethodGet},+ {path: "/environments/{id}/volumes/{volumeName}/workspace", method: http.MethodGet},+ {path: "/environments/{id}/volumes/{volumeName}/workspace", method: http.MethodPut},+ {path: "/environments/{id}/volumes/{volumeName}/workspace/file", method: http.MethodGet},+ {path: "/environments/{id}/volumes/{volumeName}/workspace/file/download", method: http.MethodGet},+ {path: "/environments/{id}/builds/browse", method: http.MethodGet},+ }+ for _, route := range canonical {+ t.Run(route.method+" "+route.path, func(t *testing.T) {+ item := paths[route.path]+ require.NotNil(t, item)+ switch route.method {+ case http.MethodGet:+ require.NotNil(t, item.Get)+ case http.MethodPut:+ require.NotNil(t, item.Put)+ }+ })+ }++ legacy := []string{+ "/environments/{id}/projects/{projectId}/files",+ "/environments/{id}/projects/{projectId}/file",+ "/environments/{id}/projects/{projectId}/includes",+ "/environments/{id}/volumes/{volumeName}/files",+ "/environments/{id}/volumes/{volumeName}/file",+ "/environments/{id}/volumes/{volumeName}/browse",+ "/environments/{id}/volumes/{volumeName}/browse/content",+ "/environments/{id}/volumes/{volumeName}/browse/download",+ "/environments/{id}/volumes/{volumeName}/browse/upload",+ "/environments/{id}/volumes/{volumeName}/browse/mkdir",+ }+ for _, path := range legacy {+ t.Run("absent "+path, func(t *testing.T) {+ require.Nil(t, paths[path])+ })+ }+}+func TestCustomSchemaNamer_PrefixesArcaneTypesByPackage(t *testing.T) {imageName := customSchemaNamer(reflect.TypeFor[imagetypes.Summary](), "")envName := customSchemaNamer(reflect.TypeFor[envtypes.Summary](), "")diff --git a/backend/internal/build/workspace_handler.go b/backend/internal/build/workspace_handler.goindex 497325a38..e838e7dc6 100644--- a/backend/internal/build/workspace_handler.go+++ b/backend/internal/build/workspace_handler.go@@ -11,7 +11,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base"- volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"+ workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace")// BuildWorkspaceHandler provides file browsing endpoints for manual build workspaces.@@ -107,7 +107,7 @@ type BrowseBuildsInput struct {}type BrowseBuildsOutput struct {- Body base.ApiResponse[[]volumetypes.FileEntry]+ Body base.ApiResponse[[]workspacetypes.FileEntry]}type GetBuildFileContentInput struct {@@ -158,7 +158,7 @@ func (h *BuildWorkspaceHandler) BrowseDirectory(ctx context.Context, input *Browif err != nil {return nil, huma.Error500InternalServerError(err.Error())}- return &BrowseBuildsOutput{Body: base.ApiResponse[[]volumetypes.FileEntry]{Success: true, Data: entries}}, nil+ return &BrowseBuildsOutput{Body: base.ApiResponse[[]workspacetypes.FileEntry]{Success: true, Data: entries}}, nil}func (h *BuildWorkspaceHandler) GetFileContent(ctx context.Context, input *GetBuildFileContentInput) (*GetBuildFileContentOutput, error) {diff --git a/backend/internal/build/workspace_service.go b/backend/internal/build/workspace_service.goindex 918b072a8..34c557be6 100644--- a/backend/internal/build/workspace_service.go+++ b/backend/internal/build/workspace_service.go@@ -15,7 +15,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"- volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"+ workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace")const defaultBuildsDirectory = "/builds"@@ -29,7 +29,7 @@ func NewBuildWorkspaceService(settings *settings.SettingsService) *BuildWorkspacreturn &BuildWorkspaceService{settings: settings}}-func (s *BuildWorkspaceService) ListDirectory(ctx context.Context, dirPath string) ([]volumetypes.FileEntry, error) {+func (s *BuildWorkspaceService) ListDirectory(ctx context.Context, dirPath string) ([]workspacetypes.FileEntry, error) {slog.DebugContext(ctx, "build workspace: list directory", "path", dirPath)root, err := s.resolveRoot()if err != nil {@@ -51,7 +51,7 @@ func (s *BuildWorkspaceService) ListDirectory(ctx context.Context, dirPath strinreturn nil, errors.WrapIf(err, "failed to list directory")}- results := make([]volumetypes.FileEntry, 0, len(entries))+ results := make([]workspacetypes.FileEntry, 0, len(entries))for _, entry := range entries {info, err := entry.Info()if err != nil {@@ -66,7 +66,7 @@ func (s *BuildWorkspaceService) ListDirectory(ctx context.Context, dirPath strinisSymlink := entry.Type()&os.ModeSymlink != 0mode := info.Mode().String()- fileEntry := volumetypes.FileEntry{+ fileEntry := workspacetypes.FileEntry{Name: entry.Name(),Path: entryPath,IsDirectory: info.IsDir(),diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex 23396a707..2f37236c1 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -85,12 +85,17 @@ var (ErrOidcMappingNotFound = Classify(ErrNotFound, errors.Sentinel("OIDC role mapping not found"))ErrOidcMappingEnvManaged = Classify(ErrConflict, errors.Sentinel("OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"))ErrNoGlobalAdminRemains = Classify(ErrConflict, errors.Sentinel("At least one user must retain a global Admin role assignment"))+ ErrProjectNotFound = Classify(ErrNotFound, errors.Sentinel("Project not found"))ErrProjectArchived = Classify(ErrConflict, errors.Sentinel("project is archived and must be unarchived before this action"))ErrProjectMustBeStopped = Classify(ErrConflict, errors.Sentinel("project must be stopped before archiving"))- ErrProjectFileConflict = Classify(ErrConflict, errors.Sentinel("Project files changed; refresh the project and try again"))- ErrProjectFileForbidden = Classify(ErrForbidden, errors.Sentinel("Forbidden project file path"))- ErrProjectFileBadRequest = Classify(ErrBadRequest, errors.Sentinel("Invalid project file request"))- ErrProjectFileNotFound = Classify(ErrNotFound, errors.Sentinel("Project file not found"))+ ErrProjectWorkspaceConflict = Classify(ErrConflict, errors.Sentinel("Project workspace changed; refresh it and try again"))+ ErrProjectWorkspaceForbidden = Classify(ErrForbidden, errors.Sentinel("Forbidden project workspace path"))+ ErrProjectWorkspaceBadRequest = Classify(ErrBadRequest, errors.Sentinel("Invalid project workspace request"))+ ErrProjectWorkspaceNotFound = Classify(ErrNotFound, errors.Sentinel("Project workspace file not found"))+ ErrVolumeWorkspaceConflict = Classify(ErrConflict, errors.Sentinel("Volume workspace changed; refresh it and try again"))+ ErrVolumeWorkspaceForbidden = Classify(ErrForbidden, errors.Sentinel("Forbidden volume workspace path"))+ ErrVolumeWorkspaceBadRequest = Classify(ErrBadRequest, errors.Sentinel("Invalid volume workspace request"))+ ErrVolumeWorkspaceNotFound = Classify(ErrNotFound, errors.Sentinel("Volume workspace file not found"))ErrProjectComposeFileNotFound = Classify(ErrNotFound, errors.Sentinel("Project compose file not found"))ErrComposeFileNotFound = Classify(ErrNotFound, errors.Sentinel("no compose file found"))ErrEnvironmentInvalidProxyTarget = Classify(ErrBadRequest, errors.Sentinel("Invalid proxy target URL"))diff --git a/backend/internal/config/config.go b/backend/internal/config/config.goindex b56d82c73..89bcee485 100644--- a/backend/internal/config/config.go+++ b/backend/internal/config/config.go@@ -63,34 +63,39 @@ type Config struct {// Docker secrets. Leave empty to manage mappings purely via the UI/API.OidcRoleMappings string `env:"OIDC_ROLE_MAPPINGS" default:"" options:"file"`- PUID string `env:"PUID" default:""`- PGID string `env:"PGID" default:""`- DockerHost string `env:"DOCKER_HOST" default:"unix:///var/run/docker.sock"`- DockerConfig string `env:"DOCKER_CONFIG" default:""`- ProjectsDirectory string `env:"PROJECTS_DIRECTORY" default:"/app/data/projects"`- TemplatesDirectory string `env:"TEMPLATES_DIRECTORY" default:"/app/data/templates"`- ProjectScanMaxDepth int `env:"PROJECT_SCAN_MAX_DEPTH" default:"3"`- ProjectFileTreeMaxDepth int `env:"PROJECT_FILE_TREE_MAX_DEPTH" default:"20"`- ProjectScanSkipDirs string `env:"PROJECT_SCAN_SKIP_DIRS" default:".git,node_modules,vendor,.venv,venv,__pycache__,.cache,dist,build,target,.next,.nuxt,.svelte-kit"`- LogJson bool `env:"LOG_JSON" default:"false"`- LogLevel string `env:"LOG_LEVEL" default:"info" options:"toLower"`- AgentMode bool `env:"AGENT_MODE" default:"false"`- AgentToken string `env:"AGENT_TOKEN" default:"" options:"file"`- ManagerApiUrl string `env:"MANAGER_API_URL" default:""`- UpdateCheckDisabled bool `env:"UPDATE_CHECK_DISABLED" default:"false"`- UIConfigurationDisabled bool `env:"UI_CONFIGURATION_DISABLED" default:"false"`- AnalyticsDisabled bool `env:"ANALYTICS_DISABLED" default:"false"`- GPUMonitoringEnabled bool `env:"GPU_MONITORING_ENABLED" default:"false"`- GPUType string `env:"GPU_TYPE" default:"auto"`- EdgeAgent bool `env:"EDGE_AGENT" default:"false"`- EdgeTransport string `env:"EDGE_TRANSPORT" default:"auto" options:"toLower"`- EdgeReconnectInterval int `env:"EDGE_RECONNECT_INTERVAL" default:"5"` // seconds- EdgeMTLSMode string `env:"EDGE_MTLS_MODE" default:"disabled" options:"toLower"`- EdgeMTLSCAFile string `env:"EDGE_MTLS_CA_FILE" default:""`- EdgeMTLSCertFile string `env:"EDGE_MTLS_CERT_FILE" default:""`- EdgeMTLSKeyFile string `env:"EDGE_MTLS_KEY_FILE" default:""`- EdgeMTLSServerName string `env:"EDGE_MTLS_SERVER_NAME" default:""`- EdgeMTLSAssetsDir string `env:"EDGE_MTLS_ASSETS_DIR" default:""`+ PUID string `env:"PUID" default:""`+ PGID string `env:"PGID" default:""`+ DockerHost string `env:"DOCKER_HOST" default:"unix:///var/run/docker.sock"`+ DockerConfig string `env:"DOCKER_CONFIG" default:""`+ ProjectsDirectory string `env:"PROJECTS_DIRECTORY" default:"/app/data/projects"`+ TemplatesDirectory string `env:"TEMPLATES_DIRECTORY" default:"/app/data/templates"`+ ProjectScanMaxDepth int `env:"PROJECT_SCAN_MAX_DEPTH" default:"3"`+ ProjectWorkspaceMaxDepth int `env:"PROJECT_WORKSPACE_MAX_DEPTH" default:"20"`+ ProjectWorkspaceMaxEntries int `env:"PROJECT_WORKSPACE_MAX_ENTRIES" default:"2000"`+ ProjectWorkspaceMaxFileSizeMB int `env:"PROJECT_WORKSPACE_MAX_FILE_SIZE_MB" default:"10"`+ ProjectScanSkipDirs string `env:"PROJECT_SCAN_SKIP_DIRS" default:".git,node_modules,vendor,.venv,venv,__pycache__,.cache,dist,build,target,.next,.nuxt,.svelte-kit"`+ VolumeWorkspaceMaxDepth int `env:"VOLUME_WORKSPACE_MAX_DEPTH" default:"50"`+ VolumeWorkspaceMaxEntries int `env:"VOLUME_WORKSPACE_MAX_ENTRIES" default:"10000"`+ VolumeWorkspaceMaxFileSizeMB int `env:"VOLUME_WORKSPACE_MAX_FILE_SIZE_MB" default:"10"`+ LogJson bool `env:"LOG_JSON" default:"false"`+ LogLevel string `env:"LOG_LEVEL" default:"info" options:"toLower"`+ AgentMode bool `env:"AGENT_MODE" default:"false"`+ AgentToken string `env:"AGENT_TOKEN" default:"" options:"file"`+ ManagerApiUrl string `env:"MANAGER_API_URL" default:""`+ UpdateCheckDisabled bool `env:"UPDATE_CHECK_DISABLED" default:"false"`+ UIConfigurationDisabled bool `env:"UI_CONFIGURATION_DISABLED" default:"false"`+ AnalyticsDisabled bool `env:"ANALYTICS_DISABLED" default:"false"`+ GPUMonitoringEnabled bool `env:"GPU_MONITORING_ENABLED" default:"false"`+ GPUType string `env:"GPU_TYPE" default:"auto"`+ EdgeAgent bool `env:"EDGE_AGENT" default:"false"`+ EdgeTransport string `env:"EDGE_TRANSPORT" default:"auto" options:"toLower"`+ EdgeReconnectInterval int `env:"EDGE_RECONNECT_INTERVAL" default:"5"` // seconds+ EdgeMTLSMode string `env:"EDGE_MTLS_MODE" default:"disabled" options:"toLower"`+ EdgeMTLSCAFile string `env:"EDGE_MTLS_CA_FILE" default:""`+ EdgeMTLSCertFile string `env:"EDGE_MTLS_CERT_FILE" default:""`+ EdgeMTLSKeyFile string `env:"EDGE_MTLS_KEY_FILE" default:""`+ EdgeMTLSServerName string `env:"EDGE_MTLS_SERVER_NAME" default:""`+ EdgeMTLSAssetsDir string `env:"EDGE_MTLS_ASSETS_DIR" default:""`TrustedProxies string `env:"TRUSTED_PROXIES" default:""`@@ -118,6 +123,7 @@ func Load() *Config {applyOptions(cfg)applyAgentModeDefaults(cfg)applyProxyDefaults(cfg)+ applyWorkspaceDefaults(cfg)// Set global file permissionspkgutils.FilePerm = cfg.FilePerm@@ -126,20 +132,46 @@ func Load() *Config {return cfg}-type ProjectFilesConfig struct {- ProjectScanMaxDepth int- ProjectFileTreeMaxDepth int- ProjectScanSkipDirs string+type ProjectWorkspaceConfig struct {+ ProjectScanMaxDepth int+ ProjectWorkspaceMaxDepth int+ ProjectWorkspaceMaxEntries int+ ProjectWorkspaceMaxFileSizeMB int+ ProjectScanSkipDirs string}-func LoadProjectFilesConfig() ProjectFilesConfig {+func LoadProjectWorkspaceConfig() ProjectWorkspaceConfig {cfg := &Config{}loadFromEnv(cfg)+ applyWorkspaceDefaults(cfg)- return ProjectFilesConfig{- ProjectScanMaxDepth: cfg.ProjectScanMaxDepth,- ProjectFileTreeMaxDepth: cfg.ProjectFileTreeMaxDepth,- ProjectScanSkipDirs: cfg.ProjectScanSkipDirs,+ return ProjectWorkspaceConfig{+ ProjectScanMaxDepth: cfg.ProjectScanMaxDepth,+ ProjectWorkspaceMaxDepth: cfg.ProjectWorkspaceMaxDepth,+ ProjectWorkspaceMaxEntries: cfg.ProjectWorkspaceMaxEntries,+ ProjectWorkspaceMaxFileSizeMB: cfg.ProjectWorkspaceMaxFileSizeMB,+ ProjectScanSkipDirs: cfg.ProjectScanSkipDirs,+ }+}++func applyWorkspaceDefaults(cfg *Config) {+ if cfg.ProjectWorkspaceMaxDepth <= 0 {+ cfg.ProjectWorkspaceMaxDepth = 20+ }+ if cfg.ProjectWorkspaceMaxEntries <= 0 {+ cfg.ProjectWorkspaceMaxEntries = 2000+ }+ if cfg.ProjectWorkspaceMaxFileSizeMB <= 0 {+ cfg.ProjectWorkspaceMaxFileSizeMB = 10+ }+ if cfg.VolumeWorkspaceMaxDepth <= 0 {+ cfg.VolumeWorkspaceMaxDepth = 50+ }+ if cfg.VolumeWorkspaceMaxEntries <= 0 {+ cfg.VolumeWorkspaceMaxEntries = 10000+ }+ if cfg.VolumeWorkspaceMaxFileSizeMB <= 0 {+ cfg.VolumeWorkspaceMaxFileSizeMB = 10}}diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.goindex 8eddfc3e6..e4fc3a280 100644--- a/backend/internal/config/config_test.go+++ b/backend/internal/config/config_test.go@@ -60,6 +60,55 @@ func TestConfig_LoadPermissions(t *testing.T) {})}+func TestConfig_LoadWorkspaceLimits(t *testing.T) {+ t.Run("defaults", func(t *testing.T) {+ cfg := Load()+ require.Equal(t, 20, cfg.ProjectWorkspaceMaxDepth)+ require.Equal(t, 2000, cfg.ProjectWorkspaceMaxEntries)+ require.Equal(t, 10, cfg.ProjectWorkspaceMaxFileSizeMB)+ require.Equal(t, 50, cfg.VolumeWorkspaceMaxDepth)+ require.Equal(t, 10000, cfg.VolumeWorkspaceMaxEntries)+ require.Equal(t, 10, cfg.VolumeWorkspaceMaxFileSizeMB)+ })++ t.Run("positive overrides", func(t *testing.T) {+ t.Setenv("PROJECT_WORKSPACE_MAX_DEPTH", "25")+ t.Setenv("PROJECT_WORKSPACE_MAX_ENTRIES", "2500")+ t.Setenv("PROJECT_WORKSPACE_MAX_FILE_SIZE_MB", "12")+ t.Setenv("VOLUME_WORKSPACE_MAX_DEPTH", "75")+ t.Setenv("VOLUME_WORKSPACE_MAX_ENTRIES", "20000")+ t.Setenv("VOLUME_WORKSPACE_MAX_FILE_SIZE_MB", "18")++ cfg := Load()+ require.Equal(t, 25, cfg.ProjectWorkspaceMaxDepth)+ require.Equal(t, 2500, cfg.ProjectWorkspaceMaxEntries)+ require.Equal(t, 12, cfg.ProjectWorkspaceMaxFileSizeMB)+ require.Equal(t, 75, cfg.VolumeWorkspaceMaxDepth)+ require.Equal(t, 20000, cfg.VolumeWorkspaceMaxEntries)+ require.Equal(t, 18, cfg.VolumeWorkspaceMaxFileSizeMB)+ })++ for _, value := range []string{"0", "-1", "not-a-number"} {+ t.Run("invalid values fall back "+value, func(t *testing.T) {+ t.Setenv("PROJECT_WORKSPACE_MAX_FILE_SIZE_MB", value)+ t.Setenv("VOLUME_WORKSPACE_MAX_FILE_SIZE_MB", value)+ cfg := Load()+ require.Equal(t, 10, cfg.ProjectWorkspaceMaxFileSizeMB)+ require.Equal(t, 10, cfg.VolumeWorkspaceMaxFileSizeMB)+ })+ }++ t.Run("old names are not aliases", func(t *testing.T) {+ t.Setenv("PROJECT_FILE_TREE_MAX_DEPTH", "99")+ t.Setenv("VOLUME_FILE_TREE_MAX_DEPTH", "99")+ t.Setenv("VOLUME_FILE_TREE_MAX_ENTRIES", "99")+ cfg := Load()+ require.Equal(t, 20, cfg.ProjectWorkspaceMaxDepth)+ require.Equal(t, 50, cfg.VolumeWorkspaceMaxDepth)+ require.Equal(t, 10000, cfg.VolumeWorkspaceMaxEntries)+ })+}+func TestConfig_DockerSecretsFileSupport(t *testing.T) {// Save original env varsorigEncryptionKey := os.Getenv("ENCRYPTION_KEY")diff --git a/backend/internal/config/schema/schema_test.go b/backend/internal/config/schema/schema_test.goindex 2a78e98a9..a7cd33c14 100644--- a/backend/internal/config/schema/schema_test.go+++ b/backend/internal/config/schema/schema_test.go@@ -247,9 +247,11 @@ var expectedEnvConfigVars = []string{"PGID","PORT","PROJECTS_DIRECTORY",- "PROJECT_FILE_TREE_MAX_DEPTH","PROJECT_SCAN_MAX_DEPTH","PROJECT_SCAN_SKIP_DIRS",+ "PROJECT_WORKSPACE_MAX_DEPTH",+ "PROJECT_WORKSPACE_MAX_ENTRIES",+ "PROJECT_WORKSPACE_MAX_FILE_SIZE_MB","PROXY_REQUEST_TIMEOUT","PUID","REGISTRY_TIMEOUT",@@ -262,6 +264,9 @@ var expectedEnvConfigVars = []string{"TZ","UI_CONFIGURATION_DISABLED","UPDATE_CHECK_DISABLED",+ "VOLUME_WORKSPACE_MAX_DEPTH",+ "VOLUME_WORKSPACE_MAX_ENTRIES",+ "VOLUME_WORKSPACE_MAX_FILE_SIZE_MB",}var expectedSettingOverrideKeys = []string{@@ -360,7 +365,7 @@ var expectedSettingOverrideKeys = []string{"trivyServerEnabled","trivyServerToken","trivyServerUrl",- "volumeBrowserHelperIdleTimeout",+ "volumeHelperIdleTimeout","vulnerabilityScanEnabled","vulnerabilityScanInterval",}diff --git a/backend/internal/dashboard/service_test.go b/backend/internal/dashboard/service_test.goindex 1a2a0515f..74320434a 100644--- a/backend/internal/dashboard/service_test.go+++ b/backend/internal/dashboard/service_test.go@@ -182,7 +182,7 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {Status: models.ProjectStatusStopped,}).Error)projectSvc := project.NewProjectService(db, settingsSvc, nil, image.NewImageService(db, nil, nil, nil, nil, nil), nil, nil, nil, nil, config.Load())- svc := NewDashboardService(db, dockerSvc, nil, projectSvc, nil, settingsSvc, nil, nil, nil, volume.NewVolumeService(db, nil, nil, nil, nil, ""))+ svc := NewDashboardService(db, dockerSvc, nil, projectSvc, nil, settingsSvc, nil, nil, nil, volume.NewVolumeService(db, nil, nil, nil, nil, nil))snapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{})require.NoError(t, err)diff --git a/backend/internal/database/database_test.go b/backend/internal/database/database_test.goindex 9d6e32004..2c7d52c29 100644--- a/backend/internal/database/database_test.go+++ b/backend/internal/database/database_test.go@@ -202,6 +202,43 @@ func TestMigration070_PasskeysAndMFA_UpAndDown(t *testing.T) {assert.Zero(t, columnCount)}+func TestMigration071_RenamesVolumeWorkspaceLegacyKeys(t *testing.T) {+ ctx := context.Background()+ rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-volume-workspace-keys.db")++ require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 70))+ _, err := rawDB.Exec(`DELETE FROM settings WHERE key = 'volumeHelperIdleTimeout'`)+ require.NoError(t, err)+ _, err = rawDB.Exec(`INSERT INTO settings (key, value) VALUES ('volumeBrowserHelperIdleTimeout', '27')`)+ require.NoError(t, err)+ _, err = rawDB.Exec(`INSERT INTO roles (id, name, permissions) VALUES ('role-workspace', 'Workspace role', '["volumes:browse","volumes:read","volumes:upload"]')`)+ require.NoError(t, err)+ _, err = rawDB.Exec(`INSERT INTO api_keys (id, name, key_hash, key_prefix) VALUES ('key-workspace', 'Workspace key', 'hash', 'arc_')`)+ require.NoError(t, err)+ _, err = rawDB.Exec(`INSERT INTO api_key_permissions (id, api_key_id, permission) VALUES ('grant-browse', 'key-workspace', 'volumes:browse'), ('grant-read', 'key-workspace', 'volumes:read')`)+ require.NoError(t, err)++ require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 71))+ var timeout string+ require.NoError(t, rawDB.QueryRow(`SELECT value FROM settings WHERE key = 'volumeHelperIdleTimeout'`).Scan(&timeout))+ assert.Equal(t, "27", timeout)+ var count int+ require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM settings WHERE key = 'volumeBrowserHelperIdleTimeout'`).Scan(&count))+ assert.Zero(t, count)+ require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM json_each((SELECT permissions FROM roles WHERE id = 'role-workspace')) WHERE value = 'volumes:read'`).Scan(&count))+ assert.Equal(t, 1, count)+ require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM json_each((SELECT permissions FROM roles WHERE id = 'role-workspace')) WHERE value = 'volumes:browse'`).Scan(&count))+ assert.Zero(t, count)+ require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM api_key_permissions WHERE api_key_id = 'key-workspace' AND permission = 'volumes:read'`).Scan(&count))+ assert.Equal(t, 1, count)+ require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM api_key_permissions WHERE permission = 'volumes:browse'`).Scan(&count))+ assert.Zero(t, count)++ require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{AllowDowngrade: true}, 70))+ require.NoError(t, rawDB.QueryRow(`SELECT value FROM settings WHERE key = 'volumeBrowserHelperIdleTimeout'`).Scan(&timeout))+ assert.Equal(t, "27", timeout)+}+func TestMigrateDatabase_BlocksFutureGooseVersionWithoutFlag(t *testing.T) {ctx := context.Background()rawDB, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-future.db")diff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.goindex 13cd241df..715c05ae3 100644--- a/backend/internal/di/providers.go+++ b/backend/internal/di/providers.go@@ -212,13 +212,13 @@ func provideGitRepositoryServiceInternal(module *gitrepo.Module) *gitrepo.GitRepfunc provideVolumeModuleInternal(lc fx.Lifecycle, db *database.DB, docker *docker.DockerClientService, event *event.EventService, settings *settings.SettingsService, image *image.ImageService, activity *activity.ActivityService, cfg *config.Config) *volume.Module {module := volume.New(volume.Dependencies{- DB: db,- Docker: docker,- Event: event,- Settings: settings,- Image: image,- Activity: activity,- BackupVolumeName: cfg.BackupVolumeName,+ DB: db,+ Docker: docker,+ Event: event,+ Settings: settings,+ Image: image,+ Activity: activity,+ Config: cfg,})lc.Append(fx.Hook{OnStop: func(ctx context.Context) error {diff --git a/backend/internal/event/service.go b/backend/internal/event/service.goindex 7b6cad3d6..b5c336565 100644--- a/backend/internal/event/service.go+++ b/backend/internal/event/service.go@@ -671,6 +671,8 @@ var eventDefinitions = map[models.EventType]eventDefinition{models.EventTypeVolumeFileCreate: {"Volume file created: %s", "A file or directory was created in volume '%s'", models.EventSeveritySuccess},models.EventTypeVolumeFileDelete: {"Volume file deleted: %s", "A file or directory was deleted in volume '%s'", models.EventSeverityWarning},models.EventTypeVolumeFileUpload: {"Volume file uploaded: %s", "A file was uploaded to volume '%s'", models.EventSeveritySuccess},+ models.EventTypeVolumeFileUpdate: {"Volume workspace updated: %s", "Files in volume '%s' were updated", models.EventSeverityInfo},+ models.EventTypeVolumeWorkspaceUpdate: {"Volume workspace updated: %s", "Workspace files in volume '%s' were updated", models.EventSeverityInfo},models.EventTypeVolumeBackupCreate: {"Volume backup created: %s", "A backup was created for volume '%s'", models.EventSeveritySuccess},models.EventTypeVolumeBackupDelete: {"Volume backup deleted: %s", "A backup was deleted for volume '%s'", models.EventSeverityWarning},models.EventTypeVolumeBackupRestore: {"Volume backup restored: %s", "A backup was restored for volume '%s'", models.EventSeverityWarning},diff --git a/backend/internal/gitops/gitops_sync.go b/backend/internal/gitops/gitops_sync.goindex c8ba9976e..79be9b4fa 100644--- a/backend/internal/gitops/gitops_sync.go+++ b/backend/internal/gitops/gitops_sync.go@@ -1483,7 +1483,7 @@ func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, sy// Use the non-suffixing create: a GitOps sync must never mint a "-N" duplicate.// A name collision means a project directory already exists for this name, so the// binding is broken — fail loudly and disable auto-sync instead of duplicating.- project, err := s.projectService.CreateProject(ctx, sync.ProjectName, composeContent, envContent, nil, actor, false)+ project, err := s.projectService.CreateProject(ctx, sync.ProjectName, composeContent, envContent, projecttypes.CreateProjectWorkspaceManifest{}, nil, actor, false)if err != nil {if errors.Is(err, projects.ErrProjectDirExists) {bindingErr := common.Classify(common.ErrGitOpsSyncProjectBindingBroken, errors.WrapIf(errors.Errorf("sync %s cannot create project %q: a directory with that name already exists; refusing to create a duplicate", sync.ID, projects.SanitizeProjectName(sync.ProjectName)), "GitOps sync project binding broken"))diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.goindex ac1327489..ca938175f 100644--- a/backend/internal/middleware/environment_middleware.go+++ b/backend/internal/middleware/environment_middleware.go@@ -4,9 +4,13 @@ import ("github.com/samber/mo""context"+ "encoding/json/v2""io""log/slog"+ "mime"+ "mime/multipart""net/http"+ "os""path""strings""time"@@ -19,6 +23,7 @@ import (wsutil "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/labstack/echo/v5")@@ -29,6 +34,8 @@ const (// proxyTimeout is intentionally generous because some proxied operations// (e.g., image pulls with progress streaming) can take multiple minutes.proxyTimeout = 30 * time.Minute++ maxProxiedWorkspaceManifestBytes = 1024 * 1024)// managementEndpointSet contains paths handled locally and never proxied to remote environments.@@ -239,9 +246,106 @@ func (m *EnvironmentMiddleware) proxyPermissionDenied(c *echo.Context, ps *authz"method", method, "path", suffix, "permission", perm, "environment_id", envID)return true}+ if isVolumeWorkspaceUpdateRequestInternal(method, suffix) {+ required, err := proxiedVolumeWorkspacePermissionsInternal(c.Request())+ if err != nil {+ slog.DebugContext(c.Request().Context(), "Denying proxied volume workspace request with invalid manifest",+ "path", suffix, "environment_id", envID, "error", err)+ return true+ }+ for _, operationPermission := range required {+ if !ps.Allows(operationPermission, envID) {+ slog.DebugContext(c.Request().Context(), "Denying proxied volume workspace operation",+ "path", suffix, "permission", operationPermission, "environment_id", envID)+ return true+ }+ }+ }return false}+func isVolumeWorkspaceUpdateRequestInternal(method, suffix string) bool {+ if method != http.MethodPut {+ return false+ }+ segments := strings.Split(strings.Trim(suffix, "/"), "/")+ return len(segments) == 3 && segments[0] == "volumes" && segments[1] != "" && segments[2] == "workspace"+}++func proxiedVolumeWorkspacePermissionsInternal(request *http.Request) ([]string, error) {+ if request == nil || request.Body == nil {+ return nil, errors.New("missing multipart request body")+ }+ mediaType, params, err := mime.ParseMediaType(request.Header.Get("Content-Type"))+ if err != nil || mediaType != "multipart/form-data" || params["boundary"] == "" {+ return nil, errors.New("invalid multipart content type")+ }++ originalBody := request.Body+ captured, err := os.CreateTemp("", "arcane-volume-workspace-manifest-*")+ if err != nil {+ return nil, errors.WrapIf(err, "create workspace manifest buffer")+ }+ defer func() {+ _, _ = captured.Seek(0, io.SeekStart)+ request.Body = &proxiedReplayBodyInternal{+ Reader: io.MultiReader(captured, originalBody),+ captured: captured,+ original: originalBody,+ path: captured.Name(),+ }+ }()++ reader := multipart.NewReader(io.TeeReader(originalBody, captured), params["boundary"])+ for {+ part, nextErr := reader.NextPart()+ if nextErr != nil {+ return nil, errors.WrapIf(nextErr, "find workspace manifest part")+ }+ if part.FormName() != "manifest" || part.FileName() != "" {+ if closeErr := part.Close(); closeErr != nil {+ return nil, errors.WrapIf(closeErr, "skip multipart field before workspace manifest")+ }+ continue+ }+ manifestJSON, readErr := io.ReadAll(io.LimitReader(part, maxProxiedWorkspaceManifestBytes+1))+ closeErr := part.Close()+ if readErr != nil {+ return nil, errors.WrapIf(readErr, "read workspace manifest")+ }+ if closeErr != nil {+ return nil, errors.WrapIf(closeErr, "close workspace manifest part")+ }+ if len(manifestJSON) > maxProxiedWorkspaceManifestBytes {+ return nil, errors.New("workspace manifest is too large")+ }+ var manifest volumetypes.WorkspaceUpdateManifest+ if err := json.Unmarshal(manifestJSON, &manifest); err != nil {+ return nil, errors.WrapIf(err, "decode workspace manifest")+ }+ required, valid := authz.VolumeWorkspaceRequiredPermissions(manifest.FileChanges)+ if !valid {+ return nil, errors.New("workspace manifest contains an unknown operation")+ }+ return required, nil+ }+}++type proxiedReplayBodyInternal struct {+ io.Reader++ captured *os.File+ original io.ReadCloser+ path string+}++func (b *proxiedReplayBodyInternal) Close() error {+ capturedErr := b.captured.Close()+ originalErr := b.original.Close()+ removeErr := os.Remove(b.path)+ return errors.Combine(capturedErr, originalErr, removeErr)+}+func (m *EnvironmentMiddleware) proxyActiveEdgeTunnelInternal(c *echo.Context, envID string, accessToken *string) (bool, error) {tunnel, ok := m.getActiveEdgeTunnelInternal(envID).Get()if !ok {diff --git a/backend/internal/middleware/environment_middleware_authz_test.go b/backend/internal/middleware/environment_middleware_authz_test.goindex 9127ef584..9cf656c69 100644--- a/backend/internal/middleware/environment_middleware_authz_test.go+++ b/backend/internal/middleware/environment_middleware_authz_test.go@@ -1,6 +1,10 @@package middlewareimport (+ "bytes"+ "encoding/json/v2"+ "io"+ "mime/multipart""net/http""net/http/httptest""testing"@@ -8,6 +12,7 @@ import ("github.com/labstack/echo/v5""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/stretchr/testify/require")@@ -112,6 +117,67 @@ func TestProxyPermissionDeniedAllowsPublicRoute(t *testing.T) {}+func volumeWorkspaceMatcher() *authz.PermissionMatcher {+ m := authz.NewPermissionMatcher()+ m.Add(http.MethodPut, "/volumes/{volumeName}/workspace", authz.PermVolumesRead)+ return m+}++func newProxyVolumeWorkspaceContext(t *testing.T, changes []volumetypes.WorkspaceFileChange, fileFirst ...bool) (*echo.Context, []byte) {+ t.Helper()+ var body bytes.Buffer+ writer := multipart.NewWriter(&body)+ if len(fileFirst) == 1 && fileFirst[0] {+ filePart, err := writer.CreateFormFile("files", "example.txt")+ require.NoError(t, err)+ _, err = filePart.Write([]byte("content"))+ require.NoError(t, err)+ }+ manifestPart, err := writer.CreateFormField("manifest")+ require.NoError(t, err)+ manifestJSON, err := json.Marshal(volumetypes.WorkspaceUpdateManifest{FileTreeRevision: "revision", FileChanges: changes})+ require.NoError(t, err)+ _, err = manifestPart.Write(manifestJSON)+ require.NoError(t, err)+ require.NoError(t, writer.Close())++ rawBody := append([]byte(nil), body.Bytes()...)+ e := echo.New()+ req := httptest.NewRequest(http.MethodPut, "/api/environments/"+proxyTestEnvID+"/volumes/data/workspace", bytes.NewReader(rawBody))+ req.Header.Set("Content-Type", writer.FormDataContentType())+ t.Cleanup(func() { _ = req.Body.Close() })+ return e.NewContext(req, httptest.NewRecorder()), rawBody+}++func TestProxyPermissionDeniedChecksVolumeWorkspaceManifestPermissions(t *testing.T) {+ m := newProxyAuthzMiddleware(volumeWorkspaceMatcher())+ changes := []volumetypes.WorkspaceFileChange{{Operation: volumetypes.FileOpRename}}++ readOnly := authz.NewPermissionSet()+ readOnly.AddEnv(proxyTestEnvID, authz.PermVolumesRead)+ c, _ := newProxyVolumeWorkspaceContext(t, changes)+ require.True(t, m.proxyPermissionDenied(c, readOnly, proxyTestEnvID))++ uploadOnly := authz.NewPermissionSet()+ uploadOnly.AddEnv(proxyTestEnvID, authz.PermVolumesRead, authz.PermVolumesUpload)+ c, _ = newProxyVolumeWorkspaceContext(t, changes)+ require.True(t, m.proxyPermissionDenied(c, uploadOnly, proxyTestEnvID))++ permitted := authz.NewPermissionSet()+ permitted.AddEnv(proxyTestEnvID, authz.PermVolumesRead, authz.PermVolumesUpload, authz.PermVolumesDelete)+ c, rawBody := newProxyVolumeWorkspaceContext(t, changes)+ require.False(t, m.proxyPermissionDenied(c, permitted, proxyTestEnvID))+ replayed, err := io.ReadAll(c.Request().Body)+ require.NoError(t, err)+ require.Equal(t, rawBody, replayed)++ c, rawBody = newProxyVolumeWorkspaceContext(t, changes, true)+ require.False(t, m.proxyPermissionDenied(c, permitted, proxyTestEnvID))+ replayed, err = io.ReadAll(c.Request().Body)+ require.NoError(t, err)+ require.Equal(t, rawBody, replayed)+}+// wsTerminalMatcher mirrors ws.AddProxiedPermissions for the container terminal// stream: the proxy computes the suffix "/ws/containers/{id}/terminal" for a// forwarded WebSocket request, and the matcher requires containers:exec for it.diff --git a/backend/internal/models/event.go b/backend/internal/models/event.goindex 21b5bee79..bb08b2352 100644--- a/backend/internal/models/event.go+++ b/backend/internal/models/event.go@@ -57,9 +57,11 @@ const (EventTypeVolumeDelete EventType = "volume.delete"EventTypeVolumeError EventType = "volume.error"- EventTypeVolumeFileCreate EventType = "volume.file.create"- EventTypeVolumeFileDelete EventType = "volume.file.delete"- EventTypeVolumeFileUpload EventType = "volume.file.upload"+ EventTypeVolumeFileCreate EventType = "volume.file.create"+ EventTypeVolumeFileDelete EventType = "volume.file.delete"+ EventTypeVolumeFileUpload EventType = "volume.file.upload"+ EventTypeVolumeFileUpdate EventType = "volume.file.update"+ EventTypeVolumeWorkspaceUpdate EventType = "volume.workspace.update"EventTypeVolumeBackupCreate EventType = "volume.backup.create"EventTypeVolumeBackupDelete EventType = "volume.backup.delete"diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.goindex 04041b8e7..6ff169411 100644--- a/backend/internal/models/settings.go+++ b/backend/internal/models/settings.go@@ -108,7 +108,7 @@ type Settings struct {AutoHealExcludedContainers SettingVariable `key:"autoHealExcludedContainers" meta:"label=Auto Heal Excluded Containers;type=text;keywords=auto,heal,exclude,containers,ignore,skip,health;category=internal;description=Comma-separated list of containers to exclude from auto-heal"`AutoHealMaxRestarts SettingVariable `key:"autoHealMaxRestarts" meta:"label=Auto Heal Max Restarts;type=number;keywords=auto,heal,max,restarts,limit,loop,protection;category=internal;description=Maximum auto-heal restarts per container within the restart window (default: 5)"`AutoHealRestartWindow SettingVariable `key:"autoHealRestartWindow" meta:"label=Auto Heal Restart Window;type=number;keywords=auto,heal,restart,window,minutes,cooldown,protection;category=internal;description=Time window in minutes for counting auto-heal restarts (default: 30)"`- VolumeBrowserHelperIdleTimeout SettingVariable `key:"volumeBrowserHelperIdleTimeout" meta:"label=Volume Browser Idle Timeout;type=number;keywords=volume,browser,helper,idle,timeout,cleanup,reaper,minutes;category=internal;description=Minutes a volume-browser helper container may sit idle before automatic removal (default: 10; 0 disables)"`+ VolumeHelperIdleTimeout SettingVariable `key:"volumeHelperIdleTimeout" meta:"label=Volume Helper Idle Timeout;type=number;keywords=volume,workspace,helper,idle,timeout,cleanup,reaper,minutes;category=internal;description=Minutes a volume helper container may sit idle before automatic removal (default: 10; 0 disables)"`MaxImageUploadSize SettingVariable `key:"maxImageUploadSize" meta:"label=Max Image Upload Size;type=number;keywords=upload,size,limit,maximum,image,tar,file,megabytes,mb,storage;category=internal;description=Maximum size in MB for image archive uploads (default: 500)"`GitSyncMaxFiles SettingVariable `key:"gitSyncMaxFiles,envOverride" meta:"label=Git Sync Max Files;type=number;keywords=git,sync,files,limit,repository,compose,gitops;category=general;description=Maximum number of repository files copied during a Git sync. Set 0 to disable the environment cap (default: 500)"`GitSyncMaxTotalSizeMb SettingVariable `key:"gitSyncMaxTotalSizeMb,envOverride" meta:"label=Git Sync Max Total Size (MB);type=number;keywords=git,sync,size,limit,repository,compose,gitops,mb;category=general;description=Maximum combined size in MB for files copied during a Git sync. Set 0 to disable the environment cap (default: 50)"`diff --git a/backend/internal/project/handler.go b/backend/internal/project/handler.goindex a38c61017..8a21275a7 100644--- a/backend/internal/project/handler.go+++ b/backend/internal/project/handler.go@@ -6,6 +6,7 @@ import ("fmt""io""log/slog"+ "mime/multipart""net/http""strings""time"@@ -24,6 +25,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"+ workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/project""github.com/samber/mo"@@ -82,8 +84,8 @@ type DownProjectOutput struct {}type CreateProjectInput struct {- EnvironmentID string `path:"id" doc:"Environment ID"`- Body project.CreateProject+ EnvironmentID string `path:"id" doc:"Environment ID"`+ RawBody multipart.Form `contentType:"multipart/form-data"`}type CreateProjectOutput struct {@@ -99,16 +101,6 @@ type GetProjectOutput struct {Body base.ApiResponse[project.Details]}-type GetProjectFileInput struct {- EnvironmentID string `path:"id" doc:"Environment ID"`- ProjectID string `path:"projectId" doc:"Project ID"`- RelativePath string `query:"relativePath" doc:"Path to the file relative to the project"`-}--type GetProjectFileOutput struct {- Body base.ApiResponse[project.IncludeFile]-}-type RedeployProjectInput struct {EnvironmentID string `path:"id" doc:"Environment ID"`ProjectID string `path:"projectId" doc:"Project ID"`@@ -135,16 +127,6 @@ type UpdateProjectOutput struct {Body base.ApiResponse[project.Details]}-type UpdateProjectIncludeInput struct {- EnvironmentID string `path:"id" doc:"Environment ID"`- ProjectID string `path:"projectId" doc:"Project ID"`- Body project.UpdateIncludeFile-}--type UpdateProjectIncludeOutput struct {- Body base.ApiResponse[project.Details]-}-type RestartProjectInput struct {EnvironmentID string `path:"id" doc:"Environment ID"`ProjectID string `path:"projectId" doc:"Project ID"`@@ -209,6 +191,7 @@ func RegisterProjects(api huma.API, projectService *ProjectService, activityServactivityService: activityService,appCtx: appCtx.Context(),}+ registerProjectWorkspaceRoutesInternal(api, h)middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-projects",@@ -258,6 +241,21 @@ func RegisterProjects(api huma.API, projectService *ProjectService, activityServDescription: "Create a new Docker Compose project",Tags: []string{"Projects"},Security: handlerutil.DefaultOperationSecurity(),+ RequestBody: &huma.RequestBody{+ Content: map[string]*huma.MediaType{+ "multipart/form-data": {+ Schema: &huma.Schema{+ Type: "object",+ Properties: map[string]*huma.Schema{+ "project": {Type: "string", Description: "JSON encoded project configuration"},+ "manifest": {Type: "string", Description: "JSON encoded initial project workspace manifest"},+ "files": {Type: "array", Items: &huma.Schema{Type: "string", Format: "binary"}},+ },+ Required: []string{"project", "manifest"},+ },+ },+ },+ },}, authz.PermProjectsCreate, h.CreateProject)middleware.RegisterWithPermission(api, huma.Operation{@@ -280,16 +278,6 @@ func RegisterProjects(api huma.API, projectService *ProjectService, activityServSecurity: handlerutil.DefaultOperationSecurity(),}, authz.PermProjectsRead, h.GetProjectCompose)- middleware.RegisterWithPermission(api, huma.Operation{- OperationID: "get-project-files",- Method: http.MethodGet,- Path: "/environments/{id}/projects/{projectId}/files",- Summary: "Get project files",- Description: "Get directory files for a project",- Tags: []string{"Projects"},- Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermProjectsRead, h.GetProjectFiles)-middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-project-runtime",Method: http.MethodGet,@@ -310,16 +298,6 @@ func RegisterProjects(api huma.API, projectService *ProjectService, activityServSecurity: handlerutil.DefaultOperationSecurity(),}, authz.PermProjectsRead, h.GetProjectUpdates)- middleware.RegisterWithPermission(api, huma.Operation{- OperationID: "get-project-file",- Method: http.MethodGet,- Path: "/environments/{id}/projects/{projectId}/file",- Summary: "Get a project file",- Description: "Get the contents of a single project-related file by relative path",- Tags: []string{"Projects"},- Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermProjectsRead, h.GetProjectFile)-middleware.RegisterWithPermission(api, huma.Operation{OperationID: "redeploy-project",Method: http.MethodPost,@@ -350,16 +328,6 @@ func RegisterProjects(api huma.API, projectService *ProjectService, activityServSecurity: handlerutil.DefaultOperationSecurity(),}, authz.PermProjectsUpdate, h.UpdateProject)- middleware.RegisterWithPermission(api, huma.Operation{- OperationID: "update-project-include",- Method: http.MethodPut,- Path: "/environments/{id}/projects/{projectId}/includes",- Summary: "Update project include file",- Description: "Update an include file within a Docker Compose project",- Tags: []string{"Projects"},- Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermProjectsUpdate, h.UpdateProjectInclude)-middleware.RegisterWithPermission(api, huma.Operation{OperationID: "restart-project",Method: http.MethodPost,@@ -614,19 +582,19 @@ func projectUpdateHTTPErrorInternal(err error) error {if spaceErr, ok := stderrors.AsType[*volumes.ProjectVolumeRenameInsufficientSpaceError](err); ok {return huma.NewError(http.StatusInsufficientStorage, spaceErr.Error())}- return projectFileHTTPError(err)+ return projectWorkspaceRequestHTTPErrorInternal(err)}-// projectFileHTTPError maps project file management errors to HTTP errors.-// It returns nil when err is not a project file error.-func projectFileHTTPError(err error) error {- if errors.Is(err, common.ErrProjectFileConflict) {+// projectWorkspaceRequestHTTPErrorInternal maps workspace validation errors that+// can also surface during atomic project creation or configuration updates.+func projectWorkspaceRequestHTTPErrorInternal(err error) error {+ if errors.Is(err, common.ErrProjectWorkspaceConflict) {return huma.Error409Conflict(err.Error())}- if errors.Is(err, common.ErrProjectFileForbidden) {+ if errors.Is(err, common.ErrProjectWorkspaceForbidden) {return huma.Error403Forbidden(err.Error())}- if errors.Is(err, common.ErrProjectFileBadRequest) {+ if errors.Is(err, common.ErrProjectWorkspaceBadRequest) {return huma.Error400BadRequest(err.Error())}return nil@@ -634,6 +602,22 @@ func projectFileHTTPError(err error) error {// CreateProject creates a new Docker Compose project.func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectInput) (*CreateProjectOutput, error) {+ projectInput, err := handlerutil.ParseMultipartJSONPart[project.CreateProject](input.RawBody, "project")+ if err != nil {+ return nil, err+ }+ manifest, err := handlerutil.ParseMultipartJSONPart[project.CreateProjectWorkspaceManifest](input.RawBody, "manifest")+ if err != nil {+ return nil, err+ }+ maxFileSizeMB := workspacepkg.DefaultMaxFileSizeMB+ if h.projectService != nil && h.projectService.config != nil {+ maxFileSizeMB = h.projectService.config.ProjectWorkspaceMaxFileSizeMB+ }+ uploads, err := handlerutil.ReadWorkspaceUploads(input.RawBody, workspacepkg.MaxFileSizeBytes(maxFileSizeMB))+ if err != nil {+ return nil, err+ }user, err := handlerutil.RequireUser(ctx)if err != nil {return nil, err@@ -645,8 +629,8 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectEnvironmentID: input.EnvironmentID,Type: models.ActivityTypeResourceAction,ResourceType: "project",- ResourceID: input.Body.Name,- ResourceName: input.Body.Name,+ ResourceID: projectInput.Name,+ ResourceName: projectInput.Name,User: user,Step: "Creating project",Message: "Creating project",@@ -654,11 +638,11 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectMetadata: models.JSON{"action": "create_project"},}, func(runtimeCtx context.Context) error {var createErr error- proj, createErr = h.projectService.CreateProject(runtimeCtx, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent, input.Body.ProjectFiles, *user)+ proj, createErr = h.projectService.CreateProject(runtimeCtx, projectInput.Name, projectInput.ComposeContent, projectInput.EnvContent, manifest, uploads, *user)return createErr})if err != nil {- if httpErr := projectFileHTTPError(err); httpErr != nil {+ if httpErr := projectWorkspaceRequestHTTPErrorInternal(err); httpErr != nil {return nil, httpErr}return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create project").Error())@@ -733,13 +717,6 @@ func (h *ProjectHandler) GetProjectCompose(ctx context.Context, input *GetProjec})}-func (h *ProjectHandler) GetProjectFiles(ctx context.Context, input *GetProjectInput) (*GetProjectOutput, error) {- return h.getProjectDetailsWithOptionsInternal(ctx, input, project.DetailsOptions{- IncludeDirectoryFiles: true,- IncludeProjectFiles: true,- })-}-func (h *ProjectHandler) GetProjectRuntime(ctx context.Context, input *GetProjectInput) (*GetProjectOutput, error) {return h.getProjectDetailsWithOptionsInternal(ctx, input, project.DetailsOptions{IncludeRuntimeServices: true,@@ -753,36 +730,6 @@ func (h *ProjectHandler) GetProjectUpdates(ctx context.Context, input *GetProjec})}-func (h *ProjectHandler) GetProjectFile(ctx context.Context, input *GetProjectFileInput) (*GetProjectFileOutput, error) {- if input.ProjectID == "" {- return nil, huma.Error400BadRequest("Project ID is required")- }- if input.RelativePath == "" {- return nil, huma.Error400BadRequest("relativePath is required")- }-- file, err := h.projectService.GetProjectFileContent(ctx, input.ProjectID, input.RelativePath)- if err != nil {- switch {- case errors.Is(err, common.ErrProjectFileBadRequest):- return nil, huma.Error400BadRequest(err.Error())- case errors.Is(err, common.ErrProjectFileForbidden):- return nil, huma.Error403Forbidden(err.Error())- case errors.Is(err, common.ErrProjectFileNotFound):- return nil, huma.Error404NotFound("project file not found")- default:- return nil, huma.Error500InternalServerError("internal error")- }- }-- return &GetProjectFileOutput{- Body: base.ApiResponse[project.IncludeFile]{- Success: true,- Data: file,- },- }, nil-}-// RedeployProject redeploys a Docker Compose project.// RedeployProject pulls project images and re-deploys, streaming the raw// docker CLI output as NDJSON like DeployProject.@@ -879,7 +826,7 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectSuccessMessage: "Project updated successfully",Metadata: models.JSON{"action": "update_project", "projectID": input.ProjectID},}, func(runtimeCtx context.Context) error {- _, updateErr := h.projectService.UpdateProject(runtimeCtx, input.ProjectID, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent, input.Body.OverrideContent, input.Body.FileTreeRevision, input.Body.FileChanges, *user)+ _, updateErr := h.projectService.UpdateProject(runtimeCtx, input.ProjectID, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent, input.Body.OverrideContent, *user)return updateErr})if err != nil {@@ -889,15 +836,11 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectreturn nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to update project").Error())}- // Skip the recursive directory walks on save: the file tree is only- // re-read when the save actually staged file changes (fresh revision),- // and the frontend fetches /files lazily otherwise.details, err := h.projectService.GetProjectDetails(runtimeCtx, input.ProjectID, project.DetailsOptions{IncludeComposeContent: true,IncludeEnvState: true,IncludeIncludeFiles: true,IncludeServiceConfigs: true,- IncludeProjectFiles: len(input.Body.FileChanges) > 0,IncludeRuntimeServices: true,IncludeUpdateInfo: true,})@@ -914,61 +857,6 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProject}, nil}-// UpdateProjectInclude updates an include file within a project.-func (h *ProjectHandler) UpdateProjectInclude(ctx context.Context, input *UpdateProjectIncludeInput) (*UpdateProjectIncludeOutput, error) {- if input.ProjectID == "" {- return nil, huma.Error400BadRequest("Project ID is required")- }-- 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: models.ActivityTypeResourceAction,- ResourceType: "project",- ResourceID: input.ProjectID,- ResourceName: input.ProjectID,- User: user,- Step: "Updating project file",- Message: "Updating project include file",- SuccessMessage: "Project file updated successfully",- Metadata: models.JSON{- "action": "update_project_include",- "projectID": input.ProjectID,- "relativePath": input.Body.RelativePath,- },- }, func(runtimeCtx context.Context) error {- return h.projectService.UpdateProjectIncludeFile(runtimeCtx, input.ProjectID, input.Body.RelativePath, input.Body.Content, *user)- })- if err != nil {- return nil, huma.Error400BadRequest(errors.WithMessage(err, "Failed to update project").Error())- }-- details, err := h.projectService.GetProjectDetails(runtimeCtx, input.ProjectID, project.DetailsOptions{- IncludeComposeContent: true,- IncludeEnvState: true,- IncludeIncludeFiles: true,- IncludeServiceConfigs: true,- IncludeRuntimeServices: true,- IncludeUpdateInfo: true,- })- if err != nil {- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get project details").Error())- }- details.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()-- return &UpdateProjectIncludeOutput{- Body: base.ApiResponse[project.Details]{- Success: true,- Data: details,- },- }, nil-}-// RestartProject restarts the given services in a project (all services when none// are specified).func (h *ProjectHandler) RestartProject(ctx context.Context, input *RestartProjectInput) (*RestartProjectOutput, error) {diff --git a/backend/internal/project/project_details.go b/backend/internal/project/project_details.goindex cafde37bc..3646c61cf 100644--- a/backend/internal/project/project_details.go+++ b/backend/internal/project/project_details.go@@ -5,7 +5,6 @@ import ("context""io""log/slog"- "os""path/filepath""strings""sync"@@ -14,7 +13,6 @@ import ("emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -259,12 +257,6 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID strings.enrichWithComposeServiceConfigs(ctx, proj, composeFile, &resp)}}- if opts.IncludeDirectoryFiles {- s.enrichWithDirectoryFiles(ctx, proj.Path, &resp)- }- if opts.IncludeProjectFiles {- s.enrichWithProjectFiles(ctx, proj.Path, resp.ComposeFileName, &resp)- }s.enrichWithGitOpsInfo(ctx, proj, &resp)// Refresh runtime status/counts even when callers do not request the full@@ -315,121 +307,6 @@ func buildProjectRuntimeServicesInternal(services []ProjectServiceInfo) []projecreturn runtimeServices}-func (s *ProjectService) GetProjectFileContent(ctx context.Context, projectID, relativePath string) (project.IncludeFile, error) {- proj, err := s.GetProjectFromDatabaseByID(ctx, projectID)- if err != nil {- return project.IncludeFile{}, err- }- if strings.TrimSpace(relativePath) == "" {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: relative path is required"))- }- normalizedRelativePath, err := projects.NormalizeProjectRelativePath(relativePath)- if err != nil {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.WrapIf(err, "Forbidden project file path"))- }-- composeFile, detectErr := s.ResolveProjectComposeFile(ctx, proj)- if detectErr == nil {- cfg := s.settingsService.GetSettingsOrDefaults(ctx)- projectsDirectory, _ := projects.GetProjectsDirectory(ctx, strings.TrimSpace(cfg.ProjectsDirectory.Value))- envLoader := projects.NewEnvLoader(projectsDirectory, filepath.Dir(composeFile), utils.BoolOrDefault(cfg.AutoInjectEnv.Value, false))- envMap, _, _ := envLoader.LoadEnvironment(ctx)-- includes, parseErr := projects.ParseIncludes(composeFile, envMap, false)- if parseErr == nil {- for _, inc := range includes {- if inc.RelativePath != normalizedRelativePath {- continue- }- if !projects.IsSafeSubdirectory(proj.Path, inc.Path) {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.New("Forbidden project file path: include resolves outside project directory"))- }- return readProjectIncludeFileContentInternal(proj.Path, inc)- }- }- }-- absFilePath, err := projects.ValidateIncludePathForWrite(proj.Path, normalizedRelativePath)- if err != nil {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.WrapIf(err, "Forbidden project file path"))- }-- info, err := os.Lstat(absFilePath)- if err != nil {- if os.IsNotExist(err) {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileNotFound, errors.New("Project file not found"))- }- return project.IncludeFile{}, errors.WrapIf(err, "failed to stat file")- }- if info.IsDir() {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: path is a directory"))- }- if info.Mode()&os.ModeSymlink != 0 {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.New("Forbidden project file path: symlinks are not allowed"))- }-- content, err := os.ReadFile(absFilePath)- if err != nil {- if os.IsNotExist(err) {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileNotFound, errors.New("Project file not found"))- }- return project.IncludeFile{}, errors.WrapIf(err, "failed to read file")- }- if projects.IsBinaryProjectFileContent(content) {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: binary files are not supported"))- }-- return project.IncludeFile{- Path: absFilePath,- RelativePath: normalizedRelativePath,- Content: string(content),- }, nil-}--func readProjectIncludeFileContentInternal(projectPath string, inc projects.IncludeFile) (project.IncludeFile, error) {- validatedPath, err := projects.ValidateIncludePathForWrite(projectPath, inc.Path)- if err != nil {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.WrapIf(err, "Forbidden project file path"))- }-- resolvedPath, err := utils.ResolveWithinRoot(projectPath, validatedPath)- if err != nil {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.WrapIf(err, "Forbidden project file path"))- }-- info, err := os.Stat(resolvedPath)- if os.IsNotExist(err) {- return project.IncludeFile{- Path: validatedPath,- RelativePath: inc.RelativePath,- Content: "# This file will be created when you save changes\nservices:\n",- }, nil- }- if err != nil {- return project.IncludeFile{}, errors.WrapIf(err, "failed to stat include file")- }- if info.IsDir() {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: path is a directory"))- }-- content, err := os.ReadFile(resolvedPath)- if err != nil {- if os.IsNotExist(err) {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileNotFound, errors.New("Project file not found"))- }- return project.IncludeFile{}, errors.WrapIf(err, "failed to read include file")- }- if projects.IsBinaryProjectFileContent(content) {- return project.IncludeFile{}, common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: binary files are not supported"))- }-- return project.IncludeFile{- Path: resolvedPath,- RelativePath: inc.RelativePath,- Content: string(content),- }, nil-}-func (s *ProjectService) enrichWithIncludeFiles(ctx context.Context, composeFile string, resp *project.Details) {if strings.TrimSpace(composeFile) == "" {return@@ -619,49 +496,6 @@ func buildProjectUpdateInfoSummaryInternal(return summary}-func (s *ProjectService) enrichWithDirectoryFiles(ctx context.Context, projectPath string, resp *project.Details) {- if projectPath == "" {- return- }-- // Build set of already-shown files to skip- shownFiles := map[string]bool{- ".env": true,- "compose.yaml": true,- "compose.yml": true,- "docker-compose.yaml": true,- "docker-compose.yml": true,- "podman-compose.yaml": true,- "podman-compose.yml": true,- }- for _, inc := range resp.IncludeFiles {- shownFiles[inc.RelativePath] = true- }-- dirFiles, err := projects.ReadProjectDirectoryFiles(projectPath, shownFiles, s.config.ProjectScanMaxDepth, s.config.ProjectScanSkipDirs)- if err != nil {- slog.WarnContext(ctx, "Failed to scan project directory files", "error", err, "path", projectPath)- }-- resp.DirectoryFiles = dirFiles-}--func (s *ProjectService) enrichWithProjectFiles(ctx context.Context, projectPath, composeFileName string, resp *project.Details) {- if projectPath == "" {- return- }-- files, revision, truncated, err := projects.ReadProjectFileTree(projectPath, s.config.ProjectFileTreeMaxDepth, s.config.ProjectScanSkipDirs, composeFileName, projects.DefaultProjectFileTreeMaxEntries)- if err != nil {- slog.WarnContext(ctx, "Failed to scan project file tree", "error", err, "path", projectPath)- return- }-- resp.ProjectFiles = files- resp.FileTreeRevision = revision- resp.FileTreeTruncated = truncated-}-func (s *ProjectService) enrichWithGitOpsInfo(ctx context.Context, proj *models.Project, resp *project.Details) {if proj.GitOpsManagedBy != nil {var syncRecord models.GitOpsSyncdiff --git a/backend/internal/project/project_lifecycle.go b/backend/internal/project/project_lifecycle.goindex 56c7433fe..5ef1aa2a7 100644--- a/backend/internal/project/project_lifecycle.go+++ b/backend/internal/project/project_lifecycle.go@@ -20,6 +20,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace""github.com/getarcaneapp/arcane/types/v2""github.com/getarcaneapp/arcane/types/v2/containerregistry""github.com/getarcaneapp/arcane/types/v2/project"@@ -371,7 +372,7 @@ func (s *ProjectService) DownProject(ctx context.Context, projectID string, user// "-N" (the interactive default). When false a collision returns// projects.ErrProjectDirExists (wrapped) so GitOps creates fail loudly instead of// minting runaway "-N" duplicate projects on a broken binding.-func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent string, envContent *string, projectFiles []project.ProjectFileDraft, user models.User, allowNameSuffixOptions ...bool) (*models.Project, error) {+func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent string, envContent *string, manifest project.CreateProjectWorkspaceManifest, uploads map[int][]byte, user models.User, allowNameSuffixOptions ...bool) (*models.Project, error) {allowNameSuffix := trueif len(allowNameSuffixOptions) > 0 {allowNameSuffix = allowNameSuffixOptions[0]@@ -408,13 +409,15 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContentRunningCount: 0,}- if err := projects.ApplyProjectFileDrafts(projectPath, projectFiles, projects.ProjectFileApplyOptions{- MaxDepth: s.config.ProjectFileTreeMaxDepth,- SkipDirectories: s.config.ProjectScanSkipDirs,- ComposeFileName: projects.DefaultComposeFileName,+ if err := projects.ApplyProjectWorkspaceChanges(projectPath, manifest.FileChanges, uploads, projects.ProjectWorkspaceApplyOptions{+ MaxDepth: s.config.ProjectWorkspaceMaxDepth,+ MaxEntries: s.config.ProjectWorkspaceMaxEntries,+ MaxFileSizeBytes: workspacepkg.MaxFileSizeBytes(s.config.ProjectWorkspaceMaxFileSizeMB),+ SkipDirectories: s.config.ProjectScanSkipDirs,+ ComposeFileName: projects.DefaultComposeFileName,}); err != nil {_ = os.RemoveAll(projectPath)- return nil, wrapProjectFileErrorInternal(err)+ return nil, wrapProjectWorkspaceErrorInternal(err)}// GitOps-originated creates (allowNameSuffix=false) tolerate not-yet-supplieddiff --git a/backend/internal/project/project_update.go b/backend/internal/project/project_update.goindex 4c60ead4c..ce14c6107 100644--- a/backend/internal/project/project_update.go+++ b/backend/internal/project/project_update.go@@ -19,11 +19,10 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumes""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"- "github.com/getarcaneapp/arcane/types/v2/project""gorm.io/gorm")-func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, name *string, composeContent, envContent, overrideContent *string, fileTreeRevision *string, fileChanges []project.ProjectFileChange, user models.User) (*models.Project, error) {+func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, name *string, composeContent, envContent, overrideContent *string, user models.User) (*models.Project, error) {proj, projectsDirectory, err := s.getProjectForUpdate(ctx, projectID)if err != nil {return nil, err@@ -47,22 +46,18 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, naif err := ensureProjectMutableInternal(&proj); err != nil {return nil, err}- if len(fileChanges) > 0 && isGitOpsManagedProjectInternal(&proj) {- return nil, common.Classify(common.ErrProjectFileForbidden, errors.New("Forbidden project file path: GitOps-managed project files cannot be edited"))- }-if err := s.ensureProjectStoppedForRenameInternal(ctx, &proj, name); err != nil {return nil, err}- volumeMigration, err := s.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, &proj, name, projectsDirectory, composeContent, envContent, overrideContent, fileTreeRevision, fileChanges)+ volumeMigration, err := s.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, &proj, name, projectsDirectory, composeContent, envContent, overrideContent)if err != nil {return nil, err}renameJournal := s.prepareProjectRenameJournalInternal(&proj, name, projectsDirectory, volumeMigration)- backup, cleanupBackup, err := s.prepareProjectUpdateBackupInternal(ctx, projectsDirectory, proj.Path, composeContent, envContent, overrideContent, fileChanges)+ backup, cleanupBackup, err := s.prepareProjectUpdateBackupInternal(ctx, projectsDirectory, proj.Path, composeContent, envContent, overrideContent)if err != nil {return nil, err}@@ -75,14 +70,14 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, naprojectStateCommitted := falseif err := withProjectRenameRollback(ctx, &proj, &projectStateCommitted, func() error {- return s.applyProjectUpdateWithRenameJournalInternal(ctx, &proj, name, projectsDirectory, composeContent, envContent, overrideContent, fileTreeRevision, fileChanges, volumeMigration, renameJournal, &journalActive, &projectStateCommitted)+ return s.applyProjectUpdateWithRenameJournalInternal(ctx, &proj, name, projectsDirectory, composeContent, envContent, overrideContent, volumeMigration, renameJournal, &journalActive, &projectStateCommitted)}); err != nil {err = s.handleProjectUpdateFailureInternal(ctx, projectID, projectsDirectory, &proj, backup, &journalActive, projectStateCommitted, err)return nil, err}- s.refreshProjectAfterContentUpdateInternal(ctx, &proj, composeContent, overrideContent, fileChanges)- s.logProjectUpdateEventInternal(ctx, &proj, composeContent, envContent, overrideContent, fileChanges, user)+ s.refreshProjectAfterContentUpdateInternal(ctx, &proj, composeContent, overrideContent)+ s.logProjectUpdateEventInternal(ctx, &proj, composeContent, envContent, overrideContent, user)slog.InfoContext(ctx, "project updated", "projectID", proj.ID, "name", proj.Name)return &proj, nil@@ -109,12 +104,12 @@ func resolveAuthoritativeProjectNameInternal(proj *models.Project, name *string,return name}-func (s *ProjectService) prepareProjectUpdateBackupInternal(ctx context.Context, projectsDirectory, projectPath string, composeContent, envContent, overrideContent *string, fileChanges []project.ProjectFileChange) (*projects.ProjectUpdateBackup, func(), error) {- if composeContent == nil && envContent == nil && overrideContent == nil && len(fileChanges) == 0 {+func (s *ProjectService) prepareProjectUpdateBackupInternal(ctx context.Context, projectsDirectory, projectPath string, composeContent, envContent, overrideContent *string) (*projects.ProjectUpdateBackup, func(), error) {+ if composeContent == nil && envContent == nil && overrideContent == nil {return nil, func() {}, nil}- scope := projects.BuildUpdateBackupScope(projectPath, composeContent, envContent, overrideContent, fileChanges)+ scope := projects.ProjectUpdateBackupScope{TopLevelFiles: true}if scope.IsEmpty() {return nil, func() {}, nil}@@ -127,7 +122,7 @@ func (s *ProjectService) prepareProjectUpdateBackupInternal(ctx context.Context,return backup, func() { _ = os.RemoveAll(backup.BackupDir) }, nil}-func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx context.Context, proj *models.Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string, fileTreeRevision *string, fileChanges []project.ProjectFileChange, volumeMigration volumes.Migration, renameJournal *projectRenameJournalInternal, journalActive *bool, projectStateCommitted *bool) (err error) {+func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx context.Context, proj *models.Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string, volumeMigration volumes.Migration, renameJournal *projectRenameJournalInternal, journalActive *bool, projectStateCommitted *bool) (err error) {volumeMigrationApplied := falsedefer func() {stateCommitted := projectStateCommitted != nil && *projectStateCommitted@@ -141,9 +136,6 @@ func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx contextif err = s.applyProjectRenameIfNeeded(proj, name, projectsDirectory); err != nil {return err}- if err = s.persistProjectFileChanges(ctx, proj, fileTreeRevision, fileChanges); err != nil {- return err- }if err = s.persistUpdatedProjectFiles(ctx, proj, projectsDirectory, composeContent, envContent, overrideContent); err != nil {return err}@@ -203,7 +195,7 @@ func (s *ProjectService) handleProjectUpdateFailureInternal(ctx context.Context,return err}-func (s *ProjectService) logProjectUpdateEventInternal(ctx context.Context, proj *models.Project, composeContent, envContent, overrideContent *string, fileChanges []project.ProjectFileChange, user models.User) {+func (s *ProjectService) logProjectUpdateEventInternal(ctx context.Context, proj *models.Project, composeContent, envContent, overrideContent *string, user models.User) {metadata := models.JSON{"action": "update","projectID": proj.ID,@@ -218,15 +210,11 @@ func (s *ProjectService) logProjectUpdateEventInternal(ctx context.Context, projif overrideContent != nil {metadata["overrideUpdated"] = true}- if len(fileChanges) > 0 {- metadata["projectFilesUpdated"] = true- metadata["projectFileChangeCount"] = len(fileChanges)- }s.logProjectEventInternal(ctx, models.EventTypeProjectUpdate, proj.ID, proj.Name, user, metadata, "could not log project update action")}-func (s *ProjectService) refreshProjectAfterContentUpdateInternal(ctx context.Context, proj *models.Project, composeContent, overrideContent *string, fileChanges []project.ProjectFileChange) {- if composeContent == nil && overrideContent == nil && len(fileChanges) == 0 {+func (s *ProjectService) refreshProjectAfterContentUpdateInternal(ctx context.Context, proj *models.Project, composeContent, overrideContent *string) {+ if composeContent == nil && overrideContent == nil {return}@@ -312,15 +300,12 @@ func (s *ProjectService) getProjectForUpdate(ctx context.Context, projectID strireturn proj, projectsDirectory, nil}-func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ctx context.Context, proj *models.Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string, fileTreeRevision *string, fileChanges []project.ProjectFileChange) (volumes.Migration, error) {+func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ctx context.Context, proj *models.Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string) (volumes.Migration, error) {if !isProjectRenameRequestedInternal(proj, name) {return nil, nil}- if err := requireProjectFileRevisionInternal(fileTreeRevision, fileChanges); err != nil {- return nil, err- }- if composeContent == nil && envContent == nil && overrideContent == nil && len(fileChanges) == 0 {+ if composeContent == nil && envContent == nil && overrideContent == nil {return s.prepareProjectRenameVolumeMigrationInternal(ctx, proj, name)}@@ -340,9 +325,6 @@ func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ctpreviewProject := *projpreviewProject.Path = previewPath- if err := s.applyProjectFileChangesInternal(ctx, &previewProject, "", fileChanges); err != nil {- return nil, errors.WrapIf(err, "failed to prepare project update preview")- }if err := s.persistUpdatedProjectFiles(ctx, &previewProject, projectsDirectory, composeContent, envContent, overrideContent); err != nil {return nil, errors.WrapIf(err, "failed to prepare project update preview")}@@ -399,79 +381,6 @@ func isProjectRenameRequestedInternal(proj *models.Project, name *string) bool {return newName != "" && proj.Name != newName}-func isGitOpsManagedProjectInternal(proj *models.Project) bool {- return proj != nil && proj.GitOpsManagedBy != nil && strings.TrimSpace(*proj.GitOpsManagedBy) != ""-}--func requireProjectFileRevisionInternal(fileTreeRevision *string, fileChanges []project.ProjectFileChange) error {- if len(fileChanges) == 0 {- return nil- }- if fileTreeRevision == nil || strings.TrimSpace(*fileTreeRevision) == "" {- return common.Classify(common.ErrProjectFileBadRequest, errors.New("Invalid project file request: file tree revision is required"))- }- return nil-}--func (s *ProjectService) persistProjectFileChanges(ctx context.Context, proj *models.Project, fileTreeRevision *string, fileChanges []project.ProjectFileChange) error {- if err := requireProjectFileRevisionInternal(fileTreeRevision, fileChanges); err != nil {- return err- }- expectedRevision := ""- if fileTreeRevision != nil {- expectedRevision = strings.TrimSpace(*fileTreeRevision)- }- return s.applyProjectFileChangesInternal(ctx, proj, expectedRevision, fileChanges)-}--func (s *ProjectService) applyProjectFileChangesInternal(ctx context.Context, proj *models.Project, expectedRevision string, fileChanges []project.ProjectFileChange) error {- if len(fileChanges) == 0 {- return nil- }- opts := s.projectFileApplyOptionsInternal(ctx, proj, expectedRevision)- if err := projects.ApplyProjectFileChanges(proj.Path, fileChanges, opts); err != nil {- return wrapProjectFileErrorInternal(err)- }- return nil-}--func (s *ProjectService) projectFileApplyOptionsInternal(ctx context.Context, proj *models.Project, expectedRevision string) projects.ProjectFileApplyOptions {- composeFileName := projects.DefaultComposeFileName- if composeFile, err := s.ResolveProjectComposeFile(ctx, proj); err == nil {- composeFileName = filepath.Base(composeFile)- }-- return projects.ProjectFileApplyOptions{- ExpectedRevision: strings.TrimSpace(expectedRevision),- MaxDepth: s.config.ProjectFileTreeMaxDepth,- MaxEntries: projects.DefaultProjectFileTreeMaxEntries,- SkipDirectories: s.config.ProjectScanSkipDirs,- ComposeFileName: composeFileName,- }-}--// wrapProjectFileErrorInternal maps pkg/projects sentinel errors onto the-// common.ProjectFile* error structs the handlers translate into HTTP statuses.-func wrapProjectFileErrorInternal(err error) error {- switch {- case errors.Is(err, projects.ErrProjectFileRevisionConflict):- return common.Classify(common.ErrProjectFileConflict, errors.WithStackIf(err))- case errors.Is(err, projects.ErrProjectFileOutsideProjectDirectory),- errors.Is(err, projects.ErrProjectFileProtectedPath),- errors.Is(err, projects.ErrProjectFileSymlinkPath):- return common.Classify(common.ErrProjectFileForbidden, errors.WrapIf(err, "Forbidden project file path"))-- default:- return common.Classify(common.ErrProjectFileBadRequest, errors.-- // projectUpdateBackupScopeInternal derives the exact set of paths an update- // can mutate so the backup never copies out-of-scope data directories.- // Changes that fail normalization are skipped: the apply step rejects them- // before mutating anything, so there is nothing to roll back for them.- WrapIf(err, "Invalid project file request"))- }-}-func backupProjectDirectoryInternal(ctx context.Context, projectsDirectory, projectPath string, scope projects.ProjectUpdateBackupScope) (*projects.ProjectUpdateBackup, error) {projectAbs, err := filepath.Abs(projectPath)if err != nil {@@ -731,36 +640,3 @@ func (s *ProjectService) applyProjectRenameIfNeeded(proj *models.Project, name *proj.Name = newNamereturn nil}--func (s *ProjectService) UpdateProjectIncludeFile(ctx context.Context, projectID, relativePath, content string, user models.User) error {- proj, err := s.getMutableProjectInternal(ctx, projectID)- if err != nil {- return err- }-- // Normalize and persist project path to ensure include writes occur under projects root- if err := s.EnsureProjectPathUnderRoot(ctx, proj, true); err != nil {- return err- }-- if err := projects.WriteIncludeFile(proj.Path, relativePath, content); err != nil {- return errors.WrapIf(err, "failed to update include file")- }- s.refreshProjectImageRefsInternal(ctx, proj)-- // Recalculate service counts since include files can define services- if err := s.updateProjectStatusandCountsInternal(ctx, proj.ID, proj.Status); err != nil {- slog.WarnContext(ctx, "failed to update service counts after include file edit", "projectID", proj.ID, "error", err)- }-- metadata := models.JSON{- "action": "update_include",- "projectID": proj.ID,- "projectName": proj.Name,- "relativePath": relativePath,- }- s.logProjectEventInternal(ctx, models.EventTypeProjectUpdate, proj.ID, proj.Name, user, metadata, "could not log project include update action")-- slog.InfoContext(ctx, "project include file updated", "projectID", proj.ID, "file", relativePath)- return nil-}diff --git a/backend/internal/project/service_test.go b/backend/internal/project/service_test.goindex 985e2fd42..b226728e4 100644--- a/backend/internal/project/service_test.go+++ b/backend/internal/project/service_test.go@@ -81,6 +81,14 @@ func setupProjectTestDB(t *testing.T) *database.DB {return &database.DB{DB: db}}+func TestUpdateProjectWorkspaceRejectsInvalidManifestBeforeProjectLookup(t *testing.T) {+ service := &ProjectService{}++ _, err := service.UpdateProjectWorkspace(context.Background(), "missing", projecttypes.WorkspaceUpdateManifest{}, nil, models.User{})+ require.ErrorIs(t, err, common.ErrProjectWorkspaceBadRequest)+ require.ErrorContains(t, err, "revision")+}+func newSettingsServiceForTestInternal(t *testing.T, ctx context.Context, db *database.DB) (*settings.SettingsService, error) {t.Helper()lifecycle := fxtest.NewLifecycle(t)@@ -1210,7 +1218,7 @@ func TestProjectService_UpdateProject_RenameFailsWhenVolumeMigrationPreparationF}require.NoError(t, db.Create(project).Error)- _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, nil, nil, models.User{+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -1256,7 +1264,7 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_AppliesVolumeMigratiprojectForUpdate := *projectjournalActive := falseprojectStateCommitted := false- err = svc.applyProjectUpdateWithRenameJournalInternal(ctx, &projectForUpdate, new("bar"), projectsDir, nil, nil, nil, nil, nil, migration, nil, &journalActive, &projectStateCommitted)+ err = svc.applyProjectUpdateWithRenameJournalInternal(ctx, &projectForUpdate, new("bar"), projectsDir, nil, nil, nil, migration, nil, &journalActive, &projectStateCommitted)require.NoError(t, err)assert.True(t, migration.applyCalled)@@ -1330,7 +1338,7 @@ func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesComposet.Run("skips volume made explicit in pending compose", func(t *testing.T) {newCompose := "services:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n name: fixed-data\n"- migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil, nil, nil)+ migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)require.NoError(t, err)require.Nil(t, migration)@@ -1343,7 +1351,7 @@ func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesComposet.Run("plans unchanged auto-managed volume from pending compose", func(t *testing.T) {newCompose := "services:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n driver: local\n"- migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil, nil, nil)+ migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)require.NoError(t, err)require.NotNil(t, migration)@@ -1360,7 +1368,7 @@ func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesComposet.Run("plans auto-managed volume when pending compose name renames project", func(t *testing.T) {newCompose := "name: web\nservices:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n driver: local\n"- migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil, nil, nil)+ migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)require.NoError(t, err)require.NotNil(t, migration)@@ -1377,7 +1385,7 @@ func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesComposet.Run("plans interpolated explicit name from pending compose", func(t *testing.T) {newCompose := "services:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n name: ${DATA_VOLUME:-nginx_data}\n"- migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil, nil, nil)+ migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)require.NoError(t, err)require.NotNil(t, migration)@@ -1429,7 +1437,7 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_RollsBackVolumeMigrajournalActive := falseprojectStateCommitted := falseerr = withProjectRenameRollback(ctx, &projectForUpdate, &projectStateCommitted, func() error {- return svc.applyProjectUpdateWithRenameJournalInternal(ctx, &projectForUpdate, new("bar"), projectsDir, nil, nil, nil, nil, nil, migration, nil, &journalActive, &projectStateCommitted)+ return svc.applyProjectUpdateWithRenameJournalInternal(ctx, &projectForUpdate, new("bar"), projectsDir, nil, nil, nil, migration, nil, &journalActive, &projectStateCommitted)})require.Error(t, err)assert.Contains(t, err.Error(), "forced project save failure")@@ -1474,7 +1482,7 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_SucceedsCommittedRenjournalActive := falseprojectStateCommitted := falseerr = withProjectRenameRollback(ctx, &projectForUpdate, &projectStateCommitted, func() error {- return svc.applyProjectUpdateWithRenameJournalInternal(ctx, &projectForUpdate, new("bar"), projectsDir, nil, nil, nil, nil, nil, migration, nil, &journalActive, &projectStateCommitted)+ return svc.applyProjectUpdateWithRenameJournalInternal(ctx, &projectForUpdate, new("bar"), projectsDir, nil, nil, nil, migration, nil, &journalActive, &projectStateCommitted)})require.NoError(t, err)require.True(t, migration.applyCalled)@@ -1539,7 +1547,7 @@ func TestProjectService_UpdateProject_ClearsJournalForNonRenameWhenRecoveryDockerequire.NoError(t, kvService.Set(ctx, projectRenameJournalKeyInternal(project.ID), string(payload)))envContent := "FOO=bar\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &envContent, nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &envContent, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -1604,7 +1612,7 @@ func TestProjectService_UpdateProject_AllowsRenameAfterJournalRecoveryDockerUnavrequire.NoError(t, err)require.NoError(t, kvService.Set(ctx, projectRenameJournalKeyInternal(project.ID), string(payload)))- updated, err := svc.UpdateProject(ctx, project.ID, ptr("web"), nil, nil, nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, ptr("web"), nil, nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -1646,7 +1654,7 @@ func TestProjectService_UpdateProject_RenamesDirectoryWhenNameChanges(t *testing}require.NoError(t, db.Create(project).Error)- updated, err := svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -1698,7 +1706,7 @@ func TestProjectService_UpdateProject_RenameFailsWhenTargetDirectoryExists(t *te}require.NoError(t, db.Create(project).Error)- _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, nil, nil, models.User{+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -1742,7 +1750,7 @@ func TestProjectService_UpdateProject_RenameFailsWhenProjectRunning(t *testing.T}require.NoError(t, db.Create(project).Error)- _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, nil, nil, models.User{+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -1801,7 +1809,7 @@ func TestProjectService_UpdateProject_RenameRejectsStaleStoppedWhenRuntimeIsRunn}require.NoError(t, db.Create(project).Error)- _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, nil, nil, models.User{+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -1849,7 +1857,7 @@ func TestProjectService_UpdateProject_RenameResolvesUnknownStoppedStatusBeforeVo}require.NoError(t, db.Create(project).Error)- updated, err := svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -1921,7 +1929,7 @@ func TestProjectService_UpdateProject_RenameRejectsUnknownWhenRuntimeIsRunning(t}require.NoError(t, db.Create(project).Error)- _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, nil, nil, models.User{+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -1973,7 +1981,7 @@ services:`env := "COMPOSE_PROJECT_NAME=\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2016,7 +2024,7 @@ func TestProjectService_UpdateProject_AllowsMissingEnvFileDuringComposeValidatio- .env`- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2061,7 +2069,7 @@ services:image: nginx:alpine`- updated, err := svc.UpdateProject(ctx, project.ID, nil, ptr(compose), nil, nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, ptr(compose), nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2077,65 +2085,6 @@ services:require.Len(t, details.IncludeFiles, 1)assert.Equal(t, "metadata.yaml", details.IncludeFiles[0].RelativePath)- includeFile, err := svc.GetProjectFileContent(ctx, project.ID, "metadata.yaml")- require.NoError(t, err)- assert.Equal(t, "metadata.yaml", includeFile.RelativePath)- assert.Contains(t, includeFile.Content, "This file will be created when you save changes")-- includeContent := "services: {}\n"- require.NoError(t, svc.UpdateProjectIncludeFile(ctx, project.ID, "metadata.yaml", includeContent, models.User{- BaseModel: models.BaseModel{ID: "u1"},- Username: "tester",- }))-- writtenContent, err := os.ReadFile(includePath)- require.NoError(t, err)- assert.Equal(t, includeContent, string(writtenContent))-}--func TestProjectService_UpdateProject_RejectsMissingExternalIncludeDuringComposeValidation(t *testing.T) {- db := setupProjectTestDB(t)- ctx := context.Background()-- projectsDir := t.TempDir()- t.Setenv("PROJECTS_DIRECTORY", projectsDir)-- settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)- require.NoError(t, err)-- eventService := event.NewEventService(db, nil, nil)- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())-- dirName := "include-external"- projectPath := filepath.Join(projectsDir, dirName)- require.NoError(t, os.MkdirAll(projectPath, 0o755))-- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-external-include"},- Name: "include-external",- DirName: &dirName,- Path: projectPath,- Status: models.ProjectStatusStopped,- }- require.NoError(t, db.Create(project).Error)-- compose := `include:- - ../metadata.yaml-services:- app:- image: nginx:alpine-`-- updated, err := svc.UpdateProject(ctx, project.ID, nil, ptr(compose), nil, nil, nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},- Username: "tester",- })-- require.Error(t, err)- assert.Nil(t, updated)- assert.Contains(t, err.Error(), "invalid compose file")- assert.NoFileExists(t, filepath.Join(projectsDir, "metadata.yaml"))- assert.NoFileExists(t, filepath.Join(projectPath, "compose.yaml"))}func TestProjectService_CreateProject_RejectsExternalInclude(t *testing.T) {@@ -2159,7 +2108,7 @@ services:image: nginx:alpine`- project, err := svc.CreateProject(ctx, "evil", compose, nil, nil, models.User{+ project, err := svc.CreateProject(ctx, "evil", compose, nil, projecttypes.CreateProjectWorkspaceManifest{}, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2197,7 +2146,7 @@ services:image: nginx:alpine`- project, err := svc.CreateProject(ctx, "evil-array", compose, nil, nil, models.User{+ project, err := svc.CreateProject(ctx, "evil-array", compose, nil, projecttypes.CreateProjectWorkspaceManifest{}, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2212,386 +2161,68 @@ services:assert.Zero(t, count)}-func TestProjectService_CreateProject_WritesStagedProjectFiles(t *testing.T) {+func TestProjectService_CreateProject_CommitsWorkspaceAndConfigurationTogether(t *testing.T) {db := setupProjectTestDB(t)ctx := context.Background()-projectsDir := t.TempDir()t.Setenv("PROJECTS_DIRECTORY", projectsDir)settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)require.NoError(t, err)-- eventService := event.NewEventService(db, nil, nil)- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())-- includeContent := "services: {}\n"- compose := `include:- - config/app.yaml-services:- app:- image: nginx:alpine-`-- project, err := svc.CreateProject(ctx, "with-files", compose, nil, []projecttypes.ProjectFileDraft{- {RelativePath: "config", IsDirectory: true},- {RelativePath: "config/app.yaml", Content: includeContent},- {RelativePath: "README.md", Content: "hello\n"},- }, models.User{- BaseModel: models.BaseModel{ID: "u1"},- Username: "tester",- })- require.NoError(t, err)- require.NotNil(t, project)-- assert.FileExists(t, filepath.Join(project.Path, "compose.yaml"))- assert.FileExists(t, filepath.Join(project.Path, ".env"))- assert.FileExists(t, filepath.Join(project.Path, "config", "app.yaml"))- assert.FileExists(t, filepath.Join(project.Path, "README.md"))-- details, err := svc.GetProjectDetails(ctx, project.ID, projecttypes.DetailsOptions{IncludeProjectFiles: true})- require.NoError(t, err)- assert.NotEmpty(t, details.FileTreeRevision)-- relativePaths := make([]string, 0, len(details.ProjectFiles))- for _, file := range details.ProjectFiles {- relativePaths = append(relativePaths, file.RelativePath)- }- assert.Contains(t, relativePaths, "config")- assert.Contains(t, relativePaths, filepath.ToSlash(filepath.Join("config", "app.yaml")))- assert.Contains(t, relativePaths, "README.md")- assert.NotContains(t, relativePaths, "compose.yaml")- assert.NotContains(t, relativePaths, ".env")-}--func TestProjectService_GetProjectDetails_UsesFileTreeMaxDepthForProjectFiles(t *testing.T) {- db := setupProjectTestDB(t)- ctx := context.Background()-- projectsDir := t.TempDir()- t.Setenv("PROJECTS_DIRECTORY", projectsDir)- t.Setenv("PROJECT_SCAN_MAX_DEPTH", "3")- t.Setenv("PROJECT_FILE_TREE_MAX_DEPTH", "8")-- settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)- require.NoError(t, err)-- eventService := event.NewEventService(db, nil, nil)- cfg := config.Load()- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, cfg)-- deepFolder := filepath.ToSlash(filepath.Join("level1", "level2", "level3", "level4", "level5"))- project, err := svc.CreateProject(ctx, "deep-files", "services:\n app:\n image: nginx:alpine\n", nil, []projecttypes.ProjectFileDraft{- {RelativePath: deepFolder, IsDirectory: true},- }, models.User{- BaseModel: models.BaseModel{ID: "u1"},- Username: "tester",- })- require.NoError(t, err)-- assert.DirExists(t, filepath.Join(project.Path, filepath.FromSlash(deepFolder)))-- filesAtScanDepth, _, _, err := projects.ReadProjectFileTree(project.Path, cfg.ProjectScanMaxDepth, cfg.ProjectScanSkipDirs, "compose.yaml", 0)- require.NoError(t, err)- scanDepthRelativePaths := make([]string, 0, len(filesAtScanDepth))- for _, file := range filesAtScanDepth {- scanDepthRelativePaths = append(scanDepthRelativePaths, file.RelativePath)- }- assert.NotContains(t, scanDepthRelativePaths, deepFolder)-- details, err := svc.GetProjectDetails(ctx, project.ID, projecttypes.DetailsOptions{IncludeProjectFiles: true})- require.NoError(t, err)-- fileTreeRelativePaths := make([]string, 0, len(details.ProjectFiles))- for _, file := range details.ProjectFiles {- fileTreeRelativePaths = append(fileTreeRelativePaths, file.RelativePath)- }- assert.Contains(t, fileTreeRelativePaths, deepFolder)-}--func TestProjectService_UpdateProject_AppliesStagedProjectFileChanges(t *testing.T) {- db := setupProjectTestDB(t)- ctx := context.Background()-- projectsDir := t.TempDir()- t.Setenv("PROJECTS_DIRECTORY", projectsDir)-- settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)- require.NoError(t, err)-- eventService := event.NewEventService(db, nil, nil)- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())-- project, err := svc.CreateProject(ctx, "editable-files", "services:\n app:\n image: nginx:alpine\n", nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},- Username: "tester",- })- require.NoError(t, err)-- _, revision, _, err := projects.ReadProjectFileTree(project.Path, config.Load().ProjectScanMaxDepth, config.Load().ProjectScanSkipDirs, "compose.yaml", 0)- require.NoError(t, err)-- updated := "updated\n"- _, err = svc.UpdateProject(ctx, project.ID, nil, nil, nil, nil, &revision, []projecttypes.ProjectFileChange{- {Operation: "create_folder", RelativePath: "config"},- {Operation: "create_folder", RelativePath: "archive"},- {Operation: "create_file", RelativePath: "config/app.yaml", Content: new("hello\n")},- {Operation: "update_file", RelativePath: "config/app.yaml", Content: &updated},- {Operation: "rename", RelativePath: "config/app.yaml", NewName: "renamed.yaml"},- {Operation: "move", RelativePath: "config/renamed.yaml", NewParentPath: "archive"},- }, models.User{- BaseModel: models.BaseModel{ID: "u1"},- Username: "tester",- })-- require.NoError(t, err)-- bytes, err := os.ReadFile(filepath.Join(project.Path, "archive", "renamed.yaml"))- require.NoError(t, err)- assert.Equal(t, updated, string(bytes))- assert.NoFileExists(t, filepath.Join(project.Path, "config", "renamed.yaml"))-}--func TestProjectService_UpdateProject_RejectsStaleProjectFileRevision(t *testing.T) {- db := setupProjectTestDB(t)- ctx := context.Background()-- projectsDir := t.TempDir()- t.Setenv("PROJECTS_DIRECTORY", projectsDir)-- settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)- require.NoError(t, err)-- eventService := event.NewEventService(db, nil, nil)- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())-- project, err := svc.CreateProject(ctx, "stale-files", "services:\n app:\n image: nginx:alpine\n", nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},- Username: "tester",- })- require.NoError(t, err)-- _, revision, _, err := projects.ReadProjectFileTree(project.Path, config.Load().ProjectScanMaxDepth, config.Load().ProjectScanSkipDirs, "compose.yaml", 0)- require.NoError(t, err)- require.NoError(t, os.WriteFile(filepath.Join(project.Path, "external.txt"), []byte("external\n"), 0o644))-- _, err = svc.UpdateProject(ctx, project.ID, nil, nil, nil, nil, &revision, []projecttypes.ProjectFileChange{- {Operation: "create_file", RelativePath: "notes.txt", Content: new("new\n")},- }, models.User{- BaseModel: models.BaseModel{ID: "u1"},- Username: "tester",- })-- require.Error(t, err)- require.ErrorIs(t, err, common.ErrProjectFileConflict)- assert.NoFileExists(t, filepath.Join(project.Path, "notes.txt"))-}--func TestProjectService_UpdateProject_RejectsStaleDeepProjectFileRevision(t *testing.T) {- db := setupProjectTestDB(t)- ctx := context.Background()-- projectsDir := t.TempDir()- t.Setenv("PROJECTS_DIRECTORY", projectsDir)- t.Setenv("PROJECT_SCAN_MAX_DEPTH", "3")- t.Setenv("PROJECT_FILE_TREE_MAX_DEPTH", "8")-- settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)- require.NoError(t, err)-- eventService := event.NewEventService(db, nil, nil)- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())-- project, err := svc.CreateProject(ctx, "stale-deep-files", "services:\n app:\n image: nginx:alpine\n", nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},- Username: "tester",- })+ svc := NewProjectService(db, settingsService, event.NewEventService(db, nil, nil), nil, nil, nil, nil, nil, config.Load())+ uploadIndex := 0+ manifest := projecttypes.CreateProjectWorkspaceManifest{FileChanges: []projecttypes.WorkspaceFileChange{{+ Operation: projecttypes.FileOpCreateFile, RelativePath: "config/app.txt", UploadIndex: &uploadIndex,+ }}}++ created, err := svc.CreateProject(+ ctx,+ "atomic-workspace",+ "services:\n app:\n image: nginx:alpine\n",+ new("VALUE=one\n"),+ manifest,+ map[int][]byte{0: []byte("workspace content\n")},+ models.User{BaseModel: models.BaseModel{ID: "u1"}, Username: "tester"},+ )require.NoError(t, err)-- details, err := svc.GetProjectDetails(ctx, project.ID, projecttypes.DetailsOptions{IncludeProjectFiles: true})+ require.NotNil(t, created)+ require.FileExists(t, filepath.Join(created.Path, projects.DefaultComposeFileName))+ require.FileExists(t, filepath.Join(created.Path, ".env"))+ require.FileExists(t, filepath.Join(created.Path, "config", "app.txt"))+ content, err := os.ReadFile(filepath.Join(created.Path, "config", "app.txt"))require.NoError(t, err)- require.NotEmpty(t, details.FileTreeRevision)-- deepParent := filepath.Join(project.Path, "level1", "level2", "level3", "level4")- require.NoError(t, os.MkdirAll(deepParent, 0o755))- require.NoError(t, os.WriteFile(filepath.Join(deepParent, "external.txt"), []byte("external\n"), 0o644))-- _, err = svc.UpdateProject(ctx, project.ID, nil, nil, nil, nil, &details.FileTreeRevision, []projecttypes.ProjectFileChange{- {Operation: "create_file", RelativePath: "notes.txt", Content: new("new\n")},- }, models.User{- BaseModel: models.BaseModel{ID: "u1"},- Username: "tester",- })-- require.Error(t, err)- require.ErrorIs(t, err, common.ErrProjectFileConflict)- assert.NoFileExists(t, filepath.Join(project.Path, "notes.txt"))+ require.Equal(t, "workspace content\n", string(content))}-func TestProjectService_GetProjectFileContent_RejectsExternalInclude(t *testing.T) {+func TestProjectService_CreateProject_RollsBackInvalidWorkspaceManifest(t *testing.T) {db := setupProjectTestDB(t)ctx := context.Background()-projectsDir := t.TempDir()t.Setenv("PROJECTS_DIRECTORY", projectsDir)settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)require.NoError(t, err)-- eventService := event.NewEventService(db, nil, nil)- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())-- dirName := "include-read"- projectPath := filepath.Join(projectsDir, dirName)- require.NoError(t, os.MkdirAll(projectPath, 0o755))- require.NoError(t, os.WriteFile(filepath.Join(projectsDir, "metadata.yaml"), []byte("services: {}\n"), 0o644))-- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-external-include-read"},- Name: "include-read",- DirName: &dirName,- Path: projectPath,- Status: models.ProjectStatusStopped,- }- require.NoError(t, db.Create(project).Error)-- compose := `include:- - ../metadata.yaml-services:- app:- image: nginx:alpine-`- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte(compose), 0o644))-- includeFile, err := svc.GetProjectFileContent(ctx, project.ID, "../metadata.yaml")- require.Error(t, err)- assert.Empty(t, includeFile)- assert.ErrorIs(t, err, common.ErrProjectFileForbidden)-}--func TestProjectService_GetProjectFileContent_RejectsSymlinkInclude(t *testing.T) {- db := setupProjectTestDB(t)- ctx := context.Background()-- projectsDir := t.TempDir()- t.Setenv("PROJECTS_DIRECTORY", projectsDir)-- settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)- require.NoError(t, err)-- eventService := event.NewEventService(db, nil, nil)- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())-- dirName := "include-symlink"- projectPath := filepath.Join(projectsDir, dirName)- require.NoError(t, os.MkdirAll(projectPath, 0o755))-- outsidePath := filepath.Join(t.TempDir(), "outside.yaml")- require.NoError(t, os.WriteFile(outsidePath, []byte("services: {}\n"), 0o644))- require.NoError(t, os.Symlink(outsidePath, filepath.Join(projectPath, "evil-link")))-- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-symlink-include-read"},- Name: "include-symlink",- DirName: &dirName,- Path: projectPath,- Status: models.ProjectStatusStopped,- }- require.NoError(t, db.Create(project).Error)-- compose := `include:- - ./evil-link-services:- app:- image: nginx:alpine-`- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte(compose), 0o644))-- includeFile, err := svc.GetProjectFileContent(ctx, project.ID, "evil-link")- require.Error(t, err)- assert.Empty(t, includeFile)- assert.ErrorIs(t, err, common.ErrProjectFileForbidden)-}--func TestProjectService_GetProjectFileContent_RejectsIntermediateSymlinkInclude(t *testing.T) {- db := setupProjectTestDB(t)- ctx := context.Background()-- projectsDir := t.TempDir()- t.Setenv("PROJECTS_DIRECTORY", projectsDir)-- settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)- require.NoError(t, err)-- eventService := event.NewEventService(db, nil, nil)- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())-- dirName := "include-intermediate-symlink"- projectPath := filepath.Join(projectsDir, dirName)- require.NoError(t, os.MkdirAll(projectPath, 0o755))-- outsideDir := t.TempDir()- require.NoError(t, os.WriteFile(filepath.Join(outsideDir, "secret.yaml"), []byte("services: {}\n"), 0o644))- require.NoError(t, os.Symlink(outsideDir, filepath.Join(projectPath, "subdir")))-- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-intermediate-symlink-include-read"},- Name: "include-intermediate-symlink",- DirName: &dirName,- Path: projectPath,- Status: models.ProjectStatusStopped,- }- require.NoError(t, db.Create(project).Error)-- compose := `include:- - ./subdir/secret.yaml-services:- app:- image: nginx:alpine-`- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte(compose), 0o644))-- includeFile, err := svc.GetProjectFileContent(ctx, project.ID, "subdir/secret.yaml")+ svc := NewProjectService(db, settingsService, event.NewEventService(db, nil, nil), nil, nil, nil, nil, nil, config.Load())+ manifest := projecttypes.CreateProjectWorkspaceManifest{FileChanges: []projecttypes.WorkspaceFileChange{{+ Operation: projecttypes.FileOpDelete, RelativePath: "missing.txt",+ }}}++ created, err := svc.CreateProject(+ ctx,+ "invalid-workspace",+ "services:\n app:\n image: nginx:alpine\n",+ nil,+ manifest,+ nil,+ models.User{BaseModel: models.BaseModel{ID: "u1"}, Username: "tester"},+ )require.Error(t, err)- assert.Empty(t, includeFile)- assert.ErrorIs(t, err, common.ErrProjectFileForbidden)-}--func TestProjectService_GetProjectFileContent_RejectsIntermediateSymlinkProjectFile(t *testing.T) {- db := setupProjectTestDB(t)- ctx := context.Background()-- projectsDir := t.TempDir()- t.Setenv("PROJECTS_DIRECTORY", projectsDir)-- settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)- require.NoError(t, err)-- eventService := event.NewEventService(db, nil, nil)- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())-- dirName := "project-file-intermediate-symlink"- projectPath := filepath.Join(projectsDir, dirName)- require.NoError(t, os.MkdirAll(projectPath, 0o755))- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services: {}\n"), 0o644))-- outsideDir := t.TempDir()- require.NoError(t, os.WriteFile(filepath.Join(outsideDir, "secret.yaml"), []byte("services: {}\n"), 0o644))- require.NoError(t, os.Symlink(outsideDir, filepath.Join(projectPath, "subdir")))-- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-intermediate-symlink-project-file-read"},- Name: "project-file-intermediate-symlink",- DirName: &dirName,- Path: projectPath,- Status: models.ProjectStatusStopped,- }- require.NoError(t, db.Create(project).Error)+ require.Nil(t, created)+ require.NoDirExists(t, filepath.Join(projectsDir, "invalid-workspace"))- includeFile, err := svc.GetProjectFileContent(ctx, project.ID, "subdir/secret.yaml")- require.Error(t, err)- assert.Empty(t, includeFile)- assert.ErrorIs(t, err, common.ErrProjectFileForbidden)+ var count int64+ require.NoError(t, db.Model(&models.Project{}).Where("name = ?", "invalid-workspace").Count(&count).Error)+ require.Zero(t, count)}func TestProjectService_UpdateProject_UsesExistingEnvFileDuringComposeValidation(t *testing.T) {@@ -2628,7 +2259,7 @@ func TestProjectService_UpdateProject_UsesExistingEnvFileDuringComposeValidation- .env`- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2678,7 +2309,7 @@ func TestProjectService_UpdateProject_CreatesOverrideWithDefaultName(t *testing.svc, project, projectPath := newProjectServiceForOverrideTestInternal(t, "override-create", "services:\n app:\n image: nginx:alpine\n")override := "services:\n app:\n image: busybox:latest\n"- _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(override), nil, nil, models.User{+ _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(override), models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2705,7 +2336,7 @@ func TestProjectService_UpdateProject_PreservesExistingOverrideName(t *testing.Trequire.NoError(t, os.WriteFile(filepath.Join(projectPath, "docker-compose.override.yml"), []byte("services:\n app:\n image: alpine:3\n"), 0o600))override := "services:\n app:\n image: busybox:latest\n"- _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(override), nil, nil, models.User{+ _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(override), models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2725,7 +2356,7 @@ func TestProjectService_UpdateProject_DeletesOverrideOnBlank(t *testing.T) {require.NoError(t, os.WriteFile(overridePath, []byte("services:\n app:\n image: busybox:latest\n"), 0o600))// A non-nil blank override deletes the file so the deploy stops merging it.- _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(""), nil, nil, models.User{+ _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(""), models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2743,7 +2374,7 @@ func TestProjectService_UpdateProject_MergedValidationFailureLeavesDiskUnchanged// backup/restore must leave both the base and the override untouched on disk.newCompose := "services:\n app:\n image: nginx:1.27\n"badOverride := "services:\n app:\n image: \"unterminated\n"- _, err := svc.UpdateProject(ctx, project.ID, nil, new(newCompose), nil, new(badOverride), nil, nil, models.User{+ _, err := svc.UpdateProject(ctx, project.ID, nil, new(newCompose), nil, new(badOverride), models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2789,7 +2420,7 @@ func TestProjectService_UpdateProject_UsesProvidedEnvContentDuringComposeValidat`env := "FOO=updated\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2836,7 +2467,7 @@ func TestProjectService_UpdateProject_ReturnsEnvParseErrorDuringComposeValidatio`env := "BROKEN=${UNTERMINATED\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2882,7 +2513,7 @@ func TestProjectService_UpdateProject_UsesGlobalEnvDuringComposeValidation(t *te- ${MYPATH}cats/templates:/app/templates`- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2930,7 +2561,7 @@ func TestProjectService_UpdateProject_DoesNotResolveHostEnvThroughGlobalEnvDurin- ${DATA_NAS_FOLDER}:/data`- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -2969,7 +2600,7 @@ func TestProjectService_UpdateProject_DerivesProjectOverrideEnvWhenGitSourceExis}require.NoError(t, db.Create(project).Error)- updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, new("BASE=git\nLOCAL_ONLY=example\n"), nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, new("BASE=git\nLOCAL_ONLY=example\n"), nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -3021,7 +2652,7 @@ func TestProjectService_UpdateProject_UnchangedGitEnvLeavesFilesUntouched(t *tes}require.NoError(t, db.Create(project).Error)- updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &effectiveContent, nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &effectiveContent, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -3114,7 +2745,7 @@ func TestProjectService_UpdateProject_DeletingGitBackedKeyFallsBackToGit(t *test}require.NoError(t, db.Create(project).Error)- updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, new("BASE=git\nLOCAL_ONLY=1\n"), nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, new("BASE=git\nLOCAL_ONLY=1\n"), nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -5455,7 +5086,7 @@ func TestProjectService_UpdateProject_WritesThroughSymlinkedProjectPath(t *testiupdatedCompose := "services:\n app:\n image: nginx:1.27-alpine\n"updatedEnv := "FOO=updated\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(updatedCompose), new(updatedEnv), nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(updatedCompose), new(updatedEnv), nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -5508,7 +5139,7 @@ func TestProjectService_UpdateProject_WritesThroughExternalEnvSymlink(t *testingrequire.NoError(t, db.Create(project).Error)updatedEnv := "FOO=updated\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &updatedEnv, nil, nil, nil, models.User{+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &updatedEnv, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -5573,7 +5204,7 @@ func TestProjectService_UpdateProject_RestoresExternalEnvSymlinkTargetWhenProjec}))updatedEnv := "FOO=updated\n"- _, err = svc.UpdateProject(ctx, project.ID, nil, nil, &updatedEnv, nil, nil, nil, models.User{+ _, err = svc.UpdateProject(ctx, project.ID, nil, nil, &updatedEnv, nil, models.User{BaseModel: models.BaseModel{ID: "u1"},Username: "tester",})@@ -5697,57 +5328,6 @@ func TestResolveRemoveOrphans(t *testing.T) {}}-func TestProjectService_UpdateProject_RenameRollsBackWhenFileRevisionIsStale(t *testing.T) {- db := setupProjectTestDB(t)- ctx := context.Background()-- projectsDir := t.TempDir()- t.Setenv("PROJECTS_DIRECTORY", projectsDir)-- settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)- require.NoError(t, err)- require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsDir))-- eventService := event.NewEventService(db, nil, nil)- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())- configureProjectRuntimeDockerInternal(t, nil)-- originalDirName := "Foo"- originalPath := createComposeProjectDir(t, projectsDir, originalDirName)- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-stale-file-revision"},- Name: "Foo",- DirName: &originalDirName,- Path: originalPath,- Status: models.ProjectStatusStopped,- }- require.NoError(t, db.Create(project).Error)-- _, revision, _, err := projects.ReadProjectFileTree(project.Path, config.Load().ProjectFileTreeMaxDepth, config.Load().ProjectScanSkipDirs, "compose.yaml", 0)- require.NoError(t, err)- require.NoError(t, os.WriteFile(filepath.Join(project.Path, "external.txt"), []byte("external\n"), 0o644))-- content := "new\n"- _, err = svc.UpdateProject(ctx, project.ID, ptr("bar"), nil, nil, nil, &revision, []projecttypes.ProjectFileChange{- {Operation: projecttypes.FileOpCreateFile, RelativePath: "notes.txt", Content: &content},- }, models.User{- BaseModel: models.BaseModel{ID: "u1"},- Username: "tester",- })-- require.Error(t, err)- require.ErrorIs(t, err, common.ErrProjectFileConflict)- require.DirExists(t, originalPath)- require.NoDirExists(t, filepath.Join(projectsDir, "bar"))- require.FileExists(t, filepath.Join(originalPath, "external.txt"))- require.NoFileExists(t, filepath.Join(originalPath, "notes.txt"))-- var fromDB models.Project- require.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)- require.Equal(t, "Foo", fromDB.Name)- require.Equal(t, originalPath, fromDB.Path)-}-func TestProjectService_RecoverProjectRenameJournals_RollsBackUncommittedDirectoryRename(t *testing.T) {db := setupProjectTestDB(t)require.NoError(t, db.AutoMigrate(&models.KVEntry{}))@@ -7510,115 +7090,3 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenTargetPresrequire.FileExists(t, filepath.Join(oldPath, "compose.yaml"))require.NoDirExists(t, newPath)}--func TestProjectUpdateBackup_ScopedBackupAndRestore(t *testing.T) {- projectsDir := t.TempDir()- projectPath := createComposeProjectDir(t, projectsDir, "scoped")- require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env"), []byte("A=1\n"), 0o644))- require.NoError(t, os.MkdirAll(filepath.Join(projectPath, "data"), 0o755))- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "data", "keep.bin"), []byte("keep"), 0o644))-- compose := "services: {}\n"- scope := projects.BuildUpdateBackupScope(projectPath, &compose, nil, nil, []projecttypes.ProjectFileChange{- {Operation: projecttypes.FileOpCreateFile, RelativePath: "notes.txt", Content: ptr("notes\n")},- })-- backupDir := t.TempDir()- backup, err := projects.BackupProjectUpdateScope(projectPath, backupDir, scope)- require.NoError(t, err)- require.FileExists(t, filepath.Join(backupDir, "compose.yaml"))- require.FileExists(t, filepath.Join(backupDir, ".env"))- require.NoDirExists(t, filepath.Join(backupDir, "data"))- require.Equal(t, []string{"notes.txt"}, backup.AbsentEntries)-- // Simulate a failed update: compose overwritten, notes.txt created, and an- // out-of-scope file written into data/ by a running container.- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("broken\n"), 0o644))- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "notes.txt"), []byte("notes\n"), 0o644))- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "data", "new.bin"), []byte("new"), 0o644))-- require.NoError(t, projects.RestoreProjectUpdateBackup(projectPath, backup))-- restored, err := os.ReadFile(filepath.Join(projectPath, "compose.yaml"))- require.NoError(t, err)- require.Equal(t, "services:\n app:\n image: nginx:alpine\n", string(restored))- require.NoFileExists(t, filepath.Join(projectPath, "notes.txt"))- require.FileExists(t, filepath.Join(projectPath, "data", "keep.bin"))- require.FileExists(t, filepath.Join(projectPath, "data", "new.bin"))-}--func TestProjectService_UpdateProject_FileChangeFailureRollsBackScoped(t *testing.T) {- db := setupProjectTestDB(t)- ctx := context.Background()-- projectsDir := t.TempDir()- t.Setenv("PROJECTS_DIRECTORY", projectsDir)-- settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)- require.NoError(t, err)- require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsDir))-- eventService := event.NewEventService(db, nil, nil)- svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())- configureProjectRuntimeDockerInternal(t, nil)-- dirName := "rollback"- projectPath := createComposeProjectDir(t, projectsDir, dirName)- require.NoError(t, os.MkdirAll(filepath.Join(projectPath, "data"), 0o755))- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "data", "keep.bin"), []byte("keep"), 0o644))-- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-scoped-rollback"},- Name: "rollback",- DirName: &dirName,- Path: projectPath,- Status: models.ProjectStatusStopped,- }- require.NoError(t, db.Create(project).Error)-- _, revision, _, err := projects.ReadProjectFileTree(project.Path, config.Load().ProjectFileTreeMaxDepth, config.Load().ProjectScanSkipDirs, "compose.yaml", 0)- require.NoError(t, err)-- // The second change fails after the first has mutated the directory.- _, err = svc.UpdateProject(ctx, project.ID, nil, nil, nil, nil, &revision, []projecttypes.ProjectFileChange{- {Operation: projecttypes.FileOpCreateFile, RelativePath: "notes.txt", Content: ptr("notes\n")},- {Operation: projecttypes.FileOpUpdateFile, RelativePath: "missing.txt", Content: ptr("nope\n")},- }, models.User{BaseModel: models.BaseModel{ID: "u1"}, Username: "tester"})-- require.Error(t, err)- require.NoFileExists(t, filepath.Join(projectPath, "notes.txt"))- require.FileExists(t, filepath.Join(projectPath, "compose.yaml"))- require.FileExists(t, filepath.Join(projectPath, "data", "keep.bin"))-- entries, err := os.ReadDir(projectsDir)- require.NoError(t, err)- for _, entry := range entries {- require.False(t, strings.HasPrefix(entry.Name(), ".project-update-backup-"), "leftover backup dir: %s", entry.Name())- }-}--func TestProjectUpdateBackup_RenamedDirDemotedToCopyWhenBatchTouchesIt(t *testing.T) {- projectsDir := t.TempDir()- projectPath := createComposeProjectDir(t, projectsDir, "demote")- require.NoError(t, os.MkdirAll(filepath.Join(projectPath, "a"), 0o755))- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "a", "keep.txt"), []byte("keep\n"), 0o644))-- // Batch: rename a -> b, then delete b — the inverse rename cannot roll- // this back, so the rename must be demoted to a full copy of a.- scope := projects.BuildUpdateBackupScope(projectPath, nil, nil, nil, []projecttypes.ProjectFileChange{- {Operation: projecttypes.FileOpRename, RelativePath: "a", NewName: "b"},- {Operation: projecttypes.FileOpDelete, RelativePath: "b", Recursive: true},- })- require.Empty(t, scope.RenamedDirs)-- backup, err := projects.BackupProjectUpdateScope(projectPath, t.TempDir(), scope)- require.NoError(t, err)-- // Simulate the batch running, then failing on a later change.- require.NoError(t, os.Rename(filepath.Join(projectPath, "a"), filepath.Join(projectPath, "b")))- require.NoError(t, os.RemoveAll(filepath.Join(projectPath, "b")))-- require.NoError(t, projects.RestoreProjectUpdateBackup(projectPath, backup))- require.FileExists(t, filepath.Join(projectPath, "a", "keep.txt"))- require.NoDirExists(t, filepath.Join(projectPath, "b"))-}diff --git a/backend/internal/project/workspace.go b/backend/internal/project/workspace.gonew file mode 100644index 000000000..8db864f54--- /dev/null+++ b/backend/internal/project/workspace.go@@ -0,0 +1,249 @@+package project++import (+ "context"+ "io"+ "net/http"+ "os"+ "path/filepath"+ "strings"++ "emperror.dev/errors"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/projects"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace"+ projecttypes "github.com/getarcaneapp/arcane/types/v2/project"+ workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"+)++func (s *ProjectService) GetProjectWorkspace(ctx context.Context, projectID string) (*workspacetypes.Workspace, error) {+ proj, err := s.GetProjectFromDatabaseByID(ctx, projectID)+ if err != nil {+ return nil, err+ }+ if err := s.EnsureProjectPathUnderRoot(ctx, proj, false); err != nil {+ return nil, err+ }+ composeFileName := projects.DefaultComposeFileName+ if composeFile, resolveErr := s.ResolveProjectComposeFile(ctx, proj); resolveErr == nil {+ composeFileName = filepath.Base(composeFile)+ }+ files, revision, truncated, err := projects.ReadProjectWorkspace(+ proj.Path,+ s.config.ProjectWorkspaceMaxDepth,+ s.config.ProjectScanSkipDirs,+ composeFileName,+ s.config.ProjectWorkspaceMaxEntries,+ workspacepkg.MaxFileSizeBytes(s.config.ProjectWorkspaceMaxFileSizeMB),+ )+ if err != nil {+ return nil, errors.WrapIf(err, "read project workspace")+ }+ return &workspacetypes.Workspace{Files: files, FileTreeRevision: revision, FileTreeTruncated: truncated}, nil+}++func (s *ProjectService) GetProjectWorkspaceFile(ctx context.Context, projectID, relativePath string) (*workspacetypes.FileContent, error) {+ proj, rel, fullPath, info, err := s.resolveProjectWorkspacePathInternal(ctx, projectID, relativePath)+ if err != nil {+ return nil, err+ }+ _ = proj+ response := &workspacetypes.FileContent{+ Path: fullPath,+ RelativePath: rel,+ Name: filepath.Base(fullPath),+ Size: info.Size(),+ }+ if info.IsDir() {+ return nil, common.Classify(common.ErrProjectWorkspaceBadRequest, errors.New("workspace path is a directory"))+ }+ if info.Mode()&os.ModeSymlink != 0 {+ response.ReadOnlyReason = workspacetypes.FileReadOnlySymlink+ return response, nil+ }+ if !info.Mode().IsRegular() {+ response.ReadOnlyReason = workspacetypes.FileReadOnlySpecial+ return response, nil+ }+ maxBytes := workspacepkg.MaxFileSizeBytes(s.config.ProjectWorkspaceMaxFileSizeMB)+ if info.Size() > maxBytes {+ response.ReadOnlyReason = workspacetypes.FileReadOnlyTooLarge+ return response, nil+ }+ content, err := os.ReadFile(fullPath)+ if err != nil {+ return nil, errors.WrapIf(err, "read project workspace file")+ }+ response.MimeType = http.DetectContentType(content)+ if !workspacepkg.IsTextContent(content) {+ response.ReadOnlyReason = workspacetypes.FileReadOnlyBinary+ return response, nil+ }+ response.Editable = true+ response.Content = string(content)+ return response, nil+}++func (s *ProjectService) DownloadProjectWorkspaceFile(ctx context.Context, projectID, relativePath string) (io.ReadCloser, int64, string, error) {+ proj, rel, _, info, err := s.resolveProjectWorkspacePathInternal(ctx, projectID, relativePath)+ if err != nil {+ return nil, 0, "", err+ }+ if info.IsDir() {+ return nil, 0, "", common.Classify(common.ErrProjectWorkspaceBadRequest, errors.New("workspace path is a directory"))+ }+ root, err := os.OpenRoot(proj.Path)+ if err != nil {+ return nil, 0, "", errors.WrapIf(err, "open project workspace")+ }+ file, err := root.Open(filepath.ToSlash(rel))+ if err != nil {+ _ = root.Close()+ return nil, 0, "", errors.WrapIf(err, "open project workspace file")+ }+ return &projectWorkspaceDownloadInternal{ReadCloser: file, root: root}, info.Size(), filepath.Base(rel), nil+}++type projectWorkspaceDownloadInternal struct {+ io.ReadCloser++ root *os.Root+}++func (d *projectWorkspaceDownloadInternal) Close() error {+ fileErr := d.ReadCloser.Close()+ rootErr := d.root.Close()+ return errors.Combine(fileErr, rootErr)+}++func (s *ProjectService) UpdateProjectWorkspace(ctx context.Context, projectID string, manifest projecttypes.WorkspaceUpdateManifest, uploads map[int][]byte, user models.User) (*workspacetypes.Workspace, error) {+ if err := workspacepkg.ValidateUpdateManifest(manifest.FileTreeRevision, len(manifest.FileChanges), 500); err != nil {+ return nil, common.Classify(common.ErrProjectWorkspaceBadRequest, err)+ }+ proj, err := s.getMutableProjectInternal(ctx, projectID)+ if err != nil {+ return nil, err+ }+ if isGitOpsManagedProjectInternal(proj) {+ return nil, common.Classify(common.ErrProjectWorkspaceForbidden, errors.New("GitOps-managed project workspaces cannot be edited"))+ }+ if err := s.EnsureProjectPathUnderRoot(ctx, proj, true); err != nil {+ return nil, err+ }++ projectsDirectory, err := s.GetProjectsDirectory(ctx)+ if err != nil {+ return nil, err+ }+ backup, cleanup, err := s.prepareProjectWorkspaceBackupInternal(ctx, projectsDirectory, proj.Path, manifest.FileChanges)+ if err != nil {+ return nil, err+ }+ defer cleanup()++ opts := s.projectWorkspaceApplyOptionsInternal(ctx, proj, manifest.FileTreeRevision)+ if err := projects.ApplyProjectWorkspaceChanges(proj.Path, manifest.FileChanges, uploads, opts); err != nil {+ if restoreErr := projects.RestoreProjectUpdateBackup(proj.Path, backup); restoreErr != nil {+ return nil, errors.Combine(wrapProjectWorkspaceErrorInternal(err), errors.WrapIf(restoreErr, "rollback project workspace"))+ }+ return nil, wrapProjectWorkspaceErrorInternal(err)+ }++ s.refreshProjectImageRefsInternal(ctx, proj)+ if err := s.updateProjectStatusandCountsInternal(ctx, proj.ID, proj.Status); err != nil {+ return nil, errors.WrapIf(err, "refresh project after workspace update")+ }+ s.logProjectEventInternal(ctx, models.EventTypeProjectUpdate, proj.ID, proj.Name, user, models.JSON{+ "action": "update_project_workspace",+ "fileChangeCount": len(manifest.FileChanges),+ }, "could not log project workspace update")+ return s.GetProjectWorkspace(ctx, projectID)+}++func (s *ProjectService) resolveProjectWorkspacePathInternal(ctx context.Context, projectID, relativePath string) (*models.Project, string, string, os.FileInfo, error) {+ proj, err := s.GetProjectFromDatabaseByID(ctx, projectID)+ if err != nil {+ return nil, "", "", nil, err+ }+ rel, err := utils.NormalizeRelativePath(relativePath)+ if err != nil {+ return nil, "", "", nil, common.Classify(common.ErrProjectWorkspaceForbidden, errors.WrapIf(err, "invalid project workspace path"))+ }+ composeFileName := projects.DefaultComposeFileName+ if composeFile, resolveErr := s.ResolveProjectComposeFile(ctx, proj); resolveErr == nil {+ composeFileName = filepath.Base(composeFile)+ }+ rootName, _, _ := strings.Cut(rel, "/")+ protected := projects.ProtectedProjectFilePaths(composeFileName)+ if protected[rel] || protected[rootName] {+ return nil, "", "", nil, common.Classify(common.ErrProjectWorkspaceForbidden, errors.New("project configuration is not part of the workspace"))+ }+ fullPath := filepath.Join(proj.Path, filepath.FromSlash(rel))+ info, err := os.Lstat(fullPath)+ if err != nil {+ if os.IsNotExist(err) {+ return nil, "", "", nil, common.Classify(common.ErrProjectWorkspaceNotFound, errors.New("project workspace file not found"))+ }+ return nil, "", "", nil, errors.WrapIf(err, "inspect project workspace file")+ }+ return proj, rel, fullPath, info, nil+}++func (s *ProjectService) projectWorkspaceApplyOptionsInternal(ctx context.Context, proj *models.Project, expectedRevision string) projects.ProjectWorkspaceApplyOptions {+ composeFileName := projects.DefaultComposeFileName+ if composeFile, err := s.ResolveProjectComposeFile(ctx, proj); err == nil {+ composeFileName = filepath.Base(composeFile)+ }+ return projects.ProjectWorkspaceApplyOptions{+ ExpectedRevision: strings.TrimSpace(expectedRevision),+ MaxDepth: s.config.ProjectWorkspaceMaxDepth,+ MaxEntries: s.config.ProjectWorkspaceMaxEntries,+ MaxFileSizeBytes: workspacepkg.MaxFileSizeBytes(s.config.ProjectWorkspaceMaxFileSizeMB),+ SkipDirectories: s.config.ProjectScanSkipDirs,+ ComposeFileName: composeFileName,+ }+}++func (s *ProjectService) prepareProjectWorkspaceBackupInternal(ctx context.Context, projectsDirectory, projectPath string, changes []projecttypes.WorkspaceFileChange) (*projects.ProjectUpdateBackup, func(), error) {+ scope := projects.ProjectUpdateBackupScope{}+ for _, change := range changes {+ rel, err := utils.NormalizeRelativePath(change.RelativePath)+ if err != nil {+ continue+ }+ scope.Paths = append(scope.Paths, rel)+ switch change.Operation {+ case projecttypes.FileOpRename:+ if newName, nameErr := utils.ValidateFileName(change.NewName); nameErr == nil {+ scope.Paths = append(scope.Paths, filepath.ToSlash(filepath.Join(filepath.Dir(rel), newName)))+ }+ case projecttypes.FileOpMove:+ scope.Paths = append(scope.Paths, filepath.ToSlash(filepath.Join(change.NewParentPath, filepath.Base(rel))))+ }+ }+ backup, err := backupProjectDirectoryInternal(ctx, projectsDirectory, projectPath, scope)+ if err != nil {+ return nil, nil, err+ }+ return backup, func() { _ = os.RemoveAll(backup.BackupDir) }, nil+}++func isGitOpsManagedProjectInternal(proj *models.Project) bool {+ return proj != nil && proj.GitOpsManagedBy != nil && strings.TrimSpace(*proj.GitOpsManagedBy) != ""+}++func wrapProjectWorkspaceErrorInternal(err error) error {+ switch {+ case errors.Is(err, projects.ErrProjectWorkspaceRevisionConflict):+ return common.Classify(common.ErrProjectWorkspaceConflict, errors.WithStackIf(err))+ case errors.Is(err, projects.ErrProjectWorkspaceOutsideProjectDirectory),+ errors.Is(err, projects.ErrProjectWorkspaceProtectedPath),+ errors.Is(err, projects.ErrProjectWorkspaceSymlinkPath):+ return common.Classify(common.ErrProjectWorkspaceForbidden, errors.WrapIf(err, "forbidden project workspace path"))+ default:+ return common.Classify(common.ErrProjectWorkspaceBadRequest, errors.WrapIf(err, "invalid project workspace request"))+ }+}diff --git a/backend/internal/project/workspace_handler.go b/backend/internal/project/workspace_handler.gonew file mode 100644index 000000000..8166f143f--- /dev/null+++ b/backend/internal/project/workspace_handler.go@@ -0,0 +1,146 @@+package project++import (+ "context"+ "io"+ "mime/multipart"+ "net/http"+ "strconv"+ "strings"++ "emperror.dev/errors"+ "github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace"+ "github.com/getarcaneapp/arcane/types/v2/base"+ projecttypes "github.com/getarcaneapp/arcane/types/v2/project"+ workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"+ "github.com/samber/mo"+)++type GetProjectWorkspaceInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ProjectID string `path:"projectId" doc:"Project ID"`+}++type GetProjectWorkspaceOutput struct {+ Body base.ApiResponse[workspacetypes.Workspace]+}++type GetProjectWorkspaceFileInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ProjectID string `path:"projectId" doc:"Project ID"`+ RelativePath string `query:"relativePath" doc:"Path relative to the project workspace root"`+}++type GetProjectWorkspaceFileOutput struct {+ Body base.ApiResponse[workspacetypes.FileContent]+}++type UpdateProjectWorkspaceInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ ProjectID string `path:"projectId" doc:"Project ID"`+ RawBody multipart.Form `contentType:"multipart/form-data"`+}++type UpdateProjectWorkspaceOutput struct {+ Body base.ApiResponse[workspacetypes.Workspace]+}++func registerProjectWorkspaceRoutesInternal(api huma.API, h *ProjectHandler) {+ basePath := "/environments/{id}/projects/{projectId}/workspace"+ tag := "Project Workspace"+ handlerutil.RegisterSecured(api, handlerutil.Operation("get-project-workspace", http.MethodGet, basePath, "Get project workspace", "", tag), authz.PermProjectsRead, h.GetProjectWorkspace)+ handlerutil.RegisterSecured(api, handlerutil.Operation("get-project-workspace-file", http.MethodGet, basePath+"/file", "Get project workspace file", "", tag), authz.PermProjectsRead, h.GetProjectWorkspaceFile)+ handlerutil.RegisterSecured(api, handlerutil.Operation("download-project-workspace-file", http.MethodGet, basePath+"/file/download", "Download project workspace file", "", tag), authz.PermProjectsRead, h.DownloadProjectWorkspaceFile)+ updateOperation := handlerutil.Operation("update-project-workspace", http.MethodPut, basePath, "Update project workspace", "", tag)+ updateOperation.RequestBody = handlerutil.WorkspaceMultipartRequestBody("JSON encoded project workspace manifest")+ handlerutil.RegisterSecured(api, updateOperation, authz.PermProjectsUpdate, h.UpdateProjectWorkspace)+}++func projectWorkspaceHTTPErrorInternal(err error) error {+ switch {+ case errors.Is(err, common.ErrProjectWorkspaceConflict):+ return huma.Error409Conflict(err.Error())+ case errors.Is(err, common.ErrProjectArchived):+ return huma.Error409Conflict(err.Error())+ case errors.Is(err, common.ErrProjectWorkspaceForbidden):+ return huma.Error403Forbidden(err.Error())+ case errors.Is(err, common.ErrProjectWorkspaceNotFound), errors.Is(err, common.ErrProjectNotFound):+ return huma.Error404NotFound(err.Error())+ case errors.Is(err, common.ErrProjectWorkspaceBadRequest):+ return huma.Error400BadRequest(err.Error())+ default:+ return huma.Error500InternalServerError("internal error")+ }+}++func (h *ProjectHandler) GetProjectWorkspace(ctx context.Context, input *GetProjectWorkspaceInput) (*GetProjectWorkspaceOutput, error) {+ result, err := h.projectService.GetProjectWorkspace(ctx, input.ProjectID)+ if err != nil {+ return nil, projectWorkspaceHTTPErrorInternal(err)+ }+ return &GetProjectWorkspaceOutput{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil+}++func (h *ProjectHandler) GetProjectWorkspaceFile(ctx context.Context, input *GetProjectWorkspaceFileInput) (*GetProjectWorkspaceFileOutput, error) {+ result, err := h.projectService.GetProjectWorkspaceFile(ctx, input.ProjectID, input.RelativePath)+ if err != nil {+ return nil, projectWorkspaceHTTPErrorInternal(err)+ }+ return &GetProjectWorkspaceFileOutput{Body: base.ApiResponse[workspacetypes.FileContent]{Success: true, Data: *result}}, nil+}++func (h *ProjectHandler) DownloadProjectWorkspaceFile(ctx context.Context, input *GetProjectWorkspaceFileInput) (*huma.StreamResponse, error) {+ reader, size, name, err := h.projectService.DownloadProjectWorkspaceFile(ctx, input.ProjectID, input.RelativePath)+ if err != nil {+ return nil, projectWorkspaceHTTPErrorInternal(err)+ }+ return &huma.StreamResponse{Body: func(humaCtx huma.Context) {+ defer func() { _ = reader.Close() }()+ humaCtx.SetHeader("Content-Type", "application/octet-stream")+ humaCtx.SetHeader("Content-Disposition", "attachment; filename="+name)+ humaCtx.SetHeader("Content-Length", strconv.FormatInt(size, 10))+ _, _ = io.Copy(humaCtx.BodyWriter(), reader)+ }}, nil+}++func (h *ProjectHandler) UpdateProjectWorkspace(ctx context.Context, input *UpdateProjectWorkspaceInput) (*UpdateProjectWorkspaceOutput, error) {+ manifest, err := handlerutil.ParseMultipartJSONPart[projecttypes.WorkspaceUpdateManifest](input.RawBody, "manifest")+ if err != nil {+ return nil, err+ }+ maxFileSizeMB := workspacepkg.DefaultMaxFileSizeMB+ if h.projectService != nil && h.projectService.config != nil {+ maxFileSizeMB = h.projectService.config.ProjectWorkspaceMaxFileSizeMB+ }+ uploads, err := handlerutil.ReadWorkspaceUploads(input.RawBody, workspacepkg.MaxFileSizeBytes(maxFileSizeMB))+ if err != nil {+ return nil, err+ }+ user, err := handlerutil.RequireUser(ctx)+ if err != nil {+ return nil, err+ }+ var result *workspacetypes.Workspace+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{+ EnvironmentID: input.EnvironmentID, Type: models.ActivityTypeResourceAction, ResourceType: "project", ResourceID: input.ProjectID, ResourceName: input.ProjectID, User: user,+ Step: "Updating project workspace", Message: "Updating project workspace", SuccessMessage: "Project workspace updated successfully",+ Metadata: models.JSON{"action": "update_project_workspace", "fileChangeCount": len(manifest.FileChanges)},+ }, func(runtimeCtx context.Context) error {+ var updateErr error+ result, updateErr = h.projectService.UpdateProjectWorkspace(runtimeCtx, input.ProjectID, manifest, uploads, *user)+ return updateErr+ })+ if err != nil {+ return nil, projectWorkspaceHTTPErrorInternal(err)+ }+ result.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()+ return &UpdateProjectWorkspaceOutput{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil+}diff --git a/backend/internal/settings/handler.go b/backend/internal/settings/handler.goindex 421f9cc3a..06ea03f05 100644--- a/backend/internal/settings/handler.go+++ b/backend/internal/settings/handler.go@@ -21,12 +21,18 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"+ workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/category"searchtypes "github.com/getarcaneapp/arcane/types/v2/search"settingstypes "github.com/getarcaneapp/arcane/types/v2/settings")+const (+ projectWorkspaceMaxFileSizeSettingKey = "projectWorkspaceMaxFileSizeMb"+ volumeWorkspaceMaxFileSizeSettingKey = "volumeWorkspaceMaxFileSizeMb"+)+// SettingsHandler provides Huma-based settings management endpoints.type SettingsHandler struct {settingsService *SettingsService@@ -219,6 +225,17 @@ func (h *SettingsHandler) appendRuntimeSettingsInternal(settingsDto []settingstyType: "boolean",})+ projectWorkspaceMaxFileSizeMB := 10+ volumeWorkspaceMaxFileSizeMB := 10+ if h.cfg != nil {+ projectWorkspaceMaxFileSizeMB = workspacepkg.EffectiveMaxFileSizeMB(h.cfg.ProjectWorkspaceMaxFileSizeMB)+ volumeWorkspaceMaxFileSizeMB = workspacepkg.EffectiveMaxFileSizeMB(h.cfg.VolumeWorkspaceMaxFileSizeMB)+ }+ settingsDto = append(settingsDto,+ settingstypes.PublicSetting{Key: projectWorkspaceMaxFileSizeSettingKey, Value: strconv.Itoa(projectWorkspaceMaxFileSizeMB), Type: "number"},+ settingstypes.PublicSetting{Key: volumeWorkspaceMaxFileSizeSettingKey, Value: strconv.Itoa(volumeWorkspaceMaxFileSizeMB), Type: "number"},+ )+backupVolumeName := "arcane-backups"if h.cfg != nil && strings.TrimSpace(h.cfg.BackupVolumeName) != "" {backupVolumeName = h.cfg.BackupVolumeName@@ -296,6 +313,8 @@ func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInpfor _, setting := range h.settingsService.ListSettings(visibility) {allowedKeys[setting.Key] = struct{}{}}+ allowedKeys[projectWorkspaceMaxFileSizeSettingKey] = struct{}{}+ allowedKeys[volumeWorkspaceMaxFileSizeSettingKey] = struct{}{}filtered := make([]settingstypes.PublicSetting, 0, len(*settingsDto))for _, setting := range *settingsDto {if _, ok := allowedKeys[setting.Key]; ok {diff --git a/backend/internal/settings/handler_test.go b/backend/internal/settings/handler_test.gonew file mode 100644index 000000000..1cb568686--- /dev/null+++ b/backend/internal/settings/handler_test.go@@ -0,0 +1,124 @@+package settings++import (+ "context"+ "encoding/json/v2"+ "net/http"+ "os"+ "path/filepath"+ "runtime"+ "testing"++ "github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"+ settingstypes "github.com/getarcaneapp/arcane/types/v2/settings"+ "github.com/stretchr/testify/require"+)++func TestSettingsHandlerAppendRuntimeSettingsInternal(t *testing.T) {+ handler := &SettingsHandler{cfg: &config.Config{+ UIConfigurationDisabled: true,+ BackupVolumeName: "custom-backups",+ ProjectWorkspaceMaxFileSizeMB: 12,+ VolumeWorkspaceMaxFileSizeMB: 18,+ }}++ publicKeys := runtimeSettingKeysInternal(handler.appendRuntimeSettingsInternal(nil, false))+ require.NotContains(t, publicKeys, "uiConfigDisabled")+ require.NotContains(t, publicKeys, "backupVolumeName")+ require.NotContains(t, publicKeys, "depotConfigured")+ require.NotContains(t, publicKeys, "edgeMTLSManagerCAAvailable")++ authenticatedKeys := runtimeSettingKeysInternal(handler.appendRuntimeSettingsInternal(nil, true))+ require.Equal(t, "12", authenticatedKeys[projectWorkspaceMaxFileSizeSettingKey])+ require.Equal(t, "18", authenticatedKeys[volumeWorkspaceMaxFileSizeSettingKey])+ require.Equal(t, "true", authenticatedKeys["uiConfigDisabled"])+ require.Equal(t, "custom-backups", authenticatedKeys["backupVolumeName"])+ require.Equal(t, "false", authenticatedKeys["edgeMTLSManagerCAAvailable"])+}++func TestSettingsHandlerAppendRuntimeSettingsDoesNotGenerateEdgeMTLSCAInternal(t *testing.T) {+ assetsDir := t.TempDir()+ handler := &SettingsHandler{cfg: &config.Config{+ EdgeMTLSMode: edge.EdgeMTLSModeRequired,+ EdgeMTLSAssetsDir: assetsDir,+ }}++ authenticatedKeys := runtimeSettingKeysInternal(handler.appendRuntimeSettingsInternal(nil, true))+ require.Equal(t, "false", authenticatedKeys["edgeMTLSManagerCAAvailable"])+ require.NoFileExists(t, filepath.Join(assetsDir, "ca.crt"))+ require.NoFileExists(t, filepath.Join(assetsDir, "ca.key"))+}++func TestSettingsHandlerUpdateLocalEnvironmentRejectsUnreadableProjectsDirectoryInternal(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("POSIX permission-denied behavior is not portable to Windows")+ }+ if os.Geteuid() == 0 {+ t.Skip("test requires a non-root UID to trigger permission-denied on ReadDir")+ }++ ctx := context.Background()+ settingsService, err := newSettingsServiceForTestInternal(t, ctx, setupSettingsTestDB(t))+ require.NoError(t, err)+ originalDir := settingsService.GetSettingsConfig().ProjectsDirectory.Value++ unreadable := t.TempDir()+ require.NoError(t, os.Chmod(unreadable, 0))+ t.Cleanup(func() { _ = os.Chmod(unreadable, 0o700) })++ handler := &SettingsHandler{settingsService: settingsService, cfg: &config.Config{}}+ _, err = handler.updateSettingsForLocalEnvironment(ctx, settingstypes.Update{ProjectsDirectory: new(unreadable)})+ require.Error(t, err)++ var statusErr huma.StatusError+ require.ErrorAs(t, err, &statusErr)+ require.Equal(t, http.StatusBadRequest, statusErr.GetStatus())+ require.Contains(t, err.Error(), "cannot read projects directory")+ require.Equal(t, originalDir, settingsService.GetSettingsConfig().ProjectsDirectory.Value)+}++func TestSettingsHandlerRemoteWorkspaceSettingsVisibilityInternal(t *testing.T) {+ remoteSettings := []settingstypes.PublicSetting{+ {Key: "dockerHost", Type: "string", Value: "unix:///var/run/docker.sock"},+ {Key: "baseServerUrl", Type: "string", Value: "https://manager.example"},+ {Key: "defaultShell", Type: "string", Value: "/bin/bash"},+ {Key: projectWorkspaceMaxFileSizeSettingKey, Type: "number", Value: "12"},+ {Key: volumeWorkspaceMaxFileSizeSettingKey, Type: "number", Value: "18"},+ {Key: "futureAdminSetting", Type: "string", Value: "hidden"},+ }+ proxy := func(_ context.Context, _, method, path string, _ []byte, output any) error {+ require.Equal(t, http.MethodGet, method)+ require.Equal(t, "/api/environments/0/settings", path)+ payload, err := json.Marshal(remoteSettings)+ require.NoError(t, err)+ return json.Unmarshal(payload, output)+ }++ settingsService, err := newSettingsServiceForTestInternal(t, context.Background(), setupSettingsTestDB(t))+ require.NoError(t, err)+ handler := &SettingsHandler{settingsService: settingsService, proxyRemoteJSON: proxy}++ permissions := authz.NewPermissionSet()+ permissions.AddEnv("env-remote", authz.PermSettingsRead)+ ctx := context.WithValue(context.Background(), middleware.ContextKeyUserPermissions, permissions)+ output, err := handler.GetSettings(ctx, &GetSettingsInput{EnvironmentID: "env-remote"})+ require.NoError(t, err)+ require.Equal(t, []settingstypes.PublicSetting{remoteSettings[0], remoteSettings[3], remoteSettings[4]}, output.Body)++ adminCtx := context.WithValue(context.Background(), middleware.ContextKeyUserPermissions, authz.SudoPermissionSet())+ output, err = handler.GetSettings(adminCtx, &GetSettingsInput{EnvironmentID: "env-remote"})+ require.NoError(t, err)+ require.Equal(t, remoteSettings, output.Body)+}++func runtimeSettingKeysInternal(settings []settingstypes.PublicSetting) map[string]string {+ keys := make(map[string]string, len(settings))+ for _, setting := range settings {+ keys[setting.Key] = setting.Value+ }+ return keys+}diff --git a/backend/internal/settings/service.go b/backend/internal/settings/service.goindex 55e8941f0..fe15592f7 100644--- a/backend/internal/settings/service.go+++ b/backend/internal/settings/service.go@@ -219,7 +219,7 @@ func DefaultSettingsConfig() *models.Settings {AutoHealExcludedContainers: models.SettingVariable{Value: ""},AutoHealMaxRestarts: models.SettingVariable{Value: "5"},AutoHealRestartWindow: models.SettingVariable{Value: "30"},- VolumeBrowserHelperIdleTimeout: models.SettingVariable{Value: "10"},+ VolumeHelperIdleTimeout: models.SettingVariable{Value: "10"},BaseServerURL: models.SettingVariable{Value: "http://localhost"},EnableGravatar: models.SettingVariable{Value: "true"},AvatarMaxUploadSizeMb: models.SettingVariable{Value: "2"},diff --git a/backend/internal/volume/backup.go b/backend/internal/volume/backup.goindex 00985bb71..0f6306fad 100644--- a/backend/internal/volume/backup.go+++ b/backend/internal/volume/backup.go@@ -220,6 +220,11 @@ func (s *VolumeService) ensureBackupVolumeInternal(ctx context.Context) error {func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, user models.User) (*models.VolumeBackup, error) {slog.DebugContext(ctx, "volume service: create backup", "volume", volumeName, "user", user.ID)+ workspaceLock, _ := ctx.Value(volumeWorkspaceLockContextKeyInternal{}).(volumeWorkspaceLockContextInternal)+ if workspaceLock.service != s || workspaceLock.volumeName != volumeName {+ defer s.workspaceLocks.Lock(volumeName)()+ }+dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {return nil, err@@ -429,6 +434,12 @@ func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupIDif backup.VolumeName != volumeName {return errors.Errorf("backup does not belong to volume %s", volumeName)}+ unlock := s.workspaceLocks.Lock(volumeName)+ defer unlock()+ ctx = context.WithValue(ctx, volumeWorkspaceLockContextKeyInternal{}, volumeWorkspaceLockContextInternal{+ service: s,+ volumeName: volumeName,+ })// Check if volume is in use by running containersinUse, containerIDs, err := s.GetVolumeUsage(ctx, volumeName)@@ -554,6 +565,26 @@ func (s *VolumeService) backupArchiveFilenameInternal(backupID string) (string,return sanitizedBackupID + ".tar.gz", nil}+func (s *VolumeService) restoreBackupFilesInContainerInternal(ctx context.Context, containerID, filename string, cleanedPaths []string) (string, error) {+ args := make([]string, 0, len(cleanedPaths)+5)+ args = append(args, "sh", "-c", restoreBackupFilesScriptInternal, "sh", path.Join("/backups", filename))+ for _, cleaned := range cleanedPaths {+ args = append(args, "./"+cleaned)+ }+ _, stderr, err := s.execInContainerInternal(ctx, containerID, args)+ return stderr, errors.WrapIf(err, "failed to restore files")+}++const restoreBackupFilesScriptInternal = `set -e+archive="$1"+shift+archive_mode=$(stat -c '%A' -- "$archive" 2>/dev/null) || { echo ARCANE_NOT_FOUND >&2; exit 44; }+case "$archive_mode" in -*) ;; *) echo ARCANE_NOT_FOUND >&2; exit 44 ;; esac+for member do+ if ! tar -tzf "$archive" -- "$member" >/dev/null 2>&1; then echo ARCANE_NOT_FOUND >&2; exit 44; fi+done+tar -xzf "$archive" -C /volume -- "$@"`+func (s *VolumeService) BackupHasPath(ctx context.Context, backupID string, filePath string) (bool, error) {slog.DebugContext(ctx, "volume service: backup has path", "backup_id", backupID, "path", filePath)cleaned, err := s.sanitizeBackupPathInternal(filePath)@@ -694,6 +725,12 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backif backup.VolumeName != volumeName {return errors.New("backup does not belong to volume")}+ unlock := s.workspaceLocks.Lock(volumeName)+ defer unlock()+ ctx = context.WithValue(ctx, volumeWorkspaceLockContextKeyInternal{}, volumeWorkspaceLockContextInternal{+ service: s,+ volumeName: volumeName,+ })// Create pre-restore backup for safety (consistent with RestoreBackup behavior)preBackup, err := s.CreateBackup(ctx, volumeName, user)@@ -714,11 +751,6 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backreturn errors.New("no valid paths provided")}- tarPaths := make([]string, 0, len(cleanedPaths))- for _, p := range cleanedPaths {- tarPaths = append(tarPaths, "./"+p)- }-dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {return err@@ -763,8 +795,7 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, back}defer cleanup()- cmd := append([]string{"tar", "-xzf", path.Join("/backups", filename), "-C", "/volume", "--"}, tarPaths...)- _, stderr, err := s.execInContainerInternal(ctx, resp.ID, cmd)+ stderr, err := s.restoreBackupFilesInContainerInternal(ctx, resp.ID, filename, cleanedPaths)if err != nil {return errors.WrapIf(err, "failed to restore files")}@@ -859,6 +890,12 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,return errors.WrapIf(err, "invalid archive")}_ = gzr.Close()+ unlock := s.workspaceLocks.Lock(volumeName)+ defer unlock()+ ctx = context.WithValue(ctx, volumeWorkspaceLockContextKeyInternal{}, volumeWorkspaceLockContextInternal{+ service: s,+ volumeName: volumeName,+ })preBackup, err := s.CreateBackup(ctx, volumeName, user)if err != nil {@@ -870,7 +907,7 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,return err}- containerID, cleanup, err := s.createTempContainerInternal(ctx, volumeName, false)+ containerID, cleanup, err := s.acquireVolumeHelperInternal(ctx, volumeName)if err != nil {return err}diff --git a/backend/internal/volume/files.go b/backend/internal/volume/files.godeleted file mode 100644index d77511b02..000000000--- a/backend/internal/volume/files.go+++ /dev/null@@ -1,330 +0,0 @@-package volume--import (- "archive/tar"- "bytes"- "context"- "io"- "log/slog"- "net/http"- "path"- "strconv"- "strings"- "time"-- "emperror.dev/errors"-- "github.com/getarcaneapp/arcane/backend/v2/internal/models"- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"- volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"- "github.com/moby/moby/client"-)--// isBrowsableVolumeInternal returns an error if the volume uses driver options-// that prevent it from being mounted inside a helper container, such as-// type=none or o=bind (host bind-mounts that require a device path on the host).-func (s *VolumeService) isBrowsableVolumeInternal(ctx context.Context, volumeName string) error {- vol, err := s.GetVolumeByName(ctx, volumeName)- if err != nil {- return errors.WrapIf(err, "failed to inspect volume")- }- if vol.Options["type"] == "none" || strings.Contains(vol.Options["o"], "bind") {- return errors.Errorf("volume %q uses a custom mount configuration and cannot be browsed", volumeName)- }- return nil-}--func (s *VolumeService) ListDirectory(ctx context.Context, volumeName, dirPath string) ([]volumetypes.FileEntry, error) {- slog.DebugContext(ctx, "volume service: list directory", "volume", volumeName, "path", dirPath)-- if err := s.isBrowsableVolumeInternal(ctx, volumeName); err != nil {- return nil, err- }-- sanitizedPath, err := utils.SanitizeBrowsePath(dirPath)- if err != nil {- return nil, errors.WrapIf(err, "invalid path")- }-- containerID, cleanup, err := s.createTempContainerInternal(ctx, volumeName, true)- if err != nil {- return nil, err- }- defer cleanup()-- targetPath := path.Join("/volume", sanitizedPath)- cmd := []string{- "sh",- "-c",- `find "$1" -mindepth 1 -maxdepth 1 | while IFS= read -r f; do out=$(stat -c "%s %Y %f %A" -- "$f" 2>/dev/null) || continue; printf "%s\0%s\0" "$f" "$out"; done`,- "sh",- targetPath,- }- stdout, _, err := s.execInContainerInternal(ctx, containerID, cmd)- if err != nil {- return nil, errors.WrapIf(err, "failed to list directory")- }-- lines := strings.Split(stdout, "\x00")- entries := make([]volumetypes.FileEntry, 0)- for i := 0; i+1 < len(lines); i += 2 {- fullPath := lines[i]- meta := strings.Fields(strings.TrimSpace(lines[i+1]))- if fullPath == "" || len(meta) < 4 {- continue- }- name := path.Base(fullPath)- size, _ := strconv.ParseInt(meta[0], 10, 64)- modTimeSec, _ := strconv.ParseInt(meta[1], 10, 64)- mode := meta[3]-- isDir := strings.HasPrefix(mode, "d")- isSymlink := strings.HasPrefix(mode, "l")-- relPath := strings.TrimPrefix(fullPath, "/volume")- if relPath == "" {- relPath = "/"- }-- entry := volumetypes.FileEntry{- Name: name,- Path: relPath,- IsDirectory: isDir,- Size: size,- ModTime: time.Unix(modTimeSec, 0),- Mode: mode,- IsSymlink: isSymlink,- }-- if isSymlink {- // Use readlink without -f to get the raw symlink target (not resolved)- // This prevents exposing paths outside the volume- target, _, _ := s.execInContainerInternal(ctx, containerID, []string{"readlink", fullPath})- target = strings.TrimSpace(target)- if target != "" {- // If target is relative, it's safe to show- // If target is absolute and within /volume, strip the /volume prefix- // If target points outside /volume, indicate it's external- switch {- case strings.HasPrefix(target, "/volume/"):- entry.LinkTarget = strings.TrimPrefix(target, "/volume")- case strings.HasPrefix(target, "/volume"):- entry.LinkTarget = "/"- case !strings.HasPrefix(target, "/"):- // Relative path - safe to show as-is- entry.LinkTarget = target- default:- // Absolute path outside /volume - indicate it's external- entry.LinkTarget = "(external)"- }- }- }-- entries = append(entries, entry)- }-- return entries, nil-}--func (s *VolumeService) GetFileContent(ctx context.Context, volumeName, filePath string, maxBytes int64) ([]byte, string, error) {- slog.DebugContext(ctx, "volume service: get file content", "volume", volumeName, "path", filePath, "max_bytes", maxBytes)-- if err := s.isBrowsableVolumeInternal(ctx, volumeName); err != nil {- return nil, "", err- }-- sanitizedPath, err := utils.SanitizeBrowsePath(filePath)- if err != nil {- return nil, "", errors.WrapIf(err, "invalid path")- }-- containerID, cleanup, err := s.createTempContainerInternal(ctx, volumeName, true)- if err != nil {- return nil, "", err- }- defer cleanup()-- targetPath := path.Join("/volume", sanitizedPath)- cmd := []string{"head", "-c", strconv.FormatInt(maxBytes, 10), targetPath}- stdout, _, err := s.execInContainerInternal(ctx, containerID, cmd)- if err != nil {- return nil, "", errors.WrapIf(err, "failed to read file")- }-- content := []byte(stdout)- mimeType := http.DetectContentType(content)-- return content, mimeType, nil-}--func (s *VolumeService) DownloadFile(ctx context.Context, volumeName, filePath string) (io.ReadCloser, int64, error) {- slog.DebugContext(ctx, "volume service: download file", "volume", volumeName, "path", filePath)-- if err := s.isBrowsableVolumeInternal(ctx, volumeName); err != nil {- return nil, 0, err- }-- sanitizedPath, err := utils.SanitizeBrowsePath(filePath)- if err != nil {- return nil, 0, errors.WrapIf(err, "invalid path")- }-- dockerClient, err := s.dockerService.GetClient(ctx)- if err != nil {- return nil, 0, err- }-- containerID, cleanup, err := s.createTempContainerInternal(ctx, volumeName, true)- if err != nil {- return nil, 0, err- }-- targetPath := path.Join("/volume", sanitizedPath)- return volumehelper.DownloadFileFromContainer(ctx, dockerClient, containerID, targetPath, cleanup)-}--func (s *VolumeService) DeleteFile(ctx context.Context, volumeName, filePath string, user *models.User) error {- slog.DebugContext(ctx, "volume service: delete file", "volume", volumeName, "path", filePath)-- sanitizedPath, err := utils.SanitizeBrowsePath(filePath)- if err != nil {- return errors.WrapIf(err, "invalid path")- }- // Prevent deleting root- if sanitizedPath == "/" {- return errors.New("cannot delete root directory")- }-- containerID, cleanup, err := s.createTempContainerInternal(ctx, volumeName, false)- if err != nil {- return err- }- defer cleanup()-- targetPath := path.Join("/volume", sanitizedPath)- _, stderr, err := s.execInContainerInternal(ctx, containerID, []string{"rm", "-rf", targetPath})- if err != nil {- return err- }- if stderr != "" {- return errors.Errorf("delete failed: %s", stderr)- }-- actingUser := user- if actingUser == nil {- actingUser = &models.SystemUser- }- metadata := models.JSON{- "action": "file_delete",- "path": filePath,- }- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeFileDelete, volumeName, volumeName, actingUser.ID, actingUser.Username, "0", metadata); logErr != nil {- slog.WarnContext(ctx, "could not log volume file delete event", "volume", volumeName, "error", logErr.Error())- }- return nil-}--func (s *VolumeService) CreateDirectory(ctx context.Context, volumeName, dirPath string, user *models.User) error {- slog.DebugContext(ctx, "volume service: create directory", "volume", volumeName, "path", dirPath)-- sanitizedPath, err := utils.SanitizeBrowsePath(dirPath)- if err != nil {- return errors.WrapIf(err, "invalid path")- }-- containerID, cleanup, err := s.createTempContainerInternal(ctx, volumeName, false)- if err != nil {- return err- }- defer cleanup()-- targetPath := path.Join("/volume", sanitizedPath)- _, stderr, err := s.execInContainerInternal(ctx, containerID, []string{"mkdir", "-p", targetPath})- if err != nil {- return err- }- if stderr != "" {- return errors.Errorf("mkdir failed: %s", stderr)- }-- actingUser := user- if actingUser == nil {- actingUser = &models.SystemUser- }- metadata := models.JSON{- "action": "file_create",- "path": dirPath,- }- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeFileCreate, volumeName, volumeName, actingUser.ID, actingUser.Username, "0", metadata); logErr != nil {- slog.WarnContext(ctx, "could not log volume file create event", "volume", volumeName, "error", logErr.Error())- }- return nil-}--func (s *VolumeService) UploadFile(ctx context.Context, volumeName, destPath string, content io.Reader, filename string, user *models.User) error {- slog.DebugContext(ctx, "volume service: upload file", "volume", volumeName, "dest_path", destPath, "filename", filename)-- sanitizedPath, err := utils.SanitizeBrowsePath(destPath)- if err != nil {- return errors.WrapIf(err, "invalid path")- }-- dockerClient, err := s.dockerService.GetClient(ctx)- if err != nil {- return err- }-- containerID, cleanup, err := s.createTempContainerInternal(ctx, volumeName, false)- if err != nil {- return err- }- defer cleanup()-- var buf bytes.Buffer- tw := tar.NewWriter(&buf)-- contentBytes, err := io.ReadAll(content)- if err != nil {- return err- }-- hdr := &tar.Header{- Name: filename,- Mode: 0o644,- Size: int64(len(contentBytes)),- }- if err := tw.WriteHeader(hdr); err != nil {- return err- }- if _, err := tw.Write(contentBytes); err != nil {- return err- }- if err := tw.Close(); err != nil {- return err- }-- targetDir := path.Join("/volume", sanitizedPath)- _, err = dockerClient.CopyToContainer(ctx, containerID, client.CopyToContainerOptions{- DestinationPath: targetDir,- Content: &buf,- })- if err != nil {- return errors.WrapIf(err, "failed to upload")- }-- actingUser := user- if actingUser == nil {- actingUser = &models.SystemUser- }- metadata := models.JSON{- "action": "file_upload",- "path": destPath,- "filename": filename,- }- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeFileUpload, volumeName, volumeName, actingUser.ID, actingUser.Username, "0", metadata); logErr != nil {- slog.WarnContext(ctx, "could not log volume file upload event", "volume", volumeName, "error", logErr.Error())- }-- return nil-}diff --git a/backend/internal/volume/handler.go b/backend/internal/volume/handler.goindex 0c4ad56ed..e2eedd509 100644--- a/backend/internal/volume/handler.go+++ b/backend/internal/volume/handler.go@@ -5,7 +5,6 @@ import ("io""mime/multipart""net/http"- "path""strconv""strings"@@ -143,58 +142,7 @@ type GetVolumeSizesOutput struct {Body base.ApiResponse[[]VolumeSizeInfo]}-// --- Volume Browser & Backup -----type BrowseDirectoryInput struct {- EnvironmentID string `path:"id" doc:"Environment ID"`- VolumeName string `path:"volumeName" doc:"Volume name"`- Path string `query:"path" default:"/" doc:"Directory path to browse"`-}--type BrowseDirectoryOutput struct {- Body base.ApiResponse[[]volumetypes.FileEntry]-}--type GetFileContentInput struct {- EnvironmentID string `path:"id" doc:"Environment ID"`- VolumeName string `path:"volumeName" doc:"Volume name"`- Path string `query:"path" doc:"File path"`- MaxBytes int64 `query:"maxBytes" default:"1048576" doc:"Maximum bytes to read (default 1MB)"`-}--type FileContentResponse struct {- Content []byte `json:"content"`- MimeType string `json:"mimeType"`-}--type GetFileContentOutput struct {- Body base.ApiResponse[FileContentResponse]-}--type DownloadFileInput struct {- EnvironmentID string `path:"id" doc:"Environment ID"`- VolumeName string `path:"volumeName" doc:"Volume name"`- Path string `query:"path" doc:"File path"`-}--type UploadFileInput struct {- EnvironmentID string `path:"id" doc:"Environment ID"`- VolumeName string `path:"volumeName" doc:"Volume name"`- Path string `query:"path" default:"/" doc:"Destination path"`- RawBody multipart.Form `contentType:"multipart/form-data"`-}--type CreateDirectoryInput struct {- EnvironmentID string `path:"id" doc:"Environment ID"`- VolumeName string `path:"volumeName" doc:"Volume name"`- Path string `query:"path" doc:"Directory path to create"`-}--type DeleteFileInput struct {- EnvironmentID string `path:"id" doc:"Environment ID"`- VolumeName string `path:"volumeName" doc:"Volume name"`- Path string `query:"path" doc:"File or directory path to delete"`-}+// --- Volume Backup ---type ListBackupsInput struct {EnvironmentID string `path:"id" doc:"Environment ID"`@@ -387,76 +335,7 @@ func RegisterVolumes(api huma.API, dockerService *docker.DockerClientService, vo// --- Volume Browsing Endpoints ---- middleware.RegisterWithPermission(api, huma.Operation{- OperationID: "browse-volume-directory",- Method: http.MethodGet,- Path: "/environments/{id}/volumes/{volumeName}/browse",- Summary: "List volume directory",- Tags: []string{"Volume Browser"},- Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermVolumesBrowse, h.BrowseDirectory)-- middleware.RegisterWithPermission(api, huma.Operation{- OperationID: "get-volume-file-content",- Method: http.MethodGet,- Path: "/environments/{id}/volumes/{volumeName}/browse/content",- Summary: "Get file content preview",- Tags: []string{"Volume Browser"},- Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermVolumesBrowse, h.GetFileContent)-- middleware.RegisterWithPermission(api, huma.Operation{- OperationID: "download-volume-file",- Method: http.MethodGet,- Path: "/environments/{id}/volumes/{volumeName}/browse/download",- Summary: "Download file from volume",- Tags: []string{"Volume Browser"},- Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermVolumesBrowse, h.DownloadFile)-- middleware.RegisterWithPermission(api, huma.Operation{- OperationID: "upload-volume-file",- Method: http.MethodPost,- Path: "/environments/{id}/volumes/{volumeName}/browse/upload",- Summary: "Upload file to volume",- Tags: []string{"Volume Browser"},- Security: handlerutil.DefaultOperationSecurity(),- RequestBody: &huma.RequestBody{- Content: map[string]*huma.MediaType{- "multipart/form-data": {- Schema: &huma.Schema{- Type: "object",- Properties: map[string]*huma.Schema{- "file": {- Type: "string",- Format: "binary",- Description: "File to upload",- },- },- Required: []string{"file"},- },- },- },- },- }, authz.PermVolumesUpload, h.UploadFile)-- middleware.RegisterWithPermission(api, huma.Operation{- OperationID: "create-volume-directory",- Method: http.MethodPost,- Path: "/environments/{id}/volumes/{volumeName}/browse/mkdir",- Summary: "Create directory in volume",- Tags: []string{"Volume Browser"},- Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermVolumesUpload, h.CreateDirectory)-- middleware.RegisterWithPermission(api, huma.Operation{- OperationID: "delete-volume-file",- Method: http.MethodDelete,- Path: "/environments/{id}/volumes/{volumeName}/browse",- Summary: "Delete file or directory in volume",- Tags: []string{"Volume Browser"},- Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermVolumesDelete, h.DeleteFile)+ registerVolumeWorkspaceRoutesInternal(api, h)// --- Volume Backup Endpoints ---@@ -467,7 +346,7 @@ func RegisterVolumes(api huma.API, dockerService *docker.DockerClientService, voSummary: "List volume backups",Tags: []string{"Volume Backup"},Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermVolumesBrowse, h.ListBackups)+ }, authz.PermVolumesRead, h.ListBackups)middleware.RegisterWithPermission(api, huma.Operation{OperationID: "create-volume-backup",@@ -512,7 +391,7 @@ func RegisterVolumes(api huma.API, dockerService *docker.DockerClientService, voSummary: "Download volume backup",Tags: []string{"Volume Backup"},Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermVolumesBrowse, h.DownloadBackup)+ }, authz.PermVolumesRead, h.DownloadBackup)middleware.RegisterWithPermission(api, huma.Operation{OperationID: "backup-has-path",@@ -521,7 +400,7 @@ func RegisterVolumes(api huma.API, dockerService *docker.DockerClientService, voSummary: "Check if backup contains path",Tags: []string{"Volume Backup"},Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermVolumesBrowse, h.BackupHasPath)+ }, authz.PermVolumesRead, h.BackupHasPath)middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-backup-files",@@ -530,7 +409,7 @@ func RegisterVolumes(api huma.API, dockerService *docker.DockerClientService, voSummary: "List files in a volume backup",Tags: []string{"Volume Backup"},Security: handlerutil.DefaultOperationSecurity(),- }, authz.PermVolumesBrowse, h.ListBackupFiles)+ }, authz.PermVolumesRead, h.ListBackupFiles)middleware.RegisterWithPermission(api, huma.Operation{OperationID: "upload-volume-backup",@@ -791,154 +670,6 @@ func (h *VolumeHandler) GetVolumeSizes(ctx context.Context, input *GetVolumeSize}, nil}-// --- Volume Browser Handler Methods -----func (h *VolumeHandler) BrowseDirectory(ctx context.Context, input *BrowseDirectoryInput) (*BrowseDirectoryOutput, error) {- entries, err := h.volumeService.ListDirectory(ctx, input.VolumeName, input.Path)- if err != nil {- return nil, huma.Error500InternalServerError(err.Error())- }- return &BrowseDirectoryOutput{- Body: base.ApiResponse[[]volumetypes.FileEntry]{- Success: true,- Data: entries,- },- }, nil-}--func (h *VolumeHandler) GetFileContent(ctx context.Context, input *GetFileContentInput) (*GetFileContentOutput, error) {- content, mimeType, err := h.volumeService.GetFileContent(ctx, input.VolumeName, input.Path, input.MaxBytes)- if err != nil {- return nil, huma.Error500InternalServerError(err.Error())- }- return &GetFileContentOutput{- Body: base.ApiResponse[FileContentResponse]{- Success: true,- Data: FileContentResponse{- Content: content,- MimeType: mimeType,- },- },- }, nil-}--func (h *VolumeHandler) DownloadFile(ctx context.Context, input *DownloadFileInput) (*huma.StreamResponse, error) {- reader, size, err := h.volumeService.DownloadFile(ctx, input.VolumeName, input.Path)- if err != nil {- return nil, huma.Error500InternalServerError(err.Error())- }-- return &huma.StreamResponse{- Body: func(humaCtx huma.Context) {- defer func() { _ = reader.Close() }()-- humaCtx.SetHeader("Content-Type", "application/octet-stream")- humaCtx.SetHeader("Content-Disposition", "attachment; filename="+path.Base(input.Path))- humaCtx.SetHeader("Content-Length", strconv.FormatInt(size, 10))-- writer := humaCtx.BodyWriter()- _, _ = io.Copy(writer, reader)- },- }, nil-}--func (h *VolumeHandler) UploadFile(ctx context.Context, input *UploadFileInput) (*base.ApiResponse[base.MessageResponse], error) {- file, fileHeader, err := handlerutil.OpenUploadedFile(input.RawBody)- if err != nil {- return nil, err- }- defer func() { _ = file.Close() }()-- user, _ := models.CurrentUserFromContext(ctx)- runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)- activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{- EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,- ResourceType: "volume",- ResourceID: input.VolumeName,- ResourceName: input.VolumeName,- User: user,- Step: "Uploading file",- Message: "Uploading file to volume",- SuccessMessage: "File uploaded successfully",- Metadata: models.JSON{- "action": "upload_volume_file",- "path": input.Path,- "filename": fileHeader.Filename,- },- }, func(runtimeCtx context.Context) error {- return h.volumeService.UploadFile(runtimeCtx, input.VolumeName, input.Path, file, fileHeader.Filename, user)- })- if err != nil {- return nil, huma.Error500InternalServerError(err.Error())- }- return &base.ApiResponse[base.MessageResponse]{- Success: true,- Data: base.MessageResponse{Message: "File uploaded successfully", ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},- }, nil-}--func (h *VolumeHandler) CreateDirectory(ctx context.Context, input *CreateDirectoryInput) (*base.ApiResponse[base.MessageResponse], error) {- return h.runVolumePathActivityInternal(ctx, input.EnvironmentID, input.VolumeName, input.Path, volumePathActivityConfigInternal{- Step: "Creating directory",- Message: "Creating directory in volume",- SuccessMessage: "Directory created successfully",- MetadataAction: "create_volume_directory",- Action: func(runtimeCtx context.Context, volumeName, path string, user *models.User) error {- return h.volumeService.CreateDirectory(runtimeCtx, volumeName, path, user)- },- })-}--func (h *VolumeHandler) DeleteFile(ctx context.Context, input *DeleteFileInput) (*base.ApiResponse[base.MessageResponse], error) {- return h.runVolumePathActivityInternal(ctx, input.EnvironmentID, input.VolumeName, input.Path, volumePathActivityConfigInternal{- Step: "Deleting file",- Message: "Deleting file or directory from volume",- SuccessMessage: "Deleted successfully",- MetadataAction: "delete_volume_file",- Action: func(runtimeCtx context.Context, volumeName, path string, user *models.User) error {- return h.volumeService.DeleteFile(runtimeCtx, volumeName, path, user)- },- })-}--type volumePathActivityConfigInternal struct {- Step string- Message string- SuccessMessage string- MetadataAction string- Action func(context.Context, string, string, *models.User) error-}--func (h *VolumeHandler) runVolumePathActivityInternal(ctx context.Context, environmentID, volumeName, volumePath string, cfg volumePathActivityConfigInternal) (*base.ApiResponse[base.MessageResponse], error) {- user, _ := models.CurrentUserFromContext(ctx)- runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)- activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{- EnvironmentID: environmentID,- Type: models.ActivityTypeResourceAction,- ResourceType: "volume",- ResourceID: volumeName,- ResourceName: volumeName,- User: user,- Step: cfg.Step,- Message: cfg.Message,- SuccessMessage: cfg.SuccessMessage,- Metadata: models.JSON{- "action": cfg.MetadataAction,- "path": volumePath,- },- }, func(runtimeCtx context.Context) error {- return cfg.Action(runtimeCtx, volumeName, volumePath, user)- })- if err != nil {- return nil, huma.Error500InternalServerError(err.Error())- }- return &base.ApiResponse[base.MessageResponse]{- Success: true,- Data: base.MessageResponse{Message: cfg.SuccessMessage, ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()},- }, nil-}-// --- Volume Backup Handler Methods ---func (h *VolumeHandler) ListBackups(ctx context.Context, input *ListBackupsInput) (*ListBackupsOutput, error) {diff --git a/backend/internal/volume/helper_container.go b/backend/internal/volume/helper_container.goindex 7c3d96440..8bb46ecb6 100644--- a/backend/internal/volume/helper_container.go+++ b/backend/internal/volume/helper_container.go@@ -3,7 +3,6 @@ package volumeimport ("bytes""context"- "fmt""io""log/slog""strings"@@ -24,7 +23,7 @@ import ("github.com/samber/mo")-// volumeHelper tracks a reused read-only browse helper container and the last+// volumeHelper tracks a reused helper container and the last// time it serviced a request, so idle helpers can be reaped. inUse counts the// requests currently holding the helper: the reaper must not remove a helper// mid-download just because it was acquired longer ago than the idle timeout.@@ -36,6 +35,36 @@ type volumeHelper struct {const volumeHelperImage = volumehelper.DefaultToolsImage+func isUnlabeledVolumeHelperContainerInternal(c container.Summary) bool {+ if !libarcane.IsInternalContainer(c.Labels) {+ return false+ }++ command := strings.ToLower(c.Command)+ if !strings.Contains(command, "sleep") || !strings.Contains(command, "infinity") {+ return false+ }++ for _, mounted := range c.Mounts {+ if mounted.Destination == "/volume" {+ return true+ }+ }++ return false+}++func isVolumeHelperContainerInternal(c container.Summary) bool {+ if isUnlabeledVolumeHelperContainerInternal(c) {+ return true+ }+ if !libarcane.IsInternalContainer(c.Labels) {+ return false+ }++ return strings.EqualFold(c.Labels[volumehelper.ContainerLabel], "true")+}+func getVolumeHelperImageInternal(ctx context.Context, dockerService *docker.DockerClientService, imageService *image.ImageService, dockerClient *client.Client) (string, error) {slog.DebugContext(ctx, "volume service: resolve helper image")var err error@@ -76,23 +105,19 @@ func getVolumeHelperImageInternal(ctx context.Context, dockerService *docker.Docreturn "", errors.WrapIf(pullErr, "failed to resolve helper image: tools image unavailable and arcane fallback not found")}-func (s *VolumeService) createTempContainerInternal(ctx context.Context, volumeName string, readOnly bool) (string, func(), error) {- slog.DebugContext(ctx, "volume service: create temp container", "volume", volumeName, "read_only", readOnly)+func (s *VolumeService) acquireVolumeHelperInternal(ctx context.Context, volumeName string) (string, func(), error) {+ slog.DebugContext(ctx, "volume service: acquire helper container", "volume", volumeName)dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {return "", nil, err}- if !readOnly {- return s.startHelperContainerInternal(ctx, dockerClient, volumeName, false)- }-- // Read-only helpers are shared and reaped when idle; the caller's cleanup+ // Helpers are shared and reaped when idle; the caller's cleanup// releases its in-use hold instead of removing the container. The resolve →// acquire gap is racy against the reaper, so retry a resolve whose helper// was reaped before this caller could take its hold.for range 3 {- containerID, err := s.resolveReadOnlyHelperInternal(ctx, dockerClient, volumeName)+ containerID, err := s.resolveHelperInternal(ctx, dockerClient, volumeName)if err != nil {return "", nil, err}@@ -103,14 +128,14 @@ func (s *VolumeService) createTempContainerInternal(ctx context.Context, volumeNreturn "", nil, errors.New("failed to acquire volume helper container")}-// resolveReadOnlyHelperInternal returns the shared read-only helper container ID+// resolveHelperInternal returns the shared helper container ID// for volumeName, creating it if needed. singleflight collapses concurrent// misses: without it both requests create a helper and the loser is orphaned,// holding the volume mount with no cleanup path until Arcane restarts. The// creation itself can pull an image, so it must not run under helperMu.-func (s *VolumeService) resolveReadOnlyHelperInternal(ctx context.Context, dockerClient *client.Client, volumeName string) (string, error) {+func (s *VolumeService) resolveHelperInternal(ctx context.Context, dockerClient *client.Client, volumeName string) (string, error) {resultCh := s.helperGroup.DoChan(volumeName, func() (any, error) {- if containerID, ok := s.getReusableReadOnlyContainerInternal(ctx, dockerClient, volumeName).Get(); ok {+ if containerID, ok := s.getReusableHelperInternal(ctx, dockerClient, volumeName).Get(); ok {return containerID, nil}@@ -118,11 +143,11 @@ func (s *VolumeService) resolveReadOnlyHelperInternal(ctx context.Context, docke// mid-create doesn't abort the helper the other waiters are blocked on,// but still bounded: WithoutCancel alone would let a hung daemon or// image pull wedge this singleflight key forever, queueing every later- // browse of the volume behind it with no recovery until restart.+ // workspace request for the volume behind it with no recovery until restart.createCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeouts.DefaultDockerImagePull)defer cancel()- containerID, _, createErr := s.startHelperContainerInternal(createCtx, dockerClient, volumeName, true)+ containerID, _, createErr := s.startHelperContainerInternal(createCtx, dockerClient, volumeName)if createErr != nil {return nil, createErr}@@ -183,9 +208,9 @@ func (s *VolumeService) acquireHelperInternal(volumeName, containerID string) (f}// startHelperContainerInternal creates and starts a volume helper container and-// returns a cleanup that removes it. Tracking of reusable read-only helpers is+// returns a cleanup that removes it. Tracking of reusable helpers is// the caller's responsibility.-func (s *VolumeService) startHelperContainerInternal(ctx context.Context, dockerClient *client.Client, volumeName string, readOnly bool) (string, func(), error) {+func (s *VolumeService) startHelperContainerInternal(ctx context.Context, dockerClient *client.Client, volumeName string) (string, func(), error) {helperImage, err := getVolumeHelperImageInternal(ctx, s.dockerService, s.imageService, dockerClient)if err != nil {return "", nil, err@@ -198,14 +223,7 @@ func (s *VolumeService) startHelperContainerInternal(ctx context.Context, dockerLabels: volumehelper.Labels(),}- hostConfig := volumehelper.HostConfig(helperImage, []string{- fmt.Sprintf("%s:/volume%s", volumeName, func() string {- if readOnly {- return ":ro"- }- return ""- }()),- }, nil)+ hostConfig := volumehelper.HostConfig(helperImage, []string{volumeName + ":/volume"}, nil)resp, err := dockerClient.ContainerCreate(ctx, client.ContainerCreateOptions{Config: config,@@ -227,7 +245,7 @@ func (s *VolumeService) startHelperContainerInternal(ctx context.Context, dockerreturn resp.ID, cleanup, nil}-func (s *VolumeService) getReusableReadOnlyContainerInternal(ctx context.Context, dockerClient *client.Client, volumeName string) mo.Option[string] {+func (s *VolumeService) getReusableHelperInternal(ctx context.Context, dockerClient *client.Client, volumeName string) mo.Option[string] {s.helperMu.Lock()helper := s.helperByVolume[volumeName]s.helperMu.Unlock()@@ -282,7 +300,7 @@ func (s *VolumeService) CleanupHelperContainers(ctx context.Context) {}}-// ReapIdleHelpers removes reused read-only browse helper containers that have+// ReapIdleHelpers removes reused helper containers that have// not serviced a request within idleTimeout. It is map-driven (orphaned helpers// not tracked in helperByVolume are left to the startup orphan sweep). Entries// are removed from the map before the container is removed, so a concurrent@@ -339,7 +357,7 @@ func (s *VolumeService) collectStaleHelperIDsInternal(now time.Time, idleTimeoutreturn staleIDs}-// StopHelper removes the reused read-only browse helper for a single volume, if+// StopHelper removes the reused helper for a single volume, if// one exists. It is idempotent: stopping a volume with no active helper returns// nil.func (s *VolumeService) StopHelper(ctx context.Context, volumeName string) error {@@ -392,7 +410,7 @@ func (s *VolumeService) CleanupOrphanedVolumeHelpers(ctx context.Context) (int,removedCount := 0for _, c := range containers.Items {- if !volumehelper.IsHelperContainer(c) {+ if !isVolumeHelperContainerInternal(c) {continue}diff --git a/backend/internal/volume/module.go b/backend/internal/volume/module.goindex ae2a26e82..c58ae25c6 100644--- a/backend/internal/volume/module.go+++ b/backend/internal/volume/module.go@@ -8,6 +8,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/image""github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ "github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/settings"@@ -16,13 +17,13 @@ import (// Dependencies are the collaborators the volume domain needs.type Dependencies struct {- DB *database.DB- Docker *docker.DockerClientService- Event *event.EventService- Settings *settings.SettingsService- Image *image.ImageService- Activity *activity.ActivityService- BackupVolumeName string+ DB *database.DB+ Docker *docker.DockerClientService+ Event *event.EventService+ Settings *settings.SettingsService+ Image *image.ImageService+ Activity *activity.ActivityService+ Config *config.Config}// Module wires the volume domain and mounts its routes.@@ -34,7 +35,7 @@ type Module struct {// New builds the volume domain from its dependencies.func New(deps Dependencies) *Module {return &Module{- service: NewVolumeService(deps.DB, deps.Docker, deps.Event, deps.Settings, deps.Image, deps.BackupVolumeName),+ service: NewVolumeService(deps.DB, deps.Docker, deps.Event, deps.Settings, deps.Image, deps.Config),deps: deps,}}diff --git a/backend/internal/volume/service.go b/backend/internal/volume/service.goindex 05b17f2d5..b0162674c 100644--- a/backend/internal/volume/service.go+++ b/backend/internal/volume/service.go@@ -6,6 +6,7 @@ import ("strings""sync"+ "github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/image"@@ -18,20 +19,26 @@ import (dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/moby/moby/client""golang.org/x/sync/singleflight")type VolumeService struct {- db *database.DB- dockerService *docker.DockerClientService- eventService *event.EventService- settingsService *settings.SettingsService- imageService *image.ImageService- backupVolumeName string- helperMu sync.Mutex- helperByVolume map[string]*volumeHelper+ db *database.DB+ dockerService *docker.DockerClientService+ eventService *event.EventService+ settingsService *settings.SettingsService+ imageService *image.ImageService+ backupVolumeName string+ workspaceMaxDepth int+ workspaceMaxEntries int+ workspaceMaxFileSizeBytes int64+ workspaceLocks utils.KeyedMutex+ helperMu sync.Mutex+ helperByVolume map[string]*volumeHelper// helperGroup deduplicates concurrent read-only helper creation per volume.// Without it two simultaneous browse requests each create a helper and the// second overwrites the first in helperByVolume, orphaning a `sleep infinity`@@ -39,21 +46,41 @@ type VolumeService struct {helperGroup singleflight.Group}+type volumeWorkspaceLockContextKeyInternal struct{}++type volumeWorkspaceLockContextInternal struct {+ service *VolumeService+ volumeName string+}+const trivyCacheVolumePruneFilterValue = libarcane.InternalResourceLabel + "=true"-func NewVolumeService(db *database.DB, dockerService *docker.DockerClientService, eventService *event.EventService, settingsService *settings.SettingsService, imageService *image.ImageService, backupVolumeName string) *VolumeService {+func NewVolumeService(db *database.DB, dockerService *docker.DockerClientService, eventService *event.EventService, settingsService *settings.SettingsService, imageService *image.ImageService, cfg *config.Config) *VolumeService {slog.Debug("volume service: new")+ backupVolumeName := ""+ workspaceMaxDepth := 50+ workspaceMaxEntries := 10000+ workspaceMaxFileSizeMB := workspacepkg.DefaultMaxFileSizeMB+ if cfg != nil {+ backupVolumeName = cfg.BackupVolumeName+ workspaceMaxDepth = cfg.VolumeWorkspaceMaxDepth+ workspaceMaxEntries = cfg.VolumeWorkspaceMaxEntries+ workspaceMaxFileSizeMB = cfg.VolumeWorkspaceMaxFileSizeMB+ }if strings.TrimSpace(backupVolumeName) == "" {backupVolumeName = "arcane-backups"}return &VolumeService{- db: db,- dockerService: dockerService,- eventService: eventService,- settingsService: settingsService,- imageService: imageService,- backupVolumeName: backupVolumeName,- helperByVolume: make(map[string]*volumeHelper),+ db: db,+ dockerService: dockerService,+ eventService: eventService,+ settingsService: settingsService,+ imageService: imageService,+ backupVolumeName: backupVolumeName,+ workspaceMaxDepth: workspaceMaxDepth,+ workspaceMaxEntries: workspaceMaxEntries,+ workspaceMaxFileSizeBytes: workspacepkg.MaxFileSizeBytes(workspaceMaxFileSizeMB),+ helperByVolume: make(map[string]*volumeHelper),}}diff --git a/backend/internal/volume/service_test.go b/backend/internal/volume/service_test.goindex 7dc6a23c3..251d1cfc7 100644--- a/backend/internal/volume/service_test.go+++ b/backend/internal/volume/service_test.go@@ -2,16 +2,221 @@ package volumeimport ("context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings""testing""time"+ "github.com/getarcaneapp/arcane/backend/v2/internal/docker"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/mount""github.com/moby/moby/api/types/volume"+ "github.com/moby/moby/client""github.com/stretchr/testify/require")+func newVolumeServiceTestDockerClientInternal(t *testing.T, server *httptest.Server) *client.Client {+ t.Helper()+ dockerClient, err := client.New(+ client.WithHost(server.URL),+ client.WithAPIVersion("1.41"),+ client.WithHTTPClient(server.Client()),+ )+ require.NoError(t, err)+ t.Cleanup(func() { _ = dockerClient.Close() })+ return dockerClient+}++func TestValidateVolumeHelperSupportInternalOnlyInspectsVolume(t *testing.T) {+ var requests []string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests = append(requests, r.Method+" "+r.URL.Path)+ if r.Method != http.MethodGet || !strings.HasSuffix(r.URL.Path, "/volumes/workspace-volume") {+ http.Error(w, "unexpected Docker request", http.StatusInternalServerError)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(volume.Volume{Name: "workspace-volume", Driver: "local"}); err != nil {+ t.Errorf("encode volume inspect response: %v", err)+ }+ }))+ t.Cleanup(server.Close)++ dockerService := docker.NewDockerClientService(context.Background(), nil, nil, nil).WithClient(newVolumeServiceTestDockerClientInternal(t, server))+ service := &VolumeService{dockerService: dockerService}++ require.NoError(t, service.validateVolumeHelperSupportInternal(context.Background(), "workspace-volume"))+ require.Equal(t, []string{"GET /v1.41/volumes/workspace-volume"}, requests)+}++func TestCreateTempContainerInternalReusesWritableHelper(t *testing.T) {+ var createCalls, startCalls, removeCalls int+ var createRequest struct {+ NetworkDisabled bool `json:"NetworkDisabled"`+ HostConfig *container.HostConfig `json:"HostConfig"`+ }+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(map[string]string{"Id": "tools-image"}); err != nil {+ t.Errorf("encode image inspect response: %v", err)+ }+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/create"):+ createCalls+++ if err := json.NewDecoder(r.Body).Decode(&createRequest); err != nil {+ t.Errorf("decode container create request: %v", err)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(map[string]any{"Id": "helper-1", "Warnings": []string{}}); err != nil {+ t.Errorf("encode container create response: %v", err)+ }+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/helper-1/start"):+ startCalls+++ w.WriteHeader(http.StatusNoContent)+ case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/helper-1/json"):+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(container.InspectResponse{+ ID: "helper-1",+ State: &container.State{Running: true},+ }); err != nil {+ t.Errorf("encode container inspect response: %v", err)+ }+ case r.Method == http.MethodDelete && strings.Contains(r.URL.Path, "/containers/helper-1"):+ removeCalls+++ w.WriteHeader(http.StatusNoContent)+ default:+ http.Error(w, "unexpected Docker request: "+r.Method+" "+r.URL.Path, http.StatusInternalServerError)+ }+ }))+ t.Cleanup(server.Close)++ service := &VolumeService{+ dockerService: docker.NewDockerClientService(context.Background(), nil, nil, nil).WithClient(newVolumeServiceTestDockerClientInternal(t, server)),+ helperByVolume: make(map[string]*volumeHelper),+ }++ firstID, releaseFirst, err := service.acquireVolumeHelperInternal(context.Background(), "workspace-volume")+ require.NoError(t, err)+ secondID, releaseSecond, err := service.acquireVolumeHelperInternal(context.Background(), "workspace-volume")+ require.NoError(t, err)++ require.Equal(t, "helper-1", firstID)+ require.Equal(t, firstID, secondID)+ require.Equal(t, 1, createCalls)+ require.Equal(t, 1, startCalls)+ require.Zero(t, removeCalls)+ require.True(t, createRequest.NetworkDisabled)+ require.NotNil(t, createRequest.HostConfig)+ require.Equal(t, []string{"workspace-volume:/volume"}, createRequest.HostConfig.Binds)+ require.Equal(t, 2, service.helperByVolume["workspace-volume"].inUse)++ service.helperByVolume["workspace-volume"].lastUsedAt = time.Now().Add(-time.Hour)+ require.Empty(t, service.collectStaleHelperIDsInternal(time.Now(), time.Minute))+ require.Contains(t, service.helperByVolume, "workspace-volume")++ releaseFirst()+ releaseSecond()+ require.Zero(t, service.helperByVolume["workspace-volume"].inUse)+}++func TestIsUnlabeledVolumeHelperContainerInternal(t *testing.T) {+ tests := []struct {+ name string+ summary container.Summary+ want bool+ }{+ {+ name: "unlabeled helper signature matches",+ summary: container.Summary{+ Labels: map[string]string{+ libarcane.InternalResourceLabel: "true",+ },+ Command: "sleep infinity",+ Mounts: []container.MountPoint{+ {Destination: "/volume"},+ },+ },+ want: true,+ },+ {+ name: "internal trivy-like helper is not treated as an unlabeled volume helper",+ summary: container.Summary{+ Labels: map[string]string{+ libarcane.InternalResourceLabel: "true",+ },+ Command: "trivy image --quiet alpine:latest",+ Mounts: []container.MountPoint{+ {Destination: "/var/run/docker.sock"},+ },+ },+ want: false,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ require.Equal(t, tt.want, isUnlabeledVolumeHelperContainerInternal(tt.summary))+ })+ }+}++func TestIsVolumeHelperContainerInternal_UsesExplicitHelperLabel(t *testing.T) {+ tests := []struct {+ name string+ summary container.Summary+ want bool+ }{+ {+ name: "new helper label matches",+ summary: container.Summary{+ Labels: map[string]string{+ libarcane.InternalResourceLabel: "true",+ volumehelper.ContainerLabel: "true",+ },+ },+ want: true,+ },+ {+ name: "generic internal volume mount does not match",+ summary: container.Summary{+ Labels: map[string]string{+ libarcane.InternalResourceLabel: "true",+ },+ Mounts: []container.MountPoint{+ {Destination: "/volume"},+ },+ },+ want: false,+ },+ {+ name: "unlabeled helper still matches",+ summary: container.Summary{+ Labels: map[string]string{+ libarcane.InternalResourceLabel: "true",+ },+ Command: "sleep infinity",+ Mounts: []container.MountPoint{+ {Destination: "/volume"},+ },+ },+ want: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ require.Equal(t, tt.want, isVolumeHelperContainerInternal(tt.summary))+ })+ }+}+func TestEnrichVolumesWithUsageDataInternal(t *testing.T) {tests := []struct {diff --git a/backend/internal/volume/workspace.go b/backend/internal/volume/workspace.gonew file mode 100644index 000000000..04b60469a--- /dev/null+++ b/backend/internal/volume/workspace.go@@ -0,0 +1,1094 @@+package volume++import (+ "archive/tar"+ "context"+ "crypto/sha256"+ "encoding/hex"+ stderrors "errors"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "os"+ "path"+ "slices"+ "strconv"+ "strings"+ "time"++ "emperror.dev/errors"+ cerrdefs "github.com/containerd/errdefs"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"+ dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace"+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"+ workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"+ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/api/types/mount"+ "github.com/moby/moby/client"+)++const volumeWorkspaceTreeScriptInternal = `export LC_ALL=C+depth_budget="$1"+entry_budget="$2"+truncated=0+stop=0++walk() {+ for full in "$1"/..?* "$1"/.[!.]* "$1"/*; do+ case "$stop" in 1) return ;; esac+ metadata=$(stat -c '%s|%y|%A' -- "$full" 2>/dev/null) || continue+ case "$entry_budget" in '') truncated=1; stop=1; return ;; esac++ name=${full##*/}+ case "$2" in '') rel=$name ;; *) rel="$2/$name" ;; esac+ size=${metadata%%|*}+ metadata=${metadata#*|}+ mtime=${metadata%|*}+ mode=${metadata##*|}+ link=+ case "$mode" in+ l*) kind=l; link=$(readlink "$full" 2>/dev/null) || link= ;;+ d*) kind=d ;;+ -*) kind=f ;;+ *) kind=s ;;+ esac+ printf '%s\0%s\0%s\0%s\0%s\0%s\0' "$rel" "$kind" "$size" "$mtime" "$mode" "$link"+ entry_budget=${entry_budget#?}++ case "$kind" in+ d)+ next_depth=${3#?}+ case "$next_depth" in+ '')+ for child in "$full"/..?* "$full"/.[!.]* "$full"/*; do+ if stat -c '%A' -- "$child" >/dev/null 2>&1; then truncated=1; break; fi+ done+ ;;+ *) walk "$full" "$rel" "$next_depth" ;;+ esac+ ;;+ esac+ done+}++walk /volume '' "$depth_budget"+printf 'ARCANE_TREE_END\0%s\0' "$truncated"`++func (s *VolumeService) GetVolumeWorkspace(ctx context.Context, volumeName string) (*workspacetypes.Workspace, error) {+ defer s.workspaceLocks.RLock(volumeName)()++ totalStartedAt := time.Now()+ defer func() {+ slog.DebugContext(ctx, "volume workspace load completed", "volume", volumeName, "total_duration", time.Since(totalStartedAt))+ }()++ inspectionStartedAt := time.Now()+ if err := s.validateVolumeHelperSupportInternal(ctx, volumeName); err != nil {+ return nil, classifyVolumeWorkspaceHelperSupportErrorInternal(err)+ }+ slog.DebugContext(ctx, "volume workspace inspection completed", "volume", volumeName, "duration", time.Since(inspectionStartedAt))++ helperStartedAt := time.Now()+ containerID, cleanup, err := s.acquireVolumeHelperInternal(ctx, volumeName)+ if err != nil {+ return nil, err+ }+ defer cleanup()+ slog.DebugContext(ctx, "volume workspace helper acquired", "volume", volumeName, "container_id", containerID, "duration", time.Since(helperStartedAt))++ scanStartedAt := time.Now()+ workspace, err := s.readVolumeWorkspaceFromContainerInternal(ctx, containerID)+ if err != nil {+ return nil, err+ }+ slog.DebugContext(ctx, "volume workspace tree scan completed", "volume", volumeName, "file_count", len(workspace.Files), "truncated", workspace.FileTreeTruncated, "duration", time.Since(scanStartedAt))+ return workspace, nil+}++func (s *VolumeService) readVolumeWorkspaceFromContainerInternal(ctx context.Context, containerID string) (*workspacetypes.Workspace, error) {+ maxDepth := s.workspaceMaxDepth+ if maxDepth <= 0 {+ maxDepth = 50+ }+ maxEntries := s.workspaceMaxEntries+ if maxEntries <= 0 {+ maxEntries = 10000+ }+ depthBudget := strings.Repeat("d", maxDepth)+ entryBudget := strings.Repeat("e", maxEntries)+ stdout, stderr, err := s.execInContainerInternal(ctx, containerID, []string{"sh", "-c", volumeWorkspaceTreeScriptInternal, "sh", depthBudget, entryBudget})+ if err != nil {+ return nil, classifyVolumeWorkspaceExecErrorInternal(err, stderr, "read volume workspace")+ }+ return parseVolumeWorkspaceTreeInternal(stdout, maxEntries, s.volumeWorkspaceMaxFileSizeBytesInternal())+}++func parseVolumeWorkspaceTreeInternal(stdout string, maxEntries int, configuredMaxFileSizeBytes ...int64) (*workspacetypes.Workspace, error) {+ maxFileSizeBytes := workspacepkg.MaxFileSizeBytes(workspacepkg.DefaultMaxFileSizeMB)+ if len(configuredMaxFileSizeBytes) == 1 && configuredMaxFileSizeBytes[0] > 0 {+ maxFileSizeBytes = configuredMaxFileSizeBytes[0]+ }+ fields := strings.Split(stdout, "\x00")+ if len(fields) > 0 && fields[len(fields)-1] == "" {+ fields = fields[:len(fields)-1]+ }+ if len(fields) < 2 || fields[len(fields)-2] != "ARCANE_TREE_END" || (fields[len(fields)-1] != "0" && fields[len(fields)-1] != "1") {+ return nil, errors.New("invalid volume workspace truncation marker")+ }+ truncated := fields[len(fields)-1] == "1"+ fields = fields[:len(fields)-2]+ if len(fields)%6 != 0 {+ return nil, errors.New("invalid volume workspace file entry")+ }+ entries := make([]workspacetypes.FileEntry, 0, min(len(fields)/6, maxEntries+1))+ classifications := make(map[string]string, min(len(fields)/6, maxEntries+1))+ for i := 0; i+5 < len(fields); i += 6 {+ if fields[i] == "" {+ continue+ }+ entry, classification, err := parseVolumeWorkspaceEntryInternal(fields[i:i+6], maxFileSizeBytes)+ if err != nil {+ return nil, err+ }+ classifications[entry.RelativePath] = classification+ entries = append(entries, entry)+ }++ revisionEntries := slices.Clone(entries)+ slices.SortFunc(revisionEntries, func(a, b workspacetypes.FileEntry) int {+ return strings.Compare(a.RelativePath, b.RelativePath)+ })+ truncated = truncated || len(entries) > maxEntries+ if len(revisionEntries) > maxEntries {+ revisionEntries = revisionEntries[:maxEntries]+ }+ entries = slices.Clone(revisionEntries)++ h := sha256.New()+ for _, entry := range revisionEntries {+ utils.WriteFileTreeRevisionEntry(h, entry.RelativePath, classifications[entry.RelativePath], entry.Size, entry.ModTime.UnixNano(), entry.Mode, false)+ }+ slices.SortFunc(entries, func(a, b workspacetypes.FileEntry) int {+ if a.IsDirectory != b.IsDirectory {+ if a.IsDirectory {+ return -1+ }+ return 1+ }+ return strings.Compare(a.RelativePath, b.RelativePath)+ })++ return &workspacetypes.Workspace{+ Files: entries,+ FileTreeRevision: hex.EncodeToString(h.Sum(nil)),+ FileTreeTruncated: truncated,+ }, nil+}++func parseVolumeWorkspaceEntryInternal(fields []string, maxFileSizeBytes int64) (workspacetypes.FileEntry, string, error) {+ relativePath := fields[0]+ size, err := strconv.ParseInt(fields[2], 10, 64)+ if err != nil {+ return workspacetypes.FileEntry{}, "", errors.WrapIf(err, "parse volume workspace file size")+ }+ modTime, err := parseVolumeWorkspaceModTimeInternal(fields[3])+ if err != nil {+ return workspacetypes.FileEntry{}, "", errors.WrapIf(err, "parse volume workspace modification time")+ }++ mode := fields[4]+ classificationKey := "kind:" + fields[1]+ if mode != "" {+ classificationKey = "mode:" + mode[:1]+ }+ classification := "special"+ switch classificationKey {+ case "kind:d", "mode:d":+ classification = "dir"+ case "kind:l", "mode:l":+ classification = "symlink"+ case "kind:f", "mode:-":+ classification = "file"+ }++ entry := workspacetypes.FileEntry{+ ModTime: modTime,+ Name: path.Base(relativePath),+ Path: "/" + relativePath,+ RelativePath: relativePath,+ Mode: mode,+ LinkTarget: fields[5],+ Size: size,+ IsDirectory: classification == "dir",+ IsSymlink: classification == "symlink",+ }+ switch classification {+ case "dir":+ entry.Size = 0+ entry.Editable = true+ case "symlink":+ entry.ReadOnlyReason = workspacetypes.FileReadOnlySymlink+ case "special":+ entry.ReadOnlyReason = workspacetypes.FileReadOnlySpecial+ case "file":+ if size > maxFileSizeBytes {+ entry.ReadOnlyReason = workspacetypes.FileReadOnlyTooLarge+ } else {+ entry.Editable = true+ }+ }+ return entry, classification, nil+}++func parseVolumeWorkspaceModTimeInternal(value string) (time.Time, error) {+ trimmed := strings.TrimSpace(value)+ if seconds, err := strconv.ParseFloat(trimmed, 64); err == nil {+ return time.Unix(0, int64(seconds*float64(time.Second))), nil+ }+ return time.Parse("2006-01-02 15:04:05 -0700", trimmed)+}++func (s *VolumeService) volumeWorkspaceMaxFileSizeBytesInternal() int64 {+ if s.workspaceMaxFileSizeBytes <= 0 {+ return workspacepkg.MaxFileSizeBytes(workspacepkg.DefaultMaxFileSizeMB)+ }+ return s.workspaceMaxFileSizeBytes+}++func (s *VolumeService) GetVolumeWorkspaceFile(ctx context.Context, volumeName, relativePath string) (*workspacetypes.FileContent, error) {+ defer s.workspaceLocks.RLock(volumeName)()++ if err := s.validateVolumeHelperSupportInternal(ctx, volumeName); err != nil {+ return nil, classifyVolumeWorkspaceHelperSupportErrorInternal(err)+ }+ rel, err := utils.NormalizeRelativePath(relativePath)+ if err != nil {+ return nil, common.Classify(common.ErrVolumeWorkspaceForbidden, errors.WrapIf(err, "invalid volume workspace path"))+ }+ containerID, cleanup, err := s.acquireVolumeHelperInternal(ctx, volumeName)+ if err != nil {+ return nil, err+ }+ defer cleanup()+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, err+ }+ statResult, err := dockerClient.ContainerStatPath(ctx, containerID, client.ContainerStatPathOptions{Path: path.Join("/volume", rel)})+ if err != nil {+ if cerrdefs.IsNotFound(err) {+ return nil, common.Classify(common.ErrVolumeWorkspaceNotFound, errors.New("volume workspace file not found"))+ }+ return nil, errors.WrapIf(err, "inspect volume workspace file")+ }+ stat := statResult.Stat+ if stat.Mode&os.ModeSymlink != 0 {+ return &workspacetypes.FileContent{Path: "/" + rel, RelativePath: rel, Name: path.Base(rel), Size: stat.Size, ReadOnlyReason: workspacetypes.FileReadOnlySymlink}, nil+ }+ if stat.Mode.IsDir() {+ return nil, common.Classify(common.ErrVolumeWorkspaceBadRequest, errors.New("path is a directory"))+ }+ if !stat.Mode.IsRegular() {+ return volumeWorkspaceFileContentResponseInternal(rel, "special", stat.Size, nil, s.volumeWorkspaceMaxFileSizeBytesInternal())+ }+ maxFileSizeBytes := s.volumeWorkspaceMaxFileSizeBytesInternal()+ if stat.Size > maxFileSizeBytes {+ return volumeWorkspaceFileContentResponseInternal(rel, "regular", stat.Size, nil, maxFileSizeBytes)+ }++ reader, size, err := volumehelper.DownloadFileFromContainer(ctx, dockerClient, containerID, path.Join("/volume", rel), func() {})+ if err != nil {+ return nil, errors.WrapIf(err, "read volume workspace file")+ }+ content, readErr := io.ReadAll(io.LimitReader(reader, maxFileSizeBytes+1))+ closeErr := reader.Close()+ if readErr != nil {+ return nil, errors.WrapIf(readErr, "read volume workspace file content")+ }+ if closeErr != nil {+ return nil, errors.WrapIf(closeErr, "close volume workspace file content")+ }+ if int64(len(content)) > maxFileSizeBytes || size > maxFileSizeBytes {+ return volumeWorkspaceFileContentResponseInternal(rel, "regular", size, nil, maxFileSizeBytes)+ }+ return volumeWorkspaceFileContentResponseInternal(rel, "regular", size, content, maxFileSizeBytes)+}++func (s *VolumeService) DownloadVolumeWorkspaceFile(ctx context.Context, volumeName, relativePath string) (io.ReadCloser, int64, error) {+ unlock := s.workspaceLocks.RLock(volumeName)+ if err := s.validateVolumeHelperSupportInternal(ctx, volumeName); err != nil {+ unlock()+ return nil, 0, classifyVolumeWorkspaceHelperSupportErrorInternal(err)+ }+ rel, err := utils.NormalizeRelativePath(relativePath)+ if err != nil {+ unlock()+ return nil, 0, common.Classify(common.ErrVolumeWorkspaceForbidden, errors.WrapIf(err, "invalid volume workspace path"))+ }+ containerID, cleanup, err := s.acquireVolumeHelperInternal(ctx, volumeName)+ if err != nil {+ unlock()+ return nil, 0, err+ }+ cleanupAndUnlock := func() {+ cleanup()+ unlock()+ }+ parent := path.Dir(rel)+ if parent != "." {+ if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, parent, false); err != nil {+ cleanupAndUnlock()+ return nil, 0, err+ }+ }+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ cleanupAndUnlock()+ return nil, 0, err+ }+ return volumehelper.DownloadFileFromContainer(ctx, dockerClient, containerID, path.Join("/volume", rel), cleanupAndUnlock)+}++func (s *VolumeService) validateVolumeHelperSupportInternal(ctx context.Context, volumeName string) error {+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return errors.WrapIf(err, "failed to connect to Docker")+ }+ result, err := dockerClient.VolumeInspect(ctx, volumeName, client.VolumeInspectOptions{})+ if err != nil {+ return errors.WrapIf(err, "failed to inspect volume")+ }+ return dockerutil.ValidateVolumeWorkspaceHelperSupport(volumeName, result.Volume.Options)+}++func volumeWorkspaceFileContentResponseInternal(relativePath, kind string, size int64, content []byte, maxFileSizeBytes int64) (*workspacetypes.FileContent, error) {+ response := &workspacetypes.FileContent{+ Path: "/" + relativePath,+ RelativePath: relativePath,+ Name: path.Base(relativePath),+ MimeType: http.DetectContentType(content),+ Size: size,+ }+ if kind == "special" {+ response.ReadOnlyReason = workspacetypes.FileReadOnlySpecial+ return response, nil+ }+ if kind != "regular" {+ return nil, errors.New("invalid volume workspace file kind")+ }+ if size > maxFileSizeBytes {+ response.ReadOnlyReason = workspacetypes.FileReadOnlyTooLarge+ return response, nil+ }+ if !workspacepkg.IsTextContent(content) {+ response.ReadOnlyReason = workspacetypes.FileReadOnlyBinary+ return response, nil+ }+ response.Editable = true+ response.Content = string(content)+ return response, nil+}++func classifyVolumeWorkspaceExecErrorInternal(err error, stderr, fallbackContext string) error {+ message := stderr + " " + err.Error()+ switch {+ case strings.Contains(message, "ARCANE_SYMLINK"):+ return common.Classify(common.ErrVolumeWorkspaceForbidden, errors.New("symlink volume paths are not supported"))+ case strings.Contains(message, "ARCANE_NOT_FOUND"):+ return common.Classify(common.ErrVolumeWorkspaceNotFound, errors.New("volume workspace file not found"))+ case strings.Contains(message, "ARCANE_COLLISION"):+ return common.Classify(common.ErrVolumeWorkspaceBadRequest, errors.New("volume workspace destination already exists"))+ case strings.Contains(message, "ARCANE_NOT_DIRECTORY"):+ return common.Classify(common.ErrVolumeWorkspaceBadRequest, errors.New("volume workspace parent is not a directory"))+ case strings.Contains(message, "ARCANE_NOT_FILE"):+ return common.Classify(common.ErrVolumeWorkspaceBadRequest, errors.New("volume workspace path is not a regular file"))+ case strings.Contains(message, "ARCANE_NOT_EMPTY"):+ return common.Classify(common.ErrVolumeWorkspaceBadRequest, errors.New("volume directory is not empty; recursive delete is required"))+ case strings.Contains(message, "ARCANE_DIRECTORY"):+ return common.Classify(common.ErrVolumeWorkspaceBadRequest, errors.New("path is a directory"))+ default:+ return errors.WrapIf(err, fallbackContext)+ }+}++func classifyVolumeWorkspaceHelperSupportErrorInternal(err error) error {+ switch {+ case cerrdefs.IsNotFound(err):+ return common.Classify(common.ErrVolumeWorkspaceNotFound, err)+ case strings.Contains(err.Error(), "uses a custom mount configuration"):+ return common.Classify(common.ErrVolumeWorkspaceBadRequest, err)+ default:+ return err+ }+}++func (s *VolumeService) validateVolumeWorkspacePathInternal(ctx context.Context, containerID, relativePath string, allowMissing bool) error {+ allowMissingValue := "0"+ if allowMissing {+ allowMissingValue = "1"+ }+ _, stderr, err := s.execInContainerInternal(ctx, containerID, []string{"sh", "-c", volumeWorkspaceValidatePathScriptInternal, "sh", relativePath, allowMissingValue})+ if err != nil {+ return classifyVolumeWorkspaceExecErrorInternal(err, stderr, "validate volume workspace path")+ }+ return nil+}++const volumeWorkspaceValidatePathScriptInternal = `set -e+rel="$1"+allow_missing="$2"+cur=/volume+remaining=$rel+while :; do+ case "$remaining" in '') break ;; esac+ case "$remaining" in+ */*) segment=${remaining%%/*}; remaining=${remaining#*/} ;;+ *) segment=$remaining; remaining= ;;+ esac+ cur="$cur/$segment"+ if mode=$(stat -c '%A' -- "$cur" 2>/dev/null); then+ case "$mode" in l*) echo ARCANE_SYMLINK >&2; exit 42 ;; esac+ else+ case "$allow_missing" in 1) exit 0 ;; esac+ echo ARCANE_NOT_FOUND >&2+ exit 44+ fi+ case "$remaining" in+ '') ;;+ *) case "$mode" in d*) ;; *) echo ARCANE_NOT_DIRECTORY >&2; exit 47 ;; esac ;;+ esac+done`++func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName string, manifest volumetypes.WorkspaceUpdateManifest, uploads map[int][]byte, user models.User) (*workspacetypes.Workspace, error) {+ totalStartedAt := time.Now()+ defer func() {+ slog.DebugContext(ctx, "volume workspace update completed", "volume", volumeName, "file_change_count", len(manifest.FileChanges), "total_duration", time.Since(totalStartedAt))+ }()++ if err := workspacepkg.ValidateUpdateManifest(manifest.FileTreeRevision, len(manifest.FileChanges), 500); err != nil {+ return nil, common.Classify(common.ErrVolumeWorkspaceBadRequest, err)+ }+ uploadReferences := make([]workspacepkg.UploadReference, 0, len(manifest.FileChanges))+ for _, change := range manifest.FileChanges {+ uploadReferences = append(uploadReferences, workspacepkg.UploadReference{Operation: change.Operation, UploadIndex: change.UploadIndex})+ if err := validateVolumeWorkspaceFileChangeInternal(change); err != nil {+ return nil, common.Classify(common.ErrVolumeWorkspaceBadRequest, err)+ }+ }+ if err := workspacepkg.ValidateUploadIndices(uploadReferences, len(uploads), volumetypes.FileOpCreateFile, volumetypes.FileOpUpdateFile); err != nil {+ return nil, common.Classify(common.ErrVolumeWorkspaceBadRequest, err)+ }+ inspectionStartedAt := time.Now()+ if err := s.validateVolumeHelperSupportInternal(ctx, volumeName); err != nil {+ return nil, classifyVolumeWorkspaceHelperSupportErrorInternal(err)+ }+ slog.DebugContext(ctx, "volume workspace inspection completed", "volume", volumeName, "duration", time.Since(inspectionStartedAt))+ defer s.workspaceLocks.Lock(volumeName)()++ needsBackups := slices.ContainsFunc(manifest.FileChanges, func(change volumetypes.WorkspaceFileChange) bool {+ return change.Operation == volumetypes.FileOpRestoreFile+ })+ helperStartedAt := time.Now()+ containerID, cleanup, err := s.createVolumeWorkspaceMutationContainerInternal(ctx, volumeName, needsBackups)+ if err != nil {+ return nil, err+ }+ defer cleanup()+ slog.DebugContext(ctx, "volume workspace mutation helper acquired", "volume", volumeName, "container_id", containerID, "dedicated", needsBackups, "duration", time.Since(helperStartedAt))++ revisionScanStartedAt := time.Now()+ current, err := s.readVolumeWorkspaceFromContainerInternal(ctx, containerID)+ if err != nil {+ return nil, err+ }+ slog.DebugContext(ctx, "volume workspace revision tree scan completed", "volume", volumeName, "file_count", len(current.Files), "truncated", current.FileTreeTruncated, "duration", time.Since(revisionScanStartedAt))+ if err := validateVolumeWorkspaceRevisionInternal(manifest.FileTreeRevision, current.FileTreeRevision); err != nil {+ return nil, err+ }++ stagingStartedAt := time.Now()+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return nil, err+ }+ stagedFiles, err := s.stageVolumeWorkspaceChangesInternal(ctx, dockerClient, containerID, manifest.FileChanges, uploads)+ if err != nil {+ return nil, err+ }+ slog.DebugContext(ctx, "volume workspace staging completed", "volume", volumeName, "staged_file_count", len(stagedFiles), "duration", time.Since(stagingStartedAt))++ backupStartedAt := time.Now()+ scope, err := volumeWorkspaceBackupScopeInternal(manifest.FileChanges)+ if err != nil {+ return nil, common.Classify(common.ErrVolumeWorkspaceBadRequest, err)+ }+ for _, relativePath := range scope {+ if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, relativePath, true); err != nil {+ return nil, err+ }+ }+ backup, err := s.backupVolumeWorkspaceScopeInternal(ctx, containerID, scope)+ if err != nil {+ return nil, err+ }+ slog.DebugContext(ctx, "volume workspace backup completed", "volume", volumeName, "scope_count", len(scope), "duration", time.Since(backupStartedAt))++ applyStartedAt := time.Now()+ if err := applyVolumeWorkspaceChangesTransactionInternal(+ manifest.FileChanges,+ func(index int, change volumetypes.WorkspaceFileChange) error {+ return s.applyVolumeWorkspaceChangeInternal(ctx, containerID, change, stagedFiles[index], volumeName)+ },+ func() error { return s.restoreVolumeWorkspaceScopeInternal(ctx, containerID, backup) },+ ); err != nil {+ return nil, err+ }+ slog.DebugContext(ctx, "volume workspace changes applied", "volume", volumeName, "file_change_count", len(manifest.FileChanges), "duration", time.Since(applyStartedAt))++ finalScanStartedAt := time.Now()+ workspace, err := s.readVolumeWorkspaceFromContainerInternal(ctx, containerID)+ if err != nil {+ return nil, err+ }+ slog.DebugContext(ctx, "volume workspace final tree scan completed", "volume", volumeName, "file_count", len(workspace.Files), "truncated", workspace.FileTreeTruncated, "duration", time.Since(finalScanStartedAt))++ if s.eventService != nil {+ metadata := models.JSON{"action": "workspace_update", "fileChangeCount": len(manifest.FileChanges)}+ if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeWorkspaceUpdate, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {+ slog.WarnContext(ctx, "could not log volume workspace update event", "volume", volumeName, "error", logErr.Error())+ }+ }+ return workspace, nil+}++type volumeWorkspaceStagedFileInternal struct {+ path string+ size int64+}++type volumeWorkspaceStagedContentInternal struct {+ name string+ content io.ReadCloser+ size int64+}++func (s *VolumeService) stageVolumeWorkspaceChangesInternal(ctx context.Context, dockerClient *client.Client, containerID string, changes []volumetypes.WorkspaceFileChange, uploads map[int][]byte) (map[int]volumeWorkspaceStagedFileInternal, error) {+ if _, _, err := s.execInContainerInternal(ctx, containerID, []string{"sh", "-c", "rm -rf -- /tmp/arcane-workspace && mkdir -p -- /tmp/arcane-workspace"}); err != nil {+ return nil, errors.WrapIf(err, "prepare volume workspace staging directory")+ }++ stagedFiles := make(map[int]volumeWorkspaceStagedFileInternal)+ stagedContents := make([]volumeWorkspaceStagedContentInternal, 0, len(changes))+ for index, change := range changes {+ if change.UploadIndex == nil {+ continue+ }+ stagedPath := fmt.Sprintf("/tmp/arcane-workspace/change-%d", index)+ content := uploads[*change.UploadIndex]+ reader := io.NopCloser(strings.NewReader(string(content)))+ size := int64(len(content))+ stagedFiles[index] = volumeWorkspaceStagedFileInternal{path: stagedPath, size: size}+ stagedContents = append(stagedContents, volumeWorkspaceStagedContentInternal{+ name: path.Base(stagedPath),+ content: reader,+ size: size,+ })+ }+ if len(stagedContents) == 0 {+ return stagedFiles, nil+ }+ if err := s.copyVolumeWorkspaceFilesToContainerInternal(ctx, dockerClient, containerID, stagedContents); err != nil {+ return nil, err+ }+ return stagedFiles, nil+}++func validateVolumeWorkspaceRevisionInternal(expected, current string) error {+ if strings.TrimSpace(expected) != current {+ return common.Classify(common.ErrVolumeWorkspaceConflict, errors.New("volume workspace changed; refresh it and try again"))+ }+ return nil+}++func applyVolumeWorkspaceChangesTransactionInternal(+ changes []volumetypes.WorkspaceFileChange,+ apply func(int, volumetypes.WorkspaceFileChange) error,+ rollback func() error,+) error {+ for index, change := range changes {+ if err := apply(index, change); err != nil {+ if rollbackErr := rollback(); rollbackErr != nil {+ return stderrors.Join(err, errors.WrapIf(rollbackErr, "failed to roll back volume workspace"))+ }+ return err+ }+ }+ return nil+}++func validateVolumeWorkspaceFileChangeInternal(change volumetypes.WorkspaceFileChange) error {+ if _, err := utils.NormalizeRelativePath(change.RelativePath); err != nil {+ return errors.WrapIf(err, "invalid volume workspace path")+ }+ hasUpload := change.UploadIndex != nil+ switch change.Operation {+ case volumetypes.FileOpCreateFile, volumetypes.FileOpUpdateFile:+ if !hasUpload {+ return errors.New("create_file and update_file require uploadIndex")+ }+ case volumetypes.FileOpCreateFolder, volumetypes.FileOpDelete:+ if hasUpload {+ return errors.New("operation does not accept file content")+ }+ case volumetypes.FileOpRename:+ if hasUpload {+ return errors.New("rename does not accept file content")+ }+ if _, err := utils.ValidateFileName(change.NewName); err != nil {+ return errors.WrapIf(err, "invalid volume workspace file name")+ }+ case volumetypes.FileOpMove:+ if hasUpload {+ return errors.New("move does not accept file content")+ }+ if strings.TrimSpace(change.NewParentPath) != "" {+ if _, err := utils.NormalizeRelativePath(change.NewParentPath); err != nil {+ return errors.WrapIf(err, "invalid destination folder")+ }+ }+ case volumetypes.FileOpRestoreFile:+ if hasUpload {+ return errors.New("restore_file does not accept file content")+ }+ if strings.TrimSpace(change.BackupID) == "" {+ return errors.New("restore_file requires backupId")+ }+ default:+ return errors.Errorf("unsupported volume workspace operation %q", change.Operation)+ }+ return nil+}++func (s *VolumeService) copyVolumeWorkspaceFilesToContainerInternal(ctx context.Context, dockerClient *client.Client, containerID string, contents []volumeWorkspaceStagedContentInternal) error {+ pipeReader, pipeWriter := io.Pipe()+ archiveDone := make(chan error, 1)+ go func() {+ tarWriter := tar.NewWriter(pipeWriter)+ var err error+ for _, stagedContent := range contents {+ if err = tarWriter.WriteHeader(&tar.Header{Name: stagedContent.name, Mode: 0o600, Size: stagedContent.size}); err != nil {+ break+ }+ if _, err = io.CopyN(tarWriter, stagedContent.content, stagedContent.size); err != nil {+ break+ }+ }+ if closeErr := tarWriter.Close(); err == nil {+ err = closeErr+ }+ _ = pipeWriter.CloseWithError(err)+ archiveDone <- err+ }()+ _, copyErr := dockerClient.CopyToContainer(ctx, containerID, client.CopyToContainerOptions{DestinationPath: "/tmp/arcane-workspace", Content: pipeReader})+ _ = pipeReader.Close()+ archiveErr := <-archiveDone+ for _, stagedContent := range contents {+ _ = stagedContent.content.Close()+ }+ if copyErr != nil {+ return errors.WrapIf(copyErr, "stage volume workspace files")+ }+ if archiveErr != nil {+ return errors.WrapIf(archiveErr, "create volume workspace staging archive")+ }+ return nil+}++func (s *VolumeService) createVolumeWorkspaceMutationContainerInternal(ctx context.Context, volumeName string, withBackups bool) (string, func(), error) {+ if !withBackups {+ return s.acquireVolumeHelperInternal(ctx, volumeName)+ }+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return "", nil, err+ }+ helperImage, err := getVolumeHelperImageInternal(ctx, s.dockerService, s.imageService, dockerClient)+ if err != nil {+ return "", nil, err+ }+ backupStorage, err := s.resolveUsableBackupStorageMountInternal(ctx, dockerClient, "/backups", true)+ if err != nil {+ return "", nil, err+ }+ config := &container.Config{Image: helperImage, Cmd: []string{"sleep", "infinity"}, NetworkDisabled: true, Labels: volumehelper.Labels()}+ hostConfig := volumehelper.HostConfig(helperImage, []string{volumeName + ":/volume"}, []mount.Mount{backupStorage.mount})+ resp, err := dockerClient.ContainerCreate(ctx, client.ContainerCreateOptions{Config: config, HostConfig: hostConfig})+ if err != nil {+ return "", nil, errors.WrapIf(err, "create volume workspace helper")+ }+ if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {+ _, _ = dockerClient.ContainerRemove(ctx, resp.ID, volumehelper.RemoveOptions())+ return "", nil, errors.WrapIf(err, "start volume workspace helper")+ }+ return resp.ID, func() {+ _, _ = dockerClient.ContainerRemove(context.WithoutCancel(ctx), resp.ID, volumehelper.RemoveOptions())+ }, nil+}++func volumeWorkspaceBackupScopeInternal(changes []volumetypes.WorkspaceFileChange) ([]string, error) {+ paths := make([]string, 0, len(changes)*2)+ for _, change := range changes {+ rel, err := utils.NormalizeRelativePath(change.RelativePath)+ if err != nil {+ return nil, err+ }+ paths = append(paths, rel)+ switch change.Operation {+ case volumetypes.FileOpRename:+ newName, err := utils.ValidateFileName(change.NewName)+ if err != nil {+ return nil, err+ }+ paths = append(paths, path.Join(path.Dir(rel), newName))+ case volumetypes.FileOpMove:+ parent := ""+ if strings.TrimSpace(change.NewParentPath) != "" {+ parent, err = utils.NormalizeRelativePath(change.NewParentPath)+ if err != nil {+ return nil, err+ }+ }+ paths = append(paths, path.Join(parent, path.Base(rel)))+ }+ }+ return normalizeVolumeWorkspaceScopeInternal(paths), nil+}++func normalizeVolumeWorkspaceScopeInternal(paths []string) []string {+ normalized := slices.Clone(paths)+ slices.Sort(normalized)+ normalized = slices.Compact(normalized)+ result := make([]string, 0, len(normalized))+ for _, candidate := range normalized {+ if candidate == "." || candidate == "" {+ continue+ }+ if slices.ContainsFunc(result, func(parent string) bool { return utils.FilePathMatches(candidate, parent) }) {+ continue+ }+ result = append(result, candidate)+ }+ return result+}++type volumeWorkspaceBackupArchiveInternal struct {+ relativePath string+ archivePath string+}++type volumeWorkspaceBackupInternal struct {+ archives []volumeWorkspaceBackupArchiveInternal+ absentEntries []string+}++const volumeWorkspaceBackupCreateScriptInternal = `set -e+rel="$1"+archive="$2"+cur=/volume+current=+remaining=$rel+while :; do+ case "$remaining" in '') break ;; esac+ case "$remaining" in+ */*) segment=${remaining%%/*}; remaining=${remaining#*/} ;;+ *) segment=$remaining; remaining= ;;+ esac+ case "$current" in '') current=$segment ;; *) current="$current/$segment" ;; esac+ cur="$cur/$segment"+ if mode=$(stat -c '%A' -- "$cur" 2>/dev/null); then+ case "$mode" in l*) echo ARCANE_SYMLINK >&2; exit 42 ;; esac+ else+ printf 'absent\0%s\0' "$current"+ exit 0+ fi+ case "$remaining" in+ '') ;;+ *) case "$mode" in d*) ;; *) echo ARCANE_NOT_DIRECTORY >&2; exit 47 ;; esac ;;+ esac+done+case "$rel" in+ */*) parent="/volume/${rel%/*}"; entry=${rel##*/} ;;+ *) parent=/volume; entry=$rel ;;+esac+cd "$parent"+tar -cf "$archive" "./$entry"+printf 'present\0'`++func (s *VolumeService) backupVolumeWorkspaceScopeInternal(ctx context.Context, containerID string, scope []string) (*volumeWorkspaceBackupInternal, error) {+ if _, _, err := s.execInContainerInternal(ctx, containerID, []string{"mkdir", "-p", "/tmp/arcane-workspace"}); err != nil {+ return nil, errors.WrapIf(err, "prepare volume workspace backup directory")+ }+ backup := &volumeWorkspaceBackupInternal{+ archives: make([]volumeWorkspaceBackupArchiveInternal, 0, len(scope)),+ absentEntries: make([]string, 0, len(scope)),+ }+ for index, relativePath := range scope {+ archivePath := fmt.Sprintf("/tmp/arcane-workspace/backup-%d.tar", index)+ stdout, stderr, err := s.execInContainerInternal(ctx, containerID, []string{"sh", "-c", volumeWorkspaceBackupCreateScriptInternal, "sh", relativePath, archivePath})+ if err != nil {+ return nil, classifyVolumeWorkspaceExecErrorInternal(err, stderr, "back up volume workspace path")+ }+ fields := strings.Split(stdout, "\x00")+ switch {+ case len(fields) >= 1 && fields[0] == "present":+ backup.archives = append(backup.archives, volumeWorkspaceBackupArchiveInternal{+ relativePath: relativePath,+ archivePath: archivePath,+ })+ case len(fields) >= 2 && fields[0] == "absent" && fields[1] != "":+ backup.absentEntries = append(backup.absentEntries, fields[1])+ default:+ return nil, errors.New("invalid volume workspace backup path response")+ }+ }+ backup.absentEntries = normalizeVolumeWorkspaceScopeInternal(backup.absentEntries)+ return backup, nil+}++func volumeWorkspaceRollbackPathsInternal(backup *volumeWorkspaceBackupInternal) []string {+ removePaths := slices.Clone(backup.absentEntries)+ for _, archive := range backup.archives {+ removePaths = append(removePaths, archive.relativePath)+ }+ slices.SortFunc(removePaths, func(a, b string) int {+ depthA := strings.Count(a, "/")+ depthB := strings.Count(b, "/")+ if depthA != depthB {+ return depthB - depthA+ }+ return strings.Compare(b, a)+ })+ return removePaths+}++func (s *VolumeService) restoreVolumeWorkspaceScopeInternal(ctx context.Context, containerID string, backup *volumeWorkspaceBackupInternal) error {+ removePaths := volumeWorkspaceRollbackPathsInternal(backup)+ args := append([]string{"sh", "-c", `set -e+for rel do rm -rf -- "/volume/$rel"; done`, "sh"}, removePaths...)+ if _, stderr, err := s.execInContainerInternal(ctx, containerID, args); err != nil {+ return classifyVolumeWorkspaceExecErrorInternal(err, stderr, "remove failed volume workspace changes")+ }++ for _, archive := range backup.archives {+ parent := path.Dir(archive.relativePath)+ containerParent := "/volume"+ if parent != "." {+ containerParent = path.Join(containerParent, parent)+ }+ if _, stderr, err := s.execInContainerInternal(ctx, containerID, []string{"mkdir", "-p", containerParent}); err != nil {+ return classifyVolumeWorkspaceExecErrorInternal(err, stderr, "recreate volume workspace backup parent")+ }+ if _, stderr, err := s.execInContainerInternal(ctx, containerID, []string{"tar", "-xf", archive.archivePath, "-C", containerParent}); err != nil {+ return classifyVolumeWorkspaceExecErrorInternal(err, stderr, "restore volume workspace backup")+ }+ }+ return nil+}++const (+ volumeWorkspaceCreateFileScriptInternal = `set -e+target="/volume/$1"+parent=/volume+case "$2" in '') ;; *) parent="/volume/$2" ;; esac+if stat -c '%A' -- "$target" >/dev/null 2>&1; then echo ARCANE_COLLISION >&2; exit 45; fi+if parent_mode=$(stat -c '%A' -- "$parent" 2>/dev/null); then+ case "$parent_mode" in+ l*) echo ARCANE_SYMLINK >&2; exit 42 ;;+ d*) ;;+ *) echo ARCANE_NOT_DIRECTORY >&2; exit 47 ;;+ esac+fi+mkdir -p -- "$parent"+parent_mode=$(stat -c '%A' -- "$parent" 2>/dev/null) || { echo ARCANE_NOT_DIRECTORY >&2; exit 47; }+case "$parent_mode" in+ l*) echo ARCANE_SYMLINK >&2; exit 42 ;;+ d*) ;;+ *) echo ARCANE_NOT_DIRECTORY >&2; exit 47 ;;+esac+umask 022+set -C+head -c "$4" "$3" > "$target"`+ volumeWorkspaceCreateFolderScriptInternal = `set -e+target="/volume/$1"+parent=/volume+case "$2" in '') ;; *) parent="/volume/$2" ;; esac+if stat -c '%A' -- "$target" >/dev/null 2>&1; then echo ARCANE_COLLISION >&2; exit 45; fi+if parent_mode=$(stat -c '%A' -- "$parent" 2>/dev/null); then+ case "$parent_mode" in+ l*) echo ARCANE_SYMLINK >&2; exit 42 ;;+ d*) ;;+ *) echo ARCANE_NOT_DIRECTORY >&2; exit 47 ;;+ esac+fi+mkdir -p -- "$parent"+parent_mode=$(stat -c '%A' -- "$parent" 2>/dev/null) || { echo ARCANE_NOT_DIRECTORY >&2; exit 47; }+case "$parent_mode" in+ l*) echo ARCANE_SYMLINK >&2; exit 42 ;;+ d*) ;;+ *) echo ARCANE_NOT_DIRECTORY >&2; exit 47 ;;+esac+umask 022+mkdir -m 0755 -- "$target"`+ volumeWorkspaceUpdateFileScriptInternal = `set -e+target="/volume/$1"+target_mode=$(stat -c '%A' -- "$target" 2>/dev/null) || { echo ARCANE_NOT_FOUND >&2; exit 44; }+case "$target_mode" in+ l*) echo ARCANE_SYMLINK >&2; exit 42 ;;+ -*) ;;+ *) echo ARCANE_NOT_FILE >&2; exit 46 ;;+esac+head -c "$3" "$2" > "$target"`+ volumeWorkspaceRenameScriptInternal = `set -e+source="/volume/$1"+target="/volume/$2"+if stat -c '%A' -- "$target" >/dev/null 2>&1; then echo ARCANE_COLLISION >&2; exit 45; fi+mv -- "$source" "$target"`+ volumeWorkspaceMoveScriptInternal = `set -e+source="/volume/$1"+parent="/volume/$2"+target="/volume/$3"+parent_mode=$(stat -c '%A' -- "$parent" 2>/dev/null) || { echo ARCANE_NOT_DIRECTORY >&2; exit 47; }+case "$parent_mode" in d*) ;; *) echo ARCANE_NOT_DIRECTORY >&2; exit 47 ;; esac+if stat -c '%A' -- "$target" >/dev/null 2>&1; then echo ARCANE_COLLISION >&2; exit 45; fi+mv -- "$source" "$target"`+ volumeWorkspaceDeleteScriptInternal = `set -e+target="/volume/$1"+case "$2" in+ 1) rm -rf -- "$target" ;;+ *)+ target_mode=$(stat -c '%A' -- "$target" 2>/dev/null) || { echo ARCANE_NOT_FOUND >&2; exit 44; }+ case "$target_mode" in+ d*) if ! rmdir -- "$target"; then echo ARCANE_NOT_EMPTY >&2; exit 48; fi ;;+ *) rm -- "$target" ;;+ esac+ ;;+esac`+)++func (s *VolumeService) applyVolumeWorkspaceChangeInternal(ctx context.Context, containerID string, change volumetypes.WorkspaceFileChange, stagedFile volumeWorkspaceStagedFileInternal, volumeName string) error {+ rel, _ := utils.NormalizeRelativePath(change.RelativePath)+ if change.Operation == volumetypes.FileOpRestoreFile {+ return s.restoreVolumeWorkspaceFileInternal(ctx, containerID, volumeName, change.BackupID, rel)+ }+ cmd, err := s.volumeWorkspaceMutationCommandInternal(ctx, containerID, change, stagedFile, rel)+ if err != nil {+ return err+ }+ _, stderr, err := s.execInContainerInternal(ctx, containerID, cmd)+ if err != nil {+ return classifyVolumeWorkspaceExecErrorInternal(err, stderr, "apply volume workspace change")+ }+ if strings.TrimSpace(stderr) != "" {+ slog.DebugContext(ctx, "volume workspace change stderr", "operation", change.Operation, "path", rel, "stderr", strings.TrimSpace(stderr))+ }+ return nil+}++func (s *VolumeService) volumeWorkspaceMutationCommandInternal(ctx context.Context, containerID string, change volumetypes.WorkspaceFileChange, stagedFile volumeWorkspaceStagedFileInternal, rel string) ([]string, error) {+ var cmd []string+ parent := path.Dir(rel)+ if parent == "." {+ parent = ""+ }+ switch change.Operation {+ case volumetypes.FileOpCreateFile:+ if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, rel, true); err != nil {+ return nil, err+ }+ cmd = []string{"sh", "-c", volumeWorkspaceCreateFileScriptInternal, "sh", rel, parent, stagedFile.path, strconv.FormatInt(stagedFile.size, 10)}+ case volumetypes.FileOpCreateFolder:+ if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, rel, true); err != nil {+ return nil, err+ }+ cmd = []string{"sh", "-c", volumeWorkspaceCreateFolderScriptInternal, "sh", rel, parent}+ case volumetypes.FileOpUpdateFile:+ if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, rel, false); err != nil {+ return nil, err+ }+ cmd = []string{"sh", "-c", volumeWorkspaceUpdateFileScriptInternal, "sh", rel, stagedFile.path, strconv.FormatInt(stagedFile.size, 10)}+ case volumetypes.FileOpRename:+ newName, _ := utils.ValidateFileName(change.NewName)+ target := path.Join(path.Dir(rel), newName)+ if target == rel {+ return nil, common.Classify(common.ErrVolumeWorkspaceBadRequest, errors.New("new name must change the file path"))+ }+ if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, rel, false); err != nil {+ return nil, err+ }+ if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, target, true); err != nil {+ return nil, err+ }+ cmd = []string{"sh", "-c", volumeWorkspaceRenameScriptInternal, "sh", rel, target}+ case volumetypes.FileOpMove:+ parent = ""+ if strings.TrimSpace(change.NewParentPath) != "" {+ parent, _ = utils.NormalizeRelativePath(change.NewParentPath)+ }+ target := path.Join(parent, path.Base(rel))+ if target == rel || (parent != "" && utils.FilePathMatches(parent, rel)) {+ return nil, common.Classify(common.ErrVolumeWorkspaceBadRequest, errors.New("invalid move destination"))+ }+ if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, rel, false); err != nil {+ return nil, err+ }+ if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, target, true); err != nil {+ return nil, err+ }+ cmd = []string{"sh", "-c", volumeWorkspaceMoveScriptInternal, "sh", rel, parent, target}+ case volumetypes.FileOpDelete:+ if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, rel, false); err != nil {+ return nil, err+ }+ recursive := "0"+ if change.Recursive {+ recursive = "1"+ }+ cmd = []string{"sh", "-c", volumeWorkspaceDeleteScriptInternal, "sh", rel, recursive}+ }+ return cmd, nil+}++func (s *VolumeService) restoreVolumeWorkspaceFileInternal(ctx context.Context, containerID, volumeName, backupID, rel string) error {+ if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, rel, true); err != nil {+ return err+ }+ filename, err := s.backupArchiveFilenameInternal(backupID)+ if err != nil {+ return common.Classify(common.ErrVolumeWorkspaceNotFound, err)+ }+ var backup models.VolumeBackup+ if err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&backup).Error; err != nil {+ return common.Classify(common.ErrVolumeWorkspaceNotFound, err)+ }+ if backup.VolumeName != volumeName {+ return common.Classify(common.ErrVolumeWorkspaceForbidden, errors.New("backup does not belong to volume"))+ }+ cleaned, err := s.sanitizeBackupPathInternal(rel)+ if err != nil {+ return common.Classify(common.ErrVolumeWorkspaceBadRequest, err)+ }+ stderr, err := s.restoreBackupFilesInContainerInternal(ctx, containerID, filename, []string{cleaned})+ if err != nil {+ return classifyVolumeWorkspaceExecErrorInternal(err, stderr, "restore volume workspace file")+ }+ if strings.TrimSpace(stderr) != "" {+ slog.DebugContext(ctx, "volume workspace change stderr", "operation", volumetypes.FileOpRestoreFile, "path", rel, "stderr", strings.TrimSpace(stderr))+ }+ return nil+}diff --git a/backend/internal/volume/workspace_handler.go b/backend/internal/volume/workspace_handler.gonew file mode 100644index 000000000..a2aa826aa--- /dev/null+++ b/backend/internal/volume/workspace_handler.go@@ -0,0 +1,163 @@+package volume++import (+ "context"+ "io"+ "mime/multipart"+ "net/http"+ "path"+ "strconv"+ "strings"++ "emperror.dev/errors"+ "github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace"+ "github.com/getarcaneapp/arcane/types/v2/base"+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"+ workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"+ "github.com/samber/mo"+)++type GetVolumeWorkspaceInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ VolumeName string `path:"volumeName" doc:"Volume name"`+}++type GetVolumeWorkspaceOutput struct {+ Body base.ApiResponse[workspacetypes.Workspace]+}++type GetVolumeWorkspaceFileInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ VolumeName string `path:"volumeName" doc:"Volume name"`+ RelativePath string `query:"relativePath" doc:"Path relative to the volume workspace root"`+}++type GetVolumeWorkspaceFileOutput struct {+ Body base.ApiResponse[workspacetypes.FileContent]+}++type UpdateVolumeWorkspaceInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ VolumeName string `path:"volumeName" doc:"Volume name"`+ RawBody multipart.Form `contentType:"multipart/form-data"`+}++type UpdateVolumeWorkspaceOutput struct {+ Body base.ApiResponse[workspacetypes.Workspace]+}++func registerVolumeWorkspaceRoutesInternal(api huma.API, h *VolumeHandler) {+ basePath := "/environments/{id}/volumes/{volumeName}/workspace"+ tag := "Volume Workspace"+ handlerutil.RegisterSecured(api, handlerutil.Operation("get-volume-workspace", http.MethodGet, basePath, "Get volume workspace", "", tag), authz.PermVolumesRead, h.GetVolumeWorkspace)+ handlerutil.RegisterSecured(api, handlerutil.Operation("get-volume-workspace-file", http.MethodGet, basePath+"/file", "Get volume workspace file", "", tag), authz.PermVolumesRead, h.GetVolumeWorkspaceFile)+ handlerutil.RegisterSecured(api, handlerutil.Operation("download-volume-workspace-file", http.MethodGet, basePath+"/file/download", "Download volume workspace file", "", tag), authz.PermVolumesRead, h.DownloadVolumeWorkspaceFile)+ updateOperation := handlerutil.Operation("update-volume-workspace", http.MethodPut, basePath, "Update volume workspace", "", tag)+ updateOperation.RequestBody = handlerutil.WorkspaceMultipartRequestBody("JSON encoded volume workspace manifest")+ handlerutil.RegisterSecured(api, updateOperation, authz.PermVolumesRead, h.UpdateVolumeWorkspace)+}++func volumeWorkspaceHTTPErrorInternal(err error) error {+ switch {+ case errors.Is(err, common.ErrVolumeWorkspaceConflict):+ return huma.Error409Conflict(err.Error())+ case errors.Is(err, common.ErrVolumeWorkspaceForbidden):+ return huma.Error403Forbidden(err.Error())+ case errors.Is(err, common.ErrVolumeWorkspaceNotFound):+ return huma.Error404NotFound(err.Error())+ case errors.Is(err, common.ErrVolumeWorkspaceBadRequest):+ return huma.Error400BadRequest(err.Error())+ default:+ return huma.Error500InternalServerError("internal error")+ }+}++func (h *VolumeHandler) GetVolumeWorkspace(ctx context.Context, input *GetVolumeWorkspaceInput) (*GetVolumeWorkspaceOutput, error) {+ result, err := h.volumeService.GetVolumeWorkspace(ctx, input.VolumeName)+ if err != nil {+ return nil, volumeWorkspaceHTTPErrorInternal(err)+ }+ return &GetVolumeWorkspaceOutput{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil+}++func (h *VolumeHandler) GetVolumeWorkspaceFile(ctx context.Context, input *GetVolumeWorkspaceFileInput) (*GetVolumeWorkspaceFileOutput, error) {+ result, err := h.volumeService.GetVolumeWorkspaceFile(ctx, input.VolumeName, input.RelativePath)+ if err != nil {+ return nil, volumeWorkspaceHTTPErrorInternal(err)+ }+ return &GetVolumeWorkspaceFileOutput{Body: base.ApiResponse[workspacetypes.FileContent]{Success: true, Data: *result}}, nil+}++func (h *VolumeHandler) DownloadVolumeWorkspaceFile(ctx context.Context, input *GetVolumeWorkspaceFileInput) (*huma.StreamResponse, error) {+ reader, size, err := h.volumeService.DownloadVolumeWorkspaceFile(ctx, input.VolumeName, input.RelativePath)+ if err != nil {+ return nil, volumeWorkspaceHTTPErrorInternal(err)+ }+ return &huma.StreamResponse{Body: func(humaCtx huma.Context) {+ defer func() { _ = reader.Close() }()+ humaCtx.SetHeader("Content-Type", "application/octet-stream")+ humaCtx.SetHeader("Content-Disposition", "attachment; filename="+path.Base(input.RelativePath))+ humaCtx.SetHeader("Content-Length", strconv.FormatInt(size, 10))+ _, _ = io.Copy(humaCtx.BodyWriter(), reader)+ }}, nil+}++func requireVolumeWorkspacePermissionsInternal(ctx context.Context, environmentID string, changes []volumetypes.WorkspaceFileChange) error {+ permissions, ok := middleware.PermissionsFromContext(ctx)+ if !ok || permissions == nil {+ return huma.Error403Forbidden("insufficient permissions")+ }+ required, _ := authz.VolumeWorkspaceRequiredPermissions(changes)+ for _, permission := range required {+ if !permissions.Allows(permission, environmentID) {+ return huma.Error403Forbidden("insufficient permissions for volume workspace operation")+ }+ }+ return nil+}++func (h *VolumeHandler) UpdateVolumeWorkspace(ctx context.Context, input *UpdateVolumeWorkspaceInput) (*UpdateVolumeWorkspaceOutput, error) {+ manifest, err := handlerutil.ParseMultipartJSONPart[volumetypes.WorkspaceUpdateManifest](input.RawBody, "manifest")+ if err != nil {+ return nil, err+ }+ if err := requireVolumeWorkspacePermissionsInternal(ctx, input.EnvironmentID, manifest.FileChanges); err != nil {+ return nil, err+ }+ maxFileSizeBytes := workspacepkg.MaxFileSizeBytes(workspacepkg.DefaultMaxFileSizeMB)+ if h.volumeService != nil && h.volumeService.workspaceMaxFileSizeBytes > 0 {+ maxFileSizeBytes = h.volumeService.workspaceMaxFileSizeBytes+ }+ uploads, err := handlerutil.ReadWorkspaceUploads(input.RawBody, maxFileSizeBytes)+ if err != nil {+ return nil, err+ }+ user, err := handlerutil.RequireUser(ctx)+ if err != nil {+ return nil, err+ }+ var result *workspacetypes.Workspace+ runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)+ activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{+ EnvironmentID: input.EnvironmentID, Type: models.ActivityTypeResourceAction, ResourceType: "volume", ResourceID: input.VolumeName, ResourceName: input.VolumeName, User: user,+ Step: "Updating volume workspace", Message: "Updating volume workspace", SuccessMessage: "Volume workspace updated successfully",+ Metadata: models.JSON{"action": "update_volume_workspace", "fileChangeCount": len(manifest.FileChanges)},+ }, func(runtimeCtx context.Context) error {+ var updateErr error+ result, updateErr = h.volumeService.UpdateVolumeWorkspace(runtimeCtx, input.VolumeName, manifest, uploads, *user)+ return updateErr+ })+ if err != nil {+ return nil, volumeWorkspaceHTTPErrorInternal(err)+ }+ result.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()+ return &UpdateVolumeWorkspaceOutput{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil+}diff --git a/backend/internal/volume/workspace_handler_test.go b/backend/internal/volume/workspace_handler_test.gonew file mode 100644index 000000000..e5781aaa1--- /dev/null+++ b/backend/internal/volume/workspace_handler_test.go@@ -0,0 +1,85 @@+package volume++import (+ "context"+ "mime/multipart"+ "net/http"+ "testing"++ "github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func volumeWorkspacePermissionContextInternal(environmentID string, permissions ...string) context.Context {+ permissionSet := authz.NewPermissionSet()+ permissionSet.AddEnv(environmentID, permissions...)+ return context.WithValue(context.Background(), middleware.ContextKeyUserPermissions, permissionSet)+}++func TestUploadAndRestoreReturnsBadRequestWhenNoFileProvided(t *testing.T) {+ h := &VolumeHandler{volumeService: &VolumeService{}}++ ctx := context.WithValue(context.Background(), models.CurrentUserContextKey{}, &models.User{BaseModel: models.BaseModel{ID: "u-1"}})++ _, err := h.UploadAndRestore(ctx, &UploadAndRestoreInput{+ EnvironmentID: "0",+ VolumeName: "vol-1",+ RawBody: multipart.Form{},+ })++ require.Error(t, err)++ var statusErr huma.StatusError+ require.ErrorAs(t, err, &statusErr)+ assert.Equal(t, http.StatusBadRequest, statusErr.GetStatus())+}++func TestParseVolumeWorkspaceManifestInternal(t *testing.T) {+ _, err := handlerutil.ParseMultipartJSONPart[volumetypes.WorkspaceUpdateManifest](multipart.Form{}, "manifest")+ require.Error(t, err)+ _, err = handlerutil.ParseMultipartJSONPart[volumetypes.WorkspaceUpdateManifest](multipart.Form{Value: map[string][]string{"manifest": {"{"}}}, "manifest")+ require.Error(t, err)+ _, err = handlerutil.ParseMultipartJSONPart[volumetypes.WorkspaceUpdateManifest](multipart.Form{Value: map[string][]string{"manifest": {"{}", "{}"}}}, "manifest")+ require.Error(t, err)++ manifest, err := handlerutil.ParseMultipartJSONPart[volumetypes.WorkspaceUpdateManifest](multipart.Form{Value: map[string][]string{+ "manifest": {`{"fileTreeRevision":"revision","fileChanges":[{"operation":"delete","relativePath":"old.txt"}]}`},+ }}, "manifest")+ require.NoError(t, err)+ require.Equal(t, "revision", manifest.FileTreeRevision)+ require.Equal(t, volumetypes.FileOpDelete, manifest.FileChanges[0].Operation)+}++func TestRequireVolumeWorkspacePermissionsInternal(t *testing.T) {+ const environmentID = "env-1"+ create := []volumetypes.WorkspaceFileChange{{Operation: volumetypes.FileOpCreateFile}}+ rename := []volumetypes.WorkspaceFileChange{{Operation: volumetypes.FileOpRename}}+ remove := []volumetypes.WorkspaceFileChange{{Operation: volumetypes.FileOpDelete}}+ restore := []volumetypes.WorkspaceFileChange{{Operation: volumetypes.FileOpRestoreFile}}++ require.Error(t, requireVolumeWorkspacePermissionsInternal(context.Background(), environmentID, create))+ require.NoError(t, requireVolumeWorkspacePermissionsInternal(+ volumeWorkspacePermissionContextInternal(environmentID, authz.PermVolumesUpload), environmentID, create,+ ))+ require.Error(t, requireVolumeWorkspacePermissionsInternal(+ volumeWorkspacePermissionContextInternal(environmentID, authz.PermVolumesUpload), environmentID, rename,+ ))+ require.NoError(t, requireVolumeWorkspacePermissionsInternal(+ volumeWorkspacePermissionContextInternal(environmentID, authz.PermVolumesUpload, authz.PermVolumesDelete), environmentID, rename,+ ))+ require.NoError(t, requireVolumeWorkspacePermissionsInternal(+ volumeWorkspacePermissionContextInternal(environmentID, authz.PermVolumesDelete), environmentID, remove,+ ))+ require.NoError(t, requireVolumeWorkspacePermissionsInternal(+ volumeWorkspacePermissionContextInternal(environmentID, authz.PermVolumesBackup), environmentID, restore,+ ))+ require.Error(t, requireVolumeWorkspacePermissionsInternal(+ volumeWorkspacePermissionContextInternal("env-2", authz.PermVolumesUpload), environmentID, create,+ ))+}diff --git a/backend/internal/volume/workspace_test.go b/backend/internal/volume/workspace_test.gonew file mode 100644index 000000000..d19997f2a--- /dev/null+++ b/backend/internal/volume/workspace_test.go@@ -0,0 +1,824 @@+package volume++import (+ "archive/tar"+ "context"+ "encoding/base64"+ "encoding/binary"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "strconv"+ "strings"+ "testing"+ "time"++ cerrdefs "github.com/containerd/errdefs"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/docker"+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper"+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"+ workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"+ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/api/types/volume"+ "github.com/moby/moby/client"+ "github.com/stretchr/testify/require"+)++func newVolumeWorkspaceTestDockerClientInternal(t *testing.T, server *httptest.Server) *client.Client {+ t.Helper()+ dialer := &net.Dialer{}+ dockerClient, err := client.New(+ client.WithHost(server.URL),+ client.WithAPIVersion("1.41"),+ client.WithHTTPClient(server.Client()),+ client.WithDialContext(func(ctx context.Context, _, _ string) (net.Conn, error) {+ return dialer.DialContext(ctx, "tcp", server.Listener.Addr().String())+ }),+ )+ require.NoError(t, err)+ t.Cleanup(func() { _ = dockerClient.Close() })+ return dockerClient+}++func writeDockerExecAttachResponseInternal(t *testing.T, w http.ResponseWriter, stdout string) {+ t.Helper()+ hijacker, ok := w.(http.Hijacker)+ if !ok {+ t.Error("Docker exec response does not support hijacking")+ return+ }+ connection, buffer, err := hijacker.Hijack()+ if err != nil {+ t.Errorf("hijack Docker exec response: %v", err)+ return+ }+ defer connection.Close()+ if _, err := fmt.Fprint(buffer, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n"); err != nil {+ t.Errorf("write Docker exec response headers: %v", err)+ return+ }+ if stdout != "" {+ header := make([]byte, 8)+ header[0] = 1+ binary.BigEndian.PutUint32(header[4:], uint32(len(stdout)))+ if _, err := buffer.Write(header); err != nil {+ t.Errorf("write Docker exec stream header: %v", err)+ return+ }+ if _, err := buffer.WriteString(stdout); err != nil {+ t.Errorf("write Docker exec stream: %v", err)+ return+ }+ }+ if err := buffer.Flush(); err != nil {+ t.Errorf("flush Docker exec response: %v", err)+ }+}++func TestUpdateVolumeWorkspaceValidationFailureReturnsNoWorkspace(t *testing.T) {+ workspace, err := (&VolumeService{}).UpdateVolumeWorkspace(+ context.Background(),+ "volume",+ volumetypes.WorkspaceUpdateManifest{},+ nil,+ models.User{},+ )++ require.Nil(t, workspace)+ require.ErrorIs(t, err, common.ErrVolumeWorkspaceBadRequest)+}++func TestVolumeWorkspaceReadsWaitForMutationLock(t *testing.T) {+ testCases := map[string]func(context.Context, *VolumeService) error{+ "tree": func(ctx context.Context, service *VolumeService) error {+ _, err := service.GetVolumeWorkspace(ctx, "workspace-volume")+ return err+ },+ "file": func(ctx context.Context, service *VolumeService) error {+ _, err := service.GetVolumeWorkspaceFile(ctx, "workspace-volume", "file.txt")+ return err+ },+ "download": func(ctx context.Context, service *VolumeService) error {+ _, _, err := service.DownloadVolumeWorkspaceFile(ctx, "workspace-volume", "file.txt")+ return err+ },+ }++ for name, read := range testCases {+ t.Run(name, func(t *testing.T) {+ requestStarted := make(chan struct{}, 1)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ requestStarted <- struct{}{}+ http.Error(w, "stop after lock acquisition", http.StatusInternalServerError)+ }))+ t.Cleanup(server.Close)++ service := &VolumeService{+ dockerService: docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newVolumeWorkspaceTestDockerClientInternal(t, server)),+ }+ unlockMutation := service.workspaceLocks.Lock("workspace-volume")+ readStarted := make(chan struct{})+ readDone := make(chan error, 1)+ go func() {+ close(readStarted)+ readDone <- read(context.Background(), service)+ }()+ <-readStarted++ require.Never(t, func() bool {+ select {+ case <-requestStarted:+ return true+ default:+ return false+ }+ }, 50*time.Millisecond, time.Millisecond, "workspace read reached Docker while a mutation held the volume lock")++ unlockMutation()+ require.Eventually(t, func() bool {+ select {+ case <-requestStarted:+ return true+ default:+ return false+ }+ }, time.Second, time.Millisecond)+ require.Error(t, <-readDone)+ })+ }+}++func TestDownloadVolumeWorkspaceFileHoldsReadLockUntilClosed(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/workspace-volume"):+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(volume.Volume{Name: "workspace-volume", Driver: "local"})+ case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/helper/json"):+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "Id": "helper",+ "State": map[string]any{"Running": true},+ })+ case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/helper/archive"):+ w.Header().Set("Content-Type", "application/x-tar")+ content := []byte("content")+ stat, err := json.Marshal(container.PathStat{Name: "file.txt", Size: int64(len(content)), Mode: 0o600})+ if err != nil {+ t.Errorf("marshal download path stat: %v", err)+ return+ }+ w.Header().Set("X-Docker-Container-Path-Stat", base64.StdEncoding.EncodeToString(stat))+ tarWriter := tar.NewWriter(w)+ if err := tarWriter.WriteHeader(&tar.Header{Name: "file.txt", Mode: 0o600, Size: int64(len(content))}); err != nil {+ t.Errorf("write download header: %v", err)+ return+ }+ if _, err := tarWriter.Write(content); err != nil {+ t.Errorf("write download content: %v", err)+ return+ }+ if err := tarWriter.Close(); err != nil {+ t.Errorf("close download archive: %v", err)+ }+ default:+ http.Error(w, "unexpected Docker request: "+r.Method+" "+r.URL.Path, http.StatusInternalServerError)+ }+ }))+ t.Cleanup(server.Close)++ service := &VolumeService{+ dockerService: docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newVolumeWorkspaceTestDockerClientInternal(t, server)),+ helperByVolume: map[string]*volumeHelper{+ "workspace-volume": {id: "helper", lastUsedAt: time.Now()},+ },+ }+ reader, size, err := service.DownloadVolumeWorkspaceFile(context.Background(), "workspace-volume", "file.txt")+ require.NoError(t, err)+ require.EqualValues(t, 7, size)++ _, acquired := service.workspaceLocks.TryLock("workspace-volume")+ require.False(t, acquired, "mutation lock acquired before download stream closed")+ content, err := io.ReadAll(reader)+ require.NoError(t, err)+ require.Equal(t, "content", string(content))+ require.NoError(t, reader.Close())++ unlockMutation, acquired := service.workspaceLocks.TryLock("workspace-volume")+ require.True(t, acquired, "mutation lock remained held after download stream closed")+ unlockMutation()+}++func volumeWorkspaceTreeRecordInternal(relativePath, kind, size, modTime, mode, linkTarget string) string {+ return strings.Join([]string{relativePath, kind, size, modTime, mode, linkTarget}, "\x00") + "\x00"+}++func volumeWorkspaceTreeOutputInternal(truncated bool, records string) string {+ marker := "0"+ if truncated {+ marker = "1"+ }+ return records + "ARCANE_TREE_END\x00" + marker + "\x00"+}++func TestParseVolumeWorkspaceTreeInternalSortsAndClassifiesFromMode(t *testing.T) {+ stdout := volumeWorkspaceTreeOutputInternal(false,+ volumeWorkspaceTreeRecordInternal("z.txt", "d", "4", "1700000000.25", "-rw-r--r--", "")++ volumeWorkspaceTreeRecordInternal("folder/link", "f", "7", "1700000001.5", "lrwxrwxrwx", "../z.txt")++ volumeWorkspaceTreeRecordInternal("folder/child.txt", "d", "5", "1700000001.75", "-rw-r--r--", "")++ volumeWorkspaceTreeRecordInternal("folder", "f", "4096", "1700000002", "drwxr-xr-x", "")++ volumeWorkspaceTreeRecordInternal("empty", "f", "4096", "1700000003", "drwx------", "")++ volumeWorkspaceTreeRecordInternal("special", "f", "0", "1700000004", "prw-------", ""))++ workspace, err := parseVolumeWorkspaceTreeInternal(stdout, 10)+ require.NoError(t, err)+ require.False(t, workspace.FileTreeTruncated)+ require.Equal(t, []string{"empty", "folder", "folder/child.txt", "folder/link", "special", "z.txt"}, []string{+ workspace.Files[0].RelativePath,+ workspace.Files[1].RelativePath,+ workspace.Files[2].RelativePath,+ workspace.Files[3].RelativePath,+ workspace.Files[4].RelativePath,+ workspace.Files[5].RelativePath,+ })+ require.Zero(t, workspace.Files[0].Size)+ require.Zero(t, workspace.Files[1].Size)+ require.True(t, workspace.Files[0].IsDirectory)+ require.True(t, workspace.Files[1].IsDirectory)+ require.False(t, workspace.Files[2].IsDirectory)+ require.False(t, workspace.Files[3].IsDirectory)+ require.False(t, workspace.Files[4].IsDirectory)+ require.False(t, workspace.Files[5].IsDirectory)+ require.True(t, workspace.Files[3].IsSymlink)+ require.Equal(t, "../z.txt", workspace.Files[3].LinkTarget)+ require.NotEmpty(t, workspace.FileTreeRevision)++ reordered, err := parseVolumeWorkspaceTreeInternal(volumeWorkspaceTreeOutputInternal(false,+ volumeWorkspaceTreeRecordInternal("empty", "d", "4096", "1700000003", "drwx------", "")++ volumeWorkspaceTreeRecordInternal("folder", "d", "4096", "1700000002", "drwxr-xr-x", "")++ volumeWorkspaceTreeRecordInternal("folder/child.txt", "f", "5", "1700000001.75", "-rw-r--r--", "")++ volumeWorkspaceTreeRecordInternal("z.txt", "f", "4", "1700000000.25", "-rw-r--r--", "")++ volumeWorkspaceTreeRecordInternal("special", "s", "0", "1700000004", "prw-------", "")++ volumeWorkspaceTreeRecordInternal("folder/link", "l", "7", "1700000001.5", "lrwxrwxrwx", "../z.txt")), 10)+ require.NoError(t, err)+ require.Equal(t, workspace.FileTreeRevision, reordered.FileTreeRevision)+}++func TestParseVolumeWorkspaceTreeInternalFallsBackToKindWithoutMode(t *testing.T) {+ workspace, err := parseVolumeWorkspaceTreeInternal(volumeWorkspaceTreeOutputInternal(false,+ volumeWorkspaceTreeRecordInternal("folder", "d", "4096", "1", "", "")++ volumeWorkspaceTreeRecordInternal("link", "l", "3", "2", "", "folder")++ volumeWorkspaceTreeRecordInternal("regular", "f", "4", "3", "", "")), 10)+ require.NoError(t, err)+ require.True(t, workspace.Files[0].IsDirectory)+ require.Zero(t, workspace.Files[0].Size)+ require.True(t, workspace.Files[1].IsSymlink)++ special, err := parseVolumeWorkspaceTreeInternal(volumeWorkspaceTreeOutputInternal(false,+ volumeWorkspaceTreeRecordInternal("folder", "d", "4096", "1", "", "")++ volumeWorkspaceTreeRecordInternal("link", "l", "3", "2", "", "folder")++ volumeWorkspaceTreeRecordInternal("regular", "s", "4", "3", "", "")), 10)+ require.NoError(t, err)+ require.NotEqual(t, workspace.FileTreeRevision, special.FileTreeRevision)+}++func TestParseVolumeWorkspaceTreeInternalReportsBothLimits(t *testing.T) {+ entries := volumeWorkspaceTreeRecordInternal("b", "f", "1", "1", "-rw-r--r--", "") ++ volumeWorkspaceTreeRecordInternal("a", "f", "1", "1", "-rw-r--r--", "")++ depthLimited, err := parseVolumeWorkspaceTreeInternal(volumeWorkspaceTreeOutputInternal(true, entries), 10)+ require.NoError(t, err)+ require.True(t, depthLimited.FileTreeTruncated)++ entryLimited, err := parseVolumeWorkspaceTreeInternal(volumeWorkspaceTreeOutputInternal(false, entries), 1)+ require.NoError(t, err)+ require.True(t, entryLimited.FileTreeTruncated)+ require.Len(t, entryLimited.Files, 1)+ require.Equal(t, "a", entryLimited.Files[0].RelativePath)++ _, err = parseVolumeWorkspaceTreeInternal(entries+"invalid\x000\x00", 10)+ require.Error(t, err)+}++func TestParseVolumeWorkspaceModTimeInternalPreservesNanoseconds(t *testing.T) {+ modTime, err := parseVolumeWorkspaceModTimeInternal("2026-08-02 16:09:00.123456789 +0000")+ require.NoError(t, err)+ require.Equal(t, 123456789, modTime.Nanosecond())+}++func TestParseVolumeWorkspaceTreeInternalPreservesUnusualNamesAndSpecialFiles(t *testing.T) {+ workspace, err := parseVolumeWorkspaceTreeInternal(volumeWorkspaceTreeOutputInternal(false,+ volumeWorkspaceTreeRecordInternal(".hidden", "f", "1", "1", "-rw-r--r--", "")++ volumeWorkspaceTreeRecordInternal("line\nbreak", "s", "0", "2", "prw-------", "")), 10)+ require.NoError(t, err)+ require.Equal(t, []string{".hidden", "line\nbreak"}, []string{+ workspace.Files[0].RelativePath,+ workspace.Files[1].RelativePath,+ })+ require.NotEmpty(t, workspace.FileTreeRevision)+}++func TestVolumeWorkspaceFileContentResponseInternal(t *testing.T) {+ const maxFileSizeBytes int64 = 10 * 1024 * 1024+ text := []byte("hello")+ below, err := volumeWorkspaceFileContentResponseInternal("notes.txt", "regular", maxFileSizeBytes-1, text, maxFileSizeBytes)+ require.NoError(t, err)+ require.True(t, below.Editable)+ require.Equal(t, "hello", below.Content)++ atLimit, err := volumeWorkspaceFileContentResponseInternal("notes.txt", "regular", maxFileSizeBytes, text, maxFileSizeBytes)+ require.NoError(t, err)+ require.True(t, atLimit.Editable)++ above, err := volumeWorkspaceFileContentResponseInternal("notes.txt", "regular", maxFileSizeBytes+1, text, maxFileSizeBytes)+ require.NoError(t, err)+ require.False(t, above.Editable)+ require.Equal(t, workspacetypes.FileReadOnlyTooLarge, above.ReadOnlyReason)++ binary, err := volumeWorkspaceFileContentResponseInternal("data.bin", "regular", 2, []byte{0xff, 0x00}, maxFileSizeBytes)+ require.NoError(t, err)+ require.Equal(t, workspacetypes.FileReadOnlyBinary, binary.ReadOnlyReason)++ special, err := volumeWorkspaceFileContentResponseInternal("pipe", "special", 0, nil, maxFileSizeBytes)+ require.NoError(t, err)+ require.Equal(t, workspacetypes.FileReadOnlySpecial, special.ReadOnlyReason)+}++func TestValidateVolumeWorkspaceFileChangeInternalOperationsAndMultipartMapping(t *testing.T) {+ first := 0+ second := 1+ tests := []volumetypes.WorkspaceFileChange{+ {Operation: volumetypes.FileOpCreateFile, RelativePath: "empty.txt", UploadIndex: &first},+ {Operation: volumetypes.FileOpUpdateFile, RelativePath: "first.bin", UploadIndex: &first},+ {Operation: volumetypes.FileOpCreateFile, RelativePath: "second.bin", UploadIndex: &second},+ {Operation: volumetypes.FileOpCreateFolder, RelativePath: "folder"},+ {Operation: volumetypes.FileOpRename, RelativePath: "old.txt", NewName: "new.txt"},+ {Operation: volumetypes.FileOpMove, RelativePath: "new.txt", NewParentPath: "folder"},+ {Operation: volumetypes.FileOpDelete, RelativePath: "folder", Recursive: true},+ {Operation: volumetypes.FileOpRestoreFile, RelativePath: "restored.txt", BackupID: "backup-id"},+ }+ for _, change := range tests {+ require.NoError(t, validateVolumeWorkspaceFileChangeInternal(change), change.Operation)+ }++ require.Error(t, validateVolumeWorkspaceFileChangeInternal(volumetypes.WorkspaceFileChange{+ Operation: volumetypes.FileOpUpdateFile, RelativePath: "missing.bin",+ }))+ require.Error(t, validateVolumeWorkspaceFileChangeInternal(volumetypes.WorkspaceFileChange{+ Operation: volumetypes.FileOpRestoreFile, RelativePath: "file.txt",+ }))+ require.Error(t, validateVolumeWorkspaceFileChangeInternal(volumetypes.WorkspaceFileChange{+ Operation: "unknown", RelativePath: "file.txt",+ }))+ require.Error(t, validateVolumeWorkspaceFileChangeInternal(volumetypes.WorkspaceFileChange{+ Operation: volumetypes.FileOpDelete, RelativePath: "../escape",+ }))+}++func TestVolumeWorkspaceBackupScopeInternalCoversSourcesAndDestinations(t *testing.T) {+ changes := []volumetypes.WorkspaceFileChange{+ {Operation: volumetypes.FileOpRename, RelativePath: "docs/a.txt", NewName: "b.txt"},+ {Operation: volumetypes.FileOpMove, RelativePath: "cache", NewParentPath: "docs"},+ {Operation: volumetypes.FileOpCreateFile, RelativePath: "docs/a.txt/child", UploadIndex: new(0)},+ }+ scope, err := volumeWorkspaceBackupScopeInternal(changes)+ require.NoError(t, err)+ require.Equal(t, []string{"cache", "docs/a.txt", "docs/b.txt", "docs/cache"}, scope)+}++func TestNormalizeVolumeWorkspaceScopeInternalCollapsesAbsentAncestors(t *testing.T) {+ require.Equal(t, []string{"cache", "docs"}, normalizeVolumeWorkspaceScopeInternal([]string{+ "docs/b.txt",+ "docs",+ "cache/item",+ "cache",+ "docs/a.txt",+ "cache",+ }))+}++func TestVolumeWorkspaceRollbackPathsInternalRemovesDeepestFirst(t *testing.T) {+ backup := &volumeWorkspaceBackupInternal{+ archives: []volumeWorkspaceBackupArchiveInternal{+ {relativePath: "docs/file.txt", archivePath: "/tmp/file.tar"},+ {relativePath: "cache", archivePath: "/tmp/cache.tar"},+ },+ absentEntries: []string{"docs/new/deep", "other"},+ }+ require.Equal(t, []string{"docs/new/deep", "docs/file.txt", "other", "cache"}, volumeWorkspaceRollbackPathsInternal(backup))+}++func TestVolumeWorkspaceHelperScriptsUseSupportedTooling(t *testing.T) {+ helperScripts := []string{+ volumeWorkspaceTreeScriptInternal,+ volumeWorkspaceValidatePathScriptInternal,+ volumeWorkspaceBackupCreateScriptInternal,+ volumeWorkspaceCreateFileScriptInternal,+ volumeWorkspaceCreateFolderScriptInternal,+ volumeWorkspaceUpdateFileScriptInternal,+ volumeWorkspaceRenameScriptInternal,+ volumeWorkspaceMoveScriptInternal,+ volumeWorkspaceDeleteScriptInternal,+ restoreBackupFilesScriptInternal,+ }+ scripts := strings.Join(helperScripts, "\n")+ for _, unsupported := range []string{+ "if [",+ "elif [",+ "while [",+ "test ",+ "local ",+ "find -P",+ "-printf",+ "sort -z",+ "xargs",+ "cat --",+ "dirname",+ "install ",+ "--files-from",+ "tar -r",+ "$((",+ } {+ require.NotContains(t, scripts, unsupported)+ }+ require.Contains(t, volumeWorkspaceCreateFileScriptInternal, "head -c")+ require.Contains(t, volumeWorkspaceCreateFolderScriptInternal, "mkdir -m 0755")+ require.Contains(t, volumeWorkspaceUpdateFileScriptInternal, "head -c")+ require.Contains(t, volumeWorkspaceBackupCreateScriptInternal, `printf 'absent\0%s\0'`)+ require.Contains(t, volumeWorkspaceBackupCreateScriptInternal, `cd "$parent"`)+ require.NotContains(t, volumeWorkspaceBackupCreateScriptInternal, " -C ")+ if shellPath, err := exec.LookPath("sh"); err == nil {+ for index, script := range helperScripts {+ output, syntaxErr := exec.Command(shellPath, "-n", "-c", script).CombinedOutput()+ require.NoErrorf(t, syntaxErr, "helper script %d has invalid syntax: %s", index, output)+ }+ }+}++func TestClassifyVolumeWorkspaceExecErrorInternal(t *testing.T) {+ base := errors.New("exit status 1")+ require.ErrorIs(t, classifyVolumeWorkspaceExecErrorInternal(base, "ARCANE_SYMLINK", "execute"), common.ErrVolumeWorkspaceForbidden)+ require.ErrorIs(t, classifyVolumeWorkspaceExecErrorInternal(base, "ARCANE_NOT_FOUND", "execute"), common.ErrVolumeWorkspaceNotFound)+ require.ErrorIs(t, classifyVolumeWorkspaceExecErrorInternal(base, "ARCANE_COLLISION", "execute"), common.ErrVolumeWorkspaceBadRequest)+ require.ErrorIs(t, classifyVolumeWorkspaceExecErrorInternal(base, "unexpected", "execute"), base)+}++func TestClassifyVolumeWorkspaceHelperSupportErrorInternal(t *testing.T) {+ require.ErrorIs(t, classifyVolumeWorkspaceHelperSupportErrorInternal(cerrdefs.ErrNotFound), common.ErrVolumeWorkspaceNotFound)+ require.ErrorIs(t, classifyVolumeWorkspaceHelperSupportErrorInternal(errors.New("volume uses a custom mount configuration")), common.ErrVolumeWorkspaceBadRequest)+ unexpected := errors.New("docker unavailable")+ require.ErrorIs(t, classifyVolumeWorkspaceHelperSupportErrorInternal(unexpected), unexpected)+}++func TestValidateVolumeWorkspaceRevisionInternal(t *testing.T) {+ require.NoError(t, validateVolumeWorkspaceRevisionInternal(" revision ", "revision"))+ require.ErrorIs(t, validateVolumeWorkspaceRevisionInternal("stale", "current"), common.ErrVolumeWorkspaceConflict)+}++func TestStageVolumeWorkspaceChangesClearsAndCopiesContentsInOneArchive(t *testing.T) {+ var execCommands [][]string+ var copiedArchives []map[string]string+ execID := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/helper/exec"):+ execID+++ var request struct {+ Cmd []string `json:"Cmd"`+ }+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ t.Errorf("decode exec request: %v", err)+ return+ }+ execCommands = append(execCommands, request.Cmd)+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(map[string]string{"Id": fmt.Sprintf("exec-%d", execID)}); err != nil {+ t.Errorf("encode exec response: %v", err)+ }+ case r.Method == http.MethodPost && strings.Contains(r.URL.Path, "/exec/exec-") && strings.HasSuffix(r.URL.Path, "/start"):+ _, _ = io.Copy(io.Discard, r.Body)+ writeDockerExecAttachResponseInternal(t, w, "")+ case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/exec/exec-") && strings.HasSuffix(r.URL.Path, "/json"):+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(map[string]any{"Running": false, "ExitCode": 0}); err != nil {+ t.Errorf("encode exec inspect response: %v", err)+ }+ case r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/containers/helper/archive"):+ if got := r.URL.Query().Get("path"); got != "/tmp/arcane-workspace" {+ t.Errorf("unexpected archive destination %q", got)+ }+ archive := make(map[string]string)+ tarReader := tar.NewReader(r.Body)+ for {+ header, err := tarReader.Next()+ if errors.Is(err, io.EOF) {+ break+ }+ if err != nil {+ t.Errorf("read staging archive: %v", err)+ return+ }+ content, err := io.ReadAll(tarReader)+ if err != nil {+ t.Errorf("read staging archive content: %v", err)+ return+ }+ archive[header.Name] = string(content)+ }+ copiedArchives = append(copiedArchives, archive)+ w.WriteHeader(http.StatusOK)+ default:+ http.Error(w, "unexpected Docker request: "+r.Method+" "+r.URL.Path, http.StatusInternalServerError)+ }+ }))+ t.Cleanup(server.Close)++ dockerClient := newVolumeWorkspaceTestDockerClientInternal(t, server)+ service := &VolumeService{dockerService: docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(dockerClient)}+ firstUpload := 0+ secondUpload := 1+ firstStaged, err := service.stageVolumeWorkspaceChangesInternal(context.Background(), dockerClient, "helper", []volumetypes.WorkspaceFileChange{+ {UploadIndex: &firstUpload},+ {},+ {UploadIndex: &secondUpload},+ }, map[int][]byte{0: []byte("alpha"), 1: {}})+ require.NoError(t, err)+ require.Equal(t, volumeWorkspaceStagedFileInternal{path: "/tmp/arcane-workspace/change-0", size: 5}, firstStaged[0])+ require.Equal(t, volumeWorkspaceStagedFileInternal{path: "/tmp/arcane-workspace/change-2", size: 0}, firstStaged[2])++ secondStaged, err := service.stageVolumeWorkspaceChangesInternal(context.Background(), dockerClient, "helper", []volumetypes.WorkspaceFileChange{{UploadIndex: &firstUpload}}, map[int][]byte{0: []byte("second")})+ require.NoError(t, err)+ require.Equal(t, volumeWorkspaceStagedFileInternal{path: "/tmp/arcane-workspace/change-0", size: 6}, secondStaged[0])++ require.Equal(t, [][]string{+ {"sh", "-c", "rm -rf -- /tmp/arcane-workspace && mkdir -p -- /tmp/arcane-workspace"},+ {"sh", "-c", "rm -rf -- /tmp/arcane-workspace && mkdir -p -- /tmp/arcane-workspace"},+ }, execCommands)+ require.Equal(t, []map[string]string{+ {"change-0": "alpha", "change-2": ""},+ {"change-0": "second"},+ }, copiedArchives)+}++func TestUpdateVolumeWorkspaceRejectsStaleRevisionBeforeStaging(t *testing.T) {+ var execCommands [][]string+ archiveCopies := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/workspace-volume"):+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(volume.Volume{Name: "workspace-volume", Driver: "local"})+ case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]string{"Id": "tools-image"})+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/create"):+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"Id": "helper", "Warnings": []string{}})+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/helper/start"):+ w.WriteHeader(http.StatusNoContent)+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/helper/exec"):+ var request struct {+ Cmd []string `json:"Cmd"`+ }+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ t.Errorf("decode exec request: %v", err)+ return+ }+ execCommands = append(execCommands, request.Cmd)+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]string{"Id": "tree-exec"})+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/exec/tree-exec/start"):+ _, _ = io.Copy(io.Discard, r.Body)+ writeDockerExecAttachResponseInternal(t, w, volumeWorkspaceTreeOutputInternal(false, ""))+ case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/exec/tree-exec/json"):+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"Running": false, "ExitCode": 0})+ case r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/containers/helper/archive"):+ archiveCopies+++ w.WriteHeader(http.StatusOK)+ default:+ http.Error(w, "unexpected Docker request: "+r.Method+" "+r.URL.Path, http.StatusInternalServerError)+ }+ }))+ t.Cleanup(server.Close)++ dockerClient := newVolumeWorkspaceTestDockerClientInternal(t, server)+ service := &VolumeService{+ dockerService: docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(dockerClient),+ helperByVolume: make(map[string]*volumeHelper),+ }+ uploadIndex := 0+ workspace, err := service.UpdateVolumeWorkspace(context.Background(), "workspace-volume", volumetypes.WorkspaceUpdateManifest{+ FileTreeRevision: "stale",+ FileChanges: []volumetypes.WorkspaceFileChange{{+ Operation: volumetypes.FileOpCreateFile,+ RelativePath: "new.txt",+ UploadIndex: &uploadIndex,+ }},+ }, map[int][]byte{0: []byte("new content")}, models.User{})++ require.Nil(t, workspace)+ require.ErrorIs(t, err, common.ErrVolumeWorkspaceConflict)+ require.Len(t, execCommands, 1)+ require.Contains(t, execCommands[0], volumeWorkspaceTreeScriptInternal)+ require.Zero(t, archiveCopies)+}++func TestCreateVolumeWorkspaceMutationContainerUsesDedicatedBackupHelper(t *testing.T) {+ var createRequest struct {+ HostConfig *container.HostConfig `json:"HostConfig"`+ }+ createCalls := 0+ removeCalls := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]string{"Id": "tools-image"})+ case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode([]container.Summary{})+ case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/containers/") && strings.HasSuffix(r.URL.Path, "/json"):+ http.NotFound(w, r)+ case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/arcane-backups"):+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(volume.Volume{Name: "arcane-backups", Driver: "local"})+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/create"):+ createCalls+++ if err := json.NewDecoder(r.Body).Decode(&createRequest); err != nil {+ t.Errorf("decode container create request: %v", err)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"Id": "restore-helper", "Warnings": []string{}})+ case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/restore-helper/start"):+ w.WriteHeader(http.StatusNoContent)+ case r.Method == http.MethodDelete && strings.Contains(r.URL.Path, "/containers/restore-helper"):+ removeCalls+++ w.WriteHeader(http.StatusNoContent)+ default:+ http.Error(w, "unexpected Docker request: "+r.Method+" "+r.URL.Path, http.StatusInternalServerError)+ }+ }))+ t.Cleanup(server.Close)++ dockerClient := newVolumeWorkspaceTestDockerClientInternal(t, server)+ service := &VolumeService{+ dockerService: docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(dockerClient),+ backupVolumeName: "arcane-backups",+ helperByVolume: map[string]*volumeHelper{+ "workspace-volume": {id: "cached-helper", lastUsedAt: time.Now()},+ },+ }++ containerID, cleanup, err := service.createVolumeWorkspaceMutationContainerInternal(context.Background(), "workspace-volume", true)+ require.NoError(t, err)+ require.Equal(t, "restore-helper", containerID)+ require.Equal(t, 1, createCalls)+ require.Equal(t, "cached-helper", service.helperByVolume["workspace-volume"].id)+ require.NotNil(t, createRequest.HostConfig)+ require.Equal(t, []string{"workspace-volume:/volume"}, createRequest.HostConfig.Binds)+ require.Len(t, createRequest.HostConfig.Mounts, 1)+ require.Equal(t, "arcane-backups", createRequest.HostConfig.Mounts[0].Source)+ require.Equal(t, "/backups", createRequest.HostConfig.Mounts[0].Target)+ require.True(t, createRequest.HostConfig.Mounts[0].ReadOnly)++ cleanup()+ require.Equal(t, 1, removeCalls)+}++func TestApplyVolumeWorkspaceChangesTransactionInternalRollsBackEveryMutationStage(t *testing.T) {+ changes := []volumetypes.WorkspaceFileChange{+ {Operation: volumetypes.FileOpCreateFolder, RelativePath: "one"},+ {Operation: volumetypes.FileOpRename, RelativePath: "one", NewName: "two"},+ {Operation: volumetypes.FileOpDelete, RelativePath: "two", Recursive: true},+ }+ applyFailure := errors.New("apply failed")+ for failureIndex := range changes {+ t.Run(changes[failureIndex].Operation, func(t *testing.T) {+ applied := make([]int, 0, failureIndex+1)+ rollbackCalls := 0+ err := applyVolumeWorkspaceChangesTransactionInternal(changes, func(index int, _ volumetypes.WorkspaceFileChange) error {+ applied = append(applied, index)+ if index == failureIndex {+ return applyFailure+ }+ return nil+ }, func() error {+ rollbackCalls+++ return nil+ })+ require.ErrorIs(t, err, applyFailure)+ require.Equal(t, failureIndex+1, len(applied))+ require.Equal(t, 1, rollbackCalls)+ })+ }++ rollbackFailure := errors.New("rollback failed")+ err := applyVolumeWorkspaceChangesTransactionInternal(changes, func(_ int, _ volumetypes.WorkspaceFileChange) error {+ return applyFailure+ }, func() error {+ return rollbackFailure+ })+ require.ErrorIs(t, err, applyFailure)+ require.ErrorIs(t, err, rollbackFailure)+}++func TestVolumeWorkspaceScriptsAgainstToolsImage(t *testing.T) {+ if os.Getenv("ARCANE_VOLUME_WORKSPACE_DOCKER_TEST") != "1" {+ t.Skip("set ARCANE_VOLUME_WORKSPACE_DOCKER_TEST=1 to run the helper image integration test")+ }+ dockerPath, err := exec.LookPath("docker")+ require.NoError(t, err)++ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)+ defer cancel()+ runDocker := func(args ...string) string {+ t.Helper()+ output, err := exec.CommandContext(ctx, dockerPath, args...).CombinedOutput()+ require.NoErrorf(t, err, "docker %s\n%s", strings.Join(args, " "), output)+ return string(output)+ }+ runInVolume := func(volumeName, outerScript string, args ...string) string {+ t.Helper()+ dockerArgs := []string{"run", "--rm", "-v", volumeName + ":/volume", volumehelper.DefaultToolsImage, "sh", "-c", outerScript, "sh"}+ dockerArgs = append(dockerArgs, args...)+ return runDocker(dockerArgs...)+ }++ volumeName := "arcane-workspace-test-" + strconv.FormatInt(time.Now().UnixNano(), 10)+ runDocker("volume", "create", volumeName)+ t.Cleanup(func() {+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cleanupCancel()+ _, _ = exec.CommandContext(cleanupCtx, dockerPath, "volume", "rm", volumeName).CombinedOutput()+ })++ runInVolume(volumeName, `mkdir -p /volume/folder/nested+printf child > /volume/folder/nested/child.txt+printf hidden > /volume/.hidden+printf alpha > /volume/z.txt`)+ treeOutput := runInVolume(volumeName, `sh -c "$1" sh "$2" "$3"`, volumeWorkspaceTreeScriptInternal, strings.Repeat("d", 5), strings.Repeat("e", 100))+ workspace, err := parseVolumeWorkspaceTreeInternal(treeOutput, 100)+ require.NoError(t, err)+ require.Equal(t, []string{"folder", "folder/nested", ".hidden", "folder/nested/child.txt", "z.txt"}, []string{+ workspace.Files[0].RelativePath,+ workspace.Files[1].RelativePath,+ workspace.Files[2].RelativePath,+ workspace.Files[3].RelativePath,+ workspace.Files[4].RelativePath,+ })+ require.True(t, workspace.Files[0].IsDirectory)+ require.True(t, workspace.Files[1].IsDirectory)+ require.False(t, workspace.Files[2].IsDirectory)+ require.False(t, workspace.Files[3].IsDirectory)+ require.False(t, workspace.Files[4].IsDirectory)++ runInVolume(volumeName, `sh -c "$1" sh folder/nested/child.txt 0`, volumeWorkspaceValidatePathScriptInternal)+ runInVolume(volumeName, `sh -c "$1" sh missing/path 1`, volumeWorkspaceValidatePathScriptInternal)+ runInVolume(volumeName, `sh -c "$1" sh nested ''`, volumeWorkspaceCreateFolderScriptInternal)+ runInVolume(volumeName, `printf one > /tmp/staged+sh -c "$1" sh nested/a.txt nested /tmp/staged 3`, volumeWorkspaceCreateFileScriptInternal)+ require.Equal(t, "644 3\n", runInVolume(volumeName, `stat -c '%a %s' /volume/nested/a.txt`))+ runInVolume(volumeName, `printf updated > /tmp/staged+sh -c "$1" sh nested/a.txt /tmp/staged 7`, volumeWorkspaceUpdateFileScriptInternal)+ require.Equal(t, "updated", runInVolume(volumeName, `head -c 7 /volume/nested/a.txt`))++ runInVolume(volumeName, `sh -c "$1" sh nested/a.txt nested/b.txt`, volumeWorkspaceRenameScriptInternal)+ runInVolume(volumeName, `sh -c "$1" sh dest ''`, volumeWorkspaceCreateFolderScriptInternal)+ runInVolume(volumeName, `sh -c "$1" sh nested/b.txt dest dest/b.txt`, volumeWorkspaceMoveScriptInternal)++ restored := runInVolume(volumeName, `set -e+sh -c "$1" sh dest/b.txt /tmp/backup.tar >/dev/null+sh -c "$2" sh dest/b.txt 0+tar -xf /tmp/backup.tar -C /volume/dest+head -c 7 /volume/dest/b.txt`, volumeWorkspaceBackupCreateScriptInternal, volumeWorkspaceDeleteScriptInternal)+ require.Equal(t, "updated", restored)++ runInVolume(volumeName, `mkdir -p "/volume/Test Folder"+printf spaced > "/volume/Test Folder/file.txt"`)+ spacedRestored := runInVolume(volumeName, `set -e+sh -c "$1" sh "Test Folder" /tmp/space-backup.tar >/dev/null+rm -rf "/volume/Test Folder"+tar -xf /tmp/space-backup.tar -C /volume+head -c 6 "/volume/Test Folder/file.txt"`, volumeWorkspaceBackupCreateScriptInternal)+ require.Equal(t, "spaced", spacedRestored)++ missing := runInVolume(volumeName, `set -e+sh -c "$1" sh test.txt /tmp/missing-backup.tar+if stat -c '%A' -- /tmp/missing-backup.tar >/dev/null 2>&1; then exit 1; fi`, volumeWorkspaceBackupCreateScriptInternal)+ require.Equal(t, "absent\x00test.txt\x00", missing)++ missingNested := runInVolume(volumeName, `set -e+sh -c "$1" sh "New Folder/test.txt" /tmp/missing-nested-backup.tar+if stat -c '%A' -- /tmp/missing-nested-backup.tar >/dev/null 2>&1; then exit 1; fi`, volumeWorkspaceBackupCreateScriptInternal)+ require.Equal(t, "absent\x00New Folder\x00", missingNested)+}diff --git a/backend/pkg/authz/catalog.go b/backend/pkg/authz/catalog.goindex 8766bba28..cd3b69f34 100644--- a/backend/pkg/authz/catalog.go+++ b/backend/pkg/authz/catalog.go@@ -148,7 +148,6 @@ var permissionCatalog = []PermissionCatalogResource{{"create", PermVolumesCreate, "Create", ""},{"delete", PermVolumesDelete, "Delete", ""},{"prune", PermVolumesPrune, "Prune", ""},- {"browse", PermVolumesBrowse, "Browse", ""},{"upload", PermVolumesUpload, "Upload", ""},{"backup", PermVolumesBackup, "Backup / restore", ""},}},diff --git a/backend/pkg/authz/permission_matcher_test.go b/backend/pkg/authz/permission_matcher_test.goindex 1c3be20aa..cc9906ae1 100644--- a/backend/pkg/authz/permission_matcher_test.go+++ b/backend/pkg/authz/permission_matcher_test.go@@ -72,12 +72,12 @@ func TestPermissionMatcherMethodAndLengthMismatch(t *testing.T) {func TestPermissionMatcherNormalizesEchoParamsAndStripsQuery(t *testing.T) {m := NewPermissionMatcher()- m.Add("GET", "/volumes/:volumeName/browse", "volumes:browse")+ m.Add("GET", "/volumes/:volumeName/workspace", "volumes:read"){- perm, ok := m.Lookup("GET", "/volumes/data/browse?path=/etc").Get()- require.False(t, !ok || perm != "volumes:browse",- "expected volumes:browse with echo param + query string, got %q ok=%v", perm, ok)+ perm, ok := m.Lookup("GET", "/volumes/data/workspace?path=/etc").Get()+ require.False(t, !ok || perm != "volumes:read",+ "expected volumes:read with echo param + query string, got %q ok=%v", perm, ok)}}diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.goindex 9e921eb04..30060afff 100644--- a/backend/pkg/authz/permissions.go+++ b/backend/pkg/authz/permissions.go@@ -137,7 +137,6 @@ const (PermVolumesCreate = "volumes:create"PermVolumesDelete = "volumes:delete"PermVolumesPrune = "volumes:prune"- PermVolumesBrowse = "volumes:browse"PermVolumesUpload = "volumes:upload"PermVolumesBackup = "volumes:backup"@@ -299,7 +298,7 @@ func BuiltInEditorPermissions() []string {PermContainersList, PermContainersRead, PermContainersLogs, PermContainersCreate, PermContainersStart, PermContainersStop, PermContainersRestart, PermContainersRedeploy, 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, PermVolumesBrowse, PermVolumesUpload, PermVolumesBackup,+ PermVolumesList, PermVolumesRead, PermVolumesCreate, PermVolumesDelete, PermVolumesPrune, PermVolumesUpload, PermVolumesBackup,PermNetworksList, PermNetworksRead, PermNetworksCreate, PermNetworksDelete, PermNetworksPrune,PermSwarmRead, PermSwarmSpec, PermSwarmNodes, PermSwarmServices, PermSwarmServicesLogs, PermSwarmStacks, PermSwarmConfigs, PermSwarmSecrets,PermGitOpsList, PermGitOpsRead, PermGitOpsCreate, PermGitOpsUpdate, PermGitOpsDelete, PermGitOpsSync,@@ -326,7 +325,7 @@ func BuiltInDeployerPermissions() []string {PermContainersList, PermContainersRead, PermContainersLogs, PermContainersStart, PermContainersStop, PermContainersRestart, PermContainersRedeploy, PermContainersKill, PermContainersPause,PermProjectsList, PermProjectsRead, PermProjectsLogs, PermProjectsDeploy, PermProjectsDown, PermProjectsRestart,PermImagesList, PermImagesRead, PermImagesPull, PermImagesTag, PermImagesCommit,- PermVolumesList, PermVolumesRead, PermVolumesBrowse,+ PermVolumesList, PermVolumesRead,PermNetworksList, PermNetworksRead,PermSwarmRead, PermSwarmServicesLogs,PermGitOpsList, PermGitOpsRead, PermGitOpsSync,@@ -356,7 +355,7 @@ func BuiltInViewerPermissions() []string {PermContainersList, PermContainersRead, PermContainersLogs,PermProjectsList, PermProjectsRead, PermProjectsLogs,PermImagesList, PermImagesRead,- PermVolumesList, PermVolumesRead, PermVolumesBrowse,+ PermVolumesList, PermVolumesRead,PermNetworksList, PermNetworksRead,PermSwarmRead, PermSwarmServicesLogs,PermGitOpsList, PermGitOpsRead,diff --git a/backend/pkg/authz/volume_workspace.go b/backend/pkg/authz/volume_workspace.gonew file mode 100644index 000000000..de9144d12--- /dev/null+++ b/backend/pkg/authz/volume_workspace.go@@ -0,0 +1,35 @@+package authz++import volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"++// VolumeWorkspaceRequiredPermissions returns the distinct mutation permissions+// required by a Volume Workspace manifest. The boolean is false when a change+// uses an unknown operation so remote proxies can fail closed.+func VolumeWorkspaceRequiredPermissions(changes []volumetypes.WorkspaceFileChange) ([]string, bool) {+ required := make([]string, 0, 3)+ seen := make(map[string]struct{}, 3)+ add := func(permission string) {+ if _, exists := seen[permission]; exists {+ return+ }+ seen[permission] = struct{}{}+ required = append(required, permission)+ }++ for _, change := range changes {+ switch change.Operation {+ case volumetypes.FileOpCreateFile, volumetypes.FileOpCreateFolder, volumetypes.FileOpUpdateFile:+ add(PermVolumesUpload)+ case volumetypes.FileOpRename, volumetypes.FileOpMove:+ add(PermVolumesUpload)+ add(PermVolumesDelete)+ case volumetypes.FileOpDelete:+ add(PermVolumesDelete)+ case volumetypes.FileOpRestoreFile:+ add(PermVolumesBackup)+ default:+ return nil, false+ }+ }+ return required, true+}diff --git a/backend/pkg/authz/volume_workspace_test.go b/backend/pkg/authz/volume_workspace_test.gonew file mode 100644index 000000000..d96b37bdc--- /dev/null+++ b/backend/pkg/authz/volume_workspace_test.go@@ -0,0 +1,22 @@+package authz++import (+ "testing"++ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"+ "github.com/stretchr/testify/require"+)++func TestVolumeWorkspaceRequiredPermissions(t *testing.T) {+ permissions, valid := VolumeWorkspaceRequiredPermissions([]volumetypes.WorkspaceFileChange{+ {Operation: volumetypes.FileOpCreateFile},+ {Operation: volumetypes.FileOpRename},+ {Operation: volumetypes.FileOpRestoreFile},+ })+ require.True(t, valid)+ require.Equal(t, []string{PermVolumesUpload, PermVolumesDelete, PermVolumesBackup}, permissions)++ permissions, valid = VolumeWorkspaceRequiredPermissions([]volumetypes.WorkspaceFileChange{{Operation: "unknown"}})+ require.False(t, valid)+ require.Nil(t, permissions)+}diff --git a/backend/pkg/dockerutil/volume_workspace.go b/backend/pkg/dockerutil/volume_workspace.gonew file mode 100644index 000000000..16596c25f--- /dev/null+++ b/backend/pkg/dockerutil/volume_workspace.go@@ -0,0 +1,16 @@+package docker++import (+ "strings"++ "emperror.dev/errors"+)++// ValidateVolumeWorkspaceHelperSupport rejects Docker volume configurations+// that cannot be mounted safely inside Arcane's reusable workspace helper.+func ValidateVolumeWorkspaceHelperSupport(volumeName string, options map[string]string) error {+ if options["type"] == "none" || strings.Contains(options["o"], "bind") {+ return errors.Errorf("volume %q uses a custom mount configuration and cannot be accessed through the workspace helper", volumeName)+ }+ return nil+}diff --git a/backend/pkg/dockerutil/volume_workspace_test.go b/backend/pkg/dockerutil/volume_workspace_test.gonew file mode 100644index 000000000..665f14164--- /dev/null+++ b/backend/pkg/dockerutil/volume_workspace_test.go@@ -0,0 +1,14 @@+package docker++import (+ "testing"++ "github.com/stretchr/testify/require"+)++func TestValidateVolumeWorkspaceHelperSupport(t *testing.T) {+ require.NoError(t, ValidateVolumeWorkspaceHelperSupport("data", nil))+ require.NoError(t, ValidateVolumeWorkspaceHelperSupport("data", map[string]string{"type": "nfs"}))+ require.Error(t, ValidateVolumeWorkspaceHelperSupport("data", map[string]string{"type": "none"}))+ require.Error(t, ValidateVolumeWorkspaceHelperSupport("data", map[string]string{"o": "bind,rw"}))+}diff --git a/backend/pkg/libarcane/edge/commands.go b/backend/pkg/libarcane/edge/commands.goindex ae3fb7ead..9e55ede08 100644--- a/backend/pkg/libarcane/edge/commands.go+++ b/backend/pkg/libarcane/edge/commands.go@@ -73,14 +73,15 @@ var commandRoutes = []commandRoute{{Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects", CommandName: "project.create"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects/{projectId}", CommandName: "project.inspect"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects/{projectId}/compose", CommandName: "project.compose"},- {Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects/{projectId}/files", CommandName: "project.files"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects/{projectId}/workspace", CommandName: "project.workspace.list"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects/{projectId}/runtime", CommandName: "project.runtime"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects/{projectId}/updates", CommandName: "project.updates"},- {Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects/{projectId}/file", CommandName: "project.file"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects/{projectId}/workspace/file", CommandName: "project.workspace.read_file"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects/{projectId}/workspace/file/download", CommandName: "project.workspace.download"},+ {Method: http.MethodPut, PathPattern: "/api/environments/{id}/projects/{projectId}/workspace", CommandName: "project.workspace.update"},{Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects/{projectId}/redeploy", CommandName: "project.redeploy"},{Method: http.MethodDelete, PathPattern: "/api/environments/{id}/projects/{projectId}/destroy", CommandName: "project.destroy"},{Method: http.MethodPut, PathPattern: "/api/environments/{id}/projects/{projectId}", CommandName: "project.update"},- {Method: http.MethodPut, PathPattern: "/api/environments/{id}/projects/{projectId}/includes", CommandName: "project.includes"},{Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects/{projectId}/restart", CommandName: "project.restart"},{Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects/{projectId}/update-services", CommandName: "project.update_services"},{Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects/{projectId}/pull", CommandName: "project.pull"},@@ -106,12 +107,10 @@ var commandRoutes = []commandRoute{{Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/prune", CommandName: "volume.prune"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/usage", CommandName: "volume.usage"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/sizes", CommandName: "volume.sizes"},- {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse", CommandName: "volume.browse.list"},- {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse/content", CommandName: "volume.browse.read_file"},- {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse/download", CommandName: "volume.browse.download"},- {Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse/upload", CommandName: "volume.browse.upload"},- {Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse/mkdir", CommandName: "volume.browse.mkdir"},- {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse", CommandName: "volume.browse.delete"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/workspace", CommandName: "volume.workspace.list"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/workspace/file", CommandName: "volume.workspace.read_file"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/workspace/file/download", CommandName: "volume.workspace.download"},+ {Method: http.MethodPut, PathPattern: "/api/environments/{id}/volumes/{volumeName}/workspace", CommandName: "volume.workspace.update"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/backups", CommandName: "volume.backup.list"},{Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/{volumeName}/backups", CommandName: "volume.backup.create"},{Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/{volumeName}/backups/{backupId}/restore", CommandName: "volume.backup.restore"},diff --git a/backend/pkg/libarcane/edge/commands_test.go b/backend/pkg/libarcane/edge/commands_test.goindex 7b4187afa..a9cda1c5d 100644--- a/backend/pkg/libarcane/edge/commands_test.go+++ b/backend/pkg/libarcane/edge/commands_test.go@@ -21,7 +21,19 @@ func TestResolveEdgeCommandName(t *testing.T) {}{{name: "container list", method: "GET", path: "/api/environments/0/containers", command: "container.list", shouldHit: true},{name: "container start", method: "POST", path: "/api/environments/0/containers/abc/start", command: "container.start", shouldHit: true},- {name: "volume browse download", method: "GET", path: "/api/environments/0/volumes/data/browse/download", command: "volume.browse.download", shouldHit: true},+ {name: "volume workspace download", method: "GET", path: "/api/environments/0/volumes/data/workspace/file/download?relativePath=notes/readme.txt", command: "volume.workspace.download", shouldHit: true},+ {name: "volume workspace list", method: "GET", path: "/api/environments/0/volumes/data/workspace", command: "volume.workspace.list", shouldHit: true},+ {name: "volume workspace read file", method: "GET", path: "/api/environments/0/volumes/data/workspace/file?relativePath=notes/readme.txt", command: "volume.workspace.read_file", shouldHit: true},+ {name: "volume workspace update", method: "PUT", path: "/api/environments/0/volumes/data/workspace", command: "volume.workspace.update", shouldHit: true},+ {name: "project workspace list", method: "GET", path: "/api/environments/0/projects/p1/workspace", command: "project.workspace.list", shouldHit: true},+ {name: "project workspace read file", method: "GET", path: "/api/environments/0/projects/p1/workspace/file?relativePath=notes/readme.txt", command: "project.workspace.read_file", shouldHit: true},+ {name: "project workspace download", method: "GET", path: "/api/environments/0/projects/p1/workspace/file/download?relativePath=notes/readme.txt", command: "project.workspace.download", shouldHit: true},+ {name: "project workspace update", method: "PUT", path: "/api/environments/0/projects/p1/workspace", command: "project.workspace.update", shouldHit: true},+ {name: "build workspace browse retained", method: "GET", path: "/api/environments/0/builds/browse", command: "build_workspace.browse.list", shouldHit: true},+ {name: "legacy project files absent", method: "GET", path: "/api/environments/0/projects/p1/files", shouldHit: false},+ {name: "legacy project includes absent", method: "PUT", path: "/api/environments/0/projects/p1/includes", shouldHit: false},+ {name: "legacy volume browse absent", method: "GET", path: "/api/environments/0/volumes/data/browse", shouldHit: false},+ {name: "legacy volume files absent", method: "GET", path: "/api/environments/0/volumes/data/files", shouldHit: false},{name: "project logs stream", method: "GET", path: "/api/environments/0/ws/projects/p1/logs", stream: true, command: "project.logs.stream", shouldHit: true},{name: "project updates", method: "GET", path: "/api/environments/0/projects/p1/updates", command: "project.updates", shouldHit: true},{name: "project archive", method: "POST", path: "/api/environments/0/projects/p1/archive", command: "project.archive", shouldHit: true},diff --git a/backend/pkg/libarcane/volumehelper/container_files.go b/backend/pkg/libarcane/volumehelper/container_files.goindex af50d4f23..9e6cc1780 100644--- a/backend/pkg/libarcane/volumehelper/container_files.go+++ b/backend/pkg/libarcane/volumehelper/container_files.go@@ -79,10 +79,10 @@ func DownloadFileFromContainer(cleanup()return nil, 0, errors.WrapIf(err, "failed to read tar stream")}- if hdr.FileInfo().IsDir() {+ if err := validateDownloadHeaderInternal(hdr); err != nil {_ = reader.Close()cleanup()- return nil, 0, errors.New("path is a directory")+ return nil, 0, err}return &cleanupReadCloserInternal{@@ -91,3 +91,10 @@ func DownloadFileFromContainer(cleanup: cleanup,}, hdr.Size, nil}++func validateDownloadHeaderInternal(header *tar.Header) error {+ if header.FileInfo().IsDir() {+ return errors.New("path is a directory")+ }+ return nil+}diff --git a/backend/pkg/libarcane/volumehelper/container_files_test.go b/backend/pkg/libarcane/volumehelper/container_files_test.goindex c17df33ca..e28932a61 100644--- a/backend/pkg/libarcane/volumehelper/container_files_test.go+++ b/backend/pkg/libarcane/volumehelper/container_files_test.go@@ -1,6 +1,7 @@package volumehelperimport (+ "archive/tar""testing""github.com/moby/moby/api/types/container"@@ -9,6 +10,13 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane")+func TestValidateDownloadHeaderInternalRejectsDirectories(t *testing.T) {+ require.NoError(t, validateDownloadHeaderInternal(&tar.Header{Typeflag: tar.TypeReg, Mode: 0o644}))+ require.EqualError(t, validateDownloadHeaderInternal(&tar.Header{Typeflag: tar.TypeDir, Mode: 0o755}), "path is a directory")+ require.NoError(t, validateDownloadHeaderInternal(&tar.Header{Typeflag: tar.TypeSymlink, Mode: 0o777}))+ require.NoError(t, validateDownloadHeaderInternal(&tar.Header{Typeflag: tar.TypeFifo, Mode: 0o644}))+}+func TestIsLegacyVolumeHelperContainerInternal(t *testing.T) {tests := []struct {name stringdiff --git a/backend/pkg/projects/fs_backup.go b/backend/pkg/projects/fs_backup.goindex 5fa4f30a1..225cf5096 100644--- a/backend/pkg/projects/fs_backup.go+++ b/backend/pkg/projects/fs_backup.go@@ -8,8 +8,6 @@ import ("strings""emperror.dev/errors"- "github.com/getarcaneapp/arcane/types/v2/project"-"go.getarcane.app/sys/atomic")@@ -483,84 +481,3 @@ func restoreTopLevelFilesInternal(backupRoot, projRoot *os.Root, backup *Project}return nil}--// BuildUpdateBackupScope derives the backup scope for one project update from-// the content and file changes it will apply.-func BuildUpdateBackupScope(projectPath string, composeContent, envContent, overrideContent *string, fileChanges []project.ProjectFileChange) ProjectUpdateBackupScope {- scope := ProjectUpdateBackupScope{- TopLevelFiles: composeContent != nil || envContent != nil || overrideContent != nil,- }-- for _, change := range fileChanges {- rel, err := NormalizeProjectRelativePath(change.RelativePath)- if err != nil {- continue- }-- var dest string- switch change.Operation {- case project.FileOpRename:- newName, nameErr := ValidateProjectFileName(change.NewName)- if nameErr != nil {- continue- }- dest = path.Join(path.Dir(rel), newName)- case project.FileOpMove:- parent := strings.TrimSpace(change.NewParentPath)- if parent != "" {- normalizedParent, parentErr := NormalizeProjectRelativePath(parent)- if parentErr != nil {- continue- }- parent = normalizedParent- }- dest = path.Join(parent, path.Base(rel))- default:- scope.Paths = append(scope.Paths, rel)- continue- }-- // Rename/move of an existing directory rolls back via an inverse- // rename — never a copy of a potentially huge tree.- if info, statErr := os.Lstat(filepath.Join(projectPath, filepath.FromSlash(rel))); statErr == nil && info.IsDir() {- scope.RenamedDirs = append(scope.RenamedDirs, [2]string{rel, dest})- } else {- scope.Paths = append(scope.Paths, rel, dest)- }- }-- demoteInterferingRenamedDirsInternal(&scope)- return scope-}--// demoteInterferingRenamedDirsInternal downgrades a directory rename to a full-// copy when another change in the same batch touches its source or destination-// subtree (e.g. rename a -> b then delete b, or update_file b/x). The inverse-// rename alone cannot roll those back: the destination may be mutated or gone-// by the time the batch fails, so the original directory must be backed up.-func demoteInterferingRenamedDirsInternal(scope *ProjectUpdateBackupScope) {- overlaps := func(a, b string) bool {- return a == b || strings.HasPrefix(a, b+"/") || strings.HasPrefix(b, a+"/")- }- touchesPair := func(p string, pair [2]string) bool {- return overlaps(p, pair[0]) || overlaps(p, pair[1])- }-- for i := 0; i < len(scope.RenamedDirs); i++ {- pair := scope.RenamedDirs[i]- conflict := slices.ContainsFunc(scope.Paths, func(p string) bool { return touchesPair(p, pair) })- if !conflict {- for j, other := range scope.RenamedDirs {- if j != i && (touchesPair(other[0], pair) || touchesPair(other[1], pair)) {- conflict = true- break- }- }- }- if conflict {- scope.Paths = append(scope.Paths, pair[0], pair[1])- scope.RenamedDirs = slices.Delete(scope.RenamedDirs, i, i+1)- i--- }- }-}diff --git a/backend/pkg/projects/fs_util.go b/backend/pkg/projects/fs_util.goindex 39dd885bf..de4b3ea4f 100644--- a/backend/pkg/projects/fs_util.go+++ b/backend/pkg/projects/fs_util.go@@ -14,7 +14,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config"pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"- "github.com/getarcaneapp/arcane/types/v2/project""github.com/samber/mo""go.yaml.in/yaml/v4")@@ -144,27 +143,9 @@ func GetTemplatesDirectory(ctx context.Context, templatesDir string) (string, erreturn resolved, nil}-func ReadProjectDirectoryFiles(projectPath string, shownFiles map[string]bool, maxDepth int, skipDirectories string) ([]project.IncludeFile, error) {- if maxDepth <= 0 {- maxDepth = config.LoadProjectFilesConfig().ProjectScanMaxDepth- }-- var dirFiles []project.IncludeFile-- root, err := os.OpenRoot(projectPath)- if err != nil {- return dirFiles, err- }- defer func() { _ = root.Close() }()-- err = collectProjectDirectoryFilesInternal(root, ".", projectPath, shownFiles, &dirFiles, 0, maxDepth, projectScanSkipDirectorySetInternal(skipDirectories), false)-- return dirFiles, err-}-func projectScanSkipDirectorySetInternal(skipDirectories string) map[string]bool {if strings.TrimSpace(skipDirectories) == "" {- skipDirectories = config.LoadProjectFilesConfig().ProjectScanSkipDirs+ skipDirectories = config.LoadProjectWorkspaceConfig().ProjectScanSkipDirs}dirs := map[string]bool{}@@ -175,88 +156,12 @@ func projectScanSkipDirectorySetInternal(skipDirectories string) map[string]bool}}- // Never allow .git contents to be exposed through the project file browser.+ // Never allow .git contents to be exposed through the project workspace.dirs[".git"] = truereturn dirs}-func collectProjectDirectoryFilesInternal(- root *os.Root,- relDir string,- projectPath string,- shownFiles map[string]bool,- dirFiles *[]project.IncludeFile,- currentDepth int,- maxDepth int,- skipDirs map[string]bool,- includeContent bool,-) error {- if currentDepth >= maxDepth {- return nil- }-- dir, err := root.Open(relDir)- if err != nil {- return err- }- defer func() { _ = dir.Close() }()-- entries, err := dir.ReadDir(-1)- if err != nil {- return err- }-- for _, entry := range entries {- relPath := entry.Name()- if relDir != "." {- relPath = filepath.Join(relDir, entry.Name())- }- if entry.Type()&os.ModeSymlink != 0 {- continue- }- if entry.IsDir() {- if skipDirs[entry.Name()] {- continue- }- if err := collectProjectDirectoryFilesInternal(root, relPath, projectPath, shownFiles, dirFiles, currentDepth+1, maxDepth, skipDirs, includeContent); err != nil {- slog.Debug("Skipping unreadable project subdirectory", "relativePath", relPath, "error", err)- }- continue- }- if shownFiles[relPath] {- continue- }-- info, err := entry.Info()- if err != nil || info.Size() > 1024*1024 {- continue- }-- file := project.IncludeFile{- Path: filepath.Join(projectPath, relPath),- RelativePath: relPath,- }-- if includeContent {- content, err := root.ReadFile(relPath)- if err != nil || IsBinaryProjectFileContent(content) {- continue- }- file.Content = string(content)- }-- *dirFiles = append(*dirFiles, file)- }-- return nil-}--func IsBinaryProjectFileContent(content []byte) bool {- checkSize := min(len(content), 512)- return slices.Contains(content[:checkSize], 0)-}-func syncedProjectFileMatchesInternal(projectPath string, file SyncFile) (bool, error) {existingPath := filepath.Join(projectPath, file.RelativePath)info, err := os.Stat(existingPath)diff --git a/backend/pkg/projects/fs_util_test.go b/backend/pkg/projects/fs_util_test.goindex 34cd736a3..fc2643da6 100644--- a/backend/pkg/projects/fs_util_test.go+++ b/backend/pkg/projects/fs_util_test.go@@ -104,53 +104,3 @@ func TestReadProjectFiles(t *testing.T) {assert.Equal(t, "TZ=UTC\n", envContent)})}--func TestReadProjectDirectoryFiles_RespectsDepthAndSkipDirectories(t *testing.T) {- projectPath := t.TempDir()-- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "README.md"), []byte("root"), 0o644))- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "shown.txt"), []byte("shown"), 0o644))- require.NoError(t, os.MkdirAll(filepath.Join(projectPath, "nested", "deep"), 0o755))- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "nested", "config.txt"), []byte("nested"), 0o644))- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "nested", "deep", "secret.txt"), []byte("deep"), 0o644))- require.NoError(t, os.MkdirAll(filepath.Join(projectPath, "vendor"), 0o755))- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "vendor", "ignored.txt"), []byte("skip"), 0o644))- require.NoError(t, os.MkdirAll(filepath.Join(projectPath, ".git"), 0o755))- require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".git", "config"), []byte("token=secret"), 0o644))-- t.Run("uses configured max depth", func(t *testing.T) {- dirFiles, err := ReadProjectDirectoryFiles(projectPath, map[string]bool{"shown.txt": true}, 1, "")- require.NoError(t, err)-- relativePaths := make([]string, 0, len(dirFiles))- for _, file := range dirFiles {- relativePaths = append(relativePaths, file.RelativePath)- }-- assert.ElementsMatch(t, []string{"README.md"}, relativePaths)- })-- t.Run("uses configured skip directories", func(t *testing.T) {- dirFiles, err := ReadProjectDirectoryFiles(projectPath, map[string]bool{"shown.txt": true}, 3, "vendor")- require.NoError(t, err)-- relativePaths := make([]string, 0, len(dirFiles))- for _, file := range dirFiles {- relativePaths = append(relativePaths, file.RelativePath)- }-- assert.ElementsMatch(t, []string{"README.md", filepath.Join("nested", "config.txt"), filepath.Join("nested", "deep", "secret.txt")}, relativePaths)- })-- t.Run("always skips git directory", func(t *testing.T) {- dirFiles, err := ReadProjectDirectoryFiles(projectPath, map[string]bool{"shown.txt": true}, 3, "vendor,nested")- require.NoError(t, err)-- relativePaths := make([]string, 0, len(dirFiles))- for _, file := range dirFiles {- relativePaths = append(relativePaths, file.RelativePath)- }-- assert.ElementsMatch(t, []string{"README.md"}, relativePaths)- })-}diff --git a/backend/pkg/projects/project_files.go b/backend/pkg/projects/workspace.gosimilarity index 50%rename from backend/pkg/projects/project_files.gorename to backend/pkg/projects/workspace.goindex 52f74f140..0ffc128fd 100644--- a/backend/pkg/projects/project_files.go+++ b/backend/pkg/projects/workspace.go@@ -1,6 +1,7 @@package projectsimport (+ "bytes""crypto/sha256""encoding/hex""hash"@@ -11,47 +12,44 @@ import ("path""path/filepath""slices"- "strconv""strings"- "unicode/utf8""emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/config"pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace""github.com/getarcaneapp/arcane/types/v2/project"+ workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace")-const (- MaxManagedProjectFileBytes = 1024 * 1024- ProjectFileTreeUseScanDepth = -1- // DefaultProjectFileTreeMaxEntries bounds the file-tree walk so a project- // with a huge data directory cannot stall the details load. Not a user- // setting; pass 0 to use it.- DefaultProjectFileTreeMaxEntries = 2000-)+const ProjectWorkspaceUseScanDepth = -1const (- ErrProjectFileRevisionConflict = errors.Sentinel("project file tree changed; refresh the project and try again")- ErrProjectFileOutsideProjectDirectory = errors.Sentinel("path is outside project directory")- ErrProjectFileProtectedPath = errors.Sentinel("protected project file cannot be modified")- ErrProjectFileSymlinkPath = errors.Sentinel("symlink project paths are not supported")+ ErrProjectWorkspaceRevisionConflict = errors.Sentinel("project workspace changed; refresh it and try again")+ ErrProjectWorkspaceOutsideProjectDirectory = errors.Sentinel("path is outside project directory")+ ErrProjectWorkspaceProtectedPath = errors.Sentinel("protected project configuration cannot be modified through the workspace")+ ErrProjectWorkspaceSymlinkPath = errors.Sentinel("symlink workspace paths are not supported"))-type ProjectFileApplyOptions struct {+type ProjectWorkspaceApplyOptions struct {ExpectedRevision stringMaxDepth intMaxEntries intSkipDirectories stringComposeFileName string+ MaxFileSizeBytes int64}-func ReadProjectFileTree(projectPath string, maxDepth int, skipDirectories, composeFileName string, maxEntries int) ([]project.ProjectFile, string, bool, error) {- if maxDepth == ProjectFileTreeUseScanDepth {- maxDepth = config.LoadProjectFilesConfig().ProjectFileTreeMaxDepth+func ReadProjectWorkspace(projectPath string, maxDepth int, skipDirectories, composeFileName string, maxEntries int, maxFileSizeBytes int64) ([]workspacetypes.FileEntry, string, bool, error) {+ if maxDepth == ProjectWorkspaceUseScanDepth {+ maxDepth = config.LoadProjectWorkspaceConfig().ProjectWorkspaceMaxDepth}if maxEntries <= 0 {- maxEntries = DefaultProjectFileTreeMaxEntries+ maxEntries = config.LoadProjectWorkspaceConfig().ProjectWorkspaceMaxEntries+ }+ if maxFileSizeBytes <= 0 {+ maxFileSizeBytes = workspacepkg.MaxFileSizeBytes(config.LoadProjectWorkspaceConfig().ProjectWorkspaceMaxFileSizeMB)}projectAbs, err := filepath.Abs(projectPath)@@ -66,21 +64,22 @@ func ReadProjectFileTree(projectPath string, maxDepth int, skipDirectories, comp}defer func() { _ = root.Close() }()- walker := &projectFileTreeWalkerInternal{- projectAbs: projectAbs,- maxDepth: maxDepth,- maxEntries: maxEntries,- protected: ProtectedProjectFilePaths(composeFileName),- skipDirs: projectScanSkipDirectorySetInternal(skipDirectories),- files: []project.ProjectFile{},- revisionHash: sha256.New(),+ walker := &projectWorkspaceTreeWalkerInternal{+ projectAbs: projectAbs,+ maxDepth: maxDepth,+ maxEntries: maxEntries,+ maxFileSizeBytes: maxFileSizeBytes,+ protected: ProtectedProjectFilePaths(composeFileName),+ skipDirs: projectScanSkipDirectorySetInternal(skipDirectories),+ files: []workspacetypes.FileEntry{},+ revisionHash: sha256.New(),}if err := fs.WalkDir(root.FS(), ".", walker.visit); err != nil {return nil, "", false, err}- slices.SortFunc(walker.files, func(a, b project.ProjectFile) int {+ slices.SortFunc(walker.files, func(a, b workspacetypes.FileEntry) int {if a.IsDirectory != b.IsDirectory {if a.IsDirectory {return -1@@ -93,28 +92,29 @@ func ReadProjectFileTree(projectPath string, maxDepth int, skipDirectories, compreturn walker.files, hex.EncodeToString(walker.revisionHash.Sum(nil)), walker.truncated, nil}-type projectFileTreeWalkerInternal struct {- projectAbs string- maxDepth int- maxEntries int- protected map[string]bool- skipDirs map[string]bool- files []project.ProjectFile- revisionHash hash.Hash- entryCount int- truncated bool+type projectWorkspaceTreeWalkerInternal struct {+ projectAbs string+ maxDepth int+ maxEntries int+ maxFileSizeBytes int64+ protected map[string]bool+ skipDirs map[string]bool+ files []workspacetypes.FileEntry+ revisionHash hash.Hash+ entryCount int+ truncated bool}-func (w *projectFileTreeWalkerInternal) visit(rel string, entry fs.DirEntry, walkErr error) error {+func (w *projectWorkspaceTreeWalkerInternal) visit(rel string, entry fs.DirEntry, walkErr error) error {if walkErr != nil {// fs.WalkDir reports a directory it could not read by invoking the// callback a second time with the ReadDir error. Skipping keeps the// rest of the tree intact instead of discarding every sibling; the// directory itself was already recorded by the first call. A failure- // on the project root, or one that is not a permission/disappearance+ // on the project workspace root, or one that is not a permission/disappearance// error, stays fatal so real I/O problems remain observable.if rel != "." && entry != nil && entry.IsDir() && (os.IsPermission(walkErr) || os.IsNotExist(walkErr)) {- slog.Debug("Skipping unreadable project subdirectory", "relativePath", rel, "error", walkErr)+ slog.Debug("Skipping unreadable project workspace subdirectory", "relativePath", rel, "error", walkErr)return fs.SkipDir}return walkErr@@ -139,9 +139,6 @@ func (w *projectFileTreeWalkerInternal) visit(rel string, entry fs.DirEntry, walreturn nil}- if entry.Type()&fs.ModeSymlink != 0 {- return nil- }if entry.IsDir() && w.skipDirs[entry.Name()] {return fs.SkipDir}@@ -155,77 +152,98 @@ func (w *projectFileTreeWalkerInternal) visit(rel string, entry fs.DirEntry, walif !os.IsPermission(err) && !os.IsNotExist(err) {return err}- slog.Debug("Skipping unreadable project entry", "relativePath", rel, "error", err)+ slog.Debug("Skipping unreadable project workspace entry", "relativePath", rel, "error", err)if entry.IsDir() {return fs.SkipDir}return nil}- // fs.WalkDir visits entries in deterministic lexical order, so hashing- // in visit order yields a stable revision.isProtected := w.protected[rel]- writeProjectFileRevisionEntryInternal(w.revisionHash, rel, info, entry.IsDir(), isProtected)- w.entryCount++-if isProtected {return nil}+ // Protected Compose configuration is intentionally absent from both the+ // workspace response and its revision so configuration saves cannot make+ // a workspace draft stale.+ kind := "file"+ switch {+ case entry.IsDir():+ kind = "dir"+ case info.Mode()&os.ModeSymlink != 0:+ kind = "symlink"+ case !info.Mode().IsRegular():+ kind = "special"+ }+ pkgutils.WriteFileTreeRevisionEntry(w.revisionHash, rel, kind, info.Size(), info.ModTime().UnixNano(), info.Mode().String(), false)+ w.entryCount+++size := info.Size()if entry.IsDir() {size = 0}- w.files = append(w.files, project.ProjectFile{+ workspaceEntry := workspacetypes.FileEntry{Path: filepath.Join(w.projectAbs, filepath.FromSlash(rel)),RelativePath: rel,Name: entry.Name(),IsDirectory: entry.IsDir(),Size: size,ModTime: info.ModTime(),- Protected: false,- })+ Mode: info.Mode().String(),+ IsSymlink: info.Mode()&os.ModeSymlink != 0,+ }+ switch kind {+ case "dir":+ workspaceEntry.Editable = true+ case "symlink":+ workspaceEntry.ReadOnlyReason = workspacetypes.FileReadOnlySymlink+ if target, err := os.Readlink(workspaceEntry.Path); err == nil {+ workspaceEntry.LinkTarget = target+ }+ case "special":+ workspaceEntry.ReadOnlyReason = workspacetypes.FileReadOnlySpecial+ case "file":+ workspaceEntry.Editable, workspaceEntry.ReadOnlyReason = classifyProjectWorkspaceFileInternal(workspaceEntry.Path, size, w.maxFileSizeBytes)+ }+ w.files = append(w.files, workspaceEntry)return nil}-func ApplyProjectFileDrafts(projectPath string, drafts []project.ProjectFileDraft, opts ProjectFileApplyOptions) error {- if len(drafts) == 0 {- return nil+func classifyProjectWorkspaceFileInternal(filePath string, size, maxFileSizeBytes int64) (bool, string) {+ if size > maxFileSizeBytes {+ return false, workspacetypes.FileReadOnlyTooLarge}-- changes := make([]project.ProjectFileChange, 0, len(drafts))- for _, draft := range drafts {- operation := project.FileOpCreateFile- var content *string- if draft.IsDirectory {- operation = project.FileOpCreateFolder- } else {- content = new(draft.Content)- }- changes = append(changes, project.ProjectFileChange{- Operation: operation,- RelativePath: draft.RelativePath,- Content: content,- })+ content, err := os.ReadFile(filePath)+ if err != nil || !bytes.Equal(bytes.ToValidUTF8(content, []byte{}), content) || bytes.IndexByte(content, 0) >= 0 {+ return false, workspacetypes.FileReadOnlyBinary}-- opts.ExpectedRevision = ""- return ApplyProjectFileChanges(projectPath, changes, opts)+ return true, ""}-func ApplyProjectFileChanges(projectPath string, changes []project.ProjectFileChange, opts ProjectFileApplyOptions) error {+func ApplyProjectWorkspaceChanges(projectPath string, changes []project.WorkspaceFileChange, uploads map[int][]byte, opts ProjectWorkspaceApplyOptions) error {+ if opts.MaxFileSizeBytes <= 0 {+ opts.MaxFileSizeBytes = workspacepkg.MaxFileSizeBytes(workspacepkg.DefaultMaxFileSizeMB)+ }+ uploadReferences := make([]workspacepkg.UploadReference, 0, len(changes))+ for _, change := range changes {+ uploadReferences = append(uploadReferences, workspacepkg.UploadReference{Operation: change.Operation, UploadIndex: change.UploadIndex})+ }+ if err := workspacepkg.ValidateUploadIndices(uploadReferences, len(uploads), project.FileOpCreateFile, project.FileOpUpdateFile); err != nil {+ return err+ }if len(changes) == 0 {return nil}if opts.ExpectedRevision != "" {- _, currentRevision, _, err := ReadProjectFileTree(projectPath, opts.MaxDepth, opts.SkipDirectories, opts.ComposeFileName, opts.MaxEntries)+ _, currentRevision, _, err := ReadProjectWorkspace(projectPath, opts.MaxDepth, opts.SkipDirectories, opts.ComposeFileName, opts.MaxEntries, opts.MaxFileSizeBytes)if err != nil {- return errors.WrapIf(err, "read project file tree revision")+ return errors.WrapIf(err, "read project workspace revision")}if currentRevision != opts.ExpectedRevision {- return ErrProjectFileRevisionConflict+ return ErrProjectWorkspaceRevisionConflict}}@@ -237,7 +255,7 @@ func ApplyProjectFileChanges(projectPath string, changes []project.ProjectFileChprotected := ProtectedProjectFilePaths(opts.ComposeFileName)for _, change := range changes {- if err := applyProjectFileChangeInternal(root, protected, change); err != nil {+ if err := applyWorkspaceFileChangeInternal(root, protected, change, uploads, opts.MaxFileSizeBytes); err != nil {return err}}@@ -263,93 +281,39 @@ func ProtectedProjectFilePaths(composeFileName string) map[string]bool {return protected}-func NormalizeProjectRelativePath(input string) (string, error) {- trimmed := strings.TrimSpace(input)- if trimmed == "" {- return "", errors.New("path is required")- }- if strings.ContainsRune(trimmed, 0) {- return "", errors.New("path contains a null byte")- }- if strings.Contains(trimmed, "\\") {- return "", errors.New("path must use forward slashes")- }- if path.IsAbs(trimmed) || filepath.IsAbs(trimmed) {- return "", errors.New("absolute paths are not allowed")- }-- cleaned := path.Clean(trimmed)- if cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, "../") {- return "", errors.New("path traversal is not allowed")- }- for segment := range strings.SplitSeq(cleaned, "/") {- if segment == "" || segment == "." || segment == ".." {- return "", errors.New("path contains an invalid segment")- }- }-- return cleaned, nil-}--func ValidateProjectFileName(name string) (string, error) {- trimmed := strings.TrimSpace(name)- if trimmed == "" {- return "", errors.New("name is required")- }- if strings.ContainsRune(trimmed, 0) {- return "", errors.New("name contains a null byte")- }- if strings.Contains(trimmed, "/") || strings.Contains(trimmed, "\\") {- return "", errors.New("name must not contain path separators")- }- if filepath.VolumeName(trimmed) != "" {- return "", errors.New("name must not contain a volume prefix")- }- if trimmed == "." || trimmed == ".." || filepath.Base(trimmed) != trimmed {- return "", errors.New("invalid name")- }- return trimmed, nil-}--func applyProjectFileChangeInternal(root *os.Root, protected map[string]bool, change project.ProjectFileChange) error {- rel, err := NormalizeProjectRelativePath(change.RelativePath)+func applyWorkspaceFileChangeInternal(root *os.Root, protected map[string]bool, change project.WorkspaceFileChange, uploads map[int][]byte, maxFileSizeBytes int64) error {+ rel, err := pkgutils.NormalizeRelativePath(change.RelativePath)if err != nil {- return errors.WrapIf(err, "invalid project file path")+ return errors.WrapIf(err, "invalid project workspace path")}switch change.Operation {case project.FileOpCreateFile:- if change.Content == nil {- return errors.New("file content is required")- }- return createManagedProjectFileInternal(root, protected, rel, *change.Content)+ return createProjectWorkspaceFileInternal(root, protected, rel, uploads[*change.UploadIndex], maxFileSizeBytes)case project.FileOpCreateFolder:- return createManagedProjectFolderInternal(root, protected, rel)+ return createProjectWorkspaceFolderInternal(root, protected, rel)case project.FileOpUpdateFile:- if change.Content == nil {- return errors.New("file content is required")- }- return updateManagedProjectFileInternal(root, protected, rel, *change.Content)+ return updateProjectWorkspaceFileInternal(root, protected, rel, uploads[*change.UploadIndex], maxFileSizeBytes)case project.FileOpRename:- newName, err := ValidateProjectFileName(change.NewName)+ newName, err := pkgutils.ValidateFileName(change.NewName)if err != nil {- return errors.WrapIf(err, "invalid project file name")+ return errors.WrapIf(err, "invalid project workspace file name")}- return renameManagedProjectPathInternal(root, protected, rel, newName)+ return renameProjectWorkspacePathInternal(root, protected, rel, newName)case project.FileOpMove:- return moveManagedProjectPathInternal(root, protected, rel, change.NewParentPath)+ return moveProjectWorkspacePathInternal(root, protected, rel, change.NewParentPath)case project.FileOpDelete:- return deleteManagedProjectPathInternal(root, protected, rel, change.Recursive)+ return deleteProjectWorkspacePathInternal(root, protected, rel, change.Recursive)default:- return errors.Errorf("unsupported project file operation %q", change.Operation)+ return errors.Errorf("unsupported project workspace operation %q", change.Operation)}}-func createManagedProjectFileInternal(root *os.Root, protected map[string]bool, rel, content string) error {+func createProjectWorkspaceFileInternal(root *os.Root, protected map[string]bool, rel string, content []byte, maxFileSizeBytes int64) error {if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {return err}- if err := validateProjectTextContentInternal(content); err != nil {+ if err := workspacepkg.ValidateTextContent(content, maxFileSizeBytes); err != nil {return err}if err := ensureProjectPathHasNoSymlinkInternal(root, path.Dir(rel)); err != nil {@@ -365,21 +329,21 @@ func createManagedProjectFileInternal(root *os.Root, protected map[string]bool,f, err := root.OpenFile(rel, os.O_WRONLY|os.O_CREATE|os.O_EXCL, pkgutils.FilePerm)if err != nil {if errors.Is(err, os.ErrExist) {- return errors.Errorf("project file already exists: %s", rel)+ return errors.Errorf("project workspace file already exists: %s", rel)}- return errors.WrapIf(err, "create project file")+ return errors.WrapIf(err, "create project workspace file")}- _, writeErr := f.WriteString(content)+ _, writeErr := f.Write(content)if closeErr := f.Close(); writeErr == nil {writeErr = closeErr}if writeErr != nil {- return errors.WrapIf(writeErr, "create project file")+ return errors.WrapIf(writeErr, "create project workspace file")}return nil}-func createManagedProjectFolderInternal(root *os.Root, protected map[string]bool, rel string) error {+func createProjectWorkspaceFolderInternal(root *os.Root, protected map[string]bool, rel string) error {if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {return err}@@ -388,21 +352,21 @@ func createManagedProjectFolderInternal(root *os.Root, protected map[string]bool}if _, err := root.Lstat(rel); err == nil {- return errors.Errorf("project folder already exists: %s", rel)+ return errors.Errorf("project workspace folder already exists: %s", rel)} else if !errors.Is(err, os.ErrNotExist) {- return errors.WrapIf(err, "inspect project folder")+ return errors.WrapIf(err, "inspect project workspace folder")}if err := root.MkdirAll(rel, pkgutils.DirPerm); err != nil {- return errors.WrapIf(err, "create project folder")+ return errors.WrapIf(err, "create project workspace folder")}return nil}-func updateManagedProjectFileInternal(root *os.Root, protected map[string]bool, rel, content string) error {+func updateProjectWorkspaceFileInternal(root *os.Root, protected map[string]bool, rel string, content []byte, maxFileSizeBytes int64) error {if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {return err}- if err := validateProjectTextContentInternal(content); err != nil {+ if err := workspacepkg.ValidateTextContent(content, maxFileSizeBytes); err != nil {return err}if err := ensureProjectPathHasNoSymlinkInternal(root, rel); err != nil {@@ -412,24 +376,24 @@ func updateManagedProjectFileInternal(root *os.Root, protected map[string]bool,info, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return errors.Errorf("project file not found: %s", rel)+ return errors.Errorf("project workspace file not found: %s", rel)}- return errors.WrapIf(err, "inspect project file")+ return errors.WrapIf(err, "inspect project workspace file")}if info.IsDir() {return errors.Errorf("path is a folder: %s", rel)}if info.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink files are not supported")+ return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink files are not supported")}- if err := root.WriteFile(rel, []byte(content), pkgutils.FilePerm); err != nil {- return errors.WrapIf(err, "update project file")+ if err := root.WriteFile(rel, content, pkgutils.FilePerm); err != nil {+ return errors.WrapIf(err, "update project workspace file")}return nil}-func renameManagedProjectPathInternal(root *os.Root, protected map[string]bool, rel, newName string) error {+func renameProjectWorkspacePathInternal(root *os.Root, protected map[string]bool, rel, newName string) error {if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {return err}@@ -440,12 +404,12 @@ func renameManagedProjectPathInternal(root *os.Root, protected map[string]bool,info, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return errors.Errorf("project path not found: %s", rel)+ return errors.Errorf("project workspace path not found: %s", rel)}- return errors.WrapIf(err, "inspect project path")+ return errors.WrapIf(err, "inspect project workspace path")}if info.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink paths are not supported")+ return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink paths are not supported")}targetRel := path.Join(path.Dir(rel), newName)@@ -456,13 +420,13 @@ func renameManagedProjectPathInternal(root *os.Root, protected map[string]bool,return err}if _, err := root.Lstat(targetRel); err == nil {- return errors.Errorf("project path already exists: %s", targetRel)+ return errors.Errorf("project workspace path already exists: %s", targetRel)} else if !errors.Is(err, os.ErrNotExist) {- return errors.WrapIf(err, "inspect project path")+ return errors.WrapIf(err, "inspect project workspace path")}if err := root.Rename(rel, targetRel); err != nil {- return errors.WrapIf(err, "rename project path")+ return errors.WrapIf(err, "rename project workspace path")}return nil}@@ -471,10 +435,10 @@ func normalizeOptionalProjectParentPathInternal(input string) (string, error) {if strings.TrimSpace(input) == "" {return "", nil}- return NormalizeProjectRelativePath(input)+ return pkgutils.NormalizeRelativePath(input)}-func moveManagedProjectPathInternal(root *os.Root, protected map[string]bool, rel, newParentPath string) error {+func moveProjectWorkspacePathInternal(root *os.Root, protected map[string]bool, rel, newParentPath string) error {if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {return err}@@ -484,7 +448,7 @@ func moveManagedProjectPathInternal(root *os.Root, protected map[string]bool, reparentRel, err := normalizeOptionalProjectParentPathInternal(newParentPath)if err != nil {- return errors.WrapIf(err, "invalid project parent path")+ return errors.WrapIf(err, "invalid project workspace parent path")}if parentRel != "" {if err := ensureWritableProjectRelPathInternal(protected, parentRel); err != nil {@@ -495,14 +459,14 @@ func moveManagedProjectPathInternal(root *os.Root, protected map[string]bool, resourceInfo, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return errors.Errorf("project path not found: %s", rel)+ return errors.Errorf("project workspace path not found: %s", rel)}- return errors.WrapIf(err, "inspect project path")+ return errors.WrapIf(err, "inspect project workspace path")}if sourceInfo.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink paths are not supported")+ return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink paths are not supported")}- if sourceInfo.IsDir() && parentRel != "" && projectFilePathMatchesInternal(parentRel, rel) {+ if sourceInfo.IsDir() && parentRel != "" && pkgutils.FilePathMatches(parentRel, rel) {return errors.New("folder cannot be moved into itself or a descendant")}@@ -515,7 +479,7 @@ func moveManagedProjectPathInternal(root *os.Root, protected map[string]bool, retargetRel = path.Join(parentRel, path.Base(rel))}if targetRel == rel {- return errors.New("project path is already in the destination folder")+ return errors.New("project workspace path is already in the destination folder")}if err := ensureWritableProjectRelPathInternal(protected, targetRel); err != nil {return err@@ -524,13 +488,13 @@ func moveManagedProjectPathInternal(root *os.Root, protected map[string]bool, rereturn err}if _, err := root.Lstat(targetRel); err == nil {- return errors.Errorf("project path already exists: %s", targetRel)+ return errors.Errorf("project workspace path already exists: %s", targetRel)} else if !errors.Is(err, os.ErrNotExist) {- return errors.WrapIf(err, "inspect project path")+ return errors.WrapIf(err, "inspect project workspace path")}if err := root.Rename(rel, targetRel); err != nil {- return errors.WrapIf(err, "move project path")+ return errors.WrapIf(err, "move project workspace path")}return nil}@@ -551,7 +515,7 @@ func validateProjectMoveParentInternal(root *os.Root, parentRel string) error {return errors.WrapIf(err, "inspect destination folder")}if parentInfo.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink destination folders are not supported")+ return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink destination folders are not supported")}if !parentInfo.IsDir() {return errors.Errorf("destination path is not a folder: %s", parentRel)@@ -559,7 +523,7 @@ func validateProjectMoveParentInternal(root *os.Root, parentRel string) error {return nil}-func deleteManagedProjectPathInternal(root *os.Root, protected map[string]bool, rel string, recursive bool) error {+func deleteProjectWorkspacePathInternal(root *os.Root, protected map[string]bool, rel string, recursive bool) error {if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {return err}@@ -570,12 +534,12 @@ func deleteManagedProjectPathInternal(root *os.Root, protected map[string]bool,info, err := root.Lstat(rel)if err != nil {if errors.Is(err, os.ErrNotExist) {- return errors.Errorf("project path not found: %s", rel)+ return errors.Errorf("project workspace path not found: %s", rel)}- return errors.WrapIf(err, "inspect project path")+ return errors.WrapIf(err, "inspect project workspace path")}if info.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink paths are not supported")+ return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink paths are not supported")}if info.IsDir() && !recursive {empty, err := isDirectoryEmptyInternal(root, rel)@@ -589,12 +553,12 @@ func deleteManagedProjectPathInternal(root *os.Root, protected map[string]bool,if info.IsDir() {if err := root.RemoveAll(rel); err != nil {- return errors.WrapIf(err, "delete project folder")+ return errors.WrapIf(err, "delete project workspace folder")}return nil}if err := root.Remove(rel); err != nil {- return errors.WrapIf(err, "delete project file")+ return errors.WrapIf(err, "delete project workspace file")}return nil}@@ -618,10 +582,10 @@ func ensureProjectPathHasNoSymlinkInternal(root *os.Root, rel string) error {if errors.Is(err, os.ErrNotExist) {return nil}- return errors.WrapIf(err, "inspect project path")+ return errors.WrapIf(err, "inspect project workspace path")}if info.Mode()&os.ModeSymlink != 0 {- return errors.WrapIf(ErrProjectFileSymlinkPath, "symlink paths are not supported")+ return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink paths are not supported")}}return nil@@ -629,25 +593,11 @@ func ensureProjectPathHasNoSymlinkInternal(root *os.Root, rel string) error {func ensureWritableProjectRelPathInternal(protected map[string]bool, rel string) error {if rel == "." || rel == "" {- return errors.New("project root cannot be modified")+ return errors.New("project workspace root cannot be modified")}rootName, _, _ := strings.Cut(rel, "/")if protected[rel] || protected[rootName] {- return errors.WrapIff(ErrProjectFileProtectedPath, "%s", rel)- }- return nil-}--func projectFilePathMatchesInternal(relativePath string, rootPath string) bool {- return relativePath == rootPath || strings.HasPrefix(relativePath, rootPath+"/")-}--func validateProjectTextContentInternal(content string) error {- if len(content) > MaxManagedProjectFileBytes {- return errors.Errorf("file exceeds %d byte limit", MaxManagedProjectFileBytes)- }- if !utf8.ValidString(content) || strings.IndexByte(content, 0) >= 0 {- return errors.New("binary files are not supported")+ return errors.WrapIff(ErrProjectWorkspaceProtectedPath, "%s", rel)}return nil}@@ -668,25 +618,3 @@ func isDirectoryEmptyInternal(root *os.Root, rel string) (bool, error) {}return false, nil}--func writeProjectFileRevisionEntryInternal(h hash.Hash, rel string, info fs.FileInfo, isDir, protected bool) {- kind := "file"- if isDir {- kind = "dir"- }- protectedFlag := ""- if protected {- protectedFlag = "protected"- }-- entry := strings.Join([]string{- rel,- kind,- strconv.FormatInt(info.Size(), 10),- strconv.FormatInt(info.ModTime().UnixNano(), 10),- info.Mode().String(),- protectedFlag,- }, "\x00")- _, _ = io.WriteString(h, entry)- _, _ = h.Write([]byte{'\n'})-}diff --git a/backend/pkg/projects/project_files_test.go b/backend/pkg/projects/workspace_test.gosimilarity index 66%rename from backend/pkg/projects/project_files_test.gorename to backend/pkg/projects/workspace_test.goindex 29064bcb8..bad5ae9f6 100644--- a/backend/pkg/projects/project_files_test.go+++ b/backend/pkg/projects/workspace_test.go@@ -7,12 +7,13 @@ import ("strings""testing"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/project""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")-func TestReadProjectFileTree_ExcludesProtectedFilesAndReturnsFolders(t *testing.T) {+func TestReadProjectWorkspace_ExcludesProtectedFilesAndReturnsFolders(t *testing.T) {t.Parallel()projectDir := t.TempDir()@@ -26,7 +27,7 @@ func TestReadProjectFileTree_ExcludesProtectedFilesAndReturnsFolders(t *testing.require.NoError(t, os.MkdirAll(filepath.Join(projectDir, ".git"), 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectDir, ".git", "config"), []byte("private"), 0o644))- files, revision, _, err := ReadProjectFileTree(projectDir, 3, "", "compose.yaml", 0)+ files, revision, _, err := ReadProjectWorkspace(projectDir, 3, "", "compose.yaml", 0, 0)require.NoError(t, err)require.NotEmpty(t, revision)@@ -38,7 +39,7 @@ func TestReadProjectFileTree_ExcludesProtectedFilesAndReturnsFolders(t *testing.assert.ElementsMatch(t, []string{"README.md", "config", filepath.ToSlash(filepath.Join("config", "app.yaml")), filepath.ToSlash(filepath.Join("config", "nested"))}, relativePaths)}-func TestReadProjectFileTree_ZeroMaxDepthDisablesExpansion(t *testing.T) {+func TestReadProjectWorkspace_ZeroMaxDepthDisablesExpansion(t *testing.T) {t.Parallel()projectDir := t.TempDir()@@ -46,22 +47,22 @@ func TestReadProjectFileTree_ZeroMaxDepthDisablesExpansion(t *testing.T) {require.NoError(t, os.MkdirAll(filepath.Join(projectDir, "config"), 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectDir, "config", "app.yaml"), []byte("value: true\n"), 0o644))- files, revision, _, err := ReadProjectFileTree(projectDir, 0, "", "compose.yaml", 0)+ files, revision, _, err := ReadProjectWorkspace(projectDir, 0, "", "compose.yaml", 0, 0)require.NoError(t, err)assert.NotEmpty(t, revision)assert.Empty(t, files)}-func TestReadProjectFileTree_UseScanDepthSentinelUsesFileTreeMaxDepth(t *testing.T) {+func TestReadProjectWorkspace_UseScanDepthSentinelUsesWorkspaceMaxDepth(t *testing.T) {projectDir := t.TempDir()- t.Setenv("PROJECT_FILE_TREE_MAX_DEPTH", "2")+ t.Setenv("PROJECT_WORKSPACE_MAX_DEPTH", "2")require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte("services: {}\n"), 0o644))require.NoError(t, os.MkdirAll(filepath.Join(projectDir, "level1", "level2"), 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectDir, "level1", "visible.txt"), []byte("visible\n"), 0o644))require.NoError(t, os.WriteFile(filepath.Join(projectDir, "level1", "level2", "hidden.txt"), []byte("hidden\n"), 0o644))- files, _, _, err := ReadProjectFileTree(projectDir, ProjectFileTreeUseScanDepth, "", "compose.yaml", 0)+ files, _, _, err := ReadProjectWorkspace(projectDir, ProjectWorkspaceUseScanDepth, "", "compose.yaml", 0, 0)require.NoError(t, err)relativePaths := make([]string, 0, len(files))@@ -75,7 +76,7 @@ func TestReadProjectFileTree_UseScanDepthSentinelUsesFileTreeMaxDepth(t *testingassert.NotContains(t, relativePaths, filepath.ToSlash(filepath.Join("level1", "level2", "hidden.txt")))}-func TestApplyProjectFileChanges_RejectsUnsafePathsAndProtectedFiles(t *testing.T) {+func TestApplyWorkspaceFileChanges_RejectsUnsafePathsAndProtectedFiles(t *testing.T) {t.Parallel()projectDir := t.TempDir()@@ -83,26 +84,28 @@ func TestApplyProjectFileChanges_RejectsUnsafePathsAndProtectedFiles(t *testing.testCases := []struct {name string- change project.ProjectFileChange+ change project.WorkspaceFileChange+ upload []byte}{{name: "traversal",- change: project.ProjectFileChange{+ change: project.WorkspaceFileChange{Operation: "create_file",RelativePath: "../escape.txt",- Content: new("safe\n"),+ UploadIndex: new(0),},+ upload: []byte("safe\n"),},{name: "protected compose",- change: project.ProjectFileChange{+ change: project.WorkspaceFileChange{Operation: "delete",RelativePath: "compose.yaml",},},{name: "move protected compose",- change: project.ProjectFileChange{+ change: project.WorkspaceFileChange{Operation: "move",RelativePath: "compose.yaml",NewParentPath: "config",@@ -110,41 +113,47 @@ func TestApplyProjectFileChanges_RejectsUnsafePathsAndProtectedFiles(t *testing.},{name: "protected compose descendant",- change: project.ProjectFileChange{+ change: project.WorkspaceFileChange{Operation: "create_file",RelativePath: "compose.yaml/child.yaml",- Content: new("bad\n"),+ UploadIndex: new(0),},+ upload: []byte("bad\n"),},{name: "binary content",- change: project.ProjectFileChange{+ change: project.WorkspaceFileChange{Operation: "create_file",RelativePath: "binary.txt",- Content: new(string([]byte{0})),+ UploadIndex: new(0),},+ upload: []byte{0},},}for _, tc := range testCases {t.Run(tc.name, func(t *testing.T) {- err := ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{tc.change}, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})+ uploads := map[int][]byte{}+ if tc.upload != nil {+ uploads[0] = tc.upload+ }+ err := ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{tc.change}, uploads, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml"})require.Error(t, err)})}}-func TestApplyProjectFileChanges_WrapsForbiddenSentinelErrors(t *testing.T) {+func TestApplyWorkspaceFileChanges_WrapsForbiddenSentinelErrors(t *testing.T) {t.Parallel()projectDir := t.TempDir()require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte("services: {}\n"), 0o644))- err := ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{+ err := ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{{Operation: "delete", RelativePath: "compose.yaml"},- }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})+ }, nil, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml"})require.Error(t, err)- require.ErrorIs(t, err, ErrProjectFileProtectedPath)+ require.ErrorIs(t, err, ErrProjectWorkspaceProtectedPath)targetPath := filepath.Join(projectDir, "target.txt")linkPath := filepath.Join(projectDir, "link.txt")@@ -153,12 +162,12 @@ func TestApplyProjectFileChanges_WrapsForbiddenSentinelErrors(t *testing.T) {t.Skipf("symlink creation is unavailable: %v", err)}- content := "updated\n"- err = ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{- {Operation: "update_file", RelativePath: "link.txt", Content: &content},- }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})+ content := []byte("updated\n")+ err = ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{+ {Operation: "update_file", RelativePath: "link.txt", UploadIndex: new(0)},+ }, map[int][]byte{0: content}, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml"})require.Error(t, err)- require.ErrorIs(t, err, ErrProjectFileSymlinkPath)+ require.ErrorIs(t, err, ErrProjectWorkspaceSymlinkPath)outsideDir := t.TempDir()require.NoError(t, os.WriteFile(filepath.Join(outsideDir, "outside.txt"), []byte("outside\n"), 0o644))@@ -167,56 +176,56 @@ func TestApplyProjectFileChanges_WrapsForbiddenSentinelErrors(t *testing.T) {t.Skipf("symlink creation is unavailable: %v", err)}- err = ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{- {Operation: "update_file", RelativePath: "link-dir/outside.txt", Content: &content},- }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})+ err = ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{+ {Operation: "update_file", RelativePath: "link-dir/outside.txt", UploadIndex: new(0)},+ }, map[int][]byte{0: content}, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml"})require.Error(t, err)- assert.ErrorIs(t, err, ErrProjectFileSymlinkPath)+ assert.ErrorIs(t, err, ErrProjectWorkspaceSymlinkPath)}-func TestApplyProjectFileChanges_UsesRevisionConflictDetection(t *testing.T) {+func TestApplyWorkspaceFileChanges_UsesRevisionConflictDetection(t *testing.T) {t.Parallel()projectDir := t.TempDir()require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte("services: {}\n"), 0o644))require.NoError(t, os.WriteFile(filepath.Join(projectDir, "notes.txt"), []byte("old\n"), 0o644))- _, revision, _, err := ReadProjectFileTree(projectDir, 3, "", "compose.yaml", 0)+ _, revision, _, err := ReadProjectWorkspace(projectDir, 3, "", "compose.yaml", 0, 0)require.NoError(t, err)require.NoError(t, os.WriteFile(filepath.Join(projectDir, "notes.txt"), []byte("changed elsewhere\n"), 0o644))- err = ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{- {Operation: "update_file", RelativePath: "notes.txt", Content: new("new\n")},- }, ProjectFileApplyOptions{+ err = ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{+ {Operation: "update_file", RelativePath: "notes.txt", UploadIndex: new(0)},+ }, map[int][]byte{0: []byte("new\n")}, ProjectWorkspaceApplyOptions{ExpectedRevision: revision,ComposeFileName: "compose.yaml",})require.Error(t, err)- assert.ErrorIs(t, err, ErrProjectFileRevisionConflict)+ assert.ErrorIs(t, err, ErrProjectWorkspaceRevisionConflict)}-func TestApplyProjectFileChanges_AppliesOrderedTextFileOperations(t *testing.T) {+func TestApplyWorkspaceFileChanges_AppliesOrderedTextFileOperations(t *testing.T) {t.Parallel()projectDir := t.TempDir()require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte("services: {}\n"), 0o644))- updated := "updated\n"- err := ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{+ updated := []byte("updated\n")+ err := ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{{Operation: "create_folder", RelativePath: "config"},- {Operation: "create_file", RelativePath: "config/app.yaml", Content: new("hello\n")},- {Operation: "update_file", RelativePath: "config/app.yaml", Content: &updated},+ {Operation: "create_file", RelativePath: "config/app.yaml", UploadIndex: new(0)},+ {Operation: "update_file", RelativePath: "config/app.yaml", UploadIndex: new(1)},{Operation: "rename", RelativePath: "config/app.yaml", NewName: "renamed.yaml"},- }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})+ }, map[int][]byte{0: []byte("hello\n"), 1: updated}, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml"})require.NoError(t, err)bytes, err := os.ReadFile(filepath.Join(projectDir, "config", "renamed.yaml"))require.NoError(t, err)- assert.Equal(t, updated, string(bytes))+ assert.Equal(t, string(updated), string(bytes))}-func TestApplyProjectFileChanges_MovesProjectPaths(t *testing.T) {+func TestApplyWorkspaceFileChanges_MovesProjectPaths(t *testing.T) {t.Parallel()projectDir := t.TempDir()@@ -226,10 +235,10 @@ func TestApplyProjectFileChanges_MovesProjectPaths(t *testing.T) {require.NoError(t, os.WriteFile(filepath.Join(projectDir, "config", "app.yaml"), []byte("value: true\n"), 0o644))require.NoError(t, os.WriteFile(filepath.Join(projectDir, "config", "nested", "child.txt"), []byte("child\n"), 0o644))- err := ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{+ err := ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{{Operation: "move", RelativePath: "config/app.yaml", NewParentPath: "archive"},{Operation: "move", RelativePath: "config/nested"},- }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})+ }, nil, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml"})require.NoError(t, err)assert.NoFileExists(t, filepath.Join(projectDir, "config", "app.yaml"))@@ -238,7 +247,7 @@ func TestApplyProjectFileChanges_MovesProjectPaths(t *testing.T) {assert.FileExists(t, filepath.Join(projectDir, "nested", "child.txt"))}-func TestApplyProjectFileChanges_RejectsInvalidMoves(t *testing.T) {+func TestApplyWorkspaceFileChanges_RejectsInvalidMoves(t *testing.T) {t.Parallel()testCases := []struct {@@ -251,7 +260,7 @@ func TestApplyProjectFileChanges_RejectsInvalidMoves(t *testing.T) {name: "duplicate destination",relativePath: "config/app.yaml",newParentPath: "archive",- wantError: "project path already exists",+ wantError: "project workspace path already exists",},{name: "folder into descendant",@@ -284,16 +293,16 @@ func TestApplyProjectFileChanges_RejectsInvalidMoves(t *testing.T) {require.NoError(t, os.WriteFile(filepath.Join(projectDir, "config", "app.yaml"), []byte("value: true\n"), 0o644))require.NoError(t, os.WriteFile(filepath.Join(projectDir, "archive", "app.yaml"), []byte("existing\n"), 0o644))- err := ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{+ err := ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{{Operation: "move", RelativePath: tc.relativePath, NewParentPath: tc.newParentPath},- }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})+ }, nil, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml"})require.Error(t, err)assert.Contains(t, err.Error(), tc.wantError)})}}-func TestApplyProjectFileChanges_RequiresRecursiveForNonEmptyFolderDelete(t *testing.T) {+func TestApplyWorkspaceFileChanges_RequiresRecursiveForNonEmptyFolderDelete(t *testing.T) {t.Parallel()projectDir := t.TempDir()@@ -301,28 +310,35 @@ func TestApplyProjectFileChanges_RequiresRecursiveForNonEmptyFolderDelete(t *tesrequire.NoError(t, os.MkdirAll(filepath.Join(projectDir, "config"), 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectDir, "config", "app.yaml"), []byte("value: true\n"), 0o644))- err := ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{+ err := ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{{Operation: "delete", RelativePath: "config"},- }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})+ }, nil, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml"})require.Error(t, err)assert.Contains(t, err.Error(), "folder is not empty")- err = ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{+ err = ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{{Operation: "delete", RelativePath: "config", Recursive: true},- }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})+ }, nil, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml"})require.NoError(t, err)_, err = os.Stat(filepath.Join(projectDir, "config"))assert.True(t, os.IsNotExist(err))}-func TestValidateProjectFileName_RejectsPathSeparators(t *testing.T) {+func TestApplyProjectWorkspaceChangesRejectsUnusedUploadsForEmptyManifest(t *testing.T) {t.Parallel()- _, err := ValidateProjectFileName(strings.Join([]string{"folder", "name"}, string(filepath.Separator)))+ err := ApplyProjectWorkspaceChanges(t.TempDir(), nil, map[int][]byte{0: []byte("unused")}, ProjectWorkspaceApplyOptions{})+ require.ErrorContains(t, err, "unused")+}++func TestValidateProjectWorkspaceFileName_RejectsPathSeparators(t *testing.T) {+ t.Parallel()++ _, err := utils.ValidateFileName(strings.Join([]string{"folder", "name"}, string(filepath.Separator)))require.Error(t, err)}-func TestReadProjectFileTree_CapsEntriesWithStableRevision(t *testing.T) {+func TestReadProjectWorkspace_CapsEntriesWithStableRevision(t *testing.T) {t.Parallel()projectDir := t.TempDir()@@ -331,20 +347,18 @@ func TestReadProjectFileTree_CapsEntriesWithStableRevision(t *testing.T) {require.NoError(t, os.WriteFile(filepath.Join(projectDir, fmt.Sprintf("file-%d.txt", i)), []byte("x\n"), 0o644))}- files, revision, truncated, err := ReadProjectFileTree(projectDir, 3, "", "compose.yaml", 3)+ files, revision, truncated, err := ReadProjectWorkspace(projectDir, 3, "", "compose.yaml", 3, 0)require.NoError(t, err)assert.True(t, truncated)- // compose.yaml is hashed but protected (not returned), so the cap of 3- // hashed entries yields 2 listed files.- assert.Len(t, files, 2)+ assert.Len(t, files, 3)- _, again, truncatedAgain, err := ReadProjectFileTree(projectDir, 3, "", "compose.yaml", 3)+ _, again, truncatedAgain, err := ReadProjectWorkspace(projectDir, 3, "", "compose.yaml", 3, 0)require.NoError(t, err)assert.True(t, truncatedAgain)assert.Equal(t, revision, again)}-func TestApplyProjectFileChanges_SucceedsWithCappedRevision(t *testing.T) {+func TestApplyWorkspaceFileChanges_SucceedsWithCappedRevision(t *testing.T) {t.Parallel()projectDir := t.TempDir()@@ -353,13 +367,13 @@ func TestApplyProjectFileChanges_SucceedsWithCappedRevision(t *testing.T) {require.NoError(t, os.WriteFile(filepath.Join(projectDir, fmt.Sprintf("file-%d.txt", i)), []byte("x\n"), 0o644))}- _, revision, truncated, err := ReadProjectFileTree(projectDir, 3, "", "compose.yaml", 3)+ _, revision, truncated, err := ReadProjectWorkspace(projectDir, 3, "", "compose.yaml", 3, 0)require.NoError(t, err)require.True(t, truncated)- err = ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{- {Operation: "update_file", RelativePath: "file-0.txt", Content: new("new\n")},- }, ProjectFileApplyOptions{+ err = ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{+ {Operation: "update_file", RelativePath: "file-0.txt", UploadIndex: new(0)},+ }, map[int][]byte{0: []byte("new\n")}, ProjectWorkspaceApplyOptions{ExpectedRevision: revision,MaxDepth: 3,MaxEntries: 3,diff --git a/backend/pkg/projects/project_files_unix_test.go b/backend/pkg/projects/workspace_unix_test.gosimilarity index 82%rename from backend/pkg/projects/project_files_unix_test.gorename to backend/pkg/projects/workspace_unix_test.goindex 50eebf7db..1b7819a80 100644--- a/backend/pkg/projects/project_files_unix_test.go+++ b/backend/pkg/projects/workspace_unix_test.go@@ -14,8 +14,8 @@ import (// Reproduces issue #3309: a project directory containing a bind-mount data// folder Arcane cannot read must still list everything else. Before the fix a// single EACCES from fs.WalkDir aborted the walk, so the whole tree (and the-// revision that gates file edits) came back empty.-func TestReadProjectFileTree_SkipsUnreadableDirectory(t *testing.T) {+// revision that gates workspace edits) came back empty.+func TestReadProjectWorkspace_SkipsUnreadableDirectory(t *testing.T) {if os.Geteuid() == 0 {t.Skip("permission bits are ignored when running as root")}@@ -32,9 +32,9 @@ func TestReadProjectFileTree_SkipsUnreadableDirectory(t *testing.T) {// Restore before t.TempDir's own cleanup runs, or it cannot remove the tree.t.Cleanup(func() { _ = os.Chmod(workdir, 0o755) })- files, revision, _, err := ReadProjectFileTree(projectDir, 5, "", "compose.yaml", 0)+ files, revision, _, err := ReadProjectWorkspace(projectDir, 5, "", "compose.yaml", 0, 0)require.NoError(t, err)- require.NotEmpty(t, revision, "an empty revision blocks every project file edit")+ require.NotEmpty(t, revision, "an empty revision blocks every project workspace edit")relativePaths := make([]string, 0, len(files))for _, file := range files {@@ -51,9 +51,9 @@ func TestReadProjectFileTree_SkipsUnreadableDirectory(t *testing.T) {"volumes/adguard-home/workdir",}, relativePaths)- // The compare walk in ApplyProjectFileChanges skips identically, so the+ // The compare walk in ApplyWorkspaceFileChanges skips identically, so the// optimistic-concurrency check does not spuriously conflict.- _, again, _, err := ReadProjectFileTree(projectDir, 5, "", "compose.yaml", 0)+ _, again, _, err := ReadProjectWorkspace(projectDir, 5, "", "compose.yaml", 0, 0)require.NoError(t, err)assert.Equal(t, revision, again)}diff --git a/backend/pkg/scheduler/volume_helper_reaper_job.go b/backend/pkg/scheduler/volume_helper_reaper_job.goindex 9be277f3f..be664f109 100644--- a/backend/pkg/scheduler/volume_helper_reaper_job.go+++ b/backend/pkg/scheduler/volume_helper_reaper_job.go@@ -13,15 +13,15 @@ const (PruningVolumeHelperJobName = "pruning-volume-helper"// volumeHelperIdleTimeoutSetting is the settings key (in minutes) controlling how- // long a volume-browser helper container may sit idle before it is reaped.- volumeHelperIdleTimeoutSetting = "volumeBrowserHelperIdleTimeout"+ // long a volume workspace helper container may sit idle before it is reaped.+ volumeHelperIdleTimeoutSetting = "volumeHelperIdleTimeout"defaultVolumeHelperIdleTimeoutMinutes = 10volumeHelperPruningSchedule = "0 */5 * * * *")-// PruningVolumeHelperJob periodically removes idle volume-browser helper+// PruningVolumeHelperJob periodically removes idle volume workspace helper// containers. The run frequency is fixed (every 5 minutes); how stale a helper must-// be to be pruned is driven by the volumeBrowserHelperIdleTimeout setting.+// be pruned is driven by the volumeHelperIdleTimeout setting.type PruningVolumeHelperJob struct {volumeService *volume.VolumeServicesettingsService *settings.SettingsServicediff --git a/backend/pkg/utils/handlerutil/handlerutil.go b/backend/pkg/utils/handlerutil/handlerutil.goindex 0d04d3c7b..6fc9886af 100644--- a/backend/pkg/utils/handlerutil/handlerutil.go+++ b/backend/pkg/utils/handlerutil/handlerutil.go@@ -2,6 +2,9 @@ package handlerutilimport ("context"+ "encoding/json/v2"+ "fmt"+ "io""mime/multipart""strings"@@ -12,6 +15,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"+ workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace""github.com/getarcaneapp/arcane/types/v2/auth""github.com/getarcaneapp/arcane/types/v2/base")@@ -90,6 +94,59 @@ func OpenUploadedFile(form multipart.Form) (multipart.File, *multipart.FileHeadereturn file, fileHeader, nil}+// ParseMultipartJSONPart decodes one required JSON-valued multipart field.+func ParseMultipartJSONPart[T any](form multipart.Form, partName string) (T, error) {+ var result T+ values := form.Value[partName]+ if len(values) != 1 {+ return result, huma.Error400BadRequest("exactly one " + partName + " part is required")+ }+ if err := json.Unmarshal([]byte(values[0]), &result); err != nil {+ return result, huma.Error400BadRequest("invalid " + partName + " JSON")+ }+ return result, nil+}++// ReadWorkspaceUploads reads and validates text files from a workspace multipart request.+func ReadWorkspaceUploads(form multipart.Form, maxFileSizeBytes int64) (map[int][]byte, error) {+ headers := form.File["files"]+ uploads := make(map[int][]byte, len(headers))+ limitMessage := fmt.Sprintf("uploaded file exceeds configured %d MiB workspace limit", maxFileSizeBytes/(1024*1024))+ for index, header := range headers {+ if header.Size > maxFileSizeBytes {+ return nil, huma.Error413RequestEntityTooLarge(limitMessage)+ }+ file, err := header.Open()+ if err != nil {+ return nil, huma.Error400BadRequest("failed to open uploaded file")+ }+ content, readErr := io.ReadAll(io.LimitReader(file, maxFileSizeBytes+1))+ closeErr := file.Close()+ if readErr != nil {+ return nil, huma.Error400BadRequest("failed to read uploaded file")+ }+ if closeErr != nil {+ return nil, huma.Error400BadRequest("failed to close uploaded file")+ }+ if int64(len(content)) > maxFileSizeBytes {+ return nil, huma.Error413RequestEntityTooLarge(limitMessage)+ }+ if err := workspacepkg.ValidateTextContent(content, maxFileSizeBytes); err != nil {+ return nil, huma.Error400BadRequest(err.Error())+ }+ uploads[index] = content+ }+ return uploads, nil+}++// WorkspaceMultipartRequestBody describes the shared workspace multipart schema.+func WorkspaceMultipartRequestBody(manifestDescription string) *huma.RequestBody {+ return &huma.RequestBody{Content: map[string]*huma.MediaType{"multipart/form-data": {Schema: &huma.Schema{Type: "object", Properties: map[string]*huma.Schema{+ "manifest": {Type: "string", Description: manifestDescription},+ "files": {Type: "array", Items: &huma.Schema{Type: "string", Format: "binary"}},+ }, Required: []string{"manifest"}}}}}+}+func RegisterSecured[I, O any](api huma.API,op huma.Operation,diff --git a/backend/pkg/utils/handlerutil/workspace_test.go b/backend/pkg/utils/handlerutil/workspace_test.gonew file mode 100644index 000000000..8d071e978--- /dev/null+++ b/backend/pkg/utils/handlerutil/workspace_test.go@@ -0,0 +1,99 @@+package handlerutil++import (+ "bytes"+ "mime/multipart"+ "net/http"+ "testing"++ "github.com/danielgtaylor/huma/v2"+ "github.com/stretchr/testify/require"+)++type workspaceUploadFixtureInternal struct {+ name string+ content []byte+}++func workspaceMultipartFormInternal(t *testing.T, values map[string][]string, files []workspaceUploadFixtureInternal) multipart.Form {+ t.Helper()++ var body bytes.Buffer+ writer := multipart.NewWriter(&body)+ for name, entries := range values {+ for _, value := range entries {+ require.NoError(t, writer.WriteField(name, value))+ }+ }+ for _, fixture := range files {+ part, err := writer.CreateFormFile("files", fixture.name)+ require.NoError(t, err)+ _, err = part.Write(fixture.content)+ require.NoError(t, err)+ }+ require.NoError(t, writer.Close())++ request, err := http.NewRequest(http.MethodPut, "/workspace", &body)+ require.NoError(t, err)+ request.Header.Set("Content-Type", writer.FormDataContentType())+ require.NoError(t, request.ParseMultipartForm(int64(body.Len())))+ t.Cleanup(func() { _ = request.MultipartForm.RemoveAll() })+ return *request.MultipartForm+}++func requireWorkspaceHTTPStatusInternal(t *testing.T, err error, expected int) {+ t.Helper()+ var statusErr huma.StatusError+ require.ErrorAs(t, err, &statusErr)+ require.Equal(t, expected, statusErr.GetStatus())+}++func TestParseWorkspaceJSONPartInternalRequiresExactlyOnePart(t *testing.T) {+ type manifest struct {+ Revision string `json:"revision"`+ }++ _, err := ParseMultipartJSONPart[manifest](workspaceMultipartFormInternal(t, nil, nil), "manifest")+ requireWorkspaceHTTPStatusInternal(t, err, http.StatusBadRequest)++ form := workspaceMultipartFormInternal(t, map[string][]string{"manifest": {`{"revision":"one"}`, `{"revision":"two"}`}}, nil)+ _, err = ParseMultipartJSONPart[manifest](form, "manifest")+ requireWorkspaceHTTPStatusInternal(t, err, http.StatusBadRequest)++ form = workspaceMultipartFormInternal(t, map[string][]string{"manifest": {`{"revision":"current"}`}}, nil)+ parsed, err := ParseMultipartJSONPart[manifest](form, "manifest")+ require.NoError(t, err)+ require.Equal(t, "current", parsed.Revision)+}++func TestReadWorkspaceUploadsInternal(t *testing.T) {+ form := workspaceMultipartFormInternal(t, nil, []workspaceUploadFixtureInternal{+ {name: "one.txt", content: []byte("one")},+ {name: "two.txt", content: []byte("two")},+ })+ uploads, err := ReadWorkspaceUploads(form, 16)+ require.NoError(t, err)+ require.Equal(t, []byte("one"), uploads[0])+ require.Equal(t, []byte("two"), uploads[1])+}++func TestReadWorkspaceUploadsInternalRejectsInvalidTextAndConfiguredLimit(t *testing.T) {+ tests := []struct {+ name string+ content []byte+ maxBytes int64+ status int+ }{+ {name: "invalid UTF-8", content: []byte{0xff}, maxBytes: 16, status: http.StatusBadRequest},+ {name: "NUL byte", content: []byte{'a', 0, 'b'}, maxBytes: 16, status: http.StatusBadRequest},+ {name: "configured size", content: []byte("four"), maxBytes: 3, status: http.StatusRequestEntityTooLarge},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ form := workspaceMultipartFormInternal(t, nil, []workspaceUploadFixtureInternal{{name: "upload.txt", content: tt.content}})+ _, err := ReadWorkspaceUploads(form, tt.maxBytes)+ requireWorkspaceHTTPStatusInternal(t, err, tt.status)+ })+ }+}diff --git a/backend/pkg/utils/keyedmutex.go b/backend/pkg/utils/keyedmutex.goindex c1ed1a790..1858866f7 100644--- a/backend/pkg/utils/keyedmutex.go+++ b/backend/pkg/utils/keyedmutex.go@@ -19,7 +19,7 @@ type KeyedMutex struct {}type keyedMutexEntry struct {- mu sync.Mutex+ mu sync.RWMutexrefs int}@@ -65,6 +65,18 @@ func (k *KeyedMutex) Lock(key string) func() {}}+// RLock blocks until the key's mutex is held for reading and returns its+// unlock function. Multiple readers for the same key may proceed concurrently.+func (k *KeyedMutex) RLock(key string) func() {+ entry := k.reserve(key)+ entry.mu.RLock()++ return func() {+ entry.mu.RUnlock()+ k.release(key, entry)+ }+}+// TryLock acquires the key's mutex without blocking. It reports whether the// lock was taken; the unlock function is only valid when it was.func (k *KeyedMutex) TryLock(key string) (func(), bool) {diff --git a/backend/pkg/utils/keyedmutex_test.go b/backend/pkg/utils/keyedmutex_test.goindex d2d4cc2da..132f0777f 100644--- a/backend/pkg/utils/keyedmutex_test.go+++ b/backend/pkg/utils/keyedmutex_test.go@@ -3,6 +3,7 @@ package utilsimport ("sync""testing"+ "time""github.com/stretchr/testify/require")@@ -61,3 +62,48 @@ func TestKeyedMutexTryLockDoesNotBlockOnHeldKey(t *testing.T) {retaken()require.Empty(t, locks.locks)}++func TestKeyedMutexReadLocksShareKeyAndBlockWriter(t *testing.T) {+ var locks KeyedMutex++ firstReadUnlock := locks.RLock("volume")+ secondReadUnlock := locks.RLock("volume")+ writerAcquired := make(chan struct{})+ writerReleased := make(chan struct{})+ go func() {+ defer close(writerReleased)+ defer locks.Lock("volume")()+ close(writerAcquired)+ }()++ require.Never(t, func() bool {+ select {+ case <-writerAcquired:+ return true+ default:+ return false+ }+ }, 50*time.Millisecond, time.Millisecond, "writer acquired a key while readers held it")++ firstReadUnlock()+ require.Never(t, func() bool {+ select {+ case <-writerAcquired:+ return true+ default:+ return false+ }+ }, 50*time.Millisecond, time.Millisecond, "writer acquired a key before every reader released it")++ secondReadUnlock()+ require.Eventually(t, func() bool {+ select {+ case <-writerAcquired:+ return true+ default:+ return false+ }+ }, time.Second, time.Millisecond)+ <-writerReleased+ require.Empty(t, locks.locks)+}diff --git a/backend/pkg/utils/path_util.go b/backend/pkg/utils/path_util.goindex 82f0f66cd..9794911c6 100644--- a/backend/pkg/utils/path_util.go+++ b/backend/pkg/utils/path_util.go@@ -1,14 +1,95 @@package utilsimport (+ "bytes"+ "hash"+ "io""os""path""path/filepath"+ "strconv""strings"+ "unicode/utf8""emperror.dev/errors")+// NormalizeRelativePath validates and normalizes a slash-delimited path rooted+// at a managed file tree. The returned path never begins with a slash.+func NormalizeRelativePath(input string) (string, error) {+ trimmed := strings.TrimSpace(input)+ if trimmed == "" {+ return "", errors.New("path is required")+ }+ if strings.ContainsRune(trimmed, 0) {+ return "", errors.New("path contains a null byte")+ }+ if strings.Contains(trimmed, "\\") {+ return "", errors.New("path must use forward slashes")+ }+ if path.IsAbs(trimmed) || filepath.IsAbs(trimmed) {+ return "", errors.New("absolute paths are not allowed")+ }++ cleaned := path.Clean(trimmed)+ if cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, "../") {+ return "", errors.New("path traversal is not allowed")+ }+ for segment := range strings.SplitSeq(cleaned, "/") {+ if segment == "" || segment == "." || segment == ".." {+ return "", errors.New("path contains an invalid segment")+ }+ }++ return cleaned, nil+}++// ValidateFileName validates a single file-tree path segment.+func ValidateFileName(name string) (string, error) {+ trimmed := strings.TrimSpace(name)+ if trimmed == "" {+ return "", errors.New("name is required")+ }+ if strings.ContainsRune(trimmed, 0) {+ return "", errors.New("name contains a null byte")+ }+ if strings.Contains(trimmed, "/") || strings.Contains(trimmed, "\\") {+ return "", errors.New("name must not contain path separators")+ }+ if filepath.VolumeName(trimmed) != "" {+ return "", errors.New("name must not contain a volume prefix")+ }+ if trimmed == "." || trimmed == ".." || filepath.Base(trimmed) != trimmed {+ return "", errors.New("invalid name")+ }+ return trimmed, nil+}++func FilePathMatches(relativePath, rootPath string) bool {+ return relativePath == rootPath || strings.HasPrefix(relativePath, rootPath+"/")+}++func IsBinaryFileContent(content []byte) bool {+ return !utf8.Valid(content) || bytes.IndexByte(content, 0) >= 0+}++func WriteFileTreeRevisionEntry(h hash.Hash, relativePath, kind string, size, modTimeUnixNano int64, mode string, protected bool) {+ protectedFlag := ""+ if protected {+ protectedFlag = "protected"+ }+ entry := strings.Join([]string{+ relativePath,+ kind,+ strconv.FormatInt(size, 10),+ strconv.FormatInt(modTimeUnixNano, 10),+ mode,+ protectedFlag,+ }, "\x00")+ _, _ = io.WriteString(h, entry)+ _, _ = h.Write([]byte{'\n'})+}+// IsWithinRoot reports whether target is root or lies beneath it. Both paths are// cleaned first; neither is resolved, so this only proves the *spelling* of the// path stays inside root. Use ResolveWithinRoot when a symlink could redirect it.diff --git a/backend/pkg/utils/path_util_test.go b/backend/pkg/utils/path_util_test.goindex 07d868365..ae35aec8c 100644--- a/backend/pkg/utils/path_util_test.go+++ b/backend/pkg/utils/path_util_test.go@@ -1,11 +1,42 @@package utilsimport (+ "crypto/sha256"+ "encoding/hex"+ "strings""testing""github.com/stretchr/testify/require")+func TestNormalizeRelativePath(t *testing.T) {+ for _, input := range []string{"", "/absolute", "../escape", "folder\\file", "name\x00"} {+ _, err := NormalizeRelativePath(input)+ require.Error(t, err, input)+ }+ got, err := NormalizeRelativePath("folder/file.txt")+ require.NoError(t, err)+ require.Equal(t, "folder/file.txt", got)+}++func TestValidateFileName(t *testing.T) {+ for _, input := range []string{"", ".", "..", "folder/name", "folder\\name", "name\x00"} {+ _, err := ValidateFileName(input)+ require.Error(t, err, input)+ }+ got, err := ValidateFileName("notes.txt")+ require.NoError(t, err)+ require.Equal(t, "notes.txt", got)+}++func TestFileTreeRevisionEntryIsStable(t *testing.T) {+ h := sha256.New()+ WriteFileTreeRevisionEntry(h, "folder/file.txt", "file", 12, 1234, "-rw-r--r--", false)+ require.Equal(t, "95f6a8dc033860a753fee2a04a21580d43087967d732a717d3e7a18f88ea4f65", hex.EncodeToString(h.Sum(nil)))+ require.False(t, IsBinaryFileContent([]byte(strings.Repeat("a", 8))))+ require.True(t, IsBinaryFileContent([]byte{'a', 0, 'b'}))+}+func TestSanitizeBrowsePath(t *testing.T) {tests := []struct {name stringdiff --git a/backend/pkg/workspace/workspace.go b/backend/pkg/workspace/workspace.gonew file mode 100644index 000000000..c7cec7ab8--- /dev/null+++ b/backend/pkg/workspace/workspace.go@@ -0,0 +1,82 @@+package workspace++import (+ "bytes"+ "strings"+ "unicode/utf8"++ "emperror.dev/errors"+)++const DefaultMaxFileSizeMB = 10++type UploadReference struct {+ Operation string+ UploadIndex *int+}++func EffectiveMaxFileSizeMB(configured int) int {+ if configured <= 0 {+ return DefaultMaxFileSizeMB+ }+ return configured+}++func MaxFileSizeBytes(configuredMB int) int64 {+ return int64(EffectiveMaxFileSizeMB(configuredMB)) * 1024 * 1024+}++func ValidateUpdateManifest(fileTreeRevision string, fileChangeCount, maxFileChanges int) error {+ if strings.TrimSpace(fileTreeRevision) == "" {+ return errors.New("workspace revision is required")+ }+ if fileChangeCount == 0 || fileChangeCount > maxFileChanges {+ return errors.Errorf("fileChanges must contain between 1 and %d changes", maxFileChanges)+ }+ return nil+}++func ValidateTextContent(content []byte, maxBytes int64) error {+ if int64(len(content)) > maxBytes {+ return errors.Errorf("file exceeds %d MiB limit", maxBytes/(1024*1024))+ }+ if !utf8.Valid(content) {+ return errors.New("file must contain valid UTF-8 text")+ }+ if bytes.IndexByte(content, 0) >= 0 {+ return errors.New("file must not contain NUL bytes")+ }+ return nil+}++func IsTextContent(content []byte) bool {+ return ValidateTextContent(content, int64(len(content))) == nil+}++func ValidateUploadIndices(changes []UploadReference, uploadCount int, createFileOperation, updateFileOperation string) error {+ used := make(map[int]struct{}, uploadCount)+ for _, change := range changes {+ requiresUpload := change.Operation == createFileOperation || change.Operation == updateFileOperation+ if requiresUpload && change.UploadIndex == nil {+ return errors.Errorf("uploadIndex is required for %s", change.Operation)+ }+ if !requiresUpload && change.UploadIndex != nil {+ return errors.Errorf("uploadIndex is not allowed for %s", change.Operation)+ }+ if change.UploadIndex == nil {+ continue+ }+ index := *change.UploadIndex+ if index < 0 || index >= uploadCount {+ return errors.Errorf("uploadIndex %d is out of range", index)+ }+ if _, exists := used[index]; exists {+ return errors.Errorf("uploadIndex %d is duplicated", index)+ }+ used[index] = struct{}{}+ }+ if len(used) != uploadCount {+ return errors.New("one or more uploaded files are unused")+ }+ return nil+}diff --git a/backend/pkg/workspace/workspace_test.go b/backend/pkg/workspace/workspace_test.gonew file mode 100644index 000000000..c9a1e44c8--- /dev/null+++ b/backend/pkg/workspace/workspace_test.go@@ -0,0 +1,73 @@+package workspace++import (+ "strings"+ "testing"++ "github.com/stretchr/testify/require"+)++func intPointer(value int) *int { return &value }++func TestEffectiveMaxFileSizeMB(t *testing.T) {+ require.Equal(t, DefaultMaxFileSizeMB, EffectiveMaxFileSizeMB(0))+ require.Equal(t, DefaultMaxFileSizeMB, EffectiveMaxFileSizeMB(-1))+ require.Equal(t, 24, EffectiveMaxFileSizeMB(24))+ require.Equal(t, int64(24*1024*1024), MaxFileSizeBytes(24))+}++func TestValidateTextContent(t *testing.T) {+ limit := int64(4)+ require.NoError(t, ValidateTextContent([]byte("text"), limit))+ require.ErrorContains(t, ValidateTextContent([]byte("large"), limit), "file exceeds")+ require.ErrorContains(t, ValidateTextContent([]byte{0xff}, limit), "UTF-8")+ require.ErrorContains(t, ValidateTextContent([]byte{'a', 0}, limit), "NUL")+}++func TestIsTextContent(t *testing.T) {+ require.True(t, IsTextContent([]byte("hello\n")))+ require.False(t, IsTextContent([]byte{0xff}))+ require.False(t, IsTextContent([]byte("hello\x00world")))+}++func TestValidateTextContentUsesDynamicMiBLimit(t *testing.T) {+ limit := int64(2 * 1024 * 1024)+ err := ValidateTextContent([]byte(strings.Repeat("a", int(limit+1))), limit)+ require.ErrorContains(t, err, "2 MiB")+}++func TestValidateUploadIndices(t *testing.T) {+ valid := []UploadReference{+ {Operation: "create_file", UploadIndex: intPointer(1)},+ {Operation: "create_folder"},+ {Operation: "update_file", UploadIndex: intPointer(0)},+ }+ require.NoError(t, ValidateUploadIndices(valid, 2, "create_file", "update_file"))++ tests := []struct {+ name string+ changes []UploadReference+ uploadCount int+ message string+ }{+ {name: "missing", changes: []UploadReference{{Operation: "create_file"}}, uploadCount: 0, message: "required"},+ {name: "unexpected", changes: []UploadReference{{Operation: "delete", UploadIndex: intPointer(0)}}, uploadCount: 1, message: "not allowed"},+ {name: "negative", changes: []UploadReference{{Operation: "create_file", UploadIndex: intPointer(-1)}}, uploadCount: 1, message: "out of range"},+ {name: "out of range", changes: []UploadReference{{Operation: "create_file", UploadIndex: intPointer(1)}}, uploadCount: 1, message: "out of range"},+ {name: "duplicate", changes: []UploadReference{{Operation: "create_file", UploadIndex: intPointer(0)}, {Operation: "update_file", UploadIndex: intPointer(0)}}, uploadCount: 1, message: "duplicated"},+ {name: "unused", changes: []UploadReference{{Operation: "create_file", UploadIndex: intPointer(0)}}, uploadCount: 2, message: "unused"},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ err := ValidateUploadIndices(test.changes, test.uploadCount, "create_file", "update_file")+ require.ErrorContains(t, err, test.message)+ })+ }+}++func TestValidateUpdateManifest(t *testing.T) {+ require.NoError(t, ValidateUpdateManifest("revision", 1, 500))+ require.ErrorContains(t, ValidateUpdateManifest(" ", 1, 500), "revision")+ require.ErrorContains(t, ValidateUpdateManifest("revision", 0, 500), "between 1 and 500")+ require.ErrorContains(t, ValidateUpdateManifest("revision", 501, 500), "between 1 and 500")+}diff --git a/backend/resources/migrations/postgres/071_rename_volume_workspace_legacy_keys.sql b/backend/resources/migrations/postgres/071_rename_volume_workspace_legacy_keys.sqlnew file mode 100644index 000000000..1f404dfb4--- /dev/null+++ b/backend/resources/migrations/postgres/071_rename_volume_workspace_legacy_keys.sql@@ -0,0 +1,47 @@+-- +goose Up+INSERT INTO settings (key, value)+SELECT 'volumeHelperIdleTimeout', value+FROM settings+WHERE key = 'volumeBrowserHelperIdleTimeout'+ON CONFLICT (key) DO NOTHING;++DELETE FROM settings WHERE key = 'volumeBrowserHelperIdleTimeout';++UPDATE roles+SET permissions = (+ SELECT jsonb_agg(permission ORDER BY permission)+ FROM (+ SELECT DISTINCT CASE value+ WHEN 'volumes:browse' THEN 'volumes:read'+ ELSE value+ END AS permission+ FROM jsonb_array_elements_text(roles.permissions)+ ) AS migrated_permissions+)+WHERE permissions ? 'volumes:browse';++DELETE FROM api_key_permissions AS legacy+WHERE legacy.permission = 'volumes:browse'+ AND EXISTS (+ SELECT 1+ FROM api_key_permissions AS current+ WHERE current.api_key_id = legacy.api_key_id+ AND current.permission = 'volumes:read'+ AND COALESCE(current.environment_id, '') = COALESCE(legacy.environment_id, '')+ );++UPDATE api_key_permissions+SET permission = 'volumes:read'+WHERE permission = 'volumes:browse';++-- +goose Down+INSERT INTO settings (key, value)+SELECT 'volumeBrowserHelperIdleTimeout', value+FROM settings+WHERE key = 'volumeHelperIdleTimeout'+ON CONFLICT (key) DO NOTHING;++DELETE FROM settings WHERE key = 'volumeHelperIdleTimeout';++-- Permission grants are intentionally not reversed because volumes:read may+-- have existed before this migration and cannot be distinguished safely.diff --git a/backend/resources/migrations/sqlite/071_rename_volume_workspace_legacy_keys.sql b/backend/resources/migrations/sqlite/071_rename_volume_workspace_legacy_keys.sqlnew file mode 100644index 000000000..d1c6c731b--- /dev/null+++ b/backend/resources/migrations/sqlite/071_rename_volume_workspace_legacy_keys.sql@@ -0,0 +1,47 @@+-- +goose Up+INSERT OR IGNORE INTO settings (key, value)+SELECT 'volumeHelperIdleTimeout', value+FROM settings+WHERE key = 'volumeBrowserHelperIdleTimeout';++DELETE FROM settings WHERE key = 'volumeBrowserHelperIdleTimeout';++UPDATE roles+SET permissions = (+ SELECT json_group_array(permission)+ FROM (+ SELECT DISTINCT CASE value+ WHEN 'volumes:browse' THEN 'volumes:read'+ ELSE value+ END AS permission+ FROM json_each(roles.permissions)+ )+)+WHERE EXISTS (+ SELECT 1 FROM json_each(roles.permissions) WHERE value = 'volumes:browse'+);++DELETE FROM api_key_permissions AS legacy+WHERE legacy.permission = 'volumes:browse'+ AND EXISTS (+ SELECT 1+ FROM api_key_permissions AS current+ WHERE current.api_key_id = legacy.api_key_id+ AND current.permission = 'volumes:read'+ AND COALESCE(current.environment_id, '') = COALESCE(legacy.environment_id, '')+ );++UPDATE api_key_permissions+SET permission = 'volumes:read'+WHERE permission = 'volumes:browse';++-- +goose Down+INSERT OR IGNORE INTO settings (key, value)+SELECT 'volumeBrowserHelperIdleTimeout', value+FROM settings+WHERE key = 'volumeHelperIdleTimeout';++DELETE FROM settings WHERE key = 'volumeHelperIdleTimeout';++-- Permission grants are intentionally not reversed because volumes:read may+-- have existed before this migration and cannot be distinguished safely.diff --git a/cli/go.mod b/cli/go.modindex 79a4883b2..47d719e78 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -2,6 +2,8 @@ module github.com/getarcaneapp/arcane/cli/v2go 1.26.5+replace github.com/getarcaneapp/arcane/types/v2 => ../types+require (charm.land/bubbles/v2 v2.1.1charm.land/bubbletea/v2 v2.0.8diff --git a/cli/go.sum b/cli/go.sumindex df056a9fc..7eb1132b0 100644--- a/cli/go.sum+++ b/cli/go.sum@@ -67,8 +67,6 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkgithub.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=-github.com/getarcaneapp/arcane/types/v2 v2.6.0 h1:aXa3ksWtsmUWKjnrRjmt9TCnBZ46koelmBNQoDbmqlI=-github.com/getarcaneapp/arcane/types/v2 v2.6.0/go.mod h1:45FfXso7vCN2mAE4dXVABRGYrQKeQlcdPQk7S6aEpok=github.com/go-logfmt/logfmt v0.6.1 h1:4hvbpePJKnIzH1B+8OR/JPbTx37NktoI9LE2QZBBkvE=github.com/go-logfmt/logfmt v0.6.1/go.mod h1:EV2pOAQoZaT1ZXZbqDl5hrymndi4SY9ED9/z6CO0XAk=github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=diff --git a/cli/internal/types/endpoints.go b/cli/internal/types/endpoints.goindex c9b138deb..f65764a73 100644--- a/cli/internal/types/endpoints.go+++ b/cli/internal/types/endpoints.go@@ -87,16 +87,16 @@ type ArcaneApiEndpoints struct {VolumeUsageEndpoint string// Projects (Stacks)- ProjectsEndpoint string- ProjectEndpoint string- ProjectsCountsEndpoint string- ProjectDestroyEndpoint string- ProjectUpEndpoint string- ProjectDownEndpoint string- ProjectRestartEndpoint string- ProjectRedeployEndpoint string- ProjectPullEndpoint string- ProjectIncludesEndpoint string+ ProjectsEndpoint string+ ProjectEndpoint string+ ProjectsCountsEndpoint string+ ProjectDestroyEndpoint string+ ProjectUpEndpoint string+ ProjectDownEndpoint string+ ProjectRestartEndpoint string+ ProjectRedeployEndpoint string+ ProjectPullEndpoint string+ ProjectWorkspaceEndpoint string// SystemSystemPruneEndpoint string@@ -257,16 +257,16 @@ var Endpoints = ArcaneApiEndpoints{ //nolint:gosec // static endpoint paths; autVolumeUsageEndpoint: "/api/environments/%s/volumes/%s/usage",// Projects (Stacks)- ProjectsEndpoint: "/api/environments/%s/projects",- ProjectEndpoint: "/api/environments/%s/projects/%s",- ProjectsCountsEndpoint: "/api/environments/%s/projects/counts",- ProjectDestroyEndpoint: "/api/environments/%s/projects/%s/destroy",- ProjectUpEndpoint: "/api/environments/%s/projects/%s/up",- ProjectDownEndpoint: "/api/environments/%s/projects/%s/down",- ProjectRestartEndpoint: "/api/environments/%s/projects/%s/restart",- ProjectRedeployEndpoint: "/api/environments/%s/projects/%s/redeploy",- ProjectPullEndpoint: "/api/environments/%s/projects/%s/pull",- ProjectIncludesEndpoint: "/api/environments/%s/projects/%s/includes",+ ProjectsEndpoint: "/api/environments/%s/projects",+ ProjectEndpoint: "/api/environments/%s/projects/%s",+ ProjectsCountsEndpoint: "/api/environments/%s/projects/counts",+ ProjectDestroyEndpoint: "/api/environments/%s/projects/%s/destroy",+ ProjectUpEndpoint: "/api/environments/%s/projects/%s/up",+ ProjectDownEndpoint: "/api/environments/%s/projects/%s/down",+ ProjectRestartEndpoint: "/api/environments/%s/projects/%s/restart",+ ProjectRedeployEndpoint: "/api/environments/%s/projects/%s/redeploy",+ ProjectPullEndpoint: "/api/environments/%s/projects/%s/pull",+ ProjectWorkspaceEndpoint: "/api/environments/%s/projects/%s/workspace",// SystemSystemPruneEndpoint: "/api/environments/%s/system/prune",@@ -564,8 +564,8 @@ func (e ArcaneApiEndpoints) ProjectPull(envID, projectID string) string {return fmt.Sprintf(e.ProjectPullEndpoint, envID, projectID)}-func (e ArcaneApiEndpoints) ProjectIncludes(envID, projectID string) string {- return fmt.Sprintf(e.ProjectIncludesEndpoint, envID, projectID)+func (e ArcaneApiEndpoints) ProjectWorkspace(envID, projectID string) string {+ return fmt.Sprintf(e.ProjectWorkspaceEndpoint, envID, projectID)}// System endpointsdiff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.goindex 50a73c7ba..0b2173335 100644--- a/cli/pkg/projects/cmd.go+++ b/cli/pkg/projects/cmd.go@@ -2,10 +2,12 @@ package projectsimport ("bufio"+ "bytes""context""encoding/json""fmt""io"+ "mime/multipart""net/http""net/url""os"@@ -23,6 +25,7 @@ import ("github.com/getarcaneapp/arcane/cli/v2/internal/types""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/project"+ workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace""github.com/spf13/cobra")@@ -486,7 +489,27 @@ var createCmd = &cobra.Command{// Creating can take a long time as it may pull imagesc.SetTimeout(30 * time.Minute)- resp, err := c.Post(cmd.Context(), types.Endpoints.Projects(c.EnvID()), body)+ projectJSON, err := json.Marshal(body)+ if err != nil {+ return errors.WrapIf(err, "failed to encode project configuration")+ }+ manifestJSON, err := json.Marshal(project.CreateProjectWorkspaceManifest{FileChanges: []project.WorkspaceFileChange{}})+ if err != nil {+ return errors.WrapIf(err, "failed to encode project workspace manifest")+ }+ var requestBody bytes.Buffer+ writer := multipart.NewWriter(&requestBody)+ if err := writer.WriteField("project", string(projectJSON)); err != nil {+ return errors.WrapIf(err, "failed to write project configuration")+ }+ if err := writer.WriteField("manifest", string(manifestJSON)); err != nil {+ return errors.WrapIf(err, "failed to write project workspace manifest")+ }+ if err := writer.Close(); err != nil {+ return errors.WrapIf(err, "failed to finalize project request")+ }++ resp, err := c.RequestRaw(cmd.Context(), http.MethodPost, types.Endpoints.Projects(c.EnvID()), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})if err != nil {return errors.WrapIf(err, "failed to create project")}@@ -605,12 +628,53 @@ var updateIncludesCmd = &cobra.Command{return errors.WrapIf(err, "failed to read include file")}- body := project.UpdateIncludeFile{- RelativePath: filepath.Base(includesFile),- Content: string(content),+ workspaceResponse, err := c.Get(cmd.Context(), types.Endpoints.ProjectWorkspace(c.EnvID(), resolved.ID))+ if err != nil {+ return errors.WrapIf(err, "failed to get project workspace")+ }+ defer func() { _ = workspaceResponse.Body.Close() }()+ if err := cmdutil.EnsureSuccessStatus(workspaceResponse); err != nil {+ return errors.WrapIf(err, "failed to get project workspace")+ }+ var current base.ApiResponse[workspacetypes.Workspace]+ if err := cmdutil.DecodeJSON(workspaceResponse, ¤t); err != nil {+ return err+ }++ relativePath := filepath.ToSlash(filepath.Base(includesFile))+ operation := project.FileOpCreateFile+ for _, entry := range current.Data.Files {+ if entry.RelativePath == relativePath && !entry.IsDirectory {+ operation = project.FileOpUpdateFile+ break+ }+ }+ uploadIndex := 0+ manifest := project.WorkspaceUpdateManifest{+ FileTreeRevision: current.Data.FileTreeRevision,+ FileChanges: []project.WorkspaceFileChange{{Operation: operation, RelativePath: relativePath, UploadIndex: &uploadIndex}},+ }+ manifestJSON, err := json.Marshal(manifest)+ if err != nil {+ return errors.WrapIf(err, "failed to encode workspace manifest")+ }+ var requestBody bytes.Buffer+ writer := multipart.NewWriter(&requestBody)+ if err := writer.WriteField("manifest", string(manifestJSON)); err != nil {+ return errors.WrapIf(err, "failed to write workspace manifest")+ }+ filePart, err := writer.CreateFormFile("files", filepath.Base(includesFile))+ if err != nil {+ return errors.WrapIf(err, "failed to create workspace upload")+ }+ if _, err := filePart.Write(content); err != nil {+ return errors.WrapIf(err, "failed to write workspace upload")+ }+ if err := writer.Close(); err != nil {+ return errors.WrapIf(err, "failed to finalize workspace upload")}- resp, err := c.Put(cmd.Context(), types.Endpoints.ProjectIncludes(c.EnvID(), resolved.ID), body)+ resp, err := c.RequestRaw(cmd.Context(), http.MethodPut, types.Endpoints.ProjectWorkspace(c.EnvID(), resolved.ID), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})if err != nil {return errors.WrapIf(err, "failed to update include file")}@@ -620,7 +684,7 @@ var updateIncludesCmd = &cobra.Command{}if jsonOutput {- var result base.ApiResponse[project.Details]+ var result base.ApiResponse[workspacetypes.Workspace]if err := cmdutil.DecodeJSON(resp, &result); err != nil {return err}diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex aa0bafbcd..6ceaccc5b 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -893,6 +893,20 @@"unused_volumes": "Unused Volumes","volumes_nav_browser": "Browser","volumes_nav_backups": "Backups",+ "volumes_workspace_files": "Volume Workspace",+ "volumes_workspace_files_empty": "No workspace files in this volume",+ "volumes_workspace_upload_description": "Upload one or more files to the volume workspace.",+ "volumes_workspace_root_destination": "Volume root",+ "volumes_workspace_root_path": "Create at the volume root.",+ "volumes_workspace_delete_confirm": "Delete {name} from the volume? This will be applied when you save.",+ "volumes_workspace_truncated": "The workspace listing is truncated by the configured depth or entry limit. Hidden paths are not shown.",+ "volumes_workspace_select_file": "Select a file to open it in the editor.",+ "volumes_workspace_restore_readonly": "This file's contents are unknown until the staged restore is saved.",+ "volumes_workspace_locked_file": "Locked file",+ "volumes_workspace_upload_collision_title": "Replace existing files?",+ "volumes_workspace_upload_collision_message": "The following files already exist and will be replaced when you save:\n\n{paths}",+ "volumes_workspace_restore_staged": "The selected backup restore will be applied when you save.",+ "volumes_workspace_save_success": "Volume workspace updated successfully.","volumes_backups_title": "Volume Backups","volumes_backups_restore": "Restore","volumes_remove_in_use_warning": "Warning: This volume is currently in use by containers. Forcing removal may cause data loss or container issues.",@@ -908,8 +922,8 @@"volumes_remove_selected_message": "Are you sure you want to remove the selected volume(s)? This action cannot be undone.","volumes_remove_failed": "Failed to remove volume {name}","volumes_remove_success": "Volume {name} removed successfully",- "volumes_browser_upload_files": "Upload Files",- "volumes_browser_delete_confirm": "Are you sure you want to delete {name}?",+ "workspace_upload_files": "Upload Files",+ "workspace_delete_immediate_confirm": "Are you sure you want to delete {name}?","volumes_backup_create": "Create Backup","volumes_backup_delete_confirm": "Are you sure you want to delete this backup?","volumes_backup_restore_title": "Restore Volume",@@ -2606,6 +2620,45 @@"common_image_id": "Image ID","common_entrypoint": "Entrypoint","workspace": "Workspace",+ "workspace_files": "Workspace Files",+ "workspace_files_empty": "No workspace files",+ "workspace_new_file": "New File",+ "workspace_create_file_title": "Create File",+ "workspace_create_folder_title": "Create Folder",+ "workspace_upload_description": "Upload one or more UTF-8 text files to the workspace.",+ "workspace_upload_file_label": "File",+ "workspace_upload_file_required": "Choose a file to upload.",+ "workspace_upload_too_large": "File must be {maxFileSizeMb} MiB or smaller.",+ "workspace_upload_text_required": "Only UTF-8 text files without NUL bytes can be uploaded.",+ "workspace_file_move_description": "Move {name} to another folder.",+ "workspace_file_move_destination_label": "Destination",+ "workspace_root_destination": "Workspace root",+ "workspace_file_invalid_move_destination": "Choose a valid destination.",+ "workspace_move_current_location": "Current location",+ "workspace_move_duplicate_destination": "Name already exists",+ "workspace_move_descendant_blocked": "Inside itself",+ "workspace_file_name_placeholder": "config.yaml",+ "workspace_folder_name_placeholder": "config",+ "workspace_file_invalid_name": "Use a single safe file or folder name.",+ "workspace_file_not_found": "Workspace file not found.",+ "workspace_file_duplicate_name": "A file or folder already exists with that name.",+ "workspace_root_path": "Create at the workspace root.",+ "workspace_file_parent_path": "Create under {path}.",+ "workspace_delete_confirm": "Delete {name} from the workspace? This will be applied when you save.",+ "workspace_file_rename_label": "Rename {name}",+ "workspace_file_move_label": "Move {name}",+ "workspace_file_read_only": "Read-only file",+ "workspace_binary_readonly": "Binary files cannot be edited in the workspace.",+ "workspace_large_readonly": "Files larger than {maxFileSizeMb} MiB cannot be edited in the workspace.",+ "workspace_symlink_readonly": "Symbolic links are read-only in the workspace.",+ "workspace_special_readonly": "Special files are read-only in the workspace.",+ "workspace_readonly": "This file is read-only.",+ "workspace_restore": "Restore",+ "workspace_file_expand_folder": "Expand {name}",+ "workspace_file_collapse_folder": "Collapse {name}",+ "projects_workspace_saved_configuration_failed": "Workspace changes were saved, but project configuration failed: {error}",+ "projects_workspace_readonly_git": "Git-managed project workspace files are read-only.",+ "projects_workspace_not_loaded": "Project workspace is not loaded.","project_view_description": "Toggle workspace mode","environments_created_title": "Environment Created Successfully","environments_created_description": "Use the API key and deployment snippets below to set up your agent.",@@ -2619,41 +2672,11 @@"environments_agent_address_placeholder": "agent.example.com","environments_agent_address_description": "The URL where your agent will be accessible","environments_generate_config": "Generate Agent Configuration",- "project_files": "Project Files",- "project_files_empty": "No project files",- "project_file_new_file": "New File","new_folder": "New Folder","upload_file": "Upload File",- "project_file_create_file_title": "Create File",- "project_file_create_folder_title": "Create Folder",- "project_file_upload_description": "Upload one text file to the project files.",- "project_file_upload_file_label": "File",- "project_file_upload_file_required": "Choose a file to upload.",- "project_file_upload_too_large": "File must be 1 MB or smaller.",- "project_file_upload_text_required": "Only UTF-8 text files can be uploaded.","rename": "Rename","move": "Move",- "project_file_move_description": "Move {name} to another folder.",- "project_file_move_destination_label": "Destination",- "project_file_root_destination": "Project root",- "project_file_invalid_move_destination": "Choose a valid destination.",- "project_file_move_current_location": "Current location",- "project_file_move_duplicate_destination": "Name already exists",- "project_file_move_descendant_blocked": "Inside itself",- "project_file_name_placeholder": "config.yaml",- "project_file_folder_name_placeholder": "config",- "project_file_invalid_name": "Use a single safe file or folder name.",- "project_file_duplicate_name": "A file or folder already exists with that name.",- "project_file_root_path": "Create at the project root.",- "project_file_parent_path": "Create under {path}.",- "project_file_delete_confirm": "Delete {name} from the project files? This will be applied when you save.","delete_name": "Delete {name}",- "project_file_rename_label": "Rename {name}",- "project_file_move_label": "Move {name}",- "project_file_protected": "Protected file",- "project_file_expand_folder": "Expand {name}",- "project_file_collapse_folder": "Collapse {name}",- "project_files_readonly_git": "Git-managed project files are read-only.","notifications_event_prune_report_label": "System Prune Report","notifications_event_prune_report_description": "Receive a summary report when a scheduled prune operation completes","notifications_event_auto_heal_label": "Auto-Heal Restart",@@ -2992,10 +3015,10 @@"common_clear_search": "Clear search","common_documentation": "Documentation","common_github": "GitHub",- "file_browser_restore": "Restore file from backup",- "file_browser_no_backups": "No backups available.",- "file_browser_backup": "Backup",- "file_browser_backup_missing_file": "This backup does not contain the selected file.",+ "volumes_workspace_restore": "Restore file from backup",+ "volumes_workspace_no_backups": "No backups available.",+ "volumes_workspace_backup": "Backup",+ "volumes_workspace_backup_missing_file": "This backup does not contain the selected file.","nav_expand_user_card": "Expand user card","network_example_subnet": "e.g., 172.20.0.0/16","network_example_gateway": "e.g., 172.20.0.1",@@ -3056,7 +3079,7 @@"environments_connect_error": "Failed to Connect to Environment","common_access_denied": "Access denied","volumes_backup_restore_desc": "Select files from this backup to restore.",- "file_browser_backup_restore_desc": "Select a backup to restore the chosen file.",+ "volumes_workspace_backup_restore_desc": "Select a backup to restore the chosen file.","editor_commands_desc": "Run editor commands","environments_swarm_stack_source_label": "Swarm Stack Sources Directory","environments_swarm_stack_source_help": "Directory where original compose/env sources for Swarm stack deploys are stored. Supports the same container:host bind-mount format as Projects Directory.",@@ -3064,7 +3087,7 @@"carousel_previous_slide": "Previous slide","common_edit_name": "Edit name","common_ive_saved_it": "I've saved it",- "file_browser_restore_file": "Restore file",+ "volumes_workspace_restore_file": "Restore file","containers_status_restarting": "Restarting","containers_status_removing": "Removing","paused": "Paused",diff --git a/frontend/src/routes/(app)/projects/components/CodePanel.svelte b/frontend/src/lib/components/code-panel.sveltesimilarity index 100%rename from frontend/src/routes/(app)/projects/components/CodePanel.svelterename to frontend/src/lib/components/code-panel.sveltediff --git a/frontend/src/routes/(app)/projects/components/EditorTabStrip.svelte b/frontend/src/lib/components/editor-tab-strip.sveltesimilarity index 100%rename from frontend/src/routes/(app)/projects/components/EditorTabStrip.svelterename to frontend/src/lib/components/editor-tab-strip.sveltediff --git a/frontend/src/lib/components/file-browser/FileList.svelte b/frontend/src/lib/components/file-browser/FileList.svelteindex 836148962..08627435d 100644--- a/frontend/src/lib/components/file-browser/FileList.svelte+++ b/frontend/src/lib/components/file-browser/FileList.svelte@@ -104,7 +104,7 @@if (!onDelete) return;openConfirmDialog({title: m.common_remove_title({ resource: file.name }),- message: m.volumes_browser_delete_confirm({ name: file.name }),+ message: m.workspace_delete_immediate_confirm({ name: file.name }),confirm: {label: m.common_delete(),destructive: true,diff --git a/frontend/src/lib/components/file-browser/FileUploadDialog.svelte b/frontend/src/lib/components/file-browser/FileUploadDialog.svelteindex 83655ae70..b17c94972 100644--- a/frontend/src/lib/components/file-browser/FileUploadDialog.svelte+++ b/frontend/src/lib/components/file-browser/FileUploadDialog.svelte@@ -60,7 +60,7 @@><Dialog.Content class="sm:max-w-[500px]"><Dialog.Header>- <Dialog.Title>{m.volumes_browser_upload_files()}</Dialog.Title>+ <Dialog.Title>{m.workspace_upload_files()}</Dialog.Title><Dialog.Description>Upload files to {currentPath}</Dialog.Description>diff --git a/frontend/src/lib/components/file-browser/GenericFileBrowser.svelte b/frontend/src/lib/components/file-browser/GenericFileBrowser.sveltedeleted file mode 100644index d1706f5ff..000000000--- a/frontend/src/lib/components/file-browser/GenericFileBrowser.svelte+++ /dev/null@@ -1,347 +0,0 @@-<script lang="ts" module>- import type { BackupEntry, FileEntry } from '#lib/types/shared';-- export interface FileProvider {- list: (path: string) => Promise<FileEntry[]>;- mkdir: (path: string) => Promise<unknown>;- upload: (path: string, file: File) => Promise<unknown>;- delete: (path: string) => Promise<unknown>;- download: (path: string) => Promise<void>;- getContent: (path: string) => Promise<{ content: string }>;- listBackups?: () => Promise<BackupEntry[]>;- restoreFromBackup?: (backupId: string, path: string) => Promise<unknown>;- backupHasPath?: (backupId: string, path: string) => Promise<boolean>;- }-- // Sorts file entries in place: directories first, then alphabetically by name.- export function sortFileEntries(files: FileEntry[]): FileEntry[] {- return files.sort((a, b) => {- if (a.isDirectory && !b.isDirectory) return -1;- if (!a.isDirectory && b.isDirectory) return 1;- return a.name.localeCompare(b.name);- });- }-</script>--<script lang="ts">- import { m } from '#lib/paraglide/messages';- import { onMount } from 'svelte';- import FileList from './FileList.svelte';- import FileBreadcrumb from './FileBreadcrumb.svelte';- import { UploadIcon, MoveToFolderIcon, InfoIcon } from '#lib/icons';- import { ArcaneButton } from '#lib/components/arcane-button';- import CreateFolderDialog from './CreateFolderDialog.svelte';- import FileUploadDialog from './FileUploadDialog.svelte';- import FilePreview from './FilePreview.svelte';- import { Spinner } from '#lib/components/ui/spinner/index.js';- import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog';- import * as Select from '#lib/components/ui/select';- import * as Alert from '#lib/components/ui/alert';- import { Label } from '#lib/components/ui/label';- import { toast } from 'svelte-sonner';- import { bytes, formatDateTimeShort } from '#lib/utils/formatting';- import { environmentStore } from '#lib/stores/environment.store.svelte';- import { hasPermission } from '#lib/utils/auth';- import IfPermitted from '#lib/components/if-permitted.svelte';- import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast';-- let { provider, rootLabel, persistKey }: { provider: FileProvider; rootLabel?: string; persistKey?: string } = $props();-- const currentEnvId = $derived(environmentStore.selected?.id || '0');- const canDeleteVolume = $derived(hasPermission('volumes:delete', currentEnvId));- const canBackupVolume = $derived(hasPermission('volumes:backup', currentEnvId));-- let currentPath = $state('/');- let files = $state<FileEntry[]>([]);- let loading = $state(true);- let error = $state<string | null>(null);-- let showCreateFolder = $state(false);- let showUpload = $state(false);- let previewFile = $state<FileEntry | null>(null);- let showRestoreFile = $state(false);- let restoreTarget = $state<FileEntry | null>(null);- let backups = $state<BackupEntry[]>([]);- let loadingBackups = $state(false);- let restoringFile = $state(false);- let selectedBackupId = $state('');- let backupHasFile = $state<boolean | null>(null);- let checkingBackup = $state(false);- let lastCheckedKey = $state('');- const selectedBackup = $derived(backups.find((b) => b.id === selectedBackupId));-- const canRestoreFromBackup = $derived(!!provider.listBackups && !!provider.restoreFromBackup);- const requiresBackupCheck = $derived(!!provider.backupHasPath);-- async function loadFiles(path: string) {- loading = true;- error = null;- try {- const result = await provider.list(path);- // Sort: directories first, then alphabetically- files = sortFileEntries(result);- currentPath = path;- } catch (e: any) {- error = e.message || m.common_failed();- } finally {- loading = false;- }- }-- function handleNavigate(path: string) {- loadFiles(path);- }-- async function loadBackups() {- if (!provider.listBackups) return;- loadingBackups = true;- try {- backups = await provider.listBackups();- if (backups.length > 0) {- const firstBackup = backups[0];- if (firstBackup) {- selectedBackupId = firstBackup.id;- }- }- } catch (e: any) {- toast.error(e.message || m.common_failed());- } finally {- loadingBackups = false;- }- }-- function openRestoreFileDialog(file: FileEntry) {- if (file.isDirectory || file.isSymlink) return;- restoreTarget = file;- selectedBackupId = '';- backups = [];- backupHasFile = null;- lastCheckedKey = '';- showRestoreFile = true;- loadBackups();- }-- async function handleRestoreFile() {- if (!restoreTarget || !provider.restoreFromBackup || !selectedBackupId) return;- restoringFile = true;- try {- const result = await provider.restoreFromBackup(selectedBackupId, restoreTarget.path);- toast.success(m.volumes_backup_file_restore_success(), activityToastOptions(extractActivityId(result)));- showRestoreFile = false;- // Refresh the file list to show the restored file- await loadFiles(currentPath);- } catch (e: any) {- toast.error(e.message || m.common_failed());- } finally {- restoringFile = false;- }- }-- async function checkBackupHasFile(backupId: string, filePath: string) {- if (!provider.backupHasPath) return;- const key = `${backupId}:${filePath}`;- if (key === lastCheckedKey) return;- lastCheckedKey = key;- checkingBackup = true;- backupHasFile = null;- try {- backupHasFile = await provider.backupHasPath(backupId, filePath);- } catch (e: any) {- backupHasFile = null;- toast.error(e.message || m.common_failed());- } finally {- checkingBackup = false;- }- }-- function formatBackupLabel(backup: BackupEntry): string {- const sizeLabel = bytes.format(backup.size, { unitSeparator: ' ' }) ?? '-';- const createdLabel = backup.createdAt ? formatDateTimeShort(backup.createdAt) : '-';- return `${backup.id} • ${createdLabel} • ${sizeLabel}`;- }-- onMount(() => {- loadFiles('/');- });-- $effect(() => {- if (!showRestoreFile) return;- if (!requiresBackupCheck) return;- if (!restoreTarget || !selectedBackupId) {- backupHasFile = null;- return;- }- checkBackupHasFile(selectedBackupId, restoreTarget.path);- });-</script>--<div class="flex flex-col gap-4">- <div class="flex items-center justify-between">- <FileBreadcrumb path={currentPath} {rootLabel} onNavigate={handleNavigate} />- <div class="flex gap-2">- <IfPermitted perm="volumes:upload">- <ArcaneButton- action="base"- tone="outline"- size="sm"- onclick={() => (showCreateFolder = true)}- icon={MoveToFolderIcon}- customLabel={m.new_folder()}- />- <ArcaneButton- action="base"- tone="outline"- size="sm"- onclick={() => (showUpload = true)}- icon={UploadIcon}- customLabel={m.volumes_browser_upload_files()}- />- </IfPermitted>- </div>- </div>-- {#if loading}- <div class="flex justify-center p-12">- <Spinner class="size-8 text-muted-foreground" />- </div>- {:else if error}- <div class="rounded-lg border border-destructive/20 bg-destructive/10 p-8 text-center text-destructive">- {error}- </div>- {:else}- <FileList- {files}- {currentPath}- {persistKey}- onNavigate={handleNavigate}- onRefresh={() => loadFiles(currentPath)}- onDelete={canDeleteVolume ? (file) => provider.delete(file.path) : undefined}- onDownload={(file) => provider.download(file.path)}- onPreview={(file) => (previewFile = file)}- onRestoreFromBackup={canRestoreFromBackup && canBackupVolume ? openRestoreFileDialog : undefined}- />- {/if}-</div>--<CreateFolderDialog- bind:open={showCreateFolder}- {currentPath}- onCreate={async (name) => {- const fullPath = currentPath === '/' ? `/${name}` : `${currentPath}/${name}`;- await provider.mkdir(fullPath);- await loadFiles(currentPath);- }}-/>--<FileUploadDialog- bind:open={showUpload}- {currentPath}- onUpload={async (file) => {- await provider.upload(currentPath, file);- await loadFiles(currentPath);- }}-/>--{#if previewFile}- <FilePreview- file={previewFile}- fetchContent={async (path) => {- const res = await provider.getContent(path);- return res.content;- }}- onClose={() => (previewFile = null)}- />-{/if}--<ResponsiveDialog- open={showRestoreFile}- onOpenChange={(nextOpen) => (showRestoreFile = nextOpen)}- title={m.file_browser_restore()}- description={m.file_browser_backup_restore_desc()}- contentClass="sm:max-w-[520px]"->- {#snippet children()}- <div class="space-y-4 py-2">- <Alert.Root class="py-2 [&>svg]:top-2">- <InfoIcon class="size-4" />- <Alert.Description class="text-xs">- {m.volumes_backup_safety_info()}- </Alert.Description>- </Alert.Root>-- {#if restoreTarget}- <div class="text-xs text-muted-foreground">- File: <code class="rounded bg-muted/40 px-1.5 py-0.5 font-mono">{restoreTarget.path}</code>- </div>- {/if}-- {#if loadingBackups}- <div class="flex items-center gap-2 text-sm text-muted-foreground">- <Spinner class="size-4" />- Loading backups...- </div>- {:else if backups.length === 0}- <div class="text-sm text-muted-foreground">{m.file_browser_no_backups()}</div>- {:else}- <div class="space-y-2">- <Label for="restore-backup-select">{m.file_browser_backup()}</Label>- <div class="w-full overflow-hidden">- <Select.Root- type="single"- value={selectedBackupId}- onValueChange={(value) => {- selectedBackupId = value;- }}- >- <Select.Trigger id="restore-backup-select" class="h-10 w-full overflow-hidden">- <span class="min-w-0 flex-1 truncate">- {selectedBackup ? formatBackupLabel(selectedBackup) : 'Select backup'}- </span>- </Select.Trigger>- <Select.Content>- {#each backups as backup (backup.id)}- <Select.Item value={backup.id}>{formatBackupLabel(backup)}</Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>- </div>- {#if requiresBackupCheck}- {#if checkingBackup}- <div class="flex items-center gap-2 text-xs text-muted-foreground">- <Spinner class="size-3" />- Checking backup contents...- </div>- {:else if backupHasFile === false}- <div class="text-xs text-destructive">{m.file_browser_backup_missing_file()}</div>- {/if}- {/if}- {/if}- </div>- {/snippet}-- {#snippet footer()}- <ArcaneButton- action="cancel"- onclick={() => {- showRestoreFile = false;- restoreTarget = null;- selectedBackupId = '';- }}- />- {#if canBackupVolume}- <ArcaneButton- action="create"- customLabel={m.file_browser_restore_file()}- onclick={handleRestoreFile}- loading={restoringFile}- disabled={restoringFile ||- loadingBackups ||- checkingBackup ||- !selectedBackupId ||- !restoreTarget ||- (requiresBackupCheck && backupHasFile !== true)}- />- {/if}- {/snippet}-</ResponsiveDialog>diff --git a/frontend/src/lib/components/file-browser/VolumeBrowser.svelte b/frontend/src/lib/components/file-browser/VolumeBrowser.sveltedeleted file mode 100644index 37239de67..000000000--- a/frontend/src/lib/components/file-browser/VolumeBrowser.svelte+++ /dev/null@@ -1,66 +0,0 @@-<script lang="ts">- import { volumeBrowserService } from '#lib/services/volume-browser-service';- import { volumeBackupService } from '#lib/services/volume-backup-service';- import { queryKeys } from '#lib/query/query-keys';- import GenericFileBrowser, { type FileProvider } from './GenericFileBrowser.svelte';- import { useQueryClient } from '@tanstack/svelte-query';-- let { volumeName }: { volumeName: string } = $props();- const queryClient = useQueryClient();-- const provider: FileProvider = {- list: (path) =>- queryClient.fetchQuery({- queryKey: queryKeys.volumes.list(volumeName, path),- queryFn: () => volumeBrowserService.listDirectory(volumeName, path),- staleTime: 0- }),- mkdir: async (path) => {- const result = await volumeBrowserService.createDirectory(volumeName, path);- await queryClient.invalidateQueries({ queryKey: queryKeys.volumes.listPrefix(volumeName) });- return result;- },- upload: async (path, file) => {- const result = await volumeBrowserService.uploadFile(volumeName, path, file);- await queryClient.invalidateQueries({ queryKey: queryKeys.volumes.listPrefix(volumeName) });- return result;- },- delete: async (path) => {- const result = await volumeBrowserService.deleteFile(volumeName, path);- await queryClient.invalidateQueries({ queryKey: queryKeys.volumes.listPrefix(volumeName) });- return result;- },- download: (path) => volumeBrowserService.downloadFile(volumeName, path),- getContent: (path) =>- queryClient.fetchQuery({- queryKey: queryKeys.volumes.content(volumeName, path),- queryFn: () => volumeBrowserService.getFileContent(volumeName, path),- staleTime: 0- }),- listBackups: async () => {- const res = await queryClient.fetchQuery({- queryKey: queryKeys.volumes.backups(volumeName),- queryFn: () =>- volumeBackupService.listBackups(volumeName, {- pagination: { page: 1, limit: 200 },- sort: { column: 'createdAt', direction: 'desc' }- }),- staleTime: 0- });- return res.data;- },- restoreFromBackup: async (backupId, path) => {- const result = await volumeBackupService.restoreBackupFiles(volumeName, backupId, [path]);- await queryClient.invalidateQueries({ queryKey: queryKeys.volumes.listPrefix(volumeName) });- return result;- },- backupHasPath: (backupId, path) =>- queryClient.fetchQuery({- queryKey: queryKeys.volumes.backupHasPath(backupId, path),- queryFn: () => volumeBackupService.backupHasPath(backupId, path),- staleTime: 0- })- };-</script>--<GenericFileBrowser {provider} rootLabel={volumeName} persistKey="volume-file-browser" />diff --git a/frontend/src/lib/components/file-browser/file-provider.ts b/frontend/src/lib/components/file-browser/file-provider.tsnew file mode 100644index 000000000..6b885edff--- /dev/null+++ b/frontend/src/lib/components/file-browser/file-provider.ts@@ -0,0 +1,18 @@+import type { FileEntry } from '#lib/types/shared';++export interface FileProvider {+ list: (path: string) => Promise<FileEntry[]>;+ mkdir: (path: string) => Promise<unknown>;+ upload: (path: string, file: File) => Promise<unknown>;+ delete: (path: string) => Promise<unknown>;+ download: (path: string) => Promise<void>;+ getContent: (path: string) => Promise<{ content: string }>;+}++export function sortFileEntries(files: FileEntry[]): FileEntry[] {+ return files.sort((a, b) => {+ if (a.isDirectory && !b.isDirectory) return -1;+ if (!a.isDirectory && b.isDirectory) return 1;+ return a.name.localeCompare(b.name);+ });+}diff --git a/frontend/src/lib/components/file-browser/index.ts b/frontend/src/lib/components/file-browser/index.tsindex 529c4f78d..69e6827a1 100644--- a/frontend/src/lib/components/file-browser/index.ts+++ b/frontend/src/lib/components/file-browser/index.ts@@ -1,24 +1,19 @@-import Root from './GenericFileBrowser.svelte';import Breadcrumb from './FileBreadcrumb.svelte';import List from './FileList.svelte';import Preview from './FilePreview.svelte';import UploadDialog from './FileUploadDialog.svelte';import CreateFolderDialog from './CreateFolderDialog.svelte';-import VolumeBrowser from './VolumeBrowser.svelte';-export type { FileProvider } from './GenericFileBrowser.svelte';-export { sortFileEntries } from './GenericFileBrowser.svelte';+export type { FileProvider } from './file-provider';+export { sortFileEntries } from './file-provider';export {- Root,Breadcrumb,List,Preview,UploadDialog,CreateFolderDialog,- VolumeBrowser,// aliases- Root as FileBrowser,Breadcrumb as FileBreadcrumb,List as FileList,Preview as FilePreview,diff --git a/frontend/src/routes/(app)/projects/components/ProjectFileTreePanel.svelte b/frontend/src/lib/components/workspace-file-tree-panel.sveltesimilarity index 55%rename from frontend/src/routes/(app)/projects/components/ProjectFileTreePanel.svelterename to frontend/src/lib/components/workspace-file-tree-panel.svelteindex 86423e981..7d648c426 100644--- a/frontend/src/routes/(app)/projects/components/ProjectFileTreePanel.svelte+++ b/frontend/src/lib/components/workspace-file-tree-panel.svelte@@ -11,33 +11,41 @@ArrowRightIcon,CreateFileIcon,CreateFolderIcon,+ DownloadIcon,EditIcon,FileTextIcon,FolderMoveIcon,FolderOpenIcon,LockIcon,+ RefreshIcon,TrashIcon,UploadIcon} from '#lib/icons';import { m } from '#lib/paraglide/messages';import { cn } from '#lib/utils';import {- compareProjectFileEntries,- joinProjectFilePath,- projectFileBasename,- projectFileParentPath,- projectFilePathMatches,- validateProjectFileName,- type ManagedProjectFileEntry- } from './project-file-tree-utils';-- const MAX_MANAGED_PROJECT_FILE_BYTES = 1024 * 1024;+ compareWorkspaceFileEntries,+ joinWorkspaceFilePath,+ workspaceFileBasename,+ workspaceFileParentPath,+ workspaceFilePathMatches,+ validateWorkspaceFileName,+ type WorkspaceFileEntry+ } from '#lib/utils/workspace-files';type DialogMode = 'create_file' | 'create_folder' | 'rename' | 'move' | 'upload';- type TreeRow = ManagedProjectFileEntry & {+ type TreeRow = WorkspaceFileEntry & {depth: number;hasChildren: boolean;};+ type WorkspaceTreeLeadingRow = {+ key: string;+ label: string;+ iconClass?: string;+ locked?: boolean;+ action?: boolean;+ onSelect?: () => void;+ };type FolderDestinationOption = {relativePath: string;label: string;@@ -48,31 +56,35 @@};interface Props {- composeFileName: string;- // The override row is pinned only by the project editor. showOverride renders- // the existing-override row (labeled overrideFileName); onAddOverride renders- // an "add override" affordance for a project that has none yet. Other- // consumers (new project, swarm stacks) omit all three.- overrideFileName?: string;- showOverride?: boolean;- onAddOverride?: () => void;- entries: ManagedProjectFileEntry[];+ title?: string;+ leadingRows?: WorkspaceTreeLeadingRow[];+ entries: WorkspaceFileEntry[];selectedFile: string;disabled?: boolean;readOnlyMessage?: string;onSelect: (key: string) => void;- onCreateFile?: (parentPath: string, name: string, content?: string) => void;+ onCreateFile?: (parentPath: string, name: string) => void;onCreateFolder?: (parentPath: string, name: string) => void;onRename?: (relativePath: string, newName: string) => void;onMove?: (relativePath: string, newParentPath: string) => void;onDelete?: (relativePath: string) => void;+ onUpload?: (parentPath: string, files: File[]) => Promise<string | void> | string | void;+ onDownload?: (relativePath: string) => void;+ onRestore?: (relativePath: string) => void;+ multipleUploads?: boolean;+ allowUploadOverwrite?: boolean;+ validateName?: (name: string, parentPath: string) => string | null;+ emptyMessage?: string;+ uploadDescription?: string;+ rootDestinationLabel?: string;+ rootPathMessage?: string;+ deleteConfirmMessage?: (name: string) => string;+ lockedLabel?: string;}let {- composeFileName,- overrideFileName,- showOverride = false,- onAddOverride,+ title = m.workspace_files(),+ leadingRows = [],entries,selectedFile,disabled = false,@@ -82,7 +94,19 @@onCreateFolder,onRename,onMove,- onDelete+ onDelete,+ onUpload,+ onDownload,+ onRestore,+ multipleUploads = false,+ allowUploadOverwrite = false,+ validateName,+ emptyMessage = m.workspace_files_empty(),+ uploadDescription = m.workspace_upload_description(),+ rootDestinationLabel = m.workspace_root_destination(),+ rootPathMessage = m.workspace_root_path(),+ deleteConfirmMessage = (name) => m.workspace_delete_confirm({ name }),+ lockedLabel = m.workspace_file_read_only()}: Props = $props();let openFolders = $state<Record<string, boolean>>({});@@ -94,26 +118,31 @@let dialogTargetPath = $state('');let dialogDestinationPath = $state('');let destinationOpenFolders = $state<Record<string, boolean>>({});- let uploadFile = $state<File | null>(null);+ let uploadFiles = $state<File[]>([]);let uploadInputKey = $state(0);let dialogSubmitting = $state(false);let dialogError = $state<string | null>(null);const entryByPath = $derived.by(() => new Map(entries.map((entry) => [entry.relativePath, entry])));- const selectedManagedPath = $derived(selectedFile.startsWith('file:') ? selectedFile.slice(5) : '');- const selectedManagedEntry = $derived(selectedManagedPath ? entryByPath.get(selectedManagedPath) : undefined);+ const selectedWorkspacePath = $derived(selectedFile.startsWith('file:') ? selectedFile.slice(5) : '');+ const selectedWorkspaceEntry = $derived(selectedWorkspacePath ? entryByPath.get(selectedWorkspacePath) : undefined);const selectedParentPath = $derived.by(() => {if (activeFolderPath && entryByPath.get(activeFolderPath)?.isDirectory) return activeFolderPath;- return selectedManagedEntry?.isDirectory ? selectedManagedEntry.relativePath : projectFileParentPath(selectedManagedPath);+ return selectedWorkspaceEntry?.isDirectory+ ? selectedWorkspaceEntry.relativePath+ : workspaceFileParentPath(selectedWorkspacePath);});const rows = $derived.by(() => flattenRows(entries, openFolders));const hasDirectories = $derived(entries.some((entry) => entry.isDirectory));- const canManageFiles = $derived(!!onCreateFile && !!onCreateFolder && !!onRename && !!onMove && !!onDelete);+ const canCreateFile = $derived(!!onCreateFile);+ const canCreateFolder = $derived(!!onCreateFolder);+ const canUpload = $derived(!!onUpload);+ const hasHeaderActions = $derived(canCreateFile || canCreateFolder || canUpload);const dialogTitle = $derived.by(() => {if (dialogMode === 'upload') return m.upload_file();if (dialogMode === 'move') return m.move();if (dialogMode === 'rename') return m.rename();- return dialogMode === 'create_folder' ? m.project_file_create_folder_title() : m.project_file_create_file_title();+ return dialogMode === 'create_folder' ? m.workspace_create_folder_title() : m.workspace_create_file_title();});const dialogActionLabel = $derived.by(() => {if (dialogMode === 'upload') return m.upload();@@ -143,16 +172,16 @@};}- function flattenRows(files: ManagedProjectFileEntry[], folderStates: Record<string, boolean>): TreeRow[] {- const byParent = new Map<string, ManagedProjectFileEntry[]>();+ function flattenRows(files: WorkspaceFileEntry[], folderStates: Record<string, boolean>): TreeRow[] {+ const byParent = new Map<string, WorkspaceFileEntry[]>();for (const entry of files) {- const parentPath = projectFileParentPath(entry.relativePath);+ const parentPath = workspaceFileParentPath(entry.relativePath);const siblings = byParent.get(parentPath) ?? [];siblings.push(entry);byParent.set(parentPath, siblings);}for (const siblings of byParent.values()) {- siblings.sort(compareProjectFileEntries);+ siblings.sort(compareWorkspaceFileEntries);}const result: TreeRow[] = [];@@ -178,7 +207,7 @@dialogTargetPath = '';dialogDestinationPath = parentPath;destinationOpenFolders = parentPath ? openAncestorDestinationFolders(parentPath) : {};- uploadFile = null;+ uploadFiles = [];dialogSubmitting = false;dialogError = null;dialogOpen = true;@@ -187,17 +216,17 @@function openRenameDialog(relativePath: string) {if (disabled) return;dialogMode = 'rename';- dialogName = projectFileBasename(relativePath);- dialogParentPath = projectFileParentPath(relativePath);+ dialogName = workspaceFileBasename(relativePath);+ dialogParentPath = workspaceFileParentPath(relativePath);dialogTargetPath = relativePath;dialogDestinationPath = '';- uploadFile = null;+ uploadFiles = [];dialogSubmitting = false;dialogError = null;dialogOpen = true;}- function compareProjectFolderPaths(a: string, b: string): number {+ function compareWorkspaceFolderPaths(a: string, b: string): number {const aSegments = a.split('/');const bSegments = b.split('/');const length = Math.min(aSegments.length, bSegments.length);@@ -223,7 +252,7 @@const childCounts = new Map<string, number>();for (const entry of entries) {if (!entry.isDirectory) continue;- const parentPath = projectFileParentPath(entry.relativePath);+ const parentPath = workspaceFileParentPath(entry.relativePath);childCounts.set(parentPath, (childCounts.get(parentPath) ?? 0) + 1);}return childCounts;@@ -234,17 +263,17 @@return [{relativePath: '',- label: m.project_file_root_destination(),+ label: rootDestinationLabel,depth: 0,hasChildren: (childCounts.get('') ?? 0) > 0,disabled: false},...entries.filter((candidate) => candidate.isDirectory)- .sort((a, b) => compareProjectFolderPaths(a.relativePath, b.relativePath))+ .sort((a, b) => compareWorkspaceFolderPaths(a.relativePath, b.relativePath)).map((candidate) => ({relativePath: candidate.relativePath,- label: projectFileBasename(candidate.relativePath),+ label: workspaceFileBasename(candidate.relativePath),depth: destinationDepth(candidate.relativePath),hasChildren: (childCounts.get(candidate.relativePath) ?? 0) > 0,disabled: false@@ -256,17 +285,17 @@const entry = entryByPath.get(relativePath);if (!entry) return [];- const basename = projectFileBasename(relativePath);- const currentParentPath = projectFileParentPath(relativePath);+ const basename = workspaceFileBasename(relativePath);+ const currentParentPath = workspaceFileParentPath(relativePath);return buildFolderDestinationOptions().map((candidate) => {- const targetPath = joinProjectFilePath(candidate.relativePath, basename);+ const targetPath = joinWorkspaceFilePath(candidate.relativePath, basename);let reason: string | undefined;if (candidate.relativePath === currentParentPath) {- reason = m.project_file_move_current_location();- } else if (entry.isDirectory && candidate.relativePath && projectFilePathMatches(candidate.relativePath, relativePath)) {- reason = m.project_file_move_descendant_blocked();+ reason = m.workspace_move_current_location();+ } else if (entry.isDirectory && candidate.relativePath && workspaceFilePathMatches(candidate.relativePath, relativePath)) {+ reason = m.workspace_move_descendant_blocked();} else if (entryByPath.has(targetPath)) {- reason = m.project_file_move_duplicate_destination();+ reason = m.workspace_move_duplicate_destination();}return {@@ -279,19 +308,19 @@function openAncestorDestinationFolders(relativePath: string): Record<string, boolean> {const folders: Record<string, boolean> = {};- let parentPath = projectFileParentPath(relativePath);+ let parentPath = workspaceFileParentPath(relativePath);while (parentPath) {folders[parentPath] = true;- parentPath = projectFileParentPath(parentPath);+ parentPath = workspaceFileParentPath(parentPath);}return folders;}function isDestinationVisible(relativePath: string): boolean {- let parentPath = projectFileParentPath(relativePath);+ let parentPath = workspaceFileParentPath(relativePath);while (parentPath) {if (destinationOpenFolders[parentPath] !== true) return false;- parentPath = projectFileParentPath(parentPath);+ parentPath = workspaceFileParentPath(parentPath);}return true;}@@ -313,7 +342,7 @@dialogTargetPath = relativePath;dialogDestinationPath = selectedDestinationPath;destinationOpenFolders = selectedDestinationPath ? openAncestorDestinationFolders(selectedDestinationPath) : {};- uploadFile = null;+ uploadFiles = [];dialogSubmitting = false;dialogError = null;dialogOpen = true;@@ -327,7 +356,7 @@dialogTargetPath = '';dialogDestinationPath = parentPath;destinationOpenFolders = parentPath ? openAncestorDestinationFolders(parentPath) : {};- uploadFile = null;+ uploadFiles = [];uploadInputKey += 1;dialogSubmitting = false;dialogError = null;@@ -336,38 +365,22 @@function handleUploadFileChange(event: Event) {const input = event.currentTarget as HTMLInputElement;- const file = input.files?.[0] ?? null;- uploadFile = file;- if (file) {- dialogName = file.name;+ uploadFiles = input.files ? [...input.files] : [];+ if (uploadFiles.length === 1) {+ dialogName = uploadFiles[0]?.name ?? '';}dialogError = null;}- async function readUploadFileContent(file: File): Promise<string | null> {- if (file.size > MAX_MANAGED_PROJECT_FILE_BYTES) {- dialogError = m.project_file_upload_too_large();- return null;- }-- try {- const bytes = new Uint8Array(await file.arrayBuffer());- if (bytes.includes(0)) {- dialogError = m.project_file_upload_text_required();- return null;- }- return new TextDecoder('utf-8', { fatal: true }).decode(bytes);- } catch {- dialogError = m.project_file_upload_text_required();- return null;- }+ function normalizeDialogName(name: string, parentPath: string): string | null {+ return validateName ? validateName(name, parentPath) : validateWorkspaceFileName(name);}async function handleDialogSubmit() {if (dialogMode === 'move') {const destination = allDestinationOptions.find((option) => option.relativePath === dialogDestinationPath);if (!destination || destination.disabled) {- dialogError = destination?.reason ?? m.project_file_invalid_move_destination();+ dialogError = destination?.reason ?? m.workspace_file_invalid_move_destination();return;}@@ -383,15 +396,15 @@}if (dialogMode === 'rename') {- const name = validateProjectFileName(dialogName, dialogParentPath, composeFileName);+ const name = normalizeDialogName(dialogName, dialogParentPath);if (!name) {- dialogError = m.project_file_invalid_name();+ dialogError = m.workspace_file_invalid_name();return;}- const targetPath = joinProjectFilePath(dialogParentPath, name);+ const targetPath = joinWorkspaceFilePath(dialogParentPath, name);if (targetPath !== dialogTargetPath && entryByPath.has(targetPath)) {- dialogError = m.project_file_duplicate_name();+ dialogError = m.workspace_file_duplicate_name();return;}@@ -400,39 +413,60 @@return;}- const name = validateProjectFileName(dialogName, dialogDestinationPath, composeFileName);- if (!name) {- dialogError = m.project_file_invalid_name();- return;- }-- const targetPath = joinProjectFilePath(dialogDestinationPath, name);- if (entryByPath.has(targetPath)) {- dialogError = m.project_file_duplicate_name();- return;- }-if (dialogMode === 'upload') {- if (!uploadFile) {- dialogError = m.project_file_upload_file_required();+ if (uploadFiles.length === 0) {+ dialogError = m.workspace_upload_file_required();return;}-- dialogSubmitting = true;- const content = await readUploadFileContent(uploadFile);- dialogSubmitting = false;- if (content === null) {+ const normalizedNames = multipleUploads+ ? uploadFiles.map((file) => normalizeDialogName(file.name, dialogDestinationPath))+ : [normalizeDialogName(dialogName, dialogDestinationPath)];+ if (normalizedNames.some((name) => !name)) {+ dialogError = m.workspace_file_invalid_name();+ return;+ }+ if (+ !allowUploadOverwrite &&+ normalizedNames.some((name) => name && entryByPath.has(joinWorkspaceFilePath(dialogDestinationPath, name)))+ ) {+ dialogError = m.workspace_file_duplicate_name();return;}- onCreateFile?.(dialogDestinationPath, name, content);- if (dialogDestinationPath) {- openFolders = {- ...openFolders,- [dialogDestinationPath]: true- };+ dialogSubmitting = true;+ try {+ const selectedFiles = multipleUploads+ ? uploadFiles+ : [+ new File([uploadFiles[0]!], normalizedNames[0]!, {+ type: uploadFiles[0]!.type,+ lastModified: uploadFiles[0]!.lastModified+ })+ ];+ const error = await onUpload?.(dialogDestinationPath, selectedFiles);+ if (typeof error === 'string' && error) {+ dialogError = error;+ return;+ }+ if (dialogDestinationPath) {+ openFolders = { ...openFolders, [dialogDestinationPath]: true };+ }+ dialogOpen = false;+ } finally {+ dialogSubmitting = false;}- dialogOpen = false;+ return;+ }++ const name = normalizeDialogName(dialogName, dialogDestinationPath);+ if (!name) {+ dialogError = m.workspace_file_invalid_name();+ return;+ }++ const targetPath = joinWorkspaceFilePath(dialogDestinationPath, name);+ if (entryByPath.has(targetPath)) {+ dialogError = m.workspace_file_duplicate_name();return;}@@ -453,11 +487,11 @@dialogOpen = false;}- function handleDelete(entry: ManagedProjectFileEntry) {+ function handleDelete(entry: WorkspaceFileEntry) {if (disabled) return;openConfirmDialog({title: m.delete_name({ name: entry.relativePath }),- message: m.project_file_delete_confirm({ name: entry.relativePath }),+ message: deleteConfirmMessage(entry.relativePath),confirm: {label: m.common_delete(),destructive: true,@@ -469,57 +503,63 @@<div class="flex min-h-0 flex-1 flex-col"><div class="flex h-9 shrink-0 items-center border-b border-border px-2">- <span class="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">{m.project_files()}</span>- {#if canManageFiles}+ <span class="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">{title}</span>+ {#if hasHeaderActions}<div class="ml-auto flex items-center gap-0.5">- <Tooltip.Root>- <Tooltip.Trigger>- <ArcaneButton- action="create"- size="icon"- tone="ghost"- class="size-6"- icon={CreateFileIcon}- showLabel={false}- {disabled}- customLabel={m.project_file_new_file()}- onclick={() => openCreateDialog('create_file')}- />- </Tooltip.Trigger>- <Tooltip.Content>{m.project_file_new_file()}</Tooltip.Content>- </Tooltip.Root>- <Tooltip.Root>- <Tooltip.Trigger>- <ArcaneButton- action="create"- size="icon"- tone="ghost"- class="size-6"- icon={CreateFolderIcon}- showLabel={false}- {disabled}- customLabel={m.new_folder()}- onclick={() => openCreateDialog('create_folder')}- />- </Tooltip.Trigger>- <Tooltip.Content>{m.new_folder()}</Tooltip.Content>- </Tooltip.Root>- <Tooltip.Root>- <Tooltip.Trigger>- <ArcaneButton- action="base"- size="icon"- tone="ghost"- class="size-6"- icon={UploadIcon}- showLabel={false}- {disabled}- customLabel={m.upload_file()}- onclick={() => openUploadDialog()}- />- </Tooltip.Trigger>- <Tooltip.Content>{m.upload_file()}</Tooltip.Content>- </Tooltip.Root>+ {#if canCreateFile}+ <Tooltip.Root>+ <Tooltip.Trigger>+ <ArcaneButton+ action="create"+ size="icon"+ tone="ghost"+ class="size-6"+ icon={CreateFileIcon}+ showLabel={false}+ {disabled}+ customLabel={m.workspace_new_file()}+ onclick={() => openCreateDialog('create_file')}+ />+ </Tooltip.Trigger>+ <Tooltip.Content>{m.workspace_new_file()}</Tooltip.Content>+ </Tooltip.Root>+ {/if}+ {#if canCreateFolder}+ <Tooltip.Root>+ <Tooltip.Trigger>+ <ArcaneButton+ action="create"+ size="icon"+ tone="ghost"+ class="size-6"+ icon={CreateFolderIcon}+ showLabel={false}+ {disabled}+ customLabel={m.new_folder()}+ onclick={() => openCreateDialog('create_folder')}+ />+ </Tooltip.Trigger>+ <Tooltip.Content>{m.new_folder()}</Tooltip.Content>+ </Tooltip.Root>+ {/if}+ {#if canUpload}+ <Tooltip.Root>+ <Tooltip.Trigger>+ <ArcaneButton+ action="base"+ size="icon"+ tone="ghost"+ class="size-6"+ icon={UploadIcon}+ showLabel={false}+ {disabled}+ customLabel={m.upload_file()}+ onclick={() => openUploadDialog()}+ />+ </Tooltip.Trigger>+ <Tooltip.Content>{m.upload_file()}</Tooltip.Content>+ </Tooltip.Root>+ {/if}</div>{/if}</div>@@ -530,78 +570,35 @@<div class="min-h-0 flex-1 overflow-auto"><TreeView.Root class="min-w-max p-2 whitespace-nowrap">- <button- type="button"- class={cn(- 'flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-[13px] hover:bg-accent',- selectedFile === 'compose' && 'bg-accent'- )}- onclick={() => onSelect('compose')}- >- {#if hasDirectories}- <span class="inline-flex size-4 shrink-0 items-center justify-center"></span>- {/if}- <FileTextIcon class="size-4 shrink-0 text-blue-500" />- <span class="min-w-0 flex-1 truncate">{composeFileName}</span>- <span class="inline-flex size-6 shrink-0 items-center justify-center">- <LockIcon class="size-3.5 shrink-0 text-muted-foreground" aria-label={m.project_file_protected()} />- </span>- </button>-- {#if showOverride}+ {#each leadingRows as leadingRow (leadingRow.key)}<buttontype="button"class={cn('flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-[13px] hover:bg-accent',- selectedFile === 'override' && 'bg-accent'+ selectedFile === leadingRow.key && 'bg-accent',+ leadingRow.action && 'text-muted-foreground hover:text-foreground')}- onclick={() => onSelect('override')}+ onclick={() => (leadingRow.onSelect ? leadingRow.onSelect() : onSelect(leadingRow.key))}>{#if hasDirectories}<span class="inline-flex size-4 shrink-0 items-center justify-center"></span>{/if}- <FileTextIcon class="size-4 shrink-0 text-purple-500" />- <span class="min-w-0 flex-1 truncate">{overrideFileName}</span>- <span class="inline-flex size-6 shrink-0 items-center justify-center">- <LockIcon class="size-3.5 shrink-0 text-muted-foreground" aria-label={m.project_file_protected()} />- </span>- </button>- {:else if onAddOverride}- <button- type="button"- class="flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-[13px] text-muted-foreground hover:bg-accent hover:text-foreground"- onclick={() => onAddOverride?.()}- >- {#if hasDirectories}- <span class="inline-flex size-4 shrink-0 items-center justify-center"></span>+ {#if leadingRow.action}+ <CreateFileIcon class="size-4 shrink-0" />+ {:else}+ <FileTextIcon class={cn('size-4 shrink-0', leadingRow.iconClass ?? 'text-muted-foreground')} />+ {/if}+ <span class="min-w-0 flex-1 truncate">{leadingRow.label}</span>+ {#if leadingRow.locked}+ <span class="inline-flex size-6 shrink-0 items-center justify-center">+ <LockIcon class="size-3.5 shrink-0 text-muted-foreground" aria-label={lockedLabel} />+ </span>{/if}- <CreateFileIcon class="size-4 shrink-0" />- <span class="min-w-0 flex-1 truncate">{m.compose_override_add()}</span></button>- {/if}-- <button- type="button"- class={cn(- 'flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-[13px] hover:bg-accent',- selectedFile === 'env' && 'bg-accent'- )}- onclick={() => onSelect('env')}- >- {#if hasDirectories}- <span class="inline-flex size-4 shrink-0 items-center justify-center"></span>- {/if}- <FileTextIcon class="size-4 shrink-0 text-green-500" />- <span class="min-w-0 flex-1 truncate">.env</span>- <span class="inline-flex size-6 shrink-0 items-center justify-center">- <LockIcon class="size-3.5 shrink-0 text-muted-foreground" aria-label={m.project_file_protected()} />- </span>- </button>+ {/each}{#if rows.length === 0}- {#if canManageFiles}- <div class="px-7 py-3 text-xs text-muted-foreground">{m.project_files_empty()}</div>- {/if}+ <div class="px-7 py-3 text-xs text-muted-foreground">{emptyMessage}</div>{:else}{#each rows as row (row.relativePath)}<div@@ -616,8 +613,8 @@type="button"class="inline-flex size-4 shrink-0 items-center justify-center rounded hover:bg-muted"aria-label={openFolders[row.relativePath]- ? m.project_file_collapse_folder({ name: row.name })- : m.project_file_expand_folder({ name: row.name })}+ ? m.workspace_file_collapse_folder({ name: row.name })+ : m.workspace_file_expand_folder({ name: row.name })}onclick={() => toggleFolder(row.relativePath)}>{#if openFolders[row.relativePath] === true}@@ -651,50 +648,90 @@{/if}</button>- {#if canManageFiles}+ {#if row.locked || row.isSymlink || onRename || onMove || onDelete || onDownload || onRestore}<div class="flex shrink-0 items-center gap-0.5">- <Tooltip.Root>- <Tooltip.Trigger>- <button- type="button"- class="inline-flex size-6 items-center justify-center rounded text-foreground hover:bg-foreground/10"- aria-label={m.project_file_rename_label({ name: row.relativePath })}- {disabled}- onclick={() => openRenameDialog(row.relativePath)}- >- <EditIcon class="size-3.5" />- </button>- </Tooltip.Trigger>- <Tooltip.Content>{m.rename()}</Tooltip.Content>- </Tooltip.Root>- <Tooltip.Root>- <Tooltip.Trigger>- <button- type="button"- class="inline-flex size-6 items-center justify-center rounded text-foreground hover:bg-foreground/10"- aria-label={m.project_file_move_label({ name: row.relativePath })}- {disabled}- onclick={() => openMoveDialog(row.relativePath)}- >- <FolderMoveIcon class="size-3.5" />- </button>- </Tooltip.Trigger>- <Tooltip.Content>{m.move()}</Tooltip.Content>- </Tooltip.Root>- <Tooltip.Root>- <Tooltip.Trigger>- <button- type="button"- class="inline-flex size-6 items-center justify-center rounded text-destructive hover:bg-destructive/10"- aria-label={m.delete_name({ name: row.relativePath })}- {disabled}- onclick={() => handleDelete(row)}- >- <TrashIcon class="size-3.5" />- </button>- </Tooltip.Trigger>- <Tooltip.Content>{m.common_delete()}</Tooltip.Content>- </Tooltip.Root>+ {#if onDownload && !row.isDirectory && !row.pending}+ <Tooltip.Root>+ <Tooltip.Trigger>+ <button+ type="button"+ class="inline-flex size-6 items-center justify-center rounded text-foreground hover:bg-foreground/10"+ aria-label={m.templates_download()}+ onclick={() => onDownload?.(row.relativePath)}+ >+ <DownloadIcon class="size-3.5" />+ </button>+ </Tooltip.Trigger>+ <Tooltip.Content>{m.templates_download()}</Tooltip.Content>+ </Tooltip.Root>+ {/if}+ {#if row.locked || row.isSymlink}+ <LockIcon class="mx-1 size-3.5 shrink-0 text-muted-foreground" aria-label={lockedLabel} />+ {:else}+ {#if onRestore && !row.isDirectory && !row.pending}+ <Tooltip.Root>+ <Tooltip.Trigger>+ <button+ type="button"+ class="inline-flex size-6 items-center justify-center rounded text-foreground hover:bg-foreground/10"+ aria-label={m.workspace_restore()}+ onclick={() => onRestore?.(row.relativePath)}+ >+ <RefreshIcon class="size-3.5" />+ </button>+ </Tooltip.Trigger>+ <Tooltip.Content>{m.workspace_restore()}</Tooltip.Content>+ </Tooltip.Root>+ {/if}+ {#if onRename}+ <Tooltip.Root>+ <Tooltip.Trigger>+ <button+ type="button"+ class="inline-flex size-6 items-center justify-center rounded text-foreground hover:bg-foreground/10"+ aria-label={m.workspace_file_rename_label({ name: row.relativePath })}+ {disabled}+ onclick={() => openRenameDialog(row.relativePath)}+ >+ <EditIcon class="size-3.5" />+ </button>+ </Tooltip.Trigger>+ <Tooltip.Content>{m.rename()}</Tooltip.Content>+ </Tooltip.Root>+ {/if}+ {#if onMove}+ <Tooltip.Root>+ <Tooltip.Trigger>+ <button+ type="button"+ class="inline-flex size-6 items-center justify-center rounded text-foreground hover:bg-foreground/10"+ aria-label={m.workspace_file_move_label({ name: row.relativePath })}+ {disabled}+ onclick={() => openMoveDialog(row.relativePath)}+ >+ <FolderMoveIcon class="size-3.5" />+ </button>+ </Tooltip.Trigger>+ <Tooltip.Content>{m.move()}</Tooltip.Content>+ </Tooltip.Root>+ {/if}+ {#if onDelete}+ <Tooltip.Root>+ <Tooltip.Trigger>+ <button+ type="button"+ class="inline-flex size-6 items-center justify-center rounded text-destructive hover:bg-destructive/10"+ aria-label={m.delete_name({ name: row.relativePath })}+ {disabled}+ onclick={() => handleDelete(row)}+ >+ <TrashIcon class="size-3.5" />+ </button>+ </Tooltip.Trigger>+ <Tooltip.Content>{m.common_delete()}</Tooltip.Content>+ </Tooltip.Root>+ {/if}+ {/if}</div>{/if}</div>@@ -717,35 +754,41 @@<Dialog.Title>{dialogTitle}</Dialog.Title><Dialog.Description>{#if dialogMode === 'move'}- {m.project_file_move_description({ name: dialogTargetPath })}+ {m.workspace_file_move_description({ name: dialogTargetPath })}{:else if dialogMode === 'upload'}- {m.project_file_upload_description()}+ {uploadDescription}{:else if dialogMode === 'create_file' || dialogMode === 'create_folder'}- {dialogDestinationPath ? m.project_file_parent_path({ path: dialogDestinationPath }) : m.project_file_root_path()}+ {dialogDestinationPath ? m.workspace_file_parent_path({ path: dialogDestinationPath }) : rootPathMessage}{:else}- {dialogParentPath ? m.project_file_parent_path({ path: dialogParentPath }) : m.project_file_root_path()}+ {dialogParentPath ? m.workspace_file_parent_path({ path: dialogParentPath }) : rootPathMessage}{/if}</Dialog.Description></Dialog.Header>{#if dialogMode === 'upload'}<div class="space-y-2">- <Label for="project-file-upload">{m.project_file_upload_file_label()}</Label>+ <Label for="workspace-file-upload">{m.workspace_upload_file_label()}</Label>{#key uploadInputKey}- <Input id="project-file-upload" type="file" onchange={handleUploadFileChange} aria-invalid={!!dialogError} />+ <Input+ id="workspace-file-upload"+ type="file"+ multiple={multipleUploads}+ onchange={handleUploadFileChange}+ aria-invalid={!!dialogError}+ />{/key}</div>{/if}- {#if dialogMode !== 'move'}+ {#if dialogMode !== 'move' && (dialogMode !== 'upload' || !multipleUploads)}<div class="space-y-2">- <Label for="project-file-name">{m.common_name()}</Label>+ <Label for="workspace-file-name">{m.common_name()}</Label><Input- id="project-file-name"+ id="workspace-file-name"bind:value={dialogName}placeholder={dialogMode === 'create_folder'- ? m.project_file_folder_name_placeholder()- : m.project_file_name_placeholder()}+ ? m.workspace_folder_name_placeholder()+ : m.workspace_file_name_placeholder()}aria-invalid={!!dialogError}/></div>@@ -753,7 +796,7 @@{#if hasDestinationPicker}<div class="min-h-0 space-y-2">- <Label>{m.project_file_move_destination_label()}</Label>+ <Label>{m.workspace_file_move_destination_label()}</Label><div class="max-h-[56vh] min-h-80 space-y-1 overflow-auto rounded-md border p-1">{#each visibleDestinationOptions as option (option.relativePath)}<div@@ -769,8 +812,8 @@type="button"class="inline-flex size-4 shrink-0 items-center justify-center rounded hover:bg-muted"aria-label={destinationOpenFolders[option.relativePath]- ? m.project_file_collapse_folder({ name: option.label })- : m.project_file_expand_folder({ name: option.label })}+ ? m.workspace_file_collapse_folder({ name: option.label })+ : m.workspace_file_expand_folder({ name: option.label })}onclick={() => toggleDestinationFolder(option.relativePath)}>{#if destinationOpenFolders[option.relativePath] === true}@@ -817,7 +860,7 @@loading={dialogSubmitting}disabled={dialogSubmitting ||(dialogMode === 'move' && !hasValidDestination) ||- (dialogMode === 'upload' && !uploadFile)}+ (dialogMode === 'upload' && uploadFiles.length === 0)}/></Dialog.Footer></form>diff --git a/frontend/src/lib/hooks/use-url-tab.svelte.ts b/frontend/src/lib/hooks/use-url-tab.svelte.tsindex 8b9364137..1cd712baa 100644--- a/frontend/src/lib/hooks/use-url-tab.svelte.ts+++ b/frontend/src/lib/hooks/use-url-tab.svelte.ts@@ -6,9 +6,15 @@ type UseUrlTabOptions<T extends string> = {validTabs: () => readonly T[];defaultTab: () => T;ready?: () => boolean;+ aliases?: () => Readonly<Partial<Record<string, T>>>;};-export function useUrlTab<T extends string>({ validTabs, defaultTab, ready = () => true }: UseUrlTabOptions<T>) {+export function useUrlTab<T extends string>({+ validTabs,+ defaultTab,+ ready = () => true,+ aliases = () => ({})+}: UseUrlTabOptions<T>) {let pendingUrlUpdate = Promise.resolve();function currentUrl() {@@ -36,7 +42,9 @@ export function useUrlTab<T extends string>({ validTabs, defaultTab, ready = ()const fallback = tabs.includes(defaultValue) ? defaultValue : (tabs[0] ?? defaultValue);const requested = url.searchParams.get('tab');- return requested && tabs.includes(requested as T) ? (requested as T) : fallback;+ if (!requested) return fallback;+ const aliased = aliases()[requested] ?? requested;+ return tabs.includes(aliased as T) ? (aliased as T) : fallback;}let value = $state<T>(resolveTab());diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.tsindex c5a9c4eea..ee5a0bd4d 100644--- a/frontend/src/lib/query/query-keys.ts+++ b/frontend/src/lib/query/query-keys.ts@@ -116,7 +116,9 @@ export const queryKeys = {['project', 'check-updates', environmentId, projectId] as const,statusCounts: (environmentId: string) => ['projects', 'status-counts', environmentId] as const,detail: (environmentId: string, projectId: string) => ['project', environmentId, projectId] as const,- files: (environmentId: string, projectId: string) => ['project', environmentId, projectId, 'files'] as const+ workspace: (environmentId: string, projectId: string) => ['project', environmentId, projectId, 'workspace'] as const,+ workspaceFile: (environmentId: string, projectId: string, relativePath: string) =>+ ['project', environmentId, projectId, 'workspace-file', relativePath] as const},networks: {all: ['networks'] as const,@@ -140,9 +142,9 @@ export const queryKeys = {table: (environmentId: string, options: SearchPaginationSortRequest) =>['volumes', environmentId, stableSerialize(options)] as const,detail: (environmentId: string, volumeName: string) => ['volume', environmentId, volumeName] as const,- list: (volumeName: string, path: string) => ['volume-browser', volumeName, 'list', path] as const,- listPrefix: (volumeName: string) => ['volume-browser', volumeName, 'list'] as const,- content: (volumeName: string, path: string) => ['volume-browser', volumeName, 'content', path] as const,+ workspace: (environmentId: string, volumeName: string) => ['volume', environmentId, volumeName, 'workspace'] as const,+ workspaceFile: (environmentId: string, volumeName: string, relativePath: string) =>+ ['volume', environmentId, volumeName, 'workspace-file', relativePath] as const,backups: (volumeName: string) => ['volume-backups', volumeName] as const,backupHasPath: (backupId: string, path: string) => ['volume-backups', backupId, 'has-path', path] as const},diff --git a/frontend/src/lib/services/project-service.ts b/frontend/src/lib/services/project-service.tsindex cb1718afd..b76c2175e 100644--- a/frontend/src/lib/services/project-service.ts+++ b/frontend/src/lib/services/project-service.ts@@ -1,8 +1,8 @@import { m } from '#lib/paraglide/messages';import { environmentStore } from '#lib/stores/environment.store.svelte';import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';-import type { IncludeFile, Project, ProjectStatusCounts } from '#lib/types/swarm';-import type { ProjectFileChange, ProjectFileDraft } from '#lib/types/project-files';+import type { Project, ProjectStatusCounts } from '#lib/types/swarm';+import type { ProjectWorkspaceFileDraft } from '#lib/types/project-workspace';import { readNdjsonStream } from '#lib/utils/streaming';import { transformPaginationParams } from '#lib/utils/tables';import BaseAPIService from './api-service';@@ -59,16 +59,21 @@ class ProjectService extends BaseAPIService {projectName: string,composeContent: string,envContent?: string,- projectFiles?: ProjectFileDraft[]+ workspaceFiles: ProjectWorkspaceFileDraft[] = []): Promise<Project> {const envId = await environmentStore.getCurrentEnvironmentId();- const payload = {- name: projectName,- composeContent,- envContent,- projectFiles- };- return this.handleResponse(this.api.post(`/environments/${envId}/projects`, payload));+ const form = new FormData();+ const uploads: File[] = [];+ const fileChanges = workspaceFiles.map((file) => {+ if (file.isDirectory) return { operation: 'create_folder' as const, relativePath: file.relativePath };+ const uploadIndex = uploads.length;+ uploads.push(new File([file.content ?? ''], file.relativePath));+ return { operation: 'create_file' as const, relativePath: file.relativePath, uploadIndex };+ });+ form.append('project', JSON.stringify({ name: projectName, composeContent, envContent }));+ form.append('manifest', JSON.stringify({ fileChanges }));+ for (const file of uploads) form.append('files', file, file.name);+ return this.handleResponse(this.api.post(`/environments/${envId}/projects`, form));}async getProject(projectId: string): Promise<Project> {@@ -78,8 +83,6 @@ class ProjectService extends BaseAPIService {async getProjectForEnvironment(environmentId: string, projectId: string): Promise<Project> {const basePath = `/environments/${environmentId}/projects/${projectId}`;- // The /files section walks the project directory recursively and can be- // slow on large projects, so it is fetched lazily via getProjectFiles.const [summary, compose, runtime, updates] = await Promise.all([this.getProjectSection(basePath),this.getProjectSection(`${basePath}/compose`),@@ -95,10 +98,6 @@ class ProjectService extends BaseAPIService {};}- async getProjectFiles(environmentId: string, projectId: string): Promise<Project> {- return this.getProjectSection(`/environments/${environmentId}/projects/${projectId}/files`);- }-private async getProjectSection(path: string): Promise<Project> {const response = await this.handleResponse<{ project?: Project; success?: boolean } | Project>(this.api.get(path));return 'project' in response && response.project ? response.project : (response as Project);@@ -138,19 +137,6 @@ class ProjectService extends BaseAPIService {});}- async getProjectFile(projectId: string, relativePath: string): Promise<IncludeFile> {- const envId = await this.resolveEnvironmentId();- return this.getProjectFileForEnvironment(envId, projectId, relativePath);- }-- async getProjectFileForEnvironment(environmentId: string, projectId: string, relativePath: string): Promise<IncludeFile> {- return this.handleResponse<IncludeFile>(- this.api.get(`/environments/${environmentId}/projects/${projectId}/file`, {- params: { relativePath }- })- );- }-async getProjectStatusCounts(): Promise<ProjectStatusCounts> {const envId = await this.resolveEnvironmentId();return this.getProjectStatusCountsForEnvironment(envId);@@ -166,9 +152,7 @@ class ProjectService extends BaseAPIService {name?: string,composeContent?: string,envContent?: string,- overrideContent?: string,- fileTreeRevision?: string,- fileChanges?: ProjectFileChange[]+ overrideContent?: string): Promise<Project> {const envId = await environmentStore.getCurrentEnvironmentId();const payload: {@@ -176,8 +160,6 @@ class ProjectService extends BaseAPIService {composeContent?: string;envContent?: string;overrideContent?: string;- fileTreeRevision?: string;- fileChanges?: ProjectFileChange[];} = {};if (name !== undefined) {payload.name = name;@@ -191,22 +173,9 @@ class ProjectService extends BaseAPIService {if (overrideContent !== undefined) {payload.overrideContent = overrideContent;}- if (fileChanges && fileChanges.length > 0) {- payload.fileTreeRevision = fileTreeRevision;- payload.fileChanges = fileChanges;- }return this.handleResponse(this.api.put(`/environments/${envId}/projects/${projectId}`, payload));}- async updateProjectIncludeFile(projectId: string, relativePath: string, content: string): Promise<Project> {- const envId = await environmentStore.getCurrentEnvironmentId();- const payload = {- relativePath,- content- };- return this.handleResponse(this.api.put(`/environments/${envId}/projects/${projectId}/includes`, payload));- }-async restartProject(projectId: string, services?: string[]): Promise<unknown> {const envId = await environmentStore.getCurrentEnvironmentId();let params: URLSearchParams | undefined;diff --git a/frontend/src/lib/services/project-workspace-service.ts b/frontend/src/lib/services/project-workspace-service.tsnew file mode 100644index 000000000..7d6cda3ee--- /dev/null+++ b/frontend/src/lib/services/project-workspace-service.ts@@ -0,0 +1,46 @@+import { environmentStore } from '#lib/stores/environment.store.svelte';+import type { ProjectWorkspace, ProjectWorkspaceFileContent, ProjectWorkspaceUpdateManifest } from '#lib/types/project-workspace';+import { downloadBlob, filenameFromPath } from '#lib/utils/browser-download';+import BaseAPIService from './api-service';++class ProjectWorkspaceService extends BaseAPIService {+ private async resolveEnvironmentId(environmentId?: string): Promise<string> {+ return environmentId ?? (await environmentStore.getCurrentEnvironmentId());+ }++ async getWorkspace(projectId: string, environmentId?: string): Promise<ProjectWorkspace> {+ const envId = await this.resolveEnvironmentId(environmentId);+ return this.handleResponse(this.api.get(`/environments/${envId}/projects/${projectId}/workspace`));+ }++ async getWorkspaceFile(projectId: string, relativePath: string, environmentId?: string): Promise<ProjectWorkspaceFileContent> {+ const envId = await this.resolveEnvironmentId(environmentId);+ return this.handleResponse(+ this.api.get(`/environments/${envId}/projects/${projectId}/workspace/file`, { params: { relativePath } })+ );+ }++ async updateWorkspace(+ projectId: string,+ manifest: ProjectWorkspaceUpdateManifest,+ files: File[],+ environmentId?: string+ ): Promise<ProjectWorkspace> {+ const envId = await this.resolveEnvironmentId(environmentId);+ const form = new FormData();+ form.append('manifest', JSON.stringify(manifest));+ for (const file of files) form.append('files', file, file.name);+ return this.handleResponse(this.api.put(`/environments/${envId}/projects/${projectId}/workspace`, form));+ }++ async downloadWorkspaceFile(projectId: string, relativePath: string, environmentId?: string): Promise<void> {+ const envId = await this.resolveEnvironmentId(environmentId);+ const response = await this.api.get(`/environments/${envId}/projects/${projectId}/workspace/file/download`, {+ params: { relativePath },+ responseType: 'blob'+ });+ downloadBlob(response.data, filenameFromPath(relativePath));+ }+}++export const projectWorkspaceService = new ProjectWorkspaceService();diff --git a/frontend/src/lib/services/settings-service.ts b/frontend/src/lib/services/settings-service.tsindex f98e1c551..6b5c7193d 100644--- a/frontend/src/lib/services/settings-service.ts+++ b/frontend/src/lib/services/settings-service.ts@@ -125,6 +125,9 @@ class SettingsService extends BaseAPIService {}if (value === 'true') return true;if (value === 'false') return false;+ if (key === 'projectWorkspaceMaxFileSizeMb' || key === 'volumeWorkspaceMaxFileSizeMb') {+ return Number(value);+ }return value;}}diff --git a/frontend/src/lib/services/volume-browser-service.ts b/frontend/src/lib/services/volume-browser-service.tsdeleted file mode 100644index 5ba7686f6..000000000--- a/frontend/src/lib/services/volume-browser-service.ts+++ /dev/null@@ -1,57 +0,0 @@-import BaseAPIService from './api-service';-import { environmentStore } from '#lib/stores/environment.store.svelte';-import type { FileEntry, FileContentResponse } from '#lib/types/shared';-import { downloadBlob, filenameFromPath } from '#lib/utils/browser-download';--class VolumeBrowserService extends BaseAPIService {- async listDirectory(volumeName: string, path: string = '/'): Promise<FileEntry[]> {- const envId = await environmentStore.getCurrentEnvironmentId();- const res = await this.api.get(`/environments/${envId}/volumes/${volumeName}/browse`, {- params: { path }- });- return res.data.data;- }-- async getFileContent(volumeName: string, path: string): Promise<FileContentResponse> {- const envId = await environmentStore.getCurrentEnvironmentId();- const res = await this.api.get(`/environments/${envId}/volumes/${volumeName}/browse/content`, {- params: { path }- });- return res.data.data;- }-- async downloadFile(volumeName: string, path: string): Promise<void> {- const envId = await environmentStore.getCurrentEnvironmentId();- const res = await this.api.get(`/environments/${envId}/volumes/${volumeName}/browse/download`, {- params: { path },- responseType: 'blob'- });-- downloadBlob(res.data, filenameFromPath(path));- }-- async uploadFile(volumeName: string, path: string, file: File): Promise<any> {- const envId = await environmentStore.getCurrentEnvironmentId();- return this.postFile(`/environments/${envId}/volumes/${volumeName}/browse/upload`, file, { path });- }-- async createDirectory(volumeName: string, path: string): Promise<any> {- const envId = await environmentStore.getCurrentEnvironmentId();- return this.handleResponse(- this.api.post(`/environments/${envId}/volumes/${volumeName}/browse/mkdir`, null, {- params: { path }- })- );- }-- async deleteFile(volumeName: string, path: string): Promise<any> {- const envId = await environmentStore.getCurrentEnvironmentId();- return this.handleResponse(- this.api.delete(`/environments/${envId}/volumes/${volumeName}/browse`, {- params: { path }- })- );- }-}--export const volumeBrowserService = new VolumeBrowserService();diff --git a/frontend/src/lib/services/volume-workspace-service.ts b/frontend/src/lib/services/volume-workspace-service.tsnew file mode 100644index 000000000..e27b128ce--- /dev/null+++ b/frontend/src/lib/services/volume-workspace-service.ts@@ -0,0 +1,46 @@+import { environmentStore } from '#lib/stores/environment.store.svelte';+import type { VolumeWorkspace, VolumeWorkspaceFileContent, VolumeWorkspaceUpdateManifest } from '#lib/types/volume-workspace';+import { downloadBlob, filenameFromPath } from '#lib/utils/browser-download';+import BaseAPIService from './api-service';++class VolumeWorkspaceService extends BaseAPIService {+ private async resolveEnvironmentId(environmentId?: string): Promise<string> {+ return environmentId ?? (await environmentStore.getCurrentEnvironmentId());+ }++ async getWorkspace(volumeName: string, environmentId?: string): Promise<VolumeWorkspace> {+ const envId = await this.resolveEnvironmentId(environmentId);+ return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}/workspace`));+ }++ async getWorkspaceFile(volumeName: string, relativePath: string, environmentId?: string): Promise<VolumeWorkspaceFileContent> {+ const envId = await this.resolveEnvironmentId(environmentId);+ return this.handleResponse(+ this.api.get(`/environments/${envId}/volumes/${volumeName}/workspace/file`, { params: { relativePath } })+ );+ }++ async updateWorkspace(+ volumeName: string,+ manifest: VolumeWorkspaceUpdateManifest,+ files: File[],+ environmentId?: string+ ): Promise<VolumeWorkspace> {+ const envId = await this.resolveEnvironmentId(environmentId);+ const form = new FormData();+ form.append('manifest', JSON.stringify(manifest));+ for (const file of files) form.append('files', file, file.name);+ return this.handleResponse(this.api.put(`/environments/${envId}/volumes/${volumeName}/workspace`, form));+ }++ async downloadWorkspaceFile(volumeName: string, relativePath: string, environmentId?: string): Promise<void> {+ const envId = await this.resolveEnvironmentId(environmentId);+ const response = await this.api.get(`/environments/${envId}/volumes/${volumeName}/workspace/file/download`, {+ params: { relativePath },+ responseType: 'blob'+ });+ downloadBlob(response.data, filenameFromPath(relativePath));+ }+}++export const volumeWorkspaceService = new VolumeWorkspaceService();diff --git a/frontend/src/lib/types/project-files.ts b/frontend/src/lib/types/project-files.tsdeleted file mode 100644index 3157e548f..000000000--- a/frontend/src/lib/types/project-files.ts+++ /dev/null@@ -1,27 +0,0 @@-export interface ProjectFile {- path: string;- relativePath: string;- name: string;- isDirectory: boolean;- size: number;- modTime?: string;- protected?: boolean;- content?: string;-}--export interface ProjectFileDraft {- relativePath: string;- isDirectory?: boolean;- content?: string;-}--export type ProjectFileChangeOperation = 'create_file' | 'create_folder' | 'update_file' | 'rename' | 'move' | 'delete';--export interface ProjectFileChange {- operation: ProjectFileChangeOperation;- relativePath: string;- newName?: string;- newParentPath?: string;- content?: string;- recursive?: boolean;-}diff --git a/frontend/src/lib/types/project-workspace.ts b/frontend/src/lib/types/project-workspace.tsnew file mode 100644index 000000000..8eb837da5--- /dev/null+++ b/frontend/src/lib/types/project-workspace.ts@@ -0,0 +1,16 @@+import type { Workspace, WorkspaceFileChange, WorkspaceFileContent, WorkspaceFileDraft, WorkspaceFileEntry } from './workspace';++export type ProjectWorkspaceFile = WorkspaceFileEntry;+export type ProjectWorkspace = Workspace;+export type ProjectWorkspaceFileContent = WorkspaceFileContent;+export type ProjectWorkspaceFileChange = WorkspaceFileChange;+export type ProjectWorkspaceFileDraft = WorkspaceFileDraft;++export interface ProjectWorkspaceUpdateManifest {+ fileTreeRevision: string;+ fileChanges: ProjectWorkspaceFileChange[];+}++export interface CreateProjectWorkspaceManifest {+ fileChanges: ProjectWorkspaceFileChange[];+}diff --git a/frontend/src/lib/types/settings.ts b/frontend/src/lib/types/settings.tsindex 31204611f..69420dcbd 100644--- a/frontend/src/lib/types/settings.ts+++ b/frontend/src/lib/types/settings.ts@@ -45,7 +45,9 @@ export type Settings = {autoHealExcludedContainers?: string;autoHealMaxRestarts?: number;autoHealRestartWindow?: number;- volumeBrowserHelperIdleTimeout?: number;+ volumeHelperIdleTimeout?: number;+ projectWorkspaceMaxFileSizeMb?: number;+ volumeWorkspaceMaxFileSizeMb?: number;maxImageUploadSize: number;gitSyncMaxFiles: number;gitSyncMaxTotalSizeMb: number;diff --git a/frontend/src/lib/types/shared.ts b/frontend/src/lib/types/shared.tsindex 03e5c2529..a880f3045 100644--- a/frontend/src/lib/types/shared.ts+++ b/frontend/src/lib/types/shared.ts@@ -91,6 +91,7 @@ export interface GPUStats {export interface FileEntry {name: string;path: string;+ relativePath?: string;isDirectory: boolean;size: number;modTime: string;diff --git a/frontend/src/lib/types/swarm.ts b/frontend/src/lib/types/swarm.tsindex 3f579afb5..11101f63e 100644--- a/frontend/src/lib/types/swarm.ts+++ b/frontend/src/lib/types/swarm.ts@@ -1,5 +1,3 @@-import type { ProjectFile } from './project-files';-// --- Swarm services, ports, mounts ---export interface SwarmServicePort {@@ -617,10 +615,6 @@ export interface Project {overrideFileName?: string;envContent?: string;includeFiles?: IncludeFile[];- directoryFiles?: IncludeFile[];- projectFiles?: ProjectFile[];- fileTreeRevision?: string;- fileTreeTruncated?: boolean;}export interface ProjectStatusCounts {diff --git a/frontend/src/lib/types/volume-workspace.ts b/frontend/src/lib/types/volume-workspace.tsnew file mode 100644index 000000000..3fd476fad--- /dev/null+++ b/frontend/src/lib/types/volume-workspace.ts@@ -0,0 +1,32 @@+import type {+ Workspace,+ WorkspaceFileChange,+ WorkspaceFileContent,+ WorkspaceFileEntry,+ WorkspaceReadOnlyReason+} from './workspace';++export type VolumeWorkspaceFile = WorkspaceFileEntry;+export type VolumeWorkspace = Workspace;+export interface VolumeWorkspaceFileContent extends Omit<WorkspaceFileContent, 'readOnlyReason'> {+ readOnlyReason?: WorkspaceReadOnlyReason | 'restore_pending';+}++export type VolumeWorkspaceFileChangeOperation =+ | 'create_file'+ | 'create_folder'+ | 'update_file'+ | 'rename'+ | 'move'+ | 'delete'+ | 'restore_file';++export interface VolumeWorkspaceFileChange extends Omit<WorkspaceFileChange, 'operation'> {+ operation: VolumeWorkspaceFileChangeOperation;+ backupId?: string;+}++export interface VolumeWorkspaceUpdateManifest {+ fileTreeRevision: string;+ fileChanges: VolumeWorkspaceFileChange[];+}diff --git a/frontend/src/lib/types/workspace.ts b/frontend/src/lib/types/workspace.tsnew file mode 100644index 000000000..43d766ad2--- /dev/null+++ b/frontend/src/lib/types/workspace.ts@@ -0,0 +1,50 @@+export type WorkspaceReadOnlyReason = 'binary' | 'too_large' | 'symlink' | 'special';++export interface WorkspaceFileEntry {+ path: string;+ relativePath: string;+ name: string;+ isDirectory: boolean;+ size: number;+ modTime?: string;+ mode?: string;+ isSymlink: boolean;+ linkTarget?: string;+ editable: boolean;+ readOnlyReason?: WorkspaceReadOnlyReason;+}++export interface Workspace {+ files: WorkspaceFileEntry[];+ fileTreeRevision: string;+ fileTreeTruncated: boolean;+ activityId?: string;+}++export interface WorkspaceFileContent {+ path: string;+ relativePath: string;+ name: string;+ size: number;+ mimeType: string;+ content?: string;+ editable: boolean;+ readOnlyReason?: WorkspaceReadOnlyReason;+}++export type WorkspaceFileChangeOperation = 'create_file' | 'create_folder' | 'update_file' | 'rename' | 'move' | 'delete';++export interface WorkspaceFileChange {+ operation: WorkspaceFileChangeOperation;+ relativePath: string;+ newName?: string;+ newParentPath?: string;+ uploadIndex?: number;+ recursive?: boolean;+}++export interface WorkspaceFileDraft {+ relativePath: string;+ isDirectory?: boolean;+ content?: string;+}diff --git a/frontend/src/lib/utils/workspace-files.ts b/frontend/src/lib/utils/workspace-files.tsnew file mode 100644index 000000000..728aaf571--- /dev/null+++ b/frontend/src/lib/utils/workspace-files.ts@@ -0,0 +1,302 @@+import type { CodeLanguage } from '#lib/components/code-editor/analysis/types';+import { m } from '#lib/paraglide/messages';+import { toast } from 'svelte-sonner';+import type {+ WorkspaceFileChange as WorkspaceFileChangeDto,+ WorkspaceFileChangeOperation,+ WorkspaceFileEntry as WorkspaceFileDto,+ WorkspaceReadOnlyReason+} from '#lib/types/workspace';++export interface WorkspaceFileEntry extends Omit<WorkspaceFileDto, 'editable' | 'isSymlink' | 'readOnlyReason'> {+ editable?: boolean;+ isSymlink?: boolean;+ readOnlyReason?: WorkspaceReadOnlyReason | 'restore_pending';+ content?: string;+ mimeType?: string;+ protected?: boolean;+ locked?: boolean;+ pending?: boolean;+}++type WorkspaceDisplayFileChange = Omit<WorkspaceFileChangeDto, 'operation'> & {+ operation: WorkspaceFileChangeOperation | 'restore_file';+};++export function buildWorkspaceMultipartUpdate<T extends WorkspaceDisplayFileChange>(+ draftChanges: T[],+ fileContents: Record<string, string>,+ loadedFileContents: Record<string, string>+): { fileChanges: T[]; files: File[] } {+ const fileChanges = draftChanges.map(({ uploadIndex: _uploadIndex, ...change }) => ({ ...change }) as T);+ const files: File[] = [];+ const changedPaths = Object.keys(fileContents).filter(+ (relativePath) => fileContents[relativePath] !== loadedFileContents[relativePath]+ );++ const stageText = (change: T, content: string) => {+ change.uploadIndex = files.length;+ files.push(new File([content], workspaceFileBasename(change.relativePath), { type: 'text/plain' }));+ };++ for (const change of fileChanges) {+ if (change.operation === 'create_file') stageText(change, fileContents[change.relativePath] ?? '');+ }++ for (const relativePath of changedPaths) {+ if (+ fileChanges.some((change) => change.operation === 'delete' && workspaceFilePathMatches(relativePath, change.relativePath))+ ) {+ continue;+ }+ let change = fileChanges.findLast(+ (candidate) =>+ (candidate.operation === 'create_file' || candidate.operation === 'update_file') &&+ candidate.relativePath === relativePath+ );+ if (!change) {+ change = { operation: 'update_file', relativePath } as T;+ fileChanges.push(change);+ }+ if (change.uploadIndex === undefined) stageText(change, fileContents[relativePath] ?? '');+ }++ return { fileChanges, files };+}++export function normalizeWorkspaceRelativePath(relativePath: string): string {+ return relativePath.trim().replaceAll('\\', '/').split('/').filter(Boolean).join('/');+}++export function workspaceFileBasename(relativePath: string): string {+ const normalized = normalizeWorkspaceRelativePath(relativePath);+ const index = normalized.lastIndexOf('/');+ return index >= 0 ? normalized.slice(index + 1) : normalized;+}++export function workspaceFileParentPath(relativePath: string): string {+ const normalized = normalizeWorkspaceRelativePath(relativePath);+ const index = normalized.lastIndexOf('/');+ return index >= 0 ? normalized.slice(0, index) : '';+}++export function joinWorkspaceFilePath(parentPath: string, name: string): string {+ const parent = normalizeWorkspaceRelativePath(parentPath);+ return parent ? `${parent}/${name}` : name;+}++export function validateWorkspaceFileName(name: string): string | null {+ const trimmed = name.trim();+ if (!trimmed || trimmed === '.' || trimmed === '..') return null;+ if (trimmed.includes('/') || trimmed.includes('\\') || trimmed.includes('\0')) return null;+ return trimmed;+}++export function planWorkspaceFileCreate(existingPaths: ReadonlySet<string>, parentPath: string, name: string): string | null {+ const normalizedName = validateWorkspaceFileName(name);+ if (!normalizedName) {+ toast.error(m.workspace_file_invalid_name());+ return null;+ }+ const relativePath = joinWorkspaceFilePath(parentPath, normalizedName);+ if (existingPaths.has(relativePath)) {+ toast.error(m.workspace_file_duplicate_name());+ return null;+ }+ return relativePath;+}++export function planWorkspaceFileRename(+ existingPaths: ReadonlySet<string>,+ relativePath: string,+ newName: string+): { newName: string; newPath: string } | null {+ const normalizedName = validateWorkspaceFileName(newName);+ if (!normalizedName) {+ toast.error(m.workspace_file_invalid_name());+ return null;+ }+ const newPath = joinWorkspaceFilePath(workspaceFileParentPath(relativePath), normalizedName);+ if (newPath !== relativePath && existingPaths.has(newPath)) {+ toast.error(m.workspace_file_duplicate_name());+ return null;+ }+ return { newName: normalizedName, newPath };+}++export function planWorkspaceFileMove(+ entry: Pick<WorkspaceFileEntry, 'isDirectory'> | undefined,+ existingPaths: ReadonlySet<string>,+ relativePath: string,+ newParentPath: string+): string | null {+ if (!entry || newParentPath === workspaceFileParentPath(relativePath)) return null;+ if (entry.isDirectory && newParentPath && workspaceFilePathMatches(newParentPath, relativePath)) {+ toast.error(m.workspace_file_invalid_move_destination());+ return null;+ }+ const newPath = joinWorkspaceFilePath(newParentPath, workspaceFileBasename(relativePath));+ if (newPath !== relativePath && existingPaths.has(newPath)) {+ toast.error(m.workspace_file_duplicate_name());+ return null;+ }+ return newPath;+}++export async function readWorkspaceTextUpload(file: File, maxFileSizeMb: number): Promise<{ content?: string; error?: string }> {+ if (file.size > maxFileSizeMb * 1024 * 1024) return { error: m.workspace_upload_too_large({ maxFileSizeMb }) };+ try {+ const bytes = new Uint8Array(await file.arrayBuffer());+ if (bytes.includes(0)) return { error: m.workspace_upload_text_required() };+ return { content: new TextDecoder('utf-8', { fatal: true }).decode(bytes) };+ } catch {+ return { error: m.workspace_upload_text_required() };+ }+}++export function workspaceReadOnlyMessage(reason: WorkspaceReadOnlyReason | undefined, maxFileSizeMb: number): string {+ if (reason === 'binary') return m.workspace_binary_readonly();+ if (reason === 'too_large') return m.workspace_large_readonly({ maxFileSizeMb });+ if (reason === 'symlink') return m.workspace_symlink_readonly();+ if (reason === 'special') return m.workspace_special_readonly();+ return m.workspace_readonly();+}++export function workspaceFilePathMatches(relativePath: string, rootPath: string): boolean {+ return relativePath === rootPath || relativePath.startsWith(`${rootPath}/`);+}++export function remapWorkspaceFilePath(filePath: string, oldPath: string, newPath: string): string {+ return workspaceFilePathMatches(filePath, oldPath) ? `${newPath}${filePath.slice(oldPath.length)}` : filePath;+}++export function remapSelectedWorkspaceFileKey(selectedKey: string, oldPath: string, newPath: string): string | null {+ if (!selectedKey.startsWith('file:')) return null;+ const selectedPath = selectedKey.slice(5);+ if (!workspaceFilePathMatches(selectedPath, oldPath)) return null;+ return `file:${newPath}${selectedPath.slice(oldPath.length)}`;+}++export function isWorkspaceFileSelectionUnder(selectedKey: string, rootPath: string): boolean {+ return selectedKey.startsWith('file:') && workspaceFilePathMatches(selectedKey.slice(5), rootPath);+}++export function remapWorkspaceFileRecord<T>(record: Record<string, T>, oldPath: string, newPath: string): Record<string, T> {+ return Object.fromEntries(+ Object.entries(record).map(([relativePath, value]) => [remapWorkspaceFilePath(relativePath, oldPath, newPath), value])+ );+}++export function removeWorkspaceFileRecord<T>(record: Record<string, T>, rootPath: string): Record<string, T> {+ return Object.fromEntries(Object.entries(record).filter(([relativePath]) => !workspaceFilePathMatches(relativePath, rootPath)));+}++export function workspaceFileLanguage(relativePath: string): CodeLanguage {+ const lower = relativePath.toLowerCase();+ const basename = workspaceFileBasename(lower);+ if (lower.endsWith('.env') || basename.startsWith('.env')) return 'env';+ if (lower.endsWith('.yaml') || lower.endsWith('.yml')) return 'yaml';+ if (lower.endsWith('.json')) return 'json';+ if (lower.endsWith('.toml')) return 'toml';+ if (basename === 'dockerfile' || basename.startsWith('dockerfile.') || lower.endsWith('.dockerfile')) return 'dockerfile';+ if (lower.endsWith('.sh') || lower.endsWith('.bash') || lower.endsWith('.zsh') || lower.endsWith('.fish')) return 'shell';+ if (lower.endsWith('.ts') || lower.endsWith('.tsx') || lower.endsWith('.mts') || lower.endsWith('.cts')) return 'typescript';+ if (lower.endsWith('.js') || lower.endsWith('.jsx') || lower.endsWith('.mjs') || lower.endsWith('.cjs')) return 'javascript';+ if (lower.endsWith('.md') || lower.endsWith('.markdown') || lower.endsWith('.mdx')) return 'markdown';+ return 'plaintext';+}++export function compareWorkspaceFileEntries(a: WorkspaceFileEntry, b: WorkspaceFileEntry): number {+ if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;+ const baseComparison = a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });+ return baseComparison || a.name.localeCompare(b.name);+}++export function applyWorkspaceFileChangesForDisplay(+ files: WorkspaceFileEntry[],+ changes: WorkspaceDisplayFileChange[]+): WorkspaceFileEntry[] {+ const entries = new Map<string, WorkspaceFileEntry>();++ for (const file of files) {+ const modeType = file.mode?.[0];+ const isDirectory = modeType ? modeType === 'd' : file.isDirectory;+ const isSymlink = modeType ? modeType === 'l' : file.isSymlink;+ entries.set(file.relativePath, {+ ...file,+ name: file.name || workspaceFileBasename(file.relativePath),+ isDirectory,+ isSymlink+ });+ }++ for (const change of changes) {+ const relativePath = normalizeWorkspaceRelativePath(change.relativePath);+ switch (change.operation) {+ case 'create_file':+ entries.set(relativePath, {+ path: relativePath,+ relativePath,+ name: workspaceFileBasename(relativePath),+ isDirectory: false,+ size: 0,+ pending: true+ });+ break;+ case 'create_folder':+ entries.set(relativePath, {+ path: relativePath,+ relativePath,+ name: workspaceFileBasename(relativePath),+ isDirectory: true,+ size: 0,+ pending: true+ });+ break;+ case 'update_file': {+ const entry = entries.get(relativePath);+ if (entry) entries.set(relativePath, { ...entry, pending: true });+ break;+ }+ case 'rename':+ case 'move': {+ const entry = entries.get(relativePath);+ if (!entry) break;+ const newPath =+ change.operation === 'rename' && change.newName+ ? joinWorkspaceFilePath(workspaceFileParentPath(relativePath), change.newName)+ : joinWorkspaceFilePath(change.newParentPath ?? '', workspaceFileBasename(relativePath));+ const remapped = new Map<string, WorkspaceFileEntry>();+ for (const [entryPath, current] of entries.entries()) {+ if (!workspaceFilePathMatches(entryPath, relativePath)) {+ remapped.set(entryPath, current);+ continue;+ }+ const movedPath = `${newPath}${entryPath.slice(relativePath.length)}`;+ remapped.set(movedPath, {+ ...current,+ path: movedPath,+ relativePath: movedPath,+ name: workspaceFileBasename(movedPath),+ pending: true+ });+ }+ entries.clear();+ for (const [entryPath, current] of remapped.entries()) entries.set(entryPath, current);+ break;+ }+ case 'delete':+ for (const entryPath of [...entries.keys()]) {+ if (workspaceFilePathMatches(entryPath, relativePath)) entries.delete(entryPath);+ }+ break;+ case 'restore_file': {+ const entry = entries.get(relativePath);+ if (entry) entries.set(relativePath, { ...entry, pending: true });+ break;+ }+ }+ }++ return [...entries.values()].sort((a, b) => a.relativePath.localeCompare(b.relativePath));+}diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelteindex 3f44e9137..a6d30bcfc 100644--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte@@ -42,7 +42,7 @@} from '#lib/icons';import { parse as parseYaml } from 'yaml';import type { IncludeFile } from '#lib/types/swarm';- import { projectService } from '#lib/services/project-service';+ import { projectWorkspaceService } from '#lib/services/project-workspace-service';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';@@ -226,8 +226,8 @@// Returns { includeFile: null } for root compose, { includeFile: <file> } for a sub-file,// or null if the service isn't found anywhere (hides the tab).//- // Include file content is lazy-loaded (PR #2259), so we fetch on-demand via- // getProjectFileForEnvironment, stopping as soon as the service is found.+ // Include file content is lazy-loaded, so fetch it from Project Workspace on+ // demand and stop as soon as the service is found.const hasServiceInContent = (content: string, serviceName: string): boolean => {try {const parsed = parseYaml(content) as Record<string, unknown> | null;@@ -261,7 +261,7 @@return { includeFile: f };}try {- const loaded = await projectService.getProjectFileForEnvironment(envId, proj.id, f.relativePath);+ const loaded = await projectWorkspaceService.getWorkspaceFile(proj.id, f.relativePath, envId);if (loaded?.content && hasServiceInContent(loaded.content, svcName)) {return { includeFile: { ...f, content: loaded.content } };}diff --git a/frontend/src/routes/(app)/containers/components/ContainerComposePanel.svelte b/frontend/src/routes/(app)/containers/components/ContainerComposePanel.svelteindex ac2d94dad..d8fff683d 100644--- a/frontend/src/routes/(app)/containers/components/ContainerComposePanel.svelte+++ b/frontend/src/routes/(app)/containers/components/ContainerComposePanel.svelte@@ -1,7 +1,8 @@<script lang="ts">import { ComposeEditorWrapper } from '#lib/components/compose';- import CodePanel from '../../projects/components/CodePanel.svelte';+ import CodePanel from '#lib/components/code-panel.svelte';import { projectService } from '#lib/services/project-service';+ import { projectWorkspaceService } from '#lib/services/project-workspace-service';import type { Project, IncludeFile } from '#lib/types/swarm';let {@@ -29,7 +30,15 @@async function save() {if (includeFile) {- await projectService.updateProjectIncludeFile(project.id, includeFile.relativePath, composeContent);+ const workspace = await projectWorkspaceService.getWorkspace(project.id);+ await projectWorkspaceService.updateWorkspace(+ project.id,+ {+ fileTreeRevision: workspace.fileTreeRevision,+ fileChanges: [{ operation: 'update_file', relativePath: includeFile.relativePath, uploadIndex: 0 }]+ },+ [new File([composeContent], includeFile.relativePath, { type: 'text/yaml' })]+ );} else {await projectService.updateProject(project.id, undefined, composeContent);}diff --git a/frontend/src/routes/(app)/customize/templates/components/template-editor-workspace.svelte b/frontend/src/routes/(app)/customize/templates/components/template-editor-workspace.svelteindex c6744ae5b..cd0cebb5d 100644--- a/frontend/src/routes/(app)/customize/templates/components/template-editor-workspace.svelte+++ b/frontend/src/routes/(app)/customize/templates/components/template-editor-workspace.svelte@@ -1,7 +1,7 @@<script lang="ts">import { ArcaneButton } from '#lib/components/arcane-button/index.js';import FormInput from '#lib/components/form/form-input.svelte';- import CodePanel from '../../../projects/components/CodePanel.svelte';+ import CodePanel from '#lib/components/code-panel.svelte';import EditableName from '../../../projects/components/EditableName.svelte';import { ComposeEditorSplit } from '#lib/components/compose';import { goto } from '$app/navigation';diff --git a/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte b/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelteindex cda2f2120..5ef64b05f 100644--- a/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte+++ b/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte@@ -224,7 +224,7 @@</DropdownMenu.Item><DropdownMenu.Item onclick={() => (showUpload = true)}><UploadIcon class="size-4" />- {m.volumes_browser_upload_files()}+ {m.workspace_upload_files()}</DropdownMenu.Item>{/if}</DropdownMenu.Content>diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte b/frontend/src/routes/(app)/projects/[projectId]/+page.svelteindex db18d09f7..38b30263b 100644--- a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte@@ -1,6 +1,6 @@<script lang="ts">import type { IncludeFile, Project } from '#lib/types/swarm';- import type { ProjectFileChange } from '#lib/types/project-files';+ import type { ProjectWorkspaceFileChange, ProjectWorkspaceFileContent } from '#lib/types/project-workspace';import * as Tabs from '#lib/components/ui/tabs/index.js';import * as Alert from '#lib/components/ui/alert/index.js';import { ArcaneButton } from '#lib/components/arcane-button/index.js';@@ -41,15 +41,17 @@import { useUrlTab } from '#lib/hooks/use-url-tab.svelte';import ComposeFileEditorPanel from '#lib/components/compose-file-editor-panel.svelte';import EditableName from '../components/EditableName.svelte';- import ProjectFileTreePanel from '../components/ProjectFileTreePanel.svelte';- import EditorTabStrip from '../components/EditorTabStrip.svelte';+ import WorkspaceFileTreePanel from '#lib/components/workspace-file-tree-panel.svelte';+ import EditorTabStrip from '#lib/components/editor-tab-strip.svelte';import ProjectServicesPanel from '../components/ProjectServicesPanel.svelte';- import CodePanel from '../components/CodePanel.svelte';+ import CodePanel from '#lib/components/code-panel.svelte';import ProjectsLogsPanel from '../components/ProjectLogsPanel.svelte';import ResizableSplit from '#lib/components/resizable-split.svelte';import { Switch } from '#lib/components/ui/switch';import { untrack } from 'svelte';import { projectService } from '#lib/services/project-service';+ import { projectWorkspaceService } from '#lib/services/project-workspace-service';+ import settingsStore from '#lib/stores/config-store';import { imageService } from '#lib/services/image-service';import { gitOpsSyncService } from '#lib/services/gitops-sync-service';import { environmentStore } from '#lib/stores/environment.store.svelte';@@ -63,18 +65,24 @@import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast';import { globalVariablesToMap } from '#lib/utils/template-load';import {- applyProjectFileChangesForDisplay,- isProjectFileSelectionUnder,- planProjectFileCreate,- planProjectFileMove,- planProjectFileRename,- projectFileBasename,- projectFileLanguage,- projectFilePathMatches,- remapProjectFileRecord,- remapSelectedProjectFileKey,- removeProjectFileRecord- } from '../components/project-file-tree-utils';+ planProjectWorkspaceFileCreate,+ planProjectWorkspaceFileMove,+ planProjectWorkspaceFileRename,+ validateProjectWorkspaceFileName+ } from '../components/project-workspace-utils';+ import {+ applyWorkspaceFileChangesForDisplay,+ buildWorkspaceMultipartUpdate,+ isWorkspaceFileSelectionUnder,+ workspaceFileBasename,+ workspaceFileLanguage,+ remapWorkspaceFileRecord,+ remapSelectedWorkspaceFileKey,+ removeWorkspaceFileRecord,+ readWorkspaceTextUpload,+ workspaceReadOnlyMessage,+ type WorkspaceFileEntry+ } from '#lib/utils/workspace-files';import { composeTreeSplitProps, extractComposeYamlName } from '#lib/utils/compose-flow';let { data } = $props();@@ -104,13 +112,15 @@let includeFilesState = $state<Record<string, string>>({});let loadedIncludeFileContents = $state<Record<string, string>>({});let loadedDirectoryFileContents = $state<Record<string, string>>({});- let managedProjectFileChanges = $state<ProjectFileChange[]>([]);- let managedProjectFileContents = $state<Record<string, string>>({});- let loadedManagedProjectFileContents = $state<Record<string, string>>({});- let managedProjectFileLoadErrors = $state<Record<string, string>>({});- let managedProjectFileLoading = $state<Record<string, boolean>>({});- let projectFilePromises: Record<string, Promise<IncludeFile> | undefined> = {};+ let projectWorkspaceChanges = $state<ProjectWorkspaceFileChange[]>([]);+ let projectWorkspaceContents = $state<Record<string, string>>({});+ let loadedProjectWorkspaceContents = $state<Record<string, string>>({});+ let projectWorkspaceLoadErrors = $state<Record<string, string>>({});+ let projectWorkspaceLoading = $state<Record<string, boolean>>({});+ let projectWorkspaceFileMetadata = $state<Record<string, ProjectWorkspaceFileContent>>({});+ let projectWorkspaceFilePromises: Record<string, Promise<IncludeFile | ProjectWorkspaceFileContent> | undefined> = {};const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));+ const projectWorkspaceMaxFileSizeMb = $derived($settingsStore?.projectWorkspaceMaxFileSizeMb ?? 10);const projectDetailQuery = createQuery(() => ({queryKey: queryKeys.projects.detail(envId, projectId),@@ -119,11 +129,11 @@refetchOnMount: false}));- // The file tree walk can be slow on large projects, so it loads lazily and+ // The workspace walk can be slow on large projects, so it loads lazily and// never blocks navigation; +page.ts prefetches this key without awaiting.- const projectFilesQuery = createQuery(() => ({- queryKey: queryKeys.projects.files(envId, projectId),- queryFn: () => projectService.getProjectFiles(envId, projectId)+ const projectWorkspaceQuery = createQuery(() => ({+ queryKey: queryKeys.projects.workspace(envId, projectId),+ queryFn: () => projectWorkspaceService.getWorkspace(projectId, envId)}));const lifecycleSyncQuery = createQuery(() => {@@ -168,7 +178,7 @@const { inputs, ...form } = createForm<typeof formSchema>(formSchema, initialFormData);- function withLoadedProjectFileContent(details: Project | null | undefined): Project | null {+ function withLoadedProjectIncludeContent(details: Project | null | undefined): Project | null {if (!details) return null;return {@@ -176,14 +186,6 @@includeFiles: (details.includeFiles ?? []).map((file) => ({...file,content: file.content ?? loadedIncludeFileContents[file.relativePath]- })),- directoryFiles: (details.directoryFiles ?? []).map((file) => ({- ...file,- content: file.content ?? loadedDirectoryFileContents[file.relativePath]- })),- projectFiles: (details.projectFiles ?? []).map((file) => ({- ...file,- content: file.content ?? loadedManagedProjectFileContents[file.relativePath]}))};}@@ -191,7 +193,7 @@const project = $derived.by(() => {const detail = projectDetailQuery.data ?? data.project;if (!detail) return null;- return withLoadedProjectFileContent({ ...detail, ...(projectFilesQuery.data ?? {}) });+ return withLoadedProjectIncludeContent(detail);});const projectImageRefs = $derived.by(() => getProjectImageRefs(project));const serverName = $derived(project?.name ?? '');@@ -205,13 +207,22 @@)));- const managedProjectFiles = $derived.by(() =>- applyProjectFileChangesForDisplay(project?.projectFiles ?? [], managedProjectFileChanges)+ const projectWorkspaceEntries = $derived.by(() =>+ applyWorkspaceFileChangesForDisplay(projectWorkspaceQuery.data?.files ?? [], projectWorkspaceChanges).map((file) => {+ const metadata = projectWorkspaceFileMetadata[file.relativePath];+ const editable = metadata?.editable ?? file.editable;+ return {+ ...file,+ editable,+ readOnlyReason: metadata?.readOnlyReason ?? file.readOnlyReason,+ locked: !file.isDirectory && editable === false+ };+ }));- const managedProjectFilePaths = $derived.by(() => new Set(managedProjectFiles.map((file) => file.relativePath)));- const changedManagedProjectFilePaths = $derived.by(() =>- Object.keys(managedProjectFileContents).filter(- (relativePath) => managedProjectFileContents[relativePath] !== loadedManagedProjectFileContents[relativePath]+ const projectWorkspacePaths = $derived.by(() => new Set(projectWorkspaceEntries.map((file) => file.relativePath)));+ const changedProjectWorkspacePaths = $derived.by(() =>+ Object.keys(projectWorkspaceContents).filter(+ (relativePath) => projectWorkspaceContents[relativePath] !== loadedProjectWorkspaceContents[relativePath]));@@ -226,8 +237,8 @@$inputs.overrideContent.value !== serverOverrideContent ||$inputs.envContent.value !== serverEnvContent ||Object.entries(includeFilesState).some(([relativePath, content]) => content !== serverIncludeFiles[relativePath]) ||- managedProjectFileChanges.length > 0 ||- changedManagedProjectFilePaths.length > 0+ projectWorkspaceChanges.length > 0 ||+ changedProjectWorkspacePaths.length > 0);let isGitOpsManaged = $derived(!!project?.gitOpsManagedBy);@@ -246,7 +257,7 @@// Override edits are blocked for GitOps-managed projects, mirroring canEditCompose.let canEditOverride = $derived(canUpdateProject && !project?.isArchived && !isGitOpsManaged);let canEditEnv = $derived(canUpdateProject && !project?.isArchived);- let canEditProjectFiles = $derived(canUpdateProject && !project?.isArchived && !isGitOpsManaged);+ let canEditProjectWorkspace = $derived(canUpdateProject && !project?.isArchived && !isGitOpsManaged);let composeFileName = $derived(project?.composeFileName || 'compose.yaml');// Set when the user opts to add an override to a project that has none yet.let overrideEditorRequested = $state(false);@@ -257,6 +268,22 @@// The override editor surfaces only when an override exists or the user asked// to add one this session; otherwise the UI shows an "add override" affordance.let overrideActive = $derived(overrideExists || overrideEditorRequested);+ const projectWorkspaceLeadingRows = $derived([+ { key: 'compose', label: composeFileName, iconClass: 'text-blue-500', locked: true },+ ...(overrideActive+ ? [{ key: 'override', label: overrideFileName, iconClass: 'text-purple-500', locked: true }]+ : canEditOverride+ ? [+ {+ key: 'add-override',+ label: m.compose_override_add(),+ action: true,+ onSelect: handleAddOverride+ }+ ]+ : []),+ { key: 'env', label: '.env', iconClass: 'text-green-500', locked: true }+ ]);let archiveRequiresStopped = $derived(!!project &&!project.isArchived &&@@ -297,33 +324,36 @@let overrideHasErrors = $state(false);let envHasErrors = $state(false);let includeFilesHasErrors = $state<Record<string, boolean>>({});- let managedProjectFileHasErrors = $state<Record<string, boolean>>({});+ let projectWorkspaceHasErrors = $state<Record<string, boolean>>({});let composeValidationReady = $state(false);let overrideValidationReady = $state(false);let envValidationReady = $state(false);let includeFilesValidationReady = $state<Record<string, boolean>>({});- let managedProjectFileValidationReady = $state<Record<string, boolean>>({});+ let projectWorkspaceValidationReady = $state<Record<string, boolean>>({});const includeFilePaths = $derived.by(() => new Set((project?.includeFiles ?? []).map((file) => file.relativePath)));- const directoryFilePaths = $derived.by(() => new Set((project?.directoryFiles ?? []).map((file) => file.relativePath)));+ const directoryFilePaths = $derived.by(() => new Set(projectWorkspaceEntries.map((file) => file.relativePath)));const selectedFile = $derived.by(() => {const current = selectedFilePreference;if (current === 'override') return overrideActive ? 'override' : 'compose';if (current === 'compose' || current === 'env') return current;if (current.startsWith('file:')) {const relativePath = current.slice(5);- return managedProjectFilePaths.has(relativePath) ? current : 'compose';+ return projectWorkspacePaths.has(relativePath) ? current : 'compose';}if (current.startsWith('dir:')) {return directoryFilePaths.has(current.slice(4)) ? current : 'compose';}return includeFilePaths.has(current) ? current : 'compose';});- const selectedManagedProjectFilePath = $derived(selectedFile.startsWith('file:') ? selectedFile.slice(5) : '');- const selectedManagedProjectFile = $derived.by(() =>- selectedManagedProjectFilePath- ? managedProjectFiles.find((file) => file.relativePath === selectedManagedProjectFilePath)+ const selectedProjectWorkspacePath = $derived(selectedFile.startsWith('file:') ? selectedFile.slice(5) : '');+ const selectedProjectWorkspaceEntry = $derived.by(() =>+ selectedProjectWorkspacePath+ ? projectWorkspaceEntries.find((file) => file.relativePath === selectedProjectWorkspacePath): undefined);+ const selectedProjectWorkspaceMetadata = $derived(+ selectedProjectWorkspacePath ? projectWorkspaceFileMetadata[selectedProjectWorkspacePath] : undefined+ );const openTabs = $derived.by(() => {const valid = openTabsPreference.filter((key) => {if (key === 'compose' || key === 'env') return true;@@ -331,8 +361,8 @@// via a blank save) and no add is in progress.if (key === 'override') return overrideActive;if (!key.startsWith('file:')) return false;- // fallow-ignore-next-line code-duplication -- managed-file predicate; script-level, diverges per page- const entry = managedProjectFiles.find((file) => file.relativePath === key.slice(5));+ // fallow-ignore-next-line code-duplication -- workspace-entry predicate; script-level, diverges per page+ const entry = projectWorkspaceEntries.find((file) => file.relativePath === key.slice(5));return !!entry && !entry.isDirectory;});return valid.length > 0 ? valid : ['compose'];@@ -411,7 +441,7 @@type RebaseEditorDraftOptions = {preserveEditableDrafts?: boolean;- preserveManagedProjectFileContents?: boolean;+ preserveProjectWorkspaceContents?: boolean;clearLoadedFileCache?: boolean;};@@ -459,16 +489,16 @@}}- function ensureManagedProjectFileUiState(relativePath: string) {- if (managedProjectFileHasErrors[relativePath] === undefined) {- managedProjectFileHasErrors = {- ...managedProjectFileHasErrors,+ function ensureProjectWorkspaceUiState(relativePath: string) {+ if (projectWorkspaceHasErrors[relativePath] === undefined) {+ projectWorkspaceHasErrors = {+ ...projectWorkspaceHasErrors,[relativePath]: false};}- if (managedProjectFileValidationReady[relativePath] === undefined) {- managedProjectFileValidationReady = {- ...managedProjectFileValidationReady,+ if (projectWorkspaceValidationReady[relativePath] === undefined) {+ projectWorkspaceValidationReady = {+ ...projectWorkspaceValidationReady,[relativePath]: true};}@@ -510,14 +540,15 @@);}- function clearLoadedProjectFileCache() {+ function clearLoadedProjectWorkspaceCache() {loadedIncludeFileContents = {};loadedDirectoryFileContents = {};- loadedManagedProjectFileContents = {};- managedProjectFileContents = {};- managedProjectFileLoadErrors = {};- managedProjectFileLoading = {};- projectFilePromises = {};+ loadedProjectWorkspaceContents = {};+ projectWorkspaceContents = {};+ projectWorkspaceLoadErrors = {};+ projectWorkspaceLoading = {};+ projectWorkspaceFileMetadata = {};+ projectWorkspaceFilePromises = {};}function rebaseEditorDraft(details: Project, options: RebaseEditorDraftOptions = {}) {@@ -526,46 +557,32 @@const dirtyIncludeDrafts = options.preserveEditableDrafts === true ? getDirtyIncludeDrafts() : {};if (options.clearLoadedFileCache === true) {- clearLoadedProjectFileCache();+ clearLoadedProjectWorkspaceCache();}- const normalizedProject = withLoadedProjectFileContent(details);+ const normalizedProject = withLoadedProjectIncludeContent(details);if (!normalizedProject) return;- // A slim save response (no file changes) carries no projectFiles; the tree is- // unchanged server-side, so keep the current contents instead of deriving- // them from an empty tree.- const savedManagedProjectFileContents =- options.preserveManagedProjectFileContents === true- ? details.projectFiles === undefined- ? { ...managedProjectFileContents }- : Object.fromEntries(- (normalizedProject.projectFiles ?? []).flatMap((file) => {- if (file.isDirectory) return [];- const content =- loadedManagedProjectFileContents[file.relativePath] ?? managedProjectFileContents[file.relativePath];- return content === undefined ? [] : [[file.relativePath, content] as const];- })- )- : {};+ const savedProjectWorkspaceContents =+ options.preserveProjectWorkspaceContents === true ? { ...projectWorkspaceContents } : {};$inputs.name.value = normalizedProject.name || '';$inputs.composeContent.value = normalizedProject.composeContent || '';$inputs.overrideContent.value = normalizedProject.overrideContent || '';$inputs.envContent.value = shouldPreserveEnvDraft ? envDraft : normalizedProject.envContent || '';- managedProjectFileChanges = [];- managedProjectFileContents = savedManagedProjectFileContents;+ projectWorkspaceChanges = [];+ projectWorkspaceContents = savedProjectWorkspaceContents;// Seed the per-file UI-state records for every retained path. A mounted// CodePanel binds these entries; handing a bound $bindable-with-fallback// prop an undefined entry throws props_invalid_value and kills the page's// effect tree (stale editor shown until a full refresh).- managedProjectFileHasErrors = Object.fromEntries(- Object.keys(savedManagedProjectFileContents).map((relativePath) => [relativePath, false])+ projectWorkspaceHasErrors = Object.fromEntries(+ Object.keys(savedProjectWorkspaceContents).map((relativePath) => [relativePath, false]));- managedProjectFileValidationReady = Object.fromEntries(- Object.keys(savedManagedProjectFileContents).map((relativePath) => [relativePath, true])+ projectWorkspaceValidationReady = Object.fromEntries(+ Object.keys(savedProjectWorkspaceContents).map((relativePath) => [relativePath, true]));- managedProjectFileLoadErrors = {};- managedProjectFileLoading = {};+ projectWorkspaceLoadErrors = {};+ projectWorkspaceLoading = {};const freshIncludeFiles = getProjectIncludeFileContents(normalizedProject);includeFilesState = {@@ -587,22 +604,6 @@queryKeys.projects.detail(currentEnvId, updatedProject.id),(old: Project | undefined) => ({ ...(old ?? {}), ...updatedProject }) as Project);- if (updatedProject.projectFiles || updatedProject.fileTreeRevision) {- // A file-changes save returns a fresh tree + revision; sync it into the- // files cache so the next file save doesn't hit a revision conflict.- queryClient.setQueryData(- queryKeys.projects.files(currentEnvId, updatedProject.id),- (old: Project | undefined) =>- ({- ...(old ?? {}),- projectFiles: updatedProject.projectFiles,- fileTreeRevision: updatedProject.fileTreeRevision,- fileTreeTruncated: updatedProject.fileTreeTruncated- }) as Project- );- } else {- await queryClient.invalidateQueries({ queryKey: queryKeys.projects.files(currentEnvId, updatedProject.id) });- }await Promise.all([queryClient.invalidateQueries({ queryKey: ['projects', currentEnvId] }),queryClient.invalidateQueries({ queryKey: queryKeys.projects.statusCounts(currentEnvId) })@@ -646,9 +647,9 @@const prefsStorageKey = `arcane.compose.ui:${project.id}`;const hadStoredPrefs = sessionStorage.getItem(prefsStorageKey) !== null;- // The tree/classic auto-detect needs the lazily loaded file tree; without- // stored prefs, wait for the files query to settle before finalizing.- if (!hadStoredPrefs && !(projectFilesQuery.isSuccess || projectFilesQuery.isError)) return;+ // The tree/classic auto-detect needs the lazily loaded workspace; without+ // stored prefs, wait for its query to settle before finalizing.+ if (!hadStoredPrefs && !(projectWorkspaceQuery.isSuccess || projectWorkspaceQuery.isError)) return;lastPrefsProjectId = project.id;prefs = new PersistedState<ComposeUIPrefs>(prefsStorageKey, defaultComposeUIPrefs, {@@ -676,13 +677,12 @@selectedFilePreference = cur.selectedFile ?? defaultComposeUIPrefs.selectedFile ?? 'compose';openTabsPreference = cur.openTabs && cur.openTabs.length > 0 ? cur.openTabs : [selectedFilePreference];- // Auto-detect layout mode based on includeFiles or directoryFiles. PersistedState- // always materializes the defaults, so only trust the stored layoutMode when this- // project actually had persisted prefs.+ // Auto-detect layout mode from includes and workspace entries. PersistedState+ // always materializes the defaults, so only trust the stored layoutMode when+ // this project actually had persisted prefs.const hasIncludes = project?.includeFiles && project.includeFiles.length > 0;- const hasDirectoryFiles = project?.directoryFiles && project.directoryFiles.length > 0;- const hasProjectFiles = project?.projectFiles && project.projectFiles.length > 0;- const defaultMode = hasIncludes || hasDirectoryFiles || hasProjectFiles ? 'tree' : 'classic';+ const hasWorkspaceEntries = projectWorkspaceEntries.length > 0;+ const defaultMode = hasIncludes || hasWorkspaceEntries ? 'tree' : 'classic';layoutMode = hadStoredPrefs ? (cur.layoutMode ?? defaultMode) : defaultMode;// PersistedState seeds storage with the defaults on first mount; persist the// resolved state so the auto-detected layout survives the next visit.@@ -691,50 +691,6 @@}});- function isDeletedByProjectFileChanges(relativePath: string, changes: ProjectFileChange[]): boolean {- return changes.some((change) => change.operation === 'delete' && projectFilePathMatches(relativePath, change.relativePath));- }-- function buildProjectFileSaveChanges(): ProjectFileChange[] {- const changes = managedProjectFileChanges.map((change) => ({ ...change }));- const contentChanges = new Map<string, string>();-- for (const relativePath of changedManagedProjectFilePaths) {- const content = managedProjectFileContents[relativePath];- if (content !== undefined) {- contentChanges.set(relativePath, content);- }- }-- const createFilePaths = new Set<string>();- for (const change of changes) {- if (change.operation === 'create_file') {- createFilePaths.add(change.relativePath);- change.content = contentChanges.get(change.relativePath) ?? change.content ?? '';- }- }-- for (const [relativePath, content] of contentChanges.entries()) {- if (createFilePaths.has(relativePath) || isDeletedByProjectFileChanges(relativePath, changes)) {- continue;- }- changes.push({- operation: 'update_file',- relativePath,- content- });- }-- return changes;- }-- function buildIncludeFileSaveUpdates(): Array<{ relativePath: string; content: string }> {- return changedIncludeFilePaths.flatMap((relativePath) => {- const content = includeFilesState[relativePath];- return content === undefined ? [] : [{ relativePath, content }];- });- }-async function handleSaveChanges() {if (!project || !hasChanges) return;if (project.isArchived) {@@ -757,59 +713,56 @@// Blank override => delete, which the backend treats as a no-op when none// exists, so we can always send it (except for read-only GitOps projects).const overridePayload = isGitOpsManaged ? undefined : overrideContent;- const fileChangesPayload = buildProjectFileSaveChanges();- const includeFileUpdates = buildIncludeFileSaveUpdates();- const fileTreeRevision = fileChangesPayload.length > 0 ? project.fileTreeRevision : undefined;-- handleApiResultWithCallbacks({- result: await tryCatch(- (async () => {- let updatedProject = await projectService.updateProject(- projectId,- namePayload,- composePayload,- envPayload,- overridePayload,- fileTreeRevision,- fileChangesPayload- );-- // The file-tree changes are committed server-side at this point. Rebase the- // local tree state and project query immediately — if an include-file update- // below fails, the already-applied changes must not stay queued with a stale- // fileTreeRevision, or every retry would be rejected with a 409 conflict.- loadedManagedProjectFileContents = {- ...loadedManagedProjectFileContents,- ...managedProjectFileContents- };- rebaseEditorDraft(updatedProject, { preserveManagedProjectFileContents: true, preserveEditableDrafts: true });- await syncProjectQueries(updatedProject);-- for (const update of includeFileUpdates) {- updatedProject = await projectService.updateProjectIncludeFile(projectId, update.relativePath, update.content);- }- return updatedProject;- })()- ),- message: m.common_save_failed(),- setLoadingState: (value) => (isLoading.saving = value),- onSuccess: async (updatedProject: Project) => {+ const workspaceUpdate = buildWorkspaceMultipartUpdate(+ projectWorkspaceChanges,+ { ...projectWorkspaceContents, ...includeFilesState },+ { ...loadedProjectWorkspaceContents, ...loadedIncludeFileContents }+ );+ let workspaceCommitted = false;+ isLoading.saving = true;+ try {+ if (workspaceUpdate.fileChanges.length > 0) {+ const workspace = await projectWorkspaceService.updateWorkspace(+ projectId,+ {+ fileTreeRevision: projectWorkspaceQuery.data?.fileTreeRevision ?? '',+ fileChanges: workspaceUpdate.fileChanges+ },+ workspaceUpdate.files,+ envId+ );+ workspaceCommitted = true;+ queryClient.setQueryData(queryKeys.projects.workspace(envId, projectId), workspace);++ loadedProjectWorkspaceContents = { ...loadedProjectWorkspaceContents, ...projectWorkspaceContents };loadedIncludeFileContents = {...loadedIncludeFileContents,...Object.fromEntries(- Object.entries(includeFilesState).filter(([relativePath]) =>- (updatedProject.includeFiles ?? []).some((file) => file.relativePath === relativePath)- )+ changedIncludeFilePaths.flatMap((relativePath) => {+ const content = includeFilesState[relativePath];+ return content === undefined ? [] : [[relativePath, content] as const];+ }))};- rebaseEditorDraft(updatedProject, { preserveManagedProjectFileContents: true });- await syncProjectQueries(updatedProject);- toast.success(- m.common_update_success({ resource: m.project() }),- activityToastOptions(extractActivityId(updatedProject))- );+ projectWorkspaceChanges = [];}- });++ const updatedProject = await projectService.updateProject(+ projectId,+ namePayload,+ composePayload,+ envPayload,+ overridePayload+ );+ rebaseEditorDraft(updatedProject, { preserveProjectWorkspaceContents: true });+ await syncProjectQueries(updatedProject);+ toast.success(m.common_update_success({ resource: m.project() }), activityToastOptions(extractActivityId(updatedProject)));+ } catch (error) {+ const message = error instanceof Error ? error.message : m.common_save_failed();+ toast.error(workspaceCommitted ? m.projects_workspace_saved_configuration_failed({ error: message }) : message);+ } finally {+ isLoading.saving = false;+ }}function saveNameIfChanged() {@@ -865,13 +818,13 @@};}- type ProjectFileKind = 'include' | 'directory' | 'managed';+ type ProjectWorkspaceSource = 'include' | 'directory' | 'workspace';- function getProjectFileKey(projectId: string, kind: ProjectFileKind, relativePath: string): string {+ function getProjectWorkspaceCacheKey(projectId: string, kind: ProjectWorkspaceSource, relativePath: string): string {return `${projectId}:${kind}:${relativePath}`;}- function updateLoadedProjectFile(kind: ProjectFileKind, relativePath: string, content: string) {+ function updateLoadedProjectWorkspaceSource(kind: ProjectWorkspaceSource, relativePath: string, content: string) {if (kind === 'include') {ensureIncludeFileUiState(relativePath);loadedIncludeFileContents = {@@ -893,36 +846,53 @@};}- function updateLoadedManagedProjectFile(relativePath: string, content: string) {- ensureManagedProjectFileUiState(relativePath);- loadedManagedProjectFileContents = {- ...loadedManagedProjectFileContents,+ function updateLoadedProjectWorkspaceFile(relativePath: string, content: string) {+ ensureProjectWorkspaceUiState(relativePath);+ loadedProjectWorkspaceContents = {+ ...loadedProjectWorkspaceContents,[relativePath]: content};- if (managedProjectFileContents[relativePath] === undefined) {- managedProjectFileContents = {- ...managedProjectFileContents,+ if (projectWorkspaceContents[relativePath] === undefined) {+ projectWorkspaceContents = {+ ...projectWorkspaceContents,[relativePath]: content};}- managedProjectFileLoadErrors = removeProjectFileRecord(managedProjectFileLoadErrors, relativePath);+ projectWorkspaceLoadErrors = removeWorkspaceFileRecord(projectWorkspaceLoadErrors, relativePath);}- function getProjectFileResource(kind: ProjectFileKind, relativePath: string): IncludeFile | Promise<IncludeFile> {+ function getProjectWorkspaceFileResource(+ kind: 'workspace',+ relativePath: string+ ): ProjectWorkspaceFileContent | Promise<ProjectWorkspaceFileContent>;+ function getProjectWorkspaceFileResource(+ kind: 'include' | 'directory',+ relativePath: string+ ): IncludeFile | Promise<IncludeFile>;+ function getProjectWorkspaceFileResource(+ kind: ProjectWorkspaceSource,+ relativePath: string+ ): IncludeFile | ProjectWorkspaceFileContent | Promise<IncludeFile | ProjectWorkspaceFileContent> {const currentProjectId = project?.id;if (!currentProjectId) {- throw new Error('Project is not loaded');+ throw new Error(m.projects_workspace_not_loaded());}if (kind === 'include') {ensureIncludeFileUiState(relativePath);- } else if (kind === 'managed') {- ensureManagedProjectFileUiState(relativePath);- if (managedProjectFileContents[relativePath] !== undefined) {- return {- path: relativePath,- relativePath,- content: managedProjectFileContents[relativePath]- };+ } else if (kind === 'workspace') {+ ensureProjectWorkspaceUiState(relativePath);+ if (projectWorkspaceContents[relativePath] !== undefined) {+ return (+ projectWorkspaceFileMetadata[relativePath] ?? {+ path: relativePath,+ relativePath,+ name: workspaceFileBasename(relativePath),+ size: projectWorkspaceContents[relativePath].length,+ mimeType: 'text/plain',+ content: projectWorkspaceContents[relativePath],+ editable: true+ }+ );}}@@ -930,60 +900,66 @@kind === 'include'? project?.includeFiles?.find((file) => file.relativePath === relativePath): kind === 'directory'- ? project?.directoryFiles?.find((file) => file.relativePath === relativePath)- : managedProjectFiles.find((file) => file.relativePath === relativePath);+ ? projectWorkspaceEntries.find((file) => file.relativePath === relativePath)+ : projectWorkspaceEntries.find((file) => file.relativePath === relativePath);if (!targetFile) {- throw new Error('Project file not found');+ throw new Error(m.workspace_file_not_found());}if (targetFile.content !== undefined) {- if (kind === 'managed') {- updateLoadedManagedProjectFile(relativePath, targetFile.content ?? '');+ if (kind === 'workspace') {+ const workspaceTarget = targetFile as WorkspaceFileEntry;+ updateLoadedProjectWorkspaceFile(relativePath, workspaceTarget.content ?? '');+ return {+ path: workspaceTarget.path,+ relativePath,+ name: workspaceTarget.name,+ size: workspaceTarget.size,+ mimeType: workspaceTarget.mimeType ?? 'text/plain',+ content: workspaceTarget.content ?? '',+ editable: workspaceTarget.editable !== false,+ readOnlyReason: workspaceTarget.readOnlyReason === 'restore_pending' ? undefined : workspaceTarget.readOnlyReason+ };} else {- updateLoadedProjectFile(kind, relativePath, targetFile.content ?? '');+ updateLoadedProjectWorkspaceSource(kind, relativePath, targetFile.content ?? '');}return targetFile;}- const requestKey = getProjectFileKey(currentProjectId, kind, relativePath);- const existingPromise = projectFilePromises[requestKey];+ const requestKey = getProjectWorkspaceCacheKey(currentProjectId, kind, relativePath);+ const existingPromise = projectWorkspaceFilePromises[requestKey];if (existingPromise) {return existingPromise;}const promise = (async () => {- const file = await projectService.getProjectFile(currentProjectId, relativePath);- if (kind === 'managed') {- updateLoadedManagedProjectFile(relativePath, file.content ?? '');- } else {- updateLoadedProjectFile(kind, relativePath, file.content ?? '');+ const file = await projectWorkspaceService.getWorkspaceFile(currentProjectId, relativePath, envId);+ if (kind !== 'workspace') {+ updateLoadedProjectWorkspaceSource(kind, relativePath, file.content ?? '');}- return {- ...file,- content: file.content ?? ''- };+ return file;})().finally(() => {- delete projectFilePromises[requestKey];+ delete projectWorkspaceFilePromises[requestKey];});- projectFilePromises[requestKey] = promise;+ projectWorkspaceFilePromises[requestKey] = promise;return promise;}- function isManagedDirectoryKey(key: string): boolean {+ function isWorkspaceDirectoryKey(key: string): boolean {if (!key.startsWith('file:')) return false;- return managedProjectFiles.find((file) => file.relativePath === key.slice(5))?.isDirectory === true;+ return projectWorkspaceEntries.find((file) => file.relativePath === key.slice(5))?.isDirectory === true;}function openFileTab(key: string) {// The file panel's bound UI-state entries must exist before mount; binding// an undefined entry to a $bindable-with-fallback prop throws props_invalid_value.- if (key.startsWith('file:') && !isManagedDirectoryKey(key)) {- ensureManagedProjectFileUiState(key.slice(5));+ if (key.startsWith('file:') && !isWorkspaceDirectoryKey(key)) {+ ensureProjectWorkspaceUiState(key.slice(5));}- if (!isManagedDirectoryKey(key) && !openTabsPreference.includes(key)) {+ if (!isWorkspaceDirectoryKey(key) && !openTabsPreference.includes(key)) {openTabsPreference = [...openTabsPreference, key];}selectedFilePreference = key;@@ -1012,7 +988,7 @@if (key === 'compose') return composeFileName;if (key === 'override') return overrideFileName;if (key === 'env') return '.env';- return projectFileBasename(key.startsWith('file:') ? key.slice(5) : key);+ return workspaceFileBasename(key.startsWith('file:') ? key.slice(5) : key);}function treeTabTitle(key: string): string {@@ -1029,12 +1005,12 @@if (!key.startsWith('file:')) return false;const relativePath = key.slice(5);return (- changedManagedProjectFilePaths.includes(relativePath) ||- managedProjectFiles.find((file) => file.relativePath === relativePath)?.pending === true+ changedProjectWorkspacePaths.includes(relativePath) ||+ projectWorkspaceEntries.find((file) => file.relativePath === relativePath)?.pending === true);}- function selectManagedProjectFile(key: string) {+ function selectProjectWorkspaceFile(key: string) {openFileTab(key);}@@ -1060,122 +1036,151 @@}}- async function loadManagedProjectFileDraft(relativePath: string) {- if (!relativePath || managedProjectFileContents[relativePath] !== undefined || managedProjectFileLoading[relativePath]) {+ async function loadProjectWorkspaceFileDraft(relativePath: string) {+ if (!relativePath || projectWorkspaceContents[relativePath] !== undefined || projectWorkspaceLoading[relativePath]) {return;}- managedProjectFileLoading = {- ...managedProjectFileLoading,+ projectWorkspaceLoading = {+ ...projectWorkspaceLoading,[relativePath]: true};- managedProjectFileLoadErrors = removeProjectFileRecord(managedProjectFileLoadErrors, relativePath);+ projectWorkspaceLoadErrors = removeWorkspaceFileRecord(projectWorkspaceLoadErrors, relativePath);try {- const file = await getProjectFileResource('managed', relativePath);- updateLoadedManagedProjectFile(relativePath, file.content ?? '');+ const file = await getProjectWorkspaceFileResource('workspace', relativePath);+ projectWorkspaceFileMetadata = { ...projectWorkspaceFileMetadata, [relativePath]: file };+ if (file.editable) updateLoadedProjectWorkspaceFile(relativePath, file.content ?? '');} catch (error) {- managedProjectFileLoadErrors = {- ...managedProjectFileLoadErrors,+ projectWorkspaceLoadErrors = {+ ...projectWorkspaceLoadErrors,[relativePath]: error instanceof Error ? error.message : String(error)};} finally {- managedProjectFileLoading = removeProjectFileRecord(managedProjectFileLoading, relativePath);+ projectWorkspaceLoading = removeWorkspaceFileRecord(projectWorkspaceLoading, relativePath);}}$effect(() => {- const relativePath = selectedManagedProjectFilePath;- const entry = selectedManagedProjectFile;- const hasContent = relativePath ? managedProjectFileContents[relativePath] !== undefined : true;- const isLoadingFile = relativePath ? managedProjectFileLoading[relativePath] === true : false;- const hasLoadError = relativePath ? managedProjectFileLoadErrors[relativePath] !== undefined : false;-- if (!relativePath || !entry || entry.isDirectory || hasContent || isLoadingFile || hasLoadError) {+ const relativePath = selectedProjectWorkspacePath;+ const entry = selectedProjectWorkspaceEntry;+ const hasContent = relativePath ? projectWorkspaceContents[relativePath] !== undefined : true;+ const hasMetadata = relativePath ? projectWorkspaceFileMetadata[relativePath] !== undefined : true;+ const isLoadingFile = relativePath ? projectWorkspaceLoading[relativePath] === true : false;+ const hasLoadError = relativePath ? projectWorkspaceLoadErrors[relativePath] !== undefined : false;++ if (!relativePath || !entry || entry.isDirectory || hasContent || hasMetadata || isLoadingFile || hasLoadError) {return;}- void loadManagedProjectFileDraft(relativePath);+ void loadProjectWorkspaceFileDraft(relativePath);});- function remapManagedProjectFileState(oldPath: string, newPath: string) {- managedProjectFileContents = remapProjectFileRecord(managedProjectFileContents, oldPath, newPath);- loadedManagedProjectFileContents = remapProjectFileRecord(loadedManagedProjectFileContents, oldPath, newPath);- managedProjectFileHasErrors = remapProjectFileRecord(managedProjectFileHasErrors, oldPath, newPath);- managedProjectFileValidationReady = remapProjectFileRecord(managedProjectFileValidationReady, oldPath, newPath);- managedProjectFileLoadErrors = remapProjectFileRecord(managedProjectFileLoadErrors, oldPath, newPath);- managedProjectFileLoading = remapProjectFileRecord(managedProjectFileLoading, oldPath, newPath);- includeFilesState = remapProjectFileRecord(includeFilesState, oldPath, newPath);- loadedIncludeFileContents = remapProjectFileRecord(loadedIncludeFileContents, oldPath, newPath);- includeFilesPanelStates = remapProjectFileRecord(includeFilesPanelStates, oldPath, newPath);- includeFilesHasErrors = remapProjectFileRecord(includeFilesHasErrors, oldPath, newPath);- includeFilesValidationReady = remapProjectFileRecord(includeFilesValidationReady, oldPath, newPath);- openTabsPreference = openTabsPreference.map((tab) => remapSelectedProjectFileKey(tab, oldPath, newPath) ?? tab);- const remappedSelection = remapSelectedProjectFileKey(selectedFile, oldPath, newPath);+ function remapProjectWorkspaceState(oldPath: string, newPath: string) {+ projectWorkspaceContents = remapWorkspaceFileRecord(projectWorkspaceContents, oldPath, newPath);+ loadedProjectWorkspaceContents = remapWorkspaceFileRecord(loadedProjectWorkspaceContents, oldPath, newPath);+ projectWorkspaceHasErrors = remapWorkspaceFileRecord(projectWorkspaceHasErrors, oldPath, newPath);+ projectWorkspaceValidationReady = remapWorkspaceFileRecord(projectWorkspaceValidationReady, oldPath, newPath);+ projectWorkspaceLoadErrors = remapWorkspaceFileRecord(projectWorkspaceLoadErrors, oldPath, newPath);+ projectWorkspaceLoading = remapWorkspaceFileRecord(projectWorkspaceLoading, oldPath, newPath);+ projectWorkspaceFileMetadata = remapWorkspaceFileRecord(projectWorkspaceFileMetadata, oldPath, newPath);+ includeFilesState = remapWorkspaceFileRecord(includeFilesState, oldPath, newPath);+ loadedIncludeFileContents = remapWorkspaceFileRecord(loadedIncludeFileContents, oldPath, newPath);+ includeFilesPanelStates = remapWorkspaceFileRecord(includeFilesPanelStates, oldPath, newPath);+ includeFilesHasErrors = remapWorkspaceFileRecord(includeFilesHasErrors, oldPath, newPath);+ includeFilesValidationReady = remapWorkspaceFileRecord(includeFilesValidationReady, oldPath, newPath);+ openTabsPreference = openTabsPreference.map((tab) => remapSelectedWorkspaceFileKey(tab, oldPath, newPath) ?? tab);+ const remappedSelection = remapSelectedWorkspaceFileKey(selectedFile, oldPath, newPath);if (remappedSelection) {selectedFilePreference = remappedSelection;}}- function removeManagedProjectFileState(relativePath: string) {- managedProjectFileContents = removeProjectFileRecord(managedProjectFileContents, relativePath);- loadedManagedProjectFileContents = removeProjectFileRecord(loadedManagedProjectFileContents, relativePath);- managedProjectFileHasErrors = removeProjectFileRecord(managedProjectFileHasErrors, relativePath);- managedProjectFileValidationReady = removeProjectFileRecord(managedProjectFileValidationReady, relativePath);- managedProjectFileLoadErrors = removeProjectFileRecord(managedProjectFileLoadErrors, relativePath);- managedProjectFileLoading = removeProjectFileRecord(managedProjectFileLoading, relativePath);- includeFilesState = removeProjectFileRecord(includeFilesState, relativePath);- loadedIncludeFileContents = removeProjectFileRecord(loadedIncludeFileContents, relativePath);- includeFilesPanelStates = removeProjectFileRecord(includeFilesPanelStates, relativePath);- includeFilesHasErrors = removeProjectFileRecord(includeFilesHasErrors, relativePath);- includeFilesValidationReady = removeProjectFileRecord(includeFilesValidationReady, relativePath);- openTabsPreference = openTabsPreference.filter((tab) => !isProjectFileSelectionUnder(tab, relativePath));- if (isProjectFileSelectionUnder(selectedFile, relativePath)) {+ function removeProjectWorkspaceState(relativePath: string) {+ projectWorkspaceContents = removeWorkspaceFileRecord(projectWorkspaceContents, relativePath);+ loadedProjectWorkspaceContents = removeWorkspaceFileRecord(loadedProjectWorkspaceContents, relativePath);+ projectWorkspaceHasErrors = removeWorkspaceFileRecord(projectWorkspaceHasErrors, relativePath);+ projectWorkspaceValidationReady = removeWorkspaceFileRecord(projectWorkspaceValidationReady, relativePath);+ projectWorkspaceLoadErrors = removeWorkspaceFileRecord(projectWorkspaceLoadErrors, relativePath);+ projectWorkspaceLoading = removeWorkspaceFileRecord(projectWorkspaceLoading, relativePath);+ projectWorkspaceFileMetadata = removeWorkspaceFileRecord(projectWorkspaceFileMetadata, relativePath);+ includeFilesState = removeWorkspaceFileRecord(includeFilesState, relativePath);+ loadedIncludeFileContents = removeWorkspaceFileRecord(loadedIncludeFileContents, relativePath);+ includeFilesPanelStates = removeWorkspaceFileRecord(includeFilesPanelStates, relativePath);+ includeFilesHasErrors = removeWorkspaceFileRecord(includeFilesHasErrors, relativePath);+ includeFilesValidationReady = removeWorkspaceFileRecord(includeFilesValidationReady, relativePath);+ openTabsPreference = openTabsPreference.filter((tab) => !isWorkspaceFileSelectionUnder(tab, relativePath));+ if (isWorkspaceFileSelectionUnder(selectedFile, relativePath)) {selectedFilePreference = openTabs[0] ?? 'compose';}}- function createManagedProjectFile(parentPath: string, name: string, content = '') {- const relativePath = planProjectFileCreate(managedProjectFilePaths, parentPath, name, composeFileName);+ function createProjectWorkspaceFile(parentPath: string, name: string, content = '') {+ const relativePath = planProjectWorkspaceFileCreate(projectWorkspacePaths, parentPath, name, composeFileName);if (!relativePath) return;- managedProjectFileChanges = [...managedProjectFileChanges, { operation: 'create_file', relativePath, content }];- managedProjectFileContents = { ...managedProjectFileContents, [relativePath]: content };- loadedManagedProjectFileContents = { ...loadedManagedProjectFileContents, [relativePath]: content };- managedProjectFileLoadErrors = removeProjectFileRecord(managedProjectFileLoadErrors, relativePath);- ensureManagedProjectFileUiState(relativePath);+ projectWorkspaceChanges = [...projectWorkspaceChanges, { operation: 'create_file', relativePath }];+ projectWorkspaceContents = { ...projectWorkspaceContents, [relativePath]: content };+ loadedProjectWorkspaceContents = { ...loadedProjectWorkspaceContents, [relativePath]: content };+ projectWorkspaceFileMetadata = {+ ...projectWorkspaceFileMetadata,+ [relativePath]: {+ path: relativePath,+ relativePath,+ name: workspaceFileBasename(relativePath),+ size: content.length,+ mimeType: 'text/plain',+ content,+ editable: true+ }+ };+ projectWorkspaceLoadErrors = removeWorkspaceFileRecord(projectWorkspaceLoadErrors, relativePath);+ ensureProjectWorkspaceUiState(relativePath);openFileTab(`file:${relativePath}`);}- function createManagedProjectFolder(parentPath: string, name: string) {- const relativePath = planProjectFileCreate(managedProjectFilePaths, parentPath, name, composeFileName);+ async function uploadProjectWorkspaceFiles(parentPath: string, files: File[]): Promise<string | void> {+ const file = files[0];+ if (!file) return m.workspace_upload_file_required();+ const result = await readWorkspaceTextUpload(file, projectWorkspaceMaxFileSizeMb);+ if (result.error) return result.error;+ createProjectWorkspaceFile(parentPath, file.name, result.content ?? '');+ }++ async function downloadProjectWorkspaceFile(relativePath: string) {+ try {+ await projectWorkspaceService.downloadWorkspaceFile(projectId, relativePath, envId);+ } catch (error) {+ toast.error(error instanceof Error ? error.message : m.common_download_error());+ }+ }++ function createProjectWorkspaceFolder(parentPath: string, name: string) {+ const relativePath = planProjectWorkspaceFileCreate(projectWorkspacePaths, parentPath, name, composeFileName);if (!relativePath) return;- managedProjectFileChanges = [...managedProjectFileChanges, { operation: 'create_folder', relativePath }];+ projectWorkspaceChanges = [...projectWorkspaceChanges, { operation: 'create_folder', relativePath }];selectedFilePreference = `file:${relativePath}`;}- function renameManagedProjectFile(relativePath: string, newName: string) {- const plan = planProjectFileRename(managedProjectFilePaths, relativePath, newName, composeFileName);+ function renameProjectWorkspaceFile(relativePath: string, newName: string) {+ const plan = planProjectWorkspaceFileRename(projectWorkspacePaths, relativePath, newName, composeFileName);if (!plan) return;- managedProjectFileChanges = [...managedProjectFileChanges, { operation: 'rename', relativePath, newName: plan.newName }];- remapManagedProjectFileState(relativePath, plan.newPath);+ projectWorkspaceChanges = [...projectWorkspaceChanges, { operation: 'rename', relativePath, newName: plan.newName }];+ remapProjectWorkspaceState(relativePath, plan.newPath);}- function moveManagedProjectFile(relativePath: string, newParentPath: string) {- const entry = managedProjectFiles.find((file) => file.relativePath === relativePath);- const newPath = planProjectFileMove(entry, managedProjectFilePaths, relativePath, newParentPath);+ function moveProjectWorkspaceFile(relativePath: string, newParentPath: string) {+ const entry = projectWorkspaceEntries.find((file) => file.relativePath === relativePath);+ const newPath = planProjectWorkspaceFileMove(entry, projectWorkspacePaths, relativePath, newParentPath);if (!newPath) return;- managedProjectFileChanges = [...managedProjectFileChanges, { operation: 'move', relativePath, newParentPath }];- remapManagedProjectFileState(relativePath, newPath);+ projectWorkspaceChanges = [...projectWorkspaceChanges, { operation: 'move', relativePath, newParentPath }];+ remapProjectWorkspaceState(relativePath, newPath);}- function deleteManagedProjectFile(relativePath: string) {- const entry = managedProjectFiles.find((file) => file.relativePath === relativePath);+ function deleteProjectWorkspaceFile(relativePath: string) {+ const entry = projectWorkspaceEntries.find((file) => file.relativePath === relativePath);if (!entry) return;- managedProjectFileChanges = [- ...managedProjectFileChanges,- { operation: 'delete', relativePath, recursive: entry.isDirectory }- ];- removeManagedProjectFileState(relativePath);+ projectWorkspaceChanges = [...projectWorkspaceChanges, { operation: 'delete', relativePath, recursive: entry.isDirectory }];+ removeProjectWorkspaceState(relativePath);}function toggleIncludeFileTab(relativePath: string) {@@ -1569,21 +1574,21 @@onResizeEnd={persistPrefs}>{#snippet first()}- <ProjectFileTreePanel- {composeFileName}- {overrideFileName}- showOverride={overrideActive}- onAddOverride={canEditOverride ? handleAddOverride : undefined}- entries={managedProjectFiles}+ <WorkspaceFileTreePanel+ leadingRows={projectWorkspaceLeadingRows}+ entries={projectWorkspaceEntries}{selectedFile}- disabled={!canEditProjectFiles}- readOnlyMessage={isGitOpsManaged ? m.project_files_readonly_git() : undefined}- onSelect={selectManagedProjectFile}- onCreateFile={createManagedProjectFile}- onCreateFolder={createManagedProjectFolder}- onRename={renameManagedProjectFile}- onMove={moveManagedProjectFile}- onDelete={deleteManagedProjectFile}+ disabled={!canEditProjectWorkspace}+ readOnlyMessage={isGitOpsManaged ? m.projects_workspace_readonly_git() : undefined}+ onSelect={selectProjectWorkspaceFile}+ onCreateFile={createProjectWorkspaceFile}+ onCreateFolder={createProjectWorkspaceFolder}+ onUpload={uploadProjectWorkspaceFiles}+ onDownload={downloadProjectWorkspaceFile}+ validateName={(name, parentPath) => validateProjectWorkspaceFileName(name, parentPath, composeFileName)}+ onRename={renameProjectWorkspaceFile}+ onMove={moveProjectWorkspaceFile}+ onDelete={deleteProjectWorkspaceFile}/>{/snippet}@@ -1659,11 +1664,20 @@/>{:else if activeTreeTab.startsWith('file:')}{@const relativePath = activeTreeTab.slice(5)}- {#if managedProjectFileLoadErrors[relativePath]}+ {#if projectWorkspaceLoadErrors[relativePath]}<div class="flex h-full min-h-0 items-center justify-center px-4 text-sm text-destructive">- {managedProjectFileLoadErrors[relativePath]}+ {projectWorkspaceLoadErrors[relativePath]}+ </div>+ {:else if selectedProjectWorkspaceMetadata?.editable === false}+ <div+ class="flex h-full min-h-0 items-center justify-center px-4 text-center text-sm text-muted-foreground"+ >+ {workspaceReadOnlyMessage(+ selectedProjectWorkspaceMetadata.readOnlyReason,+ projectWorkspaceMaxFileSizeMb+ )}</div>- {:else if managedProjectFileContents[relativePath] === undefined}+ {:else if projectWorkspaceContents[relativePath] === undefined}<div class="flex h-full min-h-0 items-center justify-center text-muted-foreground">{m.common_loading()}</div>@@ -1672,14 +1686,14 @@variant="plain"open={true}title={relativePath}- language={projectFileLanguage(relativePath)}+ language={workspaceFileLanguage(relativePath)}validationMode="none"- bind:value={managedProjectFileContents[relativePath]}- readOnly={!canEditProjectFiles}- bind:hasErrors={managedProjectFileHasErrors[relativePath]}- bind:validationReady={managedProjectFileValidationReady[relativePath]}+ bind:value={projectWorkspaceContents[relativePath]}+ readOnly={!canEditProjectWorkspace}+ bind:hasErrors={projectWorkspaceHasErrors[relativePath]}+ bind:validationReady={projectWorkspaceValidationReady[relativePath]}fileId={`project:${projectId}:file:${relativePath}`}- originalValue={loadedManagedProjectFileContents[relativePath] ?? ''}+ originalValue={loadedProjectWorkspaceContents[relativePath] ?? ''}enableDiff={true}editorContext={codeEditorContext}bind:outlineOpen={treeOutlineOpen}@@ -1729,10 +1743,10 @@{#if selectedIncludeTab}{@const includeFile = project?.includeFiles?.find((f) => f.relativePath === selectedIncludeTab)}{@const dirFile = !includeFile- ? project?.directoryFiles?.find((f) => f.relativePath === selectedIncludeTab)+ ? projectWorkspaceEntries.find((f) => f.relativePath === selectedIncludeTab): undefined}{@const fileKind = includeFile ? 'include' : 'directory'}- {#await getProjectFileResource(fileKind, selectedIncludeTab)}+ {#await getProjectWorkspaceFileResource(fileKind, selectedIncludeTab)}<div class="flex h-full min-h-0 items-center justify-center rounded-lg border text-muted-foreground">{m.common_loading()}</div>diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.ts b/frontend/src/routes/(app)/projects/[projectId]/+page.tsindex f16128ee2..969855b23 100644--- a/frontend/src/routes/(app)/projects/[projectId]/+page.ts+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.ts@@ -1,4 +1,5 @@import { projectService } from '#lib/services/project-service';+import { projectWorkspaceService } from '#lib/services/project-workspace-service';import { variableService } from '#lib/services/variable-service';import { environmentStore } from '#lib/stores/environment.store.svelte';import { queryKeys } from '#lib/query/query-keys';@@ -37,8 +38,8 @@ export const load: PageLoad = async ({ params, parent }) => {// Kick off the file-tree walk without awaiting it: on large projects it can// take a while and must not block navigation.void queryClient.prefetchQuery({- queryKey: queryKeys.projects.files(envId, params.projectId),- queryFn: () => projectService.getProjectFiles(envId, params.projectId)+ queryKey: queryKeys.projects.workspace(envId, params.projectId),+ queryFn: () => projectWorkspaceService.getWorkspace(params.projectId, envId)});const globalVariables = await loadGlobalVariables(queryClient);diff --git a/frontend/src/routes/(app)/projects/components/project-file-tree-utils.ts b/frontend/src/routes/(app)/projects/components/project-file-tree-utils.tsdeleted file mode 100644index 6adadfcd8..000000000--- a/frontend/src/routes/(app)/projects/components/project-file-tree-utils.ts+++ /dev/null@@ -1,287 +0,0 @@-import { toast } from 'svelte-sonner';-import { m } from '#lib/paraglide/messages';-import type { ProjectFile, ProjectFileChange } from '#lib/types/project-files';-import type { CodeLanguage } from '#lib/components/code-editor/analysis/types';--export type ManagedProjectFileEntry = ProjectFile & {- pending?: boolean;-};--const reservedRootNames = new Set([- '.env',- '.env.git',- 'project.env',- 'compose.yaml',- 'compose.yml',- 'docker-compose.yaml',- 'docker-compose.yml',- 'podman-compose.yaml',- 'podman-compose.yml',- 'compose.override.yaml',- 'compose.override.yml',- 'docker-compose.override.yaml',- 'docker-compose.override.yml'-]);--export function projectFileBasename(relativePath: string): string {- const normalized = normalizeProjectRelativePath(relativePath);- const index = normalized.lastIndexOf('/');- return index >= 0 ? normalized.slice(index + 1) : normalized;-}--export function projectFileParentPath(relativePath: string): string {- const normalized = normalizeProjectRelativePath(relativePath);- const index = normalized.lastIndexOf('/');- return index >= 0 ? normalized.slice(0, index) : '';-}--export function joinProjectFilePath(parentPath: string, name: string): string {- const parent = normalizeProjectRelativePath(parentPath);- return parent ? `${parent}/${name}` : name;-}--export function normalizeProjectRelativePath(relativePath: string): string {- return relativePath.trim().replaceAll('\\', '/').split('/').filter(Boolean).join('/');-}--export function validateProjectFileName(name: string, parentPath = '', composeFileName = 'compose.yaml'): string | null {- const trimmed = name.trim();- if (!trimmed || trimmed === '.' || trimmed === '..') return null;- if (trimmed.includes('/') || trimmed.includes('\\') || trimmed.includes('\0')) return null;- if (!parentPath && isReservedProjectFileName(trimmed, composeFileName)) return null;- return trimmed;-}--export function isReservedProjectFileName(name: string, composeFileName = 'compose.yaml'): boolean {- const lower = name.trim().toLowerCase();- return lower === composeFileName.toLowerCase() || reservedRootNames.has(lower);-}--export function projectFilePathMatches(relativePath: string, rootPath: string): boolean {- return relativePath === rootPath || relativePath.startsWith(`${rootPath}/`);-}--function requireValidProjectFileName(name: string, parentPath: string, composeFileName: string): string | null {- const normalized = validateProjectFileName(name, parentPath, composeFileName);- if (!normalized) {- toast.error(m.project_file_invalid_name());- }- return normalized;-}--// Validates a create operation and returns the new relative path, or null-// (after showing a toast) when the name is invalid or already taken.-export function planProjectFileCreate(- existingPaths: ReadonlySet<string>,- parentPath: string,- name: string,- composeFileName = 'compose.yaml'-): string | null {- const normalizedName = requireValidProjectFileName(name, parentPath, composeFileName);- if (!normalizedName) return null;- const relativePath = joinProjectFilePath(parentPath, normalizedName);- if (existingPaths.has(relativePath)) {- toast.error(m.project_file_duplicate_name());- return null;- }- return relativePath;-}--// Validates a rename and returns the normalized name plus resulting path, or-// null (after showing a toast) when invalid.-export function planProjectFileRename(- existingPaths: ReadonlySet<string>,- relativePath: string,- newName: string,- composeFileName = 'compose.yaml'-): { newName: string; newPath: string } | null {- const parentPath = projectFileParentPath(relativePath);- const normalizedName = requireValidProjectFileName(newName, parentPath, composeFileName);- if (!normalizedName) return null;- const newPath = joinProjectFilePath(parentPath, normalizedName);- if (newPath !== relativePath && existingPaths.has(newPath)) {- toast.error(m.project_file_duplicate_name());- return null;- }- return { newName: normalizedName, newPath };-}--// Validates a move and returns the resulting path. Returns null without a-// toast when the move is a no-op, or with a toast when it is invalid.-export function planProjectFileMove(- entry: Pick<ManagedProjectFileEntry, 'isDirectory'> | undefined,- existingPaths: ReadonlySet<string>,- relativePath: string,- newParentPath: string-): string | null {- if (!entry) return null;- if (newParentPath === projectFileParentPath(relativePath)) return null;- if (entry.isDirectory && newParentPath && projectFilePathMatches(newParentPath, relativePath)) {- toast.error(m.project_file_invalid_move_destination());- return null;- }- const newPath = joinProjectFilePath(newParentPath, projectFileBasename(relativePath));- if (newPath !== relativePath && existingPaths.has(newPath)) {- toast.error(m.project_file_duplicate_name());- return null;- }- return newPath;-}--export function remapProjectFilePath(path: string, oldPath: string, newPath: string): string {- return projectFilePathMatches(path, oldPath) ? `${newPath}${path.slice(oldPath.length)}` : path;-}--// Remaps a "file:<path>" selection key after a rename/move; returns null when-// the selection is unrelated to oldPath.-export function remapSelectedProjectFileKey(selectedKey: string, oldPath: string, newPath: string): string | null {- if (!selectedKey.startsWith('file:')) return null;- const selectedPath = selectedKey.slice(5);- if (!projectFilePathMatches(selectedPath, oldPath)) return null;- return `file:${newPath}${selectedPath.slice(oldPath.length)}`;-}--export function isProjectFileSelectionUnder(selectedKey: string, rootPath: string): boolean {- return selectedKey.startsWith('file:') && projectFilePathMatches(selectedKey.slice(5), rootPath);-}--export function remapProjectFileRecord<T>(record: Record<string, T>, oldPath: string, newPath: string): Record<string, T> {- return Object.fromEntries(- Object.entries(record).map(([relativePath, value]) => {- if (!projectFilePathMatches(relativePath, oldPath)) {- return [relativePath, value] as const;- }-- const suffix = relativePath.slice(oldPath.length);- return [`${newPath}${suffix}`, value] as const;- })- );-}--export function removeProjectFileRecord<T>(record: Record<string, T>, rootPath: string): Record<string, T> {- return Object.fromEntries(Object.entries(record).filter(([relativePath]) => !projectFilePathMatches(relativePath, rootPath)));-}--export function projectFileLanguage(relativePath: string): CodeLanguage {- const lower = relativePath.toLowerCase();- const basename = projectFileBasename(lower);- if (lower.endsWith('.env') || basename.startsWith('.env')) return 'env';- if (lower.endsWith('.yaml') || lower.endsWith('.yml')) return 'yaml';- if (lower.endsWith('.json')) return 'json';- if (lower.endsWith('.toml')) return 'toml';- if (basename === 'dockerfile' || basename.startsWith('dockerfile.') || lower.endsWith('.dockerfile')) return 'dockerfile';- if (lower.endsWith('.sh') || lower.endsWith('.bash') || lower.endsWith('.zsh') || lower.endsWith('.fish')) return 'shell';- if (lower.endsWith('.ts') || lower.endsWith('.tsx') || lower.endsWith('.mts') || lower.endsWith('.cts')) return 'typescript';- if (lower.endsWith('.js') || lower.endsWith('.jsx') || lower.endsWith('.mjs') || lower.endsWith('.cjs')) return 'javascript';- if (lower.endsWith('.md') || lower.endsWith('.markdown') || lower.endsWith('.mdx')) return 'markdown';- return 'plaintext';-}--export function compareProjectFileEntries(a: ManagedProjectFileEntry, b: ManagedProjectFileEntry): number {- if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;- return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });-}--export function applyProjectFileChangesForDisplay(files: ProjectFile[], changes: ProjectFileChange[]): ManagedProjectFileEntry[] {- const entries = new Map<string, ManagedProjectFileEntry>();-- for (const file of files) {- entries.set(file.relativePath, {- ...file,- name: file.name || projectFileBasename(file.relativePath)- });- }-- for (const change of changes) {- const relativePath = normalizeProjectRelativePath(change.relativePath);- switch (change.operation) {- case 'create_file':- entries.set(relativePath, {- path: relativePath,- relativePath,- name: projectFileBasename(relativePath),- isDirectory: false,- size: change.content?.length ?? 0,- pending: true- });- break;- case 'create_folder':- entries.set(relativePath, {- path: relativePath,- relativePath,- name: projectFileBasename(relativePath),- isDirectory: true,- size: 0,- pending: true- });- break;- case 'rename': {- const entry = entries.get(relativePath);- if (!entry || !change.newName) break;-- const parentPath = projectFileParentPath(relativePath);- const newPath = joinProjectFilePath(parentPath, change.newName);- const remapped = new Map<string, ManagedProjectFileEntry>();- for (const [entryPath, current] of entries.entries()) {- if (!projectFilePathMatches(entryPath, relativePath)) {- remapped.set(entryPath, current);- continue;- }-- const suffix = entryPath.slice(relativePath.length);- const movedPath = `${newPath}${suffix}`;- remapped.set(movedPath, {- ...current,- path: movedPath,- relativePath: movedPath,- name: projectFileBasename(movedPath),- pending: true- });- }- entries.clear();- for (const [entryPath, current] of remapped.entries()) {- entries.set(entryPath, current);- }- break;- }- case 'move': {- const entry = entries.get(relativePath);- if (!entry) break;-- const newParentPath = normalizeProjectRelativePath(change.newParentPath ?? '');- const newPath = joinProjectFilePath(newParentPath, projectFileBasename(relativePath));- const remapped = new Map<string, ManagedProjectFileEntry>();- for (const [entryPath, current] of entries.entries()) {- if (!projectFilePathMatches(entryPath, relativePath)) {- remapped.set(entryPath, current);- continue;- }-- const suffix = entryPath.slice(relativePath.length);- const movedPath = `${newPath}${suffix}`;- remapped.set(movedPath, {- ...current,- path: movedPath,- relativePath: movedPath,- name: projectFileBasename(movedPath),- pending: true- });- }- entries.clear();- for (const [entryPath, current] of remapped.entries()) {- entries.set(entryPath, current);- }- break;- }- case 'delete':- for (const entryPath of [...entries.keys()]) {- if (projectFilePathMatches(entryPath, relativePath)) {- entries.delete(entryPath);- }- }- break;- }- }-- return [...entries.values()].sort((a, b) => a.relativePath.localeCompare(b.relativePath));-}diff --git a/frontend/src/routes/(app)/projects/components/project-workspace-utils.ts b/frontend/src/routes/(app)/projects/components/project-workspace-utils.tsnew file mode 100644index 000000000..fe39447e1--- /dev/null+++ b/frontend/src/routes/(app)/projects/components/project-workspace-utils.ts@@ -0,0 +1,99 @@+import { toast } from 'svelte-sonner';+import { m } from '#lib/paraglide/messages';+import {+ joinWorkspaceFilePath,+ validateWorkspaceFileName,+ workspaceFileBasename,+ workspaceFileParentPath,+ workspaceFilePathMatches,+ type WorkspaceFileEntry+} from '#lib/utils/workspace-files';++export type ProjectWorkspaceEntry = WorkspaceFileEntry;++const reservedRootNames = new Set([+ '.env',+ '.env.git',+ 'project.env',+ 'compose.yaml',+ 'compose.yml',+ 'docker-compose.yaml',+ 'docker-compose.yml',+ 'podman-compose.yaml',+ 'podman-compose.yml',+ 'compose.override.yaml',+ 'compose.override.yml',+ 'docker-compose.override.yaml',+ 'docker-compose.override.yml'+]);++export function validateProjectWorkspaceFileName(name: string, parentPath = '', composeFileName = 'compose.yaml'): string | null {+ const normalized = validateWorkspaceFileName(name);+ if (!normalized) return null;+ if (!parentPath && isReservedProjectFileName(normalized, composeFileName)) return null;+ return normalized;+}++export function isReservedProjectFileName(name: string, composeFileName = 'compose.yaml'): boolean {+ const lower = name.trim().toLowerCase();+ return lower === composeFileName.toLowerCase() || reservedRootNames.has(lower);+}++function requireValidProjectWorkspaceFileName(name: string, parentPath: string, composeFileName: string): string | null {+ const normalized = validateProjectWorkspaceFileName(name, parentPath, composeFileName);+ if (!normalized) toast.error(m.workspace_file_invalid_name());+ return normalized;+}++export function planProjectWorkspaceFileCreate(+ existingPaths: ReadonlySet<string>,+ parentPath: string,+ name: string,+ composeFileName = 'compose.yaml'+): string | null {+ const normalizedName = requireValidProjectWorkspaceFileName(name, parentPath, composeFileName);+ if (!normalizedName) return null;+ const relativePath = joinWorkspaceFilePath(parentPath, normalizedName);+ if (existingPaths.has(relativePath)) {+ toast.error(m.workspace_file_duplicate_name());+ return null;+ }+ return relativePath;+}++export function planProjectWorkspaceFileRename(+ existingPaths: ReadonlySet<string>,+ relativePath: string,+ newName: string,+ composeFileName = 'compose.yaml'+): { newName: string; newPath: string } | null {+ const parentPath = workspaceFileParentPath(relativePath);+ const normalizedName = requireValidProjectWorkspaceFileName(newName, parentPath, composeFileName);+ if (!normalizedName) return null;+ const newPath = joinWorkspaceFilePath(parentPath, normalizedName);+ if (newPath !== relativePath && existingPaths.has(newPath)) {+ toast.error(m.workspace_file_duplicate_name());+ return null;+ }+ return { newName: normalizedName, newPath };+}++export function planProjectWorkspaceFileMove(+ entry: Pick<WorkspaceFileEntry, 'isDirectory'> | undefined,+ existingPaths: ReadonlySet<string>,+ relativePath: string,+ newParentPath: string+): string | null {+ if (!entry) return null;+ if (newParentPath === workspaceFileParentPath(relativePath)) return null;+ if (entry.isDirectory && newParentPath && workspaceFilePathMatches(newParentPath, relativePath)) {+ toast.error(m.workspace_file_invalid_move_destination());+ return null;+ }+ const newPath = joinWorkspaceFilePath(newParentPath, workspaceFileBasename(relativePath));+ if (newPath !== relativePath && existingPaths.has(newPath)) {+ toast.error(m.workspace_file_duplicate_name());+ return null;+ }+ return newPath;+}diff --git a/frontend/src/routes/(app)/projects/new/+page.svelte b/frontend/src/routes/(app)/projects/new/+page.svelteindex d3efa393c..34541c676 100644--- a/frontend/src/routes/(app)/projects/new/+page.svelte+++ b/frontend/src/routes/(app)/projects/new/+page.svelte@@ -9,10 +9,10 @@import { projectService } from '#lib/services/project-service.js';import ComposeCreateMenu from '#lib/components/compose-create-menu.svelte';import ComposeFileEditorPanel from '#lib/components/compose-file-editor-panel.svelte';- import CodePanel from '../components/CodePanel.svelte';+ import CodePanel from '#lib/components/code-panel.svelte';import EditableName from '../components/EditableName.svelte';- import ProjectFileTreePanel from '../components/ProjectFileTreePanel.svelte';- import EditorTabStrip from '../components/EditorTabStrip.svelte';+ import WorkspaceFileTreePanel from '#lib/components/workspace-file-tree-panel.svelte';+ import EditorTabStrip from '#lib/components/editor-tab-strip.svelte';import { environmentStore } from '#lib/stores/environment.store.svelte';import { hasPermission } from '#lib/utils/auth';import { ComposeEditorSplit } from '#lib/components/compose';@@ -21,21 +21,26 @@import DockerRunConverterDialog from '#lib/components/compose/docker-run-converter-dialog.svelte';import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast';import { globalVariablesToMap } from '#lib/utils/template-load';- import type { ProjectFileDraft } from '#lib/types/project-files';+ import type { ProjectWorkspaceFileDraft } from '#lib/types/project-workspace';+ import settingsStore from '#lib/stores/config-store';import {- isProjectFileSelectionUnder,- planProjectFileCreate,- planProjectFileMove,- planProjectFileRename,- projectFileBasename,- projectFileLanguage,- projectFilePathMatches,- remapProjectFilePath,- remapProjectFileRecord,- remapSelectedProjectFileKey,- removeProjectFileRecord,- type ManagedProjectFileEntry- } from '../components/project-file-tree-utils';+ planProjectWorkspaceFileCreate,+ planProjectWorkspaceFileMove,+ planProjectWorkspaceFileRename,+ validateProjectWorkspaceFileName+ } from '../components/project-workspace-utils';+ import {+ isWorkspaceFileSelectionUnder,+ workspaceFileBasename,+ workspaceFileLanguage,+ workspaceFilePathMatches,+ remapWorkspaceFilePath,+ remapWorkspaceFileRecord,+ remapSelectedWorkspaceFileKey,+ removeWorkspaceFileRecord,+ readWorkspaceTextUpload,+ type WorkspaceFileEntry+ } from '#lib/utils/workspace-files';import {composeTreeSplitProps,createComposeEditorSchema,@@ -54,6 +59,7 @@const currentEnvId = $derived(environmentStore.selected?.id || '0');const canCreateProject = $derived(hasPermission('projects:create', currentEnvId));+ const projectWorkspaceMaxFileSizeMb = $derived($settingsStore?.projectWorkspaceMaxFileSizeMb ?? 10);let ui = $state({saving: false,@@ -79,12 +85,12 @@let composeOpen = $state(true);let envOpen = $state(true);let layoutMode = $state<'classic' | 'tree'>('classic');- let selectedProjectFile = $state<'compose' | 'env' | string>('compose');+ let selectedEditorFile = $state<'compose' | 'env' | string>('compose');let treePaneWidth = $state(280);- let newProjectFiles = $state<ProjectFileDraft[]>([]);- let newProjectFileContents = $state<Record<string, string>>({});- let newProjectFileHasErrors = $state<Record<string, boolean>>({});- let newProjectFileValidationReady = $state<Record<string, boolean>>({});+ let newProjectWorkspaceFiles = $state<ProjectWorkspaceFileDraft[]>([]);+ let newProjectWorkspaceContents = $state<Record<string, string>>({});+ let newProjectWorkspaceHasErrors = $state<Record<string, boolean>>({});+ let newProjectWorkspaceValidationReady = $state<Record<string, boolean>>({});let validation = $state({composeHasErrors: false,envHasErrors: false,@@ -93,18 +99,22 @@});const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));- const newProjectFileEntries = $derived.by<ManagedProjectFileEntry[]>(() =>- newProjectFiles.map((file) => ({+ const newProjectWorkspaceEntries = $derived.by<WorkspaceFileEntry[]>(() =>+ newProjectWorkspaceFiles.map((file) => ({path: file.relativePath,relativePath: file.relativePath,- name: projectFileBasename(file.relativePath),+ name: workspaceFileBasename(file.relativePath),isDirectory: !!file.isDirectory,- size: file.isDirectory ? 0 : (newProjectFileContents[file.relativePath]?.length ?? 0),- content: file.isDirectory ? undefined : (newProjectFileContents[file.relativePath] ?? ''),+ size: file.isDirectory ? 0 : (newProjectWorkspaceContents[file.relativePath]?.length ?? 0),+ content: file.isDirectory ? undefined : (newProjectWorkspaceContents[file.relativePath] ?? ''),pending: true})));- const newProjectFilePaths = $derived.by(() => new Set(newProjectFileEntries.map((file) => file.relativePath)));+ const newProjectWorkspacePaths = $derived.by(() => new Set(newProjectWorkspaceEntries.map((file) => file.relativePath)));+ const newProjectWorkspaceLeadingRows = [+ { key: 'compose', label: 'compose.yaml', iconClass: 'text-blue-500', locked: true },+ { key: 'env', label: '.env', iconClass: 'text-green-500', locked: true }+ ];let openProjectTabs = $state<string[]>(['compose']);let treeOutlineOpen = $state(false);let treeDiffOpen = $state(false);@@ -113,16 +123,16 @@const valid = openProjectTabs.filter((key) => {if (key === 'compose' || key === 'env') return true;if (!key.startsWith('file:')) return false;- const entry = newProjectFileEntries.find((file) => file.relativePath === key.slice(5));+ const entry = newProjectWorkspaceEntries.find((file) => file.relativePath === key.slice(5));return !!entry && !entry.isDirectory;});return valid.length > 0 ? valid : ['compose'];});- const activeProjectTab = $derived(openTabs.includes(selectedProjectFile) ? selectedProjectFile : (openTabs[0] ?? 'compose'));+ const activeProjectTab = $derived(openTabs.includes(selectedEditorFile) ? selectedEditorFile : (openTabs[0] ?? 'compose'));const projectTabs = $derived(openTabs.map((key) => ({key,- label: key === 'compose' ? 'compose.yaml' : key === 'env' ? '.env' : projectFileBasename(key.slice(5)),+ label: key === 'compose' ? 'compose.yaml' : key === 'env' ? '.env' : workspaceFileBasename(key.slice(5)),title: key === 'compose' ? 'compose.yaml' : key === 'env' ? '.env' : key.slice(5),iconClass: key === 'compose' ? 'text-blue-500' : key === 'env' ? 'text-green-500' : 'text-muted-foreground',pending: false@@ -131,22 +141,22 @@function isNewProjectDirectoryKey(key: string): boolean {if (!key.startsWith('file:')) return false;- return newProjectFileEntries.find((file) => file.relativePath === key.slice(5))?.isDirectory === true;+ return newProjectWorkspaceEntries.find((file) => file.relativePath === key.slice(5))?.isDirectory === true;}- function openProjectFileTab(key: string) {+ function openEditorFileTab(key: string) {if (!isNewProjectDirectoryKey(key) && !openProjectTabs.includes(key)) {openProjectTabs = [...openProjectTabs, key];}- selectedProjectFile = key;+ selectedEditorFile = key;}- function closeProjectFileTab(key: string) {+ function closeEditorFileTab(key: string) {const index = openTabs.indexOf(key);const remaining = openTabs.filter((tab) => tab !== key);openProjectTabs = openProjectTabs.filter((tab) => tab !== key);- if (selectedProjectFile === key) {- selectedProjectFile = remaining[Math.min(Math.max(index - 1, 0), remaining.length - 1)] ?? 'compose';+ if (selectedEditorFile === key) {+ selectedEditorFile = remaining[Math.min(Math.max(index - 1, 0), remaining.length - 1)] ?? 'compose';}}const validationState = $derived(@@ -183,7 +193,7 @@validate: () => validateTemplateEditorForm(validationState, form.validate),setLoading: (value) => (ui.saving = value),submit: ({ name, composeContent, envContent }) =>- projectService.createProject(name, composeContent, envContent, buildNewProjectFilePayload()),+ projectService.createProject(name, composeContent, envContent, buildNewProjectWorkspacePayload()),failureMessage: (name) => m.common_create_failed({ resource: `${m.resource_project()} "${name}"` }),onSuccess: async (project, { name }) => {toast.success(@@ -205,81 +215,91 @@hasEditorErrors: () => hasEditorErrors});- function ensureNewProjectFileUiState(relativePath: string) {- if (newProjectFileHasErrors[relativePath] === undefined) {- newProjectFileHasErrors = {- ...newProjectFileHasErrors,+ function ensureNewProjectWorkspaceUiState(relativePath: string) {+ if (newProjectWorkspaceHasErrors[relativePath] === undefined) {+ newProjectWorkspaceHasErrors = {+ ...newProjectWorkspaceHasErrors,[relativePath]: false};}- if (newProjectFileValidationReady[relativePath] === undefined) {- newProjectFileValidationReady = {- ...newProjectFileValidationReady,+ if (newProjectWorkspaceValidationReady[relativePath] === undefined) {+ newProjectWorkspaceValidationReady = {+ ...newProjectWorkspaceValidationReady,[relativePath]: true};}}- function createNewProjectFile(parentPath: string, name: string, content = '') {- const relativePath = planProjectFileCreate(newProjectFilePaths, parentPath, name);+ function createNewProjectWorkspaceFile(parentPath: string, name: string, content = '') {+ const relativePath = planProjectWorkspaceFileCreate(newProjectWorkspacePaths, parentPath, name);if (!relativePath) return;- newProjectFiles = [...newProjectFiles, { relativePath, isDirectory: false }];- newProjectFileContents = { ...newProjectFileContents, [relativePath]: content };- ensureNewProjectFileUiState(relativePath);- openProjectFileTab(`file:${relativePath}`);+ newProjectWorkspaceFiles = [...newProjectWorkspaceFiles, { relativePath, isDirectory: false }];+ newProjectWorkspaceContents = { ...newProjectWorkspaceContents, [relativePath]: content };+ ensureNewProjectWorkspaceUiState(relativePath);+ openEditorFileTab(`file:${relativePath}`);+ }++ async function uploadNewProjectWorkspaceFiles(parentPath: string, files: File[]): Promise<string | void> {+ const file = files[0];+ if (!file) return m.workspace_upload_file_required();+ const result = await readWorkspaceTextUpload(file, projectWorkspaceMaxFileSizeMb);+ if (result.error) return result.error;+ createNewProjectWorkspaceFile(parentPath, file.name, result.content ?? '');}function createNewProjectFolder(parentPath: string, name: string) {- const relativePath = planProjectFileCreate(newProjectFilePaths, parentPath, name);+ const relativePath = planProjectWorkspaceFileCreate(newProjectWorkspacePaths, parentPath, name);if (!relativePath) return;- newProjectFiles = [...newProjectFiles, { relativePath, isDirectory: true }];- selectedProjectFile = `file:${relativePath}`;+ newProjectWorkspaceFiles = [...newProjectWorkspaceFiles, { relativePath, isDirectory: true }];+ selectedEditorFile = `file:${relativePath}`;}- function applyNewProjectFilePathChange(oldPath: string, newPath: string) {- newProjectFiles = newProjectFiles.map((file) => ({+ function applyNewProjectWorkspacePathChange(oldPath: string, newPath: string) {+ newProjectWorkspaceFiles = newProjectWorkspaceFiles.map((file) => ({...file,- relativePath: remapProjectFilePath(file.relativePath, oldPath, newPath)+ relativePath: remapWorkspaceFilePath(file.relativePath, oldPath, newPath)}));- newProjectFileContents = remapProjectFileRecord(newProjectFileContents, oldPath, newPath);- newProjectFileHasErrors = remapProjectFileRecord(newProjectFileHasErrors, oldPath, newPath);- newProjectFileValidationReady = remapProjectFileRecord(newProjectFileValidationReady, oldPath, newPath);- openProjectTabs = openProjectTabs.map((tab) => remapSelectedProjectFileKey(tab, oldPath, newPath) ?? tab);- const remappedSelection = remapSelectedProjectFileKey(selectedProjectFile, oldPath, newPath);+ newProjectWorkspaceContents = remapWorkspaceFileRecord(newProjectWorkspaceContents, oldPath, newPath);+ newProjectWorkspaceHasErrors = remapWorkspaceFileRecord(newProjectWorkspaceHasErrors, oldPath, newPath);+ newProjectWorkspaceValidationReady = remapWorkspaceFileRecord(newProjectWorkspaceValidationReady, oldPath, newPath);+ openProjectTabs = openProjectTabs.map((tab) => remapSelectedWorkspaceFileKey(tab, oldPath, newPath) ?? tab);+ const remappedSelection = remapSelectedWorkspaceFileKey(selectedEditorFile, oldPath, newPath);if (remappedSelection) {- selectedProjectFile = remappedSelection;+ selectedEditorFile = remappedSelection;}}- function renameNewProjectFile(relativePath: string, newName: string) {- const plan = planProjectFileRename(newProjectFilePaths, relativePath, newName);+ function renameNewProjectWorkspaceFile(relativePath: string, newName: string) {+ const plan = planProjectWorkspaceFileRename(newProjectWorkspacePaths, relativePath, newName);if (!plan) return;- applyNewProjectFilePathChange(relativePath, plan.newPath);+ applyNewProjectWorkspacePathChange(relativePath, plan.newPath);}- function moveNewProjectFile(relativePath: string, newParentPath: string) {- const entry = newProjectFileEntries.find((file) => file.relativePath === relativePath);- const newPath = planProjectFileMove(entry, newProjectFilePaths, relativePath, newParentPath);+ function moveNewProjectWorkspaceFile(relativePath: string, newParentPath: string) {+ const entry = newProjectWorkspaceEntries.find((file) => file.relativePath === relativePath);+ const newPath = planProjectWorkspaceFileMove(entry, newProjectWorkspacePaths, relativePath, newParentPath);if (!newPath) return;- applyNewProjectFilePathChange(relativePath, newPath);+ applyNewProjectWorkspacePathChange(relativePath, newPath);}- function deleteNewProjectFile(relativePath: string) {- newProjectFiles = newProjectFiles.filter((file) => !projectFilePathMatches(file.relativePath, relativePath));- newProjectFileContents = removeProjectFileRecord(newProjectFileContents, relativePath);- newProjectFileHasErrors = removeProjectFileRecord(newProjectFileHasErrors, relativePath);- newProjectFileValidationReady = removeProjectFileRecord(newProjectFileValidationReady, relativePath);- openProjectTabs = openProjectTabs.filter((tab) => !isProjectFileSelectionUnder(tab, relativePath));- if (isProjectFileSelectionUnder(selectedProjectFile, relativePath)) {- selectedProjectFile = openTabs[0] ?? 'compose';+ function deleteNewProjectWorkspaceFile(relativePath: string) {+ newProjectWorkspaceFiles = newProjectWorkspaceFiles.filter(+ (file) => !workspaceFilePathMatches(file.relativePath, relativePath)+ );+ newProjectWorkspaceContents = removeWorkspaceFileRecord(newProjectWorkspaceContents, relativePath);+ newProjectWorkspaceHasErrors = removeWorkspaceFileRecord(newProjectWorkspaceHasErrors, relativePath);+ newProjectWorkspaceValidationReady = removeWorkspaceFileRecord(newProjectWorkspaceValidationReady, relativePath);+ openProjectTabs = openProjectTabs.filter((tab) => !isWorkspaceFileSelectionUnder(tab, relativePath));+ if (isWorkspaceFileSelectionUnder(selectedEditorFile, relativePath)) {+ selectedEditorFile = openTabs[0] ?? 'compose';}}- function buildNewProjectFilePayload(): ProjectFileDraft[] {- return newProjectFiles.map((file) => ({+ function buildNewProjectWorkspacePayload(): ProjectWorkspaceFileDraft[] {+ return newProjectWorkspaceFiles.map((file) => ({relativePath: file.relativePath,isDirectory: !!file.isDirectory,- content: file.isDirectory ? undefined : (newProjectFileContents[file.relativePath] ?? '')+ content: file.isDirectory ? undefined : (newProjectWorkspaceContents[file.relativePath] ?? '')}));}@@ -411,7 +431,7 @@aria-label={m.project_view_description()}onCheckedChange={(checked) => {layoutMode = checked ? 'tree' : 'classic';- openProjectFileTab('compose');+ openEditorFileTab('compose');}}/></div>@@ -427,17 +447,19 @@persistStorage="local">{#snippet first()}- <ProjectFileTreePanel- composeFileName="compose.yaml"- entries={newProjectFileEntries}- selectedFile={selectedProjectFile}+ <WorkspaceFileTreePanel+ leadingRows={newProjectWorkspaceLeadingRows}+ entries={newProjectWorkspaceEntries}+ selectedFile={selectedEditorFile}disabled={ui.saving || ui.isLoadingTemplateContent}- onSelect={openProjectFileTab}- onCreateFile={createNewProjectFile}+ onSelect={openEditorFileTab}+ onCreateFile={createNewProjectWorkspaceFile}onCreateFolder={createNewProjectFolder}- onRename={renameNewProjectFile}- onMove={moveNewProjectFile}- onDelete={deleteNewProjectFile}+ onUpload={uploadNewProjectWorkspaceFiles}+ validateName={(name, parentPath) => validateProjectWorkspaceFileName(name, parentPath)}+ onRename={renameNewProjectWorkspaceFile}+ onMove={moveNewProjectWorkspaceFile}+ onDelete={deleteNewProjectWorkspaceFile}/>{/snippet}@@ -446,8 +468,8 @@<EditorTabStriptabs={projectTabs}activeKey={activeProjectTab}- onSelect={openProjectFileTab}- onClose={closeProjectFileTab}+ onSelect={openEditorFileTab}+ onClose={closeEditorFileTab}>{#snippet actions()}<ComposeFileEditorPanel@@ -494,11 +516,11 @@variant="plain"open={true}title={relativePath}- language={projectFileLanguage(relativePath)}+ language={workspaceFileLanguage(relativePath)}validationMode="none"- bind:value={newProjectFileContents[relativePath]}- bind:hasErrors={newProjectFileHasErrors[relativePath]}- bind:validationReady={newProjectFileValidationReady[relativePath]}+ bind:value={newProjectWorkspaceContents[relativePath]}+ bind:hasErrors={newProjectWorkspaceHasErrors[relativePath]}+ bind:validationReady={newProjectWorkspaceValidationReady[relativePath]}fileId={`projects:new:file:${relativePath}`}originalValue=""enableDiff={true}diff --git a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelteindex 95eabe579..661eaf7a9 100644--- a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte+++ b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte@@ -6,8 +6,8 @@import * as Tabs from '#lib/components/ui/tabs';import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte';import { LayersIcon, DockIcon, JobsIcon, TrashIcon, EditIcon, FileTextIcon } from '#lib/icons';- import EditorTabStrip from '../../../projects/components/EditorTabStrip.svelte';- import ProjectFileTreePanel from '../../../projects/components/ProjectFileTreePanel.svelte';+ import EditorTabStrip from '#lib/components/editor-tab-strip.svelte';+ import WorkspaceFileTreePanel from '#lib/components/workspace-file-tree-panel.svelte';import ResizableSplit from '#lib/components/resizable-split.svelte';import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';import { m } from '#lib/paraglide/messages';@@ -47,6 +47,10 @@pending: false})));+ const sourceWorkspaceLeadingRows = [+ { key: 'compose', label: 'compose.yaml', iconClass: 'text-blue-500', locked: true },+ { key: 'env', label: '.env', iconClass: 'text-green-500', locked: true }+ ];function openSourceTab(key: string) {if (!openSourceTabs.includes(key)) {@@ -276,8 +280,8 @@persistKey={`arcane.swarm.split:${stackName}:source`}>{#snippet first()}- <ProjectFileTreePanel- composeFileName="compose.yaml"+ <WorkspaceFileTreePanel+ leadingRows={sourceWorkspaceLeadingRows}entries={[]}selectedFile={selectedSourceFile}onSelect={openSourceTab}diff --git a/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/new/+page.svelteindex b8f9970db..4e024b3ca 100644--- a/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte+++ b/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte@@ -10,10 +10,10 @@import ComposeCreateMenu from '#lib/components/compose-create-menu.svelte';import ComposeFileEditorPanel from '#lib/components/compose-file-editor-panel.svelte';import { ArrowLeftIcon, TrashIcon } from '#lib/icons';- import CodePanel from '../../../projects/components/CodePanel.svelte';+ import CodePanel from '#lib/components/code-panel.svelte';import EditableName from '../../../projects/components/EditableName.svelte';- import EditorTabStrip from '../../../projects/components/EditorTabStrip.svelte';- import ProjectFileTreePanel from '../../../projects/components/ProjectFileTreePanel.svelte';+ import EditorTabStrip from '#lib/components/editor-tab-strip.svelte';+ import WorkspaceFileTreePanel from '#lib/components/workspace-file-tree-panel.svelte';import ResizableSplit from '#lib/components/resizable-split.svelte';import { Checkbox } from '#lib/components/ui/checkbox';import { Label } from '#lib/components/ui/label';@@ -21,22 +21,25 @@import { environmentStore } from '#lib/stores/environment.store.svelte';import DockerRunConverterDialog from '#lib/components/compose/docker-run-converter-dialog.svelte';import { globalVariablesToMap } from '#lib/utils/template-load';- import type { ProjectFileDraft } from '#lib/types/project-files';+ import type { WorkspaceFileDraft } from '#lib/types/workspace';import type { SwarmSyncFile } from '#lib/types/swarm';import {- isProjectFileSelectionUnder,- planProjectFileCreate,- planProjectFileMove,- planProjectFileRename,- projectFileBasename,- projectFileLanguage,- projectFilePathMatches,- remapProjectFilePath,- remapProjectFileRecord,- remapSelectedProjectFileKey,- removeProjectFileRecord,- type ManagedProjectFileEntry- } from '../../../projects/components/project-file-tree-utils';+ isWorkspaceFileSelectionUnder,+ planWorkspaceFileCreate,+ planWorkspaceFileMove,+ planWorkspaceFileRename,+ readWorkspaceTextUpload,+ remapWorkspaceFilePath,+ remapWorkspaceFileRecord,+ remapSelectedWorkspaceFileKey,+ removeWorkspaceFileRecord,+ validateWorkspaceFileName,+ workspaceFileBasename,+ workspaceFileLanguage,+ workspaceFilePathMatches,+ type WorkspaceFileEntry+ } from '#lib/utils/workspace-files';+ import settingsStore from '#lib/stores/config-store';import {createComposeEditorSchema,createComposeTemplateDialogFlow,@@ -45,6 +48,7 @@} from '#lib/utils/compose-flow';let { data } = $props();+ const workspaceMaxFileSizeMb = $derived($settingsStore?.projectWorkspaceMaxFileSizeMb ?? 10);let ui = $state({saving: false,@@ -112,7 +116,7 @@return btoa(encoded);}- let stackFiles = $state<ProjectFileDraft[]>(+ let stackFiles = $state<WorkspaceFileDraft[]>(untrack(() => (data.sourceFiles ?? []).map((file) => ({ relativePath: file.relativePath, isDirectory: false }))));let stackFileContents = $state<Record<string, string>>(@@ -120,11 +124,11 @@Object.fromEntries((data.sourceFiles ?? []).map((file) => [file.relativePath, decodeStackFileContent(file.content)]))));- const stackFileEntries = $derived.by<ManagedProjectFileEntry[]>(() =>+ const stackFileEntries = $derived.by<WorkspaceFileEntry[]>(() =>stackFiles.map((file) => ({path: file.relativePath,relativePath: file.relativePath,- name: projectFileBasename(file.relativePath),+ name: workspaceFileBasename(file.relativePath),isDirectory: !!file.isDirectory,size: file.isDirectory ? 0 : (stackFileContents[file.relativePath]?.length ?? 0),content: file.isDirectory ? undefined : (stackFileContents[file.relativePath] ?? ''),@@ -132,6 +136,13 @@})));const stackFilePaths = $derived.by(() => new Set(stackFileEntries.map((file) => file.relativePath)));+ const stackWorkspaceLeadingRows = $derived.by(() => [+ { key: 'compose', label: 'compose.yaml', iconClass: 'text-blue-500', locked: true },+ ...(overrideActive+ ? [{ key: 'override', label: 'compose.override.yaml', iconClass: 'text-purple-500', locked: true }]+ : [{ key: 'add-override', label: m.compose_override_add(), action: true, onSelect: addOverride }]),+ { key: 'env', label: '.env', iconClass: 'text-green-500', locked: true }+ ]);let selectedStackFile = $state('compose');let openStackTabs = $state<string[]>(['compose']);@@ -161,7 +172,7 @@? 'compose.override.yaml': key === 'env'? '.env'- : projectFileBasename(key.slice(5)),+ : workspaceFileBasename(key.slice(5)),title:key === 'compose' ? 'compose.yaml' : key === 'override' ? 'compose.override.yaml' : key === 'env' ? '.env' : key.slice(5),iconClass:@@ -209,15 +220,23 @@}function createStackFile(parentPath: string, name: string, content = '') {- const relativePath = planProjectFileCreate(stackFilePaths, parentPath, name);+ const relativePath = planWorkspaceFileCreate(stackFilePaths, parentPath, name);if (!relativePath) return;stackFiles = [...stackFiles, { relativePath, isDirectory: false }];stackFileContents = { ...stackFileContents, [relativePath]: content };openStackTab(`file:${relativePath}`);}+ async function uploadStackFile(parentPath: string, files: File[]): Promise<string | void> {+ const file = files[0];+ if (!file) return m.workspace_upload_file_required();+ const result = await readWorkspaceTextUpload(file, workspaceMaxFileSizeMb);+ if (result.error) return result.error;+ createStackFile(parentPath, file.name, result.content ?? '');+ }+function createStackFolder(parentPath: string, name: string) {- const relativePath = planProjectFileCreate(stackFilePaths, parentPath, name);+ const relativePath = planWorkspaceFileCreate(stackFilePaths, parentPath, name);if (!relativePath) return;stackFiles = [...stackFiles, { relativePath, isDirectory: true }];selectedStackFile = `file:${relativePath}`;@@ -226,34 +245,34 @@function applyStackFilePathChange(oldPath: string, newPath: string) {stackFiles = stackFiles.map((file) => ({...file,- relativePath: remapProjectFilePath(file.relativePath, oldPath, newPath)+ relativePath: remapWorkspaceFilePath(file.relativePath, oldPath, newPath)}));- stackFileContents = remapProjectFileRecord(stackFileContents, oldPath, newPath);- openStackTabs = openStackTabs.map((tab) => remapSelectedProjectFileKey(tab, oldPath, newPath) ?? tab);- const remappedSelection = remapSelectedProjectFileKey(selectedStackFile, oldPath, newPath);+ stackFileContents = remapWorkspaceFileRecord(stackFileContents, oldPath, newPath);+ openStackTabs = openStackTabs.map((tab) => remapSelectedWorkspaceFileKey(tab, oldPath, newPath) ?? tab);+ const remappedSelection = remapSelectedWorkspaceFileKey(selectedStackFile, oldPath, newPath);if (remappedSelection) {selectedStackFile = remappedSelection;}}function renameStackFile(relativePath: string, newName: string) {- const plan = planProjectFileRename(stackFilePaths, relativePath, newName);+ const plan = planWorkspaceFileRename(stackFilePaths, relativePath, newName);if (!plan) return;applyStackFilePathChange(relativePath, plan.newPath);}function moveStackFile(relativePath: string, newParentPath: string) {const entry = stackFileEntries.find((file) => file.relativePath === relativePath);- const newPath = planProjectFileMove(entry, stackFilePaths, relativePath, newParentPath);+ const newPath = planWorkspaceFileMove(entry, stackFilePaths, relativePath, newParentPath);if (!newPath) return;applyStackFilePathChange(relativePath, newPath);}function deleteStackFile(relativePath: string) {- stackFiles = stackFiles.filter((file) => !projectFilePathMatches(file.relativePath, relativePath));- stackFileContents = removeProjectFileRecord(stackFileContents, relativePath);- openStackTabs = openStackTabs.filter((tab) => !isProjectFileSelectionUnder(tab, relativePath));- if (isProjectFileSelectionUnder(selectedStackFile, relativePath)) {+ stackFiles = stackFiles.filter((file) => !workspaceFilePathMatches(file.relativePath, relativePath));+ stackFileContents = removeWorkspaceFileRecord(stackFileContents, relativePath);+ openStackTabs = openStackTabs.filter((tab) => !isWorkspaceFileSelectionUnder(tab, relativePath));+ if (isWorkspaceFileSelectionUnder(selectedStackFile, relativePath)) {selectedStackFile = stackOpenTabs[0] ?? 'compose';}}@@ -465,17 +484,16 @@persistKey="arcane.swarm.split:new">{#snippet first()}- <ProjectFileTreePanel- composeFileName="compose.yaml"- overrideFileName="compose.override.yaml"- showOverride={overrideActive}- onAddOverride={addOverride}+ <WorkspaceFileTreePanel+ leadingRows={stackWorkspaceLeadingRows}entries={stackFileEntries}selectedFile={selectedStackFile}disabled={ui.saving || ui.isLoadingTemplateContent}onSelect={openStackTab}onCreateFile={createStackFile}onCreateFolder={createStackFolder}+ onUpload={uploadStackFile}+ validateName={(name) => validateWorkspaceFileName(name)}onRename={renameStackFile}onMove={moveStackFile}onDelete={deleteStackFile}@@ -555,7 +573,7 @@variant="plain"open={true}title={relativePath}- language={projectFileLanguage(relativePath)}+ language={workspaceFileLanguage(relativePath)}validationMode="none"bind:value={stackFileContents[relativePath]}fileId={`swarm:stacks:${isEditMode ? initialName : 'new'}:file:${relativePath}`}diff --git a/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte b/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelteindex 6bb2f6e19..fd2e47cdf 100644--- a/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte+++ b/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte@@ -1,6 +1,18 @@<script lang="ts">// fallow-ignore-file code-duplication -- useUrlTab initialization is the hook's intended per-page integration surface- import { VolumesIcon, ClockIcon, TagIcon, LayersIcon, GlobeIcon, ContainersIcon, BoxIcon } from '#lib/icons';+ import * as Card from '#lib/components/ui/card/index.js';+ import {+ VolumesIcon,+ ClockIcon,+ TagIcon,+ LayersIcon,+ InfoIcon,+ GlobeIcon,+ ContainersIcon,+ BoxIcon,+ FileTextIcon,+ AlertIcon+ } from '#lib/icons';import { goto } from '$app/navigation';import { Badge } from '#lib/components/ui/badge';import { formatDateTimeShort, truncateString } from '#lib/utils/formatting';@@ -12,9 +24,9 @@import { m } from '#lib/paraglide/messages';import { untrack } from 'svelte';import { volumeService } from '#lib/services/volume-service.js';+ import { volumeWorkspaceService } from '#lib/services/volume-workspace-service';import { type DetailAction } from '#lib/layouts';import TabbedPageLayout from '#lib/layouts/tabbed-page-layout.svelte';- import { VolumeBrowser } from '#lib/components/file-browser';import BackupList from '../components/volume-backup-table.svelte';import settingsStore from '#lib/stores/config-store';import { environmentStore } from '#lib/stores/environment.store.svelte';@@ -23,6 +35,39 @@import { DetailMetaStrip, DetailSection, KeyValueCard, KeyValueGrid } from '#lib/components/resource-detail';import InUseStatus from '#lib/components/arcane-table/cells/in-use-status.svelte';import { useUrlTab } from '#lib/hooks/use-url-tab.svelte';+ import { createQuery, useQueryClient } from '@tanstack/svelte-query';+ import { queryKeys } from '#lib/query/query-keys';+ import WorkspaceFileTreePanel from '#lib/components/workspace-file-tree-panel.svelte';+ import EditorTabStrip from '#lib/components/editor-tab-strip.svelte';+ import CodePanel from '#lib/components/code-panel.svelte';+ import ResizableSplit from '#lib/components/resizable-split.svelte';+ import { composeTreeSplitProps } from '#lib/utils/compose-flow';+ import type { VolumeWorkspaceFileChange, VolumeWorkspaceFileContent } from '#lib/types/volume-workspace';+ import {+ applyWorkspaceFileChangesForDisplay,+ buildWorkspaceMultipartUpdate,+ isWorkspaceFileSelectionUnder,+ joinWorkspaceFilePath,+ remapSelectedWorkspaceFileKey,+ remapWorkspaceFileRecord,+ removeWorkspaceFileRecord,+ readWorkspaceTextUpload,+ validateWorkspaceFileName,+ workspaceFileBasename,+ workspaceFileLanguage,+ workspaceFileParentPath,+ workspaceFilePathMatches+ } from '#lib/utils/workspace-files';+ import { volumeBackupService } from '#lib/services/volume-backup-service';+ import type { BackupEntry } from '#lib/types/shared';+ import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog';+ import * as Select from '#lib/components/ui/select';+ import { Label } from '#lib/components/ui/label';+ import * as Alert from '#lib/components/ui/alert';+ import { Spinner } from '#lib/components/ui/spinner';+ import { bytes } from '#lib/utils/formatting';+ import { PersistedState } from 'runed';+ import { volumeWorkspaceReadOnlyMessage } from '../components/volume-workspace-utils';let { data } = $props();let volume = $state(untrack(() => data.volume));@@ -33,13 +78,17 @@const currentEnvId = $derived(environmentStore.selected?.id || '0');const canDeleteVolume = $derived(hasPermission('volumes:delete', currentEnvId));+ const canReadVolume = $derived(hasPermission('volumes:read', currentEnvId));+ const canUploadVolume = $derived(hasPermission('volumes:upload', currentEnvId));+ const canBackupVolume = $derived(hasPermission('volumes:backup', currentEnvId));+ const volumeWorkspaceMaxFileSizeMb = $derived($settingsStore?.volumeWorkspaceMaxFileSizeMb ?? 10);- let isLoading = $state({ remove: false });+ let isLoading = $state({ remove: false, save: false });const createdDate = $derived(volume.createdAt ? formatDateTimeShort(volume.createdAt) : m.common_unknown());const tabItems = $derived([{ value: 'overview', label: m.common_overview() },- { value: 'browser', label: m.volumes_nav_browser() },+ { value: 'workspace', label: m.workspace() },{ value: 'backups', label: m.volumes_nav_backups() }]);const urlTab = useUrlTab({@@ -47,6 +96,492 @@defaultTab: () => 'overview'});const selectedTab = $derived(urlTab.value);+ const queryClient = useQueryClient();++ let workspaceRequested = $state(false);+ let workspaceFileChanges = $state<VolumeWorkspaceFileChange[]>([]);+ let workspaceFileContents = $state<Record<string, string>>({});+ let loadedWorkspaceFileContents = $state<Record<string, string>>({});+ let workspaceFileMetadata = $state<Record<string, VolumeWorkspaceFileContent>>({});+ let workspaceFileLoadErrors = $state<Record<string, string>>({});+ let workspaceFileLoading = $state<Record<string, boolean>>({});+ let workspaceRestoreRecords = $state<Record<string, true>>({});+ let selectedWorkspaceFile = $state('');+ let openWorkspaceTabs = $state<string[]>([]);+ let workspaceTreePaneWidth = $state(420);+ type VolumeWorkspaceUIPrefs = { selectedFile: string; openTabs: string[] };+ let workspacePrefs: PersistedState<VolumeWorkspaceUIPrefs> | null = null;+ let lastWorkspacePrefsKey = $state('');++ let showWorkspaceRestore = $state(false);+ let workspaceRestorePath = $state('');+ let workspaceBackups = $state<BackupEntry[]>([]);+ let selectedWorkspaceBackupId = $state('');+ let loadingWorkspaceBackups = $state(false);+ let checkingWorkspaceBackup = $state(false);+ let workspaceBackupHasPath = $state<boolean | null>(null);+ let lastWorkspaceBackupCheck = '';++ const workspaceQuery = createQuery(() => ({+ queryKey: queryKeys.volumes.workspace(currentEnvId, volume.name),+ queryFn: () => volumeWorkspaceService.getWorkspace(volume.name, currentEnvId),+ enabled: workspaceRequested && canReadVolume,+ refetchOnMount: false+ }));++ const visibleWorkspaceFiles = $derived.by(() =>+ applyWorkspaceFileChangesForDisplay(workspaceQuery.data?.files ?? [], workspaceFileChanges).map((file) => {+ const modeType = file.mode?.[0];+ const metadata = workspaceFileMetadata[file.relativePath];+ const editable = metadata?.editable ?? file.editable;+ return {+ ...file,+ editable,+ readOnlyReason: metadata?.readOnlyReason ?? file.readOnlyReason,+ locked:+ !file.isDirectory &&+ (editable === false || file.isSymlink === true || (!!modeType && modeType !== '-' && modeType !== 'd'))+ };+ })+ );+ const workspaceFilePaths = $derived.by(() => new Set(visibleWorkspaceFiles.map((file) => file.relativePath)));+ const changedWorkspaceTextPaths = $derived.by(() =>+ Object.keys(workspaceFileContents).filter(+ (relativePath) => workspaceFileContents[relativePath] !== loadedWorkspaceFileContents[relativePath]+ )+ );+ const hasWorkspaceChanges = $derived(workspaceFileChanges.length > 0 || changedWorkspaceTextPaths.length > 0);+ const canSaveWorkspace = $derived(+ hasWorkspaceChanges &&+ !isLoading.save &&+ workspaceFileChanges.every((change) => {+ switch (change.operation) {+ case 'create_file':+ case 'create_folder':+ case 'update_file':+ return canUploadVolume;+ case 'rename':+ case 'move':+ return canUploadVolume && canDeleteVolume;+ case 'delete':+ return canDeleteVolume;+ case 'restore_file':+ return canBackupVolume;+ }+ }) &&+ (changedWorkspaceTextPaths.length === 0 || canUploadVolume)+ );+ const validWorkspaceTabs = $derived(+ openWorkspaceTabs.filter((key) => {+ if (!key.startsWith('file:')) return false;+ const entry = visibleWorkspaceFiles.find((file) => file.relativePath === key.slice(5));+ return !!entry && !entry.isDirectory;+ })+ );+ const activeWorkspaceTab = $derived(+ validWorkspaceTabs.includes(selectedWorkspaceFile) ? selectedWorkspaceFile : (validWorkspaceTabs[0] ?? '')+ );+ const workspaceTabs = $derived(+ validWorkspaceTabs.map((key) => {+ const relativePath = key.slice(5);+ return {+ key,+ label: workspaceFileBasename(relativePath),+ title: relativePath,+ iconClass: 'text-muted-foreground',+ pending:+ changedWorkspaceTextPaths.includes(relativePath) ||+ visibleWorkspaceFiles.find((file) => file.relativePath === relativePath)?.pending === true+ };+ })+ );+ const selectedWorkspaceEntry = $derived.by(() => {+ if (!activeWorkspaceTab.startsWith('file:')) return undefined;+ return visibleWorkspaceFiles.find((file) => file.relativePath === activeWorkspaceTab.slice(5));+ });+ const selectedWorkspaceMetadata = $derived(+ activeWorkspaceTab.startsWith('file:') ? workspaceFileMetadata[activeWorkspaceTab.slice(5)] : undefined+ );++ $effect(() => {+ if (selectedTab === 'workspace') workspaceRequested = true;+ });++ $effect(() => {+ const key = `arcane.volume.workspace.ui:${currentEnvId}:${volume.name}`;+ if (lastWorkspacePrefsKey === key) return;+ lastWorkspacePrefsKey = key;+ workspacePrefs = new PersistedState<VolumeWorkspaceUIPrefs>(+ key,+ { selectedFile: '', openTabs: [] },+ {+ storage: 'session',+ syncTabs: false+ }+ );+ selectedWorkspaceFile = workspacePrefs.current.selectedFile;+ openWorkspaceTabs = workspacePrefs.current.openTabs;+ });++ function persistWorkspacePrefs() {+ if (!workspacePrefs) return;+ workspacePrefs.current = { selectedFile: selectedWorkspaceFile, openTabs: openWorkspaceTabs };+ }++ function workspaceReadOnlyMessage(reason?: string): string {+ return volumeWorkspaceReadOnlyMessage(reason as VolumeWorkspaceFileContent['readOnlyReason'], volumeWorkspaceMaxFileSizeMb);+ }++ function closeWorkspaceTab(key: string) {+ const index = validWorkspaceTabs.indexOf(key);+ const remaining = validWorkspaceTabs.filter((tab) => tab !== key);+ openWorkspaceTabs = openWorkspaceTabs.filter((tab) => tab !== key);+ if (selectedWorkspaceFile === key) {+ selectedWorkspaceFile = remaining[Math.min(Math.max(index - 1, 0), remaining.length - 1)] ?? '';+ }+ persistWorkspacePrefs();+ }++ function openWorkspaceFile(key: string) {+ const relativePath = key.startsWith('file:') ? key.slice(5) : '';+ const entry = visibleWorkspaceFiles.find((file) => file.relativePath === relativePath);+ if (!entry) return;+ if (entry.isDirectory) {+ selectedWorkspaceFile = key;+ persistWorkspacePrefs();+ return;+ }+ if (!openWorkspaceTabs.includes(key)) openWorkspaceTabs = [...openWorkspaceTabs, key];+ selectedWorkspaceFile = key;+ persistWorkspacePrefs();+ }++ async function loadWorkspaceFile(relativePath: string) {+ if (!relativePath || workspaceFileMetadata[relativePath] || workspaceFileLoading[relativePath]) return;+ const entry = visibleWorkspaceFiles.find((file) => file.relativePath === relativePath);+ if (!entry || entry.isDirectory) return;+ if (workspaceRestoreRecords[relativePath]) {+ workspaceFileMetadata = {+ ...workspaceFileMetadata,+ [relativePath]: {+ path: entry.path,+ relativePath,+ name: entry.name,+ size: entry.size,+ mimeType: '',+ editable: false,+ readOnlyReason: 'restore_pending'+ }+ };+ return;+ }+ if (entry.isSymlink) {+ workspaceFileMetadata = {+ ...workspaceFileMetadata,+ [relativePath]: {+ path: entry.path,+ relativePath,+ name: entry.name,+ size: entry.size,+ mimeType: '',+ editable: false,+ readOnlyReason: 'symlink'+ }+ };+ return;+ }++ workspaceFileLoading = { ...workspaceFileLoading, [relativePath]: true };+ workspaceFileLoadErrors = removeWorkspaceFileRecord(workspaceFileLoadErrors, relativePath);+ try {+ const file = await volumeWorkspaceService.getWorkspaceFile(volume.name, relativePath, currentEnvId);+ workspaceFileMetadata = { ...workspaceFileMetadata, [relativePath]: file };+ if (file.editable) {+ const content = file.content ?? '';+ loadedWorkspaceFileContents = { ...loadedWorkspaceFileContents, [relativePath]: content };+ if (workspaceFileContents[relativePath] === undefined) {+ workspaceFileContents = { ...workspaceFileContents, [relativePath]: content };+ }+ }+ } catch (error) {+ workspaceFileLoadErrors = {+ ...workspaceFileLoadErrors,+ [relativePath]: error instanceof Error ? error.message : String(error)+ };+ } finally {+ workspaceFileLoading = removeWorkspaceFileRecord(workspaceFileLoading, relativePath);+ }+ }++ $effect(() => {+ if (!activeWorkspaceTab.startsWith('file:')) return;+ const relativePath = activeWorkspaceTab.slice(5);+ if (!workspaceFileMetadata[relativePath] && !workspaceFileLoadErrors[relativePath]) void loadWorkspaceFile(relativePath);+ });++ function createVolumeWorkspaceFile(parentPath: string, name: string) {+ const normalizedName = validateWorkspaceFileName(name);+ if (!normalizedName) return;+ const relativePath = joinWorkspaceFilePath(parentPath, normalizedName);+ if (workspaceFilePaths.has(relativePath)) {+ toast.error(m.workspace_file_duplicate_name());+ return;+ }+ workspaceFileChanges = [...workspaceFileChanges, { operation: 'create_file', relativePath }];+ workspaceFileContents = { ...workspaceFileContents, [relativePath]: '' };+ loadedWorkspaceFileContents = { ...loadedWorkspaceFileContents, [relativePath]: '' };+ workspaceFileMetadata = {+ ...workspaceFileMetadata,+ [relativePath]: {+ path: `/${relativePath}`,+ relativePath,+ name: normalizedName,+ size: 0,+ mimeType: 'text/plain',+ content: '',+ editable: true+ }+ };+ openWorkspaceFile(`file:${relativePath}`);+ }++ function createVolumeWorkspaceFolder(parentPath: string, name: string) {+ const normalizedName = validateWorkspaceFileName(name);+ if (!normalizedName) return;+ const relativePath = joinWorkspaceFilePath(parentPath, normalizedName);+ if (workspaceFilePaths.has(relativePath)) {+ toast.error(m.workspace_file_duplicate_name());+ return;+ }+ workspaceFileChanges = [...workspaceFileChanges, { operation: 'create_folder', relativePath }];+ selectedWorkspaceFile = `file:${relativePath}`;+ persistWorkspacePrefs();+ }++ function remapVolumeWorkspaceState(oldPath: string, newPath: string) {+ workspaceFileContents = remapWorkspaceFileRecord(workspaceFileContents, oldPath, newPath);+ loadedWorkspaceFileContents = remapWorkspaceFileRecord(loadedWorkspaceFileContents, oldPath, newPath);+ workspaceFileMetadata = remapWorkspaceFileRecord(workspaceFileMetadata, oldPath, newPath);+ workspaceFileLoadErrors = remapWorkspaceFileRecord(workspaceFileLoadErrors, oldPath, newPath);+ workspaceFileLoading = remapWorkspaceFileRecord(workspaceFileLoading, oldPath, newPath);+ workspaceRestoreRecords = remapWorkspaceFileRecord(workspaceRestoreRecords, oldPath, newPath);+ openWorkspaceTabs = openWorkspaceTabs.map((tab) => remapSelectedWorkspaceFileKey(tab, oldPath, newPath) ?? tab);+ const remappedSelection = remapSelectedWorkspaceFileKey(selectedWorkspaceFile, oldPath, newPath);+ if (remappedSelection) selectedWorkspaceFile = remappedSelection;+ persistWorkspacePrefs();+ }++ function renameVolumeWorkspaceFile(relativePath: string, newName: string) {+ const normalizedName = validateWorkspaceFileName(newName);+ if (!normalizedName) return;+ const newPath = joinWorkspaceFilePath(workspaceFileParentPath(relativePath), normalizedName);+ if (newPath !== relativePath && workspaceFilePaths.has(newPath)) {+ toast.error(m.workspace_file_duplicate_name());+ return;+ }+ workspaceFileChanges = [...workspaceFileChanges, { operation: 'rename', relativePath, newName: normalizedName }];+ remapVolumeWorkspaceState(relativePath, newPath);+ }++ function moveVolumeWorkspaceFile(relativePath: string, newParentPath: string) {+ const entry = visibleWorkspaceFiles.find((file) => file.relativePath === relativePath);+ if (!entry || newParentPath === workspaceFileParentPath(relativePath)) return;+ if (entry.isDirectory && newParentPath && workspaceFilePathMatches(newParentPath, relativePath)) {+ toast.error(m.workspace_file_invalid_move_destination());+ return;+ }+ const newPath = joinWorkspaceFilePath(newParentPath, workspaceFileBasename(relativePath));+ if (workspaceFilePaths.has(newPath)) {+ toast.error(m.workspace_file_duplicate_name());+ return;+ }+ workspaceFileChanges = [...workspaceFileChanges, { operation: 'move', relativePath, newParentPath }];+ remapVolumeWorkspaceState(relativePath, newPath);+ }++ function removeVolumeWorkspaceState(relativePath: string) {+ workspaceFileContents = removeWorkspaceFileRecord(workspaceFileContents, relativePath);+ loadedWorkspaceFileContents = removeWorkspaceFileRecord(loadedWorkspaceFileContents, relativePath);+ workspaceFileMetadata = removeWorkspaceFileRecord(workspaceFileMetadata, relativePath);+ workspaceFileLoadErrors = removeWorkspaceFileRecord(workspaceFileLoadErrors, relativePath);+ workspaceFileLoading = removeWorkspaceFileRecord(workspaceFileLoading, relativePath);+ workspaceRestoreRecords = removeWorkspaceFileRecord(workspaceRestoreRecords, relativePath);+ openWorkspaceTabs = openWorkspaceTabs.filter((tab) => !isWorkspaceFileSelectionUnder(tab, relativePath));+ if (isWorkspaceFileSelectionUnder(selectedWorkspaceFile, relativePath)) selectedWorkspaceFile = openWorkspaceTabs[0] ?? '';+ persistWorkspacePrefs();+ }++ function deleteVolumeWorkspaceFile(relativePath: string) {+ const entry = visibleWorkspaceFiles.find((file) => file.relativePath === relativePath);+ if (!entry) return;+ workspaceFileChanges = [...workspaceFileChanges, { operation: 'delete', relativePath, recursive: entry.isDirectory }];+ removeVolumeWorkspaceState(relativePath);+ }++ async function stageVolumeUpload(parentPath: string, file: File, overwrite: boolean) {+ const relativePath = joinWorkspaceFilePath(parentPath, file.name);+ const existing = visibleWorkspaceFiles.find((entry) => entry.relativePath === relativePath);+ if (existing?.isDirectory) return;+ const upload = await readWorkspaceTextUpload(file, volumeWorkspaceMaxFileSizeMb);+ if (upload.error) return upload.error;+ const uploadedText = upload.content ?? '';+ workspaceFileChanges = [...workspaceFileChanges, { operation: overwrite ? 'update_file' : 'create_file', relativePath }];+ workspaceFileMetadata = {+ ...workspaceFileMetadata,+ [relativePath]: {+ path: `/${relativePath}`,+ relativePath,+ name: file.name,+ size: file.size,+ mimeType: file.type || 'application/octet-stream',+ editable: true+ }+ };+ workspaceFileContents = { ...workspaceFileContents, [relativePath]: uploadedText };+ if (loadedWorkspaceFileContents[relativePath] === undefined) {+ loadedWorkspaceFileContents = { ...loadedWorkspaceFileContents, [relativePath]: '' };+ }+ openWorkspaceFile(`file:${relativePath}`);+ }++ async function uploadVolumeWorkspaceFiles(parentPath: string, files: File[]): Promise<string | void> {+ const invalidFile = files.find((file) => !validateWorkspaceFileName(file.name));+ if (invalidFile) return m.workspace_file_invalid_name();+ if (new Set(files.map((file) => file.name)).size !== files.length) return m.workspace_file_duplicate_name();+ const directoryCollision = files.find((file) =>+ visibleWorkspaceFiles.some(+ (entry) => entry.relativePath === joinWorkspaceFilePath(parentPath, file.name) && entry.isDirectory+ )+ );+ if (directoryCollision) return m.workspace_file_duplicate_name();++ const collisions = files.filter((file) => workspaceFilePaths.has(joinWorkspaceFilePath(parentPath, file.name)));+ for (const file of files.filter((candidate) => !collisions.includes(candidate))) {+ const error = await stageVolumeUpload(parentPath, file, false);+ if (error) return error;+ }+ if (collisions.length > 0) {+ openConfirmDialog({+ title: m.volumes_workspace_upload_collision_title(),+ message: m.volumes_workspace_upload_collision_message({+ paths: collisions.map((file) => joinWorkspaceFilePath(parentPath, file.name)).join('\n')+ }),+ confirm: {+ label: m.upload(),+ action: async () => {+ for (const file of collisions) {+ const error = await stageVolumeUpload(parentPath, file, true);+ if (error) toast.error(error);+ }+ }+ }+ });+ }+ }++ function clearVolumeWorkspaceDrafts() {+ workspaceFileChanges = [];+ workspaceFileContents = {};+ loadedWorkspaceFileContents = {};+ workspaceFileMetadata = {};+ workspaceFileLoadErrors = {};+ workspaceFileLoading = {};+ workspaceRestoreRecords = {};+ }++ async function handleSaveVolumeWorkspace() {+ if (!workspaceQuery.data || !canSaveWorkspace) return;+ const update = buildWorkspaceMultipartUpdate(workspaceFileChanges, workspaceFileContents, loadedWorkspaceFileContents);+ handleApiResultWithCallbacks({+ result: await tryCatch(+ volumeWorkspaceService.updateWorkspace(+ volume.name,+ {+ fileTreeRevision: workspaceQuery.data.fileTreeRevision,+ fileChanges: update.fileChanges+ },+ update.files,+ currentEnvId+ )+ ),+ message: m.common_save_failed(),+ setLoadingState: (value) => (isLoading.save = value),+ onSuccess: async (workspace) => {+ queryClient.setQueryData(queryKeys.volumes.workspace(currentEnvId, volume.name), workspace);+ clearVolumeWorkspaceDrafts();+ toast.success(m.volumes_workspace_save_success(), activityToastOptions(workspace.activityId));+ }+ });+ }++ async function openWorkspaceRestoreDialog(relativePath: string) {+ workspaceRestorePath = relativePath;+ workspaceBackups = [];+ selectedWorkspaceBackupId = '';+ workspaceBackupHasPath = null;+ lastWorkspaceBackupCheck = '';+ showWorkspaceRestore = true;+ loadingWorkspaceBackups = true;+ try {+ const response = await volumeBackupService.listBackups(volume.name, { pagination: { page: 1, limit: 100 } });+ workspaceBackups = response.data;+ selectedWorkspaceBackupId = response.data[0]?.id ?? '';+ } catch (error) {+ toast.error(error instanceof Error ? error.message : m.common_failed());+ } finally {+ loadingWorkspaceBackups = false;+ }+ }++ async function checkWorkspaceBackupPath(backupId: string, relativePath: string) {+ const key = `${backupId}:${relativePath}`;+ if (!backupId || !relativePath || key === lastWorkspaceBackupCheck) return;+ lastWorkspaceBackupCheck = key;+ checkingWorkspaceBackup = true;+ workspaceBackupHasPath = null;+ try {+ workspaceBackupHasPath = await volumeBackupService.backupHasPath(backupId, `/${relativePath}`);+ } catch (error) {+ workspaceBackupHasPath = null;+ toast.error(error instanceof Error ? error.message : m.common_failed());+ } finally {+ checkingWorkspaceBackup = false;+ }+ }++ $effect(() => {+ if (showWorkspaceRestore && selectedWorkspaceBackupId && workspaceRestorePath) {+ void checkWorkspaceBackupPath(selectedWorkspaceBackupId, workspaceRestorePath);+ }+ });++ function stageWorkspaceRestore() {+ if (!workspaceRestorePath || !selectedWorkspaceBackupId || workspaceBackupHasPath !== true) return;+ workspaceFileChanges = [+ ...workspaceFileChanges,+ {+ operation: 'restore_file',+ relativePath: workspaceRestorePath,+ backupId: selectedWorkspaceBackupId+ }+ ];+ removeVolumeWorkspaceState(workspaceRestorePath);+ workspaceRestoreRecords = { ...workspaceRestoreRecords, [workspaceRestorePath]: true };+ showWorkspaceRestore = false;+ toast.success(m.volumes_workspace_restore_staged());+ }++ function formatWorkspaceBackupLabel(backup: BackupEntry): string {+ return `${backup.id} · ${bytes.format(backup.size, { unitSeparator: ' ' }) ?? '-'}`;+ }++ async function downloadVolumeWorkspaceFile(relativePath: string) {+ try {+ await volumeWorkspaceService.downloadWorkspaceFile(volume.name, relativePath, currentEnvId);+ } catch (error) {+ toast.error(error instanceof Error ? error.message : m.common_download_error());+ }+ }async function handleRemoveVolumeConfirm(volumeName: string) {const safeName = volumeName?.trim() || m.common_unknown();@@ -76,20 +611,30 @@});}- const actions: DetailAction[] = $derived(- canDeleteVolume- ? [- {- id: 'remove',- action: 'remove' as const,- label: m.common_remove(),- loading: isLoading.remove,- disabled: isLoading.remove || isBackupVolume,- onclick: () => handleRemoveVolumeConfirm(volume.name)- }- ]- : []- );+ const actions: DetailAction[] = $derived.by(() => {+ const items: DetailAction[] = [];+ if (hasWorkspaceChanges) {+ items.push({+ id: 'save-workspace',+ action: 'save',+ label: m.common_save_changes(),+ loading: isLoading.save,+ disabled: !canSaveWorkspace,+ onclick: handleSaveVolumeWorkspace+ });+ }+ if (canDeleteVolume) {+ items.push({+ id: 'remove',+ action: 'remove',+ label: m.common_remove(),+ loading: isLoading.remove,+ disabled: isLoading.remove || isBackupVolume,+ onclick: () => handleRemoveVolumeConfirm(volume.name)+ });+ }+ return items;+ });function onTabChange(value: string) {urlTab.select(value);@@ -199,8 +744,134 @@{#if (!volume.labels || Object.keys(volume.labels).length === 0) && (!volume.options || Object.keys(volume.options).length === 0)}<p class="border-t pt-6 text-center text-muted-foreground">{m.volumes_no_labels_or_options()}</p>{/if}- {:else if tab === 'browser'}- <VolumeBrowser volumeName={volume.name} />+ {:else if tab === 'workspace'}+ {#if !canReadVolume}+ <div class="flex min-h-96 items-center justify-center rounded-lg border text-sm text-muted-foreground">+ {m.common_access_denied()}+ </div>+ {:else if workspaceQuery.isPending}+ <div class="flex min-h-96 items-center justify-center rounded-lg border text-muted-foreground">+ <Spinner class="size-6" />+ </div>+ {:else if workspaceQuery.error}+ <div class="flex min-h-96 items-center justify-center rounded-lg border px-4 text-sm text-destructive">+ {workspaceQuery.error instanceof Error ? workspaceQuery.error.message : m.common_failed()}+ </div>+ {:else}+ <div class="space-y-3">+ {#if workspaceQuery.data?.fileTreeTruncated}+ <Alert.Root>+ <AlertIcon class="size-4" />+ <Alert.Description>{m.volumes_workspace_truncated()}</Alert.Description>+ </Alert.Root>+ {/if}+ <div+ class="flex h-[calc(100vh-15rem)] min-h-[32rem] flex-col overflow-hidden rounded-lg border border-border bg-card"+ >+ <ResizableSplit+ class="h-full min-h-0 flex-1"+ {...composeTreeSplitProps}+ bind:size={workspaceTreePaneWidth}+ ariaLabel={m.compose_editor_resize_files_panel()}+ persistKey={`arcane.volume.workspace.split:${currentEnvId}:${volume.name}`}+ >+ {#snippet first()}+ <WorkspaceFileTreePanel+ title={m.volumes_workspace_files()}+ leadingRows={[]}+ entries={visibleWorkspaceFiles}+ selectedFile={selectedWorkspaceFile}+ disabled={isLoading.save}+ emptyMessage={m.volumes_workspace_files_empty()}+ uploadDescription={m.volumes_workspace_upload_description()}+ rootDestinationLabel={m.volumes_workspace_root_destination()}+ rootPathMessage={m.volumes_workspace_root_path()}+ deleteConfirmMessage={(name) => m.volumes_workspace_delete_confirm({ name })}+ lockedLabel={m.volumes_workspace_locked_file()}+ onSelect={openWorkspaceFile}+ onCreateFile={canUploadVolume ? createVolumeWorkspaceFile : undefined}+ onCreateFolder={canUploadVolume ? createVolumeWorkspaceFolder : undefined}+ onUpload={canUploadVolume ? uploadVolumeWorkspaceFiles : undefined}+ multipleUploads={true}+ allowUploadOverwrite={true}+ validateName={validateWorkspaceFileName}+ onRename={canUploadVolume && canDeleteVolume ? renameVolumeWorkspaceFile : undefined}+ onMove={canUploadVolume && canDeleteVolume ? moveVolumeWorkspaceFile : undefined}+ onDelete={canDeleteVolume ? deleteVolumeWorkspaceFile : undefined}+ onDownload={downloadVolumeWorkspaceFile}+ onRestore={canBackupVolume ? openWorkspaceRestoreDialog : undefined}+ />+ {/snippet}++ {#snippet second()}+ <div class="flex h-full min-h-0 flex-1 flex-col">+ {#if workspaceTabs.length > 0}+ <EditorTabStrip+ tabs={workspaceTabs}+ activeKey={activeWorkspaceTab}+ onSelect={openWorkspaceFile}+ onClose={closeWorkspaceTab}+ />+ {/if}+ <div class="flex min-h-0 flex-1 flex-col">+ {#if !activeWorkspaceTab}+ <div class="flex h-full items-center justify-center px-4 text-sm text-muted-foreground">+ {m.volumes_workspace_select_file()}+ </div>+ {:else}+ {@const relativePath = activeWorkspaceTab.slice(5)}+ {#if workspaceFileLoadErrors[relativePath]}+ <div class="flex h-full items-center justify-center px-4 text-sm text-destructive">+ {workspaceFileLoadErrors[relativePath]}+ </div>+ {:else if workspaceFileLoading[relativePath] || !selectedWorkspaceMetadata}+ <div class="flex h-full items-center justify-center text-muted-foreground">+ <Spinner class="size-5" />+ </div>+ {:else if selectedWorkspaceMetadata.editable && workspaceFileContents[relativePath] !== undefined}+ <CodePanel+ variant="plain"+ open={true}+ title={relativePath}+ language={workspaceFileLanguage(relativePath)}+ validationMode="none"+ bind:value={workspaceFileContents[relativePath]}+ readOnly={!canUploadVolume}+ fileId={`volume:${currentEnvId}:${volume.name}:${relativePath}`}+ originalValue={loadedWorkspaceFileContents[relativePath] ?? ''}+ enableDiff={true}+ />+ {:else}+ <div class="flex h-full items-center justify-center p-6">+ <Card.Root class="w-full max-w-xl">+ <Card.Header icon={FileTextIcon}>+ <div class="min-w-0">+ <Card.Title>{workspaceFileBasename(relativePath)}</Card.Title>+ <Card.Description+ >{workspaceReadOnlyMessage(selectedWorkspaceMetadata.readOnlyReason)}</Card.Description+ >+ </div>+ </Card.Header>+ <Card.Content class="space-y-2 text-sm text-muted-foreground">+ <p>{m.common_size()}: {bytes.format(selectedWorkspaceMetadata.size, { unitSeparator: ' ' })}</p>+ {#if selectedWorkspaceMetadata.mimeType}<p>+ {m.common_type()}: {selectedWorkspaceMetadata.mimeType}+ </p>{/if}+ {#if selectedWorkspaceEntry?.linkTarget}<p>+ {m.volumes_symlink_target_tooltip({ target: selectedWorkspaceEntry.linkTarget })}+ </p>{/if}+ </Card.Content>+ </Card.Root>+ </div>+ {/if}+ {/if}+ </div>+ </div>+ {/snippet}+ </ResizableSplit>+ </div>+ </div>+ {/if}{:else if tab === 'backups'}<BackupList volumeName={volume.name} />{/if}@@ -225,3 +896,75 @@/></div>{/if}++<ResponsiveDialog+ open={showWorkspaceRestore}+ onOpenChange={(open) => (showWorkspaceRestore = open)}+ title={m.volumes_workspace_restore()}+ description={m.volumes_workspace_backup_restore_desc()}+ contentClass="sm:max-w-[520px]"+>+ {#snippet children()}+ <div class="space-y-4 py-2">+ <Alert.Root class="py-2 [&>svg]:top-2">+ <InfoIcon class="size-4" />+ <Alert.Description class="text-xs">{m.volumes_backup_safety_info()}</Alert.Description>+ </Alert.Root>+ {#if workspaceRestorePath}+ <code class="block rounded bg-muted/40 px-2 py-1 font-mono text-xs break-all">/{workspaceRestorePath}</code>+ {/if}+ {#if loadingWorkspaceBackups}+ <div class="flex items-center gap-2 text-sm text-muted-foreground">+ <Spinner class="size-4" />+ {m.common_loading()}+ </div>+ {:else if workspaceBackups.length === 0}+ <div class="text-sm text-muted-foreground">{m.volumes_workspace_no_backups()}</div>+ {:else}+ <div class="space-y-2">+ <Label for="workspace-restore-backup">{m.volumes_workspace_backup()}</Label>+ <Select.Root+ type="single"+ value={selectedWorkspaceBackupId}+ onValueChange={(value) => {+ selectedWorkspaceBackupId = value;+ workspaceBackupHasPath = null;+ lastWorkspaceBackupCheck = '';+ }}+ >+ <Select.Trigger id="workspace-restore-backup" class="h-10 w-full overflow-hidden">+ <span class="min-w-0 flex-1 truncate">+ {workspaceBackups.find((backup) => backup.id === selectedWorkspaceBackupId)+ ? formatWorkspaceBackupLabel(workspaceBackups.find((backup) => backup.id === selectedWorkspaceBackupId)!)+ : m.volumes_workspace_backup()}+ </span>+ </Select.Trigger>+ <Select.Content>+ {#each workspaceBackups as backup (backup.id)}+ <Select.Item value={backup.id}>{formatWorkspaceBackupLabel(backup)}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ {#if checkingWorkspaceBackup}+ <div class="flex items-center gap-2 text-xs text-muted-foreground">+ <Spinner class="size-3" />+ {m.common_loading()}+ </div>+ {:else if workspaceBackupHasPath === false}+ <div class="text-xs text-destructive">{m.volumes_workspace_backup_missing_file()}</div>+ {/if}+ {/if}+ </div>+ {/snippet}++ {#snippet footer()}+ <ArcaneButton action="cancel" onclick={() => (showWorkspaceRestore = false)} />+ <ArcaneButton+ action="confirm"+ customLabel={m.volumes_workspace_restore_file()}+ onclick={stageWorkspaceRestore}+ disabled={loadingWorkspaceBackups || checkingWorkspaceBackup || workspaceBackupHasPath !== true}+ />+ {/snippet}+</ResponsiveDialog>diff --git a/frontend/src/routes/(app)/volumes/components/volume-workspace-utils.ts b/frontend/src/routes/(app)/volumes/components/volume-workspace-utils.tsnew file mode 100644index 000000000..a26445b17--- /dev/null+++ b/frontend/src/routes/(app)/volumes/components/volume-workspace-utils.ts@@ -0,0 +1,11 @@+import { m } from '#lib/paraglide/messages';+import type { VolumeWorkspaceFileContent } from '#lib/types/volume-workspace';+import { workspaceReadOnlyMessage } from '#lib/utils/workspace-files';++export function volumeWorkspaceReadOnlyMessage(+ reason: VolumeWorkspaceFileContent['readOnlyReason'],+ maxFileSizeMb: number+): string {+ if (reason === 'restore_pending') return m.volumes_workspace_restore_readonly();+ return workspaceReadOnlyMessage(reason, maxFileSizeMb);+}diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.tsindex aa3fb6d7a..3ea4fc787 100644--- a/tests/spec/project.spec.ts+++ b/tests/spec/project.spec.ts@@ -1036,11 +1036,11 @@ test.describe('GitOps Managed Project', () => {name: 'Toggle workspace mode',exact: true});- const projectFilesLabel = page.getByText('Project Files', { exact: true });+ const workspaceFilesLabel = page.getByText('Workspace Files', { exact: true });// Projects with extra files default to tree view; start from classic.- if (await projectFilesLabel.isVisible().catch(() => false)) {+ if (await workspaceFilesLabel.isVisible().catch(() => false)) {await layoutSwitch.click();- await expect(projectFilesLabel).not.toBeVisible();+ await expect(workspaceFilesLabel).not.toBeVisible();}await page.waitForTimeout(800);@@ -1058,7 +1058,7 @@ test.describe('GitOps Managed Project', () => {if (await layoutSwitch.count()) {await layoutSwitch.click();await page.waitForLoadState('load');- await expect(projectFilesLabel).toBeVisible();+ await expect(workspaceFilesLabel).toBeVisible();const envFileButton = page.getByRole('button', { name: '.env' }).first();await expect(envFileButton).toBeVisible();@@ -1300,8 +1300,8 @@ test.describe('Project Detail Page', () => {// - classic: side-by-side compose.yaml + .env panels// - tree view (default when the project has extra files): file list on the// left and a tabbed code panel on the right- const projectFilesLabel = page.getByText('Project Files', { exact: true });- const isTreeView = await projectFilesLabel.isVisible().catch(() => false);+ const workspaceFilesLabel = page.getByText('Workspace Files', { exact: true });+ const isTreeView = await workspaceFilesLabel.isVisible().catch(() => false);if (isTreeView) {const composeFileButton = page.getByRole('button', { name: 'compose.yaml' }).first();@@ -1329,7 +1329,7 @@ test.describe('Project Detail Page', () => {});if (await layoutSwitch.count()) {await layoutSwitch.click();- await expect(projectFilesLabel).toBeVisible();+ await expect(workspaceFilesLabel).toBeVisible();const composeFileButton = page.getByRole('button', { name: 'compose.yaml' }).first();const envFileButton = page.getByRole('button', { name: '.env' }).first();@@ -1365,11 +1365,11 @@ test.describe('Project Detail Page', () => {'No layout switch available for project configuration');- const projectFilesLabel = page.getByText('Project Files', { exact: true });+ const workspaceFilesLabel = page.getByText('Workspace Files', { exact: true });- if (!(await projectFilesLabel.isVisible().catch(() => false))) {+ if (!(await workspaceFilesLabel.isVisible().catch(() => false))) {await layoutSwitch.click();- await expect(projectFilesLabel).toBeVisible();+ await expect(workspaceFilesLabel).toBeVisible();}await page.reload();@@ -1384,7 +1384,7 @@ test.describe('Project Detail Page', () => {await page.waitForLoadState('load');}- await expect(projectFilesLabel).toBeVisible();+ await expect(workspaceFilesLabel).toBeVisible();await expect(page.locator('[data-tab-key="compose"][data-active="true"]')).toBeVisible();const treeComposeEditor = page.locator('.cm-editor').filter({ visible: true }).first();diff --git a/types/project/project.go b/types/project/project.goindex c9ad83484..df5569f2d 100644--- a/types/project/project.go+++ b/types/project/project.go@@ -25,121 +25,6 @@ type IncludeFile struct {Content string `json:"content,omitempty"`}-// ProjectFile represents a file or folder within a project directory.-type ProjectFile struct {- // ModTime is the last modification time.- //- // Required: true- ModTime time.Time `json:"modTime"`-- // Path is the absolute path to the file or folder.- //- // Required: true- Path string `json:"path"`-- // RelativePath is the path relative to the project directory.- //- // Required: true- RelativePath string `json:"relativePath"`-- // Name is the base name of the file or folder.- //- // Required: true- Name string `json:"name"`-- // Content is the file content when explicitly requested.- //- // Required: false- Content string `json:"content,omitempty"`-- // Size is the file size in bytes. Directories report zero.- //- // Required: true- Size int64 `json:"size"`-- // IsDirectory indicates whether this entry is a folder.- //- // Required: true- IsDirectory bool `json:"isDirectory"`-- // Protected indicates that Arcane owns this path and it cannot be renamed,- // deleted, moved, or overwritten through project file management.- //- // Required: false- Protected bool `json:"protected,omitempty"`-}--// ProjectFileDraft is used when creating a project with staged files.-type ProjectFileDraft struct {- // RelativePath is the path relative to the project directory.- //- // Required: true- RelativePath string `json:"relativePath" binding:"required"`-- // IsDirectory indicates whether the draft creates a folder.- //- // Required: true- IsDirectory bool `json:"isDirectory"`-- // Content is the text file content. It is ignored for folders.- //- // Required: false- Content string `json:"content,omitempty"`-}--// Project file operations accepted by ProjectFileChange.Operation.-const (- FileOpCreateFile = "create_file"- FileOpCreateFolder = "create_folder"- FileOpUpdateFile = "update_file"- FileOpRename = "rename"- FileOpMove = "move"- FileOpDelete = "delete"-)--// ProjectFileChange describes one staged file-tree operation.-type ProjectFileChange struct {- // Operation is one of create_file, create_folder, update_file, rename, move, or delete.- //- // Required: true- Operation string `json:"operation" binding:"required" enum:"create_file,create_folder,update_file,rename,move,delete"`-- // RelativePath is the source or target path relative to the project directory.- //- // Required: true- RelativePath string `json:"relativePath" binding:"required"`-- // NewName is used by rename operations. Rename is basename-only and never moves- // a file or folder to another parent.- //- // Required: false- NewName string `json:"newName,omitempty"`-- // NewParentPath is used by move operations. Empty means project root.- //- // Required: false- NewParentPath string `json:"newParentPath,omitempty"`-- // Content is used by create_file and update_file operations.- //- // Required: false- Content *string `json:"content,omitempty"`-- // Recursive allows deleting a non-empty folder. The UI must require a strong- // confirmation before sending this flag.- //- // Required: false- Recursive bool `json:"recursive,omitempty"`-}--// FileContentRequest requests the contents of a single project-related file.-type FileContentRequest struct {- // RelativePath is the path to the file relative to the project.- //- // Required: true- RelativePath string `json:"relativePath" query:"relativePath" binding:"required"`-}-// CreateProject is used to create a new project.type CreateProject struct {// Name of the project.@@ -156,11 +41,6 @@ type CreateProject struct {//// Required: falseEnvContent *string `json:"envContent,omitempty"`-- // ProjectFiles are optional text files and folders staged during project creation.- //- // Required: false- ProjectFiles []ProjectFileDraft `json:"projectFiles,omitempty" maxItems:"500"`}// UpdateProject is used to update a project.@@ -188,18 +68,6 @@ type UpdateProject struct {//// Required: falseOverrideContent *string `json:"overrideContent,omitempty"`-- // FileTreeRevision is the revision observed by the client before staging- // FileChanges. The server rejects stale revisions to avoid clobbering- // concurrent filesystem changes.- //- // Required: false- FileTreeRevision *string `json:"fileTreeRevision,omitempty"`-- // FileChanges are staged project file-tree operations applied with Save.- //- // Required: false- FileChanges []ProjectFileChange `json:"fileChanges,omitempty" maxItems:"500"`}// DeployOptions configures project deploy behavior.@@ -226,19 +94,6 @@ type DeployOptions struct {RecreateVolumes bool `json:"recreateVolumes,omitempty"`}-// UpdateIncludeFile is used to update an include file within a project.-type UpdateIncludeFile struct {- // RelativePath is the path to the include file relative to the project.- //- // Required: true- RelativePath string `json:"relativePath" binding:"required"`-- // Content is the file content.- //- // Required: true- Content string `json:"content" binding:"required"`-}-// RuntimeService contains live container status information for a service.type RuntimeService struct {// Name is the service name from the compose file.@@ -356,8 +211,6 @@ type DetailsOptions struct {IncludeEnvState boolIncludeIncludeFiles boolIncludeServiceConfigs bool- IncludeDirectoryFiles bool- IncludeProjectFiles boolIncludeRuntimeServices boolIncludeUpdateInfo bool}@@ -368,8 +221,6 @@ func AllDetails() DetailsOptions {IncludeEnvState: true,IncludeIncludeFiles: true,IncludeServiceConfigs: true,- IncludeDirectoryFiles: true,- IncludeProjectFiles: true,IncludeRuntimeServices: true,IncludeUpdateInfo: true,}@@ -536,12 +387,6 @@ type Details struct {// Required: falseIconLightURL string `json:"iconLightUrl,omitempty"`- // FileTreeRevision identifies the project file tree state returned to the client.- // Mutations using staged file changes must include this value.- //- // Required: false- FileTreeRevision string `json:"fileTreeRevision,omitempty"`-// RelativePath is the path to the project directory relative to the configured projects root.//// Required: false@@ -586,17 +431,6 @@ type Details struct {// Required: falseURLs []string `json:"urls,omitempty"`- // ProjectFiles contains the editable file tree for project file management.- //- // Required: false- ProjectFiles []ProjectFile `json:"projectFiles,omitempty"`-- // DirectoryFiles contains all other files in the project directory- // (excluding compose files, .env, and include files which are shown separately).- //- // Required: false- DirectoryFiles []IncludeFile `json:"directoryFiles,omitempty"`-// IncludeFiles is a list of included files in the project.//// Required: false@@ -631,12 +465,6 @@ type Details struct {//// Required: falseRedeployDisabled bool `json:"redeployDisabled,omitempty"`-- // FileTreeTruncated indicates the file tree walk hit the entry cap and- // ProjectFiles is only a prefix of the full tree.- //- // Required: false- FileTreeTruncated bool `json:"fileTreeTruncated,omitempty"`}// Destroy is used to destroy a project.diff --git a/types/project/workspace.go b/types/project/workspace.gonew file mode 100644index 000000000..d690b096a--- /dev/null+++ b/types/project/workspace.go@@ -0,0 +1,23 @@+package project++import workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"++const (+ FileOpCreateFile = workspacetypes.FileOpCreateFile+ FileOpCreateFolder = workspacetypes.FileOpCreateFolder+ FileOpUpdateFile = workspacetypes.FileOpUpdateFile+ FileOpRename = workspacetypes.FileOpRename+ FileOpMove = workspacetypes.FileOpMove+ FileOpDelete = workspacetypes.FileOpDelete+)++type WorkspaceFileChange = workspacetypes.FileChange++type WorkspaceUpdateManifest struct {+ FileTreeRevision string `json:"fileTreeRevision" binding:"required"`+ FileChanges []WorkspaceFileChange `json:"fileChanges" binding:"required" minItems:"1" maxItems:"500"`+}++type CreateProjectWorkspaceManifest struct {+ FileChanges []WorkspaceFileChange `json:"fileChanges" binding:"required" maxItems:"500"`+}diff --git a/types/settings/settings.go b/types/settings/settings.goindex a019ed1da..a0205ea3b 100644--- a/types/settings/settings.go+++ b/types/settings/settings.go@@ -458,11 +458,11 @@ type Update struct {// Required: falseAutoHealRestartWindow *string `json:"autoHealRestartWindow,omitempty"`- // VolumeBrowserHelperIdleTimeout is the number of minutes a volume-browser helper+ // VolumeHelperIdleTimeout is the number of minutes a volume helper// container may sit idle before it is automatically removed (0 disables).//// Required: false- VolumeBrowserHelperIdleTimeout *string `json:"volumeBrowserHelperIdleTimeout,omitempty"`+ VolumeHelperIdleTimeout *string `json:"volumeHelperIdleTimeout,omitempty"`// BuildProvider is the default build provider (local|depot).//diff --git a/types/volume/browse.go b/types/volume/browse.godeleted file mode 100644index 2e96a7b1b..000000000--- a/types/volume/browse.go+++ /dev/null@@ -1,22 +0,0 @@-package volume--import "time"--type FileEntry struct {- ModTime time.Time `json:"modTime" doc:"Last modification time"`- Name string `json:"name" doc:"Name of the file or directory"`- Path string `json:"path" doc:"Full path to the file"`- Mode string `json:"mode" doc:"File mode/permissions"`- LinkTarget string `json:"linkTarget,omitempty" doc:"Target of the symbolic link"`- Size int64 `json:"size" doc:"Size of the file in bytes"`- IsDirectory bool `json:"isDirectory" doc:"Whether this entry is a directory"`- IsSymlink bool `json:"isSymlink" doc:"Whether this entry is a symbolic link"`-}--type FileMetadata struct {- FileEntry-- MimeType string `json:"mimeType" doc:"MIME type of the file"`- IsText bool `json:"isText" doc:"Whether the file is a text file"`- IsBinary bool `json:"isBinary" doc:"Whether the file is a binary file"`-}diff --git a/types/volume/workspace.go b/types/volume/workspace.gonew file mode 100644index 000000000..075c1bcdf--- /dev/null+++ b/types/volume/workspace.go@@ -0,0 +1,28 @@+package volume++import workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"++const (+ FileOpCreateFile = workspacetypes.FileOpCreateFile+ FileOpCreateFolder = workspacetypes.FileOpCreateFolder+ FileOpUpdateFile = workspacetypes.FileOpUpdateFile+ FileOpRename = workspacetypes.FileOpRename+ FileOpMove = workspacetypes.FileOpMove+ FileOpDelete = workspacetypes.FileOpDelete+ FileOpRestoreFile = "restore_file"+)++type WorkspaceFileChange struct {+ Operation string `json:"operation" binding:"required" enum:"create_file,create_folder,update_file,rename,move,delete,restore_file"`+ RelativePath string `json:"relativePath" binding:"required"`+ NewName string `json:"newName,omitempty"`+ NewParentPath string `json:"newParentPath,omitempty"`+ UploadIndex *int `json:"uploadIndex,omitempty" minimum:"0"`+ BackupID string `json:"backupId,omitempty"`+ Recursive bool `json:"recursive,omitempty"`+}++type WorkspaceUpdateManifest struct {+ FileTreeRevision string `json:"fileTreeRevision" binding:"required"`+ FileChanges []WorkspaceFileChange `json:"fileChanges" binding:"required" minItems:"1" maxItems:"500"`+}diff --git a/types/workspace/workspace.go b/types/workspace/workspace.gonew file mode 100644index 000000000..ea8124101--- /dev/null+++ b/types/workspace/workspace.go@@ -0,0 +1,60 @@+package workspace++import "time"++const (+ FileOpCreateFile = "create_file"+ FileOpCreateFolder = "create_folder"+ FileOpUpdateFile = "update_file"+ FileOpRename = "rename"+ FileOpMove = "move"+ FileOpDelete = "delete"+)++const (+ FileReadOnlyBinary = "binary"+ FileReadOnlyTooLarge = "too_large"+ FileReadOnlySymlink = "symlink"+ FileReadOnlySpecial = "special"+)++type FileEntry struct {+ ModTime time.Time `json:"modTime" doc:"Last modification time"`+ Name string `json:"name" doc:"Name of the file or directory"`+ Path string `json:"path" doc:"Full path to the file"`+ RelativePath string `json:"relativePath" doc:"Path relative to the workspace root"`+ Mode string `json:"mode,omitempty" doc:"File mode/permissions"`+ LinkTarget string `json:"linkTarget,omitempty" doc:"Target of the symbolic link"`+ Size int64 `json:"size" doc:"Size of the file in bytes"`+ IsDirectory bool `json:"isDirectory" doc:"Whether this entry is a directory"`+ IsSymlink bool `json:"isSymlink" doc:"Whether this entry is a symbolic link"`+ Editable bool `json:"editable" doc:"Whether this entry can be edited"`+ ReadOnlyReason string `json:"readOnlyReason,omitempty" enum:"binary,too_large,symlink,special"`+}++type FileChange struct {+ Operation string `json:"operation" binding:"required" enum:"create_file,create_folder,update_file,rename,move,delete"`+ RelativePath string `json:"relativePath" binding:"required"`+ NewName string `json:"newName,omitempty"`+ NewParentPath string `json:"newParentPath,omitempty"`+ UploadIndex *int `json:"uploadIndex,omitempty" minimum:"0"`+ Recursive bool `json:"recursive,omitempty"`+}++type Workspace struct {+ Files []FileEntry `json:"files"`+ FileTreeRevision string `json:"fileTreeRevision"`+ FileTreeTruncated bool `json:"fileTreeTruncated"`+ ActivityID *string `json:"activityId,omitempty"`+}++type FileContent struct {+ Path string `json:"path"`+ RelativePath string `json:"relativePath"`+ Name string `json:"name"`+ Content string `json:"content,omitempty"`+ MimeType string `json:"mimeType"`+ Size int64 `json:"size"`+ Editable bool `json:"editable"`+ ReadOnlyReason string `json:"readOnlyReason,omitempty" enum:"binary,too_large,symlink,special"`+}