diff --git a/src/agent.rs b/src/agent.rs index ba0357c..6d70c3d 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -344,7 +344,7 @@ pub(crate) fn worth_noting(turn: &[Message]) -> bool { const NOTE_MIN_LOOKS: usize = 5; fn memory_note(job: &Job, history: &[Message]) { - let Some(start) = history.iter().rposition(|m| m.role == Role::User && !m.steer) else { return }; + let Some(start) = history.iter().rposition(|m| m.role == Role::User && !m.steer && !only_in_turn(m)) else { return }; if !worth_noting(&history[start..]) { return; } @@ -361,7 +361,7 @@ fn memory_note(job: &Job, history: &[Message]) { } fn learn(job: &Job, history: &[Message], cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) { - let Some(start) = history.iter().rposition(|m| m.role == Role::User && !m.steer) else { return }; + let Some(start) = history.iter().rposition(|m| m.role == Role::User && !m.steer && !only_in_turn(m)) else { return }; let turn = &history[start..]; if !crate::memory::worth_learning(turn) { return; @@ -1033,7 +1033,7 @@ pub fn compaction_cut(h: &[Message]) -> Option { /// AnyBot's own words to the model inside one turn (a nudge, a hook's 「not yet」): the chat in /// the window never has them, so a summary is never cut at one (the window finds the cut by it). -fn only_in_turn(m: &Message) -> bool { +pub(crate) fn only_in_turn(m: &Message) -> bool { m.role == Role::User && m.text.starts_with("【AnyBot:") } @@ -1668,7 +1668,7 @@ enum Gate { /// What the turn is about (its first message) and the skills it read, for the check. fn turn_brief(history: &[Message]) -> (String, String) { - let start = history.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0); + let start = history.iter().rposition(|m| m.role == Role::User && !m.steer && !only_in_turn(m)).unwrap_or(0); let task = history.get(start).map(|m| m.text.clone()).unwrap_or_default(); let skills: Vec<&str> = history[start..].iter().filter(|m| m.role == Role::Tool && m.tool_name == "use_skill").map(|m| m.text.as_str()).collect(); let skills = skills.join("\n\n"); @@ -2174,10 +2174,12 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< }; // A quiet step after a nudge: nothing shows until it is known to be worth showing // (its words and calls come whole with StepDone); the watchdog still hears it work. - let hushed = |ev: StreamEvent| { - if matches!(ev, StreamEvent::Alive | StreamEvent::Retrying(_) | StreamEvent::Text(_) | StreamEvent::Thinking(_) | StreamEvent::ToolCall(_)) { - send(StreamEvent::Alive) - } + // (Words and calls as they come say only 「it is answering」: an empty thought, which + // adds nothing to the chat but tells the watchdog output started.) + let hushed = |ev: StreamEvent| match ev { + StreamEvent::Alive | StreamEvent::Retrying(_) => send(StreamEvent::Alive), + StreamEvent::Text(_) | StreamEvent::Thinking(_) | StreamEvent::ToolCall(_) => send(StreamEvent::Thinking(String::new())), + _ => {} }; let tried_quick = quick.clone(); let mut attempt = 0; @@ -5675,9 +5677,10 @@ echo 'done送出了' > done.html; (setsid pyt let job = smart_job(port, vec![Message::user("研究一下怎麼生圖")], None, Duration::from_secs(300), true); let (tx, rx) = channel(); spawn(Job { direct: Arc::new(AtomicBool::new(true)), ..job }, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); - let (mut shown, mut results, mut nudged) = (vec![], vec![], false); + let (mut shown, mut results, mut nudged, mut quiet_output) = (vec![], vec![], false, false); loop { match rx.recv_timeout(Duration::from_secs(20)).expect("loop stalled") { + (_, StreamEvent::Thinking(t)) if t.is_empty() => quiet_output = true, (_, StreamEvent::StepDone(m)) => shown.push((m.text.clone(), m.tool_calls.len())), (_, StreamEvent::ToolResult(m)) => results.push(m.text.clone()), (_, StreamEvent::Retrying(w)) if w.contains("接著做") => nudged = true, @@ -5690,6 +5693,7 @@ echo 'done送出了' > done.html; (setsid pyt } } assert!(nudged, "the person sees why it goes on"); + assert!(quiet_output, "the quiet step's output still tells the watchdog it is answering"); assert_eq!(shown.len(), 3, "the announcement, the step, the answer: {shown:?}"); assert_eq!(shown[1].1, 1, "the quiet step's call is shown with its step"); assert!(results.iter().any(|r| r.contains("page-written")), "{results:?}"); diff --git a/src/app.rs b/src/app.rs index 17b684b..466ebcd 100644 --- a/src/app.rs +++ b/src/app.rs @@ -3040,9 +3040,11 @@ impl App { live.produced = true; live.status = None; } + // A new try (or a quiet step after a nudge): the first-response deadline again. StreamEvent::Retrying(msg) => { live.status = Some(msg.clone()); live.started = Instant::now(); + live.produced = false; } // A new model step gets the first-response deadline again. StreamEvent::NextStep(_) => { @@ -6998,16 +7000,19 @@ impl eframe::App for App { ctx.send_viewport_cmd(egui::ViewportCommand::Maximized(!zoomed)); } } - if self.mirror_waiting_at_door() { + // (At the door nothing is edited: before the brain's first answer an edit had nothing to + // be compared with and was dropped once it came.) + let at_door = self.mirror_waiting_at_door(); + if at_door { self.mirror_door(ui); } else { self.sidebar(ui); self.main_pane(ui); + self.bot_editor(ctx); + self.memory_page(ctx); + self.drops_page(ctx); + self.settings(ctx); } - self.bot_editor(ctx); - self.memory_page(ctx); - self.drops_page(ctx); - self.settings(ctx); self.delete_dialog(ctx); self.delete_routine_dialog(ctx); self.routines_window(ctx); diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index 2b1b899..17d9823 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -434,7 +434,7 @@ pub enum Incoming { File(String), /// A message that couldn't reach the brain however long it was tried: its words go back /// into that bot's input (when the person hasn't typed something else there since). - Unsent { bot: u64, text: String }, + Unsent { bot: u64, text: String, atts: Vec }, } /// Each message and chat action from this screen gets a name of its own (this screen's, then a @@ -1215,10 +1215,11 @@ impl App { self.mir.fetching.remove(&path); self.att.thumbs.remove(&path); } - Incoming::Unsent { bot, text } => { - if self.drafts.get(&bot).is_none_or(|d| d.trim().is_empty()) { - self.drafts.insert(bot, text); - } + Incoming::Unsent { bot, text, atts } => { + // (Put before what was typed since, never in place of it.) + let draft = self.drafts.entry(bot).or_default(); + *draft = if draft.trim().is_empty() { text } else { format!("{text}\n{draft}") }; + self.att.pending.entry(bot).or_default().extend(atts); } Incoming::Pull(v) => { if let Some(e) = v["error"].as_str() { @@ -1542,23 +1543,36 @@ impl App { } } Out::Send { bot, id, text, atts, memories } => { + // The files first (each asked again while the line is down); one that can't + // go keeps the whole message here — words without their file would be a + // different message. let mut paths = vec![]; + let mut failed = None; for a in &atts { - match std::fs::read(&a.path).map_err(|e| format!("讀不到這個檔案({e})")).and_then(|b| remote::sync_upload(&s, bot, &a.name, &b)) { + match std::fs::read(&a.path).map_err(|e| format!("讀不到這個檔案({e})")).and_then(|b| remote::sync_upload_sure(&s, bot, &a.name, &b, &waiting)) { Ok(p) => paths.push(p), - Err(e) => *err.lock().unwrap() = format!("「{}」沒有傳到大腦:{e}", a.name), + Err(e) => { + failed = Some(format!("「{}」沒有傳到大腦:{e}", a.name)); + break; + } } } - let mut body = json!({"bot": bot, "action": "send", "id": id, "text": text, "attachments": paths}); - if let Some(m) = memories { - body["memories"] = json!(m); - } - if let Err(e) = remote::sync_post_sure(&s, "act", &body, &waiting) { + let sent = match failed { + Some(e) => Err(e), + None => { + let mut body = json!({"bot": bot, "action": "send", "id": id, "text": text, "attachments": paths}); + if let Some(m) = memories { + body["memories"] = json!(m); + } + remote::sync_post_sure(&s, "act", &body, &waiting).map(|_| ()) + } + }; + if let Err(e) = sent { *err.lock().unwrap() = format!("訊息沒有送到大腦(已放回輸入框):{e}"); - // Take back the message shown ahead of time; its words go back to the input. + // Take back the message shown ahead of time; its words and files go back to the input. resync.store(true, Ordering::SeqCst); if let Some(tx) = &back { - let _ = tx.send(Incoming::Unsent { bot, text: text.clone() }); + let _ = tx.send(Incoming::Unsent { bot, text: text.clone(), atts: atts.clone() }); } } sending.fetch_sub(1, Ordering::AcqRel); diff --git a/src/memory.rs b/src/memory.rs index 54cab7e..6b6c208 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -382,7 +382,8 @@ fn brief_steps(turn: &[crate::model::Message]) -> Vec<(String, Option)> = vec![]; for (i, m) in turn.iter().enumerate() { - if m.role == Role::User && i > 0 { + // (AnyBot's own nudges inside a turn are not the person's words.) + if m.role == Role::User && i > 0 && !crate::agent::only_in_turn(m) { steps.push((format!("(使用者中途說:{})", cut(&m.text, 300)), None)); } for c in &m.tool_calls { @@ -1093,6 +1094,21 @@ pub fn api_write(state: &mut crate::model::State, b: &serde_json::Value) -> serd mod tests { use super::*; + /// AnyBot's own nudge inside a turn (說了就做) is not the person's words: the look back + /// lists only what they typed in between. + #[test] + fn a_nudge_is_not_the_person_talking() { + use crate::model::Message; + let turn = vec![ + Message::user("研究一下"), + Message::assistant("我把它整理成一頁。", "x"), + Message { wake: true, ..Message::user("【AnyBot:你剛才說了接下來要做什麼,但那一則沒有呼叫任何工具…】") }, + Message::user("順便看一下價格"), + ]; + let steps: Vec = brief_steps(&turn).into_iter().map(|(s, _)| s).collect(); + assert_eq!(steps, vec!["(使用者中途說:順便看一下價格)".to_string()], "{steps:?}"); + } + #[test] fn anybots_own_problems_are_reported_apart_from_the_skill() { let out = r#"{"save": true, "name": "Threads 回覆", "description": "回覆貼文", "instructions": "1. 開貼文", "replay": [], "tool_issues": ["browser_fill_contact 被誤用來打字", " ", "多行字只能用剪貼簿貼上"]}"#; diff --git a/src/remote.rs b/src/remote.rs index 915a245..7229769 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -2684,11 +2684,21 @@ const SURE_TRY_SECS: u64 = 20; /// for up to SURE_SECS. `waiting` is told before each new try. A refusal from the brain itself /// (not the line) is answered at once. pub fn sync_post_sure(s: &Settings, what: &str, body: &Value, waiting: &dyn Fn()) -> Result { - let bytes = body.to_string(); + post_sure(s, &format!("/{what}"), &[], body.to_string().as_bytes(), SURE_TRY_SECS, waiting) +} + +/// sync_upload, asked again while the line is down (a file sent twice is only a second copy at +/// the brain, never a second message). +pub fn sync_upload_sure(s: &Settings, bot: u64, name: &str, bytes: &[u8], waiting: &dyn Fn()) -> Result { + let v = post_sure(s, &format!("/upload/{bot}"), &[("name", name.to_string())], bytes, 120, waiting)?; + v["path"].as_str().map(String::from).ok_or("大腦沒有收下檔案".into()) +} + +fn post_sure(s: &Settings, rest: &str, query: &[(&str, String)], bytes: &[u8], try_secs: u64, waiting: &dyn Fn()) -> Result { let until = Instant::now() + Duration::from_secs(SURE_SECS); let mut wait = 500u64; loop { - let r = to_brain_any(s, "POST", &format!("/{what}"), &[], bytes.as_bytes(), SURE_TRY_SECS); + let r = to_brain_any(s, "POST", rest, query, bytes, try_secs); // (502–504: the account server couldn't reach the brain, or gave up waiting for it.) let again = match &r { Err(_) => true,