* Fix blank terminal after split operations and add visual tests ## Blank Terminal Fix - Add `needsRefreshAfterWindowChange` flag in GhosttyTerminalView - Force terminal refresh when view is added to window, even if size unchanged - Add `ghostty_surface_refresh()` call in attachToView for same-view reattachment - Add debug logging for surface attachment lifecycle (DEBUG builds only) ## Bonsplit Migration - Add bonsplit as local Swift package (vendor/bonsplit submodule) - Replace custom SplitTree with BonsplitController - Add Panel protocol with TerminalPanel and BrowserPanel implementations - Add SidebarTab as main tab container with BonsplitController - Remove old Splits/ directory (SplitTree, SplitView, TerminalSplitTreeView) ## Visual Screenshot Tests - Add test_visual_screenshots.py for automated visual regression testing - Uses in-app screenshot API (CGWindowListCreateImage) - no screen recording needed - Generates HTML report with before/after comparisons - Tests: splits, browser panels, focus switching, close operations, rapid cycles - Includes annotation fields for easy feedback ## Browser Shortcut (⌘⇧B) - Add keyboard shortcut to open browser panel in current pane - Add openBrowser() method to TabManager - Add shortcut configuration in KeyboardShortcutSettings ## Screenshot Command - Add 'screenshot' command to TerminalController for in-app window capture - Returns OK with screenshot ID and path ## Other - Add tests/visual_output/ and tests/visual_report.html to .gitignore * Add browser title subscription and set tab height to 30px - Subscribe to BrowserPanel.$pageTitle changes to update bonsplit tabs - Update tab titles in real-time as page navigation occurs - Clean up subscriptions when panels are removed - Set bonsplit tab bar and tab height to 30px (in submodule) * Fix socket API regressions in list_surfaces, list_bonsplit_tabs, focus_pane - list_surfaces: Remove [terminal]/[browser] suffix to keep UUID-only format that clients and tests expect for parsing - list_bonsplit_tabs --pane: Properly look up pane by UUID instead of creating a new PaneID (requires bonsplit PaneID.id to be public) - focus_pane: Accept both UUID strings and integer indices as documented * Fix browser panel stability and keyboard shortcuts - Prevent WKWebView focus lifecycle crashes during split/view reshuffles - Match bracket shortcuts via keyCode (Cmd+Shift+[ / ], Cmd+Ctrl+[ / ]) - Support Ghostty config goto_split:* keybinds when WebView is focused - Add focus_webview/is_webview_focused socket commands and regression tests - Rename SidebarTab to Workspace and update docs * Make ctrl+enter keybind test skippable Skip when the Ghostty keybind isn't configured or when osascript can't send keystrokes (no Accessibility permission), so VM runs stay green. * Auto-focus browser omnibar when blank When a browser surface is focused but no URL is loaded yet, focus the address bar instead of the WKWebView. * Stabilize socket surface indexing * Focus browser omnibar escape; add webview keybind UI tests - Escape in omnibar now returns focus to WKWebView\n- Add UI tests for Cmd+Ctrl+H pane navigation with WebKit focused (including Ghostty config)\n- Avoid flaky element screenshots in UpdatePillUITests on the UTM VM * Fix browser drag-to-split blanks and socket parsing * Fix webview-focused shortcuts and stabilize browser splits - Match ctrl/shift shortcuts by keyCode where needed (Ctrl+H, bracket keys) - Load Ghostty goto_split triggers reliably and refresh on config load - Add debug socket helpers: set_shortcut + simulate_shortcut for tests - Convert browser goto_split/keybind tests to socket-based injection (no osascript) - Bump bonsplit for drag-to-split fixes * Fix split layout collapse and harden socket pane APIs * Stabilize OSC 99 notification test timing * Fix terminal focus routing after split reparent * Support simulate_shortcut enter for focus routing test * Stabilize terminal focus routing test * Fix frozen new terminal tabs after many splits * Fix frozen new terminal tabs after splits * Fix terminal freeze on launch/new tabs * Update ghostty submodule * Fix terminal focus/render stalls after split churn * Fix nested split collapsing existing pane * Fix nested split collapse + stabilize new-surface focus * Update bonsplit submodule * Fix SIGINT test flake * Remove bonsplit tab-switch crossfade * Remove PROJECTS.md * Remove bonsplit tab selection animation * Ignore generated test reports * Middle click closes tab * Revert unintended .gitignore change * Fix build after main merge * Revert "Fix build after main merge" This reverts commit 16bf9816d0856b5385d52f886aa5eb50f3c9d9a4. * Revert "Merge remote-tracking branch 'origin/main' into fix/blank-terminal-and-visual-tests" This reverts commit 7c20fb53fd71fea7a19a3673f2dd73e5f0c783c4, reversing changes made to 0aff107d787bc9d8bbc28220090b4ca7af72e040. * Remove tab close fade animation * Use terminal.fill icon * Make terminal tab icon smaller * Match browser globe tab icon size * Bonsplit: tab min width 48 and tighter close button * Bonsplit: smaller tab title font * Show unread notification badge in bonsplit tabs and improve UI polish Sync unread notification state to bonsplit tab badges (blue dot). Improve EmptyPanelView with Terminal/Browser buttons and shortcut hints. Add tooltips to close tab button and search overlay buttons. * Fix reload.sh single-instance safety check on macOS Replace GNU-only `ps -o etimes=` with portable `ps -o etime=` and parse the dd-hh:mm:ss format manually for macOS compatibility. * Centralize keyboard shortcut definitions into Action enum Replace per-shortcut boilerplate with a single Action enum that holds the label, defaults key, and default binding for each shortcut. All call sites now use shortcut(for:). Settings UI is data-driven via ForEach(Action.allCases). Titlebar tooltips update dynamically when shortcuts are changed. Remove duplicate .keyboardShortcut() modifiers from menu items that are already handled by the event monitor. * Fix WKWebView consuming app menu shortcuts and close panel confirmation Add CmuxWebView subclass that routes key equivalents through the main menu before WebKit, so Cmd+N/Cmd+W/tab switching work when a browser pane is focused. Fix Cmd+W close-panel path: bypass Bonsplit delegate gating after the user confirms the running-process dialog by tracking forceCloseTabIds. Add unit tests (CmuxWebViewKeyEquivalentTests) and UI test scaffolding (MenuKeyEquivalentRoutingUITests) with a new cmux-unit Xcode scheme. * Update CLAUDE.md and PROJECTS.md with recent changes CLAUDE.md: enforce --tag for reload commands, add cleanup safety rules. PROJECTS.md: log notification badge, reload.sh fix, Cmd+W fix, WebView key equiv fix, and centralized shortcuts work. * Keep selection index stable on close * Add concepts page documenting terminology hierarchy New docs page explaining Window > Workspace > Pane > Surface > Panel hierarchy with aligned ASCII diagram. Updated tabs.mdx and splits.mdx to use consistent terminology (workspace instead of tab, surface instead of panel) and corrected outdated CLI command references. * Update bonsplit submodule * WIP: improve split close stability and UI regressions * Close terminal panel on child exit; hide terminal dirty dot * Fix split close/focus regressions and stabilize UI tests * Add unread Dock/Cmd+Tab badge with settings toggle * Fix browser-surface shortcuts and Cmd+L browser opening * Snapshot current workspace state before regression fixes * Update bonsplit submodule snapshot * Stabilize split-close regression capture and sidebar resize assertions * Change default Show Notifications shortcut from Cmd+Shift+I to Cmd+I * Fix update check readiness race, enable release update logging, and improve checking spinner * Restore terminal file drop, fix browser omnibar click focus, and add panel workspace ID mutation for surface moves * Add Cmd+digit workspace hints, titlebar shortcut pills, sidebar drag-reorder, and workspace placement settings * Add v2 browser automation API, surface move/reorder commands, and short-handle ref system to TerminalController * Add CLI browser command surface, --id-format flag, and move/reorder commands * Extend test clients with move/reorder APIs, ref-handle support, and increased timeouts * Harden test runner scripts with deterministic builds, retry logic, and robust socket readiness * Stabilize existing test suites with focus-wait helpers, increased timeouts, and API shape updates * Add terminal file drop e2e regression test * Add v2 browser API, CLI ref resolution, and surface move/reorder test suites * Add unit tests for shortcut hints, workspace reorder, drop planner, and update UI test stabilization * Add cmux-debug-windows skill with snapshot script and agent config * Update project docs: mark browser parity and move/reorder phases complete, add parallel agent workflow guidelines * Update bonsplit submodule: re-entrant setPosition guard, tab shortcut hints, and moveTab/reorderTab API * Add browser agent UX improvements: snapshot refs, placement reuse, diagnostics, and skill docs - Upgrade browser.snapshot to emit accessibility tree text with element refs (eN) - Add right-sibling pane reuse policy for browser.open_split placement - Add rich not_found diagnostics with retry logic for selector actions - Support --snapshot-after for post-action verification on mutating commands - Allow browser fill with empty text for clearing inputs - Default CLI --id-format to refs-first (UUIDs opt-in via --id-format uuids|both) - Format legacy new-pane/new-surface output with short surface refs - Add skills/cmuxterm-browser/ and skills/cmuxterm/ end-user skill docs - Add regression tests for placement policy, snapshot refs, diagnostics, and ID defaults * Update bonsplit submodule: keep raster favicons in color when inactive
420 lines
18 KiB
Python
420 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
"""Comprehensive v2 browser API coverage (ported from agent-browser test themes)."""
|
|
|
|
import os
|
|
import sys
|
|
import time
|
|
import urllib.parse
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent))
|
|
from cmux import cmux, cmuxError
|
|
|
|
|
|
SOCKET_PATH = os.environ.get("CMUX_SOCKET", "/tmp/cmux-debug.sock")
|
|
|
|
|
|
def _must(cond: bool, msg: str) -> None:
|
|
if not cond:
|
|
raise cmuxError(msg)
|
|
|
|
|
|
def _data_url(html: str) -> str:
|
|
return "data:text/html;charset=utf-8," + urllib.parse.quote(html)
|
|
|
|
|
|
def _wait_until(pred, timeout_s: float, label: str) -> None:
|
|
deadline = time.time() + timeout_s
|
|
last_exc = None
|
|
while time.time() < deadline:
|
|
try:
|
|
if pred():
|
|
return
|
|
except Exception as exc: # noqa: BLE001
|
|
last_exc = exc
|
|
time.sleep(0.05)
|
|
if last_exc is not None:
|
|
raise cmuxError(f"Timed out waiting for {label}: {last_exc}")
|
|
raise cmuxError(f"Timed out waiting for {label}")
|
|
|
|
|
|
def _expect_error(label: str, fn, code_substr: str) -> None:
|
|
try:
|
|
fn()
|
|
except cmuxError as exc:
|
|
text = str(exc)
|
|
if code_substr in text:
|
|
return
|
|
raise cmuxError(f"{label}: expected error containing {code_substr!r}, got: {text}")
|
|
raise cmuxError(f"{label}: expected error containing {code_substr!r}, but call succeeded")
|
|
|
|
def _expect_error_contains(label: str, fn, *needles: str) -> None:
|
|
try:
|
|
fn()
|
|
except cmuxError as exc:
|
|
text = str(exc)
|
|
missing = [needle for needle in needles if needle not in text]
|
|
if missing:
|
|
raise cmuxError(f"{label}: missing expected substrings {missing!r} in error: {text}")
|
|
return
|
|
raise cmuxError(f"{label}: expected failure, but call succeeded")
|
|
|
|
|
|
def _value(res: dict, key: str = "value"):
|
|
return (res or {}).get(key)
|
|
|
|
|
|
|
|
def _wait_with_fallback(c: cmux, surface_id: str, params: dict, pred, timeout_s: float, label: str) -> None:
|
|
call_params = dict(params)
|
|
call_params["surface_id"] = surface_id
|
|
try:
|
|
c._call("browser.wait", call_params)
|
|
return
|
|
except cmuxError as exc:
|
|
if "timeout" not in str(exc):
|
|
raise
|
|
_wait_until(pred, timeout_s=timeout_s, label=f"{label} fallback")
|
|
|
|
|
|
def _build_pages() -> tuple[str, str]:
|
|
page1 = """
|
|
<!doctype html>
|
|
<html>
|
|
<head>
|
|
<title>cmux-browser-comprehensive-1</title>
|
|
<style>
|
|
body { margin: 0; font-family: sans-serif; min-height: 2200px; }
|
|
#scroller { width: 220px; height: 90px; overflow: auto; border: 1px solid #666; }
|
|
#scroller-inner { height: 520px; padding-top: 8px; }
|
|
#style-target { color: rgb(255, 0, 0); width: 123px; height: 45px; display: block; }
|
|
#hidden { display: none; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<h1 id="hdr">Browser Comprehensive</h1>
|
|
<input id="name" value="">
|
|
<button id="btn" data-role="submit" onclick="document.querySelector('#status').textContent = document.querySelector('#name').value || 'empty';">Go</button>
|
|
<div id="status" data-role="status">ready</div>
|
|
|
|
<input id="chk" type="checkbox">
|
|
<select id="sel">
|
|
<option value="a">A</option>
|
|
<option value="b">B</option>
|
|
</select>
|
|
|
|
<div id="hover" onmouseover="window.__hover = (window.__hover || 0) + 1">hover target</div>
|
|
<div id="dbl" ondblclick="window.__dbl = (window.__dbl || 0) + 1">double target</div>
|
|
|
|
<input id="keys" value="">
|
|
<button id="disabled" disabled>Disabled</button>
|
|
<div id="hidden">not visible</div>
|
|
<div id="style-target">styles</div>
|
|
|
|
<div id="scroller">
|
|
<div id="scroller-inner">
|
|
<div id="bottom">bottom-marker</div>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
window.__hover = 0;
|
|
window.__dbl = 0;
|
|
window.__keys = { down: 0, up: 0, press: 0 };
|
|
document.addEventListener('keydown', () => window.__keys.down++);
|
|
document.addEventListener('keyup', () => window.__keys.up++);
|
|
document.addEventListener('keypress', () => window.__keys.press++);
|
|
</script>
|
|
</body>
|
|
</html>
|
|
""".strip()
|
|
|
|
page2 = """
|
|
<!doctype html>
|
|
<html>
|
|
<head><title>cmux-browser-comprehensive-2</title></head>
|
|
<body>
|
|
<div id="page2">page-two</div>
|
|
</body>
|
|
</html>
|
|
""".strip()
|
|
|
|
return _data_url(page1), _data_url(page2)
|
|
|
|
|
|
def main() -> int:
|
|
page1_url, page2_url = _build_pages()
|
|
|
|
with cmux(SOCKET_PATH) as c:
|
|
opened = c._call("browser.open_split", {"url": "about:blank"}) or {}
|
|
sid = str(opened.get("surface_id") or "")
|
|
sref = str(opened.get("surface_ref") or "")
|
|
_must(bool(sid), f"browser.open_split returned no surface_id: {opened}")
|
|
target = sid
|
|
if sref:
|
|
_ = c._call("browser.url.get", {"surface_id": sref})
|
|
|
|
probe_url = _data_url("<!doctype html><html><body><button id='probe'>P</button></body></html>")
|
|
c._call("browser.navigate", {"surface_id": target, "url": probe_url})
|
|
_wait_with_fallback(
|
|
c,
|
|
target,
|
|
{"selector": "#probe", "timeout_ms": 3000},
|
|
lambda: bool((c._call("browser.eval", {"surface_id": target, "script": "document.querySelector('#probe') !== null"}) or {}).get("value")),
|
|
timeout_s=4.0,
|
|
label="browser.wait selector #probe",
|
|
)
|
|
|
|
c._call("browser.navigate", {"surface_id": target, "url": page1_url})
|
|
_wait_with_fallback(
|
|
c,
|
|
target,
|
|
{"text_contains": "ready", "timeout_ms": 3000},
|
|
lambda: "ready" in str((c._call("browser.eval", {"surface_id": target, "script": "document.body ? (document.body.innerText || '') : ''"}) or {}).get("value") or ""),
|
|
timeout_s=4.0,
|
|
label="browser.wait text_contains ready",
|
|
)
|
|
_wait_with_fallback(
|
|
c,
|
|
target,
|
|
{"function": "document.querySelector('#hdr') !== null", "timeout_ms": 3000},
|
|
lambda: bool((c._call("browser.eval", {"surface_id": target, "script": "document.querySelector('#hdr') !== null"}) or {}).get("value")),
|
|
timeout_s=4.0,
|
|
label="browser.wait function hdr",
|
|
)
|
|
_wait_with_fallback(
|
|
c,
|
|
target,
|
|
{"load_state": "complete", "timeout_ms": 5000},
|
|
lambda: str((c._call("browser.eval", {"surface_id": target, "script": "document.readyState"}) or {}).get("value") or "").lower() == "complete",
|
|
timeout_s=6.0,
|
|
label="browser.wait load_state complete",
|
|
)
|
|
_wait_with_fallback(
|
|
c,
|
|
target,
|
|
{"url_contains": "data:text/html", "timeout_ms": 3000},
|
|
lambda: "data:text/html" in str((c._call("browser.url.get", {"surface_id": target}) or {}).get("url") or ""),
|
|
timeout_s=4.0,
|
|
label="browser.wait url_contains data:text/html",
|
|
)
|
|
|
|
_wait_until(
|
|
lambda: "cmux-browser-comprehensive-1"
|
|
in str((c._call("browser.get.title", {"surface_id": target}) or {}).get("title") or ""),
|
|
timeout_s=3.0,
|
|
label="browser.get.title page1",
|
|
)
|
|
url_payload = c._call("browser.url.get", {"surface_id": target}) or {}
|
|
_must("data:text/html" in str(url_payload.get("url") or ""), f"Expected data URL from browser.url.get: {url_payload}")
|
|
|
|
c._call("browser.fill", {"surface_id": target, "selector": "#name", "text": "cmux"})
|
|
c._call("browser.click", {"surface_id": target, "selector": "#btn"})
|
|
out_text = c._call("browser.get.text", {"surface_id": target, "selector": "#status"}) or {}
|
|
_must(str(_value(out_text)) == "cmux", f"Expected status text to be cmux: {out_text}")
|
|
|
|
cleared = c._call("browser.fill", {"surface_id": target, "selector": "#name", "text": "", "snapshot_after": True}) or {}
|
|
_must(bool(cleared.get("post_action_snapshot")), f"Expected post_action_snapshot from fill(snapshot_after): {cleared}")
|
|
cleared_value = c._call("browser.get.value", {"surface_id": target, "selector": "#name"}) or {}
|
|
_must(str(_value(cleared_value)) == "", f"Expected fill with empty text to clear input: {cleared_value}")
|
|
|
|
c._call("browser.fill", {"surface_id": target, "selector": "#name", "text": "cmux"})
|
|
c._call("browser.type", {"surface_id": target, "selector": "#name", "text": "-v2"})
|
|
name_val = c._call("browser.get.value", {"surface_id": target, "selector": "#name"}) or {}
|
|
_must(str(_value(name_val)) == "cmux-v2", f"Expected typed suffix in input value: {name_val}")
|
|
|
|
c._call("browser.focus", {"surface_id": target, "selector": "#keys"})
|
|
active = c._call(
|
|
"browser.eval",
|
|
{"surface_id": target, "script": "document.activeElement ? document.activeElement.id : ''"},
|
|
) or {}
|
|
_must(str(_value(active)) == "keys", f"Expected focus on #keys: {active}")
|
|
|
|
c._call("browser.hover", {"surface_id": target, "selector": "#hover"})
|
|
c._call("browser.dblclick", {"surface_id": target, "selector": "#dbl"})
|
|
|
|
c._call("browser.press", {"surface_id": target, "key": "A"})
|
|
c._call("browser.keydown", {"surface_id": target, "key": "B"})
|
|
c._call("browser.keyup", {"surface_id": target, "key": "C"})
|
|
|
|
key_stats = c._call(
|
|
"browser.eval",
|
|
{
|
|
"surface_id": target,
|
|
"script": "({hover: window.__hover, dbl: window.__dbl, down: window.__keys.down, up: window.__keys.up, press: window.__keys.press})",
|
|
},
|
|
) or {}
|
|
key_value = _value(key_stats)
|
|
_must(isinstance(key_value, dict), f"Expected dict counters from eval: {key_stats}")
|
|
_must(int(key_value.get("hover", 0)) >= 1, f"Expected hover counter >= 1: {key_stats}")
|
|
_must(int(key_value.get("dbl", 0)) >= 1, f"Expected dbl counter >= 1: {key_stats}")
|
|
_must(int(key_value.get("down", 0)) >= 2, f"Expected keydown counter >= 2: {key_stats}")
|
|
_must(int(key_value.get("up", 0)) >= 2, f"Expected keyup counter >= 2: {key_stats}")
|
|
_must(int(key_value.get("press", 0)) >= 1, f"Expected keypress counter >= 1: {key_stats}")
|
|
|
|
c._call("browser.check", {"surface_id": target, "selector": "#chk"})
|
|
is_checked = c._call("browser.is.checked", {"surface_id": target, "selector": "#chk"}) or {}
|
|
_must(bool(_value(is_checked)) is True, f"Expected checked=true: {is_checked}")
|
|
c._call("browser.uncheck", {"surface_id": target, "selector": "#chk"})
|
|
is_unchecked = c._call("browser.is.checked", {"surface_id": target, "selector": "#chk"}) or {}
|
|
_must(bool(_value(is_unchecked)) is False, f"Expected checked=false: {is_unchecked}")
|
|
|
|
c._call("browser.select", {"surface_id": target, "selector": "#sel", "value": "b"})
|
|
sel_val = c._call("browser.get.value", {"surface_id": target, "selector": "#sel"}) or {}
|
|
_must(str(_value(sel_val)) == "b", f"Expected selected value b: {sel_val}")
|
|
|
|
html_val = c._call("browser.get.html", {"surface_id": target, "selector": "#status"}) or {}
|
|
_must("id=\"status\"" in str(_value(html_val) or ""), f"Expected status HTML: {html_val}")
|
|
|
|
attr_val = c._call("browser.get.attr", {"surface_id": target, "selector": "#status", "attr": "data-role"}) or {}
|
|
_must(str(_value(attr_val)) == "status", f"Expected data-role=status: {attr_val}")
|
|
|
|
cnt_val = c._call("browser.get.count", {"surface_id": target, "selector": "option"}) or {}
|
|
_must(int((cnt_val or {}).get("count") or 0) == 2, f"Expected option count=2: {cnt_val}")
|
|
|
|
box_val = c._call("browser.get.box", {"surface_id": target, "selector": "#status"}) or {}
|
|
box = _value(box_val)
|
|
_must(isinstance(box, dict), f"Expected box dict: {box_val}")
|
|
_must(float(box.get("width") or 0.0) > 0.0, f"Expected positive box width: {box_val}")
|
|
|
|
style_prop = c._call(
|
|
"browser.get.styles",
|
|
{"surface_id": target, "selector": "#style-target", "property": "color"},
|
|
) or {}
|
|
_must("rgb" in str(_value(style_prop) or ""), f"Expected rgb color in style property: {style_prop}")
|
|
|
|
style_all = c._call("browser.get.styles", {"surface_id": target, "selector": "#style-target"}) or {}
|
|
_must(isinstance(_value(style_all), dict), f"Expected style dictionary: {style_all}")
|
|
_must("display" in (_value(style_all) or {}), f"Expected display in style dictionary: {style_all}")
|
|
|
|
visible_status = c._call("browser.is.visible", {"surface_id": target, "selector": "#status"}) or {}
|
|
visible_hidden = c._call("browser.is.visible", {"surface_id": target, "selector": "#hidden"}) or {}
|
|
_must(bool(_value(visible_status)) is True, f"Expected #status visible: {visible_status}")
|
|
_must(bool(_value(visible_hidden)) is False, f"Expected #hidden not visible: {visible_hidden}")
|
|
|
|
enabled_btn = c._call("browser.is.enabled", {"surface_id": target, "selector": "#btn"}) or {}
|
|
enabled_disabled = c._call("browser.is.enabled", {"surface_id": target, "selector": "#disabled"}) or {}
|
|
_must(bool(_value(enabled_btn)) is True, f"Expected #btn enabled: {enabled_btn}")
|
|
_must(bool(_value(enabled_disabled)) is False, f"Expected #disabled not enabled: {enabled_disabled}")
|
|
|
|
c._call("browser.scroll", {"surface_id": target, "selector": "#scroller", "dx": 0, "dy": 160})
|
|
scrolled = c._call(
|
|
"browser.eval",
|
|
{"surface_id": target, "script": "document.querySelector('#scroller').scrollTop"},
|
|
) or {}
|
|
_must(float(_value(scrolled) or 0) >= 100, f"Expected scroller scrollTop >= 100: {scrolled}")
|
|
|
|
c._call("browser.scroll", {"surface_id": target, "dy": 240})
|
|
c._call("browser.scroll_into_view", {"surface_id": target, "selector": "#bottom"})
|
|
in_view = c._call(
|
|
"browser.eval",
|
|
{
|
|
"surface_id": target,
|
|
"script": "(() => { const r = document.querySelector('#bottom').getBoundingClientRect(); return r.top < window.innerHeight; })()",
|
|
},
|
|
) or {}
|
|
_must(bool(_value(in_view)) is True, f"Expected #bottom in viewport: {in_view}")
|
|
|
|
shot = c._call("browser.screenshot", {"surface_id": target}) or {}
|
|
_must(len(str((shot or {}).get("png_base64") or "")) > 100, f"Expected screenshot payload: {shot}")
|
|
|
|
snap = c._call("browser.snapshot", {"surface_id": target}) or {}
|
|
snapshot_text = str((snap or {}).get("snapshot") or "")
|
|
_must("cmux-browser-comprehensive-1" in snapshot_text, f"Expected snapshot text for page1: {snap}")
|
|
refs = (snap or {}).get("refs") or {}
|
|
_must(isinstance(refs, dict), f"Expected snapshot refs dict: {snap}")
|
|
_must(any(str(key).startswith("e") for key in refs.keys()), f"Expected eN refs from snapshot: {snap}")
|
|
|
|
c._call("browser.navigate", {"surface_id": target, "url": page2_url})
|
|
_wait_with_fallback(
|
|
c,
|
|
target,
|
|
{"text_contains": "page-two", "timeout_ms": 4000},
|
|
lambda: "page-two" in str((c._call("browser.eval", {"surface_id": target, "script": "document.body ? (document.body.innerText || '') : ''"}) or {}).get("value") or ""),
|
|
timeout_s=5.0,
|
|
label="browser.wait text_contains page-two",
|
|
)
|
|
_wait_until(
|
|
lambda: "cmux-browser-comprehensive-2"
|
|
in str((c._call("browser.get.title", {"surface_id": target}) or {}).get("title") or ""),
|
|
timeout_s=3.0,
|
|
label="browser.get.title page2",
|
|
)
|
|
|
|
c._call("browser.back", {"surface_id": target})
|
|
_wait_with_fallback(
|
|
c,
|
|
target,
|
|
{"url_contains": "cmux-browser-comprehensive-1", "timeout_ms": 4000},
|
|
lambda: "cmux-browser-comprehensive-1" in str((c._call("browser.url.get", {"surface_id": target}) or {}).get("url") or ""),
|
|
timeout_s=5.0,
|
|
label="browser.wait url_contains page1 (history)",
|
|
)
|
|
c._call("browser.forward", {"surface_id": target})
|
|
_wait_with_fallback(
|
|
c,
|
|
target,
|
|
{"url_contains": "cmux-browser-comprehensive-2", "timeout_ms": 4000},
|
|
lambda: "cmux-browser-comprehensive-2" in str((c._call("browser.url.get", {"surface_id": target}) or {}).get("url") or ""),
|
|
timeout_s=5.0,
|
|
label="browser.wait url_contains page2 (history)",
|
|
)
|
|
c._call("browser.reload", {"surface_id": target})
|
|
_wait_with_fallback(
|
|
c,
|
|
target,
|
|
{"url_contains": "cmux-browser-comprehensive-2", "timeout_ms": 4000},
|
|
lambda: "cmux-browser-comprehensive-2" in str((c._call("browser.url.get", {"surface_id": target}) or {}).get("url") or ""),
|
|
timeout_s=5.0,
|
|
label="browser.wait url_contains page2 (reload)",
|
|
)
|
|
|
|
c._call("browser.focus_webview", {"surface_id": target})
|
|
_wait_until(
|
|
lambda: bool((c._call("browser.is_webview_focused", {"surface_id": target}) or {}).get("focused")),
|
|
timeout_s=2.5,
|
|
label="browser.is_webview_focused",
|
|
)
|
|
|
|
# Negative cases adapted from agent-browser protocol/actions tests.
|
|
_expect_error(
|
|
"click missing selector",
|
|
lambda: c._call("browser.click", {"surface_id": target}),
|
|
"invalid_params",
|
|
)
|
|
_expect_error_contains(
|
|
"click missing element",
|
|
lambda: c._call("browser.click", {"surface_id": target, "selector": "#does-not-exist"}),
|
|
"not_found",
|
|
"snapshot",
|
|
"hint",
|
|
)
|
|
_expect_error(
|
|
"get.attr missing attr",
|
|
lambda: c._call("browser.get.attr", {"surface_id": target, "selector": "#status"}),
|
|
"invalid_params",
|
|
)
|
|
_expect_error(
|
|
"wait timeout",
|
|
lambda: c._call("browser.wait", {"surface_id": target, "selector": "#never", "timeout_ms": 100}),
|
|
"timeout",
|
|
)
|
|
_expect_error(
|
|
"navigate missing url",
|
|
lambda: c._call("browser.navigate", {"surface_id": target}),
|
|
"invalid_params",
|
|
)
|
|
|
|
terminal_surface = c.new_surface(panel_type="terminal")
|
|
_expect_error(
|
|
"browser method on terminal surface",
|
|
lambda: c._call("browser.url.get", {"surface_id": terminal_surface}),
|
|
"not_found",
|
|
)
|
|
|
|
print("PASS: comprehensive browser.* coverage (ported/adapted from agent-browser) is green")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|