Skip to content

mission control for agent skills

Add skills.sh registry search flow

Alvin Unreal51db594ea2bb
diff --git a/README.md b/README.md
index 0421e4a..65a2fe7 100644
--- a/README.md
+++ b/README.md
@@ -37,6 +37,7 @@ LazySkills is a blazing-fast terminal UI for managing agent skills. It gives you
- **Preview before you act** - inspect metadata, rendered skill content, and the exact command LazySkills is about to run.
- **Safe skill actions** - open, reinstall/update, remove, prune orphaned locks, or run bulk updates/removals with confirmation prompts.
- **Discover more from a source** - scan local checkouts or GitHub skill sources to find skills you have not installed yet.
+- **Find and install new skills** - search skills.sh from inside LazySkills, preview the install command, then install to project or global scope with confirmation.
## 🛠️ Install
@@ -89,6 +90,7 @@ Useful keys:
| `f` | Toggle project/global/all scopes |
| `enter` | Open details for a skill or source |
| `c` | Show available actions |
+| `n` | Find new skills from skills.sh |
| `space` | Select a skill for bulk actions |
| `u` | Reinstall/update selected skill |
| `x` | Remove selected skill |
@@ -96,6 +98,12 @@ Useful keys:
LazySkills previews actions before running them, and destructive actions require confirmation.
+For agent-friendly registry search without opening the TUI:
+
+```bash
+lazyskills find --json "browser automation"
+```
+
## 🔄 Updates
LazySkills can check for new releases and show the command to update your installation manually.
diff --git a/cmd/lazyskills/main.go b/cmd/lazyskills/main.go
index 0f73863..9e71776 100644
--- a/cmd/lazyskills/main.go
+++ b/cmd/lazyskills/main.go
@@ -8,6 +8,7 @@ import (
"os"
"github.com/alvinunreal/lazyskills/internal/buildinfo"
+ "github.com/alvinunreal/lazyskills/internal/registry"
"github.com/alvinunreal/lazyskills/internal/scan"
"github.com/alvinunreal/lazyskills/internal/selfupdate"
"github.com/alvinunreal/lazyskills/internal/tui"
@@ -43,6 +44,43 @@ func run(args []string) error {
fmt.Fprintf(os.Stdout, "lazyskills %s\ncommit: %s\nbuilt: %s\n", buildinfo.Version, buildinfo.Commit, buildinfo.Date)
return nil
}
+ if len(args) > 0 && args[0] == "find" {
+ fs := flag.NewFlagSet("find", flag.ContinueOnError)
+ fs.SetOutput(os.Stderr)
+ jsonOut := fs.Bool("json", false, "output JSON")
+ if err := fs.Parse(args[1:]); err != nil {
+ return err
+ }
+ if !*jsonOut {
+ return fmt.Errorf("usage: lazyskills find --json <query>")
+ }
+ if fs.NArg() != 1 {
+ return fmt.Errorf("usage: lazyskills find --json <query>")
+ }
+ query := fs.Arg(0)
+
+ client := registry.NewClient()
+ ctx := context.Background()
+ skills, err := client.Search(ctx, query, 0)
+ if err != nil {
+ return err
+ }
+
+ res := struct {
+ Query string `json:"query"`
+ Results []registry.Skill `json:"results"`
+ }{
+ Query: query,
+ Results: skills,
+ }
+ if res.Results == nil {
+ res.Results = []registry.Skill{}
+ }
+
+ enc := json.NewEncoder(os.Stdout)
+ enc.SetIndent("", " ")
+ return enc.Encode(res)
+ }
if len(args) > 0 && args[0] == "update" {
fs := flag.NewFlagSet("update", flag.ContinueOnError)
fs.SetOutput(os.Stderr)
@@ -138,7 +176,7 @@ func run(args []string) error {
return err
}
if fs.NArg() > 0 {
- return fmt.Errorf("usage: lazyskills [--cwd <path>] | lazyskills scan --json [--cwd <path>] | lazyskills update [--check] [--print-command] | lazyskills version")
+ return fmt.Errorf("usage: lazyskills [--cwd <path>] | lazyskills scan --json [--cwd <path>] | lazyskills update [--check] [--print-command] | lazyskills find --json <query> | lazyskills version")
}
if *cwd == "" {
var err error
diff --git a/cmd/lazyskills/main_test.go b/cmd/lazyskills/main_test.go
index 6b5ef17..4c7d03e 100644
--- a/cmd/lazyskills/main_test.go
+++ b/cmd/lazyskills/main_test.go
@@ -3,12 +3,16 @@ package main
import (
"bytes"
"context"
+ "encoding/json"
"io"
+ "net/http"
+ "net/http/httptest"
"os"
"strings"
"testing"
"github.com/alvinunreal/lazyskills/internal/buildinfo"
+ "github.com/alvinunreal/lazyskills/internal/registry"
"github.com/alvinunreal/lazyskills/internal/selfupdate"
)
@@ -128,3 +132,72 @@ func TestCLIUpdate(t *testing.T) {
t.Error("should not print Already up to date when update checks are disabled")
}
}
+
+func TestCLIFind(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "skills": [
+ {"id": "owner/one/skill-1", "skillId": "skill-1", "name": "Skill One", "installs": 10, "source": "github.com/one"}
+ ]
+ }`))
+ }))
+ defer server.Close()
+
+ t.Setenv("SKILLS_API_URL", server.URL)
+
+ oldOut := os.Stdout
+ defer func() { os.Stdout = oldOut }()
+
+ captureStdout := func(args []string) (string, error) {
+ r, w, _ := os.Pipe()
+ os.Stdout = w
+ err := run(args)
+ w.Close()
+ var buf bytes.Buffer
+ _, _ = io.Copy(&buf, r)
+ os.Stdout = oldOut
+ return buf.String(), err
+ }
+
+ // 1. Missing json flag
+ _, err := captureStdout([]string{"find", "test-query"})
+ if err == nil || !strings.Contains(err.Error(), "usage: lazyskills find --json <query>") {
+ t.Fatalf("expected usage error without --json, got: %v", err)
+ }
+
+ // 2. Missing query
+ _, err = captureStdout([]string{"find", "--json"})
+ if err == nil || !strings.Contains(err.Error(), "usage: lazyskills find --json <query>") {
+ t.Fatalf("expected usage error without query, got: %v", err)
+ }
+
+ // 3. Multi query or too many args
+ _, err = captureStdout([]string{"find", "--json", "q1", "q2"})
+ if err == nil || !strings.Contains(err.Error(), "usage: lazyskills find --json <query>") {
+ t.Fatalf("expected usage error with multiple queries, got: %v", err)
+ }
+
+ // 4. Success JSON
+ out, err := captureStdout([]string{"find", "--json", "test-query"})
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ // Check if output is stable indented JSON containing the query and skills
+ var res struct {
+ Query string `json:"query"`
+ Results []registry.Skill `json:"results"`
+ }
+ if err := json.Unmarshal([]byte(out), &res); err != nil {
+ t.Fatalf("failed to parse JSON output: %v\nOutput was:\n%s", err, out)
+ }
+
+ if res.Query != "test-query" {
+ t.Errorf("expected query %q, got %q", "test-query", res.Query)
+ }
+
+ if len(res.Results) != 1 || res.Results[0].Slug != "skill-1" {
+ t.Errorf("unexpected results: %+v", res.Results)
+ }
+}
diff --git a/internal/actions/actions.go b/internal/actions/actions.go
index f8929d1..8e30d99 100644
--- a/internal/actions/actions.go
+++ b/internal/actions/actions.go
@@ -112,6 +112,18 @@ func AppLevelActionsWithResolver(resolve SkillsResolver) []CommandPreview {
gateAvailability(&updatePreview, available, reason)
previews = append(previews, updatePreview)
+ // find new skills from skills.sh
+ registryPreview := CommandPreview{
+ ID: "find_new_skills",
+ Title: "Find new skills from skills.sh",
+ Description: "Search skills.sh registry inside LazySkills.",
+ Command: "find new skills from skills.sh",
+ Exec: ExecSpec{Internal: "find_new_skills"},
+ Available: true,
+ RequiresConfirm: false,
+ }
+ previews = append(previews, registryPreview)
+
return previews
}
@@ -141,12 +153,41 @@ func ForAvailableSkill(source, name string) []CommandPreview {
return ForAvailableSkillWithResolver(source, name, false, ResolveSkillsCommand)
}
-func ForAvailableSkillWithResolver(source, name string, global bool, resolve SkillsResolver) []CommandPreview {
+type InstallOptions struct {
+ DisplayName string
+ Slug string
+ Global bool
+}
+
+func ForAvailableSkillWithOptions(source string, opts InstallOptions) []CommandPreview {
+ return ForAvailableSkillWithOptionsAndResolver(source, opts, ResolveSkillsCommand)
+}
+
+func ForAvailableSkillWithOptionsAndResolver(source string, opts InstallOptions, resolve SkillsResolver) []CommandPreview {
+ title := "Install selected skill"
+ if opts.DisplayName != "" {
+ if opts.Global {
+ title = fmt.Sprintf("Install %s globally", opts.DisplayName)
+ } else {
+ title = fmt.Sprintf("Install %s to project", opts.DisplayName)
+ }
+ } else {
+ if opts.Global {
+ title = "Install selected skill globally"
+ } else {
+ title = "Install selected skill"
+ }
+ }
+
if !safeExecValue(source) || strings.HasPrefix(source, "-") {
- return []CommandPreview{unavailablePreview("Install selected skill", "source is empty, option-like, or contains unsafe characters")}
+ return []CommandPreview{unavailablePreview(title, "source is empty, option-like, or contains unsafe characters")}
}
- if !safeExecValue(name) || strings.HasPrefix(name, "-") {
- return []CommandPreview{unavailablePreview("Install selected skill", "skill name is empty, option-like, or contains unsafe characters")}
+ if !safeExecValue(opts.Slug) || strings.HasPrefix(opts.Slug, "-") {
+ reason := "skill slug is empty, option-like, or contains unsafe characters"
+ if opts.DisplayName == "" {
+ reason = "skill name is empty, option-like, or contains unsafe characters"
+ }
+ return []CommandPreview{unavailablePreview(title, reason)}
}
if resolve == nil {
@@ -156,20 +197,29 @@ func ForAvailableSkillWithResolver(source, name string, global bool, resolve Ski
program, baseArgs := resolve()
args := append([]string{}, baseArgs...)
- args = append(args, "add", source, "--skill", name, "--yes")
- if global {
+ args = append(args, "add", source, "--skill", opts.Slug, "--yes")
+ if opts.Global {
args = append(args, "--global")
}
- description := "Install this skill to project."
- if global {
- description = "Install this skill globally."
+ desc := "Install this skill to project."
+ if opts.Global {
+ desc = "Install this skill globally."
}
- preview := newPreview("install_skill", "Install selected skill", program, args, description, true, true, false, "yes")
+
+ preview := newPreview("install_skill", title, program, args, desc, true, true, false, "yes")
gateAvailability(&preview, available, reason)
return []CommandPreview{preview}
}
+func ForAvailableSkillWithResolver(source, name string, global bool, resolve SkillsResolver) []CommandPreview {
+ return ForAvailableSkillWithOptionsAndResolver(source, InstallOptions{
+ Slug: name,
+ DisplayName: "",
+ Global: global,
+ }, resolve)
+}
+
func ForSkillWithResolver(sk *model.Skill, resolve SkillsResolver) []CommandPreview {
if sk == nil {
return nil
diff --git a/internal/actions/actions_test.go b/internal/actions/actions_test.go
index c7b7a0c..ca923f7 100644
--- a/internal/actions/actions_test.go
+++ b/internal/actions/actions_test.go
@@ -316,8 +316,8 @@ func containsArg(args []string, want string) bool {
func TestAppLevelActions(t *testing.T) {
previews := AppLevelActions()
- if len(previews) != 3 {
- t.Fatalf("expected 3 app-level actions, got %d", len(previews))
+ if len(previews) != 4 {
+ t.Fatalf("expected 4 app-level actions, got %d", len(previews))
}
initAct := previewByTitle(t, previews, "Initialize skills in project")
if initAct.ID != "skills_init" || !initAct.Mutates || !initAct.RequiresConfirm {
@@ -333,6 +333,11 @@ func TestAppLevelActions(t *testing.T) {
if updateAct.ID != "skills_update" || !updateAct.Mutates || !updateAct.RequiresConfirm {
t.Errorf("unexpected skills update preview: %+v", updateAct)
}
+
+ registryAct := previewByTitle(t, previews, "Find new skills from skills.sh")
+ if registryAct.ID != "find_new_skills" || registryAct.Exec.Internal != "find_new_skills" || !registryAct.Available {
+ t.Errorf("unexpected registry preview: %+v", registryAct)
+ }
}
func TestMissingDepsDisablesActions(t *testing.T) {
@@ -468,3 +473,77 @@ func TestResolveSkillsCommandMutationIsolation(t *testing.T) {
t.Fatalf("expected skills and nil args, got prog=%q args=%#v", prog3, args3)
}
}
+
+func TestForAvailableSkillWithOptions(t *testing.T) {
+ LookPath = func(name string) (string, error) {
+ return "/usr/bin/" + name, nil
+ }
+
+ // 1. Display name differs from slug: check title and args
+ previews := ForAvailableSkillWithOptions("owner/repo", InstallOptions{
+ DisplayName: "My Display Name",
+ Slug: "my-slug-name",
+ Global: false,
+ })
+ if len(previews) != 1 {
+ t.Fatalf("expected 1 preview, got %d", len(previews))
+ }
+ p := previews[0]
+ if !p.Available {
+ t.Fatalf("expected preview to be available, got unavailable with reason: %s", p.Reason)
+ }
+ if p.Title != "Install My Display Name to project" {
+ t.Errorf("expected project title, got %q", p.Title)
+ }
+ if !containsArg(p.Exec.Args, "owner/repo") || !containsArg(p.Exec.Args, "my-slug-name") {
+ t.Errorf("expected source and slug-name in args, got %+v", p.Exec.Args)
+ }
+ if containsArg(p.Exec.Args, "My Display Name") {
+ t.Errorf("did not expect display name in command args: %+v", p.Exec.Args)
+ }
+ if containsArg(p.Exec.Args, "--global") {
+ t.Errorf("did not expect global --global flag when Global=false")
+ }
+
+ // 2. Global --global flag added only when Global is true
+ globalPreviews := ForAvailableSkillWithOptions("owner/repo", InstallOptions{
+ DisplayName: "My Display Name",
+ Slug: "my-slug-name",
+ Global: true,
+ })
+ if len(globalPreviews) != 1 {
+ t.Fatalf("expected 1 preview, got %d", len(globalPreviews))
+ }
+ gp := globalPreviews[0]
+ if gp.Title != "Install My Display Name globally" {
+ t.Errorf("expected global title, got %q", gp.Title)
+ }
+ if !containsArg(gp.Exec.Args, "--global") {
+ t.Errorf("expected global --global flag in args, got %+v", gp.Exec.Args)
+ }
+
+ // 3. Unsafe source/slug rejection checks
+ unsafeCases := []struct {
+ desc string
+ source string
+ opts InstallOptions
+ }{
+ {"unsafe source", "source\x1b", InstallOptions{DisplayName: "Name", Slug: "slug"}},
+ {"unsafe slug", "source", InstallOptions{DisplayName: "Name", Slug: "slug\n"}},
+ {"empty slug", "source", InstallOptions{DisplayName: "Name", Slug: ""}},
+ {"empty source", "", InstallOptions{DisplayName: "Name", Slug: "slug"}},
+ {"option source", "-g", InstallOptions{DisplayName: "Name", Slug: "slug"}},
+ {"option slug", "source", InstallOptions{DisplayName: "Name", Slug: "-g"}},
+ }
+ for _, tc := range unsafeCases {
+ t.Run(tc.desc, func(t *testing.T) {
+ previews := ForAvailableSkillWithOptions(tc.source, tc.opts)
+ if len(previews) != 1 {
+ t.Fatalf("expected 1 preview, got %d", len(previews))
+ }
+ if previews[0].Available {
+ t.Errorf("expected preview to be unavailable for %+v", tc)
+ }
+ })
+ }
+}
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
new file mode 100644
index 0000000..5d964df
--- /dev/null
+++ b/internal/registry/registry.go
@@ -0,0 +1,159 @@
+package registry
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "os"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/alvinunreal/lazyskills/internal/compat"
+)
+
+// Skill represents the sanitized/mapped registry skill fields.
+type Skill struct {
+ ID string `json:"id"`
+ DisplayName string `json:"display_name"`
+ Slug string `json:"slug"`
+ Source string `json:"source"`
+ Installs int `json:"installs"`
+ Invalid bool `json:"invalid,omitempty"`
+ Reason string `json:"reason,omitempty"`
+}
+
+// Client represents the skills.sh registry API client.
+type Client struct {
+ BaseURL string
+ HTTPClient *http.Client
+}
+
+// NewClient returns a registry Client initialized with base URL from environment or fallback, and a default timeout.
+func NewClient() *Client {
+ baseURL := os.Getenv("SKILLS_API_URL")
+ if baseURL == "" {
+ baseURL = "https://skills.sh"
+ }
+ return &Client{
+ BaseURL: baseURL,
+ HTTPClient: &http.Client{
+ Timeout: 9 * time.Second,
+ },
+ }
+}
+
+type apiResponse struct {
+ Skills []struct {
+ ID string `json:"id"`
+ SkillID string `json:"skillId"`
+ Name string `json:"name"`
+ Installs int `json:"installs"`
+ Source string `json:"source"`
+ } `json:"skills"`
+}
+
+// Search queries the registry API for matching skills.
+func (c *Client) Search(ctx context.Context, query string, limit int) ([]Skill, error) {
+ if len(query) < 2 {
+ return nil, nil
+ }
+
+ baseURL := c.BaseURL
+ if baseURL == "" {
+ baseURL = os.Getenv("SKILLS_API_URL")
+ if baseURL == "" {
+ baseURL = "https://skills.sh"
+ }
+ }
+
+ httpClient := c.HTTPClient
+ if httpClient == nil {
+ httpClient = &http.Client{
+ Timeout: 9 * time.Second,
+ }
+ }
+
+ parsedURL, err := url.Parse(baseURL)
+ if err != nil {
+ return nil, fmt.Errorf("invalid base URL %q: %w", baseURL, err)
+ }
+
+ u := parsedURL.ResolveReference(&url.URL{
+ Path: "/api/search",
+ })
+ q := url.Values{}
+ q.Set("q", query)
+ if limit > 0 {
+ q.Set("limit", strconv.Itoa(limit))
+ }
+ u.RawQuery = q.Encode()
+
+ req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create search request: %w", err)
+ }
+
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("registry search request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("unexpected registry response status: %d", resp.StatusCode)
+ }
+
+ var res apiResponse
+ if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
+ return nil, fmt.Errorf("failed to parse registry json response: %w", err)
+ }
+
+ skills := make([]Skill, 0, len(res.Skills))
+ for _, raw := range res.Skills {
+ slugRaw := raw.SkillID
+ if slugRaw == "" {
+ slugRaw = raw.Name
+ }
+ id := compat.SanitizeMetadata(raw.ID)
+ displayName := compat.SanitizeMetadata(raw.Name)
+ slug := compat.SanitizeMetadata(slugRaw)
+ source := compat.SanitizeMetadata(raw.Source)
+ invalid, reason := invalidCommandFields(slugRaw, raw.Source, slug, source)
+ skills = append(skills, Skill{
+ ID: id,
+ DisplayName: displayName,
+ Slug: slug,
+ Source: source,
+ Installs: raw.Installs,
+ Invalid: invalid,
+ Reason: reason,
+ })
+ }
+
+ // Sort by installs desc if API order is not reliable.
+ sort.Slice(skills, func(i, j int) bool {
+ return skills[i].Installs > skills[j].Installs
+ })
+
+ return skills, nil
+}
+
+func invalidCommandFields(rawSlug, rawSource, slug, source string) (bool, string) {
+ if rawSlug == "" || rawSource == "" {
+ return true, "registry result is missing an install slug or source"
+ }
+ if rawSlug != slug {
+ return true, "registry skill slug contains unsafe characters"
+ }
+ if rawSource != source {
+ return true, "registry source contains unsafe characters"
+ }
+ if strings.HasPrefix(slug, "-") || strings.HasPrefix(source, "-") {
+ return true, "registry install slug or source is option-like"
+ }
+ return false, ""
+}
diff --git a/internal/registry/registry_test.go b/internal/registry/registry_test.go
new file mode 100644
index 0000000..15906b8
--- /dev/null
+++ b/internal/registry/registry_test.go
@@ -0,0 +1,220 @@
+package registry
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+)
+
+func TestSearchSuccessAndSorting(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "skills": [
+ {"id": "owner/one/skill-1", "skillId": "skill-1", "name": "Skill One", "installs": 10, "source": "github.com/one"},
+ {"id": "owner/two/skill-2", "skillId": "skill-2", "name": "Skill Two", "installs": 99, "source": "github.com/two"}
+ ]
+ }`))
+ }))
+ defer server.Close()
+
+ client := &Client{
+ BaseURL: server.URL,
+ }
+
+ skills, err := client.Search(context.Background(), "test-query", 10)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ if len(skills) != 2 {
+ t.Fatalf("expected 2 skills, got %d", len(skills))
+ }
+
+ // Verify sorting by installs desc
+ if skills[0].Slug != "skill-2" || skills[1].Slug != "skill-1" {
+ t.Errorf("expected skill-2 first (99 installs) then skill-1 (10 installs), got order: %s, %s", skills[0].Slug, skills[1].Slug)
+ }
+
+ if skills[0].DisplayName != "Skill Two" || skills[0].Source != "github.com/two" || skills[0].Installs != 99 {
+ t.Errorf("unexpected fields for skill[0]: %+v", skills[0])
+ }
+ if skills[0].ID != "owner/two/skill-2" {
+ t.Errorf("expected registry id to be preserved separately, got %q", skills[0].ID)
+ }
+}
+
+func TestSearchFallsBackToNameForMissingSkillID(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "skills": [
+ {"id": "owner/repo/friendly-skill", "name": "friendly-skill", "installs": 10, "source": "owner/repo"}
+ ]
+ }`))
+ }))
+ defer server.Close()
+
+ client := &Client{BaseURL: server.URL}
+ skills, err := client.Search(context.Background(), "friendly", 10)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if len(skills) != 1 || skills[0].Slug != "friendly-skill" {
+ t.Fatalf("expected name fallback slug, got %+v", skills)
+ }
+}
+
+func TestSearchEscaping(t *testing.T) {
+ var requestedRawQuery string
+ var requestedPath string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requestedPath = r.URL.Path
+ requestedRawQuery = r.URL.RawQuery
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"skills": []}`))
+ }))
+ defer server.Close()
+
+ client := &Client{
+ BaseURL: server.URL,
+ }
+
+ query := "hello & world / ?"
+ _, err := client.Search(context.Background(), query, 3)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ if requestedPath != "/api/search" {
+ t.Errorf("expected path /api/search, got %q", requestedPath)
+ }
+
+ // Let's check query values
+ values, err := url.ParseQuery(requestedRawQuery)
+ if err != nil {
+ t.Fatalf("failed to parse query: %v", err)
+ }
+ if values.Get("q") != query {
+ t.Errorf("expected query parameter q=%q, got %q", query, values.Get("q"))
+ }
+ if values.Get("limit") != "3" {
+ t.Errorf("expected limit=3, got %q", values.Get("limit"))
+ }
+}
+
+func TestSearchNon200(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusInternalServerError)
+ }))
+ defer server.Close()
+
+ client := &Client{
+ BaseURL: server.URL,
+ }
+
+ _, err := client.Search(context.Background(), "query", 5)
+ if err == nil {
+ t.Fatal("expected error for non-200 response, but got nil")
+ }
+}
+
+func TestSearchMalformedJSON(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{ "skills": [{ "id": "1", "name": "bad`))
+ }))
+ defer server.Close()
+
+ client := &Client{
+ BaseURL: server.URL,
+ }
+
+ _, err := client.Search(context.Background(), "query", 5)
+ if err == nil {
+ t.Fatal("expected error for malformed json, but got nil")
+ }
+}
+
+func TestSearchEnvBaseURL(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"skills": []}`))
+ }))
+ defer server.Close()
+
+ t.Setenv("SKILLS_API_URL", server.URL)
+ client := NewClient()
+
+ if client.BaseURL != server.URL {
+ t.Errorf("expected BaseURL from env %q, got %q", server.URL, client.BaseURL)
+ }
+
+ _, err := client.Search(context.Background(), "query", 5)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
+
+func TestSearchShortQueryNoRequest(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t.Fatal("expected no request to be sent for short query")
+ }))
+ defer server.Close()
+
+ client := &Client{
+ BaseURL: server.URL,
+ }
+
+ skills, err := client.Search(context.Background(), "a", 5)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if skills != nil {
+ t.Errorf("expected nil skills for short query, got %+v", skills)
+ }
+}
+
+func TestSearchSanitization(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "skills": [
+ {"id": "id\u001b[31;1m-sanitized", "skillId": "slug\u001b[31m", "name": "name\nwith\rnewline", "installs": 5, "source": "source\u0000sanitized"}
+ ]
+ }`))
+ }))
+ defer server.Close()
+
+ client := &Client{
+ BaseURL: server.URL,
+ }
+
+ skills, err := client.Search(context.Background(), "query", 5)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ if len(skills) != 1 {
+ t.Fatalf("expected 1 skill, got %d", len(skills))
+ }
+
+ s := skills[0]
+ if s.ID != "id-sanitized" {
+ t.Errorf("expected sanitized id %q, got %q", "id-sanitized", s.ID)
+ }
+ if s.Slug != "slug" {
+ t.Errorf("expected sanitized display slug %q, got %q", "slug", s.Slug)
+ }
+ if s.DisplayName != "name withnewline" {
+ t.Errorf("expected sanitized display name %q, got %q", "name withnewline", s.DisplayName)
+ }
+ if s.Source != "sourcesanitized" {
+ t.Errorf("expected sanitized source %q, got %q", "sourcesanitized", s.Source)
+ }
+ if !s.Invalid || s.Reason == "" {
+ t.Errorf("expected unsafe command fields to mark result invalid, got %+v", s)
+ }
+}
diff --git a/internal/tui/state.go b/internal/tui/state.go
index ff9da1b..0fd6797 100644
--- a/internal/tui/state.go
+++ b/internal/tui/state.go
@@ -9,6 +9,7 @@ import (
"github.com/alvinunreal/lazyskills/internal/compat"
"github.com/alvinunreal/lazyskills/internal/display"
"github.com/alvinunreal/lazyskills/internal/model"
+ "github.com/alvinunreal/lazyskills/internal/registry"
)
func (m *appModel) syncViewport() {
@@ -608,3 +609,58 @@ func (m appModel) cachedSkillView(sk *model.Skill) display.SkillView {
}
return display.Skill(sk)
}
+
+type RegistryMatchStatus int
+
+const (
+ StatusInstallable RegistryMatchStatus = iota
+ StatusInstalled
+ StatusSimilarInstalled
+)
+
+func (m appModel) checkRegistrySkillStatus(s registry.Skill) (RegistryMatchStatus, string) {
+ sSource := normalizeSource(s.Source)
+ sSlug := compat.NormalizeName(s.Slug)
+ sDisplay := compat.NormalizeName(s.DisplayName)
+
+ similarMatch := false
+ var matchingInstalledSkillName string
+
+ for _, sk := range m.result.Skills {
+ info := sourceInfo(sk)
+ instSource := normalizeSource(info.Source)
+ instName := compat.NormalizeName(sk.Name)
+
+ nameMatch := (instName == sSlug || instName == sDisplay)
+ sourceMatch := (instSource != "" && sSource != "" && instSource == sSource)
+
+ if sourceMatch && nameMatch {
+ return StatusInstalled, fmt.Sprintf("Already installed in catalog from this source as %s", sk.Name)
+ }
+ if nameMatch {
+ similarMatch = true
+ matchingInstalledSkillName = sk.Name
+ }
+ }
+
+ if similarMatch {
+ return StatusSimilarInstalled, matchingInstalledSkillName
+ }
+
+ return StatusInstallable, ""
+}
+
+func normalizeSource(src string) string {
+ src = strings.ToLower(strings.TrimSpace(src))
+ src = strings.TrimPrefix(src, "git+https://")
+ src = strings.TrimPrefix(src, "https://")
+ src = strings.TrimPrefix(src, "http://")
+ src = strings.TrimPrefix(src, "git@") // for ssh URLs
+ src = strings.ReplaceAll(src, ":", "/") // normalize [email protected]:foo/bar
+ src = strings.TrimSuffix(src, ".git")
+ src = strings.TrimRight(src, "/")
+ for _, host := range []string{"github.com/", "gitlab.com/"} {
+ src = strings.TrimPrefix(src, host)
+ }
+ return src
+}
diff --git a/internal/tui/tui.go b/internal/tui/tui.go
index 7cb9bd3..0eacaa6 100644
--- a/internal/tui/tui.go
+++ b/internal/tui/tui.go
@@ -11,6 +11,7 @@ import (
"github.com/alvinunreal/lazyskills/internal/actions"
"github.com/alvinunreal/lazyskills/internal/display"
"github.com/alvinunreal/lazyskills/internal/model"
+ "github.com/alvinunreal/lazyskills/internal/registry"
"github.com/alvinunreal/lazyskills/internal/runner"
"github.com/alvinunreal/lazyskills/internal/scan"
"github.com/alvinunreal/lazyskills/internal/selfupdate"
@@ -105,6 +106,17 @@ type appModel struct {
updatePlan *selfupdate.UpdatePlan
updatePlanErr error
appUpdateModal bool
+ updatingApp bool
+ updateSuccess bool
+ updateError error
+ registryModal bool
+ registryQuery string
+ registryLoading bool
+ registryResults []registry.Skill
+ registrySelected int
+ registryError error
+ registryGeneration int
+ registryFocusList bool
}
type paneLayout struct {
@@ -186,6 +198,21 @@ type updatePlanMsg struct {
err error
}
+type appUpdateResultMsg struct {
+ err error
+}
+
+type registryDebounceMsg struct {
+ generation int
+ query string
+}
+
+type registrySearchMsg struct {
+ generation int
+ results []registry.Skill
+ err error
+}
+
func Run(cwd string) error {
program := tea.NewProgram(newModel(cwd), tea.WithAltScreen())
_, err := program.Run()
diff --git a/internal/tui/update.go b/internal/tui/update.go
index dc4f5ea..76de0b6 100644
--- a/internal/tui/update.go
+++ b/internal/tui/update.go
@@ -1,6 +1,7 @@
package tui
import (
+ "context"
"fmt"
"os"
"os/exec"
@@ -14,6 +15,7 @@ import (
"github.com/alvinunreal/lazyskills/internal/compat"
"github.com/alvinunreal/lazyskills/internal/locks"
"github.com/alvinunreal/lazyskills/internal/model"
+ "github.com/alvinunreal/lazyskills/internal/registry"
"github.com/alvinunreal/lazyskills/internal/runner"
)
@@ -157,6 +159,29 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.updatePlan = msg.plan
m.updatePlanErr = msg.err
m.syncViewport()
+ case appUpdateResultMsg:
+ m.updatingApp = false
+ if msg.err != nil {
+ m.updateError = msg.err
+ m.updateSuccess = false
+ } else {
+ m.updateSuccess = true
+ m.updateError = nil
+ }
+ m.syncViewport()
+ case registryDebounceMsg:
+ if msg.generation == m.registryGeneration {
+ m.registryLoading = true
+ return m, m.searchRegistryCmd(msg.query, msg.generation)
+ }
+ case registrySearchMsg:
+ if msg.generation == m.registryGeneration {
+ m.registryLoading = false
+ m.registryResults = msg.results
+ m.registryError = msg.err
+ m.registrySelected = 0
+ m.syncViewport()
+ }
case tea.KeyMsg:
key := msg.String()
var postKeyCmd tea.Cmd
@@ -166,6 +191,156 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
return m, nil
}
+ if m.registryModal {
+ switch key {
+ case "esc":
+ m.registryModal = false
+ m.registryQuery = ""
+ m.registryResults = nil
+ m.registryError = nil
+ m.registryLoading = false
+ m.syncViewport()
+ return m, nil
+ case "q":
+ if m.registryFocusList {
+ m.registryModal = false
+ m.registryQuery = ""
+ m.registryResults = nil
+ m.registryError = nil
+ m.registryLoading = false
+ m.syncViewport()
+ return m, nil
+ }
+ // Otherwise let it flow down to type 'q' in search query
+ case "ctrl+c":
+ return m, tea.Quit
+ case "tab":
+ m.registryFocusList = !m.registryFocusList
+ m.syncViewport()
+ return m, nil
+ case "up", "k":
+ if len(m.registryResults) > 0 {
+ m.registrySelected--
+ if m.registrySelected < 0 {
+ m.registrySelected = len(m.registryResults) - 1
+ }
+ m.syncViewport()
+ }
+ return m, nil
+ case "down", "j":
+ if len(m.registryResults) > 0 {
+ m.registrySelected++
+ if m.registrySelected >= len(m.registryResults) {
+ m.registrySelected = 0
+ }
+ m.syncViewport()
+ }
+ return m, nil
+ case "enter":
+ if !m.registryFocusList {
+ if len(m.registryQuery) >= 2 && (m.registryError != nil || len(m.registryResults) == 0) {
+ m.registryGeneration++
+ m.registryLoading = true
+ m.syncViewport()
+ return m, m.searchRegistryCmd(m.registryQuery, m.registryGeneration)
+ }
+ if len(m.registryResults) > 0 {
+ m.registryFocusList = true
+ m.syncViewport()
+ }
+ return m, nil
+ }
+ // List is focused: start project install confirmation
+ if len(m.registryResults) > 0 && m.registrySelected >= 0 && m.registrySelected < len(m.registryResults) {
+ s := m.registryResults[m.registrySelected]
+ status, checkMsg := m.checkRegistrySkillStatus(s)
+ if status == StatusInstalled || s.Invalid {
+ // Do not install
+ return m, nil
+ }
+ // Build preview
+ previews := actions.ForAvailableSkillWithOptions(s.Source, actions.InstallOptions{
+ DisplayName: s.DisplayName,
+ Slug: s.Slug,
+ Global: false,
+ })
+ if len(previews) > 0 && previews[0].Available {
+ m.registryModal = false
+ armed := previews[0]
+ if status == StatusSimilarInstalled {
+ armed.Description += " (Warning: A similar skill named '" + checkMsg + "' is already installed)."
+ }
+ m.pendingAction = &armed
+ m.confirming = true
+ m.confirmInput = ""
+ m.confirmError = ""
+ m.syncViewport()
+ return m, nil
+ }
+ }
+ return m, nil
+ case "g":
+ if m.registryFocusList {
+ // list focused: start global install confirmation
+ if len(m.registryResults) > 0 && m.registrySelected >= 0 && m.registrySelected < len(m.registryResults) {
+ s := m.registryResults[m.registrySelected]
+ status, checkMsg := m.checkRegistrySkillStatus(s)
+ if status == StatusInstalled || s.Invalid {
+ // Do not install
+ return m, nil
+ }
+ previews := actions.ForAvailableSkillWithOptions(s.Source, actions.InstallOptions{
+ DisplayName: s.DisplayName,
+ Slug: s.Slug,
+ Global: true,
+ })
+ if len(previews) > 0 && previews[0].Available {
+ m.registryModal = false
+ armed := previews[0]
+ if status == StatusSimilarInstalled {
+ armed.Description += " (Warning: A similar skill named '" + checkMsg + "' is already installed)."
+ }
+ m.pendingAction = &armed
+ m.confirming = true
+ m.confirmInput = ""
+ m.confirmError = ""
+ m.syncViewport()
+ return m, nil
+ }
+ }
+ return m, nil
+ }
+ // fallback: typing 'g'
+ }
+
+ // If input is focused and it's a typing key
+ if !m.registryFocusList {
+ switch key {
+ case "backspace", "ctrl+h":
+ if len(m.registryQuery) > 0 {
+ m.registryQuery = m.registryQuery[:len(m.registryQuery)-1]
+ }
+ default:
+ if len(key) == 1 {
+ m.registryQuery += key
+ }
+ }
+ m.registrySelected = 0
+ m.registryGeneration++
+ if len(m.registryQuery) >= 2 {
+ m.syncViewport()
+ return m, scheduleRegistrySearch(m.registryQuery, m.registryGeneration)
+ } else {
+ m.registryResults = nil
+ m.registryError = nil
+ m.registryLoading = false
+ m.syncViewport()
+ return m, nil
+ }
+ }
+
+ return m, nil
+ }
if m.appUpdateModal {
switch key {
case "esc", "q":
@@ -491,6 +666,9 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case "U":
m.appUpdateModal = true
m.syncViewport()
+ case "n":
+ m = m.openRegistryModal()
+ m.syncViewport()
case "c":
m.commands = !m.commands
m.action = 0
@@ -1056,6 +1234,11 @@ func confirmationError(action actions.CommandPreview) string {
func (m appModel) executeAction(action actions.CommandPreview) (tea.Model, tea.Cmd) {
m.commands = false
+ if action.Exec.Internal == "find_new_skills" {
+ m = m.openRegistryModal()
+ m.syncViewport()
+ return m, nil
+ }
if action.ID == "source_discover" {
m.actionResult = nil
return m.startDiscovery(action.ConfirmValue, true)
@@ -1324,6 +1507,18 @@ func (m appModel) executeAction(action actions.CommandPreview) (tea.Model, tea.C
}
}
+func (m appModel) openRegistryModal() appModel {
+ m.registryModal = true
+ m.registryQuery = ""
+ m.registryResults = nil
+ m.registrySelected = 0
+ m.registryError = nil
+ m.registryLoading = false
+ m.registryFocusList = false
+ m.registryGeneration++
+ return m
+}
+
func cleanupLockAfterRemove(action actions.CommandPreview, cwd string, result *runner.Result) bool {
if action.ID != "remove" || result == nil || result.ExitCode != 0 || result.Err != "" || action.ConfirmValue == "" {
return false
@@ -1612,3 +1807,22 @@ func insertToggleActions(previews, toggleActions []actions.CommandPreview) []act
out = append(out, previews[insertAt:]...)
return out
}
+func (m appModel) searchRegistryCmd(query string, gen int) tea.Cmd {
+ return func() tea.Msg {
+ client := registry.NewClient()
+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+ defer cancel()
+ results, err := client.Search(ctx, query, 10)
+ return registrySearchMsg{
+ generation: gen,
+ results: results,
+ err: err,
+ }
+ }
+}
+
+func scheduleRegistrySearch(query string, generation int) tea.Cmd {
+ return tea.Tick(300*time.Millisecond, func(time.Time) tea.Msg {
+ return registryDebounceMsg{generation: generation, query: query}
+ })
+}
diff --git a/internal/tui/update_test.go b/internal/tui/update_test.go
index 03a0990..36a4048 100644
--- a/internal/tui/update_test.go
+++ b/internal/tui/update_test.go
@@ -5,6 +5,10 @@ import (
"strings"
"testing"
+ "github.com/alvinunreal/lazyskills/internal/actions"
+ "github.com/alvinunreal/lazyskills/internal/model"
+ "github.com/alvinunreal/lazyskills/internal/registry"
+ "github.com/alvinunreal/lazyskills/internal/runner"
"github.com/alvinunreal/lazyskills/internal/selfupdate"
tea "github.com/charmbracelet/bubbletea"
)
@@ -165,3 +169,303 @@ func TestTUIAppUpdateModalStates(t *testing.T) {
t.Errorf("expected error message to be surfaced, got: %s", viewOut)
}
}
+
+func TestTUIRegistrySearchModalFlow(t *testing.T) {
+ t.Setenv("XDG_CACHE_HOME", t.TempDir())
+ m := newModel("")
+ m.width = 100
+ m.height = 30
+ m.result = model.ScanResult{
+ Skills: []*model.Skill{
+ {
+ Name: "already",
+ Scope: model.ScopeProject,
+ LocalLock: &model.LocalLockEntry{Source: "github.com/org/already"},
+ },
+ {
+ Name: "similar-matched",
+ Scope: model.ScopeProject,
+ LocalLock: &model.LocalLockEntry{Source: "github.com/org/another"},
+ },
+ },
+ }
+
+ // 1. Modal opens from app actions
+ previews := actions.AppLevelActions()
+ var regPreview *actions.CommandPreview
+ for i := range previews {
+ if previews[i].ID == "find_new_skills" {
+ regPreview = &previews[i]
+ }
+ }
+ if regPreview == nil {
+ t.Fatal("expected find_new_skills action in app-level actions")
+ }
+
+ modelTmp, cmd := m.Update(actionResultMsg{result: runner.Result{ExitCode: 0}}) // dummy trigger/sync check
+ m = modelTmp.(appModel)
+ modelTmp, cmd = m.executeAction(*regPreview)
+ m = modelTmp.(appModel)
+ if !m.registryModal {
+ t.Fatal("expected registryModal to be true after executing find_new_skills action")
+ }
+ if cmd != nil {
+ t.Fatal("expected no immediate command after opening registry search")
+ }
+
+ // Direct keyboard entry should also open the modal from normal inventory.
+ m.registryModal = false
+ modelTmp, cmd = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'n'}})
+ m = modelTmp.(appModel)
+ if !m.registryModal {
+ t.Fatal("expected n to open registry search modal")
+ }
+ if cmd != nil {
+ t.Fatal("expected no immediate command after n opens registry search")
+ }
+
+ // 2. Query <2 chars does not search
+ modelTmp, cmd = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'a'}})
+ m = modelTmp.(appModel)
+ if m.registryQuery != "a" {
+ t.Errorf("expected query to be 'a', got %q", m.registryQuery)
+ }
+ if cmd != nil {
+ t.Errorf("expected no search command for query < 2 chars, got: %T", cmd)
+ }
+
+ // 3. Query >= 2 chars schedules debounce search
+ modelTmp, cmd = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'b'}})
+ m = modelTmp.(appModel)
+ if m.registryQuery != "ab" {
+ t.Fatalf("expected query to be 'ab', got %q", m.registryQuery)
+ }
+ if cmd == nil {
+ t.Fatal("expected search command to be scheduled for query >= 2 chars")
+ }
+
+ // 4. Debounced/latest-query result handling
+ // Simulate debounce msg firing
+ modelTmp, cmd = m.Update(registryDebounceMsg{generation: m.registryGeneration, query: "ab"})
+ m = modelTmp.(appModel)
+ if !m.registryLoading {
+ t.Error("expected registryLoading to be true after debounce triggers search")
+ }
+ if cmd == nil {
+ t.Fatal("expected searchRegistryCmd to be returned by debounce handler")
+ }
+
+ // Stale/old generation debounce msg should be ignored
+ modelTmp2, cmd2 := m.Update(registryDebounceMsg{generation: m.registryGeneration - 1, query: "ab"})
+ if modelTmp2.(appModel).registryResults != nil || cmd2 != nil {
+ t.Error("expected stale debounce msg to be ignored")
+ }
+
+ // Make sure the view renders without crash in loading state
+ loadingView := m.View()
+ if !strings.Contains(loadingView, "Searching registry...") {
+ t.Errorf("expected view to indicate loading, got: %s", loadingView)
+ }
+
+ // Simulate search results payload
+ registryResults := []registry.Skill{
+ {
+ DisplayName: "Already Installed Skill",
+ Slug: "already",
+ Source: "github.com/org/already",
+ Installs: 42,
+ },
+ {
+ DisplayName: "Similar Installed Skill",
+ Slug: "similar-matched",
+ Source: "github.com/org/different-source",
+ Installs: 10,
+ },
+ {
+ DisplayName: "Brand New Skill",
+ Slug: "brand-new",
+ Source: "github.com/org/brand-new",
+ Installs: 999,
+ },
+ }
+
+ modelTmp, cmd = m.Update(registrySearchMsg{
+ generation: m.registryGeneration,
+ results: registryResults,
+ err: nil,
+ })
+ m = modelTmp.(appModel)
+ if m.registryLoading {
+ t.Error("expected registryLoading to be false after search result arrives")
+ }
+ if len(m.registryResults) != 3 {
+ t.Fatalf("expected 3 results, got %d", len(m.registryResults))
+ }
+
+ // View of results
+ resultsView := m.View()
+ if !strings.Contains(resultsView, "Already Installed Skill") {
+ t.Errorf("expected view to contain Displays Names, got: %s", resultsView)
+ }
+ if !strings.Contains(resultsView, "Similar Installed") {
+ t.Errorf("expected view to contain similarity check name, got: %s", resultsView)
+ }
+
+ // 5. Exact installed disables install; similar installed warns/allows.
+ // First selection is index 0: "Already Installed Skill" (exact installed)
+ m.registrySelected = 0
+ status0, _ := m.checkRegistrySkillStatus(m.registryResults[0])
+ if status0 != StatusInstalled {
+ t.Errorf("expected StatusInstalled, got %d", status0)
+ }
+ // Try to install project (enter) on exact installed: should do nothing (not close modal, not go to confirming)
+ m.registryFocusList = true
+ modelTmp, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ m = modelTmp.(appModel)
+ if !m.registryModal || m.confirming {
+ t.Error("expected install request on exact installed to be ignored (modal remains open, no confirmation)")
+ }
+
+ // Second selection is index 1: "Similar Installed Skill" (similar installed)
+ m.registrySelected = 1
+ status1, warnMsg1 := m.checkRegistrySkillStatus(m.registryResults[1])
+ if status1 != StatusSimilarInstalled {
+ t.Errorf("expected StatusSimilarInstalled, got %d", status1)
+ }
+ if warnMsg1 == "" {
+ t.Error("expected similar warning message, got empty")
+ }
+ // Try to install project on similar installed: should warn but allow (confirming = true, registryModal = false)
+ modelTmp, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ m = modelTmp.(appModel)
+ if m.registryModal || !m.confirming {
+ t.Error("expected install request on similar/name-only match to close registry search and schedule confirmation")
+ }
+ if m.pendingAction == nil {
+ t.Fatal("expected pending action to be armed")
+ }
+ if !strings.Contains(m.pendingAction.Description, "Warning: A similar skill") {
+ t.Errorf("expected confirmation descriptions to warn about similar installed skill, got: %s", m.pendingAction.Description)
+ }
+ usesSlug := false
+ for _, arg := range m.pendingAction.Args {
+ if arg == "similar-matched" {
+ usesSlug = true
+ }
+ if arg == "Similar Installed Skill" {
+ t.Fatalf("install command must use registry slug, not display name: %v", m.pendingAction.Args)
+ }
+ }
+ if !usesSlug {
+ t.Fatalf("expected project install command to use slug similar-matched, got %v", m.pendingAction.Args)
+ }
+
+ // 6. Global install appends -g
+ m.registryModal = true
+ m.confirming = false
+ m.pendingAction = nil
+ m.registrySelected = 2 // "Brand New Skill"
+ status2, _ := m.checkRegistrySkillStatus(m.registryResults[2])
+ if status2 != StatusInstallable {
+ t.Errorf("expected StatusInstallable, got %d", status2)
+ }
+ // Try to install globally ('g'): should arm confirmation with -g
+ modelTmp, cmd = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'g'}})
+ m = modelTmp.(appModel)
+ if m.registryModal || !m.confirming {
+ t.Error("expected global install ('g') to close registry search and schedule confirmation")
+ }
+ if m.pendingAction == nil {
+ t.Fatal("expected armed global confirmation action")
+ }
+ hasG := false
+ for _, arg := range m.pendingAction.Args {
+ if arg == "--global" {
+ hasG = true
+ break
+ }
+ }
+ if !hasG {
+ t.Errorf("expected global install command args to contain '--global', got: %v", m.pendingAction.Args)
+ }
+}
+
+func TestTUIRegistrySearchErrorStates(t *testing.T) {
+ t.Setenv("XDG_CACHE_HOME", t.TempDir())
+ m := newModel("")
+ m.width = 100
+ m.height = 30
+ m.registryModal = true
+ m.registryQuery = "xyz"
+
+ // Simulate error payload
+ modelTmp, _ := m.Update(registrySearchMsg{
+ generation: m.registryGeneration,
+ results: nil,
+ err: fmt.Errorf("API timeout/offline error"),
+ })
+ m = modelTmp.(appModel)
+
+ if m.registryError == nil {
+ t.Fatal("expected registryError to be recorded")
+ }
+
+ viewOut := m.View()
+ if !strings.Contains(viewOut, "API timeout/offline error") {
+ t.Errorf("expected error message in view, got: %s", viewOut)
+ }
+ if m.registryQuery != "xyz" {
+ t.Errorf("expected query text to be preserved on error, got %q", m.registryQuery)
+ }
+
+ // Simulate editing query to change it/retry
+ modelTmp, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'z'}})
+ m = modelTmp.(appModel)
+ if m.registryQuery != "xyzz" {
+ t.Errorf("expected query to be editable after error, got %q", m.registryQuery)
+ }
+ if cmd == nil {
+ t.Error("expected editing to trigger another debounced search")
+ }
+
+ // Enter in error state should retry the same query immediately.
+ m.registryError = fmt.Errorf("still offline")
+ modelTmp, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ m = modelTmp.(appModel)
+ if !m.registryLoading {
+ t.Error("expected enter to retry and set loading state")
+ }
+ if cmd == nil {
+ t.Error("expected enter retry to start registry search command")
+ }
+}
+
+func TestTUIRegistryInvalidResultDisablesInstall(t *testing.T) {
+ m := newModel("")
+ m.width = 100
+ m.height = 30
+ m.registryModal = true
+ m.registryQuery = "bad"
+ m.registryFocusList = true
+ m.registryResults = []registry.Skill{{
+ DisplayName: "Unsafe Skill",
+ Slug: "unsafe",
+ Source: "owner/repo",
+ Invalid: true,
+ Reason: "registry skill slug contains unsafe characters",
+ }}
+
+ help := m.registryModalHelpLine()
+ if strings.Contains(help, "enter install") || strings.Contains(help, "g install") {
+ t.Fatalf("invalid registry result should not advertise install keys, got %q", help)
+ }
+ if !strings.Contains(help, "install unavailable") {
+ t.Fatalf("expected unavailable help copy, got %q", help)
+ }
+
+ modelTmp, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
+ m = modelTmp.(appModel)
+ if cmd != nil || m.confirming || !m.registryModal {
+ t.Fatalf("invalid registry install should no-op in modal, confirming=%v modal=%v cmd=%v", m.confirming, m.registryModal, cmd)
+ }
+}
diff --git a/internal/tui/view.go b/internal/tui/view.go
index 1a77391..6f37c7a 100644
--- a/internal/tui/view.go
+++ b/internal/tui/view.go
@@ -30,6 +30,9 @@ func (m appModel) View() string {
return smallTerminalView(layout.Width, layout.Height)
}
+ if m.registryModal {
+ return m.registryModalOverlay(layout)
+ }
if m.detailModal {
return m.detailModalOverlay(layout)
}
@@ -1321,14 +1324,14 @@ func (m appModel) footerText(width int, rows []skillsRow, actions []actions.Comm
} else if m.helpOpen {
text = "esc/q/? close help"
} else if m.focus == focusMetadata {
- parts := []string{"↑/↓ scroll metadata", "enter open", "c commands"}
+ parts := []string{"↑/↓ scroll metadata", "enter open", "c commands", "n find new"}
if hasAvailableToggleAction(actions) {
parts = append(parts, "e enable/disable")
}
parts = append(parts, "? help")
text = strings.Join(parts, " · ")
} else if m.focus == focusPreview {
- parts := []string{"↑/↓ scroll preview", "enter open", "c commands"}
+ parts := []string{"↑/↓ scroll preview", "enter open", "c commands", "n find new"}
if hasAvailableToggleAction(actions) {
parts = append(parts, "e enable/disable")
}
@@ -1346,14 +1349,14 @@ func (m appModel) footerText(width int, rows []skillsRow, actions []actions.Comm
if discoverable, _ := m.isSourceDiscoverable(row.groupName); discoverable {
parts = append(parts, "d scan")
}
- parts = append(parts, "c actions", "? help")
+ parts = append(parts, "c actions", "n find new", "? help")
text = strings.Join(parts, " · ")
} else {
parts := []string{"enter open"}
if hasAvailableToggleAction(actions) {
parts = append(parts, "e enable/disable")
}
- parts = append(parts, "c actions")
+ parts = append(parts, "c actions", "n find new")
if hasAvailableAction(actions, preferredUpdateActionID(m.selectedCount())) {
parts = append(parts, "u update")
}
@@ -1364,7 +1367,7 @@ func (m appModel) footerText(width int, rows []skillsRow, actions []actions.Comm
text = strings.Join(parts, " · ")
}
} else {
- text = "enter open · c actions · ? help"
+ text = "n find new · c actions · ? help"
}
}
isNormalState := !m.running && !m.confirming && !m.searching && !m.detailModal && !m.commands && !m.helpOpen
@@ -1430,6 +1433,7 @@ func (m appModel) helpModalOverlay(layout appLayout) string {
" o Open selected skill directly in editor",
" e Enable / disable selected skill or source group",
" c Open command picker menu",
+ " n Find and install new skills from skills.sh",
" u / x Quick reinstall-update / remove for selection",
" U Check/run LazySkills application update",
" d Check local or remote source for available skills (Source row)",
@@ -1703,3 +1707,248 @@ func truncateReleaseNotes(notes string, width int) string {
}
return strings.Join(out, "\n")
}
+
+func (m appModel) registryModalOverlay(layout appLayout) string {
+ modalWidth, modalHeight := detailModalDimensions(layout)
+ innerWidth := modalWidth - 4
+ innerHeight := modalHeight - 6
+
+ // Split innerWidth: left is 45%, right is 55%
+ leftWidth := innerWidth * 45 / 100
+ rightWidth := innerWidth - leftWidth - 3 // leave a small space/divider
+
+ // Left pane header: Query input
+ var inputLine string
+ focusPrompt := "Search: "
+ if !m.registryFocusList {
+ focusPrompt = "Search › "
+ }
+ if m.registryQuery == "" {
+ inputLine = focusPrompt + dimStyle.Render("Type to search...")
+ } else {
+ inputLine = lipgloss.NewStyle().Foreground(lipgloss.Color("205")).Bold(true).Render(focusPrompt) + m.registryQuery + "_"
+ }
+
+ var leftContentLines []string
+ leftContentLines = append(leftContentLines, inputLine, "")
+
+ // Left pane body: status or results
+ if m.registryLoading {
+ leftContentLines = append(leftContentLines, " "+runningStyle.Render("Searching registry..."))
+ } else if m.registryError != nil {
+ leftContentLines = append(leftContentLines,
+ errorStyle.Render(" Error fetching results:"),
+ wrapText(" "+m.registryError.Error(), leftWidth),
+ "",
+ " Press Enter to retry, or type to search.",
+ )
+ } else if len(m.registryQuery) < 2 {
+ leftContentLines = append(leftContentLines, " Type at least 2 characters to search.")
+ } else if len(m.registryResults) == 0 {
+ leftContentLines = append(leftContentLines, " No skills found in registry.")
+ } else {
+ // Show results
+ for idx, s := range m.registryResults {
+ selector := " "
+ if idx == m.registrySelected {
+ selector = "› "
+ }
+
+ status, _ := m.checkRegistrySkillStatus(s)
+ var badge string
+ if status == StatusInstalled {
+ badge = scopeProjectStyle.Render("[installed]")
+ } else if status == StatusSimilarInstalled {
+ badge = warningStyle.Render("[similar]")
+ }
+
+ installsText := fmt.Sprintf("%d↓", s.Installs)
+ installsStyled := dimStyle.Render(installsText)
+
+ // Selector (2) + Name(?) + Badge(?) + Installs(?)
+ // Let's truncate Name to fit nicely in leftWidth
+ rightPart := ""
+ if badge != "" {
+ rightPart = badge + " " + installsStyled
+ } else {
+ rightPart = installsStyled
+ }
+ rightPartWidth := lipgloss.Width(rightPart)
+ availNameWidth := leftWidth - 2 - rightPartWidth - 1 // 1 space padding
+ if availNameWidth < 5 {
+ availNameWidth = 5
+ }
+ namePart := truncate(s.DisplayName, availNameWidth)
+
+ // Pad the line
+ line := selector + namePart
+ paddingLen := leftWidth - lipgloss.Width(line) - rightPartWidth
+ if paddingLen > 0 {
+ line += strings.Repeat(" ", paddingLen)
+ }
+ line += rightPart
+
+ if idx == m.registrySelected {
+ leftContentLines = append(leftContentLines, selectedStyle.Render(padRight(line, leftWidth)))
+ } else {
+ leftContentLines = append(leftContentLines, line)
+ }
+ }
+ }
+
+ leftPane := fitLines(strings.Join(leftContentLines, "\n"), innerHeight)
+
+ // Right pane: detail preview
+ var rightContentLines []string
+ if len(m.registryResults) > 0 && m.registrySelected >= 0 && m.registrySelected < len(m.registryResults) {
+ s := m.registryResults[m.registrySelected]
+ status, similarMsg := m.checkRegistrySkillStatus(s)
+
+ rightContentLines = append(rightContentLines,
+ titleStyle.Render(s.DisplayName),
+ "",
+ formatMetaLine("Slug:", s.Slug, rightWidth),
+ formatMetaLine("Source:", s.Source, rightWidth),
+ formatMetaLine("Installs:", fmt.Sprintf("%d", s.Installs), rightWidth),
+ )
+
+ // Fetch previews
+ projActions := actions.ForAvailableSkillWithOptions(s.Source, actions.InstallOptions{
+ DisplayName: s.DisplayName,
+ Slug: s.Slug,
+ Global: false,
+ })
+ globalActions := actions.ForAvailableSkillWithOptions(s.Source, actions.InstallOptions{
+ DisplayName: s.DisplayName,
+ Slug: s.Slug,
+ Global: true,
+ })
+
+ allowInstall := true
+ cantInstallReason := ""
+ if len(projActions) == 0 {
+ allowInstall = false
+ cantInstallReason = "installation configuration failed"
+ } else if !projActions[0].Available {
+ allowInstall = false
+ cantInstallReason = projActions[0].Reason
+ }
+
+ var statusVal string
+ if status == StatusInstalled {
+ statusVal = scopeProjectStyle.Render("[installed] Already installed")
+ allowInstall = false
+ cantInstallReason = "Already installed in project or global catalog."
+ } else if s.Invalid {
+ statusVal = errorStyle.Render("unavailable")
+ allowInstall = false
+ cantInstallReason = compat.FirstNonEmpty(s.Reason, "registry result cannot be safely installed")
+ } else if status == StatusSimilarInstalled {
+ statusVal = warningStyle.Render("[similar] Similar name installed")
+ } else {
+ statusVal = lipgloss.NewStyle().Foreground(lipgloss.Color("114")).Render("not installed (installable)")
+ }
+
+ rightContentLines = append(rightContentLines, formatMetaLine("Status:", statusVal, rightWidth))
+ if status == StatusSimilarInstalled && similarMsg != "" {
+ rightContentLines = append(rightContentLines, "", errorStyle.Render(wrapText("Notice: A similar skill named '"+similarMsg+"' is already installed.", rightWidth)))
+ }
+
+ // Install Command previews
+ rightContentLines = append(rightContentLines, "")
+ rightContentLines = append(rightContentLines, sectionHeaderStyle.Render("Install Commands:"), "")
+
+ if !allowInstall && cantInstallReason != "" {
+ rightContentLines = append(rightContentLines, errorStyle.Render(wrapText("Installations disabled: "+cantInstallReason, rightWidth)))
+ } else {
+ if len(projActions) > 0 && projActions[0].Available {
+ rightContentLines = append(rightContentLines,
+ dimStyle.Render("Project-local:"),
+ " "+projActions[0].Command,
+ )
+ }
+ if len(globalActions) > 0 && globalActions[0].Available {
+ rightContentLines = append(rightContentLines,
+ dimStyle.Render("Globally (adds -g):"),
+ " "+globalActions[0].Command,
+ )
+ }
+ }
+ } else {
+ rightContentLines = append(rightContentLines, dimStyle.Render("Select a registry search result to view details."))
+ }
+
+ rightPane := fitLines(strings.Join(rightContentLines, "\n"), innerHeight)
+
+ // Vertical divider
+ var dividerLines []string
+ for i := 0; i < innerHeight; i++ {
+ dividerLines = append(dividerLines, dimStyle.Render("│"))
+ }
+ dividerString := strings.Join(dividerLines, "\n")
+
+ // Combine left and right
+ body := lipgloss.JoinHorizontal(lipgloss.Top,
+ lipgloss.NewStyle().Width(leftWidth).Render(leftPane),
+ " ",
+ dividerString,
+ " ",
+ lipgloss.NewStyle().Width(rightWidth).Render(rightPane),
+ )
+
+ // Help line
+ helpLineText := m.registryModalHelpLine()
+ helpLine := dimStyle.Render(helpLineText)
+
+ content := []string{
+ titleStyle.Render(" Skills.sh Registry Search "),
+ "",
+ body,
+ "",
+ helpLine,
+ }
+
+ box := lipgloss.NewStyle().
+ Border(lipgloss.RoundedBorder()).
+ BorderForeground(actionBorderColor).
+ Padding(1, 2).
+ Width(modalWidth).
+ Height(modalHeight).
+ Render(strings.Join(content, "\n"))
+
+ return fitToScreen(lipgloss.Place(layout.Width, layout.Height, lipgloss.Center, lipgloss.Center, box), layout.Width, layout.Height)
+}
+
+func (m appModel) registryModalHelpLine() string {
+ if !m.registryFocusList {
+ if m.registryError != nil && len(m.registryQuery) >= 2 {
+ return "type search · enter retry · tab select list · esc close"
+ }
+ return "type search · tab select list · esc close"
+ }
+ parts := []string{"type search", "↑/↓ choose"}
+ if m.selectedRegistryResultInstallable() {
+ parts = append(parts, "enter install to project", "g install globally")
+ } else {
+ parts = append(parts, "install unavailable")
+ }
+ parts = append(parts, "tab type search", "esc close")
+ return strings.Join(parts, " · ")
+}
+
+func (m appModel) selectedRegistryResultInstallable() bool {
+ if len(m.registryResults) == 0 || m.registrySelected < 0 || m.registrySelected >= len(m.registryResults) {
+ return false
+ }
+ s := m.registryResults[m.registrySelected]
+ if s.Invalid {
+ return false
+ }
+ status, _ := m.checkRegistrySkillStatus(s)
+ if status == StatusInstalled {
+ return false
+ }
+ projectActions := actions.ForAvailableSkillWithOptions(s.Source, actions.InstallOptions{DisplayName: s.DisplayName, Slug: s.Slug, Global: false})
+ globalActions := actions.ForAvailableSkillWithOptions(s.Source, actions.InstallOptions{DisplayName: s.DisplayName, Slug: s.Slug, Global: true})
+ return len(projectActions) > 0 && projectActions[0].Available && len(globalActions) > 0 && globalActions[0].Available
+}