npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@mechris3/glassbox

v0.5.7

Published

Debugger-style browser automation test runner with live execution control via CDP

Readme

@mechris3/glassbox

Debugger-style browser automation test runner using Chrome DevTools Protocol (CDP) directly. No Puppeteer, no Playwright — just raw WebSocket + JSON.

Features:

  • Live execution control: breakpoints, pause/resume, step-through
  • Visual dashboard with real-time action streaming
  • Headless batch runner for CI
  • Diagnostic data collection (console errors, network, performance)
  • MCP server for AI agent integration
  • Browser and profile auto-detection

Quick Start

Note: There is an unrelated npm package also called glassbox (a code-review tool). Always use the full scoped name @mechris3/glassbox with npx to avoid resolving the wrong package.

# Install
npm install @mechris3/glassbox

# Scaffold a project (creates glassbox.config.ts + directories)
npx @mechris3/glassbox init

# Write journeys and page objects (see below), then:
npx @mechris3/glassbox serve     # Dashboard UI at http://localhost:3001
npx @mechris3/glassbox run       # Headless batch run (for CI)

glassbox init creates this structure in your current directory:

my-tests/
├── package.json          ← dependency + scripts
├── glassbox.config.ts    ← created by init
├── journeys/             ← put your journey files here
└── page-objects/         ← put your page objects here

The generated package.json includes convenience scripts:

npm run serve        # Start the visual dashboard at http://localhost:3001
npm run run          # Run all journeys headless (exit 0 = pass, 1 = fail)
npm run run:headed   # Run with a visible browser window

After running npx @mechris3/glassbox init, install dependencies and you're ready:

npm install
npm run serve

You can set this up as a standalone project or as a subfolder within an existing frontend project:

# Standalone
my-e2e-tests/
├── package.json
├── glassbox.config.ts
├── journeys/
└── page-objects/

# Inside an existing project
my-app/
├── src/
├── package.json
└── e2e/
    ├── glassbox.config.ts
    ├── journeys/
    └── page-objects/

Either way, run @mechris3/glassbox commands from the directory containing your glassbox.config.ts.

Prerequisites

  • Node.js 20+
  • A Chromium-based browser (Chrome, Brave, Edge)

Environment Variables

Config files, hooks, journeys, and page objects are all TypeScript running in Node — process.env works everywhere:

// page-objects/login.page.ts — credentials from env
async login() {
  const user = process.env.TEST_USERNAME ?? '[email protected]';
  const pass = process.env.TEST_PASSWORD ?? 'password123';
  await this.fill('[data-testid="email"]', user);
  await this.fill('[data-testid="password"]', pass);
  await this.click('[data-testid="submit"]');
}

// glassbox.config.ts — headless in CI
browser: { headless: process.env.CI === 'true' }

// helpers/before-each.ts — API key for test data service
const apiKey = process.env.TEST_API_KEY;
await fetch('http://...', { headers: { Authorization: `Bearer ${apiKey}` } });

Consumer Usage

Page Objects

Extend BasePage — no constructor needed. The following methods are available via this:

| Method | Description | |--------|-------------| | Interaction | | | click(selector) | Click an element | | hover(selector) | Hover over an element | | focus(selector) | Focus an element | | pressKey(key) | Press a key ('Enter', 'Tab', 'Escape', etc.) | | fill(selector, value) | Clear and set an input's value | | type(selector, value, {delay?}) | Type character by character | | uploadFile(selector, filePath) | Upload a file to a file input | | selectByIndex(selector, index) | Select dropdown option by index | | selectByValue(selector, value) | Select dropdown option by value | | selectByText(selector, text) | Select dropdown option by visible text | | Queries | | | getText(selector) | Get element's text content | | getInputValue(selector) | Get input's current value | | getAttribute(selector, attr) | Get an attribute value | | countElements(selector) | Count matching elements | | isVisible(selector) | Check if element is visible | | isDisabled(selector) | Check if element is disabled | | Waiting | | | waitForSelector(selector, {timeout?}) | Wait for element to appear | | waitForHidden(selector, {timeout?}) | Wait for element to disappear | | waitForText(selector, expected, {timeout?}) | Wait until text content matches | | waitForCount(selector, expected, {timeout?}) | Wait until element count matches | | waitForTimeout(ms) | Fixed delay (use sparingly) | | Navigation | | | goto(url) | Navigate (relative URLs resolve against target) | | clickAndWaitForNavigation(selector) | Click and wait for page load | | getCurrentUrl() | Get the current page URL | | Advanced | | | evaluate(script) | Execute arbitrary JS in the page | | clearSession(origin?) | Clear cookies and storage | | readClipboard() | Read text from clipboard | | addInitScript(source) | Register JS to run before page scripts on every navigation | | removeInitScript(identifier) | Remove a previously registered init script | | interceptRequests(patterns, handler) | Intercept network requests and return mock responses | | stopIntercepting() | Disable all request interception |

