Files
Willie 78a8dc7c0d fix(trash): keep install metadata when restoring from the trash (#680)
* fix(trash): keep install metadata when restoring from the trash

Uninstall pruned a skill's, tracked repo's or agent's entry from the
central .metadata.json, and only the files went to the trash, so a
restore brought back a remote install as a local one: update and check
no longer knew its source (#679).

Uninstall now saves the entries it prunes, with their audit acceptances
and target overrides, beside the trash entry, re-keyed to the trash
name so they match where restore puts the item. uninstall.Restore and
RestoreAgent merge them back after the files return, and every restore
path (CLI, trash TUI, dashboard) goes through them; the dashboard
passes its cached store so it does not go stale. The saved copy is
taken with the same rule RemoveByNames uses and copies each entry, so
legacy repo-group entries are kept and re-keying never touches the
live store.

In project mode uninstall also drops the skill's .gitignore rule and
lock pin, so a skill restore reconciles the project skills afterwards.

trash.Delete removes an entry with its saved metadata, and replaces the
direct RemoveAll calls in delete, empty and the 7-day cleanup. Items
trashed before this change have no saved metadata and still restore as
local.

* fix(trash): keep live records of another path when restoring metadata

A legacy store keys a grouped skill by its basename, so the saved copy of
frontend/foo was keyed "foo". If a different skill was installed as
root-level foo while frontend/foo sat in the trash, restoring it replaced
the root skill's record and lost its source.

Extract now writes full source-relative keys (legacy repo-group entries
keep theirs, since their Group is not their path), and Merge keeps a live
entry whose key names a different path instead of overwriting it. Merge
is shared by skill and agent restore, so both are covered.
2026-10-31 17:25:04 +08:00

268 lines
6.5 KiB
Go

package server
import (
"fmt"
"net/http"
"time"
"skillshare/internal/trash"
"skillshare/internal/uninstall"
)
type trashKind string
const (
trashKindAll trashKind = "all"
trashKindSkill trashKind = "skill"
trashKindAgent trashKind = "agent"
)
type trashItemJSON struct {
Name string `json:"name"`
Kind string `json:"kind,omitempty"`
Timestamp string `json:"timestamp"`
Date string `json:"date"`
Size int64 `json:"size"`
Path string `json:"path"`
}
type resolvedTrashEntry struct {
entry *trash.TrashEntry
kind trashKind
dest string
}
// trashBase returns the trash directory for the current mode.
func (s *Server) trashBase() string {
if s.IsProjectMode() {
return trash.ProjectTrashDir(s.projectRoot)
}
return trash.TrashDir()
}
// agentTrashBase returns the agent trash directory for the current mode.
func (s *Server) agentTrashBase() string {
if s.IsProjectMode() {
return trash.ProjectAgentTrashDir(s.projectRoot)
}
return trash.AgentTrashDir()
}
func parseTrashKind(raw string) (trashKind, error) {
switch raw {
case "", "all":
return trashKindAll, nil
case "skill", "skills":
return trashKindSkill, nil
case "agent", "agents":
return trashKindAgent, nil
default:
return "", fmt.Errorf("invalid trash kind %q", raw)
}
}
func (s *Server) trashDest(kind trashKind) string {
switch kind {
case trashKindAgent:
return s.agentsSource()
default:
return s.skillsSource()
}
}
func (s *Server) findTrashEntry(name string, kind trashKind) (*resolvedTrashEntry, error) {
if kind == trashKindSkill || kind == trashKindAll {
base := s.trashBase()
if entry := trash.FindByName(base, name); entry != nil {
return &resolvedTrashEntry{
entry: entry,
kind: trashKindSkill,
dest: s.trashDest(trashKindSkill),
}, nil
}
}
if kind == trashKindAgent || kind == trashKindAll {
base := s.agentTrashBase()
if entry := trash.FindByName(base, name); entry != nil {
return &resolvedTrashEntry{
entry: entry,
kind: trashKindAgent,
dest: s.trashDest(trashKindAgent),
}, nil
}
}
return nil, nil
}
// handleListTrash returns all trashed items with total size.
func (s *Server) handleListTrash(w http.ResponseWriter, r *http.Request) {
// Snapshot config under RLock, then release before I/O.
s.mu.RLock()
base := s.trashBase()
agentBase := s.agentTrashBase()
s.mu.RUnlock()
items := trash.List(base)
agentItems := trash.List(agentBase)
out := make([]trashItemJSON, 0, len(items)+len(agentItems))
for _, item := range items {
out = append(out, trashItemJSON{
Name: item.Name,
Kind: "skill",
Timestamp: item.Timestamp,
Date: item.Date.Format("2006-01-02T15:04:05Z07:00"),
Size: item.Size,
Path: item.Path,
})
}
for _, item := range agentItems {
out = append(out, trashItemJSON{
Name: item.Name,
Kind: "agent",
Timestamp: item.Timestamp,
Date: item.Date.Format("2006-01-02T15:04:05Z07:00"),
Size: item.Size,
Path: item.Path,
})
}
totalSize := trash.TotalSize(base) + trash.TotalSize(agentBase)
writeJSON(w, map[string]any{
"items": out,
"totalSize": totalSize,
})
}
// handleRestoreTrash restores a trashed skill or agent back to its source directory.
func (s *Server) handleRestoreTrash(w http.ResponseWriter, r *http.Request) {
start := time.Now()
s.mu.Lock()
defer s.mu.Unlock()
name := r.PathValue("name")
kind, err := parseTrashKind(r.URL.Query().Get("kind"))
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
resolved, err := s.findTrashEntry(name, kind)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to resolve trashed item: "+err.Error())
return
}
if resolved == nil {
writeError(w, http.StatusNotFound, "trashed item not found: "+name)
return
}
switch resolved.kind {
case trashKindAgent:
err = uninstall.RestoreAgent(resolved.entry, resolved.dest, s.agentsStore)
default:
if err = uninstall.Restore(resolved.entry, resolved.dest, s.skillsWalk().Follow, s.skillsStore); err == nil {
s.reconcileSkillsConfig(resolved.dest)
}
}
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to restore: "+err.Error())
return
}
s.writeOpsLog("trash", "ok", start, map[string]any{
"action": "restore",
"name": name,
"kind": string(resolved.kind),
"scope": "ui",
}, "")
writeJSON(w, map[string]any{"success": true})
}
// handleDeleteTrash permanently deletes a single trashed item.
func (s *Server) handleDeleteTrash(w http.ResponseWriter, r *http.Request) {
start := time.Now()
s.mu.Lock()
defer s.mu.Unlock()
name := r.PathValue("name")
kind, err := parseTrashKind(r.URL.Query().Get("kind"))
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
resolved, err := s.findTrashEntry(name, kind)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to resolve trashed item: "+err.Error())
return
}
if resolved == nil {
writeError(w, http.StatusNotFound, "trashed item not found: "+name)
return
}
if err := trash.Delete(resolved.entry.Path); err != nil {
writeError(w, http.StatusInternalServerError, "failed to delete: "+err.Error())
return
}
s.writeOpsLog("trash", "ok", start, map[string]any{
"action": "delete",
"name": name,
"kind": string(resolved.kind),
"scope": "ui",
}, "")
writeJSON(w, map[string]any{"success": true})
}
// handleEmptyTrash permanently deletes all trashed items.
func (s *Server) handleEmptyTrash(w http.ResponseWriter, r *http.Request) {
start := time.Now()
s.mu.Lock()
defer s.mu.Unlock()
kind, err := parseTrashKind(r.URL.Query().Get("kind"))
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
type emptyTarget struct {
base string
}
targets := make([]emptyTarget, 0, 2)
if kind == trashKindAll || kind == trashKindSkill {
targets = append(targets, emptyTarget{base: s.trashBase()})
}
if kind == trashKindAll || kind == trashKindAgent {
targets = append(targets, emptyTarget{base: s.agentTrashBase()})
}
removed := 0
for _, target := range targets {
items := trash.List(target.base)
for _, item := range items {
if err := trash.Delete(item.Path); err != nil {
writeError(w, http.StatusInternalServerError, "failed to empty trash: "+err.Error())
return
}
removed++
}
}
s.writeOpsLog("trash", "ok", start, map[string]any{
"action": "empty",
"kind": string(kind),
"removed": removed,
"scope": "ui",
}, "")
writeJSON(w, map[string]any{"success": true, "removed": removed})
}