mirror of
https://github.com/penpot/penpot.git
synced 2026-11-26 21:00:32 +00:00
🐛 Stop MCP plugin tasks from throwing after the plugin closes (#13224)
Closing a plugin removes its globals (console, penpot, ...) while a task of the MCP plugin may still be running. Under SES a removed global reads as undefined, so the task failed at its next use of console or penpot, and the catch handlers failed again on console.error. The rejection reached the workspace as "Cannot read properties of undefined (reading 'error')", for tasks that succeeded as well as for failed ones. A task that ends after the plugin closed now returns quietly. It cannot answer: the UI iframe and its WebSocket are gone, and the MCP server already fails the task when the plugin connection closes. The outer catch logs through the console reference taken at load, so it cannot throw. Tests: PluginTaskRequest.test.ts runs TaskHandler.ts and plugin.ts in one sandbox, removes the globals while a task waits, and checks that no rejection escapes and no error is logged when the task ends in success or failure. A task that fails while the plugin is open still sends its error response. Closes #12503 AI-assisted-by: claude-opus-5-5
This commit is contained in:
parent
b58f7d2996
commit
3bd549a146
152
mcp/packages/plugin/src/PluginTaskRequest.test.ts
Normal file
152
mcp/packages/plugin/src/PluginTaskRequest.test.ts
Normal file
@ -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<void>((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<void>): Promise<unknown[]> {
|
||||
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/);
|
||||
});
|
||||
@ -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)}`);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user