feat(app): the bot browser's window on a virtual monitor to share in Discord

- features.browserShare (봇용 크롬창 화면공유 선택 표시, off by default) and a driver card on the
  features screen: the Virtual Display Driver 25.7.23 (MIT, SignPath-signed) ships in
  display-driver/ (hash-checked by package.sh); install and uninstall run jarvis.exe elevated
  once (--display-driver), settings in %ProgramData%\JarvisBot\display-driver, another
  program's copy of the driver is left alone
- the monitor is on the desktop only while the bot browser uses it, at the rightmost real
  monitor's bottom-right corner; the stop closes Chrome first, then takes the monitor off
- Chrome starts with no window and the app opens it over CDP in the background, so it never
  takes the focus; the window is a tool window (no Alt+Tab, no taskbar button), fills the
  monitor's work area and keeps drawing when covered; without a monitor it runs headless with
  the reason on the dashboard
- Chrome runs with --do-not-de-elevate on Windows: started by an app running as administrator
  it restarted itself as the user and the app lost hold of it
- checked on the win-ci Windows VM from install to uninstall (focus kept while typing, no
  taskbar button, no Chrome left, nothing left after uninstall) and on Linux with a real Chrome

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-14 02:43:32 +09:00
parent 56212c06dc
commit 1bd7defbb4
17 changed files with 884 additions and 43 deletions

View File