Example:

// page-objects/login.page.ts
import { BasePage } from '@mechris3/glassbox';

export class LoginPage extends BasePage {
  private selectors = {
    username: '[data-testid="username"]',
    password: '[data-testid="password"]',
    submit: '[data-testid="submit"]',
  };

  async login(user: string, pass: string) {
    await this.fill(this.selectors.username, user);
    await this.fill(this.selectors.password, pass);
    await this.click(this.selectors.submit);
  }

  async verifyLoggedIn(expectedName: string) {
    const name = await this.getText('[data-testid="display-name"]');
    if (name !== expectedName) throw new Error(`Expected "${expectedName}", got "${name}"`);
  }
}

Journeys

Extend Journey — use this.page() to create page objects:

// journeys/login.journey.ts
import { Journey } from '@mechris3/glassbox';
import { LoginPage } from '../page-objects/login.page';

export class LoginJourney extends Journey {
  loginPage = this.page(LoginPage);

  async execute() {
    await this.loginPage.login('testuser', 'password123');
    await this.loginPage.verifyLoggedIn('testuser');
  }
}

The Journey base class provides:

| Method | Description | |--------|-------------| | this.page(PageClass) | Create a page object bound to the default browser session. | | this.createClient(name, options?) | Get a named, fully-isolated browser session (own context/cookies/auth). Same name → same client. Optional { width, height } overrides the window size for this client. Provisioned eagerly; await it. See Multi-Session Journeys. | | client.page(PageClass) | Create a page object bound to that client's isolated session. |

Config

All paths in the config are relative to the config file's directory:

my-tests/
├── glassbox.config.ts
├── journeys/
│   └── login.journey.ts
├── page-objects/
│   └── login.page.ts
└── helpers/
    └── before-each.ts
// glassbox.config.ts
import { defineConfig } from '@mechris3/glassbox';

export default defineConfig({
  journeys: './journeys/**/*.journey.ts',
  browser: {
    defaultWindowSize: { width: 1280, height: 720 },
    headless: false,
  },
  server: { port: 3001 },
  testData: {
    beforeEach: './helpers/before-each.ts',
  },
});

Stealth / automation-detection

By default a CDP-launched browser advertises that it is automated: navigator.webdriver is true and Chromium exposes automation-controlled hints. Some anti-bot systems read those passive signals and may loop or deny the session. The opt-in stealth option suppresses that passive announcement:

import { defineConfig } from '@mechris3/glassbox';

export default defineConfig({
  browser: {
    stealth: true, // off by default
  },
});

When enabled, glassbox applies exactly two passive measures:

  1. Launches the browser with --disable-blink-features=AutomationControlled.
  2. Registers an init script on every new document so navigator.webdriver reports undefined before any page script runs.

