Skip to content

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

feat(notfair-cmo): browser auto-shuts down after 5 min idle

Yuting Zhong0556122968e9
diff --git a/notfair-cmo/src/app/api/browser/launch/route.test.ts b/notfair-cmo/src/app/api/browser/launch/route.test.ts
index d1d1e610..ac539780 100644
--- a/notfair-cmo/src/app/api/browser/launch/route.test.ts
+++ b/notfair-cmo/src/app/api/browser/launch/route.test.ts
@@ -9,8 +9,8 @@ vi.mock("@/server/browser/session", () => ({
userDataDir: "/tmp/profile",
launchedAt: 1_000,
uptimeMs: 5_000,
+ idleTimeoutMs: 300_000,
})),
- registerShutdownHooks: vi.fn(),
}));
vi.mock("@/server/browser/tabs", () => ({
@@ -50,7 +50,6 @@ describe("POST /api/browser/launch", () => {
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 () => {
diff --git a/notfair-cmo/src/app/api/browser/launch/route.ts b/notfair-cmo/src/app/api/browser/launch/route.ts
index a7ce9a97..24bb076a 100644
--- a/notfair-cmo/src/app/api/browser/launch/route.ts
+++ b/notfair-cmo/src/app/api/browser/launch/route.ts
@@ -1,10 +1,6 @@
import { NextResponse } from "next/server";
-import {
- getOrLaunchBrowser,
- getSessionStatus,
- registerShutdownHooks,
-} from "@/server/browser/session";
+import { getOrLaunchBrowser, getSessionStatus } from "@/server/browser/session";
import { openTab } from "@/server/browser/tabs";
export const dynamic = "force-dynamic";
@@ -37,7 +33,8 @@ export async function POST(req: Request) {
}
try {
- registerShutdownHooks();
+ // Shutdown hooks + idle checker are auto-registered inside
+ // getOrLaunchBrowser, so this route does not need explicit setup.
await getOrLaunchBrowser(body.project_slug, { headless: body.headless ?? false });
const status = getSessionStatus(body.project_slug);
diff --git a/notfair-cmo/src/app/api/browser/status/route.test.ts b/notfair-cmo/src/app/api/browser/status/route.test.ts
index 146f412f..161a9393 100644
--- a/notfair-cmo/src/app/api/browser/status/route.test.ts
+++ b/notfair-cmo/src/app/api/browser/status/route.test.ts
@@ -8,6 +8,8 @@ vi.mock("@/server/browser/session", () => ({
userDataDir: "/tmp/profile",
launchedAt: 1_000,
uptimeMs: 5_000,
+ idleMs: 2_000,
+ idleTimeoutMs: 300_000,
})),
}));
@@ -50,6 +52,7 @@ describe("GET /api/browser/status", () => {
running: false,
cdpPort: 19042,
userDataDir: "/tmp/profile",
+ idleTimeoutMs: 300_000,
});
const res = await GET(makeReq("?project_slug=acme"));
const body = await res.json();
diff --git a/notfair-cmo/src/components/workspace-browser-card.test.tsx b/notfair-cmo/src/components/workspace-browser-card.test.tsx
index 6b0a2c1a..8cbf9fdb 100644
--- a/notfair-cmo/src/components/workspace-browser-card.test.tsx
+++ b/notfair-cmo/src/components/workspace-browser-card.test.tsx
@@ -41,13 +41,15 @@ describe("WorkspaceBrowserCard", () => {
expect(screen.getByText(/Profile dir:/)).toBeInTheDocument();
});
- it("shows running state, sign-in buttons, and open tabs when session is up", async () => {
+ it("shows running state, idle countdown, sign-in buttons, and open tabs when session is up", async () => {
mockFetch(() => ({
status: {
running: true,
cdpPort: 19042,
userDataDir: "/tmp/profile",
uptimeMs: 32_000,
+ idleMs: 60_000,
+ idleTimeoutMs: 300_000,
},
tabs: [
{ id: "greg", url: "https://greg.example/", title: "Greg" },
@@ -59,6 +61,8 @@ describe("WorkspaceBrowserCard", () => {
await waitFor(() => expect(screen.getByText(/Running on port 19042/)).toBeInTheDocument());
expect(screen.getByText(/32s uptime/)).toBeInTheDocument();
+ // 300_000 - 60_000 = 240_000ms → "auto-stops in 240s if idle"
+ expect(screen.getByText(/auto-stops in 240s if idle/)).toBeInTheDocument();
expect(screen.getByRole("button", { name: /Open Google/ })).toBeInTheDocument();
expect(screen.getByRole("button", { name: /Open Meta/ })).toBeInTheDocument();
expect(screen.getByText("greg")).toBeInTheDocument();
diff --git a/notfair-cmo/src/components/workspace-browser-card.tsx b/notfair-cmo/src/components/workspace-browser-card.tsx
index 0d4d71c3..bb878529 100644
--- a/notfair-cmo/src/components/workspace-browser-card.tsx
+++ b/notfair-cmo/src/components/workspace-browser-card.tsx
@@ -11,10 +11,25 @@ type Status = {
cdpPort: number;
userDataDir: string;
uptimeMs?: number;
+ idleMs?: number;
+ idleTimeoutMs: number;
};
type Tab = { id: string; url: string; title: string };
+function formatRunningStatus(status: Status): string {
+ const parts = [`Running on port ${status.cdpPort}`];
+ if (status.uptimeMs) parts.push(`${Math.round(status.uptimeMs / 1000)}s uptime`);
+ if (status.idleMs !== undefined) {
+ const remainingSec = Math.max(
+ 0,
+ Math.round((status.idleTimeoutMs - status.idleMs) / 1000),
+ );
+ parts.push(`auto-stops in ${remainingSec}s if idle`);
+ }
+ return parts.join(" · ");
+}
+
const SIGNIN_TARGETS: Array<{ label: string; url: string }> = [
{ label: "Google", url: "https://accounts.google.com/" },
{ label: "Meta / Facebook", url: "https://www.facebook.com/login/" },
@@ -124,8 +139,7 @@ export function WorkspaceBrowserCard({ projectSlug }: { projectSlug: string }) {
{loading
? "Checking…"
: status?.running
- ? `Running on port ${status.cdpPort}` +
- (status.uptimeMs ? ` · ${Math.round(status.uptimeMs / 1000)}s uptime` : "")
+ ? formatRunningStatus(status)
: "Not running"}
</span>
diff --git a/notfair-cmo/src/server/browser/session.test.ts b/notfair-cmo/src/server/browser/session.test.ts
index 903eab1f..e7cfc33a 100644
--- a/notfair-cmo/src/server/browser/session.test.ts
+++ b/notfair-cmo/src/server/browser/session.test.ts
@@ -5,6 +5,8 @@ import type { ChromeLaunchOptions, LaunchedChrome } from "./chrome";
import type { Browser, BrowserContext } from "playwright-core";
import {
_sessionsByProject,
+ _stopIdleChecker,
+ checkIdleSessions,
getOrLaunchBrowser,
getSessionStatus,
stopAllBrowsers,
@@ -56,13 +58,20 @@ function makeFakeBrowser(): { browser: Browser; context: BrowserContext; closed:
beforeEach(() => {
process.env.NOTFAIR_CMO_DATA_DIR = "/tmp/notfair-cmo-test";
process.env.NOTFAIR_CHROME_PATH = "/usr/bin/fake-chrome";
+ // Disable the idle ticker globally so tests that don't exercise it
+ // never get surprise shutdowns mid-assertion.
+ process.env.NOTFAIR_BROWSER_IDLE_DISABLED = "1";
_sessionsByProject.clear();
+ _stopIdleChecker();
});
afterEach(async () => {
await stopAllBrowsers();
+ _stopIdleChecker();
delete process.env.NOTFAIR_CMO_DATA_DIR;
delete process.env.NOTFAIR_CHROME_PATH;
+ delete process.env.NOTFAIR_BROWSER_IDLE_DISABLED;
+ delete process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS;
});
// ── Tests ────────────────────────────────────────────────────────────────
@@ -221,5 +230,84 @@ describe("getSessionStatus", () => {
expect(status.running).toBe(true);
expect(status.launchedAt).toBeTypeOf("number");
expect(status.uptimeMs).toBeGreaterThanOrEqual(0);
+ expect(status.idleMs).toBeGreaterThanOrEqual(0);
+ expect(status.idleTimeoutMs).toBe(5 * 60 * 1000);
+ });
+
+ it("reflects NOTFAIR_BROWSER_IDLE_TIMEOUT_MS in idleTimeoutMs", () => {
+ process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "90000";
+ const status = getSessionStatus("brand-new");
+ expect(status.idleTimeoutMs).toBe(90_000);
+ });
+
+ it("falls back to the default when the env value is non-numeric or non-positive", () => {
+ process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "garbage";
+ expect(getSessionStatus("a").idleTimeoutMs).toBe(5 * 60 * 1000);
+ process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "0";
+ expect(getSessionStatus("a").idleTimeoutMs).toBe(5 * 60 * 1000);
+ });
+});
+
+// ── Idle auto-shutdown ───────────────────────────────────────────────────
+
+describe("checkIdleSessions", () => {
+ it("stops sessions whose lastActivityAt exceeds the timeout", async () => {
+ process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "1000";
+ const launch = vi.fn(async () => makeLaunched(19042));
+ const fake = makeFakeBrowser();
+ const connectOverCDP = vi.fn(async () => fake.browser);
+
+ const session = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
+ // Backdate the lastActivityAt to make this session "idle".
+ session.lastActivityAt = Date.now() - 5_000;
+
+ const stopped = await checkIdleSessions();
+ expect(stopped).toEqual(["acme"]);
+ expect(_sessionsByProject.has("acme")).toBe(false);
+ });
+
+ it("leaves recently-active sessions running", async () => {
+ process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "60000";
+ const launch = vi.fn(async () => makeLaunched(19042));
+ const fake = makeFakeBrowser();
+ const connectOverCDP = vi.fn(async () => fake.browser);
+
+ await getOrLaunchBrowser("acme", { launch, connectOverCDP });
+ const stopped = await checkIdleSessions();
+ expect(stopped).toEqual([]);
+ expect(_sessionsByProject.has("acme")).toBe(true);
+ });
+
+ it("getOrLaunchBrowser bumps lastActivityAt on cache hit (touches the session)", async () => {
+ process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "1000";
+ const launch = vi.fn(async () => makeLaunched(19042));
+ const fake = makeFakeBrowser();
+ const connectOverCDP = vi.fn(async () => fake.browser);
+
+ const session = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
+ session.lastActivityAt = Date.now() - 10_000; // would-be idle
+
+ await getOrLaunchBrowser("acme", { launch, connectOverCDP });
+ // After the second call, the touch should have moved lastActivityAt forward.
+ expect(Date.now() - session.lastActivityAt).toBeLessThan(500);
+
+ // Idle check now leaves it alone.
+ const stopped = await checkIdleSessions();
+ expect(stopped).toEqual([]);
+ });
+
+ it("can shut down multiple idle projects in one tick", async () => {
+ process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "1000";
+ 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("beta", { launch, connectOverCDP });
+ a.lastActivityAt = Date.now() - 5_000;
+ b.lastActivityAt = Date.now() - 5_000;
+
+ const stopped = await checkIdleSessions();
+ expect(stopped.sort()).toEqual(["acme", "beta"]);
});
});
diff --git a/notfair-cmo/src/server/browser/session.ts b/notfair-cmo/src/server/browser/session.ts
index 3594368e..3a6794dd 100644
--- a/notfair-cmo/src/server/browser/session.ts
+++ b/notfair-cmo/src/server/browser/session.ts
@@ -2,15 +2,20 @@
* 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).
+ * tool runs for that project. 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.
+ * Shutdown happens four ways:
+ * 1. User clicks Settings → Workspace browser → Stop (manual).
+ * 2. notfair-cmo process exits — SIGINT/SIGTERM/beforeExit handlers
+ * registered automatically on the first launch.
+ * 3. User Cmd-Q's the Chrome window — process exit event evicts the
+ * cached session so the next browser_open relaunches.
+ * 4. Idle auto-shutdown: a 30s tick checks for sessions with no
+ * activity (no getOrLaunchBrowser call) in the last
+ * NOTFAIR_BROWSER_IDLE_TIMEOUT_MS (default 5 minutes). Disable
+ * with NOTFAIR_BROWSER_IDLE_DISABLED=1.
*/
import type { Browser, BrowserContext } from "playwright-core";
@@ -36,8 +41,13 @@ export interface BrowserSession {
context: BrowserContext;
/** Wall-clock launch time, for diagnostics. */
launchedAt: number;
+ /** Wall-clock of the most recent getOrLaunchBrowser call. Drives idle timeout. */
+ lastActivityAt: number;
}
+const DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1000;
+const IDLE_CHECK_INTERVAL_MS = 30_000;
+
/**
* Per-process registry of running browser sessions, keyed by project slug.
* Exported for tests; production code goes through getOrLaunchBrowser().
@@ -74,8 +84,15 @@ export async function getOrLaunchBrowser(
projectSlug: string,
opts: GetOrLaunchOptions = {},
): Promise<BrowserSession> {
+ // Every entry point goes through here, so this is also the right place
+ // to install our process-lifetime maintenance: shutdown hooks (cleanup on
+ // notfair-cmo exit) + idle checker (stop unused browsers).
+ registerShutdownHooks();
+ ensureIdleChecker();
+
const existing = _sessionsByProject.get(projectSlug);
if (existing && isSessionAlive(existing)) {
+ existing.lastActivityAt = Date.now();
return existing;
}
if (existing) {
@@ -147,6 +164,7 @@ async function launchSession(
browser,
context,
launchedAt: Date.now(),
+ lastActivityAt: Date.now(),
};
_sessionsByProject.set(projectSlug, session);
@@ -206,6 +224,8 @@ let _shutdownHooksInstalled = false;
/**
* Register SIGINT/SIGTERM/beforeExit handlers that stop every browser
* session. Idempotent — safe to call from multiple call sites.
+ * Auto-invoked from getOrLaunchBrowser so cron-triggered launches are
+ * covered too, not just UI launches via /api/browser/launch.
*/
export function registerShutdownHooks(): void {
if (_shutdownHooksInstalled) return;
@@ -219,6 +239,59 @@ export function registerShutdownHooks(): void {
process.once("beforeExit", handler);
}
+// ── Idle auto-shutdown ──────────────────────────────────────────────────
+
+function resolveIdleTimeoutMs(): number {
+ const raw = process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS?.trim();
+ if (!raw) return DEFAULT_IDLE_TIMEOUT_MS;
+ const n = Number(raw);
+ if (!Number.isFinite(n) || n <= 0) return DEFAULT_IDLE_TIMEOUT_MS;
+ return n;
+}
+
+let _idleCheckerInterval: ReturnType<typeof setInterval> | null = null;
+
+/**
+ * Start the periodic idle check. Idempotent — call freely. The Node
+ * interval is .unref'd so it never keeps the process alive on its own.
+ *
+ * Disable with NOTFAIR_BROWSER_IDLE_DISABLED=1 (useful for tests that
+ * want manual control, or for users who want Chrome to stay warm
+ * indefinitely).
+ */
+export function ensureIdleChecker(): void {
+ if (_idleCheckerInterval) return;
+ if (process.env.NOTFAIR_BROWSER_IDLE_DISABLED === "1") return;
+ _idleCheckerInterval = setInterval(() => {
+ void checkIdleSessions();
+ }, IDLE_CHECK_INTERVAL_MS);
+ _idleCheckerInterval.unref?.();
+}
+
+/**
+ * Find sessions with no getOrLaunchBrowser call inside the idle window
+ * and stop them. Exported for tests; production code calls via the timer.
+ */
+export async function checkIdleSessions(now: number = Date.now()): Promise<string[]> {
+ const idleTimeoutMs = resolveIdleTimeoutMs();
+ const slugsToStop: string[] = [];
+ for (const [slug, session] of _sessionsByProject) {
+ if (now - session.lastActivityAt >= idleTimeoutMs) {
+ slugsToStop.push(slug);
+ }
+ }
+ await Promise.all(slugsToStop.map((slug) => stopBrowser(slug)));
+ return slugsToStop;
+}
+
+/** Test-only: cancel the periodic checker. */
+export function _stopIdleChecker(): void {
+ if (_idleCheckerInterval) {
+ clearInterval(_idleCheckerInterval);
+ _idleCheckerInterval = null;
+ }
+}
+
/** Status snapshot for browser_status MCP tool + diagnostics. */
export interface BrowserSessionStatus {
projectSlug: string;
@@ -227,14 +300,20 @@ export interface BrowserSessionStatus {
userDataDir: string;
launchedAt?: number;
uptimeMs?: number;
+ /** Milliseconds since the last getOrLaunchBrowser call — what the idle
+ * shutdown timer compares against. */
+ idleMs?: number;
+ /** The current idle-shutdown threshold (env-overridable). */
+ idleTimeoutMs: number;
}
export function getSessionStatus(projectSlug: string): BrowserSessionStatus {
const session = _sessionsByProject.get(projectSlug);
const cdpPort = allocateCdpPort(projectSlug);
const userDataDir = resolveUserDataDir(projectSlug);
+ const idleTimeoutMs = resolveIdleTimeoutMs();
if (!session) {
- return { projectSlug, running: false, cdpPort, userDataDir };
+ return { projectSlug, running: false, cdpPort, userDataDir, idleTimeoutMs };
}
return {
projectSlug,
@@ -243,5 +322,7 @@ export function getSessionStatus(projectSlug: string): BrowserSessionStatus {
userDataDir: session.userDataDir,
launchedAt: session.launchedAt,
uptimeMs: Date.now() - session.launchedAt,
+ idleMs: Date.now() - session.lastActivityAt,
+ idleTimeoutMs,
};
}