AnyBot/src/tunnel.rs

687 lines
31 KiB
Rust
Raw Normal View History

// 長連線: one lasting WebSocket from this AnyBot to the account server. Requests for this AnyBot
// (the phone, a screen of this brain, a brain using this computer's hands) come down it at once;
// this AnyBot's own requests to the account's other AnyBots go up it. Big bodies are compressed.
// A ping every 15 s keeps it (and any proxy on the way) awake; 45 s without a word and it is
// opened again. If the account server is older and has no WebSocket, the old way (asking
// "anything for me?" over and over) is used instead.
use crate::httpd::Req;
use crate::wire;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::io::{ErrorKind, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use tungstenite::{Message, WebSocket};
const PING_SECS: u64 = 15;
const DEAD_SECS: u64 = 45;
fix: 慢的線上長連線不再被切斷;斷線接回馬上重新同步;大腦那一欄看得出是哪一段 計畫 R7。2026-11-17 早上:Mac mini 經 Tailscale 香港中繼連 nobledesktop(約 100 KB/s),大腦整份資料約 5 MB 要 45–55 秒。這台 45 秒沒收到「一則完整訊息」就算斷線,傳到一半被切、螢幕又從頭要整份,一直循環(實測:連線 9:41:48 開、9:42:33 剛好 45 秒時被切;第二次 9:43:55 一樣)。帳號那欄寫已連線、大腦那欄寫「和帳號伺服器的連線斷了」,看不出是哪一段。 - tunnel.rs:Stream 讀到資料就記(bytes_in、receiving);keep() 有資料進來就算還活著(DEAD_SECS 照舊,但量的是真的沒聲音)。call() 過了自己的時間、但連線還在收資料就繼續等(最多 10 分鐘)。link_serial() 給螢幕知道長連線接回了。 - 帳號伺服器(relay)的長連線同樣:Counted 包住 TcpStream,資料進來就算活著(這台上傳大份資料時不會被那端的 60 秒切掉)。要 make update-server 才生效。relay/clippy.toml:主程式的「HTTP 用戶端只能在 net.rs 建」不套用到 relay。 - 螢幕(mirror_ui):等重試時每 0.2 秒看一次長連線,接回就馬上再要(以前最多等 20 秒,這段時間帳號那欄已經寫已連線);記下上次同步的時間、大小、秒數。 - 設定的大腦那一欄:狀態下面分段寫「這台 ↔ 帳號伺服器」「帳號伺服器 ↔ 大腦(在線上/不在線上,帳號伺服器說的)」「上次同步 …(大小、秒數、KB/s)」。 已驗證:cargo test 571 全過、clippy -D warnings 過;relay cargo test 22 全過。新測試:假的帳號伺服器把一則 64 KB 的訊息分 3 秒慢慢送(允許的沉默設成 1 秒),連線不斷;之後真的沒聲音就斷。把「有資料進來就算活著」拿掉,同一個測試失敗:「已連線」後馬上「連線中斷」——就是早上的情況。 未驗證:真的 Tailscale 中繼線路上走一次(要更新這台的 App 和伺服器)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:41:15 +00:00
/// Silence after which the link is opened again (DEAD_SECS; a test makes it short).
static DEAD_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(DEAD_SECS * 1000);
/// Bodies bigger than this are compressed.
const ZIP_OVER: usize = 1024;
const CUT: &str = "和帳號伺服器的連線斷了,正在重新連線";
/// Another AnyBot's answer to a call.
pub struct Answer {
pub status: u16,
pub body: Vec<u8>,
}
type Calls = Arc<Mutex<HashMap<String, Sender<Result<Answer, String>>>>>;
struct Link {
tx: Sender<Vec<u8>>,
calls: Calls,
serial: u64,
}
fn link() -> &'static Mutex<Option<Link>> {
static L: OnceLock<Mutex<Option<Link>>> = OnceLock::new();
L.get_or_init(|| Mutex::new(None))
}
pub fn zip(b: &[u8]) -> Vec<u8> {
let mut e = flate2::write::DeflateEncoder::new(Vec::with_capacity(b.len() / 3), flate2::Compression::fast());
let _ = e.write_all(b);
e.finish().unwrap_or_default()
}
/// The body to send and whether it is compressed: only when that saves a good part of it
/// (pictures and PDFs are compressed already).
fn maybe_zip(b: Vec<u8>) -> (Vec<u8>, bool) {
// JPEG, PNG, GIF, WebP, PDF, zip/docx, gzip: compressed already, not worth a try (the live
// picture is a JPEG several times a second).
const PACKED: [&[u8]; 7] = [b"\xff\xd8\xff", b"\x89PNG", b"GIF8", b"RIFF", b"%PDF", b"PK\x03\x04", b"\x1f\x8b"];
if b.len() <= ZIP_OVER || PACKED.iter().any(|m| b.starts_with(m)) {
return (b, false);
}
let z = zip(&b);
if z.len() * 10 < b.len() * 9 {
(z, true)
} else {
(b, false)
}
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
const MAX_UNZIP: u64 = 64 * 1024 * 1024;
const MAX_ACTIVE_JOBS: usize = 64;
pub fn unzip(b: &[u8]) -> Result<Vec<u8>, String> {
let mut out = vec![];
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
flate2::read::DeflateDecoder::new(b).take(MAX_UNZIP + 1).read_to_end(&mut out).map_err(|_| "收到的資料壞掉了".to_string())?;
if out.len() as u64 > MAX_UNZIP {
return Err("收到的壓縮資料太大了".into());
}
Ok(out)
}
// ---------- the connection ----------
enum Stream {
Plain(TcpStream),
Tls(Box<rustls::StreamOwned<rustls::ClientConnection, TcpStream>>),
}
impl Stream {
fn tcp(&self) -> &TcpStream {
match self {
Stream::Plain(t) => t,
Stream::Tls(s) => &s.sock,
}
}
}
impl Read for Stream {
fn read(&mut self, b: &mut [u8]) -> std::io::Result<usize> {
fix: 慢的線上長連線不再被切斷;斷線接回馬上重新同步;大腦那一欄看得出是哪一段 計畫 R7。2026-11-17 早上:Mac mini 經 Tailscale 香港中繼連 nobledesktop(約 100 KB/s),大腦整份資料約 5 MB 要 45–55 秒。這台 45 秒沒收到「一則完整訊息」就算斷線,傳到一半被切、螢幕又從頭要整份,一直循環(實測:連線 9:41:48 開、9:42:33 剛好 45 秒時被切;第二次 9:43:55 一樣)。帳號那欄寫已連線、大腦那欄寫「和帳號伺服器的連線斷了」,看不出是哪一段。 - tunnel.rs:Stream 讀到資料就記(bytes_in、receiving);keep() 有資料進來就算還活著(DEAD_SECS 照舊,但量的是真的沒聲音)。call() 過了自己的時間、但連線還在收資料就繼續等(最多 10 分鐘)。link_serial() 給螢幕知道長連線接回了。 - 帳號伺服器(relay)的長連線同樣:Counted 包住 TcpStream,資料進來就算活著(這台上傳大份資料時不會被那端的 60 秒切掉)。要 make update-server 才生效。relay/clippy.toml:主程式的「HTTP 用戶端只能在 net.rs 建」不套用到 relay。 - 螢幕(mirror_ui):等重試時每 0.2 秒看一次長連線,接回就馬上再要(以前最多等 20 秒,這段時間帳號那欄已經寫已連線);記下上次同步的時間、大小、秒數。 - 設定的大腦那一欄:狀態下面分段寫「這台 ↔ 帳號伺服器」「帳號伺服器 ↔ 大腦(在線上/不在線上,帳號伺服器說的)」「上次同步 …(大小、秒數、KB/s)」。 已驗證:cargo test 571 全過、clippy -D warnings 過;relay cargo test 22 全過。新測試:假的帳號伺服器把一則 64 KB 的訊息分 3 秒慢慢送(允許的沉默設成 1 秒),連線不斷;之後真的沒聲音就斷。把「有資料進來就算活著」拿掉,同一個測試失敗:「已連線」後馬上「連線中斷」——就是早上的情況。 未驗證:真的 Tailscale 中繼線路上走一次(要更新這台的 App 和伺服器)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:41:15 +00:00
let r = match self {
Stream::Plain(t) => t.read(b),
Stream::Tls(s) => s.read(b),
fix: 慢的線上長連線不再被切斷;斷線接回馬上重新同步;大腦那一欄看得出是哪一段 計畫 R7。2026-11-17 早上:Mac mini 經 Tailscale 香港中繼連 nobledesktop(約 100 KB/s),大腦整份資料約 5 MB 要 45–55 秒。這台 45 秒沒收到「一則完整訊息」就算斷線,傳到一半被切、螢幕又從頭要整份,一直循環(實測:連線 9:41:48 開、9:42:33 剛好 45 秒時被切;第二次 9:43:55 一樣)。帳號那欄寫已連線、大腦那欄寫「和帳號伺服器的連線斷了」,看不出是哪一段。 - tunnel.rs:Stream 讀到資料就記(bytes_in、receiving);keep() 有資料進來就算還活著(DEAD_SECS 照舊,但量的是真的沒聲音)。call() 過了自己的時間、但連線還在收資料就繼續等(最多 10 分鐘)。link_serial() 給螢幕知道長連線接回了。 - 帳號伺服器(relay)的長連線同樣:Counted 包住 TcpStream,資料進來就算活著(這台上傳大份資料時不會被那端的 60 秒切掉)。要 make update-server 才生效。relay/clippy.toml:主程式的「HTTP 用戶端只能在 net.rs 建」不套用到 relay。 - 螢幕(mirror_ui):等重試時每 0.2 秒看一次長連線,接回就馬上再要(以前最多等 20 秒,這段時間帳號那欄已經寫已連線);記下上次同步的時間、大小、秒數。 - 設定的大腦那一欄:狀態下面分段寫「這台 ↔ 帳號伺服器」「帳號伺服器 ↔ 大腦(在線上/不在線上,帳號伺服器說的)」「上次同步 …(大小、秒數、KB/s)」。 已驗證:cargo test 571 全過、clippy -D warnings 過;relay cargo test 22 全過。新測試:假的帳號伺服器把一則 64 KB 的訊息分 3 秒慢慢送(允許的沉默設成 1 秒),連線不斷;之後真的沒聲音就斷。把「有資料進來就算活著」拿掉,同一個測試失敗:「已連線」後馬上「連線中斷」——就是早上的情況。 未驗證:真的 Tailscale 中繼線路上走一次(要更新這台的 App 和伺服器)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:41:15 +00:00
};
if let Ok(n) = r {
if n > 0 {
came_in(n);
}
}
fix: 慢的線上長連線不再被切斷;斷線接回馬上重新同步;大腦那一欄看得出是哪一段 計畫 R7。2026-11-17 早上:Mac mini 經 Tailscale 香港中繼連 nobledesktop(約 100 KB/s),大腦整份資料約 5 MB 要 45–55 秒。這台 45 秒沒收到「一則完整訊息」就算斷線,傳到一半被切、螢幕又從頭要整份,一直循環(實測:連線 9:41:48 開、9:42:33 剛好 45 秒時被切;第二次 9:43:55 一樣)。帳號那欄寫已連線、大腦那欄寫「和帳號伺服器的連線斷了」,看不出是哪一段。 - tunnel.rs:Stream 讀到資料就記(bytes_in、receiving);keep() 有資料進來就算還活著(DEAD_SECS 照舊,但量的是真的沒聲音)。call() 過了自己的時間、但連線還在收資料就繼續等(最多 10 分鐘)。link_serial() 給螢幕知道長連線接回了。 - 帳號伺服器(relay)的長連線同樣:Counted 包住 TcpStream,資料進來就算活著(這台上傳大份資料時不會被那端的 60 秒切掉)。要 make update-server 才生效。relay/clippy.toml:主程式的「HTTP 用戶端只能在 net.rs 建」不套用到 relay。 - 螢幕(mirror_ui):等重試時每 0.2 秒看一次長連線,接回就馬上再要(以前最多等 20 秒,這段時間帳號那欄已經寫已連線);記下上次同步的時間、大小、秒數。 - 設定的大腦那一欄:狀態下面分段寫「這台 ↔ 帳號伺服器」「帳號伺服器 ↔ 大腦(在線上/不在線上,帳號伺服器說的)」「上次同步 …(大小、秒數、KB/s)」。 已驗證:cargo test 571 全過、clippy -D warnings 過;relay cargo test 22 全過。新測試:假的帳號伺服器把一則 64 KB 的訊息分 3 秒慢慢送(允許的沉默設成 1 秒),連線不斷;之後真的沒聲音就斷。把「有資料進來就算活著」拿掉,同一個測試失敗:「已連線」後馬上「連線中斷」——就是早上的情況。 未驗證:真的 Tailscale 中繼線路上走一次(要更新這台的 App 和伺服器)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:41:15 +00:00
r
}
}
fix: 慢的線上長連線不再被切斷;斷線接回馬上重新同步;大腦那一欄看得出是哪一段 計畫 R7。2026-11-17 早上:Mac mini 經 Tailscale 香港中繼連 nobledesktop(約 100 KB/s),大腦整份資料約 5 MB 要 45–55 秒。這台 45 秒沒收到「一則完整訊息」就算斷線,傳到一半被切、螢幕又從頭要整份,一直循環(實測:連線 9:41:48 開、9:42:33 剛好 45 秒時被切;第二次 9:43:55 一樣)。帳號那欄寫已連線、大腦那欄寫「和帳號伺服器的連線斷了」,看不出是哪一段。 - tunnel.rs:Stream 讀到資料就記(bytes_in、receiving);keep() 有資料進來就算還活著(DEAD_SECS 照舊,但量的是真的沒聲音)。call() 過了自己的時間、但連線還在收資料就繼續等(最多 10 分鐘)。link_serial() 給螢幕知道長連線接回了。 - 帳號伺服器(relay)的長連線同樣:Counted 包住 TcpStream,資料進來就算活著(這台上傳大份資料時不會被那端的 60 秒切掉)。要 make update-server 才生效。relay/clippy.toml:主程式的「HTTP 用戶端只能在 net.rs 建」不套用到 relay。 - 螢幕(mirror_ui):等重試時每 0.2 秒看一次長連線,接回就馬上再要(以前最多等 20 秒,這段時間帳號那欄已經寫已連線);記下上次同步的時間、大小、秒數。 - 設定的大腦那一欄:狀態下面分段寫「這台 ↔ 帳號伺服器」「帳號伺服器 ↔ 大腦(在線上/不在線上,帳號伺服器說的)」「上次同步 …(大小、秒數、KB/s)」。 已驗證:cargo test 571 全過、clippy -D warnings 過;relay cargo test 22 全過。新測試:假的帳號伺服器把一則 64 KB 的訊息分 3 秒慢慢送(允許的沉默設成 1 秒),連線不斷;之後真的沒聲音就斷。把「有資料進來就算活著」拿掉,同一個測試失敗:「已連線」後馬上「連線中斷」——就是早上的情況。 未驗證:真的 Tailscale 中繼線路上走一次(要更新這台的 App 和伺服器)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:41:15 +00:00
// ---------- what is coming in ----------
// 2026-11-17: over Tailscale's relay in Hong Kong (about 100 KB/s) a full sync of the brain (about
// 5 MB) took 45–55 s. The link counted as dead after 45 s without a *whole* message, so it was cut
// in the middle of the answer — and the screen asked for everything again, and again. Now bytes
// arriving are what keeps it alive, and a call still receiving its answer goes on waiting.
static BYTES_IN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// When bytes last came in (ms since this process started; 0: never).
static LAST_IN_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn since_start_ms() -> u64 {
static START: OnceLock<Instant> = OnceLock::new();
START.get_or_init(Instant::now).elapsed().as_millis() as u64 + 1
}
fn came_in(n: usize) {
BYTES_IN.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed);
LAST_IN_MS.store(since_start_ms(), std::sync::atomic::Ordering::Relaxed);
}
/// Bytes received on the lasting connection since this AnyBot started.
pub fn bytes_in() -> u64 {
BYTES_IN.load(std::sync::atomic::Ordering::Relaxed)
}
/// Whether bytes came in within the last `ms`.
pub fn receiving(ms: u64) -> bool {
let last = LAST_IN_MS.load(std::sync::atomic::Ordering::Relaxed);
last != 0 && since_start_ms().saturating_sub(last) <= ms
}
/// The lasting connection's number (a new one each time it connects; 0 while it isn't up): a
/// screen of a brain asks again the moment it is back.
pub fn link_serial() -> u64 {
link().lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|l| l.serial).unwrap_or(0)
}
/// How long a call keeps waiting past its own time while its answer is still coming in.
const LONGEST_WAIT: Duration = Duration::from_secs(600);
impl Write for Stream {
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
match self {
Stream::Plain(t) => t.write(b),
Stream::Tls(s) => s.write(b),
}
}
fn flush(&mut self) -> std::io::Result<()> {
match self {
Stream::Plain(t) => t.flush(),
Stream::Tls(s) => s.flush(),
}
}
}
/// The root certificates a connection to the account server accepts: the public ones every
/// browser knows (built in), plus the ones this computer trusts itself. So a server on the local
/// network that signs its own certificate (https://10.0.0.25) works here once this computer
/// trusts it, just as it does in the browser. Read once (the system's list takes a moment).
pub fn trusted_roots() -> &'static [rustls::pki_types::CertificateDer<'static>] {
static R: OnceLock<Vec<rustls::pki_types::CertificateDer<'static>>> = OnceLock::new();
R.get_or_init(|| {
let mut v = webpki_root_certs::TLS_SERVER_ROOT_CERTS.to_vec();
// A computer whose list can't be read still has the public ones.
v.extend(rustls_native_certs::load_native_certs().certs);
v
})
}
fn tls_config() -> Arc<rustls::ClientConfig> {
static C: OnceLock<Arc<rustls::ClientConfig>> = OnceLock::new();
C.get_or_init(|| {
let mut roots = rustls::RootCertStore::empty();
roots.add_parsable_certificates(trusted_roots().iter().cloned());
Arc::new(
rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions()
.expect("TLS versions")
.with_root_certificates(roots)
.with_no_client_auth(),
)
})
.clone()
}
fn would_block(e: &tungstenite::Error) -> bool {
matches!(e, tungstenite::Error::Io(io) if matches!(io.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut))
}
/// Why it couldn't connect; `old` = the account server has no WebSocket (use the old way).
struct NoLink {
old: bool,
why: String,
}
fn open(url: &str, token: &str) -> Result<WebSocket<Stream>, NoLink> {
use tungstenite::client::IntoClientRequest;
let fail = |why: &str| NoLink { old: false, why: why.to_string() };
fix: 帳號伺服器的明文規則管到每一個帶密碼或金鑰的連線,在開連線那一刻查;Tailscale 通道認得更準 第三輪(新的獨立審查:兩個早就有的 P1,和幾個 P2): - A:「從帳號備份還原」不經 relay_join,原本 http 檢查管不到。現在帶帳號密碼、配對碼或這台電腦金鑰 的請求都經 relay_post/relay_agent:登入、建立帳號、兩步驗證、還原、配對、通知、網站、成員、備份、 和大腦同步、手腳的指令、還有備用連線(workers)。 - B:http 的帳號伺服器原本只在登入時查一次,之後長連線每次重連都直接連。現在 tunnel::open 每次 (重)連都對要連的位址查,不符合就不連、狀態寫原因、照原本的退避再試;workers 每一輪也一樣。 - 1(DNS 兩次查):選「釘住」——http 的帳號伺服器用自己的 ureq client,resolver 在開連線那一刻對 查到的位址做檢查,只連通過的那幾個(web_fetch 已經用同一種做法);長連線也是查完就連那幾個位址。 名字可以照常用,不必限定 IP 或 *.ts.net。這個 client 不走代理(代理會照它自己的路把明文轉出去)。 - 2:host_port 改用 ureq 自己的 URL 解析(http::Uri),`?`、`#` 後面不是主機;長連線也用它。 model_fetch_here 的私有位址檢查一起修好。 - 3:Tailscale 通道要「叫 tailscale…」或「點對點介面+Tailscale IPv6(fd7a:115c:a1e0::/48)」, Windows 看介面卡名字;PPPoE、電信 NAT、WARP 的 100.x 不算,ip -o addr 的 /32 不再算。ifconfig 找不到 通道(busybox、舊 net-tools 的 inet addr:)時也問 ip。 - 4:沒有 IPv6 的電腦上,*.ts.net 的 IPv6 位址沒有路由就略過、用 IPv4(原本整個拒絕)。 - 5:介面資料 30 秒更新一次,第一次之後都在背景讀,設定頁每一幀拿快取(Windows 不會在 UI 執行緒跑 ipconfig);remote::addresses 也用同一份,不再每一幀跑 ifconfig。 - 6:綁不到連接埠時分開說:位址不在、不准用(1024 以下、系統保留)、被占用、其他;65535 會試,不再說 「65535–65534」。 - 文件照程式寫:SECURITY.md(帳號伺服器的規則管到哪些請求、每次開連線查、釘住、不走代理、一個字的 名字在一般網路上的風險、通道怎麼認)、phone.md、FEATURES.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(652 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。每個回退各做一次、新測試都抓到(10 個):relay_post 不查、長連線開連線不查、workers 用一般 client、resolver 放行一切、host_port 改回手寫切法、任何點對點 100.x 都算通道、沒路由的位址算拒絕、介面過期時在呼叫的執行緒重讀、不准用說成被占用、65535 不試。 實機(verify-anybot,這台 Mac 的 utun4 有 100.84.144.91 和 fd7a:115c:a1e0::d738:905c):phone 區範例旅程 照貼結束碼 0;預設綁定照舊(*:埠、Tailscale 位址 http 200、區網 http 308)。 未驗證: 帳號伺服器的部分沒有接真的帳號伺服器跑——用單元測試走 relay_join、restore、relay_worker、 tunnel::run 和 http client 的真程式碼(scratch 不准帶 ANYBOT_ACCOUNT,也不手寫含金鑰的設定檔); Wi-Fi 自己發 100.64.x 的網路、PPPoE、WARP、busybox 的 ifconfig 只有樣本測試;Linux、Windows 實機沒跑 (Windows 的 ipconfig 只有樣本;cargo check --target x86_64-pc-windows-msvc 卡在 ring 要 Windows SDK 的 C 標頭,cfg(windows) 那幾行沒編譯過);設定頁顯示快取的那一行沒有開視窗看。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:35:43 +00:00
let tls = match (url.starts_with("https://"), url.starts_with("http://")) {
(true, _) => true,
(_, true) => false,
_ => return Err(fail("帳號伺服器的網址不對")),
};
fix: 帳號伺服器的明文規則管到每一個帶密碼或金鑰的連線,在開連線那一刻查;Tailscale 通道認得更準 第三輪(新的獨立審查:兩個早就有的 P1,和幾個 P2): - A:「從帳號備份還原」不經 relay_join,原本 http 檢查管不到。現在帶帳號密碼、配對碼或這台電腦金鑰 的請求都經 relay_post/relay_agent:登入、建立帳號、兩步驗證、還原、配對、通知、網站、成員、備份、 和大腦同步、手腳的指令、還有備用連線(workers)。 - B:http 的帳號伺服器原本只在登入時查一次,之後長連線每次重連都直接連。現在 tunnel::open 每次 (重)連都對要連的位址查,不符合就不連、狀態寫原因、照原本的退避再試;workers 每一輪也一樣。 - 1(DNS 兩次查):選「釘住」——http 的帳號伺服器用自己的 ureq client,resolver 在開連線那一刻對 查到的位址做檢查,只連通過的那幾個(web_fetch 已經用同一種做法);長連線也是查完就連那幾個位址。 名字可以照常用,不必限定 IP 或 *.ts.net。這個 client 不走代理(代理會照它自己的路把明文轉出去)。 - 2:host_port 改用 ureq 自己的 URL 解析(http::Uri),`?`、`#` 後面不是主機;長連線也用它。 model_fetch_here 的私有位址檢查一起修好。 - 3:Tailscale 通道要「叫 tailscale…」或「點對點介面+Tailscale IPv6(fd7a:115c:a1e0::/48)」, Windows 看介面卡名字;PPPoE、電信 NAT、WARP 的 100.x 不算,ip -o addr 的 /32 不再算。ifconfig 找不到 通道(busybox、舊 net-tools 的 inet addr:)時也問 ip。 - 4:沒有 IPv6 的電腦上,*.ts.net 的 IPv6 位址沒有路由就略過、用 IPv4(原本整個拒絕)。 - 5:介面資料 30 秒更新一次,第一次之後都在背景讀,設定頁每一幀拿快取(Windows 不會在 UI 執行緒跑 ipconfig);remote::addresses 也用同一份,不再每一幀跑 ifconfig。 - 6:綁不到連接埠時分開說:位址不在、不准用(1024 以下、系統保留)、被占用、其他;65535 會試,不再說 「65535–65534」。 - 文件照程式寫:SECURITY.md(帳號伺服器的規則管到哪些請求、每次開連線查、釘住、不走代理、一個字的 名字在一般網路上的風險、通道怎麼認)、phone.md、FEATURES.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(652 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。每個回退各做一次、新測試都抓到(10 個):relay_post 不查、長連線開連線不查、workers 用一般 client、resolver 放行一切、host_port 改回手寫切法、任何點對點 100.x 都算通道、沒路由的位址算拒絕、介面過期時在呼叫的執行緒重讀、不准用說成被占用、65535 不試。 實機(verify-anybot,這台 Mac 的 utun4 有 100.84.144.91 和 fd7a:115c:a1e0::d738:905c):phone 區範例旅程 照貼結束碼 0;預設綁定照舊(*:埠、Tailscale 位址 http 200、區網 http 308)。 未驗證: 帳號伺服器的部分沒有接真的帳號伺服器跑——用單元測試走 relay_join、restore、relay_worker、 tunnel::run 和 http client 的真程式碼(scratch 不准帶 ANYBOT_ACCOUNT,也不手寫含金鑰的設定檔); Wi-Fi 自己發 100.64.x 的網路、PPPoE、WARP、busybox 的 ifconfig 只有樣本測試;Linux、Windows 實機沒跑 (Windows 的 ipconfig 只有樣本;cargo check --target x86_64-pc-windows-msvc 卡在 ring 要 Windows SDK 的 C 標頭,cfg(windows) 那幾行沒編譯過);設定頁顯示快取的那一行沒有開視窗看。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:35:43 +00:00
// (Read by the same parser the other requests use: the address checked is the one connected to.)
let (host, port) = crate::remote::host_port(url).ok_or_else(|| fail("帳號伺服器的網址不對"))?;
let host = host.as_str();
let hostport = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let mut addrs: Vec<_> = (host, port).to_socket_addrs().map_err(|_| fail("找不到伺服器:這台電腦可能沒連上網路,或伺服器網址打錯了"))?.collect();
// http:// carries this computer's key in the clear, and whoever answers gets to run things
// here as the account's owner: only to a server off the air (remote::plain_hop), checked on
// every (re)connect against exactly the addresses connected to below. Refused, it says why and
// tries again later, like any connection that failed.
if !tls {
addrs = crate::remote::plain_hop(host, &addrs).map_err(|why| fail(&why))?;
}
// Each address in turn ("localhost" is both ::1 and 127.0.0.1).
let mut last = None;
let mut tcp = None;
for a in &addrs {
match TcpStream::connect_timeout(a, Duration::from_secs(10)) {
Ok(t) => {
tcp = Some(t);
break;
}
Err(e) => last = Some(e.kind()),
}
}
let tcp = tcp.ok_or_else(|| {
fail(match last {
None => "找不到伺服器",
Some(ErrorKind::ConnectionRefused) => "伺服器沒有開(連線被拒絕)",
Some(ErrorKind::TimedOut | ErrorKind::WouldBlock) => "伺服器沒有回應:可能沒開機,或網路把連線擋住了",
_ => "這台電腦沒有連上網路",
})
})?;
let _ = tcp.set_nodelay(true);
let _ = tcp.set_read_timeout(Some(Duration::from_secs(15)));
let _ = tcp.set_write_timeout(Some(Duration::from_secs(30)));
let stream = if tls {
let name = rustls::pki_types::ServerName::try_from(host.to_string()).map_err(|_| fail("帳號伺服器的網址不對"))?;
let conn = rustls::ClientConnection::new(tls_config(), name).map_err(|_| fail("和伺服器的安全連線失敗"))?;
Stream::Tls(Box::new(rustls::StreamOwned::new(conn, tcp)))
} else {
Stream::Plain(tcp)
};
let mut req = format!("{}://{hostport}/relay/host/ws", if tls { "wss" } else { "ws" }).into_client_request().map_err(|_| fail("帳號伺服器的網址不對"))?;
if let Ok(v) = format!("Bearer {token}").parse() {
req.headers_mut().insert("Authorization", v);
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let cfg = tungstenite::protocol::WebSocketConfig::default().max_message_size(Some(64 << 20)).max_frame_size(Some(64 << 20));
match tungstenite::client::client_with_config(req, stream, Some(cfg)) {
Ok((ws, _)) => Ok(ws),
Err(tungstenite::HandshakeError::Failure(tungstenite::Error::Http(r))) => match r.status().as_u16() {
401 | 403 => Err(fail("這台電腦的帳號登入失效了,請到「設定 › 手機與帳號」重新登入")),
400 | 404 | 405 | 426 => Err(NoLink { old: true, why: String::new() }),
_ => Err(fail("帳號伺服器暫時無法使用,稍後會自動再試")),
},
Err(tungstenite::HandshakeError::Failure(e)) if e.to_string().to_lowercase().contains("unknownissuer") => Err(fail("這台電腦還不信任伺服器的憑證(伺服器自己簽的):先在這台電腦安裝並信任它的憑證,再試一次")),
Err(tungstenite::HandshakeError::Failure(e)) if e.to_string().to_lowercase().contains("certificate") || e.to_string().to_lowercase().contains("tls") => Err(fail("和伺服器的安全連線失敗(伺服器的憑證有問題)")),
Err(_) => Err(fail("連線到一半斷掉了")),
}
}
/// Keep the connection for as long as `alive()`. Returns false when the account server has no
/// WebSocket (the caller then uses the old way).
pub fn run(url: &str, token: &str, alive: &dyn Fn() -> bool, status: &dyn Fn(&str)) -> bool {
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
let mut backoff = 1u64;
while alive() {
match open(url, token) {
Err(NoLink { old: true, .. }) => return false,
Err(e) => {
status(&format!("連不上帳號伺服器:{}", e.why));
// Wait, but notice at once when told to stop.
let until = Instant::now() + Duration::from_secs(backoff);
while Instant::now() < until && alive() {
std::thread::sleep(Duration::from_millis(200));
}
backoff = (backoff * 2).min(30);
}
Ok(ws) => {
status("已連線");
let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
/btw 支線、送出先顯示;公測前的安全與資源修正(帳號盜用、灌爆、團隊權限、背景指令與連線的上限和清理) 支線與介面 - /btw:Bot 的分身帶著同一段對話和記憶平行做另一件事,做完回報到主聊天;主線在忙時先判斷會不會衝突,會就等主線做完 - 螢幕一次只給一輪工作操作(所有 Bot 適用) - 「/」只列指令,打字才找這個 Bot 自己的技能 - Bot 工作中送出的訊息立刻以淡色顯示(電腦、手機) - 支線修正:沒被讀到的回報照常進聊天、卡片顯示結果、可回答支線的問題、重新產生不吃掉卡片和回報 安全(中繼伺服器) - 大腦回傳的內容只放行安全類型並加沙箱;團隊改成邀請制;手機不照大腦說的類型開檔案 - 沒登入的請求最多 256 KB、接收中的上傳有總量上限、單一 IP 連線上限、常駐連線另計 - 登入次數加上每帳號上限並先計數再驗證;密碼雜湊同時最多 4 個 - 新增電腦要 15 分鐘內剛登入;可改密碼;註冊限速,有邀請碼時第一個帳號也要 - 發布的網站不能送表單和對外連線;Caddy 加安全標頭 安全(大腦) - 區網(明文)不能打開直接操作、加一律允許規則、加連接器;區網登入 30 天沒用失效 - 團隊成員只看得到勾選「團隊成員可以使用」的 Bot - 沒有角色的請求一律拒絕;環境變數的金鑰只送官方位址 資源 - 中繼:小變動每分鐘寫一次、回應有總時限、每台電腦呼叫上限、網站/登入/電腦/配對碼上限、資料檔壞掉不啟動 - App:伺服器回錯誤和連線秒斷時逐次退避;區網看螢幕偵測斷線 - 背景指令:刪 Bot 和支線結束時停掉、最多 24 個、結束 10 分鐘後移除、可用 stop 停掉 - 截圖在收起和歸檔時釋放;刪 Bot 時刪附件和對照表;每晚清稽核資料和暫存;手機圖片快取上限 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3a7riWESpv471gDgC
2026-11-13 15:36:34 +00:00
let since = Instant::now();
keep(ws, serial, alive);
if alive() {
status("連線中斷,正在重新連線…");
}
/btw 支線、送出先顯示;公測前的安全與資源修正(帳號盜用、灌爆、團隊權限、背景指令與連線的上限和清理) 支線與介面 - /btw:Bot 的分身帶著同一段對話和記憶平行做另一件事,做完回報到主聊天;主線在忙時先判斷會不會衝突,會就等主線做完 - 螢幕一次只給一輪工作操作(所有 Bot 適用) - 「/」只列指令,打字才找這個 Bot 自己的技能 - Bot 工作中送出的訊息立刻以淡色顯示(電腦、手機) - 支線修正:沒被讀到的回報照常進聊天、卡片顯示結果、可回答支線的問題、重新產生不吃掉卡片和回報 安全(中繼伺服器) - 大腦回傳的內容只放行安全類型並加沙箱;團隊改成邀請制;手機不照大腦說的類型開檔案 - 沒登入的請求最多 256 KB、接收中的上傳有總量上限、單一 IP 連線上限、常駐連線另計 - 登入次數加上每帳號上限並先計數再驗證;密碼雜湊同時最多 4 個 - 新增電腦要 15 分鐘內剛登入;可改密碼;註冊限速,有邀請碼時第一個帳號也要 - 發布的網站不能送表單和對外連線;Caddy 加安全標頭 安全(大腦) - 區網(明文)不能打開直接操作、加一律允許規則、加連接器;區網登入 30 天沒用失效 - 團隊成員只看得到勾選「團隊成員可以使用」的 Bot - 沒有角色的請求一律拒絕;環境變數的金鑰只送官方位址 資源 - 中繼:小變動每分鐘寫一次、回應有總時限、每台電腦呼叫上限、網站/登入/電腦/配對碼上限、資料檔壞掉不啟動 - App:伺服器回錯誤和連線秒斷時逐次退避;區網看螢幕偵測斷線 - 背景指令:刪 Bot 和支線結束時停掉、最多 24 個、結束 10 分鐘後移除、可用 stop 停掉 - 截圖在收起和歸檔時釋放;刪 Bot 時刪附件和對照表;每晚清稽核資料和暫存;手機圖片快取上限 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3a7riWESpv471gDgC
2026-11-13 15:36:34 +00:00
// A link that held is a fresh start; one the server took and dropped at once
// waits longer each time (it used to reconnect flat out). A moment apart for
// each computer, so they don't all come back in the same instant after the
// server restarts.
backoff = if since.elapsed() > Duration::from_secs(30) { 1 } else { (backoff * 2).min(30) };
let apart = Duration::from_millis(500 + (std::process::id() as u64 * 7919 + serial * 131) % 1500);
let until = Instant::now() + Duration::from_secs(backoff) + apart;
while Instant::now() < until && alive() {
std::thread::sleep(Duration::from_millis(200));
}
}
}
}
true
}
fn keep(mut ws: WebSocket<Stream>, serial: u64, alive: &dyn Fn() -> bool) {
let mut pace = wire::Pace::new();
let (tx, rx) = channel::<Vec<u8>>();
let calls: Calls = Arc::default();
*link().lock().unwrap() = Some(Link { tx: tx.clone(), calls: calls.clone(), serial });
let s = crate::remote::hub().settings();
let _ = tx.send(wire::pack(&json!({"t": "hello", "brain": s.brain_id, "hands": s.device_link}), &[]));
let (mut heard, mut pinged) = (Instant::now(), Instant::now());
fix: 慢的線上長連線不再被切斷;斷線接回馬上重新同步;大腦那一欄看得出是哪一段 計畫 R7。2026-11-17 早上:Mac mini 經 Tailscale 香港中繼連 nobledesktop(約 100 KB/s),大腦整份資料約 5 MB 要 45–55 秒。這台 45 秒沒收到「一則完整訊息」就算斷線,傳到一半被切、螢幕又從頭要整份,一直循環(實測:連線 9:41:48 開、9:42:33 剛好 45 秒時被切;第二次 9:43:55 一樣)。帳號那欄寫已連線、大腦那欄寫「和帳號伺服器的連線斷了」,看不出是哪一段。 - tunnel.rs:Stream 讀到資料就記(bytes_in、receiving);keep() 有資料進來就算還活著(DEAD_SECS 照舊,但量的是真的沒聲音)。call() 過了自己的時間、但連線還在收資料就繼續等(最多 10 分鐘)。link_serial() 給螢幕知道長連線接回了。 - 帳號伺服器(relay)的長連線同樣:Counted 包住 TcpStream,資料進來就算活著(這台上傳大份資料時不會被那端的 60 秒切掉)。要 make update-server 才生效。relay/clippy.toml:主程式的「HTTP 用戶端只能在 net.rs 建」不套用到 relay。 - 螢幕(mirror_ui):等重試時每 0.2 秒看一次長連線,接回就馬上再要(以前最多等 20 秒,這段時間帳號那欄已經寫已連線);記下上次同步的時間、大小、秒數。 - 設定的大腦那一欄:狀態下面分段寫「這台 ↔ 帳號伺服器」「帳號伺服器 ↔ 大腦(在線上/不在線上,帳號伺服器說的)」「上次同步 …(大小、秒數、KB/s)」。 已驗證:cargo test 571 全過、clippy -D warnings 過;relay cargo test 22 全過。新測試:假的帳號伺服器把一則 64 KB 的訊息分 3 秒慢慢送(允許的沉默設成 1 秒),連線不斷;之後真的沒聲音就斷。把「有資料進來就算活著」拿掉,同一個測試失敗:「已連線」後馬上「連線中斷」——就是早上的情況。 未驗證:真的 Tailscale 中繼線路上走一次(要更新這台的 App 和伺服器)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:41:15 +00:00
let mut got = bytes_in();
'live: while alive() {
pace.tune(ws.get_ref().tcp());
match ws.read() {
Ok(Message::Binary(b)) => {
heard = Instant::now();
pace.moved();
if let Some((head, body)) = wire::unpack(&b) {
// The relay says this machine was unregistered (signed out): stop for good.
if head["t"] == "bye" {
break;
}
on_frame(head, body, &tx, &calls);
}
}
Ok(Message::Close(_)) => break,
Ok(_) => heard = Instant::now(),
Err(e) if would_block(&e) => {}
Err(_) => break,
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
for _ in 0..32 {
let Ok(f) = rx.try_recv() else { break };
pace.moved();
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
match ws.write(Message::Binary(f.into())) {
Ok(()) => {}
Err(e) if would_block(&e) => break,
Err(_) => break 'live,
}
}
if pinged.elapsed().as_secs() >= PING_SECS {
pinged = Instant::now();
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
match ws.write(Message::Ping(Vec::new().into())) {
Ok(()) => {}
Err(e) if would_block(&e) => {}
Err(_) => break,
}
}
match ws.flush() {
Err(e) if !would_block(&e) => break,
_ => {}
}
fix: 慢的線上長連線不再被切斷;斷線接回馬上重新同步;大腦那一欄看得出是哪一段 計畫 R7。2026-11-17 早上:Mac mini 經 Tailscale 香港中繼連 nobledesktop(約 100 KB/s),大腦整份資料約 5 MB 要 45–55 秒。這台 45 秒沒收到「一則完整訊息」就算斷線,傳到一半被切、螢幕又從頭要整份,一直循環(實測:連線 9:41:48 開、9:42:33 剛好 45 秒時被切;第二次 9:43:55 一樣)。帳號那欄寫已連線、大腦那欄寫「和帳號伺服器的連線斷了」,看不出是哪一段。 - tunnel.rs:Stream 讀到資料就記(bytes_in、receiving);keep() 有資料進來就算還活著(DEAD_SECS 照舊,但量的是真的沒聲音)。call() 過了自己的時間、但連線還在收資料就繼續等(最多 10 分鐘)。link_serial() 給螢幕知道長連線接回了。 - 帳號伺服器(relay)的長連線同樣:Counted 包住 TcpStream,資料進來就算活著(這台上傳大份資料時不會被那端的 60 秒切掉)。要 make update-server 才生效。relay/clippy.toml:主程式的「HTTP 用戶端只能在 net.rs 建」不套用到 relay。 - 螢幕(mirror_ui):等重試時每 0.2 秒看一次長連線,接回就馬上再要(以前最多等 20 秒,這段時間帳號那欄已經寫已連線);記下上次同步的時間、大小、秒數。 - 設定的大腦那一欄:狀態下面分段寫「這台 ↔ 帳號伺服器」「帳號伺服器 ↔ 大腦(在線上/不在線上,帳號伺服器說的)」「上次同步 …(大小、秒數、KB/s)」。 已驗證:cargo test 571 全過、clippy -D warnings 過;relay cargo test 22 全過。新測試:假的帳號伺服器把一則 64 KB 的訊息分 3 秒慢慢送(允許的沉默設成 1 秒),連線不斷;之後真的沒聲音就斷。把「有資料進來就算活著」拿掉,同一個測試失敗:「已連線」後馬上「連線中斷」——就是早上的情況。 未驗證:真的 Tailscale 中繼線路上走一次(要更新這台的 App 和伺服器)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:41:15 +00:00
// Alive while anything comes in, a big answer in the middle of arriving included.
let now_got = bytes_in();
if now_got != got {
got = now_got;
heard = Instant::now();
}
if heard.elapsed().as_millis() as u64 >= DEAD_MS.load(std::sync::atomic::Ordering::Relaxed) {
break;
}
}
let _ = ws.close(None);
let _ = ws.flush();
let mut l = link().lock().unwrap();
if l.as_ref().map(|l| l.serial) == Some(serial) {
*l = None;
}
drop(l);
People watch and help on the bots' computer through VNC (noVNC), carried by the account server The core: the bot works the computer; a person watches it like a colleague, and takes over when it needs them. VNC is made for that (only what changed, every mouse move and key, touch on phones), so the pictures sent one by one go, and with them their own input path. - vnc.rs: a VNC proxy to the box's x11vnc through one docker exec (a Python bridge that ends with either side). It signs in to the box with the box's own password (its VNC_PASSWORD) and offers the viewer no password, so the password never leaves the brain. The person's clicks and keys make the bot's steps wait until 8 s after they stop; text typed in the viewer's box (any language) is pasted in the box. - Account server: /screen (the viewer page) and /novnc.js (noVNC 1.6.0, MPL-2.0, bundled); /relay/vnc/<host> takes the browser's WebSocket (account session, or a 10-minute ticket the app asks for with POST /relay/screen-ticket; owners and admins) and carries it over that AnyBot's lasting connection (vopen / vdata / vtext / vclose). Both ends of that connection wait 2 ms instead of 40 ms to read while things move: a request and its answer took up to 160 ms more than needed. - Phone page: 看 Bot 的電腦 and 接管 open the viewer page (also on the local network: /api/vnc on the AnyBot's own phone server). This Mac's own screen moved to the ⋯ menu. - Mac app: 看畫面 opens the viewer in the browser (a screen of a brain: the brain's computer by ticket; else this computer's box, noVNC straight from it). The in-app picture viewer, the live JPEG stream, the person's click/move/scroll/key endpoints and the input shell are gone. - Opening a Mac app uses LaunchServices (`open -a`): agent-desktop's launch waited on the window through accessibility and failed without 輔助使用 now and then. Measured on this Mac (made-up account, local relay + headless brain + the real box): viewer signed in in 0.4–0.7 s, a request and its answer through relay + brain + box 25–58 ms median; headless Chrome shows the desktop live in /screen. remote_e2e 28/28 ×2, 149 unit tests, relay 11. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:05:44 +00:00
streams().lock().unwrap().clear();
// Whoever waits on an answer hears now, not after a timeout.
for (_, w) in calls.lock().unwrap().drain() {
let _ = w.send(Err(CUT.into()));
}
}
People watch and help on the bots' computer through VNC (noVNC), carried by the account server The core: the bot works the computer; a person watches it like a colleague, and takes over when it needs them. VNC is made for that (only what changed, every mouse move and key, touch on phones), so the pictures sent one by one go, and with them their own input path. - vnc.rs: a VNC proxy to the box's x11vnc through one docker exec (a Python bridge that ends with either side). It signs in to the box with the box's own password (its VNC_PASSWORD) and offers the viewer no password, so the password never leaves the brain. The person's clicks and keys make the bot's steps wait until 8 s after they stop; text typed in the viewer's box (any language) is pasted in the box. - Account server: /screen (the viewer page) and /novnc.js (noVNC 1.6.0, MPL-2.0, bundled); /relay/vnc/<host> takes the browser's WebSocket (account session, or a 10-minute ticket the app asks for with POST /relay/screen-ticket; owners and admins) and carries it over that AnyBot's lasting connection (vopen / vdata / vtext / vclose). Both ends of that connection wait 2 ms instead of 40 ms to read while things move: a request and its answer took up to 160 ms more than needed. - Phone page: 看 Bot 的電腦 and 接管 open the viewer page (also on the local network: /api/vnc on the AnyBot's own phone server). This Mac's own screen moved to the ⋯ menu. - Mac app: 看畫面 opens the viewer in the browser (a screen of a brain: the brain's computer by ticket; else this computer's box, noVNC straight from it). The in-app picture viewer, the live JPEG stream, the person's click/move/scroll/key endpoints and the input shell are gone. - Opening a Mac app uses LaunchServices (`open -a`): agent-desktop's launch waited on the window through accessibility and failed without 輔助使用 now and then. Measured on this Mac (made-up account, local relay + headless brain + the real box): viewer signed in in 0.4–0.7 s, a request and its answer through relay + brain + box 25–58 ms median; headless Chrome shows the desktop live in /screen. remote_e2e 28/28 ×2, 149 unit tests, relay 11. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:05:44 +00:00
/// People watching the bots' computer through the account server: one VNC stream each, by the
/// relay's stream id (vopen / vdata / vtext / vclose).
fn streams() -> &'static Mutex<HashMap<String, crate::vnc::Session>> {
static S: OnceLock<Mutex<HashMap<String, crate::vnc::Session>>> = OnceLock::new();
S.get_or_init(Default::default)
}
/// The screen viewer `sid` is connected to (None when it isn't: gone, or not open yet).
fn typing_screen(sid: &str) -> Option<String> {
streams().lock().unwrap_or_else(|e| e.into_inner()).get(sid).map(|s| s.screen().to_string())
}
feat: 每個 Bot 一個螢幕——Bot 的電腦上各有自己的螢幕和瀏覽器,支線另開暫時的螢幕,右側面板和「全部螢幕」看得到每一個 照 Grok Bot 的分法:一台電腦、每個 Bot 一個螢幕,大家同時做互不干擾。使用者自己的電腦只有一個實體螢幕,還是一次一個 Bot。 - box:anybot-screen(up/down/list/reap)開關每個 Bot 的螢幕,同時最多 6 個,閒置 10 分鐘關掉;browser 每個螢幕自己的設定檔(第一次從共用的複製登入;支線 <key>-t<n> 從主線那份複製,關掉時刪掉);start.sh 給每個螢幕 VNC token;Bot 電腦升到版本 10 - cloudbox:每個螢幕有自己的狀態(編號、尺寸、貼上檔、瀏覽器埠),指令開的視窗出現在它的 Bot 的螢幕上;branch_screen、close_screen、open_screens、thumbnail_of - agent:在 Bot 的電腦上,一輪用它自己的螢幕(支線用暫時的),佔用照螢幕算 - 支線結束時關掉它的暫時螢幕 - 畫面:右側「電腦」顯示目前 Bot 的螢幕;群組跟著正在回答的成員,「成員」卡片點小畫面就固定顯示那個成員;「全部螢幕(N)」一格一個螢幕;接管時只停那個 Bot;手機和中繼帶上要看哪個 Bot 的螢幕 - 群組和支線的系統指示:看不到彼此開著的網頁,交棒時寫網址或檔案路徑 - 功能地圖:screen、team、computers、browser Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha4mzWbjJAWAsDVuBun
2026-11-15 08:12:09 +00:00
fn on_stream(kind: &str, sid: String, bot: String, body: Vec<u8>, tx: &Sender<Vec<u8>>) {
People watch and help on the bots' computer through VNC (noVNC), carried by the account server The core: the bot works the computer; a person watches it like a colleague, and takes over when it needs them. VNC is made for that (only what changed, every mouse move and key, touch on phones), so the pictures sent one by one go, and with them their own input path. - vnc.rs: a VNC proxy to the box's x11vnc through one docker exec (a Python bridge that ends with either side). It signs in to the box with the box's own password (its VNC_PASSWORD) and offers the viewer no password, so the password never leaves the brain. The person's clicks and keys make the bot's steps wait until 8 s after they stop; text typed in the viewer's box (any language) is pasted in the box. - Account server: /screen (the viewer page) and /novnc.js (noVNC 1.6.0, MPL-2.0, bundled); /relay/vnc/<host> takes the browser's WebSocket (account session, or a 10-minute ticket the app asks for with POST /relay/screen-ticket; owners and admins) and carries it over that AnyBot's lasting connection (vopen / vdata / vtext / vclose). Both ends of that connection wait 2 ms instead of 40 ms to read while things move: a request and its answer took up to 160 ms more than needed. - Phone page: 看 Bot 的電腦 and 接管 open the viewer page (also on the local network: /api/vnc on the AnyBot's own phone server). This Mac's own screen moved to the ⋯ menu. - Mac app: 看畫面 opens the viewer in the browser (a screen of a brain: the brain's computer by ticket; else this computer's box, noVNC straight from it). The in-app picture viewer, the live JPEG stream, the person's click/move/scroll/key endpoints and the input shell are gone. - Opening a Mac app uses LaunchServices (`open -a`): agent-desktop's launch waited on the window through accessibility and failed without 輔助使用 now and then. Measured on this Mac (made-up account, local relay + headless brain + the real box): viewer signed in in 0.4–0.7 s, a request and its answer through relay + brain + box 25–58 ms median; headless Chrome shows the desktop live in /screen. remote_e2e 28/28 ×2, 149 unit tests, relay 11. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:05:44 +00:00
let send = {
let (tx, sid) = (tx.clone(), sid.clone());
move |b: &[u8]| tx.send(wire::pack(&json!({"t": "vdata", "sid": sid}), b)).is_ok()
};
let close = {
let (tx, sid) = (tx.clone(), sid.clone());
move |why: &str| {
streams().lock().unwrap().remove(&sid);
let _ = tx.send(wire::pack(&json!({"t": "vclose", "sid": sid, "why": why}), &[]));
}
};
match kind {
"vopen" => {
std::thread::spawn(move || {
let out = {
let (send, close) = (send.clone(), close.clone());
move |b: &[u8]| if b.is_empty() { close("這台電腦的畫面關了"); false } else { send(b) }
};
feat: 每個 Bot 一個螢幕——Bot 的電腦上各有自己的螢幕和瀏覽器,支線另開暫時的螢幕,右側面板和「全部螢幕」看得到每一個 照 Grok Bot 的分法:一台電腦、每個 Bot 一個螢幕,大家同時做互不干擾。使用者自己的電腦只有一個實體螢幕,還是一次一個 Bot。 - box:anybot-screen(up/down/list/reap)開關每個 Bot 的螢幕,同時最多 6 個,閒置 10 分鐘關掉;browser 每個螢幕自己的設定檔(第一次從共用的複製登入;支線 <key>-t<n> 從主線那份複製,關掉時刪掉);start.sh 給每個螢幕 VNC token;Bot 電腦升到版本 10 - cloudbox:每個螢幕有自己的狀態(編號、尺寸、貼上檔、瀏覽器埠),指令開的視窗出現在它的 Bot 的螢幕上;branch_screen、close_screen、open_screens、thumbnail_of - agent:在 Bot 的電腦上,一輪用它自己的螢幕(支線用暫時的),佔用照螢幕算 - 支線結束時關掉它的暫時螢幕 - 畫面:右側「電腦」顯示目前 Bot 的螢幕;群組跟著正在回答的成員,「成員」卡片點小畫面就固定顯示那個成員;「全部螢幕(N)」一格一個螢幕;接管時只停那個 Bot;手機和中繼帶上要看哪個 Bot 的螢幕 - 群組和支線的系統指示:看不到彼此開著的網頁,交棒時寫網址或檔案路徑 - 功能地圖:screen、team、computers、browser Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha4mzWbjJAWAsDVuBun
2026-11-15 08:12:09 +00:00
// 每個 Bot 一個螢幕: the bot the viewer was opened for (an older account server
// names none: the shared screen).
let screen = crate::cloudbox::screen_for_bot(&bot);
match crate::vnc::open_on(&screen, out) {
People watch and help on the bots' computer through VNC (noVNC), carried by the account server The core: the bot works the computer; a person watches it like a colleague, and takes over when it needs them. VNC is made for that (only what changed, every mouse move and key, touch on phones), so the pictures sent one by one go, and with them their own input path. - vnc.rs: a VNC proxy to the box's x11vnc through one docker exec (a Python bridge that ends with either side). It signs in to the box with the box's own password (its VNC_PASSWORD) and offers the viewer no password, so the password never leaves the brain. The person's clicks and keys make the bot's steps wait until 8 s after they stop; text typed in the viewer's box (any language) is pasted in the box. - Account server: /screen (the viewer page) and /novnc.js (noVNC 1.6.0, MPL-2.0, bundled); /relay/vnc/<host> takes the browser's WebSocket (account session, or a 10-minute ticket the app asks for with POST /relay/screen-ticket; owners and admins) and carries it over that AnyBot's lasting connection (vopen / vdata / vtext / vclose). Both ends of that connection wait 2 ms instead of 40 ms to read while things move: a request and its answer took up to 160 ms more than needed. - Phone page: 看 Bot 的電腦 and 接管 open the viewer page (also on the local network: /api/vnc on the AnyBot's own phone server). This Mac's own screen moved to the ⋯ menu. - Mac app: 看畫面 opens the viewer in the browser (a screen of a brain: the brain's computer by ticket; else this computer's box, noVNC straight from it). The in-app picture viewer, the live JPEG stream, the person's click/move/scroll/key endpoints and the input shell are gone. - Opening a Mac app uses LaunchServices (`open -a`): agent-desktop's launch waited on the window through accessibility and failed without 輔助使用 now and then. Measured on this Mac (made-up account, local relay + headless brain + the real box): viewer signed in in 0.4–0.7 s, a request and its answer through relay + brain + box 25–58 ms median; headless Chrome shows the desktop live in /screen. remote_e2e 28/28 ×2, 149 unit tests, relay 11. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:05:44 +00:00
Ok(s) => {
streams().lock().unwrap().insert(sid, s);
// Only now: the viewer answers this at once.
if !send(crate::vnc::GREETING) {
close("");
}
}
Err(e) => close(&e),
}
});
}
"vdata" => {
let mut all = streams().lock().unwrap();
let ok = all.get_mut(&sid).map(|s| s.feed(&body, &send)).unwrap_or(false);
drop(all);
if !ok {
close("這台電腦的畫面關了");
}
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
"vtext" => {
// 每個 Bot 一個螢幕: the words go to the screen this viewer is connected to, as its
// session knows it (a bot's own, or the shared one when that bot had none open) — not
// the bot's screen asked again: in a group chat that follows whoever speaks, and a
// bot's screen that isn't open would be made for the words. No viewer, no typing.
if let Some(screen) = typing_screen(&sid) {
let _ = std::thread::Builder::new().spawn(move || {
crate::vnc::person_typed(&String::from_utf8_lossy(&body), &screen);
});
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
}
People watch and help on the bots' computer through VNC (noVNC), carried by the account server The core: the bot works the computer; a person watches it like a colleague, and takes over when it needs them. VNC is made for that (only what changed, every mouse move and key, touch on phones), so the pictures sent one by one go, and with them their own input path. - vnc.rs: a VNC proxy to the box's x11vnc through one docker exec (a Python bridge that ends with either side). It signs in to the box with the box's own password (its VNC_PASSWORD) and offers the viewer no password, so the password never leaves the brain. The person's clicks and keys make the bot's steps wait until 8 s after they stop; text typed in the viewer's box (any language) is pasted in the box. - Account server: /screen (the viewer page) and /novnc.js (noVNC 1.6.0, MPL-2.0, bundled); /relay/vnc/<host> takes the browser's WebSocket (account session, or a 10-minute ticket the app asks for with POST /relay/screen-ticket; owners and admins) and carries it over that AnyBot's lasting connection (vopen / vdata / vtext / vclose). Both ends of that connection wait 2 ms instead of 40 ms to read while things move: a request and its answer took up to 160 ms more than needed. - Phone page: 看 Bot 的電腦 and 接管 open the viewer page (also on the local network: /api/vnc on the AnyBot's own phone server). This Mac's own screen moved to the ⋯ menu. - Mac app: 看畫面 opens the viewer in the browser (a screen of a brain: the brain's computer by ticket; else this computer's box, noVNC straight from it). The in-app picture viewer, the live JPEG stream, the person's click/move/scroll/key endpoints and the input shell are gone. - Opening a Mac app uses LaunchServices (`open -a`): agent-desktop's launch waited on the window through accessibility and failed without 輔助使用 now and then. Measured on this Mac (made-up account, local relay + headless brain + the real box): viewer signed in in 0.4–0.7 s, a request and its answer through relay + brain + box 25–58 ms median; headless Chrome shows the desktop live in /screen. remote_e2e 28/28 ×2, 149 unit tests, relay 11. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:05:44 +00:00
_ => {
streams().lock().unwrap().remove(&sid);
}
}
}
fn on_frame(head: Value, body: Vec<u8>, tx: &Sender<Vec<u8>>, calls: &Calls) {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
use std::sync::atomic::{AtomicUsize, Ordering};
static ACTIVE_JOBS: AtomicUsize = AtomicUsize::new(0);
struct JobSlot;
impl Drop for JobSlot {
fn drop(&mut self) {
ACTIVE_JOBS.fetch_sub(1, Ordering::SeqCst);
}
}
People watch and help on the bots' computer through VNC (noVNC), carried by the account server The core: the bot works the computer; a person watches it like a colleague, and takes over when it needs them. VNC is made for that (only what changed, every mouse move and key, touch on phones), so the pictures sent one by one go, and with them their own input path. - vnc.rs: a VNC proxy to the box's x11vnc through one docker exec (a Python bridge that ends with either side). It signs in to the box with the box's own password (its VNC_PASSWORD) and offers the viewer no password, so the password never leaves the brain. The person's clicks and keys make the bot's steps wait until 8 s after they stop; text typed in the viewer's box (any language) is pasted in the box. - Account server: /screen (the viewer page) and /novnc.js (noVNC 1.6.0, MPL-2.0, bundled); /relay/vnc/<host> takes the browser's WebSocket (account session, or a 10-minute ticket the app asks for with POST /relay/screen-ticket; owners and admins) and carries it over that AnyBot's lasting connection (vopen / vdata / vtext / vclose). Both ends of that connection wait 2 ms instead of 40 ms to read while things move: a request and its answer took up to 160 ms more than needed. - Phone page: 看 Bot 的電腦 and 接管 open the viewer page (also on the local network: /api/vnc on the AnyBot's own phone server). This Mac's own screen moved to the ⋯ menu. - Mac app: 看畫面 opens the viewer in the browser (a screen of a brain: the brain's computer by ticket; else this computer's box, noVNC straight from it). The in-app picture viewer, the live JPEG stream, the person's click/move/scroll/key endpoints and the input shell are gone. - Opening a Mac app uses LaunchServices (`open -a`): agent-desktop's launch waited on the window through accessibility and failed without 輔助使用 now and then. Measured on this Mac (made-up account, local relay + headless brain + the real box): viewer signed in in 0.4–0.7 s, a request and its answer through relay + brain + box 25–58 ms median; headless Chrome shows the desktop live in /screen. remote_e2e 28/28 ×2, 149 unit tests, relay 11. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:05:44 +00:00
let t = head["t"].as_str().unwrap_or("");
if matches!(t, "vopen" | "vdata" | "vtext" | "vclose") {
feat: 每個 Bot 一個螢幕——Bot 的電腦上各有自己的螢幕和瀏覽器,支線另開暫時的螢幕,右側面板和「全部螢幕」看得到每一個 照 Grok Bot 的分法:一台電腦、每個 Bot 一個螢幕,大家同時做互不干擾。使用者自己的電腦只有一個實體螢幕,還是一次一個 Bot。 - box:anybot-screen(up/down/list/reap)開關每個 Bot 的螢幕,同時最多 6 個,閒置 10 分鐘關掉;browser 每個螢幕自己的設定檔(第一次從共用的複製登入;支線 <key>-t<n> 從主線那份複製,關掉時刪掉);start.sh 給每個螢幕 VNC token;Bot 電腦升到版本 10 - cloudbox:每個螢幕有自己的狀態(編號、尺寸、貼上檔、瀏覽器埠),指令開的視窗出現在它的 Bot 的螢幕上;branch_screen、close_screen、open_screens、thumbnail_of - agent:在 Bot 的電腦上,一輪用它自己的螢幕(支線用暫時的),佔用照螢幕算 - 支線結束時關掉它的暫時螢幕 - 畫面:右側「電腦」顯示目前 Bot 的螢幕;群組跟著正在回答的成員,「成員」卡片點小畫面就固定顯示那個成員;「全部螢幕(N)」一格一個螢幕;接管時只停那個 Bot;手機和中繼帶上要看哪個 Bot 的螢幕 - 群組和支線的系統指示:看不到彼此開著的網頁,交棒時寫網址或檔案路徑 - 功能地圖:screen、team、computers、browser Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha4mzWbjJAWAsDVuBun
2026-11-15 08:12:09 +00:00
return on_stream(t, head["sid"].as_str().unwrap_or("").to_string(), head["bot"].as_str().unwrap_or("").to_string(), body, tx);
People watch and help on the bots' computer through VNC (noVNC), carried by the account server The core: the bot works the computer; a person watches it like a colleague, and takes over when it needs them. VNC is made for that (only what changed, every mouse move and key, touch on phones), so the pictures sent one by one go, and with them their own input path. - vnc.rs: a VNC proxy to the box's x11vnc through one docker exec (a Python bridge that ends with either side). It signs in to the box with the box's own password (its VNC_PASSWORD) and offers the viewer no password, so the password never leaves the brain. The person's clicks and keys make the bot's steps wait until 8 s after they stop; text typed in the viewer's box (any language) is pasted in the box. - Account server: /screen (the viewer page) and /novnc.js (noVNC 1.6.0, MPL-2.0, bundled); /relay/vnc/<host> takes the browser's WebSocket (account session, or a 10-minute ticket the app asks for with POST /relay/screen-ticket; owners and admins) and carries it over that AnyBot's lasting connection (vopen / vdata / vtext / vclose). Both ends of that connection wait 2 ms instead of 40 ms to read while things move: a request and its answer took up to 160 ms more than needed. - Phone page: 看 Bot 的電腦 and 接管 open the viewer page (also on the local network: /api/vnc on the AnyBot's own phone server). This Mac's own screen moved to the ⋯ menu. - Mac app: 看畫面 opens the viewer in the browser (a screen of a brain: the brain's computer by ticket; else this computer's box, noVNC straight from it). The in-app picture viewer, the live JPEG stream, the person's click/move/scroll/key endpoints and the input shell are gone. - Opening a Mac app uses LaunchServices (`open -a`): agent-desktop's launch waited on the window through accessibility and failed without 輔助使用 now and then. Measured on this Mac (made-up account, local relay + headless brain + the real box): viewer signed in in 0.4–0.7 s, a request and its answer through relay + brain + box 25–58 ms median; headless Chrome shows the desktop live in /screen. remote_e2e 28/28 ×2, 149 unit tests, relay 11. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:05:44 +00:00
}
match t {
"job" => {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let id_now = head["id"].as_str().unwrap_or("").to_string();
if ACTIVE_JOBS.load(Ordering::SeqCst) >= MAX_ACTIVE_JOBS {
let err = crate::httpd::Resp::error(503, "這台 AnyBot 忙碌中,請稍後再試");
let _ = tx.send(wire::pack(&json!({"t": "reply", "id": id_now, "status": err.status, "ctype": err.ctype, "headers": err.headers, "z": false}), &err.body));
return;
}
ACTIVE_JOBS.fetch_add(1, Ordering::SeqCst);
let slot = JobSlot;
let tx = tx.clone();
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let _ = std::thread::Builder::new().spawn(move || {
let _slot = slot;
let s = |k: &str| head[k].as_str().unwrap_or("").to_string();
let id = s("id");
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let body = if head["z"].as_bool().unwrap_or(false) {
match unzip(&body) {
Ok(b) => b,
Err(e) => {
let err = crate::httpd::Resp::error(400, &e);
let _ = tx.send(wire::pack(&json!({"t": "reply", "id": id, "status": err.status, "ctype": err.ctype, "headers": err.headers, "z": false}), &err.body));
return;
}
}
} else {
body
};
let req = Req {
method: s("method"),
path: s("path"),
query: head["query"].as_object().map(|o| o.iter().map(|(k, v)| (k.clone(), v.as_str().unwrap_or("").to_string())).collect()).unwrap_or_default(),
/btw 支線、送出先顯示;公測前的安全與資源修正(帳號盜用、灌爆、團隊權限、背景指令與連線的上限和清理) 支線與介面 - /btw:Bot 的分身帶著同一段對話和記憶平行做另一件事,做完回報到主聊天;主線在忙時先判斷會不會衝突,會就等主線做完 - 螢幕一次只給一輪工作操作(所有 Bot 適用) - 「/」只列指令,打字才找這個 Bot 自己的技能 - Bot 工作中送出的訊息立刻以淡色顯示(電腦、手機) - 支線修正:沒被讀到的回報照常進聊天、卡片顯示結果、可回答支線的問題、重新產生不吃掉卡片和回報 安全(中繼伺服器) - 大腦回傳的內容只放行安全類型並加沙箱;團隊改成邀請制;手機不照大腦說的類型開檔案 - 沒登入的請求最多 256 KB、接收中的上傳有總量上限、單一 IP 連線上限、常駐連線另計 - 登入次數加上每帳號上限並先計數再驗證;密碼雜湊同時最多 4 個 - 新增電腦要 15 分鐘內剛登入;可改密碼;註冊限速,有邀請碼時第一個帳號也要 - 發布的網站不能送表單和對外連線;Caddy 加安全標頭 安全(大腦) - 區網(明文)不能打開直接操作、加一律允許規則、加連接器;區網登入 30 天沒用失效 - 團隊成員只看得到勾選「團隊成員可以使用」的 Bot - 沒有角色的請求一律拒絕;環境變數的金鑰只送官方位址 資源 - 中繼:小變動每分鐘寫一次、回應有總時限、每台電腦呼叫上限、網站/登入/電腦/配對碼上限、資料檔壞掉不啟動 - App:伺服器回錯誤和連線秒斷時逐次退避;區網看螢幕偵測斷線 - 背景指令:刪 Bot 和支線結束時停掉、最多 24 個、結束 10 分鐘後移除、可用 stop 停掉 - 截圖在收起和歸檔時釋放;刪 Bot 時刪附件和對照表;每晚清稽核資料和暫存;手機圖片快取上限 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3a7riWESpv471gDgC
2026-11-13 15:36:34 +00:00
headers: [("x-anybot-user", s("user")), ("x-anybot-role", if head["role"].is_string() { s("role") } else { "none".into() }), ("x-anybot-from", s("from"))].into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
body,
peer: "relay".into(),
};
let resp = crate::remote::handle(req, true);
let (out, z) = if head["z_ok"].as_bool().unwrap_or(false) { maybe_zip(resp.body) } else { (resp.body, false) };
let _ = tx.send(wire::pack(&json!({"t": "reply", "id": id, "status": resp.status, "ctype": resp.ctype, "headers": resp.headers, "z": z}), &out));
});
}
"ret" => {
if let Some(w) = calls.lock().unwrap().remove(head["id"].as_str().unwrap_or("")) {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let status = head["status"].as_u64().unwrap_or(502) as u16;
let z = head["z"].as_bool().unwrap_or(false);
if z {
let _ = std::thread::Builder::new().spawn(move || {
let _ = w.send(unzip(&body).map(|body| Answer { status, body }));
});
} else {
let _ = w.send(Ok(Answer { status, body }));
}
}
}
_ => {}
}
}
/// Tell the account server which brain this AnyBot shows (so the phone can go there).
pub fn hello(brain: &str, hands: bool) {
if let Some(l) = link().lock().unwrap().as_ref() {
let _ = l.tx.send(wire::pack(&json!({"t": "hello", "brain": brain, "hands": hands}), &[]));
}
}
/// Ask another AnyBot of this account over the lasting connection. None when it isn't open
/// (the caller then uses an ordinary request).
pub fn call(to: &str, method: &str, path: &str, query: &[(&str, String)], body: &[u8], secs: u64) -> Option<Result<Answer, String>> {
let (tx, calls) = {
let l = link().lock().unwrap();
let l = l.as_ref()?;
(l.tx.clone(), l.calls.clone())
};
let id = crate::httpd::random_hex(8);
let (rtx, rrx) = channel();
calls.lock().unwrap().insert(id.clone(), rtx);
let (out, z) = maybe_zip(body.to_vec());
let q: serde_json::Map<String, Value> = query.iter().map(|(k, v)| (k.to_string(), json!(v))).collect();
if tx.send(wire::pack(&json!({"t": "call", "id": id, "to": to, "method": method, "path": path, "query": q, "z": z}), &out)).is_err() {
calls.lock().unwrap().remove(&id);
return None;
}
fix: 慢的線上長連線不再被切斷;斷線接回馬上重新同步;大腦那一欄看得出是哪一段 計畫 R7。2026-11-17 早上:Mac mini 經 Tailscale 香港中繼連 nobledesktop(約 100 KB/s),大腦整份資料約 5 MB 要 45–55 秒。這台 45 秒沒收到「一則完整訊息」就算斷線,傳到一半被切、螢幕又從頭要整份,一直循環(實測:連線 9:41:48 開、9:42:33 剛好 45 秒時被切;第二次 9:43:55 一樣)。帳號那欄寫已連線、大腦那欄寫「和帳號伺服器的連線斷了」,看不出是哪一段。 - tunnel.rs:Stream 讀到資料就記(bytes_in、receiving);keep() 有資料進來就算還活著(DEAD_SECS 照舊,但量的是真的沒聲音)。call() 過了自己的時間、但連線還在收資料就繼續等(最多 10 分鐘)。link_serial() 給螢幕知道長連線接回了。 - 帳號伺服器(relay)的長連線同樣:Counted 包住 TcpStream,資料進來就算活著(這台上傳大份資料時不會被那端的 60 秒切掉)。要 make update-server 才生效。relay/clippy.toml:主程式的「HTTP 用戶端只能在 net.rs 建」不套用到 relay。 - 螢幕(mirror_ui):等重試時每 0.2 秒看一次長連線,接回就馬上再要(以前最多等 20 秒,這段時間帳號那欄已經寫已連線);記下上次同步的時間、大小、秒數。 - 設定的大腦那一欄:狀態下面分段寫「這台 ↔ 帳號伺服器」「帳號伺服器 ↔ 大腦(在線上/不在線上,帳號伺服器說的)」「上次同步 …(大小、秒數、KB/s)」。 已驗證:cargo test 571 全過、clippy -D warnings 過;relay cargo test 22 全過。新測試:假的帳號伺服器把一則 64 KB 的訊息分 3 秒慢慢送(允許的沉默設成 1 秒),連線不斷;之後真的沒聲音就斷。把「有資料進來就算活著」拿掉,同一個測試失敗:「已連線」後馬上「連線中斷」——就是早上的情況。 未驗證:真的 Tailscale 中繼線路上走一次(要更新這台的 App 和伺服器)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:41:15 +00:00
// Its own time, and longer while the link is still receiving (its answer may be what is
// arriving), up to LONGEST_WAIT.
let start = Instant::now();
let due = start + Duration::from_secs(secs);
Some(loop {
match rrx.recv_timeout(Duration::from_millis(500)) {
Ok(r) => break r,
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break Err(CUT.into()),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
let now = Instant::now();
if now >= due && (!receiving(3_000) || now - start >= LONGEST_WAIT) {
calls.lock().unwrap().remove(&id);
break Err("等太久沒有回應:網路很慢或斷斷續續".into());
}
}
}
})
}
/// An account server on the local network with its own certificate (setup.sh 「區網 IP」, Caddy
/// `tls internal`). Trusted (SSL_CERT_FILE = its root, read like the system's list):
/// ANYBOT_TLS_URL=https://10.0.0.25 SSL_CERT_FILE=root.crt cargo test -- --ignored own_certificate
/// Without SSL_CERT_FILE (and not trusted by this computer) it checks the refusal says what to do.
#[cfg(test)]
mod own_certificate_live {
#[test]
#[ignore]
fn a_server_with_its_own_certificate() {
let url = std::env::var("ANYBOT_TLS_URL").expect("ANYBOT_TLS_URL");
let trusted = std::env::var_os("SSL_CERT_FILE").is_some();
// A sign-up with a wrong invite: refused by the server itself (never makes an account).
let http = crate::remote::relay_post(&format!("{url}/relay/signup"), "", &serde_json::json!({"user": "tls-probe", "password": "tls-probe-123", "invite": "wrong"})).unwrap_err();
let ws = super::open(&url, "not-a-token").err().map(|e| e.why).unwrap_or_default();
if trusted {
assert!(!http.starts_with("連不到帳號伺服器"), "the secure connection should work: {http}");
assert!(ws.contains("登入失效"), "the long connection should reach the server: {ws}");
} else {
assert!(http.contains("不信任伺服器的憑證"), "{http}");
assert!(ws.contains("不信任伺服器的憑證"), "{ws}");
}
}
}
#[cfg(test)]
mod tests {
fix: 慢的線上長連線不再被切斷;斷線接回馬上重新同步;大腦那一欄看得出是哪一段 計畫 R7。2026-11-17 早上:Mac mini 經 Tailscale 香港中繼連 nobledesktop(約 100 KB/s),大腦整份資料約 5 MB 要 45–55 秒。這台 45 秒沒收到「一則完整訊息」就算斷線,傳到一半被切、螢幕又從頭要整份,一直循環(實測:連線 9:41:48 開、9:42:33 剛好 45 秒時被切;第二次 9:43:55 一樣)。帳號那欄寫已連線、大腦那欄寫「和帳號伺服器的連線斷了」,看不出是哪一段。 - tunnel.rs:Stream 讀到資料就記(bytes_in、receiving);keep() 有資料進來就算還活著(DEAD_SECS 照舊,但量的是真的沒聲音)。call() 過了自己的時間、但連線還在收資料就繼續等(最多 10 分鐘)。link_serial() 給螢幕知道長連線接回了。 - 帳號伺服器(relay)的長連線同樣:Counted 包住 TcpStream,資料進來就算活著(這台上傳大份資料時不會被那端的 60 秒切掉)。要 make update-server 才生效。relay/clippy.toml:主程式的「HTTP 用戶端只能在 net.rs 建」不套用到 relay。 - 螢幕(mirror_ui):等重試時每 0.2 秒看一次長連線,接回就馬上再要(以前最多等 20 秒,這段時間帳號那欄已經寫已連線);記下上次同步的時間、大小、秒數。 - 設定的大腦那一欄:狀態下面分段寫「這台 ↔ 帳號伺服器」「帳號伺服器 ↔ 大腦(在線上/不在線上,帳號伺服器說的)」「上次同步 …(大小、秒數、KB/s)」。 已驗證:cargo test 571 全過、clippy -D warnings 過;relay cargo test 22 全過。新測試:假的帳號伺服器把一則 64 KB 的訊息分 3 秒慢慢送(允許的沉默設成 1 秒),連線不斷;之後真的沒聲音就斷。把「有資料進來就算活著」拿掉,同一個測試失敗:「已連線」後馬上「連線中斷」——就是早上的情況。 未驗證:真的 Tailscale 中繼線路上走一次(要更新這台的 App 和伺服器)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:41:15 +00:00
/// R7: one big answer coming in slowly (longer than the silence the link allows) keeps the
/// link up — it used to be cut at DEAD_SECS without a whole message, mid-answer, over and over.
/// Then real silence still ends it.
#[test]
fn a_big_answer_arriving_slowly_keeps_the_link() {
use std::io::Write as _;
use std::sync::atomic::{AtomicBool, Ordering};
super::DEAD_MS.store(1_000, Ordering::Relaxed);
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
std::thread::spawn(move || {
let (s, _) = l.accept().unwrap();
let mut ws = tungstenite::accept(s).unwrap();
// One binary frame of 64 KB (a frame the client can read only once it is whole),
// written over 3 s — three times the allowed silence — then silence.
let body = super::wire::pack(&serde_json::json!({"t": "ret", "id": "nobody"}), &vec![b'x'; 64 * 1024]);
let mut frame = vec![0x82u8, 127];
frame.extend_from_slice(&(body.len() as u64).to_be_bytes());
frame.extend_from_slice(&body);
let raw = ws.get_mut();
for chunk in frame.chunks(frame.len() / 12 + 1) {
let _ = raw.write_all(chunk);
let _ = raw.flush();
std::thread::sleep(std::time::Duration::from_millis(250));
}
std::thread::sleep(std::time::Duration::from_secs(10));
});
let said = std::sync::Arc::new(std::sync::Mutex::new(Vec::<(std::time::Instant, String)>::new()));
let (said2, stop) = (said.clone(), std::sync::Arc::new(AtomicBool::new(false)));
let stop2 = stop.clone();
let t0 = std::time::Instant::now();
let h = std::thread::spawn(move || {
super::run(&format!("http://127.0.0.1:{port}"), "token", &|| !stop2.load(Ordering::Relaxed), &|m| said2.lock().unwrap().push((std::time::Instant::now(), m.to_string())));
});
std::thread::sleep(std::time::Duration::from_millis(3_200));
let early: Vec<String> = said.lock().unwrap().iter().filter(|(t, _)| t.duration_since(t0).as_millis() < 3_200).map(|(_, m)| m.clone()).collect();
assert_eq!(early, vec!["已連線".to_string()], "the link stayed up while the answer came in");
assert!(super::receiving(1_000) && super::bytes_in() >= 64 * 1024);
// Real silence (the server stopped sending): the link is opened again.
std::thread::sleep(std::time::Duration::from_millis(2_000));
assert!(said.lock().unwrap().iter().any(|(_, m)| m.contains("中斷")), "{:?}", said.lock().unwrap());
stop.store(true, Ordering::Relaxed);
super::DEAD_MS.store(super::DEAD_SECS * 1000, Ordering::Relaxed);
// (Not joined: it may be waiting on a reconnect the fake server no longer answers.)
drop(h);
}
#[test]
fn the_public_certificates_are_always_trusted() {
// The system's list comes on top; a computer without one still reaches public servers.
assert!(super::trusted_roots().len() >= webpki_root_certs::TLS_SERVER_ROOT_CERTS.len());
}
#[test]
fn compression_round_trips_and_shrinks_text() {
let text = "你好,這是一段會重複的聊天內容。".repeat(400);
let z = super::zip(text.as_bytes());
assert!(z.len() * 5 < text.len());
assert_eq!(super::unzip(&z).unwrap(), text.as_bytes());
// Already-compressed bytes go as they are.
let mut x = 88172645463325252u64;
let noise: Vec<u8> = (0..5000)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
(x >> 24) as u8
})
.collect();
assert!(!super::maybe_zip(noise).1);
assert!(super::maybe_zip(text.into_bytes()).1);
}
/// Words typed in a viewer go to the screen its session is on (the shared one when the bot's
/// wasn't open), whatever bot the account server names; a viewer that isn't there types
/// nothing (it used to make that bot's screen, unseen, for the words).
#[test]
fn typed_words_go_to_the_screen_the_viewer_is_on() {
super::streams().lock().unwrap().insert("vt-shared".into(), crate::vnc::Session::for_test(""));
super::streams().lock().unwrap().insert("vt-own".into(), crate::vnc::Session::for_test("bot7"));
assert_eq!(super::typing_screen("vt-shared").as_deref(), Some(""));
assert_eq!(super::typing_screen("vt-own").as_deref(), Some("bot7"));
assert_eq!(super::typing_screen("vt-gone"), None);
super::streams().lock().unwrap().remove("vt-shared");
super::streams().lock().unwrap().remove("vt-own");
}
}