Skip to content

Commit cfbe8cf

Browse files
committed
fix(cloud): complete setup after plugin activation
Wait for the exact applied config revision before refreshing the current client's hello in Cloud setup and Plugins. Reuse the config owner's existing refresh loop and retain Gateway, auth, source, mutation, and page fences. Keep long diagnostics readable in wrapping descriptions and report a closed archive-format rejection without exposing raw native details. Explicit CLI installation refreshes inspection so operator-provided executables can be adopted and removed or tampered files cannot report stale availability. Ordinary inspection remains process-cached and concurrent installs coalesce. Validation: 243 UI/diagnostic tests, final 41 selected installer/setup/discovery tests, canonical UI/extension types, focused lint, i18n, docs, and formatting pass. Regression failures were captured first. Fresh Codex P0 review reports no actionable findings. Full candidate build and live replay follow. Managed PAX extraction is still blocked in fs-safe; no dependency, hash, extraction safeguard, SDK budget, or native lifecycle gate was bypassed. Related to #130713 (guided cloud-session setup).
1 parent 97c6b86 commit cfbe8cf

11 files changed

Lines changed: 646 additions & 38 deletions

‎docs/gateway/cloud-workers.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ Open **Settings → Connections → Cloud sessions**, then choose **Add cloud pr
4848

4949
The test creates an ordinary managed-worktree session, runs a real agent turn, verifies a file roundtrip, and reclaims the worker. A pass requires verified teardown, not just a successful credential check or a session appearing in the sidebar. Navigating away does not cancel server-owned cleanup. Cancellation can remain **cleanup pending** until release is verified. After a Gateway restart, the test is interrupted rather than replayed; durable cleanup intent allows the Gateway to reclaim only that exact test placement. An interrupted test never becomes a pass merely because its environment disappears.
5050

51+
If archive validation rejects the CLI release, keep the validation checks enabled. Check for an OpenClaw update, or place a compatible Crabbox executable on the Gateway user's existing `PATH` and choose **Install compatible dependency** again. This explicit action rechecks the installation without allocating a worker.
52+
5153
Saved keys are write-only through the secret-store API, but the SQLite store is **not encrypted at rest**. Protect the Gateway's state directory and backups. Cloud control credentials are resolved only for the selected connection's local Crabbox commands; they are not forwarded to worker setup or agent tools. See [Secrets](/gateway/secrets).
5254

5355
Use **Advanced** for existing manual profiles and provider configurations without guided setup. Removing a profile also removes project defaults that reference it, but retains its connection and secret so outstanding workers can still be cleaned up.

‎extensions/crabbox/src/crabbox-install.test.ts‎

Lines changed: 141 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
1-
import { chmod, mkdir, readFile, stat, symlink, writeFile } from "node:fs/promises";
1+
import { createHash, Hash } from "node:crypto";
2+
import {
3+
chmod,
4+
mkdir,
5+
readFile,
6+
readdir,
7+
stat,
8+
symlink,
9+
unlink,
10+
writeFile,
11+
} from "node:fs/promises";
212
import path from "node:path";
13+
import { ArchiveFormatError } from "@openclaw/fs-safe/archive";
314
import type { SpawnResult } from "openclaw/plugin-sdk/process-runtime";
415
import { useAutoCleanupTempDirTracker } from "openclaw/plugin-sdk/test-env";
516
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -32,7 +43,10 @@ beforeEach(() => {
3243
mock.mockReset();
3344
}
3445
});
35-
afterEach(() => vi.unstubAllEnvs());
46+
afterEach(() => {
47+
vi.unstubAllEnvs();
48+
vi.restoreAllMocks();
49+
});
3650

