Files
skillshare/internal/server/handler_skill_content.go
T
Willie 5fc5ee4fe5 feat(ui): add web-based skill editor with metadata, live preview, and diff review
Introduces a full in-browser skill editor reachable from the skill detail
page, replacing the previous read-only detail view for edits.

Editor
- Two-pane layout with Markdown textarea, live preview, and synced scroll
- Edit / Split / Preview mode toggle in the status bar (⌘P to cycle)
- Keyboard shortcuts: ⌘S save (with diff review), Esc cancel
- Outline drawer with jump-to-heading
- Token / word / line / file count in status bar, 5K budget warning

Frontmatter
- Grouped field editor (Identity / Invocation / Execution / Metadata)
  matching the 13 official SKILL.md fields
- Shared 1,536-char budget enforced across description + when_to_use
- Switch toggles for booleans, segmented control for enums, chip array
  inputs for list-valued fields
- Metadata group edits nested metadata.* keys directly, with stable row
  ids so typing key → clicking value no longer remounts the inputs
- Special handling for metadata.targets so values serialize as a YAML
  list (backend ParseFrontmatterList requires arrays)
- YAML mode for raw editing; Fields ↔ YAML round-trips cleanly
- Legacy root-level 'targets:' migrated to metadata.targets on load

Diff review
- Save triggers a side-by-side diff modal built on the shared DialogShell
  with focus trap and backdrop, using the Button component for actions
- YAML serializer emits plain scalars when safe instead of wrapping every
  value containing ':', '*', '#', or '"', eliminating spurious churn in
  the save diff

Misc
- DialogShell gains 4xl–7xl maxWidth presets
- Resource detail sidebar shows a Targets row when metadata.targets is set

Backend additions (server handlers):
- POST /api/resources/:name/content   save SKILL.md content
- POST /api/resources/:name/open      open in local editor
2026-04-19 09:29:18 +08:00

170 lines
4.7 KiB
Go

package server
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"skillshare/internal/resource"
"skillshare/internal/sync"
)
// skillContentRequest is the JSON body for PUT /api/resources/{name}/content
type skillContentRequest struct {
Content string `json:"content"`
}
// skillContentResponse is the JSON response on successful save.
type skillContentResponse struct {
BytesWritten int `json:"bytesWritten"`
Path string `json:"path"`
ContentType string `json:"contentType"`
SavedAt string `json:"savedAt"`
}
// handlePutSkillContent saves the SKILL.md (or agent markdown) content to disk.
// Request body: {"content": "..."}
// Writes atomically via <file>.tmp + rename.
func (s *Server) handlePutSkillContent(w http.ResponseWriter, r *http.Request) {
start := time.Now()
s.mu.RLock()
source := s.skillsSource()
agentsSource := s.agentsSource()
s.mu.RUnlock()
name := r.PathValue("name")
kind := r.URL.Query().Get("kind")
if kind != "" && kind != "skill" && kind != "agent" {
writeError(w, http.StatusBadRequest, "invalid kind: "+kind)
return
}
var req skillContentRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
return
}
// Reject writes above a conservative ceiling to guard against accidents.
const maxBytes = 2 * 1024 * 1024 // 2 MiB
if len(req.Content) > maxBytes {
writeError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("content exceeds %d bytes", maxBytes))
return
}
targetPath, resolvedKind, err := s.resolveEditableSkillPath(source, agentsSource, name, kind)
if err != nil {
writeError(w, http.StatusNotFound, err.Error())
return
}
if err := writeFileAtomic(targetPath, []byte(req.Content), 0o644); err != nil {
writeError(w, http.StatusInternalServerError, "failed to save: "+err.Error())
return
}
s.writeOpsLog("skill.edit", "ok", start, map[string]any{
"name": name,
"kind": resolvedKind,
"path": targetPath,
"length": len(req.Content),
}, "")
writeJSON(w, skillContentResponse{
BytesWritten: len(req.Content),
Path: targetPath,
ContentType: "text/markdown",
SavedAt: time.Now().UTC().Format(time.RFC3339),
})
}
// resolveEditableSkillPath locates the on-disk markdown file for a skill or agent.
// For skills this is <skillDir>/SKILL.md; for agents this is the agent's single .md file.
// Returns (absPath, resolvedKind, error).
func (s *Server) resolveEditableSkillPath(source, agentsSource, name, kind string) (string, string, error) {
if kind != "agent" && source != "" {
discovered, err := sync.DiscoverSourceSkillsAll(source)
if err == nil {
for _, d := range discovered {
baseName := filepath.Base(d.SourcePath)
if d.FlatName != name && baseName != name {
continue
}
skillMd := filepath.Join(d.SourcePath, "SKILL.md")
if !withinDir(skillMd, d.SourcePath) {
return "", "", fmt.Errorf("invalid skill path")
}
return skillMd, "skill", nil
}
}
}
if kind != "skill" && agentsSource != "" {
agents, _ := resource.AgentKind{}.Discover(agentsSource)
for _, d := range agents {
if !matchesAgentName(d, name) {
continue
}
if !withinDir(d.SourcePath, agentsSource) {
return "", "", fmt.Errorf("invalid agent path")
}
return d.SourcePath, "agent", nil
}
}
return "", "", fmt.Errorf("skill not found: %s", name)
}
// withinDir reports whether path is inside dir (after cleaning).
func withinDir(path, dir string) bool {
abs := filepath.Clean(path)
base := filepath.Clean(dir) + string(filepath.Separator)
// If dir is exactly the file (e.g. single-file agent), treat as within.
if abs == filepath.Clean(dir) {
return true
}
return strings.HasPrefix(abs, base)
}
// writeFileAtomic writes data to a temp file in the same directory, then renames it
// into place. This prevents partial writes if the process is killed mid-write.
func writeFileAtomic(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".skillshare-"+filepath.Base(path)+".*")
if err != nil {
return fmt.Errorf("create temp: %w", err)
}
tmpPath := tmp.Name()
cleanup := func() { _ = os.Remove(tmpPath) }
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
cleanup()
return fmt.Errorf("write temp: %w", err)
}
if err := tmp.Chmod(perm); err != nil {
_ = tmp.Close()
cleanup()
return fmt.Errorf("chmod temp: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
cleanup()
return fmt.Errorf("sync temp: %w", err)
}
if err := tmp.Close(); err != nil {
cleanup()
return fmt.Errorf("close temp: %w", err)
}
if err := os.Rename(tmpPath, path); err != nil {
cleanup()
return fmt.Errorf("rename temp: %w", err)
}
return nil
}