diff --git a/internal/install/install_update.go b/internal/install/install_update.go index 734df8c07..1d0e29b82 100644 --- a/internal/install/install_update.go +++ b/internal/install/install_update.go @@ -3,7 +3,9 @@ package install import ( "fmt" "os" + "os/exec" "path/filepath" + "strings" "skillshare/internal/audit" ) @@ -15,7 +17,7 @@ func handleUpdate(source *Source, destPath string, result *InstallResult, opts I // installs. Legacy installs of repo-root orchestrators (root SKILL.md plus // child skills) used to be full repository clones; migrate those through the // discovery installer so the root skill becomes SKILL.md-only. - if source.IsGit() && !source.HasSubdir() && IsGitRepo(destPath) { + if source.IsGit() && !source.HasSubdir() && IsGitRepo(destPath) && checkoutOnBranch(destPath, source.Branch) { if hasDescendantSkillFile(destPath) { migrated, err := updateRepoRootOrchestrator(source, destPath, result, opts) if migrated || err != nil { @@ -143,6 +145,11 @@ func handleUpdate(source *Source, destPath string, result *InstallResult, opts I // Installation failed - original skill is preserved return nil, err } + // A branch or upstream commit that dropped SKILL.md would replace a skill + // with a plain folder. + if skillFileExists(destPath) && !skillFileExists(tempDest) { + return nil, fmt.Errorf("the new version has no SKILL.md; kept the installed skill") + } // Propagate audit results and warnings from inner install if innerResult != nil { @@ -290,3 +297,14 @@ func repoRootOrchestratorRoot(discovery *DiscoveryResult) (SkillInfo, bool) { } return SkillInfo{}, false } + +// checkoutOnBranch reports whether a pull keeps a checkout on branch. An empty +// branch is the remote default the clone tracks, and a commit pin is checked +// out detached on purpose; any other branch needs a fresh clone. +func checkoutOnBranch(repoPath, branch string) bool { + if branch == "" || IsCommitSHA(branch) { + return true + } + out, err := exec.Command("git", "-C", repoPath, "rev-parse", "--abbrev-ref", "HEAD").Output() + return err == nil && strings.TrimSpace(string(out)) == branch +} diff --git a/internal/install/install_update_test.go b/internal/install/install_update_test.go index c2510a3c5..99d506e2e 100644 --- a/internal/install/install_update_test.go +++ b/internal/install/install_update_test.go @@ -281,3 +281,80 @@ func TestUpdate_GitSkillReinstallKeepsLocalEditWhenFetchFails(t *testing.T) { t.Fatalf("local edit lost after failed update: %q", got) } } + +// writeCommit writes SKILL.md (or removes it for an empty body) under rel and commits. +func writeCommit(t *testing.T, repo, rel, body string) { + t.Helper() + dir := filepath.Join(repo, rel) + if err := os.MkdirAll(dir, 0755); err != nil { + t.Fatal(err) + } + file := filepath.Join(dir, "SKILL.md") + if body == "" { + if err := os.Remove(file); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("no skill here\n"), 0644); err != nil { + t.Fatal(err) + } + } else if err := os.WriteFile(file, []byte(body), 0644); err != nil { + t.Fatal(err) + } + gitAdd(t, repo, ".") + gitCommit(t, repo, "change "+rel) +} + +func TestUpdate_RootGitSkillFollowsAnotherBranch(t *testing.T) { + repo := initTestRepo(t) + writeCommit(t, repo, ".", "---\nname: demo\n---\n# default\n") + runGit(t, repo, "branch", "other") + runGit(t, repo, "checkout", "other") + writeCommit(t, repo, ".", "---\nname: demo\n---\n# other\n") + runGit(t, repo, "checkout", "-") + sourceDir := t.TempDir() + dest := filepath.Join(sourceDir, "demo") + if err := cloneRepo("file://"+repo, dest, "", false, nil); err != nil { + t.Fatalf("clone failed: %v", err) + } + source, err := ParseSource("file://" + repo) + if err != nil { + t.Fatal(err) + } + source.Branch = "other" + + if _, err := Install(source, dest, InstallOptions{Update: true, Force: true, SourceDir: sourceDir, SkipAudit: true}); err != nil { + t.Fatalf("update failed: %v", err) + } + if got, _ := os.ReadFile(filepath.Join(dest, "SKILL.md")); !strings.Contains(string(got), "# other") { + t.Fatalf("SKILL.md = %q, want the other branch", got) + } +} + +func TestUpdate_CandidateWithoutSkillFileKeepsTheInstall(t *testing.T) { + repo := initTestRepo(t) + writeCommit(t, repo, "skills/foo", "---\nname: foo\n---\n# kept\n") + runGit(t, repo, "checkout", "-b", "empty") + writeCommit(t, repo, "skills/foo", "") + runGit(t, repo, "checkout", "-") + sourceDir := t.TempDir() + dest := filepath.Join(sourceDir, "foo") + source, err := ParseSource("file://" + repo + "//skills/foo") + if err != nil { + t.Fatal(err) + } + if _, err := Install(source, dest, InstallOptions{SourceDir: sourceDir, SkipAudit: true}); err != nil { + t.Fatalf("install failed: %v", err) + } + // An update parses the recorded source again; the install pinned this one's commit. + if source, err = ParseSource("file://" + repo + "//skills/foo"); err != nil { + t.Fatal(err) + } + source.Branch = "empty" + + if _, err := Install(source, dest, InstallOptions{Update: true, Force: true, SourceDir: sourceDir, SkipAudit: true}); err == nil { + t.Fatal("expected the update to refuse a version without SKILL.md") + } + if got, _ := os.ReadFile(filepath.Join(dest, "SKILL.md")); !strings.Contains(string(got), "# kept") { + t.Fatalf("SKILL.md = %q, want the installed version kept", got) + } +} diff --git a/internal/server/handler_update.go b/internal/server/handler_update.go index 68ce4f4e5..f218acdd8 100644 --- a/internal/server/handler_update.go +++ b/internal/server/handler_update.go @@ -24,6 +24,8 @@ type updateRequest struct { Force bool `json:"force"` All bool `json:"all"` SkipAudit bool `json:"skipAudit"` + // Branch reinstalls one skill from this branch of its recorded source. + Branch string `json:"branch,omitempty"` } type updateResultItem struct { @@ -65,6 +67,11 @@ func (s *Server) handleUpdate(w http.ResponseWriter, r *http.Request) { return } + if body.Branch != "" && (body.All || body.Kind == "agent") { + writeError(w, http.StatusBadRequest, "branch applies to a single skill only") + return + } + if body.All { results := s.updateAll(body.Force, body.SkipAudit) total := len(results) @@ -117,7 +124,12 @@ func (s *Server) handleUpdate(w http.ResponseWriter, r *http.Request) { return } - result := s.updateSingleByKind(body.Name, body.Kind, body.Force, body.SkipAudit) + var result updateResultItem + if body.Branch != "" { + result = s.switchSkillBranch(body.Name, body.Branch, body.Force, body.SkipAudit) + } else { + result = s.updateSingleByKind(body.Name, body.Kind, body.Force, body.SkipAudit) + } status := "ok" msg := "" if result.Action == "error" { @@ -130,12 +142,16 @@ func (s *Server) handleUpdate(w http.ResponseWriter, r *http.Request) { status = "partial" msg = result.Message } - s.writeOpsLog("update", status, start, map[string]any{ + logArgs := map[string]any{ "name": body.Name, "force": body.Force, "skip_audit": body.SkipAudit, "scope": "ui", - }, msg) + } + if body.Branch != "" { + logArgs["branch"] = body.Branch + } + s.writeOpsLog("update", status, start, logArgs, msg) writeJSON(w, map[string]any{"results": []updateResultItem{result}}) } @@ -381,7 +397,39 @@ func trackedBlockMessage(e *install.AuditGateError) string { return fmt.Sprintf("blocked by security audit — findings at/above %s detected (%s)", e.Threshold, e.RollbackNote()) } +// switchSkillBranch reinstalls a skill from another branch of its recorded +// source. Tracked repos change branch with git checkout instead. +func (s *Server) switchSkillBranch(name, branch string, force, skipAudit bool) updateResultItem { + name = path.Clean(filepath.ToSlash(name)) + skillPath := filepath.Join(s.cfg.EffectiveSkillsSource(), name) + if entry := s.skillsStore.GetByPath(name); entry == nil || entry.Source == "" || entry.Tracked || install.IsTrackedCheckout(skillPath) { + return updateResultItem{Name: name, Action: "error", Message: "only a skill installed from a remote source can switch branch"} + } + walk := s.skillsWalk() + result := s.reinstallRegularSkill(name, skillPath, branch, force, skipAudit, walk.Follow) + if result.Action == "updated" && s.IsProjectMode() { + // config.yaml declares the branch teammates install from, so it follows + // the switch; other declarations stay as the shared file has them. + for i := range s.projectCfg.Skills { + if skill := &s.projectCfg.Skills[i]; skill.FullName() == name { + skill.Branch = branch + if err := s.projectCfg.Save(s.projectRoot); err != nil { + result.Message += "; failed to record the branch in config.yaml: " + err.Error() + } + break + } + } + } + return result +} + func (s *Server) updateRegularSkill(name, skillPath string, force, skipAudit bool, follow ...*sourcewalk.Follow) updateResultItem { + return s.reinstallRegularSkill(name, skillPath, "", force, skipAudit, follow...) +} + +// reinstallRegularSkill reinstalls a skill from its recorded source, from +// branch when set and from the recorded branch otherwise. +func (s *Server) reinstallRegularSkill(name, skillPath, branch string, force, skipAudit bool, follow ...*sourcewalk.Follow) updateResultItem { if refusal := s.refuseFollowedCheckout(name, skillPath, follow); refusal != nil { return *refusal } @@ -400,7 +448,10 @@ func (s *Server) updateRegularSkill(name, skillPath string, force, skipAudit boo Message: "invalid source: " + err.Error(), } } - source.ApplyRecordedBranch(entry.Branch) + if branch == "" { + branch = entry.Branch + } + source.ApplyRecordedBranch(branch) sourceDir := s.cfg.EffectiveSkillsSource() opts := install.InstallOptions{ diff --git a/internal/server/handler_update_branch_test.go b/internal/server/handler_update_branch_test.go new file mode 100644 index 000000000..5df3d305d --- /dev/null +++ b/internal/server/handler_update_branch_test.go @@ -0,0 +1,129 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/config" + "skillshare/internal/install" +) + +// installFromDev installs skills/foo into src from the dev branch of a remote +// whose main branch has its own skills/foo, and returns the recorded source. +func installFromDev(t *testing.T, s *Server, src string) string { + t.Helper() + remote := t.TempDir() + initGitRepo(t, remote) + runGit(t, remote, "branch", "-M", "main") + writeSkill := func(body string) { + dir := filepath.Join(remote, "skills", "foo") + if err := os.MkdirAll(dir, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("---\nname: foo\n---\n"+body+"\n"), 0644); err != nil { + t.Fatal(err) + } + runGit(t, remote, "add", ".") + runGit(t, remote, "commit", "-m", body) + } + writeSkill("main body") + runGit(t, remote, "checkout", "-b", "dev") + writeSkill("dev body") + runGit(t, remote, "checkout", "main") + + local := filepath.Join(src, "foo") + if err := os.MkdirAll(local, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(local, "SKILL.md"), []byte("---\nname: foo\n---\ndev body\n"), 0644); err != nil { + t.Fatal(err) + } + source := "file://" + remote + "//skills/foo" + s.skillsStore = install.NewMetadataStore() + s.skillsStore.Set("foo", &install.MetadataEntry{ + Source: source, + RepoURL: "file://" + remote, + Subdir: "skills/foo", + Branch: "dev", + }) + if err := s.skillsStore.Save(src); err != nil { + t.Fatal(err) + } + return source +} + +func postUpdate(s *Server, body string) *httptest.ResponseRecorder { + rr := httptest.NewRecorder() + s.handleUpdate(rr, httptest.NewRequest(http.MethodPost, "/api/update", strings.NewReader(body))) + return rr +} + +func TestHandleUpdate_BranchReinstallsFromThatBranch(t *testing.T) { + s, src := newTestServer(t) + installFromDev(t, s, src) + + results := updateResults(t, postUpdate(s, `{"name":"foo","branch":"main"}`), false) + if len(results) != 1 || results[0].Action != "updated" { + t.Fatalf("results = %+v, want one updated", results) + } + got, _ := os.ReadFile(filepath.Join(src, "foo", "SKILL.md")) + stored, err := install.LoadMetadata(src) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(got), "main body") || stored.GetByPath("foo").Branch != "main" { + t.Fatalf("SKILL.md = %q, recorded branch = %q; want main's content and branch", got, stored.GetByPath("foo").Branch) + } +} + +// Only the switched skill's declaration moves; another skill whose local record +// lags the shared config keeps what config.yaml says. +func TestHandleUpdate_BranchMovesOnlyThatProjectDeclaration(t *testing.T) { + s, root := newTestProjectServerWithExtras(t, nil) + src := s.cfg.EffectiveSkillsSource() + source := installFromDev(t, s, src) + s.skillsStore.Set("bar", &install.MetadataEntry{Source: "github.com/o/r/bar", Branch: "old"}) + if err := s.skillsStore.Save(src); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(src, "bar"), 0755); err != nil { + t.Fatal(err) + } + s.projectCfg.Skills = []config.SkillEntry{ + {Name: "foo", Source: source, Branch: "dev"}, + {Name: "bar", Source: "github.com/o/r/bar", Branch: "new"}, + } + if err := s.projectCfg.Save(root); err != nil { + t.Fatal(err) + } + + updateResults(t, postUpdate(s, `{"name":"foo","branch":"main"}`), false) + + loaded, err := config.LoadProject(root) + if err != nil { + t.Fatal(err) + } + got := map[string]string{} + for _, skill := range loaded.Skills { + got[skill.Name] = skill.Branch + } + if got["foo"] != "main" || got["bar"] != "new" { + t.Fatalf("declared branches = %v, want foo on main and bar left on new", got) + } +} + +func TestHandleUpdate_BranchNeedsOneSkill(t *testing.T) { + s, _ := newTestServer(t) + for _, body := range []string{ + `{"all":true,"branch":"main"}`, + `{"name":"foo","kind":"agent","branch":"main"}`, + } { + if rr := postUpdate(s, body); rr.Code != http.StatusBadRequest { + t.Errorf("%s: status = %d, want 400", body, rr.Code) + } + } +} diff --git a/ui/src/api/update.ts b/ui/src/api/update.ts index 127b81498..8cd752f6c 100644 --- a/ui/src/api/update.ts +++ b/ui/src/api/update.ts @@ -2,7 +2,7 @@ import { apiFetch, BASE, createSSEStream } from './http'; import type { UpdateResultItem, UpdateStreamSummary } from './types/update'; export const updateApi = { - update: (opts: { name?: string; kind?: 'skill' | 'agent'; force?: boolean; all?: boolean; skipAudit?: boolean }) => + update: (opts: { name?: string; kind?: 'skill' | 'agent'; force?: boolean; all?: boolean; skipAudit?: boolean; branch?: string }) => apiFetch<{ results: UpdateResultItem[] }>('/update', { method: 'POST', body: JSON.stringify(opts), diff --git a/ui/src/components/resources/TreeDetailPane.tsx b/ui/src/components/resources/TreeDetailPane.tsx index 22b875b80..e4a8dfee5 100644 --- a/ui/src/components/resources/TreeDetailPane.tsx +++ b/ui/src/components/resources/TreeDetailPane.tsx @@ -83,6 +83,7 @@ export default function TreeDetailPane({ kind, subject, busy, onToggleAll, onTog path = skill.relPath.slice(0, Math.max(0, skill.relPath.lastIndexOf('/'))); title = skill.name; tracked = skill.isInRepo; + meta = skill.isInRepo ? '' : skill.branch ?? ''; } else { title = t('resources.tree.pane.selected', { what: count(skills.length) }); } diff --git a/ui/src/i18n/locales/de.json b/ui/src/i18n/locales/de.json index 7e77a3fa4..651cccd5b 100644 --- a/ui/src/i18n/locales/de.json +++ b/ui/src/i18n/locales/de.json @@ -1278,6 +1278,11 @@ "resourceDetail.meta.tools": "Tools", "resourceDetail.meta.tracked": "Getrackt", "resourceDetail.meta.trackedBranch": "Ja, Branch {branch}", + "resourceDetail.meta.branch": "Branch", + "resourceDetail.branch.title": "Branch wechseln", + "resourceDetail.branch.message": "{name} aus {branch} neu installieren? Die Dateien werden durch die Version aus diesem Branch ersetzt. Hat {branch} diesen Skill nicht, bleibt die aktuelle Installation erhalten.", + "resourceDetail.branch.confirm": "Wechseln und neu installieren", + "resourceDetail.toast.switchedBranch": "{name} auf {branch} umgestellt{auditInfo}", "resourceDetail.meta.words.one": "{count} Wort", "resourceDetail.meta.words.other": "{count} Wörter", "resourceDetail.meta.yes": "Ja", diff --git a/ui/src/i18n/locales/en.json b/ui/src/i18n/locales/en.json index 844f2581c..b34f52fc9 100644 --- a/ui/src/i18n/locales/en.json +++ b/ui/src/i18n/locales/en.json @@ -1278,6 +1278,11 @@ "resourceDetail.meta.tools": "Tools", "resourceDetail.meta.tracked": "Tracked", "resourceDetail.meta.trackedBranch": "Yes, branch {branch}", + "resourceDetail.meta.branch": "Branch", + "resourceDetail.branch.title": "Switch branch", + "resourceDetail.branch.message": "Reinstall {name} from {branch}? Its files are replaced with that branch's version. If {branch} has no such skill, the current install stays.", + "resourceDetail.branch.confirm": "Switch and reinstall", + "resourceDetail.toast.switchedBranch": "Switched {name} to {branch}{auditInfo}", "resourceDetail.meta.words.one": "{count} word", "resourceDetail.meta.words.other": "{count} words", "resourceDetail.meta.yes": "Yes", diff --git a/ui/src/i18n/locales/es.json b/ui/src/i18n/locales/es.json index 33fe44398..f328d7f5c 100644 --- a/ui/src/i18n/locales/es.json +++ b/ui/src/i18n/locales/es.json @@ -1278,6 +1278,11 @@ "resourceDetail.meta.tools": "Herramientas", "resourceDetail.meta.tracked": "Rastreado", "resourceDetail.meta.trackedBranch": "Sí, rama {branch}", + "resourceDetail.meta.branch": "Rama", + "resourceDetail.branch.title": "Cambiar de rama", + "resourceDetail.branch.message": "¿Reinstalar {name} desde {branch}? Sus archivos se reemplazan por la versión de esa rama. Si {branch} no tiene este skill, se conserva la instalación actual.", + "resourceDetail.branch.confirm": "Cambiar y reinstalar", + "resourceDetail.toast.switchedBranch": "{name} cambiado a {branch}{auditInfo}", "resourceDetail.meta.words.one": "{count} palabra", "resourceDetail.meta.words.other": "{count} palabras", "resourceDetail.meta.yes": "Sí", diff --git a/ui/src/i18n/locales/fa.json b/ui/src/i18n/locales/fa.json index ac4f7e677..16132b947 100644 --- a/ui/src/i18n/locales/fa.json +++ b/ui/src/i18n/locales/fa.json @@ -1278,6 +1278,11 @@ "resourceDetail.meta.tools": "ابزارها", "resourceDetail.meta.tracked": "ردیابی‌شده", "resourceDetail.meta.trackedBranch": "بله، شاخهٔ {branch}", + "resourceDetail.meta.branch": "شاخه", + "resourceDetail.branch.title": "تغییر شاخه", + "resourceDetail.branch.message": "{name} از {branch} دوباره نصب شود؟ فایل‌های آن با نسخهٔ همان شاخه جایگزین می‌شوند. اگر {branch} این skill را نداشته باشد، نصب فعلی باقی می‌ماند.", + "resourceDetail.branch.confirm": "تغییر و نصب دوباره", + "resourceDetail.toast.switchedBranch": "{name} به {branch} تغییر کرد{auditInfo}", "resourceDetail.meta.words.one": "{count} واژه", "resourceDetail.meta.words.other": "{count} واژه", "resourceDetail.meta.yes": "بله", diff --git a/ui/src/i18n/locales/fr.json b/ui/src/i18n/locales/fr.json index 61799f910..5339acf86 100644 --- a/ui/src/i18n/locales/fr.json +++ b/ui/src/i18n/locales/fr.json @@ -1278,6 +1278,11 @@ "resourceDetail.meta.tools": "Outils", "resourceDetail.meta.tracked": "Suivi", "resourceDetail.meta.trackedBranch": "Oui, branche {branch}", + "resourceDetail.meta.branch": "Branche", + "resourceDetail.branch.title": "Changer de branche", + "resourceDetail.branch.message": "Réinstaller {name} depuis {branch} ? Ses fichiers sont remplacés par la version de cette branche. Si {branch} n'a pas ce skill, l'installation actuelle est conservée.", + "resourceDetail.branch.confirm": "Changer et réinstaller", + "resourceDetail.toast.switchedBranch": "{name} est passé sur {branch}{auditInfo}", "resourceDetail.meta.words.one": "{count} mot", "resourceDetail.meta.words.other": "{count} mots", "resourceDetail.meta.yes": "Oui", diff --git a/ui/src/i18n/locales/id.json b/ui/src/i18n/locales/id.json index 44240fd00..957dcf2e2 100644 --- a/ui/src/i18n/locales/id.json +++ b/ui/src/i18n/locales/id.json @@ -1278,6 +1278,11 @@ "resourceDetail.meta.tools": "Tools", "resourceDetail.meta.tracked": "Dilacak", "resourceDetail.meta.trackedBranch": "Ya, branch {branch}", + "resourceDetail.meta.branch": "Branch", + "resourceDetail.branch.title": "Ganti branch", + "resourceDetail.branch.message": "Pasang ulang {name} dari {branch}? File-nya diganti dengan versi dari branch itu. Jika {branch} tidak punya skill ini, instalasi saat ini tetap dipertahankan.", + "resourceDetail.branch.confirm": "Ganti dan pasang ulang", + "resourceDetail.toast.switchedBranch": "{name} dipindah ke {branch}{auditInfo}", "resourceDetail.meta.words.one": "{count} kata", "resourceDetail.meta.words.other": "{count} kata", "resourceDetail.meta.yes": "Ya", diff --git a/ui/src/i18n/locales/ja.json b/ui/src/i18n/locales/ja.json index 8c80aa6de..1daf573d9 100644 --- a/ui/src/i18n/locales/ja.json +++ b/ui/src/i18n/locales/ja.json @@ -1278,6 +1278,11 @@ "resourceDetail.meta.tools": "ツール", "resourceDetail.meta.tracked": "追跡", "resourceDetail.meta.trackedBranch": "はい、ブランチ {branch}", + "resourceDetail.meta.branch": "ブランチ", + "resourceDetail.branch.title": "ブランチを切り替え", + "resourceDetail.branch.message": "{branch} から {name} を再インストールしますか?ファイルはそのブランチの版に置き換わります。{branch} にこの skill がない場合は、現在のインストールがそのまま残ります。", + "resourceDetail.branch.confirm": "切り替えて再インストール", + "resourceDetail.toast.switchedBranch": "{name} を {branch} に切り替えました{auditInfo}", "resourceDetail.meta.words.one": "{count} 語", "resourceDetail.meta.words.other": "{count} 語", "resourceDetail.meta.yes": "はい", diff --git a/ui/src/i18n/locales/ko.json b/ui/src/i18n/locales/ko.json index 977e3137a..c9910df6c 100644 --- a/ui/src/i18n/locales/ko.json +++ b/ui/src/i18n/locales/ko.json @@ -1278,6 +1278,11 @@ "resourceDetail.meta.tools": "도구", "resourceDetail.meta.tracked": "추적", "resourceDetail.meta.trackedBranch": "예, 브랜치 {branch}", + "resourceDetail.meta.branch": "브랜치", + "resourceDetail.branch.title": "브랜치 전환", + "resourceDetail.branch.message": "{branch}에서 {name}을(를) 다시 설치할까요? 파일이 해당 브랜치의 버전으로 바뀝니다. {branch}에 이 skill이 없으면 현재 설치가 그대로 유지됩니다.", + "resourceDetail.branch.confirm": "전환하고 다시 설치", + "resourceDetail.toast.switchedBranch": "{name}을(를) {branch}(으)로 전환했습니다{auditInfo}", "resourceDetail.meta.words.one": "{count}단어", "resourceDetail.meta.words.other": "{count}단어", "resourceDetail.meta.yes": "예", diff --git a/ui/src/i18n/locales/pt-BR.json b/ui/src/i18n/locales/pt-BR.json index 8c560e211..15a42c0de 100644 --- a/ui/src/i18n/locales/pt-BR.json +++ b/ui/src/i18n/locales/pt-BR.json @@ -1278,6 +1278,11 @@ "resourceDetail.meta.tools": "Ferramentas", "resourceDetail.meta.tracked": "Rastreado", "resourceDetail.meta.trackedBranch": "Sim, branch {branch}", + "resourceDetail.meta.branch": "Branch", + "resourceDetail.branch.title": "Trocar de branch", + "resourceDetail.branch.message": "Reinstalar {name} a partir de {branch}? Os arquivos serão substituídos pela versão desse branch. Se {branch} não tiver esse skill, a instalação atual é mantida.", + "resourceDetail.branch.confirm": "Trocar e reinstalar", + "resourceDetail.toast.switchedBranch": "{name} trocado para {branch}{auditInfo}", "resourceDetail.meta.words.one": "{count} palavra", "resourceDetail.meta.words.other": "{count} palavras", "resourceDetail.meta.yes": "Sim", diff --git a/ui/src/i18n/locales/zh-CN.json b/ui/src/i18n/locales/zh-CN.json index ef9bf7719..da289c5df 100644 --- a/ui/src/i18n/locales/zh-CN.json +++ b/ui/src/i18n/locales/zh-CN.json @@ -1278,6 +1278,11 @@ "resourceDetail.meta.tools": "工具", "resourceDetail.meta.tracked": "跟踪", "resourceDetail.meta.trackedBranch": "是,分支 {branch}", + "resourceDetail.meta.branch": "分支", + "resourceDetail.branch.title": "切换分支", + "resourceDetail.branch.message": "要从 {branch} 重新安装 {name} 吗?它的文件会替换为该分支的版本。如果 {branch} 没有这个 skill,会保留当前的安装。", + "resourceDetail.branch.confirm": "切换并重新安装", + "resourceDetail.toast.switchedBranch": "已将 {name} 切换到 {branch}{auditInfo}", "resourceDetail.meta.words.one": "{count} 词", "resourceDetail.meta.words.other": "{count} 词", "resourceDetail.meta.yes": "是", diff --git a/ui/src/i18n/locales/zh-TW.json b/ui/src/i18n/locales/zh-TW.json index f7c29f595..966663f8f 100644 --- a/ui/src/i18n/locales/zh-TW.json +++ b/ui/src/i18n/locales/zh-TW.json @@ -1278,6 +1278,11 @@ "resourceDetail.meta.tools": "工具", "resourceDetail.meta.tracked": "追蹤", "resourceDetail.meta.trackedBranch": "是,分支 {branch}", + "resourceDetail.meta.branch": "分支", + "resourceDetail.branch.title": "切換分支", + "resourceDetail.branch.message": "要從 {branch} 重新安裝 {name} 嗎?它的檔案會換成該分支的版本。如果 {branch} 沒有這個 skill,會保留目前的安裝。", + "resourceDetail.branch.confirm": "切換並重新安裝", + "resourceDetail.toast.switchedBranch": "已將 {name} 切換到 {branch}{auditInfo}", "resourceDetail.meta.words.one": "{count} 字", "resourceDetail.meta.words.other": "{count} 字", "resourceDetail.meta.yes": "是", diff --git a/ui/src/lib/queryEvents.test.ts b/ui/src/lib/queryEvents.test.ts index f9ae2a6cb..a9551a2fd 100644 --- a/ui/src/lib/queryEvents.test.ts +++ b/ui/src/lib/queryEvents.test.ts @@ -70,6 +70,7 @@ const TARGETS: Label[] = [...T, 'projects', 'config', 'overview', 'diff', 'syncM const stale: Record = { skillsChanged: [...S, 'overview', 'diff'], + skillBranchSwitched: [...S, 'overview', 'diff', 'config'], skillEdited: { args: ['a'], stale: S }, installDialogClosed: S, reposChanged: [...S, 'overview', 'trash'], diff --git a/ui/src/lib/queryEvents.ts b/ui/src/lib/queryEvents.ts index 12d6bdf04..302495d87 100644 --- a/ui/src/lib/queryEvents.ts +++ b/ui/src/lib/queryEvents.ts @@ -17,6 +17,8 @@ const ignoreFile = [k.diff(), k.overview, k.skills.all, k.doctor]; const events = { // Skills and agents skillsChanged: () => keys(k.skills.all, k.overview, k.diff()), + // A project's config.yaml declares the branch, so the config editor reloads too. + skillBranchSwitched: () => keys(k.skills.all, k.overview, k.diff(), k.config), // The list shows frontmatter (description, manual only), so an edit refreshes it too. skillEdited: (name: string) => keys(k.skills.all, k.skills.detail(name)), installDialogClosed: () => keys(k.skills.all), diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts index 2995a85e3..6eb2b9469 100644 --- a/ui/src/lib/queryKeys.ts +++ b/ui/src/lib/queryKeys.ts @@ -161,4 +161,5 @@ export const staleTimes = { doctor: 60 * 1000, // 1min — health checks skillignore: 5 * 60 * 1000, // 5min — rarely changes agentignore: 5 * 60 * 1000, // 5min — rarely changes + refs: 5 * 60 * 1000, // 5min — a source's branches and tags (ls-remote) }; diff --git a/ui/src/pages/ResourceDetailPage.test.tsx b/ui/src/pages/ResourceDetailPage.test.tsx index a5f72af34..3d48d1e1b 100644 --- a/ui/src/pages/ResourceDetailPage.test.tsx +++ b/ui/src/pages/ResourceDetailPage.test.tsx @@ -4,14 +4,16 @@ import userEvent from '@testing-library/user-event'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { expect, it, vi } from 'vitest'; import { api, type Skill } from '../api/client'; +import { hubRefs } from '../api/hubDrafts'; import { I18nProvider } from '../i18n'; import { ToastProvider } from '../components/Toast'; import ResourceDetailPage from './ResourceDetailPage'; vi.mock('../api/client', async (load) => ({ ...await load(), api: { getSyncMatrix: vi.fn(), listTargets: vi.fn(), getResource: vi.fn(), listSkills: vi.fn(), - auditSkill: vi.fn(), diff: vi.fn(), batchUninstall: vi.fn(), moveResources: vi.fn(), + auditSkill: vi.fn(), diff: vi.fn(), batchUninstall: vi.fn(), moveResources: vi.fn(), update: vi.fn(), } })); +vi.mock('../api/hubDrafts', () => ({ hubRefs: vi.fn() })); it('uninstalls only the linked skill from its detail page', async () => { const user = userEvent.setup(); @@ -106,3 +108,32 @@ it('keeps the move result open after the old name stops loading, and goes to the await user.click(screen.getByRole('button', { name: 'Later' })); await waitFor(() => expect(api.getResource).toHaveBeenCalledWith('archive__demo', undefined)); }); + +it('reinstalls from the default branch by name only after confirming', async () => { + const user = userEvent.setup(); + const remote: Skill = { + name: 'foo', kind: 'skill', flatName: 'foo', relPath: 'foo', sourcePath: '/skills/foo', isInRepo: false, + source: 'github.com/o/r/skills/foo', repoUrl: 'https://github.com/o/r.git', branch: 'dev', + }; + vi.mocked(api.getResource).mockResolvedValue({ resource: remote, skillMdContent: '', files: [] }); + vi.mocked(api.listSkills).mockResolvedValue({ resources: [remote] }); + vi.mocked(api.listTargets).mockResolvedValue({ targets: [], sourceSkillCount: 1 }); + vi.mocked(api.getSyncMatrix).mockResolvedValue({ entries: [] } as never); + vi.mocked(api.diff).mockResolvedValue({ diffs: [] } as never); + vi.mocked(api.auditSkill).mockResolvedValue({ result: { findings: [] } } as never); + vi.mocked(hubRefs).mockResolvedValue({ pinnable: true, current: '', defaultBranch: 'main', branches: ['dev', 'main'], tags: ['v1'] }); + vi.mocked(api.update).mockResolvedValue({ results: [{ name: 'foo', action: 'updated' }] } as never); + render( + + + } /> + + + ); + await user.click(await screen.findByRole('combobox', { name: 'Branch' })); + await user.click(await screen.findByRole('option', { name: /^Default branch/ })); + const dialog = await screen.findByRole('dialog', { name: 'Switch branch' }); + expect(api.update).not.toHaveBeenCalled(); + await user.click(within(dialog).getByRole('button', { name: 'Switch and reinstall' })); + await waitFor(() => expect(api.update).toHaveBeenCalledWith({ name: 'foo', kind: 'skill', skipAudit: false, force: false, branch: 'main' })); +}); diff --git a/ui/src/pages/ResourceDetailPage.tsx b/ui/src/pages/ResourceDetailPage.tsx index da02621d4..c6239d403 100644 --- a/ui/src/pages/ResourceDetailPage.tsx +++ b/ui/src/pages/ResourceDetailPage.tsx @@ -7,6 +7,7 @@ import { FolderInput, FolderOpen, Github, Globe, Pencil, Power, RefreshCw, ShieldAlert, ShieldCheck, Trash2, TriangleAlert, X, } from 'lucide-react'; import { api, type AuditResult, type DiffTarget, type Skill, type SyncMatrixEntry } from '../api/client'; +import { hubRefs } from '../api/hubDrafts'; import { queryKeys, staleTimes } from '../lib/queryKeys'; import { clearAuditCache } from '../lib/auditCache'; import { SEV, parseFindings, thresholdOf } from '../lib/auditMessage'; @@ -31,6 +32,8 @@ import { CODE_EXT, fileTree } from '../lib/fileTree'; import MarkdownView, { ViewToggle } from '../components/MarkdownView'; import { SkillDetailSkeleton } from '../components/Skeleton'; import Spinner from '../components/Spinner'; +import { Select } from '../components/Select'; +import { refOptions } from '../components/hub/hubShared'; import { SkillContextMenu, type ContextMenuItem } from '../components/TargetMenu'; import { useToast } from '../components/Toast'; import { SkillEditor } from '../components/skill-editor'; @@ -86,6 +89,10 @@ export default function ResourceDetailPage() { const [updating, setUpdating] = useState(false); const [toggling, setToggling] = useState(false); const [blocked, setBlocked] = useState(null); + // A branch picked in the sidebar waits here for confirmation. + const [branchTo, setBranchTo] = useState(null); + // The branch being switched to, kept while a force or skip-audit retry may follow. + const [switchTo, setSwitchTo] = useState(null); // The Updates tab links a modified skill here with ?changes=1 to show its edits. const [modified, setModified] = useState(() => searchParams.get('changes') === '1'); const [raw, setRaw] = useState(false); @@ -165,21 +172,25 @@ export default function ResourceDetailPage() { }); }; - const runUpdate = async (skipAudit: boolean, force = false) => { + const runUpdate = async (skipAudit: boolean, force = false, branch = switchTo ?? undefined) => { setUpdating(true); try { const target = repoOf(resource) ?? (isAgent ? resource.flatName : resource.relPath); - const res = await api.update({ name: target, kind: resource.kind, skipAudit, force }); + const res = await api.update({ name: target, kind: resource.kind, skipAudit, force, branch }); const item = res.results[0]; + const retryable = item?.action === 'blocked' || (item?.action === 'skipped' && isForceRetryable(item.message)); + if (!retryable) setSwitchTo(null); if (item?.action === 'updated') { setBlocked(null); const auditInfo = item.auditRiskLabel ? ` · Security: ${item.auditRiskLabel.toUpperCase()}${item.auditRiskScore ? ` (${item.auditRiskScore}/100)` : ''}` : ''; - toast(t('resourceDetail.toast.updated', { name: resource.name, message: item.message ?? '', auditInfo }), 'success'); + toast(branch + ? t('resourceDetail.toast.switchedBranch', { name: resource.name, branch, auditInfo }) + : t('resourceDetail.toast.updated', { name: resource.name, message: item.message ?? '', auditInfo }), 'success'); markUpToDate(); clearAuditCache(queryClient); - await refreshResource(); + await (branch ? invalidate(queryClient, 'skillBranchSwitched') : refreshResource()); } else if (item?.action === 'up-to-date') { toast(t('resourceDetail.toast.upToDate', { name: resource.name }), 'info'); markUpToDate(); @@ -193,6 +204,7 @@ export default function ResourceDetailPage() { toast(item?.message ?? t('resourceDetail.toast.skipped'), 'warning'); } } catch (e) { + setSwitchTo(null); toast((e as Error).message, 'error'); } finally { setUpdating(false); @@ -364,6 +376,8 @@ export default function ResourceDetailPage() { audit={audit} auditPending={auditQuery.isPending} auditHref={tabSearch('audit')} + branchBusy={updating} + onBranch={setBranchTo} /> {!resource.disabled && } @@ -398,10 +412,23 @@ export default function ResourceDetailPage() { wide loading={updating} onConfirm={() => runUpdate(false, true).then(() => setModified(false))} - onCancel={() => setModified(false)} + onCancel={() => { setModified(false); setSwitchTo(null); }} + /> + { + const branch = branchTo!; + setSwitchTo(branch); + void runUpdate(false, false, branch).then(() => setBranchTo(null)); + }} + onCancel={() => setBranchTo(null)} /> {blocked !== null && ( - runUpdate(true)} onClose={() => setBlocked(null)} /> + runUpdate(true)} onClose={() => { setBlocked(null); setSwitchTo(null); }} /> )} {moveDialog} @@ -411,7 +438,40 @@ export default function ResourceDetailPage() { /* -- Sidebar -------------------------------------- */ -function MetaBox({ resource, frontmatter, body, fileCount, check, audit, auditPending, auditHref }: { +/** Picks the branch to reinstall a skill from; the branches are listed once someone reaches for it. */ +function BranchPicker({ resource, busy, onPick }: { resource: Skill; busy: boolean; onPick: (branch: string) => void }) { + const t = useT(); + const source = resource.source ?? ''; + const [wanted, setWanted] = useState(false); + const refs = useQuery({ + queryKey: queryKeys.hub.refs(source), + queryFn: () => hubRefs(source), + enabled: wanted, + staleTime: staleTimes.refs, + }); + const current = resource.branch ?? ''; + const fixed = refs.data?.pinnable === false; + return ( +
setWanted(true)} onFocusCapture={() => setWanted(true)} title={fixed ? t('hubs.ref.fixed') : undefined}> +