Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions packages/replayio/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,20 @@ This CLI will automatically prompt you to log into your Replay account (or to re

The CLI will also prompt you to download the Replay runtime if you have not already done so.

## Browser facade

`replayio` exposes an `agent-browser` facade under the `browser` command:

```bash
replayio browser open https://google.com
replayio browser click "text=Sign in"
replayio browser close
```

`agent-browser` is installed as a dependency and patched to enforce Replay Chrome launch behavior.
On `replayio browser close`, recordings for the closed browser session are automatically uploaded
when you are authenticated (`replayio login` or `REPLAY_API_KEY`).

## Contributing

Contributing guide can be found [here](contributing.md).
6 changes: 6 additions & 0 deletions packages/replayio/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"scripts": {
"build": "pkg-build",
"lint": "prettier --write .",
"postinstall": "node ./scripts/apply-agent-browser-patches.js",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

postinstall scripts might get aggressively blocked by package managers - this package really shouldn't depend on them

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you summarize what this PR and what the patch is meant to accomplish here? From what I see agent-browser supports custom browser executables already. Can't this package just piggyback on that? What else is missing?

"test": "jest --ci",
"typecheck": "tsc --noEmit"
},
Expand All @@ -25,13 +26,17 @@
},
"files": [
"dist",
"patches",
"scripts",
"replayio.js"
],
"homepage": "https://github.com/replayio/replay-cli/blob/main/packages/replayio/README.md",
"dependencies": {
"@replayio/playwright": "5.0.1",
"@replayio/protocol": "^0.71.0",
"@replayio/sourcemap-upload": "workspace:^",
"@types/semver": "^7.5.6",
"agent-browser": "0.9.0",
"assert": "latest",
"bvaughn-enquirer": "2.4.2",
"chalk": "^4.1.2",
Expand All @@ -47,6 +52,7 @@
"log-update": "^4",
"mixpanel": "^0.18.0",
"open": "^8.4.2",
"patch-package": "^8.0.1",
"pretty-ms": "^7.0.1",
"query-registry": "^2.6.0",
"semver": "^7.5.4",
Expand Down
171 changes: 171 additions & 0 deletions packages/replayio/patches/agent-browser+0.9.0.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
diff --git a/node_modules/agent-browser/dist/browser.js b/node_modules/agent-browser/dist/browser.js
index 589b843..38d9f3f 100644
--- a/node_modules/agent-browser/dist/browser.js
+++ b/node_modules/agent-browser/dist/browser.js
@@ -1,8 +1,83 @@
import { chromium, firefox, webkit, devices, } from 'playwright-core';
+import * as replayPlaywright from '@replayio/playwright';
import path from 'node:path';
import os from 'node:os';
import { existsSync, mkdirSync, rmSync } from 'node:fs';
import { getEnhancedSnapshot, parseRef } from './snapshot.js';
+const REPLAY_REQUIRED_PREFIX = 'REPLAY_REQUIRED:';
+function replayRequiredError(message) {
+ return new Error(`${REPLAY_REQUIRED_PREFIX}\n${message}`);
+}
+function requireReplayExecutablePath(browserType, explicitPath) {
+ if (browserType && browserType !== 'chromium') {
+ throw replayRequiredError(`Replay Chrome is required to record every run.\n\n` +
+ `Unsupported browser type: ${browserType}.\n` +
+ `Use Chromium (Replay Chrome) or remove the --browser option.`);
+ }
+ const getExecutablePath = replayPlaywright.getExecutablePath;
+ if (!getExecutablePath) {
+ throw replayRequiredError(`Replay Chrome is required to record every run.\n\n` +
+ `Could not resolve Replay Chrome runtime.\n` +
+ `Run: agent-browser install`);
+ }
+ const resolved = getExecutablePath('chromium');
+ if (!resolved || !existsSync(resolved)) {
+ throw replayRequiredError(`Replay Chrome is required to record every run.\n\n` +
+ `Replay Chrome is not installed or not supported on this platform.\n` +
+ `Run: agent-browser install\n` +
+ `Supported: macOS (arm64/x64), Linux (x64).`);
+ }
+ if (explicitPath) {
+ const normalizedExplicit = path.resolve(explicitPath);
+ const normalizedResolved = path.resolve(resolved);
+ if (normalizedExplicit !== normalizedResolved) {
+ throw replayRequiredError(`Replay Chrome is required to record every run.\n\n` +
+ `Custom executable path does not match Replay Chrome.\n` +
+ `Resolved Replay Chrome: ${resolved}`);
+ }
+ return normalizedExplicit;
+ }
+ return resolved;
+}
+function getSessionProcessGroupId(sessionName) {
+ return `agent-browser-session:${sessionName}`;
+}
+function getReplayLaunchEnv(sessionName) {
+ const devices = replayPlaywright.devices;
+ const replayDevice = devices?.['Replay Chromium'];
+ const env = replayDevice?.launchOptions?.env;
+ const baseEnv = {
+ ...process.env,
+ ...(env && typeof env === 'object'
+ ? Object.fromEntries(Object.entries(env).flatMap(([key, value]) => value === undefined || value === null ? [] : [[key, String(value)]]))
+ : {}),
+ };
+ let metadata = {};
+ if (typeof process.env.RECORD_REPLAY_METADATA === 'string') {
+ try {
+ const parsed = JSON.parse(process.env.RECORD_REPLAY_METADATA);
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ metadata = parsed;
+ }
+ }
+ catch {
+ // Ignore malformed metadata and continue with session metadata only.
+ }
+ }
+ return Object.fromEntries(Object.entries({
+ ...baseEnv,
+ RECORD_ALL_CONTENT: '1',
+ RECORD_REPLAY_VERBOSE: '1',
+ RECORD_REPLAY_METADATA: JSON.stringify({
+ ...metadata,
+ browserSession: sessionName,
+ processGroupId: getSessionProcessGroupId(sessionName),
+ }),
+ ...(process.env.RECORD_REPLAY_ENABLE_ASSERTS
+ ? { RECORD_REPLAY_ENABLE_ASSERTS: process.env.RECORD_REPLAY_ENABLE_ASSERTS }
+ : {}),
+ }).flatMap(([key, value]) => value === undefined || value === null ? [] : [[key, String(value)]]));
+}
/**
* Manages the Playwright browser lifecycle with multiple tabs/windows
*/
@@ -880,7 +955,10 @@ export class BrowserManager {
await this.connectToKernel();
return;
}
+ const session = process.env.AGENT_BROWSER_SESSION || 'default';
const browserType = options.browser ?? 'chromium';
+ const executablePath = requireReplayExecutablePath(browserType, options.executablePath);
+ const replayLaunchEnv = getReplayLaunchEnv(session);
if (hasExtensions && browserType !== 'chromium') {
throw new Error('Extensions are only supported in Chromium');
}
@@ -890,17 +968,17 @@ export class BrowserManager {
if (hasExtensions) {
// Extensions require persistent context in a temp directory
const extPaths = options.extensions.join(',');
- const session = process.env.AGENT_BROWSER_SESSION || 'default';
// Combine extension args with custom args
const extArgs = [`--disable-extensions-except=${extPaths}`, `--load-extension=${extPaths}`];
const allArgs = options.args ? [...extArgs, ...options.args] : extArgs;
context = await launcher.launchPersistentContext(path.join(os.tmpdir(), `agent-browser-ext-${session}`), {
headless: false,
- executablePath: options.executablePath,
+ executablePath,
args: allArgs,
viewport,
extraHTTPHeaders: options.headers,
userAgent: options.userAgent,
+ env: replayLaunchEnv,
...(options.proxy && { proxy: options.proxy }),
ignoreHTTPSErrors: options.ignoreHTTPSErrors ?? false,
});
@@ -912,11 +990,12 @@ export class BrowserManager {
const profilePath = options.profile.replace(/^~\//, os.homedir() + '/');
context = await launcher.launchPersistentContext(profilePath, {
headless: options.headless ?? true,
- executablePath: options.executablePath,
+ executablePath,
args: options.args,
viewport,
extraHTTPHeaders: options.headers,
userAgent: options.userAgent,
+ env: replayLaunchEnv,
...(options.proxy && { proxy: options.proxy }),
ignoreHTTPSErrors: options.ignoreHTTPSErrors ?? false,
});
@@ -926,8 +1005,9 @@ export class BrowserManager {
// Regular ephemeral browser
this.browser = await launcher.launch({
headless: options.headless ?? true,
- executablePath: options.executablePath,
+ executablePath,
args: options.args,
+ env: replayLaunchEnv,
});
this.cdpEndpoint = null;
context = await this.browser.newContext({
@@ -1532,4 +1612,4 @@ export class BrowserManager {
this.frameCallback = null;
}
}
-//# sourceMappingURL=browser.js.map
\ No newline at end of file
+//# sourceMappingURL=browser.js.map
diff --git a/node_modules/agent-browser/package.json b/node_modules/agent-browser/package.json
index 035d5ba..1b05ac4 100644
--- a/node_modules/agent-browser/package.json
+++ b/node_modules/agent-browser/package.json
@@ -11,7 +11,7 @@
"skills"
],
"bin": {
- "agent-browser": "./bin/agent-browser.js"
+ "replay-browser": "./bin/agent-browser.js"
},
"keywords": [
"browser",
@@ -75,4 +75,4 @@
"ci:version": "changeset version && pnpm run version:sync && pnpm install --no-frozen-lockfile",
"ci:publish": "pnpm run version:sync && pnpm run build && changeset publish"
}
-}
\ No newline at end of file
+}
90 changes: 90 additions & 0 deletions packages/replayio/scripts/apply-agent-browser-patches.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"use strict";

const fs = require("fs");
const path = require("path");
const { spawnSync } = require("child_process");

function findNodeModulesRoot(startDir) {
let current = startDir;
while (true) {
const candidate = path.join(current, "node_modules", "agent-browser", "package.json");
if (fs.existsSync(candidate)) {
return current;
}

const parent = path.dirname(current);
if (parent === current) {
return null;
}
current = parent;
}
}

function main() {
const packageDir = path.resolve(__dirname, "..");
const patchDir = path.join(packageDir, "patches");

if (!fs.existsSync(patchDir)) {
process.exit(0);
}

const nodeModulesRoot = findNodeModulesRoot(packageDir);
if (!nodeModulesRoot) {
// agent-browser may not be installed yet; skip silently.
process.exit(0);
}

const patchPackageEntry = require.resolve("patch-package/dist/index.js");
const patchDirArg = path.relative(nodeModulesRoot, patchDir);
const result = spawnSync(
process.execPath,
[patchPackageEntry, "--patch-dir", patchDirArg, "--error-on-fail", "--silent"],
{
cwd: nodeModulesRoot,
stdio: "inherit",
}
);

if (result.error) {
throw result.error;
}

if ((result.status ?? 0) === 0) {
ensureReplayBrowserShim(nodeModulesRoot);
}

process.exit(result.status ?? 0);
}

function ensureReplayBrowserShim(nodeModulesRoot) {
const binDir = path.join(nodeModulesRoot, "node_modules", ".bin");
const source = path.join(
nodeModulesRoot,
"node_modules",
"agent-browser",
"bin",
"agent-browser.js"
);
if (!fs.existsSync(source) || !fs.existsSync(binDir)) {
return;
}

// Remove the original shim name to avoid ambiguity with globally-installed agent-browser.
for (const stale of ["agent-browser", "agent-browser.cmd", "agent-browser.ps1"]) {
const stalePath = path.join(binDir, stale);
if (fs.existsSync(stalePath)) {
fs.rmSync(stalePath, { force: true });
}
}

const unixShimPath = path.join(binDir, "replay-browser");
const unixShim = "#!/usr/bin/env node\nrequire('../agent-browser/bin/agent-browser.js');\n";
fs.writeFileSync(unixShimPath, unixShim, "utf8");
fs.chmodSync(unixShimPath, 0o755);

const cmdShimPath = path.join(binDir, "replay-browser.cmd");
const cmdShim = '@ECHO off\r\nnode "%~dp0\\..\\agent-browser\\bin\\agent-browser.js" %*\r\n';
fs.writeFileSync(cmdShimPath, cmdShim, "utf8");
}

main();
1 change: 1 addition & 0 deletions packages/replayio/src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import "./commands/info";
import "./commands/list";
import "./commands/login";
import "./commands/logout";
import "./commands/browser";
import "./commands/open";
import "./commands/record";
import "./commands/remove";
Expand Down
Loading
Loading