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
22c502a9eb
commit
dd91501e10
12 files changed
+484
-108
No files matched your search
@@ -135,7 +135,7 @@ The native surface:
|
|||||||
```
|
```
|
||||||
GET /healthz GET /v1/sessions
|
GET /healthz GET /v1/sessions
|
||||||
POST /v1/sessions {"name"} — create an empty interactive session
|
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}/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>
|
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
|
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`,
|
SSE frames are `id: <seq>` plus `data: {..}`: `user_message`,
|
||||||
`thinking_delta`, `text_delta`, `tool_start`, `tool_result`,
|
`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
|
reload and a daemon restart rebuild the transcript, and a session that
|
||||||
runs for weeks keeps all of it.
|
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 =
|
pub const MAX_MESSAGE_BODY_BYTES: usize =
|
||||||
MAX_INBOUND_IMAGE_BYTES * 4 / 3 * MAX_INBOUND_IMAGES + 1024 * 1024;
|
MAX_INBOUND_IMAGE_BYTES * 4 / 3 * MAX_INBOUND_IMAGES + 1024 * 1024;
|
||||||
|
|
||||||
/// `{"text": "..."}` — one chat message, plus the images it carries.
|
/// `{"text": "..."}` — one chat message, plus the images and the chip
|
||||||
/// A body without `images` is the old shape, unchanged.
|
/// payloads it carries. A body without `images` or `pastes` is the old
|
||||||
|
/// shape, unchanged.
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct MessageBody {
|
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,
|
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
|
/// The message's inline images, each the full MIME type plus bare
|
||||||
/// base64. The route checks the budget, then the dispatch copies
|
/// base64. The route checks the budget, then the dispatch copies
|
||||||
/// the bytes into the attachment store — the stream carries ids,
|
/// 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(
|
if let Err(err) = state.dispatcher.ingest(crate::interactive::user_event(
|
||||||
key.as_str(),
|
key.as_str(),
|
||||||
&body.text,
|
&body.text,
|
||||||
|
&body.pastes,
|
||||||
&body.images,
|
&body.images,
|
||||||
)) {
|
)) {
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -28,6 +28,7 @@
|
|||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::{HashMap, VecDeque};
|
||||||
use std::sync::{Arc, Mutex, PoisonError};
|
use std::sync::{Arc, Mutex, PoisonError};
|
||||||
|
|
||||||
|
use rhema_core::paste::PasteSpan;
|
||||||
use rhema_rsd::ResourceKey;
|
use rhema_rsd::ResourceKey;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use tokio::sync::broadcast;
|
use tokio::sync::broadcast;
|
||||||
@@ -74,13 +75,23 @@ pub enum TurnEvent {
|
|||||||
/// shows its own messages as it sends them, and skips the live
|
/// shows its own messages as it sends them, and skips the live
|
||||||
/// echo.
|
/// echo.
|
||||||
UserMessage {
|
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,
|
text: String,
|
||||||
/// The batch's images, in arrival order, as the attachment
|
/// The batch's images, in arrival order, as the attachment
|
||||||
/// store holds them. `default` because rows recorded before
|
/// store holds them. `default` because rows recorded before
|
||||||
/// images rode the transcript carry no field.
|
/// images rode the transcript carry no field.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
images: Vec<UserImage>,
|
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.
|
/// A piece of the model's reasoning trace, in stream order.
|
||||||
ThinkingDelta {
|
ThinkingDelta {
|
||||||
@@ -565,10 +576,27 @@ mod tests {
|
|||||||
serde_json::to_string(&TurnEvent::UserMessage {
|
serde_json::to_string(&TurnEvent::UserMessage {
|
||||||
text: "hi".into(),
|
text: "hi".into(),
|
||||||
images: Vec::new(),
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new(),
|
||||||
})
|
})
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
r#"{"type":"user_message","text":"hi","images":[]}"#
|
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!(
|
assert_eq!(
|
||||||
serde_json::to_string(&TurnEvent::ToolResult {
|
serde_json::to_string(&TurnEvent::ToolResult {
|
||||||
name: "bash".into(),
|
name: "bash".into(),
|
||||||
@@ -600,7 +628,8 @@ mod tests {
|
|||||||
event,
|
event,
|
||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: "hello".into(),
|
text: "hello".into(),
|
||||||
images: Vec::new()
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new()
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -614,7 +643,8 @@ mod tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: "x".into(),
|
text: "x".into(),
|
||||||
images: Vec::new()
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new()
|
||||||
}
|
}
|
||||||
.kind(),
|
.kind(),
|
||||||
"user_message"
|
"user_message"
|
||||||
@@ -659,6 +689,7 @@ mod tests {
|
|||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: "hello".into(),
|
text: "hello".into(),
|
||||||
images: Vec::new(),
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new(),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
hub.emit(&key, text("hi"));
|
hub.emit(&key, text("hi"));
|
||||||
@@ -669,7 +700,8 @@ mod tests {
|
|||||||
vec![
|
vec![
|
||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: "hello".into(),
|
text: "hello".into(),
|
||||||
images: Vec::new()
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new()
|
||||||
},
|
},
|
||||||
text("hi"),
|
text("hi"),
|
||||||
],
|
],
|
||||||
@@ -795,6 +827,7 @@ mod tests {
|
|||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: "earlier".into(),
|
text: "earlier".into(),
|
||||||
images: Vec::new(),
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new(),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
let (history, mut receiver) = hub.subscribe_with_history(&key);
|
let (history, mut receiver) = hub.subscribe_with_history(&key);
|
||||||
@@ -896,6 +929,7 @@ mod tests {
|
|||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: format!("q{turn}"),
|
text: format!("q{turn}"),
|
||||||
images: Vec::new(),
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new(),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
hub.emit(&key, text(&format!("a{turn}")));
|
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
|
/// The event one chat message becomes. The id is unique per message (a
|
||||||
/// wall-clock millisecond plus a process counter), so a redelivery
|
/// wall-clock millisecond plus a process counter), so a redelivery
|
||||||
/// never dedups a different message away. The payload carries the
|
/// never dedups a different message away. The chips' payloads ride
|
||||||
/// message's images when it has any, and no `images` key when it has
|
/// beside the text, and the images with them, each only when the
|
||||||
/// none — old payloads stay byte-identical.
|
/// message staged any — payloads without chips stay byte-identical.
|
||||||
pub fn user_event(key: &str, text: &str, images: &[WireImage]) -> Event {
|
pub fn user_event(key: &str, text: &str, pastes: &[String], images: &[WireImage]) -> Event {
|
||||||
static MESSAGE_SEQ: AtomicU64 = AtomicU64::new(0);
|
static MESSAGE_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||||
let now = SystemTime::now()
|
let now = SystemTime::now()
|
||||||
.duration_since(UNIX_EPOCH)
|
.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)
|
MESSAGE_SEQ.fetch_add(1, Ordering::Relaxed)
|
||||||
),
|
),
|
||||||
source: SOURCE.to_owned(),
|
source: SOURCE.to_owned(),
|
||||||
payload: if images.is_empty() {
|
// The chips' payloads ride only when the message staged any,
|
||||||
json!({ "key": key, "text": text })
|
// and images only when it carried any: the old two-field shape
|
||||||
} else {
|
// rides byte-for-byte otherwise.
|
||||||
json!({ "key": key, "text": text, "images": images })
|
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,
|
received_at: now.as_millis() as u64,
|
||||||
}
|
}
|
||||||
@@ -441,7 +449,9 @@ impl InteractiveHandler {
|
|||||||
.await
|
.await
|
||||||
.map_err(|err| format!("inbox poll for {key} failed: {err}"))?;
|
.map_err(|err| format!("inbox poll for {key} failed: {err}"))?;
|
||||||
// Texts fold in arrival order, and so do the images, across
|
// 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 texts = Vec::new();
|
||||||
let mut images = Vec::new();
|
let mut images = Vec::new();
|
||||||
for item in &items {
|
for item in &items {
|
||||||
@@ -451,7 +461,35 @@ impl InteractiveHandler {
|
|||||||
.or_else(|| payload.get("prompt"))
|
.or_else(|| payload.get("prompt"))
|
||||||
.and_then(Value::as_str)
|
.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) {
|
if let Some(carried) = payload.get("images").and_then(Value::as_array) {
|
||||||
images.extend(
|
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() {
|
if input.trim().is_empty() {
|
||||||
// Round one's emptiness is the dispatch bug it always was:
|
// Round one's emptiness is the dispatch bug it always was:
|
||||||
// the lease exists because something waited. A steered
|
// the lease exists because something waited. A steered
|
||||||
@@ -512,13 +565,17 @@ impl InteractiveHandler {
|
|||||||
}
|
}
|
||||||
// The transcript's question, recorded before anything else can
|
// The transcript's question, recorded before anything else can
|
||||||
// stream: a replay shows what was asked, not only what was
|
// stream: a replay shows what was asked, not only what was
|
||||||
// answered. Raw input — the notification-contract framing below
|
// answered. The fold composed the record — plain text, the
|
||||||
// is the model's business, not the viewer's.
|
// 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(
|
self.hub.emit(
|
||||||
&ctx.key,
|
&ctx.key,
|
||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: input.clone(),
|
text: input.clone(),
|
||||||
images: transcript_images,
|
images: transcript_images,
|
||||||
|
pastes: pastes.clone(),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
// A non-chat resident key has no subscriber to read the reply:
|
// 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
|
// future at its current await — a streaming request, or a
|
||||||
// running shell command, whose child dies with the drop. The
|
// running shell command, whose child dies with the drop. The
|
||||||
// next round revives whatever committed before the drop.
|
// next round revives whatever committed before the drop.
|
||||||
// Chat input may carry embedded pastes — the compact chip form
|
// The input rides in the plain form the fold recorded — the
|
||||||
// the UIs mint — migrated here into the plain record the engine
|
// payloads sit in the text and the model never sees a mark —
|
||||||
// and its providers read: the payload sits in the text, its span
|
// with the span note riding the message, so the checkpoint
|
||||||
// note survives the checkpoint, and the model never sees a mark.
|
// (and a session resumed from it) keeps the chips beside the
|
||||||
let mut turn_input = [Message::text_with_images(Role::User, input, core_images)];
|
// plain text. The framings above live in the model's copy:
|
||||||
rhema_core::paste::migrate(&mut turn_input);
|
// their bytes are known exactly, and each span shifts by them,
|
||||||
let [turn_input] = turn_input;
|
// 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(
|
let mut turn = Box::pin(run_turn(
|
||||||
&mut agent,
|
&mut agent,
|
||||||
&mut session,
|
&mut session,
|
||||||
@@ -1115,12 +1184,17 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The paste contract across the provider seam: a chat input that
|
/// The environment a paste test drives: the recording provider, the
|
||||||
/// carries an embedded paste (the compact form the UIs mint) is
|
/// hub, and a dispatcher wired to one interactive handler over a
|
||||||
/// expanded before the request leaves, while the transcript the hub
|
/// throwaway workspace.
|
||||||
/// streams keeps the compact form.
|
fn paste_env() -> (
|
||||||
#[tokio::test]
|
Arc<RecordingProvider>,
|
||||||
async fn an_embedded_paste_expands_for_the_model_and_not_for_the_transcript() {
|
Arc<EventHub>,
|
||||||
|
Arc<Dispatcher>,
|
||||||
|
InteractiveHandler,
|
||||||
|
Key,
|
||||||
|
tempfile::TempDir,
|
||||||
|
) {
|
||||||
let recorder = RecordingProvider::new();
|
let recorder = RecordingProvider::new();
|
||||||
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
|
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
|
||||||
let hub = Arc::new(EventHub::default());
|
let hub = Arc::new(EventHub::default());
|
||||||
@@ -1146,7 +1220,7 @@ mod tests {
|
|||||||
Arc::new(rhema_memory::VolatileStore::new()),
|
Arc::new(rhema_memory::VolatileStore::new()),
|
||||||
Arc::new(Bootstrap::new(workspace.path().join("bootstrap")).expect("store opens")),
|
Arc::new(Bootstrap::new(workspace.path().join("bootstrap")).expect("store opens")),
|
||||||
hub.clone(),
|
hub.clone(),
|
||||||
notifications.clone(),
|
notifications,
|
||||||
attachments(),
|
attachments(),
|
||||||
crate::config::DEFAULT_MAX_TURN_STEPS,
|
crate::config::DEFAULT_MAX_TURN_STEPS,
|
||||||
extensions,
|
extensions,
|
||||||
@@ -1161,14 +1235,31 @@ mod tests {
|
|||||||
Arc::new(VolatileStore::new()),
|
Arc::new(VolatileStore::new()),
|
||||||
));
|
));
|
||||||
register_user(&dispatcher);
|
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))
|
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
|
||||||
.with_holder("test");
|
.with_holder("test");
|
||||||
let key = Key::from("interactive:web");
|
|
||||||
dispatcher
|
dispatcher
|
||||||
.ingest(user_event(
|
.ingest(user_event(
|
||||||
key.as_str(),
|
key.as_str(),
|
||||||
"review this:\u{FFFC}fn main() {}\nfn other() {}\u{FFFC}",
|
"review this:\u{FFFC}fn main() {}\nfn other() {}\u{FFFC}",
|
||||||
&[],
|
&[],
|
||||||
|
&[],
|
||||||
))
|
))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
driver.run_once().await.expect("the run happens");
|
driver.run_once().await.expect("the run happens");
|
||||||
@@ -1178,17 +1269,61 @@ mod tests {
|
|||||||
"review this:fn main() {}\nfn other() {}",
|
"review this:fn main() {}\nfn other() {}",
|
||||||
"the model saw the payload, not the marks"
|
"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 (history, _) = hub.subscribe_with_history(&key);
|
||||||
let saw_input = history.into_iter().find_map(|event| match event {
|
let question = history.into_iter().find_map(|event| match event {
|
||||||
TurnEvent::UserMessage { text, .. } => Some(text),
|
TurnEvent::UserMessage { text, pastes, .. } => Some((text, pastes)),
|
||||||
_ => None,
|
_ => None,
|
||||||
});
|
});
|
||||||
assert!(
|
let (text, pastes) = question.expect("the transcript saw the question");
|
||||||
saw_input
|
let payload = "fn main() {}\nfn other() {}";
|
||||||
.expect("the transcript saw the question")
|
assert_eq!(text, "review this:fn main() {}\nfn other() {}", "no marks");
|
||||||
.contains('\u{FFFC}'),
|
assert_eq!(pastes.len(), 1, "the chip is one span");
|
||||||
"the transcript keeps the compact chip form"
|
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`.
|
/// A scripted tool-call turn: the model asking for `name` with `args`.
|
||||||
@@ -1313,8 +1448,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn user_events_carry_the_key_and_unique_ids() {
|
fn user_events_carry_the_key_and_unique_ids() {
|
||||||
let first = user_event("interactive:web", "hello", &[]);
|
let first = user_event("interactive:web", "hello", &[], &[]);
|
||||||
let second = user_event("interactive:web", "again", &[]);
|
let second = user_event("interactive:web", "again", &[], &[]);
|
||||||
assert_eq!(first.source, "user");
|
assert_eq!(first.source, "user");
|
||||||
assert_eq!(first.id, first.id, "stable within itself");
|
assert_eq!(first.id, first.id, "stable within itself");
|
||||||
assert_ne!(first.id, second.id, "messages never share a dedup id");
|
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.
|
/// order; a plain message carries no `images` key at all.
|
||||||
#[test]
|
#[test]
|
||||||
fn user_events_carry_images_only_when_the_message_has_any() {
|
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!(
|
assert_eq!(
|
||||||
bare.payload,
|
bare.payload,
|
||||||
json!({"key": "interactive:web", "text": "plain"}),
|
json!({"key": "interactive:web", "text": "plain"}),
|
||||||
@@ -1337,6 +1472,7 @@ mod tests {
|
|||||||
let carried = user_event(
|
let carried = user_event(
|
||||||
"interactive:web",
|
"interactive:web",
|
||||||
"look",
|
"look",
|
||||||
|
&[],
|
||||||
&[
|
&[
|
||||||
WireImage {
|
WireImage {
|
||||||
media_type: "image/png".to_owned(),
|
media_type: "image/png".to_owned(),
|
||||||
@@ -1369,7 +1505,7 @@ mod tests {
|
|||||||
Arc::new(VolatileStore::new()),
|
Arc::new(VolatileStore::new()),
|
||||||
);
|
);
|
||||||
register_user(&dispatcher);
|
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
|
// Ingesting resolves the key through the registered fn: the
|
||||||
// record lands under exactly the payload's key.
|
// record lands under exactly the payload's key.
|
||||||
dispatcher.ingest(event).expect("ingests");
|
dispatcher.ingest(event).expect("ingests");
|
||||||
@@ -1605,7 +1741,7 @@ mod tests {
|
|||||||
let key = Key::from("interactive:web");
|
let key = Key::from("interactive:web");
|
||||||
let mut receiver = hub.subscribe(&key);
|
let mut receiver = hub.subscribe(&key);
|
||||||
dispatcher
|
dispatcher
|
||||||
.ingest(user_event(key.as_str(), "hello", &[]))
|
.ingest(user_event(key.as_str(), "hello", &[], &[]))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
|
|
||||||
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
|
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
|
||||||
@@ -1618,7 +1754,8 @@ mod tests {
|
|||||||
receiver.try_recv().unwrap(),
|
receiver.try_recv().unwrap(),
|
||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: "hello".into(),
|
text: "hello".into(),
|
||||||
images: Vec::new()
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new()
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -1694,7 +1831,7 @@ mod tests {
|
|||||||
let key = Key::from("interactive:web");
|
let key = Key::from("interactive:web");
|
||||||
let mut receiver = hub.subscribe(&key);
|
let mut receiver = hub.subscribe(&key);
|
||||||
dispatcher
|
dispatcher
|
||||||
.ingest(user_event(key.as_str(), "hello", &[]))
|
.ingest(user_event(key.as_str(), "hello", &[], &[]))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
|
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
|
||||||
.with_holder("test");
|
.with_holder("test");
|
||||||
@@ -1714,7 +1851,7 @@ mod tests {
|
|||||||
|
|
||||||
// Steer, in the route's order: ingest first, signal second.
|
// Steer, in the route's order: ingest first, signal second.
|
||||||
dispatcher
|
dispatcher
|
||||||
.ingest(user_event(key.as_str(), "stop that", &[]))
|
.ingest(user_event(key.as_str(), "stop that", &[], &[]))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
assert!(registry.signal(key.as_str()));
|
assert!(registry.signal(key.as_str()));
|
||||||
|
|
||||||
@@ -1731,7 +1868,8 @@ mod tests {
|
|||||||
receiver.try_recv().unwrap(),
|
receiver.try_recv().unwrap(),
|
||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: "hello".into(),
|
text: "hello".into(),
|
||||||
images: Vec::new()
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new()
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -1745,7 +1883,8 @@ mod tests {
|
|||||||
receiver.try_recv().unwrap(),
|
receiver.try_recv().unwrap(),
|
||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: "stop that".into(),
|
text: "stop that".into(),
|
||||||
images: Vec::new()
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new()
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -1919,6 +2058,7 @@ mod tests {
|
|||||||
.ingest(user_event(
|
.ingest(user_event(
|
||||||
key.as_str(),
|
key.as_str(),
|
||||||
"look at this",
|
"look at this",
|
||||||
|
&[],
|
||||||
&[WireImage {
|
&[WireImage {
|
||||||
media_type: "image/png".to_owned(),
|
media_type: "image/png".to_owned(),
|
||||||
data: png.clone(),
|
data: png.clone(),
|
||||||
@@ -1929,6 +2069,7 @@ mod tests {
|
|||||||
.ingest(user_event(
|
.ingest(user_event(
|
||||||
key.as_str(),
|
key.as_str(),
|
||||||
"and at this",
|
"and at this",
|
||||||
|
&[],
|
||||||
&[WireImage {
|
&[WireImage {
|
||||||
media_type: "Image/JPEG".to_owned(),
|
media_type: "Image/JPEG".to_owned(),
|
||||||
data: jpeg.clone(),
|
data: jpeg.clone(),
|
||||||
@@ -1936,7 +2077,7 @@ mod tests {
|
|||||||
))
|
))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
dispatcher
|
dispatcher
|
||||||
.ingest(user_event(key.as_str(), "no picture here", &[]))
|
.ingest(user_event(key.as_str(), "no picture here", &[], &[]))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
driver.run_once().await.expect("the run happens"),
|
driver.run_once().await.expect("the run happens"),
|
||||||
@@ -1949,7 +2090,11 @@ mod tests {
|
|||||||
let question = history
|
let question = history
|
||||||
.iter()
|
.iter()
|
||||||
.find_map(|event| match event {
|
.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,
|
_ => None,
|
||||||
})
|
})
|
||||||
.expect("the transcript saw the question");
|
.expect("the transcript saw the question");
|
||||||
@@ -2055,7 +2200,7 @@ mod tests {
|
|||||||
|
|
||||||
// Dispatch 1: the model saves through the chain's memory tools.
|
// Dispatch 1: the model saves through the chain's memory tools.
|
||||||
dispatcher
|
dispatcher
|
||||||
.ingest(user_event(key.as_str(), "remember the channel", &[]))
|
.ingest(user_event(key.as_str(), "remember the channel", &[], &[]))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
driver.run_once().await.expect("first run"),
|
driver.run_once().await.expect("first run"),
|
||||||
@@ -2074,7 +2219,7 @@ mod tests {
|
|||||||
// Dispatch 2: the model searches the same chain and answers from
|
// Dispatch 2: the model searches the same chain and answers from
|
||||||
// memory — a fresh session turn, the same durable store.
|
// memory — a fresh session turn, the same durable store.
|
||||||
dispatcher
|
dispatcher
|
||||||
.ingest(user_event(key.as_str(), "where do releases go?", &[]))
|
.ingest(user_event(key.as_str(), "where do releases go?", &[], &[]))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
driver.run_once().await.expect("second run"),
|
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
|
// Dispatch 1: the model writes SOUL.md through the chain. A key
|
||||||
// with a session continues, so both calls ride one key.
|
// with a session continues, so both calls ride one key.
|
||||||
dispatcher
|
dispatcher
|
||||||
.ingest(user_event(key.as_str(), "call me claw", &[]))
|
.ingest(user_event(key.as_str(), "call me claw", &[], &[]))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
driver.run_once().await.expect("first run"),
|
driver.run_once().await.expect("first run"),
|
||||||
@@ -2181,7 +2326,7 @@ mod tests {
|
|||||||
|
|
||||||
// Dispatch 2: USER.md, same chain — and the pending flag clears.
|
// Dispatch 2: USER.md, same chain — and the pending flag clears.
|
||||||
dispatcher
|
dispatcher
|
||||||
.ingest(user_event(key.as_str(), "and I am Ana", &[]))
|
.ingest(user_event(key.as_str(), "and I am Ana", &[], &[]))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
driver.run_once().await.expect("second run"),
|
driver.run_once().await.expect("second run"),
|
||||||
@@ -2239,7 +2384,7 @@ mod tests {
|
|||||||
register_user(&dispatcher);
|
register_user(&dispatcher);
|
||||||
let key = Key::from("interactive:web");
|
let key = Key::from("interactive:web");
|
||||||
dispatcher
|
dispatcher
|
||||||
.ingest(user_event(key.as_str(), "hello", &[]))
|
.ingest(user_event(key.as_str(), "hello", &[], &[]))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
let driver = rhema_autonomous_agent::Driver::new(dispatcher, Arc::new(handler));
|
let driver = rhema_autonomous_agent::Driver::new(dispatcher, Arc::new(handler));
|
||||||
driver.run_once().await.expect("the run happens");
|
driver.run_once().await.expect("the run happens");
|
||||||
@@ -2379,7 +2524,7 @@ mod tests {
|
|||||||
// An interactive reply is the chat surface's business: notified
|
// An interactive reply is the chat surface's business: notified
|
||||||
// nowhere.
|
// nowhere.
|
||||||
dispatcher
|
dispatcher
|
||||||
.ingest(user_event("interactive:web", "hello", &[]))
|
.ingest(user_event("interactive:web", "hello", &[], &[]))
|
||||||
.expect("ingests");
|
.expect("ingests");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
driver.run_once().await.expect("the run happens"),
|
driver.run_once().await.expect("the run happens"),
|
||||||
@@ -2457,7 +2602,12 @@ mod tests {
|
|||||||
|
|
||||||
// The evening's work, in the chat session.
|
// The evening's work, in the chat session.
|
||||||
dispatcher
|
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");
|
.expect("ingests");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
driver.run_once().await.expect("first run"),
|
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(
|
if let Err(err) = state.dispatcher().ingest(crate::interactive::user_event(
|
||||||
key.as_str(),
|
key.as_str(),
|
||||||
&input.text,
|
&input.text,
|
||||||
|
&[],
|
||||||
&input.images,
|
&input.images,
|
||||||
)) {
|
)) {
|
||||||
return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string());
|
return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string());
|
||||||
|
|||||||
@@ -325,6 +325,7 @@ mod tests {
|
|||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: "hello".into(),
|
text: "hello".into(),
|
||||||
images: Vec::new(),
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new(),
|
||||||
},
|
},
|
||||||
text_delta("hi"),
|
text_delta("hi"),
|
||||||
],
|
],
|
||||||
@@ -348,7 +349,8 @@ mod tests {
|
|||||||
0,
|
0,
|
||||||
TurnEvent::UserMessage {
|
TurnEvent::UserMessage {
|
||||||
text: "hello".into(),
|
text: "hello".into(),
|
||||||
images: Vec::new()
|
images: Vec::new(),
|
||||||
|
pastes: Vec::new()
|
||||||
}
|
}
|
||||||
),
|
),
|
||||||
(1, text_delta("hi")),
|
(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
|
/// A turn nobody watched is still replayable: a client arriving after
|
||||||
/// the fact — a reloaded browser, a reopened phone — subscribes cold and
|
/// the fact — a reloaded browser, a reopened phone — subscribes cold and
|
||||||
/// gets the finished turns back before the live feed. The same holds
|
/// gets the finished turns back before the live feed. The same holds
|
||||||
|
|||||||
+10
-5
@@ -97,10 +97,14 @@ Two consequences worth knowing before changing this code:
|
|||||||
folds those other events; only the render ignores them.
|
folds those other events; only the render ignores them.
|
||||||
- **Long pastes travel as chips.** A paste over three lines (the TUI's
|
- **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
|
`PASTE_INLINE_LINES`) never lands in the composer; it stages as a
|
||||||
droppable chip (`▣1 42L`) and embeds into the sent text as
|
droppable chip (`▣1 42L`) and rides the body's `pastes` array beside
|
||||||
U+FFFC-payload-U+FFFC — the same record `rhema-core`'s
|
the plain draft — the claw composes the record (the payload in
|
||||||
`paste::embed` keeps — so the transcript renders each embed back as
|
place, the span note beside it) — so no mark ever crosses the wire.
|
||||||
a chip in place of the payload. An unpaired mark is literal text.
|
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
|
- **The agent can ask.** A `consent_request` event renders as an
|
||||||
inline card: kind `secret` gets a password input plus submit, kind
|
inline card: kind `secret` gets a password input plus submit, kind
|
||||||
`phone` gets Approve/Deny, and both carry a deny link
|
`phone` gets Approve/Deny, and both carry a deny link
|
||||||
@@ -198,7 +202,8 @@ app/
|
|||||||
composables/
|
composables/
|
||||||
useClaw.ts the typed API client + fetch-based SSE
|
useClaw.ts the typed API client + fetch-based SSE
|
||||||
useTranscript.ts folds TurnEvents into renderable turn
|
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/
|
server/
|
||||||
middleware/claw-proxy.ts dev-only same-origin proxy to a running claw
|
middleware/claw-proxy.ts dev-only same-origin proxy to a running claw
|
||||||
```
|
```
|
||||||
+12
-7
@@ -21,7 +21,7 @@ import type {
|
|||||||
SandboxState,
|
SandboxState,
|
||||||
StreamStatus,
|
StreamStatus,
|
||||||
} from '~/composables/useClaw'
|
} from '~/composables/useClaw'
|
||||||
import { useTranscript } from '~/composables/useTranscript'
|
import { composeChips, useTranscript } from '~/composables/useTranscript'
|
||||||
import type { StagedImage } from '~/composables/useTranscript'
|
import type { StagedImage } from '~/composables/useTranscript'
|
||||||
|
|
||||||
const TOKEN_STORE_KEY = 'claw.token'
|
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> {
|
async function send(message: { text: string; pastes: string[]; images: StagedImage[] }): Promise<void> {
|
||||||
// The optimistic row renders the staged previews; the stream's
|
// The optimistic row renders the staged previews and the composed
|
||||||
// user_message echo carries the stored ids and dedupes against it.
|
// 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(
|
const rowId = transcript.addSent(
|
||||||
message.text,
|
composed.text,
|
||||||
message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })),
|
message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })),
|
||||||
|
composed.pastes,
|
||||||
)
|
)
|
||||||
busy.value = true
|
busy.value = true
|
||||||
try {
|
try {
|
||||||
// Fire-and-forget by design: the claw answers 202 and the reply
|
// Fire-and-forget by design: the claw answers 202 and the reply
|
||||||
// arrives on the event stream. The body carries the images only
|
// arrives on the event stream. The chips and the images ride the
|
||||||
// when there are some.
|
// body only when there are some.
|
||||||
await claw.sendMessage(
|
await claw.sendMessage(
|
||||||
activeKey.value,
|
activeKey.value,
|
||||||
message.text,
|
message.text,
|
||||||
|
message.pastes,
|
||||||
message.images.map(({ media_type, data }) => ({ media_type, data })),
|
message.images.map(({ media_type, data }) => ({ media_type, data })),
|
||||||
)
|
)
|
||||||
apiError.value = null
|
apiError.value = null
|
||||||
|
|||||||
@@ -10,12 +10,14 @@
|
|||||||
import {
|
import {
|
||||||
PASTE_INLINE_LINES,
|
PASTE_INLINE_LINES,
|
||||||
chipLabel,
|
chipLabel,
|
||||||
embedPastes,
|
byteToIndex,
|
||||||
|
chipLinesLabel,
|
||||||
lineCount,
|
lineCount,
|
||||||
normalizePaste,
|
normalizePaste,
|
||||||
pasteParts,
|
pasteParts,
|
||||||
} from '~/composables/useTranscript'
|
} from '~/composables/useTranscript'
|
||||||
import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw'
|
import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw'
|
||||||
|
import type { PasteSpan } from '~/composables/useClaw'
|
||||||
import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript'
|
import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -45,6 +47,9 @@ const agentName = computed(() => props.identity?.name?.trim() || 'rhema')
|
|||||||
* the staged images, previews included for the optimistic row. */
|
* the staged images, previews included for the optimistic row. */
|
||||||
interface SendPayload {
|
interface SendPayload {
|
||||||
text: string
|
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[]
|
images: StagedImage[]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,7 +162,7 @@ function submit(): void {
|
|||||||
// answers 202 at once) — a running turn never blocks the composer,
|
// answers 202 at once) — a running turn never blocks the composer,
|
||||||
// because a send into one steers it.
|
// because a send into one steers it.
|
||||||
if (!text || !props.canSend || props.busy) return
|
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++
|
stageGeneration++
|
||||||
draft.value = ''
|
draft.value = ''
|
||||||
pastes.value = []
|
pastes.value = []
|
||||||
@@ -359,17 +364,36 @@ function storedImageName(image: SentImage): string {
|
|||||||
type MessageSegment = PastePart | { kind: 'chip'; label: string }
|
type MessageSegment = PastePart | { kind: 'chip'; label: string }
|
||||||
|
|
||||||
/** The message's render pieces: literal text and resolved chips, the
|
/** The message's render pieces: literal text and resolved chips, the
|
||||||
* chips' one-based ids counted across the message. */
|
* chips' one-based ids counted across the message. The chips come
|
||||||
function messageSegments(text: string): MessageSegment[] {
|
* 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[] = []
|
const segments: MessageSegment[] = []
|
||||||
let chip = 0
|
let chip = 0
|
||||||
for (const part of pasteParts(text)) {
|
let cut = 0
|
||||||
if (part.kind === 'text') {
|
for (const span of [...pastes].sort((a, b) => a.start - b.start)) {
|
||||||
if (part.text !== '') segments.push(part)
|
const start = indexOf(span.start)
|
||||||
} else {
|
const end = indexOf(span.end)
|
||||||
segments.push({ kind: 'chip', label: chipLabel(part.text, chip++) })
|
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
|
return segments
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -445,7 +469,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="reply plain">
|
<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>
|
<span v-if="segment.kind === 'chip'" class="badge paste-chip">{{ segment.label }}</span>
|
||||||
<template v-else>{{ segment.text }}</template>
|
<template v-else>{{ segment.text }}</template>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -56,9 +56,20 @@ export interface UserImage {
|
|||||||
media_type: string
|
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). */
|
/** One turn event, exactly `hub.rs`'s `TurnEvent` (serde type tag, snake case). */
|
||||||
export type TurnEvent =
|
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: 'thinking_delta'; text: string }
|
||||||
| { type: 'text_delta'; text: string }
|
| { type: 'text_delta'; text: string }
|
||||||
| { type: 'tool_start'; name: 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,
|
* a plain src will not do). Cached per id: attachments are immutable,
|
||||||
* so a replayed event never refetches. */
|
* so a replayed event never refetches. */
|
||||||
attachmentUrl(id: string): Promise<string>
|
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. */
|
/** `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, images?: OutboundImage[]): Promise<void>
|
sendMessage(key: string, text: string, pastes?: string[], images?: OutboundImage[]): Promise<void>
|
||||||
/** `GET /v1/providers` — the constructible backends and the active pair. */
|
/** `GET /v1/providers` — the constructible backends and the active pair. */
|
||||||
providers(): Promise<ProvidersState>
|
providers(): Promise<ProvidersState>
|
||||||
/** `PUT /v1/providers/active` — switch the backend, persisted claw-side. Answers the new active pair only. */
|
/** `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`, {
|
await send(`/v1/sessions/${encodeURIComponent(key)}/messages`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
|
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
|
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. */
|
/** Parses one `data:` payload into a `TurnEvent`; unknown shapes are dropped, not guessed. */
|
||||||
function parseTurnEvent(data: string): TurnEvent | null {
|
function parseTurnEvent(data: string): TurnEvent | null {
|
||||||
try {
|
try {
|
||||||
@@ -929,6 +966,7 @@ function parseTurnEvent(data: string): TurnEvent | null {
|
|||||||
type: 'user_message',
|
type: 'user_message',
|
||||||
text: String(raw.text ?? ''),
|
text: String(raw.text ?? ''),
|
||||||
images: parseUserImages(raw.images),
|
images: parseUserImages(raw.images),
|
||||||
|
pastes: parseUserPastes(raw.pastes),
|
||||||
}
|
}
|
||||||
case 'thinking_delta':
|
case 'thinking_delta':
|
||||||
case 'text_delta':
|
case 'text_delta':
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
// mirror when the stream reopens and folds what arrives, never the other
|
// mirror when the stream reopens and folds what arrives, never the other
|
||||||
// way around.
|
// way around.
|
||||||
import { ref } from 'vue'
|
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. */
|
/** One tool call inside a turn: started, then completed by its result. */
|
||||||
export interface ToolRow {
|
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. */
|
/** A transcript line: a message the local user sent, or one streamed turn. */
|
||||||
export type TranscriptItem =
|
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: 'turn'; id: number; turn: TurnBlock }
|
||||||
| { kind: 'consent'; id: number; consent: ConsentCard }
|
| { kind: 'consent'; id: number; consent: ConsentCard }
|
||||||
| { kind: 'attachment'; id: number; attachment: AttachmentCard }
|
| { kind: 'attachment'; id: number; attachment: AttachmentCard }
|
||||||
@@ -123,20 +123,53 @@ export function lineCount(text: string): number {
|
|||||||
return lines.length
|
return lines.length
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A chip's label: `▣1 5L` — the anchor's one-based id and the
|
/** A chip's label from its line count: `▣1 5L` — the chip's
|
||||||
* payload's line count (the TUI's chip_label). */
|
* one-based id and the payload's line count (the TUI's chip_label). */
|
||||||
export function chipLabel(paste: string, index: number): string {
|
export function chipLinesLabel(lines: number, index: number): string {
|
||||||
return `▣${index + 1} ${lineCount(paste)}L`
|
return `▣${index + 1} ${lines}L`
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Appends each paste as one MARK-payload-MARK embed, in order — the
|
/** A chip's label from its payload (the TUI's chip_label). */
|
||||||
* session's record of the prompt (paste::embed; a web draft holds no
|
export function chipLabel(paste: string, index: number): string {
|
||||||
* anchors, so every payload lands at the end). */
|
return chipLinesLabel(lineCount(paste), index)
|
||||||
export function embedPastes(draft: string, pastes: string[]): string {
|
}
|
||||||
return (
|
|
||||||
draft +
|
/** The modern record the wire carries: each paste a byte span in the
|
||||||
pastes.map((paste) => `${PASTE_MARK}${normalizePaste(paste)}${PASTE_MARK}`).join('')
|
* 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. */
|
/** One scanned piece of embedded-form text. */
|
||||||
@@ -244,6 +277,7 @@ export function useTranscript() {
|
|||||||
id: nextId++,
|
id: nextId++,
|
||||||
text: event.text,
|
text: event.text,
|
||||||
images: event.images.map((image) => ({ ...image, url: null, name: null })),
|
images: event.images.map((image) => ({ ...image, url: null, name: null })),
|
||||||
|
pastes: event.pastes,
|
||||||
})
|
})
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -356,10 +390,10 @@ export function useTranscript() {
|
|||||||
* Its images render from the staged previews — the claw stores them
|
* Its images render from the staged previews — the claw stores them
|
||||||
* and the stream's echo dedupes against this row. Returns the row's
|
* and the stream's echo dedupes against this row. Returns the row's
|
||||||
* id, so a failed POST can retract it. */
|
* 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++
|
const id = nextId++
|
||||||
pendingSent.push({ text, images: images.length, itemId: id })
|
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
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user