refactor: unify restart gating and update availability sync

This commit is contained in:
Peter Steinberger
2026-02-19 10:00:27 +01:00
parent 18179fc2c1
commit b4dbe03298
25 changed files with 288 additions and 41 deletions

View File

@@ -1,4 +1,5 @@
import { Type } from "@sinclair/typebox";
import { isRestartEnabled } from "../../config/commands.js";
import type { OpenClawConfig } from "../../config/config.js";
import { resolveConfigSnapshotHash } from "../../config/io.js";
import { extractDeliveryInfo } from "../../config/sessions.js";
@@ -75,8 +76,8 @@ export function createGatewayTool(opts?: {
const params = args as Record<string, unknown>;
const action = readStringParam(params, "action", { required: true });
if (action === "restart") {
if (opts?.config?.commands?.restart !== true) {
throw new Error("Gateway restart is disabled. Set commands.restart=true to enable.");
if (!isRestartEnabled(opts?.config)) {
throw new Error("Gateway restart is disabled (commands.restart=false).");
}
const sessionKey =
typeof params.sessionKey === "string" && params.sessionKey.trim()

View File

@@ -58,7 +58,7 @@ describe("trigger handling", () => {
);
});
});
it("rejects /restart by default", async () => {
it("restarts by default", async () => {
await withTempHome(async (home) => {
const runEmbeddedPiAgentMock = getRunEmbeddedPiAgentMock();
const res = await getReplyFromConfig(
@@ -72,14 +72,14 @@ describe("trigger handling", () => {
makeCfg(home),
);
const text = Array.isArray(res) ? res[0]?.text : res?.text;
expect(text).toContain("/restart is disabled");
expect(text?.startsWith("⚙️ Restarting") || text?.startsWith("⚠️ Restart failed")).toBe(true);
expect(runEmbeddedPiAgentMock).not.toHaveBeenCalled();
});
});
it("restarts when enabled", async () => {
it("rejects /restart when explicitly disabled", async () => {
await withTempHome(async (home) => {
const runEmbeddedPiAgentMock = getRunEmbeddedPiAgentMock();
const cfg = { ...makeCfg(home), commands: { restart: true } } as OpenClawConfig;
const cfg = { ...makeCfg(home), commands: { restart: false } } as OpenClawConfig;
const res = await getReplyFromConfig(
{
Body: "/restart",
@@ -91,7 +91,7 @@ describe("trigger handling", () => {
cfg,
);
const text = Array.isArray(res) ? res[0]?.text : res?.text;
expect(text?.startsWith("⚙️ Restarting") || text?.startsWith("⚠️ Restart failed")).toBe(true);
expect(text).toContain("/restart is disabled");
expect(runEmbeddedPiAgentMock).not.toHaveBeenCalled();
});
});

View File

@@ -1,4 +1,5 @@
import { abortEmbeddedPiRun } from "../../agents/pi-embedded.js";
import { isRestartEnabled } from "../../config/commands.js";
import type { SessionEntry } from "../../config/sessions.js";
import { updateSessionStore } from "../../config/sessions.js";
import { logVerbose } from "../../globals.js";
@@ -256,11 +257,11 @@ export const handleRestartCommand: CommandHandler = async (params, allowTextComm
);
return { shouldContinue: false };
}
if (params.cfg.commands?.restart !== true) {
if (!isRestartEnabled(params.cfg)) {
return {
shouldContinue: false,
reply: {
text: "⚠️ /restart is disabled. Set commands.restart=true to enable.",
text: "⚠️ /restart is disabled (commands.restart=false).",
},
};
}

View File

@@ -124,7 +124,7 @@ export async function runGatewayLoop(params: {
const authorized = consumeGatewaySigusr1RestartAuthorization();
if (!authorized && !isGatewaySigusr1RestartExternallyAllowed()) {
gatewayLog.warn(
"SIGUSR1 restart ignored (not authorized; enable commands.restart or use gateway tool).",
"SIGUSR1 restart ignored (not authorized; commands.restart=false or use gateway tool).",
);
return;
}

View File

@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import {
isRestartEnabled,
isNativeCommandsExplicitlyDisabled,
resolveNativeCommandsEnabled,
resolveNativeSkillsEnabled,
@@ -97,3 +98,13 @@ describe("isNativeCommandsExplicitlyDisabled", () => {
).toBe(false);
});
});
describe("isRestartEnabled", () => {
it("defaults to enabled unless explicitly false", () => {
expect(isRestartEnabled(undefined)).toBe(true);
expect(isRestartEnabled({})).toBe(true);
expect(isRestartEnabled({ commands: {} })).toBe(true);
expect(isRestartEnabled({ commands: { restart: true } })).toBe(true);
expect(isRestartEnabled({ commands: { restart: false } })).toBe(false);
});
});

View File

@@ -61,3 +61,7 @@ export function isNativeCommandsExplicitlyDisabled(params: {
}
return false;
}
export function isRestartEnabled(config?: { commands?: { restart?: boolean } }): boolean {
return config?.commands?.restart !== false;
}

View File

@@ -307,7 +307,7 @@ export const FIELD_HELP: Record<string, string> = {
"How long bash waits before backgrounding (default: 2000; 0 backgrounds immediately).",
"commands.config": "Allow /config chat command to read/write config on disk (default: false).",
"commands.debug": "Allow /debug chat command for runtime-only overrides (default: false).",
"commands.restart": "Allow /restart and gateway restart tool actions (default: false).",
"commands.restart": "Allow /restart and gateway restart tool actions (default: true).",
"commands.useAccessGroups": "Enforce access-group allowlists/policies for commands.",
"commands.ownerAllowFrom":
"Explicit owner allowlist for owner-only tools/commands. Use channel-native IDs (optionally prefixed like \"whatsapp:+15551234567\"). '*' is ignored.",

View File

@@ -112,7 +112,7 @@ export type CommandsConfig = {
config?: boolean;
/** Allow /debug command (default: false). */
debug?: boolean;
/** Allow restart commands/tools (default: false). */
/** Allow restart commands/tools (default: true). */
restart?: boolean;
/** Enforce access-group allowlists/policies for commands (default: true). */
useAccessGroups?: boolean;

View File

@@ -129,11 +129,11 @@ export const CommandsSchema = z
bashForegroundMs: z.number().int().min(0).max(30_000).optional(),
config: z.boolean().optional(),
debug: z.boolean().optional(),
restart: z.boolean().optional(),
restart: z.boolean().optional().default(true),
useAccessGroups: z.boolean().optional(),
ownerAllowFrom: z.array(z.union([z.string(), z.number()])).optional(),
allowFrom: ElevatedAllowFromSchema.optional(),
})
.strict()
.optional()
.default({ native: "auto", nativeSkills: "auto" });
.default({ native: "auto", nativeSkills: "auto", restart: true });

7
src/gateway/events.ts Normal file
View File

@@ -0,0 +1,7 @@
import type { UpdateAvailable } from "../infra/update-startup.js";
export const GATEWAY_EVENT_UPDATE_AVAILABLE = "update.available" as const;
export type GatewayUpdateAvailableEventPayload = {
updateAvailable: UpdateAvailable | null;
};

View File

@@ -1,4 +1,5 @@
import { listChannelPlugins } from "../channels/plugins/index.js";
import { GATEWAY_EVENT_UPDATE_AVAILABLE } from "./events.js";
const BASE_METHODS = [
"health",
@@ -117,4 +118,5 @@ export const GATEWAY_EVENTS = [
"voicewake.changed",
"exec.approval.requested",
"exec.approval.resolved",
GATEWAY_EVENT_UPDATE_AVAILABLE,
];

View File

@@ -2,6 +2,7 @@ import { getActiveEmbeddedRunCount } from "../agents/pi-embedded-runner/runs.js"
import { getTotalPendingReplies } from "../auto-reply/reply/dispatcher-registry.js";
import type { CliDeps } from "../cli/deps.js";
import { resolveAgentMaxConcurrent, resolveSubagentMaxConcurrent } from "../config/agent-limits.js";
import { isRestartEnabled } from "../config/commands.js";
import type { loadConfig } from "../config/config.js";
import { startGmailWatcherWithLogs } from "../hooks/gmail-watcher-lifecycle.js";
import { stopGmailWatcher } from "../hooks/gmail-watcher.js";
@@ -48,7 +49,7 @@ export function createGatewayReloadHandlers(params: {
plan: GatewayReloadPlan,
nextConfig: ReturnType<typeof loadConfig>,
) => {
setGatewaySigusr1RestartPolicy({ allowExternal: nextConfig.commands?.restart === true });
setGatewaySigusr1RestartPolicy({ allowExternal: isRestartEnabled(nextConfig) });
const state = params.getState();
const nextState = { ...state };
@@ -138,7 +139,7 @@ export function createGatewayReloadHandlers(params: {
plan: GatewayReloadPlan,
nextConfig: ReturnType<typeof loadConfig>,
) => {
setGatewaySigusr1RestartPolicy({ allowExternal: nextConfig.commands?.restart === true });
setGatewaySigusr1RestartPolicy({ allowExternal: isRestartEnabled(nextConfig) });
const reasons = plan.restartReasons.length
? plan.restartReasons.join(", ")
: plan.changedPaths.join(", ");

View File

@@ -8,6 +8,7 @@ import type { CanvasHostServer } from "../canvas-host/server.js";
import { type ChannelId, listChannelPlugins } from "../channels/plugins/index.js";
import { formatCliCommand } from "../cli/command-format.js";
import { createDefaultDeps } from "../cli/deps.js";
import { isRestartEnabled } from "../config/commands.js";
import {
CONFIG_PATH,
isNixMode,
@@ -49,6 +50,10 @@ import { createAuthRateLimiter, type AuthRateLimiter } from "./auth-rate-limit.j
import { startChannelHealthMonitor } from "./channel-health-monitor.js";
import { startGatewayConfigReloader } from "./config-reload.js";
import type { ControlUiRootState } from "./control-ui.js";
import {
GATEWAY_EVENT_UPDATE_AVAILABLE,
type GatewayUpdateAvailableEventPayload,
} from "./events.js";
import { ExecApprovalManager } from "./exec-approval-manager.js";
import { NodeRegistry } from "./node-registry.js";
import type { startBrowserControlServerIfEnabled } from "./server-browser.js";
@@ -252,7 +257,7 @@ export async function startGatewayServer(
if (diagnosticsEnabled) {
startDiagnosticHeartbeat();
}
setGatewaySigusr1RestartPolicy({ allowExternal: cfgAtStart.commands?.restart === true });
setGatewaySigusr1RestartPolicy({ allowExternal: isRestartEnabled(cfgAtStart) });
setPreRestartDeferralCheck(
() => getTotalQueueSize() + getTotalPendingReplies() + getActiveEmbeddedRunCount(),
);
@@ -628,7 +633,15 @@ export async function startGatewayServer(
isNixMode,
});
if (!minimalTestGateway) {
scheduleGatewayUpdateCheck({ cfg: cfgAtStart, log, isNixMode });
scheduleGatewayUpdateCheck({
cfg: cfgAtStart,
log,
isNixMode,
onUpdateAvailableChange: (updateAvailable) => {
const payload: GatewayUpdateAvailableEventPayload = { updateAvailable };
broadcast(GATEWAY_EVENT_UPDATE_AVAILABLE, payload, { dropIfSlow: true });
},
});
}
const tailscaleCleanup = minimalTestGateway
? null

View File

@@ -49,6 +49,8 @@ describe("update-startup", () => {
let checkUpdateStatus: (typeof import("./update-check.js"))["checkUpdateStatus"];
let resolveNpmChannelTag: (typeof import("./update-check.js"))["resolveNpmChannelTag"];
let runGatewayUpdateCheck: (typeof import("./update-startup.js"))["runGatewayUpdateCheck"];
let getUpdateAvailable: (typeof import("./update-startup.js"))["getUpdateAvailable"];
let resetUpdateAvailableStateForTest: (typeof import("./update-startup.js"))["resetUpdateAvailableStateForTest"];
let loaded = false;
beforeAll(async () => {
@@ -77,9 +79,14 @@ describe("update-startup", () => {
if (!loaded) {
({ resolveOpenClawPackageRoot } = await import("./openclaw-root.js"));
({ checkUpdateStatus, resolveNpmChannelTag } = await import("./update-check.js"));
({ runGatewayUpdateCheck } = await import("./update-startup.js"));
({ runGatewayUpdateCheck, getUpdateAvailable, resetUpdateAvailableStateForTest } =
await import("./update-startup.js"));
loaded = true;
}
vi.mocked(resolveOpenClawPackageRoot).mockReset();
vi.mocked(checkUpdateStatus).mockReset();
vi.mocked(resolveNpmChannelTag).mockReset();
resetUpdateAvailableStateForTest();
});
afterEach(async () => {
@@ -99,6 +106,7 @@ describe("update-startup", () => {
} else {
delete process.env.VITEST;
}
resetUpdateAvailableStateForTest();
});
afterAll(async () => {
@@ -133,6 +141,8 @@ describe("update-startup", () => {
const parsed = JSON.parse(await fs.readFile(statePath, "utf-8")) as {
lastNotifiedVersion?: string;
lastNotifiedTag?: string;
lastAvailableVersion?: string;
lastAvailableTag?: string;
};
return { log, parsed };
}
@@ -144,6 +154,7 @@ describe("update-startup", () => {
expect.stringContaining("update available (latest): v2.0.0"),
);
expect(parsed.lastNotifiedVersion).toBe("2.0.0");
expect(parsed.lastAvailableVersion).toBe("2.0.0");
});
it("uses latest when beta tag is older than release", async () => {
@@ -155,6 +166,87 @@ describe("update-startup", () => {
expect(parsed.lastNotifiedTag).toBe("latest");
});
it("hydrates cached update from persisted state during throttle window", async () => {
const statePath = path.join(tempDir, "update-check.json");
await fs.writeFile(
statePath,
JSON.stringify(
{
lastCheckedAt: new Date(Date.now()).toISOString(),
lastAvailableVersion: "2.0.0",
lastAvailableTag: "latest",
},
null,
2,
),
"utf-8",
);
const onUpdateAvailableChange = vi.fn();
await runGatewayUpdateCheck({
cfg: { update: { channel: "stable" } },
log: { info: vi.fn() },
isNixMode: false,
allowInTests: true,
onUpdateAvailableChange,
});
expect(vi.mocked(checkUpdateStatus)).not.toHaveBeenCalled();
expect(onUpdateAvailableChange).toHaveBeenCalledWith({
currentVersion: "1.0.0",
latestVersion: "2.0.0",
channel: "latest",
});
expect(getUpdateAvailable()).toEqual({
currentVersion: "1.0.0",
latestVersion: "2.0.0",
channel: "latest",
});
});
it("emits update change callback when update state clears", async () => {
vi.mocked(resolveOpenClawPackageRoot).mockResolvedValue("/opt/openclaw");
vi.mocked(checkUpdateStatus).mockResolvedValue({
root: "/opt/openclaw",
installKind: "package",
packageManager: "npm",
} satisfies UpdateCheckResult);
vi.mocked(resolveNpmChannelTag)
.mockResolvedValueOnce({
tag: "latest",
version: "2.0.0",
})
.mockResolvedValueOnce({
tag: "latest",
version: "1.0.0",
});
const onUpdateAvailableChange = vi.fn();
await runGatewayUpdateCheck({
cfg: { update: { channel: "stable" } },
log: { info: vi.fn() },
isNixMode: false,
allowInTests: true,
onUpdateAvailableChange,
});
vi.setSystemTime(new Date("2026-01-18T11:00:00Z"));
await runGatewayUpdateCheck({
cfg: { update: { channel: "stable" } },
log: { info: vi.fn() },
isNixMode: false,
allowInTests: true,
onUpdateAvailableChange,
});
expect(onUpdateAvailableChange).toHaveBeenNthCalledWith(1, {
currentVersion: "1.0.0",
latestVersion: "2.0.0",
channel: "latest",
});
expect(onUpdateAvailableChange).toHaveBeenNthCalledWith(2, null);
expect(getUpdateAvailable()).toBeNull();
});
it("skips update check when disabled in config", async () => {
const log = { info: vi.fn() };

View File

@@ -12,9 +12,11 @@ type UpdateCheckState = {
lastCheckedAt?: string;
lastNotifiedVersion?: string;
lastNotifiedTag?: string;
lastAvailableVersion?: string;
lastAvailableTag?: string;
};
type UpdateAvailable = {
export type UpdateAvailable = {
currentVersion: string;
latestVersion: string;
channel: string;
@@ -26,6 +28,10 @@ export function getUpdateAvailable(): UpdateAvailable | null {
return updateAvailableCache;
}
export function resetUpdateAvailableStateForTest(): void {
updateAvailableCache = null;
}
const UPDATE_CHECK_FILENAME = "update-check.json";
const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
@@ -54,11 +60,54 @@ async function writeState(statePath: string, state: UpdateCheckState): Promise<v
await fs.writeFile(statePath, JSON.stringify(state, null, 2), "utf-8");
}
function sameUpdateAvailable(a: UpdateAvailable | null, b: UpdateAvailable | null): boolean {
if (a === b) {
return true;
}
if (!a || !b) {
return false;
}
return (
a.currentVersion === b.currentVersion &&
a.latestVersion === b.latestVersion &&
a.channel === b.channel
);
}
function setUpdateAvailableCache(params: {
next: UpdateAvailable | null;
onUpdateAvailableChange?: (updateAvailable: UpdateAvailable | null) => void;
}): void {
if (sameUpdateAvailable(updateAvailableCache, params.next)) {
return;
}
updateAvailableCache = params.next;
params.onUpdateAvailableChange?.(params.next);
}
function resolvePersistedUpdateAvailable(state: UpdateCheckState): UpdateAvailable | null {
const latestVersion = state.lastAvailableVersion?.trim();
if (!latestVersion) {
return null;
}
const cmp = compareSemverStrings(VERSION, latestVersion);
if (cmp == null || cmp >= 0) {
return null;
}
const channel = state.lastAvailableTag?.trim() || DEFAULT_PACKAGE_CHANNEL;
return {
currentVersion: VERSION,
latestVersion,
channel,
};
}
export async function runGatewayUpdateCheck(params: {
cfg: ReturnType<typeof loadConfig>;
log: { info: (msg: string, meta?: Record<string, unknown>) => void };
isNixMode: boolean;
allowInTests?: boolean;
onUpdateAvailableChange?: (updateAvailable: UpdateAvailable | null) => void;
}): Promise<void> {
if (shouldSkipCheck(Boolean(params.allowInTests))) {
return;
@@ -74,6 +123,11 @@ export async function runGatewayUpdateCheck(params: {
const state = await readState(statePath);
const now = Date.now();
const lastCheckedAt = state.lastCheckedAt ? Date.parse(state.lastCheckedAt) : null;
const persistedAvailable = resolvePersistedUpdateAvailable(state);
setUpdateAvailableCache({
next: persistedAvailable,
onUpdateAvailableChange: params.onUpdateAvailableChange,
});
if (lastCheckedAt && Number.isFinite(lastCheckedAt)) {
if (now - lastCheckedAt < UPDATE_CHECK_INTERVAL_MS) {
return;
@@ -98,6 +152,12 @@ export async function runGatewayUpdateCheck(params: {
};
if (status.installKind !== "package") {
delete nextState.lastAvailableVersion;
delete nextState.lastAvailableTag;
setUpdateAvailableCache({
next: null,
onUpdateAvailableChange: params.onUpdateAvailableChange,
});
await writeState(statePath, nextState);
return;
}
@@ -112,11 +172,17 @@ export async function runGatewayUpdateCheck(params: {
const cmp = compareSemverStrings(VERSION, resolved.version);
if (cmp != null && cmp < 0) {
updateAvailableCache = {
const nextAvailable: UpdateAvailable = {
currentVersion: VERSION,
latestVersion: resolved.version,
channel: tag,
};
setUpdateAvailableCache({
next: nextAvailable,
onUpdateAvailableChange: params.onUpdateAvailableChange,
});
nextState.lastAvailableVersion = resolved.version;
nextState.lastAvailableTag = tag;
const shouldNotify =
state.lastNotifiedVersion !== resolved.version || state.lastNotifiedTag !== tag;
if (shouldNotify) {
@@ -126,6 +192,13 @@ export async function runGatewayUpdateCheck(params: {
nextState.lastNotifiedVersion = resolved.version;
nextState.lastNotifiedTag = tag;
}
} else {
delete nextState.lastAvailableVersion;
delete nextState.lastAvailableTag;
setUpdateAvailableCache({
next: null,
onUpdateAvailableChange: params.onUpdateAvailableChange,
});
}
await writeState(statePath, nextState);
@@ -135,6 +208,7 @@ export function scheduleGatewayUpdateCheck(params: {
cfg: ReturnType<typeof loadConfig>;
log: { info: (msg: string, meta?: Record<string, unknown>) => void };
isNixMode: boolean;
onUpdateAvailableChange?: (updateAvailable: UpdateAvailable | null) => void;
}): void {
void runGatewayUpdateCheck(params).catch(() => {});
}

View File

@@ -220,7 +220,7 @@ async function main() {
const authorized = consumeGatewaySigusr1RestartAuthorization();
if (!authorized && !isGatewaySigusr1RestartExternallyAllowed()) {
defaultRuntime.log(
"gateway: SIGUSR1 restart ignored (not authorized; enable commands.restart or use gateway tool).",
"gateway: SIGUSR1 restart ignored (not authorized; commands.restart=false or use gateway tool).",
);
return;
}