Files
skillshare/internal/server/handler_plugin_test.go
Willie 2bc791ed19 perf(plugin): check every plugin at once and skip sources that did not move (#812)
* perf(plugin): check every plugin at once and skip sources that did not move

The Plugins page's update check read every Agent CLI, cloned and hashed
every source, and asked npm about every package one after another, so it
grew with each plugin added. A single Agent CLI that stopped answering
held the whole page at "Checking for updates" with no way to tell which
plugin was stuck.

The check now asks every Agent and checks every plugin at the same time.
Plugins share one read of each Agent and each source, so an Agent with
many plugins is still asked once, and a plugin waits only on its own
Agents, including when proving its own leftover installs. Before downloading a remote source with no pinned ref, the
check asks the remote which commit its default branch points at with
`git ls-remote` and reports no update when that is the installed commit.
A check of three unchanged GitHub plugins on two Agents went from 4.3s
with three clones to 0.6s with none.

The dashboard reads the check from a new stream, GET
/api/plugins/check/stream, that sends each plugin as soon as it is
checked. The page marks rows as they arrive and counts progress in the
header. The stream stops waiting after 60 seconds: a plugin bound to an
Agent that has not answered by then shows "Check failed" with the
reason, and plugins on other Agents are unaffected. There is no limit on
how many plugins run together, because plugins waiting on a hung Agent
would otherwise hold every slot and starve the rest.

A cancelled command did not return when the Agent CLI was a shim that
starts the real client, such as an npm, mise or volta wrapper: killing
the shim left the child holding its output, so the command waited until
the child exited and no timeout took effect. Commands now stop waiting
for output two seconds after they are cancelled; a command that exits on
its own while a helper keeps its output open still counts as answered.

* fix(ui): offer every update the Plugins page shows in the update dialog

The header counted updates from the per-plugin marks, but the update
dialog offered only the targets in the last completed check's plan. Two
cases left the header saying Update N with nothing to tick in the dialog:
a first check that broke off after finding an update never set the plan,
and a recheck that could not reach an Agent kept that Agent's earlier
update while the plan said blocked.

The dialog's plan is now derived from each plugin's last answer together
with the kept updates, so a kept update stands in for the blocked or
missing answer and both always agree. A broken-off check also keeps the
answers it did receive.
2026-11-09 15:06:55 +08:00

197 lines
7.6 KiB
Go

package server
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"os"
"slices"
"strings"
"testing"
"time"
"skillshare/internal/config"
"skillshare/internal/plugin"
)
func TestPluginAPIRequiresPreviewAndLocalOrigin(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
for _, body := range []string{`{"request":{"action":"sync"}}`, `{"request":{"action":"sync"},"unknown":true}`} {
w := httptest.NewRecorder()
s.handlePluginApply(w, httptest.NewRequest(http.MethodPost, "/api/plugins/apply", strings.NewReader(body)))
if w.Code != 400 {
t.Fatalf("status %d: %s", w.Code, w.Body.String())
}
}
r := httptest.NewRequest(http.MethodPost, "http://attacker.example/api/plugins/apply", strings.NewReader(`{}`))
r.RemoteAddr = "127.0.0.1:1234"
w := httptest.NewRecorder()
s.requireLocalPlugin(s.handlePluginApply)(w, r)
if w.Code != 403 {
t.Fatalf("rebind accepted: %d", w.Code)
}
}
// The Plugins page draws its Agents from targetDefinitions, so a target that is another
// config directory of an Agent has to be one of them.
func TestPluginListIncludesAnAccountOfAnAgent(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
s.cfg.Targets = map[string]config.TargetConfig{"claude-work": {Agent: "claude", ConfigDir: t.TempDir()}}
w := httptest.NewRecorder()
s.handlePluginList(w, httptest.NewRequest(http.MethodGet, "/api/plugins?hosts=false", nil))
if w.Code != 200 {
t.Fatalf("status %d: %s", w.Code, w.Body.String())
}
type definition struct {
Target string `json:"target"`
Label string `json:"label"`
}
var inventory struct {
TargetDefinitions []definition `json:"targetDefinitions"`
}
if err := json.Unmarshal(w.Body.Bytes(), &inventory); err != nil {
t.Fatal(err)
}
if !slices.ContainsFunc(inventory.TargetDefinitions, func(d definition) bool { return d.Target == "claude-work" }) {
t.Fatalf("the account is missing: %+v", inventory.TargetDefinitions)
}
}
// A source that cannot be reached answers with a key the dashboard translates, not git's output.
func TestPluginDiscoverNamesANetworkFailure(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
w := httptest.NewRecorder()
s.handlePluginDiscover(w, httptest.NewRequest(http.MethodPost, "/api/plugins/discover", strings.NewReader(`{"name":"demo","source":"https://127.0.0.1:1/demo.git"}`)))
var body struct {
Code string `json:"error_code"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != 400 || body.Code != "plugins.error.network" {
t.Fatalf("status %d: %s", w.Code, w.Body.String())
}
}
// A slow source must not hold the config lock: every other API request reloads config
// under it, so the dashboard would hang until the check finished.
func TestPluginDiscoverDoesNotHoldTheConfigLock(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
accepted := make(chan net.Conn, 1)
go func() {
if conn, err := listener.Accept(); err == nil {
accepted <- conn
}
}()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
body := `{"source":"https://` + listener.Addr().String() + `/demo.git"}`
r := httptest.NewRequest(http.MethodPost, "/api/plugins/discover", strings.NewReader(body)).WithContext(ctx)
s.handlePluginDiscover(httptest.NewRecorder(), r)
}()
defer func() { cancel(); <-done }()
select {
case conn := <-accepted:
defer conn.Close()
case <-time.After(10 * time.Second):
t.Fatal("discover never reached the source")
}
if !s.mu.TryLock() {
t.Fatal("a discover still reaching its source holds the config lock")
}
s.mu.Unlock()
}
// Only one plugin change runs at a time; a batch update that cannot start says so before streaming.
func TestPluginUpdateStreamRefusesWhilePluginsAreLocked(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
unlock, err := s.pluginService().Lock()
if err != nil {
t.Fatal(err)
}
defer unlock()
w := httptest.NewRecorder()
s.handlePluginUpdateStream(w, httptest.NewRequest(http.MethodPost, "/api/plugins/update/stream", strings.NewReader(`{"items":[{"name":"demo","targets":["claude"]}]}`)))
if w.Code != http.StatusConflict {
t.Fatalf("status %d: %s", w.Code, w.Body.String())
}
}
// Each plugin ends with its own result, so one that fails leaves the others to run.
func TestPluginUpdateStreamReportsEachPluginThenDone(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
w := httptest.NewRecorder()
s.handlePluginUpdateStream(w, httptest.NewRequest(http.MethodPost, "/api/plugins/update/stream", strings.NewReader(`{"items":[{"name":"gone","targets":[]},{"name":"other","targets":[]}]}`)))
body := w.Body.String()
if strings.Count(body, "event: result") != 2 || !strings.Contains(body, `not found`) || !strings.HasSuffix(strings.TrimSpace(body), `data: {"failure":""}`) {
t.Fatalf("stream:\n%s", body)
}
}
// hosts=false returns declarations even before any machine-local native binding
// exists; it never claims that another host's imported plugin is installed here.
func TestPluginListIncludesUnboundNativeImport(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
service := s.pluginService()
if err := os.WriteFile(service.ConfigPath, []byte("plugins:\n version: 2\n packages:\n router:\n bindings:\n omp: {imported: true}\n"), 0600); err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
s.handlePluginList(w, httptest.NewRequest(http.MethodGet, "/api/plugins?hosts=false", nil))
var result plugin.Inventory
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil {
t.Fatalf("status %d: %s", w.Code, w.Body.String())
}
b := result.Packages["router"].Bindings["omp"]
if !b.Imported || b.ID != "" || len(result.Hosts) != 0 {
t.Fatalf("foreign native binding: %+v", result)
}
}
// The check stream sends each plugin's plan on its own, then says it is done.
func TestPluginCheckStreamSendsEachPlugin(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
service := s.pluginService()
if err := os.WriteFile(service.ConfigPath, []byte("plugins:\n version: 2\n packages:\n one:\n bindings:\n omp: {imported: true}\n two:\n bindings:\n omp: {imported: true}\n"), 0600); err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
s.handlePluginCheckStream(w, httptest.NewRequest(http.MethodGet, "/api/plugins/check/stream", nil))
var names []string
for block := range strings.SplitSeq(w.Body.String(), "\n\n") {
event, data, ok := strings.Cut(strings.TrimPrefix(block, "event: "), "\ndata: ")
if !ok || event != "plan" {
continue
}
var got struct {
Name string `json:"name"`
Plan *plugin.Plan `json:"plan"`
}
if err := json.Unmarshal([]byte(data), &got); err != nil || got.Plan == nil || len(got.Plan.Changes) != 1 {
t.Fatalf("plan event %q: %v", data, err)
}
names = append(names, got.Name)
}
if slices.Sort(names); !slices.Equal(names, []string{"one", "two"}) || !strings.HasSuffix(w.Body.String(), "event: done\ndata: {\"failure\":\"\"}\n\n") {
t.Fatalf("stream %v: %s", names, w.Body.String())
}
}
func TestPluginPreviewPreservesLocalizedError(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
w := httptest.NewRecorder()
s.handlePluginPreview(w, httptest.NewRequest(http.MethodPost, "/api/plugins/preview", strings.NewReader(`{"request":{"action":"import","from":"omp","plugin":"npm-package"}}`)))
var body struct {
Code string `json:"error_code"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != 400 || body.Code != "plugins.error.ompPackageImport" {
t.Fatalf("status %d: %s", w.Code, w.Body.String())
}
}