Skip to content

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.

feat(ide): show the user's own Chrome, signed in with their profile, in the browser panel (#747)

Ruben Lütke8748001aac72
diff --git a/dodaios/ui/browser_embed.py b/dodaios/ui/browser_embed.py
new file mode 100644
index 0000000000..9f13201b33
--- /dev/null
+++ b/dodaios/ui/browser_embed.py
@@ -0,0 +1,863 @@
+"""Show a real window of the user's own Chrome inside the app (Windows).
+
+The Agentic IDE's browser panel used to be an ``<iframe>``. Most large sites
+(GitHub, Google, X, banks) forbid being framed, and a frame never has the
+user's sign-ins. This module puts a window of the user's own, already running
+browser into the panel instead: same profile, same cookies, same extensions,
+the browser's own tabs and address bar.
+
+How it works:
+
+1. The browser is started with ``--profile-directory=<profile> --new-window
+ <blank page titled with a one-off token>``. A running browser opens the
+ window in its existing process, so it is the user's real session.
+2. The window whose title carries the token is taken: its frame styles are
+ switched to a child window and it is parented into a small container window
+ the app owns, which sits on top of the page exactly where the panel is.
+3. The page reports the panel's rectangle (and hides the container when the
+ panel is hidden). A watchdog keeps the browser window filling the container,
+ undoes minimize / maximize from the browser's own buttons, and notices when
+ the user closes the window.
+4. On release (app exit, profile switch, "open in own window") the window gets
+ its original styles and placement back, so the browser remembers sensible
+ bounds, and is either closed or left as a normal window.
+
+The container and every native call run on one thread of their own that pumps
+messages: a window created on a thread without a message loop would block the
+app's UI thread the first time it sent the window a message.
+
+Limits that come with a foreign window: a page popup of the app that overlaps
+the panel is drawn below the browser (the page hides the panel's browser while
+such a popup covers it), and a link opened from another program can land in
+this window when it was the browser's last active one.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import logging
+import os
+import queue
+import subprocess
+import sys
+import threading
+import time
+from collections.abc import Callable, Mapping
+from concurrent.futures import Future
+from concurrent.futures import TimeoutError as FutureTimeout
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, TypeVar
+
+from dodaios.ui.browser_profiles import (
+ BrowserSpec,
+ browser_by_id,
+ find_browser_exe,
+ handoff_url,
+ is_profile_dir,
+ new_token,
+ panel_to_client_rect,
+ read_profiles,
+ real_local_app_data,
+ safe_start_url,
+ user_data_dir,
+)
+
+logger = logging.getLogger(__name__)
+
+__all__ = ["ChromeEmbed", "get_embed", "release_host_if_any", "shutdown_embed"]
+
+T = TypeVar("T")
+
+#: How long a launch waits for the browser's new window (a cold start is slow).
+LAUNCH_TIMEOUT_S = 25.0
+#: How often the watchdog checks the window.
+WATCH_INTERVAL_MS = 200
+#: How long a caller waits for the native thread before giving up.
+CALL_TIMEOUT_S = 5.0
+#: How long a visible placement holds without the page confirming it.
+LEASE_S = 3.0
+
+_WINDOW_CLASS = "Chrome_WidgetWin_1"
+_CONTAINER_CLASS = "DodaiosBrowserPanelHost"
+
+# winuser.h
+GWL_STYLE = -16
+GWL_EXSTYLE = -20
+WS_CHILD = 0x40000000
+WS_POPUP = 0x80000000
+WS_VISIBLE = 0x10000000
+WS_MINIMIZE = 0x20000000
+WS_MAXIMIZE = 0x01000000
+WS_CAPTION = 0x00C00000
+WS_SYSMENU = 0x00080000
+WS_THICKFRAME = 0x00040000
+WS_MINIMIZEBOX = 0x00020000
+WS_MAXIMIZEBOX = 0x00010000
+WS_CLIPSIBLINGS = 0x04000000
+WS_CLIPCHILDREN = 0x02000000
+WS_EX_APPWINDOW = 0x00040000
+WS_EX_NOPARENTNOTIFY = 0x00000004
+SWP_NOSIZE = 0x0001
+SWP_NOMOVE = 0x0002
+SWP_NOZORDER = 0x0004
+SWP_NOACTIVATE = 0x0010
+SWP_FRAMECHANGED = 0x0020
+SWP_SHOWWINDOW = 0x0040
+SWP_HIDEWINDOW = 0x0080
+SWP_ASYNCWINDOWPOS = 0x4000
+SW_HIDE = 0
+SW_SHOWNORMAL = 1
+SW_SHOW = 5
+SW_RESTORE = 9
+GW_HWNDNEXT = 2
+GW_CHILD = 5
+WM_CLOSE = 0x0010
+WM_TIMER = 0x0113
+WM_QUIT = 0x0012
+WM_APP_TASK = 0x8000 + 0x51
+PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
+HWND_TOP = 0
+
+
+def _is_windows() -> bool:
+ return sys.platform == "win32"
+
+
+@dataclass
+class _Saved:
+ """What the browser window looked like before it was taken."""
+
+ style: int
+ exstyle: int
+ placement: Any
+
+
+class _Api:
+ """user32/kernel32 with real 64-bit signatures (handles are pointers)."""
+
+ def __init__(self) -> None:
+ from ctypes import wintypes # noqa: PLC0415
+
+ self.wt = wintypes
+ u = ctypes.WinDLL("user32", use_last_error=True)
+ k = ctypes.WinDLL("kernel32", use_last_error=True)
+ self.user32, self.kernel32 = u, k
+ H, INT, B, UI = wintypes.HWND, ctypes.c_int, wintypes.BOOL, wintypes.UINT
+ LP = ctypes.c_ssize_t
+ self.WNDPROC = ctypes.WINFUNCTYPE(LP, H, UI, wintypes.WPARAM, wintypes.LPARAM)
+ self.ENUMPROC = ctypes.WINFUNCTYPE(B, H, wintypes.LPARAM)
+
+ class WNDCLASSEXW(ctypes.Structure):
+ _fields_ = [
+ ("cbSize", UI), ("style", UI), ("lpfnWndProc", self.WNDPROC),
+ ("cbClsExtra", INT), ("cbWndExtra", INT), ("hInstance", wintypes.HINSTANCE),
+ ("hIcon", wintypes.HICON), ("hCursor", wintypes.HANDLE),
+ ("hbrBackground", wintypes.HBRUSH), ("lpszMenuName", wintypes.LPCWSTR),
+ ("lpszClassName", wintypes.LPCWSTR), ("hIconSm", wintypes.HICON),
+ ]
+
+ class WINDOWPLACEMENT(ctypes.Structure):
+ _fields_ = [
+ ("length", UI), ("flags", UI), ("showCmd", UI),
+ ("ptMinPosition", wintypes.POINT), ("ptMaxPosition", wintypes.POINT),
+ ("rcNormalPosition", wintypes.RECT),
+ ]
+
+ self.WNDCLASSEXW = WNDCLASSEXW
+ self.WINDOWPLACEMENT = WINDOWPLACEMENT
+
+ def sig(fn: Any, res: Any, *args: Any) -> None:
+ fn.restype = res
+ fn.argtypes = list(args)
+
+ sig(u.DefWindowProcW, LP, H, UI, wintypes.WPARAM, wintypes.LPARAM)
+ sig(u.RegisterClassExW, wintypes.ATOM, ctypes.POINTER(WNDCLASSEXW))
+ sig(u.CreateWindowExW, H, wintypes.DWORD, wintypes.LPCWSTR, wintypes.LPCWSTR,
+ wintypes.DWORD, INT, INT, INT, INT, H, wintypes.HMENU, wintypes.HINSTANCE,
+ wintypes.LPVOID)
+ sig(u.DestroyWindow, B, H)
+ sig(u.GetWindowLongPtrW, LP, H, INT)
+ sig(u.SetWindowLongPtrW, LP, H, INT, LP)
+ sig(u.SetParent, H, H, H)
+ sig(u.GetParent, H, H)
+ sig(u.GetWindow, H, H, UI)
+ sig(u.IsWindow, B, H)
+ sig(u.IsWindowVisible, B, H)
+ sig(u.IsIconic, B, H)
+ sig(u.IsHungAppWindow, B, H)
+ sig(u.IsZoomed, B, H)
+ sig(u.ShowWindow, B, H, INT)
+ sig(u.ShowWindowAsync, B, H, INT)
+ sig(u.SetWindowPos, B, H, H, INT, INT, INT, INT, UI)
+ sig(u.GetWindowRect, B, H, ctypes.POINTER(wintypes.RECT))
+ sig(u.GetClientRect, B, H, ctypes.POINTER(wintypes.RECT))
+ sig(u.MapWindowPoints, INT, H, H, ctypes.POINTER(wintypes.POINT), UI)
+ sig(u.GetWindowPlacement, B, H, ctypes.POINTER(WINDOWPLACEMENT))
+ sig(u.SetWindowPlacement, B, H, ctypes.POINTER(WINDOWPLACEMENT))
+ sig(u.PostMessageW, B, H, UI, wintypes.WPARAM, wintypes.LPARAM)
+ sig(u.PostThreadMessageW, B, wintypes.DWORD, UI, wintypes.WPARAM, wintypes.LPARAM)
+ sig(u.GetMessageW, B, ctypes.POINTER(wintypes.MSG), H, UI, UI)
+ sig(u.PeekMessageW, B, ctypes.POINTER(wintypes.MSG), H, UI, UI, UI)
+ sig(u.TranslateMessage, B, ctypes.POINTER(wintypes.MSG))
+ sig(u.DispatchMessageW, LP, ctypes.POINTER(wintypes.MSG))
+ sig(u.SetTimer, ctypes.c_size_t, H, ctypes.c_size_t, UI, ctypes.c_void_p)
+ sig(u.EnumWindows, B, self.ENUMPROC, wintypes.LPARAM)
+ sig(u.GetClassNameW, INT, H, wintypes.LPWSTR, INT)
+ sig(u.GetWindowTextW, INT, H, wintypes.LPWSTR, INT)
+ sig(u.GetWindowTextLengthW, INT, H)
+ sig(u.GetWindowThreadProcessId, wintypes.DWORD, H, ctypes.POINTER(wintypes.DWORD))
+ sig(u.SetForegroundWindow, B, H)
+ sig(k.GetCurrentThreadId, wintypes.DWORD)
+ sig(k.GetModuleHandleW, wintypes.HMODULE, wintypes.LPCWSTR)
+ sig(k.OpenProcess, wintypes.HANDLE, wintypes.DWORD, B, wintypes.DWORD)
+ sig(k.CloseHandle, B, wintypes.HANDLE)
+ sig(k.QueryFullProcessImageNameW, B, wintypes.HANDLE, wintypes.DWORD,
+ wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD))
+ gdi = ctypes.WinDLL("gdi32")
+ sig(gdi.GetStockObject, wintypes.HGDIOBJ, INT)
+ self.gdi32 = gdi
+
+ # -- small readers ----------------------------------------------------------
+
+ def class_name(self, hwnd: int) -> str:
+ buf = ctypes.create_unicode_buffer(128)
+ self.user32.GetClassNameW(hwnd, buf, 128)
+ return buf.value
+
+ def title(self, hwnd: int) -> str:
+ length = self.user32.GetWindowTextLengthW(hwnd)
+ if length <= 0:
+ return ""
+ buf = ctypes.create_unicode_buffer(length + 1)
+ self.user32.GetWindowTextW(hwnd, buf, length + 1)
+ return buf.value
+
+ def image_name(self, hwnd: int) -> str:
+ pid = self.wt.DWORD()
+ self.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
+ handle = self.kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid.value)
+ if not handle:
+ return ""
+ try:
+ size = self.wt.DWORD(1024)
+ buf = ctypes.create_unicode_buffer(size.value)
+ if not self.kernel32.QueryFullProcessImageNameW(handle, 0, buf, ctypes.byref(size)):
+ return ""
+ return Path(buf.value).name.lower()
+ finally:
+ self.kernel32.CloseHandle(handle)
+
+ def rect(self, hwnd: int, client: bool = False) -> tuple[int, int, int, int]:
+ r = self.wt.RECT()
+ (self.user32.GetClientRect if client else self.user32.GetWindowRect)(hwnd, ctypes.byref(r))
+ return r.left, r.top, r.right - r.left, r.bottom - r.top
+
+
+@dataclass
+class _Request:
+ owner: str
+ host: int
+ rect: Mapping[str, float] | None
+ dpr: float
+ visible: bool
+
+
+class ChromeEmbed:
+ """One browser window shown inside the app, driven from any thread.
+
+ Public methods are thread-safe and block for at most a few seconds
+ (``launch`` up to :data:`LAUNCH_TIMEOUT_S`). Every native window call runs
+ on the embed's own message-loop thread.
+ """
+
+ def __init__(self) -> None:
+ self._api: _Api | None = None
+ self._lock = threading.RLock()
+ self._tasks: queue.Queue[tuple[Callable[[], Any], Future[Any]]] = queue.Queue()
+ self._thread: threading.Thread | None = None
+ self._thread_id = 0
+ self._wndproc: Any = None
+ self._container = 0
+ self._host = 0
+ self._chrome = 0
+ self._saved: _Saved | None = None
+ self._owner = ""
+ self._visible = False
+ self._client_rect: tuple[int, int, int, int] | None = None
+ self._state = "idle"
+ self._reason = ""
+ self._browser = ""
+ self._profile = ""
+ self._generation = 0
+ self._closing = False
+ #: The page re-sends a visible placement about every second; without
+ #: one for a while (the page reloaded or crashed without saying so)
+ #: the window hides instead of staying over whatever loads next.
+ self._lease_until = 0.0
+
+ # -- public API -----------------------------------------------------------
+
+ @staticmethod
+ def supported() -> bool:
+ return _is_windows()
+
+ def status(self) -> dict[str, Any]:
+ with self._lock:
+ return {
+ "available": self.supported(),
+ "state": self._state,
+ "reason": self._reason,
+ "browser": self._browser,
+ "profile": self._profile,
+ "visible": self._visible and self._state == "embedded",
+ }
+
+ def launch(self, browser_id: str, profile: str, url: str | None, host: int) -> dict[str, Any]:
+ """Open a new window of ``browser_id`` with ``profile`` and take it into ``host``.
+
+ A window already shown for the same browser and profile is kept (the
+ page only asked again) and moves to ``host``. A different profile closes
+ the old window first. A newer launch supersedes one still waiting for
+ its window: the older one closes the window it opened.
+ """
+ if not self.supported():
+ return self._fail("unsupported")
+ spec = browser_by_id(browser_id)
+ if spec is None:
+ return self._fail("unknown_browser")
+ if not is_profile_dir(profile) or not self._profile_exists(spec, profile):
+ return self._fail("bad_profile")
+ exe = find_browser_exe(spec)
+ if exe is None:
+ return self._fail("browser_missing")
+ with self._lock:
+ if self._closing:
+ return self._fail("shutting_down")
+ self._generation += 1
+ generation = self._generation
+ same = (self._browser, self._profile) == (spec.id, profile)
+ alive = bool(self._chrome and self._api and self._api.user32.IsWindow(self._chrome))
+ try:
+ if alive and same:
+ self._call(lambda: self._ensure_container(host))
+ return {**self.status(), "ok": True}
+ if alive:
+ self.release(close=True)
+ self._ensure_thread()
+ with self._lock:
+ self._state, self._reason = "launching", ""
+ self._browser, self._profile = spec.id, profile
+ token = new_token()
+ if not self._start_browser(exe, profile, handoff_url(token, safe_start_url(url))):
+ return self._fail("launch_failed")
+ hwnd = self._wait_for_window(spec, token, generation)
+ if not hwnd:
+ if not self._current(generation):
+ return {**self.status(), "ok": False, "reason": "superseded"}
+ return self._fail("window_not_found")
+ if not self._current(generation):
+ # A newer launch or the app's shutdown came first.
+ self._load_api().user32.PostMessageW(hwnd, WM_CLOSE, 0, 0)
+ return {**self.status(), "ok": False, "reason": "superseded"}
+ try:
+ self._call(lambda: self._take(hwnd, host, generation))
+ except Exception:
+ # A window we opened but could not take must not stay behind.
+ self._load_api().user32.PostMessageW(hwnd, WM_CLOSE, 0, 0)
+ raise
+ return {**self.status(), "ok": True}
+ except Exception as exc: # noqa: BLE001 - reported to the page, logged here
+ logger.warning("Browser panel launch failed: %s", exc, exc_info=True)
+ return self._fail("launch_failed")
+
+ def _current(self, generation: int) -> bool:
+ with self._lock:
+ return generation == self._generation and not self._closing
+
+ @staticmethod
+ def _profile_exists(spec: BrowserSpec, profile: str) -> bool:
+ """Only a profile the browser lists may be opened; a typo would create a new one."""
+ profiles, _ = read_profiles(user_data_dir(spec))
+ if not profiles:
+ return profile == "Default"
+ return any(p.directory == profile for p in profiles)
+
+ def place(
+ self,
+ owner: str,
+ host: int,
+ rect: Mapping[str, float] | None,
+ dpr: float,
+ visible: bool,
+ ) -> dict[str, Any]:
+ """Move the window over the panel's rectangle, or hide it.
+
+ ``owner`` names the page component asking. Several hidden panels may
+ exist (one per workspace); a hide from a panel that is not the one shown
+ last is ignored, so it cannot blank the visible one.
+ """
+ if not self.supported():
+ return {**self.status(), "ok": False}
+ request = _Request(owner, host, rect, dpr, visible)
+ if self._thread is None:
+ # Nothing to move before the first launch; remember who asked.
+ with self._lock:
+ if visible:
+ self._owner = owner
+ return {**self.status(), "ok": True}
+ self._call(lambda: self._apply(request))
+ return {**self.status(), "ok": True}
+
+ def release(
+ self, *, close: bool, focus: bool = False, timeout: float = CALL_TIMEOUT_S,
+ ) -> dict[str, Any]:
+ """Give the window back to the desktop, then close it or leave it open."""
+ if self._thread is None or not self._chrome:
+ return {**self.status(), "ok": True}
+ try:
+ self._call(lambda: self._give_back(close=close, focus=focus), timeout)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Browser panel release failed: %s", exc, exc_info=True)
+ return {**self.status(), "ok": False, "reason": "release_failed"}
+ return {**self.status(), "ok": True}
+
+ def release_host(self, host: int) -> None:
+ """Close the window before ``host`` is destroyed (it would take it along)."""
+ if host and self._host == host and self._chrome:
+ # Called from the closing window's UI thread, which does not pump
+ # messages while it waits: keep the wait short.
+ hwnd = self._chrome
+ result = self.release(close=True, timeout=2.0)
+ if not result.get("ok") and hwnd and self._api is not None:
+ # At least ask the browser to close the window itself.
+ self._api.user32.PostMessageW(hwnd, WM_CLOSE, 0, 0)
+
+ def shutdown(self) -> None:
+ """Close the browser window and stop the native thread. Idempotent."""
+ with self._lock:
+ self._closing = True
+ self._generation += 1 # a launch still waiting closes what it finds
+ thread = self._thread
+ if thread is None:
+ return
+ try:
+ self.release(close=True, timeout=2.0)
+ self._call(self._destroy_container, 2.0)
+ except Exception: # noqa: BLE001
+ logger.debug("Browser panel shutdown was not clean", exc_info=True)
+ api = self._api
+ if api is not None and self._thread_id:
+ api.user32.PostThreadMessageW(self._thread_id, WM_QUIT, 0, 0)
+ thread.join(1.0)
+
+ # -- launching (caller thread) ----------------------------------------------
+
+ def _fail(self, reason: str) -> dict[str, Any]:
+ with self._lock:
+ if self._state == "launching":
+ self._state = "error"
+ self._reason = reason
+ return {**self.status(), "ok": False, "reason": reason}
+
+ @staticmethod
+ def _start_browser(exe: Path, profile: str, url: str) -> bool:
+ """Start the browser exe; a running browser opens the window in its own process.
+
+ The browser must not belong to the app's job object: when the browser
+ was not running yet, the started exe IS the browser, and closing the
+ app must not take it down. Breakaway can be forbidden by the job, so a
+ plain start is the fallback.
+ """
+ from dodaios.core.process_utils import NO_WINDOW_CREATIONFLAGS # noqa: PLC0415
+
+ argv = [str(exe), f"--profile-directory={profile}", "--new-window", url]
+ # The browser finds its profiles below %LOCALAPPDATA%. An app started
+ # with that variable pointed elsewhere (an isolated instance) would
+ # otherwise start a second, empty browser instead of the user's own.
+ env = dict(os.environ)
+ local = real_local_app_data()
+ if local:
+ env["LOCALAPPDATA"] = local
+ breakaway = getattr(subprocess, "CREATE_BREAKAWAY_FROM_JOB", 0x01000000)
+ for flags in (NO_WINDOW_CREATIONFLAGS | breakaway, NO_WINDOW_CREATIONFLAGS):
+ try:
+ subprocess.Popen(argv, creationflags=flags, close_fds=True, env=env) # noqa: S603
+ return True
+ except OSError as exc:
+ logger.info("Browser start with flags %#x failed: %s", flags, exc)
+ return False
+
+ def _wait_for_window(self, spec: BrowserSpec, token: str, generation: int) -> int:
+ api = self._load_api()
+ deadline = time.monotonic() + LAUNCH_TIMEOUT_S
+ while time.monotonic() < deadline and self._current(generation):
+ hwnd = self._find_window(api, spec, token)
+ if hwnd:
+ return hwnd
+ time.sleep(0.05)
+ return 0
+
+ @staticmethod
+ def _find_window(api: _Api, spec: BrowserSpec, token: str) -> int:
+ hits: list[int] = []
+
+ def visit(hwnd: int, _lparam: int) -> bool:
+ if token in api.title(hwnd) and api.class_name(hwnd) == _WINDOW_CLASS:
+ hits.append(int(hwnd))
+ return False
+ return True
+
+ api.user32.EnumWindows(api.ENUMPROC(visit), 0)
+ for hwnd in hits:
+ if api.image_name(hwnd) == spec.image_name:
+ return hwnd
+ return 0
+
+ # -- the native thread -------------------------------------------------------
+
+ def _load_api(self) -> _Api:
+ if self._api is None:
+ self._api = _Api()
+ return self._api
+
+ def _ensure_thread(self) -> None:
+ with self._lock:
+ if self._thread is not None and self._thread.is_alive():
+ return
+ if self._closing:
+ raise RuntimeError("browser panel is shutting down")
+ ready = threading.Event()
+ self._thread = threading.Thread(
+ target=self._loop, args=(ready,), name="browser-panel-embed", daemon=True,
+ )
+ self._thread.start()
+ if not ready.wait(CALL_TIMEOUT_S):
+ raise RuntimeError("browser panel thread did not start")
+
+ def _call(self, fn: Callable[[], T], timeout: float = CALL_TIMEOUT_S) -> T:
+ if threading.current_thread() is self._thread:
+ return fn()
+ self._ensure_thread()
+ future: Future[T] = Future()
+ self._tasks.put((fn, future))
+ self._load_api().user32.PostThreadMessageW(self._thread_id, WM_APP_TASK, 0, 0)
+ try:
+ return future.result(timeout)
+ except FutureTimeout as exc:
+ raise RuntimeError("browser panel thread did not answer") from exc
+
+ def _loop(self, ready: threading.Event) -> None:
+ api = self._load_api()
+ try:
+ from dodaios.core.win32_dpi import ensure_dpi_awareness # noqa: PLC0415
+
+ ensure_dpi_awareness()
+ except Exception: # noqa: BLE001
+ logger.debug("DPI awareness not set for the browser panel", exc_info=True)
+ msg = api.wt.MSG()
+ api.user32.PeekMessageW(ctypes.byref(msg), None, 0, 0, 0) # creates the queue
+ self._thread_id = int(api.kernel32.GetCurrentThreadId())
+ self._register_class(api)
+ api.user32.SetTimer(None, 0, WATCH_INTERVAL_MS, None)
+ ready.set()
+ while api.user32.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0:
+ try:
+ if msg.message == WM_APP_TASK and not msg.hWnd:
+ self._run_tasks()
+ elif msg.message == WM_TIMER and not msg.hWnd:
+ self._watch()
+ else:
+ api.user32.TranslateMessage(ctypes.byref(msg))
+ api.user32.DispatchMessageW(ctypes.byref(msg))
+ except Exception: # noqa: BLE001 - the loop outlives one bad message
+ logger.warning("Browser panel message failed", exc_info=True)
+ self._run_tasks()
+
+ def _run_tasks(self) -> None:
+ while True:
+ try:
+ fn, future = self._tasks.get_nowait()
+ except queue.Empty: # every queued task has run
+ return
+ if future.set_running_or_notify_cancel():
+ try:
+ future.set_result(fn())
+ except BaseException as exc: # noqa: BLE001 - handed to the caller
+ future.set_exception(exc)
+
+ def _register_class(self, api: _Api) -> None:
+ user32 = api.user32
+ self._wndproc = api.WNDPROC(lambda h, m, w, lp: user32.DefWindowProcW(h, m, w, lp))
+ wc = api.WNDCLASSEXW()
+ wc.cbSize = ctypes.sizeof(api.WNDCLASSEXW)
+ wc.lpfnWndProc = self._wndproc
+ wc.hInstance = api.kernel32.GetModuleHandleW(None)
+ wc.hbrBackground = api.gdi32.GetStockObject(4) # BLACK_BRUSH
+ wc.lpszClassName = _CONTAINER_CLASS
+ # A second embed in the same process finds the class already there: fine.
+ user32.RegisterClassExW(ctypes.byref(wc))
+
+ def _ensure_container(self, host: int) -> int:
+ api = self._load_api()
+ user32 = api.user32
+ if self._container and user32.IsWindow(self._container):
+ if self._host != host and host:
+ user32.SetParent(self._container, host)
+ self._host = host
+ return self._container
+ self._container = int(user32.CreateWindowExW(
+ WS_EX_NOPARENTNOTIFY, _CONTAINER_CLASS, None,
+ WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
+ 0, 0, 0, 0, host, None, api.kernel32.GetModuleHandleW(None), None,
+ ) or 0)
+ if not self._container:
+ raise RuntimeError(f"container window not created ({ctypes.get_last_error()})")
+ self._host = host
+ return self._container
+
+ def _destroy_container(self) -> None:
+ if self._container and self._api and self._api.user32.IsWindow(self._container):
+ self._api.user32.DestroyWindow(self._container)
+ self._container = 0
+ self._host = 0
+
+ # -- native work (runs on the embed thread) --------------------------------
+
+ def _take(self, hwnd: int, host: int, generation: int) -> None:
+ if not self._current(generation):
+ raise RuntimeError("superseded")
+ api = self._load_api()
+ user32 = api.user32
+ container = self._ensure_container(host)
+ placement = api.WINDOWPLACEMENT()
+ placement.length = ctypes.sizeof(api.WINDOWPLACEMENT)
+ user32.GetWindowPlacement(hwnd, ctypes.byref(placement))
+ style = int(user32.GetWindowLongPtrW(hwnd, GWL_STYLE))
+ exstyle = int(user32.GetWindowLongPtrW(hwnd, GWL_EXSTYLE))
+ self._saved = _Saved(style, exstyle, placement)
+ if user32.IsZoomed(hwnd) or user32.IsIconic(hwnd):
+ user32.ShowWindow(hwnd, SW_RESTORE)
+ frame = WS_POPUP | WS_CAPTION | WS_THICKFRAME | WS_MINIMIZE | WS_MAXIMIZE
+ frame |= WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX
+ user32.SetWindowLongPtrW(hwnd, GWL_STYLE, (style & ~frame) | WS_CHILD | WS_VISIBLE)
+ user32.SetWindowLongPtrW(hwnd, GWL_EXSTYLE, exstyle & ~WS_EX_APPWINDOW)
+ user32.SetParent(hwnd, container)
+ with self._lock:
+ self._chrome = hwnd
+ self._state, self._reason = "embedded", ""
+ self._fit()
+ self._show_container(self._visible and self._client_rect is not None)
+ logger.info("Browser panel took a %s window", self._browser)
+
+ def _apply(self, request: _Request) -> None:
+ with self._lock:
+ if not request.visible:
+ if request.owner != self._owner:
+ return
+ self._visible = False
+ else:
+ self._owner = request.owner
+ self._visible = True
+ self._lease_until = time.monotonic() + LEASE_S
+ if not request.visible or not request.host:
+ self._show_container(False)
+ return
+ container = self._ensure_container(request.host)
+ if request.rect is not None:
+ origin = self._page_origin(request.host)
+ self._client_rect = panel_to_client_rect(request.rect, request.dpr, origin)
+ if self._client_rect is None:
+ return
+ x, y, w, h = self._client_rect
+ self._load_api().user32.SetWindowPos(
+ container, HWND_TOP, x, y, w, h, SWP_NOACTIVATE,
+ )
+ self._fit()
+ self._show_container(bool(self._chrome) and w > 0 and h > 0)
+
+ def _page_origin(self, host: int) -> tuple[int, int]:
+ """Where the page (the WebView) starts inside the host's client area.
+
+ The WebView is the host's largest visible child; the container itself
+ is skipped. A host without children puts the page at the origin.
+ """
+ api = self._load_api()
+ user32 = api.user32
+ best, best_area = 0, -1
+ child = user32.GetWindow(host, GW_CHILD)
+ while child:
+ if int(child) != self._container and user32.IsWindowVisible(child):
+ _, _, w, h = api.rect(child)
+ if w * h > best_area:
+ best, best_area = int(child), w * h
+ child = user32.GetWindow(child, GW_HWNDNEXT)
+ if not best:
+ return 0, 0
+ point = api.wt.POINT(0, 0)
+ user32.MapWindowPoints(best, host, ctypes.byref(point), 1)
+ return point.x, point.y
+
+ def _show_container(self, show: bool) -> None:
+ api = self._load_api()
+ if not self._container:
+ return
+ if show:
+ api.user32.SetWindowPos(
+ self._container, HWND_TOP, 0, 0, 0, 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW,
+ )
+ else:
+ api.user32.ShowWindow(self._container, SW_HIDE)
+
+ def _fit(self) -> None:
+ """Make the browser's page area fill the container exactly.
+
+ The browser keeps an invisible resize border around its client area
+ even as a child window (7 px left, right and bottom at 100 %). The
+ window is made that much larger and shifted, so the border falls
+ outside the container and is clipped instead of showing as a black
+ frame.
+ """
+ target = self._fit_target()
+ if target is None:
+ return
+ x, y, w, h = target
+ self._load_api().user32.SetWindowPos(
+ self._chrome, None, x, y, w, h,
+ SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS,
+ )
+
+ def _fit_target(self) -> tuple[int, int, int, int] | None:
+ """Where the browser window must sit inside the container, or None."""
+ if not self._chrome or not self._container:
+ return None
+ api = self._load_api()
+ _, _, cw, ch = api.rect(self._container, client=True)
+ left, top, right, bottom = self._frame_insets()
+ return -left, -top, cw + left + right, ch + top + bottom
+
+ def _frame_insets(self) -> tuple[int, int, int, int]:
+ """The browser window's border around its client area: left, top, right, bottom."""
+ api = self._load_api()
+ wx, wy, ww, wh = api.rect(self._chrome)
+ _, _, cw, ch = api.rect(self._chrome, client=True)
+ origin = api.wt.POINT(0, 0)
+ api.user32.MapWindowPoints(self._chrome, None, ctypes.byref(origin), 1)
+ left, top = origin.x - wx, origin.y - wy
+ right, bottom = ww - cw - left, wh - ch - top
+ insets = (left, top, right, bottom)
+ # A border wider than 32 px is a reading taken mid-change: ignore it.
+ return insets if all(0 <= v <= 32 for v in insets) else (0, 0, 0, 0)
+
+ def _watch(self) -> None:
+ """Keep the window in place and notice when it is gone. Runs on a timer."""
+ hwnd = self._chrome
+ if not hwnd:
+ return
+ api = self._load_api()
+ user32 = api.user32
+ if self._visible and time.monotonic() > self._lease_until:
+ with self._lock:
+ self._visible = False
+ self._show_container(False)
+ if user32.IsHungAppWindow(hwnd):
+ return # never wait on a browser that does not answer
+ try:
+ if not user32.IsWindow(hwnd) or int(user32.GetParent(hwnd) or 0) != self._container:
+ with self._lock:
+ self._lost("closed")
+ self._show_container(False)
+ return
+ if user32.IsIconic(hwnd) or user32.IsZoomed(hwnd):
+ # The browser's own minimize / maximize buttons: stay in the panel.
+ user32.ShowWindowAsync(hwnd, SW_RESTORE)
+ target = self._fit_target()
+ if target is not None:
+ _, _, w, h = api.rect(hwnd)
+ if (w, h) != target[2:]:
+ self._fit()
+ if self._visible and user32.IsWindowVisible(self._container):
+ top = int(user32.GetWindow(self._host, GW_CHILD) or 0)
+ if top and top != self._container:
+ self._show_container(True)
+ except Exception: # noqa: BLE001 - a watchdog tick must never end the loop
+ logger.debug("Browser panel watchdog tick failed", exc_info=True)
+
+ def _lost(self, state: str) -> None:
+ self._chrome = 0
+ self._saved = None
+ self._state = state
+
+ def _give_back(self, *, close: bool, focus: bool) -> None:
+ hwnd, saved = self._chrome, self._saved
+ api = self._load_api()
+ user32 = api.user32
+ with self._lock:
+ self._lost("released" if not close else "idle")
+ self._show_container(False)
+ if not hwnd or not user32.IsWindow(hwnd):
+ return
+ if user32.IsHungAppWindow(hwnd):
+ # Every call below would wait on the frozen browser. Ask it to close
+ # once it recovers; otherwise it goes down with the app window.
+ logger.warning("Browser panel window does not answer; not handing it back")
+ if close:
+ user32.PostMessageW(hwnd, WM_CLOSE, 0, 0)
+ return
+ if close:
+ user32.ShowWindow(hwnd, SW_HIDE)
+ user32.SetParent(hwnd, None)
+ if saved is not None:
+ style = saved.style & ~(WS_VISIBLE | WS_MINIMIZE | WS_MAXIMIZE)
+ user32.SetWindowLongPtrW(hwnd, GWL_STYLE, style)
+ user32.SetWindowLongPtrW(hwnd, GWL_EXSTYLE, saved.exstyle)
+ placement = saved.placement
+ if close:
+ placement.showCmd = SW_HIDE
+ elif placement.showCmd not in (SW_SHOWNORMAL, 3): # 3 = SW_SHOWMAXIMIZED
+ placement.showCmd = SW_SHOWNORMAL
+ user32.SetWindowPlacement(hwnd, ctypes.byref(placement))
+ user32.SetWindowPos(
+ hwnd, None, 0, 0, 0, 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE,
+ )
+ logger.info("Browser panel gave its window back (%s)", "closed" if close else "kept open")
+ if close:
+ user32.PostMessageW(hwnd, WM_CLOSE, 0, 0)
+ else:
+ user32.ShowWindow(hwnd, SW_SHOW)
+ if focus:
+ user32.SetForegroundWindow(hwnd)
+
+
+_embed: ChromeEmbed | None = None
+_embed_lock = threading.Lock()
+
+
+def get_embed() -> ChromeEmbed:
+ """The process-wide embed (one browser window per app)."""
+ global _embed
+ with _embed_lock:
+ if _embed is None:
+ _embed = ChromeEmbed()
+ return _embed
+
+
+def release_host_if_any(host: int) -> None:
+ """Close the panel's browser window if it sits in ``host``; no-op otherwise."""
+ embed = _embed
+ if embed is not None:
+ embed.release_host(host)
+
+
+def shutdown_embed() -> None:
+ """Close the panel's browser window on app exit. Never raises."""
+ embed = _embed
+ if embed is None:
+ return
+ try:
+ embed.shutdown()
+ except Exception: # noqa: BLE001
+ logger.debug("Browser panel shutdown failed", exc_info=True)
+
diff --git a/dodaios/ui/browser_profiles.py b/dodaios/ui/browser_profiles.py
new file mode 100644
index 0000000000..f8ccb444bc
--- /dev/null
+++ b/dodaios/ui/browser_profiles.py
@@ -0,0 +1,315 @@
+"""The user's installed Chromium browsers and their profiles, for the IDE browser panel.
+
+The Agentic IDE's browser panel shows a real window of the user's own browser,
+signed in with their own profile (see ``dodaios.ui.browser_embed``). This module
+holds the parts that need no window system: where the browsers live, which
+profiles they have, how the new window is recognised, and how a panel's page
+rectangle becomes window pixels. Everything here is pure or reads files only,
+so it is tested on every platform.
+
+Profiles come from the browser's own ``Local State`` file, the same list the
+browser's profile picker shows. Nothing is copied, decrypted or changed: the
+window that opens is the browser itself, so cookies and sign-ins stay where they
+are.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import re
+from collections.abc import Mapping
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+from urllib.parse import quote, urlparse
+
+logger = logging.getLogger(__name__)
+
+__all__ = [
+ "BROWSERS",
+ "DEFAULT_START_URL",
+ "BrowserProfile",
+ "BrowserSpec",
+ "browser_by_id",
+ "find_browser_exe",
+ "handoff_url",
+ "installed_browsers",
+ "is_profile_dir",
+ "is_token",
+ "new_token",
+ "panel_to_client_rect",
+ "read_profiles",
+ "real_local_app_data",
+ "safe_start_url",
+]
+
+#: Where a fresh panel window goes when no address was given.
+DEFAULT_START_URL = "https://www.google.com/"
+
+
+@dataclass(frozen=True)
+class BrowserSpec:
+ """One Chromium browser: where its exe and its profiles live on Windows."""
+
+ id: str
+ label: str
+ #: Paths below Program Files, Program Files (x86) or %LOCALAPPDATA%.
+ exe_relpaths: tuple[str, ...]
+ #: The ``User Data`` folder below %LOCALAPPDATA%.
+ user_data_rel: str
+
+ @property
+ def image_name(self) -> str:
+ """The exe file name, as the process of a browser window reports it."""
+ return Path(self.exe_relpaths[0].replace("\\", "/")).name.lower()
+
+
+#: Chrome first: it is what most people mean by "my browser". Edge and Brave are
+#: the same engine, so the same window handling works for them.
+BROWSERS: tuple[BrowserSpec, ...] = (
+ BrowserSpec(
+ "chrome", "Google Chrome",
+ (r"Google\Chrome\Application\chrome.exe",), r"Google\Chrome\User Data",
+ ),
+ BrowserSpec(
+ "edge", "Microsoft Edge",
+ (r"Microsoft\Edge\Application\msedge.exe",), r"Microsoft\Edge\User Data",
+ ),
+ BrowserSpec(
+ "brave", "Brave",
+ (r"BraveSoftware\Brave-Browser\Application\brave.exe",),
+ r"BraveSoftware\Brave-Browser\User Data",
+ ),
+)
+
+
+def browser_by_id(browser_id: str | None) -> BrowserSpec | None:
+ """The spec for ``browser_id``, or None for an unknown id."""
+ return next((spec for spec in BROWSERS if spec.id == browser_id), None)
+
+
+@dataclass(frozen=True)
+class BrowserProfile:
+ """One profile as the browser's own profile picker lists it."""
+
+ directory: str
+ name: str
+ #: The signed-in account, empty for a profile without sign-in.
+ email: str
+
+ def as_dict(self) -> dict[str, str]:
+ return {"directory": self.directory, "name": self.name, "email": self.email}
+
+
+def _install_roots(env: Mapping[str, str]) -> list[Path]:
+ local = env.get("LOCALAPPDATA") if env is not os.environ else (
+ real_local_app_data() or env.get("LOCALAPPDATA")
+ )
+ roots = [
+ env.get("PROGRAMFILES") or r"C:\Program Files",
+ env.get("PROGRAMFILES(X86)") or r"C:\Program Files (x86)",
+ local or "",
+ ]
+ return [Path(root) for root in roots if root]
+
+
+def find_browser_exe(spec: BrowserSpec, env: Mapping[str, str] | None = None) -> Path | None:
+ """The installed exe of ``spec``, or None when it is not installed."""
+ env = os.environ if env is None else env
+ for root in _install_roots(env):
+ for relpath in spec.exe_relpaths:
+ candidate = root / relpath
+ if candidate.is_file():
+ return candidate
+ return None
+
+
+def real_local_app_data() -> str | None:
+ """The real per-user Local AppData folder from the shell, or None off Windows.
+
+ Asked from the shell rather than read from %LOCALAPPDATA%, which a launcher
+ or an isolated test instance may point elsewhere: the browser's profiles
+ are always in the user's real folder.
+ """
+ if os.name != "nt":
+ return None
+ try:
+ import ctypes # noqa: PLC0415
+ import uuid # noqa: PLC0415
+ from ctypes import wintypes # noqa: PLC0415
+
+ folder = uuid.UUID("{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}") # FOLDERID_LocalAppData
+ guid = (ctypes.c_byte * 16).from_buffer_copy(folder.bytes_le)
+ path = wintypes.LPWSTR()
+ shell32 = ctypes.WinDLL("shell32")
+ if shell32.SHGetKnownFolderPath(ctypes.byref(guid), 0, None, ctypes.byref(path)) != 0:
+ return None
+ try:
+ return path.value
+ finally:
+ ctypes.WinDLL("ole32").CoTaskMemFree(path)
+ except (OSError, AttributeError, ValueError): # no shell folder API: callers use %LOCALAPPDATA%
+ return None
+
+
+def user_data_dir(spec: BrowserSpec, env: Mapping[str, str] | None = None) -> Path | None:
+ """The browser's ``User Data`` folder, or None when Local AppData is unknown.
+
+ With an explicit ``env`` (tests) only that mapping is used.
+ """
+ if env is not None:
+ local = env.get("LOCALAPPDATA")
+ else:
+ local = real_local_app_data() or os.environ.get("LOCALAPPDATA")
+ return Path(local) / spec.user_data_rel if local else None
+
+
+def read_profiles(user_data: Path | None) -> tuple[list[BrowserProfile], str | None]:
+ """The profiles in ``user_data`` and the one used last.
+
+ Reads ``Local State``, the file behind the browser's own profile picker.
+ Profiles keep the picker's order. A missing or unreadable file gives no
+ profiles, so a browser that was never started simply offers its default
+ profile. Never raises.
+ """
+ if user_data is None:
+ return [], None
+ try:
+ state = json.loads((user_data / "Local State").read_text(encoding="utf-8"))
+ except FileNotFoundError: # a browser that never ran has no profile list yet
+ return [], None
+ except (OSError, ValueError) as exc:
+ logger.warning("Could not read the browser profile list: %s", type(exc).__name__)
+ return [], None
+ section = state.get("profile") if isinstance(state, dict) else None
+ if not isinstance(section, dict):
+ return [], None
+ cache = section.get("info_cache")
+ if not isinstance(cache, dict):
+ return [], None
+ profiles: dict[str, BrowserProfile] = {}
+ for directory, info in cache.items():
+ if not isinstance(directory, str) or not isinstance(info, dict):
+ continue
+ if info.get("is_omitted_from_profile_list") or info.get("is_ephemeral"):
+ continue
+ name = str(info.get("name") or info.get("gaia_name") or directory)
+ email = str(info.get("user_name") or "")
+ profiles[directory] = BrowserProfile(directory, name, email)
+ order = section.get("profiles_order")
+ ordered: list[BrowserProfile] = []
+ if isinstance(order, list):
+ ordered = [profiles.pop(d) for d in order if isinstance(d, str) and d in profiles]
+ ordered.extend(sorted(profiles.values(), key=lambda p: p.name.lower()))
+ last_used = section.get("last_used")
+ if not isinstance(last_used, str) or last_used not in {p.directory for p in ordered}:
+ last_used = ordered[0].directory if ordered else None
+ return ordered, last_used
+
+
+def installed_browsers(env: Mapping[str, str] | None = None) -> list[dict[str, Any]]:
+ """Every installed browser of :data:`BROWSERS` with its profiles, for the panel's picker."""
+ found: list[dict[str, Any]] = []
+ for spec in BROWSERS:
+ if find_browser_exe(spec, env) is None:
+ continue
+ profiles, last_used = read_profiles(user_data_dir(spec, env))
+ if not profiles:
+ # A browser that never ran still has its default profile.
+ profiles, last_used = [BrowserProfile("Default", spec.label, "")], "Default"
+ found.append({
+ "id": spec.id,
+ "label": spec.label,
+ "profiles": [profile.as_dict() for profile in profiles],
+ "last_used": last_used,
+ })
+ return found
+
+
+_PROFILE_DIR = re.compile(r"^[A-Za-z0-9 _.-]{1,64}$")
+
+
+def is_profile_dir(value: str) -> bool:
+ """Whether ``value`` can be a profile folder name (no paths, no switches)."""
+ return (
+ bool(_PROFILE_DIR.fullmatch(value))
+ and not value.startswith(("-", ".", " "))
+ and not value.endswith((".", " "))
+ )
+
+
+def safe_start_url(url: str | None) -> str:
+ """``url`` when it is a plain http(s) address, otherwise the default start page.
+
+ Only web addresses are passed on: a ``file:``, ``javascript:`` or browser
+ internal page cannot be opened this way and is not tried.
+ """
+ if not url:
+ return DEFAULT_START_URL
+ parsed = urlparse(url.strip())
+ if parsed.scheme in ("http", "https") and parsed.netloc:
+ return url.strip()
+ return DEFAULT_START_URL
+
+
+_TOKEN = re.compile(r"^[a-z0-9]{12,40}$")
+
+
+def new_token() -> str:
+ """A fresh marker that names exactly one new browser window."""
+ import secrets # noqa: PLC0415
+
+ return "dodaios" + secrets.token_hex(8)
+
+
+def is_token(value: str) -> bool:
+ return bool(_TOKEN.match(value))
+
+
+def handoff_url(token: str, target: str) -> str:
+ """The address the new window opens first: a blank page titled ``token``.
+
+ The window title carries the page title, so the token identifies the window
+ the app asked for even when the browser opens other windows at the same
+ time (a cold start restoring the last session). A ``data:`` page needs no
+ server: the browser never has to reach the app. It forwards to ``target``
+ after a moment, which is enough for the app to find and take the window;
+ ``location.replace`` keeps the blank page out of the back history.
+ """
+ if not is_token(token):
+ raise ValueError("invalid window token")
+ # JSON keeps the address a string literal; escaping "<" keeps it inside the script.
+ target_js = json.dumps(safe_start_url(target)).replace("<", "\\u003c")
+ html = (
+ f"<!doctype html><title>{token}</title>"
+ "<body style='margin:0;background:#1f1f1f'></body>"
+ f"<script>setTimeout(function(){{location.replace({target_js})}},900)</script>"
+ )
+ return "data:text/html;charset=utf-8," + quote(html, safe="")
+
+
+def panel_to_client_rect(
+ rect: Mapping[str, float],
+ device_pixel_ratio: float,
+ origin: tuple[int, int],
+) -> tuple[int, int, int, int]:
+ """Turn a page rectangle (CSS pixels) into ``(x, y, width, height)`` window pixels.
+
+ ``rect`` is the panel's ``getBoundingClientRect()``; ``device_pixel_ratio``
+ is the page's ``devicePixelRatio``, which already holds both the monitor
+ scale and the app's own zoom. ``origin`` is where the page's top-left corner
+ sits in the host window's client area. Edges are rounded separately, so two
+ panels that touch in CSS still touch in pixels. Never negative in size.
+ """
+ ratio = device_pixel_ratio if device_pixel_ratio > 0 else 1.0
+ x = float(rect.get("x", 0.0))
+ y = float(rect.get("y", 0.0))
+ width = max(0.0, float(rect.get("width", 0.0)))
+ height = max(0.0, float(rect.get("height", 0.0)))
+ left = round(x * ratio) + origin[0]
+ top = round(y * ratio) + origin[1]
+ right = round((x + width) * ratio) + origin[0]
+ bottom = round((y + height) * ratio) + origin[1]
+ return left, top, max(0, right - left), max(0, bottom - top)
diff --git a/dodaios/ui/desktop_app.py b/dodaios/ui/desktop_app.py
index d0946bd2c0..26c218ae80 100644
--- a/dodaios/ui/desktop_app.py
+++ b/dodaios/ui/desktop_app.py
@@ -5420,6 +5420,42 @@ class DesktopApp:
window = self._detached_windows.get(section_window(view)) if view else self._window
return set_window_zoom(window, factor)
+ def browser_panel_host(self, view: str | None) -> int | None:
+ """The native handle of the window that shows ``view`` (main when None).
+
+ The IDE browser panel puts the user's own browser window inside this
+ window (see ``dodaios.ui.browser_embed``). None off Windows or when that
+ window is not open.
+ """
+ if sys.platform != "win32":
+ return None
+ from dodaios.ui.window_frame import native_hwnd
+
+ window = self._detached_windows.get(section_window(view)) if view else self._window
+ return native_hwnd(window) if window is not None else None
+
+ @staticmethod
+ def _release_browser_panel(window: Any) -> None:
+ """Close the panel's browser window before ``window`` is destroyed.
+
+ A child window goes down with its parent; closing it first lets the
+ browser keep its normal window bounds. Never raises: closing the app
+ window must not depend on it.
+ """
+ if sys.platform != "win32" or window is None:
+ return
+ try:
+ from dodaios.ui.browser_embed import release_host_if_any
+ from dodaios.ui.window_frame import native_hwnd
+
+ hwnd = native_hwnd(window)
+ if hwnd:
+ release_host_if_any(hwnd)
+ except Exception: # noqa: BLE001
+ from loguru import logger
+
+ logger.exception("The browser panel was not released before the window closed")
+
def _arm_window_frame(self, window: Any) -> None:
"""Let a frameless Windows window still be resized from its edges.
@@ -5564,6 +5600,7 @@ class DesktopApp:
self._detached_windows[view] = window
self._arm_window_frame(window)
window.events.loaded += lambda w=window, v=view: self._inject_into_secondary(w, v)
+ window.events.closing += lambda w=window: self._release_browser_panel(w)
window.events.closed += lambda v=view: self._on_detached_closed(v)
self._publish_detached_event_threadsafe(view, opened=True)
return {"ok": True, "already_open": False, "view": view}
@@ -6850,6 +6887,7 @@ class DesktopApp:
are released. Explicit Quit always overrides the background preference.
"""
self._main_window_closing = True
+ self._release_browser_panel(self._window)
if not self._detached_windows and not self._background_keeps_running():
self._user_requested_quit = True
self._begin_quit_from_close()
@@ -7102,6 +7140,10 @@ class DesktopApp:
self._shutdown_done = True
_mark_instance_quitting()
self._window_visible = False
+ if sys.platform == "win32":
+ from dodaios.ui.browser_embed import shutdown_embed
+
+ shutdown_embed()
self._destroy_background_keeper()
# A shutting-down backend fails every health probe by design; without
diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/BrowserTab.tsx b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/BrowserTab.tsx
index 36598503af..f76f83adbe 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/BrowserTab.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/BrowserTab.tsx
@@ -1,10 +1,31 @@
import { useRef, useState, type FormEvent } from "react";
-import { ExternalLink, Globe, RotateCw } from "lucide-react";
+import { AppWindow, ExternalLink, Globe, RotateCw } from "lucide-react";
import { useT } from "@/i18n";
+import { hasEmbeddedDesktopBridge } from "@/lib/embeddedDesktop";
import { openExternalUrl } from "@/lib/openExternal";
import { normalizeBrowserAddress } from "./browserAddress";
+import { NativeBrowserPanel } from "./NativeBrowserPanel";
+import { useNativeBrowserStatus } from "./nativeBrowserApi";
const URL_KEY = "jarvis.agenticIde.browserUrl.v1";
+const BUILTIN_KEY = "jarvis.agenticIde.browserBuiltin.v1";
+
+function storedBuiltin(): boolean {
+ try {
+ return localStorage.getItem(BUILTIN_KEY) === "1";
+ } catch {
+ return false;
+ }
+}
+
+function persistBuiltin(value: boolean): void {
+ try {
+ if (value) localStorage.setItem(BUILTIN_KEY, "1");
+ else localStorage.removeItem(BUILTIN_KEY);
+ } catch {
+ /* a convenience only */
+ }
+}
function storedUrl(): string {
try {
@@ -28,14 +49,46 @@ const TOOL_BTN =
"disabled:cursor-default disabled:opacity-40 disabled:hover:bg-transparent";
/**
- * The side panel's Browser surface: an address bar over an embedded page.
+ * The side panel's Browser surface.
+ *
+ * On the Windows desktop app it shows the user's own browser (Chrome, Edge or
+ * Brave) with their profile and sign-ins: see `NativeBrowserPanel`. Everywhere
+ * else, or when the reader picks it, it is the built-in page view below.
+ */
+export function BrowserTab() {
+ // Fixed for the page's lifetime, so the branch never swaps hooks.
+ return hasEmbeddedDesktopBridge() ? <DesktopBrowserTab /> : <FrameBrowser />;
+}
+
+function DesktopBrowserTab() {
+ const [builtin, setBuiltin] = useState(storedBuiltin);
+ const status = useNativeBrowserStatus(true, !builtin);
+ const native = status.data?.available ? status.data : null;
+
+ const chooseBuiltin = (value: boolean) => {
+ persistBuiltin(value);
+ setBuiltin(value);
+ };
+
+ if (!builtin && status.isPending) {
+ return <div data-testid="ide-browser-tab" className="h-full" />;
+ }
+ if (native && !builtin) {
+ return <NativeBrowserPanel status={native} startUrl={storedUrl() || null}
+ onUseBuiltin={() => chooseBuiltin(true)} />;
+ }
+ return <FrameBrowser onUseNative={native ? () => chooseBuiltin(false) : undefined} />;
+}
+
+/**
+ * The built-in page view: an address bar over an embedded page.
*
* Built for local previews (a dev server on localhost) and plain pages. Many
* public sites forbid being shown inside another app; for those the "open in
* your browser" button hands the address to the system browser. The frame may
* not navigate the app itself (no `allow-top-navigation`).
*/
-export function BrowserTab() {
+function FrameBrowser({ onUseNative }: { onUseNative?: () => void }) {
const t = useT();
const [url, setUrl] = useState(storedUrl);
const [draft, setDraft] = useState(url);
@@ -74,6 +127,13 @@ export function BrowserTab() {
data-testid="ide-browser-address"
className="h-7 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
+ {onUseNative && (
+ <button type="button" onClick={onUseNative}
+ aria-label={t("ide_side_panel.browser.native.use_native")} title={t("ide_side_panel.browser.native.use_native")}
+ data-testid="ide-browser-use-native" className={TOOL_BTN}>
+ <AppWindow className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ )}
<button type="button" onClick={() => void openExternalUrl(url)} disabled={!url}
aria-label={t("ide_side_panel.browser.open_external")} title={t("ide_side_panel.browser.open_external")}
data-testid="ide-browser-external" className={TOOL_BTN}>
diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/NativeBrowserPanel.test.tsx b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/NativeBrowserPanel.test.tsx
new file mode 100644
index 0000000000..786a07fd80
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/NativeBrowserPanel.test.tsx
@@ -0,0 +1,117 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { BrowserTab } from "./BrowserTab";
+import { initialChoice, type NativeBrowser } from "./nativeBrowserApi";
+import { boxesOverlap, measurePanel, overlayCovers } from "./useNativePlacement";
+
+const BROWSERS: NativeBrowser[] = [{
+ id: "chrome",
+ label: "Google Chrome",
+ profiles: [
+ { directory: "Profile 7", name: "kontakt", email: "[email protected]" },
+ { directory: "Profile 3", name: "Profil 1", email: "[email protected]" },
+ ],
+ last_used: "Profile 3",
+}];
+
+function rect(x: number, y: number, width: number, height: number): DOMRect {
+ return { x, y, width, height, left: x, top: y, right: x + width, bottom: y + height, toJSON: () => ({}) } as DOMRect;
+}
+
+describe("placement helpers", () => {
+ afterEach(() => cleanup());
+
+ it("detects overlapping boxes, not touching ones", () => {
+ expect(boxesOverlap(rect(0, 0, 10, 10), rect(5, 5, 10, 10))).toBe(true);
+ expect(boxesOverlap(rect(0, 0, 10, 10), rect(10, 0, 10, 10))).toBe(false);
+ });
+
+ it("reports a hidden panel as hidden", () => {
+ const panel = document.createElement("div");
+ document.body.appendChild(panel);
+ panel.getBoundingClientRect = () => rect(0, 0, 0, 0);
+ expect(measurePanel(panel, "p").visible).toBe(false);
+ expect(measurePanel(null, "p").visible).toBe(false);
+ panel.remove();
+ });
+
+ it("hides the browser while an app menu covers the panel", () => {
+ const panel = document.createElement("div");
+ panel.getBoundingClientRect = () => rect(100, 100, 400, 400);
+ const menu = document.createElement("div");
+ menu.setAttribute("role", "menu");
+ menu.getBoundingClientRect = () => rect(300, 80, 200, 100);
+ document.body.append(panel, menu);
+ expect(overlayCovers(panel)).toBe(true);
+ expect(measurePanel(panel, "p").visible).toBe(false);
+ menu.getBoundingClientRect = () => rect(0, 0, 50, 50);
+ expect(measurePanel(panel, "p")).toMatchObject({ visible: true, rect: { x: 100, y: 100, width: 400, height: 400 } });
+ panel.remove();
+ menu.remove();
+ });
+});
+
+describe("initialChoice", () => {
+ beforeEach(() => localStorage.clear());
+
+ it("uses the browser's own last profile first", () => {
+ expect(initialChoice(BROWSERS)).toEqual({ browser: "chrome", profile: "Profile 3" });
+ });
+
+ it("keeps a remembered profile that still exists", () => {
+ localStorage.setItem("jarvis.agenticIde.browserProfile.v1", JSON.stringify({ browser: "chrome", profile: "Profile 7" }));
+ expect(initialChoice(BROWSERS)).toEqual({ browser: "chrome", profile: "Profile 7" });
+ localStorage.setItem("jarvis.agenticIde.browserProfile.v1", JSON.stringify({ browser: "chrome", profile: "Gone" }));
+ expect(initialChoice(BROWSERS)).toEqual({ browser: "chrome", profile: "Profile 3" });
+ });
+
+ it("has nothing to offer without a browser", () => {
+ expect(initialChoice([])).toBeNull();
+ });
+});
+
+describe("BrowserTab on the desktop app", () => {
+ const host = window as unknown as { __JARVIS_EMBEDDED_DESKTOP?: boolean };
+
+ beforeEach(() => {
+ localStorage.clear();
+ host.__JARVIS_EMBEDDED_DESKTOP = true;
+ });
+
+ afterEach(() => {
+ cleanup();
+ delete host.__JARVIS_EMBEDDED_DESKTOP;
+ vi.unstubAllGlobals();
+ });
+
+ function renderTab(status: Record<string, unknown>) {
+ const fetchMock = vi.fn(async (url: string) => ({
+ ok: true,
+ json: async () => (url.endsWith("/status") ? status : { ...status, ok: true }),
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(<QueryClientProvider client={client}><BrowserTab /></QueryClientProvider>);
+ return fetchMock;
+ }
+
+ it("shows the user's own browser with a profile picker", async () => {
+ renderTab({ available: true, reason: "", state: "idle", browsers: BROWSERS });
+ await waitFor(() => expect(screen.getByTestId("ide-browser-tab").dataset.mode).toBe("native"));
+ expect(screen.getByTestId("ide-browser-profile")).toBeTruthy();
+ expect(screen.queryByTestId("ide-browser-frame")).toBeNull();
+ });
+
+ it("offers reopening after the window was closed", async () => {
+ renderTab({ available: true, reason: "", state: "closed", browser: "chrome", profile: "Profile 3", browsers: BROWSERS });
+ await waitFor(() => expect(screen.getByTestId("ide-browser-reopen")).toBeTruthy());
+ });
+
+ it("falls back to the built-in view where the browser cannot be shown", async () => {
+ renderTab({ available: false, reason: "no_browser", state: "idle", browsers: [] });
+ await waitFor(() => expect(screen.getByTestId("ide-browser-address")).toBeTruthy());
+ expect(screen.queryByTestId("ide-browser-use-native")).toBeNull();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/NativeBrowserPanel.tsx b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/NativeBrowserPanel.tsx
new file mode 100644
index 0000000000..04438fa420
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/NativeBrowserPanel.tsx
@@ -0,0 +1,176 @@
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { AppWindow, Globe, Loader2 } from "lucide-react";
+
+import { BrandedSelect } from "@/components/ui/select";
+import { fill, useT } from "@/i18n";
+
+import {
+ NATIVE_BROWSER_STATUS_QUERY,
+ initialChoice,
+ launchNativeBrowser,
+ releaseNativeBrowser,
+ rememberChoice,
+ type NativeBrowserChoice,
+ type NativeBrowserStatus,
+} from "./nativeBrowserApi";
+import { useNativePlacement } from "./useNativePlacement";
+
+const TOOL_BTN =
+ "inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors " +
+ "hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring " +
+ "disabled:cursor-default disabled:opacity-40 disabled:hover:bg-transparent";
+
+const LINK_BTN =
+ "rounded-md border border-border px-3 py-1.5 text-xs text-foreground transition-colors hover:bg-secondary " +
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
+
+function choiceValue(choice: NativeBrowserChoice): string {
+ return `${choice.browser}\n${choice.profile}`;
+}
+
+function parseChoice(value: string): NativeBrowserChoice {
+ const [browser = "", profile = ""] = value.split("\n");
+ return { browser, profile };
+}
+
+/**
+ * The browser panel on the Windows desktop app: the user's own browser.
+ *
+ * A real window of the installed Chrome (or Edge, Brave) sits on top of this
+ * component's body, opened with the picked profile, so every site works and
+ * every sign-in is there; its own tabs and address bar are the panel's. The
+ * body underneath only shows while the window is opening, closed or failed.
+ */
+export function NativeBrowserPanel({
+ status,
+ startUrl,
+ onUseBuiltin,
+}: {
+ status: NativeBrowserStatus;
+ startUrl: string | null;
+ onUseBuiltin: () => void;
+}) {
+ const t = useT();
+ const queryClient = useQueryClient();
+ const owner = `panel-${useId()}`;
+ const body = useRef<HTMLDivElement>(null);
+ const [choice, setChoice] = useState<NativeBrowserChoice | null>(() => initialChoice(status.browsers));
+ const [launching, setLaunching] = useState(false);
+ const [failure, setFailure] = useState<string | null>(null);
+ const autoStarted = useRef(false);
+
+ const state = launching ? "launching" : status.state;
+ const shown = state === "embedded"
+ && status.browser === choice?.browser && status.profile === choice?.profile;
+ // Resend the rectangle whenever the backend took a new window.
+ const visible = useNativePlacement(body, owner, `${state}:${status.browser}:${status.profile}`);
+
+ const options = useMemo(() => status.browsers.flatMap((browser) => browser.profiles.map((profile) => ({
+ value: choiceValue({ browser: browser.id, profile: profile.directory }),
+ label: profile.name,
+ hint: profile.email || undefined,
+ // With more than one browser installed, say which one each profile is in.
+ description: status.browsers.length > 1 ? browser.label : undefined,
+ }))), [status.browsers]);
+
+ const launch = useCallback(async (next: NativeBrowserChoice) => {
+ setLaunching(true);
+ setFailure(null);
+ const result = await launchNativeBrowser(next, startUrl);
+ // A newer pick replaced this one; its own answer decides what shows.
+ if (result.reason === "superseded") return;
+ setLaunching(false);
+ if (!result.ok) setFailure(result.reason || "launch_failed");
+ queryClient.setQueryData(NATIVE_BROWSER_STATUS_QUERY, (old: NativeBrowserStatus | undefined) =>
+ old ? { ...old, ...result, browsers: old.browsers } : old);
+ }, [queryClient, startUrl]);
+
+ // Open the window the first time the panel is on screen. A window the user
+ // closed or popped out stays that way until they ask for it again.
+ useEffect(() => {
+ if (!visible || !choice || autoStarted.current) return;
+ autoStarted.current = true;
+ const alreadyThere = status.state === "embedded"
+ && status.browser === choice.browser && status.profile === choice.profile;
+ if (!alreadyThere && (status.state === "idle" || status.state === "embedded" || status.state === "error")) {
+ void launch(choice);
+ }
+ }, [visible, choice, status.state, status.browser, status.profile, launch]);
+
+ const pick = (value: string) => {
+ const next = parseChoice(value);
+ setChoice(next);
+ rememberChoice(next);
+ void launch(next);
+ };
+
+ const popOut = async () => {
+ const result = await releaseNativeBrowser(false);
+ queryClient.setQueryData(NATIVE_BROWSER_STATUS_QUERY, (old: NativeBrowserStatus | undefined) =>
+ old ? { ...old, ...result, browsers: old.browsers } : old);
+ };
+
+ const browserLabel = status.browsers.find((b) => b.id === choice?.browser)?.label ?? "Chrome";
+
+ return (
+ <div data-testid="ide-browser-tab" data-mode="native" className="flex h-full min-h-0 flex-col">
+ <div className="flex h-10 shrink-0 items-center gap-1 border-b border-border/60 px-2">
+ <Globe className="ml-1 h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
+ {choice && (
+ <BrandedSelect
+ value={choiceValue(choice)}
+ options={options}
+ onValueChange={pick}
+ ariaLabel={t("ide_side_panel.browser.native.profile")}
+ testId="ide-browser-profile"
+ className="h-7 min-w-0 max-w-[24rem] flex-1 text-sm"
+ />
+ )}
+ <div className="flex-1" />
+ <button type="button" onClick={() => void popOut()} disabled={!shown}
+ aria-label={t("ide_side_panel.browser.native.pop_out")} title={t("ide_side_panel.browser.native.pop_out")}
+ data-testid="ide-browser-pop-out" className={TOOL_BTN}>
+ <AppWindow className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ </div>
+ <div ref={body} data-testid="ide-browser-native-body"
+ className="relative flex min-h-0 flex-1 flex-col items-center justify-center gap-3 px-6 text-center">
+ {state === "launching" && (
+ <>
+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
+ <p className="text-sm text-foreground">{fill(t("ide_side_panel.browser.native.opening"), { browser: browserLabel })}</p>
+ <p className="max-w-xs text-xs text-muted-foreground">{t("ide_side_panel.browser.native.opening_hint")}</p>
+ </>
+ )}
+ {state !== "launching" && (failure || state === "error") && (
+ <>
+ <p className="text-sm text-foreground">{t("ide_side_panel.browser.native.error_title")}</p>
+ <p className="max-w-xs text-xs text-muted-foreground">
+ {(failure ?? status.reason) === "browser_missing"
+ ? t("ide_side_panel.browser.native.error_missing")
+ : t("ide_side_panel.browser.native.error_generic")}
+ </p>
+ <div className="flex gap-2">
+ {choice && <button type="button" className={LINK_BTN} onClick={() => void launch(choice)}>
+ {t("ide_side_panel.browser.native.retry")}</button>}
+ <button type="button" className={LINK_BTN} onClick={onUseBuiltin}>
+ {t("ide_side_panel.browser.native.builtin")}</button>
+ </div>
+ </>
+ )}
+ {state !== "launching" && !failure && (state === "closed" || state === "released" || (state === "idle" && autoStarted.current)) && (
+ <>
+ <p className="text-sm text-foreground">
+ {state === "released"
+ ? t("ide_side_panel.browser.native.popped_title")
+ : t("ide_side_panel.browser.native.closed_title")}
+ </p>
+ {choice && <button type="button" className={LINK_BTN} data-testid="ide-browser-reopen"
+ onClick={() => void launch(choice)}>{t("ide_side_panel.browser.native.reopen")}</button>}
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/nativeBrowserApi.ts b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/nativeBrowserApi.ts
new file mode 100644
index 0000000000..f59ba7fc40
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/nativeBrowserApi.ts
@@ -0,0 +1,130 @@
+/**
+ * Talks to `/api/ide-browser/*`: the user's own browser shown inside the panel.
+ *
+ * On the Windows desktop app the panel shows a real window of the user's
+ * Chrome (or Edge, Brave), opened with their profile, so every site works and
+ * every sign-in is there. The backend opens the window and keeps it on the
+ * panel's rectangle; see `dodaios/ui/browser_embed.py`.
+ */
+import { useQuery } from "@tanstack/react-query";
+
+import { windowIdentity } from "@/lib/sectionWindows";
+import { useEventStore } from "@/store/events";
+
+export interface NativeBrowserProfile {
+ directory: string;
+ name: string;
+ email: string;
+}
+
+export interface NativeBrowser {
+ id: string;
+ label: string;
+ profiles: NativeBrowserProfile[];
+ last_used: string | null;
+}
+
+/** `released`: handed back as a normal window ("open in its own window"). */
+export type NativeBrowserState = "idle" | "launching" | "embedded" | "closed" | "released" | "error";
+
+export interface NativeBrowserStatus {
+ ok?: boolean;
+ available: boolean;
+ reason: string;
+ state: NativeBrowserState;
+ browser?: string;
+ profile?: string;
+ visible?: boolean;
+ browsers: NativeBrowser[];
+}
+
+export interface NativeBrowserChoice {
+ browser: string;
+ profile: string;
+}
+
+export const NATIVE_BROWSER_STATUS_QUERY = ["ide-browser", "status"] as const;
+
+const UNAVAILABLE: NativeBrowserStatus = {
+ available: false, reason: "request_failed", state: "idle", browsers: [],
+};
+
+async function call(path: string, body?: unknown): Promise<NativeBrowserStatus> {
+ try {
+ const response = await fetch(`/api/ide-browser/${path}`, body === undefined ? undefined : {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ // A hide sent while the page unloads must still arrive.
+ keepalive: true,
+ });
+ if (!response.ok) return UNAVAILABLE;
+ return { browsers: [], reason: "", ...(await response.json()) } as NativeBrowserStatus;
+ } catch {
+ return UNAVAILABLE;
+ }
+}
+
+/** The window this page is shown in: a detached view's id, or null for the main window. */
+export function currentWindowView(): string | null {
+ const { solo, activeSection } = useEventStore.getState();
+ return solo ? windowIdentity(window.location.search, activeSection) : null;
+}
+
+export function useNativeBrowserStatus(enabled: boolean, poll: boolean) {
+ return useQuery({
+ queryKey: NATIVE_BROWSER_STATUS_QUERY,
+ queryFn: () => call("status"),
+ enabled,
+ // The user can close the window or switch tabs in it at any time.
+ refetchInterval: poll ? 1500 : false,
+ staleTime: 1000,
+ });
+}
+
+export function launchNativeBrowser(choice: NativeBrowserChoice, url: string | null) {
+ return call("launch", { ...choice, url, view: currentWindowView() });
+}
+
+export interface PanelPlacement {
+ owner: string;
+ visible: boolean;
+ rect: { x: number; y: number; width: number; height: number } | null;
+ dpr: number;
+}
+
+export function placeNativeBrowser(placement: PanelPlacement) {
+ return call("place", { ...placement, view: currentWindowView() });
+}
+
+export function releaseNativeBrowser(close: boolean) {
+ return call("release", { close });
+}
+
+const CHOICE_KEY = "jarvis.agenticIde.browserProfile.v1";
+
+/** The browser and profile picked last, if it still exists; else the browser's own last profile. */
+export function initialChoice(browsers: NativeBrowser[]): NativeBrowserChoice | null {
+ let stored: NativeBrowserChoice | null = null;
+ try {
+ stored = JSON.parse(localStorage.getItem(CHOICE_KEY) ?? "null") as NativeBrowserChoice | null;
+ } catch {
+ stored = null;
+ }
+ if (stored) {
+ const browser = browsers.find((b) => b.id === stored?.browser);
+ if (browser?.profiles.some((p) => p.directory === stored?.profile)) return stored;
+ }
+ const first = browsers[0];
+ if (!first) return null;
+ const profile = first.last_used ?? first.profiles[0]?.directory;
+ return profile ? { browser: first.id, profile } : null;
+}
+
+export function rememberChoice(choice: NativeBrowserChoice): void {
+ try {
+ localStorage.setItem(CHOICE_KEY, JSON.stringify(choice));
+ } catch {
+ /* a convenience only */
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/useNativePlacement.ts b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/useNativePlacement.ts
new file mode 100644
index 0000000000..f367950cf3
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/useNativePlacement.ts
@@ -0,0 +1,171 @@
+import { useEffect, useRef, useState, type RefObject } from "react";
+
+import { placeNativeBrowser, type PanelPlacement } from "./nativeBrowserApi";
+
+/**
+ * Popups of the app that can open over the panel. The browser is a separate
+ * native window drawn above the page, so it would cover them; while one
+ * overlaps the panel the browser is hidden instead.
+ */
+const OVERLAY_SELECTOR = [
+ '[role="dialog"]',
+ '[role="alertdialog"]',
+ '[role="menu"]',
+ '[role="listbox"]',
+ "[data-radix-popper-content-wrapper]",
+].join(",");
+
+interface Box {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
+
+export function boxesOverlap(a: Box, b: Box): boolean {
+ return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;
+}
+
+/** Whether an app popup (outside `panel`) currently covers part of the panel. */
+export function overlayCovers(panel: HTMLElement, root: ParentNode = document): boolean {
+ const own = panel.getBoundingClientRect();
+ for (const node of Array.from(root.querySelectorAll<HTMLElement>(OVERLAY_SELECTOR))) {
+ if (panel.contains(node) || node.contains(panel)) continue;
+ const box = node.getBoundingClientRect();
+ if (box.width <= 0 || box.height <= 0) continue;
+ if (boxesOverlap(own, box)) return true;
+ }
+ return false;
+}
+
+/** What to tell the backend about `panel` right now. */
+export function measurePanel(panel: HTMLElement | null, owner: string): PanelPlacement {
+ const hidden: PanelPlacement = { owner, visible: false, rect: null, dpr: window.devicePixelRatio || 1 };
+ if (!panel || document.visibilityState === "hidden") return hidden;
+ const box = panel.getBoundingClientRect();
+ // A `hidden` ancestor (another side panel tab, another workspace) gives a 0 box.
+ if (box.width < 2 || box.height < 2) return hidden;
+ if (overlayCovers(panel)) return hidden;
+ return {
+ owner,
+ visible: true,
+ rect: { x: box.x, y: box.y, width: box.width, height: box.height },
+ dpr: window.devicePixelRatio || 1,
+ };
+}
+
+const HEARTBEAT_MS = 1000;
+
+function samePlacement(a: PanelPlacement | null, b: PanelPlacement): boolean {
+ if (!a || a.visible !== b.visible || a.dpr !== b.dpr) return false;
+ if (!a.rect || !b.rect) return a.rect === b.rect;
+ return (
+ Math.round(a.rect.x) === Math.round(b.rect.x)
+ && Math.round(a.rect.y) === Math.round(b.rect.y)
+ && Math.round(a.rect.width) === Math.round(b.rect.width)
+ && Math.round(a.rect.height) === Math.round(b.rect.height)
+ );
+}
+
+/**
+ * Keep the native browser window on `panel`'s rectangle, and hide it whenever
+ * the panel is not on screen. Returns whether the panel is visible.
+ *
+ * Layout changes that move the panel without resizing it (a sidebar folding,
+ * the window being maximized) do not reach a ResizeObserver, so the rectangle
+ * is also checked on a short timer, and right after every click or key press
+ * (which is how app menus open). Only changes are sent, one request at a
+ * time, and only the newest placement waits behind it.
+ */
+export function useNativePlacement(
+ panel: RefObject<HTMLElement | null>,
+ owner: string,
+ generation: unknown,
+): boolean {
+ const [visible, setVisible] = useState(false);
+ const sent = useRef<PanelPlacement | null>(null);
+ const inFlight = useRef(false);
+ const queued = useRef<PanelPlacement | null>(null);
+
+ useEffect(() => {
+ let disposed = false;
+ sent.current = null; // a new generation (window taken, profile switched) resends
+
+ let lastSentAt = 0;
+ const send = (placement: PanelPlacement) => {
+ if (inFlight.current) {
+ queued.current = placement;
+ return;
+ }
+ inFlight.current = true;
+ lastSentAt = Date.now();
+ void placeNativeBrowser(placement).then((result) => {
+ // Remember it only once the backend took it: a lost hide is sent again.
+ sent.current = result.ok ? placement : null;
+ }).finally(() => {
+ inFlight.current = false;
+ const next = queued.current;
+ queued.current = null;
+ if (next && !samePlacement(sent.current, next)) send(next);
+ });
+ };
+
+ const check = () => {
+ if (disposed) return;
+ const placement = measurePanel(panel.current, owner);
+ setVisible(placement.visible);
+ // A shown window is confirmed every second; the backend hides it when the
+ // confirmations stop (the page reloaded or crashed without cleaning up).
+ const heartbeat = placement.visible && Date.now() - lastSentAt > HEARTBEAT_MS;
+ if (heartbeat || !samePlacement(sent.current, placement)) send(placement);
+ };
+
+ let frame = 0;
+ const schedule = () => {
+ if (frame) return;
+ frame = requestAnimationFrame(() => {
+ frame = 0;
+ check();
+ });
+ };
+
+ // Menus and dialogs open from a click or a key: look again right after.
+ const soon = () => {
+ schedule();
+ window.setTimeout(schedule, 60);
+ };
+
+ check();
+ const timer = window.setInterval(check, 250);
+ const resize = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
+ if (panel.current) resize?.observe(panel.current);
+ window.addEventListener("resize", schedule);
+ document.addEventListener("visibilitychange", schedule);
+ document.addEventListener("pointerdown", soon, true);
+ document.addEventListener("keydown", soon, true);
+ return () => {
+ disposed = true;
+ if (frame) cancelAnimationFrame(frame);
+ window.clearInterval(timer);
+ resize?.disconnect();
+ window.removeEventListener("resize", schedule);
+ document.removeEventListener("visibilitychange", schedule);
+ document.removeEventListener("pointerdown", soon, true);
+ document.removeEventListener("keydown", soon, true);
+ };
+ }, [panel, owner, generation]);
+
+ // Leaving the page (tab closed, workspace removed, reload) hides the window.
+ useEffect(() => {
+ const hide = () => {
+ void placeNativeBrowser({ owner, visible: false, rect: null, dpr: window.devicePixelRatio || 1 });
+ };
+ window.addEventListener("pagehide", hide);
+ return () => {
+ window.removeEventListener("pagehide", hide);
+ hide();
+ };
+ }, [owner]);
+
+ return visible;
+}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.json
index b3249a0601..a25f0b173d 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json
@@ -7536,7 +7536,22 @@
"address": "Adresse",
"open_external": "Im Browser öffnen",
"empty_title": "Gib oben eine Adresse ein",
- "empty_hint": "Gedacht für lokale Vorschauen wie einen Dev-Server. Viele öffentliche Seiten erlauben keine Anzeige in einer anderen App; öffne sie in deinem Browser."
+ "empty_hint": "Gedacht für lokale Vorschauen wie einen Dev-Server. Viele öffentliche Seiten erlauben keine Anzeige in einer anderen App; öffne sie in deinem Browser.",
+ "native": {
+ "opening": "{browser} wird geöffnet…",
+ "opening_hint": "Hier öffnet sich dein eigener Browser, angemeldet mit dem gewählten Profil.",
+ "closed_title": "Das Browserfenster wurde geschlossen",
+ "popped_title": "Der Browser läuft jetzt in einem eigenen Fenster",
+ "reopen": "Wieder hier anzeigen",
+ "error_title": "Dein Browser konnte hier nicht angezeigt werden",
+ "error_missing": "Installiere Chrome, Edge oder Brave, um ihn hier zu sehen.",
+ "error_generic": "Versuch es noch einmal oder nutze die eingebaute Ansicht für lokale Vorschauen.",
+ "retry": "Erneut versuchen",
+ "builtin": "Eingebaute Ansicht nutzen",
+ "use_native": "Meinen Browser zeigen",
+ "pop_out": "In eigenem Fenster öffnen",
+ "profile": "Browserprofil"
+ }
},
"all_open": "Alle Tabs sind bereits offen",
"close_tab": "Tab schließen",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.json
index 8b7b53ba5d..1006c1f500 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json
@@ -7536,7 +7536,22 @@
"address": "Address",
"open_external": "Open in your browser",
"empty_title": "Enter an address above",
- "empty_hint": "Made for local previews such as a dev server. Many public sites do not allow being shown inside another app; open those in your browser."
+ "empty_hint": "Made for local previews such as a dev server. Many public sites do not allow being shown inside another app; open those in your browser.",
+ "native": {
+ "opening": "Opening {browser}…",
+ "opening_hint": "Your own browser opens here, signed in with the profile you picked.",
+ "closed_title": "The browser window was closed",
+ "popped_title": "The browser is in its own window now",
+ "reopen": "Show it here again",
+ "error_title": "Your browser could not be shown here",
+ "error_missing": "Install Chrome, Edge or Brave to see it here.",
+ "error_generic": "Try again, or use the built-in view for local previews.",
+ "retry": "Try again",
+ "builtin": "Use the built-in view",
+ "use_native": "Show my browser",
+ "pop_out": "Open in its own window",
+ "profile": "Browser profile"
+ }
},
"all_open": "Every tab is already open",
"close_tab": "Close tab",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.json
index f68d3db563..c484b0cc5c 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json
@@ -7536,7 +7536,22 @@
"address": "Dirección",
"open_external": "Abrir en tu navegador",
"empty_title": "Escribe una dirección arriba",
- "empty_hint": "Pensado para vistas previas locales, como un servidor de desarrollo. Muchos sitios públicos no permiten mostrarse dentro de otra app; ábrelos en tu navegador."
+ "empty_hint": "Pensado para vistas previas locales, como un servidor de desarrollo. Muchos sitios públicos no permiten mostrarse dentro de otra app; ábrelos en tu navegador.",
+ "native": {
+ "opening": "Abriendo {browser}…",
+ "opening_hint": "Aquí se abre tu propio navegador, con la sesión del perfil que elegiste.",
+ "closed_title": "Se cerró la ventana del navegador",
+ "popped_title": "El navegador está ahora en su propia ventana",
+ "reopen": "Mostrarlo aquí otra vez",
+ "error_title": "No se pudo mostrar tu navegador aquí",
+ "error_missing": "Instala Chrome, Edge o Brave para verlo aquí.",
+ "error_generic": "Inténtalo de nuevo o usa la vista integrada para vistas previas locales.",
+ "retry": "Reintentar",
+ "builtin": "Usar la vista integrada",
+ "use_native": "Mostrar mi navegador",
+ "pop_out": "Abrir en su propia ventana",
+ "profile": "Perfil del navegador"
+ }
},
"all_open": "Todas las pestañas ya están abiertas",
"close_tab": "Cerrar pestaña",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
index 6d48f92a9b..a8978f6d81 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
@@ -7536,7 +7536,22 @@
"address": "Endereço",
"open_external": "Abrir no teu navegador",
"empty_title": "Introduz um endereço acima",
- "empty_hint": "Feito para pré-visualizações locais, como um servidor de desenvolvimento. Muitos sites públicos não permitem ser mostrados dentro de outra aplicação; abre-os no teu navegador."
+ "empty_hint": "Feito para pré-visualizações locais, como um servidor de desenvolvimento. Muitos sites públicos não permitem ser mostrados dentro de outra aplicação; abre-os no teu navegador.",
+ "native": {
+ "opening": "Abrindo {browser}…",
+ "opening_hint": "Seu próprio navegador abre aqui, conectado com o perfil escolhido.",
+ "closed_title": "A janela do navegador foi fechada",
+ "popped_title": "O navegador está agora em uma janela própria",
+ "reopen": "Mostrar aqui de novo",
+ "error_title": "Não foi possível mostrar seu navegador aqui",
+ "error_missing": "Instale o Chrome, Edge ou Brave para vê-lo aqui.",
+ "error_generic": "Tente de novo ou use a visualização integrada para prévias locais.",
+ "retry": "Tentar de novo",
+ "builtin": "Usar a visualização integrada",
+ "use_native": "Mostrar meu navegador",
+ "pop_out": "Abrir em janela própria",
+ "profile": "Perfil do navegador"
+ }
},
"all_open": "Todos os separadores já estão abertos",
"close_tab": "Fechar separador",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
index 742e640f43..6dc0dff7df 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
@@ -7536,7 +7536,22 @@
"address": "地址",
"open_external": "在浏览器中打开",
"empty_title": "在上方输入地址",
- "empty_hint": "适用于本地预览,例如开发服务器。许多公共网站不允许在其他应用中显示;请在浏览器中打开它们。"
+ "empty_hint": "适用于本地预览,例如开发服务器。许多公共网站不允许在其他应用中显示;请在浏览器中打开它们。",
+ "native": {
+ "opening": "正在打开 {browser}…",
+ "opening_hint": "你自己的浏览器会在这里打开,并使用你选择的配置文件登录。",
+ "closed_title": "浏览器窗口已关闭",
+ "popped_title": "浏览器现在在单独的窗口中",
+ "reopen": "在这里重新显示",
+ "error_title": "无法在这里显示你的浏览器",
+ "error_missing": "安装 Chrome、Edge 或 Brave 后即可在这里查看。",
+ "error_generic": "请重试,或使用内置视图查看本地预览。",
+ "retry": "重试",
+ "builtin": "使用内置视图",
+ "use_native": "显示我的浏览器",
+ "pop_out": "在单独窗口中打开",
+ "profile": "浏览器配置文件"
+ }
},
"all_open": "所有标签页都已打开",
"close_tab": "关闭标签页",
diff --git a/dodaios/ui/web/ide_browser_routes.py b/dodaios/ui/web/ide_browser_routes.py
new file mode 100644
index 0000000000..67529fa882
--- /dev/null
+++ b/dodaios/ui/web/ide_browser_routes.py
@@ -0,0 +1,131 @@
+"""REST API for the Agentic IDE's browser panel: the user's own browser inside the app.
+
+The panel shows a real window of the user's installed Chrome (or Edge, Brave),
+opened with the profile they pick, so every site works and every sign-in is
+there (see ``dodaios.ui.browser_embed``). The page drives it through these routes:
+
+ GET /api/ide-browser/status installed browsers, their profiles, window state
+ POST /api/ide-browser/launch {browser, profile, url?, view?} open + take a window
+ POST /api/ide-browser/place {owner, visible, rect?, dpr?, view?} follow the panel
+ POST /api/ide-browser/release {close} close it, or hand it back as a normal window
+
+Only the Windows desktop shell can do this. Anywhere else (a browser tab, a
+headless server, macOS, Linux) ``status`` answers ``available: false`` with a
+reason and the panel keeps its built-in page view. ``view`` names a detached
+window, as for ``/api/window/zoom``; omitted, the main window is used.
+
+Every native call is thread-hopped off the event loop.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Any
+
+from fastapi import APIRouter, Request
+from pydantic import BaseModel, Field
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/ide-browser", tags=["ide-browser"])
+
+
+class LaunchBody(BaseModel):
+ browser: str = Field(min_length=1, max_length=32)
+ profile: str = Field(min_length=1, max_length=64)
+ url: str | None = Field(default=None, max_length=4096)
+ view: str | None = Field(default=None, max_length=64)
+
+
+class PanelRect(BaseModel):
+ x: float = Field(ge=-100_000, le=100_000)
+ y: float = Field(ge=-100_000, le=100_000)
+ width: float = Field(ge=0, le=100_000)
+ height: float = Field(ge=0, le=100_000)
+
+
+class PlaceBody(BaseModel):
+ owner: str = Field(min_length=1, max_length=64)
+ visible: bool
+ rect: PanelRect | None = None
+ dpr: float = Field(default=1.0, gt=0, le=16)
+ view: str | None = Field(default=None, max_length=64)
+
+
+class ReleaseBody(BaseModel):
+ close: bool = True
+
+
+def _host(request: Request, view: str | None) -> int | None:
+ desktop = getattr(request.app.state, "desktop_app", None)
+ lookup = getattr(desktop, "browser_panel_host", None)
+ if not callable(lookup):
+ return None
+ return lookup(view or None)
+
+
+def _unavailable(reason: str) -> dict[str, Any]:
+ return {"ok": False, "available": False, "reason": reason, "browsers": [], "state": "idle"}
+
+
[email protected]("/status", operation_id="status")
+async def ide_browser_status(request: Request) -> dict[str, Any]:
+ """Which browsers and profiles the panel can show, and the window's state."""
+ from dodaios.ui.browser_embed import get_embed
+ from dodaios.ui.browser_profiles import installed_browsers
+
+ embed = get_embed()
+ if not embed.supported():
+ return _unavailable("unsupported_platform")
+ if not callable(getattr(getattr(request.app.state, "desktop_app", None),
+ "browser_panel_host", None)):
+ return _unavailable("no_desktop_shell")
+ browsers = await asyncio.to_thread(installed_browsers)
+ if not browsers:
+ return _unavailable("no_browser")
+ state = await asyncio.to_thread(embed.status)
+ return {**state, "ok": True, "available": True, "browsers": browsers}
+
+
+# Opening and closing the user's own browser windows: the CLI asks for --yes.
[email protected]("/launch", operation_id="launch", openapi_extra={"x-jarvis-dangerous": True})
+async def ide_browser_launch(body: LaunchBody, request: Request) -> dict[str, Any]:
+ """Open a window of the chosen browser and profile inside the app window."""
+ from dodaios.ui.browser_embed import get_embed
+
+ host = await asyncio.to_thread(_host, request, body.view)
+ if not host:
+ return _unavailable("no_desktop_shell")
+ embed = get_embed()
+ return await asyncio.to_thread(embed.launch, body.browser, body.profile, body.url, host)
+
+
[email protected]("/place", operation_id="place")
+async def ide_browser_place(body: PlaceBody, request: Request) -> dict[str, Any]:
+ """Keep the browser window on the panel's rectangle, or hide it with the panel."""
+ from dodaios.ui.browser_embed import get_embed
+
+ host = await asyncio.to_thread(_host, request, body.view)
+ if not host:
+ return _unavailable("no_desktop_shell")
+ rect = body.rect.model_dump() if body.rect is not None else None
+ embed = get_embed()
+ try:
+ return await asyncio.to_thread(
+ embed.place, body.owner, host, rect, body.dpr, body.visible,
+ )
+ except Exception as exc: # noqa: BLE001 - reported to the page, logged here
+ log.warning("Browser panel place failed: %s", exc, exc_info=True)
+ return {**embed.status(), "ok": False, "reason": "place_failed"}
+
+
[email protected]("/release", operation_id="release", openapi_extra={"x-jarvis-dangerous": True})
+async def ide_browser_release(body: ReleaseBody) -> dict[str, Any]:
+ """Close the panel's browser window, or hand it back as a normal browser window."""
+ from dodaios.ui.browser_embed import get_embed
+
+ embed = get_embed()
+ if not embed.supported():
+ return _unavailable("unsupported_platform")
+ return await asyncio.to_thread(embed.release, close=body.close, focus=not body.close)
diff --git a/dodaios/ui/web/server.py b/dodaios/ui/web/server.py
index 1f453e716e..9dd438d4e3 100644
--- a/dodaios/ui/web/server.py
+++ b/dodaios/ui/web/server.py
@@ -532,6 +532,7 @@ class WebServer:
from .friends_routes import router as friends_router
from .frontier_routes import router as frontier_router
from .grok_build_routes import router as grok_build_router
+ from .ide_browser_routes import router as ide_browser_router
from .ide_skills_routes import router as ide_skills_router
from .jarvisx_routes import router as jarvisx_router
from .live_routes import router as live_router
@@ -642,6 +643,7 @@ class WebServer:
# Detachable views: the desktop shell (when attached) spawns/closes
# solo windows; headless hosts answer honestly with a fallback URL.
app.include_router(desktop_router)
+ app.include_router(ide_browser_router)
app.include_router(profile_router)
app.include_router(settings_router)
app.include_router(soul_router)
diff --git a/tests/unit/ui/test_browser_profiles.py b/tests/unit/ui/test_browser_profiles.py
new file mode 100644
index 0000000000..1c9ab688d5
--- /dev/null
+++ b/tests/unit/ui/test_browser_profiles.py
@@ -0,0 +1,165 @@
+"""The IDE browser panel's browser discovery, profile list, window marker and geometry."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from urllib.parse import unquote
+
+import pytest
+
+from dodaios.ui import browser_profiles as cp
+
+
+def _install(root: Path, relpath: str) -> None:
+ exe = root / relpath
+ exe.parent.mkdir(parents=True, exist_ok=True)
+ exe.write_bytes(b"")
+
+
+def _local_state(user_data: Path, profile: dict) -> None:
+ user_data.mkdir(parents=True, exist_ok=True)
+ (user_data / "Local State").write_text(json.dumps({"profile": profile}), encoding="utf-8")
+
+
+def env(tmp_path: Path) -> dict[str, str]:
+ return {
+ "PROGRAMFILES": str(tmp_path / "pf"),
+ "PROGRAMFILES(X86)": str(tmp_path / "pf86"),
+ "LOCALAPPDATA": str(tmp_path / "local"),
+ }
+
+
+def test_profiles_keep_the_pickers_order_and_skip_hidden_ones(tmp_path: Path) -> None:
+ user_data = tmp_path / "User Data"
+ _local_state(user_data, {
+ "info_cache": {
+ "Default": {"name": "Work", "user_name": "[email protected]"},
+ "Profile 2": {"name": "Home", "user_name": ""},
+ "Profile 9": {"name": "Gone", "is_omitted_from_profile_list": True},
+ "Guest Profile": {"name": "Guest", "is_ephemeral": True},
+ },
+ "profiles_order": ["Profile 2", "Default"],
+ "last_used": "Default",
+ })
+ profiles, last_used = cp.read_profiles(user_data)
+ assert [p.directory for p in profiles] == ["Profile 2", "Default"]
+ assert profiles[1].email == "[email protected]"
+ assert last_used == "Default"
+
+
+def test_profiles_without_an_order_are_sorted_and_last_used_falls_back(tmp_path: Path) -> None:
+ user_data = tmp_path / "User Data"
+ _local_state(user_data, {
+ "info_cache": {"Profile 3": {"name": "beta"}, "Profile 1": {"name": "Alpha"}},
+ "last_used": "Profile 99",
+ })
+ profiles, last_used = cp.read_profiles(user_data)
+ assert [p.name for p in profiles] == ["Alpha", "beta"]
+ assert last_used == "Profile 1"
+
+
[email protected]("content", ["not json", json.dumps([1, 2]), json.dumps({"profile": 3})])
+def test_a_broken_local_state_gives_no_profiles(tmp_path: Path, content: str) -> None:
+ user_data = tmp_path / "User Data"
+ user_data.mkdir()
+ (user_data / "Local State").write_text(content, encoding="utf-8")
+ assert cp.read_profiles(user_data) == ([], None)
+
+
+def test_missing_local_state_gives_no_profiles(tmp_path: Path) -> None:
+ assert cp.read_profiles(tmp_path / "nothing") == ([], None)
+ assert cp.read_profiles(None) == ([], None)
+
+
+def test_installed_browsers_lists_only_installed_ones_with_profiles(env: dict[str, str]) -> None:
+ _install(Path(env["PROGRAMFILES"]), r"Google\Chrome\Application\chrome.exe")
+ _install(Path(env["LOCALAPPDATA"]), r"BraveSoftware\Brave-Browser\Application\brave.exe")
+ _local_state(Path(env["LOCALAPPDATA"]) / r"Google\Chrome\User Data", {
+ "info_cache": {"Profile 3": {"name": "Profil 1", "user_name": "[email protected]"}},
+ "last_used": "Profile 3",
+ })
+ found = cp.installed_browsers(env)
+ assert [b["id"] for b in found] == ["chrome", "brave"]
+ assert found[0]["profiles"] == [
+ {"directory": "Profile 3", "name": "Profil 1", "email": "[email protected]"},
+ ]
+ assert found[0]["last_used"] == "Profile 3"
+ # A browser that never ran still offers its default profile.
+ assert found[1]["profiles"][0]["directory"] == "Default"
+ assert found[1]["last_used"] == "Default"
+
+
+def test_no_browser_installed(env: dict[str, str]) -> None:
+ assert cp.installed_browsers(env) == []
+
+
+def test_image_name_is_the_exe_file_name() -> None:
+ assert cp.browser_by_id("chrome").image_name == "chrome.exe" # type: ignore[union-attr]
+ assert cp.browser_by_id("edge").image_name == "msedge.exe" # type: ignore[union-attr]
+ assert cp.browser_by_id("nope") is None
+
+
[email protected](("value", "ok"), [
+ ("Default", True),
+ ("Profile 12", True),
+ ("Guest Profile", True),
+ ("--user-data-dir=x", False),
+ ("..\\..\\Windows", False),
+ ("a/b", False),
+ ("", False),
+ ("Default\n", False),
+ (".", False),
+ ("Profile 1.", False),
+ (" Default", False),
+])
+def test_profile_dir_names(value: str, ok: bool) -> None:
+ assert cp.is_profile_dir(value) is ok
+
+
[email protected](("url", "expected"), [
+ ("https://github.com/", "https://github.com/"),
+ (" http://localhost:5173/x ", "http://localhost:5173/x"),
+ ("javascript:alert(1)", cp.DEFAULT_START_URL),
+ ("file:///C:/secret.txt", cp.DEFAULT_START_URL),
+ ("chrome://settings", cp.DEFAULT_START_URL),
+ ("", cp.DEFAULT_START_URL),
+ (None, cp.DEFAULT_START_URL),
+])
+def test_start_url_is_a_web_address(url: str | None, expected: str) -> None:
+ assert cp.safe_start_url(url) == expected
+
+
+def test_handoff_page_is_titled_with_the_token_and_forwards() -> None:
+ token = cp.new_token()
+ assert cp.is_token(token)
+ url = cp.handoff_url(token, "https://example.com/?a=1&b=</script>")
+ assert url.startswith("data:text/html;charset=utf-8,")
+ html = unquote(url.split(",", 1)[1])
+ assert f"<title>{token}</title>" in html
+ assert "location.replace" in html
+ # The address cannot close the script tag it is written into.
+ assert "</script>\"" not in html
+ assert "\\u003c/script>" in html
+
+
+def test_handoff_rejects_a_bad_token() -> None:
+ with pytest.raises(ValueError):
+ cp.handoff_url("<title>", "https://example.com")
+
+
+def test_panel_rect_scales_and_offsets() -> None:
+ rect = {"x": 100.4, "y": 50.0, "width": 300.0, "height": 200.5}
+ assert cp.panel_to_client_rect(rect, 1.5, (8, 0)) == (159, 75, 450, 301)
+
+
+def test_touching_panels_stay_touching() -> None:
+ left = cp.panel_to_client_rect({"x": 0, "y": 0, "width": 100.3, "height": 10}, 1.25, (0, 0))
+ right = cp.panel_to_client_rect({"x": 100.3, "y": 0, "width": 50, "height": 10}, 1.25, (0, 0))
+ assert left[0] + left[2] == right[0]
+
+
+def test_panel_rect_never_negative() -> None:
+ rect = {"x": 5, "y": 5, "width": -3, "height": 0}
+ assert cp.panel_to_client_rect(rect, 0, (0, 0))[2:] == (0, 0)
diff --git a/tests/unit/ui/test_ide_browser_routes.py b/tests/unit/ui/test_ide_browser_routes.py
new file mode 100644
index 0000000000..c31b988ebe
--- /dev/null
+++ b/tests/unit/ui/test_ide_browser_routes.py
@@ -0,0 +1,167 @@
+"""REST routes of the IDE browser panel: honest answers without a desktop shell."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from dodaios.ui import browser_embed
+from dodaios.ui.web.ide_browser_routes import router
+
+
+class FakeEmbed:
+ def __init__(self, supported: bool = True) -> None:
+ self._supported = supported
+ self.calls: list[tuple[str, Any]] = []
+
+ def supported(self) -> bool:
+ return self._supported
+
+ def status(self) -> dict[str, Any]:
+ return {"available": self._supported, "state": "idle", "reason": "",
+ "browser": "", "profile": "", "visible": False}
+
+ def launch(self, browser: str, profile: str, url: str | None, host: int) -> dict[str, Any]:
+ self.calls.append(("launch", (browser, profile, url, host)))
+ return {**self.status(), "ok": True, "state": "embedded"}
+
+ def place(self, owner: str, host: int, rect: Any, dpr: float, visible: bool) -> dict[str, Any]:
+ self.calls.append(("place", (owner, host, rect, dpr, visible)))
+ return {**self.status(), "ok": True}
+
+ def release(self, *, close: bool, focus: bool = False) -> dict[str, Any]:
+ self.calls.append(("release", (close, focus)))
+ return {**self.status(), "ok": True}
+
+
+def _client(desktop: Any, embed: FakeEmbed, monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ monkeypatch.setattr(browser_embed, "get_embed", lambda: embed)
+ app = FastAPI()
+ app.include_router(router)
+ app.state.desktop_app = desktop
+ return TestClient(app)
+
+
+def _desktop(hwnd: int | None = 4242) -> SimpleNamespace:
+ seen: list[str | None] = []
+
+ def host(view: str | None) -> int | None:
+ seen.append(view)
+ return hwnd
+
+ return SimpleNamespace(browser_panel_host=host, seen=seen)
+
+
+def test_status_without_a_desktop_shell(monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _client(None, FakeEmbed(), monkeypatch)
+ body = client.get("/api/ide-browser/status").json()
+ assert body["available"] is False
+ assert body["reason"] == "no_desktop_shell"
+
+
+def test_status_off_windows(monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _client(_desktop(), FakeEmbed(supported=False), monkeypatch)
+ body = client.get("/api/ide-browser/status").json()
+ assert body == {**body, "available": False, "reason": "unsupported_platform"}
+
+
+def test_status_without_a_browser(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("dodaios.ui.browser_profiles.installed_browsers", lambda: [])
+ client = _client(_desktop(), FakeEmbed(), monkeypatch)
+ assert client.get("/api/ide-browser/status").json()["reason"] == "no_browser"
+
+
+def test_status_lists_browsers(monkeypatch: pytest.MonkeyPatch) -> None:
+ browsers = [{"id": "chrome", "label": "Google Chrome", "profiles": [], "last_used": None}]
+ monkeypatch.setattr("dodaios.ui.browser_profiles.installed_browsers", lambda: browsers)
+ client = _client(_desktop(), FakeEmbed(), monkeypatch)
+ body = client.get("/api/ide-browser/status").json()
+ assert body["available"] is True
+ assert body["browsers"] == browsers
+
+
+def test_launch_targets_the_window_of_the_view(monkeypatch: pytest.MonkeyPatch) -> None:
+ desktop, embed = _desktop(), FakeEmbed()
+ client = _client(desktop, embed, monkeypatch)
+ body = client.post("/api/ide-browser/launch", json={
+ "browser": "chrome", "profile": "Profile 3",
+ "url": "https://github.com/", "view": "agentic-ide",
+ }).json()
+ assert body["ok"] is True
+ assert desktop.seen == ["agentic-ide"]
+ assert embed.calls == [("launch", ("chrome", "Profile 3", "https://github.com/", 4242))]
+
+
+def test_launch_without_a_window(monkeypatch: pytest.MonkeyPatch) -> None:
+ embed = FakeEmbed()
+ client = _client(_desktop(hwnd=None), embed, monkeypatch)
+ payload = {"browser": "chrome", "profile": "Default"}
+ body = client.post("/api/ide-browser/launch", json=payload).json()
+ assert body["ok"] is False
+ assert embed.calls == []
+
+
+def test_place_passes_the_rectangle(monkeypatch: pytest.MonkeyPatch) -> None:
+ desktop, embed = _desktop(), FakeEmbed()
+ client = _client(desktop, embed, monkeypatch)
+ client.post("/api/ide-browser/place", json={
+ "owner": "panel-1", "visible": True, "dpr": 1.5,
+ "rect": {"x": 10, "y": 20, "width": 300, "height": 400},
+ })
+ assert embed.calls == [("place", (
+ "panel-1", 4242, {"x": 10.0, "y": 20.0, "width": 300.0, "height": 400.0}, 1.5, True,
+ ))]
+ assert desktop.seen == [None]
+
+
+def test_place_rejects_a_bad_ratio(monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _client(_desktop(), FakeEmbed(), monkeypatch)
+ response = client.post("/api/ide-browser/place", json={"owner": "p", "visible": True, "dpr": 0})
+ assert response.status_code == 422
+
+
[email protected](("close", "focus"), [(True, False), (False, True)])
+def test_release(monkeypatch: pytest.MonkeyPatch, close: bool, focus: bool) -> None:
+ embed = FakeEmbed()
+ client = _client(_desktop(), embed, monkeypatch)
+ client.post("/api/ide-browser/release", json={"close": close})
+ assert embed.calls == [("release", (close, focus))]
+
+
+def test_embed_refuses_off_windows(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(browser_embed, "_is_windows", lambda: False)
+ embed = browser_embed.ChromeEmbed()
+ result = embed.launch("chrome", "Default", None, 1)
+ assert result["ok"] is False
+ assert result["reason"] == "unsupported"
+ assert embed.place("p", 1, None, 1.0, True)["ok"] is False
+
+
+def test_embed_rejects_bad_input_before_starting_anything(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(browser_embed, "_is_windows", lambda: True)
+ # A browser that never ran lists no profiles: only its Default may open.
+ monkeypatch.setattr(browser_embed, "read_profiles", lambda _user_data: ([], None))
+ embed = browser_embed.ChromeEmbed()
+ assert embed.launch("netscape", "Default", None, 1)["reason"] == "unknown_browser"
+ assert embed.launch("chrome", "Profile 5", None, 1)["reason"] == "bad_profile"
+ assert embed.launch("chrome", "--user-data-dir=x", None, 1)["reason"] == "bad_profile"
+ monkeypatch.setattr(browser_embed, "read_profiles", lambda _dir: ([], None))
+ # Without a profile list only the default profile may be opened.
+ assert embed.launch("chrome", "Profile 5", None, 1)["reason"] == "bad_profile"
+ monkeypatch.setattr(browser_embed, "find_browser_exe", lambda spec: None)
+ assert embed.launch("chrome", "Default", None, 1)["reason"] == "browser_missing"
+ assert embed._thread is None
+
+
+def test_embed_refuses_to_launch_after_shutdown(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(browser_embed, "_is_windows", lambda: True)
+ monkeypatch.setattr(browser_embed, "read_profiles", lambda _dir: ([], None))
+ monkeypatch.setattr(browser_embed, "find_browser_exe", lambda spec: "chrome.exe")
+ embed = browser_embed.ChromeEmbed()
+ embed.shutdown()
+ assert embed.launch("chrome", "Default", None, 1)["reason"] == "shutting_down"
+ assert embed._thread is None