Skip to content

Commit 40a29df

Browse files
authored
fix: interactive update can leave the Gateway stopped when completion refresh fails (#131393)
* fix: keep Gateway restart after completion failures * test: cover completion refresh protected paths * fix: keep JSON completion failures silent
1 parent 740f54e commit 40a29df

3 files changed

Lines changed: 215 additions & 58 deletions

File tree

‎src/cli/update-cli/update-command-post-update.test.ts‎

Lines changed: 149 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@ import fs from "node:fs/promises";
22
import os from "node:os";
33
import path from "node:path";
44
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
56
import type { UpdateRunResult } from "../../infra/update-runner.js";
67
import { defaultRuntime } from "../../runtime.js";
78

9+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
810
const mocks = vi.hoisted(() => ({
11+
checkCompletionStatus: vi.fn(),
912
completePluginUpdate: vi.fn(),
13+
ensureCompletionCache: vi.fn(),
1014
leaseActive: false,
1115
loadPluginRecords: vi.fn(),
1216
markSentinelFailure: vi.fn(async () => undefined),
@@ -24,8 +28,6 @@ const mocks = vi.hoisted(() => ({
2428
typeof import("./update-command-service.js").revalidateManagedGatewayServiceAfterUpdate
2529
>(),
2630
restoreWindowsAutoStart: vi.fn(async () => true),
27-
tryInstallCompletion: vi.fn(async () => undefined),
28-
tryWriteCompletionCache: vi.fn(async () => undefined),
2931
updatePlugins: vi.fn(),
3032
writeSentinel: vi.fn(async () => undefined),
3133
}));
@@ -43,6 +45,11 @@ vi.mock("../../daemon/service.js", async (importOriginal) => ({
4345
...(await importOriginal<typeof import("../../daemon/service.js")>()),
4446
readGatewayServiceState: mocks.readServiceState,
4547
}));
48+
vi.mock("../../commands/doctor-completion.js", async (importOriginal) => ({
49+
...(await importOriginal<typeof import("../../commands/doctor-completion.js")>()),
50+
checkShellCompletionStatus: mocks.checkCompletionStatus,
51+
ensureCompletionCacheExists: mocks.ensureCompletionCache,
52+
}));
4653
vi.mock("../../plugins/plugin-lifecycle-lease.js", () => ({
4754
withPluginLifecycleLease: async (_params: unknown, callback: () => unknown) => {
4855
mocks.leaseActive = true;
@@ -72,10 +79,6 @@ vi.mock("./update-command-fresh-doctor.js", () => ({
7279
vi.mock("./update-command-plugins.js", () => ({
7380
updatePluginsAfterCoreUpdate: mocks.updatePlugins,
7481
}));
75-
vi.mock("./shared.js", async (importOriginal) => ({
76-
...(await importOriginal<typeof import("./shared.js")>()),
77-
tryWriteCompletionCache: mocks.tryWriteCompletionCache,
78-
}));
7982
vi.mock("./restart-helper.js", () => ({
8083
prepareRestartScript: mocks.prepareRestartScript,
8184
}));
@@ -85,7 +88,6 @@ vi.mock("./update-command-service.js", async (importOriginal) => ({
8588
maybeRestartServiceAfterFailedMutableUpdate: mocks.restart,
8689
revalidateManagedGatewayServiceAfterUpdate: mocks.revalidateService,
8790
restoreWindowsTaskAutoStartOrExit: mocks.restoreWindowsAutoStart,
88-
tryInstallShellCompletion: mocks.tryInstallCompletion,
8991
}));
9092
vi.mock("./update-command-post-core.js", async (importOriginal) => ({
9193
...(await importOriginal<typeof import("./update-command-post-core.js")>()),
@@ -98,6 +100,15 @@ import { finishUpdate } from "./update-command-post-update.js";
98100
import { resolveUpdatedGatewayRestartPort } from "./update-command-service.js";
99101

100102
type FinishUpdateParams = Parameters<typeof finishUpdate>[0];
103+
const stdinIsTTYDescriptor = Object.getOwnPropertyDescriptor(process.stdin, "isTTY");
104+
105+
afterEach(() => {
106+
if (stdinIsTTYDescriptor) {
107+
Object.defineProperty(process.stdin, "isTTY", stdinIsTTYDescriptor);
108+
} else {
109+
Reflect.deleteProperty(process.stdin, "isTTY");
110+
}
111+
});
101112

102113
const validConfigSnapshot = {
103114
valid: true,
@@ -129,6 +140,7 @@ async function finishSuccessfulPackageSwitch(params: {
129140
previousRoot: string;
130141
packageRoot: string;
131142
restartEnvironment?: NodeJS.ProcessEnv;
143+
json?: boolean;
132144
sealed?: boolean;
133145
updateMode?: UpdateRunResult["mode"];
134146
stoppedForUpdate?: boolean;
@@ -157,7 +169,7 @@ async function finishSuccessfulPackageSwitch(params: {
157169
channel: params.updateMode === "git" ? "dev" : "stable",
158170
downgradeRisk: true,
159171
shouldRestart: Boolean(params.restartEnvironment),
160-
opts: {},
172+
opts: { json: params.json },
161173
showProgress: false,
162174
controlPlaneUpdateSentinelMeta: {},
163175
preUpdatePluginInstallRecords: {},
@@ -292,6 +304,135 @@ describe("successful update finalization ordering", () => {
292304
vi.spyOn(defaultRuntime, "log").mockImplementation(() => undefined);
293305
});
294306

307+
it("restarts after completion status inspection fails", async () => {
308+
Object.defineProperty(process.stdin, "isTTY", { configurable: true, value: true });
309+
mocks.checkCompletionStatus.mockRejectedValueOnce(
310+
Object.assign(new Error("EACCES: completion profile read denied"), { code: "EACCES" }),
311+
);
312+
313+
let failure: unknown;
314+
try {
315+
await finishSuccessfulPackageSwitch({
316+
previousRoot: "/tmp/openclaw-update",
317+
packageRoot: "/tmp/openclaw-update",
318+
restartEnvironment: process.env,
319+
});
320+
} catch (err) {
321+
failure = err;
322+
}
323+
324+
const output = vi.mocked(defaultRuntime.log).mock.calls.flat().map(String).join("\n");
325+
expect.soft(failure).toBeUndefined();
326+
expect.soft(output).toContain("Shell completion refresh failed");
327+
expect.soft(mocks.restartService).toHaveBeenCalledOnce();
328+
expect(mocks.restartService.mock.invocationCallOrder[0]).toBeLessThan(
329+
mocks.checkCompletionStatus.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
330+
);
331+
});
332+
333+
it("restarts when completion cache refresh reports failure", async () => {
334+
const root = tempDirs.make("openclaw-completion-failure-");
335+
await fs.writeFile(
336+
path.join(root, "openclaw.mjs"),
337+
'process.stderr.write("injected completion cache failure"); process.exit(1);',
338+
);
339+
340+
await finishSuccessfulPackageSwitch({
341+
previousRoot: root,
342+
packageRoot: root,
343+
restartEnvironment: process.env,
344+
});
345+
346+
const logCalls = vi.mocked(defaultRuntime.log).mock.calls;
347+
const warningIndex = logCalls.findIndex((call) =>
348+
call.some((value) => String(value).includes("Completion cache update failed")),
349+
);
350+
expect(warningIndex).toBeGreaterThanOrEqual(0);
351+
expect(mocks.restartService.mock.invocationCallOrder[0]).toBeLessThan(
352+
vi.mocked(defaultRuntime.log).mock.invocationCallOrder[warningIndex] ??
353+
Number.POSITIVE_INFINITY,
354+
);
355+
expect(logCalls[warningIndex]?.join(" ")).toContain("openclaw completion --write-state");
356+
});
357+
358+
it("restarts when shell completion cache generation returns false", async () => {
359+
Object.defineProperty(process.stdin, "isTTY", { configurable: true, value: true });
360+
mocks.checkCompletionStatus.mockResolvedValueOnce({
361+
shell: "zsh",
362+
profileInstalled: true,
363+
cacheExists: true,
364+
cachePath: "/tmp/openclaw-completion.zsh",
365+
usesSlowPattern: true,
366+
});
367+
mocks.ensureCompletionCache.mockResolvedValueOnce(false);
368+
369+
await finishSuccessfulPackageSwitch({
370+
previousRoot: "/tmp/openclaw-update",
371+
packageRoot: "/tmp/openclaw-update",
372+
restartEnvironment: process.env,
373+
});
374+
375+
const output = vi.mocked(defaultRuntime.log).mock.calls.flat().map(String).join("\n");
376+
expect(output).toContain("completion cache generation failed");
377+
expect(output).toContain("openclaw completion --write-state --install");
378+
expect(mocks.restartService).toHaveBeenCalledOnce();
379+
expect(mocks.restartService.mock.invocationCallOrder[0]).toBeLessThan(
380+
mocks.ensureCompletionCache.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
381+
);
382+
});
383+
384+
it("keeps JSON completion cache failures silent and restarts", async () => {
385+
const root = tempDirs.make("openclaw-json-completion-failure-");
386+
await fs.writeFile(path.join(root, "openclaw.mjs"), "process.exit(1);");
387+
Object.defineProperty(process.stdin, "isTTY", { configurable: true, value: true });
388+
389+
await finishSuccessfulPackageSwitch({
390+
previousRoot: root,
391+
packageRoot: root,
392+
restartEnvironment: process.env,
393+
json: true,
394+
});
395+
396+
expect(defaultRuntime.error).not.toHaveBeenCalled();
397+
expect(mocks.checkCompletionStatus).not.toHaveBeenCalled();
398+
expect(mocks.ensureCompletionCache).not.toHaveBeenCalled();
399+
expect(mocks.restartService).toHaveBeenCalledOnce();
400+
});
401+
402+
it("skips interactive completion in non-TTY mode", async () => {
403+
Object.defineProperty(process.stdin, "isTTY", { configurable: true, value: false });
404+
405+
await finishSuccessfulPackageSwitch({
406+
previousRoot: "/tmp/openclaw-update",
407+
packageRoot: "/tmp/openclaw-update",
408+
restartEnvironment: process.env,
409+
});
410+
411+
expect(mocks.checkCompletionStatus).not.toHaveBeenCalled();
412+
expect(mocks.ensureCompletionCache).not.toHaveBeenCalled();
413+
expect(mocks.restartService).toHaveBeenCalledOnce();
414+
});
415+
416+
it("keeps an unhealthy restart blocking before completion refresh", async () => {
417+
Object.defineProperty(process.stdin, "isTTY", { configurable: true, value: true });
418+
mocks.restartService.mockResolvedValueOnce(false);
419+
mocks.checkCompletionStatus.mockRejectedValueOnce(
420+
new Error("completion status should not run after failed restart health"),
421+
);
422+
423+
await finishSuccessfulPackageSwitch({
424+
previousRoot: "/tmp/openclaw-update",
425+
packageRoot: "/tmp/openclaw-update",
426+
restartEnvironment: process.env,
427+
});
428+
429+
expect(mocks.markSentinelFailure).toHaveBeenCalledWith(
430+
expect.objectContaining({ reason: "restart-unhealthy" }),
431+
);
432+
expect(defaultRuntime.exit).toHaveBeenCalledWith(1);
433+
expect(mocks.checkCompletionStatus).not.toHaveBeenCalled();
434+
});
435+
295436
it("retires the wrapper before persisting and printing success", async () => {
296437
const home = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-finalize-order-"));
297438
const previousRoot = path.join(home, "old-root");

‎src/cli/update-cli/update-command-post-update.ts‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -470,12 +470,6 @@ export async function finishUpdate(params: {
470470
}
471471
}
472472

473-
await tryWriteCompletionCache(postUpdateRoot, Boolean(params.opts.json));
474-
await tryInstallShellCompletion({
475-
jsonMode: Boolean(params.opts.json),
476-
skipPrompt: Boolean(params.opts.yes),
477-
});
478-
479473
await writeControlPlaneUpdateRestartSentinelBestEffort({
480474
meta: params.controlPlaneUpdateSentinelMeta,
481475
result: buildControlPlaneUpdateRestartHealthPendingResult(resultWithPostUpdate),
@@ -515,6 +509,28 @@ export async function finishUpdate(params: {
515509
return;
516510
}
517511

512+
// Restart and health verification own recovery of the service stopped for this update.
513+
// Optional completion refresh must run only after that lifecycle boundary settles.
514+
try {
515+
await tryWriteCompletionCache(postUpdateRoot, Boolean(params.opts.json));
516+
} catch (err) {
517+
if (!params.opts.json) {
518+
const completionCacheRefreshCommand = replaceCliName(
519+
formatCliCommand("openclaw completion --write-state"),
520+
CLI_NAME,
521+
);
522+
defaultRuntime.log(
523+
theme.warn(
524+
`Completion cache update failed: ${formatErrorMessage(err)}. Update will continue; retry with: ${completionCacheRefreshCommand}`,
525+
),
526+
);
527+
}
528+
}
529+
await tryInstallShellCompletion({
530+
jsonMode: Boolean(params.opts.json),
531+
skipPrompt: Boolean(params.opts.yes),
532+
});
533+
518534
if (params.installKindChanged && resultWithPostUpdate.mode !== "git") {
519535
const retirement = await retireStandaloneGitWrapper({
520536
previousRoot: params.previousInstallRoot ?? params.root,

‎src/cli/update-cli/update-command-service.ts‎

Lines changed: 44 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import {
4040
import { readGatewayServiceState, resolveGatewayService } from "../../daemon/service.js";
4141
import { resolveSystemdServiceName } from "../../daemon/systemd-service-files.js";
4242
import { sha256Hex } from "../../infra/crypto-digest.js";
43+
import { formatErrorMessage } from "../../infra/errors.js";
4344
import { assertGatewayServiceMutationAllowed } from "../../infra/gateway-supervision.js";
4445
import { getSelfAndAncestorPidsSync } from "../../infra/restart-stale-pids.js";
4546
import { nodeVersionSatisfiesEngine } from "../../infra/runtime-guard.js";
@@ -874,60 +875,59 @@ export async function tryInstallShellCompletion(opts: {
874875
return;
875876
}
876877

877-
const status = await checkShellCompletionStatus(CLI_NAME);
878-
const generationOptions = { generationMode: "core-only" } as const;
879-
880-
if (status.usesSlowPattern) {
881-
defaultRuntime.log(theme.muted("Upgrading shell completion to cached version..."));
882-
const cacheGenerated = await ensureCompletionCacheExists(CLI_NAME, generationOptions);
883-
if (cacheGenerated) {
884-
await installShellCompletionForUpdate(status.shell, true);
885-
}
886-
return;
887-
}
888-
889-
if (status.profileInstalled && !status.cacheExists) {
890-
defaultRuntime.log(theme.muted("Regenerating shell completion cache..."));
891-
await ensureCompletionCacheExists(CLI_NAME, generationOptions);
892-
return;
893-
}
894-
895-
if (!status.profileInstalled) {
896-
defaultRuntime.log("");
897-
defaultRuntime.log(theme.heading("Shell completion"));
898-
899-
const shouldInstall = await confirm({
900-
message: stylePromptMessage(`Enable ${status.shell} shell completion for ${CLI_NAME}?`),
901-
initialValue: true,
902-
});
878+
try {
879+
const status = await checkShellCompletionStatus(CLI_NAME);
880+
const generationOptions = { generationMode: "core-only" } as const;
903881

904-
if (isCancel(shouldInstall) || !shouldInstall) {
905-
if (!opts.skipPrompt) {
906-
defaultRuntime.log(
907-
theme.muted(
908-
`Skipped. Run \`${replaceCliName(formatCliCommand("openclaw completion --install"), CLI_NAME)}\` later to enable.`,
909-
),
910-
);
882+
if (status.usesSlowPattern) {
883+
defaultRuntime.log(theme.muted("Upgrading shell completion to cached version..."));
884+
if (!(await ensureCompletionCacheExists(CLI_NAME, generationOptions))) {
885+
throw new Error("completion cache generation failed");
911886
}
887+
await installCompletion(status.shell, true, CLI_NAME);
912888
return;
913889
}
914890

915-
const cacheGenerated = await ensureCompletionCacheExists(CLI_NAME, generationOptions);
916-
if (!cacheGenerated) {
917-
defaultRuntime.log(theme.warn("Failed to generate completion cache."));
891+
if (status.profileInstalled && !status.cacheExists) {
892+
defaultRuntime.log(theme.muted("Regenerating shell completion cache..."));
893+
if (!(await ensureCompletionCacheExists(CLI_NAME, generationOptions))) {
894+
throw new Error("completion cache generation failed");
895+
}
918896
return;
919897
}
920898

921-
await installShellCompletionForUpdate(status.shell, opts.skipPrompt);
922-
}
923-
}
899+
if (!status.profileInstalled) {
900+
defaultRuntime.log("");
901+
defaultRuntime.log(theme.heading("Shell completion"));
924902

925-
async function installShellCompletionForUpdate(shell: string, yes: boolean): Promise<void> {
926-
try {
927-
await installCompletion(shell, yes, CLI_NAME);
903+
const shouldInstall = await confirm({
904+
message: stylePromptMessage(`Enable ${status.shell} shell completion for ${CLI_NAME}?`),
905+
initialValue: true,
906+
});
907+
908+
if (isCancel(shouldInstall) || !shouldInstall) {
909+
if (!opts.skipPrompt) {
910+
defaultRuntime.log(
911+
theme.muted(
912+
`Skipped. Run \`${replaceCliName(formatCliCommand("openclaw completion --install"), CLI_NAME)}\` later to enable.`,
913+
),
914+
);
915+
}
916+
return;
917+
}
918+
919+
if (!(await ensureCompletionCacheExists(CLI_NAME, generationOptions))) {
920+
throw new Error("completion cache generation failed");
921+
}
922+
await installCompletion(status.shell, opts.skipPrompt, CLI_NAME);
923+
}
928924
} catch (err) {
929-
const message = err instanceof Error ? err.message : String(err);
930-
defaultRuntime.log(theme.warn(`Shell completion refresh failed: ${message}`));
925+
const message = formatErrorMessage(err);
926+
defaultRuntime.log(
927+
theme.warn(
928+
`Shell completion refresh failed: ${message}. Update will continue; retry with: ${replaceCliName(formatCliCommand("openclaw completion --write-state --install"), CLI_NAME)}`,
929+
),
930+
);
931931
}
932932
}
933933

0 commit comments

Comments
 (0)