diff --git a/cmd/skillshare/install.go b/cmd/skillshare/install.go index 0b95b13d6..68045c0dc 100644 --- a/cmd/skillshare/install.go +++ b/cmd/skillshare/install.go @@ -639,8 +639,8 @@ func printInstallHelp() { {"skillshare install ~/my-skill --into frontend/react", ""}, }}, helpGroup{title: "Tracked repositories (Team Edition)", examples: true, rows: []helpRow{ - {"skillshare install team/shared-skills --track", "Clone as _shared-skills"}, - {"skillshare install _shared-skills --update", "Update tracked repo"}, + {"skillshare install team/shared-skills --track", "Clone as _team-shared-skills"}, + {"skillshare install _team-shared-skills --update", "Update tracked repo"}, }}, helpGroup{title: "Install from config (no arguments)", examples: true, rows: []helpRow{ {"skillshare install", "Install all skills from config.yaml"}, diff --git a/cmd/skillshare/install_context.go b/cmd/skillshare/install_context.go index 2c794e8e9..575ebce52 100644 --- a/cmd/skillshare/install_context.go +++ b/cmd/skillshare/install_context.go @@ -1,8 +1,6 @@ package main import ( - "strings" - "skillshare/internal/config" "skillshare/internal/install" ) @@ -13,37 +11,6 @@ var ( _ install.InstallContext = (*projectInstallContext)(nil) ) -// storeToSkillEntryDTOs converts MetadataStore entries to []install.SkillEntryDTO. -func storeToSkillEntryDTOs(store *install.MetadataStore) []install.SkillEntryDTO { - names := store.List() // sorted - dtos := make([]install.SkillEntryDTO, 0, len(names)) - for _, name := range names { - entry := store.Get(name) - if entry == nil { - continue - } - relPath := install.KeyToRelPath(name, entry) - group, bareName := splitMetadataRelPath(relPath) - dtos = append(dtos, install.SkillEntryDTO{ - Name: bareName, - Source: entry.Source, - Tracked: entry.Tracked, - Group: group, - Branch: entry.Branch, - }) - } - return dtos -} - -func splitMetadataRelPath(relPath string) (group, name string) { - relPath = strings.Trim(relPath, "/") - idx := strings.LastIndex(relPath, "/") - if idx < 0 { - return "", relPath - } - return relPath[:idx], relPath[idx+1:] -} - // --------------------------------------------------------------------------- // globalInstallContext // --------------------------------------------------------------------------- @@ -56,7 +23,7 @@ type globalInstallContext struct { func (g *globalInstallContext) SourcePath() string { return g.cfg.EffectiveSkillsSource() } func (g *globalInstallContext) ConfigSkills() []install.SkillEntryDTO { - return storeToSkillEntryDTOs(g.store) + return install.MetadataSkillEntries(g.store) } func (g *globalInstallContext) Reconcile() error { return config.ReconcileGlobalSkills(g.cfg, g.store) @@ -79,18 +46,7 @@ type projectInstallContext struct { func (p *projectInstallContext) SourcePath() string { return p.runtime.sourcePath } func (p *projectInstallContext) ConfigSkills() []install.SkillEntryDTO { - skills := p.runtime.config.Skills - dtos := make([]install.SkillEntryDTO, 0, len(skills)) - for _, s := range skills { - dtos = append(dtos, install.SkillEntryDTO{ - Name: s.Name, - Source: s.Source, - Tracked: s.Tracked, - Group: s.Group, - Branch: s.Branch, - }) - } - return dtos + return config.ProjectSkillEntries(p.runtime.config.Skills) } func (p *projectInstallContext) Reconcile() error { return reconcileProjectRemoteSkills(p.runtime) diff --git a/cmd/skillshare/install_handlers.go b/cmd/skillshare/install_handlers.go index 43dcd4bc5..24cd25d26 100644 --- a/cmd/skillshare/install_handlers.go +++ b/cmd/skillshare/install_handlers.go @@ -747,6 +747,37 @@ func buildInstallSummary(installed, failed, skipped int, noun string) string { return strings.Join(parts, ", ") } +// buildConfigInstallSummary formats the summary for installing from config, +// counting tracked repos apart from single skills. +func buildConfigInstallSummary(r install.ConfigInstallResult) string { + var parts []string + plainInstalled := r.Installed - r.InstalledRepos + if r.InstalledRepos > 0 { + parts = append(parts, fmt.Sprintf("Installed %s (%s)", + plural(r.InstalledRepos, "tracked repo"), plural(r.InstalledRepoSkills, "skill"))) + if plainInstalled > 0 { + parts = append(parts, plural(plainInstalled, "skill")) + } + } else { + parts = append(parts, "Installed "+plural(plainInstalled, "skill")) + } + if r.Skipped > 0 { + skipped := fmt.Sprintf("%d skipped", r.Skipped) + if r.SkippedRepos > 0 { + kinds := []string{plural(r.SkippedRepos, "repo")} + if n := r.Skipped - r.SkippedRepos; n > 0 { + kinds = append(kinds, plural(n, "skill")) + } + skipped += " (" + strings.Join(kinds, ", ") + ")" + } + parts = append(parts, skipped) + } + if len(r.FailedSkills) > 0 { + parts = append(parts, fmt.Sprintf("%d failed", len(r.FailedSkills))) + } + return strings.Join(parts, ", ") +} + func handleDirectInstall(source *install.Source, cfg *config.Config, opts install.InstallOptions) (installLogSummary, error) { logSummary := installLogSummary{ Source: source.Raw, @@ -895,18 +926,11 @@ func installFromGlobalConfig(cfg *config.Config, opts install.InstallOptions) (i } elapsed := time.Since(installStart) - parts := []string{"Installed " + plural(result.Installed, "skill")} - if result.Skipped > 0 { - parts = append(parts, fmt.Sprintf("%d skipped", result.Skipped)) - } - if len(result.FailedSkills) > 0 { - parts = append(parts, fmt.Sprintf("%d failed", len(result.FailedSkills))) - } status := "success" if len(result.FailedSkills) > 0 { status = "error" } - ui.StepResult(status, strings.Join(parts, ", "), elapsed) + ui.StepResult(status, buildConfigInstallSummary(result), elapsed) // Show failed details if len(result.FailedSkills) > 0 { diff --git a/cmd/skillshare/install_project.go b/cmd/skillshare/install_project.go index da4ef9b72..0074ceef8 100644 --- a/cmd/skillshare/install_project.go +++ b/cmd/skillshare/install_project.go @@ -144,7 +144,7 @@ func installFromProjectConfig(runtime *projectRuntime, opts install.InstallOptio spinner.Stop() fmt.Println() - ui.Done(ui.MarkOK, "Installed "+plural(result.Installed, "skill"), time.Since(spinner.Started())) + ui.Done(ui.MarkOK, buildConfigInstallSummary(result), time.Since(spinner.Started())) ui.Next("skillshare sync", "link them into your targets") return summary, nil diff --git a/cmd/skillshare/install_warning_output_test.go b/cmd/skillshare/install_warning_output_test.go index 78d2700e5..3cfcd7475 100644 --- a/cmd/skillshare/install_warning_output_test.go +++ b/cmd/skillshare/install_warning_output_test.go @@ -526,3 +526,25 @@ func TestDisplayInstallResults_SkippedFallbackLabel(t *testing.T) { t.Errorf("expected fallback 'same repo' label, got:\n%s", output) } } + +func TestBuildConfigInstallSummary(t *testing.T) { + tests := []struct { + name string + in install.ConfigInstallResult + want string + }{ + {"skills only", install.ConfigInstallResult{Installed: 3, Skipped: 1}, "Installed 3 skills, 1 skipped"}, + {"tracked repo", install.ConfigInstallResult{Installed: 1, InstalledRepos: 1, InstalledRepoSkills: 12, Skipped: 9, SkippedRepos: 1}, + "Installed 1 tracked repo (12 skills), 9 skipped (1 repo, 8 skills)"}, + {"repo and skills", install.ConfigInstallResult{Installed: 3, InstalledRepos: 1, InstalledRepoSkills: 5, FailedSkills: []string{"x"}}, + "Installed 1 tracked repo (5 skills), 2 skills, 1 failed"}, + {"only repos skipped", install.ConfigInstallResult{Skipped: 2, SkippedRepos: 2}, "Installed 0 skills, 2 skipped (2 repos)"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := buildConfigInstallSummary(tt.in); got != tt.want { + t.Errorf("got %q, want %q", got, tt.want) + } + }) + } +} diff --git a/internal/config/project_reconcile.go b/internal/config/project_reconcile.go index 8f43494af..f7e25505f 100644 --- a/internal/config/project_reconcile.go +++ b/internal/config/project_reconcile.go @@ -250,3 +250,13 @@ func ReconcileProjectAgents(projectRoot string, store *install.MetadataStore, ag return nil } + +// ProjectSkillEntries lists a project's config skills as install entries, the +// project counterpart of install.MetadataSkillEntries. +func ProjectSkillEntries(skills []SkillEntry) []install.SkillEntryDTO { + dtos := make([]install.SkillEntryDTO, 0, len(skills)) + for _, s := range skills { + dtos = append(dtos, install.SkillEntryDTO{Name: s.Name, Source: s.Source, Tracked: s.Tracked, Group: s.Group, Branch: s.Branch}) + } + return dtos +} diff --git a/internal/install/context.go b/internal/install/context.go index cf1f28feb..0b561c814 100644 --- a/internal/install/context.go +++ b/internal/install/context.go @@ -72,8 +72,13 @@ type InstallContext interface { // ConfigInstallResult summarises the outcome of InstallFromConfig. type ConfigInstallResult struct { - Installed int - Skipped int - InstalledSkills []string - FailedSkills []string + Installed int + Skipped int + // Tracked repos counted within Installed/Skipped, so the summary can tell + // a whole repo apart from a single skill. + InstalledRepos int + InstalledRepoSkills int // skills inside InstalledRepos + SkippedRepos int + InstalledSkills []string + FailedSkills []string } diff --git a/internal/install/install.go b/internal/install/install.go index 6a2c1b28c..4cfa9e03a 100644 --- a/internal/install/install.go +++ b/internal/install/install.go @@ -356,9 +356,3 @@ func GetTrackedRepos(sourceDir string, walk ...sourcewalk.Options) ([]string, er func GetMissingTrackedRepos(sourceDir string, walks ...sourcewalk.Options) ([]TrackedRepoMeta, error) { return getMissingTrackedReposImpl(sourceDir, walks...) } - -// RehydrateMissingTrackedRepos re-clones tracked repos declared in metadata whose -// clone directories are absent on disk. Repos already present are left untouched. -func RehydrateMissingTrackedRepos(sourceDir string, parseOpts ParseOptions, opts InstallOptions) ([]RehydrateResult, error) { - return rehydrateMissingTrackedReposImpl(sourceDir, parseOpts, opts) -} diff --git a/internal/install/install_config.go b/internal/install/install_config.go index 303e48da4..25cbcf018 100644 --- a/internal/install/install_config.go +++ b/internal/install/install_config.go @@ -103,6 +103,44 @@ func matchDiscoveredSkillBySubdir(discovery *DiscoveryResult, subdir string) (Sk return SkillInfo{}, false } +// MetadataSkillEntries lists the entries of a metadata store as config skills, +// sorted by key; it is the global-mode source of InstallContext.ConfigSkills. +func MetadataSkillEntries(store *MetadataStore) []SkillEntryDTO { + names := store.List() // sorted + dtos := make([]SkillEntryDTO, 0, len(names)) + for _, name := range names { + entry := store.Get(name) + if entry == nil { + continue + } + group, bareName := splitTrackedRelPath(filepath.ToSlash(KeyToRelPath(name, entry))) + dtos = append(dtos, SkillEntryDTO{ + Name: bareName, + Source: entry.Source, + Tracked: entry.Tracked, + Group: group, + Branch: entry.Branch, + }) + } + return dtos +} + +// MissingFromConfig returns the config skills InstallFromConfig would install: +// entries with a name whose directory does not exist on disk. +func MissingFromConfig(ctx InstallContext) []SkillEntryDTO { + sourcePath := ctx.SourcePath() + var missing []SkillEntryDTO + for _, skill := range ctx.ConfigSkills() { + if _, bareName := skill.EffectiveParts(); strings.TrimSpace(bareName) == "" { + continue + } + if _, err := os.Stat(filepath.Join(sourcePath, filepath.FromSlash(skill.FullName()))); err != nil { + missing = append(missing, skill) + } + } + return missing +} + // InstallFromConfig iterates over the remote skills listed in the config // (via ctx.ConfigSkills) and installs each one that is not already present. // It handles both tracked repos and plain skills, delegates per-skill hooks @@ -150,6 +188,9 @@ func InstallFromConfig(ctx InstallContext, opts InstallOptions) (ConfigInstallRe if _, err := os.Stat(destPath); err == nil { if locked == "" || InstalledCommit(destPath, store.GetByPath(displayName)) == locked { result.Skipped++ + if skill.Tracked { + result.SkippedRepos++ + } if !opts.Quiet { ui.StepDone(displayName, "skipped (already exists)") } @@ -230,6 +271,8 @@ func InstallFromConfig(ctx InstallContext, opts InstallOptions) (ConfigInstallRe } result.InstalledSkills = append(result.InstalledSkills, installed.skills...) result.Installed++ + result.InstalledRepos++ + result.InstalledRepoSkills += installed.skillCount } // ── Phase 2: grouped plain skills (clone once per repo) ── @@ -341,9 +384,10 @@ func InstallFromConfig(ctx InstallContext, opts InstallOptions) (ConfigInstallRe // trackedInstallOutcome captures the result of a single tracked-repo install // within the config loop. type trackedInstallOutcome struct { - failed bool - action string // only meaningful on dry-run - skills []string // skills names to record + failed bool + action string // only meaningful on dry-run + skills []string // skills names to record + skillCount int // skills discovered in the repo } // installTrackedFromConfig installs a single tracked repo from config and @@ -356,6 +400,7 @@ func installTrackedFromConfig( opts InstallOptions, ) trackedInstallOutcome { trackOpts := opts + trackOpts.Name = source.Name // keep the name recorded in config if groupDir != "" { trackOpts.Into = groupDir } @@ -380,7 +425,7 @@ func installTrackedFromConfig( if len(skills) == 0 { skills = []string{displayName} } - return trackedInstallOutcome{skills: skills} + return trackedInstallOutcome{skills: skills, skillCount: trackedResult.SkillCount} } // installPlainFromConfig installs a single non-tracked skill from config. diff --git a/internal/install/install_queries.go b/internal/install/install_queries.go index d74439f93..ab0d8459f 100644 --- a/internal/install/install_queries.go +++ b/internal/install/install_queries.go @@ -81,70 +81,6 @@ func getMissingTrackedReposImpl(sourceDir string, walks ...sourcewalk.Options) ( return missing, nil } -// RehydrateResult reports the outcome of rehydrating one missing tracked repo. -type RehydrateResult struct { - Name string `json:"name"` - Action string `json:"action"` // "rehydrated" | "error" - Error string `json:"error,omitempty"` -} - -// rehydrateMissingTrackedReposImpl re-clones tracked repos declared in metadata -// whose clone directories are absent on disk. It mirrors the tracked-repo phase -// of InstallFromConfig (bare `skillshare install`); repos already on disk are -// left untouched. See issue #212. -func rehydrateMissingTrackedReposImpl(sourceDir string, parseOpts ParseOptions, opts InstallOptions) ([]RehydrateResult, error) { - store, err := LoadMetadata(sourceDir) - if err != nil { - return nil, err - } - existingRepos, err := GetTrackedRepos(sourceDir, sourcewalk.Options{Follow: opts.SourceFollow}) - if err != nil { - return nil, err - } - existing := make(map[string]bool, len(existingRepos)) - for _, repo := range existingRepos { - existing[repo] = true - } - - opts.Quiet = true - opts.Update = false - var results []RehydrateResult - for _, key := range store.List() { - entry := store.Get(key) - if entry == nil || !entry.Tracked { - continue - } - relPath := filepath.ToSlash(KeyToRelPath(key, entry)) - if !strings.HasPrefix(filepath.Base(relPath), "_") { - continue - } - if existing[relPath] { - continue - } - - groupDir, bareName := splitTrackedRelPath(relPath) - source, perr := ParseSourceWithOptions(entry.Source, parseOpts) - if perr != nil { - results = append(results, RehydrateResult{Name: relPath, Action: "error", Error: "invalid source: " + perr.Error()}) - continue - } - source.Name = bareName - source.ApplyRecordedBranch(entry.Branch) - - trackOpts := opts - trackOpts.Name = bareName - if groupDir != "" { - trackOpts.Into = groupDir - } - if _, ierr := InstallTrackedRepo(source, sourceDir, trackOpts); ierr != nil { - results = append(results, RehydrateResult{Name: relPath, Action: "error", Error: ierr.Error()}) - continue - } - results = append(results, RehydrateResult{Name: relPath, Action: "rehydrated"}) - } - return results, nil -} - // splitTrackedRelPath splits a tracked repo's relative path into its parent // group directory and base name (the base retains its leading "_"). func splitTrackedRelPath(relPath string) (group, name string) { diff --git a/internal/install/install_tracked.go b/internal/install/install_tracked.go index eb51590d4..1ffc956d9 100644 --- a/internal/install/install_tracked.go +++ b/internal/install/install_tracked.go @@ -17,13 +17,22 @@ func installTrackedRepoImpl(source *Source, sourceDir string, opts InstallOption return nil, err } - // Determine repo name: opts.Name > source.Name (from config) > TrackName (derived from URL) + // Determine repo name: opts.Name (--name or the name recorded in config) > + // TrackName (owner-repo, so two repos both called "skills" don't collide) > + // source.Name. ParseSource always fills source.Name with the URL basename, + // so it must not win over TrackName. repoName := opts.Name if repoName == "" { - repoName = source.Name + repoName = source.TrackName() + // Before owner-repo naming the clone was _; keep using that + // checkout when it is the same repo, so a repeat install does not clone twice. + legacy := filepath.Join(sourceDir, opts.Into, "_"+strings.TrimPrefix(source.Name, "_")) + if source.Name != "" && repoURLsMatch(getRemoteURL(legacy), source.CloneURL) { + repoName = source.Name + } } if repoName == "" { - repoName = source.TrackName() + repoName = source.Name } // Prefix with _ to indicate tracked repo (avoid double prefix if user already added _) diff --git a/internal/install/install_tracked_test.go b/internal/install/install_tracked_test.go index 0f711f0dc..9ab71c09d 100644 --- a/internal/install/install_tracked_test.go +++ b/internal/install/install_tracked_test.go @@ -1,6 +1,7 @@ package install import ( + "errors" "os" "os/exec" "path/filepath" @@ -57,9 +58,25 @@ func fileURL(p string) string { return "file://" + p } -// TestRehydrateMissingTrackedRepos_ReclonesAbsent verifies that a tracked repo -// declared in metadata but absent on disk is re-cloned (issue #212). -func TestRehydrateMissingTrackedRepos_ReclonesAbsent(t *testing.T) { +// metadataInstallContext is a global-mode InstallContext over a metadata file. +type metadataInstallContext struct{ dir string } + +func (c metadataInstallContext) SourcePath() string { return c.dir } +func (c metadataInstallContext) ConfigSkills() []SkillEntryDTO { + return MetadataSkillEntries(LoadMetadataOrNew(c.dir)) +} +func (metadataInstallContext) Reconcile() error { return nil } +func (metadataInstallContext) PostInstallSkill(string) error { return nil } +func (metadataInstallContext) Mode() string { return "global" } +func (metadataInstallContext) GitLabHosts() []string { return nil } +func (metadataInstallContext) AzureHosts() []string { return nil } +func (metadataInstallContext) CNBHosts() []string { return nil } +func (metadataInstallContext) GiteaHosts() []string { return nil } + +// TestInstallFromConfig_ReclonesMissingTrackedRepo verifies that a tracked repo +// declared in metadata but absent on disk is listed as missing and re-cloned +// under its recorded name (issue #212). +func TestInstallFromConfig_ReclonesMissingTrackedRepo(t *testing.T) { remoteURL := makeRemote(t, "") sourceDir := t.TempDir() @@ -69,27 +86,30 @@ func TestRehydrateMissingTrackedRepos_ReclonesAbsent(t *testing.T) { if err := store.Save(sourceDir); err != nil { t.Fatalf("save metadata: %v", err) } - - results, err := RehydrateMissingTrackedRepos(sourceDir, ParseOptions{}, InstallOptions{SkipAudit: true}) - if err != nil { - t.Fatalf("RehydrateMissingTrackedRepos() error = %v", err) + ctx := metadataInstallContext{sourceDir} + if missing := MissingFromConfig(ctx); len(missing) != 1 || !missing[0].Tracked { + t.Fatalf("expected the tracked repo to be missing, got %+v", missing) } - if len(results) != 1 || results[0].Action != "rehydrated" { - t.Fatalf("unexpected results: %+v", results) + + result, err := InstallFromConfig(ctx, InstallOptions{SkipAudit: true, Quiet: true}) + if err != nil { + t.Fatalf("InstallFromConfig() error = %v", err) + } + if result.InstalledRepos != 1 || len(result.FailedSkills) != 0 { + t.Fatalf("unexpected result: %+v", result) } if _, err := os.Stat(filepath.Join(sourceDir, "_team-skills", ".git")); err != nil { t.Fatalf("expected cloned repo at _team-skills: %v", err) } - // After rehydration nothing should remain missing. - if missing, _ := GetMissingTrackedRepos(sourceDir); len(missing) != 0 { - t.Fatalf("expected no missing repos after rehydrate, got %+v", missing) + if missing := MissingFromConfig(ctx); len(missing) != 0 { + t.Fatalf("expected nothing missing after install, got %+v", missing) } } -// TestInstallTrackedRepo_NameFromSource verifies that when opts.Name is empty, -// the directory name is taken from source.Name rather than being derived from -// the remote URL via TrackName(). -func TestInstallTrackedRepo_NameFromSource(t *testing.T) { +// TestInstallTrackedRepo_NameFromOptions verifies that a name passed in +// opts.Name (--name, or the name recorded in config) wins over the +// URL-derived TrackName(). +func TestInstallTrackedRepo_NameFromOptions(t *testing.T) { remoteURL := makeRemote(t, "") sourceDir := t.TempDir() @@ -97,10 +117,9 @@ func TestInstallTrackedRepo_NameFromSource(t *testing.T) { Type: SourceTypeGitHTTPS, Raw: remoteURL, CloneURL: remoteURL, - Name: "my-custom-name", // explicit name; should win over TrackName() } - result, err := InstallTrackedRepo(source, sourceDir, InstallOptions{}) + result, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "my-custom-name"}) if err != nil { t.Fatalf("InstallTrackedRepo() error = %v", err) } @@ -119,6 +138,52 @@ func TestInstallTrackedRepo_NameFromSource(t *testing.T) { } } +// TestInstallTrackedRepo_SameBasenameDoesNotCollide verifies that two repos +// whose URLs end in the same basename get distinct owner-repo directories, +// even though ParseSource fills source.Name with that shared basename. +func TestInstallTrackedRepo_SameBasenameDoesNotCollide(t *testing.T) { + remoteURL := makeRemote(t, "") + sourceDir := t.TempDir() + seen := map[string]bool{} + for _, owner := range []string{"alice", "bob"} { + // Raw names the owner (TrackName reads it); the clone uses the local remote. + source := &Source{ + Type: SourceTypeGitSSH, + Raw: "git@example.com:" + owner + "/skills.git", + CloneURL: remoteURL, + Name: "skills", // what ParseSource fills in from the basename + } + result, err := InstallTrackedRepo(source, sourceDir, InstallOptions{SkipAudit: true}) + if err != nil { + t.Fatalf("install %s: %v", owner, err) + } + if result.RepoName == "_skills" || seen[result.RepoName] { + t.Fatalf("repo %s got colliding name %q", owner, result.RepoName) + } + seen[result.RepoName] = true + } +} + +// TestInstallTrackedRepo_ReusesLegacyBasenameCheckout verifies that repeating +// an install whose repo was cloned under the older basename name (_skills) +// skips as the same repo instead of cloning a second _owner-skills copy. +func TestInstallTrackedRepo_ReusesLegacyBasenameCheckout(t *testing.T) { + remoteURL := makeRemote(t, "") + sourceDir := t.TempDir() + source := &Source{Type: SourceTypeGitSSH, Raw: "git@example.com:alice/skills.git", CloneURL: remoteURL, Name: "skills"} + if _, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "skills", SkipAudit: true}); err != nil { + t.Fatalf("legacy install: %v", err) + } + + _, err := InstallTrackedRepo(source, sourceDir, InstallOptions{SkipAudit: true}) + if !errors.Is(err, ErrSkipSameRepo) { + t.Fatalf("err = %v, want ErrSkipSameRepo", err) + } + if _, err := os.Stat(filepath.Join(sourceDir, "_"+source.TrackName())); err == nil { + t.Fatal("cloned a second copy under the owner-qualified name") + } +} + // TestInstallTrackedRepo_BranchFromSource verifies that when opts.Branch is // empty, the repo is cloned onto source.Branch rather than the remote default. func TestInstallTrackedRepo_BranchFromSource(t *testing.T) { @@ -130,11 +195,10 @@ func TestInstallTrackedRepo_BranchFromSource(t *testing.T) { Type: SourceTypeGitHTTPS, Raw: remoteURL, CloneURL: remoteURL, - Name: "mybranch-skill", Branch: featureBranch, // should be used; opts.Branch is empty } - result, err := InstallTrackedRepo(source, sourceDir, InstallOptions{}) + result, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "mybranch-skill"}) if err != nil { t.Fatalf("InstallTrackedRepo() error = %v", err) } @@ -173,8 +237,7 @@ func TestMissingTrackedReposFollowPolicy(t *testing.T) { if err != nil || len(missing) != 0 { t.Fatalf("present followed checkout reported missing: %+v %v", missing, err) } - results, err := RehydrateMissingTrackedRepos(source, ParseOptions{}, InstallOptions{SourceFollow: walk.Follow}) - if err != nil || len(results) != 0 { - t.Fatalf("present followed checkout rehydrated: %+v %v", results, err) + if got := MissingFromConfig(metadataInstallContext{source}); len(got) != 0 { + t.Fatalf("present followed checkout listed for install: %+v", got) } } diff --git a/cmd/skillshare/install_context_test.go b/internal/install/metadata_entries_test.go similarity index 67% rename from cmd/skillshare/install_context_test.go rename to internal/install/metadata_entries_test.go index 6078295b6..fd1779d66 100644 --- a/cmd/skillshare/install_context_test.go +++ b/internal/install/metadata_entries_test.go @@ -1,20 +1,18 @@ -package main +package install import ( "testing" - - "skillshare/internal/install" ) -func TestStoreToSkillEntryDTOs_FullPathKeyWithGroup(t *testing.T) { - store := install.NewMetadataStore() - store.Set("team/_demo", &install.MetadataEntry{ +func TestMetadataSkillEntries_FullPathKeyWithGroup(t *testing.T) { + store := NewMetadataStore() + store.Set("team/_demo", &MetadataEntry{ Source: "file:///tmp/demo", Tracked: true, Group: "team", }) - dtos := storeToSkillEntryDTOs(store) + dtos := MetadataSkillEntries(store) if len(dtos) != 1 { t.Fatalf("expected 1 dto, got %d", len(dtos)) } @@ -31,15 +29,15 @@ func TestStoreToSkillEntryDTOs_FullPathKeyWithGroup(t *testing.T) { } } -func TestStoreToSkillEntryDTOs_LegacyBasenameKeyWithGroup(t *testing.T) { - store := install.NewMetadataStore() - store.Set("_demo", &install.MetadataEntry{ +func TestMetadataSkillEntries_LegacyBasenameKeyWithGroup(t *testing.T) { + store := NewMetadataStore() + store.Set("_demo", &MetadataEntry{ Source: "file:///tmp/demo", Tracked: true, Group: "team", }) - dtos := storeToSkillEntryDTOs(store) + dtos := MetadataSkillEntries(store) if len(dtos) != 1 { t.Fatalf("expected 1 dto, got %d", len(dtos)) } diff --git a/internal/install/source.go b/internal/install/source.go index 6c61ca431..309dd2393 100644 --- a/internal/install/source.go +++ b/internal/install/source.go @@ -970,6 +970,10 @@ func (s *Source) TrackName() string { // Try extracting full path from HTTPS clone URL cloneURL = strings.TrimSuffix(cloneURL, ".git") if u, err := url.Parse(cloneURL); err == nil { + // A local file:// remote has no owner; its full path is not a name. + if u.Scheme == "file" { + return s.Name + } pathStr := strings.Trim(u.Path, "/") if pathStr != "" { return strings.ReplaceAll(pathStr, "/", "-") diff --git a/internal/install/source_test.go b/internal/install/source_test.go index 59747865b..a9c1a13af 100644 --- a/internal/install/source_test.go +++ b/internal/install/source_test.go @@ -777,6 +777,11 @@ func TestSource_TrackName(t *testing.T) { raw: "onprem.gitlab.internal/org/sub1/sub2/project", want: "org-sub1-sub2-project", }, + { + name: "file URL keeps basename", + raw: "file:///tmp/remotes/team-repo", + want: "team-repo", + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/server/handler_check.go b/internal/server/handler_check.go index ae706c30a..3e79f8bb4 100644 --- a/internal/server/handler_check.go +++ b/internal/server/handler_check.go @@ -43,8 +43,7 @@ func (s *Server) planSkillCheck(sourceDir, projectRoot string, walk sourcewalk.O // dashboardSkillResults converts resolved statuses to the dashboard payload, // which is narrower than the CLI's: a skill without a remote carries only its -// name, status and message, and a skill removed upstream is reported as -// update_available because the dashboard has no "stale" state. +// name, status and message. func dashboardSkillResults(results []check.SkillResult) []skillCheckResult { out := make([]skillCheckResult, 0, len(results)) for _, r := range results { @@ -52,15 +51,11 @@ func dashboardSkillResults(results []check.SkillResult) []skillCheckResult { out = append(out, skillCheckResult{Name: r.Name, Status: r.Status, Message: r.Message}) continue } - status := r.Status - if status == "stale" { - status = "update_available" - } out = append(out, skillCheckResult{ Name: r.Name, Source: r.Source, Version: r.Version, - Status: status, + Status: r.Status, InstalledAt: r.InstalledAt, }) } diff --git a/internal/server/handler_check_resolution_test.go b/internal/server/handler_check_resolution_test.go index 47bc773a7..0456f906c 100644 --- a/internal/server/handler_check_resolution_test.go +++ b/internal/server/handler_check_resolution_test.go @@ -41,14 +41,13 @@ func decodeCheckPayload(t *testing.T, raw string) checkPayload { } // wantDashboardSkills is what the dashboard reports for checktest.Seed. Unlike -// the CLI it reports a skill removed upstream as update_available, and gives -// only name, status and message for a skill without a remote. +// the CLI it gives only name, status and message for a skill without a remote. func wantDashboardSkills(versions map[string]string) []skillCheckResult { statuses := map[string]string{ "broken": "error", "changed": "update_available", "current": "up_to_date", - "doomed": "update_available", + "doomed": "stale", "notree": "update_available", "same": "up_to_date", "slash": "up_to_date", diff --git a/internal/server/handler_install_config.go b/internal/server/handler_install_config.go new file mode 100644 index 000000000..063f45978 --- /dev/null +++ b/internal/server/handler_install_config.go @@ -0,0 +1,128 @@ +package server + +import ( + "net/http" + "time" + + "skillshare/internal/config" + "skillshare/internal/install" + "skillshare/internal/projectdir" +) + +// serverInstallContext runs the CLI's bare `skillshare install` (install +// everything recorded in config that is not on disk) for the dashboard. +type serverInstallContext struct{ s *Server } + +var _ install.InstallContext = serverInstallContext{} + +// SourcePath is the project's skills folder in project mode, else the global one. +func (c serverInstallContext) SourcePath() string { return c.s.skillsSource() } + +func (c serverInstallContext) ConfigSkills() []install.SkillEntryDTO { + if !c.s.IsProjectMode() { + return install.MetadataSkillEntries(install.LoadMetadataOrNew(c.SourcePath())) + } + return config.ProjectSkillEntries(c.s.projectCfg.Skills) +} + +func (c serverInstallContext) Reconcile() error { + // Reload from the same folder the install wrote to; reloadSkillsStore reads the global one. + if st, err := install.LoadMetadataWithMigration(c.SourcePath(), ""); err == nil && st != nil { + c.s.skillsStore = st + } + c.s.reconcileSkillsConfig(c.SourcePath()) + return nil +} + +func (c serverInstallContext) PostInstallSkill(displayName string) error { + if !c.s.IsProjectMode() { + return nil + } + dir := c.s.gitignoreDir() + if dir == "" { + return nil + } + return install.UpdateGitIgnore(dir, c.s.projectGitignorePrefix()+"/"+displayName) +} + +func (c serverInstallContext) Mode() string { return c.s.installLogMode() } +func (c serverInstallContext) GitLabHosts() []string { return c.s.parseOpts().GitLabHosts } +func (c serverInstallContext) AzureHosts() []string { return c.s.parseOpts().AzureHosts } +func (c serverInstallContext) CNBHosts() []string { return c.s.parseOpts().CNBHosts } +func (c serverInstallContext) GiteaHosts() []string { return c.s.parseOpts().GiteaHosts } + +type configEntryInfo struct { + Name string `json:"name"` + Source string `json:"source"` + Tracked bool `json:"tracked"` + Branch string `json:"branch,omitempty"` +} + +// handleMissingConfigEntries lists config entries that are not on disk, so the +// dashboard can offer to install them (bare `skillshare install`). +func (s *Server) handleMissingConfigEntries(w http.ResponseWriter, r *http.Request) { + s.mu.RLock() + missing := install.MissingFromConfig(serverInstallContext{s}) + s.mu.RUnlock() + entries := make([]configEntryInfo, 0, len(missing)) + for _, m := range missing { + entries = append(entries, configEntryInfo{Name: m.FullName(), Source: m.Source, Tracked: m.Tracked, Branch: m.Branch}) + } + file := ".metadata.json" + if s.IsProjectMode() { + file = ".skillshare/config.yaml" + } + writeJSON(w, map[string]any{"entries": entries, "file": file}) +} + +// handleInstallFromConfig installs every config entry missing on disk, like +// bare `skillshare install`. +func (s *Server) handleInstallFromConfig(w http.ResponseWriter, r *http.Request) { + start := time.Now() + s.mu.Lock() + defer s.mu.Unlock() + defer s.trackProjectLock()() + + opts := install.InstallOptions{ + Quiet: true, + AuditThreshold: s.auditThreshold(), + SourceFollow: s.skillsWalk().Follow, + } + if s.IsProjectMode() { + opts.AuditProjectRoot = s.projectRoot + lock, err := install.LoadLock(projectdir.Resolve(s.projectRoot)) + if err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + opts.Lock = lock + } + + result, err := install.InstallFromConfig(serverInstallContext{s}, opts) + status, msg := "ok", "" + if err != nil { + status, msg = "error", err.Error() + } else if len(result.FailedSkills) > 0 { + status = "partial" + } + s.writeOpsLog("install", status, start, map[string]any{ + "source": "config", + "mode": s.installLogMode(), + "threshold": s.auditThreshold(), + "scope": "ui", + "installed_skills": result.InstalledSkills, + "failed_skills": result.FailedSkills, + }, msg) + if err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + + writeJSON(w, map[string]any{ + "installed": result.Installed, + "installedRepos": result.InstalledRepos, + "installedRepoSkills": result.InstalledRepoSkills, + "skipped": result.Skipped, + "failed": result.FailedSkills, + }) +} diff --git a/internal/server/handler_install_config_test.go b/internal/server/handler_install_config_test.go new file mode 100644 index 000000000..cc9e25984 --- /dev/null +++ b/internal/server/handler_install_config_test.go @@ -0,0 +1,65 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "skillshare/internal/config" + "skillshare/internal/install" +) + +func TestHandleMissingConfigEntries_ListsAbsentEntries(t *testing.T) { + s, src := newTestServer(t) + store := install.LoadMetadataOrNew(src) + store.Set("_team-skills", &install.MetadataEntry{Source: "https://github.com/team/skills.git", Tracked: true, Branch: "main"}) + if err := store.Save(src); err != nil { + t.Fatalf("save metadata: %v", err) + } + + rr := httptest.NewRecorder() + s.handleMissingConfigEntries(rr, httptest.NewRequest(http.MethodGet, "/api/install/missing", nil)) + var resp struct { + Entries []configEntryInfo `json:"entries"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + want := configEntryInfo{Name: "_team-skills", Source: "https://github.com/team/skills.git", Tracked: true, Branch: "main"} + if len(resp.Entries) != 1 || resp.Entries[0] != want { + t.Fatalf("entries = %+v, want [%+v]", resp.Entries, want) + } +} + +func TestHandleInstallFromConfig_NothingMissing(t *testing.T) { + s, _ := newTestServer(t) + rr := httptest.NewRecorder() + s.handleInstallFromConfig(rr, httptest.NewRequest(http.MethodPost, "/api/install/from-config", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String()) + } +} + +func TestHandleMissingConfigEntries_ProjectModeChecksProjectSource(t *testing.T) { + s, root := newTestProjectServerWithExtras(t, nil) + s.projectCfg.Skills = []config.SkillEntry{{Name: "present", Source: "github.com/team/skills/present"}, {Name: "absent", Source: "github.com/team/skills/absent"}} + // Only the project source has "present"; the global source has neither. + if err := os.MkdirAll(filepath.Join(s.projectCfg.EffectiveSkillsSource(root), "present"), 0o755); err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + s.handleMissingConfigEntries(rr, httptest.NewRequest(http.MethodGet, "/api/install/missing", nil)) + var resp struct { + Entries []configEntryInfo `json:"entries"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if len(resp.Entries) != 1 || resp.Entries[0].Name != "absent" { + t.Fatalf("entries = %+v, want only absent", resp.Entries) + } +} diff --git a/internal/server/handler_update.go b/internal/server/handler_update.go index 9e0cb5cca..b19c8cca9 100644 --- a/internal/server/handler_update.go +++ b/internal/server/handler_update.go @@ -27,28 +27,6 @@ type updateRequest struct { SkipAudit bool `json:"skipAudit"` } -// missingTrackedRepoInfo describes a tracked repo declared in metadata whose -// clone directory is absent on disk. Carried in update responses so the UI can -// warn and offer rehydration (issue #212). -type missingTrackedRepoInfo struct { - Name string `json:"name"` - Source string `json:"source"` - Branch string `json:"branch,omitempty"` -} - -// missingTrackedRepos returns tracked repos declared in metadata but absent on disk. -func (s *Server) missingTrackedRepos() []missingTrackedRepoInfo { - repos, err := install.GetMissingTrackedRepos(s.cfg.EffectiveSkillsSource(), s.skillsWalk()) - if err != nil || len(repos) == 0 { - return nil - } - out := make([]missingTrackedRepoInfo, 0, len(repos)) - for _, r := range repos { - out = append(out, missingTrackedRepoInfo{Name: r.Name, Source: r.Source, Branch: r.Branch}) - } - return out -} - type updateResultItem struct { Name string `json:"name"` Action string `json:"action"` // "updated", "up-to-date", "skipped", "error", "blocked" @@ -123,7 +101,7 @@ func (s *Server) handleUpdate(w http.ResponseWriter, r *http.Request) { "results_blocked": blocked, "scope": "ui", }, msg) - writeJSON(w, map[string]any{"results": results, "missingTrackedRepos": s.missingTrackedRepos()}) + writeJSON(w, map[string]any{"results": results}) return } @@ -474,70 +452,6 @@ func (s *Server) updateAll(force, skipAudit bool) []updateResultItem { return results } -// handleMissingTrackedRepos returns tracked repos declared in metadata whose -// clone directories are absent on disk (issue #212), so the UI can warn on load. -func (s *Server) handleMissingTrackedRepos(w http.ResponseWriter, r *http.Request) { - s.mu.RLock() - repos := s.missingTrackedRepos() - s.mu.RUnlock() - if repos == nil { - repos = []missingTrackedRepoInfo{} - } - writeJSON(w, map[string]any{"repos": repos}) -} - -// handleRehydrateTrackedRepos re-clones tracked repos declared in metadata whose -// clone directories are absent on disk (issue #212). Mirrors bare CLI install. -func (s *Server) handleRehydrateTrackedRepos(w http.ResponseWriter, r *http.Request) { - start := time.Now() - s.mu.Lock() - defer s.mu.Unlock() - - sourceDir := s.cfg.EffectiveSkillsSource() - opts := install.InstallOptions{ - AuditThreshold: s.updateAuditThreshold(), - SourceDir: sourceDir, - SourceFollow: s.skillsWalk().Follow, - } - if s.IsProjectMode() { - opts.AuditProjectRoot = s.projectRoot - } - - results, err := install.RehydrateMissingTrackedRepos(sourceDir, s.parseOpts(), opts) - if err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) - return - } - - // Reload metadata + reconcile config so newly cloned repos register. - if st, lerr := install.LoadMetadataWithMigration(sourceDir, ""); lerr == nil && st != nil { - s.skillsStore = st - } - s.reconcileSkillsConfig(sourceDir) - - rehydrated, failed := 0, 0 - for _, res := range results { - if res.Action == "rehydrated" { - rehydrated++ - } else { - failed++ - } - } - status, msg := "ok", "" - if failed > 0 { - status = "partial" - msg = fmt.Sprintf("%d repo(s) failed to rehydrate", failed) - } - s.writeOpsLog("install", status, start, map[string]any{ - "name": "--rehydrate", - "tracked": true, - "scope": "ui", - "rehydrated": rehydrated, - "failed": failed, - }, msg) - writeJSON(w, map[string]any{"results": results}) -} - // getServerUpdatableSkills returns relative paths of skills that have metadata with a remote source. // It walks the source directory recursively to find nested skills (e.g. utils/ascii-box-check). func getServerUpdatableSkills(sourceDir string, store *install.MetadataStore, walk sourcewalk.Options) ([]string, error) { diff --git a/internal/server/handler_update_follow_test.go b/internal/server/handler_update_follow_test.go index 0d65dbc5b..0e69effd8 100644 --- a/internal/server/handler_update_follow_test.go +++ b/internal/server/handler_update_follow_test.go @@ -205,7 +205,7 @@ func assertUpdateFollowLink(t *testing.T, link string) { } } -func TestHandleRehydrate_FollowedCheckoutWithMetadata(t *testing.T) { +func TestHandleInstallFromConfig_FollowedCheckoutWithMetadata(t *testing.T) { for _, project := range []bool{false, true} { t.Run(fmt.Sprintf("project=%t", project), func(t *testing.T) { s, source := newUpdateFollowServer(t, project, true) @@ -220,19 +220,19 @@ func TestHandleRehydrate_FollowedCheckoutWithMetadata(t *testing.T) { if err := store.Save(source); err != nil { t.Fatal(err) } - if repos := s.missingTrackedRepos(); len(repos) != 0 { + if repos, _ := install.GetMissingTrackedRepos(source, s.skillsWalk()); len(repos) != 0 { t.Fatalf("followed checkout reported missing: %+v", repos) } rr := httptest.NewRecorder() - s.handleRehydrateTrackedRepos(rr, httptest.NewRequest(http.MethodPost, "/api/update/rehydrate", nil)) + s.handleInstallFromConfig(rr, httptest.NewRequest(http.MethodPost, "/api/install/from-config", nil)) var resp struct { - Results []install.RehydrateResult `json:"results"` + Installed int `json:"installed"` } if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { t.Fatal(err) } - if rr.Code != http.StatusOK || len(resp.Results) != 0 { - t.Fatalf("followed checkout rehydrated: %d %s", rr.Code, rr.Body.String()) + if rr.Code != http.StatusOK || resp.Installed != 0 { + t.Fatalf("followed checkout reinstalled: %d %s", rr.Code, rr.Body.String()) } assertUpdateFollowLink(t, link) }) diff --git a/internal/server/handler_update_stream.go b/internal/server/handler_update_stream.go index 1ab5fde81..2b7cd1986 100644 --- a/internal/server/handler_update_stream.go +++ b/internal/server/handler_update_stream.go @@ -98,12 +98,11 @@ func (s *Server) handleUpdateStream(w http.ResponseWriter, r *http.Request) { var results []updateResultItem summary := struct { - Updated int `json:"updated"` - UpToDate int `json:"upToDate"` - Blocked int `json:"blocked"` - Errors int `json:"errors"` - Skipped int `json:"skipped"` - MissingTrackedRepos []missingTrackedRepoInfo `json:"missingTrackedRepos,omitempty"` + Updated int `json:"updated"` + UpToDate int `json:"upToDate"` + Blocked int `json:"blocked"` + Errors int `json:"errors"` + Skipped int `json:"skipped"` }{} for _, item := range items { @@ -148,12 +147,6 @@ func (s *Server) handleUpdateStream(w http.ResponseWriter, r *http.Request) { // Surface tracked repos declared in metadata but absent on disk (issue #212). // Only relevant for the update-all flow, not targeted updates. - if namesParam == "" { - s.mu.RLock() - summary.MissingTrackedRepos = s.missingTrackedRepos() - s.mu.RUnlock() - } - // Write ops log s.mu.Lock() status := "ok" diff --git a/internal/server/handler_update_test.go b/internal/server/handler_update_test.go index 59d1f2e26..076c43262 100644 --- a/internal/server/handler_update_test.go +++ b/internal/server/handler_update_test.go @@ -1,8 +1,6 @@ package server import ( - "net/http" - "net/http/httptest" "os" "os/exec" "path/filepath" @@ -41,47 +39,6 @@ func initGitRepo(t *testing.T, dir string) { } } -// TestMissingTrackedRepos_ReportedFromMetadata verifies the server detects tracked -// repos declared in metadata whose clone dirs are absent (issue #212). -func TestMissingTrackedRepos_ReportedFromMetadata(t *testing.T) { - s, src := newTestServer(t) - - store := install.LoadMetadataOrNew(src) - store.Set("_team-skills", &install.MetadataEntry{ - Source: "https://github.com/example/team-skills", - Branch: "main", - Tracked: true, - }) - if err := store.Save(src); err != nil { - t.Fatalf("save metadata: %v", err) - } - - missing := s.missingTrackedRepos() - if len(missing) != 1 { - t.Fatalf("expected 1 missing repo, got %d (%+v)", len(missing), missing) - } - if missing[0].Name != "_team-skills" || missing[0].Branch != "main" { - t.Fatalf("unexpected missing repo: %+v", missing[0]) - } -} - -// TestHandleRehydrate_NoMissing_OK verifies the rehydrate endpoint succeeds with -// an empty result set when nothing is missing. -func TestHandleRehydrate_NoMissing_OK(t *testing.T) { - s, _ := newTestServer(t) - - req := httptest.NewRequest(http.MethodPost, "/api/update/rehydrate", nil) - rr := httptest.NewRecorder() - s.handleRehydrateTrackedRepos(rr, req) - - if rr.Code != http.StatusOK { - t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String()) - } - if !strings.Contains(rr.Body.String(), "results") { - t.Fatalf("expected results field, got %s", rr.Body.String()) - } -} - func TestUpdateSingle_NestedTrackedRepo_Resolves(t *testing.T) { s, src := newTestServer(t) diff --git a/internal/server/server.go b/internal/server/server.go index 5230d45b9..27d0cd57a 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -563,6 +563,8 @@ func (s *Server) registerRoutes() { s.mux.HandleFunc("POST /api/discover", s.handleDiscover) s.mux.HandleFunc("POST /api/install", s.handleInstall) s.mux.HandleFunc("POST /api/install/batch", s.handleInstallBatch) + s.mux.HandleFunc("GET /api/install/missing", s.handleMissingConfigEntries) + s.mux.HandleFunc("POST /api/install/from-config", s.handleInstallFromConfig) s.mux.HandleFunc("POST /api/uninstall/batch", s.handleBatchUninstall) s.mux.HandleFunc("POST /api/source-links", s.handleCreateSourceLink) s.mux.HandleFunc("DELETE /api/source-links/{name}", s.handleRemoveSourceLink) @@ -570,8 +572,6 @@ func (s *Server) registerRoutes() { // Update & Check s.mux.HandleFunc("POST /api/update", s.handleUpdate) s.mux.HandleFunc("GET /api/update/stream", s.handleUpdateStream) - s.mux.HandleFunc("GET /api/update/missing-tracked-repos", s.handleMissingTrackedRepos) - s.mux.HandleFunc("POST /api/update/rehydrate", s.handleRehydrateTrackedRepos) s.mux.HandleFunc("GET /api/check/stream", s.handleCheckStream) s.mux.HandleFunc("GET /api/check", s.handleCheck) diff --git a/ui/src/api/install.ts b/ui/src/api/install.ts index 77811e77f..b8950c3ff 100644 --- a/ui/src/api/install.ts +++ b/ui/src/api/install.ts @@ -1,5 +1,5 @@ import { apiFetch, BASE, createSSEStream } from './http'; -import type { BatchInstallResult, CheckResult, DiscoverResult, DiscoveredSkill, HubConfigResponse, HubIndex, HubSavedEntry, InstallResult, SearchResult, SkillPreview } from './types/install'; +import type { BatchInstallResult, CheckResult, ConfigEntry, DiscoverResult, DiscoveredSkill, HubConfigResponse, HubIndex, HubSavedEntry, InstallFromConfigResult, InstallResult, SearchResult, SkillPreview } from './types/install'; export const installApi = { hubIndex: () => apiFetch('/hub/index'), @@ -48,6 +48,9 @@ export const installApi = { method: 'POST', body: JSON.stringify(opts), }), + // Entries recorded in config but not on disk (bare `skillshare install`) + missingConfigEntries: () => apiFetch<{ entries: ConfigEntry[]; file: string }>('/install/missing'), + installFromConfig: () => apiFetch('/install/from-config', { method: 'POST' }), installBatch: (opts: { source: string; skills: DiscoveredSkill[]; force?: boolean; skipAudit?: boolean; into?: string; name?: string; branch?: string; kind?: 'skill' | 'agent' }) => apiFetch('/install/batch', { method: 'POST', diff --git a/ui/src/api/types/install.ts b/ui/src/api/types/install.ts index bb24ea1dd..d7f30ec46 100644 --- a/ui/src/api/types/install.ts +++ b/ui/src/api/types/install.ts @@ -92,6 +92,21 @@ export interface SkillCheckResult { message?: string; } +export interface ConfigEntry { + name: string; + source: string; + tracked: boolean; + branch?: string; +} + +export interface InstallFromConfigResult { + installed: number; + installedRepos: number; + installedRepoSkills: number; + skipped: number; + failed: string[]; +} + export interface CheckResult { linked_repos?: LinkedRepo[]; tracked_repos: RepoCheckResult[]; diff --git a/ui/src/api/types/update.ts b/ui/src/api/types/update.ts index 7880f26fa..f46b23c78 100644 --- a/ui/src/api/types/update.ts +++ b/ui/src/api/types/update.ts @@ -8,23 +8,11 @@ export interface UpdateResultItem { auditRiskLabel?: string; } -export interface MissingTrackedRepo { - name: string; - source: string; - branch?: string; -} - export interface UpdateStreamSummary { updated: number; upToDate: number; blocked: number; errors: number; skipped: number; - missingTrackedRepos?: MissingTrackedRepo[]; } -export interface RehydrateResultItem { - name: string; - action: string; // "rehydrated" | "error" - error?: string; -} diff --git a/ui/src/api/update.ts b/ui/src/api/update.ts index 24f1ba74c..1709e47c9 100644 --- a/ui/src/api/update.ts +++ b/ui/src/api/update.ts @@ -1,9 +1,9 @@ import { apiFetch, BASE, createSSEStream } from './http'; -import type { MissingTrackedRepo, RehydrateResultItem, UpdateResultItem, UpdateStreamSummary } from './types/update'; +import type { UpdateResultItem, UpdateStreamSummary } from './types/update'; export const updateApi = { update: (opts: { name?: string; kind?: 'skill' | 'agent'; force?: boolean; all?: boolean; skipAudit?: boolean }) => - apiFetch<{ results: UpdateResultItem[]; missingTrackedRepos?: MissingTrackedRepo[] }>('/update', { + apiFetch<{ results: UpdateResultItem[] }>('/update', { method: 'POST', body: JSON.stringify(opts), }), @@ -24,12 +24,4 @@ export const updateApi = { done: onDone, }, onError, 'Update stream failed'); }, - // Tracked repos declared in metadata but absent on disk (issue #212) - missingTrackedRepos: () => - apiFetch<{ repos: MissingTrackedRepo[] }>('/update/missing-tracked-repos'), - // Rehydrate tracked repos declared in metadata but absent on disk (issue #212) - rehydrateTrackedRepos: () => - apiFetch<{ results: RehydrateResultItem[] }>('/update/rehydrate', { - method: 'POST', - }), }; diff --git a/ui/src/components.css b/ui/src/components.css index 925f4350f..49dd2b97e 100644 --- a/ui/src/components.css +++ b/ui/src/components.css @@ -233,6 +233,15 @@ svg.lucide { flex: none; stroke-width: var(--isw); } .ss-gh { display: flex; align-items: center; gap: 10px; min-height: 40px; padding: 6px 16px; background: var(--sunken); border-top: var(--sep); font-size: 13px; } .ss-gh:first-child { border-top: 0; } .ss-plain .ss-r { padding-left: 0; padding-right: 0; min-height: 44px; } +/* A toolbar that sticks to the top while its list scrolls; .stick lists keep their header and group heads under it */ +.ss-stickbar { position: sticky; top: 0; z-index: 20; margin: 0 -12px; padding: 12px; background: var(--bg); } +.ss-stickbar.stuck { box-shadow: 0 1px 0 var(--line); } +.ss-btnpair { display: inline-flex; } +.ss-btnpair>.ss-btn:first-child:not(:last-child) { border-top-right-radius: 0; border-bottom-right-radius: 0; padding-right: 12px; } +.ss-btnpair>.ss-btn:last-child:not(:first-child) { border-top-left-radius: 0; border-bottom-left-radius: 0; padding: 0 9px; border-left: 1px solid color-mix(in srgb, var(--on-pri) 22%, transparent); } +.ss-list.stick { overflow: clip; } +.ss-list.stick>.ss-lh { position: sticky; top: var(--stick, 0px); z-index: 3; } +.ss-list.stick>.ss-gh { position: sticky; top: calc(var(--stick, 0px) + 34px); z-index: 2; } /* Update progress: a bar on the status card, a moving line under the row being updated, and a pop when a row finishes */ .ss-update-icon { width: 40px; height: 40px; flex-shrink: 0; display: grid; place-items: center; border-radius: 11px; background: var(--sunken); color: var(--ink); } .ss-update-icon.ok { background: var(--ok-bg); color: var(--ok); } @@ -249,9 +258,20 @@ svg.lucide { flex: none; stroke-width: var(--isw); } @keyframes ss-indet { from { transform: translateX(-100%); } to { transform: translateX(300%); } } @keyframes ss-flash { from { background: var(--ok-bg); } to { background: transparent; } } @keyframes ss-pop { from { transform: scale(.3); opacity: 0; } to { transform: scale(1); opacity: 1; } } +/* Collapse a block to nothing: wrap it in .ss-collapse and add .shut */ +.ss-collapse { display: grid; grid-template-rows: 1fr; transition: grid-template-rows .45s cubic-bezier(.3,.7,.3,1), opacity .3s; } +.ss-collapse>* { overflow: hidden; min-height: 0; } +.ss-collapse.shut { grid-template-rows: 0fr; opacity: 0; } +/* A removed row slides out, then its .ss-collapse wrapper closes the gap */ +.ss-collapse.out { grid-template-rows: 0fr; transition-delay: .2s; } +.ss-collapse.out .ss-r { transform: translateX(-32px); opacity: 0; } +.ss-collapse .ss-r { transition: transform .26s cubic-bezier(.5,0,.75,0), opacity .22s, background .3s; } +.ss-note.ok { background: var(--ok-bg); border-color: transparent; } +.ss-note.ok>svg { color: var(--ok); } +.ss-note.live { position: relative; overflow: hidden; transition: background .45s; } @media (prefers-reduced-motion: reduce) { .ss-bar.indet>span, .ss-rowbar::after, .ss-r.flash, .ss-pop { animation: none; } - .ss-bar>span { transition: none; } + .ss-bar>span, .ss-collapse, .ss-collapse .ss-r, .ss-note.live { transition: none; } } .ss-note { display: flex; align-items: flex-start; gap: 10px; padding: 11px 14px; border-radius: 10px; background: var(--sunken); border: 1px solid var(--line); font-size: 13px; line-height: 1.5; } :root[data-theme="playful"] .ss-note { border: 2px solid var(--line); border-radius: 12px; } @@ -462,6 +482,8 @@ span.bad, b.bad, svg.bad { color: var(--bad); } :root[data-theme="playful"] .ss-gh { background: var(--pe); border-top: 2px solid var(--line); border-bottom: 1.5px dashed var(--line); } :root[data-theme="playful"] .ss-gh:first-child { border-top: 0; } :root[data-theme="playful"] .ss-lh+.ss-gh { border-top: 0; } +:root[data-theme="playful"] .ss-list.stick>.ss-lh { background: var(--surface); } +:root[data-theme="playful"] .ss-list.stick>.ss-gh { top: calc(var(--stick, 0px) + 36px); } :root[data-theme="playful"] .ss-gh+.ss-r { border-top: 0; } :root[data-theme="playful"] .ss-tabs { border-bottom: 0; gap: 8px; } :root[data-theme="playful"] .ss-tabs>* { margin: 0; padding: 0 14px; height: 34px; border: 2px solid transparent; border-radius: 999px; } diff --git a/ui/src/components/ConfigInstallPanel.tsx b/ui/src/components/ConfigInstallPanel.tsx new file mode 100644 index 000000000..c7e391d96 --- /dev/null +++ b/ui/src/components/ConfigInstallPanel.tsx @@ -0,0 +1,81 @@ +import type { CSSProperties, ReactNode } from 'react'; +import { Check, CircleAlert, Download, FolderDown, GitBranch, Loader2, Puzzle, X } from 'lucide-react'; +import Button from './Button'; +import { parseRemoteURL } from '../lib/parseRemoteURL'; +import { plural, useT } from '../i18n'; +import { useInstallFromConfig } from '../hooks/useInstallFromConfig'; + +/** Rows finish one after another, so results read top to bottom. */ +const stagger = (i: number): CSSProperties => ({ animationDelay: `${i * 90}ms`, animationFillMode: 'both' }); + +/** Install dialog section: what config records but the disk lacks, installed in one go. */ +export default function ConfigInstallPanel() { + const t = useT(); + const { entries, file, phase, done, failed, summary, contents, error, run, dismiss } = useInstallFromConfig(); + if (entries.length === 0) return null; + + let icon = ; + let tone = ''; + let title = t(plural('install.fromConfig.title', entries.length), { count: entries.length, file }); + let sub = t('install.fromConfig.hint', { items: contents }); + let action: ReactNode = ; + if (phase === 'running') { + icon = ; + title = t('install.fromConfig.installing', { file }); + sub = t('install.audited'); + action = null; + } else if (done) { + icon = failed.size ? : ; + tone = failed.size ? 'warn' : 'ok'; + title = summary; + sub = t(failed.size ? 'install.fromConfig.failedHint' : 'install.fromConfig.syncHint', { file }); + action = failed.size + ? + : ; + } else if (error) { + tone = 'bad'; + icon = ; + sub = error; + } + + return ( +
+
+
+ {icon} +
+ {title} + {sub} +
+ {action} +
+ {phase === 'running' &&
} +
+
+ {entries.map((e, i) => { + const bad = done && failed.has(e.name); + const row = phase === 'running' ? 'updating' : done && !bad ? 'flash' : ''; + return ( +
+ {e.tracked + ? + : } + {e.name} + {e.tracked && tracked} + {parseRemoteURL(e.source)?.ownerRepo ?? e.source} + + {phase === 'running' && } + {done && (bad + ? + : )} + + {phase === 'running' && } +
+ ); + })} +
+
+
+
+ ); +} diff --git a/ui/src/components/InstallDialog.tsx b/ui/src/components/InstallDialog.tsx index 2c20a5e4b..a46367855 100644 --- a/ui/src/components/InstallDialog.tsx +++ b/ui/src/components/InstallDialog.tsx @@ -33,6 +33,7 @@ import { queryKeys, staleTimes } from '../lib/queryKeys'; import { formatSkillDisplayName } from '../lib/resourceNames'; import { useI18n, useT } from '../i18n'; import Button from './Button'; +import ConfigInstallPanel from './ConfigInstallPanel'; import { Checkbox } from './Checkbox'; import DialogShell from './DialogShell'; import EmptyState from './EmptyState'; @@ -58,6 +59,7 @@ const COMMUNITY_HUB: HubSavedEntry = { builtIn: true, }; const STEP = 10; +/** Past this many found items, a filter box shows. */ const FOUND_PREVIEW = 5; /** Backend error code for a mixed-track-repo ambiguity (see internal/server/handler_install.go). */ const TRACK_KIND_AMBIGUOUS = 'install.track_kind_ambiguous'; @@ -136,7 +138,6 @@ export default function InstallDialog({ kind, initialTab, initialSource, onClose const [wanted, setWanted] = useState(null); const [selected, setSelected] = useState>(new Set()); const [filter, setFilter] = useState(''); - const [expanded, setExpanded] = useState(false); const [kindChoice, setKindChoice] = useState(null); const [kindPick, setKindPick] = useState(kind); @@ -297,7 +298,6 @@ export default function InstallDialog({ kind, initialTab, initialSource, onClose const preselected = requestedSkills(wanted, from, items) ?? items.filter((i) => !isInstalled(i.kind ?? 'skill', discoveredSource(from, i.path))); setSelected(new Set(preselected.map((i) => i.path))); setFilter(''); - setExpanded(false); setTab('url'); setView(null); }; @@ -630,6 +630,7 @@ export default function InstallDialog({ kind, initialTab, initialSource, onClose } body = ( <> + {!isAgent && } {tabs}