Skip to content

mission control for agent skills

Add guarded skill actions

Alvin Unrealefa3e0c2315d
diff --git a/internal/actions/actions.go b/internal/actions/actions.go
index 9cae5b5..cb0a8de 100644
--- a/internal/actions/actions.go
+++ b/internal/actions/actions.go
@@ -1,6 +1,7 @@
package actions
import (
+ "os/exec"
"path/filepath"
"strings"
@@ -9,55 +10,99 @@ import (
)
type CommandPreview struct {
- Title string
+ ID string
+ Title string
+ Program string
+ Args []string
+ Exec ExecSpec
+ Command string
+ Description string
+ Mutates bool
+ RequiresConfirm bool
+ Dangerous bool
+ ConfirmValue string
+ Available bool
+ Reason string
+}
+
+type ExecSpec struct {
Program string
Args []string
- Command string
- Description string
- Mutates bool
- Available bool
- Reason string
+ Cwd string
+ Interactive bool
+ Internal string
}
+type SkillsResolver func() (program string, baseArgs []string)
+
func ForSkill(sk *model.Skill) []CommandPreview {
+ return ForSkillWithResolver(sk, ResolveSkillsCommand)
+}
+
+func ForSkillWithResolver(sk *model.Skill, resolve SkillsResolver) []CommandPreview {
if sk == nil {
return nil
}
+ if resolve == nil {
+ resolve = ResolveSkillsCommand
+ }
previews := []CommandPreview{
- newPreview("Refresh LazySkills", "lazyskills", nil, "Refresh is handled inside the TUI with r; this command reopens the dashboard.", false),
+ newInternalPreview("refresh", "Refresh LazySkills", "refresh", "Rescan skills without leaving LazySkills.", false),
}
if addSource, skillFilter, ok, reason := addIdentity(sk); ok {
- args := []string{"skills", "add", addSource, "--skill", skillFilter}
+ program, baseArgs := resolve()
+ args := append([]string{}, baseArgs...)
+ args = append(args, "add", addSource, "--skill", skillFilter, "--yes")
if sk.Scope == model.ScopeGlobal {
args = append(args, "-g")
}
- preview := newPreview("Reinstall/update selected skill", "npx", args, "Mutating preview only. Reinstall/update this skill via the official skills CLI.", true)
+ preview := newPreview("reinstall_update", "Reinstall/update selected skill", program, args, "Reinstall/update this skill via the official skills CLI after confirmation.", true, true, false, "yes")
previews = append(previews, preview)
} else {
previews = append(previews, unavailablePreview("Reinstall/update selected skill", reason))
}
if target, ok, reason := removeIdentity(sk); ok {
- args := []string{"skills", "remove", target}
+ program, baseArgs := resolve()
+ args := append([]string{}, baseArgs...)
+ args = append(args, "remove", target, "--yes")
if sk.Scope == model.ScopeGlobal {
args = append(args, "-g")
}
- previews = append(previews, newPreview("Remove selected skill", "npx", args, "Mutating preview only. Remove this installed skill via the official skills CLI after confirmation outside LazySkills.", true))
+ previews = append(previews, newPreview("remove", "Remove selected skill", program, args, "Remove this installed skill via the official skills CLI after typing the exact target.", true, true, true, target))
} else {
previews = append(previews, unavailablePreview("Remove selected skill", reason))
}
return previews
}
-func newPreview(title, program string, args []string, description string, mutates bool) CommandPreview {
- program = safeToken(program)
- safeArgs := make([]string, 0, len(args))
+func ResolveSkillsCommand() (string, []string) {
+ if _, err := exec.LookPath("skills"); err == nil {
+ return "skills", nil
+ }
+ return "npx", []string{"--yes", "skills"}
+}
+
+func newInternalPreview(id, title, internal, description string, mutates bool) CommandPreview {
+ preview := CommandPreview{ID: id, Title: title, Description: description, Mutates: mutates, Available: true, Exec: ExecSpec{Internal: internal}}
+ preview.Command = title
+ return preview
+}
+
+func newPreview(id, title, program string, args []string, description string, mutates, confirm, dangerous bool, confirmValue string) CommandPreview {
+ if !safeExecValue(program) {
+ return unavailablePreview(title, "program is empty or unsafe")
+ }
+ execArgs := make([]string, 0, len(args))
for _, arg := range args {
- safeArgs = append(safeArgs, compat.SanitizeMetadata(arg))
+ if !safeExecValue(arg) {
+ return unavailablePreview(title, "command argument is empty, option-like, or contains control characters")
+ }
+ execArgs = append(execArgs, arg)
}
- preview := CommandPreview{Title: title, Program: program, Args: safeArgs, Description: description, Mutates: mutates, Available: true}
- preview.Command = renderCommand(program, safeArgs)
+ preview := CommandPreview{ID: id, Title: title, Program: program, Args: execArgs, Exec: ExecSpec{Program: program, Args: execArgs}, Description: description, Mutates: mutates, RequiresConfirm: confirm, Dangerous: dangerous, ConfirmValue: confirmValue, Available: true}
+ preview.Command = renderCommand(program, execArgs)
return preview
}
@@ -68,11 +113,11 @@ func unavailablePreview(title, reason string) CommandPreview {
func addIdentity(sk *model.Skill) (source string, skillFilter string, ok bool, reason string) {
source, ref, skillPath := sourceRefPath(sk)
source = buildInstallSource(source, ref, skillPath)
- if !safeCLIValue(source) {
+ if !safeExecValue(source) || strings.HasPrefix(source, "-") {
return "", "", false, "source is empty or option-like"
}
- filter := compat.SanitizeMetadata(sk.Name)
- if !safeCLIValue(filter) {
+ filter := sk.Name
+ if !safeExecValue(filter) || strings.HasPrefix(filter, "-") {
return "", "", false, "skill name is empty or option-like"
}
return source, filter, true, ""
@@ -80,15 +125,11 @@ func addIdentity(sk *model.Skill) (source string, skillFilter string, ok bool, r
func removeIdentity(sk *model.Skill) (target string, ok bool, reason string) {
for _, path := range candidateInstallPaths(sk) {
- base := compat.SanitizeName(filepath.Base(path))
- if safeCLIValue(base) {
+ base := filepath.Base(path)
+ if safeExecValue(base) && !strings.HasPrefix(base, "-") {
return base, true, ""
}
}
- fallback := compat.SanitizeName(sk.Name)
- if safeCLIValue(sk.Name) && safeCLIValue(fallback) {
- return fallback, true, ""
- }
return "", false, "installed directory identity is empty or option-like"
}
@@ -110,18 +151,24 @@ func sourceRefPath(sk *model.Skill) (source, ref, skillPath string) {
func globalUpdateSource(entry model.GlobalLockEntry) string {
if entry.SkillPath == "" {
- return firstNonEmpty(entry.SourceURL, entry.Source)
+ return firstRawNonEmpty(entry.SourceURL, entry.Source)
}
- return firstNonEmpty(entry.Source, entry.SourceURL)
+ return firstRawNonEmpty(entry.Source, entry.SourceURL)
}
func buildInstallSource(source, ref, skillPath string) string {
- source = compat.SanitizeMetadata(source)
- ref = compat.SanitizeMetadata(ref)
- skillPath = compat.SanitizeMetadata(skillPath)
if source == "" {
return ""
}
+ if !safeExecValue(source) || strings.HasPrefix(source, "-") {
+ return ""
+ }
+ if ref != "" && (!safeExecValue(ref) || strings.HasPrefix(ref, "-")) {
+ return ""
+ }
+ if skillPath != "" && (!safeExecValue(skillPath) || strings.HasPrefix(skillPath, "-")) {
+ return ""
+ }
if skillPath != "" && supportsAppendedSubpath(source) {
folder := deriveSkillFolder(skillPath)
if folder != "" {
@@ -172,6 +219,13 @@ func safeCLIValue(value string) bool {
return value != "" && !strings.HasPrefix(value, "-")
}
+func safeExecValue(value string) bool {
+ if value == "" {
+ return false
+ }
+ return compat.SanitizeMetadata(value) == value && !strings.ContainsAny(value, "\x00\x1b\r\n")
+}
+
func safeToken(value string) string {
value = compat.SanitizeMetadata(value)
if value == "" || strings.HasPrefix(value, "-") || strings.ContainsAny(value, " \t\n'\"$`\\!*?[]{}()&;<>|") {
@@ -207,3 +261,12 @@ func firstNonEmpty(values ...string) string {
}
return ""
}
+
+func firstRawNonEmpty(values ...string) string {
+ for _, value := range values {
+ if value != "" {
+ return value
+ }
+ }
+ return ""
+}
diff --git a/internal/actions/actions_test.go b/internal/actions/actions_test.go
index d5e5652..f2ec343 100644
--- a/internal/actions/actions_test.go
+++ b/internal/actions/actions_test.go
@@ -9,10 +9,10 @@ import (
func TestForSkillBuildsStructuredSanitizedCommandPreviews(t *testing.T) {
sk := &model.Skill{
- Name: "Deploy Skill\x1b[31m",
+ Name: "Deploy Skill",
Scope: model.ScopeGlobal,
CanonicalPath: "/tmp/deploy-skill",
- GlobalLock: &model.GlobalLockEntry{Source: "owner/repo\x1b[31m", SkillPath: "skills/deploy/SKILL.md", Ref: "v1"},
+ GlobalLock: &model.GlobalLockEntry{Source: "owner/repo", SkillPath: "skills/deploy/SKILL.md", Ref: "v1"},
}
previews := ForSkill(sk)
if len(previews) < 3 {
@@ -22,19 +22,68 @@ func TestForSkillBuildsStructuredSanitizedCommandPreviews(t *testing.T) {
if strings.ContainsRune(preview.Command, '\x1b') {
t.Fatalf("command contains escape: %#v", preview)
}
- if preview.Available && preview.Program == "" {
+ if preview.Available && preview.Program == "" && preview.Exec.Internal == "" {
t.Fatalf("available preview missing program: %#v", preview)
}
}
add := previewByTitle(t, previews, "Reinstall/update selected skill")
- if !add.Available || add.Program != "npx" || len(add.Args) == 0 {
+ if !add.Available || add.Exec.Program == "" || len(add.Exec.Args) == 0 {
t.Fatalf("expected structured add preview, got %#v", add)
}
+ if !containsArg(add.Exec.Args, "--yes") {
+ t.Fatalf("expected --yes in add args: %#v", add.Exec.Args)
+ }
if !strings.Contains(add.Command, "owner/repo/skills/deploy#v1") {
t.Fatalf("expected ref and skill path preserved, got %q", add.Command)
}
}
+func TestUnsafeRawValuesSuppressExecActions(t *testing.T) {
+ previews := ForSkill(&model.Skill{Name: "Deploy\x1b[31m", Scope: model.ScopeProject, CanonicalPath: "/tmp/deploy", LocalLock: &model.LocalLockEntry{Source: "owner/repo"}})
+ add := previewByTitle(t, previews, "Reinstall/update selected skill")
+ if add.Available {
+ t.Fatalf("expected unsafe raw name to suppress executable add: %#v", add)
+ }
+}
+
+func TestUnsafeRawLockFieldsSuppressExecActions(t *testing.T) {
+ cases := []struct {
+ name string
+ skill *model.Skill
+ }{
+ {"local source", &model.Skill{Name: "Deploy", Scope: model.ScopeProject, CanonicalPath: "/tmp/deploy", LocalLock: &model.LocalLockEntry{Source: "owner/\x1b[31mrepo"}}},
+ {"local ref", &model.Skill{Name: "Deploy", Scope: model.ScopeProject, CanonicalPath: "/tmp/deploy", LocalLock: &model.LocalLockEntry{Source: "owner/repo", Ref: "main\x1b"}}},
+ {"local skill path", &model.Skill{Name: "Deploy", Scope: model.ScopeProject, CanonicalPath: "/tmp/deploy", LocalLock: &model.LocalLockEntry{Source: "owner/repo", SkillPath: "skills/\x1bdeploy/SKILL.md"}}},
+ {"global source url", &model.Skill{Name: "Deploy", Scope: model.ScopeGlobal, CanonicalPath: "/tmp/deploy", GlobalLock: &model.GlobalLockEntry{SourceURL: "https://example.com/\x1bskills"}}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ add := previewByTitle(t, ForSkill(tc.skill), "Reinstall/update selected skill")
+ if add.Available {
+ t.Fatalf("expected unsafe raw lock field to suppress action: %#v", add)
+ }
+ })
+ }
+}
+
+func TestResolverFallbackUsesNpxYesSkills(t *testing.T) {
+ previews := ForSkillWithResolver(&model.Skill{Name: "Deploy", Scope: model.ScopeProject, CanonicalPath: "/tmp/deploy", LocalLock: &model.LocalLockEntry{Source: "owner/repo"}}, func() (string, []string) {
+ return "npx", []string{"--yes", "skills"}
+ })
+ add := previewByTitle(t, previews, "Reinstall/update selected skill")
+ if add.Exec.Program != "npx" || len(add.Exec.Args) < 3 || add.Exec.Args[0] != "--yes" || add.Exec.Args[1] != "skills" {
+ t.Fatalf("expected npx --yes skills fallback, got %#v", add.Exec)
+ }
+}
+
+func TestRemoveRequiresInstalledDirectoryIdentity(t *testing.T) {
+ previews := ForSkill(&model.Skill{Name: "Display Name", Scope: model.ScopeProject, LocalLock: &model.LocalLockEntry{Source: "owner/repo"}})
+ remove := previewByTitle(t, previews, "Remove selected skill")
+ if remove.Available {
+ t.Fatalf("expected remove unavailable without installed path identity: %#v", remove)
+ }
+}
+
func TestOptionLookingSkillNameSuppressesMutatingPreviews(t *testing.T) {
previews := ForSkill(&model.Skill{Name: "--all", Scope: model.ScopeProject, LocalLock: &model.LocalLockEntry{Source: "owner/repo"}})
add := previewByTitle(t, previews, "Reinstall/update selected skill")
@@ -67,6 +116,25 @@ func TestRemoveUsesInstallDirectoryIdentityNotDisplayName(t *testing.T) {
}
}
+func TestRemoveUsesExactInstallBasenameWithoutSanitizing(t *testing.T) {
+ previews := ForSkill(&model.Skill{Name: "Display Name", Scope: model.ScopeProject, CanonicalPath: "/tmp/Exact_Name.1", LocalLock: &model.LocalLockEntry{Source: "owner/repo"}})
+ remove := previewByTitle(t, previews, "Remove selected skill")
+ if !remove.Available {
+ t.Fatalf("expected remove available: %#v", remove)
+ }
+ if remove.ConfirmValue != "Exact_Name.1" || !containsArg(remove.Exec.Args, "Exact_Name.1") {
+ t.Fatalf("expected exact basename target, got confirm=%q args=%#v", remove.ConfirmValue, remove.Exec.Args)
+ }
+}
+
+func TestRemoveRejectsUnsafeInstallBasename(t *testing.T) {
+ previews := ForSkill(&model.Skill{Name: "Display Name", Scope: model.ScopeProject, CanonicalPath: "/tmp/bad\x1bname", LocalLock: &model.LocalLockEntry{Source: "owner/repo"}})
+ remove := previewByTitle(t, previews, "Remove selected skill")
+ if remove.Available {
+ t.Fatalf("expected unsafe exact basename to suppress remove: %#v", remove)
+ }
+}
+
func TestGenericGitSourceKeepsRefButDoesNotAppendSkillPath(t *testing.T) {
previews := ForSkill(&model.Skill{Name: "Deploy", Scope: model.ScopeGlobal, CanonicalPath: "/tmp/deploy", GlobalLock: &model.GlobalLockEntry{Source: "[email protected]:owner/repo.git", Ref: "main", SkillPath: "skills/deploy/SKILL.md"}})
add := previewByTitle(t, previews, "Reinstall/update selected skill")
@@ -113,3 +181,12 @@ func previewByTitle(t *testing.T, previews []CommandPreview, title string) Comma
t.Fatalf("preview %q not found in %#v", title, previews)
return CommandPreview{}
}
+
+func containsArg(args []string, want string) bool {
+ for _, arg := range args {
+ if arg == want {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/runner/runner.go b/internal/runner/runner.go
new file mode 100644
index 0000000..8dc82da
--- /dev/null
+++ b/internal/runner/runner.go
@@ -0,0 +1,110 @@
+package runner
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "os/exec"
+ "strings"
+ "time"
+
+ "lazyskills/internal/compat"
+)
+
+const MaxOutputBytes = 32 * 1024
+
+type ExecSpec struct {
+ Program string
+ Args []string
+ Cwd string
+}
+
+type Result struct {
+ Program string
+ Args []string
+ Cwd string
+ Stdout string
+ Stderr string
+ ExitCode int
+ Err string
+ Truncated bool
+}
+
+type Runner interface {
+ Run(ExecSpec) Result
+}
+
+type OSRunner struct {
+ Timeout time.Duration
+}
+
+func (r OSRunner) Run(spec ExecSpec) Result {
+ result := Result{Program: spec.Program, Args: append([]string{}, spec.Args...), Cwd: spec.Cwd, ExitCode: -1}
+ if spec.Program == "" {
+ result.Err = "missing program"
+ return result
+ }
+ timeout := r.Timeout
+ if timeout == 0 {
+ timeout = 5 * time.Minute
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), timeout)
+ defer cancel()
+
+ cmd := exec.CommandContext(ctx, spec.Program, spec.Args...)
+ cmd.Dir = spec.Cwd
+ var stdout, stderr cappedBuffer
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+ err := cmd.Run()
+ result.Stdout, result.Stderr = sanitizeOutput(stdout.String()), sanitizeOutput(stderr.String())
+ result.Truncated = stdout.Truncated || stderr.Truncated
+ if cmd.ProcessState != nil {
+ result.ExitCode = cmd.ProcessState.ExitCode()
+ }
+ if ctx.Err() != nil {
+ result.Err = ctx.Err().Error()
+ return result
+ }
+ if err != nil {
+ var exitErr *exec.ExitError
+ if errors.As(err, &exitErr) {
+ result.ExitCode = exitErr.ExitCode()
+ } else {
+ result.Err = err.Error()
+ }
+ }
+ return result
+}
+
+type cappedBuffer struct {
+ buf bytes.Buffer
+ Truncated bool
+}
+
+func (b *cappedBuffer) Write(p []byte) (int, error) {
+ remaining := MaxOutputBytes - b.buf.Len()
+ if remaining <= 0 {
+ b.Truncated = true
+ return len(p), nil
+ }
+ if len(p) > remaining {
+ b.Truncated = true
+ _, _ = b.buf.Write(p[:remaining])
+ return len(p), nil
+ }
+ return b.buf.Write(p)
+}
+
+func (b *cappedBuffer) String() string {
+ out := b.buf.String()
+ if b.Truncated {
+ out += "\n[output truncated]"
+ }
+ return out
+}
+
+func sanitizeOutput(value string) string {
+ value = compat.SanitizePreviewContent(value)
+ return strings.TrimRight(value, "\n")
+}
diff --git a/internal/runner/runner_test.go b/internal/runner/runner_test.go
new file mode 100644
index 0000000..128c7da
--- /dev/null
+++ b/internal/runner/runner_test.go
@@ -0,0 +1,24 @@
+package runner
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestCappedBufferTruncatesOutput(t *testing.T) {
+ var b cappedBuffer
+ input := strings.Repeat("x", MaxOutputBytes+10)
+ if n, err := b.Write([]byte(input)); err != nil || n != len(input) {
+ t.Fatalf("unexpected write result n=%d err=%v", n, err)
+ }
+ if !b.Truncated || !strings.Contains(b.String(), "[output truncated]") {
+ t.Fatalf("expected truncation marker")
+ }
+}
+
+func TestSanitizeOutputStripsControls(t *testing.T) {
+ out := sanitizeOutput("hello\x1b[31m red\n")
+ if strings.ContainsRune(out, '\x1b') || out != "hello red" {
+ t.Fatalf("unexpected sanitized output %q", out)
+ }
+}
diff --git a/internal/tui/tui.go b/internal/tui/tui.go
index ba8dc50..e626a3a 100644
--- a/internal/tui/tui.go
+++ b/internal/tui/tui.go
@@ -15,6 +15,7 @@ import (
"lazyskills/internal/compat"
"lazyskills/internal/display"
"lazyskills/internal/model"
+ "lazyskills/internal/runner"
"lazyskills/internal/scan"
)
@@ -27,19 +28,24 @@ const (
)
type appModel struct {
- cwd string
- result model.ScanResult
- err error
- selected int
- filter scopeFilter
- agent string
- search string
- searching bool
- commands bool
- help bool
- width int
- height int
- viewport viewport.Model
+ cwd string
+ result model.ScanResult
+ err error
+ selected int
+ filter scopeFilter
+ agent string
+ search string
+ searching bool
+ commands bool
+ help bool
+ action int
+ confirming bool
+ confirmInput string
+ running bool
+ actionResult *runner.Result
+ width int
+ height int
+ viewport viewport.Model
}
type paneLayout struct {
@@ -71,6 +77,7 @@ var (
selectedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("230")).Background(lipgloss.Color("62"))
dimStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
errorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("203"))
+ runExec = runner.OSRunner{}.Run
)
type snapshotMsg struct {
@@ -78,6 +85,11 @@ type snapshotMsg struct {
err error
}
+type actionResultMsg struct {
+ result runner.Result
+ mutates bool
+}
+
func Run(cwd string) error {
program := tea.NewProgram(newModel(cwd), tea.WithAltScreen())
_, err := program.Run()
@@ -110,8 +122,42 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.err = msg.err
m.clampSelection()
m.syncViewport()
+ case actionResultMsg:
+ m.running = false
+ m.confirming = false
+ m.confirmInput = ""
+ m.actionResult = &msg.result
+ m.syncViewport()
+ if msg.mutates && msg.result.ExitCode == 0 && msg.result.Err == "" {
+ return m, loadSnapshot(m.cwd)
+ }
case tea.KeyMsg:
key := msg.String()
+ if m.running {
+ if key == "ctrl+c" || key == "q" {
+ return m, tea.Quit
+ }
+ return m, nil
+ }
+ if m.confirming {
+ switch key {
+ case "esc":
+ m.confirming = false
+ m.confirmInput = ""
+ case "enter":
+ return m.confirmAction()
+ case "backspace", "ctrl+h":
+ if len(m.confirmInput) > 0 {
+ m.confirmInput = m.confirmInput[:len(m.confirmInput)-1]
+ }
+ default:
+ if len(key) == 1 {
+ m.confirmInput += key
+ }
+ }
+ m.syncViewport()
+ return m, nil
+ }
if m.searching {
switch key {
case "esc", "enter":
@@ -139,8 +185,13 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.help = !m.help
case "c":
m.commands = !m.commands
+ m.action = 0
case "/":
m.searching = true
+ case "enter":
+ if m.commands {
+ return m.startAction()
+ }
case "r":
m.viewport.GotoTop()
return m, loadSnapshot(m.cwd)
@@ -157,10 +208,18 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.selected = 0
m.viewport.GotoTop()
case "down", "j":
- m.selected++
+ if m.commands {
+ m.action++
+ } else {
+ m.selected++
+ }
m.viewport.GotoTop()
case "up", "k":
- m.selected--
+ if m.commands {
+ m.action--
+ } else {
+ m.selected--
+ }
m.viewport.GotoTop()
case "pgdown", "ctrl+d":
var cmd tea.Cmd
@@ -174,11 +233,86 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.viewport.GotoTop()
}
m.clampSelection()
+ m.clampAction()
m.syncViewport()
}
return m, nil
}
+func (m *appModel) clampAction() {
+ actions := m.currentActions()
+ if len(actions) == 0 {
+ m.action = 0
+ return
+ }
+ if m.action < 0 {
+ m.action = 0
+ }
+ if m.action >= len(actions) {
+ m.action = len(actions) - 1
+ }
+}
+
+func (m appModel) currentActions() []actions.CommandPreview {
+ items := m.filteredSkills()
+ if len(items) == 0 || m.selected >= len(items) {
+ return nil
+ }
+ return actions.ForSkill(items[m.selected])
+}
+
+func (m appModel) startAction() (tea.Model, tea.Cmd) {
+ actions := m.currentActions()
+ if len(actions) == 0 || m.action >= len(actions) {
+ return m, nil
+ }
+ action := actions[m.action]
+ if !action.Available {
+ return m, nil
+ }
+ if action.RequiresConfirm {
+ m.confirming = true
+ m.confirmInput = ""
+ m.actionResult = nil
+ m.syncViewport()
+ return m, nil
+ }
+ return m.executeAction(action)
+}
+
+func (m appModel) confirmAction() (tea.Model, tea.Cmd) {
+ actions := m.currentActions()
+ if len(actions) == 0 || m.action >= len(actions) {
+ return m, nil
+ }
+ action := actions[m.action]
+ if m.confirmInput != action.ConfirmValue {
+ m.actionResult = &runner.Result{Err: "confirmation did not match", ExitCode: -1}
+ m.confirming = false
+ m.confirmInput = ""
+ m.syncViewport()
+ return m, nil
+ }
+ return m.executeAction(action)
+}
+
+func (m appModel) executeAction(action actions.CommandPreview) (tea.Model, tea.Cmd) {
+ if action.Exec.Internal == "refresh" {
+ m.actionResult = nil
+ return m, loadSnapshot(m.cwd)
+ }
+ spec := runner.ExecSpec{Program: action.Exec.Program, Args: action.Exec.Args, Cwd: m.cwd}
+ m.running = true
+ m.actionResult = nil
+ m.confirming = false
+ m.confirmInput = ""
+ m.syncViewport()
+ return m, func() tea.Msg {
+ result := runExec(spec)
+ return actionResultMsg{result: result, mutates: action.Mutates}
+ }
+}
+
func (m *appModel) syncViewport() {
layout := newAppLayout(m.width, m.height)
if layout.Small {
@@ -411,11 +545,30 @@ func (m appModel) visibilitySummary(view display.SkillView) []string {
}
func (m appModel) commandPreview(sk *model.Skill, width int) []string {
- lines := []string{titleStyle.Render("Command previews")}
- lines = append(lines, dimStyle.Render("Preview only. LazySkills will not run these commands yet."))
- for _, preview := range actions.ForSkill(sk) {
+ lines := []string{titleStyle.Render("Actions")}
+ lines = append(lines, dimStyle.Render("j/k choose, enter run, esc cancel confirmation"))
+ if m.running {
+ lines = append(lines, "", "Running action...")
+ }
+ if m.confirming {
+ current := m.currentActions()
+ prompt := "type confirmation"
+ if len(current) > 0 && m.action < len(current) {
+ prompt = fmt.Sprintf("type %q to confirm", current[m.action].ConfirmValue)
+ }
+ lines = append(lines, "", errorStyle.Render("Confirm mutation"), prompt, "> "+compat.SanitizeMetadata(m.confirmInput))
+ }
+ if m.actionResult != nil {
+ lines = append(lines, "")
+ lines = append(lines, m.renderActionResult(width)...)
+ }
+ for i, preview := range actions.ForSkill(sk) {
+ selector := " "
+ if i == m.action {
+ selector = "› "
+ }
if !preview.Available {
- lines = append(lines, "", fmt.Sprintf("%s (unavailable)", compat.SanitizeMetadata(preview.Title)))
+ lines = append(lines, "", selector+fmt.Sprintf("%s (unavailable)", compat.SanitizeMetadata(preview.Title)))
lines = append(lines, wrap(compat.SanitizeMetadata(preview.Reason), width))
continue
}
@@ -423,7 +576,10 @@ func (m appModel) commandPreview(sk *model.Skill, width int) []string {
if preview.Mutates {
marker = "mutates"
}
- lines = append(lines, "", fmt.Sprintf("%s (%s)", compat.SanitizeMetadata(preview.Title), marker))
+ if preview.Dangerous {
+ marker += ", dangerous"
+ }
+ lines = append(lines, "", selector+fmt.Sprintf("%s (%s)", compat.SanitizeMetadata(preview.Title), marker))
lines = append(lines, truncate(compat.SanitizeMetadata(preview.Command), width))
if preview.Description != "" {
lines = append(lines, wrap(compat.SanitizeMetadata(preview.Description), width))
@@ -432,14 +588,39 @@ func (m appModel) commandPreview(sk *model.Skill, width int) []string {
return lines
}
+func (m appModel) renderActionResult(width int) []string {
+ if m.actionResult == nil {
+ return nil
+ }
+ result := m.actionResult
+ status := "success"
+ if result.ExitCode != 0 || result.Err != "" {
+ status = "failed"
+ }
+ lines := []string{fmt.Sprintf("Result: %s (exit %d)", status, result.ExitCode)}
+ if result.Err != "" {
+ lines = append(lines, wrap(compat.SanitizeMetadata(result.Err), width))
+ }
+ if result.Stdout != "" {
+ lines = append(lines, "stdout:", fitLines(wrapText(result.Stdout, width), 8))
+ }
+ if result.Stderr != "" {
+ lines = append(lines, "stderr:", fitLines(wrapText(result.Stderr, width), 8))
+ }
+ if result.Truncated {
+ lines = append(lines, dimStyle.Render("output truncated"))
+ }
+ return lines
+}
+
func (m appModel) footer() string {
mode := ""
if m.searching {
mode = " search mode: type to filter, esc/enter to leave"
} else if m.commands {
- mode = " command previews: c to hide"
+ mode = " actions: enter run, c hide"
}
- return dimStyle.Render("LazySkills is read-only." + mode)
+ return dimStyle.Render("LazySkills actions are guarded." + mode)
}
func (m appModel) filteredSkills() []*model.Skill {
diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go
index 5828498..c226d7c 100644
--- a/internal/tui/tui_test.go
+++ b/internal/tui/tui_test.go
@@ -10,6 +10,7 @@ import (
"github.com/charmbracelet/lipgloss"
"lazyskills/internal/model"
+ "lazyskills/internal/runner"
)
func TestFilteredSkillsUsesSanitizedSearch(t *testing.T) {
@@ -41,7 +42,7 @@ func TestErrorViewIsSanitized(t *testing.T) {
func TestViewRendersReadOnlyFooter(t *testing.T) {
m := appModel{width: 100, height: 30, result: model.ScanResult{Skills: []*model.Skill{{Name: "Build", Description: "Build desc", Scope: model.ScopeProject}}}}
out := m.View()
- if !strings.Contains(out, "LazySkills is read-only") || !strings.Contains(out, "Build") {
+ if !strings.Contains(out, "LazySkills actions are guarded") || !strings.Contains(out, "Build") {
t.Fatalf("unexpected view: %s", out)
}
}
@@ -108,8 +109,8 @@ func TestCommandPreviewModeRendersWithoutExecuting(t *testing.T) {
LocalLock: &model.LocalLockEntry{Source: "owner/repo"},
}}}}
out := m.View()
- if !strings.Contains(out, "Command previews") || !strings.Contains(out, "Preview only") || !strings.Contains(out, "npx skills") {
- t.Fatalf("expected command previews in output: %q", out)
+ if !strings.Contains(out, "Actions") || !strings.Contains(out, "Reinstall/update selected skill") || !strings.Contains(out, "skills add") || !strings.Contains(out, "--yes") {
+ t.Fatalf("expected actions in output: %q", out)
}
}
@@ -154,6 +155,121 @@ func TestCommandPreviewToggle(t *testing.T) {
}
}
+func TestActionConfirmationCancelDoesNotExecute(t *testing.T) {
+ called := false
+ old := runExec
+ runExec = func(spec runner.ExecSpec) runner.Result { called = true; return runner.Result{ExitCode: 0} }
+ t.Cleanup(func() { runExec = old })
+
+ m := actionTestModel(t.TempDir())
+ m.commands = true
+ m.action = 1
+ updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ next := updated.(appModel)
+ if cmd != nil || !next.confirming {
+ t.Fatalf("expected confirmation without command, confirming=%v cmd=%v", next.confirming, cmd)
+ }
+ updated, cmd = next.Update(tea.KeyMsg{Type: tea.KeyEsc})
+ next = updated.(appModel)
+ if cmd != nil || next.confirming || called {
+ t.Fatalf("expected cancel without execution, confirming=%v called=%v", next.confirming, called)
+ }
+}
+
+func TestActionExecUsesProjectCwdAndPreventsDuplicateWhileRunning(t *testing.T) {
+ cwd := t.TempDir()
+ old := runExec
+ runExec = func(spec runner.ExecSpec) runner.Result {
+ if spec.Cwd != cwd {
+ t.Fatalf("expected cwd %q, got %q", cwd, spec.Cwd)
+ }
+ return runner.Result{Program: spec.Program, Args: spec.Args, Cwd: spec.Cwd, ExitCode: 0, Stdout: "ok"}
+ }
+ t.Cleanup(func() { runExec = old })
+
+ m := actionTestModel(cwd)
+ m.commands = true
+ m.action = 1
+ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ m = updated.(appModel)
+ for _, r := range []rune("yes") {
+ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
+ m = updated.(appModel)
+ }
+ updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ m = updated.(appModel)
+ if cmd == nil || !m.running {
+ t.Fatalf("expected running command")
+ }
+ updated, dup := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ if dup != nil || !updated.(appModel).running {
+ t.Fatalf("expected duplicate enter ignored while running")
+ }
+ msg := cmd()
+ updated, rescan := m.Update(msg)
+ m = updated.(appModel)
+ if m.running || m.actionResult == nil || m.actionResult.Stdout != "ok" || rescan == nil {
+ t.Fatalf("expected result and rescan, model=%#v rescan=%v", m.actionResult, rescan)
+ }
+}
+
+func TestFailedMutationDoesNotTriggerRescan(t *testing.T) {
+ cwd := t.TempDir()
+ old := runExec
+ runExec = func(spec runner.ExecSpec) runner.Result {
+ return runner.Result{Program: spec.Program, Args: spec.Args, Cwd: spec.Cwd, ExitCode: 2, Stderr: "nope"}
+ }
+ t.Cleanup(func() { runExec = old })
+
+ m := actionTestModel(cwd)
+ m.commands = true
+ m.action = 1
+ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ m = updated.(appModel)
+ for _, r := range []rune("yes") {
+ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
+ m = updated.(appModel)
+ }
+ updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ m = updated.(appModel)
+ if cmd == nil {
+ t.Fatalf("expected command")
+ }
+ updated, rescan := m.Update(cmd())
+ m = updated.(appModel)
+ if rescan != nil || m.actionResult == nil || m.actionResult.ExitCode != 2 {
+ t.Fatalf("expected failed result without rescan, result=%#v rescan=%v", m.actionResult, rescan)
+ }
+}
+
+func TestRemoveRequiresExactTypedIdentity(t *testing.T) {
+ m := actionTestModel(t.TempDir())
+ m.result.Skills[0].CanonicalPath = "/tmp/deploy-skill"
+ m.commands = true
+ m.action = 2
+ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ m = updated.(appModel)
+ for _, r := range []rune("wrong") {
+ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
+ m = updated.(appModel)
+ }
+ updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ m = updated.(appModel)
+ if cmd != nil || m.actionResult == nil || !strings.Contains(m.actionResult.Err, "confirmation") {
+ t.Fatalf("expected failed confirmation without command, result=%#v cmd=%v", m.actionResult, cmd)
+ }
+}
+
+func actionTestModel(cwd string) appModel {
+ return appModel{cwd: cwd, width: 120, height: 32, result: model.ScanResult{Skills: []*model.Skill{{
+ Name: "Deploy Skill",
+ Description: "desc",
+ Scope: model.ScopeProject,
+ CanonicalPath: "/tmp/deploy-skill",
+ LocalLock: &model.LocalLockEntry{Source: "owner/repo"},
+ }}}}
+}
+
func TestDetailPaneClipsLongPreview(t *testing.T) {
preview := strings.Repeat("line\n", 80)
m := appModel{width: 100, height: 20, result: model.ScanResult{Skills: []*model.Skill{{Name: "Long", Description: "desc", Scope: model.ScopeProject, Preview: preview}}}}