Honest scope: this only stops the browser from passively announcing that it is automated. It does not defeat behavioural analysis, managed/interactive challenges (such as Cloudflare's managed challenge), CAPTCHAs, TLS/JA3 fingerprinting, canvas fingerprinting, or user-agent based detection. It is off by default, and leaving it unset keeps behaviour identical to earlier versions.

Video capture

The opt-in video option records each journey's page to a browser-playable VP8 .webm:

import { defineConfig } from '@mechris3/glassbox';

export default defineConfig({
  browser: {
    video: true, // off by default
    // Optional, CLI/CI only — hard cap (ms) on the encode so a batch run can never
    // hang on a stuck or very long encode. Default 60000 (60s). Ignored in serve mode,
    // which lets the encode run to completion. Inert unless `video` is enabled.
    videoFlushTimeoutMs: 60000,
    // Optional — cap on encoded frames (default 1500 ≈ 100s at 15fps). Bounds encode
    // time for very long journeys by keeping the most recent frames. Inert unless
    // `video` is enabled.
    videoMaxEncodedFrames: 1500,
    // Optional — pin each `createClient()` session's viewport to its window size via
    // Emulation.setDeviceMetricsOverride. Off by default; clients only.
    emulateViewport: false,
  },
});

You can also toggle recording from the dashboard settings panel in glassbox serve — the Record video checkbox is a run-wide switch (it applies to every journey in the run) and, when set, overrides the config-file browser.video value for that run. It is off by default, so leaving it unchecked records nothing. Set it in the config file for CLI runs, or from the dashboard for serve-mode runs.

When enabled, each journey records its page target via CDP Page.startScreencast and writes one file per journey to .glassbox/videos/<journey-slug>-<timestamp>.webm. The output is VP8 in a WebM container, so it plays in any Chromium browser and in standalone players such as VLC. Works headed and with --headless=new.

Recording is strictly best-effort and never affects a journey's pass/fail outcome. It runs entirely in the driver process on the CDP event channel; the journey never waits on it, and every recorder error is swallowed — a recorder fault can never slow, break, or fail the journey.

The encode is finalized shortly after the journey finishes, so the .webm may appear a moment after the journey's result:

  • In glassbox serve (the dashboard) the server is long-lived, so the encode runs to completion and is never cut off. When it finishes, the [VIDEO] wrote … line appears in the dashboard Console panel and the file is on disk. This is the common case, since video is primarily a dashboard feature.
  • In CLI/CI (glassbox run) the batch process must exit, so the encode is bounded by a generous, configurable hard cap — browser.videoFlushTimeoutMs, default 60s (≈1000 encoded frames at 15fps). A journey whose encode would exceed the cap is dropped (reported as timed out) so the batch can never hang. browser.videoMaxEncodedFrames (default 1500) is an additional backstop that bounds encode time for very long journeys by keeping the most recent frames.

When a journey fails (throws), its video uses the SAME generous, mode-aware flush budget as a passing journey. Recording is a deliberate, occasional diagnostic choice — it is slow, which naturally limits how often it is used, and people often run a single failing journey specifically to record it — so a long encode of the failed journey (usually the most valuable clip) is allowed to finish rather than being cut off by a short failure-only budget. The recorder finalizes the video from the frames captured up to the failure; when it finishes you get the failed journey's video ([VIDEO] wrote …). The run is still guaranteed to move on: it is bounded by that same budget (serve's large safety cap or CLI's configurable browser.videoFlushTimeoutMs) plus the unconditional worker terminate, and a completed encode is recognised promptly via the written file (file-as-artifact) rather than riding the full timeout — so only a genuinely-stuck worker (rare) runs to the budget ceiling, at which point it is terminated and the video is dropped (reported as timed out). Recording stays strictly best-effort and never alters a journey's pass/fail outcome.

The failure video ends on the actual failure state (robustness over speed). A change-driven screencast often stops emitting frames a moment before the final, most important transition — e.g. a "waiting for API" lightbox that is replaced by an error toast right as the step times out — so without help the clip can end on the pre-failure frame and lose exactly what you wanted to see. On failure (and only on failure, with video enabled), glassbox therefore does a short, bounded pre-encode step before encoding: it keeps the CDP connection open and the recorder running, briefly waits for the UI to settle (visual quiescence — no new screencast frame for ~500ms, hard-capped at 4s), then takes one explicit screenshot of the settled state and appends it as a guaranteed final frame held on screen for ~1.2s. A blind fixed delay is deliberately avoided in favour of quiescence because it either over-waits or misses a slow toast. The whole step is best-effort and hard-bounded (overall ceiling ~5s) — it can never hang, never changes the journey's pass/fail outcome, and on any error or dimension mismatch (the appended frame must match the video's dimensions) it simply falls back to encoding what was already captured, never worse than before. The appended frame is counted in the [VIDEO] wrote … (N frames) diagnostic. This is failure-path only; the passing-journey success path is unchanged.

