Skip to content

Commit cddc1ac

Browse files
authored
fix(plugins): reuse published metadata on hot paths (#127355)
1 parent ccbfa6c commit cddc1ac

10 files changed

Lines changed: 167 additions & 41 deletions

‎src/channels/plugins/read-only-command-defaults.test.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,47 @@
11
// Read-only command default tests cover command defaulting for read-only channel plugins.
22
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
import { STATE_DIR } from "../../config/paths.js";
34

4-
const loadPluginMetadataSnapshot = vi.hoisted(() => vi.fn());
5+
const { loadPluginMetadataSnapshot, resolvePluginMetadataSnapshot } = vi.hoisted(() => ({
6+
loadPluginMetadataSnapshot: vi.fn(),
7+
resolvePluginMetadataSnapshot: vi.fn(),
8+
}));
59

610
vi.mock("../../plugins/plugin-metadata-snapshot.js", () => ({
711
loadPluginMetadataSnapshot,
8-
resolvePluginMetadataSnapshot: loadPluginMetadataSnapshot,
12+
resolvePluginMetadataSnapshot,
913
}));
1014

1115
import { resolveReadOnlyChannelCommandDefaults } from "./read-only-command-defaults.js";
1216

1317
describe("resolveReadOnlyChannelCommandDefaults", () => {
1418
beforeEach(() => {
1519
loadPluginMetadataSnapshot.mockReset();
20+
resolvePluginMetadataSnapshot.mockReset();
1621
loadPluginMetadataSnapshot.mockReturnValue({
1722
index: { plugins: [] },
1823
plugins: [],
1924
});
25+
resolvePluginMetadataSnapshot.mockImplementation(loadPluginMetadataSnapshot);
26+
});
27+
28+
it.each([
29+
{ name: "process", env: process.env, stateDir: STATE_DIR },
30+
{
31+
name: "custom",
32+
env: { HOME: "/home/demo", OPENCLAW_STATE_DIR: "/state" },
33+
stateDir: "/state",
34+
},
35+
])("reuses published metadata for the $name state root without scanning", ({ env, stateDir }) => {
36+
const currentSnapshot = { index: { plugins: [] }, plugins: [] };
37+
resolvePluginMetadataSnapshot.mockImplementation((params) =>
38+
params.stateDir === undefined ? currentSnapshot : loadPluginMetadataSnapshot(params),
39+
);
40+
41+
expect(resolveReadOnlyChannelCommandDefaults("demo", { config: {}, env, stateDir })).toBe(
42+
undefined,
43+
);
44+
expect(loadPluginMetadataSnapshot).not.toHaveBeenCalled();
2045
});
2146

2247
it("resolves command defaults from the shared metadata snapshot", () => {

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* Reads native command/skill defaults from installed plugin manifests without loading plugins.
55
*/
66
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
7+
import { resolveStateDir, STATE_DIR } from "../../config/paths.js";
78
import type { OpenClawConfig } from "../../config/types.openclaw.js";
89
import { isBlockedObjectKey } from "../../infra/prototype-keys.js";
910
import { isInstalledPluginEnabled } from "../../plugins/installed-plugin-index.js";
@@ -87,7 +88,11 @@ export function resolveReadOnlyChannelCommandDefaults(
8788
const env = options.env ?? process.env;
8889
const resolvedSnapshot = resolvePluginMetadataSnapshot({
8990
config: options.config,
90-
stateDir: options.stateDir,
91+
stateDir:
92+
options.stateDir !== undefined &&
93+
options.stateDir === (env === process.env ? STATE_DIR : resolveStateDir(env))
94+
? undefined
95+
: options.stateDir,
9196
workspaceDir: options.workspaceDir,
9297
env,
9398
allowWorkspaceScopedCurrent: true,

‎src/hooks/plugin-hooks.test.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,18 @@ import fs from "node:fs";
33
import fsp from "node:fs/promises";
44
import os from "node:os";
55
import path from "node:path";
6-
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
6+
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
77
import type { OpenClawConfig } from "../config/config.js";
8+
import { setCurrentPluginMetadataSnapshot } from "../plugins/current-plugin-metadata-snapshot.js";
9+
import { loadPluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
810
import {
911
clearInternalHooks,
1012
createInternalHookEvent,
1113
setInternalHooksEnabled,
1214
triggerInternalHook,
1315
} from "./internal-hooks.js";
1416
import { loadInternalHooks } from "./loader.js";
17+
import { resolvePluginHookDirs } from "./plugin-hooks.js";
1518
import { loadWorkspaceHookEntries } from "./workspace.js";
1619

1720
describe("bundle plugin hooks", () => {
@@ -34,6 +37,8 @@ describe("bundle plugin hooks", () => {
3437
});
3538

3639
afterEach(() => {
40+
setCurrentPluginMetadataSnapshot(undefined);
41+
vi.restoreAllMocks();
3742
clearInternalHooks();
3843
setInternalHooksEnabled(true);
3944
if (previousBundledHooksDir === undefined) {
@@ -125,6 +130,24 @@ describe("bundle plugin hooks", () => {
125130
expect(entry.metadata?.events).toEqual(["command:new"]);
126131
});
127132

133+
it("reuses published plugin metadata without rescanning manifests", async () => {
134+
const bundleRoot = await writeBundleHookFixture();
135+
const config = createConfig(true);
136+
const snapshot = loadPluginMetadataSnapshot({ config, workspaceDir, env: process.env });
137+
setCurrentPluginMetadataSnapshot(snapshot, { config, workspaceDir });
138+
const hookDir = fs.realpathSync.native(path.join(bundleRoot, "hooks"));
139+
const manifestRegistry = await import("../plugins/manifest-registry-installed.js");
140+
const scanManifests = vi.spyOn(manifestRegistry, "loadPluginManifestRegistryForInstalledIndex");
141+
142+
for (let iteration = 0; iteration < 2; iteration += 1) {
143+
expect(resolvePluginHookDirs({ workspaceDir, config })).toEqual([
144+
{ dir: hookDir, pluginId: "sample-bundle" },
145+
]);
146+
}
147+
148+
expect(scanManifests).not.toHaveBeenCalled();
149+
});
150+
128151
it("loads and executes enabled bundle hooks through the internal hook loader", async () => {
129152
await writeBundleHookFixture();
130153

‎src/hooks/plugin-hooks.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
resolvePolicyPluginActivationState,
99
} from "../plugins/config-policy.js";
1010
import { resolveMemorySlotDecision } from "../plugins/config-state.js";
11-
import { loadPluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
11+
import { resolvePluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
1212
import { hasKind } from "../plugins/slots.js";
1313
import { isPathInsideWithRealpath } from "../security/scan-paths.js";
1414

@@ -28,9 +28,9 @@ export function resolvePluginHookDirs(params: {
2828
if (!workspaceDir) {
2929
return [];
3030
}
31-
const metadataSnapshot = loadPluginMetadataSnapshot({
31+
const metadataSnapshot = resolvePluginMetadataSnapshot({
3232
workspaceDir,
33-
config: params.config ?? {},
33+
config: params.config,
3434
env: process.env,
3535
});
3636
const registry = metadataSnapshot.manifestRegistry;

‎src/plugins/tools.optional.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2269,6 +2269,47 @@ describe("resolvePluginTools optional tools", () => {
22692269
expect(factory).toHaveBeenCalledTimes(2);
22702270
});
22712271

2272+
it("executes cached plugin tools from the published generation without rescanning manifests", async () => {
2273+
const context = createContext();
2274+
const runtimeConfig: OpenClawConfig = {
2275+
...context.config,
2276+
channels: { telegram: { enabled: false } },
2277+
};
2278+
const getRuntimeConfig = vi.fn(() => runtimeConfig);
2279+
const toolContext = { ...context, getRuntimeConfig };
2280+
const factory = vi.fn(() => makeTool("cached_generation_tool"));
2281+
setRegistry(
2282+
[
2283+
createNamedToolEntry("cache-generation", "cached_generation_tool", {
2284+
factory,
2285+
}),
2286+
],
2287+
context.config,
2288+
);
2289+
2290+
resolvePluginTools(createResolveToolsParams({ context: toolContext }));
2291+
const [cachedTool] = resolvePluginTools(createResolveToolsParams({ context: toolContext }));
2292+
expect(cachedTool?.name).toBe("cached_generation_tool");
2293+
expect(getRuntimeConfig).toHaveBeenCalledTimes(2);
2294+
2295+
const manifestRegistry = await import("./manifest-registry-installed.js");
2296+
const manifestScan = vi
2297+
.spyOn(manifestRegistry, "loadPluginManifestRegistryForInstalledIndex")
2298+
.mockImplementation(() => {
2299+
throw new Error("cached plugin execution rescanned manifests");
2300+
});
2301+
try {
2302+
await expect(cachedTool?.execute("call", {}, undefined)).resolves.toEqual({
2303+
content: [{ type: "text", text: "ok" }],
2304+
});
2305+
expect(manifestScan).not.toHaveBeenCalled();
2306+
expect(getRuntimeConfig).toHaveBeenCalledTimes(2);
2307+
expect(factory).toHaveBeenCalledTimes(2);
2308+
} finally {
2309+
manifestScan.mockRestore();
2310+
}
2311+
});
2312+
22722313
it("keeps cached ordinary plugin tools free of network provenance", async () => {
22732314
const factory = vi.fn(() => makeTool("cached_ordinary_tool"));
22742315
setRegistry([

‎src/plugins/tools.ts‎

Lines changed: 6 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
} from "./manifest-contract-eligibility.js";
3232
import type { PluginManifestRecord } from "./manifest-registry.js";
3333
import { hasManifestToolAvailability } from "./manifest-tool-availability.js";
34+
import { resolvePluginMetadataSnapshot } from "./plugin-metadata-snapshot.js";
3435
import type { PluginMetadataManifestView } from "./plugin-metadata-snapshot.types.js";
3536
import type { PluginRegistry, PluginToolRegistration } from "./registry-types.js";
3637
import {
@@ -292,26 +293,6 @@ function blocksHostRestrictedConversationReadRegistration(params: {
292293
);
293294
}
294295

295-
function resolveCurrentManifestPlugin(params: {
296-
pluginId: string;
297-
ctx: OpenClawPluginToolContext;
298-
loadContext: ReturnType<typeof resolvePluginRuntimeLoadContext>;
299-
}): PluginManifestRecord | undefined {
300-
let config = params.ctx.runtimeConfig ?? params.ctx.config ?? params.loadContext.config;
301-
if (params.ctx.getRuntimeConfig) {
302-
try {
303-
config = params.ctx.getRuntimeConfig() ?? config;
304-
} catch {
305-
return undefined;
306-
}
307-
}
308-
return loadManifestContractSnapshot({
309-
config,
310-
workspaceDir: params.loadContext.workspaceDir,
311-
env: params.loadContext.env,
312-
}).plugins.find((plugin) => plugin.id === params.pluginId);
313-
}
314-
315296
/**
316297
* Builds a collision-proof key for plugin-owned tool metadata lookups.
317298
*/
@@ -876,11 +857,11 @@ function createCachedDescriptorPluginTool(params: {
876857
const resolveCandidateTool = (
877858
candidate: PluginToolRegistration,
878859
): AnyAgentTool | undefined => {
879-
const manifestPlugin = resolveCurrentManifestPlugin({
880-
pluginId,
881-
ctx: params.ctx,
882-
loadContext: params.loadContext,
883-
});
860+
const manifestPlugin = resolvePluginMetadataSnapshot({
861+
config: params.loadContext.config,
862+
workspaceDir: params.loadContext.workspaceDir,
863+
env: params.loadContext.env,
864+
}).byPluginId.get(pluginId);
884865
if (
885866
blocksHostRestrictedConversationReadRegistration({
886867
entry: candidate,

‎src/secrets/channel-env-vars.dynamic.test.ts‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,16 @@ const pluginRegistryMocks = vi.hoisted(() => {
1818
plugins: [],
1919
diagnostics: [],
2020
}));
21+
const loadPluginMetadataSnapshot = vi.fn((_params?: unknown) => ({
22+
plugins: loadManifestRegistry().plugins,
23+
manifestRegistry: loadManifestRegistry(),
24+
}));
2125
return {
2226
loadPluginManifestRegistryForInstalledIndex: loadManifestRegistry,
2327
loadPluginManifestRegistryForPluginRegistry: loadManifestRegistry,
2428
loadPluginRegistrySnapshot: vi.fn(() => ({ plugins: [] })),
25-
loadPluginMetadataSnapshot: vi.fn(() => ({
26-
plugins: loadManifestRegistry().plugins,
27-
manifestRegistry: loadManifestRegistry(),
28-
})),
29+
loadPluginMetadataSnapshot,
30+
resolvePluginMetadataSnapshot: vi.fn((params: unknown) => loadPluginMetadataSnapshot(params)),
2931
};
3032
});
3133

@@ -42,6 +44,7 @@ vi.mock("../plugins/plugin-registry.js", () => ({
4244

4345
vi.mock("../plugins/plugin-metadata-snapshot.js", () => ({
4446
loadPluginMetadataSnapshot: pluginRegistryMocks.loadPluginMetadataSnapshot,
47+
resolvePluginMetadataSnapshot: pluginRegistryMocks.resolvePluginMetadataSnapshot,
4548
}));
4649

4750
describe("channel env vars dynamic package metadata", () => {
@@ -55,6 +58,10 @@ describe("channel env vars dynamic package metadata", () => {
5558
pluginRegistryMocks.loadPluginRegistrySnapshot.mockReset();
5659
pluginRegistryMocks.loadPluginRegistrySnapshot.mockReturnValue({ plugins: [] });
5760
pluginRegistryMocks.loadPluginMetadataSnapshot.mockClear();
61+
pluginRegistryMocks.resolvePluginMetadataSnapshot.mockReset();
62+
pluginRegistryMocks.resolvePluginMetadataSnapshot.mockImplementation((params) =>
63+
pluginRegistryMocks.loadPluginMetadataSnapshot(params),
64+
);
5865
});
5966

6067
it("includes later-installed plugin env vars without a bundled generated map", async () => {
@@ -81,4 +88,31 @@ describe("channel env vars dynamic package metadata", () => {
8188
expect(knownNames).toContain("MATTERMOST_BOT_TOKEN");
8289
expect(knownNames).toContain("MATTERMOST_URL");
8390
});
91+
92+
it("reuses published channel metadata without rescanning manifests", async () => {
93+
pluginRegistryMocks.resolvePluginMetadataSnapshot.mockReturnValue({
94+
plugins: [
95+
{
96+
id: "external-mattermost",
97+
origin: "global",
98+
packageChannel: {
99+
id: "mattermost",
100+
configuredState: { env: { anyOf: ["MATTERMOST_BOT_TOKEN"] } },
101+
},
102+
},
103+
],
104+
manifestRegistry: { plugins: [], diagnostics: [] },
105+
});
106+
const mod = await import("./channel-env-vars.js");
107+
108+
expect(mod.getChannelEnvVars("mattermost")).toEqual(["MATTERMOST_BOT_TOKEN"]);
109+
expect(mod.listKnownChannelEnvVarNames()).toEqual(["MATTERMOST_BOT_TOKEN"]);
110+
expect(pluginRegistryMocks.loadPluginMetadataSnapshot).not.toHaveBeenCalled();
111+
expect(pluginRegistryMocks.resolvePluginMetadataSnapshot).toHaveBeenCalledTimes(2);
112+
expect(pluginRegistryMocks.resolvePluginMetadataSnapshot).toHaveBeenCalledWith({
113+
config: undefined,
114+
workspaceDir: undefined,
115+
env: process.env,
116+
});
117+
});
84118
});

‎src/secrets/channel-env-vars.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/** Discovers plugin-declared environment variable names for channel credential setup. */
22
import { uniqueStrings } from "@openclaw/normalization-core/string-normalization";
33
import type { OpenClawConfig } from "../config/types.openclaw.js";
4-
import { loadPluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
4+
import { resolvePluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
55
import { appendUniqueEnvVarCandidates } from "../shared/env-var-candidates.js";
66

77
type ChannelEnvVarLookupParams = {
@@ -20,8 +20,8 @@ type ChannelEnvVarLookupParams = {
2020
function resolveChannelEnvVars(
2121
params?: ChannelEnvVarLookupParams,
2222
): Record<string, readonly string[]> {
23-
const snapshot = loadPluginMetadataSnapshot({
24-
config: params?.config ?? {},
23+
const snapshot = resolvePluginMetadataSnapshot({
24+
config: params?.config,
2525
workspaceDir: params?.workspaceDir,
2626
env: params?.env ?? process.env,
2727
});

‎src/skills/loading/plugin-skills.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,24 @@ describe("resolvePluginSkillDirs", () => {
302302
expect(hoisted.loadPluginMetadataSnapshot).not.toHaveBeenCalled();
303303
});
304304

305+
it("preserves absent config when resolving current lifecycle metadata", async () => {
306+
const workspaceDir = await tempDirs.make("openclaw-");
307+
const manifestRegistry: PluginManifestRegistry = { diagnostics: [], plugins: [] };
308+
const metadataSnapshot = {
309+
manifestRegistry,
310+
plugins: manifestRegistry.plugins,
311+
normalizePluginId: (pluginId: string) => pluginId,
312+
};
313+
hoisted.resolvePluginMetadataSnapshot.mockImplementationOnce((params: unknown) =>
314+
(params as { config?: OpenClawConfig }).config === undefined
315+
? metadataSnapshot
316+
: hoisted.loadPluginMetadataSnapshot(params),
317+
);
318+
319+
expect(resolvePluginSkillDirs({ workspaceDir })).toEqual([]);
320+
expect(hoisted.loadPluginMetadataSnapshot).not.toHaveBeenCalled();
321+
});
322+
305323
it.each([
306324
{
307325
name: "unavailable to available",

‎src/skills/loading/plugin-skills.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,9 @@ export function resolvePluginSkillDirs(params: {
5050
});
5151
return [];
5252
}
53-
const config = params.config ?? {};
5453
const metadataSnapshot = resolvePluginMetadataSnapshot({
5554
workspaceDir,
56-
config,
55+
config: params.config,
5756
env: process.env,
5857
});
5958
return resolvePluginSkillDirsFromMetadata({ ...params, metadataSnapshot });

0 commit comments

Comments
 (0)