Skip to content

Commit 29f5a89

Browse files
committed
fix: preserve provider defaults during config saves
1 parent 841cb12 commit 29f5a89

2 files changed

Lines changed: 158 additions & 5 deletions

File tree

‎src/gateway/server-methods/config.ts‎

Lines changed: 95 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@ import {
55
readConfigFileSnapshot,
66
readConfigFileSnapshotForWrite,
77
resolveConfigSnapshotHash,
8+
validateConfigObjectRawWithPlugins,
89
validateConfigObjectWithPlugins,
910
} from "../../config/config.js";
11+
import { createMergePatch, projectSourceOntoRuntimeShape } from "../../config/io.write-prepare.js";
1012
import { formatConfigIssueLines } from "../../config/issue-format.js";
1113
import { applyMergePatch } from "../../config/merge-patch.js";
1214
import {
@@ -17,6 +19,7 @@ import {
1719
import { loadGatewayRuntimeConfigSchema } from "../../config/runtime-schema.js";
1820
import { lookupConfigSchema, type ConfigSchemaResponse } from "../../config/schema.js";
1921
import type { ConfigValidationIssue, OpenClawConfig } from "../../config/types.openclaw.js";
22+
import { isBuiltInModelProviderOverlayId } from "../../config/zod-schema.core.js";
2023
import { formatErrorMessage } from "../../infra/errors.js";
2124
import {
2225
prepareSecretsRuntimeSnapshot,
@@ -189,12 +192,70 @@ function formatConfigOpenError(error: unknown): string {
189192
return String(error);
190193
}
191194

195+
function isRecord(value: unknown): value is Record<string, unknown> {
196+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
197+
}
198+
199+
function hasOwnRecordValue(value: unknown, key: string): boolean {
200+
return isRecord(value) && Object.prototype.hasOwnProperty.call(value, key);
201+
}
202+
203+
function stripBundledProviderRuntimeDefaults(params: {
204+
candidate: unknown;
205+
sourceConfig: unknown;
206+
}): unknown {
207+
if (!isRecord(params.candidate)) {
208+
return params.candidate;
209+
}
210+
const models = params.candidate.models;
211+
if (!isRecord(models) || !isRecord(models.providers)) {
212+
return params.candidate;
213+
}
214+
const sourceModels = isRecord(params.sourceConfig) ? params.sourceConfig.models : undefined;
215+
const sourceProviders = isRecord(sourceModels) ? sourceModels.providers : undefined;
216+
217+
let nextProviders: Record<string, unknown> | undefined;
218+
for (const [providerId, provider] of Object.entries(models.providers)) {
219+
if (!isBuiltInModelProviderOverlayId(providerId) || !isRecord(provider)) {
220+
continue;
221+
}
222+
const sourceProvider = isRecord(sourceProviders) ? sourceProviders[providerId] : undefined;
223+
let nextProvider: Record<string, unknown> | undefined;
224+
if (provider.baseUrl === "" && !hasOwnRecordValue(sourceProvider, "baseUrl")) {
225+
nextProvider = { ...provider };
226+
delete nextProvider.baseUrl;
227+
}
228+
if (
229+
Array.isArray(provider.models) &&
230+
provider.models.length === 0 &&
231+
!hasOwnRecordValue(sourceProvider, "models")
232+
) {
233+
nextProvider ??= { ...provider };
234+
delete nextProvider.models;
235+
}
236+
if (nextProvider) {
237+
nextProviders ??= { ...models.providers };
238+
nextProviders[providerId] = nextProvider;
239+
}
240+
}
241+
if (!nextProviders) {
242+
return params.candidate;
243+
}
244+
return {
245+
...params.candidate,
246+
models: {
247+
...models,
248+
providers: nextProviders,
249+
},
250+
};
251+
}
252+
192253
function parseValidateConfigFromRawOrRespond(
193254
params: unknown,
194255
requestName: string,
195256
snapshot: Awaited<ReturnType<typeof readConfigFileSnapshot>>,
196257
respond: RespondFn,
197-
): { config: OpenClawConfig; schema: ConfigSchemaResponse } | null {
258+
): { config: OpenClawConfig; writeConfig: OpenClawConfig; schema: ConfigSchemaResponse } | null {
198259
const rawValue = parseRawConfigOrRespond(params, requestName, respond);
199260
if (!rawValue) {
200261
return null;
@@ -214,7 +275,32 @@ function parseValidateConfigFromRawOrRespond(
214275
);
215276
return null;
216277
}
217-
const validated = validateConfigObjectWithPlugins(restored.result);
278+
const projectedValidationCandidate = snapshot.valid
279+
? applyMergePatch(
280+
projectSourceOntoRuntimeShape(snapshot.resolved, snapshot.config),
281+
createMergePatch(snapshot.config, restored.result),
282+
)
283+
: restored.result;
284+
const validationCandidate = stripBundledProviderRuntimeDefaults({
285+
candidate: projectedValidationCandidate,
286+
sourceConfig: snapshot.parsed,
287+
});
288+
const sourceValidated = validateConfigObjectRawWithPlugins(validationCandidate);
289+
if (!sourceValidated.ok) {
290+
respond(
291+
false,
292+
undefined,
293+
errorShape(
294+
ErrorCodes.INVALID_REQUEST,
295+
summarizeConfigValidationIssues(sourceValidated.issues),
296+
{
297+
details: { issues: sourceValidated.issues },
298+
},
299+
),
300+
);
301+
return null;
302+
}
303+
const validated = validateConfigObjectWithPlugins(validationCandidate);
218304
if (!validated.ok) {
219305
respond(
220306
false,
@@ -225,7 +311,11 @@ function parseValidateConfigFromRawOrRespond(
225311
);
226312
return null;
227313
}
228-
return { config: validated.config, schema };
314+
return {
315+
config: validated.config,
316+
writeConfig: validationCandidate as OpenClawConfig,
317+
schema,
318+
};
229319
}
230320

231321
function summarizeConfigValidationIssues(issues: ReadonlyArray<ConfigValidationIssue>): string {
@@ -357,7 +447,7 @@ export const configHandlers: GatewayRequestHandlers = {
357447
const writeResult = await commitGatewayConfigWrite({
358448
snapshot,
359449
writeOptions,
360-
nextConfig: parsed.config,
450+
nextConfig: parsed.writeConfig,
361451
context,
362452
});
363453
clearConfigSchemaResponseCache();
@@ -573,7 +663,7 @@ export const configHandlers: GatewayRequestHandlers = {
573663
const writeResult = await commitGatewayConfigWrite({
574664
snapshot,
575665
writeOptions,
576-
nextConfig: parsed.config,
666+
nextConfig: parsed.writeConfig,
577667
context,
578668
disconnectSharedAuthClients,
579669
});

‎src/gateway/server.config-patch.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,69 @@ describe("gateway config methods", () => {
200200
requireConfigObject(res.payload?.config, "response config");
201201
});
202202

203+
it("accepts runtime-shaped config.set when bundled provider baseUrl was only defaulted", async () => {
204+
const { createConfigIO, resetConfigRuntimeState } = await import("../config/config.js");
205+
const configPath = createConfigIO().configPath;
206+
await fs.mkdir(path.dirname(configPath), { recursive: true });
207+
try {
208+
await fs.writeFile(
209+
configPath,
210+
`${JSON.stringify(
211+
{
212+
models: {
213+
providers: {
214+
openai: {
215+
agentRuntime: { id: "pi" },
216+
},
217+
},
218+
},
219+
},
220+
null,
221+
2,
222+
)}\n`,
223+
"utf-8",
224+
);
225+
resetConfigRuntimeState();
226+
227+
const current = await rpcReq<{
228+
hash?: string;
229+
config?: Record<string, unknown>;
230+
}>(requireWs(), "config.get", {});
231+
expect(current.ok).toBe(true);
232+
expect(typeof current.payload?.hash).toBe("string");
233+
const nextConfig = structuredClone(
234+
requireConfigObject(current.payload?.config, "current config"),
235+
);
236+
const providers = ((nextConfig.models as Record<string, unknown>).providers ?? {}) as Record<
237+
string,
238+
Record<string, unknown>
239+
>;
240+
providers.openai ??= {};
241+
providers.openai.baseUrl = "";
242+
providers.openai.models = [];
243+
244+
const gateway = (nextConfig.gateway ??= {}) as Record<string, unknown>;
245+
gateway.port = 19002;
246+
247+
const res = await rpcReq<{
248+
ok?: boolean;
249+
error?: { message?: string };
250+
}>(requireWs(), "config.set", {
251+
raw: JSON.stringify(nextConfig, null, 2),
252+
baseHash: current.payload?.hash,
253+
});
254+
255+
expect(res.error).toBeUndefined();
256+
expect(res.ok).toBe(true);
257+
const persisted = await fs.readFile(configPath, "utf-8");
258+
expect(persisted).toContain('"port": 19002');
259+
expect(persisted).not.toContain('"baseUrl"');
260+
} finally {
261+
await fs.rm(configPath, { force: true });
262+
resetConfigRuntimeState();
263+
}
264+
});
265+
203266
it("redacts browser cdpUrl credentials from config.get responses", async () => {
204267
const { createConfigIO, resetConfigRuntimeState } = await import("../config/config.js");
205268
const configPath = createConfigIO().configPath;

0 commit comments

Comments
 (0)