Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: support for `include` compose directive (#817)
Elisamuel Resto Donateeced6980dc33
diff --git a/backend/internal/api/project_handler.go b/backend/internal/api/project_handler.goindex c9560039f..32884247c 100644--- a/backend/internal/api/project_handler.go+++ b/backend/internal/api/project_handler.go@@ -60,6 +60,7 @@ func NewProjectHandler(group *gin.RouterGroup, projectService *services.ProjectSapiGroup.POST("/:projectId/redeploy", handler.RedeployProject)apiGroup.DELETE("/:projectId/destroy", handler.DestroyProject)apiGroup.PUT("/:projectId", handler.UpdateProject)+ apiGroup.PUT("/:projectId/includes", handler.UpdateProjectInclude)apiGroup.POST("/:projectId/restart", handler.RestartProject)apiGroup.GET("/:projectId/logs/ws", handler.GetProjectLogsWS)@@ -293,6 +294,36 @@ func (h *ProjectHandler) UpdateProject(c *gin.Context) {})}+func (h *ProjectHandler) UpdateProjectInclude(c *gin.Context) {+ projectID := c.Param("projectId")+ if projectID == "" {+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "Project ID is required"})+ return+ }++ var req dto.UpdateProjectIncludeDto+ if err := c.ShouldBindJSON(&req); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "Invalid request format"})+ return+ }++ if err := h.projectService.UpdateProjectIncludeFile(c.Request.Context(), projectID, req.RelativePath, req.Content); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": err.Error()})+ return+ }++ details, err := h.projectService.GetProjectDetails(c.Request.Context(), projectID)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "Failed to fetch updated project details"})+ return+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": details,+ })+}+func (h *ProjectHandler) RestartProject(c *gin.Context) {projectID := c.Param("projectId")if projectID == "" {diff --git a/backend/internal/dto/project_dto.go b/backend/internal/dto/project_dto.goindex 74b4b8489..adfce2fa1 100644--- a/backend/internal/dto/project_dto.go+++ b/backend/internal/dto/project_dto.go@@ -1,5 +1,11 @@package dto+type IncludeFileDto struct {+ Path string `json:"path"`+ RelativePath string `json:"relativePath"`+ Content string `json:"content"`+}+type CreateProjectDto struct {Name string `json:"name" binding:"required"`ComposeContent string `json:"composeContent" binding:"required"`@@ -12,6 +18,11 @@ type UpdateProjectDto struct {EnvContent *string `json:"envContent,omitempty"`}+type UpdateProjectIncludeDto struct {+ RelativePath string `json:"relativePath" binding:"required"`+ Content string `json:"content" binding:"required"`+}+type CreateProjectReponseDto struct {ID string `json:"id"`Name string `json:"name"`@@ -26,19 +37,20 @@ type CreateProjectReponseDto struct {}type ProjectDetailsDto struct {- ID string `json:"id"`- Name string `json:"name"`- DirName string `json:"dirName,omitempty"`- Path string `json:"path"`- ComposeContent string `json:"composeContent,omitempty"`- EnvContent string `json:"envContent,omitempty"`- Status string `json:"status"`- StatusReason *string `json:"statusReason,omitempty"`- ServiceCount int `json:"serviceCount"`- RunningCount int `json:"runningCount"`- CreatedAt string `json:"createdAt"`- UpdatedAt string `json:"updatedAt"`- Services []any `json:"services,omitempty"`+ ID string `json:"id"`+ Name string `json:"name"`+ DirName string `json:"dirName,omitempty"`+ Path string `json:"path"`+ ComposeContent string `json:"composeContent,omitempty"`+ EnvContent string `json:"envContent,omitempty"`+ IncludeFiles []IncludeFileDto `json:"includeFiles,omitempty"`+ Status string `json:"status"`+ StatusReason *string `json:"statusReason,omitempty"`+ ServiceCount int `json:"serviceCount"`+ RunningCount int `json:"runningCount"`+ CreatedAt string `json:"createdAt"`+ UpdatedAt string `json:"updatedAt"`+ Services []any `json:"services,omitempty"`}type DestroyProjectDto struct {diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.goindex de44d26d3..1efa4ef79 100644--- a/backend/internal/services/project_service.go+++ b/backend/internal/services/project_service.go@@ -204,6 +204,27 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID stringcomposeContent, envContent, _ := s.GetProjectContent(ctx, projectID)+ // Parse include files from the compose file+ var includeFiles []dto.IncludeFileDto+ composeFile, detectErr := projects.DetectComposeFile(proj.Path)+ if detectErr == nil {+ includes, parseErr := projects.ParseIncludes(composeFile)+ if parseErr == nil {+ slog.InfoContext(ctx, "Parsed includes", "count", len(includes), "projectID", projectID)+ for _, inc := range includes {+ includeFiles = append(includeFiles, dto.IncludeFileDto{+ Path: inc.Path,+ RelativePath: inc.RelativePath,+ Content: inc.Content,+ })+ }+ } else {+ slog.WarnContext(ctx, "Failed to parse includes", "error", parseErr, "projectID", projectID)+ }+ } else {+ slog.WarnContext(ctx, "Failed to detect compose file", "error", detectErr, "projectID", projectID, "path", proj.Path)+ }+services, serr := s.GetProjectServices(ctx, projectID)var serviceCount, runningCount int@@ -228,6 +249,7 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID stringresp.UpdatedAt = proj.UpdatedAt.Format(time.RFC3339)resp.ComposeContent = composeContentresp.EnvContent = envContent+ resp.IncludeFiles = includeFilesresp.ServiceCount = serviceCountresp.RunningCount = runningCountresp.DirName = utils.DerefString(proj.DirName)@@ -865,6 +887,20 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, nareturn &proj, nil}+func (s *ProjectService) UpdateProjectIncludeFile(ctx context.Context, projectID, relativePath, content string) error {+ proj, err := s.GetProjectFromDatabaseByID(ctx, projectID)+ if err != nil {+ return err+ }++ if err := projects.WriteIncludeFile(proj.Path, relativePath, content); err != nil {+ return fmt.Errorf("failed to update include file: %w", err)+ }++ slog.InfoContext(ctx, "project include file updated", "projectID", proj.ID, "file", relativePath)+ return nil+}+func (s *ProjectService) StreamProjectLogs(ctx context.Context, projectID string, logsChan chan<- string, follow bool, tail, since string, timestamps bool) error {proj, err := s.GetProjectFromDatabaseByID(ctx, projectID)if err != nil {diff --git a/backend/internal/utils/projects/includes.go b/backend/internal/utils/projects/includes.gonew file mode 100644index 000000000..0a9b517ba--- /dev/null+++ b/backend/internal/utils/projects/includes.go@@ -0,0 +1,268 @@+package projects++import (+ "fmt"+ "os"+ "path/filepath"+ "strings"++ "github.com/goccy/go-yaml"+)++// Security Model for Include Files:+// - READ: Docker Compose allows include files from anywhere (parent dirs, absolute paths, etc.)+// We allow reading from any path to maintain compatibility with standard Docker Compose behavior+// - WRITE/DELETE: Restricted to files within the project directory only for security+// This prevents malicious users from modifying files outside the project scope++type IncludeFile struct {+ Path string `json:"path"`+ RelativePath string `json:"relative_path"`+ Content string `json:"content"`+}++// ParseIncludes reads a compose file and extracts all include directives+func ParseIncludes(composeFilePath string) ([]IncludeFile, error) {+ content, err := os.ReadFile(composeFilePath)+ if err != nil {+ return nil, fmt.Errorf("failed to read compose file: %w", err)+ }++ var composeData map[string]interface{}+ if err := yaml.Unmarshal(content, &composeData); err != nil {+ return nil, fmt.Errorf("failed to parse compose file: %w", err)+ }++ // Look for include at root level only (per Docker Compose spec)+ includes, ok := composeData["include"]+ if !ok {+ return []IncludeFile{}, nil+ }++ composeDir := filepath.Dir(composeFilePath)+ var includeFiles []IncludeFile++ switch v := includes.(type) {+ case []interface{}:+ for _, item := range v {+ if include, err := parseIncludeItem(item, composeDir); err == nil {+ includeFiles = append(includeFiles, include)+ }+ }+ case string:+ if include, err := parseIncludeItem(v, composeDir); err == nil {+ includeFiles = append(includeFiles, include)+ }+ }++ return includeFiles, nil+}++func parseIncludeItem(item interface{}, baseDir string) (IncludeFile, error) {+ var includePath string++ switch v := item.(type) {+ case string:+ includePath = v+ case map[string]interface{}:+ if path, ok := v["path"].(string); ok {+ includePath = path+ }+ default:+ return IncludeFile{}, fmt.Errorf("invalid include item type")+ }++ if includePath == "" {+ return IncludeFile{}, fmt.Errorf("empty include path")+ }++ var fullPath string+ if filepath.IsAbs(includePath) {+ fullPath = includePath+ } else {+ fullPath = filepath.Join(baseDir, includePath)+ }++ fullPath = filepath.Clean(fullPath)++ var content string+ fileContent, err := os.ReadFile(fullPath)+ if err != nil {+ if os.IsNotExist(err) {+ // File doesn't exist yet - return empty content so it can be created+ content = "# This file will be created when you save changes\nservices:\n"+ } else {+ return IncludeFile{}, fmt.Errorf("failed to read include file %s: %w", includePath, err)+ }+ } else {+ content = string(fileContent)+ }++ relativePath := includePath+ if filepath.IsAbs(includePath) {+ if rel, err := filepath.Rel(baseDir, fullPath); err == nil {+ relativePath = rel+ }+ }++ return IncludeFile{+ Path: fullPath,+ RelativePath: relativePath,+ Content: content,+ }, nil+}++// ValidateIncludePathForRead validates that an include path is safe to read+// Allows reading from anywhere (Docker Compose includes can reference external files)+func ValidateIncludePathForRead(includePath string) error {+ if includePath == "" {+ return fmt.Errorf("include path cannot be empty")+ }+ return nil+}++// ValidateIncludePathForWrite ensures the include path is safe for write operations+// Returns the validated absolute path to prevent recomputation after validation+// Only allows writing within the project directory+func ValidateIncludePathForWrite(projectDir, includePath string) (string, error) {+ if includePath == "" {+ return "", fmt.Errorf("include path cannot be empty")+ }++ // Resolve project directory to absolute path and evaluate symlinks+ absProjectDir, err := filepath.Abs(projectDir)+ if err != nil {+ return "", fmt.Errorf("invalid project directory: %w", err)+ }+ absProjectDir = filepath.Clean(absProjectDir)++ // Try to resolve symlinks for the project directory if it exists+ if evalProjectDir, err := filepath.EvalSymlinks(absProjectDir); err == nil {+ absProjectDir = evalProjectDir+ }++ // Resolve include path to absolute path+ var fullPath string+ if filepath.IsAbs(includePath) {+ fullPath = includePath+ } else {+ fullPath = filepath.Join(absProjectDir, includePath)+ }++ absFullPath, err := filepath.Abs(fullPath)+ if err != nil {+ return "", fmt.Errorf("invalid include path: %w", err)+ }+ absFullPath = filepath.Clean(absFullPath)++ // Resolve symlinks in the include path to prevent symlink-based path traversal attacks+ // For parent directories, we evaluate what exists up to the file itself+ evalPath := absFullPath+ if evalFullPath, err := filepath.EvalSymlinks(absFullPath); err == nil {+ evalPath = evalFullPath+ } else if !os.IsNotExist(err) {+ // If error is not "file doesn't exist", it's a real error+ return "", fmt.Errorf("failed to resolve include path: %w", err)+ } else {+ // File doesn't exist yet - evaluate parent directory symlinks+ dir := filepath.Dir(absFullPath)+ if evalDir, err := filepath.EvalSymlinks(dir); err == nil {+ evalPath = filepath.Join(evalDir, filepath.Base(absFullPath))+ } else if !os.IsNotExist(err) {+ return "", fmt.Errorf("failed to resolve parent directory: %w", err)+ }+ // If parent also doesn't exist, use the original path+ // The validation will still catch if it's outside the project+ }++ // Prevent targeting the project directory itself+ if evalPath == absProjectDir {+ return "", fmt.Errorf("include path cannot be the project directory itself")+ }++ // Check if resolved path is within project directory+ projectPrefix := absProjectDir + string(filepath.Separator)+ isWithinProject := strings.HasPrefix(evalPath+string(filepath.Separator), projectPrefix)++ if !isWithinProject {+ return "", fmt.Errorf("write access denied: path is outside project directory")+ }++ return absFullPath, nil+}++// WriteIncludeFile writes content to an include file path+func WriteIncludeFile(projectDir, includePath, content string) error {+ // Get validated absolute path - only allows writes within project+ validatedPath, err := ValidateIncludePathForWrite(projectDir, includePath)+ if err != nil {+ return err+ }++ // Resolve project directory symlinks for comparison+ absProjectDir, err := filepath.Abs(projectDir)+ if err != nil {+ return fmt.Errorf("invalid project directory: %w", err)+ }+ absProjectDir = filepath.Clean(absProjectDir)+ absProjectDir, err = filepath.EvalSymlinks(absProjectDir)+ if err != nil {+ return fmt.Errorf("failed to resolve project directory symlinks: %w", err)+ }+ absProjectDir = filepath.Clean(absProjectDir)++ // Use the validated path for all operations+ dir := filepath.Dir(validatedPath)++ // Only validate that the directory path is not empty or current directory+ if dir == "" || dir == "." {+ return fmt.Errorf("invalid include path: cannot create directory '%s'", dir)+ }++ // Additional check: ensure 'dir' (after resolving symlinks) is inside the project directory+ absDir, err := filepath.Abs(dir)+ if err != nil {+ return fmt.Errorf("invalid include directory: %w", err)+ }+ absDir = filepath.Clean(absDir)+ realDir := absDir+ if evaluatedDir, evalErr := filepath.EvalSymlinks(absDir); evalErr == nil {+ realDir = filepath.Clean(evaluatedDir)+ } else if !os.IsNotExist(evalErr) {+ return fmt.Errorf("failed to resolve include directory symlinks: %w", evalErr)+ }+ projectPrefix := absProjectDir + string(filepath.Separator)+ isWithinProject := strings.HasPrefix(realDir+string(filepath.Separator), projectPrefix) || realDir == absProjectDir+ if !isWithinProject {+ return fmt.Errorf("write access denied: include directory is outside project directory")+ }++ // Only create directory if it doesn't exist+ if _, err := os.Stat(dir); os.IsNotExist(err) {+ if err := os.MkdirAll(dir, 0755); err != nil {+ return fmt.Errorf("failed to create directory: %w", err)+ }+ }++ if err := os.WriteFile(validatedPath, []byte(content), 0600); err != nil {+ return fmt.Errorf("failed to write include file: %w", err)+ }++ return nil+}++// DeleteIncludeFile removes an include file+func DeleteIncludeFile(projectDir, includePath string) error {+ // Get validated absolute path - only allows deletes within project+ validatedPath, err := ValidateIncludePathForWrite(projectDir, includePath)+ if err != nil {+ return err+ }++ // Use the validated path for the operation+ if err := os.Remove(validatedPath); err != nil && !os.IsNotExist(err) {+ return fmt.Errorf("failed to delete include file: %w", err)+ }++ return nil+}diff --git a/backend/internal/utils/projects/includes_test.go b/backend/internal/utils/projects/includes_test.gonew file mode 100644index 000000000..efd918108--- /dev/null+++ b/backend/internal/utils/projects/includes_test.go@@ -0,0 +1,51 @@+package projects++import (+ "os"+ "path/filepath"+ "runtime"+ "testing"+)++func TestWriteIncludeFileCreatesSafeDirectory(t *testing.T) {+ t.Parallel()++ projectDir := t.TempDir()+ includePath := filepath.Join("includes", "config.yaml")+ content := "services: {}\n"++ if err := WriteIncludeFile(projectDir, includePath, content); err != nil {+ t.Fatalf("WriteIncludeFile() returned error: %v", err)+ }++ targetPath := filepath.Join(projectDir, includePath)+ data, err := os.ReadFile(targetPath)+ if err != nil {+ t.Fatalf("failed to read include file: %v", err)+ }++ if string(data) != content {+ t.Fatalf("unexpected file content: got %q, want %q", string(data), content)+ }+}++func TestWriteIncludeFileRejectsSymlinkEscape(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("symlink creation requires elevated privileges on Windows")+ }+ t.Parallel()++ projectDir := t.TempDir()+ outsideDir := t.TempDir()++ linkPath := filepath.Join(projectDir, "link")+ if err := os.Symlink(outsideDir, linkPath); err != nil {+ t.Fatalf("failed to create symlink: %v", err)+ }++ includePath := filepath.Join("link", "escape.yaml")+ err := WriteIncludeFile(projectDir, includePath, "malicious: true\n")+ if err == nil {+ t.Fatalf("WriteIncludeFile() succeeded but expected rejection for symlink escape")+ }+}diff --git a/frontend/src/lib/components/ui/tree-view/index.ts b/frontend/src/lib/components/ui/tree-view/index.tsnew file mode 100644index 000000000..738a22566--- /dev/null+++ b/frontend/src/lib/components/ui/tree-view/index.ts@@ -0,0 +1,14 @@+import TreeView from './tree-view.svelte';+import TreeViewFile from './tree-view-file.svelte';+import TreeViewFolder from './tree-view-folder.svelte';++export {+ TreeView,+ TreeViewFile,+ TreeViewFolder,++ // ...+ TreeView as Root,+ TreeViewFile as File,+ TreeViewFolder as Folder+};diff --git a/frontend/src/lib/components/ui/tree-view/tree-view-file.svelte b/frontend/src/lib/components/ui/tree-view/tree-view-file.sveltenew file mode 100644index 000000000..e7f7957cf--- /dev/null+++ b/frontend/src/lib/components/ui/tree-view/tree-view-file.svelte@@ -0,0 +1,16 @@+<script lang="ts">+ import FileIcon from '@lucide/svelte/icons/file';+ import { cn } from '$lib/utils';+ import type { TreeViewFileProps } from './types';++ let { name, icon, type = 'button', class: className, ...rest }: TreeViewFileProps = $props();+</script>++<button {type} class={cn('flex place-items-center gap-1 pl-[3px]', className)} {...rest}>+ {#if icon}+ {@render icon({ name })}+ {:else}+ <FileIcon class="size-4" />+ {/if}+ <span>{name}</span>+</button>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.sveltenew file mode 100644index 000000000..f01b2d5d3--- /dev/null+++ b/frontend/src/lib/components/ui/tree-view/tree-view-folder.svelte@@ -0,0 +1,30 @@+<script lang="ts">+ import * as Collapsible from '$lib/components/ui/collapsible/index.js';+ import FolderIcon from '@lucide/svelte/icons/folder';+ import FolderOpenIcon from '@lucide/svelte/icons/folder-open';+ import { cn } from '$lib/utils';+ import type { TreeViewFolderProps } from './types';++ let { name, open = $bindable(true), class: className, icon, children }: TreeViewFolderProps = $props();+</script>++<Collapsible.Root bind:open>+ <Collapsible.Trigger class={cn('flex place-items-center gap-1', className)}>+ {#if icon}+ {@render icon({ name, open })}+ {:else if open}+ <FolderOpenIcon class="size-4" />+ {:else}+ <FolderIcon class="size-4" />+ {/if}+ <span>{name}</span>+ </Collapsible.Trigger>+ <Collapsible.Content class="mx-2 border-l">+ <div class="relative flex place-items-start">+ <div class="bg-border mx-2 h-full w-px"></div>+ <div class="flex flex-col">+ {@render children?.()}+ </div>+ </div>+ </Collapsible.Content>+</Collapsible.Root>diff --git a/frontend/src/lib/components/ui/tree-view/tree-view.svelte b/frontend/src/lib/components/ui/tree-view/tree-view.sveltenew file mode 100644index 000000000..14510d1c4--- /dev/null+++ b/frontend/src/lib/components/ui/tree-view/tree-view.svelte@@ -0,0 +1,10 @@+<script lang="ts">+ import { cn } from '$lib/utils';+ import type { TreeViewRootProps } from './types';++ let { children, class: className }: TreeViewRootProps = $props();+</script>++<div class={cn('flex flex-col', className)}>+ {@render children?.()}+</div>diff --git a/frontend/src/lib/components/ui/tree-view/types.ts b/frontend/src/lib/components/ui/tree-view/types.tsnew file mode 100644index 000000000..4a69f79d3--- /dev/null+++ b/frontend/src/lib/components/ui/tree-view/types.ts@@ -0,0 +1,19 @@+import type { WithChildren, WithoutChildren } from 'bits-ui';+import type { Snippet } from 'svelte';+import type { HTMLAttributes, HTMLButtonAttributes } from 'svelte/elements';++export type TreeViewRootProps = HTMLAttributes<HTMLDivElement>;++export type TreeViewFolderProps = WithChildren<{+ name: string;+ open?: boolean;+ class?: string;+ icon?: Snippet<[{ name: string; open: boolean }]>;+}>;++export type TreeViewFilePropsWithoutHTML = WithChildren<{+ name: string;+ icon?: Snippet<[{ name: string }]>;+}>;++export type TreeViewFileProps = WithoutChildren<HTMLButtonAttributes> & TreeViewFilePropsWithoutHTML;diff --git a/frontend/src/lib/services/project-service.ts b/frontend/src/lib/services/project-service.tsindex 9e2b30c20..970e772f2 100644--- a/frontend/src/lib/services/project-service.ts+++ b/frontend/src/lib/services/project-service.ts@@ -58,6 +58,15 @@ export class ProjectService extends BaseAPIService {return this.handleResponse(this.api.put(`/environments/${envId}/projects/${projectId}`, payload));}+ async updateProjectIncludeFile(projectId: string, relativePath: string, content: string): Promise<Project> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const payload = {+ relativePath,+ content+ };+ return this.handleResponse(this.api.put(`/environments/${envId}/projects/${projectId}/includes`, payload));+ }+async restartProject(projectId: string): Promise<Project> {const envId = await environmentStore.getCurrentEnvironmentId();return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectId}/restart`));diff --git a/frontend/src/lib/types/project.type.ts b/frontend/src/lib/types/project.type.tsindex e9dc5f498..9ccc4bcec 100644--- a/frontend/src/lib/types/project.type.ts+++ b/frontend/src/lib/types/project.type.ts@@ -23,6 +23,12 @@ export interface ProjectService {networkSettings?: NetworkSettings;}+export interface IncludeFile {+ path: string;+ relativePath: string;+ content: string;+}+export interface Project {id: string;name: string;@@ -36,6 +42,7 @@ export interface Project {services?: ProjectService[];composeContent?: string;envContent?: string;+ includeFiles?: IncludeFile[];}export interface ProjectStatusCounts {diff --git a/frontend/src/routes/projects/[projectId]/+page.svelte b/frontend/src/routes/projects/[projectId]/+page.svelteindex 74ce780ac..15e238b19 100644--- a/frontend/src/routes/projects/[projectId]/+page.svelte+++ b/frontend/src/routes/projects/[projectId]/+page.svelte@@ -2,12 +2,14 @@import type { Project } from '$lib/types/project.type';import { Button } from '$lib/components/ui/button/index.js';import * as Tabs from '$lib/components/ui/tabs/index.js';+ import * as TreeView from '$lib/components/ui/tree-view/index.js';import { ArcaneButton } from '$lib/components/arcane-button/index.js';import ArrowLeftIcon from '@lucide/svelte/icons/arrow-left';import FileStackIcon from '@lucide/svelte/icons/file-stack';import LayersIcon from '@lucide/svelte/icons/layers';import SettingsIcon from '@lucide/svelte/icons/settings';import LogsIcon from '@lucide/svelte/icons/logs';+ import FileTextIcon from '@lucide/svelte/icons/file-text';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';@@ -48,6 +50,8 @@let originalName = $state(data.editorState.originalName);let originalComposeContent = $state(data.editorState.originalComposeContent);let originalEnvContent = $state(data.editorState.originalEnvContent || '');+ let includeFilesState = $state<Record<string, string>>({});+ let originalIncludeFiles = $state<Record<string, string>>({});const formSchema = z.object({name: z@@ -69,7 +73,8 @@let hasChanges = $derived($inputs.name.value !== originalName ||$inputs.composeContent.value !== originalComposeContent ||- $inputs.envContent.value !== originalEnvContent+ $inputs.envContent.value !== originalEnvContent ||+ JSON.stringify(includeFilesState) !== JSON.stringify(originalIncludeFiles));let canEditName = $derived(!isLoading.saving && project?.status !== 'running' && project?.status !== 'partially running');@@ -79,6 +84,8 @@let selectedTab = $state<'services' | 'compose' | 'logs'>('compose');let composeOpen = $state(true);let envOpen = $state(true);+ let includeFilesPanelStates = $state<Record<string, boolean>>({});+ let selectedFile = $state<'compose' | 'env' | string>('compose');const tabItems = $derived<TabItem[]>([{@@ -133,6 +140,19 @@composeOpen = cur.composeOpen ?? defaultComposeUIPrefs.composeOpen;envOpen = cur.envOpen ?? defaultComposeUIPrefs.envOpen;autoScrollStackLogs = cur.autoScroll ?? defaultComposeUIPrefs.autoScroll;++ // Initialize include file states+ if (project?.includeFiles) {+ const newIncludeState: Record<string, string> = {};+ project.includeFiles.forEach((file) => {+ newIncludeState[file.relativePath] = file.content;+ if (!(file.relativePath in includeFilesPanelStates)) {+ includeFilesPanelStates[file.relativePath] = true;+ }+ });+ includeFilesState = newIncludeState;+ originalIncludeFiles = { ...newIncludeState };+ }});async function handleSaveChanges() {@@ -143,15 +163,30 @@const { name, composeContent, envContent } = validated;+ // First update the main project fileshandleApiResultWithCallbacks({result: await tryCatch(projectService.updateProject(projectId, name, composeContent, envContent)),message: 'Failed to Save Project',setLoadingState: (value) => (isLoading.saving = value),onSuccess: async (updatedStack: Project) => {+ // Then update any changed include files+ for (const relativePath of Object.keys(includeFilesState)) {+ if (includeFilesState[relativePath] !== originalIncludeFiles[relativePath]) {+ const includeResult = await tryCatch(+ projectService.updateProjectIncludeFile(projectId, relativePath, includeFilesState[relativePath])+ );+ if (includeResult.error) {+ toast.error(`Failed to update ${relativePath}: ${includeResult.error.message || 'Unknown error'}`);+ return;+ }+ }+ }+toast.success('Project updated successfully!');originalName = updatedStack.name;originalComposeContent = $inputs.composeContent.value;originalEnvContent = $inputs.envContent.value;+ originalIncludeFiles = { ...includeFilesState };await new Promise((resolve) => setTimeout(resolve, 200));await invalidateAll();}@@ -270,27 +305,85 @@</Tabs.Content><Tabs.Content value="compose" class="h-full">- <div class="grid h-full grid-cols-1 gap-4 lg:grid-cols-5 lg:items-stretch" style="grid-template-rows: 1fr;">- <div class="flex h-full flex-col lg:col-span-3">- <CodePanel- bind:open={composeOpen}- title={m.compose_compose_file_title()}- language="yaml"- bind:value={$inputs.composeContent.value}- placeholder={m.compose_compose_placeholder()}- error={$inputs.composeContent.error ?? undefined}- />+ <div class="flex h-full flex-col gap-4 lg:flex-row">+ <div+ class="border-border bg-card flex w-full flex-col overflow-y-auto rounded-lg border lg:h-full lg:w-fit lg:max-w-xs lg:min-w-48"+ >+ <div class="border-border border-b p-3">+ <h3 class="text-sm font-medium">Project Files</h3>+ </div>+ <div class="p-2">+ <TreeView.Root class="p-2">+ <TreeView.File+ name="compose.yaml"+ onclick={() => (selectedFile = 'compose')}+ class={selectedFile === 'compose' ? 'bg-accent' : ''}+ >+ {#snippet icon()}+ <FileTextIcon class="size-4 text-blue-500" />+ {/snippet}+ </TreeView.File>++ <TreeView.File+ name=".env"+ onclick={() => (selectedFile = 'env')}+ 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="Includes">+ {#each project.includeFiles as includeFile}+ <TreeView.File+ name={includeFile.relativePath}+ onclick={() => (selectedFile = includeFile.relativePath)}+ class={selectedFile === includeFile.relativePath ? 'bg-accent' : ''}+ >+ {#snippet icon()}+ <FileTextIcon class="size-4 text-amber-500" />+ {/snippet}+ </TreeView.File>+ {/each}+ </TreeView.Folder>+ {/if}+ </TreeView.Root>+ </div></div>- <div class="flex h-full flex-col lg:col-span-2">- <CodePanel- bind:open={envOpen}- title={m.compose_env_title()}- language="env"- bind:value={$inputs.envContent.value}- placeholder={m.compose_env_placeholder()}- error={$inputs.envContent.error ?? undefined}- />+ <div class="flex h-full flex-1 flex-col">+ {#if selectedFile === 'compose'}+ <CodePanel+ bind:open={composeOpen}+ title="compose.yaml"+ language="yaml"+ bind:value={$inputs.composeContent.value}+ placeholder={m.compose_compose_placeholder()}+ error={$inputs.composeContent.error ?? undefined}+ />+ {:else if selectedFile === 'env'}+ <CodePanel+ bind:open={envOpen}+ title=".env"+ language="env"+ bind:value={$inputs.envContent.value}+ placeholder={m.compose_env_placeholder()}+ error={$inputs.envContent.error ?? undefined}+ />+ {:else}+ {@const includeFile = project?.includeFiles?.find((f) => f.relativePath === selectedFile)}+ {#if includeFile}+ <CodePanel+ bind:open={includeFilesPanelStates[includeFile.relativePath]}+ title={includeFile.relativePath}+ language="yaml"+ bind:value={includeFilesState[includeFile.relativePath]}+ placeholder="# Include file content"+ />+ {/if}+ {/if}</div></div></Tabs.Content>diff --git a/frontend/src/routes/projects/components/CodePanel.svelte b/frontend/src/routes/projects/components/CodePanel.svelteindex 052d164e0..0cbc2e474 100644--- a/frontend/src/routes/projects/components/CodePanel.svelte+++ b/frontend/src/routes/projects/components/CodePanel.svelte@@ -22,7 +22,7 @@} = $props();</script>-<Card.Root class="flex flex-col lg:h-full">+<Card.Root class="flex h-full flex-col"><Card.Header icon={FileTextIcon} class="flex-shrink-0 items-center"><Card.Title><h2>@@ -30,7 +30,7 @@</h2></Card.Title></Card.Header>- <Card.Content class="min-h-[500px] flex-grow p-0 lg:h-full">+ <Card.Content class="flex-grow p-0"><div class="h-full [&_.cm-content]:text-xs sm:[&_.cm-content]:text-sm"><CodeEditor bind:value {language} {placeholder} />{#if error}diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.tsindex 90734a3eb..96d42e895 100644--- a/tests/spec/project.spec.ts+++ b/tests/spec/project.spec.ts@@ -270,10 +270,29 @@ test.describe('Project Detail Page', () => {await page.goto(`/projects/${firstProject.id || firstProject.name}`);await page.waitForLoadState('networkidle');- await page.getByRole('tab', { name: /Configuration|Config/i }).click();+ const configTab = page.getByRole('tab', { name: /Configuration|Config/i });+ await configTab.click();- await expect(page.getByText(/Compose File/i)).toBeVisible();- await expect(page.getByText(/Environment\s*\(.env\)/i)).toBeVisible();+ const projectFilesHeading = page.getByRole('heading', { name: /Project Files/i });+ await expect(projectFilesHeading).toBeVisible();++ const composeFileButton = page.getByRole('button', { name: 'compose.yaml' }).first();+ const envFileButton = page.getByRole('button', { name: '.env' }).first();++ await expect(composeFileButton).toBeVisible();+ await expect(envFileButton).toBeVisible();++ // Switching files should update the visible code panel title+ await envFileButton.click();+ await expect(page.getByRole('heading', { name: '.env' })).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();+ }});test('should show logs tab for running projects', async ({ page }) => {