mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-19 02:17:09 +00:00
Every /api/ request reloads config under the write lock of s.mu. The Plugins page's inventory (Agent CLIs) and update check (network) held the read lock for their whole run, and Go's RWMutex makes later readers queue behind a waiting writer. Switching pages or reloading while a check ran froze the whole dashboard until the check finished. Build each service under the read lock and release it before the slow work: plugin list, discover and preview; Pi extensions view and preview, which run the Pi CLI; and MCP check, which looks up hosts and probes servers live. Writes still take the write lock, and apply paths still compare revisions, so a read that races a write is refused at apply time rather than applied.
265 lines
8.4 KiB
Go
265 lines
8.4 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"net/http"
|
|
"time"
|
|
|
|
"skillshare/internal/config"
|
|
"skillshare/internal/plugin"
|
|
)
|
|
|
|
// pluginServiceSnapshot builds the plugin service under s.mu.RLock and releases it.
|
|
// Reads that run Agent CLIs or reach the network use it: holding s.mu through them
|
|
// would stall every other API request, since each one reloads config under s.mu.Lock.
|
|
func (s *Server) pluginServiceSnapshot() *plugin.Service {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.pluginService()
|
|
}
|
|
|
|
func (s *Server) pluginService() *plugin.Service {
|
|
service := &plugin.Service{ConfigPath: s.configPath(), ProjectRoot: s.projectRoot, StateDir: config.StateDir()}
|
|
if s.IsProjectMode() {
|
|
service.GlobalConfigPath = config.ConfigPath()
|
|
} else {
|
|
service.Accounts = pluginAccounts(s.cfg)
|
|
}
|
|
return service
|
|
}
|
|
|
|
// pluginAccounts are the configured targets that are another config directory of an
|
|
// Agent, such as a second Claude account. They are plugin targets of their own.
|
|
func pluginAccounts(cfg *config.Config) map[string]plugin.Account {
|
|
accounts := map[string]plugin.Account{}
|
|
for name, target := range cfg.Targets {
|
|
if target.Agent != "" && target.ConfigDir != "" {
|
|
accounts[name] = plugin.Account{Agent: target.Agent, Dir: target.ConfigDir, CLI: target.CLI}
|
|
}
|
|
}
|
|
return accounts
|
|
}
|
|
|
|
func (s *Server) requireLocalPlugin(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if !mcpRequestAllowed(r, s.addr) {
|
|
writeError(w, http.StatusForbidden, "Plugin management is available only from the local dashboard")
|
|
return
|
|
}
|
|
// Native downloads can exceed the dashboard's normal 30-second deadline.
|
|
// Limit this extension to the local plugin endpoints.
|
|
_ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(5 * time.Minute))
|
|
next(w, r)
|
|
}
|
|
}
|
|
|
|
type pluginRequest struct {
|
|
Request plugin.Request `json:"request"`
|
|
Revision string `json:"revision,omitempty"`
|
|
}
|
|
|
|
func decodePluginRequest(w http.ResponseWriter, r *http.Request, v any) bool {
|
|
err := decodeJSONWith(w, r, defaultJSONBodyLimit, func(d *json.Decoder) error {
|
|
d.DisallowUnknownFields()
|
|
if err := d.Decode(v); err != nil {
|
|
return err
|
|
}
|
|
if err := d.Decode(new(any)); err != io.EOF {
|
|
return errors.New("expected a single JSON document")
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
if !errors.Is(err, errBodyTooLarge) {
|
|
writeError(w, 400, "invalid plugin request")
|
|
}
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (s *Server) handlePluginList(w http.ResponseWriter, r *http.Request) {
|
|
service := s.pluginServiceSnapshot()
|
|
// hosts=false skips the Agent CLIs: the page draws the plugin list from this answer
|
|
// and fills in the Agents when the full one arrives.
|
|
var inventory *plugin.Inventory
|
|
var err error
|
|
if r.URL.Query().Get("hosts") == "false" {
|
|
inventory, err = service.Packages()
|
|
} else {
|
|
inventory, err = service.Inventory(r.Context())
|
|
}
|
|
if err != nil {
|
|
writeError(w, 400, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, inventory)
|
|
}
|
|
|
|
func (s *Server) handlePluginDiscover(w http.ResponseWriter, r *http.Request) {
|
|
// Name is set for a plugin already managed here, whose snapshot can answer instead of the network.
|
|
var body struct {
|
|
Name string `json:"name,omitempty"`
|
|
Source string `json:"source"`
|
|
SourceRef string `json:"sourceRef,omitempty"`
|
|
Entry string `json:"entry,omitempty"`
|
|
}
|
|
if !decodePluginRequest(w, r, &body) {
|
|
return
|
|
}
|
|
result, err := s.pluginServiceSnapshot().DiscoverManaged(r.Context(), body.Name, body.Source, body.SourceRef, body.Entry)
|
|
if err != nil {
|
|
// A fixed failure carries its key as the error code, so the dashboard can translate it.
|
|
if key, args := plugin.ErrorKey(err); key != "" {
|
|
writeCodedError(w, 400, key, err.Error(), args)
|
|
return
|
|
}
|
|
writeError(w, 400, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, result)
|
|
}
|
|
|
|
func (s *Server) handlePluginPreview(w http.ResponseWriter, r *http.Request) {
|
|
var body pluginRequest
|
|
if !decodePluginRequest(w, r, &body) {
|
|
return
|
|
}
|
|
p, err := s.pluginServiceSnapshot().Preview(r.Context(), body.Request)
|
|
if err != nil {
|
|
if key, args := plugin.ErrorKey(err); key != "" {
|
|
writeCodedError(w, 400, key, err.Error(), args)
|
|
return
|
|
}
|
|
writeError(w, 400, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, p)
|
|
}
|
|
|
|
func (s *Server) handlePluginApply(w http.ResponseWriter, r *http.Request) {
|
|
var body pluginRequest
|
|
if !decodePluginRequest(w, r, &body) {
|
|
return
|
|
}
|
|
if body.Revision == "" {
|
|
writeError(w, 400, "preview before applying plugin changes")
|
|
return
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
start := time.Now()
|
|
result, err := s.pluginService().Apply(r.Context(), body.Request, body.Revision)
|
|
status := "ok"
|
|
message := ""
|
|
if err != nil {
|
|
status = "error"
|
|
message = err.Error()
|
|
}
|
|
s.writeOpsLog("plugin "+body.Request.Action, status, start, map[string]any{"scope": "ui"}, "")
|
|
if reloadErr := s.reloadConfig(); reloadErr != nil && err == nil {
|
|
message = "Plugin operation completed, but configuration reload failed"
|
|
}
|
|
// Preserve all per-target outcomes even when only some targets succeed.
|
|
writeJSON(w, map[string]any{"result": result, "failure": message})
|
|
}
|
|
|
|
// handlePluginUpdateStream updates plugins one after another under one plugin lock and streams each:
|
|
// - "start" → {"name"} a plugin begins
|
|
// - "plan" → {"name","plan"} what its Agents are about to do
|
|
// - "result" → {"name","plan","result","failure","stale"} how it ended; stale means its source moved since the check
|
|
// - "done" → {}
|
|
//
|
|
// Plugins from one source share a single read of it, and config reloads once at the end.
|
|
func (s *Server) handlePluginUpdateStream(w http.ResponseWriter, r *http.Request) {
|
|
var body struct {
|
|
Items []plugin.UpdateItem `json:"items"`
|
|
}
|
|
if !decodePluginRequest(w, r, &body) {
|
|
return
|
|
}
|
|
service := s.pluginServiceSnapshot()
|
|
unlock, err := service.Lock()
|
|
if err != nil {
|
|
writeError(w, http.StatusConflict, err.Error())
|
|
return
|
|
}
|
|
defer unlock()
|
|
send, ok := initSSE(w)
|
|
if !ok {
|
|
return
|
|
}
|
|
s.pluginStop.Store(false)
|
|
start := time.Now()
|
|
// A plugin under way finishes even if the page goes away; the next one does not start.
|
|
ctx := context.WithoutCancel(r.Context())
|
|
failed := service.UpdateBatch(ctx, plugin.Batch{
|
|
Items: body.Items,
|
|
Stopped: func() bool { return s.pluginStop.Load() || r.Context().Err() != nil },
|
|
Around: func(update func()) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
update()
|
|
},
|
|
Started: func(name string) { send("start", map[string]string{"name": name}) },
|
|
Planned: func(name string, p *plugin.Plan) { send("plan", map[string]any{"name": name, "plan": p}) },
|
|
Ended: func(name string, p *plugin.Plan, result *plugin.Result, err error) {
|
|
out := map[string]any{"name": name, "plan": p, "result": result, "failure": "", "stale": errors.Is(err, plugin.ErrSourceMoved)}
|
|
if err != nil {
|
|
out["failure"] = err.Error()
|
|
}
|
|
send("result", out)
|
|
},
|
|
})
|
|
s.mu.Lock()
|
|
status, message := "ok", ""
|
|
if failed > 0 {
|
|
status, message = "partial", fmt.Sprintf("%d plugin update(s) did not complete", failed)
|
|
}
|
|
s.writeOpsLog("plugin update", status, start, map[string]any{"scope": "ui", "plugins": len(body.Items)}, message)
|
|
failure := ""
|
|
if err := s.reloadConfig(); err != nil {
|
|
failure = "Plugin update completed, but configuration reload failed"
|
|
}
|
|
s.mu.Unlock()
|
|
send("done", map[string]string{"failure": failure})
|
|
}
|
|
|
|
// handlePluginUpdateStop lets the plugin under way finish and starts no other.
|
|
func (s *Server) handlePluginUpdateStop(w http.ResponseWriter, _ *http.Request) {
|
|
s.pluginStop.Store(true)
|
|
writeJSON(w, map[string]bool{"stopping": true})
|
|
}
|
|
|
|
// handlePluginFiles lists the reviewed snapshot of a plugin; an imported one has none and lists nothing.
|
|
func (s *Server) handlePluginFiles(w http.ResponseWriter, r *http.Request) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
files, err := s.pluginService().Files(r.PathValue("name"))
|
|
if err != nil {
|
|
writeError(w, 400, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, map[string]any{"files": files})
|
|
}
|
|
|
|
func (s *Server) handlePluginFile(w http.ResponseWriter, r *http.Request) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
data, err := s.pluginService().ReadFile(r.PathValue("name"), r.PathValue("filepath"))
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
writeError(w, http.StatusNotFound, "file not found: "+r.PathValue("filepath"))
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, 400, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, map[string]any{"content": string(data)})
|
|
}
|