Compare commits

...
Author SHA1 Message Date
leeguooooo 6f4e63ba91 chore(release): bump to 0.27.0-fork.9 — upstream sync + CDP consent fix
Upstream cherry-picks (onto v0.27.0 base):
- security: same-origin stream command relay (#1355)
- feat: hide scrollbars in headless screenshots (#1396)
- chore: pnpm minimum release age + node pinning (#1377, fork-adapted)

Fork fixes:
- fix(connect): stop remote-debugging consent storm — is_connection_alive no
  longer tears down an externally-attached browser on a transient liveness
  timeout (was an endless prompt loop / browser freeze)
- fix(connect): single consenting WebSocket — drop the throwaway verify probe
  so the user's one "Allow remote debugging?" click sticks to the real
  connection
2026-06-01 12:26:16 +09:00
leeguooooo 98622a7415 fix(connect): single consenting WebSocket — drop throwaway verify probe
auto-connect resolved the DevToolsActivePort URL by first opening a
verification WebSocket (verify_ws_endpoint: connect, Browser.getVersion,
close) and only then opening the real connection. On Chrome 136+ the
"Allow remote debugging?" consent is granted per-connection, so the user's
single Allow click was consumed by the throwaway probe and the real
connection (opened afterwards) asked again — surfacing as repeated prompts
or a hung command after the user had already clicked Allow.

resolve_cdp_from_active_port now gates the direct DevToolsActivePort URL on
a consent-free TCP liveness check (tcp_port_alive) instead of a WebSocket
probe, so the real connection is the single WebSocket the user consents to.
A bare TCP connect does not trigger the consent flow (that fires on the CDP
upgrade), and the real connect_async has no client-side timeout, so it waits
for the user to click Allow at their own pace. verify_ws_endpoint removed;
discovery-order tests updated, plus a guard test that resolution opens no
WebSocket.

Verified live: single prompt on a real Chrome attach, then open + eval +
scroll x2 + eval with zero re-prompts and no freeze.
2026-06-01 12:20:22 +09:00
leeguooooo 3d032f9e88 fix(connect): stop remote-debugging consent storm on transient liveness timeout
The daemon re-validates the CDP connection before every browsing command via
is_connection_alive() (Browser.getVersion, 3s timeout). It treated any
timeout-or-error as "dead" and tore the connection down + reconnected.

For an externally-attached browser (the stealth fork's default — the user's
real Chrome), a timed-out probe is almost always Chrome being briefly busy or
showing the Chrome 136+ "Allow remote debugging?" consent modal, which blocks
CDP responses until the user clicks Allow. Tearing the already-consented
connection down forces a reconnect that re-pops the consent prompt — repeated
on every command this becomes an endless prompt loop, and the close +
multiple new /devtools/browser WS probes storm Chrome into a freeze.

Fix: distinguish the probe outcome.
- Responded      -> alive
- TransportError -> dead (WS closed/reset; user closing Chrome lands here too,
                    so zombie-socket detection is preserved)
- TimedOut       -> alive for an external attach (don't tear down a consented
                    connection on transient slowness); dead for a browser we
                    launched ourselves (a real hang worth reconnecting, and no
                    consent modal in play).

Extracted the verdict into a pure connection_alive_from_probe() with unit
tests covering all outcomes. No behavior change for locally-launched browsers.
2026-06-01 11:36:00 +09:00
leeguooooo d027659571 feat(screenshot): hide scrollbars in headless screenshots (cherry-pick b4f2f37)
Cherry-picks upstream agent-browser #1396. Adds a configurable
--hide-scrollbars flag (AGENT_BROWSER_HIDE_SCROLLBARS env, hideScrollbars
config key, default true) that appends Chrome's --hide-scrollbars launch arg
for headless (non-extension) launches so native scrollbars aren't painted into
screenshots. Plumbed through flags.rs, connection.rs, main.rs, native/actions.rs
and native/cdp/chrome.rs; help text in output.rs + skill-data.

Fork adaptation:
- the arg lands in the headless && !has_extensions block, separate from the
  stealth base args — no interaction with anti-detection.
- dropped upstream docs/, agent-browser.schema.json and README hunks (removed
  or rewritten in this fork).

Verified: cargo check --tests passes.
2026-06-01 10:35:20 +09:00
leeguooooo 44b6218ef9 chore(ci): adopt upstream pnpm release-age + node pinning (cherry-pick 4ad2848)
Cherry-picks upstream agent-browser #1377 (chore: enforce pnpm minimum
release age), adapted for the fork:

- add .node-version (24); workflows read node-version-file instead of inline
- pin packageManager pnpm@11.1.3; drop hard-coded pnpm/action-setup versions
- pnpm-workspace.yaml: add minimumReleaseAge (48h supply-chain cooldown) +
  allowBuilds allowlist, keeping our trimmed packages list (no packages/*, docs)

Deliberately dropped from upstream:
- engines.node >=24 / engines.pnpm >=11 — would impose a Node 24 floor on
  end-users of the published agent-browser-stealth CLI (a compiled binary that
  doesn't need it). packageManager + .node-version cover dev/CI pinning.
- docs/ and README hunks — those paths are removed/rewritten in this fork.
2026-06-01 10:34:27 +09:00
Chris TateandMuhtasham e93acc68f8 Require same-origin stream commands (#1355)
* Require same-origin stream commands

Protect the per-session command relay from browser-originated cross-origin requests while preserving same-origin dashboard access.

Co-authored-by: Muhtasham <20128202+Muhtasham@users.noreply.github.com>

* Harden stream command origin checks

Require command relay requests to come from loopback same-origin metadata and prevent request bodies from spoofing security headers.

Co-authored-by: Muhtasham <20128202+Muhtasham@users.noreply.github.com>

---------

Co-authored-by: Muhtasham <20128202+Muhtasham@users.noreply.github.com>
2026-06-01 10:32:44 +09:00
leeguooooo d2a33cc005 fix(scripts): serialize all-platforms build + per-pid wait checks
Two related bugs that conspired to ship stale linux binaries on
0.27.0-fork.5/.7/.8 (caught only by manually grepping the embedded
version string each release):

1. build:all-platforms used `(... & npm run build:linux & wait)`.
   The bare `wait` waits for ALL children but exits with the LAST
   waited child's status, not each individually. So if linux fell
   over and windows succeeded last, the script reported success.
   Worse, when both processes shared cli/target/ and fought over
   cargo's filesystem locks, one would silently bail out and the
   missing binary just stayed at the previous release's bytes.

   Now serial: `npm run build:linux && npm run build:windows &&
   npm run build:macos`. Costs ~3 extra minutes wall-clock vs.
   parallel; trades latency for "every release ships what it says".

2. build:macos had the same `(... & ... & wait)` parallel pattern
   for arm64 + x64 cross-compiles. Native cargo builds against the
   same target/ dir share even more state than the docker'd Linux
   build did, so the failure mode is the same. Now uses explicit
   `PID1=$!; PID2=$!; wait $PID1 || exit 1; wait $PID2 || exit 1`
   so both must succeed.

Companion to the docker-compose $$ fix in 947d150 (which fixed the
*inside-container* wait+cp eating shell vars). This one fixes the
*outer* npm-script layer.
2026-05-09 12:58:39 +09:00
leeguooooo c26afbaba6 chore(release): bump to 0.27.0-fork.8 — auto-retry transient occlusion 2026-05-09 12:39:14 +09:00
leeguooooo ffb386e3af feat(click): auto-retry on transient occlusion before erroring
fork.7 caught the X mask-overlay race correctly but reported it to
the user verbatim — every transient overlay (modal backdrop, focus
ring, click-outside mask, sticky banner) became an error the user
had to wrap in their own retry loop. Most of these clear within a
frame or two on their own.

Now `verify_click_target` retries the elementFromPoint probe a few
times (default 3 × 200ms = 600ms total grace period) before failing.
Real-world overlays that blink in for a render cycle clear during
the first retry; persistent overlays still surface as errors with
the same actionable message — just qualified with "still occluded
after N retries / Mms" so the user knows we tried.

Tunable:
  AGENT_BROWSER_OCCLUSION_RETRIES         (default 3, 0 disables)
  AGENT_BROWSER_OCCLUSION_RETRY_DELAY_MS  (default 200)

DOM.resolveNode is called once outside the loop — backendNodeId is
stable across renders, only the element under (x, y) changes when
overlays flicker. Each probe is still capped at 500ms so a stuck
Runtime.callFunctionOn can't stall a click for longer than the user
expects.
2026-05-09 12:39:03 +09:00
leeguooooo 947d150561 fix(docker): escape \$ as \$\$ so docker compose doesn't eat shell vars
Real bug behind 0.27.0-fork.5 and fork.7 shipping stale linux binaries.
Docker compose interpolates \${VAR} (and \$VAR) at YAML parse time
against the host shell — including inside `command:` blocks. So:

  PID1=\$!                ← compose sees \$! → host has no `!` var → ""
  wait \$PID1 ...         ← compose sees \$PID1 → "" → becomes `wait `
  SRC="...\$TARGET..."    ← \$TARGET still works (set in `environment:`)
  cp "\$SRC" "..."        ← \$SRC eaten → empty → cp errors silently

Result: the per-PID error check I added in dbf272c never fired
because both lines were `wait` (no args) — which waits for ALL
children and exits with the LAST one's status, not each individually.
A failing arm64 build couldn't fail the script.

Fix: escape every script-local \$ as \$\$. Docker compose translates
\$\$ → literal \$ when materializing the command for the container,
and the in-container shell then expands \$VAR correctly.

Verified by `docker compose config` showing the resolved command
contains \$\$PID1 / \$\$SRC etc (which becomes \$PID1 / \$SRC in the
container's bash).
2026-05-09 11:07:01 +09:00
leeguooooo 06a29251a2 chore(release): bump to 0.27.0-fork.7 — click occlusion guard 2026-05-09 10:49:39 +09:00
leeguooooo 0eacec9b9f fix(click): occlusion check via document.elementFromPoint before dispatch
Closes the "modal silently closes when clicking 'Add post' on a thread"
bug. Verified root cause via instrumented page-side click logger:

  click @e31 (aria-label="Add post" at button (1034, 285))
  → mouse event dispatched to (1045, 296)
  → document.elementFromPoint(1045, 296) returned:
       DIV[testid="mask"], bounds (0,0,1746x934)
  → X interpreted as "click outside modal" → close + nav to /home

The cached coordinates were correct. Between snapshot and click, X
laid a transient full-viewport mask over the modal (their own
"click-outside-to-close" overlay). stealth dispatched the click
without checking what was actually at that pixel — the overlay
intercepted it.

Fix: just before returning (x, y) from resolve_element_center for
ref-based interactions, run a Runtime.callFunctionOn against the
ref's resolved element with `function(x, y) { return this.contains(
document.elementFromPoint(x, y)) || that.contains(this) ? null :
{...occluder details...}; }`. If the element at the point isn't us
(or our descendant — clicking the SVG icon inside a button is fine
— or our ancestor), we fail with a specific message:

  Ref @e31 is occluded by DIV[testid=mask] at the click point.
  A transient overlay (modal backdrop, mask, sticky banner, etc.)
  appeared between snapshot and click. Wait for it to clear or
  re-snapshot, then retry.

So instead of silently submitting an entire thread or nuking the
user's modal, agent gets a parseable error and can wait + retry.

Tight 500ms timeout per CDP call (matching the verify_ref_identity
defensive guard from fork.6) so a stuck DOM.resolveNode can't
re-introduce the multi-minute hang we just fixed. On any timeout
or error in the guard itself, fall through and let the click
proceed — strictly no worse than the unguarded code path.

Disable with AGENT_BROWSER_VERIFY_CLICK_TARGET=0.
2026-05-09 10:49:27 +09:00
leeguooooo 7159012173 chore(release): bump to 0.27.0-fork.6 — defensive-guard timeouts + accurate CDP tip 2026-05-09 10:04:25 +09:00
leeguooooo 1b3d41e579 fix(timeout): cap defensive CDP guards so click can't hang multi-minute
Reported: a single `click @ref` could hang 5+ minutes, with multiple
queued click invocations adding up to 7+ minutes — worst case 30s
timeout × 3 CDP calls × N parallel processes:

  - verify_ref_identity (Accessibility.getPartialAXTree)  →  default 30s
  - resolveNode / getBoxModel                              →  default 30s
  - wait_for_paint_settled (Runtime.evaluate awaitPromise) →  default 30s

The latter two are best-effort defenses added in fork.3-5 to fix SPA
race / DOM-reuse bugs. They should never block a real click for
30s — the unguarded code path was always faster than the guarded
path-that-hangs.

  - verify_ref_identity   capped at 1s   (skips check on timeout)
  - wait_for_paint_settled capped at 500ms (skips wait on timeout)

Both skip-on-timeout intentionally: the worst case is the click
behaves like fork.2 (race-prone but fast), which is strictly better
than the user pkilling stuck processes.

Also rewrites the misleading "Chrome 144+ chrome://inspect tip" in
the auto-connect failure message — the toggle exposes target
discovery only, not the /json/version HTTP API the auto-connect
flow expects (verified by user: lsof shows :9222 listening but
curl /json/version returns 404).
2026-05-09 10:04:14 +09:00
leeguooooo dbf272ced7 fix(docker): catch parallel-build failures + stop using glob in cp
Two latent bugs in the release pipeline that conspired to ship a stale
linux-x64 binary in 0.27.0-fork.5 (only caught by manually grepping
the embedded version string):

1. build-linux ran x64 and arm64 in parallel and used a single
   `wait $PID1 $PID2` to join them. That command waits for both, but
   its exit code is the LAST waited pid only — so if x64 silently
   broke and arm64 succeeded, the outer script exited 0 and shipped
   whatever was already in /output from the previous release. Now we
   wait on each pid individually and exit 1 on either failure.

2. build-single's cp used `agent-browser*` which globs to BOTH the
   binary and its `.d` dependency file. When two sources are passed,
   cp requires the destination to be a directory. We weren't, so cp
   exited non-zero with "Not a directory" and the build script
   shrugged it off because the next line was `chmod ... || true`.
   Now we resolve a single explicit source path.
2026-05-09 04:30:20 +09:00
leeguooooo 64140879d5 chore(release): bump to 0.27.0-fork.5 — attach-mode UX + zombie-CDP probe + wait @ref 2026-05-09 04:11:09 +09:00
leeguooooo d3bfd76c96 fix(connect): liveness probe + wait @ref support
Two changes that pair with each other:

1. connect_auto_with_fresh_tab now does a Runtime.evaluate "1"
   round-trip after creating the fresh tab. This catches the zombie
   CDP socket case (process alive, websocket dead) where every step
   up to that point reports success but the next user command would
   silently no-op against a dead session. Failing here lets the
   caller surface a proper "CDP session unresponsive" error instead
   of returning Ok and letting `agent-browser open URL` exit 0 with
   a still-blank tab.

2. handle_wait now recognizes @ref selectors (e.g. `wait @e8 --gone`).
   It polls resolve_element_object_id, which already runs the
   verify_ref_identity check from 007fd1b — so:
     - `wait @e8`             succeeds while the original element is
                              still mounted with its snapshot role+name
     - `wait @e8 --gone`      succeeds when the ref's identity changes
                              (modal closed, button re-textified, etc.)
   This gives users the "assert modal still open" primitive that
   prior versions could only approximate with screenshots.
2026-05-09 04:10:48 +09:00
leeguooooo 47dfe760be fix(cli): better message when only --headed is ignored in attach mode
In CDP-attach mode (the default since 0.24.0-fork.1), --headed has no
effect — the user's existing Chrome is already visible, and the
generic "use 'agent-browser close' first to restart" advice doesn't
help (the new daemon attaches right back). Explicitly say --headed is
moot and point to --launch as the actual escape hatch.

Other ignored flags (--profile, --proxy, etc.) keep the existing
"close + reopen" message because for those it IS the right advice.
2026-05-09 04:10:46 +09:00
leeguooooo 0db6604105 chore(release): bump to 0.27.0-fork.4 — ref identity guard 2026-05-09 03:26:48 +09:00
leeguooooo 007fd1b27f fix(refs): verify identity before using cached backendNodeId
Closes the "click @e20 hits the sibling element" bug. Real-world
example: snapshot shows @e20=[button "Add post"] next to
@e17=[button "Post all"]. By the time you click @e20, React has
re-rendered — and React often re-uses the same <button> DOM node
across renders, just updating its accessible name. The cached
backendNodeId still resolves to a real, well-positioned node, so
the click lands cleanly. It just lands on what is now the "Post all"
button, silently submitting the entire thread instead of adding a
draft row.

Before every ref-based interaction (click / fill / type / hover /
select / drag — anything routing through resolve_element_center or
resolve_element_object_id), call Accessibility.getPartialAXTree for
the cached backendNodeId and check role + name still match the
snapshot entry. On mismatch, abort with an error that names both
labels:

  Ref @e20 no longer matches its snapshot. Was [button "Add post"],
  now [button "Post all"].
  ...Take a fresh snapshot, then re-target.

If the node is gone (CDP fails / no AX node), we silently fall
through to the existing "find by role+name" recovery path, so this
guard never makes a working flow worse.

Adds one CDP roundtrip per ref interaction (~5–20ms). Disable with
AGENT_BROWSER_VERIFY_REF=0 if you control the page lifecycle and
need the latency back.
2026-05-09 03:26:20 +09:00
leeguooooo 3d1132af90 chore(release): bump to 0.27.0-fork.3 — click paint-settle + wait --gone 2026-05-09 02:45:45 +09:00
leeguooooo 90ba44cd38 feat(wait): add --gone / --hidden flags so users can fail fast on closed UIs
Pairs with the click paint-settle fix: even with that, a thread builder
that clicks "Add post" can race a misbehaving handler that closes the
parent modal instead of mounting the next textbox. To make that case
observable instead of silently corrupting the next inserttext, you can
now write:

  click @add-post
  wait .modal --gone --timeout 2000   # asserts modal stays mounted
  inserttext "tweet 3"

If the modal vanished, `wait --gone` succeeds — flip the assertion to
`wait .modal` (default visible) to fail-fast on disappearance.

Implementation just sets `state: "detached"` (or "hidden") on the wait
command — daemon-side `wait_for_selector` already supported these
states; only the CLI parser was missing the user-facing flag.

Also accepts `--detached` as alias for `--gone` to match the daemon's
internal vocabulary.
2026-05-09 02:45:34 +09:00
leeguooooo 52f8ead0f2 fix(click): wait for paint to settle so SPA renders complete before next command
Closes a real-world race that broke X multi-tweet thread composition
(and similar SPA flows): clicking "Add post" returned immediately,
inserttext fired before React had committed the new textarea, the
keystroke landed on the dialog wrapper, and X interpreted the stray
input as a request to dismiss the modal.

After mouseReleased we now wait for two requestAnimationFrame ticks
plus a microtask boundary (~33ms at 60fps, bounded). That's enough
for React/Vue/Svelte to commit any state update scheduled by the
click handler. Errors during the wait are swallowed — a click never
fails because of post-processing.

Opt out for perf-sensitive scripts that don't drive SPA UIs:
  AGENT_BROWSER_CLICK_WAIT_STABLE=0
2026-05-09 02:45:21 +09:00
leeguooooo ffa5bd63f6 chore(release): bump to 0.27.0-fork.2 — find error UX + URL preservation 2026-05-09 01:41:25 +09:00
leeguooooo 926f08203c chore: regenerate pnpm-lock.yaml after dashboard removal
The previous lockfile had ~11k lines of transitive deps for
packages/dashboard which we deleted in 86c4cff. Re-running pnpm install
shrinks it to ~24 lines (just husky for git hooks).
2026-05-09 01:41:12 +09:00
leeguooooo 2b1a3c308a feat(daemon): preserve URL across version-mismatch restart
Before: after `npm i -g` upgrade, the next agent-browser command would
detect daemon version mismatch, kill the old daemon, spawn a fresh one,
and connect to a brand-new about:blank tab. The user's previous
navigation state was silently lost — `get url` returned about:blank
even though the user's Chrome was still on the same page.

Now: before killing the old daemon, the CLI synchronously asks it for
its current URL via the existing socket. If non-empty and not
about:blank, it's persisted to a `.restore-url` sidecar in the socket
dir. After the new daemon spawns and auto-connects, it reads the
sidecar (read-and-delete), navigates the fresh tab to the saved URL,
and prints `⚠ Restored previous URL: <url>`.

Manual `agent-browser close` does NOT write the sidecar, so a clean
shutdown won't trigger surprise navigation. The sidecar is consumed on
read regardless of whether navigation succeeded, so a stale entry
can't haunt later auto-launches.
2026-05-09 01:41:07 +09:00
leeguooooo 6c556e519d feat(parse): friendly error when find has --flag where action verb expected
Before, `agent-browser find role button --name Submit` errored at the
daemon side with the cryptic `Unknown subaction: --name`. Now it errors
at parse time with the offending flag echoed back, the list of valid
actions (click, fill, check, hover, text), and a "Did you mean" hint
showing where to put the action verb.

Backwards compat: `find role button` (no flags, no action) still
defaults to click — only `--xxx` in action position errors.
2026-05-09 01:40:56 +09:00
leeguooooo 9e48b0757c fix(package): drop ./ prefix from bin entries
npm 10+ strips bin paths starting with ./ as invalid, leaving the
package with no executable entries (so `npm i -g` doesn't put any
binary on PATH). Match the upstream form `bin/agent-browser.js`.
2026-05-09 00:52:36 +09:00
leeguooooo e46232c496 chore(release): bump to 0.27.0-fork.1 on upstream v0.27.0 base 2026-05-09 00:28:02 +09:00
leeguooooo a3d4711c61 feat(skills): support npx skills add via skills.sh
- Add fork binary names (agent-browser-stealth, abs) to allowed-tools
  in all 6 SKILL.md files so installs into Claude Code / Cursor don't
  prompt for permission on every command
- Document `npx skills add leeguooooo/agent-browser-stealth` in README
- Bump README upstream-base mention from v0.24.0 to v0.27.0
2026-05-09 00:26:33 +09:00
leeguooooo 86c4cff26e chore(fork): drop upstream-only docs/, evals/, packages/dashboard, schema
These directories are TypeScript-side tooling that the fork dropped at
v0.24.0 to keep the repo focused on the stealth CLI binary. Upstream
either kept evolving them (docs, packages/dashboard) or added new ones
(evals/) — they came back during the v0.27.0 rebase, so prune again.

Also include skill-data/ in package.json `files` so the specialized
skills (electron, slack, dogfood, etc.) that upstream relocated from
skills/ to skill-data/ still ship in the npm tarball.
2026-05-09 00:24:27 +09:00
leeguoooooandClaude Opus 4.6 9202c1c919 fix(ci): add missing force_launch field in test Flags constructors
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-08 23:54:41 +09:00
leeguoooooandClaude Opus 4.6 9b56c07e33 docs: rewrite README to focus on fork differences
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-08 23:48:56 +09:00
leeguoooooandClaude Opus 4.6 6488aae458 chore(release): bump to 0.24.0-fork.2, publish as latest tag
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-08 23:48:50 +09:00
leeguoooooandClaude Opus 4.6 016d60f293 fix(docker): update Rust to 1.94 for cross-compilation builds
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-08 23:48:50 +09:00
leeguoooooandClaude Opus 4.6 76cfe75636 fix(stealth): achieve 0% headless via CDP-native automation override
Key insight: ANY JS-level modification to navigator.webdriver is detectable
by creepjs's lieProps system. The only undetectable approach is
Emulation.setAutomationOverride at the CDP protocol level, which tells
Chrome to natively return false for navigator.webdriver.

In CdpAttach mode, we now inject ZERO JavaScript patches — the browser's
real fingerprint is already perfect. Only the CDP protocol command is needed.

CreepJS results now match manual Chrome exactly:
- 0% headless (was 33%)
- 0% stealth (unchanged)
- 25% like headless (Chrome baseline, same as manual)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-08 23:48:50 +09:00
leeguoooooandClaude Opus 4.6 320bb61de3 fix(stealth): use getter-based webdriver override to match native Chrome shape
CreepJS detects three things for webDriverIsOn:
1. Property deletion (navigator.webdriver === undefined)
2. Value check (!!navigator.webdriver)
3. Lie detection (descriptor tampering via lieProps)

Changed from delete/defineProperty-value approach to replacing the CDP
getter with a getter returning false, matching the native descriptor shape.

Note: 33% headless in CreepJS is a CDP-inherent signal (lieProps detects
the getter replacement). This cannot be eliminated at the JS layer since
CDP sets the webdriver getter before init scripts run. Real-world impact
is minimal — Cloudflare Turnstile passes successfully.

Also confirmed: Chrome's remote_debugging preference in Local State
persists across restarts, so users only need to enable CDP once via
chrome://inspect/#remote-debugging.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-08 23:48:50 +09:00
leeguoooooandClaude Opus 4.6 81cdd3b216 fix(stealth): split minimal/full mode to eliminate detection lies on real Chrome
- CdpAttach mode: only removes navigator.webdriver (user's real Chrome
  already has genuine fingerprint, heavy patches create detectable lies)
- FullLaunch mode: applies all 32 patches (new Chrome needs full coverage)
- Improved webdriver removal: uses Object.defineProperty to override CDP
  getter on Navigator.prototype, not just delete
- CreepJS results: 0% stealth (was 20%), hasIframeProxy: gone

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-08 23:48:50 +09:00
leeguoooooandClaude Opus 4.6 7ee3d5fb94 feat(connect): make auto-connect to user's Chrome the default behavior
- Auto-connect is now ON by default (was opt-in via --auto-connect)
- Added --launch/--new flags to explicitly start a fresh browser
- CI environments (CI env var) automatically use --launch mode
- Friendly error message with platform-specific Chrome relaunch guide
- Mentions Chrome 144+ runtime CDP toggle (chrome://inspect)
- --cdp and --provider flags implicitly disable auto-connect
- AGENT_BROWSER_NO_AUTO_CONNECT=1 to disable, AGENT_BROWSER_FORCE_LAUNCH=1 to force

Track 3 of native-stealth migration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-08 23:48:50 +09:00
leeguoooooandClaude Opus 4.6 77616a209c feat(stealth): inject anti-detection patches in native Rust architecture
- Created cli/src/native/stealth.rs with stealth JS injection via CDP
- Extracted 32 patch IIFEs from TS stealth.ts into stealth_scripts.js
- Injected via Page.addScriptToEvaluateOnNewDocument on every launch/connect
- Added stealth Chrome args (disable AutomationControlled, use ANGLE GL)
- Auto-detects and cleans HeadlessChrome from User-Agent string
- Overrides navigator.userAgentData high-entropy hints
- Stealth enabled by default, disable with AGENT_BROWSER_STEALTH=0

Track 2 of native-stealth migration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-08 23:47:50 +09:00
leeguoooooandClaude Opus 4.6 6addc80aa1 feat(rebase): fork base on upstream v0.24.0 native architecture
- Rebased onto upstream/main (v0.24.0, full Rust native)
- Renamed package to agent-browser-stealth, version 0.24.0-fork.1
- Preserved fork-specific: abs alias, extensions/tab-group-cdp, .husky hooks
- Removed upstream-only: docs/, packages/dashboard, examples/, benchmarks/
- Simplified pnpm workspace to root-only
- Added [[bin]] section to keep binary name as "agent-browser"

Track 1 of native-stealth migration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-08 23:46:53 +09:00
Chris Tate 82eadcee41 Fix trusted publishing: add Release environment and per-job permissions (#1333) 2026-05-07 10:45:00 -05:00
Chris Tate c830d1b67d Prepare v0.27.0 release (#1332) 2026-05-07 10:15:30 -05:00
Thomas Kosiewski d33bdb36f3 Make dashboard work from proxied origins via same-origin proxy (#1111)
* Restore dashboard session proxy routes

Change-Id: I36ffc3727ce44100121bc94a81510a5f009ee0bc
Signed-off-by: Thomas Kosiewski <tk@coder.com>

* Port dashboard frontend and docs

Change-Id: I80356f64d618dab9d07b610ba67def14539f98ac
Signed-off-by: Thomas Kosiewski <tk@coder.com>

* docs: restore dashboard note in skill

Change-Id: Id0913c64e7a6f2cbbfc429ef03b34dae185d8487
Signed-off-by: Thomas Kosiewski <tk@coder.com>

* fix: tighten dashboard proxy same-origin checks

Change-Id: I792bc859a24cd47314bd46c94344ef3dfb7d6db5
Signed-off-by: Thomas Kosiewski <tk@coder.com>

---------

Signed-off-by: Thomas Kosiewski <tk@coder.com>
2026-05-07 09:08:12 -05:00
Chris Tate 3bb1d43f8b fix(doctor): make generated ids unique per call (#1330) 2026-05-06 10:48:19 -05:00
Andrew Qu 918d407411 Update README.md (#1328) 2026-05-05 16:55:19 -05:00
Walter KormanandClaude Opus 4.6 7ada3384e2 feat(docs): add AI Gateway app attribution headers (#1305)
Pass http-referer and x-title headers to streamText so Vercel can
identify agent-browser on AI Gateway pages.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-29 08:39:12 -07:00
Chris Tate 57405f9361 feat(react): React introspection, Web Vitals, and SPA primitives (#1257)
* feat(react): first-class React introspection, Web Vitals, and nextjs skill

Add React-general and web-universal features as first-class agent-browser verbs
(react tree/inspect/renders/suspense, vitals, pushstate). Genuinely Next.js-specific
workflows (PPR cookie protocol, /_next/mcp bridge, dev-server endpoints) ship as
a new `nextjs` skill that composes the primitives. No new runtime dependencies -
the React DevTools installHook.js is vendored (MIT) and include_str!'d into the
binary.

New commands:
  react tree                  Full React component tree (depth id parent name)
  react inspect <fiberId>     Props, hooks, state, source for one fiber
  react renders start|stop    Fiber profiler with Insts/Mounts/Re-renders/Self/DOM
                              + prev->next change details
  react suspense              Suspense boundaries + classifier (client-hook,
                              request-api, server-fetch, cache, stream, framework)
                              + root-cause grouping + recommendations
  vitals [url]                LCP/CLS/TTFB/FCP/INP + React hydration phases
  pushstate <url>             Generic SPA client-side navigation
  removeinitscript <id>       Remove a script registered via addinitscript

New launch flags:
  --init-script <path>        Register init scripts before first navigation
                              (repeatable; env AGENT_BROWSER_INIT_SCRIPTS)
  --enable <feature>          Built-in init scripts; currently react-devtools
                              (repeatable; env AGENT_BROWSER_ENABLE)

Other primitives:
  network route ... --resource-type <csv>  Filter by CDP resource type
  cookies set --curl <file>                Auto-detects JSON/cURL/Cookie-header

* fixes

* fixes

* fixes
2026-04-20 16:12:47 -05:00
Chris Tate cff12598bf adds trusted publishing (#1273)
* adds trusted publishing

* rename
2026-04-20 00:24:06 -05:00
Chris Tate 717d1b09e1 v0.26.0 (#1255) 2026-04-16 18:33:23 -05:00
Chris Tate 14ece9b3ad feat: add doctor command for diagnosing installs and cleaning stale daemon state (#1254)
* feat: add `doctor` command for install diagnostics and cleanup

Adds `agent-browser doctor`, a one-shot diagnostic that checks
environment, Chrome install, daemon state, config, encryption key,
providers, network reachability, and a live headless launch test.
Auto-cleans stale `.sock` / `.pid` / `.version` / `.stream` sidecar
files on every run. Destructive repairs (reinstall Chrome, purge old
state, close version-mismatched daemons, generate missing encryption
key) are gated behind `--fix`. Supports `--offline`, `--quick`, and
`--json`.

* fixes
2026-04-16 18:20:41 -05:00
Chris Tate 4cc6ca40b7 feat(skills): rename "agent-browser" skill to "core"; make CLI-served main skill actually useful (#1253)
Before this change, the main skill served by the CLI (`agent-browser
skills get agent-browser`) was a ~40-line discovery stub whose content
was essentially "run `agent-browser skills get <name>` before doing
anything." Agents already inside the CLI got no signal from it — the
content they needed to actually use the tool lived only in the `--full`
references.

Split the two jobs apart:

- **`skill-data/core/`** (new) — the runtime usage guide. 420-line
  `SKILL.md` covering the snapshot-and-ref loop, common workflows
  (login, extract, screenshot, multi-tab, sessions, iframes, dialogs),
  waiting strategies, element selection strategies, troubleshooting,
  and when to load a specialized skill. Supplementary `references/` and
  `templates/` (moved from `skills/agent-browser/`) provide the full
  command reference under `--full`.
- **`skills/agent-browser/SKILL.md`** — still the discovery stub that
  `npx skills add` installs, now marked `hidden: true` so it stays out
  of `skills list` inside the CLI. Body is a clean pointer to
  `agent-browser skills get core` and the specialized skills.

The `hidden: true` frontmatter flag is a new, general mechanism: skills
marked hidden are omitted from `skills list` and `skills get --all` but
can still be fetched by explicit name. This keeps the stub reachable
for anyone who installed via `npx skills add` without polluting the
CLI-side skill listing.

## Behavior

```
$ agent-browser skills list
  agentcore       Run agent-browser on AWS Bedrock AgentCore cloud browsers...
  core            Core agent-browser usage guide. Read this before running...
  dogfood         Systematically explore and test a web application...
  electron        Automate Electron desktop apps (VS Code, Slack, Discord...)
  slack           Interact with Slack workspaces using browser automation...
  vercel-sandbox  Run agent-browser + Chrome inside Vercel Sandbox microVMs...

$ agent-browser skills get core          # the actual usage guide
# ~420 lines of workflows, patterns, troubleshooting

$ agent-browser skills get agent-browser # still works if called explicitly
# the thin stub, now pointing at `core`
```

External `npx skills add vercel-labs/agent-browser` behavior is
unchanged: it finds and installs the thin `agent-browser` stub, which
tells the agent to run `agent-browser skills get core` for real
content. Version drift protection is preserved — the stub is the only
thing that gets copied; the real content is always runtime-fetched.

## Updated

- `cli/src/skills.rs` — `SkillInfo.hidden: bool`, parsed from
  frontmatter; `run_list` and `run_get --all` filter it. 3 new unit
  tests for the frontmatter parser.
- `cli/src/output.rs` — top-level `--help` and `skills` subcommand help
  reference `skills get core` / `skills get core --full`.
- `AGENTS.md` — "update these files for user-facing features" now
  points at `skill-data/core/` instead of the stub, with a note that
  the stub is not the right place for feature content.
- `README.md`, `docs/src/app/skills/page.mdx` — describe the new
  split and `skills get core --full` as the recommended entry point.
- `evals/cases/{command-usage,skill-selection}.ts` — expect
  `skills get core` in agent output instead of `skills get
  agent-browser`. Eval lib still reads `skills/agent-browser/SKILL.md`
  (simulating what an agent sees after `npx skills add`).

All 11 skills unit tests pass. `cargo clippy -- -D warnings` and
`cargo fmt --check` clean. Verified end-to-end: `skills list` shows
`core` + specialized (no stub), `skills get core` returns the new
content, `skills get agent-browser` still returns the stub on explicit
request.
2026-04-16 14:36:59 -05:00
Chris Tate 1afcaa0e84 docs(help): promote skills to the top of --help so agents discover them first (#1251)
The `Skills:` section was buried between `Setup:` and `Snapshot Options:` in
the top-level `--help`, where an agent skimming the output would pass over it
on the way to flag docs. Move it to a prominent "Start here (for AI agents)"
block directly below `Usage:` so it's the first thing an agent sees, and
reframe the copy so it conveys what skills *are* (workflow patterns, ref
usage, copy-paste examples) rather than just listing subcommand flags.

Skills are the intended entry point for agents. They ship with the CLI,
always version-match the installed binary, and cover both `agent-browser`
core usage and specialized workflows (Electron, Slack, exploratory testing,
cloud browser providers). Surfacing them up front prevents agents from
guessing commands out of flag docs when a hand-written workflow guide is
one command away.

No functional change. Only the ordering and wording of `--help` output.
2026-04-16 14:33:55 -05:00
Chris Tate 585d93a02b feat(tabs): t<N> prefix for tab ids; --label for named tabs; drop --tab peek flag (#1250)
* fix(tabs): preserve refs across --tab peek and cover outer-tab-closed path

Follow-up to #1249 so `--tab <id>` is actually useful for agents:

- Save and restore the outer tab's `ref_map`, `iframe_sessions`, and
  `active_frame_id` across a scoped command instead of clearing them.
  `snapshot` → `--tab N <cmd>` → `click @e1` now keeps the outer tab's
  refs intact. Scoped commands still see a clean slate so outer refs
  can't resolve against the scoped tab's DOM.
- Close the coverage gap the Vercel review bot flagged on #1249: the
  previous `e2e_tab_scoped_command_handles_outer_tab_closed` test used
  `tab_close`, which is in the scoped-dispatch exclusion list, so it
  never exercised the restore-skip branch it claimed to test. Renamed
  to `e2e_tab_close_with_tab_id_closes_active_tab` with an honest
  docstring, and added `e2e_tab_scoped_command_outer_tab_closed_mid_dispatch`
  that actually hits the branch via `window.opener.close()` on a
  script-opened intermediate tab.
- Add `e2e_tab_scoped_command_isolates_refs_from_outer_tab` pinning
  that outer refs don't bleed into the scoped tab's DOM resolution.
- Rewrite `e2e_tab_scoped_command_clears_state_on_switch` as
  `e2e_tab_scoped_command_preserves_outer_tab_state`, verifying the
  restored @e1 still clicks end-to-end.
- Update the 52 `--help` entries for `--tab <id>` to describe peek /
  restore semantics instead of a vague "Target specific tab ID".
- Update README, docs site, config schema, and the agent-facing
  skills reference with working examples (refs survive the peek) and
  a "when to use \`--tab <id>\` vs \`tab <id>\`" guide so agents pick
  the right flag for their workflow.

* fix(tabs): use t<N> prefix for tab ids, add --label for named tabs

Follow-on to the tab work in #1249 and the prior commit, redesigning the
tab handle surface before release since nothing ships these features yet.

## Why

Incrementing integer tab ids (`1`, `2`, `3`) look indistinguishable from
positional indices in command output, LLM-generated scripts, and docs. In
the common single-agent case where position and id coincide, readers have
no visual cue for which mental model they're using. Positional indices
silently shift when unrelated tabs open/close, so misreading a handle as
an index is a correctness hazard.

## Changes

**Tab ids are now `t1`, `t2`, `t3` (strings).** Bare integer `tabId`
values are rejected with a teaching message rather than silently accepted.
The `t` prefix matches the `@e1` element-ref convention and makes ids
unmistakably non-positional at a glance.

**Labels.** Tabs can be created with a user-assigned label (e.g. `docs`,
`app`) via `tab new --label <name> [url]`. Labels are interchangeable
with `t<N>` ids everywhere a tab ref is accepted. They're never
auto-generated, never rewritten on navigation, and must be unique within
a session.

**Dashboard fix.** `packages/dashboard/src/types.ts` declared
`TabInfo.index: number` but the daemon has been sending `tabId` (not
`index`) since #892, making `tab.index` `undefined` and breaking the
dashboard's close/switch buttons silently. Updated the TS types and
usages to consume `tabId` (string) and optional `label`, restoring the
dashboard's tab interactions.

## Surface

- `cli/src/native/browser.rs`: `TabRef::parse` / `format_tab_id` /
  `is_valid_label` / `PageInfo.label` / `BrowserManager::resolve_tab_ref`
  / `BrowserManager::has_label`. `tab_new` gains an optional label
  argument with duplicate rejection. All JSON responses use the string
  form and include the label.
- `cli/src/native/actions.rs`: scoped-command pre-dispatch and
  `handle_tab_{switch,close,new}` parse string refs and resolve to
  stable ids.
- `cli/src/{flags,commands,main,output}.rs`: `--tab` / config `tab`
  are `String`; `tab` subcommand accepts `t<N>` or a label and supports
  `tab new --label <name> [url]`. All 52 `--help` entries updated.
- `agent-browser.schema.json`: `tab` property type is now `string` with
  a pattern matching `t<N>` or label form.
- `packages/dashboard`: `TabInfo.tabId: string` / `label?: string | null`;
  `closeTabAtom`/`switchTabAtom` take `tabRef: string`; component props
  updated.
- Docs: README, docs site (`commands/` and `configuration/`), and the
  agent-facing skills reference rewritten with the new examples.

## Tests

- Added `TabRef::parse` / `format_tab_id` / `is_valid_label` unit tests
  pinning the bare-integer rejection, the teaching error, label rules,
  and round-tripping.
- Added `test_tab_switch_by_id` / `_by_label` / `test_tab_new_with_label`
  / `_with_label_and_url` / `_with_url_then_label` in `commands.rs`;
  rewrote `test_tab_unknown_subcommand_errors` since labels make
  `tab select` a legitimate ref.
- Added `e2e_tab_new_with_label_can_be_switched_and_peeked`,
  `e2e_tab_new_with_duplicate_label_errors`,
  `e2e_tab_scoped_command_rejects_bare_integer`.
- Migrated every existing tab e2e test (and one unit test) from
  integer `tabId` to the string form.

`cargo fmt`, `cargo clippy -- -D warnings`, all 30 non-ignored tab unit
tests, all 13 tab e2e tests, and `tsc --noEmit` on the dashboard all
pass.

* refactor(tabs): drop --tab scoped peek flag; keep t<N> ids and labels

After fleshing out `--tab <id|label>` in the previous commits (scoped
pre/post-dispatch save/restore, ref preservation, outer-tab-closed edge
case, full e2e coverage), the machinery-to-value ratio makes the feature
hard to justify. Nixing it now while nothing has shipped.

## Why

- Every new daemon feature touching per-tab state has to reason about
  scoped-dispatch interleaving. `ScopedRestore`, pre/post-dispatch hooks,
  and the exclusion list add ongoing maintenance tax.
- Three separate PRs (#892, #1249, and this one pre-nix) were needed to
  reach "works correctly." That's a smell.
- `tab <id|label>` switch + labels already cover the legible multi-tab
  workflow case.
- `--tab` vs `tab <id>` have opposite lifecycle semantics but look
  identical, teaching every agent two things where one would do.
- "Non-disruptive peek" isn't actually race-free: the daemon does swap
  active tab during execution, so a concurrent client between pre- and
  post-dispatch sees the scoped tab as active.
- Ref-based interaction with scoped tabs never worked ergonomically —
  refs are per-tab, so `--tab N click @e1` requires `@e1` to already be
  on tab N, which means a prior switch, which negates the peek.
- Adding a feature back is easy; removing shipped API is hard.

If per-tab caching (`HashMap<tab_id, RefMap>`) lands later, `--tab` can
be reintroduced essentially for free. That's the right time.

## Removed

- `--tab <id|label>` global flag (`cli/src/flags.rs`, `cli/src/main.rs`,
  all 52 `--help` entries in `cli/src/output.rs`).
- `tab` property in `agent-browser.schema.json` and the config-options
  row in `docs/src/app/configuration/page.mdx`.
- `ScopedRestore` struct, pre/post-dispatch save/restore in
  `execute_command` (`cli/src/native/actions.rs`).
- `impl Default for RefMap` in `cli/src/native/element.rs` (only added
  for `mem::take` in the scoped machinery).
- `e2e_tab_global_targeting`, `_snapshot`, `_snapshot_non_contiguous`,
  `e2e_tab_scoped_command_preserves_outer_tab_state`,
  `_isolates_refs_from_outer_tab`, `_restores_active_tab`,
  `_outer_tab_closed_mid_dispatch`. 590 lines.
- The "When to use `--tab` vs `tab <id|label>`" sections in README,
  docs site, and skills reference.

## Kept

- Stable tab ids (`t1`, `t2`, `t3`) with bare-integer rejection.
- User-assigned labels (`tab new --label docs [url]`), with duplicate
  rejection and interchangeable use everywhere a tab ref is accepted.
- `BrowserManager::{active_tab_id, has_tab_id, resolve_tab_ref, has_label}`
  accessors (still used by the remaining tab handlers).
- `TabRef::parse`, `format_tab_id`, `is_valid_label` and their unit
  tests.
- Dashboard TS fix (`TabInfo.tabId` + `label`).
- `e2e_tab_close_with_tab_id_closes_active_tab` (renamed docstring to
  drop the gone exclusion-list reference).
- `e2e_tab_new_with_label_can_be_switched_and_closed` (rewrite of the
  previous `_and_peeked` test — now exercises only switch and close).
- `e2e_tab_switch_rejects_bare_integer` (rewrite targeting the
  `tab_switch` daemon handler rather than the removed scoped path).

net: -900 lines across 12 files. `cargo fmt`, `cargo clippy -D warnings`,
all 25 non-ignored tab unit tests, all 6 tab e2e tests, and
`tsc --noEmit` on the dashboard all pass.
2026-04-16 14:33:43 -05:00
Chris Tate c201623710 fix(tabs): correct --tab scoped commands and un-break provider direct-page path (#1249)
* fix(tabs): initialize tab_id on missing PageInfo sites

PR #892 added a required `tab_id: u32` field to `PageInfo` but missed two
initializer sites, which broke the build on the PR branch. CI never caught
this because the external-contributor workflow status was `action_required`
and never ran.

- `cli/src/native/browser.rs:395` — the `direct_page` branch of
  `connect_cdp_inner` used by the cloud providers (Browserbase, Browserless,
  Browser Use, Kernel, AgentCore). Use `assign_tab_id()` to get a fresh id.
- `cli/src/native/browser.rs:1580` — a unit test initializer. Use `tab_id: 1`
  since the test doesn't exercise id assignment.

* feat(tabs): restore active tab and clear per-tab state for scoped --tab

Follow-up on PR #892's `--tab <id>` flag.

The original implementation called `tab_switch_by_id` directly from the
pre-dispatch block in `execute_command` but didn't touch the daemon's
per-tab state, and never restored the previously-active tab. Two concrete
issues this fixes:

1. `state.ref_map`, `state.iframe_sessions`, and `state.active_frame_id`
   were left intact across the pre-dispatch switch, so `--tab N click @e1`
   would try to resolve `@e1` against the scoped tab's DOM using a
   backend-node id from the outer tab. In practice the click handler's
   role+name fallback hid this as "element not found" errors, but on pages
   where both tabs have similarly-labelled elements it could click the
   wrong one.

2. The PR description promised scoped routing would "restore the previous
   active tab", but the implementation permanently switched. `--tab 3
   snapshot` would leave tab 3 as the active tab even after the command
   returned, surprising subsequent non-scoped commands.

This change:

- Saves the current tab's stable `tab_id` (not its array index, which
  would shift if the scoped command closed other tabs) before switching.
- Clears per-tab daemon state before the switch so refs/iframes/frame
  context can't leak between tabs.
- After the action runs, restores the original active tab (also via
  stable id) unless that tab was closed during the scoped command, in
  which case we leave the scoped tab active.
- Adds `BrowserManager::active_tab_id()` and `has_tab_id()` accessors
  to support the above without exposing the internal `pages` vector.

* test(tabs): regression tests for scoped --tab state clearing and restoration

Three new `#[ignore]` e2e tests pinning the fixed behavior:

- `e2e_tab_scoped_command_clears_state_on_switch` — populates `ref_map` on
  tab 1, runs a `tabId: 2`-scoped command, asserts `ref_map`,
  `iframe_sessions`, and `active_frame_id` are all cleared.
- `e2e_tab_scoped_command_restores_active_tab` — sets up two tabs, runs
  a scoped command against the non-active one, asserts a subsequent
  unscoped command reflects the originally-active tab.
- `e2e_tab_scoped_command_handles_outer_tab_closed` — runs a scoped
  `tab_close` that kills the outer tab itself, asserts no error and the
  scoped tab becomes active.

Also updates two misleading comments in the PR's existing
`e2e_tab_global_targeting*` tests to reflect restoration semantics; the
assertions themselves were already consistent with restoration.

* docs(tabs): document stable tab IDs and --tab scoped-command flag

Per AGENTS.md, changes that users or agents would need to know about must
land in every doc surface. Fills the gaps PR #892 left:

- `README.md` — new `--tab <id>` row in the Options table, rewrite the
  tab command examples to use `<id>` instead of `<n>`, add a paragraph
  explaining stable tab IDs and `--tab` peek semantics.
- `docs/src/app/commands/page.mdx` — same command-example rewrite plus a
  new "Stable tab IDs and `--tab`" subsection.
- `docs/src/app/configuration/page.mdx` — add `tab` row to the config
  options table so JSON config users can discover it.
- `agent-browser.schema.json` — add `tab` property with description,
  matching the config schema.
- `skills/agent-browser/references/commands.md` — same command-example
  rewrite plus a short paragraph for agents on when to use `--tab`.
2026-04-16 12:34:14 -05:00
Daniel Hails 67dc631977 Consistent Tab IDs & Global Tag Targeting (#892)
Introduces stable per-tab IDs and a global `--tab <id>` flag for scoping individual commands to a specific tab.

Breaking change: response payloads for `tab_list`, `tab_new`, `tab_switch`, `tab_close`, and `window_new` now use `tabId` instead of `index`. `tab_close` returns `{tabId, closed: true}` instead of `{closed, activeIndex}`. `agent-browser tab <unknown>` now errors instead of silently listing tabs.

Follow-up PR to land immediately after this fixes a compile error on the provider direct-page path, clears per-tab daemon state around scoped switches, and implements active-tab restoration so `--tab N` is non-intrusive as intended.
2026-04-16 12:02:55 -05:00
Chris Tate c691b269cb fix: improve config schema and serve from docs site (#1248)
Fix idleTimeout description to document human-friendly formats (30s,
5m, 1h) alongside raw milliseconds. Add trailing newline. Serve the
schema from the docs app at agent-browser.dev/schema.json via a
prebuild copy step, and update all $schema URLs to use the stable
docs-hosted URL instead of raw GitHub.
2026-04-16 10:42:44 -05:00
Michaelandvercel[bot] <35613825+vercel[bot]@users.noreply.github.com> 4f9edf9337 feat: add JSON Schema for agent-browser config files (#1242)
* feat: add JSON Schema for agent-browser config files

Adds agent-browser.schema.json describing all config options with
types and descriptions. Enables IDE autocomplete and validation when
referenced via $schema in agent-browser.json or
~/.agent-browser/config.json.

README and docs site updated to document the schema reference.

* fix(schema): use integer type for maxOutput to match usize deserialization

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>

---------

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
2026-04-16 08:44:01 -05:00
Tom Dale 19808d08f8 fix: load storage state at launch when --state / AGENT_BROWSER_STATE is set (#1241)
* fix: load storage state at launch when --state / AGENT_BROWSER_STATE is set

The `--state` flag and `AGENT_BROWSER_STATE` env var were documented as
restoring saved browser state (cookies + localStorage) at launch, but
`load_state()` was never called after the browser started. The feature
has been broken since it was introduced.

Adds `try_load_storage_state()` and calls it from every early-return
path in `auto_launch()` (lazy launch triggered by commands like
`navigate`) and from `handle_launch()` (explicit `launch` command).

Also adds 4 e2e tests covering all state-persistence paths:
- Explicit launch with `storageState` field
- Auto-launch via `AGENT_BROWSER_STATE` env var
- Session-name auto-restore via `try_auto_restore_state`
- Explicit `state_load` command (baseline sanity check)

Fixes #1164.

* style: apply cargo fmt to e2e_tests.rs

Reformats a single long format\! call to satisfy CI's rustfmt check.
No behavior change.

* fix: call try_load_storage_state in all handle_launch branches

The CDP URL, CDP port, auto-connect, and provider early-return branches
were skipping storage state loading because try_load_storage_state was
only called in the normal BrowserManager::launch() path at the bottom
of handle_launch().

Also compute storage_state_owned once and reuse it across all branches
rather than borrowing storage_state (a &str tied to cmd) in a helper
that needs an owned Option<String>.

* Fix storage state reload on reused launches

* Fix storage-state launch errors

* Fix storage state replay ordering

* Align storage-state errors across launch paths

* Fix storageState launch cleanup
2026-04-16 08:38:54 -05:00
Chris Tate a884960806 Prepare v0.25.5 (#1246)
* fix(test): tolerate stale screencast frames in viewport e2e test

Chrome's `Page.startScreencast` `maxWidth`/`maxHeight` are upper bounds,
and early frames can arrive before the viewport resize fully takes effect.
Instead of asserting exact JPEG dimensions on the first frame, skip frames
with stale dimensions and wait for one that matches.

* Prepare v0.25.5
2026-04-16 01:19:52 -05:00
Chris Tate dba382350b fix(test): tolerate stale screencast frames in viewport e2e test (#1245)
Chrome's `Page.startScreencast` `maxWidth`/`maxHeight` are upper bounds,
and early frames can arrive before the viewport resize fully takes effect.
Instead of asserting exact JPEG dimensions on the first frame, skip frames
with stale dimensions and wait for one that matches.
2026-04-16 00:54:29 -05:00
Chris Tate 2e99293e80 fix(ci): install ffmpeg for e2e recording test (#1244)
The `e2e_recording_inherits_viewport` test added in #1208 requires
ffmpeg on the CI runner. Without it, `recording_start` fails with
"ffmpeg not found".
2026-04-16 00:20:04 -05:00
jin.2andhyunjinee b02e485a37 fix: prefer DevToolsActivePort websocket path over HTTP discovery in --auto-connect (#1218)
* fix: prefer DevToolsActivePort websocket path over HTTP discovery in --auto-connect

Reverses the discovery order in `auto_connect_cdp()` so the exact
WebSocket path from DevToolsActivePort is tried first, falling back
to legacy HTTP endpoints (`/json/version`, `/json/list`) only when
the direct path fails. This eliminates the duplicate remote-debugging
permission prompts caused by unnecessary HTTP probes on Chrome M144+.

Also adds `verify_ws_endpoint()` to validate the WebSocket URL is a
live CDP server before returning it, preventing stale URLs from being
handed to callers.

Fixes #1210
Fixes #1206

* chore: remove unrelated issue references from test comment

* style: apply rustfmt

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-04-15 17:50:11 -05:00
jin.2andhyunjinee db29d5fead fix: inherit viewport dimensions in recording context (#1208)
* fix: inherit viewport dimensions in recording context

When `record start` creates a new browser context, it now re-applies the
current viewport settings (from `set viewport` or `set device`) so the
recording resolution matches what the user configured instead of falling
back to the default 1280×720.

Closes #1207

* style: apply cargo fmt to e2e test

* chore: remove obvious comments

* chore: remove obvious comments from e2e test

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-04-13 23:40:26 -05:00
Chris Tate ddf6d6a2af fix: print data for get box and get styles in text mode (#1231) (#1233)
The text-mode output formatter had branches for most `get` subcommand
response shapes but was missing handlers for `boundingbox` and `styles`.
Both commands fell through to the default "Done" message instead of
printing the returned data.

Closes #1231
2026-04-13 23:39:11 -05:00
Asish Kumar 50323499c8 fix: preserve the active page when removing earlier tabs (#1220)
Adjust tab-removal bookkeeping so closing or losing a page before the active tab keeps the session pointed at the same logical page instead of silently shifting to the next one.

Add regression coverage for earlier-tab removal, later-tab removal, last-tab clamping, and the empty-page case.

Signed-off-by: Asish Kumar <officialasishkumar@gmail.com>
2026-04-13 16:50:46 -05:00
Chris Tate 2114bdf847 Prepare v0.25.4 release (#1228) 2026-04-12 13:44:15 -05:00
Chris Tate 7c2ff0a2a6 Move specialized skills to skill-data/ so npx skills add only finds one (#1227)
The skills CLI metadata.internal flag was never implemented (PRs #587
and #652 were both closed). All 6 skills were showing in the installer.

Move the 5 specialized skills (dogfood, electron, slack, vercel-sandbox,
agentcore) from skills/ to skill-data/, which the skills CLI does not
search. The bootstrap skill stays in skills/ for discovery. The Rust CLI
searches both directories so agent-browser skills list/get still serves
all 6.
2026-04-12 13:13:04 -05:00
Chris Tate 71343069d2 Add agent-browser skills command with evals (#1225)
* Add `agent-browser skills` command

Adds a `skills` CLI command that serves bundled skill content at runtime,
always matching the installed CLI version. This solves the problem of
agents relying on stale cached SKILL.md files after CLI upgrades.

The `npx skills add vercel-labs/agent-browser` flow now installs a single
thin discovery skill with trigger words for all use cases (browser
automation, dogfooding, Electron apps, Slack, etc.) that directs agents
to `agent-browser skills get <name>` for current instructions. The other
five skills (dogfood, electron, slack, vercel-sandbox, agentcore) are
marked `metadata.internal: true` so they are not installed by default but
remain accessible via the CLI command.

Subcommands:
  skills [list]              List available skills
  skills get <name> [--full] Get skill content (with optional references)
  skills get --all           Get all skill content
  skills path [name]         Print skill directory path

* Fix skills command robustness: UTF-8 safety, flag handling, path output

- Make truncate_description UTF-8-safe using char_indices() instead of
  byte-indexed slicing that panics on multi-byte codepoints
- Pass get_all as a bool parameter to run_get instead of embedding
  --all as a sentinel string in the names list
- Canonicalize skills_dir path so `skills path` output is clean
- Warn on unrecognized flags in `skills get` instead of silently
  ignoring them

* Add evals framework and strengthen SKILL.md for better agent compliance

Strengthen SKILL.md loading instructions to require `skills get` before
running commands, and trim skill descriptions to prevent agents from
guessing at command syntax. Add TypeScript/Bun eval framework that tests
skill-loading, skill-selection, and command-usage via Claude CLI with
Vercel AI Gateway. Evals pass 20/20 (100%), up from 85% baseline.

* Fix formatting in skills.rs

* Add Codex provider to evals framework

Add multi-provider support with a shared Provider interface. Codex
provider spawns `codex exec --json`, parses JSONL output, and writes
~/.codex/config.toml for AI Gateway routing. Use `--provider codex`
to run evals with Codex (default model: openai/o3). First run scores
19/20 (95%) with 100% on skill-loading and skill-selection.

* Use scoped temp dir for Codex config instead of overwriting ~/.codex
2026-04-12 12:55:46 -05:00
Chris Tate fa043a496f fetch GitHub star count dynamically in docs header (#1202)
* fetch GitHub star count dynamically in docs header

Replace the hardcoded "27k" star count with a live fetch from the
GitHub API, revalidated every 24 hours via Next.js fetch caching.
Gracefully hides the count if the API is unreachable.

* remove GITHUB_TOKEN usage from star count fetch
2026-04-09 02:07:32 -05:00
Marshall Sun e4e2fe8633 fix(skill): correct duplicate Option numbering in auth section (#1161) 2026-04-07 01:29:01 -05:00
2164e71c30 fix: use custom viewport dimensions in streaming frame metadata and image resolution (#1033)
* fix: use custom viewport dimensions in streaming frame metadata

  CDP's Page.screencastFrame metadata returns physical device dimensions
  instead of the emulated viewport, causing frame messages to report
  incorrect deviceWidth/deviceHeight when a custom viewport is set.

  Use the viewport dimensions captured at screencast start instead of
  the CDP metadata values, since the screencast image is already captured
  at the configured viewport size.

  Closes #1031

* fix: resize browser content area on viewport change for correct
  screencast dimensions

  Emulation.setDeviceMetricsOverride only changes the CSS viewport, but
  screencast captures the actual browser content area. This caused frame
  images to have incorrect dimensions (e.g., 1000x451 instead of
  1000x1000)
  when a custom viewport was set.

  - Call Browser.setContentsSize after setDeviceMetricsOverride so the
    content area matches the emulated viewport
  - Restart active screencast when viewport dimensions change so
    maxWidth/maxHeight parameters are updated
  - Skip redundant screencast restarts when dimensions are unchanged
  - Extend E2E test to verify actual JPEG image dimensions, not just
    metadata

* fix: pass viewport dimensions to --window-size at launch and log setContentsSize failures

- Add viewport_size to LaunchOptions so --window-size matches the
  configured viewport from the start, reducing reliance on the
  experimental Browser.setContentsSize CDP call at runtime
- Log Browser.setContentsSize failures instead of silently ignoring
  them with let _ =

* fix: remove duplicate viewport change detection block (dead code from merge)

* fix: use log::debug! instead of eprintln! for setContentsSize failure

* revert: use eprintln! instead of log crate for setContentsSize failure

The daemon's stderr pipe is closed after startup, so log crate
subscribers cannot output during normal operation. eprintln! is
visible during startup and in tests, matching the existing convention.

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 01:28:36 -05:00
juniper929andwangjingjing 6520e4123c fix: re-apply ignore_https_errors to recording context (#1178)
Security.setIgnoreCertificateErrors is session-scoped, so creating a new
BrowserContext for recording (Target.createBrowserContext) starts with the
default certificate validation enabled, ignoring the launch-time flag.

Store ignore_https_errors in BrowserManager alongside download_path, and
re-apply Security.setIgnoreCertificateErrors to the new session after
recording context creation — matching the existing pattern for download
behavior re-application.

Fixes #1172

Co-authored-by: wangjingjing <wangjingjing.99@bytedance.com>
2026-04-07 01:26:07 -05:00
Chris Tate 6d05a9485d v0.25.3 (#1176) 2026-04-06 21:04:38 -05:00
jin.2andhyunjinee 1a6ea17ed0 fix: promote hidden radio/checkbox inputs in snapshot refs (#1085)
* fix: promote hidden radio/checkbox inputs in snapshot refs (#1024)

When a <label> wraps a display:none <input type="radio">, Chrome
excludes the input from the accessibility tree entirely. The label
appears as role="LabelText" with an empty name, making it impossible
for AI agents to identify radio buttons via data.refs.

Detect hidden radio/checkbox inputs during cursor-interactive scanning
and promote their parent LabelText/generic nodes to the correct role
with proper name and checked state.

- Add HiddenInputKind enum to validate input types at parse boundary
- Extend cursor-interactive JS to detect hidden inputs inside elements
- Extract promote_hidden_inputs() for testable role promotion logic
- Add unit tests for promotion, name preservation, and skip conditions

* style: apply cargo fmt

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-04-06 20:53:13 -05:00
Chris Tate c4e0f9d367 anchors (#1175) 2026-04-06 19:59:03 -05:00
Chris Tate b75fba130b v0.25.2 (#1174) 2026-04-06 18:56:05 -05:00
Chris Tate eb15cc0894 fix: remove PR_SET_PDEATHSIG that kills Chrome after ~10s idle (#1157) (#1173)
v0.24.1 introduced `prctl(PR_SET_PDEATHSIG, SIGKILL)` in #1137 to kill Chrome
when the daemon dies. However, `PR_SET_PDEATHSIG` tracks the **thread** that
called `fork()`, not the process (`prctl(2)` documents this). Chrome is spawned
via `tokio::task::spawn_blocking`, whose threads are reaped after ~10 seconds of
idle time. When the blocking thread exits, the kernel sends SIGKILL to Chrome
even though the daemon is still alive.

Symptoms reported in #1157:
- `tab list` shows `about:blank` after a few seconds
- `snapshot` returns an empty page
- All Chrome processes exit ~9 seconds after launch
- Any workflow involving navigation or waiting breaks

The fix removes `PR_SET_PDEATHSIG` from the Chrome `pre_exec` hook. Orphan
cleanup is already handled by the process-group kill (`kill(-pgid, SIGKILL)`) in
`ChromeProcess::kill()`, which runs via daemon signal handlers, `close_notify`,
idle timeout, and `Drop`.

Fixes #1157
2026-04-06 18:44:56 -05:00
Chris Tate 7b3f826cbb v0.25.1 (#1170) 2026-04-06 10:53:37 -05:00
Chris Tate 1f8757b215 embed dashboard (#1169)
* embed dashboard

* docs

* fmt
2026-04-06 10:45:08 -05:00
Chris Tate 3896ed0d9d fix: recover GitHub release when npm published but release creation failed (#1168)
check-release now detects when the npm version matches but the GitHub
release is missing. build-binaries and github-release run in that case
so binaries, dashboard, and release notes are created without requiring
a version bump.
2026-04-06 10:22:11 -05:00
Chris Tate 92d730e5fd fix dashboard build (#1167) 2026-04-06 10:05:35 -05:00
Chris Tate 77805ff4bc v0.25.0 (#1166) 2026-04-06 09:50:13 -05:00
Chris Tate c3bbb15c5f fix: CI test failures on Windows and E2E (#1165)
- Windows: match "actively refused it" error message in
  download_bytes_connection_refused test (os error 10061)
- E2E relaunch: use userAgent instead of extensions to trigger
  relaunch, since extensions force headed mode which requires a
  display server unavailable in CI
- E2E auth_login SPA: use addEventListener instead of inline
  onsubmit for more reliable form submission prevention
2026-04-06 09:42:30 -05:00
Chris Tate 131f229971 chat (#1163)
* chat

* docs

* fmt
2026-04-06 09:21:11 -05:00
Chris Tate 317e6869b6 Add AI chat to dashboard, refactor stream module, snapshot --urls, batch argument mode (#1160)
* chat

* refactor

* fixes

* fixes

* fixes

* fixes

* improvements

* download chat

* batch

* fixes

* fixes

* fixes

* fmt

* fixes

* fixes

* fixes

* fmt
2026-04-06 08:10:43 -05:00
jin.2andhyunjinee fcb6615f5a fix: support accessibility tree refs in upload command (#1156)
* fix: support accessibility tree refs in upload command (#1107)

The upload command only accepted CSS selectors while click/fill supported
accessibility tree refs (e.g. e1, @e1, ref=e1). This resolves the API
inconsistency by reusing resolve_element_object_id for all selector types.

* style: apply cargo fmt

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-04-05 15:38:49 -05:00
Chris Tateandctate c47756be9b fix(cli): honor AGENT_BROWSER_DEFAULT_TIMEOUT env var for wait commands (#1153)
* fix(cli): honor AGENT_BROWSER_DEFAULT_TIMEOUT env var for wait commands

The `AGENT_BROWSER_DEFAULT_TIMEOUT` environment variable was being ignored by CLI wait commands, causing them to use hardcoded 30-second timeouts instead of the configured default.

## Changes Made

- **Centralized timeout injection**: Modified `parse_command()` to automatically inject `flags.default_timeout` into any wait-family command that doesn't already have an explicit `--timeout` flag
- **Environment variable parsing**: Added `default_timeout` field to `Flags` struct that reads from `AGENT_BROWSER_DEFAULT_TIMEOUT` env var
- **Daemon propagation**: Updated daemon spawning to pass through the default timeout via environment variables
- **Unified timeout handling**: Added `timeout_ms()` helper method in `DaemonState` that all wait handlers now use instead of scattered `unwrap_or()` calls
- **Comprehensive test coverage**: Added 10 regression tests covering all wait command variants and edge cases

## Implementation Details

The fix uses a two-stage approach:
1. CLI parses the env var and injects timeout values into command JSON for any `wait*` action
2. Daemon reads the env var and provides a centralized fallback via `timeout_ms()` helper

This ensures new wait variants automatically inherit the default timeout without requiring per-variant wiring.

Fixes #1147

* fix: preserve 30s default timeout for backward compatibility

The default_timeout_ms fallback was set to 25_000ms, which silently
changes the existing 30_000ms behavior for users who haven't set
AGENT_BROWSER_DEFAULT_TIMEOUT. Restore the original 30s default.

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-04-05 14:15:00 -05:00
Chris Tate 44f37c92d3 fix(cli): improve dashboard download error handling and retry logic (#1154)
This PR fixes dashboard installation failures by improving HTTP error handling and adding retry logic for network issues.

## Problem
Users were experiencing dashboard installation failures with cryptic error messages like "error sending request for url" when network issues occurred or when GitHub releases were temporarily unavailable.

## Changes
- **Enhanced HTTP client**: Added proper User-Agent, timeouts (120s total, 30s connect), and better error formatting
- **Retry logic**: Added exponential backoff retry (up to 3 attempts) for connection errors and server errors (5xx)
- **Better error messages**: Improved error formatting with full error chain context
- **Comprehensive tests**: Added unit tests for various failure scenarios (404, connection errors, partial downloads)

## Implementation Details
- Replaced direct `reqwest::get()` calls with a configured HTTP client
- Added `format_reqwest_error()` to provide detailed error context
- Implemented retry logic in `download_bytes()` with exponential backoff
- Added extensive test coverage including mock HTTP server scenarios

Fixes #1146
2026-04-05 10:07:08 -05:00
jin.2andhyunjinee 9f51879012 fix: rewrite getByRole to use CDP accessibility tree with ref-based element resolution (#1145)
* fix: rewrite getByRole to use CDP accessibility tree instead of CSS selectors

The old `handle_getbyrole` generated `querySelectorAll('[role="link"], link')`
which matched `<link>` stylesheet elements instead of `<a>` anchor tags.
This happened because ARIA role names were used directly as CSS tag selectors,
and several roles differ from their HTML element names (e.g. link → a,
heading → h1-h6, textbox → input/textarea).

The fix replaces the JS-based DOM query with the CDP `Accessibility.getFullAXTree`
API, where the browser engine correctly computes implicit ARIA roles per the
WAI-ARIA / HTML-AAM spec. This is the same approach already used by `snapshot.rs`
and `element.rs` in this codebase.

Changes:
- Rewrite `handle_getbyrole` to query the browser's accessibility tree via CDP
- Add `find_ax_node_by_role` helper for AX tree traversal with role/name/exact matching
- Use `DOM.resolveNode` + `Runtime.callFunctionOn` to bridge AX node → DOM marker
- Add iframe support via `resolve_ax_session` (missing in old implementation)
- Fix cleanup to use correct CDP session (old code used default session, breaking iframe cleanup)
- Export `extract_ax_string` as `pub(super)` for reuse
- Add 4 regression tests for `find_ax_node_by_role`

Fixes #1123

* style: apply cargo fmt

* chore: remove redundant comments

* refactor: replace marker attribute with temporary ref for element resolution

Eliminates 3 CDP round-trips (DOM.resolveNode, Runtime.callFunctionOn,
Runtime.evaluate cleanup) by registering a temporary ref in the ref_map.
execute_subaction resolves the element via backendNodeId directly.
No more DOM pollution with marker attributes.

* fix: ref counter collision, ref_map leak, and stale fallback name

- Increment next_ref_num after inserting temp ref to prevent id collision
- Remove temp ref after execute_subaction to prevent unbounded ref_map growth
- Return actual AX name from find_ax_node_by_role for accurate fallback resolution
- Add RefMap::remove method

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-04-05 09:10:24 -05:00
Chris Tate 1205e2ca9c v0.24.1 (#1142)
* v0.24.1

* fix: e2e test failures on CI

- e2e_relaunch_on_options_change: use headless for all launches;
  the third launch only changes extensions, which is sufficient to
  trigger the relaunch hash mismatch without needing an X display
- e2e_auth_login flake: reduce SPA render delay from 1200ms to 800ms
  to add headroom within the 5s preferred selector window on slower
  CI runners
2026-04-04 12:49:40 -05:00
9f8e518a46 feat: reuse Chrome profile login state via --profile <name> (#1131)
* feat(chrome): add Chrome profile name resolution and copy for --profile flag

When --profile receives a name without path separators (e.g., "Default"),
it now resolves the name against installed Chrome profiles, copies the
profile to a temp directory (excluding large cache dirs), and launches
Chrome with the copied profile to reuse login state.

Key changes:
- Add profile resolution: is_chrome_profile_name, find_chrome_user_data_dir,
  list_chrome_profiles, resolve_chrome_profile (3-tier matching)
- Add copy_chrome_profile with best-effort copy and exclusion list
- Wire preprocessing into launch_chrome before retry loop
- Add use_real_keychain field to LaunchOptions for conditional keychain flags
- Make --password-store=basic and --use-mock-keychain conditional

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(cli): add `profiles` command to list available Chrome profiles

Adds `agent-browser profiles` command that reads Chrome's Local State
file to list available profiles with directory names and display names.
Supports --json output. Added help text in print_command_help and
print_help.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs: add Chrome profile reuse documentation across all locations

Update all 5 documentation locations per AGENTS.md:
- output.rs: updated --profile help text and examples
- README.md: added Chrome Profile Reuse section, updated options table
- SKILL.md: added profile reuse as Option 2
- docs/src/app/sessions/page.mdx: added Chrome profile reuse section
- chrome.rs: added doc comments to get_chrome_user_data_dirs

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* style: fix formatting and clippy warning in chrome.rs

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: simplify profile resolution and launch integration

- Only clone LaunchOptions when profile name requires resolution
  (avoids unnecessary allocation on every Chrome launch)
- Remove redundant is_file() check before copy of Local State
  (copy() handles missing files naturally)
- Extract format_profile_list() to deduplicate error formatting
- Remove unnecessary section comments in tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor(tests): use RAII TempDir guard for test cleanup

Replace manual remove_dir_all calls with a TempDir struct that
auto-cleans on drop, preventing temp dir leaks on test panics.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-04-04 11:21:11 -05:00
Chris Tateandctate 354dd8b615 fix: pass --ignore-certificate-errors Chrome flag when --ignore-https-errors is set (#1132)
* fix: pass --ignore-certificate-errors Chrome flag when --ignore-https-errors is set

The existing CDP-level Security.setIgnoreCertificateErrors only takes
effect after Chrome opens a connection, but some TLS errors (e.g.
ERR_SSL_PROTOCOL_ERROR) are rejected at the network layer before CDP
can intervene. Adding the Chrome launch flag ensures certificate errors
are bypassed from process start.

Fixes #1124

* test: add unit tests for --ignore-certificate-errors Chrome flag

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-04-04 11:15:48 -05:00
Chris Tateandctate 9b0205ef50 fix: prevent orphaned Chrome processes on daemon exit (#1137)
Three changes to ensure headless Chrome process trees are fully cleaned
up when the daemon exits, whether gracefully or abnormally:

1. Spawn Chrome in its own process group (`setpgid(0,0)`) and kill the
   entire group (`kill(-pgid, SIGKILL)`) in `ChromeProcess::kill()`.
   This takes down all helper processes (GPU, renderer, utility,
   crashpad) instead of only the main Chrome PID.

2. On Linux, set `PR_SET_PDEATHSIG(SIGKILL)` on the Chrome process so
   the kernel automatically kills it when the daemon dies for any
   reason, including SIGKILL/OOM. No macOS equivalent exists.

3. Replace `process::exit(0)` in the daemon's close handler with a
   `Notify` signal back to the main loop, so Rust destructors
   (including `ChromeProcess::Drop`) actually run.

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-04-04 11:15:26 -05:00
Chris Tateandctate c69f611d78 Fix CDP attach hang on real browser sessions (Chrome 144+) (#1133)
When connecting to a real, already-running browser (Chrome 144+) via CDP,
targets may be paused waiting for the debugger after attach. Without an
explicit Runtime.runIfWaitingForDebugger call, page-level commands hang
indefinitely even though the WebSocket connection is live.

Add Runtime.runIfWaitingForDebugger after Runtime.enable in all target
attachment paths: enable_domains (covers initial attach, tab_new,
tab_switch), enable_domains_direct (provider proxies), and the iframe
auto-attach handler. The call is placed before Network.enable to avoid
the documented deadlock when Network.enable precedes the resume. It is
a no-op for targets that are not paused.

Fixes #1130

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-04-04 11:12:35 -05:00
Chris Tateandctate 2911d91ce3 Fix stale daemon after upgrade causing silent CDP failures (#1134)
After upgrading agent-browser, the old daemon process keeps running.
ensure_daemon() only checks socket connectivity, not version, so the
new CLI silently reuses the old daemon — causing broken CDP behavior
with no error or warning.

Add a version sidecar file (.version) written by the daemon on startup.
ensure_daemon() now compares it against the CLI's compiled version and
automatically kills/restarts on mismatch. Missing version files (from
pre-fix or Node.js-era daemons) are treated as mismatches so the first
upgrade to this version also benefits.

Fixes #1127

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-04-04 11:07:30 -05:00
Chris Tateandctate 5e33672d08 fix: recover from stale daemon/socket state (#1136)
When a daemon is killed or crashes without cleaning up, stale .sock/.pid
files are left behind. Previously, `close --all` would fail to connect to
these zombie daemons and simply report an error, leaving the stale files
in place and poisoning all future sessions.

Three fixes:

1. `close --all` now force-kills unreachable daemon processes and removes
   all stale files (pid, sock, stream) instead of reporting failure. It
   also cleans up dead-but-lingering PID files during enumeration and
   scans for orphaned .sock files without corresponding .pid files.

2. `ensure_daemon` handles concurrent startup races: when a spawned
   daemon exits with "Address already in use" (another instance won the
   bind race), it checks whether the winner is accepting connections and
   piggybacks on it instead of failing.

3. `cleanup_stale_files` is now public so `close --all` can reuse it.

Fixes #1118

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-04-04 10:54:46 -05:00
jin.2andhyunjinee c976212db4 fix: idle timeout not respected due to sleep future reset in select loop (#1110)
* fix: idle timeout not respected on Unix/macOS (#1101)

The idle sleep future was recreated inside the select loop on every
iteration.  Because the drain interval ticks every 500 ms the future
was dropped and replaced before it could reach its deadline, so the
daemon never shut down.

Move the pinned Sleep future outside the loop so it survives drain
ticks and only resets on actual command receipt (reset_rx).  Apply the
same fix to the Windows path where accept events caused an identical
timer reset.

* style: apply cargo fmt

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-04-04 10:51:55 -05:00
05d86fadf5 fix: relaunch browser when launch options change (#996)
* fix: relaunch browser when launch options change (#993)

  When the daemon already held a running browser, handle_launch only
  checked connection type and liveness to decide reuse. Config changes
  like adding extensions to config.json were silently ignored.

  Store a hash of the relaunch-relevant LaunchOptions fields and compare
  on each launch command. If the hash differs the browser is closed and
  relaunched with the new options.

* fmt

* fix

* fix

* fmt

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-04-04 10:41:02 -05:00
Hung-Che Lo 4b5ba9f245 fix(native): auto_launch() honours AGENT_BROWSER_PROVIDER for cloud providers (#1126)
When a non-launch command (e.g. open, snapshot) triggers auto_launch()
before the explicit launch command is processed, auto_launch() now checks
AGENT_BROWSER_PROVIDER and connects via the provider API instead of
always falling back to a local Chrome instance.

Also redirects daemon stderr to /dev/null when not in debug mode to
prevent crashes from broken pipe after the CLI drops the piped stderr
handle. Cloud providers may write to stderr during connection setup.

Fixes #1125
Related: #979
2026-04-04 10:29:04 -05:00
Chris Tateandctate c52d25d576 Fix HAR capture missing API requests under heavy traffic (#1135)
The CDP event broadcast buffer (256 events) was too small for pages with
many concurrent API requests, causing silent event drops. Modern SPAs
routinely fire 100+ API calls during page load, generating 300+ CDP
network events that would overflow the buffer between drain cycles.

Changes:
- Increase CDP broadcast buffer from 256 to 4096 (event channel) and
  512 to 4096 (raw channel)
- Reduce background drain interval from 500ms to 100ms
- Handle Network.loadingFailed events in HAR recording
- Enable Network.enable on cross-origin iframe sessions during HAR
  recording and request tracking
- Allow Network events from iframe sessions through the session filter
- Log a warning when buffer overflow occurs instead of silently dropping

Fixes #1128

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-04-04 10:25:12 -05:00
Chris Tate 0a36666587 agentcore skill (#1122) 2026-04-02 21:00:15 -05:00
Chris Tate 2a44b515ee v0.24.0 (#1121) 2026-04-02 20:42:07 -05:00
Chris Tate 13ed01b3bd agentcore docs (#1120)
* agentcore docs

* fixes

* fixes
2026-04-02 20:31:14 -05:00
Pahud HsiehandChris Tate 8561a755ef feat: add AWS Bedrock AgentCore browser provider (native Rust) (#397)
* feat: add AWS Bedrock AgentCore browser provider (native Rust)

- Add agentcore provider with SigV4 authentication
- AWS SDK deps are optional behind 'agentcore' feature flag
- Build with: cargo build --features agentcore
- Supports AGENTCORE_REGION, AGENTCORE_PROFILE_ID, AGENTCORE_BROWSER_ID env vars
- Returns session ID and Live View URL in launch response
- Add connect_cdp_with_headers for signed WebSocket connections

* test: add unit tests for AgentCore provider

* refactor: use lightweight manual SigV4 signing instead of AWS SDK

- Replace aws-sigv4/aws-config with manual HMAC-SHA256 signing
- Removes ~60s compile time and significant binary size
- Credentials read from AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY env vars
- Supports AWS_SESSION_TOKEN for temporary credentials

* fix: correct AgentCore API endpoints

- Host: bedrock-agentcore.{region}.amazonaws.com
- Start session: PUT /browsers/{id}/sessions/start
- Stop session: PUT /browsers/{id}/sessions/stop
- Add urlencoding for browser ID in path
- Add AWS_DEFAULT_REGION fallback

* fix: use profileConfiguration.profileIdentifier for AgentCore profile

The AWS Bedrock AgentCore API expects profile configuration in the format:
{
  "profileConfiguration": {
    "profileIdentifier": "<profile-id>"
  }
}

Not the flat "profileId" field that was previously used.

* feat: support AWS credential provider chain via AWS CLI

- Try env vars first (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
- Fall back to 'aws configure export-credentials --format env'
- Honor AWS_PROFILE environment variable
- Works with SSO, IAM roles, credential files, etc.

---------

Co-authored-by: Chris Tate <chris@ctate.dev>
2026-04-02 18:33:37 -05:00
Chris Tate 89595836c6 v0.23.4 (#1100) 2026-03-31 02:09:57 -05:00
Chris Tate 7b4b124e7f Fix daemon hang on Linux caused by waitpid(-1) race condition (#1098)
* Fix daemon hang on Linux caused by waitpid(-1) race condition

Fixes #1035

The SIGCHLD handler added in v0.22.3 called `waitpid(-1, WNOHANG)` to reap zombie Chrome processes. This races with Rust's `Child::try_wait()` / `Child::wait()` because `waitpid(-1)` reaps *any* child in the process, stealing the exit status before the `Child` handle can collect it. The result is `ECHILD` errors in `BrowserManager::has_process_exited()` and `ChromeProcess::kill()`, leaving the daemon in a broken state that manifests as indefinite hangs on Linux servers.

The fix removes the global SIGCHLD handler and `reap_children()` function entirely. Instead, the existing 500ms drain interval now checks `mgr.has_process_exited()` (which delegates to `Child::try_wait()`) for targeted, race-free crash detection. When Chrome is detected as crashed, the `BrowserManager` is closed and daemon state is reset.

## Changes

- Removed `SIGCHLD` signal handler and `reap_children()` from the Unix daemon event loop
- Enhanced the drain interval to detect Chrome crashes via `has_process_exited()` and clean up state
- Added 3 regression tests:
  - Static source scan that fails if `waitpid(-1)` is re-introduced in production code
  - `try_wait()` correctness test for exit detection without a SIGCHLD handler
  - Kill detection test simulating a Chrome crash

* fmt
2026-03-31 01:59:07 -05:00
Chris Tate b2b6356d63 fix release notes (#1097)
* fix release notes

* contributors note
2026-03-30 20:54:59 -05:00
Chris Tate e6ba1eb8c9 v0.23.3 (#1096) 2026-03-30 20:29:20 -05:00
1f4b6b9d7a fix: include buttons bitmask in drag mouseMoved events (#1087)
* fix: include buttons bitmask in drag mouseMoved events

The drag handler was omitting the `buttons` field from every
`mouseMoved` event dispatched during the move phase.  Without it the
browser sees `event.buttons === 0`, meaning no button is held, so
`dragstart`/`dragover`/`drop` never fire and the drop target never
receives the element.

Fix:
- Add `"buttons": 1` (left-button mask) to each `mouseMoved` sent
  while the button is held.
- Add `"buttons": 1` to `mousePressed` and `"buttons": 0` to
  `mouseReleased`, consistent with how `dispatch_click` handles the
  same fields in interaction.rs.
- Correct the parity-test fixture for `drag`, which was supplying a
  `selector` key instead of the `source` key that `handle_drag` reads.
- Add an e2e test (`e2e_drag_action_sends_buttons_during_move`) that
  drives the high-level `drag` action against the existing
  `html5_drag_probe` fixture and asserts that `mousemove` events carry
  `buttons == 1` and that `dragstart` fires on the source element.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* style: fix rustfmt formatting in e2e drag test

---------

Co-authored-by: wangjingjing <wangjingjing.99@bytedance.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-30 20:21:04 -05:00
Chris Tate 6c93480d0d streamline release (#1095)
* update release

* more docs

* dates
2026-03-30 19:53:53 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> cc9da7aff7 chore: version packages (#1094)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-30 19:14:43 -05:00
Chris Tate 3c942e2874 prepare v0.23.2 (#1093) 2026-03-30 18:38:57 -05:00
Chris Tate 40fdb4284d feat: dashboard provider support and session creation improvements (#1092)
Add provider icons and session creation from the dashboard UI.
Sessions can now be created with cloud providers (Browserbase,
Browserless, Browser Use, Kernel) in addition to local engines.

CLI changes:
- Track provider via .provider files alongside .engine files
- Add WaitUntil::None variant to skip lifecycle event waits for providers
- Auto-set waitUntil=none when --provider is used with navigate
- Fix Browser Use: use direct WSS connection (wss://connect.browser-use.com)
- Add connect_cdp_direct for providers with page-level CDP proxies
- Fix resolve_cdp_url to convert https:// provider URLs to wss://
- Treat empty CDP session_id as None (omit from protocol messages)
- Fix Browserbase: send explicit JSON body + Content-Type header
- Increase CDP connect timeout to 25s for remote providers
- Clean up .provider files on session close

Dashboard changes:
- Show provider or engine icon per session in sidebar
- New session dialog with unified engine/provider selector grid
- Async session creation with loading state and error display
- Kill zombie daemons on provider connection failure
- Parse CLI JSON error output for user-friendly messages
- Default new session URL to https://agent-browser.dev
2026-03-30 18:35:12 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> f8bc8b368a chore: version packages (#1090)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-30 13:32:26 -05:00
Chris Tate fbcab375b0 chore: prepare v0.23.1 release (#1089)
* chore: add patch changeset for v0.23.1 release

Add changeset covering 7 commits since v0.23.0: auto-dialog dismissal,
Puppeteer cache fallback, console output improvements, same-document
navigation fix, cross-domain save_state, external tab detection in CDP
mode, and dashboard hot-reload.

Fill documentation gaps: Puppeteer/Brave in browser discovery tables,
console --json args field, AGENT_BROWSER_NO_AUTO_DIALOG env var in
SKILL.md.

* chore: point package.json homepage to agent-browser.dev
2026-03-30 13:12:07 -05:00
Chris Tate 8d78fcbbb3 fix: Windows Chrome extraction and debugging environment (#1088)
* windows debugging

* fixes

* fixes

* fix: handle Windows path separators in Chrome zip extraction

The zip crate's enclosed_name() normalizes paths to use backslashes on
Windows, but extract_zip used split_once('/') which only matches forward
slashes. This caused Chrome to be extracted into a nested chrome-win64/
subdirectory instead of directly into the version directory.

Also adds debug diagnostics to find_installed_chrome() (gated behind
AGENT_BROWSER_DEBUG) and better error messages when Chrome cache exists
but no binary is found.

Fixes #1076

* feat: add Puppeteer browser cache as Chrome fallback

Search ~/.cache/puppeteer/chrome/ (or PUPPETEER_CACHE_DIR) for Chrome
binaries before falling back to Playwright's cache. Puppeteer v19+
stores Chrome for Testing in this location, so users with an existing
Puppeteer install can use agent-browser without a separate install step.

* fmt
2026-03-30 12:37:01 -05:00
hechang27-sprtandClaude Opus 4.6 312db04e5e fix: skip wait_for_lifecycle on same-document navigation (#1059)
Chrome returns loader_id: None for same-document navigations (e.g., hash
routing in SPAs). In these cases, Page.loadEventFired never fires, causing
wait_for_lifecycle to hang forever.

The fix checks nav_result.loader_id.is_some() before waiting for lifecycle
events. Also added regression test e2e_navigate_same_url_twice_should_not_hang.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-29 12:25:37 -06:00
jin.2andhyunjinee 369f48752a fix: expose raw CDP args in console output and use preview for formatting (#1040)
Closes #1039

- Add `preview` field to `RemoteObject` to capture CDP object previews
- Implement `format_console_arg` using preview data (value → preview → description)
- Store raw CDP args in `ConsoleEntry` and include in JSON output
- Skip typed `ConsoleApiCalledEvent` deserialization in favor of direct param extraction
- Unify console arg formatting between daemon (actions.rs) and stream (stream.rs)

Before: `console.log({userId: "abc", count: 42})` → `"Object"`
After:  `console.log({userId: "abc", count: 42})` → `{userId: "abc", count: 42}`

JSON output now includes raw `args` array for programmatic access by AI agents.

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-03-29 12:24:27 -06:00
Chris Tateandctate 6dd53449e8 Add auto-dismissal for alert and beforeunload dialogs (#1075)
* Add auto-dismissal for alert and beforeunload dialogs

This PR adds automatic handling of JavaScript dialogs to prevent the agent from blocking indefinitely when `alert()` or `beforeunload` dialogs appear on web pages.

## Summary

Previously, when a website displayed native browser confirmation dialogs (like alerts or "Are you sure you want to leave?" prompts), agent-browser would hang waiting for manual intervention. This is a common issue since many websites use these dialogs for notifications or navigation warnings.

## Changes Made

- **Auto-dismiss functionality**: Added a background task that automatically accepts `alert` and `beforeunload` dialogs while leaving `confirm` and `prompt` dialogs for explicit handling
- **New flag**: Added `--no-auto-dialog` flag to disable automatic handling when needed
- **Environment variable**: Added `AGENT_BROWSER_NO_AUTO_DIALOG` for configuration
- **Documentation**: Updated README and docs with usage examples and configuration details
- **Tests**: Added comprehensive test coverage for flag parsing and dialog handling logic

## Implementation Details

- Only `alert` (notification-only) and `beforeunload` (navigation warning) dialogs are auto-handled for safety
- `confirm` and `prompt` dialogs still require explicit `dialog accept/dismiss` commands to ensure agents make deliberate choices for destructive actions
- The feature is enabled by default since these dialog types rarely require user decision-making
- Uses Chrome DevTools Protocol's `Page.handleJavaScriptDialog` for reliable dialog dismissal

Fixes #1070

* Log dialog type and message before auto-dismissal

Without this, auto-dismissed alert/beforeunload dialogs are silently
swallowed and the agent has no way to see what the dialog said. Adding
an eprintln before the CDP call makes the dismissal visible in stderr
for debugging.

* Log dialog dismissal errors instead of silently discarding them

- Remove premature "accepted" from log message since it fires before
  the CDP command executes
- Replace `let _ =` with `if let Err(e)` to log failures when
  Page.handleJavaScriptDialog fails
- Apply rustfmt to auto-dialog tests

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-29 12:00:27 -06:00
Chris Tateandctate da7fef3fef fix: dashboard server picks up installed files without restart (#1066)
The dashboard HTTP server checked for index.html once at startup and
cached the result. If the server started before `dashboard install`,
it permanently served the "not installed" fallback page.

Check for installed dashboard files on each request instead, so
`dashboard install` takes effect immediately on a running server.

Fixes #1065

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-29 11:54:06 -06:00
jin.2andhyunjinee 43d9c40bc4 fix: detect externally opened tabs in --cdp mode (#1042)
* fix: detect externally opened tabs in --cdp mode (#1037)

Tabs opened outside of agent-browser (e.g. by the user or another CDP
client) were invisible to `tab list` because:

1. `Target.targetCreated` with chrome://newtab/ was filtered by
   `is_internal_chrome_target`, and the subsequent `targetInfoChanged`
   with the real URL could not update a target that was never tracked.

2. The background drain loop only ran when `request_tracking ||
   har_recording` was active, so target events between commands were
   silently dropped from the broadcast channel.

Fix: promote untracked targets in `targetInfoChanged` to new targets,
run the background drain unconditionally (guarded by browser presence),
and extract `apply_drained_events` to share target lifecycle processing
(attach, domain filter, iframe sessions) between execute_command and
the background drain.

* refactor: clean up HashSet import and remove call-site duplication

- Import HashSet alongside HashMap instead of using fully-qualified path
- Replace duplicated drain+apply sequence in execute_command with
  drain_cdp_events_background call

* style: apply cargo fmt

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-03-29 11:51:49 -06:00
jin.2andhyunjinee dc26ff7667 fix: save_state captures cross-domain cookies and localStorage (#1064)
The Rust rewrite of save_state only captured cookies and localStorage
for the current page's origin, silently dropping cross-domain data
(e.g. SSO/CAS auth cookies). This was a regression from the JS version.

Cookies: replace Network.getCookies with Network.getAllCookies to
return cookies from all domains the browser has visited.

localStorage: track visited origins in BrowserManager during navigation,
then collect their localStorage via a temporary CDP target with Fetch
interception (serves blank HTML to avoid real network requests).

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-03-28 13:41:53 -07:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 747a3772e1 chore: version packages (#1054)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-27 10:30:33 -07:00
Chris Tate bbad2de627 fix: include root package in pnpm workspace for changesets (#1053)
The dashboard PR introduced pnpm-workspace.yaml but only listed
packages/* and docs. Changesets could no longer find the root
agent-browser package, breaking the release CI. Adding '.' makes
the root a workspace package again.
2026-03-27 10:17:48 -07:00
Chris Tate 0f0f300d40 chore: add minor changeset for v0.23.0 release (#1052) 2026-03-27 09:46:17 -07:00
Chris Tate db215a1467 fix lightpanda (#1050)
* fix lightpanda

* fmt
2026-03-27 09:33:08 -07:00
Chris Tateandctate a95bc0f75a fix(windows): fall back to OS-assigned port when Hyper-V blocks daemon TCP bind (#1041)
On Windows the daemon derives a TCP port from the session name via a
djb2 hash (e.g. "default" → 50838). On many machines this port falls
inside Hyper-V's excluded port range (winnat), causing EACCES on bind
and preventing the daemon from starting.

Changes:
- daemon: try the hash-derived port first; on failure, bind to port 0
  (OS-assigned) and write the actual port to the .port file
- client (connection.rs, stream.rs): read the .port file to discover the
  daemon's actual port, falling back to the hash if the file is absent
- run_daemon: guard .sock file operations with #[cfg(unix)] and add
  .port file cleanup for #[cfg(windows)]

Fixes #390

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-26 21:01:06 -07:00
Chris Tate 995a47fdb0 fix: use TCP instead of Unix socket on Windows in dashboard relay (#1038)
`relay_command_to_daemon` in stream.rs used `tokio::net::UnixStream`
unconditionally, which doesn't compile on Windows. Add platform-
conditional code matching the existing pattern in daemon.rs and
connection.rs: Unix sockets on unix, TCP on Windows.
2026-03-26 13:36:22 -07:00
Chris Tatectategithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>Stefan SmiljkoviczhanbaxuyongliangxuyongliangThomas Kosiewski
f9174513c2 dashboard (#1034)
* dashboard

* fix: re-apply download behavior on recording context (#1019)

* fix: re-apply download behavior on recording context

record start creates a new browser context via Target.createBrowserContext.
Browser.setDownloadBehavior called at launch only applies to the default
context, so downloads in the recording context are silently dropped.

Fix:
1. Store download_path on BrowserManager (from LaunchOptions)
2. After creating the recording context, call Browser.setDownloadBehavior
   with the new browserContextId

This ensures downloads work during recording.

Fixes #1018

* fix: add download_path to third BrowserManager constructor (auto_connect_cdp)

* fix: reap zombie Chrome process and fast-detect crash for auto-restart (#1023)

When Chrome crashes (e.g. SIGTRAP from CHECK() assertion), the daemon
now:

1. Reaps the zombie immediately via a SIGCHLD handler in the event loop
   that calls waitpid(-1, WNOHANG)
2. Detects the crash instantly on the next command via a non-blocking
   try_wait() check (has_process_exited), avoiding the 3-second CDP
   timeout that is_connection_alive() would incur
3. Auto-relaunches Chrome transparently for the caller

Fixes #1017

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>

* fix: route keyboard type through text input (#1014)

* fix: handle --clear flag in console command (#1015)

The console and errors commands parsed --clear from CLI args but the
action handlers silently ignored the flag. The handlers did not accept
the cmd parameter so they had no way to read the clear field.

Changes:
- Add clear_console() method to EventTracker in network.rs
- Update handle_console to accept cmd, read the clear field, and clear
  the buffer when --clear is passed (returns {cleared: true})
- Update call site in execute_command to pass cmd

Co-authored-by: xuyongliang <yongliang.xyl@alibaba-inc.com>

* chore: patch release - ### Bug Fixes

- **Re-apply download behavior on r... (#1025)

* Add runtime stream enable/disable/status commands (#951)

* Add runtime stream management commands

* Run rustfmt and satisfy clippy

* Fix stream disable cleanup semantics

* Format stream disable regression tests

* fix: retain radio/checkbox elements in compact snapshot tree (#1008)

compact_tree() checked for "[ref=" to identify lines worth keeping, but
radio and checkbox elements render as e.g. [checked=false, ref=e1] where
the "[" opens before "checked=", not "ref=". Dropping the leading bracket
so the check is just "ref=" fixes the match for all elements with refs.

Fixes #1006

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>

* chore: version packages (#1027)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fixes

* dashboard

* fixes

* remove observe

* fmt

* fixes

* fixes

* jotai

* fmt

* upload dashboard

---------

Co-authored-by: Stefan Smiljkovic <stefan@vanila.io>
Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
Co-authored-by: zhanba <c5e1856@gmail.com>
Co-authored-by: xuyongliang <478439790@qq.com>
Co-authored-by: xuyongliang <yongliang.xyl@alibaba-inc.com>
Co-authored-by: Thomas Kosiewski <thoma471@googlemail.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-26 08:43:35 -07:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 63f03b8e06 chore: version packages (#1029)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-25 18:24:47 -07:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 699a461646 chore: version packages (#1027)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-25 11:48:46 -07:00
Chris Tateandctate 89a8ceccf7 fix: retain radio/checkbox elements in compact snapshot tree (#1008)
compact_tree() checked for "[ref=" to identify lines worth keeping, but
radio and checkbox elements render as e.g. [checked=false, ref=e1] where
the "[" opens before "checked=", not "ref=". Dropping the leading bracket
so the check is just "ref=" fixes the match for all elements with refs.

Fixes #1006

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-25 11:40:19 -07:00
Thomas Kosiewski 67b5ee1600 Add runtime stream enable/disable/status commands (#951)
* Add runtime stream management commands

* Run rustfmt and satisfy clippy

* Fix stream disable cleanup semantics

* Format stream disable regression tests
2026-03-25 11:36:16 -07:00
Chris Tate eb64ca497a chore: patch release - ### Bug Fixes
- **Re-apply download behavior on r... (#1025)
2026-03-25 11:29:51 -07:00
xuyongliangandxuyongliang 8c6fc35450 fix: handle --clear flag in console command (#1015)
The console and errors commands parsed --clear from CLI args but the
action handlers silently ignored the flag. The handlers did not accept
the cmd parameter so they had no way to read the clear field.

Changes:
- Add clear_console() method to EventTracker in network.rs
- Update handle_console to accept cmd, read the clear field, and clear
  the buffer when --clear is passed (returns {cleared: true})
- Update call site in execute_command to pass cmd

Co-authored-by: xuyongliang <yongliang.xyl@alibaba-inc.com>
2026-03-25 08:27:28 -07:00
zhanba 7d2cd726ec fix: route keyboard type through text input (#1014) 2026-03-25 08:05:20 -07:00
Chris Tateandctate 5ac01fa743 fix: reap zombie Chrome process and fast-detect crash for auto-restart (#1023)
When Chrome crashes (e.g. SIGTRAP from CHECK() assertion), the daemon
now:

1. Reaps the zombie immediately via a SIGCHLD handler in the event loop
   that calls waitpid(-1, WNOHANG)
2. Detects the crash instantly on the next command via a non-blocking
   try_wait() check (has_process_exited), avoiding the 3-second CDP
   timeout that is_connection_alive() would incur
3. Auto-relaunches Chrome transparently for the caller

Fixes #1017

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-25 08:04:43 -07:00
Stefan Smiljkovic 2fb766fc78 fix: re-apply download behavior on recording context (#1019)
* fix: re-apply download behavior on recording context

record start creates a new browser context via Target.createBrowserContext.
Browser.setDownloadBehavior called at launch only applies to the default
context, so downloads in the recording context are silently dropped.

Fix:
1. Store download_path on BrowserManager (from LaunchOptions)
2. After creating the recording context, call Browser.setDownloadBehavior
   with the new browserContextId

This ensures downloads work during recording.

Fixes #1018

* fix: add download_path to third BrowserManager constructor (auto_connect_cdp)
2026-03-25 07:52:58 -07:00
Chris Tateandgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 0865851293 chore: version packages (#1009)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-24 15:21:31 -07:00
Chris Tate a0981979ca chore: patch release - ### New Features
- **Dialog status command** - Ad... (#1005)
2026-03-24 15:03:10 -05:00
Chris Tateandctate cd1f255129 fix: handle proxy authentication via CDP Fetch.authRequired (#1000)
* fix: handle proxy authentication via CDP Fetch.authRequired

Chrome's --proxy-server flag does not support credentials embedded in
the URL. When a proxy requires authentication, Chrome receives a 407
from the proxy but has no way to respond with credentials, resulting
in net::ERR_INVALID_AUTH_CREDENTIALS.

Fix by:
1. Parsing credentials from the proxy URL (already done by parse_proxy)
2. Storing them in DaemonState.proxy_credentials
3. Enabling Fetch.enable with handleAuthRequests: true
4. Responding to Fetch.authRequired events with Fetch.continueWithAuth
5. Passing only the server URL (without credentials) to --proxy-server
6. Forwarding credentials to the daemon via dedicated env vars

Also adds fallback to standard proxy env vars (HTTP_PROXY, HTTPS_PROXY,
ALL_PROXY, NO_PROXY) when AGENT_BROWSER_PROXY is not set.

Fixes #990

* refactor: use typed struct for parse_proxy, fix double Fetch.enable and username-only auth

- Replace serde_json::Value return from parse_proxy with a typed ParsedProxy struct
- Fix double Fetch.enable call when both proxy auth and domain filter are active
  (the second call could overwrite handleAuthRequests from the first)
- Allow username-only proxy auth (some proxies don't require a password)
- Handle empty username/password in parse_proxy as None instead of Some("")
- Use install_domain_filter_fetch in auto_launch for consistency
- Update unit tests to use typed struct fields

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-24 12:52:39 -05:00
Chris Tateandctate 23a117c5c2 fix: add font packages to install --with-deps for CJK and emoji support (#1002)
The `--with-deps` flag installed font rendering libraries (libfreetype6,
libfontconfig1) but no actual font files, causing CJK characters and
emoji to render as invisible/tofu on headless Linux systems.

Add font file packages for all three supported package managers:
- apt: fonts-noto-color-emoji, fonts-noto-cjk, fonts-freefont-ttf
- dnf: google-noto-cjk-fonts, google-noto-emoji-color-fonts, liberation-fonts
- yum: google-noto-cjk-fonts, liberation-fonts

Closes #1001

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-24 12:03:21 -05:00
Chris Tateandctate 32ffd8f3c4 feat: add dialog detection and document dialog commands (#999)
Fixes #992

When a JavaScript dialog (alert/confirm/prompt) blocks the page, agents
had no way to detect it — all commands just timed out with generic errors.

- Add `dialog status` command to check for pending dialogs
- Track dialog state via CDP Page.javascriptDialogOpening/Closed events
- Auto-inject `warning` field into all command responses when a dialog is
  pending, so agents can distinguish dialog-blocked timeouts from other issues
- Document dialog commands in SKILL.md (was missing entirely), README.md,
  docs site, and --help output

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-24 11:38:23 -05:00
Chris Tateandctate 780edb2c45 fix: download drops Browser-domain CDP events due to sessionId mismatch (#998)
Chrome's Browser.downloadWillBegin and Browser.downloadProgress events
may arrive without a sessionId or with a different sessionId than the
page session used to configure the download behavior. The previous code
required an exact session match, silently dropping these events and
causing the 30-second timeout -- which manifests as an endless download
loop when callers retry.

Changes:
- Accept Browser-domain download events regardless of sessionId while
  still matching Page-domain events by session to avoid cross-tab issues
- Add a brief retry loop (up to 1s) for the GUID file to appear on disk
  after Chrome signals completion, handling filesystem flush races
- Return a proper error instead of silently succeeding when the
  GUID-named file cannot be found
- Apply the same sessionId fix to handle_waitfordownload and add
  Browser.downloadProgress support (previously only checked
  Page.downloadProgress)

Fixes #989

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-24 11:35:49 -05:00
xuyongliangandxuyongliang 3150acd574 fix: console command returns only Done due to JSON field name mismatch (#986)
The get_console_json() method produced JSON with key 'entries' containing
objects with 'level' field, but the output formatter in output.rs expected
key 'messages' with 'type' field. This mismatch caused console output to
fall through all format checks and print only '[Done]'.

Changed get_console_json() to use 'messages' and 'type' to match the
output formatter expectations.

Co-authored-by: xuyongliang <yongliang.xyl@alibaba-inc.com>
2026-03-24 10:28:06 -05:00
volarecopilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>wanghanzhen
b5b84051e4 fix: state show always fails with "Missing 'path' parameter" (#994)
Agent-Logs-Url: https://github.com/wanghanzhen/agent-browser/sessions/a0ee212c-9d4f-4b9c-906e-7a2d8fa8df4a

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: wanghanzhen <25301012+wanghanzhen@users.noreply.github.com>
2026-03-24 10:19:46 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 859c8aaf94 chore: version packages (#987)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-24 07:56:53 -05:00
Chris Tate 3a3317b048 chore: patch release - ### Bug Fixes
- Fixed **modifier key chords** (e.... (#985)
2026-03-23 20:30:53 -05:00
Chris Tateandctate f806b666ba fix: preserve query parameters in --cdp HTTP URLs (#982)
When --cdp is given an HTTP/HTTPS URL (e.g. http://host:5095?mode=Hello),
resolve_cdp_url extracts host and port for CDP discovery but discards the
query string. The discovered WebSocket URL therefore never includes the
user's original query parameters, breaking relay servers that depend on
them.

Thread the original query string through discover_cdp_url and append it
to the final WebSocket URL after host/port rewriting. WebSocket URLs
(ws://, wss://) are already passed through unchanged and are unaffected.

Fixes #977

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-23 18:47:23 -05:00
Chris Tateandctate a7a59c94f3 Fix press Control+a and other modifier key chords (#980)
The `press` command was not parsing modifier+key chords (e.g.
`Control+a`, `Shift+Enter`). It sent the raw string as a single key
name, so CDP never applied the modifier — and the `text` field caused
the literal character to be inserted instead of triggering the shortcut.

Two changes:
1. `actions.rs` — add `parse_key_chord()` to split inputs like
   `Control+Shift+a` into the base key (`a`) and a CDP modifier
   bitmask (Alt=1, Ctrl=2, Meta=4, Shift=8), then call
   `press_key_with_modifiers` instead of `press_key`.
2. `interaction.rs` — suppress the `text` field in `keyDown`/`keyUp`
   events when Control or Meta modifiers are active, so the browser
   treats them as command chords rather than text input.

Includes unit tests for the chord parser covering plain keys, single
modifiers, multi-modifier combos, modifier aliases, and edge cases.

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-23 16:43:43 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> ce1f1f5f81 chore: version packages (#975)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-23 12:21:00 -05:00
Chris Tate be30bc902d chore: add minor changeset for release (#973) 2026-03-23 12:07:07 -05:00
Chris Tateandctate 1391f00404 Fix download command to properly handle absolute paths and click elements (#970)
* Fix download command to properly handle absolute paths and click elements

The download command was not working correctly - it would return "done" but not actually download files to the specified path. The command was only setting download behavior without clicking the element or waiting for completion.

**Changes made:**
- Modified `handle_download` to take a `selector` parameter and click the download element
- Added proper absolute path resolution and directory creation
- Implemented CDP event listening to wait for download completion with 30s timeout
- Added file renaming logic to handle Chrome's GUID-based temporary filenames
- Changed response format to return the actual download path
- Fixed function signature to use `&mut DaemonState` for state modifications

**Implementation details:**
- Uses `Browser.downloadWillBegin` and `Browser.downloadProgress` CDP events to track downloads
- Falls back to finding the most recently modified file if GUID capture fails
- Creates parent directories automatically if they don't exist
- Handles both absolute and relative path inputs

Fixes #965

* Address review feedback: harden download path handling

- Canonicalize download directory to prevent path traversal attacks
- Remove dangerous fallback that renamed the most-recently-modified file
  in the directory (could silently rename unrelated files)
- Extract timeout to a named constant (DOWNLOAD_TIMEOUT)

* Fix download event loop: handle canceled state and Page.downloadWillBegin

- Detect "canceled" download state and return an error immediately instead
  of spinning until the 30s timeout.
- Also capture the download GUID from the deprecated Page.downloadWillBegin
  event for older Chrome compatibility, matching the existing
  Page.downloadProgress fallback.
- Consolidate duplicated session/event checks with a shared is_this_session
  variable and use match for cleaner state handling.

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-23 11:09:41 -05:00
Chris Tate c5020f2b89 Fix Enter key press not working by adding text field to keyDown events (#972)
This PR fixes an issue where pressing the Enter key via the `press Enter` command had no effect on web pages, even though the command executed successfully without errors.

## Problem
The Chrome DevTools Protocol `Input.dispatchKeyEvent` requires a `text` field in `keyDown` events for certain keys to trigger their default browser actions. Without this field, keys like Enter don't actually submit forms or perform their expected actions.

## Changes
- Added new `key_text()` function that returns the appropriate text value for special keys:
  - Enter returns `"\r"` (carriage return)
  - Tab returns `"\t"` (tab character)
  - Space returns `" "` (space character)
  - Single printable characters return themselves
  - Non-printable keys (Escape, Arrow keys, etc.) return `None`
- Modified `press_key_with_modifiers()` to populate both `text` and `unmodified_text` fields in the CDP keyDown event
- Added comprehensive unit tests for the new functionality

## Implementation Details
The fix ensures that when pressing Enter on a filled search box, the form actually submits as expected, matching the behavior of manually pressing the Enter key.

Fixes #966
2026-03-23 10:46:05 -05:00
Chris Tate 9b1961af93 fix: skip auto-connect when daemon already running to prevent multiple (#971)
Previously, the `--auto-connect` flag would send connection commands to the daemon on every CLI invocation, even when the daemon was already running and maintaining an active connection. This caused Chrome to repeatedly prompt for remote debugging permissions during long-running tasks.

This fix adds checks for `daemon_result.already_running` to skip sending launch commands when the daemon is already active and holding connections. The changes apply to:

- Auto-connect flow: Skip when daemon already running since it holds the connection from previous launch
- CDP connections: Skip sending commands but validate input eagerly for immediate error feedback
- Cloud provider connections: Skip when daemon already maintains the provider connection

This preserves the existing connection reuse logic in the daemon while preventing redundant connection attempts from the CLI side.

Fixes #962
2026-03-23 10:27:54 -05:00
ChunHao Chen ceaee00952 feat: add network request detail and filtering for request tracking (#935)
* feat: add network request detail and filtering for request tracking

- Add `network request <requestId>` command to view full request/response
  details including response body via CDP Network.getResponseBody
- Add --type, --method, --status filter flags to `network requests`
  - --type: comma-separated resource types (xhr,fetch,document)
  - --method: filter by HTTP method
  - --status: supports exact (200), class (2xx), range (400-499)
- Extend TrackedRequest with request_id, post_data, status,
  response_headers, mime_type fields
- Update Network.responseReceived handler to also populate
  tracked_requests (previously only updated HAR entries)
- Add tests for parse commands and matches_status_filter
- Update README, SKILL.md, docs, and help text

Closes #932

* fix: show request ID and status in network requests output
2026-03-23 10:17:17 -05:00
GyDi 5c5c0d8081 fix: enhance target tracking and update page information handling (#969) 2026-03-23 09:38:20 -05:00
Lppyand羲洋 b48c3e9dd2 feat: enhance snapshot usability by reducing AI cognitive load of semantic noise and -C flag (#968)
* fix: add ref for cursor-interactive content roles

* fix: format

* feat: always include cursor-interactive elements in snapshot, -C is deprecated

* feat: process StaticText aggregation and deduplication

* update test

* clean up

* fix: escape text of elements in snapshot

* fix: redundant slicing

* fix: cargo fmt

* feat: deduplicate redundant StaticText

---------

Co-authored-by: 羲洋 <lipengyang.lpy@alibaba-inc.com>
2026-03-23 09:35:43 -05:00
9c0955ca99 fix: prevent state commands from starting daemon without session_name (#677) (#964)
* fix: prevent state commands from starting daemon without session_name
   (#677)

  State management commands (state_list, state_show, state_clear,
  state_clean, state_rename) are pure file operations that don't need a
  running daemon. Previously, these commands would trigger daemon
  startup
  via ensure_daemon(), and if AGENT_BROWSER_SESSION_NAME was exported
  after the first command (e.g. `state clear --all`), the daemon would
  start without session_name. Subsequent open/close commands would
  reuse
  that daemon, causing close to skip state persistence entirely.

  Fix: execute state management commands locally in the CLI process
  before
  ensure_daemon() is called. This is done via a new
  dispatch_state_command() function in state.rs that centralizes the
  command routing, used by both the CLI (local path) and the daemon
  (batch/IPC path).

  Also:
  - Add OutputOptions::from_flags() helper to deduplicate construction
  - Add unit tests for dispatch_state_command routing and error
  handling

* style: fix fmt and clippy warnings

- Remove redundant closure in dispatch_state_command (clippy::redundant_closure)
- Remove needless borrow in run_batch (clippy::needless_borrow)
- Fix trailing blank lines (rustfmt)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 08:32:14 -05:00
d374e413be chore: remove dead code and unused variables in actions.rs (#961)
* chore: remove dead code and unused variables in actions.rs

Remove `daemon_state_from_env` (superseded by `DaemonState::new`) and
`resolve_semantic_locator` (superseded by `handle_semantic_locator`),
both of which had zero call sites. Also remove unused `_session_id`
bindings in `handle_find` and `handle_multiselect`, and a no-op
`let _ = sid` in `handle_getbyrole`.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: simplify `_sid` to `_` per review feedback

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: use `is_ok()` instead of `if let Ok(_)` for idiomatic Rust

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 01:01:56 -05:00
Chris Tateandctate fb1e860b4e Improve upgrade command installation method detection robustness (#960)
* Improve upgrade command installation method detection robustness

The upgrade command was failing to detect installation method for users who installed via pnpm, yarn, or bun, showing "Could not detect installation method" errors.

## Changes Made

- **Added support for additional package managers**: Extended detection to include pnpm, yarn, and bun alongside existing npm, Homebrew, and Cargo support
- **Implemented install-time marker system**: Modified `postinstall.js` to write a `.install-method` marker file during installation, providing reliable detection that doesn't depend on fragile path heuristics
- **Enhanced path-based fallback detection**: Improved executable path analysis to better identify installation locations for all supported package managers
- **Added command probing**: Implemented fallback checks that query package managers directly to verify global installations

The detection now follows this robust hierarchy:
1. Read install-time marker file (most reliable)
2. Analyze executable path patterns
3. Probe package managers via subprocess calls

This ensures users can successfully upgrade regardless of their chosen package manager.

Fixes #954

* Add .install-method to .gitignore and note Yarn v2+ limitation

- Prevent bin/.install-method marker file from being accidentally
  committed during development
- Add comment clarifying that yarn global upgrade path only works
  with Yarn Classic (v1), not Yarn Berry (v2+)

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-22 09:51:58 -05:00
PapacyDai 84c6e6fd30 fix: prevent find flags from leaking into fill value (#955) 2026-03-21 11:24:31 -05:00
Chris Tate 7e5baa6d77 Fix viewport dimensions in streaming status messages and screencast (#952)
## Summary
Fixed an issue where custom viewport settings were ignored in WebSocket streaming, causing status messages to always report hardcoded dimensions (1280x720) instead of the actual viewport size.

## Changes Made
- **Added viewport tracking to StreamServer**: New `viewport_width` and `viewport_height` fields to store current dimensions
- **Updated viewport synchronization**: Modified `handle_viewport()` and `handle_device()` to update the stream server when viewport changes
- **Fixed status message broadcasting**: Replaced hardcoded dimensions with actual viewport values in `broadcast_status()` calls
- **Improved screencast defaults**: Changed screencast to use stored viewport dimensions as defaults instead of hardcoded 1280x720
- **Added viewport getter methods**: New `set_viewport()` and `viewport()` methods on StreamServer for dimension management

This ensures that WebSocket clients receive consistent viewport dimensions across all message types (status and frame messages), matching the actual browser viewport settings.

Fixes #950
2026-03-20 19:16:39 -05:00
jin.2andhyunjinee 59b6e5a034 feat: support cross-origin iframe snapshots and interactions via Target.setAutoAttach (#949)
* feat: support cross-origin iframe snapshots and interactions via Target.setAutoAttach (#925)

Enable Target.setAutoAttach with flatten: true on page sessions so Chrome
auto-creates dedicated CDP sessions for cross-origin iframe targets.

- Add DrainedEvents struct, iframe_sessions map, attach/detach event handling
- Extract resolve_ax_session (shared) and resolve_frame_session helpers
- resolve_element_object_id returns (object_id, effective_session) tuple
- resolve_element_center returns (x, y, effective_session) tuple
- Input dispatch (click/hover/tap) uses effective session for correct coordinates
- Thread iframe_sessions through element.rs, interaction.rs, screenshot.rs
- Clear iframe sessions on navigate, tab switch, tab new, tab close
- Ignore Target.setAutoAttach failure for non-Chrome backends (Lightpanda)
- Unit tests for session resolution logic

* fix

* fix

* fix

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-03-20 16:37:33 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 39e54113e6 chore: version packages (#948)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-20 09:13:13 -05:00
Kevin Kipp aed466b347 fix: make auth login selector targeting more reliable (#945)
Navigate with load, then wait for username/password/submit selectors using the default action timeout. This avoids networkidle hangs on pages with continuous background requests.
2026-03-20 09:01:00 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 8d14ecb92b chore: version packages (#947)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-20 08:53:47 -05:00
Chris Tate 6daad22ada chore: patch release - ### Bug Fixes
- **WebSocket keepalive for remote ... (#946)
2026-03-20 08:36:04 -05:00
9837b9c1aa perf: fast-path identical snapshots in diff_snapshots (#922)
* Update agent-browser optimization plan: PR #916 submitted, Phase 2 complete

Co-authored-by: Hermes <agent@hermes.ai>

* perf(snapshot-diff): fast-path identical snapshots

Co-authored-by: Hermes <agent@hermes.ai>

* chore(pr): remove unrelated docs from snapshot-diff fast-path

---------

Co-authored-by: Merlin <merlin@rbeckner.com>
Co-authored-by: Hermes <agent@hermes.ai>
2026-03-19 20:02:43 -05:00
jin.2andhyunjinee af800f8403 fix: support xpath= selector prefix in element resolution (#908)
* fix: support xpath= selector prefix in element resolution

Resolves #907. When a selector starts with "xpath=", use
document.evaluate() instead of document.querySelector() so that
XPath expressions like "xpath=//button" work correctly.

* test: replace overlapping test with edge case tests

Replace test_build_selector_js_xpath_strips_prefix (which overlapped
with the xpath test) with two edge case tests: empty xpath and
selector starting with "xpath" without "=" delimiter.

* fix: support xpath= selector in resolve_element_object_id

Apply the same xpath= handling to resolve_element_object_id, which is
used by type, fill, focus, hover, check, select, screenshot, drag,
and all other selector-based commands beyond basic click.

* refactor: extract build_find_element_js to deduplicate xpath/css logic

The xpath= vs querySelector branching was duplicated in both
build_selector_js and resolve_element_object_id. Extract the shared
logic into build_find_element_js and reuse it in both places.

* fix: support xpath= selector in get_element_count

Use ORDERED_NODE_SNAPSHOT_TYPE with snapshotLength for XPath counting,
matching the querySelectorAll().length behavior for CSS selectors.

* refactor: rename find to find_expr for clarity

* refactor: extract build_count_elements_js and add regression tests

Extract element counting JS generation into build_count_elements_js
helper (matching the pattern of build_find_element_js) and add tests
for both CSS and XPath counting paths.

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-03-19 19:27:03 -05:00
Chris Tateandctate 421f8fab82 fix: add WebSocket keepalive to prevent CDP connection drops on remote browsers (#936)
The v0.20.0 Rust rewrite dropped two keepalive mechanisms that the
Node.js/Playwright daemon provided, causing CDP connections to remote
Browserless instances to silently die between commands when traversing
multi-hop proxy topologies (Istio Envoy, OpenResty, etc.).

Restore parity with v0.19.0 and improve on it:

1. TCP SO_KEEPALIVE (v0.19.0 parity): Playwright's WebSocketTransport
   used HTTP agents with keepAlive: true, which set SO_KEEPALIVE on the
   underlying TCP socket. Restored via socket2::SockRef on the
   tokio_tungstenite stream before splitting.

2. WebSocket Ping frames (improvement): Send Ping frames every 30s on
   idle connections. This goes beyond v0.19.0 because L7 proxies (Envoy,
   nginx, OpenResty) can see WebSocket pings but not TCP keepalive
   probes, making this effective through application-layer proxy hops.

The keepalive task is coordinated with the reader loop via a watch
channel and stops automatically when the connection closes.

Fixes #934

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-19 19:12:57 -05:00
mikewong23571andClaude Opus 4.6 2b3c5c26cd docs: create providers/ section with dedicated provider pages (#928)
Add dedicated documentation pages for each cloud browser provider:
Browser Use, Browserbase, Browserless, and Kernel (sorted
alphabetically). Uses providers/ path per maintainer feedback.

- Fix Kernel defaults to match source code (KERNEL_HEADLESS=true,
  KERNEL_STEALTH=false) — README had these inverted
- Add Providers section to sidebar navigation
- Simplify cdp-mode cloud providers section to link to new pages

Fixes part of #774

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 02:40:33 -05:00
mikewong23571andClaude Opus 4.6 2d37967b7e docs: fix desktop browser list in iOS comparison table (#926)
The codebase only has CDP launchers for Chrome and Lightpanda
(cdp/chrome.rs, cdp/lightpanda.rs). Firefox and WebKit have no
launcher and are not supported.

Fixes part of #774

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 01:50:42 -05:00
Chris Tate 06b3b94493 colors + search for docs (#927)
* colors

* search
2026-03-19 01:50:19 -05:00
mikewong23571andClaude Opus 4.6 0749ad667e docs: migrate page metadata from MDX to layout.tsx (#904)
Move JS metadata exports out of page.mdx files into per-directory
layout.tsx files. MDX files now contain pure markdown content, making
them render cleanly on GitHub without visible JS import/export lines.

No content changes — only the metadata mechanism is relocated.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 01:25:17 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> fa563b59b9 chore: version packages (#920)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-18 19:54:32 -05:00
Chris Tate 757626f27c chore: add patch changeset for release (#919) 2026-03-18 17:02:34 -05:00
755fa50400 fix: handle relative URLs in Websocket domain filter script (#624)
* fix: handle relative URLs in domain filter WebSocket script

Pass location.href as base URL to the URL constructor so relative URLs
(e.g. "/path" or "//host/path") resolve correctly instead of throwing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Affirm-Skill: commit-and-push

* fix: apply domain filter review followups

Use location.href as base in native WebSocket handler to match
EventSource/sendBeacon, remove redundant comment, add test coverage.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-18 16:56:03 -05:00
fdc09c95f4 fix: restore origin-scoped --headers persistence across commands (#894)
* fix: restore origin-scoped --headers persistence across commands

In the v0.20 Rust rewrite, headers passed via --headers on open were
only applied to that single navigation via Network.setExtraHTTPHeaders,
which did not persist them for subsequent commands. In v0.19
(Playwright-based), these headers persisted for all subsequent
same-origin requests.

This restores the v0.19 behavior using CDP Fetch interception:

- A background task processes Fetch.requestPaused events in real-time,
  injecting origin-scoped headers into matching requests and continuing
  non-matching requests unmodified. This avoids the deadlock that occurs
  when Fetch interception pauses requests during Page.navigate or
  Runtime.evaluate (which block waiting for completion).

- The same background task also handles domain filtering and route
  interception, replacing the previous drain-between-commands approach
  that couldn't process events during navigation or script evaluation.

Fixes:
- --headers persist for same-origin navigations without re-passing flag
- --headers persist for in-page fetch/XHR to the same origin
- --headers do not leak to cross-origin navigations or sub-resources
- `set headers` (global) is unaffected and stacks with --headers
- Domain filter Fetch interception no longer deadlocks during navigation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* style: apply cargo fmt formatting

* revert inaccurate comment change

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-18 16:52:21 -05:00
Chris Tateandctate 486e1b341f Fix Chrome headless launch failures with --enable-unsafe-swiftshader (#915)
* Fix Chrome headless launch failures by adding --disable-gpu flag

Fixes silent Chrome crashes in headless mode when GPU drivers are unavailable or restricted (common in VMs, containers, and cloud environments).

## Changes Made

- **Auto-add `--disable-gpu` flag**: Automatically includes `--disable-gpu` when launching Chrome in headless mode to prevent GPU initialization crashes
- **Improved error reporting**: Enhanced error messages to include Chrome's exit code when it crashes before writing DevToolsActivePort
- **Better user guidance**: Added helpful hints in error messages suggesting `--no-sandbox` and `--disable-gpu` flags for troubleshooting
- **Updated tests**: Added test coverage for the new `--disable-gpu` flag behavior

## Implementation Details

The `--disable-gpu` flag is only added in headless mode (when `options.headless && !has_extensions`), preserving GPU acceleration for non-headless usage. The error handling now captures Chrome's exit code and provides actionable debugging information when Chrome fails silently.

Fixes #914

* Use --enable-unsafe-swiftshader instead of --disable-gpu for Playwright parity

--disable-gpu disables all GPU acceleration and breaks WebGL on Chrome 130+.
Playwright uses --enable-unsafe-swiftshader to enable CPU-based software
rendering via SwiftShader, which prevents GPU-driver crashes while preserving
WebGL support. This matches the behavior from v0.19 (Playwright-based daemon).

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-18 16:30:09 -05:00
Daniel VershininandDaniel Vershinin 5b5dffe0a2 Fix raw native mouse drag state across down/move/up (#872)
* Fix native mouse down/move/up state

* Allow clippy too_many_arguments for mouse helper

---------

Co-authored-by: Daniel Vershinin <d@sgml.me>
2026-03-18 13:29:33 -05:00
Lppyand羲洋 4be4605543 fix: dedup text content in snapshot (#909)
* fix: dedup text content in snapshot

* fix: format

---------

Co-authored-by: 羲洋 <lipengyang.lpy@alibaba-inc.com>
2026-03-18 10:59:56 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> d03f6431ea chore: version packages (#911)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-18 10:49:35 -05:00
Chris Tate 1e7619d59d chore: add patch changeset for release (#910) 2026-03-18 10:39:34 -05:00
Chris Tate 8cfba1752d feat: add built-in upgrade command for self-update (#898)
Adds a new `agent-browser upgrade` command that automatically detects the installation method (npm, Homebrew, or Cargo) and runs the appropriate update command.

**Changes:**
- Added new `upgrade.rs` module with upgrade logic
- Updated `main.rs` to handle the `upgrade` command
- Added upgrade help text in `output.rs`
- Updated README.md and documentation with upgrade instructions
- Updated SKILL.md to mention the upgrade command

**Implementation details:**
- Fetches latest version from npm registry to show version diff
- Auto-detects installation method by checking Homebrew, Cargo paths, and npm global packages
- Provides fallback instructions if installation method cannot be determined
- Uses existing color module for consistent styled output
- Gracefully handles network failures and continues with upgrade

Fixes #895
2026-03-17 23:29:07 -05:00
Cauê FelcharandClaude Sonnet 4.6 b8a5fc7101 feat: add HAR 1.2 network capture commands (#864)
* feat: enhance HAR entries with timings, cookies, postData, and protocol normalisation

Extends #874's HarEntry struct and CDP handlers with richer capture:

- wall_time (f64) replaces pre-formatted started_date_time, preserving
  sub-second precision from CDP wallTime for accurate RFC 3339 output
- request_headers / response_headers changed from Value to Vec<(String,String)>
  for typed access without re-parsing JSON objects
- post_data captured from Network.requestWillBeSent for HAR postData
- cdp_timing and loading_finished_timestamp captured from responseReceived
  and loadingFinished respectively, enabling har_compute_timings to produce
  accurate blocked/dns/connect/ssl/send/wait/receive phases
- har_cdp_protocol_to_http_version normalises CDP protocol strings
  (h2 -> HTTP/2.0, h3 -> HTTP/3.0, etc.)
- Request cookies parsed from Cookie header; response cookies from Set-Cookie
  with ';'-first split to correctly strip Path/HttpOnly attributes before '='
- har_wall_time_to_rfc3339 replaces har_started_date_time, using the time
  crate directly on the f64 epoch value

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: apply cargo fmt

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-17 15:27:27 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 8fc1d000f7 chore: version packages (#889)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-17 14:25:04 -05:00
Chris Tate c6de80b95e prepare v0.21 (#886) 2026-03-17 13:38:54 -05:00
Chris Tateandctate 1cd90078b4 fix: prevent system package removal during Ubuntu dependency install (#884)
* fix: prevent system package removal during Ubuntu dependency install

This PR fixes a critical issue where installing agent-browser dependencies on Ubuntu 24.04+ could trigger removal of hundreds of system packages due to library naming conflicts during the 64-bit time_t transition.

**Problem:**
On Ubuntu 24.04+, many core libraries were renamed with a "t64" suffix as part of the 64-bit time_t transition. The installer was trying to install old library names, causing apt to propose removing 400+ essential system packages to resolve conflicts.

**Changes:**
- Added comprehensive t64 variant detection for all apt dependencies
- Implemented pre-install simulation check to detect potential package removals
- Added safety abort mechanism when removals are detected (>0 packages)
- Enhanced error messaging to explain the issue and provide manual installation guidance
- Improved logging and user feedback during the installation process

**Implementation Details:**
- Uses `apt-get install --simulate` to safely check for conflicts before proceeding
- Checks for t64 variants first, falls back to original names if t64 versions don't exist
- Provides detailed output showing which packages would be removed
- Maintains compatibility with older Ubuntu versions that don't have t64 packages

Fixes #881

* refactor: extract duplicate install status handling into helper

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-17 11:32:07 -05:00
Mateusz Burzyński f8eb38c7f1 fix: use socket connectivity alone instead combining it with PID check for daemon liveness (#879) 2026-03-17 11:29:01 -05:00
Chris Tateandctate 60f3afcf61 Add iframe support for CLI interactions and snapshots (#869)
* Add iframe support for CLI interactions and snapshots

This PR adds comprehensive iframe support to the agent browser CLI, allowing users to interact with elements inside iframes seamlessly.

## Problem
Users couldn't interact with elements inside iframes via the command line. The existing `frame` command was non-functional as it set `active_frame_id` but no other code read this value.

## Changes Made

### Enhanced Frame Context Tracking
- Added `frame_id` field to `RefEntry` to track which frame each element reference belongs to
- Updated `RefMap::add` and related methods to accept and store frame context
- Modified element resolution functions to use frame context from ref entries

### Improved Frame Command
- Fixed the existing `frame` command to actually work by threading `active_frame_id` through snapshot operations
- Added support for iframe element references (e.g., `frame @e2`) in addition to CSS selectors
- Enhanced frame detection to work with both named frames and iframe elements

### Updated Snapshot Behavior
- Modified `take_snapshot` to accept optional frame context parameter
- Updated all snapshot call sites to pass appropriate frame context
- Maintained backward compatibility while enabling frame-scoped operations

### Element Resolution Updates
- Updated `resolve_element_center` and `resolve_element_object_id` to use frame context from ref entries
- Modified `find_node_id_by_role_name` to support frame-specific element lookup
- Ensured all interaction functions work correctly within iframe contexts

## Implementation Details
- Frame context is now properly propagated through the entire element interaction pipeline
- The `frame` command can accept both CSS selectors and element references
- All existing functionality remains intact while adding iframe capabilities
- Added `Iframe` to interactive roles for better element discovery

Fixes #863

* docs: add iframe support documentation

Document the new iframe capabilities across all documentation surfaces:
- Auto-inlining of iframe content in snapshots
- Direct interaction with iframe element refs
- frame command support for element refs (@e3)
- Scoped snapshots via frame switching

* fix: pass active frame context to diff snapshots and fix nameless iframe lookup

- handle_diff_snapshot now respects active_frame_id instead of always
  passing None, so diff snapshots work correctly inside iframes
- Nameless/id-less iframes now fall back to src URL (or null) instead of
  the literal string 'frame' which never matched any frame in the tree

* fix: resolve iframe frame ID via DOM.describeNode and reduce code duplication

- handle_frame: Use DOM.describeNode + contentDocument.frameId to resolve
  iframe frame IDs directly, fixing failures for nameless iframes that
  lack name/id/src attributes
- element.rs: Deduplicate add() by delegating to add_with_frame()
- snapshot.rs: Guard against out-of-bounds insert_str when iframe marker
  is on the last line without a trailing newline

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-17 10:51:17 -05:00
Chris Tateandctate f51e955d99 refactor: make --full/-f a command-level flag instead of global (#877)
* refactor: make --full/-f a command-level flag instead of global

Move --full/-f from global flags (parsed in flags.rs) to command-level
parsing in commands.rs, scoped to the three commands that actually use
it: `screenshot`, `diff screenshot`, and `diff url`.

This frees up `-f` for other commands (e.g. `--follow` on
`console`/`errors`, see #867) and better reflects that full-page
capture is not a global concern.

Changes:
- Remove `full` from Flags struct, Config struct, and global flag parsing
- Remove `--full`/`-f` from clean_args global boolean flags list
- Parse `--full`/`-f` inline in `screenshot` command handler
- Accept `-f` shorthand in `diff screenshot` and `diff url` (previously
  only `--full` was accepted at command level)
- Remove fallback from global `flags.full` in diff subcommands
- Update tests to pass --full as a command argument rather than a global flag

Fixes #876

* fix: remove stale AGENT_BROWSER_FULL env var from help and add -f shorthand tests

- Remove AGENT_BROWSER_FULL from help text in output.rs since the env
  var is no longer read after moving --full to command-level parsing
- Add test_screenshot_full_page_shorthand to verify screenshot -f works
- Add test_diff_screenshot_command_full_flag_shorthand to verify
  diff screenshot -f works

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-17 10:40:53 -05:00
jin.2andhyunjinee 59ea02cc8e feat: fall back to WebSocket when HTTP discovery fails (fixes #870) (#873)
* feat: fall back to ws://host:port/devtools/browser when HTTP discovery
  fails

  Chrome 136+ with UI-based remote debugging (chrome://inspect) exposes
  CDP over WebSocket but does not serve /json/version or /json/list HTTP
  endpoints. Add a third fallback in discover_cdp_url_with_timeout() that
  connects directly to ws://host:port/devtools/browser and verifies the
  endpoint with Browser.getVersion.

  Fixes #870

* chore

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-03-17 09:15:44 -05:00
Chris Yang 8dd012f4fd feat: add network har start/stop command for HAR 1.2 export (#874)
Expose HAR recording as a CLI subcommand under the existing `network`
command so users can capture and export network traffic without a
separate tool or opening the browser twice.

- Parse `network har start` and `network har stop [path]` in commands.rs
- Enrich HarEntry with request/response headers, timestamps, status text,
  resource type, HTTP version, and body sizes from CDP events
- Produce HAR 1.2 output with creator/browser metadata, query strings,
  and proper header arrays compatible with Chrome DevTools HAR viewer
- Auto-generate output path under ~/.agent-browser/tmp/har/ when omitted
- Add har_stop to skip_launch list so export works without a live browser
- Update help text, README, docs site, SKILL.md, and security policy docs
- Add unit tests for parsing, HAR entry serialization, and stop behavior
2026-03-17 09:02:39 -05:00
简简aw 663e10355a Enhance Chrome launch process with user-data-dir and timeout (#852)
* fix: improve Chrome launch process by enhancing user-data-dir handling and adding timeout for DevToolsActivePort

* fix: enhance Chrome launch process by improving user data directory handling and timeout management for DevToolsActivePort

* fix: remove unused wait_for_ws_url function to streamline Chrome launch process
2026-03-17 08:54:59 -05:00
7734bb2702 feat: add batch command for multi-step workflows (#865)
Add `batch` command that reads a JSON array of commands from stdin
and executes them sequentially against the daemon. This avoids
per-command process startup overhead when AI agents run multi-step
browser workflows.

Supports --bail to stop on first error (default: continue all)
and --json for structured output as an array of results.

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 08:48:50 -05:00
a865dd56e0 fix: fall back to /json/list when /json/version is unavailable (#861)
* fix: fall back to /json/list when /json/version is unavailable

Chrome's UI-based remote debugging mode (the permission dialog flow)
only exposes a WebSocket endpoint and does not serve /json/version.
Discovery now tries /json/version first, then falls back to /json/list
to find the browser target's WebSocket URL.

Fixes #628

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: preserve original error message when /json/list fallback fails

When both /json/version and /json/list fail, return the original
/json/version error instead of a wrapped message. This preserves the
error format expected by callers like lightpanda's timeout test.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 23:53:04 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 9a8d9f439b chore: version packages (#860)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-16 19:17:59 -05:00
Chris Tate 664789f5c6 fix: use DOM textContent as fallback name for cursor-interactive snapshot nodes (#859)
Generic elements (e.g. <div>) with cursor:pointer/onclick have empty ARIA
names because their text lives in StaticText children, which get filtered
in interactive mode. Fall back to the JS-collected textContent so the text
appears on the rendered tree line.

Fixes e2e_snapshot_cursor_many_elements CI failure from #855.
2026-03-16 18:26:22 -05:00
Chris Tate c0d4cf6a93 chore: add patch changeset for release (#858) 2026-03-16 17:37:08 -05:00
Ayush Rajgorandctate 48a265057b fix: Windows auto-connect profiling (#835) (#840)
* fix: Windows auto-connect profiling (#835)

Fix three interrelated bugs causing `--auto-connect` to fail on Windows,
plus a UX issue where auto-connect hijacked existing tabs:

1. Stale DevToolsActivePort — add TCP port liveness check before returning
   M144+ WebSocket URL; remove stale files when port is dead.

2. Missing Windows error codes — add os error 10061 (WSAECONNREFUSED) and
   10054 (WSAECONNRESET) to is_transient_error() so daemon startup races
   are retried on Windows.

3. --auto-connect not propagated to daemon — add auto_connect to
   DaemonOptions, set AGENT_BROWSER_AUTO_CONNECT env var via
   apply_daemon_env(), and guard the headed launch block so it doesn't
   send a second launch that overrides the auto-connect.

4. Auto-connect opens a fresh tab — after connecting to an existing
   Chrome, create a new about:blank tab and bring it to front so
   navigations don't hijack the user's existing tabs.

Made-with: Cursor

* fix: address review feedback — cargo fmt, shared helper, Windows tests

- Run cargo fmt on is_port_reachable() formatting
- Extract duplicated auto-connect-with-fresh-tab logic into
  connect_auto_with_fresh_tab() helper used by both handle_launch()
  and auto_launch()
- Add unit tests for Windows WSAECONNREFUSED (os error 10061) and
  WSAECONNRESET (os error 10054) in is_transient_error()

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-16 17:27:39 -05:00
0705b4ddac fix: propagate --cdp flag to daemon for reliable CDP reconnection (#857)
* fix: propagate --cdp flag to daemon via AGENT_BROWSER_CDP env var

The --cdp flag was not being passed to the daemon process as an environment
variable, causing auto-reconnection to fail. The daemon's auto_launch()
function checks for AGENT_BROWSER_CDP, but this was never set when spawning
the daemon.

This commit adds:
- cdp field to DaemonOptions struct
- AGENT_BROWSER_CDP env var setting in apply_daemon_env()
- flags.cdp propagation in main.rs

This ensures reliable CDP connection recovery when using --cdp with external
browsers like Lightpanda, Electron apps, or remote Chrome instances.

Fixes reconnection issues with --cdp flag after connection drops.

* chore: remove changeset

---------

Co-authored-by: Jake Shore <jakeshore@Jakes-Mac-mini.local>
Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-16 16:31:51 -05:00
Lppyand羲洋 811e66f99e feat: embed cursor-interactive elements into snapshot tree (#855)
* feat: embed cursor-interactive elements into snapshot tree

* optimize format

* fix: address review feedback for e2e_snapshot_cursor_interactive unitest

---------

Co-authored-by: 羲洋 <lipengyang.lpy@alibaba-inc.com>
2026-03-16 16:28:31 -05:00
42c4c56c9a feat: add --idle-timeout CLI flag for daemon auto-shutdown (#856)
* feat: add --idle-timeout CLI flag for daemon auto-shutdown

Add user-friendly --idle-timeout flag that converts time strings
to milliseconds. Supports formats like '10s', '3m', '1h', or raw ms.

This addresses a common need for ephemeral/CI environments where
daemon processes can be orphaned if not explicitly closed, leading
to resource consumption from zombie chrome-headless-shell processes.

Co-authored-by: Hermes (via claude-sonnet-4-20250520) <agent@hermes.ai>

* fix: address idle-timeout review feedback

* fix: normalize idle-timeout parsing

---------

Co-authored-by: Merlin <merlin@rbeckner.com>
Co-authored-by: Hermes (via claude-sonnet-4-20250520) <agent@hermes.ai>
2026-03-16 15:20:16 -05:00
0883813cd3 fix: support remote host in CDP discovery (#854)
* fix: support remote host in CDP discovery (#851)

  `discover_cdp_url` now accepts a host parameter instead of hardcoding
  127.0.0.1, allowing `connect "http://<remote-ip>:<port>"` to query the
  correct remote `/json/version` endpoint. The returned webSocketDebuggerUrl
  is rewritten to match the requested host and port, since Chrome always
  reports 127.0.0.1 regardless of the interface it was reached through.

* style: apply cargo fmt

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: unify discover_cdp_url and discover_cdp_url_with_request_timeout

Merge the two discovery functions into discover_cdp_url(host, port) and
discover_cdp_url_with_timeout(host, port, timeout), eliminating duplicated
logic.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: merge discover_cdp_url into single function with optional timeout

Replace discover_cdp_url + discover_cdp_url_with_timeout with a single
discover_cdp_url(host, port, timeout) where timeout is Option<Duration>.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: replace Option<Duration> with separate discover_cdp_url_with_timeout

Split back into two functions for cleaner call sites:
- discover_cdp_url(host, port) for default timeout
- discover_cdp_url_with_timeout(host, port, timeout) for custom timeout

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: bracket IPv6 addresses in CDP discovery HTTP URL

Extract bracket_ipv6 helper and apply it in fetch_cdp_info to produce
valid URLs like http://[::1]:9222/json/version instead of malformed
http://::1:9222/json/version.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 08:37:23 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 8163f6cdca chore: version packages (#850)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-16 00:31:08 -05:00
Chris Tate eda956b754 chore: add patch changeset for release (#849) 2026-03-16 00:22:08 -05:00
Chris Tate d866ee2022 Fix network idle detection for cached pages by observing 500ms idle period (#847)
The `wait --load networkidle` command was incorrectly returning immediately when pages were served from cache, causing subsequent commands to fail. This happened because the network idle logic would return instantly when no network requests were pending, without observing any idle period.

## Changes Made

- Extract network idle polling logic into a separate `poll_network_idle` function for better testability
- Fix the timeout handling to start a 500ms idle timer when no requests are pending, instead of returning immediately
- Add comprehensive unit tests covering the regression case and normal network request flows
- Ensure the function always observes at least 500ms of network inactivity before resolving, even for cached pages

## Key Fix

The critical change is in the timeout branch: when no CDP events arrive within 600ms, we now start the idle timer if no requests are pending, rather than returning `Ok(())` immediately. This prevents false-positive idle detection for pages that load entirely from cache.

Fixes #846
2026-03-15 23:11:41 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> ebfabe0e62 chore: version packages (#845)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-15 20:57:08 -05:00
Chris Tate 5fa239676b chore: add patch changeset for release (#844) 2026-03-15 20:48:08 -05:00
Chris Tateandctate 285eab46df fix: resolve snapshot -C and screenshot --annotate hang over WSS (#842)
* fix: resolve snapshot -C and screenshot --annotate hang over WSS (#841)

Root cause: sequential CDP round-trips per element in
find_cursor_interactive_elements() and collect_annotations() caused
timeouts over high-latency WSS connections (~200ms × 200+ elements
exceeds the 30s CDP timeout).

Fix:
- snapshot -C: Replace per-element CDP calls with a single JS eval
  that detects cursor:pointer/onclick/tabindex elements in-browser,
  then batch-resolve via DOM.querySelectorAll + concurrent
  DOM.describeNode calls using join_all
- screenshot --annotate: Replace sequential DOM.resolveNode +
  getRect calls with concurrent join_all, matching v0.19.0's
  Promise.all() pattern

Behavioral parity with v0.19.0 (Node.js/Playwright):
- cursor:pointer detection via getComputedStyle
- Inherited cursor:pointer dedup (skip children of pointer parents)
- interactiveTags and interactive ARIA roles exclusion
- Role differentiation: clickable vs focusable
- Text dedup against ARIA tree ref names and quoted strings
- Edge case: -i -C shows cursor elements even when ARIA tree is empty

Tests:
- 5 unit tests for build_dedup_set() helper
- 3 e2e regression tests: cursor-interactive detection, annotation
  scaling to 50 elements, cursor scaling to 100 elements

* fix: add hidden/aria-hidden filtering, contentEditable support, and cleanup robustness

- Restore hidden/aria-hidden element filtering in cursor-interactive JS
  (was present in old code, dropped during rewrite)
- Add contentEditable detection with 'editable' role and hint
- Replace fire-and-forget cleanup with warning on failure
- Simplify build_dedup_set to use ref_map only (eliminates fragile
  tree-text quote parsing; ref_map already has all ref-bearing names)

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-15 20:41:30 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 5b74604a5c chore: version packages (#839)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-15 14:14:01 -05:00
Chris Tate 4b5fc78f71 chore: add patch changeset for release (#838) 2026-03-15 14:05:01 -05:00
Chris Tateandctate c092ffd82b fix: use correct VK codes for punctuation in type command (#836)
* fix: use correct Windows virtual-key codes for punctuation in type command

The `type` command was dropping punctuation characters like `.`, `'`, and
`#` because `char_to_key_info()` used raw ASCII codes as the
`windowsVirtualKeyCode` in CDP `Input.dispatchKeyEvent` calls. For
punctuation the ASCII value collides with unrelated VK codes — most
critically '.' (ASCII 46) equals VK_DELETE (0x2E), causing Chrome to
interpret periods as Delete key presses.

Changes:
- Add `punctuation_key_info()` with correct VK_OEM_* codes matching
  Playwright's USKeyboardLayout (e.g. Period=190, Slash=191, Semicolon=186)
- Fall back to `Input.insertText` for characters without a US keyboard
  mapping (emoji, CJK, etc.), matching Playwright's `keyboard.type()`
- Update e2e test to use `type` instead of `fill` workaround for email
- Add unit tests verifying VK code parity with Playwright's layout

Fixes #833

* style: fix rustfmt formatting for InsertTextParams

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-15 13:57:15 -05:00
Chris Tateandctate 8ac7fe916e fix: restore Playwright-parity check/uncheck for Material Design controls (#837)
The v0.20.0 migration from Playwright to the native Rust daemon introduced
two regressions in checkbox/radio handling:

1. `is_element_checked` only read `this.checked`, which is undefined on
   non-input elements. Material Design and ARIA controls use wrapper divs
   with `role="checkbox"` and `aria-checked`, or hide the native input
   off-screen inside a label. The function now mirrors Playwright's
   `getChecked()` with follow-label retargeting: native `.checked`,
   `aria-checked` for ARIA roles, `label.control` traversal, and nested
   input lookup.

2. `check`/`uncheck` accepted the coordinate-based CDP click result
   without verifying the state actually changed. When the AX tree's
   `backendDOMNodeId` points to a hidden off-screen input (common in
   Material Design), `Input.dispatchMouseEvent` hits nothing. The actions
   now re-check state after clicking and fall back to a JS `.click()` on
   the resolved input — matching Playwright's `_setChecked` verify step.

Adds e2e regression test covering Material Design (hidden input + ripple
overlay), ARIA-only, and native checkbox patterns.

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-15 13:38:39 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 1fd8e9d09a chore: version packages (#831)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-15 10:28:01 -05:00
Chris Tate a3d966244e chore: add patch changeset for release (#830) 2026-03-15 10:14:01 -05:00
Matt Van HornandMatt Van Horn 8348b77800 fix: filter chrome:// internal targets from auto-connect discovery (#827)
When using --auto-connect, discover_and_attach_targets() was selecting
Chrome internal pages (chrome://, chrome-extension://, devtools://) as
the active target. Follow-up commands like `get url` and `snapshot`
would then return data from targets like chrome://omnibox-popup.top-chrome/
instead of the actual application tab.

Add is_internal_chrome_target() filter to exclude internal Chrome targets
from the discovery results. If no user-facing targets remain after
filtering, the existing "create a new tab" fallback handles it.

Fixes #813

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-03-15 10:13:22 -05:00
Chris Tateandctate 609f32c986 fix: restore WebSocket streaming in native daemon (#826)
* fix: restore WebSocket streaming in native daemon

The v0.20.0 Rust rewrite broke WebSocket streaming — connections opened
but received zero messages before closing. Multiple issues contributed:

1. StreamServer was dropped immediately after creation in daemon.rs,
   closing the broadcast channel and killing all WS connections.

2. Screencast frames were only processed during command polling
   (drain_cdp_events) instead of in real-time, unlike the 0.19.0
   TypeScript cdp.on('Page.screencastFrame') callback.

3. Auto-start/stop screencast on WS client connect/disconnect was
   missing from the Rust implementation.

4. Screencast CDP commands used the wrong session ID (daemon session
   name instead of the CDP page session from Target.attachToTarget).

5. Broadcast channel Lagged errors killed WS connections instead of
   being handled gracefully.

The fix adds a background CDP event loop in StreamServer that subscribes
to Chrome events and broadcasts screencast frames in real-time, properly
tracks the CDP page session ID, restores auto-screencast lifecycle, and
keeps the StreamServer alive in DaemonState.

Fixes #820

* fix: use actual CDP session ID for input dispatch in stream WebSocket

Pass the real cdp_session_id (from Target.attachToTarget) through to
handle_ws_client instead of an empty string. Previously, input commands
(mouse, keyboard, touch) were sent with `"sessionId": ""` which Chrome
silently rejects. Now the correct page session ID is read at dispatch
time, and when no session ID is set yet (before browser launch),
the field is omitted entirely via `None` so Chrome uses browser-level
dispatch.

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-15 10:00:28 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 79f464d47a chore: version packages (#829)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-15 09:50:01 -05:00
Chris Tate 51d9ab4d49 chore: add patch changeset for release (#828) 2026-03-15 09:42:01 -05:00
Chris Tateandctate 6636ac0e74 fix: snapshot --selector scopes to the matched element subtree (#825)
* fix: snapshot --selector scopes to the matched element subtree

The native Rust daemon accepted the --selector flag but never used it —
the full accessibility tree was always returned regardless of the
selector.  This restores the 0.19.0 behaviour where snapshot --selector
returns only the subtree rooted at the matched CSS selector.

The implementation resolves the selector via Runtime.evaluate, fetches
the full DOM subtree with DOM.describeNode(depth: -1) to collect all
descendant backendNodeIds, then filters the AX tree to render only the
nodes whose backendDOMNodeId falls within that set.  This correctly
handles elements like <body> that don't map to a direct AX node.

Also fixes handle_snapshot reading "depth" instead of "maxDepth" from
the command JSON, which caused --depth to be silently ignored.

Fixes #822

* style: run cargo fmt on snapshot.rs

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-15 09:22:55 -05:00
bc94eaf94f fix: add appium: vendor prefix to iOS capabilities for Appium v3 (#810)
* fix: add appium: vendor prefix to iOS capabilities for Appium v3

Appium v3 enforces the W3C WebDriver spec strictly, requiring
non-standard capabilities to use vendor prefixes. The iOS provider
was sending capabilities like `automationName`, `noReset`, `deviceName`,
`platformVersion`, and `udid` without the required `appium:` prefix,
causing session creation to fail with InvalidArgumentError.

This change prefixes all non-standard capabilities with `appium:` while
leaving standard W3C capabilities (`platformName`, `browserName`)
unprefixed. Backwards-compatible with Appium v2, which accepts both
formats.

Fixes #629

* fix: extract build_ios_capabilities for testable production code path

Addresses review feedback: removes unused `mut manager` warning and
validates the actual capability-building logic instead of reconstructing
JSON inline.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 09:22:32 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 77a27fe6a3 chore: version packages (#824)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-15 08:25:01 -05:00
Chris Tate daf7263385 chore: add patch changeset for release (#823) 2026-03-15 08:16:02 -05:00
0745db44a2 fix: remove obsolete BrowserManager TypeScript API from README (#821)
* fix: remove obsolete BrowserManager TypeScript API references from README

The TypeScript src/ was removed in commit 8e43469 (full native #754),
but README still referenced the non-existent BrowserManager API.
Replace Lambda example with CLI-based handler and remove Programmatic API section.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 08:05:24 -05:00
jin.2andhyunjinee 19ba9048a0 fix: recording produces correct video duration with real-time ffmpeg encoding (#812)
* fix: replace screenshot polling with screencast-based piped ffmpeg recording

  Recording previously used Page.captureScreenshot polling at 10fps,
  which was CPU-heavy and produced inconsistent results. Now uses
  Page.startScreencast with throttled acks (35ms interval) to receive
  frames event-driven from Chrome, and pipes JPEG data directly to
  ffmpeg stdin in real-time instead of saving temp files.

  - Spawn ffmpeg at recording start with piped stdin (image2pipe)
  - Background task receives screencast frames, interpolates gaps by
    repeating the last frame based on timestamps, targets 25fps
  - Ack throttling controls Chrome's frame push rate
  - Fix: current frame was never written after the first one
  - Fix: frame count was read before task finished padding
  - Remove tokio-util dependency (replaced CancellationToken with oneshot)
  - Add tokio "process" feature for async child process stdin pipe
  - Extract start/stop_recording_task helpers on DaemonState
  - Add tests for restart, ffmpeg codec selection, and stop without task

* fmt

* chore

* fix: switch WebM codec from VP9 to VP8 for correct framerate and browser
  compatibility

  VP9 realtime encoder ignored input framerate, producing 10fps output
  instead of 25fps. This caused inconsistent playback in browsers.
  VP8 respects -framerate 25 and has wider browser playback support.

* fmt

* fix: add kill_on_drop to ffmpeg process to prevent zombie on task panic

* fix: switch from screencast to screenshot polling for reliable recording duration

  Screencast only pushes frames on visual changes, producing short videos
  on static pages. Screenshot polling captures at a fixed 10fps interval
  regardless of page activity, guaranteeing duration matches wall-clock time.
  ffmpeg piped stdin architecture is preserved — no temp files.

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-03-15 08:04:27 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> e78cc05cec chore: version packages (#819)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-15 04:36:01 -05:00
Chris Tate 25a152652a chore: add patch changeset for release (#818) 2026-03-15 04:28:01 -05:00
alexph-devandClaude Opus 4.6 5ea508a917 feat: add Brave Browser support to auto-connect CDP discovery (#817)
Brave Browser is Chromium-based and uses the same DevToolsActivePort
mechanism. Add its user-data-dir paths to get_chrome_user_data_dirs()
and its executable paths to find_chrome() on all three platforms
(macOS, Linux, Windows).

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 04:21:51 -05:00
Chris Tateandctate 02d1a7ad7c Improve postinstall message to detect existing Chrome installations (#815)
* Improve postinstall message to detect existing Chrome installations

Previously, the npm postinstall script always recommended running `agent-browser install` to download Chrome for Testing, even when users already had a working Chrome installation on their system.

This change adds Chrome detection logic to the postinstall script that mirrors the runtime behavior:

- Checks for system Chrome installations on macOS, Linux, and Windows
- Shows a success message when Chrome is found, indicating it will be used automatically
- Only shows the `agent-browser install` warning when no Chrome is detected
- Provides platform-specific guidance (Linux `--with-deps` flag, `--executable-path` alternative)

The detection logic matches the existing Rust `find_chrome()` implementation to ensure consistency between postinstall messaging and runtime behavior.

Fixes #814

* Mention --cdp, --provider, --engine as alternatives in postinstall message

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-15 03:32:34 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> c23ce448bd chore: version packages (#809)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-14 21:08:38 -05:00
Chris Tate fa91c22e50 chore: add patch changeset for release (#808) 2026-03-14 21:00:39 -05:00
Chris Tateandctate c07f43e242 fix: re-query accessibility tree when backend_node_id is stale (#806)
* fix: gracefully fall back to role/name lookup when backend_node_id is stale

When the DOM changes between snapshot and click (common with SPAs and
dynamic UIs), the stored backend_node_id becomes invalid. Previously,
DOM.getBoxModel and DOM.resolveNode failures propagated as hard errors,
bypassing the role/name fallback path entirely. Now these failures are
caught and the code falls through to a JS-based element lookup.

Also adds resolve_object_id_by_role_name so that resolve_element_object_id
has a fallback for ref-based lookups (previously it had none), and
improves the role matching JS to correctly map implicit ARIA roles
(e.g. <input type="submit"> → "button", <a href> → "link").

Closes #805

* test: add e2e regression test for stale ref click fallback (#805)

Verifies that clicking a ref whose backend_node_id has become stale
(because the DOM was replaced by JavaScript) falls back to role/name
lookup instead of failing with "Could not compute box model".

* fix: use accessibility tree for stale ref fallback instead of JS heuristic

Replace the hand-rolled JS role/name matching (getImplicitRole,
getAccessibleName) with a re-query of Accessibility.getFullAXTree —
the same data source that built the ref map during snapshot. This
guarantees role/name matching is identical to what was stored,
preventing silent wrong-element clicks from name computation
divergence (e.g. aria-labelledby, <label for>, alt text).

Matches v0.19.0 (Playwright) behavior where getByRole always
re-queried the live accessibility tree.

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-14 20:54:08 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 5f8e993602 chore: version packages (#804)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-14 18:23:38 -05:00
Chris Tate fc091d294d chore: add patch changeset for release (#803) 2026-03-14 18:15:39 -05:00
Chris Tateandctate c4f0f22ae9 fix: prevent daemon panic on broken stderr pipe during Chrome launch (#802)
Replace all `eprintln!` calls in daemon-context code with
`let _ = writeln!(std::io::stderr(), ...)` so that broken pipe errors
on stderr are silently ignored instead of panicking.

The CLI client spawns the daemon with piped stderr to capture startup
errors, then drops the pipe handle once the daemon is ready. Any
subsequent `eprintln!` in the daemon panics because Rust's `eprintln!`
macro internally unwraps the write result. This caused the reported
"failed printing to stderr: Broken pipe (os error 32)" panic during
Chrome launch on Linux.

Closes #799

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-14 18:08:22 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 23a8b19de1 chore: version packages (#801)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-14 17:27:38 -05:00
Chris Tate e2ebde261c chore: add patch changeset for release (#800) 2026-03-14 17:19:38 -05:00
Chris Tate 06842ea7c5 fix: remove unused pnpm setup from global-install CI job (#798)
The global-install job only uses npm (npm pack, npm install -g) but had
pnpm setup with cache enabled. On Windows, the pnpm store directory
doesn't exist since pnpm is never used, causing the Post Setup Node.js
cache step to fail with a path validation error.
2026-03-14 16:59:05 -05:00
Chris Tate a773863214 fix: handle broadcast channel lag instead of treating it as stream closure (#797)
The CDP event broadcast channel (capacity 256) can overflow on slow CI
runners when Chrome emits many events during navigation. Previously,
RecvError::Lagged was treated the same as RecvError::Closed, causing
spurious "Event stream closed" errors even though Chrome was still
running. Now all 5 event-receiving loops correctly continue on Lagged
instead of breaking.
2026-03-14 16:29:47 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> f962c7a4c4 chore: version packages (#796)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-14 16:18:19 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 17d2785ca0 chore: version packages (#795)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-14 16:01:55 -05:00
Chris Tate d1ba208a50 fix: add --disable-dev-shm-usage for Chrome in CI/container environments (#794)
Chrome uses /dev/shm for shared memory, which is typically limited to
64MB on CI runners and containers. When Chrome exhausts this, it crashes
mid-session with "Event stream closed" errors. Auto-detect CI/container
environments and pass --disable-dev-shm-usage to use /tmp instead.
2026-03-14 15:58:44 -05:00
Chris Tate e365909d4f chore: add patch changeset for release (#793) 2026-03-14 15:54:10 -05:00
Chris Tateandctate d4b9004a6d fix: resolve snapshot hang over remote CDP (WSS) connections (#792)
The CDP WebSocket client had three issues causing snapshot to hang
indefinitely when connected to remote browsers via WSS:

1. Binary WebSocket frames were silently dropped — remote CDP proxies
   (Browserless, Browserbase, etc.) may send large responses like
   Accessibility.getFullAXTree as Binary frames instead of Text frames.

2. Default tungstenite size limits (16 MiB frame / 64 MiB message)
   could be exceeded by large accessibility tree responses, causing the
   WebSocket connection to error out and the reader task to die.

3. When the reader task died, pending commands waited for the full
   30-second timeout instead of failing immediately.

Fixes #788

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-14 15:46:08 -05:00
Chris Tate 529b8acfbe fix: retry Chrome launch up to 3 times on transient startup failures (#791)
Chrome occasionally crashes during startup on CI runners before
printing the DevTools URL, causing random e2e test failures across
different tests each run. Retry the launch with a 500ms delay to
handle these transient crashes.
2026-03-14 14:42:26 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> fe3c1ddb48 chore: version packages (#790)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-14 14:06:03 -05:00
Chris Tate 944fa01247 chore: add patch changeset for release (#789) 2026-03-14 13:50:23 -05:00
Chris Tate da45d00b2a support consecutive --auto-connect commands (#786) 2026-03-14 13:43:38 -05:00
Chris Tate fbdae9b6ae fix: restore refs dict in --json snapshot output (#787)
- Restore the `refs` dictionary in `--json` snapshot output, matching the documented API contract
- The `refs` field was silently dropped during the Node.js to Rust rewrite (v0.20), causing consumers parsing `data.refs` for programmatic element interaction to receive no structured ref data

Fixes #785
2026-03-14 13:43:29 -05:00
Manolis TzanidakisandClaude Opus 4.6 388f19e1bb feat: add linux-musl (Alpine) builds for x64 and arm64 (#784)
* feat: add linux-musl (Alpine) builds for x64 and arm64

Add x86_64-unknown-linux-musl and aarch64-unknown-linux-musl targets to
the release workflow using cargo-zigbuild. Update the JS wrapper and
postinstall script to detect musl libc and select the correct binary.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: simplify isMusl() and add musl targets to build script

Address PR #784 review feedback:
- Remove redundant first try block in isMusl() (ldd --version always
  throws on musl, so only the `|| true` variant works)
- Add x86_64-unknown-linux-musl and aarch64-unknown-linux-musl targets
  to build-all-platforms.sh to stay in sync with the release workflow

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-14 12:51:35 -05:00
jin.2andhyunjinee c4a40033e0 fix: correct e2e test assertions for diff_snapshot and domain_filter (#783)
- e2e_diff_snapshot: fix wrong field access (data.diff.identical →
  data.changed)
    and remove redundant assertion
  - e2e_domain_filter: set domain_filter after launch to avoid Fetch.enable
  deadlock

Co-authored-by: hyunjinee <leehj0110@kakao.com>
2026-03-14 12:07:46 -05:00
mikewong23571 1fa7949542 test: fix Chrome temp-dir cleanup test on Windows (#766) 2026-03-14 12:03:08 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 974d735af5 chore: version packages (#782)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-14 09:46:03 -05:00
Chris Tate bd05917f20 chore: add patch changeset for release (#781) 2026-03-14 09:36:36 -05:00
44ce24fb48 fix: use VP9 codec for webm recording output (#779)
* fix: use VP9 codec for webm recording output

The recording command hardcoded libx264 (H.264) which is incompatible
with the WebM container format. WebM only supports VP8/VP9/AV1 codecs,
causing ffmpeg to fail when users specify a .webm output file.

Select codec based on output file extension: libvpx-vp9 for .webm,
libx264 for other formats.

Fixes #778

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: use CRF mode for VP9 webm encoding

Switch from bitrate target (-b:v 2M) to constant quality mode (-crf 30),
which is the standard approach for screen recording (used by Puppeteer
and recommended by ffmpeg VP9 guide). CRF adapts bitrate to scene
complexity for more consistent quality.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add -b:v 0 for true constant quality VP9 encoding

Without -b:v 0, libvpx-vp9 uses its default bitrate target alongside
-crf, resulting in constrained quality mode instead of true constant
quality mode.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: pad video dimensions to even numbers for h264 compatibility

libx264 requires width and height to be divisible by 2, but CDP
screencast can capture frames with odd dimensions (e.g. 1280x577).
Add pad filter to ensure even dimensions for all codecs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-14 09:27:33 -05:00
67986adffc fix: correct misleading SIGPIPE comment (#776)
The comment said "Ignore SIGPIPE" but the code actually resets SIGPIPE
to SIG_DFL (default behavior = process termination), not SIG_IGN (ignore).
Updated the comment to accurately describe what the code does and why.

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-14 06:33:20 -05:00
Samuel Reed 790123f9af fix: accept integer nodeId/childIds in AX tree for Lightpanda compatibility (#775) 2026-03-14 06:32:35 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 99c732c188 chore: version packages (#772)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-13 20:33:33 -05:00
Chris Tate c7ad5ff66a fix: repair CI failures from stale lockfile and Chrome sandbox on GHA runners (#771)
Regenerate pnpm-lock.yaml to match the cleaned-up package.json (only
@changesets/cli remains). Add CI environment detection to
should_disable_sandbox() so Chrome launches with --no-sandbox on GitHub
Actions runners where AppArmor blocks unprivileged user namespaces.
2026-03-13 20:23:13 -05:00
Chris Tate f8482f3533 fix (#770) 2026-03-13 20:16:29 -05:00
Chris Tate bdfcc4ee2d publish to cargo (#769) 2026-03-13 20:15:41 -05:00
Chris Tate 235fa88dc6 prepare v0.20 (#768) 2026-03-13 20:11:30 -05:00
Chris Tate 8e43469c8b full native (#754)
* full native

* fix: apply cargo fmt formatting

* fix: prevent zip path traversal in Chromium installer

Use enclosed_name() to sanitize zip entry paths, preventing malicious
archives from writing outside the extraction directory.

* improvements

* fix: apply cargo fmt formatting

* benchmarks

* bench

* updates

* fixes
2026-03-13 19:59:21 -05:00
mikewong23571 d4b948c1d4 test: fix flaky test_launch_options_from_env_defaults due to missing EnvGuard (#763)
The test was reading AGENT_BROWSER_HEADED without holding ENV_MUTEX,
causing a race with test_launch_options_from_env_headed_flag when
tests run in parallel.
2026-03-13 12:18:40 -05:00
mikewong23571 d40fd4009d fix: harden Lightpanda startup timeouts (#762) 2026-03-13 11:36:51 -05:00
Selman 056024b447 fix: Lightpanda engine launch with release binaries (#760)
Three issues prevented --engine lightpanda from working with official
Lightpanda release builds:

1. Missing --log_level info: Lightpanda release builds default to
   log_level=warn, which suppresses the info-level "server running"
   startup message. wait_for_address() blocks forever reading an empty
   stderr pipe. Pass --log_level info explicitly.

2. --timeout 0 means instant disconnect: Lightpanda interprets 0 as
   "timeout after 0ms", not "no timeout". Use 604800 (1 week, the
   documented maximum) instead.

3. extract_address only matched pretty format: Release builds use
   logfmt (address=HOST:PORT without spaces), but the parser only
   matched the pretty format (address = HOST:PORT with spaces). Handle
   both formats.
2026-03-13 10:40:19 -05:00
mikewong23571 3a2e2796c8 fix: correct storage local key lookup parsing and text output (#761) 2026-03-13 09:45:00 -05:00
Hyunjin Lee f426860c04 fix: narrow "not found" pattern in to_ai_friendly_error to avoid catching non-element errors (#759)
* fix: narrow "not found" pattern in to_ai_friendly_error to avoid catching
  non-element errors

  Change `contains("not found")` to `contains("element not found")` so that
  connection/state errors like "Browser not found" pass through unchanged
  instead of being incorrectly mapped to "Element not found" message.

* remove comment

* fmt

* test: use real project error message in non-element not found test
2026-03-13 09:43:38 -05:00
QuietyAwe ea9d456341 fix: respect --headed false flag in CLI (#757)
When user explicitly sets --headed false, the CLI was ignoring this
flag because the launch condition only checked if flags.headed was
true. This meant that --headed false would not trigger a launch
command, and subsequent commands would auto-launch with default
headless=true.

The fix adds a cli_headed flag to track when the user explicitly
sets --headed (regardless of value), and includes this in the
launch condition check.

Fixes #743
2026-03-13 09:42:59 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> e02bc1a10c chore: version packages (#756)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-13 03:59:13 -05:00
Chris Tate 56bb92bfe1 prepare v0.19 (#755) 2026-03-13 03:48:00 -05:00
Chris Tate 087600e50e Fix linting and formatting issues to resolve CI build failures (#752)
This PR fixes CI build failures by addressing code formatting and linting issues that were causing the builds to fail.

**Changes made:**

1. **Rust formatting fixes in `cli/src/commands.rs`:**
   - Removed unnecessary multi-line formatting for clipboard operations
   - Applied consistent single-line formatting for return statements
   - Fixed line length and formatting for the `test_wait_text_with_timeout` test function

2. **TypeScript fixes in `src/actions.ts`:**
   - Fixed `waitForFunction` usage in the `handleWait` function by replacing the function parameter approach with a string-based implementation
   - Properly escaped the text parameter using `JSON.stringify` to prevent potential injection issues

These changes ensure the code passes linting checks (clippy for Rust, ESLint for TypeScript) and formatting validation (rustfmt, prettier) that are enforced in the CI pipeline.

Fixes #751
2026-03-13 03:31:49 -05:00
Chris Tate a673a77c4e feat: add screenshot output config, clipboard CLI commands, and fix wait --text native path (#749)
* feat: add screenshot output config, clipboard CLI commands, and fix wait --text native path

## Summary

- Add `--screenshot-dir`, `--screenshot-quality`, and `--screenshot-format` CLI flags (with corresponding `AGENT_BROWSER_SCREENSHOT_DIR`, `AGENT_BROWSER_SCREENSHOT_QUALITY`, `AGENT_BROWSER_SCREENSHOT_FORMAT` env vars) so users can configure where and how screenshots are saved without specifying a full path every time
- Add `clipboard read`, `clipboard write <text>`, `clipboard copy`, and `clipboard paste` CLI commands, exposing the existing protocol-level clipboard handlers that were previously only accessible via JSON-RPC
- Fix `wait --text` in native mode: the CLI was emitting `selector: "text=..."` (a Playwright-style locator) which native's `querySelector` can't handle. Now emits a `text` field that correctly hits the native `wait_for_text` polling path
- Add native clipboard `copy` and `paste` support via CDP `Input.dispatchKeyEvent`, and a `write` operation to the Node.js handler

* fix: resolve CI failures in Rust formatting and TypeScript typecheck

Use string-based page.evaluate for clipboard writeText to avoid
referencing `navigator` in Node.js compilation context. Run cargo fmt
to fix formatting in commands.rs and screenshot.rs.

* fix: clipboard write captures full multi-word text

Use rest[1..].join(" ") instead of rest.get(1) so unquoted multi-word
input like `clipboard write hello world` sends the full string rather
than silently dropping everything after the first word.

* improvements

* fixes

* improvements

* improvements
2026-03-13 02:58:30 -05:00
mikewong23571andClaude Sonnet 4.6 1129a3e7fc fix: restore BrowserManager.navigate() and package entry point (#748)
Root cause: package.json `main` pointed at `dist/daemon.js` (the
internal daemon process), so programmatic consumers of the package
received the daemon module instead of a usable API. Additionally,
`BrowserManager.launch()` required IPC-only fields (`id`, `action`),
and `navigate()` existed only as a private function inside actions.ts.

Changes:
- Add src/index.ts as the public package entry point
- Add BrowserLaunchOptions type (Pick<LaunchCommand> minus id/action/engine)
  to decouple the programmatic API from the IPC wire protocol
- Change launch() signature from LaunchCommand to BrowserLaunchOptions
- Add BrowserManager.navigate(url, options?) — consolidates domain check,
  scoped-header setup, and page.goto() into one reusable method; auto-
  recovers a new page when all pages have been closed (stale session)
- Add BrowserManager.getUrl() and getTitle() convenience methods
- Update package.json: main → ./dist/index.js, add types and exports["."]
- Add tests: navigate() with headers, waitUntil, allowedDomains blocking,
  allowedDomains allow, non-http(s) scheme blocking, getUrl/getTitle, and
  compile-time type assertions verifying the public entry exports the right
  API surface (direct repro of #307)

Fixes #307

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-13 02:55:47 -05:00
Chris Tate 640d259130 Fix extensions not being loaded from config.json (#750)
Fix issue where Chrome extensions specified in the `extensions` field of `config.json` were not being loaded when launching the browser.

## Problem
Extensions configured via the `extensions` field in `config.json` were not being passed to the Chrome browser launch command, causing them to be ignored.

## Changes
- Added `!flags.extensions.is_empty()` to the launch trigger condition to ensure browser launch is triggered when extensions are configured
- Added extensions to the launch command JSON payload so they are properly passed to the browser

Fixes #726
2026-03-13 02:42:39 -05:00
Chris Tateandctate 1327856889 feat: add browserless provider integration to native browser implementation (#746)
* feat: add browserless provider integration to native browser implementation

This PR adds support for the Browserless provider to the native browser implementation, expanding the available remote browser providers from 3 to 4.

## Changes Made

- **Added `connect_browserless()` function**: Implements session creation with Browserless API using environment variables for configuration
- **Updated provider routing**: Added "browserless" case to the main provider switch statement
- **Added session cleanup**: Implemented proper session termination using the stop URL returned by Browserless
- **Updated documentation**: Modified comments and error messages to include Browserless in the supported provider list
- **Environment variable support**: Added support for configurable Browserless settings including API key, URL, browser type, TTL, and stealth mode

## Implementation Details

- Uses standard Browserless session API with POST to create sessions and DELETE to terminate
- Supports both chromium and chrome browser types with validation
- Includes proper error handling for API failures and missing configuration
- Stores the stop URL as session_id for cleanup purposes
- Follows the existing provider pattern for consistency

Fixes #744

* fix: URL-encode API key in browserless session request

Use reqwest's .query() method instead of string-formatting the token
directly into the URL, matching the Node.js implementation's use of
encodeURIComponent. Prevents malformed URLs if the API key contains
special characters.

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-13 01:38:57 -05:00
Chris Tate a3dcf3fe60 fix scroll on page load (#747) 2026-03-13 01:38:39 -05:00
Chris Tateandctate 870876b5c1 Fix HTML retrieval by using browser.getLocator() for selector operations (#745)
* Fix HTML retrieval by using browser.getLocator() for selector operations

This PR fixes an issue where HTML content retrieval was not working properly when using selectors.

**Problem:**
The `get html` command and other selector-based operations were failing because they were using `page.locator()` directly instead of the browser manager's locator method.

**Changes:**
- Updated `handleContent()` to use `browser.getLocator()` instead of `page.locator()` for HTML retrieval with selectors
- Applied the same fix to other affected functions: `handleCount()`, `handleBoundingBox()`, `handleInnerText()`, `handleInnerHtml()`, and `handleSetValue()`
- Ensures consistent locator handling across all selector-based operations

**Implementation Details:**
The fix replaces direct `page.locator(command.selector)` calls with `browser.getLocator(command.selector)` to ensure proper element selection and interaction through the browser manager's abstraction layer.

Fixes #735

* Fix remaining page.locator() calls to use browser.getLocator()

Apply the same fix to all remaining functions that were using
page.locator(command.selector) directly instead of going through
browser.getLocator(): handleWheel, handleHighlight, handleClear,
handleSelectAll, handleDispatch, handleNth, handleMultiSelect,
and handleDiffScreenshot.

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-13 01:11:13 -05:00
Joel Griffith b9a24df40f feat: Add browserless.io as a browser provider (#502)
* feat: Add browserless as a hosted option + boolean env-parsing utility

* Add ensureDomainFilter, sanitizeExistingPage and move parseBooleanParam

* Add docs in relevant places, fix utils, rename of API env var

* Update readme

* Fix env variable name in readme

* Cleanup session stop urls when errors happen

* Fix browserlessStopUrl not being assigned in happy path
2026-03-13 00:45:02 -05:00
Chris Tate fb7185d860 ci: switch from windows-latest-8-cores to windows-latest runner (#742)
Resolves CI slowdown issues caused by limited availability of Windows containers with 8 cores by switching to the standard Windows runner image.

## Changes Made

- Updated `rust-cross` job to use `windows-latest` instead of `windows-latest-8-cores`
- Updated `windows-integration` job to use `windows-latest` instead of `windows-latest-8-cores`  
- Updated `global-install` job matrix to use `windows-latest` instead of `windows-latest-8-cores`

This change trades some performance for better availability and faster CI queue times, as the standard Windows runners have much better availability than the 8-core variant.

Fixes #741
2026-03-12 14:53:28 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> a66c5960f2 chore: version packages (#740)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-12 14:41:00 -05:00
d019c09bbc feat: add idle timeout to daemon to prevent orphaned Chrome processes (#722)
* feat: add idle timeout to daemon to prevent orphaned Chrome processes

The daemon persists indefinitely after browser sessions are used,
leaving orphaned Chromium processes consuming memory and CPU.

Add a configurable idle timeout (default 15 minutes) that shuts down
the daemon when no commands arrive. Resets on every incoming command,
so active sessions are unaffected.

Set AGENT_BROWSER_IDLE_TIMEOUT_MS=0 to disable (preserves old behavior).

Fixes #721

* fix: save session state before shutdown to prevent silent data loss

The shutdown() function (used by idle timeout, SIGINT, SIGTERM, SIGHUP)
previously closed the browser without saving state, unlike the explicit
`close` command which calls saveStateToFile(). This meant idle timeouts
silently destroyed cookies, localStorage, and login sessions.

Now shutdown() mirrors the close command's auto-save behavior: it calls
saveStateToFile() before manager.close(), preserving session state to
disk. This makes idle timeout functionally equivalent to an explicit
close — users returning after an idle shutdown get their state restored.

Addresses review feedback on #722 by @ctate.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Max Stoel <maxalerator@hotmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 14:39:25 -05:00
mikewong23571 d4f7fbc718 fix: align native daemon port hash with client on Windows (#734)
The client (connection.rs) and native daemon (native/daemon.rs) used
different get_port_for_session() implementations on Windows:

- Client:  i32, .chars(), djb2  — (hash << 5) - hash + c
- Daemon:  i64, .bytes(), Java hashCode — hash * 31 + b

For session name "default", client computes port 50838 while the
daemon binds on 51174, causing a 5-second timeout and startup failure.

Fix: align native/daemon.rs to use the identical djb2 algorithm from
connection.rs (i32, chars, djb2), so both sides agree on the port.

Unix is unaffected (uses Unix domain sockets, no port hashing).

Tests: add port hash regression tests to all three implementations
(native/daemon.rs, connection.rs, daemon.ts) to prevent future drift.

Fixes #705
2026-03-12 14:15:35 -05:00
吴洪磊andHonglei Wu 2fb2a51c82 fix: update handleGetText to use innerText for improved text retrieval (#729)
The handleGetText function now retrieves text using innerText, falling back to textContent if innerText is not available. This change enhances the accuracy of text extraction from elements.

Co-authored-by: Honglei Wu <honglei.wu@shopee.com>
2026-03-12 13:59:09 -05:00
mikewong23571 c562ef5bb7 fix: allow newTab() in persistent context (--extension/--profile) mode (#731)
When launched with --extension or --profile, launchPersistentContext()
is used which sets isPersistentContext=true but leaves this.browser as
null. The guard in newTab() checked !this.browser, causing a false
"Browser not launched" error even though the browser was running.

Replace !this.browser with !this.isLaunched(), which already accounts
for both launch paths (browser !== null || isPersistentContext).

Also improve the error message in newWindow() to clarify that it is
not supported in persistent context mode, since it requires a Browser
object to create a new context.

Fixes #411
2026-03-12 13:55:55 -05:00
01172eaa44 fix: isolate getEncryptionKey tests from local filesystem (#737)
* fix: isolate getEncryptionKey tests from local filesystem

Tests for getEncryptionKey() failed on machines where
~/.agent-browser/.encryption-key existed, because the file-based
fallback was not mocked out. Mock node:fs to isolate both env var
and key file paths, and add missing tests for the file fallback.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: clean up fs mock naming in encryption tests

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 13:45:05 -05:00
Chris Tate 942b8cd8ee prepare v0.18.0 (#738) 2026-03-12 12:19:54 -05:00
Chris Tate 315d191606 inspect (#736)
* inspect

* fixes

* improvements

* fixes

* fixes

* improvements

* fix null cdp url

* fix rust reader loop

* improvements

* improvements

* fixes
2026-03-12 12:01:40 -05:00
Chris Tate f2d4089284 auth docs (#730)
* add docs

* note

* format
2026-03-12 00:54:19 -05:00
Derek cc82dd137c Remove BROWSERBASE_PROJECT_ID requirement (#625)
* Remove BROWSERBASE_PROJECT_ID requirement

The Browserbase API no longer requires a project ID to create sessions —
it is inferred from the API key. Remove the env var requirement from both
the TypeScript daemon and Rust CLI, and update docs accordingly.

* Remove unnecessary Content-Type header since no body is sent
2026-03-11 22:40:30 -05:00
Hideeeeandhidezhao 18c3112dbd feat: Support for screenshot annotate on rust (#706)
Co-authored-by: hidezhao <hidezhao@tencent.com>
2026-03-11 22:25:28 -05:00
WenruiUteandClaude Opus 4.6 89f9c97ac2 fix: use correct Browserbase API to release sessions (#707)
Browserbase has no DELETE endpoint for sessions. The correct API is
POST /v1/sessions/:id with body { status: "REQUEST_RELEASE" }. The old
DELETE call returned an error that was silently swallowed, causing every
session to leak until the 30-min idle timeout.

Fixed in both Node.js (src/browser.ts) and native Rust
(cli/src/native/providers.rs) paths.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 22:09:58 -05:00
Iddo Gino db3d23d496 fix: use getDefaultTimeout() in CDP connect paths instead of hardcoded 10s (#704)
The connectViaCDP and connectToBrowserbase methods hardcoded
context.setDefaultTimeout(10000), ignoring the AGENT_BROWSER_DEFAULT_TIMEOUT
env var. This made page.goto time out after 10s on CDP connections even when
the env var was set to a higher value. Now both paths use getDefaultTimeout()
like all other connection modes.

Fixes #703
2026-03-11 22:08:31 -05:00
78c9aef3c9 fix: sanitize lone Unicode surrogates using toWellFormed() (#720)
* fix: sanitize lone Unicode surrogates in snapshot and response serialization (#635)

Pages with emoji/special characters can contain lone surrogates (e.g. \uD800
without a matching \uDC00-\uDFFF), causing serde_json to fail with
"unexpected end of hex escape" when parsing the JSON response.

- Add sanitizeSurrogates() to replace lone surrogates with U+FFFD in
  ariaSnapshot output
- Add sanitizeJsonSurrogates() safety net in serializeResponse for other
  response fields (page.title, page.content, etc.)
- Add tests for both sanitization paths

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: remove trivial "no surrogates unchanged" test

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* ci: retry flaky Rust test

* refactor: remove unnecessary sanitizeSurrogates from snapshot.ts

Chromium's ariaSnapshot() converts lone surrogates to literal text
(e.g. the 6-char string "\ud800"), not actual surrogate code points.
The real fix is sanitizeJsonSurrogates() in protocol.ts which handles
eval and other response paths where actual surrogates appear.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: use toWellFormed() instead of regex for lone surrogate sanitization

Upgrade tsconfig target/lib from ES2022 to ES2024 and replace the
manual regex-based surrogate sanitization with String.prototype.toWellFormed().
This is simpler, more readable, and relies on the standard API.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: remove trivial no-surrogate test

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 20:48:26 -05:00
417428463b Fix CDP connection failure on IPv6-first systems (#717)
Use 127.0.0.1 instead of localhost when constructing CDP URL from port
number, since Chrome only binds to IPv4. This prevents connection
failures on systems like Ubuntu 24.04 where localhost resolves to ::1.

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 04:15:21 -05:00
Walter Cheng def2fd90fa fix: inherit current viewport for recordings (#718) 2026-03-11 00:45:36 -05:00
Chris Tate d678058206 docs: Add missing vercel-sandbox skill and fix electron section (#713)
Updates the skills documentation to include the missing `vercel-sandbox` skill that was missing from both the available skills list and installation commands.

## Changes
- Added `vercel-sandbox` skill to the Available Skills list with description
- Added installation command for `vercel-sandbox` skill
- Added dedicated section for `vercel-sandbox` with key features and usage details
- Removed duplicate paragraph in the electron section

The `vercel-sandbox` skill enables running agent-browser + headless Chrome inside ephemeral Vercel Sandbox microVMs with features like snapshot startup, persistent workflows, and automatic OIDC authentication.

Fixes #712
2026-03-10 08:59:36 -05:00
Chris Tate c2794232ee fix deployment for example (#701) 2026-03-09 17:41:04 -05:00
Chris Tate f6c83e410b fix link (#700) 2026-03-09 17:36:01 -05:00
Umayr SheikandClaude Opus 4.6 9f41545216 docs: add viewport documentation to SKILL.md (#697)
The `set viewport` command is fully implemented but missing from the
agent-facing skill guide. Agents relying on SKILL.md would not know
they could resize the viewport, test responsive layouts, or use retina
scaling.

- Add viewport commands to Essential Commands section
- Add Viewport & Responsive Testing pattern with practical examples

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 17:34:06 -05:00
Chris Tate 82386b1c60 fix links (#699) 2026-03-09 17:33:40 -05:00
Chris Tate c309535691 sandbox docs (#698)
* sandbox docs

* format
2026-03-09 17:09:05 -05:00
Mason Williams d0651f14bc Make KERNEL_API_KEY optional for external credential injection (#687)
* Make KERNEL_API_KEY optional for external credential injection

When running inside environments with external credential injection
(e.g. Vercel Sandbox credentials brokering), the KERNEL_API_KEY env
var can be omitted. The network layer injects the Authorization header
on outbound requests to api.onkernel.com, so the API key never needs
to exist inside the sandbox.

If KERNEL_API_KEY is set, it's used as before. If not, requests are
sent without an Authorization header, allowing external injection.
Without either, the Kernel API returns 401.

Made-with: Cursor

* Make KERNEL_API_KEY optional in native Rust daemon too

Applies the same change to the native Rust connect_kernel() function
so both the Node.js and native code paths support external credential
injection.

Made-with: Cursor

* Address review feedback: fix type errors, cargo fmt, always send cleanup DELETE

- Fix kernelApiKey assignment: use ?? null for undefined -> null
- Fix closeKernelSession signature: accept string | undefined
- Always send DELETE on cleanup even without local API key (external
  injection covers it)
- Run cargo fmt on Rust code

Made-with: Cursor
2026-03-09 17:04:58 -05:00
Chris Tate 5bf9fedd58 fix environments demo (#696)
* fix

* fixes

* fixes

* update docs

* fixes

* fixes

* sandbox tokens

* better logging
2026-03-09 17:00:30 -05:00
Chris Tate c0a525c9e4 rate limits for demo (#695) 2026-03-09 15:43:25 -05:00
Chris Tateandctate cc3c70dc86 next.js example (#694)
* next.js guide

* better

* shadcn

* fixes

* fix: correct screenshot test assertion to check path instead of base64

The daemon returns { path: savePath } for screenshot commands, not base64.

* fix: cross-platform Chrome detection and gitignore hardening

- Replace hardcoded macOS Chrome path with findLocalChrome() that
  searches common paths on macOS, Linux, and WSL, with a clear error
  message when no Chrome is found.
- Add .env and .env*.local to .gitignore to prevent accidental
  secret commits.

* fix: correct Vercel deploy button repo URL to vercel-labs/agent-browser

* clean up

* demo

* next page

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
2026-03-09 15:24:44 -05:00
pixqc 3649787268 fix security docs url in readme (#690) 2026-03-09 15:13:21 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 00a0e0707e chore: version packages (#693)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-09 12:40:37 -05:00
Chris Tate 94cd888ecb chore: add patch changeset for release (#692) 2026-03-09 11:24:04 -05:00
Chris Tate 644a4f5b63 add scale factor to set viewport for retina screenshots (#691)
* device scale

* fix node.js daemon

* fix cargo fmt formatting for scale factor code

* fixes
2026-03-09 11:10:22 -05:00
a0bd0c2f0f Add webview support for Electron apps in native mode (#671)
* Add webview support for Electron apps in native mode

Fixes #580

* Fix cargo fmt violations in actions.rs and browser.rs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Revert unrelated refactors, keep only webview support changes

- Restore is_none_or (was changed to map_or unnecessarily)
- Restore single-if WebDriver check (was split into nested ifs)
- Restore simple needs_relaunch logic (was expanded into 4 branches)
- Restore find_frame signature (unused selector param was added)
- Restore flat download handler condition (was nested unnecessarily)
- Restore wait_or_kill and graceful close() to preserve cookie flushing

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 17:41:40 -05:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 2bab729f26 chore: version packages (#684)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-08 13:24:22 -05:00
Chris Tate 94521e7a8c chore: add minor changeset for release (#683) 2026-03-08 11:22:56 -05:00
d9387aae58 ci: add clippy check to Rust CI workflow (#675)
Add `cargo clippy -- -D warnings` step to the Rust CI job so that
clippy warnings fail the build. Also fix the one new lint
(`unnecessary_map_or`) introduced in the current stable clippy.

Fixes #672

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 00:41:56 -06:00
aba2353112 Fix clippy warnings across CLI codebase (#654)
* Fix clippy warnings across CLI codebase

Fixes #653

* Fix remaining items_after_test_module clippy warnings

Move functions defined after `mod tests` blocks to before the test
modules in recording.rs and webdriver/client.rs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 16:18:51 -06:00
68cebe5192 Fix Chrome extensions not loading by forcing headed mode when extensions present (#652)
* Fix Chrome extensions not loading by forcing headed mode when extensions present

Fixes #640

* Restore wait_or_kill() and add tests for headless+extensions logic

Restore the ChromeProcess::wait_or_kill() method that was accidentally
removed. It is still referenced by BrowserProcess in browser.rs and is
needed for graceful shutdown / cookie persistence (PR #650).

Add unit tests verifying --headless=new is omitted when extensions are
present.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix window-size leak in headed+extensions mode and remove unused channel option

- Skip --window-size=1280,720 when extensions force headed mode (native)
- Remove unexplained channel: 'chromium' from extensions launch path (TS)
- Add window-size assertion to existing extension test

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: ctate <366502+ctate@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 14:58:18 -06:00
Qiaochu Hu f262ff1bf3 docs: improve snapshot usage guidance and add reproducibility check (#630)
Fixes #566: Clarify snapshot vs snapshot -i usage
- Add guidance that snapshot -i is for clickable/fillable elements
- Add guidance that snapshot (no flag) is for reading page content

Fixes #565: Add reproducibility verification before collecting evidence
- Add guidance to verify issues are reproducible before recording video
- Prevent wasting turns on false positives
2026-03-06 14:31:04 -06:00
Li Yang 788ad0e61f chore: add cargo fmt check to Rust CI and fix existing violations (#620)
TypeScript CI has prettier --check but Rust CI only runs cargo test.
Add cargo fmt --check to catch formatting issues early, and fix the
8 pre-existing formatting violations on main.
2026-03-06 13:32:26 -06:00
Chris Tate b7e7a2548e fix: persist auth cookies on close in native mode (#650) 2026-03-06 12:46:03 -06:00
Chris Tate 492830accb Fix: Suppress Google Translate bar in native headless mode (#649)
Fixes #617
2026-03-06 12:36:32 -06:00
Chris Tate 7acde7e29a fix: native auth login fails due to incompatible encryption format (#648)
* fix: native auth login fails due to incompatible encryption format

* fixes

* fixes
2026-03-06 12:31:12 -06:00
Chris Tate 0da54c7038 lightpanda (#646)
* lightpanda

* lightpanda benchmarks

* improvements

* fixes

* improvements
2026-03-06 11:16:37 -06:00
Chris Tate 36c2e06f89 add benchmarks (#637) 2026-03-06 00:46:59 -06:00
layla 8f6ad817f1 Fix dialog dismiss command parsing (#605) 2026-03-04 17:14:12 -06:00
Li Yang de5ea1d8cf fix: use reqwest for CDP port discovery instead of broken hand-rolled HTTP client (#619)
reqwest_get_string() was hand-rolling HTTP/1.1 over raw TCP despite reqwest
being an existing dependency. The hand-rolled implementation had two bugs:

1. URL path parsing: url.find('/') matched the first '/' in 'http://',
   producing path '//127.0.0.1:9222/json/version' instead of '/json/version'

2. read_to_end() hangs: Chrome's DevTools HTTP server ignores Connection: close
   and keeps the socket open, so read_to_end() waits for EOF that never comes

This caused 'agent-browser --cdp <port>' to always timeout when AGENT_BROWSER_NATIVE=1.

Fix: replace 49 lines of broken TCP code with reqwest::get(), which was
already in Cargo.toml.
2026-03-04 16:32:01 -06:00
Chris Tate 139dd0ec5a fix: surface daemon startup errors instead of opaque timeout message (#614)
When the daemon process crashes during startup (e.g., missing
Playwright), stderr was discarded via Stdio::null(), so users only
saw "Daemon failed to start (port: ...)" with no diagnostic info.

Now captures daemon stderr via Stdio::piped() and detects early process
exit with try_wait() during the startup polling loop. If the daemon
crashes, the actual error from stderr is shown to the user.

Also forwards --debug flag to the daemon process as AGENT_BROWSER_DEBUG
so debug logging works end-to-end.

Closes #56
2026-03-04 01:05:33 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 794a77e26e chore: version packages (#613)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-04 01:02:34 -06:00
Chris Tate 7d2c8957ac chore: add patch changeset for release (#612) 2026-03-04 00:30:54 -06:00
Li Yang eaa968e229 fix: suppress spurious --native warning when set via env var (#611)
* fix: suppress spurious --native warning when set via env var

When AGENT_BROWSER_NATIVE=1 is set via environment variable, every
command after the first would warn:

  ⚠ --native ignored: daemon already running.

This is a false positive — the daemon was already spawned in native
mode and inherited the env var. The warning should only fire when
--native is explicitly passed on the CLI to an already-running daemon.

Add cli_native flag (consistent with existing cli_* pattern) to
distinguish CLI origin from env var origin.

* fix: add flag to test cfg

* fix: cli_native should track flag presence, not value

--native false on CLI should still warn when daemon is already
running, since the user is explicitly trying to change the mode.
2026-03-04 00:17:14 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 7edc5d596c chore: version packages (#610)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-03 23:56:46 -06:00
Chris Tate 01ac5574d4 chore: add patch changeset for release (#609) 2026-03-03 23:07:56 -06:00
Chris Tate e5fd26eb9e headed mode (#607)
* headed mode

* fixes

* fixes

* docs

* fixes

* fixes

* fixes
2026-03-03 22:34:07 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> a493d02c66 chore: version packages (#604)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-03 17:59:02 -06:00
Chris Tate c4180c8cb1 chore: add patch changeset for release (#603) 2026-03-03 17:51:29 -06:00
Chris Tate 56260f68b0 Native: auto-detect sandbox/container environments for Chrome launch (#602)
Fixes #600

Three improvements to `--native` Chrome launching:

- `find_chrome()` now falls back to Playwright's browser cache (`~/.cache/ms-playwright/`) when no system Chrome is found
- Auto-detect containers/VMs (root, Docker, Podman, cgroups) and inject `--no-sandbox`
- Chrome stderr is now captured and included in launch error messages, with a hint when sandbox errors are detected
2026-03-03 17:45:23 -06:00
Chris Tate 324a9e4e0c windows 8 cores (#599)
* windows 8 cores

* add workflow dispatch
2026-03-03 17:26:22 -06:00
Chris Tate 7f42eed031 faster ci (#598) 2026-03-03 16:45:57 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> c10981413f chore: version packages (#597)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-03 16:18:08 -06:00
Chris Tate 05018b309a prepare v0.16.0 (#596) 2026-03-03 16:09:39 -06:00
Chris Tate 9d0454d229 fix: switch from native-tls to rustls for cross-compilation (#595)
The native PR introduced tokio-tungstenite and reqwest with native-tls,
which depends on openssl-sys (C library). This breaks the release
workflow's cargo-zigbuild cross-compilation on Linux because zig's C
compiler can't find the system OpenSSL headers.

Switch to rustls (pure Rust TLS) which has zero C dependencies and
cross-compiles trivially. Also shrinks the dependency tree.
2026-03-03 15:45:20 -06:00
Chris Tate 51f5fa484c native (#594)
* Native Rust rewrite of agent-browser daemon

Single-binary Rust implementation replacing the Node.js/Playwright daemon
with direct CDP (Chrome DevTools Protocol) communication. Includes full
command parity, WebDriver/Safari/iOS backend routing, request tracking,
frame context management, CDP protocol codegen, and comprehensive tests.

* improvements

* fix ci

* fixes

* faster builds
2026-03-03 15:15:57 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 857c0b25df chore: version packages (#591)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-03 08:21:58 -06:00
Chris Tate 62241b50e9 chore: add patch changeset for release (#589) 2026-03-03 08:08:02 -06:00
Chris Tate c6a33b6338 fix(windows): resolve daemon startup failures and Git Bash compatibility (#582)
* fix(windows): resolve daemon startup failures and Git Bash compatibility

Three root causes behind 27 open Windows issues:

1. Path::canonicalize() returns \\?\ prefixed paths on Windows that
   Node.js cannot parse, preventing daemon startup. Strip the prefix
   before passing to Node. (fixes #522, #390, #56, #25, #37, #89)

2. Git Bash/MSYS2 translates Unix-style paths and resolves node to
   a shell wrapper script. Use node.exe explicitly and set
   MSYS_NO_PATHCONV/MSYS2_ARG_CONV_EXCL to prevent argument mangling.
   (fixes #148, #108, #171)

3. postinstall fixWindowsShims() hardcoded x64 arch and did not verify
   the native binary exists before rewriting shims. Now detects arch
   dynamically and validates the binary path. (fixes #262)

Also:
- Error messages now show TCP port on Windows instead of Unix socket path
- Windows CI expanded to test full daemon lifecycle (open, snapshot, close)

* fix(windows): strip \\?\ prefix in auth-cli path (fixes #579)

Same canonicalize() issue as the daemon spawn path, but in
run_auth_cli() which passes the script path to Node.js.
2026-03-03 08:00:14 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> d97e2016f5 chore: version packages (#585)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-02 17:16:52 -06:00
Chris Tate 6aea316c82 chore: add patch changeset for release (#583) 2026-03-02 17:10:32 -06:00
Chris Tate c7fa10cb1b remove skill creator (#581) 2026-03-02 16:26:19 -06:00
Giulio Leone b304a4188c fix: correct misleading output for cookies clear and tab close (#556) (#563)
Bug 1: `cookies clear` printed 'Request log cleared' instead of 'Cookies cleared'
because the output handler matched the generic `{ cleared: true }` response shape
without checking the action context. Now uses the `action` parameter to distinguish
`cookies_clear` from `requests --clear`.

Bug 2: `tab close` printed 'Browser closed' instead of 'Tab closed' because the
output handler matched the generic `{ closed: ... }` response shape without checking
the action context. Now uses the `action` parameter to distinguish `tab_close` from
`close` (full browser close).

Closes #556
2026-03-01 12:23:23 -06:00
neilmixandClaude Opus 4.6 e912f541f2 fix: treat EPERM from kill(pid, 0) as "process exists" in daemon liveness checks (#564)
Per POSIX, kill(pid, 0) returns EPERM when the process exists but the
caller lacks permission to signal it, and ESRCH when it does not exist.
The daemon liveness checks in both the Rust CLI and TypeScript daemon
treated any kill failure as "not running", which is incorrect when
running inside a macOS sandbox that restricts signal delivery to
(target self). This caused the CLI to delete the real daemon's socket
and PID files, then spawn a duplicate daemon.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 10:12:37 -06:00
7238b7da4c fix: resolve unnamed element refs matching multiple elements (#573)
* fix: resolve unnamed element refs matching multiple elements (#500)

When a page has one unnamed button among several named buttons,
clicking its ref fails with "matched N elements" because the
locator `getByRole('button')` matches all buttons on the page.

Normalize unnamed interactive elements to `name: ""` so the
selector becomes `getByRole('button', { name: "", exact: true })`
which matches only buttons with empty accessible names.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: remove dead code branch in buildSelector

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: make RefMap.name required string, remove dead code branches

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: hyunjinee <leehj0110@kakao.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 09:42:05 -06:00
Chris Tate 79d8dfe34c add skills to docs (#576) 2026-03-01 09:02:06 -06:00
Chris Tate 14ec5b5ffa add slack skill (#571) 2026-02-28 12:03:50 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 79b05877a8 chore: version packages (#548)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-26 11:45:22 -06:00
Chris Tate 7bd8ce937b chore: add patch changeset for release (#546) 2026-02-26 11:36:47 -06:00
Ryan Siddle b455a58aa2 fix: preserve chrome-extension:// and chrome:// URL schemes in CLI (#410)
The CLI's URL normalization was auto-prepending https:// to any URL
whose scheme wasn't in the allowlist (http, https, about, data, file).
This caused chrome-extension:// URLs to become
https://chrome-extension//... which fails with ERR_NAME_NOT_RESOLVED,
preventing navigation to extension pages (popup, side panel, options).

Add chrome-extension:// and chrome:// to the open command's scheme
allowlist, and update the record start/restart commands to preserve
any URL that already contains :// instead of only checking for http.

Fixes #409
2026-02-26 11:30:02 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> b59dc4c82c chore: version packages (#545)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-25 15:57:43 -06:00
Chris Tate 2e38882664 prepare v0.15 (#544)
* add security hardening features

- Add authentication vault (`auth save/login/list/show/delete`) so credentials are stored locally and never exposed to the LLM (fixes Snyk W007)
- Add `--content-boundaries` flag to wrap page-sourced output in structural markers, helping LLMs distinguish tool output from untrusted page content (fixes Snyk W011)
- Add `--allowed-domains` flag to restrict browser navigation to trusted domains
- Add `--action-policy` for static allow/deny gating of action categories, with opt-in `--confirm-actions`/`--confirm-interactive` for orchestrator or human-in-the-loop confirmation
- Add `--max-output` flag to truncate large page outputs, preventing context flooding
- New docs page at /security, updated README, SKILL.md, CLI help text, and templates

* fixes

* fixes

* fixes

* fixes

* fixes

* fixes

* fixes

* docs

* prepare v0.15
2026-02-25 15:47:26 -06:00
Chris Tate bc1e917e87 add security hardening features (#543)
* add security hardening features

- Add authentication vault (`auth save/login/list/show/delete`) so credentials are stored locally and never exposed to the LLM (fixes Snyk W007)
- Add `--content-boundaries` flag to wrap page-sourced output in structural markers, helping LLMs distinguish tool output from untrusted page content (fixes Snyk W011)
- Add `--allowed-domains` flag to restrict browser navigation to trusted domains
- Add `--action-policy` for static allow/deny gating of action categories, with opt-in `--confirm-actions`/`--confirm-interactive` for orchestrator or human-in-the-loop confirmation
- Add `--max-output` flag to truncate large page outputs, preventing context flooding
- New docs page at /security, updated README, SKILL.md, CLI help text, and templates

* fixes

* fixes

* fixes

* fixes

* fixes

* fixes

* fixes

* docs
2026-02-25 15:33:20 -06:00
Chris Tate c0e2b80f8c add dogfood skill for agent-driven exploratory qa (#538)
* dogfood skill

* evals

* haiku

* fixes

* caching

* fixes

* don't use npx
2026-02-24 11:35:50 -06:00
Chris Tate f319195974 add --selector flag to scroll command (#537)
* add --selector flag to scroll command

The `scroll` command uses `window.scrollBy()`, which has no effect on apps
that use custom scrollable containers (e.g. a nested div with overflow-y: auto).

The backend `handleScroll` already supports a `selector` parameter, but the CLI
never exposed it. This adds `-s` / `--selector` to the `scroll` command so users
can target a specific scrollable element:

    agent-browser scroll down 500 --selector "div.scroll-container"

Also fixes the backend to apply `direction`/`amount` when a selector is present
(previously those fields were only used in the no-selector branch).

Closes #501

* fixes
2026-02-24 07:40:46 -06:00
Chris Tate 77f2caa1bc feat: add --download-path option (#536)
* feat: add --download-path option

Adds a `--download-path` flag (and `AGENT_BROWSER_DOWNLOAD_PATH` env / `downloadPath` config key) to set a default download directory for browser downloads.

Without this, Playwright stores downloads in a temp directory that is deleted when the browser closes. The new option passes through to Playwright's `downloadsPath` on `launch()` and `launchPersistentContext()`.

Fixes #507

* improvements

* fixes

* fixes
2026-02-24 07:22:55 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 2fe7394dbe chore: version packages (#535)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-23 11:03:57 -06:00
Chris Tate b7665e52b6 v0.14.0 changeset (#534)
* v0.14.0 changeset

* fixes

* improvements
2026-02-23 10:48:07 -06:00
shohuandshohu 16c4ef2da6 fix(daemon): add backpressure control and command serialization to prevent IPC EAGAIN (#529)
- Add AGENT_BROWSER_DEFAULT_TIMEOUT env var to override Playwright's
  default 60s timeout (CDP/recording 10s timeouts unaffected)
- Add backpressure-aware safeWrite() that waits for drain when socket
  buffer is full, preventing data loss under load
- Serialize command execution per socket via queue to prevent concurrent
  writes that cause buffer contention

These daemon-side fixes complement #329 (CLI-side EAGAIN retry) by
addressing the root causes: Playwright operations that outlast the
CLI's IPC timeout, and concurrent socket.write() calls that overflow
the kernel buffer.

Tested with heavy React app (1000+ DOM nodes) — 10 consecutive
snapshot commands complete without os error 35/11.

Refs #322

Co-authored-by: shohu <shohu@users.noreply.github.com>
2026-02-23 10:06:06 -06:00
ProviandClaude Opus 4.6 ad6e206a90 feat: add keyboard command for raw keyboard input (#521)
Adds `keyboard type` and `keyboard insertText` subcommands that
operate on the currently focused element without requiring a selector.

Essential for contenteditable editors (Lexical, ProseMirror, CodeMirror,
Monaco) where `type <selector>` doesn't trigger the editor's internal
event pipeline (beforeinput/DOM mutation).

- `keyboard type <text>` — page.keyboard.type() with real keystrokes
- `keyboard insertText <text>` — page.keyboard.insertText()

Note: `keyboard press` intentionally omitted — the existing top-level
`press` command already operates on current focus.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 09:44:08 -06:00
Lukas Malkmus f10f3f6425 cli: only warn about --annotate when explicitly passed via CLI (#531)
The warning "⚠ --annotate only applies to the screenshot command" fires
on every non-screenshot command when annotate is set in config. This is
noisy for users who set it as a persistent default.

Add cli_annotate tracking (matching the existing cli_* pattern) so the
warning only fires when --annotate is passed as a CLI flag.
2026-02-23 09:24:19 -06:00
Chris Tate c0f8f32a55 fix remote debugging (#533)
* fix remote debugging

* debug log
2026-02-23 09:19:21 -06:00
Chris Tate 12d79e4428 add --color-scheme flag for persistent dark/light mode (#528)
Fixes #519. Playwright defaults `colorScheme` to `light` on all new contexts, overriding the browser/OS dark mode setting. This is especially disruptive in CDP mode, where every reconnection resets the scheme. The `set media dark` command also didn't persist its choice to new tabs or pages.

- Add `--color-scheme <dark|light|no-preference>` flag, config key (`colorScheme`), and env var (`AGENT_BROWSER_COLOR_SCHEME`)
- Store the preference in `BrowserManager` and automatically apply it to all new contexts (via Playwright's context option) and all new pages (via `page.emulateMedia` in `setupPageTracking`)
- `set media dark/light` now also persists its choice for subsequent pages and tabs
2026-02-23 01:50:17 -06:00
Chris Tate 467b830974 fix state load failing when no browser is running (#527)
`state load` always fails with "Cannot load state while browser is running" even when no browser is running, making the command completely unusable (#526).

The daemon's auto-launch logic starts a browser before `state_load` gets to handle the command. This adds `state_load` to the exclusion list alongside `launch` and `close`, so `handleStateLoad` can perform its own launch with the state file.
2026-02-23 00:56:48 -06:00
Chris Tate 4412899379 update header/og font (#524) 2026-02-22 16:09:37 -06:00
Chris Tate fca9d7ab5d fix og (#515) 2026-02-20 08:49:53 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 2b8a51b9a6 chore: version packages (#513)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-20 00:14:32 -06:00
Chris Tate ebd87173e4 chore: add minor changeset for release (#512) 2026-02-20 00:06:52 -06:00
Chris Tate d5a667ea2d diff (#510)
* diff

* fixes

* fixes

* fixes

* fixes

* fixes

* better docs
2026-02-19 23:51:09 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 9732031087 chore: version packages (#505)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-18 22:41:17 -06:00
Chris Tate 69ffad0f04 chore: add minor changeset for release (#504) 2026-02-18 22:31:37 -06:00
Chris Tate e2e259f1e2 annotated screenshots (#503)
* screenshot annotation

* fixes

* fix CI checks

* fixes

* fixes

* fixes

* fixes

* fixes
2026-02-18 22:20:01 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 06a32f4191 chore: version packages (#499)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-18 00:40:56 -06:00
Chris Tate c6fc7df443 chore: add patch changeset for release (#498) 2026-02-18 00:34:52 -06:00
Chris Tate 98f49da196 chaining (#497) 2026-02-18 00:24:59 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 85340cb432 chore: version packages (#496)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-17 23:33:44 -06:00
Chris Tate 5dc40b4ea4 chore: add minor changeset for release (#495) 2026-02-17 23:28:34 -06:00
Andrew ImmandChris Tate 59fa36b6e2 feat: Enable capture of profiling data (#290)
* feat: Enable capture of profiling data

Adding a new set of commands:
```
agent-browser profiler start

agent-browser profiler stop trace.json
```

With this, agents can start a profiling trace, perform a set of actions, and then extract the profiling data for analysis.

**Note:** I was originally going to call it `agent-browser profile` but I realized that might cause confusion with the `--profile` flag

CDP supports a couple commands for starting/stopping a trace.
When a trace is running, it emits events that need to be picked up.
We store these locally in the daemon until the trace is completed.
When the final event is received, we dump all of them into an output file.

That file can be loaded directly into chrome devtools or another analysis tool to visualize what happened during the agentic run.

Added some basic rust tests for parsing the commands (since they have some optional / required args)

TS daemon adds ~6 tests to make sure the profiling lifecycle (including saving the output file) works as intended

* add docs

* fixes

* fixes

---------

Co-authored-by: Chris Tate <chris@ctate.dev>
2026-02-17 23:11:11 -06:00
Chris Tate 9ca182a4df add config (#494)
* add config

* improvements

* cleaner flags

* fixes

* fixes
2026-02-17 22:27:44 -06:00
Chris Tate 76df589aea update docs (#493) 2026-02-17 21:37:41 -06:00
Chris Tate 19dd2d0c0b fix(#491): auto-disable viewport for --start-maximized and --window-size args (#492)
Fixes #491

When `--start-maximized` or `--window-size` is passed as a browser arg, Playwright's default viewport (1280x720) overrides the browser's own window sizing, making those flags have no effect on the page content.

This change auto-detects those args and sets `viewport: null` so Playwright defers to the browser's window size. Explicit viewport values still take priority.

Also allows `viewport: null` in the launch protocol for agents that want to disable viewport emulation directly.
2026-02-17 20:27:38 -06:00
Chris Tate f9b33ac23d fix: reject invalid --headers JSON, empty frame commands, and --cdp + --extension combo (#488)
## Summary

- Return a `ParseError` when `--headers` receives invalid JSON instead of silently dropping the headers and proceeding
- Reject `frame` commands that provide no `selector`, `name`, or `url` (previously returned `{ switched: true }` without doing anything)
- Add missing mutual exclusion check for `--cdp` + `--extension` (extensions require a local browser, not a CDP connection)
2026-02-16 23:55:40 -06:00
Chris Tate 01efe418af fix: resolve 3 protocol bugs, improve CLI and snapshot code quality (#487)
## Summary

- Fix `allowFileAccess` being silently stripped from launch commands by adding it to the Zod schema in `protocol.ts` (the `--allow-file-access` CLI flag was not reaching the browser)
- Fix `trace stop` requiring a path argument despite help text documenting it as optional -- now works with or without a path
- Fix `addscript`/`addstyle` silently succeeding when neither `content` nor `url` is provided -- now returns a validation error
- Replace hardcoded ANSI escape code with `color::error_indicator()` in `main.rs` to respect `NO_COLOR`
- Fix double-parse pattern and add descriptive expect messages in `commands.rs`
- Fix incomplete string escaping in `snapshot.ts` `buildSelector` (use `JSON.stringify` instead of manual quote escaping)
- Simplify redundant ternary in `snapshot.ts` cursor-interactive role assignment
- Sync docs changelog with CHANGELOG.md (v0.8.1 through v0.10.0)
2026-02-16 22:47:31 -06:00
Chris Tate b7b0da5dfa docs: fix 6 documentation issues (#303, #245, #186, #134, #61, #73) (#486)
* docs: fix 6 documentation issues (#303, #245, #186, #134, #61, #73)

Addresses six open documentation issues in a single pass:

- **#303** -- Add `npx agent-browser` usage across README, SKILL.md, docs site, and `--help` output for zero-install experience. Global install is recommended as the fastest path (native Rust CLI vs Node.js indirection with npx).
- **#245** -- Document Claude Code skill installation with `npx skills add vercel-labs/agent-browser`
- **#186** -- Split installation instructions into Global (recommended), Quick Start (npx), and Project (local dependency) sections with clear guidance on when to use each
- **#134** -- Add "Why agent-browser over playwright-mcp?" comparison table to README covering output format, element selection, protocol, sessions, performance, mobile, cloud, and streaming
- **#61** -- Add "Timeouts and Slow Pages" section to SKILL.md documenting the 60s default timeout, all `wait` variants, and guidance for slow websites
- **#73** -- Replace stale `cp node_modules/...` advice with `npx skills add`, add warning against copying SKILL.md manually, add "Session Management and Cleanup" section to SKILL.md

* remove section

* fix doc
2026-02-16 22:14:43 -06:00
Giulio LeoneandCopilot d441843cca fix(#469): deduplicate cursor-interactive elements in snapshot -C (#475)
Three fixes to eliminate duplicate entries:
1. Skip elements that only inherit cursor:pointer from a parent
   (the parent element is captured instead)
2. Broaden dedup by extracting all quoted text from the ARIA tree,
   not just ref names
3. Add accepted cursor elements to the dedup set to prevent
   multiple DOM elements with the same text from duplicating

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-02-16 11:55:08 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 9cbb363190 chore: version packages (#452)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-13 14:06:37 -06:00
Chris Tate 1112a160bd chore: add minor changeset for release (#451) 2026-02-13 13:58:54 -06:00
Aman panditandChris Tate 697b788af0 feat: add session persistence, state management commands, and --new-tab click (#184)
Rebased and fixed implementation of PR #184 features on current main:

Session persistence:
- --session-name flag and AGENT_BROWSER_SESSION_NAME env var auto-save/restore
  cookies and localStorage across browser restarts
- State files stored in ~/.agent-browser/sessions/ with owner-only permissions
- AES-256-GCM encryption via AGENT_BROWSER_ENCRYPTION_KEY env var
- Auto-expiration of old state files (AGENT_BROWSER_STATE_EXPIRE_DAYS, default 30)

State management commands:
- state list: list saved state files with metadata
- state show <file>: display state summary (cookies, origins, domains)
- state rename <old> <new>: rename state files
- state clear [name] [--all]: clear saved states
- state clean --older-than <days>: delete expired states

New --new-tab flag for click command:
- Opens link href in a new tab instead of navigating the current tab

Security hardening:
- Session name validation prevents path traversal (CLI + daemon)
- safeHeaderMerge prevents prototype pollution in header merging
- WebSocket stream server binds to 127.0.0.1 only
- State files written with 0o600 permissions

Fixes applied over the original PR:
- Use color.rs module instead of hardcoded ANSI escape codes
- Align CLI output field names with daemon response format
- Add CLI-level --session-name validation (not just daemon-side)
- Avoid adding "DOM" to tsconfig.json lib (use proper typing in evaluate)
- Keep version at 0.9.3 (matches current main)
- Centralize session name validation in daemon.ts helper
- Update all documentation (README, SKILL.md, docs site, --help output)

Co-authored-by: Chris Tate <chris@ctate.dev>
2026-02-13 11:56:20 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> cdd10ebb54 chore: version packages (#438)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-13 10:59:44 -06:00
Mathias Lafeldt 323b6cdd9d Fix clippy lints (#399)
* cargo fmt

* fix: remove redundant `use libc` import (clippy::single_component_path_imports)

* fix: use `.first()` instead of `.get(0)` (clippy::get_first)

* fix: use `.copied()` instead of `.map(|s| *s)` (clippy::map_clone)

* fix: allow too_many_arguments on ensure_daemon (clippy::too_many_arguments)

* fix: use `then_some` instead of `then` with closure (clippy::unnecessary_lazy_evaluations)

* fix: use pattern match instead of redundant guard (clippy::redundant_guards)

* fix: use pattern match instead of redundant guard in commands.rs (clippy::redundant_guards)

* fix: use `contains()` instead of `iter().any()` for simple equality (clippy::manual_contains)

* Add changeset
2026-02-13 10:44:35 -06:00
Anion 604c0b9632 fix: add missing cursor field to snapshot command schema (#435)
The `-C`/`--cursor` flag was added to the CLI parser and snapshot
implementation in #374, but the Zod schema in protocol.ts was not
updated. This caused the `cursor` field to be silently stripped
during command validation, so cursor-interactive element detection
never ran.

Fixes #434
2026-02-13 08:29:13 -06:00
Chris Tate 4b776c7ba6 fix: move skill-creator out of skills/ into .agents/skills/ (#437)
- Moves `skills/skill-creator/` to `.agents/skills/skill-creator/` so that only the project-specific `agent-browser` skill remains in `skills/`
- Non-agent-browser skills like `skill-creator` are generic tooling and don't belong alongside the product skill, which was confusing to users
2026-02-13 08:26:50 -06:00
Chris Tate 9a01e8b3b5 feat: add --auto-connect flag to discover and connect to running Chrome (#432) 2026-02-12 18:37:37 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 9c20979bfe chore: version packages (#430)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-12 17:47:59 -06:00
vercel[bot]andVercel <vercel[bot]@users.noreply.github.com> 14029d2450 Add Vercel Web Analytics to Next.js (#428)
Implemented Vercel Web Analytics for Next.js (App Router)

## Summary
Successfully installed and configured @vercel/analytics package for the Next.js documentation site.

## Changes Made

### 1. Installed Dependencies
- Installed `@vercel/analytics` package using pnpm
- Command executed: `pnpm install @vercel/analytics`

### 2. Modified Files
- **docs/src/app/layout.tsx**
  - Added import: `import { Analytics } from "@vercel/analytics/next";`
  - Added `<Analytics />` component inside the `<body>` tag, right after `<SpeedInsights />`
  - Placement follows best practices for App Router projects

### 3. Updated Lock Files
- **docs/package.json** - Added @vercel/analytics to dependencies
- **docs/pnpm-lock.yaml** - Updated with new dependency tree

## Implementation Details
- This is an App Router project (uses `app/` directory structure)
- The Analytics component was added to the root layout file at `docs/src/app/layout.tsx`
- Followed the same pattern as the existing SpeedInsights component
- Preserved all existing code structure and formatting

## Verification
 Build completed successfully with no errors
 TypeScript compilation passed
 Modified file passes ESLint checks
 All 15 static pages generated correctly

## Notes
- The project already had @vercel/speed-insights installed, so the pattern for adding Analytics was consistent
- Pre-existing lint errors in mobile-nav-context.tsx and theme-toggle.tsx are unrelated to this change
- Lock files are properly updated and staged as per dependency changes

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
2026-02-12 17:41:49 -06:00
Chris Tate d03e238516 chore: add patch changeset for release (#429) 2026-02-12 17:41:41 -06:00
Chris Tate 221d22c14f fix: resolve stale session, ref resolution and cursor-ref collision bugs (#427) 2026-02-12 17:32:58 -06:00
vercel[bot]andVercel <vercel[bot]@users.noreply.github.com> b3b9fccd72 Add Vercel Speed Insights to Next.js (#420)
Successfully implemented Vercel Speed Insights for Next.js

## Changes Made

### 1. Installed @vercel/speed-insights package
- Used pnpm (the project's package manager) to install @vercel/speed-insights@1.3.1
- Updated package.json with the new dependency
- Updated pnpm-lock.yaml with the complete dependency tree

### 2. Integrated SpeedInsights component into root layout
- Modified: docs/src/app/layout.tsx
  - Added import: `import { SpeedInsights } from "@vercel/speed-insights/next"`
  - Added `<SpeedInsights />` component inside the `<body>` tag, placed after all other content
  - This follows the recommended pattern for Next.js 13.5+ with App Router

## Implementation Details

The project uses:
- Next.js 16.1.1 with App Router
- TypeScript
- pnpm as the package manager

The SpeedInsights component was added to the root layout (app/layout.tsx) which is the correct approach for Next.js 13.5+ projects using the App Router. The component is placed at the end of the body tag to ensure it loads after the main content.

## Verification

 Build completed successfully - no compilation errors
 All changes staged with git including the lockfile
 Package installed and integrated correctly

Note: Pre-existing linter warnings in mobile-nav-context.tsx and theme-toggle.tsx were not introduced by these changes and remain unchanged.

## Files Modified

1. docs/package.json - Added @vercel/speed-insights dependency
2. docs/pnpm-lock.yaml - Updated with new package dependencies
3. docs/src/app/layout.tsx - Added SpeedInsights import and component

The implementation follows Vercel's official documentation and best practices for Next.js App Router applications.

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
2026-02-12 17:28:59 -06:00
Chris Tate ec9c6a2ed9 fix: pass --executable-path to launch command in CLI (#424) 2026-02-12 13:28:25 -06:00
Chris Tate 03a8cb95d0 fix write file (#421)
* fix write file

* fix typo
2026-02-11 19:18:48 -06:00
Chris Tate 66a11aeb4c better chat (#416)
* better chat

* fixes

* fix
2026-02-11 14:17:53 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> ffe29b8a26 chore: version packages (#408)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-10 14:15:12 -06:00
Chris Tate 76d23db1a9 chore: add patch changeset for release (#407) 2026-02-10 14:03:06 -06:00
Chris Tate 67cdc293f0 fix: allow localhost origins in stream server ws connections (#406) 2026-02-10 13:53:55 -06:00
Chris Tate dc53fedac0 fix: auto-switch to externally opened tabs (#404)
Update `setupContextTracking` in `BrowserManager` to auto-switch `activePageIndex` to newly opened tabs and invalidate the CDP session accordingly. This mirrors what `newTab()` and `newWindow()` already do for explicitly created tabs, and aligns CLI behavior with how real browsers focus newly opened tabs.

Fixes #384
2026-02-10 13:20:01 -06:00
Chris Tate cd4473aa64 fix: forward --exact flag to Playwright for role, label, and placeholder locators (#402) (#403)
Summary

- The `--exact` flag on `find role`, `find label`, and `find placeholder` was accepted by the CLI but silently dropped by the server. The Zod validation schema, TypeScript types, and action handlers all lacked the `exact` field, so it was stripped before reaching Playwright's `getByRole`, `getByLabel`, and `getByPlaceholder` calls.
- Added `exact` to the schema, types, and handler for all three locators so the flag is forwarded to Playwright as intended.
- Added tests confirming `exact: true` survives protocol parsing for `getbyrole`, `getbylabel`, and `getbyplaceholder`.

Fixes #402
2026-02-10 09:07:47 -06:00
Chris Tate 8e5ead85c8 fix build (#401) 2026-02-09 12:10:40 -06:00
Chris Tate e8ceafcbe1 docs: mdx, light/dark mode, ask (#400) 2026-02-09 11:16:21 -06:00
n33pm 4d8097a56f docs: add Homebrew installation instructions for macOS (#385) 2026-02-06 13:23:06 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 76c30690f5 chore: version packages (#377)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-05 00:38:29 -06:00
Chris Tate ae349451b7 chore: add patch changeset for release (#376) 2026-02-05 00:30:44 -06:00
Chris Tate 07c2372766 feat: add --allow-file-access flag for file:// URL support (#375)
* feat: add --allow-file-access flag for file:// URL support

Adds the ability to open and interact with local files using file:// URLs.
This enables use cases like viewing local PDFs, testing local HTML files,
and allowing JavaScript to access other local files via XHR.

The flag adds Chromium's --allow-file-access-from-files and --allow-file-access
launch arguments. Only supported in Chromium browsers.

Fixes #345

* fix: add cli_allow_file_access tracking to prevent spurious warning

When --allow-file-access is set via AGENT_BROWSER_ALLOW_FILE_ACCESS env var
(not CLI), don't warn about the flag being ignored when daemon is already running.
2026-02-05 00:24:28 -06:00
Chris Tate 74be667c80 feat: add cursor-interactive element detection in snapshots (#374)
* fix: only warn about ignored flags when explicitly passed via CLI

The warning about launch-time options being ignored (when daemon is
already running) was incorrectly shown when options were set via
environment variables like AGENT_BROWSER_EXECUTABLE_PATH, even when
no CLI flag was passed.

Now the warning only appears when flags are explicitly passed on the
command line, not when values come solely from environment variables.

Fixes #372

* feat: add cursor-interactive element detection in snapshots

Add -C/--cursor flag to snapshot command that detects clickable elements
that don't have proper ARIA roles but are interactive based on:
- cursor: pointer CSS style
- onclick attribute/handler
- tabindex attribute

This helps with modern web apps that use custom divs/spans as buttons.

Fixes #366

* fix: add cursor option to getSnapshot type signature
2026-02-04 23:44:58 -06:00
Chris Tate d34ce8c2d0 fix: only warn about ignored flags when explicitly passed via CLI (#373)
The warning about launch-time options being ignored (when daemon is
already running) was incorrectly shown when options were set via
environment variables like AGENT_BROWSER_EXECUTABLE_PATH, even when
no CLI flag was passed.

Now the warning only appears when flags are explicitly passed on the
command line, not when values come solely from environment variables.

Fixes #372
2026-02-04 23:14:31 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 79ef5764fa chore: version packages (#360)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-03 01:49:58 -06:00
Chris Tate 9d021bdf62 chore: add minor changeset for release (#359) 2026-02-03 01:43:58 -06:00
Chris Tate a1b992411e add iOS support (#358)
* ios

* tests

* docs

* real device

* better list

* fixes
2026-02-03 01:36:19 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 3c6ae7df9d chore: version packages (#357)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-02 21:46:53 -06:00
Chris Tate daeede49c5 chore: add patch changeset for release (#356) 2026-02-02 21:42:57 -06:00
Chris Tate 03eea8a90f fix: auto-chmod binary on first run to fix EACCES on macOS (#354)
Bun blocks postinstall scripts by default, leaving the binary without
execute permissions. The wrapper now fixes this automatically.

Fixes #344
2026-02-02 21:28:23 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> de859d8f6b chore: version packages (#349)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-02 20:51:46 -06:00
Chris TateandUbuntu 17dba8f7a8 chore: add patch changeset for release (#351)
Co-authored-by: Ubuntu <ctate@ip-172-31-33-149.us-east-2.compute.internal>
2026-02-02 20:51:42 -06:00
Chris Tate 0dc36f2cff Add --stdin flag for eval command (#348)
Adds --stdin flag to read JavaScript from stdin, enabling heredoc usage
for multiline scripts without shell escaping issues.
2026-02-02 20:29:43 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> f770593c66 chore: version packages (#343)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-02 19:42:32 -06:00
Chris Tate 27715884e5 chore: add patch changeset for release (#342) 2026-02-02 19:31:37 -06:00
Chris Tate e52aa49706 Add skill-creator and improve agent-browser skill (#341)
* add skills-creator

* update skill

* better docs

* minor fixes
2026-02-02 19:18:34 -06:00
Chris Tate 9c45f82193 Add base64 input for eval command (#340)
* Add base64 input for eval command

Adds -b/--base64 flag to decode script from base64, avoiding shell escaping issues for AI agents.

* Document base64 eval in SKILL.md
2026-02-02 18:52:43 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> bdf674a27e chore: version packages (#339)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-02 18:26:24 -06:00
Chris Tate d24f753f51 chore: add patch changeset for release (#338) 2026-02-02 18:01:18 -06:00
Chris Tate c00dd44750 fix: improve daemon startup error handling and diagnostics (#337)
* fixes

* add debugging
2026-02-02 13:47:15 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 97fd2828b5 chore: version packages (#331)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-31 23:11:25 -06:00
Chris Tate d75350a99e chore: add patch changeset for release (#330) 2026-01-31 23:04:46 -06:00
Chris Tate 775f166bce fix: add retry logic for transient socket errors (#329)
* fix: add retry logic for transient socket errors

Fixes race condition when rapidly closing and opening browser sessions.
The daemon has a 100ms shutdown delay, which caused the CLI to detect
stale daemons as "running" and fail with EAGAIN errors.

Changes:
- Add retry logic (5 attempts, exponential backoff) for transient errors
  including EAGAIN, EOF, connection reset, and connection refused
- Add 150ms verification delay in ensure_daemon to detect shutting-down daemons
- Add cleanup_stale_files to remove leftover socket/PID files before starting
  a new daemon

Tested with 20 rapid close/open cycles and 100+ parallel commands.

* test: add unit tests for transient error detection

Extracts is_transient_error() function and adds 14 unit tests covering:
- EAGAIN errors (macOS os error 35, Linux os error 11)
- WouldBlock and Resource temporarily unavailable
- EOF and empty JSON response errors
- Connection reset (macOS os error 54, Linux os error 104)
- Broken pipe errors
- Socket not found (os error 2)
- Connection refused (macOS os error 61, Linux os error 111)
- Non-transient errors (verifies they are NOT retried)
2026-01-31 23:00:31 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 32a0207ffa chore: version packages (#321)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-29 10:52:00 -06:00
Chris Tate cb2f8c3f73 chore: add patch changeset for release (#320) 2026-01-29 10:38:04 -06:00
Chris Tate 3d24ea38fa fix: commit bin/agent-browser.js with executable permissions (#319)
Fixes #305. The file was committed with mode 644, but npm
automatically sets the executable bit on bin files, causing
git to show the file as modified after pnpm install.
2026-01-29 10:28:11 -06:00
Chris Tate 71a79f64e8 fix: sync Cargo.lock when version changes (#302)
Update sync-version.js to also run `cargo update -p agent-browser` after
updating Cargo.toml, keeping Cargo.lock in sync. Also update pre-commit
hook to stage Cargo.lock along with Cargo.toml.

This commit also brings Cargo.lock up to date (was stuck at 0.7.6).
2026-01-27 09:33:47 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 72cbdc7f89 chore: version packages (#301)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-27 09:26:52 -06:00
Chris Tate 759302ead5 v0.8.4 changeset (#300) 2026-01-27 09:20:32 -06:00
n33pm 3f74bd2171 ci(version): add version sync check between package.json and Cargo.toml (#277)
Add automated verification that package.json and cli/Cargo.toml versions
stay in sync. This prevents version drift between the npm package and
Rust CLI binary.

- Add CI job to check version sync on push/PR
- Update pre-commit hook to sync versions automatically
- Update ci:version script to include version sync step
- Add check-version-sync.js script for CI validation
2026-01-27 09:09:04 -06:00
Chris Tate 3ce441bc4e fix daemon not found (#299) 2026-01-27 09:06:09 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 523d7d57f1 chore: version packages (#295)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-27 00:19:56 -06:00
Chris Tate 4116a8ac7f chore: add patch changeset for release (#294) 2026-01-27 00:15:04 -06:00
Chris Tate 18a1abda6e test: add Windows npm global install CI test (reproduces #262) (#293)
* test: add Windows npm global install CI test (reproduces #262)

This test packs the package and installs it globally with npm,
then runs agent-browser --version. This reproduces the issue where
npm-generated shims on Windows try to invoke /bin/sh which doesn't exist.

The bin/agent-browser.js wrapper is added but not yet wired up,
so this commit should fail CI to confirm the issue.

* fix: Windows npm global install and npx support

The shell script wrapper (bin/agent-browser) with #!/bin/sh shebang
causes npm to generate Windows shims that try to invoke /bin/sh,
which doesn't exist on Windows.

This fix uses a hybrid approach:

1. Node.js wrapper (bin/agent-browser.js) as bin entry
   - Makes npx work on all platforms
   - ~100ms overhead (acceptable since npx has its own overhead)

2. postinstall patches bin entries for global installs
   - Windows: Overwrites .cmd/.ps1 shims to invoke .exe directly
   - Mac/Linux: Replaces symlink to point to native binary
   - Zero overhead for `npm i -g agent-browser` users on all platforms

Also fixes PowerShell glob expansion in CI test.

Fixes #262

* fix: Windows npm global install and npx support

The shell script wrapper (bin/agent-browser) with #!/bin/sh shebang
causes npm to generate Windows shims that try to invoke /bin/sh,
which doesn't exist on Windows.

This fix uses a hybrid approach:

1. Node.js wrapper (bin/agent-browser.js) as bin entry
   - Makes npx work on all platforms
   - ~100ms overhead (acceptable since npx has its own overhead)

2. postinstall patches bin entries for global installs
   - Windows: Overwrites .cmd/.ps1 shims to invoke .exe directly
   - Mac/Linux: Replaces symlink to point to native binary
   - Zero overhead for `npm i -g agent-browser` users on all platforms

Also adds cross-platform CI tests for npm global install to catch
regressions on all platforms (Ubuntu, macOS, Windows).

Fixes #262

* test global install

* remove dead code
2026-01-27 00:09:51 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 28950b8ad2 chore: version packages (#292)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-26 18:06:28 -06:00
Chris Tate 7e6336f65b chore: add patch changeset for release (#291) 2026-01-26 18:01:48 -06:00
Chris Tate 143c8a8f3e ci: add test for Windows CMD wrapper (#289)
* ci: add test for Windows CMD wrapper

This test will fail until the CMD wrapper is fixed to call the native binary.

* fix: Windows CMD wrapper calls native binary instead of missing index.js
2026-01-26 17:54:46 -06:00
Chris Tate 0256c8f2e9 ci: add retry logic to flaky Windows integration test (#287)
* durable windows ci

* more
2026-01-26 17:29:44 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> ddfaa392e4 chore: version packages (#288)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-26 17:18:24 -06:00
Chris Tate 8eec634c6f chore: add patch changeset for release (#286) 2026-01-26 17:13:21 -06:00
Chris Tate 6a17379aaf fix: CLI binary not executable when postinstall is skipped (pnpm, bun) (#285)
* fix binary

* check binary in CI
2026-01-26 17:04:25 -06:00
Chris Tate bf5ba0a557 header (#283) 2026-01-26 14:09:17 -06:00
Chris Tate efb1923fbb v0.8.0 changelog (#282) 2026-01-26 13:46:17 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 9a1cc0ed6a chore: version packages (#281)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-26 12:03:32 -06:00
Chris Tate e0597304ec chore: add minor changeset for release (#280) 2026-01-26 11:56:51 -06:00
Li Yang e831b07f47 chore(cli): save screenshots to tmp dir when no path provided (#247)
* fix(cli): save screenshots to tmp dir when no path provided

Instead of outputting base64 to stdout (which is not useful for most CLI use cases),
screenshots without a path now save to ~/.agent-browser/tmp/screenshots/ with a
generated filename and return the path.

This makes the behavior more ergonomic for AI agents and CLI users alike.

* cleanup

* cleanup

* just revert the cargo.lock version for now

* refactor: extract getAppDir() from getSocketDir()

* docs: improve screenshot help text consistency
2026-01-26 09:08:39 -06:00
n33pm 12abdbd671 chore(cli): sync Cargo.toml version to 0.7.6 (#276) 2026-01-26 02:42:35 -06:00
Chris Tate 1b26ff886c Fix tab list command not recognizing new pages opened via clicks (#275)
## Summary

Fixed an issue where the `tab list` command couldn't recognize new pages that were opened externally (e.g., via `target="_blank"` links or popup windows). The problem occurred because context-level page tracking wasn't properly set up for all browser launch methods, causing new pages created outside of explicit `newTab()` calls to go untracked.

## Changes

- Added `setupContextTracking(context)` calls to `launch()`, `launchIncognito()`, and other context creation methods to ensure all contexts listen for new page events
- Added duplicate page checks (`!this.pages.includes(page)`) in `setupContextTracking()`, `newTab()`, and `launchIncognito()` to prevent the same page from being tracked multiple times
- Fixed `activePageIndex` calculation in `launch()` to properly set the active page index
- Enhanced comments to clarify that `setupContextTracking()` handles externally created pages (popups, new tabs from links)

## Implementation Details

The fix ensures that when a user clicks an element that opens a new tab/window, the browser context's 'page' event listener will automatically detect and track the new page. The duplicate prevention logic handles cases where both the context listener and manual page creation might try to add the same page.

Fixes #273
2026-01-26 01:25:49 -06:00
Chris Tate f862e2f7df Security: Reject cross-origin connections to daemon and stream server (#274) 2026-01-26 00:42:00 -06:00
RafaelandClaude Opus 4.5 fcee8f70d1 feat: add Kernel as cloud browser provider (#200)
Add Kernel (https://kernel.sh) as a third-party cloud browser provider,
following the same pattern as Browserbase and Browser Use integrations.

Features:
- Launch browser with `-p kernel` flag or `AGENT_BROWSER_PROVIDER=kernel`
- Configurable via environment variables:
  - KERNEL_API_KEY (required)
  - KERNEL_HEADLESS (default: false)
  - KERNEL_STEALTH (default: true)
  - KERNEL_TIMEOUT_SECONDS (default: 300)
  - KERNEL_PROFILE_NAME (optional, for persistent sessions)
- Profile find-or-create: automatically creates profile if it doesn't exist
- Profile persistence: cookies/logins saved back to profile on session close
- Uses raw fetch() calls for API communication (no SDK dependency)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 00:22:25 -06:00
Chris Tate a99f59cd20 Fix: check command hangs indefinitely (#272)
Fixes #257
2026-01-25 23:58:53 -06:00
Chris Tate 45506fbff0 Fix: set device does not apply deviceScaleFactor - HiDPI screenshots not possible (#270)
Fixes #255
2026-01-25 15:27:03 -06:00
shawn pana a22af0e675 generic placeholder for cloud browser provider (#260)
* docs: use generic placeholder for cloud browser provider

* docs: clarify available cloud browser providers
2026-01-25 13:55:29 -06:00
Chris Tate 79863a5180 Fix: CLI: state load / profile persistence not usable in v0.7.6 (#268)
* Fix: CLI: state load / profile persistence not usable in v0.7.6

This PR addresses issue #259

* Fix issues identified in code review
2026-01-25 13:45:17 -06:00
Chris Tate ae09fdd431 Add CLI flags for cookie URL, domain, path, httpOnly, secure, and expires (#266)
* Add CLI flags for cookie URL, domain, path, httpOnly, secure, and expires

Extends the `cookies set` command to support setting cookies with additional parameters before loading a page, solving authentication workflows where cookies need to be set for different domains.

**Key changes:**
- Added CLI flags: `--url`, `--domain`, `--path`, `--httpOnly`, `--secure`, `--sameSite`, `--expires`
- Added comprehensive test coverage for all new flags and combinations
- Updated help documentation with usage examples
- No daemon changes needed - it already supported these parameters

**Example usage:**
```bash
agent-browser cookies set session_id "abc123" --url https://app.example.com --httpOnly --secure
```

This allows setting cookies for a URL before opening the page, eliminating the need for workarounds in cross-domain authentication scenarios.

Fixes #261

* Update lock

* Fix compilation error
2026-01-25 11:53:49 -06:00
Zhiwei Li 53187a603c feat: add support for ignoring HTTPS certificate errors (#93)
* feat: add support for ignoring HTTPS certificate errors

* fix: update warning message for already running daemon to include ignore HTTPS errors option

* docs: add documentation for --ignore-https-errors option in README and SKILL.md

* feat: initialize ignore_https_errors flag in command context

* fix: change launch_cmd to mutable for cdp value handling
2026-01-24 23:54:33 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 60534dfd63 chore: version packages (#243)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-23 23:44:31 -06:00
Chris Tate a4d0c2624b chore: add patch changeset for release (#242) 2026-01-23 23:40:05 -06:00
Zach Warunek 36ea8ecb55 fix: allow null selector in screenshot command schema (#236)
The screenshot command was failing with 'Validation error: selector: Expected string, received null' when only a path was provided (e.g., 'agent-browser screenshot ~/Desktop/test.png').

The Rust CLI serializes None values as null in JSON, but the Zod schema only allowed undefined (via .optional()), not null. Changed selector field to use .nullish() which accepts both null and undefined.

Fixes issue where screenshot command without selector fails validation.
2026-01-23 17:50:11 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> d10fd2d545 chore: version packages (#233)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-23 15:59:36 -06:00
Chris Tate 8c2a6ec5d2 fix: handle existing GitHub releases in workflow (#232) 2026-01-23 15:55:18 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> c0fd1be132 chore: version packages (#231)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-23 15:44:44 -06:00
Chris Tate 957b5e5994 fix: ensure binary is executable after npm install (#229) 2026-01-23 15:40:46 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 65d4df84ac chore: version packages (#228)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-23 15:29:51 -06:00
Chris Tate 161d8f5c8d chore: add changeset for binary distribution fix (#227) 2026-01-23 15:25:53 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> f3ed1be409 chore: version packages (#226)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-23 15:13:12 -06:00
Chris Tate 6afede28b3 chore: release v0.7.1 (#225)
Fix native binary distribution in npm package. Binaries are now built
before publishing to npm, ensuring all platforms work on installation.
2026-01-23 15:08:59 -06:00
Chris Tate 6f1c83de1b fix bin (#224) 2026-01-23 15:00:13 -06:00
Chris Tate 28129df124 fix docs (#223)
* fix: download artifacts to temp directory to avoid naming conflict

The download-artifact action creates directories named after each artifact.
When downloading to bin/, this caused conflicts because the artifact directory
names matched the binary names (e.g., bin/agent-browser-darwin-arm64/agent-browser-darwin-arm64).

Fix by downloading to artifacts/ first, then using find to move the binaries to bin/.

* fix docs
2026-01-23 13:51:23 -06:00
Chris Tate eb8325e9b4 fix: download artifacts to temp directory to avoid naming conflict (#221)
The download-artifact action creates directories named after each artifact.
When downloading to bin/, this caused conflicts because the artifact directory
names matched the binary names (e.g., bin/agent-browser-darwin-arm64/agent-browser-darwin-arm64).

Fix by downloading to artifacts/ first, then using find to move the binaries to bin/.
2026-01-23 13:15:51 -06:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 9281f46823 chore: version packages (#220)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-23 13:06:48 -06:00
Chris Tate 316e649740 chore: add changeset for v0.7.0 release (#219) 2026-01-23 13:00:24 -06:00
Chris Tate 35d345b2b4 v0.7.0 docs (#218)
* auto-release

* fixes

* fix secret name

* update provider flag

* v0.7.0 changelog
2026-01-23 12:49:40 -06:00
Chris Tate fff4312d16 update provider flag (#217)
* auto-release

* fixes

* fix secret name

* update provider flag
2026-01-23 11:41:17 -06:00
Chris Tate 57dc7602fc auto-release (#216)
* auto-release

* fixes

* fix secret name
2026-01-23 11:19:43 -06:00
TimWhiteandChris Tate ea17db8564 fix(cli): correct output messages for state load and path-based actions (#109)
* Add files via upload

fix(cli): correct output messages for state load and path-based actions

* Add files via upload

* Update output.rs

* fix crlf

---------

Co-authored-by: Chris Tate <chris@ctate.dev>
2026-01-22 10:43:27 -06:00
Yonatan f74924cd0c feat(skills): Add hierarchical structure with references and templates (#157)
* feat(skills): Add hierarchical structure with references and templates

Adds modular documentation and executable templates to the agent-browser skill
for better AI agent consumption and progressive disclosure.

## Added

### References (deep-dive documentation)
- `references/snapshot-refs.md` - Ref lifecycle, invalidation, troubleshooting
- `references/session-management.md` - Parallel sessions, state persistence
- `references/authentication.md` - Login flows, OAuth, 2FA patterns
- `references/video-recording.md` - Recording for debugging/docs
- `references/proxy-support.md` - Proxy configuration, geo-testing

### Templates (ready-to-use workflows)
- `templates/form-automation.sh` - Form filling with validation
- `templates/authenticated-session.sh` - Login once, reuse state
- `templates/capture-workflow.sh` - Content extraction with screenshots

## Modified
- `SKILL.md` - Added reference tables linking to new documentation

## Benefits
- Progressive disclosure: Load overview first, deep dives on demand
- Reduced context: Smaller chunks for better LLM token efficiency
- Ready workflows: Copy-paste templates for common patterns

* fix(templates): Make authenticated-session.sh runnable out-of-box

Addresses review feedback: login actions were commented but verification
wasn't, causing script to fail when run as-is.

New approach:
- DISCOVERY MODE runs first (shows form structure)
- LOGIN FLOW section is fully commented as a unit
- User runs once to see refs, then customizes

┌─────────────────────────────────────────────────────────────┐
│ LOGIN FORM STRUCTURE                                        │
├─────────────────────────────────────────────────────────────┤
│ @e1 [input type="email"]                                    │
│ @e2 [input type="password"]                                 │
│ @e3 [button] "Sign In"                                      │
└─────────────────────────────────────────────────────────────┘
2026-01-22 10:26:31 -06:00
Danila PoyarkovandChris Tate 9f3c3ad933 fix(screenshot): support refs and improve error messages (#141)
* fix(screenshot): support refs and improve error messages

* fix(cli): support selector argument in screenshot command

* Fix CSS class selectors being treated as file paths

* fix(test): update screenshot test assertions

---------

Co-authored-by: Chris Tate <chris@ctate.dev>
2026-01-22 10:06:38 -06:00
Márk Magyar c046de2ec7 docs: update agent-browser skill documentation (#164) 2026-01-22 09:26:54 -06:00
55f4eaa728 feat: add download CLI commands with ref support (#183)
* feat: add download and waitfordownload CLI commands

Add CLI support for the existing download functionality in the daemon:

- `download <selector> <path>`: Click an element to trigger download
  and save to specified path
- `wait --download [path] [--timeout ms]`: Wait for any download to
  complete, optionally save to path with configurable timeout

Includes comprehensive unit tests and help documentation.

* fix: download command ref support and output message

- Fix handleDownload to use browser.getLocator() for ref selector support
- Fix CLI output to show "Downloaded to" instead of "Screenshot saved"

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Chris Tate <chris@ctate.dev>
2026-01-22 08:55:19 -06:00
Chris Tate 307f970d53 fix: support WebSocket URLs in connect command (#205)
* fix: support WebSocket URLs in connect command

* address feedback
2026-01-22 08:38:53 -06:00
Lindsey SimonandChris Tate 36cca10c10 Add --profile flag for persistent browser profiles (#68)
* Add --profile flag for persistent browser profiles

Adds support for persistent browser profiles that preserve cookies,
localStorage, and login sessions across browser restarts.

Changes:
- Add --profile <path> CLI flag (flags.rs)
- Add AGENT_BROWSER_PROFILE environment variable support
- Add profile field to LaunchCommand type (types.ts)
- Use launchPersistentContext when profile is specified (browser.ts)
- Update help text and README with documentation

Usage:
  agent-browser --profile ~/.myapp-profile open myapp.com

This enables AI agents to maintain authenticated sessions across
browser restarts without re-authenticating each time.

* Expand tilde in profile path to home directory

* fix: add missing profile field to test Flags struct

---------

Co-authored-by: Chris Tate <chris@ctate.dev>
2026-01-22 08:05:25 -06:00
Tom Dale c6a92a1472 docs: add Claude Code marketplace plugin installation instructions (#181)
Document the recommended way to install the agent-browser skill using the /plugin marketplace commands introduced in PR #106.
2026-01-22 01:44:06 -06:00
Shpeedle c4f66a5922 errors doc more descriptive (#190) 2026-01-22 01:25:46 -06:00
mmhiyokoandClaude Opus 4.5 946d236d9f fix: use ~/.agent-browser for socket files instead of TMPDIR (#180)
* fix: use ~/.agent-browser for socket files instead of TMPDIR

This fixes issue #163 where different TMPDIR values (common with
tmux/screen/VSCode/IntelliJ) caused the CLI and daemon to use
different socket paths.

Socket directory priority:
1. AGENT_BROWSER_SOCKET_DIR (explicit override)
2. $XDG_RUNTIME_DIR/agent-browser (Linux standard)
3. ~/.agent-browser (fallback, like Docker Desktop)

Both CLI (Rust) and daemon (Node.js) now use the same logic.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: session list now looks in correct socket directory

- Make get_socket_dir() public in connection.rs
- Update session list to use get_socket_dir() instead of temp_dir()
- Update pid file pattern from agent-browser-{session}.pid to {session}.pid
- Add tmpdir fallback to daemon.ts when homedir is unavailable

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test: add unit tests for socket directory resolution

Add comprehensive tests for get_socket_dir/getSocketDir to verify:
- AGENT_BROWSER_SOCKET_DIR takes priority
- Empty strings are ignored (fixes Rust/TypeScript consistency)
- XDG_RUNTIME_DIR fallback works correctly
- Home directory fallback when env vars unset

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 01:15:25 -06:00
cb37630ccf fix: add .exe extension for Windows source binary path (#188)
The copy-native.js script was looking for 'agent-browser' but on Windows
the compiled binary is 'agent-browser.exe', causing the copy to fail.

Co-authored-by: jiazhuangai <jiazhuangai@example.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-01-22 01:11:13 -06:00
Chris Tate 61c004db94 add missing flag (#203)
* add missing flag

* clean up tests
2026-01-22 00:59:53 -06:00
OanakiajaandChris Tate 083a946aac feat: add browser launch --args, --user-agent, --proxy-bypass configuration support. (#35)
* feat: add browser launch args, user-agent, and proxy configuration support

* fix: User Agent env need added

* fix: command pass error

---------

Co-authored-by: Chris Tate <chris@ctate.dev>
2026-01-22 00:19:37 -06:00
RafaelandClaude Opus 4.5 e892bceadf feat: support remote CDP WebSocket URLs in --cdp flag (#99)
Previously, the --cdp flag only accepted a port number and connected via
http://localhost:{port}. This made it impossible to connect to remote
browser services like Kernel, Browserless, etc. that provide WebSocket URLs.

The --cdp flag now accepts either:
- A port number (e.g., 9222) for local connections
- A full WebSocket URL (e.g., wss://...) for remote browser services

Changes:
- Added cdpUrl field to LaunchCommand type
- Updated protocol validation to accept URL format with scheme validation
- Modified connectViaCDP to detect and handle both formats
- Handle numeric strings for JSON serialization edge cases
- Updated CLI to send cdpUrl or cdpPort based on input format
- Updated README with examples for remote connections

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-21 21:11:14 -06:00
Aitor c4139fa389 feat: add Browser Use cloud browser as available provider (#138)
* feat: add Browser Use cloud browser
  integration

* feat: enhance Browser Use integration with provider flag support

- Updated README to reflect new usage instructions for enabling Browser Use with the `-p` flag.
- Modified CLI to parse and handle the `-p` flag for specifying the provider.
- Implemented logic in the main application to launch with the specified cloud provider.
- Adjusted BrowserManager to connect to Browser Use based on the provider flag or environment variable.
- Updated types and protocol schemas to include provider information.

* feat: add validation for mutually exclusive CLI options

- Implemented checks to prevent the use of both --cdp and --provider flags simultaneously.
- Added validation to ensure --extension cannot be used with the --provider flag.
- Enhanced error handling to provide clear feedback in both JSON and console output formats.
2026-01-21 18:01:19 -06:00
Paul KleinandKylejeong2 7123d46e7f Add Browserbase support for remote browser over CDP (#3)
* Add Browserbase support for remote browser over CDP

When BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID env vars are set,
connect to a Browserbase session via CDP instead of launching a local browser.

* Update URLs to browserbase repo

* Add Browserbase support for remote browser over CDP

When BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID env vars are set,
connect to a Browserbase session via CDP instead of launching a local browser.

* Update link to Browserbase Dashboard in README

* bump browserbase sdk to latest version

* remove sdk as a dep

* change name back to vercel labs

* added try catch blocks, functions to close session

* revert package names

* remove extra if statement

---------

Co-authored-by: Kylejeong2 <kylejeong21@gmail.com>
2026-01-21 17:49:21 -06:00
Chris Tate 399fd7a434 v0.6.0 changelog (#154) 2026-01-18 11:44:56 -06:00
Chris Tate 62f9b4dd6b chore: bump version to 0.6.0 (#153) 2026-01-18 11:37:26 -06:00
Chris Tate 818d9fa95e format code (#152) 2026-01-18 11:21:28 -06:00
Kye Burchard a8dcbb1222 feat: add connect command for persistent CDP sessions (#127)
Adds a `connect <port>` command that establishes a CDP connection
to a running browser. The daemon remembers the connection, so
subsequent commands work without needing --cdp on every call.

Example:
  agent-browser connect 9222
  agent-browser snapshot  # works without --cdp
  agent-browser tab
  agent-browser close
2026-01-18 10:54:12 -06:00
Mikhail Beliakovvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
a9fcef4579 fix: support libasound2t64 on newer Ubuntu versions (#112)
* fix: support libasound2t64 on newer Ubuntu versions

Updates the install logic to check if `libasound2t64` is available using
`apt-cache` before falling back to `libasound2`. This fixes installation
on Ubuntu 24.04 and other systems affected by the 64-bit time_t transition.

* Update cli/src/install.rs

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>

---------

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
2026-01-18 10:50:57 -06:00
Zhiwei Li 59baf97e51 fix: allow additional URL schemes in parse_command function (#125)
* fix: allow additional URL schemes in parse_command function

* fix: enhance URL validation in parse_command function to support lowercase schemes
2026-01-18 10:36:38 -06:00
0okay d02ef66c89 Refactor connection logic for Windows and hash calculationfix(cli): fix windows daemon startup and port calculation inconsistency (#79) 2026-01-18 09:14:03 -06:00
Danila Poyarkov 1689cf9eca fix(cli): handle SIGPIPE to prevent panic when piping output (#144) 2026-01-18 08:57:02 -06:00
Matthew KingandClaude Opus 4.5 03a53c9f36 feat: add Claude marketplace plugin (#106)
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-18 07:49:27 -06:00
Zhiwei Li b1c0c6a366 feat: enhance response output with network request details and cleared status (#117) 2026-01-18 07:35:25 -06:00
Ryan DaigleandClaude Opus 4.5 c88734da89 feat: add NO_COLOR environment variable support (#122)
Add a centralized color module (cli/src/color.rs) that respects the
NO_COLOR environment variable per https://no-color.org/

Changes:
- Add color.rs module with helper functions for colored output
- Refactor all hardcoded ANSI escape codes to use the color module
- Add tests for color formatting functions
- Update AGENTS.md with color module usage guidelines

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-17 20:37:00 -06:00
Nicenonecb 28740acecf Fix CLI/protocol mismatches for select, frame main, and headers (#45)
* fix: align CLI command payloads with protocol

* fix(cli): support multi-value select in CLI
2026-01-17 20:25:19 -06:00
jaydenfyi 4112234371 fix(cli): Output screenshot as base64 string when no path provided (#83)
* fix(cli): print screenshot base64 when no path

* chore(docs): update docs and SKILL.md

* add test for screenshot with path arg

* more minimal readme + skill change
2026-01-17 20:18:06 -06:00
Li Yang 5e08e5d077 fix: detect stale unix socket by attempting connection (#114) 2026-01-17 19:42:48 -06:00
Sanchay 42879c337a fix: respect AGENT_BROWSER_HEADED env var for headed mode (#92)
The headless option was hardcoded to true in the auto-launch section,
ignoring the AGENT_BROWSER_HEADED environment variable. This fix checks
the env var so users can run the browser in headed mode by setting
AGENT_BROWSER_HEADED=1.

Fixes #90
2026-01-17 19:22:59 -06:00
Leon Gao 412ac63b68 fix: resolve refs in input value (#139) 2026-01-17 19:05:06 -06:00
Danila Poyarkov e6e832d2bc feat: add 'get styles' command for computed styles extraction (#142) 2026-01-17 18:56:52 -06:00
Dharma b19ca760aa fix: support URL parameter in tab new command (#64)
* fix: support URL parameter in tab new command

The CLI was correctly sending the URL parameter when running
`agent-browser tab new <url>`, but the TypeScript daemon was
ignoring it because:

1. The schema didn't include the url field (stripped during validation)
2. The TabNewCommand type didn't have a url property
3. The handler didn't pass the URL to browser.newTab()
4. browser.newTab() didn't accept or use a URL parameter

This fix adds URL support throughout the chain so that
`agent-browser tab new https://example.com` now correctly
opens a new tab and navigates to the specified URL.

Fixes #62

* fix: omit url field when not provided in tab new command

Previously, the CLI always sent "url": null when no URL was provided,
which caused Zod validation to fail with "Expected string, received null".

Now the url field is only included when a URL is actually provided.

Fixes issue reported by @ctate in PR review.

* refactor: move navigation logic from BrowserManager to handleTabNew

Address review feedback:
- Add .min(1) to URL validation for consistency with navigateSchema
- Keep BrowserManager.newTab() simple (single responsibility)
- Handle navigation in handleTabNew following same pattern as handleNavigate
2026-01-17 18:53:24 -06:00
Sheingandgoogle-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com> e7c4936bc7 fix(cli): allow null path in screenshot command validation (#101)
The Rust CLI sends `null` for the `path` argument when it is not provided,
but the Zod schema only accepted `undefined`. This change updates the
`screenshotSchema` to allow `null` values for `path`, enabling the
`screenshot` command to work without a file path argument (outputting to stdout).

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
2026-01-17 18:41:55 -06:00
Sheinggoogle-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>sheing-google
7aad47d3bd fix: Prevent CDP timeout on empty URL tabs (#102)
When connecting to a browser via CDP, particularly on Android, tabs with an empty URL can cause Playwright commands to hang indefinitely. This leads to a timeout in agent-browser.

This commit fixes the issue by filtering out any pages that have an empty `page.url()` during the CDP connection process. This prevents agent-browser from attempting to interact with these problematic tabs, resolving the timeout while preserving normal pages.

Added a unit test to verify that pages with empty URLs are correctly ignored. Also increased the timeout for a flaky screencast test to improve test suite stability.

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: sheing-google <231310897+sheing-google@users.noreply.github.com>
2026-01-17 18:16:37 -06:00
edx.eth e196ed3e35 fix(cli): align protocol action names for wheel, emulatemedia, and find locators (#143)
- mouse wheel: send 'wheel' instead of 'mousewheel'
- set media: send 'emulatemedia' instead of 'media', fix reducedMotion to be string enum
- find locators: omit 'value' field when not provided (Zod .optional() expects undefined, not null)
  - Consistently applied to: role, label, placeholder, testid, first, last, nth

Fixes #131
2026-01-17 18:11:11 -06:00
1f31452fea feat: Add video recording with Playwright native video (#116)
* feat: add video recording with Playwright native video

Adds `record start/stop` commands using Playwright's built-in video
recording. No external dependencies required (no FFmpeg).

Usage:
  agent-browser record start ./demo.webm https://example.com
  agent-browser click @e1
  agent-browser record stop

Recording creates a fresh browser context with video enabled. For smooth
demos, explore the page first to plan actions, then start recording.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: auto-capture URL and transfer state for recording

When starting a recording without a URL:
- Automatically captures current page URL
- Preserves cookies and localStorage from current session

This enables a seamless workflow:
  agent-browser open https://app.example.com
  agent-browser snapshot -i  # explore, plan
  agent-browser record start ./demo.webm  # picks up URL + auth state
  agent-browser click @e3
  agent-browser record stop

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: error on non-webm recording path instead of silent coercion

Previously, specifying a non-.webm path like ./demo.mp4 would silently
change it to ./demo.webm. Now it throws a clear error telling the user
that Playwright native recording only supports WebM format.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: clean up recording temp directory after stopRecording

Previously the temp directory was created but never deleted, relying on
OS cleanup. Now we explicitly remove it after saving the video, in both
success and error paths.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add record restart command

Adds `record restart` command that stops the current recording (if any)
and starts a new one. Also improves the error message when trying to
start recording while already recording.

Changes:
- Add restartRecording method to BrowserManager
- Add recording_restart action to protocol, types, and actions
- Add CLI parsing for `record restart <path> [url]`
- Update help text and skill documentation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test: add CLI tests for record restart command

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Chris Tate <chris@ctate.dev>
2026-01-16 12:27:58 -06:00
NMW 3675e6bd7a feat: add --proxy flag for browser proxy configuration (#16)
* feat: add --proxy flag for browser proxy support

Add CLI flag to configure HTTP/SOCKS proxy for Playwright browser context.
Supports URL format with optional credentials: http://user:pass@host:port

* fix: improve proxy parsing error handling

- Handle malformed credentials (@ without :) by ignoring incomplete creds
- Replace unwrap() with expect() for better error messages
- Addresses Vercel bot code review suggestions

* Restaura cambios locales: soporte AGENT_BROWSER_HOME y timeout aumentado

- Agrega soporte para variable de entorno AGENT_BROWSER_HOME en connection.rs
- Aumenta timeout por defecto de 10s a 60s para conexiones más lentas

* feat: add --proxy flag for browser proxy configuration

Implements proxy support based on PR #16 with reviewer feedback:

Features:
- Parse proxy URLs: http://[user:pass@]host:port
- Support for HTTP, HTTPS, and SOCKS5 protocols
- Handle username-only auth (preserves username with empty password)
- Apply proxy to both standard and persistent contexts

Changes:
- cli/src/flags.rs: Add proxy flag parsing
- cli/src/main.rs: Add parse_proxy() with comprehensive tests
- cli/src/output.rs: Add --proxy to help output
- cli/src/commands.rs: Fix test helper to include proxy field
- src/types.ts: Add proxy to LaunchCommand interface
- src/protocol.ts: Add proxy validation schema
- src/browser.ts: Apply proxy to context creation

Tests:
- 7 unit tests for parse_proxy() covering all edge cases
- All Rust tests passing (69 tests)
- All TypeScript tests passing (168 tests)
- TypeScript typecheck passing

Resolves feedback from PR #16:
- Fixed username-only proxy handling (issue #2681046975)
- Added comprehensive unit tests
- Added --proxy to help documentation
- Used expect() instead of unwrap() for better error messages

* refactor: simplify parse_proxy function

- Remove redundant comments
- Extract server variable to reduce duplication
- Inline trivial username/password variables

All 7 proxy tests still passing.
2026-01-16 11:56:35 -06:00
Andrew GadzikandClaude Opus 4.5 fff9a146bd docs: update agent-browser skill with comprehensive command reference (#121)
Add documentation for new commands including focus, drag/drop, upload,
keydown/keyup, mouse control, cookies/storage, network interception,
tabs/windows, frames, dialogs, and browser settings.

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 11:40:57 -06:00
edx.eth 34dcb7195a fix(cli): align console output field name with daemon response (#133)
The CLI expected a 'logs' field but the daemon returns 'messages'.
This caused 'agent-browser console' to display nothing.

Changed cli/src/output.rs to read 'messages' instead of 'logs',
matching the actual response from handleConsole in src/actions.ts.
2026-01-16 11:38:29 -06:00
Matthew KingandClaude Opus 4.5 7bdfcf8541 feat: add --version flag to CLI (#94)
Print the current version when `agent-browser --version` is passed.

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 11:35:06 -06:00
Chris Tate 6abee37641 v0.5.0 (#78) 2026-01-13 21:54:20 -06:00
NoelandClaude Sonnet 4.5 7b43d408da fix: improve error message when element is blocked by overlay (#59)
When clicking an element that is blocked by a cookie banner or modal overlay,
the error message incorrectly showed "Element not found or not visible" even
though the element was found and visible.

The issue was in toAIFriendlyError(): the check for "Timeout" was evaluated
before "intercepts pointer events", causing the wrong error message to be
returned.

Changes:
- Reorder error detection to check "intercepts pointer events" before "Timeout"
- Improve error message to suggest dismissing modals/cookie banners
- Export toAIFriendlyError for testing
- Add focused tests for overlay blocking behavior

Before:
  Element "@e4" not found or not visible. Run 'snapshot' to see current page elements.

After:
  Element "@e4" is blocked by another element (likely a modal or overlay).
  Try dismissing any modals/cookie banners first.

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-13 15:25:46 -06:00
Chris TateandVercel <vercel[bot]@users.noreply.github.com> 2dc093cd62 add screencast (#67)
* docs

* updates

* Fix: The handleCopy function fails to handle errors from navigator.clipboard.writeText(), causing unhandled exceptions and misleading UI feedback when clipboard operations fail.

Co-authored-by: ctate <chris@ctate.dev>

* Fix: The benchmark file uses emojis (📊, 🚀, 🔨, 📈, 📋, , ⏱️, ⚠) in console output, violating repository guidelines that forbid emojis in code and output.

Co-authored-by: ctate <chris@ctate.dev>

* Remove benchmark/run.ts from PR

* screencast

* update docs

* address comments

---------

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
2026-01-13 14:53:27 -06:00
Shirshak 673e2e266e feat: Add extension support (#48)
* Rebase: Add extension support

* Fix logs
2026-01-13 14:34:59 -06:00
Chris TateandVercel <vercel[bot]@users.noreply.github.com> 4713c8b520 add docs (#54)
* docs

* updates

* Fix: The handleCopy function fails to handle errors from navigator.clipboard.writeText(), causing unhandled exceptions and misleading UI feedback when clipboard operations fail.

Co-authored-by: ctate <chris@ctate.dev>

* Fix: The benchmark file uses emojis (📊, 🚀, 🔨, 📈, 📋, , ⏱️, ⚠) in console output, violating repository guidelines that forbid emojis in code and output.

Co-authored-by: ctate <chris@ctate.dev>

* Remove benchmark/run.ts from PR

---------

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
2026-01-13 02:54:56 -06:00
Chris Tate b4bc761168 fix builds (#55) 2026-01-13 02:41:39 -06:00
152 changed files with 104404 additions and 9323 deletions
+19
View File
@@ -0,0 +1,19 @@
{
"$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
"name": "agent-browser",
"description": "Browser automation for AI agents",
"owner": {
"name": "Vercel",
"email": "support@vercel.com"
},
"plugins": [
{
"name": "agent-browser",
"description": "Automates browser interactions for web testing, form filling, screenshots, and data extraction",
"source": "./",
"strict": false,
"skills": ["./skills/agent-browser"],
"category": "development"
}
]
}
+188 -104
View File
@@ -5,53 +5,80 @@ on:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
jobs:
typescript:
name: TypeScript (Node ${{ matrix.node-version }})
version-sync:
name: Version Sync Check
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20, 22]
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Setup Node.js ${{ matrix.node-version }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: pnpm
node-version-file: .node-version
- name: Install dependencies
run: pnpm install
- name: Typecheck
run: pnpm typecheck
- name: Format check
run: pnpm format:check
- name: Install Playwright browsers
run: pnpm exec playwright install --with-deps chromium
- name: Run tests
run: pnpm test
- name: Check version sync
run: node scripts/check-version-sync.js
rust:
name: Rust
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Cache Rust build artifacts
uses: Swatinem/rust-cache@v2
with:
workspaces: cli
- name: Format check
run: cargo fmt --manifest-path cli/Cargo.toml -- --check
- name: Clippy check
run: cargo clippy --manifest-path cli/Cargo.toml -- -D warnings
- name: Run Rust tests
run: cargo test --profile ci --manifest-path cli/Cargo.toml
dashboard:
name: Dashboard
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: .node-version
- name: Install pnpm
uses: pnpm/action-setup@v4
- name: Install dependencies
run: pnpm install --filter dashboard
working-directory: packages/dashboard
- name: Build dashboard
run: pnpm build
working-directory: packages/dashboard
rust-cross:
name: Rust (${{ matrix.os }} - ${{ matrix.target }})
if: github.event_name != 'pull_request'
runs-on: ${{ matrix.os }}
strategy:
matrix:
include:
- os: ubuntu-latest
target: x86_64-unknown-linux-gnu
- os: macos-latest
target: aarch64-apple-darwin
- os: macos-latest
@@ -68,72 +95,64 @@ jobs:
with:
targets: ${{ matrix.target }}
- name: Cache Cargo dependencies
uses: actions/cache@v4
- name: Cache Rust build artifacts
uses: Swatinem/rust-cache@v2
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
cli/target/
key: ${{ runner.os }}-cargo-${{ matrix.target }}-${{ hashFiles('cli/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-${{ matrix.target }}-
- name: Build release binary
run: cargo build --release --manifest-path cli/Cargo.toml --target ${{ matrix.target }}
workspaces: cli
- name: Run Rust tests
run: cargo test --manifest-path cli/Cargo.toml --target ${{ matrix.target }}
run: cargo test --profile ci --manifest-path cli/Cargo.toml --target ${{ matrix.target }}
windows-integration:
name: Windows Integration Test
runs-on: windows-latest
native-e2e:
name: Native E2E Tests
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
needs: rust
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Setup Rust toolchain
uses: dtolnay/rust-toolchain@stable
- name: Setup Node.js
uses: actions/setup-node@v4
- name: Cache Rust build artifacts
uses: Swatinem/rust-cache@v2
with:
node-version: 22
cache: pnpm
workspaces: cli
- name: Install Chrome
run: |
cargo run --manifest-path cli/Cargo.toml -- install --with-deps
- name: Install ffmpeg
run: sudo apt-get update && sudo apt-get install -y ffmpeg
- name: Run e2e tests
run: cargo test --profile ci --manifest-path cli/Cargo.toml e2e -- --ignored --test-threads=1
windows-integration:
name: Windows Integration Test
if: github.event_name != 'pull_request'
runs-on: windows-latest
needs: rust-cross
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
targets: x86_64-pc-windows-msvc
- name: Cache Cargo dependencies
uses: actions/cache@v4
- name: Cache Rust build artifacts
uses: Swatinem/rust-cache@v2
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
cli/target/
key: windows-cargo-x86_64-pc-windows-msvc-${{ hashFiles('cli/Cargo.lock') }}
restore-keys: |
windows-cargo-x86_64-pc-windows-msvc-
workspaces: cli
- name: Build Rust CLI
run: cargo build --release --manifest-path cli/Cargo.toml --target x86_64-pc-windows-msvc
- name: Install npm dependencies
run: pnpm install
- name: Build TypeScript
run: pnpm build
- name: Copy CLI binary to bin directory
run: |
Copy-Item cli/target/x86_64-pc-windows-msvc/release/agent-browser.exe bin/agent-browser-win32-x64.exe
@@ -141,48 +160,113 @@ jobs:
- name: Test agent-browser install command
run: |
$env:PATH = "$pwd\bin;$env:PATH"
bin/agent-browser-win32-x64.exe install
shell: pwsh
- name: Verify Chromium was installed
run: |
$playwrightPath = "$env:LOCALAPPDATA\ms-playwright"
if (Test-Path $playwrightPath) {
Write-Host "Playwright browsers installed at: $playwrightPath"
Get-ChildItem $playwrightPath -Recurse -Depth 2 | Select-Object -First 20
} else {
Write-Error "Playwright browsers not found!"
exit 1
for ($i = 1; $i -le 3; $i++) {
bin/agent-browser-win32-x64.exe install
if ($LASTEXITCODE -eq 0) { exit 0 }
Write-Host "Attempt $i failed, retrying in 10 seconds..."
Start-Sleep -Seconds 10
}
exit 1
shell: pwsh
timeout-minutes: 10
serverless-chromium:
name: Serverless Chromium (@sparticuz/chromium)
runs-on: ubuntu-latest
- name: Test daemon lifecycle (open, snapshot, close)
run: |
$env:PATH = "$pwd\bin;$env:PATH"
Write-Host "--- Opening page ---"
bin/agent-browser-win32-x64.exe open https://example.com
if ($LASTEXITCODE -ne 0) { Write-Error "open failed"; exit 1 }
Write-Host "--- Taking snapshot ---"
$snapshot = bin/agent-browser-win32-x64.exe snapshot
if ($LASTEXITCODE -ne 0) { Write-Error "snapshot failed"; exit 1 }
Write-Host $snapshot
Write-Host "--- Closing browser ---"
bin/agent-browser-win32-x64.exe close
if ($LASTEXITCODE -ne 0) { Write-Error "close failed"; exit 1 }
Write-Host "--- Windows daemon lifecycle test passed ---"
shell: pwsh
timeout-minutes: 5
global-install:
name: Global Install (${{ matrix.os }})
if: github.event_name != 'pull_request'
runs-on: ${{ matrix.os }}
needs: rust-cross
strategy:
matrix:
include:
- os: ubuntu-latest
target: x86_64-unknown-linux-gnu
binary: agent-browser-linux-x64
- os: macos-latest
target: aarch64-apple-darwin
binary: agent-browser-darwin-arm64
- os: windows-latest
target: x86_64-pc-windows-msvc
binary: agent-browser-win32-x64.exe
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
node-version-file: .node-version
- name: Install dependencies
run: pnpm install
- name: Setup Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- name: Install @sparticuz/chromium
run: pnpm add -D @sparticuz/chromium
- name: Cache Rust build artifacts
uses: Swatinem/rust-cache@v2
with:
workspaces: cli
- name: Build TypeScript
run: pnpm build
- name: Build Rust CLI
run: cargo build --release --manifest-path cli/Cargo.toml --target ${{ matrix.target }}
- name: Run serverless integration test
run: pnpm exec vitest run test/serverless.test.ts
- name: Copy CLI binary to bin directory (Unix)
if: runner.os != 'Windows'
run: cp cli/target/${{ matrix.target }}/release/agent-browser bin/${{ matrix.binary }}
- name: Copy CLI binary to bin directory (Windows)
if: runner.os == 'Windows'
run: Copy-Item cli/target/${{ matrix.target }}/release/agent-browser.exe bin/${{ matrix.binary }}
- name: Test npm global install
run: |
npm pack
npm install -g agent-browser-*.tgz
agent-browser --version
shell: bash
- name: Verify symlink points to native binary (Unix)
if: runner.os != 'Windows'
run: |
SYMLINK=$(npm prefix -g)/bin/agent-browser
TARGET=$(readlink "$SYMLINK")
echo "Symlink: $SYMLINK"
echo "Target: $TARGET"
if [[ "$TARGET" != *"${{ matrix.binary }}"* ]]; then
echo "ERROR: Symlink should point to native binary, not JS wrapper"
exit 1
fi
echo "Symlink correctly points to native binary"
shell: bash
- name: Verify shim points to native binary (Windows)
if: runner.os == 'Windows'
run: |
$shimPath = "$(npm prefix -g)\agent-browser.cmd"
$content = Get-Content $shimPath -Raw
echo "Shim path: $shimPath"
echo "Shim content:"
echo $content
if ($content -notmatch "agent-browser-win32-x64\.exe") {
echo "ERROR: Shim should point to native .exe, not JS wrapper"
exit 1
}
echo "Shim correctly points to native binary"
shell: pwsh
+332
View File
@@ -0,0 +1,332 @@
name: Release
on:
push:
branches:
- main
workflow_dispatch:
concurrency: ${{ github.workflow }}-${{ github.ref }}
permissions:
contents: read
jobs:
check-release:
name: Check for new version
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
outputs:
should_release: ${{ steps.check.outputs.should_release }}
needs_github_release: ${{ steps.check.outputs.needs_github_release }}
version: ${{ steps.check.outputs.version }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: .node-version
- name: Compare package.json version to npm and check GitHub release
id: check
run: |
LOCAL_VERSION=$(node -p "require('./package.json').version")
echo "Local version: $LOCAL_VERSION"
NPM_VERSION=$(npm view agent-browser version 2>/dev/null || echo "0.0.0")
echo "npm version: $NPM_VERSION"
if [ "$LOCAL_VERSION" != "$NPM_VERSION" ]; then
echo "Version changed: $NPM_VERSION -> $LOCAL_VERSION"
echo "should_release=true" >> "$GITHUB_OUTPUT"
echo "needs_github_release=true" >> "$GITHUB_OUTPUT"
else
echo "Version unchanged on npm, skipping build and publish"
echo "should_release=false" >> "$GITHUB_OUTPUT"
# Check if GitHub release exists; it may be missing if a prior run
# published to npm but failed before creating the release.
TAG="v$LOCAL_VERSION"
if gh release view "$TAG" &>/dev/null; then
echo "GitHub release $TAG exists"
echo "needs_github_release=false" >> "$GITHUB_OUTPUT"
else
echo "GitHub release $TAG is missing, will rebuild and create it"
echo "needs_github_release=true" >> "$GITHUB_OUTPUT"
fi
fi
echo "version=$LOCAL_VERSION" >> "$GITHUB_OUTPUT"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
build-binaries:
name: Build ${{ matrix.name }}
needs: check-release
if: needs.check-release.outputs.should_release == 'true' || needs.check-release.outputs.needs_github_release == 'true'
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- name: Linux x64
os: ubuntu-latest
target: x86_64-unknown-linux-gnu
binary: agent-browser-linux-x64
use_zigbuild: true
- name: Linux ARM64
os: ubuntu-latest
target: aarch64-unknown-linux-gnu
binary: agent-browser-linux-arm64
use_zigbuild: true
- name: Linux musl x64
os: ubuntu-latest
target: x86_64-unknown-linux-musl
binary: agent-browser-linux-musl-x64
use_zigbuild: true
- name: Linux musl ARM64
os: ubuntu-latest
target: aarch64-unknown-linux-musl
binary: agent-browser-linux-musl-arm64
use_zigbuild: true
- name: Windows x64
os: ubuntu-latest
target: x86_64-pc-windows-gnu
binary: agent-browser-win32-x64.exe
use_zigbuild: false
- name: macOS x64
os: macos-latest
target: x86_64-apple-darwin
binary: agent-browser-darwin-x64
use_zigbuild: false
- name: macOS ARM64
os: macos-latest
target: aarch64-apple-darwin
binary: agent-browser-darwin-arm64
use_zigbuild: false
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: .node-version
cache: pnpm
- name: Install npm dependencies
run: pnpm install --frozen-lockfile
- name: Sync version
run: pnpm run version:sync
- name: Build dashboard
run: pnpm --filter dashboard build
- name: Setup Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- name: Install cross-compilation tools (Linux)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y gcc-aarch64-linux-gnu gcc-x86-64-linux-gnu mingw-w64
- name: Install cargo-zigbuild
if: matrix.use_zigbuild
run: |
pip3 install ziglang
cargo install cargo-zigbuild
- name: Configure Rust linkers
if: runner.os == 'Linux'
run: |
mkdir -p ~/.cargo
cat >> ~/.cargo/config.toml << 'EOF'
[target.aarch64-unknown-linux-gnu]
linker = "aarch64-linux-gnu-gcc"
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"
EOF
- name: Cache Rust build artifacts
uses: Swatinem/rust-cache@v2
with:
workspaces: cli
- name: Build with zigbuild
if: matrix.use_zigbuild
run: cargo zigbuild --release --manifest-path cli/Cargo.toml --target ${{ matrix.target }}
- name: Build with cargo
if: '!matrix.use_zigbuild'
run: cargo build --release --manifest-path cli/Cargo.toml --target ${{ matrix.target }}
- name: Copy binary
run: |
mkdir -p artifacts
if [[ "${{ matrix.target }}" == *"windows"* ]]; then
cp cli/target/${{ matrix.target }}/release/agent-browser.exe artifacts/${{ matrix.binary }}
else
cp cli/target/${{ matrix.target }}/release/agent-browser artifacts/${{ matrix.binary }}
chmod +x artifacts/${{ matrix.binary }}
fi
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.binary }}
path: artifacts/${{ matrix.binary }}
retention-days: 7
publish:
name: Publish to npm
needs: [check-release, build-binaries]
if: needs.check-release.outputs.should_release == 'true'
runs-on: ubuntu-latest
timeout-minutes: 15
environment: Release
permissions:
contents: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: .node-version
cache: pnpm
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Download all binary artifacts
uses: actions/download-artifact@v4
with:
path: artifacts/
- name: Move binaries to bin directory
run: |
mkdir -p bin
find artifacts -type f -name 'agent-browser-*' -exec mv {} bin/ \;
rm -rf artifacts
chmod +x bin/agent-browser-* 2>/dev/null || true
echo "Binaries in bin/:"
ls -la bin/
- name: Verify all binaries exist
run: |
EXPECTED_BINARIES=(
"agent-browser-linux-x64"
"agent-browser-linux-arm64"
"agent-browser-linux-musl-x64"
"agent-browser-linux-musl-arm64"
"agent-browser-win32-x64.exe"
"agent-browser-darwin-x64"
"agent-browser-darwin-arm64"
)
MIN_SIZE=100000
ERRORS=0
for binary in "${EXPECTED_BINARIES[@]}"; do
if [ ! -f "bin/$binary" ]; then
echo "ERROR: Missing bin/$binary"
ERRORS=$((ERRORS + 1))
else
SIZE=$(stat -c%s "bin/$binary" 2>/dev/null || stat -f%z "bin/$binary")
if [ "$SIZE" -lt "$MIN_SIZE" ]; then
echo "ERROR: bin/$binary is too small ($SIZE bytes, expected >= $MIN_SIZE)"
ERRORS=$((ERRORS + 1))
else
echo "OK: bin/$binary ($SIZE bytes)"
fi
fi
done
if [ "$ERRORS" -gt 0 ]; then
echo "Error: $ERRORS binary issues found"
exit 1
fi
echo "All 7 platform binaries present and valid"
- name: Publish to npm
run: npm publish --provenance
github-release:
name: Create GitHub Release
needs: [check-release, build-binaries, publish]
if: always() && needs.build-binaries.result == 'success' && needs.check-release.outputs.needs_github_release == 'true'
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts/
- name: Move binaries to bin directory
run: |
mkdir -p bin
find artifacts -type f -name 'agent-browser-*' -exec mv {} bin/ \;
rm -rf artifacts
chmod +x bin/agent-browser-* 2>/dev/null || true
ls -la bin/
- name: Verify binaries exist
run: |
BINARY_COUNT=$(ls bin/agent-browser-* 2>/dev/null | wc -l)
if [ "$BINARY_COUNT" -lt 7 ]; then
echo "Error: Expected 7 binaries, found $BINARY_COUNT"
ls -la bin/
exit 1
fi
echo "Found $BINARY_COUNT binaries"
- name: Extract changelog entry
run: |
VERSION="${{ needs.check-release.outputs.version }}"
awk '/<!-- release:start -->/{found=1; next} /<!-- release:end -->/{found=0} found{print}' CHANGELOG.md > /tmp/release-notes.md
LINES=$(wc -l < /tmp/release-notes.md | tr -d ' ')
if [ "$LINES" -lt 2 ]; then
echo "Error: No release notes found between <!-- release:start --> and <!-- release:end --> markers in CHANGELOG.md"
exit 1
fi
echo "Extracted release notes for $VERSION ($LINES lines)"
- name: Create GitHub Release
run: |
VERSION="${{ needs.check-release.outputs.version }}"
TAG="v$VERSION"
if gh release view "$TAG" &>/dev/null; then
echo "Release $TAG already exists, uploading assets..."
gh release upload "$TAG" bin/agent-browser-* --clobber
else
echo "Creating release $TAG..."
gh release create "$TAG" \
--title "$TAG" \
--notes-file /tmp/release-notes.md \
bin/agent-browser-*
fi
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+25
View File
@@ -6,6 +6,7 @@ dist/
# Native binaries (keep the launcher scripts)
bin/agent-browser-*
bin/.install-method
!bin/agent-browser
!bin/agent-browser.cmd
@@ -27,10 +28,15 @@ npm-debug.log*
.DS_Store
Thumbs.db
# Python
__pycache__/
# Test artifacts
*.png
*.jpeg
*.jpg
*.webm
test/e2e/.dogfood-output/
# Package manager
package-lock.json
@@ -40,5 +46,24 @@ yarn.lock
.env
.env.local
# Windows debug instance config
scripts/windows-debug/.instance
# opensrc - source code for packages
opensrc/
# Docs site
docs/node_modules/
docs/.next/
docs/out/
docs/package-lock.json
# pnpm
.pnpm-store/
# TypeScript
*.tsbuildinfo
# next
.next/
out/
+2 -1
View File
@@ -1 +1,2 @@
pnpm lint-staged
node scripts/sync-version.js
git add cli/Cargo.toml cli/Cargo.lock
+8
View File
@@ -0,0 +1,8 @@
if [ "${SKIP_CLAWHUB_SYNC:-0}" = "1" ]; then
echo "Skipping ClawHub sync (SKIP_CLAWHUB_SYNC=1)"
exit 0
fi
pnpm run clawhub:sync || {
echo "ClawHub sync failed. Push continues. Run 'pnpm run clawhub:sync' manually after fixing login/network."
}
+1
View File
@@ -0,0 +1 @@
24
+178
View File
@@ -2,9 +2,187 @@
Instructions for AI coding agents working with this codebase.
## Package Manager
This project uses **pnpm**. Always use `pnpm` instead of `npm` or `yarn` for installing dependencies, running scripts, etc. (e.g., `pnpm install`, `pnpm run build`).
## Code Style
- Do not use emojis in code, output, or documentation. Unicode symbols (✓, ✗, →, ⚠) are acceptable.
- In documentation and markdown, never use double hyphens (`--`) as a dash. Use an emdash (—) sparingly when needed. Prefer rewriting the sentence to avoid dashes entirely.
- CLI colored output uses `cli/src/color.rs`. This module respects the `NO_COLOR` environment variable. Never use hardcoded ANSI color codes.
- CLI flags must always use kebab-case (e.g., `--auto-connect`, `--allow-file-access`). Never use camelCase for flags (e.g., `--autoConnect` is wrong).
## Documentation
When adding or changing user-facing features (new flags, commands, behaviors, environment variables, etc.), update **all** of the following:
1. `cli/src/output.rs``--help` output (flags list, examples, environment variables)
2. `README.md` — Options table, relevant feature sections, examples
3. `skill-data/core/SKILL.md` (and its `references/`) — so AI agents know about the feature when they load the core skill. Edit `skill-data/core/SKILL.md` for overview/workflow changes; edit `skill-data/core/references/*.md` for detailed reference content. Do **not** put feature content in `skills/agent-browser/SKILL.md` — that file is an intentionally thin discovery stub for `npx skills add` and exists only to redirect agents to `agent-browser skills get core`.
4. `docs/src/app/` — the Next.js docs site (MDX pages)
5. Inline doc comments in the relevant source files
This applies to changes that either human users or AI agents would need to know about. Do not skip any of these locations.
In the `docs/src/app/` MDX files, always use HTML `<table>` syntax for tables (not markdown pipe tables). This matches the existing convention across the docs site.
## Dashboard (packages/dashboard)
- Never use native browser dialogs (`alert`, `confirm`, `prompt`). Use shadcn/ui components (`Dialog`, `AlertDialog`, etc.) instead.
- Use param-case (kebab-case) for all file and folder names (e.g., `session-tree.tsx`, not `SessionTree.tsx`). The `ui/` directory follows shadcn conventions which already uses param-case.
## Releasing
Releases are manual, single-PR affairs. There is no changesets automation. The maintainer controls the changelog voice and format.
To prepare a release:
1. Create a branch (e.g. `prepare-v0.24.0`)
2. Bump `version` in `package.json`
3. Run `pnpm version:sync` to update `cli/Cargo.toml`, `cli/Cargo.lock`, and `packages/dashboard/package.json`
4. Write the changelog entry in `CHANGELOG.md` at the top, under a new `## <version>` heading, wrapped in `<!-- release:start -->` and `<!-- release:end -->` markers. Remove the `<!-- release:start -->` and `<!-- release:end -->` markers from the previous release entry so only the new release has markers.
5. Add a matching entry to `docs/src/app/changelog/page.mdx` at the top (below the `# Changelog` heading)
6. Open a PR and merge to `main`
When the PR merges, CI compares `package.json` version to what's on npm. If it differs, it builds all 7 platform binaries, publishes to npm, and creates the GitHub release automatically. The GitHub release body is extracted from the content between the `<!-- release:start -->` and `<!-- release:end -->` markers in `CHANGELOG.md`.
### Writing the changelog
Review the git log since the last release and write the entry in `CHANGELOG.md`. Follow the existing format and voice. Group changes under `### New Features`, `### Bug Fixes`, `### Improvements`, etc. Bold the feature/fix name, then describe it concisely. Reference PR numbers in parentheses.
Wrap the release notes (everything between the `## <version>` heading and the previous version) in markers so CI can extract them for the GitHub release. Only the current release should have markers; remove the `<!-- release:start -->` and `<!-- release:end -->` markers from any previous release entry:
```markdown
## 0.24.1
<!-- release:start -->
### Bug Fixes
- Fixed **baz** not working when qux is enabled (#1235)
### Contributors
- @ctate
<!-- release:end -->
## 0.24.0
### New Features
- **Foo command** - Added `foo` command for bar (#1234)
```
Include a `### Contributors` section listing the GitHub usernames (with `@` prefix) of everyone who contributed to the release. Check the git log between the previous tag and HEAD to find them.
Do not prefix entries with commit hashes. Do not use the changesets `### Patch Changes` / `### Minor Changes` headings. Use descriptive section names instead.
### Docs changelog
The docs changelog at `docs/src/app/changelog/page.mdx` mirrors `CHANGELOG.md` but uses a slightly different format. Each entry uses:
- A `v` prefix on the version (e.g. `## v0.24.0`)
- A date line with the full date: `<p className="text-[#888] text-sm">March 30, 2026</p>`
- A `---` separator between entries
Match the existing style in that file.
## Architecture
This is a Rust codebase. The browser automation daemon lives in `cli/src/native/` (daemon, actions, browser, CDP client, snapshot, state). The `--engine` flag selects Chrome vs Lightpanda. The `install` command downloads Chrome from Chrome for Testing directly.
## Testing
### Unit Tests
```bash
cd cli && cargo test
```
Runs all unit tests (~320 tests). These are fast and don't require Chrome.
### End-to-End Tests
```bash
cd cli && cargo test e2e -- --ignored --test-threads=1
```
Runs 18 e2e tests that launch real headless Chrome instances and exercise the full native daemon command pipeline. Requirements:
- Chrome must be installed
- Must run serially (`--test-threads=1`) to avoid Chrome instance contention
- Tests are `#[ignore]`'d so they don't run during normal `cargo test`
The e2e tests live in `cli/src/native/e2e_tests.rs` and cover: launch/close, navigation, snapshots, screenshots, form interaction, cookies, storage, tabs, element queries, viewport/emulation, domain filtering, diff, state management, error handling, and Phase 8 commands.
### Linting and Formatting
```bash
cd cli && cargo fmt -- --check # Check formatting
cd cli && cargo clippy # Lint
```
## Windows Debugging
A remote Windows Server 2022 EC2 instance is available for debugging Windows-specific issues. It uses AWS Systems Manager (SSM) with no SSH or open ports. Commands run via `aws ssm send-command` and return stdout/stderr.
### Prerequisites
The instance must be provisioned first (one-time, by a human):
```bash
./scripts/windows-debug/provision.sh
```
Requires: AWS CLI v2 configured with `ec2:*`, `iam:CreateRole`, `iam:AttachRolePolicy`, `ssm:SendCommand`, `ssm:GetCommandInvocation` permissions and a default VPC.
### Usage
Start the instance (if stopped):
```bash
./scripts/windows-debug/start.sh
```
Run a command on Windows:
```bash
./scripts/windows-debug/run.sh "<powershell-command>"
```
Sync the current git branch and rebuild:
```bash
./scripts/windows-debug/sync.sh
```
Stop the instance when done (avoids cost):
```bash
./scripts/windows-debug/stop.sh
```
### Common Workflows
Run unit tests on Windows:
```bash
./scripts/windows-debug/run.sh "cd C:\agent-browser && cargo test --manifest-path cli\Cargo.toml"
```
Run e2e tests on Windows:
```bash
./scripts/windows-debug/run.sh "cd C:\agent-browser && cargo test e2e --manifest-path cli\Cargo.toml -- --ignored --test-threads=1"
```
Check bootstrap progress (first boot only):
```bash
./scripts/windows-debug/run.sh "Get-Content C:\bootstrap.log"
```
The repo lives at `C:\agent-browser` on the instance. Rust, Git, and Chrome are pre-installed. The `run.sh` wrapper automatically adds cargo and git to PATH.
<!-- opensrc:start -->
+67 -517
View File
@@ -1,550 +1,100 @@
# agent-browser
# agent-browser-stealth
Headless browser automation CLI for AI agents. Fast Rust CLI with Node.js fallback.
Stealth fork of [agent-browser](https://github.com/vercel-labs/agent-browser) — connects to your real Chrome, shares your login sessions, and is undetectable by anti-bot systems.
## Installation
For basic usage, commands, and API reference, see the [upstream documentation](https://github.com/vercel-labs/agent-browser).
### npm (recommended)
## Why this fork?
**agent-browser** launches a fresh browser with an empty profile. You need to log in again, and websites can detect it's automated.
**agent-browser-stealth** connects to your existing Chrome. Your cookies, sessions, and browser fingerprint are all real — because it IS your real browser.
| | agent-browser | agent-browser-stealth |
|---|---|---|
| Browser | Launches new Chrome | Connects to your Chrome |
| Login state | Empty, need to re-login | Your existing sessions |
| Fingerprint | Automation markers present | Your real fingerprint |
| User collaboration | Separate window | Same window, take over anytime |
| CAPTCHA | Agent stuck | You solve it, agent continues |
## Install
```bash
npm install -g agent-browser
agent-browser install # Download Chromium
npm install -g agent-browser-stealth
```
### From Source
### Install the AI agent skills
The repo ships SKILL.md files for Claude Code, Cursor, etc. Pull them into the current project with [skills.sh](https://skills.sh):
```bash
git clone https://github.com/vercel-labs/agent-browser
cd agent-browser
pnpm install
pnpm build
pnpm build:native # Requires Rust (https://rustup.rs)
pnpm link --global # Makes agent-browser available globally
agent-browser install
npx skills add leeguooooo/agent-browser-stealth
```
### Linux Dependencies
This drops `skills/agent-browser` (and the specialized `skill-data/{core,electron,slack,dogfood,agentcore,vercel-sandbox}`) into your project so your AI agent gets the right usage patterns and pre-approved bash permissions for `agent-browser`, `agent-browser-stealth`, and `abs`.
On Linux, install system dependencies:
## Setup (one time)
Enable Chrome DevTools Protocol in your Chrome:
1. Open `chrome://inspect/#remote-debugging` in Chrome
2. Toggle the switch on
That's it. This setting persists across Chrome restarts.
## Usage
```bash
agent-browser install --with-deps
# or manually: npx playwright install-deps chromium
# Connect to your Chrome and navigate
agent-browser open https://example.com
# Everything works through your logged-in browser
agent-browser click "Post"
agent-browser fill "Title" "Hello World"
agent-browser screenshot ./page.png
```
## Quick Start
The agent operates in your Chrome — you'll see tabs opening, pages loading, clicks happening in real time. You can take over at any point (e.g. solve a CAPTCHA), then let the agent continue.
### Standalone mode
If you need a separate browser (CI, testing, etc.):
```bash
agent-browser open example.com
agent-browser snapshot # Get accessibility tree with refs
agent-browser click @e2 # Click by ref from snapshot
agent-browser fill @e3 "test@example.com" # Fill by ref
agent-browser get text @e1 # Get text by ref
agent-browser screenshot page.png
agent-browser close
agent-browser --launch open https://example.com
```
### Traditional Selectors (also supported)
In CI environments, standalone mode is used automatically.
```bash
agent-browser click "#submit"
agent-browser fill "#email" "test@example.com"
agent-browser find role button click --name "Submit"
```
## Anti-detection
## Commands
When connected to your real Chrome, we inject **zero** JavaScript patches. Your browser's fingerprint is completely genuine.
### Core Commands
The only thing we do is call `Emulation.setAutomationOverride` via CDP to set `navigator.webdriver = false` at the native Chrome level — undetectable by lie-detection systems like CreepJS.
```bash
agent-browser open <url> # Navigate to URL (aliases: goto, navigate)
agent-browser click <sel> # Click element
agent-browser dblclick <sel> # Double-click element
agent-browser focus <sel> # Focus element
agent-browser type <sel> <text> # Type into element
agent-browser fill <sel> <text> # Clear and fill
agent-browser press <key> # Press key (Enter, Tab, Control+a) (alias: key)
agent-browser keydown <key> # Hold key down
agent-browser keyup <key> # Release key
agent-browser hover <sel> # Hover element
agent-browser select <sel> <val> # Select dropdown option
agent-browser check <sel> # Check checkbox
agent-browser uncheck <sel> # Uncheck checkbox
agent-browser scroll <dir> [px] # Scroll (up/down/left/right)
agent-browser scrollintoview <sel> # Scroll element into view (alias: scrollinto)
agent-browser drag <src> <tgt> # Drag and drop
agent-browser upload <sel> <files> # Upload files
agent-browser screenshot [path] # Take screenshot (--full for full page)
agent-browser pdf <path> # Save as PDF
agent-browser snapshot # Accessibility tree with refs (best for AI)
agent-browser eval <js> # Run JavaScript
agent-browser close # Close browser (aliases: quit, exit)
```
**Test results (connected to real Chrome):**
### Get Info
| Test site | Result |
|---|---|
| [CreepJS](https://abrahamjuliot.github.io/creepjs/) | 0% stealth, 0% headless |
| [bot.sannysoft.com](https://bot.sannysoft.com) | All green |
| [Cloudflare Turnstile](https://nowsecure.nl) | Passed |
```bash
agent-browser get text <sel> # Get text content
agent-browser get html <sel> # Get innerHTML
agent-browser get value <sel> # Get input value
agent-browser get attr <sel> <attr> # Get attribute
agent-browser get title # Get page title
agent-browser get url # Get current URL
agent-browser get count <sel> # Count matching elements
agent-browser get box <sel> # Get bounding box
```
When using `--launch` mode (standalone browser), a full suite of 32 stealth patches is applied for headless Chrome.
### Check State
## Differences from upstream
```bash
agent-browser is visible <sel> # Check if visible
agent-browser is enabled <sel> # Check if enabled
agent-browser is checked <sel> # Check if checked
```
Based on [agent-browser v0.27.0](https://github.com/vercel-labs/agent-browser). Changes:
### Find Elements (Semantic Locators)
- **Auto-connect is default** — `agent-browser open <url>` connects to your Chrome instead of launching a new one
- **CDP-native stealth** — `Emulation.setAutomationOverride` instead of JS patches
- **Dual stealth mode** — zero patches for real Chrome, full patches for `--launch` mode
- **`--launch` / `--new` flag** — explicitly start a standalone browser
- **CI auto-detection** — standalone mode when `CI` env var is set
```bash
agent-browser find role <role> <action> [value] # By ARIA role
agent-browser find text <text> <action> # By text content
agent-browser find label <label> <action> [value] # By label
agent-browser find placeholder <ph> <action> [value] # By placeholder
agent-browser find alt <text> <action> # By alt text
agent-browser find title <text> <action> # By title attr
agent-browser find testid <id> <action> [value] # By data-testid
agent-browser find first <sel> <action> [value] # First match
agent-browser find last <sel> <action> [value] # Last match
agent-browser find nth <n> <sel> <action> [value] # Nth match
```
**Actions:** `click`, `fill`, `check`, `hover`, `text`
**Examples:**
```bash
agent-browser find role button click --name "Submit"
agent-browser find text "Sign In" click
agent-browser find label "Email" fill "test@test.com"
agent-browser find first ".item" click
agent-browser find nth 2 "a" text
```
### Wait
```bash
agent-browser wait <selector> # Wait for element to be visible
agent-browser wait <ms> # Wait for time (milliseconds)
agent-browser wait --text "Welcome" # Wait for text to appear
agent-browser wait --url "**/dash" # Wait for URL pattern
agent-browser wait --load networkidle # Wait for load state
agent-browser wait --fn "window.ready === true" # Wait for JS condition
```
**Load states:** `load`, `domcontentloaded`, `networkidle`
### Mouse Control
```bash
agent-browser mouse move <x> <y> # Move mouse
agent-browser mouse down [button] # Press button (left/right/middle)
agent-browser mouse up [button] # Release button
agent-browser mouse wheel <dy> [dx] # Scroll wheel
```
### Browser Settings
```bash
agent-browser set viewport <w> <h> # Set viewport size
agent-browser set device <name> # Emulate device ("iPhone 14")
agent-browser set geo <lat> <lng> # Set geolocation
agent-browser set offline [on|off] # Toggle offline mode
agent-browser set headers <json> # Extra HTTP headers
agent-browser set credentials <u> <p> # HTTP basic auth
agent-browser set media [dark|light] # Emulate color scheme
```
### Cookies & Storage
```bash
agent-browser cookies # Get all cookies
agent-browser cookies set <name> <val> # Set cookie
agent-browser cookies clear # Clear cookies
agent-browser storage local # Get all localStorage
agent-browser storage local <key> # Get specific key
agent-browser storage local set <k> <v> # Set value
agent-browser storage local clear # Clear all
agent-browser storage session # Same for sessionStorage
```
### Network
```bash
agent-browser network route <url> # Intercept requests
agent-browser network route <url> --abort # Block requests
agent-browser network route <url> --body <json> # Mock response
agent-browser network unroute [url] # Remove routes
agent-browser network requests # View tracked requests
agent-browser network requests --filter api # Filter requests
```
### Tabs & Windows
```bash
agent-browser tab # List tabs
agent-browser tab new [url] # New tab (optionally with URL)
agent-browser tab <n> # Switch to tab n
agent-browser tab close [n] # Close tab
agent-browser window new # New window
```
### Frames
```bash
agent-browser frame <sel> # Switch to iframe
agent-browser frame main # Back to main frame
```
### Dialogs
```bash
agent-browser dialog accept [text] # Accept (with optional prompt text)
agent-browser dialog dismiss # Dismiss
```
### Debug
```bash
agent-browser trace start [path] # Start recording trace
agent-browser trace stop [path] # Stop and save trace
agent-browser console # View console messages
agent-browser console --clear # Clear console
agent-browser errors # View page errors
agent-browser errors --clear # Clear errors
agent-browser highlight <sel> # Highlight element
agent-browser state save <path> # Save auth state
agent-browser state load <path> # Load auth state
```
### Navigation
```bash
agent-browser back # Go back
agent-browser forward # Go forward
agent-browser reload # Reload page
```
### Setup
```bash
agent-browser install # Download Chromium browser
agent-browser install --with-deps # Also install system deps (Linux)
```
## Sessions
Run multiple isolated browser instances:
```bash
# Different sessions
agent-browser --session agent1 open site-a.com
agent-browser --session agent2 open site-b.com
# Or via environment variable
AGENT_BROWSER_SESSION=agent1 agent-browser click "#btn"
# List active sessions
agent-browser session list
# Output:
# Active sessions:
# -> default
# agent1
# Show current session
agent-browser session
```
Each session has its own:
- Browser instance
- Cookies and storage
- Navigation history
- Authentication state
## Snapshot Options
The `snapshot` command supports filtering to reduce output size:
```bash
agent-browser snapshot # Full accessibility tree
agent-browser snapshot -i # Interactive elements only (buttons, inputs, links)
agent-browser snapshot -c # Compact (remove empty structural elements)
agent-browser snapshot -d 3 # Limit depth to 3 levels
agent-browser snapshot -s "#main" # Scope to CSS selector
agent-browser snapshot -i -c -d 5 # Combine options
```
| Option | Description |
|--------|-------------|
| `-i, --interactive` | Only show interactive elements (buttons, links, inputs) |
| `-c, --compact` | Remove empty structural elements |
| `-d, --depth <n>` | Limit tree depth |
| `-s, --selector <sel>` | Scope to CSS selector |
## Options
| Option | Description |
|--------|-------------|
| `--session <name>` | Use isolated session (or `AGENT_BROWSER_SESSION` env) |
| `--headers <json>` | Set HTTP headers scoped to the URL's origin |
| `--executable-path <path>` | Custom browser executable (or `AGENT_BROWSER_EXECUTABLE_PATH` env) |
| `--json` | JSON output (for agents) |
| `--full, -f` | Full page screenshot |
| `--name, -n` | Locator name filter |
| `--exact` | Exact text match |
| `--headed` | Show browser window (not headless) |
| `--cdp <port>` | Connect via Chrome DevTools Protocol |
| `--debug` | Debug output |
## Selectors
### Refs (Recommended for AI)
Refs provide deterministic element selection from snapshots:
```bash
# 1. Get snapshot with refs
agent-browser snapshot
# Output:
# - heading "Example Domain" [ref=e1] [level=1]
# - button "Submit" [ref=e2]
# - textbox "Email" [ref=e3]
# - link "Learn more" [ref=e4]
# 2. Use refs to interact
agent-browser click @e2 # Click the button
agent-browser fill @e3 "test@example.com" # Fill the textbox
agent-browser get text @e1 # Get heading text
agent-browser hover @e4 # Hover the link
```
**Why use refs?**
- **Deterministic**: Ref points to exact element from snapshot
- **Fast**: No DOM re-query needed
- **AI-friendly**: Snapshot + ref workflow is optimal for LLMs
### CSS Selectors
```bash
agent-browser click "#id"
agent-browser click ".class"
agent-browser click "div > button"
```
### Text & XPath
```bash
agent-browser click "text=Submit"
agent-browser click "xpath=//button"
```
### Semantic Locators
```bash
agent-browser find role button click --name "Submit"
agent-browser find label "Email" fill "test@test.com"
```
## Agent Mode
Use `--json` for machine-readable output:
```bash
agent-browser snapshot --json
# Returns: {"success":true,"data":{"snapshot":"...","refs":{"e1":{"role":"heading","name":"Title"},...}}}
agent-browser get text @e1 --json
agent-browser is visible @e2 --json
```
### Optimal AI Workflow
```bash
# 1. Navigate and get snapshot
agent-browser open example.com
agent-browser snapshot -i --json # AI parses tree and refs
# 2. AI identifies target refs from snapshot
# 3. Execute actions using refs
agent-browser click @e2
agent-browser fill @e3 "input text"
# 4. Get new snapshot if page changed
agent-browser snapshot -i --json
```
## Headed Mode
Show the browser window for debugging:
```bash
agent-browser open example.com --headed
```
This opens a visible browser window instead of running headless.
## Authenticated Sessions
Use `--headers` to set HTTP headers for a specific origin, enabling authentication without login flows:
```bash
# Headers are scoped to api.example.com only
agent-browser open api.example.com --headers '{"Authorization": "Bearer <token>"}'
# Requests to api.example.com include the auth header
agent-browser snapshot -i --json
agent-browser click @e2
# Navigate to another domain - headers are NOT sent (safe!)
agent-browser open other-site.com
```
This is useful for:
- **Skipping login flows** - Authenticate via headers instead of UI
- **Switching users** - Start new sessions with different auth tokens
- **API testing** - Access protected endpoints directly
- **Security** - Headers are scoped to the origin, not leaked to other domains
To set headers for multiple origins, use `--headers` with each `open` command:
```bash
agent-browser open api.example.com --headers '{"Authorization": "Bearer token1"}'
agent-browser open api.acme.com --headers '{"Authorization": "Bearer token2"}'
```
For global headers (all domains), use `set headers`:
```bash
agent-browser set headers '{"X-Custom-Header": "value"}'
```
## Custom Browser Executable
Use a custom browser executable instead of the bundled Chromium. This is useful for:
- **Serverless deployment**: Use lightweight Chromium builds like `@sparticuz/chromium` (~50MB vs ~684MB)
- **System browsers**: Use an existing Chrome/Chromium installation
- **Custom builds**: Use modified browser builds
### CLI Usage
```bash
# Via flag
agent-browser --executable-path /path/to/chromium open example.com
# Via environment variable
AGENT_BROWSER_EXECUTABLE_PATH=/path/to/chromium agent-browser open example.com
```
### Serverless Example (Vercel/AWS Lambda)
```typescript
import chromium from '@sparticuz/chromium';
import { BrowserManager } from 'agent-browser';
export async function handler() {
const browser = new BrowserManager();
await browser.launch({
executablePath: await chromium.executablePath(),
headless: true,
});
// ... use browser
}
```
## CDP Mode
Connect to an existing browser via Chrome DevTools Protocol:
```bash
# Connect to Electron app
agent-browser --cdp 9222 snapshot
# Connect to Chrome with remote debugging
# (Start Chrome with: google-chrome --remote-debugging-port=9222)
agent-browser --cdp 9222 open about:blank
```
This enables control of:
- Electron apps
- Chrome/Chromium instances with remote debugging
- WebView2 applications
- Any browser exposing a CDP endpoint
## Architecture
agent-browser uses a client-daemon architecture:
1. **Rust CLI** (fast native binary) - Parses commands, communicates with daemon
2. **Node.js Daemon** - Manages Playwright browser instance
3. **Fallback** - If native binary unavailable, uses Node.js directly
The daemon starts automatically on first command and persists between commands for fast subsequent operations.
**Browser Engine:** Uses Chromium by default. The daemon also supports Firefox and WebKit via the Playwright protocol.
## Platforms
| Platform | Binary | Fallback |
|----------|--------|----------|
| macOS ARM64 | Native Rust | Node.js |
| macOS x64 | Native Rust | Node.js |
| Linux ARM64 | Native Rust | Node.js |
| Linux x64 | Native Rust | Node.js |
| Windows x64 | Native Rust | Node.js |
## Usage with AI Agents
### Just ask the agent
The simplest approach - just tell your agent to use it:
```
Use agent-browser to test the login flow. Run agent-browser --help to see available commands.
```
The `--help` output is comprehensive and most agents can figure it out from there.
### AGENTS.md / CLAUDE.md
For more consistent results, add to your project or global instructions file:
```markdown
## Browser Automation
Use `agent-browser` for web automation. Run `agent-browser --help` for all commands.
Core workflow:
1. `agent-browser open <url>` - Navigate to page
2. `agent-browser snapshot -i` - Get interactive elements with refs (@e1, @e2)
3. `agent-browser click @e1` / `fill @e2 "text"` - Interact using refs
4. Re-snapshot after page changes
```
### Claude Code Skill
For Claude Code, a [skill](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices) provides richer context:
```bash
cp -r node_modules/agent-browser/skills/agent-browser .claude/skills/
```
Or download:
```bash
mkdir -p .claude/skills/agent-browser
curl -o .claude/skills/agent-browser/SKILL.md \
https://raw.githubusercontent.com/vercel-labs/agent-browser/main/skills/agent-browser/SKILL.md
```
All upstream features (commands, snapshots, screenshots, recordings, tabs, sessions, etc.) work the same. See the [upstream repo](https://github.com/vercel-labs/agent-browser) for full documentation.
## License
Apache-2.0
Apache-2.0 (same as upstream)
BIN
View File
Binary file not shown.
-5
View File
@@ -1,5 +0,0 @@
@echo off
setlocal
set "SCRIPT_DIR=%~dp0"
node "%SCRIPT_DIR%..\dist\index.js" %*
exit /b %errorlevel%
+1
View File
@@ -0,0 +1 @@
/Users/leo/github.com/agent-browser/cli/target/release/agent-browser: /Users/leo/github.com/agent-browser/cli/build.rs /Users/leo/github.com/agent-browser/cli/cdp-protocol/browser_protocol.json /Users/leo/github.com/agent-browser/cli/cdp-protocol/js_protocol.json /Users/leo/github.com/agent-browser/cli/src/color.rs /Users/leo/github.com/agent-browser/cli/src/commands.rs /Users/leo/github.com/agent-browser/cli/src/connection.rs /Users/leo/github.com/agent-browser/cli/src/flags.rs /Users/leo/github.com/agent-browser/cli/src/install.rs /Users/leo/github.com/agent-browser/cli/src/main.rs /Users/leo/github.com/agent-browser/cli/src/output.rs /Users/leo/github.com/agent-browser/cli/src/validation.rs
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env node
/**
* Cross-platform CLI wrapper for agent-browser
*
* This wrapper enables npx support on Windows where shell scripts don't work.
* For global installs, postinstall.js patches the shims to invoke the native
* binary directly (zero overhead).
*/
import { spawn, execSync } from 'child_process';
import { existsSync, accessSync, chmodSync, constants } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { platform, arch } from 'os';
const __dirname = dirname(fileURLToPath(import.meta.url));
// Detect if the system uses musl libc (e.g. Alpine Linux)
function isMusl() {
if (platform() !== 'linux') return false;
try {
const result = execSync('ldd --version 2>&1 || true', { encoding: 'utf8' });
return result.toLowerCase().includes('musl');
} catch {
return existsSync('/lib/ld-musl-x86_64.so.1') || existsSync('/lib/ld-musl-aarch64.so.1');
}
}
// Map Node.js platform/arch to binary naming convention
function getBinaryName() {
const os = platform();
const cpuArch = arch();
let osKey;
switch (os) {
case 'darwin':
osKey = 'darwin';
break;
case 'linux':
osKey = isMusl() ? 'linux-musl' : 'linux';
break;
case 'win32':
osKey = 'win32';
break;
default:
return null;
}
let archKey;
switch (cpuArch) {
case 'x64':
case 'x86_64':
archKey = 'x64';
break;
case 'arm64':
case 'aarch64':
archKey = 'arm64';
break;
default:
return null;
}
const ext = os === 'win32' ? '.exe' : '';
return `agent-browser-${osKey}-${archKey}${ext}`;
}
function main() {
const binaryName = getBinaryName();
if (!binaryName) {
console.error(`Error: Unsupported platform: ${platform()}-${arch()}`);
process.exit(1);
}
const binaryPath = join(__dirname, binaryName);
if (!existsSync(binaryPath)) {
console.error(`Error: No binary found for ${platform()}-${arch()}`);
console.error(`Expected: ${binaryPath}`);
console.error('');
console.error('Run "npm run build:native" to build for your platform,');
console.error('or reinstall the package to trigger the postinstall download.');
process.exit(1);
}
// Ensure binary is executable (fixes EACCES on macOS/Linux when postinstall didn't run,
// e.g., when using bun which blocks lifecycle scripts by default)
if (platform() !== 'win32') {
try {
accessSync(binaryPath, constants.X_OK);
} catch {
// Binary exists but isn't executable - fix it
try {
chmodSync(binaryPath, 0o755);
} catch (chmodErr) {
console.error(`Error: Cannot make binary executable: ${chmodErr.message}`);
console.error('Try running: chmod +x ' + binaryPath);
process.exit(1);
}
}
}
// Spawn the native binary with inherited stdio
const child = spawn(binaryPath, process.argv.slice(2), {
stdio: 'inherit',
windowsHide: false,
});
child.on('error', (err) => {
console.error(`Error executing binary: ${err.message}`);
process.exit(1);
});
child.on('close', (code) => {
process.exit(code ?? 0);
});
}
main();
+3018 -12
View File
File diff suppressed because it is too large Load Diff
+46 -2
View File
@@ -1,13 +1,45 @@
[package]
name = "agent-browser"
version = "0.4.4"
name = "agent-browser-stealth"
version = "0.27.0-fork.9"
edition = "2021"
description = "Fast browser automation CLI for AI agents"
license = "Apache-2.0"
repository = "https://github.com/leeguooooo/agent-browser-stealth"
homepage = "https://github.com/leeguooooo/agent-browser-stealth"
readme = "../README.md"
keywords = ["browser", "automation", "ai", "cdp", "chrome"]
categories = ["command-line-utilities", "web-programming"]
[[bin]]
name = "agent-browser"
path = "src/main.rs"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
regex-lite = "0.1"
dirs = "5.0"
base64 = "0.22"
getrandom = "0.2"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "time", "sync", "signal", "process"] }
tokio-tungstenite = { version = "0.24", features = ["rustls-tls-webpki-roots"] }
futures-util = "0.3"
url = "2"
uuid = { version = "1", features = ["v4"] }
image = "0.25"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls-webpki-roots", "stream"] }
sha2 = "0.10"
aes-gcm = "0.10"
async-trait = "0.1"
socket2 = "0.6"
similar = "2"
zip = { version = "8.2.0", default-features = false, features = ["deflate"] }
time = { version = "0.3", features = ["formatting"] }
hmac = "0.12"
hex = "0.4"
chrono = "0.4"
urlencoding = "2"
rust-embed = "8"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
@@ -15,8 +47,20 @@ libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.52", features = ["Win32_System_Threading", "Win32_Foundation"] }
[dev-dependencies]
tempfile = "3"
[build-dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
[profile.release]
opt-level = 3
lto = true
codegen-units = 1
strip = true
[profile.ci]
inherits = "release"
lto = "thin"
codegen-units = 16
+498
View File
@@ -0,0 +1,498 @@
use std::collections::HashSet;
use std::env;
use std::fs;
use std::path::Path;
/// Ensure `packages/dashboard/out/` exists so `rust-embed` doesn't fail during
/// Rust-only dev builds where the dashboard hasn't been built. The placeholder
/// `index.html` is only written when the directory is completely absent.
fn ensure_dashboard_dir() {
let dashboard_out = Path::new("../packages/dashboard/out");
println!("cargo:rerun-if-changed=../packages/dashboard/out");
if !dashboard_out.join("index.html").exists() {
let _ = fs::create_dir_all(dashboard_out);
let _ = fs::write(
dashboard_out.join("index.html"),
"<!DOCTYPE html><html><body><p>Dashboard not built. Run: cd packages/dashboard &amp;&amp; pnpm build</p></body></html>\n",
);
}
}
fn main() {
ensure_dashboard_dir();
let protocol_dir = Path::new("cdp-protocol");
let out_dir = env::var("OUT_DIR").unwrap();
let out_path = Path::new(&out_dir).join("cdp_generated.rs");
let browser_path = protocol_dir.join("browser_protocol.json");
let js_path = protocol_dir.join("js_protocol.json");
if !browser_path.exists() && !js_path.exists() {
fs::write(
&out_path,
"// No protocol JSON files found in cdp-protocol/\n",
)
.unwrap();
return;
}
let mut all_domains: Vec<Domain> = Vec::new();
for path in [&browser_path, &js_path] {
if !path.exists() {
continue;
}
println!("cargo:rerun-if-changed={}", path.display());
let content = fs::read_to_string(path).unwrap();
let protocol: ProtocolSpec = match serde_json::from_str(&content) {
Ok(p) => p,
Err(e) => {
eprintln!("cargo:warning=Failed to parse {}: {}", path.display(), e);
continue;
}
};
all_domains.extend(protocol.domains);
}
// Collect all known type IDs per domain for cross-domain resolution
let mut domain_types: std::collections::HashMap<String, HashSet<String>> =
std::collections::HashMap::new();
for domain in &all_domains {
let mut types = HashSet::new();
for td in &domain.types {
types.insert(td.id.clone());
}
domain_types.insert(domain.domain.clone(), types);
}
// Known recursive struct fields that need Box wrapping
let recursive_fields: HashSet<(&str, &str, &str)> = [
("DOM", "Node", "contentDocument"),
("DOM", "Node", "templateContent"),
("DOM", "Node", "importedDocument"),
("Accessibility", "AXNode", "sources"),
("Runtime", "StackTrace", "parent"),
]
.into_iter()
.collect();
let mut output = String::new();
output.push_str("use serde::{Deserialize, Serialize};\n\n");
for domain in &all_domains {
generate_domain(domain, &domain_types, &recursive_fields, &mut output);
}
fs::write(&out_path, &output).unwrap();
}
#[allow(dead_code)]
#[derive(serde::Deserialize)]
struct ProtocolSpec {
domains: Vec<Domain>,
}
#[allow(dead_code)]
#[derive(serde::Deserialize, Clone)]
struct Domain {
domain: String,
#[serde(default)]
types: Vec<TypeDef>,
#[serde(default)]
commands: Vec<Command>,
#[serde(default)]
events: Vec<Event>,
}
#[allow(dead_code)]
#[derive(serde::Deserialize, Clone)]
struct TypeDef {
id: String,
#[serde(rename = "type", default)]
type_kind: String,
#[serde(default)]
properties: Vec<Property>,
#[serde(rename = "enum", default)]
enum_values: Vec<String>,
#[serde(default)]
description: Option<String>,
}
#[allow(dead_code)]
#[derive(serde::Deserialize, Clone)]
struct Command {
name: String,
#[serde(default)]
parameters: Vec<Property>,
#[serde(default)]
returns: Vec<Property>,
#[serde(default)]
description: Option<String>,
}
#[allow(dead_code)]
#[derive(serde::Deserialize, Clone)]
struct Event {
name: String,
#[serde(default)]
parameters: Vec<Property>,
#[serde(default)]
description: Option<String>,
}
#[allow(dead_code)]
#[derive(serde::Deserialize, Clone)]
struct Property {
name: String,
#[serde(rename = "type", default)]
type_kind: Option<String>,
#[serde(rename = "$ref", default)]
ref_type: Option<String>,
#[serde(default)]
optional: bool,
#[serde(default)]
description: Option<String>,
#[serde(default)]
items: Option<Box<ItemType>>,
#[serde(rename = "enum", default)]
enum_values: Vec<String>,
}
#[allow(dead_code)]
#[derive(serde::Deserialize, Clone)]
struct ItemType {
#[serde(rename = "type", default)]
type_kind: Option<String>,
#[serde(rename = "$ref", default)]
ref_type: Option<String>,
}
fn to_pascal_case(s: &str) -> String {
let mut result = String::new();
let mut capitalize = true;
for c in s.chars() {
if c == '_' || c == '-' || c == '.' {
capitalize = true;
} else if capitalize {
result.push(c.to_ascii_uppercase());
capitalize = false;
} else {
result.push(c);
}
}
result
}
fn to_snake_case(s: &str) -> String {
let mut result = String::new();
let chars: Vec<char> = s.chars().collect();
for (i, &c) in chars.iter().enumerate() {
if c.is_uppercase() && i > 0 {
// Only insert underscore at transitions from lowercase to uppercase,
// or when an uppercase sequence ends (e.g. "DOM" -> "dom", not "d_o_m")
let prev_upper = chars[i - 1].is_uppercase();
let next_lower = chars.get(i + 1).is_some_and(|n| n.is_lowercase());
if !prev_upper || next_lower {
result.push('_');
}
}
result.push(c.to_ascii_lowercase());
}
result
}
/// Resolve a $ref type reference. Cross-domain refs like "Page.FrameId" become
/// `super::cdp_page::FrameId`. Same-domain refs are used directly.
fn resolve_ref(
r: &str,
current_domain: &str,
domain_types: &std::collections::HashMap<String, HashSet<String>>,
) -> String {
let parts: Vec<&str> = r.split('.').collect();
if parts.len() == 2 {
let ref_domain = parts[0];
let ref_type = parts[1];
if ref_domain == current_domain {
to_pascal_case(ref_type)
} else {
// Check if this type actually exists in the referenced domain
if domain_types
.get(ref_domain)
.is_some_and(|t| t.contains(ref_type))
{
format!(
"super::cdp_{}::{}",
to_snake_case(ref_domain),
to_pascal_case(ref_type)
)
} else {
// Fall back to serde_json::Value for unknown cross-domain refs
"serde_json::Value".to_string()
}
}
} else {
to_pascal_case(r)
}
}
fn map_type_in_domain(
prop: &Property,
current_domain: &str,
domain_types: &std::collections::HashMap<String, HashSet<String>>,
) -> String {
if let Some(ref r) = prop.ref_type {
let type_name = resolve_ref(r, current_domain, domain_types);
if prop.optional {
format!("Option<{}>", type_name)
} else {
type_name
}
} else if let Some(ref t) = prop.type_kind {
let base = match t.as_str() {
"string" => "String".to_string(),
"integer" => "i64".to_string(),
"number" => "f64".to_string(),
"boolean" => "bool".to_string(),
"object" => "serde_json::Value".to_string(),
"any" => "serde_json::Value".to_string(),
"array" => {
if let Some(ref items) = prop.items {
let inner = if let Some(ref r) = items.ref_type {
resolve_ref(r, current_domain, domain_types)
} else {
match items.type_kind.as_deref().unwrap_or("any") {
"string" => "String".to_string(),
"integer" => "i64".to_string(),
"number" => "f64".to_string(),
"boolean" => "bool".to_string(),
_ => "serde_json::Value".to_string(),
}
};
format!("Vec<{}>", inner)
} else {
"Vec<serde_json::Value>".to_string()
}
}
_ => "serde_json::Value".to_string(),
};
if prop.optional {
format!("Option<{}>", base)
} else {
base
}
} else if prop.optional {
"Option<serde_json::Value>".to_string()
} else {
"serde_json::Value".to_string()
}
}
fn is_rust_keyword(s: &str) -> bool {
matches!(
s,
"type"
| "self"
| "Self"
| "super"
| "move"
| "ref"
| "fn"
| "mod"
| "use"
| "pub"
| "let"
| "mut"
| "const"
| "static"
| "if"
| "else"
| "for"
| "while"
| "loop"
| "match"
| "return"
| "break"
| "continue"
| "as"
| "in"
| "impl"
| "trait"
| "struct"
| "enum"
| "where"
| "async"
| "await"
| "dyn"
| "box"
| "yield"
| "override"
| "crate"
| "extern"
)
}
fn generate_domain(
domain: &Domain,
domain_types: &std::collections::HashMap<String, HashSet<String>>,
recursive_fields: &HashSet<(&str, &str, &str)>,
output: &mut String,
) {
let mod_name = to_snake_case(&domain.domain);
output.push_str(&format!(
"#[allow(dead_code, non_snake_case, non_camel_case_types, clippy::enum_variant_names)]\npub mod cdp_{} {{\n",
mod_name
));
output.push_str(" use super::*;\n\n");
for type_def in &domain.types {
if !type_def.enum_values.is_empty() {
// Deduplicate enum variants (some CDP enums have duplicated PascalCase forms)
let mut seen_variants = HashSet::new();
output.push_str(" #[derive(Debug, Clone, Serialize, Deserialize)]\n");
output.push_str(&format!(" pub enum {} {{\n", type_def.id));
for val in &type_def.enum_values {
let mut variant = to_pascal_case(val);
if variant == "Self" {
variant = "SelfValue".to_string();
}
if variant.chars().next().is_some_and(|c| c.is_ascii_digit()) {
variant = format!("V{}", variant);
}
if seen_variants.insert(variant.clone()) {
output.push_str(&format!(
" #[serde(rename = \"{}\")]\n {},\n",
val, variant
));
}
}
output.push_str(" }\n\n");
} else if type_def.type_kind == "object" && !type_def.properties.is_empty() {
output.push_str(
" #[derive(Debug, Clone, Serialize, Deserialize)]\n #[serde(rename_all = \"camelCase\")]\n",
);
output.push_str(&format!(" pub struct {} {{\n", type_def.id));
for prop in &type_def.properties {
let field_name = to_snake_case(&prop.name);
let field_name = if is_rust_keyword(&field_name) {
format!("r#{}", field_name)
} else {
field_name
};
let mut rust_type = map_type_in_domain(prop, &domain.domain, domain_types);
// Wrap recursive fields in Box
if recursive_fields.contains(&(
domain.domain.as_str(),
type_def.id.as_str(),
prop.name.as_str(),
)) {
if rust_type.starts_with("Option<") {
let inner = &rust_type[7..rust_type.len() - 1];
rust_type = format!("Option<Box<{}>>", inner);
} else {
rust_type = format!("Box<{}>", rust_type);
}
}
if prop.optional {
output
.push_str(" #[serde(skip_serializing_if = \"Option::is_none\")]\n");
}
output.push_str(&format!(" pub {}: {},\n", field_name, rust_type));
}
output.push_str(" }\n\n");
} else if type_def.type_kind == "object" && type_def.properties.is_empty() {
output.push_str(&format!(
" pub type {} = serde_json::Value;\n\n",
type_def.id
));
} else if type_def.type_kind == "array" {
output.push_str(&format!(
" pub type {} = Vec<serde_json::Value>;\n\n",
type_def.id
));
} else if type_def.type_kind == "string" && type_def.enum_values.is_empty() {
output.push_str(&format!(" pub type {} = String;\n\n", type_def.id));
} else if type_def.type_kind == "integer" {
output.push_str(&format!(" pub type {} = i64;\n\n", type_def.id));
} else if type_def.type_kind == "number" {
output.push_str(&format!(" pub type {} = f64;\n\n", type_def.id));
}
}
for cmd in &domain.commands {
let pascal_name = to_pascal_case(&cmd.name);
if !cmd.parameters.is_empty() {
output.push_str(
" #[derive(Debug, Clone, Serialize, Deserialize)]\n #[serde(rename_all = \"camelCase\")]\n",
);
output.push_str(&format!(" pub struct {}Params {{\n", pascal_name));
for param in &cmd.parameters {
let field_name = to_snake_case(&param.name);
let field_name = if is_rust_keyword(&field_name) {
format!("r#{}", field_name)
} else {
field_name
};
let rust_type = map_type_in_domain(param, &domain.domain, domain_types);
if param.optional {
output
.push_str(" #[serde(skip_serializing_if = \"Option::is_none\")]\n");
}
output.push_str(&format!(" pub {}: {},\n", field_name, rust_type));
}
output.push_str(" }\n\n");
}
if !cmd.returns.is_empty() {
output.push_str(
" #[derive(Debug, Clone, Serialize, Deserialize)]\n #[serde(rename_all = \"camelCase\")]\n",
);
output.push_str(&format!(" pub struct {}Result {{\n", pascal_name));
for ret in &cmd.returns {
let field_name = to_snake_case(&ret.name);
let field_name = if is_rust_keyword(&field_name) {
format!("r#{}", field_name)
} else {
field_name
};
let rust_type = map_type_in_domain(ret, &domain.domain, domain_types);
if ret.optional {
output
.push_str(" #[serde(skip_serializing_if = \"Option::is_none\")]\n");
}
output.push_str(&format!(" pub {}: {},\n", field_name, rust_type));
}
output.push_str(" }\n\n");
}
}
for event in &domain.events {
if !event.parameters.is_empty() {
let pascal_name = to_pascal_case(&event.name);
output.push_str(
" #[derive(Debug, Clone, Serialize, Deserialize)]\n #[serde(rename_all = \"camelCase\")]\n",
);
output.push_str(&format!(" pub struct {}Event {{\n", pascal_name));
for param in &event.parameters {
let field_name = to_snake_case(&param.name);
let field_name = if is_rust_keyword(&field_name) {
format!("r#{}", field_name)
} else {
field_name
};
let rust_type = map_type_in_domain(param, &domain.domain, domain_types);
if param.optional {
output
.push_str(" #[serde(skip_serializing_if = \"Option::is_none\")]\n");
}
output.push_str(&format!(" pub {}: {},\n", field_name, rust_type));
}
output.push_str(" }\n\n");
}
}
output.push_str("}\n\n");
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+503
View File
@@ -0,0 +1,503 @@
use std::io::Write as _;
use std::process::exit;
use serde_json::{json, Value};
use crate::color;
use crate::flags::Flags;
use crate::native::stream::chat;
const DEFAULT_MODEL: &str = "anthropic/claude-sonnet-4.6";
#[derive(Clone, Copy, PartialEq)]
enum Verbosity {
Quiet,
Normal,
Verbose,
}
pub fn run_chat(flags: &Flags, message: Option<String>) {
if !chat::is_chat_enabled() {
if flags.json {
println!(
"{}",
json!({"success": false, "error": "AI_GATEWAY_API_KEY not set. Set the AI_GATEWAY_API_KEY environment variable to enable chat."})
);
} else {
eprintln!(
"{} AI_GATEWAY_API_KEY not set. Set the AI_GATEWAY_API_KEY environment variable to enable chat.",
color::error_indicator()
);
}
exit(1);
}
let verbosity = if flags.quiet {
Verbosity::Quiet
} else if flags.verbose {
Verbosity::Verbose
} else {
Verbosity::Normal
};
let model = flags
.model
.clone()
.unwrap_or_else(|| DEFAULT_MODEL.to_string());
let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime");
let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdin());
match message {
Some(msg) => {
rt.block_on(run_single_turn(
&flags.session,
&model,
&msg,
verbosity,
flags.json,
));
}
None if !is_tty => {
let mut input = String::new();
if let Err(e) = std::io::stdin().read_line(&mut input) {
if flags.json {
println!(
"{}",
json!({"success": false, "error": format!("Failed to read stdin: {}", e)})
);
} else {
eprintln!("{} Failed to read stdin: {}", color::error_indicator(), e);
}
exit(1);
}
let input = input.trim();
if input.is_empty() {
if flags.json {
println!(
"{}",
json!({"success": false, "error": "No input provided"})
);
} else {
eprintln!("{} No input provided", color::error_indicator());
}
exit(1);
}
rt.block_on(run_single_turn(
&flags.session,
&model,
input,
verbosity,
flags.json,
));
}
None => {
rt.block_on(run_interactive(
&flags.session,
&model,
verbosity,
flags.json,
));
}
}
}
async fn run_single_turn(
session: &str,
model: &str,
message: &str,
verbosity: Verbosity,
json_mode: bool,
) {
let mut openai_messages: Vec<Value> =
vec![json!({"role": "system", "content": chat::get_system_prompt()})];
openai_messages.push(json!({"role": "user", "content": message}));
let result = run_chat_turn(session, model, &mut openai_messages, verbosity, json_mode).await;
if !result {
exit(1);
}
}
async fn run_interactive(session: &str, model: &str, verbosity: Verbosity, json_mode: bool) {
let mut openai_messages: Vec<Value> =
vec![json!({"role": "system", "content": chat::get_system_prompt()})];
let gateway_url = std::env::var("AI_GATEWAY_URL")
.unwrap_or_else(|_| chat::DEFAULT_AI_GATEWAY_URL.to_string())
.trim_end_matches('/')
.to_string();
let api_key = std::env::var("AI_GATEWAY_API_KEY").unwrap_or_default();
let url = format!("{}/v1/chat/completions", gateway_url);
let client = chat::http_client();
loop {
if !json_mode {
eprint!("{} ", color::cyan(">"));
let _ = std::io::stderr().flush();
}
let mut input = String::new();
match std::io::stdin().read_line(&mut input) {
Ok(0) => break,
Err(_) => break,
Ok(_) => {}
}
let input = input.trim();
if input.is_empty() {
continue;
}
if matches!(input, "quit" | "exit" | "q") {
break;
}
openai_messages.push(json!({"role": "user", "content": input}));
// Compaction check
let total_chars = chat::estimate_chars(&openai_messages);
if total_chars > chat::COMPACT_THRESHOLD_CHARS
&& openai_messages.len() > chat::KEEP_RECENT_MESSAGES + 2
{
let split = chat::find_safe_split(&openai_messages, chat::KEEP_RECENT_MESSAGES);
let to_summarize = &openai_messages[1..split];
if let Some(summary) =
chat::summarize_for_compaction(client, &url, &api_key, model, to_summarize).await
{
let summary_msg = json!({
"role": "system",
"content": format!("[Conversation summary]\n{}", summary)
});
let recent = openai_messages[split..].to_vec();
openai_messages = vec![openai_messages[0].clone(), summary_msg];
openai_messages.extend(recent);
}
}
let success =
run_chat_turn(session, model, &mut openai_messages, verbosity, json_mode).await;
if !success && !json_mode {
// Continue the loop on error; don't exit interactive mode
}
if !json_mode {
eprintln!();
}
}
}
/// Runs one chat turn: sends messages to the gateway, streams text/tool calls,
/// executes tools in a loop until the model is done. Appends assistant and tool
/// messages to `openai_messages`. Returns true on success.
async fn run_chat_turn(
session: &str,
model: &str,
openai_messages: &mut Vec<Value>,
verbosity: Verbosity,
json_mode: bool,
) -> bool {
let gateway_url = std::env::var("AI_GATEWAY_URL")
.unwrap_or_else(|_| chat::DEFAULT_AI_GATEWAY_URL.to_string())
.trim_end_matches('/')
.to_string();
let api_key = match std::env::var("AI_GATEWAY_API_KEY") {
Ok(k) => k,
Err(_) => {
if json_mode {
println!(
"{}",
json!({"success": false, "error": "AI_GATEWAY_API_KEY not set"})
);
} else {
eprintln!("{} AI_GATEWAY_API_KEY not set", color::error_indicator());
}
return false;
}
};
let tools: Value = serde_json::from_str(chat::CHAT_TOOLS).unwrap();
let url = format!("{}/v1/chat/completions", gateway_url);
let client = chat::http_client();
let total_deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(300);
let tool_timeout = std::time::Duration::from_secs(60);
let mut all_text = String::new();
let mut all_tool_calls: Vec<Value> = Vec::new();
let mut had_text = false;
for _step in 0..50 {
if tokio::time::Instant::now() >= total_deadline {
if json_mode {
println!(
"{}",
json!({"success": false, "error": "Chat session timed out (5 minute limit)."})
);
} else {
eprintln!(
"\n{} Chat session timed out (5 minute limit).",
color::error_indicator()
);
}
return false;
}
let gateway_body = json!({
"model": model,
"messages": openai_messages,
"tools": tools,
"stream": true,
});
let gw_response = match client
.post(&url)
.header("Authorization", format!("Bearer {}", api_key))
.header("Content-Type", "application/json")
.body(gateway_body.to_string())
.send()
.await
{
Ok(r) => r,
Err(e) => {
if json_mode {
println!(
"{}",
json!({"success": false, "error": format!("Gateway request failed: {}", e)})
);
} else {
eprintln!(
"\n{} Gateway request failed: {}",
color::error_indicator(),
e
);
}
return false;
}
};
if !gw_response.status().is_success() {
let body_text = gw_response.text().await.unwrap_or_default();
if json_mode {
println!("{}", json!({"success": false, "error": body_text}));
} else {
eprintln!("\n{} {}", color::error_indicator(), body_text);
}
return false;
}
let (text_chunks, tool_calls) =
parse_gateway_stream(gw_response, verbosity, json_mode).await;
if !text_chunks.is_empty() {
let text = text_chunks.join("");
all_text.push_str(&text);
if !json_mode {
if !had_text && verbosity != Verbosity::Quiet {
// Add blank line before text if we showed tool calls
if !all_tool_calls.is_empty() {
println!();
}
}
had_text = true;
}
let mut content = json!(text);
if let Some(last) = openai_messages.last() {
if last.get("role").and_then(|r| r.as_str()) == Some("assistant")
&& last.get("tool_calls").is_some()
{
content = json!(text);
}
}
openai_messages.push(json!({"role": "assistant", "content": content}));
}
if tool_calls.is_empty() {
break;
}
let tc_values: Vec<Value> = tool_calls
.iter()
.map(|(id, name, args)| {
json!({"id": id, "type": "function", "function": {"name": name, "arguments": args}})
})
.collect();
if text_chunks.is_empty() {
openai_messages.push(json!({"role": "assistant", "tool_calls": tc_values}));
} else {
// If we had both text and tool calls in the same response, merge them
if let Some(last) = openai_messages.last_mut() {
if last.get("role").and_then(|r| r.as_str()) == Some("assistant")
&& last.get("tool_calls").is_none()
{
last["tool_calls"] = json!(tc_values);
} else {
openai_messages.push(json!({"role": "assistant", "tool_calls": tc_values}));
}
}
}
for (tc_id, _tc_name, tc_args) in &tool_calls {
let input: Value = serde_json::from_str(tc_args).unwrap_or(json!({}));
let command = input.get("command").and_then(|c| c.as_str()).unwrap_or("");
if !json_mode && verbosity != Verbosity::Quiet {
eprintln!("{}", color::dim(&format!("> {}", command)));
}
let result =
match tokio::time::timeout(tool_timeout, chat::execute_chat_tool(session, command))
.await
{
Ok(r) => r,
Err(_) => "Tool execution timed out after 60 seconds.".to_string(),
};
if !json_mode && verbosity == Verbosity::Verbose {
for line in result.lines() {
eprintln!(" {}", color::dim(line));
}
}
all_tool_calls.push(json!({
"command": command,
"output": result
}));
openai_messages.push(json!({
"role": "tool",
"tool_call_id": tc_id,
"content": result
}));
}
}
if json_mode {
println!(
"{}",
json!({
"success": true,
"text": all_text,
"tool_calls": all_tool_calls
})
);
} else if !had_text && !json_mode {
// Model returned only tool calls with no final text; print newline for clean output
println!();
}
true
}
/// Parses the SSE stream from the AI gateway, printing text deltas to stdout in
/// real-time. Returns (collected_text_chunks, tool_calls).
async fn parse_gateway_stream(
gw_response: reqwest::Response,
verbosity: Verbosity,
json_mode: bool,
) -> (Vec<String>, Vec<(String, String, String)>) {
use futures_util::StreamExt as _;
let mut text_chunks: Vec<String> = Vec::new();
let mut tool_call_args: std::collections::HashMap<usize, (String, String, String)> =
std::collections::HashMap::new();
let mut byte_stream = gw_response.bytes_stream();
let mut buffer = String::new();
while let Some(chunk_result) = byte_stream.next().await {
let chunk = match chunk_result {
Ok(c) => c,
Err(_) => break,
};
buffer.push_str(&String::from_utf8_lossy(&chunk));
while let Some(newline_pos) = buffer.find('\n') {
let line = buffer[..newline_pos].trim_end_matches('\r').to_string();
buffer = buffer[newline_pos + 1..].to_string();
if line.is_empty() {
continue;
}
let Some(data) = line.strip_prefix("data: ") else {
continue;
};
if data == "[DONE]" {
let tool_calls = collect_tool_calls(&mut tool_call_args);
if !json_mode && !text_chunks.is_empty() {
// End the streamed text line
let _ = std::io::stdout().flush();
}
return (text_chunks, tool_calls);
}
let Ok(sse_json) = serde_json::from_str::<Value>(data) else {
continue;
};
let delta = sse_json
.get("choices")
.and_then(|c| c.get(0))
.and_then(|c| c.get("delta"));
let Some(delta) = delta else { continue };
if let Some(text) = delta.get("content").and_then(|c| c.as_str()) {
if !text.is_empty() {
text_chunks.push(text.to_string());
if !json_mode && verbosity != Verbosity::Quiet {
print!("{}", text);
let _ = std::io::stdout().flush();
}
}
}
if let Some(tcs) = delta.get("tool_calls").and_then(|t| t.as_array()) {
for tc in tcs {
let idx = tc.get("index").and_then(|i| i.as_u64()).unwrap_or(0) as usize;
if let std::collections::hash_map::Entry::Vacant(e) = tool_call_args.entry(idx)
{
let id = tc
.get("id")
.and_then(|i| i.as_str())
.unwrap_or("")
.to_string();
let name = tc
.get("function")
.and_then(|f| f.get("name"))
.and_then(|n| n.as_str())
.unwrap_or("")
.to_string();
e.insert((id, name, String::new()));
}
if let Some(arg_delta) = tc
.get("function")
.and_then(|f| f.get("arguments"))
.and_then(|a| a.as_str())
{
let entry = tool_call_args.get_mut(&idx).unwrap();
entry.2.push_str(arg_delta);
}
}
}
}
}
if !json_mode && !text_chunks.is_empty() {
let _ = std::io::stdout().flush();
}
let tool_calls = collect_tool_calls(&mut tool_call_args);
(text_chunks, tool_calls)
}
fn collect_tool_calls(
map: &mut std::collections::HashMap<usize, (String, String, String)>,
) -> Vec<(String, String, String)> {
let mut indices: Vec<usize> = map.keys().copied().collect();
indices.sort();
indices
.into_iter()
.filter_map(|idx| map.remove(&idx))
.collect()
}
+173
View File
@@ -0,0 +1,173 @@
//! Color output utilities.
//!
//! Colors are off by default (agent-friendly). Enable with
//! `AGENT_BROWSER_COLOR=1`. Setting `NO_COLOR` to any value disables
//! colors per <https://no-color.org/>.
use std::env;
use std::sync::OnceLock;
fn env_is_truthy(name: &str) -> Option<bool> {
env::var(name)
.ok()
.map(|val| !matches!(val.to_lowercase().as_str(), "0" | "false" | "no"))
}
/// Returns true if color output is enabled.
///
/// Priority: `NO_COLOR` (presence disables, per spec) >
/// `AGENT_BROWSER_COLOR` (truthy enables) > default (off).
pub fn is_enabled() -> bool {
static COLORS_ENABLED: OnceLock<bool> = OnceLock::new();
*COLORS_ENABLED.get_or_init(|| {
if env::var_os("NO_COLOR").is_some() {
return false;
}
env_is_truthy("AGENT_BROWSER_COLOR").unwrap_or(false)
})
}
/// Format text in red (errors)
pub fn red(text: &str) -> String {
if is_enabled() {
format!("\x1b[31m{}\x1b[0m", text)
} else {
text.to_string()
}
}
/// Format text in green (success)
pub fn green(text: &str) -> String {
if is_enabled() {
format!("\x1b[32m{}\x1b[0m", text)
} else {
text.to_string()
}
}
/// Format text in yellow (warnings)
pub fn yellow(text: &str) -> String {
if is_enabled() {
format!("\x1b[33m{}\x1b[0m", text)
} else {
text.to_string()
}
}
/// Format text in cyan (info/progress)
pub fn cyan(text: &str) -> String {
if is_enabled() {
format!("\x1b[36m{}\x1b[0m", text)
} else {
text.to_string()
}
}
/// Format text in bold
pub fn bold(text: &str) -> String {
if is_enabled() {
format!("\x1b[1m{}\x1b[0m", text)
} else {
text.to_string()
}
}
/// Format text in dim
pub fn dim(text: &str) -> String {
if is_enabled() {
format!("\x1b[2m{}\x1b[0m", text)
} else {
text.to_string()
}
}
/// Red X error indicator
pub fn error_indicator() -> &'static str {
static INDICATOR: OnceLock<String> = OnceLock::new();
INDICATOR.get_or_init(|| {
if is_enabled() {
"\x1b[31m✗\x1b[0m".to_string()
} else {
"".to_string()
}
})
}
/// Green checkmark success indicator
pub fn success_indicator() -> &'static str {
static INDICATOR: OnceLock<String> = OnceLock::new();
INDICATOR.get_or_init(|| {
if is_enabled() {
"\x1b[32m✓\x1b[0m".to_string()
} else {
"".to_string()
}
})
}
/// Yellow warning indicator
pub fn warning_indicator() -> &'static str {
static INDICATOR: OnceLock<String> = OnceLock::new();
INDICATOR.get_or_init(|| {
if is_enabled() {
"\x1b[33m⚠\x1b[0m".to_string()
} else {
"".to_string()
}
})
}
/// Get console log color prefix by level
pub fn console_level_prefix(level: &str) -> String {
if !is_enabled() {
return format!("[{}]", level);
}
let color = match level {
"error" => "\x1b[31m",
"warning" => "\x1b[33m",
"info" => "\x1b[36m",
_ => "",
};
if color.is_empty() {
format!("[{}]", level)
} else {
format!("{}[{}]\x1b[0m", color, level)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_red_contains_ansi_codes() {
// Test the format structure (actual color depends on NO_COLOR env)
let formatted = format!("\x1b[31m{}\x1b[0m", "error");
assert!(formatted.contains("\x1b[31m"));
assert!(formatted.contains("\x1b[0m"));
}
#[test]
fn test_green_contains_ansi_codes() {
let formatted = format!("\x1b[32m{}\x1b[0m", "success");
assert!(formatted.contains("\x1b[32m"));
}
#[test]
fn test_console_level_prefix_contains_level() {
// Regardless of color state, the level text should be present
assert!(console_level_prefix("error").contains("error"));
assert!(console_level_prefix("warning").contains("warning"));
assert!(console_level_prefix("info").contains("info"));
assert!(console_level_prefix("log").contains("log"));
}
#[test]
fn test_indicators_contain_symbols() {
// Regardless of color state, symbols should be present
assert!(error_indicator().contains('✗'));
assert!(success_indicator().contains('✓'));
assert!(warning_indicator().contains('⚠'));
}
}
+4149 -206
View File
File diff suppressed because it is too large Load Diff
+953 -101
View File
File diff suppressed because it is too large Load Diff
+156
View File
@@ -0,0 +1,156 @@
//! Check the Chrome install: binary path, version, cache dirs, user-data
//! dir, and the optional lightpanda engine.
use std::env;
use std::path::{Path, PathBuf};
use super::helpers::which_exists;
use super::{Check, Status};
pub(super) fn check(checks: &mut Vec<Check>) {
let category = "Chrome";
let chrome = crate::native::cdp::chrome::find_chrome();
match chrome {
Some(path) => {
let label = path.display().to_string();
match query_chrome_version(&path) {
Some(version) => checks.push(Check::new(
"chrome.installed",
category,
Status::Pass,
format!("{} at {}", version, label),
)),
None => checks.push(Check::new(
"chrome.installed",
category,
Status::Pass,
format!("Chrome at {} (version unknown)", label),
)),
}
}
None => checks.push(
Check::new(
"chrome.installed",
category,
Status::Fail,
"No Chrome binary found",
)
.with_fix("agent-browser install"),
),
}
let cache_dir = crate::install::get_browsers_dir();
if cache_dir.exists() {
checks.push(Check::new(
"chrome.cache_dir",
category,
Status::Info,
format!("Cache dir {}", cache_dir.display()),
));
}
if let Some(puppeteer_dir) = puppeteer_cache_dir() {
if puppeteer_dir.exists() {
checks.push(Check::new(
"chrome.puppeteer_cache",
category,
Status::Info,
format!(
"Puppeteer cache also present: {} (will be used as a fallback)",
puppeteer_dir.display()
),
));
}
}
if let Some(user_data_dir) = crate::native::cdp::chrome::find_chrome_user_data_dir() {
let profiles = crate::native::cdp::chrome::list_chrome_profiles(&user_data_dir);
let count = profiles.len();
let dir_label = user_data_dir.display().to_string();
if count == 0 {
checks.push(Check::new(
"chrome.user_data_dir",
category,
Status::Info,
format!(
"Chrome user data dir found ({}), no profiles parsed",
dir_label
),
));
} else {
checks.push(Check::new(
"chrome.user_data_dir",
category,
Status::Info,
format!("{} Chrome profile(s) at {}", count, dir_label),
));
}
}
if let Ok(engine) = env::var("AGENT_BROWSER_ENGINE") {
if engine == "lightpanda" {
// Best-effort PATH lookup; absence is FAIL only when the user
// explicitly opted into the lightpanda engine.
if which_exists("lightpanda") {
checks.push(Check::new(
"chrome.engine_lightpanda",
category,
Status::Pass,
"Lightpanda binary on PATH",
));
} else {
checks.push(
Check::new(
"chrome.engine_lightpanda",
category,
Status::Fail,
"AGENT_BROWSER_ENGINE=lightpanda but no lightpanda binary on PATH",
)
.with_fix("install lightpanda or unset AGENT_BROWSER_ENGINE"),
);
}
}
}
}
fn query_chrome_version(path: &Path) -> Option<String> {
let output = std::process::Command::new(path)
.arg("--version")
.output()
.ok()?;
if !output.status.success() {
return None;
}
let s = String::from_utf8_lossy(&output.stdout).trim().to_string();
if s.is_empty() {
None
} else {
Some(s)
}
}
pub(super) fn puppeteer_cache_dir() -> Option<PathBuf> {
if let Ok(p) = env::var("PUPPETEER_CACHE_DIR") {
return Some(PathBuf::from(p));
}
dirs::home_dir().map(|h| h.join(".cache").join("puppeteer"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_puppeteer_cache_dir_returns_sensible_default() {
// When PUPPETEER_CACHE_DIR is unset, we fall back to
// ~/.cache/puppeteer. Mutating env vars here would race with other
// tests, so just verify the fallback path is shaped correctly.
if env::var("PUPPETEER_CACHE_DIR").is_err() {
let dir = puppeteer_cache_dir().expect("home dir should resolve in tests");
let s = dir.to_string_lossy();
assert!(s.contains(".cache"));
assert!(s.ends_with("puppeteer"));
}
}
}
+90
View File
@@ -0,0 +1,90 @@
//! Check user config files: `~/.agent-browser/config.json`,
//! `./agent-browser.json`, and any file referenced by
//! `AGENT_BROWSER_CONFIG`.
use std::env;
use std::path::PathBuf;
use super::helpers::parse_json_file;
use super::{Check, Status};
pub(super) fn check(checks: &mut Vec<Check>) {
let category = "Config";
let user_path = dirs::home_dir().map(|d| d.join(".agent-browser").join("config.json"));
if let Some(p) = user_path {
if p.exists() {
match parse_json_file(&p) {
Ok(_) => checks.push(Check::new(
"config.user",
category,
Status::Pass,
format!("{} (valid JSON)", p.display()),
)),
Err(e) => checks.push(
Check::new(
"config.user",
category,
Status::Fail,
format!("{}: {}", p.display(), e),
)
.with_fix(format!("edit {}", p.display())),
),
}
}
}
let project_path = PathBuf::from("agent-browser.json");
if project_path.exists() {
match parse_json_file(&project_path) {
Ok(_) => checks.push(Check::new(
"config.project",
category,
Status::Pass,
format!("{} (valid JSON)", project_path.display()),
)),
Err(e) => checks.push(
Check::new(
"config.project",
category,
Status::Fail,
format!("{}: {}", project_path.display(), e),
)
.with_fix(format!("edit {}", project_path.display())),
),
}
}
if let Ok(custom) = env::var("AGENT_BROWSER_CONFIG") {
let p = PathBuf::from(&custom);
if !p.exists() {
checks.push(
Check::new(
"config.custom",
category,
Status::Fail,
format!("AGENT_BROWSER_CONFIG points to missing file: {}", custom),
)
.with_fix("update or unset AGENT_BROWSER_CONFIG"),
);
} else {
match parse_json_file(&p) {
Ok(_) => checks.push(Check::new(
"config.custom",
category,
Status::Pass,
format!("AGENT_BROWSER_CONFIG: {} (valid JSON)", custom),
)),
Err(e) => checks.push(
Check::new(
"config.custom",
category,
Status::Fail,
format!("AGENT_BROWSER_CONFIG: {}: {}", custom, e),
)
.with_fix(format!("edit {}", custom)),
),
}
}
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Check running daemons: inventory of sessions, version match with the
//! CLI, and stale sidecar files cleaned up as a side effect of the walk.
use super::{Check, Status};
use crate::connection::{walk_daemons, CleanReason};
pub(super) fn check(checks: &mut Vec<Check>) {
let category = "Daemons";
let cli_version = env!("CARGO_PKG_VERSION");
let inventory = walk_daemons();
for cleaned in &inventory.cleaned {
let reason = match cleaned.reason {
CleanReason::ProcessGone | CleanReason::DashboardGone => "process gone",
CleanReason::UnreadablePidFile => "unreadable pid file",
CleanReason::OrphanedSocket => "orphaned socket",
};
checks.push(Check::new(
format!("daemon.cleaned.{}", cleaned.name),
category,
Status::Warn,
format!("Cleaned stale files: {} ({})", cleaned.name, reason),
));
}
if inventory.sessions.is_empty() {
checks.push(Check::new(
"daemon.active",
category,
Status::Pass,
"No active daemons",
));
} else {
for session in &inventory.sessions {
let version_match = session.version.as_deref() == Some(cli_version);
let status = if version_match {
Status::Pass
} else {
Status::Warn
};
let suffix = if version_match {
String::new()
} else {
format!(" (version mismatch with CLI {})", cli_version)
};
let mut check = Check::new(
format!("daemon.session.{}", session.name),
category,
status,
format!("Session {} (pid {}){}", session.name, session.pid, suffix),
);
if !version_match {
check = check.with_fix(format!("agent-browser --session {} close", session.name));
}
checks.push(check);
}
}
if let Some(dashboard) = inventory.dashboard {
if dashboard.alive {
checks.push(Check::new(
"daemon.dashboard",
category,
Status::Pass,
format!("Dashboard server running (pid {})", dashboard.pid),
));
}
}
}
+140
View File
@@ -0,0 +1,140 @@
//! Check the local environment: CLI version, platform, state/socket dirs,
//! and free disk space.
use std::path::Path;
use super::helpers::{disk_free_bytes, human_size, is_writable_dir};
use super::{Check, Status};
use crate::connection::get_socket_dir;
use crate::native::state::get_state_dir;
pub(super) fn check(checks: &mut Vec<Check>) {
let category = "Environment";
let version = env!("CARGO_PKG_VERSION");
let platform = format!("{} {}", std::env::consts::OS, std::env::consts::ARCH);
checks.push(Check::new(
"env.version",
category,
Status::Pass,
format!("CLI version {} ({})", version, platform),
));
match dirs::home_dir() {
Some(home) => checks.push(Check::new(
"env.home",
category,
Status::Pass,
format!("Home directory {}", home.display()),
)),
None => checks.push(Check::new(
"env.home",
category,
Status::Fail,
"Could not determine home directory",
)),
}
let state_dir = get_state_dir();
let socket_dir = get_socket_dir();
// Under the default setup, state and socket dirs are the same
// (~/.agent-browser). Collapse to a single line when they match;
// split when XDG_RUNTIME_DIR or AGENT_BROWSER_SOCKET_DIR diverts
// sockets elsewhere.
if state_dir == socket_dir {
push_dir_check(
checks,
"env.state_dir",
category,
"State and socket directory",
&state_dir,
);
} else {
push_dir_check(
checks,
"env.state_dir",
category,
"State directory",
&state_dir,
);
push_dir_check(
checks,
"env.socket_dir",
category,
"Socket directory",
&socket_dir,
);
}
match disk_free_bytes(&state_dir) {
Some(bytes) => {
let mb = bytes / (1024 * 1024);
let human = human_size(bytes);
if mb < 500 {
checks.push(
Check::new(
"env.disk_free",
category,
Status::Warn,
format!("Low disk space at state dir: {} free", human),
)
.with_fix("free up disk space; Chrome installs require ~500 MB"),
);
} else {
checks.push(Check::new(
"env.disk_free",
category,
Status::Pass,
format!("{} free at state dir", human),
));
}
}
None => checks.push(Check::new(
"env.disk_free",
category,
Status::Info,
"Disk free check unavailable on this platform",
)),
}
}
fn push_dir_check(
checks: &mut Vec<Check>,
id: &'static str,
category: &'static str,
label: &str,
dir: &Path,
) {
if dir.exists() {
if is_writable_dir(dir) {
checks.push(Check::new(
id,
category,
Status::Pass,
format!("{} {}", label, dir.display()),
));
} else {
checks.push(
Check::new(
id,
category,
Status::Fail,
format!("{} not writable: {}", label, dir.display()),
)
.with_fix(format!("chmod u+rwx {}", dir.display())),
);
}
} else {
checks.push(Check::new(
id,
category,
Status::Info,
format!(
"{} does not exist yet (will be created on first use): {}",
label,
dir.display()
),
));
}
}
+247
View File
@@ -0,0 +1,247 @@
//! Destructive repair actions behind `--fix`: reinstall Chrome, close
//! version-mismatched daemons, purge expired state files, and generate a
//! missing encryption key.
use std::env;
use std::fs;
use std::path::Path;
use std::time::{Duration, SystemTime};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use serde_json::json;
use super::helpers::new_id;
use super::{Check, Status};
use crate::connection::{cleanup_stale_files, send_command, walk_daemons};
use crate::native::state::{get_sessions_dir, get_state_dir};
pub(super) fn run(checks: &mut [Check], fixed: &mut Vec<String>) {
// `close_all_sessions` is expensive and closes every session at once, so
// only fire it on the first daemon.session.* Warn we encounter. Subsequent
// daemon.session.* Warn checks piggy-back on the same result.
let mut daemons_closed: Option<usize> = None;
for c in checks.iter_mut() {
match c.id.as_str() {
"chrome.installed" if c.status == Status::Fail => {
let installed = attempt_chrome_install();
if installed {
fixed.push("Reinstalled Chrome".to_string());
c.status = Status::Pass;
c.message = format!("{} (fixed by --fix)", c.message);
c.fix = None;
}
}
id if id.starts_with("daemon.session.") && c.status == Status::Warn => {
let killed = *daemons_closed.get_or_insert_with(|| {
let n = close_all_sessions();
if n > 0 {
fixed.push(format!("Closed {} version-mismatched daemon(s)", n));
}
n
});
if killed > 0 {
c.status = Status::Pass;
c.message = format!("{} (fixed by --fix)", c.message);
c.fix = None;
}
}
"security.state_count" if c.status == Status::Warn => {
let removed = purge_old_state();
if removed > 0 {
fixed.push(format!("Deleted {} expired state file(s)", removed));
c.status = Status::Pass;
c.message = format!("{} (fixed by --fix)", c.message);
c.fix = None;
}
}
"security.encryption_key" if c.status == Status::Info => {
let generated = create_encryption_key();
if generated {
fixed.push("Generated encryption key".to_string());
c.status = Status::Pass;
c.message = format!("{} (fixed by --fix)", c.message);
c.fix = None;
}
}
_ => {}
}
}
}
fn attempt_chrome_install() -> bool {
// run_install() uses process::exit on failure, so we shell out to ourselves
// to avoid taking down the doctor process if the install fails.
let exe = match std::env::current_exe() {
Ok(p) => p,
Err(_) => return false,
};
std::process::Command::new(exe)
.arg("install")
.status()
.map(|s| s.success())
.unwrap_or(false)
}
fn close_all_sessions() -> usize {
let mut killed = 0;
for session in &walk_daemons().sessions {
let cmd = json!({ "id": new_id(), "action": "close" });
if send_command(cmd, &session.name).is_ok() {
killed += 1;
}
cleanup_stale_files(&session.name);
}
killed
}
fn purge_old_state() -> usize {
let dir = get_sessions_dir();
let expire_days = env::var("AGENT_BROWSER_STATE_EXPIRE_DAYS")
.ok()
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(30);
let cutoff = SystemTime::now()
.checked_sub(Duration::from_secs(expire_days * 86_400))
.unwrap_or(SystemTime::UNIX_EPOCH);
let mut removed = 0;
if let Ok(entries) = fs::read_dir(&dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
if let Ok(meta) = entry.metadata() {
if let Ok(modified) = meta.modified() {
if modified < cutoff && fs::remove_file(entry.path()).is_ok() {
removed += 1;
}
}
}
}
}
}
removed
}
fn create_encryption_key() -> bool {
create_encryption_key_at(&get_state_dir())
}
fn create_encryption_key_at(dir: &Path) -> bool {
if fs::create_dir_all(dir).is_err() {
return false;
}
#[cfg(unix)]
{
let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o700));
}
let path = dir.join(".encryption-key");
if path.exists() {
return false;
}
let mut buf = [0u8; 32];
if getrandom::getrandom(&mut buf).is_err() {
return false;
}
let hex: String = buf.iter().map(|b| format!("{:02x}", b)).collect();
if fs::write(&path, format!("{}\n", hex)).is_err() {
return false;
}
#[cfg(unix)]
{
let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));
}
true
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_create_encryption_key_at_writes_64_char_hex_key() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().join("state");
assert!(create_encryption_key_at(&dir));
let key = dir.join(".encryption-key");
assert!(key.exists(), "key file should be created");
let contents = fs::read_to_string(&key).unwrap();
let trimmed = contents.trim();
assert_eq!(trimmed.len(), 64, "key should be 64 hex chars");
assert!(
trimmed.chars().all(|c| c.is_ascii_hexdigit()),
"key should be all hex digits"
);
}
#[test]
fn test_create_encryption_key_at_is_idempotent() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().join("state");
assert!(create_encryption_key_at(&dir));
let original = fs::read_to_string(dir.join(".encryption-key")).unwrap();
// Second call returns false and must not overwrite the existing key.
assert!(!create_encryption_key_at(&dir));
let after = fs::read_to_string(dir.join(".encryption-key")).unwrap();
assert_eq!(original, after);
}
#[cfg(unix)]
#[test]
fn test_create_encryption_key_at_sets_0600_perms() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().join("state");
assert!(create_encryption_key_at(&dir));
let key = dir.join(".encryption-key");
let mode = fs::metadata(&key).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "key file should be 0600, got {:o}", mode);
}
#[cfg(unix)]
#[test]
fn test_run_fixes_generates_missing_encryption_key() {
// Reaches the Info-status arm in run_fixes that was previously
// unreachable due to an early-continue guard. Overrides HOME so
// get_state_dir() resolves under a temp dir.
let guard = crate::test_utils::EnvGuard::new(&["HOME"]);
let tmp = TempDir::new().unwrap();
guard.set("HOME", tmp.path().to_str().unwrap());
let mut checks = vec![Check::new(
"security.encryption_key",
"Security",
Status::Info,
"No encryption key set",
)
.with_fix("export AGENT_BROWSER_ENCRYPTION_KEY=...")];
let mut fixed = Vec::new();
run(&mut checks, &mut fixed);
assert_eq!(
checks[0].status,
Status::Pass,
"Info check should transition to Pass after --fix"
);
assert!(
checks[0].fix.is_none(),
"fix hint should be cleared after repair"
);
assert!(
fixed.iter().any(|s| s.contains("encryption key")),
"fixed summary should mention the key generation"
);
assert!(
tmp.path().join(".agent-browser/.encryption-key").exists(),
"key file should exist at ~/.agent-browser/.encryption-key"
);
}
}
+185
View File
@@ -0,0 +1,185 @@
//! Stateless helpers shared across doctor submodules.
use std::fs;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::SystemTime;
use serde_json::Value;
pub(super) fn is_writable_dir(path: &Path) -> bool {
fs::metadata(path)
.map(|m| !m.permissions().readonly())
.unwrap_or(false)
}
pub(super) fn human_size(bytes: u64) -> String {
const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
let mut value = bytes as f64;
let mut unit = 0;
while value >= 1024.0 && unit < UNITS.len() - 1 {
value /= 1024.0;
unit += 1;
}
if unit == 0 {
format!("{} {}", bytes, UNITS[0])
} else {
format!("{:.1} {}", value, UNITS[unit])
}
}
#[cfg(unix)]
pub(super) fn disk_free_bytes(path: &Path) -> Option<u64> {
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
// Walk up to the first existing ancestor (for fresh installs where the
// state dir hasn't been created yet).
let mut probe: PathBuf = path.to_path_buf();
while !probe.exists() {
match probe.parent() {
Some(p) => probe = p.to_path_buf(),
None => return None,
}
}
let c_path = CString::new(probe.as_os_str().as_bytes()).ok()?;
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(c_path.as_ptr(), &mut stat) } != 0 {
return None;
}
Some(stat.f_bavail as u64 * stat.f_frsize)
}
#[cfg(windows)]
pub(super) fn disk_free_bytes(_path: &Path) -> Option<u64> {
None
}
#[cfg(not(any(unix, windows)))]
pub(super) fn disk_free_bytes(_path: &Path) -> Option<u64> {
None
}
pub(super) fn which_exists(name: &str) -> bool {
let probe = if cfg!(target_os = "windows") {
"where"
} else {
"which"
};
std::process::Command::new(probe)
.arg(name)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
pub(super) fn parse_json_file(path: &Path) -> Result<(), String> {
let content = fs::read_to_string(path).map_err(|e| format!("read failed: {}", e))?;
serde_json::from_str::<Value>(&content).map_err(|e| format!("invalid JSON: {}", e))?;
Ok(())
}
/// Generate a unique `doctor-<pid>-<micros>-<sequence>` id for JSON command envelopes.
pub(super) fn new_id() -> String {
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
let sequence = NEXT_ID.fetch_add(1, Ordering::Relaxed);
format!(
"doctor-{}-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|d| d.as_micros())
.unwrap_or(0),
sequence
)
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_human_size_units() {
assert_eq!(human_size(0), "0 B");
assert_eq!(human_size(512), "512 B");
assert_eq!(human_size(1024), "1.0 KB");
assert_eq!(human_size(1024 * 1024), "1.0 MB");
assert_eq!(human_size(1024 * 1024 * 1024), "1.0 GB");
assert_eq!(human_size(1_500_000), "1.4 MB");
}
#[test]
fn test_disk_free_walks_up_to_existing_ancestor() {
let dir = TempDir::new().unwrap();
let nested = dir.path().join("a/b/c/d");
let bytes = disk_free_bytes(&nested);
if cfg!(unix) {
assert!(bytes.is_some());
assert!(bytes.unwrap() > 0);
}
}
#[test]
fn test_is_writable_dir_matches_metadata() {
let dir = TempDir::new().unwrap();
assert!(is_writable_dir(dir.path()));
let missing = dir.path().join("does-not-exist");
assert!(!is_writable_dir(&missing));
}
#[test]
fn test_which_exists_matches_common_binaries() {
// `sh` exists on every unix; `cmd` exists on windows.
let probe = if cfg!(target_os = "windows") {
"cmd"
} else {
"sh"
};
assert!(which_exists(probe));
assert!(!which_exists(
"agent-browser-this-does-not-exist-please-dont-install-it"
));
}
#[test]
fn test_parse_json_file_valid_and_invalid() {
let dir = TempDir::new().unwrap();
let valid = dir.path().join("ok.json");
fs::write(&valid, r#"{"k": 1}"#).unwrap();
assert!(parse_json_file(&valid).is_ok());
let invalid = dir.path().join("bad.json");
fs::write(&invalid, "{not json}").unwrap();
let err = parse_json_file(&invalid).unwrap_err();
assert!(err.contains("invalid JSON"));
let missing = dir.path().join("nope.json");
let err = parse_json_file(&missing).unwrap_err();
assert!(err.contains("read failed"));
}
#[test]
fn test_parse_json_file_accepts_arrays() {
// The config parser rejects arrays at the Config type level, but
// doctor only checks syntactic JSON validity so it should accept
// both arrays and objects.
let dir = TempDir::new().unwrap();
let path = dir.path().join("arr.json");
fs::write(&path, r#"[1, 2, 3]"#).unwrap();
assert!(parse_json_file(&path).is_ok());
}
#[test]
fn test_new_id_is_unique_per_call() {
let a = new_id();
let b = new_id();
assert_ne!(a, b);
assert!(a.starts_with("doctor-"));
}
}
+188
View File
@@ -0,0 +1,188 @@
//! Live launch test: spawn a scratch daemon session, launch headless
//! Chrome, navigate to `about:blank`, then close. Skipped under `--quick`.
//!
//! A `LaunchGuard` Drop impl ensures the scratch session is closed and its
//! sidecar files cleaned even on panic or early return.
use std::env;
use std::time::{Duration, Instant, SystemTime};
use serde_json::{json, Value};
use super::helpers::new_id;
use super::{Check, Status};
use crate::connection::{cleanup_stale_files, ensure_daemon, send_command, DaemonOptions};
pub(super) fn check(checks: &mut Vec<Check>) {
let category = "Launch test";
if env::var("AGENT_BROWSER_PROVIDER").is_ok() {
checks.push(Check::new(
"launch.skipped.provider",
category,
Status::Info,
"Skipped (AGENT_BROWSER_PROVIDER is set; would consume cloud quota)",
));
return;
}
if env::var("AGENT_BROWSER_CDP").is_ok() {
checks.push(Check::new(
"launch.skipped.cdp",
category,
Status::Info,
"Skipped (AGENT_BROWSER_CDP is set; would attach to a real browser)",
));
return;
}
let session = format!(
"doctor-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0)
);
// Armed after `ensure_daemon` succeeds so we don't send a stray `close`
// or delete sidecar files for a daemon that never started. On every early
// return past the `Some(...)` assignment below, Drop runs one close and
// one `cleanup_stale_files`.
let mut _guard: Option<LaunchGuard> = None;
let opts = DaemonOptions {
headed: false,
debug: false,
executable_path: None,
extensions: &[],
init_scripts: &[],
enable: &[],
args: None,
user_agent: None,
proxy: None,
proxy_bypass: None,
proxy_username: None,
proxy_password: None,
ignore_https_errors: false,
allow_file_access: false,
hide_scrollbars: true,
profile: None,
state: None,
provider: None,
device: None,
session_name: None,
download_path: None,
allowed_domains: None,
action_policy: None,
confirm_actions: None,
engine: None,
auto_connect: false,
force_launch: false,
idle_timeout: None,
default_timeout: None,
cdp: None,
no_auto_dialog: false,
};
let started = Instant::now();
if let Err(e) = ensure_daemon(&session, &opts) {
checks.push(
Check::new(
"launch.daemon",
category,
Status::Fail,
format!("Could not start daemon: {}", e),
)
.with_fix("check Chrome install and re-run with --debug"),
);
return;
}
_guard = Some(LaunchGuard {
session: session.clone(),
});
let launch_cmd = json!({
"id": new_id(),
"action": "launch",
"headless": true,
});
if let Err(e) = send_json(launch_cmd, &session) {
checks.push(
Check::new(
"launch.launch",
category,
Status::Fail,
format!("Browser launch failed: {}", e),
)
.with_fix("agent-browser install # or check --debug output"),
);
return;
}
let open_cmd = json!({
"id": new_id(),
"action": "navigate",
"url": "about:blank",
});
if let Err(e) = send_json(open_cmd, &session) {
checks.push(
Check::new(
"launch.navigate",
category,
Status::Fail,
format!("Navigation to about:blank failed: {}", e),
)
.with_fix("re-run with --debug for full launch logs"),
);
return;
}
// Close + stale-file cleanup happen exactly once via LaunchGuard::drop at
// end of scope; no explicit close here.
let elapsed = started.elapsed();
let secs = elapsed.as_secs_f64();
if elapsed > Duration::from_secs(5) {
checks.push(Check::new(
"launch.elapsed",
category,
Status::Warn,
format!(
"Headless launch + about:blank in {:.2}s (slow; expected < 5s)",
secs
),
));
} else {
checks.push(Check::new(
"launch.elapsed",
category,
Status::Pass,
format!("Headless launch + about:blank in {:.2}s", secs),
));
}
}
fn send_json(cmd: Value, session: &str) -> Result<(), String> {
match send_command(cmd, session) {
Ok(resp) => {
if resp.success {
Ok(())
} else {
Err(resp.error.unwrap_or_else(|| "unknown error".to_string()))
}
}
Err(e) => Err(e),
}
}
/// Best-effort cleanup when the launch test panics or returns early.
struct LaunchGuard {
session: String,
}
impl Drop for LaunchGuard {
fn drop(&mut self) {
let close_cmd = json!({ "id": new_id(), "action": "close" });
let _ = send_command(close_cmd, &self.session);
cleanup_stale_files(&self.session);
}
}
+289
View File
@@ -0,0 +1,289 @@
//! Diagnose an agent-browser installation.
//!
//! Runs a battery of checks across environment, Chrome install, daemon
//! state, config files, encryption, providers, network reachability, and
//! a live headless browser launch test.
//!
//! Auto-cleans stale daemon socket/pid/version sidecar files. Destructive
//! repairs (reinstalling Chrome, purging old state files, generating a
//! missing encryption key) are gated behind `--fix`.
mod chrome;
mod config;
mod daemon;
mod environment;
mod fix;
mod helpers;
mod launch;
mod network;
mod providers;
mod security;
use serde_json::{json, Value};
use crate::color;
#[derive(Default, Clone, Copy)]
pub struct DoctorOptions {
pub offline: bool,
pub quick: bool,
pub fix: bool,
pub json: bool,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub(crate) enum Status {
Pass,
Warn,
Fail,
Info,
}
impl Status {
fn as_str(&self) -> &'static str {
match self {
Status::Pass => "pass",
Status::Warn => "warn",
Status::Fail => "fail",
Status::Info => "info",
}
}
fn label(&self) -> String {
match self {
Status::Pass => color::green("pass"),
Status::Warn => color::yellow("warn"),
Status::Fail => color::red("fail"),
Status::Info => color::dim("info"),
}
}
}
#[derive(Clone)]
pub(crate) struct Check {
pub id: String,
pub category: &'static str,
pub status: Status,
pub message: String,
pub fix: Option<String>,
}
impl Check {
fn new(
id: impl Into<String>,
category: &'static str,
status: Status,
message: impl Into<String>,
) -> Self {
Self {
id: id.into(),
category,
status,
message: message.into(),
fix: None,
}
}
fn with_fix(mut self, fix: impl Into<String>) -> Self {
self.fix = Some(fix.into());
self
}
}
/// Run the doctor command. Returns the process exit code.
pub fn run_doctor(opts: DoctorOptions) -> i32 {
let mut checks: Vec<Check> = Vec::new();
let mut fixed: Vec<String> = Vec::new();
environment::check(&mut checks);
chrome::check(&mut checks);
daemon::check(&mut checks);
config::check(&mut checks);
security::check(&mut checks);
providers::check(&mut checks);
if !opts.offline {
network::check(&mut checks);
}
if !opts.quick {
launch::check(&mut checks);
}
if opts.fix {
fix::run(&mut checks, &mut fixed);
}
let summary = summarize(&checks);
let exit_code = if summary.fail > 0 { 1 } else { 0 };
if opts.json {
print_json(&checks, &summary, &fixed, exit_code == 0);
} else {
print_text(&checks, &summary, &fixed, opts.fix);
}
exit_code
}
struct Summary {
pass: usize,
warn: usize,
fail: usize,
}
fn summarize(checks: &[Check]) -> Summary {
let mut s = Summary {
pass: 0,
warn: 0,
fail: 0,
};
for c in checks {
match c.status {
Status::Pass => s.pass += 1,
Status::Warn => s.warn += 1,
Status::Fail => s.fail += 1,
Status::Info => {}
}
}
s
}
fn print_text(checks: &[Check], summary: &Summary, fixed: &[String], fix_ran: bool) {
println!("{}", color::bold("agent-browser doctor"));
let mut current_category = "";
for c in checks {
if c.category != current_category {
current_category = c.category;
println!();
println!("{}", color::bold(current_category));
}
println!(" {} {}", c.status.label(), c.message);
if let Some(fix) = &c.fix {
println!(" {} {}", color::dim("fix:"), fix);
}
}
if !fixed.is_empty() {
println!();
println!("{}", color::bold("Fixed"));
for line in fixed {
println!(" {} {}", color::green("done"), line);
}
}
println!();
let line = format!(
"Summary: {} pass, {} warn, {} fail",
summary.pass, summary.warn, summary.fail
);
if summary.fail > 0 {
println!("{}", color::red(&line));
} else if summary.warn > 0 {
println!("{}", color::yellow(&line));
} else {
println!("{}", color::green(&line));
}
if !fix_ran && checks.iter().any(|c| c.fix.is_some()) {
println!();
println!(
"{} Run with {} to attempt repairs.",
color::dim("tip:"),
color::bold("--fix")
);
}
}
fn print_json(checks: &[Check], summary: &Summary, fixed: &[String], success: bool) {
let checks_json: Vec<Value> = checks
.iter()
.map(|c| {
let mut obj = json!({
"id": c.id,
"category": c.category,
"status": c.status.as_str(),
"message": c.message,
});
if let Some(fix) = &c.fix {
obj["fix"] = json!(fix);
}
obj
})
.collect();
let payload = json!({
"success": success,
"summary": {
"pass": summary.pass,
"warn": summary.warn,
"fail": summary.fail,
},
"checks": checks_json,
"fixed": fixed,
});
println!("{}", payload);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_summary_counts_each_status() {
let checks = vec![
Check::new("a", "Cat", Status::Pass, "ok"),
Check::new("b", "Cat", Status::Pass, "ok"),
Check::new("c", "Cat", Status::Warn, "meh"),
Check::new("d", "Cat", Status::Fail, "no"),
Check::new("e", "Cat", Status::Info, "fyi"),
];
let s = summarize(&checks);
assert_eq!(s.pass, 2);
assert_eq!(s.warn, 1);
assert_eq!(s.fail, 1);
}
#[test]
fn test_summary_zeroes_when_only_info() {
let checks = vec![Check::new("a", "Cat", Status::Info, "ignored")];
let s = summarize(&checks);
assert_eq!(s.pass, 0);
assert_eq!(s.warn, 0);
assert_eq!(s.fail, 0);
}
#[test]
fn test_status_label_does_not_panic() {
for s in &[Status::Pass, Status::Warn, Status::Fail, Status::Info] {
assert!(!s.label().is_empty());
assert!(!s.as_str().is_empty());
}
}
#[test]
fn test_status_as_str_values() {
assert_eq!(Status::Pass.as_str(), "pass");
assert_eq!(Status::Warn.as_str(), "warn");
assert_eq!(Status::Fail.as_str(), "fail");
assert_eq!(Status::Info.as_str(), "info");
}
#[test]
fn test_check_new_and_with_fix() {
let c = Check::new("id", "cat", Status::Warn, "msg").with_fix("do thing");
assert_eq!(c.id, "id");
assert_eq!(c.category, "cat");
assert_eq!(c.status, Status::Warn);
assert_eq!(c.message, "msg");
assert_eq!(c.fix.as_deref(), Some("do thing"));
}
#[test]
fn test_check_new_no_fix_by_default() {
let c = Check::new("id", "cat", Status::Pass, "msg");
assert!(c.fix.is_none());
}
}
+154
View File
@@ -0,0 +1,154 @@
//! Probe reachability of the Chrome for Testing CDN, AI Gateway (if
//! configured), and the currently-selected provider endpoint. Each probe
//! has a 3-second timeout.
use std::env;
use std::time::{Duration, Instant};
use super::{Check, Status};
pub(super) fn check(checks: &mut Vec<Check>) {
let category = "Network";
let rt = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(r) => r,
Err(e) => {
checks.push(Check::new(
"net.runtime",
category,
Status::Fail,
format!("Could not start tokio runtime for probes: {}", e),
));
return;
}
};
let client = match reqwest::Client::builder()
.user_agent(format!("agent-browser/{}", env!("CARGO_PKG_VERSION")))
.timeout(Duration::from_secs(3))
.connect_timeout(Duration::from_secs(3))
.build()
{
Ok(c) => c,
Err(e) => {
checks.push(Check::new(
"net.client",
category,
Status::Fail,
format!("Could not build HTTP client: {}", e),
));
return;
}
};
let chrome_url =
"https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json";
probe_url(
&rt,
&client,
checks,
category,
"net.chrome_cdn",
chrome_url,
"Chrome for Testing CDN",
);
if env::var("AI_GATEWAY_API_KEY").is_ok() {
let url = env::var("AI_GATEWAY_URL")
.unwrap_or_else(|_| "https://ai-gateway.vercel.sh".to_string());
probe_url(
&rt,
&client,
checks,
category,
"net.ai_gateway",
&url,
"AI Gateway",
);
}
if let Ok(provider) = env::var("AGENT_BROWSER_PROVIDER") {
let url: Option<String> = match provider.to_lowercase().as_str() {
"browserbase" => Some("https://api.browserbase.com".to_string()),
"browserless" => Some(
env::var("BROWSERLESS_API_URL")
.unwrap_or_else(|_| "https://production-sfo.browserless.io".to_string()),
),
"browseruse" | "browser-use" => Some("https://api.browser-use.com".to_string()),
"kernel" => Some(
env::var("KERNEL_ENDPOINT")
.unwrap_or_else(|_| "https://api.onkernel.com".to_string()),
),
_ => None,
};
if let Some(url) = url {
probe_url(
&rt,
&client,
checks,
category,
"net.provider",
&url,
&format!("Provider {}", provider),
);
}
}
}
fn probe_url(
rt: &tokio::runtime::Runtime,
client: &reqwest::Client,
checks: &mut Vec<Check>,
category: &'static str,
id: &'static str,
url: &str,
label: &str,
) {
let started = Instant::now();
let result = rt.block_on(async { client.head(url).send().await });
let elapsed_ms = started.elapsed().as_millis();
match result {
Ok(resp) => {
let status = resp.status();
if status.is_success() || status.is_redirection() || status.as_u16() == 405 {
checks.push(Check::new(
id,
category,
Status::Pass,
format!(
"{} reachable ({}ms, HTTP {})",
label,
elapsed_ms,
status.as_u16()
),
));
} else {
checks.push(Check::new(
id,
category,
Status::Warn,
format!(
"{} returned HTTP {} after {}ms",
label,
status.as_u16(),
elapsed_ms
),
));
}
}
Err(e) => {
checks.push(
Check::new(
id,
category,
Status::Fail,
format!("{} unreachable after {}ms: {}", label, elapsed_ms, e),
)
.with_fix("check network connectivity / firewall / proxy settings"),
);
}
}
}
+128
View File
@@ -0,0 +1,128 @@
//! Check remote browser providers: API key presence for Browserless,
//! Browserbase, Browser Use, Kernel, AgentCore (AWS), Appium for iOS, and
//! the AI Gateway chat key. Info-level unless the provider is selected
//! via `AGENT_BROWSER_PROVIDER`.
use std::env;
use super::helpers::which_exists;
use super::{Check, Status};
pub(super) fn check(checks: &mut Vec<Check>) {
let category = "Providers";
let active = env::var("AGENT_BROWSER_PROVIDER").ok();
let normalized = active
.as_ref()
.map(|s| s.to_lowercase())
.unwrap_or_default();
let active_status = |provider: &str, ok: bool| -> Status {
if normalized == provider {
if ok {
Status::Pass
} else {
Status::Fail
}
} else {
Status::Info
}
};
let providers: &[(&str, &[&str], &str)] = &[
("browserless", &["BROWSERLESS_API_KEY"], "Browserless"),
("browserbase", &["BROWSERBASE_API_KEY"], "Browserbase"),
("browseruse", &["BROWSER_USE_API_KEY"], "Browser Use"),
("kernel", &["KERNEL_API_KEY"], "Kernel"),
];
for (id, env_keys, label) in providers {
let present = env_keys.iter().any(|k| env::var(k).is_ok());
let provider_id = *id;
let status = active_status(provider_id, present);
let msg = if present {
format!("{}: API key present", label)
} else {
format!("{}: {} not set", label, env_keys.join(" / "))
};
let mut check = Check::new(format!("providers.{}", provider_id), category, status, msg);
if status == Status::Fail {
check = check.with_fix(format!(
"set {} (or unset AGENT_BROWSER_PROVIDER={})",
env_keys.first().copied().unwrap_or(""),
provider_id
));
}
checks.push(check);
}
let aws_present = env::var("AWS_ACCESS_KEY_ID").is_ok()
|| env::var("AWS_PROFILE").is_ok()
|| env::var("AWS_SESSION_TOKEN").is_ok();
let agentcore_status = active_status("agentcore", aws_present);
let mut agentcore_check = Check::new(
"providers.agentcore",
category,
agentcore_status,
if aws_present {
"AgentCore: AWS credentials resolvable".to_string()
} else {
"AgentCore: no AWS credentials in env (AWS_ACCESS_KEY_ID / AWS_PROFILE)".to_string()
},
);
if agentcore_status == Status::Fail {
agentcore_check = agentcore_check
.with_fix("export AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY or AWS_PROFILE");
}
checks.push(agentcore_check);
if normalized == "ios" {
if which_exists("appium") {
checks.push(Check::new(
"providers.ios",
category,
Status::Pass,
"iOS: appium binary on PATH",
));
} else {
checks.push(
Check::new(
"providers.ios",
category,
Status::Fail,
"iOS: appium binary not found on PATH",
)
.with_fix("npm install -g appium && appium driver install xcuitest"),
);
}
}
let chat_key_present = env::var("AI_GATEWAY_API_KEY").is_ok();
if chat_key_present {
checks.push(Check::new(
"providers.chat",
category,
Status::Info,
"AI_GATEWAY_API_KEY present (chat enabled)",
));
} else {
checks.push(
Check::new(
"providers.chat",
category,
Status::Info,
"AI_GATEWAY_API_KEY not set (chat command disabled)",
)
.with_fix("export AI_GATEWAY_API_KEY=gw_..."),
);
}
if let Some(active) = active {
checks.push(Check::new(
"providers.active",
category,
Status::Info,
format!("AGENT_BROWSER_PROVIDER = {}", active),
));
}
}
+167
View File
@@ -0,0 +1,167 @@
//! Check security posture: encryption key presence / permissions, saved
//! state file age, and the optional action policy file.
use std::env;
use std::fs;
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use super::helpers::parse_json_file;
use super::{Check, Status};
use crate::native::state::{get_sessions_dir, get_state_dir};
pub(super) fn check(checks: &mut Vec<Check>) {
let category = "Security";
let key_env = env::var("AGENT_BROWSER_ENCRYPTION_KEY").ok();
let key_file = get_state_dir().join(".encryption-key");
if let Some(hex) = &key_env {
if hex.len() == 64 && hex.chars().all(|c| c.is_ascii_hexdigit()) {
checks.push(Check::new(
"security.encryption_key",
category,
Status::Pass,
"AGENT_BROWSER_ENCRYPTION_KEY set (64-char hex)",
));
} else {
checks.push(
Check::new(
"security.encryption_key",
category,
Status::Fail,
"AGENT_BROWSER_ENCRYPTION_KEY is not a 64-char hex string",
)
.with_fix("export AGENT_BROWSER_ENCRYPTION_KEY=$(openssl rand -hex 32)"),
);
}
} else if key_file.exists() {
let mut msg = format!("Encryption key file present: {}", key_file.display());
let mut status = Status::Pass;
let mut fix: Option<String> = None;
#[cfg(unix)]
if let Ok(meta) = fs::metadata(&key_file) {
let mode = meta.permissions().mode() & 0o777;
if mode & 0o077 != 0 {
status = Status::Warn;
msg = format!(
"Encryption key file is too permissive ({:o}): {}",
mode,
key_file.display()
);
fix = Some(format!("chmod 600 {}", key_file.display()));
}
}
let mut check = Check::new("security.encryption_key", category, status, msg);
if let Some(f) = fix {
check = check.with_fix(f);
}
checks.push(check);
} else {
checks.push(
Check::new(
"security.encryption_key",
category,
Status::Info,
"No encryption key set (will be auto-generated on first auth save)",
)
.with_fix("export AGENT_BROWSER_ENCRYPTION_KEY=$(openssl rand -hex 32)"),
);
}
let sessions_dir = get_sessions_dir();
if sessions_dir.exists() {
let expire_days = env::var("AGENT_BROWSER_STATE_EXPIRE_DAYS")
.ok()
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(30);
let cutoff = SystemTime::now()
.checked_sub(Duration::from_secs(expire_days * 86_400))
.unwrap_or(SystemTime::UNIX_EPOCH);
let mut total = 0usize;
let mut old = 0usize;
if let Ok(entries) = fs::read_dir(&sessions_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
total += 1;
if let Ok(meta) = entry.metadata() {
if let Ok(modified) = meta.modified() {
if modified < cutoff {
old += 1;
}
}
}
}
}
}
if total == 0 {
checks.push(Check::new(
"security.state_count",
category,
Status::Info,
"No saved state files",
));
} else if old > 0 {
checks.push(
Check::new(
"security.state_count",
category,
Status::Warn,
format!(
"{} state file(s) older than {} days ({} total)",
old, expire_days, total
),
)
.with_fix(format!(
"agent-browser state clean --older-than {}",
expire_days
)),
);
} else {
checks.push(Check::new(
"security.state_count",
category,
Status::Pass,
format!("{} saved state file(s)", total),
));
}
}
if let Ok(policy_path) = env::var("AGENT_BROWSER_ACTION_POLICY") {
let p = PathBuf::from(&policy_path);
if !p.exists() {
checks.push(
Check::new(
"security.action_policy",
category,
Status::Fail,
format!(
"AGENT_BROWSER_ACTION_POLICY points to missing file: {}",
policy_path
),
)
.with_fix("update or unset AGENT_BROWSER_ACTION_POLICY"),
);
} else {
match parse_json_file(&p) {
Ok(_) => checks.push(Check::new(
"security.action_policy",
category,
Status::Pass,
format!("Action policy: {}", policy_path),
)),
Err(e) => checks.push(
Check::new(
"security.action_policy",
category,
Status::Fail,
format!("Action policy: {}: {}", policy_path, e),
)
.with_fix(format!("edit {}", policy_path)),
),
}
}
}
}
+1426 -26
View File
File diff suppressed because it is too large Load Diff
+915 -144
View File
File diff suppressed because it is too large Load Diff
+1414 -133
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+556
View File
@@ -0,0 +1,556 @@
use aes_gcm::{aead::Aead, aead::KeyInit, Aes256Gcm};
use base64::{engine::general_purpose::STANDARD, Engine};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthProfile {
pub name: String,
pub url: String,
pub username: String,
pub password: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub username_selector: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub password_selector: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub submit_selector: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_login_at: Option<String>,
}
// Keep legacy Credential alias for backward compatibility
pub type Credential = AuthProfile;
fn validate_profile_name(name: &str) -> Result<(), String> {
if name.is_empty()
|| !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
return Err(format!(
"Invalid profile name '{}'. Must match /^[a-zA-Z0-9_-]+$/",
name
));
}
Ok(())
}
fn get_auth_dir() -> PathBuf {
if let Some(home) = dirs::home_dir() {
home.join(".agent-browser").join("auth")
} else {
std::env::temp_dir().join("agent-browser").join("auth")
}
}
fn get_profile_path(name: &str) -> PathBuf {
get_auth_dir().join(format!("{}.json", name))
}
const ENCRYPTION_KEY_ENV: &str = "AGENT_BROWSER_ENCRYPTION_KEY";
const KEY_FILE_NAME: &str = ".encryption-key";
fn get_agent_browser_dir() -> PathBuf {
if let Some(home) = dirs::home_dir() {
home.join(".agent-browser")
} else {
std::env::temp_dir().join("agent-browser")
}
}
fn get_key_file_path() -> PathBuf {
get_agent_browser_dir().join(KEY_FILE_NAME)
}
fn parse_key_hex(hex_str: &str) -> Option<Vec<u8>> {
let hex_str = hex_str.trim();
if hex_str.len() != 64 || !hex_str.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
let bytes: Vec<u8> = (0..32)
.map(|i| u8::from_str_radix(&hex_str[i * 2..i * 2 + 2], 16).unwrap())
.collect();
Some(bytes)
}
/// Read the encryption key from AGENT_BROWSER_ENCRYPTION_KEY env var or
/// ~/.agent-browser/.encryption-key file (matching the Node.js implementation).
fn get_encryption_key() -> Result<Vec<u8>, String> {
if let Ok(key_hex) = std::env::var(ENCRYPTION_KEY_ENV) {
return parse_key_hex(&key_hex).ok_or_else(|| {
format!(
"{} should be a 64-character hex string (256 bits). Generate one with: openssl rand -hex 32",
ENCRYPTION_KEY_ENV
)
});
}
let key_file = get_key_file_path();
if key_file.exists() {
let hex = fs::read_to_string(&key_file)
.map_err(|e| format!("Failed to read encryption key file: {}", e))?;
return parse_key_hex(&hex).ok_or_else(|| {
format!(
"Invalid encryption key in {}. Expected 64-character hex string.",
key_file.display()
)
});
}
Err(format!(
"Encryption key required. Set {} or ensure {} exists.",
ENCRYPTION_KEY_ENV,
key_file.display()
))
}
/// Ensure an encryption key exists, auto-generating one if needed.
fn ensure_encryption_key() -> Result<Vec<u8>, String> {
if let Ok(key) = get_encryption_key() {
return Ok(key);
}
let mut key = [0u8; 32];
getrandom::getrandom(&mut key).map_err(|e| format!("Failed to generate key: {}", e))?;
let key_hex = key.iter().map(|b| format!("{:02x}", b)).collect::<String>();
let dir = get_agent_browser_dir();
fs::create_dir_all(&dir).map_err(|e| format!("Failed to create directory: {}", e))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700));
}
let key_file = get_key_file_path();
fs::write(&key_file, format!("{}\n", key_hex))
.map_err(|e| format!("Failed to write encryption key: {}", e))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(&key_file, fs::Permissions::from_mode(0o600));
}
let _ = writeln!(
std::io::stderr(),
"[agent-browser] Auto-generated encryption key at {} -- back up this file or set {}",
key_file.display(),
ENCRYPTION_KEY_ENV
);
Ok(key.to_vec())
}
/// Encrypt a profile to the JSON+base64 format compatible with Node.js.
fn encrypt_profile(profile: &AuthProfile) -> Result<String, String> {
let key = ensure_encryption_key()?;
let cipher =
Aes256Gcm::new_from_slice(&key).map_err(|e| format!("Encryption key error: {}", e))?;
let plaintext = serde_json::to_string(profile)
.map_err(|e| format!("Failed to serialize profile: {}", e))?;
let mut iv = [0u8; 12];
getrandom::getrandom(&mut iv).map_err(|e| format!("Failed to generate IV: {}", e))?;
// aes_gcm appends the 16-byte auth tag to the ciphertext
let encrypted = cipher
.encrypt(aes_gcm::Nonce::from_slice(&iv), plaintext.as_bytes())
.map_err(|e| format!("Encryption failed: {}", e))?;
let tag_offset = encrypted.len() - 16;
let ciphertext = &encrypted[..tag_offset];
let auth_tag = &encrypted[tag_offset..];
let payload = json!({
"version": 1,
"encrypted": true,
"iv": STANDARD.encode(iv),
"authTag": STANDARD.encode(auth_tag),
"data": STANDARD.encode(ciphertext),
});
serde_json::to_string_pretty(&payload)
.map_err(|e| format!("Failed to serialize payload: {}", e))
}
/// JSON envelope written by Node.js encryption (src/encryption.ts).
#[derive(Deserialize)]
struct EncryptedPayload {
#[allow(dead_code)]
version: u32,
#[allow(dead_code)]
encrypted: bool,
iv: String,
#[serde(rename = "authTag")]
auth_tag: String,
data: String,
}
fn decrypt_profile(data: &[u8]) -> Result<AuthProfile, String> {
let text = std::str::from_utf8(data).map_err(|_| {
"Profile is not valid UTF-8 -- it may use an older incompatible binary format".to_string()
})?;
if let Ok(payload) = serde_json::from_str::<EncryptedPayload>(text) {
let key = get_encryption_key()?;
let iv = STANDARD
.decode(&payload.iv)
.map_err(|e| format!("Invalid base64 iv: {}", e))?;
let auth_tag = STANDARD
.decode(&payload.auth_tag)
.map_err(|e| format!("Invalid base64 authTag: {}", e))?;
let ciphertext = STANDARD
.decode(&payload.data)
.map_err(|e| format!("Invalid base64 data: {}", e))?;
// aes_gcm expects ciphertext || auth_tag as input to decrypt
let mut combined = Vec::with_capacity(ciphertext.len() + auth_tag.len());
combined.extend_from_slice(&ciphertext);
combined.extend_from_slice(&auth_tag);
let cipher =
Aes256Gcm::new_from_slice(&key).map_err(|e| format!("Decryption key error: {}", e))?;
let plaintext = cipher
.decrypt(aes_gcm::Nonce::from_slice(&iv), combined.as_slice())
.map_err(|e| format!("Decryption failed: {}", e))?;
let json_str = String::from_utf8(plaintext)
.map_err(|e| format!("Decrypted data is not valid UTF-8: {}", e))?;
return serde_json::from_str(&json_str).map_err(|e| format!("Invalid profile data: {}", e));
}
// Fallback: try as plain unencrypted JSON profile
serde_json::from_str::<AuthProfile>(text)
.map_err(|_| "Profile is not a valid encrypted or unencrypted payload".to_string())
}
fn save_profile(profile: &AuthProfile) -> Result<(), String> {
let dir = get_auth_dir();
fs::create_dir_all(&dir).map_err(|e| format!("Failed to create auth dir: {}", e))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700));
}
let encrypted_json = encrypt_profile(profile)?;
let path = get_profile_path(&profile.name);
fs::write(&path, &encrypted_json).map_err(|e| format!("Failed to write profile: {}", e))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));
}
Ok(())
}
fn load_profile(name: &str) -> Result<AuthProfile, String> {
let path = get_profile_path(name);
if !path.exists() {
return Err(format!("Auth profile '{}' not found", name));
}
let data = fs::read(&path).map_err(|e| format!("Failed to read profile: {}", e))?;
decrypt_profile(&data)
}
pub fn credentials_set(
name: &str,
username: &str,
password: &str,
url: Option<&str>,
) -> Result<Value, String> {
validate_profile_name(name)?;
let profile = AuthProfile {
name: name.to_string(),
url: url.unwrap_or("").to_string(),
username: username.to_string(),
password: password.to_string(),
username_selector: None,
password_selector: None,
submit_selector: None,
created_at: None,
last_login_at: None,
};
save_profile(&profile)?;
Ok(json!({ "saved": name }))
}
pub fn auth_save(
name: &str,
url: &str,
username: &str,
password: &str,
username_selector: Option<&str>,
password_selector: Option<&str>,
submit_selector: Option<&str>,
) -> Result<Value, String> {
validate_profile_name(name)?;
let profile = AuthProfile {
name: name.to_string(),
url: url.to_string(),
username: username.to_string(),
password: password.to_string(),
username_selector: username_selector.map(String::from),
password_selector: password_selector.map(String::from),
submit_selector: submit_selector.map(String::from),
created_at: None,
last_login_at: None,
};
save_profile(&profile)?;
Ok(json!({ "saved": name }))
}
pub fn credentials_get(name: &str) -> Result<Value, String> {
let profile = load_profile(name)?;
Ok(json!({
"name": profile.name,
"username": profile.username,
"url": profile.url,
"hasPassword": true,
}))
}
pub fn credentials_get_full(name: &str) -> Result<AuthProfile, String> {
load_profile(name)
}
pub fn credentials_delete(name: &str) -> Result<Value, String> {
validate_profile_name(name)?;
let path = get_profile_path(name);
if !path.exists() {
return Err(format!("Auth profile '{}' not found", name));
}
fs::remove_file(&path).map_err(|e| format!("Failed to delete profile: {}", e))?;
Ok(json!({ "deleted": name }))
}
pub fn credentials_list() -> Result<Value, String> {
let dir = get_auth_dir();
if !dir.exists() {
return Ok(json!({ "profiles": [] }));
}
let mut profiles = Vec::new();
if let Ok(entries) = fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
let name = path
.file_stem()
.unwrap_or_default()
.to_string_lossy()
.to_string();
match load_profile(&name) {
Ok(profile) => {
profiles.push(json!({
"name": profile.name,
"username": profile.username,
"url": profile.url,
}));
}
Err(_) => {
profiles.push(json!({
"name": name,
"error": "Failed to decrypt",
}));
}
}
}
}
Ok(json!({ "profiles": profiles }))
}
pub fn auth_show(name: &str) -> Result<Value, String> {
validate_profile_name(name)?;
let profile = load_profile(name)?;
Ok(json!({
"profile": {
"name": profile.name,
"url": profile.url,
"username": profile.username,
"usernameSelector": profile.username_selector,
"passwordSelector": profile.password_selector,
"submitSelector": profile.submit_selector,
}
}))
}
#[cfg(test)]
pub(crate) static AUTH_TEST_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[cfg(test)]
mod tests {
use super::*;
fn with_test_key<F: FnOnce()>(f: F) {
let _lock = AUTH_TEST_MUTEX.lock().unwrap();
let original = std::env::var(ENCRYPTION_KEY_ENV).ok();
let test_key = "a".repeat(64);
// SAFETY: TEST_MUTEX serializes all test access so no concurrent mutation.
unsafe { std::env::set_var(ENCRYPTION_KEY_ENV, &test_key) };
f();
// SAFETY: TEST_MUTEX serializes all test access so no concurrent mutation.
match original {
Some(val) => unsafe { std::env::set_var(ENCRYPTION_KEY_ENV, val) },
None => unsafe { std::env::remove_var(ENCRYPTION_KEY_ENV) },
}
}
#[test]
fn test_validate_profile_name() {
assert!(validate_profile_name("github").is_ok());
assert!(validate_profile_name("my-app").is_ok());
assert!(validate_profile_name("test_123").is_ok());
assert!(validate_profile_name("").is_err());
assert!(validate_profile_name("has space").is_err());
assert!(validate_profile_name("../evil").is_err());
assert!(validate_profile_name("foo/bar").is_err());
}
#[test]
fn test_auth_profile_serialization() {
let profile = AuthProfile {
name: "test".to_string(),
url: "https://example.com".to_string(),
username: "user".to_string(),
password: "pass".to_string(),
username_selector: None,
password_selector: None,
submit_selector: Some("button[type=submit]".to_string()),
created_at: None,
last_login_at: None,
};
let json = serde_json::to_string(&profile).unwrap();
let parsed: AuthProfile = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.name, "test");
assert_eq!(
parsed.submit_selector,
Some("button[type=submit]".to_string())
);
assert!(parsed.username_selector.is_none());
}
#[test]
fn test_encrypt_decrypt_roundtrip() {
with_test_key(|| {
let profile = AuthProfile {
name: "roundtrip".to_string(),
url: "https://example.com".to_string(),
username: "user".to_string(),
password: "s3cret!".to_string(),
username_selector: None,
password_selector: None,
submit_selector: None,
created_at: None,
last_login_at: None,
};
let encrypted_json = encrypt_profile(&profile).unwrap();
let decrypted = decrypt_profile(encrypted_json.as_bytes()).unwrap();
assert_eq!(decrypted.name, "roundtrip");
assert_eq!(decrypted.password, "s3cret!");
});
}
#[test]
fn test_get_encryption_key_from_env() {
with_test_key(|| {
let key = get_encryption_key().unwrap();
assert_eq!(key.len(), 32);
assert!(key.iter().all(|&b| b == 0xaa));
});
}
#[test]
fn test_parse_key_hex_valid() {
let hex = "ab".repeat(32);
let key = parse_key_hex(&hex).unwrap();
assert_eq!(key.len(), 32);
assert!(key.iter().all(|&b| b == 0xab));
}
#[test]
fn test_parse_key_hex_invalid() {
assert!(parse_key_hex("too_short").is_none());
assert!(parse_key_hex(&"g".repeat(64)).is_none());
assert!(parse_key_hex("").is_none());
}
#[test]
fn test_decrypt_json_payload_format() {
with_test_key(|| {
let key = get_encryption_key().unwrap();
let profile = AuthProfile {
name: "json-test".to_string(),
url: "https://example.com/login".to_string(),
username: "admin".to_string(),
password: "hunter2".to_string(),
username_selector: Some("#email".to_string()),
password_selector: None,
submit_selector: None,
created_at: None,
last_login_at: None,
};
// Encrypt with aes_gcm, then manually build the JSON payload
// to simulate what Node.js would produce
let cipher = Aes256Gcm::new_from_slice(&key).unwrap();
let mut iv = [0u8; 12];
getrandom::getrandom(&mut iv).unwrap();
let plaintext = serde_json::to_string(&profile).unwrap();
let encrypted = cipher
.encrypt(aes_gcm::Nonce::from_slice(&iv), plaintext.as_bytes())
.unwrap();
let tag_offset = encrypted.len() - 16;
let ciphertext = &encrypted[..tag_offset];
let auth_tag = &encrypted[tag_offset..];
let payload = format!(
r#"{{"version":1,"encrypted":true,"iv":"{}","authTag":"{}","data":"{}"}}"#,
STANDARD.encode(iv),
STANDARD.encode(auth_tag),
STANDARD.encode(ciphertext),
);
let decrypted = decrypt_profile(payload.as_bytes()).unwrap();
assert_eq!(decrypted.name, "json-test");
assert_eq!(decrypted.password, "hunter2");
assert_eq!(decrypted.username_selector, Some("#email".to_string()));
});
}
#[test]
fn test_encrypted_output_is_json_format() {
with_test_key(|| {
let profile = AuthProfile {
name: "format-check".to_string(),
url: "https://example.com".to_string(),
username: "user".to_string(),
password: "pass".to_string(),
username_selector: None,
password_selector: None,
submit_selector: None,
created_at: None,
last_login_at: None,
};
let encrypted = encrypt_profile(&profile).unwrap();
let parsed: Value = serde_json::from_str(&encrypted).unwrap();
assert_eq!(parsed["version"], 1);
assert_eq!(parsed["encrypted"], true);
assert!(parsed["iv"].is_string());
assert!(parsed["authTag"].is_string());
assert!(parsed["data"].is_string());
});
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+361
View File
@@ -0,0 +1,361 @@
use std::collections::HashMap;
use std::io::Write;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use futures_util::{SinkExt, StreamExt};
use serde_json::Value;
use tokio::sync::{broadcast, oneshot, Mutex};
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
use tokio_tungstenite::tungstenite::Message;
use super::types::{CdpCommand, CdpEvent, CdpMessage};
type PendingMap = Arc<Mutex<HashMap<u64, oneshot::Sender<CdpMessage>>>>;
/// Interval between WebSocket ping frames sent to keep the connection alive
/// through intermediate proxies (reverse proxies, load balancers, service meshes).
const WS_KEEPALIVE_INTERVAL_SECS: u64 = 30;
/// Raw incoming CDP message (text) broadcast to all subscribers.
/// Used by the inspect proxy to forward responses and events to DevTools.
#[derive(Debug, Clone)]
pub struct RawCdpMessage {
pub text: String,
pub session_id: Option<String>,
}
pub struct CdpClient {
ws_tx: Arc<
Mutex<
futures_util::stream::SplitSink<
tokio_tungstenite::WebSocketStream<
tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
>,
Message,
>,
>,
>,
next_id: AtomicU64,
pending: PendingMap,
event_tx: broadcast::Sender<CdpEvent>,
raw_tx: broadcast::Sender<RawCdpMessage>,
_reader_handle: tokio::task::JoinHandle<()>,
_keepalive_handle: tokio::task::JoinHandle<()>,
}
impl CdpClient {
pub async fn connect(url: &str) -> Result<Self, String> {
Self::connect_with_headers(url, None).await
}
pub async fn connect_with_headers(
url: &str,
headers: Option<Vec<(String, String)>>,
) -> Result<Self, String> {
let mut request = url
.into_client_request()
.map_err(|e| format!("Invalid WebSocket URL: {}", e))?;
if let Some(hdrs) = headers {
let req_headers = request.headers_mut();
for (key, value) in hdrs {
if let (Ok(name), Ok(val)) = (
key.parse::<tokio_tungstenite::tungstenite::http::header::HeaderName>(),
value.parse::<tokio_tungstenite::tungstenite::http::header::HeaderValue>(),
) {
req_headers.insert(name, val);
}
}
}
let ws_config = WebSocketConfig {
max_message_size: None,
max_frame_size: None,
..Default::default()
};
let (ws_stream, _) =
tokio_tungstenite::connect_async_with_config(request, Some(ws_config), false)
.await
.map_err(|e| format!("CDP WebSocket connect failed: {}", e))?;
enable_tcp_keepalive(ws_stream.get_ref());
let (ws_tx, mut ws_rx) = ws_stream.split();
let ws_tx = Arc::new(Mutex::new(ws_tx));
let pending: PendingMap = Arc::new(Mutex::new(HashMap::new()));
let (event_tx, _) = broadcast::channel(4096);
let (raw_tx, _) = broadcast::channel(4096);
let pending_clone = pending.clone();
let event_tx_clone = event_tx.clone();
let raw_tx_clone = raw_tx.clone();
// Notify used to stop the keepalive task when the reader loop exits.
let (cancel_tx, mut cancel_rx) = tokio::sync::watch::channel(false);
let reader_handle = tokio::spawn(async move {
while let Some(msg) = ws_rx.next().await {
// Accept both Text and Binary frames — remote CDP proxies
// (e.g. Browserless) may send responses as Binary frames.
let msg = match msg {
Ok(Message::Text(text)) => text,
Ok(Message::Binary(data)) => match String::from_utf8(data) {
Ok(text) => text,
Err(_) => continue,
},
Ok(Message::Close(frame)) => {
if std::env::var("AGENT_BROWSER_DEBUG").is_ok() {
let reason = frame
.as_ref()
.map(|f| format!("code={}, reason={}", f.code, f.reason))
.unwrap_or_else(|| "no frame".to_string());
let _ =
writeln!(std::io::stderr(), "[cdp] WebSocket Close: {}", reason);
}
break;
}
Ok(Message::Pong(_)) => continue,
Ok(_) => continue,
Err(e) => {
if std::env::var("AGENT_BROWSER_DEBUG").is_ok() {
let _ = writeln!(std::io::stderr(), "[cdp] WebSocket Error: {}", e);
}
break;
}
};
// Broadcast raw message for inspect proxy subscribers before typed parse,
// so messages with negative IDs (used by the inspect proxy) are still delivered.
if raw_tx_clone.receiver_count() > 0 {
let session_id = serde_json::from_str::<serde_json::Value>(&msg)
.ok()
.and_then(|v| v.get("sessionId")?.as_str().map(String::from));
let _ = raw_tx_clone.send(RawCdpMessage {
text: msg.clone(),
session_id,
});
}
let parsed: CdpMessage = match serde_json::from_str(&msg) {
Ok(m) => m,
// Expected for inspect proxy messages with negative IDs
// (CdpMessage.id is u64); handled via raw broadcast above.
Err(_) => continue,
};
if let Some(id) = parsed.id {
// Response to a command
let mut pending = pending_clone.lock().await;
if let Some(tx) = pending.remove(&id) {
let _ = tx.send(parsed);
}
} else if let Some(ref method) = parsed.method {
// Event
let event = CdpEvent {
method: method.clone(),
params: parsed.params.clone().unwrap_or(Value::Null),
session_id: parsed.session_id.clone(),
};
let _ = event_tx_clone.send(event);
}
}
// Reader loop exited (connection closed or error). Drop all pending
// command senders so callers get an immediate channel-closed error
// instead of waiting for the 30-second timeout.
pending_clone.lock().await.clear();
// Stop the keepalive task — the connection is gone.
let _ = cancel_tx.send(true);
});
// Spawn a keepalive task that sends WebSocket Ping frames at a regular
// interval. This prevents intermediate proxies (Envoy, nginx, OpenResty,
// cloud load balancers) from closing idle WebSocket connections. If the
// send fails, the connection is dead and we stop pinging.
let keepalive_tx = ws_tx.clone();
let keepalive_handle = tokio::spawn(async move {
let interval = std::time::Duration::from_secs(WS_KEEPALIVE_INTERVAL_SECS);
loop {
tokio::select! {
_ = tokio::time::sleep(interval) => {}
_ = cancel_rx.changed() => break,
}
let mut tx = keepalive_tx.lock().await;
if tx.send(Message::Ping(Vec::new())).await.is_err() {
break;
}
}
});
Ok(Self {
ws_tx,
next_id: AtomicU64::new(1),
pending,
event_tx,
raw_tx,
_reader_handle: reader_handle,
_keepalive_handle: keepalive_handle,
})
}
pub async fn send_command(
&self,
method: &str,
params: Option<Value>,
session_id: Option<&str>,
) -> Result<Value, String> {
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
let cmd = CdpCommand {
id,
method: method.to_string(),
params,
session_id: session_id.filter(|s| !s.is_empty()).map(|s| s.to_string()),
};
let json = serde_json::to_string(&cmd)
.map_err(|e| format!("Failed to serialize CDP command: {}", e))?;
let (tx, rx) = oneshot::channel();
{
let mut pending = self.pending.lock().await;
pending.insert(id, tx);
}
{
let mut ws_tx = self.ws_tx.lock().await;
ws_tx
.send(Message::Text(json))
.await
.map_err(|e| format!("Failed to send CDP command: {}", e))?;
}
let response = match tokio::time::timeout(std::time::Duration::from_secs(30), rx).await {
Ok(Ok(resp)) => resp,
Ok(Err(_)) => return Err("CDP response channel closed".to_string()),
Err(_) => {
self.pending.lock().await.remove(&id);
return Err(format!("CDP command timed out: {}", method));
}
};
if let Some(error) = response.error {
return Err(format!("CDP error ({}): {}", method, error));
}
Ok(response.result.unwrap_or(Value::Null))
}
pub fn subscribe(&self) -> broadcast::Receiver<CdpEvent> {
self.event_tx.subscribe()
}
/// Subscribe to all raw incoming CDP messages (responses + events).
/// Used by the inspect proxy to forward traffic to the DevTools frontend.
pub fn subscribe_raw(&self) -> broadcast::Receiver<RawCdpMessage> {
self.raw_tx.subscribe()
}
/// Create a lightweight handle for the inspect WebSocket proxy.
/// Contains only what's needed to forward messages bidirectionally.
pub fn inspect_handle(&self) -> InspectProxyHandle {
InspectProxyHandle {
ws_tx: self.ws_tx.clone(),
raw_tx: self.raw_tx.clone(),
}
}
pub async fn send_command_typed<P: serde::Serialize, R: serde::de::DeserializeOwned>(
&self,
method: &str,
params: &P,
session_id: Option<&str>,
) -> Result<R, String> {
let params_value = serde_json::to_value(params)
.map_err(|e| format!("Failed to serialize params: {}", e))?;
let result = self
.send_command(method, Some(params_value), session_id)
.await?;
serde_json::from_value(result)
.map_err(|e| format!("Failed to deserialize CDP response for {}: {}", method, e))
}
pub async fn send_command_no_params(
&self,
method: &str,
session_id: Option<&str>,
) -> Result<Value, String> {
self.send_command(method, None, session_id).await
}
/// Send raw JSON through the WebSocket without tracking a response.
/// Used by the inspect proxy to forward DevTools frontend messages.
pub async fn send_raw(&self, json: String) -> Result<(), String> {
let mut ws_tx = self.ws_tx.lock().await;
ws_tx
.send(Message::Text(json))
.await
.map_err(|e| format!("Failed to send raw CDP message: {}", e))
}
}
type WsTx = Arc<
Mutex<
futures_util::stream::SplitSink<
tokio_tungstenite::WebSocketStream<
tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
>,
Message,
>,
>,
>;
/// Lightweight handle for the inspect WebSocket proxy, holding only
/// the cloneable parts of CdpClient needed for bidirectional message forwarding.
pub struct InspectProxyHandle {
ws_tx: WsTx,
raw_tx: broadcast::Sender<RawCdpMessage>,
}
impl InspectProxyHandle {
pub async fn send_raw(&self, json: String) -> Result<(), String> {
let mut ws_tx = self.ws_tx.lock().await;
ws_tx
.send(Message::Text(json))
.await
.map_err(|e| format!("Failed to send raw CDP message: {}", e))
}
pub fn subscribe_raw(&self) -> broadcast::Receiver<RawCdpMessage> {
self.raw_tx.subscribe()
}
}
/// Enable TCP SO_KEEPALIVE on the underlying socket of a WebSocket connection.
/// This is best-effort: failures are silently ignored since the WebSocket-level
/// Ping keepalive provides the primary connection liveness mechanism.
fn enable_tcp_keepalive(stream: &tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>) {
let tcp_stream = match stream {
tokio_tungstenite::MaybeTlsStream::Plain(s) => s,
tokio_tungstenite::MaybeTlsStream::Rustls(s) => s.get_ref().0,
_ => return,
};
// SockRef borrows the fd without taking ownership.
let sock = socket2::SockRef::from(tcp_stream);
let keepalive = socket2::TcpKeepalive::new().with_time(std::time::Duration::from_secs(30));
// with_interval sets TCP_KEEPINTVL — the time between probes after the
// first keepalive probe goes unanswered. Available on most platforms
// (Linux, macOS, Windows, FreeBSD, etc.) but not OpenBSD or Haiku.
#[cfg(not(any(target_os = "openbsd", target_os = "haiku")))]
let keepalive = keepalive.with_interval(std::time::Duration::from_secs(10));
let _ = sock.set_tcp_keepalive(&keepalive);
}
+387
View File
@@ -0,0 +1,387 @@
use std::time::Duration;
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::tungstenite::Message;
use super::types::BrowserVersionInfo;
/// Default timeout for CDP discovery HTTP requests.
const DEFAULT_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(2);
/// Discover the CDP WebSocket URL for the given host and port.
///
/// Tries three methods in order: `/json/version`, `/json/list`, and a direct
/// WebSocket connection to `/devtools/browser`. The returned URL has its
/// host/port rewritten to match the requested target.
///
/// An optional `query` string (without the leading `?`) is appended to the
/// final WebSocket URL so that user-supplied URL parameters (e.g.
/// `?mode=Hello`) are forwarded to the remote endpoint.
pub async fn discover_cdp_url(
host: &str,
port: u16,
query: Option<&str>,
) -> Result<String, String> {
discover_cdp_url_with_timeout(host, port, query, DEFAULT_DISCOVERY_TIMEOUT).await
}
/// Like [`discover_cdp_url`] but with a custom request timeout.
pub async fn discover_cdp_url_with_timeout(
host: &str,
port: u16,
query: Option<&str>,
timeout: Duration,
) -> Result<String, String> {
// Primary: /json/version (standard path)
let version_err = match fetch_cdp_info(host, port, timeout).await {
Ok(info) => {
if let Some(ws_url) = info.web_socket_debugger_url {
return Ok(append_query(&rewrite_ws_host(&ws_url, host, port), query));
}
format!(
"No webSocketDebuggerUrl in /json/version at {}:{}",
host, port
)
}
Err(e) => e,
};
// Fallback: /json/list (returns target list; look for the browser target)
let list_err = match fetch_cdp_list(host, port, timeout).await {
Ok(ws_url) => return Ok(append_query(&rewrite_ws_host(&ws_url, host, port), query)),
Err(e) => e,
};
// Final fallback: direct WebSocket at /devtools/browser.
// Chrome 136+ with UI-based remote debugging (chrome://inspect) exposes
// CDP over WebSocket but does not serve HTTP discovery endpoints.
match discover_cdp_ws(host, port, timeout).await {
Ok(ws_url) => Ok(append_query(&ws_url, query)),
Err(ws_err) => Err(format!(
"All CDP discovery methods failed for {}:{}: /json/version: {}; /json/list: {}; WebSocket: {}",
host, port, version_err, list_err, ws_err
)),
}
}
/// Bracket an IPv6 address for use in URLs. No-op for IPv4 or already-bracketed addresses.
fn bracket_ipv6(host: &str) -> String {
if host.contains(':') && !host.starts_with('[') {
format!("[{}]", host)
} else {
host.to_string()
}
}
/// Fetch `/json/version` from the given host:port and parse the response.
async fn fetch_cdp_info(
host: &str,
port: u16,
timeout: Duration,
) -> Result<BrowserVersionInfo, String> {
let url = format!("http://{}:{}/json/version", bracket_ipv6(host), port);
let body = tokio::time::timeout(timeout, reqwest_get_string(&url))
.await
.map_err(|_| format!("Timeout connecting to CDP at {}:{}", host, port))?
.map_err(|e| format!("Failed to connect to CDP at {}:{}: {}", host, port, e))?;
serde_json::from_str(&body).map_err(|e| format!("Invalid /json/version response: {}", e))
}
/// Rewrite the host and port in a WebSocket URL to match the target we
/// actually connected to. Chrome's `/json/version` always returns
/// `ws://127.0.0.1:<local-port>/...` which is unreachable when the
/// browser is on a remote machine or behind a port-forward.
fn rewrite_ws_host(ws_url: &str, host: &str, port: u16) -> String {
if let Ok(mut parsed) = url::Url::parse(ws_url) {
let _ = parsed.set_host(Some(&bracket_ipv6(host)));
let _ = parsed.set_port(Some(port));
parsed.to_string()
} else {
ws_url.to_string()
}
}
/// Append a query string to a URL, preserving any existing query parameters.
fn append_query(url: &str, query: Option<&str>) -> String {
match query {
Some(q) if !q.is_empty() => {
if let Ok(mut parsed) = url::Url::parse(url) {
{
let mut pairs = parsed.query_pairs_mut();
pairs.extend_pairs(url::form_urlencoded::parse(q.as_bytes()));
}
parsed.to_string()
} else {
// Fallback: raw string append
if url.contains('?') {
format!("{}&{}", url, q)
} else {
format!("{}?{}", url, q)
}
}
}
_ => url.to_string(),
}
}
/// Fetch `/json/list` and extract the `webSocketDebuggerUrl` from the first
/// target with `type == "browser"`, or the first target if none has that type.
async fn fetch_cdp_list(host: &str, port: u16, timeout: Duration) -> Result<String, String> {
let url = format!("http://{}:{}/json/list", bracket_ipv6(host), port);
let body = tokio::time::timeout(timeout, reqwest_get_string(&url))
.await
.map_err(|_| format!("Timeout connecting to /json/list at {}:{}", host, port))?
.map_err(|e| {
format!(
"Failed to connect to /json/list at {}:{}: {}",
host, port, e
)
})?;
let targets: Vec<serde_json::Value> =
serde_json::from_str(&body).map_err(|e| format!("Invalid /json/list response: {}", e))?;
// Prefer targets with type "browser", fall back to first target with a ws URL
let browser_target = targets
.iter()
.find(|t| t.get("type").and_then(|v| v.as_str()) == Some("browser"));
let target = browser_target.or_else(|| targets.first());
target
.and_then(|t| t.get("webSocketDebuggerUrl"))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.ok_or_else(|| "No webSocketDebuggerUrl found in /json/list targets".to_string())
}
/// Discover a CDP endpoint by connecting directly to `ws://host:port/devtools/browser`
/// and verifying it responds to `Browser.getVersion`.
/// Returns the WebSocket URL on success.
async fn discover_cdp_ws(host: &str, port: u16, timeout: Duration) -> Result<String, String> {
let ws_url = format!("ws://{}:{}/devtools/browser", bracket_ipv6(host), port);
tokio::time::timeout(timeout, async {
let (mut ws_stream, _) = tokio_tungstenite::connect_async(&ws_url)
.await
.map_err(|e| format!("WebSocket connect failed at {}: {}", ws_url, e))?;
let cmd = r#"{"id":1,"method":"Browser.getVersion"}"#;
ws_stream
.send(Message::Text(cmd.into()))
.await
.map_err(|e| format!("Failed to send command: {}", e))?;
#[derive(serde::Deserialize)]
struct CdpReply {
id: u64,
}
let mut result: Result<(), String> = Err("No valid CDP response received".to_string());
while let Some(msg) = ws_stream.next().await {
match msg {
Ok(Message::Text(text)) => {
if serde_json::from_str::<CdpReply>(&text).is_ok_and(|r| r.id == 1) {
result = Ok(());
break;
}
}
Ok(Message::Close(_)) | Err(_) => break,
_ => continue,
}
}
let _ = ws_stream.close(None).await;
result
})
.await
.map_err(|_| format!("Timeout connecting to WebSocket at {}", ws_url))?
.map(|()| ws_url)
}
async fn reqwest_get_string(url: &str) -> Result<String, String> {
let resp = reqwest::get(url).await.map_err(|e| e.to_string())?;
resp.text().await.map_err(|e| e.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
const HTTP_404: &str =
"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
fn http_200(body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\nContent-Type: application/json\r\n\r\n{}",
body.len(), body
)
}
async fn accept_http(listener: &TcpListener, response: &str) {
let (mut s, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf).await;
s.write_all(response.as_bytes()).await.unwrap();
}
#[tokio::test]
async fn discovers_ws_url_from_json_version() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let server = tokio::spawn(async move {
accept_http(
&listener,
&http_200(r#"{"webSocketDebuggerUrl":"ws://127.0.0.1:1234/"}"#),
)
.await;
});
let ws_url = discover_cdp_url("127.0.0.1", port, None).await.unwrap();
assert_eq!(ws_url, format!("ws://127.0.0.1:{}/", port));
server.await.unwrap();
}
#[tokio::test]
async fn returns_error_when_version_returns_invalid_json() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let server = tokio::spawn(async move {
accept_http(&listener, &http_200("not-json")).await;
// /json/list and ws fallback both fail (server closes)
});
let err = discover_cdp_url("127.0.0.1", port, None).await.unwrap_err();
assert!(err.contains("Invalid /json/version response"));
server.await.unwrap();
}
#[tokio::test]
async fn falls_back_to_json_list_on_version_404() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let server = tokio::spawn(async move {
accept_http(&listener, HTTP_404).await;
accept_http(
&listener,
&http_200(r#"[{"type":"browser","webSocketDebuggerUrl":"ws://127.0.0.1:1234/devtools/browser/abc"}]"#),
).await;
});
let ws_url = discover_cdp_url("127.0.0.1", port, None).await.unwrap();
assert!(ws_url.contains("/devtools/browser/abc"));
assert!(ws_url.contains(&port.to_string()));
server.await.unwrap();
}
#[tokio::test]
async fn falls_back_to_ws_when_http_returns_404() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let server = tokio::spawn(async move {
// /json/version -> 404, /json/list -> 404
accept_http(&listener, HTTP_404).await;
accept_http(&listener, HTTP_404).await;
// WebSocket handshake + respond to Browser.getVersion
let (stream, _) = listener.accept().await.unwrap();
let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
if let Some(Ok(Message::Text(text))) = ws.next().await {
let req: serde_json::Value = serde_json::from_str(&text).unwrap();
let id = req.get("id").unwrap();
let reply = format!(
r#"{{"id":{},"result":{{"protocolVersion":"1.3","product":"Chrome/136"}}}}"#,
id
);
ws.send(Message::Text(reply)).await.unwrap();
}
let _ = ws.close(None).await;
});
let ws_url = discover_cdp_url("127.0.0.1", port, None).await.unwrap();
assert_eq!(ws_url, format!("ws://127.0.0.1:{}/devtools/browser", port));
server.await.unwrap();
}
#[test]
fn rewrite_ws_host_replaces_host_and_port() {
let original = "ws://127.0.0.1:9222/devtools/browser/abc";
let rewritten = rewrite_ws_host(original, "10.211.55.12", 9223);
assert_eq!(rewritten, "ws://10.211.55.12:9223/devtools/browser/abc");
}
#[test]
fn rewrite_ws_host_handles_ipv6() {
let original = "ws://127.0.0.1:9222/devtools/browser/abc";
let rewritten = rewrite_ws_host(original, "::1", 9222);
assert_eq!(rewritten, "ws://[::1]:9222/devtools/browser/abc");
}
#[test]
fn append_query_adds_params_to_url_without_query() {
let url = "ws://127.0.0.1:9222/devtools/browser/abc";
let result = append_query(url, Some("mode=Hello"));
assert_eq!(
result,
"ws://127.0.0.1:9222/devtools/browser/abc?mode=Hello"
);
}
#[test]
fn append_query_merges_with_existing_query() {
let url = "ws://127.0.0.1:9222/devtools/browser/abc?token=xyz";
let result = append_query(url, Some("mode=Hello"));
assert_eq!(
result,
"ws://127.0.0.1:9222/devtools/browser/abc?token=xyz&mode=Hello"
);
}
#[test]
fn append_query_noop_for_none() {
let url = "ws://127.0.0.1:9222/devtools/browser/abc";
let result = append_query(url, None);
assert_eq!(result, url);
}
#[test]
fn append_query_noop_for_empty() {
let url = "ws://127.0.0.1:9222/devtools/browser/abc";
let result = append_query(url, Some(""));
assert_eq!(result, url);
}
#[test]
fn append_query_handles_multiple_params() {
let url = "ws://127.0.0.1:9222/devtools/browser/abc";
let result = append_query(url, Some("mode=Hello&token=abc"));
assert_eq!(
result,
"ws://127.0.0.1:9222/devtools/browser/abc?mode=Hello&token=abc"
);
}
#[tokio::test]
async fn discover_preserves_query_params() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let server = tokio::spawn(async move {
accept_http(
&listener,
&http_200(r#"{"webSocketDebuggerUrl":"ws://127.0.0.1:1234/"}"#),
)
.await;
});
let ws_url = discover_cdp_url("127.0.0.1", port, Some("mode=Hello"))
.await
.unwrap();
assert_eq!(ws_url, format!("ws://127.0.0.1:{}/?mode=Hello", port));
server.await.unwrap();
}
}
+495
View File
@@ -0,0 +1,495 @@
use std::collections::VecDeque;
use std::io::{BufRead, BufReader};
use std::net::TcpListener;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use super::discovery::discover_cdp_url_with_timeout;
const LIGHTPANDA_STARTUP_TIMEOUT: Duration = Duration::from_secs(10);
const LIGHTPANDA_POLL_INTERVAL: Duration = Duration::from_millis(100);
const LIGHTPANDA_DISCOVERY_TIMEOUT: Duration = Duration::from_millis(500);
const LIGHTPANDA_SESSION_TIMEOUT_SECS: u64 = 604800; // 1 week, the documented maximum
const MAX_LOG_LINES: usize = 40;
pub struct LightpandaProcess {
child: Child,
pub ws_url: String,
_log_drainers: Vec<std::thread::JoinHandle<()>>,
}
impl LightpandaProcess {
pub fn kill(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
impl Drop for LightpandaProcess {
fn drop(&mut self) {
self.kill();
}
}
#[derive(Default)]
pub struct LightpandaLaunchOptions {
pub executable_path: Option<String>,
pub proxy: Option<String>,
pub port: Option<u16>,
}
fn build_lightpanda_serve_args(port: u16, proxy: Option<&str>) -> Vec<String> {
let mut args = vec![
"serve".to_string(),
"--host".to_string(),
"127.0.0.1".to_string(),
"--port".to_string(),
port.to_string(),
"--timeout".to_string(),
LIGHTPANDA_SESSION_TIMEOUT_SECS.to_string(),
];
if let Some(proxy) = proxy {
args.push("--http_proxy".to_string());
args.push(proxy.to_string());
}
args
}
#[derive(Clone, Default)]
struct LaunchLogBuffer {
stdout: Arc<Mutex<VecDeque<String>>>,
stderr: Arc<Mutex<VecDeque<String>>>,
}
impl LaunchLogBuffer {
fn push_stdout(&self, line: String) {
push_bounded(&self.stdout, line);
}
fn push_stderr(&self, line: String) {
push_bounded(&self.stderr, line);
}
fn snapshot_stdout(&self) -> Vec<String> {
self.stdout
.lock()
.expect("stdout log buffer poisoned")
.iter()
.cloned()
.collect()
}
fn snapshot_stderr(&self) -> Vec<String> {
self.stderr
.lock()
.expect("stderr log buffer poisoned")
.iter()
.cloned()
.collect()
}
}
fn push_bounded(buffer: &Mutex<VecDeque<String>>, line: String) {
let mut guard = buffer.lock().expect("log buffer poisoned");
if guard.len() >= MAX_LOG_LINES {
guard.pop_front();
}
guard.push_back(line);
}
pub fn find_lightpanda() -> Option<PathBuf> {
#[cfg(unix)]
{
if let Ok(output) = Command::new("which").arg("lightpanda").output() {
if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !path.is_empty() {
return Some(PathBuf::from(path));
}
}
}
}
#[cfg(windows)]
{
if let Ok(output) = Command::new("where").arg("lightpanda").output() {
if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout)
.lines()
.next()
.unwrap_or("")
.trim()
.to_string();
if !path.is_empty() {
return Some(PathBuf::from(path));
}
}
}
}
if let Some(home) = dirs::home_dir() {
let candidates = [
home.join(".lightpanda/lightpanda"),
home.join(".local/bin/lightpanda"),
];
for c in &candidates {
if c.exists() {
return Some(c.clone());
}
}
}
None
}
pub async fn launch_lightpanda(
options: &LightpandaLaunchOptions,
) -> Result<LightpandaProcess, String> {
let binary_path = match &options.executable_path {
Some(p) => PathBuf::from(p),
None => find_lightpanda().ok_or(
"Lightpanda not found. Install it from https://lightpanda.io/docs/open-source/installation or use --executable-path.",
)?,
};
let port = match options.port {
Some(p) => p,
None => TcpListener::bind("127.0.0.1:0")
.and_then(|l| l.local_addr())
.map(|a| a.port())
.map_err(|e| format!("Failed to find an available port for Lightpanda: {}", e))?,
};
let args = build_lightpanda_serve_args(port, options.proxy.as_deref());
let mut child = Command::new(&binary_path)
.args(&args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("Failed to launch Lightpanda at {:?}: {}", binary_path, e))?;
let (log_buffer, log_drainers) = start_log_drainers(&mut child)?;
let ws_url =
match wait_for_lightpanda_ready(&mut child, port, &log_buffer, LIGHTPANDA_STARTUP_TIMEOUT)
.await
{
Ok(url) => url,
Err(e) => {
let _ = child.kill();
let _ = child.wait();
return Err(e);
}
};
Ok(LightpandaProcess {
child,
ws_url,
_log_drainers: log_drainers,
})
}
fn start_log_drainers(
child: &mut Child,
) -> Result<(LaunchLogBuffer, Vec<std::thread::JoinHandle<()>>), String> {
let stdout = child.stdout.take().ok_or_else(|| {
let _ = child.kill();
"Failed to capture Lightpanda stdout".to_string()
})?;
let stderr = child.stderr.take().ok_or_else(|| {
let _ = child.kill();
"Failed to capture Lightpanda stderr".to_string()
})?;
let logs = LaunchLogBuffer::default();
let stdout_logs = logs.clone();
let stderr_logs = logs.clone();
let stdout_handle =
std::thread::spawn(move || drain_reader(stdout, move |line| stdout_logs.push_stdout(line)));
let stderr_handle =
std::thread::spawn(move || drain_reader(stderr, move |line| stderr_logs.push_stderr(line)));
Ok((logs, vec![stdout_handle, stderr_handle]))
}
fn drain_reader<R, F>(reader: R, mut push: F)
where
R: std::io::Read,
F: FnMut(String),
{
for line in BufReader::new(reader).lines() {
match line {
Ok(line) => push(line),
Err(_) => break,
}
}
}
async fn wait_for_lightpanda_ready(
child: &mut Child,
port: u16,
logs: &LaunchLogBuffer,
startup_timeout: Duration,
) -> Result<String, String> {
let deadline = std::time::Instant::now() + startup_timeout;
let mut last_probe_error = None;
loop {
if let Ok(Some(status)) = child.try_wait() {
// Give the drainer threads a brief window to flush the last log lines
// before we snapshot them. This is best-effort: lines written just
// before exit may still be missing, but the most useful output (early
// startup errors) will already be in the buffer.
tokio::time::sleep(Duration::from_millis(25)).await;
return Err(lightpanda_launch_error(
&format!(
"Lightpanda exited before CDP became ready (status: {})",
status
),
logs,
last_probe_error.as_deref(),
));
}
match discover_cdp_url_with_timeout("127.0.0.1", port, None, LIGHTPANDA_DISCOVERY_TIMEOUT)
.await
{
Ok(ws_url) => return Ok(ws_url),
Err(err) => last_probe_error = Some(err),
}
if std::time::Instant::now() >= deadline {
return Err(lightpanda_launch_error(
&format!(
"Timed out after {}ms waiting for Lightpanda CDP endpoint on port {}",
startup_timeout.as_millis(),
port
),
logs,
last_probe_error.as_deref(),
));
}
tokio::time::sleep(LIGHTPANDA_POLL_INTERVAL).await;
}
}
fn lightpanda_launch_error(
message: &str,
logs: &LaunchLogBuffer,
last_probe_error: Option<&str>,
) -> String {
let stdout_lines = logs.snapshot_stdout();
let stderr_lines = logs.snapshot_stderr();
let mut details = Vec::new();
if let Some(err) = last_probe_error {
details.push(format!("Last probe error: {}", err));
}
if !stderr_lines.is_empty() {
details.push(format!(
"Lightpanda stderr (last {} lines):\n {}",
stderr_lines.len(),
stderr_lines.join("\n ")
));
}
if !stdout_lines.is_empty() {
details.push(format!(
"Lightpanda stdout (last {} lines):\n {}",
stdout_lines.len(),
stdout_lines.join("\n ")
));
}
if details.is_empty() {
format!("{} (no stdout/stderr output from Lightpanda)", message)
} else {
format!("{}\n{}", message, details.join("\n"))
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener as TokioTcpListener;
fn unused_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port()
}
async fn serve_json_version_once_after_delay(port: u16, delay_ms: u64, body: &'static str) {
tokio::time::sleep(Duration::from_millis(delay_ms)).await;
let listener = TokioTcpListener::bind(("127.0.0.1", port)).await.unwrap();
let (mut socket, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 1024];
let _ = socket.read(&mut buf).await;
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\nContent-Type: application/json\r\n\r\n{}",
body.len(),
body
);
socket.write_all(response.as_bytes()).await.unwrap();
}
#[cfg(unix)]
#[tokio::test]
async fn waits_for_ready_without_logs() {
let port = unused_port();
tokio::spawn(serve_json_version_once_after_delay(
port,
150,
r#"{"webSocketDebuggerUrl":"ws://127.0.0.1:9222/"}"#,
));
let mut child = Command::new("/bin/sh")
.args(["-c", "sleep 5"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let (logs, _drainers) = start_log_drainers(&mut child).unwrap();
let ws_url = wait_for_lightpanda_ready(&mut child, port, &logs, LIGHTPANDA_STARTUP_TIMEOUT)
.await
.unwrap();
assert_eq!(ws_url, format!("ws://127.0.0.1:{}/", port));
let _ = child.kill();
let _ = child.wait();
}
#[cfg(unix)]
#[tokio::test]
async fn child_exit_surfaces_logs() {
let port = unused_port();
let mut child = Command::new("/bin/sh")
.args(["-c", "echo boom >&2; sleep 0.1; exit 23"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let (logs, _drainers) = start_log_drainers(&mut child).unwrap();
let err = wait_for_lightpanda_ready(&mut child, port, &logs, LIGHTPANDA_STARTUP_TIMEOUT)
.await
.unwrap_err();
assert!(err.contains("Lightpanda exited before CDP became ready"));
assert!(err.contains("boom"));
}
#[cfg(unix)]
#[tokio::test]
async fn timeout_reports_last_probe_error() {
let port = unused_port();
let mut child = Command::new("/bin/sh")
.args(["-c", "sleep 30"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let timeout = Duration::from_millis(300);
let (logs, _drainers) = start_log_drainers(&mut child).unwrap();
let err = tokio::time::timeout(
Duration::from_secs(2),
wait_for_lightpanda_ready(&mut child, port, &logs, timeout),
)
.await
.expect("ready wait should return before outer timeout")
.unwrap_err();
assert!(err.contains("Timed out after 300ms waiting for Lightpanda CDP endpoint"));
assert!(
err.contains("Failed to connect to CDP") || err.contains("Timeout connecting to CDP")
);
let _ = child.kill();
let _ = child.wait();
}
#[test]
fn test_find_lightpanda_returns_none_when_missing() {
let _ = find_lightpanda();
}
#[test]
fn test_lightpanda_launch_error_no_logs() {
let logs = LaunchLogBuffer::default();
let msg = lightpanda_launch_error("Lightpanda exited", &logs, None);
assert!(msg.contains("no stdout/stderr output"));
}
#[test]
fn test_lightpanda_launch_error_with_lines() {
let logs = LaunchLogBuffer::default();
logs.push_stdout("stdout line".to_string());
logs.push_stderr("stderr line".to_string());
let msg = lightpanda_launch_error("Lightpanda exited", &logs, Some("connect failed"));
assert!(msg.contains("stdout line"));
assert!(msg.contains("stderr line"));
assert!(msg.contains("Last probe error: connect failed"));
}
#[test]
fn test_default_options() {
let opts = LightpandaLaunchOptions::default();
assert!(opts.executable_path.is_none());
assert!(opts.proxy.is_none());
assert!(opts.port.is_none());
}
#[test]
fn test_build_lightpanda_serve_args_sets_explicit_session_timeout() {
let args = build_lightpanda_serve_args(9222, None);
assert_eq!(
args,
vec![
"serve".to_string(),
"--host".to_string(),
"127.0.0.1".to_string(),
"--port".to_string(),
"9222".to_string(),
"--timeout".to_string(),
"604800".to_string(),
]
);
}
#[test]
fn test_build_lightpanda_serve_args_with_proxy() {
let args = build_lightpanda_serve_args(9333, Some("http://127.0.0.1:8080"));
assert_eq!(
args,
vec![
"serve".to_string(),
"--host".to_string(),
"127.0.0.1".to_string(),
"--port".to_string(),
"9333".to_string(),
"--timeout".to_string(),
"604800".to_string(),
"--http_proxy".to_string(),
"http://127.0.0.1:8080".to_string(),
]
);
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod chrome;
pub mod client;
pub mod discovery;
pub mod lightpanda;
pub mod types;
+586
View File
@@ -0,0 +1,586 @@
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
/// Deserialize a value that may be either a string or an integer into a String.
/// Lightpanda sends numeric nodeIds/childIds in AX tree responses, while Chrome
/// sends strings. This accepts both.
fn string_or_int<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: Deserializer<'de>,
{
let v = Value::deserialize(deserializer)?;
match v {
Value::String(s) => Ok(s),
Value::Number(n) => Ok(n.to_string()),
other => Err(serde::de::Error::custom(format!(
"expected string or integer, got {}",
other
))),
}
}
/// Deserialize an optional Vec where each element may be a string or integer.
fn opt_vec_string_or_int<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
D: Deserializer<'de>,
{
let opt: Option<Vec<Value>> = Option::deserialize(deserializer)?;
match opt {
None => Ok(None),
Some(vec) => {
let mut result = Vec::with_capacity(vec.len());
for v in vec {
match v {
Value::String(s) => result.push(s),
Value::Number(n) => result.push(n.to_string()),
other => {
return Err(serde::de::Error::custom(format!(
"expected string or integer in array, got {}",
other
)))
}
}
}
Ok(Some(result))
}
}
}
// ---------------------------------------------------------------------------
// CDP message envelope
// ---------------------------------------------------------------------------
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CdpCommand {
pub id: u64,
pub method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CdpMessage {
pub id: Option<u64>,
pub result: Option<Value>,
pub error: Option<CdpError>,
pub method: Option<String>,
pub params: Option<Value>,
pub session_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct CdpError {
pub code: Option<i64>,
pub message: String,
pub data: Option<String>,
}
impl std::fmt::Display for CdpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
// ---------------------------------------------------------------------------
// CDP events (broadcast to subscribers)
// ---------------------------------------------------------------------------
#[derive(Debug, Clone)]
pub struct CdpEvent {
pub method: String,
pub params: Value,
pub session_id: Option<String>,
}
// ---------------------------------------------------------------------------
// Target domain
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TargetInfo {
pub target_id: String,
#[serde(rename = "type")]
pub target_type: String,
pub title: String,
pub url: String,
pub attached: Option<bool>,
pub browser_context_id: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetTargetsResult {
pub target_infos: Vec<TargetInfo>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AttachToTargetParams {
pub target_id: String,
pub flatten: bool,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AttachToTargetResult {
pub session_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SetDiscoverTargetsParams {
pub discover: bool,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateTargetParams {
pub url: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateTargetResult {
pub target_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CloseTargetParams {
pub target_id: String,
}
// Target events
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TargetCreatedEvent {
pub target_info: TargetInfo,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TargetDestroyedEvent {
pub target_id: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TargetInfoChangedEvent {
pub target_info: TargetInfo,
}
// ---------------------------------------------------------------------------
// Page domain
// ---------------------------------------------------------------------------
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PageNavigateParams {
pub url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub referrer: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PageNavigateResult {
pub frame_id: String,
pub loader_id: Option<String>,
pub error_text: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FrameNavigatedEvent {
pub frame: FrameInfo,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FrameInfo {
pub id: String,
pub url: String,
pub parent_id: Option<String>,
pub name: Option<String>,
}
// Page.javascriptDialogOpening
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JavascriptDialogOpeningEvent {
pub url: String,
pub message: String,
#[serde(rename = "type")]
pub dialog_type: String,
pub default_prompt: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HandleJavaScriptDialogParams {
pub accept: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_text: Option<String>,
}
// ---------------------------------------------------------------------------
// Runtime domain
// ---------------------------------------------------------------------------
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EvaluateParams {
pub expression: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_by_value: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub await_promise: Option<bool>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EvaluateResult {
pub result: RemoteObject,
pub exception_details: Option<ExceptionDetails>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoteObject {
#[serde(rename = "type")]
pub object_type: String,
pub subtype: Option<String>,
pub value: Option<Value>,
pub description: Option<String>,
pub object_id: Option<String>,
pub class_name: Option<String>,
pub unserializable_value: Option<String>,
pub preview: Option<Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExceptionDetails {
pub text: String,
pub exception: Option<RemoteObject>,
pub line_number: Option<i64>,
pub column_number: Option<i64>,
}
// Runtime.consoleAPICalled
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsoleApiCalledEvent {
#[serde(rename = "type")]
pub call_type: String,
pub args: Vec<RemoteObject>,
pub timestamp: Option<f64>,
}
// Runtime.exceptionThrown
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExceptionThrownEvent {
pub timestamp: f64,
pub exception_details: ExceptionDetails,
}
// ---------------------------------------------------------------------------
// Accessibility domain
// ---------------------------------------------------------------------------
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetFullAXTreeResult {
pub nodes: Vec<AXNode>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AXNode {
#[serde(deserialize_with = "string_or_int")]
pub node_id: String,
pub role: Option<AXValue>,
pub name: Option<AXValue>,
pub value: Option<AXValue>,
pub description: Option<AXValue>,
pub properties: Option<Vec<AXProperty>>,
#[serde(default, deserialize_with = "opt_vec_string_or_int")]
pub child_ids: Option<Vec<String>>,
pub backend_d_o_m_node_id: Option<i64>,
pub ignored: Option<bool>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AXValue {
#[serde(rename = "type")]
pub value_type: String,
pub value: Option<Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AXProperty {
pub name: String,
pub value: AXValue,
}
// ---------------------------------------------------------------------------
// Network domain (minimal for Phase 1)
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestWillBeSentEvent {
pub request_id: String,
pub request: NetworkRequest,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkRequest {
pub url: String,
pub method: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoadingFinishedEvent {
pub request_id: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoadingFailedEvent {
pub request_id: String,
}
// ---------------------------------------------------------------------------
// DOM domain
// ---------------------------------------------------------------------------
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DomResolveNodeParams {
#[serde(skip_serializing_if = "Option::is_none")]
pub backend_node_id: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub node_id: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub object_group: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DomResolveNodeResult {
pub object: RemoteObject,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DomGetBoxModelParams {
#[serde(skip_serializing_if = "Option::is_none")]
pub backend_node_id: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub node_id: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub object_id: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DomGetBoxModelResult {
pub model: BoxModel,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BoxModel {
pub content: Vec<f64>,
pub padding: Vec<f64>,
pub border: Vec<f64>,
pub margin: Vec<f64>,
pub width: i64,
pub height: i64,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DomQuerySelectorParams {
pub node_id: i64,
pub selector: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DomQuerySelectorResult {
pub node_id: i64,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DomGetDocumentParams {
#[serde(skip_serializing_if = "Option::is_none")]
pub depth: Option<i32>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DomGetDocumentResult {
pub root: DomNode,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DomNode {
pub node_id: i64,
pub backend_node_id: Option<i64>,
pub node_type: Option<i64>,
pub node_name: Option<String>,
pub children: Option<Vec<DomNode>>,
}
// ---------------------------------------------------------------------------
// Input domain
// ---------------------------------------------------------------------------
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DispatchMouseEventParams {
#[serde(rename = "type")]
pub event_type: String,
pub x: f64,
pub y: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub button: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub buttons: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub click_count: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub delta_x: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub delta_y: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub modifiers: Option<i32>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DispatchKeyEventParams {
#[serde(rename = "type")]
pub event_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unmodified_text: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub windows_virtual_key_code: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub native_virtual_key_code: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub modifiers: Option<i32>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InsertTextParams {
pub text: String,
}
// ---------------------------------------------------------------------------
// Page.captureScreenshot
// ---------------------------------------------------------------------------
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureScreenshotParams {
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub quality: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub clip: Option<Viewport>,
#[serde(skip_serializing_if = "Option::is_none")]
pub from_surface: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub capture_beyond_viewport: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Viewport {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
pub scale: f64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureScreenshotResult {
pub data: String,
}
// ---------------------------------------------------------------------------
// Runtime.callFunctionOn
// ---------------------------------------------------------------------------
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallFunctionOnParams {
pub function_declaration: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub object_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub arguments: Option<Vec<CallArgument>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_by_value: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub await_promise: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallArgument {
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub object_id: Option<String>,
}
// ---------------------------------------------------------------------------
// Version info (from /json/version)
// ---------------------------------------------------------------------------
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BrowserVersionInfo {
#[serde(rename = "webSocketDebuggerUrl")]
pub web_socket_debugger_url: Option<String>,
#[serde(rename = "Browser")]
pub browser: Option<String>,
}
/// Auto-generated CDP types from protocol JSON files in `cdp-protocol/`.
///
/// To populate: download `browser_protocol.json` and `js_protocol.json` from
/// <https://github.com/nicolo-ribaudo/nicolo-ribaudo.github.io/> (or any
/// Chromium source) into `cli/cdp-protocol/` and rebuild.
///
/// Usage: `use super::cdp::types::generated::cdp_page::*;`
#[allow(clippy::upper_case_acronyms)]
pub mod generated {
include!(concat!(env!("OUT_DIR"), "/cdp_generated.rs"));
}
+100
View File
@@ -0,0 +1,100 @@
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use super::cdp::client::CdpClient;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Cookie {
pub name: String,
pub value: String,
pub domain: String,
pub path: String,
#[serde(default)]
pub expires: f64,
#[serde(default)]
pub size: i64,
#[serde(default)]
pub http_only: bool,
#[serde(default)]
pub secure: bool,
#[serde(default)]
pub session: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub same_site: Option<String>,
}
pub async fn get_all_cookies(client: &CdpClient, session_id: &str) -> Result<Vec<Cookie>, String> {
let result = client
.send_command_no_params("Network.getAllCookies", Some(session_id))
.await?;
let cookies: Vec<Cookie> = result
.get("cookies")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
Ok(cookies)
}
pub async fn get_cookies(
client: &CdpClient,
session_id: &str,
urls: Option<Vec<String>>,
) -> Result<Vec<Cookie>, String> {
let params = match urls {
Some(ref u) if !u.is_empty() => json!({ "urls": u }),
_ => json!({}),
};
let result = client
.send_command("Network.getCookies", Some(params), Some(session_id))
.await?;
let cookies: Vec<Cookie> = result
.get("cookies")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
Ok(cookies)
}
pub async fn set_cookies(
client: &CdpClient,
session_id: &str,
cookies: Vec<Value>,
current_url: Option<&str>,
) -> Result<(), String> {
let cookies: Vec<Value> = cookies
.into_iter()
.map(|mut c| {
// Auto-fill url if no domain/path/url provided
if c.get("url").is_none() && c.get("domain").is_none() && current_url.is_some() {
c.as_object_mut().map(|m| {
m.insert(
"url".to_string(),
Value::String(current_url.unwrap().to_string()),
)
});
}
c
})
.collect();
client
.send_command(
"Network.setCookies",
Some(json!({ "cookies": cookies })),
Some(session_id),
)
.await?;
Ok(())
}
pub async fn clear_cookies(client: &CdpClient, session_id: &str) -> Result<(), String> {
client
.send_command_no_params("Network.clearBrowserCookies", Some(session_id))
.await?;
Ok(())
}
+679
View File
@@ -0,0 +1,679 @@
use serde_json::Value;
use std::env;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::signal;
use tokio::sync::{mpsc, Notify, RwLock};
use super::actions::{execute_command, DaemonState};
use super::cdp::client::CdpClient;
use super::state;
use super::stream::StreamServer;
pub async fn run_daemon(session: &str) {
let socket_dir = get_daemon_socket_dir();
if !socket_dir.exists() {
let _ = fs::create_dir_all(&socket_dir);
}
// When debug mode is on, redirect stderr to a log file so daemon
// output can be inspected (the daemon normally has stderr piped to its
// parent which drops the read end after startup).
#[cfg(unix)]
if env::var("AGENT_BROWSER_DEBUG").is_ok() {
let log_path = socket_dir.join(format!("{}.log", session));
if let Ok(file) = fs::File::create(&log_path) {
use std::os::unix::io::IntoRawFd;
let fd = file.into_raw_fd();
unsafe {
libc::dup2(fd, 2);
libc::close(fd);
}
let _ = writeln!(
std::io::stderr(),
"[daemon] Debug logging started for session: {}",
session
);
}
} else {
// Redirect stderr to /dev/null to prevent daemon crash when the
// parent CLI drops the piped stderr handle after startup. Cloud
// providers (AgentCore, Browserbase, etc.) may write to stderr
// during connection setup; a broken pipe would kill the daemon.
#[cfg(unix)]
{
use std::os::unix::io::IntoRawFd;
if let Ok(devnull) = fs::File::create("/dev/null") {
let fd = devnull.into_raw_fd();
unsafe {
libc::dup2(fd, 2);
libc::close(fd);
}
}
}
}
let pid_path = socket_dir.join(format!("{}.pid", session));
let _ = fs::write(&pid_path, process::id().to_string());
let version_path = socket_dir.join(format!("{}.version", session));
let _ = fs::write(&version_path, env!("CARGO_PKG_VERSION"));
// On Unix the daemon listens on a Unix domain socket; on Windows it uses
// TCP, so there is no .sock file — only a .port file written by the server.
let socket_path = socket_dir.join(format!("{}.sock", session));
#[cfg(unix)]
if socket_path.exists() {
let _ = fs::remove_file(&socket_path);
}
#[cfg(windows)]
{
let _ = fs::remove_file(socket_dir.join(format!("{}.port", session)));
}
let stream_path = socket_dir.join(format!("{}.stream", session));
let _ = fs::remove_file(&stream_path);
let _ = fs::remove_file(socket_dir.join(format!("{}.engine", session)));
let _ = fs::remove_file(socket_dir.join(format!("{}.provider", session)));
let _ = fs::remove_file(socket_dir.join(format!("{}.extensions", session)));
if let Ok(days_str) = env::var("AGENT_BROWSER_STATE_EXPIRE_DAYS") {
if let Ok(days) = days_str.parse::<u64>() {
if days > 0 {
let _ = state::state_clean(days);
}
}
}
let mut stream_client: Option<Arc<RwLock<Option<Arc<CdpClient>>>>> = None;
let mut stream_server_instance: Option<Arc<StreamServer>> = None;
let preferred_port = env::var("AGENT_BROWSER_STREAM_PORT")
.ok()
.and_then(|s| s.parse::<u16>().ok())
.unwrap_or(0);
match StreamServer::start_without_client(preferred_port, session.to_string(), true).await {
Ok((stream_server, client_slot)) => {
stream_client = Some(client_slot.clone());
if let Err(e) = fs::write(&stream_path, stream_server.port().to_string()) {
let _ = writeln!(std::io::stderr(), "Failed to write .stream file: {}", e);
}
stream_server_instance = Some(Arc::new(stream_server));
}
Err(e) => {
let _ = writeln!(std::io::stderr(), "Stream server failed to start: {}", e);
}
}
// Auto-shutdown the daemon after this many ms of inactivity (no commands received).
// Disabled when unset or 0.
let idle_timeout_ms = env::var("AGENT_BROWSER_IDLE_TIMEOUT_MS")
.ok()
.and_then(|s| s.parse::<u64>().ok())
.filter(|&ms| ms > 0);
let result = run_socket_server(
&socket_path,
session,
stream_client,
stream_server_instance,
idle_timeout_ms,
)
.await;
#[cfg(unix)]
{
let _ = fs::remove_file(&socket_path);
}
#[cfg(windows)]
{
let _ = fs::remove_file(socket_dir.join(format!("{}.port", session)));
}
let _ = fs::remove_file(&pid_path);
let _ = fs::remove_file(&version_path);
let _ = fs::remove_file(&stream_path);
let _ = fs::remove_file(socket_dir.join(format!("{}.engine", session)));
let _ = fs::remove_file(socket_dir.join(format!("{}.provider", session)));
let _ = fs::remove_file(socket_dir.join(format!("{}.extensions", session)));
if let Err(e) = result {
let _ = writeln!(std::io::stderr(), "Daemon error: {}", e);
process::exit(1);
}
}
#[cfg(unix)]
async fn run_socket_server(
socket_path: &PathBuf,
session: &str,
stream_client: Option<Arc<RwLock<Option<Arc<CdpClient>>>>>,
stream_server: Option<Arc<StreamServer>>,
idle_timeout_ms: Option<u64>,
) -> Result<(), String> {
use tokio::net::UnixListener;
let listener =
UnixListener::bind(socket_path).map_err(|e| format!("Failed to bind socket: {}", e))?;
let stream_file: Option<PathBuf> = if stream_server.is_some() {
let dir = socket_path.parent().unwrap_or(std::path::Path::new("."));
Some(dir.join(format!("{}.stream", session)))
} else {
None
};
let state: std::sync::Arc<tokio::sync::Mutex<DaemonState>> = std::sync::Arc::new(
tokio::sync::Mutex::new(DaemonState::new_with_stream(stream_client, stream_server)),
);
let (reset_tx, mut reset_rx) = mpsc::channel::<()>(64);
let reset_tx = idle_timeout_ms.map(|_| Arc::new(reset_tx));
// Notifier used by handle_connection to signal the daemon loop to exit
// after a "close" command, instead of calling process::exit() which skips
// destructors and can leave Chrome processes orphaned (issue #1113).
let close_notify = Arc::new(Notify::new());
let mut drain_interval = tokio::time::interval(Duration::from_millis(100));
drain_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let idle_sleep = idle_timeout_ms.map(|ms| tokio::time::sleep(Duration::from_millis(ms)));
let mut idle_sleep_pin = idle_sleep.map(Box::pin);
loop {
tokio::select! {
accept_result = listener.accept() => {
match accept_result {
Ok((stream, _)) => {
let state = state.clone();
let reset_tx = reset_tx.clone();
let sf = stream_file.clone();
let cn = close_notify.clone();
tokio::spawn(async move {
handle_connection(stream, state, reset_tx, sf, cn).await;
});
}
Err(e) => {
let _ = writeln!(std::io::stderr(), "Accept error: {}", e);
}
}
}
_ = drain_interval.tick() => {
let mut s = state.lock().await;
if let Some(ref mut mgr) = s.browser {
if mgr.has_process_exited() {
let _ = mgr.close().await;
s.browser = None;
s.screencasting = false;
s.update_stream_client().await;
} else {
s.drain_cdp_events_background().await;
}
}
}
_ = async {
match idle_sleep_pin {
Some(ref mut s) => s.as_mut().await,
None => std::future::pending::<()>().await,
}
}, if idle_timeout_ms.is_some() => {
let mut s = state.lock().await;
if let Some(ref mut mgr) = s.browser {
let _ = mgr.close().await;
}
break;
}
_ = reset_rx.recv(), if idle_timeout_ms.is_some() => {
idle_sleep_pin = idle_timeout_ms
.map(|ms| Box::pin(tokio::time::sleep(Duration::from_millis(ms))));
continue;
}
_ = close_notify.notified() => {
// "close" command was handled; browser already closed by
// handle_close(). Break to run cleanup and exit gracefully
// so destructors fire.
break;
}
_ = shutdown_signal() => {
let mut s = state.lock().await;
if let Some(ref mut mgr) = s.browser {
let _ = mgr.close().await;
}
break;
}
}
}
Ok(())
}
#[cfg(windows)]
async fn run_socket_server(
socket_path: &PathBuf,
session: &str,
stream_client: Option<Arc<RwLock<Option<Arc<CdpClient>>>>>,
stream_server: Option<Arc<StreamServer>>,
idle_timeout_ms: Option<u64>,
) -> Result<(), String> {
use tokio::net::TcpListener;
let preferred_port = get_port_for_session(session);
// Try the hash-derived port first; if it is blocked (e.g. Windows Hyper-V
// excluded port range), fall back to an OS-assigned ephemeral port.
let listener = match TcpListener::bind(format!("127.0.0.1:{}", preferred_port)).await {
Ok(l) => l,
Err(_) => TcpListener::bind("127.0.0.1:0")
.await
.map_err(|e| format!("Failed to bind TCP: {}", e))?,
};
let actual_port = listener
.local_addr()
.map_err(|e| format!("Failed to get local address: {}", e))?
.port();
let socket_dir = socket_path.parent().unwrap_or(std::path::Path::new("."));
let port_path = socket_dir.join(format!("{}.port", session));
let _ = fs::write(&port_path, actual_port.to_string());
let stream_file: Option<PathBuf> = if stream_server.is_some() {
Some(socket_dir.join(format!("{}.stream", session)))
} else {
None
};
let state: std::sync::Arc<tokio::sync::Mutex<DaemonState>> = std::sync::Arc::new(
tokio::sync::Mutex::new(DaemonState::new_with_stream(stream_client, stream_server)),
);
let (reset_tx, mut reset_rx) = mpsc::channel::<()>(64);
let reset_tx = idle_timeout_ms.map(|_| Arc::new(reset_tx));
let close_notify = Arc::new(Notify::new());
let idle_sleep = idle_timeout_ms.map(|ms| tokio::time::sleep(Duration::from_millis(ms)));
let mut idle_sleep_pin = idle_sleep.map(Box::pin);
loop {
tokio::select! {
accept_result = listener.accept() => {
match accept_result {
Ok((stream, _)) => {
let state = state.clone();
let reset_tx = reset_tx.clone();
let sf = stream_file.clone();
let cn = close_notify.clone();
tokio::spawn(async move {
handle_connection(stream, state, reset_tx, sf, cn).await;
});
}
Err(e) => {
let _ = writeln!(std::io::stderr(), "Accept error: {}", e);
}
}
}
_ = async {
match idle_sleep_pin {
Some(ref mut s) => s.as_mut().await,
None => std::future::pending::<()>().await,
}
}, if idle_timeout_ms.is_some() => {
let mut s = state.lock().await;
if let Some(ref mut mgr) = s.browser {
let _ = mgr.close().await;
}
let _ = fs::remove_file(&port_path);
break;
}
_ = reset_rx.recv(), if idle_timeout_ms.is_some() => {
idle_sleep_pin = idle_timeout_ms
.map(|ms| Box::pin(tokio::time::sleep(Duration::from_millis(ms))));
continue;
}
_ = close_notify.notified() => {
let _ = fs::remove_file(&port_path);
break;
}
_ = shutdown_signal() => {
let mut s = state.lock().await;
if let Some(ref mut mgr) = s.browser {
let _ = mgr.close().await;
}
let _ = fs::remove_file(&port_path);
break;
}
}
}
Ok(())
}
async fn handle_connection<S>(
stream: S,
state: std::sync::Arc<tokio::sync::Mutex<DaemonState>>,
idle_reset_tx: Option<Arc<mpsc::Sender<()>>>,
stream_file_cleanup: Option<PathBuf>,
close_notify: Arc<Notify>,
) where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
{
let (reader, mut writer) = tokio::io::split(stream);
let mut buf_reader = BufReader::new(reader);
let mut line = String::new();
loop {
line.clear();
match buf_reader.read_line(&mut line).await {
Ok(0) => break,
Ok(_) => {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if looks_like_http(trimmed) {
break;
}
let cmd: Value = match serde_json::from_str(trimmed) {
Ok(v) => v,
Err(e) => {
let err = serde_json::json!({
"success": false,
"error": format!("Invalid JSON: {}", e),
});
let mut resp = serde_json::to_string(&err).unwrap_or_default();
resp.push('\n');
let _ = writer.write_all(resp.as_bytes()).await;
continue;
}
};
if let Some(ref tx) = idle_reset_tx {
let _ = tx.try_send(());
}
let is_close = cmd.get("action").and_then(|v| v.as_str()) == Some("close");
let response = {
let mut s = state.lock().await;
execute_command(&cmd, &mut s).await
};
let mut resp = serde_json::to_string(&response).unwrap_or_default();
resp.push('\n');
if writer.write_all(resp.as_bytes()).await.is_err() {
break;
}
if is_close {
if let Some(ref path) = stream_file_cleanup {
let _ = fs::remove_file(path);
}
// Signal the daemon loop to exit gracefully instead of
// calling process::exit(), which skips destructors and
// can leave Chrome processes orphaned (issue #1113).
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
close_notify.notify_one();
return;
}
}
Err(_) => break,
}
}
}
fn looks_like_http(line: &str) -> bool {
let prefixes = [
"GET ", "POST ", "PUT ", "DELETE ", "PATCH ", "HEAD ", "OPTIONS ", "CONNECT ", "TRACE ",
];
prefixes.iter().any(|p| line.starts_with(p))
}
async fn shutdown_signal() {
#[cfg(unix)]
{
let mut sigint = match signal::unix::signal(signal::unix::SignalKind::interrupt()) {
Ok(s) => s,
Err(e) => {
let _ = writeln!(std::io::stderr(), "Failed to install SIGINT handler: {}", e);
process::exit(1);
}
};
let mut sigterm = match signal::unix::signal(signal::unix::SignalKind::terminate()) {
Ok(s) => s,
Err(e) => {
let _ = writeln!(
std::io::stderr(),
"Failed to install SIGTERM handler: {}",
e
);
process::exit(1);
}
};
let mut sighup = match signal::unix::signal(signal::unix::SignalKind::hangup()) {
Ok(s) => s,
Err(e) => {
let _ = writeln!(std::io::stderr(), "Failed to install SIGHUP handler: {}", e);
process::exit(1);
}
};
tokio::select! {
_ = sigint.recv() => {}
_ = sigterm.recv() => {}
_ = sighup.recv() => {}
}
}
#[cfg(windows)]
{
if let Err(e) = signal::ctrl_c().await {
let _ = writeln!(std::io::stderr(), "Failed to install Ctrl+C handler: {}", e);
process::exit(1);
}
}
}
fn get_daemon_socket_dir() -> PathBuf {
if let Ok(dir) = env::var("AGENT_BROWSER_SOCKET_DIR") {
if !dir.is_empty() {
return PathBuf::from(dir);
}
}
if let Ok(xdg) = env::var("XDG_RUNTIME_DIR") {
if !xdg.is_empty() {
return PathBuf::from(xdg).join("agent-browser");
}
}
if let Some(home) = dirs::home_dir() {
return home.join(".agent-browser");
}
std::env::temp_dir().join("agent-browser")
}
#[cfg(windows)]
fn get_port_for_session(session: &str) -> u16 {
let mut hash: i32 = 0;
for c in session.chars() {
hash = ((hash << 5).wrapping_sub(hash)).wrapping_add(c as i32);
}
49152 + ((hash.unsigned_abs() as u32 % 16383) as u16)
}
#[cfg(test)]
mod tests {
#[allow(unused_imports)]
use super::*;
#[cfg(windows)]
#[test]
fn test_port_matches_client_algorithm() {
assert_eq!(get_port_for_session("default"), 50838);
assert_eq!(get_port_for_session("my-session"), 63105);
assert_eq!(get_port_for_session("work"), 51184);
assert_eq!(get_port_for_session(""), 49152);
}
/// Guard against re-introducing `waitpid(-1)` in daemon code.
///
/// Issue #1035: a SIGCHLD handler that called `waitpid(-1, WNOHANG)` was
/// added in v0.22.3 to reap zombie Chrome processes. This races with
/// Rust's `Child::try_wait()` / `Child::wait()` because `waitpid(-1)`
/// reaps *any* child, stealing the exit status before Rust can collect
/// it. The result is ECHILD errors in `BrowserManager::has_process_exited()`
/// and `ChromeProcess::kill()`, which can leave the daemon in a broken
/// state or cause hangs on certain Linux configurations.
///
/// The fix uses the existing 500ms drain interval to call
/// `has_process_exited()` (which delegates to `Child::try_wait()`)
/// for targeted, race-free zombie detection.
#[test]
fn test_no_waitpid_minus_one_in_daemon() {
let source = include_str!("daemon.rs");
// Only check production code (everything before `#[cfg(test)]`)
let production_code = source.split("#[cfg(test)]").next().unwrap_or(source);
assert!(
!production_code.contains("waitpid(-1"),
"daemon.rs production code must not call waitpid(-1, ...). \
Use Child::try_wait() via has_process_exited() instead. \
See issue #1035."
);
}
/// Verify that `Child::try_wait()` correctly detects a crashed child
/// without needing a global SIGCHLD handler or `waitpid(-1)`.
/// This is what `has_process_exited()` uses in the fixed code.
#[cfg(unix)]
#[test]
fn test_child_try_wait_detects_exit_without_sigchld_handler() {
use std::process::{Command, Stdio};
let mut child = Command::new("/bin/sh")
.args(["-c", "exit 42"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("failed to spawn child");
std::thread::sleep(std::time::Duration::from_millis(200));
match child.try_wait() {
Ok(Some(status)) => {
assert!(
!status.success(),
"child exited with code 42, should not be success"
);
}
Ok(None) => panic!("try_wait() returned None but child should have exited"),
Err(e) => panic!("try_wait() should succeed without waitpid(-1): {}", e),
}
}
/// Regression test for #1101: idle timeout must fire even while the
/// drain interval ticks every 500 ms. The bug was that `sleep_future`
/// was created **inside** the loop, so each drain tick dropped the
/// in-progress sleep and replaced it with a fresh one the timer
/// could never reach its deadline.
#[tokio::test]
async fn test_idle_timeout_fires_despite_drain_interval() {
use tokio::sync::mpsc;
let idle_timeout_ms: u64 = 1000;
let mut drain_interval = tokio::time::interval(Duration::from_millis(500));
drain_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let (_reset_tx, mut reset_rx) = mpsc::channel::<()>(64);
let start = tokio::time::Instant::now();
let exited = tokio::time::timeout(Duration::from_secs(5), async {
let mut idle_sleep_pin = Some(Box::pin(tokio::time::sleep(Duration::from_millis(
idle_timeout_ms,
))));
loop {
tokio::select! {
_ = drain_interval.tick() => {}
_ = async {
match idle_sleep_pin {
Some(ref mut s) => s.as_mut().await,
None => std::future::pending::<()>().await,
}
} => {
break;
}
_ = reset_rx.recv() => {
idle_sleep_pin = Some(Box::pin(
tokio::time::sleep(Duration::from_millis(idle_timeout_ms)),
));
continue;
}
}
}
})
.await;
let elapsed = start.elapsed();
assert!(
exited.is_ok(),
"idle timeout never fired loop ran for >5 s (bug #1101)"
);
assert!(
elapsed < Duration::from_millis(idle_timeout_ms + 500),
"idle timeout took too long: {:?} (expected ~{} ms)",
elapsed,
idle_timeout_ms,
);
}
/// Verify that `ChromeProcess::has_exited()` (which uses `Child::try_wait()`)
/// correctly detects a killed child, the same way the drain interval does
/// in the fixed daemon code. This ensures crash detection works without
/// a SIGCHLD handler.
#[cfg(unix)]
#[test]
fn test_has_exited_detects_killed_process() {
use std::process::{Command, Stdio};
let mut child = Command::new("/bin/sh")
.args(["-c", "sleep 60"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("failed to spawn child");
// Process should be running
match child.try_wait() {
Ok(None) => {} // expected
other => panic!("expected Ok(None) for running process, got {:?}", other),
}
// Kill it (simulates Chrome crash)
child.kill().expect("failed to kill child");
std::thread::sleep(std::time::Duration::from_millis(100));
// try_wait should detect the exit
match child.try_wait() {
Ok(Some(_)) => {} // expected: detected the crash
other => panic!(
"expected Ok(Some(_)) after kill, got {:?}. \
Crash detection via try_wait() must work for the drain \
interval fix (issue #1035) to function correctly.",
other
),
}
}
}
+274
View File
@@ -0,0 +1,274 @@
use serde_json::{json, Value};
use similar::{ChangeTag, TextDiff};
pub struct ScreenshotDiffResult {
pub total_pixels: u64,
pub different_pixels: u64,
pub mismatch_percentage: f64,
pub matched: bool,
pub diff_image: Option<Vec<u8>>,
pub dimension_mismatch: Option<Value>,
}
pub struct SnapshotDiffResult {
pub diff: String,
pub additions: usize,
pub removals: usize,
pub unchanged: usize,
pub changed: bool,
}
pub fn diff_screenshot(
baseline: &[u8],
current: &[u8],
threshold: f64,
) -> Result<ScreenshotDiffResult, String> {
let img_a = image::load_from_memory(baseline)
.map_err(|e| format!("Failed to decode baseline image: {}", e))?;
let img_b = image::load_from_memory(current)
.map_err(|e| format!("Failed to decode current image: {}", e))?;
let (wa, ha) = (img_a.width(), img_a.height());
let (wb, hb) = (img_b.width(), img_b.height());
if wa != wb || ha != hb {
return Ok(ScreenshotDiffResult {
total_pixels: (wa as u64) * (ha as u64),
different_pixels: (wa as u64) * (ha as u64),
mismatch_percentage: 100.0,
matched: false,
diff_image: None,
dimension_mismatch: Some(json!({
"expected": { "width": wa, "height": ha },
"actual": { "width": wb, "height": hb },
})),
});
}
let rgba_a = img_a.to_rgba8();
let rgba_b = img_b.to_rgba8();
let total = (wa as u64) * (ha as u64);
let max_color_distance = threshold * 255.0 * (3.0_f64).sqrt();
let mut different = 0u64;
let mut diff_img = image::RgbaImage::new(wa, ha);
for y in 0..ha {
for x in 0..wa {
let pa = rgba_a.get_pixel(x, y);
let pb = rgba_b.get_pixel(x, y);
let dr = (pa[0] as f64) - (pb[0] as f64);
let dg = (pa[1] as f64) - (pb[1] as f64);
let db = (pa[2] as f64) - (pb[2] as f64);
let dist = (dr * dr + dg * dg + db * db).sqrt();
if dist > max_color_distance {
different += 1;
diff_img.put_pixel(x, y, image::Rgba([255, 0, 0, 255]));
} else {
let gray = ((pa[0] as u16 + pa[1] as u16 + pa[2] as u16) / 3) as u8;
let dimmed = (gray as f64 * 0.3) as u8;
diff_img.put_pixel(x, y, image::Rgba([dimmed, dimmed, dimmed, 255]));
}
}
}
let mismatch = if total > 0 {
(different as f64 / total as f64) * 100.0
} else {
0.0
};
let diff_bytes = if different > 0 {
let mut buf = std::io::Cursor::new(Vec::new());
diff_img
.write_to(&mut buf, image::ImageFormat::Png)
.map_err(|e| format!("Failed to encode diff image: {}", e))?;
Some(buf.into_inner())
} else {
None
};
Ok(ScreenshotDiffResult {
total_pixels: total,
different_pixels: different,
mismatch_percentage: mismatch,
matched: different == 0,
diff_image: diff_bytes,
dimension_mismatch: None,
})
}
/// Compute a snapshot diff using the Myers algorithm via the `similar` crate.
pub fn diff_snapshots(before: &str, after: &str) -> SnapshotDiffResult {
// Fast path: identical inputs.
// This avoids constructing the `similar` TextDiff object and running the diff
// iteration when agents compare a snapshot to itself (common in retry/loop
// workloads).
if before == after {
let unchanged = before.lines().count();
return SnapshotDiffResult {
diff: String::new(),
additions: 0,
removals: 0,
unchanged,
changed: false,
};
}
let text_diff = TextDiff::from_lines(before, after);
let mut additions = 0usize;
let mut removals = 0usize;
let mut unchanged = 0usize;
for change in text_diff.iter_all_changes() {
match change.tag() {
ChangeTag::Insert => additions += 1,
ChangeTag::Delete => removals += 1,
ChangeTag::Equal => unchanged += 1,
}
}
let changed = additions > 0 || removals > 0;
let diff = text_diff
.unified_diff()
.context_radius(3)
.header("before", "after")
.to_string();
SnapshotDiffResult {
diff,
additions,
removals,
unchanged,
changed,
}
}
/// Legacy JSON diff output for backwards compatibility.
pub fn diff_text(a: &str, b: &str) -> Value {
let result = diff_snapshots(a, b);
json!({
"identical": !result.changed,
"additions": result.additions,
"removals": result.removals,
"deletions": result.removals,
"unchanged": result.unchanged,
"changed": result.changed,
})
}
pub fn diff_unified(a: &str, b: &str) -> String {
diff_snapshots(a, b).diff
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_diff_identical() {
let result = diff_text("hello\nworld", "hello\nworld");
assert_eq!(result.get("identical").unwrap(), true);
assert_eq!(result.get("changed").unwrap(), false);
assert_eq!(result.get("unchanged").unwrap(), 2);
}
#[test]
fn test_diff_additions() {
let result = diff_text("hello\n", "hello\nworld\n");
assert_eq!(result.get("identical").unwrap(), false);
assert_eq!(result.get("changed").unwrap(), true);
assert!(result.get("additions").unwrap().as_i64().unwrap() > 0);
}
#[test]
fn test_diff_deletions() {
let result = diff_text("hello\nworld\n", "hello\n");
assert_eq!(result.get("identical").unwrap(), false);
assert!(result.get("removals").unwrap().as_i64().unwrap() > 0);
}
#[test]
fn test_diff_unified_output() {
let output = diff_unified("a\nb\nc\n", "a\nx\nc\n");
assert!(output.contains("---"));
assert!(output.contains("+++"));
}
#[test]
fn test_snapshot_diff_struct() {
let result = diff_snapshots("line1\nline2\n", "line1\nline3\n");
assert!(result.changed);
assert_eq!(result.additions, 1);
assert_eq!(result.removals, 1);
assert_eq!(result.unchanged, 1);
assert!(!result.diff.is_empty());
}
#[test]
fn test_diff_snapshots_identical_fast_path() {
let input = "hello\nworld\n";
let result = diff_snapshots(input, input);
assert!(!result.changed);
assert_eq!(result.additions, 0);
assert_eq!(result.removals, 0);
assert_eq!(result.unchanged, input.lines().count());
assert!(result.diff.is_empty());
}
#[test]
#[ignore]
fn bench_diff_snapshots_identical_and_changed() {
use std::hint::black_box;
use std::time::Instant;
let identical_a = (0..200)
.map(|i| format!("line {i}"))
.collect::<Vec<_>>()
.join("\n");
let identical_b = identical_a.clone();
let changed_a = identical_a.clone();
let changed_b = (0..200)
.map(|i| {
if i == 123 {
format!("line {i} changed")
} else {
format!("line {i}")
}
})
.collect::<Vec<_>>()
.join("\n");
// Keep the iteration count high enough to measure, but low enough
// to avoid long CI times when someone runs `--ignored`.
let iters = 50_000usize;
let start = Instant::now();
let mut acc_changed = 0usize;
for _ in 0..iters {
let r = diff_snapshots(black_box(&identical_a), black_box(&identical_b));
acc_changed ^= r.unchanged;
}
let identical_ms = start.elapsed().as_secs_f64() * 1000.0;
let start = Instant::now();
let mut acc_changed2 = 0usize;
for _ in 0..iters {
let r = diff_snapshots(black_box(&changed_a), black_box(&changed_b));
acc_changed2 ^= r.additions;
}
let changed_ms = start.elapsed().as_secs_f64() * 1000.0;
// Prevent the compiler from optimizing everything away.
black_box(acc_changed);
black_box(acc_changed2);
println!(
"bench_diff_snapshots_identical_and_changed: iters={iters} identical_ms={identical_ms:.2} changed_ms={changed_ms:.2}"
);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+362
View File
@@ -0,0 +1,362 @@
use std::io::Write;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::Arc;
use futures_util::{SinkExt, StreamExt};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use tokio::sync::Mutex;
use tokio_tungstenite::tungstenite::Message;
use super::cdp::client::InspectProxyHandle;
/// Counter for unique attach IDs so concurrent connections don't collide.
static ATTACH_ID: AtomicI64 = AtomicI64::new(-1000);
/// Lightweight HTTP + WebSocket server for `agent-browser inspect`.
///
/// Serves two purposes:
/// - `GET /` redirects to Chrome's built-in DevTools frontend with `ws=` pointing to this server
/// - WebSocket connections create a dedicated CDP session via `Target.attachToTarget` and proxy
/// CDP messages through the daemon's existing browser-level connection, injecting/stripping
/// `sessionId` so the DevTools frontend sees a page-level view
pub struct InspectServer {
port: u16,
_handle: tokio::task::JoinHandle<()>,
}
impl InspectServer {
/// Start the inspect proxy server.
///
/// - `proxy_handle`: lightweight handle for sending/receiving raw CDP messages
/// - `target_id`: the CDP target ID of the page to inspect
/// - `chrome_host_port`: the Chrome debug server address (e.g. "127.0.0.1:9222")
pub async fn start(
proxy_handle: InspectProxyHandle,
target_id: String,
chrome_host_port: String,
) -> Result<Self, String> {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.map_err(|e| format!("Failed to bind inspect server: {}", e))?;
let port = listener
.local_addr()
.map_err(|e| format!("Failed to get local addr: {}", e))?
.port();
let proxy = Arc::new(proxy_handle);
let handle = tokio::spawn(accept_loop(
listener,
proxy,
target_id,
chrome_host_port,
port,
));
Ok(Self {
port,
_handle: handle,
})
}
pub fn port(&self) -> u16 {
self.port
}
pub fn shutdown(self) {
self._handle.abort();
}
}
async fn accept_loop(
listener: TcpListener,
proxy: Arc<InspectProxyHandle>,
target_id: String,
chrome_host_port: String,
proxy_port: u16,
) {
loop {
let (stream, _) = match listener.accept().await {
Ok(s) => s,
Err(_) => continue,
};
let proxy = proxy.clone();
let tid = target_id.clone();
let chp = chrome_host_port.clone();
tokio::spawn(async move {
if let Err(e) = handle_connection(stream, proxy, tid, chp, proxy_port).await {
let _ = writeln!(std::io::stderr(), "[inspect] connection error: {}", e);
}
});
}
}
async fn handle_connection(
stream: tokio::net::TcpStream,
proxy: Arc<InspectProxyHandle>,
target_id: String,
chrome_host_port: String,
proxy_port: u16,
) -> Result<(), String> {
// Peek at the request line to determine routing WITHOUT consuming bytes.
// This is critical: tokio_tungstenite::accept_async needs to read the full
// HTTP upgrade request itself, so we must not consume anything for WS paths.
let mut peek_buf = [0u8; 32];
let n = stream
.peek(&mut peek_buf)
.await
.map_err(|e| e.to_string())?;
let peek = String::from_utf8_lossy(&peek_buf[..n]);
if peek.starts_with("GET /ws") {
return handle_ws_proxy(stream, proxy, target_id).await;
}
if peek.starts_with("GET / ") {
let buf_reader = BufReader::new(stream);
return handle_http_redirect(buf_reader, chrome_host_port, proxy_port).await;
}
// Unknown request -- consume and respond 404
let mut stream = stream;
let mut discard = [0u8; 4096];
let _ = stream.read(&mut discard).await;
let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
stream
.write_all(resp.as_bytes())
.await
.map_err(|e| e.to_string())?;
Ok(())
}
const MAX_HEADER_BYTES: usize = 8192;
async fn handle_http_redirect(
buf_reader: BufReader<tokio::net::TcpStream>,
chrome_host_port: String,
proxy_port: u16,
) -> Result<(), String> {
let mut br = buf_reader;
let mut total_bytes = 0usize;
loop {
let mut line = String::new();
let n = br.read_line(&mut line).await.map_err(|e| e.to_string())?;
total_bytes += n;
if line == "\r\n" || line == "\n" || line.is_empty() || total_bytes > MAX_HEADER_BYTES {
break;
}
}
let location = format!(
"http://{}/devtools/devtools_app.html?ws=127.0.0.1:{}/ws",
chrome_host_port, proxy_port
);
let body = format!(
"<html><body>Redirecting to <a href=\"{url}\">{url}</a></body></html>",
url = location
);
let resp = format!(
"HTTP/1.1 302 Found\r\nLocation: {}\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
location,
body.len(),
body
);
let mut stream = br.into_inner();
stream
.write_all(resp.as_bytes())
.await
.map_err(|e| e.to_string())?;
Ok(())
}
async fn handle_ws_proxy(
stream: tokio::net::TcpStream,
proxy: Arc<InspectProxyHandle>,
target_id: String,
) -> Result<(), String> {
let ws_stream = tokio_tungstenite::accept_async(stream)
.await
.map_err(|e| format!("WebSocket handshake failed: {}", e))?;
// Create a dedicated CDP session for this DevTools connection.
// Each connection gets its own session so domain enablements (DOM.enable, etc.)
// always trigger fresh initial state dumps from Chrome.
let attach_id = ATTACH_ID.fetch_sub(1, Ordering::SeqCst);
let attach_cmd = format!(
r#"{{"id":{},"method":"Target.attachToTarget","params":{{"targetId":"{}","flatten":true}}}}"#,
attach_id, target_id
);
// Subscribe BEFORE sending so we don't miss the response (tokio broadcast
// receivers only deliver messages to receivers that already exist).
let mut raw_rx = proxy.subscribe_raw();
proxy
.send_raw(attach_cmd)
.await
.map_err(|e| format!("Failed to send attachToTarget: {}", e))?;
// Wait for the attachToTarget response to extract the session ID
let session_id = tokio::time::timeout(std::time::Duration::from_secs(5), async {
while let Ok(raw_msg) = raw_rx.recv().await {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&raw_msg.text) {
if val.get("id").and_then(|v| v.as_i64()) == Some(attach_id) {
if let Some(sid) = val
.get("result")
.and_then(|r| r.get("sessionId"))
.and_then(|s| s.as_str())
{
return Ok(sid.to_string());
}
return Err("attachToTarget failed".to_string());
}
}
}
Err("raw message channel closed".to_string())
})
.await
.map_err(|_| "Timed out waiting for attachToTarget response".to_string())?
.map_err(|e| format!("Failed to create DevTools session: {}", e))?;
let (ws_tx, mut ws_rx) = ws_stream.split();
let ws_tx = Arc::new(Mutex::new(ws_tx));
let mut raw_rx = proxy.subscribe_raw();
let ws_tx_clone = ws_tx.clone();
let session_id_clone = session_id.clone();
// Chrome -> DevTools: forward messages matching our session, strip sessionId
let mut chrome_to_devtools = tokio::spawn(async move {
loop {
let raw_msg = match raw_rx.recv().await {
Ok(msg) => msg,
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
let _ = writeln!(
std::io::stderr(),
"[inspect] warning: dropped {} CDP messages (channel lag)",
n
);
continue;
}
Err(_) => break,
};
if raw_msg.session_id.as_deref() != Some(&session_id_clone) {
continue;
}
let stripped = strip_session_id(&raw_msg.text);
let mut tx = ws_tx_clone.lock().await;
if tx.send(Message::Text(stripped)).await.is_err() {
break;
}
}
});
// DevTools -> Chrome: inject sessionId and forward
let proxy_for_send = proxy.clone();
let session_id_for_send = session_id.clone();
let mut devtools_to_chrome = tokio::spawn(async move {
while let Some(Ok(msg)) = ws_rx.next().await {
let text = match msg {
Message::Text(t) => t,
Message::Close(_) => break,
_ => continue,
};
let injected = inject_session_id(&text, &session_id_for_send);
if proxy_for_send.send_raw(injected).await.is_err() {
break;
}
}
});
tokio::select! {
_ = &mut chrome_to_devtools => {
devtools_to_chrome.abort();
},
_ = &mut devtools_to_chrome => {
chrome_to_devtools.abort();
},
}
// Clean up the CDP session so Chrome doesn't leak attached targets
let detach_cmd = format!(
r#"{{"id":{},"method":"Target.detachFromTarget","params":{{"sessionId":"{}"}}}}"#,
ATTACH_ID.fetch_sub(1, Ordering::SeqCst),
session_id
);
let _ = proxy.send_raw(detach_cmd).await;
Ok(())
}
fn inject_session_id(json: &str, session_id: &str) -> String {
if let Ok(mut val) = serde_json::from_str::<serde_json::Value>(json) {
if let Some(obj) = val.as_object_mut() {
obj.insert(
"sessionId".to_string(),
serde_json::Value::String(session_id.to_string()),
);
}
serde_json::to_string(&val).unwrap_or_else(|_| json.to_string())
} else {
json.to_string()
}
}
fn strip_session_id(json: &str) -> String {
if let Ok(mut val) = serde_json::from_str::<serde_json::Value>(json) {
if let Some(obj) = val.as_object_mut() {
obj.remove("sessionId");
}
serde_json::to_string(&val).unwrap_or_else(|_| json.to_string())
} else {
json.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_inject_session_id() {
let input = r#"{"id":1,"method":"DOM.getDocument"}"#;
let result = inject_session_id(input, "abc123");
let parsed: serde_json::Value = serde_json::from_str(&result).expect("valid JSON");
assert_eq!(parsed["sessionId"], "abc123");
assert_eq!(parsed["method"], "DOM.getDocument");
assert_eq!(parsed["id"], 1);
}
#[test]
fn test_inject_session_id_empty_object() {
let result = inject_session_id("{}", "abc");
let parsed: serde_json::Value = serde_json::from_str(&result).expect("valid JSON");
assert_eq!(parsed["sessionId"], "abc");
}
#[test]
fn test_strip_session_id() {
let input = r#"{"id":1,"result":{},"sessionId":"abc123"}"#;
let result = strip_session_id(input);
let parsed: serde_json::Value = serde_json::from_str(&result).expect("valid JSON");
assert!(parsed.get("sessionId").is_none());
assert_eq!(parsed["id"], 1);
}
#[test]
fn test_inject_then_strip_roundtrip() {
let input = r#"{"id":42,"method":"Runtime.evaluate"}"#;
let injected = inject_session_id(input, "sess1");
let stripped = strip_session_id(&injected);
let original: serde_json::Value = serde_json::from_str(input).unwrap();
let result: serde_json::Value = serde_json::from_str(&stripped).unwrap();
assert_eq!(original, result);
}
}
File diff suppressed because it is too large Load Diff
+51
View File
@@ -0,0 +1,51 @@
#[allow(dead_code)]
pub mod actions;
#[allow(dead_code)]
pub mod auth;
#[allow(dead_code)]
pub mod browser;
#[allow(dead_code)]
pub mod cdp;
#[allow(dead_code)]
pub mod cookies;
#[allow(dead_code)]
pub mod daemon;
#[allow(dead_code)]
pub mod diff;
#[allow(dead_code)]
pub mod element;
#[allow(dead_code)]
pub mod inspect_server;
#[allow(dead_code)]
pub mod interaction;
#[allow(dead_code)]
pub mod network;
#[allow(dead_code)]
pub mod policy;
#[allow(dead_code)]
pub mod providers;
#[allow(dead_code)]
pub mod react;
#[allow(dead_code)]
pub mod recording;
#[allow(dead_code)]
pub mod screenshot;
#[allow(dead_code)]
pub mod snapshot;
#[allow(dead_code)]
pub mod state;
#[allow(dead_code)]
pub mod stealth;
#[allow(dead_code)]
pub mod storage;
#[allow(dead_code)]
pub mod stream;
#[allow(dead_code)]
pub mod tracing;
#[allow(dead_code)]
pub mod webdriver;
#[cfg(test)]
mod e2e_tests;
#[cfg(test)]
mod parity_tests;
+672
View File
@@ -0,0 +1,672 @@
use serde_json::{json, Value};
use std::collections::HashMap;
use super::cdp::client::CdpClient;
pub async fn set_extra_headers(
client: &CdpClient,
session_id: &str,
headers: &HashMap<String, String>,
) -> Result<(), String> {
let headers_value: Value = headers
.iter()
.map(|(k, v)| (k.clone(), Value::String(v.clone())))
.collect::<serde_json::Map<String, Value>>()
.into();
client
.send_command(
"Network.setExtraHTTPHeaders",
Some(json!({ "headers": headers_value })),
Some(session_id),
)
.await?;
Ok(())
}
pub async fn set_offline(
client: &CdpClient,
session_id: &str,
offline: bool,
) -> Result<(), String> {
client
.send_command(
"Network.emulateNetworkConditions",
Some(json!({
"offline": offline,
"latency": 0,
"downloadThroughput": -1,
"uploadThroughput": -1,
})),
Some(session_id),
)
.await?;
Ok(())
}
pub async fn set_content(client: &CdpClient, session_id: &str, html: &str) -> Result<(), String> {
// Get current frame ID
let tree_result = client
.send_command_no_params("Page.getFrameTree", Some(session_id))
.await?;
let frame_id = tree_result
.get("frameTree")
.and_then(|t| t.get("frame"))
.and_then(|f| f.get("id"))
.and_then(|id| id.as_str())
.ok_or("Could not determine frame ID")?;
client
.send_command(
"Page.setDocumentContent",
Some(json!({
"frameId": frame_id,
"html": html,
})),
Some(session_id),
)
.await?;
Ok(())
}
// ---------------------------------------------------------------------------
// Domain filter
// ---------------------------------------------------------------------------
#[derive(Debug, Clone)]
pub struct DomainFilter {
pub allowed_domains: Vec<String>,
}
impl DomainFilter {
pub fn new(domains: &str) -> Self {
let allowed = parse_domain_list(domains);
Self {
allowed_domains: allowed,
}
}
pub fn is_allowed(&self, hostname: &str) -> bool {
if self.allowed_domains.is_empty() {
return true;
}
let hostname = hostname.to_lowercase();
for pattern in &self.allowed_domains {
if let Some(suffix) = pattern.strip_prefix("*.") {
if hostname == suffix || hostname.ends_with(&format!(".{}", suffix)) {
return true;
}
} else if hostname == *pattern {
return true;
}
}
false
}
pub fn check_url(&self, url: &str) -> Result<(), String> {
if self.allowed_domains.is_empty() {
return Ok(());
}
let parsed = url::Url::parse(url).map_err(|_| format!("Invalid URL: {}", url))?;
let hostname = parsed
.host_str()
.ok_or_else(|| format!("No hostname in URL: {}", url))?;
if self.is_allowed(hostname) {
Ok(())
} else {
Err(format!(
"Domain '{}' is not in the allowed domains list",
hostname
))
}
}
}
fn parse_domain_list(input: &str) -> Vec<String> {
input
.split(',')
.map(|s| s.trim().to_lowercase())
.filter(|s| !s.is_empty())
.collect()
}
pub async fn sanitize_existing_pages(
client: &CdpClient,
pages: &[super::browser::PageInfo],
filter: &DomainFilter,
) {
for page in pages {
if page.url.is_empty() || page.url == "about:blank" {
continue;
}
if let Ok(parsed) = url::Url::parse(&page.url) {
if let Some(hostname) = parsed.host_str() {
if !filter.is_allowed(hostname) {
let _ = client
.send_command(
"Page.navigate",
Some(json!({ "url": "about:blank" })),
Some(&page.session_id),
)
.await;
}
}
}
}
}
pub async fn install_domain_filter_script(
client: &CdpClient,
session_id: &str,
allowed_domains: &[String],
) -> Result<(), String> {
if allowed_domains.is_empty() {
return Ok(());
}
let domains_json = serde_json::to_string(allowed_domains).unwrap_or("[]".to_string());
let script = format!(
r#"(() => {{
const _allowed = {};
function _isDomainAllowed(hostname) {{
hostname = hostname.toLowerCase();
for (const p of _allowed) {{
if (p.startsWith('*.')) {{
const suffix = p.slice(2);
if (hostname === suffix || hostname.endsWith('.' + suffix)) return true;
}} else if (hostname === p) return true;
}}
return false;
}}
const OrigWS = window.WebSocket;
window.WebSocket = function(url, protocols) {{
try {{
const u = new URL(url, location.href);
if (!_isDomainAllowed(u.hostname)) throw new DOMException('WebSocket blocked: ' + u.hostname, 'SecurityError');
}} catch(e) {{ if (e instanceof DOMException) throw e; }}
return new OrigWS(url, protocols);
}};
window.WebSocket.prototype = OrigWS.prototype;
const OrigES = window.EventSource;
if (OrigES) {{
window.EventSource = function(url, opts) {{
try {{
const u = new URL(url, location.href);
if (!_isDomainAllowed(u.hostname)) throw new DOMException('EventSource blocked: ' + u.hostname, 'SecurityError');
}} catch(e) {{ if (e instanceof DOMException) throw e; }}
return new OrigES(url, opts);
}};
window.EventSource.prototype = OrigES.prototype;
}}
const origBeacon = navigator.sendBeacon;
if (origBeacon) {{
navigator.sendBeacon = function(url, data) {{
try {{
const u = new URL(url, location.href);
if (!_isDomainAllowed(u.hostname)) return false;
}} catch(e) {{ return false; }}
return origBeacon.call(navigator, url, data);
}};
}}
}})()"#,
domains_json,
);
client
.send_command(
"Page.addScriptToEvaluateOnNewDocument",
Some(json!({ "source": script })),
Some(session_id),
)
.await?;
Ok(())
}
/// Enable Fetch-based network interception for domain filtering.
/// This intercepts all requests and checks them against the allowed domains list.
/// The actual handling of `Fetch.requestPaused` events happens in
/// `resolve_fetch_paused` in the actions module.
pub async fn install_domain_filter_fetch(
client: &CdpClient,
session_id: &str,
handle_auth_requests: bool,
) -> Result<(), String> {
let mut params = json!({
"patterns": [{ "urlPattern": "*" }]
});
if handle_auth_requests {
params["handleAuthRequests"] = json!(true);
}
client
.send_command("Fetch.enable", Some(params), Some(session_id))
.await?;
Ok(())
}
/// Install both layers of domain filtering on a session:
/// 1. JS patching (WebSocket, EventSource, sendBeacon)
/// 2. Fetch-based network interception
pub async fn install_domain_filter(
client: &CdpClient,
session_id: &str,
allowed_domains: &[String],
handle_auth_requests: bool,
) -> Result<(), String> {
install_domain_filter_script(client, session_id, allowed_domains).await?;
install_domain_filter_fetch(client, session_id, handle_auth_requests).await?;
Ok(())
}
// ---------------------------------------------------------------------------
// Console arg formatting (CDP RemoteObject → human-readable string)
// ---------------------------------------------------------------------------
/// Format a single CDP RemoteObject arg into a human-readable string.
/// Priority: value → preview → description.
pub fn format_console_arg(arg: &Value) -> Option<String> {
let obj_type = arg.get("type").and_then(|v| v.as_str()).unwrap_or("");
let subtype = arg.get("subtype").and_then(|v| v.as_str());
if obj_type == "undefined" {
return Some("undefined".to_string());
}
if subtype == Some("null") {
return Some("null".to_string());
}
// Primitive value
if let Some(v) = arg.get("value") {
return Some(match v {
Value::String(s) => s.clone(),
Value::Null => "null".to_string(),
other => other.to_string(),
});
}
// Skip preview for Map/Set — their description ("Map(1)", "Set(3)") is more useful
// than their preview properties (which only show "size")
if let Some(preview) = arg.get("preview") {
let preview_subtype = preview.get("subtype").and_then(|v| v.as_str());
if matches!(preview_subtype, Some("map" | "set" | "weakmap" | "weakset")) {
return arg
.get("description")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
}
let is_array = subtype == Some("array") || preview_subtype == Some("array");
if let Some(props) = preview.get("properties").and_then(|v| v.as_array()) {
let overflow = preview
.get("overflow")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let formatted_props: Vec<String> = props
.iter()
.filter_map(|p| {
let value_str = p.get("value").and_then(|v| v.as_str())?;
let prop_type = p.get("type").and_then(|v| v.as_str()).unwrap_or("");
let formatted_value = if prop_type == "string" {
format!("\"{}\"", value_str)
} else {
value_str.to_string()
};
if is_array {
Some(formatted_value)
} else {
let name = p.get("name").and_then(|v| v.as_str()).unwrap_or("?");
Some(format!("{}: {}", name, formatted_value))
}
})
.collect();
let inner = if overflow {
format!("{}, ...", formatted_props.join(", "))
} else {
formatted_props.join(", ")
};
return if is_array {
Some(format!("[{}]", inner))
} else {
Some(format!("{{{}}}", inner))
};
}
}
// Fallback to description
arg.get("description")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
}
/// Format an array of CDP RemoteObject args into a single space-separated string.
pub fn format_console_args(args: &[Value]) -> String {
args.iter()
.filter_map(format_console_arg)
.collect::<Vec<_>>()
.join(" ")
}
// ---------------------------------------------------------------------------
// Console and error tracking
// ---------------------------------------------------------------------------
#[derive(Debug, Clone)]
pub struct ConsoleEntry {
pub level: String,
pub text: String,
pub args: Vec<Value>,
}
#[derive(Debug, Clone)]
pub struct ErrorEntry {
pub text: String,
pub url: Option<String>,
pub line: Option<i64>,
pub column: Option<i64>,
}
pub struct EventTracker {
pub console_entries: Vec<ConsoleEntry>,
pub error_entries: Vec<ErrorEntry>,
pub max_entries: usize,
}
impl EventTracker {
pub fn new() -> Self {
Self {
console_entries: Vec::new(),
error_entries: Vec::new(),
max_entries: 1000,
}
}
pub fn add_console(&mut self, level: &str, text: &str, args: Vec<Value>) {
if self.console_entries.len() >= self.max_entries {
self.console_entries.remove(0);
}
self.console_entries.push(ConsoleEntry {
level: level.to_string(),
text: text.to_string(),
args,
});
}
pub fn add_error(
&mut self,
text: &str,
url: Option<&str>,
line: Option<i64>,
col: Option<i64>,
) {
if self.error_entries.len() >= self.max_entries {
self.error_entries.remove(0);
}
self.error_entries.push(ErrorEntry {
text: text.to_string(),
url: url.map(String::from),
line,
column: col,
});
}
pub fn clear_console(&mut self) {
self.console_entries.clear();
}
pub fn get_console_json(&self) -> Value {
let messages: Vec<Value> = self
.console_entries
.iter()
.map(|e| {
let mut msg = json!({ "type": e.level, "text": e.text });
if !e.args.is_empty() {
msg.as_object_mut()
.unwrap()
.insert("args".to_string(), Value::Array(e.args.clone()));
}
msg
})
.collect();
json!({ "messages": messages })
}
pub fn get_errors_json(&self) -> Value {
let entries: Vec<Value> = self
.error_entries
.iter()
.map(|e| {
json!({
"text": e.text,
"url": e.url,
"line": e.line,
"column": e.column,
})
})
.collect();
json!({ "errors": entries })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_domain_filter_exact() {
let filter = DomainFilter::new("example.com");
assert!(filter.is_allowed("example.com"));
assert!(!filter.is_allowed("other.com"));
}
#[test]
fn test_domain_filter_wildcard() {
let filter = DomainFilter::new("*.example.com");
assert!(filter.is_allowed("example.com"));
assert!(filter.is_allowed("api.example.com"));
assert!(filter.is_allowed("sub.api.example.com"));
assert!(!filter.is_allowed("other.com"));
}
#[test]
fn test_domain_filter_empty() {
let filter = DomainFilter::new("");
assert!(filter.is_allowed("anything.com"));
}
#[test]
fn test_domain_filter_multiple() {
let filter = DomainFilter::new("example.com, *.api.io");
assert!(filter.is_allowed("example.com"));
assert!(filter.is_allowed("api.io"));
assert!(filter.is_allowed("v1.api.io"));
assert!(!filter.is_allowed("other.com"));
}
#[test]
fn test_parse_domain_list() {
let domains = parse_domain_list("A.com, B.com , *.C.com");
assert_eq!(domains, vec!["a.com", "b.com", "*.c.com"]);
}
#[test]
fn test_event_tracker() {
let mut tracker = EventTracker::new();
tracker.add_console("log", "hello", vec![]);
tracker.add_error("oops", Some("test.js"), Some(1), Some(5));
assert_eq!(tracker.console_entries.len(), 1);
assert_eq!(tracker.error_entries.len(), 1);
}
#[test]
fn test_console_json_includes_args() {
let mut tracker = EventTracker::new();
let raw_args = vec![
json!({"type": "string", "value": "hello"}),
json!({"type": "number", "value": 42}),
];
tracker.add_console("log", "hello 42", raw_args);
let result = tracker.get_console_json();
let messages = result.get("messages").unwrap().as_array().unwrap();
assert_eq!(messages.len(), 1);
assert_eq!(messages[0].get("text").unwrap(), "hello 42");
let args = messages[0].get("args").unwrap().as_array().unwrap();
assert_eq!(args.len(), 2);
assert_eq!(args[0], json!({"type": "string", "value": "hello"}));
assert_eq!(args[1], json!({"type": "number", "value": 42}));
}
#[test]
fn test_console_json_empty_args_omits_field() {
let mut tracker = EventTracker::new();
tracker.add_console("log", "text only", vec![]);
let result = tracker.get_console_json();
let messages = result.get("messages").unwrap().as_array().unwrap();
assert!(messages[0].get("args").is_none());
}
// -- format_console_arg: primitives --
#[test]
fn test_format_arg_string() {
let arg = json!({"type": "string", "value": "hello"});
assert_eq!(format_console_arg(&arg), Some("hello".to_string()));
}
#[test]
fn test_format_arg_number() {
let arg = json!({"type": "number", "value": 42});
assert_eq!(format_console_arg(&arg), Some("42".to_string()));
}
#[test]
fn test_format_arg_null() {
let arg = json!({"type": "object", "subtype": "null", "value": null});
assert_eq!(format_console_arg(&arg), Some("null".to_string()));
}
#[test]
fn test_format_arg_undefined() {
let arg = json!({"type": "undefined"});
assert_eq!(format_console_arg(&arg), Some("undefined".to_string()));
}
// -- format_console_arg: objects with preview --
#[test]
fn test_format_arg_object_preview() {
let arg = json!({
"type": "object",
"preview": {
"properties": [
{"name": "userId", "type": "string", "value": "abc123"},
{"name": "count", "type": "number", "value": "42"}
],
"overflow": false
}
});
assert_eq!(
format_console_arg(&arg),
Some("{userId: \"abc123\", count: 42}".to_string())
);
}
#[test]
fn test_format_arg_object_preview_overflow() {
let arg = json!({
"type": "object",
"preview": {
"properties": [
{"name": "a", "type": "number", "value": "1"}
],
"overflow": true
}
});
assert_eq!(format_console_arg(&arg), Some("{a: 1, ...}".to_string()));
}
// -- format_console_arg: arrays with preview --
#[test]
fn test_format_arg_array_preview() {
let arg = json!({
"type": "object",
"subtype": "array",
"preview": {
"subtype": "array",
"properties": [
{"name": "0", "type": "number", "value": "1"},
{"name": "1", "type": "number", "value": "2"},
{"name": "2", "type": "number", "value": "3"}
],
"overflow": false
}
});
assert_eq!(format_console_arg(&arg), Some("[1, 2, 3]".to_string()));
}
// -- format_console_arg: map/set use description --
#[test]
fn test_format_arg_map_uses_description() {
let arg = json!({
"type": "object",
"subtype": "map",
"description": "Map(1)",
"preview": {
"subtype": "map",
"properties": [{"name": "size", "type": "number", "value": "1"}]
}
});
assert_eq!(format_console_arg(&arg), Some("Map(1)".to_string()));
}
// -- format_console_arg: fallback --
#[test]
fn test_format_arg_description_fallback() {
let arg = json!({"type": "object", "description": "RegExp"});
assert_eq!(format_console_arg(&arg), Some("RegExp".to_string()));
}
#[test]
fn test_format_arg_no_value_no_preview_no_description() {
let arg = json!({"type": "object"});
assert_eq!(format_console_arg(&arg), None);
}
// -- format_console_args --
#[test]
fn test_format_console_args_join() {
let args = vec![
json!({"type": "string", "value": "user"}),
json!({
"type": "object",
"preview": {
"properties": [{"name": "id", "type": "number", "value": "1"}],
"overflow": false
}
}),
];
assert_eq!(format_console_args(&args), "user {id: 1}");
}
#[test]
fn test_format_console_args_filters_none() {
// An arg that returns None should be skipped, not produce empty string
let args = vec![
json!({"type": "string", "value": "before"}),
json!({"type": "object"}), // no value, preview, or description → None
json!({"type": "string", "value": "after"}),
];
assert_eq!(format_console_args(&args), "before after");
}
}
+700
View File
@@ -0,0 +1,700 @@
//! Parity tests for the native daemon's command interface.
//!
//! These unit tests verify:
//! - All documented actions are handled (not returning "Not yet implemented")
//! - Response format consistency (success/error structure)
//! - Credential and state actions work without a browser
use serde_json::{json, Value};
use super::actions::{execute_command, DaemonState};
const ENCRYPTION_KEY_ENV: &str = "AGENT_BROWSER_ENCRYPTION_KEY";
struct TestKeyGuard {
_lock: std::sync::MutexGuard<'static, ()>,
original: Option<String>,
}
impl TestKeyGuard {
fn new() -> Self {
let lock = super::auth::AUTH_TEST_MUTEX
.lock()
.unwrap_or_else(|e| e.into_inner());
let original = std::env::var(ENCRYPTION_KEY_ENV).ok();
// SAFETY: AUTH_TEST_MUTEX serializes all test access so no concurrent mutation.
unsafe { std::env::set_var(ENCRYPTION_KEY_ENV, "a".repeat(64)) };
Self {
_lock: lock,
original,
}
}
}
impl Drop for TestKeyGuard {
fn drop(&mut self) {
// SAFETY: AUTH_TEST_MUTEX is held via _lock.
match &self.original {
Some(val) => unsafe { std::env::set_var(ENCRYPTION_KEY_ENV, val) },
None => unsafe { std::env::remove_var(ENCRYPTION_KEY_ENV) },
}
}
}
/// All documented action names that should be implemented.
const DOCUMENTED_ACTIONS: &[&str] = &[
"launch",
"navigate",
"url",
"title",
"content",
"evaluate",
"close",
"snapshot",
"screenshot",
"click",
"dblclick",
"fill",
"type",
"press",
"hover",
"scroll",
"select",
"check",
"uncheck",
"wait",
"gettext",
"getattribute",
"isvisible",
"isenabled",
"ischecked",
"back",
"forward",
"reload",
"cookies_get",
"cookies_set",
"cookies_clear",
"storage_get",
"storage_set",
"storage_clear",
"setcontent",
"headers",
"offline",
"console",
"errors",
"state_save",
"state_load",
"state_list",
"state_show",
"state_clear",
"state_clean",
"state_rename",
"trace_start",
"trace_stop",
"profiler_start",
"profiler_stop",
"recording_start",
"recording_stop",
"recording_restart",
"pdf",
"tab_list",
"tab_new",
"tab_switch",
"tab_close",
"viewport",
"user_agent",
"set_media",
"download",
"diff_snapshot",
"diff_url",
"credentials_set",
"credentials_get",
"credentials_delete",
"credentials_list",
"mouse",
"keyboard",
"focus",
"clear",
"selectall",
"scrollintoview",
"dispatch",
"highlight",
"tap",
"boundingbox",
"innertext",
"innerhtml",
"inputvalue",
"setvalue",
"count",
"styles",
"bringtofront",
"timezone",
"locale",
"geolocation",
"permissions",
"dialog",
"upload",
"addscript",
"addinitscript",
"addstyle",
"clipboard",
"wheel",
"device",
"screencast_start",
"screencast_stop",
"waitforurl",
"waitforloadstate",
"waitforfunction",
"frame",
"mainframe",
"getbyrole",
"getbytext",
"getbylabel",
"getbyplaceholder",
"getbyalttext",
"getbytitle",
"getbytestid",
"nth",
"find",
"evalhandle",
"drag",
"expose",
"pause",
"multiselect",
"responsebody",
"waitfordownload",
"window_new",
"diff_screenshot",
"video_start",
"video_stop",
"har_start",
"har_stop",
"route",
"unroute",
"requests",
"request_detail",
"credentials",
"auth_save",
"auth_login",
"auth_list",
"auth_delete",
"auth_show",
"confirm",
"deny",
"swipe",
"device_list",
"input_mouse",
"input_keyboard",
"input_touch",
"keydown",
"keyup",
"inserttext",
"mousemove",
"mousedown",
"mouseup",
];
fn minimal_command(action: &str, id: &str) -> Value {
let mut cmd = json!({ "action": action, "id": id });
let obj = cmd.as_object_mut().unwrap();
match action {
"navigate" | "diff_url" | "waitforurl" => {
obj.insert("url".to_string(), json!("https://example.com"));
}
"evaluate" | "expose" => {
obj.insert("script".to_string(), json!("1"));
}
"click" | "dblclick" | "fill" | "type" | "press" | "hover" | "scroll" | "select"
| "check" | "uncheck" | "gettext" | "getattribute" | "isvisible" | "isenabled"
| "ischecked" | "focus" | "clear" | "selectall" | "scrollintoview" | "dispatch"
| "highlight" | "tap" | "boundingbox" | "innertext" | "innerhtml" | "inputvalue"
| "setvalue" | "count" | "find" | "nth" | "getbytext" | "getbylabel"
| "getbyplaceholder" | "getbyalttext" | "getbytitle" | "getbytestid" => {
obj.insert("selector".to_string(), json!("body"));
}
"getbyrole" => {
obj.insert("role".to_string(), json!("button"));
obj.insert("selector".to_string(), json!("body"));
}
"setcontent" => {
obj.insert("html".to_string(), json!("<html></html>"));
}
"cookies_set" => {
obj.insert("name".to_string(), json!("test"));
obj.insert("value".to_string(), json!("val"));
}
"storage_get" | "storage_set" | "storage_clear" => {
obj.insert("origin".to_string(), json!("https://example.com"));
}
"state_save" | "state_load" | "state_show" | "state_clear" => {
obj.insert("path".to_string(), json!("test-parity-state.json"));
}
"state_rename" => {
obj.insert("path".to_string(), json!("test-parity-state.json"));
obj.insert("name".to_string(), json!("renamed"));
}
"state_clean" => {
obj.insert("days".to_string(), json!(7));
}
"credentials_set" => {
obj.insert("name".to_string(), json!("parity-test-cred"));
obj.insert("username".to_string(), json!("u"));
obj.insert("password".to_string(), json!("p"));
}
"auth_save" => {
obj.insert("name".to_string(), json!("parity-test-cred"));
obj.insert("url".to_string(), json!("https://example.com"));
obj.insert("username".to_string(), json!("u"));
obj.insert("password".to_string(), json!("p"));
}
"credentials_get" | "credentials_delete" | "auth_show" | "auth_delete" => {
obj.insert("name".to_string(), json!("parity-test-cred"));
}
"tab_switch" | "tab_close" => {
obj.insert("index".to_string(), json!(0));
}
"viewport" | "user_agent" | "set_media" | "timezone" | "locale" | "geolocation"
| "permissions" | "device" => {
obj.insert("value".to_string(), json!(null));
}
"headers" => {
obj.insert("headers".to_string(), json!({}));
}
"offline" => {
obj.insert("offline".to_string(), json!(false));
}
"wait" => {
obj.insert("timeout".to_string(), json!(100));
}
"waitforloadstate" => {
obj.insert("state".to_string(), json!("load"));
}
"waitforfunction" => {
obj.insert("script".to_string(), json!("() => true"));
}
"frame" => {
obj.insert("selector".to_string(), json!("iframe"));
}
"addscript" => {
obj.insert("content".to_string(), json!("console.log('test')"));
}
"addinitscript" => {
obj.insert("script".to_string(), json!("console.log('init')"));
}
"addstyle" => {
obj.insert("content".to_string(), json!("body { color: red }"));
}
"wheel" => {
obj.insert("deltaX".to_string(), json!(0));
obj.insert("deltaY".to_string(), json!(0));
}
"upload" => {
obj.insert("selector".to_string(), json!("input[type=file]"));
obj.insert("files".to_string(), json!([]));
}
"dialog" => {
obj.insert("accept".to_string(), json!(true));
}
"credentials" => {
obj.insert("username".to_string(), json!("u"));
obj.insert("password".to_string(), json!("p"));
}
"auth_login" => {
obj.insert("name".to_string(), json!("parity-test-cred"));
}
"route" => {
obj.insert("url".to_string(), json!("*"));
obj.insert("handler".to_string(), json!("continue"));
}
"diff_snapshot" | "diff_screenshot" => {
obj.insert("selector".to_string(), json!("body"));
}
"recording_start" | "recording_restart" => {
obj.insert("path".to_string(), json!("/tmp/parity-recording.webm"));
}
"video_start" => {
obj.insert("path".to_string(), json!("/tmp/parity-video.webm"));
}
"profiler_start" => {
obj.insert("path".to_string(), json!("/tmp/parity-profile"));
}
"trace_stop" | "har_stop" => {
obj.insert("path".to_string(), json!("/tmp/parity-trace"));
}
"download" => {
obj.insert("path".to_string(), json!("/tmp/parity-download"));
}
"multiselect" => {
obj.insert("selector".to_string(), json!("select"));
obj.insert("values".to_string(), json!([]));
}
"responsebody" => {
obj.insert("url".to_string(), json!("https://example.com"));
}
"waitfordownload" => {
obj.insert("path".to_string(), json!("/tmp/parity-download"));
}
"styles" => {
obj.insert("selector".to_string(), json!("body"));
obj.insert("names".to_string(), json!([]));
}
"evalhandle" => {
obj.insert("handle".to_string(), json!(""));
obj.insert("script".to_string(), json!("h => h"));
}
"drag" => {
obj.insert("source".to_string(), json!("body"));
obj.insert("target".to_string(), json!("body"));
}
"swipe" => {
obj.insert("selector".to_string(), json!("body"));
obj.insert("direction".to_string(), json!("left"));
}
"input_mouse" | "mousemove" | "mousedown" | "mouseup" => {
obj.insert("x".to_string(), json!(100));
obj.insert("y".to_string(), json!(100));
}
"input_keyboard" | "keydown" | "keyup" => {
obj.insert("key".to_string(), json!("a"));
}
"input_touch" => {
obj.insert("type".to_string(), json!("touchStart"));
obj.insert("touchPoints".to_string(), json!([]));
}
"inserttext" => {
obj.insert("text".to_string(), json!("test"));
}
_ => {}
}
cmd
}
// ---------------------------------------------------------------------------
// 1. Action dispatch coverage
// ---------------------------------------------------------------------------
#[tokio::test]
async fn test_all_documented_actions_are_handled() {
let mut state = DaemonState::new();
for (i, action) in DOCUMENTED_ACTIONS.iter().enumerate() {
let id = format!("parity-{}", i);
let cmd = minimal_command(action, &id);
let result = execute_command(&cmd, &mut state).await;
assert!(
result.get("id").is_some(),
"Action '{}': response missing 'id'",
action
);
let error = result.get("error").and_then(|v| v.as_str()).unwrap_or("");
assert!(
!error.contains("Not yet implemented"),
"Action '{}' returned 'Not yet implemented')",
action
);
}
}
// ---------------------------------------------------------------------------
// 2. Response format consistency
// ---------------------------------------------------------------------------
#[tokio::test]
async fn test_success_response_format() {
let mut state = DaemonState::new();
let cmd = json!({ "action": "state_list", "id": "fmt-1" });
let result = execute_command(&cmd, &mut state).await;
assert_eq!(result["success"], true);
assert!(result.get("id").is_some());
assert!(result.get("data").is_some());
assert!(result.get("error").is_none());
}
#[tokio::test]
async fn test_error_response_format() {
let mut state = DaemonState::new();
let cmd = json!({ "action": "nonexistent_action_xyz", "id": "fmt-2" });
let result = execute_command(&cmd, &mut state).await;
assert_eq!(result["success"], false);
assert!(result.get("id").is_some());
assert!(result.get("error").is_some());
}
// ---------------------------------------------------------------------------
// 3. Credential/state actions work without a browser
// ---------------------------------------------------------------------------
#[tokio::test]
async fn test_state_list_without_browser() {
let mut state = DaemonState::new();
let cmd = json!({ "action": "state_list", "id": "nb-1" });
let result = execute_command(&cmd, &mut state).await;
assert_eq!(result["success"], true);
assert!(result["data"]["files"].is_array());
}
#[tokio::test]
async fn test_credentials_list_without_browser() {
let mut state = DaemonState::new();
let cmd = json!({ "action": "credentials_list", "id": "nb-2" });
let result = execute_command(&cmd, &mut state).await;
assert_eq!(result["success"], true);
assert!(result["data"]["credentials"].is_array() || result["data"]["profiles"].is_array());
}
// ---------------------------------------------------------------------------
// 4. New feature parity tests
// ---------------------------------------------------------------------------
#[tokio::test]
async fn test_auth_profile_name_validation() {
use super::auth;
let _key_guard = TestKeyGuard::new();
let valid = auth::credentials_set("valid-name_123", "u", "p", None);
assert!(valid.is_ok());
let invalid = auth::credentials_set("invalid/name", "u", "p", None);
assert!(invalid.is_err());
let invalid2 = auth::credentials_set("", "u", "p", None);
assert!(invalid2.is_err());
let invalid3 = auth::credentials_set("has space", "u", "p", None);
assert!(invalid3.is_err());
// Cleanup
let _ = auth::credentials_delete("valid-name_123");
}
#[tokio::test]
async fn test_auth_save_and_show() {
use super::auth;
let _key_guard = TestKeyGuard::new();
let result = auth::auth_save(
"parity-roundtrip",
"https://example.com",
"user",
"pass",
Some("input#user"),
None,
None,
);
assert!(result.is_ok());
let show = auth::auth_show("parity-roundtrip");
assert!(show.is_ok());
let data = show.unwrap();
assert_eq!(data["profile"]["username"], "user");
assert_eq!(data["profile"]["usernameSelector"], "input#user");
let full = auth::credentials_get_full("parity-roundtrip");
assert!(full.is_ok());
assert_eq!(full.unwrap().password, "pass");
// Cleanup
let _ = auth::credentials_delete("parity-roundtrip");
}
#[tokio::test]
async fn test_har_start_stop_without_browser() {
let mut state = DaemonState::new();
// har_start requires a browser. Because execute_command auto-launches when
// no browser is present, the result depends on Chrome availability: success
// if Chrome is found (CI), failure if not. Both outcomes are valid.
let cmd = json!({ "action": "har_start", "id": "har-1" });
let result = execute_command(&cmd, &mut state).await;
let success = result["success"].as_bool().unwrap_or(false);
if success {
assert!(state.har_recording);
} else {
assert!(result["error"].as_str().is_some());
}
}
#[tokio::test]
async fn test_state_clean_action() {
let mut state = DaemonState::new();
let cmd = json!({ "action": "state_clean", "id": "clean-1", "days": 30 });
let result = execute_command(&cmd, &mut state).await;
assert_eq!(result["success"], true);
}
#[tokio::test]
async fn test_daemon_state_new_defaults() {
let state = DaemonState::new();
assert!(state.browser.is_none());
assert!(!state.har_recording);
assert!(state.har_entries.is_empty());
assert!(state.pending_confirmation.is_none());
assert!(!state.request_tracking);
assert!(state.tracked_requests.is_empty());
assert!(state.active_frame_id.is_none());
assert!(state.webdriver_backend.is_none());
assert!(state.stream_client.is_none());
}
#[tokio::test]
async fn test_tracked_request_struct() {
use super::actions::TrackedRequest;
let tr = TrackedRequest {
url: "https://example.com/api".to_string(),
method: "GET".to_string(),
headers: json!({"Accept": "text/html"}),
timestamp: 12345,
resource_type: "Document".to_string(),
request_id: "1.1".to_string(),
post_data: None,
status: Some(200),
response_headers: None,
mime_type: Some("text/html".to_string()),
};
let serialized = serde_json::to_value(&tr).unwrap();
assert_eq!(serialized["url"], "https://example.com/api");
assert_eq!(serialized["method"], "GET");
assert_eq!(serialized["resourceType"], "Document");
assert_eq!(serialized["timestamp"], 12345);
}
#[tokio::test]
async fn test_request_tracking_state() {
let mut state = DaemonState::new();
assert!(!state.request_tracking);
assert!(state.tracked_requests.is_empty());
state.tracked_requests.push(super::actions::TrackedRequest {
url: "https://example.com".to_string(),
method: "GET".to_string(),
headers: json!({}),
timestamp: 1,
resource_type: "Document".to_string(),
request_id: "1.1".to_string(),
post_data: None,
status: None,
response_headers: None,
mime_type: None,
});
state.tracked_requests.push(super::actions::TrackedRequest {
url: "https://other.com".to_string(),
method: "POST".to_string(),
headers: json!({}),
timestamp: 2,
resource_type: "XHR".to_string(),
request_id: "1.2".to_string(),
post_data: None,
status: None,
response_headers: None,
mime_type: None,
});
assert_eq!(state.tracked_requests.len(), 2);
// Filter
let filtered: Vec<_> = state
.tracked_requests
.iter()
.filter(|r| r.url.contains("example"))
.collect();
assert_eq!(filtered.len(), 1);
assert_eq!(filtered[0].url, "https://example.com");
// Clear
state.tracked_requests.clear();
assert!(state.tracked_requests.is_empty());
}
#[test]
fn test_matches_status_filter() {
use super::actions::matches_status_filter;
// Exact match
assert!(matches_status_filter(Some(200), "200"));
assert!(!matches_status_filter(Some(201), "200"));
// Class match (Nxx)
assert!(matches_status_filter(Some(200), "2xx"));
assert!(matches_status_filter(Some(299), "2xx"));
assert!(!matches_status_filter(Some(301), "2xx"));
assert!(matches_status_filter(Some(404), "4xx"));
// Range match
assert!(matches_status_filter(Some(400), "400-499"));
assert!(matches_status_filter(Some(499), "400-499"));
assert!(!matches_status_filter(Some(500), "400-499"));
// None status
assert!(!matches_status_filter(None, "200"));
assert!(!matches_status_filter(None, "2xx"));
}
#[tokio::test]
async fn test_addscript_and_addinitscript_separate_dispatch() {
let mut state = DaemonState::new();
// Both should be handled (not "Not yet implemented") even without a browser
let cmd1 = json!({ "action": "addscript", "id": "as-1", "content": "console.log(1)" });
let result1 = execute_command(&cmd1, &mut state).await;
let err1 = result1["error"].as_str().unwrap_or("");
assert!(
!err1.contains("Not yet implemented"),
"addscript should be handled"
);
let cmd2 = json!({ "action": "addinitscript", "id": "ais-1", "script": "console.log(2)" });
let result2 = execute_command(&cmd2, &mut state).await;
let err2 = result2["error"].as_str().unwrap_or("");
assert!(
!err2.contains("Not yet implemented"),
"addinitscript should be handled"
);
}
#[tokio::test]
async fn test_frame_context_management() {
let mut state = DaemonState::new();
assert!(state.active_frame_id.is_none());
// Set a frame ID and verify it persists
state.active_frame_id = Some("child-frame-123".to_string());
assert_eq!(state.active_frame_id.as_deref(), Some("child-frame-123"));
// Clearing the frame ID (what mainframe does)
state.active_frame_id = None;
assert!(state.active_frame_id.is_none());
}
#[tokio::test]
async fn test_addstyle_supports_content_and_url() {
let mut state = DaemonState::new();
// Both content-based and url-based addstyle should be recognized
let cmd1 = json!({ "action": "addstyle", "id": "style-1", "content": "body { color: red }" });
let result1 = execute_command(&cmd1, &mut state).await;
let err1 = result1["error"].as_str().unwrap_or("");
assert!(!err1.contains("Not yet implemented"));
let cmd2 =
json!({ "action": "addstyle", "id": "style-2", "url": "https://example.com/style.css" });
let result2 = execute_command(&cmd2, &mut state).await;
let err2 = result2["error"].as_str().unwrap_or("");
assert!(!err2.contains("Not yet implemented"));
}
#[tokio::test]
async fn test_domain_filter_sanitize() {
use super::network::DomainFilter;
let filter = DomainFilter::new("example.com");
assert!(filter.is_allowed("example.com"));
assert!(!filter.is_allowed("evil.com"));
filter.check_url("https://example.com/path").unwrap();
assert!(filter.check_url("https://evil.com").is_err());
}
#[tokio::test]
async fn test_state_find_auto_returns_none_for_nonexistent() {
use super::state;
let result = state::find_auto_state_file("nonexistent-session-xyz");
assert!(result.is_none());
}
+217
View File
@@ -0,0 +1,217 @@
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::env;
use std::fs;
use std::path::PathBuf;
/// Result of a policy check for an action.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PolicyResult {
/// Action is allowed.
Allow,
/// Action is blocked with the given reason.
Deny(String),
/// Action requires confirmation before proceeding.
RequiresConfirmation,
}
/// Policy configuration loaded from a JSON file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionPolicy {
#[serde(skip)]
path: PathBuf,
#[serde(default)]
default: Option<String>,
#[serde(default)]
allow: Option<Vec<String>>,
#[serde(default)]
deny: Option<Vec<String>>,
#[serde(default)]
confirm: Option<Vec<String>>,
}
/// Confirmation categories parsed from AGENT_BROWSER_CONFIRM_ACTIONS.
#[derive(Debug, Clone)]
pub struct ConfirmActions {
pub categories: HashSet<String>,
}
impl ConfirmActions {
pub fn from_env() -> Option<Self> {
let val = env::var("AGENT_BROWSER_CONFIRM_ACTIONS").ok()?;
if val.is_empty() {
return None;
}
let categories: HashSet<String> = val
.split(',')
.map(|s| s.trim().to_lowercase())
.filter(|s| !s.is_empty())
.collect();
if categories.is_empty() {
None
} else {
Some(Self { categories })
}
}
pub fn requires_confirmation(&self, action: &str) -> bool {
self.categories.contains(action)
}
}
impl ActionPolicy {
/// Load policy from a JSON file at the given path.
pub fn load(path: &str) -> Result<Self, String> {
let path_buf = PathBuf::from(path);
let contents = fs::read_to_string(&path_buf)
.map_err(|e| format!("Failed to read policy file: {}", e))?;
let mut policy: ActionPolicy =
serde_json::from_str(&contents).map_err(|e| format!("Invalid policy JSON: {}", e))?;
policy.path = path_buf;
Ok(policy)
}
/// Load policy if AGENT_BROWSER_ACTION_POLICY env var is set.
/// Falls back to AGENT_BROWSER_POLICY for backwards compatibility.
pub fn load_if_exists() -> Option<Self> {
let path = env::var("AGENT_BROWSER_ACTION_POLICY")
.or_else(|_| env::var("AGENT_BROWSER_POLICY"))
.ok()?;
Self::load(&path).ok()
}
/// Check whether an action is allowed, denied, or requires confirmation.
pub fn check(&self, action: &str) -> PolicyResult {
if let Some(deny) = &self.deny {
if deny.iter().any(|a| a == action) {
return PolicyResult::Deny(format!("Action '{}' is denied by policy", action));
}
}
if let Some(confirm) = &self.confirm {
if confirm.iter().any(|a| a == action) {
return PolicyResult::RequiresConfirmation;
}
}
if let Some(allow) = &self.allow {
if !allow.is_empty() && !allow.iter().any(|a| a == action) {
let is_default_deny = self
.default
.as_deref()
.map(|d| d.eq_ignore_ascii_case("deny"))
.unwrap_or(true);
if is_default_deny {
return PolicyResult::Deny(format!(
"Action '{}' is not in the allow list",
action
));
}
}
} else if let Some(ref default) = self.default {
if default.eq_ignore_ascii_case("deny") {
return PolicyResult::Deny(format!(
"Action '{}' denied: default policy is deny",
action
));
}
}
PolicyResult::Allow
}
/// Reload policy from the file. Re-reads the JSON and updates the policy.
pub fn reload(&mut self) -> Result<(), String> {
let contents = fs::read_to_string(&self.path)
.map_err(|e| format!("Failed to read policy file: {}", e))?;
let mut policy: ActionPolicy =
serde_json::from_str(&contents).map_err(|e| format!("Invalid policy JSON: {}", e))?;
policy.path = self.path.clone();
*self = policy;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::EnvGuard;
#[test]
fn test_policy_allow_whitelist() {
let json = r#"{"allow": ["click", "type"], "deny": [], "confirm": []}"#;
let policy: ActionPolicy = serde_json::from_str(json).unwrap();
assert_eq!(policy.check("click"), PolicyResult::Allow);
assert_eq!(policy.check("type"), PolicyResult::Allow);
assert!(matches!(policy.check("navigate"), PolicyResult::Deny(_)));
}
#[test]
fn test_policy_deny() {
let json = r#"{"allow": [], "deny": ["delete"], "confirm": []}"#;
let policy: ActionPolicy = serde_json::from_str(json).unwrap();
assert!(matches!(policy.check("delete"), PolicyResult::Deny(_)));
}
#[test]
fn test_policy_confirm() {
let json = r#"{"allow": [], "deny": [], "confirm": ["submit"]}"#;
let policy: ActionPolicy = serde_json::from_str(json).unwrap();
assert_eq!(policy.check("submit"), PolicyResult::RequiresConfirmation);
}
#[test]
fn test_policy_deny_takes_precedence() {
let json = r#"{"allow": ["danger"], "deny": ["danger"], "confirm": []}"#;
let policy: ActionPolicy = serde_json::from_str(json).unwrap();
assert!(matches!(policy.check("danger"), PolicyResult::Deny(_)));
}
#[test]
fn test_policy_confirm_takes_precedence_over_allow() {
let json = r#"{"allow": ["submit"], "deny": [], "confirm": ["submit"]}"#;
let policy: ActionPolicy = serde_json::from_str(json).unwrap();
assert_eq!(policy.check("submit"), PolicyResult::RequiresConfirmation);
}
#[test]
fn test_policy_empty_allow_allows_all() {
let json = r#"{"allow": [], "deny": [], "confirm": []}"#;
let policy: ActionPolicy = serde_json::from_str(json).unwrap();
assert_eq!(policy.check("anything"), PolicyResult::Allow);
}
#[test]
fn test_policy_missing_allow_allows_all() {
let json = r#"{"deny": []}"#;
let policy: ActionPolicy = serde_json::from_str(json).unwrap();
assert_eq!(policy.check("anything"), PolicyResult::Allow);
}
#[test]
fn test_policy_default_allow() {
let json = r#"{"default": "allow", "deny": ["navigate"]}"#;
let policy: ActionPolicy = serde_json::from_str(json).unwrap();
assert_eq!(policy.check("click"), PolicyResult::Allow);
assert!(matches!(policy.check("navigate"), PolicyResult::Deny(_)));
}
#[test]
fn test_policy_default_deny() {
let json = r#"{"default": "deny", "allow": ["click"]}"#;
let policy: ActionPolicy = serde_json::from_str(json).unwrap();
assert_eq!(policy.check("click"), PolicyResult::Allow);
assert!(matches!(policy.check("navigate"), PolicyResult::Deny(_)));
}
#[test]
fn test_confirm_actions_from_env() {
let _guard = EnvGuard::new(&["AGENT_BROWSER_CONFIRM_ACTIONS"]);
_guard.set("AGENT_BROWSER_CONFIRM_ACTIONS", "navigate,click,fill");
let ca = ConfirmActions::from_env().unwrap();
assert!(ca.requires_confirmation("navigate"));
assert!(ca.requires_confirmation("click"));
assert!(ca.requires_confirmation("fill"));
assert!(!ca.requires_confirmation("screenshot"));
}
}
+816
View File
@@ -0,0 +1,816 @@
//! Browser provider connections for remote CDP sessions.
//!
//! Supports AgentCore, Browserbase, Browserless, Browser Use, and Kernel providers.
//! Each provider returns a CDP WebSocket URL for connecting via BrowserManager.
use serde_json::{json, Value};
use std::env;
/// Provider session info for cleanup on failure.
#[derive(Debug)]
pub struct ProviderSession {
pub provider: String,
pub session_id: String,
}
#[derive(Debug)]
pub struct ProviderConnection {
pub ws_url: String,
pub session: Option<ProviderSession>,
/// If true, the WebSocket IS the page session (no Target.* commands).
pub direct_page: bool,
}
/// Connects to the specified browser provider and returns a CDP WebSocket URL
/// along with session info for cleanup on failure.
pub async fn connect_provider(provider_name: &str) -> Result<ProviderConnection, String> {
match provider_name.to_lowercase().as_str() {
"browserbase" => {
let (url, session) = connect_browserbase().await?;
Ok(ProviderConnection {
ws_url: url,
session,
direct_page: false,
})
}
"browserless" => {
let (url, session) = connect_browserless().await?;
Ok(ProviderConnection {
ws_url: url,
session,
direct_page: false,
})
}
"browser-use" | "browseruse" => {
let (url, session) = connect_browser_use().await?;
Ok(ProviderConnection {
ws_url: url,
session,
direct_page: false,
})
}
"kernel" => {
let (url, session) = connect_kernel().await?;
Ok(ProviderConnection {
ws_url: url,
session,
direct_page: false,
})
}
"agentcore" => {
let (url, session) = connect_agentcore().await?;
Ok(ProviderConnection {
ws_url: url,
session,
direct_page: false,
})
}
_ => Err(format!(
"Unknown provider '{}'. Supported: browserbase, browserless, browser-use, kernel, agentcore",
provider_name
)),
}
}
/// Close a provider session (call on CDP connect failure).
pub async fn close_provider_session(session: &ProviderSession) {
let client = reqwest::Client::new();
match session.provider.as_str() {
"browserbase" => {
if let Ok(api_key) = env::var("BROWSERBASE_API_KEY") {
let _ = client
.post(format!(
"https://api.browserbase.com/v1/sessions/{}",
session.session_id
))
.header("Content-Type", "application/json")
.header("X-BB-API-Key", &api_key)
.json(&serde_json::json!({ "status": "REQUEST_RELEASE" }))
.send()
.await;
}
}
"browser-use" => {
if let Ok(api_key) = env::var("BROWSER_USE_API_KEY") {
let _ = client
.patch(format!(
"https://api.browser-use.com/api/v2/browsers/{}",
session.session_id
))
.header("X-Browser-Use-API-Key", &api_key)
.header("Content-Type", "application/json")
.json(&json!({ "action": "stop" }))
.send()
.await;
}
}
"browserless" => {
// session_id holds the stop URL for browserless
let _ = client.delete(&session.session_id).send().await;
}
"kernel" => {
if let Ok(api_key) = env::var("KERNEL_API_KEY") {
let endpoint = env::var("KERNEL_ENDPOINT")
.unwrap_or_else(|_| "https://api.onkernel.com".to_string());
let _ = client
.delete(format!(
"{}/browsers/{}",
endpoint.trim_end_matches('/'),
session.session_id
))
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await;
}
}
"agentcore" => {
// AgentCore session cleanup is handled via signed DELETE request
let _ = close_agentcore_session(&session.session_id).await;
}
_ => {}
}
}
async fn connect_browserbase() -> Result<(String, Option<ProviderSession>), String> {
let api_key = env::var("BROWSERBASE_API_KEY")
.map_err(|_| "BROWSERBASE_API_KEY environment variable is not set")?;
let client = reqwest::Client::new();
let response = client
.post("https://api.browserbase.com/v1/sessions")
.header("content-type", "application/json")
.header("x-bb-api-key", &api_key)
.body("{}")
.send()
.await
.map_err(|e| format!("Browserbase request failed: {}", e))?;
let status = response.status();
let body = response
.text()
.await
.map_err(|e| format!("Failed to read Browserbase response: {}", e))?;
if !status.is_success() {
return Err(format!(
"Browserbase API error ({}): {}",
status.as_u16(),
body
));
}
let json: Value =
serde_json::from_str(&body).map_err(|e| format!("Invalid Browserbase response: {}", e))?;
let session_id = json
.get("id")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let ws_url = json
.get("connectUrl")
.and_then(|v| v.as_str())
.map(String::from)
.ok_or_else(|| "Browserbase response missing connectUrl".to_string())?;
Ok((
ws_url,
Some(ProviderSession {
provider: "browserbase".to_string(),
session_id,
}),
))
}
async fn connect_browserless() -> Result<(String, Option<ProviderSession>), String> {
let api_key = env::var("BROWSERLESS_API_KEY")
.map_err(|_| "BROWSERLESS_API_KEY environment variable is not set")?;
let api_url = env::var("BROWSERLESS_API_URL")
.unwrap_or_else(|_| "https://production-sfo.browserless.io".to_string());
let browser_type =
env::var("BROWSERLESS_BROWSER_TYPE").unwrap_or_else(|_| "chromium".to_string());
let supported = ["chromium", "chrome"];
if !supported.contains(&browser_type.as_str()) {
return Err(format!(
"BROWSERLESS_BROWSER_TYPE \"{}\" is not supported. Only {} are allowed.",
browser_type,
supported.join(", ")
));
}
let ttl: u64 = env::var("BROWSERLESS_TTL")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(300000);
let stealth = env::var("BROWSERLESS_STEALTH")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(true);
let url = format!("{}/session", api_url.trim_end_matches('/'));
let client = reqwest::Client::new();
let response = client
.post(&url)
.query(&[("token", &api_key)])
.header("Content-Type", "application/json")
.json(&json!({
"ttl": ttl,
"stealth": stealth,
"browser": browser_type,
}))
.send()
.await
.map_err(|e| format!("Browserless request failed: {}", e))?;
let status = response.status();
let body = response
.text()
.await
.map_err(|e| format!("Failed to read Browserless response: {}", e))?;
if !status.is_success() {
return Err(format!(
"Browserless API error ({}): {}",
status.as_u16(),
body
));
}
let json: Value =
serde_json::from_str(&body).map_err(|e| format!("Invalid Browserless response: {}", e))?;
let connect_url = json
.get("connect")
.and_then(|v| v.as_str())
.map(String::from)
.ok_or_else(|| "Browserless response missing 'connect' URL".to_string())?;
let stop_url = json
.get("stop")
.and_then(|v| v.as_str())
.map(String::from)
.ok_or_else(|| "Browserless response missing 'stop' URL".to_string())?;
Ok((
connect_url,
Some(ProviderSession {
provider: "browserless".to_string(),
// Store the stop URL as the session_id for cleanup
session_id: stop_url,
}),
))
}
async fn connect_browser_use() -> Result<(String, Option<ProviderSession>), String> {
let api_key = env::var("BROWSER_USE_API_KEY")
.map_err(|_| "BROWSER_USE_API_KEY environment variable is not set")?;
let ws_url = format!("wss://connect.browser-use.com?apiKey={}", api_key);
Ok((ws_url, None))
}
async fn connect_kernel() -> Result<(String, Option<ProviderSession>), String> {
let api_key = env::var("KERNEL_API_KEY").ok();
let endpoint =
env::var("KERNEL_ENDPOINT").unwrap_or_else(|_| "https://api.onkernel.com".to_string());
let url = format!("{}/browsers", endpoint.trim_end_matches('/'));
let headless = env::var("KERNEL_HEADLESS")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(true);
let stealth = env::var("KERNEL_STEALTH")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false);
let timeout_seconds = env::var("KERNEL_TIMEOUT_SECONDS")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(300);
let mut body = json!({
"headless": headless,
"stealth": stealth,
"timeout_seconds": timeout_seconds,
});
if let Ok(profile) = env::var("KERNEL_PROFILE_NAME") {
if !profile.is_empty() {
body.as_object_mut()
.unwrap()
.insert("profile".to_string(), json!(profile));
}
}
let client = reqwest::Client::new();
let mut request = client.post(&url).header("Content-Type", "application/json");
if let Some(ref key) = api_key {
request = request.header("Authorization", format!("Bearer {}", key));
}
let response = request
.json(&body)
.send()
.await
.map_err(|e| format!("Kernel request failed: {}", e))?;
let status = response.status();
let resp_body = response
.text()
.await
.map_err(|e| format!("Failed to read Kernel response: {}", e))?;
if !status.is_success() {
return Err(format!(
"Kernel API error ({}): {}",
status.as_u16(),
resp_body
));
}
let json: Value =
serde_json::from_str(&resp_body).map_err(|e| format!("Invalid Kernel response: {}", e))?;
let session_id = json
.get("session_id")
.or_else(|| json.get("id"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let ws_url = json
.get("cdp_ws_url")
.or_else(|| json.get("connectUrl"))
.or_else(|| json.get("connect_url"))
.or_else(|| json.get("cdpUrl"))
.or_else(|| json.get("cdp_url"))
.and_then(|v| v.as_str())
.map(String::from)
.ok_or_else(|| {
"Kernel response missing cdp_ws_url, connectUrl, connect_url, cdpUrl, or cdp_url"
.to_string()
})?;
Ok((
ws_url,
Some(ProviderSession {
provider: "kernel".to_string(),
session_id,
}),
))
}
// ============================================================================
// AgentCore Provider (AWS Bedrock AgentCore Browser)
// ============================================================================
mod agentcore {
use super::*;
/// AgentCore-specific session info for Live View URL
pub struct AgentCoreSessionInfo {
pub session_id: String,
pub browser_identifier: String,
pub region: String,
pub live_view_url: String,
}
thread_local! {
static AGENTCORE_INFO: std::cell::RefCell<Option<AgentCoreSessionInfo>> = const { std::cell::RefCell::new(None) };
static AGENTCORE_WS_HEADERS: std::cell::RefCell<Option<Vec<(String, String)>>> = const { std::cell::RefCell::new(None) };
}
pub fn set_agentcore_info(info: AgentCoreSessionInfo) {
AGENTCORE_INFO.with(|cell| *cell.borrow_mut() = Some(info));
}
pub fn get_agentcore_info() -> Option<AgentCoreSessionInfo> {
AGENTCORE_INFO.with(|cell| {
cell.borrow().as_ref().map(|i| AgentCoreSessionInfo {
session_id: i.session_id.clone(),
browser_identifier: i.browser_identifier.clone(),
region: i.region.clone(),
live_view_url: i.live_view_url.clone(),
})
})
}
pub fn set_agentcore_ws_headers(headers: Vec<(String, String)>) {
AGENTCORE_WS_HEADERS.with(|cell| *cell.borrow_mut() = Some(headers));
}
pub fn take_agentcore_ws_headers() -> Option<Vec<(String, String)>> {
AGENTCORE_WS_HEADERS.with(|cell| cell.borrow_mut().take())
}
pub async fn connect() -> Result<(String, Option<ProviderSession>), String> {
let region = env::var("AGENTCORE_REGION")
.or_else(|_| env::var("AWS_REGION"))
.or_else(|_| env::var("AWS_DEFAULT_REGION"))
.unwrap_or_else(|_| "us-east-1".to_string());
let browser_id =
env::var("AGENTCORE_BROWSER_ID").unwrap_or_else(|_| "aws.browser.v1".to_string());
let timeout_secs: u64 = env::var("AGENTCORE_SESSION_TIMEOUT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3600);
let host = format!("bedrock-agentcore.{}.amazonaws.com", region);
let path = format!(
"/browsers/{}/sessions/start",
urlencoding::encode(&browser_id)
);
let url = format!("https://{}{}", host, path);
// Generate a unique session name
let session_name = format!("agent-browser-{}", &uuid::Uuid::new_v4().to_string()[..8]);
let mut body_json = json!({
"name": session_name,
"sessionTimeoutSeconds": timeout_secs
});
if let Ok(profile_id) = env::var("AGENTCORE_PROFILE_ID") {
if !profile_id.is_empty() {
body_json.as_object_mut().unwrap().insert(
"profileConfiguration".to_string(),
json!({ "profileIdentifier": profile_id }),
);
}
}
let body = serde_json::to_string(&body_json)
.map_err(|e| format!("Failed to serialize request body: {}", e))?;
let signed_headers = sign_request("PUT", &url, &region, Some(&body)).await?;
let client = reqwest::Client::new();
let mut req = client.put(&url).body(body.clone());
for (key, value) in &signed_headers {
req = req.header(key.as_str(), value.as_str());
}
let response = req
.send()
.await
.map_err(|e| format!("AgentCore request failed: {}", e))?;
let status = response.status();
let resp_body = response
.text()
.await
.map_err(|e| format!("Failed to read AgentCore response: {}", e))?;
if !status.is_success() {
return Err(format!(
"AgentCore API error ({}): {}",
status.as_u16(),
resp_body
));
}
let json: Value = serde_json::from_str(&resp_body)
.map_err(|e| format!("Invalid AgentCore response: {}", e))?;
let session_id = json
.get("sessionId")
.and_then(|v| v.as_str())
.ok_or_else(|| "AgentCore response missing sessionId".to_string())?
.to_string();
let browser_identifier = json
.get("browserIdentifier")
.and_then(|v| v.as_str())
.unwrap_or(&browser_id)
.to_string();
let live_view_url = format!(
"https://{}.console.aws.amazon.com/bedrock-agentcore/browser/{}/session/{}#",
region, browser_identifier, session_id
);
set_agentcore_info(AgentCoreSessionInfo {
session_id: session_id.clone(),
browser_identifier: browser_identifier.clone(),
region: region.clone(),
live_view_url: live_view_url.clone(),
});
eprintln!("Session: {}", session_id);
eprintln!("Live View: {}", live_view_url);
let ws_path = format!(
"/browser-streams/{}/sessions/{}/automation",
browser_identifier, session_id
);
let ws_url = format!("wss://{}{}", host, ws_path);
let ws_headers = sign_request(
"GET",
&format!("https://{}{}", host, ws_path),
&region,
None,
)
.await?;
set_agentcore_ws_headers(ws_headers);
Ok((
ws_url,
Some(ProviderSession {
provider: "agentcore".to_string(),
session_id,
}),
))
}
/// Get AWS credentials from environment variables or AWS CLI
fn get_aws_credentials() -> Result<(String, String, Option<String>), String> {
// First try environment variables
if let (Ok(access_key), Ok(secret_key)) = (
env::var("AWS_ACCESS_KEY_ID"),
env::var("AWS_SECRET_ACCESS_KEY"),
) {
return Ok((access_key, secret_key, env::var("AWS_SESSION_TOKEN").ok()));
}
// Fall back to AWS CLI
let mut cmd = std::process::Command::new("aws");
cmd.args(["configure", "export-credentials", "--format", "env"]);
// Honor AWS_PROFILE
if let Ok(profile) = env::var("AWS_PROFILE") {
cmd.args(["--profile", &profile]);
}
let output = cmd.output()
.map_err(|e| format!("Failed to run aws CLI: {}. Install AWS CLI or set AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!(
"AWS CLI failed: {}. Run 'aws sso login' or set credentials",
stderr.trim()
));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let mut access_key = None;
let mut secret_key = None;
let mut session_token = None;
for line in stdout.lines() {
if let Some(val) = line.strip_prefix("export AWS_ACCESS_KEY_ID=") {
access_key = Some(val.to_string());
} else if let Some(val) = line.strip_prefix("export AWS_SECRET_ACCESS_KEY=") {
secret_key = Some(val.to_string());
} else if let Some(val) = line.strip_prefix("export AWS_SESSION_TOKEN=") {
session_token = Some(val.to_string());
}
}
match (access_key, secret_key) {
(Some(ak), Some(sk)) => Ok((ak, sk, session_token)),
_ => Err("Failed to parse credentials from AWS CLI output".to_string()),
}
}
async fn sign_request(
method: &str,
url: &str,
region: &str,
body: Option<&str>,
) -> Result<Vec<(String, String)>, String> {
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
// Get credentials from environment or AWS CLI
let (access_key, secret_key, session_token) = get_aws_credentials()?;
let parsed_url = url::Url::parse(url).map_err(|e| format!("Invalid URL: {}", e))?;
let host = parsed_url.host_str().unwrap_or("");
// Get current time
let now = chrono::Utc::now();
let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
let date_stamp = now.format("%Y%m%d").to_string();
// Create canonical request
let payload_hash = if let Some(b) = body {
let mut hasher = Sha256::new();
hasher.update(b.as_bytes());
hex::encode(hasher.finalize())
} else {
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".to_string()
// empty string hash
};
let canonical_uri = parsed_url.path();
let canonical_querystring = parsed_url.query().unwrap_or("");
let mut signed_headers = "content-type;host;x-amz-date".to_string();
let mut canonical_headers = format!(
"content-type:application/json\nhost:{}\nx-amz-date:{}\n",
host, amz_date
);
if let Some(ref token) = session_token {
signed_headers = "content-type;host;x-amz-date;x-amz-security-token".to_string();
canonical_headers = format!(
"content-type:application/json\nhost:{}\nx-amz-date:{}\nx-amz-security-token:{}\n",
host, amz_date, token
);
}
let canonical_request = format!(
"{}\n{}\n{}\n{}\n{}\n{}",
method,
canonical_uri,
canonical_querystring,
canonical_headers,
signed_headers,
payload_hash
);
// Create string to sign
let algorithm = "AWS4-HMAC-SHA256";
let credential_scope = format!("{}/{}/bedrock-agentcore/aws4_request", date_stamp, region);
let mut hasher = Sha256::new();
hasher.update(canonical_request.as_bytes());
let canonical_request_hash = hex::encode(hasher.finalize());
let string_to_sign = format!(
"{}\n{}\n{}\n{}",
algorithm, amz_date, credential_scope, canonical_request_hash
);
// Calculate signature
type HmacSha256 = Hmac<Sha256>;
let k_date = HmacSha256::new_from_slice(format!("AWS4{}", secret_key).as_bytes())
.unwrap()
.chain_update(date_stamp.as_bytes())
.finalize()
.into_bytes();
let k_region = HmacSha256::new_from_slice(&k_date)
.unwrap()
.chain_update(region.as_bytes())
.finalize()
.into_bytes();
let k_service = HmacSha256::new_from_slice(&k_region)
.unwrap()
.chain_update(b"bedrock-agentcore")
.finalize()
.into_bytes();
let k_signing = HmacSha256::new_from_slice(&k_service)
.unwrap()
.chain_update(b"aws4_request")
.finalize()
.into_bytes();
let signature = hex::encode(
HmacSha256::new_from_slice(&k_signing)
.unwrap()
.chain_update(string_to_sign.as_bytes())
.finalize()
.into_bytes(),
);
// Build authorization header
let authorization = format!(
"{} Credential={}/{}, SignedHeaders={}, Signature={}",
algorithm, access_key, credential_scope, signed_headers, signature
);
let mut headers = vec![
("host".to_string(), host.to_string()),
("content-type".to_string(), "application/json".to_string()),
("x-amz-date".to_string(), amz_date),
("authorization".to_string(), authorization),
];
if let Some(token) = session_token {
headers.push(("x-amz-security-token".to_string(), token));
}
Ok(headers)
}
pub async fn close_session(session_id: &str) -> Result<(), String> {
let info = get_agentcore_info();
let (region, browser_id) = match &info {
Some(i) => (i.region.clone(), i.browser_identifier.clone()),
None => {
let region = env::var("AGENTCORE_REGION")
.or_else(|_| env::var("AWS_REGION"))
.or_else(|_| env::var("AWS_DEFAULT_REGION"))
.unwrap_or_else(|_| "us-east-1".to_string());
let browser_id = env::var("AGENTCORE_BROWSER_ID")
.unwrap_or_else(|_| "aws.browser.v1".to_string());
(region, browser_id)
}
};
let host = format!("bedrock-agentcore.{}.amazonaws.com", region);
let path = format!(
"/browsers/{}/sessions/stop",
urlencoding::encode(&browser_id)
);
let url = format!("https://{}{}", host, path);
let body = serde_json::to_string(&json!({ "sessionId": session_id }))
.map_err(|e| format!("Failed to serialize close request: {}", e))?;
let signed_headers = sign_request("PUT", &url, &region, Some(&body)).await?;
let client = reqwest::Client::new();
let mut req = client.put(&url).body(body);
for (key, value) in &signed_headers {
req = req.header(key.as_str(), value.as_str());
}
let _ = req.send().await;
Ok(())
}
}
pub use agentcore::{get_agentcore_info, take_agentcore_ws_headers};
async fn connect_agentcore() -> Result<(String, Option<ProviderSession>), String> {
agentcore::connect().await
}
async fn close_agentcore_session(session_id: &str) -> Result<(), String> {
agentcore::close_session(session_id).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_connect_provider_unknown() {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(connect_provider("unknown-provider"));
assert!(result.is_err());
assert!(result.unwrap_err().contains("Unknown provider"));
}
#[test]
fn test_agentcore_env_defaults() {
// Test that default values are used when env vars not set
std::env::remove_var("AGENTCORE_REGION");
std::env::remove_var("AGENTCORE_BROWSER_ID");
std::env::remove_var("AGENTCORE_SESSION_TIMEOUT");
// These would be used in connect() - just verify they don't panic
let region = std::env::var("AGENTCORE_REGION")
.or_else(|_| std::env::var("AWS_REGION"))
.unwrap_or_else(|_| "us-east-1".to_string());
assert_eq!(region, "us-east-1");
let browser_id =
std::env::var("AGENTCORE_BROWSER_ID").unwrap_or_else(|_| "aws.browser.v1".to_string());
assert_eq!(browser_id, "aws.browser.v1");
}
#[test]
fn test_agentcore_session_info_storage() {
let info = agentcore::AgentCoreSessionInfo {
session_id: "test-session".to_string(),
browser_identifier: "aws.browser.v1".to_string(),
region: "us-east-1".to_string(),
live_view_url: "https://example.com".to_string(),
};
agentcore::set_agentcore_info(info);
let retrieved = get_agentcore_info();
assert!(retrieved.is_some());
let retrieved = retrieved.unwrap();
assert_eq!(retrieved.session_id, "test-session");
assert_eq!(retrieved.region, "us-east-1");
}
#[test]
fn test_agentcore_ws_headers_storage() {
let headers = vec![
(
"Authorization".to_string(),
"AWS4-HMAC-SHA256...".to_string(),
),
("X-Amz-Date".to_string(), "20260304T180000Z".to_string()),
];
agentcore::set_agentcore_ws_headers(headers);
let taken = take_agentcore_ws_headers();
assert!(taken.is_some());
assert_eq!(taken.unwrap().len(), 2);
// Should be None after take
let taken_again = take_agentcore_ws_headers();
assert!(taken_again.is_none());
}
}
File diff suppressed because one or more lines are too long
+31
View File
@@ -0,0 +1,31 @@
//! React/web introspection primitives.
//!
//! Scripts and handlers for the `react` subcommands (tree, inspect, renders,
//! suspense) plus the universal `vitals` verb and the generic `pushstate`
//! SPA-navigation action. These primitives are framework-agnostic: React-side
//! commands only require the `__REACT_DEVTOOLS_GLOBAL_HOOK__` to be installed,
//! and `vitals` / `pushstate` are pure web-standard APIs.
//!
//! The React DevTools `installHook.js` is vendored from the React DevTools
//! Chrome extension (MIT, facebook/react). It's registered via
//! `addScriptToEvaluateOnNewDocument` before any page JS runs when the user
//! passes `--enable react-devtools` at launch.
pub mod scripts;
mod renders;
mod suspense;
mod tree;
mod vitals;
pub use renders::{format_renders_report, RendersData};
pub use suspense::{format_suspense_report, Boundary};
pub use tree::{format_tree, TreeNode};
pub use vitals::{format_vitals_report, VitalsData};
/// React DevTools hook script (MIT, from facebook/react).
/// Registered via `addScriptToEvaluateOnNewDocument` to install
/// `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` before any page JS runs. React
/// detects the hook on boot and registers its renderers against it, which
/// enables every `react …` command.
pub const INSTALL_HOOK_JS: &str = include_str!("installHook.js");
+169
View File
@@ -0,0 +1,169 @@
//! React fiber render profiler report formatter.
//!
//! Default output is the
//! full agent-readable report (summary, FPS, component table, per-component
//! "change details (prev -> next)"). `--json` emits the raw structured data
//! instead.
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct RendersData {
pub elapsed: f64,
pub fps: FpsStats,
#[serde(rename = "totalRenders")]
pub total_renders: i64,
#[serde(rename = "totalMounts")]
pub total_mounts: i64,
#[serde(rename = "totalReRenders")]
pub total_re_renders: i64,
#[serde(rename = "totalComponents")]
pub total_components: i64,
pub components: Vec<Component>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct FpsStats {
pub avg: i64,
pub min: i64,
pub max: i64,
pub drops: i64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Component {
pub name: String,
pub count: i64,
pub mounts: i64,
#[serde(rename = "reRenders")]
pub re_renders: i64,
#[serde(rename = "instanceCount")]
pub instance_count: i64,
#[serde(rename = "totalTime")]
pub total_time: f64,
#[serde(rename = "selfTime")]
pub self_time: f64,
#[serde(rename = "domMutations")]
pub dom_mutations: i64,
pub changes: Vec<Change>,
#[serde(rename = "changeSummary")]
pub change_summary: std::collections::HashMap<String, i64>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Change {
#[serde(rename = "type")]
pub change_type: String,
pub name: Option<String>,
pub prev: Option<String>,
pub next: Option<String>,
}
pub fn format_renders_report(d: &RendersData) -> String {
if d.components.is_empty() {
return "(no renders captured)".to_string();
}
let mut lines: Vec<String> = Vec::new();
lines.push(format!("# Render Profile - {}s recording", d.elapsed));
lines.push(format!(
"# {} renders ({} mounts + {} re-renders) across {} components",
d.total_renders, d.total_mounts, d.total_re_renders, d.total_components
));
lines.push(format!(
"# FPS: avg {}, min {}, max {}, drops (<30fps): {}",
d.fps.avg, d.fps.min, d.fps.max, d.fps.drops
));
lines.push(String::new());
lines.push("## Components by total render time".to_string());
let top: Vec<&Component> = d.components.iter().take(50).collect();
let name_w = top.iter().map(|c| c.name.len()).max().unwrap_or(9).max(9);
lines.push(format!(
"| {:<name_w$} | Insts | Mounts | Re-renders | Total | Self | DOM | Top change reason |",
"Component",
name_w = name_w
));
lines.push(format!(
"| {:-<name_w$} | ----- | ------ | ---------- | -------- | -------- | ----- | -------------------------- |",
"",
name_w = name_w
));
for c in &top {
let total = if c.total_time > 0.0 {
format!("{}ms", c.total_time)
} else {
"-".to_string()
};
let self_time = if c.self_time > 0.0 {
format!("{}ms", c.self_time)
} else {
"-".to_string()
};
let dom = format!("{}/{}", c.dom_mutations, c.count);
let top_change = c
.change_summary
.iter()
.max_by_key(|(_, v)| *v)
.map(|(k, _)| k.as_str())
.unwrap_or("-");
lines.push(format!(
"| {:<name_w$} | {:>5} | {:>6} | {:>10} | {:>8} | {:>8} | {:>5} | {:<26} |",
c.name,
c.instance_count,
c.mounts,
c.re_renders,
total,
self_time,
dom,
top_change,
name_w = name_w
));
}
if d.components.len() > 50 {
lines.push(format!("... and {} more", d.components.len() - 50));
}
let detailed: Vec<&Component> = d
.components
.iter()
.filter(|c| {
c.changes
.iter()
.any(|ch| ch.change_type != "mount" && ch.change_type != "parent")
})
.take(15)
.collect();
if !detailed.is_empty() {
lines.push(String::new());
lines.push("## Change details (prev -> next)".to_string());
for c in &detailed {
lines.push(format!(" {}", c.name));
let mut seen = std::collections::HashSet::new();
for ch in &c.changes {
if ch.change_type == "mount" || ch.change_type == "parent" {
continue;
}
let name = ch.name.clone().unwrap_or_default();
let key = format!("{}:{}", ch.change_type, name);
if !seen.insert(key) {
continue;
}
let label = match ch.change_type.as_str() {
"props" => format!("props.{}", name),
"state" => format!("state ({})", name),
_ => format!("context ({})", name),
};
lines.push(format!(
" {}: {} -> {}",
label,
ch.prev.clone().unwrap_or_else(|| "?".into()),
ch.next.clone().unwrap_or_else(|| "?".into())
));
}
}
}
lines.join("\n")
}
+745
View File
@@ -0,0 +1,745 @@
//! Browser-side evaluation scripts for React/web introspection.
//!
//! These are JavaScript strings evaluated in the page context via
//! `Runtime.evaluate`. They assume the React DevTools hook is already
//! installed (via `--enable react-devtools`) except for `VITALS_INIT` and
//! `PUSHSTATE`, which only use standard Web APIs.
//!
//! Kept as raw strings rather than TS/JS files because the daemon is a single
//! Rust binary with no filesystem vendor step at runtime.
/// Build a no-argument async IIFE page-eval that returns the component tree as
/// JSON.
pub const TREE_SNAPSHOT: &str = r#"
(async () => {
const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
if (!hook) throw new Error("React DevTools hook not installed - relaunch with --enable react-devtools");
const ri = hook.rendererInterfaces && hook.rendererInterfaces.get && hook.rendererInterfaces.get(1);
if (!ri) throw new Error("No React renderer attached - the page has not booted React yet");
const batches = await new Promise((resolve) => {
const out = [];
const origEmit = hook.emit;
hook.emit = function (event, payload) {
if (event === "operations") out.push(Array.from(payload));
return origEmit.apply(hook, arguments);
};
ri.flushInitialOperations();
setTimeout(() => {
hook.emit = origEmit;
resolve(out);
}, 50);
});
const nodes = batches.flatMap((ops) => {
let i = 2;
const strings = [null];
const tableEnd = ++i + ops[i - 1];
while (i < tableEnd) {
const len = ops[i++];
strings.push(String.fromCodePoint(...ops.slice(i, i + len)));
i += len;
}
const out = [];
while (i < ops.length) {
const op = ops[i];
if (op === 1) {
const id = ops[i + 1];
const type = ops[i + 2];
i += 3;
if (type === 11) {
out.push({ id, type, name: null, key: null, parent: 0 });
i += 4;
} else {
out.push({
id,
type,
name: strings[ops[i + 2]] || null,
key: strings[ops[i + 3]] || null,
parent: ops[i],
});
i += 5;
}
} else {
i += skip(op, ops, i);
}
}
return out;
function skip(op, ops, i) {
if (op === 2) return 2 + ops[i + 1];
if (op === 3) return 3 + ops[i + 2];
if (op === 4) return 3;
if (op === 5) return 4;
if (op === 6) return 1;
if (op === 7) return 3;
if (op === 8) return 6 + rects(ops[i + 5]);
if (op === 9) return 2 + ops[i + 1];
if (op === 10) return 3 + ops[i + 2];
if (op === 11) return 3 + rects(ops[i + 2]);
if (op === 12) return suspenders(ops, i);
if (op === 13) return 2;
return 1;
}
function rects(n) {
return n === -1 ? 0 : n * 4;
}
function suspenders(ops, i) {
let j = i + 2;
for (let c = 0; c < ops[i + 1]; c++) j += 5 + ops[j + 4];
return j - i;
}
});
return JSON.stringify(nodes);
})()
"#;
/// Template for `inspect` — replace {{ID}} with the numeric fiber id.
pub const TREE_INSPECT: &str = r#"
(() => {
const id = {{ID}};
const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
const ri = hook && hook.rendererInterfaces && hook.rendererInterfaces.get && hook.rendererInterfaces.get(1);
if (!ri) throw new Error("No React renderer attached");
if (!ri.hasElementWithId(id)) throw new Error("element " + id + " not found (page reloaded?)");
const result = ri.inspectElement(1, id, null, true);
if (!result || result.type !== "full-data") {
throw new Error("inspect failed: " + (result && result.type));
}
const v = result.value;
const name = ri.getDisplayNameForElementID(id);
const lines = [name + " #" + id];
if (v.key != null) lines.push("key: " + JSON.stringify(v.key));
section("props", v.props);
section("hooks", v.hooks);
section("state", v.state);
section("context", v.context);
if (v.owners && v.owners.length) {
lines.push("rendered by: " + v.owners.map((o) => o.displayName).join(" > "));
}
const source = Array.isArray(v.source)
? [v.source[1], v.source[2], v.source[3]]
: null;
return JSON.stringify({ text: lines.join("\n"), source });
function section(label, payload) {
const data = (payload && payload.data) || payload;
if (data == null) return;
if (Array.isArray(data)) {
if (data.length === 0) return;
lines.push(label + ":");
for (const h of data) lines.push(" " + hookLine(h));
} else if (typeof data === "object") {
const entries = Object.entries(data);
if (entries.length === 0) return;
lines.push(label + ":");
for (const [k, val] of entries) lines.push(" " + k + ": " + preview(val));
}
}
function hookLine(h) {
const idx = h.id != null ? "[" + h.id + "] " : "";
const sub = h.subHooks && h.subHooks.length ? " (" + h.subHooks.length + " sub)" : "";
return idx + h.name + ": " + preview(h.value) + sub;
}
function preview(v) {
if (v == null) return String(v);
if (typeof v !== "object") return JSON.stringify(v);
if (v.type === "undefined") return "undefined";
if (v.preview_long) return v.preview_long;
if (v.preview_short) return v.preview_short;
if (Array.isArray(v)) return "[" + v.map(preview).join(", ") + "]";
const entries = Object.entries(v).map((e) => e[0] + ": " + preview(e[1]));
return "{" + entries.join(", ") + "}";
}
})()
"#;
/// Fiber profiler init script. Registered via `addScriptToEvaluateOnNewDocument`
/// so it survives navigations; also evaluated immediately on the current page
/// by `react renders start`.
pub const RENDERS_INIT: &str = r#"
(() => {
const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
if (!hook || window.__AB_RENDERS_ACTIVE__) return;
const MAX_COMPONENTS = 200;
const data = {};
const fps = { frames: [], last: 0, rafId: 0 };
window.__AB_RENDERS__ = data;
window.__AB_RENDERS_FPS__ = fps;
window.__AB_RENDERS_START__ = performance.now();
window.__AB_RENDERS_ACTIVE__ = true;
function fpsLoop(now) {
if (fps.last > 0) fps.frames.push(now - fps.last);
fps.last = now;
fps.rafId = requestAnimationFrame(fpsLoop);
}
fps.rafId = requestAnimationFrame(fpsLoop);
const origOnCommit = hook.onCommitFiberRoot;
window.__AB_RENDERS_ORIG_COMMIT__ = origOnCommit;
hook.onCommitFiberRoot = function (rendererID, root) {
try { walkFiber(root.current); } catch {}
if (typeof origOnCommit === "function") {
return origOnCommit.apply(hook, arguments);
}
};
function getName(fiber) {
if (!fiber.type || typeof fiber.type === "string") return null;
return fiber.type.displayName || fiber.type.name || null;
}
function brief(val) {
if (val === undefined) return "undefined";
if (val === null) return "null";
if (typeof val === "function") return "fn()";
if (typeof val === "string") return val.length > 60 ? '"' + val.slice(0, 57) + '..."' : '"' + val + '"';
if (typeof val === "number" || typeof val === "boolean") return String(val);
if (Array.isArray(val)) return "Array(" + val.length + ")";
if (typeof val === "object") {
try {
const keys = Object.keys(val);
return keys.length <= 3 ? "{" + keys.join(", ") + "}" : "{" + keys.slice(0, 3).join(", ") + ", ...}";
} catch { return "{...}"; }
}
return String(val).slice(0, 40);
}
function getChanges(fiber) {
const changes = [];
const alt = fiber.alternate;
if (!alt) { changes.push({ type: "mount" }); return changes; }
if (fiber.memoizedProps !== alt.memoizedProps) {
const curr = fiber.memoizedProps || {};
const prev = alt.memoizedProps || {};
const allKeys = new Set([...Object.keys(curr), ...Object.keys(prev)]);
for (const k of allKeys) {
if (k !== "children" && curr[k] !== prev[k]) {
changes.push({ type: "props", name: k, prev: brief(prev[k]), next: brief(curr[k]) });
}
}
}
if (fiber.memoizedState !== alt.memoizedState) {
let curr = fiber.memoizedState;
let prev = alt.memoizedState;
let hookIdx = 0;
while (curr || prev) {
if ((curr && curr.memoizedState) !== (prev && prev.memoizedState)) {
changes.push({
type: "state",
name: "hook #" + hookIdx,
prev: brief(prev && prev.memoizedState),
next: brief(curr && curr.memoizedState),
});
}
curr = curr && curr.next;
prev = prev && prev.next;
hookIdx++;
}
}
if (fiber.dependencies && fiber.dependencies.firstContext) {
let ctx = fiber.dependencies.firstContext;
let altCtx = alt.dependencies && alt.dependencies.firstContext;
while (ctx) {
if (!altCtx || ctx.memoizedValue !== (altCtx && altCtx.memoizedValue)) {
const ctxName =
(ctx.context && ctx.context.displayName) ||
(ctx.context && ctx.context.Provider && ctx.context.Provider.displayName) ||
"unknown";
changes.push({
type: "context",
name: ctxName,
prev: brief(altCtx && altCtx.memoizedValue),
next: brief(ctx.memoizedValue),
});
}
ctx = ctx.next;
altCtx = altCtx && altCtx.next;
}
}
if (changes.length === 0) {
let parent = fiber.return;
while (parent) {
const pName = getName(parent);
if (pName) {
const suffix = !parent.alternate ? " (mount)" : "";
changes.push({ type: "parent", name: pName + suffix });
break;
}
parent = parent.return;
}
if (changes.length === 0) changes.push({ type: "parent", name: "unknown" });
}
return changes;
}
function childrenTime(fiber) {
let t = 0;
let child = fiber.child;
while (child) {
if (typeof child.actualDuration === "number") t += child.actualDuration;
child = child.sibling;
}
return t;
}
function hasDomMutation(fiber) {
if (!fiber.alternate) return true;
let child = fiber.child;
while (child) {
if (typeof child.type === "string" && (child.flags & 6) > 0) return true;
child = child.sibling;
}
return false;
}
function walkFiber(fiber) {
if (!fiber) return;
const tag = fiber.tag;
if (tag === 0 || tag === 1 || tag === 2 || tag === 11 || tag === 15) {
const didRender =
fiber.alternate === null ||
fiber.flags > 0 ||
fiber.memoizedProps !== (fiber.alternate && fiber.alternate.memoizedProps) ||
fiber.memoizedState !== (fiber.alternate && fiber.alternate.memoizedState);
if (didRender) {
const name = getName(fiber);
if (name) {
if (!(name in data) && Object.keys(data).length >= MAX_COMPONENTS) {
// at cap - skip
} else {
if (!data[name]) {
data[name] = {
count: 0, mounts: 0, totalTime: 0, selfTime: 0,
domMutations: 0, changes: [], _instances: new Set(),
};
}
data[name].count++;
if (!fiber.alternate) data[name].mounts++;
if (!data[name]._instances.has(fiber)) {
data[name]._instances.add(fiber);
if (fiber.alternate) data[name]._instances.add(fiber.alternate);
}
if (typeof fiber.actualDuration === "number") {
data[name].totalTime += fiber.actualDuration;
data[name].selfTime += Math.max(0, fiber.actualDuration - childrenTime(fiber));
}
if (hasDomMutation(fiber)) data[name].domMutations++;
const ch = getChanges(fiber);
for (const c of ch) {
if (data[name].changes.length < 50) data[name].changes.push(c);
}
}
}
}
}
walkFiber(fiber.child);
walkFiber(fiber.sibling);
}
})()
"#;
/// Stop script for fiber profiler. Returns the collected profile as JSON.
pub const RENDERS_STOP: &str = r#"
(() => {
const active = window.__AB_RENDERS_ACTIVE__;
if (!active) throw new Error("renders recording not active - run `react renders start` first");
const data = window.__AB_RENDERS__;
const startTime = window.__AB_RENDERS_START__;
const elapsed = performance.now() - startTime;
const fpsData = window.__AB_RENDERS_FPS__;
let fpsStats = { avg: 0, min: 0, max: 0, drops: 0 };
if (fpsData) {
cancelAnimationFrame(fpsData.rafId);
if (fpsData.frames.length > 0) {
const fpsSamples = fpsData.frames.map((dt) => (dt > 0 ? 1000 / dt : 0));
const sum = fpsSamples.reduce((a, b) => a + b, 0);
fpsStats = {
avg: Math.round(sum / fpsSamples.length),
min: Math.round(Math.min(...fpsSamples)),
max: Math.round(Math.max(...fpsSamples)),
drops: fpsSamples.filter((f) => f < 30).length,
};
}
}
const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
const orig = window.__AB_RENDERS_ORIG_COMMIT__;
if (hook) hook.onCommitFiberRoot = orig || undefined;
delete window.__AB_RENDERS__;
delete window.__AB_RENDERS_START__;
delete window.__AB_RENDERS_ACTIVE__;
delete window.__AB_RENDERS_ORIG_COMMIT__;
delete window.__AB_RENDERS_FPS__;
if (!data) {
return JSON.stringify({
elapsed: 0, fps: fpsStats, totalRenders: 0, totalMounts: 0,
totalReRenders: 0, totalComponents: 0, components: [],
});
}
const round = (n) => Math.round(n * 100) / 100;
const components = Object.entries(data)
.map(([name, entry]) => {
const summary = {};
for (const c of entry.changes) {
const key = c.type === "props" ? "props." + c.name
: c.type === "state" ? "state (" + c.name + ")"
: c.type === "context" ? "context (" + c.name + ")"
: c.type === "parent" ? "parent (" + c.name + ")"
: c.type;
summary[key] = (summary[key] || 0) + 1;
}
return {
name,
count: entry.count,
mounts: entry.mounts,
reRenders: entry.count - entry.mounts,
instanceCount: entry._instances.size,
totalTime: round(entry.totalTime),
selfTime: round(entry.selfTime),
domMutations: entry.domMutations,
changes: entry.changes,
changeSummary: summary,
};
})
.sort((a, b) => b.totalTime - a.totalTime || b.count - a.count);
return JSON.stringify({
elapsed: round(elapsed / 1000),
fps: fpsStats,
totalRenders: components.reduce((s, c) => s + c.count, 0),
totalMounts: components.reduce((s, c) => s + c.mounts, 0),
totalReRenders: components.reduce((s, c) => s + c.reRenders, 0),
totalComponents: components.length,
components,
});
})()
"#;
/// Suspense boundary walker. Returns boundaries with suspendedBy metadata as JSON.
pub const SUSPENSE_WALK: &str = r#"
(async () => {
const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
if (!hook) throw new Error("React DevTools hook not installed - relaunch with --enable react-devtools");
const ri = hook.rendererInterfaces && hook.rendererInterfaces.get && hook.rendererInterfaces.get(1);
if (!ri) throw new Error("No React renderer attached");
const batches = await new Promise((resolve) => {
const out = [];
const origEmit = hook.emit;
hook.emit = function (event, payload) {
if (event === "operations") out.push(payload);
return origEmit.apply(this, arguments);
};
ri.flushInitialOperations();
setTimeout(() => {
hook.emit = origEmit;
resolve(out);
}, 50);
});
const boundaryMap = new Map();
for (const ops of batches) decodeSuspenseOps(ops, boundaryMap);
const results = [];
for (const b of boundaryMap.values()) {
if (b.parentID === 0) continue;
const boundary = {
id: b.id,
parentID: b.parentID,
name: b.name,
isSuspended: b.isSuspended,
environments: b.environments,
suspendedBy: [],
unknownSuspenders: null,
owners: [],
jsxSource: null,
};
if (ri.hasElementWithId(b.id)) {
const displayName = ri.getDisplayNameForElementID(b.id);
if (displayName) boundary.name = displayName;
const result = ri.inspectElement(1, b.id, null, true);
if (result && result.type === "full-data") {
parseInspection(boundary, result.value);
}
}
results.push(boundary);
}
return JSON.stringify(results);
function decodeSuspenseOps(ops, map) {
let i = 2;
const strings = [null];
const tableEnd = ++i + ops[i - 1];
while (i < tableEnd) {
const len = ops[i++];
strings.push(String.fromCodePoint(...ops.slice(i, i + len)));
i += len;
}
while (i < ops.length) {
const op = ops[i];
if (op === 1) {
const type = ops[i + 2];
i += 3 + (type === 11 ? 4 : 5);
} else if (op === 2) {
i += 2 + ops[i + 1];
} else if (op === 3) {
i += 3 + ops[i + 2];
} else if (op === 4) {
i += 3;
} else if (op === 5) {
i += 4;
} else if (op === 6) {
i++;
} else if (op === 7) {
i += 3;
} else if (op === 8) {
const id = ops[i + 1];
const parentID = ops[i + 2];
const nameStrID = ops[i + 3];
const isSuspended = ops[i + 4] === 1;
const numRects = ops[i + 5];
i += 6;
if (numRects !== -1) i += numRects * 4;
map.set(id, { id, parentID, name: strings[nameStrID] || null, isSuspended, environments: [] });
} else if (op === 9) {
i += 2 + ops[i + 1];
} else if (op === 10) {
i += 3 + ops[i + 2];
} else if (op === 11) {
const numRects = ops[i + 2];
i += 3;
if (numRects !== -1) i += numRects * 4;
} else if (op === 12) {
i++;
const changeLen = ops[i++];
for (let c = 0; c < changeLen; c++) {
const id = ops[i++];
i++;
i++;
const isSuspended = ops[i++] === 1;
const envLen = ops[i++];
const envs = [];
for (let e = 0; e < envLen; e++) {
const n = strings[ops[i++]];
if (n != null) envs.push(n);
}
const node = map.get(id);
if (node) {
node.isSuspended = isSuspended;
for (const env of envs) {
if (!node.environments.includes(env)) node.environments.push(env);
}
}
}
} else if (op === 13) {
i += 2;
} else {
i++;
}
}
}
function parseInspection(boundary, data) {
const rawSuspendedBy = data.suspendedBy;
const rawSuspenders = Array.isArray(rawSuspendedBy)
? rawSuspendedBy
: rawSuspendedBy && Array.isArray(rawSuspendedBy.data) ? rawSuspendedBy.data : null;
if (rawSuspenders) {
for (const entry of rawSuspenders) {
const awaited = entry && entry.awaited;
if (!awaited) continue;
const desc = preview(awaited.description) || preview(awaited.value);
boundary.suspendedBy.push({
name: awaited.name || "unknown",
description: desc,
duration: awaited.end && awaited.start ? Math.round(awaited.end - awaited.start) : 0,
env: awaited.env || (entry && entry.env) || null,
ownerName: (awaited.owner && awaited.owner.displayName) || null,
ownerStack: parseStack((awaited.owner && awaited.owner.stack) || awaited.stack),
awaiterName: (entry && entry.owner && entry.owner.displayName) || null,
awaiterStack: parseStack((entry && entry.owner && entry.owner.stack) || (entry && entry.stack)),
});
}
}
if (data.unknownSuspenders && data.unknownSuspenders !== 0) {
const reasons = {
1: "production build (no debug info)",
2: "old React version (missing tracking)",
3: "thrown Promise (library using throw instead of use())",
};
boundary.unknownSuspenders = reasons[data.unknownSuspenders] || "unknown reason";
}
if (Array.isArray(data.owners)) {
for (const o of data.owners) {
if (o && o.displayName) {
const src = Array.isArray(o.stack) && o.stack.length > 0 && Array.isArray(o.stack[0])
? [o.stack[0][1] || "(unknown)", o.stack[0][2], o.stack[0][3]]
: null;
boundary.owners.push({ name: o.displayName, env: o.env || null, source: src });
}
}
}
if (Array.isArray(data.stack) && data.stack.length > 0) {
const frame = data.stack[0];
if (Array.isArray(frame) && frame.length >= 4) {
boundary.jsxSource = [frame[1] || "(unknown)", frame[2], frame[3]];
}
}
}
function parseStack(raw) {
if (!Array.isArray(raw) || raw.length === 0) return null;
return raw
.filter((f) => Array.isArray(f) && f.length >= 4)
.map((f) => [f[0] || "", f[1] || "", f[2] || 0, f[3] || 0]);
}
function preview(v) {
if (v == null) return "";
if (typeof v === "string") return v;
if (typeof v !== "object") return String(v);
if (typeof v.preview_long === "string") return v.preview_long;
if (typeof v.preview_short === "string") return v.preview_short;
if (typeof v.value === "string") return v.value;
try {
const s = JSON.stringify(v);
return s.length > 80 ? s.slice(0, 77) + "..." : s;
} catch {
return "";
}
}
})()
"#;
/// Init script for Core Web Vitals + React hydration timing capture. Installs
/// PerformanceObservers for LCP/CLS and intercepts `console.timeStamp` to
/// capture React's profiling reconciler timings. Idempotent.
pub const VITALS_INIT: &str = r#"
(() => {
if (window.__AB_VITALS_INSTALLED__) return;
window.__AB_VITALS_INSTALLED__ = true;
const cwv = { lcp: null, cls: 0, clsEntries: [], fcp: null, inp: null };
window.__AB_VITALS__ = cwv;
try {
new PerformanceObserver((list) => {
const entries = list.getEntries();
if (entries.length > 0) {
const last = entries[entries.length - 1];
cwv.lcp = {
startTime: Math.round(last.startTime * 100) / 100,
size: last.size,
element: last.element && last.element.tagName ? last.element.tagName.toLowerCase() : null,
url: last.url || null,
};
}
}).observe({ type: "largest-contentful-paint", buffered: true });
} catch {}
try {
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput) {
cwv.cls += entry.value;
cwv.clsEntries.push({
value: Math.round(entry.value * 10000) / 10000,
startTime: Math.round(entry.startTime * 100) / 100,
});
}
}
}).observe({ type: "layout-shift", buffered: true });
} catch {}
try {
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.name === "first-contentful-paint") {
cwv.fcp = Math.round(entry.startTime * 100) / 100;
}
}
}).observe({ type: "paint", buffered: true });
} catch {}
try {
new PerformanceObserver((list) => {
let worst = cwv.inp || 0;
for (const entry of list.getEntries()) {
if (entry.duration > worst) worst = entry.duration;
}
if (worst > 0) cwv.inp = Math.round(worst * 100) / 100;
}).observe({ type: "event", buffered: true, durationThreshold: 40 });
} catch {}
// React profiling build emits console.timeStamp(label, start, end, track, trackGroup, color)
// for reconciler phases and per-component hydration timing. Intercept and collect.
const timing = [];
window.__AB_REACT_TIMING__ = timing;
const orig = console.timeStamp;
console.timeStamp = function (label) {
const args = arguments;
if (typeof label === "string" && args.length >= 3 && typeof args[1] === "number") {
timing.push({
label,
startTime: args[1],
endTime: args[2],
track: args[3] || "",
trackGroup: args[4] || "",
color: args[5] || "",
});
}
return orig.apply(console, args);
};
})()
"#;
/// Read script for vitals — collects observed metrics plus Navigation Timing
/// TTFB and any React hydration phases. Returns JSON.
pub const VITALS_READ: &str = r#"
(() => {
const cwv = window.__AB_VITALS__ || {};
const timing = window.__AB_REACT_TIMING__ || [];
const nav = performance.getEntriesByType("navigation")[0];
const ttfb = nav
? Math.round((nav.responseStart - nav.requestStart) * 100) / 100
: null;
return JSON.stringify({ cwv, timing, ttfb });
})()
"#;
/// SPA client-side navigation. Tries the framework router first so Next.js
/// app/pages router triggers an RSC fetch (pure `history.pushState` would
/// be shallow routing and bypass data loading). Falls back to
/// `history.pushState` + popstate/navigate events for vanilla pages and
/// routers that listen to history events (React Router, TanStack Router,
/// Solid Router, Vue Router).
pub const PUSHSTATE: &str = r#"
((url) => {
const before = location.href;
const absolute = new URL(url, before).href;
if (absolute === before) return before;
// Next.js pages + app router expose window.next.router with a `push`
// method that triggers the RSC fetch and re-render pipeline.
const r = typeof window.next === "object" && window.next && window.next.router;
if (r && typeof r.push === "function") {
try { r.push(url); return location.href; } catch {}
}
history.pushState(null, "", absolute);
try { dispatchEvent(new PopStateEvent("popstate", { state: null })); } catch {}
try { dispatchEvent(new Event("navigate")); } catch {}
return location.href;
})({{URL}})
"#;
+633
View File
@@ -0,0 +1,633 @@
//! React Suspense boundary introspection: walker data types, classifier, and
//! human-readable report.
//!
//! The classifier labels and recommendations are React-Suspense-general —
//! they describe what kind of thing is making a boundary suspend (`client-hook`,
//! `request-api`, `server-fetch`, `cache`, `stream`, `framework`, `unknown`)
//! and a high-level direction for fixing it. Framework-specific reasoning
//! (e.g. Next.js PPR push vs goto semantics) is left to the caller.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
pub type StackFrame = (String, String, i64, i64);
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Boundary {
pub id: i64,
#[serde(rename = "parentID")]
pub parent_id: i64,
pub name: Option<String>,
#[serde(rename = "isSuspended")]
pub is_suspended: bool,
pub environments: Vec<String>,
#[serde(rename = "suspendedBy")]
pub suspended_by: Vec<Suspender>,
#[serde(rename = "unknownSuspenders")]
pub unknown_suspenders: Option<String>,
pub owners: Vec<Owner>,
#[serde(rename = "jsxSource")]
pub jsx_source: Option<(String, i64, i64)>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Owner {
pub name: String,
pub env: Option<String>,
pub source: Option<(String, i64, i64)>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Suspender {
pub name: String,
pub description: String,
pub duration: i64,
pub env: Option<String>,
#[serde(rename = "ownerName")]
pub owner_name: Option<String>,
#[serde(rename = "ownerStack")]
pub owner_stack: Option<Vec<StackFrame>>,
#[serde(rename = "awaiterName")]
pub awaiter_name: Option<String>,
#[serde(rename = "awaiterStack")]
pub awaiter_stack: Option<Vec<StackFrame>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlockerKind {
ClientHook,
RequestApi,
ServerFetch,
Stream,
Cache,
Framework,
Unknown,
}
impl BlockerKind {
fn label(self) -> &'static str {
match self {
Self::ClientHook => "client-hook",
Self::RequestApi => "request-api",
Self::ServerFetch => "server-fetch",
Self::Stream => "stream",
Self::Cache => "cache",
Self::Framework => "framework",
Self::Unknown => "unknown",
}
}
fn weight(self) -> i32 {
match self {
Self::ClientHook => 7,
Self::RequestApi => 6,
Self::ServerFetch => 5,
Self::Cache => 4,
Self::Stream => 3,
Self::Unknown => 2,
Self::Framework => 1,
}
}
fn actionability(self) -> i32 {
match self {
Self::ClientHook => 90,
Self::RequestApi => 88,
Self::ServerFetch => 82,
Self::Cache => 74,
Self::Stream => 60,
Self::Unknown => 35,
Self::Framework => 18,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoundaryKind {
RouteSegment,
ExplicitSuspense,
Component,
}
impl BoundaryKind {
fn label(self) -> &'static str {
match self {
Self::RouteSegment => "route-segment",
Self::ExplicitSuspense => "explicit-suspense",
Self::Component => "component",
}
}
fn weight(self) -> i32 {
match self {
Self::RouteSegment => 3,
Self::ExplicitSuspense => 2,
Self::Component => 1,
}
}
}
#[derive(Debug, Clone)]
pub struct ActionableBlocker {
pub key: String,
pub name: String,
pub kind: BlockerKind,
pub env: Option<String>,
pub description: String,
pub owner_name: Option<String>,
pub awaiter_name: Option<String>,
pub source_frame: Option<StackFrame>,
pub owner_frame: Option<StackFrame>,
pub awaiter_frame: Option<StackFrame>,
pub actionability: i32,
pub suggestion: String,
}
#[derive(Debug, Clone)]
pub struct BoundaryInsight {
pub id: i64,
pub name: Option<String>,
pub boundary_kind: BoundaryKind,
pub environments: Vec<String>,
pub source: Option<(String, i64, i64)>,
pub rendered_by: Vec<Owner>,
pub primary_blocker: Option<ActionableBlocker>,
pub blockers: Vec<ActionableBlocker>,
pub unknown_suspenders: Option<String>,
pub actionability: i32,
pub recommendation: String,
}
#[derive(Debug, Clone)]
pub struct RootCauseGroup {
pub kind: BlockerKind,
pub name: String,
pub source_frame: Option<StackFrame>,
pub boundary_names: Vec<String>,
pub count: usize,
pub actionability: i32,
pub suggestion: String,
}
pub struct AnalysisReport {
pub total_boundaries: usize,
pub dynamic_hole_count: usize,
pub static_count: usize,
pub holes: Vec<BoundaryInsight>,
pub statics: Vec<StaticBoundarySummary>,
pub root_causes: Vec<RootCauseGroup>,
pub files_to_read: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct StaticBoundarySummary {
pub name: Option<String>,
pub source: Option<(String, i64, i64)>,
pub rendered_by: Vec<Owner>,
}
pub fn format_suspense_report(boundaries: &[Boundary], only_dynamic: bool) -> String {
let report = analyze_boundaries(boundaries);
format_report(&report, only_dynamic)
}
fn analyze_boundaries(boundaries: &[Boundary]) -> AnalysisReport {
let mut holes: Vec<&Boundary> = Vec::new();
let mut statics_raw: Vec<&Boundary> = Vec::new();
for b in boundaries {
if b.parent_id == 0 {
continue;
}
let has_blocker = !b.suspended_by.is_empty() || b.unknown_suspenders.is_some();
if b.is_suspended || has_blocker {
holes.push(b);
} else {
statics_raw.push(b);
}
}
let mut hole_insights: Vec<BoundaryInsight> = holes.iter().map(|b| build_insight(b)).collect();
hole_insights.sort_by(|a, b| {
b.actionability.cmp(&a.actionability).then_with(|| {
b.boundary_kind
.weight()
.cmp(&a.boundary_kind.weight())
.then_with(|| b.blockers.len().cmp(&a.blockers.len()))
.then_with(|| {
a.name
.as_deref()
.unwrap_or("")
.cmp(b.name.as_deref().unwrap_or(""))
})
})
});
let static_summaries: Vec<StaticBoundarySummary> = statics_raw
.iter()
.map(|b| StaticBoundarySummary {
name: b.name.clone(),
source: b.jsx_source.clone(),
rendered_by: b.owners.clone(),
})
.collect();
let root_causes = build_root_causes(&hole_insights);
let files_to_read = collect_files_to_read(&hole_insights, &root_causes);
AnalysisReport {
total_boundaries: hole_insights.len() + static_summaries.len(),
dynamic_hole_count: hole_insights.len(),
static_count: static_summaries.len(),
holes: hole_insights,
statics: static_summaries,
root_causes,
files_to_read,
}
}
fn build_insight(b: &Boundary) -> BoundaryInsight {
let boundary_kind = infer_boundary_kind(b);
let mut blockers: Vec<ActionableBlocker> = b
.suspended_by
.iter()
.map(build_actionable_blocker)
.collect();
blockers.sort_by(|a, b| {
b.actionability.cmp(&a.actionability).then_with(|| {
b.kind
.weight()
.cmp(&a.kind.weight())
.then_with(|| a.name.cmp(&b.name))
})
});
let primary = blockers.first().cloned();
let recommendation = recommend_fix(
boundary_kind,
primary.as_ref(),
b.unknown_suspenders.as_deref(),
);
let primary_action = primary.as_ref().map(|p| p.actionability).unwrap_or(0);
let base_action = if boundary_kind == BoundaryKind::RouteSegment {
55
} else {
0
};
BoundaryInsight {
id: b.id,
name: b.name.clone(),
boundary_kind,
environments: b.environments.clone(),
source: b.jsx_source.clone(),
rendered_by: b.owners.clone(),
primary_blocker: primary,
blockers,
unknown_suspenders: b.unknown_suspenders.clone(),
actionability: primary_action.max(base_action),
recommendation,
}
}
fn build_actionable_blocker(s: &Suspender) -> ActionableBlocker {
let owner_frame = pick_preferred_frame(s.owner_stack.as_deref());
let awaiter_frame = pick_preferred_frame(s.awaiter_stack.as_deref());
let source_frame = owner_frame.clone().or_else(|| awaiter_frame.clone());
let kind = classify_blocker(s, source_frame.as_ref());
let suggestion = suggest_blocker_fix(kind);
let mut actionability = kind.actionability();
if let Some(ref frame) = source_frame {
if !is_frameworkish_path(&frame.1) {
actionability += 8;
}
}
if s.owner_name.is_some() || s.awaiter_name.is_some() {
actionability += 4;
}
if actionability > 100 {
actionability = 100;
}
let key = build_blocker_key(&s.name, kind, source_frame.as_ref());
ActionableBlocker {
key,
name: s.name.clone(),
kind,
env: s.env.clone(),
description: s.description.clone(),
owner_name: s.owner_name.clone(),
awaiter_name: s.awaiter_name.clone(),
source_frame,
owner_frame,
awaiter_frame,
actionability,
suggestion,
}
}
fn infer_boundary_kind(b: &Boundary) -> BoundaryKind {
let owner_names: Vec<&str> = b.owners.iter().map(|o| o.name.as_str()).collect();
let name_ends_slash = b.name.as_ref().is_some_and(|n| n.ends_with('/'));
if name_ends_slash
|| owner_names.contains(&"LoadingBoundary")
|| owner_names.contains(&"OuterLayoutRouter")
{
return BoundaryKind::RouteSegment;
}
let name_has_suspense = b.name.as_ref().is_some_and(|n| n.contains("Suspense"));
if name_has_suspense || owner_names.iter().any(|n| n.contains("Suspense")) {
return BoundaryKind::ExplicitSuspense;
}
BoundaryKind::Component
}
fn classify_blocker(s: &Suspender, source_frame: Option<&StackFrame>) -> BlockerKind {
let name = s.name.to_lowercase();
match name.as_str() {
"usepathname"
| "useparams"
| "usesearchparams"
| "useselectedlayoutsegments"
| "useselectedlayoutsegment"
| "userouter" => return BlockerKind::ClientHook,
"cookies" | "headers" | "connection" | "params" | "searchparams" | "draftmode" => {
return BlockerKind::RequestApi
}
_ => {}
}
if name == "rsc stream" {
return BlockerKind::Stream;
}
if name.contains("fetch") {
return BlockerKind::ServerFetch;
}
if name.contains("cache") || s.description.to_lowercase().contains("cache") {
return BlockerKind::Cache;
}
if name.starts_with("use") {
return BlockerKind::ClientHook;
}
if let Some(frame) = source_frame {
if is_frameworkish_path(&frame.1) {
return BlockerKind::Framework;
}
}
BlockerKind::Unknown
}
fn suggest_blocker_fix(kind: BlockerKind) -> String {
match kind {
BlockerKind::ClientHook => "Move route hooks behind a smaller client Suspense or provide a real non-null loading fallback for this segment.",
BlockerKind::RequestApi => "Push request-bound reads to a smaller server leaf, or cache around them so the parent shell can stay static.",
BlockerKind::ServerFetch => "Split static shell content from data widgets, then push the fetch into smaller Suspense leaves or cache it.",
BlockerKind::Cache => "This looks cache-related; check whether \"use cache\" or runtime prefetch can eliminate the suspension.",
BlockerKind::Stream => "A stream is still pending here; extract static siblings outside the boundary and push the stream consumer deeper.",
BlockerKind::Framework => "This currently looks framework-driven; find the nearest user-owned caller above it before changing code.",
BlockerKind::Unknown => "Inspect the nearest user-owned owner/awaiter frame and verify whether this suspender really belongs at this boundary.",
}.to_string()
}
fn recommend_fix(
boundary_kind: BoundaryKind,
primary: Option<&ActionableBlocker>,
unknown_suspenders: Option<&str>,
) -> String {
if boundary_kind == BoundaryKind::RouteSegment
&& primary.is_some_and(|p| p.kind == BlockerKind::ClientHook)
{
return "This route segment is suspending on client hooks. Check loading.tsx first; if it is null or visually empty, fix the fallback before chasing deeper push-down work.".to_string();
}
if let Some(p) = primary {
match p.kind {
BlockerKind::ClientHook => {
return "Push the hook-using client UI behind a smaller local Suspense boundary so the parent shell can prerender.".to_string();
}
BlockerKind::RequestApi | BlockerKind::ServerFetch => {
return "Push the request-bound async work into a smaller leaf or split static siblings out of this boundary.".to_string();
}
BlockerKind::Cache => {
return "Check whether caching or runtime prefetch can move this personalized content into the shell.".to_string();
}
BlockerKind::Stream => {
return "Keep the stream behind Suspense, but extract any static shell content outside the boundary.".to_string();
}
BlockerKind::Framework => {
return "The top blocker still looks framework-heavy. Find the nearest user-owned caller before changing boundary placement.".to_string();
}
_ => {}
}
}
if let Some(reason) = unknown_suspenders {
return format!(
"React could not identify the suspender ({}). Investigate the nearest user-owned owner or awaiter frame.",
reason
);
}
"No primary blocker was identified. Inspect the boundary source and owner chain directly."
.to_string()
}
fn pick_preferred_frame(stack: Option<&[StackFrame]>) -> Option<StackFrame> {
let s = stack?;
if s.is_empty() {
return None;
}
s.iter()
.find(|f| !is_frameworkish_path(&f.1))
.cloned()
.or_else(|| s.first().cloned())
}
fn is_frameworkish_path(file: &str) -> bool {
file.contains("/node_modules/")
}
fn build_blocker_key(name: &str, kind: BlockerKind, source_frame: Option<&StackFrame>) -> String {
match source_frame {
None => format!("{}:{}:unknown", kind.label(), name),
Some(f) => format!("{}:{}:{}:{}", kind.label(), name, f.1, f.2),
}
}
fn build_root_causes(holes: &[BoundaryInsight]) -> Vec<RootCauseGroup> {
let mut groups: HashMap<String, RootCauseGroup> = HashMap::new();
for hole in holes {
let Some(blocker) = &hole.primary_blocker else {
continue;
};
let display_name = hole
.name
.clone()
.unwrap_or_else(|| format!("boundary-{}", hole.id));
groups
.entry(blocker.key.clone())
.and_modify(|existing| {
existing.boundary_names.push(display_name.clone());
existing.count += 1;
if blocker.actionability > existing.actionability {
existing.actionability = blocker.actionability;
}
})
.or_insert_with(|| RootCauseGroup {
kind: blocker.kind,
name: blocker.name.clone(),
source_frame: blocker.source_frame.clone(),
boundary_names: vec![display_name],
count: 1,
actionability: blocker.actionability,
suggestion: blocker.suggestion.clone(),
});
}
let mut out: Vec<RootCauseGroup> = groups.into_values().collect();
out.sort_by(|a, b| {
let score_a = (a.count as i32) * a.actionability;
let score_b = (b.count as i32) * b.actionability;
score_b.cmp(&score_a).then_with(|| a.name.cmp(&b.name))
});
out
}
fn collect_files_to_read(holes: &[BoundaryInsight], root_causes: &[RootCauseGroup]) -> Vec<String> {
let mut counts: HashMap<String, i32> = HashMap::new();
let mut add = |f: Option<&str>| {
if let Some(path) = f {
if !path.is_empty() {
*counts.entry(path.to_string()).or_insert(0) += 1;
}
}
};
for hole in holes {
add(hole.source.as_ref().map(|s| s.0.as_str()));
if let Some(pb) = &hole.primary_blocker {
add(pb.source_frame.as_ref().map(|f| f.1.as_str()));
}
for owner in &hole.rendered_by {
add(owner.source.as_ref().map(|s| s.0.as_str()));
}
}
for cause in root_causes {
add(cause.source_frame.as_ref().map(|f| f.1.as_str()));
}
let mut entries: Vec<(String, i32)> = counts.into_iter().collect();
entries.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
entries.into_iter().take(12).map(|(f, _)| f).collect()
}
fn escape_cell(s: &str) -> String {
s.replace('|', "\\|")
}
fn format_report(report: &AnalysisReport, only_dynamic: bool) -> String {
let mut lines: Vec<String> = Vec::new();
lines.push("# Suspense Boundary Analysis".to_string());
if only_dynamic {
lines.push(format!(
"# {} dynamic holes (static boundaries hidden; pass without --only-dynamic to see them)",
report.dynamic_hole_count
));
} else {
lines.push(format!(
"# {} boundaries: {} dynamic holes, {} static",
report.total_boundaries, report.dynamic_hole_count, report.static_count
));
}
lines.push(String::new());
if !report.holes.is_empty() {
lines.push("## Summary".to_string());
if let Some(top) = report.holes.first() {
if let Some(blocker) = &top.primary_blocker {
lines.push(format!(
"- Top actionable hole: {} - {} ({})",
top.name.clone().unwrap_or_else(|| "(unnamed)".into()),
blocker.name,
blocker.kind.label()
));
lines.push(format!("- Suggested next step: {}", top.recommendation));
}
}
if let Some(root) = report.root_causes.first() {
lines.push(format!(
"- Most common root cause: {} ({}) affecting {} boundar{}",
root.name,
root.kind.label(),
root.count,
if root.count == 1 { "y" } else { "ies" }
));
}
lines.push(String::new());
lines.push("## Quick Reference".to_string());
lines.push(
"| Boundary | Type | Primary blocker | Source | Suggested next step |".to_string(),
);
lines.push("| --- | --- | --- | --- | --- |".to_string());
for hole in &report.holes {
let blocker = &hole.primary_blocker;
let source = match blocker.as_ref().and_then(|b| b.source_frame.as_ref()) {
Some(f) => format!("{}:{}", f.1, f.2),
None => match &hole.source {
Some((f, l, _)) => format!("{}:{}", f, l),
None => "unknown".to_string(),
},
};
let blocker_text = match blocker {
Some(b) => format!("{} ({})", b.name, b.kind.label()),
None => "unknown".to_string(),
};
lines.push(format!(
"| {} | {} | {} | {} | {} |",
escape_cell(hole.name.as_deref().unwrap_or("(unnamed)")),
hole.boundary_kind.label(),
escape_cell(&blocker_text),
escape_cell(&source),
escape_cell(&hole.recommendation),
));
}
lines.push(String::new());
if !report.files_to_read.is_empty() {
lines.push("## Files to Read".to_string());
for file in &report.files_to_read {
lines.push(format!("- {}", file));
}
lines.push(String::new());
}
if !report.root_causes.is_empty() {
lines.push("## Root Causes".to_string());
for cause in &report.root_causes {
let source = match &cause.source_frame {
Some(f) => format!("{}:{}", f.1, f.2),
None => "unknown".to_string(),
};
lines.push(format!(
"- {} ({}) at {} - affects {} boundar{}",
cause.name,
cause.kind.label(),
source,
cause.count,
if cause.count == 1 { "y" } else { "ies" }
));
lines.push(format!(" next step: {}", cause.suggestion));
lines.push(format!(" boundaries: {}", cause.boundary_names.join(", ")));
}
lines.push(String::new());
}
}
if !only_dynamic && !report.statics.is_empty() {
lines.push("## Static (not suspended)".to_string());
for b in &report.statics {
let name = b.name.clone().unwrap_or_else(|| "(unnamed)".into());
let src = match &b.source {
Some(s) => format!(" at {}:{}:{}", s.0, s.1, s.2),
None => String::new(),
};
lines.push(format!(" {}{}", name, src));
}
}
lines.join("\n")
}
+67
View File
@@ -0,0 +1,67 @@
//! React component tree snapshot and formatter.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct TreeNode {
pub id: i64,
#[serde(rename = "type")]
pub node_type: i64,
pub name: Option<String>,
pub key: Option<String>,
pub parent: i64,
}
const HEADER: &str = "# React component tree\n# Columns: depth id parent name [key=...]\n# Use `react inspect <id>` for props/hooks/state. IDs valid until next navigation.";
pub fn format_tree(nodes: &[TreeNode]) -> String {
use std::collections::HashMap;
let mut children: HashMap<i64, Vec<&TreeNode>> = HashMap::new();
for n in nodes {
children.entry(n.parent).or_default().push(n);
}
let mut lines: Vec<String> = vec![HEADER.to_string()];
if let Some(roots) = children.get(&0) {
for root in roots {
walk(root, 0, &children, &mut lines);
}
}
lines.join("\n")
}
fn walk<'a>(
node: &'a TreeNode,
depth: usize,
children: &std::collections::HashMap<i64, Vec<&'a TreeNode>>,
lines: &mut Vec<String>,
) {
let name = node
.name
.clone()
.unwrap_or_else(|| type_name(node.node_type));
let key = match &node.key {
Some(k) => format!(" key={:?}", k),
None => String::new(),
};
let parent = if node.parent == 0 {
"-".to_string()
} else {
node.parent.to_string()
};
lines.push(format!("{} {} {} {}{}", depth, node.id, parent, name, key));
if let Some(cs) = children.get(&node.id) {
for c in cs {
walk(c, depth + 1, children, lines);
}
}
}
fn type_name(t: i64) -> String {
match t {
11 => "Root".to_string(),
12 => "Suspense".to_string(),
13 => "SuspenseList".to_string(),
_ => format!("({})", t),
}
}
+160
View File
@@ -0,0 +1,160 @@
//! Core Web Vitals + React hydration timing report.
//!
//! Universal web-standard metrics (LCP/CLS/TTFB/FCP/INP) via PerformanceObserver
//! and Navigation Timing. When the React profiling build is detected (via
//! `console.timeStamp` entries), also reports hydration phases and per-component
//! hydration timing.
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct VitalsData {
pub url: String,
pub ttfb: Option<f64>,
pub lcp: Option<Lcp>,
pub cls: Cls,
pub fcp: Option<f64>,
pub inp: Option<f64>,
pub hydration: Option<HydrationRange>,
pub phases: Vec<Phase>,
#[serde(rename = "hydratedComponents")]
pub hydrated_components: Vec<HydratedComponent>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Lcp {
#[serde(rename = "startTime")]
pub start_time: f64,
pub size: Option<i64>,
pub element: Option<String>,
pub url: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Cls {
pub score: f64,
pub entries: Vec<ClsEntry>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ClsEntry {
pub value: f64,
#[serde(rename = "startTime")]
pub start_time: f64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct HydrationRange {
#[serde(rename = "startTime")]
pub start_time: f64,
#[serde(rename = "endTime")]
pub end_time: f64,
pub duration: f64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Phase {
pub label: String,
#[serde(rename = "startTime")]
pub start_time: f64,
#[serde(rename = "endTime")]
pub end_time: f64,
pub duration: f64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct HydratedComponent {
pub name: String,
#[serde(rename = "startTime")]
pub start_time: f64,
#[serde(rename = "endTime")]
pub end_time: f64,
pub duration: f64,
}
pub fn format_vitals_report(d: &VitalsData) -> String {
let mut lines: Vec<String> = Vec::new();
lines.push(format!("# Page Load Profile - {}", d.url));
lines.push(String::new());
lines.push("## Core Web Vitals".to_string());
let ttfb_str = match d.ttfb {
Some(t) => format!("{}ms", t),
None => "-".to_string(),
};
lines.push(format!(" TTFB {:>10}", ttfb_str));
match &d.lcp {
Some(lcp) => {
let label = match (&lcp.element, &lcp.url) {
(Some(el), Some(url)) => {
let url_trunc: String = url.chars().take(60).collect();
format!(" ({}: {})", el, url_trunc)
}
(Some(el), None) => format!(" ({})", el),
_ => String::new(),
};
lines.push(format!(
" LCP {:>10}{}",
format!("{}ms", lcp.start_time),
label
));
}
None => lines.push(" LCP -".to_string()),
}
lines.push(format!(" CLS {:>10}", d.cls.score));
if let Some(fcp) = d.fcp {
lines.push(format!(" FCP {:>10}", format!("{}ms", fcp)));
}
if let Some(inp) = d.inp {
lines.push(format!(" INP {:>10}", format!("{}ms", inp)));
}
lines.push(String::new());
match &d.hydration {
Some(h) => lines.push(format!(
"## React Hydration - {}ms ({}ms -> {}ms)",
h.duration, h.start_time, h.end_time
)),
None => {
lines.push("## React Hydration - no data (requires React profiling build)".to_string())
}
}
if !d.phases.is_empty() {
for p in &d.phases {
lines.push(format!(
" {:<28} {:>10} ({} -> {})",
p.label,
format!("{}ms", p.duration),
p.start_time,
p.end_time
));
}
lines.push(String::new());
}
if !d.hydrated_components.is_empty() {
lines.push(format!(
"## Hydrated components ({} total, sorted by duration)",
d.hydrated_components.len()
));
for c in d.hydrated_components.iter().take(30) {
lines.push(format!(
" {:<40} {:>10}",
c.name,
format!("{}ms", c.duration)
));
}
if d.hydrated_components.len() > 30 {
lines.push(format!(
" ... and {} more",
d.hydrated_components.len() - 30
));
}
}
lines.join("\n")
}
+323
View File
@@ -0,0 +1,323 @@
use serde_json::{json, Value};
use std::process::Stdio;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tokio::sync::oneshot;
use super::cdp::client::CdpClient;
use super::cdp::types::{CaptureScreenshotParams, CaptureScreenshotResult};
const CAPTURE_INTERVAL_MS: u64 = 100;
const CAPTURE_FPS: u32 = 10;
pub struct RecordingState {
pub active: bool,
pub output_path: String,
pub frame_count: u64,
pub capture_task: Option<tokio::task::JoinHandle<Result<(), String>>>,
pub shared_frame_count: Option<Arc<AtomicU64>>,
pub cancel_tx: Option<oneshot::Sender<()>>,
}
impl RecordingState {
pub fn new() -> Self {
Self {
active: false,
output_path: String::new(),
frame_count: 0,
capture_task: None,
shared_frame_count: None,
cancel_tx: None,
}
}
}
pub fn recording_start(state: &mut RecordingState, path: &str) -> Result<Value, String> {
if state.active {
return Err("Recording already active".to_string());
}
state.active = true;
state.output_path = path.to_string();
state.frame_count = 0;
Ok(json!({ "started": true, "path": path }))
}
pub fn recording_stop(state: &mut RecordingState) -> Result<Value, String> {
if !state.active {
return Err("No recording in progress".to_string());
}
state.active = false;
if state.frame_count == 0 {
return Err("No frames captured".to_string());
}
Ok(json!({ "path": &state.output_path, "frames": state.frame_count }))
}
pub fn recording_restart(state: &mut RecordingState, path: &str) -> Result<Value, String> {
let previous = if state.active {
let stop_result = recording_stop(state);
stop_result
.ok()
.and_then(|v| v.get("path").and_then(|p| p.as_str()).map(String::from))
} else {
None
};
recording_start(state, path)?;
Ok(json!({
"restarted": true,
"previousPath": previous,
"path": path,
}))
}
fn build_ffmpeg_command(output_path: &str) -> tokio::process::Command {
let mut cmd = tokio::process::Command::new("ffmpeg");
cmd.args(["-y"])
.args(["-avioflags", "direct"])
.args([
"-fpsprobesize",
"0",
"-probesize",
"32",
"-analyzeduration",
"0",
])
.args([
"-f",
"image2pipe",
"-c:v",
"mjpeg",
"-framerate",
&CAPTURE_FPS.to_string(),
"-i",
"pipe:0",
])
.args(["-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2"]);
if output_path.ends_with(".webm") {
cmd.args(["-c:v", "libvpx", "-crf", "30", "-b:v", "1M"]);
} else {
cmd.args(["-c:v", "libx264", "-preset", "ultrafast"]);
}
cmd.args(["-pix_fmt", "yuv420p", "-threads", "1"])
.arg(output_path)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.kill_on_drop(true);
cmd
}
/// Spawn a background task that captures screenshots at a fixed interval
/// and pipes them to ffmpeg in real-time.
pub fn spawn_recording_task(
client: Arc<CdpClient>,
session_id: String,
output_path: String,
shared_count: Arc<AtomicU64>,
cancel_rx: oneshot::Receiver<()>,
) -> tokio::task::JoinHandle<Result<(), String>> {
tokio::spawn(async move {
let mut cancel_rx = std::pin::pin!(cancel_rx);
let mut ffmpeg = build_ffmpeg_command(&output_path).spawn().map_err(|e| {
format!(
"ffmpeg not found or failed to execute: {}. Install ffmpeg to enable recording.",
e
)
})?;
let mut stdin = ffmpeg
.stdin
.take()
.ok_or_else(|| "Failed to open ffmpeg stdin".to_string())?;
let mut interval = tokio::time::interval(Duration::from_millis(CAPTURE_INTERVAL_MS));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let params = CaptureScreenshotParams {
format: Some("jpeg".to_string()),
quality: Some(80),
clip: None,
from_surface: Some(true),
capture_beyond_viewport: None,
};
loop {
tokio::select! {
_ = &mut cancel_rx => break,
_ = interval.tick() => {}
}
let result: Result<CaptureScreenshotResult, _> = client
.send_command_typed("Page.captureScreenshot", &params, Some(&session_id))
.await;
let screenshot = match result {
Ok(s) => s,
Err(e) => {
if e.contains("Target closed") || e.contains("not found") {
break;
}
continue;
}
};
let bytes = match base64::Engine::decode(
&base64::engine::general_purpose::STANDARD,
&screenshot.data,
) {
Ok(b) => b,
Err(_) => continue,
};
if stdin.write_all(&bytes).await.is_err() {
break;
}
shared_count.fetch_add(1, Ordering::Relaxed);
}
drop(stdin);
let output = ffmpeg
.wait_with_output()
.await
.map_err(|e| format!("ffmpeg wait failed: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!(
"ffmpeg failed: {}",
stderr.chars().take(300).collect::<String>()
));
}
Ok(())
})
}
pub async fn stop_recording_task(state: &mut RecordingState) -> Result<(), String> {
if let Some(tx) = state.cancel_tx.take() {
let _ = tx.send(());
}
let counter = state.shared_frame_count.take();
let handle = state.capture_task.take();
let result = if let Some(h) = handle {
match h.await {
Ok(Ok(())) => Ok(()),
Ok(Err(e)) => Err(e),
Err(e) => Err(format!("Recording task panicked: {}", e)),
}
} else {
Ok(())
};
if let Some(c) = counter {
state.frame_count = c.load(Ordering::Relaxed);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_recording_state_new() {
let state = RecordingState::new();
assert!(!state.active);
assert!(state.output_path.is_empty());
assert_eq!(state.frame_count, 0);
}
#[test]
fn test_recording_start_sets_active() {
let mut state = RecordingState::new();
let result = recording_start(&mut state, "/tmp/test.mp4");
assert!(result.is_ok());
assert!(state.active);
assert_eq!(state.output_path, "/tmp/test.mp4");
assert_eq!(state.frame_count, 0);
}
#[test]
fn test_recording_start_while_active() {
let mut state = RecordingState::new();
recording_start(&mut state, "/tmp/test1.mp4").unwrap();
let result = recording_start(&mut state, "/tmp/test2.mp4");
assert!(result.is_err());
assert!(result.unwrap_err().contains("already active"));
}
#[test]
fn test_recording_stop_not_active() {
let mut state = RecordingState::new();
let result = recording_stop(&mut state);
assert!(result.is_err());
assert!(result.unwrap_err().contains("No recording"));
}
#[test]
fn test_recording_stop_no_frames() {
let mut state = RecordingState::new();
recording_start(&mut state, "/tmp/test.mp4").unwrap();
let result = recording_stop(&mut state);
assert!(result.is_err());
assert!(result.unwrap_err().contains("No frames"));
assert!(!state.active);
}
#[test]
fn test_recording_restart_while_inactive() {
let mut state = RecordingState::new();
let result = recording_restart(&mut state, "/tmp/new.webm");
assert!(result.is_ok());
assert!(state.active);
assert_eq!(state.output_path, "/tmp/new.webm");
}
#[test]
fn test_recording_restart_while_active() {
let mut state = RecordingState::new();
recording_start(&mut state, "/tmp/old.webm").unwrap();
state.frame_count = 10;
let result = recording_restart(&mut state, "/tmp/new.webm").unwrap();
assert!(state.active);
assert_eq!(state.output_path, "/tmp/new.webm");
assert_eq!(state.frame_count, 0);
assert_eq!(result["previousPath"], "/tmp/old.webm");
}
#[test]
fn test_build_ffmpeg_command_webm() {
let cmd = build_ffmpeg_command("/tmp/out.webm");
let args: Vec<&std::ffi::OsStr> = cmd.as_std().get_args().collect();
let args_str: Vec<&str> = args.iter().filter_map(|a| a.to_str()).collect();
assert!(args_str.contains(&"libvpx"));
assert!(args_str.contains(&"/tmp/out.webm"));
}
#[test]
fn test_build_ffmpeg_command_mp4() {
let cmd = build_ffmpeg_command("/tmp/out.mp4");
let args: Vec<&std::ffi::OsStr> = cmd.as_std().get_args().collect();
let args_str: Vec<&str> = args.iter().filter_map(|a| a.to_str()).collect();
assert!(args_str.contains(&"libx264"));
assert!(args_str.contains(&"/tmp/out.mp4"));
}
}
+691
View File
@@ -0,0 +1,691 @@
use serde::Serialize;
use serde_json::Value;
use std::path::PathBuf;
use std::collections::HashMap;
use super::cdp::client::CdpClient;
use super::cdp::types::*;
use super::element::RefMap;
const ANNOTATION_OVERLAY_ID: &str = "__agent_browser_annotations__";
#[derive(Debug, Clone)]
struct Rect {
x: f64,
y: f64,
width: f64,
height: f64,
}
#[derive(Debug, Clone)]
struct RawAnnotation {
ref_id: String,
number: u64,
role: String,
name: Option<String>,
rect: Rect,
}
#[derive(Debug, Clone, Serialize)]
pub struct AnnotationBox {
pub x: i64,
pub y: i64,
pub width: i64,
pub height: i64,
}
#[derive(Debug, Clone)]
pub struct ScreenshotAnnotation {
pub ref_id: String,
pub number: u64,
pub role: String,
pub name: Option<String>,
pub box_: AnnotationBox,
}
#[derive(Debug, Clone)]
pub struct ScreenshotResult {
pub path: String,
pub base64: String,
pub annotations: Vec<ScreenshotAnnotation>,
}
#[derive(Debug, Clone)]
pub struct ScreenshotOptions {
pub selector: Option<String>,
pub path: Option<String>,
pub full_page: bool,
pub format: String,
pub quality: Option<i32>,
pub annotate: bool,
pub output_dir: Option<String>,
}
impl Default for ScreenshotOptions {
fn default() -> Self {
Self {
selector: None,
path: None,
full_page: false,
format: "png".to_string(),
quality: None,
annotate: false,
output_dir: None,
}
}
}
impl Serialize for ScreenshotAnnotation {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct("ScreenshotAnnotation", 5)?;
state.serialize_field("ref", &self.ref_id)?;
state.serialize_field("number", &self.number)?;
state.serialize_field("role", &self.role)?;
if let Some(name) = &self.name {
state.serialize_field("name", name)?;
}
state.serialize_field("box", &self.box_)?;
state.end()
}
}
/// Captures a screenshot via CDP and optionally overlays numbered annotations
/// that mirror the Node.js screenshot `annotate` mode.
pub async fn take_screenshot(
client: &CdpClient,
session_id: &str,
ref_map: &RefMap,
options: &ScreenshotOptions,
iframe_sessions: &HashMap<String, String>,
) -> Result<ScreenshotResult, String> {
let target_rect = if options.annotate {
match options.selector.as_deref() {
Some(selector) => {
get_rect_for_selector(client, session_id, ref_map, selector, iframe_sessions)
.await?
}
None => None,
}
} else {
None
};
let raw_annotations = if options.annotate {
collect_annotations(client, session_id, ref_map).await?
} else {
Vec::new()
};
let overlay_items = filter_annotations(raw_annotations, target_rect.as_ref());
let overlay_injected = if options.annotate && !overlay_items.is_empty() {
inject_annotation_overlay(client, session_id, &overlay_items).await?;
true
} else {
false
};
let base64 =
capture_screenshot_base64(client, session_id, ref_map, options, iframe_sessions).await;
if overlay_injected {
let _ = remove_annotation_overlay(client, session_id).await;
}
let base64 = base64?;
let annotations = if options.annotate {
let scroll = if options.full_page {
Some(get_scroll_offsets(client, session_id).await?)
} else {
None
};
project_annotations(&overlay_items, target_rect.as_ref(), scroll)
} else {
Vec::new()
};
let ext = if options.format == "jpeg" {
"jpg"
} else {
"png"
};
let path = save_screenshot(
&base64,
options.path.as_deref(),
ext,
options.output_dir.as_deref(),
)?;
Ok(ScreenshotResult {
path,
base64,
annotations,
})
}
async fn capture_screenshot_base64(
client: &CdpClient,
session_id: &str,
ref_map: &RefMap,
options: &ScreenshotOptions,
iframe_sessions: &HashMap<String, String>,
) -> Result<String, String> {
let mut params = CaptureScreenshotParams {
format: Some(options.format.clone()),
quality: if options.format == "jpeg" {
options.quality.or(Some(80))
} else {
None
},
clip: None,
from_surface: Some(true),
capture_beyond_viewport: if options.full_page { Some(true) } else { None },
};
if options.full_page {
let metrics: Value = client
.send_command_no_params("Page.getLayoutMetrics", Some(session_id))
.await?;
let content_size = metrics
.get("contentSize")
.or_else(|| metrics.get("cssContentSize"));
if let Some(size) = content_size {
let width = size.get("width").and_then(|v| v.as_f64()).unwrap_or(1280.0);
let height = size.get("height").and_then(|v| v.as_f64()).unwrap_or(720.0);
params.clip = Some(Viewport {
x: 0.0,
y: 0.0,
width,
height,
scale: 1.0,
});
}
} else if let Some(ref selector) = options.selector {
if let Some(rect) =
get_rect_for_selector(client, session_id, ref_map, selector, iframe_sessions).await?
{
params.clip = Some(Viewport {
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
scale: 1.0,
});
}
}
let result: CaptureScreenshotResult = client
.send_command_typed("Page.captureScreenshot", &params, Some(session_id))
.await?;
Ok(result.data)
}
async fn collect_annotations(
client: &CdpClient,
session_id: &str,
ref_map: &RefMap,
) -> Result<Vec<RawAnnotation>, String> {
let entries = ref_map.entries_sorted();
if entries.is_empty() {
return Ok(Vec::new());
}
// Collect entries that have backend_node_ids for batch resolution.
let with_backend_ids: Vec<(String, super::element::RefEntry, i64)> = entries
.iter()
.filter_map(|(ref_id, entry)| {
entry
.backend_node_id
.map(|bid| (ref_id.clone(), entry.clone(), bid))
})
.collect();
if with_backend_ids.is_empty() {
return Ok(Vec::new());
}
// Batch-resolve all backend_node_ids to object IDs using concurrent CDP calls.
let resolve_futures: Vec<_> = with_backend_ids
.iter()
.map(|(_, _, backend_node_id)| {
client.send_command(
"DOM.resolveNode",
Some(serde_json::json!({
"backendNodeId": backend_node_id,
"objectGroup": "agent-browser-annotate"
})),
Some(session_id),
)
})
.collect();
let resolve_results = futures_util::future::join_all(resolve_futures).await;
// Collect resolved object IDs paired with their ref info.
let mut resolved: Vec<(String, super::element::RefEntry, String)> = Vec::new();
for (i, result) in resolve_results.into_iter().enumerate() {
if let Ok(val) = result {
if let Some(oid) = val
.get("object")
.and_then(|o| o.get("objectId"))
.and_then(|v| v.as_str())
{
let (ref_id, entry, _) = &with_backend_ids[i];
resolved.push((ref_id.clone(), entry.clone(), oid.to_string()));
}
}
}
if resolved.is_empty() {
return Ok(Vec::new());
}
// Batch-get bounding rects for all resolved elements using concurrent CDP calls.
let rect_futures: Vec<_> = resolved
.iter()
.map(|(_, _, object_id)| get_rect_for_object(client, session_id, object_id))
.collect();
let rect_results = futures_util::future::join_all(rect_futures).await;
let mut annotations = Vec::new();
for (i, rect_result) in rect_results.into_iter().enumerate() {
let rect = match rect_result {
Ok(Some(r)) if r.width > 0.0 && r.height > 0.0 => r,
_ => continue,
};
let (ref_id, entry, _) = &resolved[i];
let number = ref_id
.strip_prefix('e')
.and_then(|n| n.parse::<u64>().ok())
.unwrap_or(0);
annotations.push(RawAnnotation {
ref_id: ref_id.clone(),
number,
role: entry.role.clone(),
name: (!entry.name.is_empty()).then_some(entry.name.clone()),
rect,
});
}
Ok(annotations)
}
async fn get_rect_for_selector(
client: &CdpClient,
session_id: &str,
ref_map: &RefMap,
selector: &str,
iframe_sessions: &HashMap<String, String>,
) -> Result<Option<Rect>, String> {
let (object_id, effective_session_id) = super::element::resolve_element_object_id(
client,
session_id,
ref_map,
selector,
iframe_sessions,
)
.await?;
get_rect_for_object(client, &effective_session_id, &object_id).await
}
async fn get_rect_for_object(
client: &CdpClient,
session_id: &str,
object_id: &str,
) -> Result<Option<Rect>, String> {
let result: EvaluateResult = client
.send_command_typed(
"Runtime.callFunctionOn",
&CallFunctionOnParams {
function_declaration: r#"function() {
const rect = this.getBoundingClientRect();
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
}"#
.to_string(),
object_id: Some(object_id.to_string()),
arguments: None,
return_by_value: Some(true),
await_promise: Some(false),
},
Some(session_id),
)
.await?;
Ok(result.result.value.as_ref().and_then(parse_rect))
}
fn parse_rect(value: &Value) -> Option<Rect> {
Some(Rect {
x: value.get("x")?.as_f64()?,
y: value.get("y")?.as_f64()?,
width: value.get("width")?.as_f64()?,
height: value.get("height")?.as_f64()?,
})
}
fn filter_annotations(
annotations: Vec<RawAnnotation>,
target_rect: Option<&Rect>,
) -> Vec<RawAnnotation> {
let mut items = annotations
.into_iter()
.filter(|annotation| match target_rect {
Some(target) => overlaps(&annotation.rect, target),
None => true,
})
.collect::<Vec<_>>();
items.sort_by_key(|annotation| annotation.number);
items
}
fn overlaps(left: &Rect, right: &Rect) -> bool {
let left_x2 = left.x + left.width;
let left_y2 = left.y + left.height;
let right_x2 = right.x + right.width;
let right_y2 = right.y + right.height;
left.x < right_x2 && left_x2 > right.x && left.y < right_y2 && left_y2 > right.y
}
async fn inject_annotation_overlay(
client: &CdpClient,
session_id: &str,
annotations: &[RawAnnotation],
) -> Result<(), String> {
let overlay_data = annotations
.iter()
.map(|annotation| {
serde_json::json!({
"number": annotation.number,
"x": round(annotation.rect.x),
"y": round(annotation.rect.y),
"width": round(annotation.rect.width),
"height": round(annotation.rect.height),
})
})
.collect::<Vec<_>>();
let expression = format!(
r#"(() => {{
var items = {items};
var id = {overlay_id};
var existing = document.getElementById(id);
if (existing) existing.remove();
var sx = window.scrollX || 0;
var sy = window.scrollY || 0;
var c = document.createElement('div');
c.id = id;
c.style.cssText = 'position:absolute;top:0;left:0;width:0;height:0;pointer-events:none;z-index:2147483647;';
for (var i = 0; i < items.length; i++) {{
var it = items[i];
var dx = it.x + sx;
var dy = it.y + sy;
var b = document.createElement('div');
b.style.cssText = 'position:absolute;left:' + dx + 'px;top:' + dy + 'px;width:' + it.width + 'px;height:' + it.height + 'px;border:2px solid rgba(255,0,0,0.8);box-sizing:border-box;pointer-events:none;';
var l = document.createElement('div');
l.textContent = String(it.number);
var labelTop = dy < 14 ? '2px' : '-14px';
l.style.cssText = 'position:absolute;top:' + labelTop + ';left:-2px;background:rgba(255,0,0,0.9);color:#fff;font:bold 11px/14px monospace;padding:0 4px;border-radius:2px;white-space:nowrap;';
b.appendChild(l);
c.appendChild(b);
}}
document.documentElement.appendChild(c);
return true;
}})()"#,
items = serde_json::to_string(&overlay_data).unwrap_or_else(|_| "[]".to_string()),
overlay_id =
serde_json::to_string(ANNOTATION_OVERLAY_ID).unwrap_or_else(|_| "\"\"".to_string()),
);
let _: EvaluateResult = client
.send_command_typed(
"Runtime.evaluate",
&EvaluateParams {
expression,
return_by_value: Some(true),
await_promise: Some(false),
},
Some(session_id),
)
.await?;
Ok(())
}
async fn remove_annotation_overlay(client: &CdpClient, session_id: &str) -> Result<(), String> {
let expression = format!(
r#"(() => {{
var el = document.getElementById({overlay_id});
if (el) el.remove();
return true;
}})()"#,
overlay_id =
serde_json::to_string(ANNOTATION_OVERLAY_ID).unwrap_or_else(|_| "\"\"".to_string()),
);
let _: EvaluateResult = client
.send_command_typed(
"Runtime.evaluate",
&EvaluateParams {
expression,
return_by_value: Some(true),
await_promise: Some(false),
},
Some(session_id),
)
.await?;
Ok(())
}
async fn get_scroll_offsets(client: &CdpClient, session_id: &str) -> Result<(f64, f64), String> {
let result: EvaluateResult = client
.send_command_typed(
"Runtime.evaluate",
&EvaluateParams {
expression: "({x: window.scrollX || 0, y: window.scrollY || 0})".to_string(),
return_by_value: Some(true),
await_promise: Some(false),
},
Some(session_id),
)
.await?;
let value = result.result.value.unwrap_or(Value::Null);
let x = value.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0);
let y = value.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0);
Ok((x, y))
}
fn project_annotations(
annotations: &[RawAnnotation],
target_rect: Option<&Rect>,
scroll: Option<(f64, f64)>,
) -> Vec<ScreenshotAnnotation> {
annotations
.iter()
.map(|annotation| {
let rect = if let Some(target) = target_rect {
Rect {
x: annotation.rect.x - target.x,
y: annotation.rect.y - target.y,
width: annotation.rect.width,
height: annotation.rect.height,
}
} else if let Some((scroll_x, scroll_y)) = scroll {
Rect {
x: annotation.rect.x + scroll_x,
y: annotation.rect.y + scroll_y,
width: annotation.rect.width,
height: annotation.rect.height,
}
} else {
annotation.rect.clone()
};
ScreenshotAnnotation {
ref_id: annotation.ref_id.clone(),
number: annotation.number,
role: annotation.role.clone(),
name: annotation.name.clone(),
box_: AnnotationBox {
x: round(rect.x),
y: round(rect.y),
width: round(rect.width),
height: round(rect.height),
},
}
})
.collect()
}
fn save_screenshot(
base64_data: &str,
explicit_path: Option<&str>,
ext: &str,
output_dir: Option<&str>,
) -> Result<String, String> {
let save_path = match explicit_path {
Some(path) => path.to_string(),
None => {
let dir = match output_dir {
Some(d) => PathBuf::from(d),
None => get_screenshot_dir(),
};
let _ = std::fs::create_dir_all(&dir);
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis();
let name = format!("screenshot-{}.{}", timestamp, ext);
dir.join(name).to_string_lossy().to_string()
}
};
let bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, base64_data)
.map_err(|e| format!("Failed to decode screenshot: {}", e))?;
std::fs::write(&save_path, &bytes)
.map_err(|e| format!("Failed to save screenshot to {}: {}", save_path, e))?;
Ok(save_path)
}
fn round(value: f64) -> i64 {
value.round() as i64
}
fn get_screenshot_dir() -> PathBuf {
if let Some(home) = dirs::home_dir() {
home.join(".agent-browser").join("tmp").join("screenshots")
} else {
std::env::temp_dir()
.join("agent-browser")
.join("screenshots")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn filters_annotations_to_target_overlap() {
let annotations = vec![
RawAnnotation {
ref_id: "e1".to_string(),
number: 1,
role: "button".to_string(),
name: Some("Inside".to_string()),
rect: Rect {
x: 10.0,
y: 10.0,
width: 50.0,
height: 20.0,
},
},
RawAnnotation {
ref_id: "e2".to_string(),
number: 2,
role: "button".to_string(),
name: Some("Outside".to_string()),
rect: Rect {
x: 200.0,
y: 200.0,
width: 40.0,
height: 20.0,
},
},
];
let target = Rect {
x: 0.0,
y: 0.0,
width: 100.0,
height: 100.0,
};
let filtered = filter_annotations(annotations, Some(&target));
assert_eq!(filtered.len(), 1);
assert_eq!(filtered[0].ref_id, "e1");
}
#[test]
fn projects_selector_annotations_relative_to_target() {
let annotations = vec![RawAnnotation {
ref_id: "e1".to_string(),
number: 1,
role: "button".to_string(),
name: Some("Inside".to_string()),
rect: Rect {
x: 25.0,
y: 35.0,
width: 40.0,
height: 20.0,
},
}];
let target = Rect {
x: 10.0,
y: 15.0,
width: 100.0,
height: 100.0,
};
let projected = project_annotations(&annotations, Some(&target), None);
assert_eq!(projected[0].box_.x, 15);
assert_eq!(projected[0].box_.y, 20);
}
#[test]
fn projects_full_page_annotations_to_document_space() {
let annotations = vec![RawAnnotation {
ref_id: "e1".to_string(),
number: 1,
role: "button".to_string(),
name: Some("Bottom".to_string()),
rect: Rect {
x: 5.0,
y: 12.0,
width: 40.0,
height: 20.0,
},
}];
let projected = project_annotations(&annotations, None, Some((10.0, 1000.0)));
assert_eq!(projected[0].box_.x, 15);
assert_eq!(projected[0].box_.y, 1012);
}
}
File diff suppressed because it is too large Load Diff
+894
View File
@@ -0,0 +1,894 @@
use aes_gcm::{aead::Aead, aead::KeyInit, Aes256Gcm};
use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::collections::HashSet;
use std::fs;
use std::path::PathBuf;
use super::cdp::client::CdpClient;
use super::cdp::types::{
AttachToTargetParams, AttachToTargetResult, CloseTargetParams, CreateTargetParams,
CreateTargetResult, EvaluateParams,
};
use super::cookies::{self, Cookie};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StorageState {
pub cookies: Vec<Cookie>,
pub origins: Vec<OriginStorage>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OriginStorage {
pub origin: String,
pub local_storage: Vec<StorageEntry>,
#[serde(default)]
pub session_storage: Vec<StorageEntry>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StorageEntry {
pub name: String,
pub value: String,
}
fn collect_frame_origins(tree: &Value, origins: &mut HashSet<String>) {
if let Some(frame) = tree.get("frame") {
if let Some(url_str) = frame.get("url").and_then(|v| v.as_str()) {
if let Ok(parsed) = url::Url::parse(url_str) {
let origin = parsed.origin().ascii_serialization();
if origin != "null" && !origin.is_empty() {
origins.insert(origin);
}
}
}
}
if let Some(children) = tree.get("childFrames").and_then(|v| v.as_array()) {
for child in children {
collect_frame_origins(child, origins);
}
}
}
/// Parse the JS-evaluated origin storage data into an OriginStorage struct.
fn parse_origin_storage(data: &Value) -> Option<OriginStorage> {
if !data.is_object() {
return None;
}
let origin = data
.get("origin")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if origin.is_empty() || origin == "null" {
return None;
}
let local_storage: Vec<StorageEntry> = data
.get("localStorage")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
let session_storage: Vec<StorageEntry> = data
.get("sessionStorage")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
Some(OriginStorage {
origin,
local_storage,
session_storage,
})
}
/// Evaluate the storage-collection JS snippet and parse the result.
async fn eval_origin_storage(
client: &CdpClient,
session_id: &str,
origin_js: &str,
) -> Option<OriginStorage> {
let result = client
.send_command_typed::<_, super::cdp::types::EvaluateResult>(
"Runtime.evaluate",
&EvaluateParams {
expression: origin_js.to_string(),
return_by_value: Some(true),
await_promise: Some(false),
},
Some(session_id),
)
.await
.ok()?;
let data = result.result.value.unwrap_or(Value::Null);
parse_origin_storage(&data)
}
/// Create a temporary CDP target, navigate it to each origin to collect localStorage,
/// then close it. Uses Fetch interception to serve blank HTML instead of making real
/// network requests.
async fn collect_storage_via_temp_target(
client: &CdpClient,
origins: &[String],
origin_js: &str,
) -> Result<Vec<OriginStorage>, String> {
let create_result: CreateTargetResult = client
.send_command_typed(
"Target.createTarget",
&CreateTargetParams {
url: "about:blank".to_string(),
},
None,
)
.await?;
let target_id = create_result.target_id;
// Ensure the target is closed even if attach or later steps fail
let result = collect_storage_in_target(client, &target_id, origins, origin_js).await;
let _ = client
.send_command_typed::<_, Value>(
"Target.closeTarget",
&CloseTargetParams { target_id },
None,
)
.await;
result
}
async fn collect_storage_in_target(
client: &CdpClient,
target_id: &str,
origins: &[String],
origin_js: &str,
) -> Result<Vec<OriginStorage>, String> {
let attach_result: AttachToTargetResult = client
.send_command_typed(
"Target.attachToTarget",
&AttachToTargetParams {
target_id: target_id.to_string(),
flatten: true,
},
None,
)
.await?;
let temp_session = &attach_result.session_id;
client
.send_command_no_params("Page.enable", Some(temp_session))
.await?;
client
.send_command_no_params("Runtime.enable", Some(temp_session))
.await?;
// Blank HTML response body, pre-encoded to avoid repeated base64 work per request
let blank_html_b64 = base64::engine::general_purpose::STANDARD.encode("<html></html>");
let _ = client
.send_command(
"Fetch.enable",
Some(json!({ "patterns": [{ "urlPattern": "*" }] })),
Some(temp_session),
)
.await;
let mut event_rx = client.subscribe();
let mut results = Vec::new();
for target_origin in origins {
let nav_url = format!("{}/", target_origin.trim_end_matches('/'));
if client
.send_command(
"Page.navigate",
Some(json!({ "url": nav_url })),
Some(temp_session),
)
.await
.is_err()
{
continue;
}
// Fulfill intercepted requests with blank HTML until the page loads
let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(5);
let mut page_loaded = false;
while tokio::time::Instant::now() < deadline {
match tokio::time::timeout(tokio::time::Duration::from_secs(2), event_rx.recv()).await {
Ok(Ok(evt)) if evt.session_id.as_deref() == Some(temp_session) => {
if evt.method == "Fetch.requestPaused" {
if let Some(request_id) =
evt.params.get("requestId").and_then(|v| v.as_str())
{
let _ = client
.send_command(
"Fetch.fulfillRequest",
Some(json!({
"requestId": request_id,
"responseCode": 200,
"responseHeaders": [
{ "name": "Content-Type", "value": "text/html" }
],
"body": &blank_html_b64
})),
Some(temp_session),
)
.await;
}
} else if evt.method == "Page.loadEventFired" {
page_loaded = true;
break;
}
}
Ok(Ok(_)) => continue, // event for a different session
Ok(Err(_)) => continue, // lagged or closed — retry within deadline
Err(_) => break, // outer timeout elapsed
}
}
if !page_loaded {
continue;
}
if let Some(storage) = eval_origin_storage(client, temp_session, origin_js).await {
if !storage.local_storage.is_empty() || !storage.session_storage.is_empty() {
results.push(storage);
}
}
}
Ok(results)
}
pub async fn save_state(
client: &CdpClient,
session_id: &str,
path: Option<&str>,
session_name: Option<&str>,
session_id_str: &str,
visited_origins: &HashSet<String>,
) -> Result<String, String> {
let cookies = cookies::get_all_cookies(client, session_id).await?;
let origin_js = r#"(() => {
const result = { origin: location.origin, localStorage: [], sessionStorage: [] };
try {
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
result.localStorage.push({ name: key, value: localStorage.getItem(key) });
}
} catch(e) {}
try {
for (let i = 0; i < sessionStorage.length; i++) {
const key = sessionStorage.key(i);
result.sessionStorage.push({ name: key, value: sessionStorage.getItem(key) });
}
} catch(e) {}
return result;
})()"#;
// Merge visited origins with current frame tree origins
let mut all_origins = visited_origins.clone();
if let Ok(tree_result) = client
.send_command_no_params("Page.getFrameTree", Some(session_id))
.await
{
if let Some(tree) = tree_result.get("frameTree") {
collect_frame_origins(tree, &mut all_origins);
}
}
// 1. Collect localStorage from the current page
let mut origins = Vec::new();
let mut current_origin = String::new();
if let Some(storage) = eval_origin_storage(client, session_id, origin_js).await {
current_origin = storage.origin.clone();
if !storage.local_storage.is_empty() || !storage.session_storage.is_empty() {
origins.push(storage);
}
}
// 2. Collect localStorage from remaining origins via a disposable temp target
all_origins.remove(&current_origin);
if !all_origins.is_empty() {
let remaining: Vec<String> = all_origins.into_iter().collect();
if let Ok(temp_origins) =
collect_storage_via_temp_target(client, &remaining, origin_js).await
{
origins.extend(temp_origins);
}
}
let state = StorageState { cookies, origins };
let json_str = serde_json::to_string_pretty(&state)
.map_err(|e| format!("Failed to serialize state: {}", e))?;
let mut save_path = match path {
Some(p) => p.to_string(),
None => {
let dir = get_sessions_dir();
let _ = fs::create_dir_all(&dir);
let name = session_name.unwrap_or("default");
dir.join(format!("{}-{}.json", name, session_id_str))
.to_string_lossy()
.to_string()
}
};
if let Ok(key) = std::env::var("AGENT_BROWSER_ENCRYPTION_KEY") {
let encrypted = encrypt_data(json_str.as_bytes(), &key)?;
save_path.push_str(".enc");
fs::write(&save_path, &encrypted)
.map_err(|e| format!("Failed to write state to {}: {}", save_path, e))?;
} else {
fs::write(&save_path, &json_str)
.map_err(|e| format!("Failed to write state to {}: {}", save_path, e))?;
}
Ok(save_path)
}
pub async fn load_state(client: &CdpClient, session_id: &str, path: &str) -> Result<(), String> {
let json_str = if path.ends_with(".enc") {
let key = std::env::var("AGENT_BROWSER_ENCRYPTION_KEY").map_err(|_| {
"Encrypted state file requires AGENT_BROWSER_ENCRYPTION_KEY".to_string()
})?;
let data =
fs::read(path).map_err(|e| format!("Failed to read state from {}: {}", path, e))?;
let decrypted = decrypt_data(&data, &key)?;
String::from_utf8(decrypted)
.map_err(|e| format!("Decrypted state is not valid UTF-8: {}", e))?
} else {
match fs::read_to_string(path) {
Ok(s) => s,
Err(e) => {
if let Ok(key) = std::env::var("AGENT_BROWSER_ENCRYPTION_KEY") {
let enc_path = format!("{}.enc", path);
if let Ok(data) = fs::read(&enc_path) {
let decrypted = decrypt_data(&data, &key)?;
String::from_utf8(decrypted)
.map_err(|de| format!("Decrypted state is not valid UTF-8: {}", de))?
} else {
return Err(format!("Failed to read state from {}: {}", path, e));
}
} else {
return Err(format!("Failed to read state from {}: {}", path, e));
}
}
}
};
let state: StorageState =
serde_json::from_str(&json_str).map_err(|e| format!("Invalid state file: {}", e))?;
// Load cookies
if !state.cookies.is_empty() {
let cookie_values: Vec<Value> = state
.cookies
.iter()
.map(|c| serde_json::to_value(c).unwrap_or(Value::Null))
.collect();
cookies::set_cookies(client, session_id, cookie_values, None).await?;
}
// Load storage per origin
for origin in &state.origins {
if origin.local_storage.is_empty() && origin.session_storage.is_empty() {
continue;
}
// Navigate to origin to set storage
let navigate_url = format!("{}/", origin.origin.trim_end_matches('/'));
client
.send_command(
"Page.navigate",
Some(json!({ "url": navigate_url })),
Some(session_id),
)
.await?;
// Brief wait for navigation
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
for entry in &origin.local_storage {
let js = format!(
"localStorage.setItem({}, {})",
serde_json::to_string(&entry.name).unwrap_or_default(),
serde_json::to_string(&entry.value).unwrap_or_default(),
);
let _ = client
.send_command_typed::<_, super::cdp::types::EvaluateResult>(
"Runtime.evaluate",
&EvaluateParams {
expression: js,
return_by_value: Some(true),
await_promise: Some(false),
},
Some(session_id),
)
.await;
}
for entry in &origin.session_storage {
let js = format!(
"sessionStorage.setItem({}, {})",
serde_json::to_string(&entry.name).unwrap_or_default(),
serde_json::to_string(&entry.value).unwrap_or_default(),
);
let _ = client
.send_command_typed::<_, super::cdp::types::EvaluateResult>(
"Runtime.evaluate",
&EvaluateParams {
expression: js,
return_by_value: Some(true),
await_promise: Some(false),
},
Some(session_id),
)
.await;
}
}
Ok(())
}
fn is_state_file(path: &std::path::Path) -> bool {
let fname = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
fname.ends_with(".json") || fname.ends_with(".json.enc")
}
fn is_encrypted_state(path: &std::path::Path) -> bool {
path.to_string_lossy().ends_with(".json.enc")
}
pub fn state_list() -> Result<Value, String> {
let dir = get_sessions_dir();
if !dir.exists() {
return Ok(json!({ "files": [], "directory": dir.to_string_lossy() }));
}
let mut files = Vec::new();
let entries = fs::read_dir(&dir).map_err(|e| format!("Failed to read sessions dir: {}", e))?;
for entry in entries.flatten() {
let path = entry.path();
if is_state_file(&path) {
let metadata = fs::metadata(&path).ok();
let filename = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let size = metadata.as_ref().map(|m| m.len()).unwrap_or(0);
let modified = metadata
.as_ref()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs())
.unwrap_or(0);
let encrypted = is_encrypted_state(&path);
files.push(json!({
"filename": filename,
"path": path.to_string_lossy(),
"size": size,
"modified": modified,
"encrypted": encrypted,
}));
}
}
Ok(json!({ "files": files, "directory": dir.to_string_lossy() }))
}
pub fn state_show(path: &str) -> Result<Value, String> {
let encrypted = path.ends_with(".enc");
let json_str = if encrypted {
let key = std::env::var("AGENT_BROWSER_ENCRYPTION_KEY").map_err(|_| {
"Encrypted state file requires AGENT_BROWSER_ENCRYPTION_KEY".to_string()
})?;
let data = fs::read(path).map_err(|e| format!("Failed to read state file: {}", e))?;
let decrypted = decrypt_data(&data, &key)?;
String::from_utf8(decrypted)
.map_err(|e| format!("Decrypted state is not valid UTF-8: {}", e))?
} else {
fs::read_to_string(path).map_err(|e| format!("Failed to read state file: {}", e))?
};
let state: StorageState =
serde_json::from_str(&json_str).map_err(|e| format!("Invalid state file: {}", e))?;
let metadata = fs::metadata(path).ok();
let filename = std::path::Path::new(path)
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
Ok(json!({
"filename": filename,
"path": path,
"size": metadata.as_ref().map(|m| m.len()).unwrap_or(0),
"modified": metadata.as_ref()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs())
.unwrap_or(0),
"encrypted": encrypted,
"summary": format!("{} cookies, {} origins", state.cookies.len(), state.origins.len()),
"state": state,
}))
}
pub fn state_clear(path: Option<&str>) -> Result<Value, String> {
if let Some(p) = path {
fs::remove_file(p).map_err(|e| format!("Failed to delete state: {}", e))?;
return Ok(json!({ "deleted": p }));
}
let dir = get_sessions_dir();
if !dir.exists() {
return Ok(json!({ "deleted": 0 }));
}
let mut count = 0;
if let Ok(entries) = fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
if is_state_file(&path) {
let _ = fs::remove_file(&path);
count += 1;
}
}
}
Ok(json!({ "deleted": count }))
}
pub fn state_clean(max_age_days: u64) -> Result<Value, String> {
let dir = get_sessions_dir();
if !dir.exists() {
return Ok(json!({ "cleaned": 0, "keptCount": 0, "days": max_age_days }));
}
let now = std::time::SystemTime::now();
let max_age = std::time::Duration::from_secs(max_age_days * 86400);
let mut deleted = 0;
let mut kept = 0;
if let Ok(entries) = fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
if !is_state_file(&path) {
continue;
}
if let Ok(metadata) = fs::metadata(&path) {
if let Ok(modified) = metadata.modified() {
if let Ok(age) = now.duration_since(modified) {
if age > max_age {
let _ = fs::remove_file(&path);
deleted += 1;
continue;
}
}
}
}
kept += 1;
}
}
Ok(json!({ "cleaned": deleted, "keptCount": kept, "days": max_age_days }))
}
pub fn state_rename(old_path: &str, new_name: &str) -> Result<Value, String> {
let old = PathBuf::from(old_path);
if !old.exists() {
return Err(format!("State file not found: {}", old_path));
}
let fallback = PathBuf::from(".");
let dir = old.parent().unwrap_or(&fallback);
let new_path = dir.join(format!("{}.json", new_name));
fs::rename(&old, &new_path).map_err(|e| format!("Failed to rename state: {}", e))?;
Ok(json!({
"renamed": true,
"from": old_path,
"to": new_path.to_string_lossy(),
}))
}
fn encrypt_data(data: &[u8], key_str: &str) -> Result<Vec<u8>, String> {
let mut hasher = Sha256::new();
hasher.update(key_str.as_bytes());
let key_bytes = hasher.finalize();
let cipher =
Aes256Gcm::new_from_slice(&key_bytes).map_err(|e| format!("Invalid key: {}", e))?;
let mut nonce = [0u8; 12];
getrandom::getrandom(&mut nonce).map_err(|e| format!("Failed to generate nonce: {}", e))?;
let ciphertext = cipher
.encrypt(aes_gcm::Nonce::from_slice(&nonce), data)
.map_err(|e| format!("Encryption failed: {}", e))?;
let mut result = Vec::with_capacity(12 + ciphertext.len());
result.extend_from_slice(&nonce);
result.extend_from_slice(&ciphertext);
Ok(result)
}
fn decrypt_data(data: &[u8], key_str: &str) -> Result<Vec<u8>, String> {
if data.len() < 13 {
return Err("Ciphertext too short".to_string());
}
let (nonce_bytes, ciphertext) = data.split_at(12);
let mut hasher = Sha256::new();
hasher.update(key_str.as_bytes());
let key_bytes = hasher.finalize();
let cipher =
Aes256Gcm::new_from_slice(&key_bytes).map_err(|e| format!("Invalid key: {}", e))?;
let plaintext = cipher
.decrypt(aes_gcm::Nonce::from_slice(nonce_bytes), ciphertext)
.map_err(|e| format!("Decryption failed: {}", e))?;
Ok(plaintext)
}
pub fn find_auto_state_file(session_name: &str) -> Option<String> {
let dir = get_sessions_dir();
if !dir.exists() {
return None;
}
let prefix = format!("{}-", session_name);
let mut best_path: Option<(String, std::time::SystemTime)> = None;
if let Ok(entries) = fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
let fname = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let is_match = fname.starts_with(&prefix)
&& (fname.ends_with(".json") || fname.ends_with(".json.enc"));
if !is_match {
continue;
}
let modified = fs::metadata(&path)
.ok()
.and_then(|m| m.modified().ok())
.unwrap_or(std::time::UNIX_EPOCH);
if best_path.as_ref().is_none_or(|(_, t)| modified > *t) {
best_path = Some((path.to_string_lossy().to_string(), modified));
}
}
}
best_path.map(|(p, _)| p)
}
/// Dispatch a state management command from its JSON payload.
/// Returns `Some(result)` for recognised state_* actions, `None` otherwise.
pub fn dispatch_state_command(cmd: &Value) -> Option<Result<Value, String>> {
let action = cmd.get("action").and_then(|v| v.as_str())?;
match action {
"state_list" => Some(state_list()),
"state_show" => Some(
cmd.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| "Missing 'path' parameter".to_string())
.and_then(state_show),
),
"state_clear" => {
let path = cmd.get("path").and_then(|v| v.as_str());
Some(state_clear(path))
}
"state_clean" => {
let days = cmd.get("days").and_then(|v| v.as_u64()).unwrap_or(30);
Some(state_clean(days))
}
"state_rename" => Some(
cmd.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| "Missing 'path' parameter".to_string())
.and_then(|path| {
cmd.get("name")
.and_then(|v| v.as_str())
.ok_or_else(|| "Missing 'name' parameter".to_string())
.and_then(|name| state_rename(path, name))
}),
),
_ => None,
}
}
/// Return the agent-browser state root (`~/.agent-browser`, falling back to
/// `<tempdir>/agent-browser` when the home directory can't be resolved).
/// This is the parent of `sessions/`, auth storage, and the encryption key.
pub fn get_state_dir() -> PathBuf {
if let Some(home) = dirs::home_dir() {
home.join(".agent-browser")
} else {
std::env::temp_dir().join("agent-browser")
}
}
pub fn get_sessions_dir() -> PathBuf {
get_state_dir().join("sessions")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_storage_state_serialization() {
let state = StorageState {
cookies: vec![Cookie {
name: "session".to_string(),
value: "abc123".to_string(),
domain: ".example.com".to_string(),
path: "/".to_string(),
expires: 0.0,
size: 0,
http_only: true,
secure: false,
session: true,
same_site: Some("Lax".to_string()),
}],
origins: vec![OriginStorage {
origin: "https://example.com".to_string(),
local_storage: vec![StorageEntry {
name: "key".to_string(),
value: "val".to_string(),
}],
session_storage: vec![],
}],
};
let json = serde_json::to_string_pretty(&state).unwrap();
let parsed: StorageState = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.cookies.len(), 1);
assert_eq!(parsed.cookies[0].name, "session");
assert_eq!(parsed.origins.len(), 1);
assert_eq!(parsed.origins[0].local_storage.len(), 1);
}
#[test]
fn test_storage_state_empty() {
let state = StorageState {
cookies: vec![],
origins: vec![],
};
let json = serde_json::to_string(&state).unwrap();
let parsed: StorageState = serde_json::from_str(&json).unwrap();
assert!(parsed.cookies.is_empty());
assert!(parsed.origins.is_empty());
}
#[test]
fn test_state_show_nonexistent_file() {
let result = state_show("/tmp/nonexistent-agent-browser-state-file.json");
assert!(result.is_err());
}
#[test]
fn test_state_clear_nonexistent_file() {
let result = state_clear(Some("/tmp/nonexistent-agent-browser-state-file.json"));
assert!(result.is_err());
}
#[test]
fn test_state_rename_nonexistent() {
let result = state_rename("/tmp/nonexistent-agent-browser-state-file.json", "new-name");
assert!(result.is_err());
assert!(result.unwrap_err().contains("not found"));
}
#[test]
fn test_state_list_returns_json() {
let result = state_list().unwrap();
assert!(result.get("files").is_some());
assert!(result.get("directory").is_some());
}
#[test]
fn test_sessions_dir_path() {
let dir = get_sessions_dir();
assert!(dir.to_string_lossy().contains("sessions"));
}
#[test]
fn test_encrypt_decrypt_roundtrip() {
let plain = b"hello world";
let key = "test-secret-key";
let encrypted = encrypt_data(plain, key).unwrap();
assert!(encrypted.len() > 12);
assert_ne!(&encrypted[12..], plain);
let decrypted = decrypt_data(&encrypted, key).unwrap();
assert_eq!(decrypted, plain);
}
#[test]
fn test_decrypt_wrong_key_fails() {
let plain = b"secret data";
let encrypted = encrypt_data(plain, "key1").unwrap();
let result = decrypt_data(&encrypted, "key2");
assert!(result.is_err());
}
#[test]
fn test_cookie_serde_roundtrip() {
let cookie = Cookie {
name: "test".to_string(),
value: "123".to_string(),
domain: ".test.com".to_string(),
path: "/api".to_string(),
expires: 1700000000.0,
size: 7,
http_only: false,
secure: true,
session: false,
same_site: Some("Strict".to_string()),
};
let json = serde_json::to_value(&cookie).unwrap();
assert_eq!(json["name"], "test");
assert_eq!(json["httpOnly"], false);
assert_eq!(json["secure"], true);
assert_eq!(json["sameSite"], "Strict");
}
#[test]
fn test_dispatch_state_command_routes_state_list() {
let cmd = serde_json::json!({ "action": "state_list" });
let result = dispatch_state_command(&cmd);
assert!(result.is_some());
assert!(result.unwrap().is_ok());
}
#[test]
fn test_dispatch_state_command_returns_none_for_unknown() {
let cmd = serde_json::json!({ "action": "navigate" });
assert!(dispatch_state_command(&cmd).is_none());
}
#[test]
fn test_dispatch_state_command_returns_none_for_missing_action() {
let cmd = serde_json::json!({});
assert!(dispatch_state_command(&cmd).is_none());
}
#[test]
fn test_dispatch_state_show_missing_path() {
let cmd = serde_json::json!({ "action": "state_show" });
let result = dispatch_state_command(&cmd).unwrap();
assert!(result.is_err());
assert_eq!(result.unwrap_err(), "Missing 'path' parameter");
}
#[test]
fn test_dispatch_state_rename_missing_params() {
let cmd = serde_json::json!({ "action": "state_rename" });
let result = dispatch_state_command(&cmd).unwrap();
assert!(result.is_err());
assert_eq!(result.unwrap_err(), "Missing 'path' parameter");
let cmd = serde_json::json!({ "action": "state_rename", "path": "/tmp/test.json" });
let result = dispatch_state_command(&cmd).unwrap();
assert!(result.is_err());
assert_eq!(result.unwrap_err(), "Missing 'name' parameter");
}
}
+237
View File
@@ -0,0 +1,237 @@
//! Stealth anti-detection module.
//!
//! Injects browser-level patches to evade bot detection (creepjs, sannysoft,
//! Cloudflare Turnstile, etc.) by normalizing fingerprint signals that betray
//! headless or automated Chrome instances.
use serde_json::json;
use super::cdp::client::CdpClient;
/// Full stealth JS payload compiled at build time (for --launch mode).
const STEALTH_SCRIPTS_RAW: &str = include_str!("stealth_scripts.js");
/// Minimal stealth script for CDP-attach mode (connecting to user's real Chrome).
/// Only removes navigator.webdriver — the browser's own fingerprint is already real.
/// Minimal stealth script for CDP-attach mode.
/// Emulation.setAutomationOverride handles navigator.webdriver at the native
/// level, so no JS patching is needed in CdpAttach mode. An empty script
/// avoids creating any detectable lie-props artifacts.
const MINIMAL_STEALTH_SCRIPT: &str = "";
/// Chrome launch arguments that reduce automation fingerprint surface.
pub const STEALTH_CHROMIUM_ARGS: &[&str] = &[
"--disable-blink-features=AutomationControlled",
"--use-gl=angle",
"--use-angle=default",
];
/// Connection mode determines which stealth patches to apply.
#[derive(Clone, Copy, PartialEq)]
pub enum StealthMode {
/// Connected to user's real Chrome — minimal patches only (webdriver removal).
/// The browser already has a real fingerprint; heavy patches would create detectable lies.
CdpAttach,
/// Launched a new Chrome instance — apply full stealth patches.
FullLaunch,
}
/// Build the stealth JS payload for the given mode and locale.
pub fn build_stealth_script(mode: StealthMode, locale: Option<&str>) -> String {
if mode == StealthMode::CdpAttach {
return MINIMAL_STEALTH_SCRIPT.to_string();
}
// Full launch mode: inject all patches
let locale = locale.unwrap_or("en-US");
let base_lang = locale.split('-').next().unwrap_or(locale);
let languages: Vec<&str> = if base_lang == locale {
vec![locale]
} else {
vec![locale, base_lang]
};
let config_line = format!(
r#"const __abStealth = {{ locale: "{}", languages: {}, allowWebGLContextFallback: false }};"#,
locale,
serde_json::to_string(&languages).unwrap_or_else(|_| r#"["en-US","en"]"#.to_string()),
);
if let Some(rest) = STEALTH_SCRIPTS_RAW.strip_prefix(
r#"const __abStealth = { locale: "en-US", languages: ["en-US", "en"], allowWebGLContextFallback: false };"#,
) {
format!("{}{}", config_line, rest)
} else {
format!("{}\n{}", config_line, STEALTH_SCRIPTS_RAW)
}
}
/// Apply stealth patches to a browser session.
///
/// In `CdpAttach` mode (user's real Chrome): only removes `navigator.webdriver`.
/// In `FullLaunch` mode (new Chrome): injects all 32 patches + UA override.
pub async fn apply_stealth(
client: &CdpClient,
session_id: &str,
mode: StealthMode,
locale: Option<&str>,
) -> Result<(), String> {
// First: disable the automation flag at the CDP protocol level.
// This tells Chrome to natively set navigator.webdriver = false,
// which is undetectable by lie-detection systems like CreepJS.
// Falls back gracefully on older Chrome versions that don't support this.
let _ = client
.send_command(
"Emulation.setAutomationOverride",
Some(json!({ "enabled": false })),
Some(session_id),
)
.await;
let script = build_stealth_script(mode, locale);
// Inject stealth scripts to run before page JS
client
.send_command(
"Page.addScriptToEvaluateOnNewDocument",
Some(json!({ "source": script })),
Some(session_id),
)
.await?;
// In full launch mode, also override UA to remove HeadlessChrome marker
if mode == StealthMode::FullLaunch {
let ua = get_browser_user_agent(client, session_id).await;
if let Some(ua) = ua {
let cleaned = ua.replace("HeadlessChrome", "Chrome");
if cleaned != ua {
client
.send_command(
"Emulation.setUserAgentOverride",
Some(json!({
"userAgent": cleaned,
"acceptLanguage": locale.unwrap_or("en-US"),
"platform": platform_string(),
"userAgentMetadata": build_ua_metadata(&cleaned, locale),
})),
Some(session_id),
)
.await?;
}
}
}
Ok(())
}
/// Get the browser's User-Agent string via CDP.
async fn get_browser_user_agent(client: &CdpClient, session_id: &str) -> Option<String> {
let result = client
.send_command(
"Runtime.evaluate",
Some(json!({ "expression": "navigator.userAgent", "returnByValue": true })),
Some(session_id),
)
.await
.ok()?;
result
.get("result")
.and_then(|r| r.get("value"))
.and_then(|v| v.as_str())
.map(String::from)
}
/// Also run stealth script on the current page (for already-loaded pages after CDP attach).
pub async fn apply_stealth_to_current_page(
client: &CdpClient,
session_id: &str,
mode: StealthMode,
locale: Option<&str>,
) -> Result<(), String> {
let script = build_stealth_script(mode, locale);
client
.send_command(
"Runtime.evaluate",
Some(json!({
"expression": script,
"returnByValue": true,
})),
Some(session_id),
)
.await?;
Ok(())
}
/// Strip sourceURL comments from CDP expressions to avoid leaking
/// automation-framework identifiers in stack traces.
pub fn strip_source_url_labels(input: &str) -> String {
// Remove //# sourceURL=... and //@ sourceURL=...
let re_line = regex_lite::Regex::new(r"(?i)\n?\s*//[@#]\s*sourceURL=[^\n\r]*").unwrap();
let output = re_line.replace_all(input, "");
// Remove /*# sourceURL=...*/ block comments
let re_block =
regex_lite::Regex::new(r"(?is)\n?\s*/\*[@#]\s*sourceURL=[\s\S]*?\*/").unwrap();
re_block.replace_all(&output, "").to_string()
}
fn platform_string() -> &'static str {
if cfg!(target_os = "macos") {
"macOS"
} else if cfg!(target_os = "windows") {
"Win32"
} else {
"Linux"
}
}
fn platform_hint() -> &'static str {
if cfg!(target_os = "macos") {
"macOS"
} else if cfg!(target_os = "windows") {
"Windows"
} else {
"Linux"
}
}
fn platform_version_hint() -> &'static str {
if cfg!(target_os = "macos") {
"14.0.0"
} else if cfg!(target_os = "windows") {
"10.0.0"
} else {
"6.5.0"
}
}
fn build_ua_metadata(ua: &str, locale: Option<&str>) -> serde_json::Value {
// Extract Chrome version from UA string
let chrome_version = ua
.split("Chrome/")
.nth(1)
.and_then(|s| s.split_whitespace().next())
.unwrap_or("130.0.0.0");
let major = chrome_version.split('.').next().unwrap_or("130");
let _lang = locale.unwrap_or("en-US");
json!({
"brands": [
{ "brand": "Chromium", "version": major },
{ "brand": "Google Chrome", "version": major },
{ "brand": "Not?A_Brand", "version": "99" },
],
"fullVersionList": [
{ "brand": "Chromium", "version": chrome_version },
{ "brand": "Google Chrome", "version": chrome_version },
{ "brand": "Not?A_Brand", "version": "99.0.0.0" },
],
"fullVersion": chrome_version,
"platform": platform_hint(),
"platformVersion": platform_version_hint(),
"architecture": if cfg!(target_arch = "aarch64") { "arm" } else { "x86" },
"model": "",
"mobile": false,
"bitness": "64",
"wow64": false,
})
}
File diff suppressed because it is too large Load Diff
+94
View File
@@ -0,0 +1,94 @@
use serde_json::{json, Value};
use super::cdp::client::CdpClient;
use super::cdp::types::EvaluateParams;
pub async fn storage_get(
client: &CdpClient,
session_id: &str,
storage_type: &str,
key: Option<&str>,
) -> Result<Value, String> {
let st = storage_js_name(storage_type);
if let Some(k) = key {
let js = format!(
"{}.getItem({})",
st,
serde_json::to_string(k).unwrap_or_default()
);
let result = eval_simple(client, session_id, &js).await?;
Ok(json!({ "key": k, "value": result }))
} else {
let js = format!(
r#"(() => {{
const s = {};
const data = {{}};
for (let i = 0; i < s.length; i++) {{
const key = s.key(i);
data[key] = s.getItem(key);
}}
return data;
}})()"#,
st
);
let result = eval_simple(client, session_id, &js).await?;
Ok(json!({ "data": result }))
}
}
pub async fn storage_set(
client: &CdpClient,
session_id: &str,
storage_type: &str,
key: &str,
value: &str,
) -> Result<(), String> {
let st = storage_js_name(storage_type);
let js = format!(
"{}.setItem({}, {})",
st,
serde_json::to_string(key).unwrap_or_default(),
serde_json::to_string(value).unwrap_or_default(),
);
eval_simple(client, session_id, &js).await?;
Ok(())
}
pub async fn storage_clear(
client: &CdpClient,
session_id: &str,
storage_type: &str,
) -> Result<(), String> {
let st = storage_js_name(storage_type);
let js = format!("{}.clear()", st);
eval_simple(client, session_id, &js).await?;
Ok(())
}
fn storage_js_name(storage_type: &str) -> &str {
match storage_type {
"session" => "sessionStorage",
_ => "localStorage",
}
}
async fn eval_simple(client: &CdpClient, session_id: &str, js: &str) -> Result<Value, String> {
let result: super::cdp::types::EvaluateResult = client
.send_command_typed(
"Runtime.evaluate",
&EvaluateParams {
expression: js.to_string(),
return_by_value: Some(true),
await_promise: Some(false),
},
Some(session_id),
)
.await?;
if let Some(ref details) = result.exception_details {
return Err(format!("Storage error: {}", details.text));
}
Ok(result.result.value.unwrap_or(Value::Null))
}
+325
View File
@@ -0,0 +1,325 @@
use serde_json::{json, Value};
use std::sync::Arc;
use tokio::sync::{broadcast, watch, Mutex, RwLock};
use crate::native::cdp::client::CdpClient;
use crate::native::network;
use super::timestamp_ms;
/// Background task that subscribes to CDP events and broadcasts screencast frames in real-time.
/// Also handles auto-start/stop of screencast based on WebSocket client count.
#[allow(clippy::too_many_arguments)]
pub(super) async fn cdp_event_loop(
frame_tx: broadcast::Sender<String>,
client_slot: Arc<RwLock<Option<Arc<CdpClient>>>>,
client_notify: Arc<tokio::sync::Notify>,
screencasting: Arc<Mutex<bool>>,
client_count: Arc<Mutex<usize>>,
cdp_session_id: Arc<RwLock<Option<String>>>,
viewport_width: Arc<Mutex<u32>>,
viewport_height: Arc<Mutex<u32>>,
last_frame: Arc<RwLock<Option<String>>>,
last_tabs: Arc<RwLock<Vec<Value>>>,
last_engine: Arc<RwLock<String>>,
recording: Arc<Mutex<bool>>,
mut shutdown_rx: watch::Receiver<bool>,
) {
loop {
tokio::select! {
changed = shutdown_rx.changed() => {
if changed.is_err() || *shutdown_rx.borrow() {
let session_id = cdp_session_id.read().await.clone();
if *screencasting.lock().await {
if let Some(ref client) = *client_slot.read().await {
let _ = client
.send_command_no_params("Page.stopScreencast", session_id.as_deref())
.await;
}
let mut sc = screencasting.lock().await;
*sc = false;
}
return;
}
}
_ = client_notify.notified() => {}
}
let count = *client_count.lock().await;
let guard = client_slot.read().await;
if count > 0 {
if let Some(ref client) = *guard {
let mut event_rx = client.subscribe();
let client_arc = Arc::clone(client);
drop(guard);
let session_id = cdp_session_id.read().await.clone();
let vw = *viewport_width.lock().await;
let vh = *viewport_height.lock().await;
let eng = last_engine.read().await.clone();
let supports_screencast = eng == "chrome";
if supports_screencast {
let _ = client_arc
.send_command(
"Page.startScreencast",
Some(json!({
"format": "jpeg",
"quality": 80,
"maxWidth": vw,
"maxHeight": vh,
"everyNthFrame": 1,
})),
session_id.as_deref(),
)
.await;
}
{
let mut sc = screencasting.lock().await;
*sc = supports_screencast;
}
let rec = *recording.lock().await;
let status = json!({
"type": "status",
"connected": true,
"screencasting": supports_screencast,
"viewportWidth": vw,
"viewportHeight": vh,
"engine": eng,
"recording": rec,
});
let _ = frame_tx.send(status.to_string());
loop {
tokio::select! {
changed = shutdown_rx.changed() => {
if changed.is_err() || *shutdown_rx.borrow() {
if supports_screencast {
let session_id = cdp_session_id.read().await.clone();
let _ = client_arc
.send_command_no_params("Page.stopScreencast", session_id.as_deref())
.await;
}
let mut sc = screencasting.lock().await;
*sc = false;
return;
}
}
event = event_rx.recv() => {
match event {
Ok(evt) => {
if evt.method == "Page.frameNavigated" {
if let Some(frame) = evt.params.get("frame") {
let is_main = frame
.get("parentId")
.and_then(|v| v.as_str())
.is_none_or(|s| s.is_empty());
if is_main {
if let Some(url) = frame.get("url").and_then(|v| v.as_str()) {
{
let mut tabs = last_tabs.write().await;
for tab in tabs.iter_mut() {
if tab.get("active").and_then(|v| v.as_bool()).unwrap_or(false) {
tab.as_object_mut().map(|o| o.insert("url".to_string(), json!(url)));
}
}
}
let msg = json!({
"type": "url",
"url": url,
"timestamp": timestamp_ms(),
});
let _ = frame_tx.send(msg.to_string());
}
}
}
} else if evt.method == "Page.screencastFrame" {
if let Some(sid) = evt.params.get("sessionId").and_then(|v| v.as_i64()) {
let _ = client_arc.send_command(
"Page.screencastFrameAck",
Some(json!({ "sessionId": sid })),
evt.session_id.as_deref(),
).await;
}
if let Some(data) = evt.params.get("data").and_then(|v| v.as_str()) {
let meta = evt.params.get("metadata");
let msg = json!({
"type": "frame",
"data": data,
"metadata": {
"offsetTop": meta.and_then(|m| m.get("offsetTop")).and_then(|v| v.as_f64()).unwrap_or(0.0),
"pageScaleFactor": meta.and_then(|m| m.get("pageScaleFactor")).and_then(|v| v.as_f64()).unwrap_or(1.0),
"deviceWidth": vw,
"deviceHeight": vh,
"scrollOffsetX": meta.and_then(|m| m.get("scrollOffsetX")).and_then(|v| v.as_f64()).unwrap_or(0.0),
"scrollOffsetY": meta.and_then(|m| m.get("scrollOffsetY")).and_then(|v| v.as_f64()).unwrap_or(0.0),
"timestamp": meta.and_then(|m| m.get("timestamp")).and_then(|v| v.as_u64()).unwrap_or(0),
}
});
let msg_str = msg.to_string();
{
let mut lf = last_frame.write().await;
*lf = Some(msg_str.clone());
}
let _ = frame_tx.send(msg_str);
}
} else if evt.method == "Runtime.consoleAPICalled" {
let level = evt.params.get("type")
.and_then(|v| v.as_str())
.unwrap_or("log");
let raw_args = evt.params.get("args")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
let text = network::format_console_args(&raw_args);
if !text.is_empty() {
let mut msg = json!({
"type": "console",
"level": level,
"text": text,
"timestamp": timestamp_ms(),
});
if !raw_args.is_empty() {
msg.as_object_mut().unwrap().insert(
"args".to_string(),
Value::Array(raw_args),
);
}
let _ = frame_tx.send(msg.to_string());
}
} else if evt.method == "Runtime.exceptionThrown" {
let text = evt.params.get("exceptionDetails")
.and_then(|d| {
d.get("exception")
.and_then(|e| e.get("description").and_then(|v| v.as_str()))
.or_else(|| d.get("text").and_then(|v| v.as_str()))
})
.unwrap_or("Unknown error");
let line = evt.params.get("exceptionDetails")
.and_then(|d| d.get("lineNumber").and_then(|v| v.as_i64()));
let column = evt.params.get("exceptionDetails")
.and_then(|d| d.get("columnNumber").and_then(|v| v.as_i64()));
let msg = json!({
"type": "page_error",
"text": text,
"line": line,
"column": column,
"timestamp": timestamp_ms(),
});
let _ = frame_tx.send(msg.to_string());
}
}
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(broadcast::error::RecvError::Closed) => break,
}
}
_ = client_notify.notified() => {
let count = *client_count.lock().await;
let new_session_id = cdp_session_id.read().await.clone();
if count == 0 {
if supports_screencast {
let _ = client_arc
.send_command_no_params("Page.stopScreencast", session_id.as_deref())
.await;
}
let mut sc = screencasting.lock().await;
*sc = false;
break;
}
let client_changed = {
let guard = client_slot.read().await;
let same = guard
.as_ref()
.is_some_and(|c| Arc::ptr_eq(c, &client_arc));
!same
};
let session_changed = new_session_id != session_id;
let new_vw = *viewport_width.lock().await;
let new_vh = *viewport_height.lock().await;
let viewport_changed = new_vw != vw || new_vh != vh;
if client_changed || session_changed || viewport_changed {
if supports_screencast {
let _ = client_arc
.send_command_no_params("Page.stopScreencast", session_id.as_deref())
.await;
}
let mut sc = screencasting.lock().await;
*sc = false;
client_notify.notify_one();
break;
}
}
}
}
} else {
drop(guard);
}
} else {
let was_screencasting = *screencasting.lock().await;
if was_screencasting {
if let Some(ref client) = *guard {
let session_id = cdp_session_id.read().await.clone();
let _ = client
.send_command_no_params("Page.stopScreencast", session_id.as_deref())
.await;
}
let mut sc = screencasting.lock().await;
*sc = false;
}
drop(guard);
}
}
}
pub async fn start_screencast(
client: &CdpClient,
session_id: &str,
format: &str,
quality: i32,
max_width: i32,
max_height: i32,
) -> Result<(), String> {
client
.send_command(
"Page.startScreencast",
Some(json!({
"format": format,
"quality": quality,
"maxWidth": max_width,
"maxHeight": max_height,
"everyNthFrame": 1,
})),
Some(session_id),
)
.await?;
Ok(())
}
pub async fn stop_screencast(client: &CdpClient, session_id: &str) -> Result<(), String> {
client
.send_command_no_params("Page.stopScreencast", Some(session_id))
.await?;
Ok(())
}
pub async fn ack_screencast_frame(
client: &CdpClient,
session_id: &str,
screencast_session_id: i64,
) -> Result<(), String> {
client
.send_command(
"Page.screencastFrameAck",
Some(json!({ "sessionId": screencast_session_id })),
Some(session_id),
)
.await?;
Ok(())
}
+970
View File
@@ -0,0 +1,970 @@
use std::sync::OnceLock;
use serde_json::{json, Value};
use tokio::io::AsyncWriteExt;
use super::http::cors_headers_for_origin;
pub(crate) const DEFAULT_AI_GATEWAY_URL: &str = "https://ai-gateway.vercel.sh";
static HTTP_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
pub(crate) fn http_client() -> &'static reqwest::Client {
HTTP_CLIENT.get_or_init(reqwest::Client::new)
}
pub(crate) fn is_chat_enabled() -> bool {
std::env::var("AI_GATEWAY_API_KEY").is_ok()
}
pub(super) fn chat_status_json() -> String {
let enabled = is_chat_enabled();
let mut obj = json!({ "enabled": enabled });
if enabled {
if let Ok(model) = std::env::var("AI_GATEWAY_MODEL") {
obj["model"] = Value::String(model);
}
}
obj.to_string()
}
pub(super) async fn handle_models_request(
stream: &mut tokio::net::TcpStream,
origin: Option<&str>,
) {
let cors = cors_headers_for_origin(origin);
let gateway_url = std::env::var("AI_GATEWAY_URL")
.unwrap_or_else(|_| DEFAULT_AI_GATEWAY_URL.to_string())
.trim_end_matches('/')
.to_string();
let api_key = match std::env::var("AI_GATEWAY_API_KEY") {
Ok(k) => k,
Err(_) => {
let body = r#"{"data":[]}"#;
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n",
body.len()
);
let _ = stream.write_all(resp.as_bytes()).await;
let _ = stream.write_all(body.as_bytes()).await;
return;
}
};
let url = format!("{}/v1/models", gateway_url);
let client = http_client();
let result = client
.get(&url)
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await;
let body = match result {
Ok(r) if r.status().is_success() => r
.text()
.await
.unwrap_or_else(|_| r#"{"data":[]}"#.to_string()),
_ => r#"{"data":[]}"#.to_string(),
};
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n",
body.len()
);
let _ = stream.write_all(resp.as_bytes()).await;
let _ = stream.write_all(body.as_bytes()).await;
}
const SKILL_NAMES: &[&str] = &["agent-browser", "slack", "electron", "dogfood", "agentcore"];
/// Locate the `skills/` directory by walking up from the executable.
/// Works for npm installs (binary in `bin/`, skills at `../skills/`) and
/// dev builds (binary deep in `cli/target/`, skills at repo root).
fn find_skills_dir() -> Option<std::path::PathBuf> {
let exe = std::env::current_exe().ok()?;
let real = exe.canonicalize().unwrap_or(exe);
let mut dir = real.parent();
while let Some(d) = dir {
let candidate = d.join("skills");
if candidate.join("agent-browser").join("SKILL.md").exists() {
return Some(candidate);
}
dir = d.parent();
}
None
}
fn load_skills() -> Vec<(String, String)> {
let Some(skills_dir) = find_skills_dir() else {
return Vec::new();
};
SKILL_NAMES
.iter()
.filter_map(|name| {
let path = skills_dir.join(name).join("SKILL.md");
let content = std::fs::read_to_string(&path).ok()?;
Some((name.to_string(), content))
})
.collect()
}
fn strip_frontmatter(s: &str) -> &str {
if !s.starts_with("---") {
return s;
}
if let Some(end) = s[3..].find("---") {
let after = &s[3 + end + 3..];
after.trim_start_matches(['\n', '\r'])
} else {
s
}
}
pub(crate) fn get_system_prompt() -> &'static str {
static PROMPT: OnceLock<String> = OnceLock::new();
PROMPT.get_or_init(|| {
let skills = load_skills();
let mut sections = String::new();
for (name, content) in &skills {
let body = strip_frontmatter(content);
sections.push_str(&format!("\n\n<skill name=\"{}\">\n{}\n</skill>", name, body.trim()));
}
format!(
r#"You are an AI assistant that controls a browser through agent-browser. You have an active browser session, but you can also create new sessions.
RULES:
- You MUST use the agent_browser tool for every browser action. NEVER claim you performed an action without calling the tool.
- If the user asks you to do something, call the tool first, then describe the result.
- If a request is outside your capabilities (e.g. system operations), say so honestly. Do not improvise or pretend.
- One tool call per command. Do not chain with `&&` or `;`.
- Do not add `--json`.
- Do not run non-agent-browser programs.
- Keep responses concise.
- For screenshots, omit the path argument so they save to the default location (which will be displayed inline). Screenshots from tool calls are ALREADY shown to the user. Do NOT re-display them with markdown image syntax in your text response. Never use `![...]()` to reference screenshots.
- To create a new session: add `--session <name>` to any command (e.g. `agent-browser --session my-session open https://example.com`). If the session does not exist, it will be created automatically.
- To use a different browser engine: add `--engine <engine>` (e.g. `agent-browser --session lp-session --engine lightpanda open https://example.com`). Supported engines: chrome (default), lightpanda.
The following skill references describe agent-browser capabilities in detail. Use them when deciding which commands to run and how to approach tasks.
{sections}"#,
)
})
}
pub(crate) const CHAT_TOOLS: &str = r#"[{"type":"function","function":{"name":"agent_browser","description":"Execute an agent-browser command. Runs against the active session by default. Add --session <name> to target or create a different session, and --engine <engine> to choose a browser engine.","parameters":{"type":"object","properties":{"command":{"type":"string","description":"The command to execute, e.g. 'agent-browser open https://google.com' or 'agent-browser --session new-session open https://example.com' or 'agent-browser snapshot -i' or 'agent-browser click @e3'"}},"required":["command"]}}}]"#;
pub(crate) const COMPACT_THRESHOLD_CHARS: usize = 200_000;
pub(crate) const KEEP_RECENT_MESSAGES: usize = 6;
pub(crate) fn estimate_chars(messages: &[Value]) -> usize {
messages
.iter()
.map(|m| {
let content_len = m
.get("content")
.map(|c| {
if let Some(s) = c.as_str() {
s.len()
} else {
c.to_string().len()
}
})
.unwrap_or(0);
let tc_len = m
.get("tool_calls")
.map(|t| t.to_string().len())
.unwrap_or(0);
content_len + tc_len
})
.sum()
}
pub(crate) fn find_safe_split(messages: &[Value], keep_recent: usize) -> usize {
if messages.len() <= keep_recent + 1 {
return 1;
}
let desired = messages.len() - keep_recent;
for i in (1..=desired).rev() {
if messages[i].get("role").and_then(|r| r.as_str()) == Some("user") {
return i;
}
}
desired.max(1)
}
fn build_summary_text(messages: &[Value]) -> String {
let mut text = String::new();
for msg in messages {
let role = msg
.get("role")
.and_then(|r| r.as_str())
.unwrap_or("unknown");
if let Some(content) = msg.get("content").and_then(|c| c.as_str()) {
if !content.is_empty() {
let truncated = if content.len() > 2000 {
format!("{}...[truncated]", &content[..2000])
} else {
content.to_string()
};
text.push_str(&format!("[{}] {}\n\n", role, truncated));
}
}
if let Some(tcs) = msg.get("tool_calls").and_then(|t| t.as_array()) {
for tc in tcs {
let name = tc
.get("function")
.and_then(|f| f.get("name"))
.and_then(|n| n.as_str())
.unwrap_or("");
let args = tc
.get("function")
.and_then(|f| f.get("arguments"))
.and_then(|a| a.as_str())
.unwrap_or("");
text.push_str(&format!("[assistant tool:{}] {}\n", name, args));
}
}
}
text
}
pub(crate) async fn summarize_for_compaction(
client: &reqwest::Client,
url: &str,
api_key: &str,
model: &str,
messages: &[Value],
) -> Option<String> {
let conversation = build_summary_text(messages);
if conversation.is_empty() {
return None;
}
let body = json!({
"model": model,
"messages": [
{
"role": "system",
"content": "Summarize this browser automation conversation concisely. Preserve: URLs visited, actions performed, current page state, errors encountered, and user goals. Output only the summary."
},
{
"role": "user",
"content": conversation
}
],
"max_tokens": 1024,
"stream": false,
});
let resp = client
.post(url)
.header("Authorization", format!("Bearer {}", api_key))
.header("Content-Type", "application/json")
.body(body.to_string())
.send()
.await
.ok()?;
if !resp.status().is_success() {
return None;
}
let result: Value = resp.json().await.ok()?;
result
.get("choices")
.and_then(|c| c.get(0))
.and_then(|c| c.get("message"))
.and_then(|m| m.get("content"))
.and_then(|c| c.as_str())
.map(|s| s.to_string())
}
const SCREENSHOT_MAX_WIDTH: u32 = 1024;
const SCREENSHOT_JPEG_QUALITY: u8 = 40;
fn compress_image_to_jpeg(raw_bytes: &[u8]) -> Option<Vec<u8>> {
let img = image::load_from_memory(raw_bytes).ok()?;
let img = if img.width() > SCREENSHOT_MAX_WIDTH {
img.resize(
SCREENSHOT_MAX_WIDTH,
u32::MAX,
image::imageops::FilterType::Triangle,
)
} else {
img
};
let mut buf = std::io::Cursor::new(Vec::new());
let encoder =
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, SCREENSHOT_JPEG_QUALITY);
img.write_with_encoder(encoder).ok()?;
Some(buf.into_inner())
}
fn has_image_extension(s: &str) -> bool {
let lower = s.to_lowercase();
lower.ends_with(".png") || lower.ends_with(".jpg") || lower.ends_with(".jpeg")
}
fn extract_image_path(text: &str) -> Option<String> {
for line in text.lines() {
let trimmed = line.trim();
// Whole line is a path (handles paths with spaces)
if has_image_extension(trimmed) && std::path::Path::new(trimmed).exists() {
return Some(trimmed.to_string());
}
for suffix in [".png", ".jpg", ".jpeg"] {
if let Some(pos) = trimmed.to_lowercase().rfind(suffix) {
let end = pos + suffix.len();
let candidate = &trimmed[..end];
let start = candidate
.rfind(|c: char| c.is_whitespace())
.map(|i| i + 1)
.unwrap_or(0);
let path = &candidate[start..];
if !path.is_empty() && std::path::Path::new(path).exists() {
return Some(path.to_string());
}
}
}
}
None
}
fn enrich_tool_output(result: &str) -> String {
let Some(path) = extract_image_path(result) else {
return result.to_string();
};
let Ok(raw_bytes) = std::fs::read(&path) else {
return result.to_string();
};
let (jpeg_bytes, mime) = match compress_image_to_jpeg(&raw_bytes) {
Some(compressed) => (compressed, "image/jpeg"),
None => {
let lower = path.to_lowercase();
(
raw_bytes,
if lower.ends_with(".png") {
"image/png"
} else {
"image/jpeg"
},
)
}
};
let b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &jpeg_bytes);
let data_url = format!("data:{};base64,{}", mime, b64);
json!({
"text": result,
"image": data_url
})
.to_string()
}
const ALLOWED_COMMANDS: &[&str] = &[
"open",
"goto",
"navigate",
"back",
"forward",
"reload",
"click",
"dblclick",
"fill",
"type",
"hover",
"focus",
"check",
"uncheck",
"select",
"drag",
"upload",
"download",
"press",
"key",
"keydown",
"keyup",
"keyboard",
"scroll",
"scrollintoview",
"scrollinto",
"wait",
"screenshot",
"pdf",
"snapshot",
"eval",
"close",
"quit",
"exit",
"inspect",
"auth",
"confirm",
"deny",
"connect",
"cookies",
"storage",
"window",
"frame",
"dialog",
"trace",
"profiler",
"record",
"har",
"network",
"title",
"url",
"console",
"errors",
"highlight",
"state",
"emulate",
"video",
"tap",
"swipe",
"device",
"batch",
"diff",
"find",
"role",
"text",
"label",
"placeholder",
"alt",
"testid",
"first",
"last",
"nth",
"mouse",
"touchscreen",
"attribute",
"property",
"set",
"get",
"is",
"stream",
"tab",
"clipboard",
"session",
];
const ALLOWED_GLOBAL_FLAGS: &[&str] = &["--session", "--engine"];
pub(crate) async fn execute_chat_tool(session: &str, command: &str) -> String {
let exe = match std::env::current_exe() {
Ok(p) => p,
Err(e) => return format!("Failed to resolve executable: {}", e),
};
let single = command.split("&&").next().unwrap_or(command);
let single = single.split(';').next().unwrap_or(single).trim();
let stripped = single.strip_prefix("agent-browser ").unwrap_or(single);
let words = crate::commands::shell_words_split(stripped);
let mut global_flags: Vec<String> = Vec::new();
let mut cmd_words: Vec<String> = Vec::new();
let mut has_session_flag = false;
let mut i = 0;
while i < words.len() {
if ALLOWED_GLOBAL_FLAGS.contains(&words[i].as_str()) {
if words[i] == "--session" {
has_session_flag = true;
}
global_flags.push(words[i].clone());
if i + 1 < words.len() {
global_flags.push(words[i + 1].clone());
i += 2;
} else {
i += 1;
}
} else {
cmd_words.push(words[i].clone());
i += 1;
}
}
let first_cmd = cmd_words.first().map(|s| s.as_str()).unwrap_or("");
if !ALLOWED_COMMANDS.contains(&first_cmd) {
return format!(
"Blocked: '{}' is not a valid agent-browser command.",
first_cmd
);
}
let mut args: Vec<String> = Vec::new();
if !has_session_flag {
args.push("--session".into());
args.push(session.into());
}
args.extend(global_flags);
args.extend(cmd_words);
let mut cmd = tokio::process::Command::new(&exe);
cmd.args(&args)
.env_remove("AGENT_BROWSER_DASHBOARD")
.env_remove("AGENT_BROWSER_DASHBOARD_PORT")
.env_remove("AGENT_BROWSER_STREAM_PORT");
match cmd.output().await {
Ok(output) => {
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if stdout.is_empty() && !stderr.is_empty() {
stderr
} else if stdout.is_empty() {
"Command completed with no output.".to_string()
} else {
stdout
}
}
Err(e) => format!("Failed to execute command: {}", e),
}
}
async fn stream_gateway_response(
stream: &mut tokio::net::TcpStream,
gw_response: reqwest::Response,
) -> Vec<(String, String, String)> {
use futures_util::StreamExt as _;
let mut text_part_id = uuid::Uuid::new_v4().to_string();
let mut text_started = false;
let mut tool_calls: Vec<(String, String, String)> = Vec::new();
let mut tool_call_args: std::collections::HashMap<usize, (String, String, String)> =
std::collections::HashMap::new();
let mut byte_stream = gw_response.bytes_stream();
let mut buffer = String::new();
while let Some(chunk_result) = byte_stream.next().await {
let chunk = match chunk_result {
Ok(c) => c,
Err(_) => break,
};
buffer.push_str(&String::from_utf8_lossy(&chunk));
while let Some(newline_pos) = buffer.find('\n') {
let line = buffer[..newline_pos].trim_end_matches('\r').to_string();
buffer = buffer[newline_pos + 1..].to_string();
if line.is_empty() {
continue;
}
let Some(data) = line.strip_prefix("data: ") else {
continue;
};
if data == "[DONE]" {
if text_started {
let ev = format!("data: {}\n\n", json!({"type":"text-end","id":text_part_id}));
let _ = stream.write_all(ev.as_bytes()).await;
}
let mut indices: Vec<usize> = tool_call_args.keys().copied().collect();
indices.sort();
for idx in indices {
if let Some(tc) = tool_call_args.remove(&idx) {
tool_calls.push(tc);
}
}
return tool_calls;
}
let Ok(sse_json) = serde_json::from_str::<Value>(data) else {
continue;
};
let delta = sse_json
.get("choices")
.and_then(|c| c.get(0))
.and_then(|c| c.get("delta"));
let Some(delta) = delta else { continue };
if let Some(text) = delta.get("content").and_then(|c| c.as_str()) {
if !text.is_empty() {
if !text_started {
let ev = format!(
"data: {}\n\n",
json!({"type":"text-start","id":text_part_id})
);
if stream.write_all(ev.as_bytes()).await.is_err() {
return tool_calls;
}
text_started = true;
}
let ev = format!(
"data: {}\n\n",
json!({"type":"text-delta","id":text_part_id,"delta":text})
);
if stream.write_all(ev.as_bytes()).await.is_err() {
return tool_calls;
}
}
}
if let Some(tcs) = delta.get("tool_calls").and_then(|t| t.as_array()) {
if text_started {
let ev = format!("data: {}\n\n", json!({"type":"text-end","id":text_part_id}));
let _ = stream.write_all(ev.as_bytes()).await;
text_started = false;
text_part_id = uuid::Uuid::new_v4().to_string();
}
for tc in tcs {
let idx = tc.get("index").and_then(|i| i.as_u64()).unwrap_or(0) as usize;
if let std::collections::hash_map::Entry::Vacant(e) = tool_call_args.entry(idx)
{
let id = tc
.get("id")
.and_then(|i| i.as_str())
.unwrap_or("")
.to_string();
let name = tc
.get("function")
.and_then(|f| f.get("name"))
.and_then(|n| n.as_str())
.unwrap_or("")
.to_string();
let ev = format!(
"data: {}\n\n",
json!({"type":"tool-input-start","toolCallId":id,"toolName":name})
);
let _ = stream.write_all(ev.as_bytes()).await;
e.insert((id, name, String::new()));
}
if let Some(arg_delta) = tc
.get("function")
.and_then(|f| f.get("arguments"))
.and_then(|a| a.as_str())
{
let entry = tool_call_args.get_mut(&idx).unwrap();
entry.2.push_str(arg_delta);
let ev = format!(
"data: {}\n\n",
json!({"type":"tool-input-delta","toolCallId":entry.0,"inputTextDelta":arg_delta})
);
let _ = stream.write_all(ev.as_bytes()).await;
}
}
}
}
}
if text_started {
let ev = format!("data: {}\n\n", json!({"type":"text-end","id":text_part_id}));
let _ = stream.write_all(ev.as_bytes()).await;
}
let mut indices: Vec<usize> = tool_call_args.keys().copied().collect();
indices.sort();
for idx in indices {
if let Some(tc) = tool_call_args.remove(&idx) {
tool_calls.push(tc);
}
}
tool_calls
}
pub(super) async fn handle_chat_request(
stream: &mut tokio::net::TcpStream,
body: &str,
origin: Option<&str>,
) {
let cors = cors_headers_for_origin(origin);
let gateway_url = std::env::var("AI_GATEWAY_URL")
.unwrap_or_else(|_| DEFAULT_AI_GATEWAY_URL.to_string())
.trim_end_matches('/')
.to_string();
let api_key = match std::env::var("AI_GATEWAY_API_KEY") {
Ok(k) => k,
Err(_) => {
let err = r#"{"error":"AI_GATEWAY_API_KEY not set. Set the AI_GATEWAY_API_KEY environment variable to enable AI chat."}"#;
let resp = format!(
"HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n",
err.len()
);
let _ = stream.write_all(resp.as_bytes()).await;
let _ = stream.write_all(err.as_bytes()).await;
return;
}
};
let default_model = std::env::var("AI_GATEWAY_MODEL")
.unwrap_or_else(|_| "anthropic/claude-sonnet-4.6".to_string());
let parsed: Value = match serde_json::from_str(body) {
Ok(v) => v,
Err(e) => {
let err = format!(r#"{{"error":"Invalid JSON: {}"}}"#, e);
let resp = format!(
"HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{cors}\r\n",
err.len()
);
let _ = stream.write_all(resp.as_bytes()).await;
let _ = stream.write_all(err.as_bytes()).await;
return;
}
};
let messages = parsed.get("messages").cloned().unwrap_or(json!([]));
let model = parsed
.get("model")
.and_then(|v| v.as_str())
.unwrap_or(&default_model)
.to_string();
let session = parsed
.get("session")
.and_then(|v| v.as_str())
.unwrap_or("default")
.to_string();
let mut openai_messages: Vec<Value> =
vec![json!({"role": "system", "content": get_system_prompt()})];
let mut frontend_boundaries: Vec<usize> = Vec::new();
let frontend_arr = messages.as_array();
let frontend_count = frontend_arr.map(|a| a.len()).unwrap_or(0);
if let Some(arr) = frontend_arr {
for msg in arr {
frontend_boundaries.push(openai_messages.len());
let Some(role) = msg.get("role").and_then(|r| r.as_str()) else {
continue;
};
if let Some(parts) = msg.get("parts").and_then(|p| p.as_array()) {
let mut content_parts: Vec<Value> = Vec::new();
for part in parts {
match part.get("type").and_then(|t| t.as_str()) {
Some("text") => {
if let Some(text) = part.get("text").and_then(|t| t.as_str()) {
if !text.is_empty() {
content_parts.push(json!({"type": "text", "text": text}));
}
}
}
Some("file") => {
if let (Some(url), Some(media_type)) = (
part.get("url").and_then(|u| u.as_str()),
part.get("mediaType").and_then(|m| m.as_str()),
) {
if media_type.starts_with("image/") {
content_parts.push(json!({
"type": "image_url",
"image_url": { "url": url }
}));
}
}
}
_ => {}
}
}
if !content_parts.is_empty() {
let content = if content_parts.len() == 1
&& content_parts[0].get("type").and_then(|t| t.as_str()) == Some("text")
{
content_parts[0]["text"].clone()
} else {
json!(content_parts)
};
openai_messages.push(json!({"role": role, "content": content}));
}
} else if let Some(content) = msg.get("content").and_then(|c| c.as_str()) {
openai_messages.push(json!({"role": role, "content": content}));
}
}
}
let tools: Value = serde_json::from_str(CHAT_TOOLS).unwrap();
let url = format!("{}/v1/chat/completions", gateway_url);
let client = http_client();
let total_chars = estimate_chars(&openai_messages);
let mut compaction_summary: Option<String> = None;
let mut compaction_failed = false;
let mut keep_last_n: usize = frontend_count;
if total_chars > COMPACT_THRESHOLD_CHARS && openai_messages.len() > KEEP_RECENT_MESSAGES + 2 {
let split = find_safe_split(&openai_messages, KEEP_RECENT_MESSAGES);
let to_summarize = &openai_messages[1..split];
if let Some(summary) =
summarize_for_compaction(client, &url, &api_key, &model, to_summarize).await
{
let summary_msg = json!({
"role": "system",
"content": format!("[Conversation summary]\n{}", summary)
});
let recent = openai_messages[split..].to_vec();
openai_messages = vec![openai_messages[0].clone(), summary_msg];
openai_messages.extend(recent);
let kept_frontend = frontend_boundaries
.iter()
.filter(|&&boundary| boundary >= split)
.count();
keep_last_n = kept_frontend;
compaction_summary = Some(summary);
} else {
compaction_failed = true;
}
}
let headers = format!(
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\nx-vercel-ai-ui-message-stream: v1\r\n{cors}\r\n"
);
if stream.write_all(headers.as_bytes()).await.is_err() {
return;
}
let message_id = uuid::Uuid::new_v4().to_string();
let start_ev = format!(
"data: {}\n\n",
json!({"type":"start","messageId":message_id})
);
if stream.write_all(start_ev.as_bytes()).await.is_err() {
return;
}
if let Some(ref summary) = compaction_summary {
let ev = format!(
"data: {}\n\n",
json!({
"type": "message-metadata",
"messageMetadata": {
"compacted": true,
"summary": summary,
"keepLastN": keep_last_n
}
})
);
let _ = stream.write_all(ev.as_bytes()).await;
} else if compaction_failed {
let ev = format!(
"data: {}\n\n",
json!({
"type": "message-metadata",
"messageMetadata": {
"compacted": false,
"warning": "Conversation is large but compaction failed. Responses may be degraded."
}
})
);
let _ = stream.write_all(ev.as_bytes()).await;
}
let total_deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(300);
const TOOL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
for _step in 0..50 {
if tokio::time::Instant::now() >= total_deadline {
let ev = format!(
"data: {}\n\n",
json!({"type":"error","errorText":"Chat session timed out (5 minute limit)."})
);
let _ = stream.write_all(ev.as_bytes()).await;
break;
}
let step_ev = "data: {\"type\":\"start-step\"}\n\n";
if stream.write_all(step_ev.as_bytes()).await.is_err() {
return;
}
let gateway_body = json!({
"model": model,
"messages": openai_messages,
"tools": tools,
"stream": true,
});
let gw_response = match client
.post(&url)
.header("Authorization", format!("Bearer {}", api_key))
.header("Content-Type", "application/json")
.body(gateway_body.to_string())
.send()
.await
{
Ok(r) => r,
Err(e) => {
let ev = format!(
"data: {}\n\n",
json!({"type":"error","errorText":format!("Gateway request failed: {}", e)})
);
let _ = stream.write_all(ev.as_bytes()).await;
break;
}
};
if !gw_response.status().is_success() {
let body_text = gw_response.text().await.unwrap_or_default();
let ev = format!(
"data: {}\n\n",
json!({"type":"error","errorText":body_text})
);
let _ = stream.write_all(ev.as_bytes()).await;
break;
}
let tool_calls = stream_gateway_response(stream, gw_response).await;
if tool_calls.is_empty() {
let finish_step_ev = "data: {\"type\":\"finish-step\"}\n\n";
let _ = stream.write_all(finish_step_ev.as_bytes()).await;
break;
}
let tc_values: Vec<Value> = tool_calls.iter().map(|(id, name, args)| {
json!({"id": id, "type": "function", "function": {"name": name, "arguments": args}})
}).collect();
openai_messages.push(json!({"role": "assistant", "tool_calls": tc_values}));
for (tc_id, tc_name, tc_args) in &tool_calls {
let input: Value = serde_json::from_str(tc_args).unwrap_or(json!({}));
let command = input.get("command").and_then(|c| c.as_str()).unwrap_or("");
let ev = format!(
"data: {}\n\n",
json!({
"type": "tool-input-available",
"toolCallId": tc_id,
"toolName": tc_name,
"input": input
})
);
let _ = stream.write_all(ev.as_bytes()).await;
let result = match tokio::time::timeout(
TOOL_TIMEOUT,
execute_chat_tool(&session, command),
)
.await
{
Ok(r) => r,
Err(_) => "Tool execution timed out after 60 seconds.".to_string(),
};
let frontend_output = enrich_tool_output(&result);
let ev = format!(
"data: {}\n\n",
json!({
"type": "tool-output-available",
"toolCallId": tc_id,
"output": frontend_output
})
);
let _ = stream.write_all(ev.as_bytes()).await;
openai_messages.push(json!({
"role": "tool",
"tool_call_id": tc_id,
"content": result
}));
}
let finish_step_ev = "data: {\"type\":\"finish-step\"}\n\n";
let _ = stream.write_all(finish_step_ev.as_bytes()).await;
}
let finish_ev = "data: {\"type\":\"finish\"}\n\n";
let _ = stream.write_all(finish_ev.as_bytes()).await;
let done_ev = "data: [DONE]\n\n";
let _ = stream.write_all(done_ev.as_bytes()).await;
}
+960
View File
@@ -0,0 +1,960 @@
use futures_util::{SinkExt, StreamExt};
use serde_json::{json, Value};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio_tungstenite::tungstenite::Message;
use crate::connection::get_socket_dir;
use super::chat::{chat_status_json, handle_chat_request, handle_models_request};
use super::discovery::discover_sessions;
use super::http::{serve_embedded_file, CORS_HEADERS};
/// Dashboard same-origin proxy endpoints for session metadata and streams.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SessionProxyEndpoint {
Tabs,
Status,
Stream,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct DashboardProxyError {
status: &'static str,
message: String,
}
impl DashboardProxyError {
fn not_found(message: impl Into<String>) -> Self {
Self {
status: "404 Not Found",
message: message.into(),
}
}
fn bad_gateway(message: impl Into<String>) -> Self {
Self {
status: "502 Bad Gateway",
message: message.into(),
}
}
}
const PROXY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
const PROXY_MAX_RESPONSE_SIZE: u64 = 16 * 1024 * 1024;
fn build_json_error_body(error: &str) -> String {
let escaped = serde_json::to_string(error).unwrap_or_else(|_| format!("\"{}\"", error));
format!(r#"{{"success":false,"error":{escaped}}}"#)
}
async fn write_http_response_inner(
stream: &mut tokio::net::TcpStream,
status: &str,
content_type: &str,
body: &[u8],
include_cors: bool,
) {
let cors_headers = if include_cors { CORS_HEADERS } else { "" };
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n{cors_headers}\r\n",
body.len()
);
let _ = stream.write_all(response.as_bytes()).await;
let _ = stream.write_all(body).await;
}
async fn write_http_response(
stream: &mut tokio::net::TcpStream,
status: &str,
content_type: &str,
body: &[u8],
) {
write_http_response_inner(stream, status, content_type, body, true).await;
}
async fn write_http_response_no_cors(
stream: &mut tokio::net::TcpStream,
status: &str,
content_type: &str,
body: &[u8],
) {
write_http_response_inner(stream, status, content_type, body, false).await;
}
async fn write_json_error_response_no_cors(
stream: &mut tokio::net::TcpStream,
status: &'static str,
error: &str,
) {
let body = build_json_error_body(error);
write_http_response_no_cors(
stream,
status,
"application/json; charset=utf-8",
body.as_bytes(),
)
.await;
}
fn parse_request_method_and_path(request: &str) -> (&str, &str) {
let first_line = request.lines().next().unwrap_or("");
let method = first_line.split_whitespace().next().unwrap_or("GET");
let path = first_line.split_whitespace().nth(1).unwrap_or("/");
(method, path)
}
fn is_websocket_upgrade(request: &str) -> bool {
request.lines().any(|line| {
if let Some((name, value)) = line.split_once(':') {
name.trim().eq_ignore_ascii_case("upgrade")
&& value.trim().eq_ignore_ascii_case("websocket")
} else {
false
}
})
}
fn request_header_value<'a>(request: &'a str, name: &str) -> Option<&'a str> {
request.lines().find_map(|line| {
let (header_name, value) = line.split_once(':')?;
if header_name.trim().eq_ignore_ascii_case(name) {
Some(value.trim())
} else {
None
}
})
}
fn normalize_origin_authority(origin: &str) -> Option<String> {
let url = url::Url::parse(origin).ok()?;
let host = url.host_str()?.to_ascii_lowercase();
let host = if host.contains(':') {
format!("[{host}]")
} else {
host
};
Some(match url.port() {
Some(port) => format!("{host}:{port}"),
None => host,
})
}
fn normalize_host_authority(host: &str) -> String {
let host = host.trim().to_ascii_lowercase();
if let Some(bracket_end) = host.rfind(']') {
if bracket_end == host.len() - 1 {
return host;
}
if host.as_bytes().get(bracket_end + 1) == Some(&b':') {
let port = &host[bracket_end + 2..];
if port == "80" || port == "443" {
return host[..=bracket_end].to_string();
}
}
return host;
}
if let Some((name, port)) = host.rsplit_once(':') {
if !name.contains(':') && (port == "80" || port == "443") {
return name.to_string();
}
}
host
}
fn header_matches_host(request: &str, header_name: &str) -> Option<bool> {
let authority =
request_header_value(request, header_name).and_then(normalize_origin_authority)?;
let host = request_header_value(request, "host").map(normalize_host_authority)?;
Some(authority == host)
}
/// Validates that a proxied WebSocket request either has no Origin header or
/// presents an Origin whose authority matches the request Host header.
fn is_same_origin_ws_request(request: &str) -> bool {
match header_matches_host(request, "origin") {
Some(matches) => matches,
None => request_header_value(request, "origin").is_none(),
}
}
/// Validates that an HTTP session-proxy request came from a same-origin page.
///
/// For GET requests we require either a same-origin `Origin` or a same-origin
/// `Referer` so browsers cannot hit the proxy routes via side-channel tags or
/// arbitrary cross-origin fetches.
fn is_same_origin_http_request(request: &str) -> bool {
matches!(header_matches_host(request, "origin"), Some(true))
|| matches!(header_matches_host(request, "referer"), Some(true))
}
/// Parse a dashboard route of the form `/api/session/<port>/<endpoint>`.
fn parse_session_proxy_route(path: &str) -> Result<(u16, SessionProxyEndpoint), &'static str> {
if !path.starts_with("/api/session/") {
return Err("Invalid session proxy route.");
}
let mut parts = path.split('/');
if parts.next() != Some("") || parts.next() != Some("api") || parts.next() != Some("session") {
return Err("Invalid session proxy route.");
}
let port_str = parts.next().ok_or("Missing session proxy port.")?;
if port_str.is_empty() {
return Err("Missing session proxy port.");
}
let endpoint = match parts.next().ok_or("Missing session proxy endpoint.")? {
"tabs" => SessionProxyEndpoint::Tabs,
"status" => SessionProxyEndpoint::Status,
"stream" => SessionProxyEndpoint::Stream,
_ => return Err("Unknown session proxy endpoint."),
};
if parts.next().is_some() {
return Err("Unexpected path segments in session proxy route.");
}
let port = port_str
.parse::<u16>()
.map_err(|_| "Session proxy port must be a valid TCP port.")?;
if port == 0 {
return Err("Session proxy port must be a valid TCP port.");
}
Ok((port, endpoint))
}
fn sessions_json_has_active_port(sessions_json: &str, port: u16) -> Result<bool, String> {
let sessions: Vec<Value> = serde_json::from_str(sessions_json)
.map_err(|e| format!("Failed to parse active sessions: {e}"))?;
Ok(sessions.iter().any(|session| {
session
.get("port")
.and_then(|value| value.as_u64())
.map(|value| value == u64::from(port))
.unwrap_or(false)
}))
}
fn require_active_session_port(port: u16) -> Result<(), DashboardProxyError> {
let sessions_json = discover_sessions();
let is_active = sessions_json_has_active_port(&sessions_json, port)
.map_err(DashboardProxyError::bad_gateway)?;
if is_active {
Ok(())
} else {
Err(DashboardProxyError::not_found(format!(
"No active session is listening on port {port}."
)))
}
}
fn split_http_response(response: &[u8]) -> Result<(&[u8], &[u8]), String> {
if let Some(header_end) = response.windows(4).position(|window| window == b"\r\n\r\n") {
let body_start = header_end + 4;
return Ok((&response[..header_end], &response[body_start..]));
}
if let Some(header_end) = response.windows(2).position(|window| window == b"\n\n") {
let body_start = header_end + 2;
return Ok((&response[..header_end], &response[body_start..]));
}
Err("Upstream response was missing an HTTP header terminator.".to_string())
}
fn parse_upstream_http_response(response: &[u8]) -> Result<(String, String, Vec<u8>), String> {
let (header_bytes, body) = split_http_response(response)?;
let header_str = std::str::from_utf8(header_bytes)
.map_err(|e| format!("Upstream response headers were not valid UTF-8: {e}"))?;
let mut lines = header_str.lines();
let status_line = lines
.next()
.ok_or_else(|| "Upstream response was missing a status line.".to_string())?;
let status = status_line
.split_once(' ')
.map(|(_, status)| status.trim().to_string())
.filter(|status| !status.is_empty())
.ok_or_else(|| "Upstream response status line was malformed.".to_string())?;
let content_type = lines
.find_map(|line| {
let (name, value) = line.split_once(':')?;
if name.trim().eq_ignore_ascii_case("content-type") {
Some(value.trim().to_string())
} else {
None
}
})
.unwrap_or_else(|| "application/json; charset=utf-8".to_string());
Ok((status, content_type, body.to_vec()))
}
/// Proxy dashboard-origin HTTP requests for session tabs or status to the loopback session server.
async fn proxy_session_http_route(
port: u16,
endpoint: SessionProxyEndpoint,
) -> Result<(String, String, Vec<u8>), DashboardProxyError> {
debug_assert!(matches!(
endpoint,
SessionProxyEndpoint::Tabs | SessionProxyEndpoint::Status
));
require_active_session_port(port)?;
let upstream_path = match endpoint {
SessionProxyEndpoint::Tabs => "/api/tabs",
SessionProxyEndpoint::Status => "/api/status",
SessionProxyEndpoint::Stream => unreachable!("stream routes use the WebSocket proxy"),
};
let request = format!(
"GET {upstream_path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n"
);
tokio::time::timeout(PROXY_TIMEOUT, async {
let mut upstream = tokio::net::TcpStream::connect(("127.0.0.1", port))
.await
.map_err(|e| {
DashboardProxyError::bad_gateway(format!(
"Failed to connect to session {port}: {e}"
))
})?;
upstream.write_all(request.as_bytes()).await.map_err(|e| {
DashboardProxyError::bad_gateway(format!(
"Failed to proxy request to session {port}: {e}"
))
})?;
let mut response = Vec::new();
(&mut upstream)
.take(PROXY_MAX_RESPONSE_SIZE + 1)
.read_to_end(&mut response)
.await
.map_err(|e| {
DashboardProxyError::bad_gateway(format!(
"Failed to read session {port} response: {e}"
))
})?;
if response.len() as u64 > PROXY_MAX_RESPONSE_SIZE {
return Err(DashboardProxyError::bad_gateway(format!(
"Session {port} response exceeded {PROXY_MAX_RESPONSE_SIZE} bytes."
)));
}
parse_upstream_http_response(&response).map_err(DashboardProxyError::bad_gateway)
})
.await
.map_err(|_| {
DashboardProxyError::bad_gateway(format!(
"Session {port} proxy request timed out after {}s.",
PROXY_TIMEOUT.as_secs()
))
})?
}
/// Bridge a dashboard-origin WebSocket upgrade to the loopback session stream.
async fn proxy_session_stream(mut stream: tokio::net::TcpStream, port: u16) {
let upstream_url = format!("ws://127.0.0.1:{port}");
let (upstream_ws, _) = match tokio_tungstenite::connect_async(&upstream_url).await {
Ok(ws) => ws,
Err(error) => {
write_json_error_response_no_cors(
&mut stream,
"502 Bad Gateway",
&format!("Failed to connect to session {port}: {error}"),
)
.await;
return;
}
};
let client_ws = match tokio_tungstenite::accept_async(stream).await {
Ok(ws) => ws,
Err(_) => return,
};
let (mut client_tx, mut client_rx) = client_ws.split();
let (mut upstream_tx, mut upstream_rx) = upstream_ws.split();
loop {
tokio::select! {
message = client_rx.next() => {
match message {
Some(Ok(message)) => {
let is_close = matches!(message, Message::Close(_));
if upstream_tx.send(message).await.is_err() {
break;
}
if is_close {
break;
}
}
Some(Err(_)) | None => {
let _ = upstream_tx.send(Message::Close(None)).await;
break;
}
}
}
message = upstream_rx.next() => {
match message {
Some(Ok(message)) => {
let is_close = matches!(message, Message::Close(_));
if client_tx.send(message).await.is_err() {
break;
}
if is_close {
break;
}
}
Some(Err(_)) | None => {
let _ = client_tx.send(Message::Close(None)).await;
break;
}
}
}
}
}
}
pub async fn run_dashboard_server(port: u16) {
let addr = format!("127.0.0.1:{}", port);
let listener = match TcpListener::bind(&addr).await {
Ok(l) => l,
Err(e) => {
eprintln!("Failed to bind dashboard server on {}: {}", addr, e);
return;
}
};
loop {
let Ok((stream, _addr)) = listener.accept().await else {
break;
};
tokio::spawn(async move {
handle_dashboard_connection(stream).await;
});
}
}
async fn handle_dashboard_connection(mut stream: tokio::net::TcpStream) {
let mut buf = vec![0u8; 8192];
let peeked_len = match stream.peek(&mut buf).await {
Ok(n) if n > 0 => n,
_ => return,
};
let peeked_request = String::from_utf8_lossy(&buf[..peeked_len]);
let (peeked_method, peeked_path) = parse_request_method_and_path(&peeked_request);
if peeked_path.starts_with("/api/session/") {
let (port, endpoint) = match parse_session_proxy_route(peeked_path) {
Ok(route) => route,
Err(error) => {
write_json_error_response_no_cors(&mut stream, "400 Bad Request", error).await;
return;
}
};
match endpoint {
SessionProxyEndpoint::Stream => {
if peeked_method != "GET" {
write_json_error_response_no_cors(
&mut stream,
"400 Bad Request",
"Session stream proxy only supports GET WebSocket upgrades.",
)
.await;
return;
}
if !is_websocket_upgrade(&peeked_request) {
write_json_error_response_no_cors(
&mut stream,
"400 Bad Request",
"Session stream proxy requires a WebSocket upgrade request.",
)
.await;
return;
}
if !is_same_origin_ws_request(&peeked_request) {
write_json_error_response_no_cors(
&mut stream,
"403 Forbidden",
"Origin does not match Host header.",
)
.await;
return;
}
if let Err(error) = require_active_session_port(port) {
write_json_error_response_no_cors(&mut stream, error.status, &error.message)
.await;
return;
}
proxy_session_stream(stream, port).await;
return;
}
SessionProxyEndpoint::Tabs | SessionProxyEndpoint::Status => {
if peeked_method != "GET" {
write_json_error_response_no_cors(
&mut stream,
"400 Bad Request",
"Session proxy routes only support GET requests.",
)
.await;
return;
}
}
}
}
let n = match stream.read(&mut buf).await {
Ok(n) if n > 0 => n,
_ => return,
};
let request = String::from_utf8_lossy(&buf[..n]).to_string();
let (method, path) = parse_request_method_and_path(&request);
let origin = request_header_value(&request, "origin").map(|value| value.to_string());
if method == "OPTIONS" {
let response = format!(
"HTTP/1.1 204 No Content\r\n{CORS_HEADERS}Access-Control-Max-Age: 86400\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
let _ = stream.write_all(response.as_bytes()).await;
return;
}
if method == "POST" && path == "/api/chat" {
let body_str = read_post_body(&mut stream, &buf, n).await;
handle_chat_request(&mut stream, &body_str, origin.as_deref()).await;
return;
}
if method == "GET" && path == "/api/models" {
handle_models_request(&mut stream, origin.as_deref()).await;
return;
}
if method == "POST" && (path == "/api/sessions" || path == "/api/exec" || path == "/api/kill") {
let body_str = read_post_body(&mut stream, &buf, n).await;
let result = if path == "/api/exec" {
exec_cli(&body_str).await
} else if path == "/api/kill" {
kill_session(&body_str).await
} else {
spawn_session(&body_str).await
};
let (status, resp_body) = match result {
Ok(msg) => ("200 OK", msg),
Err(e) => ("400 Bad Request", build_json_error_body(&e)),
};
write_http_response(
&mut stream,
status,
"application/json; charset=utf-8",
resp_body.as_bytes(),
)
.await;
return;
}
if path.starts_with("/api/session/") {
let (port, endpoint) = match parse_session_proxy_route(path) {
Ok(route) => route,
Err(error) => {
write_json_error_response_no_cors(&mut stream, "400 Bad Request", error).await;
return;
}
};
match endpoint {
SessionProxyEndpoint::Tabs | SessionProxyEndpoint::Status => {
if !is_same_origin_http_request(&request) {
write_json_error_response_no_cors(
&mut stream,
"403 Forbidden",
"Origin or Referer does not match Host header.",
)
.await;
return;
}
match proxy_session_http_route(port, endpoint).await {
Ok((status, content_type, body)) => {
write_http_response_no_cors(&mut stream, &status, &content_type, &body)
.await;
}
Err(error) => {
write_json_error_response_no_cors(
&mut stream,
error.status,
&error.message,
)
.await;
}
}
return;
}
SessionProxyEndpoint::Stream => {
write_json_error_response_no_cors(
&mut stream,
"400 Bad Request",
"Session stream proxy requires a WebSocket upgrade request.",
)
.await;
return;
}
}
}
let (status, content_type, body): (&str, &str, Vec<u8>) = if path == "/api/sessions" {
(
"200 OK",
"application/json; charset=utf-8",
discover_sessions().into_bytes(),
)
} else if path == "/api/chat/status" {
(
"200 OK",
"application/json; charset=utf-8",
chat_status_json().into_bytes(),
)
} else {
serve_embedded_file(path)
};
write_http_response(&mut stream, status, content_type, &body).await;
}
async fn read_post_body(stream: &mut tokio::net::TcpStream, initial: &[u8], n: usize) -> String {
let header_end = initial[..n]
.windows(4)
.position(|w| w == b"\r\n\r\n")
.map(|p| p + 4)
.or_else(|| {
initial[..n]
.windows(2)
.position(|w| w == b"\n\n")
.map(|p| p + 2)
});
let Some(header_end) = header_end else {
return String::new();
};
let header_str = String::from_utf8_lossy(&initial[..header_end]);
let content_length: usize = header_str
.lines()
.find_map(|l| {
if l.len() > 16 && l[..16].eq_ignore_ascii_case("content-length: ") {
l[16..].trim().parse::<usize>().ok()
} else {
let lower = l.to_lowercase();
lower
.strip_prefix("content-length:")
.and_then(|v| v.trim().parse::<usize>().ok())
}
})
.unwrap_or(0);
if content_length == 0 {
return String::new();
}
let read_body = &initial[header_end..n];
let already_read = read_body.len().min(content_length);
let mut body = Vec::with_capacity(content_length);
body.extend_from_slice(&read_body[..already_read]);
let remaining = content_length - already_read;
if remaining > 0 {
let mut rest = vec![0u8; remaining];
if stream.read_exact(&mut rest).await.is_ok() {
body.extend_from_slice(&rest);
}
}
String::from_utf8(body).unwrap_or_default()
}
async fn exec_cli(body: &str) -> Result<String, String> {
let parsed: Value = serde_json::from_str(body).map_err(|e| format!("Invalid JSON: {}", e))?;
let args: Vec<String> = parsed
.get("args")
.and_then(|v| v.as_array())
.ok_or("Missing \"args\" array")?
.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect();
if args.is_empty() {
return Err("Empty args array".to_string());
}
let exe = std::env::current_exe().map_err(|e| format!("Cannot resolve executable: {}", e))?;
let mut cmd = tokio::process::Command::new(&exe);
cmd.args(&args)
.arg("--json")
.env_remove("AGENT_BROWSER_DASHBOARD")
.env_remove("AGENT_BROWSER_DASHBOARD_PORT")
.env_remove("AGENT_BROWSER_STREAM_PORT");
let output = cmd
.output()
.await
.map_err(|e| format!("Failed to execute: {}", e))?;
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
Ok(json!({
"success": output.status.success(),
"exit_code": output.status.code(),
"stdout": stdout,
"stderr": stderr,
})
.to_string())
}
async fn kill_session(body: &str) -> Result<String, String> {
let parsed: Value = serde_json::from_str(body).map_err(|e| format!("Invalid JSON: {}", e))?;
let session = parsed
.get("session")
.and_then(|v| v.as_str())
.ok_or("Missing \"session\" field")?;
if session.is_empty() || session.len() > 64 {
return Err("Session name must be 1-64 characters".to_string());
}
let dir = get_socket_dir();
let pid_path = dir.join(format!("{}.pid", session));
let pid_str = std::fs::read_to_string(&pid_path)
.map_err(|_| format!("No PID file for session '{}'", session))?;
let pid: u32 = pid_str
.trim()
.parse()
.map_err(|_| format!("Invalid PID in file: {}", pid_str.trim()))?;
#[cfg(unix)]
{
// SAFETY: The PID came from the daemon-managed pidfile and is only used
// to send standard termination signals to that process.
unsafe {
libc::kill(pid as i32, libc::SIGTERM);
}
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
// SAFETY: A signal value of 0 performs an existence check on the same pid.
if unsafe { libc::kill(pid as i32, 0) } == 0 {
// SAFETY: The process still exists after SIGTERM, so escalate to SIGKILL.
unsafe {
libc::kill(pid as i32, libc::SIGKILL);
}
}
}
for ext in &["pid", "sock", "stream", "engine", "extensions"] {
let _ = std::fs::remove_file(dir.join(format!("{}.{}", session, ext)));
}
Ok(json!({ "success": true, "killed_pid": pid }).to_string())
}
pub(super) async fn spawn_session(body: &str) -> Result<String, String> {
let parsed: Value = serde_json::from_str(body).map_err(|e| format!("Invalid JSON: {}", e))?;
let session = parsed
.get("session")
.and_then(|v| v.as_str())
.ok_or("Missing \"session\" field")?;
if session.is_empty() || session.len() > 64 {
return Err("Session name must be 1-64 characters".to_string());
}
let exe = std::env::current_exe().map_err(|e| format!("Cannot resolve executable: {}", e))?;
let mut cmd = tokio::process::Command::new(&exe);
cmd.arg("open")
.arg("about:blank")
.arg("--session")
.arg(session);
cmd.stdout(std::process::Stdio::null());
cmd.stderr(std::process::Stdio::null());
let status = cmd
.status()
.await
.map_err(|e| format!("Failed to spawn session: {}", e))?;
if status.success() {
Ok(format!(
r#"{{"success":true,"session":{}}}"#,
serde_json::to_string(session).unwrap_or_default()
))
} else {
Err(format!("Session process exited with {}", status))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_same_origin_ws_request_matching() {
let req = "GET /api/session/9222/stream HTTP/1.1\r\nHost: localhost:4848\r\nOrigin: http://localhost:4848\r\nUpgrade: websocket\r\n\r\n";
assert!(is_same_origin_ws_request(req));
}
#[test]
fn test_same_origin_ws_request_proxied() {
let req = "GET /api/session/9222/stream HTTP/1.1\r\nHost: dashboard.agent-browser.localhost\r\nOrigin: https://dashboard.agent-browser.localhost\r\nUpgrade: websocket\r\n\r\n";
assert!(is_same_origin_ws_request(req));
}
#[test]
fn test_normalize_origin_authority_https_without_port() {
assert_eq!(
normalize_origin_authority("https://dashboard.agent-browser.localhost"),
Some("dashboard.agent-browser.localhost".to_string())
);
}
#[test]
fn test_same_origin_ws_request_default_https_port() {
let req = "GET /api/session/9222/stream HTTP/1.1\r\nHost: dashboard.agent-browser.localhost:443\r\nOrigin: https://dashboard.agent-browser.localhost\r\nUpgrade: websocket\r\n\r\n";
assert!(is_same_origin_ws_request(req));
}
#[test]
fn test_same_origin_http_request_matching_origin() {
let req = "GET /api/session/9222/tabs HTTP/1.1\r\nHost: localhost:4848\r\nOrigin: http://localhost:4848\r\n\r\n";
assert!(is_same_origin_http_request(req));
}
#[test]
fn test_same_origin_http_request_matching_referer() {
let req = "GET /api/session/9222/tabs HTTP/1.1\r\nHost: dashboard.agent-browser.localhost:443\r\nReferer: https://dashboard.agent-browser.localhost/sessions\r\n\r\n";
assert!(is_same_origin_http_request(req));
}
#[test]
fn test_same_origin_http_request_rejects_missing_origin_and_referer() {
let req = "GET /api/session/9222/tabs HTTP/1.1\r\nHost: localhost:4848\r\n\r\n";
assert!(!is_same_origin_http_request(req));
}
#[test]
fn test_same_origin_http_request_rejects_cross_origin_referer() {
let req = "GET /api/session/9222/tabs HTTP/1.1\r\nHost: localhost:4848\r\nReferer: https://evil.com/path\r\n\r\n";
assert!(!is_same_origin_http_request(req));
}
#[test]
fn test_same_origin_ws_request_coder() {
let req = "GET /api/session/9222/stream HTTP/1.1\r\nHost: workspace.coder.com\r\nOrigin: https://workspace.coder.com\r\nUpgrade: websocket\r\n\r\n";
assert!(is_same_origin_ws_request(req));
}
#[test]
fn test_cross_origin_ws_request_rejected() {
let req = "GET /api/session/9222/stream HTTP/1.1\r\nHost: localhost:4848\r\nOrigin: https://evil.com\r\nUpgrade: websocket\r\n\r\n";
assert!(!is_same_origin_ws_request(req));
}
#[test]
fn test_no_origin_header_allowed() {
let req = "GET /api/session/9222/stream HTTP/1.1\r\nHost: localhost:4848\r\nUpgrade: websocket\r\n\r\n";
assert!(is_same_origin_ws_request(req));
}
#[test]
fn test_parse_session_proxy_route_valid() {
assert_eq!(
parse_session_proxy_route("/api/session/9222/tabs"),
Ok((9222, SessionProxyEndpoint::Tabs))
);
assert_eq!(
parse_session_proxy_route("/api/session/1337/status"),
Ok((1337, SessionProxyEndpoint::Status))
);
assert_eq!(
parse_session_proxy_route("/api/session/65535/stream"),
Ok((65535, SessionProxyEndpoint::Stream))
);
}
#[test]
fn test_parse_session_proxy_route_invalid() {
assert!(parse_session_proxy_route("/api/session/0/tabs").is_err());
assert!(parse_session_proxy_route("/api/session/not-a-port/tabs").is_err());
assert!(parse_session_proxy_route("/api/session/70000/tabs").is_err());
assert!(parse_session_proxy_route("/api/session/9222").is_err());
assert!(parse_session_proxy_route("/api/session/9222/unknown").is_err());
assert!(parse_session_proxy_route("/api/session/9222/tabs/extra").is_err());
}
#[test]
fn test_parse_session_proxy_route_path_traversal() {
assert!(parse_session_proxy_route("/api/session/9222/tabs/..").is_err());
assert!(parse_session_proxy_route("/api/session/9222/tabs/../status").is_err());
assert!(parse_session_proxy_route("/api/session/9222/../../etc/passwd").is_err());
assert!(parse_session_proxy_route("/api/session/../session/9222/tabs").is_err());
}
#[test]
fn test_parse_session_proxy_route_double_slashes() {
assert!(parse_session_proxy_route("/api/session//9222/tabs").is_err());
assert!(parse_session_proxy_route("/api//session/9222/tabs").is_err());
assert!(parse_session_proxy_route("//api/session/9222/tabs").is_err());
}
#[test]
fn test_parse_session_proxy_route_trailing_slash() {
assert!(parse_session_proxy_route("/api/session/9222/tabs/").is_err());
assert!(parse_session_proxy_route("/api/session/9222/status/").is_err());
assert!(parse_session_proxy_route("/api/session/9222/stream/").is_err());
}
#[test]
fn test_parse_session_proxy_route_encoded_paths() {
assert!(parse_session_proxy_route("/api/session/9222/tabs%20extra").is_err());
assert!(parse_session_proxy_route("/api/session/%39%32%32%32/tabs").is_err());
}
#[test]
fn test_sessions_json_has_active_port() {
let sessions_json = r#"[
{"session":"alpha","port":9222,"engine":"chrome"},
{"session":"beta","port":9333,"engine":"chrome"}
]"#;
assert_eq!(sessions_json_has_active_port(sessions_json, 9222), Ok(true));
assert_eq!(
sessions_json_has_active_port(sessions_json, 9444),
Ok(false)
);
}
#[test]
fn test_sessions_json_has_active_port_invalid_json() {
assert!(sessions_json_has_active_port("{", 9222).is_err());
}
#[test]
fn test_parse_upstream_http_response() {
let response = b"HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nConnection: close\r\n\r\n{\"ok\":true}";
let parsed = parse_upstream_http_response(response).expect("response should parse");
assert_eq!(parsed.0, "200 OK");
assert_eq!(parsed.1, "application/json; charset=utf-8");
assert_eq!(parsed.2, b"{\"ok\":true}".to_vec());
}
}
+118
View File
@@ -0,0 +1,118 @@
use serde_json::{json, Value};
use std::path::Path;
use crate::connection::get_socket_dir;
pub(super) fn discover_sessions() -> String {
let dir = get_socket_dir();
let mut sessions = Vec::new();
if let Ok(entries) = std::fs::read_dir(&dir) {
for entry in entries.flatten() {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if let Some(session) = name_str.strip_suffix(".stream") {
if let Ok(port_str) = std::fs::read_to_string(entry.path()) {
if let Ok(port) = port_str.trim().parse::<u16>() {
let pid_path = dir.join(format!("{}.pid", session));
if is_process_alive(&pid_path) {
let engine_path = dir.join(format!("{}.engine", session));
let engine = std::fs::read_to_string(&engine_path)
.ok()
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| "chrome".to_string());
let provider_path = dir.join(format!("{}.provider", session));
let provider = std::fs::read_to_string(&provider_path)
.ok()
.filter(|s| !s.trim().is_empty());
let extensions = read_extensions_metadata(&dir, session);
let mut entry = json!({
"session": session,
"port": port,
"engine": engine.trim(),
});
if let Some(ref p) = provider {
entry["provider"] = json!(p.trim());
}
if !extensions.is_empty() {
entry["extensions"] = json!(extensions);
}
sessions.push(entry);
} else {
let _ = std::fs::remove_file(entry.path());
}
}
}
}
}
}
serde_json::to_string(&sessions).unwrap_or_else(|_| "[]".to_string())
}
fn read_extensions_metadata(dir: &std::path::Path, session: &str) -> Vec<Value> {
let ext_path = dir.join(format!("{}.extensions", session));
let ext_str = match std::fs::read_to_string(&ext_path) {
Ok(s) => s,
Err(_) => return Vec::new(),
};
ext_str
.split(',')
.map(|p| p.trim())
.filter(|p| !p.is_empty())
.filter_map(|path| {
let manifest_path = std::path::Path::new(path).join("manifest.json");
let manifest_str = std::fs::read_to_string(&manifest_path).ok()?;
let manifest: Value = serde_json::from_str(&manifest_str).ok()?;
let name = manifest
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("Unknown")
.to_string();
let version = manifest
.get("version")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let description = manifest
.get("description")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let mut ext = json!({
"name": name,
"version": version,
"path": path,
});
if let Some(desc) = description {
ext["description"] = json!(desc);
}
Some(ext)
})
.collect()
}
fn is_process_alive(pid_path: &Path) -> bool {
let pid_str = match std::fs::read_to_string(pid_path) {
Ok(s) => s,
Err(_) => return false,
};
let pid: u32 = match pid_str.trim().parse() {
Ok(p) => p,
Err(_) => return false,
};
#[cfg(unix)]
{
unsafe { libc::kill(pid as i32, 0) == 0 }
}
#[cfg(not(unix))]
{
let _ = pid;
true
}
}
+715
View File
@@ -0,0 +1,715 @@
use rust_embed::Embed;
use serde_json::{json, Value};
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::RwLock;
use crate::connection::get_socket_dir;
#[cfg(windows)]
use crate::connection::resolve_port;
use super::chat::{chat_status_json, handle_chat_request, handle_models_request};
use super::dashboard::spawn_session;
use super::discovery::discover_sessions;
#[derive(Embed)]
#[folder = "../packages/dashboard/out/"]
struct DashboardAssets;
pub(super) const CORS_HEADERS: &str = "Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: GET, POST, OPTIONS\r\nAccess-Control-Allow-Headers: Content-Type\r\n";
/// Build CORS headers that reflect the request origin only when it passes
/// `is_allowed_origin`. Used for sensitive endpoints (chat, models) so the
/// API key is not accessible from arbitrary web pages.
pub(super) fn cors_headers_for_origin(origin: Option<&str>) -> String {
let allowed_origin = match origin {
Some(o) if super::is_allowed_origin(Some(o)) => o,
_ => "http://localhost",
};
format!(
"Access-Control-Allow-Origin: {}\r\nAccess-Control-Allow-Methods: GET, POST, OPTIONS\r\nAccess-Control-Allow-Headers: Content-Type\r\n",
allowed_origin
)
}
fn request_headers(request: &str) -> &str {
request
.find("\r\n\r\n")
.or_else(|| request.find("\n\n"))
.map(|header_end| &request[..header_end])
.unwrap_or(request)
}
fn request_header_value<'a>(request: &'a str, name: &str) -> Option<&'a str> {
request_headers(request).lines().find_map(|line| {
let (header_name, value) = line.split_once(':')?;
if header_name.trim().eq_ignore_ascii_case(name) {
Some(value.trim())
} else {
None
}
})
}
fn parse_origin(peeked: &[u8]) -> Option<String> {
let header_str = std::str::from_utf8(peeked).ok()?;
request_header_value(header_str, "origin").map(ToString::to_string)
}
fn normalize_origin_authority(origin: &str) -> Option<String> {
let url = url::Url::parse(origin).ok()?;
let host = url.host_str()?.to_ascii_lowercase();
let host = if host.contains(':') {
format!("[{host}]")
} else {
host
};
let default_port = (url.scheme() == "http" && url.port() == Some(80))
|| (url.scheme() == "https" && url.port() == Some(443));
Some(match url.port() {
Some(port) if !default_port => format!("{host}:{port}"),
_ => host,
})
}
fn normalize_host_authority(host: &str) -> String {
let host = host.trim().to_ascii_lowercase();
if let Some(bracket_end) = host.rfind(']') {
if bracket_end == host.len() - 1 {
return host;
}
if host.as_bytes().get(bracket_end + 1) == Some(&b':') {
let port = &host[bracket_end + 2..];
if port == "80" || port == "443" {
return host[..=bracket_end].to_string();
}
}
return host;
}
if let Some((name, port)) = host.rsplit_once(':') {
if !name.contains(':') && (port == "80" || port == "443") {
return name.to_string();
}
}
host
}
fn authority_host(authority: &str) -> &str {
if let Some(stripped) = authority.strip_prefix('[') {
if let Some(bracket_end) = stripped.find(']') {
return &authority[..=bracket_end + 1];
}
}
if let Some((host, _port)) = authority.rsplit_once(':') {
if !host.contains(':') {
return host;
}
}
authority
}
fn is_loopback_authority(authority: &str) -> bool {
matches!(
authority_host(authority),
"localhost" | "127.0.0.1" | "::1" | "[::1]"
)
}
fn header_authority_matches_host(request: &str, header_name: &str) -> bool {
let Some(authority) =
request_header_value(request, header_name).and_then(normalize_origin_authority)
else {
return false;
};
let Some(host) = request_header_value(request, "host").map(normalize_host_authority) else {
return false;
};
authority == host && is_loopback_authority(&authority) && is_loopback_authority(&host)
}
/// Protects the command relay by requiring same-origin browser metadata.
fn is_same_origin_command_request(request: &str) -> bool {
if request_header_value(request, "origin").is_some() {
header_authority_matches_host(request, "origin")
} else {
header_authority_matches_host(request, "referer")
}
}
fn command_cors_headers(request: &str) -> String {
match request_header_value(request, "origin") {
Some(origin) if is_same_origin_command_request(request) => format!(
"Access-Control-Allow-Origin: {origin}\r\nAccess-Control-Allow-Methods: POST, OPTIONS\r\nAccess-Control-Allow-Headers: Content-Type\r\nVary: Origin\r\n"
),
_ => String::new(),
}
}
async fn write_json_error_response_no_cors(
stream: &mut tokio::net::TcpStream,
status: &str,
error: &str,
) {
let body = format!(
r#"{{"success":false,"error":{}}}"#,
serde_json::to_string(error).unwrap_or_else(|_| format!("\"{}\"", error))
);
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
let _ = stream.write_all(response.as_bytes()).await;
let _ = stream.write_all(body.as_bytes()).await;
}
pub(super) async fn handle_http_request(
mut stream: tokio::net::TcpStream,
peeked: &[u8],
last_tabs: &Arc<RwLock<Vec<Value>>>,
last_engine: &Arc<RwLock<String>>,
session_name: &str,
) {
let peeked_len = peeked.len();
let mut discard = vec![0u8; peeked_len];
let _ = stream.read_exact(&mut discard).await;
let request = String::from_utf8_lossy(peeked);
let first_line = request.lines().next().unwrap_or("");
let method = first_line.split_whitespace().next().unwrap_or("GET");
let path = first_line.split_whitespace().nth(1).unwrap_or("/");
let origin = parse_origin(peeked);
if method == "OPTIONS" {
if path == "/api/command" {
if !is_same_origin_command_request(&request) {
write_json_error_response_no_cors(
&mut stream,
"403 Forbidden",
"Origin or Referer does not match Host header.",
)
.await;
return;
}
let cors_headers = command_cors_headers(&request);
let response = format!(
"HTTP/1.1 204 No Content\r\n{cors_headers}Access-Control-Max-Age: 86400\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
let _ = stream.write_all(response.as_bytes()).await;
return;
}
let response = format!(
"HTTP/1.1 204 No Content\r\n{CORS_HEADERS}Access-Control-Max-Age: 86400\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
let _ = stream.write_all(response.as_bytes()).await;
return;
}
if method == "POST" {
if path == "/api/command" && !is_same_origin_command_request(&request) {
write_json_error_response_no_cors(
&mut stream,
"403 Forbidden",
"Origin or Referer does not match Host header.",
)
.await;
return;
}
let full_body = read_full_body(&mut stream, peeked).await;
if full_body.is_none()
&& (path == "/api/chat" || path == "/api/sessions" || path == "/api/command")
{
let body = r#"{"error":"Request body too large"}"#;
let cors_headers = if path == "/api/command" {
command_cors_headers(&request)
} else {
CORS_HEADERS.to_string()
};
let response = format!(
"HTTP/1.1 413 Payload Too Large\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{cors_headers}\r\n",
body.len()
);
let _ = stream.write_all(response.as_bytes()).await;
let _ = stream.write_all(body.as_bytes()).await;
return;
}
let body_str = full_body.as_deref().unwrap_or("");
if path == "/api/sessions" {
let result = spawn_session(body_str).await;
let (status, resp_body) = match result {
Ok(msg) => ("200 OK", msg),
Err(e) => (
"400 Bad Request",
format!(
r#"{{"success":false,"error":{}}}"#,
serde_json::to_string(&e).unwrap_or_else(|_| format!("\"{}\"", e))
),
),
};
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n{CORS_HEADERS}\r\n",
resp_body.len()
);
let _ = stream.write_all(response.as_bytes()).await;
let _ = stream.write_all(resp_body.as_bytes()).await;
return;
}
if path == "/api/command" {
let result = relay_command_to_daemon(session_name, body_str).await;
let (status, resp_body) = match result {
Ok(resp) => ("200 OK", resp),
Err(e) => (
"502 Bad Gateway",
format!(
r#"{{"success":false,"error":{}}}"#,
serde_json::to_string(&e).unwrap_or_else(|_| format!("\"{}\"", e))
),
),
};
let cors_headers = command_cors_headers(&request);
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n{cors_headers}\r\n",
resp_body.len()
);
let _ = stream.write_all(response.as_bytes()).await;
let _ = stream.write_all(resp_body.as_bytes()).await;
return;
}
if path == "/api/chat" {
handle_chat_request(&mut stream, body_str, origin.as_deref()).await;
return;
}
}
if method == "GET" && path == "/api/models" {
handle_models_request(&mut stream, origin.as_deref()).await;
return;
}
let (status, content_type, body): (&str, &str, Vec<u8>) = if path == "/api/sessions" {
(
"200 OK",
"application/json; charset=utf-8",
discover_sessions().into_bytes(),
)
} else if path == "/api/tabs" {
let tabs = last_tabs.read().await;
(
"200 OK",
"application/json; charset=utf-8",
serde_json::to_string(&*tabs)
.unwrap_or_else(|_| "[]".to_string())
.into_bytes(),
)
} else if path == "/api/status" {
let engine = last_engine.read().await;
(
"200 OK",
"application/json; charset=utf-8",
format!(r#"{{"engine":"{}"}}"#, *engine).into_bytes(),
)
} else if path == "/api/chat/status" {
(
"200 OK",
"application/json; charset=utf-8",
chat_status_json().into_bytes(),
)
} else {
serve_embedded_file(path)
};
let response = format!(
"HTTP/1.1 {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n{CORS_HEADERS}\r\n",
status,
content_type,
body.len()
);
let _ = stream.write_all(response.as_bytes()).await;
let _ = stream.write_all(&body).await;
}
fn find_header_end(buf: &[u8]) -> Option<usize> {
buf.windows(4)
.position(|w| w == b"\r\n\r\n")
.map(|p| p + 4)
.or_else(|| buf.windows(2).position(|w| w == b"\n\n").map(|p| p + 2))
}
fn parse_content_length_bytes(headers: &[u8]) -> Option<usize> {
let header_str = std::str::from_utf8(headers).ok()?;
for line in header_str.lines() {
if line.len() > 16 && line[..16].eq_ignore_ascii_case("content-length: ") {
return line[16..].trim().parse().ok();
}
}
None
}
const MAX_BODY_SIZE: usize = 10 * 1024 * 1024;
async fn read_full_body(stream: &mut tokio::net::TcpStream, peeked: &[u8]) -> Option<String> {
let body_offset = find_header_end(peeked)?;
let content_length = parse_content_length_bytes(&peeked[..body_offset])?;
if content_length == 0 {
return Some(String::new());
}
if content_length > MAX_BODY_SIZE {
return None;
}
let peeked_body = &peeked[body_offset..];
let peeked_body_len = peeked_body.len().min(content_length);
let mut body = Vec::with_capacity(content_length);
body.extend_from_slice(&peeked_body[..peeked_body_len]);
let remaining = content_length - peeked_body_len;
if remaining > 0 {
let mut rest = vec![0u8; remaining];
if stream.read_exact(&mut rest).await.is_err() {
return String::from_utf8(body).ok();
}
body.extend_from_slice(&rest);
}
String::from_utf8(body).ok()
}
pub(super) async fn relay_command_to_daemon(
session_name: &str,
body: &str,
) -> Result<String, String> {
let mut cmd: Value = serde_json::from_str(body).map_err(|e| format!("Invalid JSON: {}", e))?;
if cmd.get("id").is_none() {
let id = format!(
"dash-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
);
cmd["id"] = json!(id);
}
let mut json_str = serde_json::to_string(&cmd).map_err(|e| e.to_string())?;
json_str.push('\n');
#[cfg(unix)]
let stream = {
let socket_path = get_socket_dir().join(format!("{}.sock", session_name));
tokio::net::UnixStream::connect(&socket_path)
.await
.map_err(|e| format!("Failed to connect to daemon: {}", e))?
};
#[cfg(windows)]
let stream = {
let port = resolve_port(session_name);
tokio::net::TcpStream::connect(format!("127.0.0.1:{}", port))
.await
.map_err(|e| format!("Failed to connect to daemon: {}", e))?
};
let (reader, mut writer) = tokio::io::split(stream);
writer
.write_all(json_str.as_bytes())
.await
.map_err(|e| format!("Failed to send command: {}", e))?;
let mut buf_reader = tokio::io::BufReader::new(reader);
let mut response_line = String::new();
tokio::io::AsyncBufReadExt::read_line(&mut buf_reader, &mut response_line)
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
Ok(response_line.trim().to_string())
}
pub(super) fn serve_embedded_file(url_path: &str) -> (&'static str, &'static str, Vec<u8>) {
let clean = url_path.trim_start_matches('/');
let key = if clean.is_empty() {
"index.html"
} else {
clean
};
let file = DashboardAssets::get(key).or_else(|| DashboardAssets::get("index.html"));
match file {
Some(content) => {
let ext = key.rsplit('.').next().unwrap_or("");
let ct = match ext {
"html" => "text/html; charset=utf-8",
"js" => "application/javascript; charset=utf-8",
"css" => "text/css; charset=utf-8",
"json" => "application/json; charset=utf-8",
"svg" => "image/svg+xml",
"png" => "image/png",
"ico" => "image/x-icon",
"woff2" => "font/woff2",
"woff" => "font/woff",
"txt" => "text/plain; charset=utf-8",
_ => "application/octet-stream",
};
("200 OK", ct, content.data.to_vec())
}
None => (
"404 Not Found",
"text/html; charset=utf-8",
b"<html><body><p>404 Not Found</p></body></html>".to_vec(),
),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::EnvGuard;
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio::sync::oneshot;
async fn send_request_to_handler(request: &str, session_name: &str) -> String {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let peeked = request.as_bytes().to_vec();
let last_tabs = Arc::new(RwLock::new(Vec::new()));
let last_engine = Arc::new(RwLock::new("chrome".to_string()));
let session_name = session_name.to_string();
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
handle_http_request(stream, &peeked, &last_tabs, &last_engine, &session_name).await;
});
let mut client = tokio::net::TcpStream::connect(addr).await.unwrap();
client.write_all(request.as_bytes()).await.unwrap();
client.shutdown().await.unwrap();
let mut response = Vec::new();
client.read_to_end(&mut response).await.unwrap();
server.await.unwrap();
String::from_utf8(response).unwrap()
}
#[cfg(unix)]
async fn spawn_fake_daemon(
socket_dir: &std::path::Path,
session_name: &str,
) -> oneshot::Receiver<String> {
let socket_path = socket_dir.join(format!("{session_name}.sock"));
let _ = std::fs::remove_file(&socket_path);
let listener = tokio::net::UnixListener::bind(&socket_path).unwrap();
let (tx, rx) = oneshot::channel();
tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut reader = tokio::io::BufReader::new(stream);
let mut line = String::new();
reader.read_line(&mut line).await.unwrap();
let mut stream = reader.into_inner();
stream
.write_all(br#"{"success":true,"data":{"ok":true}}"#)
.await
.unwrap();
stream.write_all(b"\n").await.unwrap();
let _ = tx.send(line);
});
rx
}
#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn cross_origin_command_post_is_rejected_without_relaying_to_daemon() {
let temp_parent = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join("t");
std::fs::create_dir_all(&temp_parent).unwrap();
let socket_dir = tempfile::Builder::new()
.prefix("ab-")
.tempdir_in(temp_parent)
.unwrap();
let guard = EnvGuard::new(&["AGENT_BROWSER_SOCKET_DIR", "XDG_RUNTIME_DIR"]);
guard.set(
"AGENT_BROWSER_SOCKET_DIR",
socket_dir.path().to_str().unwrap(),
);
guard.remove("XDG_RUNTIME_DIR");
let session_name = "x";
let daemon_command = spawn_fake_daemon(socket_dir.path(), session_name).await;
let body = r#"{"action":"tabs"}"#;
let request = format!(
"POST /api/command HTTP/1.1\r\nHost: localhost:7777\r\nOrigin: https://evil.example\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
body.len(),
body
);
let response = send_request_to_handler(&request, session_name).await;
assert!(
response.starts_with("HTTP/1.1 403 Forbidden"),
"unexpected response: {response}"
);
assert!(
tokio::time::timeout(std::time::Duration::from_millis(50), daemon_command)
.await
.is_err(),
"cross-origin request reached daemon command relay"
);
}
#[tokio::test(flavor = "current_thread")]
async fn cross_origin_command_preflight_is_rejected_without_wildcard_cors() {
let request = concat!(
"OPTIONS /api/command HTTP/1.1\r\n",
"Host: localhost:7777\r\n",
"Origin: https://evil.example\r\n",
"Access-Control-Request-Method: POST\r\n",
"Access-Control-Request-Headers: content-type\r\n",
"\r\n"
);
let response = send_request_to_handler(request, "x").await;
assert!(
response.starts_with("HTTP/1.1 403 Forbidden"),
"unexpected response: {response}"
);
assert!(
!response.contains("Access-Control-Allow-Origin: *"),
"forbidden command preflight exposed wildcard CORS: {response}"
);
}
#[tokio::test(flavor = "current_thread")]
async fn command_post_without_origin_or_referer_is_rejected() {
let body = r#"{"action":"tabs"}"#;
let request = format!(
"POST /api/command HTTP/1.1\r\nHost: localhost:7777\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
body.len(),
body
);
let response = send_request_to_handler(&request, "x").await;
assert!(
response.starts_with("HTTP/1.1 403 Forbidden"),
"unexpected response: {response}"
);
assert!(
!response.contains("Access-Control-Allow-Origin: *"),
"forbidden command response exposed wildcard CORS: {response}"
);
}
#[tokio::test(flavor = "current_thread")]
async fn command_post_with_dns_rebinding_host_is_rejected() {
let body = r#"{"action":"tabs"}"#;
let request = format!(
"POST /api/command HTTP/1.1\r\nHost: attacker.example:7777\r\nOrigin: http://attacker.example:7777\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
body.len(),
body
);
let response = send_request_to_handler(&request, "x").await;
assert!(
response.starts_with("HTTP/1.1 403 Forbidden"),
"unexpected response: {response}"
);
assert!(
!response.contains("Access-Control-Allow-Origin: *"),
"forbidden command response exposed wildcard CORS: {response}"
);
}
#[tokio::test(flavor = "current_thread")]
async fn command_post_ignores_header_like_body_lines() {
let body = "Referer: http://localhost:7777\r\n{\"action\":\"tabs\"}";
let request = format!(
"POST /api/command HTTP/1.1\r\nHost: localhost:7777\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
body.len(),
body
);
let response = send_request_to_handler(&request, "x").await;
assert!(
response.starts_with("HTTP/1.1 403 Forbidden"),
"unexpected response: {response}"
);
assert!(
!response.contains("Access-Control-Allow-Origin: *"),
"forbidden command response exposed wildcard CORS: {response}"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn same_origin_command_post_relays_without_wildcard_cors() {
let temp_parent = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join("t");
std::fs::create_dir_all(&temp_parent).unwrap();
let socket_dir = tempfile::Builder::new()
.prefix("ab-")
.tempdir_in(temp_parent)
.unwrap();
let guard = EnvGuard::new(&["AGENT_BROWSER_SOCKET_DIR", "XDG_RUNTIME_DIR"]);
guard.set(
"AGENT_BROWSER_SOCKET_DIR",
socket_dir.path().to_str().unwrap(),
);
guard.remove("XDG_RUNTIME_DIR");
let session_name = "x";
let daemon_command = spawn_fake_daemon(socket_dir.path(), session_name).await;
let body = r#"{"action":"tabs"}"#;
let request = format!(
"POST /api/command HTTP/1.1\r\nHost: localhost:7777\r\nOrigin: http://localhost:7777\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
body.len(),
body
);
let response = send_request_to_handler(&request, session_name).await;
assert!(
response.starts_with("HTTP/1.1 200 OK"),
"unexpected response: {response}"
);
assert!(
response.contains("Access-Control-Allow-Origin: http://localhost:7777"),
"same-origin command response did not reflect origin: {response}"
);
assert!(
!response.contains("Access-Control-Allow-Origin: *"),
"same-origin command response exposed wildcard CORS: {response}"
);
let relayed = tokio::time::timeout(std::time::Duration::from_secs(1), daemon_command)
.await
.unwrap()
.unwrap();
assert!(relayed.contains(r#""action":"tabs""#), "{relayed}");
}
}
+486
View File
@@ -0,0 +1,486 @@
mod cdp_loop;
pub(crate) mod chat;
mod dashboard;
mod discovery;
mod http;
mod websocket;
pub use cdp_loop::{ack_screencast_frame, start_screencast, stop_screencast};
pub use dashboard::run_dashboard_server;
use serde_json::{json, Value};
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::sync::{broadcast, watch, Mutex, Notify, RwLock};
use super::cdp::client::CdpClient;
/// Frame metadata from CDP Page.screencastFrame events.
#[derive(Debug, Clone)]
pub struct FrameMetadata {
pub offset_top: f64,
pub page_scale_factor: f64,
pub device_width: u32,
pub device_height: u32,
pub scroll_offset_x: f64,
pub scroll_offset_y: f64,
pub timestamp: u64,
}
impl Default for FrameMetadata {
fn default() -> Self {
Self {
offset_top: 0.0,
page_scale_factor: 1.0,
device_width: 1280,
device_height: 720,
scroll_offset_x: 0.0,
scroll_offset_y: 0.0,
timestamp: 0,
}
}
}
pub struct StreamServer {
port: u16,
session_name: String,
frame_tx: broadcast::Sender<String>,
client_count: Arc<Mutex<usize>>,
client_slot: Arc<RwLock<Option<Arc<CdpClient>>>>,
/// The active CDP page session ID (from Target.attachToTarget).
cdp_session_id: Arc<RwLock<Option<String>>>,
client_notify: Arc<Notify>,
screencasting: Arc<Mutex<bool>>,
viewport_width: Arc<Mutex<u32>>,
viewport_height: Arc<Mutex<u32>>,
last_tabs: Arc<RwLock<Vec<Value>>>,
last_engine: Arc<RwLock<String>>,
last_frame: Arc<RwLock<Option<String>>>,
recording: Arc<Mutex<bool>>,
shutdown_tx: watch::Sender<bool>,
accept_task: Mutex<Option<tokio::task::JoinHandle<()>>>,
cdp_task: Mutex<Option<tokio::task::JoinHandle<()>>>,
}
impl StreamServer {
pub async fn start(
preferred_port: u16,
client: Arc<CdpClient>,
session_id: String,
) -> Result<Self, String> {
let client_slot = Arc::new(RwLock::new(Some(client)));
let (server, _) = Self::start_inner(preferred_port, client_slot, session_id, true).await?;
Ok(server)
}
/// Start the stream server without a CDP client.
/// Returns the server and a shared slot to set the client when the browser launches.
/// Input messages are ignored until the client is set.
/// When `allow_port_fallback` is true, binding to an occupied port falls back to an
/// OS-assigned port (used by daemon startup). When false, the error propagates
/// (used by the runtime `stream_enable` command).
pub async fn start_without_client(
preferred_port: u16,
session_id: String,
allow_port_fallback: bool,
) -> Result<(Self, Arc<RwLock<Option<Arc<CdpClient>>>>), String> {
let client_slot = Arc::new(RwLock::new(None::<Arc<CdpClient>>));
Self::start_inner(preferred_port, client_slot, session_id, allow_port_fallback).await
}
/// Notify the background CDP listener that the client has changed (browser launched/closed).
pub fn notify_client_changed(&self) {
self.client_notify.notify_one();
}
/// Update the active CDP page session ID used for screencast commands.
pub async fn set_cdp_session_id(&self, session_id: Option<String>) {
let mut guard = self.cdp_session_id.write().await;
*guard = session_id;
}
/// Check whether the server currently has active screencast running.
pub async fn is_screencasting(&self) -> bool {
*self.screencasting.lock().await
}
/// Update the stored viewport dimensions and restart the active screencast (if any)
/// so frames are captured at the new size.
pub async fn set_viewport(&self, width: u32, height: u32) {
let mut vw = self.viewport_width.lock().await;
let mut vh = self.viewport_height.lock().await;
if *vw == width && *vh == height {
return;
}
*vw = width;
*vh = height;
drop(vw);
drop(vh);
self.client_notify.notify_one();
}
/// Get the current viewport dimensions.
pub async fn viewport(&self) -> (u32, u32) {
let w = *self.viewport_width.lock().await;
let h = *self.viewport_height.lock().await;
(w, h)
}
/// Override the cached screencast state for explicit CLI start/stop commands.
pub async fn set_screencasting(&self, active: bool) {
let mut guard = self.screencasting.lock().await;
*guard = active;
}
/// Update and broadcast the recording state.
pub async fn set_recording(&self, active: bool, engine: &str) {
*self.recording.lock().await = active;
let connected = self.client_slot.read().await.is_some();
let sc = *self.screencasting.lock().await;
let (vw, vh) = self.viewport().await;
self.broadcast_status(connected, sc, vw, vh, engine).await;
}
/// Shut down the accept loop and background CDP listener, releasing the bound port.
pub async fn shutdown(&self) {
let _ = self.shutdown_tx.send(true);
if let Some(task) = self.accept_task.lock().await.take() {
let _ = task.await;
}
if let Some(task) = self.cdp_task.lock().await.take() {
let _ = task.await;
}
}
async fn start_inner(
preferred_port: u16,
client_slot: Arc<RwLock<Option<Arc<CdpClient>>>>,
session_id: String,
allow_port_fallback: bool,
) -> Result<(Self, Arc<RwLock<Option<Arc<CdpClient>>>>), String> {
let addr = format!("127.0.0.1:{}", preferred_port);
let listener = match TcpListener::bind(&addr).await {
Ok(l) => l,
Err(_) if allow_port_fallback && preferred_port != 0 => {
TcpListener::bind("127.0.0.1:0")
.await
.map_err(|e| format!("Failed to bind stream server: {}", e))?
}
Err(e) => return Err(format!("Failed to bind stream server: {}", e)),
};
let actual_addr = listener
.local_addr()
.map_err(|e| format!("Failed to get stream address: {}", e))?;
let port = actual_addr.port();
let (frame_tx, _) = broadcast::channel::<String>(64);
let client_count = Arc::new(Mutex::new(0usize));
let client_notify = Arc::new(Notify::new());
let screencasting = Arc::new(Mutex::new(false));
let cdp_session_id = Arc::new(RwLock::new(None::<String>));
let viewport_width = Arc::new(Mutex::new(1280u32));
let viewport_height = Arc::new(Mutex::new(720u32));
let last_tabs = Arc::new(RwLock::new(Vec::<Value>::new()));
let last_engine = Arc::new(RwLock::new("chrome".to_string()));
let last_frame = Arc::new(RwLock::new(None::<String>));
let recording = Arc::new(Mutex::new(false));
let (shutdown_tx, shutdown_rx) = watch::channel(false);
let frame_tx_clone = frame_tx.clone();
let client_count_clone = client_count.clone();
let client_slot_clone = client_slot.clone();
let notify_clone = client_notify.clone();
let screencasting_clone = screencasting.clone();
let cdp_session_clone = cdp_session_id.clone();
let vw_clone = viewport_width.clone();
let vh_clone = viewport_height.clone();
let last_tabs_clone = last_tabs.clone();
let last_engine_clone = last_engine.clone();
let last_frame_clone = last_frame.clone();
let recording_clone = recording.clone();
let accept_shutdown_rx = shutdown_rx.clone();
let session_name_clone = session_id.clone();
let accept_task = tokio::spawn(async move {
websocket::accept_loop(
listener,
frame_tx_clone,
client_count_clone,
client_slot_clone,
notify_clone,
screencasting_clone,
cdp_session_clone,
vw_clone,
vh_clone,
last_tabs_clone,
last_engine_clone,
last_frame_clone,
recording_clone,
accept_shutdown_rx,
session_name_clone,
)
.await;
});
let frame_tx_bg = frame_tx.clone();
let client_slot_bg = client_slot.clone();
let client_notify_bg = client_notify.clone();
let screencasting_bg = screencasting.clone();
let client_count_bg = client_count.clone();
let cdp_session_bg = cdp_session_id.clone();
let vw_bg = viewport_width.clone();
let vh_bg = viewport_height.clone();
let last_frame_bg = last_frame.clone();
let last_tabs_bg = last_tabs.clone();
let last_engine_bg = last_engine.clone();
let recording_bg = recording.clone();
let cdp_task = tokio::spawn(async move {
cdp_loop::cdp_event_loop(
frame_tx_bg,
client_slot_bg,
client_notify_bg,
screencasting_bg,
client_count_bg,
cdp_session_bg,
vw_bg,
vh_bg,
last_frame_bg,
last_tabs_bg,
last_engine_bg,
recording_bg,
shutdown_rx,
)
.await;
});
Ok((
Self {
port,
session_name: session_id,
frame_tx,
client_count,
client_slot: client_slot.clone(),
cdp_session_id,
client_notify,
screencasting,
viewport_width,
viewport_height,
last_tabs,
last_engine,
last_frame,
recording,
shutdown_tx,
accept_task: Mutex::new(Some(accept_task)),
cdp_task: Mutex::new(Some(cdp_task)),
},
client_slot,
))
}
pub fn port(&self) -> u16 {
self.port
}
/// Broadcast a raw frame string (legacy).
pub fn broadcast_frame(&self, frame_json: &str) {
let s = frame_json.to_string();
if let Ok(mut lf) = self.last_frame.try_write() {
*lf = Some(s.clone());
}
let _ = self.frame_tx.send(s);
}
/// Broadcast a screencast frame with structured metadata.
pub fn broadcast_screencast_frame(&self, base64_data: &str, metadata: &FrameMetadata) {
let msg = json!({
"type": "frame",
"data": base64_data,
"metadata": {
"offsetTop": metadata.offset_top,
"pageScaleFactor": metadata.page_scale_factor,
"deviceWidth": metadata.device_width,
"deviceHeight": metadata.device_height,
"scrollOffsetX": metadata.scroll_offset_x,
"scrollOffsetY": metadata.scroll_offset_y,
"timestamp": metadata.timestamp,
}
});
let s = msg.to_string();
if let Ok(mut lf) = self.last_frame.try_write() {
*lf = Some(s.clone());
}
let _ = self.frame_tx.send(s);
}
/// Broadcast a status message to all connected clients.
pub async fn broadcast_status(
&self,
connected: bool,
screencasting: bool,
viewport_width: u32,
viewport_height: u32,
engine: &str,
) {
{
let mut guard = self.last_engine.write().await;
*guard = engine.to_string();
}
let rec = *self.recording.lock().await;
let msg = json!({
"type": "status",
"connected": connected,
"screencasting": screencasting,
"viewportWidth": viewport_width,
"viewportHeight": viewport_height,
"engine": engine,
"recording": rec,
});
let _ = self.frame_tx.send(msg.to_string());
}
/// Broadcast an error message to all connected clients.
pub fn broadcast_error(&self, message: &str) {
let msg = json!({
"type": "error",
"message": message,
});
let _ = self.frame_tx.send(msg.to_string());
}
/// Broadcast a command event when a command begins executing.
pub fn broadcast_command(&self, action: &str, id: &str, params: &Value) {
let msg = json!({
"type": "command",
"action": action,
"id": id,
"params": params,
"timestamp": timestamp_ms(),
});
let _ = self.frame_tx.send(msg.to_string());
}
/// Broadcast a result event after a command finishes executing.
pub fn broadcast_result(
&self,
id: &str,
action: &str,
success: bool,
data: &Value,
duration_ms: u64,
) {
let msg = json!({
"type": "result",
"id": id,
"action": action,
"success": success,
"data": data,
"duration_ms": duration_ms,
"timestamp": timestamp_ms(),
});
let _ = self.frame_tx.send(msg.to_string());
}
/// Broadcast a console event from the browser.
pub fn broadcast_console(&self, level: &str, text: &str, args: &[Value]) {
let mut msg = json!({
"type": "console",
"level": level,
"text": text,
"timestamp": timestamp_ms(),
});
if !args.is_empty() {
msg.as_object_mut()
.unwrap()
.insert("args".to_string(), Value::Array(args.to_vec()));
}
let _ = self.frame_tx.send(msg.to_string());
}
/// Broadcast a page error (uncaught exception) from the browser.
pub fn broadcast_page_error(&self, text: &str, line: Option<i64>, column: Option<i64>) {
let msg = json!({
"type": "page_error",
"text": text,
"line": line,
"column": column,
"timestamp": timestamp_ms(),
});
let _ = self.frame_tx.send(msg.to_string());
}
/// Broadcast the current tab list so the dashboard can render a tab bar.
/// Also caches the list so newly connected WebSocket clients receive it immediately.
pub async fn broadcast_tabs(&self, tabs: &[Value]) {
{
let mut guard = self.last_tabs.write().await;
*guard = tabs.to_vec();
}
let msg = json!({
"type": "tabs",
"tabs": tabs,
"timestamp": timestamp_ms(),
});
let _ = self.frame_tx.send(msg.to_string());
}
}
pub(crate) fn timestamp_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
pub fn is_allowed_origin(origin: Option<&str>) -> bool {
match origin {
None => true,
Some(o) => {
if o.starts_with("file://") {
return true;
}
if let Ok(url) = url::Url::parse(o) {
let host = url.host_str().unwrap_or("");
host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "[::1]"
} else {
false
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_allowed_origin_none() {
assert!(is_allowed_origin(None));
}
#[test]
fn test_allowed_origin_file() {
assert!(is_allowed_origin(Some("file:///path/to/file")));
}
#[test]
fn test_allowed_origin_localhost() {
assert!(is_allowed_origin(Some("http://localhost:3000")));
assert!(is_allowed_origin(Some("http://127.0.0.1:8080")));
}
#[test]
fn test_disallowed_origin() {
assert!(!is_allowed_origin(Some("http://evil.com")));
}
#[test]
fn test_frame_metadata_default() {
let meta = FrameMetadata::default();
assert_eq!(meta.device_width, 1280);
assert_eq!(meta.device_height, 720);
assert_eq!(meta.page_scale_factor, 1.0);
}
}
+338
View File
@@ -0,0 +1,338 @@
use serde_json::{json, Value};
use std::net::SocketAddr;
use std::sync::Arc;
use futures_util::{SinkExt, StreamExt};
use tokio::net::TcpListener;
use tokio::sync::{broadcast, watch, Mutex, Notify, RwLock};
use tokio_tungstenite::tungstenite::Message;
use crate::native::cdp::client::CdpClient;
use super::http::handle_http_request;
use super::{is_allowed_origin, timestamp_ms};
#[allow(clippy::too_many_arguments)]
pub(super) async fn accept_loop(
listener: TcpListener,
frame_tx: broadcast::Sender<String>,
client_count: Arc<Mutex<usize>>,
client_slot: Arc<RwLock<Option<Arc<CdpClient>>>>,
client_notify: Arc<Notify>,
screencasting: Arc<Mutex<bool>>,
cdp_session_id: Arc<RwLock<Option<String>>>,
viewport_width: Arc<Mutex<u32>>,
viewport_height: Arc<Mutex<u32>>,
last_tabs: Arc<RwLock<Vec<Value>>>,
last_engine: Arc<RwLock<String>>,
last_frame: Arc<RwLock<Option<String>>>,
recording: Arc<Mutex<bool>>,
mut shutdown_rx: watch::Receiver<bool>,
session_name: String,
) {
let session_name: Arc<str> = Arc::from(session_name);
loop {
tokio::select! {
changed = shutdown_rx.changed() => {
if changed.is_err() || *shutdown_rx.borrow() {
break;
}
}
accept_result = listener.accept() => {
let Ok((stream, addr)) = accept_result else {
break;
};
let frame_tx = frame_tx.clone();
let client_count = client_count.clone();
let client_slot = client_slot.clone();
let client_notify = client_notify.clone();
let screencasting = screencasting.clone();
let cdp_session_id = cdp_session_id.clone();
let vw = viewport_width.clone();
let vh = viewport_height.clone();
let lt = last_tabs.clone();
let le = last_engine.clone();
let lf = last_frame.clone();
let rec = recording.clone();
let shutdown_rx = shutdown_rx.clone();
let sn = session_name.clone();
tokio::spawn(async move {
handle_connection(
stream,
addr,
frame_tx,
client_count,
client_slot,
client_notify,
screencasting,
cdp_session_id,
vw,
vh,
lt,
le,
lf,
rec,
shutdown_rx,
sn,
)
.await;
});
}
}
}
}
fn is_websocket_upgrade(request: &str) -> bool {
request.lines().any(|line| {
if let Some((name, value)) = line.split_once(':') {
name.trim().eq_ignore_ascii_case("upgrade")
&& value.trim().eq_ignore_ascii_case("websocket")
} else {
false
}
})
}
/// Peek at the TCP stream to dispatch between WebSocket upgrade and plain HTTP.
#[allow(clippy::too_many_arguments)]
async fn handle_connection(
stream: tokio::net::TcpStream,
addr: SocketAddr,
frame_tx: broadcast::Sender<String>,
client_count: Arc<Mutex<usize>>,
client_slot: Arc<RwLock<Option<Arc<CdpClient>>>>,
client_notify: Arc<Notify>,
screencasting: Arc<Mutex<bool>>,
cdp_session_id: Arc<RwLock<Option<String>>>,
viewport_width: Arc<Mutex<u32>>,
viewport_height: Arc<Mutex<u32>>,
last_tabs: Arc<RwLock<Vec<Value>>>,
last_engine: Arc<RwLock<String>>,
last_frame: Arc<RwLock<Option<String>>>,
recording: Arc<Mutex<bool>>,
shutdown_rx: watch::Receiver<bool>,
session_name: Arc<str>,
) {
let mut buf = [0u8; 4096];
let n = match stream.peek(&mut buf).await {
Ok(n) => n,
Err(_) => return,
};
let request = String::from_utf8_lossy(&buf[..n]);
if is_websocket_upgrade(&request) {
let frame_rx = frame_tx.subscribe();
handle_ws_client(
stream,
addr,
frame_rx,
client_count,
client_slot,
client_notify,
screencasting,
cdp_session_id,
viewport_width,
viewport_height,
last_tabs,
last_engine,
last_frame,
recording,
shutdown_rx,
)
.await;
} else {
handle_http_request(stream, &buf[..n], &last_tabs, &last_engine, &session_name).await;
}
}
#[allow(clippy::result_large_err, clippy::too_many_arguments)]
async fn handle_ws_client(
stream: tokio::net::TcpStream,
_addr: SocketAddr,
mut frame_rx: broadcast::Receiver<String>,
client_count: Arc<Mutex<usize>>,
client_slot: Arc<RwLock<Option<Arc<CdpClient>>>>,
client_notify: Arc<Notify>,
screencasting: Arc<Mutex<bool>>,
cdp_session_id: Arc<RwLock<Option<String>>>,
viewport_width: Arc<Mutex<u32>>,
viewport_height: Arc<Mutex<u32>>,
last_tabs: Arc<RwLock<Vec<Value>>>,
last_engine: Arc<RwLock<String>>,
last_frame: Arc<RwLock<Option<String>>>,
recording: Arc<Mutex<bool>>,
mut shutdown_rx: watch::Receiver<bool>,
) {
let callback =
|req: &tokio_tungstenite::tungstenite::handshake::server::Request,
resp: tokio_tungstenite::tungstenite::handshake::server::Response| {
let origin = req
.headers()
.get("origin")
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
if !is_allowed_origin(origin.as_deref()) {
let mut reject =
tokio_tungstenite::tungstenite::handshake::server::ErrorResponse::new(Some(
"Origin not allowed".to_string(),
));
*reject.status_mut() = tokio_tungstenite::tungstenite::http::StatusCode::FORBIDDEN;
return Err(reject);
}
Ok(resp)
};
let ws_stream = match tokio_tungstenite::accept_hdr_async(stream, callback).await {
Ok(ws) => ws,
Err(_) => return,
};
{
let mut count = client_count.lock().await;
*count += 1;
}
let (mut ws_tx, mut ws_rx) = ws_stream.split();
{
let guard = client_slot.read().await;
let connected = guard.is_some();
let sc = *screencasting.lock().await;
let vw = *viewport_width.lock().await;
let vh = *viewport_height.lock().await;
let eng = last_engine.read().await.clone();
let rec = *recording.lock().await;
let status = json!({
"type": "status",
"connected": connected,
"screencasting": sc,
"viewportWidth": vw,
"viewportHeight": vh,
"engine": eng,
"recording": rec,
});
let _ = ws_tx.send(Message::Text(status.to_string())).await;
let tabs = last_tabs.read().await;
if !tabs.is_empty() {
let tabs_msg = json!({
"type": "tabs",
"tabs": *tabs,
"timestamp": timestamp_ms(),
});
let _ = ws_tx.send(Message::Text(tabs_msg.to_string())).await;
}
if let Some(ref cached) = *last_frame.read().await {
let _ = ws_tx.send(Message::Text(cached.clone())).await;
}
}
client_notify.notify_one();
loop {
tokio::select! {
changed = shutdown_rx.changed() => {
if changed.is_err() || *shutdown_rx.borrow() {
let _ = ws_tx.send(Message::Close(None)).await;
break;
}
}
frame = frame_rx.recv() => {
match frame {
Ok(data) => {
if ws_tx.send(Message::Text(data)).await.is_err() {
break;
}
}
Err(broadcast::error::RecvError::Lagged(_)) => {
continue;
}
Err(broadcast::error::RecvError::Closed) => break,
}
}
msg = ws_rx.next() => {
match msg {
Some(Ok(Message::Text(text))) => {
let guard = client_slot.read().await;
if let Some(ref client) = *guard {
let sid = cdp_session_id.read().await;
handle_client_message(&text, client.as_ref(), sid.as_deref()).await;
}
}
Some(Ok(Message::Close(_))) | None => break,
_ => {}
}
}
}
}
{
let mut count = client_count.lock().await;
*count = count.saturating_sub(1);
}
client_notify.notify_one();
}
async fn handle_client_message(msg: &str, client: &CdpClient, session_id: Option<&str>) {
let parsed: Value = match serde_json::from_str(msg) {
Ok(v) => v,
Err(_) => return,
};
let msg_type = parsed.get("type").and_then(|v| v.as_str()).unwrap_or("");
match msg_type {
"input_mouse" => {
let _ = client
.send_command(
"Input.dispatchMouseEvent",
Some(json!({
"type": parsed.get("eventType").and_then(|v| v.as_str()).unwrap_or("mouseMoved"),
"x": parsed.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0),
"y": parsed.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0),
"button": parsed.get("button").and_then(|v| v.as_str()).unwrap_or("none"),
"clickCount": parsed.get("clickCount").and_then(|v| v.as_i64()).unwrap_or(0),
"deltaX": parsed.get("deltaX").and_then(|v| v.as_f64()).unwrap_or(0.0),
"deltaY": parsed.get("deltaY").and_then(|v| v.as_f64()).unwrap_or(0.0),
"modifiers": parsed.get("modifiers").and_then(|v| v.as_i64()).unwrap_or(0),
})),
session_id,
)
.await;
}
"input_keyboard" => {
let _ = client
.send_command(
"Input.dispatchKeyEvent",
Some(json!({
"type": parsed.get("eventType").and_then(|v| v.as_str()).unwrap_or("keyDown"),
"key": parsed.get("key"),
"code": parsed.get("code"),
"text": parsed.get("text"),
"windowsVirtualKeyCode": parsed.get("windowsVirtualKeyCode").and_then(|v| v.as_i64()).unwrap_or(0),
"modifiers": parsed.get("modifiers").and_then(|v| v.as_i64()).unwrap_or(0),
})),
session_id,
)
.await;
}
"input_touch" => {
let _ = client
.send_command(
"Input.dispatchTouchEvent",
Some(json!({
"type": parsed.get("eventType").and_then(|v| v.as_str()).unwrap_or("touchStart"),
"touchPoints": parsed.get("touchPoints").unwrap_or(&json!([])),
"modifiers": parsed.get("modifiers").and_then(|v| v.as_i64()).unwrap_or(0),
})),
session_id,
)
.await;
}
"status" => {}
_ => {}
}
}
@@ -0,0 +1,135 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Drag Probe</title>
<style>
body {
margin: 0;
font: 14px/1.4 sans-serif;
background: #f4f4f4;
}
#pad {
position: relative;
width: 800px;
height: 500px;
margin: 24px;
border: 1px solid #999;
background: white;
overflow: hidden;
}
#target {
position: absolute;
left: 320px;
top: 40px;
width: 100px;
height: 40px;
background: #e34c26;
color: white;
display: flex;
align-items: center;
justify-content: center;
user-select: none;
cursor: grab;
}
#target.dragging {
cursor: grabbing;
background: #0d9488;
}
#log {
margin: 24px;
white-space: pre-wrap;
font-family: ui-monospace, monospace;
}
</style>
</head>
<body>
<div id="pad">
<div id="target">drag me</div>
</div>
<pre id="log"></pre>
<script>
const target = document.getElementById("target");
const logEl = document.getElementById("log");
window.__dragProbe = {
dragging: false,
events: [],
finalLeft: 320,
finalTop: 40,
};
let offsetX = 0;
let offsetY = 0;
function pushEvent(event, extra = {}) {
window.__dragProbe.events.push({
type: event.type,
button: event.button,
buttons: event.buttons,
x: event.clientX,
y: event.clientY,
target: event.target.id || event.target.tagName,
...extra,
});
logEl.textContent = JSON.stringify(window.__dragProbe, null, 2);
}
function onPointerLikeStart(event) {
if (event.type === "mousedown") {
const rect = target.getBoundingClientRect();
offsetX = event.clientX - rect.left;
offsetY = event.clientY - rect.top;
window.__dragProbe.dragging = true;
target.classList.add("dragging");
event.preventDefault();
}
pushEvent(event, { phase: "start" });
}
target.addEventListener("mousedown", (event) => {
const rect = target.getBoundingClientRect();
offsetX = event.clientX - rect.left;
offsetY = event.clientY - rect.top;
window.__dragProbe.dragging = true;
target.classList.add("dragging");
event.preventDefault();
pushEvent(event, { phase: "start" });
});
target.addEventListener("pointerdown", onPointerLikeStart);
document.addEventListener("mousemove", (event) => {
if (window.__dragProbe.dragging) {
const left = event.clientX - offsetX;
const top = event.clientY - offsetY;
target.style.left = `${left}px`;
target.style.top = `${top}px`;
window.__dragProbe.finalLeft = left;
window.__dragProbe.finalTop = top;
}
pushEvent(event);
});
document.addEventListener("pointermove", (event) => {
pushEvent(event);
});
document.addEventListener("mouseup", (event) => {
if (window.__dragProbe.dragging) {
window.__dragProbe.dragging = false;
target.classList.remove("dragging");
}
pushEvent(event, { phase: "end" });
});
document.addEventListener("pointerup", (event) => {
pushEvent(event, { phase: "end" });
});
target.addEventListener("dragstart", (event) => {
pushEvent(event, { phase: "dragstart" });
});
</script>
</body>
</html>
@@ -0,0 +1,91 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML5 Drag Probe</title>
<style>
body {
margin: 24px;
font: 14px/1.4 sans-serif;
}
#source, #dest {
width: 120px;
height: 80px;
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid #666;
user-select: none;
margin-right: 40px;
}
#source {
background: #f97316;
color: white;
}
#dest {
background: #e5e7eb;
}
pre {
margin-top: 24px;
white-space: pre-wrap;
font-family: ui-monospace, monospace;
}
</style>
</head>
<body>
<div id="source" draggable="true">drag source</div>
<div id="dest">drop zone</div>
<pre id="log"></pre>
<script>
const source = document.getElementById("source");
const dest = document.getElementById("dest");
const logEl = document.getElementById("log");
window.__html5DragProbe = { events: [] };
function pushEvent(event, extra = {}) {
window.__html5DragProbe.events.push({
type: event.type,
target: event.target.id || event.target.tagName,
x: event.clientX,
y: event.clientY,
button: event.button,
buttons: event.buttons,
...extra,
});
logEl.textContent = JSON.stringify(window.__html5DragProbe, null, 2);
}
for (const type of ["pointerdown", "mousedown", "dragstart", "drag", "dragend"]) {
source.addEventListener(type, (event) => {
if (type === "dragstart") {
event.dataTransfer.setData("text/plain", "probe");
}
pushEvent(event);
});
}
for (const type of ["pointermove", "mousemove", "dragenter", "dragover", "drop", "pointerup", "mouseup"]) {
document.addEventListener(type, (event) => {
if (type === "dragover") {
event.preventDefault();
}
if (type === "drop") {
pushEvent(event, { dropped: event.dataTransfer.getData("text/plain") });
return;
}
pushEvent(event);
});
}
dest.addEventListener("dragover", (event) => event.preventDefault());
dest.addEventListener("drop", (event) => {
pushEvent(event, { dropped: event.dataTransfer.getData("text/plain") });
});
</script>
</body>
</html>
@@ -0,0 +1,113 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Pointer Capture Probe</title>
<style>
body {
margin: 24px;
font: 14px/1.4 sans-serif;
}
#crop {
position: relative;
width: 240px;
height: 180px;
border: 2px solid #fff;
outline: 1px solid #555;
background: rgba(0, 0, 0, 0.2);
}
#handle {
position: absolute;
width: 20px;
height: 20px;
top: -16px;
left: -16px;
padding-top: 13px;
padding-left: 13px;
box-sizing: content-box;
background: rgba(255, 0, 0, 0.25);
}
#handle::after {
content: "";
display: block;
width: 20px;
height: 20px;
border-top: 2px solid white;
border-left: 2px solid white;
}
pre {
margin-top: 24px;
white-space: pre-wrap;
font-family: ui-monospace, monospace;
}
</style>
</head>
<body>
<div id="crop" aria-label="crop area">
<div id="handle" aria-label="crop handle topLeft" data-anchor="topLeft"></div>
</div>
<pre id="log"></pre>
<script>
const crop = document.getElementById("crop");
const handle = document.getElementById("handle");
const logEl = document.getElementById("log");
const state = {
targetAnchor: null,
dragging: false,
moved: false,
events: [],
};
window.__pointerCaptureProbe = state;
function sync() {
logEl.textContent = JSON.stringify(state, null, 2);
}
function push(event, extra = {}) {
state.events.push({
type: event.type,
target: event.target.id || event.target.tagName,
currentTarget: event.currentTarget.id || event.currentTarget.tagName,
pointerId: event.pointerId,
button: event.button,
buttons: event.buttons,
hasCapture: event.currentTarget.hasPointerCapture?.(event.pointerId) ?? false,
x: event.clientX,
y: event.clientY,
...extra,
});
sync();
}
crop.addEventListener("pointerdown", (event) => {
state.targetAnchor = event.target.getAttribute("data-anchor");
crop.setPointerCapture(event.pointerId);
event.preventDefault();
push(event, { phase: "down", targetAnchor: state.targetAnchor });
});
crop.addEventListener("pointermove", (event) => {
const hasCapture = crop.hasPointerCapture(event.pointerId);
if (hasCapture && state.targetAnchor) {
state.dragging = true;
state.moved = true;
}
push(event, { phase: hasCapture ? "drag" : "hover", targetAnchor: state.targetAnchor });
});
crop.addEventListener("pointerup", (event) => {
const hadCapture = crop.hasPointerCapture(event.pointerId);
state.dragging = false;
push(event, { phase: "up", targetAnchor: state.targetAnchor, hadCapture });
state.targetAnchor = null;
});
handle.addEventListener("pointerdown", (event) => push(event, { listener: "handle" }));
handle.addEventListener("pointermove", (event) => push(event, { listener: "handle" }));
handle.addEventListener("pointerup", (event) => push(event, { listener: "handle" }));
sync();
</script>
</body>
</html>
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head><title>Upload Test</title></head>
<body>
<h1>Upload Test</h1>
<label for="fileInput">Choose file:</label>
<input type="file" id="fileInput" name="fileInput">
<div id="result"></div>
<script>
document.getElementById('fileInput').addEventListener('change', function(e) {
var file = e.target.files[0];
if (file) {
document.getElementById('result').textContent = 'uploaded:' + file.name;
}
});
</script>
</body>
</html>
+373
View File
@@ -0,0 +1,373 @@
use serde_json::{json, Value};
use std::path::PathBuf;
use super::cdp::client::CdpClient;
const MAX_PROFILE_EVENTS: usize = 5_000_000;
const DEFAULT_PROFILER_CATEGORIES: &[&str] = &[
"devtools.timeline",
"disabled-by-default-devtools.timeline",
"disabled-by-default-devtools.timeline.frame",
"disabled-by-default-devtools.timeline.stack",
"v8.execute",
"disabled-by-default-v8.cpu_profiler",
"disabled-by-default-v8.cpu_profiler.hires",
"v8",
"disabled-by-default-v8.runtime_stats",
"blink",
"blink.user_timing",
"latencyInfo",
"renderer.scheduler",
"sequence_manager",
"toplevel",
];
pub struct TracingState {
pub active: bool,
pub events: Vec<Value>,
pub events_dropped: bool,
}
impl TracingState {
pub fn new() -> Self {
Self {
active: false,
events: Vec::new(),
events_dropped: false,
}
}
}
pub async fn trace_start(
client: &CdpClient,
session_id: &str,
tracing_state: &mut TracingState,
) -> Result<Value, String> {
if tracing_state.active {
return Err("Tracing already active".to_string());
}
client
.send_command(
"Tracing.start",
Some(json!({
"traceConfig": {
"recordMode": "recordContinuously",
},
"transferMode": "ReturnAsStream",
})),
Some(session_id),
)
.await?;
tracing_state.active = true;
tracing_state.events.clear();
tracing_state.events_dropped = false;
Ok(json!({ "started": true }))
}
pub async fn trace_stop(
client: &CdpClient,
session_id: &str,
tracing_state: &mut TracingState,
path: Option<&str>,
) -> Result<Value, String> {
if !tracing_state.active {
return Err("No tracing in progress".to_string());
}
// Subscribe to events before stopping
let mut rx = client.subscribe();
client
.send_command_no_params("Tracing.end", Some(session_id))
.await?;
// Collect trace data with timeout
let mut trace_events: Vec<Value> = Vec::new();
let mut stream_handle: Option<String> = None;
let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(30);
loop {
let result = tokio::time::timeout_at(deadline, rx.recv()).await;
match result {
Ok(Ok(event)) => {
if event.session_id.as_deref() != Some(session_id) {
continue;
}
match event.method.as_str() {
"Tracing.dataCollected" => {
if let Some(arr) = event.params.get("value").and_then(|v| v.as_array()) {
trace_events.extend(arr.iter().cloned());
}
}
"Tracing.tracingComplete" => {
stream_handle = event
.params
.get("stream")
.and_then(|v| v.as_str())
.map(String::from);
break;
}
_ => {}
}
}
Ok(Err(_)) => break,
Err(_) => {
return Err("Tracing stop timed out after 30s".to_string());
}
}
}
// If ReturnAsStream mode was used, read trace data from the IO stream
if let Some(handle) = stream_handle {
if trace_events.is_empty() {
let stream_data = read_io_stream(client, session_id, &handle).await?;
if let Ok(parsed) = serde_json::from_str::<Value>(&stream_data) {
if let Some(events) = parsed.get("traceEvents").and_then(|v| v.as_array()) {
trace_events.extend(events.iter().cloned());
}
} else {
// Try parsing as newline-delimited JSON
for line in stream_data.lines() {
if let Ok(val) = serde_json::from_str::<Value>(line) {
if let Some(events) = val.get("traceEvents").and_then(|v| v.as_array()) {
trace_events.extend(events.iter().cloned());
} else {
trace_events.push(val);
}
}
}
}
}
// Close the IO stream
let _ = client
.send_command(
"IO.close",
Some(json!({ "handle": handle })),
Some(session_id),
)
.await;
}
tracing_state.active = false;
let save_path = match path {
Some(p) => p.to_string(),
None => {
let dir = get_traces_dir();
let _ = std::fs::create_dir_all(&dir);
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis();
dir.join(format!("trace-{}.json", timestamp))
.to_string_lossy()
.to_string()
}
};
let trace_json = json!({ "traceEvents": trace_events });
let json_str = serde_json::to_string(&trace_json)
.map_err(|e| format!("Failed to serialize trace: {}", e))?;
std::fs::write(&save_path, json_str)
.map_err(|e| format!("Failed to write trace to {}: {}", save_path, e))?;
Ok(json!({ "path": save_path, "eventCount": trace_events.len() }))
}
pub async fn profiler_start(
client: &CdpClient,
session_id: &str,
tracing_state: &mut TracingState,
categories: Option<Vec<String>>,
) -> Result<Value, String> {
if tracing_state.active {
return Err("Profiling/tracing already active".to_string());
}
let cats: Vec<String> = categories.unwrap_or_else(|| {
DEFAULT_PROFILER_CATEGORIES
.iter()
.map(|s| s.to_string())
.collect()
});
client
.send_command(
"Tracing.start",
Some(json!({
"traceConfig": {
"includedCategories": cats,
"enableSampling": true,
},
"transferMode": "ReportEvents",
})),
Some(session_id),
)
.await?;
tracing_state.active = true;
tracing_state.events.clear();
tracing_state.events_dropped = false;
Ok(json!({ "started": true }))
}
pub async fn profiler_stop(
client: &CdpClient,
session_id: &str,
tracing_state: &mut TracingState,
path: Option<&str>,
) -> Result<Value, String> {
if !tracing_state.active {
return Err("No profiling in progress".to_string());
}
let mut rx = client.subscribe();
client
.send_command_no_params("Tracing.end", Some(session_id))
.await?;
let mut events: Vec<Value> = Vec::new();
let mut dropped = false;
let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(30);
loop {
let result = tokio::time::timeout_at(deadline, rx.recv()).await;
match result {
Ok(Ok(event)) => {
if event.session_id.as_deref() != Some(session_id) {
continue;
}
match event.method.as_str() {
"Tracing.dataCollected" => {
if let Some(arr) = event.params.get("value").and_then(|v| v.as_array()) {
if events.len() + arr.len() > MAX_PROFILE_EVENTS {
dropped = true;
} else {
events.extend(arr.iter().cloned());
}
}
}
"Tracing.tracingComplete" => {
break;
}
_ => {}
}
}
Ok(Err(_)) => break,
Err(_) => {
return Err("Profiler stop timed out after 30s".to_string());
}
}
}
tracing_state.active = false;
let save_path = match path {
Some(p) => p.to_string(),
None => {
let dir = get_profiles_dir();
let _ = std::fs::create_dir_all(&dir);
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis();
dir.join(format!("profile-{}.json", timestamp))
.to_string_lossy()
.to_string()
}
};
let clock_domain = get_clock_domain();
let mut profile = json!({ "traceEvents": events });
if let Some(cd) = clock_domain {
profile
.as_object_mut()
.unwrap()
.insert("metadata".to_string(), json!({ "clock-domain": cd }));
}
let json_str = serde_json::to_string(&profile)
.map_err(|e| format!("Failed to serialize profile: {}", e))?;
std::fs::write(&save_path, json_str)
.map_err(|e| format!("Failed to write profile to {}: {}", save_path, e))?;
let event_count = events.len();
let mut result = json!({ "path": save_path, "eventCount": event_count });
if dropped {
result.as_object_mut().unwrap().insert(
"warning".to_string(),
Value::String(format!(
"Events exceeded {} limit; some dropped",
MAX_PROFILE_EVENTS
)),
);
}
Ok(result)
}
/// Read all data from a CDP IO stream handle.
async fn read_io_stream(
client: &CdpClient,
session_id: &str,
handle: &str,
) -> Result<String, String> {
let mut data = String::new();
loop {
let result = client
.send_command(
"IO.read",
Some(json!({
"handle": handle,
"size": 1024 * 1024,
})),
Some(session_id),
)
.await?;
if let Some(chunk) = result.get("data").and_then(|v| v.as_str()) {
data.push_str(chunk);
}
let eof = result.get("eof").and_then(|v| v.as_bool()).unwrap_or(true);
if eof {
break;
}
}
Ok(data)
}
fn get_clock_domain() -> Option<&'static str> {
if cfg!(target_os = "linux") {
Some("LINUX_CLOCK_MONOTONIC")
} else if cfg!(target_os = "macos") {
Some("MAC_MACH_ABSOLUTE_TIME")
} else {
None
}
}
fn get_traces_dir() -> PathBuf {
if let Some(home) = dirs::home_dir() {
home.join(".agent-browser").join("tmp").join("traces")
} else {
std::env::temp_dir().join("agent-browser").join("traces")
}
}
fn get_profiles_dir() -> PathBuf {
if let Some(home) = dirs::home_dir() {
home.join(".agent-browser").join("tmp").join("profiles")
} else {
std::env::temp_dir().join("agent-browser").join("profiles")
}
}
+240
View File
@@ -0,0 +1,240 @@
use serde_json::{json, Value};
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use super::client::WebDriverClient;
const APPIUM_DEFAULT_PORT: u16 = 4723;
const APPIUM_STARTUP_TIMEOUT_SECS: u64 = 30;
pub struct AppiumManager {
pub client: WebDriverClient,
appium_process: Option<Child>,
pub device_udid: Option<String>,
}
impl AppiumManager {
pub async fn connect_or_launch(device_udid: Option<&str>) -> Result<Self, String> {
let port = APPIUM_DEFAULT_PORT;
let client = WebDriverClient::new(port);
// Check if Appium is already running
if is_appium_running(port).await {
return Ok(Self {
client,
appium_process: None,
device_udid: device_udid.map(String::from),
});
}
// Try to launch Appium
let appium_process = launch_appium(port)?;
// Wait for Appium to be ready
wait_for_appium(port, APPIUM_STARTUP_TIMEOUT_SECS).await?;
Ok(Self {
client,
appium_process: Some(appium_process),
device_udid: device_udid.map(String::from),
})
}
pub fn build_ios_capabilities(
device_udid: Option<&str>,
device_name: Option<&str>,
platform_version: Option<&str>,
) -> Value {
let mut caps = json!({
"platformName": "iOS",
"appium:automationName": "XCUITest",
"browserName": "Safari",
"appium:noReset": true,
});
if let Some(name) = device_name {
caps["appium:deviceName"] = json!(name);
} else {
caps["appium:deviceName"] = json!("iPhone");
}
if let Some(ver) = platform_version {
caps["appium:platformVersion"] = json!(ver);
}
if let Some(udid) = device_udid {
caps["appium:udid"] = json!(udid);
}
caps
}
pub async fn create_ios_session(
&mut self,
device_name: Option<&str>,
platform_version: Option<&str>,
) -> Result<Value, String> {
let caps = Self::build_ios_capabilities(
self.device_udid.as_deref(),
device_name,
platform_version,
);
self.client.create_session(caps).await
}
pub async fn tap(&self, x: f64, y: f64) -> Result<(), String> {
let sid = self
.client
.session_id_pub()
.ok_or("No active session")?
.to_string();
let actions = json!({
"actions": [{
"type": "pointer",
"id": "finger1",
"parameters": { "pointerType": "touch" },
"actions": [
{ "type": "pointerMove", "duration": 0, "x": x as i64, "y": y as i64 },
{ "type": "pointerDown", "button": 0 },
{ "type": "pause", "duration": 100 },
{ "type": "pointerUp", "button": 0 },
]
}]
});
self.client.execute_actions(&sid, &actions).await
}
pub async fn swipe(
&self,
start_x: f64,
start_y: f64,
end_x: f64,
end_y: f64,
duration_ms: u64,
) -> Result<(), String> {
let sid = self
.client
.session_id_pub()
.ok_or("No active session")?
.to_string();
let actions = json!({
"actions": [{
"type": "pointer",
"id": "finger1",
"parameters": { "pointerType": "touch" },
"actions": [
{ "type": "pointerMove", "duration": 0, "x": start_x as i64, "y": start_y as i64 },
{ "type": "pointerDown", "button": 0 },
{ "type": "pointerMove", "duration": duration_ms, "x": end_x as i64, "y": end_y as i64 },
{ "type": "pointerUp", "button": 0 },
]
}]
});
self.client.execute_actions(&sid, &actions).await
}
pub async fn close(&mut self) -> Result<(), String> {
let _ = self.client.delete_session().await;
if let Some(ref mut child) = self.appium_process {
let _ = child.kill();
let _ = child.wait();
}
Ok(())
}
}
impl Drop for AppiumManager {
fn drop(&mut self) {
if let Some(ref mut child) = self.appium_process {
let _ = child.kill();
let _ = child.wait();
}
}
}
async fn is_appium_running(port: u16) -> bool {
let addr = format!("127.0.0.1:{}", port);
tokio::time::timeout(
Duration::from_secs(2),
tokio::net::TcpStream::connect(&addr),
)
.await
.map(|r| r.is_ok())
.unwrap_or(false)
}
fn launch_appium(port: u16) -> Result<Child, String> {
// Try npx appium first, then direct appium
let result = Command::new("npx")
.args(["appium", "--relaxed-security", "--port", &port.to_string()])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn();
match result {
Ok(child) => Ok(child),
Err(_) => Command::new("appium")
.args(["--relaxed-security", "--port", &port.to_string()])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| {
format!(
"Failed to launch Appium. Install it with: npm install -g appium. Error: {}",
e
)
}),
}
}
async fn wait_for_appium(port: u16, timeout_secs: u64) -> Result<(), String> {
let deadline = tokio::time::Instant::now() + Duration::from_secs(timeout_secs);
loop {
if tokio::time::Instant::now() > deadline {
return Err("Timeout waiting for Appium to start".to_string());
}
if is_appium_running(port).await {
return Ok(());
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_appium_constants() {
assert_eq!(APPIUM_DEFAULT_PORT, 4723);
assert_eq!(APPIUM_STARTUP_TIMEOUT_SECS, 30);
}
#[test]
fn test_ios_capabilities_use_vendor_prefix() {
let caps = AppiumManager::build_ios_capabilities(
Some("TEST-UDID-123"),
Some("iPhone 16 Pro"),
Some("18.5"),
);
// W3C standard capabilities must NOT have vendor prefix
assert!(caps.get("platformName").is_some());
assert!(caps.get("browserName").is_some());
// Non-standard capabilities MUST have appium: vendor prefix
assert!(caps.get("appium:automationName").is_some());
assert!(caps.get("appium:noReset").is_some());
assert!(caps.get("appium:deviceName").is_some());
assert!(caps.get("appium:platformVersion").is_some());
assert!(caps.get("appium:udid").is_some());
// Must NOT have unprefixed non-standard capabilities
assert!(caps.get("automationName").is_none());
assert!(caps.get("noReset").is_none());
assert!(caps.get("deviceName").is_none());
assert!(caps.get("udid").is_none());
}
}
+142
View File
@@ -0,0 +1,142 @@
use async_trait::async_trait;
use serde_json::Value;
/// Abstract backend for browser automation. CDP (Chromium) and WebDriver
/// (Safari/iOS) share this interface so actions.rs can remain backend-agnostic
/// in the future.
#[async_trait]
pub trait BrowserBackend: Send + Sync {
async fn navigate(&self, url: &str) -> Result<(), String>;
async fn get_url(&self) -> Result<String, String>;
async fn get_title(&self) -> Result<String, String>;
async fn get_content(&self) -> Result<String, String>;
async fn evaluate(&self, script: &str) -> Result<Value, String>;
async fn screenshot(&self) -> Result<String, String>;
async fn click(&self, selector: &str) -> Result<(), String>;
async fn fill(&self, selector: &str, value: &str) -> Result<(), String>;
async fn close(&mut self) -> Result<(), String>;
async fn back(&self) -> Result<(), String>;
async fn forward(&self) -> Result<(), String>;
async fn reload(&self) -> Result<(), String>;
async fn get_cookies(&self) -> Result<Value, String>;
fn backend_type(&self) -> &str;
fn supports(&self, feature: &str) -> bool {
match feature {
"navigate" | "evaluate" | "screenshot" | "click" | "fill" => true,
"screencast" | "tracing" | "network_intercept" | "cdp" => self.backend_type() == "cdp",
_ => false,
}
}
fn unsupported_error(&self, action: &str) -> String {
format!(
"Action '{}' is not supported on the {} backend",
action,
self.backend_type()
)
}
}
/// WebDriver implementation of BrowserBackend
pub struct WebDriverBackend {
client: super::client::WebDriverClient,
}
impl WebDriverBackend {
pub fn new(client: super::client::WebDriverClient) -> Self {
Self { client }
}
}
#[async_trait]
impl BrowserBackend for WebDriverBackend {
async fn navigate(&self, url: &str) -> Result<(), String> {
self.client.navigate(url).await
}
async fn get_url(&self) -> Result<String, String> {
self.client.get_url().await
}
async fn get_title(&self) -> Result<String, String> {
self.client.get_title().await
}
async fn get_content(&self) -> Result<String, String> {
self.client.get_page_source().await
}
async fn evaluate(&self, script: &str) -> Result<Value, String> {
self.client.execute_script(script, vec![]).await
}
async fn screenshot(&self) -> Result<String, String> {
self.client.screenshot().await
}
async fn click(&self, selector: &str) -> Result<(), String> {
let element_id = self.client.find_element("css selector", selector).await?;
self.client.click_element(&element_id).await
}
async fn fill(&self, selector: &str, value: &str) -> Result<(), String> {
let element_id = self.client.find_element("css selector", selector).await?;
self.client.clear_element(&element_id).await?;
self.client.send_keys(&element_id, value).await
}
async fn close(&mut self) -> Result<(), String> {
self.client.delete_session().await
}
async fn back(&self) -> Result<(), String> {
self.client.back().await
}
async fn forward(&self) -> Result<(), String> {
self.client.forward().await
}
async fn reload(&self) -> Result<(), String> {
self.client.refresh().await
}
async fn get_cookies(&self) -> Result<Value, String> {
self.client.get_cookies().await
}
fn backend_type(&self) -> &str {
"webdriver"
}
}
/// CDP-backed backend constants for unsupported actions on WebDriver
pub const WEBDRIVER_UNSUPPORTED_ACTIONS: &[&str] = &[
"screencast_start",
"screencast_stop",
"trace_start",
"trace_stop",
"profiler_start",
"profiler_stop",
"route",
"unroute",
"expose",
"addscript",
"addinitscript",
"network",
"har_start",
"har_stop",
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_unsupported_actions() {
assert!(WEBDRIVER_UNSUPPORTED_ACTIONS.contains(&"screencast_start"));
assert!(WEBDRIVER_UNSUPPORTED_ACTIONS.contains(&"trace_start"));
assert!(!WEBDRIVER_UNSUPPORTED_ACTIONS.contains(&"navigate"));
}
}
+318
View File
@@ -0,0 +1,318 @@
use serde_json::{json, Value};
use std::time::Duration;
pub struct WebDriverClient {
base_url: String,
session_id: Option<String>,
}
impl WebDriverClient {
pub fn new(port: u16) -> Self {
Self {
base_url: format!("http://127.0.0.1:{}", port),
session_id: None,
}
}
pub async fn create_session(&mut self, capabilities: Value) -> Result<Value, String> {
let body = json!({
"capabilities": {
"alwaysMatch": capabilities,
}
});
let response = self.post("/session", &body).await?;
let session_id = response
.get("value")
.and_then(|v| v.get("sessionId"))
.and_then(|v| v.as_str())
.ok_or("No sessionId in response")?
.to_string();
self.session_id = Some(session_id);
Ok(response)
}
pub async fn delete_session(&mut self) -> Result<(), String> {
if let Some(ref sid) = self.session_id.clone() {
let _ = self.delete(&format!("/session/{}", sid)).await;
self.session_id = None;
}
Ok(())
}
pub async fn navigate(&self, url: &str) -> Result<(), String> {
let sid = self.session_id()?.to_string();
self.post(&format!("/session/{}/url", sid), &json!({ "url": url }))
.await?;
Ok(())
}
pub async fn get_url(&self) -> Result<String, String> {
let sid = self.session_id()?.to_string();
let response = self.get(&format!("/session/{}/url", sid)).await?;
Ok(response
.get("value")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string())
}
pub async fn get_title(&self) -> Result<String, String> {
let sid = self.session_id()?.to_string();
let response = self.get(&format!("/session/{}/title", sid)).await?;
Ok(response
.get("value")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string())
}
pub async fn find_element(&self, using: &str, value: &str) -> Result<String, String> {
let sid = self.session_id()?.to_string();
let response = self
.post(
&format!("/session/{}/element", sid),
&json!({ "using": using, "value": value }),
)
.await?;
let element_value = response.get("value").ok_or("No element in response")?;
element_value
.get("element-6066-11e4-a52e-4f735466cecf")
.or_else(|| element_value.get("ELEMENT"))
.and_then(|v| v.as_str())
.map(String::from)
.ok_or("No element ID in response".to_string())
}
pub async fn click_element(&self, element_id: &str) -> Result<(), String> {
let sid = self.session_id()?.to_string();
self.post(
&format!("/session/{}/element/{}/click", sid, element_id),
&json!({}),
)
.await?;
Ok(())
}
pub async fn send_keys(&self, element_id: &str, text: &str) -> Result<(), String> {
let sid = self.session_id()?.to_string();
self.post(
&format!("/session/{}/element/{}/value", sid, element_id),
&json!({ "text": text }),
)
.await?;
Ok(())
}
pub async fn clear_element(&self, element_id: &str) -> Result<(), String> {
let sid = self.session_id()?.to_string();
self.post(
&format!("/session/{}/element/{}/clear", sid, element_id),
&json!({}),
)
.await?;
Ok(())
}
pub async fn execute_script(&self, script: &str, args: Vec<Value>) -> Result<Value, String> {
let sid = self.session_id()?.to_string();
let response = self
.post(
&format!("/session/{}/execute/sync", sid),
&json!({ "script": script, "args": args }),
)
.await?;
Ok(response.get("value").cloned().unwrap_or(Value::Null))
}
pub async fn screenshot(&self) -> Result<String, String> {
let sid = self.session_id()?.to_string();
let response = self.get(&format!("/session/{}/screenshot", sid)).await?;
Ok(response
.get("value")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string())
}
pub async fn get_cookies(&self) -> Result<Value, String> {
let sid = self.session_id()?.to_string();
let response = self.get(&format!("/session/{}/cookie", sid)).await?;
Ok(response.get("value").cloned().unwrap_or(Value::Null))
}
pub async fn get_page_source(&self) -> Result<String, String> {
let sid = self.session_id()?.to_string();
let response = self.get(&format!("/session/{}/source", sid)).await?;
Ok(response
.get("value")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string())
}
pub async fn back(&self) -> Result<(), String> {
let sid = self.session_id()?.to_string();
self.post(&format!("/session/{}/back", sid), &json!({}))
.await?;
Ok(())
}
pub async fn forward(&self) -> Result<(), String> {
let sid = self.session_id()?.to_string();
self.post(&format!("/session/{}/forward", sid), &json!({}))
.await?;
Ok(())
}
pub async fn refresh(&self) -> Result<(), String> {
let sid = self.session_id()?.to_string();
self.post(&format!("/session/{}/refresh", sid), &json!({}))
.await?;
Ok(())
}
pub fn session_id_pub(&self) -> Option<&str> {
self.session_id.as_deref()
}
pub fn new_with_session(port: u16, session_id: String) -> Self {
Self {
base_url: format!("http://127.0.0.1:{}", port),
session_id: Some(session_id),
}
}
pub async fn execute_actions(&self, session_id: &str, actions: &Value) -> Result<(), String> {
self.post(&format!("/session/{}/actions", session_id), actions)
.await?;
Ok(())
}
fn session_id(&self) -> Result<&str, String> {
self.session_id
.as_deref()
.ok_or("No active WebDriver session".to_string())
}
async fn get(&self, path: &str) -> Result<Value, String> {
http_request("GET", &format!("{}{}", self.base_url, path), None).await
}
async fn post(&self, path: &str, body: &Value) -> Result<Value, String> {
http_request("POST", &format!("{}{}", self.base_url, path), Some(body)).await
}
async fn delete(&self, path: &str) -> Result<Value, String> {
http_request("DELETE", &format!("{}{}", self.base_url, path), None).await
}
}
async fn http_request(method: &str, url: &str, body: Option<&Value>) -> Result<Value, String> {
let parsed = url::Url::parse(url).map_err(|e| format!("Invalid URL: {}", e))?;
let host = parsed.host_str().unwrap_or("127.0.0.1");
let port = parsed.port().unwrap_or(80);
let path = parsed.path();
let addr = format!("{}:{}", host, port);
let stream = tokio::time::timeout(
Duration::from_secs(10),
tokio::net::TcpStream::connect(&addr),
)
.await
.map_err(|_| format!("Connection timeout: {}", addr))?
.map_err(|e| format!("Connection failed: {}", e))?;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let body_str = body
.map(|b| serde_json::to_string(b).unwrap_or_default())
.unwrap_or_default();
let request = if body.is_some() {
format!(
"{} {} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
method, path, addr, body_str.len(), body_str
)
} else {
format!(
"{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n",
method, path, addr
)
};
let mut stream = stream;
stream
.write_all(request.as_bytes())
.await
.map_err(|e| format!("Write failed: {}", e))?;
let mut response = Vec::new();
stream
.read_to_end(&mut response)
.await
.map_err(|e| format!("Read failed: {}", e))?;
let response_str = String::from_utf8_lossy(&response);
let body_part = response_str.split("\r\n\r\n").nth(1).unwrap_or("").trim();
// Handle chunked encoding
let json_body = if body_part.contains('\n')
&& body_part
.chars()
.next()
.map(|c| c.is_ascii_hexdigit())
.unwrap_or(false)
{
// Chunked: skip chunk size lines
body_part
.lines()
.filter(|l| !l.chars().all(|c| c.is_ascii_hexdigit() || c == '\r'))
.collect::<Vec<&str>>()
.join("")
} else {
body_part.to_string()
};
if json_body.is_empty() {
return Ok(json!({}));
}
serde_json::from_str(&json_body).map_err(|e| {
format!(
"Invalid JSON response: {} (body: {})",
e,
json_body.chars().take(100).collect::<String>()
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_client_new() {
let client = WebDriverClient::new(4444);
assert_eq!(client.base_url, "http://127.0.0.1:4444");
assert!(client.session_id.is_none());
}
#[test]
fn test_session_id_none() {
let client = WebDriverClient::new(4444);
let result = client.session_id();
assert!(result.is_err());
assert!(result.unwrap_err().contains("No active WebDriver session"));
}
#[test]
fn test_client_custom_port() {
let client = WebDriverClient::new(9515);
assert_eq!(client.base_url, "http://127.0.0.1:9515");
}
}
+235
View File
@@ -0,0 +1,235 @@
use serde_json::{json, Value};
use std::process::Command;
#[derive(Debug, Clone)]
pub struct IosDevice {
pub name: String,
pub udid: String,
pub state: String,
pub runtime: String,
pub is_real: bool,
}
pub fn list_simulators() -> Result<Vec<IosDevice>, String> {
let output = Command::new("xcrun")
.args(["simctl", "list", "devices", "--json"])
.output()
.map_err(|e| format!("Failed to run xcrun simctl: {}", e))?;
if !output.status.success() {
return Err("xcrun simctl failed. Xcode may not be installed.".to_string());
}
let json_str = String::from_utf8_lossy(&output.stdout);
let parsed: Value =
serde_json::from_str(&json_str).map_err(|e| format!("Failed to parse simctl: {}", e))?;
let mut devices = Vec::new();
if let Some(device_map) = parsed.get("devices").and_then(|v| v.as_object()) {
for (runtime, device_list) in device_map {
if let Some(arr) = device_list.as_array() {
for device in arr {
let name = device
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let udid = device
.get("udid")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let state = device
.get("state")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
devices.push(IosDevice {
name,
udid,
state,
runtime: runtime.clone(),
is_real: false,
});
}
}
}
}
Ok(devices)
}
pub fn list_real_devices() -> Result<Vec<IosDevice>, String> {
let output = Command::new("xcrun")
.args(["xctrace", "list", "devices"])
.output()
.map_err(|e| format!("Failed to run xcrun xctrace: {}", e))?;
if !output.status.success() {
return Ok(Vec::new());
}
let stdout = String::from_utf8_lossy(&output.stdout);
let mut devices = Vec::new();
let mut in_devices = false;
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.starts_with("== Devices ==") {
in_devices = true;
continue;
}
if trimmed.starts_with("== Simulators ==") {
break;
}
if !in_devices || trimmed.is_empty() {
continue;
}
// Format: "Device Name (OS Version) (UDID)"
if let Some(udid_start) = trimmed.rfind('(') {
let udid_end = trimmed.len() - 1;
let udid = &trimmed[udid_start + 1..udid_end];
// Validate it looks like a UDID (contains hyphens)
if udid.contains('-') && udid.len() > 20 {
let name_part = trimmed[..udid_start].trim();
let name = if let Some(paren_pos) = name_part.rfind('(') {
name_part[..paren_pos].trim().to_string()
} else {
name_part.to_string()
};
devices.push(IosDevice {
name,
udid: udid.to_string(),
state: "Connected".to_string(),
runtime: String::new(),
is_real: true,
});
}
}
}
Ok(devices)
}
pub fn list_all_devices() -> Result<Vec<IosDevice>, String> {
let mut all = list_simulators().unwrap_or_default();
all.extend(list_real_devices().unwrap_or_default());
Ok(all)
}
pub fn boot_simulator(udid: &str) -> Result<(), String> {
let output = Command::new("xcrun")
.args(["simctl", "boot", udid])
.output()
.map_err(|e| format!("Failed to boot simulator: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr.contains("current state: Booted") {
return Ok(());
}
return Err(format!("Failed to boot simulator {}: {}", udid, stderr));
}
Ok(())
}
pub fn shutdown_simulator(udid: &str) -> Result<(), String> {
let output = Command::new("xcrun")
.args(["simctl", "shutdown", udid])
.output()
.map_err(|e| format!("Failed to shutdown simulator: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr.contains("current state: Shutdown") {
return Ok(());
}
return Err(format!("Failed to shutdown simulator {}: {}", udid, stderr));
}
Ok(())
}
pub fn select_device(device_name: Option<&str>, udid: Option<&str>) -> Result<IosDevice, String> {
if let Some(u) = udid {
let devices = list_all_devices()?;
return devices
.into_iter()
.find(|d| d.udid == u)
.ok_or_else(|| format!("Device with UDID '{}' not found", u));
}
if let Some(name) = device_name {
let devices = list_all_devices()?;
return devices
.into_iter()
.find(|d| d.name.to_lowercase().contains(&name.to_lowercase()))
.ok_or_else(|| format!("Device '{}' not found", name));
}
// Default: prefer most recent iPhone, prefer Pro
let devices = list_simulators()?;
let iphone_devices: Vec<&IosDevice> = devices
.iter()
.filter(|d| d.name.starts_with("iPhone"))
.collect();
if iphone_devices.is_empty() {
return devices
.into_iter()
.next()
.ok_or("No iOS simulators found".to_string());
}
// Prefer Pro models
if let Some(pro) = iphone_devices.iter().find(|d| d.name.contains("Pro")) {
return Ok((*pro).clone());
}
Ok((*iphone_devices.last().unwrap()).clone())
}
pub fn to_device_json(devices: &[IosDevice]) -> Value {
let list: Vec<Value> = devices
.iter()
.map(|d| {
json!({
"name": d.name,
"udid": d.udid,
"state": d.state,
"runtime": d.runtime,
"isReal": d.is_real,
})
})
.collect();
json!({ "devices": list })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ios_device_struct() {
let device = IosDevice {
name: "iPhone 15 Pro".to_string(),
udid: "ABC-123".to_string(),
state: "Booted".to_string(),
runtime: "iOS-17-0".to_string(),
is_real: false,
};
assert_eq!(device.name, "iPhone 15 Pro");
assert!(!device.is_real);
}
#[test]
fn test_to_device_json() {
let devices = vec![IosDevice {
name: "Test".to_string(),
udid: "123".to_string(),
state: "Shutdown".to_string(),
runtime: "iOS-17".to_string(),
is_real: false,
}];
let json = to_device_json(&devices);
assert!(json.get("devices").unwrap().as_array().unwrap().len() == 1);
}
}
+6
View File
@@ -0,0 +1,6 @@
pub mod appium;
pub mod backend;
pub mod client;
pub mod ios;
pub mod safari;
pub mod types;
+80
View File
@@ -0,0 +1,80 @@
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::time::Duration;
pub struct SafariDriverProcess {
child: Child,
pub port: u16,
}
impl SafariDriverProcess {
pub fn kill(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
impl Drop for SafariDriverProcess {
fn drop(&mut self) {
self.kill();
}
}
pub fn find_safaridriver() -> Option<PathBuf> {
let candidates = ["/usr/bin/safaridriver"];
for c in &candidates {
let p = PathBuf::from(c);
if p.exists() {
return Some(p);
}
}
// Try PATH
if let Ok(output) = Command::new("which").arg("safaridriver").output() {
if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !path.is_empty() {
return Some(PathBuf::from(path));
}
}
}
None
}
pub fn launch_safaridriver(port: u16) -> Result<SafariDriverProcess, String> {
let driver_path = find_safaridriver()
.ok_or("safaridriver not found. Safari WebDriver requires macOS with Safari.")?;
let child = Command::new(&driver_path)
.arg("--port")
.arg(port.to_string())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.map_err(|e| format!("Failed to launch safaridriver: {}", e))?;
// Wait for driver to be ready
std::thread::sleep(Duration::from_millis(500));
Ok(SafariDriverProcess { child, port })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_find_safaridriver() {
// Only check on macOS
if cfg!(target_os = "macos") {
let result = find_safaridriver();
// Don't assert Some since it may not be enabled
if let Some(path) = result {
assert!(path.exists());
}
}
}
}
+97
View File
@@ -0,0 +1,97 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NewSessionRequest {
pub capabilities: Capabilities,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Capabilities {
pub always_match: Value,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionResponse {
pub value: SessionValue,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionValue {
pub session_id: String,
pub capabilities: Value,
}
#[derive(Debug, Deserialize)]
pub struct WebDriverResponse {
pub value: Value,
}
#[derive(Debug, Deserialize)]
pub struct WebDriverError {
pub error: String,
pub message: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ElementResponse {
pub value: ElementValue,
}
#[derive(Debug, Deserialize)]
pub struct ElementValue {
#[serde(rename = "element-6066-11e4-a52e-4f735466cecf")]
pub element_id: Option<String>,
#[serde(rename = "ELEMENT")]
pub element_legacy: Option<String>,
}
impl ElementValue {
pub fn id(&self) -> Option<&str> {
self.element_id
.as_deref()
.or(self.element_legacy.as_deref())
}
}
#[derive(Debug, Serialize)]
pub struct FindElementRequest {
pub using: String,
pub value: String,
}
#[derive(Debug, Serialize)]
pub struct ExecuteScriptRequest {
pub script: String,
pub args: Vec<Value>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CookieRequest {
pub cookie: CookieData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CookieData {
pub name: String,
pub value: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub domain: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub secure: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub http_only: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expiry: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub same_site: Option<String>,
}
+2350 -169
View File
File diff suppressed because it is too large Load Diff
+622
View File
@@ -0,0 +1,622 @@
use serde_json::json;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::exit;
use crate::color;
struct SkillInfo {
name: String,
description: String,
dir: PathBuf,
/// When true, the skill is omitted from `skills list` and `skills get --all`
/// but can still be fetched by name via `skills get <name>`. Used for
/// bootstrap stubs that exist for external tooling (e.g. `npx skills add`)
/// but aren't the intended entry point for agents already inside the CLI.
hidden: bool,
}
/// Skill content is split across two directories:
///
/// - `skills/` — discovery stubs (picked up by `npx skills add`). Carry
/// `hidden: true` so they don't show up in `skills list` or `skills get
/// --all` inside the CLI, since they exist only to redirect external
/// agents to `skills get core`.
/// - `skill-data/` — runtime skill content served by the CLI (`core`,
/// `electron`, `slack`, `dogfood`, etc.).
///
/// Both are shipped in the npm package and searched by `discover_skills`.
const SKILL_DIRS: &[&str] = &["skills", "skill-data"];
/// Locate the package root that contains the skill directories.
///
/// Resolution order:
/// 1. AGENT_BROWSER_SKILLS_DIR env var (points directly at a single directory)
/// 2. ../ relative to the executable (npm installs: binary is in bin/)
/// 3. Walk up from the executable to find a project root with skills/
/// (dev builds where binary is in target/debug/ or target/release/)
fn find_package_root() -> Option<PathBuf> {
if let Ok(exe) = env::current_exe() {
let exe = exe.canonicalize().unwrap_or(exe);
if let Some(parent) = exe.parent() {
// npm install layout: bin/agent-browser-* -> ../
let candidate = parent.join("..");
if candidate.join("skills").is_dir() {
return Some(candidate.canonicalize().unwrap_or(candidate));
}
// dev build layout: walk up from target/debug/ or target/release/
let mut dir = parent;
loop {
if dir.join("skills").is_dir() {
return Some(dir.to_path_buf());
}
match dir.parent() {
Some(p) => dir = p,
None => break,
}
}
}
}
None
}
/// Collect all skill directories to search, respecting the env var override.
fn find_skills_dirs() -> Vec<PathBuf> {
// Env var override: single directory, used as-is
if let Ok(dir) = env::var("AGENT_BROWSER_SKILLS_DIR") {
let p = PathBuf::from(dir);
if p.is_dir() {
return vec![p];
}
}
let Some(root) = find_package_root() else {
return vec![];
};
SKILL_DIRS
.iter()
.map(|d| root.join(d))
.filter(|p| p.is_dir())
.collect()
}
/// Parse YAML frontmatter from a SKILL.md file. Returns (name, description, hidden).
fn parse_frontmatter(content: &str) -> Option<(String, String, bool)> {
let content = content.trim_start();
if !content.starts_with("---") {
return None;
}
let after_opening = &content[3..];
let end = after_opening.find("\n---")?;
let frontmatter = &after_opening[..end];
let mut name = None;
let mut description = None;
let mut hidden = false;
let lines: Vec<&str> = frontmatter.lines().collect();
let mut i = 0;
while i < lines.len() {
let line = lines[i];
if let Some(val) = line.strip_prefix("name:") {
name = Some(val.trim().to_string());
} else if let Some(val) = line.strip_prefix("description:") {
let mut desc = val.trim().to_string();
// Consume YAML continuation lines (indented with spaces or tab)
while i + 1 < lines.len()
&& (lines[i + 1].starts_with(" ") || lines[i + 1].starts_with('\t'))
{
i += 1;
desc.push(' ');
desc.push_str(lines[i].trim());
}
description = Some(desc);
} else if let Some(val) = line.strip_prefix("hidden:") {
hidden = matches!(val.trim(), "true" | "yes");
}
i += 1;
}
Some((name?, description.unwrap_or_default(), hidden))
}
/// Discover all skills across the given directories.
fn discover_skills(dirs: &[PathBuf]) -> Vec<SkillInfo> {
let mut skills = Vec::new();
for skills_dir in dirs {
let entries = match fs::read_dir(skills_dir) {
Ok(e) => e,
Err(_) => continue,
};
for entry in entries.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
let skill_md = path.join("SKILL.md");
if !skill_md.exists() {
continue;
}
let content = match fs::read_to_string(&skill_md) {
Ok(c) => c,
Err(_) => continue,
};
if let Some((name, description, hidden)) = parse_frontmatter(&content) {
skills.push(SkillInfo {
name,
description,
dir: path,
hidden,
});
}
}
}
skills.sort_by(|a, b| a.name.cmp(&b.name));
skills
}
fn truncate_description(desc: &str, max_len: usize) -> String {
if desc.len() <= max_len {
return desc.to_string();
}
let boundary = desc
.char_indices()
.take_while(|(i, _)| *i <= max_len)
.last()
.map(|(i, _)| i)
.unwrap_or(max_len);
let end = desc[..boundary].rfind(' ').unwrap_or(boundary);
format!("{}...", &desc[..end])
}
/// Read the full SKILL.md content (including frontmatter).
fn read_skill_full(skill_md: &Path) -> Option<String> {
fs::read_to_string(skill_md).ok()
}
/// Collect all supplementary files (references/, templates/) for a skill.
fn collect_supplementary_files(skill_dir: &Path) -> Vec<(String, String)> {
let mut files = Vec::new();
for subdir_name in &["references", "templates"] {
let subdir = skill_dir.join(subdir_name);
if !subdir.is_dir() {
continue;
}
let mut entries: Vec<_> = match fs::read_dir(&subdir) {
Ok(e) => e.flatten().collect(),
Err(_) => continue,
};
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
if path.is_file() {
if let Ok(content) = fs::read_to_string(&path) {
let rel = format!(
"{}/{}",
subdir_name,
path.file_name().unwrap_or_default().to_string_lossy()
);
files.push((rel, content));
}
}
}
}
files
}
fn run_list(skills_dirs: &[PathBuf], json_mode: bool) {
let skills: Vec<SkillInfo> = discover_skills(skills_dirs)
.into_iter()
.filter(|s| !s.hidden)
.collect();
if skills.is_empty() {
if json_mode {
println!(
"{}",
serde_json::to_string(&json!({ "success": true, "data": [] })).unwrap_or_default()
);
} else {
println!("No skills found");
}
return;
}
if json_mode {
let items: Vec<serde_json::Value> = skills
.iter()
.map(|s| {
json!({
"name": s.name,
"description": s.description,
})
})
.collect();
println!(
"{}",
serde_json::to_string(&json!({ "success": true, "data": items })).unwrap_or_default()
);
} else {
let max_name = skills.iter().map(|s| s.name.len()).max().unwrap_or(0);
for s in &skills {
println!(
" {:<width$} {}",
s.name,
truncate_description(&s.description, 70),
width = max_name
);
}
}
}
fn run_get(skills_dirs: &[PathBuf], names: &[String], get_all: bool, full: bool, json_mode: bool) {
let all_skills = discover_skills(skills_dirs);
let targets: Vec<&SkillInfo> = if get_all {
all_skills.iter().filter(|s| !s.hidden).collect()
} else {
let mut targets = Vec::new();
for name in names {
if name.starts_with('-') {
eprintln!(
"{} Unknown flag ignored: {}",
color::warning_indicator(),
name
);
continue;
}
match all_skills.iter().find(|s| s.name == *name) {
Some(s) => targets.push(s),
None => {
if json_mode {
println!(
"{}",
serde_json::to_string(&json!({
"success": false,
"error": format!("Skill not found: {}", name),
}))
.unwrap_or_default()
);
} else {
eprintln!("{} Skill not found: {}", color::error_indicator(), name);
}
exit(1);
}
}
}
targets
};
if targets.is_empty() {
if json_mode {
println!(
"{}",
serde_json::to_string(&json!({
"success": false,
"error": "No skill name provided. Usage: agent-browser skills get <name>",
}))
.unwrap_or_default()
);
} else {
eprintln!(
"{} No skill name provided. Usage: agent-browser skills get <name>",
color::error_indicator()
);
}
exit(1);
}
if json_mode {
let items: Vec<serde_json::Value> = targets
.iter()
.map(|s| {
let skill_md = s.dir.join("SKILL.md");
let content = read_skill_full(&skill_md).unwrap_or_default();
let mut obj = json!({
"name": s.name,
"content": content,
});
if full {
let supplementary = collect_supplementary_files(&s.dir);
if !supplementary.is_empty() {
let files: Vec<serde_json::Value> = supplementary
.iter()
.map(|(path, content)| json!({ "path": path, "content": content }))
.collect();
obj["files"] = json!(files);
}
}
obj
})
.collect();
println!(
"{}",
serde_json::to_string(&json!({ "success": true, "data": items })).unwrap_or_default()
);
} else {
for (i, s) in targets.iter().enumerate() {
if i > 0 {
println!("\n---\n");
}
let skill_md = s.dir.join("SKILL.md");
if let Some(content) = read_skill_full(&skill_md) {
print!("{}", content);
if !content.ends_with('\n') {
println!();
}
}
if full {
let supplementary = collect_supplementary_files(&s.dir);
for (path, content) in &supplementary {
println!("\n--- {} ---\n", path);
print!("{}", content);
if !content.ends_with('\n') {
println!();
}
}
}
}
}
}
fn run_path(skills_dirs: &[PathBuf], name: Option<&str>, json_mode: bool) {
match name {
Some(name) => {
let all_skills = discover_skills(skills_dirs);
match all_skills.iter().find(|s| s.name == name) {
Some(s) => {
let path = s.dir.to_string_lossy().to_string();
if json_mode {
println!(
"{}",
serde_json::to_string(&json!({
"success": true,
"data": { "name": s.name, "path": path },
}))
.unwrap_or_default()
);
} else {
println!("{}", path);
}
}
None => {
if json_mode {
println!(
"{}",
serde_json::to_string(&json!({
"success": false,
"error": format!("Skill not found: {}", name),
}))
.unwrap_or_default()
);
} else {
eprintln!("{} Skill not found: {}", color::error_indicator(), name);
}
exit(1);
}
}
}
None => {
let paths: Vec<String> = skills_dirs
.iter()
.map(|d| d.to_string_lossy().to_string())
.collect();
if json_mode {
println!(
"{}",
serde_json::to_string(&json!({
"success": true,
"data": { "paths": paths },
}))
.unwrap_or_default()
);
} else {
for p in &paths {
println!("{}", p);
}
}
}
}
}
pub fn run_skills(args: &[String], json_mode: bool) {
let skills_dirs = find_skills_dirs();
if skills_dirs.is_empty() {
if json_mode {
println!(
"{}",
serde_json::to_string(&json!({
"success": false,
"error": "Skills directory not found. Set AGENT_BROWSER_SKILLS_DIR or reinstall via npm.",
}))
.unwrap_or_default()
);
} else {
eprintln!(
"{} Skills directory not found. Set AGENT_BROWSER_SKILLS_DIR or reinstall via npm.",
color::error_indicator()
);
}
exit(1);
}
let subcommand = args.get(1).map(|s| s.as_str());
match subcommand {
None | Some("list") => run_list(&skills_dirs, json_mode),
Some("get") => {
let names: Vec<String> = args[2..]
.iter()
.filter(|a| *a != "--full" && *a != "--all")
.cloned()
.collect();
let full = args[2..].iter().any(|a| a == "--full");
let get_all = args[2..].iter().any(|a| a == "--all");
run_get(&skills_dirs, &names, get_all, full, json_mode);
}
Some("path") => {
let name = args.get(2).map(|s| s.as_str());
run_path(&skills_dirs, name, json_mode);
}
Some(unknown) => {
if json_mode {
println!(
"{}",
serde_json::to_string(&json!({
"success": false,
"error": format!("Unknown skills subcommand: {}", unknown),
}))
.unwrap_or_default()
);
} else {
eprintln!(
"{} Unknown skills subcommand: {}",
color::error_indicator(),
unknown
);
}
exit(1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn create_test_skill(dir: &Path, name: &str, description: &str) {
let skill_dir = dir.join(name);
fs::create_dir_all(&skill_dir).unwrap();
fs::write(
skill_dir.join("SKILL.md"),
format!(
"---\nname: {}\ndescription: {}\n---\n\n# {}\n\nContent here.\n",
name, description, name
),
)
.unwrap();
}
#[test]
fn test_parse_frontmatter_basic() {
let content = "---\nname: test-skill\ndescription: A test skill.\n---\n\n# Test\n";
let (name, desc, hidden) = parse_frontmatter(content).unwrap();
assert_eq!(name, "test-skill");
assert_eq!(desc, "A test skill.");
assert!(!hidden);
}
#[test]
fn test_parse_frontmatter_multiline_description() {
let content =
"---\nname: test\ndescription: First line\n continued here\n and here\n---\n";
let (name, desc, hidden) = parse_frontmatter(content).unwrap();
assert_eq!(name, "test");
assert_eq!(desc, "First line continued here and here");
assert!(!hidden);
}
#[test]
fn test_parse_frontmatter_hidden_true() {
let content = "---\nname: stub\ndescription: A bootstrap stub.\nhidden: true\n---\n";
let (name, desc, hidden) = parse_frontmatter(content).unwrap();
assert_eq!(name, "stub");
assert_eq!(desc, "A bootstrap stub.");
assert!(hidden);
}
#[test]
fn test_parse_frontmatter_hidden_false() {
let content = "---\nname: visible\ndescription: Visible.\nhidden: false\n---\n";
let (_, _, hidden) = parse_frontmatter(content).unwrap();
assert!(!hidden);
}
#[test]
fn test_parse_frontmatter_no_frontmatter() {
let content = "# Just a heading\n\nNo frontmatter here.\n";
assert!(parse_frontmatter(content).is_none());
}
#[test]
fn test_parse_frontmatter_missing_name() {
let content = "---\ndescription: No name field\n---\n";
assert!(parse_frontmatter(content).is_none());
}
#[test]
fn test_discover_skills_single_dir() {
let tmp = tempfile::tempdir().unwrap();
create_test_skill(tmp.path(), "alpha", "Alpha skill");
create_test_skill(tmp.path(), "beta", "Beta skill");
// Non-skill directory (no SKILL.md)
fs::create_dir_all(tmp.path().join("not-a-skill")).unwrap();
fs::write(tmp.path().join("not-a-skill").join("README.md"), "hi").unwrap();
let dirs = vec![tmp.path().to_path_buf()];
let skills = discover_skills(&dirs);
assert_eq!(skills.len(), 2);
assert_eq!(skills[0].name, "alpha");
assert_eq!(skills[1].name, "beta");
}
#[test]
fn test_discover_skills_multiple_dirs() {
let tmp1 = tempfile::tempdir().unwrap();
let tmp2 = tempfile::tempdir().unwrap();
create_test_skill(tmp1.path(), "alpha", "Alpha skill");
create_test_skill(tmp2.path(), "beta", "Beta skill");
create_test_skill(tmp2.path(), "gamma", "Gamma skill");
let dirs = vec![tmp1.path().to_path_buf(), tmp2.path().to_path_buf()];
let skills = discover_skills(&dirs);
assert_eq!(skills.len(), 3);
assert_eq!(skills[0].name, "alpha");
assert_eq!(skills[1].name, "beta");
assert_eq!(skills[2].name, "gamma");
}
#[test]
fn test_truncate_description() {
assert_eq!(truncate_description("short", 10), "short");
assert_eq!(
truncate_description("this is a longer description that should be truncated", 20),
"this is a longer..."
);
}
#[test]
fn test_truncate_description_multibyte() {
let desc = "Browse \u{00e9}l\u{00e9}ments and \u{65e5}\u{672c}\u{8a9e} pages quickly";
let result = truncate_description(desc, 20);
assert!(result.ends_with("..."));
assert!(result.len() <= 30);
}
#[test]
fn test_collect_supplementary_files() {
let tmp = tempfile::tempdir().unwrap();
let refs_dir = tmp.path().join("references");
fs::create_dir_all(&refs_dir).unwrap();
fs::write(refs_dir.join("auth.md"), "# Auth\n").unwrap();
fs::write(refs_dir.join("commands.md"), "# Commands\n").unwrap();
let templates_dir = tmp.path().join("templates");
fs::create_dir_all(&templates_dir).unwrap();
fs::write(templates_dir.join("example.sh"), "#!/bin/bash\n").unwrap();
let files = collect_supplementary_files(tmp.path());
assert_eq!(files.len(), 3);
assert_eq!(files[0].0, "references/auth.md");
assert_eq!(files[1].0, "references/commands.md");
assert_eq!(files[2].0, "templates/example.sh");
}
}
+49
View File
@@ -0,0 +1,49 @@
use std::sync::{Mutex, MutexGuard};
/// Global mutex shared across all test modules to prevent parallel tests from
/// interfering with each other when mutating environment variables.
pub static ENV_MUTEX: Mutex<()> = Mutex::new(());
/// RAII guard that locks [`ENV_MUTEX`] and restores environment variables on drop.
pub struct EnvGuard<'a> {
_lock: MutexGuard<'a, ()>,
vars: Vec<(String, Option<String>)>,
}
impl<'a> EnvGuard<'a> {
pub fn new(var_names: &[&str]) -> Self {
let lock = ENV_MUTEX.lock().unwrap();
let vars = var_names
.iter()
.map(|&name| (name.to_string(), std::env::var(name).ok()))
.collect();
Self { _lock: lock, vars }
}
pub fn set(&self, name: &str, value: &str) {
debug_assert!(
self.vars.iter().any(|(n, _)| n == name),
"EnvGuard::set called with unregistered var: {name}"
);
std::env::set_var(name, value);
}
pub fn remove(&self, name: &str) {
debug_assert!(
self.vars.iter().any(|(n, _)| n == name),
"EnvGuard::remove called with unregistered var: {name}"
);
std::env::remove_var(name);
}
}
impl Drop for EnvGuard<'_> {
fn drop(&mut self) {
for (name, value) in &self.vars {
match value {
Some(v) => std::env::set_var(name, v),
None => std::env::remove_var(name),
}
}
}
}
+284
View File
@@ -0,0 +1,284 @@
use crate::color;
use std::path::Path;
use std::process::{exit, Command, Stdio};
const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
const NPM_REGISTRY_URL: &str = "https://registry.npmjs.org/agent-browser/latest";
enum InstallMethod {
Npm,
Pnpm,
Yarn,
Bun,
Homebrew,
Cargo,
Unknown,
}
async fn fetch_latest_version() -> Result<String, String> {
let resp = reqwest::get(NPM_REGISTRY_URL)
.await
.map_err(|e| format!("Failed to fetch version info: {}", e))?;
let body: serde_json::Value = resp
.json()
.await
.map_err(|e| format!("Failed to parse version info: {}", e))?;
body.get("version")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.ok_or_else(|| "No version field in registry response".to_string())
}
/// Parse the `.install-method` marker written by postinstall.js.
fn read_install_method_marker(exe_dir: &Path) -> Option<InstallMethod> {
let contents = std::fs::read_to_string(exe_dir.join(".install-method")).ok()?;
match contents.trim() {
"npm" => Some(InstallMethod::Npm),
"pnpm" => Some(InstallMethod::Pnpm),
"yarn" => Some(InstallMethod::Yarn),
"bun" => Some(InstallMethod::Bun),
_ => None,
}
}
fn detect_install_method() -> InstallMethod {
if let Ok(exe) = std::env::current_exe() {
// Resolve symlinks to find the real binary location
let real_path = exe.canonicalize().unwrap_or(exe);
// Preferred: read the marker file written at install time
if let Some(dir) = real_path.parent() {
if let Some(method) = read_install_method_marker(dir) {
return method;
}
}
// Fallback: infer from executable path
let path_str = real_path.to_string_lossy();
if path_str.contains("/.cargo/bin/") || path_str.contains("\\.cargo\\bin\\") {
return InstallMethod::Cargo;
}
if path_str.contains("/Cellar/agent-browser/")
|| path_str.contains("/homebrew/")
|| path_str.contains("/linuxbrew/")
{
return InstallMethod::Homebrew;
}
if path_str.contains("/pnpm/") || path_str.contains("/pnpm-global/") {
return InstallMethod::Pnpm;
}
if path_str.contains("/.yarn/") || path_str.contains("/yarn/global/") {
return InstallMethod::Yarn;
}
if path_str.contains("/.bun/") {
return InstallMethod::Bun;
}
if path_str.contains("node_modules/agent-browser")
|| path_str.contains("node_modules\\agent-browser")
{
return InstallMethod::Npm;
}
}
// Last resort: probe package managers via subprocess
#[cfg(any(target_os = "macos", target_os = "linux"))]
{
if command_succeeds("brew", &["list", "agent-browser"]) {
return InstallMethod::Homebrew;
}
}
if command_output_contains(
"pnpm",
&["list", "-g", "agent-browser", "--depth=0"],
"agent-browser",
) {
return InstallMethod::Pnpm;
}
if command_output_contains("yarn", &["global", "list", "--depth=0"], "agent-browser") {
return InstallMethod::Yarn;
}
if command_output_contains("bun", &["pm", "ls", "-g"], "agent-browser") {
return InstallMethod::Bun;
}
if command_succeeds("npm", &["list", "-g", "agent-browser", "--depth=0"]) {
return InstallMethod::Npm;
}
InstallMethod::Unknown
}
fn command_succeeds(cmd: &str, args: &[&str]) -> bool {
Command::new(cmd)
.args(args)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
fn command_output_contains(cmd: &str, args: &[&str], needle: &str) -> bool {
Command::new(cmd)
.args(args)
.stderr(Stdio::null())
.output()
.map(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains(needle))
.unwrap_or(false)
}
fn run_upgrade_command(method: &InstallMethod) -> bool {
let (cmd, args, display): (&str, &[&str], &str) = match method {
InstallMethod::Npm => (
"npm",
&["install", "-g", "agent-browser@latest"],
"npm install -g agent-browser@latest",
),
InstallMethod::Pnpm => (
"pnpm",
&["add", "-g", "agent-browser@latest"],
"pnpm add -g agent-browser@latest",
),
// NOTE: `yarn global` is Yarn Classic (v1) only; Yarn Berry (v2+) removed it.
// Users on Yarn v2+ won't reach this path — detection falls through to Unknown.
InstallMethod::Yarn => (
"yarn",
&["global", "add", "agent-browser@latest"],
"yarn global add agent-browser@latest",
),
InstallMethod::Bun => (
"bun",
&["install", "-g", "agent-browser@latest"],
"bun install -g agent-browser@latest",
),
InstallMethod::Homebrew => (
"brew",
&["upgrade", "agent-browser"],
"brew upgrade agent-browser",
),
InstallMethod::Cargo => (
"cargo",
&["install", "agent-browser", "--force"],
"cargo install agent-browser --force",
),
InstallMethod::Unknown => return false,
};
println!("Running: {}", display);
Command::new(cmd)
.args(args)
.status()
.map(|s| s.success())
.unwrap_or(false)
}
pub fn run_upgrade() {
let current = CURRENT_VERSION;
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap_or_else(|e| {
eprintln!(
"{} Failed to create runtime: {}",
color::error_indicator(),
e
);
exit(1);
});
let latest = match rt.block_on(fetch_latest_version()) {
Ok(v) => v,
Err(e) => {
eprintln!(
"{} Could not check latest version: {}",
color::warning_indicator(),
e
);
String::new()
}
};
if !latest.is_empty() && current == latest.as_str() {
println!(
"{} agent-browser is already at the latest version (v{})",
color::success_indicator(),
current
);
return;
}
let method = detect_install_method();
let method_name = match &method {
InstallMethod::Npm => "npm",
InstallMethod::Pnpm => "pnpm",
InstallMethod::Yarn => "yarn",
InstallMethod::Bun => "bun",
InstallMethod::Homebrew => "Homebrew",
InstallMethod::Cargo => "Cargo",
InstallMethod::Unknown => "",
};
if matches!(method, InstallMethod::Unknown) {
eprintln!(
"{} Could not detect installation method.",
color::error_indicator()
);
eprintln!(" To update manually, run one of:");
eprintln!(" npm install -g agent-browser@latest # npm");
eprintln!(" pnpm add -g agent-browser@latest # pnpm");
eprintln!(" yarn global add agent-browser@latest # yarn");
eprintln!(" bun install -g agent-browser@latest # bun");
eprintln!(" brew upgrade agent-browser # Homebrew");
eprintln!(" cargo install agent-browser --force # Cargo");
exit(1);
}
println!("Detected installation via {}.", method_name);
if !latest.is_empty() {
println!(
"{}",
color::cyan(&format!(
"Upgrading agent-browser... v{} → v{}",
current, latest
))
);
} else {
println!(
"{}",
color::cyan(&format!("Upgrading agent-browser (v{})...", current))
);
}
let success = run_upgrade_command(&method);
if success {
if !latest.is_empty() {
println!(
"{} Done! v{} → v{}",
color::success_indicator(),
current,
latest
);
} else {
println!("{} Done!", color::success_indicator());
}
} else {
eprintln!("{} Upgrade failed.", color::error_indicator());
exit(1);
}
}
+15
View File
@@ -0,0 +1,15 @@
/// Check if a session name is valid (alphanumeric, hyphens, and underscores only)
pub fn is_valid_session_name(name: &str) -> bool {
!name.is_empty()
&& name
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
}
/// Generate error message for invalid session name
pub fn session_name_error(name: &str) -> String {
format!(
"Invalid session name '{}'. Only alphanumeric characters, hyphens, and underscores are allowed.",
name
)
}
+141
View File
@@ -0,0 +1,141 @@
//! Integration tests for `agent-browser doctor`.
//!
//! These tests spawn the real CLI binary via `env!("CARGO_BIN_EXE_*")` and
//! verify the doctor command produces sane output. They override
//! `AGENT_BROWSER_SOCKET_DIR` and `HOME` / `USERPROFILE` so the doctor
//! inspects a throwaway directory and never touches the user's real state.
use std::process::Command;
use tempfile::TempDir;
const BIN: &str = env!("CARGO_BIN_EXE_agent-browser");
fn build_doctor_cmd(tmp: &TempDir, args: &[&str]) -> Command {
let socket_dir = tmp.path().join("sockets");
let home = tmp.path().join("home");
std::fs::create_dir_all(&socket_dir).unwrap();
std::fs::create_dir_all(&home).unwrap();
let mut cmd = Command::new(BIN);
cmd.args(args)
.env("AGENT_BROWSER_SOCKET_DIR", &socket_dir)
.env("HOME", &home)
.env("USERPROFILE", &home)
// Keep the launch test's skip-logic deterministic across hosts.
.env_remove("AGENT_BROWSER_PROVIDER")
.env_remove("AGENT_BROWSER_CDP")
// Don't emit color codes into captured stdout.
.env("NO_COLOR", "1");
cmd
}
#[test]
fn doctor_offline_quick_json_emits_valid_payload() {
let tmp = TempDir::new().unwrap();
let output = build_doctor_cmd(&tmp, &["doctor", "--offline", "--quick", "--json"])
.output()
.expect("failed to invoke agent-browser doctor");
let code = output.status.code().unwrap_or(-1);
let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
// Exit code 0 (all pass) or 1 (one or more fails) are both valid outcomes;
// the doctor may legitimately report a failure on a host without Chrome.
assert!(
code == 0 || code == 1,
"unexpected exit code {}\nstdout:\n{}\nstderr:\n{}",
code,
stdout,
stderr,
);
let payload: serde_json::Value = serde_json::from_str(&stdout)
.unwrap_or_else(|e| panic!("stdout was not JSON: {}\n---\n{}", e, stdout));
assert!(payload.get("success").is_some(), "missing success field");
assert!(payload.get("summary").is_some(), "missing summary field");
assert!(payload.get("fixed").is_some(), "missing fixed field");
let summary = &payload["summary"];
assert!(summary["pass"].is_number());
assert!(summary["warn"].is_number());
assert!(summary["fail"].is_number());
let checks = payload["checks"]
.as_array()
.expect("checks should be an array");
assert!(!checks.is_empty(), "checks array should not be empty");
// Every check must have a non-empty id / category / status / message.
for c in checks {
assert!(
c["id"].as_str().is_some_and(|s| !s.is_empty()),
"check missing id: {}",
c
);
assert!(
c["category"].as_str().is_some_and(|s| !s.is_empty()),
"check missing category: {}",
c
);
let status = c["status"].as_str().expect("status should be string");
assert!(
["pass", "warn", "fail", "info"].contains(&status),
"unexpected status {:?}",
status
);
assert!(
c["message"].as_str().is_some_and(|s| !s.is_empty()),
"check missing message: {}",
c
);
}
// Check IDs must be unique now that providers / sessions / skipped-launch
// states each carry their own ID suffix.
let mut seen = std::collections::HashSet::new();
for c in checks {
let id = c["id"].as_str().unwrap();
assert!(
seen.insert(id.to_string()),
"duplicate check id in JSON output: {}\nfull payload:\n{}",
id,
stdout
);
}
}
#[test]
fn doctor_help_describes_flags_and_examples() {
let tmp = TempDir::new().unwrap();
let output = build_doctor_cmd(&tmp, &["doctor", "--help"])
.output()
.expect("failed to invoke agent-browser doctor --help");
assert!(
output.status.success(),
"doctor --help should exit 0; got {:?}",
output.status
);
let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");
for needle in [
"agent-browser doctor",
"--offline",
"--quick",
"--fix",
"--json",
"Exit codes",
] {
assert!(
stdout.contains(needle),
"doctor --help output missing {:?}\n---\n{}",
needle,
stdout
);
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
# Multi-platform Rust cross-compilation image
FROM rust:1.85-bookworm
FROM rust:1.94-bookworm
# Install cross-compilation toolchains
RUN apt-get update && apt-get install -y \
+25 -8
View File
@@ -20,13 +20,19 @@ services:
# Build both targets in parallel
(echo "→ Linux x64" && cargo zigbuild --release --target x86_64-unknown-linux-gnu && cp /build/target/x86_64-unknown-linux-gnu/release/agent-browser /output/agent-browser-linux-x64 && chmod +x /output/agent-browser-linux-x64 && echo "✓ Linux x64 done") &
PID1=$!
PID1=$$!
(echo "→ Linux ARM64" && cargo zigbuild --release --target aarch64-unknown-linux-gnu && cp /build/target/aarch64-unknown-linux-gnu/release/agent-browser /output/agent-browser-linux-arm64 && chmod +x /output/agent-browser-linux-arm64 && echo "✓ Linux ARM64 done") &
PID2=$!
PID2=$$!
# Wait for both to complete
wait $PID1 $PID2
# Wait for both and check exit codes individually — without this
# the outer script exits 0 even if one of the parallel builds
# failed, silently leaving a stale binary in /output from the
# previous release. Caused 0.27.0-fork.5 to ship with a stale
# linux-x64 binary at the first publish attempt until caught
# manually by checking the embedded version string.
wait $$PID1 || { echo "✗ Linux x64 build failed"; exit 1; }
wait $$PID2 || { echo "✗ Linux ARM64 build failed"; exit 1; }
echo ""
echo "✓ Linux platforms built successfully!"
@@ -65,10 +71,21 @@ services:
environment:
- TARGET=${TARGET:-x86_64-unknown-linux-gnu}
- OUTPUT_NAME=${OUTPUT_NAME:-agent-browser-linux-x64}
# NOTE: $$ escapes a literal $ for the in-container shell. A single $ is
# interpolated by docker compose at YAML parse time against the *host*
# environment, which silently drops script-local variables like SRC
# (caused 0.27.0-fork.7 to ship with a stale linux-arm64 binary because
# the cp command resolved to `cp "" "/output/"` after compose ate $SRC
# and $OUTPUT_NAME). $TARGET / $OUTPUT_NAME are set via `environment:`
# below — those are also passed into the container, so $$TARGET and
# $$OUTPUT_NAME read them at script time.
command: |
-c '
cargo zigbuild --release --target $TARGET
cp /build/target/$TARGET/release/agent-browser* /output/$OUTPUT_NAME
chmod +x /output/$OUTPUT_NAME 2>/dev/null || true
echo "✓ Built $OUTPUT_NAME"
set -e
cargo zigbuild --release --target $$TARGET
SRC="/build/target/$$TARGET/release/agent-browser"
if [ -f "$$SRC.exe" ]; then SRC="$$SRC.exe"; fi
cp "$$SRC" "/output/$$OUTPUT_NAME"
chmod +x /output/$$OUTPUT_NAME 2>/dev/null || true
echo "✓ Built $$OUTPUT_NAME"
'
+425
View File
@@ -0,0 +1,425 @@
(() => {
const REQUEST_TYPE = 'AB_TAB_GROUP_REQUEST';
const RESPONSE_TYPE = 'AB_TAB_GROUP_RESPONSE';
const CONTENT_EVENT_TYPE = 'AB_CONTENT_EVENT';
const CONTENT_EXECUTE_ACTION = 'AB_CONTENT_EXECUTE_ACTION';
const CONTENT_GET_DOM_STATE = 'AB_CONTENT_GET_DOM_STATE';
const CONTENT_PING = 'AB_CONTENT_PING';
const PAGE_BRIDGE_EVENT = 'AB_PAGE_BRIDGE_EVENT';
const STORAGE_OPTIONS_KEY = 'abExtensionOptionsV1';
const mutationState = {
total: 0,
recent: [],
observerReady: false,
};
function pushMutationSummary(entry) {
mutationState.total += 1;
mutationState.recent.push({
...entry,
timestamp: Date.now(),
});
if (mutationState.recent.length > 40) {
mutationState.recent.splice(0, mutationState.recent.length - 40);
}
}
function serializeValue(value, depth = 0) {
if (value === null || typeof value === 'undefined') return value;
if (typeof value === 'string') return value.slice(0, 300);
if (typeof value === 'number' || typeof value === 'boolean') return value;
if (value instanceof Error) return `${value.name}: ${value.message}`;
if (depth > 2) return '[depth-limit]';
if (Array.isArray(value)) {
return value.slice(0, 10).map((item) => serializeValue(item, depth + 1));
}
if (typeof value === 'object') {
const out = {};
for (const [key, entry] of Object.entries(value).slice(0, 15)) {
out[key] = serializeValue(entry, depth + 1);
}
return out;
}
return String(value).slice(0, 300);
}
function sendRuntimeEvent(kind, payload) {
try {
chrome.runtime.sendMessage({
type: CONTENT_EVENT_TYPE,
kind,
payload: serializeValue(payload),
url: window.location.href,
title: document.title,
timestamp: Date.now(),
});
} catch {
// Ignore runtime channel errors.
}
}
function getPageBridgeEnabled() {
return new Promise((resolve) => {
try {
chrome.storage.local.get([STORAGE_OPTIONS_KEY], (result) => {
if (chrome.runtime.lastError) {
resolve(false);
return;
}
const rawOptions = result?.[STORAGE_OPTIONS_KEY];
resolve(Boolean(rawOptions && typeof rawOptions === 'object' && rawOptions.pageBridgeEnabled === true));
});
} catch {
resolve(false);
}
});
}
async function installPageBridge() {
// Receives events emitted by the injected page-world hook script.
const bridgeListener = (event) => {
if (event.source !== window) return;
const data = event.data;
if (!data || data.type !== PAGE_BRIDGE_EVENT) return;
sendRuntimeEvent(data.kind || 'page-event', data.payload || {});
};
window.addEventListener('message', bridgeListener);
const parent = document.documentElement || document.head || document.body;
if (!parent) return;
if (!(await getPageBridgeEnabled())) {
sendRuntimeEvent('lifecycle', {
event: 'bridge-disabled-default',
});
return;
}
// Use external extension script instead of inline text to reduce CSP conflicts.
const script = document.createElement('script');
script.src = chrome.runtime.getURL('page-bridge.js');
script.async = false;
script.dataset.abBridgeEvent = PAGE_BRIDGE_EVENT;
script.onload = () => script.remove();
script.onerror = () => {
sendRuntimeEvent('lifecycle', {
event: 'bridge-load-failed',
host: window.location.hostname,
});
script.remove();
};
parent.appendChild(script);
}
function ensureMutationObserver() {
if (mutationState.observerReady) return;
if (!document.documentElement) return;
const observer = new MutationObserver((records) => {
const summary = {
records: records.length,
addedNodes: 0,
removedNodes: 0,
};
for (const record of records.slice(0, 40)) {
summary.addedNodes += record.addedNodes?.length || 0;
summary.removedNodes += record.removedNodes?.length || 0;
}
pushMutationSummary(summary);
});
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['class', 'style', 'hidden', 'disabled', 'aria-hidden'],
});
mutationState.observerReady = true;
}
function toSimpleNode(element) {
if (!element || typeof element !== 'object') return null;
const node = {
tag: element.tagName?.toLowerCase() || 'unknown',
id: element.id || undefined,
className: typeof element.className === 'string' ? element.className.slice(0, 120) : '',
role: element.getAttribute?.('role') || undefined,
name:
element.getAttribute?.('aria-label') ||
element.getAttribute?.('name') ||
element.getAttribute?.('placeholder') ||
'',
text: (element.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 160),
disabled: element.disabled === true,
hidden: element.hidden === true,
};
return node;
}
function collectInteractiveElements(root, limit = 80) {
const selector = [
'a[href]',
'button',
'input',
'select',
'textarea',
'summary',
'[role="button"]',
'[role="link"]',
'[tabindex]'
].join(',');
const out = [];
const nodes = root.querySelectorAll(selector);
for (const element of nodes) {
if (out.length >= limit) break;
out.push(toSimpleNode(element));
}
return out.filter(Boolean);
}
function collectDomState(options = {}) {
const selector = typeof options.selector === 'string' ? options.selector.trim() : '';
const root = selector ? document.querySelector(selector) : document.body || document.documentElement;
if (!root) {
return {
ok: false,
error: selector ? `selector-not-found: ${selector}` : 'root-not-found',
};
}
const textPreview = (root.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 1000);
const interactiveOnly = options.interactiveOnly === true;
const interactiveElements = collectInteractiveElements(root, options.maxNodes || 80);
const dom = {
href: window.location.href,
title: document.title,
readyState: document.readyState,
selector: selector || null,
rootTag: root.tagName?.toLowerCase() || 'unknown',
textPreview,
interactiveCount: interactiveElements.length,
interactiveElements,
mutation: {
total: mutationState.total,
recent: mutationState.recent.slice(-10),
},
capturedAt: Date.now(),
};
if (interactiveOnly) {
dom.textPreview = '';
}
return {
ok: true,
state: dom,
};
}
function queryElement(selector) {
if (typeof selector !== 'string' || selector.trim().length === 0) {
throw new Error('selector is required');
}
const element = document.querySelector(selector);
if (!element) {
throw new Error(`Element not found: ${selector}`);
}
return element;
}
function focusElement(element) {
if (typeof element.focus === 'function') {
element.focus({ preventScroll: false });
}
}
function dispatchInputEvents(element) {
element.dispatchEvent(new Event('input', { bubbles: true }));
element.dispatchEvent(new Event('change', { bubbles: true }));
}
async function executeAction(command, args = {}) {
switch (command) {
case 'click': {
const element = queryElement(args.selector);
focusElement(element);
element.click();
return { ok: true, action: command, selector: args.selector };
}
case 'fill': {
const element = queryElement(args.selector);
if (!('value' in element)) {
throw new Error(`Element is not fillable: ${args.selector}`);
}
focusElement(element);
element.value = typeof args.value === 'string' ? args.value : String(args.value || '');
dispatchInputEvents(element);
return { ok: true, action: command, selector: args.selector, valueLength: element.value.length };
}
case 'press': {
const key = typeof args.key === 'string' && args.key.trim().length > 0 ? args.key.trim() : 'Enter';
let target;
if (typeof args.selector === 'string' && args.selector.trim().length > 0) {
target = queryElement(args.selector);
focusElement(target);
} else {
target = document.activeElement || document.body;
}
const down = new KeyboardEvent('keydown', { key, bubbles: true });
const up = new KeyboardEvent('keyup', { key, bubbles: true });
target.dispatchEvent(down);
target.dispatchEvent(up);
return { ok: true, action: command, key };
}
case 'eval': {
if (typeof args.expression !== 'string' || args.expression.trim().length === 0) {
throw new Error('expression is required');
}
const fn = new Function(`return (${args.expression});`);
const result = fn();
return { ok: true, action: command, result: serializeValue(result) };
}
case 'snapshot': {
return {
ok: true,
action: command,
...collectDomState({
selector: args.selector,
interactiveOnly: args.interactiveOnly === true,
maxNodes: args.maxNodes,
}),
};
}
default:
throw new Error(`Unknown content action: ${command}`);
}
}
ensureMutationObserver();
installPageBridge();
window.addEventListener('message', (event) => {
if (event.source !== window) {
return;
}
const data = event.data;
if (!data || data.type !== REQUEST_TYPE) {
return;
}
const request = {
type: REQUEST_TYPE,
nonce: data.nonce,
session: data.session,
groupTitle: data.groupTitle,
pluginId: data.pluginId,
allowedDomains: Array.isArray(data.allowedDomains) ? data.allowedDomains : undefined,
};
try {
chrome.runtime.sendMessage(request, (response) => {
const lastError = chrome.runtime.lastError;
if (lastError) {
window.postMessage(
{
type: RESPONSE_TYPE,
nonce: request.nonce,
ok: false,
error: lastError.message,
},
'*'
);
return;
}
const payload = response && typeof response === 'object' ? response : { ok: false };
window.postMessage(
{
type: RESPONSE_TYPE,
nonce: request.nonce,
ok: payload.ok === true,
extensionId:
typeof payload.extensionId === 'string' && payload.extensionId.length > 0
? payload.extensionId
: chrome.runtime.id,
groupId: typeof payload.groupId === 'number' ? payload.groupId : undefined,
windowId: typeof payload.windowId === 'number' ? payload.windowId : undefined,
color: typeof payload.color === 'string' ? payload.color : undefined,
collapsed: payload.collapsed === true,
policy:
payload.policy && typeof payload.policy === 'object'
? {
enforced: payload.policy.enforced === true,
blocked: payload.policy.blocked === true,
reason:
typeof payload.policy.reason === 'string' ? payload.policy.reason : undefined,
}
: undefined,
riskHints: Array.isArray(payload.riskHints) ? payload.riskHints : undefined,
error: typeof payload.error === 'string' ? payload.error : undefined,
},
'*'
);
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
window.postMessage(
{
type: RESPONSE_TYPE,
nonce: request.nonce,
ok: false,
error: errorMessage,
},
'*'
);
}
});
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (!message || typeof message !== 'object') return;
if (message.type === CONTENT_PING) {
sendResponse({
ok: true,
href: window.location.href,
title: document.title,
readyState: document.readyState,
});
return;
}
if (message.type === CONTENT_GET_DOM_STATE) {
sendResponse(collectDomState(message.options || {}));
return;
}
if (message.type === CONTENT_EXECUTE_ACTION) {
executeAction(message.command, message.args || {})
.then((result) => sendResponse(result))
.catch((error) => {
sendResponse({
ok: false,
action: message.command,
error: error instanceof Error ? error.message : String(error),
});
});
return true;
}
});
})();
+7
View File
@@ -0,0 +1,7 @@
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="128" height="128" rx="32" fill="#1A73E8"/>
<rect x="30" y="34" width="68" height="10" rx="2" fill="white"/>
<rect x="30" y="54" width="48" height="10" rx="2" fill="white" fill-opacity="0.8"/>
<rect x="30" y="74" width="28" height="10" rx="2" fill="white" fill-opacity="0.6"/>
<circle cx="94" cy="90" r="10" fill="#34A853" stroke="#1A73E8" stroke-width="4"/>
</svg>

After

Width:  |  Height:  |  Size: 488 B

Some files were not shown because too many files have changed in this diff Show More