Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Smart Results: API, selectors and stored blocks (#227)

Oleksandr Ivanchenko56831f5096c2
diff --git a/docs/smart-results.md b/docs/smart-results.md
new file mode 100644
index 00000000..98437df4
--- /dev/null
+++ b/docs/smart-results.md
@@ -0,0 +1,143 @@
+# Smart Results (0.6.5)
+
+A bot's final reply can carry one typed block, `results`, that the chat draws in place of a table
+or a list in the reply: a comparison card for a table, a checklist for numbered steps. The reply's
+text is never changed. When there is no block, or the chat can't draw it, the reply shows its
+markdown as it always has.
+
+Smart Results always runs. There is no setting. The release fallback is one server constant,
+`smart_results::ENABLED_TYPES` (`src/server/smart_results/mod.rs`): when a type is taken out of
+it, kwant stops storing blocks of that type and stops serving the ones already stored.
+
+Code: `src/server/smart_results/` (contract types, selectors, checks) and
+`src/db/smart_results.rs` (storage and serving).
+
+## When a reply gets a block
+
+- **Which messages qualify:** every bot reply, meaning `sender_role` is `"kwant"` and there is no
+ `meta.kind`, or the kind is `delegation_result` (a teammate's hand-off result: its reply, drawn
+ as markdown inside the hand-off card). Other cards and kwant's own posts have a `meta.kind` and
+ never get a block. A reply's own meta (`ran_on`, usage, routing, `decide_first`) doesn't stop it
+ from qualifying.
+- **When it is worked out:** once, when the message is saved (`insert_message_on`), never while
+ the reply is streaming. The selectors are deterministic: no model calls and no network. A reply
+ longer than 128 KB stays text.
+- **How the block is chosen:** the candidates are offered in priority order, every comparison
+ table first, then every steps list, each in the order it appears in the text. The first candidate
+ whose type is in `ENABLED_TYPES` and that passes the checks is stored, and only that one: a
+ message has at most one block.
+- **What it never costs:** the reply. If a selector panics, a block fails its checks, or the write
+ fails, kwant logs it and saves the message exactly as before.
+- **Edits:** when a reply's text is replaced (`set_message_text`), its block is deleted, because the
+ block was copied from the old text.
+
+## Storage and API
+
+- **Table:** `message_results(message_id PK → messages.id ON DELETE CASCADE, version, payload, created_at)`.
+ The migration is additive (`CREATE TABLE IF NOT EXISTS`). The payload is JSON of at most 64 KB.
+- **Field:** every message object has a `results` field. Its value is the block set, or `null`
+ when there is none. Messages from before 0.6.5 have no row, so they return `null`.
+- **Where `results` is set:**
+ - the message returned on insert, and so the `MessageAdded` broadcast for that message;
+ - `GET /api/channels/:id/messages`, which covers channels and direct chats, including the
+ `around` and `before` pages;
+ - `GET /api/threads/:id/messages`;
+ - the message re-broadcast after `POST /api/messages/:id/decisions/:index/change`.
+
+ Other endpoints that return messages leave it `null`. The chat reloads the list at
+ `turn_ended`, and that reload is what delivers a final reply's block.
+- **Checks when serving:** a stored block is checked again every time it is read. An unknown
+ `version`, a type this build doesn't know or no longer enables, or a payload that fails today's
+ checks is served as `null`.
+
+## Contract (payload version 1)
+
+```ts
+type ResultSet = { version: 1, blocks: [Block] } // exactly one block when there is a row
+type Source = { kind: "markdown_table" | "markdown_list", index: number }
+type Provenance = { kind: "reply_text" }
+
+type Comparison = {
+ id: "b0", type: "comparison", source: Source /* markdown_table */, provenance: Provenance,
+ columns: { key: "c0".., label: string, numeric: boolean, unit: string | null }[], // 2–8
+ rows: { id: "r0".., cells: string[] }[], // 3–50
+ highlight_row: string | null, highlight_reason: string | null,
+}
+type Steps = {
+ id: "b0", type: "steps", source: Source /* markdown_list */, provenance: Provenance,
+ items: { id: "s0".., text: string }[], // 3–15
+}
+```
+
+These are the v1 shapes. Plan v2 (§A.3) adds fields to them: `title`, column `role`, and the
+steps `variant`, `done`, `when` and `owner`. The client reads a missing field with its v1 meaning
+(`title` null, role `label` for the first column and `value` for the rest, variant `steps`).
+`smart-results-more` writes these fields.
+
+### Values are copied, never made up
+
+- Every label, unit, cell and step is a substring of the reply. The store-time check rejects any
+ value that isn't.
+- Cells are the raw markdown between the pipes, trimmed. Emphasis, code spans, links and escaped
+ pipes (`\|`) are kept as written; the chat renders them.
+- Limits: a header or cell is at most 200 characters, a step at most 300, a unit at most 10.
+ Nothing may contain HTML (`<` followed by a letter, `/`, `!` or `?`).
+- **`numeric`:** at least 80% of the column's cells are a number with the same affix. The affix
+ is a prefix of up to 4 letters or currency signs (`EUR 12`, `$12`), or a suffix of up to 10
+ (`12 GB`, `-4%`, `4.5/5`). That shared affix is the `unit`; no affix means `unit: null`.
+ Numbers may use `,` or `.` thousands grouping. Blocks of this version carry no parsed number
+ values.
+- **`highlight_row`:** set only when the prose outside the table names exactly one row's
+ first-column label in a recommending sentence. A recommending sentence contains "recommend…",
+ "best", "pick", "choose", "winner" or "go with", is not a question, and has no hedge or negative
+ word ("not", "but", "if", "unless", "instead", "depends", …).
+ - A name only counts as a whole name: `A` is not `A+`, `Pro` inside `Pro Max` names `Pro Max`,
+ `C` is not `C++`, `Node` is not `Node.js`.
+ - Labels shorter than 4 characters match case for case. A lone `A` or `I` opening a sentence is
+ the word.
+ - When the pick is unclear, no row is highlighted. That includes very long recommending prose
+ (over 8,000 characters) and labels found over 1,000 times. `highlight_reason` is always
+ "named as the pick in this reply".
+
+## Selectors
+
+**Comparison:**
+- the table is a clean top-level GFM pipe table;
+- it has 2–8 columns and 3–50 rows, every row with as many cells as the header;
+- no header or first cell is empty, and first cells don't repeat (ignoring case and emphasis).
+
+**Steps:**
+- the list is a clean top-level ordered list that starts at 1, with 3–15 single-line items;
+- no item is a task (`[ ]`, `[x]`) and none contains HTML;
+- either every item starts with "Step N", or the list is introduced as steps: the line just above
+ it, or the nearest heading above it, says "step(s)", "plan", "checklist", "todo", "how to" or
+ "to do";
+- the introduction doesn't call it reasons, tips, examples, ideas, options, pros, cons, prices or
+ tiers.
+
+## How `source.index` is counted
+
+`index` must name the same table or list the chat renders with react-markdown and remark-gfm.
+
+- **Tables:** every GFM table in document order, from 0. A table inside fenced or indented code,
+ or in raw HTML, is not a table and isn't counted.
+- **Lists:** every ordered list in pre-order, nested ones included, from 0; bullet lists aren't
+ counted. An ordered task list counts as an ordered list, but it isn't offered as steps in this
+ version.
+- **Uncertainty:** the server reads markdown line by line. Some constructs could make its count
+ differ from the chat's: a table or numbered list inside a quote or a bullet item, a list nested
+ in a list, raw HTML, tabs, or a table run straight into a paragraph. From the first such
+ construct on, kwant offers no block for that kind, and the reply stays text. Candidates before
+ that point are still offered.
+
+The client checks every block again: the labels, the row and item counts, and the cells
+(letters and digits only). On any mismatch it shows the markdown.
+
+## Adding a block type
+
+1. Add a `Block` variant and its `kind()` arm (`mod.rs`).
+2. Add a selector to `candidates()`, in the priority order of plan §A.2.
+3. Add its checks to `validate()`.
+4. Add the type to `ENABLED_TYPES`.
+5. Add tests in `selector_tests.rs`. Each test must cover the cases where the selector abstains,
+ not only the ones where it fires.
diff --git a/src/db/hires.rs b/src/db/hires.rs
index 9457e663..5f59678f 100644
--- a/src/db/hires.rs
+++ b/src/db/hires.rs
@@ -372,6 +372,8 @@ impl Database {
/// Replaces a card message's text, so bots reading the history see the decision too.
pub async fn set_message_text(&self, id: &str, text: &str) -> Result<(), DbError> {
sqlx::query("UPDATE messages SET text = ? WHERE id = ?").bind(text).bind(id).execute(&self.pool).await?;
+ // A block copied from the old text no longer matches it
+ sqlx::query("DELETE FROM message_results WHERE message_id = ?").bind(id).execute(&self.pool).await?;
Ok(())
}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 7b361d5e..2a6cf8e2 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -36,6 +36,7 @@ pub mod foundry;
pub mod automation;
pub mod truth_ledger;
pub mod routing;
+pub mod smart_results;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -176,6 +177,7 @@ impl Database {
db.migrate_checkpoints().await?;
db.migrate_autofix().await?;
db.migrate_routing().await?;
+ db.migrate_smart_results().await?;
if spaces {
let migration = db.migrate_spaces(data_dir, fresh).await?;
db.require_spaces_schema(&migration).await?;
@@ -1118,10 +1120,12 @@ pub(crate) async fn insert_message_on(
.execute(&mut *conn)
.await?;
- Ok(sqlx::query_as::<_, Message>("SELECT * FROM messages WHERE id = ?")
+ let mut msg = sqlx::query_as::<_, Message>("SELECT * FROM messages WHERE id = ?")
.bind(&id)
.fetch_one(&mut *conn)
- .await?)
+ .await?;
+ msg.results = smart_results::store_on(conn, input, extra, &id).await;
+ Ok(msg)
}
/// Renames chat `chat`, now called `chat_name` (`team-<name>`), to `archived-team-<name>`, or
diff --git a/src/db/models.rs b/src/db/models.rs
index f5e07287..060201c0 100644
--- a/src/db/models.rs
+++ b/src/db/models.rs
@@ -122,6 +122,11 @@ pub struct Message {
#[serde(default)]
#[sqlx(default)]
pub meta: Option<String>,
+ /// Smart Results: the reply's block set (`crate::server::smart_results::ResultSet`), or
+ /// `null`. Stored in `message_results`, not in this row.
+ #[serde(default)]
+ #[sqlx(skip)]
+ pub results: Option<serde_json::Value>,
}
/// Where a message goes besides [`NewMessage`]'s channel or direct chat.
diff --git a/src/db/smart_results.rs b/src/db/smart_results.rs
new file mode 100644
index 00000000..c5167ddb
--- /dev/null
+++ b/src/db/smart_results.rs
@@ -0,0 +1,253 @@
+//! `message_results`: the Smart Results block set of a bot reply, beside the message and never in
+//! its text or `meta` (see `crate::server::smart_results`).
+
+use std::collections::HashMap;
+
+use serde_json::Value;
+
+use super::models::{Message, MessageExtra, NewMessage};
+use super::{Database, DbError};
+use crate::server::smart_results::{self as sr, ResultSet};
+
+impl Database {
+ /// Additive: one row per message that has a block set; deleting the message deletes it.
+ pub(super) async fn migrate_smart_results(&self) -> Result<(), DbError> {
+ sqlx::query(
+ r#"
+ CREATE TABLE IF NOT EXISTS message_results (
+ message_id TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
+ version INTEGER NOT NULL,
+ payload TEXT NOT NULL,
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
+ )
+ "#,
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// Sets `results` on the bot replies in `messages` that have a stored block set this build
+ /// still serves. Never fails: a read error leaves them `None`, and the chat shows markdown.
+ pub async fn attach_results(&self, messages: &mut [Message]) {
+ let ids: Vec<&str> = messages.iter().filter(|m| m.sender_role == "kwant").map(|m| m.id.as_str()).collect();
+ if ids.is_empty() {
+ return;
+ }
+ let ids = serde_json::to_string(&ids).unwrap_or_default();
+ let rows: Vec<(String, i64, String)> = match sqlx::query_as(
+ "SELECT message_id, version, payload FROM message_results WHERE message_id IN (SELECT value FROM json_each(?))",
+ )
+ .bind(ids)
+ .fetch_all(&self.pool)
+ .await
+ {
+ Ok(rows) => rows,
+ Err(e) => {
+ tracing::warn!("smart results: couldn't read stored blocks: {e}");
+ return;
+ }
+ };
+ let found: HashMap<String, Value> =
+ rows.into_iter().filter_map(|(id, version, payload)| read(version, &payload).map(|v| (id, v))).collect();
+ for m in messages.iter_mut() {
+ if let Some(v) = found.get(&m.id) {
+ m.results = Some(v.clone());
+ }
+ }
+ }
+}
+
+/// A stored payload this build can serve, or `None` (an unknown version, a type no longer
+/// enabled, or a block that fails today's checks).
+fn read(version: i64, payload: &str) -> Option<Value> {
+ if version != i64::from(sr::VERSION) {
+ return None;
+ }
+ let set: ResultSet = serde_json::from_str(payload).ok()?;
+ sr::validate(&set, None).ok()?;
+ serde_json::to_value(&set).ok()
+}
+
+/// `meta.kind`s whose text is still a bot's own reply: a teammate's hand-off result, which the
+/// chat draws as markdown inside its card.
+const REPLY_KINDS: &[&str] = &["delegation_result"];
+
+/// Computes and stores the block set for a message just inserted on `conn` as `id`, and returns
+/// it for the message object. Only bot replies qualify: `sender_role` "kwant" and no `meta.kind`
+/// other than [`REPLY_KINDS`] (cards and kwnt's own posts have one; a reply's `ran_on`, `usage`
+/// or `routing` meta doesn't count). Never fails: a failed write is logged and the message stays
+/// as it was.
+pub(super) async fn store_on(
+ conn: &mut sqlx::SqliteConnection,
+ input: &NewMessage,
+ extra: &MessageExtra,
+ id: &str,
+) -> Option<Value> {
+ let kind = extra.meta.as_ref().and_then(|m| m.get("kind"));
+ let card = kind.is_some_and(|k| !k.as_str().is_some_and(|k| REPLY_KINDS.contains(&k)));
+ if input.sender_role != "kwant" || card {
+ return None;
+ }
+ let set = sr::compute(&input.text)?;
+ let value = serde_json::to_value(&set).ok()?;
+ let saved = sqlx::query("INSERT OR REPLACE INTO message_results (message_id, version, payload) VALUES (?, ?, ?)")
+ .bind(id)
+ .bind(i64::from(set.version))
+ .bind(value.to_string())
+ .execute(&mut *conn)
+ .await;
+ match saved {
+ Ok(_) => Some(value),
+ Err(e) => {
+ tracing::warn!("smart results: couldn't store the block for message {id}: {e}");
+ None
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ const TABLE: &str = "Here are the plans.\n\n| Plan | Price | Seats |\n|---|---|---|\n| Basic | EUR 12 | 1 |\n| Team | EUR 18 | 5 |\n| Business | EUR 26 | 20 |\n\nI recommend Team.\n";
+
+ fn message(role: &str, text: &str) -> NewMessage {
+ NewMessage {
+ channel_id: None,
+ direct_kwant_id: Some("k1".into()),
+ sender_role: role.into(),
+ sender_id: if role == "kwant" { "k1".into() } else { "user".into() },
+ text: text.into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ }
+ }
+
+ fn with_meta(meta: Value) -> MessageExtra {
+ MessageExtra { meta: Some(meta), ..Default::default() }
+ }
+
+ async fn stored(db: &Database, id: &str) -> Option<(i64, String)> {
+ sqlx::query_as("SELECT version, payload FROM message_results WHERE message_id = ?")
+ .bind(id)
+ .fetch_optional(&db.pool)
+ .await
+ .unwrap()
+ }
+
+ async fn served(db: &Database, id: &str) -> Option<Value> {
+ let mut m = vec![db.get_message(id).await.unwrap().unwrap()];
+ db.attach_results(&mut m).await;
+ m.remove(0).results
+ }
+
+ #[tokio::test]
+ async fn a_bot_reply_with_a_table_is_stored_and_served() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let m = db.insert_message(&message("kwant", TABLE)).await.unwrap();
+ let results = m.results.clone().expect("the saved message carries its block");
+ assert_eq!(results["version"], 1);
+ let block = &results["blocks"][0];
+ assert_eq!(block["type"], "comparison");
+ assert_eq!(block["rows"][1]["cells"], json!(["Team", "EUR 18", "5"]));
+ assert_eq!(block["highlight_row"], "r1");
+ assert_eq!(stored(&db, &m.id).await.map(|r| r.0), Some(1));
+ assert_eq!(served(&db, &m.id).await, Some(results));
+ assert_eq!(m.text, TABLE, "the text is never changed");
+ assert_eq!(serde_json::to_value(&m).unwrap()["results"]["blocks"][0]["type"], "comparison");
+ }
+
+ #[tokio::test]
+ async fn only_ordinary_bot_replies_qualify() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let person = db.insert_message(&message("user", TABLE)).await.unwrap();
+ let card = db.insert_message_with(&message("kwant", TABLE), &with_meta(json!({"kind": "routing_note"}))).await.unwrap();
+ let plain = db.insert_message(&message("kwant", "Done: the build is green.")).await.unwrap();
+ for m in [&person, &card, &plain] {
+ assert_eq!(m.results, None, "{}", m.text);
+ assert_eq!(stored(&db, &m.id).await, None, "{}", m.text);
+ assert_eq!(served(&db, &m.id).await, None, "{}", m.text);
+ assert_eq!(serde_json::to_value(m).unwrap()["results"], Value::Null, "results is always there");
+ }
+ // A reply's own meta (where it ran, what it used) doesn't make it a card
+ let ran = db.insert_message_with(&message("kwant", TABLE), &with_meta(json!({"ran_on": "vm"}))).await.unwrap();
+ assert!(ran.results.is_some());
+ // A teammate's hand-off result is its reply; kwnt's note that the work stopped is not
+ let handed = db.insert_message_with(&message("kwant", TABLE), &with_meta(json!({"kind": "delegation_result"}))).await.unwrap();
+ assert!(handed.results.is_some());
+ let stopped = db.insert_message_with(&message("system", TABLE), &with_meta(json!({"kind": "delegation_result"}))).await.unwrap();
+ assert_eq!(stopped.results, None);
+ let odd = db.insert_message_with(&message("kwant", TABLE), &with_meta(json!({"kind": ["delegation_result"]}))).await.unwrap();
+ assert_eq!(odd.results, None, "a kind that isn't a string is a card");
+ }
+
+ #[tokio::test]
+ async fn an_edited_or_deleted_reply_loses_its_block() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let edited = db.insert_message(&message("kwant", TABLE)).await.unwrap();
+ db.set_message_text(&edited.id, "The plans changed; ask me again.").await.unwrap();
+ assert_eq!(stored(&db, &edited.id).await, None);
+ assert_eq!(served(&db, &edited.id).await, None);
+ let deleted = db.insert_message(&message("kwant", TABLE)).await.unwrap();
+ sqlx::query("DELETE FROM messages WHERE id = ?").bind(&deleted.id).execute(&db.pool).await.unwrap();
+ assert_eq!(stored(&db, &deleted.id).await, None);
+ }
+
+ #[tokio::test]
+ async fn a_stored_block_this_build_cannot_serve_stays_hidden() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let m = db.insert_message(&message("kwant", TABLE)).await.unwrap();
+ let (_, good) = stored(&db, &m.id).await.unwrap();
+ let edit = |change: &dyn Fn(&mut Value)| {
+ let mut v: Value = serde_json::from_str(&good).unwrap();
+ change(&mut v);
+ v.to_string()
+ };
+ let cases = [
+ (2, good.clone()),
+ (1, "{not json".to_string()),
+ (1, edit(&|v| v["blocks"][0]["type"] = json!("chart"))),
+ (1, edit(&|v| v["blocks"][0]["highlight_row"] = json!("r9"))),
+ (1, edit(&|v| v["blocks"][0]["rows"][0]["cells"][0] = json!("<img src=x onerror=alert(1)>"))),
+ (1, edit(&|v| v["blocks"] = json!([]))),
+ ];
+ for (version, payload) in cases {
+ sqlx::query("UPDATE message_results SET version = ?, payload = ? WHERE message_id = ?")
+ .bind(version)
+ .bind(&payload)
+ .bind(&m.id)
+ .execute(&db.pool)
+ .await
+ .unwrap();
+ assert_eq!(served(&db, &m.id).await, None, "{version} {payload}");
+ }
+ }
+
+ #[tokio::test]
+ async fn blocks_are_attached_to_bot_replies_only() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let bot = db.insert_message(&message("kwant", TABLE)).await.unwrap();
+ let person = db.insert_message(&message("user", "Which plan?")).await.unwrap();
+ // Even a row stored under a person's message is never served
+ sqlx::query(
+ "INSERT INTO message_results (message_id, version, payload) SELECT ?, version, payload FROM message_results WHERE message_id = ?",
+ )
+ .bind(&person.id)
+ .bind(&bot.id)
+ .execute(&db.pool)
+ .await
+ .unwrap();
+ let mut list = db.list_messages("k1", 10).await.unwrap();
+ db.attach_results(&mut list).await;
+ let got: Vec<(&str, bool)> = list.iter().map(|m| (m.sender_role.as_str(), m.results.is_some())).collect();
+ assert_eq!(got, [("kwant", true), ("user", false)]);
+ }
+}
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index c1dbbab0..b0426b47 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -1765,6 +1765,7 @@ mod tests {
created_at: None,
thread_id: None,
meta: None,
+ results: None,
}
}
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index 2adbf9d4..c85e52ed 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -1635,6 +1635,7 @@ mod tests {
created_at: None,
thread_id: None,
meta: None,
+ results: None,
},
Message {
id: "m2".into(),
@@ -1649,6 +1650,7 @@ mod tests {
created_at: None,
thread_id: None,
meta: None,
+ results: None,
},
Message {
id: "m3".into(),
@@ -1663,6 +1665,7 @@ mod tests {
created_at: None,
thread_id: None,
meta: None,
+ results: None,
},
],
model_override: None,
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index 232b4a4b..b11b6472 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -767,6 +767,7 @@ pub(crate) mod tests {
created_at: None,
thread_id: None,
meta: None,
+ results: None,
}
}
diff --git a/src/router/sticky.rs b/src/router/sticky.rs
index f2743eb5..3fac5157 100644
--- a/src/router/sticky.rs
+++ b/src/router/sticky.rs
@@ -199,6 +199,7 @@ mod tests {
created_at: Some(t(at)),
thread_id: None,
meta: None,
+ results: None,
}
}
diff --git a/src/server/decide.rs b/src/server/decide.rs
index a168d6c0..a7f742b3 100644
--- a/src/server/decide.rs
+++ b/src/server/decide.rs
@@ -818,9 +818,11 @@ pub async fn change(
if state.db.set_message_meta(&message_id, &meta).await.is_err() {
return error(StatusCode::INTERNAL_SERVER_ERROR, "could not save the change");
}
- let Ok(Some(updated)) = state.db.get_message(&message_id).await else {
+ let Ok(Some(mut updated)) = state.db.get_message(&message_id).await else {
return error(StatusCode::INTERNAL_SERVER_ERROR, "could not load the message");
};
+ // The broadcast replaces the chat's copy, so it carries the reply's block too
+ state.db.attach_results(std::slice::from_mut(&mut updated)).await;
let context = msg.thread_id.as_deref().or(msg.channel_id.as_deref()).or(msg.direct_kwant_id.as_deref()).unwrap_or("");
if let Ok(Some(space)) = state.db.space_of_context(context).await {
let kwant_id = meta["decide_first"]["kwant_id"].as_str().map(str::to_string);
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 712e1d17..96e61947 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -1601,7 +1601,10 @@ pub async fn thread_messages(State(state): State<AppState>, Path(id): Path<Strin
Err(_) => return internal(),
}
match state.db.list_messages(&id, 100).await {
- Ok(m) => Json(m).into_response(),
+ Ok(mut m) => {
+ state.db.attach_results(&mut m).await;
+ Json(m).into_response()
+ }
Err(_) => internal(),
}
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 0630e52f..4794bed5 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -49,6 +49,7 @@ pub mod decide;
pub mod work_ahead;
pub mod missions;
pub mod app_update_routes;
+pub mod smart_results;
use crate::broker::PermissionBroker;
use crate::config::Config;
diff --git a/src/server/rerouting.rs b/src/server/rerouting.rs
index f3596817..35bc178b 100644
--- a/src/server/rerouting.rs
+++ b/src/server/rerouting.rs
@@ -455,6 +455,7 @@ mod tests {
created_at: None,
thread_id: None,
meta: None,
+ results: None,
}];
let note = routed_note(&routing("keywords", "matched"), false).unwrap();
crate::drivers::drop_current_message(&mut history, &format!("{asked}\n\n{note}"));
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 407f6a2b..3fd93125 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -539,7 +539,10 @@ pub async fn list_messages(
(None, None) => db.list_messages(&channel_or_kwant_id, limit).await.map(Some),
};
match rows {
- Ok(Some(rows)) => Ok(Json(rows)),
+ Ok(Some(mut rows)) => {
+ db.attach_results(&mut rows).await;
+ Ok(Json(rows))
+ }
Ok(None) => Err(err(StatusCode::NOT_FOUND, "That message isn't in this chat.")),
Err(_) => Err(err(StatusCode::INTERNAL_SERVER_ERROR, "Could not load messages.")),
}
diff --git a/src/server/smart_results/mod.rs b/src/server/smart_results/mod.rs
new file mode 100644
index 00000000..c9804d98
--- /dev/null
+++ b/src/server/smart_results/mod.rs
@@ -0,0 +1,132 @@
+//! Smart Results (0.6.5): a table or a numbered list in a bot's final reply, kept as a typed
+//! block the chat can draw as a comparison card or a checklist. Contract: docs/smart-results.md.
+//!
+//! - The reply's text is never changed. The block set lives beside it in `message_results`,
+//! written when the reply is saved ([`crate::db::Database::insert_message_with`]), and every
+//! message object carries it as `results` (`null` when there is none).
+//! - It always runs; there is no setting. The release fallback is [`ENABLED_TYPES`].
+//! - The selectors are deterministic (no model calls) and conservative: when one isn't sure the
+//! chat would render the same table or list, it abstains and the reply stays markdown.
+//! - Nothing here may cost the reply: a panic, an invalid block or a failed write is logged and
+//! the message is saved as it always was.
+
+mod selector;
+mod validate;
+
+pub use selector::candidates;
+pub use validate::validate;
+
+use serde::{Deserialize, Serialize};
+
+/// The block types this build stores and serves. Taking a type out (a one-line release fallback)
+/// stops new blocks of it and hides stored ones (`results: null`); the chat then shows the
+/// reply's markdown.
+pub const ENABLED_TYPES: &[&str] = &["comparison", "steps"];
+/// The payload version this build writes and reads.
+pub const VERSION: u32 = 1;
+/// Largest stored payload, in bytes of JSON.
+pub const MAX_PAYLOAD: usize = 64 * 1024;
+/// Replies longer than this stay text.
+pub const MAX_REPLY: usize = 128 * 1024;
+/// Why a row is highlighted; the only reason v1 gives.
+pub const PICK_REASON: &str = "named as the pick in this reply";
+
+/// The checked block set for a reply: the first candidate, in priority order, whose type is
+/// enabled and that passes [`validate`]; `None` when there isn't one. A selector bug must never
+/// cost the reply, so a panic is caught and logged.
+pub fn compute(text: &str) -> Option<ResultSet> {
+ let run = std::panic::catch_unwind(|| {
+ for block in candidates(text) {
+ if !ENABLED_TYPES.contains(&block.kind()) {
+ continue;
+ }
+ let set = ResultSet { version: VERSION, blocks: vec![block] };
+ match validate(&set, Some(text)) {
+ Ok(()) => return Some(set),
+ Err(why) => tracing::warn!("smart results: dropped a block that failed its checks: {why}"),
+ }
+ }
+ None
+ });
+ run.unwrap_or_else(|_| {
+ tracing::warn!("smart results: a selector panicked; the reply stays text");
+ None
+ })
+}
+
+/// `results` on a message: payload v1.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct ResultSet {
+ pub version: u32,
+ pub blocks: Vec<Block>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum Block {
+ Comparison(Comparison),
+ Steps(Steps),
+}
+
+impl Block {
+ /// The block's `type`.
+ pub fn kind(&self) -> &'static str {
+ match self {
+ Block::Comparison(_) => "comparison",
+ Block::Steps(_) => "steps",
+ }
+ }
+}
+
+/// Which table (`markdown_table`) or ordered list (`markdown_list`) of the reply a block stands
+/// for: `index` counts them in the order the chat renders them, from 0.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Source {
+ pub kind: String,
+ pub index: usize,
+}
+
+/// Where the values came from; v1 only copies them from the reply (`reply_text`).
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Provenance {
+ pub kind: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Column {
+ pub key: String,
+ pub label: String,
+ pub numeric: bool,
+ pub unit: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Row {
+ pub id: String,
+ pub cells: Vec<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Comparison {
+ pub id: String,
+ pub source: Source,
+ pub columns: Vec<Column>,
+ pub rows: Vec<Row>,
+ pub highlight_row: Option<String>,
+ pub highlight_reason: Option<String>,
+ pub provenance: Provenance,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Step {
+ pub id: String,
+ pub text: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Steps {
+ pub id: String,
+ pub source: Source,
+ pub items: Vec<Step>,
+ pub provenance: Provenance,
+}
diff --git a/src/server/smart_results/selector.rs b/src/server/smart_results/selector.rs
new file mode 100644
index 00000000..08057b95
--- /dev/null
+++ b/src/server/smart_results/selector.rs
@@ -0,0 +1,1110 @@
+//! The selector: the first comparison table, else the first steps list, of a reply.
+//!
+//! A line-by-line reading of CommonMark + GFM that is exact for the shapes bots write (top-level
+//! pipe tables and numbered lists, fenced code) and abstains on the rest. `index` must name the
+//! same table or list the chat's remark-gfm renders, so anything that could make the count
+//! uncertain (a table or numbered list inside a quote or a bullet item, a list nested in a list,
+//! raw HTML, tabs, a table run straight into a paragraph or another block) marks the reply
+//! uncertain from that line on, and no block is offered at or after it.
+
+use std::cell::OnceCell;
+use std::collections::HashSet;
+
+use super::validate::has_html;
+use super::{Block, Column, Comparison, Provenance, Row, Source, Step, Steps, MAX_REPLY, PICK_REASON};
+
+/// Every block `text` could show, in priority order and unchecked (see [`super::compute`]): each
+/// qualifying table as a comparison, then each qualifying numbered list as steps, earliest first.
+pub fn candidates(text: &str) -> Vec<Block> {
+ if text.len() > MAX_REPLY {
+ return Vec::new();
+ }
+ let doc = parse(text);
+ // Read the prose for a pick once, and only when there is a table
+ let said = OnceCell::new();
+ let tables = doc
+ .tables
+ .iter()
+ .filter(|t| t.start < doc.tables_unsure_at)
+ .filter_map(|t| comparison(t, said.get_or_init(|| recommending(&doc.prose)).as_deref()))
+ .take(MAX_TRIES);
+ let lists = doc.lists.iter().filter(|l| l.start < doc.lists_unsure_at).filter_map(steps).take(MAX_TRIES);
+ tables.map(Block::Comparison).chain(lists.map(Block::Steps)).collect()
+}
+
+/// Candidates offered per type: the first that passes its checks is used, and a reply with more
+/// tables or lists than this doesn't cost more.
+const MAX_TRIES: usize = 4;
+
+// Reading the markdown
+
+struct Table<'a> {
+ index: usize,
+ start: usize,
+ clean: bool,
+ header: Vec<&'a str>,
+ rows: Vec<Vec<&'a str>>,
+}
+
+struct List<'a> {
+ index: usize,
+ start: usize,
+ clean: bool,
+ delim: u8,
+ number: u64,
+ items: Vec<&'a str>,
+ /// The non-blank line just before the list, and the latest heading above it.
+ intro: Option<&'a str>,
+ heading: Option<&'a str>,
+}
+
+#[derive(Default)]
+struct Doc<'a> {
+ tables: Vec<Table<'a>>,
+ lists: Vec<List<'a>>,
+ /// Lines outside code, HTML and tables, where a pick can be named.
+ prose: Vec<&'a str>,
+ /// The first line from which table (list) counts may differ from the chat's.
+ tables_unsure_at: usize,
+ lists_unsure_at: usize,
+}
+
+impl Doc<'_> {
+ fn unsure_tables(&mut self, line: usize) {
+ self.tables_unsure_at = self.tables_unsure_at.min(line);
+ }
+ fn unsure_lists(&mut self, line: usize) {
+ self.lists_unsure_at = self.lists_unsure_at.min(line);
+ }
+ fn unsure(&mut self, line: usize) {
+ self.unsure_tables(line);
+ self.unsure_lists(line);
+ }
+}
+
+#[derive(Clone, Copy)]
+enum State {
+ None,
+ Para,
+ Table(usize),
+ /// A top-level ordered list; `offset` is the current item's content column.
+ List { list: usize, offset: usize, blank: bool },
+ /// A bullet list, read only as far as it can hide tables and numbered lists.
+ Bullet { offset: usize, blank: bool },
+ Quote,
+ Html,
+ Code,
+}
+
+struct Fence {
+ ch: u8,
+ len: usize,
+ /// The content column of the list item holding it; `None` at the top level.
+ inside: Option<usize>,
+}
+
+fn parse(text: &str) -> Doc<'_> {
+ let lines: Vec<&str> = text.split('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)).collect();
+ let mut doc = Doc { tables_unsure_at: usize::MAX, lists_unsure_at: usize::MAX, ..Doc::default() };
+ let mut state = State::None;
+ let mut fence: Option<Fence> = None;
+ let mut heading: Option<&str> = None;
+ let mut prev: Option<&str> = None;
+ let mut delimiter_row: Option<usize> = None;
+ for (i, &line) in lines.iter().enumerate() {
+ let (indent, rest) = lead(line);
+ let blank = rest.trim().is_empty();
+ if let Some(f) = &fence {
+ match f.inside {
+ Some(offset) if !blank && indent < offset => {
+ // The item ends and closes the fence with it; whether the chat agrees is
+ // more than this reader knows.
+ doc.unsure(i);
+ fence = None;
+ }
+ Some(_) => {
+ if fence_closes(rest, f) {
+ fence = None;
+ }
+ if !blank {
+ prev = Some(line);
+ }
+ continue;
+ }
+ None => {
+ if indent <= 3 && fence_closes(rest, f) {
+ fence = None;
+ }
+ if !blank {
+ prev = Some(line);
+ }
+ continue;
+ }
+ }
+ }
+ if delimiter_row == Some(i) {
+ delimiter_row = None;
+ prev = Some(line);
+ continue;
+ }
+ if line.contains('\t') {
+ doc.unsure(i);
+ }
+ let mut prose = !blank;
+ let mut in_table = false;
+ let mut code = false;
+ loop {
+ match state {
+ State::Table(t) => {
+ if blank {
+ state = State::None;
+ } else if indent >= 4 || block_start(rest) {
+ // GFM ends the table here, or takes the line as a row: not sure which
+ doc.unsure(i);
+ doc.tables[t].clean = false;
+ state = State::None;
+ continue;
+ } else {
+ let cells = split_cells(rest);
+ let table = &mut doc.tables[t];
+ if !has_pipe(rest) || cells.len() != table.header.len() {
+ table.clean = false;
+ }
+ table.rows.push(cells);
+ prose = false;
+ in_table = true;
+ }
+ }
+ State::List { list, offset, blank: after_blank } => {
+ if blank {
+ state = State::List { list, offset, blank: true };
+ break;
+ }
+ if indent >= offset {
+ // More of the current item: a second paragraph, nested blocks or code
+ doc.lists[list].clean = false;
+ let inner = after_cols(line, offset);
+ if has_ordered_marker(inner) {
+ doc.unsure_lists(i);
+ }
+ if let Some((ch, len)) = fence_open(inner.trim_start()) {
+ fence = Some(Fence { ch, len, inside: Some(offset) });
+ }
+ state = State::List { list, offset, blank: false };
+ break;
+ }
+ if indent <= 3 {
+ if let Some(m) = ordered_marker(rest, indent) {
+ if m.delim == doc.lists[list].delim {
+ let l = &mut doc.lists[list];
+ l.items.push(m.content);
+ if m.content.is_empty() {
+ l.clean = false;
+ }
+ if has_ordered_marker(m.content) {
+ doc.unsure_lists(i);
+ }
+ state = State::List { list, offset: m.offset, blank: false };
+ break;
+ }
+ // `1.` then `1)`: a new list
+ state = State::None;
+ continue;
+ }
+ if thematic_break(rest)
+ || bullet_marker(rest, indent).is_some()
+ || atx_heading(rest).is_some()
+ || fence_open(rest).is_some()
+ || rest.starts_with('>')
+ || html_start(rest)
+ {
+ state = State::None;
+ continue;
+ }
+ }
+ if after_blank {
+ state = State::None;
+ continue;
+ }
+ // A lazy continuation line of the item's paragraph
+ doc.lists[list].clean = false;
+ if has_ordered_marker(rest) {
+ doc.unsure_lists(i);
+ }
+ state = State::List { list, offset, blank: false };
+ }
+ State::Bullet { offset, blank: after_blank } => {
+ if blank {
+ state = State::Bullet { offset, blank: true };
+ break;
+ }
+ if indent >= offset {
+ let inner = after_cols(line, offset);
+ if has_ordered_marker(inner) {
+ doc.unsure_lists(i);
+ }
+ if let Some((ch, len)) = fence_open(inner.trim_start()) {
+ fence = Some(Fence { ch, len, inside: Some(offset) });
+ }
+ state = State::Bullet { offset, blank: false };
+ break;
+ }
+ if indent <= 3 {
+ if thematic_break(rest) {
+ state = State::None;
+ continue;
+ }
+ if let Some(b) = bullet_marker(rest, indent) {
+ if has_ordered_marker(b.content) {
+ doc.unsure_lists(i);
+ }
+ state = State::Bullet { offset: b.offset, blank: false };
+ break;
+ }
+ if let Some(m) = ordered_marker(rest, indent) {
+ if after_blank || (m.number == 1 && !m.content.is_empty()) {
+ state = State::None;
+ continue;
+ }
+ // Lazy text, or a new list: CommonMark readers differ
+ doc.unsure_lists(i);
+ state = State::Bullet { offset, blank: false };
+ break;
+ }
+ if atx_heading(rest).is_some() || fence_open(rest).is_some() || rest.starts_with('>') || html_start(rest) {
+ state = State::None;
+ continue;
+ }
+ }
+ if after_blank {
+ state = State::None;
+ continue;
+ }
+ state = State::Bullet { offset, blank: false };
+ }
+ State::Quote => {
+ if blank {
+ state = State::None;
+ } else if indent <= 3 && rest.starts_with('>') {
+ if has_ordered_marker(rest) {
+ doc.unsure_lists(i);
+ }
+ } else if indent <= 3 && block_start(rest) {
+ if let Some(m) = ordered_marker(rest, indent) {
+ if m.number != 1 || m.content.is_empty() {
+ doc.unsure_lists(i);
+ break;
+ }
+ }
+ state = State::None;
+ continue;
+ }
+ }
+ State::Html => {
+ prose = false;
+ if blank {
+ state = State::None;
+ }
+ }
+ State::Code => {
+ if blank {
+ break;
+ }
+ if indent < 4 {
+ state = State::None;
+ continue;
+ }
+ prose = false;
+ code = true;
+ if has_ordered_marker(rest) {
+ doc.unsure_lists(i);
+ }
+ }
+ State::Para => {
+ if blank {
+ state = State::None;
+ break;
+ }
+ if indent <= 3 {
+ if setext_underline(rest) {
+ if rest.contains('-') && prev.is_some_and(has_pipe) {
+ // `| a |` over `---`: a one-column table or a heading
+ doc.unsure_tables(i);
+ }
+ heading = prev.map(str::trim);
+ state = State::None;
+ break;
+ }
+ if let Some(m) = ordered_marker(rest, indent) {
+ if m.number == 1 && !m.content.is_empty() {
+ state = State::None;
+ continue;
+ }
+ // Anything else continues the paragraph
+ break;
+ }
+ if thematic_break(rest) || atx_heading(rest).is_some() || fence_open(rest).is_some() || rest.starts_with('>') {
+ state = State::None;
+ continue;
+ }
+ if bullet_marker(rest, indent).is_some_and(|b| !b.content.is_empty()) {
+ state = State::None;
+ continue;
+ }
+ if html_start(rest) {
+ doc.unsure(i);
+ state = State::None;
+ continue;
+ }
+ if table_start(&lines, i).is_some() {
+ // A table straight after a paragraph line: GFM readers differ
+ doc.unsure(i);
+ state = State::None;
+ continue;
+ }
+ }
+ }
+ State::None => {
+ if blank {
+ break;
+ }
+ if indent >= 4 {
+ state = State::Code;
+ prose = false;
+ code = true;
+ if has_ordered_marker(rest) || fence_open(rest).is_some() {
+ doc.unsure_lists(i);
+ }
+ break;
+ }
+ if let Some((ch, len)) = fence_open(rest) {
+ fence = Some(Fence { ch, len, inside: None });
+ prose = false;
+ break;
+ }
+ if let Some(h) = atx_heading(rest) {
+ heading = Some(h);
+ break;
+ }
+ if thematic_break(rest) {
+ break;
+ }
+ if rest.starts_with('>') {
+ if has_ordered_marker(rest) {
+ doc.unsure_lists(i);
+ }
+ state = State::Quote;
+ break;
+ }
+ if html_start(rest) {
+ doc.unsure(i);
+ prose = false;
+ state = State::Html;
+ break;
+ }
+ if let Some(m) = ordered_marker(rest, indent) {
+ let index = doc.lists.len();
+ if has_ordered_marker(m.content) {
+ doc.unsure_lists(i);
+ }
+ doc.lists.push(List {
+ index,
+ start: i,
+ clean: !m.content.is_empty(),
+ delim: m.delim,
+ number: m.number,
+ items: vec![m.content],
+ intro: prev,
+ heading,
+ });
+ state = State::List { list: index, offset: m.offset, blank: false };
+ break;
+ }
+ if let Some(b) = bullet_marker(rest, indent) {
+ if has_ordered_marker(b.content) {
+ doc.unsure_lists(i);
+ }
+ state = State::Bullet { offset: b.offset, blank: false };
+ break;
+ }
+ if let Some(header) = table_start(&lines, i) {
+ let index = doc.tables.len();
+ doc.tables.push(Table { index, start: i, clean: true, header, rows: Vec::new() });
+ delimiter_row = Some(i + 1);
+ state = State::Table(index);
+ prose = false;
+ in_table = true;
+ break;
+ }
+ state = State::Para;
+ }
+ }
+ break;
+ }
+ if !in_table && !code && delimiter_like(line) {
+ // A table this reader didn't take as top-level (in a quote or an item, or orphaned)
+ doc.unsure_tables(i);
+ }
+ if prose && !has_pipe(line) {
+ doc.prose.push(line);
+ }
+ if !blank {
+ prev = Some(line);
+ }
+ }
+ doc
+}
+
+/// The indentation in columns (a tab counts to the next multiple of 4) and the rest of the line.
+fn lead(line: &str) -> (usize, &str) {
+ let mut cols = 0;
+ for (i, c) in line.char_indices() {
+ match c {
+ ' ' => cols += 1,
+ '\t' => cols += 4 - cols % 4,
+ _ => return (cols, &line[i..]),
+ }
+ }
+ (cols, "")
+}
+
+/// `line` after its first `cols` columns of indentation.
+fn after_cols(line: &str, cols: usize) -> &str {
+ let mut seen = 0;
+ for (i, c) in line.char_indices() {
+ if seen >= cols {
+ return &line[i..];
+ }
+ match c {
+ ' ' => seen += 1,
+ '\t' => seen += 4 - seen % 4,
+ _ => return &line[i..],
+ }
+ }
+ ""
+}
+
+/// A line that starts a block of another kind (given indentation of at most 3).
+fn block_start(rest: &str) -> bool {
+ rest.starts_with('>')
+ || atx_heading(rest).is_some()
+ || fence_open(rest).is_some()
+ || thematic_break(rest)
+ || bullet_marker(rest, 0).is_some()
+ || ordered_marker(rest, 0).is_some()
+ || html_start(rest)
+}
+
+fn atx_heading(rest: &str) -> Option<&str> {
+ let hashes = rest.bytes().take_while(|b| *b == b'#').count();
+ if hashes == 0 || hashes > 6 {
+ return None;
+ }
+ let after = &rest[hashes..];
+ if !after.is_empty() && !after.starts_with([' ', '\t']) {
+ return None;
+ }
+ Some(after.trim().trim_end_matches('#').trim_end())
+}
+
+fn thematic_break(rest: &str) -> bool {
+ let mut marks = rest.chars().filter(|c| !matches!(c, ' ' | '\t'));
+ let Some(first) = marks.next() else { return false };
+ if !matches!(first, '-' | '*' | '_') {
+ return false;
+ }
+ let mut n = 1;
+ for c in marks {
+ if c != first {
+ return false;
+ }
+ n += 1;
+ }
+ n >= 3
+}
+
+fn setext_underline(rest: &str) -> bool {
+ let t = rest.trim_end();
+ !t.is_empty() && (t.bytes().all(|b| b == b'=') || t.bytes().all(|b| b == b'-'))
+}
+
+fn fence_open(rest: &str) -> Option<(u8, usize)> {
+ let ch = *rest.as_bytes().first()?;
+ if ch != b'`' && ch != b'~' {
+ return None;
+ }
+ let len = rest.bytes().take_while(|b| *b == ch).count();
+ if len < 3 || (ch == b'`' && rest[len..].contains('`')) {
+ return None;
+ }
+ Some((ch, len))
+}
+
+fn fence_closes(rest: &str, fence: &Fence) -> bool {
+ let len = rest.bytes().take_while(|b| *b == fence.ch).count();
+ len >= fence.len && rest[len..].trim().is_empty()
+}
+
+fn html_start(rest: &str) -> bool {
+ let mut chars = rest.chars();
+ chars.next() == Some('<') && chars.next().is_some_and(|c| c.is_ascii_alphabetic() || matches!(c, '/' | '!' | '?'))
+}
+
+struct Ordered<'a> {
+ number: u64,
+ delim: u8,
+ /// The item's first line, trimmed; empty for an empty item.
+ content: &'a str,
+ /// The column its content starts at.
+ offset: usize,
+}
+
+fn ordered_marker(rest: &str, indent: usize) -> Option<Ordered<'_>> {
+ let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
+ if digits == 0 || digits > 9 {
+ return None;
+ }
+ let delim = *rest.as_bytes().get(digits)?;
+ if delim != b'.' && delim != b')' {
+ return None;
+ }
+ let after = &rest[digits + 1..];
+ let number = rest[..digits].parse().ok()?;
+ let marker = digits + 1;
+ if after.trim().is_empty() {
+ return Some(Ordered { number, delim, content: "", offset: indent + marker + 1 });
+ }
+ if !after.starts_with(' ') {
+ return None;
+ }
+ let spaces = after.bytes().take_while(|b| *b == b' ').count();
+ let offset = if spaces >= 5 { indent + marker + 1 } else { indent + marker + spaces };
+ Some(Ordered { number, delim, content: after.trim(), offset })
+}
+
+struct Bullet<'a> {
+ content: &'a str,
+ offset: usize,
+}
+
+fn bullet_marker(rest: &str, indent: usize) -> Option<Bullet<'_>> {
+ if !rest.starts_with(['-', '+', '*']) {
+ return None;
+ }
+ let after = &rest[1..];
+ if after.trim().is_empty() {
+ return Some(Bullet { content: "", offset: indent + 2 });
+ }
+ if !after.starts_with(' ') {
+ return None;
+ }
+ let spaces = after.bytes().take_while(|b| *b == b' ').count();
+ let offset = if spaces >= 5 { indent + 2 } else { indent + 1 + spaces };
+ Some(Bullet { content: after.trim(), offset })
+}
+
+/// Whether a numbered list starts in `s`, after any quote and bullet markers: one this reader
+/// doesn't count, so the chat's count may differ from here on.
+fn has_ordered_marker(s: &str) -> bool {
+ let mut s = s.trim_start();
+ for _ in 0..32 {
+ if let Some(r) = s.strip_prefix('>') {
+ s = r.trim_start();
+ } else if let Some(b) = bullet_marker(s, 0).filter(|b| !b.content.is_empty()) {
+ s = b.content;
+ } else {
+ return ordered_marker(s, 0).is_some();
+ }
+ }
+ true
+}
+
+fn has_pipe(line: &str) -> bool {
+ let bytes = line.as_bytes();
+ let mut i = 0;
+ while i < bytes.len() {
+ match bytes[i] {
+ b'\\' => i += 2,
+ b'|' => return true,
+ _ => i += 1,
+ }
+ }
+ false
+}
+
+/// The cells of a table row: split on unescaped pipes, outer pipes dropped, each trimmed. Cells
+/// are verbatim markdown (an escaped `\|` stays escaped).
+fn split_cells(line: &str) -> Vec<&str> {
+ let s = line.trim();
+ let s = s.strip_prefix('|').unwrap_or(s);
+ let s = match s.strip_suffix('|') {
+ Some(inner) if !inner.ends_with('\\') => inner,
+ _ => s,
+ };
+ let bytes = s.as_bytes();
+ let mut cells = Vec::new();
+ let (mut start, mut i) = (0, 0);
+ while i < bytes.len() {
+ match bytes[i] {
+ b'\\' => i += 2,
+ b'|' => {
+ cells.push(s[start..i].trim());
+ i += 1;
+ start = i;
+ }
+ _ => i += 1,
+ }
+ }
+ cells.push(s[start.min(s.len())..].trim());
+ cells
+}
+
+/// A GFM delimiter row (`| --- | :-: |`): its cell count.
+fn delimiter_cells(line: &str) -> Option<usize> {
+ if !has_pipe(line) {
+ return None;
+ }
+ let cells = split_cells(line);
+ let ok = cells.iter().all(|c| {
+ let c = c.strip_prefix(':').unwrap_or(c);
+ let c = c.strip_suffix(':').unwrap_or(c);
+ !c.is_empty() && c.bytes().all(|b| b == b'-')
+ });
+ ok.then_some(cells.len())
+}
+
+/// A line that looks like a delimiter row once indentation and quote or list markers are gone.
+fn delimiter_like(line: &str) -> bool {
+ let mut s = line.trim_start();
+ for _ in 0..32 {
+ if let Some(r) = s.strip_prefix('>') {
+ s = r.trim_start();
+ } else if let Some(r) = s.strip_prefix("- ").or_else(|| s.strip_prefix("* ")).or_else(|| s.strip_prefix("+ ")) {
+ s = r.trim_start();
+ } else if let Some(m) = ordered_marker(s, 0).filter(|m| !m.content.is_empty()) {
+ s = m.content;
+ } else {
+ break;
+ }
+ }
+ s.contains('|') && s.contains('-') && s.chars().all(|c| matches!(c, '|' | '-' | ':' | ' ' | '\t'))
+}
+
+/// The header cells when lines `i` and `i + 1` open a GFM table.
+fn table_start<'a>(lines: &[&'a str], i: usize) -> Option<Vec<&'a str>> {
+ let header = lines[i];
+ let delimiter = *lines.get(i + 1)?;
+ let (h_indent, h_rest) = lead(header);
+ let (d_indent, _) = lead(delimiter);
+ if h_indent > 3 || d_indent > 3 || !has_pipe(h_rest) {
+ return None;
+ }
+ let cells = split_cells(h_rest);
+ (delimiter_cells(delimiter)? == cells.len()).then_some(cells)
+}
+
+// Comparison
+
+/// `said`: the reply's recommending sentences ([`recommending`]); `None` means no row is
+/// highlighted.
+fn comparison(t: &Table, said: Option<&[String]>) -> Option<Comparison> {
+ let cols = t.header.len();
+ if !t.clean || !(2..=8).contains(&cols) || !(3..=50).contains(&t.rows.len()) {
+ return None;
+ }
+ if t.header.iter().any(|h| h.is_empty() || h.chars().count() > 200) {
+ return None;
+ }
+ if t.rows.iter().any(|r| r.len() != cols || r.iter().any(|c| c.chars().count() > 200)) {
+ return None;
+ }
+ // Cells are shown as text, so a table with HTML in it stays markdown
+ if t.header.iter().chain(t.rows.iter().flatten()).any(|c| has_html(c)) {
+ return None;
+ }
+ let mut seen = HashSet::new();
+ for row in &t.rows {
+ let key: String = plain(row[0]).trim().chars().map(fold).collect();
+ if key.is_empty() || !seen.insert(key) {
+ return None;
+ }
+ }
+ let columns = (0..cols)
+ .map(|c| {
+ let (numeric, unit) = numeric_column(t.rows.iter().map(|r| r[c]));
+ Column { key: format!("c{c}"), label: t.header[c].to_string(), numeric, unit }
+ })
+ .collect();
+ let rows = t
+ .rows
+ .iter()
+ .enumerate()
+ .map(|(i, r)| Row { id: format!("r{i}"), cells: r.iter().map(|c| c.to_string()).collect() })
+ .collect();
+ let labels: Vec<&str> = t.rows.iter().map(|r| r[0]).collect();
+ let pick = said.and_then(|said| pick(&labels, said));
+ Some(Comparison {
+ id: "b0".into(),
+ source: Source { kind: "markdown_table".into(), index: t.index },
+ columns,
+ rows,
+ highlight_row: pick.map(|r| format!("r{r}")),
+ highlight_reason: pick.map(|_| PICK_REASON.to_string()),
+ provenance: Provenance { kind: "reply_text".into() },
+ })
+}
+
+/// Numeric when at least 80% of the cells are a number with the same prefix or suffix (that
+/// affix is the unit; none counts as an affix too).
+fn numeric_column<'a>(cells: impl Iterator<Item = &'a str>) -> (bool, Option<String>) {
+ let mut counts: Vec<(Option<&str>, usize)> = Vec::new();
+ let mut total = 0;
+ for cell in cells {
+ total += 1;
+ let Some(affix) = number_affix(cell) else { continue };
+ match counts.iter_mut().find(|(a, _)| *a == affix) {
+ Some((_, n)) => *n += 1,
+ None => counts.push((affix, 1)),
+ }
+ }
+ let mut best: Option<(Option<&str>, usize)> = None;
+ for (affix, n) in counts {
+ if best.is_none_or(|(_, b)| n > b) {
+ best = Some((affix, n));
+ }
+ }
+ match best {
+ Some((affix, n)) if total > 0 && n * 5 >= total * 4 => (true, affix.map(str::to_string)),
+ _ => (false, None),
+ }
+}
+
+/// `Some(affix)` when `cell` is a number with at most one affix: a prefix of up to 4 letters or
+/// currency signs (`EUR 12`, `$12`) or a suffix of up to 10 (`12 EUR`, `-4%`, `4.5/5`).
+fn number_affix(cell: &str) -> Option<Option<&str>> {
+ let mut s = cell.trim();
+ loop {
+ let before = s;
+ for wrap in ["**", "__", "*", "_", "`"] {
+ if s.len() > 2 * wrap.len() && s.starts_with(wrap) && s.ends_with(wrap) {
+ s = s[wrap.len()..s.len() - wrap.len()].trim();
+ }
+ }
+ if s == before {
+ break;
+ }
+ }
+ let start = s.char_indices().find_map(|(i, c)| {
+ let signed = matches!(c, '+' | '-' | '−') && s[i + c.len_utf8()..].starts_with(|d: char| d.is_ascii_digit());
+ (c.is_ascii_digit() || signed).then_some(i)
+ })?;
+ let mut end = start + s[start..].chars().next()?.len_utf8();
+ end += s[end..].bytes().take_while(|b| b.is_ascii_digit() || *b == b'.' || *b == b',').count();
+ let number = s[start..end].trim_end_matches(['.', ',']);
+ let end = start + number.len();
+ if !is_number(number) {
+ return None;
+ }
+ let (before, after) = (&s[..start], &s[end..]);
+ let prefix = before.trim_end();
+ let suffix = after.trim_start();
+ if before.len() - prefix.len() > 1 || after.len() - suffix.len() > 1 {
+ return None;
+ }
+ match (prefix.is_empty(), suffix.is_empty()) {
+ (true, true) => Some(None),
+ (false, true) => {
+ let ok = prefix.chars().count() <= 4
+ && prefix.chars().all(|c| c.is_alphabetic() || currency(c) || c == '.')
+ && prefix.chars().any(|c| c != '.');
+ ok.then_some(Some(prefix))
+ }
+ (true, false) => {
+ let out_of = suffix.strip_prefix('/').is_some_and(|d| (1..=3).contains(&d.len()) && d.bytes().all(|b| b.is_ascii_digit()));
+ let unit = suffix.chars().all(|c| c.is_alphabetic() || currency(c) || "%‰°/²³µ'\".".contains(c))
+ && suffix.chars().any(|c| c != '.');
+ (suffix.chars().count() <= 10 && (out_of || unit)).then_some(Some(suffix))
+ }
+ (false, false) => None,
+ }
+}
+
+fn currency(c: char) -> bool {
+ matches!(c, '$' | '¢' | '£' | '¤' | '¥' | '֏' | '؋' | '৳' | '฿' | '៛' | '﷼') || ('\u{20A0}'..='\u{20CF}').contains(&c)
+}
+
+/// `1299`, `12.5`, `12,5`, `1,299.00` or `1.299,00`, with an optional sign; at most 15 digits.
+fn is_number(n: &str) -> bool {
+ let n = n.strip_prefix(['+', '-', '−']).unwrap_or(n);
+ let digits = n.bytes().filter(u8::is_ascii_digit).count();
+ if digits == 0 || digits > 15 {
+ return false;
+ }
+ let all_digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
+ let grouped = |group: char, decimal: char| {
+ let (int, frac) = match n.split_once(decimal) {
+ Some((int, frac)) => (int, Some(frac)),
+ None => (n, None),
+ };
+ let mut parts = int.split(group);
+ let first = parts.next().unwrap_or("");
+ let rest: Vec<&str> = parts.collect();
+ frac.is_none_or(all_digits)
+ && (1..=3).contains(&first.len())
+ && all_digits(first)
+ && !rest.is_empty()
+ && rest.iter().all(|p| p.len() == 3 && all_digits(p))
+ };
+ let simple = match n.split_once(['.', ',']) {
+ Some((int, frac)) => all_digits(int) && all_digits(frac),
+ None => all_digits(n),
+ };
+ simple || grouped(',', '.') || grouped('.', ',')
+}
+
+// The pick
+
+const PICK_WORDS: [&str; 6] = ["best", "pick", "picks", "picked", "choose", "winner"];
+/// Words that make a sentence too hedged or negative to name a pick.
+const HEDGES: [&str; 23] = [
+ "not", "never", "avoid", "no", "nor", "none", "without", "unless", "instead", "rather", "except", "skip", "worst",
+ "worse", "if", "otherwise", "depends", "depending", "cannot", "second", "runner", "alternatively", "but",
+];
+
+/// More recommending text than this in a reply (in characters), or more label hits than
+/// [`MAX_HITS`] while looking for a table's pick, and no row is highlighted: it keeps the search
+/// cheap and the pick plain.
+const MAX_SCANNED: usize = 8_000;
+const MAX_HITS: usize = 1_000;
+
+/// The sentences of the reply's prose that recommend something ([`recommends`]), without
+/// emphasis, code marks or link targets; `None` when they run past [`MAX_SCANNED`] characters.
+fn recommending(prose: &[&str]) -> Option<Vec<String>> {
+ let mut out = Vec::new();
+ let mut total = 0;
+ for line in prose {
+ let line = plain(line);
+ for sentence in sentences(&line) {
+ if !recommends(sentence) {
+ continue;
+ }
+ total += sentence.chars().count();
+ if total > MAX_SCANNED {
+ return None;
+ }
+ out.push(sentence.to_string());
+ }
+ }
+ Some(out)
+}
+
+/// The one row whose first-column label a recommending sentence (`said`, outside the table)
+/// names; `None` when no row or more than one is named.
+fn pick(labels: &[&str], said: &[String]) -> Option<usize> {
+ // Short labels match case exactly, longer ones ignore case
+ let labels: Vec<(usize, String, bool)> = labels
+ .iter()
+ .enumerate()
+ .filter_map(|(r, l)| {
+ let l = plain(l);
+ let l = l.trim();
+ let folded: String = l.chars().map(fold).collect();
+ let usable = l.chars().any(char::is_alphabetic)
+ && !PICK_WORDS.contains(&folded.as_str())
+ && !folded.starts_with("recommend")
+ && folded != "go with";
+ let exact = l.chars().count() < 4;
+ usable.then(|| (r, if exact { l.to_string() } else { folded }, exact))
+ })
+ .collect();
+ let mut named = HashSet::new();
+ let mut hits = 0;
+ for sentence in said {
+ let folded: String = sentence.chars().map(fold).collect();
+ let (at, folded_at) = (char_positions(sentence), char_positions(&folded));
+ let mut found: Vec<(usize, usize, usize)> = Vec::new();
+ for (r, label, exact) in &labels {
+ let (h, pos) = if *exact { (sentence.as_str(), &at) } else { (folded.as_str(), &folded_at) };
+ for (start, end) in occurrences(h, label, *exact, &mut hits)? {
+ found.push((pos[start], pos[end], *r));
+ }
+ }
+ // `Pro` inside `Pro Max` names `Pro Max`
+ for &(start, end, r) in &found {
+ let inside = found.iter().any(|&(s2, e2, _)| s2 <= start && end <= e2 && e2 - s2 > end - start);
+ if !inside {
+ named.insert(r);
+ }
+ }
+ }
+ (named.len() == 1).then(|| named.into_iter().next()).flatten()
+}
+
+/// The character index of each character's first byte in `s`, and of its end.
+fn char_positions(s: &str) -> Vec<usize> {
+ let mut out = vec![0; s.len() + 1];
+ let mut n = 0;
+ for (i, _) in s.char_indices() {
+ out[i] = n;
+ n += 1;
+ }
+ out[s.len()] = n;
+ out
+}
+
+fn sentences(line: &str) -> Vec<&str> {
+ let mut out = Vec::new();
+ let mut start = 0;
+ let mut chars = line.char_indices().peekable();
+ while let Some((i, c)) = chars.next() {
+ if matches!(c, '.' | '!' | '?') && chars.peek().is_none_or(|(_, n)| n.is_whitespace()) {
+ let end = i + c.len_utf8();
+ out.push(&line[start..end]);
+ start = end;
+ }
+ }
+ out.push(&line[start..]);
+ out.into_iter().map(str::trim).filter(|s| !s.is_empty()).collect()
+}
+
+/// A sentence that recommends something, and isn't a question or hedged.
+fn recommends(sentence: &str) -> bool {
+ if sentence.ends_with('?') {
+ return false;
+ }
+ let lower: String = sentence.chars().map(fold).collect();
+ let words: Vec<&str> = lower.split(|c: char| !(c.is_alphanumeric() || c == '\'' || c == '’')).filter(|w| !w.is_empty()).collect();
+ if words.iter().any(|w| HEDGES.contains(w) || w.ends_with("n't") || w.ends_with("n’t")) {
+ return false;
+ }
+ words.iter().any(|w| PICK_WORDS.contains(w) || w.starts_with("recommend")) || words.windows(2).any(|w| w == ["go", "with"])
+}
+
+/// Where `label` appears in `h` as a whole name, as byte ranges: neighbours may not be letters,
+/// digits or `_ + # -`, and a following `.` must end the sentence (so `Node` doesn't match
+/// `Node.js`). With `exact` (a short label matched case for case), a lone `A` or `I` opening the
+/// sentence is the word, not the label. Every place `label` is found counts toward `hits`, whole
+/// name or not; `None` past [`MAX_HITS`].
+fn occurrences(h: &str, label: &str, exact: bool, hits: &mut usize) -> Option<Vec<(usize, usize)>> {
+ let joins = |c: char| c.is_alphanumeric() || matches!(c, '_' | '+' | '#' | '-');
+ let mut out = Vec::new();
+ if label.is_empty() {
+ return Some(out);
+ }
+ let mut from = 0;
+ while let Some(at) = h[from..].find(label) {
+ *hits += 1;
+ if *hits > MAX_HITS {
+ return None;
+ }
+ let start = from + at;
+ let end = start + label.len();
+ from = start + h[start..].chars().next().map_or(1, char::len_utf8);
+ if h[..start].chars().next_back().is_some_and(joins) {
+ continue;
+ }
+ let mut after = h[end..].chars();
+ if let Some(next) = after.next() {
+ if joins(next) || (next == '.' && after.next().is_some_and(|c| !c.is_whitespace())) {
+ continue;
+ }
+ }
+ if exact && matches!(label, "A" | "I") && h[..start].chars().all(|c| !c.is_alphanumeric()) {
+ continue;
+ }
+ out.push((start, end));
+ }
+ Some(out)
+}
+
+/// Text without emphasis or code marks, links reduced to their text: for matching only.
+fn plain(s: &str) -> String {
+ let chars: Vec<char> = s.chars().collect();
+ let mut out = String::with_capacity(s.len());
+ let mut i = 0;
+ // Once no `)` follows, none will: don't look again (keeps this linear)
+ let mut closes = true;
+ while i < chars.len() {
+ let c = chars[i];
+ if closes && c == ']' && chars.get(i + 1) == Some(&'(') {
+ match chars[i + 2..].iter().position(|&x| x == ')') {
+ Some(close) => {
+ i += close + 3;
+ continue;
+ }
+ None => closes = false,
+ }
+ }
+ if !matches!(c, '*' | '`' | '[' | ']') {
+ out.push(c);
+ }
+ i += 1;
+ }
+ out
+}
+
+/// One lowercase character for one character, so positions line up.
+fn fold(c: char) -> char {
+ c.to_lowercase().next().unwrap_or(c)
+}
+
+// Steps
+
+const STEP_HINTS: [&str; 5] = ["step", "steps", "checklist", "plan", "todo"];
+/// Intro words that make a numbered list something other than steps to follow.
+const NOT_STEPS: [&str; 24] = [
+ "reason", "reasons", "why", "benefit", "benefits", "advantage", "advantages", "tip", "tips", "example", "examples",
+ "idea", "ideas", "pros", "cons", "option", "options", "comparison", "compare", "pricing", "price", "prices", "tier",
+ "tiers",
+];
+
+fn steps(l: &List) -> Option<Steps> {
+ if !l.clean || l.number != 1 || !(3..=15).contains(&l.items.len()) {
+ return None;
+ }
+ if l.items.iter().any(|t| t.is_empty() || t.chars().count() > 300 || is_task(t) || has_html(t)) {
+ return None;
+ }
+ let numbered = l.items.iter().all(|t| starts_step_n(t));
+ let intro = l.intro.map(words).unwrap_or_default();
+ let heading = l.heading.map(words).unwrap_or_default();
+ let hinted = |w: &[String]| {
+ w.iter().any(|x| STEP_HINTS.contains(&x.as_str()))
+ || w.windows(2).any(|p| p == ["how", "to"] || p == ["to", "do"])
+ };
+ let hedged = |w: &[String]| w.iter().any(|x| NOT_STEPS.contains(&x.as_str()));
+ let introduced = !hedged(&intro) && (hinted(&intro) || (hinted(&heading) && !hedged(&heading)));
+ if !(numbered || introduced) {
+ return None;
+ }
+ Some(Steps {
+ id: "b0".into(),
+ source: Source { kind: "markdown_list".into(), index: l.index },
+ items: l.items.iter().enumerate().map(|(i, t)| Step { id: format!("s{i}"), text: t.to_string() }).collect(),
+ provenance: Provenance { kind: "reply_text".into() },
+ })
+}
+
+fn words(s: &str) -> Vec<String> {
+ let lower: String = s.chars().map(fold).collect();
+ lower.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).map(str::to_string).collect()
+}
+
+fn is_task(item: &str) -> bool {
+ ["[ ]", "[x]", "[X]"].iter().any(|t| item.strip_prefix(t).is_some_and(|r| r.is_empty() || r.starts_with(' ')))
+}
+
+/// "Step 1", "**Step 2:**" and the like.
+fn starts_step_n(item: &str) -> bool {
+ let s = item.trim_start_matches(['*', '_', ' ']);
+ let Some(head) = s.get(..4) else { return false };
+ if !head.eq_ignore_ascii_case("step") {
+ return false;
+ }
+ let digits = s[4..].trim_start();
+ digits.starts_with(|c: char| c.is_ascii_digit())
+}
+
+#[cfg(test)]
+#[path = "selector_tests.rs"]
+mod tests;
diff --git a/src/server/smart_results/selector_tests.rs b/src/server/smart_results/selector_tests.rs
new file mode 100644
index 00000000..44c36700
--- /dev/null
+++ b/src/server/smart_results/selector_tests.rs
@@ -0,0 +1,374 @@
+use super::*;
+use crate::server::smart_results::{compute, validate, Block, ResultSet, MAX_PAYLOAD, PICK_REASON};
+
+fn first(text: &str) -> Option<Block> {
+ compute(text).map(|set| set.blocks.into_iter().next().expect("one block"))
+}
+
+fn comparison_of(text: &str) -> Comparison {
+ match first(text) {
+ Some(Block::Comparison(c)) => c,
+ other => panic!("expected a comparison, got {other:?}"),
+ }
+}
+
+fn steps_of(text: &str) -> Steps {
+ match first(text) {
+ Some(Block::Steps(s)) => s,
+ other => panic!("expected steps, got {other:?}"),
+ }
+}
+
+const PLANS: &str = "| Plan | Price | Seats |\n|---|---|---|\n| Basic | EUR 12 | 1 |\n| Team | EUR 18 | 5 |\n| Business | EUR 26 | 20 |\n";
+
+fn with_prose(prose: &str) -> String {
+ format!("Here are the plans.\n\n{PLANS}\n{prose}\n")
+}
+
+fn highlight(prose: &str) -> Option<String> {
+ comparison_of(&with_prose(prose)).highlight_row
+}
+
+#[test]
+fn a_pipe_table_is_a_comparison_with_cells_copied_verbatim() {
+ let c = comparison_of(PLANS);
+ assert_eq!(c.id, "b0");
+ assert_eq!((c.source.kind.as_str(), c.source.index), ("markdown_table", 0));
+ assert_eq!(c.provenance.kind, "reply_text");
+ let cols: Vec<(&str, &str, bool, Option<&str>)> =
+ c.columns.iter().map(|k| (k.key.as_str(), k.label.as_str(), k.numeric, k.unit.as_deref())).collect();
+ assert_eq!(cols, [("c0", "Plan", false, None), ("c1", "Price", true, Some("EUR")), ("c2", "Seats", true, None)]);
+ assert_eq!(c.rows[1].id, "r1");
+ assert_eq!(c.rows[1].cells, ["Team", "EUR 18", "5"]);
+ assert_eq!((c.highlight_row, c.highlight_reason), (None, None));
+}
+
+#[test]
+fn small_ragged_wide_or_repeated_tables_stay_text() {
+ let two_rows = "| Plan | Price |\n|---|---|\n| Basic | 12 |\n| Team | 18 |\n";
+ assert_eq!(first(two_rows), None);
+ let ragged = "| Plan | Price |\n|---|---|\n| Basic | 12 |\n| Team |\n| Business | 26 |\n";
+ assert_eq!(first(ragged), None);
+ let one_column = "| Plan |\n|---|\n| Basic |\n| Team |\n| Business |\n";
+ assert_eq!(first(one_column), None);
+ let header = (0..9).map(|i| format!("h{i}")).collect::<Vec<_>>().join(" | ");
+ let rows = (0..3).map(|r| (0..9).map(|i| format!("r{r}c{i}")).collect::<Vec<_>>().join(" | ")).collect::<Vec<_>>();
+ let nine = format!("| {header} |\n|{}\n| {} |\n| {} |\n| {} |\n", "---|".repeat(9), rows[0], rows[1], rows[2]);
+ assert_eq!(first(&nine), None);
+ for labels in [["A", "A", "B"], ["Alpha", "alpha", "Beta"], ["**Basic**", "Basic", "Team"], ["A ", "A", "B"]] {
+ let t = format!("| Plan | Price |\n|---|---|\n| {} | 1 |\n| {} | 2 |\n| {} | 3 |\n", labels[0], labels[1], labels[2]);
+ assert_eq!(first(&t), None, "{labels:?}");
+ }
+}
+
+#[test]
+fn row_and_cell_limits() {
+ let rows = |n: usize| (0..n).map(|i| format!("| item {i} | {i} |\n")).collect::<String>();
+ let fifty = format!("| Item | N |\n|---|---|\n{}", rows(50));
+ assert_eq!(comparison_of(&fifty).rows.len(), 50);
+ let fifty_one = format!("| Item | N |\n|---|---|\n{}", rows(51));
+ assert_eq!(first(&fifty_one), None);
+ let cell = |n: usize| format!("| Plan | Note |\n|---|---|\n| Basic | {} |\n| Team | b |\n| Business | c |\n", "x".repeat(n));
+ assert!(first(&cell(200)).is_some());
+ assert_eq!(first(&cell(201)), None);
+}
+
+#[test]
+fn html_in_a_cell_or_step_stays_text() {
+ let t = "| Plan | Price |\n|---|---|\n| <b>Basic</b> | 12 |\n| Team | 18 |\n| Business | 26 |\n";
+ assert_eq!(first(t), None);
+ let s = "Steps:\n1. Open <a href=x>this</a>\n2. Two\n3. Three\n";
+ assert_eq!(first(s), None);
+ // `a < b` isn't a tag
+ let t = "| Plan | Rule |\n|---|---|\n| Basic | a < b |\n| Team | b < c |\n| Business | c < d |\n";
+ assert!(first(t).is_some());
+}
+
+#[test]
+fn tables_in_code_are_neither_offered_nor_counted() {
+ for fence in ["```", "~~~", "````"] {
+ let text = format!("{fence}\n| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n| 5 | 6 |\n{fence}\n\n{PLANS}");
+ let c = comparison_of(&text);
+ assert_eq!(c.source.index, 0, "{fence}");
+ assert_eq!(c.rows[0].cells[0], "Basic");
+ }
+ let indented = format!("Code:\n\n | a | b |\n |---|---|\n | 1 | 2 |\n\n{PLANS}");
+ assert_eq!(comparison_of(&indented).source.index, 0);
+ // An unclosed fence hides the rest of the reply
+ assert_eq!(first(&format!("```\n{PLANS}")), None);
+}
+
+#[test]
+fn the_first_qualifying_table_wins_and_keeps_its_index() {
+ let small = "| a | b |\n|---|---|\n| 1 | 2 |\n\n";
+ let c = comparison_of(&format!("{small}{PLANS}"));
+ assert_eq!(c.source.index, 1);
+ // A table beats a list, wherever the list is
+ let text = format!("Steps:\n1. One\n2. Two\n3. Three\n\n{PLANS}");
+ assert_eq!(comparison_of(&text).source.index, 0);
+}
+
+#[test]
+fn uncertain_structure_before_a_candidate_abstains() {
+ // A table inside a bullet item: remark-gfm counts it, this reader doesn't try
+ let nested = format!("- item\n\n | a | b |\n |---|---|\n | 1 | 2 |\n | 3 | 4 |\n | 5 | 6 |\n\n{PLANS}");
+ assert_eq!(first(&nested), None);
+ // A table in a quote
+ let quoted = format!("> | a | b |\n> |---|---|\n> | 1 | 2 |\n\n{PLANS}");
+ assert_eq!(first(&quoted), None);
+ // A numbered list in a quote, then steps
+ let quote_list = "> 1. a\n> 2. b\n\nSteps:\n1. One\n2. Two\n3. Three\n";
+ assert_eq!(first(quote_list), None);
+ // A numbered list nested in a bullet, then steps
+ let nested_list = "- top\n 1. a\n 2. b\n\nSteps:\n1. One\n2. Two\n3. Three\n";
+ assert_eq!(first(nested_list), None);
+ // Raw HTML
+ assert_eq!(first(&format!("<div>\nhi\n</div>\n\n{PLANS}")), None);
+ // A table straight after a paragraph line
+ assert_eq!(first(&format!("Here:\n{PLANS}")), None);
+ // Tabs
+ assert_eq!(first(&format!("a\tb\n\n{PLANS}")), None);
+ // What comes after the uncertain part is out; what comes before is still offered
+ let before = format!("{PLANS}\n> | a | b |\n> |---|---|\n> | 1 | 2 |\n");
+ assert_eq!(comparison_of(&before).source.index, 0);
+}
+
+#[test]
+fn a_pick_named_once_in_a_recommending_sentence_is_highlighted() {
+ assert_eq!(highlight("Team is the best fit for five people."), Some("r1".into()));
+ assert_eq!(highlight("I recommend **Business** for larger teams."), Some("r2".into()));
+ assert_eq!(highlight("Go with Basic."), Some("r0".into()));
+ let c = comparison_of(&with_prose("My pick: Team."));
+ assert_eq!(c.highlight_reason.as_deref(), Some(PICK_REASON));
+}
+
+#[test]
+fn no_highlight_when_unsure() {
+ // Two rows named
+ assert_eq!(highlight("Basic and Team are both the best value."), None);
+ assert_eq!(highlight("Team is the best. Basic is the best for one person."), None);
+ // No recommending word
+ assert_eq!(highlight("Team has five seats."), None);
+ // Negation, hedges and questions
+ assert_eq!(highlight("I would not recommend Team."), None);
+ assert_eq!(highlight("Don't pick Basic."), None);
+ assert_eq!(highlight("If you grow, Business is the best."), None);
+ assert_eq!(highlight("Is Team the best?"), None);
+ assert_eq!(highlight("Team is the best, but check the seats."), None);
+ // A recommending sentence inside the table doesn't count
+ let t = "| Plan | Note |\n|---|---|\n| Basic | the best for one |\n| Team | b |\n| Business | c |\n";
+ assert_eq!(comparison_of(t).highlight_row, None);
+}
+
+#[test]
+fn highlight_names_whole_labels_only() {
+ let abc = "| Option | Cost |\n|---|---|\n| A | 1 |\n| B | 2 |\n| C | 3 |\n";
+ let hl = |prose: &str| comparison_of(&format!("{abc}\n{prose}\n")).highlight_row;
+ // A lone "A" opening a sentence is the word
+ assert_eq!(hl("A clear winner is B."), Some("r1".into()));
+ // Lowercase "a" and words containing "a" aren't label A
+ assert_eq!(hl("Overall a great pick is C, also cheap."), Some("r2".into()));
+ assert_eq!(hl("Pick A."), Some("r0".into()));
+
+ let pro = "| Model | Price |\n|---|---|\n| Pro | 999 |\n| Pro Max | 1199 |\n| Air | 799 |\n";
+ let hl = |prose: &str| comparison_of(&format!("{pro}\n{prose}\n")).highlight_row;
+ assert_eq!(hl("The Pro Max is the best camera."), Some("r1".into()));
+ assert_eq!(hl("The Pro is the best value."), Some("r0".into()));
+
+ let langs = "| Language | Speed |\n|---|---|\n| C | 10 |\n| C++ | 9 |\n| Rust | 9 |\n";
+ let hl = |prose: &str| comparison_of(&format!("{langs}\n{prose}\n")).highlight_row;
+ assert_eq!(hl("I recommend C++ here."), Some("r1".into()));
+ assert_eq!(hl("I recommend C here."), Some("r0".into()));
+
+ let beta = "| Tool | Cost |\n|---|---|\n| Claude | 1 |\n| Claude (beta) | 2 |\n| Gemini | 3 |\n";
+ let hl = |prose: &str| comparison_of(&format!("{beta}\n{prose}\n")).highlight_row;
+ assert_eq!(hl("Claude (beta) is my pick."), Some("r1".into()));
+
+ let js = "| Runtime | Speed |\n|---|---|\n| Node | 1 |\n| Deno | 2 |\n| Bun | 3 |\n";
+ let hl = |prose: &str| comparison_of(&format!("{js}\n{prose}\n")).highlight_row;
+ assert_eq!(hl("Node.js is the best known."), None);
+ assert_eq!(hl("Bun is the best. "), Some("r2".into()));
+}
+
+#[test]
+fn numeric_columns_and_units() {
+ assert_eq!(number_affix("12"), Some(None));
+ assert_eq!(number_affix("EUR 12"), Some(Some("EUR")));
+ assert_eq!(number_affix("12 EUR"), Some(Some("EUR")));
+ assert_eq!(number_affix("$1,299.00"), Some(Some("$")));
+ assert_eq!(number_affix("1.299,00 EUR"), Some(Some("EUR")));
+ assert_eq!(number_affix("-4%"), Some(Some("%")));
+ assert_eq!(number_affix("−4%"), Some(Some("%")));
+ assert_eq!(number_affix("4.5/5"), Some(Some("/5")));
+ assert_eq!(number_affix("**12 ms**"), Some(Some("ms")));
+ assert_eq!(number_affix("N/A"), None);
+ assert_eq!(number_affix("about 12"), None);
+ assert_eq!(number_affix("12 to 14"), None);
+ assert_eq!(number_affix("EUR 12/mo"), None);
+ assert_eq!(number_affix("1,2,3"), None);
+ assert_eq!(number_affix("1234567890123456"), None);
+
+ let col = |cells: &[&str]| numeric_column(cells.iter().copied());
+ assert_eq!(col(&["1", "2", "3", "4", "n/a"]), (true, None));
+ assert_eq!(col(&["1", "2", "3", "n/a", "n/a"]), (false, None));
+ assert_eq!(col(&["EUR 1", "EUR 2", "EUR 3", "EUR 4", "5"]), (true, Some("EUR".into())));
+ assert_eq!(col(&["EUR 1", "EUR 2", "3 USD", "4 USD", "5"]), (false, None));
+}
+
+#[test]
+fn a_numbered_list_introduced_as_steps_is_steps() {
+ let s = steps_of("Steps:\n1. Open settings\n2. Pick a bot\n3. Save\n");
+ assert_eq!((s.source.kind.as_str(), s.source.index), ("markdown_list", 0));
+ let items: Vec<(&str, &str)> = s.items.iter().map(|i| (i.id.as_str(), i.text.as_str())).collect();
+ assert_eq!(items, [("s0", "Open settings"), ("s1", "Pick a bot"), ("s2", "Save")]);
+ assert!(first("Here's how to set it up:\n1. One\n2. Two\n3. Three\n").is_some());
+ assert!(first("A quick checklist:\n1) One\n2) Two\n3) Three\n").is_some());
+ assert!(first("## How to deploy\n\n1. One\n2. Two\n3. Three\n").is_some());
+ assert!(first("## Deploy plan\n\nDo this:\n\n1. One\n2. Two\n3. Three\n").is_some());
+ assert!(first("1. **Step 1:** Open\n2. **Step 2:** Pick\n3. Step 3 - Save\n").is_some());
+}
+
+#[test]
+fn other_numbered_lists_stay_text() {
+ assert_eq!(first("3 reasons why:\n1. One\n2. Two\n3. Three\n"), None);
+ assert_eq!(first("Here are some ideas:\n1. One\n2. Two\n3. Three\n"), None);
+ assert_eq!(first("Steps to compare pricing:\n1. One\n2. Two\n3. Three\n"), None);
+ assert_eq!(first("Some things:\n1. One\n2. Two\n3. Three\n"), None);
+ // Two items, or more than 15
+ assert_eq!(first("Steps:\n1. One\n2. Two\n"), None);
+ let many = (1..=16).map(|i| format!("{i}. item {i}\n")).collect::<String>();
+ assert_eq!(first(&format!("Steps:\n{many}")), None);
+ // Not starting at 1, or items with more than one line
+ assert_eq!(first("Steps:\n5. One\n6. Two\n7. Three\n"), None);
+ assert_eq!(first("Steps:\n1. One\n more\n2. Two\n3. Three\n"), None);
+ assert_eq!(first("Steps:\n1. One\n - sub\n2. Two\n3. Three\n"), None);
+ // 301 characters
+ assert_eq!(first(&format!("Steps:\n1. {}\n2. Two\n3. Three\n", "x".repeat(301))), None);
+}
+
+#[test]
+fn a_task_list_is_counted_but_not_offered() {
+ let text = "Plan:\n1. [ ] a\n2. [x] b\n3. [ ] c\n\nSteps:\n1. One\n2. Two\n3. Three\n";
+ assert_eq!(steps_of(text).source.index, 1);
+}
+
+#[test]
+fn lists_are_counted_in_order_and_by_delimiter() {
+ // `1.` then `1)` is two lists
+ let text = "Steps:\n1. a\n2. b\n1) c\n2) d\n3) e\n\nSteps:\n1. One\n2. Two\n3. Three\n";
+ assert_eq!(steps_of(text).source.index, 2);
+ // A list in a fence isn't counted
+ let text = "```\n1. a\n2. b\n3. c\n```\n\nSteps:\n1. One\n2. Two\n3. Three\n";
+ assert_eq!(steps_of(text).source.index, 0);
+}
+
+#[test]
+fn every_value_is_text_of_the_reply_and_checks_pass() {
+ let text = with_prose("Team is the best pick.");
+ let set = compute(&text).unwrap();
+ assert_eq!(validate(&set, Some(&text)), Ok(()));
+ let mut changed = set.clone();
+ if let Block::Comparison(c) = &mut changed.blocks[0] {
+ c.rows[0].cells[1] = "EUR 99".into();
+ }
+ assert!(validate(&changed, Some(&text)).is_err());
+ // An unknown version is never served
+ let v2 = ResultSet { version: 2, ..set.clone() };
+ assert!(validate(&v2, None).is_err());
+ let none = ResultSet { blocks: Vec::new(), ..set };
+ assert!(validate(&none, None).is_err());
+}
+
+#[test]
+fn a_too_big_block_is_dropped() {
+ let cell = "x".repeat(200);
+ let rows = (0..50).map(|i| format!("| item {i} | {cell} | {cell} | {cell} | {cell} | {cell} | {cell} | {cell} |\n")).collect::<String>();
+ let text = format!("| A | B | C | D | E | F | G | H |\n|---|---|---|---|---|---|---|---|\n{rows}");
+ assert!(text.len() > MAX_PAYLOAD);
+ assert_eq!(candidates(&text).len(), 1);
+ assert_eq!(compute(&text), None);
+ // Over the reply limit, nothing is read at all
+ let long = format!("{PLANS}\n{}", "word ".repeat(30_000));
+ assert!(candidates(&long).is_empty());
+}
+
+#[test]
+fn odd_input_never_panics() {
+ // A small deterministic generator over markdown-ish pieces, multibyte text included
+ let pieces = [
+ "|", " | ", "---", ":-:", "\n", "\n\n", "1. ", "2) ", "- ", "* ", "> ", " ", "\t", "```", "~~~", "#", "## ",
+ "Steps:", "best", "pick ", "Pro", "A", "€", "日本", "é", "💡", "\\|", "<b>", "**", "[x](y)", "](", "12", "1,299.00",
+ "-4%", "[ ]", "Step 1", "\r\n", "=", " ", ".",
+ ];
+ let mut seed: u64 = 0x5eed;
+ for _ in 0..3_000 {
+ let mut text = String::new();
+ for _ in 0..(seed % 60) {
+ seed ^= seed << 13;
+ seed ^= seed >> 7;
+ seed ^= seed << 17;
+ text.push_str(pieces[(seed % pieces.len() as u64) as usize]);
+ }
+ let found = candidates(&text);
+ if let Some(set) = compute(&text) {
+ assert_eq!(validate(&set, Some(&text)), Ok(()), "{text:?}");
+ }
+ drop(found);
+ }
+}
+
+#[test]
+fn pathological_text_stays_fast() {
+ // Labels found all over the prose but never as whole names, recommending prose over the scan
+ // cap (100 lines) and just under it (8 lines), link brackets that never close
+ let labels = (0..50).map(|i| format!("| {} | {i} |\n", "a".repeat(150 + i))).collect::<String>();
+ for lines in [100, 8] {
+ let prose = format!("{} best.\n", "a".repeat(990)).repeat(lines);
+ let text = format!("| Name | N |\n|---|---|\n{labels}\n{prose}{}", "](".repeat(2_000));
+ assert!(text.len() < MAX_REPLY);
+ let start = std::time::Instant::now();
+ let c = comparison_of(&text);
+ assert!(start.elapsed() < std::time::Duration::from_secs(2), "{lines}: {:?}", start.elapsed());
+ assert_eq!(c.highlight_row, None);
+ }
+ // Hundreds of tables cost no more than a few
+ let many = format!("{PLANS}\n").repeat(1_000) + "We recommend Team.\n";
+ assert!(many.len() < MAX_REPLY);
+ let start = std::time::Instant::now();
+ assert_eq!(candidates(&many).len(), MAX_TRIES);
+ assert!(start.elapsed() < std::time::Duration::from_secs(2), "{:?}", start.elapsed());
+}
+
+#[test]
+fn huge_ragged_tables_nested_lists_and_pipe_walls_stay_fast() {
+ // The block is worked out inside the message insert, so no reply under the size cap may be slow
+ let header = "| a | b | c | d | e | f | g | h |\n|---|---|---|---|---|---|---|---|\n";
+ let ragged = (0..2_500).map(|i| "| x ".repeat(7 + i % 3) + "|\n").collect::<String>();
+ let nested =
+ (0..5_000).map(|i| format!("{}{} x\n", " ".repeat(i % 12), if i % 2 == 0 { "1." } else { "-" })).collect::<String>();
+ let cases = [
+ ("ragged table", format!("{header}{ragged}")),
+ ("nested lists", format!("Steps:\n\n{nested}")),
+ ("pipe wall", "|".repeat(MAX_REPLY - 1)),
+ ("pipe lines", format!("{header}{}", "|||||||||\n".repeat(12_000))),
+ ("tiny tables", "| a |\n|---|\n\n".repeat(9_000)),
+ ("escaped pipes", format!("{header}{}", "| \\| ".repeat(25_000))),
+ ];
+ for (what, text) in cases {
+ assert!(text.len() < MAX_REPLY, "{what}: {} bytes", text.len());
+ let start = std::time::Instant::now();
+ let set = compute(&text);
+ let took = start.elapsed();
+ eprintln!("{what}: {took:?}");
+ assert!(took < std::time::Duration::from_secs(1), "{what}: {took:?}");
+ assert_eq!(set, None, "{what}");
+ }
+}
+
+#[test]
+fn a_long_run_of_recommending_prose_names_no_pick() {
+ let some = format!("I recommend Team. {}", "We recommend reading the docs. ".repeat(100));
+ assert_eq!(highlight(&some).as_deref(), Some("r1"));
+ let too_much = format!("I recommend Team. {}", "We recommend reading the docs. ".repeat(300));
+ assert_eq!(highlight(&too_much), None);
+}
diff --git a/src/server/smart_results/validate.rs b/src/server/smart_results/validate.rs
new file mode 100644
index 00000000..c3676233
--- /dev/null
+++ b/src/server/smart_results/validate.rs
@@ -0,0 +1,142 @@
+//! Checks every block set before it is stored, and again when a stored one is read back.
+
+use std::collections::HashSet;
+
+use super::{Block, ResultSet, ENABLED_TYPES, MAX_PAYLOAD, PICK_REASON, VERSION};
+
+/// `Ok` when `set` is a block set this build may store and serve. With `reply`, every label, unit,
+/// cell and item must also be text of that reply (values are copied, never made up).
+pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
+ if set.version != VERSION {
+ return Err(format!("unknown version {}", set.version));
+ }
+ if set.blocks.len() != 1 {
+ return Err(format!("{} blocks; v1 has exactly one", set.blocks.len()));
+ }
+ if let Some(off) = set.blocks.iter().find(|b| !ENABLED_TYPES.contains(&b.kind())) {
+ return Err(format!("type {} is not enabled", off.kind()));
+ }
+ let mut texts: Vec<&str> = Vec::new();
+ for (i, block) in set.blocks.iter().enumerate() {
+ let want = format!("b{i}");
+ match block {
+ Block::Comparison(c) => {
+ if c.id != want {
+ return Err(format!("block id {:?}", c.id));
+ }
+ if c.source.kind != "markdown_table" || c.source.index > 10_000 {
+ return Err("comparison source".into());
+ }
+ if c.provenance.kind != "reply_text" {
+ return Err("comparison provenance".into());
+ }
+ if !(2..=8).contains(&c.columns.len()) {
+ return Err(format!("{} columns", c.columns.len()));
+ }
+ for (k, col) in c.columns.iter().enumerate() {
+ if col.key != format!("c{k}") {
+ return Err(format!("column key {:?}", col.key));
+ }
+ check_text(&col.label, 200, "column label")?;
+ texts.push(&col.label);
+ match &col.unit {
+ Some(_) if !col.numeric => return Err("a unit on a text column".into()),
+ Some(unit) => {
+ check_text(unit, 10, "unit")?;
+ texts.push(unit);
+ }
+ None => {}
+ }
+ }
+ if !(3..=50).contains(&c.rows.len()) {
+ return Err(format!("{} rows", c.rows.len()));
+ }
+ let mut labels = HashSet::new();
+ for (r, row) in c.rows.iter().enumerate() {
+ if row.id != format!("r{r}") {
+ return Err(format!("row id {:?}", row.id));
+ }
+ if row.cells.len() != c.columns.len() {
+ return Err(format!("row {r} has {} cells", row.cells.len()));
+ }
+ check_text(&row.cells[0], 200, "row label")?;
+ if !labels.insert(row.cells[0].as_str()) {
+ return Err(format!("row label {:?} repeats", row.cells[0]));
+ }
+ for cell in &row.cells {
+ if cell.chars().count() > 200 {
+ return Err("a cell over 200 characters".into());
+ }
+ if has_html(cell) {
+ return Err("HTML in a cell".into());
+ }
+ texts.push(cell);
+ }
+ }
+ match (&c.highlight_row, &c.highlight_reason) {
+ (None, None) => {}
+ (Some(row), Some(reason)) => {
+ if !c.rows.iter().any(|r| &r.id == row) {
+ return Err(format!("highlight_row {row:?} is not a row"));
+ }
+ if reason != PICK_REASON {
+ return Err("highlight_reason".into());
+ }
+ }
+ _ => return Err("highlight_row and highlight_reason come together".into()),
+ }
+ }
+ Block::Steps(s) => {
+ if s.id != want {
+ return Err(format!("block id {:?}", s.id));
+ }
+ if s.source.kind != "markdown_list" || s.source.index > 10_000 {
+ return Err("steps source".into());
+ }
+ if s.provenance.kind != "reply_text" {
+ return Err("steps provenance".into());
+ }
+ if !(3..=15).contains(&s.items.len()) {
+ return Err(format!("{} steps", s.items.len()));
+ }
+ for (k, item) in s.items.iter().enumerate() {
+ if item.id != format!("s{k}") {
+ return Err(format!("step id {:?}", item.id));
+ }
+ check_text(&item.text, 300, "step")?;
+ texts.push(&item.text);
+ }
+ }
+ }
+ }
+ if let Some(reply) = reply {
+ if let Some(t) = texts.iter().find(|t| !reply.contains(**t)) {
+ return Err(format!("{t:?} is not text of the reply"));
+ }
+ }
+ let size = serde_json::to_vec(set).map_err(|e| e.to_string())?.len();
+ if size > MAX_PAYLOAD {
+ return Err(format!("payload of {size} bytes"));
+ }
+ Ok(())
+}
+
+fn check_text(s: &str, max: usize, what: &str) -> Result<(), String> {
+ if s.trim().is_empty() {
+ return Err(format!("an empty {what}"));
+ }
+ if s.chars().count() > max {
+ return Err(format!("a {what} over {max} characters"));
+ }
+ if has_html(s) {
+ return Err(format!("HTML in a {what}"));
+ }
+ Ok(())
+}
+
+/// Anything that could open an HTML tag, comment or declaration (`<b`, `</`, `<!`, `<?`).
+pub(super) fn has_html(s: &str) -> bool {
+ s.char_indices().any(|(i, c)| {
+ c == '<' && s[i + 1..].chars().next().is_some_and(|n| n.is_ascii_alphabetic() || matches!(n, '/' | '!' | '?'))
+ })
+}
diff --git a/src/server/work_ahead.rs b/src/server/work_ahead.rs
index bb0a91b5..5bd1b050 100644
--- a/src/server/work_ahead.rs
+++ b/src/server/work_ahead.rs
@@ -282,6 +282,7 @@ mod tests {
created_at: Some(Utc::now() - Duration::hours(hours_ago)),
thread_id: None,
meta: meta.map(str::to_string),
+ results: None,
}
}
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 8d82e279..c4735b95 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -5,6 +5,7 @@
//! - `CALLTOOL:<tool>:<base64 json args>` in the prompt: call that tool and reply with its text
//! (the last marker counts, and each marker runs once: later turns see it again in history).
//! - `REPLYTAG:<tag>`: reply "answer <tag>" (after any tool call).
+//! - `REPLYTEXT:<base64 text>`: reply exactly that text (say, a markdown table), and nothing else.
//! - `QUOTAONCE:<tag>` / `QUOTAALWAYS`: fail with Claude's usage-limit error, once / every time.
//! - `CAPPED:<tag>` / `CAPALWAYS:<tag>`: end at the model-call cap; the continuation doesn't / does too.
//!
@@ -58,6 +59,12 @@ if cap:
text = "partial " + cap[-1] + note
print(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result": text}))
sys.exit(0)
+# REPLYTEXT:<base64>: reply exactly that text
+rt = re.findall(r"REPLYTEXT:([A-Za-z0-9+/=]+)", prompt)
+if rt:
+ print(json.dumps({"type": "result", "is_error": False, "num_turns": 1,
+ "result": base64.b64decode(rt[-1]).decode()}))
+ sys.exit(0)
reply = []
m = ([None] + list(re.finditer(r"CALLTOOL:([a-z_]+):([A-Za-z0-9+/=]+)", prompt)))[-1]
done = None
diff --git a/tests/smart_results_test.rs b/tests/smart_results_test.rs
new file mode 100644
index 00000000..603728c4
--- /dev/null
+++ b/tests/smart_results_test.rs
@@ -0,0 +1,73 @@
+//! Smart Results over HTTP: a bot's final reply with a table comes back with its comparison block
+//! as `results` in the chat's message list and in a thread's; every other message has
+//! `results: null`.
+
+mod common;
+
+use axum::http::StatusCode;
+use base64::Engine;
+use common::*;
+use kwnt::db::models::{MessageExtra, NewMessage};
+use serde_json::{json, Value};
+
+const PLANS: &str = "Here are the plans.\n\n| Plan | Price | Seats |\n|---|---|---|\n| Basic | EUR 12 | 1 |\n| Team | EUR 18 | 5 |\n| Business | EUR 26 | 20 |\n\nI recommend Team.";
+
+async fn listed(env: &Env, uri: &str) -> Vec<Value> {
+ let (s, v) = call(&env.app, "GET", uri, None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ v.as_array().unwrap().clone()
+}
+
+#[tokio::test]
+async fn a_reply_with_a_table_comes_back_with_its_comparison() {
+ let env = setup().await;
+ let marker = format!("REPLYTEXT:{}", base64::engine::general_purpose::STANDARD.encode(PLANS));
+ send_direct(&env, &env.a, &format!("Compare the plans {marker}"), json!({})).await;
+ let reply = wait_reply(&env, &env.a, "| Business | EUR 26 | 20 |").await;
+ let list = listed(&env, &format!("/api/channels/{}/messages", env.a)).await;
+ let got = list.iter().find(|m| m["id"] == reply.id.as_str()).expect("the reply is listed");
+ assert!(got["text"].as_str().unwrap().contains(PLANS), "{got}");
+ assert_eq!(got["results"]["version"], 1, "{got}");
+ let block = &got["results"]["blocks"][0];
+ assert_eq!(block["type"], "comparison");
+ assert_eq!(block["source"], json!({"kind": "markdown_table", "index": 0}));
+ assert_eq!(block["rows"][2]["cells"], json!(["Business", "EUR 26", "20"]));
+ assert_eq!(block["columns"][1]["unit"], "EUR");
+ assert_eq!(block["highlight_row"], "r1");
+ let others: Vec<&Value> = list.iter().filter(|m| m["id"] != reply.id.as_str()).collect();
+ assert!(!others.is_empty());
+ for m in others {
+ assert_eq!(m.get("results"), Some(&Value::Null), "{m}");
+ }
+}
+
+#[tokio::test]
+async fn a_plain_reply_has_null_results() {
+ let env = setup().await;
+ send_direct(&env, &env.a, "Hello REPLYTAG:plain", json!({})).await;
+ let reply = wait_reply(&env, &env.a, "answer plain").await;
+ let list = listed(&env, &format!("/api/channels/{}/messages", env.a)).await;
+ let got = list.iter().find(|m| m["id"] == reply.id.as_str()).expect("the reply is listed");
+ assert_eq!(got.get("results"), Some(&Value::Null), "{got}");
+}
+
+#[tokio::test]
+async fn a_thread_lists_its_blocks_too() {
+ let env = setup().await;
+ let thread = env.state.db.create_thread(&env.a, "Plans", "chat", None, "user").await.unwrap();
+ let extra = MessageExtra { thread_id: Some(thread.id.clone()), ..Default::default() };
+ let reply = NewMessage {
+ channel_id: None,
+ direct_kwant_id: Some(env.a.clone()),
+ sender_role: "kwant".into(),
+ sender_id: env.a.clone(),
+ text: PLANS.into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let saved = env.state.db.insert_message_with(&reply, &extra).await.unwrap();
+ let list = listed(&env, &format!("/api/threads/{}/messages", thread.id)).await;
+ let got = list.iter().find(|m| m["id"] == saved.id.as_str()).expect("the reply is listed");
+ assert_eq!(got["results"]["blocks"][0]["type"], "comparison", "{got}");
+}