room: steer mid-turn chat to the next step boundary #1
No files matched your search
@@ -84,8 +84,9 @@ web/app/ Nuxt 4 SPA (no SSR)
|
|||||||
the turn future (turn-level steering) and starts a new turn over the
|
the turn future (turn-level steering) and starts a new turn over the
|
||||||
committed session. A message without a mention never drops anything:
|
committed session. A message without a mention never drops anything:
|
||||||
`runner::RoomSteering` hands it to the framework's steering hook, which
|
`runner::RoomSteering` hands it to the framework's steering hook, which
|
||||||
appends it at the next step boundary and advances `absorbed_seq` so the
|
appends it at the next step boundary; the turn advances `absorbed_seq`
|
||||||
next boundary pass cannot repeat it. Do not drop the room task.
|
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<room>-p<port>-<expiry>-<hmac>.<preview
|
- The preview host label is `r<room>-p<port>-<expiry>-<hmac>.<preview
|
||||||
host>` for a port, or `r<room>-s<hash>-<expiry>-<hmac>.<preview host>`
|
host>` for a port, or `r<room>-s<hash>-<expiry>-<hmac>.<preview host>`
|
||||||
for a static target. The HMAC covers the target and expiry with a key
|
for a static target. The HMAC covers the target and expiry with a key
|
||||||
|
|||||||
+10
-5
@@ -194,11 +194,16 @@ The mid-turn half of that is the framework's steering hook
|
|||||||
(`HostAgentConfig::steering`), not a step-level drop: the turn's
|
(`HostAgentConfig::steering`), not a step-level drop: the turn's
|
||||||
`RoomSteering` source hands the driver one User-role line per drain at a
|
`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
|
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 —
|
the step in flight dying. It stops at the first line it cannot carry, a
|
||||||
a mention, which the drop path owns, or a message with images, which a
|
mention (the drop path owns that one) or a message with images (a line
|
||||||
line cannot — and leaves the cursor there, so the boundary pass appends
|
of text cannot hold them), and leaves the cursor there, so the boundary
|
||||||
them in the log's order. What steering still cannot do is stop a running
|
pass appends them in the log's order. The source only reads that
|
||||||
command: only the mention drop does that, and only between steps.
|
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
|
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.
|
into the same restart, in order, one message each. Nothing is folded.
|
||||||
|
|||||||
+5
-2
@@ -29,6 +29,9 @@ pub struct TurnConfig {
|
|||||||
/// The model's stored vision fact; `None` is unknown, not no.
|
/// The model's stored vision fact; `None` is unknown, not no.
|
||||||
pub supports_vision: Option<bool>,
|
pub supports_vision: Option<bool>,
|
||||||
pub max_turn_steps: u32,
|
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 absorbed_seq: i64,
|
||||||
pub seeded: bool,
|
pub seeded: bool,
|
||||||
pub owner_name: String,
|
pub owner_name: String,
|
||||||
@@ -308,7 +311,7 @@ pub fn build_agent(
|
|||||||
state: &Shared,
|
state: &Shared,
|
||||||
config: &TurnConfig,
|
config: &TurnConfig,
|
||||||
session: Session,
|
session: Session,
|
||||||
steering: Option<Arc<dyn Steering>>,
|
steering: Arc<dyn Steering>,
|
||||||
) -> AppResult<HostAgent> {
|
) -> AppResult<HostAgent> {
|
||||||
let sandbox = build_sandbox(state, config)?;
|
let sandbox = build_sandbox(state, config)?;
|
||||||
let executor = Arc::new(ShellSandbox::new(Arc::new(sandbox)));
|
let executor = Arc::new(ShellSandbox::new(Arc::new(sandbox)));
|
||||||
@@ -359,7 +362,7 @@ pub fn build_agent(
|
|||||||
shell_env: Default::default(),
|
shell_env: Default::default(),
|
||||||
transcript: Some(Default::default()),
|
transcript: Some(Default::default()),
|
||||||
summary_worker: None,
|
summary_worker: None,
|
||||||
steering,
|
steering: Some(steering),
|
||||||
home: None,
|
home: None,
|
||||||
environment: Some(rhema_host_agent::remote_notice(
|
environment: Some(rhema_host_agent::remote_notice(
|
||||||
"ssh",
|
"ssh",
|
||||||
|
|||||||
+243
-32
@@ -40,7 +40,7 @@ pub async fn run(state: Shared, room: String, mut rx: UnboundedReceiver<Wake>) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
loop {
|
loop {
|
||||||
let config = match agent::load_turn_config(&state, &room) {
|
let mut config = match agent::load_turn_config(&state, &room) {
|
||||||
Ok(config) => config,
|
Ok(config) => config,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
notice(&state, &room, "error", err.message);
|
notice(&state, &room, "error", err.message);
|
||||||
@@ -87,11 +87,18 @@ pub async fn run(state: Shared, room: String, mut rx: UnboundedReceiver<Wake>) {
|
|||||||
pending_mention = false;
|
pending_mention = false;
|
||||||
break;
|
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(
|
let _ = state.db.conn().execute(
|
||||||
"UPDATE rooms SET absorbed_seq = ?1 WHERE id = ?2",
|
"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;
|
pending_mention = false;
|
||||||
let trigger = pending
|
let trigger = pending
|
||||||
.iter()
|
.iter()
|
||||||
@@ -124,8 +131,12 @@ async fn run_turn(
|
|||||||
rx: &mut UnboundedReceiver<Wake>,
|
rx: &mut UnboundedReceiver<Wake>,
|
||||||
pending_mention: &mut bool,
|
pending_mention: &mut bool,
|
||||||
) {
|
) {
|
||||||
let steering = steering_for(state, room, config);
|
let steering = Arc::new(RoomSteering::new(
|
||||||
let mut agent = match agent::build_agent(state, config, session, Some(steering)) {
|
state.clone(),
|
||||||
|
room.to_owned(),
|
||||||
|
config.absorbed_seq,
|
||||||
|
));
|
||||||
|
let mut agent = match agent::build_agent(state, config, session, steering.clone()) {
|
||||||
Ok(agent) => agent,
|
Ok(agent) => agent,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
notice(state, room, "error", err.message);
|
notice(state, room, "error", err.message);
|
||||||
@@ -170,6 +181,8 @@ async fn run_turn(
|
|||||||
let session = agent.session().clone();
|
let session = agent.session().clone();
|
||||||
if let Err(err) = agent::save_session(state, room, &session) {
|
if let Err(err) = agent::save_session(state, room, &session) {
|
||||||
notice(state, room, "error", err.message);
|
notice(state, room, "error", err.message);
|
||||||
|
} else {
|
||||||
|
steering.commit();
|
||||||
}
|
}
|
||||||
let data = match outcome {
|
let data = match outcome {
|
||||||
Some(Ok(output)) => {
|
Some(Ok(output)) => {
|
||||||
@@ -224,34 +237,57 @@ async fn run_turn(
|
|||||||
///
|
///
|
||||||
/// Neither is lost: the turn loop's boundary pass reads from the same
|
/// Neither is lost: the turn loop's boundary pass reads from the same
|
||||||
/// `absorbed_seq` cursor and appends whatever the drain left behind.
|
/// `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 {
|
struct RoomSteering {
|
||||||
state: Shared,
|
state: Shared,
|
||||||
room: String,
|
room: String,
|
||||||
/// The room's `absorbed_seq`, as the history and the log agree on it.
|
/// The row's cursor when the turn started, the boundary pass's last
|
||||||
/// Shared with the turn loop through the row: a line drained here is
|
/// append. The source never goes behind it: those lines are in the
|
||||||
/// already appended, so the next boundary pass must not append it
|
/// history, and reading them again would append them twice.
|
||||||
/// again.
|
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,
|
absorbed: AtomicI64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RoomSteering {
|
impl RoomSteering {
|
||||||
fn new(state: Shared, room: String, absorbed: i64) -> Self {
|
fn new(state: Shared, room: String, seeded: i64) -> Self {
|
||||||
Self {
|
Self {
|
||||||
state,
|
state,
|
||||||
room,
|
room,
|
||||||
absorbed: AtomicI64::new(absorbed),
|
seeded,
|
||||||
|
absorbed: AtomicI64::new(seeded),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Moves the cursor in the row, and only then in memory, so a failed
|
/// Writes the drained cursor to the room's row, the boundary pass's
|
||||||
/// write re-announces the line next turn instead of dropping it.
|
/// order: append, checkpoint, advance. A crash before the checkpoint
|
||||||
fn advance(&self, seq: i64) {
|
/// 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(
|
let written = self.state.db.conn().execute(
|
||||||
"UPDATE rooms SET absorbed_seq = ?1 WHERE id = ?2",
|
"UPDATE rooms SET absorbed_seq = ?1 WHERE id = ?2",
|
||||||
rusqlite::params![seq, self.room],
|
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}"),
|
||||||
);
|
);
|
||||||
if written.is_ok() {
|
|
||||||
self.absorbed.store(seq, Ordering::SeqCst);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -262,8 +298,22 @@ impl Steering for RoomSteering {
|
|||||||
let Ok(messages) = pending_messages(&self.state, &self.room, absorbed) else {
|
let Ok(messages) = pending_messages(&self.state, &self.room, absorbed) else {
|
||||||
return Vec::new();
|
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<String>, i64) {
|
||||||
let mut lines = Vec::new();
|
let mut lines = Vec::new();
|
||||||
let mut last = absorbed;
|
let mut last = from;
|
||||||
for message in messages {
|
for message in messages {
|
||||||
if message.mentions || !message.attachments.is_empty() {
|
if message.mentions || !message.attachments.is_empty() {
|
||||||
break;
|
break;
|
||||||
@@ -271,20 +321,7 @@ impl Steering for RoomSteering {
|
|||||||
lines.push(format!("{}: {}", message.author_name, message.text));
|
lines.push(format!("{}: {}", message.author_name, message.text));
|
||||||
last = message.seq as i64;
|
last = message.seq as i64;
|
||||||
}
|
}
|
||||||
if last != absorbed {
|
(lines, last)
|
||||||
self.advance(last);
|
|
||||||
}
|
|
||||||
lines
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The turn's steering source, over the cursor the turn started from.
|
|
||||||
fn steering_for(state: &Shared, room: &str, config: &TurnConfig) -> Arc<dyn Steering> {
|
|
||||||
Arc::new(RoomSteering::new(
|
|
||||||
state.clone(),
|
|
||||||
room.to_owned(),
|
|
||||||
config.absorbed_seq,
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pending_messages(state: &Shared, room: &str, absorbed: i64) -> AppResult<Vec<RoomMessage>> {
|
fn pending_messages(state: &Shared, room: &str, absorbed: i64) -> AppResult<Vec<RoomMessage>> {
|
||||||
@@ -485,3 +522,177 @@ fn truncate(text: &str, max: usize) -> String {
|
|||||||
}
|
}
|
||||||
format!("{}\n[truncated]", &text[..end])
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user