Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(ruvocal): off-main-thread WASM MCP via Web Worker (opt-in)

Reuven4b6186c70d57
diff --git a/ruflo/src/ruvocal/src/lib/stores/wasmMcp.ts b/ruflo/src/ruvocal/src/lib/stores/wasmMcp.ts
index 1991de7be9..f239179aad 100644
--- a/ruflo/src/ruvocal/src/lib/stores/wasmMcp.ts
+++ b/ruflo/src/ruvocal/src/lib/stores/wasmMcp.ts
@@ -7,6 +7,7 @@
import { writable, derived, get } from "svelte/store";
import { browser } from "$app/environment";
import { loadWasm, isWasmLoaded, getWasm } from "$lib/wasm";
+import { isWorkerEnabled, callMcpInWorker } from "$lib/wasm/workerClient";
import type { WasmMcpServer, WasmGallery, GalleryTemplate, SearchResult } from "$lib/wasm";
import * as idb from "$lib/wasm/idb";
@@ -161,6 +162,23 @@ function callMcpInternal(
* Call an MCP method on the WASM server
*/
export async function callMcp(method: string, params?: unknown): Promise<JsonRpcResponse> {
+ // Off-main-thread path (opt-in via ?worker=1 or
+ // localStorage.setItem("ruflo:wasm-worker","true")) β€” see workerClient.ts.
+ if (isWorkerEnabled()) {
+ try {
+ return (await callMcpInWorker(method, params)) as JsonRpcResponse;
+ } catch (err) {
+ return {
+ jsonrpc: "2.0",
+ id: null,
+ error: {
+ code: -32603,
+ message: err instanceof Error ? err.message : "worker call failed",
+ },
+ };
+ }
+ }
+
const state = get(wasmMcpState);
if (!state.loaded || !state.mcpServer) {
diff --git a/ruflo/src/ruvocal/src/lib/wasm/wasm.worker.ts b/ruflo/src/ruvocal/src/lib/wasm/wasm.worker.ts
new file mode 100644
index 0000000000..5e9d85eb26
--- /dev/null
+++ b/ruflo/src/ruvocal/src/lib/wasm/wasm.worker.ts
@@ -0,0 +1,134 @@
+/**
+ * WASM MCP Web Worker β€” Off-main-thread JSON-RPC server.
+ *
+ * Owns one WasmMcpServer + one WasmGallery instance and proxies the MCP
+ * surface (handle_message) plus the most common gallery operations
+ * (list / search / count / setActive / getActive) so the main thread
+ * never blocks on the ~300ms WASM compile or on tool execution.
+ *
+ * Wire format (request β†’ main β†’ worker):
+ * { id: number, method: "load" | "callMcp" | "gallery.X", params?: unknown }
+ *
+ * Wire format (response β†’ worker β†’ main):
+ * { id: number, result?: unknown, error?: string }
+ *
+ * Side-channel: { id: 0, type: "log", level, args } β€” forwarded console output.
+ */
+
+import { loadWasm } from "./index";
+import type { WasmMcpServer, WasmGallery, GalleryTemplate, SearchResult } from "./index";
+
+interface WorkerRequest {
+ id: number;
+ method: string;
+ params?: unknown;
+}
+
+interface WorkerResponse {
+ id: number;
+ result?: unknown;
+ error?: string;
+}
+
+let mcpServer: WasmMcpServer | null = null;
+let gallery: WasmGallery | null = null;
+let loadPromise: Promise<void> | null = null;
+
+const ctx = self as unknown as Worker;
+
+function reply(id: number, result?: unknown, error?: string) {
+ const msg: WorkerResponse = { id };
+ if (error !== undefined) msg.error = error;
+ else msg.result = result;
+ ctx.postMessage(msg);
+}
+
+async function ensureLoaded(): Promise<void> {
+ if (mcpServer && gallery) return;
+ if (loadPromise) return loadPromise;
+
+ loadPromise = (async () => {
+ const wasm = await loadWasm();
+ if (!wasm) throw new Error("Failed to load WASM module in worker");
+ mcpServer = new wasm.WasmMcpServer();
+ gallery = new wasm.WasmGallery();
+
+ // Initialize the JSON-RPC handshake the same way the store does.
+ const initReq = JSON.stringify({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: "2024-11-05",
+ clientInfo: { name: "ruvocal-ui-worker", version: "1.0.0" },
+ },
+ });
+ const initRes = JSON.parse(mcpServer.handle_message(initReq));
+ if (initRes.error) throw new Error(initRes.error.message ?? "MCP init failed");
+ })();
+
+ await loadPromise;
+}
+
+ctx.addEventListener("message", async (event: MessageEvent<WorkerRequest>) => {
+ const { id, method, params } = event.data;
+
+ try {
+ await ensureLoaded();
+ if (!mcpServer || !gallery) throw new Error("WASM not initialized");
+
+ switch (method) {
+ case "load":
+ reply(id, true);
+ return;
+
+ case "callMcp": {
+ const message = JSON.stringify(params);
+ const response = mcpServer.handle_message(message);
+ reply(id, JSON.parse(response));
+ return;
+ }
+
+ case "gallery.list":
+ reply(id, gallery.list() as GalleryTemplate[]);
+ return;
+
+ case "gallery.listByCategory":
+ reply(id, gallery.listByCategory(params as string) as GalleryTemplate[]);
+ return;
+
+ case "gallery.search":
+ reply(id, gallery.search(params as string) as SearchResult[]);
+ return;
+
+ case "gallery.get":
+ reply(id, gallery.get(params as string) as GalleryTemplate);
+ return;
+
+ case "gallery.setActive":
+ gallery.setActive(params as string);
+ reply(id, true);
+ return;
+
+ case "gallery.getActive":
+ reply(id, gallery.getActive());
+ return;
+
+ case "gallery.count":
+ reply(id, gallery.count());
+ return;
+
+ case "gallery.getCategories":
+ reply(id, gallery.getCategories());
+ return;
+
+ default:
+ reply(id, undefined, `Unknown method: ${method}`);
+ }
+ } catch (err) {
+ reply(id, undefined, err instanceof Error ? err.message : String(err));
+ }
+});
+
+// Signal readiness to anyone listening for it.
+ctx.postMessage({ id: 0, type: "ready" });
diff --git a/ruflo/src/ruvocal/src/lib/wasm/workerClient.ts b/ruflo/src/ruvocal/src/lib/wasm/workerClient.ts
new file mode 100644
index 0000000000..53da8930c2
--- /dev/null
+++ b/ruflo/src/ruvocal/src/lib/wasm/workerClient.ts
@@ -0,0 +1,166 @@
+/**
+ * Main-thread client for the WASM MCP Web Worker.
+ *
+ * Lazily spawns the worker, multiplexes requests with auto-incrementing IDs,
+ * and exposes a typed Promise-returning surface that mirrors the subset of
+ * WasmMcpServer / WasmGallery the chat UI needs.
+ *
+ * Behind a feature flag so the existing main-thread code path remains the
+ * default until we've broken everything in `wasmMcp.ts` over to the worker.
+ * Toggle with `localStorage.setItem("ruflo:wasm-worker", "true")` from the
+ * browser console, or pass `?worker=1` on the URL.
+ */
+
+import { browser } from "$app/environment";
+import type { GalleryTemplate, SearchResult } from "./index";
+
+interface PendingRequest {
+ resolve: (value: unknown) => void;
+ reject: (reason: Error) => void;
+}
+
+interface JsonRpcRequest {
+ jsonrpc: "2.0";
+ id: number | string;
+ method: string;
+ params?: unknown;
+}
+
+interface JsonRpcResponse {
+ jsonrpc: "2.0";
+ id: number | string | null;
+ result?: unknown;
+ error?: { code: number; message: string; data?: unknown };
+}
+
+let worker: Worker | null = null;
+let nextId = 1;
+const pending = new Map<number, PendingRequest>();
+let readyPromise: Promise<void> | null = null;
+
+export function isWorkerEnabled(): boolean {
+ if (!browser) return false;
+ try {
+ const flag = localStorage.getItem("ruflo:wasm-worker");
+ if (flag === "true") return true;
+ const params = new URLSearchParams(window.location.search);
+ return params.get("worker") === "1";
+ } catch {
+ return false;
+ }
+}
+
+function ensureWorker(): Worker {
+ if (worker) return worker;
+ // Vite resolves `?worker` import to a Worker constructor.
+ // Using new URL() so vite-plugin-svelte picks it up at build time.
+ worker = new Worker(new URL("./wasm.worker.ts", import.meta.url), {
+ type: "module",
+ name: "ruflo-wasm-mcp",
+ });
+
+ worker.addEventListener("message", (event: MessageEvent) => {
+ const data = event.data as { id: number; result?: unknown; error?: string; type?: string };
+ if (data?.type === "ready") return; // readiness ping
+ if (typeof data?.id !== "number") return;
+ const slot = pending.get(data.id);
+ if (!slot) return;
+ pending.delete(data.id);
+ if (data.error) slot.reject(new Error(data.error));
+ else slot.resolve(data.result);
+ });
+
+ worker.addEventListener("error", (e: ErrorEvent) => {
+ console.error("[wasm.worker] error:", e.message);
+ // Reject all in-flight requests so callers don't hang.
+ for (const [, slot] of pending) slot.reject(new Error(`worker error: ${e.message}`));
+ pending.clear();
+ });
+
+ return worker;
+}
+
+function call<T = unknown>(method: string, params?: unknown): Promise<T> {
+ const w = ensureWorker();
+ const id = nextId++;
+ return new Promise<T>((resolve, reject) => {
+ pending.set(id, { resolve: resolve as (v: unknown) => void, reject });
+ w.postMessage({ id, method, params });
+ });
+}
+
+/**
+ * Ensure the worker has finished its WASM load. Idempotent β€” first caller
+ * pays the ~300ms compile cost off the main thread; subsequent calls are
+ * no-ops that resolve when the same in-flight load finishes.
+ */
+export function ensureReady(): Promise<void> {
+ if (!readyPromise) readyPromise = call<boolean>("load").then(() => undefined);
+ return readyPromise;
+}
+
+/**
+ * Send a JSON-RPC message to the WASM MCP server in the worker.
+ */
+export async function callMcpInWorker(
+ method: string,
+ params?: unknown
+): Promise<JsonRpcResponse> {
+ await ensureReady();
+ const request: JsonRpcRequest = {
+ jsonrpc: "2.0",
+ id: nextId++,
+ method,
+ params,
+ };
+ return call<JsonRpcResponse>("callMcp", request);
+}
+
+export async function listTemplatesInWorker(): Promise<GalleryTemplate[]> {
+ await ensureReady();
+ return call<GalleryTemplate[]>("gallery.list");
+}
+
+export async function searchTemplatesInWorker(query: string): Promise<SearchResult[]> {
+ await ensureReady();
+ return call<SearchResult[]>("gallery.search", query);
+}
+
+export async function getTemplateInWorker(id: string): Promise<GalleryTemplate> {
+ await ensureReady();
+ return call<GalleryTemplate>("gallery.get", id);
+}
+
+export async function setActiveTemplateInWorker(id: string): Promise<void> {
+ await ensureReady();
+ await call("gallery.setActive", id);
+}
+
+export async function getActiveTemplateInWorker(): Promise<string | null> {
+ await ensureReady();
+ return call<string | null>("gallery.getActive");
+}
+
+export async function getCategoriesInWorker(): Promise<Record<string, number>> {
+ await ensureReady();
+ return call<Record<string, number>>("gallery.getCategories");
+}
+
+export async function templateCountInWorker(): Promise<number> {
+ await ensureReady();
+ return call<number>("gallery.count");
+}
+
+/**
+ * Tear down the worker (for tests or explicit cleanup).
+ */
+export function disposeWorker(): void {
+ if (worker) {
+ worker.terminate();
+ worker = null;
+ }
+ for (const [, slot] of pending) slot.reject(new Error("worker disposed"));
+ pending.clear();
+ readyPromise = null;
+ nextId = 1;
+}