Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: rework templates with new schema (#389)
Kyle Mendelle40e06e387a6
diff --git a/backend/internal/api/template_handler.go b/backend/internal/api/template_handler.goindex 83a17fbd3..a1ab38aaa 100644--- a/backend/internal/api/template_handler.go+++ b/backend/internal/api/template_handler.go@@ -10,6 +10,7 @@ import ("time""github.com/gin-gonic/gin"+ "github.com/ofkm/arcane-backend/internal/dto""github.com/ofkm/arcane-backend/internal/models""github.com/ofkm/arcane-backend/internal/services")@@ -29,14 +30,25 @@ func (h *TemplateHandler) GetAllTemplates(c *gin.Context) {if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"success": false,- "error": "Failed to get templates: " + err.Error(),+ "data": gin.H{"error": "Failed to get templates: " + err.Error()},+ })+ return+ }++ var out []dto.ComposeTemplateDto+ if mapped, mapErr := dto.MapSlice[models.ComposeTemplate, dto.ComposeTemplateDto](templates); mapErr == nil {+ out = mapped+ } else {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "data": gin.H{"error": "Failed to map templates: " + mapErr.Error()},})return}c.JSON(http.StatusOK, gin.H{- "success": true,- "templates": templates,+ "success": true,+ "data": out,})}@@ -45,30 +57,38 @@ func (h *TemplateHandler) GetTemplate(c *gin.Context) {if id == "" {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Template ID is required",+ "data": gin.H{"error": "Template ID is required"},})return}template, err := h.templateService.GetTemplate(c.Request.Context(), id)if err != nil {+ status := http.StatusInternalServerError+ msg := "Failed to get template: " + err.Error()if err.Error() == "template not found" {- c.JSON(http.StatusNotFound, gin.H{- "success": false,- "error": "Template not found",- })- return+ status = http.StatusNotFound+ msg = "Template not found"}+ c.JSON(status, gin.H{+ "success": false,+ "data": gin.H{"error": msg},+ })+ return+ }++ var out dto.ComposeTemplateDto+ if mapErr := dto.MapStruct(template, &out); mapErr != nil {c.JSON(http.StatusInternalServerError, gin.H{"success": false,- "error": "Failed to get template: " + err.Error(),+ "data": gin.H{"error": "Failed to map template: " + mapErr.Error()},})return}c.JSON(http.StatusOK, gin.H{- "success": true,- "template": template,+ "success": true,+ "data": out,})}@@ -77,7 +97,7 @@ func (h *TemplateHandler) GetTemplateContent(c *gin.Context) {if id == "" {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Template ID is required",+ "data": gin.H{"error": "Template ID is required"},})return}@@ -86,19 +106,27 @@ func (h *TemplateHandler) GetTemplateContent(c *gin.Context) {if err != nil {c.JSON(http.StatusNotFound, gin.H{"success": false,- "error": "Template not found",+ "data": gin.H{"error": "Template not found"},})return}- var composeContent, envContent string+ var outTemplate dto.ComposeTemplateDto+ if mapErr := dto.MapStruct(template, &outTemplate); mapErr != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "data": gin.H{"error": "Failed to map template: " + mapErr.Error()},+ })+ return+ }+ var composeContent, envContent stringif template.IsRemote {composeContent, envContent, err = h.templateService.FetchTemplateContent(c.Request.Context(), template)if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"success": false,- "error": "Failed to fetch template content: " + err.Error(),+ "data": gin.H{"error": "Failed to fetch template content: " + err.Error()},})return}@@ -110,10 +138,12 @@ func (h *TemplateHandler) GetTemplateContent(c *gin.Context) {}c.JSON(http.StatusOK, gin.H{- "success": true,- "content": composeContent,- "envContent": envContent,- "template": template,+ "success": true,+ "data": gin.H{+ "content": composeContent,+ "envContent": envContent,+ "template": outTemplate,+ },})}@@ -128,7 +158,7 @@ func (h *TemplateHandler) CreateTemplate(c *gin.Context) {if err := c.ShouldBindJSON(&req); err != nil {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Invalid request format: " + err.Error(),+ "data": gin.H{"error": "Invalid request format: " + err.Error()},})return}@@ -140,23 +170,30 @@ func (h *TemplateHandler) CreateTemplate(c *gin.Context) {IsCustom: true,IsRemote: false,}-if req.EnvContent != "" {template.EnvContent = &req.EnvContent}- err := h.templateService.CreateTemplate(c.Request.Context(), template)- if err != nil {+ if err := h.templateService.CreateTemplate(c.Request.Context(), template); err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "data": gin.H{"error": "Failed to create template: " + err.Error()},+ })+ return+ }++ var out dto.ComposeTemplateDto+ if mapErr := dto.MapStruct(template, &out); mapErr != nil {c.JSON(http.StatusInternalServerError, gin.H{"success": false,- "error": "Failed to create template: " + err.Error(),+ "data": gin.H{"error": "Failed to map template: " + mapErr.Error()},})return}c.JSON(http.StatusCreated, gin.H{- "success": true,- "template": template,+ "success": true,+ "data": out,})}@@ -165,7 +202,7 @@ func (h *TemplateHandler) UpdateTemplate(c *gin.Context) {if id == "" {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Template ID is required",+ "data": gin.H{"error": "Template ID is required"},})return}@@ -176,11 +213,10 @@ func (h *TemplateHandler) UpdateTemplate(c *gin.Context) {Content string `json:"content" binding:"required"`EnvContent string `json:"envContent"`}-if err := c.ShouldBindJSON(&req); err != nil {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Invalid request format: " + err.Error(),+ "data": gin.H{"error": "Invalid request format: " + err.Error()},})return}@@ -190,45 +226,47 @@ func (h *TemplateHandler) UpdateTemplate(c *gin.Context) {Description: req.Description,Content: req.Content,}-if req.EnvContent != "" {updates.EnvContent = &req.EnvContent} else {- // If envContent is empty in the request, explicitly set it to nilupdates.EnvContent = nil}- err := h.templateService.UpdateTemplate(c.Request.Context(), id, updates)- if err != nil {+ if err := h.templateService.UpdateTemplate(c.Request.Context(), id, updates); err != nil {+ status := http.StatusInternalServerError+ msg := "Failed to update template: " + err.Error()if err.Error() == "template not found" {- c.JSON(http.StatusNotFound, gin.H{- "success": false,- "error": "Template not found",- })- return+ status = http.StatusNotFound+ msg = "Template not found"}- c.JSON(http.StatusInternalServerError, gin.H{+ c.JSON(status, gin.H{"success": false,- "error": "Failed to update template: " + err.Error(),+ "data": gin.H{"error": msg},})return}- // Fetch the updated template to return in the response- updatedTemplate, err := h.templateService.GetTemplate(c.Request.Context(), id)+ updated, err := h.templateService.GetTemplate(c.Request.Context(), id)if err != nil {- // Handle error fetching the updated template, though the update succeededc.JSON(http.StatusOK, gin.H{"success": true,- "message": "Template updated successfully, but failed to fetch updated template details.",+ "data": gin.H{"message": "Template updated successfully"},+ })+ return+ }++ var out dto.ComposeTemplateDto+ if mapErr := dto.MapStruct(updated, &out); mapErr != nil {+ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": gin.H{"message": "Template updated successfully"},})return}c.JSON(http.StatusOK, gin.H{- "success": true,- "message": "Template updated successfully",- "template": updatedTemplate, // Return the updated template+ "success": true,+ "data": out,})}@@ -237,30 +275,28 @@ func (h *TemplateHandler) DeleteTemplate(c *gin.Context) {if id == "" {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Template ID is required",+ "data": gin.H{"error": "Template ID is required"},})return}- err := h.templateService.DeleteTemplate(c.Request.Context(), id)- if err != nil {+ if err := h.templateService.DeleteTemplate(c.Request.Context(), id); err != nil {+ status := http.StatusInternalServerError+ msg := "Failed to delete template: " + err.Error()if err.Error() == "template not found" {- c.JSON(http.StatusNotFound, gin.H{- "success": false,- "error": "Template not found",- })- return+ status = http.StatusNotFound+ msg = "Template not found"}- c.JSON(http.StatusInternalServerError, gin.H{+ c.JSON(status, gin.H{"success": false,- "error": "Failed to delete template: " + err.Error(),+ "data": gin.H{"error": msg},})return}c.JSON(http.StatusOK, gin.H{"success": true,- "message": "Template deleted successfully",+ "data": gin.H{"message": "Template deleted successfully"},})}@@ -268,7 +304,7 @@ func (h *TemplateHandler) GetEnvTemplate(c *gin.Context) {content := h.templateService.GetEnvTemplate()c.JSON(http.StatusOK, gin.H{"success": true,- "content": content,+ "data": gin.H{"content": content},})}@@ -276,27 +312,25 @@ func (h *TemplateHandler) SaveEnvTemplate(c *gin.Context) {var req struct {Content string `json:"content" binding:"required"`}-if err := c.ShouldBindJSON(&req); err != nil {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Invalid request format: " + err.Error(),+ "data": gin.H{"error": "Invalid request format: " + err.Error()},})return}- err := h.templateService.SaveEnvTemplate(req.Content)- if err != nil {+ if err := h.templateService.SaveEnvTemplate(req.Content); err != nil {c.JSON(http.StatusInternalServerError, gin.H{"success": false,- "error": "Failed to save env template: " + err.Error(),+ "data": gin.H{"error": "Failed to save env template: " + err.Error()},})return}c.JSON(http.StatusOK, gin.H{"success": true,- "message": "Environment template saved successfully",+ "data": gin.H{"message": "Environment template saved successfully"},})}@@ -305,14 +339,23 @@ func (h *TemplateHandler) GetRegistries(c *gin.Context) {if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"success": false,- "error": "Failed to get registries: " + err.Error(),+ "data": gin.H{"error": "Failed to get registries: " + err.Error()},+ })+ return+ }++ out, mapErr := dto.MapSlice[models.TemplateRegistry, dto.TemplateRegistryDto](registries)+ if mapErr != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "data": gin.H{"error": "Failed to map registries: " + mapErr.Error()},})return}c.JSON(http.StatusOK, gin.H{- "success": true,- "registries": registries,+ "success": true,+ "data": out,})}@@ -323,11 +366,10 @@ func (h *TemplateHandler) CreateRegistry(c *gin.Context) {Description string `json:"description"`Enabled bool `json:"enabled"`}-if err := c.ShouldBindJSON(&req); err != nil {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Invalid request format: " + err.Error(),+ "data": gin.H{"error": "Invalid request format: " + err.Error()},})return}@@ -338,19 +380,26 @@ func (h *TemplateHandler) CreateRegistry(c *gin.Context) {Description: req.Description,Enabled: req.Enabled,}-- err := h.templateService.CreateRegistry(c.Request.Context(), registry)- if err != nil {+ if err := h.templateService.CreateRegistry(c.Request.Context(), registry); err != nil {c.JSON(http.StatusInternalServerError, gin.H{"success": false,- "error": "Failed to create registry: " + err.Error(),+ "data": gin.H{"error": "Failed to create registry: " + err.Error()},+ })+ return+ }++ var out dto.TemplateRegistryDto+ if mapErr := dto.MapStruct(registry, &out); mapErr != nil {+ c.JSON(http.StatusCreated, gin.H{+ "success": true,+ "data": gin.H{"message": "Registry created"},})return}c.JSON(http.StatusCreated, gin.H{- "success": true,- "registry": registry,+ "success": true,+ "data": out,})}@@ -359,7 +408,7 @@ func (h *TemplateHandler) UpdateRegistry(c *gin.Context) {if id == "" {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Registry ID is required",+ "data": gin.H{"error": "Registry ID is required"},})return}@@ -370,11 +419,10 @@ func (h *TemplateHandler) UpdateRegistry(c *gin.Context) {Description string `json:"description"`Enabled bool `json:"enabled"`}-if err := c.ShouldBindJSON(&req); err != nil {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Invalid request format: " + err.Error(),+ "data": gin.H{"error": "Invalid request format: " + err.Error()},})return}@@ -385,27 +433,23 @@ func (h *TemplateHandler) UpdateRegistry(c *gin.Context) {Description: req.Description,Enabled: req.Enabled,}-- // Pass the string ID to the service layer- err := h.templateService.UpdateRegistry(c.Request.Context(), id, updates)- if err != nil {+ if err := h.templateService.UpdateRegistry(c.Request.Context(), id, updates); err != nil {+ status := http.StatusInternalServerError+ msg := "Failed to update registry: " + err.Error()if err.Error() == "registry not found" {- c.JSON(http.StatusNotFound, gin.H{- "success": false,- "error": "Registry not found",- })- return+ status = http.StatusNotFound+ msg = "Registry not found"}- c.JSON(http.StatusInternalServerError, gin.H{+ c.JSON(status, gin.H{"success": false,- "error": "Failed to update registry: " + err.Error(),+ "data": gin.H{"error": msg},})return}c.JSON(http.StatusOK, gin.H{"success": true,- "message": "Registry updated successfully",+ "data": gin.H{"message": "Registry updated successfully"},})}@@ -414,31 +458,28 @@ func (h *TemplateHandler) DeleteRegistry(c *gin.Context) {if id == "" {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "Registry ID is required",+ "data": gin.H{"error": "Registry ID is required"},})return}- // Pass the string ID to the service layer- err := h.templateService.DeleteRegistry(c.Request.Context(), id)- if err != nil {+ if err := h.templateService.DeleteRegistry(c.Request.Context(), id); err != nil {+ status := http.StatusInternalServerError+ msg := "Failed to delete registry: " + err.Error()if err.Error() == "registry not found" {- c.JSON(http.StatusNotFound, gin.H{- "success": false,- "error": "Registry not found",- })- return+ status = http.StatusNotFound+ msg = "Registry not found"}- c.JSON(http.StatusInternalServerError, gin.H{+ c.JSON(status, gin.H{"success": false,- "error": "Failed to delete registry: " + err.Error(),+ "data": gin.H{"error": msg},})return}c.JSON(http.StatusOK, gin.H{"success": true,- "message": "Registry deleted successfully",+ "data": gin.H{"message": "Registry deleted successfully"},})}@@ -447,21 +488,15 @@ func (h *TemplateHandler) FetchRegistry(c *gin.Context) {if url == "" {c.JSON(http.StatusBadRequest, gin.H{"success": false,- "error": "URL parameter is required",+ "data": gin.H{"error": "URL parameter is required"},})return}- client := &http.Client{- Timeout: 30 * time.Second,- }-+ client := &http.Client{Timeout: 30 * time.Second}req, err := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, url, nil)if err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid URL: " + err.Error(),- })+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Invalid URL: " + err.Error()}})return}@@ -472,19 +507,13 @@ func (h *TemplateHandler) FetchRegistry(c *gin.Context) {resp, err := client.Do(req)if err != nil {- c.JSON(http.StatusBadGateway, gin.H{- "success": false,- "error": "Failed to fetch registry: " + err.Error(),- })+ c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": "Failed to fetch registry: " + err.Error()}})return}defer resp.Body.Close()if resp.StatusCode != http.StatusOK {- c.JSON(http.StatusBadGateway, gin.H{- "success": false,- "error": fmt.Sprintf("Registry returned status %d", resp.StatusCode),- })+ c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": fmt.Sprintf("Registry returned status %d", resp.StatusCode)}})return}@@ -492,10 +521,7 @@ func (h *TemplateHandler) FetchRegistry(c *gin.Context) {if strings.Contains(resp.Header.Get("Content-Encoding"), "gzip") {gzipReader, err := gzip.NewReader(resp.Body)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to create gzip reader: " + err.Error(),- })+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to create gzip reader: " + err.Error()}})return}defer gzipReader.Close()@@ -504,65 +530,53 @@ func (h *TemplateHandler) FetchRegistry(c *gin.Context) {body, err := io.ReadAll(reader)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to read response: " + err.Error(),- })+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to read response: " + err.Error()}})return}var registry interface{}if err := json.Unmarshal(body, ®istry); err != nil {- c.JSON(http.StatusBadGateway, gin.H{- "success": false,- "error": "Invalid JSON response: " + err.Error(),- })+ c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": "Invalid JSON response: " + err.Error()}})return}- c.Header("Content-Type", "application/json")- c.Data(http.StatusOK, "application/json", body)+ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": registry,+ })}func (h *TemplateHandler) DownloadTemplate(c *gin.Context) {id := c.Param("id")if id == "" {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Template ID is required",- })+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Template ID is required"}})return}template, err := h.templateService.GetTemplate(c.Request.Context(), id)if err != nil {- c.JSON(http.StatusNotFound, gin.H{- "success": false,- "error": "Template not found",- })+ c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Template not found"}})return}-if !template.IsRemote {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Template is already local",- })+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Template is already local"}})return}localTemplate, err := h.templateService.DownloadTemplate(c.Request.Context(), template)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to download template: " + err.Error(),- })+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to download template: " + err.Error()}})+ return+ }++ var out dto.ComposeTemplateDto+ if mapErr := dto.MapStruct(localTemplate, &out); mapErr != nil {+ c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"message": "Template downloaded successfully"}})return}c.JSON(http.StatusOK, gin.H{- "success": true,- "template": localTemplate,- "message": "Template downloaded successfully",+ "success": true,+ "data": out,})}diff --git a/backend/internal/dto/template.go b/backend/internal/dto/template.godeleted file mode 100644index aac99811c..000000000--- a/backend/internal/dto/template.go+++ /dev/null@@ -1,21 +0,0 @@-package dto--type RemoteTemplate struct {- ID string `json:"id"`- Name string `json:"name"`- Description string `json:"description"`- Version string `json:"version"`- Author string `json:"author"`- Tags []string `json:"tags,omitempty"`- ComposeURL string `json:"composeUrl"`- EnvURL string `json:"envUrl,omitempty"`- DocsURL string `json:"docsUrl,omitempty"`- IconURL string `json:"iconUrl,omitempty"`- UpdatedAt string `json:"updatedAt,omitempty"`-}--type RemoteRegistry struct {- Name string `json:"name"`- Description string `json:"description,omitempty"`- Templates []RemoteTemplate `json:"templates"`-}diff --git a/backend/internal/dto/template_dto.go b/backend/internal/dto/template_dto.gonew file mode 100644index 000000000..e0a7f459f--- /dev/null+++ b/backend/internal/dto/template_dto.go@@ -0,0 +1,55 @@+package dto++type RemoteTemplate struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Description string `json:"description"`+ Version string `json:"version"`+ Author string `json:"author"`+ ComposeURL string `json:"compose_url"`+ EnvURL string `json:"env_url"`+ DocumentationURL string `json:"documentation_url"`+ Tags []string `json:"tags"`+}++type RemoteRegistry struct {+ Schema string `json:"$schema,omitempty"`+ Name string `json:"name"`+ Description string `json:"description"`+ Version string `json:"version"`+ Author string `json:"author"`+ URL string `json:"url"`+ Templates []RemoteTemplate `json:"templates"`+}++type TemplateRegistryDto struct {+ ID string `json:"id"`+ Name string `json:"name"`+ URL string `json:"url"`+ Enabled bool `json:"enabled"`+ Description string `json:"description"`+}++type ComposeTemplateMetadataDto struct {+ Version *string `json:"version,omitempty"`+ Author *string `json:"author,omitempty"`+ Tags *string `json:"tags,omitempty"`+ RemoteURL *string `json:"remoteUrl,omitempty"`+ EnvURL *string `json:"envUrl,omitempty"`+ DocumentationURL *string `json:"documentationUrl,omitempty"`+ IconURL *string `json:"iconUrl,omitempty"`+ UpdatedAt *string `json:"updatedAt,omitempty"`+}++type ComposeTemplateDto struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Description string `json:"description"`+ Content string `json:"content"`+ EnvContent *string `json:"envContent,omitempty"`+ IsCustom bool `json:"isCustom"`+ IsRemote bool `json:"isRemote"`+ RegistryID *string `json:"registryId,omitempty"`+ Registry *TemplateRegistryDto `json:"registry,omitempty"`+ Metadata *ComposeTemplateMetadataDto `json:"metadata,omitempty"`+}diff --git a/backend/internal/models/template.go b/backend/internal/models/template.goindex d24575144..cbb52b83d 100644--- a/backend/internal/models/template.go+++ b/backend/internal/models/template.go@@ -29,7 +29,6 @@ type ComposeTemplateMetadata struct {EnvURL *string `json:"envUrl,omitempty" gorm:"column:meta_env_url"`DocumentationURL *string `json:"documentationUrl,omitempty" gorm:"column:meta_documentation_url"`IconURL *string `json:"iconUrl,omitempty" gorm:"column:meta_icon_url"`- UpdatedAt *string `json:"updatedAt,omitempty" gorm:"column:meta_updated_at"`}func (TemplateRegistry) TableName() string {diff --git a/backend/internal/services/template_service.go b/backend/internal/services/template_service.goindex 39b5546cb..ff05d3691 100644--- a/backend/internal/services/template_service.go+++ b/backend/internal/services/template_service.go@@ -11,7 +11,7 @@ import ("path/filepath""regexp""strings"- "sync"+ "sync/atomic""time""github.com/ofkm/arcane-backend/internal/database"@@ -20,69 +20,115 @@ import ("gorm.io/gorm")-type TemplateService struct {- db *database.DB- // Add fields for caching remote templates- remoteTemplatesCache []models.ComposeTemplate- lastRemoteFetch time.Time- remoteFetchMutex sync.Mutex+type remoteCache struct {+ templates []models.ComposeTemplate+ lastFetch time.Time+}- httpClient *http.Client+type cacheCmd struct {+ kind string+ ctx context.Context+ reply chan error}-const remoteCacheDuration = 5 * time.Minute // Cache duration+type TemplateService struct {+ db *database.DB+ cacheCmdCh chan cacheCmd+ remoteCache atomic.Value+ httpClient *http.Client+}++const remoteCacheDuration = 5 * time.Minute++// Remote public ID helpers+const remoteIDPrefix = "remote"++func makeRemoteID(registryID, slug string) string {+ return fmt.Sprintf("%s:%s:%s", remoteIDPrefix, registryID, slug)+}func NewTemplateService(db *database.DB) *TemplateService {- return &TemplateService{+ s := &TemplateService{db: db,httpClient: &http.Client{Timeout: 30 * time.Second},+ cacheCmdCh: make(chan cacheCmd, 1),}+ s.remoteCache.Store(remoteCache{})+ s.startRemoteCacheWorker()+ return s}-// Helper to load remote templates into cache-func (s *TemplateService) ensureRemoteTemplatesLoaded(ctx context.Context) error {- s.remoteFetchMutex.Lock()- defer s.remoteFetchMutex.Unlock()+func (s *TemplateService) startRemoteCacheWorker() {+ go func() {+ for cmd := range s.cacheCmdCh {+ switch cmd.kind {+ case "ensure":+ rc := s.getRemoteCache()+ if rc.templates != nil && time.Since(rc.lastFetch) < remoteCacheDuration {+ cmd.reply <- nil+ continue+ }+ templates, err := s.loadRemoteTemplates(cmd.ctx)+ if err == nil {+ s.setRemoteCache(remoteCache{templates: templates, lastFetch: time.Now()})+ }+ cmd.reply <- err+ }+ }+ }()+}- // Check if cache is fresh- if time.Since(s.lastRemoteFetch) < remoteCacheDuration && s.remoteTemplatesCache != nil {- return nil // Cache is fresh+func (s *TemplateService) getRemoteCache() remoteCache {+ if v := s.remoteCache.Load(); v != nil {+ if rc, ok := v.(remoteCache); ok {+ return rc+ }}+ return remoteCache{}+}- // Fetch and update cache- fetchedTemplates, err := s.loadRemoteTemplates(ctx) // This function already exists- if err != nil {- // Log the error but don't fail the request if local templates are available- fmt.Printf("Warning: failed to refresh remote templates cache: %v\n", err)- // Keep the old cache if fetching failed, unless it's the first fetch- if s.remoteTemplatesCache == nil {- return fmt.Errorf("failed to load remote templates: %w", err)+func (s *TemplateService) setRemoteCache(rc remoteCache) {+ s.remoteCache.Store(rc)+}++func (s *TemplateService) ensureRemoteTemplatesLoaded(ctx context.Context) error {+ reply := make(chan error, 1)+ select {+ case s.cacheCmdCh <- cacheCmd{kind: "ensure", ctx: ctx, reply: reply}:+ case <-ctx.Done():+ return ctx.Err()+ }+ select {+ case err := <-reply:+ if err != nil {+ fmt.Printf("Warning: failed to refresh remote templates cache: %v\n", err)+ // If we have no cache at all, bubble the error+ if len(s.getRemoteCache().templates) == 0 {+ return fmt.Errorf("failed to load remote templates: %w", err)+ }}- return nil // Use stale cache if fetch failed+ return nil+ case <-ctx.Done():+ return ctx.Err()}-- s.remoteTemplatesCache = fetchedTemplates- s.lastRemoteFetch = time.Now()- return nil}func (s *TemplateService) GetAllTemplates(ctx context.Context) ([]models.ComposeTemplate, error) {var templates []models.ComposeTemplate- // Get local templateserr := s.db.WithContext(ctx).Preload("Registry").Find(&templates).Errorif err != nil {return nil, fmt.Errorf("failed to get local templates: %w", err)}- // Ensure remote templates are loaded into cacheerr = s.ensureRemoteTemplatesLoaded(ctx)if err != nil {- // Log the error but proceed with local templates if remote loading failedfmt.Printf("Warning: failed to load remote templates for GetAllTemplates: %v\n", err)} else {- // Append remote templates from cache- templates = append(templates, s.remoteTemplatesCache...)+ rc := s.getRemoteCache()+ if len(rc.templates) > 0 {+ templates = append(templates, rc.templates...)+ }}return templates, nil@@ -91,35 +137,28 @@ func (s *TemplateService) GetAllTemplates(ctx context.Context) ([]models.Composefunc (s *TemplateService) GetTemplate(ctx context.Context, id string) (*models.ComposeTemplate, error) {var template models.ComposeTemplate- // 1. Try to find in local database+ // Local DB by ID (keeps DB concerns in models)err := s.db.WithContext(ctx).Preload("Registry").Where("id = ?", id).First(&template).Errorif err == nil {- return &template, nil // Found a local template+ return &template, nil}-- // If not found in DB, check if it's a record not found errorif !errors.Is(err, gorm.ErrRecordNotFound) {- return nil, fmt.Errorf("failed to query local template: %w", err) // Other DB error+ return nil, fmt.Errorf("failed to query local template: %w", err)}- // 2. If not found in local DB, try to find in remote templates cache- err = s.ensureRemoteTemplatesLoaded(ctx) // Ensure cache is loaded/fresh- if err != nil {- // If loading remote templates failed and there's no local template, return not found+ // Remote cache by public ID+ if err := s.ensureRemoteTemplatesLoaded(ctx); err != nil {return nil, fmt.Errorf("template not found (failed to load remote templates): %w", err)}-- // Search in the in-memory cache- for _, remoteTemplate := range s.remoteTemplatesCache {+ rc := s.getRemoteCache()+ for _, remoteTemplate := range rc.templates {+ // Compare against public ID (supports both new composite IDs and legacy slug IDs if present)if remoteTemplate.ID == id {- // Found the remote template in cache- // Return a copy to avoid modifying the cached object directlyfoundTemplate := remoteTemplatereturn &foundTemplate, nil}}- // 3. If not found in local DB or remote cachereturn nil, fmt.Errorf("template not found")}@@ -227,14 +266,61 @@ func (s *TemplateService) GetRegistries(ctx context.Context) ([]models.TemplateR}func (s *TemplateService) CreateRegistry(ctx context.Context, registry *models.TemplateRegistry) error {- err := s.db.WithContext(ctx).Create(registry).Error- if err != nil {+ if registry.Name == "" || registry.Description == "" {+ if registry.URL == "" {+ return fmt.Errorf("registry URL is required")+ }+ if manifest, err := s.fetchRegistryManifest(ctx, registry.URL); err == nil {+ if registry.Name == "" {+ registry.Name = manifest.Name+ }+ if registry.Description == "" {+ registry.Description = manifest.Description+ }+ } else {+ // If required fields are still missing, bubble error+ if registry.Name == "" || registry.Description == "" {+ return fmt.Errorf("failed to fetch registry manifest: %w", err)+ }+ }+ }++ if err := s.db.WithContext(ctx).Create(registry).Error; err != nil {return fmt.Errorf("failed to create registry: %w", err)}++ s.invalidateRemoteCache()return nil}func (s *TemplateService) UpdateRegistry(ctx context.Context, id string, updates *models.TemplateRegistry) error {+ var existing models.TemplateRegistry+ if err := s.db.WithContext(ctx).Where("id = ?", id).First(&existing).Error; err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return errors.New("registry not found")+ }+ return fmt.Errorf("failed to find registry: %w", err)+ }++ urlChanged := updates.URL != "" && updates.URL != existing.URL+ needsHydration := updates.Name == "" || updates.Description == ""+ if (urlChanged || needsHydration) && (updates.URL != "" || existing.URL != "") {+ manifestURL := updates.URL+ if manifestURL == "" {+ manifestURL = existing.URL+ }+ if manifest, err := s.fetchRegistryManifest(ctx, manifestURL); err == nil {+ if updates.Name == "" {+ updates.Name = manifest.Name+ }+ if updates.Description == "" {+ updates.Description = manifest.Description+ }+ } else if urlChanged && (updates.Name == "" || updates.Description == "") {+ return fmt.Errorf("failed to fetch registry manifest: %w", err)+ }+ }+result := s.db.WithContext(ctx).Model(&models.TemplateRegistry{}).Where("id = ?", id).Updates(updates)if result.Error != nil {return result.Error@@ -242,6 +328,8 @@ func (s *TemplateService) UpdateRegistry(ctx context.Context, id string, updatesif result.RowsAffected == 0 {return errors.New("registry not found")}++ s.invalidateRemoteCache()return nil}@@ -253,6 +341,8 @@ func (s *TemplateService) DeleteRegistry(ctx context.Context, id string) error {if result.RowsAffected == 0 {return errors.New("registry not found")}++ s.invalidateRemoteCache()return nil}@@ -264,19 +354,20 @@ func (s *TemplateService) loadRemoteTemplates(ctx context.Context) ([]models.Comreturn nil, err}- for _, registry := range registries {- if !registry.Enabled {+ for i := range registries {+ reg := registries[i]+ if !reg.Enabled {continue}- remoteTemplates, err := s.fetchRegistryTemplates(ctx, registry.URL)+ remoteTemplates, err := s.fetchRegistryTemplates(ctx, reg.URL)if err != nil {- fmt.Printf("Warning: failed to fetch templates from registry %s: %v\n", registry.Name, err)+ fmt.Printf("Warning: failed to fetch templates from registry %s: %v\n", reg.Name, err)continue}for _, rt := range remoteTemplates {- template := s.convertRemoteToLocal(rt, ®istry)+ template := s.convertRemoteToLocal(rt, ®)templates = append(templates, template)}}@@ -284,7 +375,6 @@ func (s *TemplateService) loadRemoteTemplates(ctx context.Context) ([]models.Comreturn templates, nil}-// doGET performs a GET and returns the whole body. Centralizes timeout/client use.func (s *TemplateService) doGET(ctx context.Context, url string) ([]byte, error) {req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)if err != nil {@@ -321,6 +411,21 @@ func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, url stringreturn registry.Templates, nil}+func (s *TemplateService) fetchRegistryManifest(ctx context.Context, url string) (*dto.RemoteRegistry, error) {+ body, err := s.doGET(ctx, url)+ if err != nil {+ return nil, err+ }+ var reg dto.RemoteRegistry+ if err := json.Unmarshal(body, ®); err != nil {+ return nil, fmt.Errorf("failed to parse registry JSON: %w", err)+ }+ if reg.Name == "" || len(reg.Templates) == 0 {+ return nil, fmt.Errorf("invalid registry manifest: missing required fields (name, templates)")+ }+ return ®, nil+}+func (s *TemplateService) convertRemoteToLocal(remote dto.RemoteTemplate, registry *models.TemplateRegistry) models.ComposeTemplate {tagsJSON := ""if len(remote.Tags) > 0 {@@ -329,11 +434,14 @@ func (s *TemplateService) convertRemoteToLocal(remote dto.RemoteTemplate, regist}}+ publicID := makeRemoteID(registry.ID, remote.ID)+return models.ComposeTemplate{+ BaseModel: models.BaseModel{ID: publicID},Name: remote.Name,Description: remote.Description,- Content: "", // Content is not stored for remote templates initially- EnvContent: nil, // EnvContent is not stored for remote templates initially+ Content: "",+ EnvContent: nil,IsCustom: false,IsRemote: true,RegistryID: ®istry.ID,@@ -344,9 +452,8 @@ func (s *TemplateService) convertRemoteToLocal(remote dto.RemoteTemplate, registTags: &tagsJSON,RemoteURL: &remote.ComposeURL,EnvURL: &remote.EnvURL,- DocumentationURL: &remote.DocsURL,- IconURL: &remote.IconURL,- UpdatedAt: &remote.UpdatedAt,+ DocumentationURL: &remote.DocumentationURL,+ IconURL: nil,},}}@@ -402,9 +509,8 @@ func (s *TemplateService) FetchTemplateContent(ctx context.Context, template *moif template.Metadata.EnvURL != nil && *template.Metadata.EnvURL != "" {envContent, err = s.fetchURL(ctx, *template.Metadata.EnvURL)if err != nil {- // Log error but don't fail if env file fetch failsfmt.Printf("Warning: failed to fetch env content from %s: %v\n", *template.Metadata.EnvURL, err)- envContent = "" // Ensure envContent is empty string on failure+ envContent = ""}}@@ -426,7 +532,7 @@ func (s *TemplateService) DownloadTemplate(ctx context.Context, remoteTemplate *// Check if a local version with the same remote ID already exists// This prevents duplicate downloads of the same remote template- existingLocalTemplate, err := s.GetTemplate(ctx, s.generateTemplateID(remoteTemplate.Name)) // Assuming local ID is based on name+ existingLocalTemplate, err := s.GetTemplate(ctx, s.generateTemplateID(remoteTemplate.Name))if err == nil && !existingLocalTemplate.IsRemote {return existingLocalTemplate, fmt.Errorf("template '%s' is already downloaded", remoteTemplate.Name)}@@ -471,3 +577,7 @@ func (s *TemplateService) DownloadTemplate(ctx context.Context, remoteTemplate *return localTemplate, nil}++func (s *TemplateService) invalidateRemoteCache() {+ s.setRemoteCache(remoteCache{})+}diff --git a/backend/resources/migrations/postgres/008_clean_compose_templates.down.sql b/backend/resources/migrations/postgres/008_clean_compose_templates.down.sqlnew file mode 100644index 000000000..60d6d4938--- /dev/null+++ b/backend/resources/migrations/postgres/008_clean_compose_templates.down.sql@@ -0,0 +1,2 @@+ALTER TABLE compose_templates+ ADD COLUMN IF NOT EXISTS meta_updated_at TEXT;\ No newline at end of filediff --git a/backend/resources/migrations/postgres/008_clean_compose_templates.up.sql b/backend/resources/migrations/postgres/008_clean_compose_templates.up.sqlnew file mode 100644index 000000000..2cc3a80df--- /dev/null+++ b/backend/resources/migrations/postgres/008_clean_compose_templates.up.sql@@ -0,0 +1,2 @@+ALTER TABLE compose_templates+ DROP COLUMN IF EXISTS meta_updated_at;\ No newline at end of filediff --git a/backend/resources/migrations/sqlite/008_clean_compose_templates.down.sql b/backend/resources/migrations/sqlite/008_clean_compose_templates.down.sqlnew file mode 100644index 000000000..6e8ecf220--- /dev/null+++ b/backend/resources/migrations/sqlite/008_clean_compose_templates.down.sql@@ -0,0 +1 @@+ALTER TABLE compose_templates ADD COLUMN meta_updated_at TEXT;\ No newline at end of filediff --git a/backend/resources/migrations/sqlite/008_clean_compose_templates.up.sql b/backend/resources/migrations/sqlite/008_clean_compose_templates.up.sqlnew file mode 100644index 000000000..f7590971d--- /dev/null+++ b/backend/resources/migrations/sqlite/008_clean_compose_templates.up.sql@@ -0,0 +1 @@+ALTER TABLE compose_templates DROP COLUMN meta_updated_at;\ No newline at end of filediff --git a/frontend/src/lib/components/dialogs/template-selection-dialog.svelte b/frontend/src/lib/components/dialogs/template-selection-dialog.svelteindex cc8de72f8..35f5aea6e 100644--- a/frontend/src/lib/components/dialogs/template-selection-dialog.svelte+++ b/frontend/src/lib/components/dialogs/template-selection-dialog.svelte@@ -3,52 +3,120 @@import { Button } from '$lib/components/ui/button/index.js';import { Card } from '$lib/components/ui/card/index.js';import { Badge } from '$lib/components/ui/badge/index.js';- import { FileText, Globe, FolderOpen, Settings, Download, Loader2 } from '@lucide/svelte';+ import { FileText, Globe, FolderOpen, Settings, Download, Loader2, ChevronDown, ChevronRight } from '@lucide/svelte';+ import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';import { templateAPI } from '$lib/services/api';import type { Template } from '$lib/types/template.type';+ import { Label } from '$lib/components/ui/label/index.js';+ import * as Select from '$lib/components/ui/select/index.js';+ import * as Collapsible from '$lib/components/ui/collapsible/index.js';+ import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';+import { toast } from 'svelte-sonner';interface Props {open: boolean;- templates: Template[];+ templates?: Template[];onSelect: (template: Template) => void;onDownloadSuccess?: () => void;}- let { open = $bindable(), templates, onSelect, onDownloadSuccess }: Props = $props(); // Include new prop+ let { open = $bindable(), templates = [], onSelect, onDownloadSuccess }: Props = $props();let loadingStates = $state(new Map<string, boolean>());+ const allTemplates = $derived(templates ?? []);++ // UI state+ let sortBy = $state<'name-asc' | 'name-desc'>('name-asc');+ let groupByRegistry = $state(true);+ let openGroups = $state<Set<string>>(new Set());++ function normalizeTags(template: Template): string[] {+ const raw = template.metadata?.tags;+ let list: unknown = raw;++ if (typeof raw === 'string') {+ const s = raw.trim();+ if (s.startsWith('[')) {+ try {+ list = JSON.parse(s);+ } catch {+ list = s.split(',').map((t) => t.trim());+ }+ } else {+ list = s.split(',').map((t) => t.trim());+ }+ }++ const arr = Array.isArray(list) ? list : [];+ return arr+ .map((t) => String(t).trim())+ .filter(Boolean)+ .map((t) => t.replace(/^["']|["']$/g, '')) // strip quotes+ .map((t) => t.charAt(0).toUpperCase() + t.slice(1)); // capitalize first letter+ }++ function getRegistryName(t: Template): string {+ return t.registry?.name ?? (t.isRemote ? 'Remote' : 'Local');+ }++ function sortTemplates(items: Template[]): Template[] {+ const sorted = [...items];+ if (sortBy === 'name-asc') {+ sorted.sort((a, b) => a.name.localeCompare(b.name));+ } else {+ sorted.sort((a, b) => b.name.localeCompare(a.name));+ }+ return sorted;+ }++ type Group = { key: string; name: string; items: Template[] };++ const filters = {+ 'name-asc': 'Name (A-Z)',+ 'name-desc': 'Name (Z-A)'+ };++ const grouped: Group[] = $derived(+ !groupByRegistry+ ? []+ : Array.from(+ allTemplates.reduce((map, t) => {+ const key = getRegistryName(t);+ const arr = map.get(key) ?? [];+ arr.push(t);+ map.set(key, arr);+ return map;+ }, new Map<string, Template[]>())+ )+ .map(([key, items]) => ({+ key,+ name: key,+ items: sortTemplates(items)+ }))+ .sort((a, b) => a.name.localeCompare(b.name))+ );async function handleSelect(template: Template) {loadingStates.set(template.id, true);loadingStates = new Map(loadingStates);try {- const templateDetails = await templateAPI.getTemplateContent(template.id);-- if (!templateDetails.content) {+ const details = await templateAPI.getTemplateContent(template.id);+ if (!details?.content) {toast.error('Failed to load template content');return;}-- const finalTemplate = {- ...templateDetails.template,- content: templateDetails.content,- envContent: templateDetails.envContent- };-- onSelect(finalTemplate);+ onSelect({+ ...details.template,+ content: details.content,+ envContent: details.envContent+ });open = false;toast.success(`Template "${template.name}" loaded successfully!`);} catch (error) {console.error('Error loading template:', error);- let errorMessage = 'Failed to load template content';- if (error instanceof Error) {- errorMessage = error.message;- } else if (error && typeof error === 'object' && 'message' in error) {- errorMessage = String(error.message);- }- toast.error(errorMessage);+ toast.error(error instanceof Error ? error.message : 'Failed to load template content');} finally {loadingStates.delete(template.id);loadingStates = new Map(loadingStates);@@ -67,31 +135,20 @@if (result) {toast.success(`Template "${template.name}" downloaded successfully!`);- if (onDownloadSuccess) {- onDownloadSuccess();- }+ onDownloadSuccess?.();} else {toast.error('Failed to download template');}} catch (error) {console.error('Error downloading template:', error);-let errorMessage = 'Failed to download template';- if (error instanceof Error) {- errorMessage = error.message;- } else if (error && typeof error === 'object' && 'message' in error) {- errorMessage = String(error.message);- }-+ if (error instanceof Error) errorMessage = error.message;toast.error(errorMessage);} finally {loadingStates.delete(`download-${templateId}`);loadingStates = new Map(loadingStates);}}-- const localTemplates = $derived(templates.filter((t) => !t.isRemote));- const remoteTemplates = $derived(templates.filter((t) => t.isRemote));</script><Dialog.Root bind:open>@@ -101,123 +158,189 @@<FileText class="size-5" />Choose a Template</Dialog.Title>- <Dialog.Description- >Select a Docker Compose template to get started quickly, or download remote templates for- local use.</Dialog.Description- >+ <Dialog.Description>+ Browse templates from your registries or local downloads. Scroll to see more, select to use immediately, or download for+ offline use.+ </Dialog.Description></Dialog.Header>- <div class="space-y-6 py-4">- {#if templates.length === 0}- <div class="text-muted-foreground py-8 text-center">- <FileText class="mx-auto mb-4 size-12 opacity-50" />- <p class="mb-2">No templates available</p>- <p class="text-sm">- Configure remote registries in <a- href="/settings/templates"- class="text-primary hover:underline">Template Settings</a- > to access community templates- </p>- </div>- {:else}- <!-- Local Templates -->- {#if localTemplates.length > 0}- <div>- <h3 class="mb-3 flex items-center gap-2 text-lg font-semibold">- <FolderOpen class="size-5 text-blue-500" />- Local Templates ({localTemplates.length})- </h3>- <div class="grid grid-cols-1 gap-4 md:grid-cols-2">- {#each localTemplates as template}- <Card- class="hover:bg-muted/50 hover:border-primary/20 cursor-pointer border-2 transition-colors"- >- <div class="p-4">- <div class="mb-2 flex items-start justify-between">- <h4 class="truncate pr-2 font-semibold">{template.name}</h4>- <div class="ml-2 flex flex-shrink-0 gap-1">- <Badge variant="outline" class="text-xs">- <FolderOpen class="mr-1 size-3" />- Local- </Badge>- {#if template.envContent}- <Badge variant="secondary" class="text-xs">- <Settings class="mr-1 size-3" />- ENV- </Badge>- {/if}- </div>+ <div class="mb-3 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ <div class="flex items-center gap-3">+ <SwitchWithLabel+ id="groupByRegistrySwitch"+ label="Group by registry"+ description="Enable Collapsible Sections for each registry"+ bind:checked={groupByRegistry}+ />+ </div>+ <div class="flex items-center gap-3">+ <Label for="sortBy" class="whitespace-nowrap text-sm font-medium">Sort by</Label>+ <Select.Root bind:value={sortBy} type="single">+ <Select.Trigger id="sortBy" class="bg-background h-9 rounded-md border px-2 text-sm">+ {filters[sortBy]}+ </Select.Trigger>+ <Select.Content>+ {#each Object.entries(filters) as [value, label]}+ <Select.Item {value}>{label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ </div>++ <div class="py-2">+ <ScrollArea class="max-h-[65vh]">+ {#if (allTemplates?.length ?? 0) === 0}+ <div class="text-muted-foreground py-10 text-center">+ <FileText class="mx-auto mb-4 size-12 opacity-50" />+ <p class="mb-2">No templates available</p>+ <p class="text-sm">+ Add a template registry in+ <a href="/settings/templates" class="text-primary hover:underline">Template Settings</a>+ to access community templates.+ </p>+ </div>+ {:else if groupByRegistry && grouped.length}+ <div class="space-y-3">+ {#each grouped as group}+ <Collapsible.Root class="w-full">+ <Card class="border-2">+ <Collapsible.Trigger class="flex w-full items-center justify-between px-4 py-3 text-left">+ <div class="flex items-center gap-2">+ <ChevronDown class="hidden size-4 data-[state=open]:block" />+ <ChevronRight class="block size-4 data-[state=open]:hidden" />+ <span class="font-semibold">{group.name}</span>+ <Badge variant="secondary" class="ml-2">{group.items.length}</Badge></div>- <p class="text-muted-foreground mb-3 line-clamp-2 text-sm">- {template.description}- </p>- <div class="flex items-center justify-between">- <div class="text-muted-foreground text-xs">- {template.envContent ? 'Includes environment variables' : 'Ready to use'}+ </Collapsible.Trigger>+ <Collapsible.Content>+ <div class="px-6 pb-6">+ <div class="grid grid-cols-1 gap-4 md:grid-cols-2">+ {#each group.items as template}+ <Card class="hover:bg-muted/50 hover:border-primary/20 border transition-colors">+ <div class="p-4">+ <div class="mb-2 flex items-start justify-between gap-2">+ <h4 class="truncate pr-2 font-semibold">{template.name}</h4>+ <div class="ml-2 flex flex-shrink-0 flex-wrap items-center gap-1">+ {#if template.metadata?.version}+ <Badge variant="outline" class="text-xs">v{template.metadata.version}</Badge>+ {/if}+ {#if template.metadata?.envUrl || template.envContent}+ <Badge variant="secondary" class="text-xs">+ <Settings class="mr-1 size-3" />+ ENV+ </Badge>+ {/if}+ </div>+ </div>++ <p class="text-muted-foreground mb-3 line-clamp-2 text-sm">+ {template.description}+ </p>++ {#if normalizeTags(template).length > 0}+ <div class="mb-3 flex flex-wrap gap-1">+ {#each normalizeTags(template) as tag}+ <Badge variant="outline" class="text-[10px]">{tag}</Badge>+ {/each}+ </div>+ {/if}++ <div class="flex items-center justify-between gap-2">+ <div class="text-muted-foreground text-xs">+ {template.isRemote ? 'Remote template' : 'Local template'}+ </div>+ <div class="flex gap-2">+ {#if template.isRemote}+ <Button+ variant="outline"+ size="sm"+ onclick={() => handleDownload(template)}+ disabled={loadingStates.get(`download-${template.id}`)}+ >+ {#if loadingStates.get(`download-${template.id}`)}+ <Loader2 class="mr-1 size-3 animate-spin" />+ Downloading...+ {:else}+ <Download class="mr-1 size-3" />+ Download+ {/if}+ </Button>+ {/if}+ <Button+ size="sm"+ onclick={() => handleSelect(template)}+ disabled={loadingStates.get(template.id)}+ >+ {#if loadingStates.get(template.id)}+ <Loader2 class="mr-1 size-3 animate-spin" />+ Loading...+ {:else}+ Use Now+ {/if}+ </Button>+ </div>+ </div>+ </div>+ </Card>+ {/each}</div>- <Button- size="sm"- onclick={() => handleSelect(template)}- disabled={loadingStates.get(template.id)}- >- {#if loadingStates.get(template.id)}- <Loader2 class="mr-1 size-3 animate-spin" />- Loading...- {:else}- Use Template- {/if}- </Button></div>- </div>+ </Collapsible.Content></Card>- {/each}- </div>+ </Collapsible.Root>+ {/each}</div>- {/if}-- <!-- Remote Templates -->- {#if remoteTemplates.length > 0}- <div>- <h3 class="mb-3 flex items-center gap-2 text-lg font-semibold">- <Globe class="size-5 text-green-500" />- Remote Templates ({remoteTemplates.length})- </h3>- <div class="grid grid-cols-1 gap-4 md:grid-cols-2">- {#each remoteTemplates as template}- <Card class="hover:bg-muted/50 hover:border-primary/20 border-2 transition-colors">- <div class="p-4">- <div class="mb-2 flex items-start justify-between">- <h4 class="truncate pr-2 font-semibold">{template.name}</h4>- <div class="ml-2 flex flex-shrink-0 gap-1">+ {:else}+ <!-- Flat grid (no grouping) -->+ <div class="grid grid-cols-1 gap-4 md:grid-cols-2">+ {#each sortTemplates(allTemplates) as template}+ <Card class="hover:bg-muted/50 hover:border-primary/20 border-2 transition-colors">+ <div class="p-4">+ <div class="mb-2 flex items-start justify-between gap-2">+ <h4 class="truncate pr-2 font-semibold">{template.name}</h4>+ <div class="ml-2 flex flex-shrink-0 flex-wrap items-center gap-1">+ {#if template.metadata?.version}+ <Badge variant="outline" class="text-xs">v{template.metadata.version}</Badge>+ {/if}+ {#if template.metadata?.envUrl || template.envContent}<Badge variant="secondary" class="text-xs">- <Globe class="mr-1 size-3" />- {template.metadata?.author || 'Remote'}+ <Settings class="mr-1 size-3" />+ ENV</Badge>- {#if template.metadata?.envUrl}- <Badge variant="secondary" class="text-xs">- <Settings class="mr-1 size-3" />- ENV- </Badge>- {/if}- </div>+ {/if}</div>- <p class="text-muted-foreground mb-2 line-clamp-2 text-sm">- {template.description}- </p>- {#if template.metadata?.author}- <p class="text-muted-foreground mb-3 text-xs">- by {template.metadata.author}- </p>- {/if}- <div class="flex items-center justify-between gap-2">- <div class="flex-1 text-xs">- {#if template.metadata?.version}- <Badge variant="outline" class="text-xs">- v{template.metadata.version}- </Badge>- {/if}- </div>- <div class="flex gap-2">+ </div>++ <div class="mb-2">+ <Badge variant="secondary" class="text-xs">+ {#if template.isRemote}+ <Globe class="mr-1 size-3" />+ {:else}+ <FolderOpen class="mr-1 size-3" />+ {/if}+ {getRegistryName(template)}+ </Badge>+ </div>++ <p class="text-muted-foreground mb-3 line-clamp-2 text-sm">+ {template.description}+ </p>++ {#if normalizeTags(template).length > 0}+ <div class="mb-3 flex flex-wrap gap-1">+ {#each normalizeTags(template) as tag}+ <Badge variant="outline" class="text-[10px]">{tag}</Badge>+ {/each}+ </div>+ {/if}++ <div class="flex items-center justify-between gap-2">+ <div class="text-muted-foreground text-xs">+ {template.isRemote ? 'Remote template' : 'Local template'}+ </div>+ <div class="flex gap-2">+ {#if template.isRemote}<Buttonvariant="outline"size="sm"@@ -232,27 +355,23 @@Download{/if}</Button>- <Button- size="sm"- onclick={() => handleSelect(template)}- disabled={loadingStates.get(template.id)}- >- {#if loadingStates.get(template.id)}- <Loader2 class="mr-1 size-3 animate-spin" />- Loading...- {:else}- Use Now- {/if}- </Button>- </div>+ {/if}+ <Button size="sm" onclick={() => handleSelect(template)} disabled={loadingStates.get(template.id)}>+ {#if loadingStates.get(template.id)}+ <Loader2 class="mr-1 size-3 animate-spin" />+ Loading...+ {:else}+ Use Now+ {/if}+ </Button></div></div>- </Card>- {/each}- </div>+ </div>+ </Card>+ {/each}</div>{/if}- {/if}+ </ScrollArea></div><Dialog.Footer>diff --git a/frontend/src/lib/components/sheets/add-template-registry-sheet.svelte b/frontend/src/lib/components/sheets/add-template-registry-sheet.svelteindex 8148cdd29..6afee2a70 100644--- a/frontend/src/lib/components/sheets/add-template-registry-sheet.svelte+++ b/frontend/src/lib/components/sheets/add-template-registry-sheet.svelte@@ -3,7 +3,7 @@import { Button } from '$lib/components/ui/button/index.js';import FormInput from '$lib/components/form/form-input.svelte';import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';- import { Loader2, Globe, RefreshCw, CheckCircle, AlertCircle } from '@lucide/svelte';+ import { Loader2, Globe, AlertCircle } from '@lucide/svelte';import { z } from 'zod/v4';import { createForm, preventDefault } from '$lib/utils/form.utils';import { templateAPI } from '$lib/services/api';@@ -11,12 +11,7 @@type TemplateRegistryFormProps = {open: boolean;- onSubmit: (registry: {- name: string;- url: string;- description?: string;- enabled: boolean;- }) => void;+ onSubmit: (registry: { name: string; url: string; description?: string; enabled: boolean }) => void;isLoading: boolean;};@@ -24,41 +19,34 @@const formSchema = z.object({url: z.url().min(1, 'Registry URL is required'),- description: z.string().default(''),enabled: z.boolean().default(true)});let formData = $derived({url: '',- description: '',enabled: true});let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));- // Submission error statelet submitError = $state<string | null>(null);async function handleSubmit() {- // Clear previous errorssubmitError = null;const data = form.validate();if (!data) return;try {- // Validate the registry URL by fetching itconst registryData = await templateAPI.fetchRegistry(data.url);if (!registryData.name || !registryData.templates || !Array.isArray(registryData.templates)) {throw new Error('Invalid registry format: missing required fields (name, templates)');}- // Submit with the name from the registryconst registryPayload = {name: registryData.name,url: data.url,- description: data.description || undefined,enabled: data.enabled};@@ -70,7 +58,6 @@function handleOpenChange(newOpenState: boolean) {open = newOpenState;- // Clear errors when closingif (!newOpenState) {submitError = null;}@@ -79,14 +66,14 @@<Sheet.Root bind:open onOpenChange={handleOpenChange}><Sheet.Content class="p-6">- <Sheet.Header class="space-y-3 pb-6 border-b">+ <Sheet.Header class="space-y-3 border-b pb-6"><div class="flex items-center gap-3">- <div class="flex size-10 items-center justify-center rounded-lg bg-primary/10 shrink-0">- <Globe class="size-5 text-primary" />+ <div class="bg-primary/10 flex size-10 shrink-0 items-center justify-center rounded-lg">+ <Globe class="text-primary size-5" /></div><div><Sheet.Title class="text-xl font-semibold">Add Template Registry</Sheet.Title>- <Sheet.Description class="text-sm text-muted-foreground mt-1"+ <Sheet.Description class="text-muted-foreground mt-1 text-sm">Add a remote template registry to access community templates.</Sheet.Description></div>@@ -101,14 +88,6 @@bind:input={$inputs.url}/>- <FormInput- label="Description"- type="text"- placeholder="A collection of useful Docker Compose templates"- description="Optional description for this registry"- bind:input={$inputs.description}- />-<SwitchWithLabelid="enabledSwitch"label="Enable Registry"diff --git a/frontend/src/lib/components/ui/collapsible/collapsible-trigger.svelte b/frontend/src/lib/components/ui/collapsible/collapsible-trigger.svelteindex c88cebaff..ece7ad68e 100644--- a/frontend/src/lib/components/ui/collapsible/collapsible-trigger.svelte+++ b/frontend/src/lib/components/ui/collapsible/collapsible-trigger.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { Collapsible as CollapsiblePrimitive } from 'bits-ui';+ import { Collapsible as CollapsiblePrimitive } from "bits-ui";let { ref = $bindable(null), ...restProps }: CollapsiblePrimitive.TriggerProps = $props();</script>diff --git a/frontend/src/lib/components/ui/collapsible/collapsible.svelte b/frontend/src/lib/components/ui/collapsible/collapsible.svelteindex a3aafeb8a..39cdd4e4e 100644--- a/frontend/src/lib/components/ui/collapsible/collapsible.svelte+++ b/frontend/src/lib/components/ui/collapsible/collapsible.svelte@@ -1,7 +1,11 @@<script lang="ts">- import { Collapsible as CollapsiblePrimitive } from 'bits-ui';+ import { Collapsible as CollapsiblePrimitive } from "bits-ui";- let { ref = $bindable(null), open = $bindable(false), ...restProps }: CollapsiblePrimitive.RootProps = $props();+ let {+ ref = $bindable(null),+ open = $bindable(false),+ ...restProps+ }: CollapsiblePrimitive.RootProps = $props();</script>-<CollapsiblePrimitive.Root bind:ref data-slot="collapsible" {...restProps} />+<CollapsiblePrimitive.Root bind:ref bind:open data-slot="collapsible" {...restProps} />diff --git a/frontend/src/lib/components/ui/collapsible/index.ts b/frontend/src/lib/components/ui/collapsible/index.tsindex 7455459b0..169b4791d 100644--- a/frontend/src/lib/components/ui/collapsible/index.ts+++ b/frontend/src/lib/components/ui/collapsible/index.ts@@ -1,8 +1,6 @@-import { Collapsible as CollapsiblePrimitive } from 'bits-ui';--const Root = CollapsiblePrimitive.Root;-const Trigger = CollapsiblePrimitive.Trigger;-const Content = CollapsiblePrimitive.Content;+import Root from "./collapsible.svelte";+import Trigger from "./collapsible-trigger.svelte";+import Content from "./collapsible-content.svelte";export {Root,@@ -11,5 +9,5 @@ export {//Root as Collapsible,Content as CollapsibleContent,- Trigger as CollapsibleTrigger+ Trigger as CollapsibleTrigger,};diff --git a/frontend/src/lib/components/ui/scroll-area/index.ts b/frontend/src/lib/components/ui/scroll-area/index.tsnew file mode 100644index 000000000..e86a25b21--- /dev/null+++ b/frontend/src/lib/components/ui/scroll-area/index.ts@@ -0,0 +1,10 @@+import Scrollbar from "./scroll-area-scrollbar.svelte";+import Root from "./scroll-area.svelte";++export {+ Root,+ Scrollbar,+ //,+ Root as ScrollArea,+ Scrollbar as ScrollAreaScrollbar,+};diff --git a/frontend/src/lib/components/ui/scroll-area/scroll-area-scrollbar.svelte b/frontend/src/lib/components/ui/scroll-area/scroll-area-scrollbar.sveltenew file mode 100644index 000000000..412744467--- /dev/null+++ b/frontend/src/lib/components/ui/scroll-area/scroll-area-scrollbar.svelte@@ -0,0 +1,31 @@+<script lang="ts">+ import { ScrollArea as ScrollAreaPrimitive } from "bits-ui";+ import { cn, type WithoutChild } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ orientation = "vertical",+ children,+ ...restProps+ }: WithoutChild<ScrollAreaPrimitive.ScrollbarProps> = $props();+</script>++<ScrollAreaPrimitive.Scrollbar+ bind:ref+ data-slot="scroll-area-scrollbar"+ {orientation}+ class={cn(+ "flex touch-none select-none p-px transition-colors",+ orientation === "vertical" && "h-full w-2.5 border-l border-l-transparent",+ orientation === "horizontal" && "h-2.5 flex-col border-t border-t-transparent",+ className+ )}+ {...restProps}+>+ {@render children?.()}+ <ScrollAreaPrimitive.Thumb+ data-slot="scroll-area-thumb"+ class="bg-border relative flex-1 rounded-full"+ />+</ScrollAreaPrimitive.Scrollbar>diff --git a/frontend/src/lib/components/ui/scroll-area/scroll-area.svelte b/frontend/src/lib/components/ui/scroll-area/scroll-area.sveltenew file mode 100644index 000000000..38a1847f5--- /dev/null+++ b/frontend/src/lib/components/ui/scroll-area/scroll-area.svelte@@ -0,0 +1,40 @@+<script lang="ts">+ import { ScrollArea as ScrollAreaPrimitive } from "bits-ui";+ import { Scrollbar } from "./index.js";+ import { cn, type WithoutChild } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ orientation = "vertical",+ scrollbarXClasses = "",+ scrollbarYClasses = "",+ children,+ ...restProps+ }: WithoutChild<ScrollAreaPrimitive.RootProps> & {+ orientation?: "vertical" | "horizontal" | "both" | undefined;+ scrollbarXClasses?: string | undefined;+ scrollbarYClasses?: string | undefined;+ } = $props();+</script>++<ScrollAreaPrimitive.Root+ bind:ref+ data-slot="scroll-area"+ class={cn("relative", className)}+ {...restProps}+>+ <ScrollAreaPrimitive.Viewport+ data-slot="scroll-area-viewport"+ class="ring-ring/10 dark:ring-ring/20 dark:outline-ring/40 outline-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] focus-visible:outline-1 focus-visible:ring-4"+ >+ {@render children?.()}+ </ScrollAreaPrimitive.Viewport>+ {#if orientation === "vertical" || orientation === "both"}+ <Scrollbar orientation="vertical" class={scrollbarYClasses} />+ {/if}+ {#if orientation === "horizontal" || orientation === "both"}+ <Scrollbar orientation="horizontal" class={scrollbarXClasses} />+ {/if}+ <ScrollAreaPrimitive.Corner />+</ScrollAreaPrimitive.Root>diff --git a/frontend/src/lib/components/ui/table/table-cell.svelte b/frontend/src/lib/components/ui/table/table-cell.svelteindex 599204845..1a2f033fb 100644--- a/frontend/src/lib/components/ui/table/table-cell.svelte+++ b/frontend/src/lib/components/ui/table/table-cell.svelte@@ -13,7 +13,10 @@<tdbind:this={ref}data-slot="table-cell"- class={cn("whitespace-nowrap p-2 align-middle [&:has([role=checkbox])]:pr-0", className)}+ class={cn(+ "whitespace-nowrap bg-clip-padding p-2 align-middle [&:has([role=checkbox])]:pr-0",+ className+ )}{...restProps}>{@render children?.()}diff --git a/frontend/src/lib/components/ui/table/table-head.svelte b/frontend/src/lib/components/ui/table/table-head.svelteindex 2742939af..e9dd2378d 100644--- a/frontend/src/lib/components/ui/table/table-head.svelte+++ b/frontend/src/lib/components/ui/table/table-head.svelte@@ -14,7 +14,7 @@bind:this={ref}data-slot="table-head"class={cn(- "text-foreground h-10 whitespace-nowrap px-2 text-left align-middle font-medium [&:has([role=checkbox])]:pr-0",+ "text-foreground h-10 whitespace-nowrap bg-clip-padding px-2 text-left align-middle font-medium [&:has([role=checkbox])]:pr-0",className)}{...restProps}diff --git a/frontend/src/lib/components/ui/table/table-row.svelte b/frontend/src/lib/components/ui/table/table-row.svelteindex 8829581c9..0df769e0a 100644--- a/frontend/src/lib/components/ui/table/table-row.svelte+++ b/frontend/src/lib/components/ui/table/table-row.svelte@@ -14,7 +14,7 @@bind:this={ref}data-slot="table-row"class={cn(- "hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",+ "hover:[&,&>svelte-css-wrapper]:[&>th,td]:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",className)}{...restProps}diff --git a/frontend/src/lib/services/api/template-api-service.ts b/frontend/src/lib/services/api/template-api-service.tsindex fba2647c9..f4a82f7e6 100644--- a/frontend/src/lib/services/api/template-api-service.ts+++ b/frontend/src/lib/services/api/template-api-service.ts@@ -1,15 +1,15 @@import BaseAPIService from './api-service';-import type { TemplateRegistry, Template } from '$lib/types/template.type';+import type { TemplateRegistry, Template, RemoteRegistry } from '$lib/types/template.type';export default class TemplateAPIService extends BaseAPIService {async loadAll(): Promise<Template[]> {const response = await this.api.get('/templates');- return response.data.templates;+ return response.data?.data ?? [];}async getById(id: string): Promise<Template> {- const response = await this.api.get(`/templates/${id}`);- return response.data.template;+ const response = await this.api.get(`/templates/${encodeURIComponent(id)}`);+ return response.data?.data;}async getTemplateContent(id: string): Promise<{@@ -19,21 +19,17 @@ export default class TemplateAPIService extends BaseAPIService {}> {const encodedId = encodeURIComponent(id);const response = await this.api.get(`/templates/${encodedId}/content`);+ const data = response.data?.data ?? {};return {- content: response.data.content,- envContent: response.data.envContent,- template: response.data.template+ content: data.content,+ envContent: data.envContent,+ template: data.template};}- async create(template: {- name: string;- description: string;- content: string;- envContent?: string;- }): Promise<Template> {+ async create(template: { name: string; description: string; content: string; envContent?: string }): Promise<Template> {const response = await this.api.post('/templates', template);- return response.data.template;+ return response.data?.data;}async update(@@ -53,13 +49,13 @@ export default class TemplateAPIService extends BaseAPIService {}async download(id: string): Promise<Template> {- const response = await this.api.post(`/templates/${id}/download`);- return response.data.template;+ const response = await this.api.post(`/templates/${encodeURIComponent(id)}/download`);+ return response.data?.data;}async getEnvTemplate(): Promise<string> {const response = await this.api.get('/templates/env/default');- return response.data.content;+ return response.data?.data?.content ?? response.data?.content;}async saveEnvTemplate(content: string): Promise<void> {@@ -68,21 +64,17 @@ export default class TemplateAPIService extends BaseAPIService {async getRegistries(): Promise<TemplateRegistry[]> {const response = await this.api.get('/templates/registries');- return response.data.registries;+ const out = response.data?.data ?? response.data?.registries ?? response.data;+ return Array.isArray(out) ? out : [];}- async addRegistry(registry: {- name: string;- url: string;- description?: string;- enabled: boolean;- }): Promise<TemplateRegistry> {+ async addRegistry(registry: { name: string; url: string; description?: string; enabled: boolean }): Promise<TemplateRegistry> {const response = await this.api.post('/templates/registries', registry);- return response.data.registry;+ return response.data?.data ?? response.data;}async updateRegistry(- id: number,+ id: string,registry: {name: string;url: string;@@ -93,12 +85,16 @@ export default class TemplateAPIService extends BaseAPIService {await this.api.put(`/templates/registries/${id}`, registry);}- async fetchRegistry(url: string): Promise<any> {+ async fetchRegistry(url: string): Promise<RemoteRegistry> {const response = await this.api.get(`/templates/fetch?url=${encodeURIComponent(url)}`);- return response.data;+ const manifest = response.data?.data ?? response.data;+ if (!manifest || typeof manifest !== 'object' || !manifest.name || !Array.isArray(manifest.templates)) {+ throw new Error('Invalid registry format: missing required fields (name, templates)');+ }+ return manifest;}- async deleteRegistry(id: number): Promise<void> {+ async deleteRegistry(id: string): Promise<void> {await this.api.delete(`/templates/registries/${id}`);}@@ -125,9 +121,7 @@ export default class TemplateAPIService extends BaseAPIService {const categories = new Set<string>();templates.forEach((template) => {if (template.metadata?.tags) {- const tags = Array.isArray(template.metadata.tags)- ? template.metadata.tags- : JSON.parse(template.metadata.tags || '[]');+ const tags = Array.isArray(template.metadata.tags) ? template.metadata.tags : JSON.parse(template.metadata.tags || '[]');tags.forEach((tag: string) => categories.add(tag));}});@@ -159,7 +153,7 @@ export default class TemplateAPIService extends BaseAPIService {async getTemplateByRegistry(registryId: string): Promise<Template[]> {const templates = await this.loadAll();- return templates.filter((template) => template.registryId?.toString() === registryId);+ return templates.filter((template) => template.registryId === registryId);}async importFromUrl(url: string): Promise<Template> {diff --git a/frontend/src/lib/services/api/template-registry-api-service.ts b/frontend/src/lib/services/api/template-registry-api-service.tsindex 74fb0e514..e4fa8633e 100644--- a/frontend/src/lib/services/api/template-registry-api-service.ts+++ b/frontend/src/lib/services/api/template-registry-api-service.ts@@ -1,17 +1,5 @@import BaseAPIService from './api-service';--export interface TemplateRegistry {- id: string;- name: string;- url: string;- enabled: boolean;- username?: string;- password?: string;- token?: string;- description?: string;- createdAt?: string;- updatedAt?: string;-}+import type { TemplateRegistry } from '$lib/types/template.type';export default class TemplateRegistryAPIService extends BaseAPIService {async list(): Promise<TemplateRegistry[]> {diff --git a/frontend/src/lib/types/template.type.ts b/frontend/src/lib/types/template.type.tsindex 6dc7dbb94..4948d18bc 100644--- a/frontend/src/lib/types/template.type.ts+++ b/frontend/src/lib/types/template.type.ts@@ -1,11 +1,11 @@export interface TemplateRegistry {- id: number;+ id: string;name: string;url: string;enabled: boolean;description: string;- createdAt: string;- updatedAt: string;+ createdAt?: string;+ updatedAt?: string;}export interface Template {@@ -16,7 +16,7 @@ export interface Template {envContent?: string;isCustom: boolean;isRemote: boolean;- registryId?: number;+ registryId?: string;registry?: TemplateRegistry;metadata?: {version?: string;@@ -37,13 +37,21 @@ export interface RemoteTemplate {name: string;description: string;version: string;- author?: string;- tags?: string[];+ author: string;+ tags: string[];compose_url: string;env_url?: string;documentation_url?: string;- icon_url?: string;- updated_at: string;+}++export interface RemoteRegistry {+ $schema?: string;+ name: string;+ description: string;+ version: string;+ author: string;+ url: string;+ templates: RemoteTemplate[];}export interface TemplateRegistryConfig {diff --git a/frontend/src/routes/customize/templates/+page.svelte b/frontend/src/routes/customize/templates/+page.svelteindex d2e64c5c7..4ebd900a3 100644--- a/frontend/src/routes/customize/templates/+page.svelte+++ b/frontend/src/routes/customize/templates/+page.svelte@@ -6,32 +6,21 @@import { Separator } from '$lib/components/ui/separator/index.js';import { Switch } from '$lib/components/ui/switch/index.js';import { Snippet } from '$lib/components/ui/snippet';- import {- Trash2,- Plus,- ExternalLink,- RefreshCw,- FileText,- Globe,- FolderOpen,- Users- } from '@lucide/svelte';- import type { PageData } from './$types';+ import { Trash2, Plus, ExternalLink, RefreshCw, FileText, Globe, FolderOpen, Users } from '@lucide/svelte';import { templateAPI } from '$lib/services/api';import { toast } from 'svelte-sonner';- import { invalidateAll } from '$app/navigation';import AddTemplateRegistrySheet from '$lib/components/sheets/add-template-registry-sheet.svelte';import StatCard from '$lib/components/stat-card.svelte';- let { data }: { data: PageData } = $props();+ let { data } = $props();- let templates = $state(data.templates || []);- let registries = $state(data.registries || []);+ let templates = $state(data.templates);+ let registries = $state(data.registries);let isLoading = $state({addingRegistry: false,- removing: new Set<number>(),- updating: new Set<number>()+ removing: new Set<string>(),+ updating: new Set<string>()});let showAddRegistrySheet = $state(false);@@ -39,7 +28,7 @@const localTemplateCount = $derived(templates.filter((t) => !t.isRemote).length);const remoteTemplateCount = $derived(templates.filter((t) => t.isRemote).length);- async function updateRegistry(id: number, updates: { enabled?: boolean }) {+ async function updateRegistry(id: string, updates: { enabled?: boolean }) {if (isLoading.updating.has(id)) return;isLoading.updating.add(id);@@ -57,11 +46,8 @@enabled: updates.enabled ?? registry.enabled});- // Update local state- registries = registries.map((r) => (r.id === id ? { ...r, ...updates } : r));-+ registries = await templateAPI.getRegistries();toast.success('Registry updated successfully');- await invalidateAll();} catch (error) {console.error('Error updating registry:', error);toast.error(error instanceof Error ? error.message : 'Failed to update registry');@@ -70,15 +56,15 @@}}- async function removeRegistry(id: number) {+ async function removeRegistry(id: string) {if (isLoading.removing.has(id)) return;isLoading.removing.add(id);try {await templateAPI.deleteRegistry(id);registries = registries.filter((r) => r.id !== id);+ registries = await templateAPI.getRegistries();toast.success('Registry removed successfully');- await invalidateAll();} catch (error) {console.error('Error removing registry:', error);toast.error(error instanceof Error ? error.message : 'Failed to remove registry');@@ -89,7 +75,7 @@async function refreshTemplates() {try {- await invalidateAll();+ templates = await templateAPI.loadAll();toast.success('Templates refreshed successfully');} catch (error) {console.error('Error refreshing templates:', error);@@ -97,24 +83,7 @@}}- function copyToClipboard(text: string) {- navigator.clipboard- .writeText(text)- .then(() => {- toast.success('Copied to clipboard');- })- .catch(() => {- toast.error('Failed to copy');- });- }-- // Handle registry form submission- async function handleRegistrySubmit(registry: {- name: string;- url: string;- description?: string;- enabled: boolean;- }) {+ async function handleRegistrySubmit(registry: { name: string; url: string; description?: string; enabled: boolean }) {isLoading.addingRegistry = true;try {@@ -125,11 +94,10 @@enabled: registry.enabled});- registries = [...registries, created];+ registries = await templateAPI.getRegistries();showAddRegistrySheet = false;toast.success('Registry added successfully');- await invalidateAll();} catch (error) {console.error('Error adding registry:', error);toast.error(error instanceof Error ? error.message : 'Failed to add registry');@@ -139,18 +107,13 @@}</script>-<svelte:head><title>Arcane</title></svelte:head>-<div class="space-y-6"><div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center"><div><h1 class="text-3xl font-bold tracking-tight">Template Settings</h1><p class="text-muted-foreground mt-1 text-sm">Manage Docker Compose template sources and registries- <a- href="https://arcane.ofkm.dev/docs/templates/use-templates"- class="text-primary ml-1 hover:underline">→ Learn more</a- >+ <a href="https://arcane.ofkm.dev/docs/templates/use-templates" class="text-primary ml-1 hover:underline">→ Learn more</a></p></div>@@ -160,7 +123,6 @@</Button></div>- <!-- Template Statistics --><div class="grid grid-cols-1 gap-4 md:grid-cols-3"><StatCardtitle="Local Templates"@@ -187,7 +149,6 @@<Separator />- <!-- Remote Template Registries --><div class="space-y-4"><div class="flex items-center justify-between"><h2 class="text-xl font-semibold">Template Registries</h2>@@ -201,8 +162,8 @@<Globe class="size-4" /><Alert.Title>Remote Registries</Alert.Title><Alert.Description- >Add remote template registries to access community templates. Registries should provide a- JSON manifest with template definitions and download URLs.</Alert.Description+ >Add remote template registries to access community templates. Registries should provide a JSON manifest with template+ definitions and download URLs.</Alert.Description></Alert.Root>@@ -217,7 +178,6 @@</Alert.Description></Alert.Root>{/if}- <!-- Registry List -->{#if registries.length > 0}<div class="space-y-3">{#each registries as registry}@@ -230,32 +190,22 @@{registry.enabled ? 'Enabled' : 'Disabled'}</Badge></div>- <p class="text-muted-foreground text-sm break-all">{registry.url}</p>+ <p class="text-muted-foreground break-all text-sm">{registry.url}</p>{#if registry.description}<p class="text-muted-foreground mt-1 text-sm">{registry.description}</p>{/if}- <p class="text-muted-foreground mt-1 text-xs">- Updated: {new Date(registry.updatedAt).toLocaleString()}- </p></div><div class="flex items-center gap-2">- <!-- Toggle enabled/disabled --><Switchchecked={registry.enabled}onCheckedChange={(checked) => updateRegistry(registry.id, { enabled: checked })}disabled={isLoading.updating.has(registry.id)}/>- <!-- Open registry URL -->- <Button- variant="outline"- size="sm"- onclick={() => window.open(registry.url, '_blank')}- >+ <Button variant="outline" size="sm" onclick={() => window.open(registry.url, '_blank')}><ExternalLink class="size-4" /></Button>- <!-- Remove registry --><Buttonvariant="destructive"size="sm"@@ -282,7 +232,6 @@{/if}</div>- <!-- Add Template Registry Sheet --><AddTemplateRegistrySheetbind:open={showAddRegistrySheet}onSubmit={handleRegistrySubmit}diff --git a/frontend/src/routes/customize/templates/+page.ts b/frontend/src/routes/customize/templates/+page.tsindex eebeebe7e..2df723ba3 100644--- a/frontend/src/routes/customize/templates/+page.ts+++ b/frontend/src/routes/customize/templates/+page.ts@@ -1,25 +1,13 @@import { templateAPI } from '$lib/services/api';export const load = async () => {- try {- const [templates, registries] = await Promise.all([templateAPI.loadAll().catch(() => []), templateAPI.getRegistries().catch(() => [])]);+ const [templates, registries] = await Promise.all([+ templateAPI.loadAll().catch(() => []),+ templateAPI.getRegistries().catch(() => [])+ ]);- const localTemplateCount = templates.filter((t) => !t.isRemote).length;- const remoteTemplateCount = templates.filter((t) => t.isRemote).length;-- return {- templates,- registries,- localTemplateCount,- remoteTemplateCount- };- } catch (error) {- console.error('Error loading template settings:', error);- return {- templates: [],- registries: [],- localTemplateCount: 0,- remoteTemplateCount: 0- };- }+ return {+ templates,+ registries+ };};