Files
skillshare/internal/server/handler_update_stream.go
Willie 310478c28d fix(ui): fetch each repository once when the dashboard updates skills (#931)
* fix(ui): fetch each repository once when the dashboard updates skills

Updating many skills from the Updates tab cloned the repository once per
skill and reinstalled every one, so 31 skills from 8 repositories took over
a minute where `skillshare update --all` takes 16 seconds, and unchanged
skills were reported as updated.

The update stream and the update-all endpoint now group the request's
skills by repository and branch and go through install.UpdateSkillsFromRepo,
as the CLI does. A skill that already matches upstream is left alone and
reported as up to date; the Updates tab shows and counts it that way.
Results still arrive in request order, which the dashboard relies on.

Updating a single skill and switching its branch still reinstall. Those
paths now also pass the configured parse options to the installer.

* fix(ui): keep checkouts and recorded sources when updates share a fetch

Grouping a dashboard update by repository sent every skill through the
discovery installer. A root skill kept as a Git checkout was replaced by
a plain copy, losing its repository, and an updated skill had its source
recorded in the repository's canonical spelling, which a project
declaration written with another spelling no longer matches.

A checkout now updates on its own by pulling, as before, and an updated
skill keeps the source its record had, as updating one skill does.
2026-11-17 02:43:57 +08:00

203 lines
5.2 KiB
Go

package server
import (
"fmt"
"net/http"
"path/filepath"
"strings"
"time"
"skillshare/internal/install"
)
// handleUpdateStream serves an SSE endpoint that streams update progress in real time.
// Events:
// - "start" → {"total": N} after collecting updatable items
// - "result" → updateResultItem after each item is updated
// - "done" → {"results":…,"summary":…} final payload
//
// Query params: names (comma-separated), kind (skill or agent), force, skipAudit
func (s *Server) handleUpdateStream(w http.ResponseWriter, r *http.Request) {
// Agents are updated by name only; nothing updates them all at once.
kind := r.URL.Query().Get("kind")
if kind != "" && kind != "skill" && kind != "agent" {
writeError(w, http.StatusBadRequest, "invalid kind: "+kind)
return
}
if kind == "agent" && r.URL.Query().Get("names") == "" {
writeError(w, http.StatusBadRequest, "names are required for agents")
return
}
safeSend, ok := initSSE(w)
if !ok {
return
}
start := time.Now()
ctx := r.Context()
force := r.URL.Query().Get("force") == "true"
skipAudit := r.URL.Query().Get("skipAudit") == "true"
// Snapshot source under RLock, then release before slow I/O.
s.mu.RLock()
source := s.cfg.EffectiveSkillsSource()
walk := s.skillsWalk()
s.mu.RUnlock()
// Collect items to update based on "names" query param.
// If names is empty, update all updatable items.
namesParam := r.URL.Query().Get("names")
type updateItem struct {
name string
isRepo bool
agent bool
path string
invalid bool // the name would resolve outside the source; reported, never touched
}
var items []updateItem
if namesParam != "" {
// Update specific items by name
for name := range strings.SplitSeq(namesParam, ",") {
name = strings.TrimSpace(name)
if name == "" {
continue
}
if !validSourceName(name) {
items = append(items, updateItem{name: name, invalid: true})
continue
}
if kind == "agent" {
items = append(items, updateItem{name: name, agent: true})
continue
}
// A tracked repo (a _-prefixed checkout; an unprefixed one is a regular skill)
if repoName, repoPath := install.FindTrackedCheckoutUnlessSkill(source, name); repoPath != "" {
items = append(items, updateItem{name: repoName, isRepo: true, path: repoPath})
continue
}
// Regular skill
items = append(items, updateItem{name: name})
}
} else {
// Update all: tracked repos + regular skills
repos, err := install.GetTrackedRepos(source, walk)
if err == nil {
for _, repo := range repos {
items = append(items, updateItem{
name: repo,
isRepo: true,
path: filepath.Join(source, repo),
})
}
}
s.mu.RLock()
skills, err := getServerUpdatableSkills(source, s.skillsStore, walk)
s.mu.RUnlock()
if err == nil {
for _, skill := range skills {
items = append(items, updateItem{name: skill})
}
}
}
var skillNames []string
for _, item := range items {
if !item.invalid && !item.agent && !item.isRepo {
skillNames = append(skillNames, item.name)
}
}
batch := s.newSkillBatch(skillNames, force, skipAudit, walk.Follow)
safeSend("start", map[string]int{"total": len(items)})
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"`
}{}
for _, item := range items {
// Check if client disconnected
select {
case <-ctx.Done():
return
default:
}
var result updateResultItem
// Lock per-item for write operations
s.mu.Lock()
switch {
case item.invalid:
result = updateResultItem{Name: item.name, Action: "error", Message: "invalid skill name: " + item.name}
case item.agent:
result = s.updateSingleByKind(item.name, "agent", force, skipAudit)
case item.isRepo:
result = s.updateTrackedRepo(item.name, item.path, s.cfg.EffectiveSkillsSource(), force, skipAudit, walk.Follow)
default:
result = batch.update(item.name)
}
s.mu.Unlock()
results = append(results, result)
switch result.Action {
case "updated":
summary.Updated++
case "up-to-date":
summary.UpToDate++
case "blocked":
summary.Blocked++
case "error":
summary.Errors++
case "skipped":
summary.Skipped++
}
safeSend("result", result)
}
// Surface tracked repos declared in metadata but absent on disk (issue #212).
// Only relevant for the update-all flow, not targeted updates.
// Write ops log
s.mu.Lock()
status := "ok"
msg := ""
if summary.Blocked > 0 {
status = "partial"
msg = fmt.Sprintf("%d update(s) blocked by security audit", summary.Blocked)
}
if summary.Errors > 0 {
status = "partial"
if msg != "" {
msg += fmt.Sprintf(", %d update(s) failed", summary.Errors)
} else {
msg = fmt.Sprintf("%d update(s) failed", summary.Errors)
}
}
s.writeOpsLog("update", status, start, map[string]any{
"name": "--all-stream",
"force": force,
"skip_audit": skipAudit,
"results_total": len(results),
"results_failed": summary.Errors,
"results_blocked": summary.Blocked,
"scope": "ui",
}, msg)
s.mu.Unlock()
safeSend("done", map[string]any{
"results": results,
"summary": summary,
})
}