Skip to content

Commit bcc27f6

Browse files
perf(cli): carry prepared plugin metadata through cold read paths (#118460)
* perf(cli): carry prepared plugin metadata through cold read paths * perf(plugins): thread prepared metadata into auto-enable detection --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent e381977 commit bcc27f6

10 files changed

Lines changed: 317 additions & 6 deletions
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
// The real channels-list route must resolve catalog-row repair hints from prepared
2+
// manifest facts instead of rebuilding the manifest registry once per catalog row.
3+
import fs from "node:fs";
4+
import os from "node:os";
5+
import path from "node:path";
6+
import { afterAll, beforeEach, expect, it, vi } from "vitest";
7+
import type { ChannelPluginCatalogEntry } from "../channels/plugins/catalog.js";
8+
import type { OpenClawConfig } from "../config/types.openclaw.js";
9+
10+
const testState = vi.hoisted(() => ({
11+
config: {} as OpenClawConfig,
12+
json: [] as unknown[],
13+
catalogEntries: [] as ChannelPluginCatalogEntry[],
14+
manifestRegistryRebuilds: 0,
15+
}));
16+
17+
vi.mock("../plugins/plugin-registry-contributions.js", async (importOriginal) => {
18+
const actual =
19+
await importOriginal<typeof import("../plugins/plugin-registry-contributions.js")>();
20+
return {
21+
...actual,
22+
loadPluginManifestRegistryForPluginRegistry: (
23+
...args: Parameters<typeof actual.loadPluginManifestRegistryForPluginRegistry>
24+
) => {
25+
testState.manifestRegistryRebuilds += 1;
26+
return actual.loadPluginManifestRegistryForPluginRegistry(...args);
27+
},
28+
};
29+
});
30+
31+
vi.mock("./command-execution-startup.js", () => ({
32+
applyCliExecutionStartupPresentation: vi.fn(async () => {}),
33+
ensureCliExecutionBootstrap: vi.fn(async () => {}),
34+
resolveCliExecutionStartupContext: vi.fn(() => ({
35+
startupPolicy: { loadPlugins: false, suppressDoctorStdout: true },
36+
})),
37+
}));
38+
39+
vi.mock("../commands/channels/shared.js", () => ({
40+
formatChannelAccountLabel: vi.fn(),
41+
requireValidConfig: vi.fn(async () => testState.config),
42+
}));
43+
44+
vi.mock("../commands/channel-setup/trusted-catalog.js", () => ({
45+
listTrustedChannelPluginCatalogEntries: vi.fn(() => testState.catalogEntries),
46+
}));
47+
48+
vi.mock("../agents/agent-scope.js", () => ({
49+
resolveAgentWorkspaceDir: vi.fn(() => undefined),
50+
resolveDefaultAgentId: vi.fn(() => "main"),
51+
}));
52+
53+
vi.mock("../runtime.js", () => ({
54+
defaultRuntime: {
55+
error: vi.fn(),
56+
exit: vi.fn(),
57+
log: vi.fn(),
58+
writeJson: (value: unknown) => testState.json.push(value),
59+
writeStdout: vi.fn(),
60+
},
61+
writeRuntimeJson: vi.fn((runtime: { writeJson: (value: unknown) => void }, value: unknown) =>
62+
runtime.writeJson(value),
63+
),
64+
}));
65+
66+
import { tryRouteCli } from "./route.js";
67+
68+
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-channels-list-catalog-rows-"));
69+
70+
// Official external channels whose owner plugin is not installed. Each one is
71+
// configured, so `channels list` renders it as a catalog-only row and resolves a
72+
// repair hint for it.
73+
const OWNERLESS_CHANNEL_IDS = ["feishu", "googlechat", "matrix", "twitch"] as const;
74+
75+
function officialExternalCatalogEntry(channelId: string): ChannelPluginCatalogEntry {
76+
return {
77+
id: channelId,
78+
meta: { label: channelId },
79+
install: { npmSpec: `@openclaw/${channelId}` },
80+
} as ChannelPluginCatalogEntry;
81+
}
82+
83+
async function runChannelsListJson(channelIds: readonly string[]): Promise<{
84+
rebuilds: number;
85+
chat: unknown;
86+
}> {
87+
testState.catalogEntries = channelIds.map(officialExternalCatalogEntry);
88+
testState.config = {
89+
channels: Object.fromEntries(channelIds.map((channelId) => [channelId, { enabled: true }])),
90+
} as OpenClawConfig;
91+
testState.json = [];
92+
testState.manifestRegistryRebuilds = 0;
93+
await expect(tryRouteCli(["node", "openclaw", "channels", "list", "--json"])).resolves.toBe(true);
94+
return {
95+
rebuilds: testState.manifestRegistryRebuilds,
96+
chat: (testState.json[0] as { chat: unknown }).chat,
97+
};
98+
}
99+
100+
beforeEach(() => {
101+
vi.stubEnv("OPENCLAW_DISABLE_BUNDLED_PLUGINS", "1");
102+
vi.stubEnv("OPENCLAW_HOME", path.join(tempRoot, "home"));
103+
vi.stubEnv("OPENCLAW_STATE_DIR", path.join(tempRoot, "state"));
104+
});
105+
106+
afterAll(() => {
107+
fs.rmSync(tempRoot, { recursive: true, force: true });
108+
vi.unstubAllEnvs();
109+
});
110+
111+
it("resolves catalog-row repair hints without rebuilding the manifest registry", async () => {
112+
const empty = await runChannelsListJson([]);
113+
const rows = await runChannelsListJson(OWNERLESS_CHANNEL_IDS);
114+
115+
// Every row still resolves its repair hint, so the presence policy really ran.
116+
expect(rows.chat).toEqual(
117+
Object.fromEntries(
118+
OWNERLESS_CHANNEL_IDS.map((channelId) => [
119+
channelId,
120+
{ accounts: [], installed: false, origin: "configured" },
121+
]),
122+
),
123+
);
124+
// Discovery is prepared once per invocation, so row count cannot move this number.
125+
expect({ noRows: empty.rebuilds, fourRows: rows.rebuilds }).toEqual({ noRows: 0, fourRows: 0 });
126+
});

‎src/cli/command-catalog.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,11 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
439439
},
440440
},
441441
{ commandPath: ["nodes"], policy: { networkProxy: "bypass" } },
442+
// Both bodies are pure gateway RPC reads, so they skip the config guard like
443+
// `channels status`. Bare `openclaw nodes` keeps it because it still resolves
444+
// plugin-provided node subcommands from validated config.
445+
{ commandPath: ["nodes", "status"], exact: true, policy: { configGuard: "skip" } },
446+
{ commandPath: ["nodes", "list"], exact: true, policy: { configGuard: "skip" } },
442447
{ commandPath: ["pairing"], policy: { networkProxy: "bypass" } },
443448
{ commandPath: ["proxy"], policy: { networkProxy: "bypass" } },
444449
{ commandPath: ["qr"], policy: { networkProxy: "bypass" } },

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,20 @@ describe("command-path-policy", () => {
7474
});
7575
});
7676

