fix(browser): the bot opens its pages in windows of their own behind, so it never takes the focus

On the shared screen a tab brought to the front makes Chrome bring its window forward and take the
keyboard focus from the game or program the user is in (seen on the game PC). The botBrowser tool
now opens each person's page in a window of its own, behind and at the place and size of the bot
browser's window (Target.createTarget with newWindow and background), and closes it again if the
connection to it fails. While the browser runs on the virtual monitor, the app looks for new Chrome
windows every 200 ms and settles each like the first (tool window, fitted to the work area, without
activating it), the newest in front of the older ones, so the shared screen shows the page the bot
opened last.

Checked on the game PC: the bot's window loading a public page comes in front of the first, both
out of the taskbar and Alt+Tab, the focus staying in Discord also with the user idle for hours.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-15 16:15:36 +09:00
parent cb2dda25b6
commit bd7b69d4f4
8 changed files with 221 additions and 55 deletions

View File

@@ -96,10 +96,55 @@ fn foreground_pid() -> u32 {
pid
}
/// The visible top-level Chrome windows of process `pid`, top first: (title, tool window).
#[cfg(windows)]
fn chrome_windows(pid: u32) -> Vec<(String, bool)> {
use windows_sys::Win32::Foundation::{HWND, LPARAM};
use windows_sys::Win32::UI::WindowsAndMessaging::*;
unsafe extern "system" fn each(h: HWND, l: LPARAM) -> windows_sys::core::BOOL {
// SAFETY: `l` is the `(pid, Vec)` below, alive through EnumWindows; plain queries on `h`.
unsafe {
let (pid, out) = &mut *(l as *mut (u32, Vec<(String, bool)>));
let (mut p, mut class, mut title) = (0u32, [0u16; 64], [0u16; 256]);
GetWindowThreadProcessId(h, &mut p);
let n = GetClassNameW(h, class.as_mut_ptr(), 64) as usize;
if p == *pid && IsWindowVisible(h) != 0 && GetWindow(h, GW_OWNER).is_null()
&& String::from_utf16_lossy(&class[..n]) == "Chrome_WidgetWin_1" {
let t = GetWindowTextW(h, title.as_mut_ptr(), 256) as usize;
let tool = GetWindowLongPtrW(h, GWL_EXSTYLE) as u32 & WS_EX_TOOLWINDOW != 0;
out.push((String::from_utf16_lossy(&title[..t]), tool));
}
}
1
}
let mut found = (pid, vec![]);
// SAFETY: `each` writes only into `found`, which outlives the call.
unsafe { EnumWindows(Some(each), &mut found as *mut _ as LPARAM) };
found.1
}
/// One call on the browser's CDP connection.
async fn cdp<S>(s: &mut S, id: u64, method: &str, params: serde_json::Value) -> serde_json::Value
where S: futures_util::Sink<tokio_tungstenite::tungstenite::Message> + futures_util::Stream<Item =
Result<tokio_tungstenite::tungstenite::Message, tokio_tungstenite::tungstenite::Error>> + Unpin,
S::Error: std::fmt::Debug {
use futures_util::{SinkExt, StreamExt};
let msg = serde_json::json!({"id": id, "method": method, "params": params});
s.send(tokio_tungstenite::tungstenite::Message::text(msg.to_string())).await.unwrap();
loop {
let v: serde_json::Value = serde_json::from_str(s.next().await.unwrap().unwrap().to_text().unwrap()).unwrap();
if v["id"] == id {
break v["result"].clone();
}
}
}
/// With a screen, Chrome starts without a window and the app opens exactly one, at the screen's
/// place and size, without taking the focus; the page tab the bot opens joins it. Needs a display
/// on Linux (`DISPLAY`); on Windows the screen is the virtual monitor (its driver installed), on the
/// desktop only meanwhile.
/// place and size, without taking the focus. The bot's page then opens the way the botBrowser tool
/// opens it (a window of its own behind, at that window's place): also without taking the focus,
/// and on Windows the app makes it a tool window in front of the first. Needs a display on Linux
/// (`DISPLAY`); on Windows the screen is the virtual monitor (its driver installed), on the desktop
/// only meanwhile.
#[tokio::test]
async fn on_a_screen_the_bot_browser_has_one_window_at_the_monitor() {
let Ok(exe) = std::env::var("JARVIS_TEST_CHROME") else {
@@ -130,25 +175,43 @@ async fn on_a_screen_the_bot_browser_has_one_window_at_the_monitor() {
.text().await.map(|t| serde_json::from_str(&t).unwrap()).unwrap();
let first = pages(list);
assert_eq!(first.len(), 1, "one page in one window");
client.put(format!("http://127.0.0.1:{}/json/new?about:blank", b.cdp_port)).send().await.unwrap();
// Each page's window over CDP: both tabs share the one window, at the screen's rectangle.
let ws: serde_json::Value = client.get(format!("http://127.0.0.1:{}/json/version", b.cdp_port)).send().await.unwrap()
.text().await.map(|t| serde_json::from_str(&t).unwrap()).unwrap();
let (mut s, _) = tokio_tungstenite::connect_async(ws["webSocketDebuggerUrl"].as_str().unwrap()).await.unwrap();
let list: serde_json::Value = client.get(format!("http://127.0.0.1:{}/json/list", b.cdp_port)).send().await.unwrap()
.text().await.map(|t| serde_json::from_str(&t).unwrap()).unwrap();
let ids = pages(list);
assert_eq!(ids.len(), 2);
// As the botBrowser tool does it.
let at = cdp(&mut s, 1, "Browser.getWindowForTarget", serde_json::json!({"targetId": first[0]})).await["bounds"].clone();
let bot = cdp(&mut s, 2, "Target.createTarget", serde_json::json!({"url": "about:blank",
"newWindow": true, "background": true, "left": at["left"], "top": at["top"], "width": at["width"],
"height": at["height"]})).await["targetId"].as_str().unwrap().to_owned();
// A page loading in it, as the tool's `open` does.
let (mut page, _) = tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{}/devtools/page/{bot}", b.cdp_port))
.await.unwrap();
cdp(&mut page, 1, "Page.navigate", serde_json::json!({"url": "https://example.com/"})).await;
let mut loaded = false;
for _ in 0..40 {
loaded = titles(&client, b.cdp_port).await.iter().any(|(_, t)| t == "Example Domain");
if loaded {
break;
}
tokio::time::sleep(Duration::from_millis(250)).await;
}
assert!(loaded, "the bot's page loads in its window");
tokio::time::sleep(Duration::from_secs(1)).await;
#[cfg(windows)]
{
assert_eq!(foreground_pid(), focused, "the bot's window leaves the focus where it was");
let w = chrome_windows(b.pid());
eprintln!("chrome windows, top first: {w:?}");
assert_eq!(w.len(), 2, "{w:?}");
assert!(w[0].0.starts_with("Example Domain"), "the bot's window is in front: {w:?}");
assert!(w.iter().all(|(_, tool)| *tool), "no window in the taskbar or Alt+Tab: {w:?}");
}
// Each page's window over CDP: a window each, at the screen's rectangle.
let mut windows = std::collections::HashSet::new();
for (i, id) in ids.iter().enumerate() {
use futures_util::{SinkExt, StreamExt};
let msg = serde_json::json!({"id": i + 1, "method": "Browser.getWindowForTarget", "params": {"targetId": id}});
s.send(tokio_tungstenite::tungstenite::Message::text(msg.to_string())).await.unwrap();
let r = loop {
let v: serde_json::Value = serde_json::from_str(s.next().await.unwrap().unwrap().to_text().unwrap()).unwrap();
if v["id"] == i + 1 { break v["result"].clone(); }
};
for (i, id) in [first[0].clone(), bot].iter().enumerate() {
let r = cdp(&mut s, 10 + i as u64, "Browser.getWindowForTarget", serde_json::json!({"targetId": id})).await;
eprintln!("window: {r}");
windows.insert(r["windowId"].as_i64().unwrap());
let b = &r["bounds"];
@@ -163,7 +226,7 @@ async fn on_a_screen_the_bot_browser_has_one_window_at_the_monitor() {
assert_eq!((left, top, width, height), (x, y, w, h));
}
}
assert_eq!(windows.len(), 1, "the bot's tab opens in the same window");
assert_eq!(windows.len(), 2, "the bot's page has a window of its own");
if std::env::var_os("JARVIS_TEST_HOLD").is_some() {
// Time for a look at the screen (the Windows check takes a screenshot meanwhile).
tokio::time::sleep(std::time::Duration::from_secs(8)).await;