diff --git a/crates/rhema-claw/README.md b/crates/rhema-claw/README.md index f5e9258..8d59a69 100644 --- a/crates/rhema-claw/README.md +++ b/crates/rhema-claw/README.md @@ -212,6 +212,15 @@ 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. +The history route answers for every key in the inventory, not only the +resident prefixes. A key outside them — a forge thread, a finished +coding job — has no turn record to subscribe to, but the engine +checkpoints its session after every step. The route reads that stash +back as the same event shapes, cut into the same pages, and marks the +response `read_only: true`: the transcript a client can render, with no +stream to follow and no message the daemon would take. A key with no +stash yet answers an empty page. + A chat UI subscribes once, POSTs messages, and resets its mirror whenever the stream (re)opens, letting the replay rebuild it; the daemon owns the conversation, so the client mirrors the stream rather than diff --git a/crates/rhema-claw/src/http.rs b/crates/rhema-claw/src/http.rs index 6fa3969..104ab06 100644 --- a/crates/rhema-claw/src/http.rs +++ b/crates/rhema-claw/src/http.rs @@ -1287,24 +1287,30 @@ struct HistoryQuery { /// through a session's history. The page starts on a turn boundary and /// ends exactly at `before`, so pages stack without gaps or overlaps. /// The response's `more` says whether anything precedes it: `false` -/// means the client has reached the session's first event. +/// means the client has reached the session's first event, and +/// `read_only` says the page is a snapshot rather than a record a +/// message could extend. +/// +/// A key outside the resident context has no hub record: its handler +/// never streams. The daemon still holds the session the engine +/// checkpointed, so the route serves that history instead, through +/// [`crate::thread`] — the same page shape, cut the same way, so a chat +/// surface renders a finished forge thread with the renderer it already +/// has. Those keys take no message ([`messages`] refuses them), which +/// is what `read_only` tells the client. async fn session_history( State(state): State, Path(key): Path, Query(query): Query, ) -> Response { - if !crate::interactive::is_resident_key(&key) { - return ( - StatusCode::BAD_REQUEST, - Json(json!({"error": "key must start with interactive:, task:, or phone:"})), - ) - .into_response(); - } let key = ResourceKey::from(key); let limit = query .limit .unwrap_or(HISTORY_PAGE) .clamp(1, HISTORY_PAGE_MAX); + if !crate::interactive::is_resident_key(key.as_str()) { + return stashed_history(&state, &key, query.before, limit); + } let page = state.hub.replay_turn_before(&key, query.before, limit); // Whether anything sits below the page: a lookup, not a read. let more = match page.first().map(|(seq, _)| *seq) { @@ -1315,7 +1321,45 @@ async fn session_history( .into_iter() .map(|(seq, event)| json!({"seq": seq, "event": event})) .collect(); - Json(json!({"events": events, "more": more})).into_response() + Json(json!({"events": events, "more": more, "read_only": false})).into_response() +} + +/// The snapshot page for a key the resident context does not own: the +/// record's session stash, turned back into turn events. A key with no +/// record, or a record the engine never checkpointed, has nothing to +/// show and answers an empty page rather than a 404 — the inventory +/// lists the key, and an empty thread is the truth about it. +fn stashed_history( + state: &ClawState, + key: &ResourceKey, + before: Option, + limit: usize, +) -> Response { + let record = match state.store.load(key) { + Ok(record) => record, + Err(err) => { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": format!("session lookup for {key} failed: {err}")})), + ) + .into_response(); + } + }; + let (page, more) = match record.as_ref().and_then(|record| record.session.as_ref()) { + Some(session) => { + let outcome = record + .as_ref() + .and_then(|record| record.last_outcome.as_ref()); + let events = crate::thread::events(&session.core, outcome); + crate::thread::page(&events, before, limit) + } + None => (Vec::new(), false), + }; + let events: Vec = page + .into_iter() + .map(|(seq, event)| json!({"seq": seq, "event": event})) + .collect(); + Json(json!({"events": events, "more": more, "read_only": true})).into_response() } async fn watches_list(State(state): State) -> Result, (StatusCode, String)> { diff --git a/crates/rhema-claw/src/interactive.rs b/crates/rhema-claw/src/interactive.rs index a375c45..007d7fd 100644 --- a/crates/rhema-claw/src/interactive.rs +++ b/crates/rhema-claw/src/interactive.rs @@ -897,7 +897,7 @@ fn final_text(message: &Message) -> Option { /// A tool result's bounded summary for the stream: the first line, cut /// at 72 characters like the daemon's own log lines. -fn snippet(content: &str) -> String { +pub(crate) fn snippet(content: &str) -> String { let line = content.lines().next().unwrap_or(""); let mut cut = line.chars().take(72).collect::(); if line.chars().count() > 72 { @@ -925,7 +925,7 @@ struct HubSink { /// arguments JSON. A call whose args never streamed, or that parses to /// something without a string `command`, renders without one — the TUI's /// transcript makes the same bargain with the same deltas. -fn shell_command(args: Option<&str>) -> Option { +pub(crate) fn shell_command(args: Option<&str>) -> Option { let parsed = serde_json::from_str::(args?).ok()?; parsed.get("command")?.as_str().map(str::to_owned) } diff --git a/crates/rhema-claw/src/lib.rs b/crates/rhema-claw/src/lib.rs index bd51eb9..890d57f 100644 --- a/crates/rhema-claw/src/lib.rs +++ b/crates/rhema-claw/src/lib.rs @@ -105,6 +105,7 @@ pub mod steer; pub mod task_source; pub mod task_store; pub mod task_tools; +pub mod thread; pub mod toolkit; pub mod turn_store; pub(crate) mod vision; diff --git a/crates/rhema-claw/src/thread.rs b/crates/rhema-claw/src/thread.rs new file mode 100644 index 0000000..b248f67 --- /dev/null +++ b/crates/rhema-claw/src/thread.rs @@ -0,0 +1,378 @@ +//! Read-only transcripts for the keys the chat surface cannot message. +//! +//! A forge thread, a finished coding job: their dispatches run through +//! handlers that never touch the hub, so the daemon holds no turn +//! record for them. What it does hold is the session stash the +//! step engine checkpoints after every step, with the engine's own +//! history in it. This module turns that history back into the hub's +//! event shapes, so the chat surface renders a finished thread with the +//! renderer it already has, and [`page`] cuts it the way the hub cuts +//! its own record. + +use std::collections::HashMap; + +use rhema_core::{Content, Message, Role, Session as CoreSession, ToolResult}; +use rhema_rsd::Outcome; + +use crate::hub::{SeqEvent, TurnEvent}; +use crate::interactive::{shell_command, snippet}; + +/// One tool call remembered while its result is still to come: the name +/// the result event carries, and the arguments a shell result's command +/// line is read from. +struct Call { + name: String, + args: String, +} + +/// The transcript of a stashed session, as the hub's events: one +/// `user_message`, the turn's deltas and tool rows, one `turn_done` per +/// turn, in history order. `last` is the record's most recent outcome, +/// which the newest turn's end marker carries; the older turns closed +/// the way the handler closes a finished one. +/// +/// Images and pastes ride a user message only when the stash recorded +/// them: a forge or job prompt carries none, and a chat key never takes +/// this path. +pub fn events(session: &CoreSession, last: Option<&Outcome>) -> Vec { + let mut out: Vec = Vec::new(); + let mut calls: HashMap = HashMap::new(); + let mut open = false; + let mut reply: Option = None; + + for message in &session.history { + match message.role { + Role::User => { + close(&mut out, &mut open, reply.take(), "handled"); + out.push(TurnEvent::UserMessage { + text: text_of(message), + images: Vec::new(), + pastes: crate::paste::spans(message), + }); + open = true; + } + Role::Assistant => { + // A stash cut before its first user message still opens + // a turn: the history is what it is. + open = true; + let mut said: Option = None; + for content in &message.content { + match content { + Content::Text(text) => { + if text.trim().is_empty() { + continue; + } + out.push(TurnEvent::TextDelta { text: text.clone() }); + said = Some(text.clone()); + } + Content::ToolCall(call) => { + calls.insert( + call.id.clone(), + Call { + name: call.name.clone(), + args: call.args.to_string(), + }, + ); + out.push(TurnEvent::ToolStart { + name: call.name.clone(), + }); + } + Content::ToolResult(result) => push_result(&mut out, &calls, result), + Content::Image(_) => {} + } + } + if said.is_some() { + reply = said; + } + } + Role::Tool | Role::System => { + for content in &message.content { + if let Content::ToolResult(result) = content { + push_result(&mut out, &calls, result); + } + } + } + } + } + let outcome = outcome_label(last); + close(&mut out, &mut open, reply, &outcome); + out +} + +/// The text blocks of a message, joined the way the model read them. +fn text_of(message: &Message) -> String { + message + .content + .iter() + .filter_map(|content| match content { + Content::Text(text) => Some(text.as_str()), + _ => None, + }) + .collect::>() + .join("\n") +} + +/// The end marker, only for a turn that was open. +fn close(out: &mut Vec, open: &mut bool, reply: Option, outcome: &str) { + if !*open { + return; + } + out.push(TurnEvent::TurnDone { + reply, + outcome: outcome.to_owned(), + }); + *open = false; +} + +/// One tool result as the wire's row: the name its call carried, the +/// bounded snippet the summary holds, and for a shell the command line +/// parsed back out of the call's arguments. +fn push_result(out: &mut Vec, calls: &HashMap, result: &ToolResult) { + let call = calls.get(&result.id); + let name = call + .map(|call| call.name.clone()) + .unwrap_or_else(|| result.id.clone()); + let command = matches!(name.as_str(), "bash" | "run_command") + .then(|| shell_command(call.map(|call| call.args.as_str()))) + .flatten(); + out.push(TurnEvent::ToolResult { + name, + is_error: result.is_error, + summary: snippet(&result.content), + code: result.code, + command, + }); +} + +/// The outcome label a turn's end marker carries, in the handler's own +/// words: a superseded dispatch was cut, a failed one broke. +fn outcome_label(outcome: Option<&Outcome>) -> String { + match outcome { + Some(Outcome::Failed(_)) => "failed", + Some(Outcome::Superseded) => "aborted", + Some(Outcome::Handled) | None => "handled", + } + .to_owned() +} + +/// One page of a stashed transcript, cut the way the hub cuts its own +/// record: at most `limit` events ending at `before`, starting on a +/// turn boundary, with `more` saying whether anything sits below it. A +/// turn longer than `limit` comes back whole rather than split. `seq` +/// numbers the events from 1 in history order — a stable address for as +/// long as the stash does not change. +pub fn page(events: &[TurnEvent], before: Option, limit: usize) -> (Vec, bool) { + let end = match before { + Some(before) => (before - 1).clamp(0, events.len() as i64) as usize, + None => events.len(), + }; + let mut want = limit.max(1); + loop { + let from = end.saturating_sub(want); + let window = &events[from..end]; + let page_start = match window + .iter() + .position(|event| matches!(event, TurnEvent::UserMessage { .. })) + { + Some(index) => from + index, + None if from == 0 => from, + None => { + // The window sits inside one turn: read further back, + // unless there is nothing further back to read. + want = (want * 2).min(crate::hub::HISTORY_SCAN_CAP); + continue; + } + }; + let page = events[page_start..end] + .iter() + .enumerate() + .map(|(offset, event)| ((page_start + offset + 1) as i64, event.clone())) + .collect(); + return (page, page_start > 0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rhema_core::{Image, ToolCall}; + use serde_json::json; + + fn user(text: &str) -> Message { + Message::text(Role::User, text) + } + + fn assistant(content: Vec) -> Message { + Message { + role: Role::Assistant, + content, + annotations: Default::default(), + } + } + + fn result(id: &str, content: &str) -> Message { + Message { + role: Role::Tool, + content: vec![Content::ToolResult(ToolResult { + id: id.to_owned(), + content: content.to_owned(), + is_error: false, + code: Some(0), + images: Vec::new(), + })], + annotations: Default::default(), + } + } + + fn session(history: Vec) -> CoreSession { + CoreSession { + history, + ..CoreSession::default() + } + } + + #[test] + fn a_turn_becomes_the_events_the_hub_would_have_recorded() { + let core = session(vec![ + user("review PR 7"), + assistant(vec![Content::ToolCall(ToolCall { + id: "call-1".to_owned(), + name: "bash".to_owned(), + args: json!({"command": "gh pr diff 7"}), + provider_data: serde_json::Value::Null, + })]), + result("call-1", "diff --git a/x b/x"), + assistant(vec![Content::Text("LGTM.".to_owned())]), + ]); + assert_eq!( + events(&core, Some(&Outcome::Handled)), + vec![ + TurnEvent::UserMessage { + text: "review PR 7".to_owned(), + images: Vec::new(), + pastes: Vec::new(), + }, + TurnEvent::ToolStart { + name: "bash".to_owned(), + }, + TurnEvent::ToolResult { + name: "bash".to_owned(), + is_error: false, + summary: "diff --git a/x b/x".to_owned(), + code: Some(0), + command: Some("gh pr diff 7".to_owned()), + }, + TurnEvent::TextDelta { + text: "LGTM.".to_owned(), + }, + TurnEvent::TurnDone { + reply: Some("LGTM.".to_owned()), + outcome: "handled".to_owned(), + }, + ] + ); + } + + #[test] + fn each_turn_closes_before_the_next_question() { + let core = session(vec![ + user("first"), + assistant(vec![Content::Text("one".to_owned())]), + user("second"), + assistant(vec![Content::Text("two".to_owned())]), + ]); + let events = events(&core, Some(&Outcome::Failed("boom".to_owned()))); + let closes: Vec<&TurnEvent> = events + .iter() + .filter(|event| matches!(event, TurnEvent::TurnDone { .. })) + .collect(); + assert_eq!(closes.len(), 2); + assert_eq!( + closes[0], + &TurnEvent::TurnDone { + reply: Some("one".to_owned()), + outcome: "handled".to_owned(), + } + ); + // The newest turn carries the record's own outcome. + assert_eq!( + closes[1], + &TurnEvent::TurnDone { + reply: Some("two".to_owned()), + outcome: "failed".to_owned(), + } + ); + } + + #[test] + fn a_stash_that_starts_mid_turn_still_closes() { + let core = session(vec![assistant(vec![Content::Text("orphan".to_owned())])]); + assert_eq!( + events(&core, None).last(), + Some(&TurnEvent::TurnDone { + reply: Some("orphan".to_owned()), + outcome: "handled".to_owned(), + }) + ); + } + + #[test] + fn images_in_the_history_do_not_invent_attachment_ids() { + let mut message = user("look"); + message.content.push(Content::Image(Image { + media_type: rhema_core::ImageMediaType::Png, + data: "iVBORw0KGgo=".to_owned(), + })); + let events = events(&session(vec![message]), None); + assert_eq!( + events[0], + TurnEvent::UserMessage { + text: "look".to_owned(), + images: Vec::new(), + pastes: Vec::new(), + } + ); + } + + #[test] + fn a_page_starts_on_a_turn_boundary_and_stacks_backwards() { + let core = session(vec![ + user("zero"), + assistant(vec![Content::Text("a".to_owned())]), + user("one"), + assistant(vec![Content::Text("b".to_owned())]), + user("two"), + assistant(vec![Content::Text("c".to_owned())]), + ]); + let all = events(&core, None); + // The newest page holds the last turn only. + let (newest, more) = page(&all, None, 2); + assert!(more, "two turns sit above it"); + assert!(matches!(newest[0].1, TurnEvent::UserMessage { .. })); + assert_eq!(newest.len(), 3, "a turn comes whole: question, delta, done"); + assert_eq!(newest[0].0, 7, "seqs are absolute, so pages stack"); + // The next page ends exactly where the first begins. + let (older, more) = page(&all, Some(newest[0].0), 2); + assert!(more); + assert_eq!(older[0].0, 4); + let (first, more) = page(&all, Some(older[0].0), 2); + assert!(!more, "the record ends here"); + assert_eq!(first[0].0, 1); + } + + #[test] + fn a_turn_longer_than_the_page_comes_back_whole() { + let core = session(vec![ + user("long"), + assistant(vec![ + Content::Text("a".to_owned()), + Content::Text("b".to_owned()), + Content::Text("c".to_owned()), + ]), + ]); + let all = events(&core, None); + let (whole, more) = page(&all, None, 1); + assert_eq!(whole.len(), all.len()); + assert!(!more); + } +} diff --git a/crates/rhema-claw/tests/http.rs b/crates/rhema-claw/tests/http.rs index df691d2..a296acf 100644 --- a/crates/rhema-claw/tests/http.rs +++ b/crates/rhema-claw/tests/http.rs @@ -4096,3 +4096,116 @@ async fn a_leased_session_is_not_deletable() { assert_eq!(sessions[0]["key"], "interactive:web"); assert_eq!(sessions[0]["state"], "leased", "{sessions:?}"); } + +/// A key the resident context does not own has no turn record: its +/// handler never streams, and the events route refuses it. The history +/// route still opens it, read-only, from the session stash the step +/// engine checkpointed — the same page shape, cut the same way, so a +/// chat surface paints a finished forge thread with its own renderer. +#[tokio::test] +async fn a_forge_thread_reads_back_as_a_read_only_snapshot() { + let dir = tempfile::tempdir().expect("tempdir"); + let db = dir.path().join("dispatch.db"); + let daemon = Daemon::build( + &config(&dir, None), + mock_registry(Arc::new(MockProvider::new([]))), + rhema_rsd::DispatcherConfig::default(), + ) + .expect("the daemon assembles"); + let base = serve(&daemon).await; + let client = reqwest::Client::new(); + + // What a finished dispatch leaves behind: the engine's own history + // in the record's session stash. + let key = ResourceKey::from("github:issue:acme/widgets#7"); + { + let store = SqliteStore::open(&db).expect("the store opens"); + let mut record = rhema_rsd::KeyRecord::fresh(key.clone(), 1); + let mut session = rhema_rsd::Session::fresh(key.clone(), 1); + session.core.history = vec![ + Message::text(Role::User, "review the failing check"), + Message { + annotations: Default::default(), + role: Role::Assistant, + content: vec![Content::ToolCall(rhema_core::ToolCall { + id: "call-1".to_owned(), + name: "bash".to_owned(), + args: json!({"command": "gh pr checks 7"}), + provider_data: Value::Null, + })], + }, + Message { + annotations: Default::default(), + role: Role::Tool, + content: vec![Content::ToolResult(rhema_core::ToolResult { + id: "call-1".to_owned(), + content: "build\tfail\t2m".to_owned(), + is_error: false, + code: Some(1), + images: Vec::new(), + })], + }, + Message::text(Role::Assistant, "The build is red; rerunning."), + ]; + record.session = Some(session); + record.last_outcome = Some(rhema_rsd::Outcome::Handled); + store.save(record, None).expect("the record seeds"); + } + + let page = client + .get(format!( + "{base}/v1/sessions/github%3Aissue%3Aacme%2Fwidgets%237/history" + )) + .send() + .await + .expect("the history request goes out"); + assert_eq!(page.status(), 200, "a stash has a transcript to read"); + let body: Value = page.json().await.expect("the body parses"); + assert_eq!(body["read_only"], true, "the client must not open a stream"); + assert_eq!(body["more"], false); + let events = body["events"].as_array().expect("events is a list"); + let types: Vec<&str> = events + .iter() + .map(|entry| entry["event"]["type"].as_str().expect("a type")) + .collect(); + assert_eq!( + types, + [ + "user_message", + "tool_start", + "tool_result", + "text_delta", + "turn_done" + ], + "{events:?}" + ); + assert_eq!(events[0]["event"]["text"], "review the failing check"); + assert_eq!(events[2]["event"]["name"], "bash"); + assert_eq!( + events[2]["event"]["command"], "gh pr checks 7", + "the shell's command line survives the stash" + ); + assert_eq!(events[2]["event"]["code"], 1); + assert_eq!(events[4]["event"]["reply"], "The build is red; rerunning."); + + // Read-only for real: the message route still refuses the prefix, + // and the stream route refuses it too — a client that followed + // `read_only=false` would retry a 400 forever. + let refused = client + .post(format!( + "{base}/v1/sessions/github%3Aissue%3Aacme%2Fwidgets%237/messages" + )) + .json(&json!({"text": "hello"})) + .send() + .await + .expect("the message posts"); + assert_eq!(refused.status(), 400); + let stream = client + .get(format!( + "{base}/v1/sessions/github%3Aissue%3Aacme%2Fwidgets%237/events" + )) + .send() + .await + .expect("the events request goes out"); + assert_eq!(stream.status(), 400); +}