Skip to content

About

macOS Native WebKit controlled agent browser for Fusion ecosystem - AXTree tokenizer, anti-injection sanitizer, UDS/Protobuf IPC

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

doc_id fusion-browser/readme
product fusion-browser
class app
entry service
doc_type readme
title
zh en
fusion-browser 产品说明
fusion-browser README
audience engineer
status draft
version 0.2.4
updated 2026-11-07
owner @dahai
source_of_truth
README.md

fusion-browser

Doc version: Phase 4 production-hardening landed (2026-08-26) Spec: architecture/fusion-browser-prd-0826.md (v2.0) + audit/fusion-browser-audit-0826.md Plan: ~/fusion/fusion-browser-prd-plan-0826.md Docs: docs/ARCHITECTURE.md · docs/PROTOCOL.md · docs/DEVELOPMENT.md · docs/cowork-managed-backend-contract.md Bilingual: this file is English (default) — see README_CN.md for Chinese.

macOS native controlled browser engine. Provides Web visual + structured interaction for fusion-agent-studio, with CDP-automation reuse for fusion-cowork. Built on macOS native WebKit (WKWebView), dual protocol stack (UDS length-prefixed JSON main path + CDP-over-WS compatibility layer), with six built-in infrastructure modules.

Current State (Phase 4 production-hardening landed)

