Skip to content
Draft
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
4 changes: 2 additions & 2 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ Current stack:
| Media actions | Done (`media` play/pause/mute/skip_ad/fullscreen for video+audio) |
| Content/article sites | Done (`content-sites` plugin + `article` page hint) |
| One-command startup | Done (`npm start`) |
| Event bus | Done (`EventBus`, `GET /events`, SSE `/events/stream`) |
| Event bus | Done (`EventBus`, `GET /events`, SSE `/events/stream`, `dom_change` from MutationObserver) |
| Chrome extension bridge | Done (attach-only debug extension) |
| Optional neural embeddings | Done (`NeuralEmbedder`, hash fallback) |
| Rust core | Scaffolded (`crates/ber-core`: fingerprint + hashing embed + CLI; TS still default) |
Expand Down Expand Up @@ -85,7 +85,7 @@ Current stack:
- Targets can scope into iframes via `frame` / `frameUrl` / `frameName` / `frameIndex`.
- Prefer role/name targets: Playwright a11y locators often reach into shadow UI better than CSS.
- Closed shadow: observe merges CDP-pierced interactive nodes (`shadow_pierced` signal). Still imperfect for canvas-only UIs.
- Still no MutationObserver push stream.
- **Live DOM push:** in-page `MutationObserver` emits debounced `dom_change` events on the bus (`GET /events`, SSE `/events/stream`). Disable with `BER_DOM_WATCH=0`. Follow with `browser_diff` / `GET /diff` for semantic deltas.

**Dialogs & modals (DOM + native)**

Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ This project is a **local execution wrapper**:
- **Cross-origin frames** — `frameUrl` / `frameName` / `frameIndex` via Playwright frame tree
- **Closed-shadow pierce** — CDP pierce during observe (`BER_PIERCE_SHADOW=0` to disable)
- **Rust core (experimental)** — `crates/ber-core` fingerprint/embed CLI
- **Event bus** — step/recovery/run events via `GET /events` or SSE stream
- **Event bus** — step/recovery/run events via `GET /events` or SSE stream; live `dom_change` bursts from MutationObserver
- **Iframe targets** — `frame` / `frameUrl` for consent CMPs and nested UI
- **Open tool bridge** — OpenAI-style `browser_*` tools any agent can register
- **Optional LLM planner** — any OpenAI-compatible endpoint; key optional
Expand Down Expand Up @@ -372,6 +372,8 @@ See [`examples/ber.config.example.json`](./examples/ber.config.example.json).
| `BER_EMBEDDINGS_API_BASE` | no | Optional neural embeddings endpoint |
| `BER_EMBEDDINGS_MODEL` | no | Embeddings model id |
| `BER_EMBEDDINGS=hash` | no | Force local hashing embeddings |
| `BER_DOM_WATCH=0` | no | Disable live MutationObserver `dom_change` events |
| `BER_DOM_WATCH_DEBOUNCE_MS` | no | Node-side debounce for `dom_change` (default `400`) |
| `BER_HERMES_*` | no | Legacy aliases |

---
Expand Down
18 changes: 18 additions & 0 deletions fixtures/dom-mutate.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>DOM mutate fixture</title>
</head>
<body>
<h1>Mutate test</h1>
<script>
setTimeout(function () {
var d = document.createElement("div");
d.id = "injected";
d.textContent = "injected";
document.body.appendChild(d);
}, 1200);
</script>
</body>
</html>
157 changes: 157 additions & 0 deletions src/browser/domWatcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import type { BrowserContext, Page } from "playwright";

export interface DomMutationBatch {
mutations: number;
addedNodes: number;
removedNodes: number;
attributeChanges: number;
timestamp: number;
url?: string;
}

const exposedContexts = new WeakSet<BrowserContext>();

/**
* Plain browser script (no TS compile artifacts). Installs MutationObserver + debounced notify.
*/
export const DOM_OBSERVER_BOOTSTRAP = `
(() => {
const w = window;
function install() {
if (w.__berDomObserver) w.__berDomObserver.disconnect();
let scheduled = false;
let pending = { mutations: 0, addedNodes: 0, removedNodes: 0, attributeChanges: 0 };
const flush = () => {
scheduled = false;
const batch = Object.assign({}, pending, { timestamp: Date.now(), url: location.href });
pending = { mutations: 0, addedNodes: 0, removedNodes: 0, attributeChanges: 0 };
const fn = w.__berDomMutation;
if (typeof fn === "function") fn(batch).catch(() => undefined);
};
const schedule = () => {
if (scheduled) return;
scheduled = true;
setTimeout(flush, 250);
};
const observer = new MutationObserver((records) => {
for (let i = 0; i < records.length; i++) {
const r = records[i];
pending.mutations += 1;
pending.addedNodes += r.addedNodes.length;
pending.removedNodes += r.removedNodes.length;
if (r.type === "attributes") pending.attributeChanges += 1;
}
schedule();
});
const target = document.documentElement || document.body;
if (target) {
observer.observe(target, {
subtree: true,
childList: true,
attributes: true,
characterData: true,
});
}
w.__berDomObserver = observer;
}
w.__berInstallDomObserver = install;
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", install, { once: true });
} else {
install();
}
})();
`;

