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: a table cell's 200-character cap counts what it shows (#254)

Oleksandr Ivanchenkoc5127d0c1703
diff --git a/docs/smart-results.md b/docs/smart-results.md
index 01fc2a38..73c20b09 100644
--- a/docs/smart-results.md
+++ b/docs/smart-results.md
@@ -93,7 +93,7 @@ parsed from the cell as written, never computed; a cell without one is `null`, n
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.
+- Limits: a header or cell is at most 200 characters, a step at most 300, a unit at most 10. A header or cell counts what it shows: a markdown link `[text](url)` counts as its text, a bare URL in full, and a cell holds at most 1,000 characters raw.
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
diff --git a/frontend/src/components/results/Chart.tsx b/frontend/src/components/results/Chart.tsx
index 54abc510..a593596f 100644
--- a/frontend/src/components/results/Chart.tsx
+++ b/frontend/src/components/results/Chart.tsx
@@ -1,5 +1,5 @@
import React, { useEffect, useId, useMemo, useRef, useState } from 'react';
-import { ChartBlock, ChartPoint, ChartSeries, inRange, isNum, isObj, isText, optText, parseCommon, repeatsReply, uniqueIds } from '../../smartResults';
+import { ChartBlock, ChartPoint, ChartSeries, inRange, isCell, isNum, isObj, isText, optText, parseCommon, repeatsReply, uniqueIds } from '../../smartResults';
import type { RendererProps } from './registry';
import { ReplyText } from './ReplyText';
@@ -11,12 +11,12 @@ export function validChart(raw: unknown): ChartBlock | null {
if (!b) return null;
if (b.chart_kind !== 'line' && b.chart_kind !== 'bar') return null;
const x = b.x;
- if (!isObj(x) || !isText(x.label) || (x.kind !== 'time' && x.kind !== 'category')) return null;
+ if (!isObj(x) || !isCell(x.label) || (x.kind !== 'time' && x.kind !== 'category')) return null;
if (!inRange(b.series, 1, 4)) return null;
const series: ChartSeries[] = [];
const keys = new Set<string>();
for (const s of b.series as Record<string, unknown>[]) {
- if (!isObj(s) || !isText(s.key, 60) || keys.has(s.key) || !isText(s.label)) return null;
+ if (!isObj(s) || !isText(s.key, 60) || keys.has(s.key) || !isCell(s.label)) return null;
const unit = optText(s.unit, 40);
if (unit === undefined) return null;
keys.add(s.key);
@@ -30,8 +30,8 @@ export function validChart(raw: unknown): ChartBlock | null {
if (b.chart_kind === 'bar' && (b.points as unknown[]).length < 5) return null;
const points: ChartPoint[] = [];
for (const p of b.points as Record<string, unknown>[]) {
- if (!isText(p.x)) return null;
- if (!Array.isArray(p.cells) || p.cells.length !== series.length || !p.cells.every((c) => isText(c, 300, true))) return null;
+ if (!isCell(p.x)) return null;
+ if (!Array.isArray(p.cells) || p.cells.length !== series.length || !p.cells.every((c) => isCell(c, true))) return null;
// Finite and within what an SVG coordinate can carry: 1e308 turns every scaled y into NaN.
if (!Array.isArray(p.values) || p.values.length !== series.length || !p.values.every((v) => v === null || (isNum(v) && Math.abs(v) <= MAX_VALUE))) return null;
points.push({ id: p.id as string, x: p.x, cells: p.cells as string[], values: p.values as (number | null)[] });
diff --git a/frontend/src/smartResults.ts b/frontend/src/smartResults.ts
index 85e0dd59..0041075f 100644
--- a/frontend/src/smartResults.ts
+++ b/frontend/src/smartResults.ts
@@ -252,6 +252,22 @@ export const isObj = (v: unknown): v is Record<string, unknown> => typeof v ===
/** A string of at most `max` chars with no HTML tag; blank only when `empty`. */
export const isText = (v: unknown, max = MAX_TEXT, empty = false): v is string =>
typeof v === 'string' && v.length <= max && (empty || v.trim() !== '') && !HTML_TAG.test(v);
+/** The most a table cell or label may show (the server's `MAX_CELL`). */
+export const MAX_CELL = 200;
+/** The most a table cell may hold raw, URLs included (the server's `MAX_CELL_RAW`). */
+export const MAX_CELL_RAW = 1000;
+const MD_LINK = /!?\[([^\]]*)\]\([^)]*\)/g;
+/**
+ * A text's length as the reader sees it: a markdown link `[text](url)` counts as its text, since a
+ * source link's URL isn't shown; a bare URL is shown, so it counts. The server's `shown_len` agrees.
+ */
+export const shownLength = (s: string): number => s.replace(MD_LINK, '$1').length;
+/**
+ * A table cell or label, as the server's `cell_fits` takes it: at most `MAX_CELL` shown characters
+ * (`shownLength`) and `MAX_CELL_RAW` raw ones, no HTML tag; blank only when `empty`.
+ */
+export const isCell = (v: unknown, empty = false): v is string =>
+ typeof v === 'string' && v.length <= MAX_CELL_RAW && shownLength(v) <= MAX_CELL && (empty || v.trim() !== '') && !HTML_TAG.test(v);
/** isText, or null/absent (returned as null). `undefined` means invalid. */
export const optText = (v: unknown, max = MAX_TEXT): string | null | undefined => (v === null || v === undefined ? null : isText(v, max) ? v : undefined);
export const isIndex = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 0;
@@ -345,7 +361,7 @@ export function validComparison(raw: unknown): ComparisonBlock | null {
if (!inRange(cols, 2, 8) || !inRange(rows, 3, 50)) return null;
const columns: ComparisonColumn[] = [];
for (const [j, c] of cols.entries()) {
- if (!isObj(c) || typeof c.key !== 'string' || !isText(c.label) || typeof c.numeric !== 'boolean') return null;
+ if (!isObj(c) || typeof c.key !== 'string' || !isCell(c.label) || typeof c.numeric !== 'boolean') return null;
const unit = optText(c.unit, 40);
if (unit === undefined) return null;
const role = c.role === undefined || c.role === null ? (j === 0 ? 'label' : 'value') : c.role;
@@ -353,7 +369,7 @@ export function validComparison(raw: unknown): ComparisonBlock | null {
columns.push({ key: c.key, label: c.label, numeric: c.numeric, unit, role: role as ColumnRole });
}
if (new Set(columns.map((c) => c.key)).size !== columns.length) return null;
- const rowsOk = rows.every((r) => isObj(r) && inRange(r.cells, columns.length, columns.length) && r.cells.every((c) => isText(c, MAX_TEXT, true)));
+ const rowsOk = rows.every((r) => isObj(r) && inRange(r.cells, columns.length, columns.length) && r.cells.every((c) => isCell(c, true)));
if (!rowsOk || !uniqueIds(rows)) return null;
const typed = rows as unknown as ComparisonRow[];
const labels = typed.map((r) => plainText(r.cells[0]).toLowerCase());
diff --git a/frontend/tests/smartResultsCellLength.test.mjs b/frontend/tests/smartResultsCellLength.test.mjs
new file mode 100644
index 00000000..a301ebff
--- /dev/null
+++ b/frontend/tests/smartResultsCellLength.test.mjs
@@ -0,0 +1,93 @@
+// A table cell's 200-character cap counts what the reader sees: a markdown link `[text](url)` counts
+// as its text, a bare URL in full, and a cell holds at most 1,000 characters raw. The server's
+// `cell_fits` / `shown_len` (src/server/smart_results/validate.rs) count the same way; its test
+// `shown_length_counts_as_the_client_counts` (selector_tests.rs) holds the same cases as SHOWN_CASES.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const m = await loadBundled(`
+ export { shownLength, isCell, MAX_CELL, MAX_CELL_RAW, validComparison } from './src/smartResults';
+ export { validChart } from './src/components/results/Chart';
+ export { FIXTURES } from './src/components/results/fixtures';
+`);
+
+const SHOWN_CASES = [
+ ['plain', 5],
+ ['[Aldi](https://example.com/very/long/path)', 4],
+ ['![logo](https://example.com/l.png) text', 9],
+ ['see https://example.com/a', 25],
+ ['[a [b](u)', 4],
+ ['[a] (u)', 7],
+ ['[x](u', 5],
+ ['!x [y](z)', 4],
+ ['[](https://example.com)', 0],
+ ['😀[😀](https://example.com)', 4],
+ ['[a](b) and [c](d)', 7],
+ ['[a](b(c)d)', 3],
+];
+
+test('shownLength counts a link as its text, as the server does', () => {
+ for (const [s, n] of SHOWN_CASES) assert.equal(m.shownLength(s), n, s);
+});
+
+// Oleks's "Compare Aldi with Lidl": two cells were over 200 raw only because of their source links.
+const prices =
+ 'Basket of 20 staples €42.07, about 4% less than Lidl in the latest test; private labels decide most of it ([Stiftung Warentest 2025](https://www.test.de/Discounter-Preisvergleich-Aldi-Lidl-Penny-Netto-5912345-0/?utm_source=chat))';
+const app =
+ 'Lidl Plus: weekly coupons, digital receipts and a scratch card ([Lidl Plus](https://www.lidl.de/c/lidl-plus/s10007311?utm_source=chatgpt.com&utm_medium=referral&utm_campaign=lidl-plus-coupons-and-digital-receipts-2025))';
+
+const aldi = (cell = prices) => ({
+ id: 'b-aldi',
+ type: 'comparison',
+ title: null,
+ source: { kind: 'markdown_table', index: 0 },
+ provenance: { kind: 'reply_text' },
+ columns: [
+ { key: 'c0', label: 'Point', numeric: false, unit: null, role: 'label' },
+ { key: 'c1', label: 'Aldi Süd', numeric: false, unit: null, role: 'value' },
+ { key: 'c2', label: 'Lidl', numeric: false, unit: null, role: 'value' },
+ ],
+ rows: [
+ { id: 'r0', cells: ['Prices', cell, 'Basket €44.02'] },
+ { id: 'r1', cells: ['Deals', 'Tighter range', 'More non-food deals'] },
+ { id: 'r2', cells: ['App', 'Nothing comparable', app] },
+ { id: 'r3', cells: ['Store feel', 'Quicker to shop', 'Bigger, more variety'] },
+ ],
+ highlight_row: null,
+ highlight_reason: null,
+});
+
+test('the Aldi table with long source links is a comparison the client keeps', () => {
+ assert.ok(prices.length > 200 && app.length > 200, 'over 200 raw');
+ assert.ok(m.shownLength(prices) < 200 && m.shownLength(app) < 200, 'under 200 shown');
+ const c = m.validComparison(aldi());
+ assert.ok(c, 'kept');
+ assert.equal(c.rows[0].cells[1], prices, 'the cell keeps its link');
+});
+
+test('a cell showing more than 200 characters is still refused', () => {
+ const url = `https://example.com/${'p'.repeat(300)}`;
+ assert.ok(m.isCell(`${'x'.repeat(197)} [ab](${url})`), '200 shown');
+ assert.equal(m.isCell(`${'x'.repeat(197)} [abc](${url})`), false, '201 shown');
+ assert.equal(m.validComparison(aldi(`${'x'.repeat(197)} [abc](${url})`)), null, 'a comparison with one');
+ assert.equal(m.isCell(`${'x'.repeat(10)} ${url}`), false, 'a bare URL counts in full');
+});
+
+test('a cell holds at most 1,000 characters raw', () => {
+ assert.equal(m.MAX_CELL, 200);
+ assert.equal(m.MAX_CELL_RAW, 1000);
+ const cell = (n) => `xxx [ab](https://example.com/${'p'.repeat(n)})`;
+ assert.equal(cell(970).length, 1000);
+ assert.ok(m.isCell(cell(970)), '1,000 raw');
+ assert.equal(m.isCell(cell(971)), false, '1,001 raw');
+ assert.equal(m.validComparison(aldi(cell(971))), null, 'a comparison with one');
+});
+
+test('chart cells and labels count the same way', () => {
+ const b = m.FIXTURES.chartLine.results.blocks[0];
+ assert.ok(m.validChart(b));
+ const link = `[Jul 2026](https://example.com/${'p'.repeat(300)})`;
+ assert.ok(m.validChart({ ...b, points: b.points.map((p, i) => (i ? p : { ...p, x: link })) }), 'a linked label');
+ assert.equal(m.validChart({ ...b, points: b.points.map((p, i) => (i ? p : { ...p, x: 'x'.repeat(201) })) }), null, '201 shown');
+});
diff --git a/src/server/smart_results/chart.rs b/src/server/smart_results/chart.rs
index 2428af5d..a15127ca 100644
--- a/src/server/smart_results/chart.rs
+++ b/src/server/smart_results/chart.rs
@@ -4,7 +4,7 @@
use std::collections::HashSet;
use super::selector::{currency, is_number, number_parts, plain, Table};
-use super::validate::has_html;
+use super::validate::{cell_fits, has_html};
use super::{Axis, AxisKind, Chart, ChartKind, Metric, Metrics, Point, Provenance, Series, Source};
/// A table with 4–60 rows whose first column is time-like in every row and whose other 1–4
@@ -110,13 +110,13 @@ fn column_unit(affix: Option<&str>, header: &str) -> Option<String> {
(!inner.is_empty()).then(|| inner.to_lowercase())
}
-/// Labels and cells a chart can show as they are: none empty in the header, none over 200
-/// characters, no HTML, no repeated label.
+/// Labels and cells a chart can show as they are: none empty in the header, each within
+/// `cell_fits` (200 shown characters), no HTML, no repeated label.
fn plain_cells(t: &Table) -> bool {
if t.header.iter().any(|h| h.is_empty()) {
return false;
}
- if t.header.iter().chain(t.rows.iter().flatten()).any(|c| c.chars().count() > 200 || has_html(c)) {
+ if t.header.iter().chain(t.rows.iter().flatten()).any(|c| !cell_fits(c) || has_html(c)) {
return false;
}
let mut seen = HashSet::new();
diff --git a/src/server/smart_results/selector.rs b/src/server/smart_results/selector.rs
index e956d3fb..7498aab9 100644
--- a/src/server/smart_results/selector.rs
+++ b/src/server/smart_results/selector.rs
@@ -11,7 +11,7 @@
use std::cell::OnceCell;
use std::collections::HashSet;
-use super::validate::has_html;
+use super::validate::{cell_fits, has_html};
use super::{chart, items};
use super::{Block, Column, Comparison, Provenance, Role, Row, Source, Steps, Variant, MAX_REPLY, PICK_REASON};
@@ -887,10 +887,11 @@ fn comparison(t: &Table, said: Option<&[String]>) -> Option<Comparison> {
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) {
+ // A cell is measured by what it shows: a source link counts as its text (`cell_fits`)
+ if t.header.iter().any(|h| h.is_empty() || !cell_fits(h)) {
return None;
}
- if t.rows.iter().any(|r| r.len() != cols || r.iter().any(|c| c.chars().count() > 200)) {
+ if t.rows.iter().any(|r| r.len() != cols || r.iter().any(|c| !cell_fits(c))) {
return None;
}
// Cells are shown as text, so a table with HTML in it stays markdown
diff --git a/src/server/smart_results/selector_tests.rs b/src/server/smart_results/selector_tests.rs
index b40d38c8..67398333 100644
--- a/src/server/smart_results/selector_tests.rs
+++ b/src/server/smart_results/selector_tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::server::smart_results::validate::{shown_len, MAX_CELL_RAW};
use crate::server::smart_results::{compute, validate, Block, ResultSet, MAX_PAYLOAD, PICK_REASON};
fn first(text: &str) -> Option<Block> {
@@ -62,6 +63,76 @@ fn a_two_option_table_with_a_row_per_point_is_a_comparison() {
assert_eq!(c.rows[0].cells, ["Prices", "Basket €42.07, about 4% less", "Basket €44.02"]);
}
+/// A cell's 200-character cap counts what the reader sees: a source link counts as its text, not its
+/// URL. Oleks's "Compare Aldi with Lidl" table stayed text because two cells were 238 and 221 raw
+/// characters, only because of the URLs in their links.
+#[test]
+fn a_cell_counts_a_source_link_as_its_text() {
+ let prices = "Basket of 20 staples €42.07, about 4% less than Lidl in the latest test; private labels \
+ decide most of it ([Stiftung Warentest 2025](https://www.test.de/Discounter-Preisvergleich-Aldi-Lidl-Penny-Netto-5912345-0/?utm_source=chat))";
+ let app = "Lidl Plus: weekly coupons, digital receipts and a scratch card ([Lidl Plus](https://www.lidl.de/c/lidl-plus/s10007311?utm_source=chatgpt.com&utm_medium=referral&utm_campaign=lidl-plus-coupons-and-digital-receipts-2025))";
+ assert!(prices.chars().count() > 200 && app.chars().count() > 200);
+ assert!(shown_len(prices) < 200 && shown_len(app) < 200);
+ let text = format!(
+ "They're close on price.\n\n| Point | Aldi Süd | Lidl |\n|---|---|---|\n\
+ | Prices | {prices} | Basket €44.02 |\n| Deals | Tighter range | More non-food deals |\n\
+ | App | Nothing comparable | {app} |\n| Store feel | Quicker to shop | Bigger, more variety |\n"
+ );
+ let c = comparison_of(&text);
+ // The cells keep their links: only the count leaves the URL out
+ assert_eq!(c.rows[0].cells[1], prices);
+ assert_eq!(c.rows[2].cells[2], app);
+ validate(&compute(&text).unwrap(), Some(&text)).unwrap();
+
+ let cell = |n: usize, link: &str| {
+ format!("| Plan | Note |\n|---|---|\n| Basic | {}{link} |\n| Team | b |\n| Business | c |\n", "x".repeat(n))
+ };
+ // 200 shown characters with a long link pass; one more shown character is refused
+ let url = format!("https://example.com/{}", "p".repeat(300));
+ assert!(first(&cell(197, &format!(" [ab]({url})"))).is_some());
+ assert_eq!(first(&cell(197, &format!(" [abc]({url})"))), None);
+ // A bare URL is shown, so it counts in full
+ assert_eq!(first(&cell(10, &format!(" {url}"))), None);
+ // The raw ceiling: a link's URL can't make a cell hold more than 1,000 characters
+ let huge = |n: usize| format!(" [ab](https://example.com/{})", "p".repeat(n));
+ let raw = |n: usize| 3 + huge(n).chars().count();
+ assert_eq!(raw(970), MAX_CELL_RAW);
+ assert!(first(&cell(3, &huge(970))).is_some());
+ assert_eq!(first(&cell(3, &huge(971))), None);
+ // validate holds the same lines for a block built any other way
+ let shown = |n: usize| format!("{} [ab]({url})", "x".repeat(n));
+ for (cell, ok) in [(format!("xxx{}", huge(970)), true), (format!("xxx{}", huge(971)), false), (shown(197), true), (shown(198), false)] {
+ let mut set = compute(&text).unwrap();
+ let Block::Comparison(c) = &mut set.blocks[0] else { panic!() };
+ c.rows[0].cells[1] = cell;
+ assert_eq!(validate(&set, None).is_ok(), ok);
+ }
+}
+
+/// The client (`shownLength` in frontend/src/smartResults.ts) counts the same cases the same way;
+/// tests/smartResultsCellLength.test.mjs holds the same table.
+#[test]
+fn shown_length_counts_as_the_client_counts() {
+ for (s, n) in SHOWN_CASES {
+ assert_eq!(shown_len(s), *n, "{s:?}");
+ }
+}
+
+const SHOWN_CASES: &[(&str, usize)] = &[
+ ("plain", 5),
+ ("[Aldi](https://example.com/very/long/path)", 4),
+ ("![logo](https://example.com/l.png) text", 9),
+ ("see https://example.com/a", 25),
+ ("[a [b](u)", 4),
+ ("[a] (u)", 7),
+ ("[x](u", 5),
+ ("!x [y](z)", 4),
+ ("[](https://example.com)", 0),
+ ("😀[😀](https://example.com)", 4),
+ ("[a](b) and [c](d)", 7),
+ ("[a](b(c)d)", 3),
+];
+
#[test]
fn small_ragged_wide_or_repeated_tables_stay_text() {
let two_rows = "| Plan | Price |\n|---|---|\n| Basic | 12 |\n| Team | 18 |\n";
diff --git a/src/server/smart_results/validate.rs b/src/server/smart_results/validate.rs
index 0a0280b2..23dfc728 100644
--- a/src/server/smart_results/validate.rs
+++ b/src/server/smart_results/validate.rs
@@ -50,7 +50,7 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
if col.key != format!("c{k}") {
return Err(format!("column key {:?}", col.key));
}
- check_text(&col.label, 200, "column label")?;
+ check_label(&col.label, "column label")?;
if strict {
texts.push(&col.label);
}
@@ -79,7 +79,7 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
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")?;
+ check_label(&row.cells[0], "row label")?;
if !labels.insert(label_key(&row.cells[0])) {
return Err(format!("row label {:?} repeats", row.cells[0]));
}
@@ -104,7 +104,7 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
}
}
Block::Chart(c) => {
- check_text(&c.x.label, 200, "axis label")?;
+ check_label(&c.x.label, "axis label")?;
texts.push(&c.x.label);
let axis_ok = matches!((c.chart_kind, c.x.kind), (ChartKind::Line, AxisKind::Time) | (ChartKind::Bar, AxisKind::Category));
if !axis_ok {
@@ -117,7 +117,7 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
if s.key != format!("s{k}") {
return Err(format!("series key {:?}", s.key));
}
- check_text(&s.label, 200, "series label")?;
+ check_label(&s.label, "series label")?;
texts.push(&s.label);
if let Some(unit) = &s.unit {
check_text(unit, 10, "unit")?;
@@ -136,7 +136,7 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
if p.id != format!("p{k}") {
return Err(format!("point id {:?}", p.id));
}
- check_text(&p.x, 200, "point label")?;
+ check_label(&p.x, "point label")?;
if !xs.insert(p.x.as_str()) {
return Err(format!("point {:?} repeats", p.x));
}
@@ -419,10 +419,10 @@ fn check_source(block: &Block) -> Result<(), String> {
}
}
-/// A shown cell: at most 200 characters, no HTML; it may be empty (a gap).
+/// A shown cell: no HTML, within [`cell_fits`]; it may be empty (a gap).
fn check_cell(cell: &str) -> Result<(), String> {
- if utf16_len(cell) > 200 {
- return Err("a cell over 200 characters".into());
+ if !cell_fits(cell) {
+ return Err(format!("a cell over {MAX_CELL} characters"));
}
if has_html(cell) {
return Err("HTML in a cell".into());
@@ -430,6 +430,62 @@ fn check_cell(cell: &str) -> Result<(), String> {
Ok(())
}
+/// A table label (a header or a row's first cell): a cell that isn't blank.
+fn check_label(s: &str, what: &str) -> Result<(), String> {
+ if s.trim().is_empty() {
+ return Err(format!("an empty {what}"));
+ }
+ check_cell(s).map_err(|e| e.replace("cell", what))
+}
+
+/// The most a table cell may show, in characters.
+pub(super) const MAX_CELL: usize = 200;
+/// The most a table cell may hold raw, URLs included, so a long link can't bloat a stored block.
+pub(super) const MAX_CELL_RAW: usize = 1000;
+
+/// A table cell short enough to store: at most [`MAX_CELL`] shown characters ([`shown_len`]) and
+/// [`MAX_CELL_RAW`] raw ones. Lengths are UTF-16 units, as the client counts (`isCell`).
+pub(super) fn cell_fits(cell: &str) -> bool {
+ cell.encode_utf16().count() <= MAX_CELL_RAW && shown_len(cell) <= MAX_CELL
+}
+
+/// A cell's length as the reader sees it: a markdown link `[text](url)` (or image `![text](url)`)
+/// counts as its text, since a source link's URL isn't shown. A bare URL is shown, so it counts.
+/// The client's `shownLength` does the same (`/!?\[([^\]]*)\]\([^)]*\)/g` → `$1`).
+pub(super) fn shown_len(s: &str) -> usize {
+ let mut n = 0;
+ let mut rest = s;
+ while !rest.is_empty() {
+ let at = rest.find('[').unwrap_or(rest.len());
+ let (before, from) = rest.split_at(at);
+ // The `!` of an image goes with its link
+ let link = link_text(from);
+ let bang = link.is_some() && before.ends_with('!');
+ n += before.encode_utf16().count() - usize::from(bang);
+ match link {
+ Some((text, len)) => {
+ n += text.encode_utf16().count();
+ rest = &from[len..];
+ }
+ None if from.is_empty() => break,
+ None => {
+ n += 1;
+ rest = &from[1..];
+ }
+ }
+ }
+ n
+}
+
+/// `[text](url)` at the start of `s`: the text and the link's length in bytes.
+fn link_text(s: &str) -> Option<(&str, usize)> {
+ let body = s.strip_prefix('[')?;
+ let close = body.find(']')?;
+ let after = body[close + 1..].strip_prefix('(')?;
+ let end = after.find(')')?;
+ Some((&body[..close], 1 + close + 2 + end + 1))
+}
+
fn check_text(s: &str, max: usize, what: &str) -> Result<(), String> {
if s.trim().is_empty() {
return Err(format!("an empty {what}"));