mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-18 18:04:17 +00:00
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.
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// memo runs each key's read once and gives every caller its answer, also callers that ask
|
||||
// while it is still running.
|
||||
type memo[T any] struct {
|
||||
mu sync.Mutex
|
||||
calls map[string]*memoCall[T]
|
||||
}
|
||||
|
||||
type memoCall[T any] struct {
|
||||
once sync.Once
|
||||
value T
|
||||
err error
|
||||
}
|
||||
|
||||
func (m *memo[T]) get(key string, read func() (T, error)) (T, error) {
|
||||
m.mu.Lock()
|
||||
if m.calls == nil {
|
||||
m.calls = map[string]*memoCall[T]{}
|
||||
}
|
||||
c, ok := m.calls[key]
|
||||
if !ok {
|
||||
c = &memoCall[T]{}
|
||||
m.calls[key] = c
|
||||
}
|
||||
m.mu.Unlock()
|
||||
c.once.Do(func() { c.value, c.err = read() })
|
||||
return c.value, c.err
|
||||
}
|
||||
|
||||
// reads is what the previews of one operation share. Nothing outlives the operation.
|
||||
type reads struct {
|
||||
sources memo[*Discovery]
|
||||
// heads are the commits remote sources point at, which a check compares before downloading anything.
|
||||
heads memo[string]
|
||||
// latests are npm's latest versions of the packages Pi follows.
|
||||
latests memo[[]int]
|
||||
// hosts is set only for a check: an update changes what an Agent has between plugins.
|
||||
hosts *memo[Host]
|
||||
}
|
||||
|
||||
// sharedHost reads an Agent once per check, however many plugins ask about it.
|
||||
func (s *Service) sharedHost(ctx context.Context, target string) Host {
|
||||
if s.reads == nil || s.reads.hosts == nil {
|
||||
return s.host(ctx, target)
|
||||
}
|
||||
h, _ := s.reads.hosts.get(target, func() (Host, error) { return s.host(ctx, target), nil })
|
||||
return h
|
||||
}
|
||||
|
||||
// Check looks for updates to every plugin at once and passes each plugin's plan to each as soon
|
||||
// as it is ready, one call at a time. The plugins share one read of each Agent and each source,
|
||||
// and a plugin waits only on the Agents it is bound to, so an Agent that hangs holds up only its
|
||||
// own plugins. There is no cap on how many run together: a capped plugin waiting on a hung Agent
|
||||
// would keep the others from starting.
|
||||
func (s *Service) Check(ctx context.Context, r Request, each func(name string, p *Plan, err error)) error {
|
||||
if r.Action != "check" || r.Name != "" {
|
||||
return fmt.Errorf("check every plugin takes the check action without a name")
|
||||
}
|
||||
r.Targets = slices.Clone(r.Targets)
|
||||
for i, target := range r.Targets {
|
||||
r.Targets[i] = NormalizeTarget(target)
|
||||
}
|
||||
if err := s.validate(r); err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := s.load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
check := *s
|
||||
check.reads = &reads{hosts: &memo[Host]{}}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
// Ask every Agent at once, so a plugin bound to several does not ask them one after another.
|
||||
targets := map[string]bool{}
|
||||
for _, p := range d.packages {
|
||||
for target := range p.Bindings {
|
||||
targets[target] = len(r.Targets) == 0 || slices.Contains(r.Targets, target)
|
||||
}
|
||||
}
|
||||
for target, ask := range targets {
|
||||
if ask {
|
||||
wg.Go(func() { check.sharedHost(ctx, target) })
|
||||
}
|
||||
}
|
||||
for name := range d.packages {
|
||||
wg.Go(func() {
|
||||
one := r
|
||||
one.Name = name
|
||||
p, err := check.preview(ctx, one, nil)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
each(name, p, err)
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkAll is Check as one plan in name order, failing as the first plugin that failed does.
|
||||
func (s *Service) checkAll(ctx context.Context, r Request) (*Plan, error) {
|
||||
plans, errs := map[string]*Plan{}, map[string]error{}
|
||||
if err := s.Check(ctx, r, func(name string, p *Plan, err error) { plans[name], errs[name] = p, err }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all := &Plan{Changes: []Change{}}
|
||||
var revisions strings.Builder
|
||||
for _, name := range slices.Sorted(maps.Keys(plans)) {
|
||||
if errs[name] != nil {
|
||||
return nil, errs[name]
|
||||
}
|
||||
all.Changes = append(all.Changes, plans[name].Changes...)
|
||||
all.Blocked = all.Blocked || plans[name].Blocked
|
||||
revisions.WriteString(plans[name].Revision)
|
||||
}
|
||||
all.Revision = hash([]byte(revisions.String()))
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// sourceUnmoved reports whether a remote source still points at the commit b installed, so a
|
||||
// check need not download it: the same commit is the same content. Anything it cannot tell,
|
||||
// such as a pinned ref or a source that does not answer, is left to the download.
|
||||
func (s *Service) sourceUnmoved(ctx context.Context, b Binding, source, ref, plugin, entry string) bool {
|
||||
if ref != "" || b.Commit == "" || b.Digest == "" || b.Pending != "" || source != b.Source || ref != b.SourceRef || plugin != b.Plugin || entry != b.Entry {
|
||||
return false
|
||||
}
|
||||
head, err := s.reads.heads.get(source, func() (string, error) { return remoteHead(ctx, source) })
|
||||
return err == nil && head == b.Commit
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// remoteFixture serves fixture(t) as a Git repository at an HTTPS address, and returns that
|
||||
// address and a function that commits the working tree.
|
||||
func remoteFixture(t *testing.T) (string, string, func()) {
|
||||
t.Helper()
|
||||
root := fixture(t)
|
||||
git := func(args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = root
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %v: %s %v", args, out, err)
|
||||
}
|
||||
}
|
||||
commit := func() {
|
||||
git("add", ".")
|
||||
git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-m", "change")
|
||||
}
|
||||
git("init", "-b", "main")
|
||||
commit()
|
||||
url := "https://fixture.invalid/demo.git"
|
||||
cfg := filepath.Join(t.TempDir(), "gitconfig")
|
||||
writePluginFile(t, filepath.Dir(cfg), filepath.Base(cfg), "[url \"file://"+root+"\"]\n insteadOf = "+url+"\n")
|
||||
t.Setenv("GIT_CONFIG_GLOBAL", cfg)
|
||||
return url, root, commit
|
||||
}
|
||||
|
||||
func addPlugin(t *testing.T, s *Service, r Request) {
|
||||
t.Helper()
|
||||
p, err := s.Preview(context.Background(), r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Apply(context.Background(), r, p.Revision); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckDoesNotDownloadASourceStillAtTheInstalledCommit(t *testing.T) {
|
||||
url, root, commit := remoteFixture(t)
|
||||
s, _, _ := fakeClaude(t)
|
||||
addPlugin(t, s, Request{Action: "add", Source: url, Plugin: "demo", Targets: []string{"claude"}})
|
||||
trace := filepath.Join(t.TempDir(), "git.trace")
|
||||
t.Setenv("GIT_TRACE", trace)
|
||||
|
||||
p, err := s.Preview(context.Background(), Request{Action: "check"})
|
||||
if err != nil || len(p.Changes) != 1 || p.Changes[0].Action != "noop" || !slices.Equal(p.Changes[0].Components, []string{"skills"}) {
|
||||
t.Fatalf("unchanged source: %+v %v", p, err)
|
||||
}
|
||||
if raw, _ := os.ReadFile(trace); strings.Contains(string(raw), " clone ") {
|
||||
t.Fatal("check downloaded a source whose commit had not moved")
|
||||
}
|
||||
|
||||
writePluginFile(t, root, ".claude-plugin/plugin.json", `{"name":"demo","version":"1.1.0"}`)
|
||||
commit()
|
||||
p, err = s.Preview(context.Background(), Request{Action: "check"})
|
||||
if err != nil || len(p.Changes) != 1 || p.Changes[0].Action != "update-available" || p.Changes[0].Binding.Version != "1.1.0" {
|
||||
t.Fatalf("moved source: %+v %v", p, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckAsksEachAgentOnceForAllPlugins(t *testing.T) {
|
||||
s, _, _ := fakeClaude(t)
|
||||
addPlugin(t, s, Request{Action: "add", Name: "one", Source: fixture(t), Plugin: "demo", Targets: []string{"claude"}})
|
||||
addPlugin(t, s, Request{Action: "add", Name: "two", Source: fixture(t), Plugin: "demo", Targets: []string{"claude"}})
|
||||
var mu sync.Mutex
|
||||
lists := 0
|
||||
run := s.Run
|
||||
s.Run = func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
|
||||
if strings.Join(args, " ") == "plugin list --json" {
|
||||
mu.Lock()
|
||||
lists++
|
||||
mu.Unlock()
|
||||
}
|
||||
return run(ctx, dir, env, bin, args...)
|
||||
}
|
||||
|
||||
var checked []string
|
||||
if err := s.Check(context.Background(), Request{Action: "check"}, func(name string, p *Plan, err error) {
|
||||
if err != nil || len(p.Changes) != 1 || p.Changes[0].Action != "noop" {
|
||||
t.Errorf("%s: %+v %v", name, p, err)
|
||||
}
|
||||
checked = append(checked, name)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if slices.Sort(checked); !slices.Equal(checked, []string{"one", "two"}) || lists != 1 {
|
||||
t.Fatalf("checked %v, listed Claude's plugins %d times", checked, lists)
|
||||
}
|
||||
}
|
||||
|
||||
// An Agent whose CLI does not answer holds up only the plugins it has.
|
||||
func TestCheckReportsAPluginWithoutWaitingForAnotherPluginsAgent(t *testing.T) {
|
||||
s, _, _ := fakeClaude(t)
|
||||
work := t.TempDir()
|
||||
s.Accounts = map[string]Account{"claude-work": {Agent: "claude", Dir: work}}
|
||||
addPlugin(t, s, Request{Action: "add", Name: "one", Source: fixture(t), Plugin: "demo", Targets: []string{"claude"}})
|
||||
addPlugin(t, s, Request{Action: "add", Name: "two", Source: fixture(t), Plugin: "demo", Targets: []string{"claude-work"}})
|
||||
oneDone := make(chan struct{})
|
||||
run := s.Run
|
||||
s.Run = func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
|
||||
if slices.Contains(env, "CLAUDE_CONFIG_DIR="+work) {
|
||||
select {
|
||||
case <-oneDone:
|
||||
return nil, agentError{key: "plugins.error.timeout", message: "claude timed out or was cancelled; inspect native status before retrying"}
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
return run(ctx, dir, env, bin, args...)
|
||||
}
|
||||
|
||||
var order []string
|
||||
err := s.Check(t.Context(), Request{Action: "check"}, func(name string, p *Plan, err error) {
|
||||
order = append(order, name)
|
||||
if name == "one" {
|
||||
if err != nil || p.Changes[0].Action != "noop" {
|
||||
t.Errorf("one: %+v %v", p, err)
|
||||
}
|
||||
close(oneDone)
|
||||
return
|
||||
}
|
||||
if err != nil || p.Changes[0].Action != "blocked" || p.Changes[0].MessageKey != "plugins.error.timeout" {
|
||||
t.Errorf("two: %+v %v", p, err)
|
||||
}
|
||||
})
|
||||
if err != nil || !slices.Equal(order, []string{"one", "two"}) {
|
||||
t.Fatalf("order %v: %v", order, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Every plugin is checked at the same time, so plugins waiting on slow Agents never keep
|
||||
// another plugin from starting.
|
||||
func TestCheckChecksEveryPluginAtOnce(t *testing.T) {
|
||||
s, _, _ := fakeClaude(t)
|
||||
s.Accounts = map[string]Account{}
|
||||
const plugins = 9
|
||||
for i := range plugins {
|
||||
target := fmt.Sprintf("claude-%d", i)
|
||||
s.Accounts[target] = Account{Agent: "claude", Dir: t.TempDir()}
|
||||
addPlugin(t, s, Request{Action: "add", Name: fmt.Sprintf("p%d", i), Source: fixture(t), Plugin: "demo", Targets: []string{target}})
|
||||
}
|
||||
// Each Agent answers only once every plugin's Agent has been asked.
|
||||
var asked sync.WaitGroup
|
||||
asked.Add(plugins)
|
||||
all := make(chan struct{})
|
||||
go func() { asked.Wait(); close(all) }()
|
||||
run := s.Run
|
||||
s.Run = func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
|
||||
if strings.Join(args, " ") == "--version" {
|
||||
asked.Done()
|
||||
select {
|
||||
case <-all:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
return run(ctx, dir, env, bin, args...)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
checked := 0
|
||||
if err := s.Check(ctx, Request{Action: "check"}, func(name string, p *Plan, err error) {
|
||||
if err != nil || p.Changes[0].Action != "noop" {
|
||||
t.Errorf("%s: %+v %v", name, p, err)
|
||||
}
|
||||
checked++
|
||||
}); err != nil || checked != plugins || ctx.Err() != nil {
|
||||
t.Fatalf("checked %d of %d: %v %v", checked, plugins, err, ctx.Err())
|
||||
}
|
||||
}
|
||||
|
||||
// A plugin bound to several Agents asks them all at once, not one after another.
|
||||
func TestCheckAsksEveryAgentOfAPluginAtOnce(t *testing.T) {
|
||||
s, _, _ := fakeClaude(t)
|
||||
s.Accounts = map[string]Account{"claude-a": {Agent: "claude", Dir: t.TempDir()}, "claude-b": {Agent: "claude", Dir: t.TempDir()}}
|
||||
addPlugin(t, s, Request{Action: "add", Name: "demo", Source: fixture(t), Plugin: "demo", Targets: []string{"claude-a", "claude-b"}})
|
||||
var asked sync.WaitGroup
|
||||
asked.Add(2)
|
||||
both := make(chan struct{})
|
||||
go func() { asked.Wait(); close(both) }()
|
||||
run := s.Run
|
||||
s.Run = func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
|
||||
if strings.Join(args, " ") == "--version" {
|
||||
asked.Done()
|
||||
select {
|
||||
case <-both:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
return run(ctx, dir, env, bin, args...)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := s.Check(ctx, Request{Action: "check"}, func(name string, p *Plan, err error) {
|
||||
if err != nil || len(p.Changes) != 2 || p.Changes[0].Action != "noop" || p.Changes[1].Action != "noop" {
|
||||
t.Errorf("%s: %+v %v", name, p, err)
|
||||
}
|
||||
}); err != nil || ctx.Err() != nil {
|
||||
t.Fatalf("%v %v", err, ctx.Err())
|
||||
}
|
||||
}
|
||||
|
||||
// Proving another plugin's leftover install on an Agent that does not answer holds up only that plugin.
|
||||
func TestCheckDoesNotWaitOnAnotherPluginsLeftoverInstall(t *testing.T) {
|
||||
s, _, _ := fakeClaude(t)
|
||||
work := t.TempDir()
|
||||
s.Accounts = map[string]Account{"claude-work": {Agent: "claude", Dir: work}}
|
||||
addPlugin(t, s, Request{Action: "add", Name: "one", Source: fixture(t), Plugin: "demo", Targets: []string{"claude"}})
|
||||
addPlugin(t, s, Request{Action: "add", Name: "two", Source: fixture(t), Plugin: "demo", Targets: []string{"claude"}})
|
||||
d, err := s.load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d.putLocal("two", "claude-work", localBinding{Legacy: &receipt{Intent: "legacy", Store: s.storeIdentity("claude-work"), Binding: Binding{ID: "demo@elsewhere"}}})
|
||||
if err := s.saveState(d); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oneDone := make(chan struct{})
|
||||
run := s.Run
|
||||
s.Run = func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
|
||||
if slices.Contains(env, "CLAUDE_CONFIG_DIR="+work) {
|
||||
select {
|
||||
case <-oneDone:
|
||||
return nil, agentError{key: "plugins.error.timeout", message: "claude timed out or was cancelled; inspect native status before retrying"}
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
return run(ctx, dir, env, bin, args...)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
var order []string
|
||||
if err := s.Check(ctx, Request{Action: "check"}, func(name string, p *Plan, err error) {
|
||||
order = append(order, name)
|
||||
if name == "one" {
|
||||
close(oneDone)
|
||||
}
|
||||
}); err != nil || ctx.Err() != nil || len(order) != 2 || order[0] != "one" {
|
||||
t.Fatalf("order %v: %v %v", order, err, ctx.Err())
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The dashboard groups Agents by remedy, so a missing CLI has to stay distinguishable
|
||||
@@ -115,6 +116,34 @@ func TestRunCommandReadsVersionFromStderr(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A CLI that is a shim starting the real client keeps its output open in the child; a cancelled
|
||||
// command still has to return, or the check never marks the Agent as timed out.
|
||||
func TestRunCommandReturnsWhenCancelledWhileAChildStillHoldsItsOutput(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "claude"), []byte("#!/bin/sh\nsleep 60\n"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
_, err := runCommand(ctx, dir, nil, filepath.Join(dir, "claude"), "--version")
|
||||
if key, _ := ErrorKey(err); key != "plugins.error.timeout" || time.Since(start) > 15*time.Second {
|
||||
t.Fatalf("returned %v after %s", err, time.Since(start))
|
||||
}
|
||||
}
|
||||
|
||||
// A CLI that answers and exits while a helper it started keeps its output open still answered.
|
||||
func TestRunCommandKeepsAnAnswerWhenAHelperOutlivesTheCLI(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "pi"), []byte("#!/bin/sh\necho 0.73.1\nsleep 5 &\n"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := runCommand(context.Background(), dir, nil, filepath.Join(dir, "pi"), "--version")
|
||||
if err != nil || strings.TrimSpace(string(out)) != "0.73.1" {
|
||||
t.Fatalf("version = %q %v", out, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostReportsReadyWhenTheCLIAnswers(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
|
||||
@@ -298,10 +298,9 @@ type Service struct {
|
||||
Run Runner
|
||||
// findCodex stands in for the Codex CLI search in tests; nil searches this machine.
|
||||
findCodex func() (string, []string)
|
||||
// discoveries keeps each source UpdateBatch read while it runs, so its plugins share one copy.
|
||||
discoveries map[string]*Discovery
|
||||
discoveryErrs map[string]error
|
||||
applyConfig *[]byte
|
||||
// reads keeps what one operation read, so its plugins share one copy (see reads).
|
||||
reads *reads
|
||||
applyConfig *[]byte
|
||||
}
|
||||
|
||||
func (b Binding) Selected() bool { return b.Sync == nil || *b.Sync }
|
||||
|
||||
@@ -82,6 +82,10 @@ func runCommand(ctx context.Context, dir string, env []string, bin string, args
|
||||
ctx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, bin, args...)
|
||||
// A CLI that is a shim leaves the real client holding its output after it is killed; stop
|
||||
// waiting for that output soon after, or a cancelled command never returns. A CLI that
|
||||
// exits on its own while a helper it started keeps the output open has still answered.
|
||||
cmd.WaitDelay = 2 * time.Second
|
||||
cmd.Dir = dir
|
||||
// No shell, inherited stdin, or automatic native trust/command confirmation.
|
||||
cmd.Env = append(append(os.Environ(), "GIT_TERMINAL_PROMPT=0"), env...)
|
||||
@@ -91,7 +95,11 @@ func runCommand(ctx context.Context, dir string, env []string, bin string, args
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
err := cmd.Run()
|
||||
if errors.Is(err, exec.ErrWaitDelay) && ctx.Err() == nil {
|
||||
err = nil
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, exec.ErrNotFound) || missingPath(bin, err) {
|
||||
return nil, agentError{cause: ErrCLIMissing, key: "plugins.error.cliMissing", message: fmt.Sprintf("%s CLI is not installed or not on PATH on the machine running Skillshare; install it there before syncing plugins", bin)}
|
||||
}
|
||||
|
||||
@@ -147,10 +147,10 @@ func (s *Service) recordPiEntry(ctx context.Context, target string, b *Binding)
|
||||
var npmRegistry = "https://registry.npmjs.org"
|
||||
|
||||
// npmVersions is the installed and latest plain X.Y.Z versions of an npm package added without a version, nil
|
||||
// where either is unknown. latests holds the registry's answers for one preview.
|
||||
// where either is unknown. The registry is asked once per package for each operation.
|
||||
// ponytail: asks the public registry only; a package from a private registry or an .npmrc
|
||||
// scope reads as unknown, and the check falls back to the native client.
|
||||
func (s *Service) npmVersions(ctx context.Context, target, id string, h Host, latests map[string][]int) (installed, latest []int) {
|
||||
func (s *Service) npmVersions(ctx context.Context, target, id string, h Host) (installed, latest []int) {
|
||||
// Pi keeps a package added with a version, range or tag to that spec; only one added
|
||||
// without a version follows npm's latest.
|
||||
name, spec := npmSpec(id)
|
||||
@@ -169,11 +169,7 @@ func (s *Service) npmVersions(ctx context.Context, target, id string, h Host, la
|
||||
if installed == nil {
|
||||
return nil, nil
|
||||
}
|
||||
latest, ok := latests[name]
|
||||
if !ok {
|
||||
latest = plainVersion(npmLatest(ctx, name))
|
||||
latests[name] = latest
|
||||
}
|
||||
latest, _ = s.reads.latests.get(name, func() ([]int, error) { return plainVersion(npmLatest(ctx, name)), nil })
|
||||
return installed, latest
|
||||
}
|
||||
|
||||
|
||||
+23
-15
@@ -22,13 +22,9 @@ func (s *Service) managedRoot() string {
|
||||
// discover shares a reviewed source within one preview (including recursive adds)
|
||||
// or the existing update batch, without caching it across standalone previews.
|
||||
func (s *Service) discover(ctx context.Context, source, ref, entry string) (*Discovery, error) {
|
||||
key := source + "\x00" + ref + "\x00" + entry
|
||||
if d, seen := s.discoveries[key]; seen {
|
||||
return d, s.discoveryErrs[key]
|
||||
}
|
||||
d, err := DiscoverOptions(ctx, source, ref, entry)
|
||||
s.discoveries[key], s.discoveryErrs[key] = d, err
|
||||
return d, err
|
||||
return s.reads.sources.get(source+"\x00"+ref+"\x00"+entry, func() (*Discovery, error) {
|
||||
return DiscoverOptions(ctx, source, ref, entry)
|
||||
})
|
||||
}
|
||||
|
||||
// updateCandidate preserves the selected update's missing/unsupported distinction.
|
||||
@@ -124,6 +120,9 @@ func (s *Service) validate(r Request) error {
|
||||
}
|
||||
|
||||
func (s *Service) Preview(ctx context.Context, r Request) (*Plan, error) {
|
||||
if r.Action == "check" && r.Name == "" {
|
||||
return s.checkAll(ctx, r)
|
||||
}
|
||||
return s.preview(ctx, r, nil)
|
||||
}
|
||||
|
||||
@@ -139,9 +138,9 @@ func (s *Service) preview(ctx context.Context, r Request, cleanup *ompRemoval) (
|
||||
return nil, err
|
||||
}
|
||||
// Recursive source previews share this operation's discoveries, not receiver lifetime.
|
||||
if s.discoveries == nil {
|
||||
if s.reads == nil {
|
||||
preview := *s
|
||||
preview.discoveries, preview.discoveryErrs = map[string]*Discovery{}, map[string]error{}
|
||||
preview.reads = &reads{}
|
||||
s = &preview
|
||||
}
|
||||
d, err := s.load()
|
||||
@@ -154,11 +153,17 @@ func (s *Service) preview(ctx context.Context, r Request, cleanup *ompRemoval) (
|
||||
if h, ok := hosts[target]; ok {
|
||||
return h
|
||||
}
|
||||
h := s.host(ctx, target)
|
||||
h := s.sharedHost(ctx, target)
|
||||
hosts[target] = h
|
||||
return h
|
||||
}
|
||||
s.adoptLegacy(d, host)
|
||||
// A check of one plugin proves only its own leftover installs, so an Agent another plugin
|
||||
// left something on cannot hold it up.
|
||||
var own []string
|
||||
if r.Action == "check" && r.Name != "" {
|
||||
own = append(own, r.Name)
|
||||
}
|
||||
s.adoptLegacy(d, host, own...)
|
||||
// ownMarket reports whether the marketplace Skillshare registered for b is still in place.
|
||||
ownMarket := func(target string, b Binding) bool {
|
||||
_, market, _ := strings.Cut(b.ID, "@")
|
||||
@@ -396,7 +401,6 @@ func (s *Service) preview(ctx context.Context, r Request, cleanup *ompRemoval) (
|
||||
names = append(names, name)
|
||||
}
|
||||
slices.Sort(names)
|
||||
latests := map[string][]int{}
|
||||
for _, name := range names {
|
||||
if r.Name != "" && r.Name != name {
|
||||
continue
|
||||
@@ -543,7 +547,7 @@ func (s *Service) preview(ctx context.Context, r Request, cleanup *ompRemoval) (
|
||||
c.Message = "Save sync selection only. Run sync to install or remove this managed target."
|
||||
c.MessageKey = "plugins.note.selection"
|
||||
case "check", "update":
|
||||
c, err = s.checkOrUpdate(ctx, r, c, action, decl, declared, exists, host(target), latests)
|
||||
c, err = s.checkOrUpdate(ctx, r, c, action, decl, declared, exists, host(target))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -796,7 +800,7 @@ func (s *Service) prepareChange(ctx context.Context, r Request, d *document, hos
|
||||
return c
|
||||
}
|
||||
|
||||
func (s *Service) checkOrUpdate(ctx context.Context, r Request, c Change, action string, decl declaration, declared, exists bool, host Host, latests map[string][]int) (Change, error) {
|
||||
func (s *Service) checkOrUpdate(ctx context.Context, r Request, c Change, action string, decl declaration, declared, exists bool, host Host) (Change, error) {
|
||||
b, target := c.Binding, c.Target
|
||||
agent := s.agentOf(target)
|
||||
if !b.Selected() {
|
||||
@@ -810,7 +814,7 @@ func (s *Service) checkOrUpdate(ctx context.Context, r Request, c Change, action
|
||||
}
|
||||
if b.Source == "" && (r.Action != "check" || !declared || b.Imported || decl.Imported || isNpmSource(decl.Source)) {
|
||||
// An npm package has no source snapshot to compare; npm names its latest version instead.
|
||||
installed, latest := s.npmVersions(ctx, target, b.ID, host, latests)
|
||||
installed, latest := s.npmVersions(ctx, target, b.ID, host)
|
||||
known := installed != nil && latest != nil
|
||||
if known && slices.Compare(latest, installed) <= 0 {
|
||||
c.Action = "noop"
|
||||
@@ -840,6 +844,10 @@ func (s *Service) checkOrUpdate(ctx context.Context, r Request, c Change, action
|
||||
if r.SourceRef != "" {
|
||||
ref = r.SourceRef
|
||||
}
|
||||
if r.Action == "check" && s.sourceUnmoved(ctx, b, source, ref, plugin, entry) {
|
||||
c.Action, c.Components = "noop", b.Components
|
||||
return c, nil
|
||||
}
|
||||
disc, err := s.discover(ctx, source, ref, entry)
|
||||
if err != nil {
|
||||
if !r.All {
|
||||
|
||||
@@ -58,12 +58,9 @@ func acquireRef(ctx context.Context, source, ref string) (string, string, func()
|
||||
if isNpmSource(source) {
|
||||
return "", "", cleanup, fmt.Errorf("npm packages can't be previewed: Pi downloads them when it installs them. Add one to a Pi target with: skillshare plugin add %s --target pi", source)
|
||||
}
|
||||
if githubPattern.MatchString(source) {
|
||||
source = "https://github.com/" + source + ".git"
|
||||
}
|
||||
u, err := url.Parse(source)
|
||||
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return "", "", cleanup, fmt.Errorf("use an existing directory, owner/repo, or HTTPS Git URL without credentials")
|
||||
source, err := remoteURL(source)
|
||||
if err != nil {
|
||||
return "", "", cleanup, err
|
||||
}
|
||||
root, err := os.MkdirTemp("", "skillshare-plugin-")
|
||||
if err != nil {
|
||||
@@ -162,6 +159,36 @@ func DiscoverRef(ctx context.Context, source, ref string) (*Discovery, error) {
|
||||
return DiscoverOptions(ctx, source, ref, "")
|
||||
}
|
||||
|
||||
// remoteURL is the HTTPS address of a remote Git source, which may be written owner/repo.
|
||||
func remoteURL(source string) (string, error) {
|
||||
if githubPattern.MatchString(source) {
|
||||
source = "https://github.com/" + source + ".git"
|
||||
}
|
||||
u, err := url.Parse(source)
|
||||
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return "", fmt.Errorf("use an existing directory, owner/repo, or HTTPS Git URL without credentials")
|
||||
}
|
||||
return source, nil
|
||||
}
|
||||
|
||||
// remoteHead is the commit a remote Git source's default branch points at, read without downloading it.
|
||||
func remoteHead(ctx context.Context, source string) (string, error) {
|
||||
source, err := remoteURL(source)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
out, err := runCommand(ctx, "", nil, "git", "ls-remote", source, "HEAD")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for line := range strings.SplitSeq(string(out), "\n") {
|
||||
if commit, name, ok := strings.Cut(strings.TrimSpace(line), "\t"); ok && name == "HEAD" {
|
||||
return commit, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("%s names no default branch", source)
|
||||
}
|
||||
|
||||
func DiscoverOptions(ctx context.Context, source, ref, entry string) (*Discovery, error) {
|
||||
root, normalized, cleanup, err := acquireRef(ctx, source, ref)
|
||||
if err != nil {
|
||||
|
||||
@@ -321,7 +321,7 @@ func TestPluginHostStateExplicitRefValidatedBeforeWrites(t *testing.T) {
|
||||
if n := strings.Count(string(raw), " clone --depth 1 -- "); n != 1 {
|
||||
t.Fatalf("effective declaration acquired %d times in one preview", n)
|
||||
}
|
||||
if s.discoveries != nil {
|
||||
if s.reads != nil {
|
||||
t.Fatal("preview cache escaped operation")
|
||||
}
|
||||
if _, err := s.Apply(context.Background(), req, p.Revision); err != nil {
|
||||
|
||||
@@ -59,12 +59,8 @@ type Batch struct {
|
||||
// WithDiscoveryCache shares source discovery results and errors across all Preview and
|
||||
// Apply calls made inside fn, so a single CLI command reads each remote source once.
|
||||
func (s *Service) WithDiscoveryCache(fn func() error) error {
|
||||
s.discoveries = map[string]*Discovery{}
|
||||
s.discoveryErrs = map[string]error{}
|
||||
defer func() {
|
||||
s.discoveries = nil
|
||||
s.discoveryErrs = nil
|
||||
}()
|
||||
s.reads = &reads{}
|
||||
defer func() { s.reads = nil }()
|
||||
return fn()
|
||||
}
|
||||
|
||||
@@ -72,12 +68,8 @@ func (s *Service) WithDiscoveryCache(fn func() error) error {
|
||||
// failure stops nothing else, and returns how many did not complete. Plugins from one
|
||||
// source share a single read of it for this batch only.
|
||||
func (s *Service) UpdateBatch(ctx context.Context, b Batch) (failed int) {
|
||||
s.discoveries = map[string]*Discovery{}
|
||||
s.discoveryErrs = map[string]error{}
|
||||
defer func() {
|
||||
s.discoveries = nil
|
||||
s.discoveryErrs = nil
|
||||
}()
|
||||
s.reads = &reads{}
|
||||
defer func() { s.reads = nil }()
|
||||
for _, item := range b.Items {
|
||||
if b.Stopped() {
|
||||
break
|
||||
|
||||
@@ -230,6 +230,34 @@ func (s *Server) handlePluginUpdateStream(w http.ResponseWriter, r *http.Request
|
||||
send("done", map[string]string{"failure": failure})
|
||||
}
|
||||
|
||||
// pluginCheckTimeout bounds an update check, so an Agent CLI or source that does not answer
|
||||
// fails its own plugins in time instead of keeping the page waiting.
|
||||
const pluginCheckTimeout = 60 * time.Second
|
||||
|
||||
// handlePluginCheckStream checks every plugin at once and sends each plugin's plan as soon as it
|
||||
// is ready, so the page marks rows while slower plugins are still being checked.
|
||||
func (s *Server) handlePluginCheckStream(w http.ResponseWriter, r *http.Request) {
|
||||
send, ok := initSSE(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), pluginCheckTimeout)
|
||||
defer cancel()
|
||||
err := s.pluginServiceSnapshot().Check(ctx, plugin.Request{Action: "check"}, func(name string, p *plugin.Plan, err error) {
|
||||
out := map[string]any{"name": name, "plan": p}
|
||||
if err != nil {
|
||||
code, params := plugin.ErrorKey(err)
|
||||
out["error"], out["error_code"], out["error_params"] = err.Error(), code, params
|
||||
}
|
||||
send("plan", out)
|
||||
})
|
||||
failure := ""
|
||||
if err != nil {
|
||||
failure = err.Error()
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -154,6 +154,35 @@ func TestPluginListIncludesUnboundNativeImport(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
|
||||
@@ -635,6 +635,7 @@ func (s *Server) registerRoutes() {
|
||||
s.mux.HandleFunc("POST /api/plugins/discover", s.requireLocalPlugin(s.handlePluginDiscover))
|
||||
s.mux.HandleFunc("POST /api/plugins/preview", s.requireLocalPlugin(s.handlePluginPreview))
|
||||
s.mux.HandleFunc("POST /api/plugins/apply", s.requireLocalPlugin(s.handlePluginApply))
|
||||
s.mux.HandleFunc("GET /api/plugins/check/stream", s.requireLocalPlugin(s.handlePluginCheckStream))
|
||||
s.mux.HandleFunc("POST /api/plugins/update/stream", s.requireLocalPlugin(s.handlePluginUpdateStream))
|
||||
s.mux.HandleFunc("POST /api/plugins/update/stop", s.requireLocalPlugin(s.handlePluginUpdateStop))
|
||||
s.mux.HandleFunc("GET /api/mcp", s.requireLocalMCP(s.handleMCPList))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { apiFetch } from './client';
|
||||
import { BASE, parseApiErrorPayload } from './http';
|
||||
import { BASE, createSSEStream, parseApiErrorPayload } from './http';
|
||||
|
||||
export type PluginTarget = string;
|
||||
/** `npm`: the target installs npm:<package> sources (Pi, or a Pi account that runs pi). */
|
||||
@@ -99,6 +99,9 @@ export type PluginUpdateEvent =
|
||||
| { event: 'result'; name: string; plan: PluginPlan | null; result: PluginResult['result']; failure: string; stale: boolean }
|
||||
| { event: 'done'; failure: string };
|
||||
|
||||
/** One plugin's answer from the update check: its plan, or why it could not be checked. */
|
||||
export interface PluginCheckEvent { name: string; plan: PluginPlan | null; error?: string; error_code?: string; error_params?: Record<string, string> }
|
||||
|
||||
/** Reads the server's event stream for a batch update until `done`. EventSource (createSSEStream) cannot POST the picks, so fetch reads the stream. */
|
||||
async function updateStream(items: PluginUpdateItem[], on: (e: PluginUpdateEvent) => void) {
|
||||
const res = await fetch(BASE + '/plugins/update/stream', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ items }) });
|
||||
@@ -136,6 +139,11 @@ export const pluginsApi = {
|
||||
files: (name: string) => apiFetch<{ files: string[] }>(`/plugins/${encodeURIComponent(name)}/files`),
|
||||
file: (name: string, path: string) => apiFetch<{ content: string }>(`/plugins/${encodeURIComponent(name)}/files/${path.split('/').map(encodeURIComponent).join('/')}`),
|
||||
preview: (request: PluginRequest) => post<PluginPlan>('/plugins/preview', { request }),
|
||||
/** Checks every plugin at once on the server; each plugin's answer arrives through `on` as soon as it is ready. */
|
||||
check: (on: (e: PluginCheckEvent) => void) => new Promise<void>((resolve, reject) => {
|
||||
createSSEStream(BASE + '/plugins/check/stream', { plan: on, done: (d: { failure: string }) => (d.failure ? reject(new Error(d.failure)) : resolve()) },
|
||||
reject, 'The update check stopped before it finished.');
|
||||
}),
|
||||
apply: (request: PluginRequest, revision: string) => post<PluginResult>('/plugins/apply', { request, revision }),
|
||||
/** Updates the plugins one after another on the server; each one's progress arrives through `on`. */
|
||||
update: updateStream,
|
||||
|
||||
@@ -24,6 +24,8 @@ interface Props {
|
||||
pi?: boolean;
|
||||
/** The version and commit each plugin's source has, from the last update check. */
|
||||
updates?: Record<string, Record<PluginTarget, PluginUpdate>>;
|
||||
/** Why the last update check could not check a plugin, by name. */
|
||||
checkFailures?: Record<string, string>;
|
||||
busy: boolean;
|
||||
/** `name:target` of the selection being applied right now. */
|
||||
working: string;
|
||||
@@ -44,7 +46,7 @@ export default function PluginList(props: Props) {
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ name, pi, inventory, updates, busy, working, onToggle, onMenu, onAdd, onBlocked }: Props & { name: string }) {
|
||||
function Row({ name, pi, inventory, updates, checkFailures, busy, working, onToggle, onMenu, onAdd, onBlocked }: Props & { name: string }) {
|
||||
const t = useT();
|
||||
const { isProjectMode } = useAppContext();
|
||||
const pluginTargets = targetMap(inventory.targetDefinitions);
|
||||
@@ -118,6 +120,7 @@ function Row({ name, pi, inventory, updates, busy, working, onToggle, onMenu, on
|
||||
{behind.length > 0 && (
|
||||
<button type="button" className="ss-more min-h-6 shrink-0 disabled:opacity-50" disabled={busy} onClick={() => onAdd({ action: 'update', name, targets: behind }, name)}>{t('plugins.update')}</button>
|
||||
)}
|
||||
{checkFailures?.[name] && <span className="ss-tag warn shrink-0" title={checkFailures[name]}>{t('plugins.checkFailed')}<span className="sr-only">: {checkFailures[name]}</span></span>}
|
||||
{bindings.some(([target, b]) => syncAction(b, inventory.hosts.find((h) => h.target === target))) && <span className="ss-tag warn">{t('plugins.pending')}</span>}
|
||||
{bindings.some(([target, b]) => bindingStatus(b, inventory.hosts.find((h) => h.target === target)) === 'plugins.importRetained') && <span className="ss-tag">{t('plugins.importRetained')}</span>}
|
||||
{bindings.length === 0 && <span className="ss-tag">{t('plugins.noAgentsYet')}</span>}
|
||||
|
||||
@@ -2,15 +2,17 @@ import { act, renderHook } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { pluginsApi } from '../../api/plugins';
|
||||
import { ApiError } from '../../api/client';
|
||||
import type { PluginInventory, PluginPlan, PluginUpdateEvent } from '../../api/plugins';
|
||||
import type { PluginCheckEvent, PluginInventory, PluginPlan, PluginUpdateEvent } from '../../api/plugins';
|
||||
import { changedRuns, failureText, importPackageNames, importRequest, piPackageTest, reviewChanges, syncTodo, updatesFound, updatedTargets, updatesLeft, updatesPending, usePluginsFlow, versionMoves } from './pluginsFlow';
|
||||
|
||||
vi.mock('../../api/plugins', async (importOriginal) => ({ ...await importOriginal<typeof import('../../api/plugins')>(), pluginsApi: { preview: vi.fn(), apply: vi.fn(), update: vi.fn(), stopUpdate: vi.fn() } }));
|
||||
vi.mock('../../api/plugins', async (importOriginal) => ({ ...await importOriginal<typeof import('../../api/plugins')>(), pluginsApi: { preview: vi.fn(), check: vi.fn(), apply: vi.fn(), update: vi.fn(), stopUpdate: vi.fn() } }));
|
||||
|
||||
const t = (key: string) => key;
|
||||
const plan = (revision: string, ...changes: Partial<PluginPlan['changes'][number]>[]): PluginPlan =>
|
||||
({ revision, blocked: false, changes: changes.map((c) => ({ name: 'demo', target: 'codex', id: 'demo@market', action: 'selection', ...c })) });
|
||||
const ok = { result: { results: [] }, failure: '' };
|
||||
/** The server's check stream: each plugin's answer, in the order given. */
|
||||
const checks = (...events: PluginCheckEvent[]) => vi.mocked(pluginsApi.check).mockImplementationOnce(async (on) => { events.forEach(on); });
|
||||
/** The server's stream for a batch: each plugin starts, then ends with the given result. */
|
||||
const streams = (...ends: Omit<Extract<PluginUpdateEvent, { event: 'result' }>, 'event'>[]) =>
|
||||
vi.mocked(pluginsApi.update).mockImplementation(async (_items, on) => {
|
||||
@@ -117,7 +119,7 @@ describe('plugins flow', () => {
|
||||
it('remembers what a check found, opens no review, and takes an Agent off once its batch update is applied', async () => {
|
||||
const observed = { id: '/owned/driver', source: 'https://fixture.invalid/driver.git', sourceRef: 'main', plugin: 'driver', entry: 'entry.js', version: '1.1.0', commit: 'abc', digest: 'reviewed-digest' };
|
||||
const found = { name: 'driver', target: 'pi', binding: observed };
|
||||
vi.mocked(pluginsApi.preview).mockResolvedValueOnce(plan('r', { ...found, action: 'update-available' }));
|
||||
checks({ name: 'driver', plan: plan('r', { ...found, action: 'update-available' }) });
|
||||
streams({ name: 'driver', plan: plan('r2', { ...found, action: 'update' }), result: { results: [{ name: 'driver', target: 'pi', status: 'installed' }] }, failure: '', stale: false });
|
||||
const { now, onPreviewed } = flow();
|
||||
await act(() => now().check());
|
||||
@@ -162,10 +164,70 @@ describe('plugins flow', () => {
|
||||
expect(versionMoves(inventory, 'tail', [{ target: 'pi', version: '1.1.0' }, { target: 'claude', version: '1.1.0' }]).shared).toBe(false);
|
||||
});
|
||||
|
||||
it('marks each plugin as the check answers for it, and says why one could not be checked', async () => {
|
||||
const found = { name: 'driver', target: 'pi', binding: { id: 'npm:driver', version: '1.1.0' } };
|
||||
checks(
|
||||
{ name: 'driver', plan: plan('a', { ...found, action: 'update-available' }) },
|
||||
{ name: 'tail', plan: null, error: 'git timed out', error_code: 'plugins.error.timeout' },
|
||||
{ name: 'guard', plan: { ...plan('b', { name: 'guard', action: 'blocked', messageKey: 'plugins.note.accountChanged' }), blocked: true } },
|
||||
);
|
||||
const inventory = { hosts: [], targetDefinitions: [], packages: { driver: { bindings: {} }, tail: { bindings: {} }, guard: { bindings: {} } } };
|
||||
const { result } = renderHook(() => usePluginsFlow({ t, inventory, refresh: vi.fn(), onPreviewed: vi.fn() }));
|
||||
await act(() => result.current.check(true));
|
||||
expect(result.current.updates).toEqual({ driver: { pi: { version: '1.1.0', id: 'npm:driver' } } });
|
||||
expect(result.current.checkFailures).toEqual({ tail: 'plugins.error.timeout', guard: 'plugins.note.accountChanged' });
|
||||
expect(result.current.checkProgress).toEqual({ done: 3, total: 3 });
|
||||
});
|
||||
|
||||
it('keeps what the last check found for plugins a broken-off check never answered for', async () => {
|
||||
const found = (name: string) => ({ name, target: 'pi', action: 'update-available', binding: { id: `npm:${name}`, version: '2.0.0' } });
|
||||
checks({ name: 'driver', plan: plan('a', found('driver')) }, { name: 'tail', plan: plan('b', found('tail')) });
|
||||
vi.mocked(pluginsApi.check).mockImplementationOnce(async (on) => { on({ name: 'driver', plan: plan('c', { name: 'driver', action: 'noop' }) }); throw new Error('stream closed'); });
|
||||
const { now } = flow();
|
||||
await act(() => now().check());
|
||||
await act(() => now().check());
|
||||
expect(Object.keys(now().updates)).toEqual(['tail']);
|
||||
});
|
||||
|
||||
it('keeps an update the last check found on an Agent this check could not reach', async () => {
|
||||
const found = (target: string) => ({ name: 'driver', target, action: 'update-available', binding: { id: 'driver@m', version: '2.0.0' } });
|
||||
checks({ name: 'driver', plan: plan('a', found('claude'), found('claude-work')) }, { name: 'tail', plan: plan('b', { ...found('pi'), name: 'tail' }) });
|
||||
checks(
|
||||
{ name: 'driver', plan: { ...plan('c', { name: 'driver', target: 'claude', action: 'noop' }, { name: 'driver', target: 'claude-work', action: 'blocked', messageKey: 'plugins.error.timeout' }), blocked: true } },
|
||||
{ name: 'tail', plan: null, error: 'pi timed out', error_code: 'plugins.error.timeout' },
|
||||
);
|
||||
const { now } = flow();
|
||||
await act(() => now().check());
|
||||
await act(() => now().check());
|
||||
expect(now().updates).toEqual({ driver: { 'claude-work': expect.anything() }, tail: { pi: expect.anything() } });
|
||||
});
|
||||
|
||||
const offered = (p: PluginPlan | null) => (p?.changes ?? []).filter((c) => c.action === 'update-available').map((c) => `${c.name}:${c.target}`);
|
||||
|
||||
it('offers in the update dialog an update a broken-off check found', async () => {
|
||||
vi.mocked(pluginsApi.check).mockImplementationOnce(async (on) => {
|
||||
on({ name: 'driver', plan: plan('a', { name: 'driver', target: 'claude', action: 'update-available', binding: { id: 'driver@m', version: '2.0.0' } }) });
|
||||
throw new Error('stream closed');
|
||||
});
|
||||
const { now } = flow();
|
||||
await act(() => now().check());
|
||||
expect(offered(now().checked)).toEqual(['driver:claude']);
|
||||
});
|
||||
|
||||
it('offers in the update dialog an update kept for an Agent the check could not reach', async () => {
|
||||
const found = (target: string) => ({ name: 'driver', target, action: 'update-available', binding: { id: 'driver@m', version: '2.0.0' } });
|
||||
checks({ name: 'driver', plan: plan('a', found('claude'), found('claude-work')) });
|
||||
checks({ name: 'driver', plan: { ...plan('b', { name: 'driver', target: 'claude', action: 'noop' }, { name: 'driver', target: 'claude-work', action: 'blocked', messageKey: 'plugins.error.timeout' }), blocked: true } });
|
||||
const { now } = flow();
|
||||
await act(() => now().check());
|
||||
await act(() => now().check());
|
||||
expect(offered(now().checked)).toEqual(['driver:claude-work']);
|
||||
});
|
||||
|
||||
it('tells whether a check came back, so a check the user asked for can open its result', async () => {
|
||||
const { now } = flow();
|
||||
await act(async () => expect(await now().check()).toBe(true));
|
||||
vi.mocked(pluginsApi.preview).mockRejectedValueOnce(new Error('offline'));
|
||||
vi.mocked(pluginsApi.check).mockRejectedValueOnce(new Error('offline'));
|
||||
await act(async () => expect(await now().check()).toBe(false));
|
||||
});
|
||||
|
||||
@@ -182,7 +244,7 @@ describe('plugins flow', () => {
|
||||
|
||||
it('keeps a plugin whose update came back skipped on the list, as not updated', async () => {
|
||||
const found = { name: 'driver', target: 'pi', binding: { id: 'npm:driver', version: '1.1.0' } };
|
||||
vi.mocked(pluginsApi.preview).mockResolvedValueOnce(plan('r', { ...found, action: 'update-available' }));
|
||||
checks({ name: 'driver', plan: plan('r', { ...found, action: 'update-available' }) });
|
||||
streams({ name: 'driver', plan: plan('u', { ...found, action: 'update' }), result: { results: [{ name: 'driver', target: 'pi', status: 'skipped', message: 'marketplace gone' }] }, failure: '', stale: false });
|
||||
const { now } = flow();
|
||||
await act(() => now().check());
|
||||
@@ -216,9 +278,8 @@ describe('plugins flow', () => {
|
||||
|
||||
|
||||
it('drops a plugin whose source moved since the check and checks again, showing why that check failed', async () => {
|
||||
vi.mocked(pluginsApi.preview)
|
||||
.mockResolvedValueOnce(plan('r', { name: 'driver', target: 'pi', action: 'update-available', binding: { id: 'npm:driver', version: '1.1.0' } }))
|
||||
.mockRejectedValueOnce(new Error('offline'));
|
||||
checks({ name: 'driver', plan: plan('r', { name: 'driver', target: 'pi', action: 'update-available', binding: { id: 'npm:driver', version: '1.1.0' } }) });
|
||||
vi.mocked(pluginsApi.check).mockRejectedValueOnce(new Error('offline'));
|
||||
streams({ name: 'driver', plan: plan('u'), result: null, failure: 'source changed since the check; check again', stale: true });
|
||||
const { now } = flow();
|
||||
await act(() => now().check());
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { bindingVersion, byPlugin, pluginsApi, syncAction, targetMap } from '../../api/plugins';
|
||||
import type { PluginInventory, PluginOutcome, PluginPlan, PluginRequest, PluginResult, PluginTarget, PluginUpdate, PluginUpdateEvent } from '../../api/plugins';
|
||||
import { ApiError } from '../../api/client';
|
||||
import type { useT } from '../../i18n';
|
||||
import { keyedMessage } from './outcomeText';
|
||||
import { pluginErrorMessage } from './pluginError';
|
||||
@@ -58,6 +59,38 @@ export function updatesFound(plan: PluginPlan) {
|
||||
return found;
|
||||
}
|
||||
|
||||
/** What one plugin's check answer leaves of updates: an Agent the check could not reach keeps the update found before. */
|
||||
function withChecked(updates: Updates, name: string, plan: PluginPlan | null): Updates {
|
||||
const before = updates[name] ?? {};
|
||||
const found = plan ? updatesFound(plan)[name] ?? {} : { ...before };
|
||||
for (const c of plan?.changes ?? []) if (c.name === name && c.action === 'blocked' && before[c.target]) found[c.target] = before[c.target];
|
||||
const next = { ...updates };
|
||||
if (Object.keys(found).length) next[name] = found; else delete next[name];
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the update dialog offers: each plugin's check answer in name order, where an update kept from an earlier check,
|
||||
* for an Agent this check could not reach or a plugin it never answered for, stands in for what this check said.
|
||||
*/
|
||||
export function checkedPlan(plans: Record<string, PluginPlan>, updates: Updates): PluginPlan | null {
|
||||
const names = [...new Set([...Object.keys(plans), ...Object.keys(updates)])].sort();
|
||||
if (names.length === 0) return null;
|
||||
const changes = names.flatMap((name) => {
|
||||
const kept = updates[name] ?? {};
|
||||
const answered = (plans[name]?.changes ?? []).filter((c) => !(c.action === 'blocked' && kept[c.target]));
|
||||
const offered = Object.entries(kept)
|
||||
.filter(([target]) => !answered.some((c) => c.target === target && c.action === 'update-available'))
|
||||
.map(([target, u]) => ({
|
||||
name, target, id: u.id ?? '', action: 'update-available',
|
||||
message: 'Source content changed; review an update before applying.', messageKey: 'plugins.note.sourceChanged',
|
||||
binding: { id: u.id ?? '', version: u.version, commit: u.commit, digest: u.digest, source: u.source, sourceRef: u.sourceRef, plugin: u.plugin, entry: u.entry },
|
||||
}));
|
||||
return [...answered, ...offered];
|
||||
});
|
||||
return { revision: names.map((n) => plans[n]?.revision ?? '').join(''), blocked: changes.some((c) => c.action === 'blocked'), changes };
|
||||
}
|
||||
|
||||
/**
|
||||
* An Agent comes off once the result reports it updated, or already there (noop); one that
|
||||
* failed, was skipped, or never ran because the apply stopped first keeps its Update action.
|
||||
@@ -157,17 +190,45 @@ export function usePluginsFlow({ t, inventory, refresh, onPreviewed }: {
|
||||
const [result, setResult] = useState<PluginResult | null>(null);
|
||||
// What the last check found to update. An applied update takes its Agents off.
|
||||
const [updates, setUpdates] = useState<Updates>({});
|
||||
const [checked, setChecked] = useState<PluginPlan | null>(null);
|
||||
// Each plugin's answer to the last check, for the update dialog.
|
||||
const [checkedPlans, setCheckedPlans] = useState<Record<string, PluginPlan>>({});
|
||||
const [checking, setChecking] = useState(false);
|
||||
// How many plugins the check under way has answered for, and why each it could not check failed.
|
||||
const [checkProgress, setCheckProgress] = useState({ done: 0, total: 0 });
|
||||
const [checkFailures, setCheckFailures] = useState<Record<string, string>>({});
|
||||
// The batch update under way or just finished, one row per plugin, until the dialog closes.
|
||||
const [batch, setBatch] = useState<BatchItem[] | null>(null);
|
||||
|
||||
/** A check is read-only and opens nothing: it only marks the rows. Quiet, as on page load, it also keeps its error to itself. */
|
||||
/** Resolves whether the check came back, so a check the user asked for can show its result. */
|
||||
/**
|
||||
* A check is read-only and opens nothing: each plugin marks its row as soon as the server has checked it, and one the
|
||||
* server could not check says why on its row. An Agent the check could not reach, and a plugin a broken-off check
|
||||
* never answered for, keep what the last check found. Quiet, as on page load, it keeps its error to itself. Resolves whether the check came back, so a check the
|
||||
* user asked for can show its result.
|
||||
*/
|
||||
const check = async (quiet = false) => {
|
||||
setChecking(true); if (!quiet) setFailure('');
|
||||
try { const plan = await pluginsApi.preview({ action: 'check' }); setUpdates(updatesFound(plan)); setChecked(plan); return true; }
|
||||
catch (e) { if (!quiet) setFailure((e as Error).message); return false; }
|
||||
setCheckProgress({ done: 0, total: Object.keys(inventory?.packages ?? {}).length });
|
||||
const plans: Record<string, PluginPlan> = {};
|
||||
const answered = new Set<string>();
|
||||
const failed: Record<string, string> = {};
|
||||
try {
|
||||
await pluginsApi.check(({ name, plan, error, error_code, error_params }) => {
|
||||
const why = error ? pluginErrorMessage(new ApiError(200, error, { code: error_code, params: error_params }), t)
|
||||
: plan?.blocked ? blockedText(t, plan) : '';
|
||||
answered.add(name);
|
||||
if (plan) plans[name] = plan;
|
||||
if (why) failed[name] = why;
|
||||
setUpdates((u) => withChecked(u, name, plan));
|
||||
setCheckFailures((f) => { const next = { ...f }; delete next[name]; return why ? { ...next, [name]: why } : next; });
|
||||
setCheckProgress((p) => ({ ...p, done: p.done + 1 }));
|
||||
});
|
||||
// A finished check also drops plugins it no longer reports.
|
||||
setUpdates((u) => Object.fromEntries(Object.entries(u).filter(([n]) => answered.has(n))));
|
||||
setCheckFailures(failed);
|
||||
setCheckedPlans(plans);
|
||||
return true;
|
||||
}
|
||||
catch (e) { setCheckedPlans((before) => ({ ...before, ...plans })); if (!quiet) setFailure((e as Error).message); return false; }
|
||||
finally { setChecking(false); }
|
||||
};
|
||||
/**
|
||||
@@ -278,7 +339,7 @@ export function usePluginsFlow({ t, inventory, refresh, onPreviewed }: {
|
||||
|
||||
const outcomes = result?.result?.results ?? [];
|
||||
return {
|
||||
busy, working, failure, review, updates, outcomes, checked, checking, batch,
|
||||
busy, working, failure, review, updates, outcomes, checked: checkedPlan(checkedPlans, updates), checking, checkProgress, checkFailures, batch,
|
||||
preview, begin, apply, selectTarget, check, updateMany, importMany,
|
||||
stopBatch: () => { pluginsApi.stopUpdate().catch((e: Error) => setFailure(e.message)); },
|
||||
closeBatch: () => setBatch(null),
|
||||
|
||||
@@ -2581,6 +2581,7 @@
|
||||
"plugins.noChanges": "Keine Änderungen",
|
||||
"plugins.apply": "Änderungen anwenden",
|
||||
"plugins.checkingUpdates": "Suche nach Updates…",
|
||||
"plugins.checkFailed": "Prüfung fehlgeschlagen",
|
||||
"plugins.updateCount.one": "{count} aktualisieren",
|
||||
"plugins.updateCount.other": "{count} aktualisieren",
|
||||
"plugins.updateDialog.title": "Plugins aktualisieren",
|
||||
|
||||
@@ -2581,6 +2581,7 @@
|
||||
"plugins.noChanges": "No changes",
|
||||
"plugins.apply": "Apply changes",
|
||||
"plugins.checkingUpdates": "Checking for updates…",
|
||||
"plugins.checkFailed": "Check failed",
|
||||
"plugins.updateCount.one": "Update {count}",
|
||||
"plugins.updateCount.other": "Update {count}",
|
||||
"plugins.updateDialog.title": "Update plugins",
|
||||
|
||||
@@ -2581,6 +2581,7 @@
|
||||
"plugins.noChanges": "Sin cambios",
|
||||
"plugins.apply": "Aplicar cambios",
|
||||
"plugins.checkingUpdates": "Buscando actualizaciones…",
|
||||
"plugins.checkFailed": "No se pudo comprobar",
|
||||
"plugins.updateCount.one": "Actualizar {count}",
|
||||
"plugins.updateCount.other": "Actualizar {count}",
|
||||
"plugins.updateDialog.title": "Actualizar plugins",
|
||||
|
||||
@@ -2581,6 +2581,7 @@
|
||||
"plugins.noChanges": "بدون تغییر",
|
||||
"plugins.apply": "اعمال تغییرات",
|
||||
"plugins.checkingUpdates": "در حال بررسی بهروزرسانیها…",
|
||||
"plugins.checkFailed": "بررسی ناموفق بود",
|
||||
"plugins.updateCount.one": "بهروزرسانی {count}",
|
||||
"plugins.updateCount.other": "بهروزرسانی {count}",
|
||||
"plugins.updateDialog.title": "بهروزرسانی pluginها",
|
||||
|
||||
@@ -2581,6 +2581,7 @@
|
||||
"plugins.noChanges": "Aucune modification",
|
||||
"plugins.apply": "Appliquer",
|
||||
"plugins.checkingUpdates": "Recherche de mises à jour…",
|
||||
"plugins.checkFailed": "Échec de la vérification",
|
||||
"plugins.updateCount.one": "Mettre à jour {count}",
|
||||
"plugins.updateCount.other": "Mettre à jour {count}",
|
||||
"plugins.updateDialog.title": "Mettre à jour les plugins",
|
||||
|
||||
@@ -2581,6 +2581,7 @@
|
||||
"plugins.noChanges": "Tidak ada perubahan",
|
||||
"plugins.apply": "Terapkan perubahan",
|
||||
"plugins.checkingUpdates": "Memeriksa pembaruan…",
|
||||
"plugins.checkFailed": "Gagal memeriksa",
|
||||
"plugins.updateCount.one": "Perbarui {count}",
|
||||
"plugins.updateCount.other": "Perbarui {count}",
|
||||
"plugins.updateDialog.title": "Perbarui plugin",
|
||||
|
||||
@@ -2581,6 +2581,7 @@
|
||||
"plugins.noChanges": "変更なし",
|
||||
"plugins.apply": "変更を適用",
|
||||
"plugins.checkingUpdates": "更新を確認中…",
|
||||
"plugins.checkFailed": "確認に失敗",
|
||||
"plugins.updateCount.one": "{count} 件を更新",
|
||||
"plugins.updateCount.other": "{count} 件を更新",
|
||||
"plugins.updateDialog.title": "plugin を更新",
|
||||
|
||||
@@ -2581,6 +2581,7 @@
|
||||
"plugins.noChanges": "변경 없음",
|
||||
"plugins.apply": "변경 적용",
|
||||
"plugins.checkingUpdates": "업데이트 확인 중…",
|
||||
"plugins.checkFailed": "확인 실패",
|
||||
"plugins.updateCount.one": "{count}개 업데이트",
|
||||
"plugins.updateCount.other": "{count}개 업데이트",
|
||||
"plugins.updateDialog.title": "plugin 업데이트",
|
||||
|
||||
@@ -2581,6 +2581,7 @@
|
||||
"plugins.noChanges": "Sem alterações",
|
||||
"plugins.apply": "Aplicar alterações",
|
||||
"plugins.checkingUpdates": "Procurando atualizações…",
|
||||
"plugins.checkFailed": "Falha na verificação",
|
||||
"plugins.updateCount.one": "Atualizar {count}",
|
||||
"plugins.updateCount.other": "Atualizar {count}",
|
||||
"plugins.updateDialog.title": "Atualizar plugins",
|
||||
|
||||
@@ -2581,6 +2581,7 @@
|
||||
"plugins.noChanges": "没有更改",
|
||||
"plugins.apply": "应用更改",
|
||||
"plugins.checkingUpdates": "正在检查更新…",
|
||||
"plugins.checkFailed": "检查失败",
|
||||
"plugins.updateCount.one": "更新 {count} 个",
|
||||
"plugins.updateCount.other": "更新 {count} 个",
|
||||
"plugins.updateDialog.title": "更新 plugin",
|
||||
|
||||
@@ -2581,6 +2581,7 @@
|
||||
"plugins.noChanges": "沒有變更",
|
||||
"plugins.apply": "套用變更",
|
||||
"plugins.checkingUpdates": "正在檢查更新…",
|
||||
"plugins.checkFailed": "檢查失敗",
|
||||
"plugins.updateCount.one": "更新 {count} 個",
|
||||
"plugins.updateCount.other": "更新 {count} 個",
|
||||
"plugins.updateDialog.title": "更新 plugin",
|
||||
|
||||
@@ -6,7 +6,7 @@ import { pluginsApi, type PluginInventory } from '../api/plugins';
|
||||
import { ToastProvider } from '../components/Toast';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
|
||||
vi.mock('../api/plugins', async (importOriginal) => ({ ...await importOriginal<typeof import('../api/plugins')>(), pluginsApi: { list: vi.fn(), files: vi.fn(), file: vi.fn(), discover: vi.fn(), preview: vi.fn(), apply: vi.fn(), update: vi.fn(), stopUpdate: vi.fn() } }));
|
||||
vi.mock('../api/plugins', async (importOriginal) => ({ ...await importOriginal<typeof import('../api/plugins')>(), pluginsApi: { list: vi.fn(), files: vi.fn(), file: vi.fn(), discover: vi.fn(), preview: vi.fn(), check: vi.fn(), apply: vi.fn(), update: vi.fn(), stopUpdate: vi.fn() } }));
|
||||
vi.mock('../i18n', async (importOriginal) => ({ ...await importOriginal<typeof import('../i18n')>(), useT: () => (key: string) => key }));
|
||||
vi.mock('../context/AppContext', () => ({ useAppContext: () => ({ isProjectMode: false }) }));
|
||||
vi.mock('../components/plugins/PluginAddDialog', () => ({ default: ({ initialTargets }: { initialTargets?: string[] }) => <div role="dialog" aria-label="add">{initialTargets?.join(',')}</div> }));
|
||||
@@ -142,11 +142,13 @@ describe('PluginsPage', () => {
|
||||
hosts: [{ target: 'pi', version: '0.99.2', status: 'ready', installed: [{ id: 'npm:driver', version: '1.0.0', enabled: true }, { id: 'npm:tail', version: '2.0.0', enabled: true }] }],
|
||||
});
|
||||
// The check the page runs on its own.
|
||||
vi.mocked(pluginsApi.preview).mockResolvedValueOnce({ revision: 'r', blocked: false, changes: [
|
||||
{ name: 'driver', target: 'pi', id: 'npm:driver', action: 'update-available', binding: { id: 'npm:driver', version: '1.1.0' } },
|
||||
{ name: 'tail', target: 'pi', id: 'npm:tail', action: 'update-available', binding: { id: 'npm:tail', version: '2.1.0' } },
|
||||
{ name: 'tail', target: 'codex', id: 'tail@market', action: 'update-available', binding: { id: 'tail@market', version: '2.1.0' } },
|
||||
] });
|
||||
vi.mocked(pluginsApi.check).mockImplementationOnce(async (on) => {
|
||||
on({ name: 'driver', plan: { revision: 'a', blocked: false, changes: [{ name: 'driver', target: 'pi', id: 'npm:driver', action: 'update-available', binding: { id: 'npm:driver', version: '1.1.0' } }] } });
|
||||
on({ name: 'tail', plan: { revision: 'b', blocked: false, changes: [
|
||||
{ name: 'tail', target: 'pi', id: 'npm:tail', action: 'update-available', binding: { id: 'npm:tail', version: '2.1.0' } },
|
||||
{ name: 'tail', target: 'codex', id: 'tail@market', action: 'update-available', binding: { id: 'tail@market', version: '2.1.0' } },
|
||||
] } });
|
||||
});
|
||||
};
|
||||
it('checks for updates on its own and sends every plugin ticked in one batch', async () => {
|
||||
twoBehind();
|
||||
@@ -222,8 +224,7 @@ describe('PluginsPage', () => {
|
||||
it('still blocks an unsafe OMP plan but allows a reviewed fresh install without a special confirmation', async () => {
|
||||
synced.targets = [{ name: 'omp' }, { name: 'omp-work', agent: 'omp' }];
|
||||
vi.mocked(pluginsApi.list).mockResolvedValue(omp({ omp: { id: 'guard', source: 'owner/guard', sync: false } }, [{ id: 'guard', enabled: true }]));
|
||||
// The page checks for updates on its own first.
|
||||
vi.mocked(pluginsApi.preview).mockResolvedValueOnce({ revision: 'c', blocked: false, changes: [] }).mockResolvedValueOnce({ revision: 'r1', blocked: true, changes: [{ name: 'guard', target: 'omp', id: 'guard', action: 'blocked', message: 'OMP scoped removal cannot verify this installation or runtime ownership.', messageKey: 'plugins.error.ompRemovalOwnership' }] });
|
||||
vi.mocked(pluginsApi.preview).mockResolvedValueOnce({ revision: 'r1', blocked: true, changes: [{ name: 'guard', target: 'omp', id: 'guard', action: 'blocked', message: 'OMP scoped removal cannot verify this installation or runtime ownership.', messageKey: 'plugins.error.ompRemovalOwnership' }] });
|
||||
mount();
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'plugins.sync' }));
|
||||
const dialog = await screen.findByRole('dialog', { name: 'plugins.preview' });
|
||||
|
||||
@@ -58,7 +58,7 @@ export default function PluginsPage() {
|
||||
const [browsing, setBrowsing] = useState<{ name: string; source?: string } | null>(null);
|
||||
const [menu, setMenu] = useState<{ x: number; y: number; items: ContextMenuItem[] } | null>(null);
|
||||
const refresh = () => void invalidate(cache, 'pluginsChanged');
|
||||
const { busy, working, failure, review, updates, outcomes, checked, checking, batch, pendingUpdates, preview, begin, apply, selectTarget, check, updateMany, importMany, stopBatch, closeBatch, closeReview, clearResult, todo, active, idle, changed, isPi } =
|
||||
const { busy, working, failure, review, updates, outcomes, checked, checking, checkProgress, checkFailures, batch, pendingUpdates, preview, begin, apply, selectTarget, check, updateMany, importMany, stopBatch, closeBatch, closeReview, clearResult, todo, active, idle, changed, isPi } =
|
||||
usePluginsFlow({ t, inventory: data, refresh, onPreviewed: () => { setAdding(null); setImporting(false); } });
|
||||
const [updating, setUpdating] = useState(false);
|
||||
// Once per visit, as soon as there is a plugin to ask about: the rows say what has a new version without a click.
|
||||
@@ -110,7 +110,7 @@ export default function PluginsPage() {
|
||||
const piPackages = names.filter(isPi);
|
||||
const plugins = names.filter((name) => !isPi(name));
|
||||
const list = (shown: string[], pi?: boolean) => data && (
|
||||
<PluginList inventory={data} names={shown} pi={pi} updates={updates} busy={busy} working={working} onToggle={(name, target, on) => void selectTarget(name, target, on)} onMenu={openMenu} onAdd={begin} onBlocked={(name, source) => setAdding({ name, source, bound: data.packages[name]?.bindings, recorded: data.packages[name] })} />
|
||||
<PluginList inventory={data} names={shown} pi={pi} updates={updates} checkFailures={checkFailures} busy={busy} working={working} onToggle={(name, target, on) => void selectTarget(name, target, on)} onMenu={openMenu} onAdd={begin} onBlocked={(name, source) => setAdding({ name, source, bound: data.packages[name]?.bindings, recorded: data.packages[name] })} />
|
||||
);
|
||||
const importHosts = (data?.hosts ?? []).map((h) => {
|
||||
const locked = !pluginTargets[h.target]?.operations.includes('import');
|
||||
@@ -173,7 +173,7 @@ export default function PluginsPage() {
|
||||
<PageHeader title={t('plugins.title')} subtitle={t('plugins.subtitle')} actions={<>
|
||||
{shareable.length > 0 && <Button variant="ghost" disabled={busy} onClick={() => setSharing(shareable.map((p) => p.name))}><Share2 size={15} />{t('plugins.share')}</Button>}
|
||||
{packages.length > 0 && (checking
|
||||
? <span className="flex items-center gap-1.5 px-3 text-[13px] text-ink-3"><Spinner size="sm" />{t('plugins.checkingUpdates')}</span>
|
||||
? <span className="flex items-center gap-1.5 px-3 text-[13px] text-ink-3"><Spinner size="sm" />{t('plugins.checkingUpdates')}{checkProgress.total > 0 && <span className="tabular-nums">{checkProgress.done}/{checkProgress.total}</span>}</span>
|
||||
: <Button variant="ghost" disabled={busy} onClick={() => (updatable > 0 ? setUpdating(true) : void check().then((ok) => ok && setUpdating(true)))}><RefreshCw size={15} />{updatable > 0 ? t(plural('plugins.updateCount', updatable), { count: updatable }) : t('plugins.check')}</Button>)}
|
||||
{addActions}
|
||||
</>} />
|
||||
|
||||
@@ -39,6 +39,7 @@ export default defineConfig({
|
||||
'/api/update/stream': SSE_PROXY,
|
||||
'/api/check/stream': SSE_PROXY,
|
||||
'/api/diff/stream': SSE_PROXY,
|
||||
'/api/plugins/check/stream': SSE_PROXY,
|
||||
'/api/plugins/update/stream': SSE_PROXY,
|
||||
// Keep the browser's Host header: the MCP endpoints compare it against Origin,
|
||||
// and changeOrigin (the string shorthand's default) would rewrite it to the target.
|
||||
|
||||
@@ -122,7 +122,10 @@ components are not also copied into standalone Skillshare sources.
|
||||
## Updates and recovery {#updates-and-recovery}
|
||||
|
||||
The Plugins page checks for updates when it opens, and **Check updates** checks
|
||||
again on demand. A row whose source has a newer version shows `old → new`, and
|
||||
again on demand. Plugins are checked at the same time: each row shows its result
|
||||
as soon as its own check finishes, and the header counts the plugins checked so
|
||||
far. A plugin that cannot be checked shows **Check failed**, including one whose
|
||||
Agent's CLI does not answer within 60 seconds; hover it for the reason. A row whose source has a newer version shows `old → new`, and
|
||||
the header button reads **Update N**. It opens one dialog that lists every plugin
|
||||
with an update, ticked by default, with the Agents it is installed on; untick a
|
||||
plugin or an Agent to leave it out. **Update N plugins** runs the picks one at a
|
||||
|
||||
@@ -441,7 +441,9 @@ skillshare plugin update review --source-ref v1.1.0 --target claude --dry-run --
|
||||
|
||||
Shared bindings record `source_ref`; the resolved `commit` stays in the local receipt. Installation uses the
|
||||
locally reviewed commit; `check` and `update` resolve the configured ref again, so a branch
|
||||
can advance while a commit remains pinned. `--revision` is a preview token, not
|
||||
can advance while a commit remains pinned. Without a configured ref, `check` first asks the
|
||||
remote which commit its default branch points at, and downloads the source only when that
|
||||
commit differs from the installed one. `--revision` is a preview token, not
|
||||
a Git ref. `--entry` is relative to each candidate's package root and must already
|
||||
exist; it does not trigger a build or package-manager install.
|
||||
|
||||
|
||||
+1
-1
@@ -103,7 +103,7 @@ skillshare の Source にコピーされることはありません。
|
||||
|
||||
## 更新と復旧 {#updates-and-recovery}
|
||||
|
||||
Plugins ページは開いたときに更新を確認し、**Check updates** でいつでも再確認できます。source に新しいバージョンがある行には `old → new` が表示され、ヘッダーのボタンは **Update N** になります。これを押すと、更新のある plugin をすべて一覧にした 1 つのダイアログが開きます。初期状態ではすべてチェック済みで、各 plugin がインストールされている Agent も表示されます。plugin や Agent のチェックを外すと、その分は更新されません。**Update N plugins** は選んだものを 1 つずつ実行し、各行を待機中、更新中、更新済み、失敗、スキップのいずれかで表示します。**Stop after this one** は実行中の plugin を終えたところで止め、残りは更新しません。失敗した行には、更新できた Agent と失敗した Agent がエラーとともに表示され、**Retry** は失敗した Agent だけに再送します。結果はページに反映されるため、再度チェックする必要はありません。チェック後に source が変わっていた場合は何もインストールされないので、もう一度チェックして新しいバージョンを確認してください。ただし Pi の npm パッケージは例外で、Pi は npm が latest とするバージョンをインストールします。すべて最新のときは、ダイアログに各 plugin が Agent とバージョン付きで一覧表示されます。
|
||||
Plugins ページは開いたときに更新を確認し、**Check updates** でいつでも再確認できます。plugin はすべて同時に確認され、各行は自分の確認が終わった時点で結果を表示し、ヘッダーには確認済みの数が表示されます。確認できなかった plugin(Agent の CLI が 60 秒以内に応答しない場合を含む)には **Check failed** が表示され、マウスを重ねると理由がわかります。source に新しいバージョンがある行には `old → new` が表示され、ヘッダーのボタンは **Update N** になります。これを押すと、更新のある plugin をすべて一覧にした 1 つのダイアログが開きます。初期状態ではすべてチェック済みで、各 plugin がインストールされている Agent も表示されます。plugin や Agent のチェックを外すと、その分は更新されません。**Update N plugins** は選んだものを 1 つずつ実行し、各行を待機中、更新中、更新済み、失敗、スキップのいずれかで表示します。**Stop after this one** は実行中の plugin を終えたところで止め、残りは更新しません。失敗した行には、更新できた Agent と失敗した Agent がエラーとともに表示され、**Retry** は失敗した Agent だけに再送します。結果はページに反映されるため、再度チェックする必要はありません。チェック後に source が変わっていた場合は何もインストールされないので、もう一度チェックして新しいバージョンを確認してください。ただし Pi の npm パッケージは例外で、Pi は npm が latest とするバージョンをインストールします。すべて最新のときは、ダイアログに各 plugin が Agent とバージョン付きで一覧表示されます。
|
||||
|
||||
Claude はネイティブな CLI 経由で更新できます。Codex はレビュー済みのスナップショットからプラグインを再度 add します。ただし Codex で無効化されている場合は、add で再び有効になってしまうため更新しません。Import した Codex プラグインは marketplace のアップグレードで更新されます。Cursor と Antigravity は、ローカルの編集がないか確認した後、管理対象のローカルコピーを置き換えます。Pi と OpenCode はレビュー済みのスナップショットを更新します。Copilot と Antigravity CLI は既知の有効状態を保持しながらレビュー済みの Source を更新できます。Grok の更新はネイティブツール側にとどまり、ダイアログではそうしたインストールを **Update inside the Agent** の下に分けて表示します。インポートされたパッケージの制限についてはコマンドリファレンスを参照してください。互換性のある plugin を提供しなくなった source は **Cannot update** に表示されます。update が対応できない Target は理由を示してスキップされ、その plugin のほかの Agent は通常どおり更新されます。
|
||||
|
||||
|
||||
@@ -276,7 +276,7 @@ skillshare plugin add ./package --entry dist/plugin.js --target opencode --no-tu
|
||||
skillshare plugin update review --source-ref v1.1.0 --target claude --dry-run --json
|
||||
```
|
||||
|
||||
共有バインディングには `source_ref` を記録し、解決済みの `commit` はローカルの記録に保存します。インストールには reviewed されたコミットが使われます。`check` と `update` は設定された ref を再度解決するため、コミットが固定されたままブランチが進むことがあります。`--revision` は Git ref ではなくプレビュートークンです。`--entry` は各候補の package ルートからの相対パスであり、既に存在している必要があります。ビルドや package manager のインストールをトリガーすることはありません。
|
||||
共有バインディングには `source_ref` を記録し、解決済みの `commit` はローカルの記録に保存します。インストールには reviewed されたコミットが使われます。`check` と `update` は設定された ref を再度解決するため、コミットが固定されたままブランチが進むことがあります。ref を設定していない場合、`check` はまずリモートのデフォルトブランチが指す commit を問い合わせ、インストール済みの commit と異なるときだけソースをダウンロードします。`--revision` は Git ref ではなくプレビュートークンです。`--entry` は各候補の package ルートからの相対パスであり、既に存在している必要があります。ビルドや package manager のインストールをトリガーすることはありません。
|
||||
|
||||
Copilot と Antigravity CLI のインストールは、reviewed されたローカルスナップショットを使用します。インポートには再インストール用の reviewed source がありません。削除後は、ネイティブクライアントでインストールしてから再度 sync してください。Grok もインストール/再インストール前にネイティブな trust が必要です。Skillshare はネイティブな trust の承認フラグを提供しません。
|
||||
|
||||
|
||||
+1
-1
@@ -105,7 +105,7 @@ skillshare sync plugins --no-tui
|
||||
|
||||
## 업데이트와 복구 {#updates-and-recovery}
|
||||
|
||||
Plugins 페이지는 열릴 때 업데이트를 확인하며, **Check updates**로 언제든 다시 확인할 수 있습니다. source에 더 새로운 버전이 있는 행에는 `old → new`가 표시되고 헤더 버튼은 **Update N**이 됩니다. 이 버튼은 업데이트가 있는 모든 plugin을 나열한 하나의 대화상자를 엽니다. 기본적으로 모두 선택되어 있고 각 plugin이 설치된 Agent도 함께 표시됩니다. plugin이나 Agent의 선택을 해제하면 그 항목은 제외됩니다. **Update N plugins**는 선택한 항목을 하나씩 실행하며 각 행을 대기 중, 업데이트 중, 업데이트됨, 실패, 건너뜀 중 하나로 표시합니다. **Stop after this one**은 실행 중인 plugin까지만 마치고 나머지는 그대로 둡니다. 실패한 행에는 업데이트된 Agent와 실패한 Agent가 오류와 함께 표시되며, **Retry**는 실패한 Agent에만 다시 보냅니다. 결과가 페이지에 반영되므로 다시 확인할 필요가 없습니다. 확인 이후 source가 바뀌었다면 아무것도 설치되지 않으니 다시 확인하여 새 버전을 검토하세요. 단, Pi의 npm 패키지는 예외로, Pi는 npm이 latest로 지정한 버전을 설치합니다. 모두 최신이면 대화상자에 각 plugin이 Agent와 버전과 함께 나열됩니다.
|
||||
Plugins 페이지는 열릴 때 업데이트를 확인하며, **Check updates**로 언제든 다시 확인할 수 있습니다. 모든 plugin은 동시에 확인되며, 각 행은 자신의 확인이 끝나는 즉시 결과를 표시하고 헤더에는 지금까지 확인한 개수가 표시됩니다. 확인하지 못한 plugin(Agent의 CLI가 60초 안에 응답하지 않는 경우 포함)에는 **Check failed**가 표시되며, 마우스를 올리면 이유를 볼 수 있습니다. source에 더 새로운 버전이 있는 행에는 `old → new`가 표시되고 헤더 버튼은 **Update N**이 됩니다. 이 버튼은 업데이트가 있는 모든 plugin을 나열한 하나의 대화상자를 엽니다. 기본적으로 모두 선택되어 있고 각 plugin이 설치된 Agent도 함께 표시됩니다. plugin이나 Agent의 선택을 해제하면 그 항목은 제외됩니다. **Update N plugins**는 선택한 항목을 하나씩 실행하며 각 행을 대기 중, 업데이트 중, 업데이트됨, 실패, 건너뜀 중 하나로 표시합니다. **Stop after this one**은 실행 중인 plugin까지만 마치고 나머지는 그대로 둡니다. 실패한 행에는 업데이트된 Agent와 실패한 Agent가 오류와 함께 표시되며, **Retry**는 실패한 Agent에만 다시 보냅니다. 결과가 페이지에 반영되므로 다시 확인할 필요가 없습니다. 확인 이후 source가 바뀌었다면 아무것도 설치되지 않으니 다시 확인하여 새 버전을 검토하세요. 단, Pi의 npm 패키지는 예외로, Pi는 npm이 latest로 지정한 버전을 설치합니다. 모두 최신이면 대화상자에 각 plugin이 Agent와 버전과 함께 나열됩니다.
|
||||
|
||||
Claude는 네이티브 CLI를 통해 업데이트할 수 있습니다. Codex는 검토된 스냅샷에서 플러그인을 다시 add합니다. 단, Codex에서 비활성화된 플러그인은 add하면 다시 활성화되므로 업데이트하지 않습니다. Import한 Codex 플러그인은 마켓플레이스를 업그레이드하여 업데이트합니다. Cursor와 Antigravity는 로컬 편집을 확인한 후 관리되는 로컬 복사본을 교체합니다. Pi와 OpenCode는 검토된 스냅샷을 업데이트합니다. Copilot과 Antigravity CLI는 알려진 활성화 상태를 보존하면서 검토된 Source를 새로고침할 수 있습니다. Grok의 업데이트는 네이티브 도구 안에 머무르며, 대화상자는 이런 설치를 **Update inside the Agent** 아래에 따로 나열합니다. Import된 패키지의 제한 사항은 명령어 레퍼런스를 참고하세요. 호환되는 plugin을 더 이상 제공하지 않는 source는 **Cannot update** 아래에 표시됩니다. 업데이트가 처리할 수 없는 Target은 이유와 함께 건너뛰며, 해당 플러그인의 다른 Agent는 그대로 업데이트됩니다.
|
||||
|
||||
|
||||
@@ -204,7 +204,7 @@ skillshare plugin add ./package --entry dist/plugin.js --target opencode --no-tu
|
||||
skillshare plugin update review --source-ref v1.1.0 --target claude --dry-run --json
|
||||
```
|
||||
|
||||
공유 바인딩은 `source_ref`를 기록하고 해석된 `commit`은 로컬 기록에 저장합니다. 설치는 검토된 commit을 사용합니다. `check`와 `update`는 구성된 ref를 다시 해석하므로, commit이 고정된 상태에서도 브랜치는 진행될 수 있습니다. `--revision`은 Git ref가 아니라 미리보기 토큰입니다. `--entry`는 각 후보의 패키지 루트를 기준으로 하며 이미 존재해야 합니다. 이는 빌드나 패키지 매니저 설치를 트리거하지 않습니다.
|
||||
공유 바인딩은 `source_ref`를 기록하고 해석된 `commit`은 로컬 기록에 저장합니다. 설치는 검토된 commit을 사용합니다. `check`와 `update`는 구성된 ref를 다시 해석하므로, commit이 고정된 상태에서도 브랜치는 진행될 수 있습니다. ref를 설정하지 않았다면 `check`는 먼저 원격의 기본 브랜치가 가리키는 commit을 확인하고, 설치된 commit과 다를 때만 소스를 다운로드합니다. `--revision`은 Git ref가 아니라 미리보기 토큰입니다. `--entry`는 각 후보의 패키지 루트를 기준으로 하며 이미 존재해야 합니다. 이는 빌드나 패키지 매니저 설치를 트리거하지 않습니다.
|
||||
|
||||
Copilot과 Antigravity CLI 설치는 검토된 로컬 스냅샷을 사용합니다. import된 항목은 재설치를 위한 검토된 source가 없습니다: 제거 후에는 네이티브 클라이언트에서 설치하고 다시 sync하세요. Grok도 설치/재설치 전에 네이티브 trust가 필요합니다. Skillshare는 네이티브 trust 승인 플래그를 절대 제공하지 않습니다.
|
||||
|
||||
|
||||
+1
-1
@@ -102,7 +102,7 @@ Plugin 与一般的 Skill 及 MCP 同步是彼此独立的。它们所打包的
|
||||
|
||||
## 更新与恢复 {#updates-and-recovery}
|
||||
|
||||
Plugins 页面打开时会检查更新,也可以随时用 **Check updates** 再检查一次。source 有较新版本的行会显示 `old → new`,标题栏的按钮变为 **Update N**。点击后会打开一个对话框,列出所有有更新的 plugin,默认全部勾选,并显示各 plugin 安装在哪些 Agent 上;取消勾选某个 plugin 或某个 Agent 即可排除。**Update N plugins** 会逐个执行所选项目,并把每一行显示为等待中、更新中、已更新、失败或已跳过。**Stop after this one** 会在正在更新的 plugin 完成后停止,其余不再更新。失败的行会列出已更新和失败的 Agent 以及错误信息,**Retry** 只会重新处理失败的 Agent。结果会同步到页面,无需再次检查。如果 source 在检查之后发生了变化,则不会安装任何内容;请再次检查以审核新版本。Pi 的 npm 包是例外:Pi 会安装 npm 标为 latest 的版本。全部都是最新版本时,对话框会列出每个 plugin 及其 Agent 与版本。
|
||||
Plugins 页面打开时会检查更新,也可以随时用 **Check updates** 再检查一次。所有 plugin 会同时检查:每一行在自己的检查完成后就显示结果,标题栏会显示已检查的数量。无法检查的 plugin(包括 Agent 的 CLI 在 60 秒内没有响应的情况)会显示 **Check failed**,鼠标悬停可以看到原因。source 有较新版本的行会显示 `old → new`,标题栏的按钮变为 **Update N**。点击后会打开一个对话框,列出所有有更新的 plugin,默认全部勾选,并显示各 plugin 安装在哪些 Agent 上;取消勾选某个 plugin 或某个 Agent 即可排除。**Update N plugins** 会逐个执行所选项目,并把每一行显示为等待中、更新中、已更新、失败或已跳过。**Stop after this one** 会在正在更新的 plugin 完成后停止,其余不再更新。失败的行会列出已更新和失败的 Agent 以及错误信息,**Retry** 只会重新处理失败的 Agent。结果会同步到页面,无需再次检查。如果 source 在检查之后发生了变化,则不会安装任何内容;请再次检查以审核新版本。Pi 的 npm 包是例外:Pi 会安装 npm 标为 latest 的版本。全部都是最新版本时,对话框会列出每个 plugin 及其 Agent 与版本。
|
||||
|
||||
Claude 可以通过其原生 CLI 进行更新。Codex 会用经审核的快照再次 add 该 plugin;但若它在 Codex 中被停用则不会更新,因为 add 会把它重新启用;导入的 Codex plugin 则通过升级其 marketplace 来更新。Cursor 与 Antigravity 会在检查本地编辑后替换受管理的本地副本。Pi 与 OpenCode 会更新经审核的快照。Copilot 与 Antigravity CLI 可以在保留已知启用状态的同时刷新一份经审核的 Source。Grok 的更新仍留在原生工具中处理,对话框会把这类安装单独列在 **Update inside the Agent** 下;被 import 套件的限制请参见命令参考文档。不再提供兼容 plugin 的 source 会列在 **Cannot update** 下。更新无法处理的 Target 会被跳过并说明原因,该 plugin 的其他 Agent 仍会照常更新。
|
||||
|
||||
|
||||
+1
-1
@@ -282,7 +282,7 @@ skillshare plugin update review --source-ref v1.1.0 --target claude --dry-run --
|
||||
```
|
||||
|
||||
共享绑定记录 `source_ref`;解析出的 `commit` 保存在本机记录。安装使用的是已审阅的 commit;`check` 和 `update`
|
||||
会重新解析配置的 ref,因此分支可以继续推进,而 commit 则保持锁定。`--revision` 是一个预览
|
||||
会重新解析配置的 ref,因此分支可以继续推进,而 commit 则保持锁定。没有配置 ref 时,`check` 会先询问远端默认分支指向哪个 commit,只有与已安装的 commit 不同时才下载来源。`--revision` 是一个预览
|
||||
token,而不是 Git ref。`--entry` 是相对于每个候选 package root 的路径,且必须已存在;
|
||||
它不会触发构建或 package manager 安装。
|
||||
|
||||
|
||||
+1
-1
@@ -88,7 +88,7 @@ Skillshare Source 中。
|
||||
|
||||
## 更新與復原 {#updates-and-recovery}
|
||||
|
||||
Plugins 頁面開啟時會檢查更新,也可以隨時用 **Check updates** 再檢查一次。source 有較新版本的列會顯示 `old → new`,標題列的按鈕會變成 **Update N**。點下去會開啟一個對話框,列出所有有更新的 plugin,預設全部勾選,並顯示各 plugin 安裝在哪些 Agent 上;取消勾選某個 plugin 或某個 Agent 即可排除。**Update N plugins** 會逐一執行所選項目,並把每一列顯示為等待中、更新中、已更新、失敗或已略過。**Stop after this one** 會在正在更新的 plugin 完成後停止,其餘不再更新。失敗的列會列出已更新和失敗的 Agent 以及錯誤訊息,**Retry** 只會重送失敗的 Agent。結果會同步到頁面,不需要再檢查一次。如果 source 在檢查之後有變動,則不會安裝任何內容;請再檢查一次以審閱新版本。Pi 的 npm 套件是例外:Pi 會安裝 npm 標為 latest 的版本。全部都是最新版本時,對話框會列出每個 plugin 及其 Agent 與版本。
|
||||
Plugins 頁面開啟時會檢查更新,也可以隨時用 **Check updates** 再檢查一次。所有 plugin 會同時檢查:每一列在自己的檢查完成後就顯示結果,標題列會顯示已檢查的數量。無法檢查的 plugin(包括 Agent 的 CLI 在 60 秒內沒有回應的情況)會顯示 **Check failed**,滑鼠移上去可以看到原因。source 有較新版本的列會顯示 `old → new`,標題列的按鈕會變成 **Update N**。點下去會開啟一個對話框,列出所有有更新的 plugin,預設全部勾選,並顯示各 plugin 安裝在哪些 Agent 上;取消勾選某個 plugin 或某個 Agent 即可排除。**Update N plugins** 會逐一執行所選項目,並把每一列顯示為等待中、更新中、已更新、失敗或已略過。**Stop after this one** 會在正在更新的 plugin 完成後停止,其餘不再更新。失敗的列會列出已更新和失敗的 Agent 以及錯誤訊息,**Retry** 只會重送失敗的 Agent。結果會同步到頁面,不需要再檢查一次。如果 source 在檢查之後有變動,則不會安裝任何內容;請再檢查一次以審閱新版本。Pi 的 npm 套件是例外:Pi 會安裝 npm 標為 latest 的版本。全部都是最新版本時,對話框會列出每個 plugin 及其 Agent 與版本。
|
||||
|
||||
Claude 可透過其原生 CLI 更新。Codex 會以已審閱的快照再次 add 該 plugin;但若它在 Codex 中被停用則不會更新,因為 add 會把它重新啟用;匯入的 Codex plugin 則以升級其 marketplace 的方式更新。Cursor 與 Antigravity 會在檢查過本機是否有編輯後,取代受管理的本機副本。Pi 與 OpenCode 會更新已審閱的快照。Copilot 與 Antigravity CLI 可以在保留已知啟用狀態的同時重新整理已審閱的來源。Grok 的更新仍留在原生工具中進行,對話框會把這類安裝獨立列在 **Update inside the Agent** 下;匯入套件的限制請參閱指令參考。不再提供相容 plugin 的 source 會列在 **Cannot update** 下。更新無法處理的 target 會被略過並說明原因,該 plugin 的其他 Agent 仍會照常更新。
|
||||
|
||||
|
||||
+1
-1
@@ -285,7 +285,7 @@ skillshare plugin update review --source-ref v1.1.0 --target claude --dry-run --
|
||||
```
|
||||
|
||||
共用綁定會記錄 `source_ref`;解析後的 `commit` 保存在本機記錄。安裝使用的是已檢視過的 commit;`check` 與
|
||||
`update` 會重新解析設定的 ref,因此某個 branch 可以持續前進,而 commit 仍維持固定。`--revision`
|
||||
`update` 會重新解析設定的 ref,因此某個 branch 可以持續前進,而 commit 仍維持固定。沒有設定 ref 時,`check` 會先問遠端預設 branch 指向哪個 commit,只有和已安裝的 commit 不同時才下載來源。`--revision`
|
||||
是預覽用的 token,不是 Git ref。`--entry` 是相對於各候選項套件根目錄的路徑,且必須已經存在;
|
||||
它不會觸發 build 或 package manager 安裝。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user