// End-to-end test of the host side: a fake extension talks native messaging // to the real native-host.js, and a real MCP client drives mcp-server.js. // Covers browser discovery/selection, routing, batching and navigate without // a tabId. Runs on a scratch endpoint dir so live browsers are untouched. import { test, before, after } from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { endpointPath } from "../endpoint.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; const HOST = path.join(path.dirname(fileURLToPath(import.meta.url)), ".."); const DIR = fs.mkdtempSync(path.join(os.tmpdir(), "ocb-test-")); process.env.OCB_DIR = DIR; const env = { ...process.env, OCB_DIR: DIR }; // A fake browser: native host process + a tiny tool implementation. function fakeBrowser(deviceId, name) { const proc = spawn(process.execPath, [path.join(HOST, "native-host.js")], { env, stdio: ["pipe", "pipe", "inherit"] }); const seen = []; let buf = Buffer.alloc(0); const send = (obj) => { const b = Buffer.from(JSON.stringify(obj)); const h = Buffer.alloc(4); h.writeUInt32LE(b.length); proc.stdin.write(Buffer.concat([h, b])); }; const reply = (msg, result) => send({ id: msg.id, type: "tool_response", result }); proc.stdout.on("data", (chunk) => { buf = Buffer.concat([buf, chunk]); while (buf.length >= 4) { const len = buf.readUInt32LE(0); if (buf.length < 4 + len) break; const msg = JSON.parse(buf.subarray(4, 4 + len).toString()); buf = buf.subarray(4 + len); seen.push(msg); if (msg.type === "connect_request") { if (name === "Work") send({ id: msg.id, type: "connect_response", accepted: true, name: "Work Chrome" }); continue; } if (msg.type !== "tool_request") continue; const { tool, args } = msg; if (tool === "tabs_context_mcp") { reply(msg, { content: [{ type: "text", text: JSON.stringify({ availableTabs: [{ tabId: 7, title: "t", url: "about:blank" }], tabGroupId: 1 }) }], context: "\n\nTab Context:\n- Available tabs:\n • tabId 7: \"t\" (\"about:blank\")" }); } else if (tool === "navigate") { reply(msg, { content: [{ type: "text", text: `Navigated ${args.tabId} to ${args.url} in ${name}` }], context: `\n\nTab Context:\n- Executed on tabId: ${args.tabId}\n- Available tabs:\n • tabId 7: "t" ("${args.url}")` }); } else if (tool === "computer" && args.action === "screenshot") { reply(msg, { content: [{ type: "text", text: "shot" }, { type: "image", data: Buffer.from("img").toString("base64"), mimeType: "image/jpeg" }] }); } else if (tool === "find") { reply(msg, { content: [{ type: "text", text: "nothing" }], isError: true }); } else { reply(msg, { content: [{ type: "text", text: `${tool} ok` }] }); } } }); send({ type: "hello", deviceId, name, browser: "Chrome", platform: "mac", version: "test" }); return { proc, seen, kill: () => proc.kill() }; } async function mcpClient() { const client = new Client({ name: "test", version: "1" }); await client.connect(new StdioClientTransport({ command: process.execPath, args: [path.join(HOST, "mcp-server.js")], env })); return client; } const textOf = (r) => r.content.filter((c) => c.type === "text").map((c) => c.text).join("\n"); const waitFor = async (cond, ms = 3000) => { const end = Date.now() + ms; while (Date.now() < end) { if (cond()) return; await new Promise((r) => setTimeout(r, 50)); } throw new Error("timed out"); }; let home, work, client; before(async () => { home = fakeBrowser("dev-home", "Home"); await waitFor(() => fs.existsSync(path.join(DIR, "dev-home.json")) && fs.existsSync(endpointPath("dev-home"))); client = await mcpClient(); }); after(async () => { await client?.close(); home?.kill(); work?.kill(); fs.rmSync(DIR, { recursive: true, force: true }); }); test("advertises the official tool surface", async () => { const { tools } = await client.listTools(); const names = tools.map((t) => t.name).sort(); assert.deepEqual(names, [ "browser_batch", "computer", "file_upload", "find", "form_input", "get_page_text", "gif_creator", "javascript_tool", "list_connected_browsers", "navigate", "read_console_messages", "read_network_requests", "read_page", "resize_window", "select_browser", "shortcuts_execute", "shortcuts_list", "switch_browser", "tabs_close_mcp", "tabs_context_mcp", "tabs_create_mcp", "upload_image" ]); const computer = tools.find((t) => t.name === "computer"); assert.ok(computer.inputSchema.properties.action_summary); assert.ok(computer.inputSchema.properties.scale); }); test("one browser: tools just work and carry the session id", async () => { const r = await client.callTool({ name: "tabs_context_mcp", arguments: { createIfEmpty: true } }); assert.match(textOf(r), /availableTabs/); const req = home.seen.find((m) => m.tool === "tabs_context_mcp"); assert.ok(req.session, "session id forwarded"); assert.equal(req.args.createIfEmpty, true); }); test("navigate without tabId uses the group's first tab and appends context", async () => { const r = await client.callTool({ name: "navigate", arguments: { url: "example.com" } }); assert.match(r.content[0].text, /Navigated 7 to example.com in Home/); assert.match(r.content[1].text, /^\n\nTab Context:\n- Executed on tabId: 7/); const back = await client.callTool({ name: "navigate", arguments: { url: "back" } }); assert.equal(back.isError, true); }); test("browser_batch runs in order, interleaves images, stops on first error", async () => { const r = await client.callTool({ name: "browser_batch", arguments: { actions: [ { name: "navigate", input: { url: "a.com", tabId: 7 } }, { name: "computer", input: { action: "screenshot", tabId: 7 } }, { name: "find", input: { query: "x", tabId: 7 } }, { name: "navigate", input: { url: "never.com", tabId: 7 } } ] } }); assert.equal(r.isError, true); // As in the official extension: one text, images left out. assert.deepEqual(r.content.map((c) => c.type), ["text"]); assert.equal( r.content[0].text, "[navigate] Navigated 7 to a.com in Home\n[computer:screenshot] shot [Image omitted due to error]\n\n" + "actions[2] (find) failed: nothing (2 completed, 1 remaining)" ); const okRun = await client.callTool({ name: "browser_batch", arguments: { actions: [{ name: "navigate", input: { url: "b.com", tabId: 7 } }, { name: "computer", input: { action: "screenshot", tabId: 7 } }] } }); assert.deepEqual(okRun.content.map((c) => c.type), ["text", "text", "image", "text"]); assert.match(okRun.content[3].text, /^\n\nTab Context:/); assert.ok(!home.seen.some((m) => m.args?.url === "never.com")); const nested = await client.callTool({ name: "browser_batch", arguments: { actions: [{ name: "navigate", input: { url: "x.com" } }] } }); assert.match(textOf(nested), /requires an explicit tabId/); }); test("file_upload rejects missing and oversized files before reaching the browser", async () => { const r = await client.callTool({ name: "file_upload", arguments: { tabId: 7, ref: "ref_1", paths: ["/nope/missing.txt"] } }); assert.equal(r.isError, true); assert.match(textOf(r), /File not found/); const big = path.join(DIR, "big.bin"); fs.writeFileSync(big, Buffer.alloc(11 * 1024 * 1024)); const r2 = await client.callTool({ name: "file_upload", arguments: { tabId: 7, ref: "ref_1", paths: [big] } }); assert.match(textOf(r2), /under 10 MB/); }); test("save_to_disk writes the image and reports the path", async () => { const r = await client.callTool({ name: "computer", arguments: { action: "screenshot", tabId: 7, save_to_disk: true } }); const m = textOf(r).match(/Saved to disk: (.+)$/m); assert.ok(m, textOf(r)); assert.equal(fs.readFileSync(m[1].trim()).toString(), "img"); fs.unlinkSync(m[1].trim()); const req = home.seen.filter((x) => x.args?.action === "screenshot").pop(); assert.equal(req.args.save_to_disk, undefined, "not forwarded to the extension"); }); test("several browsers: requires a choice, then select_browser / switch_browser route correctly", async () => { // A fresh session (new MCP server) so nothing is selected yet. const c2 = await mcpClient(); work = fakeBrowser("dev-work", "Work"); await waitFor(() => fs.existsSync(endpointPath("dev-work"))); const blocked = await c2.callTool({ name: "navigate", arguments: { url: "x.com", tabId: 7 } }); assert.equal(blocked.isError, true); assert.match(textOf(blocked), /2 browsers are connected and none is selected/); const list = JSON.parse(textOf(await c2.callTool({ name: "list_connected_browsers", arguments: {} }))); assert.deepEqual(list.browsers.map((b) => b.deviceId).sort(), ["dev-home", "dev-work"]); assert.ok(list.browsers.every((b) => b.onThisComputer && b.inUse === false)); const sel = await c2.callTool({ name: "select_browser", arguments: { deviceId: "dev-home" } }); assert.match(textOf(sel), /Selected Home/); assert.match(textOf(await c2.callTool({ name: "navigate", arguments: { url: "x.com", tabId: 7 } })), /in Home/); const sw = await c2.callTool({ name: "switch_browser", arguments: {} }); assert.match(textOf(sw), /Connected to Work Chrome/); assert.match(textOf(await c2.callTool({ name: "navigate", arguments: { url: "y.com", tabId: 7 } })), /in Work/); assert.ok(home.seen.some((m) => m.type === "connect_cancel"), "the other browser's prompt is cancelled"); // The first session kept its own browser choice. assert.match(textOf(await client.callTool({ name: "navigate", arguments: { url: "z.com", tabId: 7 } })), /in Home/); await c2.close(); }); test("a browser going away is reported, not hung on", async () => { work.kill(); await waitFor(() => !fs.existsSync(path.join(DIR, "dev-work.json"))); const c3 = await mcpClient(); // Only Home remains, so it's used without asking. assert.match(textOf(await c3.callTool({ name: "navigate", arguments: { url: "q.com", tabId: 7 } })), /in Home/); await c3.close(); });