diff --git a/FEATURES.md b/FEATURES.md index 9a74588..f2f8c0e 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -260,6 +260,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 「模型未能及時開始回應。請重試。」:每一步開始後 120 秒內沒有任何回應(估計值)。 - 「回應中斷:模型超過 35 秒沒有送出任何內容。」:已經開始輸出後,又安靜超過 35 秒。 - 紅色的錯誤氣泡下面直接有一個〔重試〕按鈕,點它就是重新產生這一個回合。 +- **沒人在看的一輪等比較久**:例行任務、事件觸發、訊息管道和團隊成員的訊息,模型忙碌(429/503)、連不上或回空的,最多試 8 次、每次最多等 30 秒(1、2、4…秒加倍),每次的等待加減兩成隨機(很多台電腦同時遇到同一次中斷,不會在同一秒一起再問);供應商給了 Retry-After 就照它的等。有人在看的照舊試 3 次(最多等 4 秒),讓人自己決定要不要重試。以前一個供應商幾十秒的忙碌就會讓半夜的例行任務失敗。 - 等你允許或工具在執行時,不算卡住。 ### 自動捲動 diff --git a/docs/feature-map/routines.md b/docs/feature-map/routines.md index cbd078c..3215885 100644 --- a/docs/feature-map/routines.md +++ b/docs/feature-map/routines.md @@ -26,6 +26,8 @@ Bot 照排程(每天、每週、每月、只一次)或某件事發生時(P ## 陷阱 +- 沒人在看的一輪(例行任務、事件觸發、訊息管道和團隊成員的訊息)遇到模型忙碌或連不上,最多試 8 次、每次最多等 30 秒(加減兩成,避免大家同一秒再問);有人在看的一輪照舊試 3 次就停,讓你按重試。 + - 送出幾則看系統的計數和送出證據,不看 Bot 的回報:Bot 說「完成 5 則」可能只送出 3 則。 - 加這些紀錄之前跑過的,沒有執行紀錄;`list_routines` 會說「查不到」,不是「沒跑過」。 - 使用者自己按停止、或 AnyBot 被關掉,不算失敗,不會讓它自動暫停。 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 359baba..981aa55 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -62,9 +62,9 @@ ## 軌 R:穩定與安全 -### R1. 重試預算 ⬜ +### R1. 重試預算 ✅ - 現況:3 次、1→2→4 秒、沒有抖動(`providers.rs`)。 -- 做法:有人在看的一輪照舊;沒人在看的(例行任務、事件觸發、訊息管道)最多 8 次、最長等 30 秒、±20% 抖動;Retry-After 照給的等(上限 60 秒)。已經開始輸出就不重試(不變)。 +- 做法:有人在看的一輪照舊(共 3 次);沒人在看的(例行任務、事件觸發、訊息管道、團隊成員)共 8 次、最長等 30 秒、±20% 抖動;Retry-After 照給的等(上限照舊 30 秒)。已經開始輸出就不重試(不變)。 - 做完:假模型注入 503 五次後成功:沒人看的一輪成功,有人看的照舊 3 次後失敗。 ### R2. 固定樣式的規則先判斷 ⬜ diff --git a/src/agent.rs b/src/agent.rs index 8b1d10b..783b16b 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -95,6 +95,9 @@ pub struct Job { /// 計畫 (/plan) being written: only the tools that look run until the person approves it on /// the card; then these take over (see plan.rs). pub drafting: Option, + /// Nobody is watching this turn (a routine, a trigger, a channel's or a teammate's message): + /// a busy model is waited out longer (providers::set_patient). + pub unattended: bool, } /// What a turn in plan mode switches to once the plan is approved. @@ -1601,6 +1604,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< std::thread::spawn(move || { let _screens = ScreensBack(bot_id); let mut job = job; + crate::providers::set_patient(job.unattended); let send = |ev: StreamEvent| { let _ = tx.send((bot_id, ev)); ctx.request_repaint(); @@ -3398,6 +3402,7 @@ mod tests { timezone: "Asia/Taipei".into(), untrusted: false, drafting: None, + unattended: false, } } @@ -4914,6 +4919,7 @@ echo 'done送出了' > done.html; (setsid pyt timezone: "Asia/Taipei".into(), untrusted: false, drafting: None, + unattended: false, }; let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); @@ -5002,6 +5008,7 @@ echo 'done送出了' > done.html; (setsid pyt timezone: "Asia/Taipei".into(), untrusted: false, drafting: None, + unattended: false, }; let (tx, rx) = channel(); spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); @@ -5093,6 +5100,7 @@ echo 'done送出了' > done.html; (setsid pyt timezone: "Asia/Taipei".into(), untrusted: false, drafting: None, + unattended: false, }; let (tx, rx) = channel(); spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); @@ -5320,6 +5328,7 @@ echo 'done送出了' > done.html; (setsid pyt timezone: "Asia/Taipei".into(), untrusted: false, drafting: None, + unattended: false, }; let (tx, rx) = channel(); spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); diff --git a/src/app.rs b/src/app.rs index 9892b09..d6e0c7f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1914,6 +1914,7 @@ impl App { target_sends, timezone: self.state.timezone.clone(), untrusted, + unattended: unattended_wake || untrusted, drafting: match (plan_now, plan_tools, plan_system) { (Some(plan), Some(tools), Some(system)) => Some(agent::Drafting { plan, tools, system }), _ => None, diff --git a/src/providers.rs b/src/providers.rs index c4b5fb5..bbe53dd 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -382,9 +382,45 @@ impl Failure { } } -/// Delay before retry `n` (1-based): 1 s, 2 s, 4 s, capped at 4 s. -pub fn backoff_delay_ms(retry: u32) -> u64 { - (RETRY_INITIAL_DELAY_MS * RETRY_BACKOFF_FACTOR.pow(retry.saturating_sub(1))).min(RETRY_MAX_DELAY_MS) +/// Delay before retry `n` (1-based): 1 s, 2 s, 4 s… capped at `max_ms` (4 s while someone watches). +fn backoff_up_to(retry: u32, max_ms: u64) -> u64 { + (RETRY_INITIAL_DELAY_MS * RETRY_BACKOFF_FACTOR.saturating_pow(retry.saturating_sub(1))).min(max_ms) +} + +/// 沒人在看的一輪 (a routine, a trigger, a message from a channel or a teammate): a busy or +/// failing model is tried this many times, waiting up to PATIENT_MAX_DELAY_MS between, before the +/// turn gives up — a ten-second hiccup at the provider used to fail a routine at 3 a.m. A turn the +/// person is watching keeps RETRY_MAX_ATTEMPTS (they can press 重試). Like grok-build's 15 tries. +pub const PATIENT_ATTEMPTS: u32 = 8; +pub const PATIENT_MAX_DELAY_MS: u64 = 30_000; + +thread_local! { + static PATIENT: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// This thread's turn is one nobody is watching (set by agent::spawn for its turn). +pub fn set_patient(on: bool) { + PATIENT.with(|p| p.set(on)); +} + +/// (tries in all, longest wait) for this thread's model calls. +fn retry_budget() -> (u32, u64) { + if PATIENT.with(|p| p.get()) { + (PATIENT_ATTEMPTS, PATIENT_MAX_DELAY_MS) + } else { + (RETRY_MAX_ATTEMPTS, RETRY_MAX_DELAY_MS) + } +} + +/// A wait spread by ±20% (many computers coming back from the same outage don't all ask again in +/// the same second). +pub fn jitter(ms: u64) -> u64 { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0) as u64; + let spread = ms / 5; + if spread == 0 { + return ms; + } + ms - spread + nanos % (2 * spread + 1) } fn agent() -> ureq::Agent { @@ -717,6 +753,8 @@ fn run_step_unbooked(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Strea send(ev); }; let mut attempt = 1; + // 沒人在看的一輪 waits longer (set_patient). + let (tries, longest) = retry_budget(); // Steps left without a result (stopped while waiting for the person) are closed off. let repaired = ChatRequest { history: repair_history(&req.history), ..req.clone() }; let req = &repaired; @@ -745,9 +783,9 @@ fn run_step_unbooked(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Strea match result { // Nothing at all came back (no words, no tool call): a dropped stream or a hiccup. The // turn used to end on 「(沒有回應內容)」; ask again instead. - Ok(out) if out.text.trim().is_empty() && out.tool_calls.is_empty() && !produced.get() && attempt < RETRY_MAX_ATTEMPTS && !cancel.load(Ordering::Relaxed) => { - send(StreamEvent::Retrying(format!("模型這次沒有回任何內容,再問一次(第 {} 次,共 {} 次)…", attempt + 1, RETRY_MAX_ATTEMPTS))); - std::thread::sleep(Duration::from_millis(backoff_delay_ms(attempt))); + Ok(out) if out.text.trim().is_empty() && out.tool_calls.is_empty() && !produced.get() && attempt < tries && !cancel.load(Ordering::Relaxed) => { + send(StreamEvent::Retrying(format!("模型這次沒有回任何內容,再問一次(第 {} 次,共 {tries} 次)…", attempt + 1))); + std::thread::sleep(Duration::from_millis(jitter(backoff_up_to(attempt, longest)))); attempt += 1; } Ok(out) => return Ok(out), @@ -755,9 +793,10 @@ fn run_step_unbooked(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Strea mark_blind(req); send(StreamEvent::Retrying("這個模型不能看圖片,改成不附圖片再試一次…".into())); } - Err(f) if f.retryable && !produced.get() && attempt < RETRY_MAX_ATTEMPTS && !cancel.load(Ordering::Relaxed) => { - let wait = f.retry_after_ms.unwrap_or_else(|| backoff_delay_ms(attempt)); - send(StreamEvent::Retrying(format!("{}\n{:.0} 秒後重試(第 {} 次,共 {} 次)…", f.msg, wait as f64 / 1000.0, attempt + 1, RETRY_MAX_ATTEMPTS))); + Err(f) if f.retryable && !produced.get() && attempt < tries && !cancel.load(Ordering::Relaxed) => { + // (The provider's own Retry-After as it says; our own wait spread a little.) + let wait = f.retry_after_ms.unwrap_or_else(|| jitter(backoff_up_to(attempt, longest))); + send(StreamEvent::Retrying(format!("{}\n{:.0} 秒後重試(第 {} 次,共 {tries} 次)…", f.msg, wait as f64 / 1000.0, attempt + 1))); let until = std::time::Instant::now() + Duration::from_millis(wait); while std::time::Instant::now() < until { if cancel.load(Ordering::Relaxed) { @@ -1773,7 +1812,12 @@ mod tests { #[test] fn backoff_matches_original() { - assert_eq!([backoff_delay_ms(1), backoff_delay_ms(2), backoff_delay_ms(3)], [1000, 2000, 4000]); + assert_eq!([backoff_up_to(1, RETRY_MAX_DELAY_MS), backoff_up_to(2, RETRY_MAX_DELAY_MS), backoff_up_to(3, RETRY_MAX_DELAY_MS)], [1000, 2000, 4000]); + assert_eq!(backoff_up_to(9, PATIENT_MAX_DELAY_MS), PATIENT_MAX_DELAY_MS); + for ms in [0, 1, 1000, 30_000] { + let j = jitter(ms); + assert!(j >= ms - ms / 5 && j <= ms + ms / 5, "{ms} → {j}"); + } assert!(http_error(429, "{}", None).retryable); assert!(http_error(503, "{}", Some(2000)).retry_after_ms == Some(2000)); assert!(!http_error(401, "{}", None).retryable); diff --git a/src/testkit.rs b/src/testkit.rs index 1f75783..22af22b 100644 --- a/src/testkit.rs +++ b/src/testkit.rs @@ -223,6 +223,23 @@ mod tests { assert_eq!(out.usage, Usage { input: 50, output: 12, cache_read: 400, cache_write: 30, cost_micros: 0 }); } + /// R1: a turn nobody is watching waits out a busy model longer (more tries); one the person + /// watches gives up after RETRY_MAX_ATTEMPTS tries. + #[test] + fn a_turn_nobody_watches_waits_longer_for_a_busy_model() { + let busy = || (0..4).map(|_| Reply::busy(0)).chain([Reply::text("終於")]).collect::>(); + let cancel = AtomicBool::new(false); + let f = Fake::start(Format::OpenAi, busy(), None); + assert!(crate::providers::run_step(&req(ProviderKind::Custom, f.base()), &cancel, &|_| {}).is_err(), "watched: 3 tries in all"); + assert_eq!(f.requests(), crate::providers::RETRY_MAX_ATTEMPTS as usize); + let f = Fake::start(Format::OpenAi, busy(), None); + crate::providers::set_patient(true); + let out = crate::providers::run_step(&req(ProviderKind::Custom, f.base()), &cancel, &|_| {}); + crate::providers::set_patient(false); + assert_eq!(out.unwrap().text, "終於"); + assert_eq!(f.requests(), 5); + } + /// An answer with nothing in it (no words, no call) is asked again, in either format. #[test] fn an_empty_answer_is_asked_again() {