Skip to content

Commit 5d98d2e

Browse files
authored
fix(uninstall): preserve user data when gateway removal fails (#113887)
* fix(uninstall): gate cleanup on service teardown * fix(daemon): scope strict task removal checks
1 parent 4cb33d4 commit 5d98d2e

9 files changed

Lines changed: 242 additions & 24 deletions

‎src/commands/cleanup-command.test-support.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,28 @@ export const prepareLegacyWorkspaceStateReset = vi.fn();
1010
export const removeLegacyWorkspaceStateForReset = vi.fn();
1111
export const removeStateAndLinkedPaths = vi.fn();
1212
export const removeWorkspaceDirs = vi.fn();
13+
const gatewayServiceState = vi.hoisted(() => ({
14+
notLoadedText: "is not installed",
15+
isLoaded: vi.fn(),
16+
stop: vi.fn(),
17+
uninstall: vi.fn(),
18+
}));
19+
export const gatewayService = gatewayServiceState;
20+
const cleanupConfigState = vi.hoisted(() => ({ isNixMode: false }));
1321

1422
vi.mock("../agents/workspace-legacy-state.js", () => ({
1523
prepareLegacyWorkspaceStateReset,
1624
removeLegacyWorkspaceStateForReset,
1725
}));
1826

1927
vi.mock("../config/config.js", () => ({
20-
isNixMode: false,
28+
get isNixMode() {
29+
return cleanupConfigState.isNixMode;
30+
},
31+
}));
32+
33+
vi.mock("../daemon/service.js", () => ({
34+
resolveGatewayService: () => gatewayService,
2135
}));
2236

2337
vi.mock("./cleanup-plan.js", () => ({
@@ -51,6 +65,14 @@ export function resetCleanupCommandMocks() {
5165
removeLegacyWorkspaceStateForReset.mockResolvedValue({ removedPaths: [], warnings: [] });
5266
removeStateAndLinkedPaths.mockResolvedValue(true);
5367
removeWorkspaceDirs.mockResolvedValue(undefined);
68+
gatewayService.isLoaded.mockReset().mockResolvedValue(true);
69+
gatewayService.stop.mockReset().mockResolvedValue(undefined);
70+
gatewayService.uninstall.mockReset().mockResolvedValue(undefined);
71+
cleanupConfigState.isNixMode = false;
72+
}
73+
74+
export function setCleanupNixMode(value: boolean) {
75+
cleanupConfigState.isNixMode = value;
5476
}
5577

5678
export function silenceCleanupCommandRuntime(runtime: RuntimeEnv) {

‎src/commands/reset.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { beforeAll, beforeEach, describe, expect, it } from "vitest";
33
import {
44
cleanupCommandLogMessages,
55
createCleanupCommandRuntime,
6+
gatewayService,
67
removeStateAndLinkedPaths,
78
removeWorkspaceDirs,
89
resetCleanupCommandMocks,
@@ -22,6 +23,30 @@ describe("resetCommand", () => {
2223
silenceCleanupCommandRuntime(runtime);
2324
});
2425

26+
it.each([
27+
{
28+
failure: "inspection fails",
29+
arrange: () => gatewayService.isLoaded.mockRejectedValue(new Error("inspection failed")),
30+
},
31+
{
32+
failure: "stop fails",
33+
arrange: () => gatewayService.stop.mockRejectedValue(new Error("stop failed")),
34+
},
35+
])("preserves user data when gateway $failure", async ({ arrange }) => {
36+
arrange();
37+
38+
await expect(
39+
resetCommand(runtime, {
40+
scope: "full",
41+
yes: true,
42+
nonInteractive: true,
43+
}),
44+
).rejects.toMatchObject({ name: "ExitError", code: 1 });
45+
46+
expect(removeStateAndLinkedPaths).not.toHaveBeenCalled();
47+
expect(removeWorkspaceDirs).not.toHaveBeenCalled();
48+
});
49+
2550
it("recommends creating a backup before state-destructive reset scopes", async () => {
2651
await resetCommand(runtime, {
2752
scope: "config+creds+sessions",

‎src/commands/reset.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,27 +32,29 @@ type ResetOptions = {
3232
dryRun?: boolean;
3333
};
3434

35-
async function stopGatewayIfRunning(runtime: RuntimeEnv) {
35+
async function stopGatewayIfRunning(runtime: RuntimeEnv): Promise<boolean> {
3636
if (isNixMode) {
3737
// Nix mode owns service lifecycle outside OpenClaw-managed launchd/systemd
3838
// installs, so reset should not try to stop a service it did not create.
39-
return;
39+
return true;
4040
}
4141
const service = resolveGatewayService();
4242
let loaded;
4343
try {
4444
loaded = await service.isLoaded({ env: process.env });
4545
} catch (err) {
4646
runtime.error(`Gateway service check failed: ${String(err)}`);
47-
return;
47+
return false;
4848
}
4949
if (!loaded) {
50-
return;
50+
return true;
5151
}
5252
try {
5353
await service.stop({ env: process.env, stdout: process.stdout });
54+
return true;
5455
} catch (err) {
5556
runtime.error(`Gateway stop failed: ${String(err)}`);
57+
return false;
5658
}
5759
}
5860

@@ -130,8 +132,9 @@ export async function resetCommand(runtime: RuntimeEnv, opts: ResetOptions) {
130132
logBackupRecommendation(runtime);
131133
if (dryRun) {
132134
runtime.log("[dry-run] stop gateway service");
133-
} else {
134-
await stopGatewayIfRunning(runtime);
135+
} else if (!(await stopGatewayIfRunning(runtime))) {
136+
runtime.exit(1);
137+
return;
135138
}
136139
}
137140

‎src/commands/uninstall.test.ts‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@ import { beforeEach, describe, expect, it } from "vitest";
33
import {
44
cleanupCommandLogMessages,
55
createCleanupCommandRuntime,
6+
gatewayService,
67
prepareLegacyWorkspaceStateReset,
78
removeLegacyWorkspaceStateForReset,
89
removeStateAndLinkedPaths,
910
removeWorkspaceDirs,
1011
resetCleanupCommandMocks,
12+
setCleanupNixMode,
1113
silenceCleanupCommandRuntime,
1214
} from "./cleanup-command.test-support.js";
1315

@@ -21,6 +23,98 @@ describe("uninstallCommand", () => {
2123
silenceCleanupCommandRuntime(runtime);
2224
});
2325

26+
it.each([
27+
{
28+
failure: "inspection fails",
29+
arrange: () => gatewayService.isLoaded.mockRejectedValue(new Error("inspection failed")),
30+
},
31+
{
32+
failure: "stop fails",
33+
arrange: () => gatewayService.stop.mockRejectedValue(new Error("stop failed")),
34+
},
35+
{
36+
failure: "service removal fails",
37+
arrange: () => gatewayService.uninstall.mockRejectedValue(new Error("uninstall failed")),
38+
},
39+
])("preserves user data when gateway $failure", async ({ arrange }) => {
40+
arrange();
41+
42+
await expect(
43+
uninstallCommand(runtime, {
44+
all: true,
45+
yes: true,
46+
nonInteractive: true,
47+
}),
48+
).rejects.toMatchObject({ name: "ExitError", code: 1 });
49+
50+
expect(removeStateAndLinkedPaths).not.toHaveBeenCalled();
51+
expect(removeWorkspaceDirs).not.toHaveBeenCalled();
52+
expect(prepareLegacyWorkspaceStateReset).not.toHaveBeenCalled();
53+
expect(cleanupCommandLogMessages(runtime)).not.toContain(
54+
"CLI still installed. Remove via npm/pnpm if desired.",
55+
);
56+
});
57+
58+
it("preserves user data when Nix owns service lifecycle", async () => {
59+
setCleanupNixMode(true);
60+
61+
await expect(
62+
uninstallCommand(runtime, {
63+
all: true,
64+
yes: true,
65+
nonInteractive: true,
66+
}),
67+
).rejects.toMatchObject({ name: "ExitError", code: 1 });
68+
69+
expect(gatewayService.isLoaded).not.toHaveBeenCalled();
70+
expect(gatewayService.stop).not.toHaveBeenCalled();
71+
expect(gatewayService.uninstall).not.toHaveBeenCalled();
72+
expect(removeStateAndLinkedPaths).not.toHaveBeenCalled();
73+
expect(removeWorkspaceDirs).not.toHaveBeenCalled();
74+
});
75+
76+
it("still removes service registration after a failed gateway stop", async () => {
77+
gatewayService.stop.mockRejectedValue(new Error("listener still active"));
78+
79+
await expect(
80+
uninstallCommand(runtime, {
81+
service: true,
82+
yes: true,
83+
nonInteractive: true,
84+
}),
85+
).rejects.toMatchObject({ name: "ExitError", code: 1 });
86+
87+
expect(gatewayService.uninstall).toHaveBeenCalledOnce();
88+
});
89+
90+
it("removes requested data after successful gateway teardown", async () => {
91+
await uninstallCommand(runtime, {
92+
all: true,
93+
yes: true,
94+
nonInteractive: true,
95+
});
96+
97+
expect(gatewayService.stop).toHaveBeenCalledOnce();
98+
expect(gatewayService.uninstall).toHaveBeenCalledOnce();
99+
expect(removeStateAndLinkedPaths).toHaveBeenCalledOnce();
100+
expect(removeWorkspaceDirs).toHaveBeenCalledOnce();
101+
});
102+
103+
it("removes an unloaded service definition before deleting user data", async () => {
104+
gatewayService.isLoaded.mockResolvedValue(false);
105+
106+
await uninstallCommand(runtime, {
107+
all: true,
108+
yes: true,
109+
nonInteractive: true,
110+
});
111+
112+
expect(gatewayService.stop).not.toHaveBeenCalled();
113+
expect(gatewayService.uninstall).toHaveBeenCalledOnce();
114+
expect(removeStateAndLinkedPaths).toHaveBeenCalledOnce();
115+
expect(removeWorkspaceDirs).toHaveBeenCalledOnce();
116+
});
117+
24118
it("recommends creating a backup before removing state or workspaces", async () => {
25119
await uninstallCommand(runtime, {
26120
state: true,

‎src/commands/uninstall.ts‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -78,24 +78,27 @@ async function stopAndUninstallService(runtime: RuntimeEnv): Promise<boolean> {
7878
}
7979
if (!loaded) {
8080
runtime.log(`Gateway service ${service.notLoadedText}.`);
81-
return true;
8281
}
83-
try {
84-
await service.stop({ env: process.env, stdout: process.stdout });
85-
} catch (err) {
86-
runtime.error(
87-
`Gateway stop failed: ${formatErrorMessage(err)}. Run ${formatCliCommand("openclaw gateway status --deep")} before retrying uninstall.`,
88-
);
82+
let stopped = true;
83+
if (loaded) {
84+
try {
85+
await service.stop({ env: process.env, stdout: process.stdout });
86+
} catch (err) {
87+
stopped = false;
88+
runtime.error(
89+
`Gateway stop failed: ${formatErrorMessage(err)}. Run ${formatCliCommand("openclaw gateway status --deep")} before retrying uninstall.`,
90+
);
91+
}
8992
}
9093
try {
9194
await service.uninstall({ env: process.env, stdout: process.stdout });
92-
return true;
9395
} catch (err) {
9496
runtime.error(
9597
`Gateway uninstall failed: ${formatErrorMessage(err)}. Run ${formatCliCommand("openclaw gateway status --deep")} for the service state.`,
9698
);
9799
return false;
98100
}
101+
return stopped;
99102
}
100103

101104
async function removeMacApp(runtime: RuntimeEnv, dryRun?: boolean) {
@@ -188,8 +191,11 @@ export async function uninstallCommand(runtime: RuntimeEnv, opts: UninstallOptio
188191
if (scopes.has("service")) {
189192
if (dryRun) {
190193
runtime.log("[dry-run] remove gateway service");
191-
} else {
192-
await stopAndUninstallService(runtime);
194+
} else if (!(await stopAndUninstallService(runtime))) {
195+
// Service removal may prevent relaunch even when runtime termination is
196+
// uncertain; preserve mutable user data until teardown can be verified.
197+
runtime.exit(1);
198+
return;
193199
}
194200
}
195201

‎src/daemon/launchd.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
disableCurrentOpenClawUpdateLaunchdJob,
1616
disableOpenClawUpdateLaunchdJob,
1717
findStaleOpenClawUpdateLaunchdJobs,
18+
isLaunchAgentLoaded,
1819
parkCurrentLaunchAgentForMaintenance,
1920
parseLaunchctlPrint,
2021
parseLaunchctlListOpenClawUpdateJobs,
@@ -1445,6 +1446,15 @@ describe("launchd bootstrap repair", () => {
14451446
});
14461447

14471448
describe("launchd uninstall", () => {
1449+
it("rejects an unrecognized launchctl inspection failure", async () => {
1450+
state.printError = "launchctl print permission denied";
1451+
state.printFailuresRemaining = 1;
1452+
1453+
await expect(isLaunchAgentLoaded({ env: createDefaultLaunchdEnv() })).rejects.toThrow(
1454+
"launchctl print failed: launchctl print permission denied",
1455+
);
1456+
});
1457+
14481458
it("refuses an in-band uninstall before bootout or plist removal", async () => {
14491459
const env = createDefaultLaunchdEnv();
14501460
const plistPath = resolveLaunchAgentPlistPath(env);
@@ -1478,6 +1488,18 @@ describe("launchd uninstall", () => {
14781488
expect(state.files.has(plistPath)).toBe(true);
14791489
});
14801490

1491+
it("preserves the plist when launchctl cannot boot out the service", async () => {
1492+
const env = createDefaultLaunchdEnv();
1493+
const plistPath = resolveLaunchAgentPlistPath(env);
1494+
state.files.set(plistPath, "RunAtLoad=true");
1495+
state.bootoutError = "launchctl bootout permission denied";
1496+
1497+
await expect(uninstallLaunchAgent({ env, stdout: new PassThrough() })).rejects.toThrow(
1498+
"launchctl bootout failed: launchctl bootout permission denied",
1499+
);
1500+
expect(state.files.has(plistPath)).toBe(true);
1501+
});
1502+
14811503
it("reports inaccessible LaunchAgents instead of claiming they are missing", async () => {
14821504
const env = createDefaultLaunchdEnv();
14831505
const plistPath = resolveLaunchAgentPlistPath(env);

‎src/daemon/launchd.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -820,7 +820,13 @@ export async function isLaunchAgentLoaded(args: GatewayServiceEnvArgs): Promise<
820820
const domain = resolveGuiDomain();
821821
const label = resolveLaunchAgentLabel(args.env);
822822
const res = await execLaunchctl(["print", `${domain}/${label}`]);
823-
return res.code === 0;
823+
if (res.code === 0) {
824+
return true;
825+
}
826+
if (isLaunchctlNotLoaded(res)) {
827+
return false;
828+
}
829+
throw new Error(`launchctl print failed: ${formatLaunchctlResultDetail(res)}`);
824830
}
825831

826832
export async function launchAgentPlistExists(env: GatewayServiceEnv): Promise<boolean> {
@@ -974,8 +980,10 @@ export async function uninstallLaunchAgent({
974980
const domain = resolveGuiDomain();
975981
const label = resolveLaunchAgentLabel(env);
976982
const plistPath = resolveLaunchAgentPlistPath(env);
977-
await execLaunchctl(["bootout", domain, plistPath]);
978-
await execLaunchctl(["unload", plistPath]);
983+
const bootout = await execLaunchctl(["bootout", domain, plistPath]);
984+
if (bootout.code !== 0 && !isLaunchctlNotLoaded(bootout)) {
985+
throw new Error(`launchctl bootout failed: ${formatLaunchctlResultDetail(bootout)}`);
986+
}
979987

980988
try {
981989
await fs.lstat(plistPath);

0 commit comments

Comments
 (0)