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: fix the 0.6.5 QA minors on the server (#251)

Oleksandr Ivanchenko22ae0953f693
diff --git a/src/server/smart_results/block_tests.rs b/src/server/smart_results/block_tests.rs
index fd06a86b..2570e52a 100644
--- a/src/server/smart_results/block_tests.rs
+++ b/src/server/smart_results/block_tests.rs
@@ -61,6 +61,8 @@ fn gaps_are_null_never_zero_and_mixed_units_never_chart() {
fn series_in_different_units_never_share_one_axis() {
// SR-R-13: bare numbers whose headers name two units stay off one Y axis
let line = |h: &str| table(h, &rows(5, |i| format!("| {} 2025 | 1{i}0 | {}.{i} |", MONTHS[i], 3 + i % 2)));
+ // (the unitless pair below has values of one scale, so it still charts)
+ let same_scale = |h: &str| table(h, &rows(5, |i| format!("| {} 2025 | 1{i}0 | 9{i} |", MONTHS[i])));
assert_ne!(kind(&line("| Month | Price (EUR) | Rating (1-5) |")), Some("chart"));
assert_ne!(kind(&line("| Month | Price [EUR] | Rating |")), Some("chart"));
assert_ne!(kind(&line("| Month | Price (€) | Cost (EUR) |")), Some("chart"));
@@ -70,8 +72,9 @@ fn series_in_different_units_never_share_one_axis() {
let bar = table("| Shop | Price (EUR) | Rating (1-5) |", &rows(5, |i| format!("| Shop{} | 1{i}0 | 4.{i} |", MONTHS[i])));
assert_ne!(kind(&bar), Some("chart"));
// One unit, named in the headers or the cells, still charts
- for h in ["| Month | Revenue (EUR) | Cost (eur) |", "| Month | Signups | Paid |"] {
- let Some(Block::Chart(c)) = first(&line(h)) else { panic!("{h}: {:?}", first(&line(h))) };
+ for h in ["| Month | Revenue (EUR) | Cost (eur) |", "| Month | Signups | Orders |"] {
+ let t = if h.contains("Orders") { same_scale(h) } else { line(h) };
+ let Some(Block::Chart(c)) = first(&t) else { panic!("{h}: {:?}", first(&t)) };
assert_eq!(c.series.len(), 2, "{h}");
}
let t = table("| Month | Revenue (€) | Cost |", &rows(5, |i| format!("| {} 2025 | 1{i}0 | €2{i} |", MONTHS[i])));
@@ -81,9 +84,10 @@ fn series_in_different_units_never_share_one_axis() {
#[test]
fn ambiguous_locale_numbers_abstain() {
- // `1,299` alone is 1299 or 1.299: no chart, and never a misread scale
+ // `1,299` alone: every number of the column groups its thousands the same way, so one reading
let t = table("| Month | Cost |", &rows(5, |i| format!("| {} 2025 | 1,2{i}9 |", MONTHS[i])));
- assert_ne!(kind(&t), Some("chart"));
+ let Some(Block::Chart(c)) = first(&t) else { panic!("{:?}", first(&t)) };
+ assert_eq!(c.points[0].values, [Some(1209.0)]);
// With `1,299.00` beside it the column has one reading
let t = table("| Month | Cost |", &rows(5, |i| format!("| {} 2025 | 1,2{i}9.50 |", MONTHS[i])));
let Some(Block::Chart(c)) = first(&t) else { panic!("{:?}", first(&t)) };
@@ -371,3 +375,203 @@ fn a_bare_weather_list_is_two_metric_tiles() {
let set = compute(text).unwrap();
validate(&set, Some(text)).unwrap();
}
+
+// --- QA minors from 0.6.5 (Rigel, qa/pr-smart-results-more.md and -typed.md, -renderers.md)
+
+fn metric_tiles(text: &str) -> Option<Vec<(String, String, f64)>> {
+ match first(text) {
+ Some(Block::Metrics(m)) => Some(m.items.into_iter().map(|i| (i.label, i.value_text, i.value)).collect()),
+ _ => None,
+ }
+}
+
+/// more-M1: a phone number is digits in groups, not a quantity.
+#[test]
+fn a_phone_number_is_not_a_metric_tile() {
+ for text in [
+ "- **Call us:** 555 0100 any time\n- **Open:** 24 hours\n",
+ "- **Call us:** 555 123 4567\n- **Open:** 24 hours\n",
+ "- **Open:** 24 hours\n- **Fax:** 555 0101\n",
+ ] {
+ assert_ne!(kind(text), Some("metrics"), "{text}");
+ }
+ // A number with a unit and a note stays a tile
+ let tiles = metric_tiles("- **Open:** 24 hours a day\n- **Staff:** 12 people\n").expect("tiles");
+ assert_eq!(tiles[0].1, "24 hours");
+ assert_eq!(tiles[1].2, 12.0);
+}
+
+/// more-M2: a version is a name, not a quantity.
+#[test]
+fn a_version_number_is_not_a_metric_tile() {
+ for text in [
+ "- **Node:** 20.11 LTS\n- **npm:** 10.2 stable\n",
+ "- **Node:** 20.11 LTS\n- **Uptime:** 98%\n",
+ "- **Rust:** 1.76 nightly\n- **Cargo:** 1.76 beta\n",
+ "- **Version:** 3.12\n- **Uptime:** 98%\n",
+ ] {
+ assert_ne!(kind(text), Some("metrics"), "{text}");
+ }
+ let tiles = metric_tiles("- **Latency:** 12.5 ms\n- **Size:** 4.2 GB\n").expect("tiles");
+ assert_eq!((tiles[0].1.as_str(), tiles[1].1.as_str()), ("12.5 ms", "4.2 GB"));
+}
+
+/// more-M3: a recap by weekday says what happened, it isn't a plan to follow.
+#[test]
+fn a_weekday_recap_is_not_steps() {
+ for text in [
+ "This week:\n- Monday: wrote tests for the parser\n- Tuesday: fixed the build\n- Wednesday: reviewed the pull requests\n",
+ "- Mon: wrote tests\n- Tue: fixed the build\n- Wed: reviewed the PRs\n",
+ ] {
+ assert_ne!(kind(text), Some("steps"), "{text}");
+ }
+ // A weekday among clock times is still an agenda
+ assert_eq!(kind("Agenda:\n- 9:00 – Intro\n- 10:30 – Demo\n- Mon: kickoff\n"), Some("steps"));
+}
+
+/// more-M5: a column that groups thousands with commas throughout has one reading.
+#[test]
+fn comma_grouped_numbers_with_one_grouping_are_read_as_thousands() {
+ let visits = ["4,100", "1,204", "980", "12,350", "7,002"];
+ let t = table("| Page | Visits |", &rows(5, |i| format!("| Page{} | {} |", (b'A' + i as u8) as char, visits[i])));
+ let Some(Block::Chart(c)) = first(&t) else { panic!("{:?}", first(&t)) };
+ assert_eq!(c.chart_kind, ChartKind::Bar);
+ let got: Vec<_> = c.points.iter().map(|p| (p.cells[0].as_str(), p.values[0])).collect();
+ assert_eq!(got[0], ("4,100", Some(4100.0)));
+ assert_eq!(got[3], ("12,350", Some(12350.0)));
+ let set = compute(&t).unwrap();
+ validate(&set, Some(&t)).unwrap();
+ // The same in a line chart and a metric
+ let t = table("| Month | Cost |", &rows(5, |i| format!("| {} 2025 | 1,2{i}9 |", MONTHS[i])));
+ let Some(Block::Chart(c)) = first(&t) else { panic!("{:?}", first(&t)) };
+ assert_eq!(c.points[0].values, [Some(1209.0)]);
+ let tiles = metric_tiles("- **Reviews:** 1,204\n- **Rating:** 4.8/5\n").expect("tiles");
+ assert_eq!((tiles[0].1.as_str(), tiles[0].2), ("1,204", 1204.0));
+}
+
+#[test]
+fn mixed_or_unsure_groupings_still_abstain() {
+ // `1,299` and `1.299` in one column: a comma and a dot grouping, so no reading
+ let t = table("| Month | Cost |", &rows(5, |i| format!("| {} 2025 | {} |", MONTHS[i], if i == 2 { "1.299" } else { "1,299" })));
+ assert_ne!(kind(&t), Some("chart"));
+ let t = table("| Page | Visits |", &rows(5, |i| format!("| P{} | {} |", (b'A' + i as u8) as char, ["1.299", "2.450", "3.100", "4.800", "5.001"][i])));
+ assert_ne!(kind(&t), Some("chart"), "dot groups are not read as thousands");
+ // Comma and dot together, as `1,299.50`, still read as before
+ let t = table("| Month | Cost |", &rows(5, |i| format!("| {} 2025 | 1,2{i}9.50 |", MONTHS[i])));
+ let Some(Block::Chart(c)) = first(&t) else { panic!("{:?}", first(&t)) };
+ assert_eq!(c.points[0].values, [Some(1209.5)]);
+}
+
+/// more-M6: unitless series on very different scales don't share one axis.
+#[test]
+fn unitless_series_on_very_different_scales_are_not_one_line_chart() {
+ let t = table("| Month | Revenue | Orders |", &rows(5, |i| format!("| {} 2025 | {} | {} |", MONTHS[i], 120_000 + i * 1_000, 400 + i * 10)));
+ assert_ne!(kind(&t), Some("chart"), "Revenue ~120000 beside Orders ~400");
+ // Nothing is computed or dropped: the table is still a block of its own cells
+ if let Some(Block::Comparison(c)) = first(&t) {
+ assert_eq!(c.rows[0].cells, ["Jan 2025", "120000", "400"]);
+ }
+ // Similar scales share an axis; so do series in one stated unit
+ let t = table("| Month | Revenue | Orders |", &rows(5, |i| format!("| {} 2025 | {} | {} |", MONTHS[i], 1_200 + i * 100, 400 + i * 10)));
+ assert_eq!(kind(&t), Some("chart"));
+ let t = table("| Month | Revenue (EUR) | Refunds (EUR) |", &rows(5, |i| format!("| {} 2025 | {} | {} |", MONTHS[i], 120_000 + i * 1_000, 400 + i * 10)));
+ assert_eq!(kind(&t), Some("chart"));
+ // A series of zeros has no scale of its own
+ let t = table("| Month | Revenue | Refunds |", &rows(5, |i| format!("| {} 2025 | {} | 0 |", MONTHS[i], 120_000 + i * 1_000)));
+ assert_eq!(kind(&t), Some("chart"));
+}
+
+/// more-M4: a link with a login in it is never a card.
+#[test]
+fn a_card_link_with_credentials_is_refused() {
+ let text = "Resources:\n- [Docs](https://user:[email protected]/docs) — the documentation for the project\n- [Tokio](https://tokio.rs) — an async runtime for network services\n- [Serde](https://serde.rs) — serialization for Rust data structures\n";
+ assert_ne!(kind(text), Some("cards"));
+ for url in ["https://[email protected]/docs", "https://[email protected]/x", "https://:[email protected]/"] {
+ assert_ne!(kind(&text.replace("https://user:[email protected]/docs", url)), Some("cards"), "{url}");
+ }
+ // An @ after the host is a path or a query, not a login
+ for url in ["https://example.com/@user", "https://example.com/[email protected]", "https://example.com/#a@b"] {
+ assert_eq!(kind(&text.replace("https://user:[email protected]/docs", url)), Some("cards"), "{url}");
+ }
+ // The validator holds a stored card to the same rule
+ let mut set = compute(&text.replace("https://user:[email protected]/docs", "https://example.com/docs")).unwrap();
+ validate(&set, None).unwrap();
+ for bad in ["https://user:[email protected]/docs", "https://[email protected]", "https://", "https:///x"] {
+ let Block::Cards(c) = &mut set.blocks[0] else { panic!() };
+ c.items[0].url = Some(bad.to_string());
+ assert!(validate(&set, None).is_err(), "{bad}");
+ }
+ let Block::Cards(c) = &mut set.blocks[0] else { panic!() };
+ c.items[0].url = Some("https://example.com/docs".into());
+ c.items[0].meta = vec!["x".repeat(41)];
+ assert!(validate(&set, None).is_err(), "card meta over the client's 40");
+}
+
+/// typed-M1, server side: what the validator stores, the client can draw.
+#[test]
+fn a_stored_block_is_one_the_client_validators_accept() {
+ let line = compute(&table("| Month | Visits |", &rows(6, |i| format!("| {} 2025 | {} |", MONTHS[i], 100 + i)))).unwrap();
+ validate(&line, None).unwrap();
+ // Series that differ in unit share no axis
+ let mut set = line.clone();
+ let Block::Chart(c) = &mut set.blocks[0] else { panic!() };
+ c.series.push(super::super::Series { key: "s1".into(), label: "Rating".into(), unit: Some("stars".into()) });
+ for p in &mut c.points {
+ p.cells.push("4".into());
+ p.values.push(Some(4.0));
+ }
+ assert!(validate(&set, None).is_err(), "two units on one axis");
+ // A bar chart needs five points
+ let mut set = line.clone();
+ let Block::Chart(c) = &mut set.blocks[0] else { panic!() };
+ c.chart_kind = ChartKind::Bar;
+ c.x.kind = AxisKind::Category;
+ validate(&set, None).unwrap();
+ let Block::Chart(c) = &mut set.blocks[0] else { panic!() };
+ c.points.truncate(4);
+ assert!(validate(&set, None).is_err(), "a bar chart of four points");
+}
+
+#[test]
+fn comparison_row_labels_repeat_as_the_client_reads_them() {
+ let plans = "| Plan | Price |\n|---|---|\n| Basic | 12 |\n| Team | 18 |\n| Business | 26 |\n";
+ let mut set = compute(plans).unwrap();
+ validate(&set, None).unwrap();
+ let Block::Comparison(c) = &mut set.blocks[0] else { panic!() };
+ c.rows[2].cells[0] = "**team**".into();
+ assert!(validate(&set, None).is_err(), "`Team` and `**team**` read as one label");
+ let Block::Comparison(c) = &mut set.blocks[0] else { panic!() };
+ c.rows[2].cells[0] = "[TEAM](https://example.com/t)".into();
+ assert!(validate(&set, None).is_err());
+}
+
+#[test]
+fn text_limits_count_as_the_client_counts() {
+ // The client counts UTF-16 units: 160 emoji are 320 of them, over its 300
+ let item = "😀".repeat(160);
+ let mut set = compute("Steps:\n1. First do this\n2. Then do that\n3. Finally this\n").unwrap();
+ validate(&set, None).unwrap();
+ let Block::Steps(s) = &mut set.blocks[0] else { panic!() };
+ s.items[0].text = item;
+ assert!(validate(&set, None).is_err());
+}
+
+/// renderers-D3: a value the chart can't scale never reaches it.
+#[test]
+fn values_out_of_range_are_refused_in_charts_and_metrics() {
+ let mut set = compute(&table("| Month | Visits |", &rows(6, |i| format!("| {} 2025 | {} |", MONTHS[i], 100 + i)))).unwrap();
+ for (v, ok) in [(1e15, true), (-1e15, true), (1e15 + 2.0, false), (9.0e15, false), (1e308, false), (f64::INFINITY, false), (f64::NAN, false), (-1e308, false)] {
+ let Block::Chart(c) = &mut set.blocks[0] else { panic!() };
+ c.points[1].values[0] = Some(v);
+ assert_eq!(validate(&set, None).is_ok(), ok, "{v}");
+ }
+ let mut set = compute("- **Revenue:** $4.2M\n- **Uptime:** 98%\n").unwrap();
+ for (v, ok) in [(4.2e6, true), (1e15, true), (1e16, false), (1e308, false), (f64::NAN, false), (f64::NEG_INFINITY, false)] {
+ let Block::Metrics(m) = &mut set.blocks[0] else { panic!() };
+ m.items[0].value = v;
+ assert_eq!(validate(&set, None).is_ok(), ok, "{v}");
+ }
+ // A reply that writes a number that long stays text
+ let big = table("| Month | Visits |", &rows(5, |i| format!("| {} 2025 | {}000 |", MONTHS[i], 100_000_000_000_000u64 + i as u64)));
+ assert_ne!(kind(&big), Some("chart"));
+}
diff --git a/src/server/smart_results/chart.rs b/src/server/smart_results/chart.rs
index 7a855962..2428af5d 100644
--- a/src/server/smart_results/chart.rs
+++ b/src/server/smart_results/chart.rs
@@ -42,8 +42,14 @@ fn chart(t: &Table, kind: ChartKind, series: std::ops::RangeInclusive<usize>) ->
if units.windows(2).any(|w| w[0] != w[1]) {
return None;
}
+ if units[0].is_none() && scales_differ(&columns) {
+ return None;
+ }
+ // The one unit as the cells write it (a column whose unit is only in its header takes it from
+ // the others), so every series carries the same `unit` the client compares
+ let unit = columns.iter().find_map(|(u, _)| *u).map(str::to_string);
let series = (1..cols)
- .map(|c| Series { key: format!("s{}", c - 1), label: t.header[c].to_string(), unit: columns[c - 1].0.map(str::to_string) })
+ .map(|c| Series { key: format!("s{}", c - 1), label: t.header[c].to_string(), unit: unit.clone() })
.collect();
let points = t
.rows
@@ -73,6 +79,20 @@ fn chart(t: &Table, kind: ChartKind, series: std::ops::RangeInclusive<usize>) ->
})
}
+/// How many times larger one series' biggest value may be than another's before they stop sharing
+/// an axis: past it the smaller series is a flat line at the bottom.
+const MAX_SCALE_RATIO: f64 = 10.0;
+
+/// Series with no unit of their own whose largest values differ by more than [`MAX_SCALE_RATIO`]
+/// (Revenue ~120000 beside Orders ~400). A unit in the cells or the header says the series are
+/// the same kind of quantity, so they keep sharing an axis. A series of zeros has no scale.
+fn scales_differ(columns: &[(Option<&str>, Vec<Option<f64>>)]) -> bool {
+ let tops: Vec<f64> =
+ columns.iter().map(|(_, v)| v.iter().flatten().fold(0.0_f64, |m, x| m.max(x.abs()))).filter(|m| *m > 0.0).collect();
+ let (min, max) = tops.iter().fold((f64::MAX, 0.0_f64), |(lo, hi), t| (lo.min(*t), hi.max(*t)));
+ tops.len() > 1 && max > min * MAX_SCALE_RATIO
+}
+
/// The unit a column's numbers are in: the affix its cells share (`$`, `%`, `ms`), or for bare
/// numbers the bracketed end of its header (`Price (EUR)`, `Rating [1-5]`). Compared as written,
/// so `€` and `EUR` count as two units and the chart abstains.
@@ -141,12 +161,14 @@ fn series_values<'a>(cells: impl Iterator<Item = &'a str>) -> Option<(Option<&'a
/// The numbers of one column as values, read with one locale for the whole column (`1,299.00`
/// says `,` groups and `.` is the decimal point). `None` when the two readings both fit and
-/// disagree (`1,299` alone: 1299 or 1.299).
+/// disagree (`1,299` beside `1.299`), unless every number that has a separator is grouped with
+/// commas in threes (`4,100`, `1,204`, `980`): then the column has one reading, and `1,204` is 1204.
pub(super) fn column_values(numbers: &[&str]) -> Option<Vec<f64>> {
let dot: Option<Vec<f64>> = numbers.iter().map(|n| reading(n, ',', '.')).collect();
let comma: Option<Vec<f64>> = numbers.iter().map(|n| reading(n, '.', ',')).collect();
match (dot, comma) {
- (Some(d), Some(c)) => (d == c).then_some(d),
+ (Some(d), Some(c)) if d == c => Some(d),
+ (Some(d), Some(_)) => numbers.iter().all(|n| !n.contains('.')).then_some(d),
(Some(d), None) => Some(d),
(None, Some(c)) => Some(c),
(None, None) => None,
@@ -203,7 +225,7 @@ pub(super) fn metrics_table(t: &Table) -> Option<Metrics> {
let mut items = Vec::new();
let mut units = HashSet::new();
for (i, r) in t.rows.iter().enumerate() {
- if when_like(r[0]) || !r[0].chars().any(char::is_alphabetic) {
+ if when_like(r[0]) || version_label(r[0]) || !r[0].chars().any(char::is_alphabetic) {
return None;
}
let v = metric_value(r[1])?;
@@ -235,6 +257,14 @@ pub(super) struct MetricValue<'a> {
pub note: Option<&'a str>,
}
+/// Words after a number that make it a version (`20.11 LTS`, `1.76 nightly`), not a quantity.
+const VERSION_WORDS: [&str; 10] = ["lts", "stable", "beta", "alpha", "nightly", "rc", "preview", "canary", "snapshot", "latest"];
+
+/// A label that says its value is a version (`Version`, `Node version`).
+pub(super) fn version_label(label: &str) -> bool {
+ label.split(|c: char| !c.is_alphanumeric()).any(|w| w.eq_ignore_ascii_case("version") || w.eq_ignore_ascii_case("versions"))
+}
+
/// A value that starts `s`: an optional currency prefix (`$`, `EUR `), a number, an optional unit
/// suffix (`%`, ` ms`, `M`), then the rest as the note. `None` when `s` doesn't start with one, or
/// the number is a time, a range, a date or unsure in locale.
@@ -306,7 +336,11 @@ pub(super) fn metric_value(s: &str) -> Option<MetricValue<'_>> {
let unit = &rest[lead..lead + word];
let ends = rest[lead + word..].chars().next().is_none_or(|c| !c.is_alphanumeric());
let time = ["am", "pm", "a.m", "p.m"].contains(&unit.to_lowercase().as_str());
- if time {
+ if time || VERSION_WORDS.contains(&unit.to_lowercase().as_str()) {
+ return None;
+ }
+ // Digits in groups (`555 0100`, `555 123 4567`) are a phone number, not a quantity
+ if word == 0 && lead == 1 && rest[1..].starts_with(|c: char| c.is_ascii_digit()) {
return None;
}
if word > 0 && unit.chars().count() <= 8 && ends && (lead == 0 || word <= 8) {
@@ -407,6 +441,12 @@ pub(super) fn when_like(label: &str) -> bool {
}
}
+/// A weekday on its own (`Mon`, `**Friday**`): it says when, but not whether it is ahead or done.
+pub(super) fn bare_weekday(label: &str) -> bool {
+ let mut words = label.trim().trim_matches(['*', '_']).split_whitespace();
+ matches!((words.next(), words.next()), (Some(w), None) if weekday(w))
+}
+
fn year(w: &str) -> bool {
w.len() == 4 && w.parse::<u32>().is_ok_and(|y| (1900..=2100).contains(&y))
}
diff --git a/src/server/smart_results/items.rs b/src/server/smart_results/items.rs
index e0440a80..5e92d094 100644
--- a/src/server/smart_results/items.rs
+++ b/src/server/smart_results/items.rs
@@ -1,9 +1,9 @@
//! Top-level lists: metrics, findings, cards, timeline, checklist and facts, and the steps block
//! every steps variant shares (plan §A.4). Every value is a slice of the item as written.
-use super::chart::{metric_value, when_like};
+use super::chart::{bare_weekday, metric_value, version_label, when_like};
use super::selector::{is_task, words, List};
-use super::validate::has_html;
+use super::validate::{has_html, has_plain_host};
use super::{
Card, Cards, Fact, Facts, Finding, Findings, Metric, Metrics, Provenance, Ref, Severity, Source, Step, Steps,
Variant,
@@ -81,7 +81,7 @@ pub(super) fn metrics(l: &List) -> Option<Metrics> {
let mut items = Vec::new();
for (i, t) in l.items.iter().enumerate() {
let x = labeled(t).filter(|x| x.sep == ':')?;
- if when_like(x.label) || x.label.starts_with(|c: char| c.is_ascii_digit()) {
+ if when_like(x.label) || version_label(x.label) || x.label.starts_with(|c: char| c.is_ascii_digit()) {
return None;
}
let v = metric_value(x.rest)?;
@@ -172,7 +172,7 @@ fn card_head(t: &str) -> Option<(&str, Option<&str>, &str)> {
if title.contains(['[', ']']) || !url.starts_with("https://") || url.len() <= 8 {
return None;
}
- if url.contains(|c: char| c.is_whitespace() || matches!(c, '(' | '<' | '>' | '"' | '\'' | '`')) {
+ if url.contains(|c: char| c.is_whitespace() || matches!(c, '(' | '<' | '>' | '"' | '\'' | '`')) || !has_plain_host(url) {
return None;
}
// Link text that looks like another address would hide where the link goes
@@ -344,6 +344,10 @@ pub(super) fn timeline(l: &List) -> Option<Steps> {
}
items.push((x.rest.to_string(), None, Some(x.label.to_string())));
}
+ // "Monday: wrote tests" may be a recap as well as a plan: weekdays alone don't make a timeline
+ if items.iter().all(|(_, _, when)| when.as_deref().is_some_and(bare_weekday)) {
+ return None;
+ }
Some(steps_block(l, Variant::Timeline, items))
}
diff --git a/src/server/smart_results/present_result.rs b/src/server/smart_results/present_result.rs
index 64d9e876..ab5fc8af 100644
--- a/src/server/smart_results/present_result.rs
+++ b/src/server/smart_results/present_result.rs
@@ -2,13 +2,17 @@
//! deserves. Nothing it declares is shown unless it is grounded in the final reply, checked when
//! the message is stored (after any re-prompt), never when the tool is called:
//!
-//! - a `comparison` must name the table of the reply it stands for (`source`), and every row it
-//! declares must be a row of that table: each cell found in the same row, so a value moved under
-//! another label is refused (a call without `source` is refused);
-//! - `steps` must name the numbered list of the reply they stand for (`source`), and every item must
-//! quote an item of that list;
-//! - every number equals a number in the reply, every URL is a link in the reply (never plain text,
-//! never with a login in it), and nothing is HTML.
+//! - a `comparison` must name the table of the reply it stands for (`source`) and be all of it:
+//! the same columns and rows, every header and cell the same text at the same position (markdown,
+//! case and punctuation aside), so a value moved under another label is refused (a call without
+//! `source` is refused);
+//! - `steps` must name the numbered list of the reply they stand for (`source`) and be all of it:
+//! the same items in the same order (a task list is never declared as steps);
+//! - every URL is a link in the reply (never plain text, never with a login in it), and nothing is
+//! HTML.
+//!
+//! That is what the client checks before it draws a declared block in place of the reply's own, so
+//! a block that grounds here is one that is drawn.
//!
//! Only the last call that was valid when made counts. If it doesn't ground, the block is dropped
//! (logged) and the deterministic selectors run on the reply as if the tool had never been called.
@@ -22,7 +26,7 @@ use crate::mcp::SELF_SERVER_NAME;
use crate::server::continuity::SelfScope;
use crate::server::AppState;
-use super::selector::{lists_of, tables_of};
+use super::selector::{is_task, lists_of, plain, tables_of};
use super::{Block, Column, Comparison, Provenance, ResultSet, Row, Source, Step, Steps, VERSION};
const NAME: &str = "present_result";
@@ -36,7 +40,7 @@ pub fn handles(name: &str) -> bool {
pub fn tools() -> Vec<Value> {
vec![json!({
"name": NAME,
- "description": "Optional. Declare the one block kwant should draw for your final reply (a comparison table, a numbered-steps list), only when the answer's data reads better that way than as plain text; never for a simple answer, and never instead of writing the reply. The data must match your reply text exactly: every label, number and link is checked against it, and a call that doesn't match is dropped and the plain reply is shown. For a comparison, `source` is required: the index (from 0) of the table in your reply that it describes. Call it once, just before your final reply. Types today: comparison and steps; kwant draws charts, metrics, facts, cards and findings from your reply's own structure (use '**Label:** value' lines for key numbers).",
+ "description": "Optional. Declare the one block kwant should draw for your final reply (a comparison table, a numbered-steps list), only when the answer's data reads better that way than as plain text; never for a simple answer, and never instead of writing the reply. The data must match your reply text exactly: every label, cell, item and link is checked against it, and a call that doesn't match is dropped and the plain reply is shown. For a comparison, `source` is required: the index (from 0) of the table in your reply that it describes. Call it once, just before your final reply. Types today: comparison and steps; kwant draws charts, metrics, facts, cards and findings from your reply's own structure (use '**Label:** value' lines for key numbers).",
"inputSchema": {
"type": "object",
"properties": {
@@ -50,7 +54,7 @@ pub fn tools() -> Vec<Value> {
},
"data": {
"type": "object",
- "description": "comparison: {columns: [{label, numeric?, unit?}], rows: [{cells: [string, ...]}]}, 3-50 rows and 2-8 columns, cells exactly as in your table. steps: {items: [string, ...]}, 3-15 items, each quoting an item of that list.",
+ "description": "comparison: {columns: [{label, numeric?, unit?}], rows: [{cells: [string, ...]}]}, 3-50 rows and 2-8 columns, every header and cell exactly as in your table: all of its rows and columns, in its order. steps: {items: [string, ...]}, 3-15 items: all the items of that list, in its order.",
},
},
"required": ["type", "data"],
@@ -204,28 +208,40 @@ fn steps(data: &Value, source: Option<(bool, usize)>) -> Result<Block, String> {
}
/// `declared` held to `reply`, as a block with `bot_declared` provenance, or the reason it isn't.
+///
+/// A declaration is the whole table (or numbered list) it names, in the same order, because that
+/// is what the client checks before it draws the block in place of the reply's own: same number of
+/// columns, rows and items, every header, cell and item the same text (markdown, case and
+/// punctuation aside) with the same numbers in the same order, so punctuation inside a number is
+/// never aside: "26.50" is not "2650" and "-3" is not "3". A declaration the client would refuse
+/// is refused here, so a stored block is always one that is drawn.
fn ground(declared: Declared, reply: &str, tool_call_id: String) -> Result<Block, String> {
let Declared { mut block, source } = declared;
let links = reply_links(reply);
- let numbers = reply_numbers(reply);
match &mut block {
Block::Comparison(c) => {
let (_, index) = source.ok_or("a comparison without a source")?;
let table = tables_of(reply).into_iter().find(|t| t.index == index).ok_or("no table at that index")?;
- if c.columns.iter().any(|col| !has_label(&table.header, &col.label)) {
- return Err("a column label isn't in that table's header".into());
+ if c.columns.len() != table.header.len() {
+ return Err("the columns aren't all of that table's columns".into());
+ }
+ if c.rows.len() != table.rows.len() {
+ return Err("the rows aren't all of that table's rows".into());
+ }
+ if c.columns.iter().zip(&table.header).any(|(col, h)| !same_cell(&col.label, h)) {
+ return Err("a column label isn't the table's header at that position".into());
}
for col in &c.columns {
if col.unit.as_deref().is_some_and(|u| !normalize(reply).contains(&normalize(u))) {
return Err("a unit isn't in the reply".into());
}
}
- for row in &c.rows {
+ for (row, table_row) in c.rows.iter().zip(&table.rows) {
for cell in &row.cells {
check_urls(cell, &links)?;
}
- if !table.rows.iter().any(|t| row.cells.iter().all(|cell| table_row_has(t, cell))) {
- return Err("a row doesn't match any row of that table".into());
+ if row.cells.len() != table_row.len() || row.cells.iter().zip(table_row).any(|(a, b)| !same_cell(a, b)) {
+ return Err("a row doesn't match the table's row at that position".into());
}
}
c.provenance = Provenance::bot_declared(tool_call_id);
@@ -233,14 +249,17 @@ fn ground(declared: Declared, reply: &str, tool_call_id: String) -> Result<Block
Block::Steps(s) => {
let (_, index) = source.ok_or("steps without a source")?;
let list = lists_of(reply).into_iter().find(|l| l.index == index).ok_or("no list at that index")?;
- for item in &s.items {
+ if s.items.len() != list.items.len() {
+ return Err("the steps aren't all of that list's items".into());
+ }
+ // A task list is drawn as one (with its done marks) or not at all, never as plain steps
+ if list.items.iter().any(|t| is_task(t)) {
+ return Err("that list is a task list".into());
+ }
+ for (item, listed) in s.items.iter().zip(&list.items) {
check_urls(&item.text, &links)?;
- let wanted = normalize(&item.text);
- if wanted.is_empty() || !list.items.iter().any(|t| normalize(t).contains(&wanted)) {
- return Err("a step isn't an item of that list".into());
- }
- if !string_numbers(&item.text).iter().all(|n| numbers.iter().any(|r| same(*r, *n))) {
- return Err("a number isn't in the reply".into());
+ if !same_cell(&item.text, listed) {
+ return Err("a step isn't the list's item at that position".into());
}
}
s.provenance = Provenance::bot_declared(tool_call_id);
@@ -250,27 +269,57 @@ fn ground(declared: Declared, reply: &str, tool_call_id: String) -> Result<Block
Ok(block)
}
-fn has_label(header: &[String], label: &str) -> bool {
- let want = normalize(label);
- !want.is_empty() && header.iter().any(|h| normalize(h).contains(&want))
+/// The text the client compares by: markdown out, lowercase, letters and digits only.
+fn match_key(s: &str) -> String {
+ plain(s).to_lowercase().chars().filter(|c| c.is_alphanumeric()).collect()
+}
+
+/// `a` and `b` read as the same text, and not as nothing.
+fn same_text(a: &str, b: &str) -> bool {
+ let key = match_key(a);
+ !key.is_empty() && key == match_key(b)
+}
+
+/// `a` and `b` are the same text (letters and digits, as the client compares) and carry the same
+/// numbers in the same order: same values, same signs, same decimal separators ("1.5" is not "15",
+/// "1,5" is not "1.5", "-3" is not "3"). A thousands comma is not a difference ("1,800" is 1800).
+fn same_cell(a: &str, b: &str) -> bool {
+ same_text(a, b) && same_numbers(&string_numbers(&plain(a)), &string_numbers(&plain(b)))
}
-/// `cell` is found in one cell of the reply's table row `row`: every word of it is in that table
-/// cell (markdown and case aside), and a number in it equals a number there, however the reply
-/// formats it ("1800" is "1,800", "26.5" is "26.50"; "5" is never "15").
-fn table_row_has(row: &[String], cell: &str) -> bool {
- let words: Vec<String> = normalize(cell).split_whitespace().map(str::to_string).collect();
- if words.is_empty() {
- return false;
+fn same_numbers(a: &[f64], b: &[f64]) -> bool {
+ a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() <= x.abs().max(y.abs()) * 1e-9 + 1e-9)
+}
+
+/// Every number in `s`: digits with an optional leading `-` and a decimal point; `1,234,567` with
+/// thousands separators is one number, `1,5` is two.
+fn string_numbers(s: &str) -> Vec<f64> {
+ let mut nums = Vec::new();
+ let mut cur = String::new();
+ let flush = |cur: &mut String, nums: &mut Vec<f64>| {
+ let negative = cur.starts_with('-');
+ let token = cur.trim_matches(|c| matches!(c, '.' | ',' | '-')).to_string();
+ cur.clear();
+ if token.is_empty() || !token.chars().any(|c| c.is_ascii_digit()) {
+ return;
+ }
+ let groups: Vec<&str> = token.split(',').collect();
+ let thousands = groups.len() > 1 && !groups[0].is_empty() && groups[0].len() <= 3 && groups[1..].iter().all(|g| g.len() >= 3 && g.chars().take(3).all(|c| c.is_ascii_digit()));
+ let parts: Vec<String> = if thousands { vec![groups.join("")] } else { groups.iter().map(|g| g.to_string()).collect() };
+ for p in parts {
+ if let Ok(n) = p.parse::<f64>() {
+ nums.push(if negative { -n } else { n });
+ }
+ }
+ };
+ for c in s.chars().chain(std::iter::once(' ')) {
+ if c.is_ascii_digit() || matches!(c, '.' | ',') || (c == '-' && cur.is_empty()) {
+ cur.push(c);
+ } else {
+ flush(&mut cur, &mut nums);
+ }
}
- row.iter().any(|c| {
- let text = normalize(c);
- let numbers = string_numbers(&text);
- words.iter().all(|w| match parse_number(w) {
- Some(n) => numbers.iter().any(|r| same(*r, n)),
- None => text.contains(w.as_str()),
- })
- })
+ nums
}
/// Refuses a URL that isn't a link in the reply (a markdown link or `<autolink>`; the same URL as
@@ -327,56 +376,6 @@ fn normalize(s: &str) -> String {
stripped.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase()
}
-fn same(a: f64, b: f64) -> bool {
- (a - b).abs() <= a.abs().max(b.abs()) * 1e-9 + 1e-9
-}
-
-/// `s` as a number when all of it is one ("12.50", "1,000", "$9", "-3"); a currency or percent
-/// sign around it is allowed.
-fn parse_number(s: &str) -> Option<f64> {
- let t = s.trim().trim_matches(|c: char| matches!(c, '$' | '€' | '£' | '%' | ' '));
- let nums = string_numbers(t);
- let digits = t.chars().filter(char::is_ascii_digit).count();
- let shaped = t.chars().all(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-'));
- (nums.len() == 1 && digits > 0 && shaped).then(|| nums[0])
-}
-
-/// Every number in `s`: digits with an optional leading `-` and a decimal point; `1,234,567` with
-/// thousands separators is one number, `1,5` is two.
-fn string_numbers(s: &str) -> Vec<f64> {
- let mut nums = Vec::new();
- let mut cur = String::new();
- let flush = |cur: &mut String, nums: &mut Vec<f64>| {
- let negative = cur.starts_with('-');
- let token = cur.trim_matches(|c| matches!(c, '.' | ',' | '-')).to_string();
- cur.clear();
- if token.is_empty() || !token.chars().any(|c| c.is_ascii_digit()) {
- return;
- }
- let body = token.as_str();
- let groups: Vec<&str> = body.split(',').collect();
- let thousands = groups.len() > 1 && !groups[0].is_empty() && groups[0].len() <= 3 && groups[1..].iter().all(|g| g.len() >= 3 && g.chars().take(3).all(|c| c.is_ascii_digit()));
- let parts: Vec<String> = if thousands { vec![groups.join("")] } else { groups.iter().map(|g| g.to_string()).collect() };
- for p in parts {
- if let Ok(n) = p.parse::<f64>() {
- nums.push(if negative { -n } else { n });
- }
- }
- };
- for c in s.chars().chain(std::iter::once(' ')) {
- if c.is_ascii_digit() || matches!(c, '.' | ',') || (c == '-' && cur.is_empty()) {
- cur.push(c);
- } else {
- flush(&mut cur, &mut nums);
- }
- }
- nums
-}
-
-fn reply_numbers(reply: &str) -> Vec<f64> {
- string_numbers(reply)
-}
-
#[cfg(test)]
#[path = "present_result_tests.rs"]
mod tests;
diff --git a/src/server/smart_results/present_result_tests.rs b/src/server/smart_results/present_result_tests.rs
index 6a7a0722..063db547 100644
--- a/src/server/smart_results/present_result_tests.rs
+++ b/src/server/smart_results/present_result_tests.rs
@@ -13,8 +13,8 @@ fn comparison_args() -> Value {
"columns": [{"label": "Plan"}, {"label": "Price", "numeric": true}, {"label": "Seats", "numeric": true}],
"rows": [
{"cells": ["Basic", "EUR 12", "1"]},
- {"cells": ["Team", "EUR 1800", "5"]},
- {"cells": ["Business", "EUR 26.5", "20"]},
+ {"cells": ["Team", "EUR 1,800", "5"]},
+ {"cells": ["Business", "EUR 26.50", "20"]},
],
},
})
@@ -76,7 +76,7 @@ fn a_matching_comparison_is_kept_as_bot_declared() {
let Block::Comparison(c) = &b else { panic!() };
assert_eq!(c.provenance, Provenance::bot_declared("t1".into()));
assert_eq!(c.source.index, Some(0));
- assert_eq!(rows(&b)[1], ["Team", "EUR 1800", "5"], "number formats may differ, values may not");
+ assert_eq!(rows(&b)[1], ["Team", "EUR 1,800", "5"]);
let set = ResultSet { version: VERSION, blocks: vec![b] };
assert!(super::super::validate(&set, None).is_ok());
}
@@ -115,21 +115,22 @@ fn an_invented_number_or_label_is_refused() {
}
#[test]
-fn numbers_compare_by_value_with_separators() {
- for cell in ["EUR 1,800", "1800", "1800.0"] {
+fn a_number_is_the_cell_s_own_text_not_another_format_of_it() {
+ // The client matches a cell by its text, so "1800" is not the table's "EUR 1,800"
+ for cell in ["1800", "1800.0", "EUR 18,000"] {
+ let args = with(comparison_args(), |a| a["data"]["rows"][1]["cells"][1] = json!(cell));
+ assert!(pick(REPLY, args).is_none(), "{cell}");
+ }
+ // Case and the thousands comma are not a difference to the client (letters and digits only)
+ for cell in ["eur 1,800", "EUR 1800"] {
let args = with(comparison_args(), |a| a["data"]["rows"][1]["cells"][1] = json!(cell));
assert!(pick(REPLY, args).is_some(), "{cell}");
}
- assert_eq!(string_numbers("1,234,567 and 1,5 and -3.5 and 12%"), vec![1234567.0, 1.0, 5.0, -3.5, 12.0]);
- assert!(same(26.5, 26.50));
- assert!(!same(26.5, 26.51));
- assert_eq!(parse_number("$9"), Some(9.0));
- assert_eq!(parse_number("Team 5"), None);
}
#[test]
fn urls_must_be_links_in_the_reply() {
- let args = with(comparison_args(), |a| a["data"]["rows"][2]["cells"][0] = json!("Business https://example.com/biz"));
+ let args = with(comparison_args(), |a| a["data"]["rows"][2]["cells"][0] = json!("Business"));
assert!(pick(REPLY, args).is_some(), "the reply links it");
let plain = "| Plan | Price |\n|---|---|\n| A | 1 |\n| B | 2 |\n| C | https://example.com/c |\n";
let args = json!({"type": "comparison", "source": {"kind": "markdown_table", "index": 0},
@@ -196,21 +197,23 @@ fn injection_text_in_the_reply_cannot_widen_the_call() {
#[test]
fn steps_must_quote_the_list_they_name() {
+ let reply = "Do this:\n\n1. Install the tool\n2. Run `kwant init`\n3. See [the guide](https://example.com/guide)\n";
let ok = ["Install the tool", "Run `kwant init`", "See [the guide](https://example.com/guide)"];
- let b = pick(STEPS_REPLY, steps_args(&ok, Some(0))).expect("grounded in list 0");
+ let b = pick(reply, steps_args(&ok, Some(0))).expect("grounded in list 0");
let Block::Steps(s) = &b else { panic!() };
assert_eq!(s.provenance, Provenance::bot_declared("t1".into()));
assert_eq!(s.source.index, Some(0));
- assert!(pick(STEPS_REPLY, steps_args(&ok, None)).is_none(), "steps need a source");
+ assert!(pick(reply, steps_args(&ok, None)).is_none(), "steps need a source");
assert!(declared(&steps_args(&ok, None)).is_err());
- assert!(pick(STEPS_REPLY, steps_args(&ok, Some(1))).is_none(), "no list at index 1");
+ assert!(pick(reply, steps_args(&ok, Some(1))).is_none(), "no list at index 1");
let invented = ["Install the tool", "Run `kwant init`", "Delete the database"];
- assert!(pick(STEPS_REPLY, steps_args(&invented, Some(0))).is_none());
- let plain_url = ["Install the tool", "Run `kwant init`", "Open https://example.com/start and sign in"];
- assert!(pick(STEPS_REPLY, steps_args(&plain_url, Some(0))).is_none(), "the start URL is plain text in the reply");
- assert!(pick(STEPS_REPLY, steps_args(&ok[..2], Some(0))).is_none(), "fewer than 3 steps");
+ assert!(pick(reply, steps_args(&invented, Some(0))).is_none());
+ assert!(pick(reply, steps_args(&ok[..2], Some(0))).is_none(), "fewer than 3 steps");
let wrong_table = with(steps_args(&ok, Some(0)), |a| a["source"]["kind"] = json!("markdown_table"));
assert!(declared(&wrong_table).is_err());
+ // STEPS_REPLY has a fourth item with the start URL as plain text
+ let three = ["Install the tool", "Run `kwant init`", "Open https://example.com/start and sign in"];
+ assert!(pick(STEPS_REPLY, steps_args(&three, Some(0))).is_none(), "not all four items, and a plain-text URL");
let numbered = "1. Pay 5 now\n2. Pay 6 later\n3. Done\n";
assert!(pick(numbered, steps_args(&["Pay 5 now", "Pay 6 later", "Done"], Some(0))).is_some());
assert!(pick(numbered, steps_args(&["Pay 7 now", "Pay 6 later", "Done"], Some(0))).is_none());
@@ -273,3 +276,141 @@ fn the_tool_result_says_what_was_wrong() {
let why = declared(&json!({"type": "comparison", "data": {}})).err().unwrap();
assert!(why.contains("source"), "{why}");
}
+
+// --- typed-M1 (Rigel): a declared block is held to what the client checks before it draws one
+
+const SEATS: &str = "| Plan | Price | Seats |\n|---|---|---|\n| Basic | 12 EUR | 1 |\n| Team | EUR 29 | 5 |\n| Business | EUR 49 | 20 |\n";
+
+fn seats_args(f: impl FnOnce(&mut Value)) -> Value {
+ with(
+ json!({"type": "comparison", "source": {"kind": "markdown_table", "index": 0},
+ "data": {"columns": [{"label": "Plan"}, {"label": "Price", "numeric": true}, {"label": "Seats", "numeric": true}],
+ "rows": [{"cells": ["Basic", "12 EUR", "1"]}, {"cells": ["Team", "EUR 29", "5"]}, {"cells": ["Business", "EUR 49", "20"]}]}}),
+ f,
+ )
+}
+
+#[test]
+fn a_comparison_is_the_whole_table_cell_for_cell() {
+ assert!(pick(SEATS, seats_args(|_| {})).is_some());
+ // The Seats case: the value reads "29 EUR" where the table says "EUR 29"; the client would refuse it
+ assert!(pick(SEATS, seats_args(|a| a["data"]["rows"][1]["cells"][1] = json!("29 EUR"))).is_none());
+ // A number in another format is another cell
+ assert!(pick(REPLY, with(comparison_args(), |a| a["data"]["rows"][2]["cells"][1] = json!("EUR 26.5"))).is_none(), "26.5 is not 26.50");
+ // Fewer rows or columns than the table
+ assert!(pick(SEATS, seats_args(|a| a["data"]["rows"] = json!([{"cells": ["Basic", "12 EUR", "1"]}, {"cells": ["Team", "EUR 29", "5"]}]))).is_none());
+ let two_cols = seats_args(|a| {
+ a["data"]["columns"] = json!([{"label": "Plan"}, {"label": "Seats", "numeric": true}]);
+ a["data"]["rows"] = json!([{"cells": ["Basic", "1"]}, {"cells": ["Team", "5"]}, {"cells": ["Business", "20"]}]);
+ });
+ assert!(pick(SEATS, two_cols).is_none(), "a column left out");
+ // Rows or columns in another order
+ let swapped = seats_args(|a| a["data"]["rows"] = json!([{"cells": ["Team", "EUR 29", "5"]}, {"cells": ["Basic", "12 EUR", "1"]}, {"cells": ["Business", "EUR 49", "20"]}]));
+ assert!(pick(SEATS, swapped).is_none(), "rows out of order");
+ let cols = seats_args(|a| {
+ a["data"]["columns"] = json!([{"label": "Plan"}, {"label": "Seats", "numeric": true}, {"label": "Price", "numeric": true}]);
+ a["data"]["rows"] = json!([{"cells": ["Basic", "1", "12 EUR"]}, {"cells": ["Team", "5", "EUR 29"]}, {"cells": ["Business", "20", "EUR 49"]}]);
+ });
+ assert!(pick(SEATS, cols).is_none(), "columns out of order");
+ // A header that only contains the label
+ assert!(pick(SEATS, seats_args(|a| a["data"]["columns"][1]["label"] = json!("Pric"))).is_none());
+}
+
+#[test]
+fn markdown_and_separators_do_not_make_a_cell_another_cell() {
+ let ok = with(comparison_args(), |a| {
+ a["data"]["rows"][1]["cells"][1] = json!("EUR 1,800");
+ a["data"]["rows"][2]["cells"][0] = json!("**Business**");
+ a["data"]["rows"][2]["cells"][1] = json!("EUR 26.50");
+ });
+ assert!(pick(REPLY, ok).is_some(), "the client matches letters and digits only");
+ let b = pick(REPLY, with(comparison_args(), |a| a["data"]["rows"][2]["cells"][1] = json!("EUR 26.50"))).expect("grounded");
+ let set = ResultSet { version: VERSION, blocks: vec![b] };
+ assert!(super::super::validate(&set, None).is_ok());
+}
+
+#[test]
+fn steps_are_the_whole_numbered_list_in_order() {
+ let reply = "Do this:\n\n1. Install the tool\n2. Run `kwant init`\n3. See [the guide](https://example.com/guide)\n";
+ let all = ["Install the tool", "Run `kwant init`", "See [the guide](https://example.com/guide)"];
+ assert!(pick(reply, steps_args(&all, Some(0))).is_some());
+ assert!(pick(reply, steps_args(&all[..2], Some(0))).is_none(), "fewer than the list");
+ assert!(pick(reply, steps_args(&[all[1], all[0], all[2]], Some(0))).is_none(), "out of order");
+ assert!(pick(reply, steps_args(&[all[0], all[1], all[1]], Some(0))).is_none(), "an item twice");
+ let part = ["Install", "Run `kwant init`", "See [the guide](https://example.com/guide)"];
+ assert!(pick(reply, steps_args(&part, Some(0))).is_none(), "half an item is not the item");
+ let four = "1. One\n2. Two\n3. Three\n4. Four\n";
+ assert!(pick(four, steps_args(&["One", "Two", "Three"], Some(0))).is_none(), "the list has four");
+ assert!(pick(four, steps_args(&["One", "Two", "Three", "Four"], Some(0))).is_some());
+ // A task list is a checklist: it never becomes numbered steps
+ let tasks = "1. [ ] One\n2. [x] Two\n3. [ ] Three\n";
+ assert!(pick(tasks, steps_args(&["[ ] One", "[x] Two", "[ ] Three"], Some(0))).is_none());
+ assert!(pick(tasks, steps_args(&["One", "Two", "Three"], Some(0))).is_none());
+}
+
+// --- Rigel on #251: punctuation inside a number is not aside. The words match by letters and
+// digits, and the numbers in each cell must also be the reply's, in order, sign and separator.
+
+fn price_table(cell: &str) -> String {
+ format!("| Plan | Price |\n|---|---|\n| Basic | {cell} |\n| Team | 9 |\n| Business | 7 |\n")
+}
+
+fn price_args(cell: &str) -> Value {
+ json!({"type": "comparison", "source": {"kind": "markdown_table", "index": 0},
+ "data": {"columns": [{"label": "Plan"}, {"label": "Price", "numeric": true}],
+ "rows": [{"cells": ["Basic", cell]}, {"cells": ["Team", "9"]}, {"cells": ["Business", "7"]}]}})
+}
+
+fn refused(reply_cell: &str, declared_cell: &str) -> bool {
+ pick(&price_table(reply_cell), price_args(declared_cell)).is_none()
+}
+
+#[test]
+fn t11_a_moved_decimal_point_in_a_price_is_refused() {
+ assert!(refused("EUR 26.50", "EUR 2650"));
+}
+
+#[test]
+fn t11b_a_moved_thousands_comma_is_refused() {
+ assert!(refused("EUR 1,800", "EUR 18,00"));
+}
+
+#[test]
+fn t11c_a_lost_minus_sign_is_refused() {
+ assert!(refused("-3", "3"));
+}
+
+#[test]
+fn t11d_an_added_decimal_point_is_refused() {
+ assert!(refused("12", "1.2"));
+}
+
+#[test]
+fn x04_a_lost_sign_on_a_percent_is_refused() {
+ assert!(refused("-3%", "3%"));
+}
+
+#[test]
+fn t08e_steps_with_a_changed_number_are_refused() {
+ let reply = "Do this:\n\n1. Install the tool\n2. Wait 1.5 hours\n3. Sign in\n";
+ assert!(pick(reply, steps_args(&["Install the tool", "Wait 15 hours", "Sign in"], Some(0))).is_none());
+ // control: the exact list is still drawn
+ assert!(pick(reply, steps_args(&["Install the tool", "Wait 1.5 hours", "Sign in"], Some(0))).is_some());
+}
+
+#[test]
+fn a_declaration_with_the_replys_exact_numbers_is_still_accepted() {
+ assert!(!refused("EUR 26.50", "EUR 26.50"));
+ assert!(!refused("EUR 1,800", "EUR 1,800"));
+ assert!(!refused("-3", "-3"));
+ assert!(!refused("12", "12"));
+ assert!(!refused("-3%", "-3%"));
+ // a thousands comma and plain digits are the same number, as the client reads them
+ assert!(!refused("EUR 1,800", "EUR 1800"));
+ // a link's target is not part of the cell's numbers
+ let reply = "| Plan | Price |\n|---|---|\n| [Basic](https://example.com/v2) | 5 |\n| Team | 9 |\n| Business | 7 |\n";
+ let args = json!({"type": "comparison", "source": {"kind": "markdown_table", "index": 0},
+ "data": {"columns": [{"label": "Plan"}, {"label": "Price", "numeric": true}],
+ "rows": [{"cells": ["Basic", "5"]}, {"cells": ["Team", "9"]}, {"cells": ["Business", "7"]}]}});
+ assert!(pick(reply, args).is_some());
+}
diff --git a/src/server/smart_results/validate.rs b/src/server/smart_results/validate.rs
index 09de068c..0a0280b2 100644
--- a/src/server/smart_results/validate.rs
+++ b/src/server/smart_results/validate.rs
@@ -3,6 +3,7 @@
use std::collections::HashSet;
use super::items::severity_of;
+use super::selector::plain;
use super::{AxisKind, Block, ChartKind, ResultSet, Role, Variant, 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,
@@ -79,7 +80,7 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
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()) {
+ if !labels.insert(label_key(&row.cells[0])) {
return Err(format!("row label {:?} repeats", row.cells[0]));
}
for cell in &row.cells {
@@ -123,7 +124,11 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
texts.push(unit);
}
}
- if !(3..=60).contains(&c.points.len()) {
+ // One shared axis means one unit; the client draws no chart whose series differ
+ if c.series.iter().any(|s| s.unit != c.series[0].unit) {
+ return Err("series in more than one unit".into());
+ }
+ if !(3..=60).contains(&c.points.len()) || c.chart_kind == ChartKind::Bar && c.points.len() < 5 {
return Err(format!("{} points", c.points.len()));
}
let mut xs = HashSet::new();
@@ -139,8 +144,8 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
if p.cells.len() != c.series.len() || p.values.len() != c.series.len() {
return Err(format!("point {k} has {} cells, {} values", p.cells.len(), p.values.len()));
}
- if p.values.iter().flatten().any(|v| !v.is_finite()) {
- return Err("a value that isn't a number".into());
+ if p.values.iter().flatten().any(|v| !in_range(*v)) {
+ return Err("a value that isn't a number or is out of range".into());
}
for cell in &p.cells {
check_cell(cell)?;
@@ -167,8 +172,8 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
}
check_text(&x.label, 200, "metric label")?;
check_text(&x.value_text, 100, "metric value")?;
- if !x.value.is_finite() {
- return Err("a value that isn't a number".into());
+ if !in_range(x.value) {
+ return Err("a value that isn't a number or is out of range".into());
}
texts.extend([x.label.as_str(), x.value_text.as_str()]);
if let Some(unit) = &x.unit {
@@ -238,7 +243,8 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
if let Some(url) = &x.url {
let safe = url.starts_with("https://")
&& url.len() <= 2048
- && !url.contains(|c: char| c.is_whitespace() || c.is_control() || matches!(c, '<' | '>' | '"' | '\'' | '`'));
+ && !url.contains(|c: char| c.is_whitespace() || c.is_control() || matches!(c, '<' | '>' | '"' | '\'' | '`'))
+ && has_plain_host(url);
if !safe {
return Err("a card link that isn't a plain https link".into());
}
@@ -248,7 +254,7 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
return Err("card meta".into());
}
for m in &x.meta {
- check_text(m, 100, "card meta")?;
+ check_text(m, 40, "card meta")?;
texts.push(m);
}
}
@@ -415,7 +421,7 @@ fn check_source(block: &Block) -> Result<(), String> {
/// A shown cell: at most 200 characters, no HTML; it may be empty (a gap).
fn check_cell(cell: &str) -> Result<(), String> {
- if cell.chars().count() > 200 {
+ if utf16_len(cell) > 200 {
return Err("a cell over 200 characters".into());
}
if has_html(cell) {
@@ -428,7 +434,7 @@ 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 {
+ if utf16_len(s) > max {
return Err(format!("a {what} over {max} characters"));
}
if has_html(s) {
@@ -437,6 +443,35 @@ fn check_text(s: &str, max: usize, what: &str) -> Result<(), String> {
Ok(())
}
+/// A text's length as the client counts it (UTF-16 units: an emoji is two), so a text the server
+/// stores is one the client's own limit lets through.
+fn utf16_len(s: &str) -> usize {
+ s.encode_utf16().count()
+}
+
+/// The largest number a value may be: what an SVG coordinate carries without turning every scaled
+/// position into NaN (the client's own bound, `MAX_VALUE` in `Chart.tsx`); below
+/// `Number.MAX_SAFE_INTEGER`.
+const MAX_VALUE: f64 = 1e15;
+
+fn in_range(v: f64) -> bool {
+ v.is_finite() && v.abs() <= MAX_VALUE
+}
+
+/// A row label as the client compares them: markdown out, whitespace collapsed, lowercase.
+fn label_key(label: &str) -> String {
+ plain(label).split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase()
+}
+
+/// A URL (already `https://`) with a host of its own and no login in front of it
+/// (`https://user:pw@host/`, `https://host@evil/`): an `@` after the host is part of the path.
+pub(super) fn has_plain_host(url: &str) -> bool {
+ let rest = url.strip_prefix("https://").or_else(|| url.strip_prefix("http://")).unwrap_or(url);
+ let authority = rest.split(['/', '?', '#', '\\']).next().unwrap_or("");
+ let host = authority.split(':').next().unwrap_or("");
+ !authority.contains('@') && !host.is_empty() && !url.contains('\\')
+}
+
/// 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)| {