@@ -212,11 +212,11 @@ async fn refused(client: &mut TcpStream, why: &str) -> std::io::Result<()> {
// ---- Chrome ---------------------------------------------------------------------------------------
/// The arguments the bot's Chrome runs with (headless, its profile, CDP on a free port, every
/// connection through the proxy on `proxy_port`).
pub fn chrome_args(profile: &Path, proxy_port: u16, no_sandbox: bool) -> Vec<String> {
/// The arguments the bot's Chrome runs with (its profile, CDP on a free port, every connection
/// through the proxy on `proxy_port`): headless, or with `screen` a real window the app opens later
/// over CDP (admin.spec.md, "Virtual monitor").
pub fn chrome_args(profile: &Path, proxy_port: u16, no_sandbox: bool, screen: bool) -> Vec<String> {
let mut a = vec![
"--headless=new".to_owned(),
format!("--user-data-dir={}", profile.display()),
"--remote-debugging-port=0".into(),
format!("--proxy-server=http://127.0.0.1:{proxy_port}"),
@@ -235,7 +235,19 @@ pub fn chrome_args(profile: &Path, proxy_port: u16, no_sandbox: bool) -> Vec<Str
if no_sandbox {
a.push("--no-sandbox".into());
}
a.push("about:blank".into());
if cfg!(windows) {
// Started by an app running as administrator, Chrome would start again as the user and end
// the process the app holds, which could then neither see nor stop it.
a.push("--do-not-de-elevate".into());
}
if screen {
// A window opened at start would take the focus from the game the user is playing.
a.extend(["--no-startup-window", "--disable-backgrounding-occluded-windows", "--disable-renderer-backgrounding",
"--disable-background-timer-throttling"].map(String::from));
} else {
a.insert(0, "--headless=new".into());
a.push("about:blank".into());
}
a
}
@@ -246,15 +258,17 @@ pub struct BotBrowser {
}
impl BotBrowser {
/// Start Chrome `exe` with profile folder `profile` and wait until CDP answers.
pub async fn start(exe: &Path, profile: &Path) -> Result<Self, String> {
/// Start Chrome `exe` with profile folder `profile` and wait until CDP answers; with `screen`,
/// its one window sits there (the virtual monitor), opened without taking the focus and kept out
/// of Alt+Tab and the taskbar.
pub async fn start(exe: &Path, profile: &Path, screen: Option<crate::vdisplay::Rect>) -> Result<Self, String> {
let proxy = EgressProxy::start(is_public).await.map_err(|e| format!("proxy: {e}"))?;
std::fs::create_dir_all(profile).map_err(|e| e.to_string())?;
let port_file = profile.join("DevToolsActivePort");
let _ = std::fs::remove_file(&port_file);
let no_sandbox = cfg!(not(windows)) && std::env::var("JARVIS_CHROME_NO_SANDBOX").is_ok_and(|v| v == "1");
let mut cmd = tokio::process::Command::new(exe);
cmd.args(chrome_args(profile, proxy.port, no_sandbox)).stdin(std::process::Stdio::null())
cmd.args(chrome_args(profile, proxy.port, no_sandbox, screen.is_some())).stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true);
#[cfg(unix)]
cmd.process_group(0);
@@ -278,8 +292,35 @@ impl BotBrowser {
}
tokio::time::sleep(Duration::from_millis(200)).await;
};
crate::info_log!("browser", "bot browser ready (CDP on 127.0.0.1:{cdp_port})");
Ok(Self { child: Mutex::new(Some(child)), proxy, cdp_port })
let b = Self { child: Mutex::new(Some(child)), proxy, cdp_port };
if let Some(r) = screen {
if let Err(e) = b.open_window(r).await {
b.stop().await;
return Err(e);
}
}
crate::info_log!("browser", "bot browser ready (CDP on 127.0.0.1:{cdp_port}{})",
if screen.is_some() { ", on the virtual monitor" } else { "" });
Ok(b)
}
/// 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.
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);
for _ in 0..25 {
if cfg!(not(windows)) || crate::vdisplay::settle_windows(pid) > 0 {
return Ok(());
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
Err("Chrome 창을 찾지 못했습니다".into())
}
pub fn cdp_url(&self) -> String {
@@ -323,6 +364,27 @@ async fn close_over_cdp(ws: &str) -> Result<(), String> {
.map_err(|e| e.to_string())
}
/// One CDP call on the browser connection `ws`; its result, or the error Chrome gave (5 s at most).
async fn cdp_call(ws: &str, msg: serde_json::Value) -> Result<serde_json::Value, String> {
use futures_util::{SinkExt, StreamExt};
let id = msg["id"].clone();
tokio::time::timeout(Duration::from_secs(5), async {
let (mut s, _) = tokio_tungstenite::connect_async(ws).await.map_err(|e| e.to_string())?;
s.send(tokio_tungstenite::tungstenite::Message::text(msg.to_string())).await.map_err(|e| e.to_string())?;
while let Some(m) = s.next().await {
let m = m.map_err(|e| e.to_string())?;
let Ok(v) = serde_json::from_str::<serde_json::Value>(m.to_text().unwrap_or("")) else { continue };
if v["id"] == id {
return match v.get("error") {
Some(e) => Err(e["message"].as_str().unwrap_or("error").to_owned()),
None => Ok(v["result"].clone()),
};
}
}
Err("connection closed".to_owned())
}).await.map_err(|_| "timeout".to_owned())?
}
async fn kill_tree(child: &mut tokio::process::Child) {
if let Some(pid) = child.id() {
#[cfg(unix)]
@@ -437,13 +499,27 @@ mod tests {
#[test]
fn chrome_goes_through_the_proxy_with_its_own_profile() {
let a = chrome_args(Path::new("/d/browser/profile"), 4321, false);
let a = chrome_args(Path::new("/d/browser/profile"), 4321, false, false);
for want in ["--headless=new", "--user-data-dir=/d/browser/profile", "--remote-debugging-port=0",
"--proxy-server=http://127.0.0.1:4321", "--proxy-bypass-list=<-loopback>", "--disable-quic"] {
assert!(a.iter().any(|x| x == want), "{want}");
}
assert!(!a.iter().any(|x| x == "--no-sandbox"));
assert!(chrome_args(Path::new("/p"), 1, true).iter().any(|x| x == "--no-sandbox"));
assert!(chrome_args(Path::new("/p"), 1, true, false).iter().any(|x| x == "--no-sandbox"));
assert_eq!(a.iter().any(|x| x == "--do-not-de-elevate"), cfg!(windows), "the app keeps hold of Chrome on Windows");
}
#[test]
fn on_a_screen_chrome_has_a_window_it_opens_later_and_keeps_drawing_when_covered() {
let a = chrome_args(Path::new("/p"), 4321, false, true);
assert!(!a.iter().any(|x| x.starts_with("--headless")));
// No window at start: the app opens it over CDP in the background, so it never takes focus.
assert!(a.iter().any(|x| x == "--no-startup-window"));
assert!(!a.iter().any(|x| x == "about:blank"));
for want in ["--disable-backgrounding-occluded-windows", "--disable-renderer-backgrounding",
"--proxy-server=http://127.0.0.1:4321", "--disable-quic"] {
assert!(a.iter().any(|x| x == want), "{want}");
}
}
}