feat: chips travel as span records, not mark embeds
android / debug (push) Successful in 2m19s
android / release (push) Successful in 3m0s
ci / checks (push) Successful in 1m11s
ci / test (push) Successful in 38s
ci / chart (push) Successful in 5s
ci / docker (push) Successful in 1m27s
ci / web (push) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m30s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 14s
ci / publish-edge-chart (push) Successful in 4s

The claw's wire carried chips only as U+FFFC-payload-U+FFFC marks
written into the text — the very encoding 0.4.0's fold migrated at
the provider seam. Now the record rhema-core defined is the wire's
own: a message's pasted payloads ride the POST body's `pastes` array
beside the plain draft, the fold composes the plain form and measures
each chip's PasteSpan, and the `user_message` echo carries text plus
`pastes` — the session annotation's own shape — while the turn's
question carries the span note into the checkpoint, shifted by the
exact bytes any framing prefix adds.

The web client mints and renders the new record: the composer sends
draft and payloads separately, the optimistic row composes the same
plain text and spans the fold will record (so the echo dedupes), and
the render slices the text at the record's byte offsets. Rows
recorded before spans arrived still parse the mark form — as does
every arrival that still mints it, including every surface the shim
or an older client feeds.

The phone is one of those: it parses chips by scanning marks, and
kotlinx ignores the new field, so it reads spans-less rows exactly
as before; adopting span records for its own rows is a follow-up.
This commit is contained in:
vhaudiquet committed 2026-11-20 00:41:41 +01:00
1 parent df260fd9a8
commit c5bf168eed
12 files changed
+478 -102

No files matched your search

