Merge pull request #483 from runkids/runkids/install-from-config

feat: install config entries from the dashboard, prune deleted skills, calmer Sync and Skills pages
This commit is contained in:
Willie
2026-10-08 13:27:07 +08:00
committed by GitHub
70 changed files with 1931 additions and 638 deletions
+2 -2
View File
@@ -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"},
+2 -46
View File
@@ -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)
+32 -8
View File
@@ -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 {
+1 -1
View File
@@ -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
@@ -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)
}
})
}
}
+10
View File
@@ -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
}
+9 -4
View File
@@ -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
}
-6
View File
@@ -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)
}
+49 -4
View File
@@ -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.
-64
View File
@@ -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) {
+12 -3
View File
@@ -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 _<basename>; 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 _)
+86 -23
View File
@@ -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)
}
}
@@ -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))
}
+4
View File
@@ -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, "/", "-")
+5
View File
@@ -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) {
+2 -7
View File
@@ -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,
})
}
@@ -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",
+128
View File
@@ -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,
})
}
@@ -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)
}
}
+1 -87
View File
@@ -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) {
@@ -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)
})
+5 -12
View File
@@ -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"
-43
View File
@@ -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)
+2 -2
View File
@@ -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)
+4 -1
View File
@@ -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<HubIndex>('/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<InstallFromConfigResult>('/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<BatchInstallResult>('/install/batch', {
method: 'POST',
+15
View File
@@ -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[];
-12
View File
@@ -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;
}
+2 -10
View File
@@ -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',
}),
};
+23 -1
View File
@@ -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; }
+81
View File
@@ -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 = <FolderDown size={16} />;
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 = <Button variant="primary" size="sm" onClick={run}><Download size={14} />{t('install.fromConfig.installAll')}</Button>;
if (phase === 'running') {
icon = <Loader2 size={16} className="animate-spin" />;
title = t('install.fromConfig.installing', { file });
sub = t('install.audited');
action = null;
} else if (done) {
icon = failed.size ? <CircleAlert size={16} className="ss-pop" /> : <Check size={16} strokeWidth={2.6} className="ss-pop" />;
tone = failed.size ? 'warn' : 'ok';
title = summary;
sub = t(failed.size ? 'install.fromConfig.failedHint' : 'install.fromConfig.syncHint', { file });
action = failed.size
? <Button variant="secondary" size="sm" onClick={run}>{t('install.preview.retry')}</Button>
: <Button variant="secondary" size="sm" onClick={dismiss}>{t('install.done')}</Button>;
} else if (error) {
tone = 'bad';
icon = <CircleAlert size={16} />;
sub = error;
}
return (
<div className={`ss-collapse ${phase === 'closing' ? 'shut' : ''}`}>
<section className="flex flex-col gap-2" aria-live="polite">
<div className={`ss-note live items-center ${tone}`}>
{icon}
<div key={phase} className="flex flex-1 min-w-0 flex-col gap-0.5 animate-fade-in">
<b>{title}</b>
<span className="text-ink-2">{sub}</span>
</div>
{action}
</div>
{phase === 'running' && <div className="ss-bar indet animate-fade-in" role="progressbar" aria-label={title}><span /></div>}
<div className="ss-list !shadow-none">
<div className="max-h-[164px] overflow-y-auto">
{entries.map((e, i) => {
const bad = done && failed.has(e.name);
const row = phase === 'running' ? 'updating' : done && !bad ? 'flash' : '';
return (
<div key={e.name} className={`ss-r relative !min-h-10 ${row}`} style={done ? stagger(i) : undefined}>
{e.tracked
? <span className="w-[22px] grid place-items-center text-ink-2"><GitBranch size={15} /></span>
: <span className="ss-cat sm skill"><Puzzle size={13} /></span>}
<span className="nm m truncate shrink-0 max-w-[55%]">{e.name}</span>
{e.tracked && <span className="ss-tag">tracked</span>}
<span className="min-w-0 flex-1 truncate font-mono text-xs text-ink-3">{parseRemoteURL(e.source)?.ownerRepo ?? e.source}</span>
<span className="w-5 grid place-items-center">
{phase === 'running' && <Loader2 size={14} className="animate-spin text-ink-3" />}
{done && (bad
? <X size={15} strokeWidth={2.6} className="ss-pop text-bad" style={stagger(i)} />
: <Check size={15} strokeWidth={2.6} className="ss-pop text-ok" style={stagger(i)} />)}
</span>
{phase === 'running' && <span className="ss-rowbar" aria-hidden />}
</div>
);
})}
</div>
</div>
</section>
</div>
);
}
+6 -11
View File
@@ -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<SkillsAddCommand | null>(null);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [filter, setFilter] = useState('');
const [expanded, setExpanded] = useState(false);
const [kindChoice, setKindChoice] = useState<KindChoice | null>(null);
const [kindPick, setKindPick] = useState<Kind>(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 && <ConfigInstallPanel />}
{tabs}
<div className="flex items-center gap-2">
<label className="ss-inp flex-1">
@@ -668,7 +669,6 @@ export default function InstallDialog({ kind, initialTab, initialSource, onClose
const agents = found?.items[0]?.kind === 'agent';
const f = filter.trim().toLowerCase();
const filtered = (found?.items ?? []).filter((i) => !f || i.name.toLowerCase().includes(f) || i.description?.toLowerCase().includes(f));
const listed = expanded || f ? filtered : filtered.slice(0, FOUND_PREVIEW);
const allSelected = found !== null && selected.size === found.items.length;
const toggle = (path: string) => {
const next = new Set(selected);
@@ -684,6 +684,7 @@ export default function InstallDialog({ kind, initialTab, initialSource, onClose
: t(isAgent ? 'install.url.findAgents' : 'install.url.findSkills');
body = (
<>
{!isAgent && <ConfigInstallPanel />}
{tabs}
<div className="ss-fld">
<label htmlFor={`${ids}src`}>{t('install.url.sourceLabel')}</label>
@@ -740,10 +741,10 @@ export default function InstallDialog({ kind, initialTab, initialSource, onClose
<div className="flex-1">{t(agents ? 'install.url.onlyAgents' : 'install.url.onlySkills')}</div>
</div>
)}
{/* Rows scroll inside the list frame once expanded, so the dialog keeps its height */}
{/* Rows scroll inside the list frame, so the dialog keeps its height */}
<div className="ss-list !shadow-none flex flex-col">
<div className="max-h-[264px] overflow-y-auto">
{listed.map((item) => (
{filtered.map((item) => (
<div
key={item.path}
className={`ss-r !min-h-11 cursor-pointer ${selected.has(item.path) ? 'sel' : ''}`}
@@ -756,12 +757,6 @@ export default function InstallDialog({ kind, initialTab, initialSource, onClose
</div>
))}
</div>
{listed.length < filtered.length && (
<button type="button" className="ss-r !min-h-[38px] w-full text-left" onClick={() => setExpanded(true)}>
<span className="flex-1 text-[13px] text-ink-3">{t('install.url.more', { count: filtered.length - listed.length })}</span>
<ChevronDown size={15} className="text-ink-3" />
</button>
)}
</div>
</div>
)}
+8 -3
View File
@@ -22,6 +22,8 @@ export interface ContextMenuItem {
label: string;
/** What picking this does, shown under the label. */
description?: string;
/** Show the label as code, for field names and paths. */
mono?: boolean;
icon?: React.ReactNode;
/** Direct action — mutually exclusive with `items` */
onSelect?: () => void;
@@ -41,11 +43,14 @@ interface SkillContextMenuProps {
anchorPoint?: { x: number; y: number };
open: boolean;
onClose: () => void;
/** `end` puts the menu's right edge at the anchor, under a button on the right. */
align?: 'start' | 'end';
}
export function SkillContextMenu({
items,
anchorPoint,
align = 'start',
open,
onClose,
}: SkillContextMenuProps) {
@@ -64,7 +69,7 @@ export function SkillContextMenu({
const menu = menuRef.current;
const rect = menu.getBoundingClientRect();
let top = anchorPoint.y;
let left = anchorPoint.x;
let left = align === 'end' ? Math.max(8, anchorPoint.x - rect.width) : anchorPoint.x;
if (top + rect.height > window.innerHeight - 8) {
top = Math.max(8, anchorPoint.y - rect.height);
}
@@ -72,7 +77,7 @@ export function SkillContextMenu({
left = Math.max(8, anchorPoint.x - rect.width);
}
setPosition({ top, left });
}, [open, anchorPoint]);
}, [open, anchorPoint, align]);
// Close on Escape (submenu first, then parent)
useEffect(() => {
@@ -136,7 +141,7 @@ export function SkillContextMenu({
{item.icon && <span className="w-4 shrink-0 flex items-center justify-center">{item.icon}</span>}
{item.description ? (
<span className="flex min-w-0 flex-col gap-0.5">
<span className="font-mono">{item.label}</span>
<span className={item.mono ? 'font-mono' : ''}>{item.label}</span>
<span className="text-xs font-normal leading-snug text-ink-3">{item.description}</span>
</span>
) : item.label}
@@ -229,7 +229,7 @@ export default function FrontmatterEditor({ frontmatter, onChange, yaml, onYaml
anchorPoint={menu ?? undefined}
onClose={() => setMenu(null)}
items={[
...unset.map((f) => ({ key: f.key, label: f.key, description: t(`frontmatterEditor.field.${f.hint}.hint`), onSelect: () => setShown((prev) => new Set(prev).add(f.key)) })),
...unset.map((f) => ({ key: f.key, label: f.key, mono: true, description: t(`frontmatterEditor.field.${f.hint}.hint`), onSelect: () => setShown((prev) => new Set(prev).add(f.key)) })),
{ key: '__metadata', label: t('frontmatterEditor.customMetadata'), icon: <Plus size={14} />, onSelect: () => setAddingMeta(true) },
]}
/>
+35 -1
View File
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { api, type DiffTarget, type Target } from '../../api/client';
import { hooksApi, type HookPlan } from '../../api/hooks';
import { mcpApi, type MCPPlan } from '../../api/mcp';
import { countChanges, countEdited, extraGroups, failureExplanation, groupByFolder, groupInSync, HOOKS_CHANGED, hooksGroups, MCP_CHANGED, mcpGroups, otherWarnings, pendingCount, resourceGroups, runSync, type SyncFailure } from './syncView';
import { changeSets, countChanges, countEdited, discardable, extraGroups, failureExplanation, groupByFolder, groupInSync, HOOKS_CHANGED, hooksGroups, MCP_CHANGED, mcpGroups, otherWarnings, pendingCount, resourceGroups, runSync, type SyncFailure } from './syncView';
vi.mock('../../api/client', async (load) => ({ ...await load<typeof import('../../api/client')>(), api: { sync: vi.fn(), syncExtras: vi.fn() } }));
vi.mock('../../api/mcp', async (load) => ({ ...await load<typeof import('../../api/mcp')>(), mcpApi: { preview: vi.fn(), configure: vi.fn() } }));
@@ -41,6 +41,40 @@ describe('resourceGroups', () => {
});
});
describe('changeSets', () => {
it('puts targets with the same changes in one set', () => {
const same: DiffTarget[] = ['claude', 'codex', 'cursor'].map((name) => ({ target: name, items: [{ skill: name === 'cursor' ? 'other' : 'pdf', action: 'link', reason: 'new' }] }));
const { groups } = resourceGroups(same, ['claude', 'codex', 'cursor'].map((n) => target(n)), new Set(['skill']), false);
expect(changeSets(groups).map((set) => set.targets.map((g) => g.name))).toEqual([['claude', 'codex'], ['cursor']]);
});
});
describe('discardable', () => {
const skill = (flatName: string) => ({ name: flatName, kind: 'skill', flatName, relPath: flatName, sourcePath: '', isInRepo: false }) as const;
const newRows: DiffTarget[] = [{ target: 'claude', items: [
{ skill: 'fresh', action: 'link', reason: 'new' },
{ skill: 'old', action: 'link', reason: 'new' },
{ skill: 'handmade', action: 'link', reason: 'new' },
{ skill: 'gone', action: 'link', reason: 'missing in target' },
] }];
it('keeps skills already synced to another target and ones to copy again', () => {
const { groups } = resourceGroups(newRows, [target('claude')], new Set(['skill']), false);
const skills = ['fresh', 'old', 'handmade', 'gone'].map((n) => skill(n));
const expected = (name: string) => (name === 'old' ? ['claude', 'codex'] : ['claude']);
expect(discardable(groups, skills, expected).map((s) => s.flatName)).toEqual(['fresh', 'handmade']);
});
it('leaves a tracked repo alone when only some of its skills are new', () => {
// Uninstalling a tracked repo takes all of it, so one new skill must not trash synced siblings.
const rows: DiffTarget[] = [{ target: 'claude', items: [{ skill: '_team__new', action: 'link', reason: 'new' }, { skill: '_solo__a', action: 'link', reason: 'new' }, { skill: '_solo__b', action: 'link', reason: 'new' }] }];
const { groups } = resourceGroups(rows, [target('claude')], new Set(['skill']), false);
const inRepo = (flatName: string, repoPath: string) => ({ ...skill(flatName), isInRepo: true, repoPath });
const skills = [inRepo('_team__new', '_team'), inRepo('_team__old', '_team'), inRepo('_solo__a', '_solo'), inRepo('_solo__b', '_solo')];
expect(discardable(groups, skills, () => ['claude']).map((s) => s.flatName)).toEqual(['_solo__a', '_solo__b']);
});
});
describe('extraGroups', () => {
it('keeps files edited in the target unless force is on', () => {
const extras = [{ name: 'rules', target: '/home/rules', mode: 'merge', items: [
+49 -1
View File
@@ -1,4 +1,4 @@
import { api, type DiffTarget, type ExtraDiffResult, type SyncResponse, type Target } from '../../api/client';
import { api, type DiffTarget, type ExtraDiffResult, type Skill, type SyncMatrixEntry, type SyncResponse, type Target } from '../../api/client';
import { hooksApi, type HookPlan } from '../../api/hooks';
import { mcpApi, type MCPPlan } from '../../api/mcp';
import { formatAgentDisplayName } from '../../lib/resourceNames';
@@ -163,6 +163,54 @@ export function groupByFolder(names: string[]) {
return [...folders].map(([folder, items]) => ({ folder, items }));
}
/** Targets getting exactly the same changes, as one set: twelve targets adding the same 38 skills read as one list. */
export function changeSets(groups: ChangeGroup[]): { key: string; targets: ChangeGroup[]; rows: ChangeRow[] }[] {
const sets = new Map<string, { key: string; targets: ChangeGroup[]; rows: ChangeRow[] }>();
for (const g of groups) {
const sig = g.rows.map((r) => `${r.part}\t${r.name}\t${r.icon}\t${r.text}`).sort().join('\n');
const set = sets.get(sig);
if (set) set.targets.push(g);
else sets.set(sig, { key: g.key, targets: [g], rows: g.rows });
}
return [...sets.values()].sort((a, b) => b.rows.length - a.rows.length);
}
/** Rows per icon, conflicts counted as kept: both leave the target's copy alone. */
export function tally(rows: ChangeRow[]): Partial<Record<RowIcon, number>> {
const n: Partial<Record<RowIcon, number>> = {};
for (const r of rows) {
const icon = r.icon === 'conflict' ? 'kept' : r.icon;
n[icon] = (n[icon] ?? 0) + 1;
}
return n;
}
/**
* Whether a target gets a skill: by its filters, or always when it links the whole source folder.
* The matrix marks symlink-mode targets `na` since filters don't apply, yet every source skill is live there.
*/
export const receivesSkill = (e: SyncMatrixEntry) => e.status === 'synced' || e.reasonCode === 'sync_matrix.symlink_filters_not_applicable';
/**
* The skills Discard all moves to trash: never synced anywhere yet, so new in every target that should get them.
* `expected` names the targets a skill syncs to (the sync matrix). A skill already in one of them was synced before
* and stays, even when a new target is about to get it. Install times can't tell this: tracked repo skills have none.
* A tracked repo counts only as a whole, since uninstalling one skill of it removes the repo.
*/
export function discardable(groups: ChangeGroup[], skills: Skill[], expected: (flatName: string) => string[]): Skill[] {
const added = new Map<string, Set<string>>();
for (const g of groups) {
for (const r of g.rows) {
if (r.part !== 'skill' || r.icon !== 'add' || r.text === 'sync.row.recopy') continue;
added.set(r.name, (added.get(r.name) ?? new Set()).add(g.name));
}
}
const fresh = (s: Skill) => s.kind === 'skill' && added.has(s.flatName) && expected(s.flatName).every((t) => added.get(s.flatName)!.has(t));
// A tracked repo uninstalls whole, so it qualifies only when every skill in it is new.
const keptRepos = new Set(skills.filter((s) => s.kind === 'skill' && s.repoPath && !fresh(s)).map((s) => s.repoPath));
return skills.filter((s) => fresh(s) && !(s.repoPath && keptRepos.has(s.repoPath)));
}
export const countChanges = (groups: ChangeGroup[]) => groups.reduce((n, g) => n + g.rows.filter((r) => r.counts).length, 0);
/** Changes a plain sync of every part would apply (the sidebar badge). A blocked MCP or hooks plan applies nothing. */
export function pendingCount(diffs: DiffTarget[], targets: Target[], extras: ExtraDiffResult[], plan: MCPPlan | null | undefined, hooks?: HookPlan | null): number {
+105
View File
@@ -0,0 +1,105 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '../api/client';
import type { ConfigEntry, InstallFromConfigResult } from '../api/client';
import { queryKeys, staleTimes } from '../lib/queryKeys';
import { invalidate } from '../lib/queryEvents';
import { plural, useT } from '../i18n';
export type ConfigInstallPhase = 'idle' | 'running' | 'done' | 'closing';
const COLLAPSE_MS = 450;
/**
* Installs what config records but the disk lacks, like bare `skillshare install`.
* While a run is shown, `entries` stays the list it started from so rows can show their results.
*/
export function useInstallFromConfig() {
const queryClient = useQueryClient();
const { data } = useQuery({
queryKey: queryKeys.missingConfigEntries,
queryFn: () => api.missingConfigEntries(),
staleTime: staleTimes.missingConfigEntries,
});
const [phase, setPhase] = useState<ConfigInstallPhase>('idle');
const [snapshot, setSnapshot] = useState<ConfigEntry[]>([]);
const [result, setResult] = useState<InstallFromConfigResult | null>(null);
const [error, setError] = useState<string | null>(null);
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
const live = data?.entries ?? [];
const entries = phase === 'idle' ? live : snapshot;
const t = useT();
const counts = useEntryCounts();
const done = phase === 'done' || phase === 'closing';
const repoSkills = useCountUp(result?.installedRepoSkills ?? 0, done);
const failed = new Set(result?.failed ?? []);
const installedRepos = result?.installedRepos ?? 0;
const installed = result?.installed ?? 0;
const repos = entries.filter((e) => e.tracked).length;
/** What a finished run did: "Installed 1 tracked repo (12 skills), 1 failed". */
const summary = [
installed > 0 && t('install.fromConfig.installed', { items: counts(installedRepos, installed - installedRepos, installedRepos > 0 ? repoSkills : undefined) }),
failed.size > 0 && t('install.fromConfig.failed', { count: failed.size }),
].filter(Boolean).join(', ');
/** What the entries hold: "1 tracked repo, 2 skills". */
const contents = counts(repos, entries.length - repos);
const run = useCallback(async () => {
setSnapshot(live);
setPhase('running');
setError(null);
try {
const r = await api.installFromConfig();
setResult(r);
setPhase('done');
void invalidate(queryClient, 'configInstalled');
} catch (err) {
setError((err as Error).message);
setPhase('idle');
}
}, [live, queryClient]);
/** Collapses the finished panel, then hands the list back to the query. */
const dismiss = useCallback(() => {
setPhase('closing');
timer.current = setTimeout(() => {
setPhase('idle');
setResult(null);
}, COLLAPSE_MS);
}, []);
return { entries, file: data?.file ?? '.metadata.json', phase, done, failed, summary, contents, error, run, dismiss };
}
/** Counts up from 0 to `target` once `active` turns on, for a summary number that fills in. */
function useCountUp(target: number, active: boolean) {
const [value, setValue] = useState(0);
useEffect(() => {
if (!active) { setValue(0); return; }
if (target <= 0 || window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) { setValue(target); return; }
const step = Math.max(1, Math.ceil(target / 24));
const id = setInterval(() => setValue((v) => {
const next = Math.min(target, v + step);
if (next === target) clearInterval(id);
return next;
}), 40);
return () => clearInterval(id);
}, [target, active]);
return value;
}
/** "1 tracked repo, 2 skills": what a list of config entries holds. */
function useEntryCounts() {
const t = useT();
return (repos: number, skills: number, repoSkills?: number) => {
const parts: string[] = [];
if (repos > 0) {
const label = t(plural('install.fromConfig.repos', repos), { count: repos });
parts.push(repoSkills === undefined ? label : `${label} (${t(plural('install.fromConfig.skills', repoSkills), { count: repoSkills })})`);
}
if (skills > 0) parts.push(t(plural('install.fromConfig.skills', skills), { count: skills }));
return parts.join(', ');
};
}
+2 -1
View File
@@ -14,11 +14,12 @@ function summarize(entries: SyncMatrixEntry[]): { synced: number; total: number
};
}
export function useSyncMatrix() {
export function useSyncMatrix(enabled = true) {
const { data, isLoading, error } = useQuery({
queryKey: queryKeys.syncMatrix(),
queryFn: () => api.getSyncMatrix(),
staleTime: staleTimes.syncMatrix,
enabled,
});
const matrix = data?.entries ?? EMPTY;
+44 -6
View File
@@ -667,6 +667,11 @@
"resources.folder.noEditableSkills": "Keine Skills in {folder}/ geändert — deaktivierte Skills werden übersprungen",
"resources.folder.skillsUpdated": "{count} Skill(s) in {folder}/ jetzt verfügbar in {target}",
"resources.newSkill": "Neuer Skill",
"resources.moreWays": "Weitere Möglichkeiten zum Hinzufügen",
"resources.add.install": "Von URL oder Hub installieren",
"resources.add.installHint": "Öffnet den Installationsdialog",
"resources.add.newHint": "Leer oder aus einer Vorlage beginnen",
"resources.add.linkHint": "Einen lokalen Ordner in die Quelle holen",
"resources.noMatches.description": "Anderen Suchbegriff oder Filter ausprobieren.",
"resources.noMatches.title": "Keine Treffer",
"resources.skills.empty.description": "Skills von GitHub installieren oder zum Quellverzeichnis hinzufügen.",
@@ -857,6 +862,7 @@
"update.check.unchecked": "Ungeprüft",
"update.check.upToDate": "Aktuell",
"update.check.updateAvailable": "Update verfügbar",
"update.check.stale": "Upstream gelöscht",
"update.check.dirty": "Lokal geändert",
"update.done.subtitle": "Aktualisierung abgeschlossen.",
"update.done.syncHint": "Ziele erhalten die neuen Versionen beim nächsten Sync.",
@@ -879,11 +885,15 @@
"update.updating.purge": "Löschen",
"update.updating.purged": "Gelöscht",
"update.updating.purging": "Wird gelöscht...",
"update.missingRepos.title": "{count} getrackte(s) Repo(s) fehlen auf der Festplatte",
"update.missingRepos.description": "Diese getrackten Repositorys sind in den Metadaten deklariert, aber ihre Klon-Verzeichnisse fehlen. Rehydrieren, um sie aus ihren Quellen neu zu klonen.",
"update.missingRepos.rehydrate": "Rehydrieren",
"update.missingRepos.rehydrateSuccess": "{count} getrackte(s) Repo(s) rehydriert",
"update.missingRepos.rehydratePartial": "{count} Repo(s) konnten nicht rehydriert werden",
"update.missingEntries.title.one": "{count} Eintrag in {file} fehlt auf der Festplatte",
"update.missingEntries.title.other": "{count} Einträge in {file} fehlen auf der Festplatte",
"update.missingEntries.description": "„Fehlende installieren“ installiert sie erneut aus den gespeicherten Quellen.",
"update.missingEntries.install": "Fehlende installieren",
"update.stale.title": "Upstream gelöscht · {count}",
"update.stale.pruneAll": "Alle löschen",
"update.stale.note": "Diese wurden aus ihrem Quell-Repo entfernt. Löschen verschiebt sie in den Papierkorb, wo du sie 7 Tage lang wiederherstellen kannst.",
"update.stale.pruned.one": "{count} Skill gelöscht. Im Papierkorb 7 Tage lang wiederherstellbar.",
"update.stale.pruned.other": "{count} Skills gelöscht. Im Papierkorb 7 Tage lang wiederherstellbar.",
"updateDialog.copyCommand": "Befehl kopieren",
"updateDialog.needsSudo": "Für das Update wird dein Passwort benötigt. Führe skillshare upgrade in einem Terminal aus.",
"updateDialog.newVersion": "Neue Version verfügbar",
@@ -1073,7 +1083,6 @@
"install.url.selected": "{count} ausgewählt",
"install.url.filterSkills": "Skills filtern",
"install.url.filterAgents": "Agents filtern",
"install.url.more": "{count} weitere",
"install.url.track": "Dieses Repo verfolgen",
"install.url.trackHint": "Behält einen Git-Klon, damit Update neue Versionen holen kann. Ohne das bekommst du eine einmalige Kopie.",
"install.url.advanced": "Erweitert",
@@ -1104,6 +1113,19 @@
"install.title.skills": "Skills installieren",
"install.title.agents": "Agents installieren",
"install.audited": "Jeder Skill wird vor der Installation geprüft.",
"install.fromConfig.title.one": "{count} Eintrag in {file} ist nicht installiert",
"install.fromConfig.title.other": "{count} Einträge in {file} sind nicht installiert",
"install.fromConfig.hint": "{items}. Wie skillshare install.",
"install.fromConfig.installAll": "Alle installieren",
"install.fromConfig.installing": "Installiere aus {file}…",
"install.fromConfig.installed": "{items} installiert",
"install.fromConfig.failed": "{count} fehlgeschlagen",
"install.fromConfig.failedHint": "Prüfe die Quellen und deinen Zugriff, dann versuche es erneut.",
"install.fromConfig.syncHint": "Führe sync aus, um sie mit deinen Zielen zu verknüpfen.",
"install.fromConfig.repos.one": "{count} getracktes Repo",
"install.fromConfig.repos.other": "{count} getrackte Repos",
"install.fromConfig.skills.one": "{count} Skill",
"install.fromConfig.skills.other": "{count} Skills",
"install.findings": "{count} Befunde",
"install.warnings.title": "Mit Warnungen installiert",
"install.warnings.message": "Die Installation ist abgeschlossen, aber das Audit hat diese Befunde gemeldet.",
@@ -1777,6 +1799,22 @@
"sync.run.one": "{count} Änderung synchronisieren",
"sync.run.other": "{count} Änderungen synchronisieren",
"sync.run.none": "Synchronisieren",
"sync.discard": "Alle verwerfen",
"sync.pending.one": "{count} Änderung",
"sync.pending.other": "{count} Änderungen",
"sync.view.change": "Nach Änderung",
"sync.view.target": "Nach Ziel",
"sync.sum.add": "{count} neu",
"sync.sum.update": "{count} aktualisiert",
"sync.sum.remove": "{count} entfernt",
"sync.sum.kept": "{count} behalten",
"sync.set.targets.one": "{count} Ziel",
"sync.set.targets.other": "{count} Ziele",
"sync.set.add": "{count} {noun} hinzufügen",
"sync.set.update": "{count} {noun} aktualisieren",
"sync.set.remove": "{count} {noun} entfernen",
"sync.set.kept": "{count} {noun} behalten",
"sync.set.targetList": "Ziele · {count}",
"sync.include": "Einbeziehen",
"sync.changes.one": "{count} Änderung",
"sync.changes.other": "{count} Änderungen",
+48 -10
View File
@@ -661,6 +661,11 @@
"resources.folder.noEditableSkills": "No skills in {folder}/ were changed — disabled skills are skipped",
"resources.folder.skillsUpdated": "{count} skill(s) in {folder}/ now available in {target}",
"resources.newSkill": "New skill",
"resources.moreWays": "More ways to add",
"resources.add.install": "Install from URL or Hub",
"resources.add.installHint": "Opens the install dialog",
"resources.add.newHint": "Start blank or from a template",
"resources.add.linkHint": "Bring a local folder into the source",
"resources.noMatches.description": "Try a different search term or filter.",
"resources.noMatches.title": "No matches",
"resources.skills.empty.description": "Install skills from GitHub or add them to your source directory.",
@@ -778,6 +783,7 @@
"update.check.error": "Check failed",
"update.check.unchecked": "Not checked",
"update.check.updateAvailable": "Update available",
"update.check.stale": "Deleted upstream",
"update.check.upToDate": "Up to date",
"update.check.dirty": "Modified locally",
"update.done.subtitle": "Update finished.",
@@ -798,14 +804,18 @@
"update.summary.skipped": "{count} skipped",
"update.summary.updated": "{count} updated",
"update.updating.forceRetry": "Force retry",
"update.updating.purge": "Purge",
"update.updating.purged": "Purged",
"update.updating.purging": "Purging...",
"update.missingRepos.title": "{count} tracked repo(s) missing on disk",
"update.missingRepos.description": "Rehydrate clones them again from their sources.",
"update.missingRepos.rehydrate": "Rehydrate",
"update.missingRepos.rehydrateSuccess": "Rehydrated {count} tracked repo(s)",
"update.missingRepos.rehydratePartial": "{count} repo(s) failed to rehydrate",
"update.updating.purge": "Prune",
"update.updating.purged": "Pruned",
"update.updating.purging": "Pruning...",
"update.missingEntries.title.one": "{count} entry in {file} is missing on disk",
"update.missingEntries.title.other": "{count} entries in {file} are missing on disk",
"update.missingEntries.description": "Install missing installs them again from their recorded sources.",
"update.missingEntries.install": "Install missing",
"update.stale.title": "Deleted upstream · {count}",
"update.stale.pruneAll": "Prune all",
"update.stale.note": "These were removed from their source repo. Prune moves them to Trash, where you can restore them for 7 days.",
"update.stale.pruned.one": "Pruned {count} skill. Restore it from Trash within 7 days.",
"update.stale.pruned.other": "Pruned {count} skills. Restore them from Trash within 7 days.",
"theme.clean": "Clean",
"theme.dark": "Dark",
"theme.light": "Light",
@@ -1011,7 +1021,7 @@
"update.tab.checkNow": "Check for updates",
"update.tab.checkAgain": "Check again",
"update.tab.updateAll": "Update all",
"update.tab.footer": "Force retry applies an update even though the audit blocked it. Purge removes an entry whose source is gone.",
"update.tab.footer": "Force retry applies an update even though the audit blocked it. Prune removes an entry whose source is gone.",
"update.row.update": "Update",
"update.hero.available": "{count} with new versions",
"update.hero.allCurrent": "Everything is up to date",
@@ -1073,7 +1083,6 @@
"install.url.selected": "{count} selected",
"install.url.filterSkills": "Filter skills",
"install.url.filterAgents": "Filter agents",
"install.url.more": "{count} more",
"install.url.track": "Track this repo",
"install.url.trackHint": "Keeps a git clone so Update can pull new versions. Without it you get a one-time copy.",
"install.url.advanced": "Advanced",
@@ -1104,6 +1113,19 @@
"install.title.skills": "Install skills",
"install.title.agents": "Install agents",
"install.audited": "Every skill is audited before it is installed.",
"install.fromConfig.title.one": "{count} entry in {file} is not installed",
"install.fromConfig.title.other": "{count} entries in {file} are not installed",
"install.fromConfig.hint": "{items}. Same as running skillshare install.",
"install.fromConfig.installAll": "Install all",
"install.fromConfig.installing": "Installing from {file}…",
"install.fromConfig.installed": "Installed {items}",
"install.fromConfig.failed": "{count} failed",
"install.fromConfig.failedHint": "Check each source and your access, then retry.",
"install.fromConfig.syncHint": "Run sync to link them into your targets.",
"install.fromConfig.repos.one": "{count} tracked repo",
"install.fromConfig.repos.other": "{count} tracked repos",
"install.fromConfig.skills.one": "{count} skill",
"install.fromConfig.skills.other": "{count} skills",
"install.findings": "{count} findings",
"install.warnings.title": "Installed with warnings",
"install.warnings.message": "The install finished, but the audit reported these findings.",
@@ -1777,6 +1799,22 @@
"sync.run.one": "Sync {count} change",
"sync.run.other": "Sync {count} changes",
"sync.run.none": "Sync",
"sync.discard": "Discard all",
"sync.pending.one": "{count} change",
"sync.pending.other": "{count} changes",
"sync.view.change": "By change",
"sync.view.target": "By target",
"sync.sum.add": "{count} new",
"sync.sum.update": "{count} updated",
"sync.sum.remove": "{count} removed",
"sync.sum.kept": "{count} kept",
"sync.set.targets.one": "{count} target",
"sync.set.targets.other": "{count} targets",
"sync.set.add": "Add {count} {noun}",
"sync.set.update": "Update {count} {noun}",
"sync.set.remove": "Remove {count} {noun}",
"sync.set.kept": "Keep {count} {noun}",
"sync.set.targetList": "Targets · {count}",
"sync.include": "Include",
"sync.changes.one": "{count} change",
"sync.changes.other": "{count} changes",
+44 -6
View File
@@ -667,6 +667,11 @@
"resources.folder.noEditableSkills": "No se cambió ningún skill en {folder}/ — los skills deshabilitados se omiten",
"resources.folder.skillsUpdated": "{count} skill(s) en {folder}/ ahora disponibles en {target}",
"resources.newSkill": "Nueva skill",
"resources.moreWays": "Más formas de añadir",
"resources.add.install": "Instalar desde URL o Hub",
"resources.add.installHint": "Abre el diálogo de instalación",
"resources.add.newHint": "Empezar en blanco o desde una plantilla",
"resources.add.linkHint": "Incorporar una carpeta local al origen",
"resources.noMatches.description": "Prueba con otro término de búsqueda o filtro.",
"resources.noMatches.title": "Sin coincidencias",
"resources.skills.empty.description": "Instala skills desde GitHub o añádelas a tu directorio fuente.",
@@ -857,6 +862,7 @@
"update.check.unchecked": "Sin comprobar",
"update.check.upToDate": "Actualizado",
"update.check.updateAvailable": "Actualización disponible",
"update.check.stale": "Eliminado en origen",
"update.check.dirty": "Modificado localmente",
"update.done.subtitle": "Actualización completa.",
"update.done.syncHint": "Los destinos reciben las nuevas versiones en la próxima sincronización.",
@@ -879,11 +885,15 @@
"update.updating.purge": "Purgar",
"update.updating.purged": "Purgado",
"update.updating.purging": "Purgando...",
"update.missingRepos.title": "Faltan {count} repo(s) rastreado(s) en el disco",
"update.missingRepos.description": "Estos repositorios rastreados están declarados en los metadatos, pero faltan sus directorios de clonación. Rehidrata para volver a clonarlos desde sus orígenes.",
"update.missingRepos.rehydrate": "Rehidratar",
"update.missingRepos.rehydrateSuccess": "{count} repo(s) rastreado(s) rehidratado(s)",
"update.missingRepos.rehydratePartial": "No se pudieron rehidratar {count} repo(s)",
"update.missingEntries.title.one": "Falta en el disco {count} entrada de {file}",
"update.missingEntries.title.other": "Faltan en el disco {count} entradas de {file}",
"update.missingEntries.description": "«Instalar faltantes» los vuelve a instalar desde sus fuentes registradas.",
"update.missingEntries.install": "Instalar faltantes",
"update.stale.title": "Eliminado en origen · {count}",
"update.stale.pruneAll": "Purgar todo",
"update.stale.note": "Se eliminaron de su repo de origen. Purgar los mueve a la papelera, donde puedes restaurarlos durante 7 días.",
"update.stale.pruned.one": "Se purgó {count} skill. Restáuralo desde la papelera en 7 días.",
"update.stale.pruned.other": "Se purgaron {count} skills. Restáuralos desde la papelera en 7 días.",
"updateDialog.copyCommand": "Copiar comando",
"updateDialog.needsSudo": "La actualización necesita tu contraseña. Ejecuta skillshare upgrade en una terminal.",
"updateDialog.newVersion": "Nueva versión disponible",
@@ -1073,7 +1083,6 @@
"install.url.selected": "{count} seleccionadas",
"install.url.filterSkills": "Filtrar skills",
"install.url.filterAgents": "Filtrar agents",
"install.url.more": "{count} más",
"install.url.track": "Seguir este repo",
"install.url.trackHint": "Mantiene un clon de git para que Actualizar pueda traer versiones nuevas. Sin esto obtienes una copia única.",
"install.url.advanced": "Avanzado",
@@ -1104,6 +1113,19 @@
"install.title.skills": "Instalar skills",
"install.title.agents": "Instalar agents",
"install.audited": "Cada skill se audita antes de instalarse.",
"install.fromConfig.title.one": "{count} entrada de {file} no está instalada",
"install.fromConfig.title.other": "{count} entradas de {file} no están instaladas",
"install.fromConfig.hint": "{items}. Igual que ejecutar skillshare install.",
"install.fromConfig.installAll": "Instalar todo",
"install.fromConfig.installing": "Instalando desde {file}…",
"install.fromConfig.installed": "Instalado: {items}",
"install.fromConfig.failed": "{count} con error",
"install.fromConfig.failedHint": "Revisa las fuentes y tu acceso, y vuelve a intentarlo.",
"install.fromConfig.syncHint": "Ejecuta sync para enlazarlos con tus destinos.",
"install.fromConfig.repos.one": "{count} repo rastreado",
"install.fromConfig.repos.other": "{count} repos rastreados",
"install.fromConfig.skills.one": "{count} skill",
"install.fromConfig.skills.other": "{count} skills",
"install.findings": "{count} hallazgos",
"install.warnings.title": "Instalado con advertencias",
"install.warnings.message": "La instalación terminó, pero la auditoría informó estos hallazgos.",
@@ -1777,6 +1799,22 @@
"sync.run.one": "Sincronizar {count} cambio",
"sync.run.other": "Sincronizar {count} cambios",
"sync.run.none": "Sincronizar",
"sync.discard": "Descartar todo",
"sync.pending.one": "{count} cambio",
"sync.pending.other": "{count} cambios",
"sync.view.change": "Por cambio",
"sync.view.target": "Por destino",
"sync.sum.add": "{count} nuevos",
"sync.sum.update": "{count} actualizados",
"sync.sum.remove": "{count} eliminados",
"sync.sum.kept": "{count} conservados",
"sync.set.targets.one": "{count} destino",
"sync.set.targets.other": "{count} destinos",
"sync.set.add": "Añadir {count} {noun}",
"sync.set.update": "Actualizar {count} {noun}",
"sync.set.remove": "Eliminar {count} {noun}",
"sync.set.kept": "Conservar {count} {noun}",
"sync.set.targetList": "Destinos · {count}",
"sync.include": "Incluir",
"sync.changes.one": "{count} cambio",
"sync.changes.other": "{count} cambios",
+44 -6
View File
@@ -667,6 +667,11 @@
"resources.folder.noEditableSkills": "هیچ اسکیلی در {folder}/ تغییر نکرد — اسکیل‌های غیرفعال نادیده گرفته می‌شوند",
"resources.folder.skillsUpdated": "{count} اسکیل در {folder}/ اکنون در {target} در دسترس است",
"resources.newSkill": "اسکیل جدید",
"resources.moreWays": "راه‌های دیگر افزودن",
"resources.add.install": "نصب از URL یا Hub",
"resources.add.installHint": "پنجرهٔ نصب را باز می‌کند",
"resources.add.newHint": "از صفر یا از یک قالب شروع کنید",
"resources.add.linkHint": "یک پوشهٔ محلی را به منبع بیاورید",
"resources.noMatches.description": "یک عبارت جستجو یا فیلتر متفاوت امتحان کنید.",
"resources.noMatches.title": "هیچ موردی پیدا نشد",
"resources.skills.empty.description": "اسکیل‌ها را از GitHub نصب کنید یا به پوشه منبع خود اضافه کنید.",
@@ -857,6 +862,7 @@
"update.check.unchecked": "بررسی‌نشده",
"update.check.upToDate": "به‌روز",
"update.check.updateAvailable": "به‌روزرسانی موجود است",
"update.check.stale": "در مبدأ حذف شده",
"update.check.dirty": "تغییرات محلی",
"update.done.subtitle": "به‌روزرسانی کامل شد.",
"update.done.syncHint": "مقصدها نسخه‌های جدید را در همگام‌سازی بعدی دریافت می‌کنند.",
@@ -879,11 +885,15 @@
"update.updating.purge": "پاکسازی",
"update.updating.purged": "پاکسازی شد",
"update.updating.purging": "در حال پاکسازی...",
"update.missingRepos.title": "{count} مخزن ردیابی‌شده روی دیسک وجود ندارد",
"update.missingRepos.description": "این مخازن ردیابی‌شده در فراداده اعلام شده‌اند اما دایرکتوری کلون آن‌ها وجود ندارد. برای کلون مجدد از منبع، Rehydrate کنید.",
"update.missingRepos.rehydrate": "Rehydrate",
"update.missingRepos.rehydrateSuccess": "{count} مخزن ردیابی‌شده مجدداً کلون شد",
"update.missingRepos.rehydratePartial": "کلون مجدد {count} مخزن ناموفق بود",
"update.missingEntries.title.one": "{count} مورد در {file} روی دیسک وجود ندارد",
"update.missingEntries.title.other": "{count} مورد در {file} روی دیسک وجود ندارند",
"update.missingEntries.description": "«نصب موارد گم‌شده» آن‌ها را از منبع ثبت‌شده دوباره نصب می‌کند.",
"update.missingEntries.install": "نصب موارد گم‌شده",
"update.stale.title": "در مبدأ حذف شده · {count}",
"update.stale.pruneAll": "پاک‌سازی همه",
"update.stale.note": "این موارد از مخزن مبدأ حذف شده‌اند. پاک‌سازی آن‌ها را به سطل زباله می‌برد و تا ۷ روز قابل بازیابی‌اند.",
"update.stale.pruned.one": "{count} skill پاک‌سازی شد. تا ۷ روز از سطل زباله قابل بازیابی است.",
"update.stale.pruned.other": "{count} skill پاک‌سازی شد. تا ۷ روز از سطل زباله قابل بازیابی است.",
"updateDialog.copyCommand": "کپی دستور",
"updateDialog.needsSudo": "به‌روزرسانی به گذرواژهٔ شما نیاز دارد. در ترمینال skillshare upgrade را اجرا کنید.",
"updateDialog.newVersion": "نسخه جدید موجود است",
@@ -1073,7 +1083,6 @@
"install.url.selected": "{count} انتخاب‌شده",
"install.url.filterSkills": "فیلتر اسکیل‌ها",
"install.url.filterAgents": "فیلتر ایجنت‌ها",
"install.url.more": "{count} مورد دیگر",
"install.url.track": "دنبال کردن این مخزن",
"install.url.trackHint": "یک کلون git نگه می‌دارد تا Update بتواند نسخه‌های جدید را بگیرد. بدون آن فقط یک کپی یک‌باره می‌گیرید.",
"install.url.advanced": "پیشرفته",
@@ -1104,6 +1113,19 @@
"install.title.skills": "نصب اسکیل‌ها",
"install.title.agents": "نصب ایجنت‌ها",
"install.audited": "هر اسکیل پیش از نصب ممیزی می‌شود.",
"install.fromConfig.title.one": "{count} مورد در {file} نصب نشده است",
"install.fromConfig.title.other": "{count} مورد در {file} نصب نشده‌اند",
"install.fromConfig.hint": "{items}. مانند اجرای skillshare install.",
"install.fromConfig.installAll": "نصب همه",
"install.fromConfig.installing": "در حال نصب از {file}…",
"install.fromConfig.installed": "نصب شد: {items}",
"install.fromConfig.failed": "{count} ناموفق",
"install.fromConfig.failedHint": "منبع‌ها و دسترسی خود را بررسی کنید و دوباره تلاش کنید.",
"install.fromConfig.syncHint": "sync را اجرا کنید تا به مقصدها پیوند داده شوند.",
"install.fromConfig.repos.one": "{count} مخزن ردیابی‌شده",
"install.fromConfig.repos.other": "{count} مخزن ردیابی‌شده",
"install.fromConfig.skills.one": "{count} skill",
"install.fromConfig.skills.other": "{count} skill",
"install.findings": "{count} یافته",
"install.warnings.title": "با هشدار نصب شد",
"install.warnings.message": "نصب تمام شد، اما ممیزی این یافته‌ها را گزارش کرد.",
@@ -1777,6 +1799,22 @@
"sync.run.one": "همگام‌سازی {count} تغییر",
"sync.run.other": "همگام‌سازی {count} تغییر",
"sync.run.none": "همگام‌سازی",
"sync.discard": "دورریختن همه",
"sync.pending.one": "{count} تغییر",
"sync.pending.other": "{count} تغییر",
"sync.view.change": "بر اساس تغییر",
"sync.view.target": "بر اساس مقصد",
"sync.sum.add": "{count} جدید",
"sync.sum.update": "{count} به‌روزشده",
"sync.sum.remove": "{count} حذف‌شده",
"sync.sum.kept": "{count} نگه‌داشته",
"sync.set.targets.one": "{count} مقصد",
"sync.set.targets.other": "{count} مقصد",
"sync.set.add": "افزودن {count} {noun}",
"sync.set.update": "به‌روزرسانی {count} {noun}",
"sync.set.remove": "حذف {count} {noun}",
"sync.set.kept": "نگه‌داشتن {count} {noun}",
"sync.set.targetList": "مقصدها · {count}",
"sync.include": "شامل",
"sync.changes.one": "{count} تغییر",
"sync.changes.other": "{count} تغییر",
+44 -6
View File
@@ -667,6 +667,11 @@
"resources.folder.noEditableSkills": "Aucun skill modifié dans {folder}/ — les skills désactivés sont ignorés",
"resources.folder.skillsUpdated": "{count} skill(s) dans {folder}/ maintenant disponible(s) dans {target}",
"resources.newSkill": "Nouveau skill",
"resources.moreWays": "Autres façons d’ajouter",
"resources.add.install": "Installer depuis une URL ou un Hub",
"resources.add.installHint": "Ouvre la fenêtre d'installation",
"resources.add.newHint": "Partir de zéro ou d'un modèle",
"resources.add.linkHint": "Ajouter un dossier local à la source",
"resources.noMatches.description": "Essayez un autre terme de recherche ou un autre filtre.",
"resources.noMatches.title": "Aucun résultat",
"resources.skills.empty.description": "Installez des skills depuis GitHub ou ajoutez-les dans votre répertoire source.",
@@ -857,6 +862,7 @@
"update.check.unchecked": "Non vérifié",
"update.check.upToDate": "À jour",
"update.check.updateAvailable": "Mise à jour disponible",
"update.check.stale": "Supprimé en amont",
"update.check.dirty": "Modifié localement",
"update.done.subtitle": "Mise à jour terminée.",
"update.done.syncHint": "Les cibles reçoivent les nouvelles versions à la prochaine synchronisation.",
@@ -879,11 +885,15 @@
"update.updating.purge": "Purger",
"update.updating.purged": "Purgé",
"update.updating.purging": "Purge en cours...",
"update.missingRepos.title": "{count} dépôt(s) suivi(s) manquant(s) sur le disque",
"update.missingRepos.description": "Ces dépôts suivis sont déclarés dans les métadonnées, mais leurs répertoires de clonage sont absents. Réhydratez pour les recloner depuis leurs sources.",
"update.missingRepos.rehydrate": "Réhydrater",
"update.missingRepos.rehydrateSuccess": "{count} dépôt(s) suivi(s) réhydraté(s)",
"update.missingRepos.rehydratePartial": "Échec de la réhydratation de {count} dépôt(s)",
"update.missingEntries.title.one": "{count} entrée de {file} manque sur le disque",
"update.missingEntries.title.other": "{count} entrées de {file} manquent sur le disque",
"update.missingEntries.description": "« Installer les manquants » les réinstalle depuis leurs sources enregistrées.",
"update.missingEntries.install": "Installer les manquants",
"update.stale.title": "Supprimé en amont · {count}",
"update.stale.pruneAll": "Tout purger",
"update.stale.note": "Ils ont été retirés de leur dépôt source. Purger les déplace dans la corbeille, où vous pouvez les restaurer pendant 7 jours.",
"update.stale.pruned.one": "{count} skill purgé. Restaurable depuis la corbeille pendant 7 jours.",
"update.stale.pruned.other": "{count} skills purgés. Restaurables depuis la corbeille pendant 7 jours.",
"updateDialog.copyCommand": "Copier la commande",
"updateDialog.needsSudo": "La mise à jour nécessite votre mot de passe. Exécutez skillshare upgrade dans un terminal.",
"updateDialog.newVersion": "Nouvelle version disponible",
@@ -1073,7 +1083,6 @@
"install.url.selected": "{count} sélectionné(s)",
"install.url.filterSkills": "Filtrer les skills",
"install.url.filterAgents": "Filtrer les agents",
"install.url.more": "{count} de plus",
"install.url.track": "Suivre ce dépôt",
"install.url.trackHint": "Conserve un clone git pour que Mettre à jour puisse récupérer les nouvelles versions. Sinon, vous obtenez une copie unique.",
"install.url.advanced": "Avancé",
@@ -1104,6 +1113,19 @@
"install.title.skills": "Installer des skills",
"install.title.agents": "Installer des agents",
"install.audited": "Chaque skill est audité avant d’être installé.",
"install.fromConfig.title.one": "{count} entrée de {file} n’est pas installée",
"install.fromConfig.title.other": "{count} entrées de {file} ne sont pas installées",
"install.fromConfig.hint": "{items}. Comme skillshare install.",
"install.fromConfig.installAll": "Tout installer",
"install.fromConfig.installing": "Installation depuis {file}…",
"install.fromConfig.installed": "Installé : {items}",
"install.fromConfig.failed": "{count} en échec",
"install.fromConfig.failedHint": "Vérifiez les sources et vos accès, puis réessayez.",
"install.fromConfig.syncHint": "Lancez sync pour les lier à vos cibles.",
"install.fromConfig.repos.one": "{count} dépôt suivi",
"install.fromConfig.repos.other": "{count} dépôts suivis",
"install.fromConfig.skills.one": "{count} skill",
"install.fromConfig.skills.other": "{count} skills",
"install.findings": "{count} constats",
"install.warnings.title": "Installé avec des avertissements",
"install.warnings.message": "L’installation est terminée, mais l’audit a signalé ces constats.",
@@ -1777,6 +1799,22 @@
"sync.run.one": "Synchroniser {count} changement",
"sync.run.other": "Synchroniser {count} changements",
"sync.run.none": "Synchroniser",
"sync.discard": "Tout abandonner",
"sync.pending.one": "{count} modification",
"sync.pending.other": "{count} modifications",
"sync.view.change": "Par modification",
"sync.view.target": "Par cible",
"sync.sum.add": "{count} nouveaux",
"sync.sum.update": "{count} mis à jour",
"sync.sum.remove": "{count} supprimés",
"sync.sum.kept": "{count} conservés",
"sync.set.targets.one": "{count} cible",
"sync.set.targets.other": "{count} cibles",
"sync.set.add": "Ajouter {count} {noun}",
"sync.set.update": "Mettre à jour {count} {noun}",
"sync.set.remove": "Supprimer {count} {noun}",
"sync.set.kept": "Conserver {count} {noun}",
"sync.set.targetList": "Cibles · {count}",
"sync.include": "Inclure",
"sync.changes.one": "{count} changement",
"sync.changes.other": "{count} changements",
+44 -6
View File
@@ -667,6 +667,11 @@
"resources.folder.noEditableSkills": "Tidak ada skill di {folder}/ yang diubah — skill nonaktif dilewati",
"resources.folder.skillsUpdated": "{count} skill di {folder}/ sekarang tersedia di {target}",
"resources.newSkill": "Skill Baru",
"resources.moreWays": "Cara lain untuk menambahkan",
"resources.add.install": "Pasang dari URL atau Hub",
"resources.add.installHint": "Membuka dialog pemasangan",
"resources.add.newHint": "Mulai kosong atau dari templat",
"resources.add.linkHint": "Hubungkan folder lokal ke sumber",
"resources.noMatches.description": "Coba kata kunci atau filter berbeda.",
"resources.noMatches.title": "Tidak ada yang cocok",
"resources.skills.empty.description": "Instal skill dari GitHub atau tambahkan ke direktori sumber Anda.",
@@ -857,6 +862,7 @@
"update.check.unchecked": "Belum diperiksa",
"update.check.upToDate": "Sudah terbaru",
"update.check.updateAvailable": "Pembaruan tersedia",
"update.check.stale": "Dihapus di upstream",
"update.check.dirty": "Diubah secara lokal",
"update.done.subtitle": "Pembaruan selesai.",
"update.done.syncHint": "Target mendapatkan versi baru pada sinkronisasi berikutnya.",
@@ -879,11 +885,15 @@
"update.updating.purge": "Hapus Bersih",
"update.updating.purged": "Dihapus bersih",
"update.updating.purging": "Menghapus bersih...",
"update.missingRepos.title": "{count} repo terlacak hilang di disk",
"update.missingRepos.description": "Repositori terlacak ini dideklarasikan di metadata, tetapi direktori klonnya tidak ada. Rehydrate untuk mengkloningnya kembali dari sumbernya.",
"update.missingRepos.rehydrate": "Rehydrate",
"update.missingRepos.rehydrateSuccess": "{count} repo terlacak berhasil di-rehydrate",
"update.missingRepos.rehydratePartial": "{count} repo gagal di-rehydrate",
"update.missingEntries.title.one": "{count} entri di {file} tidak ada di disk",
"update.missingEntries.title.other": "{count} entri di {file} tidak ada di disk",
"update.missingEntries.description": "\"Pasang yang hilang\" memasangnya lagi dari sumber yang tercatat.",
"update.missingEntries.install": "Pasang yang hilang",
"update.stale.title": "Dihapus di upstream · {count}",
"update.stale.pruneAll": "Hapus semua",
"update.stale.note": "Item ini sudah dihapus dari repo sumbernya. Hapus memindahkannya ke Sampah, dan bisa dipulihkan selama 7 hari.",
"update.stale.pruned.one": "{count} skill dihapus. Pulihkan dari Sampah dalam 7 hari.",
"update.stale.pruned.other": "{count} skill dihapus. Pulihkan dari Sampah dalam 7 hari.",
"updateDialog.copyCommand": "Salin perintah",
"updateDialog.needsSudo": "Pembaruan memerlukan kata sandi Anda. Jalankan skillshare upgrade di terminal.",
"updateDialog.newVersion": "Versi baru tersedia",
@@ -1073,7 +1083,6 @@
"install.url.selected": "{count} dipilih",
"install.url.filterSkills": "Filter skill",
"install.url.filterAgents": "Filter agent",
"install.url.more": "{count} lagi",
"install.url.track": "Lacak repo ini",
"install.url.trackHint": "Menyimpan clone git agar Update bisa menarik versi baru. Tanpa ini Anda hanya mendapat salinan sekali pakai.",
"install.url.advanced": "Lanjutan",
@@ -1104,6 +1113,19 @@
"install.title.skills": "Instal skill",
"install.title.agents": "Instal agent",
"install.audited": "Setiap skill diaudit sebelum diinstal.",
"install.fromConfig.title.one": "{count} entri di {file} belum terpasang",
"install.fromConfig.title.other": "{count} entri di {file} belum terpasang",
"install.fromConfig.hint": "{items}. Sama seperti menjalankan skillshare install.",
"install.fromConfig.installAll": "Pasang semua",
"install.fromConfig.installing": "Memasang dari {file}…",
"install.fromConfig.installed": "Terpasang: {items}",
"install.fromConfig.failed": "{count} gagal",
"install.fromConfig.failedHint": "Periksa sumber dan akses Anda, lalu coba lagi.",
"install.fromConfig.syncHint": "Jalankan sync untuk menautkannya ke target.",
"install.fromConfig.repos.one": "{count} repo terlacak",
"install.fromConfig.repos.other": "{count} repo terlacak",
"install.fromConfig.skills.one": "{count} skill",
"install.fromConfig.skills.other": "{count} skill",
"install.findings": "{count} temuan",
"install.warnings.title": "Terinstal dengan peringatan",
"install.warnings.message": "Instalasi selesai, tetapi audit melaporkan temuan berikut.",
@@ -1777,6 +1799,22 @@
"sync.run.one": "Sinkronkan {count} perubahan",
"sync.run.other": "Sinkronkan {count} perubahan",
"sync.run.none": "Sinkronkan",
"sync.discard": "Buang semua",
"sync.pending.one": "{count} perubahan",
"sync.pending.other": "{count} perubahan",
"sync.view.change": "Per perubahan",
"sync.view.target": "Per target",
"sync.sum.add": "{count} baru",
"sync.sum.update": "{count} diperbarui",
"sync.sum.remove": "{count} dihapus",
"sync.sum.kept": "{count} dipertahankan",
"sync.set.targets.one": "{count} target",
"sync.set.targets.other": "{count} target",
"sync.set.add": "Tambah {count} {noun}",
"sync.set.update": "Perbarui {count} {noun}",
"sync.set.remove": "Hapus {count} {noun}",
"sync.set.kept": "Pertahankan {count} {noun}",
"sync.set.targetList": "Target · {count}",
"sync.include": "Sertakan",
"sync.changes.one": "{count} perubahan",
"sync.changes.other": "{count} perubahan",
+44 -6
View File
@@ -667,6 +667,11 @@
"resources.folder.noEditableSkills": "{folder}/ のスキルは変更されませんでした — 無効なスキルはスキップされます",
"resources.folder.skillsUpdated": "{folder}/ の {count} 件のスキルが {target} で利用可能になりました",
"resources.newSkill": "新しいスキル",
"resources.moreWays": "その他の追加方法",
"resources.add.install": "URL または Hub からインストール",
"resources.add.installHint": "インストール画面を開く",
"resources.add.newHint": "空白またはテンプレートから作成",
"resources.add.linkHint": "ローカルフォルダをソースに取り込む",
"resources.noMatches.description": "別の検索語句またはフィルターをお試しください。",
"resources.noMatches.title": "一致なし",
"resources.skills.empty.description": "GitHub からスキルをインストールするか、ソースディレクトリに追加してください。",
@@ -857,6 +862,7 @@
"update.check.unchecked": "未確認",
"update.check.upToDate": "最新",
"update.check.updateAvailable": "更新あり",
"update.check.stale": "上流で削除",
"update.check.dirty": "ローカルで変更あり",
"update.done.subtitle": "更新が完了しました。",
"update.done.syncHint": "ターゲットには次回の同期で新しいバージョンが反映されます。",
@@ -879,11 +885,15 @@
"update.updating.purge": "削除",
"update.updating.purged": "削除済み",
"update.updating.purging": "削除中...",
"update.missingRepos.title": "{count} 件の tracked リポジトリがディスク上に見つかりません",
"update.missingRepos.description": "これらの tracked リポジトリはメタデータに宣言されていますが、clone ディレクトリが存在しません。Rehydrate でソースから再度 clone します。",
"update.missingRepos.rehydrate": "Rehydrate",
"update.missingRepos.rehydrateSuccess": "{count} 件の tracked リポジトリを rehydrate しました",
"update.missingRepos.rehydratePartial": "{count} 件のリポジトリの rehydrate に失敗しました",
"update.missingEntries.title.one": "{file} の {count} 件の項目がディスク上にありません",
"update.missingEntries.title.other": "{file} の {count} 件の項目がディスク上にありません",
"update.missingEntries.description": "「不足分をインストール」は記録されたソースから再インストールします。",
"update.missingEntries.install": "不足分をインストール",
"update.stale.title": "上流で削除 · {count}",
"update.stale.pruneAll": "すべて削除",
"update.stale.note": "ソースリポジトリから削除された項目です。削除するとゴミ箱に移動し、7 日間は復元できます。",
"update.stale.pruned.one": "{count} 件の skill を削除しました。7 日以内ならゴミ箱から復元できます。",
"update.stale.pruned.other": "{count} 件の skill を削除しました。7 日以内ならゴミ箱から復元できます。",
"updateDialog.copyCommand": "コマンドをコピー",
"updateDialog.needsSudo": "更新にはパスワードが必要です。ターミナルで skillshare upgrade を実行してください。",
"updateDialog.newVersion": "新しいバージョンが利用可能です",
@@ -1073,7 +1083,6 @@
"install.url.selected": "{count} 件選択中",
"install.url.filterSkills": "スキルを絞り込み",
"install.url.filterAgents": "エージェントを絞り込み",
"install.url.more": "ほか {count} 件",
"install.url.track": "このリポジトリを追跡",
"install.url.trackHint": "git clone を保持し、更新で新しいバージョンを取得できるようにします。オフにすると一度きりのコピーになります。",
"install.url.advanced": "詳細設定",
@@ -1104,6 +1113,19 @@
"install.title.skills": "スキルをインストール",
"install.title.agents": "エージェントをインストール",
"install.audited": "スキルはインストール前に必ず監査されます。",
"install.fromConfig.title.one": "{file} の {count} 件の項目が未インストールです",
"install.fromConfig.title.other": "{file} の {count} 件の項目が未インストールです",
"install.fromConfig.hint": "{items}。skillshare install の実行と同じです。",
"install.fromConfig.installAll": "すべてインストール",
"install.fromConfig.installing": "{file} からインストール中…",
"install.fromConfig.installed": "{items} をインストールしました",
"install.fromConfig.failed": "{count} 件失敗",
"install.fromConfig.failedHint": "ソースとアクセス権を確認して再試行してください。",
"install.fromConfig.syncHint": "sync を実行してターゲットにリンクしてください。",
"install.fromConfig.repos.one": "{count} 件の tracked リポジトリ",
"install.fromConfig.repos.other": "{count} 件の tracked リポジトリ",
"install.fromConfig.skills.one": "{count} 件の skill",
"install.fromConfig.skills.other": "{count} 件の skill",
"install.findings": "{count} 件の検出",
"install.warnings.title": "警告付きでインストールしました",
"install.warnings.message": "インストールは完了しましたが、監査で次の項目が検出されました。",
@@ -1777,6 +1799,22 @@
"sync.run.one": "{count} 件の変更を同期",
"sync.run.other": "{count} 件の変更を同期",
"sync.run.none": "同期",
"sync.discard": "すべて破棄",
"sync.pending.one": "{count} 件の変更",
"sync.pending.other": "{count} 件の変更",
"sync.view.change": "変更ごと",
"sync.view.target": "ターゲットごと",
"sync.sum.add": "追加 {count}",
"sync.sum.update": "更新 {count}",
"sync.sum.remove": "削除 {count}",
"sync.sum.kept": "保持 {count}",
"sync.set.targets.one": "{count} 個のターゲット",
"sync.set.targets.other": "{count} 個のターゲット",
"sync.set.add": "{noun} を {count} 個追加",
"sync.set.update": "{noun} を {count} 個更新",
"sync.set.remove": "{noun} を {count} 個削除",
"sync.set.kept": "{noun} を {count} 個保持",
"sync.set.targetList": "ターゲット · {count}",
"sync.include": "対象",
"sync.changes.one": "{count} 件の変更",
"sync.changes.other": "{count} 件の変更",
+44 -6
View File
@@ -667,6 +667,11 @@
"resources.folder.noEditableSkills": "{folder}/의 Skill이 변경되지 않았습니다 — 비활성화된 Skill은 건너뜁니다",
"resources.folder.skillsUpdated": "{folder}/의 {count}개 skill(s)이 이제 {target}에서 사용 가능합니다",
"resources.newSkill": "새 Skill",
"resources.moreWays": "다른 추가 방법",
"resources.add.install": "URL 또는 Hub에서 설치",
"resources.add.installHint": "설치 창 열기",
"resources.add.newHint": "빈 상태나 템플릿에서 만들기",
"resources.add.linkHint": "로컬 폴더를 소스로 연결",
"resources.noMatches.description": "다른 검색어 또는 필터를 사용해보세요.",
"resources.noMatches.title": "일치 항목 없음",
"resources.skills.empty.description": "GitHub에서 skills를 설치하거나 소스 디렉토리에 추가하세요.",
@@ -857,6 +862,7 @@
"update.check.unchecked": "미확인",
"update.check.upToDate": "최신 상태",
"update.check.updateAvailable": "업데이트 가능",
"update.check.stale": "업스트림에서 삭제됨",
"update.check.dirty": "로컬에서 수정됨",
"update.done.subtitle": "업데이트 완료.",
"update.done.syncHint": "대상에는 다음 동기화 때 새 버전이 반영됩니다.",
@@ -879,11 +885,15 @@
"update.updating.purge": "제거",
"update.updating.purged": "제거됨",
"update.updating.purging": "제거 중...",
"update.missingRepos.title": "{count}개의 tracked 저장소가 디스크에 없습니다",
"update.missingRepos.description": "이 tracked 저장소들은 메타데이터에 선언되어 있지만 clone 디렉터리가 없습니다. Rehydrate하면 소스에서 다시 clone합니다.",
"update.missingRepos.rehydrate": "Rehydrate",
"update.missingRepos.rehydrateSuccess": "{count}개의 tracked 저장소를 rehydrate했습니다",
"update.missingRepos.rehydratePartial": "{count}개의 저장소 rehydrate에 실패했습니다",
"update.missingEntries.title.one": "{file}의 항목 {count}개가 디스크에 없습니다",
"update.missingEntries.title.other": "{file}의 항목 {count}개가 디스크에 없습니다",
"update.missingEntries.description": "'누락 항목 설치'는 기록된 소스에서 다시 설치합니다.",
"update.missingEntries.install": "누락 항목 설치",
"update.stale.title": "업스트림에서 삭제됨 · {count}",
"update.stale.pruneAll": "모두 정리",
"update.stale.note": "소스 저장소에서 제거된 항목입니다. 정리하면 휴지통으로 이동하며 7일 동안 복원할 수 있습니다.",
"update.stale.pruned.one": "skill {count}개를 정리했습니다. 7일 안에 휴지통에서 복원할 수 있습니다.",
"update.stale.pruned.other": "skill {count}개를 정리했습니다. 7일 안에 휴지통에서 복원할 수 있습니다.",
"updateDialog.copyCommand": "명령 복사",
"updateDialog.needsSudo": "업데이트하려면 비밀번호가 필요합니다. 터미널에서 skillshare upgrade 를 실행하세요.",
"updateDialog.newVersion": "새 버전 사용 가능",
@@ -1073,7 +1083,6 @@
"install.url.selected": "{count}개 선택됨",
"install.url.filterSkills": "skill 필터",
"install.url.filterAgents": "agent 필터",
"install.url.more": "{count}개 더",
"install.url.track": "이 저장소 추적",
"install.url.trackHint": "git clone을 유지해 업데이트로 새 버전을 가져올 수 있게 합니다. 끄면 일회성 복사본이 됩니다.",
"install.url.advanced": "고급",
@@ -1104,6 +1113,19 @@
"install.title.skills": "skill 설치",
"install.title.agents": "agent 설치",
"install.audited": "모든 skill은 설치 전에 감사합니다.",
"install.fromConfig.title.one": "{file}의 항목 {count}개가 설치되지 않았습니다",
"install.fromConfig.title.other": "{file}의 항목 {count}개가 설치되지 않았습니다",
"install.fromConfig.hint": "{items}. skillshare install 실행과 같습니다.",
"install.fromConfig.installAll": "모두 설치",
"install.fromConfig.installing": "{file}에서 설치 중…",
"install.fromConfig.installed": "{items} 설치됨",
"install.fromConfig.failed": "{count}개 실패",
"install.fromConfig.failedHint": "소스와 접근 권한을 확인한 뒤 다시 시도하세요.",
"install.fromConfig.syncHint": "sync를 실행해 대상에 연결하세요.",
"install.fromConfig.repos.one": "tracked 저장소 {count}개",
"install.fromConfig.repos.other": "tracked 저장소 {count}개",
"install.fromConfig.skills.one": "skill {count}개",
"install.fromConfig.skills.other": "skill {count}개",
"install.findings": "발견 항목 {count}개",
"install.warnings.title": "경고와 함께 설치됨",
"install.warnings.message": "설치는 끝났지만 감사에서 다음 항목이 보고되었습니다.",
@@ -1777,6 +1799,22 @@
"sync.run.one": "변경 {count}개 동기화",
"sync.run.other": "변경 {count}개 동기화",
"sync.run.none": "동기화",
"sync.discard": "모두 버리기",
"sync.pending.one": "변경 {count}개",
"sync.pending.other": "변경 {count}개",
"sync.view.change": "변경별",
"sync.view.target": "대상별",
"sync.sum.add": "추가 {count}",
"sync.sum.update": "업데이트 {count}",
"sync.sum.remove": "제거 {count}",
"sync.sum.kept": "유지 {count}",
"sync.set.targets.one": "대상 {count}개",
"sync.set.targets.other": "대상 {count}개",
"sync.set.add": "{noun} {count}개 추가",
"sync.set.update": "{noun} {count}개 업데이트",
"sync.set.remove": "{noun} {count}개 제거",
"sync.set.kept": "{noun} {count}개 유지",
"sync.set.targetList": "대상 · {count}",
"sync.include": "포함",
"sync.changes.one": "변경 {count}개",
"sync.changes.other": "변경 {count}개",
+44 -6
View File
@@ -667,6 +667,11 @@
"resources.folder.noEditableSkills": "Nenhum skill em {folder}/ foi alterado — skills desativados são ignorados",
"resources.folder.skillsUpdated": "{count} skill(s) em {folder}/ agora disponível(eis) em {target}",
"resources.newSkill": "Nova Skill",
"resources.moreWays": "Outras formas de adicionar",
"resources.add.install": "Instalar de URL ou Hub",
"resources.add.installHint": "Abre a janela de instalação",
"resources.add.newHint": "Começar em branco ou de um modelo",
"resources.add.linkHint": "Trazer uma pasta local para a origem",
"resources.noMatches.description": "Tente outro termo de busca ou filtro.",
"resources.noMatches.title": "Sem correspondências",
"resources.skills.empty.description": "Instale skills do GitHub ou adicione-as ao seu diretório fonte.",
@@ -857,6 +862,7 @@
"update.check.unchecked": "Não verificado",
"update.check.upToDate": "Atualizado",
"update.check.updateAvailable": "Atualização disponível",
"update.check.stale": "Excluído na origem",
"update.check.dirty": "Modificado localmente",
"update.done.subtitle": "Atualização concluída.",
"update.done.syncHint": "Os destinos recebem as novas versões na próxima sincronização.",
@@ -879,11 +885,15 @@
"update.updating.purge": "Limpar",
"update.updating.purged": "Limpo",
"update.updating.purging": "Limpando...",
"update.missingRepos.title": "{count} repositório(s) rastreado(s) ausente(s) no disco",
"update.missingRepos.description": "Esses repositórios rastreados estão declarados nos metadados, mas seus diretórios de clonagem estão ausentes. Reidrate para cloná-los novamente a partir das origens.",
"update.missingRepos.rehydrate": "Reidratar",
"update.missingRepos.rehydrateSuccess": "{count} repositório(s) rastreado(s) reidratado(s)",
"update.missingRepos.rehydratePartial": "Falha ao reidratar {count} repositório(s)",
"update.missingEntries.title.one": "{count} entrada de {file} está ausente no disco",
"update.missingEntries.title.other": "{count} entradas de {file} estão ausentes no disco",
"update.missingEntries.description": "\"Instalar ausentes\" os reinstala a partir das fontes registradas.",
"update.missingEntries.install": "Instalar ausentes",
"update.stale.title": "Excluído na origem · {count}",
"update.stale.pruneAll": "Remover tudo",
"update.stale.note": "Foram removidos do repositório de origem. Remover os move para a lixeira, onde podem ser restaurados por 7 dias.",
"update.stale.pruned.one": "{count} skill removida. Restaure da lixeira em até 7 dias.",
"update.stale.pruned.other": "{count} skills removidas. Restaure da lixeira em até 7 dias.",
"updateDialog.copyCommand": "Copiar comando",
"updateDialog.needsSudo": "A atualização precisa da sua senha. Execute skillshare upgrade em um terminal.",
"updateDialog.newVersion": "Nova versão disponível",
@@ -1073,7 +1083,6 @@
"install.url.selected": "{count} selecionada(s)",
"install.url.filterSkills": "Filtrar skills",
"install.url.filterAgents": "Filtrar agents",
"install.url.more": "mais {count}",
"install.url.track": "Acompanhar este repo",
"install.url.trackHint": "Mantém um clone git para que Atualizar possa trazer novas versões. Sem isso, você recebe uma cópia única.",
"install.url.advanced": "Avançado",
@@ -1104,6 +1113,19 @@
"install.title.skills": "Instalar skills",
"install.title.agents": "Instalar agents",
"install.audited": "Cada skill é auditada antes de ser instalada.",
"install.fromConfig.title.one": "{count} entrada de {file} não está instalada",
"install.fromConfig.title.other": "{count} entradas de {file} não estão instaladas",
"install.fromConfig.hint": "{items}. O mesmo que executar skillshare install.",
"install.fromConfig.installAll": "Instalar tudo",
"install.fromConfig.installing": "Instalando a partir de {file}…",
"install.fromConfig.installed": "Instalado: {items}",
"install.fromConfig.failed": "{count} com falha",
"install.fromConfig.failedHint": "Verifique as fontes e seu acesso, depois tente novamente.",
"install.fromConfig.syncHint": "Execute sync para vinculá-los aos seus destinos.",
"install.fromConfig.repos.one": "{count} repositório rastreado",
"install.fromConfig.repos.other": "{count} repositórios rastreados",
"install.fromConfig.skills.one": "{count} skill",
"install.fromConfig.skills.other": "{count} skills",
"install.findings": "{count} achados",
"install.warnings.title": "Instalado com avisos",
"install.warnings.message": "A instalação terminou, mas a auditoria relatou estes achados.",
@@ -1777,6 +1799,22 @@
"sync.run.one": "Sincronizar {count} alteração",
"sync.run.other": "Sincronizar {count} alterações",
"sync.run.none": "Sincronizar",
"sync.discard": "Descartar tudo",
"sync.pending.one": "{count} alteração",
"sync.pending.other": "{count} alterações",
"sync.view.change": "Por alteração",
"sync.view.target": "Por destino",
"sync.sum.add": "{count} novos",
"sync.sum.update": "{count} atualizados",
"sync.sum.remove": "{count} removidos",
"sync.sum.kept": "{count} mantidos",
"sync.set.targets.one": "{count} destino",
"sync.set.targets.other": "{count} destinos",
"sync.set.add": "Adicionar {count} {noun}",
"sync.set.update": "Atualizar {count} {noun}",
"sync.set.remove": "Remover {count} {noun}",
"sync.set.kept": "Manter {count} {noun}",
"sync.set.targetList": "Destinos · {count}",
"sync.include": "Incluir",
"sync.changes.one": "{count} alteração",
"sync.changes.other": "{count} alterações",
+44 -6
View File
@@ -667,6 +667,11 @@
"resources.folder.noEditableSkills": "{folder}/ 中没有 skill 被更改 — 已禁用的 skill 会被跳过",
"resources.folder.skillsUpdated": "{folder}/ 中的 {count} 个 skill 现已在 {target} 中可用",
"resources.newSkill": "新建 Skill",
"resources.moreWays": "更多添加方式",
"resources.add.install": "从 URL 或 Hub 安装",
"resources.add.installHint": "打开安装窗口",
"resources.add.newHint": "从空白或模板创建",
"resources.add.linkHint": "把本机文件夹接入来源",
"resources.noMatches.description": "试试其他搜索词或筛选条件。",
"resources.noMatches.title": "无匹配结果",
"resources.skills.empty.description": "从 GitHub 安装 skill,或将其添加到源目录。",
@@ -857,6 +862,7 @@
"update.check.unchecked": "未检查",
"update.check.upToDate": "已是最新",
"update.check.updateAvailable": "有可用更新",
"update.check.stale": "上游已删除",
"update.check.dirty": "本地有修改",
"update.done.subtitle": "更新完成。",
"update.done.syncHint": "目标会在下次同步时获得新版本。",
@@ -879,11 +885,15 @@
"update.updating.purge": "清除",
"update.updating.purged": "已清除",
"update.updating.purging": "清除中...",
"update.missingRepos.title": "{count} 个 tracked repo 在磁盘上缺失",
"update.missingRepos.description": "这些 tracked 仓库已在 metadata 中声明,但 clone 目录不存在。Rehydrate 会从来源重新 clone。",
"update.missingRepos.rehydrate": "Rehydrate",
"update.missingRepos.rehydrateSuccess": "已 rehydrate {count} 个 tracked repo",
"update.missingRepos.rehydratePartial": "{count} 个 repo rehydrate 失败",
"update.missingEntries.title.one": "{file} 中有 {count} 个条目不在磁盘上",
"update.missingEntries.title.other": "{file} 中有 {count} 个条目不在磁盘上",
"update.missingEntries.description": "“安装缺失项”会从记录的来源重新安装。",
"update.missingEntries.install": "安装缺失项",
"update.stale.title": "上游已删除 · {count}",
"update.stale.pruneAll": "全部清除",
"update.stale.note": "这些条目已从来源 repo 删除。清除会移到回收站,7 天内可以恢复。",
"update.stale.pruned.one": "已清除 {count} 个 skill,7 天内可从回收站恢复。",
"update.stale.pruned.other": "已清除 {count} 个 skills,7 天内可从回收站恢复。",
"updateDialog.copyCommand": "复制命令",
"updateDialog.needsSudo": "更新需要输入密码,请在终端执行 skillshare upgrade。",
"updateDialog.newVersion": "有新版本可用",
@@ -1073,7 +1083,6 @@
"install.url.selected": "已选 {count} 个",
"install.url.filterSkills": "筛选 skill",
"install.url.filterAgents": "筛选 agent",
"install.url.more": "还有 {count} 个",
"install.url.track": "追踪这个 repo",
"install.url.trackHint": "保留 git clone,之后可以用 Update 拉取新版本。不开启则只是一次性复制。",
"install.url.advanced": "高级",
@@ -1104,6 +1113,19 @@
"install.title.skills": "安装 skill",
"install.title.agents": "安装 agent",
"install.audited": "每个 skill 安装前都会先进行审计。",
"install.fromConfig.title.one": "{file} 中有 {count} 个条目尚未安装",
"install.fromConfig.title.other": "{file} 中有 {count} 个条目尚未安装",
"install.fromConfig.hint": "{items}。等同运行 skillshare install。",
"install.fromConfig.installAll": "全部安装",
"install.fromConfig.installing": "正在从 {file} 安装…",
"install.fromConfig.installed": "已安装 {items}",
"install.fromConfig.failed": "{count} 个失败",
"install.fromConfig.failedHint": "请检查来源和访问权限后重试。",
"install.fromConfig.syncHint": "运行 sync 将它们链接到目标。",
"install.fromConfig.repos.one": "{count} 个 tracked repo",
"install.fromConfig.repos.other": "{count} 个 tracked repo",
"install.fromConfig.skills.one": "{count} 个 skill",
"install.fromConfig.skills.other": "{count} 个 skills",
"install.findings": "{count} 项发现",
"install.warnings.title": "已安装,但有警告",
"install.warnings.message": "安装已完成,但审计报告了以下问题。",
@@ -1777,6 +1799,22 @@
"sync.run.one": "同步 {count} 项变更",
"sync.run.other": "同步 {count} 项变更",
"sync.run.none": "同步",
"sync.discard": "全部舍弃",
"sync.pending.one": "{count} 项变更",
"sync.pending.other": "{count} 项变更",
"sync.view.change": "按变更",
"sync.view.target": "按目标",
"sync.sum.add": "新增 {count}",
"sync.sum.update": "更新 {count}",
"sync.sum.remove": "移除 {count}",
"sync.sum.kept": "保留 {count}",
"sync.set.targets.one": "{count} 个目标",
"sync.set.targets.other": "{count} 个目标",
"sync.set.add": "新增 {count} 个 {noun}",
"sync.set.update": "更新 {count} 个 {noun}",
"sync.set.remove": "移除 {count} 个 {noun}",
"sync.set.kept": "保留 {count} 个 {noun}",
"sync.set.targetList": "目标 · {count}",
"sync.include": "包含",
"sync.changes.one": "{count} 项变更",
"sync.changes.other": "{count} 项变更",
+44 -6
View File
@@ -667,6 +667,11 @@
"resources.folder.noEditableSkills": "{folder}/ 中沒有 skill 被變更 — 已停用的 skill 會被略過",
"resources.folder.skillsUpdated": "{folder}/ 中 {count} 個 skill 現在可在 {target} 中使用",
"resources.newSkill": "新增 Skill",
"resources.moreWays": "更多新增方式",
"resources.add.install": "從 URL 或 Hub 安裝",
"resources.add.installHint": "開啟安裝視窗",
"resources.add.newHint": "從空白或範本建立",
"resources.add.linkHint": "把本機資料夾接進來源",
"resources.noMatches.description": "試試不同的搜尋關鍵字或篩選條件。",
"resources.noMatches.title": "無符合結果",
"resources.skills.empty.description": "從 GitHub 安裝 skills 或將它們加入你的來源目錄。",
@@ -857,6 +862,7 @@
"update.check.unchecked": "未檢查",
"update.check.upToDate": "已是最新版本",
"update.check.updateAvailable": "有可用更新",
"update.check.stale": "上游已刪除",
"update.check.dirty": "本機有修改",
"update.done.subtitle": "更新完成。",
"update.done.syncHint": "目標會在下次同步時取得新版本。",
@@ -879,11 +885,15 @@
"update.updating.purge": "清除",
"update.updating.purged": "已清除",
"update.updating.purging": "清除中…",
"update.missingRepos.title": "{count} 個 tracked repo 在磁碟上遺失",
"update.missingRepos.description": "這些 tracked 儲存庫已在 metadata 中宣告,但 clone 目錄不存在。Rehydrate 會從來源重新 clone。",
"update.missingRepos.rehydrate": "Rehydrate",
"update.missingRepos.rehydrateSuccess": "已 rehydrate {count} 個 tracked repo",
"update.missingRepos.rehydratePartial": "{count} 個 repo rehydrate 失敗",
"update.missingEntries.title.one": "{file} 裡有 {count} 個項目不在磁碟上",
"update.missingEntries.title.other": "{file} 裡有 {count} 個項目不在磁碟上",
"update.missingEntries.description": "「安裝缺少的項目」會從記錄的來源重新安裝。",
"update.missingEntries.install": "安裝缺少的項目",
"update.stale.title": "上游已刪除 · {count}",
"update.stale.pruneAll": "全部清除",
"update.stale.note": "這些項目已從來源 repo 移除。清除會移到垃圾桶,7 天內可以還原。",
"update.stale.pruned.one": "已清除 {count} 個 skill,7 天內可從垃圾桶還原。",
"update.stale.pruned.other": "已清除 {count} 個 skills,7 天內可從垃圾桶還原。",
"updateDialog.copyCommand": "複製指令",
"updateDialog.needsSudo": "更新需要輸入密碼,請在終端機執行 skillshare upgrade。",
"updateDialog.newVersion": "有新版本可用",
@@ -1073,7 +1083,6 @@
"install.url.selected": "已選 {count} 個",
"install.url.filterSkills": "篩選 skills",
"install.url.filterAgents": "篩選 agents",
"install.url.more": "還有 {count} 個",
"install.url.track": "追蹤這個 repo",
"install.url.trackHint": "保留 git clone,之後可以用 Update 拉新版本。不開的話只是一次性複製。",
"install.url.advanced": "進階",
@@ -1104,6 +1113,19 @@
"install.title.skills": "安裝 skills",
"install.title.agents": "安裝 agents",
"install.audited": "每個 skill 安裝前都會先經過審計。",
"install.fromConfig.title.one": "{file} 裡有 {count} 個項目尚未安裝",
"install.fromConfig.title.other": "{file} 裡有 {count} 個項目尚未安裝",
"install.fromConfig.hint": "{items}。等同執行 skillshare install。",
"install.fromConfig.installAll": "全部安裝",
"install.fromConfig.installing": "正在從 {file} 安裝…",
"install.fromConfig.installed": "已安裝 {items}",
"install.fromConfig.failed": "{count} 個失敗",
"install.fromConfig.failedHint": "請確認來源與存取權限後重試。",
"install.fromConfig.syncHint": "執行 sync 把它們連結到目標。",
"install.fromConfig.repos.one": "{count} 個 tracked repo",
"install.fromConfig.repos.other": "{count} 個 tracked repo",
"install.fromConfig.skills.one": "{count} 個 skill",
"install.fromConfig.skills.other": "{count} 個 skills",
"install.findings": "{count} 項發現",
"install.warnings.title": "已安裝,但有警告",
"install.warnings.message": "安裝已完成,但審計回報了以下問題。",
@@ -1777,6 +1799,22 @@
"sync.run.one": "同步 {count} 項變更",
"sync.run.other": "同步 {count} 項變更",
"sync.run.none": "同步",
"sync.discard": "全部捨棄",
"sync.pending.one": "{count} 項變更",
"sync.pending.other": "{count} 項變更",
"sync.view.change": "依變更",
"sync.view.target": "依目標",
"sync.sum.add": "新增 {count}",
"sync.sum.update": "更新 {count}",
"sync.sum.remove": "移除 {count}",
"sync.sum.kept": "保留 {count}",
"sync.set.targets.one": "{count} 個目標",
"sync.set.targets.other": "{count} 個目標",
"sync.set.add": "新增 {count} 個 {noun}",
"sync.set.update": "更新 {count} 個 {noun}",
"sync.set.remove": "移除 {count} 個 {noun}",
"sync.set.kept": "保留 {count} 個 {noun}",
"sync.set.targetList": "目標 · {count}",
"sync.include": "包含",
"sync.changes.one": "{count} 項變更",
"sync.changes.other": "{count} 項變更",
+3 -3
View File
@@ -28,7 +28,7 @@ const cached = {
log: k.log('ops', 10),
logStats: k.logStats('ops'),
config: k.config,
missingRepos: k.missingTrackedRepos,
missingConfigEntries: k.missingConfigEntries,
syncMatrix: k.syncMatrix(),
syncMatrixClaude: k.syncMatrix('claude'),
extras: k.extras,
@@ -72,7 +72,7 @@ const stale: Record<QueryEvent, Label[] | { args: string[]; stale: Label[] }> =
skillEdited: { args: ['a'], stale: ['skill'] },
installDialogClosed: S,
reposChanged: [...S, 'overview', 'trash'],
skillsUninstalled: [...S, 'overview', 'trash', ...SM],
skillsUninstalled: [...S, 'overview', 'trash', ...SM, 'diff'],
trashChanged: ['trash', ...S, ...SM],
skillSyncChanged: [...S, ...SM],
skillsToggled: [...S, ...SM, 'overview'],
@@ -80,7 +80,7 @@ const stale: Record<QueryEvent, Label[] | { args: string[]; stale: Label[] }> =
sourceLinked: [...S, 'overview', 'config', 'diff', 'syncMatrix'],
sourceUnlinked: [...S, 'overview', 'config', 'diff', 'syncMatrix', 'trash'],
collected: { args: ['claude'], stale: [...S, 'overview', ...T, 'diff', 'syncMatrix', 'collectScanClaude'] },
missingReposChanged: ['missingRepos'],
configInstalled: ['missingConfigEntries', ...S, 'overview', ...SM, 'diff'],
targetsChanged: TARGETS,
synced: [...T, 'overview', 'diff'],
+2 -2
View File
@@ -20,7 +20,7 @@ const events = {
skillEdited: (name: string) => keys(k.skills.detail(name)),
installDialogClosed: () => keys(k.skills.all),
reposChanged: () => keys(k.overview, k.skills.all, k.trash),
skillsUninstalled: () => keys(k.skills.all, k.overview, k.trash, k.syncMatrixAll),
skillsUninstalled: () => keys(k.skills.all, k.overview, k.trash, k.syncMatrixAll, k.diff()),
trashChanged: () => keys(k.trash, k.skills.all, k.syncMatrixAll),
skillSyncChanged: () => keys(k.skills.all, k.syncMatrixAll),
skillsToggled: () => keys(k.skills.all, k.syncMatrixAll, k.overview),
@@ -28,7 +28,7 @@ const events = {
sourceLinked: () => keys(...sourceLinks),
sourceUnlinked: () => keys(...sourceLinks, k.trash),
collected: (target?: string) => keys(k.skills.all, k.overview, k.targets.all, k.diff(), k.syncMatrix(), k.collectScan(target)),
missingReposChanged: () => keys(k.missingTrackedRepos),
configInstalled: () => keys(k.missingConfigEntries, k.skills.all, k.overview, k.syncMatrixAll, k.diff()),
// Targets, projects and sync
targetsChanged: () => keys(...targets),
+2 -2
View File
@@ -54,7 +54,7 @@ export const queryKeys = {
config: ['config'] as const,
check: ['check'] as const,
missingTrackedRepos: ['missing-tracked-repos'] as const,
missingConfigEntries: ['missing-config-entries'] as const,
// Last update check, kept client-side (see UpdatePage) and shared by the Updates tab and its count.
updateCheck: ['update-check'] as const,
syncMatrix: (target?: string) => ['sync-matrix', target ?? '__all'] as const,
@@ -148,7 +148,7 @@ export const staleTimes = {
audit: 5 * 60 * 1000, // 5min — full audit scan, expensive
auditSkill: 5 * 60 * 1000, // 5min — per-skill audit, rarely changes
check: 60 * 1000, // 1min
missingTrackedRepos: 60 * 1000, // 1min
missingConfigEntries: 60 * 1000, // 1min
syncMatrix: 30 * 1000, // 30s — changes after filter edits
extras: 30 * 1000, // 30s — fast-changing like diff
analyze: 2 * 60 * 1000, // 2min — walks every skill file
+6
View File
@@ -53,4 +53,10 @@ describe('limitGroups', () => {
expect(limitGroups(groups, 3).map((g) => g.items.map((s) => s.name))).toEqual([['a', 'b'], ['c']]);
});
it('does not charge collapsed groups against the limit', () => {
const groups = [{ key: 'x', items: [skill('a'), skill('b')] }, { key: 'y', items: [skill('c'), skill('d')] }];
expect(limitGroups(groups, 1, (g) => g.key === 'x').map((g) => g.items.map((s) => s.name))).toEqual([['a', 'b'], ['c']]);
});
});
+3 -1
View File
@@ -145,10 +145,12 @@ export function groupByFolder(items: Skill[], links: SourceLink[] = []): FolderG
}
/** Cut groups down to the first `limit` items, preserving standalone empty groups. */
export function limitGroups<G extends { items: Skill[] }>(groups: G[], limit: number): G[] {
export function limitGroups<G extends { items: Skill[] }>(groups: G[], limit: number, collapsed: (g: G) => boolean = () => false): G[] {
const out: G[] = [];
let left = limit;
for (const g of groups) {
// A collapsed group shows only its head, so its items cost nothing.
if (collapsed(g)) { out.push(g); continue; }
if (left <= 0 && g.items.length > 0) continue;
out.push({ ...g, items: g.items.slice(0, left) });
left -= g.items.length;
+3 -3
View File
@@ -34,7 +34,7 @@ import { SkillContextMenu, type ContextMenuItem } from '../components/TargetMenu
import { useToast } from '../components/Toast';
import { SkillEditor } from '../components/skill-editor';
import { UninstallDialog } from '../components/resources/UninstallDialog';
import { hasUpdate, updateUnits, useCheckStatuses } from './UpdatePage';
import { checkKey, hasUpdate, updateUnits, useCheckStatuses } from './UpdatePage';
import { useDiffQuery, useSkillsQuery } from '../hooks/useSharedQueries';
import { invalidate } from '../lib/queryEvents';
@@ -110,7 +110,7 @@ export default function ResourceDetailPage() {
const docName = isAgent ? resource.relPath.split('/').pop()! : 'SKILL.md';
const unit = updateUnits(allSkills.data?.resources ?? [resource], resource.kind, allSkills.data?.linked_repos)
.find((u) => u.items.some((i) => i.flatName === resource.flatName));
const check = statuses.get(resource.name) ?? { status: 'unchecked' as const };
const check = statuses.get(checkKey(resource)) ?? { status: 'unchecked' as const };
const updateAvailable = hasUpdate(check);
const audit = auditQuery.data?.result;
@@ -130,7 +130,7 @@ export default function ResourceDetailPage() {
// The check result belongs to the whole update unit, so a repo marks every skill in it
const markUpToDate = () => {
const names = unit?.items.map((i) => i.name) ?? [resource.name];
const names = (unit?.items ?? [resource]).map(checkKey);
const checkedAt = new Date().toISOString();
setStatuses((prev) => {
const next = new Map(prev);
+31 -6
View File
@@ -1,5 +1,5 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -189,6 +189,12 @@ describe('Skills tree view', () => {
});
});
/** Link folder sits in the menu beside Install. */
async function openLinkFolder() {
fireEvent.click(await screen.findByRole('button', { name: 'More ways to add' }));
fireEvent.mouseDown(await screen.findByRole('menuitem', { name: /^Link folder/ }));
}
describe('Link folder', () => {
beforeEach(() => {
localStorage.clear();
@@ -200,7 +206,7 @@ describe('Link folder', () => {
it('opens the dialog on the skills page', async () => {
mount();
fireEvent.click(await screen.findByRole('button', { name: 'Link folder' }));
await openLinkFolder();
expect(screen.getByRole('dialog', { name: 'Link folder' })).toBeInTheDocument();
expect(screen.getByLabelText('Folder path')).toBeInTheDocument();
expect(await screen.findByRole('checkbox', { name: /Enable follow_source_links/ })).not.toBeChecked();
@@ -208,7 +214,7 @@ describe('Link folder', () => {
it('posts the path, optional name and explicit enable flag and refreshes the list', async () => {
mount();
fireEvent.click(await screen.findByRole('button', { name: 'Link folder' }));
await openLinkFolder();
fireEvent.change(screen.getByLabelText('Folder path'), { target: { value: '/work/team' } });
fireEvent.change(screen.getByLabelText('Link name (optional)'), { target: { value: '_team' } });
fireEvent.click(await screen.findByRole('checkbox', { name: /Enable follow_source_links/ }));
@@ -223,7 +229,7 @@ describe('Link folder', () => {
const { ApiError } = await import('../api/client');
vi.mocked(api.createSourceLink).mockRejectedValue(new ApiError(400, 'target overlaps sync target /tools/skills'));
mount();
fireEvent.click(await screen.findByRole('button', { name: 'Link folder' }));
await openLinkFolder();
fireEvent.change(screen.getByLabelText('Folder path'), { target: { value: '/tools/skills' } });
await screen.findByRole('checkbox', { name: /Enable follow_source_links/ });
fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Link folder' }));
@@ -235,7 +241,7 @@ describe('Link folder', () => {
vi.mocked(api.getConfig).mockResolvedValue({ config: { FollowSourceLinks: true }, raw: '' });
vi.mocked(api.createSourceLink).mockResolvedValue({ path: '/source/_team', target: '/work/team', kind: 'symlink', warning: 'target is not a git checkout' });
mount();
fireEvent.click(await screen.findByRole('button', { name: 'Link folder' }));
await openLinkFolder();
fireEvent.change(screen.getByLabelText('Folder path'), { target: { value: '/work/team' } });
const submit = within(screen.getByRole('dialog')).getByRole('button', { name: 'Link folder' });
await waitFor(() => expect(submit).not.toBeDisabled());
@@ -348,8 +354,8 @@ describe('Unlink folder', () => {
expect(api.removeSourceLink).not.toHaveBeenCalled();
await user.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Cancel' }));
const plain = [...document.querySelectorAll<HTMLElement>('.ss-gh')].find((g) => g.querySelector('b')?.textContent === 'repo')!;
expect(within(plain).getByRole('button', { name: 'Update repo' })).toBeInTheDocument();
await user.click(within(plain).getByRole('button', { name: 'Repo actions' }));
expect(screen.getByRole('menuitem', { name: 'Update repo' })).toBeInTheDocument();
expect(screen.getByRole('menuitem', { name: 'Uninstall repo' })).toBeInTheDocument();
});
@@ -541,6 +547,25 @@ describe('Skills list folders', () => {
expect((await screen.findAllByRole('combobox')).map((el) => el.textContent)).toEqual(['Source', 'Status', 'Folder']);
});
it('collapses every list group and remembers it', async () => {
mount();
await screen.findAllByText('hooks');
fireEvent.click(screen.getByRole('button', { name: 'Collapse all' }));
expect(names()).toEqual([]);
cleanup();
mount();
await screen.findByRole('button', { name: 'Expand all' });
expect(names()).toEqual([]);
});
it('keeps the chosen filters after the page remounts', async () => {
mount();
await choose('Folder', 'frontend/react (2)');
cleanup();
mount();
await waitFor(() => expect(names()).toEqual(['hooks', 'router']));
});
it('clears a filter from its chip', async () => {
mount();
await choose('Folder', 'frontend/react (2)');
+146 -44
View File
@@ -1,8 +1,10 @@
import { useMemo, useState, type MouseEvent as ReactMouseEvent } from 'react';
import { useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
Bot,
ChevronDown,
ChevronRight,
ChevronsDownUp,
ChevronsUpDown,
CircleCheck,
@@ -18,6 +20,7 @@ import {
LayoutGrid,
List,
Link2,
Loader2,
Plus,
Power,
Puzzle,
@@ -33,6 +36,7 @@ import { api } from '../api/client';
import type { Skill, SourceLink } from '../api/client';
import { queryKeys, staleTimes } from '../lib/queryKeys';
import { globToRegex } from '../lib/glob';
import { parseRemoteURL } from '../lib/parseRemoteURL';
import { folderOf, formatTrackedRepoName, resourceHref } from '../lib/resourceNames';
import {
byTargetOrProject, countLabel, groupByFolder, groupBySource, limitGroups, parentPath, projectOf, repoOf, sortSkills, sourceLinkOf, sourceName, splitTargets, syncedByTarget,
@@ -86,7 +90,8 @@ type MenuState =
| { mode: 'folder'; path: string; summary: TargetSummary; point: Point }
| { mode: 'repo'; repo: string; point: Point }
| { mode: 'skill'; skill: Skill; point: Point }
| { mode: 'bulk'; names: string[]; point: Point };
| { mode: 'bulk'; names: string[]; point: Point }
| { mode: 'add'; point: Point };
type SkillsData = { resources: Skill[] };
const EMPTY: Skill[] = [];
@@ -95,6 +100,10 @@ const STEP = 100;
const SOURCE_ICON = { tracked: GitBranch, github: Github, remote: Globe, local: Folder };
const VIEW_KEY = 'skillshare:skills-view';
const COLLAPSED_KEY = 'skillshare:folder-collapsed';
/** List-view group keys share the collapsed set with tree folder paths, apart by prefix. */
const groupKey = (key: string) => `group:${key}`;
/** A folder group's key, kept apart from source groups of the same name. */
const folderKey = (key: string) => `f:${key}`;
/** Enable/disable toasts replace each other, so quick on/off clicks never leave an outdated one on screen. */
const TOGGLE_TOAST = 'resource-toggle';
@@ -116,6 +125,26 @@ function loadCollapsed(): Set<string> {
return new Set();
}
interface Filters { source: SourceFilter; status: StatusFilter; target: string; folder: string | null }
const FILTER_DEFAULTS: Filters = { source: 'all', status: 'all', target: 'all', folder: null };
/** One JSON entry holds every page's filters: { skill: Filters, agent: Filters }. */
const FILTERS_KEY = 'skillshare:resource-filters';
function readFilters(): Partial<Record<Kind, Filters>> {
try {
return JSON.parse(localStorage.getItem(FILTERS_KEY) ?? '{}') ?? {};
} catch { /* corrupt or unavailable */ }
return {};
}
function loadFilters(kind: Kind): Filters {
return { ...FILTER_DEFAULTS, ...readFilters()[kind] };
}
function saveFilters(kind: Kind, filters: Filters) {
try { localStorage.setItem(FILTERS_KEY, JSON.stringify({ ...readFilters(), [kind]: filters })); } catch { /* storage unavailable */ }
}
function saveCollapsed(collapsed: Set<string>) {
try { localStorage.setItem(COLLAPSED_KEY, JSON.stringify([...collapsed])); } catch { /* storage unavailable */ }
}
@@ -173,10 +202,11 @@ function TargetStack({ names, reachable = [], max = 4 }: { names: string[]; reac
);
}
function menuPoint(e: ReactMouseEvent): Point {
/** Where a menu opens: at the pointer for a right-click, else under the button; `end` lines up its right edges. */
function menuPoint(e: ReactMouseEvent, align: 'start' | 'end' = 'start'): Point {
if (e.type === 'contextmenu') return { x: e.clientX, y: e.clientY };
const r = (e.currentTarget as HTMLElement).getBoundingClientRect();
return { x: r.left, y: r.bottom + 4 };
return { x: align === 'end' ? r.right : r.left, y: r.bottom + 4 };
}
/* -- Page ----------------------------------------- */
@@ -221,16 +251,32 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
}, { replace: true });
const [search, setSearch] = useState('');
const [source, setSource] = useState<SourceFilter>('all');
const [status, setStatus] = useState<StatusFilter>('all');
const [target, setTarget] = useState('all');
const [saved] = useState(() => loadFilters(kind));
const [source, setSource] = useState<SourceFilter>(saved.source);
const [status, setStatus] = useState<StatusFilter>(saved.status);
const [target, setTarget] = useState(saved.target);
// null = all folders; '' is the source root.
const [folder, setFolder] = useState<string | null>(null);
const [folder, setFolder] = useState<string | null>(saved.folder);
useEffect(() => saveFilters(kind, { source, status, target, folder }), [kind, source, status, target, folder]);
const [sort, setSort] = useState<SortType>('name-asc');
const [group, setGroup] = useState<GroupBy>(isAgent ? 'none' : 'source');
const [view, setView] = useState<ViewType>(loadView);
const [limit, setLimit] = useState(STEP);
const [collapsed, setCollapsed] = useState<Set<string>>(loadCollapsed);
// The toolbar sticks to the top; its height places the list header and group heads under it.
const [stuck, setStuck] = useState(false);
const sentinel = useRef<HTMLDivElement>(null);
const bar = useRef<HTMLDivElement>(null);
const [barHeight, setBarHeight] = useState(0);
useEffect(() => {
const el = sentinel.current, box = bar.current;
if (!el || !box || typeof IntersectionObserver === 'undefined' || typeof ResizeObserver === 'undefined') return;
const io = new IntersectionObserver(([e]) => setStuck(!e.isIntersecting));
const ro = new ResizeObserver(() => setBarHeight(box.offsetHeight));
io.observe(el);
ro.observe(box);
return () => { io.disconnect(); ro.disconnect(); };
}, [tab, isPending]);
const [selected, setSelected] = useState<Set<string>>(new Set());
// The tree view selects folders and skills by row id, apart from the list's checkboxes.
const [treeSel, setTreeSel] = useState<Set<string>>(new Set());
@@ -446,9 +492,10 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
try { localStorage.setItem(VIEW_KEY, v); } catch { /* storage unavailable */ }
};
const updateCollapsed = (next: Set<string>) => { setCollapsed(next); saveCollapsed(next); };
const toggleFolder = (path: string) => {
/** Collapses or opens a tree folder path or a list group key. */
const toggleCollapsed = (key: string) => {
const next = new Set(collapsed);
if (!next.delete(path)) next.add(path);
if (!next.delete(key)) next.add(key);
updateCollapsed(next);
};
@@ -492,19 +539,14 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
);
const repoActions = (repo: string) => (
<>
<Button variant="secondary" size="sm" loading={updating === repo} disabled={updating !== null} onClick={() => update(repo)}>
{t('resources.repo.update')}
</Button>
<button
type="button"
className="ss-ib"
aria-label={t('resources.repo.actions')}
onClick={(e) => openGroupMenu(e, repo)}
>
<Ellipsis size={16} />
</button>
</>
<button
type="button"
className="ss-ib"
aria-label={t('resources.repo.actions')}
onClick={(e) => openGroupMenu(e, repo)}
>
{updating === repo ? <Loader2 size={16} className="animate-spin" /> : <Ellipsis size={16} />}
</button>
);
const unlinkButton = (link: SourceLink) => (
@@ -518,14 +560,33 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
</Tooltip>
);
// Many repos share a basename such as "skills"; the owner/repo tells them apart.
const repoOrigin = (repo: string, items: Skill[]) => {
const origin = parseRemoteURL(items[0]?.repoUrl ?? items[0]?.source ?? '')?.ownerRepo;
return origin && origin !== formatTrackedRepoName(repo)
? <span className="min-w-0 truncate font-mono text-xs text-ink-3">{origin}</span>
: null;
};
const groupToggle = (key: string, label: string) => {
const open = !collapsed.has(groupKey(key));
return (
<button type="button" className="ss-ib !w-6 !h-6 -ml-1 shrink-0" aria-expanded={open} aria-label={label} onClick={() => toggleCollapsed(groupKey(key))}>
{open ? <ChevronDown size={15} /> : <ChevronRight size={15} />}
</button>
);
};
const groupHead = (g: Group, asLabel: boolean) => {
const Icon = g.link ? Link2 : SOURCE_ICON[g.source];
const meta = [g.link?.warning ?? countLabel(t, kind, g.items.length), g.repo && !g.link ? g.items[0].branch : ''];
return (
<div key={`g:${g.key}`} className={asLabel ? 'ss-gl' : 'ss-gh'} onContextMenu={g.link ? undefined : (e) => openGroupMenu(e, g.repo)}>
{!asLabel && groupToggle(g.key, g.link?.name ?? formatTrackedRepoName(g.repo ?? SOURCE_LABEL[g.source]))}
<Icon size={15} className="shrink-0 text-ink-2" />
{g.link ? <b className="font-mono">{g.link.name}</b> : g.repo ? <b className="font-mono">{formatTrackedRepoName(g.repo)}</b> : <b>{SOURCE_LABEL[g.source]}</b>}
{g.repo && !g.link && <span className="ss-tag">tracked</span>}
{g.repo && !g.link && repoOrigin(g.repo, g.items)}
{g.link && <span className="min-w-0 truncate font-mono text-xs text-ink-3" title={g.link.target}>{g.link.target}</span>}
<span className="shrink-0 text-ink-3">{meta.filter(Boolean).join(' · ')}</span>
<span className="flex-1" />
@@ -538,9 +599,11 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
const folderHead = (g: FolderGroup, asLabel: boolean) => (
<div key={`f:${g.key}`} className={asLabel ? 'ss-gl' : 'ss-gh'}>
{!asLabel && groupToggle(folderKey(g.key), g.link ? g.link.name : folderName(g.key))}
{g.link ? <Link2 size={15} className="shrink-0 text-ink-2" /> : <Folder size={15} className="shrink-0 text-ink-2" />}
<b className={g.key ? 'font-mono' : ''}>{g.link ? g.link.name : folderName(g.key)}</b>
{g.repo && !g.link && <span className="ss-tag">tracked</span>}
{g.repo && !g.link && repoOrigin(g.key, g.items)}
{g.link && <span className="min-w-0 truncate font-mono text-xs text-ink-3" title={g.link.target}>{g.link.target}</span>}
<span className="shrink-0 text-ink-3">{g.link?.warning ?? countLabel(t, kind, g.items.length)}</span>
{g.link && !isAgent && <><span className="flex-1" />{unlinkButton(g.link)}</>}
@@ -603,7 +666,10 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
/* -- Content -- */
const treeItemTotal = treeRows.filter((r) => r.type === 'item').length;
const total = view === 'tree' ? treeItemTotal : filtered.length;
// List view hides a collapsed group's rows, so they neither page nor count as shown.
const listGroups = view !== 'list' ? [] : group === 'source' ? groups : group === 'folder' ? folderGroups : [];
const groupHidden = (g: { key: string }) => collapsed.has(groupKey(group === 'folder' ? folderKey(g.key) : g.key));
const total = view === 'tree' ? treeItemTotal : filtered.length - listGroups.filter(groupHidden).reduce((n, g) => n + g.items.length, 0);
const shown = Math.min(limit, total);
let content: React.ReactNode;
@@ -661,7 +727,7 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
kind={kind}
label={t(isAgent ? 'layout.nav.agents' : 'layout.nav.skills')}
onSelect={selectNode}
onToggleFolder={toggleFolder}
onToggleFolder={toggleCollapsed}
onOpen={(s) => navigate(resourceHref(s))}
renderUnlink={unlinkButton}
onContextMenu={isAgent ? undefined : (e, row) => {
@@ -725,14 +791,15 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
</div>
);
let body: React.ReactNode;
const rows = (key: string, list: Skill[]) => (collapsed.has(groupKey(key)) ? [] : list.map((s) => itemRow(s)));
if (group === 'source') {
body = limitGroups(groups, limit).map((g) => [groupHead(g, false), ...g.items.map((s) => itemRow(s))]);
body = limitGroups(groups, limit, groupHidden).map((g) => [groupHead(g, false), ...rows(g.key, g.items)]);
} else if (group === 'folder') {
body = limitGroups(folderGroups, limit).map((g) => [folderHead(g, false), ...g.items.map((s) => itemRow(s))]);
body = limitGroups(folderGroups, limit, groupHidden).map((g) => [folderHead(g, false), ...rows(folderKey(g.key), g.items)]);
} else {
body = <>{groups.filter((g) => g.link && g.items.length === 0).map((g) => groupHead(g, false))}{filtered.slice(0, limit).map((s) => itemRow(s))}</>;
}
content = <div className="ss-list">{header}{body}</div>;
content = <div className="ss-list stick">{header}{body}</div>;
}
// The tree view acts on its own selection through the detail pane, not the bulk toolbar.
@@ -752,17 +819,17 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
{syncPending && <span className="size-1.5 rounded-full bg-warn" role="img" aria-label={t('plugins.pending')} />}
</Button>
{!isAgent && <Link to="/hubs" className="ss-btn">{t('hubs.title')}</Link>}
{!isAgent && <Button variant="secondary" onClick={() => setLinkOpen(true)}><Link2 size={15} />{t('sourceLinks.title')}</Button>}
{!isAgent && (
<Link to="/skills/new" className="ss-btn">
<Plus size={15} />
{t('resources.newSkill')}
</Link>
)}
<Button variant="primary" data-tour="install-button" onClick={() => setInstall('url')}>
<Download size={15} />
{t('resources.install')}
</Button>
<span className="ss-btnpair">
<Button variant="primary" data-tour="install-button" onClick={() => setInstall('url')}>
<Download size={15} />
{t('resources.install')}
</Button>
{!isAgent && (
<Button variant="primary" aria-label={t('resources.moreWays')} aria-haspopup="menu" onClick={(e) => setMenu({ mode: 'add', point: menuPoint(e, 'end') })}>
<ChevronDown size={15} />
</Button>
)}
</span>
</>
)}
/>
@@ -795,9 +862,16 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
</div>
)}
<div ref={sentinel} aria-hidden className="-mt-2 h-0" />
{/* Every control sizes to its label: fixed widths truncated the longer values
("xcode-claude", "Disabled") and pushed the row past the container. */}
<div className="flex flex-wrap items-center gap-2 -mt-2">
<div ref={bar} className={`ss-stickbar ${stuck ? 'stuck' : ''}`}>
<div className="flex flex-wrap items-center gap-2">
{stuck && (
<b className="shrink-0 mr-2 text-[15px] animate-fade-in">
{t(isAgent ? 'layout.nav.agents' : 'layout.nav.skills')} <span className="text-[12px] font-medium text-ink-3">{items.length}</span>
</b>
)}
<label className="ss-inp w-[200px] shrink-0">
<Search size={15} className="shrink-0 text-ink-3" />
<input
@@ -855,9 +929,10 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
/>
)}
<span className="flex-1" />
{view === 'tree' && tree.children.size > 0 && (() => {
{((view === 'tree' && tree.children.size > 0) || (view === 'list' && group !== 'none')) && (() => {
// One button: collapses everything once all is open, otherwise opens everything.
const paths = folderPaths(tree);
const listKeys = group === 'source' ? groups.map((g) => groupKey(g.key)) : folderGroups.map((g) => groupKey(folderKey(g.key)));
const paths = view === 'tree' ? folderPaths(tree) : listKeys;
const allOpen = !paths.some((p) => collapsed.has(p));
const label = t(allOpen ? 'resources.folder.collapseAll' : 'resources.folder.expandAll');
return (
@@ -866,7 +941,8 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
className="ss-ib !w-[34px] !h-[34px] shrink-0"
title={label}
aria-label={label}
onClick={() => updateCollapsed(allOpen ? new Set(paths) : new Set())}
// The set also holds the other view's keys; leave those as they are.
onClick={() => updateCollapsed(allOpen ? new Set([...collapsed, ...paths]) : new Set([...collapsed].filter((k) => !paths.includes(k))))}
>
{allOpen ? <ChevronsDownUp size={16} /> : <ChevronsUpDown size={16} />}
</button>
@@ -905,9 +981,16 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
{ value: 'tree', label: <FolderTree size={15} />, title: t('resources.view.tree') },
]}
/>
{stuck && (
<Button variant="primary" size="sm" className="animate-fade-in" onClick={() => setInstall('url')}>
<Download size={14} />
{t('resources.install')}
</Button>
)}
</div>
</div>
<div className="-mt-3">
<div className="-mt-3" style={{ '--stick': `${barHeight}px` } as React.CSSProperties}>
{content}
{total > 0 && (
<div className="flex items-center justify-between mt-3">
@@ -999,12 +1082,31 @@ export default function ResourcesPage({ kind }: { kind: Kind }) {
{menu?.mode === 'bulk' && (
<TargetMenu open flat anchorPoint={menu.point} currentTargets={null} isUniform={false} onSelect={(target) => setManyTargets(menu.names, target)} onClose={() => setMenu(null)} />
)}
{menu?.mode === 'add' && (
<SkillContextMenu
open
anchorPoint={menu.point}
align="end"
onClose={() => setMenu(null)}
items={[
{ key: 'install', label: t('resources.add.install'), description: t('resources.add.installHint'), icon: <Download size={14} />, onSelect: () => setInstall('url') },
{ key: 'new', label: t('resources.newSkill'), description: t('resources.add.newHint'), icon: <Plus size={14} />, onSelect: () => navigate('/skills/new') },
{ key: 'link', label: t('sourceLinks.title'), description: t('resources.add.linkHint'), icon: <Link2 size={14} />, onSelect: () => setLinkOpen(true) },
]}
/>
)}
{menu?.mode === 'repo' && (
<SkillContextMenu
open
anchorPoint={menu.point}
onClose={() => setMenu(null)}
items={[{
key: 'update-repo',
label: t('resources.repo.update'),
icon: <RefreshCw size={14} />,
onSelect: () => { if (updating === null) update(menu.repo); },
}, {
key: 'uninstall-repo',
label: t('resources.contextMenu.uninstallRepo'),
icon: <Trash2 size={14} />,
+55 -1
View File
@@ -13,7 +13,7 @@ import SyncPage from './SyncPage';
vi.mock('../api/client', async (load) => ({
...await load<typeof import('../api/client')>(),
api: { listTargets: vi.fn(), diff: vi.fn(), diffExtras: vi.fn(), listLog: vi.fn(), skillsOffPreview: vi.fn(), updateTarget: vi.fn(), sync: vi.fn(), syncExtras: vi.fn() },
api: { listTargets: vi.fn(), listSkills: vi.fn(() => Promise.resolve({ resources: [] })), getSyncMatrix: vi.fn(() => Promise.resolve({ entries: [] })), diff: vi.fn(), diffExtras: vi.fn(), listLog: vi.fn(), skillsOffPreview: vi.fn(), updateTarget: vi.fn(), sync: vi.fn(), syncExtras: vi.fn() },
}));
vi.mock('../api/mcp', async (load) => ({ ...await load<typeof import('../api/mcp')>(), mcpApi: { list: vi.fn() } }));
vi.mock('../api/hooks', async (load) => ({ ...await load<typeof import('../api/hooks')>(), hooksApi: { list: vi.fn(() => Promise.reject(new Error('offline'))) } }));
@@ -73,6 +73,60 @@ describe('Sync page last sync', () => {
expect((await screen.findByText('Failed')).nextElementSibling).toHaveTextContent('codex and cursor');
});
it('shows targets with the same changes once and offers to discard only skills never synced anywhere', async () => {
const user = userEvent.setup();
const skill = (flatName: string) => ({ name: flatName, kind: 'skill', flatName, relPath: flatName, sourcePath: '', isInRepo: true });
vi.mocked(api.listTargets).mockResolvedValue({ targets: [target('codex'), target('cursor')], sourceSkillCount: 2 });
vi.mocked(api.diff).mockResolvedValue({
diffs: ['codex', 'cursor'].map((name) => ({ target: name, items: [{ skill: 'fresh', action: 'link', reason: 'new' }, { skill: 'old', action: 'link', reason: 'new' }] })),
ignored_count: 0, ignored_skills: [], ignore_root: '', ignore_repos: [],
} as never);
vi.mocked(api.listSkills).mockResolvedValue({ resources: [skill('fresh'), skill('old')] } as never);
// old is already in claude, so only fresh has never been synced.
const entry = (s: string, target: string) => ({ skill: s, target, status: 'synced', reason: '' });
vi.mocked(api.getSyncMatrix).mockResolvedValue({ entries: [entry('fresh', 'codex'), entry('fresh', 'cursor'), entry('old', 'codex'), entry('old', 'cursor'), entry('old', 'claude')] } as never);
renderPage();
expect(await screen.findByText('2 targets')).toBeInTheDocument();
await user.click(await screen.findByRole('button', { name: 'Discard all' }));
const dialog = await screen.findByRole('dialog');
expect(dialog).toHaveTextContent('fresh');
expect(dialog).not.toHaveTextContent('old');
});
it('does not offer Discard all for a skill a symlink-mode target already exposes', async () => {
const skill = (flatName: string) => ({ name: flatName, kind: 'skill', flatName, relPath: flatName, sourcePath: '', isInRepo: true });
vi.mocked(api.listTargets).mockResolvedValue({ targets: [target('codex')], sourceSkillCount: 1 });
vi.mocked(api.diff).mockResolvedValue({
diffs: [{ target: 'codex', items: [{ skill: 'fresh', action: 'link', reason: 'new' }] }],
ignored_count: 0, ignored_skills: [], ignore_root: '', ignore_repos: [],
} as never);
vi.mocked(api.listSkills).mockResolvedValue({ resources: [skill('fresh')] } as never);
// claude links the whole source folder, so fresh is already live there.
vi.mocked(api.getSyncMatrix).mockResolvedValue({ entries: [
{ skill: 'fresh', target: 'codex', status: 'synced', reason: '' },
{ skill: 'fresh', target: 'claude', status: 'na', reason: 'symlink mode — filters not applicable', reasonCode: 'sync_matrix.symlink_filters_not_applicable' },
] } as never);
renderPage();
expect(await screen.findByText(/Sync 1 change/)).toBeInTheDocument();
await waitFor(() => expect(api.getSyncMatrix).toHaveBeenCalled());
await new Promise((r) => setTimeout(r, 50));
expect(screen.queryByRole('button', { name: 'Discard all' })).toBeNull();
});
it('lists a skill and an agent with the same name as two changes', async () => {
vi.mocked(api.listTargets).mockResolvedValue({ targets: [target('codex')], sourceSkillCount: 1 });
vi.mocked(api.diff).mockResolvedValue({
diffs: [{ target: 'codex', items: [{ skill: 'reviewer', action: 'link', reason: 'new' }, { skill: 'reviewer', kind: 'agent', action: 'link', reason: 'new' }] }],
ignored_count: 0, ignored_skills: [], ignore_root: '', ignore_repos: [],
} as never);
renderPage();
expect(await screen.findByText(/Sync 2 changes/)).toBeInTheDocument();
expect(screen.getAllByText('reviewer', { selector: '.grid-cols-3 .truncate' })).toHaveLength(2);
});
it('counts the failed targets when an older entry has no names', async () => {
vi.mocked(api.listLog).mockResolvedValue({ entries: [{ ts: '2026-09-30T00:00:00Z', cmd: 'sync', status: 'partial', args: { targets_total: 3, targets_failed: 1 } }] } as never);
renderPage();
+164 -51
View File
@@ -14,29 +14,37 @@ import { useToast } from '../components/Toast';
import { hookLabel, hookMessage, rootName } from '../components/hooks/hooksView';
import MCPNotices from '../components/mcp/MCPNotices';
import { describeMessage, mcpClient, targetLabel } from '../components/mcp/mcpView';
import { countChanges, countEdited, extraGroups, groupByFolder, groupInSync, HOOKS_CHANGED, hooksGroups, MCP_CHANGED, mcpGroups, otherWarnings, resourceGroups, runSync, type ChangeGroup, type Part, type RowIcon, type SyncFailure } from '../components/sync/syncView';
import { changeSets, countChanges, countEdited, discardable, receivesSkill, tally, extraGroups, groupByFolder, groupInSync, HOOKS_CHANGED, hooksGroups, MCP_CHANGED, mcpGroups, otherWarnings, resourceGroups, runSync, type ChangeGroup, type Part, type RowIcon, type SyncFailure } from '../components/sync/syncView';
import SyncResult from '../components/sync/SyncResult';
import SyncError from '../components/sync/SyncError';
import SkillsOffDialog from '../components/targets/SkillsOffDialog';
import SegmentedControl from '../components/SegmentedControl';
import { UninstallDialog } from '../components/resources/UninstallDialog';
import { joinList } from '../components/targets/targetView';
import { formatDateTime, formatRelativeTime, useI18n, useT, plural } from '../i18n';
import { shortenHome } from '../lib/paths';
import { formatAgentDisplayName } from '../lib/resourceNames';
import { formatAgentDisplayName, formatTrackedRepoName } from '../lib/resourceNames';
import { queryKeys, staleTimes } from '../lib/queryKeys';
import { useDiffQuery, useHooksQuery, useMcpQuery, useSyncedTargetsQuery } from '../hooks/useSharedQueries';
import { useDiffQuery, useHooksQuery, useMcpQuery, useSkillsQuery, useSyncedTargetsQuery } from '../hooks/useSharedQueries';
import { invalidate } from '../lib/queryEvents';
import { useSyncMatrix } from '../hooks/useSyncMatrix';
const ROW_ICON: Record<RowIcon, React.ReactNode> = {
add: <Plus size={16} className="shrink-0 text-ok" />,
adopt: <Import size={15} className="shrink-0 text-info" />,
update: <RefreshCw size={15} className="shrink-0 text-info" />,
remove: <Minus size={16} className="shrink-0 text-bad" />,
kept: <CircleMinus size={15} className="shrink-0 text-ink-3" />,
conflict: <TriangleAlert size={15} className="shrink-0 text-warn" />,
const ROW_ICON: Record<RowIcon, [typeof Plus, string]> = {
add: [Plus, 'text-ok'], adopt: [Import, 'text-info'], update: [RefreshCw, 'text-info'],
remove: [Minus, 'text-bad'], kept: [CircleMinus, 'text-ink-3'], conflict: [TriangleAlert, 'text-warn'],
};
/** A row's icon; `small` for names in a grid. Plus and minus draw thinner, so they go a size up. */
function rowIcon(icon: RowIcon, small = false) {
const [Icon, tone] = ROW_ICON[icon];
return <Icon size={(icon === 'add' || icon === 'remove' ? 16 : 15) - (small ? 3 : 0)} className={`shrink-0 ${tone}`} />;
}
const PART_ICON: Record<Part, React.ReactNode> = { skill: <Puzzle size={14} />, agent: <Bot size={14} />, extra: <FolderPlus size={14} />, mcp: <Plug size={14} />, hooks: <Webhook size={14} /> };
const PART_LABEL: Record<Part, string> = { skill: 'Skills', agent: 'Agents', extra: 'Extras', mcp: 'MCP', hooks: 'Hooks' };
const PARTS = Object.keys(PART_LABEL) as Part[];
/** A target with more rows than this starts collapsed. */
const OPEN_ROWS = 8;
const SET_LABEL = [['add', 'sync.set.add'], ['update', 'sync.set.update'], ['remove', 'sync.set.remove'], ['kept', 'sync.set.kept']] as const;
const GROUP_BODY = 'flex flex-col gap-4 pb-[18px] pl-[52px] pr-[18px] pt-3.5 animate-fade-in [border-top:var(--sep)]';
/** A target in an expanded list: its logo and name. */
function TargetChip({ target, label }: { target: string; label: string }) {
@@ -82,6 +90,10 @@ export default function SyncPage() {
const [outcome, setOutcome] = useState<SyncResponse | null>(null);
const [failures, setFailures] = useState<SyncFailure[]>([]);
const [stopping, setStopping] = useState('');
const [view, setView] = useState<'change' | 'target'>('change');
// Explicit open/closed per group; unset follows each group's default.
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
const [discarding, setDiscarding] = useState(false);
const plan = mcp.data?.plan;
const hooksPlan = hooks.data?.plan;
@@ -94,6 +106,7 @@ export default function SyncPage() {
// A blocked plan applies nothing, so its rows are shown but not counted.
const count = countChanges(groups) - (plan?.blocked ? countChanges(mcpShown) : 0) - (hooksPlan?.blocked ? countChanges(hooksShown) : 0);
const edited = countEdited(groups);
const total = tally(groups.flatMap((g) => g.rows).filter((r) => r.counts));
const loading = diff.isPending || targets.isPending;
const localByTarget = diffs
@@ -110,6 +123,17 @@ export default function SyncPage() {
const conflicts = diff.data?.folder_conflicts ?? [];
const stopTarget = targetList.find((x) => x.name === stopping);
const stopConflict = conflicts.find((c) => c.stop.includes(stopping));
// Skill names and Discard all need the skills list and matrix only while skills are being added.
const addsSkills = !running && !outcome && resources.groups.some((g) => g.rows.some((r) => r.part === 'skill' && r.icon === 'add'));
const skills = useSkillsQuery({ enabled: addsSkills });
const matrix = useSyncMatrix(addsSkills);
const skillList = skills.data?.resources ?? [];
const toDiscard = !addsSkills || !matrix.matrix.length ? [] : discardable(resources.groups, skillList, (name) => matrix.getSkillTargets(name).filter(receivesSkill).map((e) => e.target));
// Show a skill by its source path; flattened target names (_repo__skills__x) are hard to read.
const relPaths = new Map(skillList.map((s) => [s.flatName, s.relPath]));
const display = (r: ChangeGroup['rows'][number]) => (r.part === 'skill' ? formatTrackedRepoName(relPaths.get(r.name) ?? r.name.replace(/__/g, '/')) : r.name);
const isOpen = (key: string, byDefault: boolean) => expanded[key] ?? byDefault;
const flip = (key: string, byDefault: boolean) => setExpanded((e) => ({ ...e, [key]: !(e[key] ?? byDefault) }));
const toggle = (set: Set<string>, key: string) => { const next = new Set(set); if (next.has(key)) next.delete(key); else next.add(key); return next; };
@@ -142,10 +166,13 @@ export default function SyncPage() {
const failedTargets = new Set(failures.filter((f) => f.part !== 'extra').map((f) => f.target));
const syncedTargets = new Set((outcome?.results ?? []).map((r) => r.target).filter((name) => !failedTargets.has(name))).size;
const chevron = (open: boolean) => (open ? <ChevronDown size={15} className="shrink-0 text-ink-3" /> : <ChevronRight size={15} className="shrink-0 text-ink-3" />);
/** A group head's content; targets wrap it in a button that collapses them. */
const groupHead = (g: ChangeGroup) => {
const n = countChanges([g]);
return (
<div className="ss-gh">
<>
{g.part === 'extra' ? <span className="ss-cat sm extra">{PART_ICON.extra}</span> : <span className="ss-at"><AgentIcon target={g.name} size={17} /></span>}
<span className="font-semibold">{g.part === 'mcp' ? targetLabel(g.name) : g.part === 'hooks' ? hookLabel(g.name) : g.name}</span>
<span className="ss-tag">{g.part === 'mcp' ? 'MCP' : g.part === 'hooks' ? 'Hooks' : g.mode}</span>
@@ -154,32 +181,100 @@ export default function SyncPage() {
{g.project && <span className="ss-tag shrink-0" title={g.project}>{g.part === 'hooks' ? rootName(g.project) : t('sync.mcp.offList', { project: shortenHome(g.project) })}</span>}
<span className="flex-1" />
{n > 0 && <span className="shrink-0 text-[12px] text-ink-2">{t(plural('sync.changes', n), { count: n })}</span>}
</>
);
};
const changeRows = (rows: ChangeGroup['rows']) => rows.map((r) => (
<div key={r.key} className="ss-r !min-h-[46px]">
{rowIcon(r.icon)}
<span className={`ss-cat sm ${r.part}`}>{PART_ICON[r.part]}</span>
<span className="w-[220px] shrink-0 truncate font-mono text-[13px] font-semibold" title={r.name}>{r.name}</span>
{r.part === 'hooks' && r.detail ? (
// A hooks reason is worded for this UI and can be long: hover shows all of it.
<span className="min-w-0 flex-1">
<Tooltip block content={hookMessage(t, r.detail)}>
<span className={`block truncate text-[13px] ${r.icon === 'conflict' ? 'text-warn' : 'text-ink-2'}`}>{r.text ? t(r.text) : hookMessage(t, r.detail)}</span>
</Tooltip>
</span>
) : (
<span className={`min-w-0 flex-1 truncate text-[13px] ${r.icon === 'conflict' ? 'text-warn' : 'text-ink-2'}`} title={r.detail}>
{r.text ? t(r.text) : r.part === 'mcp' ? describeMessage(t, r.detail) : r.detail}
</span>
)}
</div>
));
/** Skill and agent changes as names by folder, three to a line: hundreds of rows stay readable. */
const itemGrid = (rows: ChangeGroup['rows'], icons = true, from = '') => {
// A skill and an agent can share a display path, so a path holds a list.
const byPath = new Map<string, ChangeGroup['rows']>();
for (const r of rows) byPath.set(display(r), [...(byPath.get(display(r)) ?? []), r]);
return groupByFolder([...byPath.keys()]).map(({ folder, items }) => {
// The head already names the shared root, so a folder drops it.
const label = (from && folder.startsWith(`${from}/`) && folder !== `${from}/` ? folder.slice(from.length + 1) : folder).replace(/\/$/, '');
const entries = items.flatMap((name) => byPath.get(folder + name)!.map((r) => ({ name, r })));
return (
<div key={folder} className="flex flex-col gap-1.5">
{folder && <div className="flex items-center gap-[7px] text-[12px] font-semibold text-ink-3"><Folder size={14} className="shrink-0" /><span className="font-mono">{label}</span> · {entries.length}</div>}
<div className={`grid grid-cols-3 gap-x-6 gap-y-1.5 font-mono text-[12.5px] ${folder ? 'pl-[21px]' : ''}`}>
{entries.map(({ name, r }) => {
const why = r.text ? t(r.text) : r.detail;
return <span key={r.key} className="flex min-w-0 items-center gap-1.5" title={why ? `${folder + name} · ${why}` : folder + name}>{icons && rowIcon(r.icon, true)}<span className="truncate">{name}</span></span>;
})}
</div>
</div>
);
});
};
const setCard = (set: ReturnType<typeof changeSets>[number], index: number) => {
const n = countChanges(set.targets);
const open = isOpen(set.key, index === 0);
const parts = new Set(set.rows.map((r) => r.part));
const counts = tally(set.rows);
const shown = SET_LABEL.filter(([icon]) => counts[icon]);
const noun = (count: number) => (parts.size === 1 ? [...parts][0] : 'item') + (count === 1 ? '' : 's');
// Where the changes come from, when they share one: the tracked repo or folder.
const paths = set.rows.map(display);
const roots = new Set(paths.map((p) => p.split('/')[0]));
const from = paths.length === 1 ? paths[0] : roots.size === 1 ? [...roots][0] : '';
return (
<Fragment key={set.key}>
<button type="button" className="ss-gh w-full cursor-pointer text-left" aria-expanded={open} onClick={() => flip(set.key, index === 0)}>
{chevron(open)}
{shown[0] && rowIcon(shown[0][0], true)}
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="truncate font-semibold">{shown.map(([icon, key]) => t(key, { count: counts[icon]!, noun: noun(counts[icon]!) })).join(' · ')}</span>
{from && <span className="truncate font-mono text-[12px] text-ink-3">{from}</span>}
</span>
{set.targets.some((g) => failedTargets.has(g.name)) && <span className="ss-tag bad shrink-0">{t('sync.result.lastFailed')}</span>}
<span className="ss-stack">{set.targets.slice(0, 5).map((g) => <span key={g.name} className="ss-at"><AgentIcon target={g.name} size={15} /></span>)}</span>
<span className="shrink-0 text-[12px] text-ink-2">{t(plural('sync.set.targets', set.targets.length), { count: set.targets.length })}</span>
<span className="w-[84px] shrink-0 text-right text-[12px] text-ink-2">{n > 0 && t(plural('sync.changes', n), { count: n })}</span>
</button>
{open && (
<div className={GROUP_BODY}>
<div className="flex flex-col gap-2">
<span className="text-[12px] font-semibold text-ink-3">{t('sync.set.targetList', { count: set.targets.length })}</span>
<div className="flex flex-wrap gap-2">{set.targets.map((g) => <TargetChip key={g.name} target={g.name} label={g.name} />)}</div>
</div>
{itemGrid(set.rows, shown.length > 1, paths.length > 1 ? from : '')}
</div>
)}
</Fragment>
);
};
return (
<div className="animate-fade-in">
<PageHeader
title={t('sync.title')}
subtitle={t('sync.subtitle')}
actions={
<span data-tour="sync-actions">
<Button variant="primary" onClick={sync} loading={running} disabled={loading || parts.size === 0}>
{!running && <RefreshCw size={16} />}
{count > 0 ? t(plural('sync.run', count), { count }) : t('sync.run.none')}
</Button>
</span>
}
/>
<div className="grid grid-cols-[minmax(0,1fr)_280px] items-start gap-8">
<div className="flex min-w-0 flex-col gap-4">
<PageHeader title={t('sync.title')} subtitle={t('sync.subtitle')} />
<div className="ss-stickbar !py-3.5 mb-3">
<div className="flex flex-wrap items-center gap-[18px]">
<span className="text-[13px] text-ink-3">{t('sync.include')}</span>
{PARTS.map((p) => (
<Checkbox key={p} size="sm" label={PART_LABEL[p]} checked={parts.has(p)} disabled={running} onChange={() => setOff((s) => toggle(s, p) as Set<Part>)} />
))}
<span className="flex-1" />
<span className="flex items-center gap-2" title={t('sync.forceHint')}>
<button type="button" role="switch" aria-checked={force} aria-labelledby="sync-force" aria-describedby="sync-force-hint" className={`ss-sw ${force ? 'on' : ''} disabled:opacity-50`} disabled={running} onClick={() => setForce(!force)}>
<i />
@@ -187,7 +282,22 @@ export default function SyncPage() {
<span id="sync-force" className="text-[13px] font-semibold">Force</span>
<span id="sync-force-hint" className="sr-only">{t('sync.forceHint')}</span>
</span>
<span className="flex-1" />
<span className="flex items-center gap-2" data-tour="sync-actions">
{toDiscard.length > 0 && (
<Button variant="secondary" disabled={running} onClick={() => setDiscarding(true)}>
{t('sync.discard')}
</Button>
)}
<Button variant="primary" onClick={sync} loading={running} disabled={loading || parts.size === 0}>
{!running && <RefreshCw size={16} />}
{count > 0 ? t(plural('sync.run', count), { count }) : t('sync.run.none')}
</Button>
</span>
</div>
</div>
<div className="grid grid-cols-[minmax(0,1fr)_280px] items-start gap-8">
<div className="flex min-w-0 flex-col gap-4">
{edited > 0 && (
<div className={`ss-note ${force ? 'warn' : 'inf'}`}>
{force ? <TriangleAlert size={16} /> : <CircleMinus size={16} />}
@@ -233,6 +343,21 @@ export default function SyncPage() {
</div>
))}
{!loading && !diff.error && groups.length > 0 && (
<div className="flex items-center gap-3">
<h2 className="ss-h2">{t(plural('sync.pending', count), { count })}</h2>
<span className="flex-1 text-[12px] text-ink-2">
{(['add', 'update', 'remove'] as const).filter((icon) => total[icon]).map((icon, i) => (
<Fragment key={icon}>{i > 0 && ' · '}<span className={ROW_ICON[icon][1]}>{t(`sync.sum.${icon}`, { count: total[icon]! })}</span></Fragment>
))}
</span>
<SegmentedControl
value={view}
onChange={setView}
options={[{ value: 'change', label: t('sync.view.change') }, { value: 'target', label: t('sync.view.target') }]}
/>
</div>
)}
<div className="ss-list">
{loading ? (
<div className="ss-r gap-2 text-[13px] text-ink-2"><Spinner size="sm" />{t('sync.checking')}</div>
@@ -248,30 +373,17 @@ export default function SyncPage() {
{groups.length === 0 && (
<div className="ss-r text-[13px]"><CircleCheck size={16} className="text-ok" />{t('sync.nothing')}</div>
)}
{groups.map((g) => (
<Fragment key={g.key}>
{groupHead(g)}
{g.rows.map((r) => (
<div key={r.key} className="ss-r !min-h-[46px]">
{ROW_ICON[r.icon]}
<span className={`ss-cat sm ${r.part}`}>{PART_ICON[r.part]}</span>
<span className="w-[220px] shrink-0 truncate font-mono text-[13px] font-semibold" title={r.name}>{r.name}</span>
{r.part === 'hooks' && r.detail ? (
// A hooks reason is worded for this UI and can be long: hover shows all of it.
<span className="min-w-0 flex-1">
<Tooltip block content={hookMessage(t, r.detail)}>
<span className={`block truncate text-[13px] ${r.icon === 'conflict' ? 'text-warn' : 'text-ink-2'}`}>{r.text ? t(r.text) : hookMessage(t, r.detail)}</span>
</Tooltip>
</span>
) : (
<span className={`min-w-0 flex-1 truncate text-[13px] ${r.icon === 'conflict' ? 'text-warn' : 'text-ink-2'}`} title={r.detail}>
{r.text ? t(r.text) : r.part === 'mcp' ? describeMessage(t, r.detail) : r.detail}
</span>
)}
</div>
))}
</Fragment>
))}
{view === 'change' && changeSets(resources.groups).map((set, i) => setCard(set, i))}
{(view === 'change' ? groups.filter((g) => g.part !== 'target') : groups).map((g) => {
if (g.part !== 'target') return <Fragment key={g.key}><div className="ss-gh">{groupHead(g)}</div>{changeRows(g.rows)}</Fragment>;
const open = isOpen(g.key, g.rows.length <= OPEN_ROWS);
return (
<Fragment key={g.key}>
<button type="button" className="ss-gh w-full cursor-pointer text-left" aria-expanded={open} onClick={() => flip(g.key, g.rows.length <= OPEN_ROWS)}>{chevron(open)}{groupHead(g)}</button>
{open && <div className={GROUP_BODY}>{itemGrid(g.rows)}</div>}
</Fragment>
);
})}
{resources.inSync.length > 0 && (
<button type="button" className="ss-gh w-full text-left" aria-expanded={open.has('inSync')} onClick={() => setOpen((s) => toggle(s, 'inSync'))}>
{!open.has('inSync') && <span className="ss-stack ml-1.5">{resources.inSync.slice(0, 4).map((name) => <span key={name} className="ss-at"><AgentIcon target={name} size={14} /></span>)}</span>}
@@ -391,7 +503,7 @@ export default function SyncPage() {
</div>
<aside className="flex flex-col">
<aside className="sticky top-[84px] flex flex-col">
<div className="ss-box flex flex-col gap-3.5">
<div className="flex items-center justify-between">
<h3 className="text-[15px] font-semibold">{t('sync.last.title')}</h3>
@@ -423,6 +535,7 @@ export default function SyncPage() {
</div>
{collecting && <CollectDialog onClose={() => setCollecting(false)} />}
{discarding && <UninstallDialog kind="skill" selection={toDiscard} all={skillList} onClose={() => setDiscarding(false)} />}
{stopTarget && (
<SkillsOffDialog
target={stopTarget}
+63 -19
View File
@@ -17,8 +17,9 @@ vi.mock('../api/client', async (importOriginal) => {
listSkills: vi.fn(),
checkStream: vi.fn(),
updateAllStream: vi.fn(),
missingTrackedRepos: vi.fn(),
rehydrateTrackedRepos: vi.fn(),
missingConfigEntries: vi.fn(),
installFromConfig: vi.fn(),
batchUninstall: vi.fn(),
sync: vi.fn().mockResolvedValue({ results: [] }),
},
};
@@ -51,7 +52,7 @@ async function findRow(name: string) {
function cacheStatus(name: string, status: string) {
localStorage.setItem(
'skillshare.updateCheckCache.global',
JSON.stringify({ version: 1, items: { [name]: { status, checkedAt: new Date(Date.now() - 60_000).toISOString() } } }),
JSON.stringify({ version: 2, items: { [name]: { status, checkedAt: new Date(Date.now() - 60_000).toISOString() } } }),
);
}
@@ -61,7 +62,7 @@ describe('UpdatePage', () => {
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
vi.mocked(api.missingTrackedRepos).mockResolvedValue({ repos: [] });
vi.mocked(api.missingConfigEntries).mockResolvedValue({ entries: [], file: '.metadata.json' });
});
const nestedSkill = {
@@ -145,7 +146,7 @@ describe('UpdatePage', () => {
vi.mocked(api.listSkills).mockResolvedValue({
resources: [nestedSkill],
});
cacheStatus('agent-browser', 'update-available');
cacheStatus('tools/agent-browser', 'update-available');
renderUpdatePage();
@@ -185,7 +186,7 @@ describe('UpdatePage', () => {
resources: [{ ...nestedSkill, name: 'child', relPath: '_dev-skills/child', isInRepo: true }],
linked_repos: [linked],
});
cacheStatus('child', 'error');
cacheStatus('_dev-skills/child', 'error');
renderUpdatePage();
const row = await findRow('_dev-skills');
@@ -248,7 +249,7 @@ describe('UpdatePage', () => {
vi.mocked(api.listSkills).mockResolvedValue({
resources: [nestedSkill],
});
cacheStatus('agent-browser', 'update-available');
cacheStatus('tools/agent-browser', 'update-available');
vi.mocked(api.updateAllStream).mockImplementation((onStart, onResult, onDone) => {
queueMicrotask(() => {
onStart(1);
@@ -282,7 +283,7 @@ describe('UpdatePage', () => {
isRepo: false,
};
vi.mocked(api.listSkills).mockResolvedValue({ resources: [nestedSkill] });
cacheStatus('agent-browser', 'update-available');
cacheStatus('tools/agent-browser', 'update-available');
vi.mocked(api.updateAllStream).mockImplementation((onStart, onResult, onDone) => {
queueMicrotask(() => {
onStart(1);
@@ -309,7 +310,7 @@ describe('UpdatePage', () => {
it('syncs the updated kind in place after an update', async () => {
const updatedResult = { name: 'tools/agent-browser', action: 'updated', message: '', isRepo: false };
vi.mocked(api.listSkills).mockResolvedValue({ resources: [nestedSkill] });
cacheStatus('agent-browser', 'update-available');
cacheStatus('tools/agent-browser', 'update-available');
vi.mocked(api.updateAllStream).mockImplementation((onStart, onResult, onDone) => {
queueMicrotask(() => {
onStart(1);
@@ -328,24 +329,67 @@ describe('UpdatePage', () => {
expect(await screen.findByText('Only skills are written. Agents, extras and MCP stay as they are.')).toBeInTheDocument();
});
it('warns about missing tracked repos and rehydrates on click (issue #212)', async () => {
it('installs entries missing on disk from config (issue #212)', async () => {
vi.mocked(api.listSkills).mockResolvedValue({ resources: [nestedSkill] });
vi.mocked(api.missingTrackedRepos).mockResolvedValue({
repos: [{ name: '_team-skills', source: 'https://github.com/example/team-skills', branch: 'main' }],
});
vi.mocked(api.rehydrateTrackedRepos).mockResolvedValue({
results: [{ name: '_team-skills', action: 'rehydrated' }],
vi.mocked(api.missingConfigEntries).mockResolvedValue({
entries: [{ name: '_team-skills', source: 'https://github.com/example/team-skills', tracked: true, branch: 'main' }],
file: '.metadata.json',
});
vi.mocked(api.installFromConfig).mockResolvedValue({ installed: 1, installedRepos: 1, installedRepoSkills: 3, skipped: 0, failed: [] });
const user = userEvent.setup();
renderUpdatePage();
// Banner lists the missing repo.
expect(await screen.findByText('_team-skills')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /install missing/i }));
await user.click(screen.getByRole('button', { name: /rehydrate/i }));
expect(await screen.findByText(/^Installed 1 tracked repo/)).toBeInTheDocument();
});
await waitFor(() => expect(api.rehydrateTrackedRepos).toHaveBeenCalled());
it('lists skills deleted upstream and prunes them', async () => {
vi.mocked(api.listSkills).mockResolvedValue({ resources: [nestedSkill] });
vi.mocked(api.batchUninstall).mockResolvedValue({ results: [] } as never);
vi.mocked(api.checkStream).mockImplementation((_a, _b, _c, onDone) => {
queueMicrotask(() => onDone({ tracked_repos: [], skills: [{ name: 'tools/agent-browser', source: nestedSkill.source, version: '1', status: 'stale' }] }));
return { close: vi.fn() } as unknown as EventSource;
});
const user = userEvent.setup();
renderUpdatePage();
await user.click(await screen.findByRole('button', { name: /check for updates/i }));
const row = await findRow('agent-browser');
await user.click(await row.findByRole('button', { name: 'Prune' }));
await waitFor(() => expect(api.batchUninstall).toHaveBeenCalledWith({ names: ['tools/agent-browser'], force: true }));
});
it('does not offer prune from a stale status saved by an earlier session', async () => {
vi.mocked(api.listSkills).mockResolvedValue({ resources: [nestedSkill] });
cacheStatus('tools/agent-browser', 'stale');
renderUpdatePage();
await findRow('agent-browser');
expect(screen.queryByRole('button', { name: /^Prune/ })).not.toBeInTheDocument();
});
it('prunes only the skill deleted upstream when another folder has one of the same name', async () => {
const foo = (dir: string) => ({ ...nestedSkill, name: 'foo', flatName: `${dir}__foo`, relPath: `${dir}/foo`, sourcePath: `/skills/${dir}/foo`, source: `https://github.com/o/r/${dir}/foo` });
vi.mocked(api.listSkills).mockResolvedValue({ resources: [foo('a'), foo('b')] });
vi.mocked(api.batchUninstall).mockResolvedValue({ results: [] } as never);
vi.mocked(api.checkStream).mockImplementation((_a, _b, _c, onDone) => {
queueMicrotask(() => onDone({ tracked_repos: [], skills: [
{ name: 'a/foo', source: 'https://github.com/o/r/a/foo', version: '1', status: 'up_to_date' },
{ name: 'b/foo', source: 'https://github.com/o/r/b/foo', version: '1', status: 'stale' },
] }));
return { close: vi.fn() } as unknown as EventSource;
});
const user = userEvent.setup();
renderUpdatePage();
await user.click(await screen.findByRole('button', { name: /check for updates/i }));
await user.click(await screen.findByRole('button', { name: 'Prune all' }));
await waitFor(() => expect(api.batchUninstall).toHaveBeenCalledWith({ names: ['b/foo'], force: true }));
});
});
@@ -361,7 +405,7 @@ describe('update failure message helpers', () => {
}));
const units = updateUnits(resources, 'skill', [{ name: '_dev', target: '/code/dev' }]);
expect(units.map((unit) => unit.name)).toEqual(['_managed']);
expect(countUpdates(new Map(resources.map((item) => [item.name, { status: 'behind' as const }])), units)).toBe(1);
expect(countUpdates(new Map(resources.map((item) => [item.relPath, { status: 'behind' as const }])), units)).toBe(1);
});
it('offers force retry for failures force can actually resolve', () => {
+155 -47
View File
@@ -1,15 +1,15 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Bot, Check, CircleAlert, CircleArrowUp, CircleCheck, FolderX, GitBranch, Link, Loader2, Puzzle, RefreshCw, ShieldAlert, Trash2, X } from 'lucide-react';
import { Bot, Check, CircleAlert, CircleArrowUp, CircleCheck, Download, FolderX, GitBranch, Link, Loader2, Puzzle, RefreshCw, ShieldAlert, Trash2, X } from 'lucide-react';
import { api } from '../api/client';
import type { CheckResult, LinkedRepo, Skill, UpdateResultItem } from '../api/client';
import { queryKeys, staleTimes } from '../lib/queryKeys';
import { queryKeys } from '../lib/queryKeys';
import { clearAuditCache } from '../lib/auditCache';
import { parseRemoteURL } from '../lib/parseRemoteURL';
import { folderOf, formatTrackedRepoName } from '../lib/resourceNames';
import { repoOf } from '../lib/resourceGrouping';
import { formatRelativeTime, useI18n, useT } from '../i18n';
import { formatRelativeTime, plural, useI18n, useT } from '../i18n';
import Button from '../components/Button';
import { Checkbox } from '../components/Checkbox';
import EmptyState from '../components/EmptyState';
@@ -17,12 +17,13 @@ import SyncPreviewModal from '../components/SyncPreviewModal';
import { useToast } from '../components/Toast';
import { useSkillsQuery } from '../hooks/useSharedQueries';
import { invalidate } from '../lib/queryEvents';
import { useInstallFromConfig } from '../hooks/useInstallFromConfig';
/* -- Types ---------------------------------------- */
type Kind = Skill['kind'];
type CheckStatus = 'unchecked' | 'checking' | 'behind' | 'dirty' | 'up-to-date' | 'update-available' | 'error';
type CheckStatus = 'unchecked' | 'checking' | 'behind' | 'dirty' | 'up-to-date' | 'update-available' | 'stale' | 'error';
interface CheckItemStatus {
status: CheckStatus;
@@ -33,9 +34,10 @@ interface CheckItemStatus {
type CheckStatuses = Map<string, CheckItemStatus>;
const CHECK_STATUS_VALUES: CheckStatus[] = ['unchecked', 'checking', 'behind', 'dirty', 'up-to-date', 'update-available', 'error'];
const CHECK_STATUS_VALUES: CheckStatus[] = ['unchecked', 'checking', 'behind', 'dirty', 'up-to-date', 'update-available', 'stale', 'error'];
const UPDATE_CHECK_CACHE_KEY = 'skillshare.updateCheckCache.global';
const UPDATE_CHECK_CACHE_VERSION = 1;
// 2: statuses keyed by relative path; names collide across folders.
const UPDATE_CHECK_CACHE_VERSION = 2;
interface StoredCheckCache {
version: number;
@@ -104,8 +106,11 @@ export function updateUnits(resources: Skill[], kind: Kind, linkedRepos: LinkedR
}
/** Repo status is copied to every item in the repo, so the first item speaks for the unit. */
/** A skill's key in the check statuses: its relative path, since names repeat across folders. */
export const checkKey = (item: Pick<Skill, 'relPath'>) => item.relPath;
function unitCheck(statuses: CheckStatuses, unit: UpdateUnit): CheckItemStatus {
return statuses.get(unit.items[0].name) ?? { status: 'unchecked' };
return statuses.get(checkKey(unit.items[0])) ?? { status: 'unchecked' };
}
export function hasUpdate(status: CheckItemStatus) {
@@ -125,13 +130,9 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
const { toast } = useToast();
const { data: skillsData } = useSkillsQuery();
// Tracked repos declared in metadata but missing on disk (issue #212)
const { data: missingReposData } = useQuery({
queryKey: queryKeys.missingTrackedRepos,
queryFn: () => api.missingTrackedRepos(),
staleTime: staleTimes.missingTrackedRepos,
});
const missingRepos = missingReposData?.repos ?? [];
// Entries recorded in config but missing on disk (issue #212)
const missing = useInstallFromConfig();
const showMissing = kind === 'skill' && missing.entries.length > 0;
const resources = useMemo(() => skillsData?.resources ?? [], [skillsData]);
// A full check covers both kinds, so results are applied to every updatable item.
@@ -146,7 +147,8 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
const [run, setRun] = useState<Map<string, RunState>>(new Map());
const [running, setRunning] = useState(false);
const [finished, setFinished] = useState(false);
const [rehydrating, setRehydrating] = useState(false);
const [pruning, setPruning] = useState<Map<string, 'working' | 'out'>>(new Map());
const [pruned, setPruned] = useState(0);
const [syncOpen, setSyncOpen] = useState(false);
const [retried, setRetried] = useState<Set<string>>(new Set());
const [openDetails, setOpenDetails] = useState<Set<string>>(new Set());
@@ -166,12 +168,12 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
prev ? { ...prev, linked_repos: result.linked_repos ?? prev.linked_repos } : prev);
setStatuses((prev) => {
const next = new Map(prev);
const pending = new Set(updatable.map((item) => item.name));
const pending = new Set(updatable.map(checkKey));
const checkedAt = new Date().toISOString();
for (const item of updatable) {
if (item.kind === 'skill' && result.linked_repos?.some((repo) => item.relPath === repo.name || item.relPath.startsWith(`${repo.name}/`))) {
next.delete(item.name);
pending.delete(item.name);
next.delete(checkKey(item));
pending.delete(checkKey(item));
}
}
@@ -187,8 +189,8 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
: { status: 'up-to-date', message: repo.message, checkedAt };
for (const item of updatable) {
if (repoOf(item) !== repo.name) continue;
next.set(item.name, repoStatus);
pending.delete(item.name);
next.set(checkKey(item), repoStatus);
pending.delete(checkKey(item));
}
}
@@ -197,12 +199,12 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
for (const skill of result.skills) {
const item = updatable.find((i) => !i.isInRepo && matchesCheckSkill(i, skill.name));
if (!item) continue;
next.set(item.name, {
status: skill.status === 'update_available' ? 'update-available' : skill.status === 'error' ? 'error' : 'up-to-date',
next.set(checkKey(item), {
status: skill.status === 'update_available' ? 'update-available' : skill.status === 'stale' ? 'stale' : skill.status === 'error' ? 'error' : 'up-to-date',
message: skill.message,
checkedAt,
});
pending.delete(item.name);
pending.delete(checkKey(item));
}
for (const name of pending) {
@@ -215,11 +217,12 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
const runCheck = useCallback(() => {
esRef.current?.close();
setChecking(true);
setPruned(0);
setRun(new Map());
setFinished(false);
setStatuses((prev) => {
const next = new Map(prev);
for (const item of updatable) next.set(item.name, { status: 'checking' });
for (const item of updatable) next.set(checkKey(item), { status: 'checking' });
return next;
});
esRef.current = api.checkStream(
@@ -235,7 +238,7 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
setStatuses((prev) => {
const next = new Map(prev);
const checkedAt = new Date().toISOString();
for (const item of updatable) next.set(item.name, { status: 'error', checkedAt });
for (const item of updatable) next.set(checkKey(item), { status: 'error', checkedAt });
return next;
});
setChecking(false);
@@ -261,7 +264,7 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
const hit = result.isRepo
? repoOf(item) === result.name
: !item.isInRepo && matchesCheckSkill(item, result.name);
if (hit) next.set(item.name, { ...status, message: result.message });
if (hit) next.set(checkKey(item), { ...status, message: result.message });
}
}
return next;
@@ -333,21 +336,50 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
}
}, [patchRun, invalidateSkillData, t]);
const rehydrate = useCallback(async () => {
setRehydrating(true);
// A finished install-missing banner collapses on its own unless something failed.
useEffect(() => {
if (missing.phase !== 'done' || missing.failed.size) return;
const id = setTimeout(missing.dismiss, 3000);
return () => clearTimeout(id);
}, [missing.phase, missing.failed.size, missing.dismiss]);
/* -- Prune (deleted upstream) -- */
const setPrune = useCallback((name: string, state?: 'working' | 'out') => setPruning((prev) => {
const next = new Map(prev);
if (state) next.set(name, state);
else next.delete(name);
return next;
}), []);
// Like `update --prune`: the skills go to trash in one request. Rows slide out, then their gap closes.
const prune = useCallback(async (list: UpdateUnit[]) => {
for (const u of list) setPrune(u.name, 'working');
let gone = list;
try {
const { results } = await api.rehydrateTrackedRepos();
const failed = results.filter((r) => r.action !== 'rehydrated');
if (failed.length > 0) toast(t('update.missingRepos.rehydratePartial', { count: failed.length }), 'error');
else toast(t('update.missingRepos.rehydrateSuccess', { count: results.length }), 'success');
void invalidate(queryClient, 'missingReposChanged');
invalidateSkillData();
const { results } = await api.batchUninstall({ names: list.map((u) => u.name), force: true });
const failed = results.filter((r) => !r.success);
if (failed.length) toast(failed[0].error ?? failed[0].name, 'error');
gone = list.filter((u) => !failed.some((r) => r.name === u.name));
for (const u of list) if (!gone.includes(u)) setPrune(u.name);
} catch (err) {
for (const u of list) setPrune(u.name);
toast((err as Error).message, 'error');
} finally {
setRehydrating(false);
return;
}
}, [t, toast, queryClient, invalidateSkillData]);
for (const u of gone) setPrune(u.name, 'out');
// ponytail: matches the .ss-collapse.out transition in components.css; change both together.
setTimeout(() => {
setStatuses((prev) => {
const next = new Map(prev);
for (const item of gone.flatMap((u) => u.items)) next.delete(checkKey(item));
return next;
});
for (const u of gone) setPrune(u.name);
setPruned((n) => n + gone.length);
void invalidate(queryClient, 'skillsUninstalled');
}, 520);
}, [setPrune, setStatuses, toast, queryClient]);
/* -- Render -- */
@@ -377,7 +409,8 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
return s === 'blocked' || s === 'error' || retried.has(name);
};
const failedUnits = showDone ? units.filter((u) => isTrouble(u.name)) : [];
const listUnits = failedUnits.length ? units.filter((u) => !isTrouble(u.name)) : units;
const staleUnits = units.filter((u) => unitCheck(statuses, u).status === 'stale' && !failedUnits.includes(u));
const listUnits = units.filter((u) => !failedUnits.includes(u) && !staleUnits.includes(u));
const runDone = [...run.values()].filter((s) => s.status !== 'pending' && s.status !== 'in-progress').length;
const current = running ? units.find((u) => run.get(u.name)?.status === 'in-progress') : undefined;
@@ -392,6 +425,8 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
return <span className="ss-st warn">{c.behind ? t('update.check.behind', { count: c.behind }) : t('update.check.behindFallback')}</span>;
case 'update-available':
return <span className="ss-st warn">{t('update.check.updateAvailable')}</span>;
case 'stale':
return <span className="ss-st warn">{t('update.check.stale')}</span>;
case 'dirty':
return <span className="ss-st warn" title={c.message}>{t('update.check.dirty')}</span>;
case 'up-to-date':
@@ -520,16 +555,87 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
</section>
)}
{missingRepos.length > 0 && (
<div className="ss-note warn">
<FolderX size={16} />
<div className="flex-1">
<b>{t('update.missingRepos.title', { count: missingRepos.length })}</b>{' '}
<span className="font-mono">{missingRepos.map((r) => r.name).join(', ')}</span>. {t('update.missingRepos.description')}
{showMissing && (() => {
const { done, summary, contents } = missing;
const failed = missing.failed.size;
return (
<div className={`ss-collapse ${missing.phase === 'closing' ? 'shut' : ''}`}>
<div className={`ss-note live items-center ${done && !failed ? 'ok' : 'warn'}`} aria-live="polite">
{missing.phase === 'running' ? <Loader2 size={16} className="animate-spin" />
: done ? (failed ? <CircleAlert size={16} className="ss-pop" /> : <Check size={16} strokeWidth={2.6} className="ss-pop" />)
: <FolderX size={16} />}
<div key={missing.phase} className="flex-1 min-w-0 animate-fade-in">
{missing.phase === 'running' ? (
<><b>{t('install.fromConfig.installing', { file: missing.file })}</b> {t('install.audited')}</>
) : done ? (
<><b>{summary}.</b> {t(failed ? 'install.fromConfig.failedHint' : 'install.fromConfig.syncHint', { file: missing.file })}</>
) : (
<>
<b>{t(plural('update.missingEntries.title', missing.entries.length), { count: missing.entries.length, file: missing.file })}</b>{' '}
({contents}): <span className="font-mono">{missing.entries.map((e) => e.name).join(', ')}</span>. {t('update.missingEntries.description')}
{missing.error && <span className="block text-bad">{missing.error}</span>}
</>
)}
</div>
{(missing.phase === 'idle' || (done && failed > 0)) && (
<Button variant="secondary" size="sm" onClick={missing.run}>
<Download size={14} />{t(done ? 'install.preview.retry' : 'update.missingEntries.install')}
</Button>
)}
{missing.phase === 'running' && <span className="ss-rowbar" aria-hidden />}
</div>
</div>
<Button variant="secondary" size="sm" loading={rehydrating} onClick={rehydrate}>{t('update.missingRepos.rehydrate')}</Button>
);
})()}
{(staleUnits.length > 0 || pruned > 0) && (
<div className={`ss-collapse ${staleUnits.length === 0 ? 'shut' : ''}`}>
<section className="flex flex-col gap-2" aria-labelledby="update-stale-title">
<div className="flex items-center gap-3">
<h2 id="update-stale-title" className="m-0 flex-1 text-[13px] font-semibold text-warn">
{t('update.stale.title', { count: staleUnits.filter((u) => pruning.get(u.name) !== 'out').length })}
</h2>
<Button
variant="secondary"
size="sm"
disabled={busy || pruning.size > 0}
onClick={() => void prune(staleUnits)}
>
<Trash2 size={14} />{t('update.stale.pruneAll')}
</Button>
</div>
<div className="ss-list">
{staleUnits.map((unit, i) => {
const p = pruning.get(unit.name);
return (
// Rows of one Prune all leave one after another.
<div key={unit.name} className={`ss-collapse ${p === 'out' ? 'out' : ''}`} style={{ transitionDelay: p === 'out' ? `${i * 60}ms` : undefined }}>
<div className={`ss-r ${p ? 'updating' : ''}`}>
{unitIcon(unit)}
{unitName(unit)}
{p ? (
<span className="inline-flex items-center gap-2 text-[13px] text-ink-2 animate-fade-in"><Loader2 size={13} className="animate-spin" />{t('update.updating.purging')}</span>
) : (
<>
<span className="ss-st warn">{t('update.check.stale')}</span>
<Button variant="secondary" size="sm" disabled={busy} onClick={() => void prune([unit])}>{t('update.updating.purge')}</Button>
</>
)}
{p && <span className="ss-rowbar" aria-hidden />}
</div>
</div>
);
})}
</div>
<p className="m-0 text-[13px] text-ink-3">{t('update.stale.note')}</p>
</section>
</div>
)}
{pruned > 0 && staleUnits.length === 0 && (
<p className="m-0 -mt-3 flex items-center gap-2 text-[13px] text-ink-2 animate-fade-in">
<Check size={15} strokeWidth={2.6} className="ss-pop text-ok" />{t(plural('update.stale.pruned', pruned), { count: pruned })}
</p>
)}
{failedUnits.length > 0 && (
<section className="flex flex-col gap-2 animate-fade-in" aria-labelledby="update-failed-title">
@@ -587,7 +693,7 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
)}
{units.length === 0 ? (
missingRepos.length === 0 && linkedRepos.length === 0 && (
!showMissing && linkedRepos.length === 0 && (
<EmptyState
icon={CircleCheck}
title={t(kind === 'agent' ? 'update.empty.agentsTitle' : 'update.empty.title')}
@@ -686,7 +792,9 @@ function isStoredCheckStatus(value: unknown): value is CheckItemStatus {
return typeof status === 'string'
&& CHECK_STATUS_VALUES.includes(status as CheckStatus)
&& status !== 'checking'
&& status !== 'unchecked';
&& status !== 'unchecked'
// Prune acts on stale, so it must come from a check this session, not an older or other project's cache.
&& status !== 'stale';
}
function isStaleError(message?: string): boolean {
@@ -182,7 +182,7 @@ skillshare install ~/my-skill --into frontend/react
# Works with --track too
skillshare install github.com/team/skills --track --into devops
# → ~/.config/skillshare/skills/devops/_skills/
# → ~/.config/skillshare/skills/devops/_team-skills/
# Works in project mode
skillshare install anthropics/skills -s pdf --into tools -p
@@ -192,7 +192,7 @@ skillshare install anthropics/skills -s pdf --into tools -p
After `skillshare sync`, targets show auto-flattened names:
- `frontend/pdf/` → `frontend__pdf`
- `frontend/react/my-skill/` → `frontend__react__my-skill`
- `devops/_skills/frontend/ui/` → `devops___skills__frontend__ui`
- `devops/_team-skills/frontend/ui/` → `devops___team-skills__frontend__ui`
:::tip
`--into` creates intermediate directories automatically. No need to `mkdir` first.
@@ -46,7 +46,7 @@ skillshare sync
```
**What happens:**
1. Repo is cloned to `~/.config/skillshare/skills/_team-skills/`
1. Repo is cloned to `~/.config/skillshare/skills/_team-shared-skills/`
2. `.git` directory is preserved
3. The clone directory is added to the managed `.gitignore` block so it stays machine-local and is not committed as a nested git repository
4. Entire repo is security-audited using active install threshold (`audit.block_threshold` or `--threshold`)
@@ -67,6 +67,8 @@ Tracked repos are prefixed with `_` to distinguish them from regular skills:
└── _team-skills/ # Tracked repo (underscore prefix)
```
The directory name comes from the owner and repo (`_<owner>-<repo>`), so `alice/skills` and `bob/skills` install as `_alice-skills` and `_bob-skills` instead of colliding. Use `--name` to pick a different name. Repos you installed earlier keep their current names.
A tracked repo installed with `--into` sits inside a folder, such as `devops/_team-skills/`. It is still treated as one repo: its skills are grouped under it, `status` counts them, and you update or uninstall it as `devops/_team-skills`. Below the top level, an `_` folder counts as a tracked repo only when it is a git clone, so a plain folder like `devops/_drafts/` stays a regular folder.
---
@@ -182,7 +182,7 @@ skillshare install ~/my-skill --into frontend/react
# --track でも使える
skillshare install github.com/team/skills --track --into devops
# → ~/.config/skillshare/skills/devops/_skills/
# → ~/.config/skillshare/skills/devops/_team-skills/
# Project mode でも使える
skillshare install anthropics/skills -s pdf --into tools -p
@@ -192,7 +192,7 @@ skillshare install anthropics/skills -s pdf --into tools -p
`skillshare sync` の後、Target には自動フラット化された名前が表示されます。
- `frontend/pdf/` → `frontend__pdf`
- `frontend/react/my-skill/` → `frontend__react__my-skill`
- `devops/_skills/frontend/ui/` → `devops___skills__frontend__ui`
- `devops/_team-skills/frontend/ui/` → `devops___team-skills__frontend__ui`
:::tip
`--into` は中間ディレクトリを自動的に作成します。先に `mkdir` する必要はありません。
@@ -46,7 +46,7 @@ skillshare sync
```
**何が起こるか:**
1. リポジトリが `~/.config/skillshare/skills/_team-skills/` にクローンされます
1. リポジトリが `~/.config/skillshare/skills/_team-shared-skills/` にクローンされます
2. `.git` ディレクトリが保持されます
3. クローンディレクトリは管理対象の `.gitignore` ブロックに追加され、マシンローカルにとどまり、ネストされた git リポジトリとしてコミットされないようになります
4. リポジトリ全体が、有効なインストールしきい値(`audit.block_threshold` または `--threshold`)を使ってセキュリティ監査されます
@@ -67,6 +67,8 @@ skillshare sync
└── _team-skills/ # Tracked repo (underscore prefix)
```
ディレクトリ名はオーナーとリポジトリ名から付けられます(`_<owner>-<repo>`)。そのため `alice/skills` と `bob/skills` はそれぞれ `_alice-skills` と `_bob-skills` としてインストールされ、衝突しません。別の名前にするには `--name` を使います。以前にインストールしたリポジトリは今の名前のままです。
`--into` でインストールした追跡リポジトリは、`devops/_team-skills/` のようにフォルダの中に置かれます。それでも 1 つのリポジトリとして扱われます。中の Skill はその下にまとめられ、`status` でも数えられ、更新やアンインストールには `devops/_team-skills` という名前を使います。最上位より下では、git clone された `_` フォルダだけが追跡リポジトリとみなされるため、`devops/_drafts/` のような普通のフォルダは通常のフォルダのままです。
---
@@ -182,7 +182,7 @@ skillshare install ~/my-skill --into frontend/react
# --track과 함께 사용도 가능
skillshare install github.com/team/skills --track --into devops
# → ~/.config/skillshare/skills/devops/_skills/
# → ~/.config/skillshare/skills/devops/_team-skills/
# 프로젝트 모드에서도 사용 가능
skillshare install anthropics/skills -s pdf --into tools -p
@@ -192,7 +192,7 @@ skillshare install anthropics/skills -s pdf --into tools -p
`skillshare sync` 이후, Target에는 자동 평탄화된 이름이 표시됩니다:
- `frontend/pdf/` → `frontend__pdf`
- `frontend/react/my-skill/` → `frontend__react__my-skill`
- `devops/_skills/frontend/ui/` → `devops___skills__frontend__ui`
- `devops/_team-skills/frontend/ui/` → `devops___team-skills__frontend__ui`
:::tip
`--into`는 중간 디렉터리를 자동으로 생성합니다. 먼저 `mkdir`을 할 필요가 없습니다.
@@ -46,7 +46,7 @@ skillshare sync
```
**일어나는 일:**
1. repo가 `~/.config/skillshare/skills/_team-skills/`로 clone됨
1. repo가 `~/.config/skillshare/skills/_team-shared-skills/`로 clone됨
2. `.git` 디렉터리가 보존됨
3. clone 디렉터리가 관리되는 `.gitignore` 블록에 추가되어 머신 로컬 상태로 유지되며, 중첩된 git repo로 커밋되지 않음
4. 활성 install 임계값(`audit.block_threshold` 또는 `--threshold`)을 사용해 전체 repo가 보안 감사됨
@@ -67,6 +67,8 @@ Tracked repo는 일반 skill과 구분하기 위해 `_` 접두사가 붙습니
└── _team-skills/ # Tracked repo (underscore prefix)
```
디렉터리 이름은 소유자와 repo 이름으로 정해집니다(`_<owner>-<repo>`). 그래서 `alice/skills`와 `bob/skills`는 각각 `_alice-skills`, `_bob-skills`로 설치되어 충돌하지 않습니다. 다른 이름을 쓰려면 `--name`을 사용하세요. 이전에 설치한 repo는 기존 이름을 유지합니다.
`--into`로 설치한 tracked repo는 `devops/_team-skills/`처럼 폴더 안에 놓입니다. 그래도 하나의 repo로 취급됩니다. 안에 있는 skill은 그 아래로 묶이고, `status`에서도 집계되며, 업데이트나 제거할 때는 `devops/_team-skills`라는 이름을 사용합니다. 최상위 아래에서는 git clone된 `_` 폴더만 tracked repo로 간주되므로, `devops/_drafts/` 같은 일반 폴더는 그대로 일반 폴더입니다.
---
@@ -182,7 +182,7 @@ skillshare install ~/my-skill --into frontend/react
# 也可搭配 --track 使用
skillshare install github.com/team/skills --track --into devops
# → ~/.config/skillshare/skills/devops/_skills/
# → ~/.config/skillshare/skills/devops/_team-skills/
# 在 Project mode 下也可使用
skillshare install anthropics/skills -s pdf --into tools -p
@@ -192,7 +192,7 @@ skillshare install anthropics/skills -s pdf --into tools -p
执行 `skillshare sync` 后,Target 会显示自动扁平化后的名称:
- `frontend/pdf/` → `frontend__pdf`
- `frontend/react/my-skill/` → `frontend__react__my-skill`
- `devops/_skills/frontend/ui/` → `devops___skills__frontend__ui`
- `devops/_team-skills/frontend/ui/` → `devops___team-skills__frontend__ui`
:::tip
`--into` 会自动创建中间目录,无需先手动 `mkdir`。
@@ -46,7 +46,7 @@ skillshare sync
```
**发生了什么:**
1. 仓库被克隆到 `~/.config/skillshare/skills/_team-skills/`
1. 仓库被克隆到 `~/.config/skillshare/skills/_team-shared-skills/`
2. 保留 `.git` 目录
3. 克隆目录会被加入受管理的 `.gitignore` 区块,使其保持本机专属,不会作为嵌套 Git 仓库被提交
4. 使用当前 install 阈值(`audit.block_threshold` 或 `--threshold`)对整个仓库进行安全审计
@@ -67,6 +67,8 @@ Tracked repos 会以 `_` 为前缀,以便与普通 Skill 区分:
└── _team-skills/ # Tracked Repo(下划线前缀)
```
文件夹名称取自所有者和仓库(`_<owner>-<repo>`),因此 `alice/skills` 和 `bob/skills` 会分别安装为 `_alice-skills` 和 `_bob-skills`,不会互相冲突。要换名称可以用 `--name`。之前安装的 repo 保留原来的名称。
用 `--into` 安装的 tracked repo 会放在文件夹里,例如 `devops/_team-skills/`。它仍然被视为一个 repo:其中的 Skill 会归在它下面,`status` 会统计这些 Skill,更新或卸载时使用 `devops/_team-skills` 这个名称。在第一层以下,只有 git clone 得到的 `_` 文件夹才算 tracked repo,因此像 `devops/_drafts/` 这样的普通文件夹仍是普通文件夹。
---
@@ -182,7 +182,7 @@ skillshare install ~/my-skill --into frontend/react
# 也適用於 --track
skillshare install github.com/team/skills --track --into devops
# → ~/.config/skillshare/skills/devops/_skills/
# → ~/.config/skillshare/skills/devops/_team-skills/
# 也適用於 Project mode
skillshare install anthropics/skills -s pdf --into tools -p
@@ -192,7 +192,7 @@ skillshare install anthropics/skills -s pdf --into tools -p
執行 `skillshare sync` 後,Targets 會顯示自動攤平後的名稱:
- `frontend/pdf/` → `frontend__pdf`
- `frontend/react/my-skill/` → `frontend__react__my-skill`
- `devops/_skills/frontend/ui/` → `devops___skills__frontend__ui`
- `devops/_team-skills/frontend/ui/` → `devops___team-skills__frontend__ui`
:::tip
`--into` 會自動建立中介目錄,不需要先手動 `mkdir`。
@@ -46,7 +46,7 @@ skillshare sync
```
**會發生什麼事:**
1. Repo 會被 clone 到 `~/.config/skillshare/skills/_team-skills/`
1. Repo 會被 clone 到 `~/.config/skillshare/skills/_team-shared-skills/`
2. `.git` 目錄會被保留
3. Clone 目錄會被加入受管理的 `.gitignore` 區塊,讓它保持機器本機、不會被當成巢狀 git repository 被 commit 進去
4. 整個 repo 會用當前生效的安裝門檻(`audit.block_threshold` 或 `--threshold`)進行安全稽核
@@ -67,6 +67,8 @@ Tracked repos 會以 `_` 為前綴,以便與一般 skills 區分:
└── _team-skills/ # Tracked repo (underscore prefix)
```
資料夾名稱取自擁有者與 repo(`_<owner>-<repo>`),所以 `alice/skills` 和 `bob/skills` 會分別安裝成 `_alice-skills` 與 `_bob-skills`,不會互相衝突。要換名稱可以用 `--name`。先前安裝的 repo 維持原本的名稱。
用 `--into` 安裝的 tracked repo 會放在資料夾裡,例如 `devops/_team-skills/`。它仍然視為一個 repo:裡面的 skills 會歸在它底下,`status` 會計入這些 skills,更新或解除安裝時使用 `devops/_team-skills` 這個名稱。在第一層以下,只有 git clone 出來的 `_` 資料夾才算 tracked repo,所以像 `devops/_drafts/` 這樣的一般資料夾仍是普通資料夾。
---