diff --git a/mcp/packages/plugin/src/PluginTaskRequest.test.ts b/mcp/packages/plugin/src/PluginTaskRequest.test.ts new file mode 100644 index 0000000000..78a079ae06 --- /dev/null +++ b/mcp/packages/plugin/src/PluginTaskRequest.test.ts @@ -0,0 +1,152 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { createContext, runInContext, type Context } from "node:vm"; +import ts from "typescript"; +import * as ErrorUtils from "./ErrorUtils.ts"; +import * as VersionCompatibility from "./VersionCompatibility.ts"; + +/** Compiles a plugin source file for a simulated plugin context. */ +function compile(name: string) { + return ts.transpileModule(readFileSync(new URL(name, import.meta.url), "utf8"), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }).outputText; +} + +/** Exports of a compiled module run in the given context, which it shares with the plugin bundle. */ +function compiledModule(name: string, context: Context) { + const exports = {}; + context.exports = exports; + runInContext(compile(name), context); + return exports; +} + +/** + * Plugin task request handling with a task that waits until the test releases it. + * + * Closing the plugin replaces the plugin globals with `undefined`, as the plugin runtime does + * when it closes a plugin: SES reads a removed global as `undefined` instead of throwing. + */ +function pluginWithPendingTask(outcome: "success" | "failure") { + const responses: any[] = []; + const errors: unknown[][] = []; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + let onMessage!: (message: any) => void; + const context: Context = createContext({ + console: { + log() {}, + error: (...args: unknown[]) => { + errors.push(args); + }, + warn() {}, + info() {}, + }, + penpot: { + theme: "dark", + ui: { + open() {}, + onMessage: (handler: (message: any) => void) => { + onMessage = handler; + }, + sendMessage: (message: any) => { + if (message.type === "task-response") { + responses.push(message.response); + } + }, + }, + on() {}, + }, + mcp: undefined, + }); + const taskModule = compiledModule("TaskHandler.ts", context); + context.require = (name: string) => { + if (name === "./task-handlers/ExecuteCodeTaskHandler") { + return { + ExecuteCodeTaskHandler: class { + isApplicableTo(task: any) { + return task.taskType === "executeCode"; + } + async handle(task: any) { + await released; + if (outcome === "failure") { + throw new Error("code failed"); + } + task.sendSuccess({ result: 1 }); + } + }, + }; + } + if (name === "./TaskHandler") return taskModule; + if (name === "./ErrorUtils") return ErrorUtils; + if (name === "./VersionCompatibility") return VersionCompatibility; + if (name === "./RollbackLog") { + return { + LocalStorageRollbackStore: class {}, + RollbackLog: class { + listen() {} + pending() { + return []; + } + acknowledge() {} + }, + }; + } + throw new Error(`Unexpected import: ${name}`); + }; + context.exports = {}; + runInContext(compile("plugin.ts"), context); + return { + responses, + errors, + start: () => onMessage({ id: "task-1", task: "executeCode", params: { code: "" } }), + close: () => { + for (const name of ["console", "penpot", "penpotMgmt", "mcp"]) { + context[name] = undefined; + } + }, + release, + }; +} + +/** Unhandled rejections raised while the given action and its follow-up work run. */ +async function unhandledRejections(action: () => void | Promise): Promise { + const rejections: unknown[] = []; + const listener = (reason: unknown) => rejections.push(reason); + process.on("unhandledRejection", listener); + try { + await action(); + await new Promise((resolve) => setTimeout(resolve, 20)); + } finally { + process.off("unhandledRejection", listener); + } + return rejections; +} + +for (const outcome of ["success", "failure"] as const) { + test(`a task ending in ${outcome} after the plugin closed raises no error`, async () => { + const plugin = pluginWithPendingTask(outcome); + const rejections = await unhandledRejections(() => { + plugin.start(); + plugin.close(); + plugin.release(); + }); + assert.deepEqual(rejections, []); + assert.deepEqual(plugin.responses, []); + assert.deepEqual(plugin.errors, []); + }); +} + +test("a task failing while the plugin is open sends an error response", async () => { + const plugin = pluginWithPendingTask("failure"); + const rejections = await unhandledRejections(() => { + plugin.start(); + plugin.release(); + }); + assert.deepEqual(rejections, []); + assert.equal(plugin.responses.length, 1); + assert.equal(plugin.responses[0].success, false); + assert.match(plugin.responses[0].error, /code failed/); +}); diff --git a/mcp/packages/plugin/src/plugin.ts b/mcp/packages/plugin/src/plugin.ts index f659baa208..2e25375fc1 100644 --- a/mcp/packages/plugin/src/plugin.ts +++ b/mcp/packages/plugin/src/plugin.ts @@ -18,6 +18,12 @@ const isIntegratedRemoteMcp = !!mcp; */ const management = typeof penpotMgmt === "undefined" ? null : penpotMgmt; +/** + * the console of the plugin context, kept for task errors reported after the plugin is closed, + * when the runtime has removed the `console` global + */ +const pluginConsole = console; + let uiInitialized = false; /** @@ -119,7 +125,7 @@ penpot.ui.onMessage< } else if (typeof message === "object" && message.task && message.id) { // Handle plugin tasks submitted by the MCP server handlePluginTaskRequest(message).catch((error) => { - console.error("Error in handlePluginTaskRequest:", error); + pluginConsole.error("Error in handlePluginTaskRequest:", error); }); } }); @@ -156,6 +162,15 @@ function sendWorkspaceContext(): void { management?.on("workspacechange", sendWorkspaceContext); +/** + * Whether the plugin runtime has closed this plugin. + * Closing removes the plugin globals, which then read as undefined, but a task that was already + * running goes on and fails at its next use of them. + */ +function isPluginClosed(): boolean { + return typeof penpot === "undefined"; +} + /** * Handles plugin task requests received from the MCP server via WebSocket. * @@ -182,6 +197,10 @@ async function handlePluginTaskRequest(request: { id: string; task: string; para console.log("Task handled successfully:", task); } catch (error) { + if (isPluginClosed()) { + // no way to answer: the MCP server fails the task when the plugin connection closes + return; + } console.error("Error handling task:", error); task.sendError(`Error handling task: ${formatTaskError(error)}`); }