penpot/mcp/packages/server/src/dispatch/TaskDispatcher.ts
Dominik Jain be17fabc6a 🎉 Introduce global plugins and move MCP to application scope
Global plugin lifecycle:
- Add optional manifest scope "global" for plugins that remain active
  across dashboard and workspace navigation within one browser tab.
  Existing plugins retain workspace scope by default.
- Preserve global sandboxes when a workspace ends or another plugin
  loads, including when that other plugin fails to initialize.
- Avoid duplicate instances of an already-running global plugin.
- Close global plugins on explicit closure or logout, with idempotent
  cleanup of listeners, timers and UI resources. Global scope does not
  imply automatic startup or persistence across a browser reload.

Plugin API and navigation:
- Keep a permanently live penpot facade whose getters follow the current
  workspace, while user, theme and UI facilities remain available on
  the dashboard.
- Expose penpotMgmt to global plugins with workspace metadata,
  none/loading/ready status and workspacechange subscriptions.
- Add awaitable openFile(fileId, {teamId}) navigation in the current tab,
  defaulting to the current team and resolving only once the requested
  file and its active page are ready.
- Reject invalid identifiers, failed or superseded navigation and waits
  exceeding 30 seconds; release navigation watchers on completion.
- Guard workspace-bound operations while no workspace is ready and
  return null from root, currentFile and currentPage in that state.
- Require content:read for the initial management API. Callers must
  reacquire file, page and shape references after changing files.

MCP lifecycle and connection controls:
- Make MCP a global plugin and initialize its integrated controller per
  authenticated application session instead of per workspace.
- Load the enabled integration with a valid token on the dashboard as
  well as in a file, retaining its existing hidden-iframe implementation.
- Keep enabling and connecting separate: an enabled plugin starts idle,
  and each tab connects explicitly through dashboard or workspace
  controls.
- Preserve the iframe, WebSocket, heartbeat and reconnect machinery
  during navigation; disconnect on request and close on disable/logout.

MCP sessions and execution:
- Derive the short MCP session ID solely from currentUser.sessionId,
  excluding the file ID. Retain the SHA-256-based, 50-bit Base32 encoding
  to produce a stable, copyable 10-character identifier.
- Allow sessions without an open file and update workspace metadata over
  the existing connection without replacing its routing identity.
- Refresh context after the connection handshake so initialization does
  not leave stale file metadata.
- Expose penpotMgmt to execute_code, preserve execution storage across
  navigation and skip layout waits when no workspace is ready.
- Update API types, tool guidance, documentation and the changelog.

Validation:
- Cover authenticated startup, workspace survival, logout cleanup,
  readiness, navigation failure, duplicate loads and session routing.
- Verify that short IDs remain stable across files and reconnects and
  that disconnect cancels pending asynchronous ID initialization.
- Pass 16 focused frontend tests, 73 runtime tests, 30 MCP plugin tests,
  builds, TypeScript checks and frontend/runtime lint.
- Pass all 73 MCP server tests with --test-force-exit; the normal runner
  still stays alive after assertions finish.
- Verify a live dashboard-to-file-to-dashboard round trip without a
  document or iframe reload, preserving facade identity and storage.

AI-assisted-by: gpt-6
2026-10-07 14:58:32 +02:00

50 lines
2.4 KiB
TypeScript

import type { PenpotSession } from "@penpot/mcp-common";
import type { PenpotConnection } from "../PenpotConnection";
import type { AbstractPluginTask } from "../PluginTask";
import type { UserPenpotConnections } from "../UserPenpotConnections";
/** Local connection access and tracked task execution provided by PluginBridge. */
export interface TaskDispatchHost {
getUserConnections(userToken: string | null): UserPenpotConnections | undefined;
sendLocalTask(task: AbstractPluginTask, connection: PenpotConnection): void;
sendRemoteTask(task: AbstractPluginTask, userToken: string, sessionId: string): void;
displaceConnection(connection: PenpotConnection): void;
}
/** Session discovery, task routing, and connection subscription lifecycle. */
export abstract class TaskDispatcher {
abstract discoverSessions(userToken: string | null): Promise<PenpotSession[]>;
abstract dispatch(task: AbstractPluginTask, userToken: string | null, sessionId?: string): Promise<void>;
abstract onNewConnection(connection: PenpotConnection): Promise<void>;
abstract onConnectionClosed(connection: PenpotConnection): Promise<void>;
abstract close(): Promise<void>;
/** Selects the sole session from a complete discovery result. */
protected selectOnlySession(sessions: PenpotSession[]): string {
if (sessions.length === 0) {
throw new Error("No Penpot sessions are connected. Please connect the Penpot MCP plugin and retry.");
}
if (sessions.length !== 1) {
throw new Error(
"Multiple Penpot sessions are connected. Ask the user to select one of the active sessions, " +
"then retry with its sessionId:\n" +
sessions
.map(
(session) =>
`${session.sessionId}: ${session.fileId ? `${JSON.stringify(session.fileName)} (file ${session.fileId})` : "no active workspace"}`
)
.join("\n")
);
}
return sessions[0].sessionId;
}
}
/** Error returned when discovery cannot establish the complete set of sessions. */
export class SessionDiscoveryError extends Error {
constructor() {
super("Penpot session discovery failed. This may be due to temporary server load. You can retry the request.");
this.name = "SessionDiscoveryError";
}
}