forked from vhaudiquet/rhema-claw
feat: chips travel as span records, not mark embeds
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:
1 parent
df260fd9a8
commit
c5bf168eed
12 files changed
+484
-108
No files matched your search
@@ -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.
|
||||
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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}")));
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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")),
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user