Skip to content

Commit 682ddcb

Browse files
authored
fix: preserve Gateway when setup Reinstall is cancelled (#130617)
Keep replacement preparation ahead of service mutation in configure and onboarding. Let platform installers own replacement, and report surviving Gateway reachability independently of failed setup.
1 parent a872abc commit 682ddcb

8 files changed

Lines changed: 206 additions & 73 deletions

File tree

‎docs/cli/configure.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ When configure starts from a provider auth choice, the default-model and model-p
5555

5656
- After local config writes, configure installs selected downloadable plugins when the chosen setup path requires them. Remote gateway config does not install local plugin packages.
5757
- Channel-oriented services (Slack/Discord/Matrix/Microsoft Teams) prompt for channel/room allowlists during setup. You can enter names or IDs; the wizard resolves names to IDs when possible.
58+
- Choosing **Reinstall** keeps the existing Gateway service in place while you select its runtime and configure validates authentication and prepares the replacement. Cancelling or failing during preparation leaves the existing service installed.
5859
- If you run the daemon install step, token auth requires a token. If `gateway.auth.token` is SecretRef-managed, configure validates the SecretRef but does not persist resolved plaintext token values into supervisor service environment metadata; if the SecretRef is unresolved, configure blocks daemon install with actionable remediation guidance.
5960
- If both `gateway.auth.token` and `gateway.auth.password` are configured and `gateway.auth.mode` is unset, configure blocks daemon install until you set the mode explicitly.
6061

‎src/commands/configure.daemon.test.ts‎

Lines changed: 71 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Configure daemon tests cover daemon install prompts, progress labels, and runtime install calls.
22

3+
import { PassThrough } from "node:stream";
4+
import { select as clackSelect } from "@clack/prompts";
35
import { expectDefined } from "@openclaw/normalization-core";
46
import { beforeEach, describe, expect, it, vi } from "vitest";
57
import { maybeInstallDaemon } from "./configure.daemon.js";
@@ -14,13 +16,14 @@ const buildGatewayInstallPlan = vi.hoisted(() => vi.fn());
1416
const note = vi.hoisted(() => vi.fn());
1517
const serviceIsLoaded = vi.hoisted(() => vi.fn(async () => false));
1618
const serviceInstall = vi.hoisted(() => vi.fn(async () => {}));
19+
const serviceUninstall = vi.hoisted(() => vi.fn(async () => {}));
1720
const serviceRestart = vi.hoisted(() =>
1821
vi.fn<() => Promise<{ outcome: "completed" } | { outcome: "scheduled" }>>(async () => ({
1922
outcome: "completed",
2023
})),
2124
);
2225
const ensureSystemdUserLingerInteractive = vi.hoisted(() => vi.fn(async () => {}));
23-
const select = vi.hoisted(() => vi.fn(async () => "node"));
26+
const select = vi.hoisted(() => vi.fn<() => Promise<string | symbol>>(async () => "node"));
2427

2528
vi.mock("../cli/progress.js", () => ({
2629
withProgress,
@@ -49,11 +52,6 @@ vi.mock("./configure.shared.js", () => ({
4952
select,
5053
}));
5154

52-
vi.mock("./daemon-runtime.js", () => ({
53-
DEFAULT_GATEWAY_DAEMON_RUNTIME: "node",
54-
GATEWAY_DAEMON_RUNTIME_OPTIONS: [{ value: "node", label: "Node" }],
55-
}));
56-
5755
vi.mock("../daemon/service.js", async () => {
5856
const actual =
5957
await vi.importActual<typeof import("../daemon/service.js")>("../daemon/service.js");
@@ -62,15 +60,12 @@ vi.mock("../daemon/service.js", async () => {
6260
resolveGatewayService: vi.fn(() => ({
6361
isLoaded: serviceIsLoaded,
6462
install: serviceInstall,
63+
uninstall: serviceUninstall,
6564
restart: serviceRestart,
6665
})),
6766
};
6867
});
6968

70-
vi.mock("./onboard-helpers.js", () => ({
71-
guardCancel: (value: unknown) => value,
72-
}));
73-
7469
vi.mock("./systemd-linger.js", () => ({
7570
ensureSystemdUserLingerInteractive,
7671
}));
@@ -81,6 +76,9 @@ describe("maybeInstallDaemon", () => {
8176
progressSetLabel.mockReset();
8277
serviceIsLoaded.mockResolvedValue(false);
8378
serviceInstall.mockResolvedValue(undefined);
79+
serviceUninstall.mockReset();
80+
select.mockReset();
81+
select.mockResolvedValue("node");
8482
serviceRestart.mockResolvedValue({ outcome: "completed" });
8583
loadConfig.mockReturnValue({});
8684
resolveGatewayInstallToken.mockResolvedValue({
@@ -113,7 +111,11 @@ describe("maybeInstallDaemon", () => {
113111
expect(serviceInstall).toHaveBeenCalledTimes(1);
114112
});
115113

116-
it("blocks install when token SecretRef is unresolved", async () => {
114+
it.each([false, true])("blocks install with unresolved auth (reinstall=%s)", async (loaded) => {
115+
serviceIsLoaded.mockResolvedValue(loaded);
116+
if (loaded) {
117+
select.mockResolvedValueOnce("reinstall");
118+
}
117119
resolveGatewayInstallToken.mockResolvedValue({
118120
token: undefined,
119121
tokenRefConfigured: true,
@@ -133,6 +135,64 @@ describe("maybeInstallDaemon", () => {
133135
);
134136
expect(buildGatewayInstallPlan).not.toHaveBeenCalled();
135137
expect(serviceInstall).not.toHaveBeenCalled();
138+
expect(serviceUninstall).not.toHaveBeenCalled();
139+
});
140+
141+
it("keeps the installed service when runtime selection is cancelled", async () => {
142+
serviceIsLoaded.mockResolvedValue(true);
143+
const cancelled = await clackSelect({
144+
message: "Runtime",
145+
options: [{ value: "node", label: "Node" }],
146+
signal: AbortSignal.abort(),
147+
input: new PassThrough(),
148+
output: new PassThrough(),
149+
});
150+
select.mockResolvedValueOnce("reinstall").mockResolvedValueOnce(cancelled);
151+
const runtime = {
152+
log: vi.fn(),
153+
error: vi.fn(),
154+
exit: vi.fn(() => {
155+
throw new Error("setup cancelled");
156+
}),
157+
};
158+
159+
await expect(maybeInstallDaemon({ runtime, port: 18789 })).rejects.toThrow("setup cancelled");
160+
161+
expect(runtime.exit).toHaveBeenCalledWith(1);
162+
expect(serviceUninstall).not.toHaveBeenCalled();
163+
expect(resolveGatewayInstallToken).not.toHaveBeenCalled();
164+
expect(serviceInstall).not.toHaveBeenCalled();
165+
});
166+
167+
it("keeps the installed service when replacement planning fails", async () => {
168+
serviceIsLoaded.mockResolvedValue(true);
169+
select.mockResolvedValueOnce("reinstall");
170+
buildGatewayInstallPlan.mockRejectedValueOnce(new Error("replacement plan failed"));
171+
172+
await expect(
173+
maybeInstallDaemon({
174+
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
175+
port: 18789,
176+
}),
177+
).rejects.toThrow("replacement plan failed");
178+
179+
expect(serviceUninstall).not.toHaveBeenCalled();
180+
expect(serviceInstall).not.toHaveBeenCalled();
181+
});
182+
183+
it("hands the existing service to the replacement installer", async () => {
184+
serviceIsLoaded.mockResolvedValue(true);
185+
select.mockResolvedValueOnce("reinstall");
186+
187+
const outcome = await maybeInstallDaemon({
188+
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
189+
port: 18789,
190+
});
191+
192+
expect(outcome).toBe("succeeded");
193+
expect(serviceInstall).toHaveBeenCalledOnce();
194+
expect(serviceUninstall).not.toHaveBeenCalled();
195+
expect(serviceRestart).not.toHaveBeenCalled();
136196
});
137197

138198
it("continues daemon install flow when service status probe throws", async () => {

‎src/commands/configure.daemon.ts‎

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -71,19 +71,10 @@ export async function maybeInstallDaemon(params: {
7171
if (action === "skip") {
7272
return "skipped";
7373
}
74-
if (action === "reinstall") {
75-
await withProgress(
76-
{ label: "Gateway service", indeterminate: true, delayMs: 0 },
77-
async (progress) => {
78-
progress.setLabel("Uninstalling Gateway service…");
79-
await service.uninstall({ env: process.env, stdout: process.stdout });
80-
progress.setLabel("Gateway service uninstalled.");
81-
},
82-
);
83-
}
8474
}
8575

8676
if (shouldInstall) {
77+
// Keep the old service until preparation succeeds; install owns replacement.
8778
let installError: string | null = null;
8879
if (!params.daemonRuntime) {
8980
if (GATEWAY_DAEMON_RUNTIME_OPTIONS.length === 1) {

‎src/wizard/i18n/locales/en.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1140,8 +1140,6 @@ export const en = {
11401140
gatewayServiceRestarted: "Gateway service restarted.",
11411141
gatewayServiceRestarting: "Restarting Gateway service...",
11421142
gatewayServiceRestartScheduled: "Gateway service restart scheduled.",
1143-
gatewayServiceUninstalled: "Gateway service uninstalled.",
1144-
gatewayServiceUninstalling: "Uninstalling Gateway service...",
11451143
gatewayTokenGenerate: "Generate token: {command}",
11461144
gatewayTokenShared: "Gateway token: shared auth for the Gateway + Control UI.",
11471145
gatewayTokenStored:

‎src/wizard/i18n/locales/zh-CN.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1103,8 +1103,6 @@ export const zh_CN = {
11031103
gatewayServiceRestarted: "Gateway 服务已重启。",
11041104
gatewayServiceRestarting: "正在重启 Gateway 服务...",
11051105
gatewayServiceRestartScheduled: "Gateway 服务重启已排队。",
1106-
gatewayServiceUninstalled: "Gateway 服务已卸载。",
1107-
gatewayServiceUninstalling: "正在卸载 Gateway 服务...",
11081106
gatewayTokenGenerate: "生成令牌:{command}",
11091107
gatewayTokenShared: "Gateway 令牌:Gateway 和 Control UI 的共享认证。",
11101108
gatewayTokenStored:

‎src/wizard/i18n/locales/zh-TW.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,8 +1104,6 @@ export const zh_TW = {
11041104
gatewayServiceRestarted: "Gateway 服務已重新啟動。",
11051105
gatewayServiceRestarting: "正在重新啟動 Gateway 服務...",
11061106
gatewayServiceRestartScheduled: "Gateway 服務重新啟動已排程。",
1107-
gatewayServiceUninstalled: "Gateway 服務已解除安裝。",
1108-
gatewayServiceUninstalling: "正在解除安裝 Gateway 服務...",
11091107
gatewayTokenGenerate: "產生權杖:{command}",
11101108
gatewayTokenShared: "Gateway 權杖:Gateway 和 Control UI 的共享認證。",
11111109
gatewayTokenStored:

‎src/wizard/setup.finalize.test.ts‎

Lines changed: 100 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1111,6 +1111,37 @@ describe("finalizeSetupWizard", () => {
11111111
expect(gatewayServiceInstall).not.toHaveBeenCalled();
11121112
});
11131113

1114+
it.each([false, true])(
1115+
"detects the surviving gateway after failed reinstall (skipHealth=%s)",
1116+
async (skipHealth) => {
1117+
gatewayServiceIsLoaded.mockResolvedValue(true);
1118+
buildGatewayInstallPlan.mockRejectedValueOnce(new Error("replacement plan failed"));
1119+
probeGatewayReachable.mockResolvedValue({ ok: true });
1120+
const prompter = buildWizardPrompter({
1121+
select: vi.fn().mockResolvedValueOnce("reinstall").mockResolvedValueOnce("tui"),
1122+
});
1123+
1124+
await finalizeSetupWizard(
1125+
createFinalizeArgs("quickstart", {
1126+
opts: { installDaemon: true, skipHealth },
1127+
prompter,
1128+
}),
1129+
);
1130+
1131+
expect(gatewayServiceUninstall).not.toHaveBeenCalled();
1132+
expect(gatewayServiceInstall).not.toHaveBeenCalled();
1133+
expect(waitForGatewayReachable).not.toHaveBeenCalled();
1134+
expect(probeGatewayReachable).toHaveBeenCalledOnce();
1135+
expect(healthCommand).toHaveBeenCalledTimes(skipHealth ? 0 : 1);
1136+
expect(runTui).toHaveBeenCalledWith(
1137+
expect.objectContaining({ boundGateway: { url: "ws://127.0.0.1:18789" } }),
1138+
);
1139+
expectNoteContains(prompter, "replacement plan failed", "Gateway");
1140+
expectNoteNotContains(prompter, "Gateway: not detected");
1141+
expect(prompter.outro).toHaveBeenCalledWith(expect.stringContaining("setup failed"));
1142+
},
1143+
);
1144+
11141145
it("reports gateway installation failure without waiting for impossible health", async () => {
11151146
gatewayServiceInstall.mockRejectedValueOnce(new Error("service install exploded"));
11161147
const prompter = createLaterPrompter();
@@ -1124,10 +1155,10 @@ describe("finalizeSetupWizard", () => {
11241155
);
11251156

11261157
expect(waitForGatewayReachable).not.toHaveBeenCalled();
1127-
expect(probeGatewayReachable).not.toHaveBeenCalled();
1158+
expect(probeGatewayReachable).toHaveBeenCalledOnce();
11281159
expect(runtime.error).toHaveBeenCalledWith("health failed");
11291160
expectNoteContains(prompter, "service install exploded", "Gateway");
1130-
expectNoteContains(prompter, "Gateway: not detected (service install exploded)", "Control UI");
1161+
expectNoteContains(prompter, "Gateway: not detected (offline)", "Control UI");
11311162
expect(prompter.outro).toHaveBeenCalledWith(
11321163
expect.stringContaining("managed Mock Platform Service setup failed"),
11331164
);
@@ -1442,6 +1473,73 @@ describe("finalizeSetupWizard", () => {
14421473
expect(progressStop).toHaveBeenCalledWith("Gateway service restart scheduled.");
14431474
});
14441475

1476+
it.each(["auth", "planning"])(
1477+
"preserves the installed service when reinstall %s fails",
1478+
async (failure) => {
1479+
let installed = true;
1480+
gatewayServiceIsLoaded.mockImplementation(async () => installed);
1481+
gatewayServiceUninstall.mockImplementationOnce(async () => {
1482+
installed = false;
1483+
});
1484+
if (failure === "auth") {
1485+
resolveGatewayInstallToken.mockImplementationOnce(async () => ({
1486+
token: undefined,
1487+
tokenRefConfigured: true,
1488+
warnings: [],
1489+
unavailableReason: "replacement auth unavailable",
1490+
}));
1491+
} else {
1492+
buildGatewayInstallPlan.mockRejectedValueOnce(new Error("replacement plan failed"));
1493+
}
1494+
const prompter = buildWizardPrompter({ select: vi.fn(async () => "reinstall") as never });
1495+
1496+
const result = await ensureGatewayServiceForOnboarding(
1497+
createFinalizeArgs("quickstart", { opts: { installDaemon: true }, prompter }),
1498+
);
1499+
1500+
expect(result.gateway.status).toBe("failed");
1501+
expect(installed).toBe(true);
1502+
expect(gatewayServiceInstall).not.toHaveBeenCalled();
1503+
},
1504+
);
1505+
1506+
it("passes the existing service intact to the reinstall owner", async () => {
1507+
let installed = true;
1508+
gatewayServiceIsLoaded.mockImplementation(async () => installed);
1509+
gatewayServiceUninstall.mockImplementationOnce(async () => {
1510+
installed = false;
1511+
});
1512+
gatewayServiceInstall.mockImplementationOnce(async () => {
1513+
expect(installed).toBe(true);
1514+
});
1515+
const prompter = buildWizardPrompter({ select: vi.fn(async () => "reinstall") as never });
1516+
1517+
const result = await ensureGatewayServiceForOnboarding(
1518+
createFinalizeArgs("quickstart", { opts: { installDaemon: true }, prompter }),
1519+
);
1520+
1521+
expect(result.gateway).toEqual({ status: "ready", action: "installed" });
1522+
expect(gatewayServiceInstall).toHaveBeenCalledOnce();
1523+
expect(gatewayServiceUninstall).not.toHaveBeenCalled();
1524+
});
1525+
1526+
it.each(["skip", "restart"])("does not turn %s into an implicit reinstall", async (action) => {
1527+
gatewayServiceIsLoaded.mockResolvedValueOnce(true).mockResolvedValue(false);
1528+
const prompter = buildWizardPrompter({ select: vi.fn(async () => action) as never });
1529+
1530+
const result = await ensureGatewayServiceForOnboarding(
1531+
createFinalizeArgs("quickstart", { opts: { installDaemon: true }, prompter }),
1532+
);
1533+
1534+
expect(result.gateway).toEqual({
1535+
status: "ready",
1536+
action: action === "restart" ? "restarted" : "reused",
1537+
});
1538+
expect(gatewayServiceInstall).not.toHaveBeenCalled();
1539+
expect(gatewayServiceUninstall).not.toHaveBeenCalled();
1540+
expect(gatewayServiceRestart).toHaveBeenCalledTimes(action === "restart" ? 1 : 0);
1541+
});
1542+
14451543
it("localizes finalize non-prompt notes", async () => {
14461544
const previousLocale = process.env.OPENCLAW_LOCALE;
14471545
process.env.OPENCLAW_LOCALE = "zh-CN";

0 commit comments

Comments
 (0)