perf(test): mock lobster subprocess

This commit is contained in:
Peter Steinberger
2026-02-14 19:24:57 +00:00
parent e6f75e526d
commit 5e496a1519

View File

@@ -1,35 +1,21 @@
import { EventEmitter } from "node:events";
import fs from "node:fs/promises"; import fs from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { describe, expect, it } from "vitest"; import { PassThrough } from "node:stream";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawPluginApi, OpenClawPluginToolContext } from "../../../src/plugins/types.js"; import type { OpenClawPluginApi, OpenClawPluginToolContext } from "../../../src/plugins/types.js";
import { createLobsterTool } from "./lobster-tool.js";
async function writeFakeLobsterScript(scriptBody: string, prefix = "openclaw-lobster-plugin-") { const spawnState = vi.hoisted(() => ({
const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix)); queue: [] as Array<{ stdout: string; stderr?: string; exitCode?: number }>,
const isWindows = process.platform === "win32"; spawn: vi.fn(),
}));
if (isWindows) { vi.mock("node:child_process", () => ({
const scriptPath = path.join(dir, "lobster.js"); spawn: (...args: unknown[]) => spawnState.spawn(...args),
const cmdPath = path.join(dir, "lobster.cmd"); }));
await fs.writeFile(scriptPath, scriptBody, { encoding: "utf8" });
const cmd = `@echo off\r\n"${process.execPath}" "${scriptPath}" %*\r\n`;
await fs.writeFile(cmdPath, cmd, { encoding: "utf8" });
return { dir, binPath: cmdPath };
}
const binPath = path.join(dir, "lobster"); let createLobsterTool: typeof import("./lobster-tool.js").createLobsterTool;
const file = `#!/usr/bin/env node\n${scriptBody}\n`;
await fs.writeFile(binPath, file, { encoding: "utf8", mode: 0o755 });
return { dir, binPath };
}
async function writeFakeLobster(params: { payload: unknown }) {
const scriptBody =
`const payload = ${JSON.stringify(params.payload)};\n` +
`process.stdout.write(JSON.stringify(payload));\n`;
return await writeFakeLobsterScript(scriptBody);
}
function fakeApi(overrides: Partial<OpenClawPluginApi> = {}): OpenClawPluginApi { function fakeApi(overrides: Partial<OpenClawPluginApi> = {}): OpenClawPluginApi {
return { return {
@@ -72,96 +58,115 @@ function fakeCtx(overrides: Partial<OpenClawPluginToolContext> = {}): OpenClawPl
} }
describe("lobster plugin tool", () => { describe("lobster plugin tool", () => {
it("runs lobster and returns parsed envelope in details", async () => { let tempDir = "";
const fake = await writeFakeLobster({ let lobsterBinPath = "";
payload: { ok: true, status: "ok", output: [{ hello: "world" }], requiresApproval: null },
});
const originalPath = process.env.PATH; beforeAll(async () => {
process.env.PATH = `${fake.dir}${path.delimiter}${originalPath ?? ""}`; ({ createLobsterTool } = await import("./lobster-tool.js"));
try { tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-lobster-plugin-"));
const tool = createLobsterTool(fakeApi()); lobsterBinPath = path.join(tempDir, process.platform === "win32" ? "lobster.cmd" : "lobster");
const res = await tool.execute("call1", { await fs.writeFile(lobsterBinPath, "", { encoding: "utf8", mode: 0o755 });
action: "run", });
pipeline: "noop",
timeoutMs: 1000, afterAll(async () => {
if (!tempDir) {
return;
}
if (process.platform === "win32") {
await fs.rm(tempDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
} else {
await fs.rm(tempDir, { recursive: true, force: true });
}
});
beforeEach(() => {
spawnState.queue.length = 0;
spawnState.spawn.mockReset();
spawnState.spawn.mockImplementation(() => {
const next = spawnState.queue.shift() ?? { stdout: "" };
const stdout = new PassThrough();
const stderr = new PassThrough();
const child = new EventEmitter() as EventEmitter & {
stdout: PassThrough;
stderr: PassThrough;
kill: (signal?: string) => boolean;
};
child.stdout = stdout;
child.stderr = stderr;
child.kill = () => true;
setImmediate(() => {
if (next.stderr) {
stderr.end(next.stderr);
} else {
stderr.end();
}
stdout.end(next.stdout);
child.emit("exit", next.exitCode ?? 0);
}); });
expect(res.details).toMatchObject({ ok: true, status: "ok" }); return child;
} finally { });
process.env.PATH = originalPath; });
}
it("runs lobster and returns parsed envelope in details", async () => {
spawnState.queue.push({
stdout: JSON.stringify({
ok: true,
status: "ok",
output: [{ hello: "world" }],
requiresApproval: null,
}),
});
const tool = createLobsterTool(fakeApi());
const res = await tool.execute("call1", {
action: "run",
pipeline: "noop",
timeoutMs: 1000,
});
expect(spawnState.spawn).toHaveBeenCalled();
expect(res.details).toMatchObject({ ok: true, status: "ok" });
}); });
it("tolerates noisy stdout before the JSON envelope", async () => { it("tolerates noisy stdout before the JSON envelope", async () => {
const payload = { ok: true, status: "ok", output: [], requiresApproval: null }; const payload = { ok: true, status: "ok", output: [], requiresApproval: null };
const { dir } = await writeFakeLobsterScript( spawnState.queue.push({
`const payload = ${JSON.stringify(payload)};\n` + stdout: `noise before json\n${JSON.stringify(payload)}`,
`console.log("noise before json");\n` + });
`process.stdout.write(JSON.stringify(payload));\n`,
"openclaw-lobster-plugin-noisy-",
);
const originalPath = process.env.PATH; const tool = createLobsterTool(fakeApi());
process.env.PATH = `${dir}${path.delimiter}${originalPath ?? ""}`; const res = await tool.execute("call-noisy", {
action: "run",
pipeline: "noop",
timeoutMs: 1000,
});
try { expect(res.details).toMatchObject({ ok: true, status: "ok" });
const tool = createLobsterTool(fakeApi());
const res = await tool.execute("call-noisy", {
action: "run",
pipeline: "noop",
timeoutMs: 1000,
});
expect(res.details).toMatchObject({ ok: true, status: "ok" });
} finally {
process.env.PATH = originalPath;
}
}); });
it("requires absolute lobsterPath when provided (even though it is ignored)", async () => { it("requires absolute lobsterPath when provided (even though it is ignored)", async () => {
const fake = await writeFakeLobster({ const tool = createLobsterTool(fakeApi());
payload: { ok: true, status: "ok", output: [{ hello: "world" }], requiresApproval: null }, await expect(
}); tool.execute("call2", {
action: "run",
const originalPath = process.env.PATH; pipeline: "noop",
process.env.PATH = `${fake.dir}${path.delimiter}${originalPath ?? ""}`; lobsterPath: "./lobster",
}),
try { ).rejects.toThrow(/absolute path/);
const tool = createLobsterTool(fakeApi());
await expect(
tool.execute("call2", {
action: "run",
pipeline: "noop",
lobsterPath: "./lobster",
}),
).rejects.toThrow(/absolute path/);
} finally {
process.env.PATH = originalPath;
}
}); });
it("rejects lobsterPath (deprecated) when invalid", async () => { it("rejects lobsterPath (deprecated) when invalid", async () => {
const fake = await writeFakeLobster({ const tool = createLobsterTool(fakeApi());
payload: { ok: true, status: "ok", output: [{ hello: "world" }], requiresApproval: null }, await expect(
}); tool.execute("call2b", {
action: "run",
const originalPath = process.env.PATH; pipeline: "noop",
process.env.PATH = `${fake.dir}${path.delimiter}${originalPath ?? ""}`; lobsterPath: "/bin/bash",
}),
try { ).rejects.toThrow(/lobster executable/);
const tool = createLobsterTool(fakeApi());
await expect(
tool.execute("call2b", {
action: "run",
pipeline: "noop",
lobsterPath: "/bin/bash",
}),
).rejects.toThrow(/lobster executable/);
} finally {
process.env.PATH = originalPath;
}
}); });
it("rejects absolute cwd", async () => { it("rejects absolute cwd", async () => {
@@ -187,49 +192,38 @@ describe("lobster plugin tool", () => {
}); });
it("uses pluginConfig.lobsterPath when provided", async () => { it("uses pluginConfig.lobsterPath when provided", async () => {
const fake = await writeFakeLobster({ spawnState.queue.push({
payload: { ok: true, status: "ok", output: [{ hello: "world" }], requiresApproval: null }, stdout: JSON.stringify({
ok: true,
status: "ok",
output: [{ hello: "world" }],
requiresApproval: null,
}),
}); });
// Ensure `lobster` is NOT discoverable via PATH, while still allowing our const tool = createLobsterTool(fakeApi({ pluginConfig: { lobsterPath: lobsterBinPath } }));
// fake lobster (a Node script with `#!/usr/bin/env node`) to run. const res = await tool.execute("call-plugin-config", {
const originalPath = process.env.PATH; action: "run",
process.env.PATH = path.dirname(process.execPath); pipeline: "noop",
timeoutMs: 1000,
});
try { expect(spawnState.spawn).toHaveBeenCalled();
const tool = createLobsterTool(fakeApi({ pluginConfig: { lobsterPath: fake.binPath } })); const [execPath] = spawnState.spawn.mock.calls[0] ?? [];
const res = await tool.execute("call-plugin-config", { expect(execPath).toBe(lobsterBinPath);
action: "run", expect(res.details).toMatchObject({ ok: true, status: "ok" });
pipeline: "noop",
timeoutMs: 1000,
});
expect(res.details).toMatchObject({ ok: true, status: "ok" });
} finally {
process.env.PATH = originalPath;
}
}); });
it("rejects invalid JSON from lobster", async () => { it("rejects invalid JSON from lobster", async () => {
const { dir } = await writeFakeLobsterScript( spawnState.queue.push({ stdout: "nope" });
`process.stdout.write("nope");\n`,
"openclaw-lobster-plugin-bad-",
);
const originalPath = process.env.PATH; const tool = createLobsterTool(fakeApi());
process.env.PATH = `${dir}${path.delimiter}${originalPath ?? ""}`; await expect(
tool.execute("call3", {
try { action: "run",
const tool = createLobsterTool(fakeApi()); pipeline: "noop",
await expect( }),
tool.execute("call3", { ).rejects.toThrow(/invalid JSON/);
action: "run",
pipeline: "noop",
}),
).rejects.toThrow(/invalid JSON/);
} finally {
process.env.PATH = originalPath;
}
}); });
it("can be gated off in sandboxed contexts", async () => { it("can be gated off in sandboxed contexts", async () => {