Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(browser): enable direct preview input and mark Jarvis windows
rubenluetke10-beepeef99c1d943f
diff --git a/jarvis/society/browser/live.py b/jarvis/society/browser/live.pyindex cf94ae3229..7502d1ec38 100644--- a/jarvis/society/browser/live.py+++ b/jarvis/society/browser/live.py@@ -299,6 +299,9 @@ class LiveSessions:"profile_dir": str(folder / "browser-profile"),"workspace": str(folder / "workspace"),"executable": str(install.browser_executable(self.data_dir)),+ "icon_path": str(+ Path(__file__).parents[2] / "assets" / "icons" / "jarvis.ico"+ ),"allowed_domains": list(agent.browser_allowed_domains),"cdp_url": self.cdp_urlif str(getattr(agent, "browser_mode", "own")) == "attach"diff --git a/jarvis/society/browser/live_runner.py b/jarvis/society/browser/live_runner.pyindex fbd6cebb76..89a56276f5 100644--- a/jarvis/society/browser/live_runner.py+++ b/jarvis/society/browser/live_runner.py@@ -100,6 +100,7 @@ class Worker:self.native: Any = Noneself.native_frame_at = 0.0self.native_replay = False+ self.branding: asyncio.Task | None = Noneasync def rpc(self, kind: str, payload: dict) -> dict:key = uuid.uuid4().hex@@ -208,10 +209,14 @@ class Worker:raise RuntimeError("Chrome did not produce a window image")self.native.frame()await asyncio.to_thread(self.native.park)+ if args.get("icon_path"):+ self.branding = asyncio.create_task(+ asyncio.to_thread(self.native.brand, str(args["icon_path"]))+ )finally:await connection.detach()if self.page.url == "about:blank":- await self.page.goto("chrome://newtab/")+ await self.page.goto("chrome://newtab/", wait_until="commit", timeout=5000)elif self.owns_context and self.page.url == "about:blank":await self.page.set_content("<html><head><title>Personal Jarvis — Agent Browser</title></head>"@@ -677,6 +682,8 @@ class Worker:task.cancel()await asyncio.gather(*monitors, return_exceptions=True)if self.native:+ if self.branding:+ await self.brandingawait asyncio.to_thread(self.native.close)if self.browser:with contextlib.suppress(Exception):diff --git a/jarvis/society/browser/native_window.py b/jarvis/society/browser/native_window.pyindex 3e0842354a..13269ca4e7 100644--- a/jarvis/society/browser/native_window.py+++ b/jarvis/society/browser/native_window.py@@ -70,6 +70,12 @@ class NativeWindow:u.PostMessageW.restype = wintypes.BOOLu.ClientToScreen.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.POINT)]u.ClientToScreen.restype = wintypes.BOOL+ u.ScreenToClient.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.POINT)]+ u.ScreenToClient.restype = wintypes.BOOL+ u.ChildWindowFromPointEx.argtypes = [wintypes.HWND, wintypes.POINT, wintypes.UINT]+ u.ChildWindowFromPointEx.restype = wintypes.HWND+ u.IsChild.argtypes = [wintypes.HWND, wintypes.HWND]+ u.IsChild.restype = wintypes.BOOLu.SetThreadDpiAwarenessContext.argtypes = [ctypes.c_void_p]u.SetThreadDpiAwarenessContext.restype = ctypes.c_void_p@@ -100,6 +106,7 @@ class NativeWindow:self.hwnd = max(candidates)[1]if not self.hwnd:raise RuntimeError("The owned Chrome window is unavailable")+ self.input_hwnd = self.hwndcapture = WindowsCapture(window_hwnd=self.hwnd,cursor_capture=False,@@ -169,18 +176,103 @@ class NativeWindow:u.GetWindowTextW(self.hwnd, title, len(title))return title.value+ def brand(self, icon_path: str) -> bool:+ """Mark the taskbar button with the Jarvis icon; never delay first pixels."""+ from uuid import UUID++ c, w, u = self.ctypes, self.wintypes, self.user32+ ole = c.WinDLL("ole32")+ ole.CoInitializeEx.argtypes = [c.c_void_p, w.DWORD]+ ole.CoInitializeEx.restype = c.c_long+ ole.CoCreateInstance.argtypes = [+ c.c_void_p,+ c.c_void_p,+ w.DWORD,+ c.c_void_p,+ c.POINTER(c.c_void_p),+ ]+ ole.CoCreateInstance.restype = c.c_long+ ole.CoUninitialize.argtypes = []+ u.LoadImageW.argtypes = [w.HINSTANCE, w.LPCWSTR, w.UINT, c.c_int, c.c_int, w.UINT]+ u.LoadImageW.restype = w.HANDLE+ u.DestroyIcon.argtypes = [w.HICON]+ u.DestroyIcon.restype = w.BOOL+ initialized = ole.CoInitializeEx(None, 2)+ pointer = c.c_void_p()+ icon = None+ try:+ self._check_owner()+ clsid = c.create_string_buffer(UUID("56fdf344-fd6d-11d0-958a-006097c9a090").bytes_le)+ iid = c.create_string_buffer(UUID("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf").bytes_le)+ if ole.CoCreateInstance(clsid, None, 1, iid, c.byref(pointer)) < 0:+ raise RuntimeError("Taskbar icon interface is unavailable")+ table = c.cast(pointer, c.POINTER(c.POINTER(c.c_void_p))).contents+ initialize = c.WINFUNCTYPE(c.c_long, c.c_void_p)(table[3])+ overlay = c.WINFUNCTYPE(c.c_long, c.c_void_p, w.HWND, w.HICON, w.LPCWSTR)(table[18])+ if initialize(pointer) < 0:+ raise RuntimeError("Taskbar icon initialization failed")+ icon = u.LoadImageW(None, icon_path, 1, 16, 16, 0x10)+ if not icon:+ raise RuntimeError("Jarvis browser icon could not be loaded")+ if overlay(pointer, self.hwnd, icon, "Jarvis Browser") < 0:+ raise RuntimeError("Jarvis browser badge could not be applied")+ return True+ except Exception:+ log.warning("Jarvis browser badge unavailable", exc_info=True)+ return False+ finally:+ if icon:+ u.DestroyIcon(icon)+ if pointer:+ table = c.cast(pointer, c.POINTER(c.POINTER(c.c_void_p))).contents+ c.WINFUNCTYPE(w.ULONG, c.c_void_p)(table[2])(pointer)+ if initialized in (0, 1):+ ole.CoUninitialize()+def post(self, message: int, key: int, value: int = 1) -> None:+ self.post_to(self.hwnd, message, key, value)++ def post_to(self, target: int, message: int, key: int, value: int = 1) -> None:self._check_owner()- if not self.user32.PostMessageW(self.hwnd, message, key, value):+ owner = self.wintypes.DWORD()+ self.user32.GetWindowThreadProcessId(target, self.ctypes.byref(owner))+ if owner.value != self.pid or (+ target != self.hwnd and not self.user32.IsChild(self.hwnd, target)+ ):+ raise RuntimeError("Chrome input target is no longer available")+ if not self.user32.PostMessageW(target, message, key, value):raise RuntimeError("Chrome could not receive this input")+ def click_target(self, x: int, y: int) -> tuple[int, int, int]:+ """Map captured frame pixels to the owned native widget under the point."""+ c, w, u = self.ctypes, self.wintypes, self.user32+ bounds = w.RECT()+ dwm = c.WinDLL("dwmapi")+ dwm.DwmGetWindowAttribute.argtypes = [w.HWND, w.DWORD, c.c_void_p, w.DWORD]+ dwm.DwmGetWindowAttribute.restype = c.c_long+ if dwm.DwmGetWindowAttribute(self.hwnd, 9, c.byref(bounds), c.sizeof(bounds)):+ raise RuntimeError("Chrome frame geometry is unavailable")+ screen_x, screen_y = bounds.left + x, bounds.top + y+ target = self.hwnd+ for _ in range(16):+ point = w.POINT(screen_x, screen_y)+ if not u.ScreenToClient(target, c.byref(point)):+ raise RuntimeError("Chrome input coordinates are unavailable")+ # Chromium's render host can be transparent for composition while+ # still being the native keyboard/mouse input target.+ child = u.ChildWindowFromPointEx(target, point, 3)+ if not child or child == target:+ return target, point.x, point.y+ target = int(child)+ raise RuntimeError("Chrome input widget nesting is invalid")+def shortcut(self, key: int, modifiers: list[int]) -> None:"""Apply modifiers to Chrome's input queue, never to the physical keyboard."""c, w, u = self.ctypes, self.wintypes, self.user32kernel = c.WinDLL("kernel32", use_last_error=True)kernel.GetCurrentThreadId.restype = w.DWORDcurrent = kernel.GetCurrentThreadId()- target = u.GetWindowThreadProcessId(self.hwnd, None)+ target = u.GetWindowThreadProcessId(self.input_hwnd, None)u.AttachThreadInput.argtypes = [w.DWORD, w.DWORD, w.BOOL]u.AttachThreadInput.restype = w.BOOLu.GetKeyboardState.argtypes = [c.POINTER(w.BYTE)]@@ -209,7 +301,7 @@ class NativeWindow:result = c.c_size_t()for message, bits in ((0x100, 1), (0x101, 0xC0000001)):if not u.SendMessageTimeoutW(- self.hwnd, message, key, bits, 3, 200, c.byref(result)+ self.input_hwnd, message, key, bits, 3, 200, c.byref(result)):raise RuntimeError("Chrome did not respond to the keyboard shortcut")finally:@@ -225,19 +317,24 @@ class NativeWindow:# Deliver focus to Chrome's widget without changing OS foreground# focus; otherwise its background omnibox can discard typed text.self.post(0x6, 1, 0)- self.post(0x7, 0, 0)if op == "click":x, y = int(args["x"]), int(args["y"])frame = self.frame()if not frame or not (0 <= x < frame["width"] and 0 <= y < frame["height"]):raise ValueError("Click is outside the Chrome window")- self.post(0x200, 0, (y << 16) | (x & 0xFFFF))- self.post(0x201, 1, (y << 16) | (x & 0xFFFF))- self.post(0x202, 0, (y << 16) | (x & 0xFFFF))+ target, x, y = self.click_target(x, y)+ self.input_hwnd = target+ self.post_to(target, 0x7, 0, 0)+ self.post_to(target, 0x200, 0, (y << 16) | (x & 0xFFFF))+ self.post_to(target, 0x201, 1, (y << 16) | (x & 0xFFFF))+ self.post_to(target, 0x202, 0, (y << 16) | (x & 0xFFFF))elif op == "text":+ self.post_to(self.input_hwnd, 0x7, 0, 0)encoded = str(args["text"]).encode("utf-16-le")for i in range(0, len(encoded), 2):- self.post(0x102, int.from_bytes(encoded[i : i + 2], "little"))+ self.post_to(+ self.input_hwnd, 0x102, int.from_bytes(encoded[i : i + 2], "little")+ )elif op == "key":# Chromium's chrome/app/chrome_command_ids.h: dispatch the# native browser commands without a shared modifier-key state.@@ -250,6 +347,8 @@ class NativeWindow:"Control+Shift+Tab": 34017,}if args["key"] in commands:+ self.input_hwnd = self.hwnd+ self.post(0x7, 0, 0)self.post(0x111, commands[args["key"]], 0)returnkeys = {@@ -280,8 +379,8 @@ class NativeWindow:if len(parts) > 1:self.shortcut(key, [modifiers[part] for part in parts[:-1]])else:- self.post(0x100, key)- self.post(0x101, key, 0xC0000001)+ self.post_to(self.input_hwnd, 0x100, key)+ self.post_to(self.input_hwnd, 0x101, key, 0xC0000001)elif op == "scroll":delta = max(-1200, min(1200, int(-float(args.get("dy", 0)))))point = self.wintypes.POINT(200, 200)diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.test.tsxindex af59e8c818..95bcddf349 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.test.tsx@@ -47,6 +47,18 @@ describe("live agent browser", () => {fireEvent.keyDown(screen.getByLabelText("Live browser of Scout"), { key: "x" });expect(control).not.toHaveBeenCalled();});+ test("clicking the preview starts interaction without a separate takeover button", () => {+ mount();+ const canvas = screen.getByLabelText("Live browser of Scout") as HTMLCanvasElement;+ vi.spyOn(canvas, "getBoundingClientRect").mockReturnValue({+ left: 0, top: 0, width: 1280, height: 800,+ } as DOMRect);+ fireEvent.click(canvas, { clientX: 200, clientY: 60 });+ expect(document.activeElement).toBe(canvas);+ expect(control).toHaveBeenCalledWith("click", { x: 200, y: 60 });+ fireEvent.keyDown(canvas, { key: "x" });+ expect(control).toHaveBeenCalledWith("text", { text: "x" });+ });test("manual typing uses browser control, never chat", () => {state.manual = true;mount();diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsxindex 9c1e489dd2..2118579b74 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx@@ -21,9 +21,9 @@ export function AgentBrowserPreview({ agent }: { agent: SocietyAgent }) {const [address, setAddress] = useState("");useEffect(() => setAddress(state.url), [state.url]);useEffect(() => { setExpanded(false); }, [agent.agentId]);- const status = !install.data?.installed ? t("society.card.browser_setting_up")- : !state.connected || !state.ready || state.controlPending ? t("society.card.browser_connecting")- : state.manual ? t("society.browser_live.manual") : t("society.browser_live.live");+ const status = state.connected && state.ready+ ? t(state.manual ? "society.browser_live.manual" : "society.browser_live.live")+ : t(install.data && !install.data.installed ? "society.card.browser_setting_up" : "society.card.browser_connecting");const buttonClass = "rounded px-2 py-1 text-xs hover:bg-secondary disabled:opacity-40";const enterUrl = () => {const url = /^https?:\/\//i.test(address) ? address : "https://" + address;@@ -64,7 +64,7 @@ export function AgentBrowserPreview({ agent }: { agent: SocietyAgent }) {className="block max-h-full max-w-full object-contain focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring"style={{ aspectRatio: "16/10", width: "100%", height: "100%", objectFit: "contain" }}onClick={(e) => {- if (!state.manual) return;+ if (!state.ready) return;e.currentTarget.focus();const box = e.currentTarget.getBoundingClientRect();const { width, height } = e.currentTarget;@@ -73,14 +73,14 @@ export function AgentBrowserPreview({ agent }: { agent: SocietyAgent }) {const y = (e.clientY - box.top - (box.height - height * scale) / 2) / scale;if (x >= 0 && y >= 0 && x <= width && y <= height) control("click", { x, y });}}- onWheel={(e) => { if (state.manual) control("scroll", { dx: e.deltaX, dy: e.deltaY }); }}+ onWheel={(e) => { if (state.ready && document.activeElement === e.currentTarget) control("scroll", { dx: e.deltaX, dy: e.deltaY }); }}onPaste={(e) => {- if (!state.manual) return;+ if (!state.ready || document.activeElement !== e.currentTarget) return;e.preventDefault();control("text", { text: e.clipboardData.getData("text/plain") });}}onKeyDown={(e) => {- if (!state.manual) return;+ if (!state.ready || (!state.manual && document.activeElement !== e.currentTarget)) return;if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "v") return;e.preventDefault();e.stopPropagation();diff --git a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.test.tsxindex 63e585cfb4..0281feb7a2 100644--- a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.test.tsx@@ -15,6 +15,7 @@ class Socket {onopen?: () => void;onclose?: () => void;onmessage?: (event: { data: string }) => void;+ send = vi.fn();close = vi.fn(() => { this.readyState = 3; this.onclose?.(); });constructor() { Socket.current = this; }}@@ -77,3 +78,33 @@ test("startup failure remains visible while reconnecting", async () => {expect(hook.result.current.state.error).toBe("Browser startup failed");expect(hook.result.current.state.ready).toBe(false);});++test("first click and typing wait for the exclusive control acknowledgement", async () => {+ const hook = await mount();+ act(() => {+ hook.result.current.control("click", { x: 240, y: 60 });+ hook.result.current.control("text", { text: "example.com" });+ });+ expect(Socket.current.send.mock.calls.map(([value]) => JSON.parse(value))).toEqual([+ { op: "takeover", args: { enabled: true } },+ ]);+ act(() => Socket.current.onmessage?.({ data: JSON.stringify({ kind: "control", ok: true, manual: true }) }));+ expect(Socket.current.send.mock.calls.map(([value]) => JSON.parse(value))).toEqual([+ { op: "takeover", args: { enabled: true } },+ { op: "click", args: { x: 240, y: 60 } },+ { op: "text", args: { text: "example.com" } },+ ]);+});++test("denied control never replays queued input", async () => {+ const hook = await mount();+ act(() => hook.result.current.control("text", { text: "private input" }));+ act(() => Socket.current.onmessage?.({ data: JSON.stringify({ kind: "control", ok: false, error: "Already controlled" }) }));+ act(() => Socket.current.onmessage?.({ data: JSON.stringify({ kind: "control", ok: true, manual: true }) }));+ expect(Socket.current.send).toHaveBeenCalledTimes(1);+});++test("connect does not wait for a separate HTTP setup request", async () => {+ await mount();+ expect(fetch).not.toHaveBeenCalled();+});diff --git a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.tsindex f9757c8548..2578af5c01 100644--- a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts+++ b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts@@ -25,6 +25,9 @@ export function useBrowserView(agentId: string) {const canvas = useRef<HTMLCanvasElement>(null);const socket = useRef<WebSocket | null>(null);const [state, setState] = useState<BrowserViewState>(empty);+ const manual = useRef(false);+ const claiming = useRef(false);+ const inputs = useRef<Array<{ op: string; args: Record<string, unknown> }>>([]);useEffect(() => {let disposed = false;let attempt = 0;@@ -36,7 +39,9 @@ export function useBrowserView(agentId: string) {let lastLiveEvent = Date.now();let renderedFrames = 0;let latestFrame: { data: string; sequence: number; timestamp: number } | null = null;- const abort = new AbortController();+ manual.current = false;+ claiming.current = false;+ inputs.current = [];setState(empty);const clearCanvas = () => {const el = canvas.current;@@ -114,6 +119,14 @@ export function useBrowserView(agentId: string) {setState((s) => ({ ...s, manual: event.manual, running: event.running,url: event.url, target: event.target, tabs: event.tabs ?? [], fullWindow: Boolean(event.full_window) }));} else if (event.kind === "control") {+ if (typeof event.manual === "boolean") manual.current = event.manual;+ if (claiming.current && (event.manual === true || !event.ok)) {+ claiming.current = false;+ const queued = inputs.current.splice(0);+ if (event.ok && event.manual === true && ws.readyState === WebSocket.OPEN) {+ for (const input of queued) ws.send(JSON.stringify(input));+ }+ }setState((s) => ({ ...s, controlPending: false, error: event.ok ? "" : event.error,manual: typeof event.manual === "boolean" ? event.manual : s.manual }));} else if (event.kind === "control_pending") {@@ -136,6 +149,9 @@ export function useBrowserView(agentId: string) {ws.onclose = () => {if (disposed || socket.current !== ws) return;epoch++;+ manual.current = false;+ claiming.current = false;+ inputs.current = [];setState((s) => ({ ...s, connected: false, manual: false, controlPending: false }));cancelConnect = requestConnect(() => void connect(), jitteredDelay(attempt++));};@@ -147,13 +163,9 @@ export function useBrowserView(agentId: string) {cancelConnect = requestConnect(() => void connect(), jitteredDelay(attempt++));}};- void fetch("/api/society/agents/" + encodeURIComponent(agentId) + "/browser/session",- { method: "POST", signal: abort.signal }).then((response) => {- if (!response.ok) throw new Error("Browser setup " + response.status);- if (!disposed) cancelConnect = requestConnect(() => void connect());- }).catch((error) => {- if (!disposed) setState((s) => ({ ...s, error: String(error) }));- });+ // subscribe() already provisions the runtime. Do not block first pixels+ // behind a redundant setup request and a second roster/runtime lookup.+ cancelConnect = requestConnect(() => void connect());// Static pages still send state heartbeats. A silent transport is not Live.const watchdog = setInterval(() => {if (socket.current?.readyState === WebSocket.OPEN && Date.now() - lastLiveEvent > 7500) {@@ -164,7 +176,9 @@ export function useBrowserView(agentId: string) {return () => {disposed = true;epoch++;- abort.abort();+ manual.current = false;+ claiming.current = false;+ inputs.current = [];clearInterval(watchdog);cancelConnect();const ws = socket.current;@@ -183,6 +197,28 @@ export function useBrowserView(agentId: string) {return;}if (socket.current?.readyState !== WebSocket.OPEN) return;+ if (["click", "scroll", "text", "key"].includes(op) && !manual.current) {+ if (inputs.current.length >= 128) {+ setState((s) => ({ ...s, error: "Waiting for browser control; input queue is full" }));+ return;+ }+ inputs.current.push({ op, args });+ if (!claiming.current) {+ claiming.current = true;+ setState((s) => ({ ...s, controlPending: true }));+ socket.current.send(JSON.stringify({ op: "takeover", args: { enabled: true } }));+ }+ return;+ }+ if (op === "takeover" && args.enabled === false) {+ inputs.current = [];+ claiming.current = false;+ manual.current = false;+ } else if (op === "takeover" && args.enabled === true) {+ if (claiming.current) return;+ claiming.current = true;+ setState((s) => ({ ...s, controlPending: true }));+ }socket.current.send(JSON.stringify({ op, args }));}, [agentId]);const approve = useCallback(async (allow: boolean) => {diff --git a/jarvis/ui/web/society_browser_routes.py b/jarvis/ui/web/society_browser_routes.pyindex bee6c044c1..43fdefea57 100644--- a/jarvis/ui/web/society_browser_routes.py+++ b/jarvis/ui/web/society_browser_routes.py@@ -138,6 +138,8 @@ async def agent_browser_live(websocket: WebSocket, agent_id: str) -> None:write_lock = asyncio.Lock()async def send(value: dict) -> None:+ if "manual" in value and session is not None:+ value = {**value, "manual": session.control_owner == owner}async with write_lock:async with asyncio.timeout(10):await websocket.send_json(value)diff --git a/tests/contract/native_window_probe.py b/tests/contract/native_window_probe.pynew file mode 100644index 0000000000..cf00337895--- /dev/null+++ b/tests/contract/native_window_probe.py@@ -0,0 +1,81 @@+"""Real Windows widget input probe, executed by the managed browser Python."""++from __future__ import annotations++import asyncio+import ctypes+import faulthandler+import json+import sys+from ctypes import wintypes+from pathlib import Path+++async def main() -> None:+ root = Path(__file__).resolve().parents[2]+ sys.path.insert(0, str(root / "jarvis" / "society" / "browser"))+ from native_window import NativeWindow+ from playwright.async_api import async_playwright++ async with async_playwright() as pw:+ context = await pw.chromium.launch_persistent_context(+ sys.argv[2], executable_path=sys.argv[1], headless=False,+ viewport={"width": 1280, "height": 800},+ )+ native = None+ try:+ page = context.pages[0]+ await page.set_content(+ '<input aria-label="Name" style="margin:40px;height:80px;width:400px">'+ )+ cdp = await context.browser.new_browser_cdp_session()+ processes = await cdp.send("SystemInfo.getProcessInfo")+ pid = next(p["id"] for p in processes["processInfo"] if p["type"] == "browser")+ native = NativeWindow(int(pid))+ assert await asyncio.to_thread(native.ready.wait, 5)+ native.park()+ badge = await asyncio.to_thread(native.brand, str(root / "jarvis/assets/icons/jarvis.ico"))+ await asyncio.sleep(0.5)+ u = native.user32+ u.EnumChildWindows.argtypes = [wintypes.HWND, native.callback_type, wintypes.LPARAM]+ children = []++ @native.callback_type+ def child(hwnd, _unused):+ name = ctypes.create_unicode_buffer(128)+ u.GetClassNameW(hwnd, name, len(name))+ if name.value == "Chrome_RenderWidgetHostHWND" and u.IsWindowVisible(hwnd):+ point, origin = wintypes.POINT(), wintypes.POINT()+ u.ClientToScreen(hwnd, ctypes.byref(point))+ u.ClientToScreen(native.hwnd, ctypes.byref(origin))+ rect = wintypes.RECT()+ u.GetWindowRect(hwnd, ctypes.byref(rect))+ children.append((point.x - origin.x, point.y - origin.y, rect.right - rect.left))+ return True++ with native.dpi():+ u.EnumChildWindows(native.hwnd, child, 0)+ assert children+ x, y, width = children[-1]+ scale = width / 1280+ native.input("click", {"x": x + 100 * scale, "y": y + 70 * scale})+ native.input("text", {"text": "Typed through the preview"})+ await asyncio.sleep(0.3)+ value = await page.get_by_label("Name").input_value()+ assert value == "Typed through the preview", value+ assert native.input_hwnd != native.hwnd+ assert badge+ native.input("click", {"x": 300 * scale, "y": y * 0.72})+ native.input("text", {"text": "about:blank#jarvis-input-probe"})+ native.input("key", {"key": "Enter"})+ await page.wait_for_url("about:blank#jarvis-input-probe", timeout=5000)+ print(json.dumps({"typed": value, "badge": badge, "address": page.url}))+ finally:+ if native:+ native.close()+ await context.close()+++if __name__ == "__main__":+ faulthandler.enable()+ asyncio.run(main())diff --git a/tests/contract/test_browser_live.py b/tests/contract/test_browser_live.pyindex ffa74712c4..3428367d86 100644--- a/tests/contract/test_browser_live.py+++ b/tests/contract/test_browser_live.py@@ -17,6 +17,22 @@ pytestmark = pytest.mark.skipif()[email protected](os.name != "nt", reason="requires native Windows widgets")+def test_native_mouse_routes_text_to_the_webpage_widget(tmp_path):+ import subprocess+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++ result = subprocess.run(+ [os.environ["JARVIS_BROWSER_TEST_PYTHON"],+ str(Path(__file__).with_name("native_window_probe.py")),+ os.environ["JARVIS_BROWSER_TEST_EXECUTABLE"], str(tmp_path / "profile")],+ env=install.worker_env(tmp_path), capture_output=True, encoding="utf-8",+ timeout=30, creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert '"badge": true' in result.stdout++class PageHandler(BaseHTTPRequestHandler):def do_GET(self):if self.path == "/download":