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.

fix(ide): browser panel follows every frame, no flicker on app focus, survives a hard restart (#771)

Ruben Lütkec9df04a19dcb
diff --git a/dodaios/ui/browser_embed.py b/dodaios/ui/browser_embed.py
index 2bbab73c83..22d42be81a 100644
--- a/dodaios/ui/browser_embed.py
+++ b/dodaios/ui/browser_embed.py
@@ -38,6 +38,7 @@ the browser's last active one.
from __future__ import annotations
import ctypes
+import json
import logging
import os
import queue
@@ -80,6 +81,8 @@ WATCH_INTERVAL_MS = 200
CALL_TIMEOUT_S = 5.0
#: How long a visible placement holds without the page confirming it.
LEASE_S = 3.0
+#: Where the window in use is remembered, so a restarted app takes it back.
+STATE_FILE_NAME = "ide_browser_window.json"
_WINDOW_CLASS = "Chrome_WidgetWin_1"
@@ -100,6 +103,7 @@ WS_CLIPSIBLINGS = 0x04000000
WS_CLIPCHILDREN = 0x02000000
WS_EX_APPWINDOW = 0x00040000
WS_EX_TOOLWINDOW = 0x00000080
+WS_EX_TOPMOST = 0x00000008
SWP_NOSIZE = 0x0001
SWP_NOMOVE = 0x0002
SWP_NOZORDER = 0x0004
@@ -305,6 +309,8 @@ class ChromeEmbed:
self._event_proc: Any = None
self._syncing = False
self._clip_key: tuple[int, ...] | None = None
+ #: Whether the browser window is on screen over the panel right now.
+ self._shown = False
self._state = "idle"
self._reason = ""
self._browser = ""
@@ -362,6 +368,11 @@ class ChromeEmbed:
if alive and same:
self._call(lambda: self._set_host(host))
return {**self.status(), "ok": True}
+ if not alive:
+ self._ensure_thread()
+ adopted = self._call(lambda: self._adopt_left_over(spec, profile, host))
+ if adopted:
+ return {**self.status(), "ok": True}
if alive:
self.release(close=True)
self._ensure_thread()
@@ -471,6 +482,102 @@ class ChromeEmbed:
api.user32.PostThreadMessageW(self._thread_id, WM_QUIT, 0, 0)
thread.join(1.0)
+ # -- a window left by the previous app run ---------------------------------
+
+ @staticmethod
+ def _state_path() -> Path | None:
+ try:
+ from dodaios.core.config import DATA_DIR # noqa: PLC0415
+ except Exception: # noqa: BLE001 - without a data folder nothing is remembered
+ return None
+ return Path(DATA_DIR) / STATE_FILE_NAME
+
+ def _remember(self) -> None:
+ """Write down the window in use, with what it looked like before it was taken."""
+ path, saved = self._state_path(), self._saved
+ if path is None or saved is None or not self._chrome:
+ return
+ placement = saved.placement
+ rect = placement.rcNormalPosition
+ record = {
+ "hwnd": int(self._chrome), "pid": int(self._chrome_pid),
+ "browser": self._browser, "profile": self._profile,
+ "style": int(saved.style), "exstyle": int(saved.exstyle),
+ "show": int(placement.showCmd),
+ "normal": [rect.left, rect.top, rect.right, rect.bottom],
+ }
+ try:
+ path.write_text(json.dumps(record), encoding="utf-8")
+ except OSError as exc:
+ logger.debug("Browser panel window not remembered: %s", exc)
+
+ def _forget(self) -> None:
+ path = self._state_path()
+ if path is not None:
+ try:
+ path.unlink(missing_ok=True)
+ except OSError as exc:
+ logger.debug("Browser panel window record not removed: %s", exc)
+
+ def _left_over(self, spec: BrowserSpec) -> dict[str, Any] | None:
+ """The remembered window, if it is still that browser's window in panel style."""
+ path = self._state_path()
+ if path is None or not path.is_file():
+ return None
+ try:
+ record = json.loads(path.read_text(encoding="utf-8"))
+ hwnd, pid = int(record["hwnd"]), int(record["pid"])
+ except (OSError, ValueError, KeyError, TypeError) as exc:
+ logger.info("Browser panel window record unreadable, dropped: %s", exc)
+ self._forget()
+ return None
+ api = self._load_api()
+ user32 = api.user32
+ ok = (
+ user32.IsWindow(hwnd) and api.pid(hwnd) == pid
+ and api.class_name(hwnd) == _WINDOW_CLASS
+ and api.image_name(hwnd) == spec.image_name
+ and int(user32.GetWindowLongPtrW(hwnd, GWL_EXSTYLE)) & WS_EX_TOOLWINDOW
+ )
+ if not ok:
+ self._forget()
+ return None
+ return record
+
+ def _adopt_left_over(self, spec: BrowserSpec, profile: str, host: int) -> bool:
+ """Take back the window a hard-stopped app left on screen, tabs and all.
+
+ A window of another profile is handed back to the desktop instead.
+ """
+ record = self._left_over(spec)
+ if record is None:
+ return False
+ api = self._load_api()
+ placement = api.WINDOWPLACEMENT()
+ placement.length = ctypes.sizeof(api.WINDOWPLACEMENT)
+ api.user32.GetWindowPlacement(int(record["hwnd"]), ctypes.byref(placement))
+ placement.showCmd = int(record.get("show", SW_SHOWNORMAL))
+ left, top, right, bottom = (int(v) for v in record.get("normal", [0, 0, 800, 600]))
+ rect = placement.rcNormalPosition
+ rect.left, rect.top, rect.right, rect.bottom = left, top, right, bottom
+ saved = _Saved(int(record["style"]), int(record["exstyle"]), placement)
+ with self._lock:
+ self._chrome = int(record["hwnd"])
+ self._chrome_pid = int(record["pid"])
+ self._saved = saved
+ self._browser = str(record.get("browser", spec.id))
+ self._profile = str(record.get("profile", ""))
+ self._host = host or self._host
+ self._clip_key = None
+ self._state, self._reason = "embedded", ""
+ if self._profile != profile:
+ self._give_back(close=True, focus=False)
+ return False
+ self._hook_browser_events()
+ self._sync()
+ logger.info("Browser panel took back the window of the previous run")
+ return True
+
# -- launching (caller thread) ----------------------------------------------
def _fail(self, reason: str) -> dict[str, Any]:
@@ -609,8 +716,37 @@ class ChromeEmbed:
# -- window events (delivered on the embed thread) ---------------------------
+ def zorder_anchor(self, host: int) -> int | None:
+ """The browser window when it is shown over ``host``: the app window stays under it.
+
+ Called from the app window's own window procedure (see
+ ``window_frame.set_zorder_anchor``), so it only reads plain fields.
+ """
+ chrome, api = self._chrome, self._api
+ if not chrome or api is None or host != self._host or not self._shown:
+ return None
+ # Only when nothing else lies above the browser window: otherwise the app
+ # would come up under another program instead of to the front.
+ user32 = api.user32
+ window = user32.GetWindow(chrome, GW_HWNDPREV)
+ for _ in range(256):
+ if not window:
+ return chrome
+ if user32.IsWindowVisible(window) and not (
+ int(user32.GetWindowLongPtrW(window, GWL_EXSTYLE)) & WS_EX_TOPMOST
+ ):
+ return None
+ window = user32.GetWindow(window, GW_HWNDPREV)
+ return None
+
def _hook_app_events(self, api: _Api) -> None:
"""Follow the app: front, minimize and restore, move and resize, show and hide."""
+ try:
+ from dodaios.ui.window_frame import set_zorder_anchor # noqa: PLC0415
+
+ set_zorder_anchor(self.zorder_anchor)
+ except Exception: # noqa: BLE001 - without it the window is raised after the app
+ logger.debug("Browser panel z-order anchor not installed", exc_info=True)
self._event_proc = api.WINEVENTPROC(self._on_event)
own = os.getpid()
for low, high, pid in (
@@ -709,6 +845,7 @@ class ChromeEmbed:
self._clip_key = None
self._state, self._reason = "embedded", ""
self._hook_browser_events()
+ self._remember()
self._sync()
logger.info("Browser panel took a %s window", self._browser)
@@ -771,6 +908,7 @@ class ChromeEmbed:
self._syncing = True
try:
if not self._should_show() or self._page_rect is None:
+ self._shown = False
if user32.IsWindowVisible(hwnd):
user32.ShowWindow(hwnd, SW_HIDE)
return
@@ -789,6 +927,7 @@ class ChromeEmbed:
if after is None:
flags |= SWP_NOZORDER
user32.SetWindowPos(hwnd, after, *want, flags)
+ self._shown = True
# The browser keeps an invisible resize border around its page; cut
# the window to the page so that border cannot catch the app's clicks.
self._clip(want[2], want[3], (left, top, right, bottom))
@@ -868,6 +1007,8 @@ class ChromeEmbed:
logger.debug("Browser panel watchdog tick failed", exc_info=True)
def _lost(self, state: str) -> None:
+ self._forget()
+ self._shown = False
self._chrome = 0
self._chrome_pid = 0
self._saved = None
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
index f367950cf3..b49d55360e 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/useNativePlacement.ts
+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/browser/useNativePlacement.ts
@@ -38,14 +38,21 @@ export function overlayCovers(panel: HTMLElement, root: ParentNode = document):
return false;
}
-/** What to tell the backend about `panel` right now. */
-export function measurePanel(panel: HTMLElement | null, owner: string): PanelPlacement {
+/**
+ * What to tell the backend about `panel` right now. `covered` passes the popup
+ * scan's answer in when it is already known (the scan runs less often).
+ */
+export function measurePanel(
+ panel: HTMLElement | null,
+ owner: string,
+ covered?: boolean,
+): 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;
+ if (covered ?? overlayCovers(panel)) return hidden;
return {
owner,
visible: true,
@@ -55,6 +62,8 @@ export function measurePanel(panel: HTMLElement | null, owner: string): PanelPla
}
const HEARTBEAT_MS = 1000;
+const OVERLAY_SCAN_MS = 100;
+const HIDDEN_CHECK_MS = 250;
function samePlacement(a: PanelPlacement | null, b: PanelPlacement): boolean {
if (!a || a.visible !== b.visible || a.dpr !== b.dpr) return false;
@@ -71,10 +80,12 @@ function samePlacement(a: PanelPlacement | null, b: PanelPlacement): boolean {
* 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
+ * The rectangle is read on every animation frame while the panel is on screen,
+ * so the browser window follows a dragged panel edge or a layout animation
+ * frame by frame (a ResizeObserver misses moves without a resize). The scan
+ * for app popups over the panel is heavier: it runs every 100 ms, and at once
+ * after a click or key press (which is how app menus open). While the panel is
+ * hidden it is checked every 250 ms. Only changes are sent, one request at a
* time, and only the newest placement waits behind it.
*/
export function useNativePlacement(
@@ -110,46 +121,59 @@ export function useNativePlacement(
});
};
- const check = () => {
- if (disposed) return;
- const placement = measurePanel(panel.current, owner);
+ let covered = false;
+ let coveredAt = 0;
+ let forceScan = true;
+ const check = (): boolean => {
+ const now = performance.now();
+ if (forceScan || now - coveredAt > OVERLAY_SCAN_MS) {
+ covered = panel.current ? overlayCovers(panel.current) : false;
+ coveredAt = now;
+ forceScan = false;
+ }
+ const placement = measurePanel(panel.current, owner, covered);
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);
+ return placement.visible;
};
+ // Every frame while shown; a slow timer while hidden.
let frame = 0;
- const schedule = () => {
- if (frame) return;
- frame = requestAnimationFrame(() => {
- frame = 0;
- check();
- });
+ let idle = 0;
+ const tick = () => {
+ frame = 0;
+ idle = 0;
+ if (disposed) return;
+ if (check()) frame = requestAnimationFrame(tick);
+ else idle = window.setTimeout(tick, HIDDEN_CHECK_MS);
+ };
+ const wake = () => {
+ forceScan = true;
+ if (frame || disposed) return;
+ window.clearTimeout(idle);
+ frame = requestAnimationFrame(tick);
};
// Menus and dialogs open from a click or a key: look again right after.
const soon = () => {
- schedule();
- window.setTimeout(schedule, 60);
+ wake();
+ window.setTimeout(wake, 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);
+ tick();
+ window.addEventListener("resize", wake);
+ document.addEventListener("visibilitychange", wake);
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);
+ window.clearTimeout(idle);
+ window.removeEventListener("resize", wake);
+ document.removeEventListener("visibilitychange", wake);
document.removeEventListener("pointerdown", soon, true);
document.removeEventListener("keydown", soon, true);
};
diff --git a/dodaios/ui/window_frame.py b/dodaios/ui/window_frame.py
index a7fe4df357..1ebb08b752 100644
--- a/dodaios/ui/window_frame.py
+++ b/dodaios/ui/window_frame.py
@@ -37,6 +37,7 @@ __all__ = [
"install_resize_frame",
"maximized_bounds",
"native_hwnd",
+ "set_zorder_anchor",
"window_is_maximized",
]
@@ -51,6 +52,9 @@ _HTBOTTOMLEFT = 16
_HTBOTTOMRIGHT = 17
_WM_GETMINMAXINFO = 0x0024
+_WM_WINDOWPOSCHANGING = 0x0046
+_SWP_NOZORDER = 0x0004
+_HWND_TOP = 0
_WM_NCCALCSIZE = 0x0083
_WM_NCHITTEST = 0x0084
@@ -83,6 +87,23 @@ _api_lock = threading.Lock()
_api: _Win32 | None = None
_pinned: dict[int, _PinnedSubclass] = {}
+#: Answers, for a window of the app, the native window that must stay directly
+#: above it (the IDE browser panel's own browser window), or None.
+ZOrderAnchor = Callable[[int], "int | None"]
+_zorder_anchor: ZOrderAnchor | None = None
+
+
+def set_zorder_anchor(anchor: ZOrderAnchor | None) -> None:
+ """Register who keeps a window above the app window (one per process).
+
+ When the app window is brought to the front, Windows normally puts it on top
+ of everything, then the browser panel's window has to be raised again: a
+ visible flicker. With an anchor the app window goes directly under that
+ window instead, in the same step.
+ """
+ global _zorder_anchor
+ _zorder_anchor = anchor
+
@dataclass(slots=True)
class _PinnedSubclass:
@@ -468,6 +489,11 @@ def _make_proc(api: _Win32, previous: int, is_fullscreen: FullscreenProbe | None
user32 = api.user32
def proc(hwnd, msg, wparam, lparam):
+ if msg == _WM_WINDOWPOSCHANGING and _zorder_anchor is not None:
+ try:
+ _stay_under_anchor(api, hwnd, lparam)
+ except Exception: # noqa: BLE001 - a window procedure must not raise into Win32
+ _log_exception("WM_WINDOWPOSCHANGING z-order anchor failed")
if msg == _WM_GETMINMAXINFO:
# The previous procedure (WinForms, then DefWindowProc) fills the
# structure first; only the maximized rectangle is replaced.
@@ -497,6 +523,25 @@ def _make_proc(api: _Win32, previous: int, is_fullscreen: FullscreenProbe | None
return proc
+def _stay_under_anchor(api: _Win32, hwnd: object, lparam: object) -> None:
+ """Turn "to the top" into "directly under the anchor window" in a WINDOWPOS."""
+ anchor = _zorder_anchor
+ address = _pointer_bits(lparam)
+ if anchor is None or hwnd is None or address == 0:
+ return
+ target = anchor(_as_int(hwnd))
+ if not target:
+ return
+ # WINDOWPOS: HWND hwnd, HWND hwndInsertAfter, int x, y, cx, cy, UINT flags.
+ handles = (api.ctypes.c_void_p * 2).from_address(address)
+ pointer = api.ctypes.sizeof(api.ctypes.c_void_p)
+ flags = api.ctypes.c_uint.from_address(address + 2 * pointer + 16)
+ if flags.value & _SWP_NOZORDER:
+ return
+ if (handles[1] or 0) == _HWND_TOP:
+ handles[1] = target
+
+
def _probe_fullscreen(is_fullscreen: FullscreenProbe | None) -> bool:
if is_fullscreen is None:
return False