mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-19 02:17:09 +00:00
fix(plugin): leave private npm registries to Pi, and keep updates for Agents still behind
Codex review on #400: - The update check asked the public npm registry about every unpinned Pi package, even when the environment or an .npmrc sends the package, or its scope, to another registry. A public package with the same name could then hide a real update or offer an unrelated version. The check now reads the npm registry settings for the package and its scope from the environment, Pi's npm folder and the user .npmrc, and falls back to checking in Pi when any of them names another registry. - The row's Update button disappeared as soon as any Agent had the version the check found, so with one Pi target behind and another up to date, the one behind lost it. The row now compares each selected Agent with that version on its own, and updates only the ones behind.
This commit is contained in:
@@ -6,8 +6,11 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -148,10 +151,15 @@ var npmRegistry = "https://registry.npmjs.org"
|
||||
// where either is unknown. latests holds the registry's answers for one preview.
|
||||
// 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, id string, h Host, latests map[string][]int) (installed, latest []int) {
|
||||
func (s *Service) npmVersions(ctx context.Context, target, id string, h Host, latests map[string][]int) (installed, latest []int) {
|
||||
if !isNpmSource(id) || pinnedNpm(id) != "" {
|
||||
return nil, nil
|
||||
}
|
||||
name, _ := npmSpec(id)
|
||||
settings, err := s.piSettingsPath(target)
|
||||
if err != nil || !npmUsesPublicRegistry(filepath.Join(filepath.Dir(settings), "npm"), name) {
|
||||
return nil, nil
|
||||
}
|
||||
for _, item := range h.Installed {
|
||||
if item.ID == id {
|
||||
installed = plainVersion(item.Version)
|
||||
@@ -160,7 +168,6 @@ func (s *Service) npmVersions(ctx context.Context, id string, h Host, latests ma
|
||||
if installed == nil {
|
||||
return nil, nil
|
||||
}
|
||||
name, _ := npmSpec(id)
|
||||
latest, ok := latests[name]
|
||||
if !ok {
|
||||
latest = plainVersion(npmLatest(ctx, name))
|
||||
@@ -169,6 +176,46 @@ func (s *Service) npmVersions(ctx context.Context, id string, h Host, latests ma
|
||||
return installed, latest
|
||||
}
|
||||
|
||||
// npmUsesPublicRegistry reports whether npm, run in dir as Pi runs it, fetches name from the
|
||||
// public registry: no registry setting for the package's scope, or for everything, names
|
||||
// another one in the environment or in the .npmrc files npm reads first.
|
||||
// ponytail: reads the environment, dir's .npmrc and the user .npmrc, not npm's global or builtin
|
||||
// config; ask `npm config get` if a registry set only there must be seen.
|
||||
func npmUsesPublicRegistry(dir, name string) bool {
|
||||
keys := []string{"registry"}
|
||||
if scope, _, ok := strings.Cut(name, "/"); ok && strings.HasPrefix(scope, "@") {
|
||||
keys = append(keys, scope+":registry")
|
||||
}
|
||||
public := func(value string) bool {
|
||||
value = strings.TrimSuffix(strings.Trim(strings.TrimSpace(value), `"'`), "/")
|
||||
return value == "" || strings.TrimSuffix(npmRegistry, "/") == value || value == "https://registry.npmjs.org"
|
||||
}
|
||||
for _, key := range keys {
|
||||
if !public(os.Getenv("npm_config_"+key)) || !public(os.Getenv("NPM_CONFIG_"+strings.ToUpper(key))) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
user := os.Getenv("NPM_CONFIG_USERCONFIG")
|
||||
if user == "" {
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
user = filepath.Join(home, ".npmrc")
|
||||
}
|
||||
}
|
||||
for _, path := range []string{filepath.Join(dir, ".npmrc"), user} {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for line := range strings.SplitSeq(string(data), "\n") {
|
||||
key, value, ok := strings.Cut(line, "=")
|
||||
if ok && slices.Contains(keys, strings.TrimSpace(key)) && !public(value) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// npmLatest is the version npm's "latest" tag names, "" when the registry does not say.
|
||||
func npmLatest(ctx context.Context, name string) string {
|
||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
|
||||
@@ -321,6 +321,36 @@ func TestNpmPackageCheckFallsBackToPiWhenNpmDoesNotAnswer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A package npm fetches from another registry may share its name with a public one; npmjs's
|
||||
// latest says nothing about it.
|
||||
func TestNpmPackageCheckLeavesAPrivateRegistryToPi(t *testing.T) {
|
||||
for name, npmrc := range map[string]struct{ dir, body string }{
|
||||
"user registry": {"", "registry=https://npm.example.com/\n"},
|
||||
"scope in Pi's folder": {".pi/agent/npm", "@acme:registry = https://npm.example.com/\n"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
fakeNpmRegistry(t, "1.2.0")
|
||||
var commands []string
|
||||
s := fakePiNpm(t, &commands)
|
||||
id := "npm:demo"
|
||||
if npmrc.dir != "" {
|
||||
id = "npm:@acme/demo"
|
||||
}
|
||||
applyPluginRequest(t, s, Request{Action: "add", Source: id, Name: "demo", Targets: []string{"pi"}})
|
||||
pkg, _ := npmSpec(id)
|
||||
writePluginFile(t, os.Getenv("HOME"), ".pi/agent/npm/node_modules/"+pkg+"/package.json", `{"version":"1.0.0"}`)
|
||||
writePluginFile(t, filepath.Join(os.Getenv("HOME"), npmrc.dir), ".npmrc", npmrc.body)
|
||||
p, err := s.Preview(context.Background(), Request{Action: "check", Name: "demo"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c := p.Changes[0]; c.Action != "native-check" {
|
||||
t.Fatalf("changes: %+v", p.Changes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverExplainsNpmPackagesCannotBePreviewed(t *testing.T) {
|
||||
_, err := Discover(context.Background(), "npm:demo")
|
||||
if err == nil || !strings.Contains(err.Error(), "plugin add npm:") {
|
||||
|
||||
@@ -454,7 +454,7 @@ func (s *Service) Preview(ctx context.Context, r Request) (*Plan, error) {
|
||||
}
|
||||
if b.Source == "" {
|
||||
// An npm package has no source snapshot to compare; npm names its latest version instead.
|
||||
installed, latest := s.npmVersions(ctx, b.ID, host(target), latests)
|
||||
installed, latest := s.npmVersions(ctx, target, b.ID, host(target), latests)
|
||||
known := installed != nil && latest != nil
|
||||
if known && slices.Compare(latest, installed) <= 0 {
|
||||
c.Action = "noop"
|
||||
|
||||
@@ -50,6 +50,9 @@ function Row({ name, pi, inventory, updates, busy, working, onToggle, onMenu, on
|
||||
const pack = inventory.packages[name];
|
||||
const bindings = Object.entries(pack.bindings) as [PluginTarget, NonNullable<(typeof pack.bindings)[PluginTarget]>][];
|
||||
const selected = bindings.filter(([, b]) => b.sync !== false).map(([target]) => target);
|
||||
// The Agents a check's version is still ahead of, each judged on its own: one already there leaves the others behind.
|
||||
const next = updates?.[name];
|
||||
const behind = next ? selected.filter((target) => pluginTargets[target]?.operations.includes('update') && bindingVersion(inventory, target, pack.bindings[target]!) !== next) : [];
|
||||
const versions = [...new Set(bindings.map(([target, b]) => bindingVersion(inventory, target, b)).filter(Boolean))];
|
||||
// With no Agent yet, the version recorded when the plugin was added is all there is; a plugin
|
||||
// added before that was recorded asks its source, through the same query the row opens with.
|
||||
@@ -105,8 +108,8 @@ function Row({ name, pi, inventory, updates, busy, working, onToggle, onMenu, on
|
||||
? <span className="ss-tag shrink-0 font-mono" title={bindings.filter(([target, b]) => bindingVersion(inventory, target, b)).map(([target, b]) => `${pluginTargets[target]?.label ?? target} ${bindingVersion(inventory, target, b)}`).join(' · ')}>{versions.join(' / ')}</span>
|
||||
: <VersionChange from={versions[0]} to={updates?.[name]} />}
|
||||
{/* A check found another version: update it from here, through the same review as the menu. */}
|
||||
{updates?.[name] && !versions.includes(updates[name]) && (
|
||||
<button type="button" className="ss-more min-h-6 shrink-0 disabled:opacity-50" disabled={busy} onClick={() => onAdd({ action: 'update', name, targets: selected.filter((target) => pluginTargets[target]?.operations.includes('update')) }, name)}>{t('plugins.update')}</button>
|
||||
{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>
|
||||
)}
|
||||
{bindings.some(([target, b]) => syncAction(b, inventory.hosts.find((h) => h.target === target))) && <span className="ss-tag warn">{t('plugins.pending')}</span>}
|
||||
{bindings.length === 0 && <span className="ss-tag">{t('plugins.noAgentsYet')}</span>}
|
||||
|
||||
@@ -149,6 +149,24 @@ describe('PluginsPage', () => {
|
||||
fireEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'plugins.update' }));
|
||||
await waitFor(() => expect(pluginsApi.preview).toHaveBeenLastCalledWith({ action: 'update', name: 'driver', targets: ['pi'] }));
|
||||
});
|
||||
it('keeps the row update for an Agent still behind when another Agent already has the new version', async () => {
|
||||
const pi = { label: 'Pi', project: false, operations: ['add', 'check', 'update'], npm: true };
|
||||
vi.mocked(pluginsApi.list).mockResolvedValue({
|
||||
targetDefinitions: [{ target: 'pi', ...pi }, { target: 'pi-work', ...pi, label: 'pi-work' }],
|
||||
packages: { driver: { bindings: { pi: { id: 'npm:driver' }, 'pi-work': { id: 'npm:driver' } } } },
|
||||
hosts: [
|
||||
{ target: 'pi', version: '0.99.2', status: 'ready', installed: [{ id: 'npm:driver', version: '1.0.0', enabled: true }] },
|
||||
{ target: 'pi-work', version: '0.99.2', status: 'ready', installed: [{ id: 'npm:driver', version: '1.1.0', enabled: true }] },
|
||||
],
|
||||
});
|
||||
vi.mocked(pluginsApi.preview).mockResolvedValue({ revision: 'r', blocked: false, changes: [{ name: 'driver', target: 'pi', id: 'npm:driver', action: 'update-available', binding: { id: 'npm:driver', version: '1.1.0' } }] });
|
||||
mount();
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'plugins.check' }));
|
||||
fireEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'common.cancel' }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
fireEvent.click(screen.getByRole('button', { name: 'plugins.update' }));
|
||||
await waitFor(() => expect(pluginsApi.preview).toHaveBeenLastCalledWith({ action: 'update', name: 'driver', targets: ['pi'] }));
|
||||
});
|
||||
it('offers an update on the list row once a check finds a newer version', async () => {
|
||||
vi.mocked(pluginsApi.list).mockResolvedValue({ targetDefinitions: [{ target: 'pi', label: 'Pi', project: false, operations: ['add', 'check', 'update'], npm: true }], packages: { driver: { bindings: { pi: { id: 'npm:driver' } } } }, hosts: [{ target: 'pi', version: '0.99.2', status: 'ready', installed: [{ id: 'npm:driver', version: '1.0.0', enabled: true }] }] });
|
||||
vi.mocked(pluginsApi.preview).mockResolvedValue({ revision: 'r', blocked: false, changes: [{ name: 'driver', target: 'pi', id: 'npm:driver', action: 'update-available', binding: { id: 'npm:driver', version: '1.1.0' } }] });
|
||||
|
||||
Reference in New Issue
Block a user