xlerobot-sim / src /agent /bridge.js
VectorW's picture
Update the web simulation
8ff66cf verified
Raw History Blame Contribute Delete
6.71 kB
// The page's end of the MCP bridge. tools/mcp/server.mjs, which Claude Code (or another MCP client) runs on
// this computer, serves a WebSocket on 127.0.0.1; this page connects to it when asked to: ?bridge (or
// ?bridge=PORT) in its URL, or the Agent tab's Connect button. The server sends the client's tool calls; the
// page runs them one at a time, with the tools its own agent uses, and sends each result back.
//
// Messages, as JSON:
// page -> server: {type: "hello", version, tools, guide, info}, {type: "result", id, result}, {type: "progress", id, message}
// server -> page: {type: "call", id, name, args}, {type: "cancel", id}, {type: "client", name} (the MCP
// client's), {type: "tick"} (while a call runs, so that a hidden tab, which gets no animation frames, still
// steps the physics), {type: "replaced"} (another tab connected to the server instead of this one),
// {type: "perception", gemini_key} (the server's GEMINI_API_KEY, for locate: kept in memory while connected).
export const DEFAULT_PORT = 8770;
export class Bridge {
/**
* `handlers`: hello() -> {tools, guide, info}; call(name, args) -> Promise of a result; cancel() stops the running
* skill; activity() -> what the robot is doing, for progress; pump() steps the physics of a hidden tab.
* `on` tells the panel: status(state) ("off", "connecting", "waiting", "connected", "replaced"),
* call(name, args), result(name, result).
*/
constructor(handlers, on = {}) {
this.handlers = handlers;
this.on = on;
this.port = DEFAULT_PORT;
this.ws = null;
this.state = "off";
this.wanted = false; // connect, and connect again after the server goes away
this.replaced = false;
this.tries = 0;
this.retry = null;
this.queue = Promise.resolve(); // one call at a time: two skills at once would cancel each other
this.current = null; // the id of the call running
this.cancelled = new Set(); // calls cancelled while they waited their turn
}
get connected() {
return this.ws?.readyState === WebSocket.OPEN;
}
/** Connect to the server on `port`, and keep trying until it answers. */
connect(port = this.port) {
this.port = port;
this.wanted = true;
this.replaced = false;
this.tries = 0;
clearTimeout(this.retry);
if (this.ws) return; // connecting or connected already
this.#open();
}
disconnect() {
this.wanted = false;
this.geminiKey = null;
clearTimeout(this.retry);
const ws = this.ws;
this.ws = null;
ws?.close();
if (this.current !== null) this.handlers.cancel();
this.#status("off");
}
#status(state) {
this.state = state;
this.on.status?.(state);
}
#open() {
const ws = new WebSocket(`ws://127.0.0.1:${this.port}`);
let opened = false;
this.ws = ws;
this.#status(this.tries ? "waiting" : "connecting");
ws.onopen = () => {
opened = true;
this.tries = 0;
ws.send(JSON.stringify({ type: "hello", version: 1, ...this.handlers.hello() }));
this.#status("connected");
};
ws.onmessage = (event) => {
let message;
try {
message = JSON.parse(event.data);
} catch {
return;
}
this.#message(ws, message);
};
ws.onerror = () => {}; // onclose follows
ws.onclose = () => {
if (this.ws !== ws) return; // disconnected on purpose
this.ws = null;
this.geminiKey = null;
if (this.current !== null) this.handlers.cancel(); // nobody waits for it any more
if (!this.wanted || this.replaced) return this.#status(this.replaced ? "replaced" : "off");
this.tries++;
this.#status("waiting");
if (!opened) this.#checkAccess();
this.retry = setTimeout(() => this.#open(), Math.min(5000, 1000 * this.tries));
};
}
/**
* A page from another site than this computer reaches 127.0.0.1 only if the person lets it (Chrome's local
* network access checks): `access` is "granted", "prompt" or "denied" where the browser says.
*/
async #checkAccess() {
if (["127.0.0.1", "localhost", "[::1]"].includes(location.hostname)) return;
for (const name of ["loopback-network", "local-network-access"]) {
try {
const { state } = await navigator.permissions.query({ name });
if (state !== this.access) {
this.access = state;
this.on.status?.(this.state);
}
return;
} catch {
// not this browser's name for it
}
}
}
#message(ws, message) {
if (message.type === "tick") return void this.handlers.pump();
if (message.type === "replaced") {
this.replaced = true;
return;
}
if (message.type === "cancel") {
if (this.current === message.id) this.handlers.cancel();
else this.cancelled.add(message.id);
return;
}
if (message.type === "client") {
this.client = message.name; // the MCP client's name, as it gave it to the server
return void this.on.status?.(this.state);
}
if (message.type === "perception") {
this.geminiKey = typeof message.gemini_key === "string" && message.gemini_key ? message.gemini_key : null;
return void this.on.status?.(this.state);
}
if (message.type === "call") this.queue = this.queue.then(() => this.#run(ws, message)).catch((error) => console.error(error));
}
async #run(ws, { id, name, args }) {
if (this.cancelled.delete(id) || ws !== this.ws) return this.#send(ws, { type: "result", id, result: { ok: false, message: "cancelled before it started" } });
this.current = id;
this.on.call?.(name, args ?? {});
let said = null;
const progress = setInterval(() => {
const message = this.handlers.activity();
if (message && message !== said) this.#send(ws, { type: "progress", id, message: (said = message) });
}, 1000);
let result;
try {
result = await this.handlers.call(name, args ?? {});
} catch (error) {
result = { ok: false, message: error.message };
} finally {
clearInterval(progress);
this.current = null;
}
this.on.result?.(name, result ?? {});
this.#send(ws, { type: "result", id, result: result ?? {} });
}
#send(ws, message) {
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
}
}
/** The port to connect to when the page's URL asks for the bridge (?bridge or ?bridge=PORT), else null. */
export function bridgeRequested(url = location.href) {
const params = new URL(url).searchParams;
if (!params.has("bridge")) return null;
const port = Number(params.get("bridge"));
return Number.isInteger(port) && port > 0 && port < 65536 ? port : DEFAULT_PORT;
}