penpot/mcp/packages/browser-extension/src/SessionMap.test.ts
Alonso Torres 43f3bda8b5
✨ Add mcp browser extension (#12627)
* 🐛 Fail MCP tasks at once when their plugin connection closes

A response only counts when it comes from the connection the task went
to, so a task sent over a connection that then closes can never finish.
It used to wait for its full timeout. The plugin bridge now fails such
tasks as soon as their connection closes.

Connections also log their close code and reason, to tell a page
closing its socket from a browser or network failure.

* ✨ Announce the MCP session to a browser extension

Let a browser extension learn which tab holds an MCP session, so it can
keep the browser from discarding that tab. While the MCP plugin runs,
the page listens for the extension's hello message, and says it is
ready once it listens, so that a content script that said hello too
early says it again. After a hello, the page posts its session ID and
connection status, and posts them again on every status change. When
the plugin stops, it reports the session as disconnected.

The plugin also reports "disconnected" while it reconnects on its own,
for instance after a page resume, so the page announces "connecting"
then and "disconnected" only once the user has stopped the connection.
Otherwise the extension would forget the session at every reconnect.

The page only accepts messages posted on its own window by its own
origin, posts to its own origin only, and sends nothing before the
extension asks. It reaches the window through app.util.globals, whose
stand-in for the unit tests accepts postMessage.

* ✨ Keep Penpot tabs connected to MCP from being frozen

Chrome freezes some background tabs, for instance busy ones while
Battery Saver is on, and a frozen page cannot run the MCP plugin.
Chrome does not freeze a page that holds a Web Lock, so the page holds
a lock named penpot-mcp-session from the moment the user asks to
connect until the connection stops: on disconnect, logout, MCP being
turned off or the MCP runtime starting again. The lock is shared, so
several tabs can hold it at once. Browsers without Web Locks skip it,
and when the lock request fails, the next connection request tries
again.

Firefox does not freeze background pages, so the lock changes nothing
there.

* ✨ Add a browser extension that keeps MCP tabs from being discarded

A browser may discard a background tab to save memory. A discarded
Penpot tab reloads when the user returns to it and loses its MCP
session.

Add mcp/packages/browser-extension, a Manifest V3 extension for Chrome
and Firefox, built from one source into dist/chrome and dist/firefox.
It is written in TypeScript, bundled with esbuild and imports the
protocol types from mcp-common. The package joins the mcp workspace, so
the build, test and fmt scripts of mcp/ cover it; the server release
build skips it.

Its content script runs on design.penpot.app, on the test environments
under penpot.dev and on local development instances. It asks the page
for its MCP session on load, again when the page says it is ready and
when the page returns from the back/forward cache, and forwards each
valid session announcement to the background. It accepts only messages
the page posted on its own window from its own origin, and posts its
hello to that origin only. It also tells the background when the page
is hidden.

The background records which tab holds each MCP session. A tab holds
the session it last announced as connected, until its page announces a
disconnect, is hidden, or the tab is closed or replaced. The map lives
in chrome.storage.session, so it survives restarts of the background
and clears when the browser closes. While a tab holds a session, the
browser may not discard it automatically.

The extension asks only for the storage permission. Chrome runs the
background as a service worker; Firefox runs it as an event page and
needs the add-on ID, mcp-extension@penpot.app, and Firefox 140. The
toolbar popup lists the connected tabs. The icon is the Penpot logo,
white on a black rounded square, with the SVG source next to the PNGs.
A README explains how the extension works and how to build and load
it.

* 🐛 Ask MCP plugins for heartbeats so hidden tabs do not look frozen

The server refuses to send a task to a plugin whose last heartbeat is
older than 30 s, taking its tab for frozen. The plugin sent heartbeats
only from a 10 s timer, and Chrome runs the timers of a hidden page as
rarely as once a minute: without Energy Saver after about a minute
hidden, and at once with it. A Penpot tab hidden for a minute therefore
failed that check about half the time, although it could run tasks.

Chrome handles socket messages of a hidden page at once, and a frozen
page cannot handle them at all. The server now sends each plugin a
heartbeat request every 10 s, and the plugin answers it with a
heartbeat, so the heartbeat age again tells a frozen tab from a hidden
one. The plugin keeps its timer, so it still sends heartbeats to a
server that does not ask. A plugin that does not know the request
passes it to the plugin code, which ignores it.
2026-11-03 10:07:50 +01:00

126 lines
4.7 KiB
TypeScript

import assert from "node:assert/strict";
import { beforeEach, test } from "node:test";
import type { SessionAnnouncement } from "@penpot/mcp-common";
import { DiscardGuard } from "./DiscardGuard.ts";
import { SessionMap, type SessionChange, type SessionEntry, type SessionStore } from "./SessionMap.ts";
/** In-memory store standing in for session storage. */
class MemoryStore implements SessionStore {
constructor(public saved?: Record<string, SessionEntry>) {}
async load() {
return this.saved;
}
async save(entries: Record<string, SessionEntry>) {
this.saved = structuredClone(entries);
}
}
const TAB = { tabId: 1, windowId: 10 };
const OTHER_TAB = { tabId: 2, windowId: 10 };
function announcement(
status: SessionAnnouncement["status"],
sessionId: string | null = "session"
): SessionAnnouncement {
return { type: "penpot-mcp:session", sessionId, status };
}
let store: MemoryStore;
let changes: SessionChange[];
let sessions: SessionMap;
beforeEach(() => {
store = new MemoryStore();
changes = [];
sessions = new SessionMap(store);
sessions.observe({ sessionsChanged: (change) => changes.push(change) });
});
test("maps a connected session to the announcing tab and saves it", async () => {
await sessions.announce(TAB, announcement("connected"));
assert.deepEqual(sessions.get("session"), TAB);
assert.deepEqual(store.saved, { session: TAB });
assert.deepEqual(changes, [{ tabsAdded: [1], tabsRemoved: [] }]);
});
test("ignores announcements without a connected session", async () => {
await sessions.announce(TAB, announcement("connecting", null));
await sessions.announce(TAB, announcement("connected", null));
await sessions.announce(TAB, announcement("error"));
assert.deepEqual(sessions.all(), []);
assert.deepEqual(changes, []);
});
test("keeps the session while the plugin reconnects", async () => {
await sessions.announce(TAB, announcement("connected"));
await sessions.announce(TAB, announcement("connecting"));
await sessions.announce(TAB, announcement("connected"));
assert.equal(sessions.get("session")?.tabId, 1);
assert.equal(changes.length, 1);
});
test("forgets the tab's session when its page announces a disconnect", async () => {
await sessions.announce(TAB, announcement("connected"));
await sessions.announce(TAB, announcement("disconnected", null));
assert.equal(sessions.get("session"), undefined);
assert.deepEqual(changes.at(-1), { tabsAdded: [], tabsRemoved: [1] });
});
test("a tab holds only the session it announced last", async () => {
await sessions.announce(TAB, announcement("connected", "old"));
await sessions.announce(TAB, announcement("connected", "new"));
assert.equal(sessions.get("old"), undefined);
assert.equal(sessions.get("new")?.tabId, 1);
assert.deepEqual(changes.at(-1), { tabsAdded: [], tabsRemoved: [] });
});
test("forgets only the sessions of a removed tab", async () => {
await sessions.announce(TAB, announcement("connected", "first"));
await sessions.announce(OTHER_TAB, announcement("connected", "second"));
await sessions.removeTab(1);
assert.deepEqual(
sessions.all().map(([sessionId]) => sessionId),
["second"]
);
assert.deepEqual(changes.at(-1), { tabsAdded: [], tabsRemoved: [1] });
});
test("restores the saved sessions when the worker restarts", async () => {
await sessions.announce(TAB, announcement("connected"));
const restarted = new SessionMap(store);
await restarted.ready();
assert.equal(restarted.get("session")?.tabId, 1);
});
test("changes made while restoring apply to the restored sessions", async () => {
const saved = new MemoryStore({ first: TAB });
const restored = new SessionMap(saved);
await restored.announce(OTHER_TAB, announcement("connected", "second"));
assert.deepEqual(Object.keys(saved.saved!).sort(), ["first", "second"]);
});
test("the discard guard protects tabs holding a session and releases them after", async () => {
const calls: [number, boolean][] = [];
const guard = new DiscardGuard({
setAutoDiscardable: async (tabId, autoDiscardable) => {
calls.push([tabId, autoDiscardable]);
},
});
const guarded = new SessionMap(new MemoryStore());
guarded.observe(guard);
await guarded.announce(TAB, announcement("connected"));
await guarded.removeTab(1);
assert.deepEqual(calls, [
[1, false],
[1, true],
]);
});
test("the discard guard ignores tabs closed meanwhile", async () => {
const guard = new DiscardGuard({ setAutoDiscardable: () => Promise.reject(new Error("No tab with id")) });
guard.sessionsChanged({ tabsAdded: [1], tabsRemoved: [2] });
await new Promise((resolve) => setImmediate(resolve));
});