3751
describe("explicit Crabbox installation", () => {
3852
async function verifiedArchive(root: string, name: string) {
@@ -104,22 +118,89 @@ describe("explicit Crabbox installation", () => {
104118
},
105119
);
106120

107-
it("reuses a compatible PATH executable as unmanaged without downloading or publishing metadata", async () => {
121+
it("refreshes cached missing inspection on explicit install to reuse an operator PATH executable", async () => {
108122
const dir = tempDirs.make("crabbox-unmanaged-");
109123
const binary = path.join(dir, process.platform === "win32" ? "crabbox.exe" : "crabbox");
110-
await writeFile(binary, "fixture");
111-
await chmod(binary, 0o700);
112124
vi.stubEnv("PATH", dir);
113125
vi.stubEnv("OPENCLAW_STATE_DIR", path.join(dir, "state"));
114-
const installation = createCrabboxInstallation(vi.fn(async () => version));
115-
expect(await installation.install()).toMatchObject({
116-
status: "unmanaged",
117-
dependency: { version: "0.46.0", managed: false },
126+
const runCommand = vi.fn(async () => version);
127+
const installation = createCrabboxInstallation(runCommand);
128+
expect((await installation.inspect()).dependency.state).toBe("missing");
129+
await writeFile(binary, "fixture");
130+
await chmod(binary, 0o700);
131+
// Ordinary inspection remains cached until the operator explicitly requests installation.
132+
expect((await installation.inspect()).dependency.state).toBe("missing");
133+
expect(runCommand).not.toHaveBeenCalled();
134+
for (const result of await Promise.all([installation.install(), installation.install()])) {
135+
expect(result).toMatchObject({
136+
status: "unmanaged",
137+
dependency: { state: "available", version: "0.46.0", managed: false },
138+
});
139+
}
140+
expect(await installation.inspect()).toMatchObject({
141+
binary,
142+
dependency: { state: "available", managed: false },
118143
});
144+
expect(await installation.requireBinary()).toBe(binary);
145+
expect(runCommand).toHaveBeenCalledOnce();
119146
expect(mocks.fetch).not.toHaveBeenCalled();
147+
expect(mocks.extract).not.toHaveBeenCalled();
120148
expect(mocks.register).not.toHaveBeenCalled();
121149
});
122150

151+
it.each(["removed", "tampered-managed"])(
152+
"invalidates cached availability on explicit install after the executable is %s",
153+
async (change) => {
154+
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
155+
vi.spyOn(process, "arch", "get").mockReturnValue("x64");
156+
const dir = tempDirs.make("crabbox-refresh-");
157+
const stateDir = path.join(dir, "state");
158+
vi.stubEnv("PATH", dir);
159+
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
160+
let binary = path.join(dir, "crabbox");
161+
await writeFile(binary, "path-fixture", { mode: 0o700 });
162+
if (change === "tampered-managed") {
163+
const destination = path.join(stateDir, "tools", "crabbox", "0.46.0-linux_amd64");
164+
await mkdir(destination, { recursive: true });
165+
binary = path.join(destination, "crabbox");
166+
await writeFile(binary, "managed-fixture", { mode: 0o700 });
167+
mocks.lookup.mockReturnValue({
168+
binary,
169+
files: { crabbox: createHash("sha256").update("managed-fixture").digest("hex") },
170+
version: "0.46.0",
171+
assetHash: "6a9341e810307356361dbed4c4b84be28a036b5cc291af1566d2ccd376570d90",
172+
});
173+
}
174+
const runCommand = vi.fn(async () => version);
175+
const installation = createCrabboxInstallation(runCommand);
176+
expect(await installation.inspect()).toMatchObject({
177+
binary,
178+
dependency: { state: "available", managed: change === "tampered-managed" },
179+
});
180+
if (change === "removed") {
181+
await unlink(binary);
182+
} else {
183+
await writeFile(binary, "do-not-overwrite");
184+
}
185+
mocks.fetch.mockRejectedValue(new Error("fixture download unavailable"));
186+
expect(await installation.install()).toMatchObject({
187+
status: "failed",
188+
dependency: { state: "missing" },
189+
});
190+
expect((await installation.inspect()).dependency.state).toBe("missing");
191+
await expect(installation.requireBinary()).rejects.toThrow(
192+
"Install a compatible Crabbox CLI",
193+
);
194+
expect(runCommand).toHaveBeenCalledOnce();
195+
expect(mocks.fetch).toHaveBeenCalledOnce();
196+
expect(mocks.extract).not.toHaveBeenCalled();
197+
expect(mocks.register).not.toHaveBeenCalled();
198+
if (change === "tampered-managed") {
199+
expect(await readFile(binary, "utf8")).toBe("do-not-overwrite");
200+
}
201+
},
202+
);
203+
123204
it("rejects a bad official payload checksum before extraction or execution", async () => {
124205
const dir = tempDirs.make("crabbox-checksum-");
125206
await mkdir(path.join(dir, "empty-path"));
@@ -142,4 +223,55 @@ describe("explicit Crabbox installation", () => {
142223
expect(runCommand).not.toHaveBeenCalled();
143224
expect(mocks.register).not.toHaveBeenCalled();
144225
});
226+
227+
it.each([true, false])(
228+
"reports extraction failure safely (format rejection: %s)",
229+
async (format) => {
230+
vi.spyOn(process, "platform", "get").mockReturnValue("darwin");
231+
vi.spyOn(process, "arch", "get").mockReturnValue("arm64");
232+
const dir = tempDirs.make("crabbox-extraction-");
233+
const stateDir = path.join(dir, "state");
234+
vi.stubEnv("PATH", dir);
235+
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
236+
const release = vi.fn(async () => {});
237+
mocks.fetch.mockResolvedValue({
238+
response: new Response("synthetic-verified-archive"),
239+
release,
240+
});
241+
// Only the checksum oracle is mocked: exercise the installer through extraction failure.
242+
// The independent tampered-payload case above keeps the real checksum rejection boundary.
243+
vi.spyOn(Hash.prototype, "digest").mockReturnValue(
244+
"2216da0acbcc6e822ee341ec313aaab58875db951fa1daf0d13dd710ebfba9b8",
245+
);
246+
mocks.extract.mockRejectedValue(
247+
format
248+
? new ArchiveFormatError("private archive detail")
249+
: new Error("private archive detail"),
250+
);
251+
const runCommand = vi.fn(async () => version);
252+
const result = await createCrabboxInstallation(runCommand).install();
253+
expect(mocks.extract).toHaveBeenCalledOnce();
254+
expect(result).toMatchObject({
255+
status: "failed",
256+
dependency: { state: "missing", managed: false },
257+
});
258+
expect(result.diagnostics[0]?.message).not.toContain("private archive detail");
259+
if (format) {
260+
expect(result.diagnostics[0]).toMatchObject({
261+
code: "install_archive_rejected",
262+
action: "install",
263+
});
264+
expect(result.diagnostics[0]?.message).toContain("archive format");
265+
expect(result.diagnostics[0]?.message).toContain("OpenClaw update");
266+
expect(result.diagnostics[0]?.message).toContain("PATH");
267+
} else {
268+
expect(result.diagnostics[0]).toMatchObject({ code: "install_failed", action: "install" });
269+
expect(result.diagnostics[0]?.message).toContain("Check network access");
270+
}
271+
expect(release).toHaveBeenCalledOnce();
272+
expect(runCommand).not.toHaveBeenCalled();
273+
expect(mocks.register).not.toHaveBeenCalled();
274+
expect(await readdir(path.join(stateDir, "tools", "crabbox"))).toEqual([]);
275+
},
276+
);
145277
});

‎extensions/crabbox/src/crabbox-install.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,9 @@ export function createCrabboxInstallation(runCommand: CrabboxCommandRunner) {
136136
};
137137
const inspect = () => (inspection ??= load());
138138
const install = async (): Promise<WorkerSetupInstallResult> => {
139-
const current = await inspect();
139+
// Explicit installation rechecks operator changes; ordinary inspection stays cached.
140+
inspection = load();
141+
const current = await inspection;
140142
if (current.dependency.state === "available") {
141143
return {
142144
status: current.dependency.managed ? "installed" : "unmanaged",
@@ -219,6 +221,9 @@ export function createCrabboxInstallation(runCommand: CrabboxCommandRunner) {
219221
const installed = await inspection;
220222
return { status: "installed", dependency: installed.dependency, diagnostics: [] };
221223
} catch (error) {
224+
// The extractor's closed error code is safe to project; its message may contain paths.
225+
const archiveRejected =
226+
error instanceof Error && "code" in error && error.code === "archive-header-invalid";
222227
return {
223228
status: "failed",
224229
dependency: current.dependency,
@@ -227,12 +232,16 @@ export function createCrabboxInstallation(runCommand: CrabboxCommandRunner) {
227232
code:
228233
error instanceof OccupiedInstallationError
229234
? "install_directory_occupied"
230-
: "install_failed",
235+
: archiveRejected
236+
? "install_archive_rejected"
237+
: "install_failed",
231238
severity: "error",
232239
message:
233240
error instanceof OccupiedInstallationError
234241
? `The managed Crabbox version directory contains unexpected or modified files: ${destination}. Move that directory aside after stopping users of its binary, then retry installation. No files were overwritten.`
235-
: "Crabbox installation failed verification or could not be published. Check network access and the Gateway's managed tools directory, then retry; a complete verified installation can be recovered. No cloud machine was allocated.",
242+
: archiveRejected
243+
? "OpenClaw rejected the Crabbox release archive format before installation. Check for an OpenClaw update, or use a compatible Crabbox CLI on the Gateway user's PATH or set settings.binary in Advanced. No cloud machine was allocated."
244+
: "Crabbox installation failed verification or could not be published. Check network access and the Gateway's managed tools directory, then retry; a complete verified installation can be recovered. No cloud machine was allocated.",
236245
action: "install",
237246
},
238247
],
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import { expect, it } from "vitest";
2+
import { installMockGateway, waitForConfirmModal } from "../test-helpers/control-ui-e2e.ts";
3+
import {
4+
cloudSetupDescription,
5+
cloudSetupFeatureMethods,
6+
cloudSetupMethods,
7+
cloudSetupPlugin,
8+
configResponse,
9+
} from "./cloud-workers-settings.test-support.ts";
10+
import { createControlUiE2eSuite } from "./control-ui-e2e-suite.test-support.ts";
11+
12+
const suite = createControlUiE2eSuite({
13+
name: "Cloud dependency installation diagnostics",
14+
startServerBeforeBrowser: true,
15+
});
16+
17+
suite.define(() => {
18+
it("wraps failed installation guidance without hiding it beneath the recovery action", async () => {
19+
await suite.withPage(
20+
{ locale: "en-US", serviceWorkers: "block", viewport: { width: 1440, height: 1040 } },
21+
async ({ page }) => {
22+
const message =
23+
"The release archive format was rejected before installation. Check for an OpenClaw update, or use a compatible executable already installed on the Gateway through PATH or Advanced settings. No cloud machine was allocated.";
24+
const dependency = { ...cloudSetupDescription.dependency, state: "missing" };
25+
const gateway = await installMockGateway(page, {
26+
featureMethods: cloudSetupFeatureMethods,
27+
methodResponses: {
28+
"plugins.list": { plugins: [cloudSetupPlugin], diagnostics: [], mutationAllowed: true },
29+
"config.get": configResponse({}, "setup-1"),
30+
[cloudSetupMethods.describe]: { ...cloudSetupDescription, dependency },
31+
[cloudSetupMethods.install]: {
32+
status: "failed",
33+
dependency,
34+
diagnostics: [
35+
{ code: "archive_rejected", severity: "error", message, action: "install" },
36+
],
37+
},
38+
},
39+
});
40+
await page.goto(`${suite.server.baseUrl}settings/cloud-workers`);
41+
await page
42+
.getByRole("button", { name: "Install compatible dependency", exact: true })
43+
.click();
44+
const dialog = await waitForConfirmModal(page);
45+
await dialog
46+
.getByRole("button", { name: "Install compatible dependency", exact: true })
47+
.click();
48+
const guidance = page.getByText(message, { exact: true });
49+
await guidance.waitFor();
50+
await page
51+
.locator(".settings-row")
52+
.filter({ has: guidance })
53+
.getByText("Diagnostics", { exact: true })
54+
.waitFor();
55+
const geometry = await guidance.evaluate((element) => {
56+
const rect = element.getBoundingClientRect();
57+
const control = element
58+
.closest(".settings-row")
59+
?.querySelector("button")
60+
?.getBoundingClientRect();
61+
return {
62+
height: rect.height,
63+
lineHeight: Number.parseFloat(getComputedStyle(element).lineHeight),
64+
right: rect.right,
65+
controlLeft: control?.left,
66+
overflow: element.scrollWidth > element.clientWidth,
67+
};
68+
});
69+
expect(geometry.height).toBeGreaterThan(geometry.lineHeight * 2);
70+
expect(geometry.controlLeft).toBeDefined();
71+
expect(geometry.right).toBeLessThan(geometry.controlLeft!);
72+
expect(geometry.overflow).toBe(false);
73+
expect(await gateway.getRequests(cloudSetupMethods.install)).toHaveLength(1);
74+
expect(await gateway.getRequests("environments.create")).toHaveLength(0);
75+
expect(await page.getByText("Compatible", { exact: true }).count()).toBe(0);
76+
await page.getByRole("button", { name: "Manage plugins", exact: true }).last().click();
77+
await page.waitForURL((url) => url.pathname === "/settings/plugins");
78+
},
79+
);
80+
});
81+
});

‎ui/src/lib/config/config-write-coordinator.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -773,7 +773,7 @@ export function createConfigWriteCoordinator({
773773
// Do not join a config.get that started before the external RPC.
774774
const refresh = run(() => loadConfig(state));
775775
void trackLoad("config", refresh);
776-
return await refresh;
776+
return await refresh.finally(reconcileAppliedRefresh);
777777
},
778778
),
779779
unavailable,
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import type { GatewayBrowserClient } from "../../api/gateway.ts";
2+
import type { RuntimeConfigCapability } from "../config/runtime-config-capability.ts";
3+
4+
/** Observe the config owner's reload result; hello methods change only on reconnect. */
5+
export function createPluginSurfaceRefresh(
6+
config: RuntimeConfigCapability,
7+
client: GatewayBrowserClient,
8+
isCurrent: () => boolean,
9+
): (() => () => void) | undefined {
10+
const snapshot = config.state.configSnapshot;
11+
if (!snapshot?.hash) {
12+
return undefined;
13+
}
14+
const sourceHash = snapshot.hash;
15+
const revision = snapshot.configRevisionHash ?? sourceHash;
16+
return () => {
17+
const stop = () => unsubscribe();
18+
const refresh = () => {
19+
const current = config.state.configSnapshot;
20+
if (!current || !isCurrent() || current.hash !== sourceHash) {
21+
stop();
22+
} else if (current.appliedConfigHash === revision) {
23+
// Keep the client/auth identity and let the shared supervisor obtain a new hello.
24+
stop();
25+
client.forceReconnect("plugin policy changed");
26+
}
27+
};
28+
const unsubscribe = config.subscribe(refresh);
29+
refresh();
30+
return stop;
31+
};
32+
}

‎ui/src/pages/cloud-workers/cloud-provider-setup-view.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,9 @@ function diagnostics(items: WorkerSetupDiagnostic[], props: SetupProps) {
9090
renderSettingsRow({
9191
title: renderSettingsStatus({
9292
kind: item.severity === "error" ? "danger" : item.severity === "warning" ? "warn" : "muted",
93-
label: item.message,
93+
label: t("configView.sections.diagnostics"),
9494
}),
95+
description: item.message,
9596
control:
9697
item.action === "configure_endpoint"
9798
? action(t("cloudSetup.endpointSettings"), props.onEndpointSettings)

0 commit comments

Comments
 (0)