Off by default, so leaving video unset is byte-for-byte identical to earlier versions — no env var is set, no recorder is constructed, and the new options are inert.

The file plays in Chromium, Firefox, and VLC, but not in QuickTime or Safari (neither supports VP8). It is written by creating the output directory at the write site and writing an absolute native path, so recordings land correctly on every platform — including Windows, where the folder was previously created but left empty. That Windows empty-folder case is now fully resolved: the write-site hardening and the parent↔worker completion handshake fix are complemented by a mode-aware encode budget. The encode on the WASM ArrayBuffer-fallback path (hit on Windows) costs roughly 60ms per encoded frame, and the encoded-frame count grows with the journey's duration, so a longer journey's encode legitimately needs tens of seconds — far more than the old fixed ~12s budget, which cut it off and left the folder empty. The budget is now generous (unbounded in serve, 60s configurable in CLI), so Windows now writes the file like macOS and Linux.

Because recording is best-effort and silent by design, each journey always emits a single [VIDEO] diagnostic that reports its outcome, so a dropped recording is explainable rather than mysterious. Every video-enabled journey emits exactly one of:

  • written — the capture succeeded (reports the frame count and the resolved output path);
  • dropped, with a reason — the encoder worker reported an error, exited non-zero, or no frames were captured;
  • timed out — the encoder worker did not complete within the flush budget (serve mode uses a large safety cap, CLI/CI the configurable browser.videoFlushTimeoutMs); the capture was abandoned so it could never block the run;
  • skipped — recording was not running from the built dist/ tree (dev mode; see the build-mode note below).

On a CLI glassbox run it prints as a 🎬 [VIDEO] line in the run output, and in glassbox serve it appears as a [VIDEO] log line in the dashboard Console panel. (A harmless wasm streaming compile failed … falling back to ArrayBuffer instantiation line from the encoder also prints on every platform — it is expected and not an error.)

Build-mode note: video is encoded by a worker_threads worker that only runs from the compiled build (npm run build → dist/). Under npm run dev (tsx) the encode step is skipped and the video is dropped — a best-effort, no-op outcome, never an error. See CHANGELOG.md for the encoder dependency note.

Best Practices

Journeys are pure orchestration

A journey's execute() method should contain only calls to page object methods — no conditionals, no assertions, no direct selectors:

// Good — reads like a user story
async execute() {
  await this.loginPage.loginAs('[email protected]', 'alice123');
  await this.dashboardPage.verifyLoaded();
  await this.dashboardPage.navigateToProjects();
  await this.projectsPage.verifyProjectCount(6);
}

// Bad — logic leaking into journey
async execute() {
  await this.fill('[data-testid="email"]', '[email protected]');
  const count = await this.getText('[data-testid="count"]');
  if (parseInt(count) !== 6) throw new Error('wrong');
}

Page objects own everything

  • Selectors — store in a private selectors object, never expose them
  • Interaction — loginAs(), addTask(), filterByStatus() — intention-revealing names
  • Validation — verifyLoaded(), verifyErrorMessage(), verifyTaskCount() — throw descriptive errors on failure
export class ProjectsPage extends BasePage {
  private selectors = {
    projectCard: '[data-testid="project-card"]',
    filterActive: '[data-testid="filter-active"]',
    count: '[data-testid="project-count"]',
  };

  async filterByActive() {
    await this.click(this.selectors.filterActive);
  }

  async verifyProjectCount(expected: number) {
    const count = await this.getText(this.selectors.count);
    if (count !== String(expected)) {
      throw new Error(`Expected ${expected} projects, got ${count}`);
    }
  }
}

Selector strategy

  • Always use [data-testid="..."] — never CSS classes, tag names, or DOM structure
  • For repeated items, include an identifier: [data-testid="task-item-${id}"]
  • If an element doesn't have a data-testid, add one to your app first

File organisation