cowork managed-browser backend landed (issue #25, 2026-10-21) — the engine now backs a managed browser panel in fusion-cowork end to end:

  • Persistent profiles per workflow run — create_session takes a profile_id backed by a persistent WKWebsiteDataStore (macOS 14+), so a run's login survives a session close AND an engine restart. Profiles are owned by the calling AUTH-TOKEN hash (profile_denied for another token); delete_profile drops the registry entry and the on-disk store. New capability persistentProfiles (1<<9), OFF by default.
  • Cookie / login-state import — import_cookies reads the user's real browser profile: Firefox cookies.sqlite (plaintext, full fidelity), Chrome and Edge (AES-128-CBC, key from the macOS Keychain "Safe Storage" item, v10/v11 decrypt, v20 app-bound reported as skipped). Counters are honest — imported counts cookies actually committed to the session store. New capability importCookies (1<<8), OFF by default.
  • Screenshot push stream — stream_screenshots on a dedicated UDS connection pushes screenshot_frame (base64 PNG + url/title/seq) after each action and page load (200 ms throttle, in-flight skip) and ends with one stream_end. Read-only channel: admitted for the session's connection or the same principal (token hash); control stays connection-scoped.
  • Wiring — cookieImport.* config keys, FBSessionManager.cookieImport, FBStreamHub + FBWebView publish hooks, a Python client (client/python/fusion_browser_client/) with import_cookies / delete_profile / FusionBrowserStream, and the live harness scripts/cowork_smoke.py (a hard release-gate harness).
  • Two live-path bugs found and fixed while verifying: every injected cookie became Secure (HTTPCookie treats a present .secure key as true) so an http:// page never received it; and the panel stream was unreachable from a second connection (not_owner) — read access now admits the same principal.
  • Four more defects found by the post-landing review and fixed: Chrome 127+ binds a v10/v11 value with a 32-byte SHA256(host_key) prefix, so every encrypted row on a modern Chrome/Edge profile was skipped (now verify-then-stripped); profiles.json is shared by every engine process on a host, so its read-modify-write now holds an flock; the idle reaper now emits stream_end and purges a pending profile store like an explicit close; and a new FBAtomicFd keeps every read/write syscall inside the lock close() takes, so a reused fd cannot receive another client's frame.
  • Cookbook + cowork deliverables: docs/cowork-managed-backend-contract.md. Build green, 300 tests pass.

Phase 1 engine base + six infra modules + Phase 2 four tasks (AXTree extractor / anti-injection sanitizer / CDP compat layer / credential closure) + Phase 3 three tasks (multi-node dynamic quota / CDP domain extension + events / visual-grounding fallback) + Phase 4 five tasks (non-persistence verification / RSS self-restart / perf benchmark suite / UMA coexistence baseline / 1000-action long-run no-leak) complete. Build green, 189 unit tests pass. CDP :9222 end-to-end smoke pass; T3.4 visual grounding verified via real VLM smoke; Phase 4 all verified via the release binary + Python verify scripts. Post-audit hardening wave (P0→P1): H-1 per-session node-map isolation, R-1 navigate-didFinish, E-7 UDS screenshot, R-7 release gate, R-10 controlled-input setter, R-5 session reaper, E-36 cookie inject off queue, R-15 timeout log scrub, H-2 WebContent resource monitor, H-8 fair main-thread rate limiter, E-21/E-22 session-lifecycle lock + close barrier, H-5 capability-model enforcement (driver takes token caps; CDP verifyBearer surfaces caps + per-method gate), E-15 origin-gate fail-closed (WS upgrade + CDP navigate + PUT /json/new now deny on empty Origin / empty allowlist, consistent with EVALUATE; local schemes still allowed), E-23 rebuildDepth counts only real replays (handleCrash checks isIdempotent first; non-idempotent crashes no longer consume the depth cap, so two slow-page click timeouts no longer brick the session) landed; R-7 gate green end-to-end. Post-audit hardening wave P2 (in progress): E-9 Runtime.evaluate returns the real JS result (not a synthetic "ok") — evaluateJSSync return value is JSON-encoded (.fragmentsAllowed) into BrowserStateResponse.evaluateResult, CDP cdpRemoteObject maps it to {type,value}; the default token lacks the evaluate cap (H-5 scoped-token model), so the new tokenCapabilities config key elevates it (e.g. ["evaluate"] or ["all"]; unknown names dropped fail-closed); E-9 live smoke pins 6 JS types + void round-trip. E-8 CDP DOM domain: the 5 DOM.* methods (getDocument / querySelector / resolveNode / getBoxModel / focus) now deref real live elements via a per-connection identity registry on FBCDPTranslator (intToIdStr / objectIdToIdStr / idStrToSelector) bridging CDP handles to the walker's window.__fbMap — the old stubs (hardcoded 1280×800 getBoxModel, FNV-hash querySelector, never-set [data-fb-id] focus, 1-node getDocument, unregistered fb-node-N resolveNode) are gone; querySelector mints qN ids with a stored-selector re-query fallback (the walker rebuilds __fbMap fresh each extract, dropping qN entries); E-8 live smoke (scripts/cdp_dom_smoke.py) drives both cowork flows over the CDP WS surface — Flow A click (getFullAXTree → resolveNode → focus + getBoxModel → real rect centroid → dispatchMouseEvent → onclick fired) + Flow B fill (getDocument → querySelector('#u') → focus → insertText('hello') → Runtime.evaluate value == 'hello'). R-7 gate green end-to-end (230 unit tests + live harnesses incl. cdp_dom_smoke).

Enterprise-commercial gap wave landed (2026-08-29) — closes the four items the 0828 product audit's enterprise tier flagged beyond the 6 blockers:

  • H-9 multi-node capacity plane — per-node identity (FBNodeCapacity.nodeId, a process-lifetime UUID) + a UDS {type:"capacity"} route (gated behind .metrics cap) reporting maxSessions / liveSessions / freeMemoryMB / ramGB for an external scheduler's placement query. No in-process scheduler (audit R-10 改法: cross-node scheduling/migration lands in fusion-gateway; this side ships the contract + docs/multinode-contract.md + fusion-gateway issue). Pinned by scripts/multinode_smoke.py (3 binaries, distinct nodeIds) + NodeCapacityTests.
  • R-7 10-page AXTree compression SLA — versioned corpus at Tests/fixtures/pages/ (10 real-structure HTML fixtures: login/dashboard/SPA-list/heavy-table/heavy-form/ heavy-nav/deep-nest/shadow-DOM/hidden-injection/long-article). scripts/perf_multipage.py measures the PRD §1.1 SLA with the correct metric: tiktoken tokens (cl100k_base), gates = P50 compression ≥90% (median, not per-page) AND P95 AXTree node-body tokens ≤1500. Header excluded (base64 data-URL fixtures inflate the url line ~1500 tokens; real http URLs add ~10). PASS: P50=0.926, P95=407. Hard gate in release_gate.sh (live-path only). Shadow-DOM fixture honestly excluded only if the walker extracts 0 nodes (it reaches light-tree nodes — scored, not excluded).
  • R-8 sanitizer combination-variant fuzz — InjectionFuzzTests exercises all 2^11 subsets of FBSanitizer.hiddenRules (each subset classifies hidden + matches exactly), render+static combinations, and adversarial-naming near-misses (zero false-positive on exact-string contract). Pure deterministic — fits swift test.
  • Credential P2 — E-14 logout deletes only THIS session's injected cookies (by name|path) not the whole domain (two same-domain sessions no longer clobber); E-27 setCookie uses the completion-handler overload + off-main wait (returns true only after commit, not before); E-39 cookie name masked in os_log (was a %{public} leak of auth-token identity). Build green, 210 tests pass (198 + NodeCapacity + InjectionFuzz + E-14 credential).

R-10 system-caller bypass + blank-page crash fix landed (2026-08-30) — closes the last enterprise-commercial gate. R-10 fusion-browser-side: operator config tokenSystemCaller: true designates the node authToken as a system-caller token so a per-call-dial proxy (fusion-gateway dials a fresh UDS connection per op) passes ownerId: nil on create/execute/close → SessionManager bypasses E-34 ownership (mirrors the CDP nil-owner path; SessionManager unchanged). Fail-closed default false; operator config only; orthogonal to caps; trusted-proxy token only. E-40 blank-page screenshot SIGTRAP: a create with no initial_url left the WKWebView blank → WebContent idled into ProcessThrottler suspension → the first screenshot raced the suspend IPC → SIGTRAP exit 133 (crash report fusion-browser-*-112437.ips). Fix: create now loads a minimal data:text/html,<html></html> on main when no initial_url is given so WebContent renders and never idles into suspend. Verified by scripts/verify_gateway_r10.py → PASS (3 creates across 2 nodes + proxied screenshot PNG). Build green, 213 tests pass (210 + 3 isSystemCaller fail-closed unit tests; the E-40 crash is a live-WKWebView path, proven by the harness not a unit test, per ARCH-3).

Phase 1 landed

  • Swift 6 SPM package, Headless/Headed WKWebView wrapper (nonPersistent dataStore isolation; WebContent process count bounded by the session cap + WebKit per-site isolation, not a shared pool — WKProcessPool deprecated macOS 12+, removed per B-2)
  • UDS server (POSIX socket + DispatchSourceRead, bypassing the unreliable NWListener AF_UNIX accept)
  • Length-prefixed JSON framing (schema-aligned, snake_case; codec swappable to gRPC later)
  • FR-08 resource control: dynamic session count / memory budget by physical RAM, over-quota rejected
  • FR-09 flow backpressure: per-client read loop, one socket's large frame does not block others, over-cap dropped; partial-frame arrival timeout (B-4) drops a slow-drip client whose incomplete frame overstays 30s
  • FR-10 auth capability model: shared-secret token, per-action capability check, EVALUATE needs separate capability + origin whitelist
  • B-5/E-34 session ownership: every UDS connection mints a UUID owner id; a client may only execute/close sessions it created (not_owner on mismatch), system callers bypass. E-35 per-client in-flight batch cap (maxBatch=64) bounds frames-per-read so a flooded socket can't monopolize main
  • FR-11 error model: structured {code,message,retryable}, predefined error codes (node_stale/credential_locked/quota_exceeded/evaluate_denied/timeout/replay_limit, etc.)
  • FR-12 observability: metrics (count + latency quantiles) + trace_id full chain + credential append-only audit log
  • FR-13 scheduling guards: max_actions + task_timeout + consecutive-identical-action break + rebuild-depth cap 1
  • NFR-R tiered watchdog: navigate 30s / click·type 2s / scroll 500ms / screenshot·evaluate 5s; timeout crashed→rebuild, replay idempotent actions only (navigate/scroll/screenshot), non-idempotent (click/type/evaluate) fail directly
  • R-9 soft timeout (known limitation): no public WKWebView API cancels a running evaluateJavaScript/snapshot mid-flight, so the watchdog is cooperative — it sets a cancel flag checked at dispatch entry (before the webview is touched) and JOINs the in-flight block. A timeout thus bounds the caller to ≤2×timeoutMs worst case (the initial wait + a join wait of equal length), not a hard mid-action kill. The join is deliberate: it prevents a leaked block from touching a session the caller already gave up on (mid-close/rebuild). Documented per the 0828 audit R-9 acceptance criterion; not a correctness gap, a budget honesty note.

Phase 2 landed

  • T2.1 AXTree extractor: injected JS walker extracts DOM, structural fingerprint (tag + attribute subset + docPath) + JS-side window.__fbMap WeakRef<Node> stable mapping, eN synthetic locator; Markdown reduction (interactive nodes one line each, drop non-essential fields); stale eN returns node_stale
  • T2.2 anti-injection sanitizer: static hidden-vector rule catalog (display:none/visibility:hidden/opacity:0/font-size:0/aria-hidden/hidden/offscreen/text-indent/scale/filter-opacity/color=bg/covered-overlay) + post-render measurement (getBoundingClientRect size 0/offscreen + elementFromPoint hit); purge strips text only, keeps node structure (zero false-kill); adversarial test set + deterministic unit tests cover 100% interception
  • T2.3 CDP compat layer: :9222 CDP-WS shim (NOT real Chrome, a translation layer), POSIX TCP + HTTP discovery (/json//json/version//json/new//json/close) + RFC 6455 WS frame codec (SHA1 Sec-WebSocket-Accept), FBCDPTranslator translates Page/Runtime/Accessibility/Input/DOM methods into FBActionDriver actions + AXTree extract; aligned to cowork cdp_client.py contract (result.result.value/result.nodes[...].backendNodeId/result.data/result.frameId); non-whitelisted EVALUATE rejected; default off (cdpEnabled)
  • T2.4 credential closure: Keychain stores full cookie attributes (name/value/domain/path/expires/secure/httponly/samesite), account=domain, injected into the session in-memory httpCookieStore; LLM gets only credential_injected:bool (plaintext never leaves Keychain/memory); type=password input values masked to ******** in AXTree; locked screen returns credential_locked; credential audit log records op/result only, never the value; NFR-S2/D11 retain by default, logout deletes

Phase 3 landed

  • T3.2 multi-node adaptation: FBResourcesQuota.forHost(ramGB:) tiers session count / total memory by RAM (<8GB→2, 8-16GB→4, 16-32GB→10, ≥32GB→16), perSession=150MB, total=sessions×150; over-quota create rejected with quota_exceeded; explicit RAM reload makes the tier table unit-testable (no dependence on the test machine)
  • T3.3 CDP domain extension: FBCDPTranslator extended with Network/Console/Emulation/Page.lifecycleEvent (Page.frameNavigated + lifecycleEvent, Network.requestWillBeSent/responseReceived/loadingFinished, Runtime.consoleAPICalled), DOM.focus/setFileInputFiles; events decoupled into a standalone FBCDPEventEmitter (send-closure driven, no live socket/webview dependency → deterministic unit-testable); cowork remaining nodes drop in without downgrade
  • T3.4 visual-grounding fallback: on click node_stale, FBVisualLocator takes a screenshotSync PNG + the stale node's role/name description → calls fusion-mlx OpenAI-compatible /v1/chat/completions (VLM reads image_url base64 data URI) → parses {x,y} → elementFromPoint click; OOB/negative guards reject hallucination; pluggable FBHTTPClient protocol makes prediction logic unit-testable (real VLM load is integration smoke only); default off (visualLocator.enabled, needs a VLM loaded in fusion-mlx first)

Phase 4 landed (production-hardening)

  • P4-1 non-persistence verification (FR-04): nonPersistent dataStore measured live — drives a data-URL page to write document.cookie+localStorage, lsof confirms the process holds no persistent WebKit data files (WebsiteData/cookies/localStorage/IndexedDB), zero residue in the bundle container after close. Verify script scripts/verify_nonpersistent.py. During verification two real crashes were found + fixed: create with initial_url calling WKWebView.load on a background queue (exit 133) → main-thread async; close calling AppKit destroy() on a background queue (exit 133) → main-thread sync + release the queue lock before teardown (avoids main↔sessionmgr lock inversion)
  • P4-2 jetsam/RSS self-restart (new code): FBMemoryWatchdog periodically samples host-process RSS (mach_task_basic_info.resident_size), one-shot breach triggers a recovery closure (drain all sessions or exit for external supervisor restart); one-shot arm/disarm prevents repeated drain, re-arms after recovery; pluggable sampler for unit testing (the RSS syscall runs under swift test); default off (memoryWatchdog.enabled). Scope note: guards host-side growth only (AXTree strings / JS inject buffers / session table); WebContent bloat is indirectly bounded by FR-08 quota. 6 deterministic unit tests
  • P4-3 perf benchmark suite: scripts/perf_bench.py drives the release binary through a fixed load of scroll/screenshot/click (20 each), collects execution_time_ms to compute P50/P95/max, samples host RSS, computes AXTree markdown compression ratio (chars/node). Found + fixed CRITICAL: evaluateJSSyncArgs used replacingOccurrences replacing ALL __ARG__ → in multi-arg scripts the first arg fills every slot, expectFp gets the nodeId, fingerprint never matches → EVERY click/type returns node_stale; switched to range(of:)+replaceSubrange, one arg per slot. Report scripts/perf-report.json
  • P4-4 UMA coexistence baseline measured: scripts/uma_coexist.py 10 concurrent sessions × 100 actions (scroll/screenshot/click rotation), while firing inference requests at fusion-mlx; asserts host RSS delta < 150MB×10 quota, fusion_mlx_model_memory_bytes not monotonically rising, mlx keeps serving. Measured 100/100 actions ok, RSS delta 38MB, mlx memory delta 0, inference service normal. Report scripts/uma-report.json. This is PRD T1.5 measured landing
  • P4-5 1000-action long-run no-leak: scripts/longrun_leak.py single session runs 1000 actions, samples RSS every 50, compares first-quartile vs last-quartile mean (30MB allocator-jitter tolerance). Measured 1000/1000 ok, RSS span 4.1MB, last-quartile mean not significantly higher than first → no monotonic leak. Report scripts/longrun-report.json

Post-Phase-4 fix landed

  • Node-id format (commit 9b3405e, 2026-08-27): wire/structured node ids are BARE eN (interactive_nodes[].node_id, target_node_id); the markdown reduction ax_tree_markdown shows [@eN] for LLM readability only. An LLM forwarding @e1 verbatim hit a __fbMap miss → node_stale. FBActionDriver.execute now strips a leading @ from target_node_id once before admit/resolve/JS, so both e1 and @e1 resolve. Callers SHOULD send bare eN. See docs/PROTOCOL.md §4.

Rust core removed (E-17~20 / #68, 2026-08-27)

  • PRD §2 T1.4 evaluation: pure Swift (FBAXTreeReducer.toMarkdown + JSONDecoder) covers Sanitizer+AXTree — the Rust core was default OFF and never the live path (the pure-Swift path was the fallback the Rust core degraded to). Removed the entire FFI boundary: FBCoreBridge / FBCoreWorkerPool / FBCoreRust SPM target / FBCoreRustBuilder plugin / rust/ crate tree / useRustCore config key / RustCoreParityTests / scripts/parity_smoke.py. Closes audit E-17 (build not portable: hardcoded arm64), E-18 (worker pool not dedicated FIFO), E-19 (no runtime parity check), E-20 (Cargo.lock not in plugin inputs) at once. No Rust toolchain needed; --disable-sandbox no longer required (was mandatory only because the plugin ran cargo). Wire schema + AXTree output (markdown + nodes + audit) unchanged → cowork unaffected.

Not done (per roadmap)

  • T3.1 agent-studio full integration: cross-project, this side ships the contract doc + issue only, code lands in fusion-agent-studio (now landed upstream via PR #235; my tracking issue #237 closed as duplicate; #241 open for test-fidelity)

Build / Test

cd /Users/dahai/fusion/fusion-browser
swift build                # debug (pure Swift, no plugin)
swift build -c release     # release -> .build/release/fusion-browser
swift test --disable-sandbox   # 300 tests (--disable-sandbox no longer required: plugin gone; kept for compatibility)
swift test --disable-sandbox --filter CDPServerTests   # single test class

Requires: macOS 14+, Xcode CLI Tools (verified Swift 6.3.3 / Xcode 26.6 / macOS 26.5 / arm64). Pure Swift build — no Rust toolchain needed (Rust core removed, E-17~20 / #68).

Note: WKWebView completion handlers depend on the main run loop; swift test has no main loop → evaluateJSSync/screenshotSync semaphores deadlock. So live WKWebView behavior (real AX walker, screenshot, real navigation) is NOT verified inside swift test; covered by deterministic unit tests (rule catalog/reducer/translator/codec) + the built binary + Python smoke client. See docs/DEVELOPMENT.md §4.

Run

# Default socket /tmp/fusion-browser.sock, CDP off, no token (same-host UDS only; production MUST set a token)
.build/release/fusion-browser

# Config file (optional, ~/.fusion-browser/config.json, partial fields OK, missing fall back to default)
cat > ~/.fusion-browser/config.json <<'JSON'
{"socketPath":"/tmp/fusion-browser.sock","cdpEnabled":true,"cdpPort":9222,
 "authToken":"your-secret","allowedOrigins":["https://example.com"],"logLevel":"info"}
JSON
.build/release/fusion-browser

logLevel: debug/info/warn/error. Logs go to both os_log (Console.app, search com.fusion.browser) and stderr.

Config keys: socketPath, cdpEnabled, cdpPort, authToken, logLevel, allowedOrigins (origin whitelist — empty is FAIL-CLOSED per E-15: EVALUATE, CDP navigate, and the CDP WS upgrade all deny on an empty list; local schemes data:/about:/blob: still navigate freely), tokenCapabilities (E-9/H-5, default empty → .default, no evaluate — string list elevating the token's action caps, e.g. ["evaluate"]/["all"]; unknown names dropped fail-closed), tokenSystemCaller (R-10, default false — Bool designating the authToken as a system-caller token so a per-call-dial proxy/scheduler like fusion-gateway bypasses E-34 session ownership on UDS create/execute/close; OPERATOR CONFIG only, fail-closed, trusted-proxy token only, orthogonal to caps), visualLocator (T3.4 visual-grounding fallback, default off; enabling needs a VLM loaded in fusion-mlx first; sub-keys endpoint/model/timeoutMs/enabled), memoryWatchdog (P4-2 RSS self-restart, default off; sub-keys enabled/sampleIntervalMs/thresholdMB/action, action=close_sessions|exit), guards (FR-13 scheduling guards, sub-keys maxActions/taskTimeoutMs/repeatActionBreak/rebuildDepthCap). A leftover useRustCore key in an existing ~/.fusion-browser/config.json is silently ignored (Codable drops unknown keys) — the Rust core was removed in E-17~20 / #68.

P4-2 RSS self-restart enable example:

{"memoryWatchdog":{"enabled":true,"sampleIntervalMs":30000,"thresholdMB":200,"action":"close_sessions"}}

R-10 gateway proxy ownership-bypass enable example (~/.fusion-browser/config.json increment — trusted-proxy token only):

{"tokenSystemCaller":true,"tokenCapabilities":["all"]}

Verify Scripts (Phase 4)

Script Purpose Output
scripts/verify_nonpersistent.py P4-1 FR-04 non-persistence (lsof + container residue) terminal PASS/FAIL
scripts/perf_bench.py P4-3 perf benchmark (scroll/screenshot/click latency + AXTree compression ratio) scripts/perf-report.json
scripts/uma_coexist.py P4-4 UMA coexistence (10 sessions×100 actions + mlx inference concurrent) scripts/uma-report.json
scripts/longrun_leak.py P4-5 1000-action long-run no-leak (RSS quartile comparison) scripts/longrun-report.json
scripts/navigate_execute_smoke.py navigate-via-execute SIGTRAP fix (execute navigate off-main → engine stays alive, page loads) terminal PASS/FAIL
scripts/verify_gateway_r10.py R-10 system-caller bypass + E-40 blank-page screenshot (multi-node proxied screenshot PNG) scripts/gateway-r10-report.json
scripts/perf_multipage.py R-7 10-page AXTree compression SLA (tiktoken metric; ≥8 scored pages required) scripts/perf-multipage-report.json
scripts/cowork_smoke.py #25 managed backend E2E: persistent profile + real cookie import + login + screenshot stream + engine-restart persistence + delete_profile scripts/cowork-smoke-report.json

All drive the release binary (run after swift build -c release); live WKWebView is out of swift test scope.

scripts/release_gate.sh wires build + the 300 deterministic tests + 11 live hard harnesses into one PASS/FAIL gate (a missing hard harness fails the gate — not a skip). B-6/R-6 CI: .github/workflows/release-gate.yml runs it on every PR — build-and-test on a GitHub-hosted macos-15 runner, then live-path-gate on a self-hosted [self-hosted, macos, arm64, gui] runner (WKWebView needs a GUI session; uma_coexist needs fusion-mlx on :11434, set SKIP_UMA=1 to skip it — the remaining 10 harnesses still run). Both jobs are required status checks — failure blocks merge.

Visual-grounding enable example (incremental ~/.fusion-browser/config.json):

{"visualLocator":{"endpoint":"http://127.0.0.1:11434","model":"mlx-community--Qwen2.5-VL-7B-Instruct-4bit","timeoutMs":30000,"enabled":true}}

Note: model must use the fusion-mlx registered ID (registry uses -- not path /, e.g. mlx-community--Qwen2.5-VL-7B-Instruct-4bit), and that VLM must be loaded in fusion-mlx (POST /v1/models/<id>/load, admin Bearer).

Client Protocol

Full wire reference: docs/PROTOCOL.md. Summary:

UDS main path

  1. Connect to /tmp/fusion-browser.sock
  2. First frame MUST be auth: {"type":"auth","token":"..."}, success returns {"type":"auth_ack","caps":95}
  3. Then send requests (length-prefixed [u32 BE length][JSON]):
    • create session: {"type":"create_session","payload":{"mode":"headless","initial_url":null,"max_actions":null,"task_timeout_ms":null,"credential_domain":null}}
    • execute action: {"type":"execute","payload":{"session_id":"...","action":"click","target_node_id":"e1","payload_text":null,"trace_id":"..."}}
    • close session: {"type":"close","session_id":"..."}
    • create with a persistent profile: {"type":"create_session","payload":{"mode":"headless","profile_id":"run-abc"}} (needs the persistentProfiles cap)
    • import browser cookies: {"type":"import_cookies","payload":{"session_id":"...","browser":"firefox","profile":null}} (needs importCookies)
    • panel stream (own connection): {"type":"stream_screenshots","payload":{"session_id":"...","enabled":true}} → stream_ack, then pushed screenshot_frame events → stream_end
    • delete a profile: {"type":"delete_profile","payload":{"profile_id":"run-abc"}}
  4. JSON keys are snake_case (aligned to the schema). target_node_id is BARE eN (not @eN).

Smoke client: python3 scripts/smoke_client.py <token> (default socket /tmp/fusion-browser-smoke.sock, needs a matching config).

CDP compat layer (:9222, default off)

NOT real Chrome — a shim translating cowork cdp_client.py's real CDP transport. cowork code is read-only; this layer aligns to its contract:

  • HTTP discovery: GET /json (returns [{id,type,title,url,webSocketDebuggerUrl}] array), GET /json/version, PUT /json/new?<url>, GET /json/close/<id> (checks 200 only, no target split)
  • WS upgrade: ws://127.0.0.1:<port>/devtools/page/<targetId>, no subprotocol, no auth header, frames ≤10MiB
  • WS messages: {id,method,params} → {id,result} (caller reads nested: Runtime.evaluate→result.result.value, Accessibility.getFullAXTree→result.nodes (each with backendNodeId), Page.captureScreenshot→result.data (base64 PNG), Page.navigate→result.frameId, DOM.getDocument→result.root.nodeId, DOM.querySelector→result.nodeId, DOM.resolveNode→result.object.objectId)
  • Supported domains: Page (navigate/captureScreenshot/handleJavaScriptDialog + frameNavigated/lifecycleEvent), Runtime (evaluate, non-whitelisted origin rejected + consoleAPICalled), Accessibility (getFullAXTree), Input (dispatchMouseEvent click elementFromPoint / dispatchKeyEvent Enter submit / insertText), Network (requestWillBeSent/responseReceived/loadingFinished), DOM (getDocument/querySelector/resolveNode/focus/setFileInputFiles), Emulation (no-op placeholder); Performance/HeapProfiler/Tracing are no-op or minimal. Events carry NO id (per spec); cowork _dispatch_event buffers Network.*/Runtime.consoleAPICalled
  • CDP event honesty (E-11): nav events fire in real-Chrome order (Network.requestWillBeSent → responseReceived → loadingFinished then Page.frameNavigated → DOMContentLoaded → load); loaderId/requestId are per-nav (fb-loader-<seq>/fb-req-<seq>), frameId constant per frame; Network.responseReceived reports the REAL main-document HTTP status captured via WKNavigationDelegate.decidePolicyFor (status 0 when none, e.g. local schemes — was hardcoded 200); Runtime.consoleAPICalled is wired — FBCDPConnection.drainConsoleEvents reads window.__fbConsole (the console shim buffer) and emits after navigate + evaluate (was dead code). Events arrive in one synchronous burst after load completion (shim cannot stream during load; cowork buffers raw). Subresource responses stay unknown (WKWebView hides them). Live-pinned by scripts/cdp_event_smoke.py.
  • Auth (H-5/E-15): the CDP layer IS Bearer-gated — GET /json + WS upgrade require Authorization: Bearer <token> (fail-closed). WS upgrade + CDP Page.navigate + PUT /json/new are also origin-gated fail-closed: deny on empty Origin OR empty allowedOrigins (consistent with EVALUATE); local schemes data:/about: still navigate. Default off (cdpEnabled).
  • backendNodeId stability (E-13): it is a document-order position (1-based Nth interactive node), stable only for static pages — SPA reorders shift it. Callers MUST re-fetch getFullAXTree before acting on a reordered page; cross-extract handle reuse is unsupported. resolveNode re-extracts + re-registers before minting an objectId, so a stale backendNodeId derefs the CURRENT Nth node (honest) or fail-closes (node stale) if the tree shrank. Full contract in CLAUDE.md.
  • backendNodeId stability (E-13): it is a document-order position (1-based Nth interactive node), stable only for static pages — SPA reorders shift it. Callers MUST re-fetch getFullAXTree before acting on a reordered page; cross-extract handle reuse is unsupported. resolveNode re-extracts + re-registers before minting an objectId, so a stale backendNodeId derefs the CURRENT Nth node (honest) or fail-closes (node stale) if the tree shrank. Full contract in CLAUDE.md.

Source Structure

File Responsibility
main.swift entry, wires config→infra→server, runs the NSApplication run loop; starts FBCDPServer when cdpEnabled
Logging.swift os_log + stderr sink, leveled logging
ErrorModel.swift FR-11 structured error-code enum + FBResult
Protocol.swift schema Swift Codable mapping + length-prefixed framing (snake_case codec)
Auth.swift FR-10 token auth + capability + EVALUATE origin whitelist
Config.swift FR-08 resource quota (by RAM) + FR-13 scheduling guards + watchdog policy + P4-2 memoryWatchdog config + config loading
MemoryWatchdog.swift P4-2 process-level RSS monitor (mach_task_basic_info sampling) + one-shot breach recovery closure + pluggable sampler
Observability.swift FR-12 metrics + trace_id + credential audit log
Framing.swift FR-09 frame reader (multi-frame split + over-limit backpressure drop + B-4 partial-frame arrival timeout)
Session.swift session state machine + scheduler (admit/canRebuild/idempotent classify)
Credentials.swift FR-05/T2.4 Keychain credential custody (stores full cookie attributes, lock-screen detect)
AXWalker.swift T2.1 injected JS walker script + stable mapping (structural fingerprint/WeakRef) + FBExtractedNode/Result
AXTree.swift T2.1 extractor (extract→parse→install mapping→Markdown reduction) + T2.2 sanitizer rule catalog/purge policy + reducer
WebView.swift FR-04/06 WKWebView wrapper (Headless offscreen / Headed window, non-persistent dataStore) + evaluateJSSync/screenshotSync (off-main semaphore) + full cookie-attribute injection
SessionManager.swift FR-04/08 session lifecycle + quota enforcement (main-thread WKWebView creation) + firstSession (CDP shim target mapping) + #25 profile store resolution/teardown
ActionDriver.swift FR-06 action dispatch + NFR-R tiered watchdog + crash-rebuild replay policy + EVALUATE origin check + node-id normalize (strip leading @) + T3.4 click node_stale visual fallback
UDSServer.swift FR-09/10 POSIX socket UDS server + per-client read loop + auth routing
CDPServer.swift T2.3/T3.3 CDP-WS shim: POSIX TCP + HTTP discovery + WS upgrade + frame codec + FBCDPTranslator (CDP method→ActionDriver, extended Network/Console/Emulation/Page.lifecycleEvent/DOM) + FBCDPEventEmitter (events decoupled, deterministic unit-testable)
VisualLocator.swift T3.4 visual-grounding fallback: screenshot→fusion-mlx VLM /v1/chat/completions predicts {x,y} + OOB guards; pluggable FBHTTPClient
CookieCrypto.swift #25 Chromium cookie decryption (AES-128-CBC, PBKDF2 key from the Keychain Safe Storage password, v10/v11, v20 app-bound detection)
BrowserCookieImport.swift #25 Chrome/Edge/Firefox cookie readers + Keychain Safe Storage lookup + FBCookieImportConfig (temp copy incl. -wal/-shm, counts only in logs)
StreamHub.swift #25 screenshot push hub: per-session subscribers, 200 ms throttle, in-flight skip, one stream_end per subscriber
ProfileRegistry.swift #25 persistent-profile registry (~/.fusion-browser/profiles.json, token-hash ownership, atomic 0600 writes, corrupt→empty)

Removed in E-17~20 / #68: FBCoreBridge.swift, FBCoreWorkerPool.swift, Sources/FBCoreRust/, Plugins/FBCoreRustBuilder/, rust/fb-core/ — the Rust core path. The AXTree compile now runs pure Swift (FBAXTreeReducer.toMarkdown + JSONDecoder) in AXTree.swift's FBAXTreeExtractor.extract, the path the Rust core always degraded to.

Roadmap (see PRD §4)

  • Phase 1 (base): engine base + six infra modules + action passthrough + tiered watchdog ✓
  • Phase 2: AXTree extractor + anti-injection sanitizer + CDP compat layer (4 domains) + credential closure ✓
  • Phase 3: multi-node adaptation (T3.2) + CDP domain extension + events (T3.3) + visual-grounding fallback (T3.4) ✓; agent-studio full integration (T3.1) cross-project, landed upstream
  • Phase 4 (production-hardening): non-persistence verification (P4-1, FR-04) + RSS self-restart (P4-2) + perf benchmark suite (P4-3) + UMA coexistence baseline (P4-4, PRD T1.5) + 1000-action long-run no-leak (P4-5) ✓
  • Rust core engine (PRD §4.3 module 5, T1.4): was flag-gated fb_core staticlib + C-ABI FFI; REMOVED in E-17~20 / #68 — PRD §2 T1.4 evaluation concluded pure Swift covers Sanitizer+AXTree (the Rust path was default OFF, the pure-Swift reducer was the fallback). Audit E-17~20 (build not portable / worker pool not FIFO / no runtime parity check / Cargo.lock not in plugin inputs) all closed by removal. Default-OFF pure-Swift path is now the only path ✓

About

macOS Native WebKit controlled agent browser for Fusion ecosystem - AXTree tokenizer, anti-injection sanitizer, UDS/Protobuf IPC

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages