From 0dc2018747844aa1a44b9a9c2ff697c7e82d263d Mon Sep 17 00:00:00 2001 From: Willie Date: Mon, 16 Nov 2026 22:55:13 +0800 Subject: [PATCH] feat(hooks): browse, edit and remove unmanaged hooks in the import dialog (#920) * 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 --- internal/hooks/apply.go | 65 +++ internal/hooks/inventory.go | 1 + internal/hooks/native.go | 3 + internal/hooks/native_edit.go | 244 +++++++++++ internal/hooks/native_edit_test.go | 366 ++++++++++++++++ internal/hooks/service.go | 2 + internal/server/handler_hooks.go | 59 ++- .../server/handler_hooks_contract_test.go | 54 +++ internal/server/handler_hooks_test.go | 18 +- internal/server/server.go | 2 + ui/src/api/hooks.ts | 9 +- ui/src/components/hooks/HookBindingEditor.tsx | 162 +++++++- ui/src/components/hooks/HookDialog.test.tsx | 118 +++++- ui/src/components/hooks/HooksImportDialog.tsx | 390 +++++++++++++----- ui/src/components/hooks/HooksImportEditor.tsx | 70 ++++ ui/src/components/hooks/HooksImportRow.tsx | 133 ++++++ ui/src/components/hooks/HooksScope.tsx | 4 +- ui/src/components/hooks/hooksImport.test.ts | 95 +++++ ui/src/components/hooks/hooksImport.ts | 136 ++++++ ui/src/i18n/locales/de.json | 46 ++- ui/src/i18n/locales/en.json | 46 ++- ui/src/i18n/locales/es.json | 46 ++- ui/src/i18n/locales/fa.json | 46 ++- ui/src/i18n/locales/fr.json | 46 ++- ui/src/i18n/locales/id.json | 46 ++- ui/src/i18n/locales/ja.json | 46 ++- ui/src/i18n/locales/ko.json | 46 ++- ui/src/i18n/locales/pt-BR.json | 46 ++- ui/src/i18n/locales/zh-CN.json | 46 ++- ui/src/i18n/locales/zh-TW.json | 46 ++- website/docs/reference/commands/hooks.md | 9 + .../current/reference/commands/hooks.md | 2 +- .../current/reference/commands/hooks.md | 2 +- .../current/reference/commands/hooks.md | 2 +- .../current/reference/commands/hooks.md | 2 +- 35 files changed, 2290 insertions(+), 164 deletions(-) create mode 100644 internal/hooks/native_edit.go create mode 100644 internal/hooks/native_edit_test.go create mode 100644 ui/src/components/hooks/HooksImportEditor.tsx create mode 100644 ui/src/components/hooks/HooksImportRow.tsx create mode 100644 ui/src/components/hooks/hooksImport.test.ts create mode 100644 ui/src/components/hooks/hooksImport.ts diff --git a/internal/hooks/apply.go b/internal/hooks/apply.go index 1d15f2629..814c01ce5 100644 --- a/internal/hooks/apply.go +++ b/internal/hooks/apply.go @@ -500,6 +500,24 @@ func (s *Service) applyScoped(p *Plan, root *string) (*Result, error) { } // Settings added since the preview keep a file the plan deletes. remove = f.remove && skeleton(f.agent, after) + // Count here, for every write: a restore's own backup can be restored as well. + left, err := parseNative(f.agent, after) + if err != nil { + return result, fmt.Errorf("%s: %w", f.path, err) + } + ops := append([]elementOp(nil), f.ops...) + for i, op := range ops { + ops[i].Twins = 0 + if op.Key != "" || op.Before == nil { + continue + } + for _, item := range left.events[op.Event] { + if elementHash(item) == elementHash(op.Before) { + ops[i].Twins++ + } + } + } + f.ops = ops } id := fmt.Sprintf("%d-%s", time.Now().UnixNano(), digest([]byte(f.path))[:8]) backup := backupRecord{ID: id, Owner: p.source.ConfigPath, Target: f.target, Path: f.path, Root: f.root, Kind: f.kind, Ops: f.ops, OwnedBefore: map[string]*record{}, OwnedAfter: map[string]*record{}, GitInclude: f.include, GitSection: f.gitSection, BeforeMode: beforeMode, AfterMode: mode} @@ -974,6 +992,28 @@ func (s *Service) PreviewRestore(id string) (*Plan, error) { } } located := locate(doc, current) + // claimed are the elements a record owns or an earlier op already addressed, so + // an op on an unmanaged hook finds its element by content among the rest. + claimed := map[string]map[int]bool{} + claim := func(event string, i int) { + if claimed[event] == nil { + claimed[event] = map[int]bool{} + } + claimed[event][i] = true + } + for key, i := range located { + claim(current[key].Event, i) + } + // unowned finds, and claims, an element no record owns by its content. + unowned := func(event string, value any) (int, bool) { + for at, item := range doc.events[event] { + if !claimed[event][at] && elementHash(item) == elementHash(value) { + claim(event, at) + return at, true + } + } + return 0, false + } for _, op := range b.Ops { if r := b.OwnedAfter[op.Key]; r != nil { change.Name = r.Entry @@ -984,11 +1024,29 @@ func (s *Service) PreviewRestore(id string) (*Plan, error) { conflict("hook changed after the backup; restore would overwrite newer changes") break } + // Nothing records that an unmanaged hook was put back, so more copies than the write + // left are the sign: restoring the same backup again must not add another. A copy + // imported since then counts too. + if op.Key == "" && op.Before != nil { + copies := 0 + for _, item := range doc.events[op.Event] { + if elementHash(item) == elementHash(op.Before) { + copies++ + } + } + if copies > op.Twins { + conflict("the hook is already in the file; this backup may have been restored before") + break + } + } switch { case op.Value == nil: // the write removed it: add it back f.ops = append(f.ops, elementOp{Key: op.Key, Event: op.Event, Index: -1, Value: op.Before}) default: i, ok := located[op.Key] + if op.Key == "" { + i, ok = unowned(op.Event, op.Value) + } if !ok { conflict("hook changed after the backup; restore would overwrite newer changes") break @@ -1002,6 +1060,13 @@ func (s *Service) PreviewRestore(id string) (*Plan, error) { if change.Action == "conflict" { break } + if op.Key == "" { + // An unmanaged hook has no entry to name and no ownership to restore. + if !strings.Contains(", "+change.Name+", ", ", "+op.Event+", ") { + change.Name = strings.TrimPrefix(change.Name+", "+op.Event, ", ") + } + continue + } restoreOwnership(op.Key) } if !p.Blocked { diff --git a/internal/hooks/inventory.go b/internal/hooks/inventory.go index 44a9d649d..dfdeb4b51 100644 --- a/internal/hooks/inventory.go +++ b/internal/hooks/inventory.go @@ -406,6 +406,7 @@ func (s *Service) importShared(target string, req ImportRequest, state ledger) ( c.Warnings = warnings case req.Content == "": c.Warnings = []string{adoptWarning} + c.Editable = nativeEditable(target) } if target == "antigravity" { c = antigravityCandidate(event, items[0].(map[string]any), c.Warnings) diff --git a/internal/hooks/native.go b/internal/hooks/native.go index 7bd590c11..d0d2304fa 100644 --- a/internal/hooks/native.go +++ b/internal/hooks/native.go @@ -175,6 +175,9 @@ type elementOp struct { Index int `json:"index"` Value any `json:"value,omitempty"` Before any `json:"before,omitempty"` + // Twins is how many elements with Before's content a change to an unmanaged element + // left in the event. A restore finding more knows the element is already back. + Twins int `json:"twins,omitempty"` } // edit applies ops and returns the new bytes plus the final index of each op key diff --git a/internal/hooks/native_edit.go b/internal/hooks/native_edit.go new file mode 100644 index 000000000..ce59c81ba --- /dev/null +++ b/internal/hooks/native_edit.go @@ -0,0 +1,244 @@ +package hooks + +import ( + "encoding/json" + "fmt" + "strings" +) + +// NativeEdit rewrites or removes hooks no Skillshare config manages, in the target's +// own settings file. They stay unmanaged: neither the source nor the ownership ledger +// changes. +type NativeEdit struct { + Target string `json:"target"` + // Root edits a hooks.projects root's native file instead of the current scope's. + Root string `json:"root,omitempty"` + // Before holds the unmanaged registrations as Import listed them, keyed by event. + Before map[string]any `json:"before"` + // After replaces them; empty removes them. + After map[string]any `json:"after,omitempty"` +} + +// nativeEditable reports the Agents whose unmanaged hooks are elements of one event +// map, which is what NativeEdit can address. +func nativeEditable(agent string) bool { + def, ok := targetDef(agent) + return ok && def.Kind == KindCommand && agent != "copilot" && agent != "antigravity" +} + +type nativeEditFile struct { + plan *filePlan + doc *nativeDoc + // claimed are the elements a record owns or an earlier edit already addressed. + claimed map[string]map[int]bool + // managed are the content hashes Skillshare records for this file, per event. + managed map[string]bool +} + +// PreviewNativeEdits plans the edits without writing. Each Before element must still +// be in the file and must not be content Skillshare manages. +func (s *Service) PreviewNativeEdits(edits []NativeEdit) (*Plan, error) { + s = s.memoProbe() + if len(edits) == 0 { + return nil, fmt.Errorf("no hook changes given") + } + source, err := s.loadSource() + if err != nil { + return nil, err + } + state, stateBytes, err := s.loadLedger() + if err != nil { + return nil, err + } + p := &Plan{SourcePath: source.ConfigPath, Changes: []Change{}, Warnings: []string{}, source: source, stateBytes: stateBytes, state: state} + files := map[string]*nativeEditFile{} + for _, e := range edits { + target := canonicalTarget(e.Target) + scope, agent := s.forTarget(target) + if !nativeEditable(agent) { + return nil, fmt.Errorf("%s hooks cannot be edited in place; import them to change them", e.Target) + } + root := "" + if e.Root != "" { + if s.ProjectRoot != "" { + return nil, fmt.Errorf("hooks.projects belongs in the global config") + } + if agent != target { + return nil, fmt.Errorf("hooks.projects roots are read by every account; use %s", agent) + } + if root, err = projectRoot(e.Root); err != nil { + return nil, err + } + if _, ok := source.Projects[root]; !ok { + return nil, fmt.Errorf("%w: %s", ErrUnknownProject, e.Root) + } + scope = s.scoped(root) + } + path, err := scope.nativePath(agent) + if err != nil { + return nil, err + } + file := files[path] + if file == nil { + if file, err = s.nativeEditFile(target, agent, root, path, state); err != nil { + return nil, err + } + files[path] = file + p.files = append(p.files, file.plan) + } + if len(e.Before) == 0 { + return nil, fmt.Errorf("%s: no hooks named to change", e.Target) + } + if len(e.After) > 0 { + if err := validateEvents(agent, e.After); err != nil { + return nil, err + } + } + for _, event := range sortedKeys(e.Before) { + before, ok := e.Before[event].([]any) + if !ok || len(before) == 0 { + return nil, fmt.Errorf("event %s must be a non-empty array", event) + } + after, _ := e.After[event].([]any) + for i, item := range before { + index, err := file.find(event, item) + if err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + switch { + case i >= len(after): + file.plan.ops = append(file.plan.ops, elementOp{Event: event, Index: index, Before: item}) + case elementHash(after[i]) != elementHash(item): + if err := file.unmanaged(event, after[i]); err != nil { + return nil, err + } + file.plan.ops = append(file.plan.ops, elementOp{Event: event, Index: index, Value: after[i], Before: item}) + } + } + for i := len(before); i < len(after); i++ { + if err := file.unmanaged(event, after[i]); err != nil { + return nil, err + } + file.plan.ops = append(file.plan.ops, elementOp{Event: event, Index: -1, Value: after[i]}) + } + } + for _, event := range sortedKeys(e.After) { + if _, ok := e.Before[event]; ok { + continue + } + for _, item := range e.After[event].([]any) { + if err := file.unmanaged(event, item); err != nil { + return nil, err + } + file.plan.ops = append(file.plan.ops, elementOp{Event: event, Index: -1, Value: item}) + } + } + action := "update" + if len(e.After) == 0 { + action = "remove" + } + p.Changes = append(p.Changes, Change{Target: target, Path: path, Root: root, Name: strings.Join(sortedKeys(e.Before), ", "), Action: action}) + } + proposal, _ := json.Marshal(edits) + revision := digest(source.bytes) + digest(stateBytes) + digest(proposal) + for _, f := range p.files { + after, _, err := files[f.path].doc.edit(f.ops, nil, false) + if err != nil { + return nil, fmt.Errorf("%s: %w", f.path, err) + } + f.after = after + revision += digest([]byte(f.path + "\x00" + f.section)) + } + p.Revision = digest([]byte(revision)) + p.Fingerprint = p.Revision + return p, nil +} + +func (s *Service) nativeEditFile(target, agent, root, path string, state ledger) (*nativeEditFile, error) { + base, err := s.base(target, root) + if err != nil { + return nil, err + } + if err := checkPath(base, path); err != nil { + return nil, err + } + data, exists, mode, err := safeRead(path) + if err != nil { + return nil, err + } + if !exists { + return nil, fmt.Errorf("%s does not exist", path) + } + doc, err := parseNative(agent, data) + if err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + file := &nativeEditFile{ + plan: &filePlan{path: path, target: target, agent: agent, root: root, base: base, kind: kindJSON, before: data, exists: true, mode: mode, section: doc.sectionDigest()}, + doc: doc, + claimed: map[string]map[int]bool{}, + managed: map[string]bool{}, + } + records := map[string]record{} + for key, r := range state.Records { + if r.Path == path && r.Event != "" { + records[key] = r + file.managed[r.Event+"\x00"+r.Hash] = true + } + } + for key, i := range locate(doc, records) { + file.claim(records[key].Event, i) + } + return file, nil +} + +func (f *nativeEditFile) claim(event string, i int) { + if f.claimed[event] == nil { + f.claimed[event] = map[int]bool{} + } + f.claimed[event][i] = true +} + +// unmanaged refuses content Skillshare also records for the event, as what to change +// or as what to write: nobody could tell the copies apart afterwards. +func (f *nativeEditFile) unmanaged(event string, item any) error { + if f.managed[event+"\x00"+elementHash(item)] { + return fmt.Errorf("a %s hook with the same content is managed by Skillshare; edit that hook instead", event) + } + return nil +} + +// find returns the index of an unmanaged element with this content and claims it. +func (f *nativeEditFile) find(event string, item any) (int, error) { + if err := f.unmanaged(event, item); err != nil { + return 0, err + } + hash := elementHash(item) + for i, current := range f.doc.events[event] { + if !f.claimed[event][i] && elementHash(current) == hash { + f.claim(event, i) + return i, nil + } + } + return 0, fmt.Errorf("the %s hooks changed since they were read: %w", event, ErrStaleRevision) +} + +// ApplyNativeEdits writes previewed edits, with a backup per file. +func (s *Service) ApplyNativeEdits(edits []NativeEdit, revision string) (*Result, error) { + lock, err := s.lock() + if err != nil { + return nil, err + } + defer lock.Unlock() + if err := s.recoverPending(); err != nil { + return nil, err + } + p, err := s.PreviewNativeEdits(edits) + if err != nil { + return nil, err + } + if p.Revision != revision { + return nil, ErrStaleRevision + } + return s.applyScoped(p, nil) +} diff --git a/internal/hooks/native_edit_test.go b/internal/hooks/native_edit_test.go new file mode 100644 index 000000000..f41fab26f --- /dev/null +++ b/internal/hooks/native_edit_test.go @@ -0,0 +1,366 @@ +package hooks + +import ( + "encoding/json" + "errors" + "path/filepath" + "reflect" + "strings" + "testing" +) + +// nativeEdit previews then applies edits, as the dashboard does. +func nativeEdit(t *testing.T, s *Service, edits ...NativeEdit) *Result { + t.Helper() + p, err := s.PreviewNativeEdits(edits) + must(t, err) + r, err := s.ApplyNativeEdits(edits, p.Revision) + must(t, err) + return r +} + +// guardOnWrite is trialSettings' PreToolUse hook with its matcher changed. +func guardOnWrite(t *testing.T) map[string]any { + t.Helper() + var out map[string]any + must(t, json.Unmarshal([]byte(`{"PreToolUse":[{"matcher":"Write","hooks":[{"type":"command","command":"~/.claude/guard.sh"}]}]}`), &out)) + return out +} + +func unmanagedNames(t *testing.T, s *Service) string { + t.Helper() + inventory, err := s.List() + must(t, err) + var names []string + for _, u := range inventory.Unmanaged { + names = append(names, u.Names...) + } + return strings.Join(names, ",") +} + +func TestNativeEdit_RewritesAnUnmanagedHookAndLeavesItUnmanaged(t *testing.T) { + e := newEnv(t) + path := filepath.Join(e.home, ".claude", "settings.json") + write(t, path, trialSettings) + c := importOne(t, e.service, "claude", "claude-pretooluse") + if !c.Editable { + t.Fatal("a Claude event must be editable in place") + } + before := c.Entry.Bindings["claude"].Events + after := guardOnWrite(t) + edits := []NativeEdit{{Target: "claude", Before: before, After: after}} + p, err := e.service.PreviewNativeEdits(edits) + must(t, err) + if files := p.Files(); len(files) != 1 || !strings.Contains(files[0].After, `"matcher":"Write"`) { + t.Fatalf("preview must show the rewritten file: %+v", files) + } + if read(t, path) != trialSettings { + t.Fatal("preview must not write") + } + if _, err := e.service.ApplyNativeEdits(edits, p.Revision); err != nil { + t.Fatal(err) + } + got := read(t, path) + if !strings.Contains(got, `"matcher":"Write"`) || strings.Contains(got, `"matcher":"Bash"`) || !strings.Contains(got, "afplay") || !strings.Contains(got, `"model":"opus"`) { + t.Fatalf("only the edited hook may change:\n%s", got) + } + if names := unmanagedNames(t, e.service); names != "PreToolUse,Stop" { + t.Fatalf("edited hooks must stay unmanaged: %s", names) + } +} + +func TestNativeEdit_RemovesAnUnmanagedHook(t *testing.T) { + e := newEnv(t) + path := filepath.Join(e.home, ".claude", "settings.json") + write(t, path, trialSettings) + c := importOne(t, e.service, "claude", "claude-stop") + nativeEdit(t, e.service, NativeEdit{Target: "claude", Before: c.Entry.Bindings["claude"].Events}) + got := read(t, path) + if strings.Contains(got, "Stop") || !strings.Contains(got, "guard.sh") { + t.Fatalf("only Stop may be removed:\n%s", got) + } +} + +func TestNativeEdit_BackupRestoresTheFile(t *testing.T) { + e := newEnv(t) + path := filepath.Join(e.home, ".claude", "settings.json") + write(t, path, trialSettings) + stop := importOne(t, e.service, "claude", "claude-stop").Entry.Bindings["claude"].Events + guard := importOne(t, e.service, "claude", "claude-pretooluse").Entry.Bindings["claude"].Events + r := nativeEdit(t, e.service, + NativeEdit{Target: "claude", Before: stop}, + NativeEdit{Target: "claude", Before: guard, After: guardOnWrite(t)}, + ) + if len(r.BackupIDs) != 1 { + t.Fatalf("one file, one backup: %v", r.BackupIDs) + } + p, err := e.service.PreviewRestore(r.BackupIDs[0]) + must(t, err) + if p.Blocked { + t.Fatalf("restore blocked: %+v", p.Changes) + } + _, err = e.service.Restore(r.BackupIDs[0], p.Revision) + must(t, err) + got := read(t, path) + if !strings.Contains(got, "afplay") || !strings.Contains(got, `"matcher":"Bash"`) || strings.Contains(got, `"matcher":"Write"`) { + t.Fatalf("restore must bring both hooks back:\n%s", got) + } +} + +func TestNativeEdit_RefusesAManagedHook(t *testing.T) { + e := newEnv(t) + write(t, filepath.Join(e.home, ".claude", "settings.json"), trialSettings) + c := importOne(t, e.service, "claude", "claude-stop") + m := Mutation{Name: c.Name, Entry: &c.Entry, Adopt: true} + p, err := e.service.PreviewMutation(m) + must(t, err) + _, err = e.service.Mutate(m, p.Revision, false) + must(t, err) + _, err = e.service.PreviewNativeEdits([]NativeEdit{{Target: "claude", Before: c.Entry.Bindings["claude"].Events}}) + if err == nil || !strings.Contains(err.Error(), "managed by Skillshare") { + t.Fatalf("a managed hook must be refused: %v", err) + } +} + +func TestNativeEdit_StaleFileIsRefused(t *testing.T) { + e := newEnv(t) + path := filepath.Join(e.home, ".claude", "settings.json") + write(t, path, trialSettings) + c := importOne(t, e.service, "claude", "claude-stop") + edits := []NativeEdit{{Target: "claude", Before: c.Entry.Bindings["claude"].Events}} + p, err := e.service.PreviewNativeEdits(edits) + must(t, err) + write(t, path, strings.Replace(trialSettings, "guard.sh", "other.sh", 1)) + if _, err := e.service.ApplyNativeEdits(edits, p.Revision); !errors.Is(err, ErrStaleRevision) { + t.Fatalf("want ErrStaleRevision, got %v", err) + } +} + +func TestNativeEdit_RefusesFileAndBlockTargets(t *testing.T) { + for _, target := range []string{"pi", "copilot", "antigravity"} { + e := newEnv(t) + _, err := e.service.PreviewNativeEdits([]NativeEdit{{Target: target, Before: map[string]any{"x": []any{map[string]any{}}}}}) + if err == nil || !strings.Contains(err.Error(), "cannot be edited in place") { + t.Fatalf("%s hooks must be refused: %v", target, err) + } + } +} + +// Every Agent that keeps hooks as events of one file: the edit lands in that file's own shape. +func TestNativeEdit_EveryEditableFileShape(t *testing.T) { + files := map[string]string{ + "claude": `{"model":"opus","hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo mine"}]}]}}`, + "gemini": `{"theme":"x","hooks":{"BeforeTool":[{"matcher":"write_.*","hooks":[{"type":"command","command":"echo mine"}]}]}}`, + "qwen": `{"hooks":{"PreToolUse":[{"matcher":"Shell","hooks":[{"type":"command","command":"echo mine"}]}]}}`, + "codex": `{"hooks":{"PreToolUse":[{"matcher":"^shell$","hooks":[{"type":"command","command":"echo mine"}]}]}}`, + "cursor": `{"version":1,"hooks":{"beforeShellExecution":[{"command":"echo mine","matcher":"git"}]}}`, + "droid": `{"PreToolUse":[{"matcher":"Execute","hooks":[{"type":"command","command":"echo mine"}]}]}`, + } + for target, content := range files { + t.Run(target, func(t *testing.T) { + e := newEnv(t) + path := e.service.Paths()[target] + write(t, path, content) + c, err := e.service.Import(ImportRequest{From: target}) + must(t, err) + if len(c) != 1 || !c[0].Editable { + t.Fatalf("want one editable candidate: %+v", c) + } + before := c[0].Entry.Bindings[target].Events + raw, err := json.Marshal(before) + must(t, err) + var after map[string]any + must(t, json.Unmarshal([]byte(strings.Replace(string(raw), "echo mine", "echo edited", 1)), &after)) + nativeEdit(t, e.service, NativeEdit{Target: target, Before: before, After: after}) + got := read(t, path) + if !strings.Contains(got, "echo edited") || strings.Contains(got, "echo mine") { + t.Fatalf("not rewritten:\n%s", got) + } + again, err := e.service.Import(ImportRequest{From: target}) + must(t, err) + if len(again) != 1 || !reflect.DeepEqual(again[0].Entry.Bindings[target].Events, after) { + t.Fatalf("the file must read back as the edited hook: %+v", again) + } + }) + } +} + +// managedBeside saves a managed Stop hook next to an unmanaged one and returns the unmanaged events. +func managedBeside(t *testing.T, e *env, path string) map[string]any { + t.Helper() + save(t, e.service, Mutation{Name: "m", Entry: entry(t, `{"bindings":{"claude":{"events":{"Stop":[{"hooks":[{"type":"command","command":"echo managed"}]}]}}}}`)}) + var doc map[string]map[string][]any + must(t, json.Unmarshal([]byte(read(t, path)), &doc)) + var mine any + must(t, json.Unmarshal([]byte(`{"hooks":[{"type":"command","command":"echo mine"}]}`), &mine)) + doc["hooks"]["Stop"] = append([]any{mine}, doc["hooks"]["Stop"]...) + raw, err := json.Marshal(doc) + must(t, err) + write(t, path, string(raw)) + return importOne(t, e.service, "claude", "claude-stop").Entry.Bindings["claude"].Events +} + +func TestNativeEdit_LeavesAManagedHookOfTheSameEventManaged(t *testing.T) { + e := newEnv(t) + path := filepath.Join(e.home, ".claude", "settings.json") + nativeEdit(t, e.service, NativeEdit{Target: "claude", Before: managedBeside(t, e, path)}) + if got := read(t, path); strings.Contains(got, "echo mine") || !strings.Contains(got, "echo managed") { + t.Fatalf("only the unmanaged hook may go:\n%s", got) + } + p, err := e.service.PreviewMutation(Mutation{}) + must(t, err) + if p.Blocked || unmanagedNames(t, e.service) != "" { + t.Fatalf("the managed hook must still be located: %+v", p.Changes) + } +} + +func TestNativeEdit_RefusesToWriteACopyOfAManagedHook(t *testing.T) { + e := newEnv(t) + path := filepath.Join(e.home, ".claude", "settings.json") + before := managedBeside(t, e, path) + var after map[string]any + must(t, json.Unmarshal([]byte(`{"Stop":[{"hooks":[{"type":"command","command":"echo managed"}]}]}`), &after)) + _, err := e.service.PreviewNativeEdits([]NativeEdit{{Target: "claude", Before: before, After: after}}) + if err == nil || !strings.Contains(err.Error(), "managed by Skillshare") { + t.Fatalf("a second copy of a managed hook must be refused: %v", err) + } +} + +func TestNativeEdit_RemovesOneOfTwoIdenticalHooks(t *testing.T) { + e := newEnv(t) + path := filepath.Join(e.home, ".claude", "settings.json") + one := `{"hooks":[{"type":"command","command":"echo twin"}]}` + write(t, path, `{"hooks":{"Stop":[`+one+`,`+one+`]}}`) + var before map[string]any + must(t, json.Unmarshal([]byte(`{"Stop":[`+one+`]}`), &before)) + nativeEdit(t, e.service, NativeEdit{Target: "claude", Before: before}) + if n := strings.Count(read(t, path), "echo twin"); n != 1 { + t.Fatalf("want one copy left, got %d:\n%s", n, read(t, path)) + } +} + +func TestNativeEdit_RestorePreviewNamesTheEvent(t *testing.T) { + e := newEnv(t) + write(t, filepath.Join(e.home, ".claude", "settings.json"), trialSettings) + stop := importOne(t, e.service, "claude", "claude-stop").Entry.Bindings["claude"].Events + r := nativeEdit(t, e.service, NativeEdit{Target: "claude", Before: stop}) + p, err := e.service.PreviewRestore(r.BackupIDs[0]) + must(t, err) + if len(p.Changes) != 1 || p.Changes[0].Name != "Stop" { + t.Fatalf("the restore must say which hook comes back: %+v", p.Changes) + } +} + +// A backup stays listed after it is restored, so restoring it again must not add the hook twice. +func TestNativeEdit_RestoringARemovalTwiceIsRefused(t *testing.T) { + e := newEnv(t) + path := filepath.Join(e.home, ".claude", "settings.json") + write(t, path, trialSettings) + stop := importOne(t, e.service, "claude", "claude-stop").Entry.Bindings["claude"].Events + r := nativeEdit(t, e.service, NativeEdit{Target: "claude", Before: stop}) + p, err := e.service.PreviewRestore(r.BackupIDs[0]) + must(t, err) + _, err = e.service.Restore(r.BackupIDs[0], p.Revision) + must(t, err) + again, err := e.service.PreviewRestore(r.BackupIDs[0]) + must(t, err) + if !again.Blocked { + t.Fatalf("a second restore must be refused: %+v", again.Changes) + } + if n := strings.Count(read(t, path), "afplay"); n != 1 { + t.Fatalf("want the hook once, got %d", n) + } +} + +// Removing one of two identical hooks leaves a copy behind; that copy is not a restored one. +func TestNativeEdit_RestoresARemovedTwinOnce(t *testing.T) { + e := newEnv(t) + path := filepath.Join(e.home, ".claude", "settings.json") + one := `{"hooks":[{"type":"command","command":"echo twin"}]}` + write(t, path, `{"hooks":{"Stop":[`+one+`,`+one+`]}}`) + var before map[string]any + must(t, json.Unmarshal([]byte(`{"Stop":[`+one+`]}`), &before)) + r := nativeEdit(t, e.service, NativeEdit{Target: "claude", Before: before}) + p, err := e.service.PreviewRestore(r.BackupIDs[0]) + must(t, err) + if p.Blocked { + t.Fatalf("the first restore must go through: %+v", p.Changes) + } + _, err = e.service.Restore(r.BackupIDs[0], p.Revision) + must(t, err) + if n := strings.Count(read(t, path), "echo twin"); n != 2 { + t.Fatalf("want both copies back, got %d", n) + } + again, err := e.service.PreviewRestore(r.BackupIDs[0]) + must(t, err) + if !again.Blocked { + t.Fatalf("a second restore must be refused: %+v", again.Changes) + } +} + +// Removing the first of two hooks is stored as an update and a removal; neither may run twice. +func TestNativeEdit_RestoringAShiftedRemovalTwiceIsRefused(t *testing.T) { + e := newEnv(t) + path := filepath.Join(e.home, ".claude", "settings.json") + a := `{"hooks":[{"type":"command","command":"echo first"}]}` + b := `{"hooks":[{"type":"command","command":"echo second"}]}` + write(t, path, `{"hooks":{"Stop":[`+a+`,`+b+`]}}`) + var before, after map[string]any + must(t, json.Unmarshal([]byte(`{"Stop":[`+a+`,`+b+`]}`), &before)) + must(t, json.Unmarshal([]byte(`{"Stop":[`+b+`]}`), &after)) + r := nativeEdit(t, e.service, NativeEdit{Target: "claude", Before: before, After: after}) + p, err := e.service.PreviewRestore(r.BackupIDs[0]) + must(t, err) + _, err = e.service.Restore(r.BackupIDs[0], p.Revision) + must(t, err) + again, err := e.service.PreviewRestore(r.BackupIDs[0]) + must(t, err) + if got := read(t, path); !again.Blocked || strings.Count(got, "echo first") != 1 || strings.Count(got, "echo second") != 1 { + t.Fatalf("want each hook once and a second restore refused: blocked=%v %s", again.Blocked, got) + } +} + +// Importing the restored hook makes it managed; the backup must still see it is back. +func TestNativeEdit_RestoringARemovalAfterImportingTheHookIsRefused(t *testing.T) { + e := newEnv(t) + write(t, filepath.Join(e.home, ".claude", "settings.json"), trialSettings) + stop := importOne(t, e.service, "claude", "claude-stop") + r := nativeEdit(t, e.service, NativeEdit{Target: "claude", Before: stop.Entry.Bindings["claude"].Events}) + p, err := e.service.PreviewRestore(r.BackupIDs[0]) + must(t, err) + _, err = e.service.Restore(r.BackupIDs[0], p.Revision) + must(t, err) + save(t, e.service, Mutation{Name: "stop", Entry: &stop.Entry, Adopt: true}) + again, err := e.service.PreviewRestore(r.BackupIDs[0]) + must(t, err) + if !again.Blocked { + t.Fatalf("a second restore must be refused: %+v", again.Changes) + } +} + +// A restore writes its own backup, and that one must be restorable too: undoing the undo. +func TestNativeEdit_RestoreCanBeUndoneWhenATwinSurvives(t *testing.T) { + e := newEnv(t) + path := filepath.Join(e.home, ".claude", "settings.json") + a := `{"hooks":[{"type":"command","command":"echo first"}]}` + b := `{"hooks":[{"type":"command","command":"echo second"}]}` + write(t, path, `{"hooks":{"Stop":[`+a+`,`+b+`]}}`) + var before, after map[string]any + must(t, json.Unmarshal([]byte(`{"Stop":[`+a+`]}`), &before)) + must(t, json.Unmarshal([]byte(`{"Stop":[`+b+`]}`), &after)) + r := nativeEdit(t, e.service, NativeEdit{Target: "claude", Before: before, After: after}) + p, err := e.service.PreviewRestore(r.BackupIDs[0]) + must(t, err) + restored, err := e.service.Restore(r.BackupIDs[0], p.Revision) + must(t, err) + undo, err := e.service.PreviewRestore(restored.BackupIDs[0]) + must(t, err) + if undo.Blocked { + t.Fatalf("the restore's own backup must restore: %+v", undo.Changes) + } + _, err = e.service.Restore(restored.BackupIDs[0], undo.Revision) + must(t, err) + if got := read(t, path); strings.Contains(got, "echo first") || strings.Count(got, "echo second") != 2 { + t.Fatalf("want the edit back: %s", got) + } +} diff --git a/internal/hooks/service.go b/internal/hooks/service.go index 8e8deb7d9..69894a12d 100644 --- a/internal/hooks/service.go +++ b/internal/hooks/service.go @@ -190,6 +190,8 @@ type Candidate struct { Entry Entry `json:"entry"` Problems []string `json:"problems"` Warnings []string `json:"warnings"` + // Editable marks unmanaged hooks a NativeEdit can change or remove in place. + Editable bool `json:"editable,omitempty"` } // ConfigDirsFromEnv reads the Agent directory overrides Agents themselves honor. diff --git a/internal/server/handler_hooks.go b/internal/server/handler_hooks.go index a396d3c53..33dc9a125 100644 --- a/internal/server/handler_hooks.go +++ b/internal/server/handler_hooks.go @@ -8,6 +8,7 @@ import ( "net/http" "os" "reflect" + "slices" "strings" "time" @@ -172,6 +173,58 @@ func (s *Server) handleHooksConfigure(w http.ResponseWriter, r *http.Request) { writeJSON(w, result) } +type hooksNativeRequest struct { + Edits []hooks.NativeEdit `json:"edits"` + Revision string `json:"revision"` +} + +// handleHooksNativePreview plans changes to hooks Skillshare does not manage. +func (s *Server) handleHooksNativePreview(w http.ResponseWriter, r *http.Request) { + var body hooksNativeRequest + if !decodeHooksRequest(w, r, &body) { + return + } + s.mu.RLock() + defer s.mu.RUnlock() + p, err := s.hooksService().PreviewNativeEdits(body.Edits) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + writeJSON(w, struct { + *hooks.Plan + Files []hooks.FileDiff `json:"files"` + }{p, p.Files()}) +} + +// handleHooksNativeApply writes previewed changes to hooks Skillshare does not manage. +func (s *Server) handleHooksNativeApply(w http.ResponseWriter, r *http.Request) { + var body hooksNativeRequest + if !decodeHooksRequest(w, r, &body) { + return + } + if body.Revision == "" { + writeError(w, http.StatusBadRequest, "preview the hooks changes before saving") + return + } + s.mu.Lock() + defer s.mu.Unlock() + start := time.Now() + result, err := s.hooksService().ApplyNativeEdits(body.Edits, body.Revision) + targets := []string{} + for _, e := range body.Edits { + if at := e.Target + "@" + e.Root; !slices.Contains(targets, strings.TrimSuffix(at, "@")) { + targets = append(targets, strings.TrimSuffix(at, "@")) + } + } + s.writeOpsLog("hooks edit-native", opStatus(err), start, map[string]any{"scope": "ui", "edits": len(body.Edits), "targets": strings.Join(targets, ", ")}, "") + if err != nil { + writeHooksFailure(w, result, err) + return + } + writeJSON(w, result) +} + func (s *Server) handleHooksImport(w http.ResponseWriter, r *http.Request) { var body hooks.ImportRequest if !decodeHooksRequest(w, r, &body) { @@ -246,7 +299,11 @@ func writeHooksFailure(w http.ResponseWriter, result *hooks.Result, err error) { } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusConflict) - _ = json.NewEncoder(w).Encode(map[string]any{"error": message, "result": result}) + body := map[string]any{"error": message, "result": result} + if partial { + body["error_params"] = map[string]any{"applied": result.Applied} + } + _ = json.NewEncoder(w).Encode(body) } // hooksAccounts are the global targets with their own native config homes. diff --git a/internal/server/handler_hooks_contract_test.go b/internal/server/handler_hooks_contract_test.go index 81b57c30e..628a241c0 100644 --- a/internal/server/handler_hooks_contract_test.go +++ b/internal/server/handler_hooks_contract_test.go @@ -379,3 +379,57 @@ func TestHooksUIContract_AccountTargets(t *testing.T) { t.Fatalf("%d %s", w.Code, w.Body) } } + +// HooksImportDialog editing a hook that was never imported: preview the edit, apply it +// with that revision. The hook changes in the target's file and stays unmanaged. +func TestHooksUIContract_EditUnmanagedHook(t *testing.T) { + for i, newScope := range hooksUIScopes { + t.Run(hooksUIScopeNames[i], func(t *testing.T) { + sc := newScope(t) + // A managed hook registers the scope and shares the file with the user's own hook. + sc.addAndSync(t, "guard", "echo contract-guard") + mine := `{"hooks":[{"type":"command","command":"echo mine"}]}` + var doc struct { + Hooks map[string]json.RawMessage `json:"hooks"` + } + if err := json.Unmarshal([]byte(readOrEmpty(sc.settings)), &doc); err != nil { + t.Fatal(err) + } + doc.Hooks["SessionEnd"] = json.RawMessage(`[` + mine + `]`) + own, err := json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(sc.settings, own, 0644); err != nil { + t.Fatal(err) + } + root := "" + if sc.project != "" { + root = `"root":"` + sc.project + `",` + } + edits := `[{"target":"claude",` + root + `"before":{"SessionEnd":[` + mine + `]},"after":{"SessionEnd":[` + strings.Replace(mine, "echo mine", "echo edited", 1) + `]}}]` + preview := hooksPost(sc.s, sc.s.handleHooksNativePreview, "/api/hooks/native/preview", `{"edits":`+edits+`}`) + var p struct { + Revision string `json:"revision"` + Files []struct { + After string `json:"after"` + } `json:"files"` + } + if preview.Code != http.StatusOK || json.Unmarshal(preview.Body.Bytes(), &p) != nil || len(p.Files) != 1 || !strings.Contains(p.Files[0].After, "echo edited") { + t.Fatalf("native preview: %d %s", preview.Code, preview.Body) + } + if w := hooksPost(sc.s, sc.s.handleHooksNativeApply, "/api/hooks/native", `{"edits":`+edits+`}`); w.Code != http.StatusBadRequest { + t.Fatalf("apply without a preview: %d %s", w.Code, w.Body) + } + if w := hooksPost(sc.s, sc.s.handleHooksNativeApply, "/api/hooks/native", `{"edits":`+edits+`,"revision":"`+p.Revision+`"}`); w.Code != http.StatusOK { + t.Fatalf("native apply: %d %s", w.Code, w.Body) + } + if got := readOrEmpty(sc.settings); !strings.Contains(got, "echo edited") || strings.Contains(got, "echo mine") || !strings.Contains(got, "echo contract-guard") { + t.Fatalf("edited file:\n%s", got) + } + if _, ok := sc.entries(t)["guard"]; !ok || len(sc.entries(t)) != 1 { + t.Fatalf("the edited hook must stay out of the source: %v", sc.entries(t)) + } + }) + } +} diff --git a/internal/server/handler_hooks_test.go b/internal/server/handler_hooks_test.go index 42edcf36a..6163af630 100644 --- a/internal/server/handler_hooks_test.go +++ b/internal/server/handler_hooks_test.go @@ -2,6 +2,7 @@ package server import ( "encoding/json" + "errors" "net/http" "net/http/httptest" "os" @@ -9,6 +10,7 @@ import ( "strings" "testing" + "skillshare/internal/hooks" "skillshare/internal/oplog" ) @@ -155,7 +157,7 @@ func TestHooksAPIImportListsCandidatesWithoutExecuting(t *testing.T) { 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/restore", "GET /api/hooks/catalog"} { + 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" @@ -418,3 +420,17 @@ func TestHooksAPIPreviewCarriesFileTexts(t *testing.T) { 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) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 9a033605b..dd701296e 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -654,6 +654,8 @@ func (s *Server) registerRoutes() { s.mux.HandleFunc("POST /api/hooks/preview", s.requireLocalHooks(s.handleHooksPreview)) s.mux.HandleFunc("POST /api/hooks/render", s.requireLocalHooks(s.handleHooksRender)) s.mux.HandleFunc("POST /api/hooks/import", s.requireLocalHooks(s.handleHooksImport)) + s.mux.HandleFunc("POST /api/hooks/native", s.requireLocalHooks(s.handleHooksNativeApply)) + s.mux.HandleFunc("POST /api/hooks/native/preview", s.requireLocalHooks(s.handleHooksNativePreview)) s.mux.HandleFunc("POST /api/hooks/restore", s.requireLocalHooks(s.handleHooksRestore)) s.mux.HandleFunc("GET /api/hooks/catalog", s.requireLocalHooks(s.handleHooksCatalog)) s.mux.HandleFunc("GET /api/extras", s.handleExtras) diff --git a/ui/src/api/hooks.ts b/ui/src/api/hooks.ts index 051a405cc..ab8e87dcc 100644 --- a/ui/src/api/hooks.ts +++ b/ui/src/api/hooks.ts @@ -58,7 +58,10 @@ export interface HookTargetDef { name: string; agent?: string; kind: string; not /** Hooks in an Agent's native configuration that Skillshare does not manage. */ export interface HookUnmanaged { target: string; path: string; names: string[]; project?: string } export interface HookBackup { id: string; target: string; path: string; root?: string; time?: string } -export interface HookCandidate { name: string; entry: HookEntry; problems: string[]; warnings: string[] } +/** `editable`: the hook can be changed or removed in its target file without importing it. */ +export interface HookCandidate { name: string; entry: HookEntry; problems: string[]; warnings: string[]; editable?: boolean } +/** A change to hooks Skillshare does not manage: `before` as the import listed them, `after` their replacement (left out removes them). */ +export interface HookNativeEdit { target: string; root?: string; before: Record; after?: Record } export interface HookImportRequest { from: string; content?: string; name?: string; /** Reads the Agent's file under this hooks.projects root. */ root?: string } /** One root under hooks.projects: hooks that live in that folder's own native files. */ export interface HookProject { entries?: Record } @@ -105,6 +108,10 @@ export const hooksApi = { const res = await post<{ candidates: HookCandidate[] } | HookCandidate[]>('/hooks/import', body); return Array.isArray(res) ? res : res.candidates ?? []; }, + /** What editing or removing unmanaged hooks would write to their target files. Writes nothing. */ + previewNative: (edits: HookNativeEdit[]) => post('/hooks/native/preview', { edits }), + /** Writes previewed edits, with a backup per file. The hooks stay unmanaged. */ + applyNative: (edits: HookNativeEdit[], revision: string) => post('/hooks/native', { edits, revision }), previewRestore: (backupId: string) => post('/hooks/restore', { backupId, preview: true }), restore: (backupId: string, revision: string) => post('/hooks/restore', { backupId, revision }), }; diff --git a/ui/src/components/hooks/HookBindingEditor.tsx b/ui/src/components/hooks/HookBindingEditor.tsx index 022977168..d371f6608 100644 --- a/ui/src/components/hooks/HookBindingEditor.tsx +++ b/ui/src/components/hooks/HookBindingEditor.tsx @@ -1,10 +1,14 @@ import { useMemo, useRef, useState } from 'react'; import type { ReactNode } from 'react'; +import { createPortal } from 'react-dom'; import type { CompletionSource } from '@codemirror/autocomplete'; import type { Diagnostic } from '@codemirror/lint'; -import { AlertCircle, Maximize2, Minimize2, Plus, SquareTerminal, WandSparkles, X } from 'lucide-react'; +import { AlertCircle, ChevronDown, Maximize2, Minimize2, Plus, SquareTerminal, Trash2, WandSparkles, X } from 'lucide-react'; import { useT } from '../../i18n'; import CodeEditor from '../CodeEditor'; +import IconButton from '../IconButton'; +import Reveal from '../Reveal'; +import SegmentedControl from '../SegmentedControl'; import { Select } from '../Select'; import { eventSuggestions, hookLabel, isCodeAgent, newFileRow, newRow, parseNative, rowBlank, rowProblems, rowShape, switchMode, eventsToRows, @@ -15,6 +19,7 @@ import { } from './hookCatalog'; import type { HookCatalog, HookDiagnostic } from './hookCatalog'; import { dialogGhost } from '../../lib/exitGhost'; +import { commandSummary, formatCommand } from './hooksImport'; interface Props { agent: string; @@ -24,6 +29,10 @@ interface Props { onChange: (draft: BindingDraft) => void; disabled: boolean; catalog?: HookCatalog; + /** One collapsible card per command with a multi-line command editor, and no script files: for a hook edited in its target file. */ + cards?: boolean; + /** With `cards`: where the fields / native JSON switch is rendered, outside the editor's own body. */ + tabsHost?: HTMLElement | null; } type T = ReturnType; @@ -56,13 +65,30 @@ function useCompletions(agent: string, catalog: HookCatalog | undefined): Comple }, [agent, catalog, t]); } +type Row = BindingDraft['rows'][number]; + +/** What the event, matcher and timeout fields of a row offer for one target. */ +function useRowFields(agent: string, catalog: HookCatalog | undefined) { + const t = useT(); + const documented = catalog?.[agent]?.events ?? eventSuggestions(agent).map((name) => ({ name, description: '', matcher: true })); + return { + unit: t(timeoutUnit(catalog, agent) === 'milliseconds' ? 'hooks.unit.milliseconds' : 'hooks.unit.seconds'), + options: (r: Row) => [ + ...(r.event && !documented.some((e) => e.name === r.event) ? [{ value: r.event, label: r.event, description: t('hooks.eventUndocumented') }] : []), + ...documented.map((e) => ({ value: e.name, label: e.name, description: eventDescription(t, e.name, e.description), badge: e.matcher ? t('hooks.matcherBadge') : undefined, group: t('hooks.eventsOf', { agent: hookLabel(agent) }) })), + ], + hasMatcher: (r: Row) => r.shape === 'group' && (r.event ? eventHasMatcher(catalog, agent, r.event) || Boolean(r.matcher) : true), + pickEvent: (r: Row, event: string): Partial => ({ event, shape: agent === 'antigravity' ? rowShape(agent, event) : r.shape, ...(!eventHasMatcher(catalog, agent, event) && { matcher: '' }) }), + }; +} + /** Event, matcher, command and timeout as plain fields. Everything else in the native entry is carried along untouched. */ function SimpleEvents({ agent, draft, onChange, disabled, catalog }: Pick) { const t = useT(); const commands = useRef>({}); - const patch = (id: string, change: Partial) => onChange({ ...draft, rows: draft.rows.map((r) => (r.id === id ? { ...r, ...change } : r)) }); - const documented = catalog?.[agent]?.events ?? eventSuggestions(agent).map((name) => ({ name, description: '', matcher: true })); - const unit = t(timeoutUnit(catalog, agent) === 'milliseconds' ? 'hooks.unit.milliseconds' : 'hooks.unit.seconds'); + const patch = (id: string, change: Partial) => onChange({ ...draft, rows: draft.rows.map((r) => (r.id === id ? { ...r, ...change } : r)) }); + const fields = useRowFields(agent, catalog); + const unit = fields.unit; const variables = commandVariables(agent); const insert = (id: string, command: string, text: string) => { const input = commands.current[id]; @@ -75,11 +101,8 @@ function SimpleEvents({ agent, draft, onChange, disabled, catalog }: Pick { const problems = rowProblems(r); const shown = (key: 'event' | 'command' | 'timeout') => !rowBlank(r) && problems[key]; - const options = [ - ...(r.event && !documented.some((e) => e.name === r.event) ? [{ value: r.event, label: r.event, description: t('hooks.eventUndocumented') }] : []), - ...documented.map((e) => ({ value: e.name, label: e.name, description: eventDescription(t, e.name, e.description), badge: e.matcher ? t('hooks.matcherBadge') : undefined, group: t('hooks.eventsOf', { agent: hookLabel(agent) }) })), - ]; - const matcher = r.shape === 'group' && (r.event ? eventHasMatcher(catalog, agent, r.event) || Boolean(r.matcher) : true); + const options = fields.options(r); + const matcher = fields.hasMatcher(r); return (
@@ -93,7 +116,7 @@ function SimpleEvents({ agent, draft, onChange, disabled, catalog }: Pick patch(r.id, { event, shape: agent === 'antigravity' ? rowShape(agent, event) : r.shape, ...(!eventHasMatcher(catalog, agent, event) && { matcher: '' }) })} + onChange={(event) => patch(r.id, fields.pickEvent(r, event))} />
{matcher && ( @@ -136,6 +159,98 @@ function SimpleEvents({ agent, draft, onChange, disabled, catalog }: Pick) { + const t = useT(); + const [open, setOpen] = useState(draft.rows[0]?.id ?? ''); + const patch = (id: string, change: Partial) => onChange({ ...draft, rows: draft.rows.map((r) => (r.id === id ? { ...r, ...change } : r)) }); + const fields = useRowFields(agent, catalog); + const variables = commandVariables(agent); + const add = () => { + const row = newRow(agent, draft.rows[draft.rows.length - 1]?.event); + onChange({ ...draft, rows: [...draft.rows, row] }); + setOpen(row.id); + }; + return ( +
+ {draft.rows.map((r, i) => { + const problems = rowProblems(r); + const shown = (key: 'event' | 'command' | 'timeout') => !rowBlank(r) && problems[key]; + const on = open === r.id; + const title = t('hooks.commandN', { n: String(i + 1) }); + return ( +
+
+ + } label={`${t('hooks.removeRow')} ${i + 1}`} onClick={() => onChange({ ...draft, rows: draft.rows.filter((x) => x.id !== r.id) })} disabled={disabled} /> +
+ +
+
+
+ {t('hooks.event')} + patch(r.id, { matcher: e.target.value })} placeholder={t('hooks.matcherPlaceholder')} aria-label={`${t('hooks.matcher')} ${i + 1}`} disabled={disabled} /> + +
+ )} +
+ {t('hooks.timeout')} + + patch(r.id, { timeout: e.target.value })} aria-label={`${t('hooks.timeout')} ${i + 1}`} disabled={disabled} /> + {fields.unit} + +
+
+ ( + <> + {!expanded && {t('hooks.command')}} + + {variables.length > 0 && t('hooks.insertVariable')} + {variables.map((v) => )} + + + + )} + > + {(expanded) => ( + <> + patch(r.id, { command })} ariaLabel={`${t('hooks.command')} ${i + 1}`} placeholder={commandPlaceholder(agent)} disabled={disabled} wrap minHeight="88px" maxHeight="260px" fill={expanded} className={`${expanded ? 'min-h-0 flex-1' : ''} ${shown('command') ? '!border-bad' : '!border-transparent'}`} /> + {t('hooks.commandHint')} + + )} + +
+
+
+ ); + })} +
+ +
+
+ ); +} + function ScriptFiles({ name, draft, onChange, disabled }: Pick) { const t = useT(); const patch = (id: string, change: Partial) => onChange({ ...draft, files: draft.files.map((f) => (f.id === id ? { ...f, ...change } : f)) }); @@ -202,7 +317,7 @@ function Expandable({ title, tools, children }: { title: string; tools: (expande } /** One target's part of a hook: command targets edit events, code targets edit their native extension. */ -export default function HookBindingEditor({ agent, name, draft, check, onChange, disabled, catalog }: Props) { +export default function HookBindingEditor({ agent, name, draft, check, onChange, disabled, catalog, cards = false, tabsHost }: Props) { const t = useT(); const lint = useNativeLint(agent, catalog); const completions = useCompletions(agent, catalog); @@ -251,14 +366,19 @@ export default function HookBindingEditor({ agent, name, draft, check, onChange, onChange(switchMode(draft, mode)); }; return ( -
-
- - -
+
+ {cards ? tabsHost && createPortal( + 0 && { count: errors.length }) }]} />, + tabsHost, + ) : ( +
+ + +
+ )} {native && stuck &&
{stuck}
} {native ? ( )} - ) : } - + ) : cards ? : } + {!cards && }
); } diff --git a/ui/src/components/hooks/HookDialog.test.tsx b/ui/src/components/hooks/HookDialog.test.tsx index 967773c0d..feb8ef97d 100644 --- a/ui/src/components/hooks/HookDialog.test.tsx +++ b/ui/src/components/hooks/HookDialog.test.tsx @@ -5,6 +5,7 @@ import { MemoryRouter } from 'react-router-dom'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { I18nProvider } from '../../i18n'; import { hooksApi } from '../../api/hooks'; +import { ApiError } from '../../api/http'; import type { HookCandidate, HookInventory } from '../../api/hooks'; import HookDialog from './HookDialog'; import HooksImportDialog from './HooksImportDialog'; @@ -15,7 +16,7 @@ vi.mock('../CodeEditor', () => ({ })); vi.mock('../../api/hooks', async (load) => ({ ...await load(), - hooksApi: { catalog: vi.fn(), preview: vi.fn(), save: vi.fn(), configure: vi.fn(), import: vi.fn() }, + hooksApi: { catalog: vi.fn(), preview: vi.fn(), save: vi.fn(), configure: vi.fn(), import: vi.fn(), previewNative: vi.fn(), applyNative: vi.fn() }, })); const catalog = { claude: { timeoutUnit: 'seconds' as const, events: [ @@ -92,13 +93,13 @@ describe('hooks import', () => { vi.mocked(hooksApi.import).mockResolvedValue([candidate('notify', './notify.sh'), candidate('format', './format.sh')]); vi.mocked(hooksApi.save).mockResolvedValue({ applied: [], backupIds: [] }); const onImported = vi.fn(); - wrap(); + wrap(); const group = await screen.findByRole('region', { name: 'Claude' }); expect(within(group).getByTitle('/home/u/.claude/settings.json')).toBeInTheDocument(); - await user.click(within(group).getByRole('checkbox', { name: 'format' })); - expect(screen.getByText('1 selected')).toBeInTheDocument(); + await user.click(await within(group).findByRole('checkbox', { name: 'Import format' })); + expect(screen.getByText('1 selected, from 1 target')).toBeInTheDocument(); await user.click(screen.getByRole('button', { name: 'Import 1' })); - await waitFor(() => expect(onImported).toHaveBeenCalledWith(1)); + await waitFor(() => expect(onImported).toHaveBeenCalledWith(1, 0)); expect(hooksApi.import).toHaveBeenCalledWith({ from: 'claude' }); expect(hooksApi.save).toHaveBeenCalledTimes(1); expect(hooksApi.save).toHaveBeenCalledWith(expect.objectContaining({ entry: candidate('notify', './notify.sh').entry, adopt: true })); @@ -110,13 +111,116 @@ describe('hooks import', () => { vi.mocked(hooksApi.import).mockResolvedValue([block]); vi.mocked(hooksApi.save).mockResolvedValue({ applied: [], backupIds: [] }); const agy = { ...data, paths: { antigravity: '/home/u/.gemini/config/hooks.json' }, unmanaged: [{ target: 'antigravity', path: '/home/u/.gemini/config/hooks.json', names: ['lint'] }] } as unknown as HookInventory; - wrap(); - const name = await screen.findByRole('textbox', { name: 'Name for lint' }); + wrap(); + await user.click(await screen.findByRole('button', { expanded: false })); + const name = screen.getByRole('textbox', { name: 'Name for lint' }); expect(name).toHaveValue('lint'); expect(name).toBeDisabled(); await user.click(screen.getByRole('button', { name: 'Import 1' })); await waitFor(() => expect(hooksApi.save).toHaveBeenCalledWith(expect.objectContaining({ name: 'lint', adopt: true }))); }); + + const editable = (name: string, command: string): HookCandidate => ({ ...candidate(name, command), editable: true }); + const nativePlan = { revision: 'r1', fingerprint: 'r1', sourcePath: '/s.yaml', blocked: false, changes: [], files: [] }; + + it('writes a removal only after the review, and before importing the rest', async () => { + const user = userEvent.setup(); + vi.mocked(hooksApi.import).mockResolvedValue([editable('notify', './notify.sh'), editable('format', './format.sh')]); + vi.mocked(hooksApi.previewNative).mockResolvedValue(nativePlan); + vi.mocked(hooksApi.applyNative).mockResolvedValue({ applied: [], backupIds: [] }); + vi.mocked(hooksApi.save).mockResolvedValue({ applied: [], backupIds: [] }); + const onImported = vi.fn(); + wrap(); + await user.click(await screen.findByRole('button', { name: 'Remove notify from the target' })); + expect(screen.getByRole('checkbox', { name: 'Import notify' })).toBeDisabled(); + expect(screen.queryByRole('button', { name: /^Import \d/ })).not.toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Review changes' })); + const edits = [{ target: 'claude', before: editable('notify', './notify.sh').entry.bindings.claude.events }]; + await waitFor(() => expect(hooksApi.previewNative).toHaveBeenCalledWith(edits)); + expect(hooksApi.applyNative).not.toHaveBeenCalled(); + expect(hooksApi.save).not.toHaveBeenCalled(); + await user.click(await screen.findByRole('button', { name: 'Apply changes' })); + await waitFor(() => expect(onImported).toHaveBeenCalledWith(1, 1)); + expect(hooksApi.applyNative).toHaveBeenCalledWith(edits, 'r1'); + expect(hooksApi.save).toHaveBeenCalledTimes(1); + expect(hooksApi.save).toHaveBeenCalledWith(expect.objectContaining({ entry: candidate('format', './format.sh').entry, adopt: true })); + expect(vi.mocked(hooksApi.applyNative).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(hooksApi.save).mock.invocationCallOrder[0]); + }); + + it('sends an edited hook as it was read and as edited, and leaves an untouched one alone', async () => { + const user = userEvent.setup(); + vi.mocked(hooksApi.catalog).mockResolvedValue(catalog); + vi.mocked(hooksApi.import).mockResolvedValue([editable('notify', './notify.sh')]); + vi.mocked(hooksApi.previewNative).mockResolvedValue(nativePlan); + wrap(); + await user.click(await screen.findByRole('button', { name: 'Edit notify' })); + await user.click(screen.getByRole('button', { name: 'Done' })); + expect(screen.getByRole('button', { name: 'Import 1' })).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Edit notify' })); + await user.type(screen.getByLabelText('Command 1'), ' --fast'); + await user.click(screen.getByRole('button', { name: 'Done' })); + await user.click(screen.getByRole('button', { name: 'Review changes' })); + await waitFor(() => expect(hooksApi.previewNative).toHaveBeenCalledWith([{ + target: 'claude', + before: { Stop: [{ hooks: [{ type: 'command', command: './notify.sh' }] }] }, + after: { Stop: [{ hooks: [{ type: 'command', command: './notify.sh --fast' }] }] }, + }])); + }); + + it('after a write went through and an import failed, sends neither the change nor that hook again', async () => { + const user = userEvent.setup(); + vi.mocked(hooksApi.catalog).mockResolvedValue(catalog); + vi.mocked(hooksApi.import) + .mockResolvedValueOnce([editable('notify', './notify.sh'), editable('format', './format.sh')]) + // Read again, the edit may sit under other rows than the one it was made in: an edit can move a + // command to another event, and candidates are listed per event. + .mockResolvedValue([editable('notify', './notify.sh'), editable('moved', './notify.sh --fast'), editable('format', './format.sh')]); + vi.mocked(hooksApi.previewNative).mockResolvedValue(nativePlan); + vi.mocked(hooksApi.applyNative).mockResolvedValue({ applied: [], backupIds: [] }); + vi.mocked(hooksApi.save).mockRejectedValueOnce(new Error('name taken')).mockResolvedValue({ applied: [], backupIds: [] }); + const onChanged = vi.fn(); + const onImported = vi.fn(); + wrap(); + await user.click(await screen.findByRole('button', { name: 'Edit notify' })); + await user.type(screen.getByLabelText('Command 1'), ' --fast'); + await user.click(screen.getByRole('button', { name: 'Done' })); + await user.click(screen.getByRole('button', { name: 'Review changes' })); + await user.click(await screen.findByRole('button', { name: 'Apply changes' })); + expect(await screen.findByRole('alert')).toHaveTextContent('name taken'); + expect(onChanged).toHaveBeenCalled(); + // The file now holds the edit, so nothing is pending, and neither the edited hook nor a row the edit + // produced is picked up as an import. + await screen.findByRole('checkbox', { name: 'Import moved' }); + expect(screen.queryByRole('button', { name: 'Review changes' })).not.toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Import 1' })); + await waitFor(() => expect(onImported).toHaveBeenCalledWith(1, 0)); + expect(hooksApi.applyNative).toHaveBeenCalledTimes(1); + expect(hooksApi.save).toHaveBeenLastCalledWith(expect.objectContaining({ entry: candidate('format', './format.sh').entry })); + }); + + it('keeps the changes of a file a failed write did not reach', async () => { + const user = userEvent.setup(); + const geminiPath = '/home/u/.gemini/settings.json'; + const both = { ...data, paths: { ...data.paths, gemini: geminiPath }, unmanaged: [...data.unmanaged, { target: 'gemini', path: geminiPath, names: ['cleanup'] }] } as unknown as HookInventory; + const cleanup: HookCandidate = { name: 'cleanup', problems: [], warnings: [], editable: true, entry: { bindings: { gemini: { events: { SessionEnd: [{ hooks: [{ type: 'command', command: './cleanup.sh' }] }] } } } } }; + let written = false; + vi.mocked(hooksApi.catalog).mockResolvedValue(catalog); + vi.mocked(hooksApi.import).mockImplementation(async ({ from }) => (from === 'gemini' ? [cleanup] : written ? [] : [editable('notify', './notify.sh')])); + vi.mocked(hooksApi.previewNative).mockResolvedValue(nativePlan); + vi.mocked(hooksApi.applyNative).mockImplementation(async () => { + written = true; + throw new ApiError(409, 'permission denied; already applied: /home/u/.claude/settings.json; backup IDs: b1', { params: { applied: ['/home/u/.claude/settings.json'] } }); + }); + wrap(); + await user.click(await screen.findByRole('button', { name: 'Remove notify from the target' })); + await user.click(screen.getByRole('button', { name: /Gemini/ })); + await user.click(await screen.findByRole('button', { name: 'Remove cleanup from the target' })); + await user.click(screen.getByRole('button', { name: 'Review changes' })); + await user.click(await screen.findByRole('button', { name: 'Apply changes' })); + expect(await screen.findByRole('alert')).toHaveTextContent('permission denied'); + await user.click(await screen.findByRole('button', { name: 'Review changes' })); + await waitFor(() => expect(hooksApi.previewNative).toHaveBeenLastCalledWith([{ target: 'gemini', before: cleanup.entry.bindings.gemini.events }])); + }); }); describe('hooks remove', () => { diff --git a/ui/src/components/hooks/HooksImportDialog.tsx b/ui/src/components/hooks/HooksImportDialog.tsx index 7f55d936d..65a27d36e 100644 --- a/ui/src/components/hooks/HooksImportDialog.tsx +++ b/ui/src/components/hooks/HooksImportDialog.tsx @@ -1,9 +1,10 @@ import { useState } from 'react'; import { useQueries } from '@tanstack/react-query'; -import { Download, Plus, TriangleAlert, X } from 'lucide-react'; +import { Download, Pencil, Plus, Trash2, TriangleAlert, X } from 'lucide-react'; import { hookAgents, hooksApi } from '../../api/hooks'; -import type { HookCandidate, HookInventory } from '../../api/hooks'; -import { useT } from '../../i18n'; +import { ApiError } from '../../api/http'; +import type { HookCandidate, HookInventory, HookPreview } from '../../api/hooks'; +import { plural, useT } from '../../i18n'; import { shortenHome } from '../../lib/paths'; import { queryKeys } from '../../lib/queryKeys'; import AgentIcon from '../AgentIcon'; @@ -14,28 +15,34 @@ import DialogShell from '../DialogShell'; import { Select } from '../Input'; import Spinner from '../Spinner'; import { bindingLines, suggestName } from './hookCatalog'; -import { HOOK_NAME, hookAccounts, agentOfKey, keyLabel, hookMessage, isCodeAgent, scopeEntries, scopePaths, scopeUnmanaged } from './hooksView'; +import HooksImportEditor from './HooksImportEditor'; +import HooksImportRow from './HooksImportRow'; +import { nativeEdits, rowEvents, rowTitle, sameEvents } from './hooksImport'; +import type { ImportRow, NativeChange } from './hooksImport'; +import HooksPreview from './HooksPreview'; +import { HOOK_NAME, hookAccounts, agentOfKey, keyLabel, isCodeAgent, scopeEntries, scopePaths, scopeUnmanaged } from './hooksView'; interface Props { data: HookInventory; /** A root under hooks.projects: read that folder's target files and save into that project. */ project?: string; onClose: () => void; - onImported: (count: number) => void; + /** How many hooks were imported, and how many were changed or removed in their target files instead. */ + onImported: (count: number, changed: number) => void; + /** A save failed after it may have written something: what the page shows is out of date. */ + onChanged: () => void; } -/** A candidate as the dialog shows it: where it was read from and whether saving takes over its native registrations. */ -interface Row { id: string; target: string; candidate: HookCandidate; adopt: boolean } - -// Said once in the dialog's subtitle rather than on every row. -const ADOPT_WARNING = 'saving the import takes over the existing registrations in place; sync leaves them as they are instead of adding duplicates'; +const PASTE = 'paste'; /** - * Reads the hooks each target has that Skillshare does not manage yet, or pasted text, and saves the - * checked ones into the source, one hook each. Reading never executes anything; a read candidate is - * saved as the owner of the registrations it came from, so sync does not write them twice. + * Reads the hooks each target has that Skillshare does not manage yet, or pasted text, one target at a + * time. Checked hooks are saved into the source, one hook each, as the owner of the registrations they + * came from. A hook can also be edited or removed in its target file without importing it: that stays a + * pending change until the review step, which shows the file diff and writes on confirmation. + * Reading never executes anything. */ -export default function HooksImportDialog({ data, project, onClose, onImported }: Props) { +export default function HooksImportDialog({ data, project, onClose, onImported, onChanged }: Props) { const t = useT(); const existing = scopeEntries(data, project); const paths = scopePaths(data, project); @@ -53,20 +60,27 @@ export default function HooksImportDialog({ data, project, onClose, onImported } retry: false, })), }); - const [pasting, setPasting] = useState(targets.length === 0); + const [picked, setPicked] = useState(targets[0] ?? PASTE); const [pasteFrom, setPasteFrom] = useState(hookAgents[0]); const [content, setContent] = useState(''); const [pasted, setPasted] = useState(null); const [reading, setReading] = useState(false); const [names, setNames] = useState>({}); const [unchecked, setUnchecked] = useState([]); + const [opened, setOpened] = useState(''); + const [changes, setChanges] = useState>({}); + // Per target, the only rows still picked for import after a write to its file went through. + const [kept, setKept] = useState>({}); + const [editing, setEditing] = useState(''); + const [footerHost, setFooterHost] = useState(null); + const [plan, setPlan] = useState(null); const [saving, setSaving] = useState(false); const [error, setError] = useState(''); const busy = saving || reading; - const rows: Row[] = [ + const rows: ImportRow[] = [ ...targets.flatMap((target, i) => (reads[i].data ?? []).map((candidate) => ({ id: `${target}:${candidate.name}`, target, candidate, adopt: true }))), - ...(pasted ?? []).map((candidate) => ({ id: `paste:${candidate.name}`, target: pasteFrom, candidate, adopt: false })), + ...(pasted ?? []).map((candidate) => ({ id: `${PASTE}:${candidate.name}`, target: pasteFrom, candidate, adopt: false })), ]; // Prefilled names never repeat a saved hook or each other. const defaults: Record = {}; @@ -76,18 +90,34 @@ export default function HooksImportDialog({ data, project, onClose, onImported } defaults[row.id] = suggestName(row.candidate.name, isCodeAgent(agentOf(row.target)) ? '' : line?.command ?? '', taken); } // An Antigravity hook is the block of that name, so taking one over keeps the block's name. - const fixedName = (row: Row) => row.adopt && row.target === 'antigravity'; - const nameOf = (row: Row) => (fixedName(row) ? row.candidate.name : names[row.id] ?? defaults[row.id]); - const nameError = (row: Row) => { + const fixedName = (row: ImportRow) => row.adopt && row.target === 'antigravity'; + const nameOf = (row: ImportRow) => (fixedName(row) ? row.candidate.name : names[row.id] ?? defaults[row.id]); + const nameError = (row: ImportRow) => { const name = nameOf(row).trim(); if (!HOOK_NAME.test(name)) return t('hooks.nameHint'); if (name in existing || rows.some((r) => r.id !== row.id && checked(r) && nameOf(r).trim() === name)) return t('mcp.nameTaken'); return ''; }; - const importable = (row: Row) => row.candidate.problems.length === 0; - const checked = (row: Row) => importable(row) && !unchecked.includes(row.id); + const importable = (row: ImportRow) => row.candidate.problems.length === 0; + // A change counts while the target still differs from it: once a write went through and the hook was + // read again, an edit equals what is there and a removed hook has no row. + const changeOf = (row: ImportRow): NativeChange | undefined => { + const change = changes[row.id]; + return change && ('remove' in change || !sameEvents(change.events, rowEvents(row))) ? change : undefined; + }; + // A hook with a pending edit or removal is written to its target file as it is, not imported in the same pass. + const checked = (row: ImportRow) => importable(row) && !changeOf(row) && !unchecked.includes(row.id) && (!row.adopt || !kept[row.target] || kept[row.target].includes(row.id)); + const check = (ids: string[], on: boolean) => { + setUnchecked((prev) => (on ? prev.filter((x) => !ids.includes(x)) : [...new Set([...prev, ...ids])])); + if (on) setKept((prev) => Object.fromEntries(Object.entries(prev).map(([target, list]) => [target, [...list, ...rows.filter((r) => r.target === target && ids.includes(r.id)).map((r) => r.id)]]))); + }; const chosen = rows.filter(checked); const blocked = chosen.some((r) => nameError(r)); + const changed = rows.filter(changeOf); + const edits = nativeEdits(changed.map((r) => ({ target: r.target, root: project, before: rowEvents(r), change: changeOf(r)! }))); + // The hook being edited, while its target still has it. + const row = rows.find((r) => r.id === editing); + const undo = (id: string) => setChanges((prev) => Object.fromEntries(Object.entries(prev).filter(([key]) => key !== id))); const read = async () => { setReading(true); @@ -101,69 +131,161 @@ export default function HooksImportDialog({ data, project, onClose, onImported } } }; - const save = async () => { + const review = async () => { setSaving(true); setError(''); try { - // One at a time: each save previews and sends its own revision, so a parallel batch would be refused. - for (const row of chosen) { - await hooksApi.save({ ...(project && { project }), name: nameOf(row).trim(), entry: row.candidate.entry, ...(row.adopt && { adopt: true }) }); - } - onImported(chosen.length); + setPlan(await hooksApi.previewNative(edits)); } catch (e) { setError((e as Error).message); + // Usually a target file that changed since it was read: read again so the next review can pass. + for (const r of reads) void r.refetch(); + } finally { setSaving(false); } }; - const group = (key: string, target: string, path: string | undefined, list: Row[]) => ( -
-
- - {labelOf(target)} - {path && {shortenHome(path)}} -
- {list.map((row) => { - const lines = bindingLines(row.candidate.entry.bindings[row.target]); - const notes = [ - ...row.candidate.problems.map((message) => ({ message, problem: true })), - ...row.candidate.warnings.filter((w) => w !== ADOPT_WARNING).map((message) => ({ message, problem: false })), - ]; - const error = checked(row) ? nameError(row) : ''; - return ( -
- setUnchecked((prev) => (on ? prev.filter((x) => x !== row.id) : [...prev, row.id]))} /> - - {lines.length > 0 ? lines.map((l, i) => ( - - {l.event}{l.matcher && ` · ${l.matcher}`} - → - {l.command} - - )) : {row.candidate.name}} - {notes.map(({ message, problem }) => {hookMessage(t, message)})} - - - - {t('hooks.name')} - - setNames((prev) => ({ ...prev, [row.id]: e.target.value }))} aria-label={t('hooks.importNameFor', { name: row.candidate.name })} disabled={!checked(row) || busy || fixedName(row)} /> - - - {error && {error}} - -
- ); - })} -
- ); + const save = async () => { + setSaving(true); + setError(''); + let written = false; + try { + // The target files first: an import changes ownership, which would outdate the revision just reviewed. + if (plan) { + await hooksApi.applyNative(edits, plan.revision); + written = true; + } + // One at a time: each save previews and sends its own revision, so a parallel batch would be refused. + for (const row of chosen) { + await hooksApi.save({ ...(project && { project }), name: nameOf(row).trim(), entry: row.candidate.entry, ...(row.adopt && { adopt: true }) }); + } + onImported(chosen.length, edits.length); + } catch (e) { + setError((e as Error).message); + setSaving(false); + setPlan(null); + // A write that failed after its first file names the files it already wrote. + const applied = !written && plan && e instanceof ApiError && Array.isArray(e.params?.applied) ? e.params.applied as string[] : []; + const done = changed.filter((r) => written || applied.includes(paths[r.target] ?? '')); + if (done.length > 0) { + // Those files hold their changes now, so none of them is sent again; a file the write did not reach + // keeps its changes pending. Read again, a change may show up as other rows than it was made in (an + // edit can move a command to another event), so in the targets written only what was picked before + // stays picked: a hook changed in place was not meant to be imported. + const frozen = Object.fromEntries([...new Set(done.map((r) => r.target))].map((target) => [target, chosen.filter((r) => r.target === target).map((r) => r.id)])); + setKept((prev) => ({ ...prev, ...frozen })); + setChanges((prev) => Object.fromEntries(Object.entries(prev).filter(([id]) => !done.some((r) => r.id === id)))); + } + // Otherwise nothing is known to be written; changeOf drops any change the files turn out to hold. + for (const r of reads) void r.refetch(); + onChanged(); + } + }; - const loading = reads.some((r) => r.isPending); - const failed = reads.map((r, i) => r.error && `${labelOf(targets[i])}: ${(r.error as Error).message}`).filter(Boolean); - const found = rows.filter((r) => r.adopt); + const failure = error &&
{error}
; + + if (plan) { + const title = t('hooks.importReview'); + const removed = changed.filter((r) => 'remove' in changeOf(r)!); + const edited = changed.filter((r) => 'events' in changeOf(r)!); + const tile = 'grid h-[26px] w-[26px] shrink-0 place-items-center rounded-sm'; + const hooksOf = (list: ImportRow[]) => list.map((r) => ( + {rowTitle(r)} + )); + const sep = t('hooks.importSum.listSep'); + const labels = (list: string[]) => [...new Set(list)].map(labelOf).join(sep); + const counts = [...new Set(chosen.map((r) => r.target))].map((target) => t('hooks.importSum.count', { target: labelOf(target), count: String(chosen.filter((r) => r.target === target).length) })).join(sep); + const wrote = new Set(changed.map((r) => r.target)); + const others = labels(targets.filter((target) => !wrote.has(target))); + const backupNote = t(plural('hooks.importBackupNote', plan.files?.length ?? wrote.size)); + return ( + +
+
+

{title}

+

{t('hooks.importReviewHint')}

+
+ +
+
+
+ {chosen.length > 0 && ( +
+ + + {t('hooks.importSum.import', { count: String(chosen.length) })} + {t('hooks.importSum.importHint', { list: counts })} + +
+ )} + {edited.length > 0 && ( +
+ + + {t('hooks.importSum.edit', { count: String(edited.length) })} + {hooksOf(edited)} + +
+ )} + {removed.length > 0 && ( +
+ + + {t('hooks.importSum.remove', { count: String(removed.length) })} + {hooksOf(removed)}{t('hooks.importSum.removeHint', { target: labels(removed.map((r) => r.target)) })} + +
+ )} +
+
+

{t('hooks.importFiles')}

+ +

{backupNote}{others && `${/[.!?]$/.test(backupNote) ? ' ' : ''}${t('hooks.importBackupOthers', { targets: others })}`}

+
+ {failure} +
+
+ + +
+
+ ); + } + + const list = (shown: ImportRow[]) => shown.map((row) => { + const editable = row.candidate.editable; + return ( + check([row.id], on)} + onToggle={() => setOpened((prev) => (prev === row.id ? '' : row.id))} + onName={(name) => setNames((prev) => ({ ...prev, [row.id]: name }))} + onEdit={editable ? () => setEditing(row.id) : undefined} + onRemove={editable ? () => setChanges((prev) => ({ ...prev, [row.id]: { remove: true } })) : undefined} + onUndo={() => undo(row.id)} + /> + ); + }); + + const pending = changed.length; + const sources = new Set(chosen.map((r) => (r.adopt ? r.target : PASTE))).size; + const active = picked === PASTE || targets.includes(picked) ? picked : PASTE; + const at = targets.indexOf(active); + const found = rows.filter((r) => r.adopt && r.target === active); + const ready = found.filter((r) => importable(r) && !changeOf(r)); const title = t('hooks.importTitle'); return ( - + 0 || Boolean(row)} ariaLabel={title} className="!max-w-[1120px] !bg-bg">

{title}

@@ -171,41 +293,99 @@ export default function HooksImportDialog({ data, project, onClose, onImported }
-
- {loading && } - {failed.map((f) =>
{f}
)} - {targets.map((target) => { - const list = found.filter((r) => r.target === target); - return list.length > 0 && group(target, target, paths[target], list); - })} - {!loading && targets.length > 0 && found.length === 0 && failed.length === 0 &&

{t('hooks.importNone')}

} - {pasted && pasted.length > 0 && group('paste', pasteFrom, undefined, rows.filter((r) => !r.adopt))} - {pasted && pasted.length === 0 &&

{t('hooks.importNone')}

} - {pasting ? ( -
- {t('hooks.importPaste')} - { setPasteFrom(v); setPasted(null); }} + disabled={busy} + options={available.map((a) => ({ value: a, label: labelOf(a), icon: }))} + /> + { setContent(v); setPasted(null); }} lang={isCodeAgent(agentOf(pasteFrom)) ? 'typescript' : 'json'} ariaLabel={t('hooks.importPaste')} placeholder={t('hooks.importPastePlaceholder')} disabled={busy} minHeight="96px" /> + + {t('hooks.importPasteHint')} + + + {pasted && pasted.length === 0 &&

{t('hooks.importNone')}

} +
+ {pasted && pasted.length > 0 &&
{list(rows.filter((r) => !r.adopt))}
} +
+ ) : ( - +
+
+ 0 && ready.every(checked)} indeterminate={ready.some(checked) && !ready.every(checked)} disabled={ready.length === 0 || busy} onChange={(on) => check(ready.map((r) => r.id), on)} /> + {labelOf(active)} + {paths[active] ? {shortenHome(paths[active])} : } + {t('hooks.importPickedOf', { picked: String(found.filter(checked).length), total: String(found.length) })} +
+
+ {reads[at]?.isPending &&
} + {reads[at]?.error &&
{(reads[at].error as Error).message}
} + {reads[at]?.isSuccess && found.length === 0 &&

{t('hooks.importNone')}

} + {list(found)} +
+
)} - {error &&
{error}
}
-
- {t('hooks.importSelected', { count: String(chosen.length) })} - - + {failure &&
{failure}
} + {/* While a hook is being edited the footer holds the editor's actions instead. */} +
+ {!row && ( + <> + + {pending > 0 + ? t('hooks.importFooterPending', { count: String(chosen.length), changes: String(pending) }) + : t(plural('hooks.importFooter', sources), { count: String(chosen.length), targets: String(sources) })} + + + {pending > 0 && } + {pending > 0 + ? + : } + + )}
); diff --git a/ui/src/components/hooks/HooksImportEditor.tsx b/ui/src/components/hooks/HooksImportEditor.tsx new file mode 100644 index 000000000..3ffadd6f6 --- /dev/null +++ b/ui/src/components/hooks/HooksImportEditor.tsx @@ -0,0 +1,70 @@ +import { useState } from 'react'; +import { createPortal } from 'react-dom'; +import { useQuery } from '@tanstack/react-query'; +import { ArrowLeft, Trash2 } from 'lucide-react'; +import { hooksApi } from '../../api/hooks'; +import { useT } from '../../i18n'; +import { shortenHome } from '../../lib/paths'; +import { queryKeys } from '../../lib/queryKeys'; +import Button from '../Button'; +import IconButton from '../IconButton'; +import HookBindingEditor from './HookBindingEditor'; +import { sameEvents } from './hooksImport'; +import type { HookEvents } from './hooksImport'; +import { bindingInvalid, bindingToDraft, checkBinding, draftToBinding } from './hooksView'; + +interface Props { + agent: string; + /** The target's label and the hook's title, shown as "Claude / PostToolUse". */ + label: string; + title: string; + path?: string; + /** The dialog's footer, where this editor's actions go while it is open. */ + footerHost: HTMLElement | null; + /** The hook as the dialog holds it now, and as it was read from the target. */ + events: HookEvents; + original: HookEvents; + onCancel: () => void; + /** The edited events, or null when they are back to what the target has. */ + onDone: (events: HookEvents | null) => void; + onRemove: () => void; +} + +/** Edits a hook in place of the list. Nothing is written here: the result becomes a pending change of the import dialog. */ +export default function HooksImportEditor({ agent, label, title, path, footerHost, events, original, onCancel, onDone, onRemove }: Props) { + const t = useT(); + const { data: catalog } = useQuery({ queryKey: queryKeys.hooksCatalog, queryFn: () => hooksApi.catalog(), staleTime: Infinity }); + const [draft, setDraft] = useState(() => bindingToDraft(agent, { events })); + const [tabsHost, setTabsHost] = useState(null); + const check = checkBinding(agent, draft); + const done = () => { + const edited = draftToBinding(agent, draft).events ?? {}; + // The editor may write the same hook in another shape, so compare against the original taken through it too. + const untouched = draftToBinding(agent, bindingToDraft(agent, { events: original })).events ?? {}; + onDone(sameEvents(edited, untouched) || sameEvents(edited, original) ? null : edited); + }; + return ( +
+
+ } label={t('common.back')} onClick={onCancel} /> + + {label} / + {title} + + +
+
+ +
+ {footerHost && createPortal( + <> + + {t('hooks.importEditNote', { path: path ? shortenHome(path) : label })} + + + , + footerHost, + )} +
+ ); +} diff --git a/ui/src/components/hooks/HooksImportRow.tsx b/ui/src/components/hooks/HooksImportRow.tsx new file mode 100644 index 000000000..5a8c71935 --- /dev/null +++ b/ui/src/components/hooks/HooksImportRow.tsx @@ -0,0 +1,133 @@ +import { ChevronDown, Pencil, Trash2 } from 'lucide-react'; +import { plural, useT } from '../../i18n'; +import Button from '../Button'; +import { Checkbox } from '../Checkbox'; +import IconButton from '../IconButton'; +import Reveal from '../Reveal'; +import Tooltip from '../Tooltip'; +import { bindingLines } from './hookCatalog'; +import { commandSummary, describeChange, rowEvents, rowTitle } from './hooksImport'; +import type { ImportRow, NativeChange } from './hooksImport'; +import { hookMessage } from './hooksView'; + +// Said once in the dialog's subtitle rather than on every row. +const ADOPT_WARNING = 'saving the import takes over the existing registrations in place; sync leaves them as they are instead of adding duplicates'; + +interface Props { + row: ImportRow; + /** The target's name, for saying whose file a removal changes. */ + targetLabel: string; + change?: NativeChange; + checked: boolean; + importable: boolean; + open: boolean; + busy: boolean; + name: string; + nameFixed: boolean; + nameError: string; + onCheck: (on: boolean) => void; + onToggle: () => void; + onName: (name: string) => void; + /** Left out for a hook that cannot be changed in its target file. */ + onEdit?: () => void; + onRemove?: () => void; + onUndo: () => void; +} + +/** + * One hook of a target: what runs and when on two lines, the full commands and the import name + * when opened. A hook with a pending edit or removal says so and can only be put back. + */ +export default function HooksImportRow({ row, targetLabel, change, checked, importable, open, busy, name, nameFixed, nameError, onCheck, onToggle, onName, onEdit, onRemove, onUndo }: Props) { + const t = useT(); + const removed = Boolean(change && 'remove' in change); + const before = rowEvents(row); + const events = change && 'events' in change ? change.events : before; + const binding = row.candidate.entry.bindings[row.target]; + const lines = bindingLines(binding?.events ? { ...binding, events } : binding); + const title = rowTitle(row); + const matcher = lines[0]?.matcher ?? ''; + // A code hook is one file, or a folder of them, imported whole. + const code = lines.length > 0 ? [] : Object.entries(binding?.package ?? (binding?.code === undefined ? {} : { [binding.codeFile ?? '']: binding.code })); + const summary = lines.length > 0 ? commandSummary(lines[0].command) : code.length > 0 ? t('hooks.importWholeFile') : binding?.codeFile ?? ''; + const edited = change && 'events' in change ? describeChange(before, change.events) : undefined; + const notes = [ + ...row.candidate.problems.map((message) => ({ message, problem: true })), + ...row.candidate.warnings.filter((w) => w !== ADOPT_WARNING).map((message) => ({ message, problem: false })), + ]; + const fade = 'animate-[ss-fade-in_.15s_ease-out]'; + const expanded = open && !change; + return ( +
+
+ + {/* A larger place to click; the button that opens the row is the chevron at the end. */} +
+ + {title} + {matcher && lines.length === 1 && {matcher}} + {lines.length > 1 && {t(plural('hooks.commandCount', lines.length), { count: String(lines.length) })}} + {change && pending} + + {removed ? {t('hooks.importWillRemove', { target: targetLabel })} + : edited ? {t(edited.key, edited.params)} + : nameError ? {nameError} + : notes.some((n) => n.problem) ? {hookMessage(t, notes.find((n) => n.problem)!.message)} + : 0 ? '' : 'font-mono'}`}>{summary}} +
+ {change ? ( + + {!removed && onEdit && } + + + ) : ( + + {onEdit && onRemove && ( + <> + + } label={t('hooks.importEdit', { name: row.candidate.name })} onClick={onEdit} disabled={busy} /> + + + } label={t('hooks.importRemove', { name: row.candidate.name })} onClick={onRemove} disabled={busy} /> + + + )} + } label={row.candidate.name} onClick={onToggle} /> + + )} +
+ +
+ {lines.map((l, i) => ( +
+ {/* One command needs no heading: the row above already names its event and filter. */} + {(lines.length > 1 || l.event !== title) && ( + + {lines.length > 1 && {t('hooks.commandN', { n: String(i + 1) })}} + {l.event !== title && {l.event}} + {l.matcher && {t('hooks.matcher')} {l.matcher}} + + )} +
{l.command}
+
+ ))} + {code.map(([file, text]) => ( +
+ {file && {file}} +
{text}
+
+ ))} + {notes.map(({ message, problem }) => {hookMessage(t, message)})} + + {row.adopt && !onEdit && {t('hooks.importNotEditable')}} +
+
+
+ ); +} diff --git a/ui/src/components/hooks/HooksScope.tsx b/ui/src/components/hooks/HooksScope.tsx index 6e62a3f06..ca1451756 100644 --- a/ui/src/components/hooks/HooksScope.tsx +++ b/ui/src/components/hooks/HooksScope.tsx @@ -2,7 +2,7 @@ import { useState, type ReactNode } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { AlertCircle, Archive, Copy, Download, Eye, Info, Pencil, Plus, Trash2, Webhook } from 'lucide-react'; import { hooksApi, type HookChange, type HookEntry, type HookInventory } from '../../api/hooks'; -import { useT } from '../../i18n'; +import { plural, useT } from '../../i18n'; import { shortenHome } from '../../lib/paths'; import Button from '../Button'; import EmptyState from '../EmptyState'; @@ -153,7 +153,7 @@ export default function HooksScope({ data, project, header }: Props) { {editing !== null && ( setEditing(null)} onSaved={(synced) => done(t(synced ? 'hooks.toast.savedSynced' : 'hooks.toast.saved'))} /> )} - {importing && setImporting(false)} onImported={(count) => done(t('hooks.toast.imported', { count }))} />} + {importing && setImporting(false)} onChanged={refresh} onImported={(count, changed) => done(count > 0 || changed === 0 ? t('hooks.toast.imported', { count }) : t(plural('hooks.toast.nativeChanged', changed), { count: changed }))} />} {removing && setRemoving('')} onSaved={(unmanaged) => done(t(unmanaged ? 'hooks.toast.unmanaged' : 'hooks.toast.removed', { name: removing }))} />} {viewing && entries[viewing] && setViewing('')} />} {takingOver && entries[takingOver] && { setTakingOver(''); refresh(); }} />} diff --git a/ui/src/components/hooks/hooksImport.test.ts b/ui/src/components/hooks/hooksImport.test.ts new file mode 100644 index 000000000..3b83b9831 --- /dev/null +++ b/ui/src/components/hooks/hooksImport.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from 'vitest'; +import { commandSummary, describeChange, formatCommand, nativeEdits, sameEvents } from './hooksImport'; + +const group = (matcher: string, command: string) => ({ matcher, hooks: [{ type: 'command', command }] }); + +describe('commandSummary', () => { + it('shows the script a long command ends up running', () => { + expect(commandSummary('if [ -z "$X" ]; then exit 0; fi; [ -x ~/.claude/hook.sh ] && ~/.claude/hook.sh Stop')).toBe('~/.claude/hook.sh'); + }); + it('keeps the variable a script path starts with', () => { + expect(commandSummary('"$CLAUDE_PROJECT_DIR"/.claude/hooks/fmt.sh')).toBe('$CLAUDE_PROJECT_DIR/.claude/hooks/fmt.sh'); + }); + it('falls back to the first line', () => { + expect(commandSummary('\nafplay Glass\necho done')).toBe('afplay Glass'); + }); +}); + +describe('sameEvents', () => { + it('ignores key order', () => { + expect(sameEvents({ Stop: [{ a: 1, b: 2 }] }, { Stop: [{ b: 2, a: 1 }] })).toBe(true); + }); + it('sees a changed command', () => { + expect(sameEvents({ Stop: [group('', 'a')] }, { Stop: [group('', 'b')] })).toBe(false); + }); +}); + +describe('nativeEdits', () => { + it('sends a removal without an after and an edit with one', () => { + const before = { Stop: [group('', 'a')] }; + const after = { Stop: [group('', 'b')] }; + expect(nativeEdits([ + { target: 'claude', before, change: { remove: true } }, + { target: 'codex', root: '/repo', before, change: { events: after } }, + ])).toEqual([{ target: 'claude', before }, { target: 'codex', root: '/repo', before, after }]); + }); +}); + +describe('describeChange', () => { + it('names a matcher change', () => { + expect(describeChange({ PreToolUse: [group('', 'a')] }, { PreToolUse: [group('Bash', 'a')] })).toEqual({ key: 'hooks.importChange.matcher', params: { from: '*', to: 'Bash' } }); + }); + it('names the command that changed', () => { + expect(describeChange({ Stop: [group('', 'a'), group('', 'b')] }, { Stop: [group('', 'a'), group('', 'c')] })).toEqual({ key: 'hooks.importChange.command', params: { n: '2' } }); + }); + it('says only that anything larger was edited', () => { + expect(describeChange({ Stop: [group('', 'a')] }, { Stop: [group('', 'a'), group('', 'b')] })).toEqual({ key: 'hooks.importChange.edited' }); + }); +}); + +describe('formatCommand', () => { + it('puts one statement on a line and indents blocks', () => { + expect(formatCommand('if [ -z "$X" ]; then case "$Y" in a) exit 0;; esac; fi; [ -x ~/h.sh ] && ~/h.sh Stop')).toBe([ + 'if [ -z "$X" ]; then', + ' case "$Y" in a) exit 0;; esac', + 'fi', + '[ -x ~/h.sh ] &&', + ' ~/h.sh Stop', + ].join('\n')); + }); + it('leaves separators inside quotes and substitutions alone', () => { + const escaped = String.raw`find . -exec rm {} \;`; + expect(formatCommand(`echo "a; b" && x=$(date; id) ; ${escaped}`)).toBe(['echo "a; b" &&', ' x=$(date; id)', escaped].join('\n')); + }); + it('formats a loop', () => { + expect(formatCommand('for f in a b; do echo $f; done')).toBe('for f in a b; do\n echo $f\ndone'); + }); + it.each([ + 'cat < { + expect(formatCommand(command)).toBe(command); + }); + it('does not take a command that starts with a keyword for the keyword', () => { + expect(formatCommand('cd /x; do-backup.sh; else.sh')).toBe('cd /x\ndo-backup.sh\nelse.sh'); + }); + it('is stable on its own output', () => { + const once = formatCommand('if a; then b; else c; fi'); + expect(once).toBe('if a; then\n b\nelse\n c\nfi'); + expect(formatCommand(once)).toBe(once); + }); +}); diff --git a/ui/src/components/hooks/hooksImport.ts b/ui/src/components/hooks/hooksImport.ts new file mode 100644 index 000000000..58cb9740b --- /dev/null +++ b/ui/src/components/hooks/hooksImport.ts @@ -0,0 +1,136 @@ +import type { HookCandidate, HookNativeEdit } from '../../api/hooks'; +import { bindingLines } from './hookCatalog'; + +export type HookEvents = Record; +/** What the import dialog will write to a hook it has not imported: new events, or its removal. */ +export type NativeChange = { remove: true } | { events: HookEvents }; + +/** A candidate as the dialog shows it: where it was read from and whether saving takes over its native registrations. */ +export interface ImportRow { id: string; target: string; candidate: HookCandidate; adopt: boolean } + +export const rowEvents = (row: ImportRow): HookEvents => row.candidate.entry.bindings[row.target]?.events ?? {}; + +/** The event of a one-event candidate; a named block or a whole file goes by its own name. */ +export const rowTitle = (row: ImportRow) => { + const events = Object.keys(rowEvents(row)); + return events.length === 1 && row.target !== 'antigravity' ? events[0] : row.candidate.name; +}; + +const SCRIPT = /(?:"?\$\{?\w+\}?"?|~|\.{1,2})?(?:\/[\w.@+-]+)+\.\w+/g; + +/** The script a command runs, else its first line: what a collapsed row shows of a long command. */ +export function commandSummary(command: string) { + const scripts = command.match(SCRIPT); + if (scripts) return scripts[scripts.length - 1].replace(/"/g, ''); + return command.split('\n').map((l) => l.trim()).find(Boolean) ?? ''; +} + +const stable = (v: unknown): unknown => + Array.isArray(v) ? v.map(stable) + : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, stable((v as Record)[k])])) + : v; + +/** Equal event maps, whatever order their keys are written in. */ +export const sameEvents = (a: HookEvents | undefined, b: HookEvents | undefined) => JSON.stringify(stable(a ?? {})) === JSON.stringify(stable(b ?? {})); + +/** The edits to send: each changed hook's events as read, and what replaces them. */ +export function nativeEdits(rows: { target: string; root?: string; before: HookEvents; change: NativeChange }[]): HookNativeEdit[] { + return rows.map(({ target, root, before, change }) => ({ target, ...(root && { root }), before, ...('events' in change && { after: change.events }) })); +} + +/** One line on what an edit changed, as a translation key: a single matcher or command when that is all, else just "edited". */ +export function describeChange(before: HookEvents, after: HookEvents): { key: string; params?: Record } { + const was = bindingLines({ events: before }); + const now = bindingLines({ events: after }); + const changed = was.length === now.length ? [...now.keys()].filter((i) => JSON.stringify(was[i]) !== JSON.stringify(now[i])) : []; + if (changed.length === 1) { + const [i] = changed; + const [a, b] = [was[i], now[i]]; + if (a.event === b.event && a.command === b.command) return { key: 'hooks.importChange.matcher', params: { from: a.matcher || '*', to: b.matcher || '*' } }; + if (a.event === b.event && a.matcher === b.matcher) return { key: 'hooks.importChange.command', params: { n: String(i + 1) } }; + } + return { key: 'hooks.importChange.edited' }; +} + +/** + * Splits a command where a statement ends outside quotes and brackets. Null for anything this does not + * model exactly (heredocs, backticks, comments, an expansion inside double quotes, ANSI-C strings, an escaped space or + * line break, case fall-through): a wrong split would change what the command runs. + */ +function statements(command: string): string[] | null { + if (/<<|`/.test(command)) return null; + const out: string[] = []; + let current = ''; + let quote = ''; + let depth = 0; + const end = () => { if (current.trim()) out.push(current.trim()); current = ''; }; + for (let i = 0; i < command.length; i++) { + const c = command[i]; + const next = command[i + 1]; + if (c === '\\' && quote !== "'") { + if (next === undefined || /\s/.test(next)) return null; + current += c + next; + i++; + continue; + } + if (quote) { + if (quote === '"' && c === '$' && (next === '(' || next === '{')) return null; + if (c === quote) quote = ''; + current += c; + continue; + } + if (c === '$' && (next === "'" || next === '"')) return null; + if (c === '"' || c === "'") { quote = c; current += c; continue; } + if (c === '#') return null; + if (c === '(' || (c === '{' && command[i - 1] === '$')) depth++; + if (c === ')' || (c === '}' && depth > 0 && !/\s/.test(command[i - 1] ?? ' '))) depth = Math.max(0, depth - 1); + if (depth === 0 && c === '\n') { end(); continue; } + if (depth === 0 && c === ';' && next === ';') { + if (command[i + 2] === '&') return null; + current += ';;'; + i++; + continue; + } + if (depth === 0 && c === ';') { + if (next === '&') return null; + end(); + continue; + } + if (depth === 0 && (c === '&' || c === '|') && next === c) { current += c + c; i++; end(); continue; } + current += c; + } + if (quote) return null; + end(); + return out; +} + +const OPENER = /^(then|do|else)(?=\s|$)\s*([\s\S]*)$/; + +/** + * A one-line shell command laid out one statement per line, indented by block. Only line breaks and + * leading spaces change; a command this cannot split safely is returned as is. + */ +export function formatCommand(command: string) { + const parts = statements(command); + if (!parts) return command; + const lines: string[] = []; + let level = 0; + let continued = false; + const push = (text: string) => { + lines.push(' '.repeat(Math.max(level, 0) + (continued ? 1 : 0)) + text); + continued = /(&&|\|\|)$/.test(text); + }; + for (let s of parts) { + for (let opener = OPENER.exec(s); opener; opener = OPENER.exec(s)) { + if (opener[1] === 'else') { level--; push('else'); } else if (lines.length > 0 && !continued) lines[lines.length - 1] += `; ${opener[1]}`; else push(opener[1]); + level++; + s = opener[2]; + } + if (!s) continue; + if (/^(fi|done|esac|elif|\})(?![\w-])/.test(s)) level--; + push(s); + if (/^case\b/.test(s) && !/\besac\b/.test(s)) level++; + if (/(^|\s)\{$/.test(s)) level++; + } + return lines.join('\n'); +} diff --git a/ui/src/i18n/locales/de.json b/ui/src/i18n/locales/de.json index 35981c99a..76a1b57ae 100644 --- a/ui/src/i18n/locales/de.json +++ b/ui/src/i18n/locales/de.json @@ -3083,7 +3083,7 @@ "hooks.backupsHint": "Vor jeder Änderung durch Skillshare wird von jeder nativen Datei ein Backup erstellt.", "hooks.restoreHint": "Beim Wiederherstellen bleiben Änderungen nach dem Backup erhalten. Es bricht ab, wenn die Datei seitdem bearbeitet wurde.", "hooks.importTitle": "Hooks importieren", - "hooks.importHint": "Diese Hooks verwaltet skillshare noch nicht. Jeder markierte wird ein eigener Hook, den skillshare übernimmt, damit nichts doppelt geschrieben wird. Dateien werden nur gelesen, nie ausgeführt.", + "hooks.importHint": "Hooks, die deine Tools bereits ausführen, die skillshare aber noch nicht verwaltet. Die Konfigurationsdatei eines Ziels ändert sich erst, nachdem du die Änderungen geprüft hast.", "hooks.importFrom": "Importieren aus", "hooks.importPaste": "Konfiguration oder Code eines Ziels einfügen", "hooks.importPastePlaceholder": "Hooks-Abschnitt oder Plugin-Code einfügen", @@ -3415,7 +3415,49 @@ "hooks.unmanaged.review": "Prüfen und importieren", "hooks.importNameFor": "Name für {name}", "hooks.importPasteOpen": "Konfiguration oder Code zum Import einfügen", - "hooks.importSelected": "{count} ausgewählt", + "hooks.importTargets": "Ziele", + "hooks.importSelectAll": "Alle in {target} auswählen", + "hooks.importPickedOf": "{picked} von {total} ausgewählt", + "hooks.importFooter.one": "{count} ausgewählt, aus {targets} Ziel", + "hooks.importFooter.other": "{count} ausgewählt, aus {targets} Zielen", + "hooks.importFooterPending": "{count} zum Import ausgewählt; noch nicht geschriebene Änderungen: {changes}", + "hooks.importNameLabel": "Name in skillshare", + "hooks.importEdit": "{name} bearbeiten", + "hooks.importRemove": "{name} aus dem Ziel entfernen", + "hooks.importEditAction": "Bearbeiten", + "hooks.importRemoveAction": "Aus Ziel entfernen", + "hooks.importRemoveHook": "Diesen Hook entfernen", + "hooks.importUndo": "Rückgängig", + "hooks.importDone": "Fertig", + "hooks.importDiscard": "Änderungen verwerfen", + "hooks.importWillRemove": "Wird aus der Konfigurationsdatei von {target} entfernt", + "hooks.importChange.matcher": "Tool-Filter geändert von {from} zu {to}", + "hooks.importChange.command": "Befehl {n} bearbeitet", + "hooks.importChange.edited": "Bearbeitet, noch nicht geschrieben", + "hooks.importEditNote": "Änderungen gehen nach {path}, nachdem du sie geprüft hast.", + "hooks.importNotEditable": "Dieser Hook lässt sich erst nach dem Import ändern.", + "hooks.importReview": "Änderungen prüfen", + "hooks.importReviewHint": "Nichts wird geschrieben, bis du Änderungen anwenden wählst.", + "hooks.importApply": "Änderungen anwenden", + "hooks.importSum.import": "Zu importierende Hooks: {count}", + "hooks.importSum.importHint": "{list}. skillshare übernimmt sie. Der Import ändert die Konfigurationsdatei eines Ziels nicht.", + "hooks.importSum.edit": "Zu bearbeitende Hooks: {count}", + "hooks.importSum.remove": "Zu entfernende Hooks: {count}", + "hooks.importSum.removeHint": "Aus der Konfigurationsdatei von {target} gelöscht, nicht importiert.", + "hooks.importFiles": "Dateien, die geschrieben werden", + "hooks.importSum.count": "{target} {count}", + "hooks.importSum.listSep": ", ", + "hooks.importBackupNote.one": "Diese Datei wird vor dem Schreiben gesichert, und du kannst sie auf der Seite „Backups“ wiederherstellen.", + "hooks.importBackupNote.other": "Diese Dateien werden vor dem Schreiben gesichert, und du kannst sie auf der Seite „Backups“ wiederherstellen.", + "hooks.importBackupOthers": "Dateien von {targets} werden nicht geändert.", + "hooks.importWholeFile": "Die ganze Datei wird als ein Hook importiert", + "hooks.importPick": "{name} importieren", + "hooks.commandCount.one": "{count} Befehl", + "hooks.commandCount.other": "{count} Befehle", + "hooks.toast.nativeChanged.one": "{count} Änderung auf Zieldateien angewendet", + "hooks.toast.nativeChanged.other": "{count} Änderungen auf Zieldateien angewendet", + "hooks.commandN": "Befehl {n}", + "hooks.commandHint": "Zeilenumbrüche werden unverändert in die Konfigurationsdatei geschrieben. Formatieren ändert nur Zeilenumbrüche und Einrückung, nie den Befehl.", "hooks.native.antigravity": "Antigravity-IDE und -CLI lesen dieselbe hooks.json (~/.gemini/config/hooks.json bzw. .agents/hooks.json im Projekt). Skillshare schreibt jeden Hook als Block mit seinem Namen.", "hooks.events.pretooluse": "Bevor ein Tool läuft; kann es blockieren", "hooks.events.posttooluse": "Nachdem ein Tool fertig ist", diff --git a/ui/src/i18n/locales/en.json b/ui/src/i18n/locales/en.json index ae352ffb0..b22c026c2 100644 --- a/ui/src/i18n/locales/en.json +++ b/ui/src/i18n/locales/en.json @@ -3083,7 +3083,7 @@ "hooks.backupsHint": "Every native file is backed up before Skillshare changes it.", "hooks.restoreHint": "Restoring keeps changes made after the backup. It stops if the file was edited since.", "hooks.importTitle": "Import hooks", - "hooks.importHint": "These hooks are not managed by skillshare yet. Each checked one becomes its own hook and skillshare takes it over, so nothing is written twice. Files are only read, never run.", + "hooks.importHint": "Hooks your tools already run that skillshare does not manage yet. A target's config file changes only after you review.", "hooks.importFrom": "Import from", "hooks.importPaste": "Paste a target's config or code", "hooks.importPastePlaceholder": "Paste the hooks section or plugin code", @@ -3415,7 +3415,49 @@ "hooks.unmanaged.review": "Review and import", "hooks.importNameFor": "Name for {name}", "hooks.importPasteOpen": "Paste a config or code to import", - "hooks.importSelected": "{count} selected", + "hooks.importTargets": "Targets", + "hooks.importSelectAll": "Select all in {target}", + "hooks.importPickedOf": "{picked} of {total} selected", + "hooks.importFooter.one": "{count} selected, from {targets} target", + "hooks.importFooter.other": "{count} selected, from {targets} targets", + "hooks.importFooterPending": "{count} selected to import; changes not written yet: {changes}", + "hooks.importNameLabel": "Name in skillshare", + "hooks.importEdit": "Edit {name}", + "hooks.importRemove": "Remove {name} from the target", + "hooks.importEditAction": "Edit", + "hooks.importRemoveAction": "Remove from target", + "hooks.importRemoveHook": "Remove this hook", + "hooks.importUndo": "Undo", + "hooks.importDone": "Done", + "hooks.importDiscard": "Discard changes", + "hooks.importWillRemove": "Will be removed from {target}'s config file", + "hooks.importChange.matcher": "Matcher changed from {from} to {to}", + "hooks.importChange.command": "Command {n} edited", + "hooks.importChange.edited": "Edited, not written yet", + "hooks.importEditNote": "Changes go to {path} after you review them.", + "hooks.importNotEditable": "This hook can be changed only after you import it.", + "hooks.importReview": "Review changes", + "hooks.importReviewHint": "Nothing is written until you choose Apply changes.", + "hooks.importApply": "Apply changes", + "hooks.importSum.import": "Hooks to import: {count}", + "hooks.importSum.importHint": "{list}. skillshare takes them over. Importing does not change a target's config file.", + "hooks.importSum.edit": "Hooks to edit: {count}", + "hooks.importSum.remove": "Hooks to remove: {count}", + "hooks.importSum.removeHint": "Deleted from {target}'s config file, not imported.", + "hooks.importFiles": "Files that will be written", + "hooks.importSum.count": "{target} {count}", + "hooks.importSum.listSep": ", ", + "hooks.importBackupNote.one": "This file is backed up before it is written, and you can restore it on the Backups page.", + "hooks.importBackupNote.other": "These files are backed up before they are written, and you can restore them on the Backups page.", + "hooks.importBackupOthers": "Files of {targets} are not changed.", + "hooks.importWholeFile": "The whole file is imported as one hook", + "hooks.importPick": "Import {name}", + "hooks.commandCount.one": "{count} command", + "hooks.commandCount.other": "{count} commands", + "hooks.toast.nativeChanged.one": "Applied {count} change to target files", + "hooks.toast.nativeChanged.other": "Applied {count} changes to target files", + "hooks.commandN": "Command {n}", + "hooks.commandHint": "Line breaks are written to the config file as they are. Format changes only line breaks and indentation, never the command.", "hooks.native.antigravity": "The Antigravity IDE and CLI read the same hooks.json (~/.gemini/config/hooks.json, or .agents/hooks.json in a project). Skillshare writes each hook as a block named after it.", "hooks.events.pretooluse": "Before a tool runs; can block it", "hooks.events.posttooluse": "After a tool finishes", diff --git a/ui/src/i18n/locales/es.json b/ui/src/i18n/locales/es.json index 0416dc3a9..1d04bc8c5 100644 --- a/ui/src/i18n/locales/es.json +++ b/ui/src/i18n/locales/es.json @@ -3083,7 +3083,7 @@ "hooks.backupsHint": "Se hace una copia de cada archivo nativo antes de que Skillshare lo cambie.", "hooks.restoreHint": "Al restaurar se conservan los cambios hechos después de la copia. Se detiene si el archivo se editó desde entonces.", "hooks.importTitle": "Importar hooks", - "hooks.importHint": "Estos hooks aún no los gestiona skillshare. Cada uno marcado se vuelve un hook y skillshare lo toma, así nada se escribe dos veces. Solo se leen, nunca se ejecutan.", + "hooks.importHint": "Hooks que tus herramientas ya ejecutan y que skillshare aún no gestiona. El archivo de configuración de un destino solo cambia después de que revises los cambios.", "hooks.importFrom": "Importar desde", "hooks.importPaste": "Pega la configuración o el código de un destino", "hooks.importPastePlaceholder": "Pega la sección hooks o el código del plugin", @@ -3415,7 +3415,49 @@ "hooks.unmanaged.review": "Revisar e importar", "hooks.importNameFor": "Nombre para {name}", "hooks.importPasteOpen": "Pegar una configuración o código para importar", - "hooks.importSelected": "{count} seleccionados", + "hooks.importTargets": "Destinos", + "hooks.importSelectAll": "Seleccionar todo en {target}", + "hooks.importPickedOf": "{picked} de {total} seleccionados", + "hooks.importFooter.one": "{count} seleccionado, de {targets} destino", + "hooks.importFooter.other": "{count} seleccionados, de {targets} destinos", + "hooks.importFooterPending": "{count} seleccionados para importar; cambios aún sin escribir: {changes}", + "hooks.importNameLabel": "Nombre en skillshare", + "hooks.importEdit": "Editar {name}", + "hooks.importRemove": "Quitar {name} del destino", + "hooks.importEditAction": "Editar", + "hooks.importRemoveAction": "Quitar del destino", + "hooks.importRemoveHook": "Quitar este hook", + "hooks.importUndo": "Deshacer", + "hooks.importDone": "Listo", + "hooks.importDiscard": "Descartar cambios", + "hooks.importWillRemove": "Se quitará del archivo de configuración de {target}", + "hooks.importChange.matcher": "Filtro cambiado de {from} a {to}", + "hooks.importChange.command": "Comando {n} editado", + "hooks.importChange.edited": "Editado, aún sin escribir", + "hooks.importEditNote": "Los cambios van a {path} después de que los revises.", + "hooks.importNotEditable": "Este hook solo se puede cambiar después de importarlo.", + "hooks.importReview": "Revisar cambios", + "hooks.importReviewHint": "No se escribe nada hasta que elijas Aplicar cambios.", + "hooks.importApply": "Aplicar cambios", + "hooks.importSum.import": "Hooks por importar: {count}", + "hooks.importSum.importHint": "{list}. skillshare los toma. Importar no cambia el archivo de configuración de un destino.", + "hooks.importSum.edit": "Hooks por editar: {count}", + "hooks.importSum.remove": "Hooks por quitar: {count}", + "hooks.importSum.removeHint": "Se elimina del archivo de configuración de {target}, no se importa.", + "hooks.importFiles": "Archivos que se escribirán", + "hooks.importSum.count": "{target} {count}", + "hooks.importSum.listSep": ", ", + "hooks.importBackupNote.one": "Este archivo se respalda antes de escribirse, y puedes restaurarlo en la página Copias de seguridad.", + "hooks.importBackupNote.other": "Estos archivos se respaldan antes de escribirse, y puedes restaurarlos en la página Copias de seguridad.", + "hooks.importBackupOthers": "Los archivos de {targets} no se modifican.", + "hooks.importWholeFile": "Todo el archivo se importa como un solo hook", + "hooks.importPick": "Importar {name}", + "hooks.commandCount.one": "{count} comando", + "hooks.commandCount.other": "{count} comandos", + "hooks.toast.nativeChanged.one": "Se aplicó {count} cambio a los archivos de destino", + "hooks.toast.nativeChanged.other": "Se aplicaron {count} cambios a los archivos de destino", + "hooks.commandN": "Comando {n}", + "hooks.commandHint": "Los saltos de línea se escriben en el archivo de configuración tal cual. Formatear solo cambia saltos de línea y sangría, nunca el comando.", "hooks.native.antigravity": "El IDE y la CLI de Antigravity leen el mismo hooks.json (~/.gemini/config/hooks.json, o .agents/hooks.json en un proyecto). Skillshare escribe cada hook como un bloque con su nombre.", "hooks.events.pretooluse": "Antes de ejecutar una herramienta; puede bloquearla", "hooks.events.posttooluse": "Después de que termina una herramienta", diff --git a/ui/src/i18n/locales/fa.json b/ui/src/i18n/locales/fa.json index 62921c65b..bad238c0e 100644 --- a/ui/src/i18n/locales/fa.json +++ b/ui/src/i18n/locales/fa.json @@ -3083,7 +3083,7 @@ "hooks.backupsHint": "پیش از هر تغییر Skillshare، از هر فایل بومی نسخهٔ پشتیبان گرفته می‌شود.", "hooks.restoreHint": "بازیابی، تغییرهای پس از پشتیبان را نگه می‌دارد. اگر فایل از آن زمان ویرایش شده باشد متوقف می‌شود.", "hooks.importTitle": "درون‌ریزی hooks", - "hooks.importHint": "این hookها هنوز در مدیریت skillshare نیستند. هر مورد انتخاب‌شده یک hook جدا می‌شود و skillshare آن را برعهده می‌گیرد تا چیزی دوبار نوشته نشود. فایل‌ها فقط خوانده می‌شوند و اجرا نمی‌شوند.", + "hooks.importHint": "hookهایی که ابزارهای شما از قبل اجرا می‌کنند اما skillshare هنوز مدیریتشان نمی‌کند. فایل تنظیمات هر هدف فقط پس از بازبینی شما تغییر می‌کند.", "hooks.importFrom": "درون‌ریزی از", "hooks.importPaste": "تنظیمات یا کد یک هدف را بچسبانید", "hooks.importPastePlaceholder": "بخش hooks یا کد افزونه را بچسبانید", @@ -3415,7 +3415,49 @@ "hooks.unmanaged.review": "بررسی و وارد کردن", "hooks.importNameFor": "نام برای {name}", "hooks.importPasteOpen": "برای وارد کردن، تنظیمات یا کد را بچسبانید", - "hooks.importSelected": "{count} انتخاب‌شده", + "hooks.importTargets": "هدف‌ها", + "hooks.importSelectAll": "انتخاب همه در {target}", + "hooks.importPickedOf": "{picked} از {total} انتخاب شد", + "hooks.importFooter.one": "{count} انتخاب‌شده، از {targets} هدف", + "hooks.importFooter.other": "{count} انتخاب‌شده، از {targets} هدف", + "hooks.importFooterPending": "{count} مورد برای درون‌ریزی انتخاب شد؛ تغییرات ننوشته‌شده: {changes}", + "hooks.importNameLabel": "نام در skillshare", + "hooks.importEdit": "ویرایش {name}", + "hooks.importRemove": "حذف {name} از هدف", + "hooks.importEditAction": "ویرایش", + "hooks.importRemoveAction": "حذف از هدف", + "hooks.importRemoveHook": "حذف این hook", + "hooks.importUndo": "واگرد", + "hooks.importDone": "انجام شد", + "hooks.importDiscard": "دور ریختن تغییرات", + "hooks.importWillRemove": "از فایل تنظیمات {target} حذف می‌شود", + "hooks.importChange.matcher": "فیلتر از {from} به {to} تغییر کرد", + "hooks.importChange.command": "دستور {n} ویرایش شد", + "hooks.importChange.edited": "ویرایش شده، هنوز نوشته نشده", + "hooks.importEditNote": "تغییرات پس از بازبینی شما در {path} نوشته می‌شود.", + "hooks.importNotEditable": "این hook را فقط پس از درون‌ریزی می‌توان تغییر داد.", + "hooks.importReview": "بازبینی تغییرات", + "hooks.importReviewHint": "تا وقتی «اعمال تغییرات» را نزنید چیزی نوشته نمی‌شود.", + "hooks.importApply": "اعمال تغییرات", + "hooks.importSum.import": "hookهای درون‌ریزی: {count}", + "hooks.importSum.importHint": "{list}. skillshare آن‌ها را برعهده می‌گیرد. درون‌ریزی فایل تنظیمات هدف را تغییر نمی‌دهد.", + "hooks.importSum.edit": "hookهای ویرایش: {count}", + "hooks.importSum.remove": "hookهای حذف: {count}", + "hooks.importSum.removeHint": "از فایل تنظیمات {target} حذف می‌شود و درون‌ریزی نمی‌شود.", + "hooks.importFiles": "فایل‌هایی که نوشته می‌شوند", + "hooks.importSum.count": "{target} {count}", + "hooks.importSum.listSep": "، ", + "hooks.importBackupNote.one": "این فایل پیش از نوشتن پشتیبان‌گیری می‌شود و می‌توانید آن را در صفحه پشتیبان‌ها بازیابی کنید.", + "hooks.importBackupNote.other": "این فایل‌ها پیش از نوشتن پشتیبان‌گیری می‌شوند و می‌توانید آن‌ها را در صفحه پشتیبان‌ها بازیابی کنید.", + "hooks.importBackupOthers": "فایل‌های {targets} تغییر نمی‌کنند.", + "hooks.importWholeFile": "کل فایل به‌عنوان یک hook درون‌ریزی می‌شود", + "hooks.importPick": "درون‌ریزی {name}", + "hooks.commandCount.one": "{count} دستور", + "hooks.commandCount.other": "{count} دستور", + "hooks.toast.nativeChanged.one": "{count} تغییر روی فایل‌های هدف اعمال شد", + "hooks.toast.nativeChanged.other": "{count} تغییر روی فایل‌های هدف اعمال شد", + "hooks.commandN": "دستور {n}", + "hooks.commandHint": "شکستن خط‌ها همان‌طور که هست در فایل تنظیمات نوشته می‌شود. قالب‌بندی فقط شکستن خط و تورفتگی را تغییر می‌دهد، نه دستور را.", "hooks.native.antigravity": "IDE و CLI در Antigravity همان hooks.json را می‌خوانند (~/.gemini/config/hooks.json یا .agents/hooks.json در پروژه). Skillshare هر hook را به‌صورت بلوکی به نام خودش می‌نویسد.", "hooks.events.pretooluse": "پیش از اجرای ابزار؛ می‌تواند جلویش را بگیرد", "hooks.events.posttooluse": "پس از پایان اجرای ابزار", diff --git a/ui/src/i18n/locales/fr.json b/ui/src/i18n/locales/fr.json index bf4f70a47..ac008e739 100644 --- a/ui/src/i18n/locales/fr.json +++ b/ui/src/i18n/locales/fr.json @@ -3083,7 +3083,7 @@ "hooks.backupsHint": "Chaque fichier natif est sauvegardé avant que Skillshare ne le modifie.", "hooks.restoreHint": "La restauration conserve les modifications faites après la sauvegarde. Elle s'arrête si le fichier a été modifié depuis.", "hooks.importTitle": "Importer des hooks", - "hooks.importHint": "Ces hooks ne sont pas encore gérés par skillshare. Chaque hook coché devient un hook repris par skillshare, sans double écriture. Les fichiers sont lus, jamais exécutés.", + "hooks.importHint": "Des hooks que vos outils exécutent déjà et que skillshare ne gère pas encore. Le fichier de configuration d'une cible ne change qu'après votre relecture.", "hooks.importFrom": "Importer depuis", "hooks.importPaste": "Collez la configuration ou le code d'une cible", "hooks.importPastePlaceholder": "Collez la section hooks ou le code du plugin", @@ -3415,7 +3415,49 @@ "hooks.unmanaged.review": "Vérifier et importer", "hooks.importNameFor": "Nom pour {name}", "hooks.importPasteOpen": "Coller une configuration ou du code à importer", - "hooks.importSelected": "{count} sélectionnés", + "hooks.importTargets": "Cibles", + "hooks.importSelectAll": "Tout sélectionner dans {target}", + "hooks.importPickedOf": "{picked} sur {total} sélectionnés", + "hooks.importFooter.one": "{count} sélectionné, de {targets} cible", + "hooks.importFooter.other": "{count} sélectionnés, de {targets} cibles", + "hooks.importFooterPending": "{count} sélectionnés à importer ; modifications pas encore écrites : {changes}", + "hooks.importNameLabel": "Nom dans skillshare", + "hooks.importEdit": "Modifier {name}", + "hooks.importRemove": "Retirer {name} de la cible", + "hooks.importEditAction": "Modifier", + "hooks.importRemoveAction": "Retirer de la cible", + "hooks.importRemoveHook": "Retirer ce hook", + "hooks.importUndo": "Annuler", + "hooks.importDone": "Terminé", + "hooks.importDiscard": "Abandonner les modifications", + "hooks.importWillRemove": "Sera retiré du fichier de configuration de {target}", + "hooks.importChange.matcher": "Filtre modifié de {from} à {to}", + "hooks.importChange.command": "Commande {n} modifiée", + "hooks.importChange.edited": "Modifié, pas encore écrit", + "hooks.importEditNote": "Les modifications vont dans {path} après votre relecture.", + "hooks.importNotEditable": "Ce hook ne peut être modifié qu'après son import.", + "hooks.importReview": "Relire les modifications", + "hooks.importReviewHint": "Rien n'est écrit tant que vous ne choisissez pas Appliquer les modifications.", + "hooks.importApply": "Appliquer les modifications", + "hooks.importSum.import": "Hooks à importer : {count}", + "hooks.importSum.importHint": "{list}. skillshare les reprend. L'import ne modifie pas le fichier de configuration d'une cible.", + "hooks.importSum.edit": "Hooks à modifier : {count}", + "hooks.importSum.remove": "Hooks à retirer : {count}", + "hooks.importSum.removeHint": "Supprimé du fichier de configuration de {target}, non importé.", + "hooks.importFiles": "Fichiers qui seront écrits", + "hooks.importSum.count": "{target} {count}", + "hooks.importSum.listSep": ", ", + "hooks.importBackupNote.one": "Ce fichier est sauvegardé avant d'être écrit, et vous pouvez le restaurer sur la page Sauvegardes.", + "hooks.importBackupNote.other": "Ces fichiers sont sauvegardés avant d'être écrits, et vous pouvez les restaurer sur la page Sauvegardes.", + "hooks.importBackupOthers": "Les fichiers de {targets} ne sont pas modifiés.", + "hooks.importWholeFile": "Le fichier entier est importé comme un seul hook", + "hooks.importPick": "Importer {name}", + "hooks.commandCount.one": "{count} commande", + "hooks.commandCount.other": "{count} commandes", + "hooks.toast.nativeChanged.one": "{count} modification appliquée aux fichiers des cibles", + "hooks.toast.nativeChanged.other": "{count} modifications appliquées aux fichiers des cibles", + "hooks.commandN": "Commande {n}", + "hooks.commandHint": "Les sauts de ligne sont écrits tels quels dans le fichier de configuration. Formater ne change que les sauts de ligne et l'indentation, jamais la commande.", "hooks.native.antigravity": "L'IDE et la CLI Antigravity lisent le même hooks.json (~/.gemini/config/hooks.json, ou .agents/hooks.json dans un projet). Skillshare écrit chaque hook comme un bloc portant son nom.", "hooks.events.pretooluse": "Avant l'exécution d'un outil ; peut la bloquer", "hooks.events.posttooluse": "Après l'exécution d'un outil", diff --git a/ui/src/i18n/locales/id.json b/ui/src/i18n/locales/id.json index 867e757cc..34ec8178f 100644 --- a/ui/src/i18n/locales/id.json +++ b/ui/src/i18n/locales/id.json @@ -3083,7 +3083,7 @@ "hooks.backupsHint": "Setiap file native dicadangkan sebelum Skillshare mengubahnya.", "hooks.restoreHint": "Pemulihan mempertahankan perubahan setelah pencadangan. Pemulihan berhenti jika file sudah diedit sejak itu.", "hooks.importTitle": "Impor hooks", - "hooks.importHint": "Hook ini belum dikelola skillshare. Tiap yang dicentang menjadi hook tersendiri dan diambil alih skillshare, jadi tidak ditulis dua kali. File hanya dibaca, tidak dijalankan.", + "hooks.importHint": "Hook yang sudah dijalankan alat Anda tetapi belum dikelola skillshare. File konfigurasi target baru berubah setelah Anda meninjau perubahannya.", "hooks.importFrom": "Impor dari", "hooks.importPaste": "Tempel konfigurasi atau kode target", "hooks.importPastePlaceholder": "Tempel bagian hooks atau kode plugin", @@ -3415,7 +3415,49 @@ "hooks.unmanaged.review": "Tinjau dan impor", "hooks.importNameFor": "Nama untuk {name}", "hooks.importPasteOpen": "Tempel konfigurasi atau kode untuk diimpor", - "hooks.importSelected": "{count} dipilih", + "hooks.importTargets": "Target", + "hooks.importSelectAll": "Pilih semua di {target}", + "hooks.importPickedOf": "{picked} dari {total} dipilih", + "hooks.importFooter.one": "{count} dipilih, dari {targets} target", + "hooks.importFooter.other": "{count} dipilih, dari {targets} target", + "hooks.importFooterPending": "{count} dipilih untuk diimpor; perubahan belum ditulis: {changes}", + "hooks.importNameLabel": "Nama di skillshare", + "hooks.importEdit": "Edit {name}", + "hooks.importRemove": "Hapus {name} dari target", + "hooks.importEditAction": "Edit", + "hooks.importRemoveAction": "Hapus dari target", + "hooks.importRemoveHook": "Hapus hook ini", + "hooks.importUndo": "Urungkan", + "hooks.importDone": "Selesai", + "hooks.importDiscard": "Buang perubahan", + "hooks.importWillRemove": "Akan dihapus dari file konfigurasi {target}", + "hooks.importChange.matcher": "Filter diubah dari {from} ke {to}", + "hooks.importChange.command": "Command {n} diedit", + "hooks.importChange.edited": "Diedit, belum ditulis", + "hooks.importEditNote": "Perubahan masuk ke {path} setelah Anda meninjaunya.", + "hooks.importNotEditable": "Hook ini hanya bisa diubah setelah diimpor.", + "hooks.importReview": "Tinjau perubahan", + "hooks.importReviewHint": "Tidak ada yang ditulis sampai Anda memilih Terapkan perubahan.", + "hooks.importApply": "Terapkan perubahan", + "hooks.importSum.import": "Hook yang diimpor: {count}", + "hooks.importSum.importHint": "{list}. skillshare mengambil alihnya. Impor tidak mengubah file konfigurasi target.", + "hooks.importSum.edit": "Hook yang diedit: {count}", + "hooks.importSum.remove": "Hook yang dihapus: {count}", + "hooks.importSum.removeHint": "Dihapus dari file konfigurasi {target}, tidak diimpor.", + "hooks.importFiles": "File yang akan ditulis", + "hooks.importSum.count": "{target} {count}", + "hooks.importSum.listSep": ", ", + "hooks.importBackupNote.one": "File ini dicadangkan sebelum ditulis, dan Anda bisa memulihkannya di halaman Cadangan.", + "hooks.importBackupNote.other": "File-file ini dicadangkan sebelum ditulis, dan Anda bisa memulihkannya di halaman Cadangan.", + "hooks.importBackupOthers": "File milik {targets} tidak diubah.", + "hooks.importWholeFile": "Seluruh file diimpor sebagai satu hook", + "hooks.importPick": "Impor {name}", + "hooks.commandCount.one": "{count} command", + "hooks.commandCount.other": "{count} command", + "hooks.toast.nativeChanged.one": "{count} perubahan diterapkan ke file target", + "hooks.toast.nativeChanged.other": "{count} perubahan diterapkan ke file target", + "hooks.commandN": "Command {n}", + "hooks.commandHint": "Baris baru ditulis ke file konfigurasi apa adanya. Rapikan hanya mengubah baris baru dan indentasi, tidak pernah command-nya.", "hooks.native.antigravity": "IDE dan CLI Antigravity membaca hooks.json yang sama (~/.gemini/config/hooks.json, atau .agents/hooks.json dalam proyek). Skillshare menulis tiap hook sebagai blok bernama sesuai hook itu.", "hooks.events.pretooluse": "Sebelum tool berjalan; bisa memblokirnya", "hooks.events.posttooluse": "Setelah tool selesai", diff --git a/ui/src/i18n/locales/ja.json b/ui/src/i18n/locales/ja.json index 40624d3c5..2fcef691e 100644 --- a/ui/src/i18n/locales/ja.json +++ b/ui/src/i18n/locales/ja.json @@ -3083,7 +3083,7 @@ "hooks.backupsHint": "Skillshare がネイティブファイルを変更する前に、毎回バックアップします。", "hooks.restoreHint": "復元してもバックアップ後の変更は保持されます。その後ファイルが編集されている場合は中止されます。", "hooks.importTitle": "hooks をインポート", - "hooks.importHint": "skillshare がまだ管理していない hook です。チェックしたものはそれぞれ 1 つの hook になり、skillshare が引き継ぐので二重に書き込みません。読み取るだけで実行はしません。", + "hooks.importHint": "ツールですでに動いているが、skillshare がまだ管理していない hook です。ターゲットの設定ファイルは、変更を確認した後にだけ書き換えられます。", "hooks.importFrom": "インポート元", "hooks.importPaste": "ターゲットの設定やコードを貼り付け", "hooks.importPastePlaceholder": "hooks セクションかプラグインのコードを貼り付け", @@ -3415,7 +3415,49 @@ "hooks.unmanaged.review": "確認してインポート", "hooks.importNameFor": "{name} の名前", "hooks.importPasteOpen": "設定やコードを貼り付けてインポート", - "hooks.importSelected": "{count} 件選択", + "hooks.importTargets": "ターゲット", + "hooks.importSelectAll": "{target} をすべて選択", + "hooks.importPickedOf": "{total} 件中 {picked} 件を選択", + "hooks.importFooter.one": "{targets} 個のターゲットから {count} 件を選択", + "hooks.importFooter.other": "{targets} 個のターゲットから {count} 件を選択", + "hooks.importFooterPending": "{count} 件をインポート予定。未書き込みの変更: {changes}", + "hooks.importNameLabel": "skillshare での名前", + "hooks.importEdit": "{name} を編集", + "hooks.importRemove": "{name} をターゲットから削除", + "hooks.importEditAction": "編集", + "hooks.importRemoveAction": "ターゲットから削除", + "hooks.importRemoveHook": "この hook を削除", + "hooks.importUndo": "元に戻す", + "hooks.importDone": "完了", + "hooks.importDiscard": "変更を破棄", + "hooks.importWillRemove": "{target} の設定ファイルから削除されます", + "hooks.importChange.matcher": "絞り込みを {from} から {to} に変更", + "hooks.importChange.command": "コマンド {n} を編集", + "hooks.importChange.edited": "編集済み、未書き込み", + "hooks.importEditNote": "変更は確認後に {path} に書き込まれます。", + "hooks.importNotEditable": "この hook はインポートしてからでないと変更できません。", + "hooks.importReview": "変更を確認", + "hooks.importReviewHint": "「変更を適用」を選ぶまで何も書き込まれません。", + "hooks.importApply": "変更を適用", + "hooks.importSum.import": "インポートする hook: {count} 件", + "hooks.importSum.importHint": "{list}。skillshare が引き継ぎます。インポートでターゲットの設定ファイルは変わりません。", + "hooks.importSum.edit": "編集する hook: {count} 件", + "hooks.importSum.remove": "削除する hook: {count} 件", + "hooks.importSum.removeHint": "{target} の設定ファイルから削除され、インポートはされません。", + "hooks.importFiles": "書き込まれるファイル", + "hooks.importSum.count": "{target} {count} 件", + "hooks.importSum.listSep": "、", + "hooks.importBackupNote.one": "このファイルは書き込み前にバックアップされ、「バックアップ」ページで復元できます。", + "hooks.importBackupNote.other": "これらのファイルは書き込み前にバックアップされ、「バックアップ」ページで復元できます。", + "hooks.importBackupOthers": "{targets} のファイルは変更されません。", + "hooks.importWholeFile": "ファイル全体が 1 つの hook としてインポートされます", + "hooks.importPick": "{name} をインポート", + "hooks.commandCount.one": "コマンド {count} 件", + "hooks.commandCount.other": "コマンド {count} 件", + "hooks.toast.nativeChanged.one": "ターゲットのファイルに {count} 件の変更を適用しました", + "hooks.toast.nativeChanged.other": "ターゲットのファイルに {count} 件の変更を適用しました", + "hooks.commandN": "コマンド {n}", + "hooks.commandHint": "改行は設定ファイルにそのまま書き込まれます。整形で変わるのは改行とインデントだけで、コマンドは変わりません。", "hooks.native.antigravity": "Antigravity の IDE と CLI は同じ hooks.json(~/.gemini/config/hooks.json、プロジェクトでは .agents/hooks.json)を読みます。skillshare は各 hook をその名前のブロックとして書きます。", "hooks.events.pretooluse": "ツール実行前(ブロック可)", "hooks.events.posttooluse": "ツール実行後", diff --git a/ui/src/i18n/locales/ko.json b/ui/src/i18n/locales/ko.json index 6792e3af0..00bc30dff 100644 --- a/ui/src/i18n/locales/ko.json +++ b/ui/src/i18n/locales/ko.json @@ -3083,7 +3083,7 @@ "hooks.backupsHint": "Skillshare가 네이티브 파일을 변경하기 전에 항상 백업합니다.", "hooks.restoreHint": "복원해도 백업 이후의 변경 사항은 유지됩니다. 그 사이 파일이 편집되었다면 복원이 중단됩니다.", "hooks.importTitle": "hooks 가져오기", - "hooks.importHint": "skillshare가 아직 관리하지 않는 hook입니다. 선택한 항목은 각각 hook이 되고 skillshare가 넘겨받아 중복으로 쓰지 않습니다. 읽기만 하고 실행하지 않습니다.", + "hooks.importHint": "도구에서 이미 실행 중이지만 skillshare가 아직 관리하지 않는 hook입니다. 대상의 설정 파일은 변경 사항을 검토한 뒤에만 바뀝니다.", "hooks.importFrom": "가져올 곳", "hooks.importPaste": "대상의 설정이나 코드 붙여넣기", "hooks.importPastePlaceholder": "hooks 섹션이나 플러그인 코드를 붙여넣기", @@ -3415,7 +3415,49 @@ "hooks.unmanaged.review": "확인하고 가져오기", "hooks.importNameFor": "{name}의 이름", "hooks.importPasteOpen": "설정이나 코드를 붙여넣어 가져오기", - "hooks.importSelected": "{count}개 선택됨", + "hooks.importTargets": "대상", + "hooks.importSelectAll": "{target} 전체 선택", + "hooks.importPickedOf": "{total}개 중 {picked}개 선택됨", + "hooks.importFooter.one": "{targets}개 대상에서 {count}개 선택됨", + "hooks.importFooter.other": "{targets}개 대상에서 {count}개 선택됨", + "hooks.importFooterPending": "{count}개 가져오기 선택됨, 아직 쓰지 않은 변경: {changes}", + "hooks.importNameLabel": "skillshare에서의 이름", + "hooks.importEdit": "{name} 편집", + "hooks.importRemove": "대상에서 {name} 제거", + "hooks.importEditAction": "편집", + "hooks.importRemoveAction": "대상에서 제거", + "hooks.importRemoveHook": "이 hook 제거", + "hooks.importUndo": "실행 취소", + "hooks.importDone": "완료", + "hooks.importDiscard": "변경 사항 버리기", + "hooks.importWillRemove": "{target}의 설정 파일에서 제거됩니다", + "hooks.importChange.matcher": "필터를 {from}에서 {to}(으)로 변경", + "hooks.importChange.command": "명령 {n} 편집됨", + "hooks.importChange.edited": "편집됨, 아직 쓰지 않음", + "hooks.importEditNote": "변경 사항은 검토한 뒤 {path}에 쓰입니다.", + "hooks.importNotEditable": "이 hook은 가져온 뒤에만 바꿀 수 있습니다.", + "hooks.importReview": "변경 사항 검토", + "hooks.importReviewHint": "변경 사항 적용을 누르기 전에는 아무것도 쓰이지 않습니다.", + "hooks.importApply": "변경 사항 적용", + "hooks.importSum.import": "가져올 hook: {count}개", + "hooks.importSum.importHint": "{list}. skillshare가 넘겨받습니다. 가져오기는 대상의 설정 파일을 바꾸지 않습니다.", + "hooks.importSum.edit": "편집할 hook: {count}개", + "hooks.importSum.remove": "제거할 hook: {count}개", + "hooks.importSum.removeHint": "{target}의 설정 파일에서 삭제되며, 가져오지 않습니다.", + "hooks.importFiles": "쓰게 될 파일", + "hooks.importSum.count": "{target} {count}개", + "hooks.importSum.listSep": ", ", + "hooks.importBackupNote.one": "이 파일은 쓰기 전에 백업되며, 백업 페이지에서 복원할 수 있습니다.", + "hooks.importBackupNote.other": "이 파일들은 쓰기 전에 백업되며, 백업 페이지에서 복원할 수 있습니다.", + "hooks.importBackupOthers": "{targets}의 파일은 바뀌지 않습니다.", + "hooks.importWholeFile": "파일 전체가 hook 하나로 가져와집니다", + "hooks.importPick": "{name} 가져오기", + "hooks.commandCount.one": "명령 {count}개", + "hooks.commandCount.other": "명령 {count}개", + "hooks.toast.nativeChanged.one": "대상 파일에 변경 {count}개를 적용했습니다", + "hooks.toast.nativeChanged.other": "대상 파일에 변경 {count}개를 적용했습니다", + "hooks.commandN": "명령 {n}", + "hooks.commandHint": "줄바꿈은 설정 파일에 그대로 쓰입니다. 서식 정리는 줄바꿈과 들여쓰기만 바꾸고 명령은 바꾸지 않습니다.", "hooks.native.antigravity": "Antigravity IDE와 CLI는 같은 hooks.json(~/.gemini/config/hooks.json, 프로젝트에서는 .agents/hooks.json)을 읽습니다. skillshare는 각 hook을 그 이름의 블록으로 씁니다.", "hooks.events.pretooluse": "도구 실행 전(차단 가능)", "hooks.events.posttooluse": "도구 실행 후", diff --git a/ui/src/i18n/locales/pt-BR.json b/ui/src/i18n/locales/pt-BR.json index 44a3ef178..eb1aef222 100644 --- a/ui/src/i18n/locales/pt-BR.json +++ b/ui/src/i18n/locales/pt-BR.json @@ -3083,7 +3083,7 @@ "hooks.backupsHint": "Todo arquivo nativo tem backup antes de o Skillshare alterá-lo.", "hooks.restoreHint": "Restaurar mantém as alterações feitas depois do backup. Ele para se o arquivo foi editado desde então.", "hooks.importTitle": "Importar hooks", - "hooks.importHint": "Esses hooks ainda não são gerenciados pelo skillshare. Cada um marcado vira um hook assumido pelo skillshare, sem gravação duplicada. Os arquivos só são lidos, nunca executados.", + "hooks.importHint": "Hooks que suas ferramentas já executam e que o skillshare ainda não gerencia. O arquivo de configuração de um destino só muda depois que você revisar as alterações.", "hooks.importFrom": "Importar de", "hooks.importPaste": "Cole a configuração ou o código de um destino", "hooks.importPastePlaceholder": "Cole a seção hooks ou o código do plugin", @@ -3415,7 +3415,49 @@ "hooks.unmanaged.review": "Revisar e importar", "hooks.importNameFor": "Nome para {name}", "hooks.importPasteOpen": "Colar uma configuração ou código para importar", - "hooks.importSelected": "{count} selecionados", + "hooks.importTargets": "Destinos", + "hooks.importSelectAll": "Selecionar tudo em {target}", + "hooks.importPickedOf": "{picked} de {total} selecionados", + "hooks.importFooter.one": "{count} selecionado, de {targets} destino", + "hooks.importFooter.other": "{count} selecionados, de {targets} destinos", + "hooks.importFooterPending": "{count} selecionados para importar; alterações ainda não gravadas: {changes}", + "hooks.importNameLabel": "Nome no skillshare", + "hooks.importEdit": "Editar {name}", + "hooks.importRemove": "Remover {name} do destino", + "hooks.importEditAction": "Editar", + "hooks.importRemoveAction": "Remover do destino", + "hooks.importRemoveHook": "Remover este hook", + "hooks.importUndo": "Desfazer", + "hooks.importDone": "Concluído", + "hooks.importDiscard": "Descartar alterações", + "hooks.importWillRemove": "Será removido do arquivo de configuração de {target}", + "hooks.importChange.matcher": "Filtro alterado de {from} para {to}", + "hooks.importChange.command": "Comando {n} editado", + "hooks.importChange.edited": "Editado, ainda não gravado", + "hooks.importEditNote": "As alterações vão para {path} depois que você as revisar.", + "hooks.importNotEditable": "Este hook só pode ser alterado depois de importado.", + "hooks.importReview": "Revisar alterações", + "hooks.importReviewHint": "Nada é gravado até você escolher Aplicar alterações.", + "hooks.importApply": "Aplicar alterações", + "hooks.importSum.import": "Hooks a importar: {count}", + "hooks.importSum.importHint": "{list}. O skillshare assume esses hooks. Importar não altera o arquivo de configuração de um destino.", + "hooks.importSum.edit": "Hooks a editar: {count}", + "hooks.importSum.remove": "Hooks a remover: {count}", + "hooks.importSum.removeHint": "Excluído do arquivo de configuração de {target}, não importado.", + "hooks.importFiles": "Arquivos que serão gravados", + "hooks.importSum.count": "{target} {count}", + "hooks.importSum.listSep": ", ", + "hooks.importBackupNote.one": "Este arquivo é copiado para backup antes de ser gravado, e você pode restaurá-lo na página Backups.", + "hooks.importBackupNote.other": "Estes arquivos são copiados para backup antes de serem gravados, e você pode restaurá-los na página Backups.", + "hooks.importBackupOthers": "Os arquivos de {targets} não são alterados.", + "hooks.importWholeFile": "O arquivo inteiro é importado como um único hook", + "hooks.importPick": "Importar {name}", + "hooks.commandCount.one": "{count} comando", + "hooks.commandCount.other": "{count} comandos", + "hooks.toast.nativeChanged.one": "{count} alteração aplicada aos arquivos de destino", + "hooks.toast.nativeChanged.other": "{count} alterações aplicadas aos arquivos de destino", + "hooks.commandN": "Comando {n}", + "hooks.commandHint": "As quebras de linha são gravadas no arquivo de configuração como estão. Formatar altera só quebras de linha e indentação, nunca o comando.", "hooks.native.antigravity": "O IDE e a CLI do Antigravity leem o mesmo hooks.json (~/.gemini/config/hooks.json, ou .agents/hooks.json em um projeto). O Skillshare grava cada hook como um bloco com o nome dele.", "hooks.events.pretooluse": "Antes de uma ferramenta rodar; pode bloqueá-la", "hooks.events.posttooluse": "Depois que uma ferramenta termina", diff --git a/ui/src/i18n/locales/zh-CN.json b/ui/src/i18n/locales/zh-CN.json index c84a9c5ba..806d8310c 100644 --- a/ui/src/i18n/locales/zh-CN.json +++ b/ui/src/i18n/locales/zh-CN.json @@ -3083,7 +3083,7 @@ "hooks.backupsHint": "Skillshare 更改原生文件前,都会先备份。", "hooks.restoreHint": "还原时会保留备份之后的变更。若文件在那之后被编辑过,还原会中止。", "hooks.importTitle": "导入 hooks", - "hooks.importHint": "找到还没交给 skillshare 管理的 hook。勾选的会各自变成一个 hook,并由 skillshare 接手,不会重复写入。只会读取,不会执行。", + "hooks.importHint": "这些 hook 已经在你的工具里运行,但还没交给 skillshare 管理。目标的配置文件要等你检查变更后才会修改。", "hooks.importFrom": "导入来源", "hooks.importPaste": "粘贴目标的配置或代码", "hooks.importPastePlaceholder": "粘贴 hooks 段落或插件代码", @@ -3415,7 +3415,49 @@ "hooks.unmanaged.review": "查看并导入", "hooks.importNameFor": "{name} 的名称", "hooks.importPasteOpen": "粘贴配置或代码来导入", - "hooks.importSelected": "已选 {count} 个", + "hooks.importTargets": "目标", + "hooks.importSelectAll": "全选 {target}", + "hooks.importPickedOf": "已选 {picked} / {total}", + "hooks.importFooter.one": "已选 {count} 个,来自 {targets} 个目标", + "hooks.importFooter.other": "已选 {count} 个,来自 {targets} 个目标", + "hooks.importFooterPending": "已选 {count} 个要导入,另有 {changes} 项变更还没写入", + "hooks.importNameLabel": "在 skillshare 中的名称", + "hooks.importEdit": "编辑 {name}", + "hooks.importRemove": "从目标移除 {name}", + "hooks.importEditAction": "编辑", + "hooks.importRemoveAction": "从目标移除", + "hooks.importRemoveHook": "移除这个 hook", + "hooks.importUndo": "撤销", + "hooks.importDone": "完成", + "hooks.importDiscard": "放弃变更", + "hooks.importWillRemove": "会从 {target} 的配置文件移除", + "hooks.importChange.matcher": "筛选工具从 {from} 改成 {to}", + "hooks.importChange.command": "命令 {n} 已修改", + "hooks.importChange.edited": "已修改,还没写入", + "hooks.importEditNote": "变更会在你检查后写进 {path}。", + "hooks.importNotEditable": "这个 hook 要先导入才能修改。", + "hooks.importReview": "检查变更", + "hooks.importReviewHint": "点击“应用变更”之后才会写入。", + "hooks.importApply": "应用变更", + "hooks.importSum.import": "导入 {count} 个 hook", + "hooks.importSum.importHint": "{list}。由 skillshare 接手;导入本身不会改目标的配置文件。", + "hooks.importSum.edit": "修改 {count} 个 hook", + "hooks.importSum.remove": "移除 {count} 个 hook", + "hooks.importSum.removeHint": "会从 {target} 的配置文件删掉,不会导入。", + "hooks.importFiles": "会写入的文件", + "hooks.importSum.count": "{target} {count} 个", + "hooks.importSum.listSep": "、", + "hooks.importBackupNote.one": "写入前会先备份这个文件,可以在“备份”页还原。", + "hooks.importBackupNote.other": "写入前会先备份这些文件,可以在“备份”页还原。", + "hooks.importBackupOthers": "{targets} 的文件不会改动。", + "hooks.importWholeFile": "整个文件会当成一个 hook 导入", + "hooks.importPick": "导入 {name}", + "hooks.commandCount.one": "共 {count} 个命令", + "hooks.commandCount.other": "共 {count} 个命令", + "hooks.toast.nativeChanged.one": "已把 {count} 项变更写入目标的文件", + "hooks.toast.nativeChanged.other": "已把 {count} 项变更写入目标的文件", + "hooks.commandN": "命令 {n}", + "hooks.commandHint": "换行会原样写入配置文件。“格式化”只调整换行和缩进,不改命令内容。", "hooks.native.antigravity": "Antigravity 的 IDE 和 CLI 读同一个 hooks.json(~/.gemini/config/hooks.json,项目内为 .agents/hooks.json)。skillshare 会把每个 hook 写成以它命名的区块。", "hooks.events.pretooluse": "工具执行前,可以拦下", "hooks.events.posttooluse": "工具执行完之后", diff --git a/ui/src/i18n/locales/zh-TW.json b/ui/src/i18n/locales/zh-TW.json index 201687567..af6ca030d 100644 --- a/ui/src/i18n/locales/zh-TW.json +++ b/ui/src/i18n/locales/zh-TW.json @@ -3083,7 +3083,7 @@ "hooks.backupsHint": "Skillshare 更改原生檔案前,都會先備份。", "hooks.restoreHint": "還原時會保留備份之後的變更。若檔案在那之後被編輯過,還原會中止。", "hooks.importTitle": "匯入 hooks", - "hooks.importHint": "找到還沒交給 skillshare 管理的 hook。勾選的會各自變成一個 hook,並由 skillshare 接手,不會重複寫入。只會讀取,不會執行。", + "hooks.importHint": "這些 hook 已經在你的工具裡執行,但還沒交給 skillshare 管理。目標的設定檔要等你檢查變更後才會修改。", "hooks.importFrom": "匯入來源", "hooks.importPaste": "貼上目標的設定或程式碼", "hooks.importPastePlaceholder": "貼上 hooks 區段或外掛程式碼", @@ -3415,7 +3415,49 @@ "hooks.unmanaged.review": "檢視並匯入", "hooks.importNameFor": "{name} 的名稱", "hooks.importPasteOpen": "貼上設定或程式碼來匯入", - "hooks.importSelected": "已選 {count} 個", + "hooks.importTargets": "目標", + "hooks.importSelectAll": "全選 {target}", + "hooks.importPickedOf": "已選 {picked} / {total}", + "hooks.importFooter.one": "已選 {count} 個,來自 {targets} 個目標", + "hooks.importFooter.other": "已選 {count} 個,來自 {targets} 個目標", + "hooks.importFooterPending": "已選 {count} 個要匯入,另有 {changes} 項變更還沒寫入", + "hooks.importNameLabel": "在 skillshare 的名稱", + "hooks.importEdit": "編輯 {name}", + "hooks.importRemove": "從目標移除 {name}", + "hooks.importEditAction": "編輯", + "hooks.importRemoveAction": "從目標移除", + "hooks.importRemoveHook": "移除這個 hook", + "hooks.importUndo": "復原", + "hooks.importDone": "完成", + "hooks.importDiscard": "捨棄變更", + "hooks.importWillRemove": "會從 {target} 的設定檔移除", + "hooks.importChange.matcher": "篩選工具從 {from} 改成 {to}", + "hooks.importChange.command": "指令 {n} 已修改", + "hooks.importChange.edited": "已修改,還沒寫入", + "hooks.importEditNote": "變更會在你檢查後寫進 {path}。", + "hooks.importNotEditable": "這個 hook 要先匯入才能修改。", + "hooks.importReview": "檢視變更", + "hooks.importReviewHint": "按下「套用變更」之後才會寫入。", + "hooks.importApply": "套用變更", + "hooks.importSum.import": "匯入 {count} 個 hook", + "hooks.importSum.importHint": "{list}。由 skillshare 接手;匯入本身不會改目標的設定檔。", + "hooks.importSum.edit": "修改 {count} 個 hook", + "hooks.importSum.remove": "移除 {count} 個 hook", + "hooks.importSum.removeHint": "會從 {target} 的設定檔刪掉,不會匯入。", + "hooks.importFiles": "會寫入的檔案", + "hooks.importSum.count": "{target} {count} 個", + "hooks.importSum.listSep": "、", + "hooks.importBackupNote.one": "寫入前會先備份這個檔案,可以在「備份」頁還原。", + "hooks.importBackupNote.other": "寫入前會先備份這些檔案,可以在「備份」頁還原。", + "hooks.importBackupOthers": "{targets} 的檔案不會改動。", + "hooks.importWholeFile": "整個檔案會當成一個 hook 匯入", + "hooks.importPick": "匯入 {name}", + "hooks.commandCount.one": "共 {count} 個指令", + "hooks.commandCount.other": "共 {count} 個指令", + "hooks.toast.nativeChanged.one": "已把 {count} 項變更寫入目標的檔案", + "hooks.toast.nativeChanged.other": "已把 {count} 項變更寫入目標的檔案", + "hooks.commandN": "指令 {n}", + "hooks.commandHint": "可以換行,寫入設定檔時會原樣保留。「格式化」只調整換行和縮排,不改指令內容。", "hooks.native.antigravity": "Antigravity 的 IDE 和 CLI 讀同一個 hooks.json(~/.gemini/config/hooks.json,專案內為 .agents/hooks.json)。skillshare 會把每個 hook 寫成以它命名的區塊。", "hooks.events.pretooluse": "工具執行前,可以擋下", "hooks.events.posttooluse": "工具執行完之後", diff --git a/website/docs/reference/commands/hooks.md b/website/docs/reference/commands/hooks.md index 74e13cddf..5de95523b 100644 --- a/website/docs/reference/commands/hooks.md +++ b/website/docs/reference/commands/hooks.md @@ -44,6 +44,15 @@ Agent event or file; choose one name to save. Saving an import takes over the registrations it read in place: the next sync adopts them without `--replace`, and events you did not import stay unmanaged. Import only reads configuration or code and never runs it. + +The dashboard's import dialog can also edit or remove a hook in its Agent's +settings file without importing it. This works for Agents that keep hooks as +events in one settings file (Claude, Codex, Gemini, Cursor, Qwen, and Droid's +`hooks.json`); hooks +that are a whole file or a named block must be imported first. The dialog shows +the file diff before anything is written and backs the file up; the hook stays +unmanaged. + Add, edit, import, enable, disable and remove save source only unless `--sync` is supplied. Sync and restore always preview again before applying. `sync hooks` is the resource-only alias; `sync --all` includes hooks and checks diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/hooks.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/hooks.md index 5aef40176..a98a0b516 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/hooks.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/hooks.md @@ -30,7 +30,7 @@ skillshare hooks restore BACKUP_ID --dry-run skillshare hooks restore BACKUP_ID ``` -サブコマンドなしでは entries を一覧表示します。`add`/`edit` は `--file` の Entry JSON/YAML を読み込みます。インポートで名前を省略すると候補(Agent の event またはファイルごとに 1 件)を表示し、名前を指定すると保存します。インポートを保存すると、読み取った登録をその場で引き継ぎます。次回の同期は `--replace` なしで adopt し、インポートしなかった event は管理外のままです。設定とコードを読むだけで実行しません。追加、編集、インポート、有効化、無効化、削除はソースのみを保存し、`--sync` で同期します。同期と復元は適用前に再プレビューします。 +サブコマンドなしでは entries を一覧表示します。`add`/`edit` は `--file` の Entry JSON/YAML を読み込みます。インポートで名前を省略すると候補(Agent の event またはファイルごとに 1 件)を表示し、名前を指定すると保存します。インポートを保存すると、読み取った登録をその場で引き継ぎます。次回の同期は `--replace` なしで adopt し、インポートしなかった event は管理外のままです。設定とコードを読むだけで実行しません。追加、編集、インポート、有効化、無効化、削除はソースのみを保存し、`--sync` で同期します。同期と復元は適用前に再プレビューします。Dashboard のインポートダイアログでは、インポートしていない hook を Agent の設定ファイル内で直接編集・削除することもできます(hooks を 1 つの設定ファイルの event として持つ Agent のみ:Claude、Codex、Gemini、Cursor、Qwen、および Droid の `hooks.json`。ファイル単位や名前付きブロックの hook は先にインポートが必要です)。書き込み前にファイルの差分を表示してバックアップを取り、hook は管理外のままです。 | Option | Meaning | |---|---| diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/hooks.md b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/hooks.md index a5f801c9e..ce9175998 100644 --- a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/hooks.md +++ b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/hooks.md @@ -30,7 +30,7 @@ skillshare hooks restore BACKUP_ID --dry-run skillshare hooks restore BACKUP_ID ``` -하위 명령이 없으면 entries를 나열합니다. `add`/`edit`는 `--file`의 Entry JSON/YAML을 읽습니다. 이름 없는 가져오기는 후보(Agent event 또는 파일마다 하나)를 나열하고 이름을 지정하면 저장합니다. 가져오기를 저장하면 읽은 등록을 그 자리에서 인수합니다. 다음 동기화는 `--replace` 없이 adopt하며, 가져오지 않은 event는 관리되지 않은 채 남습니다. 설정과 코드만 읽고 실행하지 않습니다. 추가, 편집, 가져오기, 활성화, 비활성화, 제거는 소스만 저장하며 `--sync`를 붙이면 동기화합니다. 동기화와 복원은 적용 전 다시 미리 봅니다. +하위 명령이 없으면 entries를 나열합니다. `add`/`edit`는 `--file`의 Entry JSON/YAML을 읽습니다. 이름 없는 가져오기는 후보(Agent event 또는 파일마다 하나)를 나열하고 이름을 지정하면 저장합니다. 가져오기를 저장하면 읽은 등록을 그 자리에서 인수합니다. 다음 동기화는 `--replace` 없이 adopt하며, 가져오지 않은 event는 관리되지 않은 채 남습니다. 설정과 코드만 읽고 실행하지 않습니다. 추가, 편집, 가져오기, 활성화, 비활성화, 제거는 소스만 저장하며 `--sync`를 붙이면 동기화합니다. 동기화와 복원은 적용 전 다시 미리 봅니다. Dashboard의 가져오기 대화상자에서는 가져오지 않은 hook을 Agent 설정 파일에서 바로 편집하거나 제거할 수도 있습니다(hooks를 하나의 설정 파일 안 event로 두는 Agent만 해당: Claude, Codex, Gemini, Cursor, Qwen, 그리고 Droid의 `hooks.json`. 파일 전체이거나 이름 있는 블록인 hook은 먼저 가져와야 합니다). 쓰기 전에 파일 diff를 보여 주고 백업하며, hook은 관리되지 않은 상태로 남습니다. | Option | Meaning | |---|---| diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/hooks.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/hooks.md index 78beae03f..a31a9ffb2 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/hooks.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/hooks.md @@ -30,7 +30,7 @@ skillshare hooks restore BACKUP_ID --dry-run skillshare hooks restore BACKUP_ID ``` -没有子命令时列出 entries。`add`/`edit` 从 `--file` 读取 Entry JSON 或 YAML;导入不指定名称时列出候选项(每个 Agent event 或文件各一项),指定名称才保存。保存导入即原地接管读到的注册:下次同步直接 adopt,无需 `--replace`;未导入的 event 保持不受管理。导入只读取配置或代码,不执行。新增、编辑、导入、启用、停用与移除默认只保存来源,加上 `--sync` 才同步。同步与恢复会重新预览。 +没有子命令时列出 entries。`add`/`edit` 从 `--file` 读取 Entry JSON 或 YAML;导入不指定名称时列出候选项(每个 Agent event 或文件各一项),指定名称才保存。保存导入即原地接管读到的注册:下次同步直接 adopt,无需 `--replace`;未导入的 event 保持不受管理。导入只读取配置或代码,不执行。新增、编辑、导入、启用、停用与移除默认只保存来源,加上 `--sync` 才同步。同步与恢复会重新预览。Dashboard 的导入对话框也能直接修改或移除 Agent 配置文件里还没导入的 hook(限以 event 存在同一个配置文件的 Agent:Claude、Codex、Gemini、Cursor、Qwen,以及 Droid 的 `hooks.json`;整个文件或具名区块的 hook 要先导入)。写入前会显示文件差异并备份,该 hook 保持不受管理。 | Option | Meaning | |---|---| diff --git a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/hooks.md b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/hooks.md index c556720e7..dc2d4b1dc 100644 --- a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/hooks.md +++ b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/hooks.md @@ -30,7 +30,7 @@ skillshare hooks restore BACKUP_ID --dry-run skillshare hooks restore BACKUP_ID ``` -沒有子指令時列出 entries。`add`/`edit` 從 `--file` 讀取 Entry JSON 或 YAML;匯入不指定名稱時列出候選項目(每個 Agent event 或檔案各一項),指定名稱才儲存。儲存匯入即原地接管讀到的註冊:下次同步直接 adopt,不需 `--replace`;沒匯入的 event 維持不受管理。匯入只讀取設定或程式碼,不會執行。新增、編輯、匯入、啟用、停用與移除預設只儲存來源,加入 `--sync` 才同步。同步與還原會重新預覽。 +沒有子指令時列出 entries。`add`/`edit` 從 `--file` 讀取 Entry JSON 或 YAML;匯入不指定名稱時列出候選項目(每個 Agent event 或檔案各一項),指定名稱才儲存。儲存匯入即原地接管讀到的註冊:下次同步直接 adopt,不需 `--replace`;沒匯入的 event 維持不受管理。匯入只讀取設定或程式碼,不會執行。新增、編輯、匯入、啟用、停用與移除預設只儲存來源,加入 `--sync` 才同步。同步與還原會重新預覽。Dashboard 的匯入對話框也能直接修改或移除 Agent 設定檔裡還沒匯入的 hook(限以 event 存在同一個設定檔的 Agent:Claude、Codex、Gemini、Cursor、Qwen,以及 Droid 的 `hooks.json`;整個檔案或具名區塊的 hook 要先匯入)。寫入前會顯示檔案差異並備份,該 hook 維持不受管理。 | Option | Meaning | |---|---|