glassbox/
├── page-objects/
│   ├── login.page.ts        ← one class per file
│   ├── dashboard.page.ts
│   └── projects.page.ts
├── journeys/
│   ├── login-and-browse.journey.ts
│   └── create-task.journey.ts
└── helpers/
    └── before-each.ts

Pre-Navigation Scripts (addInitScript)

Use addInitScript() to inject JavaScript that runs before any page code on every navigation. This is essential for apps that check auth state immediately on load (AWS Amplify/Cognito, Firebase Auth, Supabase) — you need to seed localStorage/cookies before the app's scripts execute, not after.

// page-objects/auth.page.ts
import { BasePage } from '@mechris3/glassbox';

export class AuthPage extends BasePage {
  private initScriptId: string | null = null;

  /** Seed fake auth tokens so the app loads in an authenticated state. */
  async seedFakeSession(token: string) {
    this.initScriptId = await this.addInitScript(`
      // This runs BEFORE Angular/React/Vue bootstraps
      localStorage.setItem('auth_token', '${token}');
      localStorage.setItem('user', JSON.stringify({ name: 'testuser', email: '[email protected]' }));
    `);
  }

  /** Remove the fake session so subsequent navigations hit the login page. */
  async clearFakeSession() {
    if (this.initScriptId) {
      await this.removeInitScript(this.initScriptId);
      this.initScriptId = null;
    }
  }
}
// journeys/dashboard.journey.ts
import { Journey } from '@mechris3/glassbox';
import { AuthPage } from '../page-objects/auth.page';
import { DashboardPage } from '../page-objects/dashboard.page';

export class DashboardJourney extends Journey {
  authPage = this.page(AuthPage);
  dashboardPage = this.page(DashboardPage);

  async execute() {
    // Register the init script BEFORE navigating
    await this.authPage.seedFakeSession('fake-jwt-token-here');

    // Now navigate — the init script runs before app code
    await this.authPage.goto('/');

    // App loads already authenticated — no login redirect
    await this.dashboardPage.verifyLoaded();
    await this.dashboardPage.verifyUserName('testuser');
  }
}

Key points:

  • Call addInitScript() before goto() — the script only fires on the next navigation
  • The script persists across navigations until explicitly removed with removeInitScript(id)
  • Use removeInitScript() when you need to test unauthenticated flows later in the same journey
  • The script runs in the page context (has access to localStorage, sessionStorage, document, window)
  • Multiple init scripts can be registered simultaneously — they run in registration order

Request Interception (API Mocking)

Use interceptRequests() to mock API responses at the network level. This uses CDP's Fetch domain — it intercepts real HTTP requests before they hit the network, so it works with both fetch() and XMLHttpRequest (Angular HttpClient, Axios, etc.).

// page-objects/api-mock.page.ts
import { BasePage, InterceptedRequest, MockResponse } from '@mechris3/glassbox';
import { readFileSync } from 'fs';

export class ApiMockPage extends BasePage {
  async enableMocks() {
    await this.interceptRequests(
      ['http://localhost:80/api/*', 'https://api.example.com/*'],
      async (request: InterceptedRequest): Promise<MockResponse | null> => {
        if (request.method === 'GET' && request.url.includes('/v1/users')) {
          const fixture = readFileSync('./fixtures/users.json', 'utf-8');
          return { status: 200, body: fixture };
        }
        if (request.url.includes('/v1/config')) {
          return { status: 200, body: JSON.stringify({ featureFlag: true }) };
        }
        // Return null to let unmatched requests through to the real server
        return null;
      }
    );
  }

  async disableMocks() {
    await this.stopIntercepting();
  }
}
// journeys/with-mocks.journey.ts
import { Journey } from '@mechris3/glassbox';
import { ApiMockPage } from '../page-objects/api-mock.page';
import { DashboardPage } from '../page-objects/dashboard.page';

export class WithMocksJourney extends Journey {
  apiMock = this.page(ApiMockPage);
  dashboard = this.page(DashboardPage);

  async execute() {
    await this.apiMock.enableMocks();
    await this.dashboard.goto('/');
    await this.dashboard.verifyUserCount(0); // mocked response has empty array
    await this.apiMock.disableMocks();
  }
}

