diff --git a/crates/rhema-claw/README.md b/crates/rhema-claw/README.md index a14993c..be09366 100644 --- a/crates/rhema-claw/README.md +++ b/crates/rhema-claw/README.md @@ -135,7 +135,7 @@ The native surface: ``` GET /healthz GET /v1/sessions POST /v1/sessions {"name"} — create an empty interactive session -POST /v1/sessions/{key}/messages {"text": "..."} -> 202 +POST /v1/sessions/{key}/messages {"text": "...", "images"?, "pastes"?} -> 202 GET /v1/sessions/{key}/events SSE turn events (see below); ?since= resumes a cursor GET /v1/sessions/{key}/history one page of older turns: ?before=&limit= DELETE /v1/sessions/{key} drop a session and its turn history @@ -183,7 +183,10 @@ lets a UI badge setup state. SSE frames are `id: ` plus `data: {..}`: `user_message`, `thinking_delta`, `text_delta`, `tool_start`, `tool_result`, -`turn_done`. Every streamed event is persisted as it streams, so both a +`turn_done`. A `user_message` names its paste chips as the byte spans +they stand for in its plain text (`paste::PasteSpan`, the session +record's own shape) — a client renders from that record; rows recorded +before spans arrived carry the legacy mark form in the text instead. Every streamed event is persisted as it streams, so both a reload and a daemon restart rebuild the transcript, and a session that runs for weeks keeps all of it. diff --git a/crates/rhema-claw/src/http.rs b/crates/rhema-claw/src/http.rs index 8fec63c..15250a5 100644 --- a/crates/rhema-claw/src/http.rs +++ b/crates/rhema-claw/src/http.rs @@ -663,12 +663,20 @@ pub const MAX_INBOUND_IMAGES: usize = 8; pub const MAX_MESSAGE_BODY_BYTES: usize = MAX_INBOUND_IMAGE_BYTES * 4 / 3 * MAX_INBOUND_IMAGES + 1024 * 1024; -/// `{"text": "..."}` — one chat message, plus the images it carries. -/// A body without `images` is the old shape, unchanged. +/// `{"text": "..."}` — one chat message, plus the images and the chip +/// payloads it carries. A body without `images` or `pastes` is the old +/// shape, unchanged. #[derive(Deserialize)] pub struct MessageBody { - /// The message text. + /// The message text, plain: each paste payload appended to it in + /// the fold, its chip noted as a span in the recorded event — no + /// mark form on the wire. pub text: String, + /// The message's staged chips, payloads in order. A sender that + /// mints the legacy mark form sends none; the fold rewrites that + /// form too. + #[serde(default)] + pub pastes: Vec, /// The message's inline images, each the full MIME type plus bare /// base64. The route checks the budget, then the dispatch copies /// the bytes into the attachment store — the stream carries ids, @@ -740,6 +748,7 @@ async fn messages( if let Err(err) = state.dispatcher.ingest(crate::interactive::user_event( key.as_str(), &body.text, + &body.pastes, &body.images, )) { return ( diff --git a/crates/rhema-claw/src/hub.rs b/crates/rhema-claw/src/hub.rs index db38b14..4be97c0 100644 --- a/crates/rhema-claw/src/hub.rs +++ b/crates/rhema-claw/src/hub.rs @@ -28,6 +28,7 @@ use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex, PoisonError}; +use rhema_core::paste::PasteSpan; use rhema_rsd::ResourceKey; use serde::{Deserialize, Serialize}; use tokio::sync::broadcast; @@ -74,13 +75,23 @@ pub enum TurnEvent { /// shows its own messages as it sends them, and skips the live /// echo. UserMessage { - /// The input text, verbatim. + /// The input text in the plain form the model read — each + /// paste's payload in place, no marks. text: String, /// The batch's images, in arrival order, as the attachment /// store holds them. `default` because rows recorded before /// images rode the transcript carry no field. #[serde(default)] images: Vec, + /// The paste chips the input carried, the same span record the + /// session's `rhema-code` annotation holds: the byte range + /// each chip stands for in `text`, plus its line count for the + /// label. `default` because rows recorded before chips rode + /// as spans carry the marks in the text instead — a client + /// that finds none scans for them; skipped when empty, so + /// rows without chips replay byte-for-byte as they landed. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pastes: Vec, }, /// A piece of the model's reasoning trace, in stream order. ThinkingDelta { @@ -565,10 +576,27 @@ mod tests { serde_json::to_string(&TurnEvent::UserMessage { text: "hi".into(), images: Vec::new(), + pastes: Vec::new(), }) .unwrap(), r#"{"type":"user_message","text":"hi","images":[]}"# ); + // The chip record rides only when there is one: the span + // shape is the session annotation's own, byte offsets over + // the plain text. + assert_eq!( + serde_json::to_string(&TurnEvent::UserMessage { + text: "hi".into(), + images: Vec::new(), + pastes: vec![PasteSpan { + start: 3, + end: 9, + lines: 4, + }], + }) + .unwrap(), + r#"{"type":"user_message","text":"hi","images":[],"pastes":[{"start":3,"end":9,"lines":4}]}"# + ); assert_eq!( serde_json::to_string(&TurnEvent::ToolResult { name: "bash".into(), @@ -600,7 +628,8 @@ mod tests { event, TurnEvent::UserMessage { text: "hello".into(), - images: Vec::new() + images: Vec::new(), + pastes: Vec::new() } ); } @@ -614,7 +643,8 @@ mod tests { assert_eq!( TurnEvent::UserMessage { text: "x".into(), - images: Vec::new() + images: Vec::new(), + pastes: Vec::new() } .kind(), "user_message" @@ -659,6 +689,7 @@ mod tests { TurnEvent::UserMessage { text: "hello".into(), images: Vec::new(), + pastes: Vec::new(), }, ); hub.emit(&key, text("hi")); @@ -669,7 +700,8 @@ mod tests { vec![ TurnEvent::UserMessage { text: "hello".into(), - images: Vec::new() + images: Vec::new(), + pastes: Vec::new() }, text("hi"), ], @@ -795,6 +827,7 @@ mod tests { TurnEvent::UserMessage { text: "earlier".into(), images: Vec::new(), + pastes: Vec::new(), }, ); let (history, mut receiver) = hub.subscribe_with_history(&key); @@ -896,6 +929,7 @@ mod tests { TurnEvent::UserMessage { text: format!("q{turn}"), images: Vec::new(), + pastes: Vec::new(), }, ); hub.emit(&key, text(&format!("a{turn}"))); diff --git a/crates/rhema-claw/src/interactive.rs b/crates/rhema-claw/src/interactive.rs index 985a2c1..592d8c1 100644 --- a/crates/rhema-claw/src/interactive.rs +++ b/crates/rhema-claw/src/interactive.rs @@ -166,10 +166,10 @@ pub struct WireImage { /// The event one chat message becomes. The id is unique per message (a /// wall-clock millisecond plus a process counter), so a redelivery -/// never dedups a different message away. The payload carries the -/// message's images when it has any, and no `images` key when it has -/// none — old payloads stay byte-identical. -pub fn user_event(key: &str, text: &str, images: &[WireImage]) -> Event { +/// never dedups a different message away. The chips' payloads ride +/// beside the text, and the images with them, each only when the +/// message staged any — payloads without chips stay byte-identical. +pub fn user_event(key: &str, text: &str, pastes: &[String], images: &[WireImage]) -> Event { static MESSAGE_SEQ: AtomicU64 = AtomicU64::new(0); let now = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -181,10 +181,18 @@ pub fn user_event(key: &str, text: &str, images: &[WireImage]) -> Event { MESSAGE_SEQ.fetch_add(1, Ordering::Relaxed) ), source: SOURCE.to_owned(), - payload: if images.is_empty() { - json!({ "key": key, "text": text }) - } else { - json!({ "key": key, "text": text, "images": images }) + // The chips' payloads ride only when the message staged any, + // and images only when it carried any: the old two-field shape + // rides byte-for-byte otherwise. + payload: { + let mut payload = json!({ "key": key, "text": text }); + if !pastes.is_empty() { + payload["pastes"] = json!(pastes); + } + if !images.is_empty() { + payload["images"] = json!(images); + } + payload }, received_at: now.as_millis() as u64, } @@ -441,7 +449,9 @@ impl InteractiveHandler { .await .map_err(|err| format!("inbox poll for {key} failed: {err}"))?; // Texts fold in arrival order, and so do the images, across - // the whole batch whichever events carried them. + // the whole batch whichever events carried them — each text + // with its chips already composed in, their spans measured + // over it. let mut texts = Vec::new(); let mut images = Vec::new(); for item in &items { @@ -451,7 +461,35 @@ impl InteractiveHandler { .or_else(|| payload.get("prompt")) .and_then(Value::as_str) { - texts.push(text); + // The fold owns the chip record. A legacy sender's + // marks ride the text and migrate here, per message; + // a payload chip appends in order right after — + // plain either way before the join, its span + // measured where it lands. + let mut message = [Message::text(Role::User, text.to_owned())]; + rhema_core::paste::migrate(&mut message); + let mut spans = rhema_core::paste::spans(&message[0]); + let mut composed = match &message[0].content[0] { + Content::Text(text) => text.clone(), + _ => unreachable!("the message was built with one text block"), + }; + for paste in payload + .get("pastes") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(rhema_core::paste::normalize) + { + let span = rhema_core::paste::PasteSpan { + start: composed.len(), + end: composed.len() + paste.len(), + lines: paste.lines().count(), + }; + composed.push_str(&paste); + spans.push(span); + } + texts.push((composed, spans)); } if let Some(carried) = payload.get("images").and_then(Value::as_array) { images.extend( @@ -461,7 +499,22 @@ impl InteractiveHandler { ); } } - let input = texts.join("\n\n"); + let mut input = String::new(); + let mut pastes = Vec::new(); + let mut first = true; + for (text, spans) in texts { + if !first { + input.push_str("\n\n"); + } + let base = input.len(); + input.push_str(&text); + pastes.extend(spans.into_iter().map(|span| rhema_core::paste::PasteSpan { + start: span.start + base, + end: span.end + base, + lines: span.lines, + })); + first = false; + } if input.trim().is_empty() { // Round one's emptiness is the dispatch bug it always was: // the lease exists because something waited. A steered @@ -512,13 +565,17 @@ impl InteractiveHandler { } // The transcript's question, recorded before anything else can // stream: a replay shows what was asked, not only what was - // answered. Raw input — the notification-contract framing below - // is the model's business, not the viewer's. + // answered. The fold composed the record — plain text, the + // chip spans beside it — and the turn runs this exact input; + // the notification-contract framing below is the model's + // business, not the viewer's. + let recorded_len = input.len(); self.hub.emit( &ctx.key, TurnEvent::UserMessage { text: input.clone(), images: transcript_images, + pastes: pastes.clone(), }, ); // A non-chat resident key has no subscriber to read the reply: @@ -572,13 +629,25 @@ impl InteractiveHandler { // future at its current await — a streaming request, or a // running shell command, whose child dies with the drop. The // next round revives whatever committed before the drop. - // Chat input may carry embedded pastes — the compact chip form - // the UIs mint — migrated here into the plain record the engine - // and its providers read: the payload sits in the text, its span - // note survives the checkpoint, and the model never sees a mark. - let mut turn_input = [Message::text_with_images(Role::User, input, core_images)]; - rhema_core::paste::migrate(&mut turn_input); - let [turn_input] = turn_input; + // The input rides in the plain form the fold recorded — the + // payloads sit in the text and the model never sees a mark — + // with the span note riding the message, so the checkpoint + // (and a session resumed from it) keeps the chips beside the + // plain text. The framings above live in the model's copy: + // their bytes are known exactly, and each span shifts by them, + // still pointing into the text it annotates. + let framed_len = input.len(); + let pastes = pastes + .iter() + .map(|span| rhema_core::paste::PasteSpan { + start: span.start + framed_len - recorded_len, + end: span.end + framed_len - recorded_len, + lines: span.lines, + }) + .collect::>(); + let mut question = [Message::text_with_images(Role::User, input, core_images)]; + rhema_core::paste::annotate(&mut question[0], &pastes); + let [turn_input] = question; let mut turn = Box::pin(run_turn( &mut agent, &mut session, @@ -1115,12 +1184,17 @@ mod tests { } } - /// The paste contract across the provider seam: a chat input that - /// carries an embedded paste (the compact form the UIs mint) is - /// expanded before the request leaves, while the transcript the hub - /// streams keeps the compact form. - #[tokio::test] - async fn an_embedded_paste_expands_for_the_model_and_not_for_the_transcript() { + /// The environment a paste test drives: the recording provider, the + /// hub, and a dispatcher wired to one interactive handler over a + /// throwaway workspace. + fn paste_env() -> ( + Arc, + Arc, + Arc, + InteractiveHandler, + Key, + tempfile::TempDir, + ) { let recorder = RecordingProvider::new(); let store = Arc::new(ClawStore::in_memory().expect("store opens")); let hub = Arc::new(EventHub::default()); @@ -1146,7 +1220,7 @@ mod tests { Arc::new(rhema_memory::VolatileStore::new()), Arc::new(Bootstrap::new(workspace.path().join("bootstrap")).expect("store opens")), hub.clone(), - notifications.clone(), + notifications, attachments(), crate::config::DEFAULT_MAX_TURN_STEPS, extensions, @@ -1161,14 +1235,31 @@ mod tests { Arc::new(VolatileStore::new()), )); register_user(&dispatcher); + ( + recorder, + hub, + dispatcher, + handler, + Key::from("interactive:web"), + workspace, + ) + } + + /// The legacy intake: a chat input still carrying the embedded + /// mark form migrates at the fold — the model reads the payload in + /// place, and the recorded question is the plain form with the + /// chip noted beside it. + #[tokio::test] + async fn an_embedded_arrival_migrates_at_the_fold() { + let (recorder, hub, dispatcher, handler, key, _workspace) = paste_env(); let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler)) .with_holder("test"); - let key = Key::from("interactive:web"); dispatcher .ingest(user_event( key.as_str(), "review this:\u{FFFC}fn main() {}\nfn other() {}\u{FFFC}", &[], + &[], )) .expect("ingests"); driver.run_once().await.expect("the run happens"); @@ -1178,17 +1269,61 @@ mod tests { "review this:fn main() {}\nfn other() {}", "the model saw the payload, not the marks" ); + // The recorded question is the plain form, the chip record + // riding beside it as spans: the mark form lives on only in + // rows recorded before chips rode as spans. let (history, _) = hub.subscribe_with_history(&key); - let saw_input = history.into_iter().find_map(|event| match event { - TurnEvent::UserMessage { text, .. } => Some(text), + let question = history.into_iter().find_map(|event| match event { + TurnEvent::UserMessage { text, pastes, .. } => Some((text, pastes)), _ => None, }); - assert!( - saw_input - .expect("the transcript saw the question") - .contains('\u{FFFC}'), - "the transcript keeps the compact chip form" + let (text, pastes) = question.expect("the transcript saw the question"); + let payload = "fn main() {}\nfn other() {}"; + assert_eq!(text, "review this:fn main() {}\nfn other() {}", "no marks"); + assert_eq!(pastes.len(), 1, "the chip is one span"); + assert_eq!(pastes[0].start, "review this:".len()); + assert_eq!(pastes[0].end, "review this:".len() + payload.len()); + assert_eq!(pastes[0].lines, 2); + } + + /// The modern intake: chips ride as payloads beside their message, + /// each appending to it — no mark on the wire, the span record born + /// at the fold. A payload's carriage returns and stray marks + /// normalize there too, so a chip can never re-cut the scan. + #[tokio::test] + async fn a_staged_chip_rides_its_payload_beside_the_question() { + let (recorder, hub, dispatcher, handler, key, _workspace) = paste_env(); + let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler)) + .with_holder("test"); + dispatcher + .ingest(user_event( + key.as_str(), + "review this:", + &["fn main() {}\r\nfn other() {}\u{FFFC}".to_owned()], + &[], + )) + .expect("ingests"); + driver.run_once().await.expect("the run happens"); + + // The model read the draft with the normalized payload + // appended: what the record says is what the request carried. + assert_eq!( + recorder.last_user_text(), + "review this:fn main() {}\nfn other() {}", + "the model saw the payload, normalized, in place" ); + let (history, _) = hub.subscribe_with_history(&key); + let question = history.into_iter().find_map(|event| match event { + TurnEvent::UserMessage { text, pastes, .. } => Some((text, pastes)), + _ => None, + }); + let (text, pastes) = question.expect("the transcript saw the question"); + let payload = "fn main() {}\nfn other() {}"; + assert_eq!(text, format!("review this:{payload}"), "the plain form"); + assert_eq!(pastes.len(), 1, "the chip is one span"); + assert_eq!(pastes[0].start, "review this:".len()); + assert_eq!(pastes[0].end, "review this:".len() + payload.len()); + assert_eq!(pastes[0].lines, 2); } /// A scripted tool-call turn: the model asking for `name` with `args`. @@ -1313,8 +1448,8 @@ mod tests { #[test] fn user_events_carry_the_key_and_unique_ids() { - let first = user_event("interactive:web", "hello", &[]); - let second = user_event("interactive:web", "again", &[]); + let first = user_event("interactive:web", "hello", &[], &[]); + let second = user_event("interactive:web", "again", &[], &[]); assert_eq!(first.source, "user"); assert_eq!(first.id, first.id, "stable within itself"); assert_ne!(first.id, second.id, "messages never share a dedup id"); @@ -1328,7 +1463,7 @@ mod tests { /// order; a plain message carries no `images` key at all. #[test] fn user_events_carry_images_only_when_the_message_has_any() { - let bare = user_event("interactive:web", "plain", &[]); + let bare = user_event("interactive:web", "plain", &[], &[]); assert_eq!( bare.payload, json!({"key": "interactive:web", "text": "plain"}), @@ -1337,6 +1472,7 @@ mod tests { let carried = user_event( "interactive:web", "look", + &[], &[ WireImage { media_type: "image/png".to_owned(), @@ -1369,7 +1505,7 @@ mod tests { Arc::new(VolatileStore::new()), ); register_user(&dispatcher); - let event = user_event("interactive:web", "hello", &[]); + let event = user_event("interactive:web", "hello", &[], &[]); // Ingesting resolves the key through the registered fn: the // record lands under exactly the payload's key. dispatcher.ingest(event).expect("ingests"); @@ -1605,7 +1741,7 @@ mod tests { let key = Key::from("interactive:web"); let mut receiver = hub.subscribe(&key); dispatcher - .ingest(user_event(key.as_str(), "hello", &[])) + .ingest(user_event(key.as_str(), "hello", &[], &[])) .expect("ingests"); let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler)) @@ -1618,7 +1754,8 @@ mod tests { receiver.try_recv().unwrap(), TurnEvent::UserMessage { text: "hello".into(), - images: Vec::new() + images: Vec::new(), + pastes: Vec::new() } ); assert_eq!( @@ -1694,7 +1831,7 @@ mod tests { let key = Key::from("interactive:web"); let mut receiver = hub.subscribe(&key); dispatcher - .ingest(user_event(key.as_str(), "hello", &[])) + .ingest(user_event(key.as_str(), "hello", &[], &[])) .expect("ingests"); let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler)) .with_holder("test"); @@ -1714,7 +1851,7 @@ mod tests { // Steer, in the route's order: ingest first, signal second. dispatcher - .ingest(user_event(key.as_str(), "stop that", &[])) + .ingest(user_event(key.as_str(), "stop that", &[], &[])) .expect("ingests"); assert!(registry.signal(key.as_str())); @@ -1731,7 +1868,8 @@ mod tests { receiver.try_recv().unwrap(), TurnEvent::UserMessage { text: "hello".into(), - images: Vec::new() + images: Vec::new(), + pastes: Vec::new() } ); assert_eq!( @@ -1745,7 +1883,8 @@ mod tests { receiver.try_recv().unwrap(), TurnEvent::UserMessage { text: "stop that".into(), - images: Vec::new() + images: Vec::new(), + pastes: Vec::new() } ); assert_eq!( @@ -1919,6 +2058,7 @@ mod tests { .ingest(user_event( key.as_str(), "look at this", + &[], &[WireImage { media_type: "image/png".to_owned(), data: png.clone(), @@ -1929,6 +2069,7 @@ mod tests { .ingest(user_event( key.as_str(), "and at this", + &[], &[WireImage { media_type: "Image/JPEG".to_owned(), data: jpeg.clone(), @@ -1936,7 +2077,7 @@ mod tests { )) .expect("ingests"); dispatcher - .ingest(user_event(key.as_str(), "no picture here", &[])) + .ingest(user_event(key.as_str(), "no picture here", &[], &[])) .expect("ingests"); assert_eq!( driver.run_once().await.expect("the run happens"), @@ -1949,7 +2090,11 @@ mod tests { let question = history .iter() .find_map(|event| match event { - TurnEvent::UserMessage { text, images } => Some((text.clone(), images.clone())), + TurnEvent::UserMessage { + text, + pastes, + images, + } => Some((text.clone(), images.clone(), pastes.clone())), _ => None, }) .expect("the transcript saw the question"); @@ -2055,7 +2200,7 @@ mod tests { // Dispatch 1: the model saves through the chain's memory tools. dispatcher - .ingest(user_event(key.as_str(), "remember the channel", &[])) + .ingest(user_event(key.as_str(), "remember the channel", &[], &[])) .expect("ingests"); assert_eq!( driver.run_once().await.expect("first run"), @@ -2074,7 +2219,7 @@ mod tests { // Dispatch 2: the model searches the same chain and answers from // memory — a fresh session turn, the same durable store. dispatcher - .ingest(user_event(key.as_str(), "where do releases go?", &[])) + .ingest(user_event(key.as_str(), "where do releases go?", &[], &[])) .expect("ingests"); assert_eq!( driver.run_once().await.expect("second run"), @@ -2162,7 +2307,7 @@ mod tests { // Dispatch 1: the model writes SOUL.md through the chain. A key // with a session continues, so both calls ride one key. dispatcher - .ingest(user_event(key.as_str(), "call me claw", &[])) + .ingest(user_event(key.as_str(), "call me claw", &[], &[])) .expect("ingests"); assert_eq!( driver.run_once().await.expect("first run"), @@ -2181,7 +2326,7 @@ mod tests { // Dispatch 2: USER.md, same chain — and the pending flag clears. dispatcher - .ingest(user_event(key.as_str(), "and I am Ana", &[])) + .ingest(user_event(key.as_str(), "and I am Ana", &[], &[])) .expect("ingests"); assert_eq!( driver.run_once().await.expect("second run"), @@ -2239,7 +2384,7 @@ mod tests { register_user(&dispatcher); let key = Key::from("interactive:web"); dispatcher - .ingest(user_event(key.as_str(), "hello", &[])) + .ingest(user_event(key.as_str(), "hello", &[], &[])) .expect("ingests"); let driver = rhema_autonomous_agent::Driver::new(dispatcher, Arc::new(handler)); driver.run_once().await.expect("the run happens"); @@ -2379,7 +2524,7 @@ mod tests { // An interactive reply is the chat surface's business: notified // nowhere. dispatcher - .ingest(user_event("interactive:web", "hello", &[])) + .ingest(user_event("interactive:web", "hello", &[], &[])) .expect("ingests"); assert_eq!( driver.run_once().await.expect("the run happens"), @@ -2457,7 +2602,12 @@ mod tests { // The evening's work, in the chat session. dispatcher - .ingest(user_event(key.as_str(), "we shipped the claw tonight", &[])) + .ingest(user_event( + key.as_str(), + "we shipped the claw tonight", + &[], + &[], + )) .expect("ingests"); assert_eq!( driver.run_once().await.expect("first run"), diff --git a/crates/rhema-claw/src/openai.rs b/crates/rhema-claw/src/openai.rs index 16553a3..5564474 100644 --- a/crates/rhema-claw/src/openai.rs +++ b/crates/rhema-claw/src/openai.rs @@ -259,6 +259,7 @@ pub async fn chat_completions( if let Err(err) = state.dispatcher().ingest(crate::interactive::user_event( key.as_str(), &input.text, + &[], &input.images, )) { return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()); diff --git a/crates/rhema-claw/src/turn_store.rs b/crates/rhema-claw/src/turn_store.rs index 3354812..20c6954 100644 --- a/crates/rhema-claw/src/turn_store.rs +++ b/crates/rhema-claw/src/turn_store.rs @@ -325,6 +325,7 @@ mod tests { TurnEvent::UserMessage { text: "hello".into(), images: Vec::new(), + pastes: Vec::new(), }, text_delta("hi"), ], @@ -348,7 +349,8 @@ mod tests { 0, TurnEvent::UserMessage { text: "hello".into(), - images: Vec::new() + images: Vec::new(), + pastes: Vec::new() } ), (1, text_delta("hi")), diff --git a/crates/rhema-claw/tests/http.rs b/crates/rhema-claw/tests/http.rs index 06b8ac3..c98fe13 100644 --- a/crates/rhema-claw/tests/http.rs +++ b/crates/rhema-claw/tests/http.rs @@ -670,6 +670,77 @@ async fn chat_messages_carry_images_into_the_attachment_store() { ); } +/// A staged chip rides beside its draft and records as spans: the +/// echo on the stream and the stashed session both carry the plain +/// text with the `rhema-code` annotation beside it, and no mark ever +/// crosses the wire. +#[tokio::test] +async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_stash() { + let provider = Arc::new(MockProvider::new([reply("on it")])); + let dir = tempfile::tempdir().expect("tempdir"); + let daemon = Daemon::build( + &config(&dir, None), + mock_registry(provider), + rhema_rsd::DispatcherConfig::default(), + ) + .expect("the daemon assembles"); + let base = serve(&daemon).await; + let client = reqwest::Client::new(); + + // The chip rides as a payload beside the plain draft. + let accepted = client + .post(format!("{base}/v1/sessions/interactive:web/messages")) + .json(&json!({ + "text": "review this:", + "pastes": ["fn main() {}\nfn other() {}"], + })) + .send() + .await + .expect("the message posts"); + assert_eq!(accepted.status(), 202); + + // The echo on the stream: the payload in place, the span record + // beside it, no marks in the text. + let events = client + .get(format!("{base}/v1/sessions/interactive:web/events")) + .send() + .await + .expect("the events request goes out"); + let mut stream = sse_body(events).await; + let mut seen = String::new(); + read_until(&mut stream, &mut seen, r#""type":"turn_done""#).await; + assert!( + seen.contains(r#""type":"user_message","text":"review this:fn main() {}\nfn other() {}""#), + "the echo carries the composed plain form: {seen}" + ); + assert!( + seen.contains(r#""pastes":[{"start":12,"end":38,"lines":2}]"#), + "the chip notes itself as the span it stands for: {seen}" + ); + assert!(!seen.contains('\u{FFFC}'), "no marks ride the wire: {seen}"); + + // The stash: the checkpoint's user message carries the payload in + // the text and the annotation that outlives the turn. + let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens"); + let key = ResourceKey::from("interactive:web"); + let record = store + .load(&key) + .expect("the record loads") + .expect("the key has a record"); + let stashed: Session = + serde_json::from_value(record.session.expect("a session").core.driver_state) + .expect("the stash parses"); + let ask = stashed + .history + .iter() + .find(|message| message.role == Role::User) + .expect("the question is stashed"); + assert_eq!(rhema_core::paste::spans(ask).len(), 1); + assert_eq!(rhema_core::paste::spans(ask)[0].start, 12); + assert_eq!(rhema_core::paste::spans(ask)[0].end, 38); + assert_eq!(rhema_core::paste::spans(ask)[0].lines, 2); +} + /// A turn nobody watched is still replayable: a client arriving after /// the fact — a reloaded browser, a reopened phone — subscribes cold and /// gets the finished turns back before the live feed. The same holds diff --git a/web/claw/README.md b/web/claw/README.md index 6c13ed1..1df4f7e 100644 --- a/web/claw/README.md +++ b/web/claw/README.md @@ -97,10 +97,14 @@ Two consequences worth knowing before changing this code: folds those other events; only the render ignores them. - **Long pastes travel as chips.** A paste over three lines (the TUI's `PASTE_INLINE_LINES`) never lands in the composer; it stages as a - droppable chip (`▣1 42L`) and embeds into the sent text as - U+FFFC-payload-U+FFFC — the same record `rhema-core`'s - `paste::embed` keeps — so the transcript renders each embed back as - a chip in place of the payload. An unpaired mark is literal text. + droppable chip (`▣1 42L`) and rides the body's `pastes` array beside + the plain draft — the claw composes the record (the payload in + place, the span note beside it) — so no mark ever crosses the wire. + The `user_message` echo names each chip as the byte span it stands + for (the session record's own shape, `paste::PasteSpan`), and the + transcript renders from that. Rows recorded before spans rode the + stream carry the legacy mark form in the text instead; the render + still scans for those, and an unpaired mark stays literal. - **The agent can ask.** A `consent_request` event renders as an inline card: kind `secret` gets a password input plus submit, kind `phone` gets Approve/Deny, and both carry a deny link @@ -198,7 +202,8 @@ app/ composables/ useClaw.ts the typed API client + fetch-based SSE useTranscript.ts folds TurnEvents into renderable turn - blocks; owns the paste-embed text form + blocks; owns the paste span record (and + the legacy mark form old rows carry) server/ middleware/claw-proxy.ts dev-only same-origin proxy to a running claw ``` diff --git a/web/claw/app/app.vue b/web/claw/app/app.vue index 80af3f2..1d39734 100644 --- a/web/claw/app/app.vue +++ b/web/claw/app/app.vue @@ -21,7 +21,7 @@ import type { SandboxState, StreamStatus, } from '~/composables/useClaw' -import { useTranscript } from '~/composables/useTranscript' +import { composeChips, useTranscript } from '~/composables/useTranscript' import type { StagedImage } from '~/composables/useTranscript' const TOKEN_STORE_KEY = 'claw.token' @@ -533,21 +533,26 @@ async function saveSandbox(choice: SandboxSelection): Promise { } } -async function send(message: { text: string; images: StagedImage[] }): Promise { - // The optimistic row renders the staged previews; the stream's - // user_message echo carries the stored ids and dedupes against it. +async function send(message: { text: string; pastes: string[]; images: StagedImage[] }): Promise { + // The optimistic row renders the staged previews and the composed + // chip record — the same plain text and spans the fold records on + // the other side — so the stream's user_message echo, which + // carries the stored ids beside that record, dedupes against it. + const composed = composeChips(message.text, message.pastes) const rowId = transcript.addSent( - message.text, + composed.text, message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })), + composed.pastes, ) busy.value = true try { // Fire-and-forget by design: the claw answers 202 and the reply - // arrives on the event stream. The body carries the images only - // when there are some. + // arrives on the event stream. The chips and the images ride the + // body only when there are some. await claw.sendMessage( activeKey.value, message.text, + message.pastes, message.images.map(({ media_type, data }) => ({ media_type, data })), ) apiError.value = null diff --git a/web/claw/app/components/ChatPanel.vue b/web/claw/app/components/ChatPanel.vue index 88abfd6..cdbe8c2 100644 --- a/web/claw/app/components/ChatPanel.vue +++ b/web/claw/app/components/ChatPanel.vue @@ -10,12 +10,14 @@ import { PASTE_INLINE_LINES, chipLabel, - embedPastes, + byteToIndex, + chipLinesLabel, lineCount, normalizePaste, pasteParts, } from '~/composables/useTranscript' import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw' +import type { PasteSpan } from '~/composables/useClaw' import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript' const props = defineProps<{ @@ -45,6 +47,9 @@ const agentName = computed(() => props.identity?.name?.trim() || 'rhema') * the staged images, previews included for the optimistic row. */ interface SendPayload { text: string + /** The chip payloads, in staging order — the wire carries them + * beside the plain draft; the fold composes the record. */ + pastes: string[] images: StagedImage[] } @@ -157,7 +162,7 @@ function submit(): void { // answers 202 at once) — a running turn never blocks the composer, // because a send into one steers it. if (!text || !props.canSend || props.busy) return - emit('send', { text: embedPastes(text, pastes.value), images: stagedImages.value }) + emit('send', { text, pastes: pastes.value, images: stagedImages.value }) stageGeneration++ draft.value = '' pastes.value = [] @@ -359,17 +364,36 @@ function storedImageName(image: SentImage): string { type MessageSegment = PastePart | { kind: 'chip'; label: string } /** The message's render pieces: literal text and resolved chips, the - * chips' one-based ids counted across the message. */ -function messageSegments(text: string): MessageSegment[] { + * chips' one-based ids counted across the message. The chips come + * from the row's span record — the plain text sliced at the spans' + * byte boundaries — and a row from before spans rode the wire + * carries none; that one still scans the mark form in its text. */ +function messageSegments(text: string, pastes: PasteSpan[] = []): MessageSegment[] { + if (pastes.length === 0) { + const segments: MessageSegment[] = [] + let chip = 0 + for (const part of pasteParts(text)) { + if (part.kind === 'text') { + if (part.text !== '') segments.push(part) + } else { + segments.push({ kind: 'chip', label: chipLabel(part.text, chip++) }) + } + } + return segments + } + const indexOf = byteToIndex(text) const segments: MessageSegment[] = [] let chip = 0 - for (const part of pasteParts(text)) { - if (part.kind === 'text') { - if (part.text !== '') segments.push(part) - } else { - segments.push({ kind: 'chip', label: chipLabel(part.text, chip++) }) - } + let cut = 0 + for (const span of [...pastes].sort((a, b) => a.start - b.start)) { + const start = indexOf(span.start) + const end = indexOf(span.end) + if (start === -1 || end === -1 || start < cut || end < start) continue + if (start > cut) segments.push({ kind: 'text', text: text.slice(cut, start) }) + segments.push({ kind: 'chip', label: chipLinesLabel(span.lines, chip++) }) + cut = end } + if (cut < text.length) segments.push({ kind: 'text', text: text.slice(cut) }) return segments } @@ -445,7 +469,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
-