diff --git a/docs/feature-map/computers.md b/docs/feature-map/computers.md index d0021d9..f7ab29b 100644 --- a/docs/feature-map/computers.md +++ b/docs/feature-map/computers.md @@ -34,7 +34,7 @@ - 使用者選的那台沒開機、或那台的 AnyBot 沒開沒登入,就不在清單上:Bot 先待在自己的電腦,`list_computers` 會寫那台「現在沒有連線」。 - 在 Bot 自己的電腦上做事不用問,但它看不到使用者的檔案;檔案工具只碰得到自己的資料夾(大家共用同一台)。 - Bot 的電腦的桌面是第 12 版起換的(照 LazyBoy2 的 box:XFCE 工作列、深色主題、粉圓字型、繁中、台北時間);第 11 版以前是 fluxbox,只有右鍵選單和一條細工作列,設定 › 電腦「更新 Bot 的電腦」換新版。桌面設定每次開機照映像檔重放,在桌面上改的外觀、工作列不會留下;留下的是檔案和瀏覽器的登入。工作列鎖住(xfconf 的鎖要寫使用者名稱 bot,寫「*」不算數);它的「面板 › 登出 › 結束」只關掉工作列,一秒後自己回來。網頁上傳檔案的視窗開機時設好大小和位置(GTK 沒有記著位置就照字型算大小,比螢幕大)。時區是 /etc/localtime(台北),沒有 TZ 變數,Bot 改了就生效。 -- 檔案視窗的「取消」「開啟」在視窗最上面(第 11 版以前在最下面、被螢幕切掉,網頁上傳圖片選得到檔案卻送不出去——設定 › 電腦「更新 Bot 的電腦」換新版)。看畫面時可以跟自己的電腦互相複製貼上。 +- 檔案視窗的「取消」「開啟」在視窗最上面(第 11 版以前在最下面、被螢幕切掉,網頁上傳圖片選得到檔案卻送不出去——設定 › 電腦「更新 Bot 的電腦」換新版)。看畫面時可以跟自己的電腦互相複製貼上;在畫面裡打的字進到正在看的那個螢幕(Bot 自己的螢幕也一樣,不會打到共用的)。 - 從帳號看 Bot 電腦的畫面,只要開著就不會斷;之前靜止畫面一分鐘、或看超過十分鐘會被帳號伺服器切掉,要更新帳號伺服器(make update-server)。 - 「在這台電腦上執行」設成永不允許(或被管理員鎖住)時,這台的檔案也不能傳出去、打開或發佈。 - SSH 電腦上的檔案不能直接傳到聊天、打開給使用者看或發佈網站,要先複製到 Bot 自己的電腦。 diff --git a/docs/feature-map/screen.md b/docs/feature-map/screen.md index 257e62d..593f07d 100644 --- a/docs/feature-map/screen.md +++ b/docs/feature-map/screen.md @@ -11,7 +11,7 @@ Bot 用一個 `computer` 工具看一台電腦的螢幕、動滑鼠和鍵盤: - `intent`:系統捷徑(音量、Wi-Fi、鎖螢幕、深淺色、清空垃圾桶,Mac 還有退出磁碟)一步做完。電腦現況列了「系統捷徑」才有:macOS 和 Linux 桌面有,Windows 和 Bot 自己的電腦沒有。 - 交給使用者:`hand_over_computer` 在聊天放一張「需要處理」卡和那台電腦的畫面,使用者做完按「我完成了」或「跳過」。 - 示範教學(macOS、Linux X11):使用者自己做一次,AnyBot 記成步驟和每一步的畫面;Bot 用 `view_demo_step` 看某一步當時的畫面。 -- Bot 自己的電腦:每個 Bot 有自己的螢幕(照 Grok Bot 的分法:一台電腦、每個 Bot 一個螢幕),Bot 第一次看畫面或用瀏覽器時才開,大家同時做互不干擾。支線另開一個暫時的螢幕(瀏覽器從主線那份複製),支線結束就關掉、複製的那份也刪掉。同時最多開 6 個,閒置 10 分鐘的會自己關掉(瀏覽器的登入留著)。原本那個共用的桌面還在。 +- Bot 自己的電腦:每個 Bot 有自己的螢幕(照 Grok Bot 的分法:一台電腦、每個 Bot 一個螢幕),Bot 第一次看畫面或用瀏覽器時才開,大家同時做互不干擾。支線另開一個暫時的螢幕(瀏覽器從主線那份複製),支線結束就關掉、複製的那份也刪掉。同時最多開 6 個,閒置 10 分鐘的會自己關掉(瀏覽器的登入留著);開著看畫面的那個不算閒置,不會被關。原本那個共用的桌面還在。 - 使用者自己的電腦只有一個實體螢幕:一次只給一個 Bot 操作,別人在用時會被擋下,對方停手 120 秒後輪到。只看畫面不受影響。 - 截圖上的卡號和驗證碼會先塗黑,才交給模型。 diff --git a/relay/src/main.rs b/relay/src/main.rs index 6722ba4..fb7ed9a 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -518,7 +518,7 @@ impl Relay { self.streams.lock().unwrap().insert(sid.clone(), (tx, host.to_string(), on)); // 每個 Bot 一個螢幕: which bot's screen (digits only; the AnyBot picks the screen). let bot: String = req.query.get("bot").map(|b| b.chars().filter(|c| c.is_ascii_digit()).take(20).collect()).unwrap_or_default(); - if to_host.send(wire::pack(&json!({"t": "vopen", "sid": sid, "bot": bot}), &[])).is_err() { + if to_host.send(wire::pack(&json!({"t": "vopen", "sid": sid, "bot": bot.clone()}), &[])).is_err() { self.streams.lock().unwrap().remove(&sid); return; } @@ -543,7 +543,11 @@ impl Relay { if let Some((t, b)) = up { heard = Instant::now(); pace.moved(); - if to_host.send(wire::pack(&json!({"t": t, "sid": sid}), &b)).is_err() { + // 每個 Bot 一個螢幕: typed words name the bot whose screen this viewer is on, so + // the AnyBot types into that screen (data frames need no name: they ride the + // viewer's own VNC connection). + let head = if t == "vtext" { json!({"t": t, "sid": sid, "bot": &bot}) } else { json!({"t": t, "sid": sid}) }; + if to_host.send(wire::pack(&head, &b)).is_err() { break; } } diff --git a/src/app/computers_ui.rs b/src/app/computers_ui.rs index 89da663..9d0ceb2 100644 --- a/src/app/computers_ui.rs +++ b/src/app/computers_ui.rs @@ -1025,8 +1025,10 @@ impl App { return; } let key = self.screen_key_for(bot); - let key = if cloudbox::open_screens().iter().any(|(k, _)| *k == key) { key } else { String::new() }; + // Asking the box which screens are open is a docker call: it goes in the background task, + // so a starting box can't freeze the window for its timeout. self.box_task(move || { + let key = if cloudbox::open_screens().iter().any(|(k, _)| *k == key) { key } else { String::new() }; let url = cloudbox::viewer_url_of(&key, control)?; crate::preview::open_with_system(&url); Ok(String::new()) diff --git a/src/botbrowser.rs b/src/botbrowser.rs index 4e24a5d..d5e9501 100644 --- a/src/botbrowser.rs +++ b/src/botbrowser.rs @@ -479,7 +479,9 @@ pub fn using_box() -> bool { /// The debugging port of a bot browser that is already open (None when it isn't; never starts one). pub fn running_port(profile: Option<&str>) -> Option { if using_box() { - return crate::cloudbox::browser_running().then(crate::cloudbox::browser_port).and_then(Result::ok); + // Its own browser on its own screen (每個 Bot 一個螢幕) — and only when it is answering: + // listing browsers and a turn's tidy-up must not open a screen for nothing. + return crate::cloudbox::browser_open_port(); } live_port(&resolve(profile).ok()?) } diff --git a/src/cloudbox.rs b/src/cloudbox.rs index fe966dd..5d7e73a 100644 --- a/src/cloudbox.rs +++ b/src/cloudbox.rs @@ -1119,7 +1119,7 @@ fn screen_cdp_port(fresh: bool) -> Result { if let Some(p) = known { return Ok(p); } - let out = dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &format!("command -v anybot-screen >/dev/null || {{ echo CDP_PORT={BOX_CDP_PORT}; exit 0; }}; anybot-screen up {key}")], 30_000) + let out = dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &format!("command -v anybot-screen >/dev/null || {{ echo CDP_PORT={BOX_CDP_PORT}; exit 0; }}; anybot-screen up {key} 2>&1")], 30_000) .map(|o| String::from_utf8_lossy(&o).to_string()) .map_err(|e| screen_full(&e).unwrap_or_else(|| format!("Bot 的電腦開不了這個 Bot 的螢幕:{e}")))?; let port = out.lines().find_map(|l| l.trim().strip_prefix("CDP_PORT=")?.parse::().ok()).ok_or("Bot 的電腦沒有說這個 Bot 的瀏覽器在哪個埠")?; @@ -1130,11 +1130,33 @@ fn screen_cdp_port(fresh: bool) -> Result { Ok(port) } -/// Is the current screen's Chromium answering already? +/// Is the current screen's Chromium answering already? (This opens the screen when it isn't: a +/// bot's browser step needs one. For a check that must never wake a screen, see +/// `browser_open_port`.) pub fn browser_running() -> bool { screen_cdp_port(false).and_then(box_cdp_forward).map(box_cdp_alive).unwrap_or(false) } +/// The current screen's Chromium's local port when it is answering already — and nothing else: +/// it never opens a screen or a browser. Listings and a turn's tidy-up ask this, so they don't +/// take a screen slot (of the six) for a screen they never use. +pub fn browser_open_port() -> Option { + let key = current_screen(); + let port = if key.is_empty() { + BOX_CDP_PORT + } else { + if !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { + return None; + } + // The same fall as screen_sh: a box without anybot-screen (an old image) is all on the + // shared screen; a new one whose screen was closed has no env file and says nothing. + let out = dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &format!("command -v anybot-screen >/dev/null || {{ echo CDP_PORT={BOX_CDP_PORT}; exit 0; }}; cat /tmp/anybot-screens/{key}/env 2>/dev/null")], 10_000).ok()?; + String::from_utf8_lossy(&out).lines().find_map(|l| l.trim().strip_prefix("CDP_PORT=")?.parse::().ok())? + }; + box_cdp_forward(port).ok()?; + box_cdp_alive(port).then_some(port) +} + /// The current screen's Chromium (each bot its own, on its own screen, with its own profile that /// started as a copy of the shared one's logins), started when it isn't running. Gives the local /// port that reaches it. @@ -2267,6 +2289,17 @@ pub fn close_screen(key: &str) { screens().lock().unwrap_or_else(|e| e.into_inner()).remove(key); } +/// Mark a screen used, so the box's idle sweep (10 min) doesn't close it under a person who is +/// watching it (its viewer alone touches nothing else: a still screen sends no bot steps). +pub fn touch_screen(key: &str) { + if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { + return; + } + if run_state().is_running() { + let _ = dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &format!("touch /tmp/anybot-screens/{key}/last 2>/dev/null")], 10_000); + } +} + fn current_screen() -> String { ON_SCREEN.with(|s| s.borrow().clone()) } @@ -2624,7 +2657,7 @@ pub fn computer_run(name: &str, v: &Value) -> Result<(String, Option), S "computer_use_show" => return box_show(), _ => {} } - if is_held(¤t_screen()) || crate::vnc::person_active() { + if is_held(¤t_screen()) || crate::vnc::person_active(¤t_screen()) { return Err("使用者正在自己操作這台電腦。請等他操作完(停下幾秒後)再繼續,或先截圖看看畫面。".into()); } if name == "computer_use_open_app" { diff --git a/src/remote.rs b/src/remote.rs index 8a854cd..3800927 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1591,7 +1591,8 @@ fn lan_vnc(req: Req, mut c: std::net::TcpStream, gen: u64) { } Ok(Message::Text(t)) => { heard = Instant::now(); - crate::vnc::person_typed(&t) + // Words typed in the viewer go to the screen this viewer is on (每個 Bot 一個螢幕). + crate::vnc::person_typed(&t, &screen) } Ok(Message::Close(_)) => break, Ok(_) => heard = Instant::now(), diff --git a/src/tunnel.rs b/src/tunnel.rs index 88fafeb..1af6969 100644 --- a/src/tunnel.rs +++ b/src/tunnel.rs @@ -376,8 +376,11 @@ fn on_stream(kind: &str, sid: String, bot: String, body: Vec, tx: &Sender { + // 每個 Bot 一個螢幕: the words go to the screen this viewer is on, not always the + // shared one (the account server passes the bot the viewer was opened for). + let screen = crate::cloudbox::screen_for_bot(&bot); let _ = std::thread::Builder::new().spawn(move || { - crate::vnc::person_typed(&String::from_utf8_lossy(&body)); + crate::vnc::person_typed(&String::from_utf8_lossy(&body), &screen); }); } _ => { diff --git a/src/vnc.rs b/src/vnc.rs index 6b67475..7f277b7 100644 --- a/src/vnc.rs +++ b/src/vnc.rs @@ -47,8 +47,13 @@ while True: /// Viewers connected now (the box stays awake while there is one). static OPEN: AtomicUsize = AtomicUsize::new(0); -/// When the person last clicked or typed through a viewer. -static LAST_INPUT: Mutex> = Mutex::new(None); +/// When the person last clicked or typed through a viewer, per screen ("" is the shared one): +/// using one bot's screen must not stop the bots working on their own (每個 Bot 一個螢幕 — +/// 接管時只有它停手,別的 Bot 照做). +static LAST_INPUT: std::sync::OnceLock>> = std::sync::OnceLock::new(); +fn last_input() -> &'static Mutex> { + LAST_INPUT.get_or_init(Default::default) +} /// VNC authentication: the 16-byte challenge encrypted with DES, the key being the password's /// first 8 bytes with each byte's bits reversed (RFC 6143 §7.2.2, as every VNC server does it). @@ -82,6 +87,8 @@ pub struct Session { sniffing: bool, /// The viewer's ClientInit (one byte) is still to come. init: bool, + /// The screen this viewer watches ("" is the shared one): input pauses that screen's bot only. + screen: String, } /// Open a viewer's way to `key`'s screen on the box (a bot's own, 每個 Bot 一個螢幕; "" or one not @@ -135,6 +142,21 @@ pub fn open_on(key: &str, out: impl Fn(&[u8]) -> bool + Send + 'static) -> Resul } OPEN.fetch_add(1, Ordering::SeqCst); crate::cloudbox::set_viewer_open(true); + // A person watching a bot's screen keeps it from being reaped as idle: touch its stamp now + // and while the viewer lives (a still screen sends no frames, so the read loop below sleeps). + crate::cloudbox::touch_screen(&key); + let alive = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + { + let (alive, k) = (alive.clone(), key.clone()); + std::thread::spawn(move || { + while alive.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_secs(60)); + if alive.load(Ordering::SeqCst) { + crate::cloudbox::touch_screen(&k); + } + } + }); + } std::thread::spawn(move || { let mut buf = vec![0u8; 64 * 1024]; loop { @@ -142,11 +164,13 @@ pub fn open_on(key: &str, out: impl Fn(&[u8]) -> bool + Send + 'static) -> Resul Ok(0) | Err(_) => break, Ok(n) => { if !out(&buf[..n]) { + alive.store(false, Ordering::SeqCst); return; } } } } + alive.store(false, Ordering::SeqCst); // The box's side ended: an empty send says so. out(&[]); }); @@ -158,7 +182,7 @@ pub fn open_on(key: &str, out: impl Fn(&[u8]) -> bool + Send + 'static) -> Resul } } }); - Ok(Session { child, writer: wtx, greeting: 13, pending: Vec::new(), sniffing: true, init: true }) + Ok(Session { child, writer: wtx, greeting: 13, pending: Vec::new(), sniffing: true, init: true, screen: key }) } impl Session { @@ -208,7 +232,7 @@ impl Session { } Msg::Is { len, input } => { if input { - person_acted(); + person_acted(&self.screen); } at += len; } @@ -287,21 +311,23 @@ impl Drop for Session { } } -/// The person clicked or typed: the bot's steps wait until a little after they stop. -pub fn person_acted() { - *LAST_INPUT.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now()); +/// The person clicked or typed on `key`'s screen: that screen's bot waits until a little after +/// they stop; bots on other screens don't (每個 Bot 一個螢幕). +pub fn person_acted(key: &str) { + last_input().lock().unwrap_or_else(|e| e.into_inner()).insert(key.to_string(), Instant::now()); } -/// The person is using the box through a viewer right now (input in the last few seconds). -pub fn person_active() -> bool { - LAST_INPUT.lock().unwrap_or_else(|e| e.into_inner()).map(|t| t.elapsed() < HELD_AFTER_INPUT).unwrap_or(false) +/// The person is using `key`'s screen through a viewer right now (input in the last few seconds). +pub fn person_active(key: &str) -> bool { + last_input().lock().unwrap_or_else(|e| e.into_inner()).get(key).map(|t| t.elapsed() < HELD_AFTER_INPUT).unwrap_or(false) } -/// Text the person typed in the viewer's own box (any language): pasted into the box. -pub fn person_typed(text: &str) { +/// Text the person typed in the viewer's own box (any language): pasted into the box, on the +/// screen that viewer watches — not always the shared one (每個 Bot 一個螢幕). +pub fn person_typed(text: &str, key: &str) { if !text.is_empty() { - person_acted(); - crate::cloudbox::viewer_text(text); + person_acted(key); + crate::cloudbox::on_screen(key, || crate::cloudbox::viewer_text(text)); } } @@ -347,6 +373,16 @@ mod tests { assert!(BRIDGE.contains("\n r=select") && BRIDGE.contains("\n if not d: break")); } + #[test] + fn a_persons_input_holds_only_the_screen_they_use() { + // 每個 Bot 一個螢幕: clicking on one bot's screen must not stop the bots working on + // their own screens, nor the shared one. + person_acted("bot12"); + assert!(person_active("bot12")); + assert!(!person_active(""), "the shared desktop is free"); + assert!(!person_active("bot13"), "another bot's screen is free"); + } + #[test] fn vnc_password_answer_matches_the_standard() { // Password "password", challenge 00..0f: DES-ECB with the bit-reversed key 0e86ceceeef64e26