mirror of
https://github.com/moltbot/moltbot.git
synced 2026-04-21 05:32:53 +00:00
fix(runtime): guard import-time side effects
This commit is contained in:
@@ -1,39 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const listBootstrapChannelPlugins = vi.hoisted(() =>
|
||||
vi.fn(() => [
|
||||
{
|
||||
id: "signal",
|
||||
messaging: {
|
||||
defaultMarkdownTableMode: "bullets",
|
||||
},
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
vi.mock("../channels/plugins/bootstrap-registry.js", () => ({
|
||||
listBootstrapChannelPlugins,
|
||||
}));
|
||||
|
||||
describe("markdown table defaults import behavior", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
listBootstrapChannelPlugins.mockClear();
|
||||
});
|
||||
|
||||
it("does not bootstrap channel plugins during module import", async () => {
|
||||
const module = await import("./markdown-tables.js");
|
||||
|
||||
expect(module.DEFAULT_TABLE_MODES).toBeDefined();
|
||||
expect(listBootstrapChannelPlugins).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("loads bootstrap defaults lazily on first access and memoizes them", async () => {
|
||||
const { DEFAULT_TABLE_MODES, resolveMarkdownTableMode } = await import("./markdown-tables.js");
|
||||
|
||||
expect(DEFAULT_TABLE_MODES.get("signal")).toBe("bullets");
|
||||
expect(listBootstrapChannelPlugins).toHaveBeenCalledTimes(1);
|
||||
expect(resolveMarkdownTableMode({ channel: "signal" })).toBe("bullets");
|
||||
expect(listBootstrapChannelPlugins).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { assertNoImportTimeSideEffects } from "./testkit.js";
|
||||
|
||||
const listBootstrapChannelPlugins = vi.hoisted(() =>
|
||||
vi.fn(() => [
|
||||
{
|
||||
id: "signal",
|
||||
messaging: {
|
||||
defaultMarkdownTableMode: "bullets",
|
||||
},
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
const BOOTSTRAP_SEAM = "listBootstrapChannelPlugins()";
|
||||
const BOOTSTRAP_WHY =
|
||||
"it boots bundled channel metadata on hot runtime/config import paths and turns cheap module evaluation into channel bootstrap work.";
|
||||
const BOOTSTRAP_FIX =
|
||||
"keep the seam behind a lazy getter/runtime boundary so import stays cold and the first real lookup loads once.";
|
||||
|
||||
function mockBootstrapRegistry() {
|
||||
vi.doMock("../../channels/plugins/bootstrap-registry.js", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("../../channels/plugins/bootstrap-registry.js")>(
|
||||
"../../channels/plugins/bootstrap-registry.js",
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
listBootstrapChannelPlugins,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function expectNoBootstrapDuringImport(moduleId: string) {
|
||||
assertNoImportTimeSideEffects({
|
||||
moduleId,
|
||||
forbiddenSeam: BOOTSTRAP_SEAM,
|
||||
calls: listBootstrapChannelPlugins.mock.calls,
|
||||
why: BOOTSTRAP_WHY,
|
||||
fixHint: BOOTSTRAP_FIX,
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
vi.restoreAllMocks();
|
||||
vi.doUnmock("../../channels/plugins/bootstrap-registry.js");
|
||||
});
|
||||
|
||||
describe("runtime import side-effect contracts", () => {
|
||||
beforeEach(() => {
|
||||
listBootstrapChannelPlugins.mockClear();
|
||||
});
|
||||
|
||||
it("keeps config/markdown-tables cold on import", async () => {
|
||||
mockBootstrapRegistry();
|
||||
await import("../../config/markdown-tables.js");
|
||||
|
||||
expectNoBootstrapDuringImport("src/config/markdown-tables.ts");
|
||||
});
|
||||
|
||||
it("keeps markdown table defaults lazy and memoized after import", async () => {
|
||||
mockBootstrapRegistry();
|
||||
const markdownTables = await import("../../config/markdown-tables.js");
|
||||
|
||||
expectNoBootstrapDuringImport("src/config/markdown-tables.ts");
|
||||
|
||||
expect(markdownTables.DEFAULT_TABLE_MODES.get("signal")).toBe("bullets");
|
||||
expect(listBootstrapChannelPlugins).toHaveBeenCalledTimes(1);
|
||||
expect(markdownTables.DEFAULT_TABLE_MODES.has("signal")).toBe(true);
|
||||
expect(listBootstrapChannelPlugins).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps plugins/runtime/runtime-channel cold on import", async () => {
|
||||
mockBootstrapRegistry();
|
||||
await import("../runtime/runtime-channel.js");
|
||||
|
||||
expectNoBootstrapDuringImport("src/plugins/runtime/runtime-channel.ts");
|
||||
});
|
||||
|
||||
it("keeps plugins/runtime/runtime-system cold on import", async () => {
|
||||
mockBootstrapRegistry();
|
||||
await import("../runtime/runtime-system.js");
|
||||
|
||||
expectNoBootstrapDuringImport("src/plugins/runtime/runtime-system.ts");
|
||||
});
|
||||
|
||||
it("keeps web-search/runtime cold on import", async () => {
|
||||
mockBootstrapRegistry();
|
||||
await import("../../web-search/runtime.js");
|
||||
|
||||
expectNoBootstrapDuringImport("src/web-search/runtime.ts");
|
||||
});
|
||||
|
||||
it("keeps web-fetch/runtime cold on import", async () => {
|
||||
mockBootstrapRegistry();
|
||||
await import("../../web-fetch/runtime.js");
|
||||
|
||||
expectNoBootstrapDuringImport("src/web-fetch/runtime.ts");
|
||||
});
|
||||
|
||||
it("keeps plugins/runtime/index cold on import", async () => {
|
||||
mockBootstrapRegistry();
|
||||
await import("../runtime/index.js");
|
||||
|
||||
expectNoBootstrapDuringImport("src/plugins/runtime/index.ts");
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,46 @@ export function uniqueSortedStrings(values: readonly string[]) {
|
||||
return [...new Set(values)].toSorted((left, right) => left.localeCompare(right));
|
||||
}
|
||||
|
||||
function formatImportSideEffectCall(args: readonly unknown[]): string {
|
||||
if (args.length === 0) {
|
||||
return "(no args)";
|
||||
}
|
||||
return args
|
||||
.map((arg) => {
|
||||
try {
|
||||
return JSON.stringify(arg);
|
||||
} catch {
|
||||
return String(arg);
|
||||
}
|
||||
})
|
||||
.join(", ");
|
||||
}
|
||||
|
||||
export function assertNoImportTimeSideEffects(params: {
|
||||
moduleId: string;
|
||||
forbiddenSeam: string;
|
||||
calls: readonly (readonly unknown[])[];
|
||||
why: string;
|
||||
fixHint: string;
|
||||
}) {
|
||||
if (params.calls.length === 0) {
|
||||
return;
|
||||
}
|
||||
const observedCalls = params.calls
|
||||
.slice(0, 3)
|
||||
.map((call, index) => ` ${index + 1}. ${formatImportSideEffectCall(call)}`)
|
||||
.join("\n");
|
||||
throw new Error(
|
||||
[
|
||||
`[runtime contract] ${params.moduleId} touched ${params.forbiddenSeam} during module import.`,
|
||||
`why this is banned: ${params.why}`,
|
||||
`expected fix: ${params.fixHint}`,
|
||||
`observed calls (${params.calls.length}):`,
|
||||
observedCalls,
|
||||
].join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
export function createPluginRegistryFixture(config = {} as OpenClawConfig) {
|
||||
return {
|
||||
config,
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
import { runHeartbeatOnce as runHeartbeatOnceInternal } from "../../infra/heartbeat-runner.js";
|
||||
import { requestHeartbeatNow } from "../../infra/heartbeat-wake.js";
|
||||
import { enqueueSystemEvent } from "../../infra/system-events.js";
|
||||
import { runCommandWithTimeout } from "../../process/exec.js";
|
||||
import { createLazyRuntimeMethod, createLazyRuntimeModule } from "../../shared/lazy-runtime.js";
|
||||
import { formatNativeDependencyHint } from "./native-deps.js";
|
||||
import type { RunHeartbeatOnceOptions } from "./types-core.js";
|
||||
import type { PluginRuntime } from "./types.js";
|
||||
|
||||
const loadHeartbeatRunnerRuntime = createLazyRuntimeModule(
|
||||
() => import("../../infra/heartbeat-runner.js"),
|
||||
);
|
||||
const runHeartbeatOnceInternal = createLazyRuntimeMethod(
|
||||
loadHeartbeatRunnerRuntime,
|
||||
(runtime) => runtime.runHeartbeatOnce,
|
||||
);
|
||||
|
||||
export function createRuntimeSystem(): PluginRuntime["system"] {
|
||||
return {
|
||||
enqueueSystemEvent,
|
||||
|
||||
18
src/secrets/runtime-web-tools-state.ts
Normal file
18
src/secrets/runtime-web-tools-state.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { RuntimeWebToolsMetadata } from "./runtime-web-tools.types.js";
|
||||
|
||||
let activeRuntimeWebToolsMetadata: RuntimeWebToolsMetadata | null = null;
|
||||
|
||||
export function clearActiveRuntimeWebToolsMetadata(): void {
|
||||
activeRuntimeWebToolsMetadata = null;
|
||||
}
|
||||
|
||||
export function setActiveRuntimeWebToolsMetadata(metadata: RuntimeWebToolsMetadata): void {
|
||||
activeRuntimeWebToolsMetadata = structuredClone(metadata);
|
||||
}
|
||||
|
||||
export function getActiveRuntimeWebToolsMetadata(): RuntimeWebToolsMetadata | null {
|
||||
if (!activeRuntimeWebToolsMetadata) {
|
||||
return null;
|
||||
}
|
||||
return structuredClone(activeRuntimeWebToolsMetadata);
|
||||
}
|
||||
@@ -34,6 +34,11 @@ import {
|
||||
createResolverContext,
|
||||
type SecretResolverWarning,
|
||||
} from "./runtime-shared.js";
|
||||
import {
|
||||
clearActiveRuntimeWebToolsMetadata,
|
||||
getActiveRuntimeWebToolsMetadata as getActiveRuntimeWebToolsMetadataFromState,
|
||||
setActiveRuntimeWebToolsMetadata,
|
||||
} from "./runtime-web-tools-state.js";
|
||||
import { resolveRuntimeWebTools, type RuntimeWebToolsMetadata } from "./runtime-web-tools.js";
|
||||
|
||||
export type { SecretResolverWarning } from "./runtime-shared.js";
|
||||
@@ -98,6 +103,7 @@ function cloneRefreshContext(context: SecretsRuntimeRefreshContext): SecretsRunt
|
||||
function clearActiveSecretsRuntimeState(): void {
|
||||
activeSnapshot = null;
|
||||
activeRefreshContext = null;
|
||||
clearActiveRuntimeWebToolsMetadata();
|
||||
setRuntimeConfigSnapshotRefreshHandler(null);
|
||||
clearRuntimeConfigSnapshot();
|
||||
clearRuntimeAuthProfileStoreSnapshots();
|
||||
@@ -256,6 +262,7 @@ export function activateSecretsRuntimeSnapshot(snapshot: PreparedSecretsRuntimeS
|
||||
replaceRuntimeAuthProfileStoreSnapshots(next.authStores);
|
||||
activeSnapshot = next;
|
||||
activeRefreshContext = cloneRefreshContext(refreshContext);
|
||||
setActiveRuntimeWebToolsMetadata(next.webTools);
|
||||
setRuntimeConfigSnapshotRefreshHandler({
|
||||
refresh: async ({ sourceConfig }) => {
|
||||
if (!activeSnapshot || !activeRefreshContext) {
|
||||
@@ -286,10 +293,7 @@ export function getActiveSecretsRuntimeSnapshot(): PreparedSecretsRuntimeSnapsho
|
||||
}
|
||||
|
||||
export function getActiveRuntimeWebToolsMetadata(): RuntimeWebToolsMetadata | null {
|
||||
if (!activeSnapshot) {
|
||||
return null;
|
||||
}
|
||||
return structuredClone(activeSnapshot.webTools);
|
||||
return getActiveRuntimeWebToolsMetadataFromState();
|
||||
}
|
||||
|
||||
export function resolveCommandSecretsFromActiveRuntimeSnapshot(params: {
|
||||
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
import { resolvePluginWebFetchProviders } from "../plugins/web-fetch-providers.runtime.js";
|
||||
import { sortWebFetchProvidersForAutoDetect } from "../plugins/web-fetch-providers.shared.js";
|
||||
import type { RuntimeWebFetchMetadata } from "../secrets/runtime-web-tools.types.js";
|
||||
import { getActiveRuntimeWebToolsMetadata } from "../secrets/runtime.js";
|
||||
import { getActiveRuntimeWebToolsMetadata } from "../secrets/runtime-web-tools-state.js";
|
||||
import { normalizeSecretInput } from "../utils/normalize-secret-input.js";
|
||||
|
||||
type WebFetchConfig = NonNullable<OpenClawConfig["tools"]>["web"] extends infer Web
|
||||
|
||||
@@ -9,7 +9,7 @@ import { resolvePluginWebSearchProviders } from "../plugins/web-search-providers
|
||||
import { resolveRuntimeWebSearchProviders } from "../plugins/web-search-providers.runtime.js";
|
||||
import { sortWebSearchProvidersForAutoDetect } from "../plugins/web-search-providers.shared.js";
|
||||
import type { RuntimeWebSearchMetadata } from "../secrets/runtime-web-tools.types.js";
|
||||
import { getActiveRuntimeWebToolsMetadata } from "../secrets/runtime.js";
|
||||
import { getActiveRuntimeWebToolsMetadata } from "../secrets/runtime-web-tools-state.js";
|
||||
import { normalizeSecretInput } from "../utils/normalize-secret-input.js";
|
||||
|
||||
type WebSearchConfig = NonNullable<OpenClawConfig["tools"]>["web"] extends infer Web
|
||||
|
||||
Reference in New Issue
Block a user