Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(notfair-cmo): add workspace browser tool for agents

Yuting Zhonga5436d05d04c
diff --git a/notfair-cmo/package.json b/notfair-cmo/package.json
index 417dad11..db202430 100644
--- a/notfair-cmo/package.json
+++ b/notfair-cmo/package.json
@@ -44,6 +44,7 @@
"next": "^16.2.6",
"next-themes": "^0.4.6",
"open": "^10.1.0",
+ "playwright-core": "^1.60.0",
"radix-ui": "^1.4.3",
"react": "^19.0.0",
"react-dom": "^19.0.0",
diff --git a/notfair-cmo/pnpm-lock.yaml b/notfair-cmo/pnpm-lock.yaml
index f7195005..aab638f4 100644
--- a/notfair-cmo/pnpm-lock.yaml
+++ b/notfair-cmo/pnpm-lock.yaml
@@ -62,6 +62,9 @@ importers:
open:
specifier: ^10.1.0
version: 10.2.0
+ playwright-core:
+ specifier: ^1.60.0
+ version: 1.60.0
radix-ui:
specifier: ^1.4.3
@@ -3505,6 +3508,11 @@ packages:
resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==}
+ engines: {node: '>=18'}
+ hasBin: true
+
resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==}
engines: {node: '>= 0.4'}
@@ -7837,6 +7845,8 @@ snapshots:
+
diff --git a/notfair-cmo/src/app/api/browser/launch/route.test.ts b/notfair-cmo/src/app/api/browser/launch/route.test.ts
new file mode 100644
index 00000000..d1d1e610
--- /dev/null
+++ b/notfair-cmo/src/app/api/browser/launch/route.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+
+vi.mock("@/server/browser/session", () => ({
+ getOrLaunchBrowser: vi.fn(async () => ({})),
+ getSessionStatus: vi.fn(() => ({
+ projectSlug: "acme",
+ running: true,
+ cdpPort: 19042,
+ userDataDir: "/tmp/profile",
+ launchedAt: 1_000,
+ uptimeMs: 5_000,
+ })),
+ registerShutdownHooks: vi.fn(),
+}));
+
+vi.mock("@/server/browser/tabs", () => ({
+ openTab: vi.fn(async (_slug: string, opts: { label?: string; url?: string }) => ({
+ id: opts.label ?? "t1",
+ label: opts.label ?? "t1",
+ url: opts.url ?? "about:blank",
+ title: "",
+ })),
+}));
+
+import { POST } from "./route";
+import * as session from "@/server/browser/session";
+import * as tabs from "@/server/browser/tabs";
+
+function makeReq(body: unknown): Request {
+ return new Request("http://localhost/api/browser/launch", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("POST /api/browser/launch", () => {
+ it("400s when project_slug is missing", async () => {
+ const res = await POST(makeReq({}));
+ expect(res.status).toBe(400);
+ });
+
+ it("launches the browser headed by default and returns status", async () => {
+ const res = await POST(makeReq({ project_slug: "acme" }));
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.status.running).toBe(true);
+ expect(session.getOrLaunchBrowser).toHaveBeenCalledWith("acme", { headless: false });
+ expect(session.registerShutdownHooks).toHaveBeenCalledOnce();
+ });
+
+ it("honors headless=true when provided", async () => {
+ await POST(makeReq({ project_slug: "acme", headless: true }));
+ expect(session.getOrLaunchBrowser).toHaveBeenCalledWith("acme", { headless: true });
+ });
+
+ it("opens a signin tab when signin_url is provided", async () => {
+ const res = await POST(
+ makeReq({ project_slug: "acme", signin_url: "https://accounts.google.com" }),
+ );
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.signin_tab).toEqual({ id: "signin", url: "https://accounts.google.com" });
+ expect(tabs.openTab).toHaveBeenCalledWith("acme", {
+ label: "signin",
+ url: "https://accounts.google.com",
+ });
+ });
+
+ it("500s with the error message when launch fails", async () => {
+ (session.getOrLaunchBrowser as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error("Chrome not found"),
+ );
+ const res = await POST(makeReq({ project_slug: "acme" }));
+ expect(res.status).toBe(500);
+ const body = await res.json();
+ expect(body.error).toBe("Chrome not found");
+ });
+});
diff --git a/notfair-cmo/src/app/api/browser/launch/route.ts b/notfair-cmo/src/app/api/browser/launch/route.ts
new file mode 100644
index 00000000..a7ce9a97
--- /dev/null
+++ b/notfair-cmo/src/app/api/browser/launch/route.ts
@@ -0,0 +1,60 @@
+import { NextResponse } from "next/server";
+
+import {
+ getOrLaunchBrowser,
+ getSessionStatus,
+ registerShutdownHooks,
+} from "@/server/browser/session";
+import { openTab } from "@/server/browser/tabs";
+
+export const dynamic = "force-dynamic";
+export const runtime = "nodejs";
+
+/**
+ * Launch (or attach to) the workspace browser for a project.
+ *
+ * Headed by default — onboarding uses this to pop Chrome open so the user
+ * can sign into Google, Meta, etc. Once cookies persist in the workspace
+ * user-data-dir, agents on subsequent runs inherit the logged-in state
+ * automatically.
+ *
+ * POST body:
+ * { project_slug: string, signin_url?: string, headless?: boolean }
+ *
+ * Returns: { status, signin_tab? }
+ */
+export async function POST(req: Request) {
+ const body = (await req.json().catch(() => ({}))) as {
+ project_slug?: string;
+ signin_url?: string;
+ headless?: boolean;
+ };
+ if (!body.project_slug) {
+ return NextResponse.json(
+ { error: "project_slug required" },
+ { status: 400 },
+ );
+ }
+
+ try {
+ registerShutdownHooks();
+ await getOrLaunchBrowser(body.project_slug, { headless: body.headless ?? false });
+ const status = getSessionStatus(body.project_slug);
+
+ let signinTab: { id: string; url: string } | undefined;
+ if (body.signin_url) {
+ const handle = await openTab(body.project_slug, {
+ label: "signin",
+ url: body.signin_url,
+ });
+ signinTab = { id: handle.id, url: handle.url };
+ }
+
+ return NextResponse.json({ status, signin_tab: signinTab });
+ } catch (err) {
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : String(err) },
+ { status: 500 },
+ );
+ }
+}
diff --git a/notfair-cmo/src/app/api/browser/shutdown/route.test.ts b/notfair-cmo/src/app/api/browser/shutdown/route.test.ts
new file mode 100644
index 00000000..e849ff03
--- /dev/null
+++ b/notfair-cmo/src/app/api/browser/shutdown/route.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+
+vi.mock("@/server/browser/session", () => ({
+ stopBrowser: vi.fn(async () => {}),
+}));
+
+import { POST } from "./route";
+import * as session from "@/server/browser/session";
+
+function makeReq(body: unknown): Request {
+ return new Request("http://localhost/api/browser/shutdown", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("POST /api/browser/shutdown", () => {
+ it("400s when project_slug is missing", async () => {
+ const res = await POST(makeReq({}));
+ expect(res.status).toBe(400);
+ });
+
+ it("calls stopBrowser and returns ok", async () => {
+ const res = await POST(makeReq({ project_slug: "acme" }));
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.ok).toBe(true);
+ expect(session.stopBrowser).toHaveBeenCalledWith("acme");
+ });
+
+ it("500s with the error message when stopBrowser throws", async () => {
+ (session.stopBrowser as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error("kill failed"),
+ );
+ const res = await POST(makeReq({ project_slug: "acme" }));
+ expect(res.status).toBe(500);
+ const body = await res.json();
+ expect(body.error).toBe("kill failed");
+ });
+});
diff --git a/notfair-cmo/src/app/api/browser/shutdown/route.ts b/notfair-cmo/src/app/api/browser/shutdown/route.ts
new file mode 100644
index 00000000..cb014d8f
--- /dev/null
+++ b/notfair-cmo/src/app/api/browser/shutdown/route.ts
@@ -0,0 +1,31 @@
+import { NextResponse } from "next/server";
+
+import { stopBrowser } from "@/server/browser/session";
+
+export const dynamic = "force-dynamic";
+export const runtime = "nodejs";
+
+/**
+ * Stop the workspace browser for a project.
+ *
+ * Cookies persist in the workspace user-data-dir, so the next launch
+ * picks up the same login state. Used by Settings → "Restart browser"
+ * and from the agent-facing browser_shutdown tool.
+ *
+ * POST body: { project_slug: string }
+ */
+export async function POST(req: Request) {
+ const body = (await req.json().catch(() => ({}))) as { project_slug?: string };
+ if (!body.project_slug) {
+ return NextResponse.json({ error: "project_slug required" }, { status: 400 });
+ }
+ try {
+ await stopBrowser(body.project_slug);
+ return NextResponse.json({ ok: true });
+ } catch (err) {
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : String(err) },
+ { status: 500 },
+ );
+ }
+}
diff --git a/notfair-cmo/src/app/api/browser/status/route.test.ts b/notfair-cmo/src/app/api/browser/status/route.test.ts
new file mode 100644
index 00000000..146f412f
--- /dev/null
+++ b/notfair-cmo/src/app/api/browser/status/route.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+
+vi.mock("@/server/browser/session", () => ({
+ getSessionStatus: vi.fn(() => ({
+ projectSlug: "acme",
+ running: true,
+ cdpPort: 19042,
+ userDataDir: "/tmp/profile",
+ launchedAt: 1_000,
+ uptimeMs: 5_000,
+ })),
+}));
+
+vi.mock("@/server/browser/tabs", () => ({
+ listTabs: vi.fn(async () => [
+ { id: "greg", label: "greg", url: "https://example.com", title: "Example" },
+ ]),
+}));
+
+import { GET } from "./route";
+import * as session from "@/server/browser/session";
+import * as tabs from "@/server/browser/tabs";
+
+function makeReq(qs: string): Request {
+ return new Request(`http://localhost/api/browser/status${qs}`);
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("GET /api/browser/status", () => {
+ it("400s when project_slug is missing", async () => {
+ const res = await GET(makeReq(""));
+ expect(res.status).toBe(400);
+ });
+
+ it("returns status + tabs when running", async () => {
+ const res = await GET(makeReq("?project_slug=acme"));
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.status.running).toBe(true);
+ expect(body.tabs).toHaveLength(1);
+ expect(body.tabs[0].id).toBe("greg");
+ });
+
+ it("returns status without tabs when not running", async () => {
+ (session.getSessionStatus as ReturnType<typeof vi.fn>).mockReturnValueOnce({
+ projectSlug: "acme",
+ running: false,
+ cdpPort: 19042,
+ userDataDir: "/tmp/profile",
+ });
+ const res = await GET(makeReq("?project_slug=acme"));
+ const body = await res.json();
+ expect(body.status.running).toBe(false);
+ expect(body.tabs).toEqual([]);
+ expect(tabs.listTabs).not.toHaveBeenCalled();
+ });
+
+ it("returns empty tab list when listTabs throws (doesn't fail the whole probe)", async () => {
+ (tabs.listTabs as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("boom"));
+ const res = await GET(makeReq("?project_slug=acme"));
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.tabs).toEqual([]);
+ });
+});
diff --git a/notfair-cmo/src/app/api/browser/status/route.ts b/notfair-cmo/src/app/api/browser/status/route.ts
new file mode 100644
index 00000000..41cef09c
--- /dev/null
+++ b/notfair-cmo/src/app/api/browser/status/route.ts
@@ -0,0 +1,33 @@
+import { NextResponse } from "next/server";
+
+import { getSessionStatus } from "@/server/browser/session";
+import { listTabs } from "@/server/browser/tabs";
+
+export const dynamic = "force-dynamic";
+export const runtime = "nodejs";
+
+/**
+ * Check whether the workspace browser is running and list its tabs.
+ *
+ * Cheap; safe to poll from the Settings page.
+ *
+ * GET /api/browser/status?project_slug=<slug>
+ */
+export async function GET(req: Request) {
+ const url = new URL(req.url);
+ const slug = url.searchParams.get("project_slug");
+ if (!slug) {
+ return NextResponse.json({ error: "project_slug query param required" }, { status: 400 });
+ }
+ const status = getSessionStatus(slug);
+ let tabs: Array<{ id: string; url: string; title: string }> = [];
+ if (status.running) {
+ try {
+ const handles = await listTabs(slug);
+ tabs = handles.map((h) => ({ id: h.id, url: h.url, title: h.title }));
+ } catch {
+ // listing failed — return status without tabs rather than blowing up
+ }
+ }
+ return NextResponse.json({ status, tabs });
+}
diff --git a/notfair-cmo/src/server/browser/actions.test.ts b/notfair-cmo/src/server/browser/actions.test.ts
new file mode 100644
index 00000000..2be882cb
--- /dev/null
+++ b/notfair-cmo/src/server/browser/actions.test.ts
@@ -0,0 +1,222 @@
+import { describe, expect, it, vi } from "vitest";
+
+import type { Page } from "playwright-core";
+import {
+ back,
+ click,
+ navigate,
+ press,
+ scroll,
+ type as typeAction,
+} from "./actions";
+
+// ── Page fake — only the surface our action layer actually touches ───────
+
+interface LocatorCalls {
+ click?: unknown;
+ dblclick?: unknown;
+ fill?: unknown[];
+ press?: unknown[];
+}
+
+function makeLocatorRecorder() {
+ const byRef = new Map<string, LocatorCalls>();
+ const locator = (selector: string) => {
+ const ref = selector.match(/data-notfair-ref="([^"]+)"/)?.[1] ?? "?";
+ if (!byRef.has(ref)) byRef.set(ref, { fill: [], press: [] });
+ const calls = byRef.get(ref)!;
+ return {
+ click: vi.fn(async (opts?: unknown) => {
+ calls.click = opts;
+ }),
+ dblclick: vi.fn(async (opts?: unknown) => {
+ calls.dblclick = opts;
+ }),
+ fill: vi.fn(async (text: string, opts?: unknown) => {
+ calls.fill!.push({ text, opts });
+ }),
+ press: vi.fn(async (key: string, opts?: unknown) => {
+ calls.press!.push({ key, opts });
+ }),
+ };
+ };
+ return { locator, byRef };
+}
+
+function makePage(rec: ReturnType<typeof makeLocatorRecorder>) {
+ const keyboardPress = vi.fn(async (_key: string) => {});
+ const evaluateCalls: unknown[] = [];
+ const page = {
+ url: () => "https://example.com",
+ title: async () => "Example",
+ goto: vi.fn(async (_url: string, _opts?: unknown) => null),
+ goBack: vi.fn(async (_opts?: unknown) => null),
+ locator: rec.locator,
+ keyboard: { press: keyboardPress },
+ evaluate: vi.fn(async (_fn: unknown, arg?: unknown) => {
+ evaluateCalls.push(arg);
+ }),
+ } as unknown as Page;
+ return { page, keyboardPress, evaluateCalls };
+}
+
+// ── navigate ─────────────────────────────────────────────────────────────
+
+describe("navigate", () => {
+ it("calls page.goto with defaults and returns url+title", async () => {
+ const rec = makeLocatorRecorder();
+ const { page } = makePage(rec);
+ const result = await navigate(page, { url: "https://example.com" });
+ expect(page.goto).toHaveBeenCalledWith("https://example.com", {
+ waitUntil: "load",
+ timeout: 30_000,
+ });
+ expect(result).toEqual({ url: "https://example.com", title: "Example" });
+ });
+
+ it("honors caller-supplied waitUntil + timeoutMs", async () => {
+ const rec = makeLocatorRecorder();
+ const { page } = makePage(rec);
+ await navigate(page, {
+ url: "https://example.com",
+ waitUntil: "networkidle",
+ timeoutMs: 5_000,
+ });
+ expect(page.goto).toHaveBeenCalledWith("https://example.com", {
+ waitUntil: "networkidle",
+ timeout: 5_000,
+ });
+ });
+});
+
+// ── click ────────────────────────────────────────────────────────────────
+
+describe("click", () => {
+ it("rejects refs that don't match e<number>", async () => {
+ const rec = makeLocatorRecorder();
+ const { page } = makePage(rec);
+ await expect(click(page, { ref: "weird" })).rejects.toThrow(/Invalid ref/);
+ });
+
+ it("issues a single click by default", async () => {
+ const rec = makeLocatorRecorder();
+ const { page } = makePage(rec);
+ await click(page, { ref: "e3" });
+ expect(rec.byRef.get("e3")?.click).toBeDefined();
+ expect(rec.byRef.get("e3")?.dblclick).toBeUndefined();
+ });
+
+ it("issues a double-click when requested", async () => {
+ const rec = makeLocatorRecorder();
+ const { page } = makePage(rec);
+ await click(page, { ref: "e1", doubleClick: true });
+ expect(rec.byRef.get("e1")?.dblclick).toBeDefined();
+ expect(rec.byRef.get("e1")?.click).toBeUndefined();
+ });
+
+ it("forwards button and modifiers to Playwright", async () => {
+ const rec = makeLocatorRecorder();
+ const { page } = makePage(rec);
+ await click(page, {
+ ref: "e2",
+ button: "right",
+ modifiers: ["Meta", "Shift"],
+ });
+ expect(rec.byRef.get("e2")?.click).toMatchObject({
+ button: "right",
+ modifiers: ["Meta", "Shift"],
+ });
+ });
+});
+
+// ── type ─────────────────────────────────────────────────────────────────
+
+describe("type", () => {
+ it("clears the field then fills with the new text", async () => {
+ const rec = makeLocatorRecorder();
+ const { page } = makePage(rec);
+ await typeAction(page, { ref: "e5", text: "hello world" });
+ const fills = rec.byRef.get("e5")?.fill ?? [];
+ expect(fills.length).toBe(2);
+ expect((fills[0] as { text: string }).text).toBe("");
+ expect((fills[1] as { text: string }).text).toBe("hello world");
+ });
+
+ it("skips the clear when clearFirst is explicitly false", async () => {
+ const rec = makeLocatorRecorder();
+ const { page } = makePage(rec);
+ await typeAction(page, { ref: "e5", text: "append", clearFirst: false });
+ const fills = rec.byRef.get("e5")?.fill ?? [];
+ expect(fills.length).toBe(1);
+ expect((fills[0] as { text: string }).text).toBe("append");
+ });
+
+ it("presses Enter after typing when submit is true", async () => {
+ const rec = makeLocatorRecorder();
+ const { page } = makePage(rec);
+ await typeAction(page, { ref: "e5", text: "search", submit: true });
+ const presses = rec.byRef.get("e5")?.press ?? [];
+ expect(presses).toHaveLength(1);
+ expect((presses[0] as { key: string }).key).toBe("Enter");
+ });
+});
+
+// ── press ────────────────────────────────────────────────────────────────
+
+describe("press", () => {
+ it("presses on a locator when ref is supplied", async () => {
+ const rec = makeLocatorRecorder();
+ const { page, keyboardPress } = makePage(rec);
+ await press(page, { ref: "e1", key: "Tab" });
+ expect((rec.byRef.get("e1")?.press ?? [])[0]).toMatchObject({ key: "Tab" });
+ expect(keyboardPress).not.toHaveBeenCalled();
+ });
+
+ it("presses at page level when ref is omitted", async () => {
+ const rec = makeLocatorRecorder();
+ const { page, keyboardPress } = makePage(rec);
+ await press(page, { key: "Escape" });
+ expect(keyboardPress).toHaveBeenCalledWith("Escape");
+ });
+});
+
+// ── scroll ───────────────────────────────────────────────────────────────
+
+describe("scroll", () => {
+ it.each([
+ ["up", { x: 0, y: -600 }],
+ ["down", { x: 0, y: 600 }],
+ ["left", { x: -600, y: 0 }],
+ ["right", { x: 600, y: 0 }],
+ ] as const)("scrolls %s by default amount", async (direction, expected) => {
+ const rec = makeLocatorRecorder();
+ const { page, evaluateCalls } = makePage(rec);
+ await scroll(page, { direction });
+ expect(evaluateCalls).toContainEqual(expected);
+ });
+
+ it("honors a custom amount", async () => {
+ const rec = makeLocatorRecorder();
+ const { page, evaluateCalls } = makePage(rec);
+ await scroll(page, { direction: "down", amount: 1200 });
+ expect(evaluateCalls).toContainEqual({ x: 0, y: 1200 });
+ });
+});
+
+// ── back ─────────────────────────────────────────────────────────────────
+
+describe("back", () => {
+ it("calls page.goBack with load wait", async () => {
+ const rec = makeLocatorRecorder();
+ const { page } = makePage(rec);
+ await back(page);
+ expect(page.goBack).toHaveBeenCalledWith({ waitUntil: "load" });
+ });
+
+ it("swallows navigation errors (back on first page is normal)", async () => {
+ const rec = makeLocatorRecorder();
+ const { page } = makePage(rec);
+ (page.goBack as ReturnType<typeof vi.fn>).mockRejectedValue(new Error("no history"));
+ await expect(back(page)).resolves.toBeUndefined();
+ });
+});
diff --git a/notfair-cmo/src/server/browser/actions.ts b/notfair-cmo/src/server/browser/actions.ts
new file mode 100644
index 00000000..205a1b68
--- /dev/null
+++ b/notfair-cmo/src/server/browser/actions.ts
@@ -0,0 +1,249 @@
+/**
+ * Page-level browser primitives the MCP tools wrap.
+ *
+ * Each function takes a Playwright Page and a small typed opts payload,
+ * runs the action with sensible defaults, and returns a normalized result.
+ * Keeping the action layer separate from the MCP tool layer means the
+ * tools can stay one-screen each (zod schema + handler) and these can be
+ * unit-tested without any MCP envelope plumbing.
+ *
+ * Snapshot format: V1 returns a flat list of interactable elements with
+ * stable ref ids (e1, e2, ...) scoped to the snapshot call. This matches
+ * Hermes' agent-browser ref convention so agent prompts can reuse the
+ * same mental model. The full Playwright aria tree comes in V1.1.
+ */
+import type { Page } from "playwright-core";
+
+export interface NavigateOptions {
+ url: string;
+ waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit";
+ timeoutMs?: number;
+}
+
+export interface NavigateResult {
+ url: string;
+ title: string;
+}
+
+export async function navigate(page: Page, opts: NavigateOptions): Promise<NavigateResult> {
+ await page.goto(opts.url, {
+ waitUntil: opts.waitUntil ?? "load",
+ timeout: opts.timeoutMs ?? 30_000,
+ });
+ return {
+ url: page.url(),
+ title: await page.title().catch(() => ""),
+ };
+}
+
+export interface SnapshotElement {
+ /** Ref id stable within this snapshot, e.g. "e1". */
+ ref: string;
+ /** ARIA role or tag name. */
+ role: string;
+ /** Accessible name when available, else trimmed text. */
+ name: string;
+ /** Empty for buttons/links; populated for inputs/selects. */
+ value?: string;
+ /** True when disabled / aria-disabled. */
+ disabled?: boolean;
+ /** href for links so agents can decide whether to navigate directly. */
+ href?: string;
+}
+
+export interface SnapshotResult {
+ url: string;
+ title: string;
+ elements: SnapshotElement[];
+ /** Truncated text content of the page, for context. */
+ text: string;
+}
+
+const SNAPSHOT_ELEMENT_LIMIT = 200;
+const SNAPSHOT_TEXT_CHAR_LIMIT = 8_000;
+
+/**
+ * Build a flat list of interactable elements + a text excerpt.
+ *
+ * We evaluate in the page rather than using Playwright's role queries
+ * because we want a single round-trip that returns everything we need:
+ * role, accessible name, current value, href, and a temporary numbered
+ * attribute we hang off each element so subsequent click/type calls can
+ * resolve back to the same DOM node via [data-notfair-ref="eN"].
+ */
+export async function snapshot(page: Page): Promise<SnapshotResult> {
+ const { url, title, elements, text } = await page.evaluate(
+ ({ elemLimit, textLimit }) => {
+ const REF_ATTR = "data-notfair-ref";
+ // Clear stale refs from a previous snapshot.
+ for (const stale of Array.from(document.querySelectorAll(`[${REF_ATTR}]`))) {
+ stale.removeAttribute(REF_ATTR);
+ }
+
+ const SELECTOR = [
+ "a[href]",
+ "button",
+ "input:not([type=hidden])",
+ "select",
+ "textarea",
+ "[role=button]",
+ "[role=link]",
+ "[role=checkbox]",
+ "[role=radio]",
+ "[role=tab]",
+ "[role=menuitem]",
+ "[contenteditable=true]",
+ ].join(",");
+
+ const isVisible = (el: Element): boolean => {
+ const rect = (el as HTMLElement).getBoundingClientRect();
+ if (rect.width === 0 || rect.height === 0) return false;
+ const style = window.getComputedStyle(el as HTMLElement);
+ return style.visibility !== "hidden" && style.display !== "none";
+ };
+
+ const accessibleName = (el: Element): string => {
+ const aria = el.getAttribute("aria-label");
+ if (aria) return aria;
+ const labelled = el.getAttribute("aria-labelledby");
+ if (labelled) {
+ const node = document.getElementById(labelled);
+ if (node?.textContent) return node.textContent.trim();
+ }
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
+ const id = el.getAttribute("id");
+ if (id) {
+ const label = document.querySelector(`label[for="${CSS.escape(id)}"]`);
+ if (label?.textContent) return label.textContent.trim();
+ }
+ if (el.placeholder) return el.placeholder;
+ }
+ const text = (el as HTMLElement).innerText ?? el.textContent ?? "";
+ return text.trim().slice(0, 200);
+ };
+
+ const out: Array<Record<string, unknown>> = [];
+ let counter = 0;
+ const nodes = Array.from(document.querySelectorAll(SELECTOR)).filter(isVisible);
+ for (const el of nodes) {
+ if (counter >= elemLimit) break;
+ counter++;
+ const ref = `e${counter}`;
+ el.setAttribute(REF_ATTR, ref);
+
+ const tag = el.tagName.toLowerCase();
+ const role = el.getAttribute("role") ?? tag;
+ const item: Record<string, unknown> = {
+ ref,
+ role,
+ name: accessibleName(el),
+ };
+ if (el instanceof HTMLAnchorElement && el.href) item.href = el.href;
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
+ item.value = el.value;
+ }
+ if ((el as HTMLButtonElement).disabled || el.getAttribute("aria-disabled") === "true") {
+ item.disabled = true;
+ }
+ out.push(item);
+ }
+
+ const rawText = document.body?.innerText ?? "";
+ const text = rawText.slice(0, textLimit);
+
+ return {
+ url: window.location.href,
+ title: document.title,
+ elements: out,
+ text,
+ };
+ },
+ { elemLimit: SNAPSHOT_ELEMENT_LIMIT, textLimit: SNAPSHOT_TEXT_CHAR_LIMIT },
+ );
+ return { url, title, elements: elements as unknown as SnapshotElement[], text };
+}
+
+function refSelector(ref: string): string {
+ // CSS attribute selectors don't need escaping for our ref format (eN).
+ if (!/^e\d+$/.test(ref)) {
+ throw new Error(`Invalid ref "${ref}" — expected "e<number>"`);
+ }
+ return `[data-notfair-ref="${ref}"]`;
+}
+
+export interface ClickOptions {
+ ref: string;
+ button?: "left" | "right" | "middle";
+ modifiers?: ("Alt" | "Control" | "Meta" | "Shift")[];
+ doubleClick?: boolean;
+ timeoutMs?: number;
+}
+
+export async function click(page: Page, opts: ClickOptions): Promise<void> {
+ const locator = page.locator(refSelector(opts.ref));
+ const timeout = opts.timeoutMs ?? 10_000;
+ if (opts.doubleClick) {
+ await locator.dblclick({ button: opts.button, modifiers: opts.modifiers, timeout });
+ } else {
+ await locator.click({ button: opts.button, modifiers: opts.modifiers, timeout });
+ }
+}
+
+export interface TypeOptions {
+ ref: string;
+ text: string;
+ /** Press Enter after typing. */
+ submit?: boolean;
+ /** Clear the field before typing. Default: true. */
+ clearFirst?: boolean;
+ timeoutMs?: number;
+}
+
+export async function type(page: Page, opts: TypeOptions): Promise<void> {
+ const locator = page.locator(refSelector(opts.ref));
+ const timeout = opts.timeoutMs ?? 10_000;
+ if (opts.clearFirst !== false) {
+ await locator.fill("", { timeout });
+ }
+ await locator.fill(opts.text, { timeout });
+ if (opts.submit) {
+ await locator.press("Enter", { timeout });
+ }
+}
+
+export interface PressOptions {
+ /** Playwright key string, e.g. "Enter", "Tab", "Control+a". */
+ key: string;
+ /** Optional ref to focus before pressing. If omitted, presses at page level. */
+ ref?: string;
+ timeoutMs?: number;
+}
+
+export async function press(page: Page, opts: PressOptions): Promise<void> {
+ const timeout = opts.timeoutMs ?? 10_000;
+ if (opts.ref) {
+ const locator = page.locator(refSelector(opts.ref));
+ await locator.press(opts.key, { timeout });
+ } else {
+ await page.keyboard.press(opts.key);
+ }
+}
+
+export interface ScrollOptions {
+ direction: "up" | "down" | "left" | "right";
+ /** Pixels. Default: 600 (one screen-ish on most viewports). */
+ amount?: number;
+}
+
+export async function scroll(page: Page, opts: ScrollOptions): Promise<void> {
+ const amount = opts.amount ?? 600;
+ const dx =
+ opts.direction === "left" ? -amount : opts.direction === "right" ? amount : 0;
+ const dy =
+ opts.direction === "up" ? -amount : opts.direction === "down" ? amount : 0;
+ await page.evaluate(({ x, y }) => window.scrollBy(x, y), { x: dx, y: dy });
+}
+
+export async function back(page: Page): Promise<void> {
+ await page.goBack({ waitUntil: "load" }).catch(() => {});
+}
diff --git a/notfair-cmo/src/server/browser/browser.e2e.test.ts b/notfair-cmo/src/server/browser/browser.e2e.test.ts
new file mode 100644
index 00000000..0f361f9c
--- /dev/null
+++ b/notfair-cmo/src/server/browser/browser.e2e.test.ts
@@ -0,0 +1,122 @@
+/**
+ * Real-Chrome smoke test.
+ *
+ * Skipped unless BOTH of the following are true:
+ * - findChromeExecutable() finds a Chromium-family binary on the host
+ * - NOTFAIR_E2E_BROWSER=1 in the env (gated so day-to-day `pnpm test`
+ * stays fast and offline-safe)
+ *
+ * Confirms the actual wire works end-to-end: Chrome launches, Playwright
+ * attaches via CDP, a tab navigates to a data: URL, snapshot extracts
+ * interactable elements, click fires the inline handler, type fills the
+ * input, scroll moves the viewport, close tears it down.
+ *
+ * Run locally: `NOTFAIR_E2E_BROWSER=1 pnpm test browser.e2e`
+ */
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { findChromeExecutable } from "./chrome";
+import { click, navigate, snapshot, scroll, type as typeAction } from "./actions";
+import {
+ _sessionsByProject,
+ getOrLaunchBrowser,
+ stopAllBrowsers,
+} from "./session";
+import { _resetTabRegistries, closeTab, listTabs, openTab } from "./tabs";
+
+const SKIP =
+ process.env.NOTFAIR_E2E_BROWSER !== "1" || findChromeExecutable() === null;
+
+const PROJECT_SLUG = "e2e-smoke";
+const TEST_HTML = encodeURIComponent(`
+ <!DOCTYPE html>
+ <html>
+ <head><title>e2e smoke</title></head>
+ <body style="height: 3000px">
+ <h1 id="heading">hello e2e</h1>
+ <button id="b1" onclick="window.__clicked = (window.__clicked||0)+1">click me</button>
+ <input id="i1" placeholder="type here" />
+ <span id="counter">0</span>
+ </body>
+ </html>
+`);
+const TEST_URL = `data:text/html,${TEST_HTML}`;
+
+let dataDir: string;
+
+beforeAll(() => {
+ if (SKIP) return;
+ dataDir = mkdtempSync(join(tmpdir(), "notfair-cmo-e2e-"));
+ process.env.NOTFAIR_CMO_DATA_DIR = dataDir;
+ // Headless on CI/local runs; this is a smoke test, not a UX test.
+ process.env.NOTFAIR_BROWSER_HEADLESS = "1";
+});
+
+afterAll(async () => {
+ if (SKIP) return;
+ await stopAllBrowsers();
+ _resetTabRegistries();
+ _sessionsByProject.clear();
+ if (dataDir) rmSync(dataDir, { recursive: true, force: true });
+ delete process.env.NOTFAIR_CMO_DATA_DIR;
+ delete process.env.NOTFAIR_BROWSER_HEADLESS;
+});
+
+describe.skipIf(SKIP)("browser E2E smoke (real Chrome)", () => {
+ it(
+ "launches Chrome, snapshots a page, clicks + types + scrolls, then closes the tab",
+ { timeout: 60_000 },
+ async () => {
+ const session = await getOrLaunchBrowser(PROJECT_SLUG);
+ expect(session.launched.process.exitCode).toBeNull();
+
+ const handle = await openTab(PROJECT_SLUG, { label: "smoke", url: TEST_URL });
+ expect(handle.id).toBe("smoke");
+ expect(handle.url).toContain("data:text/html");
+
+ const page = (await import("./tabs")).getTab.bind(null);
+ const livePage = await page(PROJECT_SLUG, "smoke");
+ expect(livePage).not.toBeNull();
+ if (!livePage) throw new Error("unreachable");
+
+ // Navigate via the action layer to a fresh page so we exercise it too.
+ const navResult = await navigate(livePage, { url: TEST_URL });
+ expect(navResult.title).toBe("e2e smoke");
+
+ // Snapshot must find the button + input.
+ const snap = await snapshot(livePage);
+ const button = snap.elements.find((e) => e.name === "click me");
+ const input = snap.elements.find((e) => e.role === "input");
+ expect(button).toBeDefined();
+ expect(input).toBeDefined();
+
+ // Click the button — inline handler should bump window.__clicked.
+ await click(livePage, { ref: button!.ref });
+ const clickedCount = await livePage.evaluate(() => (window as unknown as { __clicked?: number }).__clicked);
+ expect(clickedCount).toBe(1);
+
+ // Type into the input and verify the value sticks.
+ await typeAction(livePage, { ref: input!.ref, text: "hello world" });
+ const typedValue = await livePage.evaluate(
+ () => (document.querySelector("#i1") as HTMLInputElement).value,
+ );
+ expect(typedValue).toBe("hello world");
+
+ // Scroll and verify scrollY moved.
+ await scroll(livePage, { direction: "down", amount: 500 });
+ const scrollY = await livePage.evaluate(() => window.scrollY);
+ expect(scrollY).toBeGreaterThan(0);
+
+ // List tabs sanity.
+ const tabs = await listTabs(PROJECT_SLUG);
+ expect(tabs.some((t) => t.id === "smoke")).toBe(true);
+
+ // Close the tab.
+ const closed = await closeTab(PROJECT_SLUG, "smoke");
+ expect(closed).toBe(true);
+ },
+ );
+});
diff --git a/notfair-cmo/src/server/browser/chrome.test.ts b/notfair-cmo/src/server/browser/chrome.test.ts
new file mode 100644
index 00000000..1da39ec1
--- /dev/null
+++ b/notfair-cmo/src/server/browser/chrome.test.ts
@@ -0,0 +1,185 @@
+import fs from "node:fs";
+import path from "node:path";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ buildChromeLaunchArgs,
+ clearChromeSingletonArtifacts,
+ findChromeExecutable,
+ waitForCdpReady,
+} from "./chrome";
+
+describe("findChromeExecutable", () => {
+ it("returns NOTFAIR_CHROME_PATH when set and the file exists", () => {
+ const env = { NOTFAIR_CHROME_PATH: "/custom/chrome" };
+ const result = findChromeExecutable(env, "darwin", (p) => p === "/custom/chrome");
+ expect(result).toBe("/custom/chrome");
+ });
+
+ it("ignores NOTFAIR_CHROME_PATH when the file does not exist and falls through to defaults", () => {
+ const env = { NOTFAIR_CHROME_PATH: "/missing" };
+ const result = findChromeExecutable(env, "darwin", (p) =>
+ p === "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
+ );
+ expect(result).toBe(
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
+ );
+ });
+
+ it("probes macOS Chrome locations on darwin", () => {
+ const result = findChromeExecutable(
+ {},
+ "darwin",
+ (p) => p === "/Applications/Chromium.app/Contents/MacOS/Chromium",
+ );
+ expect(result).toBe("/Applications/Chromium.app/Contents/MacOS/Chromium");
+ });
+
+ it("probes Linux locations on linux", () => {
+ const result = findChromeExecutable({}, "linux", (p) => p === "/usr/bin/chromium");
+ expect(result).toBe("/usr/bin/chromium");
+ });
+
+ it("returns null when nothing matches", () => {
+ const result = findChromeExecutable({}, "darwin", () => false);
+ expect(result).toBeNull();
+ });
+
+ it("returns null on unsupported platforms (win32 stub for now)", () => {
+ const result = findChromeExecutable({}, "win32", () => true);
+ expect(result).toBeNull();
+ });
+});
+
+describe("buildChromeLaunchArgs", () => {
+ const base = {
+ executablePath: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
+ userDataDir: "/tmp/profile",
+ cdpPort: 19042,
+ };
+
+ it("includes the required CDP + user-data-dir flags", () => {
+ const args = buildChromeLaunchArgs(base);
+ expect(args).toContain("--remote-debugging-port=19042");
+ expect(args).toContain("--user-data-dir=/tmp/profile");
+ });
+
+ it("omits headless flags by default", () => {
+ const args = buildChromeLaunchArgs(base);
+ expect(args).not.toContain("--headless=new");
+ expect(args).not.toContain("--disable-gpu");
+ });
+
+ it("adds --headless=new and --disable-gpu when headless=true", () => {
+ const args = buildChromeLaunchArgs({ ...base, headless: true });
+ expect(args).toContain("--headless=new");
+ expect(args).toContain("--disable-gpu");
+ });
+
+ it("adds --disable-dev-shm-usage on linux only", () => {
+ expect(buildChromeLaunchArgs({ ...base, platform: "linux" })).toContain(
+ "--disable-dev-shm-usage",
+ );
+ expect(buildChromeLaunchArgs({ ...base, platform: "darwin" })).not.toContain(
+ "--disable-dev-shm-usage",
+ );
+ });
+
+ it("appends extraArgs verbatim at the end", () => {
+ const args = buildChromeLaunchArgs({
+ ...base,
+ extraArgs: ["--window-size=1280,800", "--proxy-server=127.0.0.1:8888"],
+ });
+ expect(args.slice(-2)).toEqual([
+ "--window-size=1280,800",
+ "--proxy-server=127.0.0.1:8888",
+ ]);
+ });
+
+ it("disables Chrome onboarding + crash bubbles that block agent flows", () => {
+ const args = buildChromeLaunchArgs(base);
+ expect(args).toContain("--no-first-run");
+ expect(args).toContain("--no-default-browser-check");
+ expect(args).toContain("--disable-session-crashed-bubble");
+ expect(args).toContain("--hide-crash-restore-bubble");
+ });
+});
+
+describe("clearChromeSingletonArtifacts", () => {
+ let dir: string;
+ beforeEach(() => {
+ dir = mkdtempSync(path.join(tmpdir(), "notfair-cmo-chrome-test-"));
+ });
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ it("removes SingletonLock, SingletonSocket, and SingletonCookie", () => {
+ for (const f of ["SingletonLock", "SingletonSocket", "SingletonCookie"]) {
+ writeFileSync(path.join(dir, f), "");
+ }
+ clearChromeSingletonArtifacts(dir);
+ expect(fs.existsSync(path.join(dir, "SingletonLock"))).toBe(false);
+ expect(fs.existsSync(path.join(dir, "SingletonSocket"))).toBe(false);
+ expect(fs.existsSync(path.join(dir, "SingletonCookie"))).toBe(false);
+ });
+
+ it("leaves unrelated files alone", () => {
+ writeFileSync(path.join(dir, "SingletonLock"), "");
+ writeFileSync(path.join(dir, "Preferences"), "{}");
+ clearChromeSingletonArtifacts(dir);
+ expect(fs.existsSync(path.join(dir, "Preferences"))).toBe(true);
+ });
+
+ it("no-ops when the dir or files don't exist", () => {
+ expect(() => clearChromeSingletonArtifacts("/nonexistent/path/here")).not.toThrow();
+ });
+});
+
+describe("waitForCdpReady", () => {
+ const originalFetch = globalThis.fetch;
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ vi.useRealTimers();
+ });
+
+ it("resolves when /json/version returns 200", async () => {
+ globalThis.fetch = vi
+ .fn()
+ .mockResolvedValue(new Response("ok", { status: 200 })) as typeof fetch;
+ await expect(
+ waitForCdpReady("http://127.0.0.1:19042", 500, 10),
+ ).resolves.toBeUndefined();
+ });
+
+ it("retries on transient errors then succeeds", async () => {
+ let attempts = 0;
+ globalThis.fetch = vi.fn().mockImplementation(async () => {
+ attempts++;
+ if (attempts < 3) throw new Error("connection refused");
+ return new Response("ok", { status: 200 });
+ }) as typeof fetch;
+ await expect(
+ waitForCdpReady("http://127.0.0.1:19042", 1000, 10),
+ ).resolves.toBeUndefined();
+ expect(attempts).toBeGreaterThanOrEqual(3);
+ });
+
+ it("rejects with the last error message when the deadline passes", async () => {
+ globalThis.fetch = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")) as typeof fetch;
+ await expect(
+ waitForCdpReady("http://127.0.0.1:19042", 50, 10),
+ ).rejects.toThrow(/did not become ready within 50ms.*ECONNREFUSED/);
+ });
+
+ it("treats non-200 responses as not-ready", async () => {
+ globalThis.fetch = vi
+ .fn()
+ .mockResolvedValue(new Response("server starting", { status: 503 })) as typeof fetch;
+ await expect(
+ waitForCdpReady("http://127.0.0.1:19042", 50, 10),
+ ).rejects.toThrow(/status 503/);
+ });
+});
diff --git a/notfair-cmo/src/server/browser/chrome.ts b/notfair-cmo/src/server/browser/chrome.ts
new file mode 100644
index 00000000..c0195f25
--- /dev/null
+++ b/notfair-cmo/src/server/browser/chrome.ts
@@ -0,0 +1,238 @@
+/**
+ * Workspace Chrome lifecycle.
+ *
+ * Discovers a Chromium-family browser binary, builds launch args for a
+ * managed instance pointed at a workspace user-data-dir, starts it on a
+ * known CDP port, waits for the CDP endpoint to come up, and shuts it down
+ * cleanly. Borrowed pattern from openclaw's chrome.ts but trimmed to the
+ * essentials a single-user local app needs.
+ */
+import { type ChildProcess, spawn } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+
+const SINGLETON_LOCK_FILES = ["SingletonLock", "SingletonSocket", "SingletonCookie"];
+
+const MAC_CHROME_CANDIDATES: ReadonlyArray<string> = [
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
+];
+
+const LINUX_CHROME_CANDIDATES: ReadonlyArray<string> = [
+ "/usr/bin/google-chrome",
+ "/usr/bin/google-chrome-stable",
+ "/usr/bin/chromium",
+ "/usr/bin/chromium-browser",
+ "/usr/bin/microsoft-edge",
+ "/usr/bin/brave-browser",
+];
+
+/**
+ * Find a Chromium-family binary.
+ *
+ * Respects $NOTFAIR_CHROME_PATH first, then probes platform defaults.
+ * Returns null when nothing is found — callers should produce a friendly
+ * error pointing the user at the env var or an install link.
+ */
+export function findChromeExecutable(
+ env: Readonly<Record<string, string | undefined>> = process.env,
+ platform: NodeJS.Platform = process.platform,
+ exists: (p: string) => boolean = (p) => fs.existsSync(p),
+): string | null {
+ const explicit = env.NOTFAIR_CHROME_PATH?.trim();
+ if (explicit && exists(explicit)) return explicit;
+
+ const candidates =
+ platform === "darwin"
+ ? MAC_CHROME_CANDIDATES
+ : platform === "linux"
+ ? LINUX_CHROME_CANDIDATES
+ : [];
+
+ for (const candidate of candidates) {
+ if (exists(candidate)) return candidate;
+ }
+ return null;
+}
+
+/**
+ * Remove Chrome's SingletonLock / SingletonSocket / SingletonCookie files.
+ *
+ * Chrome refuses to start a second process against the same --user-data-dir,
+ * keying off these files. If our prior managed Chrome crashed (or the OS
+ * killed the parent without unlinking), the locks survive and the next
+ * launch silently no-ops or fails. Clear them before every launch — they're
+ * a coordination primitive, not durable state.
+ */
+export function clearChromeSingletonArtifacts(userDataDir: string): void {
+ for (const basename of SINGLETON_LOCK_FILES) {
+ try {
+ fs.rmSync(path.join(userDataDir, basename), { force: true });
+ } catch {
+ // best-effort: a residual file the kernel can't unlink is not worth aborting launch
+ }
+ }
+}
+
+export interface ChromeLaunchOptions {
+ executablePath: string;
+ userDataDir: string;
+ cdpPort: number;
+ /** Default false. Onboarding sign-in always wants headed; agent runtime can choose. */
+ headless?: boolean;
+ /** Override platform for testability. */
+ platform?: NodeJS.Platform;
+ /** Extra args appended verbatim. Useful for --proxy-server, --window-size, etc. */
+ extraArgs?: string[];
+}
+
+/** Compose the Chrome argv list. Pure — does not touch disk or spawn anything. */
+export function buildChromeLaunchArgs(opts: ChromeLaunchOptions): string[] {
+ const platform = opts.platform ?? process.platform;
+ const args = [
+ `--remote-debugging-port=${opts.cdpPort}`,
+ `--user-data-dir=${opts.userDataDir}`,
+ "--no-first-run",
+ "--no-default-browser-check",
+ "--disable-sync",
+ "--disable-background-networking",
+ "--disable-component-update",
+ "--disable-features=Translate,MediaRouter",
+ "--disable-session-crashed-bubble",
+ "--hide-crash-restore-bubble",
+ "--password-store=basic",
+ ];
+ if (opts.headless) {
+ args.push("--headless=new", "--disable-gpu");
+ }
+ if (platform === "linux") {
+ args.push("--disable-dev-shm-usage");
+ }
+ if (opts.extraArgs?.length) {
+ args.push(...opts.extraArgs);
+ }
+ return args;
+}
+
+export interface LaunchedChrome {
+ process: ChildProcess;
+ cdpPort: number;
+ cdpHttpUrl: string;
+ userDataDir: string;
+}
+
+/**
+ * Spawn Chrome and wait for its CDP HTTP endpoint to respond.
+ *
+ * Throws if Chrome exits before CDP becomes reachable, or if the readiness
+ * probe times out. Callers should catch and surface a friendly error
+ * (Chrome version too old, port already taken, etc.).
+ */
+export async function launchChrome(
+ opts: ChromeLaunchOptions,
+ readyTimeoutMs = 15_000,
+): Promise<LaunchedChrome> {
+ fs.mkdirSync(opts.userDataDir, { recursive: true });
+ clearChromeSingletonArtifacts(opts.userDataDir);
+
+ const args = buildChromeLaunchArgs(opts);
+ const proc = spawn(opts.executablePath, args, {
+ stdio: ["ignore", "pipe", "pipe"],
+ detached: false,
+ });
+
+ const cdpHttpUrl = `http://127.0.0.1:${opts.cdpPort}`;
+
+ const stderrChunks: string[] = [];
+ proc.stderr?.on("data", (chunk: Buffer) => {
+ // Keep last ~4KB of stderr so we can include a hint in launch failures.
+ stderrChunks.push(chunk.toString("utf8"));
+ while (stderrChunks.join("").length > 4096) stderrChunks.shift();
+ });
+
+ const earlyExit = new Promise<never>((_, reject) => {
+ proc.once("exit", (code, signal) => {
+ reject(
+ new Error(
+ `Chrome exited before CDP became ready (code=${code} signal=${signal}). ` +
+ `stderr tail: ${stderrChunks.join("").slice(-512)}`,
+ ),
+ );
+ });
+ });
+
+ try {
+ await Promise.race([waitForCdpReady(cdpHttpUrl, readyTimeoutMs), earlyExit]);
+ } catch (err) {
+ if (proc.exitCode === null) proc.kill("SIGKILL");
+ throw err;
+ }
+
+ return {
+ process: proc,
+ cdpPort: opts.cdpPort,
+ cdpHttpUrl,
+ userDataDir: opts.userDataDir,
+ };
+}
+
+/** Poll the CDP /json/version endpoint until it 200s or we time out. */
+export async function waitForCdpReady(
+ cdpHttpUrl: string,
+ timeoutMs: number,
+ pollIntervalMs = 150,
+): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ let lastErr: unknown;
+ while (Date.now() < deadline) {
+ try {
+ const res = await fetch(`${cdpHttpUrl}/json/version`, {
+ signal: AbortSignal.timeout(Math.min(1000, timeoutMs)),
+ });
+ if (res.ok) return;
+ lastErr = new Error(`CDP probe returned status ${res.status}`);
+ } catch (err) {
+ lastErr = err;
+ }
+ await sleep(pollIntervalMs);
+ }
+ throw new Error(
+ `Chrome CDP at ${cdpHttpUrl} did not become ready within ${timeoutMs}ms` +
+ (lastErr ? `: ${(lastErr as Error).message ?? String(lastErr)}` : ""),
+ );
+}
+
+/** Graceful SIGTERM with SIGKILL fallback, then SingletonLock cleanup. */
+export async function stopChrome(launched: LaunchedChrome, timeoutMs = 5_000): Promise<void> {
+ const { process: proc, userDataDir } = launched;
+ if (proc.exitCode === null && !proc.killed) {
+ proc.kill("SIGTERM");
+ await waitForExit(proc, timeoutMs);
+ if (proc.exitCode === null) {
+ proc.kill("SIGKILL");
+ await waitForExit(proc, 1_000);
+ }
+ }
+ clearChromeSingletonArtifacts(userDataDir);
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function waitForExit(proc: ChildProcess, timeoutMs: number): Promise<void> {
+ return new Promise((resolve) => {
+ if (proc.exitCode !== null) {
+ resolve();
+ return;
+ }
+ const timer = setTimeout(resolve, timeoutMs);
+ proc.once("exit", () => {
+ clearTimeout(timer);
+ resolve();
+ });
+ });
+}
diff --git a/notfair-cmo/src/server/browser/paths.test.ts b/notfair-cmo/src/server/browser/paths.test.ts
new file mode 100644
index 00000000..2a14f5b0
--- /dev/null
+++ b/notfair-cmo/src/server/browser/paths.test.ts
@@ -0,0 +1,112 @@
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import {
+ CDP_PORT_RANGE_END,
+ CDP_PORT_RANGE_START,
+ allocateCdpPort,
+ isValidProjectSlug,
+ notfairDataDir,
+ resolveBrowserProfileDir,
+ resolveUserDataDir,
+} from "./paths";
+
+describe("isValidProjectSlug", () => {
+ it.each([
+ "acme",
+ "acme-co",
+ "a1",
+ "0-foo",
+ "x".repeat(64),
+ ])("accepts %s", (slug) => {
+ expect(isValidProjectSlug(slug)).toBe(true);
+ });
+
+ it.each([
+ "",
+ "ACME",
+ "acme co",
+ "acme_co",
+ "-acme",
+ "x".repeat(65),
+ "acme.co",
+ ])("rejects %s", (slug) => {
+ expect(isValidProjectSlug(slug)).toBe(false);
+ });
+});
+
+describe("notfairDataDir", () => {
+ let originalEnv: string | undefined;
+ beforeEach(() => {
+ originalEnv = process.env.NOTFAIR_CMO_DATA_DIR;
+ });
+ afterEach(() => {
+ if (originalEnv === undefined) delete process.env.NOTFAIR_CMO_DATA_DIR;
+ else process.env.NOTFAIR_CMO_DATA_DIR = originalEnv;
+ });
+
+ it("uses env override when set", () => {
+ process.env.NOTFAIR_CMO_DATA_DIR = "/tmp/notfair-cmo-test";
+ expect(notfairDataDir()).toBe("/tmp/notfair-cmo-test");
+ });
+
+ it("falls back to ~/.notfair-cmo when env not set", () => {
+ delete process.env.NOTFAIR_CMO_DATA_DIR;
+ expect(notfairDataDir()).toBe(join(homedir(), ".notfair-cmo"));
+ });
+});
+
+describe("resolveBrowserProfileDir / resolveUserDataDir", () => {
+ beforeEach(() => {
+ process.env.NOTFAIR_CMO_DATA_DIR = "/tmp/notfair-cmo-test";
+ });
+ afterEach(() => {
+ delete process.env.NOTFAIR_CMO_DATA_DIR;
+ });
+
+ it("nests profile dir under projects/<slug>/browser", () => {
+ expect(resolveBrowserProfileDir("acme")).toBe(
+ "/tmp/notfair-cmo-test/projects/acme/browser",
+ );
+ });
+
+ it("nests user-data dir under the profile dir", () => {
+ expect(resolveUserDataDir("acme")).toBe(
+ "/tmp/notfair-cmo-test/projects/acme/browser/user-data",
+ );
+ });
+
+ it("throws on invalid slug", () => {
+ expect(() => resolveBrowserProfileDir("Invalid Slug")).toThrow(/Invalid project slug/);
+ expect(() => resolveUserDataDir("")).toThrow(/Invalid project slug/);
+ });
+});
+
+describe("allocateCdpPort", () => {
+ it("returns a port in the configured range", () => {
+ const port = allocateCdpPort("acme");
+ expect(port).toBeGreaterThanOrEqual(CDP_PORT_RANGE_START);
+ expect(port).toBeLessThanOrEqual(CDP_PORT_RANGE_END);
+ });
+
+ it("is deterministic for the same slug", () => {
+ expect(allocateCdpPort("acme")).toBe(allocateCdpPort("acme"));
+ expect(allocateCdpPort("xyz-123")).toBe(allocateCdpPort("xyz-123"));
+ });
+
+ it("distributes across the range for different slugs (hash spreads)", () => {
+ const seen = new Set<number>();
+ for (let i = 0; i < 50; i++) {
+ seen.add(allocateCdpPort(`project-${i}`));
+ }
+ // 50 slugs into a 100-port space. Birthday-paradox expected distinct ≈ 39.
+ // We just want to prove the hash isn't degenerate; require >30 to give
+ // headroom over the expected value while staying deterministic.
+ expect(seen.size).toBeGreaterThan(30);
+ });
+
+ it("throws on invalid slug", () => {
+ expect(() => allocateCdpPort("Invalid")).toThrow(/Invalid project slug/);
+ });
+});
diff --git a/notfair-cmo/src/server/browser/paths.ts b/notfair-cmo/src/server/browser/paths.ts
new file mode 100644
index 00000000..8e06133c
--- /dev/null
+++ b/notfair-cmo/src/server/browser/paths.ts
@@ -0,0 +1,69 @@
+/**
+ * Per-workspace browser profile path + port resolution.
+ *
+ * Layout under ~/.notfair-cmo/ (override via NOTFAIR_CMO_DATA_DIR):
+ *
+ * projects/<slug>/browser/
+ * user-data/ <- Chrome --user-data-dir (cookies, login state)
+ * state.json <- last-launched metadata (signed_in_at, etc.)
+ *
+ * CDP ports are hashed deterministically from the project slug into the
+ * 19000-19099 range. We intentionally avoid openclaw's 18800-18899 range
+ * so both can run on the same machine without colliding.
+ */
+import { createHash } from "node:crypto";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+/** First CDP port in our managed range. */
+export const CDP_PORT_RANGE_START = 19000;
+/** Last CDP port in our managed range. */
+export const CDP_PORT_RANGE_END = 19099;
+
+const PROJECT_SLUG_REGEX = /^[a-z0-9][a-z0-9-]*$/;
+const MAX_SLUG_LENGTH = 64;
+
+/** Resolve the notfair-cmo data dir (matches db.ts / agent-meta.ts convention). */
+export function notfairDataDir(): string {
+ return process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
+}
+
+/** True when slug matches the lowercase-alphanum + hyphen format the rest of notfair-cmo uses. */
+export function isValidProjectSlug(slug: string): boolean {
+ if (!slug || slug.length > MAX_SLUG_LENGTH) return false;
+ return PROJECT_SLUG_REGEX.test(slug);
+}
+
+/** Per-project browser dir (parent of user-data + metadata files). */
+export function resolveBrowserProfileDir(projectSlug: string): string {
+ assertValidSlug(projectSlug);
+ return join(notfairDataDir(), "projects", projectSlug, "browser");
+}
+
+/** Chrome --user-data-dir for the workspace. Persists cookies / login state. */
+export function resolveUserDataDir(projectSlug: string): string {
+ return join(resolveBrowserProfileDir(projectSlug), "user-data");
+}
+
+/**
+ * Deterministic CDP port for a project slug.
+ *
+ * Same slug always hashes to the same port across restarts, so a relaunched
+ * notfair-cmo process can reattach to a still-running Chrome without
+ * re-discovering ports.
+ */
+export function allocateCdpPort(projectSlug: string): number {
+ assertValidSlug(projectSlug);
+ const span = CDP_PORT_RANGE_END - CDP_PORT_RANGE_START + 1;
+ const hash = createHash("sha256").update(projectSlug).digest();
+ const offset = hash.readUInt32BE(0) % span;
+ return CDP_PORT_RANGE_START + offset;
+}
+
+function assertValidSlug(slug: string): void {
+ if (!isValidProjectSlug(slug)) {
+ throw new Error(
+ `Invalid project slug "${slug}": must match ${PROJECT_SLUG_REGEX} and be <=${MAX_SLUG_LENGTH} chars`,
+ );
+ }
+}
diff --git a/notfair-cmo/src/server/browser/session.test.ts b/notfair-cmo/src/server/browser/session.test.ts
new file mode 100644
index 00000000..903eab1f
--- /dev/null
+++ b/notfair-cmo/src/server/browser/session.test.ts
@@ -0,0 +1,225 @@
+import { EventEmitter } from "node:events";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { ChromeLaunchOptions, LaunchedChrome } from "./chrome";
+import type { Browser, BrowserContext } from "playwright-core";
+import {
+ _sessionsByProject,
+ getOrLaunchBrowser,
+ getSessionStatus,
+ stopAllBrowsers,
+ stopBrowser,
+} from "./session";
+
+// ── Fakes ────────────────────────────────────────────────────────────────
+
+class FakeProcess extends EventEmitter {
+ exitCode: number | null = null;
+ killed = false;
+ kill(_signal?: string) {
+ if (this.exitCode === null) {
+ this.exitCode = 0;
+ this.killed = true;
+ setImmediate(() => this.emit("exit", 0, null));
+ }
+ return true;
+ }
+}
+
+function makeLaunched(port: number): LaunchedChrome {
+ return {
+ process: new FakeProcess() as unknown as LaunchedChrome["process"],
+ cdpPort: port,
+ cdpHttpUrl: `http://127.0.0.1:${port}`,
+ userDataDir: `/tmp/notfair-cmo-test/projects/acme/browser/user-data`,
+ };
+}
+
+function makeFakeBrowser(): { browser: Browser; context: BrowserContext; closed: () => boolean } {
+ let closedFlag = false;
+ const context = {
+ pages: () => [],
+ on: vi.fn(),
+ once: vi.fn(),
+ newPage: vi.fn(),
+ close: vi.fn(async () => {}),
+ } as unknown as BrowserContext;
+ const browser = {
+ contexts: () => [context],
+ close: vi.fn(async () => {
+ closedFlag = true;
+ }),
+ } as unknown as Browser;
+ return { browser, context, closed: () => closedFlag };
+}
+
+beforeEach(() => {
+ process.env.NOTFAIR_CMO_DATA_DIR = "/tmp/notfair-cmo-test";
+ process.env.NOTFAIR_CHROME_PATH = "/usr/bin/fake-chrome";
+ _sessionsByProject.clear();
+});
+
+afterEach(async () => {
+ await stopAllBrowsers();
+ delete process.env.NOTFAIR_CMO_DATA_DIR;
+ delete process.env.NOTFAIR_CHROME_PATH;
+});
+
+// ── Tests ────────────────────────────────────────────────────────────────
+
+describe("getOrLaunchBrowser", () => {
+ it("launches Chrome and attaches Playwright on first call", async () => {
+ const launch = vi.fn(async (_opts: ChromeLaunchOptions) => makeLaunched(19042));
+ const fake = makeFakeBrowser();
+ const connectOverCDP = vi.fn(async () => fake.browser);
+
+ const session = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
+
+ expect(launch).toHaveBeenCalledOnce();
+ expect(connectOverCDP).toHaveBeenCalledWith("http://127.0.0.1:19042");
+ expect(session.projectSlug).toBe("acme");
+ expect(session.browser).toBe(fake.browser);
+ expect(session.context).toBe(fake.context);
+ });
+
+ it("reuses the cached session on subsequent calls", async () => {
+ const launch = vi.fn(async () => makeLaunched(19042));
+ const fake = makeFakeBrowser();
+ const connectOverCDP = vi.fn(async () => fake.browser);
+
+ const a = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
+ const b = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
+
+ expect(a).toBe(b);
+ expect(launch).toHaveBeenCalledOnce();
+ expect(connectOverCDP).toHaveBeenCalledOnce();
+ });
+
+ it("dedupes concurrent launches with the same slug", async () => {
+ let launchCount = 0;
+ const launch = vi.fn(async () => {
+ launchCount++;
+ await new Promise((r) => setTimeout(r, 20));
+ return makeLaunched(19042);
+ });
+ const fake = makeFakeBrowser();
+ const connectOverCDP = vi.fn(async () => fake.browser);
+
+ const [a, b, c] = await Promise.all([
+ getOrLaunchBrowser("acme", { launch, connectOverCDP }),
+ getOrLaunchBrowser("acme", { launch, connectOverCDP }),
+ getOrLaunchBrowser("acme", { launch, connectOverCDP }),
+ ]);
+
+ expect(launchCount).toBe(1);
+ expect(a).toBe(b);
+ expect(b).toBe(c);
+ });
+
+ it("relaunches when the cached session's Chrome process has exited", async () => {
+ const launch = vi
+ .fn<(opts: ChromeLaunchOptions) => Promise<LaunchedChrome>>()
+ .mockImplementationOnce(async () => makeLaunched(19042))
+ .mockImplementationOnce(async () => makeLaunched(19043));
+ const fake = makeFakeBrowser();
+ const connectOverCDP = vi.fn(async () => fake.browser);
+
+ const first = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
+ // Simulate Chrome dying.
+ (first.launched.process as unknown as FakeProcess).kill();
+ await new Promise((r) => setImmediate(r));
+
+ const second = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
+ expect(second).not.toBe(first);
+ expect(launch).toHaveBeenCalledTimes(2);
+ });
+
+ it("throws a friendly error when Chrome cannot be found", async () => {
+ // Override findChromeExecutable's discovery path by passing an empty
+ // executablePath (falsy, so the lookup fallback runs but lands on the
+ // null branch — explicit empty string sidesteps the env/file probe).
+ const launch = vi.fn();
+ const connectOverCDP = vi.fn();
+ await expect(
+ getOrLaunchBrowser("acme", {
+ executablePath: "",
+ launch,
+ connectOverCDP,
+ }),
+ ).rejects.toThrow(/Could not find Chrome/);
+ expect(launch).not.toHaveBeenCalled();
+ });
+
+ it("cleans up Chrome when Playwright attach fails", async () => {
+ const launched = makeLaunched(19042);
+ const launch = vi.fn(async () => launched);
+ const connectOverCDP = vi.fn(async () => {
+ throw new Error("CDP handshake failed");
+ });
+
+ await expect(
+ getOrLaunchBrowser("acme", { launch, connectOverCDP }),
+ ).rejects.toThrow(/Failed to attach Playwright/);
+
+ // Process should have been killed during cleanup.
+ expect((launched.process as unknown as FakeProcess).killed).toBe(true);
+ });
+
+ it("rejects connections with no default context", async () => {
+ const launched = makeLaunched(19042);
+ const launch = vi.fn(async () => launched);
+ const browser = {
+ contexts: () => [],
+ close: vi.fn(async () => {}),
+ } as unknown as Browser;
+ const connectOverCDP = vi.fn(async () => browser);
+
+ await expect(
+ getOrLaunchBrowser("acme", { launch, connectOverCDP }),
+ ).rejects.toThrow(/no default context/);
+ });
+});
+
+describe("stopBrowser", () => {
+ it("closes Playwright + Chrome and clears the registry entry", async () => {
+ const launched = makeLaunched(19042);
+ const launch = vi.fn(async () => launched);
+ const fake = makeFakeBrowser();
+ const connectOverCDP = vi.fn(async () => fake.browser);
+
+ await getOrLaunchBrowser("acme", { launch, connectOverCDP });
+ expect(_sessionsByProject.has("acme")).toBe(true);
+
+ await stopBrowser("acme");
+
+ expect(_sessionsByProject.has("acme")).toBe(false);
+ expect(fake.closed()).toBe(true);
+ expect((launched.process as unknown as FakeProcess).killed).toBe(true);
+ });
+
+ it("no-ops when the project has no active session", async () => {
+ await expect(stopBrowser("missing")).resolves.toBeUndefined();
+ });
+});
+
+describe("getSessionStatus", () => {
+ it("reports running=false when no session exists", () => {
+ const status = getSessionStatus("brand-new");
+ expect(status.running).toBe(false);
+ expect(status.cdpPort).toBeGreaterThanOrEqual(19000);
+ expect(status.cdpPort).toBeLessThanOrEqual(19099);
+ expect(status.userDataDir).toContain("brand-new/browser/user-data");
+ });
+
+ it("reports running=true with uptime once launched", async () => {
+ const launch = vi.fn(async () => makeLaunched(19042));
+ const fake = makeFakeBrowser();
+ const connectOverCDP = vi.fn(async () => fake.browser);
+ await getOrLaunchBrowser("acme", { launch, connectOverCDP });
+
+ const status = getSessionStatus("acme");
+ expect(status.running).toBe(true);
+ expect(status.launchedAt).toBeTypeOf("number");
+ expect(status.uptimeMs).toBeGreaterThanOrEqual(0);
+ });
+});
diff --git a/notfair-cmo/src/server/browser/session.ts b/notfair-cmo/src/server/browser/session.ts
new file mode 100644
index 00000000..3594368e
--- /dev/null
+++ b/notfair-cmo/src/server/browser/session.ts
@@ -0,0 +1,247 @@
+/**
+ * Workspace-scoped Chrome session lifecycle.
+ *
+ * One Chrome process per project, lazily launched the first time a browser
+ * tool runs for that project, reused for the remainder of the notfair-cmo
+ * process lifetime. Chrome's user-data-dir lock prevents a second concurrent
+ * instance, so all agents within a workspace share the same Chrome and
+ * coordinate via labeled tabs (see tabs.ts).
+ *
+ * We deliberately do NOT auto-shutdown on idle in V1. Keeping Chrome warm
+ * preserves cookies (no extra disk writes) and avoids the 1-2s relaunch
+ * cost on every agent turn. Process-exit handlers in registerShutdownHooks()
+ * make sure we don't leak Chrome processes when notfair-cmo stops.
+ */
+import type { Browser, BrowserContext } from "playwright-core";
+
+import {
+ type ChromeLaunchOptions,
+ type LaunchedChrome,
+ findChromeExecutable,
+ launchChrome,
+ stopChrome,
+} from "./chrome";
+import { allocateCdpPort, resolveUserDataDir } from "./paths";
+
+export interface BrowserSession {
+ projectSlug: string;
+ cdpPort: number;
+ cdpHttpUrl: string;
+ userDataDir: string;
+ /** Live Chrome subprocess + metadata from launchChrome(). */
+ launched: LaunchedChrome;
+ /** Playwright Browser handle (CDP-attached). */
+ browser: Browser;
+ /** Persistent default context — owns the cookies/storage from user-data-dir. */
+ context: BrowserContext;
+ /** Wall-clock launch time, for diagnostics. */
+ launchedAt: number;
+}
+
+/**
+ * Per-process registry of running browser sessions, keyed by project slug.
+ * Exported for tests; production code goes through getOrLaunchBrowser().
+ */
+export const _sessionsByProject = new Map<string, BrowserSession>();
+
+/**
+ * In-flight launch promises, keyed by project slug. Without this, two
+ * concurrent tool calls on the same project would each kick off a Chrome
+ * launch, the second hitting Chrome's SingletonLock and failing.
+ */
+const _launchPromises = new Map<string, Promise<BrowserSession>>();
+
+export interface GetOrLaunchOptions {
+ /** Force headless. Default: respect NOTFAIR_BROWSER_HEADLESS env (default false on macOS, true on linux). */
+ headless?: boolean;
+ /** Override chrome executable path. Falls back to findChromeExecutable(). */
+ executablePath?: string;
+ /** Extra Chrome args. Useful for tests + advanced users. */
+ extraArgs?: string[];
+ /** Override the Playwright connect function (for tests). */
+ connectOverCDP?: (cdpHttpUrl: string) => Promise<Browser>;
+ /** Override the Chrome launcher (for tests). */
+ launch?: (opts: ChromeLaunchOptions) => Promise<LaunchedChrome>;
+}
+
+/**
+ * Lazily launch (or reuse) the workspace Chrome for a project.
+ *
+ * Idempotent: concurrent callers share the same launch promise. Subsequent
+ * calls after a successful launch return the cached session immediately.
+ */
+export async function getOrLaunchBrowser(
+ projectSlug: string,
+ opts: GetOrLaunchOptions = {},
+): Promise<BrowserSession> {
+ const existing = _sessionsByProject.get(projectSlug);
+ if (existing && isSessionAlive(existing)) {
+ return existing;
+ }
+ if (existing) {
+ // Stale entry from a crashed Chrome — clean it up before relaunching.
+ _sessionsByProject.delete(projectSlug);
+ }
+
+ const inflight = _launchPromises.get(projectSlug);
+ if (inflight) return inflight;
+
+ const promise = launchSession(projectSlug, opts).finally(() => {
+ _launchPromises.delete(projectSlug);
+ });
+ _launchPromises.set(projectSlug, promise);
+ return promise;
+}
+
+async function launchSession(
+ projectSlug: string,
+ opts: GetOrLaunchOptions,
+): Promise<BrowserSession> {
+ const executablePath = opts.executablePath ?? findChromeExecutable();
+ if (!executablePath) {
+ throw new Error(
+ "Could not find Chrome / Chromium. Install Chrome, or set NOTFAIR_CHROME_PATH to the binary.",
+ );
+ }
+
+ const userDataDir = resolveUserDataDir(projectSlug);
+ const cdpPort = allocateCdpPort(projectSlug);
+ const headless = resolveHeadless(opts.headless);
+
+ const launch = opts.launch ?? launchChrome;
+ const launched = await launch({
+ executablePath,
+ userDataDir,
+ cdpPort,
+ headless,
+ extraArgs: opts.extraArgs,
+ });
+
+ let browser: Browser;
+ try {
+ const connect = opts.connectOverCDP ?? defaultConnectOverCDP;
+ browser = await connect(launched.cdpHttpUrl);
+ } catch (err) {
+ await stopChrome(launched).catch(() => {});
+ throw new Error(
+ `Failed to attach Playwright to Chrome CDP at ${launched.cdpHttpUrl}: ${(err as Error).message}`,
+ );
+ }
+
+ const contexts = browser.contexts();
+ if (contexts.length === 0) {
+ await browser.close().catch(() => {});
+ await stopChrome(launched).catch(() => {});
+ throw new Error(
+ "Connected to Chrome CDP but no default context exists — Chrome may have launched in an unexpected mode.",
+ );
+ }
+ const context = contexts[0]!;
+
+ const session: BrowserSession = {
+ projectSlug,
+ cdpPort: launched.cdpPort,
+ cdpHttpUrl: launched.cdpHttpUrl,
+ userDataDir: launched.userDataDir,
+ launched,
+ browser,
+ context,
+ launchedAt: Date.now(),
+ };
+ _sessionsByProject.set(projectSlug, session);
+
+ // If Chrome exits unexpectedly, evict the cached session so the next call
+ // triggers a fresh launch instead of returning a dead handle.
+ launched.process.once("exit", () => {
+ if (_sessionsByProject.get(projectSlug) === session) {
+ _sessionsByProject.delete(projectSlug);
+ }
+ });
+
+ return session;
+}
+
+async function defaultConnectOverCDP(cdpHttpUrl: string): Promise<Browser> {
+ // Lazy import keeps playwright-core out of the cold-start path for
+ // notfair-cmo features that don't touch the browser.
+ const { chromium } = await import("playwright-core");
+ return chromium.connectOverCDP(cdpHttpUrl);
+}
+
+function resolveHeadless(explicit?: boolean): boolean {
+ if (explicit !== undefined) return explicit;
+ const env = process.env.NOTFAIR_BROWSER_HEADLESS?.trim().toLowerCase();
+ if (env === "1" || env === "true") return true;
+ if (env === "0" || env === "false") return false;
+ return process.platform === "linux"; // headed on macOS by default, headless on linux servers
+}
+
+function isSessionAlive(session: BrowserSession): boolean {
+ return session.launched.process.exitCode === null && !session.launched.process.killed;
+}
+
+/**
+ * Tear down a single project's browser session. Used by tests + the
+ * onboarding "restart browser" flow.
+ */
+export async function stopBrowser(projectSlug: string): Promise<void> {
+ const session = _sessionsByProject.get(projectSlug);
+ if (!session) return;
+ _sessionsByProject.delete(projectSlug);
+ try {
+ await session.browser.close();
+ } catch {
+ // Browser may already be dead; ignore.
+ }
+ await stopChrome(session.launched).catch(() => {});
+}
+
+/** Tear down every active session — call on process exit. */
+export async function stopAllBrowsers(): Promise<void> {
+ const slugs = [..._sessionsByProject.keys()];
+ await Promise.all(slugs.map((slug) => stopBrowser(slug)));
+}
+
+let _shutdownHooksInstalled = false;
+/**
+ * Register SIGINT/SIGTERM/beforeExit handlers that stop every browser
+ * session. Idempotent — safe to call from multiple call sites.
+ */
+export function registerShutdownHooks(): void {
+ if (_shutdownHooksInstalled) return;
+ _shutdownHooksInstalled = true;
+
+ const handler = () => {
+ void stopAllBrowsers();
+ };
+ process.once("SIGINT", handler);
+ process.once("SIGTERM", handler);
+ process.once("beforeExit", handler);
+}
+
+/** Status snapshot for browser_status MCP tool + diagnostics. */
+export interface BrowserSessionStatus {
+ projectSlug: string;
+ running: boolean;
+ cdpPort: number;
+ userDataDir: string;
+ launchedAt?: number;
+ uptimeMs?: number;
+}
+
+export function getSessionStatus(projectSlug: string): BrowserSessionStatus {
+ const session = _sessionsByProject.get(projectSlug);
+ const cdpPort = allocateCdpPort(projectSlug);
+ const userDataDir = resolveUserDataDir(projectSlug);
+ if (!session) {
+ return { projectSlug, running: false, cdpPort, userDataDir };
+ }
+ return {
+ projectSlug,
+ running: isSessionAlive(session),
+ cdpPort: session.cdpPort,
+ userDataDir: session.userDataDir,
+ launchedAt: session.launchedAt,
+ uptimeMs: Date.now() - session.launchedAt,
+ };
+}
diff --git a/notfair-cmo/src/server/browser/tabs.test.ts b/notfair-cmo/src/server/browser/tabs.test.ts
new file mode 100644
index 00000000..81476856
--- /dev/null
+++ b/notfair-cmo/src/server/browser/tabs.test.ts
@@ -0,0 +1,207 @@
+import { EventEmitter } from "node:events";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { Browser, BrowserContext, Page } from "playwright-core";
+import type { ChromeLaunchOptions, LaunchedChrome } from "./chrome";
+import {
+ _sessionsByProject,
+ getOrLaunchBrowser,
+ stopAllBrowsers,
+} from "./session";
+import { _resetTabRegistries, assertValidLabel, closeTab, getTab, listTabs, openTab } from "./tabs";
+
+// ── Page / Context / Browser fakes ───────────────────────────────────────
+
+class FakePage extends EventEmitter {
+ private _url = "about:blank";
+ private _title = "";
+ private _closed = false;
+
+ url() { return this._url; }
+ async title() { return this._title; }
+ isClosed() { return this._closed; }
+ async goto(url: string) { this._url = url; this._title = `title:${url}`; }
+ async close() {
+ if (this._closed) return;
+ this._closed = true;
+ this.emit("close");
+ }
+ setTitle(t: string) { this._title = t; }
+}
+
+class FakeContext extends EventEmitter {
+ private _pages: FakePage[] = [];
+ pages() { return [...this._pages] as unknown as Page[]; }
+ async newPage(): Promise<Page> {
+ const page = new FakePage();
+ this._pages.push(page);
+ page.once("close", () => {
+ this._pages = this._pages.filter((p) => p !== page);
+ });
+ this.emit("page", page);
+ return page as unknown as Page;
+ }
+ async close() {
+ this.emit("close");
+ }
+}
+
+class FakeProcess extends EventEmitter {
+ exitCode: number | null = null;
+ killed = false;
+ kill() {
+ if (this.exitCode === null) {
+ this.exitCode = 0;
+ this.killed = true;
+ setImmediate(() => this.emit("exit", 0, null));
+ }
+ return true;
+ }
+}
+
+function makeFakeBrowserAndLaunch() {
+ const context = new FakeContext();
+ const browser = {
+ contexts: () => [context as unknown as BrowserContext],
+ close: vi.fn(async () => {}),
+ } as unknown as Browser;
+ const launched: LaunchedChrome = {
+ process: new FakeProcess() as unknown as LaunchedChrome["process"],
+ cdpPort: 19042,
+ cdpHttpUrl: "http://127.0.0.1:19042",
+ userDataDir: "/tmp/notfair-cmo-test/projects/acme/browser/user-data",
+ };
+ return {
+ launched,
+ browser,
+ context,
+ launch: vi.fn(async (_o: ChromeLaunchOptions) => launched),
+ connectOverCDP: vi.fn(async () => browser),
+ };
+}
+
+beforeEach(async () => {
+ process.env.NOTFAIR_CMO_DATA_DIR = "/tmp/notfair-cmo-test";
+ process.env.NOTFAIR_CHROME_PATH = "/usr/bin/fake-chrome";
+ _sessionsByProject.clear();
+ _resetTabRegistries();
+});
+
+afterEach(async () => {
+ await stopAllBrowsers();
+ _resetTabRegistries();
+ delete process.env.NOTFAIR_CMO_DATA_DIR;
+ delete process.env.NOTFAIR_CHROME_PATH;
+});
+
+// ── Tests ────────────────────────────────────────────────────────────────
+
+describe("assertValidLabel", () => {
+ it.each(["greg", "tina_googleads", "agent-1", "a"])("accepts %s", (l) => {
+ expect(() => assertValidLabel(l)).not.toThrow();
+ });
+ it.each(["", "-greg", "greg page", "greg.cmo", "x".repeat(65)])("rejects %s", (l) => {
+ expect(() => assertValidLabel(l)).toThrow(/Invalid tab label/);
+ });
+});
+
+describe("openTab", () => {
+ it("opens a new tab with a caller-supplied label", async () => {
+ const env = makeFakeBrowserAndLaunch();
+ await getOrLaunchBrowser("acme", env);
+
+ const handle = await openTab("acme", { label: "greg", url: "https://example.com" });
+
+ expect(handle.id).toBe("greg");
+ expect(handle.label).toBe("greg");
+ expect(handle.url).toBe("https://example.com");
+ });
+
+ it("auto-generates t1/t2/... when label is omitted", async () => {
+ const env = makeFakeBrowserAndLaunch();
+ await getOrLaunchBrowser("acme", env);
+
+ const a = await openTab("acme");
+ const b = await openTab("acme");
+ expect(a.id).toMatch(/^t\d+$/);
+ expect(b.id).toMatch(/^t\d+$/);
+ expect(a.id).not.toBe(b.id);
+ });
+
+ it("reuses an existing labeled tab instead of opening a duplicate", async () => {
+ const env = makeFakeBrowserAndLaunch();
+ await getOrLaunchBrowser("acme", env);
+
+ const first = await openTab("acme", { label: "greg", url: "https://example.com" });
+ const second = await openTab("acme", { label: "greg", url: "https://other.com" });
+
+ expect(second.id).toBe(first.id);
+ expect(second.url).toBe("https://other.com");
+ // Only one page should exist on the context.
+ const tabs = await listTabs("acme");
+ expect(tabs).toHaveLength(1);
+ });
+
+ it("rejects invalid labels", async () => {
+ const env = makeFakeBrowserAndLaunch();
+ await getOrLaunchBrowser("acme", env);
+
+ await expect(openTab("acme", { label: "bad label" })).rejects.toThrow(/Invalid tab label/);
+ });
+});
+
+describe("getTab + listTabs + closeTab", () => {
+ it("getTab resolves by id and returns null for unknown refs", async () => {
+ const env = makeFakeBrowserAndLaunch();
+ await getOrLaunchBrowser("acme", env);
+
+ const opened = await openTab("acme", { label: "greg" });
+ const page = await getTab("acme", opened.id);
+ expect(page).not.toBeNull();
+ expect(await getTab("acme", "nope")).toBeNull();
+ });
+
+ it("listTabs includes all open tabs with current URL + title", async () => {
+ const env = makeFakeBrowserAndLaunch();
+ await getOrLaunchBrowser("acme", env);
+
+ await openTab("acme", { label: "greg", url: "https://greg.example/" });
+ await openTab("acme", { label: "tina", url: "https://tina.example/" });
+
+ const tabs = await listTabs("acme");
+ expect(tabs.map((t) => t.id).sort()).toEqual(["greg", "tina"]);
+ expect(tabs.find((t) => t.id === "greg")?.url).toBe("https://greg.example/");
+ expect(tabs.find((t) => t.id === "tina")?.title).toBe("title:https://tina.example/");
+ });
+
+ it("closeTab closes the page and removes it from the registry", async () => {
+ const env = makeFakeBrowserAndLaunch();
+ await getOrLaunchBrowser("acme", env);
+ await openTab("acme", { label: "greg" });
+
+ const ok = await closeTab("acme", "greg");
+ expect(ok).toBe(true);
+
+ const tabs = await listTabs("acme");
+ expect(tabs.find((t) => t.id === "greg")).toBeUndefined();
+ expect(await getTab("acme", "greg")).toBeNull();
+ });
+
+ it("closeTab returns false for an unknown ref", async () => {
+ const env = makeFakeBrowserAndLaunch();
+ await getOrLaunchBrowser("acme", env);
+ expect(await closeTab("acme", "missing")).toBe(false);
+ });
+
+ it("adopts pages opened on the context outside of openTab (e.g. oauth redirects)", async () => {
+ const env = makeFakeBrowserAndLaunch();
+ await getOrLaunchBrowser("acme", env);
+
+ // Simulate Chrome opening a tab itself (e.g. _blank link, oauth popup).
+ await env.context.newPage();
+
+ const tabs = await listTabs("acme");
+ expect(tabs).toHaveLength(1);
+ expect(tabs[0]!.id).toMatch(/^t\d+$/);
+ });
+});
diff --git a/notfair-cmo/src/server/browser/tabs.ts b/notfair-cmo/src/server/browser/tabs.ts
new file mode 100644
index 00000000..7dec27f1
--- /dev/null
+++ b/notfair-cmo/src/server/browser/tabs.ts
@@ -0,0 +1,209 @@
+/**
+ * Labeled-tab registry for a workspace browser session.
+ *
+ * Each agent gets a stable handle ("greg-cmo", "tina-googleads", or an
+ * auto-generated "t1", "t2", ...) that survives across MCP tool calls.
+ * Pages added/removed from the underlying BrowserContext are reconciled so
+ * agent-supplied targetIds keep resolving even when the user opens or
+ * closes tabs in the headed Chrome.
+ */
+import type { Page } from "playwright-core";
+
+import { getOrLaunchBrowser, type BrowserSession } from "./session";
+
+const TAB_LABEL_REGEX = /^[a-z0-9][a-z0-9_\-]{0,63}$/i;
+
+export interface TabHandle {
+ /** Stable id the agent passes back. Equals `label` when one was provided. */
+ id: string;
+ /** Human label (matches id when none was set by the caller). */
+ label: string;
+ /** Best-effort current URL — may be "about:blank" or stale until next snapshot. */
+ url: string;
+ /** Best-effort current title. */
+ title: string;
+}
+
+interface TabRegistry {
+ /** label/id → Page */
+ byId: Map<string, Page>;
+ /** Page → label (reverse lookup so we can rebuild handles after a list) */
+ labelByPage: WeakMap<Page, string>;
+ /** Counter for auto-generated ids ("t1", "t2", ...). */
+ autoCounter: number;
+ /** Cached project's BrowserSession; we re-validate on each call. */
+ session: BrowserSession;
+}
+
+const _registries = new Map<string, TabRegistry>();
+
+async function getRegistry(projectSlug: string): Promise<TabRegistry> {
+ const session = await getOrLaunchBrowser(projectSlug);
+ let registry = _registries.get(projectSlug);
+ if (!registry || registry.session !== session) {
+ registry = createRegistry(session);
+ _registries.set(projectSlug, registry);
+ }
+ return registry;
+}
+
+function createRegistry(session: BrowserSession): TabRegistry {
+ const registry: TabRegistry = {
+ byId: new Map(),
+ labelByPage: new WeakMap(),
+ autoCounter: 0,
+ session,
+ };
+
+ // Pre-adopt any pages already on the context (Chrome opens an about:blank
+ // on first launch). We do NOT subscribe to context.on("page") — openTab
+ // owns labeling, and externally-opened pages are reconciled lazily by
+ // listTabs(). Subscribing would race with openTab and produce duplicate
+ // entries for every labeled tab.
+ for (const page of session.context.pages()) {
+ adoptPage(registry, page, undefined);
+ }
+ session.context.on("close", () => {
+ registry.byId.clear();
+ });
+ return registry;
+}
+
+function adoptPage(
+ registry: TabRegistry,
+ page: Page,
+ explicitLabel: string | undefined,
+): TabHandle {
+ const existing = registry.labelByPage.get(page);
+ if (existing && registry.byId.get(existing) === page) {
+ return handleForPage(page, existing);
+ }
+ const label = explicitLabel ?? `t${++registry.autoCounter}`;
+ registry.byId.set(label, page);
+ registry.labelByPage.set(page, label);
+
+ page.once("close", () => {
+ if (registry.byId.get(label) === page) {
+ registry.byId.delete(label);
+ }
+ });
+ return handleForPage(page, label);
+}
+
+function handleForPage(page: Page, label: string): TabHandle {
+ return {
+ id: label,
+ label,
+ url: safe(() => page.url()),
+ title: "", // populated on demand to avoid eagerly hitting the page on every list
+ };
+}
+
+function safe<T>(fn: () => T, fallback = ""): T | string {
+ try {
+ return fn();
+ } catch {
+ return fallback;
+ }
+}
+
+/** Validate a caller-supplied tab label. Throws on bad input. */
+export function assertValidLabel(label: string): void {
+ if (!TAB_LABEL_REGEX.test(label)) {
+ throw new Error(
+ `Invalid tab label "${label}": must be 1-64 chars of [A-Za-z0-9_-], starting with alphanumeric`,
+ );
+ }
+}
+
+export interface OpenTabOptions {
+ /** Stable handle for future calls. Defaults to an auto id "t1"/"t2"/... */
+ label?: string;
+ /** Initial URL. If omitted, the tab is left at about:blank. */
+ url?: string;
+ /** Wait condition before returning. Default: "load". */
+ waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit";
+ /** Per-navigation timeout. Default: 30s. */
+ timeoutMs?: number;
+}
+
+/**
+ * Open a new tab. If `label` is supplied and already exists, reuses the
+ * existing tab and (optionally) navigates it — this matches the openclaw
+ * "reuse labeled tab" pattern that avoids duplicates on retries.
+ */
+export async function openTab(
+ projectSlug: string,
+ opts: OpenTabOptions = {},
+): Promise<TabHandle> {
+ const registry = await getRegistry(projectSlug);
+ if (opts.label) assertValidLabel(opts.label);
+
+ let page: Page;
+ let label: string;
+ if (opts.label && registry.byId.has(opts.label)) {
+ page = registry.byId.get(opts.label)!;
+ label = opts.label;
+ } else {
+ page = await registry.session.context.newPage();
+ const handle = adoptPage(registry, page, opts.label);
+ label = handle.label;
+ }
+
+ if (opts.url) {
+ await page.goto(opts.url, {
+ waitUntil: opts.waitUntil ?? "load",
+ timeout: opts.timeoutMs ?? 30_000,
+ });
+ }
+
+ return handleForPage(page, label);
+}
+
+/** Resolve a caller-supplied ref ("label", "t1", or raw guid) to a live Page. */
+export async function getTab(projectSlug: string, ref: string): Promise<Page | null> {
+ const registry = await getRegistry(projectSlug);
+ return registry.byId.get(ref) ?? null;
+}
+
+/** List every tab the registry knows about, with up-to-date url/title. */
+export async function listTabs(projectSlug: string): Promise<TabHandle[]> {
+ const registry = await getRegistry(projectSlug);
+ // Sync against actual pages — context.pages() is the source of truth.
+ for (const page of registry.session.context.pages()) {
+ if (!registry.labelByPage.has(page)) {
+ adoptPage(registry, page, undefined);
+ }
+ }
+ const handles: TabHandle[] = [];
+ for (const [label, page] of registry.byId.entries()) {
+ if (page.isClosed()) {
+ registry.byId.delete(label);
+ continue;
+ }
+ handles.push({
+ id: label,
+ label,
+ url: safe(() => page.url()),
+ title: await page.title().catch(() => ""),
+ });
+ }
+ return handles;
+}
+
+/** Close the tab and drop it from the registry. */
+export async function closeTab(projectSlug: string, ref: string): Promise<boolean> {
+ const registry = await getRegistry(projectSlug);
+ const page = registry.byId.get(ref);
+ if (!page) return false;
+ registry.byId.delete(ref);
+ if (!page.isClosed()) {
+ await page.close().catch(() => {});
+ }
+ return true;
+}
+
+/** Test-only: forget cached registries. Lets tests start clean. */
+export function _resetTabRegistries(): void {
+ _registries.clear();
+}
diff --git a/notfair-cmo/src/server/mcp-server/browser-tools.test.ts b/notfair-cmo/src/server/mcp-server/browser-tools.test.ts
new file mode 100644
index 00000000..ee3e16cd
--- /dev/null
+++ b/notfair-cmo/src/server/mcp-server/browser-tools.test.ts
@@ -0,0 +1,369 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// We mock the browser modules wholesale — these tests verify schema
+// parsing, error envelopes, and that the right action functions get
+// invoked with the right arguments. Real Page / Browser behavior is
+// covered by actions.test.ts and the E2E smoke test.
+
+vi.mock("@/server/browser/session", () => ({
+ getOrLaunchBrowser: vi.fn(async () => ({ projectSlug: "acme" })),
+ getSessionStatus: vi.fn(() => ({
+ projectSlug: "acme",
+ running: true,
+ cdpPort: 19042,
+ userDataDir: "/tmp/profile",
+ launchedAt: 1_000,
+ uptimeMs: 5_000,
+ })),
+ stopBrowser: vi.fn(async () => {}),
+}));
+
+vi.mock("@/server/browser/tabs", () => ({
+ openTab: vi.fn(async (_slug: string, opts: { label?: string; url?: string }) => ({
+ id: opts.label ?? "t1",
+ label: opts.label ?? "t1",
+ url: opts.url ?? "about:blank",
+ title: "",
+ })),
+ listTabs: vi.fn(async () => [
+ { id: "greg", label: "greg", url: "https://example.com", title: "Example" },
+ ]),
+ closeTab: vi.fn(async (_slug: string, ref: string) => ref === "greg"),
+ getTab: vi.fn(async (_slug: string, ref: string) =>
+ ref === "greg" ? ({ __fakePage: true } as unknown as null) : null,
+ ),
+}));
+
+vi.mock("@/server/browser/actions", () => ({
+ navigate: vi.fn(async () => ({ url: "https://example.com", title: "Example" })),
+ snapshot: vi.fn(async () => ({
+ url: "https://example.com",
+ title: "Example",
+ elements: [
+ { ref: "e1", role: "button", name: "Sign in" },
+ { ref: "e2", role: "input", name: "Email", value: "" },
+ ],
+ text: "Sign in to your account",
+ })),
+ click: vi.fn(async () => {}),
+ type: vi.fn(async () => {}),
+ press: vi.fn(async () => {}),
+ scroll: vi.fn(async () => {}),
+ back: vi.fn(async () => {}),
+}));
+
+import { BROWSER_TOOLS } from "./browser-tools";
+import * as session from "@/server/browser/session";
+import * as tabs from "@/server/browser/tabs";
+import * as actions from "@/server/browser/actions";
+
+function tool(name: string) {
+ const found = BROWSER_TOOLS.find((t) => t.name === name);
+ if (!found) throw new Error(`No tool named ${name}`);
+ return found;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+// ── Registry shape ─────────────────────────────────────────────────────
+
+describe("BROWSER_TOOLS registry", () => {
+ it("exposes exactly the 12 expected tools (status, tabs, open, close, navigate, snapshot, click, type, press, scroll, back, shutdown)", () => {
+ expect(BROWSER_TOOLS.map((t) => t.name).sort()).toEqual(
+ [
+ "browser_back",
+ "browser_click",
+ "browser_close",
+ "browser_navigate",
+ "browser_open",
+ "browser_press",
+ "browser_scroll",
+ "browser_shutdown",
+ "browser_snapshot",
+ "browser_status",
+ "browser_tabs",
+ "browser_type",
+ ].sort(),
+ );
+ });
+
+ it("each tool ships a non-empty description and a zod inputSchema", () => {
+ for (const t of BROWSER_TOOLS) {
+ expect(t.description.length).toBeGreaterThan(20);
+ expect(typeof t.inputSchema.safeParse).toBe("function");
+ }
+ });
+});
+
+// ── browser_status ─────────────────────────────────────────────────────
+
+describe("browser_status", () => {
+ it("returns running status from getSessionStatus", async () => {
+ const result = await tool("browser_status").handler({ project_slug: "acme" }, {});
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ const payload = JSON.parse(result.content[0]!.text);
+ expect(payload.running).toBe(true);
+ expect(payload.cdpPort).toBe(19042);
+ }
+ expect(session.getSessionStatus).toHaveBeenCalledWith("acme");
+ });
+
+ it("rejects missing project_slug", async () => {
+ const result = await tool("browser_status").handler({}, {});
+ expect(result.ok).toBe(false);
+ });
+});
+
+// ── browser_tabs ───────────────────────────────────────────────────────
+
+describe("browser_tabs", () => {
+ it("returns the tab list from listTabs", async () => {
+ const result = await tool("browser_tabs").handler({ project_slug: "acme" }, {});
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ const payload = JSON.parse(result.content[0]!.text);
+ expect(payload).toHaveLength(1);
+ expect(payload[0].id).toBe("greg");
+ }
+ expect(tabs.listTabs).toHaveBeenCalledWith("acme");
+ });
+});
+
+// ── browser_open ───────────────────────────────────────────────────────
+
+describe("browser_open", () => {
+ it("launches the session and forwards label + url", async () => {
+ const result = await tool("browser_open").handler(
+ { project_slug: "acme", label: "greg", url: "https://example.com" },
+ {},
+ );
+ expect(result.ok).toBe(true);
+ expect(session.getOrLaunchBrowser).toHaveBeenCalledWith("acme");
+ expect(tabs.openTab).toHaveBeenCalledWith("acme", {
+ label: "greg",
+ url: "https://example.com",
+ });
+ });
+
+ it("rejects invalid url", async () => {
+ const result = await tool("browser_open").handler(
+ { project_slug: "acme", url: "not a url" },
+ {},
+ );
+ expect(result.ok).toBe(false);
+ });
+
+ it("rejects invalid label format", async () => {
+ const result = await tool("browser_open").handler(
+ { project_slug: "acme", label: "bad label", url: "https://example.com" },
+ {},
+ );
+ expect(result.ok).toBe(false);
+ });
+});
+
+// ── browser_close ──────────────────────────────────────────────────────
+
+describe("browser_close", () => {
+ it("reports success when closeTab returns true", async () => {
+ const result = await tool("browser_close").handler(
+ { project_slug: "acme", target_id: "greg" },
+ {},
+ );
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.content[0]!.text).toMatch(/Closed tab/);
+ }
+ });
+
+ it("reports no-op when closeTab returns false", async () => {
+ const result = await tool("browser_close").handler(
+ { project_slug: "acme", target_id: "missing" },
+ {},
+ );
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.content[0]!.text).toMatch(/No tab/);
+ }
+ });
+});
+
+// ── browser_navigate ───────────────────────────────────────────────────
+
+describe("browser_navigate", () => {
+ it("invokes actions.navigate on the resolved tab", async () => {
+ const result = await tool("browser_navigate").handler(
+ { project_slug: "acme", target_id: "greg", url: "https://example.com" },
+ {},
+ );
+ expect(result.ok).toBe(true);
+ expect(actions.navigate).toHaveBeenCalledOnce();
+ expect((actions.navigate as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({
+ url: "https://example.com",
+ });
+ });
+
+ it("returns a clear error when the tab handle is unknown", async () => {
+ const result = await tool("browser_navigate").handler(
+ { project_slug: "acme", target_id: "ghost", url: "https://example.com" },
+ {},
+ );
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error).toMatch(/No tab "ghost"/);
+ });
+});
+
+// ── browser_snapshot ───────────────────────────────────────────────────
+
+describe("browser_snapshot", () => {
+ it("returns the snapshot payload as JSON", async () => {
+ const result = await tool("browser_snapshot").handler(
+ { project_slug: "acme", target_id: "greg" },
+ {},
+ );
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ const payload = JSON.parse(result.content[0]!.text);
+ expect(payload.elements).toHaveLength(2);
+ expect(payload.elements[0].ref).toBe("e1");
+ }
+ });
+
+ it("respects max_elements truncation", async () => {
+ const result = await tool("browser_snapshot").handler(
+ { project_slug: "acme", target_id: "greg", max_elements: 1 },
+ {},
+ );
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ const payload = JSON.parse(result.content[0]!.text);
+ expect(payload.elements).toHaveLength(1);
+ }
+ });
+});
+
+// ── browser_click ──────────────────────────────────────────────────────
+
+describe("browser_click", () => {
+ it("forwards ref + button + modifiers to actions.click", async () => {
+ const result = await tool("browser_click").handler(
+ {
+ project_slug: "acme",
+ target_id: "greg",
+ ref: "e2",
+ button: "right",
+ modifiers: ["Meta"],
+ double_click: true,
+ },
+ {},
+ );
+ expect(result.ok).toBe(true);
+ expect((actions.click as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({
+ ref: "e2",
+ button: "right",
+ modifiers: ["Meta"],
+ doubleClick: true,
+ });
+ });
+
+ it("rejects refs that don't match e<number>", async () => {
+ const result = await tool("browser_click").handler(
+ { project_slug: "acme", target_id: "greg", ref: "weird" },
+ {},
+ );
+ expect(result.ok).toBe(false);
+ });
+});
+
+// ── browser_type ───────────────────────────────────────────────────────
+
+describe("browser_type", () => {
+ it("forwards text + submit + clear_first", async () => {
+ const result = await tool("browser_type").handler(
+ {
+ project_slug: "acme",
+ target_id: "greg",
+ ref: "e2",
+ text: "hello",
+ submit: true,
+ clear_first: false,
+ },
+ {},
+ );
+ expect(result.ok).toBe(true);
+ expect((actions.type as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({
+ ref: "e2",
+ text: "hello",
+ submit: true,
+ clearFirst: false,
+ });
+ });
+});
+
+// ── browser_press ──────────────────────────────────────────────────────
+
+describe("browser_press", () => {
+ it("forwards key + optional ref", async () => {
+ const result = await tool("browser_press").handler(
+ { project_slug: "acme", target_id: "greg", key: "Tab", ref: "e1" },
+ {},
+ );
+ expect(result.ok).toBe(true);
+ expect((actions.press as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({
+ key: "Tab",
+ ref: "e1",
+ });
+ });
+});
+
+// ── browser_scroll ─────────────────────────────────────────────────────
+
+describe("browser_scroll", () => {
+ it("forwards direction + amount", async () => {
+ const result = await tool("browser_scroll").handler(
+ { project_slug: "acme", target_id: "greg", direction: "down", amount: 1000 },
+ {},
+ );
+ expect(result.ok).toBe(true);
+ expect((actions.scroll as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({
+ direction: "down",
+ amount: 1000,
+ });
+ });
+
+ it("rejects invalid direction", async () => {
+ const result = await tool("browser_scroll").handler(
+ { project_slug: "acme", target_id: "greg", direction: "diagonal" },
+ {},
+ );
+ expect(result.ok).toBe(false);
+ });
+});
+
+// ── browser_back / browser_shutdown ────────────────────────────────────
+
+describe("browser_back", () => {
+ it("invokes actions.back", async () => {
+ const result = await tool("browser_back").handler(
+ { project_slug: "acme", target_id: "greg" },
+ {},
+ );
+ expect(result.ok).toBe(true);
+ expect(actions.back).toHaveBeenCalledOnce();
+ });
+});
+
+describe("browser_shutdown", () => {
+ it("calls stopBrowser and reports success", async () => {
+ const result = await tool("browser_shutdown").handler({ project_slug: "acme" }, {});
+ expect(result.ok).toBe(true);
+ expect(session.stopBrowser).toHaveBeenCalledWith("acme");
+ });
+});
diff --git a/notfair-cmo/src/server/mcp-server/browser-tools.ts b/notfair-cmo/src/server/mcp-server/browser-tools.ts
new file mode 100644
index 00000000..e477d5ef
--- /dev/null
+++ b/notfair-cmo/src/server/mcp-server/browser-tools.ts
@@ -0,0 +1,467 @@
+/**
+ * MCP tool definitions for the workspace browser.
+ *
+ * Agent-facing surface modeled on Hermes' tool shape: many small, typed
+ * tools rather than one mega-tool with an action discriminator. Each tool
+ * takes `project_slug` (from IDENTITY.md, used to pick the right workspace
+ * Chrome) plus the action-specific args. Stable `targetId` handles let
+ * agents thread state across calls without re-snapshotting tabs.
+ */
+import { z } from "zod";
+
+import {
+ back as actBack,
+ click as actClick,
+ navigate as actNavigate,
+ press as actPress,
+ scroll as actScroll,
+ snapshot as actSnapshot,
+ type as actType,
+ type SnapshotElement,
+} from "@/server/browser/actions";
+import { getOrLaunchBrowser, getSessionStatus, stopBrowser } from "@/server/browser/session";
+import { closeTab, getTab, listTabs, openTab } from "@/server/browser/tabs";
+
+import type { ToolDefinition, ToolResult } from "./tools";
+
+// ── Shared helpers ─────────────────────────────────────────────────────
+
+const projectSlug = z
+ .string()
+ .min(1)
+ .describe("The project this browser belongs to. From your IDENTITY.md prompt header.");
+
+const targetId = z
+ .string()
+ .min(1)
+ .describe(
+ "Tab handle from browser_open or browser_tabs. Use your agent_id as the label when opening, then reuse the same label in subsequent calls.",
+ );
+
+const ref = z
+ .string()
+ .regex(/^e\d+$/, "ref must look like 'e1', 'e2', ... from the latest snapshot")
+ .describe("Element ref from the most recent browser_snapshot call.");
+
+function invalid(err: z.ZodError): ToolResult {
+ return {
+ ok: false,
+ error: `Invalid arguments: ${err.issues
+ .map((i) => `${i.path.join(".")} ${i.message}`)
+ .join("; ")}`,
+ };
+}
+
+function txt(text: string): ToolResult {
+ return { ok: true, content: [{ type: "text", text }] };
+}
+
+function fail(message: string): ToolResult {
+ return { ok: false, error: message };
+}
+
+function safeMessage(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
+
+async function withTab<T>(
+ project_slug: string,
+ target: string,
+ fn: (page: Awaited<ReturnType<typeof getTab>>) => Promise<T>,
+): Promise<T | ToolResult> {
+ const page = await getTab(project_slug, target);
+ if (!page) {
+ return fail(
+ `No tab "${target}" in workspace "${project_slug}". Call browser_tabs to see what's open, or browser_open to create one.`,
+ );
+ }
+ return fn(page);
+}
+
+// ── browser_status ─────────────────────────────────────────────────────
+
+const browserStatusInput = z.object({ project_slug: projectSlug });
+
+async function handleBrowserStatus(input: unknown): Promise<ToolResult> {
+ const parsed = browserStatusInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const status = getSessionStatus(parsed.data.project_slug);
+ return txt(
+ JSON.stringify(
+ {
+ running: status.running,
+ cdpPort: status.cdpPort,
+ userDataDir: status.userDataDir,
+ uptimeMs: status.uptimeMs,
+ // V1 has no real signed-in check; surface the user-data-dir so
+ // agents/users know cookies persist across restarts.
+ note: status.running
+ ? "Workspace browser is running. Use browser_tabs to list windows."
+ : "Workspace browser is not running. The first browser_open will launch it.",
+ },
+ null,
+ 2,
+ ),
+ );
+}
+
+// ── browser_tabs ───────────────────────────────────────────────────────
+
+const browserTabsInput = z.object({ project_slug: projectSlug });
+
+async function handleBrowserTabs(input: unknown): Promise<ToolResult> {
+ const parsed = browserTabsInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ try {
+ const tabs = await listTabs(parsed.data.project_slug);
+ return txt(JSON.stringify(tabs, null, 2));
+ } catch (err) {
+ return fail(`browser_tabs failed: ${safeMessage(err)}`);
+ }
+}
+
+// ── browser_open ───────────────────────────────────────────────────────
+
+const browserOpenInput = z.object({
+ project_slug: projectSlug,
+ url: z.string().url().optional().describe("Initial URL. Omit to open about:blank."),
+ label: z
+ .string()
+ .regex(/^[a-z0-9][a-z0-9_\-]{0,63}$/i)
+ .optional()
+ .describe(
+ "Stable handle for future calls. Recommended: your agent_id. Reusing an existing label navigates that tab instead of opening a duplicate.",
+ ),
+});
+
+async function handleBrowserOpen(input: unknown): Promise<ToolResult> {
+ const parsed = browserOpenInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, url, label } = parsed.data;
+ try {
+ // Ensure the session is up — first open triggers the Chrome launch.
+ await getOrLaunchBrowser(project_slug);
+ const handle = await openTab(project_slug, { label, url });
+ return txt(JSON.stringify(handle, null, 2));
+ } catch (err) {
+ return fail(`browser_open failed: ${safeMessage(err)}`);
+ }
+}
+
+// ── browser_close ──────────────────────────────────────────────────────
+
+const browserCloseInput = z.object({
+ project_slug: projectSlug,
+ target_id: targetId,
+});
+
+async function handleBrowserClose(input: unknown): Promise<ToolResult> {
+ const parsed = browserCloseInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, target_id } = parsed.data;
+ try {
+ const ok = await closeTab(project_slug, target_id);
+ return txt(ok ? `Closed tab "${target_id}".` : `No tab "${target_id}" to close.`);
+ } catch (err) {
+ return fail(`browser_close failed: ${safeMessage(err)}`);
+ }
+}
+
+// ── browser_navigate ───────────────────────────────────────────────────
+
+const browserNavigateInput = z.object({
+ project_slug: projectSlug,
+ target_id: targetId,
+ url: z.string().url(),
+ wait_until: z.enum(["load", "domcontentloaded", "networkidle", "commit"]).optional(),
+ timeout_ms: z.number().int().positive().max(120_000).optional(),
+});
+
+async function handleBrowserNavigate(input: unknown): Promise<ToolResult> {
+ const parsed = browserNavigateInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, target_id, url, wait_until, timeout_ms } = parsed.data;
+ const result = await withTab(project_slug, target_id, async (page) => {
+ const r = await actNavigate(page!, { url, waitUntil: wait_until, timeoutMs: timeout_ms });
+ return txt(JSON.stringify(r, null, 2));
+ });
+ if (isToolResult(result)) return result;
+ return result;
+}
+
+// ── browser_snapshot ───────────────────────────────────────────────────
+
+const browserSnapshotInput = z.object({
+ project_slug: projectSlug,
+ target_id: targetId,
+ /** Truncate the element list shown to the model. Underlying snapshot may have more. */
+ max_elements: z.number().int().positive().max(200).optional(),
+});
+
+async function handleBrowserSnapshot(input: unknown): Promise<ToolResult> {
+ const parsed = browserSnapshotInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, target_id, max_elements } = parsed.data;
+ const result = await withTab(project_slug, target_id, async (page) => {
+ const snap = await actSnapshot(page!);
+ const elements: SnapshotElement[] = max_elements
+ ? snap.elements.slice(0, max_elements)
+ : snap.elements;
+ return txt(
+ JSON.stringify(
+ {
+ url: snap.url,
+ title: snap.title,
+ elements,
+ text: snap.text,
+ },
+ null,
+ 2,
+ ),
+ );
+ });
+ if (isToolResult(result)) return result;
+ return result;
+}
+
+// ── browser_click ──────────────────────────────────────────────────────
+
+const browserClickInput = z.object({
+ project_slug: projectSlug,
+ target_id: targetId,
+ ref: ref,
+ button: z.enum(["left", "right", "middle"]).optional(),
+ modifiers: z.array(z.enum(["Alt", "Control", "Meta", "Shift"])).optional(),
+ double_click: z.boolean().optional(),
+ timeout_ms: z.number().int().positive().max(30_000).optional(),
+});
+
+async function handleBrowserClick(input: unknown): Promise<ToolResult> {
+ const parsed = browserClickInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, target_id, ref, button, modifiers, double_click, timeout_ms } = parsed.data;
+ const result = await withTab(project_slug, target_id, async (page) => {
+ await actClick(page!, {
+ ref,
+ button,
+ modifiers,
+ doubleClick: double_click,
+ timeoutMs: timeout_ms,
+ });
+ return txt(`Clicked ${ref} on tab "${target_id}".`);
+ });
+ if (isToolResult(result)) return result;
+ return result;
+}
+
+// ── browser_type ───────────────────────────────────────────────────────
+
+const browserTypeInput = z.object({
+ project_slug: projectSlug,
+ target_id: targetId,
+ ref: ref,
+ text: z.string(),
+ submit: z.boolean().optional().describe("Press Enter after typing."),
+ clear_first: z.boolean().optional().describe("Clear the field before typing. Default true."),
+ timeout_ms: z.number().int().positive().max(30_000).optional(),
+});
+
+async function handleBrowserType(input: unknown): Promise<ToolResult> {
+ const parsed = browserTypeInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, target_id, ref, text, submit, clear_first, timeout_ms } = parsed.data;
+ const result = await withTab(project_slug, target_id, async (page) => {
+ await actType(page!, {
+ ref,
+ text,
+ submit,
+ clearFirst: clear_first,
+ timeoutMs: timeout_ms,
+ });
+ return txt(`Typed ${text.length} chars into ${ref}${submit ? " and submitted" : ""}.`);
+ });
+ if (isToolResult(result)) return result;
+ return result;
+}
+
+// ── browser_press ──────────────────────────────────────────────────────
+
+const browserPressInput = z.object({
+ project_slug: projectSlug,
+ target_id: targetId,
+ key: z
+ .string()
+ .min(1)
+ .describe("Playwright key string, e.g. 'Enter', 'Tab', 'Control+a', 'ArrowDown'."),
+ ref: z
+ .string()
+ .regex(/^e\d+$/)
+ .optional()
+ .describe("Focus this element before pressing. Omit to press at the page/keyboard level."),
+});
+
+async function handleBrowserPress(input: unknown): Promise<ToolResult> {
+ const parsed = browserPressInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, target_id, key, ref } = parsed.data;
+ const result = await withTab(project_slug, target_id, async (page) => {
+ await actPress(page!, { key, ref });
+ return txt(`Pressed ${key}${ref ? ` on ${ref}` : ""}.`);
+ });
+ if (isToolResult(result)) return result;
+ return result;
+}
+
+// ── browser_scroll ─────────────────────────────────────────────────────
+
+const browserScrollInput = z.object({
+ project_slug: projectSlug,
+ target_id: targetId,
+ direction: z.enum(["up", "down", "left", "right"]),
+ amount: z.number().int().positive().max(10_000).optional(),
+});
+
+async function handleBrowserScroll(input: unknown): Promise<ToolResult> {
+ const parsed = browserScrollInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, target_id, direction, amount } = parsed.data;
+ const result = await withTab(project_slug, target_id, async (page) => {
+ await actScroll(page!, { direction, amount });
+ return txt(`Scrolled ${direction}${amount ? ` by ${amount}px` : ""}.`);
+ });
+ if (isToolResult(result)) return result;
+ return result;
+}
+
+// ── browser_back ───────────────────────────────────────────────────────
+
+const browserBackInput = z.object({
+ project_slug: projectSlug,
+ target_id: targetId,
+});
+
+async function handleBrowserBack(input: unknown): Promise<ToolResult> {
+ const parsed = browserBackInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, target_id } = parsed.data;
+ const result = await withTab(project_slug, target_id, async (page) => {
+ await actBack(page!);
+ return txt(`Navigated back on tab "${target_id}".`);
+ });
+ if (isToolResult(result)) return result;
+ return result;
+}
+
+// ── browser_shutdown (admin) ───────────────────────────────────────────
+
+const browserShutdownInput = z.object({ project_slug: projectSlug });
+
+async function handleBrowserShutdown(input: unknown): Promise<ToolResult> {
+ const parsed = browserShutdownInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ try {
+ await stopBrowser(parsed.data.project_slug);
+ return txt(`Workspace browser for "${parsed.data.project_slug}" stopped.`);
+ } catch (err) {
+ return fail(`browser_shutdown failed: ${safeMessage(err)}`);
+ }
+}
+
+// ── Helpers ────────────────────────────────────────────────────────────
+
+function isToolResult(x: unknown): x is ToolResult {
+ return (
+ typeof x === "object" &&
+ x !== null &&
+ "ok" in x &&
+ (("content" in x && Array.isArray((x as ToolResult & { content?: unknown }).content)) ||
+ "error" in x)
+ );
+}
+
+// ── Registry export ────────────────────────────────────────────────────
+
+export const BROWSER_TOOLS: ToolDefinition[] = [
+ {
+ name: "browser_status",
+ description:
+ "Check whether the workspace browser is running and where its profile lives. Cheap; safe to call before any other browser tool.",
+ inputSchema: browserStatusInput,
+ handler: handleBrowserStatus,
+ },
+ {
+ name: "browser_tabs",
+ description:
+ "List every tab in the workspace browser with its handle, URL, and title. Call before browser_open to avoid duplicating a tab that already exists for your agent.",
+ inputSchema: browserTabsInput,
+ handler: handleBrowserTabs,
+ },
+ {
+ name: "browser_open",
+ description:
+ "Open (or reuse) a tab. Pass your agent_id as `label` so subsequent calls can target the same tab by handle. If `label` already exists, this navigates that tab instead of duplicating it. Returns a TabHandle.",
+ inputSchema: browserOpenInput,
+ handler: handleBrowserOpen,
+ },
+ {
+ name: "browser_close",
+ description: "Close a tab by handle. Safe no-op if the handle is unknown.",
+ inputSchema: browserCloseInput,
+ handler: handleBrowserClose,
+ },
+ {
+ name: "browser_navigate",
+ description: "Navigate an existing tab to a new URL. Returns the loaded URL + title.",
+ inputSchema: browserNavigateInput,
+ handler: handleBrowserNavigate,
+ },
+ {
+ name: "browser_snapshot",
+ description:
+ "Capture the page's interactable elements (buttons, links, inputs, etc.) with stable refs like e1/e2 plus a text excerpt. Snapshot the tab before any click/type so your refs are fresh — refs from a prior snapshot become stale after navigation or DOM mutation.",
+ inputSchema: browserSnapshotInput,
+ handler: handleBrowserSnapshot,
+ },
+ {
+ name: "browser_click",
+ description:
+ "Click an element by ref (from the latest browser_snapshot). Supports right/middle/double click and keyboard modifiers.",
+ inputSchema: browserClickInput,
+ handler: handleBrowserClick,
+ },
+ {
+ name: "browser_type",
+ description:
+ "Type text into an input/textarea/contenteditable ref. By default clears the field first; set submit=true to press Enter when done.",
+ inputSchema: browserTypeInput,
+ handler: handleBrowserType,
+ },
+ {
+ name: "browser_press",
+ description:
+ "Press a single key or key combo. With `ref` set, focuses that element first; without, presses at the page keyboard level (e.g. Escape to dismiss a modal).",
+ inputSchema: browserPressInput,
+ handler: handleBrowserPress,
+ },
+ {
+ name: "browser_scroll",
+ description:
+ "Scroll the viewport up/down/left/right. Defaults to ~600px (about one screen). Use when elements aren't visible in the current snapshot.",
+ inputSchema: browserScrollInput,
+ handler: handleBrowserScroll,
+ },
+ {
+ name: "browser_back",
+ description:
+ "Navigate back one entry in the tab's history. No-ops cleanly on the first page (no error).",
+ inputSchema: browserBackInput,
+ handler: handleBrowserBack,
+ },
+ {
+ name: "browser_shutdown",
+ description:
+ "Stop the workspace browser. Use rarely — only when the user explicitly asks to close it. Cookies persist in the profile dir, so the next browser_open relaunches with the same session.",
+ inputSchema: browserShutdownInput,
+ handler: handleBrowserShutdown,
+ },
+];
diff --git a/notfair-cmo/src/server/mcp-server/tools.ts b/notfair-cmo/src/server/mcp-server/tools.ts
index daf36716..17eb095e 100644
--- a/notfair-cmo/src/server/mcp-server/tools.ts
+++ b/notfair-cmo/src/server/mcp-server/tools.ts
@@ -26,6 +26,8 @@ import {
} from "@/server/orchestration/handlers";
import type { TaskStatus } from "@/types";
+import { BROWSER_TOOLS } from "./browser-tools";
+
/**
* Tool definitions exposed by notfair-cmo's MCP server to OpenClaw-side
* agents. The MCP server is **globally installed** (one OpenClaw row,
@@ -845,6 +847,7 @@ export const TOOLS: ToolDefinition[] = [
inputSchema: scheduleRecurringWorkInput,
handler: handleScheduleRecurringWorkTool,
},
+ ...BROWSER_TOOLS,
];
export function describeTool(tool: ToolDefinition): {