File size: 6,769 Bytes
253e783 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | // Plugin API lifecycle guard: registration-only methods stop working once
// register() returns, while runtime methods remain callable from hooks and tools.
import { expectDefined } from "@openclaw/normalization-core";
import { describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { buildPluginApi } from "./api-builder.js";
import { runPluginRegisterSyncInRegistry } from "./loader-module-runtime.js";
import { createEmptyPluginRegistry } from "./registry-empty.js";
import type { PluginRuntime } from "./runtime/types.js";
import type { OpenClawPluginApi } from "./types.js";
function createPluginApi(handlers: Parameters<typeof buildPluginApi>[0]["handlers"] = {}) {
return buildPluginApi({
id: "late-call-fixture",
name: "Late Call Fixture",
source: "test",
registrationMode: "full",
config: {} as OpenClawConfig,
runtime: {} as PluginRuntime,
logger: { info() {}, warn() {}, error() {}, debug() {} },
resolvePath: (input) => input,
handlers,
});
}
function captureRegisteredPluginApi(handlers: Parameters<typeof buildPluginApi>[0]["handlers"]) {
const api = createPluginApi(handlers);
let captured: OpenClawPluginApi | undefined;
runPluginRegisterSyncInRegistry(
(pluginApi) => {
captured = pluginApi;
},
api,
createEmptyPluginRegistry(),
"late-call-fixture",
);
return expectDefined(captured, "captured plugin api");
}
describe("plugin api lifecycle", () => {
it("returns inert results for unwired runtime and scheduler handlers", async () => {
const api = createPluginApi();
const sessionKey = "agent:main:main";
expect(api.emitAgentEvent({ runId: "run", stream: "lifecycle", data: {} })).toEqual({
emitted: false,
reason: "not wired",
});
expect(api.setRunContext({ runId: "run", namespace: "workflow", value: 1 })).toBe(false);
expect(api.getRunContext({ runId: "run", namespace: "workflow" })).toBeUndefined();
expect(
api.registerSessionSchedulerJob({ id: "job", sessionKey, kind: "session-turn" }),
).toBeUndefined();
await expect(api.enqueueNextTurnInjection({ sessionKey, text: "queued" })).resolves.toEqual({
enqueued: false,
id: "",
sessionKey,
});
await expect(
api.sendSessionAttachment({ sessionKey, files: [{ path: "/tmp/attachment.txt" }] }),
).resolves.toEqual({ ok: false, error: "not wired" });
await expect(
api.scheduleSessionTurn({ sessionKey, message: "wake", delayMs: 1_000 }),
).resolves.toBeUndefined();
await expect(api.unscheduleSessionTurnsByTag({ sessionKey, tag: "wake" })).resolves.toEqual({
removed: 0,
failed: 0,
});
});
it("keeps inherited handlers, undefined defaults, and one captured CLI lookup", () => {
const reads: string[] = [];
const registerCli = vi.fn<OpenClawPluginApi["registerCli"]>();
const registerHook = vi.fn<OpenClawPluginApi["registerHook"]>();
class InheritedHandlers {
get registerCli() {
reads.push("cli");
return registerCli;
}
get registerTool() {
reads.push("tool");
return undefined;
}
get registerHook() {
reads.push("hook");
return registerHook;
}
}
const api = createPluginApi(new InheritedHandlers());
const hook: Parameters<OpenClawPluginApi["registerHook"]>[1] = () => {};
const registrar: Parameters<OpenClawPluginApi["registerCli"]>[0] = () => {};
const toolFactory = vi.fn(() => null);
expect(api.registerTool(toolFactory)).toBeUndefined();
expect(toolFactory).not.toHaveBeenCalled();
expect(api.registerHook).toBe(registerHook);
expect(api.registerCli).toBe(registerCli);
api.registerHook("message_received", hook);
expect(registerHook).toHaveBeenCalledExactlyOnceWith("message_received", hook);
api.registerNodeCliFeature(registrar, { commands: ["camera"] });
expect(registerCli).toHaveBeenCalledExactlyOnceWith(registrar, {
commands: ["camera"],
parentPath: ["nodes"],
});
expect(reads).toEqual(["cli", "tool", "hook"]);
});
it("keeps both next-turn injection APIs callable after registration", async () => {
const enqueueNextTurnInjection = vi.fn(async (injection) => ({
enqueued: true,
id: `injection-${injection.text}`,
sessionKey: injection.sessionKey,
}));
const api = captureRegisteredPluginApi({ enqueueNextTurnInjection });
const groupedResult = await api.session.workflow.enqueueNextTurnInjection({
sessionKey: "global",
text: "grouped",
agentId: "work",
});
const flatResult = await api.enqueueNextTurnInjection({
sessionKey: "global",
text: "flat",
agentId: "main",
});
expect(groupedResult).toEqual({
enqueued: true,
id: "injection-grouped",
sessionKey: "global",
});
expect(flatResult).toEqual({
enqueued: true,
id: "injection-flat",
sessionKey: "global",
});
expect(enqueueNextTurnInjection).toHaveBeenCalledTimes(2);
expect(enqueueNextTurnInjection).toHaveBeenNthCalledWith(1, {
sessionKey: "global",
agentId: "work",
text: "grouped",
});
expect(enqueueNextTurnInjection).toHaveBeenNthCalledWith(2, {
sessionKey: "global",
agentId: "main",
text: "flat",
});
});
it("blocks registration-phase methods after registration", () => {
const registerSessionExtension = vi.fn();
const api = captureRegisteredPluginApi({ registerSessionExtension });
const result = api.session.state.registerSessionExtension({
namespace: "workflow",
description: "workflow",
});
expect(result).toBeUndefined();
expect(registerSessionExtension).not.toHaveBeenCalled();
});
it.each<[string, boolean]>([
["clearRunContext", true],
["emitAgentEvent", true],
["enqueueNextTurnInjection", true],
["getRunContext", true],
["sendSessionAttachment", true],
["scheduleSessionTurn", true],
["setRunContext", true],
["unscheduleSessionTurnsByTag", true],
["registerTool", false],
["registerSessionExtension", false],
["unknown", false],
["", false],
["constructor", false],
["toString", false],
["__proto__", false],
])("enforces post-registration call eligibility for %j as %s", (methodName, expected) => {
const handler = vi.fn();
const api = captureRegisteredPluginApi({ [methodName]: handler });
const method = Reflect.get(api, methodName);
const result = typeof method === "function" ? Reflect.apply(method, api, []) : undefined;
expect(handler).toHaveBeenCalledTimes(expected ? 1 : 0);
expect(result).toBeUndefined();
});
});
|