77+
it("keeps RPC-only nodes reads off the config guard", () => {
78+
expectResolvedPolicy(["nodes", "status"], {
79+
configGuard: "skip",
80+
networkProxy: "bypass",
81+
});
82+
expectResolvedPolicy(["nodes", "list"], {
83+
configGuard: "skip",
84+
networkProxy: "bypass",
85+
});
86+
// Bare `openclaw nodes` still resolves plugin subcommands from validated config.
87+
expectResolvedPolicy(["nodes"], { networkProxy: "bypass" });
88+
expectResolvedPolicy(["nodes", "pair"], { networkProxy: "bypass" });
89+
});
90+
7791
it("applies exact overrides after broader channel plugin rules", () => {
7892
expectResolvedPolicy(["channels", "send"], {
7993
loadPlugins: "always",

‎src/commands/channels.list.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,8 @@ describe("channels list", () => {
411411
},
412412
channelId: "discord",
413413
workspaceDir: "/tmp/workspace",
414+
// Prepared once for the invocation; the row loop must not rediscover.
415+
manifestRecords: expect.any(Array),
414416
});
415417
const output = stripAnsi(loggedText(runtime));
416418
expect(output).toContain("Discord");

‎src/commands/channels/list.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,7 @@ export async function channelsListCommand(
281281
config: cfg,
282282
channelId: entry.id,
283283
...(workspaceDir ? { workspaceDir } : {}),
284+
manifestRecords: metadataSnapshot.plugins,
284285
});
285286
return {
286287
entry,

‎src/plugins/channel-presence-policy.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -599,13 +599,15 @@ export function resolveConfiguredChannelPluginIds(params: {
599599
activationSourceConfig?: OpenClawConfig;
600600
workspaceDir?: string;
601601
env: NodeJS.ProcessEnv;
602+
manifestRecords?: readonly PluginManifestRecord[];
602603
}): string[] {
603604
const configuredChannelIds = normalizeChannelIds([
604605
...listConfiguredChannelIdsForReadOnlyScope({
605606
config: params.config,
606607
activationSourceConfig: params.activationSourceConfig,
607608
workspaceDir: params.workspaceDir,
608609
env: params.env,
610+
manifestRecords: params.manifestRecords,
609611
}),
610612
...listExplicitConfiguredChannelIdsForConfig(params.activationSourceConfig ?? params.config),
611613
]);

‎src/plugins/effective-plugin-ids.ts‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ import {
1616
import { normalizePluginsConfig } from "./config-state.js";
1717
import { loadManifestMetadataSnapshot } from "./manifest-contract-eligibility.js";
1818
import { passesManifestOwnerBasePolicy } from "./manifest-owner-policy.js";
19+
import type { PluginManifestRecord } from "./manifest-registry.js";
20+
import type { PluginMetadataSnapshot } from "./plugin-metadata-snapshot.types.js";
1921
import { defaultSlotIdForKey } from "./slots.js";
2022

2123
function collectConfiguredChannelIds(
@@ -48,6 +50,7 @@ function collectBundledChannelOwnerPluginIds(params: {
4850
env: NodeJS.ProcessEnv;
4951
workspaceDir?: string;
5052
bundledPluginsDir?: string;
53+
manifestRecords?: readonly PluginManifestRecord[];
5154
}): string[] {
5255
const plugins = normalizePluginsConfig(params.config.plugins);
5356
const channelIds = new Set(
@@ -67,13 +70,15 @@ function collectBundledChannelOwnerPluginIds(params: {
6770
: {}),
6871
}
6972
: params.env;
70-
const snapshot = loadManifestMetadataSnapshot({
71-
config: params.config,
72-
env,
73-
workspaceDir: params.workspaceDir,
74-
});
73+
const records =
74+
params.manifestRecords ??
75+
loadManifestMetadataSnapshot({
76+
config: params.config,
77+
env,
78+
workspaceDir: params.workspaceDir,
79+
}).plugins;
7580
const pluginIds = new Set<string>();
76-
for (const plugin of snapshot.plugins) {
81+
for (const plugin of records) {
7782
if (plugin.origin !== "bundled") {
7883
continue;
7984
}
@@ -148,10 +153,22 @@ export function resolveEffectivePluginIds(params: {
148153
env: NodeJS.ProcessEnv;
149154
workspaceDir?: string;
150155
bundledPluginsDir?: string;
156+
/** Prepared metadata for this invocation. Without it every lookup below rebuilds
157+
* the registry, so callers that already hold a snapshot must pass it. */
158+
metadataSnapshot?: PluginMetadataSnapshot;
151159
}): string[] {
160+
// Effective ids are a whole-config question. A plugin-scoped snapshot only carries
161+
// its own manifests, and a bundled-plugins-dir override rewrites the discovery env,
162+
// so neither can answer it — those callers keep re-deriving.
163+
const prepared =
164+
params.bundledPluginsDir || params.metadataSnapshot?.pluginIds
165+
? undefined
166+
: params.metadataSnapshot;
152167
const autoEnabled = applyPluginAutoEnable({
153168
config: params.config,
154169
env: params.env,
170+
...(prepared ? { manifestRegistry: prepared.manifestRegistry } : {}),
171+
...(prepared?.discovery ? { discovery: prepared.discovery } : {}),
155172
});
156173
const effectiveConfig = autoEnabled.config;
157174
const ids = new Set(collectExplicitEffectivePluginIds(effectiveConfig));
@@ -168,6 +185,7 @@ export function resolveEffectivePluginIds(params: {
168185
activationSourceConfig: params.config,
169186
workspaceDir: params.workspaceDir,
170187
env: params.env,
188+
manifestRecords: prepared?.plugins,
171189
})) {
172190
ids.add(pluginId);
173191
}
@@ -176,6 +194,7 @@ export function resolveEffectivePluginIds(params: {
176194
channelIds: configuredChannelIds,
177195
env: params.env,
178196
workspaceDir: params.workspaceDir,
197+
manifestRecords: prepared?.plugins,
179198
...(params.bundledPluginsDir ? { bundledPluginsDir: params.bundledPluginsDir } : {}),
180199
})) {
181200
ids.add(pluginId);
@@ -185,6 +204,7 @@ export function resolveEffectivePluginIds(params: {
185204
activationSourceConfig: params.config,
186205
workspaceDir: params.workspaceDir,
187206
env: params.env,
207+
...(prepared ? { metadataSnapshot: prepared } : {}),
188208
}).pluginIds) {
189209
ids.add(pluginId);
190210
}

‎src/plugins/official-external-plugin-repair-hints.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/** Builds doctor/install repair hints for missing official external plugin owners. */
22
import type { OpenClawConfig } from "../config/types.openclaw.js";
33
import { resolveConfiguredChannelPresencePolicy } from "./channel-plugin-ids.js";
4+
import type { PluginManifestRecord } from "./manifest-registry.js";
45
import {
56
getOfficialExternalPluginCatalogEntry,
67
getOfficialExternalPluginCatalogManifest,
@@ -60,6 +61,9 @@ export function resolveMissingOfficialExternalChannelPluginRepairHint(params: {
6061
channelId: string;
6162
workspaceDir?: string;
6263
env?: NodeJS.ProcessEnv;
64+
/** Prepared manifest facts. Callers resolving many channels must pass these, or
65+
* presence policy rebuilds the whole manifest registry once per channel. */
66+
manifestRecords?: readonly PluginManifestRecord[];
6367
}): OfficialExternalPluginRepairHint | null {
6468
const hint = resolveOfficialExternalPluginRepairHint(params.channelId);
6569
if (!hint?.channelId || hint.channelId !== params.channelId) {
@@ -71,6 +75,7 @@ export function resolveMissingOfficialExternalChannelPluginRepairHint(params: {
7175
workspaceDir: params.workspaceDir,
7276
env: params.env,
7377
includePersistedAuthState: false,
78+
manifestRecords: params.manifestRecords,
7479
}).find((entry) => entry.channelId === hint.channelId);
7580
if (!policy || policy.effective) {
7681
return null;

0 commit comments

Comments
 (0)