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

@@ -4,7 +4,8 @@
use std::net::{IpAddr, SocketAddr};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -16,6 +17,8 @@ const HEAD_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_HEAD: usize = 64 * 1024;
const READY_TIMEOUT: Duration = Duration::from_secs(30);
const CLOSE_WAIT: Duration = Duration::from_secs(5);
/// How often the windows the bot opens on the virtual monitor are looked for.
const WATCH_EVERY: Duration = Duration::from_millis(200);
/// Whether an address is on the public internet: not this PC, the local network or a special range.
pub fn is_public(ip: &IpAddr) -> bool {
@@ -255,6 +258,14 @@ pub struct BotBrowser {
child: Mutex<Option<tokio::process::Child>>,
proxy: EgressProxy,
pub cdp_port: u16,
/// While set (with a screen, on Windows), a thread settles the windows the bot opens.
watching: Arc<AtomicBool>,
}
impl Drop for BotBrowser {
fn drop(&mut self) {
self.watching.store(false, Ordering::Relaxed);
}
}
impl BotBrowser {
@@ -293,12 +304,25 @@ impl BotBrowser {
}
tokio::time::sleep(Duration::from_millis(200)).await;
};
let b = Self { child: Mutex::new(Some(child)), proxy, cdp_port };
let b = Self { child: Mutex::new(Some(child)), proxy, cdp_port, watching: Arc::new(AtomicBool::new(false)) };
if let Some(r) = screen {
if let Err(e) = b.open_window(r).await {
b.stop().await;
return Err(e);
}
if cfg!(windows) {
// The bot opens a window per person (bot_browser.spec.md), each settled like the first.
b.watching.store(true, Ordering::Relaxed);
let (on, pid) = (b.watching.clone(), b.pid());
std::thread::spawn(move || {
while on.load(Ordering::Relaxed) {
if crate::vdisplay::settle_windows(pid) > 0 {
crate::debug_log!("browser", "a new bot browser window settled on the virtual monitor");
}
std::thread::sleep(WATCH_EVERY);
}
});
}
}
crate::info_log!("browser", "bot browser ready (CDP on 127.0.0.1:{cdp_port}{})",
if screen.is_some() { ", on the virtual monitor" } else { "" });
@@ -307,14 +331,15 @@ impl BotBrowser {
/// The window on `r`: a background page in a new window (CDP), then out of the window switcher
/// and fitted to the monitor's work area.
/// It holds the first tab, which the bot never closes, so the window stays.
/// It holds the first page, which the bot never closes, so the window stays; the bot's own
/// windows open where it is.
async fn open_window(&self, r: crate::vdisplay::Rect) -> Result<(), String> {
let ws = version(self.cdp_port).await.and_then(|v| v["webSocketDebuggerUrl"].as_str().map(str::to_owned))
.ok_or("Chrome의 CDP 주소를 읽지 못했습니다")?;
cdp_call(&ws, serde_json::json!({"id": 1, "method": "Target.createTarget", "params": {"url": "about:blank",
"newWindow": true, "background": true, "left": r.x, "top": r.y, "width": r.w, "height": r.h}})).await
.map_err(|e| format!("Chrome 창을 열지 못했습니다: {e}"))?;
let pid = self.child.lock().unwrap().as_ref().and_then(|c| c.id()).unwrap_or(0);
let pid = self.pid();
for _ in 0..25 {
if cfg!(not(windows)) || crate::vdisplay::settle_windows(pid) > 0 {
return Ok(());
@@ -324,6 +349,11 @@ impl BotBrowser {
Err("Chrome 창을 찾지 못했습니다".into())
}
/// Chrome's main process (0 once it ended), the one owning its windows.
pub fn pid(&self) -> u32 {
self.child.lock().unwrap().as_ref().and_then(|c| c.id()).unwrap_or(0)
}
pub fn cdp_url(&self) -> String {
format!("http://127.0.0.1:{}", self.cdp_port)
}
@@ -335,6 +365,7 @@ impl BotBrowser {
/// `Browser.close`, then up to 5 s for Chrome to end, else it is killed; the proxy ends too.
pub async fn stop(&self) {
self.watching.store(false, Ordering::Relaxed);
let child = self.child.lock().unwrap().take();
if let Some(mut child) = child {
if let Some(ws) = version(self.cdp_port).await.and_then(|v| v["webSocketDebuggerUrl"].as_str().map(str::to_owned)) {