mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-18 18:04:17 +00:00
* feat(hooks): browse, edit and remove unmanaged hooks in the import dialog The import dialog listed every target's hooks in one long scroll of full commands, so it was hard to read and hard to tell which target a row belonged to. It also offered no way to change a hook without first handing it to skillshare. The dialog now shows one target at a time from a rail, with two-line rows that open to the full commands. A hook that lives as an event in a target's settings file can be edited or removed in place: the change stays pending, a review step shows the file diff, and only then is the file written, with a backup that restores it. The hook stays unmanaged. The write is a new operation in internal/hooks (PreviewNativeEdits and ApplyNativeEdits) that addresses elements by content, refuses anything a ledger record holds, and reuses the existing backup and journal path. Whole-file hooks, Copilot files and Antigravity blocks still have to be imported first. * fix(hooks): keep repeated restores and retries from writing a hook twice Two ways an unmanaged hook could end up in a target file twice: Restoring the backup of a removal a second time appended the hook again. An unmanaged hook has no ledger record, so nothing marked the backup as restored. PreviewRestore now reports a conflict when the removed hook is already in the file. When the dialog's native write succeeded and a later import failed, the retry compared each pending change with the row it was made in. An edit that moves or adds a command under another event comes back as other rows, so the change stayed pending and was written again, and the new row was picked for import. The dialog now drops every change once the write went through (or reports files it already applied), and keeps only the rows picked before as imports for the targets it wrote. * chore: release as 0.30.9 Keep the next release on the patch version the maintainer asked for, instead of the 0.31.0 that Release Please derives from the feat commit. Release-As: 0.30.9 * fix(hooks): tell a restored hook from a surviving twin, keep unwritten edits The check that refuses a second restore of a removed unmanaged hook looked for any unmanaged hook with the same content. When one of two identical hooks was removed, the survivor made the first restore look done. A removal that shifts later hooks is stored as an update plus a removal, which the check did not cover, and a restored hook that was imported afterwards no longer counted, so those backups could still restore twice. Every change to an unmanaged hook now records how many identical hooks the write left, and a restore is refused only when the file holds more than that. When a native write failed after its first file, the dialog dropped every pending change, including those of files the write never reached. The failure response now lists the applied files in error_params, and the dialog drops only the changes of those files. Pasted candidates are no longer unpicked by a write to the target they were pasted for. * fix(ui): show a hook row's edit and remove actions once An open row in the import dialog showed the pencil and trash icons next to the labelled Edit and Remove buttons below, which do the same thing. The icons now hide while the row is open; their space is kept so the chevron stays where it was clicked. * chore: release as 0.30.9 Keep the next release on the patch version the maintainer asked for, instead of the 0.31.0 that Release Please derives from the feat commit. Release-As: 0.30.9 * fix(hooks): count surviving twins for every backup, not only native edits Only the native edit preview recorded how many identical hooks a write left, so the backup a restore writes had no count. Undoing a restore through Backups was then refused whenever a hook with the same content was still in the file. The count now happens where every backup is written. * fix(ui): keep the row icons as the only edit and remove actions The labelled Edit and Remove buttons under an open row repeated the icons and stood out too much, so they are gone and the icons stay visible on open rows again. Each icon now has a tooltip that says what it does. * chore: release as 0.30.9 Keep the next release on the patch version the maintainer asked for, instead of the 0.31.0 that Release Please derives from the feat commit. Release-As: 0.30.9 * fix(ui): put the import dialog's hooks on one card, with fewer lines and fills The dialog mixed a grey rail, a grey footer, grey expanded rows and a divider around every region, and the editor stacked its own Cancel and Done above the dialog's. It read as cluttered, and a long JSON line pushed the editor's controls out of the dialog. The dialog now sits on the page background with the hook list, or the editor, as one card. Rows are separated only by the list separator, the row icons are neutral until hovered, and code is the only sunken fill. One row is open at a time, and a single command no longer repeats its event as a heading. While a hook is edited, the dialog's footer holds the editor's actions, so there is one row of buttons and Cancel returns to the list instead of closing the dialog with the draft. Commands are sections of the card and wrap instead of scrolling sideways. The dialog is larger. The hint is one line, the edit note moved to the footer, and the name field is labelled by where the name is used. * chore: release as 0.30.9 Keep the next release on the patch version the maintainer asked for, instead of the 0.31.0 that Release Please derives from the feat commit. Release-As: 0.30.9 * fix(ui): give the import review step the same card-on-ground look The review step still had the white body, the grey footer and the bordered summary box, so it looked like a different dialog from the list it follows. It now sits on the page background with the summary as one card, and the removal tile is neutral with only its icon in the danger colour. * chore: release as 0.30.9 Keep the next release on the patch version the maintainer asked for, instead of the 0.31.0 that Release Please derives from the feat commit. Release-As: 0.30.9
437 lines
18 KiB
Go
437 lines
18 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"skillshare/internal/hooks"
|
|
"skillshare/internal/oplog"
|
|
)
|
|
|
|
const hooksTestMutation = `{"name":"bash-log","entry":{"bindings":{"claude":{"events":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo skillshare-hooks-test"}]}]}}}}}`
|
|
|
|
func hooksTestHome(t *testing.T) string {
|
|
t.Helper()
|
|
home := t.TempDir()
|
|
t.Setenv("HOME", home)
|
|
t.Setenv("CLAUDE_CONFIG_DIR", "")
|
|
return home
|
|
}
|
|
|
|
func hooksPost(s *Server, handler http.HandlerFunc, path, body string) *httptest.ResponseRecorder {
|
|
w := httptest.NewRecorder()
|
|
handler(w, httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)))
|
|
return w
|
|
}
|
|
|
|
// hooksPreviewRevision previews the mutation and returns its revision.
|
|
func hooksPreviewRevision(t *testing.T, s *Server, mutation string) string {
|
|
t.Helper()
|
|
w := hooksPost(s, s.handleHooksPreview, "/api/hooks/preview", `{"mutation":`+mutation+`}`)
|
|
var p struct {
|
|
Revision string `json:"revision"`
|
|
}
|
|
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &p) != nil || p.Revision == "" {
|
|
t.Fatalf("preview: %d %s", w.Code, w.Body)
|
|
}
|
|
return p.Revision
|
|
}
|
|
|
|
func TestHooksAPIPreviewThenApply(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
home := hooksTestHome(t)
|
|
settings := filepath.Join(home, ".claude", "settings.json")
|
|
|
|
revision := hooksPreviewRevision(t, s, hooksTestMutation)
|
|
if _, err := os.Stat(settings); !os.IsNotExist(err) {
|
|
t.Fatal("preview wrote native configuration")
|
|
}
|
|
w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"`+revision+`","sync":true}`)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("apply: %d %s", w.Code, w.Body)
|
|
}
|
|
data, err := os.ReadFile(settings)
|
|
if err != nil || !strings.Contains(string(data), "skillshare-hooks-test") {
|
|
t.Fatalf("apply did not write Claude settings: %v %s", err, data)
|
|
}
|
|
|
|
list := httptest.NewRecorder()
|
|
s.handleHooksList(list, httptest.NewRequest(http.MethodGet, "/api/hooks", nil))
|
|
var view struct {
|
|
Source struct {
|
|
Entries map[string]json.RawMessage `json:"entries"`
|
|
} `json:"source"`
|
|
}
|
|
if list.Code != http.StatusOK || json.Unmarshal(list.Body.Bytes(), &view) != nil || view.Source.Entries["bash-log"] == nil {
|
|
t.Fatalf("list: %d %s", list.Code, list.Body)
|
|
}
|
|
}
|
|
|
|
func TestHooksAPIProjectModeWritesProjectFiles(t *testing.T) {
|
|
s, root := newTestProjectServerWithExtras(t, nil)
|
|
home := hooksTestHome(t)
|
|
|
|
revision := hooksPreviewRevision(t, s, hooksTestMutation)
|
|
w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"`+revision+`","sync":true}`)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("apply: %d %s", w.Code, w.Body)
|
|
}
|
|
if data, err := os.ReadFile(filepath.Join(root, ".claude", "settings.json")); err != nil || !strings.Contains(string(data), "skillshare-hooks-test") {
|
|
t.Fatalf("project apply did not write project settings: %v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(home, ".claude", "settings.json")); !os.IsNotExist(err) {
|
|
t.Fatal("project apply wrote global settings")
|
|
}
|
|
}
|
|
|
|
func TestHooksAPIRejectsUnpreviewedOrStaleSaves(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
hooksTestHome(t)
|
|
|
|
missing := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"sync":true}`)
|
|
if missing.Code != http.StatusBadRequest {
|
|
t.Fatalf("save without revision: %d %s", missing.Code, missing.Body)
|
|
}
|
|
stale := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"stale","sync":true}`)
|
|
if stale.Code != http.StatusConflict {
|
|
t.Fatalf("stale revision: %d %s", stale.Code, stale.Body)
|
|
}
|
|
}
|
|
|
|
func TestHooksAPIRejectsMalformedRequests(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
hooksTestHome(t)
|
|
for _, tc := range []struct {
|
|
name string
|
|
handler http.HandlerFunc
|
|
body string
|
|
}{
|
|
{"unknown field", s.handleHooksPreview, `{"mutation":{},"extra":true}`},
|
|
{"two documents", s.handleHooksPreview, `{"mutation":{}}{"mutation":{}}`},
|
|
{"import unknown field", s.handleHooksImport, `{"from":"claude","piExtension":"builtin"}`},
|
|
{"restore without backup", s.handleHooksRestore, `{"preview":true}`},
|
|
{"restore without preview", s.handleHooksRestore, `{"backupId":"x"}`},
|
|
} {
|
|
if w := hooksPost(s, tc.handler, "/", tc.body); w.Code != http.StatusBadRequest {
|
|
t.Errorf("%s: %d %s", tc.name, w.Code, w.Body)
|
|
}
|
|
}
|
|
large := hooksPost(s, s.handleHooksPreview, "/", `{"mutation":{"name":"`+strings.Repeat("x", int(defaultJSONBodyLimit))+`"}}`)
|
|
if large.Code != http.StatusRequestEntityTooLarge {
|
|
t.Fatalf("oversized body: %d", large.Code)
|
|
}
|
|
}
|
|
|
|
func TestHooksAPIImportListsCandidatesWithoutExecuting(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
home := hooksTestHome(t)
|
|
marker := filepath.Join(t.TempDir(), "executed")
|
|
settings := filepath.Join(home, ".claude", "settings.json")
|
|
if err := os.MkdirAll(filepath.Dir(settings), 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
native := `{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"touch ` + marker + `"}]}]}}`
|
|
if err := os.WriteFile(settings, []byte(native), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude"}`)
|
|
var result struct {
|
|
Candidates []struct {
|
|
Name string `json:"name"`
|
|
} `json:"candidates"`
|
|
}
|
|
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &result) != nil || len(result.Candidates) == 0 {
|
|
t.Fatalf("import: %d %s", w.Code, w.Body)
|
|
}
|
|
if _, err := os.Stat(marker); !os.IsNotExist(err) {
|
|
t.Fatal("import executed a hook command")
|
|
}
|
|
}
|
|
|
|
func TestHooksRoutesRejectRebindingHost(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
s.addr = "127.0.0.1:19420"
|
|
for _, route := range []string{"GET /api/hooks", "POST /api/hooks", "POST /api/hooks/preview", "POST /api/hooks/render", "POST /api/hooks/import", "POST /api/hooks/native", "POST /api/hooks/native/preview", "POST /api/hooks/restore", "GET /api/hooks/catalog"} {
|
|
method, path, _ := strings.Cut(route, " ")
|
|
req := httptest.NewRequest(method, path, strings.NewReader(`{}`))
|
|
req.RemoteAddr = "127.0.0.1:5555"
|
|
req.Host = "attacker.example:19420"
|
|
w := httptest.NewRecorder()
|
|
s.mux.ServeHTTP(w, req)
|
|
if w.Code != http.StatusForbidden {
|
|
t.Fatalf("%s: status = %d, want 403", route, w.Code)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestHooksAPIRenderShowsOneHookWithoutWriting(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
home := hooksTestHome(t)
|
|
config := readOrEmpty(s.configPath())
|
|
root := t.TempDir()
|
|
for _, tc := range []struct{ mutation, path string }{
|
|
{hooksTestMutation, filepath.Join(home, ".claude", "settings.json")},
|
|
{hooksProjectEntry(root, "guard", "echo skillshare-hooks-test"), filepath.Join(root, ".claude", "settings.json")},
|
|
} {
|
|
w := hooksPost(s, s.handleHooksRender, "/api/hooks/render", `{"mutation":`+tc.mutation+`}`)
|
|
var body struct {
|
|
Rendered []struct {
|
|
Target, Path, Content, Error string
|
|
} `json:"rendered"`
|
|
}
|
|
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &body) != nil || len(body.Rendered) != 1 {
|
|
t.Fatalf("render: %d %s", w.Code, w.Body)
|
|
}
|
|
f := body.Rendered[0]
|
|
if f.Target != "claude" || f.Path != tc.path || f.Error != "" || !strings.Contains(f.Content, `"hooks"`) || !strings.Contains(f.Content, "skillshare-hooks-test") {
|
|
t.Fatalf("rendered: %+v", f)
|
|
}
|
|
if _, err := os.Stat(tc.path); !os.IsNotExist(err) {
|
|
t.Fatal("render wrote native configuration")
|
|
}
|
|
}
|
|
if readOrEmpty(s.configPath()) != config {
|
|
t.Fatal("render must not save the source")
|
|
}
|
|
if entries, _ := oplog.Read(s.configPath(), oplog.OpsFile, 10); len(entries) != 0 {
|
|
t.Fatalf("render must not write the operations log: %+v", entries)
|
|
}
|
|
}
|
|
|
|
func TestHooksAPIRenderRejectsNonRenderRequests(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
hooksTestHome(t)
|
|
for _, body := range []string{
|
|
`{"mutation":` + hooksTestMutation + `,"revision":"x"}`,
|
|
`{"mutation":{"name":"bash-log","remove":true}}`,
|
|
`{"mutation":{"name":"bash-log"}}`,
|
|
`{"mutation":{"entry":{"bindings":{}}}}`,
|
|
`{"mutation":` + strings.Replace(hooksTestMutation, `"name"`, `"replace":true,"name"`, 1) + `}`,
|
|
`{"mutation":` + hooksTestMutation + `}{}`,
|
|
} {
|
|
if w := hooksPost(s, s.handleHooksRender, "/api/hooks/render", body); w.Code != http.StatusBadRequest {
|
|
t.Fatalf("%s: status %d %s", body, w.Code, w.Body)
|
|
}
|
|
}
|
|
}
|
|
|
|
// hooksSave previews and saves a mutation to the source without syncing.
|
|
func hooksSave(t *testing.T, s *Server, mutation string) {
|
|
t.Helper()
|
|
revision := hooksPreviewRevision(t, s, mutation)
|
|
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+mutation+`,"revision":"`+revision+`"}`); w.Code != http.StatusOK {
|
|
t.Fatalf("save %s: %d %s", mutation, w.Code, w.Body)
|
|
}
|
|
}
|
|
|
|
func hooksProjectEntry(root, name, command string) string {
|
|
return `{"project":"` + root + `","name":"` + name + `","entry":{"bindings":{"claude":{"events":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"` + command + `"}]}]}}}}}`
|
|
}
|
|
|
|
func readOrEmpty(path string) string {
|
|
data, _ := os.ReadFile(path)
|
|
return string(data)
|
|
}
|
|
|
|
func TestHooksAPIProjectSyncAppliesOnlyThatRoot(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
home := hooksTestHome(t)
|
|
rootA, rootB := t.TempDir(), t.TempDir()
|
|
settingsA := filepath.Join(rootA, ".claude", "settings.json")
|
|
if err := os.MkdirAll(filepath.Dir(settingsA), 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(settingsA, []byte(`{"theme":"dark"}`), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
hooksSave(t, s, hooksProjectEntry(rootA, "a", "echo hook-a"))
|
|
hooksSave(t, s, hooksProjectEntry(rootB, "b", "echo hook-b"))
|
|
hooksSave(t, s, hooksTestMutation)
|
|
|
|
revision := hooksPreviewRevision(t, s, `{}`)
|
|
w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+rootA+`"}`)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("project sync: %d %s", w.Code, w.Body)
|
|
}
|
|
if got := readOrEmpty(settingsA); !strings.Contains(got, "echo hook-a") || !strings.Contains(got, `"theme"`) {
|
|
t.Fatalf("root A not synced with its settings kept:\n%s", got)
|
|
}
|
|
if got := readOrEmpty(filepath.Join(rootB, ".claude", "settings.json")); got != "" {
|
|
t.Fatalf("syncing root A wrote root B:\n%s", got)
|
|
}
|
|
if got := readOrEmpty(filepath.Join(home, ".claude", "settings.json")); got != "" {
|
|
t.Fatalf("syncing root A wrote the global settings:\n%s", got)
|
|
}
|
|
|
|
stale := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+rootB+`"}`)
|
|
if stale.Code != http.StatusConflict {
|
|
t.Fatalf("reused revision: %d %s", stale.Code, stale.Body)
|
|
}
|
|
|
|
hooksSave(t, s, `{"project":"`+rootA+`","name":"a","remove":true}`)
|
|
revision = hooksPreviewRevision(t, s, `{}`)
|
|
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+rootA+`"}`); w.Code != http.StatusOK {
|
|
t.Fatalf("prune sync: %d %s", w.Code, w.Body)
|
|
}
|
|
if got := readOrEmpty(settingsA); strings.Contains(got, "echo hook-a") || !strings.Contains(got, `"theme"`) {
|
|
t.Fatalf("prune did not remove only the owned hook:\n%s", got)
|
|
}
|
|
if got := readOrEmpty(filepath.Join(rootB, ".claude", "settings.json")); got != "" {
|
|
t.Fatalf("pruning root A wrote root B:\n%s", got)
|
|
}
|
|
}
|
|
|
|
func TestHooksAPIProjectSyncRejectsInvalidRoot(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
hooksTestHome(t)
|
|
root := t.TempDir()
|
|
hooksSave(t, s, hooksProjectEntry(root, "a", "echo hook-a"))
|
|
revision := hooksPreviewRevision(t, s, `{}`)
|
|
for name, body := range map[string]string{
|
|
"with changes": `{"mutation":{"name":"a","remove":true},"revision":"` + revision + `","sync":true,"root":"` + root + `"}`,
|
|
"without sync": `{"mutation":{},"revision":"` + revision + `","root":"` + root + `"}`,
|
|
"unknown root": `{"mutation":{},"revision":"` + revision + `","sync":true,"root":"` + t.TempDir() + `"}`,
|
|
} {
|
|
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", body); w.Code != http.StatusBadRequest {
|
|
t.Errorf("%s: %d %s", name, w.Code, w.Body)
|
|
}
|
|
}
|
|
|
|
project, _ := newTestProjectServerWithExtras(t, nil)
|
|
revision = hooksPreviewRevision(t, project, `{}`)
|
|
w := hooksPost(project, project.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+root+`"}`)
|
|
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "global mode") {
|
|
t.Fatalf("project mode root: %d %s", w.Code, w.Body)
|
|
}
|
|
}
|
|
|
|
func TestHooksAPIImportReadsProjectRoot(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
hooksTestHome(t)
|
|
root := t.TempDir()
|
|
hooksSave(t, s, `{"project":"`+root+`"}`)
|
|
settings := filepath.Join(root, ".claude", "settings.json")
|
|
if err := os.MkdirAll(filepath.Dir(settings), 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(settings, []byte(`{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo project-native"}]}]}}`), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude","root":"`+root+`"}`)
|
|
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "project-native") {
|
|
t.Fatalf("project import: %d %s", w.Code, w.Body)
|
|
}
|
|
global := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude"}`)
|
|
if global.Code != http.StatusOK || strings.Contains(global.Body.String(), "project-native") {
|
|
t.Fatalf("global import read the project file: %d %s", global.Code, global.Body)
|
|
}
|
|
if w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude","root":"`+t.TempDir()+`"}`); w.Code != http.StatusBadRequest {
|
|
t.Fatalf("unknown import root: %d %s", w.Code, w.Body)
|
|
}
|
|
}
|
|
|
|
func TestHooksAPICatalogListsCommandAgentEvents(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
w := httptest.NewRecorder()
|
|
s.handleHooksCatalog(w, httptest.NewRequest(http.MethodGet, "/api/hooks/catalog", nil))
|
|
var catalog map[string]struct {
|
|
Events []struct {
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
Matcher bool `json:"matcher"`
|
|
} `json:"events"`
|
|
TimeoutUnit string `json:"timeoutUnit"`
|
|
}
|
|
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &catalog) != nil {
|
|
t.Fatalf("catalog: %d %s", w.Code, w.Body)
|
|
}
|
|
if c := catalog["gemini"]; c.TimeoutUnit != "milliseconds" || len(c.Events) == 0 || c.Events[0].Description == "" {
|
|
t.Fatalf("gemini catalog: %+v", c)
|
|
}
|
|
if _, ok := catalog["pi"]; ok {
|
|
t.Fatal("code Agents have no event catalog")
|
|
}
|
|
}
|
|
|
|
func TestHooksAPIImportSaveTakesOverWithoutReplace(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
home := hooksTestHome(t)
|
|
settings := filepath.Join(home, ".claude", "settings.json")
|
|
native := `{"model":"opus","hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo stop"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo guard"}]}]}}`
|
|
if err := os.MkdirAll(filepath.Dir(settings), 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(settings, []byte(native), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude","name":"claude-stop"}`)
|
|
var imported struct {
|
|
Candidates []struct {
|
|
Entry json.RawMessage `json:"entry"`
|
|
} `json:"candidates"`
|
|
}
|
|
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &imported) != nil || len(imported.Candidates) != 1 {
|
|
t.Fatalf("import: %d %s", w.Code, w.Body)
|
|
}
|
|
mutation := `{"name":"claude-stop","entry":` + string(imported.Candidates[0].Entry) + `,"adopt":true}`
|
|
revision := hooksPreviewRevision(t, s, mutation)
|
|
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+mutation+`,"revision":"`+revision+`","sync":false}`); w.Code != http.StatusOK {
|
|
t.Fatalf("save: %d %s", w.Code, w.Body)
|
|
}
|
|
preview := hooksPost(s, s.handleHooksPreview, "/api/hooks/preview", `{"mutation":{}}`)
|
|
var plan struct {
|
|
Blocked bool `json:"blocked"`
|
|
Changes []struct {
|
|
Action string `json:"action"`
|
|
} `json:"changes"`
|
|
}
|
|
if json.Unmarshal(preview.Body.Bytes(), &plan) != nil || plan.Blocked || len(plan.Changes) != 1 || plan.Changes[0].Action != "adopt" {
|
|
t.Fatalf("sync after an imported save: %s", preview.Body)
|
|
}
|
|
}
|
|
|
|
func TestHooksAPIPreviewCarriesFileTexts(t *testing.T) {
|
|
s, _ := newTestServerWithExtras(t, nil, "")
|
|
home := hooksTestHome(t)
|
|
w := hooksPost(s, s.handleHooksPreview, "/api/hooks/preview", `{"mutation":`+hooksTestMutation+`}`)
|
|
var p struct {
|
|
Revision string `json:"revision"`
|
|
Files []struct {
|
|
Target, Path, Before, After string
|
|
} `json:"files"`
|
|
}
|
|
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &p) != nil || len(p.Files) != 1 {
|
|
t.Fatalf("preview: %d %s", w.Code, w.Body)
|
|
}
|
|
f := p.Files[0]
|
|
if f.Target != "claude" || f.Path != filepath.Join(home, ".claude", "settings.json") || f.Before != "" || !strings.Contains(f.After, "skillshare-hooks-test") {
|
|
t.Fatalf("file diff: %+v", f)
|
|
}
|
|
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"`+p.Revision+`","sync":true}`); w.Code != http.StatusOK {
|
|
t.Fatalf("apply: %d %s", w.Code, w.Body)
|
|
}
|
|
if data, _ := os.ReadFile(f.Path); string(data) != f.After {
|
|
t.Fatalf("written file differs from the preview:\n%s", data)
|
|
}
|
|
}
|
|
|
|
// A write that failed part-way names the files it already wrote, so the dashboard keeps the rest pending.
|
|
func TestWriteHooksFailure_ListsAppliedFiles(t *testing.T) {
|
|
w := httptest.NewRecorder()
|
|
writeHooksFailure(w, &hooks.Result{Applied: []string{"/a/settings.json"}, BackupIDs: []string{"b1"}}, errors.New("write failed"))
|
|
var body struct {
|
|
Params struct {
|
|
Applied []string `json:"applied"`
|
|
} `json:"error_params"`
|
|
}
|
|
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != http.StatusConflict || len(body.Params.Applied) != 1 || body.Params.Applied[0] != "/a/settings.json" {
|
|
t.Fatalf("want the applied file in error_params: %d %s", w.Code, w.Body)
|
|
}
|
|
}
|