Files
skillshare/internal/server/handler_skill_content_test.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

140 lines
4.1 KiB
Go

package server
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestHandlePutSkillContent_WritesFile(t *testing.T) {
s, src := newTestServer(t)
addSkill(t, src, "my-skill")
body := skillContentRequest{Content: "---\nname: my-skill\ndescription: edited\n---\n# Updated"}
raw, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPut, "/api/resources/my-skill/content", bytes.NewReader(raw))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
s.handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
}
var resp skillContentResponse
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
t.Fatalf("response decode: %v", err)
}
if resp.BytesWritten != len(body.Content) {
t.Errorf("expected %d bytes written, got %d", len(body.Content), resp.BytesWritten)
}
on := filepath.Join(src, "my-skill", "SKILL.md")
got, err := os.ReadFile(on)
if err != nil {
t.Fatalf("read saved file: %v", err)
}
if string(got) != body.Content {
t.Errorf("file content mismatch:\nwant: %q\ngot: %q", body.Content, got)
}
}
func TestHandlePutSkillContent_NotFound(t *testing.T) {
s, _ := newTestServer(t)
body := skillContentRequest{Content: "foo"}
raw, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPut, "/api/resources/nope/content", bytes.NewReader(raw))
rr := httptest.NewRecorder()
s.handler.ServeHTTP(rr, req)
if rr.Code != http.StatusNotFound {
t.Fatalf("expected 404, got %d: %s", rr.Code, rr.Body.String())
}
}
func TestHandlePutSkillContent_InvalidJSON(t *testing.T) {
s, src := newTestServer(t)
addSkill(t, src, "my-skill")
req := httptest.NewRequest(http.MethodPut, "/api/resources/my-skill/content", strings.NewReader("not-json"))
rr := httptest.NewRecorder()
s.handler.ServeHTTP(rr, req)
if rr.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d: %s", rr.Code, rr.Body.String())
}
}
func TestHandlePutSkillContent_TooLarge(t *testing.T) {
s, src := newTestServer(t)
addSkill(t, src, "my-skill")
// Assemble a 3 MiB body — exceeds the 2 MiB ceiling.
huge := make([]byte, 3*1024*1024)
for i := range huge {
huge[i] = 'x'
}
body := skillContentRequest{Content: string(huge)}
raw, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPut, "/api/resources/my-skill/content", bytes.NewReader(raw))
rr := httptest.NewRecorder()
s.handler.ServeHTTP(rr, req)
if rr.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("expected 413, got %d", rr.Code)
}
}
func TestHandlePutSkillContent_AtomicTempCleanup(t *testing.T) {
s, src := newTestServer(t)
addSkill(t, src, "my-skill")
body := skillContentRequest{Content: "new content"}
raw, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPut, "/api/resources/my-skill/content", bytes.NewReader(raw))
rr := httptest.NewRecorder()
s.handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("unexpected %d", rr.Code)
}
entries, err := os.ReadDir(filepath.Join(src, "my-skill"))
if err != nil {
t.Fatalf("readdir: %v", err)
}
for _, e := range entries {
if strings.HasPrefix(e.Name(), ".skillshare-") {
t.Errorf("temp file left behind: %s", e.Name())
}
}
}
func TestHandlePutSkillContent_RejectsTraversal(t *testing.T) {
// The route only exposes {name}; Go's mux rejects a literal "/" inside
// {name}, but we still want to confirm `..` as a name doesn't escape.
s, src := newTestServer(t)
addSkill(t, src, "victim")
body := skillContentRequest{Content: "boom"}
raw, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPut, "/api/resources/..%2Fescape/content", bytes.NewReader(raw))
rr := httptest.NewRecorder()
s.handler.ServeHTTP(rr, req)
// Any of: 400 / 404 is acceptable — what matters is that the victim's file
// is untouched.
got, err := os.ReadFile(filepath.Join(src, "victim", "SKILL.md"))
if err != nil {
t.Fatalf("read victim: %v", err)
}
if !strings.Contains(string(got), "# victim") {
t.Errorf("victim content was modified: %q", got)
}
}