diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index e60d294..9135252 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -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) | @@ -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)** diff --git a/README.md b/README.md index eff6acc..bac02c8 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 | --- diff --git a/fixtures/dom-mutate.html b/fixtures/dom-mutate.html new file mode 100644 index 0000000..9c4da87 --- /dev/null +++ b/fixtures/dom-mutate.html @@ -0,0 +1,18 @@ + + + + + DOM mutate fixture + + +

Mutate test

+ + + diff --git a/src/browser/domWatcher.ts b/src/browser/domWatcher.ts new file mode 100644 index 0000000..b6fc7be --- /dev/null +++ b/src/browser/domWatcher.ts @@ -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(); + +/** + * 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 | 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 { + 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 { + 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); + } +} diff --git a/src/events/bus.ts b/src/events/bus.ts index fffbdfd..e7b17a4 100644 --- a/src/events/bus.ts +++ b/src/events/bus.ts @@ -2,6 +2,7 @@ export type RuntimeEventType = | "attached" | "detached" | "observe" + | "dom_change" | "run_start" | "run_end" | "step_start" diff --git a/src/runtime.ts b/src/runtime.ts index 0f18daa..09a90f0 100644 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -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"; @@ -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; @@ -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 { + if (!this.session.isAttached()) { + await this.domWatcher.unwatch(); + return; + } + await this.domWatcher.watch(this.session.getPage()); } async attach(options: AttachOptions = {}): Promise { 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, @@ -122,6 +143,7 @@ export class BrowserRuntime { this.ensureAttached(); const tab = await this.session.newTab(url); await this.observe(); + await this.syncDomWatcher(); return tab; } @@ -129,6 +151,7 @@ export class BrowserRuntime { this.ensureAttached(); const tab = await this.session.switchTab(index); await this.observe(); + await this.syncDomWatcher(); return tab; } @@ -136,6 +159,7 @@ export class BrowserRuntime { this.ensureAttached(); const tabs = await this.session.closeTab(index); await this.observe(); + await this.syncDomWatcher(); return tabs; } @@ -296,6 +320,7 @@ export class BrowserRuntime { } async close(): Promise { + await this.domWatcher.unwatch(); this.events.emit("detached", {}); await this.session.close(); this.experiences.close(); diff --git a/tests/browser-smoke.test.ts b/tests/browser-smoke.test.ts index ef714dc..7ade732 100644 --- a/tests/browser-smoke.test.ts +++ b/tests/browser-smoke.test.ts @@ -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, + ); }); diff --git a/tests/dom-watcher.test.ts b/tests/dom-watcher.test.ts new file mode 100644 index 0000000..2fc1e2e --- /dev/null +++ b/tests/dom-watcher.test.ts @@ -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); + }); +});