diff --git a/crates/rhema-claw/README.md b/crates/rhema-claw/README.md index 8d59a69..0ee940d 100644 --- a/crates/rhema-claw/README.md +++ b/crates/rhema-claw/README.md @@ -204,11 +204,14 @@ The seq is the record's dense per-key number for the event, and it is the client's cursor. A subscription opens with a replay cut atomically against the live feed, and the frames of both carry their seqs, so a client that reconnects sends `?since=` and receives -exactly the gap. With no cursor the replay is the tail — the newest 400 -events, cut back to the first turn boundary in them — so a weeks-old -session paints its latest turn at once instead of replaying everything; -the turns above it come from the history route, one whole turn per -page, each ending exactly where the previous page began. A cursor the +exactly the gap. With no cursor the replay is the tail: the newest 400 +events, cut back to the first turn boundary in them. The window widens +by doubling while it sits inside one turn, because a long agent turn +streams hundreds of deltas and a reload that opened mid-reply would +drop what the turn began with. A weeks-old session thus paints its +latest turn at once instead of replaying everything, and the turns +above it come from the history route, one whole turn per page, each +ending exactly where the previous page began. A cursor the record can no longer serve (a wiped table) answers with a `reset;` comment and the tail, and the client rebuilds rather than splice. diff --git a/crates/rhema-claw/src/http.rs b/crates/rhema-claw/src/http.rs index 104ab06..26322de 100644 --- a/crates/rhema-claw/src/http.rs +++ b/crates/rhema-claw/src/http.rs @@ -1095,19 +1095,14 @@ async fn events( let key = ResourceKey::from(key); let (replay, mut receiver) = match query.since { Some(cursor) => state.hub.replay_after(&key, cursor, TAIL_WINDOW), - None => state.hub.replay_tail(&key, TAIL_WINDOW), + // A tail window can open mid-turn, and a transcript that opens + // on a reply with no question above it reads as a bug. The hub + // widens the window back to the turn's first event. A cursor + // replay is exact by construction and is never cut. + None => state.hub.replay_tail_turn(&key, TAIL_WINDOW), }; let stale = replay.stale; - // A tail window can open mid-turn (the oldest events in it belong - // to a turn that started before the window), and a transcript that - // opens on a reply with no question above it reads as a bug. Cut - // back to the window's first question. A cursor replay is exact by - // construction and is never cut. - let history = if query.since.is_none() { - snap_to_turn(replay.events) - } else { - replay.events - }; + let history = replay.events; // The pump decouples the broadcast channel from the SSE body: the // client's disconnect closes the body, which fails the send, which // ends the pump. The stream never ends on its own — a chat UI @@ -1255,21 +1250,6 @@ fn sse_event(seq: i64, turn: TurnEvent) -> SseEvent { } } -/// A replay window cut back to its first question: the events before -/// it belong to a turn whose start the window did not reach, and half a -/// turn reads as a bug. A window with no question in it (one turn -/// longer than the window) is returned whole — showing it beats showing -/// nothing, and the walk back through history continues above it. -fn snap_to_turn(mut events: Vec) -> Vec { - match events - .iter() - .position(|(_, event)| matches!(event, TurnEvent::UserMessage { .. })) - { - Some(index) if index > 0 => events.split_off(index), - _ => events, - } -} - /// The history route's query: the page ends at `before` (the seq of the /// oldest event the client holds; absent reads from the newest), and /// `limit` is the most events it may hold before the page is widened diff --git a/crates/rhema-claw/src/hub.rs b/crates/rhema-claw/src/hub.rs index a23091b..18026ab 100644 --- a/crates/rhema-claw/src/hub.rs +++ b/crates/rhema-claw/src/hub.rs @@ -331,6 +331,42 @@ impl EventHub { ) } + /// The newest page, cut with the live receiver, starting on a turn's + /// first event: the window a client with no cache opens with. It + /// widens by doubling while the window falls inside one turn, up to + /// [`HISTORY_SCAN_CAP`], and a record that opens inside a turn comes + /// back whole rather than as a fragment. A long agent turn streams + /// hundreds of deltas past the file it handed over, so a reload that + /// landed mid-reply used to drop what the turn began with, images + /// among it. + pub fn replay_tail_turn( + &self, + key: &ResourceKey, + limit: usize, + ) -> (Replay, broadcast::Receiver) { + let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner); + let entry = Self::entry(&mut entries, key, self.capacity); + let store = self.record_store.as_deref(); + let mut want = limit.max(1); + let events = loop { + let window = Self::record_tail(store, entry, key, want); + let opens_on_turn = window + .first() + .is_some_and(|(_, event)| matches!(event, TurnEvent::UserMessage { .. })); + if opens_on_turn || window.len() < want || want >= HISTORY_SCAN_CAP { + break window; + } + want = (want * 2).min(HISTORY_SCAN_CAP); + }; + ( + Replay { + events, + stale: false, + }, + entry.sender.subscribe(), + ) + } + /// One page of the record older than `before` (`None` reads from the /// newest), ending exactly at `before` and starting at a turn's /// first event — the page a client walking backward asks for, so a @@ -916,6 +952,77 @@ mod tests { assert_eq!(replay.events, vec![(4, text("4")), (5, text("5"))]); } + /// The tail a fresh client opens with starts on a question even when + /// the newest turn is longer than the window: a reload must not land + /// on the middle of a reply, where the file the turn handed over (and + /// the question that asked for it) are behind the window. + #[test] + fn a_tail_window_inside_one_turn_widens_to_the_question() { + let hub = EventHub::default(); + let key = key("longturn"); + hub.emit( + &key, + TurnEvent::UserMessage { + text: "q".into(), + images: Vec::new(), + pastes: Vec::new(), + }, + ); + for n in 0..5 { + hub.emit(&key, text(&n.to_string())); + } + // A window of 2 from the end sits inside the turn; the widened + // one opens on the question and holds the whole turn. + let (replay, _) = hub.replay_tail_turn(&key, 2); + assert!(!replay.stale); + assert_eq!( + replay.events.len(), + 6, + "the whole turn: {:?}", + replay.events + ); + assert_eq!(replay.events[0].0, 0); + assert!(matches!(replay.events[0].1, TurnEvent::UserMessage { .. })); + } + + /// The widening stops at the record's start: a record with no + /// question in it replays whole instead of looping after the cap. + #[test] + fn a_tail_window_with_no_question_replays_the_record_once() { + let hub = EventHub::default(); + let key = key("questionless"); + for n in 0..6 { + hub.emit(&key, text(&n.to_string())); + } + let (replay, _) = hub.replay_tail_turn(&key, 2); + assert_eq!(replay.events.len(), 6); + assert_eq!(replay.events[0].0, 0, "the record's first event"); + } + + /// A tail that already opens on a question is left exactly as asked: + /// no widening past the window the store served. + #[test] + fn a_tail_window_on_a_question_is_not_widened() { + let hub = EventHub::default(); + let key = key("plain"); + for turn in 0..3 { + hub.emit( + &key, + TurnEvent::UserMessage { + text: format!("q{turn}"), + images: Vec::new(), + pastes: Vec::new(), + }, + ); + hub.emit(&key, text(&format!("a{turn}"))); + hub.emit(&key, done(&format!("a{turn}"))); + } + // Seqs 6, 7, 8: the third turn, opening on its question. + let (replay, _) = hub.replay_tail_turn(&key, 3); + assert_eq!(replay.events.len(), 3); + assert_eq!(replay.events[0].0, 6); + } + /// Backward paging: each page ends where the last began and starts /// on a turn boundary, so a transcript stacks pages without gaps, /// overlaps, or a fragment at its top.