fix(plugins): unload previous version before reloading on plugin update (#1861)

* fix(plugins): unload previous version before reloading on plugin update

The install/update path reloaded a plugin without first unloading the
previous version's registrations, unlike disable/uninstall. Because the
slot registry only appends, this ran initialize() twice and left two
main-top-bar slot entries, duplicating the plugin's widget icon until
a page refresh.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(plugins): cache-bust plugin bundle import so updates re-execute

unloadPlugin(id, {evictCache: true}) drops the cached bundle registration
on install/update, but a same-tab re-import() of the identical bundle URL
returns the browser's already-evaluated ES module without re-running its
top-level registerKandevPlugin() call — leaving an updated plugin active
but missing from the UI. Key the bundle URL on the plugin's installed
version (?v=<version>) on both the frontend (toActivePlugin) and the
backend boot payload (bootActivePlugins) so a version bump forces a real
re-import while an unchanged version stays cache-friendly across boots.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(plugins): update bundleUrl assertions for cache-bust query param

toActivePlugin now appends a ?v=<version> cache-busting query param to
bundleUrl; these two assertions still expected the bare path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(plugins): only evict bundle cache on install/update, not on enable

loadIfActive unconditionally evicted the cached bundle registration, which
broke the disable->enable cycle: since bundleUrl doesn't change on plain
enable, the browser's ES module cache returned the already-evaluated module
without re-running registerKandevPlugin, leaving the plugin's slots/routes
unregistered until a full page refresh.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
João Salavisa
2026-07-22 13:45:18 +01:00
committed by GitHub
parent 24f2fba183
commit 07038018ac
9 changed files with 376 additions and 16 deletions
+16 -1
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io/fs"
"net/http"
"net/url"
"os"
"strings"
"time"
@@ -713,13 +714,27 @@ func bootActivePlugins(p routeParams) []webapp.ActivePluginPayload {
out = append(out, webapp.ActivePluginPayload{
ID: rec.ID,
Name: rec.DisplayName,
BundleURL: "/api/plugins/" + rec.ID + "/bundle",
BundleURL: pluginBundleURL(rec),
StyleURLs: pluginStyleURLs(rec),
})
}
return out
}
// pluginBundleURL builds the browser-facing bundle URL, mirrored on the
// frontend by lib/plugins/active-plugin.ts's toActivePlugin. The `?v=`
// query param keys the URL on the installed version so an updated plugin
// resolves to a *different* module specifier: without it,
// unloadPlugin(id, {evictCache: true}) (apps/web/lib/plugins/host.ts) drops
// the cached bundle registration on update, but a same-tab re-import() of
// the identical URL returns the browser's already-evaluated ES module
// without re-running its top-level registerKandevPlugin() call — leaving
// the plugin active but unregistered. An unchanged version keeps the same
// URL across boots, so normal (non-update) loads stay cache-friendly.
func pluginBundleURL(rec pluginstore.Record) string {
return "/api/plugins/" + rec.ID + "/bundle?v=" + url.QueryEscape(rec.Version)
}
// pluginStyleURLs maps a plugin's root-relative ui.styles paths to
// browser-facing URLs served through the /api/plugins/:id/ui/* proxy (the
// plugin's own base_url is never exposed to the browser directly).
@@ -108,6 +108,53 @@ func installTestPluginForBoot(t *testing.T, svc *plugins.Service, id string, wit
return rec
}
// testPluginPackageVersioned mirrors testPluginPackage but lets the caller
// pin a specific manifest version, so tests can simulate an update (same id,
// bumped version) via a second Install call.
func testPluginPackageVersioned(t *testing.T, id, version string) *bytes.Buffer {
t.Helper()
platformKey := goruntime.GOOS + "-" + goruntime.GOARCH
manifestYAML := fmt.Sprintf(`
id: %s
api_version: 1
version: %q
display_name: Test Plugin %s
capabilities:
events: ["task.created"]
runtime:
type: binary
executables:
%s: server/plugin
ui:
bundle: "/ui/bundle.js"
styles: ["/ui/style.css"]
`, id, version, id, platformKey)
var buf bytes.Buffer
files := map[string][]byte{
"manifest.yaml": []byte(manifestYAML),
"server/plugin": []byte("#!/bin/sh\necho fake\n"),
"ui/bundle.js": []byte("export default {};"),
"ui/style.css": []byte("body{}"),
}
if err := pkgtartest.WritePackage(&buf, files); err != nil {
t.Fatalf("WritePackage: %v", err)
}
return &buf
}
// installTestPluginPackageForBoot installs (or, on a repeat call with a new
// version, updates) the plugin with an explicit version — used to prove
// bootActivePlugins keys BundleURL on the installed version.
func installTestPluginPackageForBoot(t *testing.T, svc *plugins.Service, id, version string) *store.Record {
t.Helper()
rec, err := svc.Install(context.Background(), testPluginPackageVersioned(t, id, version))
if err != nil {
t.Fatalf("Install(%q@%s): %v", id, version, err)
}
return rec
}
func TestBootActivePluginsGatedOnFeatureFlag(t *testing.T) {
svc := newTestPluginsService(t)
installTestPluginForBoot(t, svc, "kandev-plugin-hello", true)
@@ -143,14 +190,72 @@ func TestBootActivePluginsPopulatesFromActiveUIPlugins(t *testing.T) {
if entry.ID != "kandev-plugin-hello" {
t.Fatalf("entry.ID = %q, want %q", entry.ID, "kandev-plugin-hello")
}
if entry.BundleURL != "/api/plugins/kandev-plugin-hello/bundle" {
t.Fatalf("entry.BundleURL = %q, want %q", entry.BundleURL, "/api/plugins/kandev-plugin-hello/bundle")
if entry.BundleURL != "/api/plugins/kandev-plugin-hello/bundle?v=1.0.0" {
t.Fatalf("entry.BundleURL = %q, want %q", entry.BundleURL, "/api/plugins/kandev-plugin-hello/bundle?v=1.0.0")
}
if len(entry.StyleURLs) != 1 || entry.StyleURLs[0] != "/api/plugins/kandev-plugin-hello/ui/ui/style.css" {
t.Fatalf("entry.StyleURLs = %v, want [/api/plugins/kandev-plugin-hello/ui/ui/style.css]", entry.StyleURLs)
}
}
// TestBootActivePluginsBundleURLChangesWithVersion proves the fix for the
// same-tab plugin-update bug: unloadPlugin(id, {evictCache:true}) evicts the
// cached bundle registration on update, but a same-tab re-import() of the
// same URL returns the browser's already-evaluated ES module without
// re-running its top-level registerKandevPlugin() call — leaving the plugin
// active but unregistered. Keying BundleURL on the installed version forces
// a real re-import (new module specifier) whenever the version changes,
// while keeping an unchanged version's URL byte-identical across boots.
func TestBootActivePluginsBundleURLChangesWithVersion(t *testing.T) {
dir := t.TempDir()
fsStore := store.NewFSStore(dir)
registry := plugins.NewRegistry()
if err := registry.Load(fsStore); err != nil {
t.Fatalf("load registry: %v", err)
}
svc := plugins.NewService(fsStore, registry, nil, testPluginsLogger(t))
svc.SetPluginsDir(dir)
svc.SetRuntime(alwaysUpRuntime{})
installTestPluginPackageForBoot(t, svc, "kandev-plugin-hello", "1.0.0")
first := bootActivePlugins(routeParams{
features: config.FeaturesConfig{Plugins: true},
services: &Services{Plugins: svc},
})
if len(first) != 1 {
t.Fatalf("bootActivePlugins() len = %d, want 1: %+v", len(first), first)
}
firstURL := first[0].BundleURL
if firstURL != "/api/plugins/kandev-plugin-hello/bundle?v=1.0.0" {
t.Fatalf("first BundleURL = %q, want %q", firstURL, "/api/plugins/kandev-plugin-hello/bundle?v=1.0.0")
}
// Same version reinstalled (no-op update) must resolve to the identical
// URL — no needless cache-busting.
repeat := bootActivePlugins(routeParams{
features: config.FeaturesConfig{Plugins: true},
services: &Services{Plugins: svc},
})
if repeat[0].BundleURL != firstURL {
t.Fatalf("repeat BundleURL = %q, want unchanged %q", repeat[0].BundleURL, firstURL)
}
// Update to a new version: the URL must differ so the browser re-imports
// and re-executes the bundle's registerKandevPlugin() side effect.
installTestPluginPackageForBoot(t, svc, "kandev-plugin-hello", "1.0.1")
updated := bootActivePlugins(routeParams{
features: config.FeaturesConfig{Plugins: true},
services: &Services{Plugins: svc},
})
updatedURL := updated[0].BundleURL
if updatedURL == firstURL {
t.Fatalf("updated BundleURL = %q, want different from %q after a version bump", updatedURL, firstURL)
}
if updatedURL != "/api/plugins/kandev-plugin-hello/bundle?v=1.0.1" {
t.Fatalf("updated BundleURL = %q, want %q", updatedURL, "/api/plugins/kandev-plugin-hello/bundle?v=1.0.1")
}
}
func TestBootActivePluginsNoServiceReturnsNil(t *testing.T) {
got := bootActivePlugins(routeParams{features: config.FeaturesConfig{Plugins: true}, services: &Services{}})
if got != nil {
+7 -2
View File
@@ -217,7 +217,12 @@ describe("PluginsSettingsPage", () => {
);
await vi.waitFor(() =>
expect(loadPluginsSpy).toHaveBeenCalledWith(
[expect.objectContaining({ id: PLUGIN_ID, bundleUrl: `/api/plugins/${PLUGIN_ID}/bundle` })],
[
expect.objectContaining({
id: PLUGIN_ID,
bundleUrl: `/api/plugins/${PLUGIN_ID}/bundle?v=1.0.0`,
}),
],
expect.any(Function),
),
);
@@ -266,7 +271,7 @@ describe("PluginsSettingsPage install dialog", () => {
[
expect.objectContaining({
id: NEW_PLUGIN_ID,
bundleUrl: `/api/plugins/${NEW_PLUGIN_ID}/bundle`,
bundleUrl: `/api/plugins/${NEW_PLUGIN_ID}/bundle?v=1.0.0`,
}),
],
expect.any(Function),
@@ -0,0 +1,105 @@
import { renderHook, act, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { ReactNode } from "react";
import { StateProvider } from "@/components/state-provider";
import type { PluginRecord } from "@/lib/types/plugins";
import type { InstallResult } from "@/lib/api/domains/plugins-api";
const loadPlugins = vi.fn(async () => {});
const unloadPlugin = vi.fn();
const installPluginFromUrl = vi.fn<() => Promise<InstallResult>>();
const installPluginUpload = vi.fn<() => Promise<InstallResult>>();
const enablePlugin = vi.fn(async () => ({ enabled: true }));
vi.mock("@/lib/plugins/host", () => ({
loadPlugins: (...args: unknown[]) => loadPlugins(...(args as [])),
unloadPlugin: (...args: unknown[]) => unloadPlugin(...(args as [])),
}));
vi.mock("@/lib/api/domains/plugins-api", async () => {
const actual = await vi.importActual<typeof import("@/lib/api/domains/plugins-api")>(
"@/lib/api/domains/plugins-api",
);
return {
...actual,
installPluginFromUrl: (...args: unknown[]) => installPluginFromUrl(...(args as [])),
installPluginUpload: (...args: unknown[]) => installPluginUpload(...(args as [])),
enablePlugin: (...args: unknown[]) => enablePlugin(...(args as [])),
};
});
import { usePluginActions } from "./use-plugin-actions";
function wrapper({ children }: { children: ReactNode }) {
return <StateProvider>{children}</StateProvider>;
}
function activeRecord(overrides: Partial<PluginRecord> = {}): PluginRecord {
return {
id: "acme-tools",
api_version: 1,
version: "2.0.0",
display_name: "Acme Tools",
description: "",
author: "",
categories: [],
capabilities: {},
status: "active",
install_path: "/home/user/.kandev/plugins/acme-tools/2.0.0",
signed: true,
installed_at: "2026-01-01T00:00:00Z",
restart_count: 0,
ui: { bundle: "/ui/bundle.js" },
...overrides,
};
}
beforeEach(() => {
loadPlugins.mockClear();
unloadPlugin.mockClear();
installPluginFromUrl.mockReset();
installPluginUpload.mockReset();
enablePlugin.mockClear();
});
describe("usePluginActions — install/update", () => {
it("unloads the plugin's previous registrations before reloading it, so an update doesn't leave duplicate slot registrations", async () => {
const plugin = activeRecord();
installPluginFromUrl.mockResolvedValue({ plugin });
const { result } = renderHook(() => usePluginActions(), { wrapper });
await act(async () => {
await result.current.submitInstallUrl("https://example.com/acme-tools.tar.gz");
});
await waitFor(() => expect(loadPlugins).toHaveBeenCalledTimes(1));
expect(unloadPlugin).toHaveBeenCalledWith(plugin.id, { evictCache: true });
const unloadOrder = unloadPlugin.mock.invocationCallOrder[0];
const loadOrder = loadPlugins.mock.invocationCallOrder[0];
expect(unloadOrder).toBeLessThan(loadOrder);
});
});
describe("usePluginActions — enable", () => {
it("does not evict the cached bundle registration on plain enable, so a disable-then-re-enable cycle reuses it", async () => {
const plugin = activeRecord();
const { result } = renderHook(() => usePluginActions(), { wrapper });
await act(async () => {
await result.current.handleEnable(plugin);
});
await waitFor(() => expect(loadPlugins).toHaveBeenCalledTimes(1));
// Enable must unload without evicting the cache — eviction is reserved
// for install/update, where the bundle content actually changed.
expect(unloadPlugin).toHaveBeenCalledWith(plugin.id);
expect(unloadPlugin).not.toHaveBeenCalledWith(plugin.id, { evictCache: true });
const unloadOrder = unloadPlugin.mock.invocationCallOrder[0];
const loadOrder = loadPlugins.mock.invocationCallOrder[0];
expect(unloadOrder).toBeLessThan(loadOrder);
});
});
@@ -26,15 +26,40 @@ function withStatus(plugin: PluginRecord, status: PluginStatus): PluginRecord {
return { ...plugin, status };
}
/** Loads a plugin's UI bundle into the running app, if it declares one. */
/**
* Loads a plugin's UI bundle into the running app, if it declares one.
* Unloads any previous registrations first — a first-time load is a safe
* no-op through `unloadPlugin` since nothing is registered yet.
*
* `evictCache` controls whether the cached bundle registration is dropped
* before reloading:
* - Install/update (`afterInstall`) passes `evictCache: true`: the backend
* install endpoint is also how an update is applied, so without eviction an
* update would leave the prior version's nav/route/slot registrations in
* place alongside the new ones (e.g. a duplicated top-bar widget), and
* `loadPlugins` would skip re-importing the bundle and re-run the old
* version's `initialize()` against the new registry entry.
* - Plain enable (`handleEnable`) passes `evictCache: false`: the disable path
* intentionally keeps the cached registration (see `unloadPlugin`'s doc) so
* a same-tab disable→enable cycle can reuse it without depending on the
* browser re-executing the bundle's module-eval side effect — the
* `bundleUrl` is unchanged, so a forced re-import would silently return the
* already-evaluated module without calling `registerKandevPlugin` again.
*/
async function loadIfActive(
record: PluginRecord,
storeApi: StoreApi<AppState>,
theme: "light" | "dark",
evictCache: boolean,
) {
if (record.status !== "active") return;
const active = toActivePlugin(record);
if (!active) return;
if (evictCache) {
unloadPlugin(record.id, { evictCache: true });
} else {
unloadPlugin(record.id);
}
await loadPlugins([active], (pluginId) => buildHostApi(pluginId, storeApi, theme));
}
@@ -55,7 +80,7 @@ function useEnableDisableActions(upsertPlugin: (p: PluginRecord) => void) {
await enablePlugin(plugin.id);
const updated = withStatus(plugin, "active");
upsertPlugin(updated);
await loadIfActive(updated, storeApi, resolvedTheme);
await loadIfActive(updated, storeApi, resolvedTheme, false);
} catch (err) {
toast.error(err instanceof Error ? err.message : `Failed to enable ${plugin.display_name}`);
} finally {
@@ -134,7 +159,7 @@ function useInstallAction(upsertPlugin: (p: PluginRecord) => void) {
// "installed" toast, so it takes priority over the success toast.
const afterInstall = async ({ plugin, warning }: InstallResult) => {
upsertPlugin(plugin);
await loadIfActive(plugin, storeApi, resolvedTheme);
await loadIfActive(plugin, storeApi, resolvedTheme, true);
if (warning) {
toast.warning(warning);
} else {
+15 -2
View File
@@ -23,14 +23,27 @@ function record(overrides: Partial<PluginRecord> = {}): PluginRecord {
}
describe("toActivePlugin", () => {
it("builds the bundle URL from the plugin id, mirroring the backend's boot payload mapping", () => {
it("builds the bundle URL from the plugin id and version, mirroring the backend's boot payload mapping", () => {
const result = toActivePlugin(record());
expect(result).not.toBeNull();
expect(result?.bundleUrl).toBe("/api/plugins/acme-tools/bundle");
expect(result?.bundleUrl).toBe("/api/plugins/acme-tools/bundle?v=1.0.0");
expect(result?.id).toBe("acme-tools");
expect(result?.name).toBe("Acme Tools");
});
it("appends the plugin's version as a cache-busting query param, so an updated version resolves to a new module specifier", () => {
const before = toActivePlugin(record({ version: "1.0.0" }));
const after = toActivePlugin(record({ version: "1.0.1" }));
expect(before?.bundleUrl).not.toBe(after?.bundleUrl);
expect(after?.bundleUrl).toBe("/api/plugins/acme-tools/bundle?v=1.0.1");
});
it("resolves to the identical bundleUrl on a plain unchanged reload (no needless cache-busting)", () => {
const first = toActivePlugin(record({ version: "1.0.0" }));
const second = toActivePlugin(record({ version: "1.0.0" }));
expect(first?.bundleUrl).toBe(second?.bundleUrl);
});
it("maps ui.styles to /api/plugins/:id/ui/:style, mirroring pluginStyleURLs on the backend", () => {
const result = toActivePlugin(
record({ ui: { bundle: "/ui/bundle.js", styles: ["/ui/a.css", "/ui/b.css"] } }),
+12 -1
View File
@@ -12,6 +12,17 @@ import type { PluginRecord } from "@/lib/types/plugins";
/**
* Returns the `ActivePlugin` for a plugin record, or null when the plugin
* declares no UI bundle (nothing to load).
*
* `bundleUrl` carries the installed `version` as a `?v=` query param so an
* updated plugin resolves to a *different* module specifier. Without this,
* `unloadPlugin(id, { evictCache: true })` (see `lib/plugins/host.ts`) drops
* the cached bundle registration, but a same-tab re-`import()` of the same
* URL returns the browser's already-evaluated ES module without re-running
* its top-level `registerKandevPlugin()` — leaving the plugin active but
* unregistered. Keying the URL on version keeps a plain unchanged
* enable/disable cycle or reload cache-friendly (identical URL, browser
* cache hit) while forcing a real re-import + re-execution whenever the
* version actually changes.
*/
export function toActivePlugin(record: PluginRecord): ActivePlugin | null {
const bundle = record.ui?.bundle;
@@ -20,7 +31,7 @@ export function toActivePlugin(record: PluginRecord): ActivePlugin | null {
return {
id: record.id,
name: record.display_name,
bundleUrl: `/api/plugins/${record.id}/bundle`,
bundleUrl: `/api/plugins/${record.id}/bundle?v=${encodeURIComponent(record.version)}`,
styleUrls: pluginStyleURLs(record),
};
}
+71
View File
@@ -376,6 +376,77 @@ describe("loadPlugins — initialize() timeout isolation", () => {
});
});
describe("update sequence: unload before reload", () => {
const PLUGIN_UPDATE_A_ID = "plugin-update-a";
const MAIN_TOP_BAR_SLOT = "main-top-bar";
afterEach(() => {
pluginRegistry.unregisterPlugin(PLUGIN_UPDATE_A_ID);
});
it("registers the top-bar slot component exactly once when a plugin is unloaded then reloaded (update), not twice", async () => {
const Widget = () => null;
const importer = fakeImporterFor({
[BUNDLE_JS_URL]: (win) =>
(win as unknown as FakeWindow).registerKandevPlugin(PLUGIN_UPDATE_A_ID, {
initialize: (registry: PluginRegistry) => {
registry.registerComponent(MAIN_TOP_BAR_SLOT, Widget);
},
}),
});
// First install.
await loadPlugins(
[activePlugin({ id: PLUGIN_UPDATE_A_ID, bundleUrl: BUNDLE_JS_URL })],
makeHostFactory,
importer,
);
expect(pluginRegistry.getSlotComponents(MAIN_TOP_BAR_SLOT)).toEqual([Widget]);
// Update: the reused install path must revoke the previous version's
// registrations before reloading, exactly like disable/uninstall do.
unloadPlugin(PLUGIN_UPDATE_A_ID);
await loadPlugins(
[activePlugin({ id: PLUGIN_UPDATE_A_ID, bundleUrl: BUNDLE_JS_URL })],
makeHostFactory,
importer,
);
expect(pluginRegistry.getSlotComponents(MAIN_TOP_BAR_SLOT)).toEqual([Widget]);
});
});
describe("unloadPlugin — evictCache option", () => {
const PLUGIN_EVICT_A_ID = "plugin-evict-a";
afterEach(() => {
pluginRegistry.unregisterPlugin(PLUGIN_EVICT_A_ID);
});
it("re-imports the bundle on the next load when evictCache is true, unlike the default reuse-cached-registration behavior", async () => {
const firstInitialize = vi.fn();
const secondInitialize = vi.fn();
let importCount = 0;
const importer = vi.fn(async (_url: string) => {
importCount += 1;
registerFake(PLUGIN_EVICT_A_ID, {
initialize: importCount === 1 ? firstInitialize : secondInitialize,
});
return {};
});
await loadPlugins([activePlugin({ id: PLUGIN_EVICT_A_ID })], makeHostFactory, importer);
expect(importCount).toBe(1);
expect(firstInitialize).toHaveBeenCalledTimes(1);
unloadPlugin(PLUGIN_EVICT_A_ID, { evictCache: true });
await loadPlugins([activePlugin({ id: PLUGIN_EVICT_A_ID })], makeHostFactory, importer);
expect(importCount).toBe(2);
expect(secondInitialize).toHaveBeenCalledTimes(1);
});
});
describe("disable then re-enable in the same session", () => {
afterEach(() => {
pluginRegistry.unregisterPlugin(PLUGIN_REENABLE_A_ID);
+15 -5
View File
@@ -175,12 +175,19 @@ function removeStyles(pluginId: string): void {
/**
* Disables a plugin: calls `destroy?.()`, bulk-revokes its registry
* registrations, and removes its injected stylesheets. Deliberately keeps
* the `registeredPlugins` entry — see module doc — so a later re-enable in
* the same tab can re-run `initialize` without depending on the browser
* re-executing the bundle's module-eval side effect.
* registrations, and removes its injected stylesheets. By default this
* keeps the `registeredPlugins` entry — see module doc — so a later
* re-enable in the same tab can re-run `initialize` without depending on the
* browser re-executing the bundle's module-eval side effect.
*
* Pass `evictCache: true` for the install/update path specifically: an
* updated package can ship new bundle code under the same `bundleUrl`, so
* the cached registration (and, with it, the stale `initialize`/`destroy`
* closures from the previous version) must be dropped so the next
* `loadPlugin` re-imports it. This is opt-in — unconditional eviction here
* would break the plain disable/re-enable cycle's cached-registration reuse.
*/
export function unloadPlugin(id: string): void {
export function unloadPlugin(id: string, options?: { evictCache?: boolean }): void {
const plugin = registeredPlugins.get(id);
try {
plugin?.destroy?.();
@@ -189,5 +196,8 @@ export function unloadPlugin(id: string): void {
} finally {
pluginRegistry.unregisterPlugin(id);
removeStyles(id);
if (options?.evictCache) {
registeredPlugins.delete(id);
}
}
}