diff --git a/AGENTS.md b/AGENTS.md index 5bb6a60..d4ca657 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,7 +82,11 @@ web/app/ Nuxt 4 SPA (no SSR) before its last message. `message` is `ReplaySafety::Unsafe`. - Turns are serialized per room. A new mention while a turn runs drops the turn future (turn-level steering) and starts a new turn over the - committed session. Do not drop the room task. + committed session. A message without a mention never drops anything: + `runner::RoomSteering` hands it to the framework's steering hook, which + appends it at the next step boundary; the turn advances `absorbed_seq` + once that session is saved, so the next boundary pass cannot repeat it. + Do not drop the room task. - The preview host label is `r-p--.` for a port, or `r-s--.` for a static target. The HMAC covers the target and expiry with a key diff --git a/specs/rhema-together.md b/specs/rhema-together.md index 6961e3b..65b4a35 100644 --- a/specs/rhema-together.md +++ b/specs/rhema-together.md @@ -190,6 +190,21 @@ an `absorbed_seq` cursor, so nothing is appended twice. The cursor advances on every append, whatever the path, so the boundary pass and the interrupt path cannot both write the same line. +The mid-turn half of that is the framework's steering hook +(`HostAgentConfig::steering`), not a step-level drop: the turn's +`RoomSteering` source hands the driver one User-role line per drain at a +step boundary, so a member can correct the agent while it works without +the step in flight dying. It stops at the first line it cannot carry, a +mention (the drop path owns that one) or a message with images (a line +of text cannot hold them), and leaves the cursor there, so the boundary +pass appends them in the log's order. The source only reads that +cursor. The turn writes it after the session holding the drained lines +is saved, the order the boundary pass already uses: append, checkpoint, +advance. A crash before the checkpoint repeats a line at worst, and the +framework's per-turn dedupe drops the repeat. What steering still cannot +do is stop a running command: only the mention drop does that, and only +between steps. + A burst of mentions that lands before the first drop completes all goes into the same restart, in order, one message each. Nothing is folded. @@ -663,7 +678,10 @@ Backups: the SQLite file (attachments included) and the secret key. Small and additive, in the framework's own terms: 1. `HostAgent::step` plus the turn setup around it, so a frontend can own - the loop and drop one step. `rhema-code` steers at turn level: it + the loop and drop one step. The steering hook covers the common case + today: chat lands at a step boundary without a drop. A drop is still + what stops a long command, and it still costs the whole turn. + `rhema-code` steers at turn level: it drops the whole turn future and starts a new turn with the nudge on the same agent and session (`turn.rs`). That is enough for a single-user TUI, where a turn boundary is a ledger row. A room wants diff --git a/src/room/agent.rs b/src/room/agent.rs index 9dd05fd..6837068 100644 --- a/src/room/agent.rs +++ b/src/room/agent.rs @@ -9,7 +9,7 @@ use base64::Engine; use rhema_bash::{AllowAll, ShellTools}; use rhema_core::request::ThinkingEffort; use rhema_core::{Overlay, Session, ToolResolver}; -use rhema_host_agent::{HostAgent, HostAgentConfig}; +use rhema_host_agent::{HostAgent, HostAgentConfig, Steering}; use rhema_sandbox::WorkspaceSeed; use rhema_sandbox::{Sandbox, ShellSandbox}; @@ -29,6 +29,9 @@ pub struct TurnConfig { /// The model's stored vision fact; `None` is unknown, not no. pub supports_vision: Option, pub max_turn_steps: u32, + /// The cursor the turn starts from. The boundary pass moves it to + /// the last line it appended, so the turn's steering source reads on + /// from there and never over what is already in the history. pub absorbed_seq: i64, pub seeded: bool, pub owner_name: String, @@ -302,8 +305,14 @@ fn room_section(config: &TurnConfig) -> String { ) } -/// Assembles the host agent over `session`. -pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> AppResult { +/// Assembles the host agent over `session`, with `steering` as the turn +/// loop's step-boundary source (see `runner::RoomSteering`). +pub fn build_agent( + state: &Shared, + config: &TurnConfig, + session: Session, + steering: Arc, +) -> AppResult { let sandbox = build_sandbox(state, config)?; let executor = Arc::new(ShellSandbox::new(Arc::new(sandbox))); let shell = Arc::new(ShellTools::with_executor( @@ -353,7 +362,7 @@ pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> App shell_env: Default::default(), transcript: Some(Default::default()), summary_worker: None, - steering: None, + steering: Some(steering), home: None, environment: Some(rhema_host_agent::remote_notice( "ssh", diff --git a/src/room/runner.rs b/src/room/runner.rs index 38f3b2d..eed8255 100644 --- a/src/room/runner.rs +++ b/src/room/runner.rs @@ -1,16 +1,22 @@ //! The per-room turn loop. One task per room, one turn at a time. //! -//! Steering is turn level for now: a new mention drops the running turn -//! future and starts a fresh turn over the committed session, the shape -//! `rhema-code` uses. The step-level hook (`HostAgent::step`) is -//! deferred; see the spec's framework section. +//! A mention is turn level: it drops the running turn future and starts a +//! fresh turn over the committed session, the shape `rhema-code` uses. The +//! step-level hook (`HostAgent::step`) is deferred; see the spec's framework +//! section. +//! +//! Chat is step level, through the framework's steering hook: a message +//! posted without a mention while the agent works lands in the history at +//! the next step boundary instead of waiting for the next turn. See +//! [`RoomSteering`]. use std::collections::HashMap; use std::sync::Arc; -use std::sync::atomic::AtomicBool; +use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; use rhema_core::event::Event; use rhema_core::{EventSink, Message, Role, Session, Usage}; +use rhema_host_agent::Steering; use serde_json::json; use tokio::sync::mpsc::UnboundedReceiver; @@ -34,7 +40,7 @@ pub async fn run(state: Shared, room: String, mut rx: UnboundedReceiver) { continue; } loop { - let config = match agent::load_turn_config(&state, &room) { + let mut config = match agent::load_turn_config(&state, &room) { Ok(config) => config, Err(err) => { notice(&state, &room, "error", err.message); @@ -81,11 +87,18 @@ pub async fn run(state: Shared, room: String, mut rx: UnboundedReceiver) { pending_mention = false; break; } - let last = pending.last().map(|message| message.seq).unwrap_or(0); + // The batch's cursor, in the row and in the config the turn + // reads, so the turn's steering source starts after what this + // pass just appended instead of reading it back. + let last = pending + .last() + .map(|message| message.seq as i64) + .unwrap_or(config.absorbed_seq); let _ = state.db.conn().execute( "UPDATE rooms SET absorbed_seq = ?1 WHERE id = ?2", - rusqlite::params![last as i64, room], + rusqlite::params![last, room], ); + config.absorbed_seq = last; pending_mention = false; let trigger = pending .iter() @@ -118,7 +131,12 @@ async fn run_turn( rx: &mut UnboundedReceiver, pending_mention: &mut bool, ) { - let mut agent = match agent::build_agent(state, config, session) { + let steering = Arc::new(RoomSteering::new( + state.clone(), + room.to_owned(), + config.absorbed_seq, + )); + let mut agent = match agent::build_agent(state, config, session, steering.clone()) { Ok(agent) => agent, Err(err) => { notice(state, room, "error", err.message); @@ -163,6 +181,8 @@ async fn run_turn( let session = agent.session().clone(); if let Err(err) = agent::save_session(state, room, &session) { notice(state, room, "error", err.message); + } else { + steering.commit(); } let data = match outcome { Some(Ok(output)) => { @@ -198,6 +218,112 @@ async fn run_turn( } } +/// The steering source of one turn: chat that arrives while the agent +/// works, appended at the next step boundary. +/// +/// Without it a message posted mid-turn waits for the next turn, so the +/// model never reads "no, on the other branch" until the work the line +/// is about is finished. The framework drains a [`Steering`] between two +/// steps and appends one User-role message per drain, so the line lands +/// in the history without destroying the step in flight (the step is +/// what the mention path drops, and only a mention does). +/// +/// Two messages deliberately stay out of the drain, and the drain stops +/// at the first one it meets so the room log is appended in order: +/// +/// - a mention, which the turn loop answers by dropping the turn. Two +/// handlers for one line would append it twice. +/// - a message with images, which a line of text cannot carry. +/// +/// Neither is lost: the turn loop's boundary pass reads from the same +/// `absorbed_seq` cursor and appends whatever the drain left behind. +/// +/// The source is a query over that cursor and never writes it. The turn +/// commits what it drained once the session holding those lines is +/// saved, so the row can lag behind the history but never lead it, which +/// is the framework's own contract for [`Steering::drain`]: a line that +/// comes back is a line the driver dedupes away, a line retired too early +/// is gone. +struct RoomSteering { + state: Shared, + room: String, + /// The row's cursor when the turn started, the boundary pass's last + /// append. The source never goes behind it: those lines are in the + /// history, and reading them again would append them twice. + seeded: i64, + /// The cursor after this turn's drains. Held here, not in the row: + /// only [`RoomSteering::commit`] writes it, once the session that + /// holds the lines is saved. + absorbed: AtomicI64, +} + +impl RoomSteering { + fn new(state: Shared, room: String, seeded: i64) -> Self { + Self { + state, + room, + seeded, + absorbed: AtomicI64::new(seeded), + } + } + + /// Writes the drained cursor to the room's row, the boundary pass's + /// order: append, checkpoint, advance. A crash before the checkpoint + /// leaves the row behind, so the next boundary pass re-announces a + /// line rather than losing it, and the framework's per-turn dedupe + /// keeps that repeat out of one turn's history. + fn commit(&self) { + let absorbed = self.absorbed.load(Ordering::SeqCst); + if absorbed == self.seeded { + return; + } + let written = self.state.db.conn().execute( + "UPDATE rooms SET absorbed_seq = ?1 WHERE id = ?2", + rusqlite::params![absorbed, self.room], + ); + if let Err(err) = written { + notice( + &self.state, + &self.room, + "error", + format!("cannot advance the room's message cursor: {err}"), + ); + } + } +} + +impl Steering for RoomSteering { + fn drain(&self) -> Vec { + let absorbed = self.absorbed.load(Ordering::SeqCst); + let Ok(messages) = pending_messages(&self.state, &self.room, absorbed) else { + return Vec::new(); + }; + let (lines, last) = steerable(&messages, absorbed); + if last != absorbed { + self.absorbed.store(last, Ordering::SeqCst); + } + lines + } +} + +/// The lines one drain can carry, and the cursor after them: everything +/// in log order up to the first line it cannot carry, a mention (the drop +/// path owns that one) or a message with images (a line of text cannot +/// hold them). The caller leaves the rest to the next boundary pass, so +/// the room log is appended in its own order. +fn steerable(messages: &[RoomMessage], from: i64) -> (Vec, i64) { + let mut lines = Vec::new(); + let mut last = from; + for message in messages { + if message.mentions || !message.attachments.is_empty() { + break; + } + lines.push(format!("{}: {}", message.author_name, message.text)); + last = message.seq as i64; + } + (lines, last) +} + fn pending_messages(state: &Shared, room: &str, absorbed: i64) -> AppResult> { let conn = state.db.conn(); let mut stmt = conn.prepare( @@ -396,3 +522,177 @@ fn truncate(text: &str, max: usize) -> String { } format!("{}\n[truncated]", &text[..end]) } + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use super::*; + use crate::models::Attachment; + + fn line(seq: u64, text: &str, mentions: bool) -> RoomMessage { + RoomMessage { + seq, + id: format!("m{seq}"), + author_id: Some("a1".into()), + author_name: "ana".into(), + author_kind: "human".into(), + text: text.into(), + mentions, + created_at: 0, + attachments: Vec::new(), + } + } + + fn image(seq: u64, text: &str) -> RoomMessage { + RoomMessage { + attachments: vec![Attachment { + id: format!("att{seq}"), + mime: "image/png".into(), + size: 40, + }], + ..line(seq, text, false) + } + } + + /// A state over a fresh database holding one account and one room. + fn room(absorbed: i64) -> (Shared, PathBuf) { + let dir = std::env::temp_dir().join(format!("rhema-steering-{}", random_id(10))); + let db = crate::db::Db::open(&dir.join("test.db")).expect("db"); + let secrets = + crate::crypto::Secrets::load_or_create(&dir.join("test.key")).expect("secrets"); + let state = Arc::new(crate::state::AppState { + config: crate::config::Config::default(), + db, + secrets, + hub: crate::state::Hub::default(), + rooms: Default::default(), + workers: Default::default(), + presence: Default::default(), + logins: Default::default(), + }); + let conn = state.db.conn(); + conn.execute( + "INSERT INTO accounts (id, handle, display_name, created_at) + VALUES ('a1', 'ana', 'Ana', 1)", + [], + ) + .expect("account"); + conn.execute( + "INSERT INTO rooms (id, name, owner_id, workspace, absorbed_seq, created_at) + VALUES ('r1', 'Room', 'a1', 'ws', ?1, 1)", + rusqlite::params![absorbed], + ) + .expect("room"); + drop(conn); + (state, dir) + } + + /// Posts one chat line the way the API does: the event's sequence is + /// the message's own, and the cursor reads that field. + fn post(state: &Shared, mut message: RoomMessage) -> i64 { + let seq = state.hub.next_seq(&state.db, "r1"); + message.seq = seq; + let data = serde_json::to_value(&message).expect("json"); + state + .hub + .insert(&state.db, "r1", seq, "message", &data) + .expect("event"); + seq as i64 + } + + fn cursor(state: &Shared) -> i64 { + state + .db + .scalar("SELECT absorbed_seq FROM rooms WHERE id = 'r1'", []) + .expect("cursor") + } + + #[test] + fn a_drain_stops_at_the_first_line_it_cannot_carry() { + let messages = [ + line(4, "one", false), + image(5, "two"), + line(6, "three", false), + ]; + assert_eq!(steerable(&messages, 3), (vec!["ana: one".to_owned()], 4)); + + let messages = [ + line(4, "one", false), + line(5, "@rhema two", true), + line(6, "three", false), + ]; + assert_eq!(steerable(&messages, 3), (vec!["ana: one".to_owned()], 4)); + + let (lines, cursor) = steerable(&[line(4, "@rhema two", true)], 3); + assert!(lines.is_empty()); + assert_eq!(cursor, 3, "a drain that carries nothing moves nothing"); + } + + #[test] + fn a_drain_seeded_at_the_boundary_pass_reads_nothing_back() { + let (state, dir) = room(0); + post(&state, line(0, "check the other branch", false)); + let boundary = post(&state, line(0, "@rhema go", true)); + state + .db + .conn() + .execute( + "UPDATE rooms SET absorbed_seq = ?1 WHERE id = 'r1'", + rusqlite::params![boundary], + ) + .expect("boundary cursor"); + + let steering = RoomSteering::new(state.clone(), "r1".into(), boundary); + assert!( + steering.drain().is_empty(), + "the batch the boundary pass appended is already in the history" + ); + steering.commit(); + assert_eq!(cursor(&state), boundary); + + drop(steering); + drop(state); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_drain_holds_the_row_until_the_turn_commits() { + let (state, dir) = room(0); + let first = post(&state, line(0, "check the other branch", false)); + let steering = RoomSteering::new(state.clone(), "r1".into(), 0); + + assert_eq!(steering.drain(), ["ana: check the other branch"]); + assert_eq!(cursor(&state), 0, "the row waits for the checkpoint"); + assert!( + steering.drain().is_empty(), + "a line the turn took does not come back" + ); + + steering.commit(); + assert_eq!(cursor(&state), first); + + drop(steering); + drop(state); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_mention_left_to_the_boundary_pass_is_not_committed() { + let (state, dir) = room(0); + post(&state, line(0, "@rhema go", true)); + let steering = RoomSteering::new(state.clone(), "r1".into(), 0); + + assert!(steering.drain().is_empty()); + steering.commit(); + assert_eq!( + cursor(&state), + 0, + "a drain that took nothing commits nothing" + ); + + drop(steering); + drop(state); + let _ = std::fs::remove_dir_all(&dir); + } +}