export function domWatchEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
const v = env.BER_DOM_WATCH;
if (v === "0" || v === "false") return false;
return true;
}

export function resolveDomWatchDebounceMs(env: NodeJS.ProcessEnv = process.env): number {
const raw = env.BER_DOM_WATCH_DEBOUNCE_MS;
if (!raw) return 400;
const n = Number.parseInt(raw, 10);
return Number.isFinite(n) && n >= 0 ? n : 400;
}

export function mergeDomBatches(a: DomMutationBatch, b: DomMutationBatch): DomMutationBatch {
return {
mutations: a.mutations + b.mutations,
addedNodes: a.addedNodes + b.addedNodes,
removedNodes: a.removedNodes + b.removedNodes,
attributeChanges: a.attributeChanges + b.attributeChanges,
timestamp: b.timestamp,
url: b.url ?? a.url,
};
}

/**
* In-page MutationObserver → debounced bursts on the Node event bus.
* Disable with BER_DOM_WATCH=0.
*/
export class DomMutationWatcher {
private page: Page | null = null;
private nodeTimer: ReturnType<typeof setTimeout> | null = null;
private pending: DomMutationBatch | null = null;
private readonly debounceMs: number;
private readonly env: NodeJS.ProcessEnv;

constructor(
private readonly onBurst: (batch: DomMutationBatch) => void,
options?: { debounceMs?: number; env?: NodeJS.ProcessEnv },
) {
const env = options?.env ?? process.env;
this.debounceMs = options?.debounceMs ?? resolveDomWatchDebounceMs(env);
this.env = env;
}

async watch(page: Page): Promise<void> {
if (!domWatchEnabled(this.env)) return;
await this.unwatch();
this.page = page;
const context = page.context();
if (!exposedContexts.has(context)) {
await context.exposeFunction("__berDomMutation", (batch: DomMutationBatch) => {
this.ingest(batch);
});
await context.addInitScript({ content: DOM_OBSERVER_BOOTSTRAP });
exposedContexts.add(context);
}
await page.evaluate(DOM_OBSERVER_BOOTSTRAP);
}

async unwatch(): Promise<void> {
if (this.nodeTimer) {
clearTimeout(this.nodeTimer);
this.nodeTimer = null;
}
this.pending = null;
const page = this.page;
this.page = null;
if (page && !page.isClosed()) {
await page
.evaluate(() => {
const w = window as Window & { __berDomObserver?: MutationObserver };
w.__berDomObserver?.disconnect();
})
.catch(() => undefined);
}
}

private ingest(batch: DomMutationBatch): void {
if (!domWatchEnabled(this.env)) return;
this.pending = this.pending ? mergeDomBatches(this.pending, batch) : batch;
if (this.nodeTimer) clearTimeout(this.nodeTimer);
this.nodeTimer = setTimeout(() => this.flush(), this.debounceMs);
}

private flush(): void {
this.nodeTimer = null;
const batch = this.pending;
this.pending = null;
if (!batch || batch.mutations <= 0) return;
this.onBurst(batch);
}
}
1 change: 1 addition & 0 deletions src/events/bus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export type RuntimeEventType =
| "attached"
| "detached"
| "observe"
| "dom_change"
| "run_start"
| "run_end"
| "step_start"
Expand Down
25 changes: 25 additions & 0 deletions src/runtime.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { resolve } from "node:path";
import { DomMutationWatcher } from "./browser/domWatcher.js";
import { BrowserSession, type AttachOptions } from "./browser/session.js";
import { EventBus } from "./events/bus.js";
import { ExperienceStore } from "./experience/store.js";
Expand Down Expand Up @@ -49,6 +50,7 @@ export class BrowserRuntime {
private readonly plugins: PluginRegistry;
private readonly dataDir: string;
readonly events: EventBus;
private readonly domWatcher: DomMutationWatcher;
private lastPlan?: Plan;
private lastResult?: RunResult;

Expand All @@ -65,12 +67,31 @@ export class BrowserRuntime {
options.computerUseFallback ?? new NoopComputerUseFallback();
this.plugins = options.plugins ?? new PluginRegistry();
this.events = options.events ?? new EventBus();
this.domWatcher = new DomMutationWatcher((batch) => {
this.events.emit("dom_change", {
url: batch.url,
mutations: batch.mutations,
addedNodes: batch.addedNodes,
removedNodes: batch.removedNodes,
attributeChanges: batch.attributeChanges,
observedAt: batch.timestamp,
});
});
}

private async syncDomWatcher(): Promise<void> {
if (!this.session.isAttached()) {
await this.domWatcher.unwatch();
return;
}
await this.domWatcher.watch(this.session.getPage());
}

async attach(options: AttachOptions = {}): Promise<SemanticState> {
await this.session.attach(options);
const state = await observePage(this.session.getPage());
this.sessionMemory.setState(state);
await this.syncDomWatcher();
this.events.emit("attached", {
url: state.url,
domain: state.domain,
Expand Down Expand Up @@ -122,20 +143,23 @@ export class BrowserRuntime {
this.ensureAttached();
const tab = await this.session.newTab(url);
await this.observe();
await this.syncDomWatcher();
return tab;
}

async switchTab(index: number) {
this.ensureAttached();
const tab = await this.session.switchTab(index);
await this.observe();
await this.syncDomWatcher();
return tab;
}

async closeTab(index?: number) {
this.ensureAttached();
const tabs = await this.session.closeTab(index);
await this.observe();
await this.syncDomWatcher();
return tabs;
}

Expand Down Expand Up @@ -296,6 +320,7 @@ export class BrowserRuntime {
}

async close(): Promise<void> {
await this.domWatcher.unwatch();
this.events.emit("detached", {});
await this.session.close();
this.experiences.close();
Expand Down
32 changes: 32 additions & 0 deletions tests/browser-smoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,4 +246,36 @@ describe.sequential("browser smoke (Playwright)", () => {
},
60_000,
);

it(
"dom-mutate fixture: emits dom_change on SSE bus after SPA injection",
async () => {
const server = await startFixtureServer({ "/": "dom-mutate.html" });
const runtime = new BrowserRuntime({
dataDir: tempDataDir(),
policy: { headless: smokeHeadless() },
});

try {
await runtime.attach({ startUrl: server.url("/") });
const deadline = Date.now() + 5000;
let domChange: { mutations?: number } | undefined;
while (Date.now() < deadline) {
const hit = runtime
.listEvents({ type: "dom_change" })
.find((e) => (e.data?.mutations as number) > 0);
if (hit) {
domChange = hit.data;
break;
}
await new Promise((r) => setTimeout(r, 100));
}
expect(domChange?.mutations).toBeGreaterThan(0);
} finally {
await runtime.close();
await server.close();
}
},
30_000,
);
});
54 changes: 54 additions & 0 deletions tests/dom-watcher.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import {
domWatchEnabled,
mergeDomBatches,
resolveDomWatchDebounceMs,
} from "../src/browser/domWatcher.js";
import { EventBus } from "../src/events/bus.js";

describe("dom mutation watcher helpers", () => {
it("mergeDomBatches aggregates counts", () => {
const merged = mergeDomBatches(
{
mutations: 2,
addedNodes: 1,
removedNodes: 0,
attributeChanges: 1,
timestamp: 100,
url: "https://a.test",
},
{
mutations: 3,
addedNodes: 2,
removedNodes: 1,
attributeChanges: 0,
timestamp: 200,
url: "https://b.test",
},
);
expect(merged.mutations).toBe(5);
expect(merged.addedNodes).toBe(3);
expect(merged.removedNodes).toBe(1);
expect(merged.attributeChanges).toBe(1);
expect(merged.timestamp).toBe(200);
expect(merged.url).toBe("https://b.test");
});

it("domWatchEnabled respects BER_DOM_WATCH", () => {
expect(domWatchEnabled({ BER_DOM_WATCH: "0" })).toBe(false);
expect(domWatchEnabled({ BER_DOM_WATCH: "false" })).toBe(false);
expect(domWatchEnabled({})).toBe(true);
});

it("resolveDomWatchDebounceMs parses env", () => {
expect(resolveDomWatchDebounceMs({ BER_DOM_WATCH_DEBOUNCE_MS: "100" })).toBe(100);
expect(resolveDomWatchDebounceMs({ BER_DOM_WATCH_DEBOUNCE_MS: "nope" })).toBe(400);
});

it("EventBus accepts dom_change type", () => {
const bus = new EventBus();
const ev = bus.emit("dom_change", { mutations: 4 });
expect(ev.type).toBe("dom_change");
expect(bus.list({ type: "dom_change" })).toHaveLength(1);
});
});
Loading