fix(claw): open a fresh stream on the newest turn's first event

A client with no cursor opens on the newest 400 events, and the route cut
that window back to the first question in it. A turn longer than the
window has no question inside it, so the cut did nothing and the replay
started mid-turn. A reload then landed on the middle of a reply: the
question was gone from the top, and so was everything the turn began
with, attachments included. A turn that attaches a file and then streams
a long answer hits this every time.

The window now widens by doubling while it sits inside one turn, up to
the history scan cap, and a record that opens inside a turn comes back
whole. A record with no question in it reads once to its start and
stops, so the walk still terminates.
This commit is contained in:
vhaudiquet committed 2026-11-24 21:33:15 +01:00
1 parent 04b06e7623
commit ea6edfe67a
3 files changed
+121 -31

No files matched your search

+8 -5
View File
@@ -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 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 against the live feed, and the frames of both carry their seqs, so a
client that reconnects sends `?since=<last seq it saw>` and receives client that reconnects sends `?since=<last seq it saw>` and receives
exactly the gap. With no cursor the replay is the tail — the newest 400 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 events, cut back to the first turn boundary in them. The window widens
session paints its latest turn at once instead of replaying everything; by doubling while it sits inside one turn, because a long agent turn
the turns above it come from the history route, one whole turn per streams hundreds of deltas and a reload that opened mid-reply would
page, each ending exactly where the previous page began. A cursor the 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;` record can no longer serve (a wiped table) answers with a `reset;`
comment and the tail, and the client rebuilds rather than splice. comment and the tail, and the client rebuilds rather than splice.
+6 -26
View File
@@ -1095,19 +1095,14 @@ async fn events(
let key = ResourceKey::from(key); let key = ResourceKey::from(key);
let (replay, mut receiver) = match query.since { let (replay, mut receiver) = match query.since {
Some(cursor) => state.hub.replay_after(&key, cursor, TAIL_WINDOW), 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; let stale = replay.stale;
// A tail window can open mid-turn (the oldest events in it belong let history = replay.events;
// 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
};
// The pump decouples the broadcast channel from the SSE body: the // The pump decouples the broadcast channel from the SSE body: the
// client's disconnect closes the body, which fails the send, which // client's disconnect closes the body, which fails the send, which
// ends the pump. The stream never ends on its own — a chat UI // 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<crate::hub::SeqEvent>) -> Vec<crate::hub::SeqEvent> {
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 /// 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 /// oldest event the client holds; absent reads from the newest), and
/// `limit` is the most events it may hold before the page is widened /// `limit` is the most events it may hold before the page is widened
+107
View File
@@ -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<TurnEvent>) {
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 /// One page of the record older than `before` (`None` reads from the
/// newest), ending exactly at `before` and starting at a turn's /// newest), ending exactly at `before` and starting at a turn's
/// first event — the page a client walking backward asks for, so a /// 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"))]); 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 /// Backward paging: each page ends where the last began and starts
/// on a turn boundary, so a transcript stacks pages without gaps, /// on a turn boundary, so a transcript stacks pages without gaps,
/// overlaps, or a fragment at its top. /// overlaps, or a fragment at its top.