diff --git a/CHANGELOG.md b/CHANGELOG.md index f92140211..d66d6a340 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,12 @@ Extras (non-skill resources like rules, prompts, commands) are now a first-class skillshare extras init rules --target ~/.claude/rules --target ~/.cursor/rules skillshare extras init prompts --target .claude/prompts --mode copy -p ``` -- **`extras list`** — view all configured extras with sync status (`synced`, `drift`, `not synced`, `no source`). Supports `--json` output +- **`extras list`** — view all configured extras with sync status (`synced`, `drift`, `not synced`, `no source`). Interactive TUI with split-pane detail view, or `--json` / `--no-tui` output +- **`extras mode`** — change sync mode of an extra's target from CLI, TUI (`M` key), or Web UI: + ```bash + skillshare extras rules --mode copy # single target auto-resolved + skillshare extras mode rules --target ~/.claude/rules --mode copy + ``` - **`extras remove`** — remove an extra from config (source files and synced targets are preserved) - **`extras collect`** — reverse-sync local files from a target back into the extras source directory: ```bash @@ -47,9 +52,9 @@ The web dashboard (`skillshare ui`) received a complete visual overhaul — repl #### Web UI Extras Page -- New **Extras page** in the web dashboard with list, sync, remove, and add-extra modal +- New **Extras page** in the web dashboard with list, sync, remove, add-extra modal, and inline mode dropdown per target - **Dashboard card** showing extras count, total files, and total targets -- REST API: `GET /api/extras`, `GET /api/extras/diff`, `POST /api/extras`, `POST /api/extras/sync`, `DELETE /api/extras/{name}` +- REST API: `GET /api/extras`, `GET /api/extras/diff`, `POST /api/extras`, `POST /api/extras/sync`, `PATCH /api/extras/{name}/mode`, `DELETE /api/extras/{name}` #### Custom GitLab Domain Support @@ -91,6 +96,7 @@ The web dashboard (`skillshare ui`) received a complete visual overhaul — repl - **HTTPS fallback on non-GitLab hosts** — fixed platform-aware HTTPS URL parsing that could misroute GitHub Enterprise and Gitea URLs with subdirectory paths - **Skill discovery in projects** — `skillshare install` now skips known AI tool config directories (`.claude/`, `.cursor/`, etc.) when scanning a project directory for skills, preventing circular discovery and false duplicates - **Sync collision message** — `skillshare sync` now shows both duplicate skill names in collision warning messages for easier troubleshooting +- **Extras mode switch without `--force`** — changing an extra's sync mode (e.g., from `merge` to `copy`) and re-syncing now automatically replaces old symlinks. Previously, leftover symlinks from the old mode were treated as conflicts requiring `--force` ## [0.16.14] - 2026-03-09 diff --git a/cmd/skillshare/extras.go b/cmd/skillshare/extras.go index c97140939..0bd3ac4cc 100644 --- a/cmd/skillshare/extras.go +++ b/cmd/skillshare/extras.go @@ -20,10 +20,16 @@ func cmdExtras(args []string) error { return cmdExtrasRemove(rest) case "collect": return cmdExtrasCollect(rest) + case "mode": + return cmdExtrasMode(rest) case "--help", "-h": printExtrasHelp() return nil default: + // Shorthand: skillshare extras --mode + if hasFlag(args, "--mode") { + return cmdExtrasMode(args) + } return fmt.Errorf("unknown extras subcommand: %s (run 'skillshare extras --help')", sub) } } @@ -38,6 +44,7 @@ Commands: list List all configured extras and sync status (interactive TUI) remove Remove an extra resource type collect Collect local files from a target into extras source + mode Change sync mode of an extra's target Options: --project, -p Use project-mode extras (.skillshare/) diff --git a/cmd/skillshare/extras_init_tui.go b/cmd/skillshare/extras_init_tui.go index b7db66f80..faafdf807 100644 --- a/cmd/skillshare/extras_init_tui.go +++ b/cmd/skillshare/extras_init_tui.go @@ -37,7 +37,7 @@ type extrasInitTUIModel struct { err error } -var syncModes = []string{"merge", "copy", "symlink"} +var syncModes = config.ExtraSyncModes func newExtrasInitTUIModel() extrasInitTUIModel { ti := textinput.New() diff --git a/cmd/skillshare/extras_list_tui.go b/cmd/skillshare/extras_list_tui.go index 8ba4dd49b..44d28e608 100644 --- a/cmd/skillshare/extras_list_tui.go +++ b/cmd/skillshare/extras_list_tui.go @@ -85,6 +85,12 @@ type extrasListTUIModel struct { targetCursor int targetAction string + // Mode picker + showModePicker bool + modePickerTarget string // target path being edited + modePickerExtra string + modeCursor int + // Action feedback lastActionMsg string } @@ -230,6 +236,10 @@ func (m extrasListTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.handleTargetMenuKey(msg) } + if m.showModePicker { + return m.handleModePickerKey(msg) + } + if m.filtering { switch msg.String() { case "esc": @@ -285,6 +295,8 @@ func (m extrasListTUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.enterTargetMenu("sync") case "C": return m.enterTargetMenu("collect") + case "M": + return m.enterTargetMenu("mode") } } @@ -316,6 +328,9 @@ func (m extrasListTUIModel) View() string { if m.showTargetMenu { return m.renderTargetMenu() } + if m.showModePicker { + return m.renderModePicker() + } if extrasSplitActive(m.termWidth) { return m.viewExtrasSplit() } @@ -432,6 +447,7 @@ func (m extrasListTUIModel) renderExtrasDetail(e extrasListEntry) string { if len(e.Targets) == 0 { b.WriteString(tc.Dim.Render(" No targets configured") + "\n") } else { + hasDrift := false for _, t := range e.Targets { var icon string var style lipgloss.Style @@ -442,9 +458,11 @@ func (m extrasListTUIModel) renderExtrasDetail(e extrasListEntry) string { case "drift": icon = "△" style = tc.Yellow + hasDrift = true case "not synced": icon = "✗" style = tc.Red + hasDrift = true default: icon = "-" style = tc.Dim @@ -456,6 +474,9 @@ func (m extrasListTUIModel) renderExtrasDetail(e extrasListEntry) string { fmt.Fprintf(&b, " %s %s (%s)%s\n", style.Render(icon), shortenPath(t.Path), t.Mode, tc.Dim.Render(statusText)) } + if hasDrift { + b.WriteString("\n" + tc.Yellow.Render("hint:") + " press S to sync, or use --force to overwrite conflicts\n") + } } if e.SourceExists && e.FileCount > 0 { @@ -499,7 +520,7 @@ func (m extrasListTUIModel) renderExtrasFilterBar() string { } func (m extrasListTUIModel) renderExtrasHelp(scrollInfo string) string { - helpText := "↑↓ navigate / filter Enter view N new X remove S sync C collect q quit" + helpText := "↑↓ navigate / filter Enter view N new X remove S sync C collect M mode q quit" if m.filtering { helpText = "Enter lock Esc clear q quit" } @@ -629,7 +650,7 @@ func (m extrasListTUIModel) renderConfirmOverlay() string { body = fmt.Sprintf("Collect from %s into %q?", target, m.confirmExtra) } - return fmt.Sprintf("\n %s\n\n %s\n\n Proceed? [Y/n] ", + return fmt.Sprintf("\n%s\n\n%s\n\nProceed? [Y/n] ", tc.Title.Render(title), body) } @@ -644,7 +665,11 @@ func (m extrasListTUIModel) enterTargetMenu(action string) (tea.Model, tea.Cmd) m.lastActionMsg = "✗ No targets configured" return m, nil } + // Single target: skip menu for sync/collect/mode if len(item.entry.Targets) == 1 { + if action == "mode" { + return m.openModePicker(item.entry.Name, item.entry.Targets[0]) + } m.confirmExtra = item.entry.Name m.confirmAction = action m.confirmTarget = item.entry.Targets[0].Path @@ -661,7 +686,11 @@ func (m extrasListTUIModel) enterTargetMenu(action string) (tea.Model, tea.Cmd) } func (m extrasListTUIModel) handleTargetMenuKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + // "mode" has no "All targets" row totalItems := len(m.targetMenuItems) + 1 + if m.targetAction == "mode" { + totalItems = len(m.targetMenuItems) + } switch msg.String() { case "q", "esc": @@ -685,6 +714,13 @@ func (m extrasListTUIModel) handleTargetMenuKey(msg tea.KeyMsg) (tea.Model, tea. return m, nil } m.showTargetMenu = false + + // Mode action: no "All targets", go directly to mode picker + if m.targetAction == "mode" { + t := m.targetMenuItems[m.targetCursor] + return m.openModePicker(item.entry.Name, t) + } + m.confirmExtra = item.entry.Name m.confirmAction = m.targetAction if m.targetCursor == 0 { @@ -702,30 +738,151 @@ func (m extrasListTUIModel) renderTargetMenu() string { var b strings.Builder title := "Sync targets" - if m.targetAction == "collect" { + switch m.targetAction { + case "collect": title = "Collect from" + case "mode": + title = "Change mode" } - fmt.Fprintf(&b, "\n %s\n\n", tc.Title.Render(title)) + fmt.Fprintf(&b, "\n%s\n\n", tc.Title.Render(title)) - for i := 0; i <= len(m.targetMenuItems); i++ { - prefix := " " - if i == m.targetCursor { - prefix = tc.Cyan.Render(">") + " " + if m.targetAction == "mode" { + // No "All targets" for mode — list targets directly + for i, t := range m.targetMenuItems { + prefix := " " + if i == m.targetCursor { + prefix = tc.Cyan.Render(">") + " " + } + fmt.Fprintf(&b, "%s%s (%s)\n", prefix, shortenPath(t.Path), t.Mode) } - if i == 0 { - fmt.Fprintf(&b, " %s%s\n", prefix, "All targets") - } else { - t := m.targetMenuItems[i-1] - fmt.Fprintf(&b, " %s%s (%s)\n", prefix, shortenPath(t.Path), t.Mode) + } else { + for i := 0; i <= len(m.targetMenuItems); i++ { + prefix := " " + if i == m.targetCursor { + prefix = tc.Cyan.Render(">") + " " + } + if i == 0 { + fmt.Fprintf(&b, "%s%s\n", prefix, "All targets") + } else { + t := m.targetMenuItems[i-1] + fmt.Fprintf(&b, "%s%s (%s)\n", prefix, shortenPath(t.Path), t.Mode) + } } } - fmt.Fprintf(&b, "\n %s\n", tc.Help.Render("↑↓ select Enter confirm Esc cancel")) + fmt.Fprintf(&b, "\n%s\n", tc.Help.Render("↑↓ select Enter confirm Esc cancel")) return b.String() } +// ─── Mode Picker ───────────────────────────────────────────────────── + +var extrasSyncModes = config.ExtraSyncModes + +func (m extrasListTUIModel) openModePicker(extraName string, t extrasTargetInfo) (tea.Model, tea.Cmd) { + m.showModePicker = true + m.modePickerExtra = extraName + m.modePickerTarget = t.Path + m.modeCursor = 0 + current := sync.EffectiveMode(t.Mode) + for i, mode := range extrasSyncModes { + if mode == current { + m.modeCursor = i + break + } + } + m.lastActionMsg = "" + return m, nil +} + +func (m extrasListTUIModel) handleModePickerKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.String() { + case "q", "esc": + m.showModePicker = false + return m, nil + case "up", "k": + if m.modeCursor > 0 { + m.modeCursor-- + } + return m, nil + case "down", "j": + if m.modeCursor < len(extrasSyncModes)-1 { + m.modeCursor++ + } + return m, nil + case "enter": + m.showModePicker = false + newMode := extrasSyncModes[m.modeCursor] + name := m.modePickerExtra + target := m.modePickerTarget + return m, func() tea.Msg { + msg, err := m.doSetMode(name, target, newMode) + return extrasActionDoneMsg{msg: msg, err: err} + } + } + return m, nil +} + +func (m extrasListTUIModel) renderModePicker() string { + var b strings.Builder + + fmt.Fprintf(&b, "\n%s\n", tc.Title.Render("Change mode")) + fmt.Fprintf(&b, "%s %s\n\n", tc.Dim.Render("Extra:"), m.modePickerExtra) + fmt.Fprintf(&b, "%s %s\n\n", tc.Dim.Render("Target:"), shortenPath(m.modePickerTarget)) + + for i, mode := range extrasSyncModes { + cursor := " " + if i == m.modeCursor { + cursor = tc.Cyan.Render(">") + " " + } + var desc string + switch mode { + case "merge": + desc = " (per-file symlinks)" + case "copy": + desc = " (file copies)" + case "symlink": + desc = " (directory symlink)" + } + if i == m.modeCursor { + fmt.Fprintf(&b, "%s%s%s\n", cursor, tc.Cyan.Render(mode), tc.Dim.Render(desc)) + } else { + fmt.Fprintf(&b, "%s%s%s\n", cursor, mode, tc.Dim.Render(desc)) + } + } + + fmt.Fprintf(&b, "\n%s\n", tc.Help.Render("↑↓ select Enter confirm Esc cancel")) + return b.String() +} + +func (m extrasListTUIModel) doSetMode(name, targetPath, newMode string) (string, error) { + if m.projCfg != nil { + projCfg, err := config.LoadProject(m.cwd) + if err != nil { + return "", err + } + if err := setExtraTargetMode(projCfg.Extras, name, targetPath, newMode); err != nil { + return "", err + } + if err := projCfg.Save(m.cwd); err != nil { + return "", err + } + } else { + cfg, err := config.Load() + if err != nil { + return "", err + } + if err := setExtraTargetMode(cfg.Extras, name, targetPath, newMode); err != nil { + return "", err + } + if err := cfg.Save(); err != nil { + return "", err + } + } + return fmt.Sprintf("✓ Set %s → %s to %s", name, shortenPath(targetPath), newMode), nil +} + // ─── Action Execution ──────────────────────────────────────────────── func (m extrasListTUIModel) executeAction() tea.Cmd { diff --git a/cmd/skillshare/extras_mode.go b/cmd/skillshare/extras_mode.go new file mode 100644 index 000000000..282b4ec0b --- /dev/null +++ b/cmd/skillshare/extras_mode.go @@ -0,0 +1,167 @@ +package main + +import ( + "fmt" + "os" + "time" + + "skillshare/internal/config" + "skillshare/internal/oplog" + "skillshare/internal/ui" +) + +func cmdExtrasMode(args []string) error { + start := time.Now() + + mode, rest, err := parseModeArgs(args) + if err != nil { + return err + } + + cwd, _ := os.Getwd() + if mode == modeAuto { + if projectConfigExists(cwd) { + mode = modeProject + } else { + mode = modeGlobal + } + } + + applyModeLabel(mode) + + var name, targetPath, syncMode string + for i := 0; i < len(rest); i++ { + switch rest[i] { + case "--target": + if i+1 >= len(rest) { + return fmt.Errorf("--target requires a path argument") + } + i++ + targetPath = rest[i] + case "--mode": + if i+1 >= len(rest) { + return fmt.Errorf("--mode requires an argument (merge/copy/symlink)") + } + i++ + syncMode = rest[i] + case "--help", "-h": + printExtrasModeHelp() + return nil + default: + if name == "" { + name = rest[i] + } else { + return fmt.Errorf("unexpected argument: %s", rest[i]) + } + } + } + + if name == "" { + return fmt.Errorf("extras name is required: skillshare extras --mode [--target ]") + } + if syncMode == "" { + return fmt.Errorf("--mode is required") + } + + if err := config.ValidateExtraMode(syncMode); err != nil { + return err + } + + // Load config to resolve target when --target is omitted + var extras []config.ExtraConfig + var configPath string + var saveFn func() error + + if mode == modeProject { + projCfg, loadErr := config.LoadProject(cwd) + if loadErr != nil { + return loadErr + } + extras = projCfg.Extras + configPath = config.ProjectConfigPath(cwd) + saveFn = func() error { return projCfg.Save(cwd) } + } else { + cfg, loadErr := config.Load() + if loadErr != nil { + return loadErr + } + extras = cfg.Extras + configPath = config.ConfigPath() + saveFn = cfg.Save + } + + // Auto-resolve target when omitted + if targetPath == "" { + for _, extra := range extras { + if extra.Name == name { + switch len(extra.Targets) { + case 0: + return fmt.Errorf("extra %q has no targets", name) + case 1: + targetPath = extra.Targets[0].Path + default: + return fmt.Errorf("extra %q has %d targets — use --target to specify which one", name, len(extra.Targets)) + } + break + } + } + if targetPath == "" { + return fmt.Errorf("extra %q not found", name) + } + } + + if err := setExtraTargetMode(extras, name, targetPath, syncMode); err != nil { + return err + } + if err := saveFn(); err != nil { + return fmt.Errorf("failed to save config: %w", err) + } + + ui.Success("Set mode of %s target %s to %s", name, shortenPath(targetPath), syncMode) + + e := oplog.NewEntry("extras-mode", "ok", time.Since(start)) + e.Args = map[string]any{"name": name, "target": targetPath, "mode": syncMode} + oplog.WriteWithLimit(configPath, oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck + + return nil +} + +// setExtraTargetMode finds an extra by name and sets the mode on a specific target. +// Operates on the extras slice in-place (caller must save config). +func setExtraTargetMode(extras []config.ExtraConfig, name, targetPath, mode string) error { + for i, extra := range extras { + if extra.Name != name { + continue + } + for j, t := range extra.Targets { + if t.Path == targetPath { + extras[i].Targets[j].Mode = mode + return nil + } + } + return fmt.Errorf("target %q not found in extra %q", targetPath, name) + } + return fmt.Errorf("extra %q not found", name) +} + +func printExtrasModeHelp() { + fmt.Println(`Usage: skillshare extras mode --mode [--target ] + skillshare extras --mode [--target ] + +Change the sync mode of an extra's target. + +Arguments: + name Extra name (e.g., rules, commands) + +Options: + --mode New sync mode: merge, copy, or symlink + --target Target directory path (optional if extra has only one target) + --project, -p Use project mode (.skillshare/) + --global, -g Use global mode (~/.config/skillshare/) + --help, -h Show this help + +Examples: + skillshare extras rules --mode copy + skillshare extras mode rules --target ~/.claude/rules --mode copy + skillshare extras mode commands --target ~/.cursor/commands --mode symlink -p`) +} diff --git a/internal/config/extras_validate.go b/internal/config/extras_validate.go index a21631010..4a96b77c6 100644 --- a/internal/config/extras_validate.go +++ b/internal/config/extras_validate.go @@ -3,6 +3,7 @@ package config import ( "fmt" "regexp" + "slices" ) var extraNameRegex = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]*$`) @@ -29,15 +30,19 @@ func ValidateExtraName(name string) error { return nil } +// ExtraSyncModes is the authoritative list of valid extras sync modes. +var ExtraSyncModes = []string{"merge", "copy", "symlink"} + // ValidateExtraMode checks that mode is a valid sync mode. // Empty string is allowed (defaults to "merge" at runtime). func ValidateExtraMode(mode string) error { - switch mode { - case "", "merge", "copy", "symlink": + if mode == "" { return nil - default: + } + if !slices.Contains(ExtraSyncModes, mode) { return fmt.Errorf("invalid mode %q: must be merge, copy, or symlink", mode) } + return nil } // ValidateExtraNameUnique checks that the name doesn't duplicate an existing extra. diff --git a/internal/server/handler_extras.go b/internal/server/handler_extras.go index c3318e983..81443717b 100644 --- a/internal/server/handler_extras.go +++ b/internal/server/handler_extras.go @@ -380,6 +380,77 @@ func (s *Server) handleExtrasSync(w http.ResponseWriter, r *http.Request) { writeJSON(w, map[string]any{"results": results}) } +// handleExtrasMode — PATCH /api/extras/{name}/mode +func (s *Server) handleExtrasMode(w http.ResponseWriter, r *http.Request) { + start := time.Now() + name := r.PathValue("name") + + var body struct { + Target string `json:"target"` + Mode string `json:"mode"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + + if body.Target == "" { + writeError(w, http.StatusBadRequest, "target is required") + return + } + if err := config.ValidateExtraMode(body.Mode); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + + s.mu.Lock() + defer s.mu.Unlock() + + extras := s.extrasConfig() + + // Find extra and target, update mode in-place + found := false + for i, extra := range extras { + if extra.Name != name { + continue + } + for j, t := range extra.Targets { + if t.Path == body.Target { + extras[i].Targets[j].Mode = body.Mode + found = true + break + } + } + if !found { + writeError(w, http.StatusNotFound, "target not found: "+body.Target) + return + } + break + } + if !found { + writeError(w, http.StatusNotFound, "extra not found: "+name) + return + } + + if err := s.saveConfig(); err != nil { + writeError(w, http.StatusInternalServerError, "failed to save config: "+err.Error()) + return + } + if err := s.reloadConfig(); err != nil { + writeError(w, http.StatusInternalServerError, "failed to reload config: "+err.Error()) + return + } + + s.writeOpsLog("extras-mode", "ok", start, map[string]any{ + "name": name, + "target": body.Target, + "mode": body.Mode, + "scope": "ui", + }, "") + + writeJSON(w, map[string]any{"success": true, "name": name, "target": body.Target, "mode": body.Mode}) +} + // handleExtrasDelete — DELETE /api/extras/{name} func (s *Server) handleExtrasDelete(w http.ResponseWriter, r *http.Request) { start := time.Now() diff --git a/internal/server/server.go b/internal/server/server.go index 2184f81db..bc20c9f31 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -305,6 +305,7 @@ func (s *Server) registerRoutes() { s.mux.HandleFunc("GET /api/extras/diff", s.handleExtrasDiff) s.mux.HandleFunc("POST /api/extras", s.handleExtrasCreate) s.mux.HandleFunc("POST /api/extras/sync", s.handleExtrasSync) + s.mux.HandleFunc("PATCH /api/extras/{name}/mode", s.handleExtrasMode) s.mux.HandleFunc("DELETE /api/extras/{name}", s.handleExtrasDelete) // Git diff --git a/internal/sync/extras.go b/internal/sync/extras.go index 0e8406db9..c68a9b099 100644 --- a/internal/sync/extras.go +++ b/internal/sync/extras.go @@ -194,37 +194,31 @@ func syncOneExtraFile(srcFile, tgtFile, mode string, dryRun, force bool) (int, i // Check if target already exists info, lstatErr := os.Lstat(tgtFile) if lstatErr == nil { - // Target exists - if mode == "merge" && info.Mode()&os.ModeSymlink != 0 { - // It's a symlink — check if it points to our source + isSymlink := info.Mode()&os.ModeSymlink != 0 + + // Already correct? → skip (idempotent) + if mode == "merge" && isSymlink { dest, readErr := os.Readlink(tgtFile) if readErr == nil { absDest, _ := filepath.Abs(dest) if absDest == srcFile { - // Already correct symlink return 1, 0, nil } } - // Wrong symlink — treat as conflict } - - if mode == "copy" && info.Mode()&os.ModeSymlink == 0 && !info.IsDir() { - // Regular file — check if content matches source (idempotent) + if mode == "copy" && !isSymlink && !info.IsDir() { srcInfo, srcErr := os.Stat(srcFile) - if srcErr == nil && srcInfo.Size() == info.Size() { - if contentEqual(srcFile, tgtFile) { - return 1, 0, nil - } + if srcErr == nil && srcInfo.Size() == info.Size() && contentEqual(srcFile, tgtFile) { + return 1, 0, nil } - // Content differs — treat as conflict } - // Conflict: target exists and is not our symlink / matching copy - if !force { + // Symlinks left over from a different mode are safe to replace + autoReplace := isSymlink + if !autoReplace && !force { return 0, 1, nil } - // Force: remove and replace if !dryRun { if err := os.Remove(tgtFile); err != nil { return 0, 0, fmt.Errorf("failed to remove conflicting file: %w", err) diff --git a/skills/skillshare/SKILL.md b/skills/skillshare/SKILL.md index 228f39871..127796756 100644 --- a/skills/skillshare/SKILL.md +++ b/skills/skillshare/SKILL.md @@ -48,6 +48,7 @@ skillshare extras list # Show status per target skillshare extras list --json # JSON output skillshare extras collect rules # Pull local files into source skillshare extras remove rules # Remove from config (source preserved) +skillshare extras rules --mode copy # Change sync mode of a target skillshare sync extras # Sync all extras to targets skillshare sync extras --dry-run --force # Preview / overwrite conflicts skillshare sync --all # Sync skills + extras together @@ -130,7 +131,7 @@ See [TROUBLESHOOTING.md](references/TROUBLESHOOTING.md) for more. | `sync`, `collect` | ✓ (auto) | ✓ | | `install`, `uninstall`, `update`, `check`, `search`, `new` | ✓ (`-p`) | ✓ (except new) | | `target`, `audit`, `trash`, `log`, `hub` | ✓ (`-p`) | ✓ (target list, audit, log) | -| `extras init/list/remove/collect` | ✓ (`-p`) | ✓ (list) | +| `extras init/list/remove/collect/mode` | ✓ (`-p`) | ✓ (list, mode) | | `push`, `pull`, `backup`, `restore` | ✗ | ✗ | | `tui`, `upgrade` | ✗ | ✗ | | `ui` | ✓ (`-p`) | ✗ | diff --git a/tests/integration/extras_test.go b/tests/integration/extras_test.go index 04e7c680c..0bf6f9f90 100644 --- a/tests/integration/extras_test.go +++ b/tests/integration/extras_test.go @@ -571,3 +571,185 @@ extras: t.Error("migrated file should be synced as symlink in target") } } + +// TestExtras_Mode_SingleTarget verifies that "extras mode" changes the sync mode +// of an extra's target when the extra has only one target (auto-resolved). +func TestExtras_Mode_SingleTarget(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + rulesTarget := filepath.Join(sb.Home, ".claude", "rules") + os.MkdirAll(rulesTarget, 0755) + + rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules") + os.MkdirAll(rulesSource, 0755) + os.WriteFile(filepath.Join(rulesSource, "coding.md"), []byte("# Coding"), 0644) + + claudeTarget := sb.CreateTarget("claude") + sb.WriteConfig(`source: ` + sb.SourcePath + ` +targets: + claude: + path: ` + claudeTarget + ` +extras: + - name: rules + targets: + - path: ` + rulesTarget + ` +`) + + // Change mode from merge (default) to copy + result := sb.RunCLI("extras", "mode", "rules", "--mode", "copy", "-g") + + result.AssertSuccess(t) + result.AssertAnyOutputContains(t, "copy") + + // Verify config was updated + configContent := sb.ReadFile(sb.ConfigPath) + if !strings.Contains(configContent, "mode: copy") { + t.Errorf("expected config to contain 'mode: copy', got:\n%s", configContent) + } +} + +// TestExtras_Mode_Shorthand verifies the shorthand form: +// "extras --mode " (without the "mode" subcommand). +func TestExtras_Mode_Shorthand(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + rulesTarget := filepath.Join(sb.Home, ".claude", "rules") + os.MkdirAll(rulesTarget, 0755) + + rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules") + os.MkdirAll(rulesSource, 0755) + + claudeTarget := sb.CreateTarget("claude") + sb.WriteConfig(`source: ` + sb.SourcePath + ` +targets: + claude: + path: ` + claudeTarget + ` +extras: + - name: rules + targets: + - path: ` + rulesTarget + ` +`) + + // Use shorthand: extras rules --mode symlink + result := sb.RunCLI("extras", "rules", "--mode", "symlink", "-g") + + result.AssertSuccess(t) + result.AssertAnyOutputContains(t, "symlink") + + configContent := sb.ReadFile(sb.ConfigPath) + if !strings.Contains(configContent, "mode: symlink") { + t.Errorf("expected config to contain 'mode: symlink', got:\n%s", configContent) + } +} + +// TestExtras_Mode_WithTarget verifies that "extras mode" with --target +// changes the mode on a specific target when multiple targets exist. +func TestExtras_Mode_WithTarget(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + rulesTarget1 := filepath.Join(sb.Home, ".claude", "rules") + rulesTarget2 := filepath.Join(sb.Home, ".cursor", "rules") + os.MkdirAll(rulesTarget1, 0755) + os.MkdirAll(rulesTarget2, 0755) + + rulesSource := filepath.Join(sb.Home, ".config", "skillshare", "extras", "rules") + os.MkdirAll(rulesSource, 0755) + + claudeTarget := sb.CreateTarget("claude") + sb.WriteConfig(`source: ` + sb.SourcePath + ` +targets: + claude: + path: ` + claudeTarget + ` +extras: + - name: rules + targets: + - path: ` + rulesTarget1 + ` + - path: ` + rulesTarget2 + ` +`) + + // Change mode of second target only + result := sb.RunCLI("extras", "mode", "rules", "--target", rulesTarget2, "--mode", "copy", "-g") + + result.AssertSuccess(t) + + configContent := sb.ReadFile(sb.ConfigPath) + // The second target should have mode: copy, first should remain default (merge) + if !strings.Contains(configContent, "mode: copy") { + t.Errorf("expected config to contain 'mode: copy' for second target, got:\n%s", configContent) + } +} + +// TestExtras_Mode_MultipleTargets_NoTarget verifies that "extras mode" errors +// when the extra has multiple targets and --target is not specified. +func TestExtras_Mode_MultipleTargets_NoTarget(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + rulesTarget1 := filepath.Join(sb.Home, ".claude", "rules") + rulesTarget2 := filepath.Join(sb.Home, ".cursor", "rules") + os.MkdirAll(rulesTarget1, 0755) + os.MkdirAll(rulesTarget2, 0755) + + claudeTarget := sb.CreateTarget("claude") + sb.WriteConfig(`source: ` + sb.SourcePath + ` +targets: + claude: + path: ` + claudeTarget + ` +extras: + - name: rules + targets: + - path: ` + rulesTarget1 + ` + - path: ` + rulesTarget2 + ` +`) + + result := sb.RunCLI("extras", "mode", "rules", "--mode", "copy", "-g") + + result.AssertFailure(t) + result.AssertAnyOutputContains(t, "--target") +} + +// TestExtras_Mode_InvalidMode verifies that an invalid mode is rejected. +func TestExtras_Mode_InvalidMode(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + rulesTarget := filepath.Join(sb.Home, ".claude", "rules") + os.MkdirAll(rulesTarget, 0755) + + claudeTarget := sb.CreateTarget("claude") + sb.WriteConfig(`source: ` + sb.SourcePath + ` +targets: + claude: + path: ` + claudeTarget + ` +extras: + - name: rules + targets: + - path: ` + rulesTarget + ` +`) + + result := sb.RunCLI("extras", "mode", "rules", "--mode", "invalid", "-g") + + result.AssertFailure(t) + result.AssertAnyOutputContains(t, "invalid") +} + +// TestExtras_Mode_UnknownExtra verifies that mode change on non-existent extra fails. +func TestExtras_Mode_UnknownExtra(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + claudeTarget := sb.CreateTarget("claude") + sb.WriteConfig(`source: ` + sb.SourcePath + ` +targets: + claude: + path: ` + claudeTarget + ` +`) + + result := sb.RunCLI("extras", "mode", "nonexistent", "--mode", "copy", "-g") + + result.AssertFailure(t) + result.AssertAnyOutputContains(t, "not found") +} diff --git a/tests/integration/sync_extras_test.go b/tests/integration/sync_extras_test.go index 30f895d80..882596891 100644 --- a/tests/integration/sync_extras_test.go +++ b/tests/integration/sync_extras_test.go @@ -238,6 +238,148 @@ extras: } } +// TestSyncExtras_ModeSwitchMergeToCopy verifies that switching mode from merge +// to copy and re-syncing replaces symlinks with copies without needing --force. +func TestSyncExtras_ModeSwitchMergeToCopy(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + sb.CreateSkill("placeholder", map[string]string{ + "SKILL.md": "# Placeholder", + }) + targetPath := sb.CreateTarget("claude") + + // Create extras source + sourceRoot := filepath.Dir(sb.SourcePath) + rulesSource := filepath.Join(sourceRoot, "extras", "rules") + os.MkdirAll(rulesSource, 0755) + os.WriteFile(filepath.Join(rulesSource, "coding.md"), []byte("# Coding Rules"), 0644) + + rulesTarget := filepath.Join(sb.Home, ".claude", "rules") + os.MkdirAll(rulesTarget, 0755) + + // Step 1: Sync with merge mode (creates symlinks) + sb.WriteConfig(`source: ` + sb.SourcePath + ` +targets: + claude: + path: ` + targetPath + ` +extras: + - name: rules + targets: + - path: ` + rulesTarget + ` +`) + + result := sb.RunCLI("sync", "extras") + result.AssertSuccess(t) + + codingFile := filepath.Join(rulesTarget, "coding.md") + if !sb.IsSymlink(codingFile) { + t.Fatal("coding.md should be a symlink after merge sync") + } + + // Step 2: Change mode to copy and re-sync + sb.WriteConfig(`source: ` + sb.SourcePath + ` +targets: + claude: + path: ` + targetPath + ` +extras: + - name: rules + targets: + - path: ` + rulesTarget + ` + mode: copy +`) + + result = sb.RunCLI("sync", "extras") + result.AssertSuccess(t) + + // Verify: file should now be a regular copy, not a symlink + if sb.IsSymlink(codingFile) { + t.Error("coding.md should be a regular file after switching to copy mode, but is still a symlink") + } + if !sb.FileExists(codingFile) { + t.Fatal("coding.md should exist in target after copy sync") + } + + content := sb.ReadFile(codingFile) + if content != "# Coding Rules" { + t.Errorf("copied file content = %q, want %q", content, "# Coding Rules") + } +} + +// TestSyncExtras_ModeSwitchCopyToMerge verifies that switching mode from copy +// to merge and re-syncing replaces copies with symlinks (requires --force since +// regular files are not auto-replaced). +func TestSyncExtras_ModeSwitchCopyToMerge(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + sb.CreateSkill("placeholder", map[string]string{ + "SKILL.md": "# Placeholder", + }) + targetPath := sb.CreateTarget("claude") + + // Create extras source + sourceRoot := filepath.Dir(sb.SourcePath) + rulesSource := filepath.Join(sourceRoot, "extras", "rules") + os.MkdirAll(rulesSource, 0755) + os.WriteFile(filepath.Join(rulesSource, "coding.md"), []byte("# Coding Rules"), 0644) + + rulesTarget := filepath.Join(sb.Home, ".claude", "rules") + os.MkdirAll(rulesTarget, 0755) + + // Step 1: Sync with copy mode + sb.WriteConfig(`source: ` + sb.SourcePath + ` +targets: + claude: + path: ` + targetPath + ` +extras: + - name: rules + targets: + - path: ` + rulesTarget + ` + mode: copy +`) + + result := sb.RunCLI("sync", "extras") + result.AssertSuccess(t) + + codingFile := filepath.Join(rulesTarget, "coding.md") + if sb.IsSymlink(codingFile) { + t.Fatal("coding.md should be a regular file after copy sync") + } + + // Step 2: Change mode to merge and sync WITHOUT --force (should skip) + sb.WriteConfig(`source: ` + sb.SourcePath + ` +targets: + claude: + path: ` + targetPath + ` +extras: + - name: rules + targets: + - path: ` + rulesTarget + ` +`) + + result = sb.RunCLI("sync", "extras") + result.AssertSuccess(t) + + // File should still be a regular file (skipped because no --force) + if sb.IsSymlink(codingFile) { + t.Error("coding.md should still be a regular file without --force") + } + + // Step 3: Sync WITH --force (should replace with symlink) + result = sb.RunCLI("sync", "extras", "--force") + result.AssertSuccess(t) + + if !sb.IsSymlink(codingFile) { + t.Error("coding.md should be a symlink after --force sync with merge mode") + } + + expectedTarget := filepath.Join(rulesSource, "coding.md") + if got := sb.SymlinkTarget(codingFile); got != expectedTarget { + t.Errorf("symlink target = %q, want %q", got, expectedTarget) + } +} + func TestSyncExtras_SourceNotExist(t *testing.T) { sb := testutil.NewSandbox(t) defer sb.Cleanup() diff --git a/ui/src/api/client.ts b/ui/src/api/client.ts index 8fbca060a..aa09f98ca 100644 --- a/ui/src/api/client.ts +++ b/ui/src/api/client.ts @@ -302,6 +302,11 @@ export const api = { }), deleteExtra: (name: string) => apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}`, { method: 'DELETE' }), + setExtraMode: (name: string, target: string, mode: string) => + apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}/mode`, { + method: 'PATCH', + body: JSON.stringify({ target, mode }), + }), // Log listLog: (type?: string, limit?: number, filters?: { cmd?: string; status?: string; since?: string }) => { diff --git a/ui/src/components/Select.tsx b/ui/src/components/Select.tsx index 4eb2b779d..e30a639ec 100644 --- a/ui/src/components/Select.tsx +++ b/ui/src/components/Select.tsx @@ -1,4 +1,4 @@ -import { useState, useRef, useEffect, useCallback } from 'react'; +import { useState, useRef, useEffect, useLayoutEffect, useCallback } from 'react'; import { Check, ChevronDown } from 'lucide-react'; import { radius, shadows } from '../design'; @@ -15,6 +15,7 @@ interface SelectProps { options: SelectOption[]; className?: string; size?: 'sm' | 'md'; + disabled?: boolean; } const selectTriggerSizes = { @@ -22,9 +23,11 @@ const selectTriggerSizes = { md: 'px-4 py-2.5 text-sm', }; -export function Select({ label, value, onChange, options, className = '', size = 'md' }: SelectProps) { +export function Select({ label, value, onChange, options, className = '', size = 'md', disabled = false }: SelectProps) { const [open, setOpen] = useState(false); const [focusIdx, setFocusIdx] = useState(-1); + const [dropUp, setDropUp] = useState(false); + const [dropRight, setDropRight] = useState(false); const containerRef = useRef(null); const listRef = useRef(null); @@ -43,6 +46,23 @@ export function Select({ label, value, onChange, options, className = '', size = return () => document.removeEventListener('mousedown', handler); }, [open]); + // Collision detection: determine dropdown direction (up/down, left/right) + // useLayoutEffect blocks paint until position is computed, preventing visual flash + useLayoutEffect(() => { + if (!open || !containerRef.current) return; + const rect = containerRef.current.getBoundingClientRect(); + const dropdownHeight = Math.min(options.length * 48, 256); // rough est, max 16rem + const dropdownWidth = 240; // rough min-width for description options + + // Vertical: prefer below, flip up if not enough space below but enough above + const spaceBelow = window.innerHeight - rect.bottom; + setDropUp(spaceBelow < dropdownHeight + 8 && rect.top > dropdownHeight); + + // Horizontal: default is left-aligned (left: 0). If dropdown overflows right edge, right-align instead. + const spaceRight = window.innerWidth - rect.left; + setDropRight(spaceRight < dropdownWidth); + }, [open, options.length]); + // Scroll focused item into view useEffect(() => { if (!open || focusIdx < 0 || !listRef.current) return; @@ -99,13 +119,15 @@ export function Select({ label, value, onChange, options, className = '', size = )}