Key points:

  • Patterns use simple wildcard matching (NOT regex): * matches any characters, everything else is literal
  • Pattern examples: http://localhost:80/*, */api/v1/*, *://api.example.com/*
  • The handler is called for each matching request — return a MockResponse to mock it, or null to let it through
  • Calling interceptRequests() again replaces the previous interception (not additive)
  • stopIntercepting() disables all interception — requests go directly to the network
  • Content-Type defaults to application/json if the response body starts with { or [
  • CORS headers (Access-Control-Allow-Origin: *) are added automatically
  • Lifecycle: mocks live for the duration of the journey — each journey runs in its own process with a fresh CDP session, so mocks are automatically cleaned up between journeys. You only need stopIntercepting() if you want to disable mocks mid-journey.

Multi-Session Journeys (two or more isolated users in one journey)

Use await this.createClient(name) to drive several fully-isolated browser sessions within a single journey. Each client owns its own CDP browser context — independent cookies, localStorage, sessionStorage and HTTP auth — the same isolation Playwright gives you with multiple BrowserContexts. This is the primitive for testing genuinely multi-user, real-time features (invites, presence, live updates): one user acts, another observes the effect against the real backend, no mocking.

glassbox stays protocol-agnostic. It hands you isolated, independently-driven sessions; how you wait for a "live" effect is ordinary DOM polling in your page objects. Any real-time transport specifics (SignalR, raw WebSocket, SSE) live in your test code, not in glassbox.

// journeys/two-user-invite.journey.ts
import { Journey } from '@mechris3/glassbox';
import { LoginPage } from '../page-objects/login.page';
import { InvitePage } from '../page-objects/invite.page';
import { NotificationsPage } from '../page-objects/notifications.page';

export class TwoUserInviteJourney extends Journey {
  async execute() {
    // Each client is a fresh, isolated browser context. Provisioning is eager:
    // the context + page target are created when you await createClient, so any
    // failure surfaces right here rather than at a later, surprising action.
    const host = await this.createClient('host');
    const guest = await this.createClient('guest');

    // Each client logs in independently against the REAL backend — no mocking.
    await host.page(LoginPage).loginAs('alice');
    await guest.page(LoginPage).loginAs('bob');

    await host.page(InvitePage).invite('bob');

    // Guest observes the live effect (e.g. a notification rendered in the DOM).
    // This is just a normal DOM wait — glassbox has no idea a SignalR event drove it.
    await guest.page(NotificationsPage).waitForInviteFrom('alice');
    await guest.page(InvitePage).accept();

    await host.page(NotificationsPage).waitForAcceptedBy('bob');
  }
}

The page objects are completely ordinary — they are the same BasePage subclasses you already write, and they have no awareness of multi-session at all:

// page-objects/notifications.page.ts
import { BasePage } from '@mechris3/glassbox';

export class NotificationsPage extends BasePage {
  // Ordinary DOM polling — glassbox has no idea a real-time event drove this.
  async waitForInviteFrom(name: string) {
    await this.waitForText('[data-testid="invite-from"]', name, { timeout: 10_000 });
  }
  async waitForAcceptedBy(name: string) {
    await this.waitForText('[data-testid="accepted-by"]', name, { timeout: 10_000 });
  }
}

Key points

  • this.page(X) still works exactly as before — it is the default client. Journeys that never call this.createClient(...) are completely unaffected and create no extra contexts.

  • Same name → same client. createClient('host') is idempotent; calling it again returns the same client.

  • True isolation, or a clear error. createClient is a primitive: it either hands you a cleanly-isolated context or it throws. There is deliberately no silent "shared context" fallback — a session that is secretly not isolated is worse than one that fails loudly.

  • TEST_DOMAIN is required. Each client opens its first page at your app's base URL (never about:blank, which would trip a CDP renderer-swap failure). If TEST_DOMAIN is unset, createClient throws explaining why.

  • Isolation is incognito-equivalent, not profile-based. A client is a fresh, empty context — it does not load a different on-disk Chrome profile. That keeps tests deterministic and portable (they don't depend on whatever is logged in on the machine). If you genuinely need two different real logged-in identities, log each client in explicitly inside the journey.

  • Each client gets its own window, sized like the default one. Client windows use browser.defaultWindowSize from your config. Override one client with createClient('guest', { width: 800, height: 600 }); precedence is per-client > browser.defaultWindowSize > the OS default (when no size is configured). Both values must be positive integers or createClient throws. Options on a repeat call for an existing name are ignored. Note that this sets the outer window size; a window manager may adjust it. Set browser.emulateViewport: true (off by default) to also pin each client's viewport with Emulation.setDeviceMetricsOverride, so layout is deterministic regardless. It applies to clients only, not the default session.

  • Lock-step is the recommended pattern. One WebSocket serializes all CDP commands, so driving clients in turn (A acts → assert B → …) is natural and clear. Promise.all across clients works but interleaves the action log.

  • The action log attributes each step to its client. Every action from an extra client is tagged with its name in the trace (e.g. host / guest), so interleaved multi-client steps are distinguishable. The default client's lines are unlabeled, exactly as before.

Scope for this release: the headless runner (glassbox run) supports N isolated clients fully. The serve dashboard's live view, screencast and pause/step/breakpoints currently target the primary (default) session; extra clients run and are driven correctly (and their action-log lines are client-tagged) but are not yet individually visualized or breakpointable. Per-client dashboard panels are a planned follow-up.

Lifecycle Hooks

Run code before/after journeys for test data setup and cleanup:

// glassbox.config.ts
export default defineConfig({
  hooks: {
    globalSetup: './helpers/global-setup.ts',    // Once before all journeys
    beforeEach: './helpers/before-each.ts',       // Before each journey
    afterEach: './helpers/after-each.ts',         // After each journey (even on failure)
    globalTeardown: './helpers/global-teardown.ts', // Once after all journeys
  },
});

Hook files export a default async function. Use them for any setup/teardown your tests need — resetting databases, seeding test data, clearing caches, etc:

// helpers/before-each.ts
import type { HookContext } from '@mechris3/glassbox';

export default async function(context: HookContext) {
  // Call your test API to reset state (can be any URL, not necessarily the target app)
  await fetch('http://localhost:4000/api/test-data/reset', { method: 'POST' });

  // Or seed specific data
  await fetch('http://localhost:4000/api/test-data/seed', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ users: ['testuser'], projects: 3 }),
  });
}

