diff --git a/specs/rhema-together.md b/specs/rhema-together.md index 9ac8bb3..6f012f8 100644 --- a/specs/rhema-together.md +++ b/specs/rhema-together.md @@ -378,6 +378,9 @@ shows `Rhema is working...` until `turn_end`. When the turn ends, the log gets one collapsed line: `rhema finished ยท 3 steps`. Expanding it shows the draft text, thinking, tool calls, and usage. Nothing from the model stream is visible by default. The summary line is per turn, not per message. +An open turn does not outlive the process: at startup the server appends +an interrupted `turn_end` for any `turn_start` without one, so a restart +cannot leave the status line working over no task. ### Preview diff --git a/src/main.rs b/src/main.rs index 309e030..c4e35c2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -54,6 +54,9 @@ async fn main() -> anyhow::Result<()> { presence: Default::default(), logins: Default::default(), }); + // A previous process may have stopped between a turn's start and its + // end. Close those turns before the feed can replay them as running. + room::runner::close_open_turns(&state); let app = api::router(state).layer(TraceLayer::new_for_http()); let listener = tokio::net::TcpListener::bind(&config.listen).await?; tracing::info!(listen = %config.listen, "rhema-together"); diff --git a/src/room/runner.rs b/src/room/runner.rs index eed8255..3f34135 100644 --- a/src/room/runner.rs +++ b/src/room/runner.rs @@ -345,6 +345,75 @@ fn pending_messages(state: &Shared, room: &str, absorbed: i64) -> AppResult> = HashMap::new(); + { + let conn = state.db.conn(); + let mut stmt = match conn.prepare( + "SELECT room_id, kind, data FROM events + WHERE kind IN ('turn_start', 'turn_end') + ORDER BY room_id, seq", + ) { + Ok(stmt) => stmt, + Err(err) => { + tracing::error!(error = %err, "cannot read turns to close"); + return; + } + }; + let rows = match stmt.query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + )) + }) { + Ok(rows) => rows, + Err(err) => { + tracing::error!(error = %err, "cannot read turns to close"); + return; + } + }; + for row in rows { + let Ok((room, kind, data)) = row else { + continue; + }; + let turn_id = serde_json::from_str::(&data) + .ok() + .and_then(|value| value.get("turn_id")?.as_str().map(str::to_owned)); + let Some(turn_id) = turn_id else { + continue; + }; + let open = pending.entry(room).or_default(); + if kind == "turn_start" { + open.push(turn_id); + } else if let Some(index) = open.iter().rposition(|id| id == &turn_id) { + open.remove(index); + } + } + } + for (room, turns) in pending { + for turn_id in turns { + let data = json!({ + "turn_id": turn_id, + "status": "interrupted", + "usage": null, + "steps": 0, + }); + if let Err(err) = state.hub.durable(&state.db, &room, "turn_end", data) { + tracing::error!(error = %err, room = %room, "cannot close a turn left open"); + } + } + } +} + fn notice(state: &Shared, room: &str, level: &str, text: impl Into) { let _ = state.hub.durable( &state.db, @@ -695,4 +764,82 @@ mod tests { drop(state); let _ = std::fs::remove_dir_all(&dir); } + + fn turn_event(state: &Shared, kind: &str, turn_id: &str) { + state + .hub + .durable(&state.db, "r1", kind, json!({ "turn_id": turn_id })) + .expect("turn event"); + } + + fn turn_ends(state: &Shared) -> Vec { + let conn = state.db.conn(); + let mut stmt = conn + .prepare( + "SELECT data FROM events + WHERE room_id = 'r1' AND kind = 'turn_end' ORDER BY seq", + ) + .expect("statement"); + stmt.query_map([], |row| row.get::<_, String>(0)) + .expect("rows") + .filter_map(Result::ok) + .filter_map(|data| serde_json::from_str(&data).ok()) + .collect() + } + + #[test] + fn a_turn_left_open_is_closed_as_interrupted() { + let (state, dir) = room(0); + turn_event(&state, "turn_start", "t1"); + close_open_turns(&state); + + let ends = turn_ends(&state); + assert_eq!(ends.len(), 1); + assert_eq!(ends[0]["turn_id"], "t1"); + assert_eq!(ends[0]["status"], "interrupted"); + + close_open_turns(&state); + assert_eq!( + turn_ends(&state).len(), + 1, + "a turn with its end in the log stays closed" + ); + + drop(state); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_finished_turn_is_left_alone() { + let (state, dir) = room(0); + turn_event(&state, "turn_start", "t1"); + turn_event(&state, "turn_end", "t1"); + + close_open_turns(&state); + assert_eq!( + turn_ends(&state).len(), + 1, + "a turn that ended before the restart needs no second end" + ); + + drop(state); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn only_the_turn_still_open_is_closed() { + let (state, dir) = room(0); + turn_event(&state, "turn_start", "t1"); + turn_event(&state, "turn_end", "t1"); + turn_event(&state, "turn_start", "t2"); + + close_open_turns(&state); + let ends = turn_ends(&state); + assert_eq!(ends.len(), 2); + assert_eq!(ends[1]["turn_id"], "t2"); + assert_eq!(ends[1]["status"], "interrupted"); + + drop(state); + let _ = std::fs::remove_dir_all(&dir); + } }