Skip to content

Modern Docker Management, Designed for Everyone

feat: add project file tree management (#2893)

Neureka20c608c2d4fd
diff --git a/backend/api/handlers/projects.go b/backend/api/handlers/projects.go
index c3146b1e4..216a38a43 100644
--- a/backend/api/handlers/projects.go
+++ b/backend/api/handlers/projects.go
@@ -688,6 +688,21 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpu
}, nil
}
+// 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 conflictErr, ok := errors.AsType[*common.ProjectFileConflictError](err); ok {
+ return huma.Error409Conflict(conflictErr.Error())
+ }
+ if forbiddenErr, ok := errors.AsType[*common.ProjectFileForbiddenError](err); ok {
+ return huma.Error403Forbidden(forbiddenErr.Error())
+ }
+ if badRequestErr, ok := errors.AsType[*common.ProjectFileBadRequestError](err); ok {
+ return huma.Error400BadRequest(badRequestErr.Error())
+ }
+ return nil
+}
+
// CreateProject creates a new Docker Compose project.
func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectInput) (*CreateProjectOutput, error) {
if h.projectService == nil {
@@ -714,10 +729,13 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject
Metadata: 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, *user)
+ proj, createErr = h.projectService.CreateProject(runtimeCtx, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent, input.Body.ProjectFiles, *user)
return createErr
})
if err != nil {
+ if httpErr := projectFileHTTPError(err); httpErr != nil {
+ return nil, httpErr
+ }
return nil, huma.Error500InternalServerError((&common.ProjectCreationError{Err: err}).Error())
}
@@ -800,6 +818,7 @@ 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,
})
}
@@ -941,10 +960,13 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProject
SuccessMessage: "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, *user)
+ _, updateErr := h.projectService.UpdateProject(runtimeCtx, input.ProjectID, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent, input.Body.FileTreeRevision, input.Body.FileChanges, *user)
return updateErr
})
if err != nil {
+ if httpErr := projectFileHTTPError(err); httpErr != nil {
+ return nil, httpErr
+ }
return nil, huma.Error400BadRequest((&common.ProjectUpdateError{Err: err}).Error())
}
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index 9f03cbd76..3923e1d04 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -833,6 +833,17 @@ func (e *ProjectFileNotFoundError) Error() string {
return "Project file not found"
}
+type ProjectFileConflictError struct {
+ Err error
+}
+
+func (e *ProjectFileConflictError) Error() string {
+ if e.Err == nil {
+ return "Project files changed; refresh the project and try again"
+ }
+ return e.Err.Error()
+}
+
type ProjectComposeFileNotFoundError struct {
Err error
}
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index a144a2306..ea7003844 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -69,6 +69,7 @@ type Config struct {
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"`
diff --git a/backend/internal/configschema/schema_test.go b/backend/internal/configschema/schema_test.go
index c1ec77333..043f2eff2 100644
--- a/backend/internal/configschema/schema_test.go
+++ b/backend/internal/configschema/schema_test.go
@@ -245,6 +245,7 @@ var expectedEnvConfigVars = []string{
"PGID",
"PORT",
"PROJECTS_DIRECTORY",
+ "PROJECT_FILE_TREE_MAX_DEPTH",
"PROJECT_SCAN_MAX_DEPTH",
"PROJECT_SCAN_SKIP_DIRS",
"PROXY_REQUEST_TIMEOUT",
diff --git a/backend/internal/services/gitops_sync_service.go b/backend/internal/services/gitops_sync_service.go
index 0958a2541..1c6d5327b 100644
--- a/backend/internal/services/gitops_sync_service.go
+++ b/backend/internal/services/gitops_sync_service.go
@@ -1037,7 +1037,7 @@ func (s *GitOpsSyncService) failSync(ctx context.Context, id string, result *git
}
func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, sync *models.GitOpsSync, id string, composeContent string, envContent *string, result *gitops.SyncResult, actor models.User) (*models.Project, error) {
- project, err := s.projectService.CreateProject(ctx, sync.ProjectName, composeContent, envContent, actor)
+ project, err := s.projectService.CreateProject(ctx, sync.ProjectName, composeContent, envContent, nil, actor)
if err != nil {
return nil, s.failSync(ctx, id, result, sync, actor, "Failed to create project", err.Error())
}
diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.go
index eaa937845..99f7628e9 100644
--- a/backend/internal/services/project_service.go
+++ b/backend/internal/services/project_service.go
@@ -1063,6 +1063,9 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID string
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
@@ -1121,6 +1124,10 @@ func (s *ProjectService) GetProjectFileContent(ctx context.Context, projectID, r
if strings.TrimSpace(relativePath) == "" {
return project.IncludeFile{}, &common.ProjectFileBadRequestError{Err: errors.New("relative path is required")}
}
+ normalizedRelativePath, err := projects.NormalizeProjectRelativePath(relativePath)
+ if err != nil {
+ return project.IncludeFile{}, &common.ProjectFileForbiddenError{Err: err}
+ }
composeFile, detectErr := s.resolveProjectComposeFileInternal(ctx, proj)
if detectErr == nil {
@@ -1132,7 +1139,7 @@ func (s *ProjectService) GetProjectFileContent(ctx context.Context, projectID, r
includes, parseErr := projects.ParseIncludes(composeFile, envMap, false)
if parseErr == nil {
for _, inc := range includes {
- if inc.RelativePath != relativePath {
+ if inc.RelativePath != normalizedRelativePath {
continue
}
if !projects.IsSafeSubdirectory(proj.Path, inc.Path) {
@@ -1143,16 +1150,8 @@ func (s *ProjectService) GetProjectFileContent(ctx context.Context, projectID, r
}
}
- fullPath := filepath.Join(proj.Path, relativePath)
- absProjectPath, err := filepath.Abs(proj.Path)
+ absFilePath, err := projects.ValidateIncludePathForWrite(proj.Path, normalizedRelativePath)
if err != nil {
- return project.IncludeFile{}, fmt.Errorf("failed to resolve project path: %w", err)
- }
- absFilePath, err := filepath.Abs(fullPath)
- if err != nil {
- return project.IncludeFile{}, fmt.Errorf("failed to resolve file path: %w", err)
- }
- if !projects.IsSafeSubdirectory(absProjectPath, absFilePath) {
return project.IncludeFile{}, &common.ProjectFileForbiddenError{Err: errors.New("file path is outside project directory")}
}
@@ -1183,7 +1182,7 @@ func (s *ProjectService) GetProjectFileContent(ctx context.Context, projectID, r
return project.IncludeFile{
Path: absFilePath,
- RelativePath: relativePath,
+ RelativePath: normalizedRelativePath,
Content: string(content),
}, nil
}
@@ -1481,6 +1480,21 @@ func (s *ProjectService) enrichWithDirectoryFiles(ctx context.Context, projectPa
resp.DirectoryFiles = dirFiles
}
+func (s *ProjectService) enrichWithProjectFiles(ctx context.Context, projectPath, composeFileName string, resp *project.Details) {
+ if projectPath == "" {
+ return
+ }
+
+ files, revision, err := projects.ReadProjectFileTree(projectPath, s.config.ProjectFileTreeMaxDepth, s.config.ProjectScanSkipDirs, composeFileName)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to scan project file tree", "error", err, "path", projectPath)
+ return
+ }
+
+ resp.ProjectFiles = files
+ resp.FileTreeRevision = revision
+}
+
func (s *ProjectService) enrichWithGitOpsInfo(ctx context.Context, proj *models.Project, resp *project.Details) {
if proj.GitOpsManagedBy != nil {
var sync models.GitOpsSync
@@ -2041,7 +2055,7 @@ func (s *ProjectService) DownProject(ctx context.Context, projectID string, user
return nil
}
-func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent string, envContent *string, user models.User) (*models.Project, error) {
+func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent string, envContent *string, projectFiles []project.ProjectFileDraft, user models.User) (*models.Project, error) {
// A top-level `name:` in the compose file is authoritative over the
// submitted project name.
if yamlName := projects.ComposeContentProjectName(composeContent); yamlName != "" {
@@ -2069,21 +2083,30 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent
RunningCount: 0,
}
- if err := s.db.WithContext(ctx).Create(proj).Error; err != nil {
- return nil, fmt.Errorf("failed to create project: %w", err)
+ if err := projects.ApplyProjectFileDrafts(projectPath, projectFiles, projects.ProjectFileApplyOptions{
+ MaxDepth: s.config.ProjectFileTreeMaxDepth,
+ SkipDirectories: s.config.ProjectScanSkipDirs,
+ ComposeFileName: projects.DefaultComposeFileName,
+ }); err != nil {
+ _ = os.RemoveAll(projectPath)
+ return nil, wrapProjectFileErrorInternal(err)
}
if err := s.validateComposeContentForUpdate(ctx, projectsDirectory, projectPath, name, composeContent, envContent); err != nil {
- _ = s.db.WithContext(ctx).Delete(proj).Error
_ = os.RemoveAll(projectPath)
return nil, fmt.Errorf("invalid compose file: %w", err)
}
if err := projects.SaveOrUpdateProjectFiles(projectsDirectory, projectPath, composeContent, envContent); err != nil {
// Best-effort cleanup to restore pre-transaction behavior.
- _ = s.db.WithContext(ctx).Delete(proj).Error
+ _ = os.RemoveAll(projectPath)
return nil, fmt.Errorf("failed to save project files: %w", err)
}
+
+ if err := s.db.WithContext(ctx).Create(proj).Error; err != nil {
+ _ = os.RemoveAll(projectPath)
+ return nil, fmt.Errorf("failed to create project: %w", err)
+ }
s.refreshProjectImageRefsInternal(ctx, proj)
metadata := models.JSON{"action": "create", "projectID": proj.ID, "projectName": name, "path": projectPath}
@@ -2896,7 +2919,7 @@ func (s *ProjectService) RestartProject(ctx context.Context, projectID string, u
return nil
}
-func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, name *string, composeContent, envContent *string, user models.User) (*models.Project, error) {
+func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, name *string, composeContent, envContent *string, fileTreeRevision *string, fileChanges []project.ProjectFileChange, user models.User) (*models.Project, error) {
proj, projectsDirectory, err := s.getProjectForUpdate(ctx, projectID)
if err != nil {
return nil, err
@@ -2904,26 +2927,32 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, na
if err := ensureProjectMutableInternal(&proj); err != nil {
return nil, err
}
+ if len(fileChanges) > 0 && isGitOpsManagedProjectInternal(&proj) {
+ return nil, &common.ProjectFileForbiddenError{Err: errors.New("git-managed project files are read-only")}
+ }
- // A top-level `name:` in the compose file is authoritative over the
- // submitted project name. For name-only renames, enforce against the
- // compose file on disk so the lock can't be bypassed via the API.
- if composeContent != nil {
- if yamlName := projects.ComposeContentProjectName(*composeContent); yamlName != "" {
- name = &yamlName
+ backupPath := ""
+ if len(fileChanges) > 0 {
+ backupPath, err = s.backupProjectDirectoryInternal(projectsDirectory, proj.Path)
+ if err != nil {
+ return nil, err
}
- } else if name != nil {
- if onDiskCompose, _, readErr := projects.ReadProjectFiles(proj.Path, ""); readErr == nil {
- if yamlName := projects.ComposeContentProjectName(onDiskCompose); yamlName != "" {
- name = &yamlName
+ defer func() {
+ if backupPath != "" {
+ _ = os.RemoveAll(backupPath)
}
- }
+ }()
}
+ name = resolveAuthoritativeProjectNameInternal(&proj, name, composeContent)
+
if err := s.withProjectRenameRollback(ctx, &proj, func() error {
if 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); err != nil {
return err
}
@@ -2932,18 +2961,44 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, na
}
return nil
}); err != nil {
+ if backupPath != "" {
+ if restoreErr := s.restoreProjectDirectoryBackupInternal(ctx, projectsDirectory, proj.Path, backupPath); restoreErr != nil {
+ slog.WarnContext(ctx, "failed to restore project files after update failure", "projectID", projectID, "error", restoreErr)
+ }
+ }
return nil, err
}
- // When compose content changes, recalculate service counts and status so the
- // overview doesn't show stale values (e.g. ghost services after removal).
+ s.refreshProjectAfterContentUpdateInternal(ctx, &proj, composeContent, fileChanges)
+
+ s.logProjectUpdateEventInternal(ctx, &proj, composeContent, envContent, fileChanges, user)
+
+ slog.InfoContext(ctx, "project updated", "projectID", proj.ID, "name", proj.Name)
+ return &proj, nil
+}
+
+// resolveAuthoritativeProjectNameInternal enforces that a top-level `name:` in
+// the compose file is authoritative over the submitted project name. For
+// name-only renames, it checks the compose file on disk so the lock can't be
+// bypassed via the API.
+func resolveAuthoritativeProjectNameInternal(proj *models.Project, name *string, composeContent *string) *string {
if composeContent != nil {
- s.refreshProjectImageRefsInternal(ctx, &proj)
- if err := s.updateProjectStatusandCountsInternal(ctx, proj.ID, proj.Status); err != nil {
- slog.WarnContext(ctx, "failed to update service counts after compose edit", "projectID", proj.ID, "error", err)
+ if yamlName := projects.ComposeContentProjectName(*composeContent); yamlName != "" {
+ return &yamlName
}
+ return name
}
+ if name != nil {
+ if onDiskCompose, _, readErr := projects.ReadProjectFiles(proj.Path, ""); readErr == nil {
+ if yamlName := projects.ComposeContentProjectName(onDiskCompose); yamlName != "" {
+ return &yamlName
+ }
+ }
+ }
+ return name
+}
+func (s *ProjectService) logProjectUpdateEventInternal(ctx context.Context, proj *models.Project, composeContent, envContent *string, fileChanges []project.ProjectFileChange, user models.User) {
metadata := models.JSON{
"action": "update",
"projectID": proj.ID,
@@ -2955,12 +3010,24 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, na
if envContent != nil {
metadata["envUpdated"] = true
}
+ if len(fileChanges) > 0 {
+ metadata["projectFilesUpdated"] = true
+ metadata["projectFileChangeCount"] = len(fileChanges)
+ }
if logErr := s.eventService.LogProjectEvent(ctx, models.EventTypeProjectUpdate, proj.ID, proj.Name, user.ID, user.Username, "0", metadata); logErr != nil {
slog.ErrorContext(ctx, "could not log project update action", "error", logErr)
}
+}
- slog.InfoContext(ctx, "project updated", "projectID", proj.ID, "name", proj.Name)
- return &proj, nil
+func (s *ProjectService) refreshProjectAfterContentUpdateInternal(ctx context.Context, proj *models.Project, composeContent *string, fileChanges []project.ProjectFileChange) {
+ if composeContent == nil && len(fileChanges) == 0 {
+ return
+ }
+
+ s.refreshProjectImageRefsInternal(ctx, proj)
+ if err := s.updateProjectStatusandCountsInternal(ctx, proj.ID, proj.Status); err != nil {
+ slog.WarnContext(ctx, "failed to update service counts after compose edit", "projectID", proj.ID, "error", err)
+ }
}
func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectID string, composeContent string, gitEnvContent *string, user models.User) (*models.Project, error) {
@@ -3035,6 +3102,105 @@ func (s *ProjectService) getProjectForUpdate(ctx context.Context, projectID stri
return proj, projectsDirectory, nil
}
+func isGitOpsManagedProjectInternal(proj *models.Project) bool {
+ return proj != nil && proj.GitOpsManagedBy != nil && strings.TrimSpace(*proj.GitOpsManagedBy) != ""
+}
+
+func (s *ProjectService) persistProjectFileChanges(ctx context.Context, proj *models.Project, fileTreeRevision *string, fileChanges []project.ProjectFileChange) error {
+ if len(fileChanges) == 0 {
+ return nil
+ }
+ if fileTreeRevision == nil || strings.TrimSpace(*fileTreeRevision) == "" {
+ return &common.ProjectFileBadRequestError{Err: errors.New("file tree revision is required")}
+ }
+
+ composeFileName := projects.DefaultComposeFileName
+ if composeFile, err := s.resolveProjectComposeFileInternal(ctx, proj); err == nil {
+ composeFileName = filepath.Base(composeFile)
+ }
+
+ if err := projects.ApplyProjectFileChanges(proj.Path, fileChanges, projects.ProjectFileApplyOptions{
+ ExpectedRevision: strings.TrimSpace(*fileTreeRevision),
+ MaxDepth: s.config.ProjectFileTreeMaxDepth,
+ SkipDirectories: s.config.ProjectScanSkipDirs,
+ ComposeFileName: composeFileName,
+ }); err != nil {
+ return wrapProjectFileErrorInternal(err)
+ }
+ return nil
+}
+
+// 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.ProjectFileConflictError{Err: err}
+ case errors.Is(err, projects.ErrProjectFileOutsideProjectDirectory),
+ errors.Is(err, projects.ErrProjectFileProtectedPath),
+ errors.Is(err, projects.ErrProjectFileSymlinkPath):
+ return &common.ProjectFileForbiddenError{Err: err}
+ default:
+ return &common.ProjectFileBadRequestError{Err: err}
+ }
+}
+
+func (s *ProjectService) backupProjectDirectoryInternal(projectsDirectory, projectPath string) (string, error) {
+ projectAbs, err := filepath.Abs(projectPath)
+ if err != nil {
+ return "", fmt.Errorf("failed to resolve project path: %w", err)
+ }
+ projectAbs = filepath.Clean(projectAbs)
+
+ rootAbs, err := filepath.Abs(projectsDirectory)
+ if err != nil {
+ return "", fmt.Errorf("failed to resolve projects directory: %w", err)
+ }
+ rootAbs = filepath.Clean(rootAbs)
+ if !projects.IsSafeSubdirectory(rootAbs, projectAbs) || projectAbs == rootAbs {
+ return "", errors.New("project path is outside projects directory")
+ }
+
+ backupPath, err := os.MkdirTemp(projectsDirectory, ".project-update-backup-*")
+ if err != nil {
+ return "", fmt.Errorf("failed to create project backup directory: %w", err)
+ }
+ if err := projects.CopyDirectoryContents(projectAbs, backupPath); err != nil {
+ _ = os.RemoveAll(backupPath)
+ return "", fmt.Errorf("failed to backup project files: %w", err)
+ }
+ return backupPath, nil
+}
+
+func (s *ProjectService) restoreProjectDirectoryBackupInternal(ctx context.Context, projectsDirectory, projectPath, backupPath string) error {
+ projectAbs, err := filepath.Abs(projectPath)
+ if err != nil {
+ return fmt.Errorf("failed to resolve project path: %w", err)
+ }
+ projectAbs = filepath.Clean(projectAbs)
+
+ rootAbs, err := filepath.Abs(projectsDirectory)
+ if err != nil {
+ return fmt.Errorf("failed to resolve projects directory: %w", err)
+ }
+ rootAbs = filepath.Clean(rootAbs)
+ if !projects.IsSafeSubdirectory(rootAbs, projectAbs) || projectAbs == rootAbs {
+ return errors.New("project path is outside projects directory")
+ }
+
+ slog.DebugContext(ctx, "restoring project directory backup", "path", projectAbs, "backup", backupPath)
+ if err := os.RemoveAll(projectAbs); err != nil {
+ return fmt.Errorf("failed to remove failed project directory state: %w", err)
+ }
+ if err := os.MkdirAll(projectAbs, common.DirPerm); err != nil {
+ return fmt.Errorf("failed to recreate project directory: %w", err)
+ }
+ if err := projects.CopyDirectoryContents(backupPath, projectAbs); err != nil {
+ return fmt.Errorf("failed to restore project backup: %w", err)
+ }
+ return nil
+}
+
func (s *ProjectService) withProjectRenameRollback(ctx context.Context, proj *models.Project, run func() error) error {
originalPath := proj.Path
originalDirName := proj.DirName
diff --git a/backend/internal/services/project_service_test.go b/backend/internal/services/project_service_test.go
index 3cf713561..23ff97ea7 100644
--- a/backend/internal/services/project_service_test.go
+++ b/backend/internal/services/project_service_test.go
@@ -1098,7 +1098,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, models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1149,7 +1149,7 @@ func TestProjectService_UpdateProject_RenameFailsWhenTargetDirectoryExists(t *te
}
require.NoError(t, db.Create(project).Error)
- _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, models.User{
+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1192,7 +1192,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, models.User{
+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1242,7 +1242,7 @@ services:
`
env := "COMPOSE_PROJECT_NAME=\n"
- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1284,7 +1284,7 @@ func TestProjectService_UpdateProject_AllowsMissingEnvFileDuringComposeValidatio
- .env
`
- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1328,7 +1328,7 @@ services:
image: nginx:alpine
`
- updated, err := svc.UpdateProject(ctx, project.ID, nil, ptr(compose), nil, models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, ptr(compose), nil, nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1392,7 +1392,7 @@ services:
image: nginx:alpine
`
- updated, err := svc.UpdateProject(ctx, project.ID, nil, ptr(compose), nil, models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, ptr(compose), nil, nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1424,7 +1424,7 @@ services:
image: nginx:alpine
`
- project, err := svc.CreateProject(ctx, "evil", compose, nil, models.User{
+ project, err := svc.CreateProject(ctx, "evil", compose, nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1462,7 +1462,7 @@ services:
image: nginx:alpine
`
- project, err := svc.CreateProject(ctx, "evil-array", compose, nil, models.User{
+ project, err := svc.CreateProject(ctx, "evil-array", compose, nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1477,6 +1477,226 @@ services:
assert.Zero(t, count)
}
+func TestProjectService_CreateProject_WritesStagedProjectFiles(t *testing.T) {
+ db := setupProjectTestDB(t)
+ ctx := context.Background()
+
+ projectsDir := t.TempDir()
+ t.Setenv("PROJECTS_DIRECTORY", projectsDir)
+
+ settingsService, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ eventService := NewEventService(db, nil, nil)
+ svc := NewProjectService(db, settingsService, eventService, 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 := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ eventService := NewEventService(db, nil, nil)
+ cfg := config.Load()
+ svc := NewProjectService(db, settingsService, eventService, 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")
+ 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 := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ eventService := NewEventService(db, nil, nil)
+ svc := NewProjectService(db, settingsService, eventService, 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")
+ require.NoError(t, err)
+
+ content := "hello\n"
+ updated := "updated\n"
+ _, err = svc.UpdateProject(ctx, project.ID, nil, nil, nil, &revision, []projecttypes.ProjectFileChange{
+ {Operation: "create_folder", RelativePath: "config"},
+ {Operation: "create_folder", RelativePath: "archive"},
+ {Operation: "create_file", RelativePath: "config/app.yaml", Content: &content},
+ {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 := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ eventService := NewEventService(db, nil, nil)
+ svc := NewProjectService(db, settingsService, eventService, 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")
+ 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, nil, nil, nil, &revision, []projecttypes.ProjectFileChange{
+ {Operation: "create_file", RelativePath: "notes.txt", Content: &content},
+ }, models.User{
+ BaseModel: models.BaseModel{ID: "u1"},
+ Username: "tester",
+ })
+ require.Error(t, err)
+
+ var conflictErr *common.ProjectFileConflictError
+ assert.ErrorAs(t, err, &conflictErr)
+ 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 := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ eventService := NewEventService(db, nil, nil)
+ svc := NewProjectService(db, settingsService, eventService, 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",
+ })
+ require.NoError(t, err)
+
+ details, err := svc.GetProjectDetails(ctx, project.ID, projecttypes.DetailsOptions{IncludeProjectFiles: true})
+ 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))
+
+ content := "new\n"
+ _, err = svc.UpdateProject(ctx, project.ID, nil, nil, nil, &details.FileTreeRevision, []projecttypes.ProjectFileChange{
+ {Operation: "create_file", RelativePath: "notes.txt", Content: &content},
+ }, models.User{
+ BaseModel: models.BaseModel{ID: "u1"},
+ Username: "tester",
+ })
+ require.Error(t, err)
+
+ var conflictErr *common.ProjectFileConflictError
+ assert.ErrorAs(t, err, &conflictErr)
+ assert.NoFileExists(t, filepath.Join(project.Path, "notes.txt"))
+}
+
func TestProjectService_GetProjectFileContent_RejectsExternalInclude(t *testing.T) {
db := setupProjectTestDB(t)
ctx := context.Background()
@@ -1612,6 +1832,45 @@ services:
assert.ErrorAs(t, err, &forbiddenErr)
}
+func TestProjectService_GetProjectFileContent_RejectsIntermediateSymlinkProjectFile(t *testing.T) {
+ db := setupProjectTestDB(t)
+ ctx := context.Background()
+
+ projectsDir := t.TempDir()
+ t.Setenv("PROJECTS_DIRECTORY", projectsDir)
+
+ settingsService, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ eventService := NewEventService(db, nil, nil)
+ svc := NewProjectService(db, settingsService, eventService, 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)
+
+ includeFile, err := svc.GetProjectFileContent(ctx, project.ID, "subdir/secret.yaml")
+ require.Error(t, err)
+ assert.Empty(t, includeFile)
+
+ var forbiddenErr *common.ProjectFileForbiddenError
+ assert.ErrorAs(t, err, &forbiddenErr)
+}
+
func TestProjectService_UpdateProject_UsesExistingEnvFileDuringComposeValidation(t *testing.T) {
db := setupProjectTestDB(t)
ctx := context.Background()
@@ -1646,7 +1905,7 @@ func TestProjectService_UpdateProject_UsesExistingEnvFileDuringComposeValidation
- .env
`
- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1692,7 +1951,7 @@ func TestProjectService_UpdateProject_UsesProvidedEnvContentDuringComposeValidat
`
env := "FOO=updated\n"
- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1738,7 +1997,7 @@ func TestProjectService_UpdateProject_ReturnsEnvParseErrorDuringComposeValidatio
`
env := "BROKEN=${UNTERMINATED\n"
- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1783,7 +2042,7 @@ func TestProjectService_UpdateProject_UsesGlobalEnvDuringComposeValidation(t *te
- ${MYPATH}cats/templates:/app/templates
`
- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1830,7 +2089,7 @@ func TestProjectService_UpdateProject_DoesNotResolveHostEnvThroughGlobalEnvDurin
- ${DATA_NAS_FOLDER}:/data
`
- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1868,7 +2127,7 @@ func TestProjectService_UpdateProject_DerivesProjectOverrideEnvWhenGitSourceExis
}
require.NoError(t, db.Create(project).Error)
- updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, new("BASE=git\nTOKEN=secret\n"), models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, new("BASE=git\nLOCAL_ONLY=example\n"), nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -1877,12 +2136,12 @@ func TestProjectService_UpdateProject_DerivesProjectOverrideEnvWhenGitSourceExis
overrideBytes, readErr := os.ReadFile(filepath.Join(projectPath, "project.env"))
require.NoError(t, readErr)
- assert.Equal(t, "TOKEN=secret\n", string(overrideBytes))
+ assert.Equal(t, "LOCAL_ONLY=example\n", string(overrideBytes))
effectiveBytes, readErr := os.ReadFile(filepath.Join(projectPath, ".env"))
require.NoError(t, readErr)
assert.Contains(t, string(effectiveBytes), "BASE=git\n")
- assert.Contains(t, string(effectiveBytes), "TOKEN=secret\n")
+ assert.Contains(t, string(effectiveBytes), "LOCAL_ONLY=example\n")
}
func TestProjectService_UpdateProject_DeletingGitBackedKeyFallsBackToGit(t *testing.T) {
@@ -1915,7 +2174,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"), models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, new("BASE=git\nLOCAL_ONLY=1\n"), nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
@@ -3957,7 +4216,7 @@ func TestProjectService_UpdateProject_WritesThroughSymlinkedProjectPath(t *testi
updatedCompose := "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), models.User{
+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(updatedCompose), new(updatedEnv), nil, nil, models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "tester",
})
diff --git a/backend/pkg/projects/fs_writer.go b/backend/pkg/projects/fs_writer.go
index 088aa80ca..275a07858 100644
--- a/backend/pkg/projects/fs_writer.go
+++ b/backend/pkg/projects/fs_writer.go
@@ -11,8 +11,12 @@ import (
pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
)
+// DefaultComposeFileName is the compose filename Arcane writes when a project
+// has no existing compose file.
+const DefaultComposeFileName = "compose.yaml"
+
var composeFileCandidates = []string{
- "compose.yaml",
+ DefaultComposeFileName,
"compose.yml",
"docker-compose.yaml",
"docker-compose.yml",
@@ -66,7 +70,7 @@ func WriteComposeFile(projectsRoot, dirPath, content string) error {
if existingFile := detectExistingComposeFileInternal(dirPath); existingFile != "" {
composePath = existingFile
} else {
- composePath = filepath.Join(dirPath, "compose.yaml")
+ composePath = filepath.Join(dirPath, DefaultComposeFileName)
}
if err := os.WriteFile(composePath, []byte(content), pkgutils.FilePerm); err != nil {
diff --git a/backend/pkg/projects/project_files.go b/backend/pkg/projects/project_files.go
new file mode 100644
index 000000000..4af7c410d
--- /dev/null
+++ b/backend/pkg/projects/project_files.go
@@ -0,0 +1,637 @@
+package projects
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "hash"
+ "io"
+ "io/fs"
+ "os"
+ "path"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/config"
+ pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
+ "github.com/getarcaneapp/arcane/types/v2/project"
+)
+
+const (
+ MaxManagedProjectFileBytes = 1024 * 1024
+ ProjectFileTreeUseScanDepth = -1
+)
+
+var (
+ ErrProjectFileRevisionConflict = errors.New("project file tree changed; refresh the project and try again")
+ ErrProjectFileOutsideProjectDirectory = errors.New("path is outside project directory")
+ ErrProjectFileProtectedPath = errors.New("protected project file cannot be modified")
+ ErrProjectFileSymlinkPath = errors.New("symlink project paths are not supported")
+)
+
+type ProjectFileApplyOptions struct {
+ ExpectedRevision string
+ MaxDepth int
+ SkipDirectories string
+ ComposeFileName string
+}
+
+func ReadProjectFileTree(projectPath string, maxDepth int, skipDirectories, composeFileName string) ([]project.ProjectFile, string, error) {
+ if maxDepth == ProjectFileTreeUseScanDepth {
+ maxDepth = config.Load().ProjectFileTreeMaxDepth
+ }
+
+ projectAbs, err := filepath.Abs(projectPath)
+ if err != nil {
+ return nil, "", fmt.Errorf("resolve project path: %w", err)
+ }
+ projectAbs = filepath.Clean(projectAbs)
+
+ root, err := os.OpenRoot(projectAbs)
+ if err != nil {
+ return nil, "", fmt.Errorf("open project directory: %w", err)
+ }
+ defer func() { _ = root.Close() }()
+
+ protected := ProtectedProjectFilePaths(composeFileName)
+ skipDirs := projectScanSkipDirectorySetInternal(skipDirectories)
+ files := []project.ProjectFile{}
+ revisionHash := sha256.New()
+
+ err = fs.WalkDir(root.FS(), ".", func(rel string, entry fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return walkErr
+ }
+ if rel == "." {
+ return nil
+ }
+
+ depth := strings.Count(rel, "/") + 1
+ if depth > maxDepth {
+ if entry.IsDir() {
+ return fs.SkipDir
+ }
+ return nil
+ }
+
+ if entry.Type()&fs.ModeSymlink != 0 {
+ return nil
+ }
+ if entry.IsDir() && skipDirs[entry.Name()] {
+ return fs.SkipDir
+ }
+
+ info, err := entry.Info()
+ if err != nil {
+ return fmt.Errorf("inspect project file: %w", err)
+ }
+
+ // fs.WalkDir visits entries in deterministic lexical order, so hashing
+ // in visit order yields a stable revision.
+ isProtected := protected[rel]
+ writeProjectFileRevisionEntryInternal(revisionHash, rel, info, entry.IsDir(), isProtected)
+
+ if isProtected {
+ return nil
+ }
+
+ size := info.Size()
+ if entry.IsDir() {
+ size = 0
+ }
+ files = append(files, project.ProjectFile{
+ Path: filepath.Join(projectAbs, filepath.FromSlash(rel)),
+ RelativePath: rel,
+ Name: entry.Name(),
+ IsDirectory: entry.IsDir(),
+ Size: size,
+ ModTime: info.ModTime(),
+ Protected: false,
+ })
+
+ return nil
+ })
+ if err != nil {
+ return nil, "", err
+ }
+
+ slices.SortFunc(files, func(a, b project.ProjectFile) int {
+ if a.IsDirectory != b.IsDirectory {
+ if a.IsDirectory {
+ return -1
+ }
+ return 1
+ }
+ return strings.Compare(a.RelativePath, b.RelativePath)
+ })
+
+ return files, hex.EncodeToString(revisionHash.Sum(nil)), nil
+}
+
+func ApplyProjectFileDrafts(projectPath string, drafts []project.ProjectFileDraft, opts ProjectFileApplyOptions) error {
+ if len(drafts) == 0 {
+ return nil
+ }
+
+ changes := make([]project.ProjectFileChange, 0, len(drafts))
+ for _, draft := range drafts {
+ operation := project.FileOpCreateFile
+ var content *string
+ if draft.IsDirectory {
+ operation = project.FileOpCreateFolder
+ } else {
+ contentValue := draft.Content
+ content = &contentValue
+ }
+ changes = append(changes, project.ProjectFileChange{
+ Operation: operation,
+ RelativePath: draft.RelativePath,
+ Content: content,
+ })
+ }
+
+ opts.ExpectedRevision = ""
+ return ApplyProjectFileChanges(projectPath, changes, opts)
+}
+
+func ApplyProjectFileChanges(projectPath string, changes []project.ProjectFileChange, opts ProjectFileApplyOptions) error {
+ if len(changes) == 0 {
+ return nil
+ }
+
+ if opts.ExpectedRevision != "" {
+ _, currentRevision, err := ReadProjectFileTree(projectPath, opts.MaxDepth, opts.SkipDirectories, opts.ComposeFileName)
+ if err != nil {
+ return fmt.Errorf("read project file tree revision: %w", err)
+ }
+ if currentRevision != opts.ExpectedRevision {
+ return ErrProjectFileRevisionConflict
+ }
+ }
+
+ root, err := os.OpenRoot(projectPath)
+ if err != nil {
+ return fmt.Errorf("open project directory: %w", err)
+ }
+ defer func() { _ = root.Close() }()
+
+ protected := ProtectedProjectFilePaths(opts.ComposeFileName)
+ for _, change := range changes {
+ if err := applyProjectFileChangeInternal(root, protected, change); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func ProtectedProjectFilePaths(composeFileName string) map[string]bool {
+ protected := map[string]bool{
+ EffectiveEnvFileName: true,
+ GitSourceEnvFileName: true,
+ OverrideEnvFileName: true,
+ }
+ for _, candidate := range ComposeFileCandidates() {
+ protected[candidate] = true
+ }
+ if trimmed := strings.TrimSpace(composeFileName); trimmed != "" {
+ protected[path.Base(filepath.ToSlash(trimmed))] = true
+ }
+ 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)
+ if err != nil {
+ return fmt.Errorf("invalid project file path: %w", err)
+ }
+
+ switch change.Operation {
+ case project.FileOpCreateFile:
+ if change.Content == nil {
+ return errors.New("file content is required")
+ }
+ return createManagedProjectFileInternal(root, protected, rel, *change.Content)
+ case project.FileOpCreateFolder:
+ return createManagedProjectFolderInternal(root, protected, rel)
+ case project.FileOpUpdateFile:
+ if change.Content == nil {
+ return errors.New("file content is required")
+ }
+ return updateManagedProjectFileInternal(root, protected, rel, *change.Content)
+ case project.FileOpRename:
+ newName, err := ValidateProjectFileName(change.NewName)
+ if err != nil {
+ return fmt.Errorf("invalid project file name: %w", err)
+ }
+ return renameManagedProjectPathInternal(root, protected, rel, newName)
+ case project.FileOpMove:
+ return moveManagedProjectPathInternal(root, protected, rel, change.NewParentPath)
+ case project.FileOpDelete:
+ return deleteManagedProjectPathInternal(root, protected, rel, change.Recursive)
+ default:
+ return fmt.Errorf("unsupported project file operation %q", change.Operation)
+ }
+}
+
+func createManagedProjectFileInternal(root *os.Root, protected map[string]bool, rel, content string) error {
+ if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {
+ return err
+ }
+ if err := validateProjectTextContentInternal(content); err != nil {
+ return err
+ }
+ if err := ensureProjectPathHasNoSymlinkInternal(root, path.Dir(rel)); err != nil {
+ return err
+ }
+
+ if err := root.MkdirAll(path.Dir(rel), pkgutils.DirPerm); err != nil {
+ return mapProjectRootErrorInternal("create parent directory", err)
+ }
+
+ // O_EXCL makes the exists-check-and-create atomic; os.Root confines the
+ // path to the project directory in the kernel.
+ 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 fmt.Errorf("project file already exists: %s", rel)
+ }
+ return mapProjectRootErrorInternal("create project file", err)
+ }
+ _, writeErr := f.WriteString(content)
+ if closeErr := f.Close(); writeErr == nil {
+ writeErr = closeErr
+ }
+ if writeErr != nil {
+ return fmt.Errorf("create project file: %w", writeErr)
+ }
+ return nil
+}
+
+func createManagedProjectFolderInternal(root *os.Root, protected map[string]bool, rel string) error {
+ if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {
+ return err
+ }
+ if err := ensureProjectPathHasNoSymlinkInternal(root, rel); err != nil {
+ return err
+ }
+
+ if _, err := root.Lstat(rel); err == nil {
+ return fmt.Errorf("project folder already exists: %s", rel)
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return mapProjectRootErrorInternal("inspect project folder", err)
+ }
+ if err := root.MkdirAll(rel, pkgutils.DirPerm); err != nil {
+ return mapProjectRootErrorInternal("create project folder", err)
+ }
+ return nil
+}
+
+func updateManagedProjectFileInternal(root *os.Root, protected map[string]bool, rel, content string) error {
+ if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {
+ return err
+ }
+ if err := validateProjectTextContentInternal(content); err != nil {
+ return err
+ }
+ if err := ensureProjectPathHasNoSymlinkInternal(root, rel); err != nil {
+ return err
+ }
+
+ info, err := root.Lstat(rel)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("project file not found: %s", rel)
+ }
+ return mapProjectRootErrorInternal("inspect project file", err)
+ }
+ if info.IsDir() {
+ return fmt.Errorf("path is a folder: %s", rel)
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("symlink files are not supported: %w", ErrProjectFileSymlinkPath)
+ }
+
+ if err := root.WriteFile(rel, []byte(content), pkgutils.FilePerm); err != nil {
+ return mapProjectRootErrorInternal("update project file", err)
+ }
+ return nil
+}
+
+func renameManagedProjectPathInternal(root *os.Root, protected map[string]bool, rel, newName string) error {
+ if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {
+ return err
+ }
+ if err := ensureProjectPathHasNoSymlinkInternal(root, rel); err != nil {
+ return err
+ }
+
+ info, err := root.Lstat(rel)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("project path not found: %s", rel)
+ }
+ return mapProjectRootErrorInternal("inspect project path", err)
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("symlink paths are not supported: %w", ErrProjectFileSymlinkPath)
+ }
+
+ targetRel := path.Join(path.Dir(rel), newName)
+ if err := ensureWritableProjectRelPathInternal(protected, targetRel); err != nil {
+ return err
+ }
+ if err := ensureProjectPathHasNoSymlinkInternal(root, path.Dir(targetRel)); err != nil {
+ return err
+ }
+ if _, err := root.Lstat(targetRel); err == nil {
+ return fmt.Errorf("project path already exists: %s", targetRel)
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return mapProjectRootErrorInternal("inspect project path", err)
+ }
+
+ if err := root.Rename(rel, targetRel); err != nil {
+ return mapProjectRootErrorInternal("rename project path", err)
+ }
+ return nil
+}
+
+func normalizeOptionalProjectParentPathInternal(input string) (string, error) {
+ if strings.TrimSpace(input) == "" {
+ return "", nil
+ }
+ return NormalizeProjectRelativePath(input)
+}
+
+func moveManagedProjectPathInternal(root *os.Root, protected map[string]bool, rel, newParentPath string) error {
+ if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {
+ return err
+ }
+ if err := ensureProjectPathHasNoSymlinkInternal(root, rel); err != nil {
+ return err
+ }
+
+ parentRel, err := normalizeOptionalProjectParentPathInternal(newParentPath)
+ if err != nil {
+ return fmt.Errorf("invalid project parent path: %w", err)
+ }
+ if parentRel != "" {
+ if err := ensureWritableProjectRelPathInternal(protected, parentRel); err != nil {
+ return err
+ }
+ }
+
+ sourceInfo, err := root.Lstat(rel)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("project path not found: %s", rel)
+ }
+ return mapProjectRootErrorInternal("inspect project path", err)
+ }
+ if sourceInfo.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("symlink paths are not supported: %w", ErrProjectFileSymlinkPath)
+ }
+ if sourceInfo.IsDir() && parentRel != "" && projectFilePathMatchesInternal(parentRel, rel) {
+ return errors.New("folder cannot be moved into itself or a descendant")
+ }
+
+ if err := validateProjectMoveParentInternal(root, parentRel); err != nil {
+ return err
+ }
+
+ targetRel := path.Base(rel)
+ if parentRel != "" {
+ targetRel = path.Join(parentRel, path.Base(rel))
+ }
+ if targetRel == rel {
+ return errors.New("project path is already in the destination folder")
+ }
+ if err := ensureWritableProjectRelPathInternal(protected, targetRel); err != nil {
+ return err
+ }
+ if err := ensureProjectPathHasNoSymlinkInternal(root, path.Dir(targetRel)); err != nil {
+ return err
+ }
+ if _, err := root.Lstat(targetRel); err == nil {
+ return fmt.Errorf("project path already exists: %s", targetRel)
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return mapProjectRootErrorInternal("inspect project path", err)
+ }
+
+ if err := root.Rename(rel, targetRel); err != nil {
+ return mapProjectRootErrorInternal("move project path", err)
+ }
+ return nil
+}
+
+func validateProjectMoveParentInternal(root *os.Root, parentRel string) error {
+ if parentRel == "" {
+ return nil
+ }
+ if err := ensureProjectPathHasNoSymlinkInternal(root, parentRel); err != nil {
+ return err
+ }
+
+ parentInfo, err := root.Lstat(parentRel)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("destination folder not found: %s", parentRel)
+ }
+ return mapProjectRootErrorInternal("inspect destination folder", err)
+ }
+ if parentInfo.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("symlink destination folders are not supported: %w", ErrProjectFileSymlinkPath)
+ }
+ if !parentInfo.IsDir() {
+ return fmt.Errorf("destination path is not a folder: %s", parentRel)
+ }
+ return nil
+}
+
+func deleteManagedProjectPathInternal(root *os.Root, protected map[string]bool, rel string, recursive bool) error {
+ if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {
+ return err
+ }
+ if err := ensureProjectPathHasNoSymlinkInternal(root, rel); err != nil {
+ return err
+ }
+
+ info, err := root.Lstat(rel)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("project path not found: %s", rel)
+ }
+ return mapProjectRootErrorInternal("inspect project path", err)
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("symlink paths are not supported: %w", ErrProjectFileSymlinkPath)
+ }
+ if info.IsDir() && !recursive {
+ empty, err := isDirectoryEmptyInternal(root, rel)
+ if err != nil {
+ return err
+ }
+ if !empty {
+ return errors.New("folder is not empty")
+ }
+ }
+
+ if info.IsDir() {
+ if err := root.RemoveAll(rel); err != nil {
+ return mapProjectRootErrorInternal("delete project folder", err)
+ }
+ return nil
+ }
+ if err := root.Remove(rel); err != nil {
+ return mapProjectRootErrorInternal("delete project file", err)
+ }
+ return nil
+}
+
+func mapProjectRootErrorInternal(action string, err error) error {
+ return fmt.Errorf("%s: %w", action, err)
+}
+
+func ensureProjectPathHasNoSymlinkInternal(root *os.Root, rel string) error {
+ cleaned := path.Clean(rel)
+ if cleaned == "." || cleaned == "" {
+ return nil
+ }
+
+ current := ""
+ for segment := range strings.SplitSeq(cleaned, "/") {
+ if current == "" {
+ current = segment
+ } else {
+ current = path.Join(current, segment)
+ }
+
+ info, err := root.Lstat(current)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ return mapProjectRootErrorInternal("inspect project path", err)
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("symlink paths are not supported: %w", ErrProjectFileSymlinkPath)
+ }
+ }
+ return nil
+}
+
+func ensureWritableProjectRelPathInternal(protected map[string]bool, rel string) error {
+ if rel == "." || rel == "" {
+ return errors.New("project root cannot be modified")
+ }
+ rootName, _, _ := strings.Cut(rel, "/")
+ if protected[rel] || protected[rootName] {
+ return fmt.Errorf("%w: %s", ErrProjectFileProtectedPath, 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 fmt.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 nil
+}
+
+func isDirectoryEmptyInternal(root *os.Root, rel string) (bool, error) {
+ f, err := root.Open(rel)
+ if err != nil {
+ return false, fmt.Errorf("open folder: %w", err)
+ }
+ defer func() { _ = f.Close() }()
+
+ _, err = f.Readdirnames(1)
+ if errors.Is(err, io.EOF) {
+ return true, nil
+ }
+ if err != nil {
+ return false, fmt.Errorf("read folder: %w", err)
+ }
+ 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/project_files_test.go
new file mode 100644
index 000000000..822786923
--- /dev/null
+++ b/backend/pkg/projects/project_files_test.go
@@ -0,0 +1,341 @@
+package projects
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/getarcaneapp/arcane/types/v2/project"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestReadProjectFileTree_ExcludesProtectedFilesAndReturnsFolders(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, ".env"), []byte("APP_VALUE=sample\n"), 0o644))
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, ".env.git"), []byte("APP_VALUE=git\n"), 0o644))
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "project.env"), []byte("APP_VALUE=local\n"), 0o644))
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "README.md"), []byte("hello\n"), 0o644))
+ require.NoError(t, os.MkdirAll(filepath.Join(projectDir, "config", "nested"), 0o755))
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "config", "app.yaml"), []byte("value: true\n"), 0o644))
+ 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")
+ require.NoError(t, err)
+ require.NotEmpty(t, revision)
+
+ relativePaths := make([]string, 0, len(files))
+ for _, file := range files {
+ relativePaths = append(relativePaths, file.RelativePath)
+ }
+
+ 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) {
+ t.Parallel()
+
+ projectDir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte("services: {}\n"), 0o644))
+ 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")
+ require.NoError(t, err)
+ assert.NotEmpty(t, revision)
+ assert.Empty(t, files)
+}
+
+func TestReadProjectFileTree_UseScanDepthSentinelUsesFileTreeMaxDepth(t *testing.T) {
+ projectDir := t.TempDir()
+ t.Setenv("PROJECT_FILE_TREE_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")
+ require.NoError(t, err)
+
+ relativePaths := make([]string, 0, len(files))
+ for _, file := range files {
+ relativePaths = append(relativePaths, file.RelativePath)
+ }
+
+ assert.Contains(t, relativePaths, "level1")
+ assert.Contains(t, relativePaths, filepath.ToSlash(filepath.Join("level1", "visible.txt")))
+ assert.Contains(t, relativePaths, filepath.ToSlash(filepath.Join("level1", "level2")))
+ assert.NotContains(t, relativePaths, filepath.ToSlash(filepath.Join("level1", "level2", "hidden.txt")))
+}
+
+func TestApplyProjectFileChanges_RejectsUnsafePathsAndProtectedFiles(t *testing.T) {
+ t.Parallel()
+
+ projectDir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte("services: {}\n"), 0o644))
+
+ content := "safe\n"
+ protectedDescendantContent := "bad\n"
+ binaryContent := string([]byte{0})
+ testCases := []struct {
+ name string
+ change project.ProjectFileChange
+ }{
+ {
+ name: "traversal",
+ change: project.ProjectFileChange{
+ Operation: "create_file",
+ RelativePath: "../escape.txt",
+ Content: &content,
+ },
+ },
+ {
+ name: "protected compose",
+ change: project.ProjectFileChange{
+ Operation: "delete",
+ RelativePath: "compose.yaml",
+ },
+ },
+ {
+ name: "move protected compose",
+ change: project.ProjectFileChange{
+ Operation: "move",
+ RelativePath: "compose.yaml",
+ NewParentPath: "config",
+ },
+ },
+ {
+ name: "protected compose descendant",
+ change: project.ProjectFileChange{
+ Operation: "create_file",
+ RelativePath: "compose.yaml/child.yaml",
+ Content: &protectedDescendantContent,
+ },
+ },
+ {
+ name: "binary content",
+ change: project.ProjectFileChange{
+ Operation: "create_file",
+ RelativePath: "binary.txt",
+ Content: &binaryContent,
+ },
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ err := ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{tc.change}, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})
+ require.Error(t, err)
+ })
+ }
+}
+
+func TestApplyProjectFileChanges_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{
+ {Operation: "delete", RelativePath: "compose.yaml"},
+ }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})
+ require.Error(t, err)
+ assert.ErrorIs(t, err, ErrProjectFileProtectedPath)
+
+ targetPath := filepath.Join(projectDir, "target.txt")
+ linkPath := filepath.Join(projectDir, "link.txt")
+ require.NoError(t, os.WriteFile(targetPath, []byte("target\n"), 0o644))
+ if err := os.Symlink(targetPath, linkPath); err != nil {
+ 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"})
+ require.Error(t, err)
+ assert.ErrorIs(t, err, ErrProjectFileSymlinkPath)
+
+ outsideDir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(outsideDir, "outside.txt"), []byte("outside\n"), 0o644))
+ linkDirPath := filepath.Join(projectDir, "link-dir")
+ if err := os.Symlink(outsideDir, linkDirPath); err != nil {
+ 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"})
+ require.Error(t, err)
+ assert.ErrorIs(t, err, ErrProjectFileSymlinkPath)
+}
+
+func TestMapProjectRootErrorInternal_DoesNotClassifyByErrorMessage(t *testing.T) {
+ t.Parallel()
+
+ err := mapProjectRootErrorInternal("inspect project path", &os.PathError{
+ Op: "lstat",
+ Path: "notes.txt",
+ Err: errors.New("disk check escapes normal retry path"),
+ })
+
+ require.Error(t, err)
+ assert.NotErrorIs(t, err, ErrProjectFileOutsideProjectDirectory)
+}
+
+func TestApplyProjectFileChanges_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")
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "notes.txt"), []byte("changed elsewhere\n"), 0o644))
+
+ content := "new\n"
+ err = ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{
+ {Operation: "update_file", RelativePath: "notes.txt", Content: &content},
+ }, ProjectFileApplyOptions{
+ ExpectedRevision: revision,
+ ComposeFileName: "compose.yaml",
+ })
+
+ require.Error(t, err)
+ assert.True(t, errors.Is(err, ErrProjectFileRevisionConflict))
+}
+
+func TestApplyProjectFileChanges_AppliesOrderedTextFileOperations(t *testing.T) {
+ t.Parallel()
+
+ projectDir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte("services: {}\n"), 0o644))
+
+ content := "hello\n"
+ updated := "updated\n"
+ err := ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{
+ {Operation: "create_folder", RelativePath: "config"},
+ {Operation: "create_file", RelativePath: "config/app.yaml", Content: &content},
+ {Operation: "update_file", RelativePath: "config/app.yaml", Content: &updated},
+ {Operation: "rename", RelativePath: "config/app.yaml", NewName: "renamed.yaml"},
+ }, ProjectFileApplyOptions{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))
+}
+
+func TestApplyProjectFileChanges_MovesProjectPaths(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.MkdirAll(filepath.Join(projectDir, "config", "nested"), 0o755))
+ require.NoError(t, os.MkdirAll(filepath.Join(projectDir, "archive"), 0o755))
+ 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{
+ {Operation: "move", RelativePath: "config/app.yaml", NewParentPath: "archive"},
+ {Operation: "move", RelativePath: "config/nested"},
+ }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})
+ require.NoError(t, err)
+
+ assert.NoFileExists(t, filepath.Join(projectDir, "config", "app.yaml"))
+ assert.FileExists(t, filepath.Join(projectDir, "archive", "app.yaml"))
+ assert.NoDirExists(t, filepath.Join(projectDir, "config", "nested"))
+ assert.FileExists(t, filepath.Join(projectDir, "nested", "child.txt"))
+}
+
+func TestApplyProjectFileChanges_RejectsInvalidMoves(t *testing.T) {
+ t.Parallel()
+
+ testCases := []struct {
+ name string
+ relativePath string
+ newParentPath string
+ wantError string
+ }{
+ {
+ name: "duplicate destination",
+ relativePath: "config/app.yaml",
+ newParentPath: "archive",
+ wantError: "project path already exists",
+ },
+ {
+ name: "folder into descendant",
+ relativePath: "config",
+ newParentPath: "config/nested",
+ wantError: "folder cannot be moved into itself or a descendant",
+ },
+ {
+ name: "missing destination folder",
+ relativePath: "config/app.yaml",
+ newParentPath: "missing",
+ wantError: "destination folder not found",
+ },
+ {
+ name: "same destination",
+ relativePath: "config/app.yaml",
+ newParentPath: "config",
+ wantError: "already in the destination folder",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(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.MkdirAll(filepath.Join(projectDir, "config", "nested"), 0o755))
+ require.NoError(t, os.MkdirAll(filepath.Join(projectDir, "archive"), 0o755))
+ 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{
+ {Operation: "move", RelativePath: tc.relativePath, NewParentPath: tc.newParentPath},
+ }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), tc.wantError)
+ })
+ }
+}
+
+func TestApplyProjectFileChanges_RequiresRecursiveForNonEmptyFolderDelete(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.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{
+ {Operation: "delete", RelativePath: "config"},
+ }, ProjectFileApplyOptions{ComposeFileName: "compose.yaml"})
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "folder is not empty")
+
+ err = ApplyProjectFileChanges(projectDir, []project.ProjectFileChange{
+ {Operation: "delete", RelativePath: "config", Recursive: true},
+ }, ProjectFileApplyOptions{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) {
+ t.Parallel()
+
+ _, err := ValidateProjectFileName(strings.Join([]string{"folder", "name"}, string(filepath.Separator)))
+ require.Error(t, err)
+}
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 0402bb12e..a8f5dacfa 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -2717,9 +2717,8 @@
"common_mounts": "mounts",
"common_image_id": "Image ID",
"common_entrypoint": "Entrypoint",
- "classic": "Classic",
- "tree_view": "Tree View",
- "project_view_description": "Switch between classic side-by-side layout and tree view",
+ "workspace": "Workspace",
+ "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.",
"environments_api_key": "API Key",
@@ -2735,6 +2734,47 @@
"environments_generate_config": "Generate Agent Configuration",
"project_files": "Project Files",
"project_includes": "Includes",
+ "project_files_empty": "No project files",
+ "project_file_new_file": "New File",
+ "project_file_new_folder": "New Folder",
+ "project_file_upload_file": "Upload File",
+ "project_file_create_file_title": "Create File",
+ "project_file_create_folder_title": "Create Folder",
+ "project_file_upload_title": "Upload File",
+ "project_file_upload_action": "Upload",
+ "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.",
+ "project_file_rename_title": "Rename",
+ "project_file_rename_action": "Rename",
+ "project_file_move_title": "Move",
+ "project_file_move_action": "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_label": "Name",
+ "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_title": "Delete {name}",
+ "project_file_delete_confirm": "Delete {name} from the project files? This will be applied when you save.",
+ "project_file_delete_label": "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_file_folder_selected": "Select or create a file in this folder.",
+ "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",
diff --git a/frontend/package.json b/frontend/package.json
index 2f1ff9aaa..8bc8d51f6 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -15,6 +15,9 @@
},
"dependencies": {
"@codemirror/autocomplete": "^6.20.3",
+ "@codemirror/lang-javascript": "^6.2.5",
+ "@codemirror/lang-json": "^6.0.2",
+ "@codemirror/lang-markdown": "^6.5.0",
"@codemirror/lang-yaml": "^6.1.3",
"@codemirror/language": "^6.12.3",
"@codemirror/legacy-modes": "^6.5.3",
diff --git a/frontend/src/lib/components/code-editor/analysis/types.ts b/frontend/src/lib/components/code-editor/analysis/types.ts
index 7e4b299c7..5b6cb35ff 100644
--- a/frontend/src/lib/components/code-editor/analysis/types.ts
+++ b/frontend/src/lib/components/code-editor/analysis/types.ts
@@ -1,6 +1,17 @@
import type { Diagnostic } from '@codemirror/lint';
-export type CodeLanguage = 'yaml' | 'env';
+export type CodeLanguage =
+ | 'yaml'
+ | 'env'
+ | 'json'
+ | 'toml'
+ | 'dockerfile'
+ | 'shell'
+ | 'javascript'
+ | 'typescript'
+ | 'markdown'
+ | 'plaintext';
+export type CodeValidationMode = 'compose' | 'env' | 'none';
export type SchemaStatus = 'ready' | 'cached' | 'unavailable';
diff --git a/frontend/src/lib/components/code-editor/editor.svelte b/frontend/src/lib/components/code-editor/editor.svelte
index 7115f3753..27ead8024 100644
--- a/frontend/src/lib/components/code-editor/editor.svelte
+++ b/frontend/src/lib/components/code-editor/editor.svelte
@@ -2,9 +2,15 @@
import CodeMirror from 'svelte-codemirror-editor';
import * as Command from '$lib/components/ui/command';
import { autocompletion, type Completion, type CompletionContext } from '@codemirror/autocomplete';
+ import { javascript } from '@codemirror/lang-javascript';
+ import { json } from '@codemirror/lang-json';
+ import { markdown } from '@codemirror/lang-markdown';
import { yaml } from '@codemirror/lang-yaml';
import { StreamLanguage, foldAll, unfoldAll, foldKeymap } from '@codemirror/language';
+ import { dockerFile } from '@codemirror/legacy-modes/mode/dockerfile';
import { properties } from '@codemirror/legacy-modes/mode/properties';
+ import { shell } from '@codemirror/legacy-modes/mode/shell';
+ import { toml } from '@codemirror/legacy-modes/mode/toml';
import {
linter,
lintGutter,
@@ -27,7 +33,7 @@
import { analyzeEnvContent } from './analysis/env-analysis';
import type { YamlPositionContext } from './analysis/compose-analysis';
import type { ComposeSchemaContext } from './analysis/compose-schema';
- import type { CodeLanguage, DiagnosticSummary, EditorContext, OutlineItem } from './analysis/types';
+ import type { CodeLanguage, CodeValidationMode, DiagnosticSummary, EditorContext, OutlineItem } from './analysis/types';
type ComposeAnalysisModule = typeof import('./analysis/compose-analysis');
type ComposeSchemaModule = typeof import('./analysis/compose-schema');
@@ -48,6 +54,7 @@
let {
value = $bindable(''),
language = 'yaml' as CodeLanguage,
+ validationMode,
placeholder = '',
readOnly = false,
fontSize = '12px',
@@ -65,6 +72,7 @@
}: {
value?: string;
language?: CodeLanguage;
+ validationMode?: CodeValidationMode;
placeholder?: string;
readOnly?: boolean;
fontSize?: string;
@@ -92,12 +100,31 @@
const storageKey = $derived(fileId ? `arcane.editor.state:${fileId}` : null);
const isDiffActive = $derived(Boolean(enableDiff && diffOpen && originalValue !== undefined));
+ const effectiveValidationMode = $derived(validationMode ?? defaultValidationModeForLanguage(language));
const effectiveEditorContext = $derived({
envContent: editorContext?.envContent ?? '',
composeContents: editorContext?.composeContents ?? [],
globalVariables: editorContext?.globalVariables ?? {}
});
+ function defaultValidationModeForLanguage(lang: CodeLanguage): CodeValidationMode {
+ switch (lang) {
+ case 'yaml':
+ return 'compose';
+ case 'env':
+ return 'env';
+ case 'json':
+ case 'toml':
+ case 'dockerfile':
+ case 'shell':
+ case 'javascript':
+ case 'typescript':
+ case 'markdown':
+ case 'plaintext':
+ return 'none';
+ }
+ }
+
const mergeActionParams = $derived({
diffActive: isDiffActive,
language,
@@ -170,6 +197,20 @@
});
}
+ function markValidationNotRequiredReady() {
+ if (!readOnly && effectiveValidationMode !== 'none') return;
+ hasErrors = false;
+ validationReady = true;
+ activeOutlineItems = [];
+ updateSummary({
+ errors: 0,
+ warnings: 0,
+ infos: 0,
+ hints: 0,
+ validationReady: true
+ });
+ }
+
function updateCursorSummary(view: EditorView) {
const position = view.state.selection.main.head;
const line = view.state.doc.lineAt(position);
@@ -283,7 +324,7 @@
if (parsed.errors.length === 0) {
formatted = parsed.toString({ indent: 2, lineWidth: 0 });
}
- } else {
+ } else if (language === 'env') {
formatted = formatEnvContent(current);
}
@@ -379,7 +420,7 @@
};
const composeCompletionSource = async (context: CompletionContext) => {
- if (language !== 'yaml' || readOnly) return null;
+ if (language !== 'yaml' || effectiveValidationMode !== 'compose' || readOnly) return null;
const source = context.state.doc.toString();
const analysisModule = await loadComposeAnalysisModule();
const yamlContext = analysisModule.findYamlPositionContext(source, context.pos);
@@ -399,7 +440,7 @@
};
const envCompletionSource = async (context: CompletionContext) => {
- if (language !== 'env' || readOnly) return null;
+ if (language !== 'env' || effectiveValidationMode !== 'env' || readOnly) return null;
const before = context.matchBefore(/[A-Za-z0-9_.-]*/);
if (!context.explicit && (!before || before.from === before.to)) return null;
@@ -433,7 +474,7 @@
const yamlHover = hoverTooltip(
async (view, position) => {
- if (language !== 'yaml' || isSchemaHoverSuppressed(view)) return null;
+ if (language !== 'yaml' || effectiveValidationMode !== 'compose' || isSchemaHoverSuppressed(view)) return null;
const source = view.state.doc.toString();
const analysisModule = await loadComposeAnalysisModule();
const variableRef = analysisModule.resolveVariableSourceAtPosition(source, position, effectiveEditorContext);
@@ -576,7 +617,7 @@
]);
const yamlLinter: LintSource = async (view): Promise<Diagnostic[]> => {
- if (readOnly) {
+ if (readOnly || effectiveValidationMode !== 'compose') {
validationReady = true;
hasErrors = false;
return [];
@@ -598,7 +639,7 @@
};
const envLinter: LintSource = async (view): Promise<Diagnostic[]> => {
- if (readOnly) {
+ if (readOnly || effectiveValidationMode !== 'env') {
validationReady = true;
hasErrors = false;
return [];
@@ -618,9 +659,42 @@
const enterIndentKeymaps: Record<CodeLanguage, Extension> = {
yaml: createEnterIndentKeymap('yaml'),
- env: createEnterIndentKeymap('env')
+ env: createEnterIndentKeymap('env'),
+ json: createEnterIndentKeymap('json'),
+ toml: createEnterIndentKeymap('toml'),
+ dockerfile: createEnterIndentKeymap('dockerfile'),
+ shell: createEnterIndentKeymap('shell'),
+ javascript: createEnterIndentKeymap('javascript'),
+ typescript: createEnterIndentKeymap('typescript'),
+ markdown: createEnterIndentKeymap('markdown'),
+ plaintext: createEnterIndentKeymap('plaintext')
};
+ function getBasicLanguageExtension(lang: CodeLanguage): Extension[] {
+ switch (lang) {
+ case 'yaml':
+ return [yaml()];
+ case 'env':
+ return [StreamLanguage.define(properties)];
+ case 'json':
+ return [json()];
+ case 'toml':
+ return [StreamLanguage.define(toml)];
+ case 'dockerfile':
+ return [StreamLanguage.define(dockerFile)];
+ case 'shell':
+ return [StreamLanguage.define(shell)];
+ case 'javascript':
+ return [javascript({ jsx: true })];
+ case 'typescript':
+ return [javascript({ typescript: true, jsx: true })];
+ case 'markdown':
+ return [markdown()];
+ case 'plaintext':
+ return [];
+ }
+ }
+
function getLanguageExtension(lang: CodeLanguage, options: { lightweight?: boolean } = {}): Extension[] {
const lightweight = options.lightweight === true;
const extensions: Extension[] = [editorLifecycleExtension, selectionHoverGuardExtension, shortcutKeymapExtension];
@@ -631,8 +705,8 @@
switch (lang) {
case 'yaml':
- extensions.push(yaml());
- if (!readOnly && !lightweight) {
+ extensions.push(...getBasicLanguageExtension(lang));
+ if (!readOnly && !lightweight && effectiveValidationMode === 'compose') {
extensions.push(
lintGutter(),
linter(yamlLinter, { delay: 140 }),
@@ -645,8 +719,8 @@
}
break;
case 'env':
- extensions.push(StreamLanguage.define(properties));
- if (!readOnly && !lightweight) {
+ extensions.push(...getBasicLanguageExtension(lang));
+ if (!readOnly && !lightweight && effectiveValidationMode === 'env') {
extensions.push(
lintGutter(),
linter(envLinter, { delay: 140 }),
@@ -657,11 +731,26 @@
);
}
break;
+ case 'json':
+ case 'toml':
+ case 'dockerfile':
+ case 'shell':
+ case 'javascript':
+ case 'typescript':
+ case 'markdown':
+ extensions.push(...getBasicLanguageExtension(lang));
+ break;
+ case 'plaintext':
+ break;
}
return extensions;
}
+ function getReadonlyLanguageExtension(lang: CodeLanguage): Extension[] {
+ return getBasicLanguageExtension(lang);
+ }
+
const theme = $derived.by(() => {
$configStore;
return mode.current === 'dark' ? arcaneDarkInit() : arcaneLightInit();
@@ -670,6 +759,7 @@
const mergeHostAction = createMergeHostAction({
getTheme: () => theme,
getLanguageExtension,
+ getReadonlyLanguageExtension,
onValueChange: (nextValue) => {
value = nextValue;
},
@@ -678,6 +768,7 @@
restoreEditorState(view);
updateCursorSummary(view);
markReadOnlyReady();
+ markValidationNotRequiredReady();
}
});
@@ -706,6 +797,7 @@
restoreEditorState(view);
updateCursorSummary(view);
markReadOnlyReady();
+ markValidationNotRequiredReady();
}
}
diff --git a/frontend/src/lib/components/code-editor/merge-editor.ts b/frontend/src/lib/components/code-editor/merge-editor.ts
index 0f21a84d2..5db3b50a6 100644
--- a/frontend/src/lib/components/code-editor/merge-editor.ts
+++ b/frontend/src/lib/components/code-editor/merge-editor.ts
@@ -1,6 +1,3 @@
-import { yaml } from '@codemirror/lang-yaml';
-import { StreamLanguage } from '@codemirror/language';
-import { properties } from '@codemirror/legacy-modes/mode/properties';
import { EditorState, type Extension } from '@codemirror/state';
import { MergeView } from '@codemirror/merge';
import { EditorView } from '@codemirror/view';
@@ -17,12 +14,13 @@ export type MergeActionParams = {
type CreateMergeHostActionOptions = {
getTheme: () => Extension;
getLanguageExtension: (lang: CodeLanguage, options?: { lightweight?: boolean }) => Extension[];
+ getReadonlyLanguageExtension: (lang: CodeLanguage) => Extension[];
onValueChange: (nextValue: string) => void;
onPrimaryViewReady: (view: EditorView) => void;
};
export function createMergeHostAction(options: CreateMergeHostActionOptions): Action<HTMLDivElement, MergeActionParams> {
- const { getTheme, getLanguageExtension, onValueChange, onPrimaryViewReady } = options;
+ const { getTheme, getLanguageExtension, getReadonlyLanguageExtension, onValueChange, onPrimaryViewReady } = options;
return (node, params) => {
let currentParams = params;
@@ -56,7 +54,7 @@ export function createMergeHostAction(options: CreateMergeHostActionOptions): Ac
},
b: {
doc: currentParams.baseline,
- extensions: [currentParams.language === 'yaml' ? yaml() : StreamLanguage.define(properties), ...readonlyExtension]
+ extensions: [...getReadonlyLanguageExtension(currentParams.language), ...readonlyExtension]
}
});
diff --git a/frontend/src/lib/components/resizable-split.svelte b/frontend/src/lib/components/resizable-split.svelte
index 68fc1ddcc..5e6f88b38 100644
--- a/frontend/src/lib/components/resizable-split.svelte
+++ b/frontend/src/lib/components/resizable-split.svelte
@@ -10,11 +10,13 @@
second: Snippet;
size?: number | null;
minSize?: number;
+ maxSize?: number;
minSecondSize?: number;
defaultRatio?: number;
allowCollapse?: boolean;
collapseThreshold?: number;
handleSize?: number;
+ variant?: 'default' | 'flush';
stackBelow?: number;
class?: string;
firstClass?: string;
@@ -31,11 +33,13 @@
second,
size = $bindable<number | null>(null),
minSize = 240,
+ maxSize,
minSecondSize = 240,
defaultRatio = 0.5,
allowCollapse = true,
collapseThreshold = 28,
handleSize = 8,
+ variant = 'default',
stackBelow,
class: className = '',
firstClass = '',
@@ -68,12 +72,17 @@
const clampSize = (value: number, minValue: number, maxValue: number) => Math.min(Math.max(value, minValue), maxValue);
+ const layoutHandleSize = $derived(variant === 'flush' ? 1 : handleSize);
+
const getAvailableWidth = () => {
if (!containerRef) return 0;
- return Math.max(0, containerRef.getBoundingClientRect().width - handleSize);
+ return Math.max(0, containerRef.getBoundingClientRect().width - layoutHandleSize);
};
- const getMaxNormalSize = () => Math.max(0, getAvailableWidth() - minSecondSize);
+ const getMaxNormalSize = () => {
+ const base = Math.max(0, getAvailableWidth() - minSecondSize);
+ return maxSize !== undefined ? Math.min(base, maxSize) : base;
+ };
const ensureInitialSize = () => {
if (!containerRef || size !== null) return;
@@ -103,7 +112,7 @@
if (persist) commitSize();
return;
}
- if (allowCollapse && nextSize >= available - collapseThreshold) {
+ if (allowCollapse && maxSize === undefined && nextSize >= available - collapseThreshold) {
collapsedSide = 'second';
size = available;
if (persist) commitSize();
@@ -225,7 +234,10 @@
});
</script>
-<div bind:this={containerRef} class={['flex min-h-0 min-w-0', isStacked && 'flex-col gap-4', className]}>
+<div
+ bind:this={containerRef}
+ class={['flex min-h-0 min-w-0', isStacked && (variant === 'flush' ? 'flex-col' : 'flex-col gap-4'), className]}
+>
<div
class={['min-h-0 min-w-0 overflow-hidden', isStacked ? 'flex-1' : 'flex-none', firstClass]}
style={isStacked ? '' : `width: ${size ?? 0}px;`}
@@ -242,10 +254,15 @@
aria-orientation="vertical"
aria-label={ariaLabel ?? m.common_resize_panels()}
class={['group relative z-20 flex shrink-0 cursor-col-resize items-stretch justify-center overflow-visible', handleClass]}
- style={`width: ${handleSize}px;`}
+ style={`width: ${layoutHandleSize}px;`}
onpointerdown={startResize}
>
- <div class="bg-border group-hover:bg-primary/50 my-2 w-0.5 rounded-full transition-colors"></div>
+ {#if variant === 'flush'}
+ <div class="bg-border group-hover:bg-primary/50 w-px transition-colors"></div>
+ <div class="absolute inset-y-0 -right-1 -left-1"></div>
+ {:else}
+ <div class="bg-border group-hover:bg-primary/50 my-2 w-0.5 rounded-full transition-colors"></div>
+ {/if}
{#if collapsedSide}
<button
class="bg-background border-border text-muted-foreground hover:text-foreground focus-visible:ring-ring absolute inset-0 z-10 m-auto flex size-6 items-center justify-center rounded-full border shadow-sm focus-visible:ring-2 focus-visible:outline-none"
diff --git a/frontend/src/lib/components/ui/tree-view/tree-view-folder.svelte b/frontend/src/lib/components/ui/tree-view/tree-view-folder.svelte
index ec6d8c0e4..0bbc0a850 100644
--- a/frontend/src/lib/components/ui/tree-view/tree-view-folder.svelte
+++ b/frontend/src/lib/components/ui/tree-view/tree-view-folder.svelte
@@ -1,14 +1,19 @@
<script lang="ts">
import * as Collapsible from '$lib/components/ui/collapsible/index.js';
- import { FolderOpenIcon } from '$lib/icons';
+ import { ArrowDownIcon, ArrowRightIcon, FolderOpenIcon } from '$lib/icons';
import { cn } from '$lib/utils';
import type { TreeViewFolderProps } from './types';
- let { name, open = $bindable(true), class: className, icon, children }: TreeViewFolderProps = $props();
+ let { name, open = $bindable(false), class: className, icon, children }: TreeViewFolderProps = $props();
</script>
<Collapsible.Root bind:open>
<Collapsible.Trigger class={cn('flex place-items-center gap-1', className)}>
+ {#if open}
+ <ArrowDownIcon class="size-4" />
+ {:else}
+ <ArrowRightIcon class="size-4" />
+ {/if}
{#if icon}
{@render icon({ name, open })}
{:else}
diff --git a/frontend/src/lib/icons/index.ts b/frontend/src/lib/icons/index.ts
index fa041834e..78fc031ab 100644
--- a/frontend/src/lib/icons/index.ts
+++ b/frontend/src/lib/icons/index.ts
@@ -81,6 +81,9 @@ export { default as InspectIcon } from 'virtual:icons/solar/card-search-linear';
export { default as UpdateIcon } from 'virtual:icons/solar/upload-square-linear';
export { default as RestartIcon } from 'virtual:icons/solar/restart-linear';
export { default as FileTextIcon } from 'virtual:icons/solar/file-text-linear';
+export { default as CreateFileIcon } from 'virtual:icons/lucide/file-plus';
+export { default as CreateFolderIcon } from 'virtual:icons/solar/add-folder-linear';
+export { default as FolderMoveIcon } from 'virtual:icons/lucide/folder-input';
export { default as TemplateIcon } from 'virtual:icons/tabler/template';
export { default as TerminalIcon } from 'virtual:icons/solar/programming-linear';
export { default as StatsIcon } from 'virtual:icons/solar/station-minimalistic-linear';
diff --git a/frontend/src/lib/services/project-service.ts b/frontend/src/lib/services/project-service.ts
index f7a77c94c..2b82e71aa 100644
--- a/frontend/src/lib/services/project-service.ts
+++ b/frontend/src/lib/services/project-service.ts
@@ -2,6 +2,7 @@ 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 { readNdjsonStream } from '$lib/utils/streaming';
import { transformPaginationParams } from '$lib/utils/tables';
import BaseAPIService from './api-service';
@@ -66,12 +67,18 @@ class ProjectService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectName}/down`));
}
- async createProject(projectName: string, composeContent: string, envContent?: string): Promise<Project> {
+ async createProject(
+ projectName: string,
+ composeContent: string,
+ envContent?: string,
+ projectFiles?: ProjectFileDraft[]
+ ): Promise<Project> {
const envId = await environmentStore.getCurrentEnvironmentId();
const payload = {
name: projectName,
composeContent,
- envContent
+ envContent,
+ projectFiles
};
return this.handleResponse(this.api.post(`/environments/${envId}/projects`, payload));
}
@@ -136,17 +143,34 @@ class ProjectService extends BaseAPIService {
return res.data.data;
}
- async updateProject(projectId: string, name?: string, composeContent?: string, envContent?: string): Promise<Project> {
+ async updateProject(
+ projectId: string,
+ name?: string,
+ composeContent?: string,
+ envContent?: string,
+ fileTreeRevision?: string,
+ fileChanges?: ProjectFileChange[]
+ ): Promise<Project> {
const envId = await environmentStore.getCurrentEnvironmentId();
- const payload: Record<string, string> = {};
+ const payload: {
+ name?: string;
+ composeContent?: string;
+ envContent?: string;
+ fileTreeRevision?: string;
+ fileChanges?: ProjectFileChange[];
+ } = {};
if (name !== undefined) {
- payload['name'] = name;
+ payload.name = name;
}
if (composeContent !== undefined) {
- payload['composeContent'] = composeContent;
+ payload.composeContent = composeContent;
}
if (envContent !== undefined) {
- payload['envContent'] = envContent;
+ payload.envContent = envContent;
+ }
+ if (fileChanges && fileChanges.length > 0) {
+ payload.fileTreeRevision = fileTreeRevision;
+ payload.fileChanges = fileChanges;
}
return this.handleResponse(this.api.put(`/environments/${envId}/projects/${projectId}`, payload));
}
diff --git a/frontend/src/lib/types/project-files.ts b/frontend/src/lib/types/project-files.ts
new file mode 100644
index 000000000..3157e548f
--- /dev/null
+++ b/frontend/src/lib/types/project-files.ts
@@ -0,0 +1,27 @@
+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/swarm.ts b/frontend/src/lib/types/swarm.ts
index 952c71722..ec4a73429 100644
--- a/frontend/src/lib/types/swarm.ts
+++ b/frontend/src/lib/types/swarm.ts
@@ -1,3 +1,5 @@
+import type { ProjectFile } from './project-files';
+
// --- Swarm services, ports, mounts ---
export interface SwarmServicePort {
@@ -547,6 +549,8 @@ export interface Project {
envContent?: string;
includeFiles?: IncludeFile[];
directoryFiles?: IncludeFile[];
+ projectFiles?: ProjectFile[];
+ fileTreeRevision?: string;
}
export interface ProjectStatusCounts {
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
index 0b98b1c5f..fef950fcb 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
@@ -1,11 +1,21 @@
<script lang="ts">
import type { IncludeFile, Project } from '$lib/types/swarm';
+ import type { ProjectFileChange } from '$lib/types/project-files';
import * as Tabs from '$lib/components/ui/tabs/index.js';
- import * as TreeView from '$lib/components/ui/tree-view/index.js';
- import * as Card from '$lib/components/ui/card';
import * as Alert from '$lib/components/ui/alert/index.js';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { ArrowLeftIcon, BoxIcon, ProjectsIcon, LayersIcon, SettingsIcon, FileTextIcon, AlertIcon, GlobeIcon } from '$lib/icons';
+ import {
+ ArrowLeftIcon,
+ ArrowsUpDownIcon,
+ BoxIcon,
+ ProjectsIcon,
+ LayersIcon,
+ SearchIcon,
+ SettingsIcon,
+ FileTextIcon,
+ AlertIcon,
+ GlobeIcon
+ } from '$lib/icons';
import { type TabItem } from '$lib/components/tab-bar/index.js';
import TabbedPageLayout from '$lib/layouts/tabbed-page-layout.svelte';
import ActionButtons from '$lib/components/action-buttons.svelte';
@@ -24,11 +34,13 @@
import { toSafeHref } from '$lib/utils/navigation';
import { PersistedState } from 'runed';
import EditableName from '../components/EditableName.svelte';
+ import ProjectFileTreePanel from '../components/ProjectFileTreePanel.svelte';
+ import EditorTabStrip from '../components/EditorTabStrip.svelte';
import ProjectContainersTable from '../components/ProjectContainersTable.svelte';
import CodePanel from '../components/CodePanel.svelte';
import ProjectsLogsPanel from '../components/ProjectLogsPanel.svelte';
import ResizableSplit from '$lib/components/resizable-split.svelte';
- import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
+ import { Switch } from '$lib/components/ui/switch';
import { untrack } from 'svelte';
import { projectService } from '$lib/services/project-service';
import { imageService } from '$lib/services/image-service';
@@ -43,6 +55,19 @@
import IfPermitted from '$lib/components/if-permitted.svelte';
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';
import { extractComposeYamlName } from '$lib/utils/compose-flow';
let { data } = $props();
@@ -72,6 +97,11 @@
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> = {};
const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));
@@ -119,6 +149,10 @@
directoryFiles: (details.directoryFiles ?? []).map((file) => ({
...file,
content: file.content ?? loadedDirectoryFileContents[file.relativePath]
+ })),
+ projectFiles: (details.projectFiles ?? []).map((file) => ({
+ ...file,
+ content: file.content ?? loadedManagedProjectFileContents[file.relativePath]
}))
};
}
@@ -135,6 +169,15 @@
)
)
);
+ const managedProjectFiles = $derived.by(() =>
+ applyProjectFileChangesForDisplay(project?.projectFiles ?? [], managedProjectFileChanges)
+ );
+ 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 composeYamlName = $derived(extractComposeYamlName($inputs.composeContent.value));
// The compose file's top-level `name:` is authoritative; surface it as the
@@ -145,7 +188,9 @@
effectiveName !== serverName ||
$inputs.composeContent.value !== serverComposeContent ||
$inputs.envContent.value !== serverEnvContent ||
- Object.entries(includeFilesState).some(([relativePath, content]) => content !== serverIncludeFiles[relativePath])
+ Object.entries(includeFilesState).some(([relativePath, content]) => content !== serverIncludeFiles[relativePath]) ||
+ managedProjectFileChanges.length > 0 ||
+ changedManagedProjectFilePaths.length > 0
);
let isGitOpsManaged = $derived(!!project?.gitOpsManagedBy);
@@ -162,6 +207,7 @@
);
let canEditCompose = $derived(canUpdateProject && !project?.isArchived && !isGitOpsManaged);
let canEditEnv = $derived(canUpdateProject && !project?.isArchived);
+ let canEditProjectFiles = $derived(canUpdateProject && !project?.isArchived && !isGitOpsManaged);
let composeFileName = $derived(project?.composeFileName || 'compose.yaml');
let archiveRequiresStopped = $derived(
!!project &&
@@ -180,11 +226,16 @@
let envOpen = $state(true);
let includeFilesPanelStates = $state<Record<string, boolean>>({});
let selectedFilePreference = $state<'compose' | 'env' | string>('compose');
+ let openTabsPreference = $state<string[]>(['compose']);
+ let treeOutlineOpen = $state(false);
+ let treeDiffOpen = $state(false);
+ let treeCommandPaletteOpen = $state(false);
let layoutMode = $state<'classic' | 'tree'>('classic');
let selectedIncludeTabPreference = $state<string | null>(null);
- let treePaneWidth = $state(320);
+ let treePaneWidth = $state(420);
let composeSplitWidth = $state<number | null>(null);
const minTreePaneWidth = 200;
+ const maxTreePaneWidth = 480;
const minEditorPaneWidth = 360;
const minComposePaneWidth = 360;
const minEnvPaneWidth = 280;
@@ -192,19 +243,50 @@
let composeHasErrors = $state(false);
let envHasErrors = $state(false);
let includeFilesHasErrors = $state<Record<string, boolean>>({});
+ let managedProjectFileHasErrors = $state<Record<string, boolean>>({});
let composeValidationReady = $state(false);
let envValidationReady = $state(false);
let includeFilesValidationReady = $state<Record<string, boolean>>({});
+ let managedProjectFileValidationReady = $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 selectedFile = $derived.by(() => {
const current = selectedFilePreference;
if (current === 'compose' || current === 'env') return current;
+ if (current.startsWith('file:')) {
+ const relativePath = current.slice(5);
+ return managedProjectFilePaths.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)
+ : undefined
+ );
+ const openTabs = $derived.by(() => {
+ const valid = openTabsPreference.filter((key) => {
+ if (key === 'compose' || key === 'env') return true;
+ if (!key.startsWith('file:')) return false;
+ const entry = managedProjectFiles.find((file) => file.relativePath === key.slice(5));
+ return !!entry && !entry.isDirectory;
+ });
+ return valid.length > 0 ? valid : ['compose'];
+ });
+ const activeTreeTab = $derived(openTabs.includes(selectedFile) ? selectedFile : (openTabs[0] ?? 'compose'));
+ const treeTabs = $derived(
+ openTabs.map((key) => ({
+ key,
+ label: treeTabLabel(key),
+ title: treeTabTitle(key),
+ iconClass: key === 'compose' ? 'text-blue-500' : key === 'env' ? 'text-green-500' : 'text-muted-foreground',
+ pending: treeTabPending(key)
+ }))
+ );
const selectedIncludeTab = $derived.by(() => {
if (!selectedIncludeTabPreference) return null;
return includeFilePaths.has(selectedIncludeTabPreference) ? selectedIncludeTabPreference : null;
@@ -258,10 +340,12 @@
autoScroll: boolean;
layoutMode: 'classic' | 'tree';
selectedFile?: 'compose' | 'env' | string;
+ openTabs?: string[];
};
type RebaseEditorDraftOptions = {
preserveEditableDrafts?: boolean;
+ preserveManagedProjectFileContents?: boolean;
clearLoadedFileCache?: boolean;
};
@@ -275,7 +359,8 @@
envOpen: true,
autoScroll: true,
layoutMode: 'classic',
- selectedFile: 'compose'
+ selectedFile: 'compose',
+ openTabs: ['compose']
};
let prefs: PersistedState<ComposeUIPrefs> | null = null;
@@ -297,6 +382,21 @@
if (includeFilesValidationReady[relativePath] === undefined) {
includeFilesValidationReady = {
...includeFilesValidationReady,
+ [relativePath]: false
+ };
+ }
+ }
+
+ function ensureManagedProjectFileUiState(relativePath: string) {
+ if (managedProjectFileHasErrors[relativePath] === undefined) {
+ managedProjectFileHasErrors = {
+ ...managedProjectFileHasErrors,
+ [relativePath]: false
+ };
+ }
+ if (managedProjectFileValidationReady[relativePath] === undefined) {
+ managedProjectFileValidationReady = {
+ ...managedProjectFileValidationReady,
[relativePath]: true
};
}
@@ -341,6 +441,10 @@
function clearLoadedProjectFileCache() {
loadedIncludeFileContents = {};
loadedDirectoryFileContents = {};
+ loadedManagedProjectFileContents = {};
+ managedProjectFileContents = {};
+ managedProjectFileLoadErrors = {};
+ managedProjectFileLoading = {};
projectFilePromises = {};
}
@@ -355,10 +459,27 @@
const normalizedProject = withLoadedProjectFileContent(details);
if (!normalizedProject) return;
+ const savedManagedProjectFileContents =
+ options.preserveManagedProjectFileContents === true
+ ? 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];
+ })
+ )
+ : {};
$inputs.name.value = normalizedProject.name || '';
$inputs.composeContent.value = normalizedProject.composeContent || '';
$inputs.envContent.value = shouldPreserveEnvDraft ? envDraft : normalizedProject.envContent || '';
+ managedProjectFileChanges = [];
+ managedProjectFileContents = savedManagedProjectFileContents;
+ managedProjectFileHasErrors = {};
+ managedProjectFileValidationReady = {};
+ managedProjectFileLoadErrors = {};
+ managedProjectFileLoading = {};
const freshIncludeFiles = getProjectIncludeFileContents(normalizedProject);
includeFilesState = {
@@ -417,7 +538,9 @@
if (lastPrefsProjectId === project.id) return;
lastPrefsProjectId = project.id;
- prefs = new PersistedState<ComposeUIPrefs>(`arcane.compose.ui:${project.id}`, defaultComposeUIPrefs, {
+ const prefsStorageKey = `arcane.compose.ui:${project.id}`;
+ const hadStoredPrefs = sessionStorage.getItem(prefsStorageKey) !== null;
+ prefs = new PersistedState<ComposeUIPrefs>(prefsStorageKey, defaultComposeUIPrefs, {
storage: 'session',
syncTabs: false
});
@@ -427,14 +550,67 @@
envOpen = cur.envOpen ?? defaultComposeUIPrefs.envOpen;
autoScrollStackLogs = cur.autoScroll ?? defaultComposeUIPrefs.autoScroll;
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
+ // 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.
const hasIncludes = project?.includeFiles && project.includeFiles.length > 0;
const hasDirectoryFiles = project?.directoryFiles && project.directoryFiles.length > 0;
- const defaultMode = hasIncludes || hasDirectoryFiles ? 'tree' : 'classic';
- layoutMode = cur.layoutMode ?? defaultMode;
+ const hasProjectFiles = project?.projectFiles && project.projectFiles.length > 0;
+ const defaultMode = hasIncludes || hasDirectoryFiles || hasProjectFiles ? '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.
+ if (!hadStoredPrefs) {
+ persistPrefs();
+ }
});
+ 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) {
@@ -453,43 +629,56 @@
const { composeContent, envContent } = validated;
const namePayload = isGitOpsManaged ? undefined : effectiveName;
const composePayload = isGitOpsManaged ? undefined : composeContent;
+ const fileChangesPayload = buildProjectFileSaveChanges();
+ const includeFileUpdates = buildIncludeFileSaveUpdates();
+ const fileTreeRevision = fileChangesPayload.length > 0 ? project.fileTreeRevision : undefined;
handleApiResultWithCallbacks({
- result: await tryCatch(projectService.updateProject(projectId, namePayload, composePayload, envContent)),
+ result: await tryCatch(
+ (async () => {
+ let updatedProject = await projectService.updateProject(
+ projectId,
+ namePayload,
+ composePayload,
+ envContent,
+ 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) => {
- let savedProject = updatedProject;
-
- for (const relativePath of Object.keys(includeFilesState)) {
- const includeFileContent = includeFilesState[relativePath];
- if (includeFileContent === undefined) {
- continue;
- }
-
- if (includeFileContent !== serverIncludeFiles[relativePath]) {
- const includeResult = await tryCatch(
- projectService.updateProjectIncludeFile(projectId, relativePath, includeFileContent)
- );
- if (includeResult.error) {
- toast.error(includeResult.error.message || m.common_update_failed({ resource: relativePath }));
- return;
- }
- savedProject = includeResult.data;
- }
- }
-
loadedIncludeFileContents = {
...loadedIncludeFileContents,
...Object.fromEntries(
Object.entries(includeFilesState).filter(([relativePath]) =>
- (savedProject.includeFiles ?? []).some((file) => file.relativePath === relativePath)
+ (updatedProject.includeFiles ?? []).some((file) => file.relativePath === relativePath)
)
)
};
- rebaseEditorDraft(savedProject);
- await syncProjectQueries(savedProject);
- toast.success(m.common_update_success({ resource: m.project() }), activityToastOptions(extractActivityId(savedProject)));
+ rebaseEditorDraft(updatedProject, { preserveManagedProjectFileContents: true });
+ await syncProjectQueries(updatedProject);
+ toast.success(
+ m.common_update_success({ resource: m.project() }),
+ activityToastOptions(extractActivityId(updatedProject))
+ );
}
});
}
@@ -541,18 +730,12 @@
envOpen,
autoScroll: autoScrollStackLogs,
layoutMode,
- selectedFile
+ selectedFile,
+ openTabs
};
}
- $effect(() => {
- selectedFile;
- if (layoutMode === 'tree') {
- persistPrefs();
- }
- });
-
- type ProjectFileKind = 'include' | 'directory';
+ type ProjectFileKind = 'include' | 'directory' | 'managed';
function getProjectFileKey(projectId: string, kind: ProjectFileKind, relativePath: string): string {
return `${projectId}:${kind}:${relativePath}`;
@@ -580,6 +763,21 @@
};
}
+ function updateLoadedManagedProjectFile(relativePath: string, content: string) {
+ ensureManagedProjectFileUiState(relativePath);
+ loadedManagedProjectFileContents = {
+ ...loadedManagedProjectFileContents,
+ [relativePath]: content
+ };
+ if (managedProjectFileContents[relativePath] === undefined) {
+ managedProjectFileContents = {
+ ...managedProjectFileContents,
+ [relativePath]: content
+ };
+ }
+ managedProjectFileLoadErrors = removeProjectFileRecord(managedProjectFileLoadErrors, relativePath);
+ }
+
function getProjectFileResource(kind: ProjectFileKind, relativePath: string): IncludeFile | Promise<IncludeFile> {
const currentProjectId = project?.id;
if (!currentProjectId) {
@@ -587,18 +785,34 @@
}
if (kind === 'include') {
ensureIncludeFileUiState(relativePath);
+ } else if (kind === 'managed') {
+ ensureManagedProjectFileUiState(relativePath);
+ if (managedProjectFileContents[relativePath] !== undefined) {
+ return {
+ path: relativePath,
+ relativePath,
+ content: managedProjectFileContents[relativePath]
+ };
+ }
}
const targetFile =
kind === 'include'
? project?.includeFiles?.find((file) => file.relativePath === relativePath)
- : project?.directoryFiles?.find((file) => file.relativePath === relativePath);
+ : kind === 'directory'
+ ? project?.directoryFiles?.find((file) => file.relativePath === relativePath)
+ : managedProjectFiles.find((file) => file.relativePath === relativePath);
if (!targetFile) {
throw new Error('Project file not found');
}
if (targetFile.content !== undefined) {
+ if (kind === 'managed') {
+ updateLoadedManagedProjectFile(relativePath, targetFile.content ?? '');
+ } else {
+ updateLoadedProjectFile(kind, relativePath, targetFile.content ?? '');
+ }
return targetFile;
}
@@ -610,7 +824,11 @@
const promise = (async () => {
const file = await projectService.getProjectFile(currentProjectId, relativePath);
- updateLoadedProjectFile(kind, relativePath, file.content ?? '');
+ if (kind === 'managed') {
+ updateLoadedManagedProjectFile(relativePath, file.content ?? '');
+ } else {
+ updateLoadedProjectFile(kind, relativePath, file.content ?? '');
+ }
return {
...file,
content: file.content ?? ''
@@ -624,21 +842,174 @@
return promise;
}
- function selectComposeFile() {
- selectedFilePreference = 'compose';
+ function isManagedDirectoryKey(key: string): boolean {
+ if (!key.startsWith('file:')) return false;
+ return managedProjectFiles.find((file) => file.relativePath === key.slice(5))?.isDirectory === true;
}
- function selectEnvFile() {
- selectedFilePreference = 'env';
+ function openFileTab(key: string) {
+ if (!isManagedDirectoryKey(key) && !openTabsPreference.includes(key)) {
+ openTabsPreference = [...openTabsPreference, key];
+ }
+ selectedFilePreference = key;
+ if (layoutMode === 'tree') {
+ persistPrefs();
+ }
}
- function selectIncludeFile(relativePath: string) {
- ensureIncludeFileUiState(relativePath);
- selectedFilePreference = relativePath;
+ function closeFileTab(key: string) {
+ const index = openTabs.indexOf(key);
+ const remaining = openTabs.filter((tab) => tab !== key);
+ openTabsPreference = openTabsPreference.filter((tab) => tab !== key);
+ if (selectedFile === key) {
+ selectedFilePreference = remaining[Math.min(Math.max(index - 1, 0), remaining.length - 1)] ?? 'compose';
+ }
+ persistPrefs();
+ }
+
+ function treeTabLabel(key: string): string {
+ if (key === 'compose') return composeFileName;
+ if (key === 'env') return '.env';
+ return projectFileBasename(key.startsWith('file:') ? key.slice(5) : key);
+ }
+
+ function treeTabTitle(key: string): string {
+ if (key === 'compose') return composeFileName;
+ if (key === 'env') return '.env';
+ return key.startsWith('file:') ? key.slice(5) : key;
+ }
+
+ function treeTabPending(key: string): boolean {
+ if (key === 'compose') return composeHasChanges;
+ if (key === 'env') return envHasChanges;
+ if (!key.startsWith('file:')) return false;
+ const relativePath = key.slice(5);
+ return (
+ changedManagedProjectFilePaths.includes(relativePath) ||
+ managedProjectFiles.find((file) => file.relativePath === relativePath)?.pending === true
+ );
+ }
+
+ function selectManagedProjectFile(key: string) {
+ openFileTab(key);
+ }
+
+ async function loadManagedProjectFileDraft(relativePath: string) {
+ if (!relativePath || managedProjectFileContents[relativePath] !== undefined || managedProjectFileLoading[relativePath]) {
+ return;
+ }
+
+ managedProjectFileLoading = {
+ ...managedProjectFileLoading,
+ [relativePath]: true
+ };
+ managedProjectFileLoadErrors = removeProjectFileRecord(managedProjectFileLoadErrors, relativePath);
+
+ try {
+ const file = await getProjectFileResource('managed', relativePath);
+ updateLoadedManagedProjectFile(relativePath, file.content ?? '');
+ } catch (error) {
+ managedProjectFileLoadErrors = {
+ ...managedProjectFileLoadErrors,
+ [relativePath]: error instanceof Error ? error.message : String(error)
+ };
+ } finally {
+ managedProjectFileLoading = removeProjectFileRecord(managedProjectFileLoading, 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) {
+ return;
+ }
+
+ void loadManagedProjectFileDraft(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);
+ 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)) {
+ selectedFilePreference = openTabs[0] ?? 'compose';
+ }
+ }
+
+ function createManagedProjectFile(parentPath: string, name: string, content = '') {
+ const relativePath = planProjectFileCreate(managedProjectFilePaths, 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);
+ openFileTab(`file:${relativePath}`);
+ }
+
+ function createManagedProjectFolder(parentPath: string, name: string) {
+ const relativePath = planProjectFileCreate(managedProjectFilePaths, parentPath, name, composeFileName);
+ if (!relativePath) return;
+ managedProjectFileChanges = [...managedProjectFileChanges, { operation: 'create_folder', relativePath }];
+ selectedFilePreference = `file:${relativePath}`;
}
- function selectDirectoryFile(relativePath: string) {
- selectedFilePreference = `dir:${relativePath}`;
+ function renameManagedProjectFile(relativePath: string, newName: string) {
+ const plan = planProjectFileRename(managedProjectFilePaths, relativePath, newName, composeFileName);
+ if (!plan) return;
+ managedProjectFileChanges = [...managedProjectFileChanges, { operation: 'rename', relativePath, newName: plan.newName }];
+ remapManagedProjectFileState(relativePath, plan.newPath);
+ }
+
+ function moveManagedProjectFile(relativePath: string, newParentPath: string) {
+ const entry = managedProjectFiles.find((file) => file.relativePath === relativePath);
+ const newPath = planProjectFileMove(entry, managedProjectFilePaths, relativePath, newParentPath);
+ if (!newPath) return;
+ managedProjectFileChanges = [...managedProjectFileChanges, { operation: 'move', relativePath, newParentPath }];
+ remapManagedProjectFileState(relativePath, newPath);
+ }
+
+ function deleteManagedProjectFile(relativePath: string) {
+ const entry = managedProjectFiles.find((file) => file.relativePath === relativePath);
+ if (!entry) return;
+ managedProjectFileChanges = [
+ ...managedProjectFileChanges,
+ { operation: 'delete', relativePath, recursive: entry.isDirectory }
+ ];
+ removeManagedProjectFileState(relativePath);
}
function toggleIncludeFileTab(relativePath: string) {
@@ -938,16 +1309,22 @@
</div>
</Alert.Root>
{/if}
- <div class="mb-4 shrink-0">
- <SwitchWithLabel
+ <div class="mb-2 flex shrink-0 items-center justify-end gap-2">
+ <label
+ for="layout-mode-toggle"
+ class="text-muted-foreground cursor-pointer text-xs"
+ title={m.project_view_description()}
+ >
+ {m.workspace()}
+ </label>
+ <Switch
id="layout-mode-toggle"
checked={layoutMode === 'tree'}
- label={layoutMode === 'tree' ? m.tree_view() : m.classic()}
- description={m.project_view_description()}
+ aria-label={m.project_view_description()}
onCheckedChange={(checked) => {
layoutMode = checked ? 'tree' : 'classic';
if (checked) {
- selectedFilePreference = 'compose';
+ openFileTab('compose');
selectedIncludeTabPreference = null;
}
persistPrefs();
@@ -957,166 +1334,153 @@
<div class="min-h-0 flex-1">
{#if layoutMode === 'tree'}
- <ResizableSplit
- class="h-full min-h-0 lg:gap-2"
- firstClass="flex min-h-0 flex-col"
- secondClass="flex min-h-0 flex-col"
- bind:size={treePaneWidth}
- minSize={minTreePaneWidth}
- minSecondSize={minEditorPaneWidth}
- defaultRatio={0.3}
- stackBelow={1024}
- ariaLabel={m.compose_editor_resize_files_panel()}
- persistKey={`arcane.compose.split:${project.id}:tree`}
- onResizeEnd={persistPrefs}
- >
- {#snippet first()}
- <Card.Root class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
- <Card.Header icon={FileTextIcon} class="shrink-0 items-center">
- <Card.Title>
- <h2>{m.project_files()}</h2>
- </Card.Title>
- </Card.Header>
- <Card.Content class="min-h-0 flex-1 overflow-auto p-2">
- <TreeView.Root class="min-w-max p-2 whitespace-nowrap">
- <TreeView.File
- name={composeFileName}
- onclick={selectComposeFile}
- class={selectedFile === 'compose' ? 'bg-accent' : ''}
- >
- {#snippet icon()}
- <FileTextIcon class="size-4 text-blue-500" />
- {/snippet}
- </TreeView.File>
-
- <TreeView.File name=".env" onclick={selectEnvFile} class={selectedFile === 'env' ? 'bg-accent' : ''}>
- {#snippet icon()}
- <FileTextIcon class="size-4 text-green-500" />
- {/snippet}
- </TreeView.File>
-
- {#if project?.includeFiles && project.includeFiles.length > 0}
- <TreeView.Folder name={m.project_includes()}>
- {#each project.includeFiles as includeFile (includeFile.relativePath)}
- <TreeView.File
- name={includeFile.relativePath}
- onclick={() => selectIncludeFile(includeFile.relativePath)}
- class={selectedFile === includeFile.relativePath ? 'bg-accent' : ''}
- >
- {#snippet icon()}
- <FileTextIcon class="size-4 text-amber-500" />
- {/snippet}
- </TreeView.File>
- {/each}
- </TreeView.Folder>
- {/if}
-
- {#if project?.directoryFiles && project.directoryFiles.length > 0}
- {#each project.directoryFiles as dirFile (dirFile.relativePath)}
- <TreeView.File
- name={dirFile.relativePath}
- onclick={() => selectDirectoryFile(dirFile.relativePath)}
- class={selectedFile === `dir:${dirFile.relativePath}` ? 'bg-accent' : ''}
- >
- {#snippet icon()}
- <FileTextIcon class="text-muted-foreground size-4" />
- {/snippet}
- </TreeView.File>
- {/each}
- {/if}
- </TreeView.Root>
- </Card.Content>
- </Card.Root>
- {/snippet}
-
- {#snippet second()}
- <div class="flex h-full min-h-0 flex-1 flex-col">
- {#if selectedFile === 'compose'}
- <CodePanel
- bind:open={composeOpen}
- title={composeFileName}
- language="yaml"
- bind:value={$inputs.composeContent.value}
- error={$inputs.composeContent.error ?? undefined}
- readOnly={!canEditCompose}
- bind:hasErrors={composeHasErrors}
- bind:validationReady={composeValidationReady}
- fileId={`project:${projectId}:compose`}
- originalValue={serverComposeContent}
- enableDiff={true}
- editorContext={codeEditorContext}
- />
- {:else if selectedFile === 'env'}
- <CodePanel
- bind:open={envOpen}
- title=".env"
- language="env"
- bind:value={$inputs.envContent.value}
- error={$inputs.envContent.error ?? undefined}
- readOnly={!canEditEnv}
- bind:hasErrors={envHasErrors}
- bind:validationReady={envValidationReady}
- fileId={`project:${projectId}:env`}
- originalValue={serverEnvContent}
- enableDiff={true}
- editorContext={codeEditorContext}
- />
- {:else if selectedFile.startsWith('dir:')}
- {@const dirRelPath = selectedFile.slice(4)}
- {@const dirFile = project?.directoryFiles?.find((f) => f.relativePath === dirRelPath)}
- {#if dirFile}
- {#await getProjectFileResource('directory', dirRelPath)}
- <div class="text-muted-foreground flex h-full min-h-0 items-center justify-center rounded-lg border">
- {m.common_loading()}
- </div>
- {:then loadedFile}
- <CodePanel
- open={true}
- title={loadedFile.relativePath}
- language="yaml"
- value={loadedFile.content ?? ''}
- readOnly={true}
+ <div class="bg-card border-border flex h-full min-h-0 flex-col overflow-hidden rounded-lg border">
+ <ResizableSplit
+ class="h-full min-h-0 flex-1"
+ variant="flush"
+ firstClass="bg-muted/20 border-border flex min-h-0 flex-col border-b lg:border-r lg:border-b-0"
+ secondClass="flex min-h-0 flex-col"
+ bind:size={treePaneWidth}
+ minSize={minTreePaneWidth}
+ maxSize={maxTreePaneWidth}
+ minSecondSize={minEditorPaneWidth}
+ defaultRatio={0.22}
+ stackBelow={1024}
+ ariaLabel={m.compose_editor_resize_files_panel()}
+ persistKey={`arcane.compose.split:${project.id}:tree`}
+ onResizeEnd={persistPrefs}
+ >
+ {#snippet first()}
+ <ProjectFileTreePanel
+ {composeFileName}
+ entries={managedProjectFiles}
+ {selectedFile}
+ disabled={!canEditProjectFiles}
+ readOnlyMessage={isGitOpsManaged ? m.project_files_readonly_git() : undefined}
+ onSelect={selectManagedProjectFile}
+ onCreateFile={createManagedProjectFile}
+ onCreateFolder={createManagedProjectFolder}
+ onRename={renameManagedProjectFile}
+ onMove={moveManagedProjectFile}
+ onDelete={deleteManagedProjectFile}
+ />
+ {/snippet}
+
+ {#snippet second()}
+ <div class="flex h-full min-h-0 flex-1 flex-col">
+ <EditorTabStrip tabs={treeTabs} activeKey={activeTreeTab} onSelect={openFileTab} onClose={closeFileTab}>
+ {#snippet actions()}
+ <ArcaneButton
+ action="base"
+ tone={treeOutlineOpen ? 'outline-primary' : 'ghost'}
+ size="icon"
+ class="size-6"
+ showLabel={false}
+ icon={FileTextIcon}
+ customLabel={m.compose_editor_toggle_outline()}
+ onclick={() => (treeOutlineOpen = !treeOutlineOpen)}
/>
- {:catch error}
- <div
- class="text-destructive flex h-full min-h-0 items-center justify-center rounded-lg border px-4 text-sm"
- >
- {error instanceof Error ? error.message : String(error)}
- </div>
- {/await}
- {/if}
- {:else}
- {@const includeFile = project?.includeFiles?.find((f) => f.relativePath === selectedFile)}
- {#if includeFile}
- {#await getProjectFileResource('include', includeFile.relativePath)}
- <div class="text-muted-foreground flex h-full min-h-0 items-center justify-center rounded-lg border">
- {m.common_loading()}
- </div>
- {:then}
- <CodePanel
- bind:open={includeFilesPanelStates[includeFile.relativePath]}
- title={includeFile.relativePath}
- language="yaml"
- bind:value={includeFilesState[includeFile.relativePath]}
- bind:hasErrors={includeFilesHasErrors[includeFile.relativePath]}
- bind:validationReady={includeFilesValidationReady[includeFile.relativePath]}
- fileId={`project:${projectId}:include:${includeFile.relativePath}`}
- originalValue={serverIncludeFiles[includeFile.relativePath] ?? ''}
- enableDiff={true}
- editorContext={codeEditorContext}
+ <ArcaneButton
+ action="base"
+ tone={treeDiffOpen ? 'outline-primary' : 'ghost'}
+ size="icon"
+ class="size-6"
+ showLabel={false}
+ icon={ArrowsUpDownIcon}
+ customLabel={m.compose_editor_toggle_diff()}
+ onclick={() => (treeDiffOpen = !treeDiffOpen)}
/>
- {:catch error}
- <div
- class="text-destructive flex h-full min-h-0 items-center justify-center rounded-lg border px-4 text-sm"
- >
- {error instanceof Error ? error.message : String(error)}
- </div>
- {/await}
- {/if}
- {/if}
- </div>
- {/snippet}
- </ResizableSplit>
+ <ArcaneButton
+ action="base"
+ tone="ghost"
+ size="icon"
+ class="size-6"
+ showLabel={false}
+ icon={SearchIcon}
+ customLabel={m.compose_editor_command_palette()}
+ onclick={() => (treeCommandPaletteOpen = true)}
+ />
+ {/snippet}
+ </EditorTabStrip>
+ <div class="flex min-h-0 flex-1 flex-col">
+ {#key activeTreeTab}
+ {#if activeTreeTab === 'compose'}
+ <CodePanel
+ variant="plain"
+ bind:open={composeOpen}
+ title={composeFileName}
+ language="yaml"
+ validationMode="compose"
+ bind:value={$inputs.composeContent.value}
+ error={$inputs.composeContent.error ?? undefined}
+ readOnly={!canEditCompose}
+ bind:hasErrors={composeHasErrors}
+ bind:validationReady={composeValidationReady}
+ fileId={`project:${projectId}:compose`}
+ originalValue={serverComposeContent}
+ enableDiff={true}
+ editorContext={codeEditorContext}
+ bind:outlineOpen={treeOutlineOpen}
+ bind:diffOpen={treeDiffOpen}
+ bind:commandPaletteOpen={treeCommandPaletteOpen}
+ />
+ {:else if activeTreeTab === 'env'}
+ <CodePanel
+ variant="plain"
+ bind:open={envOpen}
+ title=".env"
+ language="env"
+ validationMode="env"
+ bind:value={$inputs.envContent.value}
+ error={$inputs.envContent.error ?? undefined}
+ readOnly={!canEditEnv}
+ bind:hasErrors={envHasErrors}
+ bind:validationReady={envValidationReady}
+ fileId={`project:${projectId}:env`}
+ originalValue={serverEnvContent}
+ enableDiff={true}
+ editorContext={codeEditorContext}
+ bind:outlineOpen={treeOutlineOpen}
+ bind:diffOpen={treeDiffOpen}
+ bind:commandPaletteOpen={treeCommandPaletteOpen}
+ />
+ {:else if activeTreeTab.startsWith('file:')}
+ {@const relativePath = activeTreeTab.slice(5)}
+ {#if managedProjectFileLoadErrors[relativePath]}
+ <div class="text-destructive flex h-full min-h-0 items-center justify-center px-4 text-sm">
+ {managedProjectFileLoadErrors[relativePath]}
+ </div>
+ {:else if managedProjectFileContents[relativePath] === undefined}
+ <div class="text-muted-foreground flex h-full min-h-0 items-center justify-center">
+ {m.common_loading()}
+ </div>
+ {:else}
+ <CodePanel
+ variant="plain"
+ open={true}
+ title={relativePath}
+ language={projectFileLanguage(relativePath)}
+ validationMode="none"
+ bind:value={managedProjectFileContents[relativePath]}
+ readOnly={!canEditProjectFiles}
+ bind:hasErrors={managedProjectFileHasErrors[relativePath]}
+ bind:validationReady={managedProjectFileValidationReady[relativePath]}
+ fileId={`project:${projectId}:file:${relativePath}`}
+ originalValue={loadedManagedProjectFileContents[relativePath] ?? ''}
+ enableDiff={true}
+ editorContext={codeEditorContext}
+ bind:outlineOpen={treeOutlineOpen}
+ bind:diffOpen={treeDiffOpen}
+ bind:commandPaletteOpen={treeCommandPaletteOpen}
+ />
+ {/if}
+ {/if}
+ {/key}
+ </div>
+ </div>
+ {/snippet}
+ </ResizableSplit>
+ </div>
{:else}
<div class="flex h-full min-h-0 flex-col gap-4">
{#if project?.includeFiles && project.includeFiles.length > 0}
@@ -1149,6 +1513,7 @@
bind:open={includeFilesPanelStates[includeFile.relativePath]}
title={includeFile.relativePath}
language="yaml"
+ validationMode="compose"
bind:value={includeFilesState[includeFile.relativePath]}
bind:hasErrors={includeFilesHasErrors[includeFile.relativePath]}
bind:validationReady={includeFilesValidationReady[includeFile.relativePath]}
@@ -1185,6 +1550,7 @@
bind:open={composeOpen}
title={composeFileName}
language="yaml"
+ validationMode="compose"
bind:value={$inputs.composeContent.value}
error={$inputs.composeContent.error ?? undefined}
readOnly={!canEditCompose}
@@ -1204,6 +1570,7 @@
bind:open={envOpen}
title=".env"
language="env"
+ validationMode="env"
bind:value={$inputs.envContent.value}
error={$inputs.envContent.error ?? undefined}
readOnly={!canEditEnv}
diff --git a/frontend/src/routes/(app)/projects/components/CodePanel.svelte b/frontend/src/routes/(app)/projects/components/CodePanel.svelte
index 92d097ce4..bf6f01cec 100644
--- a/frontend/src/routes/(app)/projects/components/CodePanel.svelte
+++ b/frontend/src/routes/(app)/projects/components/CodePanel.svelte
@@ -5,12 +5,18 @@
import { CodeIcon, FileTextIcon, SearchIcon, ArrowsUpDownIcon } from '$lib/icons';
import { IsMobile } from '$lib/hooks/is-mobile.svelte.js';
import { m } from '$lib/paraglide/messages';
- import type { CodeLanguage, DiagnosticSummary, EditorContext } from '$lib/components/code-editor/analysis/types';
+ import type {
+ CodeLanguage,
+ CodeValidationMode,
+ DiagnosticSummary,
+ EditorContext
+ } from '$lib/components/code-editor/analysis/types';
let {
title,
open = $bindable(true),
language,
+ validationMode,
value = $bindable(''),
error,
autoHeight = false,
@@ -34,11 +40,13 @@
editorContext,
outlineOpen = $bindable(false),
diffOpen = $bindable(false),
- commandPaletteOpen = $bindable(false)
+ commandPaletteOpen = $bindable(false),
+ variant = 'card'
}: {
title: string;
open?: boolean;
language: CodeLanguage;
+ validationMode?: CodeValidationMode;
value?: string;
error?: string;
autoHeight?: boolean;
@@ -53,73 +61,85 @@
outlineOpen?: boolean;
diffOpen?: boolean;
commandPaletteOpen?: boolean;
+ variant?: 'card' | 'plain';
} = $props();
const isMobile = new IsMobile();
const effectiveAutoHeight = $derived(autoHeight || isMobile.current);
</script>
-<Card.Root class="flex {effectiveAutoHeight ? '' : 'flex-1'} min-h-0 flex-col overflow-hidden" data-open={open}>
- <Card.Header icon={CodeIcon} class="flex-shrink-0 items-center">
- <Card.Title>
- <h2>{title}</h2>
- </Card.Title>
- <Card.Action class="flex items-center gap-1 pt-1">
- <ArcaneButton
- action="base"
- tone={outlineOpen ? 'outline-primary' : 'ghost'}
- size="icon"
- showLabel={false}
- icon={FileTextIcon}
- customLabel={m.compose_editor_toggle_outline()}
- onclick={() => (outlineOpen = !outlineOpen)}
+{#snippet editorBody()}
+ <div class="{effectiveAutoHeight ? '' : 'relative flex-1'} min-h-0 w-full min-w-0">
+ <div class={effectiveAutoHeight ? '' : 'absolute inset-0'}>
+ <CodeEditor
+ bind:value
+ {language}
+ {validationMode}
+ fontSize="13px"
+ autoHeight={effectiveAutoHeight}
+ {readOnly}
+ bind:hasErrors
+ bind:validationReady
+ bind:diagnosticSummary
+ {fileId}
+ {originalValue}
+ {enableDiff}
+ {editorContext}
+ bind:outlineOpen
+ bind:diffOpen
+ bind:commandPaletteOpen
/>
- {#if enableDiff && originalValue !== undefined}
+ </div>
+ </div>
+ {#if error}
+ <p class="text-destructive px-4 py-2 text-xs">{error}</p>
+ {/if}
+{/snippet}
+
+{#if variant === 'plain'}
+ <div class="relative z-0 flex min-h-0 {effectiveAutoHeight ? '' : 'flex-1'} flex-col" data-open={open}>
+ {@render editorBody()}
+ </div>
+{:else}
+ <Card.Root class="flex {effectiveAutoHeight ? '' : 'flex-1'} min-h-0 flex-col overflow-hidden" data-open={open}>
+ <Card.Header icon={CodeIcon} class="flex-shrink-0 items-center">
+ <Card.Title>
+ <h2>{title}</h2>
+ </Card.Title>
+ <Card.Action class="flex items-center gap-1 pt-1">
<ArcaneButton
action="base"
- tone={diffOpen ? 'outline-primary' : 'ghost'}
+ tone={outlineOpen ? 'outline-primary' : 'ghost'}
size="icon"
showLabel={false}
- icon={ArrowsUpDownIcon}
- customLabel={m.compose_editor_toggle_diff()}
- onclick={() => (diffOpen = !diffOpen)}
+ icon={FileTextIcon}
+ customLabel={m.compose_editor_toggle_outline()}
+ onclick={() => (outlineOpen = !outlineOpen)}
/>
- {/if}
- <ArcaneButton
- action="base"
- tone="ghost"
- size="icon"
- showLabel={false}
- icon={SearchIcon}
- customLabel={m.compose_editor_command_palette()}
- onclick={() => (commandPaletteOpen = true)}
- />
- </Card.Action>
- </Card.Header>
- <Card.Content class="relative z-0 flex min-h-0 {effectiveAutoHeight ? '' : 'flex-1'} flex-col overflow-visible p-0">
- <div class="{effectiveAutoHeight ? '' : 'relative flex-1'} min-h-0 w-full min-w-0">
- <div class={effectiveAutoHeight ? '' : 'absolute inset-0'}>
- <CodeEditor
- bind:value
- {language}
- fontSize="13px"
- autoHeight={effectiveAutoHeight}
- {readOnly}
- bind:hasErrors
- bind:validationReady
- bind:diagnosticSummary
- {fileId}
- {originalValue}
- {enableDiff}
- {editorContext}
- bind:outlineOpen
- bind:diffOpen
- bind:commandPaletteOpen
+ {#if enableDiff && originalValue !== undefined}
+ <ArcaneButton
+ action="base"
+ tone={diffOpen ? 'outline-primary' : 'ghost'}
+ size="icon"
+ showLabel={false}
+ icon={ArrowsUpDownIcon}
+ customLabel={m.compose_editor_toggle_diff()}
+ onclick={() => (diffOpen = !diffOpen)}
+ />
+ {/if}
+ <ArcaneButton
+ action="base"
+ tone="ghost"
+ size="icon"
+ showLabel={false}
+ icon={SearchIcon}
+ customLabel={m.compose_editor_command_palette()}
+ onclick={() => (commandPaletteOpen = true)}
/>
- </div>
- </div>
- {#if error}
- <p class="text-destructive px-4 py-2 text-xs">{error}</p>
- {/if}
- </Card.Content>
-</Card.Root>
+ </Card.Action>
+ </Card.Header>
+ <Card.Content class="relative z-0 flex min-h-0 {effectiveAutoHeight ? '' : 'flex-1'} flex-col overflow-visible p-0">
+ {@render editorBody()}
+ </Card.Content>
+ </Card.Root>
+{/if}
diff --git a/frontend/src/routes/(app)/projects/components/EditorTabStrip.svelte b/frontend/src/routes/(app)/projects/components/EditorTabStrip.svelte
new file mode 100644
index 000000000..3ac7a2778
--- /dev/null
+++ b/frontend/src/routes/(app)/projects/components/EditorTabStrip.svelte
@@ -0,0 +1,80 @@
+<script lang="ts">
+ import type { Snippet } from 'svelte';
+ import { CloseIcon, FileTextIcon } from '$lib/icons';
+ import { m } from '$lib/paraglide/messages';
+ import { cn } from '$lib/utils';
+
+ interface EditorTab {
+ key: string;
+ label: string;
+ title: string;
+ iconClass: string;
+ pending: boolean;
+ }
+
+ interface Props {
+ tabs: EditorTab[];
+ activeKey: string;
+ onSelect: (key: string) => void;
+ onClose: (key: string) => void;
+ actions?: Snippet;
+ }
+
+ let { tabs, activeKey, onSelect, onClose, actions }: Props = $props();
+</script>
+
+<div class="border-border bg-muted/30 flex h-9 shrink-0 items-center border-b">
+ <div class="scrollbar-hide flex h-full min-w-0 flex-1 items-center overflow-x-auto">
+ {#each tabs as tab (tab.key)}
+ {@const isActive = activeKey === tab.key}
+ <div
+ class={cn(
+ 'group border-border relative flex h-full shrink-0 items-center border-r',
+ isActive ? 'bg-card' : 'hover:bg-accent/50'
+ )}
+ data-tab-key={tab.key}
+ data-active={isActive}
+ >
+ {#if isActive}
+ <span class="bg-primary absolute inset-x-0 top-0 h-0.5"></span>
+ {/if}
+ <button
+ type="button"
+ class={cn(
+ 'flex h-full items-center gap-1.5 pr-1 pl-3 text-[13px]',
+ isActive ? 'text-foreground' : 'text-muted-foreground'
+ )}
+ title={tab.title}
+ onclick={() => onSelect(tab.key)}
+ >
+ <FileTextIcon class={cn('size-3.5 shrink-0', tab.iconClass)} />
+ <span class="max-w-40 truncate">{tab.label}</span>
+ {#if tab.pending}
+ <span
+ class="bg-primary size-1.5 shrink-0 rounded-full"
+ role="img"
+ aria-label={m.common_unsaved_changes()}
+ title={m.common_unsaved_changes()}
+ ></span>
+ {/if}
+ </button>
+ <button
+ type="button"
+ class={cn(
+ 'hover:bg-foreground/10 mr-1 inline-flex size-5 shrink-0 items-center justify-center rounded opacity-0 group-hover:opacity-100 focus-visible:opacity-100',
+ isActive && 'opacity-100'
+ )}
+ aria-label={m.common_close()}
+ onclick={() => onClose(tab.key)}
+ >
+ <CloseIcon class="size-3" />
+ </button>
+ </div>
+ {/each}
+ </div>
+ {#if actions}
+ <div class="flex shrink-0 items-center gap-0.5 px-1.5">
+ {@render actions()}
+ </div>
+ {/if}
+</div>
diff --git a/frontend/src/routes/(app)/projects/components/ProjectFileTreePanel.svelte b/frontend/src/routes/(app)/projects/components/ProjectFileTreePanel.svelte
new file mode 100644
index 000000000..8731dd4c7
--- /dev/null
+++ b/frontend/src/routes/(app)/projects/components/ProjectFileTreePanel.svelte
@@ -0,0 +1,783 @@
+<script lang="ts">
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import * as Dialog from '$lib/components/ui/dialog';
+ import { Input } from '$lib/components/ui/input';
+ import { Label } from '$lib/components/ui/label';
+ import * as Tooltip from '$lib/components/ui/tooltip/index.js';
+ import * as TreeView from '$lib/components/ui/tree-view/index.js';
+ import {
+ ArrowDownIcon,
+ ArrowRightIcon,
+ CreateFileIcon,
+ CreateFolderIcon,
+ EditIcon,
+ FileTextIcon,
+ FolderMoveIcon,
+ FolderOpenIcon,
+ LockIcon,
+ 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;
+
+ type DialogMode = 'create_file' | 'create_folder' | 'rename' | 'move' | 'upload';
+ type TreeRow = ManagedProjectFileEntry & {
+ depth: number;
+ hasChildren: boolean;
+ };
+ type FolderDestinationOption = {
+ relativePath: string;
+ label: string;
+ depth: number;
+ hasChildren: boolean;
+ disabled: boolean;
+ reason?: string;
+ };
+
+ interface Props {
+ composeFileName: string;
+ entries: ManagedProjectFileEntry[];
+ selectedFile: string;
+ disabled?: boolean;
+ readOnlyMessage?: string;
+ onSelect: (key: string) => void;
+ onCreateFile?: (parentPath: string, name: string, content?: string) => void;
+ onCreateFolder?: (parentPath: string, name: string) => void;
+ onRename?: (relativePath: string, newName: string) => void;
+ onMove?: (relativePath: string, newParentPath: string) => void;
+ onDelete?: (relativePath: string) => void;
+ }
+
+ let {
+ composeFileName,
+ entries,
+ selectedFile,
+ disabled = false,
+ readOnlyMessage,
+ onSelect,
+ onCreateFile,
+ onCreateFolder,
+ onRename,
+ onMove,
+ onDelete
+ }: Props = $props();
+
+ let openFolders = $state<Record<string, boolean>>({});
+ let activeFolderPath = $state('');
+ let dialogOpen = $state(false);
+ let dialogMode = $state<DialogMode>('create_file');
+ let dialogName = $state('');
+ let dialogParentPath = $state('');
+ let dialogTargetPath = $state('');
+ let dialogDestinationPath = $state('');
+ let destinationOpenFolders = $state<Record<string, boolean>>({});
+ let uploadFile = $state<File | null>(null);
+ 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 selectedParentPath = $derived.by(() => {
+ if (activeFolderPath && entryByPath.get(activeFolderPath)?.isDirectory) return activeFolderPath;
+ return selectedManagedEntry?.isDirectory ? selectedManagedEntry.relativePath : projectFileParentPath(selectedManagedPath);
+ });
+ const rows = $derived.by(() => flattenRows(entries, openFolders));
+ const hasDirectories = $derived(entries.some((entry) => entry.isDirectory));
+ const canManageFiles = $derived(!!onCreateFile && !!onCreateFolder && !!onRename && !!onMove && !!onDelete);
+ const dialogTitle = $derived.by(() => {
+ if (dialogMode === 'upload') return m.project_file_upload_title();
+ if (dialogMode === 'move') return m.project_file_move_title();
+ if (dialogMode === 'rename') return m.project_file_rename_title();
+ return dialogMode === 'create_folder' ? m.project_file_create_folder_title() : m.project_file_create_file_title();
+ });
+ const dialogActionLabel = $derived.by(() => {
+ if (dialogMode === 'upload') return m.project_file_upload_action();
+ if (dialogMode === 'move') return m.project_file_move_action();
+ return dialogMode === 'rename' ? m.project_file_rename_action() : m.common_create();
+ });
+ const hasDestinationPicker = $derived(
+ dialogMode === 'create_file' || dialogMode === 'create_folder' || dialogMode === 'upload' || dialogMode === 'move'
+ );
+ const allDestinationOptions = $derived.by(() =>
+ hasDestinationPicker
+ ? dialogMode === 'move' && dialogTargetPath
+ ? buildMoveDestinationOptions(dialogTargetPath)
+ : buildFolderDestinationOptions()
+ : []
+ );
+ const visibleDestinationOptions = $derived.by(() =>
+ allDestinationOptions.filter((option) => option.relativePath === '' || isDestinationVisible(option.relativePath))
+ );
+ const hasValidDestination = $derived(allDestinationOptions.some((option) => !option.disabled));
+
+ function toggleFolder(relativePath: string) {
+ activeFolderPath = relativePath;
+ openFolders = {
+ ...openFolders,
+ [relativePath]: openFolders[relativePath] !== true
+ };
+ }
+
+ function flattenRows(files: ManagedProjectFileEntry[], folderStates: Record<string, boolean>): TreeRow[] {
+ const byParent = new Map<string, ManagedProjectFileEntry[]>();
+ for (const entry of files) {
+ const parentPath = projectFileParentPath(entry.relativePath);
+ const siblings = byParent.get(parentPath) ?? [];
+ siblings.push(entry);
+ byParent.set(parentPath, siblings);
+ }
+ for (const siblings of byParent.values()) {
+ siblings.sort(compareProjectFileEntries);
+ }
+
+ const result: TreeRow[] = [];
+ const appendRows = (parentPath: string, depth: number) => {
+ for (const entry of byParent.get(parentPath) ?? []) {
+ const hasChildren = (byParent.get(entry.relativePath) ?? []).length > 0;
+ result.push({ ...entry, depth, hasChildren });
+ if (entry.isDirectory && folderStates[entry.relativePath] === true) {
+ appendRows(entry.relativePath, depth + 1);
+ }
+ }
+ };
+
+ appendRows('', 0);
+ return result;
+ }
+
+ function openCreateDialog(mode: Extract<DialogMode, 'create_file' | 'create_folder'>, parentPath = selectedParentPath) {
+ if (disabled) return;
+ dialogMode = mode;
+ dialogName = '';
+ dialogParentPath = '';
+ dialogTargetPath = '';
+ dialogDestinationPath = parentPath;
+ destinationOpenFolders = parentPath ? openAncestorDestinationFolders(parentPath) : {};
+ uploadFile = null;
+ dialogSubmitting = false;
+ dialogError = null;
+ dialogOpen = true;
+ }
+
+ function openRenameDialog(relativePath: string) {
+ if (disabled) return;
+ dialogMode = 'rename';
+ dialogName = projectFileBasename(relativePath);
+ dialogParentPath = projectFileParentPath(relativePath);
+ dialogTargetPath = relativePath;
+ dialogDestinationPath = '';
+ uploadFile = null;
+ dialogSubmitting = false;
+ dialogError = null;
+ dialogOpen = true;
+ }
+
+ function compareProjectFolderPaths(a: string, b: string): number {
+ const aSegments = a.split('/');
+ const bSegments = b.split('/');
+ const length = Math.min(aSegments.length, bSegments.length);
+
+ for (let index = 0; index < length; index += 1) {
+ const aSegment = aSegments[index] ?? '';
+ const bSegment = bSegments[index] ?? '';
+ const baseComparison = aSegment.localeCompare(bSegment, undefined, { sensitivity: 'base' });
+ if (baseComparison !== 0) return baseComparison;
+
+ const exactComparison = aSegment.localeCompare(bSegment);
+ if (exactComparison !== 0) return exactComparison;
+ }
+
+ return aSegments.length - bSegments.length;
+ }
+
+ function destinationDepth(relativePath: string): number {
+ return relativePath ? relativePath.split('/').length - 1 : 0;
+ }
+
+ function buildDestinationChildCounts(): Map<string, number> {
+ const childCounts = new Map<string, number>();
+ for (const entry of entries) {
+ if (!entry.isDirectory) continue;
+ const parentPath = projectFileParentPath(entry.relativePath);
+ childCounts.set(parentPath, (childCounts.get(parentPath) ?? 0) + 1);
+ }
+ return childCounts;
+ }
+
+ function buildFolderDestinationOptions(): FolderDestinationOption[] {
+ const childCounts = buildDestinationChildCounts();
+ return [
+ {
+ relativePath: '',
+ label: m.project_file_root_destination(),
+ depth: 0,
+ hasChildren: (childCounts.get('') ?? 0) > 0,
+ disabled: false
+ },
+ ...entries
+ .filter((candidate) => candidate.isDirectory)
+ .sort((a, b) => compareProjectFolderPaths(a.relativePath, b.relativePath))
+ .map((candidate) => ({
+ relativePath: candidate.relativePath,
+ label: projectFileBasename(candidate.relativePath),
+ depth: destinationDepth(candidate.relativePath),
+ hasChildren: (childCounts.get(candidate.relativePath) ?? 0) > 0,
+ disabled: false
+ }))
+ ];
+ }
+
+ function buildMoveDestinationOptions(relativePath: string): FolderDestinationOption[] {
+ const entry = entryByPath.get(relativePath);
+ if (!entry) return [];
+
+ const basename = projectFileBasename(relativePath);
+ const currentParentPath = projectFileParentPath(relativePath);
+ return buildFolderDestinationOptions().map((candidate) => {
+ const targetPath = joinProjectFilePath(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();
+ } else if (entryByPath.has(targetPath)) {
+ reason = m.project_file_move_duplicate_destination();
+ }
+
+ return {
+ ...candidate,
+ disabled: !!reason,
+ reason
+ };
+ });
+ }
+
+ function openAncestorDestinationFolders(relativePath: string): Record<string, boolean> {
+ const folders: Record<string, boolean> = {};
+ let parentPath = projectFileParentPath(relativePath);
+ while (parentPath) {
+ folders[parentPath] = true;
+ parentPath = projectFileParentPath(parentPath);
+ }
+ return folders;
+ }
+
+ function isDestinationVisible(relativePath: string): boolean {
+ let parentPath = projectFileParentPath(relativePath);
+ while (parentPath) {
+ if (destinationOpenFolders[parentPath] !== true) return false;
+ parentPath = projectFileParentPath(parentPath);
+ }
+ return true;
+ }
+
+ function toggleDestinationFolder(relativePath: string) {
+ destinationOpenFolders = {
+ ...destinationOpenFolders,
+ [relativePath]: destinationOpenFolders[relativePath] !== true
+ };
+ }
+
+ function openMoveDialog(relativePath: string) {
+ if (disabled) return;
+ const destinations = buildMoveDestinationOptions(relativePath);
+ const selectedDestinationPath = destinations.find((destination) => !destination.disabled)?.relativePath ?? '';
+ dialogMode = 'move';
+ dialogName = '';
+ dialogParentPath = '';
+ dialogTargetPath = relativePath;
+ dialogDestinationPath = selectedDestinationPath;
+ destinationOpenFolders = selectedDestinationPath ? openAncestorDestinationFolders(selectedDestinationPath) : {};
+ uploadFile = null;
+ dialogSubmitting = false;
+ dialogError = null;
+ dialogOpen = true;
+ }
+
+ function openUploadDialog(parentPath = selectedParentPath) {
+ if (disabled) return;
+ dialogMode = 'upload';
+ dialogName = '';
+ dialogParentPath = '';
+ dialogTargetPath = '';
+ dialogDestinationPath = parentPath;
+ destinationOpenFolders = parentPath ? openAncestorDestinationFolders(parentPath) : {};
+ uploadFile = null;
+ uploadInputKey += 1;
+ dialogSubmitting = false;
+ dialogError = null;
+ dialogOpen = true;
+ }
+
+ function handleUploadFileChange(event: Event) {
+ const input = event.currentTarget as HTMLInputElement;
+ const file = input.files?.[0] ?? null;
+ uploadFile = file;
+ if (file) {
+ dialogName = file.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;
+ }
+ }
+
+ 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();
+ return;
+ }
+
+ onMove?.(dialogTargetPath, dialogDestinationPath);
+ if (dialogDestinationPath) {
+ openFolders = {
+ ...openFolders,
+ [dialogDestinationPath]: true
+ };
+ }
+ dialogOpen = false;
+ return;
+ }
+
+ if (dialogMode === 'rename') {
+ const name = validateProjectFileName(dialogName, dialogParentPath, composeFileName);
+ if (!name) {
+ dialogError = m.project_file_invalid_name();
+ return;
+ }
+
+ const targetPath = joinProjectFilePath(dialogParentPath, name);
+ if (targetPath !== dialogTargetPath && entryByPath.has(targetPath)) {
+ dialogError = m.project_file_duplicate_name();
+ return;
+ }
+
+ onRename?.(dialogTargetPath, name);
+ dialogOpen = false;
+ 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();
+ return;
+ }
+
+ dialogSubmitting = true;
+ const content = await readUploadFileContent(uploadFile);
+ dialogSubmitting = false;
+ if (content === null) {
+ return;
+ }
+
+ onCreateFile?.(dialogDestinationPath, name, content);
+ if (dialogDestinationPath) {
+ openFolders = {
+ ...openFolders,
+ [dialogDestinationPath]: true
+ };
+ }
+ dialogOpen = false;
+ return;
+ }
+
+ if (dialogMode === 'create_folder') {
+ onCreateFolder?.(dialogDestinationPath, name);
+ openFolders = {
+ ...openFolders,
+ [dialogDestinationPath]: true
+ };
+ } else {
+ onCreateFile?.(dialogDestinationPath, name);
+ openFolders = {
+ ...openFolders,
+ [dialogDestinationPath]: true
+ };
+ }
+
+ dialogOpen = false;
+ }
+
+ function handleDelete(entry: ManagedProjectFileEntry) {
+ if (disabled) return;
+ openConfirmDialog({
+ title: m.project_file_delete_title({ name: entry.relativePath }),
+ message: m.project_file_delete_confirm({ name: entry.relativePath }),
+ confirm: {
+ label: m.common_delete(),
+ destructive: true,
+ action: () => onDelete?.(entry.relativePath)
+ }
+ });
+ }
+</script>
+
+<div class="flex min-h-0 flex-1 flex-col">
+ <div class="border-border flex h-9 shrink-0 items-center border-b px-2">
+ <span class="text-muted-foreground text-[11px] font-semibold tracking-wider uppercase">{m.project_files()}</span>
+ {#if canManageFiles}
+ <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.project_file_new_folder()}
+ onclick={() => openCreateDialog('create_folder')}
+ />
+ </Tooltip.Trigger>
+ <Tooltip.Content>{m.project_file_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.project_file_upload_file()}
+ onclick={() => openUploadDialog()}
+ />
+ </Tooltip.Trigger>
+ <Tooltip.Content>{m.project_file_upload_file()}</Tooltip.Content>
+ </Tooltip.Root>
+ </div>
+ {/if}
+ </div>
+
+ {#if readOnlyMessage}
+ <div class="text-muted-foreground border-border border-b px-3 py-2 text-xs">{readOnlyMessage}</div>
+ {/if}
+
+ <div class="min-h-0 flex-1 overflow-auto">
+ <TreeView.Root class="min-w-max p-2 whitespace-nowrap">
+ <button
+ type="button"
+ class={cn(
+ 'hover:bg-accent flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-[13px]',
+ 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="text-muted-foreground size-3.5 shrink-0" aria-label={m.project_file_protected()} />
+ </span>
+ </button>
+
+ <button
+ type="button"
+ class={cn(
+ 'hover:bg-accent flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-[13px]',
+ 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="text-muted-foreground size-3.5 shrink-0" aria-label={m.project_file_protected()} />
+ </span>
+ </button>
+
+ {#if rows.length === 0}
+ {#if canManageFiles}
+ <div class="text-muted-foreground px-7 py-3 text-xs">{m.project_files_empty()}</div>
+ {/if}
+ {:else}
+ {#each rows as row (row.relativePath)}
+ <div
+ class={cn(
+ 'group hover:bg-accent flex w-full items-center gap-1.5 rounded-md px-2 py-0.5 text-[13px]',
+ selectedFile === `file:${row.relativePath}` && 'bg-accent'
+ )}
+ style={`padding-left: ${0.5 + row.depth * 1}rem`}
+ >
+ {#if row.isDirectory}
+ <button
+ type="button"
+ class="hover:bg-muted inline-flex size-4 shrink-0 items-center justify-center rounded"
+ aria-label={openFolders[row.relativePath]
+ ? m.project_file_collapse_folder({ name: row.name })
+ : m.project_file_expand_folder({ name: row.name })}
+ onclick={() => toggleFolder(row.relativePath)}
+ >
+ {#if openFolders[row.relativePath] === true}
+ <ArrowDownIcon class="size-3.5" />
+ {:else}
+ <ArrowRightIcon class="size-3.5" />
+ {/if}
+ </button>
+ {:else if hasDirectories}
+ <span class="inline-flex size-4 shrink-0 items-center justify-center"></span>
+ {/if}
+
+ <button
+ type="button"
+ class="flex min-w-0 flex-1 items-center gap-1.5 py-1 text-left"
+ onclick={() => (row.isDirectory ? toggleFolder(row.relativePath) : onSelect(`file:${row.relativePath}`))}
+ >
+ {#if row.isDirectory}
+ <FolderOpenIcon class="size-4 shrink-0 text-amber-500" />
+ {:else}
+ <FileTextIcon class="text-muted-foreground size-4 shrink-0" />
+ {/if}
+ <span class="min-w-0 truncate">{row.name}</span>
+ {#if row.pending}
+ <span
+ class="bg-primary size-1.5 shrink-0 rounded-full"
+ role="img"
+ aria-label={m.common_unsaved_changes()}
+ title={m.common_unsaved_changes()}
+ ></span>
+ {/if}
+ </button>
+
+ {#if canManageFiles}
+ <div class="flex shrink-0 items-center gap-0.5">
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <button
+ type="button"
+ class="text-foreground hover:bg-foreground/10 inline-flex size-6 items-center justify-center rounded"
+ 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.project_file_rename_action()}</Tooltip.Content>
+ </Tooltip.Root>
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <button
+ type="button"
+ class="text-foreground hover:bg-foreground/10 inline-flex size-6 items-center justify-center rounded"
+ 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.project_file_move_action()}</Tooltip.Content>
+ </Tooltip.Root>
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <button
+ type="button"
+ class="text-destructive hover:bg-destructive/10 inline-flex size-6 items-center justify-center rounded"
+ aria-label={m.project_file_delete_label({ name: row.relativePath })}
+ {disabled}
+ onclick={() => handleDelete(row)}
+ >
+ <TrashIcon class="size-3.5" />
+ </button>
+ </Tooltip.Trigger>
+ <Tooltip.Content>{m.common_delete()}</Tooltip.Content>
+ </Tooltip.Root>
+ </div>
+ {/if}
+ </div>
+ {/each}
+ {/if}
+ </TreeView.Root>
+ </div>
+</div>
+
+<Dialog.Root bind:open={dialogOpen}>
+ <Dialog.Content class="max-h-[calc(100vh-2rem)] max-w-2xl overflow-hidden">
+ <form
+ class="flex max-h-[calc(100vh-5rem)] min-h-0 flex-col gap-4"
+ onsubmit={(event) => {
+ event.preventDefault();
+ void handleDialogSubmit();
+ }}
+ >
+ <Dialog.Header>
+ <Dialog.Title>{dialogTitle}</Dialog.Title>
+ <Dialog.Description>
+ {#if dialogMode === 'move'}
+ {m.project_file_move_description({ name: dialogTargetPath })}
+ {:else if dialogMode === 'upload'}
+ {m.project_file_upload_description()}
+ {:else if dialogMode === 'create_file' || dialogMode === 'create_folder'}
+ {dialogDestinationPath ? m.project_file_parent_path({ path: dialogDestinationPath }) : m.project_file_root_path()}
+ {:else}
+ {dialogParentPath ? m.project_file_parent_path({ path: dialogParentPath }) : m.project_file_root_path()}
+ {/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>
+ {#key uploadInputKey}
+ <Input id="project-file-upload" type="file" onchange={handleUploadFileChange} aria-invalid={!!dialogError} />
+ {/key}
+ </div>
+ {/if}
+
+ {#if dialogMode !== 'move'}
+ <div class="space-y-2">
+ <Label for="project-file-name">{m.project_file_name_label()}</Label>
+ <Input
+ id="project-file-name"
+ bind:value={dialogName}
+ placeholder={dialogMode === 'create_folder'
+ ? m.project_file_folder_name_placeholder()
+ : m.project_file_name_placeholder()}
+ aria-invalid={!!dialogError}
+ />
+ </div>
+ {/if}
+
+ {#if hasDestinationPicker}
+ <div class="min-h-0 space-y-2">
+ <Label>{m.project_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
+ class={cn(
+ 'flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm',
+ dialogDestinationPath === option.relativePath && !option.disabled && 'bg-accent',
+ option.disabled ? 'opacity-45' : 'hover:bg-accent'
+ )}
+ style={`padding-left: ${0.5 + option.depth * 1.25}rem`}
+ >
+ {#if option.relativePath && option.hasChildren}
+ <button
+ type="button"
+ class="hover:bg-muted inline-flex size-4 shrink-0 items-center justify-center rounded"
+ aria-label={destinationOpenFolders[option.relativePath]
+ ? m.project_file_collapse_folder({ name: option.label })
+ : m.project_file_expand_folder({ name: option.label })}
+ onclick={() => toggleDestinationFolder(option.relativePath)}
+ >
+ {#if destinationOpenFolders[option.relativePath] === true}
+ <ArrowDownIcon class="size-4" />
+ {:else}
+ <ArrowRightIcon class="size-4" />
+ {/if}
+ </button>
+ {:else}
+ <span class="inline-flex size-4 shrink-0 items-center justify-center"></span>
+ {/if}
+ <button
+ type="button"
+ class={cn('flex min-w-0 flex-1 items-center gap-2 text-left', option.disabled && 'cursor-not-allowed')}
+ disabled={option.disabled}
+ title={option.relativePath || option.label}
+ onclick={() => {
+ dialogDestinationPath = option.relativePath;
+ dialogError = null;
+ }}
+ >
+ <FolderOpenIcon class="size-4 shrink-0 text-amber-500" />
+ <span class="min-w-0 flex-1 truncate">{option.label}</span>
+ </button>
+ {#if option.reason}
+ <span class="text-muted-foreground shrink-0 text-xs">{option.reason}</span>
+ {/if}
+ </div>
+ {/each}
+ </div>
+ </div>
+ {/if}
+
+ {#if dialogError}
+ <p class="text-destructive text-sm">{dialogError}</p>
+ {/if}
+
+ <Dialog.Footer>
+ <ArcaneButton action="cancel" onclick={() => (dialogOpen = false)} />
+ <ArcaneButton
+ action="confirm"
+ type="submit"
+ customLabel={dialogActionLabel}
+ loading={dialogSubmitting}
+ disabled={dialogSubmitting ||
+ (dialogMode === 'move' && !hasValidDestination) ||
+ (dialogMode === 'upload' && !uploadFile)}
+ />
+ </Dialog.Footer>
+ </form>
+ </Dialog.Content>
+</Dialog.Root>
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.ts
new file mode 100644
index 000000000..549f8894c
--- /dev/null
+++ b/frontend/src/routes/(app)/projects/components/project-file-tree-utils.ts
@@ -0,0 +1,281 @@
+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'
+]);
+
+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/new/+page.svelte b/frontend/src/routes/(app)/projects/new/+page.svelte
index f7bee0086..ad6dc9805 100644
--- a/frontend/src/routes/(app)/projects/new/+page.svelte
+++ b/frontend/src/routes/(app)/projects/new/+page.svelte
@@ -1,6 +1,15 @@
<script lang="ts">
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { ArrowLeftIcon, TerminalIcon, TemplateIcon, AddIcon, GitBranchIcon } from '$lib/icons';
+ import {
+ ArrowLeftIcon,
+ ArrowsUpDownIcon,
+ TerminalIcon,
+ TemplateIcon,
+ AddIcon,
+ GitBranchIcon,
+ FileTextIcon,
+ SearchIcon
+ } from '$lib/icons';
import { Spinner } from '$lib/components/ui/spinner/index.js';
import { goto, invalidateAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
@@ -14,13 +23,32 @@
import { ArrowDownIcon as ChevronDown } from '$lib/icons';
import CodePanel from '../components/CodePanel.svelte';
import EditableName from '../components/EditableName.svelte';
+ import ProjectFileTreePanel from '../components/ProjectFileTreePanel.svelte';
+ import EditorTabStrip from '../components/EditorTabStrip.svelte';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { hasPermission } from '$lib/utils/auth';
import IfPermitted from '$lib/components/if-permitted.svelte';
import { ComposeEditorSplit } from '$lib/components/compose';
+ import ResizableSplit from '$lib/components/resizable-split.svelte';
+ import { Switch } from '$lib/components/ui/switch';
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 {
+ isProjectFileSelectionUnder,
+ planProjectFileCreate,
+ planProjectFileMove,
+ planProjectFileRename,
+ projectFileBasename,
+ projectFileLanguage,
+ projectFilePathMatches,
+ remapProjectFilePath,
+ remapProjectFileRecord,
+ remapSelectedProjectFileKey,
+ removeProjectFileRecord,
+ type ManagedProjectFileEntry
+ } from '../components/project-file-tree-utils';
import {
createComposeEditorSchema,
createComposeTemplateDialogFlow,
@@ -65,6 +93,16 @@
let composeOpen = $state(true);
let envOpen = $state(true);
+ let layoutMode = $state<'classic' | 'tree'>('classic');
+ let selectedProjectFile = $state<'compose' | 'env' | string>('compose');
+ let treePaneWidth = $state(420);
+ const minTreePaneWidth = 200;
+ const maxTreePaneWidth = 480;
+ const minEditorPaneWidth = 360;
+ let newProjectFiles = $state<ProjectFileDraft[]>([]);
+ let newProjectFileContents = $state<Record<string, string>>({});
+ let newProjectFileHasErrors = $state<Record<string, boolean>>({});
+ let newProjectFileValidationReady = $state<Record<string, boolean>>({});
let validation = $state({
composeHasErrors: false,
envHasErrors: false,
@@ -73,6 +111,62 @@
});
const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));
+ const newProjectFileEntries = $derived.by<ManagedProjectFileEntry[]>(() =>
+ newProjectFiles.map((file) => ({
+ path: file.relativePath,
+ relativePath: file.relativePath,
+ name: projectFileBasename(file.relativePath),
+ isDirectory: !!file.isDirectory,
+ size: file.isDirectory ? 0 : (newProjectFileContents[file.relativePath]?.length ?? 0),
+ content: file.isDirectory ? undefined : (newProjectFileContents[file.relativePath] ?? ''),
+ pending: true
+ }))
+ );
+ const newProjectFilePaths = $derived.by(() => new Set(newProjectFileEntries.map((file) => file.relativePath)));
+ let openProjectTabs = $state<string[]>(['compose']);
+ let treeOutlineOpen = $state(false);
+ let treeDiffOpen = $state(false);
+ let treeCommandPaletteOpen = $state(false);
+ const openTabs = $derived.by(() => {
+ 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));
+ return !!entry && !entry.isDirectory;
+ });
+ return valid.length > 0 ? valid : ['compose'];
+ });
+ const activeProjectTab = $derived(openTabs.includes(selectedProjectFile) ? selectedProjectFile : (openTabs[0] ?? 'compose'));
+ const projectTabs = $derived(
+ openTabs.map((key) => ({
+ key,
+ label: key === 'compose' ? 'compose.yaml' : key === 'env' ? '.env' : projectFileBasename(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
+ }))
+ );
+
+ function isNewProjectDirectoryKey(key: string): boolean {
+ if (!key.startsWith('file:')) return false;
+ return newProjectFileEntries.find((file) => file.relativePath === key.slice(5))?.isDirectory === true;
+ }
+
+ function openProjectFileTab(key: string) {
+ if (!isNewProjectDirectoryKey(key) && !openProjectTabs.includes(key)) {
+ openProjectTabs = [...openProjectTabs, key];
+ }
+ selectedProjectFile = key;
+ }
+
+ function closeProjectFileTab(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';
+ }
+ }
const validationState = $derived(
getTemplateEditorValidationState(
validation.composeValidationReady,
@@ -82,6 +176,11 @@
)
);
let hasEditorErrors = $derived(hasTemplateEditorErrors(validationState));
+ const codeEditorContext = $derived({
+ envContent: $inputs.envContent.value,
+ composeContents: [$inputs.composeContent.value].filter((value) => value.length > 0),
+ globalVariables: globalVariableMap
+ });
let nameInputRef = $state<HTMLInputElement | null>(null);
@@ -101,7 +200,8 @@
await submitComposeResourceForm({
validate: () => validateTemplateEditorForm(validationState, form.validate),
setLoading: (value) => (ui.saving = value),
- submit: ({ name, composeContent, envContent }) => projectService.createProject(name, composeContent, envContent),
+ submit: ({ name, composeContent, envContent }) =>
+ projectService.createProject(name, composeContent, envContent, buildNewProjectFilePayload()),
failureMessage: (name) => m.common_create_failed({ resource: `${m.resource_project()} "${name}"` }),
onSuccess: async (project, { name }) => {
toast.success(
@@ -121,6 +221,84 @@
setLoading: (value) => (ui.creatingTemplate = value),
hasEditorErrors: () => hasEditorErrors
});
+
+ function ensureNewProjectFileUiState(relativePath: string) {
+ if (newProjectFileHasErrors[relativePath] === undefined) {
+ newProjectFileHasErrors = {
+ ...newProjectFileHasErrors,
+ [relativePath]: false
+ };
+ }
+ if (newProjectFileValidationReady[relativePath] === undefined) {
+ newProjectFileValidationReady = {
+ ...newProjectFileValidationReady,
+ [relativePath]: true
+ };
+ }
+ }
+
+ function createNewProjectFile(parentPath: string, name: string, content = '') {
+ const relativePath = planProjectFileCreate(newProjectFilePaths, parentPath, name);
+ if (!relativePath) return;
+ newProjectFiles = [...newProjectFiles, { relativePath, isDirectory: false }];
+ newProjectFileContents = { ...newProjectFileContents, [relativePath]: content };
+ ensureNewProjectFileUiState(relativePath);
+ openProjectFileTab(`file:${relativePath}`);
+ }
+
+ function createNewProjectFolder(parentPath: string, name: string) {
+ const relativePath = planProjectFileCreate(newProjectFilePaths, parentPath, name);
+ if (!relativePath) return;
+ newProjectFiles = [...newProjectFiles, { relativePath, isDirectory: true }];
+ selectedProjectFile = `file:${relativePath}`;
+ }
+
+ function applyNewProjectFilePathChange(oldPath: string, newPath: string) {
+ newProjectFiles = newProjectFiles.map((file) => ({
+ ...file,
+ relativePath: remapProjectFilePath(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);
+ if (remappedSelection) {
+ selectedProjectFile = remappedSelection;
+ }
+ }
+
+ function renameNewProjectFile(relativePath: string, newName: string) {
+ const plan = planProjectFileRename(newProjectFilePaths, relativePath, newName);
+ if (!plan) return;
+ applyNewProjectFilePathChange(relativePath, plan.newPath);
+ }
+
+ function moveNewProjectFile(relativePath: string, newParentPath: string) {
+ const entry = newProjectFileEntries.find((file) => file.relativePath === relativePath);
+ const newPath = planProjectFileMove(entry, newProjectFilePaths, relativePath, newParentPath);
+ if (!newPath) return;
+ applyNewProjectFilePathChange(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 buildNewProjectFilePayload(): ProjectFileDraft[] {
+ return newProjectFiles.map((file) => ({
+ relativePath: file.relativePath,
+ isDirectory: !!file.isDirectory,
+ content: file.isDirectory ? undefined : (newProjectFileContents[file.relativePath] ?? '')
+ }));
+ }
</script>
<div class="bg-background flex h-full min-h-0 flex-col">
@@ -272,43 +450,192 @@
/>
</div>
- <ComposeEditorSplit onsubmit={preventDefault(handleSubmit)}>
- {#snippet compose()}
- <CodePanel
- bind:open={composeOpen}
- title={m.compose_compose_file_title()}
- language="yaml"
- bind:value={$inputs.composeContent.value}
- error={$inputs.composeContent.error ?? undefined}
- bind:hasErrors={validation.composeHasErrors}
- bind:validationReady={validation.composeValidationReady}
- fileId="projects:new:compose"
- editorContext={{
- envContent: $inputs.envContent.value,
- composeContents: [$inputs.composeContent.value],
- globalVariables: globalVariableMap
- }}
- />
- {/snippet}
-
- {#snippet env()}
- <CodePanel
- bind:open={envOpen}
- title={m.compose_env_title()}
- language="env"
- bind:value={$inputs.envContent.value}
- error={$inputs.envContent.error ?? undefined}
- bind:hasErrors={validation.envHasErrors}
- bind:validationReady={validation.envValidationReady}
- fileId="projects:new:env"
- editorContext={{
- envContent: $inputs.envContent.value,
- composeContents: [$inputs.composeContent.value],
- globalVariables: globalVariableMap
- }}
- />
- {/snippet}
- </ComposeEditorSplit>
+ <div class="flex shrink-0 items-center justify-end gap-2">
+ <label
+ for="new-project-layout-mode-toggle"
+ class="text-muted-foreground cursor-pointer text-xs"
+ title={m.project_view_description()}
+ >
+ {m.workspace()}
+ </label>
+ <Switch
+ id="new-project-layout-mode-toggle"
+ checked={layoutMode === 'tree'}
+ aria-label={m.project_view_description()}
+ onCheckedChange={(checked) => {
+ layoutMode = checked ? 'tree' : 'classic';
+ openProjectFileTab('compose');
+ }}
+ />
+ </div>
+
+ {#if layoutMode === 'tree'}
+ <div class="bg-card border-border flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border">
+ <ResizableSplit
+ class="min-h-0 flex-1"
+ variant="flush"
+ firstClass="bg-muted/20 border-border flex min-h-0 flex-col border-b lg:border-r lg:border-b-0"
+ secondClass="flex min-h-0 flex-col"
+ bind:size={treePaneWidth}
+ minSize={minTreePaneWidth}
+ maxSize={maxTreePaneWidth}
+ minSecondSize={minEditorPaneWidth}
+ defaultRatio={0.22}
+ stackBelow={1024}
+ ariaLabel={m.compose_editor_resize_files_panel()}
+ persistKey="arcane.compose.split:new-project:tree"
+ >
+ {#snippet first()}
+ <ProjectFileTreePanel
+ composeFileName="compose.yaml"
+ entries={newProjectFileEntries}
+ selectedFile={selectedProjectFile}
+ disabled={ui.saving || ui.isLoadingTemplateContent}
+ onSelect={openProjectFileTab}
+ onCreateFile={createNewProjectFile}
+ onCreateFolder={createNewProjectFolder}
+ onRename={renameNewProjectFile}
+ onMove={moveNewProjectFile}
+ onDelete={deleteNewProjectFile}
+ />
+ {/snippet}
+
+ {#snippet second()}
+ <div class="flex h-full min-h-0 flex-1 flex-col">
+ <EditorTabStrip
+ tabs={projectTabs}
+ activeKey={activeProjectTab}
+ onSelect={openProjectFileTab}
+ onClose={closeProjectFileTab}
+ >
+ {#snippet actions()}
+ <ArcaneButton
+ action="base"
+ tone={treeOutlineOpen ? 'outline-primary' : 'ghost'}
+ size="icon"
+ class="size-6"
+ showLabel={false}
+ icon={FileTextIcon}
+ customLabel={m.compose_editor_toggle_outline()}
+ onclick={() => (treeOutlineOpen = !treeOutlineOpen)}
+ />
+ <ArcaneButton
+ action="base"
+ tone={treeDiffOpen ? 'outline-primary' : 'ghost'}
+ size="icon"
+ class="size-6"
+ showLabel={false}
+ icon={ArrowsUpDownIcon}
+ customLabel={m.compose_editor_toggle_diff()}
+ onclick={() => (treeDiffOpen = !treeDiffOpen)}
+ />
+ <ArcaneButton
+ action="base"
+ tone="ghost"
+ size="icon"
+ class="size-6"
+ showLabel={false}
+ icon={SearchIcon}
+ customLabel={m.compose_editor_command_palette()}
+ onclick={() => (treeCommandPaletteOpen = true)}
+ />
+ {/snippet}
+ </EditorTabStrip>
+ <div class="flex min-h-0 flex-1 flex-col">
+ {#key activeProjectTab}
+ {#if activeProjectTab === 'compose'}
+ <CodePanel
+ variant="plain"
+ bind:open={composeOpen}
+ title={m.compose_compose_file_title()}
+ language="yaml"
+ validationMode="compose"
+ bind:value={$inputs.composeContent.value}
+ error={$inputs.composeContent.error ?? undefined}
+ bind:hasErrors={validation.composeHasErrors}
+ bind:validationReady={validation.composeValidationReady}
+ fileId="projects:new:compose"
+ editorContext={codeEditorContext}
+ bind:outlineOpen={treeOutlineOpen}
+ bind:diffOpen={treeDiffOpen}
+ bind:commandPaletteOpen={treeCommandPaletteOpen}
+ />
+ {:else if activeProjectTab === 'env'}
+ <CodePanel
+ variant="plain"
+ bind:open={envOpen}
+ title={m.compose_env_title()}
+ language="env"
+ validationMode="env"
+ bind:value={$inputs.envContent.value}
+ error={$inputs.envContent.error ?? undefined}
+ bind:hasErrors={validation.envHasErrors}
+ bind:validationReady={validation.envValidationReady}
+ fileId="projects:new:env"
+ editorContext={codeEditorContext}
+ bind:outlineOpen={treeOutlineOpen}
+ bind:diffOpen={treeDiffOpen}
+ bind:commandPaletteOpen={treeCommandPaletteOpen}
+ />
+ {:else if activeProjectTab.startsWith('file:')}
+ {@const relativePath = activeProjectTab.slice(5)}
+ <CodePanel
+ variant="plain"
+ open={true}
+ title={relativePath}
+ language={projectFileLanguage(relativePath)}
+ validationMode="none"
+ bind:value={newProjectFileContents[relativePath]}
+ bind:hasErrors={newProjectFileHasErrors[relativePath]}
+ bind:validationReady={newProjectFileValidationReady[relativePath]}
+ fileId={`projects:new:file:${relativePath}`}
+ originalValue=""
+ enableDiff={true}
+ editorContext={codeEditorContext}
+ bind:outlineOpen={treeOutlineOpen}
+ bind:diffOpen={treeDiffOpen}
+ bind:commandPaletteOpen={treeCommandPaletteOpen}
+ />
+ {/if}
+ {/key}
+ </div>
+ </div>
+ {/snippet}
+ </ResizableSplit>
+ </div>
+ {:else}
+ <ComposeEditorSplit onsubmit={preventDefault(handleSubmit)}>
+ {#snippet compose()}
+ <CodePanel
+ bind:open={composeOpen}
+ title={m.compose_compose_file_title()}
+ language="yaml"
+ validationMode="compose"
+ bind:value={$inputs.composeContent.value}
+ error={$inputs.composeContent.error ?? undefined}
+ bind:hasErrors={validation.composeHasErrors}
+ bind:validationReady={validation.composeValidationReady}
+ fileId="projects:new:compose"
+ editorContext={codeEditorContext}
+ />
+ {/snippet}
+
+ {#snippet env()}
+ <CodePanel
+ bind:open={envOpen}
+ title={m.compose_env_title()}
+ language="env"
+ validationMode="env"
+ bind:value={$inputs.envContent.value}
+ error={$inputs.envContent.error ?? undefined}
+ bind:hasErrors={validation.envHasErrors}
+ bind:validationReady={validation.envValidationReady}
+ fileId="projects:new:env"
+ editorContext={codeEditorContext}
+ />
+ {/snippet}
+ </ComposeEditorSplit>
+ {/if}
</div>
</div>
</div>
diff --git a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte
index cf6c96041..7ba1c9936 100644
--- a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte
@@ -5,7 +5,10 @@
import * as Card from '$lib/components/ui/card';
import * as Tabs from '$lib/components/ui/tabs';
import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';
- import { LayersIcon, DockIcon, JobsIcon, TrashIcon, EditIcon, FileTextIcon, CodeIcon } from '$lib/icons';
+ 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 ResizableSplit from '$lib/components/resizable-split.svelte';
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
import { m } from '$lib/paraglide/messages';
import { swarmService } from '$lib/services/swarm-service';
@@ -26,6 +29,39 @@
let tasks = $state(untrack(() => data.tasks));
let source = $state<SwarmStackSource | null>(untrack(() => data.source));
let sourceState = $state<'loading' | 'available' | 'missing' | 'forbidden' | 'error'>(untrack(() => data.sourceState));
+
+ let selectedSourceFile = $state('compose');
+ let openSourceTabs = $state<string[]>(['compose']);
+ let sourceTreeWidth = $state<number | null>(null);
+ const sourceOpenTabs = $derived(openSourceTabs.length > 0 ? openSourceTabs : ['compose']);
+ const activeSourceTab = $derived(
+ sourceOpenTabs.includes(selectedSourceFile) ? selectedSourceFile : (sourceOpenTabs[0] ?? 'compose')
+ );
+ const sourceTabs = $derived(
+ sourceOpenTabs.map((key) => ({
+ key,
+ label: key === 'compose' ? 'compose.yaml' : '.env',
+ title: key === 'compose' ? 'compose.yaml' : '.env',
+ iconClass: key === 'compose' ? 'text-blue-500' : 'text-green-500',
+ pending: false
+ }))
+ );
+
+ function openSourceTab(key: string) {
+ if (!openSourceTabs.includes(key)) {
+ openSourceTabs = [...openSourceTabs, key];
+ }
+ selectedSourceFile = key;
+ }
+
+ function closeSourceTab(key: string) {
+ const index = sourceOpenTabs.indexOf(key);
+ const remaining = sourceOpenTabs.filter((tab) => tab !== key);
+ openSourceTabs = openSourceTabs.filter((tab) => tab !== key);
+ if (selectedSourceFile === key) {
+ selectedSourceFile = remaining[Math.min(Math.max(index - 1, 0), remaining.length - 1)] ?? 'compose';
+ }
+ }
let servicesRequestOptions = $state(untrack(() => data.servicesRequestOptions));
let tasksRequestOptions = $state(untrack(() => data.tasksRequestOptions));
type StackTab = 'services' | 'tasks' | 'source';
@@ -225,50 +261,71 @@
</Tabs.Content>
<Tabs.Content value="source" class="flex min-h-0 flex-1 flex-col">
{#if sourceState === 'available' && source}
- <div class="grid min-h-0 flex-1 auto-rows-fr gap-6 xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
- <Card.Root class="flex min-h-0 min-w-0 flex-col overflow-hidden">
- <Card.Header icon={CodeIcon} class="flex-shrink-0">
- <Card.Title>
- <h2>compose.yaml</h2>
- </Card.Title>
- </Card.Header>
- <Card.Content class="relative z-0 flex min-h-0 flex-1 flex-col overflow-visible p-0">
- <div class="absolute inset-0 min-h-0 w-full min-w-0 rounded-b-xl">
- <CodeEditor
- value={source.composeContent}
- language="yaml"
- readOnly={true}
- fontSize="13px"
- fileId={`swarm-stack-source:${stackName}:compose.yaml`}
- />
- </div>
- </Card.Content>
- </Card.Root>
+ {@const stackSource = source}
+ <div class="bg-card border-border flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border">
+ <ResizableSplit
+ class="min-h-0 flex-1"
+ variant="flush"
+ firstClass="bg-muted/20 border-border flex min-h-0 flex-col border-b lg:border-r lg:border-b-0"
+ secondClass="flex min-h-0 flex-col"
+ bind:size={sourceTreeWidth}
+ minSize={200}
+ maxSize={480}
+ minSecondSize={360}
+ defaultRatio={0.2}
+ stackBelow={1024}
+ ariaLabel={m.compose_editor_resize_files_panel()}
+ persistKey={`arcane.swarm.split:${stackName}:source`}
+ >
+ {#snippet first()}
+ <ProjectFileTreePanel
+ composeFileName="compose.yaml"
+ entries={[]}
+ selectedFile={selectedSourceFile}
+ onSelect={openSourceTab}
+ />
+ {/snippet}
- <Card.Root class="flex min-h-0 min-w-0 flex-col overflow-hidden">
- <Card.Header icon={FileTextIcon} class="flex-shrink-0">
- <Card.Title>
- <h2>.env</h2>
- </Card.Title>
- </Card.Header>
- <Card.Content class="relative z-0 flex min-h-0 flex-1 flex-col overflow-visible p-0">
- {#if source.envContent?.trim()}
- <div class="absolute inset-0 min-h-0 w-full min-w-0 rounded-b-xl">
- <CodeEditor
- value={source.envContent}
- language="env"
- readOnly={true}
- fontSize="13px"
- fileId={`swarm-stack-source:${stackName}:.env`}
- />
- </div>
- {:else}
- <div class="text-muted-foreground flex flex-1 items-center justify-center p-6 text-center text-sm">
- No saved `.env` file was stored for this stack.
+ {#snippet second()}
+ <div class="flex h-full min-h-0 flex-1 flex-col">
+ <EditorTabStrip
+ tabs={sourceTabs}
+ activeKey={activeSourceTab}
+ onSelect={openSourceTab}
+ onClose={closeSourceTab}
+ />
+ <div class="relative min-h-0 flex-1">
+ {#key activeSourceTab}
+ {#if activeSourceTab === 'compose'}
+ <div class="absolute inset-0 min-h-0 w-full min-w-0">
+ <CodeEditor
+ value={stackSource.composeContent}
+ language="yaml"
+ readOnly={true}
+ fontSize="13px"
+ fileId={`swarm-stack-source:${stackName}:compose.yaml`}
+ />
+ </div>
+ {:else if stackSource.envContent?.trim()}
+ <div class="absolute inset-0 min-h-0 w-full min-w-0">
+ <CodeEditor
+ value={stackSource.envContent}
+ language="env"
+ readOnly={true}
+ fontSize="13px"
+ fileId={`swarm-stack-source:${stackName}:.env`}
+ />
+ </div>
+ {:else}
+ <div class="text-muted-foreground flex h-full items-center justify-center p-6 text-center text-sm">
+ No saved `.env` file was stored for this stack.
+ </div>
+ {/if}
+ {/key}
</div>
- {/if}
- </Card.Content>
- </Card.Root>
+ </div>
+ {/snippet}
+ </ResizableSplit>
</div>
{:else if sourceState === 'loading'}
<Card.Root variant="subtle">
diff --git a/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte
index 0bd078bf3..52c412818 100644
--- a/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte
@@ -10,11 +10,22 @@
import { swarmService } from '$lib/services/swarm-service.js';
import * as ButtonGroup from '$lib/components/ui/button-group/index.js';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import { ArrowLeftIcon, TerminalIcon, TemplateIcon, AddIcon, ArrowDownIcon as ChevronDown, GitBranchIcon } from '$lib/icons';
+ import {
+ ArrowLeftIcon,
+ TerminalIcon,
+ TemplateIcon,
+ AddIcon,
+ ArrowDownIcon as ChevronDown,
+ FileTextIcon,
+ GitBranchIcon,
+ SearchIcon
+ } from '$lib/icons';
import CodePanel from '../../../projects/components/CodePanel.svelte';
import EditableName from '../../../projects/components/EditableName.svelte';
+ import EditorTabStrip from '../../../projects/components/EditorTabStrip.svelte';
+ import ProjectFileTreePanel from '../../../projects/components/ProjectFileTreePanel.svelte';
+ import ResizableSplit from '$lib/components/resizable-split.svelte';
import { environmentStore } from '$lib/stores/environment.store.svelte';
- import { ComposeEditorSplit } from '$lib/components/compose';
import DockerRunConverterDialog from '$lib/components/compose/docker-run-converter-dialog.svelte';
import { globalVariablesToMap } from '$lib/utils/template-load';
import {
@@ -70,6 +81,41 @@
let envOpen = $state(true);
let nameInputRef = $state<HTMLInputElement | null>(null);
+ let selectedStackFile = $state('compose');
+ let openStackTabs = $state<string[]>(['compose']);
+ let stackTreeWidth = $state<number | null>(null);
+ let treeOutlineOpen = $state(false);
+ let treeCommandPaletteOpen = $state(false);
+ const stackOpenTabs = $derived(openStackTabs.length > 0 ? openStackTabs : ['compose']);
+ const activeStackTab = $derived(
+ stackOpenTabs.includes(selectedStackFile) ? selectedStackFile : (stackOpenTabs[0] ?? 'compose')
+ );
+ const stackTabs = $derived(
+ stackOpenTabs.map((key) => ({
+ key,
+ label: key === 'compose' ? 'compose.yaml' : '.env',
+ title: key === 'compose' ? 'compose.yaml' : '.env',
+ iconClass: key === 'compose' ? 'text-blue-500' : 'text-green-500',
+ pending: false
+ }))
+ );
+
+ function openStackTab(key: string) {
+ if (!openStackTabs.includes(key)) {
+ openStackTabs = [...openStackTabs, key];
+ }
+ selectedStackFile = key;
+ }
+
+ function closeStackTab(key: string) {
+ const index = stackOpenTabs.indexOf(key);
+ const remaining = stackOpenTabs.filter((tab) => tab !== key);
+ openStackTabs = openStackTabs.filter((tab) => tab !== key);
+ if (selectedStackFile === key) {
+ selectedStackFile = remaining[Math.min(Math.max(index - 1, 0), remaining.length - 1)] ?? 'compose';
+ }
+ }
+
const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));
async function handleSubmit() {
@@ -249,42 +295,102 @@
/>
</div>
- <ComposeEditorSplit
- class="flex h-full min-h-0 flex-1 flex-col gap-4 px-2 sm:px-6 lg:grid lg:grid-cols-5 lg:grid-rows-1 lg:items-stretch"
- onsubmit={preventDefault(handleSubmit)}
- >
- {#snippet compose()}
- <CodePanel
- bind:open={composeOpen}
- title="compose.yaml"
- language="yaml"
- bind:value={$inputs.composeContent.value}
- error={$inputs.composeContent.error ?? undefined}
- fileId={isEditMode ? `swarm:stacks:${initialName}:compose` : 'swarm:stacks:new:compose'}
- editorContext={{
- envContent: $inputs.envContent.value,
- composeContents: [$inputs.composeContent.value],
- globalVariables: globalVariableMap
- }}
- />
- {/snippet}
+ <form class="flex h-full min-h-0 flex-1 flex-col px-2 pb-4 sm:px-6" onsubmit={preventDefault(handleSubmit)}>
+ <div class="bg-card border-border flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border">
+ <ResizableSplit
+ class="min-h-0 flex-1"
+ variant="flush"
+ firstClass="bg-muted/20 border-border flex min-h-0 flex-col border-b lg:border-r lg:border-b-0"
+ secondClass="flex min-h-0 flex-col"
+ bind:size={stackTreeWidth}
+ minSize={200}
+ maxSize={480}
+ minSecondSize={360}
+ defaultRatio={0.2}
+ stackBelow={1024}
+ ariaLabel={m.compose_editor_resize_files_panel()}
+ persistKey="arcane.swarm.split:new"
+ >
+ {#snippet first()}
+ <ProjectFileTreePanel
+ composeFileName="compose.yaml"
+ entries={[]}
+ selectedFile={selectedStackFile}
+ disabled={ui.saving || ui.isLoadingTemplateContent}
+ onSelect={openStackTab}
+ />
+ {/snippet}
- {#snippet env()}
- <CodePanel
- bind:open={envOpen}
- title=".env"
- language="env"
- bind:value={$inputs.envContent.value}
- error={$inputs.envContent.error ?? undefined}
- fileId={isEditMode ? `swarm:stacks:${initialName}:env` : 'swarm:stacks:new:env'}
- editorContext={{
- envContent: $inputs.envContent.value,
- composeContents: [$inputs.composeContent.value],
- globalVariables: globalVariableMap
- }}
- />
- {/snippet}
- </ComposeEditorSplit>
+ {#snippet second()}
+ <div class="flex h-full min-h-0 flex-1 flex-col">
+ <EditorTabStrip tabs={stackTabs} activeKey={activeStackTab} onSelect={openStackTab} onClose={closeStackTab}>
+ {#snippet actions()}
+ <ArcaneButton
+ action="base"
+ tone={treeOutlineOpen ? 'outline-primary' : 'ghost'}
+ size="icon"
+ class="size-6"
+ showLabel={false}
+ icon={FileTextIcon}
+ customLabel={m.compose_editor_toggle_outline()}
+ onclick={() => (treeOutlineOpen = !treeOutlineOpen)}
+ />
+ <ArcaneButton
+ action="base"
+ tone="ghost"
+ size="icon"
+ class="size-6"
+ showLabel={false}
+ icon={SearchIcon}
+ customLabel={m.compose_editor_command_palette()}
+ onclick={() => (treeCommandPaletteOpen = true)}
+ />
+ {/snippet}
+ </EditorTabStrip>
+ <div class="flex min-h-0 flex-1 flex-col">
+ {#key activeStackTab}
+ {#if activeStackTab === 'compose'}
+ <CodePanel
+ variant="plain"
+ bind:open={composeOpen}
+ title="compose.yaml"
+ language="yaml"
+ bind:value={$inputs.composeContent.value}
+ error={$inputs.composeContent.error ?? undefined}
+ fileId={isEditMode ? `swarm:stacks:${initialName}:compose` : 'swarm:stacks:new:compose'}
+ editorContext={{
+ envContent: $inputs.envContent.value,
+ composeContents: [$inputs.composeContent.value],
+ globalVariables: globalVariableMap
+ }}
+ bind:outlineOpen={treeOutlineOpen}
+ bind:commandPaletteOpen={treeCommandPaletteOpen}
+ />
+ {:else if activeStackTab === 'env'}
+ <CodePanel
+ variant="plain"
+ bind:open={envOpen}
+ title=".env"
+ language="env"
+ bind:value={$inputs.envContent.value}
+ error={$inputs.envContent.error ?? undefined}
+ fileId={isEditMode ? `swarm:stacks:${initialName}:env` : 'swarm:stacks:new:env'}
+ editorContext={{
+ envContent: $inputs.envContent.value,
+ composeContents: [$inputs.composeContent.value],
+ globalVariables: globalVariableMap
+ }}
+ bind:outlineOpen={treeOutlineOpen}
+ bind:commandPaletteOpen={treeCommandPaletteOpen}
+ />
+ {/if}
+ {/key}
+ </div>
+ </div>
+ {/snippet}
+ </ResizableSplit>
+ </div>
+ </form>
</div>
</div>
</div>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index adfd3c2de..ee17f8322 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -75,6 +75,15 @@ importers:
'@codemirror/autocomplete':
specifier: ^6.20.3
version: 6.20.3
+ '@codemirror/lang-javascript':
+ specifier: ^6.2.5
+ version: 6.2.5
+ '@codemirror/lang-json':
+ specifier: ^6.0.2
+ version: 6.0.2
+ '@codemirror/lang-markdown':
+ specifier: ^6.5.0
+ version: 6.5.0
'@codemirror/lang-yaml':
specifier: ^6.1.3
version: 6.1.3
@@ -86,7 +95,7 @@ importers:
version: 6.5.3
'@codemirror/lint':
specifier: ^6.9.6
- version: 6.9.6
+ version: 6.9.7
'@codemirror/merge':
specifier: ^6.12.1
version: 6.12.1
@@ -95,7 +104,7 @@ importers:
version: 6.6.0
'@codemirror/view':
specifier: ^6.43.0
- version: 6.43.0
+ version: 6.43.1
'@fontsource-variable/geist-mono':
specifier: ^5.2.8
version: 5.2.8
@@ -122,7 +131,7 @@ importers:
version: 3.17.0
'@uiw/codemirror-themes':
specifier: ^4.25.10
- version: 4.25.10(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
+ version: 4.25.10(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
'@xterm/addon-fit':
specifier: ^0.11.0
version: 0.11.0
@@ -356,6 +365,21 @@ packages:
'@codemirror/[email protected]':
resolution: {integrity: sha512-JFRiqhKu+bvSkDLI+rUhJwSxQxYb759W5GBezE8Uc8mHLqC9aV/9aTC7yJSqCtB3F00pylrLCwnyS91Ap5ej4Q==}
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-0K40bZ35jpHya6FriukbgaleaqzBLZfOh7HuzqbMxBXkbYMJDxfF39c23xOgxFezR+3G+tR2/Mup+Xk865OMvw==}
+
'@codemirror/[email protected]':
resolution: {integrity: sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ==}
@@ -365,9 +389,6 @@ packages:
'@codemirror/[email protected]':
resolution: {integrity: sha512-xCsmIzH78MyWkib9jlPaaun57XNkfbMIhagfaZVd0iLTqlpw3jXaIcbZm72MTmmn64eTZpBVNjbyYh+QXnxRsg==}
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-6Kp7r6XfCi/D/5sdXieMfg9pJU1bUEx96WITuLU6ESaKizCz0QHFMjY/TaFSbigDdEAIgi93itLBIUETP4oK+A==}
-
'@codemirror/[email protected]':
resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==}
@@ -380,9 +401,6 @@ packages:
'@codemirror/[email protected]':
resolution: {integrity: sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==}
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-V7ZCLQO3Jus9hzh2jVCCPW3mO4IBMr43O37PqSUYautJSnnJF41YlgLw21x0fLJTYvJ+Vkm6Gp+qKGH9pltgXA==}
-
'@codemirror/[email protected]':
resolution: {integrity: sha512-+BIjw/AG3tDQ4pJgTLPYdAW25eDE66YsvM4LKyVPgGzVgZ4a9Wj1SRX8kPVKgBDdPt8oHtZ15F0qx7p0oOHdHw==}
@@ -713,12 +731,27 @@ packages:
resolution: {integrity: sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==}
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-RzBo8r+/6QJeow7aPHIpGVIH59xTcJXp399820gZoMo9noQDRVpJLheIBUicYwKcsbOYoBRoLZlf2720dG/4Tg==}
+
resolution: {integrity: sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==}
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==}
+
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==}
+
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==}
+
resolution: {integrity: sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==}
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-N0SxazMj4k65DBfaf1azqtMZd6u7MqluP84/NZnB/io8Td9aleFmAhz9hcbvSfsxT5tdYlJ5qgv5aMJGY4zEtA==}
+
resolution: {integrity: sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw==}
@@ -2960,7 +2993,7 @@ snapshots:
dependencies:
'@codemirror/language': 6.12.3
'@codemirror/state': 6.6.0
- '@codemirror/view': 6.43.0
+ '@codemirror/view': 6.43.1
'@lezer/common': 1.5.2
'@codemirror/[email protected]':
@@ -2970,6 +3003,51 @@ snapshots:
'@codemirror/view': 6.43.1
'@lezer/common': 1.5.2
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/autocomplete': 6.20.3
+ '@codemirror/language': 6.12.3
+ '@codemirror/state': 6.6.0
+ '@lezer/common': 1.5.2
+ '@lezer/css': 1.3.3
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/autocomplete': 6.20.3
+ '@codemirror/lang-css': 6.3.1
+ '@codemirror/lang-javascript': 6.2.5
+ '@codemirror/language': 6.12.3
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.43.1
+ '@lezer/common': 1.5.2
+ '@lezer/css': 1.3.3
+ '@lezer/html': 1.3.13
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/autocomplete': 6.20.3
+ '@codemirror/language': 6.12.3
+ '@codemirror/lint': 6.9.7
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.43.1
+ '@lezer/common': 1.5.2
+ '@lezer/javascript': 1.5.4
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/language': 6.12.3
+ '@lezer/json': 1.0.3
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/autocomplete': 6.20.3
+ '@codemirror/lang-html': 6.4.11
+ '@codemirror/language': 6.12.3
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.43.1
+ '@lezer/common': 1.5.2
+ '@lezer/markdown': 1.6.4
+
'@codemirror/[email protected]':
dependencies:
'@codemirror/autocomplete': 6.20.3
@@ -2983,7 +3061,7 @@ snapshots:
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.6.0
- '@codemirror/view': 6.43.0
+ '@codemirror/view': 6.43.1
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/lr': 1.4.10
@@ -2993,12 +3071,6 @@ snapshots:
dependencies:
'@codemirror/language': 6.12.3
- '@codemirror/[email protected]':
- dependencies:
- '@codemirror/state': 6.6.0
- '@codemirror/view': 6.43.0
- crelt: 1.0.6
-
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.6.0
@@ -3009,27 +3081,20 @@ snapshots:
dependencies:
'@codemirror/language': 6.12.3
'@codemirror/state': 6.6.0
- '@codemirror/view': 6.43.0
+ '@codemirror/view': 6.43.1
'@lezer/highlight': 1.2.3
style-mod: 4.1.3
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.6.0
- '@codemirror/view': 6.43.0
+ '@codemirror/view': 6.43.1
crelt: 1.0.6
'@codemirror/[email protected]':
dependencies:
'@marijn/find-cluster-break': 1.0.2
- '@codemirror/[email protected]':
- dependencies:
- '@codemirror/state': 6.6.0
- crelt: 1.0.6
- style-mod: 4.1.3
- w3c-keyname: 2.2.8
-
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.6.0
@@ -3284,14 +3349,43 @@ snapshots:
'@lezer/[email protected]': {}
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.2
+ '@lezer/highlight': 1.2.3
+ '@lezer/lr': 1.4.10
+
dependencies:
'@lezer/common': 1.5.2
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.2
+ '@lezer/highlight': 1.2.3
+ '@lezer/lr': 1.4.10
+
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.2
+ '@lezer/highlight': 1.2.3
+ '@lezer/lr': 1.4.10
+
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.2
+ '@lezer/highlight': 1.2.3
+ '@lezer/lr': 1.4.10
+
dependencies:
'@lezer/common': 1.5.2
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.2
+ '@lezer/highlight': 1.2.3
+
dependencies:
'@lezer/common': 1.5.2
@@ -3804,11 +3898,11 @@ snapshots:
'@typescript/native-preview-win32-arm64': 7.0.0-dev.20260609.1
'@typescript/native-preview-win32-x64': 7.0.0-dev.20260609.1
- '@uiw/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
+ '@uiw/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
'@codemirror/language': 6.12.3
'@codemirror/state': 6.6.0
- '@codemirror/view': 6.43.0
+ '@codemirror/view': 6.43.1
dependencies:
diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.ts
index 3def7746b..819c4aadd 100644
--- a/tests/spec/project.spec.ts
+++ b/tests/spec/project.spec.ts
@@ -1013,6 +1013,16 @@ test.describe('GitOps Managed Project', () => {
await configTab.click();
await page.waitForLoadState('load');
+ const layoutSwitch = page.getByRole('switch', {
+ name: /workspace/i
+ });
+ const projectFilesLabel = page.getByText('Project Files', { exact: true });
+ // Projects with extra files default to tree view; start from classic.
+ if (await projectFilesLabel.isVisible().catch(() => false)) {
+ await layoutSwitch.click();
+ await expect(projectFilesLabel).not.toBeVisible();
+ }
+
await page.waitForTimeout(800);
const envEditor = page.locator('.cm-editor:visible').nth(1);
const marker = `ARCANE_E2E_${Date.now()}`;
@@ -1025,12 +1035,10 @@ test.describe('GitOps Managed Project', () => {
await expect(envEditor).toContainText(marker);
await expect(page.getByRole('button', { name: 'Save', exact: true }).first()).toBeVisible();
- const layoutSwitch = page.getByRole('switch', {
- name: /Classic|Tree View/i
- });
if (await layoutSwitch.count()) {
await layoutSwitch.click();
await page.waitForLoadState('load');
+ await expect(projectFilesLabel).toBeVisible();
const envFileButton = page.getByRole('button', { name: '.env' }).first();
await expect(envFileButton).toBeVisible();
@@ -1206,14 +1214,11 @@ test.describe('Project Detail Page', () => {
await configTab.click();
// The project config editor supports two layouts:
- // - classic (default): side-by-side compose.yaml + .env panels
- // - tree view: file list on the left and a single code panel on the right
- await expect(page.getByRole('heading', { name: 'compose.yaml' })).toBeVisible();
-
- const projectFilesHeading = page.getByRole('heading', {
- name: /Project Files/i
- });
- const isTreeView = await projectFilesHeading.isVisible();
+ // - 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);
if (isTreeView) {
const composeFileButton = page.getByRole('button', { name: 'compose.yaml' }).first();
@@ -1221,29 +1226,26 @@ test.describe('Project Detail Page', () => {
await expect(composeFileButton).toBeVisible();
await expect(envFileButton).toBeVisible();
+ await expect(page.locator('[data-tab-key="compose"]')).toBeVisible();
- // Switching files should update the visible code panel title
+ // Selecting files should open and activate their editor tabs
await envFileButton.click();
- await expect(page.getByRole('heading', { name: '.env' })).toBeVisible();
+ await expect(page.locator('[data-tab-key="env"][data-active="true"]')).toBeVisible();
await composeFileButton.click();
- await expect(page.getByRole('heading', { name: 'compose.yaml' })).toBeVisible();
-
- const includesFolder = page.getByRole('button', { name: 'Includes' });
- if (await includesFolder.count()) {
- await expect(includesFolder.first()).toBeVisible();
- }
+ await expect(page.locator('[data-tab-key="compose"][data-active="true"]')).toBeVisible();
} else {
// Classic layout renders both editors at the same time.
+ await expect(page.getByRole('heading', { name: 'compose.yaml' })).toBeVisible();
await expect(page.getByRole('heading', { name: '.env' })).toBeVisible();
// Also validate that we can switch to tree view and see the file list.
const layoutSwitch = page.getByRole('switch', {
- name: /Classic|Tree View/i
+ name: /workspace/i
});
if (await layoutSwitch.count()) {
await layoutSwitch.click();
- await expect(projectFilesHeading).toBeVisible();
+ await expect(projectFilesLabel).toBeVisible();
const composeFileButton = page.getByRole('button', { name: 'compose.yaml' }).first();
const envFileButton = page.getByRole('button', { name: '.env' }).first();
@@ -1252,7 +1254,7 @@ test.describe('Project Detail Page', () => {
await expect(envFileButton).toBeVisible();
await envFileButton.click();
- await expect(page.getByRole('heading', { name: '.env' })).toBeVisible();
+ await expect(page.locator('[data-tab-key="env"][data-active="true"]')).toBeVisible();
}
}
});
@@ -1271,20 +1273,18 @@ test.describe('Project Detail Page', () => {
await page.waitForLoadState('load');
let layoutSwitch = page.getByRole('switch', {
- name: /Classic|Tree View/i
+ name: /workspace/i
});
test.skip(
(await layoutSwitch.count()) === 0,
'No layout switch available for project configuration'
);
- const projectFilesHeading = page.getByRole('heading', {
- name: /Project Files/i
- });
+ const projectFilesLabel = page.getByText('Project Files', { exact: true });
- if (!(await projectFilesHeading.isVisible().catch(() => false))) {
+ if (!(await projectFilesLabel.isVisible().catch(() => false))) {
await layoutSwitch.click();
- await expect(projectFilesHeading).toBeVisible();
+ await expect(projectFilesLabel).toBeVisible();
}
await page.reload();
@@ -1296,8 +1296,8 @@ test.describe('Project Detail Page', () => {
await page.waitForLoadState('load');
}
- await expect(projectFilesHeading).toBeVisible();
- await expect(page.getByRole('heading', { name: 'compose.yaml' })).toBeVisible();
+ await expect(projectFilesLabel).toBeVisible();
+ await expect(page.locator('[data-tab-key="compose"][data-active="true"]')).toBeVisible();
const treeComposeEditor = page.locator('.cm-editor:visible').first();
await expect(treeComposeEditor).toBeVisible();
@@ -1315,7 +1315,7 @@ test.describe('Project Detail Page', () => {
await expect(envFileButton).toBeVisible();
layoutSwitch = page.getByRole('switch', {
- name: /Classic|Tree View/i
+ name: /workspace/i
});
await layoutSwitch.click();
await expect(page.getByRole('heading', { name: 'compose.yaml' })).toBeVisible();
@@ -1356,7 +1356,7 @@ test.describe('Project Detail Page', () => {
.toContain(marker);
const layoutSwitch = page.getByRole('switch', {
- name: /Classic|Tree View/i
+ name: /workspace/i
});
if (await layoutSwitch.count()) {
await layoutSwitch.click();
diff --git a/types/project/project.go b/types/project/project.go
index 08dba0d0a..1d75de1e6 100644
--- a/types/project/project.go
+++ b/types/project/project.go
@@ -25,6 +25,113 @@ type IncludeFile struct {
Content string `json:"content,omitempty"`
}
+// ProjectFile represents a file or folder within a project directory.
+type ProjectFile struct {
+ // 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"`
+
+ // IsDirectory indicates whether this entry is a folder.
+ //
+ // Required: true
+ IsDirectory bool `json:"isDirectory"`
+
+ // Size is the file size in bytes. Directories report zero.
+ //
+ // Required: true
+ Size int64 `json:"size"`
+
+ // ModTime is the last modification time.
+ //
+ // Required: true
+ ModTime time.Time `json:"modTime"`
+
+ // 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"`
+
+ // Content is the file content when explicitly requested.
+ //
+ // Required: false
+ Content string `json:"content,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.
@@ -49,6 +156,11 @@ type CreateProject struct {
//
// Required: false
EnvContent *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.
@@ -67,6 +179,18 @@ type UpdateProject struct {
//
// Required: false
EnvContent *string `json:"envContent,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.
@@ -218,6 +342,7 @@ type DetailsOptions struct {
IncludeIncludeFiles bool
IncludeServiceConfigs bool
IncludeDirectoryFiles bool
+ IncludeProjectFiles bool
IncludeRuntimeServices bool
IncludeUpdateInfo bool
}
@@ -229,6 +354,7 @@ func AllDetails() DetailsOptions {
IncludeIncludeFiles: true,
IncludeServiceConfigs: true,
IncludeDirectoryFiles: true,
+ IncludeProjectFiles: true,
IncludeRuntimeServices: true,
IncludeUpdateInfo: true,
}
@@ -380,6 +506,17 @@ type Details struct {
// Required: false
DirectoryFiles []IncludeFile `json:"directoryFiles,omitempty"`
+ // ProjectFiles contains the editable file tree for project file management.
+ //
+ // Required: false
+ ProjectFiles []ProjectFile `json:"projectFiles,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"`
+
// Status is the current status of the project.
//
// Required: true