targetUrl comes from the dashboard settings panel (the URL field) or the --url flag when using the CLI. It's the URL of the app you're testing.

HookContext contains:

| Property | Available in | Description | |----------|-------------|-------------| | targetUrl | All hooks | The app URL being tested | | journeyName | beforeEach, afterEach | Display name of the current journey | | journeyPath | beforeEach, afterEach | File path of the current journey | | journeyStatus | afterEach only | 'passed' or 'failed' |

CLI Commands

Run all commands from the directory containing your glassbox.config.ts:

cd my-tests/   # where your glassbox.config.ts lives

Once you've run npm install in your project, use npm run serve / npm run run — these resolve the local node_modules/.bin/glassbox (the right one) automatically. When running outside a project with npx, always use the full scoped name: npx @mechris3/glassbox <command>

Dashboard (visual UI):

npx @mechris3/glassbox serve         # Start dashboard at http://localhost:3001

Open the URL in your browser to see journeys, run them, set breakpoints, pause/step, and inspect results visually.

Headless runner (CI / terminal):

npx @mechris3/glassbox run                          # Run all journeys, exit 0/1
npx @mechris3/glassbox run login                    # Only journeys matching "login"
npx @mechris3/glassbox run --url http://localhost:3000  # Specify app URL
npx @mechris3/glassbox run --headed                 # Show the browser while running
npx @mechris3/glassbox run --no-fail-fast           # Don't stop at first failure

Other:

npx @mechris3/glassbox init          # Scaffold config + directories in current dir
npx @mechris3/glassbox mcp           # Start MCP server for AI agent integration

MCP Server (AI Integration)

The MCP server lets AI agents debug failed journeys by querying diagnostic data.

Add it to your MCP client's config (e.g. .kiro/settings/mcp.json, or your client's equivalent):

