Skip to content

Commit 69f1726

Browse files
authored
fix(update): show reliable progress and final outcomes (#133622)
* fix(update): show reliable progress and final outcomes Reuse the inspected package target for Node preflight, overlap beta metadata reads, and share the bounded step runner. Report finalization failures and full elapsed time while preserving restart notification consumption. Stop failed Git cleanliness checks before mutation. * test(gateway): remove circular config mock dependency
1 parent cf25af4 commit 69f1726

22 files changed

Lines changed: 743 additions & 497 deletions

‎docs/cli/update.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,13 @@ for channel/availability only. Gateway console verbosity (`--verbose`) and
5656
file log level (`logging.level: "debug"`/`"trace"`) are independent knobs; see
5757
[Gateway logging](/gateway/logging).
5858

59+
Interactive updates show the current step and elapsed time. When output is
60+
piped or captured in a log, each step prints its progress without animation.
61+
Failed steps include the final diagnostics from both output streams; timeouts
62+
are labeled explicitly. The final total includes plugin updates and requested
63+
Gateway restart checks. `--json` keeps stdout machine-readable and does not
64+
print progress steps.
65+
5966
<Note>
6067
In Nix mode (`OPENCLAW_NIX_MODE=1`), mutating `openclaw update` runs are disabled. Update the Nix source or flake input for this install instead; for nix-openclaw, use the agent-first [Quick Start](https://github.com/openclaw/nix-openclaw#quick-start). `openclaw update status` and `openclaw update --dry-run` remain read-only.
6168
</Note>

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

Lines changed: 125 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ import { createCliRuntimeCapture, getMockCallOutput } from "./test-runtime-captu
3434
const confirm = vi.fn();
3535
const select = vi.fn();
3636
const text = vi.fn();
37-
const spinner = vi.fn(() => ({ start: vi.fn(), stop: vi.fn() }));
37+
const spinner = vi.fn(() => ({ start: vi.fn(), stop: vi.fn(), clear: vi.fn() }));
3838
const isCancel = (value: unknown) => value === "cancel";
3939

4040
const readPackageName = vi.fn();
@@ -542,7 +542,7 @@ const {
542542
const updateCliShared = await import("./update-cli/shared.js");
543543
const { resolveGitInstallDir } = updateCliShared;
544544
const { spawnSync } = await import("node:child_process");
545-
const { readRestartSentinel } = await import("../infra/restart-sentinel.js");
545+
const { clearRestartSentinel, readRestartSentinel } = await import("../infra/restart-sentinel.js");
546546

547547
function requireValue<T>(value: T | undefined, label: string): T {
548548
if (value === undefined) {
@@ -3106,11 +3106,13 @@ describe("update-cli", () => {
31063106
return child;
31073107
});
31083108

3109-
await expect(updateCommand({ yes: true })).rejects.toThrow(
3110-
"post-update process exited with code 2",
3111-
);
3109+
await updateCommand({ yes: true, json: true });
31123110

31133111
expect(defaultRuntime.exit).toHaveBeenCalledWith(2);
3112+
expect(lastWriteJsonCall()).toMatchObject({
3113+
status: "error",
3114+
reason: "post-core-update-failed",
3115+
});
31143116
expect(updateNpmInstalledPlugins).not.toHaveBeenCalled();
31153117
});
31163118

@@ -4019,6 +4021,43 @@ describe("update-cli", () => {
40194021
expect(packageInstallCommandCall()?.[0]).toContain("[email protected]");
40204022
});
40214023

4024+
it.each([true, false])(
4025+
"uses inspected package runtime requirements when a later lookup disagrees (compatible=%s)",
4026+
async (compatible) => {
4027+
mockPackageInstallStatus(createCaseDir("openclaw-runtime-target"));
4028+
const inspectedEngine = compatible ? ">=22.19.0" : ">=999.0.0";
4029+
vi.mocked(fetchNpmPackageTargetStatus)
4030+
.mockResolvedValueOnce(packageTargetStatus({ nodeEngine: inspectedEngine }))
4031+
.mockResolvedValue(
4032+
packageTargetStatus({ nodeEngine: compatible ? ">=999.0.0" : ">=22.19.0" }),
4033+
);
4034+
nodeVersionSatisfiesEngine.mockImplementation(
4035+
(_version: string | null, engine: string | null) => engine !== ">=999.0.0",
4036+
);
4037+
4038+
await updateCommand({ yes: true, restart: false });
4039+
4040+
if (compatible) {
4041+
expect(packageInstallCommandCall()?.[0]).toContain("[email protected]");
4042+
} else {
4043+
expect(packageInstallCommandCall()).toBeUndefined();
4044+
expect(getErrorOutput()).toContain("The requested package requires >=999.0.0");
4045+
}
4046+
expect(fetchNpmPackageTargetStatus).toHaveBeenCalledOnce();
4047+
},
4048+
);
4049+
4050+
it("previews the resolved package owner without probing for another manager", async () => {
4051+
mockPackageInstallStatus(createCaseDir("openclaw-dry-run-owner"));
4052+
resolveGlobalManager.mockResolvedValueOnce("npm").mockResolvedValue("bun");
4053+
4054+
await updateCommand({ dryRun: true, json: true });
4055+
4056+
expect(lastWriteJsonCall()).toMatchObject({ mode: "npm" });
4057+
expect(resolveGlobalManager).toHaveBeenCalledOnce();
4058+
expect(packageInstallCommandCall()).toBeUndefined();
4059+
});
4060+
40224061
it("reports an incompatible package target during dry-run", async () => {
40234062
mockPackageInstallStatus(createCaseDir("openclaw-schema-dry-run"));
40244063
vi.mocked(fetchNpmPackageTargetStatus).mockResolvedValue(
@@ -4578,10 +4617,10 @@ describe("update-cli", () => {
45784617
expectPackageInstallSpec("[email protected]");
45794618
const preflightParams = vi
45804619
.mocked(fetchNpmPackageTargetStatus)
4581-
.mock.calls.find(([params]) => params.target === "latest")?.[0];
4620+
.mock.calls.find(([params]) => params.target === "9999.0.0")?.[0];
45824621
expect(preflightParams).toEqual(
45834622
expect.objectContaining({
4584-
target: "latest",
4623+
target: "9999.0.0",
45854624
45864625
cwd: process.cwd(),
45874626
}),
@@ -5713,11 +5752,15 @@ describe("update-cli", () => {
57135752
});
57145753
const serviceCommand = {
57155754
...servicePlan,
5716-
environment: Object.fromEntries(
5717-
Object.entries(servicePlan.environment).filter(
5718-
(entry): entry is [string, string] => typeof entry[1] === "string",
5755+
environment: {
5756+
...Object.fromEntries(
5757+
Object.entries(servicePlan.environment).filter(
5758+
(entry): entry is [string, string] => typeof entry[1] === "string",
5759+
),
57195760
),
5720-
),
5761+
// This sealed service deliberately has no CLI on PATH, including host-wide installs.
5762+
PATH: wrapperDir,
5763+
},
57215764
};
57225765
serviceReadCommand.mockResolvedValue(serviceCommand);
57235766
serviceLoaded.mockResolvedValue(true);
@@ -7414,7 +7457,7 @@ describe("update-cli", () => {
74147457
const probeCall = probeGatewayCall() as { includeDetails?: boolean } | undefined;
74157458
expect(probeCall?.includeDetails).toBe(true);
74167459
expect(defaultRuntime.exit).toHaveBeenCalledWith(1);
7417-
expect(defaultRuntime.writeJson).not.toHaveBeenCalled();
7460+
expect(lastWriteJsonCall()).toMatchObject({ status: "error", reason: "restart-unhealthy" });
74187461
expect(getErrorOutput()).toContain(
74197462
"Gateway version mismatch: expected 2026.4.24, running gateway reported 2026.4.23.",
74207463
);
@@ -7556,25 +7599,42 @@ describe("update-cli", () => {
75567599
expect(sentinel?.payload.continuation).toBeUndefined();
75577600
});
75587601

7559-
it("marks the control-plane update sentinel failed when restart health verification fails", async () => {
7560-
const sentinel = await runControlPlaneUpdate({
7561-
meta: {
7562-
sessionKey: "agent:main:webchat:dm:user-123",
7563-
continuationMessage: "This should not report a successful update.",
7564-
},
7565-
options: { yes: true, json: true },
7566-
beforeUpdate: () => {
7567-
setupNpmUpdatedRootRefresh();
7568-
prepareRestartScript.mockResolvedValue(null);
7569-
serviceLoaded.mockResolvedValue(true);
7570-
mockGatewayProbe("2026.4.23", "old-gateway");
7571-
},
7572-
});
7573-
expect(sentinel?.payload.status).toBe("error");
7574-
expect(sentinel?.payload.stats?.reason).toBe("restart-unhealthy");
7575-
expect(sentinel?.payload.continuation).toBeUndefined();
7576-
expect(defaultRuntime.exit).toHaveBeenCalledWith(1);
7577-
});
7602+
it.each([false, true])(
7603+
"preserves control-plane update sentinel consumption on restart health failure (consumed=%s)",
7604+
async (consumed) => {
7605+
let sentinelConsumed = false;
7606+
const sentinel = await runControlPlaneUpdate({
7607+
meta: {
7608+
sessionKey: "agent:main:webchat:dm:user-123",
7609+
continuationMessage: "This should not report a successful update.",
7610+
},
7611+
options: { yes: true, json: true },
7612+
beforeUpdate: async () => {
7613+
setupNpmUpdatedRootRefresh();
7614+
prepareRestartScript.mockResolvedValue(null);
7615+
serviceLoaded.mockResolvedValue(true);
7616+
mockGatewayProbe("2026.4.23", "old-gateway");
7617+
if (consumed) {
7618+
const probeResult = await probeGateway();
7619+
probeGateway.mockImplementation(async () => {
7620+
sentinelConsumed = (await clearRestartSentinel()) || sentinelConsumed;
7621+
return probeResult;
7622+
});
7623+
}
7624+
},
7625+
});
7626+
if (consumed) {
7627+
expect(sentinelConsumed).toBe(true);
7628+
expect(sentinel).toBeNull();
7629+
} else {
7630+
expect(sentinel?.payload.status).toBe("error");
7631+
expect(sentinel?.payload.stats?.reason).toBe("restart-unhealthy");
7632+
expect(sentinel?.payload.continuation).toBeUndefined();
7633+
}
7634+
expect(lastWriteJsonCall()).toMatchObject({ status: "error", reason: "restart-unhealthy" });
7635+
expect(defaultRuntime.exit).toHaveBeenCalledWith(1);
7636+
},
7637+
);
75787638

75797639
it("fails a package update when the restarted gateway reports activated plugin load errors", async () => {
75807640
setupNpmUpdatedRootRefresh();
@@ -7760,51 +7820,43 @@ describe("update-cli", () => {
77607820
});
77617821

77627822
it("updateCommand continues after doctor sub-step and clears update flag", async () => {
7763-
const randomSpy = vi.spyOn(Math, "random").mockReturnValue(0);
7764-
try {
7765-
await withEnvAsync({ OPENCLAW_UPDATE_IN_PROGRESS: undefined }, async () => {
7766-
mockRunningManagedGateway([
7767-
"node",
7768-
path.join(process.cwd(), "dist", "index.js"),
7769-
"gateway",
7770-
]);
7771-
mockGitUpdateAfterMutation();
7772-
prepareRestartScript.mockResolvedValue(null);
7773-
vi.mocked(runDaemonRestart).mockResolvedValue(true);
7774-
vi.mocked(doctorCommand).mockResolvedValue(undefined);
7775-
vi.mocked(defaultRuntime.log).mockClear();
7823+
await withEnvAsync({ OPENCLAW_UPDATE_IN_PROGRESS: undefined }, async () => {
7824+
mockRunningManagedGateway(["node", path.join(process.cwd(), "dist", "index.js"), "gateway"]);
7825+
mockGitUpdateAfterMutation();
7826+
prepareRestartScript.mockResolvedValue(null);
7827+
vi.mocked(runDaemonRestart).mockResolvedValue(true);
7828+
vi.mocked(doctorCommand).mockResolvedValue(undefined);
7829+
vi.mocked(defaultRuntime.log).mockClear();
77767830

7777-
await updateCommand({});
7831+
await updateCommand({});
77787832

7779-
const doctorCall = vi.mocked(doctorCommand).mock.calls[0];
7780-
expect(doctorCall?.[0]).toBe(defaultRuntime);
7781-
expect(doctorCall?.[1]?.nonInteractive).toBe(true);
7782-
expect(process.env.OPENCLAW_UPDATE_IN_PROGRESS).toBeUndefined();
7783-
const snapshotOrders = createPreUpdateConfigSnapshotMock.mock.invocationCallOrder;
7784-
expect(createPreUpdateConfigSnapshotMock).toHaveBeenCalledTimes(2);
7785-
expect(requireValue(snapshotOrders[0], "restart snapshot call order")).toBeLessThan(
7786-
requireValue(
7787-
vi.mocked(runDaemonRestart).mock.invocationCallOrder[0],
7788-
"daemon restart call order",
7789-
),
7790-
);
7791-
expect(requireValue(snapshotOrders[1], "doctor snapshot call order")).toBeLessThan(
7792-
requireValue(
7793-
vi.mocked(doctorCommand).mock.invocationCallOrder[0],
7794-
"doctor command call order",
7795-
),
7796-
);
7833+
const doctorCall = vi.mocked(doctorCommand).mock.calls[0];
7834+
expect(doctorCall?.[0]).toBe(defaultRuntime);
7835+
expect(doctorCall?.[1]?.nonInteractive).toBe(true);
7836+
expect(process.env.OPENCLAW_UPDATE_IN_PROGRESS).toBeUndefined();
7837+
const snapshotOrders = createPreUpdateConfigSnapshotMock.mock.invocationCallOrder;
7838+
expect(createPreUpdateConfigSnapshotMock).toHaveBeenCalledTimes(2);
7839+
expect(requireValue(snapshotOrders[0], "restart snapshot call order")).toBeLessThan(
7840+
requireValue(
7841+
vi.mocked(runDaemonRestart).mock.invocationCallOrder[0],
7842+
"daemon restart call order",
7843+
),
7844+
);
7845+
expect(requireValue(snapshotOrders[1], "doctor snapshot call order")).toBeLessThan(
7846+
requireValue(
7847+
vi.mocked(doctorCommand).mock.invocationCallOrder[0],
7848+
"doctor command call order",
7849+
),
7850+
);
77977851

7798-
const logLines = vi.mocked(defaultRuntime.log).mock.calls.map((call) => String(call[0]));
7799-
expect(
7800-
logLines.some((line) =>
7801-
line.includes("Leveled up! New skills unlocked. You're welcome."),
7802-
),
7803-
).toBe(true);
7804-
});
7805-
} finally {
7806-
randomSpy.mockRestore();
7807-
}
7852+
const successIndex = vi
7853+
.mocked(defaultRuntime.log)
7854+
.mock.calls.findIndex((call) => String(call[0]).includes("Update Result: OK"));
7855+
expect(successIndex).toBeGreaterThanOrEqual(0);
7856+
expect(vi.mocked(defaultRuntime.log).mock.invocationCallOrder[successIndex]).toBeGreaterThan(
7857+
requireValue(vi.mocked(doctorCommand).mock.invocationCallOrder[0], "doctor call order"),
7858+
);
7859+
});
78087860
});
78097861

78107862
it("marks the whole update command as update-in-progress", async () => {

‎src/cli/update-cli/progress.test.ts‎

Lines changed: 64 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
// Update progress tests cover progress event formatting for update operations.
22
import { afterEach, describe, expect, it, vi } from "vitest";
3-
import type { UpdateRunResult } from "../../infra/update-runner.js";
3+
import type { UpdateRunResult, UpdateStepResult } from "../../infra/update-runner.js";
44
import { defaultRuntime } from "../../runtime.js";
5-
import { printResult } from "./progress.js";
5+
import { createUpdateProgress, printResult } from "./progress.js";
66

77
function makeResult(
88
stepName: string,
99
stderrTail: string,
1010
mode: UpdateRunResult["mode"] = "npm",
11-
): UpdateRunResult {
11+
): UpdateRunResult & { steps: [UpdateStepResult] } {
1212
return {
1313
status: "error",
1414
mode,
@@ -27,12 +27,12 @@ function makeResult(
2727
};
2828
}
2929

30-
function renderResult(result: UpdateRunResult): string {
30+
function renderResult(result: UpdateRunResult, hideSteps = true): string {
3131
const lines: string[] = [];
3232
vi.spyOn(defaultRuntime, "log").mockImplementation((...args: unknown[]) => {
3333
lines.push(args.map(String).join(" "));
3434
});
35-
printResult(result, { hideSteps: true });
35+
printResult(result, { hideSteps });
3636
return lines.join("\n");
3737
}
3838

@@ -119,4 +119,63 @@ describe("update failure hints", () => {
119119
expect(output).not.toContain("Recovery hints:");
120120
expect(output).not.toContain("npm config set prefix ~/.local");
121121
});
122+
123+
it("shows the final diagnostics from both build streams", () => {
124+
const result = makeResult("build", "Build failed", "git");
125+
result.steps[0].stdoutTail = [
126+
"old output",
127+
...Array.from({ length: 10 }, (_, i) => `diagnostic ${i}`),
128+
].join("\n");
129+
130+
const output = renderResult(result, false);
131+
132+
expect(output).toContain("Building");
133+
expect(output).toContain("diagnostic 9");
134+
expect(output).toContain("Build failed");
135+
expect(output).not.toContain("old output");
136+
});
137+
138+
it("explains a timeout even when the subprocess produced no output", () => {
139+
const result = makeResult("build", "", "git");
140+
result.steps[0].exitCode = null;
141+
result.steps[0].termination = "timeout";
142+
143+
expect(renderResult(result, false)).toContain("Building — timed out");
144+
});
145+
146+
it("reports redirected progress before completion and preserves stdout failures", () => {
147+
const tty = Object.getOwnPropertyDescriptor(process.stdout, "isTTY");
148+
Object.defineProperty(process.stdout, "isTTY", { configurable: true, value: false });
149+
const log = vi.spyOn(defaultRuntime, "log").mockImplementation(() => {});
150+
const { progress, stop } = createUpdateProgress(true);
151+
const step = { name: "build", command: "pnpm build", index: 0, total: 1 };
152+
try {
153+
progress.onStepStart?.(step);
154+
expect(log).toHaveBeenCalledWith("Building...");
155+
progress.onStepComplete?.({
156+
...step,
157+
durationMs: 1200,
158+
exitCode: 1,
159+
stdoutTail: "Build type error",
160+
});
161+
expect(log.mock.calls.flat().join("\n")).toContain("Build type error");
162+
} finally {
163+
stop();
164+
if (tty) {
165+
Object.defineProperty(process.stdout, "isTTY", tty);
166+
} else {
167+
Reflect.deleteProperty(process.stdout, "isTTY");
168+
}
169+
}
170+
});
171+
172+
it("keeps progress silent when JSON output owns stdout", () => {
173+
const log = vi.spyOn(defaultRuntime, "log").mockImplementation(() => {});
174+
const { progress, stop } = createUpdateProgress(false);
175+
const step = { name: "build", command: "pnpm build", index: 0, total: 1 };
176+
progress.onStepStart?.(step);
177+
progress.onStepComplete?.({ ...step, durationMs: 1, exitCode: 0 });
178+
stop();
179+
expect(log).not.toHaveBeenCalled();
180+
});
122181
});

0 commit comments

Comments
 (0)