Skip to content

Commit b1776b9

Browse files
committed
refactor(gateway): reduce repeated control-plane work
1 parent 8e2b93e commit b1776b9

22 files changed

Lines changed: 364 additions & 281 deletions

‎src/agents/agent-project-settings-snapshot.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,6 @@ function sanitizeAgentSettingsSnapshot(settings: AgentSettingsSnapshot): AgentSe
4242
return sanitized;
4343
}
4444

45-
function sanitizeProjectSettings(settings: AgentSettingsSnapshot): AgentSettingsSnapshot {
46-
return sanitizeAgentSettingsSnapshot(settings);
47-
}
48-
4945
function loadBundleSettingsFile(params: {
5046
rootDir: string;
5147
relativePath: string;
@@ -166,7 +162,7 @@ export function buildEmbeddedAgentSettingsSnapshot(params: {
166162
params.policy === "ignore"
167163
? {}
168164
: params.policy === "sanitize"
169-
? sanitizeProjectSettings(params.projectSettings)
165+
? sanitizeAgentSettingsSnapshot(params.projectSettings)
170166
: params.projectSettings;
171167
const withPluginSettings = applyMergePatch(
172168
params.globalSettings,

‎src/agents/agent-project-settings.test.ts‎

Lines changed: 66 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -142,45 +142,70 @@ describe("buildEmbeddedAgentSettingsSnapshot", () => {
142142
});
143143

144144
describe("createPreparedEmbeddedAgentSettingsManager", () => {
145-
it("keeps trusted file-backed settings runtime-scoped after preparation", async () => {
146-
const baseDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-agent-settings-"));
147-
try {
148-
const cwd = path.join(baseDir, "workspace");
149-
const agentDir = path.join(baseDir, "agent");
150-
const projectSettingsDir = path.join(cwd, ".openclaw");
151-
const agentSettingsPath = path.join(agentDir, "settings.json");
152-
await fs.mkdir(projectSettingsDir, { recursive: true });
153-
await fs.mkdir(agentDir, { recursive: true });
154-
await fs.writeFile(
155-
agentSettingsPath,
156-
JSON.stringify({ retry: { enabled: true } }, null, 2),
157-
"utf8",
158-
);
159-
await fs.writeFile(
160-
path.join(projectSettingsDir, "settings.json"),
161-
JSON.stringify({ shellCommandPrefix: "echo trusted &&" }, null, 2),
162-
"utf8",
163-
);
164-
165-
const settingsManager = createPreparedEmbeddedAgentSettingsManager({
166-
cwd,
167-
agentDir,
168-
cfg: {
169-
agents: { defaults: { embeddedAgent: { projectSettingsPolicy: "trusted" } } },
170-
},
171-
});
172-
173-
expect(settingsManager.getShellCommandPrefix()).toBe("echo trusted &&");
174-
expect(settingsManager.getRetryEnabled()).toBe(false);
175-
176-
await settingsManager.flush();
177-
178-
const diskSettings = JSON.parse(await fs.readFile(agentSettingsPath, "utf8")) as {
179-
retry?: { enabled?: boolean };
180-
};
181-
expect(diskSettings.retry?.enabled).toBe(true);
182-
} finally {
183-
await fs.rm(baseDir, { recursive: true, force: true });
184-
}
185-
});
145+
it.each([
146+
{ policy: "trusted", shellCommandPrefix: "echo trusted &&", reserveTokens: 32_000 },
147+
{ policy: "sanitize", shellCommandPrefix: "echo global &&", reserveTokens: 32_000 },
148+
{ policy: "ignore", shellCommandPrefix: "echo global &&", reserveTokens: 22_000 },
149+
] as const)(
150+
"keeps $policy file-backed settings runtime-scoped after preparation",
151+
async (testCase) => {
152+
const baseDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-agent-settings-"));
153+
try {
154+
const cwd = path.join(baseDir, "workspace");
155+
const agentDir = path.join(baseDir, "agent");
156+
const projectSettingsDir = path.join(cwd, ".openclaw");
157+
const agentSettingsPath = path.join(agentDir, "settings.json");
158+
await fs.mkdir(projectSettingsDir, { recursive: true });
159+
await fs.mkdir(agentDir, { recursive: true });
160+
const globalSettings = {
161+
retry: { enabled: true },
162+
shellCommandPrefix: "echo global &&",
163+
compaction: { reserveTokens: 22_000, keepRecentTokens: 23_000 },
164+
};
165+
await fs.writeFile(agentSettingsPath, JSON.stringify(globalSettings, null, 2), "utf8");
166+
await fs.writeFile(
167+
path.join(projectSettingsDir, "settings.json"),
168+
JSON.stringify({
169+
shellCommandPrefix: "echo trusted &&",
170+
compaction: { reserveTokens: 32_000 },
171+
}),
172+
"utf8",
173+
);
174+
175+
const params = {
176+
cwd,
177+
agentDir,
178+
cfg: {
179+
agents: { defaults: { embeddedAgent: { projectSettingsPolicy: testCase.policy } } },
180+
},
181+
};
182+
const settingsManager = createPreparedEmbeddedAgentSettingsManager(params);
183+
184+
expect(settingsManager.getShellCommandPrefix()).toBe(testCase.shellCommandPrefix);
185+
expect(settingsManager.getCompactionReserveTokens()).toBe(testCase.reserveTokens);
186+
expect(settingsManager.getCompactionKeepRecentTokens()).toBe(23_000);
187+
expect(settingsManager.getRetryEnabled()).toBe(false);
188+
189+
await settingsManager.flush();
190+
191+
expect(JSON.parse(await fs.readFile(agentSettingsPath, "utf8"))).toEqual(globalSettings);
192+
193+
await fs.writeFile(
194+
agentSettingsPath,
195+
JSON.stringify({
196+
...globalSettings,
197+
compaction: { ...globalSettings.compaction, keepRecentTokens: 45_000 },
198+
}),
199+
);
200+
await settingsManager.reload();
201+
expect(settingsManager.getCompactionKeepRecentTokens()).toBe(23_000);
202+
expect(settingsManager.getRetryEnabled()).toBe(false);
203+
const nextSettingsManager = createPreparedEmbeddedAgentSettingsManager(params);
204+
expect(nextSettingsManager.getCompactionKeepRecentTokens()).toBe(45_000);
205+
await nextSettingsManager.flush();
206+
} finally {
207+
await fs.rm(baseDir, { recursive: true, force: true });
208+
}
209+
},
210+
);
186211
});

‎src/agents/agent-project-settings.ts‎

Lines changed: 9 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -9,45 +9,6 @@ import {
99
import { applyAgentCompactionSettingsFromConfig } from "./agent-settings.js";
1010
import { SettingsManager } from "./sessions/index.js";
1111

12-
function createEmbeddedAgentSettingsManager(params: {
13-
cwd: string;
14-
agentDir: string;
15-
cfg?: OpenClawConfig;
16-
pluginMetadataSnapshot?: PluginMetadataSnapshot;
17-
}): SettingsManager {
18-
const fileSettingsManager = SettingsManager.create(params.cwd, params.agentDir);
19-
const policy = resolveEmbeddedAgentProjectSettingsPolicy(params.cfg);
20-
const pluginSettings = loadEnabledBundleAgentSettingsSnapshot({
21-
cwd: params.cwd,
22-
cfg: params.cfg,
23-
pluginMetadataSnapshot: params.pluginMetadataSnapshot,
24-
});
25-
const hasPluginSettings = Object.keys(pluginSettings).length > 0;
26-
if (policy === "trusted" && !hasPluginSettings) {
27-
return fileSettingsManager;
28-
}
29-
const settings = buildEmbeddedAgentSettingsSnapshot({
30-
globalSettings: fileSettingsManager.getGlobalSettings(),
31-
pluginSettings,
32-
projectSettings: fileSettingsManager.getProjectSettings(),
33-
policy,
34-
});
35-
return SettingsManager.inMemory(settings);
36-
}
37-
38-
function createRuntimeEmbeddedAgentSettingsManager(
39-
settingsManager: SettingsManager,
40-
): SettingsManager {
41-
return SettingsManager.inMemory(
42-
buildEmbeddedAgentSettingsSnapshot({
43-
globalSettings: settingsManager.getGlobalSettings(),
44-
pluginSettings: {},
45-
projectSettings: settingsManager.getProjectSettings(),
46-
policy: "trusted",
47-
}),
48-
);
49-
}
50-
5112
/** Creates the runtime SettingsManager with project/plugin settings and compaction overrides. */
5213
export function createPreparedEmbeddedAgentSettingsManager(params: {
5314
cwd: string;
@@ -57,8 +18,15 @@ export function createPreparedEmbeddedAgentSettingsManager(params: {
5718
/** Resolved context window budget so reserve-token floor can be capped for small models. */
5819
contextTokenBudget?: number;
5920
}): SettingsManager {
60-
const settingsManager = createRuntimeEmbeddedAgentSettingsManager(
61-
createEmbeddedAgentSettingsManager(params),
21+
const fileSettingsManager = SettingsManager.create(params.cwd, params.agentDir);
22+
// Lock-backed reads stay authoritative; runtime writes and reloads use only this snapshot.
23+
const settingsManager = SettingsManager.inMemory(
24+
buildEmbeddedAgentSettingsSnapshot({
25+
globalSettings: fileSettingsManager.getGlobalSettings(),
26+
pluginSettings: loadEnabledBundleAgentSettingsSnapshot(params),
27+
projectSettings: fileSettingsManager.getProjectSettings(),
28+
policy: resolveEmbeddedAgentProjectSettingsPolicy(params.cfg),
29+
}),
6230
);
6331
applyAgentCompactionSettingsFromConfig({
6432
settingsManager,

‎src/gateway/assistant-identity.test.ts‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import fs from "node:fs/promises";
55
import path from "node:path";
66
import { describe, expect, it } from "vitest";
77
import type { OpenClawConfig } from "../config/config.js";
8+
import { retainLegacyDefaultAgentId } from "../config/legacy.default-agent-owner.js";
89
import { AVATAR_MAX_DATA_URL_CHARS } from "../shared/avatar-limits.js";
910
import { AVATAR_MAX_BYTES } from "../shared/avatar-policy.js";
1011
import { withTestDir } from "../test-helpers/temp-dir.js";
@@ -28,15 +29,49 @@ describe("resolveAssistantIdentity", () => {
2829
expect(identity.avatar).toBe("W");
2930
});
3031

31-
it("uses the first roster entry for presentation on an explicit fleet", () => {
32-
const identity = resolveAssistantIdentity({
32+
it.each<{
33+
name: string;
34+
cfg: OpenClawConfig;
35+
agentId?: string;
36+
expected: string;
37+
}>([
38+
{ name: "implicit main", cfg: {}, expected: "main" },
39+
{ name: "sole agent", cfg: { agents: { entries: { research: {} } } }, expected: "research" },
40+
{
41+
name: "first explicit roster entry, not the ambient system owner",
42+
cfg: {
43+
agents: {
44+
ownership: "explicit",
45+
entries: { ops: {}, research: {} },
46+
defaults: { systemAgent: { agentId: "research" } },
47+
},
48+
},
49+
expected: "ops",
50+
},
51+
{
52+
name: "retained legacy owner",
53+
cfg: retainLegacyDefaultAgentId(
54+
{ agents: { ownership: "explicit", entries: { ops: {}, research: {} } } },
55+
"research",
56+
),
57+
expected: "research",
58+
},
59+
{
60+
name: "normalized explicit selection",
3361
cfg: { agents: { ownership: "explicit", entries: { ops: {}, research: {} } } },
62+
agentId: "RESEARCH",
63+
expected: "research",
64+
},
65+
])("uses $name for presentation", ({ cfg, agentId, expected }) => {
66+
const identity = resolveAssistantIdentity({
67+
cfg,
68+
agentId,
3469
workspaceDir: "",
3570
});
3671

3772
expect(identity).toEqual({
3873
...DEFAULT_ASSISTANT_IDENTITY,
39-
agentId: "ops",
74+
agentId: expected,
4075
nameSource: "default",
4176
});
4277
});

‎src/gateway/assistant-identity.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,16 +101,20 @@ function normalizeEmojiValue(value: string | undefined): string | undefined {
101101
return value;
102102
}
103103

104+
// Presentation may choose the first roster entry even when ambient work needs an explicit owner.
105+
export function resolveAssistantAgentId(cfg: OpenClawConfig, agentId?: string | null): string {
106+
return normalizeAgentId(
107+
agentId ?? tryResolveLegacyCompatibilityAgentId(cfg) ?? listAgentEntries(cfg)[0]?.id ?? "main",
108+
);
109+
}
110+
104111
/** Resolve the display name/avatar/emoji for an agent-facing assistant identity. */
105112
export function resolveAssistantIdentity(params: {
106113
cfg: OpenClawConfig;
107114
agentId?: string | null;
108115
workspaceDir?: string | null;
109116
}): ResolvedAssistantIdentity {
110-
const compatibilityAgentId = tryResolveLegacyCompatibilityAgentId(params.cfg);
111-
const presentationAgentId =
112-
params.agentId ?? compatibilityAgentId ?? listAgentEntries(params.cfg)[0]?.id ?? "main";
113-
const agentId = normalizeAgentId(presentationAgentId);
117+
const agentId = resolveAssistantAgentId(params.cfg, params.agentId);
114118
const workspaceDir = params.workspaceDir ?? resolveAgentWorkspaceDir(params.cfg, agentId);
115119
const agentIdentity = resolveAgentIdentity(params.cfg, agentId);
116120
const fileIdentity = workspaceDir ? loadAgentIdentity(workspaceDir) : null;

‎src/gateway/control-ui-static.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,13 @@ function openFile(body: string) {
2020
const filePath = path.join(tempDirs.make("openclaw-ui-read-"), "asset.txt");
2121
fs.writeFileSync(filePath, body);
2222
const fd = fs.openSync(filePath, "r");
23+
vi.spyOn(fs, "closeSync");
2324
return { filePath, fd, size: fs.fstatSync(fd).size };
2425
}
2526

2627
function expectClosed(fd: number) {
27-
expect(() => fs.fstatSync(fd)).toThrow(expect.objectContaining({ code: "EBADF" }));
28+
// Observe release itself: after awaiting the read, another worker may reuse the fd number.
29+
expect(fs.closeSync).toHaveBeenCalledWith(fd);
2830
}
2931

3032
describe("pinned Control UI file reads", () => {

‎src/gateway/control-ui.ts‎

Lines changed: 19 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1025,34 +1025,7 @@ export async function handleControlUiHttpRequest(
10251025
safeFile = resolveSafeControlUiFile(retained.rootRealPath, retained.filePath, true);
10261026
}
10271027
}
1028-
if (safeFile) {
1029-
if (path.basename(safeFile.path) === "index.html") {
1030-
if (req.method === "HEAD") {
1031-
try {
1032-
const encoding = resolveControlUiHtmlEncoding(req);
1033-
if (encoding === "not-acceptable") {
1034-
respondControlUiNotAcceptable(res);
1035-
return true;
1036-
}
1037-
respondHeadForControlUiFile(res, safeFile.path, {
1038-
encoding: encoding === "identity" ? undefined : encoding,
1039-
});
1040-
return true;
1041-
} finally {
1042-
fs.closeSync(safeFile.fd);
1043-
}
1044-
}
1045-
const body = (await readAndCloseControlUiFile(safeFile)).toString("utf8");
1046-
await serveResolvedIndexHtml(
1047-
req,
1048-
res,
1049-
body,
1050-
basePath,
1051-
terminalEnabled,
1052-
opts?.config?.gateway?.controlUi?.environment,
1053-
);
1054-
return true;
1055-
}
1028+
if (safeFile && path.basename(safeFile.path) !== "index.html") {
10561029
// Filesystem clocks may lead this host; validators cannot postdate message
10571030
// origination or a future date would 304 later replacements (mirrors
10581031
// resolveByteResponse in http-byte-range.ts).
@@ -1095,40 +1068,39 @@ export async function handleControlUiHttpRequest(
10951068
return true;
10961069
}
10971070

1098-
// If the requested path looks like a static asset (known extension), return
1099-
// 404 rather than falling through to the SPA index.html fallback. We check
1100-
// against the same extension set used by the static response helper so
1101-
// that dotted SPA routes (e.g. /user/jane.doe, /v2.0) still get the
1102-
// client-side router fallback.
1103-
if (isControlUiStaticAssetExtension(path.extname(fileRel).toLowerCase())) {
1104-
respondControlUiNotFound(res);
1105-
return true;
1106-
}
1107-
1108-
if (!route.spaFallback) {
1109-
return false;
1071+
if (!safeFile) {
1072+
// Missing assets stay 404; dotted routes can still use the SPA document.
1073+
if (isControlUiStaticAssetExtension(path.extname(fileRel).toLowerCase())) {
1074+
respondControlUiNotFound(res);
1075+
return true;
1076+
}
1077+
if (!route.spaFallback) {
1078+
return false;
1079+
}
1080+
const indexPath = path.resolve(root, "index.html");
1081+
if (filePath !== indexPath) {
1082+
safeFile = resolveSafeControlUiFile(rootReal, indexPath, rejectHardlinks);
1083+
}
11101084
}
11111085

1112-
// SPA fallback (client-side router): serve index.html for unknown paths.
1113-
const indexPath = path.join(root, "index.html");
1114-
const safeIndex = resolveSafeControlUiFile(rootReal, indexPath, rejectHardlinks);
1115-
if (safeIndex) {
1086+
// Direct documents and SPA fallbacks share rewriting, CSP, encoding and fd ownership.
1087+
if (safeFile) {
11161088
if (req.method === "HEAD") {
11171089
try {
11181090
const encoding = resolveControlUiHtmlEncoding(req);
11191091
if (encoding === "not-acceptable") {
11201092
respondControlUiNotAcceptable(res);
11211093
return true;
11221094
}
1123-
respondHeadForControlUiFile(res, safeIndex.path, {
1095+
respondHeadForControlUiFile(res, safeFile.path, {
11241096
encoding: encoding === "identity" ? undefined : encoding,
11251097
});
11261098
return true;
11271099
} finally {
1128-
fs.closeSync(safeIndex.fd);
1100+
fs.closeSync(safeFile.fd);
11291101
}
11301102
}
1131-
const body = (await readAndCloseControlUiFile(safeIndex)).toString("utf8");
1103+
const body = (await readAndCloseControlUiFile(safeFile)).toString("utf8");
11321104
await serveResolvedIndexHtml(
11331105
req,
11341106
res,

0 commit comments

Comments
 (0)