+5 -2
View File
@@ -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=<seq> resumes a cursor
GET /v1/sessions/{key}/history one page of older turns: ?before=<seq>&limit=<n>
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: <seq>` 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.
+12 -3
View File
@@ -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<String>,
/// 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 (
+38 -4
View File
@@ -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<UserImage>,
/// 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<PasteSpan>,
},
/// 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}")));
+204 -54
View File
@@ -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::<Vec<_>>();
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<RecordingProvider>,
Arc<EventHub>,
Arc<Dispatcher>,
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"),
+1
View File
@@ -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());
+3 -1
View File
@@ -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")),
+71
View File
@@ -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
+10 -5
View File
@@ -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
```
+12 -7
View File
@@ -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<void> {
}
}
async function send(message: { text: string; images: StagedImage[] }): Promise<void> {
// 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<void> {
// 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
+29 -5
View File
@@ -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,8 +364,12 @@ 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)) {
@@ -372,6 +381,21 @@ function messageSegments(text: string): MessageSegment[] {
}
return segments
}
const indexOf = byteToIndex(text)
const segments: MessageSegment[] = []
let chip = 0
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
}
const displayName = computed(() => props.activeKey.replace(/^interactive:/, ''))
@@ -445,7 +469,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
</button>
</div>
<div class="reply plain">
<template v-for="(segment, index) in messageSegments(item.text)" :key="index">
<template v-for="(segment, index) in messageSegments(item.text, item.pastes)" :key="index">
<span v-if="segment.kind === 'chip'" class="badge paste-chip">{{ segment.label }}</span>
<template v-else>{{ segment.text }}</template>
</template>
+43 -5
View File
@@ -56,9 +56,20 @@ export interface UserImage {
media_type: string
}
/** One paste chip a `user_message` carries: the record the session's
* `rhema-code` annotation holds — the byte range in the plain text the
* chip stands for (UTF-8 offsets; see useTranscript's
* `byteToIndex`), plus the payload's line count for the chip's label
* (rhema-core `PasteSpan`). */
export interface PasteSpan {
start: number
end: number
lines: number
}
/** One turn event, exactly `hub.rs`'s `TurnEvent` (serde type tag, snake case). */
export type TurnEvent =
| { type: 'user_message'; text: string; images: UserImage[] }
| { type: 'user_message'; text: string; images: UserImage[]; pastes: PasteSpan[] }
| { type: 'thinking_delta'; text: string }
| { type: 'text_delta'; text: string }
| { type: 'tool_start'; name: string }
@@ -398,8 +409,8 @@ export interface ClawApi {
* a plain src will not do). Cached per id: attachments are immutable,
* so a replayed event never refetches. */
attachmentUrl(id: string): Promise<string>
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void>
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images and chip payloads ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
sendMessage(key: string, text: string, pastes?: string[], images?: OutboundImage[]): Promise<void>
/** `GET /v1/providers` — the constructible backends and the active pair. */
providers(): Promise<ProvidersState>
/** `PUT /v1/providers/active` — switch the backend, persisted claw-side. Answers the new active pair only. */
@@ -533,11 +544,19 @@ export function useClaw(token: Ref<string | null>): ClawApi {
})
}
async function sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void> {
async function sendMessage(
key: string,
text: string,
pastes?: string[],
images?: OutboundImage[],
): Promise<void> {
const body: { text: string; pastes?: string[]; images?: OutboundImage[] } = { text }
if (pastes?.length) body.pastes = pastes
if (images?.length) body.images = images
await send(`/v1/sessions/${encodeURIComponent(key)}/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
body: JSON.stringify(images?.length ? { text, images } : { text }),
body: JSON.stringify(body),
})
}
@@ -919,6 +938,24 @@ function parseUserImages(raw: unknown): UserImage[] {
return images
}
/** The paste chips a `user_message` carries: rows recorded before
* chips rode as spans carry the mark form in the text instead and no
* field at all — empty, the render falls back to scanning — and a
* span without whole-number bounds or a line count is not one. */
function parseUserPastes(raw: unknown): PasteSpan[] {
if (!Array.isArray(raw)) return []
const pastes: PasteSpan[] = []
for (const entry of raw) {
const span = entry as Record<string, unknown>
if (typeof span.start !== 'number' || typeof span.end !== 'number') continue
if (typeof span.lines !== 'number') continue
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || !Number.isInteger(span.lines)) continue
if (span.start < 0 || span.end < span.start || span.lines < 0) continue
pastes.push({ start: span.start, end: span.end, lines: span.lines })
}
return pastes
}
/** Parses one `data:` payload into a `TurnEvent`; unknown shapes are dropped, not guessed. */
function parseTurnEvent(data: string): TurnEvent | null {
try {
@@ -929,6 +966,7 @@ function parseTurnEvent(data: string): TurnEvent | null {
type: 'user_message',
text: String(raw.text ?? ''),
images: parseUserImages(raw.images),
pastes: parseUserPastes(raw.pastes),
}
case 'thinking_delta':
case 'text_delta':
+50 -16
View File
@@ -6,7 +6,7 @@
// mirror when the stream reopens and folds what arrives, never the other
// way around.
import { ref } from 'vue'
import type { AttachmentMedia, ConsentKind, OutboundImage, TurnEvent } from './useClaw'
import type { AttachmentMedia, ConsentKind, OutboundImage, PasteSpan, TurnEvent } from './useClaw'
/** One tool call inside a turn: started, then completed by its result. */
export interface ToolRow {
@@ -89,7 +89,7 @@ export interface StagedImage extends OutboundImage {
/** A transcript line: a message the local user sent, or one streamed turn. */
export type TranscriptItem =
| { kind: 'sent'; id: number; text: string; images: SentImage[] }
| { kind: 'sent'; id: number; text: string; images: SentImage[]; pastes: PasteSpan[] }
| { kind: 'turn'; id: number; turn: TurnBlock }
| { kind: 'consent'; id: number; consent: ConsentCard }
| { kind: 'attachment'; id: number; attachment: AttachmentCard }
@@ -123,20 +123,53 @@ export function lineCount(text: string): number {
return lines.length
}
/** A chip's label: `▣1 5L` — the anchor's one-based id and the
* payload's line count (the TUI's chip_label). */
export function chipLabel(paste: string, index: number): string {
return `▣${index + 1} ${lineCount(paste)}L`
/** A chip's label from its line count: `▣1 5L` — the chip's
* one-based id and the payload's line count (the TUI's chip_label). */
export function chipLinesLabel(lines: number, index: number): string {
return `▣${index + 1} ${lines}L`
}
/** Appends each paste as one MARK-payload-MARK embed, in order — the
* session's record of the prompt (paste::embed; a web draft holds no
* anchors, so every payload lands at the end). */
export function embedPastes(draft: string, pastes: string[]): string {
return (
draft +
pastes.map((paste) => `${PASTE_MARK}${normalizePaste(paste)}${PASTE_MARK}`).join('')
)
/** A chip's label from its payload (the TUI's chip_label). */
export function chipLabel(paste: string, index: number): string {
return chipLinesLabel(lineCount(paste), index)
}
/** The modern record the wire carries: each paste a byte span in the
* plain text (the `rhema-code` annotation's own shape), one walk over
* the composed text mapping every code-point boundary — a span that
* splits a code point maps to none, the render skips it. */
export function byteToIndex(text: string): (byte: number) => number {
const at = new Map<number, number>([[0, 0]])
const bytesOf = new TextEncoder()
let bytes = 0
let units = 0
for (const cp of text) {
bytes += bytesOf.encode(cp).length
units += cp.length
at.set(bytes, units)
}
return (byte) => at.get(byte) ?? -1
}
/** Composes a send the way the fold composes its record: each paste's
* normalized payload appends to the draft, its chip's span measured
* over the composed plain text. The same form the `user_message`
* echo carries, so the optimistic row and the replay render rows of
* one shape and the echo dedupes against what this surface sent. */
export function composeChips(
draft: string,
pastes: string[],
): { text: string; pastes: PasteSpan[] } {
const bytesOf = new TextEncoder()
let text = draft
const spans: PasteSpan[] = []
for (const paste of pastes) {
const payload = normalizePaste(paste)
const start = bytesOf.encode(text).length
text += payload
spans.push({ start, end: bytesOf.encode(text).length, lines: lineCount(payload) })
}
return { text, pastes: spans }
}
/** One scanned piece of embedded-form text. */
@@ -244,6 +277,7 @@ export function useTranscript() {
id: nextId++,
text: event.text,
images: event.images.map((image) => ({ ...image, url: null, name: null })),
pastes: event.pastes,
})
break
}
@@ -356,10 +390,10 @@ export function useTranscript() {
* Its images render from the staged previews — the claw stores them
* and the stream's echo dedupes against this row. Returns the row's
* id, so a failed POST can retract it. */
function addSent(text: string, images: SentImage[] = []): number {
function addSent(text: string, images: SentImage[] = [], pastes: PasteSpan[] = []): number {
const id = nextId++
pendingSent.push({ text, images: images.length, itemId: id })
items.value.push({ kind: 'sent', id, text, images })
items.value.push({ kind: 'sent', id, text, images, pastes })
return id
}