Skip to content

Commit 4d14f29

Browse files
authored
perf(cli): keep read-only commands on cold paths (#117932)
* perf(cli): keep read-only commands on cold paths * perf(channels): reuse list metadata snapshot
1 parent 3f9b451 commit 4d14f29

30 files changed

Lines changed: 550 additions & 242 deletions

‎src/channels/plugins/read-only.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
import type { PluginManifestRecord } from "../../plugins/manifest-registry.js";
2828
import { registerPluginMetadataProcessMemoLifecycleClear } from "../../plugins/plugin-metadata-lifecycle.js";
2929
import { resolvePluginMetadataSnapshot } from "../../plugins/plugin-metadata-snapshot.js";
30+
import type { PluginMetadataSnapshot } from "../../plugins/plugin-metadata-snapshot.types.js";
3031
import {
3132
getCachedPluginModuleLoader,
3233
type PluginModuleLoaderCache,
@@ -59,6 +60,7 @@ type ReadOnlyChannelPluginOptions = {
5960
activationSourceConfig?: OpenClawConfig;
6061
includePersistedAuthState?: boolean;
6162
includeSetupFallbackPlugins?: boolean;
63+
metadataSnapshot?: PluginMetadataSnapshot;
6264
};
6365

6466
type ReadOnlyChannelPluginResolution = {
@@ -717,13 +719,15 @@ export function resolveReadOnlyChannelPluginsForConfig(
717719
if (cached) {
718720
return cloneReadOnlyChannelPluginResolution(cached);
719721
}
720-
const manifestRecords = resolvePluginMetadataSnapshot({
721-
config: cfg,
722-
stateDir: options.stateDir,
723-
workspaceDir,
724-
env,
725-
allowWorkspaceScopedCurrent: true,
726-
}).plugins;
722+
const manifestRecords =
723+
options.metadataSnapshot?.plugins ??
724+
resolvePluginMetadataSnapshot({
725+
config: cfg,
726+
stateDir: options.stateDir,
727+
workspaceDir,
728+
env,
729+
allowWorkspaceScopedCurrent: true,
730+
}).plugins;
727731
const bundledManifestRecords = listBundledChannelManifestRecords(manifestRecords);
728732
const externalManifestRecords = listExternalChannelManifestRecords(manifestRecords);
729733
const activationSourceConfig = options.activationSourceConfig ?? cfg;
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// The real channels-list route must project manifest facts without executing setup modules.
2+
import fs from "node:fs";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import { afterAll, expect, it, vi } from "vitest";
6+
import type { OpenClawConfig } from "../config/types.openclaw.js";
7+
import {
8+
createColdPluginFixture,
9+
isColdPluginRuntimeLoaded,
10+
} from "../plugins/test-helpers/cold-plugin-fixtures.js";
11+
12+
const testState = vi.hoisted(() => ({
13+
config: {} as OpenClawConfig,
14+
json: [] as unknown[],
15+
}));
16+
17+
vi.mock("./command-execution-startup.js", () => ({
18+
applyCliExecutionStartupPresentation: vi.fn(async () => {}),
19+
ensureCliExecutionBootstrap: vi.fn(async () => {}),
20+
resolveCliExecutionStartupContext: vi.fn(() => ({
21+
startupPolicy: { loadPlugins: false, suppressDoctorStdout: true },
22+
})),
23+
}));
24+
25+
vi.mock("../commands/channels/shared.js", () => ({
26+
formatChannelAccountLabel: vi.fn(),
27+
requireValidConfig: vi.fn(async () => testState.config),
28+
}));
29+
30+
vi.mock("../commands/channel-setup/trusted-catalog.js", () => ({
31+
listTrustedChannelPluginCatalogEntries: vi.fn(() => []),
32+
}));
33+
34+
vi.mock("../agents/agent-scope.js", () => ({
35+
resolveAgentWorkspaceDir: vi.fn(() => undefined),
36+
resolveDefaultAgentId: vi.fn(() => "main"),
37+
}));
38+
39+
vi.mock("../runtime.js", () => ({
40+
defaultRuntime: {
41+
error: vi.fn(),
42+
exit: vi.fn(),
43+
log: vi.fn(),
44+
writeJson: (value: unknown) => testState.json.push(value),
45+
writeStdout: vi.fn(),
46+
},
47+
writeRuntimeJson: vi.fn((runtime: { writeJson: (value: unknown) => void }, value: unknown) =>
48+
runtime.writeJson(value),
49+
),
50+
}));
51+
52+
import { tryRouteCli } from "./route.js";
53+
54+
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-channels-list-route-"));
55+
56+
afterAll(() => {
57+
fs.rmSync(tempRoot, { recursive: true, force: true });
58+
vi.unstubAllEnvs();
59+
});
60+
61+
it("renders configured channel metadata without loading the plugin runtime", async () => {
62+
const pluginRoot = path.join(tempRoot, "cold-channel-plugin");
63+
fs.mkdirSync(pluginRoot, { recursive: true });
64+
const fixture = createColdPluginFixture({
65+
rootDir: pluginRoot,
66+
pluginId: "cold-channel-plugin",
67+
channelId: "cold-channel",
68+
manifest: {
69+
channelConfigs: {
70+
"cold-channel": {
71+
schema: {
72+
type: "object",
73+
additionalProperties: false,
74+
properties: { token: { type: "string" } },
75+
},
76+
label: "Cold Channel",
77+
description: "Prepared cold channel metadata",
78+
},
79+
},
80+
},
81+
});
82+
vi.stubEnv("OPENCLAW_DISABLE_BUNDLED_PLUGINS", "1");
83+
vi.stubEnv("OPENCLAW_HOME", path.join(tempRoot, "home"));
84+
vi.stubEnv("OPENCLAW_STATE_DIR", path.join(tempRoot, "state"));
85+
testState.config = {
86+
channels: { "cold-channel": { token: "configured" } },
87+
plugins: {
88+
load: { paths: [pluginRoot] },
89+
entries: { "cold-channel-plugin": { enabled: true } },
90+
},
91+
};
92+
93+
await expect(tryRouteCli(["node", "openclaw", "channels", "list", "--json"])).resolves.toBe(true);
94+
95+
expect(testState.json).toEqual([
96+
{
97+
chat: {
98+
"cold-channel": {
99+
accounts: ["default"],
100+
installed: true,
101+
origin: "configured",
102+
},
103+
},
104+
},
105+
]);
106+
expect(isColdPluginRuntimeLoaded(fixture)).toBe(false);
107+
});

‎src/cli/command-catalog.ts‎

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
127127
{
128128
commandPath: ["agents", "bindings"],
129129
exact: true,
130-
policy: { loadPlugins: "never" },
130+
policy: { configGuard: "skip", loadPlugins: "never" },
131131
},
132132
{
133133
commandPath: ["agents", "unbind"],
@@ -213,11 +213,19 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
213213
{ commandPath: ["gateway", "install"], exact: true, policy: { networkProxy: "bypass" } },
214214
{ commandPath: ["gateway", "probe"], exact: true, policy: { networkProxy: "bypass" } },
215215
{ commandPath: ["gateway", "restart"], exact: true, policy: { networkProxy: "bypass" } },
216-
{ commandPath: ["gateway", "stability"], exact: true, policy: { networkProxy: "bypass" } },
216+
{
217+
commandPath: ["gateway", "stability"],
218+
exact: true,
219+
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
220+
},
217221
{ commandPath: ["gateway", "start"], exact: true, policy: { networkProxy: "bypass" } },
218222
{ commandPath: ["gateway", "stop"], exact: true, policy: { networkProxy: "bypass" } },
219223
{ commandPath: ["gateway", "uninstall"], exact: true, policy: { networkProxy: "bypass" } },
220-
{ commandPath: ["gateway", "usage-cost"], exact: true, policy: { networkProxy: "bypass" } },
224+
{
225+
commandPath: ["gateway", "usage-cost"],
226+
exact: true,
227+
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
228+
},
221229
{
222230
commandPath: ["sessions"],
223231
exact: true,
@@ -232,6 +240,7 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
232240
{
233241
commandPath: ["commitments"],
234242
policy: {
243+
configGuard: "skip",
235244
ensureCliPath: false,
236245
loadPlugins: "never",
237246
networkProxy: "bypass",
@@ -284,6 +293,7 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
284293
policy: {
285294
ensureCliPath: false,
286295
configGuard: "skip",
296+
loadPlugins: "never",
287297
networkProxy: ({ argv }) => (hasFlag(argv, "--probe") ? "default" : "bypass"),
288298
},
289299
route: { id: "models-status" },
@@ -335,6 +345,11 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
335345
policy: { ownsProtocolStdout: true },
336346
},
337347
{ commandPath: ["approvals"], policy: { networkProxy: "bypass" } },
348+
{
349+
commandPath: ["approvals", "pending"],
350+
exact: true,
351+
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
352+
},
338353
// automations is a commander alias for cron; argv-derived command paths keep the typed token.
339354
{
340355
commandPath: ["automations"],
@@ -513,11 +528,23 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
513528
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
514529
route: { id: "channels-list" },
515530
},
516-
{ commandPath: ["skills"], exact: true, policy: { networkProxy: "bypass" } },
517-
{ commandPath: ["skills", "check"], exact: true, policy: { networkProxy: "bypass" } },
531+
{
532+
commandPath: ["skills"],
533+
exact: true,
534+
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
535+
},
536+
{
537+
commandPath: ["skills", "check"],
538+
exact: true,
539+
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
540+
},
518541
{ commandPath: ["skills", "info"], exact: true, policy: { networkProxy: "bypass" } },
519542
{ commandPath: ["skills", "install"], exact: true },
520-
{ commandPath: ["skills", "list"], exact: true, policy: { networkProxy: "bypass" } },
543+
{
544+
commandPath: ["skills", "list"],
545+
exact: true,
546+
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
547+
},
521548
{ commandPath: ["skills", "search"], exact: true },
522549
{ commandPath: ["skills", "update"], exact: true },
523550
{ commandPath: ["skills", "verify"], exact: true },

‎src/cli/command-path-policy.test.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,6 @@ describe("command-path-policy", () => {
212212
}
213213
for (const commandPath of [
214214
["agents", "bind"],
215-
["agents", "bindings"],
216215
["agents", "unbind"],
217216
["agents", "set-identity"],
218217
["agents", "delete"],
@@ -222,6 +221,28 @@ describe("command-path-policy", () => {
222221
networkProxy: "bypass",
223222
});
224223
}
224+
expectResolvedPolicy(["agents", "bindings"], {
225+
configGuard: "skip",
226+
loadPlugins: "never",
227+
networkProxy: "bypass",
228+
});
229+
});
230+
231+
it.each([
232+
["approvals", "pending"],
233+
["commitments"],
234+
["skills"],
235+
["skills", "list"],
236+
["skills", "check"],
237+
["gateway", "stability"],
238+
["gateway", "usage-cost"],
239+
])("keeps read-only cold path %s out of startup config and plugins", (...commandPath) => {
240+
expectResolvedPolicy(commandPath, {
241+
configGuard: "skip",
242+
loadPlugins: "never",
243+
...(commandPath[0] === "commitments" ? { ensureCliPath: false } : {}),
244+
networkProxy: "bypass",
245+
});
225246
});
226247

227248
it("resolves mixed startup-only rules", () => {

‎src/cli/command-startup-policy.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,14 @@ describe("command-startup-policy", () => {
3333
["docs"],
3434
["agent", "exec"],
3535
["status"],
36+
["agents", "bindings"],
37+
["approvals", "pending"],
38+
["commitments"],
39+
["skills"],
40+
["skills", "list"],
41+
["skills", "check"],
42+
["gateway", "stability"],
43+
["gateway", "usage-cost"],
3644
]) {
3745
expect(resolvePolicy({ commandPath }).skipConfigGuard, commandPath.join(" ")).toBe(true);
3846
}

‎src/cli/gateway-cli.coverage.test.ts‎

Lines changed: 14 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -298,76 +298,24 @@ describe("gateway-cli coverage", () => {
298298
);
299299
});
300300

301-
it("waits for refreshing all-agent usage caches before printing totals", async () => {
302-
const settleSleep = vi.fn(async (_ms: number) => {});
303-
gatewayProgram = createGatewayProgram({
304-
usageCostSettle: {
305-
now: () => 0,
306-
sleep: settleSleep,
307-
},
308-
});
309-
callGateway
310-
.mockResolvedValueOnce({
311-
cacheStatus: { status: "refreshing", cachedFiles: 0, pendingFiles: 2 },
312-
})
313-
.mockResolvedValueOnce({
301+
it.each(["refreshing", "partial", "stale"] as const)(
302+
"returns the first usage-cost RPC result when the cache is %s",
303+
async (status) => {
304+
const summary = {
314305
totals: { totalTokens: 100, totalCost: 0.1 },
315-
cacheStatus: { status: "fresh", cachedFiles: 2, pendingFiles: 0 },
316-
});
306+
cacheStatus: { status, cachedFiles: 0, pendingFiles: 2 },
307+
};
308+
callGateway.mockResolvedValue(summary);
317309

318-
await runGatewayCommand(["gateway", "usage-cost", "--all-agents", "--days", "7", "--json"]);
310+
await runGatewayCommand(["gateway", "usage-cost", "--all-agents", "--days", "7", "--json"]);
319311

320-
expect(callGateway).toHaveBeenCalledTimes(2);
321-
expect(settleSleep).toHaveBeenCalledOnce();
322-
expect(settleSleep).toHaveBeenCalledWith(250);
323-
const costCalls = callGateway.mock.calls.map(
324-
([raw]) => raw as { method?: string; timeoutMs?: number },
325-
);
326-
expect(costCalls.every((call) => call.method === "usage.cost")).toBe(true);
327-
expect(costCalls.every((call) => call.timeoutMs === 10_000)).toBe(true);
328-
expect(defaultRuntime.writeJson).toHaveBeenCalledWith(
329-
expect.objectContaining({
330-
totals: expect.objectContaining({ totalTokens: 100, totalCost: 0.1 }),
331-
cacheStatus: expect.objectContaining({ status: "fresh" }),
332-
}),
333-
);
334-
});
335-
336-
it.each(["refreshing", "partial", "stale"] as const)(
337-
"uses --timeout as the command-wide usage-cost settle budget for %s caches",
338-
async (status) => {
339-
let now = 0;
340-
gatewayProgram = createGatewayProgram({
341-
usageCostSettle: {
342-
now: () => now,
343-
sleep: async (ms) => {
344-
now += ms;
345-
},
346-
},
347-
});
348-
callGateway.mockResolvedValue({
349-
cacheStatus: { status, cachedFiles: 0, pendingFiles: 1 },
312+
expect(callGateway).toHaveBeenCalledOnce();
313+
expect(firstMockArg(callGateway)).toMatchObject({
314+
method: "usage.cost",
315+
params: { days: 7, agentScope: "all" },
316+
timeoutMs: 10_000,
350317
});
351-
352-
await expectGatewayExit([
353-
"gateway",
354-
"usage-cost",
355-
"--all-agents",
356-
"--timeout",
357-
"50",
358-
"--json",
359-
]);
360-
361-
// A fast host can fit a second poll inside the 50ms budget; the contract
362-
// is the budget bound on every call, not the poll count.
363-
expect(callGateway.mock.calls.length).toBeGreaterThanOrEqual(1);
364-
const costCalls = callGateway.mock.calls.map(
365-
([raw]) => raw as { method?: string; timeoutMs?: number },
366-
);
367-
expect(costCalls.every((call) => call.method === "usage.cost")).toBe(true);
368-
expect(costCalls.every((call) => (call.timeoutMs ?? 0) > 0)).toBe(true);
369-
expect(costCalls.every((call) => (call.timeoutMs ?? 0) <= 50)).toBe(true);
370-
expect(runtimeErrors.join("\n")).toContain("Timed out waiting for usage cost cache refresh");
318+
expect(defaultRuntime.writeJson).toHaveBeenCalledWith(summary);
371319
},
372320
);
373321

0 commit comments

Comments
 (0)