Files
skillshare/internal/server/handler_projects_test.go
T
Willie 52744e2f34 feat(project): register every Git checkout in a workspace with --scan (#958)
Some tools, such as Codex, look for project skills only up to the Git root
of the folder you open. When one workspace folder holds several checkouts
or worktrees, skills synced to the workspace are not seen inside them, and
registering each checkout by hand repeats the same settings many times.

`project add <root> --scan DIR` registers the root and each Git checkout
found below the scan folders as ordinary project entries with the same
settings, in one write. No scan setting is saved; rerun it after a new
clone. It only adds: a checkout already registered with the same settings
is kept, one with different settings or its own .skillshare/ is skipped
with the reason, and a name clash derives the name from the path. A scan
folder that is missing or cannot be read is skipped with a warning so one
unreadable folder does not block the rest. Rows carry a root-relative path
and a skip code so the dashboard can explain them in its own words.

Dashboard:

The dashboard should offer what `project add --scan` does, so a workspace
with many checkouts can be set up without the terminal.

The Add project dialog gains "Also add each checkout inside this folder"
with the folders to look in. Review runs the scan as a dry run through the
new POST /api/projects/scan and lists each folder as Added, Kept or Skipped
with a translated reason and a link to a project whose settings differ;
nothing is written until it is confirmed. The write scans again and counts
what it actually added, so a checkout registered in the meantime is not
reported as new. MCP and Hooks, when picked, are set up for each added
project. Without an explicit storage choice the default follows
projects_storage, as the CLI does without a flag.

Closes #953

Release-As: 0.30.12
2026-11-19 01:35:56 +08:00

461 lines
17 KiB
Go

package server
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"skillshare/internal/config"
"skillshare/internal/projects"
ssync "skillshare/internal/sync"
)
func projectRequest(t *testing.T, s *Server, method, url, body string) *httptest.ResponseRecorder {
t.Helper()
rr := httptest.NewRecorder()
s.handler.ServeHTTP(rr, httptest.NewRequest(method, url, strings.NewReader(body)))
return rr
}
func addProject(t *testing.T, s *Server, root string) {
t.Helper()
addProjectIn(t, s, root, "")
}
func addProjectIn(t *testing.T, s *Server, root, storage string) {
t.Helper()
if err := os.MkdirAll(root, 0755); err != nil {
t.Fatal(err)
}
body := `{"create":true,"storage":"` + storage + `","root":"` + root + `","targets":["claude","codex"],"skills":{"mode":"copy","include":["team-*"],"exclude":[]}}`
if rr := projectRequest(t, s, http.MethodPut, "/api/projects", body); rr.Code != http.StatusOK {
t.Fatalf("add project: %d %s", rr.Code, rr.Body)
}
}
func TestListProjects_DetectsVisibleProjectConfig(t *testing.T) {
s, src := newTestServer(t)
root := filepath.Join(filepath.Dir(src), "app")
addProject(t, s, root)
if err := os.MkdirAll(filepath.Join(root, "skillshare"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "skillshare", "config.yaml"), []byte("targets:\n - claude\n"), 0644); err != nil {
t.Fatal(err)
}
var listed struct {
Projects []projectItem `json:"projects"`
}
json.Unmarshal(projectRequest(t, s, http.MethodGet, "/api/projects", "").Body.Bytes(), &listed)
if len(listed.Projects) != 1 || !listed.Projects[0].HasOwnConfig {
t.Fatalf("projects %+v, want hasOwnConfig for the visible project dir", listed.Projects)
}
}
func TestSaveProject_AddsTargetsThatOnlyTheProjectScopeLists(t *testing.T) {
s, src := newTestServer(t)
root := filepath.Join(filepath.Dir(src), "app")
addProject(t, s, root)
var listed struct {
Targets []targetItem `json:"targets"`
}
json.Unmarshal(projectRequest(t, s, http.MethodGet, "/api/targets?scope=projects", "").Body.Bytes(), &listed)
if len(listed.Targets) != 2 || listed.Targets[0].Project != root {
t.Fatalf("project targets %+v", listed.Targets)
}
json.Unmarshal(projectRequest(t, s, http.MethodGet, "/api/targets", "").Body.Bytes(), &listed)
if len(listed.Targets) != 0 {
t.Fatalf("own targets %+v", listed.Targets)
}
}
func TestSaveProject_Rejected(t *testing.T) {
s, src := newTestServer(t)
root := filepath.Join(filepath.Dir(src), "app")
addProject(t, s, root)
for name, body := range map[string]string{
"already declared": `{"create":true,"root":"` + root + `","targets":["claude"]}`,
"folder not found": `{"create":true,"root":"` + root + `-gone","targets":["claude"]}`,
"unknown target": `{"root":"` + root + `","targets":["nope"]}`,
"invalid mode": `{"root":"` + root + `","targets":["claude"],"skills":{"mode":"mirror"}}`,
} {
if rr := projectRequest(t, s, http.MethodPut, "/api/projects", body); rr.Code == http.StatusOK {
t.Errorf("%s: saved", name)
}
}
}
func TestProjectTargets_CannotBeEditedAsTargets(t *testing.T) {
s, src := newTestServer(t)
addProject(t, s, filepath.Join(filepath.Dir(src), "app"))
for _, method := range []string{http.MethodPatch, http.MethodDelete} {
if rr := projectRequest(t, s, method, "/api/targets/app@claude", `{"mode":"merge"}`); rr.Code != http.StatusBadRequest {
t.Errorf("%s: %d %s", method, rr.Code, rr.Body)
}
}
}
func TestRemoveProject_DropsItsTargets(t *testing.T) {
s, src := newTestServer(t)
root := filepath.Join(filepath.Dir(src), "app")
addProject(t, s, root)
if rr := projectRequest(t, s, http.MethodDelete, "/api/projects?root="+root, ""); rr.Code != http.StatusOK {
t.Fatalf("%d %s", rr.Code, rr.Body)
}
if len(s.cfg.Projects) != 0 || len(s.cfg.Targets) != 0 {
t.Fatalf("projects %v, targets %v", s.cfg.Projects, s.cfg.Targets)
}
}
func TestConvertProject_MovesTargetsUnderProjectsWithTheSameFolders(t *testing.T) {
root := filepath.Join(t.TempDir(), "legacy")
skills := filepath.Join(root, ".claude", "skills")
s, _ := newTestServerWithTargets(t, map[string]string{"old-claude": skills})
if rr := projectRequest(t, s, http.MethodPost, "/api/projects/convert", `{"root":"`+root+`"}`); rr.Code != http.StatusOK {
t.Fatalf("%d %s", rr.Code, rr.Body)
}
if _, kept := s.cfg.Targets["old-claude"]; kept {
t.Error("old-claude is still a target")
}
converted := s.cfg.Targets[config.ProjectTargetName("legacy", "claude")]
if got := converted.SkillsConfig().Path; got != skills {
t.Errorf("skills path %q, want %q", got, skills)
}
}
func TestProjectReplacementParity(t *testing.T) {
for _, tc := range []struct {
name, replacement string
skills, agents bool
}{
{"clear name and skills", `"agents":{"mode":"symlink","include":["team-*"],"exclude":["private"]}`, false, true},
{"clear agents", `"skills":{}`, true, false},
{"MCP hooks only", `"skills":null,"agents":null`, false, false},
} {
t.Run(tc.name, func(t *testing.T) {
s, src := newTestServer(t)
root := filepath.Join(filepath.Dir(src), "app")
addProject(t, s, root)
rr := projectRequest(t, s, http.MethodPut, "/api/projects", `{"root":"`+root+`","name":"custom","targets":["claude"],"skills":{},"agents":{}}`)
if rr.Code != 200 {
t.Fatalf("seed: %d %s", rr.Code, rr.Body)
}
rr = projectRequest(t, s, http.MethodPut, "/api/projects", `{"root":"`+root+`","targets":["claude"],`+tc.replacement+`}`)
var response struct {
Success bool `json:"success"`
Root string `json:"root"`
Origin string `json:"origin"`
OriginPath string `json:"originPath"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if rr.Code != 200 || !response.Success || response.Root != root || response.Origin != "shared" || response.OriginPath != s.configPath() {
t.Fatalf("replacement: %d %s", rr.Code, rr.Body)
}
p := s.cfg.Projects[root]
if p.Name != "" || (p.Skills != nil) != tc.skills || (p.Agents != nil) != tc.agents {
t.Fatalf("replacement not full value: %+v", p)
}
if tc.agents && (len(p.Agents.Include) != 1 || p.Agents.Include[0] != "team-*" || len(p.Agents.Exclude) != 1) {
t.Fatalf("agent filters lost: %+v", p.Agents)
}
listed := projectRequest(t, s, http.MethodGet, "/api/projects", "")
var envelope map[string]json.RawMessage
if err := json.Unmarshal(listed.Body.Bytes(), &envelope); err != nil {
t.Fatal(err)
}
if len(envelope) != 5 || envelope["projects"] == nil || envelope["convertible"] == nil || envelope["tools"] == nil || string(envelope["storage"]) != `"shared"` {
t.Fatalf("list envelope: %s", listed.Body)
}
var paths map[string]string
if err := json.Unmarshal(envelope["storagePaths"], &paths); err != nil || paths["shared"] != s.configPath() || !strings.HasSuffix(paths["local"], ".yaml") {
t.Fatalf("storagePaths: %s", envelope["storagePaths"])
}
})
}
}
func TestSaveProject_EffectiveCandidateRejectedWithoutMutation(t *testing.T) {
s, src := newTestServer(t)
root := filepath.Join(filepath.Dir(src), "app")
other := filepath.Join(filepath.Dir(src), "other")
for _, dir := range []string{root, other} {
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatal(err)
}
}
raw := []byte("source: " + src + "\ntargets: {}\nprojects:\n " + root + ": &shared\n targets: [claude]\n skills: {}\n " + other + ": *shared\n")
if err := os.WriteFile(config.ConfigPath(), raw, 0644); err != nil {
t.Fatal(err)
}
rr := projectRequest(t, s, http.MethodPut, "/api/projects", `{"root":"`+root+`","name":"other","targets":["claude"],"skills":{}}`)
if rr.Code != http.StatusBadRequest || !strings.Contains(rr.Body.String(), "both named") {
t.Fatalf("effective validation: %d %s", rr.Code, rr.Body)
}
if got, _ := os.ReadFile(config.ConfigPath()); !bytes.Equal(got, raw) {
t.Fatal("rejected candidate changed disk")
}
if s.cfg.Projects[root].Name != "" || s.cfg.Projects[other].Name != "" {
t.Fatal("rejected candidate changed in-memory declarations")
}
}
func TestRemoveProject_DetachFailureKeepsRegistration(t *testing.T) {
s, src := newTestServer(t)
root := filepath.Join(filepath.Dir(src), "app")
addProject(t, s, root)
original := detachSkillsTarget
t.Cleanup(func() { detachSkillsTarget = original })
calls := 0
detachSkillsTarget = func(path string, opts ssync.DetachOptions) (ssync.DetachReport, error) {
calls++
if opts.Source != src || opts.DryRun {
t.Fatalf("detach inputs: %+v", opts)
}
if calls == 2 {
return ssync.DetachReport{}, errors.New("later detach denied")
}
return ssync.DetachReport{Removed: []string{path}}, nil
}
rr := projectRequest(t, s, http.MethodDelete, "/api/projects?root="+root, "")
if rr.Code != 500 || !strings.Contains(rr.Body.String(), "later detach denied") {
t.Fatalf("detach response: %d %s", rr.Code, rr.Body)
}
if _, ok := s.cfg.Projects[root]; !ok {
t.Fatal("detach failure changed memory")
}
disk, err := config.LoadReadOnly()
if err != nil {
t.Fatal(err)
}
if _, ok := disk.Projects[root]; !ok {
t.Fatal("detach failure changed disk")
}
}
func TestProjectsHTTP_RootOnlyLookupAndStatusParity(t *testing.T) {
s, src := newTestServer(t)
root := filepath.Join(filepath.Dir(src), "app")
addProject(t, s, root)
for _, tc := range []struct {
method, url, body string
status int
}{
{http.MethodPut, "/api/projects", `{"create":true,"root":"` + root + `","targets":["claude"]}`, 409},
{http.MethodPut, "/api/projects", `{"root":"app","targets":["claude"],"skills":{}}`, 404},
{http.MethodDelete, "/api/projects?root=app", "", 404},
{http.MethodPut, "/api/projects", `{"create":true,"root":"` + root + `-gone","targets":["claude"]}`, 400},
{http.MethodPut, "/api/projects", `{"root":"` + root + `","targets":["claude"],"agents":{"include":["["]}}`, 400},
} {
rr := projectRequest(t, s, tc.method, tc.url, tc.body)
if rr.Code != tc.status {
t.Fatalf("%s %s: %d %s, want %d", tc.method, tc.url, rr.Code, rr.Body, tc.status)
}
}
}
func TestProjectsHTTP_NormalizedSharedRootIsOverriddenLocally(t *testing.T) {
s, src := newTestServer(t)
root := filepath.Join(filepath.Dir(src), "app")
addProjectIn(t, s, root, "local")
alias := root + string(filepath.Separator) + "."
raw := "source: " + src + "\ntargets: {}\nprojects:\n " + alias + ": {name: shared, targets: [codex], skills: {}}\n"
if err := os.WriteFile(s.configPath(), []byte(raw), 0644); err != nil {
t.Fatal(err)
}
rr := projectRequest(t, s, http.MethodGet, "/api/projects", "")
if rr.Code != 200 || !strings.Contains(rr.Body.String(), `"origin":"local"`) {
t.Fatalf("%d %s", rr.Code, rr.Body)
}
if len(s.cfg.Projects) != 1 {
t.Fatal(s.cfg.Projects)
}
}
func TestConvertProject_ExcludedRootKeepsOrdinaryTargets(t *testing.T) {
root := filepath.Join(t.TempDir(), "app")
s, _ := newTestServerWithTargets(t, map[string]string{"old-claude": filepath.Join(root, ".claude", "skills")})
t.Setenv("XDG_STATE_HOME", t.TempDir())
local, err := config.LocalProjectsPath(s.configPath())
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(local), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(local, []byte("version: 1\nexcluded:\n - "+root+"\n"), 0600); err != nil {
t.Fatal(err)
}
before, _ := os.ReadFile(s.configPath())
rr := projectRequest(t, s, http.MethodPost, "/api/projects/convert", `{"root":"`+root+`"}`)
if rr.Code != http.StatusNotFound {
t.Fatalf("%d %s", rr.Code, rr.Body)
}
after, _ := os.ReadFile(s.configPath())
if !bytes.Equal(before, after) {
t.Fatal("conversion wrote hidden replacement")
}
}
func TestProjectMutationResponsesIncludeOrigin(t *testing.T) {
s, src := newTestServer(t)
root := filepath.Join(filepath.Dir(src), "app")
if err := os.MkdirAll(root, 0755); err != nil {
t.Fatal(err)
}
for _, method := range []string{http.MethodPut, http.MethodDelete} {
url := "/api/projects"
body := `{"create":true,"root":"` + root + `","targets":["claude"],"skills":{}}`
if method == http.MethodDelete {
url += "?root=" + root
body = ""
}
rr := projectRequest(t, s, method, url, body)
var response struct{ Origin, OriginPath string }
if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if rr.Code != 200 || response.Origin != "shared" || response.OriginPath == "" {
t.Fatalf("%s: %d %s", method, rr.Code, rr.Body)
}
}
}
// Removing a project this machine overrides keeps config.yaml's copy unless
// shared=true asks to remove it there too.
func TestRemoveProject_LocalOverrideKeepsSharedCopy(t *testing.T) {
for _, shared := range []bool{false, true} {
s, src := newTestServer(t)
root := filepath.Join(filepath.Dir(src), "app")
addProjectIn(t, s, root, "local")
raw := "source: " + src + "\ntargets: {}\nprojects:\n " + root + ": {targets: [codex], skills: {}}\n"
if err := os.WriteFile(s.configPath(), []byte(raw), 0644); err != nil {
t.Fatal(err)
}
url := "/api/projects?root=" + root
if shared {
url += "&shared=true"
}
rr := projectRequest(t, s, http.MethodDelete, url, "")
var response struct{ Remaining bool }
if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil || rr.Code != http.StatusOK {
t.Fatalf("shared=%v: %d %s", shared, rr.Code, rr.Body)
}
after, _ := os.ReadFile(s.configPath())
if kept := strings.Contains(string(after), root); response.Remaining == shared || kept == shared {
t.Fatalf("shared=%v: remaining %v, config.yaml keeps project %v", shared, response.Remaining, kept)
}
}
}
func TestSaveProject_StorageFollowsSettingByDefault(t *testing.T) {
s, src := newTestServer(t)
if err := os.WriteFile(s.configPath(), []byte("source: "+src+"\ntargets: {}\nprojects_storage: machine-local\n"), 0644); err != nil {
t.Fatal(err)
}
root := filepath.Join(filepath.Dir(src), "app")
addProjectIn(t, s, root, "")
if after, _ := os.ReadFile(s.configPath()); strings.Contains(string(after), root) {
t.Fatal("projects_storage: machine-local still saved the project in config.yaml")
}
if rr := projectRequest(t, s, http.MethodGet, "/api/projects", ""); !strings.Contains(rr.Body.String(), `"origin":"local"`) {
t.Fatalf("project is not machine-local: %s", rr.Body)
}
}
func TestScanProjects_PreviewThenAdd(t *testing.T) {
s, src := newTestServer(t)
suite := filepath.Join(filepath.Dir(src), "suite")
for _, dir := range []string{"app-a/.git", ".worktrees/app-a", "docs"} {
if err := os.MkdirAll(filepath.Join(suite, dir), 0755); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(suite, ".worktrees", "app-a", ".git"), []byte("gitdir: /elsewhere\n"), 0644); err != nil {
t.Fatal(err)
}
body := func(dryRun bool) string {
return `{"root":"` + suite + `","scan":[".",".worktrees","later"],"targets":["claude"],"skills":{"mode":"","include":[],"exclude":[]},"dryRun":` + map[bool]string{true: "true", false: "false"}[dryRun] + `}`
}
type scanReply struct {
Applied bool `json:"applied"`
Rows []map[string]string `json:"rows"`
Warnings []projects.ScanWarning `json:"warnings"`
}
listed := func() int {
var list struct {
Projects []projectItem `json:"projects"`
}
json.Unmarshal(projectRequest(t, s, http.MethodGet, "/api/projects", "").Body.Bytes(), &list)
return len(list.Projects)
}
rr := projectRequest(t, s, http.MethodPost, "/api/projects/scan", body(true))
var preview scanReply
if err := json.Unmarshal(rr.Body.Bytes(), &preview); err != nil || rr.Code != http.StatusOK {
t.Fatalf("preview: %d %s", rr.Code, rr.Body)
}
if preview.Applied || len(preview.Rows) != 3 || listed() != 0 {
t.Fatalf("preview wrote or missed rows: %+v, %d listed", preview, listed())
}
if len(preview.Warnings) != 1 || preview.Warnings[0].Kind != projects.ScanMissing || preview.Warnings[0].Folder != "later" {
t.Fatalf("warnings %+v", preview.Warnings)
}
rr = projectRequest(t, s, http.MethodPost, "/api/projects/scan", body(false))
var added scanReply
json.Unmarshal(rr.Body.Bytes(), &added)
if !added.Applied || listed() != 3 {
t.Fatalf("apply: %s, %d listed", rr.Body, listed())
}
paths := map[string]string{}
for _, row := range added.Rows {
paths[row["path"]] = row["name"]
}
if paths["."] != "suite" || paths["app-a"] != "app-a" || paths[".worktrees/app-a"] != "worktrees-app-a" {
t.Fatalf("rows %+v", added.Rows)
}
// A rescan, with the root given with a trailing separator, only keeps.
rr = projectRequest(t, s, http.MethodPost, "/api/projects/scan", strings.Replace(body(false), `"root":"`+suite, `"root":"`+suite+`/`, 1))
var again scanReply
json.Unmarshal(rr.Body.Bytes(), &again)
for _, row := range again.Rows {
if row["result"] != projects.ScanKept {
t.Fatalf("rescan: %s", rr.Body)
}
}
if again.Applied || listed() != 3 {
t.Fatalf("rescan: %s, %d listed", rr.Body, listed())
}
}
func TestScanProjects_RejectsBadRequests(t *testing.T) {
s, src := newTestServer(t)
suite := filepath.Join(filepath.Dir(src), "suite")
if err := os.MkdirAll(suite, 0755); err != nil {
t.Fatal(err)
}
for name, body := range map[string]string{
"no scan folder": `{"root":"` + suite + `","scan":[],"targets":["claude"]}`,
"folder outside root": `{"root":"` + suite + `","scan":["../other"],"targets":["claude"]}`,
"bad filter": `{"root":"` + suite + `","scan":["."],"targets":["claude"],"skills":{"mode":"","include":["["],"exclude":[]}}`,
} {
if rr := projectRequest(t, s, http.MethodPost, "/api/projects/scan", body); rr.Code != http.StatusBadRequest {
t.Errorf("%s: got %d %s", name, rr.Code, rr.Body)
}
}
}