Skip to content

Commit 2e5be0c

Browse files
PerfectPansteipete
andauthored
fix(gateway): pin relative state dir at startup
* fix(gateway): normalize explicit state dir overrides at startup * test(gateway): simplify state-dir startup coverage * test: fix state dir startup coverage --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent b47bace commit 2e5be0c

6 files changed

Lines changed: 59 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ Docs: https://docs.openclaw.ai
5454

5555
### Fixes
5656

57+
- Gateway/config: pin relative `OPENCLAW_STATE_DIR` overrides to an absolute path at startup so later working-directory changes cannot retarget gateway state. (#52264) Thanks @PerfectPan.
5758
- Release/package: run npm release, prepublish, and postpublish verification through Windows-safe npm command shims so native Windows checks can execute `npm.cmd` instead of treating it as a binary.
5859
- Agents/harness: pass CLI runtime aliases through harness selection so provider-owned CLI aliases no longer get rejected before reaching the right runtime. (#85631) Thanks @potterdigital.
5960
- Secrets: show the irreversible apply warning after interactive `secrets configure` confirmation so confirmed migrations still get the final safety prompt. (#85638) Thanks @alkor2000.

‎src/cli/gateway-cli/run.option-collisions.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ type GatewayLoopStart = (params?: { startupStartedAt?: number }) => Promise<unkn
2525
const runGatewayLoop = vi.fn(async ({ start }: { start: GatewayLoopStart }) => {
2626
await start();
2727
});
28+
const normalizeStateDirEnv = vi.fn((_env?: NodeJS.ProcessEnv) => undefined);
29+
const callOrder = vi.hoisted(() => [] as string[]);
2830
const gatewayLogMessages = vi.hoisted(() => [] as string[]);
2931
const configState = vi.hoisted(() => ({
3032
cfg: {} as Record<string, unknown>,
@@ -65,6 +67,7 @@ vi.mock("../../config/config.js", () => ({
6567

6668
vi.mock("../../config/paths.js", () => ({
6769
CONFIG_PATH: "/tmp/openclaw-test-missing-config.json",
70+
normalizeStateDirEnv: (env?: NodeJS.ProcessEnv) => normalizeStateDirEnv(env),
6871
resolveStateDir: () => "/tmp",
6972
resolveGatewayPort: (cfg?: { gateway?: { port?: number } }) => cfg?.gateway?.port ?? 18789,
7073
}));
@@ -236,6 +239,8 @@ describe("gateway run option collisions", () => {
236239
waitForPortBindable.mockClear();
237240
ensureDevGatewayConfig.mockClear();
238241
runGatewayLoop.mockClear();
242+
normalizeStateDirEnv.mockReset();
243+
callOrder.length = 0;
239244
});
240245

241246
async function runGatewayCli(argv: string[]) {
@@ -265,6 +270,14 @@ describe("gateway run option collisions", () => {
265270
}
266271

267272
it("forwards parent-captured options to `gateway run` subcommand", async () => {
273+
normalizeStateDirEnv.mockImplementation((_env?: NodeJS.ProcessEnv) => {
274+
callOrder.push("normalize");
275+
});
276+
startGatewayServer.mockImplementationOnce(async (_port: number, _opts?: unknown) => {
277+
callOrder.push("start");
278+
return { close: vi.fn(async () => {}) };
279+
});
280+
268281
await runGatewayCli([
269282
"gateway",
270283
"run",
@@ -283,6 +296,8 @@ describe("gateway run option collisions", () => {
283296
).toEqual({ intervalMs: 150, timeoutMs: 3000 });
284297
expect(setGatewayWsLogStyle).toHaveBeenCalledWith("full");
285298
expect(gatewayStartOptions().auth?.token).toBe("tok_run");
299+
expect(normalizeStateDirEnv).toHaveBeenCalledWith(process.env);
300+
expect(callOrder).toEqual(["normalize", "start"]);
286301
});
287302

288303
it("marks service-mode gateway descendants with the live gateway pid", async () => {
@@ -297,6 +312,7 @@ describe("gateway run option collisions", () => {
297312
expect(process.env[GATEWAY_SERVICE_RUNTIME_PID_ENV]).toBe(String(process.pid));
298313
},
299314
);
315+
expect(normalizeStateDirEnv).toHaveBeenCalledWith(process.env);
300316
});
301317

302318
it("blocks --force port cleanup from an older binary with newer config", async () => {

‎src/cli/gateway-cli/run.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@ import type {
99
GatewayTailscaleMode,
1010
ReadConfigFileSnapshotWithPluginMetadataResult,
1111
} from "../../config/config.js";
12-
import { CONFIG_PATH, resolveGatewayPort, resolveStateDir } from "../../config/paths.js";
12+
import {
13+
CONFIG_PATH,
14+
normalizeStateDirEnv,
15+
resolveGatewayPort,
16+
resolveStateDir,
17+
} from "../../config/paths.js";
1318
import type { OpenClawConfig } from "../../config/types.openclaw.js";
1419
import { hasConfiguredSecretInput } from "../../config/types.secrets.js";
1520
import { GATEWAY_SERVICE_RUNTIME_PID_ENV } from "../../daemon/constants.js";
@@ -465,6 +470,7 @@ async function maybeWriteGatewayStartupFailureBundle(err: unknown): Promise<void
465470
}
466471

467472
export async function runGatewayCommand(opts: GatewayRunOpts) {
473+
normalizeStateDirEnv(process.env);
468474
installQaParentWatchdog();
469475
if (process.env.OPENCLAW_SERVICE_MARKER?.trim()) {
470476
process.env[GATEWAY_SERVICE_RUNTIME_PID_ENV] = String(process.pid);

‎src/config/paths.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest";
44
import { withTempDir } from "../test-helpers/temp-dir.js";
55
import {
66
DEFAULT_GATEWAY_PORT,
7+
normalizeStateDirEnv,
78
resolveDefaultConfigCandidates,
89
resolveConfigPathCandidate,
910
resolveConfigPath,
@@ -123,6 +124,30 @@ describe("state + config path candidates", () => {
123124
expect(resolveStateDir(env, () => "/home/test")).toBe(path.resolve("/new/state"));
124125
});
125126

127+
it("normalizes relative OPENCLAW_STATE_DIR overrides to absolute paths", () => {
128+
const env = {
129+
OPENCLAW_STATE_DIR: ".",
130+
OPENCLAW_HOME: "/srv/openclaw-home",
131+
} as NodeJS.ProcessEnv;
132+
133+
normalizeStateDirEnv(env);
134+
135+
expect(env.OPENCLAW_STATE_DIR).toBe(path.resolve("."));
136+
});
137+
138+
it("pins a relative state-dir override before later resolution", () => {
139+
const env = {
140+
OPENCLAW_STATE_DIR: "relative-state",
141+
OPENCLAW_HOME: "/srv/openclaw-home",
142+
} as NodeJS.ProcessEnv;
143+
144+
normalizeStateDirEnv(env);
145+
const normalized = env.OPENCLAW_STATE_DIR;
146+
147+
expect(normalized).toBe(path.resolve("relative-state"));
148+
expect(resolveStateDir(env, () => "/srv/other-home")).toBe(normalized);
149+
});
150+
126151
it("uses OPENCLAW_HOME for default state/config locations", () => {
127152
const env = {
128153
OPENCLAW_HOME: "/srv/openclaw-home",

‎src/config/paths.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,14 @@ export function resolveStateDir(
8888
return newDir;
8989
}
9090

91+
export function normalizeStateDirEnv(env: NodeJS.ProcessEnv = process.env): void {
92+
const effectiveHomedir = () => resolveRequiredHomeDir(env, envHomedir(env));
93+
const openclawOverride = env.OPENCLAW_STATE_DIR?.trim();
94+
if (openclawOverride) {
95+
env.OPENCLAW_STATE_DIR = resolveUserPath(openclawOverride, env, effectiveHomedir);
96+
}
97+
}
98+
9199
function resolveUserPath(
92100
input: string,
93101
env: NodeJS.ProcessEnv = process.env,

‎src/gateway/server.impl.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
setRuntimeConfigSnapshot,
1818
type ReadConfigFileSnapshotWithPluginMetadataResult,
1919
} from "../config/io.js";
20-
import { isNixMode } from "../config/paths.js";
20+
import { isNixMode, normalizeStateDirEnv } from "../config/paths.js";
2121
import { applyPluginAutoEnable } from "../config/plugin-auto-enable.js";
2222
import { applyConfigOverrides } from "../config/runtime-overrides.js";
2323
import { resolveMainSessionKey } from "../config/sessions.js";
@@ -538,6 +538,7 @@ export async function startGatewayServer(
538538
port = 18789,
539539
opts: GatewayServerOptions = {},
540540
): Promise<GatewayServer> {
541+
normalizeStateDirEnv(process.env);
541542
const { bootstrapGatewayNetworkRuntime } = await import("./server-network-runtime.js");
542543
bootstrapGatewayNetworkRuntime();
543544

0 commit comments

Comments
 (0)