Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Closing lent MCP servers waits for them to exit
milind-soni7b6a47080fd3
diff --git a/electron/lent-mcp.d.mts b/electron/lent-mcp.d.mtsindex ed6b9e0f12..025c204b11 100644--- a/electron/lent-mcp.d.mts+++ b/electron/lent-mcp.d.mts@@ -14,5 +14,5 @@ export function createLentMcp(options?: {fetch?: typeof fetch;}): {call(operation: { action: "mcp_tools" | "mcp_call"; server: LentMcpServer; tool_name?: string; arguments?: Record<string, unknown> }, signal: AbortSignal): Promise<unknown>;- close(): void;+ close(): Promise<void>;};diff --git a/electron/lent-mcp.mjs b/electron/lent-mcp.mjsindex 2271e73071..b0dca6c46f 100644--- a/electron/lent-mcp.mjs+++ b/electron/lent-mcp.mjs@@ -149,7 +149,13 @@ function stdioClient(server, { environment, home }) {});},notify(method) { if (!closed) write({ jsonrpc: "2.0", method }); },- close() { lines.close(); end(failure(`${server.name} stopped`)); },+ close() {+ lines.close();+ const exited = child.exitCode !== null || child.signalCode !== null || !child.pid ? Promise.resolve()+ : new Promise(resolve => { const timer = setTimeout(resolve, 5_000); child.once("exit", () => { clearTimeout(timer); resolve(); }); });+ end(failure(`${server.name} stopped`));+ return exited;+ },};}@@ -217,7 +223,7 @@ function httpClient(server, { fetch: fetchImpl }) {request: (method, params, signal, ms) => send({ jsonrpc: "2.0", id: ++sequence, method, params }, signal, ms),notify(method) { void send({ jsonrpc: "2.0", method }, new AbortController().signal, 10_000).catch(() => {}); },started(version) { protocol = typeof version === "string" ? version : PROTOCOL; },- close() { session = null; },+ close() { session = null; return Promise.resolve(); },};}@@ -225,7 +231,12 @@ function httpClient(server, { fetch: fetchImpl }) {* one unused for ten minutes is stopped. */export function createLentMcp({ environment = async () => ({ ...inheritedEnvironment(), PATH: await commandPath() }), home = os.homedir(), fetch: fetchImpl = globalThis.fetch } = {}) {const running = new Map();- const stop = name => { const live = running.get(name); if (!live) return; clearTimeout(live.idle); live.client.close(); running.delete(name); };+ const stop = name => {+ const live = running.get(name);+ if (!live) return Promise.resolve();+ clearTimeout(live.idle); running.delete(name);+ return live.client.close();+ };const ready = async (server, signal) => {const key = hash(server);const known = running.get(server.name);@@ -277,6 +288,7 @@ export function createLentMcp({ environment = async () => ({ ...inheritedEnvironif (typeof operation.tool_name !== "string" || !operation.tool_name) throw failure("Name the tool to call");return use(server, signal, client => client.request("tools/call", { name: operation.tool_name, arguments: operation.arguments ?? {} }, signal, CALL_MS));},- close() { for (const name of running.keys()) stop(name); },+ /** Resolves once every server it started has exited, or after five seconds. */+ close: () => Promise.all([...running.keys()].map(stop)).then(() => {}),};}diff --git a/electron/lent-mcp.node-test.mjs b/electron/lent-mcp.node-test.mjsindex 29d72e7ac3..ca41dbdf09 100644--- a/electron/lent-mcp.node-test.mjs+++ b/electron/lent-mcp.node-test.mjs@@ -26,15 +26,18 @@ readline.createInterface({ input: process.stdin }).on("line", line => {});`;+/** One step of a test, refused after 20 seconds by name, so a hang says where it is. */+const step = (name, promise) => Promise.race([promise, new Promise((_, reject) => setTimeout(() => reject(new Error(`${name} took over 20 s`)), 20_000).unref())]);+async function stdioFixture(t) {const dir = await realpath(await mkdtemp(path.join(tmpdir(), "omb-lent-mcp-")));- t.after(() => rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }));const script = path.join(dir, "server.mjs");await writeFile(script, SERVER_SCRIPT);const home = path.join(dir, "home");await mkdir(home);const lent = createLentMcp({ environment: () => ({ ...inheritedEnvironment(), PATH: process.env.PATH ?? "" }), home });- t.after(() => lent.close());+ // Windows keeps a running process's working folder: the servers end before their folder goes.+ t.after(async () => { await lent.close(); await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); });return { dir, home, script, lent, server: { name: "notes", command: process.execPath, args: [script], env: { NOTES_TOKEN: "saved-env-key" } } };}@@ -79,16 +82,16 @@ test("the executor refuses before anything starts when the grant doesn't allow itest("a command server starts once, from the home folder, with its saved key, and keeps running between calls", async t => {const { lent, server, home } = await stdioFixture(t);- const listed = await lent.call({ action: "mcp_tools", server }, signal());+ const listed = await step("listing", lent.call({ action: "mcp_tools", server }, signal()));assert.deepEqual(listed.tools.map(tool => tool.name), ["whoami", "fail"], "every page");- const first = JSON.parse((await lent.call({ action: "mcp_call", server, tool_name: "whoami", arguments: {} }, signal())).content[0].text);+ const first = JSON.parse((await step("the first call", lent.call({ action: "mcp_call", server, tool_name: "whoami", arguments: {} }, signal()))).content[0].text);assert.equal(first.key, "saved-env-key");assert.equal(await realpath(first.cwd), await realpath(home));- await assert.rejects(lent.call({ action: "mcp_call", server, tool_name: "fail" }, signal()), /no such thing/);- const again = JSON.parse((await lent.call({ action: "mcp_call", server, tool_name: "whoami" }, signal())).content[0].text);+ await assert.rejects(step("a failing call", lent.call({ action: "mcp_call", server, tool_name: "fail" }, signal())), /no such thing/);+ const again = JSON.parse((await step("the call after it", lent.call({ action: "mcp_call", server, tool_name: "whoami" }, signal()))).content[0].text);assert.equal(again.pid, first.pid, "an error from the server leaves it running");const changed = { ...server, env: { NOTES_TOKEN: "new-key" } };- const fresh = JSON.parse((await lent.call({ action: "mcp_call", server: changed, tool_name: "whoami" }, signal())).content[0].text);+ const fresh = JSON.parse((await step("the changed server's call", lent.call({ action: "mcp_call", server: changed, tool_name: "whoami" }, signal()))).content[0].text);assert.notEqual(fresh.pid, first.pid, "a changed server starts anew");assert.equal(fresh.key, "new-key");});@@ -110,7 +113,7 @@ test("a server that refuses to start is started again on the next call, not kepttest("a command server that can't start says so by its program's name, never with its keys", async t => {const { lent } = await stdioFixture(t);const missing = { name: "notes", command: path.join(tmpdir(), "omb-no-such-program"), args: [], env: { NOTES_TOKEN: "never-echoed" } };- await assert.rejects(lent.call({ action: "mcp_tools", server: missing }, signal()), error => {+ await assert.rejects(step("a missing program", lent.call({ action: "mcp_tools", server: missing }, signal())), error => {assert.match(error.message, /notes could not start: omb-no-such-program is not on this computer/);assert.doesNotMatch(error.message, /never-echoed/);return true;