From 8dfd966d3f8bbdc6aefe86855207e2a0bbe9f2cb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 22:03:46 +0100 Subject: [PATCH] K20 reply excerpts: a line the page lists whole is named, not quoted again; a quote cut at the cap ends on a word and says "(shortened)" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Soul (high), plan E: the quote above a reply was cut at REPLY_EXCERPT_CHARS mid-word with no mark, and Eureka read her own edited line as cut short, said so, and promised a repair. Kiko also read Meta's line three times. - ReplyTo.at_cap (serde-skipped, read off the decode): the excerpt as sent reached the mouth's cap, so the line may run on. The fixture mouth sets it the same way. Replied carries the event and at_cap. - reply_parts: when the page lists the answered line whole, the reply reads ", replying to {other}'s line ({when}, shown here)" and quotes nothing, wherever that is no longer than the quote. Otherwise a capped quote ends on its last whole word: > {other}: "...word…" (shortened), the mark outside the quote marks. - Chat and beat pages render twice: the first pass, every reply quoted, selects the lines each page lists whole (heard: whole messages to her, others kept, earlier lines kept; stimulus: its own whole lines plus heard's, since only the Interpreter reads it, beside heard). Names never grow a line, so the second pass keeps every line the first did. - shown_words is unchanged: the echo check reads every word the mouth quoted. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/chat_client.rs | 11 +- crates/mind-body/src/chat_client/tests.rs | 11 +- crates/mind-body/src/projection.rs | 2 +- crates/mind-body/src/projection/harness.rs | 2 +- .../mind-body/src/projection/harness/tests.rs | 15 +- crates/mind-body/src/projection/select.rs | 158 +++++++++++++----- crates/mind-body/src/projection/tests.rs | 59 ++++++- crates/mind-body/tests/public_surface.txt | 2 +- 8 files changed, 204 insertions(+), 56 deletions(-) diff --git a/crates/mind-body/src/chat_client.rs b/crates/mind-body/src/chat_client.rs index 9c90d55..9ec290a 100644 --- a/crates/mind-body/src/chat_client.rs +++ b/crates/mind-body/src/chat_client.rs @@ -94,6 +94,11 @@ pub struct ReplyTo { pub event_id: String, pub sender: String, pub excerpt: Option, + /// Whether the excerpt as sent reached `REPLY_EXCERPT_CHARS`, the mouth's cap: the line may run on past it, cut wherever the + /// cap fell. A line of exactly the cap reads as cut too; the mouth says nothing that tells the two apart. Read off the decode, + /// never sent. + #[serde(skip)] + pub at_cap: bool, } /// How a reply link out of the mouth's contract fails it, first by tuple order. A class and nothing the mouth sent, so no path can echo @@ -311,11 +316,11 @@ impl<'de> Deserialize<'de> for ReplyLink { (Some(Element::Text(event_id)), _, _) if !event_id_shape(&event_id) => Self::Dropped(ReplyViolation::BadEventId), (Some(Element::Text(_)), Some(Element::Text(sender)), _) if !matrix_user_id(&sender) => Self::Dropped(ReplyViolation::BadSenderId), (Some(Element::Text(event_id)), Some(Element::Text(sender)), Some(excerpt)) => match excerpt { - Element::Nil => Self::Quote(ReplyTo { event_id, sender, excerpt: None }), + Element::Nil => Self::Quote(ReplyTo { event_id, sender, excerpt: None, at_cap: false }), Element::Text(text) if text.chars().take(REPLY_EXCERPT_CHARS + 1).count() > REPLY_EXCERPT_CHARS => Self::Dropped(ReplyViolation::ExcerptTooLong), Element::Text(text) => { - let shown = without_invisible(&text); - Self::Quote(ReplyTo { event_id, sender, excerpt: if shown.is_empty() { None } else { Some(shown) } }) + let (shown, at_cap) = (without_invisible(&text), text.chars().count() == REPLY_EXCERPT_CHARS); + Self::Quote(ReplyTo { event_id, sender, excerpt: if shown.is_empty() { None } else { Some(shown) }, at_cap }) } _ => Self::Dropped(ReplyViolation::ExcerptNotText), }, diff --git a/crates/mind-body/src/chat_client/tests.rs b/crates/mind-body/src/chat_client/tests.rs index 770c90d..e152fe8 100644 --- a/crates/mind-body/src/chat_client/tests.rs +++ b/crates/mind-body/src/chat_client/tests.rs @@ -143,7 +143,7 @@ fn a_tail_line_carries_the_event_it_replies_to() { value[2][1].as_array_mut().unwrap().push(serde_json::json!(["$e0", "@meta:gamecult.org", "earlier"])); value[2][0].as_array_mut().unwrap().push(serde_json::json!(["$q", "@a:b", 5])); let tail = decode::(&rmp_serde::to_vec(&value).unwrap()).unwrap().tail.unwrap(); - assert_eq!(tail[1].reply_to, ReplyLink::Quote(ReplyTo { event_id: "$e0".into(), sender: "@meta:gamecult.org".into(), excerpt: Some("earlier".into()) })); + assert_eq!(tail[1].reply_to, ReplyLink::Quote(ReplyTo { event_id: "$e0".into(), sender: "@meta:gamecult.org".into(), excerpt: Some("earlier".into()), at_cap: false })); assert_eq!(tail[0].reply_to, ReplyLink::Dropped(ReplyViolation::ExcerptNotText), "a defective link drops that quote only"); let plain: ChatPending = decode(PENDING_TAIL_BYTES).unwrap(); assert!(plain.tail.unwrap().iter().all(|line| line.reply_to == ReplyLink::Absent), "seven fields reply to nothing"); @@ -349,7 +349,7 @@ fn the_pending_answer_decodes_tail_gaps_and_defaults_them_to_none() { } fn quote(sender: &str, excerpt: Option<&str>) -> ReplyLink { - ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: sender.into(), excerpt: excerpt.map(Into::into) }) + ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: sender.into(), excerpt: excerpt.map(Into::into), at_cap: false }) } /// The v4 answers carry `reply_to` at delivery index 14. The mouth always sends the fourth, empty `tail_gaps` element on a v4 answer, @@ -578,7 +578,7 @@ fn format_and_private_use_characters_are_stripped_from_the_excerpt() { fn an_excerpt_emptied_by_stripping_is_none_and_the_quote_stays() { for sent in ["\u{FE0F}", "\u{200B}\u{E0049}", &"\u{FE0F}\u{200D}".repeat(5), ""] { let link = link_of(&answer_with(serde_json::json!(["$q1", "@alice:gamecult.org", sent]))); - assert_eq!(link, ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: "@alice:gamecult.org".into(), excerpt: None }), "{sent:?}"); + assert_eq!(link, ReplyLink::Quote(ReplyTo { event_id: "$q1".into(), sender: "@alice:gamecult.org".into(), excerpt: None, at_cap: false }), "{sent:?}"); } assert_eq!(excerpt_of(" ").as_deref(), Some(" ")); assert_eq!(link_of(&answer_with(serde_json::json!(["$q1", "@alice:gamecult.org", null]))), quote("@alice:gamecult.org", None)); @@ -592,6 +592,11 @@ fn the_excerpt_bound_is_checked_before_the_strip_and_never_clips() { assert_eq!(dropped_as(long(240, "\u{FE0F}")), Some(ReplyViolation::ExcerptTooLong)); assert_eq!(excerpt_of(&format!("{}\u{FE0F}", "x".repeat(239))).map(|t| t.chars().count()), Some(239)); assert_eq!(dropped_as(serde_json::json!(["$q1", "@a:b", "\u{FE0F}".repeat(1_000_000)])), Some(ReplyViolation::ExcerptTooLong)); + // An excerpt that reached the cap as sent may be cut, whatever the strip left of it; one short of it is whole. + let at_cap = |sent: serde_json::Value| link_of(&answer_with(sent)).quote().map(|quote| quote.at_cap); + assert_eq!(at_cap(long(240, "")), Some(true)); + assert_eq!(at_cap(long(239, "\u{FE0F}")), Some(true)); + assert_eq!(at_cap(long(239, "")), Some(false)); } /// Invalid UTF-8 in the excerpt's bytes is a defect of that quote, never of the document. diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 3ee9978..5428b91 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -280,7 +280,7 @@ fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Roo /// The line a reply answers, as the mouth quoted it within its contract; a dropped link is no reply (`ReplyLink::quote`). fn replied(link: &ReplyLink) -> Option { - link.quote().map(|quote| Replied { sender: quote.sender.clone(), text: quote.excerpt.clone() }) + link.quote().map(|quote| Replied { event: quote.event_id.clone(), sender: quote.sender.clone(), text: quote.excerpt.clone(), at_cap: quote.at_cap }) } fn packet_json(packet: &Packet) -> Value { diff --git a/crates/mind-body/src/projection/harness.rs b/crates/mind-body/src/projection/harness.rs index 1fd3c93..e07e6be 100644 --- a/crates/mind-body/src/projection/harness.rs +++ b/crates/mind-body/src/projection/harness.rs @@ -179,7 +179,7 @@ impl Line { /// original, with its sender, above the reply (map 16.20.8 (D)); the simulated room shows it the same way. fn reply_link(&self, lines: &[Line]) -> ReplyLink { match self.reply_to.and_then(|at| lines.get(at).map(|replied| (at, replied))) { - Some((at, replied)) => ReplyLink::Quote(ReplyTo { event_id: format!("$fixture-{at}"), sender: replied.from.clone(), excerpt: Some(replied.says.chars().take(REPLY_EXCERPT_CHARS).collect()) }), + Some((at, replied)) => ReplyLink::Quote(ReplyTo { event_id: format!("$fixture-{at}"), sender: replied.from.clone(), excerpt: Some(replied.says.chars().take(REPLY_EXCERPT_CHARS).collect()), at_cap: replied.says.chars().count() >= REPLY_EXCERPT_CHARS }), None => ReplyLink::Absent, } } diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index e649a02..9d2e0c1 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -162,12 +162,25 @@ says = "This is what she said before she left." ) .unwrap(); let pending = MouthReader::pending(&fixture).unwrap(); - let quote = ReplyTo { event_id: "$fixture-0".into(), sender: "@meta:gamecult.org".into(), excerpt: Some("Back at six, tell Kiko the render can wait.".into()) }; + let quote = ReplyTo { event_id: "$fixture-0".into(), sender: "@meta:gamecult.org".into(), excerpt: Some("Back at six, tell Kiko the render can wait.".into()), at_cap: false }; assert_eq!(pending.deliveries[0].reply_to, ReplyLink::Quote(quote.clone())); let tail = pending.tail.unwrap(); assert_eq!((&tail[0].reply_to, &tail[1].reply_to), (&ReplyLink::Absent, &ReplyLink::Quote(quote))); } +/// The fixture quotes as the mouth does: a line past the cap is cut at it, and the quote says it reached the cap. +#[test] +fn a_reply_to_a_line_past_the_cap_quotes_it_cut_and_says_so() { + let long = "word ".repeat(60); + let fixture = Fixture::parse(&format!( + "her = \"@eureka:gamecult.org\"\nkind = \"chat\"\nnow = \"2026-11-20T15:00:00Z\"\nrooms = [\"#minds:gamecult.org\"]\n[[message]]\nfrom = \"@eureka:gamecult.org\"\nroom = \"#minds:gamecult.org\"\nago = \"1h\"\nsays = \"{long}\"\n[[message]]\nfrom = \"@kiko:gamecult.org\"\nroom = \"#minds:gamecult.org\"\nnew = true\nreply_to = 1\nsays = \"did it go out?\"\n" + )) + .unwrap(); + let pending = MouthReader::pending(&fixture).unwrap(); + let quote = pending.deliveries[0].reply_to.quote().unwrap(); + assert_eq!((quote.excerpt.as_ref().map(|words| words.chars().count()), quote.at_cap), (Some(REPLY_EXCERPT_CHARS), true)); +} + #[test] fn a_fixture_that_is_not_a_room_is_refused_naming_what_is_wrong() { let head = "her = \"@eureka:gamecult.org\"\nkind = \"chat\"\nnow = \"2026-11-20T15:00:00Z\"\nrooms = [\"#a:x\"]\n"; diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 25483c4..c90a397 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -115,12 +115,16 @@ pub(crate) struct RoomLine { pub reply: Option, } -/// The line a reply answers (map 16.20.8 (D)): who said it, and its words as the mouth quoted them, none when it quoted -/// none (redacted, edited, or not text). Every Matrix client shows it above the reply; so does every line rendered here. -#[derive(Clone, Debug, PartialEq, Eq)] +/// The line a reply answers (map 16.20.8 (D)): its event, who said it, and its words as the mouth quoted them, none when +/// it quoted none (redacted, edited, or not text); `at_cap` when the quote reached the mouth's cap and the line may run on. +/// Every Matrix client shows it above the reply; so does every line rendered here, unless the same page lists that line +/// whole, where the reply names it instead. +#[derive(Clone, Debug, Default, PartialEq, Eq)] pub(crate) struct Replied { + pub event: String, pub sender: String, pub text: Option, + pub at_cap: bool, } /// The room as the mouth showed it: new messages, and the recent tail. @@ -752,14 +756,44 @@ fn sender_name(sender: &str, inputs: &Inputs) -> String { /// A reply as every line renders it (map 16.20.8 (D), K20): the line it answers, above it, by who said it and in the words /// the mouth quoted (`> {other}: "…"`), and `, replying to {other}` after the speaker's name. Both empty for a line that -/// replies to nothing. -fn reply_parts(line: &RoomLine, inputs: &Inputs) -> (String, String) { +/// replies to nothing. When the page lists the answered line whole (`listed`), the reply names it by who and when +/// (`, replying to {other}'s line (15 min ago, shown here)`) and quotes it no second time, wherever the name is no longer +/// than the quote: a selection made on quoted lines then still fits. +fn reply_parts(line: &RoomLine, inputs: &Inputs, listed: &[&RoomLine]) -> (String, String) { let Some(replied) = &line.reply else { return (String::new(), String::new()); }; let other = sender_name(&replied.sender, inputs); - let words = replied.text.as_deref().map_or_else(|| "(no words shown)".to_owned(), spoken); - (format!("> {other}: {words}\n"), format!(", replying to {other}")) + let (above, replying) = (format!("> {other}: {}\n", excerpt(replied)), format!(", replying to {other}")); + let named = listed.iter().find(|shown| !replied.event.is_empty() && shown.event == replied.event).map(|shown| format!(", replying to {other}'s line ({}, shown here)", when(shown, inputs))); + match named { + Some(named) if named.len() <= above.len() + replying.len() => (String::new(), named), + _ => (above, replying), + } +} + +/// The words of an answered line as a reply shows them: escaped, or `(no words shown)`. A quote that reached the mouth's +/// cap ends on the last whole word before the cut and says so outside the quote marks (`…" (shortened)`), so no reader +/// takes the excerpt for the whole line and the mark is never quotable as the speaker's words. +fn excerpt(replied: &Replied) -> String { + match replied.text.as_deref() { + None => "(no words shown)".to_owned(), + Some(words) if replied.at_cap => { + let whole = words.rfind(char::is_whitespace).map(|end| words[..end].trim_end()).filter(|whole| !whole.is_empty()).unwrap_or(words); + format!("{} (shortened)", spoken(&format!("{whole}…"))) + } + Some(words) => spoken(words), + } +} + +/// When a listed line was said, as the page says it of its lines: a beat's in hours, a chat turn's new lines "just now", +/// its earlier ones in minutes. +fn when(line: &RoomLine, inputs: &Inputs) -> String { + match inputs.kind { + TurnKind::Beat => format!("{} h ago", hours(inputs.now, line.at_ms)), + _ if inputs.room.messages.iter().any(|message| std::ptr::eq(message, line)) => "just now".to_owned(), + _ => format!("{} min ago", minutes(inputs.now, line.at_ms)), + } } /// The words of a line she was shown: its own, and the words it quotes of another's line when it is a reply to someone @@ -797,37 +831,37 @@ impl Lines { } /// A section of room lines under `cap` bytes: its heading, a note counting the older lines that did not fit, then the -/// newest whole lines that did. Empty when there are no lines, or not even the heading fits. -fn newest_section(heading: &str, lines: &[String], cap: usize) -> String { +/// newest whole lines that did; and the indices of the lines it shows. Empty when there are no lines, or not even the +/// heading fits. +fn newest_section(heading: &str, lines: &[String], cap: usize) -> (String, Vec) { if lines.is_empty() { - return String::new(); + return (String::new(), Vec::new()); } // The note is at most this long: "(NNNNN earlier not shown)". let note_room = 32; - let mut kept: Vec<&String> = Vec::new(); + let mut kept: Vec = Vec::new(); let mut used = heading.len() + note_room; - for line in lines.iter().rev() { + for (at, line) in lines.iter().enumerate().rev() { if used + line.len() + 1 > cap { break; } used += line.len() + 1; - kept.push(line); + kept.push(at); } kept.reverse(); let dropped = lines.len() - kept.len(); let mut out = Lines::new(cap); if !out.push(heading) { - return String::new(); + return (String::new(), Vec::new()); } let mut shown = false; if dropped > 0 { shown |= out.push(&format!("({dropped} earlier not shown)")); } - for line in kept { - shown |= out.push(line); - } + kept.retain(|at| out.push(&lines[*at])); + shown |= !kept.is_empty(); // A heading over nothing says nothing. - if shown { out.out } else { String::new() } + if shown { (out.out, kept) } else { (String::new(), Vec::new()) } } /// Which messages to her a turn shows: whole messages, newest first, until the `addressed_bytes` ceiling, and a single @@ -893,23 +927,40 @@ fn said_to_her<'a>(to_her: &[&'a RoomLine], render: impl Fn(&RoomLine, &str) -> Addressed { shown, left_out, clipped } } +/// The lines each page lists whole, so a reply to one names it rather than quoting it again: what she heard (the +/// Persona's stream and the Interpreter's), and the stimulus, which reaches only the Interpreter, beside what she heard. +#[derive(Default)] +struct Listed<'a> { + stimulus: Vec<&'a RoomLine>, + heard: Vec<&'a RoomLine>, +} + /// A chat turn's stimulus, what she heard, the same bridged for the Persona (`Packet::bridged`), the overflow, and the /// earlier lines from others it shows her. `present` and `turned` are the packet's people present and who /// turned to her (`turned_to_her`): the arrival's who and where, which each bridge renders. +/// +/// Rendered twice: first with every reply quoted, which selects the lines each page lists whole; then with a reply to one +/// of those naming it instead. A name is never longer than the quote it replaces (`reply_parts`), so the second pass keeps +/// every line the first one did and each name points at a line its page shows. fn chat_stimulus<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, String)], turned: &[(String, String)]) -> (String, String, String, Overflow, Vec<&'a RoomLine>) { + let (_, listed) = chat_page(inputs, tuning, present, turned, &Listed::default()); + chat_page(inputs, tuning, present, turned, &listed).0 +} + +fn chat_page<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, String)], turned: &[(String, String)], listed: &Listed) -> ((String, String, String, Overflow, Vec<&'a RoomLine>), Listed<'a>) { let messages: Vec<&RoomLine> = inputs.room.messages.iter().filter(|line| line.sender != inputs.people.own_sender).collect(); if messages.is_empty() { - return ("Nothing new was said.".into(), String::new(), String::new(), Overflow::default(), Vec::new()); + return (("Nothing new was said.".into(), String::new(), String::new(), Overflow::default(), Vec::new()), Listed::default()); } let (to_her, others): (Vec<&RoomLine>, Vec<&RoomLine>) = messages.into_iter().partition(|line| line.to_her); let typed = |line: &RoomLine, body: &str| { - let (above, replying) = reply_parts(line, inputs); + let (above, replying) = reply_parts(line, inputs, &listed.stimulus); format!("{above}- {} in {}{replying}: {body}", name_of(line, inputs), line.room) }; // Heard lines are prose for the Persona: the speaker and the room from the mouth, then the escaped words; a reply with // the line it answers above it. let heard = |line: &RoomLine, body: &str| { - let (above, replying) = reply_parts(line, inputs); + let (above, replying) = reply_parts(line, inputs, &listed.heard); format!("{above}{}{replying}, in {}: {body}", name_of(line, inputs), line.room) }; let ceiling = tuning.select.addressed_bytes; @@ -930,7 +981,7 @@ fn chat_stimulus<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, St } let others_typed: Vec = others.iter().map(|line| typed(line, &spoken(&line.text))).collect(); let room_left = tuning.select.stimulus_bytes.saturating_sub(stimulus.len() + 1); - let mut also = newest_section("Also in the room:", &others_typed, room_left); + let (mut also, also_shown) = newest_section("Also in the room:", &others_typed, room_left); if also.is_empty() && !others_typed.is_empty() { // The messages to her took the room: the others are counted, never silently gone. also = format!("({} more in the room not shown)", others_typed.len()); @@ -945,7 +996,9 @@ fn chat_stimulus<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, St let mut heard_text = heard_to_her.join("\n"); let others_heard: Vec = others.iter().map(|line| heard(line, &spoken(&line.text))).collect(); let heard_left = tuning.select.heard_bytes.saturating_sub(heard_text.len() + 1); - let (others_kept, _) = newest_that_fit(&others_heard, heard_left); + let (others_kept, others_dropped) = newest_that_fit(&others_heard, heard_left); + let whole_to_her: Vec<&RoomLine> = addressed.shown.iter().filter(|(_, cut)| cut.is_none()).map(|(line, _)| *line).collect(); + let mut heard_listed: Vec<&RoomLine> = whole_to_her.iter().copied().chain(others[others_dropped..].iter().copied()).collect(); for line in &others_kept { if !heard_text.is_empty() { heard_text.push('\n'); @@ -956,7 +1009,7 @@ fn chat_stimulus<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, St // what `heard_bytes` leaves, then the new ones as above. The Persona's and the Interpreter's, never the Projector's // (I16.7). The earlier lines from others it shows her are words she heard: the echo check reads them beside the new // messages (`Packet::bodies`). - let earlier = earlier_lines(inputs); + let earlier = earlier_lines(inputs, &listed.heard); let mut earlier_shown = Vec::new(); let mut earlier_block = String::new(); if !earlier.is_empty() { @@ -969,6 +1022,7 @@ fn chat_stimulus<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, St earlier_block = format!("{heading}\n{}", kept.join("\n")); heard_text = format!("{earlier_block}\n{just}\n{heard_text}"); earlier_shown = earlier[dropped..].iter().filter(|(_, line)| line.sender != inputs.people.own_sender).map(|(_, line)| *line).collect(); + heard_listed.extend(earlier[dropped..].iter().map(|(_, line)| *line)); } } // The Persona's (map 16.21): the stream ends on the arrival, so what she reads next opens on it. Each person who @@ -1007,12 +1061,13 @@ fn chat_stimulus<'a>(inputs: &'a Inputs, tuning: &Tuning, present: &[(String, St } let bridged = blocks.join("\n\n"); let overflow = Overflow { stimulus: stimulus.len().saturating_sub(tuning.select.stimulus_bytes), heard: heard_text.len().saturating_sub(tuning.select.heard_bytes), said_to_her_not_shown: left_out, clipped_bytes: clipped }; - (stimulus, heard_text, bridged, overflow, earlier_shown) + let stimulus_listed = whole_to_her.into_iter().chain(also_shown.into_iter().map(|at| others[at])).chain(heard_listed.iter().copied()).collect(); + ((stimulus, heard_text, bridged, overflow, earlier_shown), Listed { stimulus: stimulus_listed, heard: heard_listed }) } /// The turn room's lines before this turn's new messages, oldest first, as the Persona reads them: who (her own lines by /// her name), how long ago, and the words verbatim; each with the line it renders. -fn earlier_lines<'a>(inputs: &'a Inputs) -> Vec<(String, &'a RoomLine)> { +fn earlier_lines<'a>(inputs: &'a Inputs, listed: &[&RoomLine]) -> Vec<(String, &'a RoomLine)> { let messages = &inputs.room.messages; let Some(newest) = messages.iter().map(|line| line.at_ms).max() else { return Vec::new(); @@ -1024,7 +1079,7 @@ fn earlier_lines<'a>(inputs: &'a Inputs) -> Vec<(String, &'a RoomLine)> { .filter(|line| !new(line) && line.at_ms <= newest) .map(|line| { let name = if line.sender == inputs.people.own_sender && !own.is_empty() { clip(&one_line(own), NAME_BYTES) } else { name_of(line, inputs) }; - let (above, replying) = reply_parts(line, inputs); + let (above, replying) = reply_parts(line, inputs, listed); (format!("{above}{name}{replying}, {} min ago: {}", minutes(inputs.now, line.at_ms), spoken(&line.text)), line) }) .collect() @@ -1053,23 +1108,33 @@ fn hours(now: DateTime, at_ms: u64) -> i64 { /// A beat: nothing addressed her; when she last heard from each person she is bound to (the relatedness cue, most /// recently heard first, in at most two thirds of the cap, a note counting any left out); then the newest lines of her -/// rooms in what is left. Every line is refused whole that would pass the cap. -fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String { +/// rooms in what is left. Every line is refused whole that would pass the cap. With the tail lines it shows whole. +fn beat_stimulus<'a>(inputs: &'a Inputs, tuning: &Tuning, listed: &[&RoomLine]) -> (String, Vec<&'a RoomLine>) { let cap = tuning.select.stimulus_bytes; let mut out = Lines { out: beat_contacts(inputs, tuning), cap }; let her = forms(inputs.state); - let lines: Vec = beat_tail(inputs, tuning) + let tail = beat_tail(inputs, tuning); + let words = |line: &RoomLine| clip(&line.text, tuning.select.item_bytes / 2); + let lines: Vec = tail .iter() .map(|line| { - let (above, replying) = reply_parts(line, inputs); - format!("{above}- {}{replying} in {}, {} h ago: {}", name_of(line, inputs), line.room, hours(inputs.now, line.at_ms), spoken(&clip(&line.text, tuning.select.item_bytes / 2))) + let (above, replying) = reply_parts(line, inputs, listed); + format!("{above}- {}{replying} in {}, {} h ago: {}", name_of(line, inputs), line.room, hours(inputs.now, line.at_ms), spoken(&words(line))) }) .collect(); - let section = newest_section(&format!("Lately in {} rooms:", her.poss), &lines, cap.saturating_sub(out.out.len() + 2)); - if !section.is_empty() && out.push("") { - out.push(§ion); - } - out.out + let (section, shown) = newest_section(&format!("Lately in {} rooms:", her.poss), &lines, cap.saturating_sub(out.out.len() + 2)); + let whole = if !section.is_empty() && out.push("") && out.push(§ion) { shown.into_iter().map(|at| tail[at]).filter(|line| words(line) == line.text).collect() } else { Vec::new() }; + (out.out, whole) +} + +/// A beat's stimulus and what she heard, rendered twice as a chat turn's are (`chat_stimulus`): first with every reply +/// quoted, then with a reply to a line its page lists whole naming it. The stimulus reaches only the Interpreter, which +/// reads what she heard beside it. +fn beat_pages(inputs: &Inputs, tuning: &Tuning) -> (String, String) { + let (_, heard_listed) = beat_heard(inputs, tuning, &[]); + let (_, stimulus_listed) = beat_stimulus(inputs, tuning, &heard_listed); + let stimulus_listed: Vec<&RoomLine> = stimulus_listed.into_iter().chain(heard_listed.iter().copied()).collect(); + (beat_stimulus(inputs, tuning, &stimulus_listed).0, beat_heard(inputs, tuning, &heard_listed).0) } /// What reaches a beat's Projector (map 16.19.2): that nothing addressed her, and when she last heard from each person she @@ -1106,16 +1171,18 @@ fn beat_contacts(inputs: &Inputs, tuning: &Tuning) -> String { } /// A beat's recent room lines as the Persona reads them, after the stream: the speaker, the room and when, then the words -/// verbatim, newest kept within `heard_bytes`. -fn beat_heard(inputs: &Inputs, tuning: &Tuning) -> String { - let lines: Vec = beat_tail(inputs, tuning) +/// verbatim, newest kept within `heard_bytes`; with the lines it shows. +fn beat_heard<'a>(inputs: &'a Inputs, tuning: &Tuning, listed: &[&RoomLine]) -> (String, Vec<&'a RoomLine>) { + let tail = beat_tail(inputs, tuning); + let lines: Vec = tail .iter() .map(|line| { - let (above, replying) = reply_parts(line, inputs); + let (above, replying) = reply_parts(line, inputs, listed); format!("{above}{}{replying}, in {}, {} h ago: {}", name_of(line, inputs), line.room, hours(inputs.now, line.at_ms), spoken(&line.text)) }) .collect(); - newest_that_fit(&lines, tuning.select.heard_bytes).0.join("\n") + let (kept, dropped) = newest_that_fit(&lines, tuning.select.heard_bytes); + (kept.join("\n"), tail[dropped..].to_vec()) } /// Where each person who turned to her this turn did so (map 16.21): the people whose message to her is new on a chat @@ -1146,7 +1213,7 @@ fn beat_tail<'a>(inputs: &'a Inputs, tuning: &Tuning) -> Vec<&'a RoomLine> { fn reflection_stimulus(inputs: &Inputs, tuning: &Tuning) -> String { let lines: Vec = items(inputs.state, &["thoughtMemory", "shortTerm"]).iter().filter(|item| live(item)).map(|item| format!("- {}", clip(&one_line(text(item, &["summary"])), tuning.select.item_bytes))).collect(); let subj = forms(inputs.state).subj; - let section = newest_section(&format!("Since {subj} last took stock:"), &lines, tuning.select.stimulus_bytes); + let (section, _) = newest_section(&format!("Since {subj} last took stock:"), &lines, tuning.select.stimulus_bytes); if section.is_empty() { clip(&format!("Since {subj} last took stock: nothing new."), tuning.select.stimulus_bytes) } else { section } } @@ -1736,7 +1803,10 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { let turned = turned_to_her(inputs); let (stimulus, heard, bridged, overflow, earlier_shown) = match inputs.kind { TurnKind::Chat => chat_stimulus(inputs, tuning, &present, &turned), - TurnKind::Beat => (beat_stimulus(inputs, tuning), beat_heard(inputs, tuning), String::new(), Overflow::default(), Vec::new()), + TurnKind::Beat => { + let (stimulus, heard) = beat_pages(inputs, tuning); + (stimulus, heard, String::new(), Overflow::default(), Vec::new()) + } TurnKind::FollowUp => (clip(&format!("{} just found: {}", forms(inputs.state).cap_subj, inputs.observation.unwrap_or("nothing")), tuning.select.stimulus_bytes), String::new(), String::new(), Overflow::default(), Vec::new()), TurnKind::Reflection => (reflection_stimulus(inputs, tuning), String::new(), String::new(), Overflow::default(), Vec::new()), }; diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index 67649d1..28f6e8e 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -2242,7 +2242,7 @@ fn k19_the_conversation_on_screen_reaches_the_persona_and_the_interpreter_and_ne #[test] fn k20_a_reply_shows_the_line_it_answers_above_it_in_another_minds_packet() { const META: &str = "SEALION back at six, the render can wait."; - let replied = Some(Replied { sender: OPERATOR.into(), text: Some(META.into()) }); + let replied = Some(Replied { sender: OPERATOR.into(), text: Some(META.into()), ..Replied::default() }); let reply = |minutes, new| RoomLine { event: "$r".into(), reply: replied.clone(), ..message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", "This is what she said before she left.", minutes, new) }; let quote = format!("> Meta, the operator: {}", serde_json::to_string(META).unwrap()); // Just now, and in the Interpreter's stimulus. @@ -2257,11 +2257,66 @@ fn k20_a_reply_shows_the_line_it_answers_above_it_in_another_minds_packet() { let heard = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1).heard; assert!(heard.starts_with(&format!("Earlier in #swarm:gamecult.org:\n{quote}\nLibby, replying to Meta, the operator, 5 min ago: ")), "{heard}"); // A reply whose words the mouth did not quote says so; a line that replies to nothing renders as it did. - let unquoted = Room { messages: vec![RoomLine { reply: Some(Replied { sender: OPERATOR.into(), text: None }), ..reply(1, true) }], ..Room::default() }; + let unquoted = Room { messages: vec![RoomLine { reply: Some(Replied { sender: OPERATOR.into(), text: None, ..Replied::default() }), ..reply(1, true) }], ..Room::default() }; assert!(packet_of(TurnKind::Chat, &state(), &unquoted, &History::default(), 1).heard.starts_with("> Meta, the operator: (no words shown)\nLibby, replying to Meta, the operator, in ")); assert!(!packet_of(TurnKind::Chat, &state(), &chat_room(), &History::default(), 1).heard.contains("replying")); } +/// Soul on K20, plan E: a quote cut at the mouth's cap read to her as her own line cut short, and she said so. A quote that +/// reached the cap ends on the last whole word and says, outside the quote marks, that it is shortened, on every page; the +/// echo check still reads every word the mouth quoted, the cut word too. +#[test] +fn k20_a_quote_cut_at_the_cap_ends_on_a_whole_word_and_says_it_is_shortened() { + let line = format!("{}takeover, and the rest of the edited line", "word ".repeat(47)); + let excerpt: String = line.chars().take(crate::chat_client::REPLY_EXCERPT_CHARS).collect(); + assert!(excerpt.ends_with(" takeo"), "the cap falls mid-word"); + let shortened = format!("{} (shortened)", serde_json::to_string(&format!("{}\u{2026}", "word ".repeat(47).trim_end())).unwrap()); + for (sender, name) in [(OWN, "Eureka"), (OPERATOR, "Meta, the operator")] { + let replied = Replied { event: "$long".into(), sender: sender.into(), text: Some(excerpt.clone()), at_cap: true }; + let reply = RoomLine { reply: Some(replied), ..message("#minds:gamecult.org", "@kiko:gamecult.org", "Kiko", "did it go out?", 1, true) }; + let room = Room { messages: vec![reply], here: Some("#minds:gamecult.org".into()), ..Room::default() }; + let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1); + for page in [&packet.heard, &packet.stimulus, &packet.bridged] { + assert!(page.contains(&format!("> {name}: {shortened}\n")) && !page.contains("takeo"), "{page}"); + } + if sender == OPERATOR { + assert!(packet.bodies.contains(&excerpt), "the echo check reads the whole quote: {:?}", packet.bodies); + } + } + // A quote short of the cap is the whole line, and says nothing more. + let whole = Replied { event: "$short".into(), sender: OPERATOR.into(), text: Some("word takeo".into()), at_cap: false }; + let room = Room { messages: vec![RoomLine { reply: Some(whole), ..message("#minds:gamecult.org", "@kiko:gamecult.org", "Kiko", "did it go out?", 1, true) }], ..Room::default() }; + assert!(packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1).heard.starts_with("> Meta, the operator: \"word takeo\"\nKiko, replying to Meta, the operator, in ")); +} + +/// Soul on K20: Kiko read Meta's line three times. A reply to a line its page lists whole names that line by who and when +/// and quotes it no second time; the stimulus, which reaches only the Interpreter beside what she heard, names a line either +/// lists. The echo check still reads the words the mouth quoted. +#[test] +fn k20_a_reply_to_a_line_listed_whole_names_it_and_quotes_it_no_second_time() { + const MINE: &str = "Sure, Kiko. I'll paste the door-fix diff here as text. MARMOSET"; + const META: &str = "Heimdall, are we still on for the notes tomorrow morning? OSPREY"; + let room_id = "#minds:gamecult.org"; + let mine = RoomLine { event: "$mine".into(), ..message(room_id, OWN, "Eureka", MINE, 15, false) }; + let meta = RoomLine { event: "$meta".into(), ..message(room_id, OPERATOR, "Meta", META, 2, false) }; + let to = |line: &RoomLine| Some(Replied { event: line.event.clone(), sender: line.sender.clone(), text: Some(line.text.clone()), at_cap: false }); + let kiko = RoomLine { event: "$kiko".into(), reply: to(&mine), ..message(room_id, "@kiko:gamecult.org", "Kiko", "did the file go out?", 1, true) }; + let heimdall = RoomLine { event: "$heimdall".into(), reply: to(&meta), ..message(room_id, "@heimdall:gamecult.org", "Heimdall", "I can't confirm that.", 1, false) }; + let room = Room { messages: vec![meta.clone(), kiko, heimdall], tail: vec![mine], here: Some(room_id.into()), ..Room::default() }; + let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1); + for page in [&packet.heard, &packet.bridged] { + assert_eq!((page.matches("MARMOSET").count(), page.matches("OSPREY").count()), (1, 1), "{page}"); + assert!(!page.contains("> "), "{page}"); + assert!(page.contains("Kiko, replying to Eureka's line (15 min ago, shown here), in #minds:gamecult.org: \"did the file go out?\""), "{page}"); + assert!(page.contains(", replying to Meta, the operator's line (just now, shown here), in #minds:gamecult.org: \"I can't confirm that.\""), "{page}"); + } + let stimulus = &packet.stimulus; + assert_eq!((stimulus.matches("MARMOSET").count(), stimulus.matches("OSPREY").count(), stimulus.contains("> ")), (0, 1, false), "{stimulus}"); + assert!(stimulus.contains("- Kiko in #minds:gamecult.org, replying to Eureka's line (15 min ago, shown here): "), "{stimulus}"); + assert!(stimulus.contains(", replying to Meta, the operator's line (just now, shown here): "), "{stimulus}"); + assert!(packet.bodies.iter().any(|body| body == META), "{:?}", packet.bodies); +} + /// Q-E unanswered, option A: an earlier line someone else wrote, said verbatim, is an echo, bare or behind a lead-in and /// with words of her own after it (Heimdall's live draft at 0cfc386, Soul's K19 pass). #[test] diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 0b5bef2..ca3c168 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -94,7 +94,7 @@ mind_body::chat_client: struct ChatSendReceipt # [derive (Clone , Debug , Partia mind_body::chat_client: struct ChatSendRequest # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, persona: String, room_alias: String, text: String, basis: Option < SendBasis >] mind_body::chat_client: struct ContextLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[sender: String, text: String, at_unix_ms: u64] mind_body::chat_client: struct MouthRefused # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub-fields[0: Refusal] -mind_body::chat_client: struct ReplyTo # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[event_id: String, sender: String, excerpt: Option < String >] +mind_body::chat_client: struct ReplyTo # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[event_id: String, sender: String, excerpt: Option < String >, at_cap: bool] mind_body::chat_client: struct SendBasis # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[seen_event_id: Option < String >, since_unix_ms: u64] mind_body::chat_client: struct TailLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[room: String, event_id: String, at_unix_ms: u64, sender: String, form: Form, basis: Option < Basis >, body: String, reply_to: ReplyLink] mind_body::chat_image: impl Skip