Skip to content

Commit d6e6d67

Browse files
authored
fix(plugins): uninstall fully removes isolated npm plugin files (#123973)
* fix(plugins): remove isolated npm projects on uninstall Ordinary uninstall now removes the whole owner-managed per-plugin npm project, including packed archives and transitive dependency debris, while shared roots and retained update generations keep their existing lifecycle behavior. * fix(plugins): preserve failed install cleanup Allow persistence-failure compensation to remove only a planner-validated isolated npm project root, while continuing to reject shared or ambiguous cleanup targets.
1 parent e4633cd commit d6e6d67

6 files changed

Lines changed: 88 additions & 11 deletions

File tree

‎scripts/e2e/lib/plugins/assertions.mjs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -732,6 +732,11 @@ function assertPluginFileRemoved() {
732732

733733
function assertNpmPluginRemoved() {
734734
const installPath = fs.readFileSync(scratchFile("plugins-npm-install-path.txt"), "utf8").trim();
735+
const packageParent = path.dirname(installPath);
736+
const nodeModulesPath = path.basename(packageParent).startsWith("@")
737+
? path.dirname(packageParent)
738+
: packageParent;
739+
const projectRoot = path.dirname(nodeModulesPath);
735740
const dependencyPackagePath = fs
736741
.readFileSync(scratchFile("plugins-npm-dependency-path.txt"), "utf8")
737742
.trim();
@@ -747,6 +752,9 @@ function assertNpmPluginRemoved() {
747752
`npm managed dependency still exists after uninstall: ${dependencyPackagePath}`,
748753
);
749754
}
755+
if (fs.existsSync(projectRoot)) {
756+
throw new Error(`npm managed project still exists after uninstall: ${projectRoot}`);
757+
}
750758
}
751759

752760
function assertNpmPluginRetained() {

‎src/plugins/install-record-commit.ts‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -228,18 +228,13 @@ function resolveRetainedManagedNpmInstallMarkerTarget(params: {
228228
{ runtimePluginIds: [] },
229229
),
230230
);
231-
if (
232-
!plan.ok ||
233-
!plan.directoryRemoval ||
234-
plan.directoryRemoval.cleanup?.kind !== "npm" ||
235-
path.resolve(plan.directoryRemoval.target) !== path.resolve(previousInstallPath)
236-
) {
231+
if (!plan.ok || !plan.directoryRemoval || plan.directoryRemoval.cleanup?.kind !== "npm") {
237232
return null;
238233
}
239-
if (nextInstallPath && installPathsOverlap(plan.directoryRemoval.target, nextInstallPath)) {
234+
if (nextInstallPath && installPathsOverlap(previousInstallPath, nextInstallPath)) {
240235
return null;
241236
}
242-
return plan.directoryRemoval.target;
237+
return previousInstallPath;
243238
}
244239

245240
function resolveNpmInstallRecordPackageName(record: PluginInstallRecord): string | null {

‎src/plugins/management-service.install-compensation.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
14
import { beforeEach, describe, expect, it, vi } from "vitest";
5+
import { resolveDefaultPluginNpmDir, resolvePluginNpmProjectDir } from "./install-paths.js";
26

37
const mocks = vi.hoisted(() => ({
48
applyUninstall: vi.fn(),
59
clawhubInstall: vi.fn(),
610
installRecords: vi.fn(),
11+
npmInstall: vi.fn(),
712
pathInstall: vi.fn(),
813
persistInstall: vi.fn(),
914
planUninstall: vi.fn(),
@@ -15,6 +20,7 @@ vi.mock("./clawhub.js", () => ({
1520

1621
vi.mock("./install.js", async (importOriginal) => ({
1722
...(await importOriginal<typeof import("./install.js")>()),
23+
installPluginFromNpmSpec: (...args: unknown[]) => mocks.npmInstall(...args),
1824
installPluginFromPath: (...args: unknown[]) => mocks.pathInstall(...args),
1925
}));
2026

@@ -35,6 +41,7 @@ vi.mock("./uninstall.js", async (importOriginal) => ({
3541
}));
3642

3743
const { installManagedPluginSource } = await import("./management-service.js");
44+
const actualUninstall = await vi.importActual<typeof import("./uninstall.js")>("./uninstall.js");
3845

3946
function installPersistSnapshot() {
4047
return {
@@ -97,6 +104,58 @@ describe("managed plugin install compensation", () => {
97104
expect(mocks.applyUninstall).toHaveBeenCalledWith({ target: targetDir });
98105
});
99106

107+
it("removes a planner-validated isolated npm project after persistence conflicts", async () => {
108+
const home = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-managed-npm-conflict-"));
109+
const env = { HOME: home };
110+
const packageName = "@openclaw/demo";
111+
const npmRoot = resolvePluginNpmProjectDir({
112+
npmDir: resolveDefaultPluginNpmDir(env),
113+
packageName,
114+
});
115+
const targetDir = path.join(npmRoot, "node_modules", "@openclaw", "demo");
116+
const packArchive = path.join(npmRoot, "_openclaw-pack-archives", "demo.tgz");
117+
const conflict = new Error("config changed during npm plugin install");
118+
119+
try {
120+
await fs.mkdir(targetDir, { recursive: true });
121+
await fs.mkdir(path.dirname(packArchive), { recursive: true });
122+
await fs.writeFile(packArchive, "packed plugin");
123+
mocks.npmInstall.mockResolvedValue({
124+
ok: true,
125+
pluginId: "demo",
126+
targetDir,
127+
extensions: ["index.js"],
128+
manifestName: packageName,
129+
});
130+
mocks.persistInstall.mockRejectedValue(conflict);
131+
mocks.planUninstall.mockImplementation((params) =>
132+
actualUninstall.planPluginUninstall(
133+
params as Parameters<typeof actualUninstall.planPluginUninstall>[0],
134+
),
135+
);
136+
mocks.applyUninstall.mockImplementation(async (removal: { target: string }) => {
137+
await fs.rm(removal.target, { recursive: true, force: true });
138+
return { directoryRemoved: true, warnings: [] };
139+
});
140+
141+
await expect(
142+
installManagedPluginSource({
143+
request: { source: "npm", spec: packageName, mode: "install" },
144+
snapshot: installPersistSnapshot(),
145+
env,
146+
}),
147+
).rejects.toBe(conflict);
148+
149+
expect(mocks.applyUninstall).toHaveBeenCalledWith({
150+
target: npmRoot,
151+
cleanup: { kind: "npm", npmRoot, packageName },
152+
});
153+
await expect(fs.access(npmRoot)).rejects.toMatchObject({ code: "ENOENT" });
154+
} finally {
155+
await fs.rm(home, { recursive: true, force: true });
156+
}
157+
});
158+
100159
it("never deletes an operator-owned source when link persistence fails", async () => {
101160
const env = { HOME: "/tmp/openclaw-managed-link-conflict-home" };
102161
const sourcePath = "/tmp/operator-owned-plugin-source";

‎src/plugins/management-service.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ import { refreshPluginRegistryAfterConfigMutation } from "./registry-refresh.js"
8686
import { applySlotSelectionForPlugin } from "./slot-selection.js";
8787
import { setPluginEnabledInConfig } from "./toggle-config.js";
8888
import { collectClawPluginUninstallWarnings } from "./uninstall-claw-references.js";
89+
import { isUninstallPathInsideOrEqual } from "./uninstall-config.js";
8990
import {
9091
prepareConfigForPendingPluginDirectoryRemovalSet,
9192
recordPluginPackageUninstallPlan,
@@ -1084,7 +1085,13 @@ async function cleanupFailedManagedPluginInstall(params: {
10841085
`Could not resolve a managed cleanup target for failed plugin install ${params.pluginId}.`,
10851086
];
10861087
}
1087-
if (path.resolve(plan.directoryRemoval.target) !== path.resolve(params.targetDir)) {
1088+
const plannedTarget = path.resolve(plan.directoryRemoval.target);
1089+
const installedTarget = path.resolve(params.targetDir);
1090+
const removesIsolatedNpmProject =
1091+
plan.directoryRemoval.cleanup?.kind === "npm" &&
1092+
plannedTarget === path.resolve(plan.directoryRemoval.cleanup.npmRoot) &&
1093+
isUninstallPathInsideOrEqual(plannedTarget, installedTarget);
1094+
if (plannedTarget !== installedTarget && !removesIsolatedNpmProject) {
10881095
return [
10891096
`Refused cleanup for failed plugin install ${params.pluginId}: planned target does not match the newly installed target.`,
10901097
];

‎src/plugins/uninstall.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1291,7 +1291,7 @@ describe("uninstallPlugin", () => {
12911291
throw new Error(plan.error);
12921292
}
12931293
expect(plan.directoryRemoval).toEqual({
1294-
target: pluginDir,
1294+
target: npmRoot,
12951295
cleanup: {
12961296
kind: "npm",
12971297
npmRoot,
@@ -1304,6 +1304,7 @@ describe("uninstallPlugin", () => {
13041304
expect(applied).toEqual({ directoryRemoved: true, warnings: [] });
13051305
expectNpmUninstallCommand({ packageName: "@openclaw/kitchen-sink", npmRoot });
13061306
await expectPathAccessState(pluginDir, "missing");
1307+
await expectPathAccessState(npmRoot, "missing");
13071308
});
13081309

13091310
it("repairs remaining npm plugin openclaw peer links after npm uninstall prunes them", async () => {

‎src/plugins/uninstall.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,14 @@ function resolveNpmManagedProjectInstall(params: {
220220
installPath: params.installPath,
221221
nodeModulesRoot,
222222
});
223-
return packageName ? { installPath: params.installPath, npmRoot, packageName } : null;
223+
if (
224+
!packageName ||
225+
resolveComparableUninstallPath(params.installPath) !==
226+
resolveComparableUninstallPath(path.join(nodeModulesRoot, ...packageName.split("/")))
227+
) {
228+
return null;
229+
}
230+
return { installPath: npmRoot, npmRoot, packageName };
224231
}
225232

226233
function resolveNpmPackageNameFromInstallPath(params: {

0 commit comments

Comments
 (0)