{
  "mcpServers": {
    "glassbox": {
      "command": "npx",
      "args": ["@mechris3/glassbox", "mcp"],
      "env": { "GLASSBOX_URL": "http://localhost:3001" }
    }
  }
}

Requires glassbox serve to be running - the MCP server forwards every tool call to it over GLASSBOX_URL. Set GLASSBOX_URL only when serve is not on the default http://localhost:3001. The AI gets these tools:

| Tool | Purpose | |------|---------| | getDiagnosticSummary | Summary of diagnostic counts (call first) | | getConsoleErrors | console.error/warn with stack traces | | getExceptions | Unhandled JS exceptions with source locations | | getNetworkFailures | Failed HTTP requests (4xx/5xx/network errors) | | getNetworkLog | All XHR/Fetch requests with status codes | | getTimeline | Chronological event stream | | getPerformanceMetrics | Heap size, DOM nodes, layout recalculations | | listJourneys | Available journey files | | runJourney | Run by name/ID (browser stays open on failure) | | getDomSnapshot | Inspect page HTML or a specific element | | getScreenshot | Capture page screenshot (base64 PNG) | | getAccessibilityTree | Full ARIA tree for understanding page structure | | resetDiagnostics | Clear data + close live session before re-run |

The AI can identify journeys by name ("login"), ID ("login-and-add-todos"), or full path. After a failure, the browser stays open so getDomSnapshot and getScreenshot can inspect the failed state.

Inspecting a library-driven session

The MCP tools and the serve dashboard are built around the journey runner - they inspect the session a failed journey leaves open. If instead you use glassbox as a library (you launch and drive a CDP session yourself, without the journey runner), you can still point the diagnostic tools at your own live session.

Call registerInspectableSession({ wsEndpoint }) with the CDP WebSocket endpoint of your running browser. It hands that endpoint to a running glassbox serve, which then lets getDomSnapshot / getScreenshot / getAccessibilityTree (via the dashboard or an MCP client) read your session. This is opt-in and additive: if you never call it, serve and MCP behave exactly as before.

import {
  launchBrowser,
  CDPConnection,
  CDPAdapter,
  TargetDomain,
  PageDomain,
  RuntimeDomain,
  registerInspectableSession,
} from '@mechris3/glassbox';

// 1. Launch and drive a browser via the library (no journey runner).
const browser = await launchBrowser({ browserPath, headless: true });
const connection = await CDPConnection.connect(browser.wsEndpoint);

// Open a page target and attach to it, using the typed TargetDomain helper
// rather than raw CDP method strings.
const targets = new TargetDomain(connection);
const { targetId } = await targets.createTarget('about:blank');
const { sessionId } = await targets.attachToTarget(targetId, true);

// Enable the Page/Runtime domains so navigation events are delivered.
await new PageDomain(connection, sessionId).enable();
await new RuntimeDomain(connection, sessionId).enable();

const page = new CDPAdapter(connection, sessionId);
await page.goto('http://localhost:3000');

// 2. Expose this live session to a running `glassbox serve`.
await registerInspectableSession({ wsEndpoint: browser.wsEndpoint });
# 3. In another terminal, run the dashboard (if it isn't already running):
npx @mechris3/glassbox serve

Now an MCP client calling getDomSnapshot reads the HTML of your library-driven page, and getDiagnosticSummary reports liveSessionAvailable: true. Call unregisterInspectableSession() when you're done to detach.

Ownership / teardown: glassbox treats your registered session as attached, not owned. It only holds a CDP connection to your endpoint and will never kill your browser process - tearing the browser down stays your responsibility (detaching just closes serve's CDP connection).

History capture: console / network / exception / timeline history is now captured for a registered library-driven session too. When you call registerInspectableSession, serve attaches its own diagnostic collector to your session and records those events from that point on, so getConsoleErrors, getExceptions, getNetworkLog, getNetworkFailures, and getTimeline return live data (via the dashboard or an MCP client). Two caveats: events emitted before you register are not captured (the collector only records from the moment it attaches), and performance-metric snapshots remain journey-only, so the metrics endpoint is empty for a library-driven session.

License

Proprietary. All rights reserved.