From c736e5abd4c42a43ec1910e23900f71210c7b04a Mon Sep 17 00:00:00 2001 From: shaitrish37 <244331886+shaitrish37@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:27:17 +0600 Subject: [PATCH 1/5] AI text fits the page, nicer AI handwriting, show_progress op, streamed and drawn-on writing - rupok-live fit.rs: add_text and replace_items_with_text size, wrap and place agent text inside the slide frame; too much text shrinks, moves up or continues on new pages. - write_handwriting always fits the page (explicit spots, new pages), continues an earlier group (anchor.group) and has a joined style. - rupok-ink write: Catmull-Rom smoothing, hand-like pen order, ink-based letter spacing, a wandering baseline, pressure on downstrokes, faster natural timing, optional joined letters. - show_progress op (rupok_live::progress): the agent's working card. - Engine: streamed writing queues behind the reveal; agent shapes draw on. --- crates/rupok-ink/src/write/glyphs.rs | 180 ++++++++++-- crates/rupok-ink/src/write/layout.rs | 154 ++++++++++- crates/rupok-ink/src/write/mod.rs | 21 +- crates/rupok-ink/src/write/pen.rs | 69 ++++- crates/rupok-ink/src/write/tests.rs | 169 ++++++++++- crates/rupok-live/src/apply.rs | 278 ++++++++++++++++--- crates/rupok-live/src/fit.rs | 369 +++++++++++++++++++++++++ crates/rupok-live/src/handwriting.rs | 156 +++++++++-- crates/rupok-live/src/lib.rs | 2 + crates/rupok-live/src/op.rs | 14 +- crates/rupok-live/src/progress.rs | 245 ++++++++++++++++ crates/rupok-wasm/src/engine/reveal.rs | 80 +++++- crates/rupok-wasm/src/live.rs | 80 +++++- 13 files changed, 1721 insertions(+), 96 deletions(-) create mode 100644 crates/rupok-live/src/fit.rs create mode 100644 crates/rupok-live/src/progress.rs diff --git a/crates/rupok-ink/src/write/glyphs.rs b/crates/rupok-ink/src/write/glyphs.rs index 6b6c204..b30bbe4 100644 --- a/crates/rupok-ink/src/write/glyphs.rs +++ b/crates/rupok-ink/src/write/glyphs.rs @@ -47,11 +47,103 @@ fn from_hershey(rec: &str) -> Option { }) .collect::>(); Some(Glyph { - strokes: join_touching(strokes), + strokes: pen_order(join_touching(strokes)), adv: right - left, }) } +/// Reorder and join a font glyph's strokes the way a hand writes them, so +/// the pen lifts only where a person's would: +/// +/// - dots (of `i`, `j`, `!`, `?`…) come after the stroke they sit on; +/// - two strokes meeting end to end become one (`v`, `w`: down and up); +/// - a stroke that starts on the previous one continues it by retracing +/// (`a`, `d`, `n`, `m`, `h`: down the stem, back up, round the bowl); +/// - a stroke that ends on the next one runs straight on into it (`u`). +fn pen_order(strokes: Vec>) -> Vec> { + const NEAR: f32 = 0.8; + let is_dot = |s: &Vec| BBox::of(s).size() < 2.5; + let (dots, mut rest): (Vec>, Vec>) = + strokes.into_iter().partition(|s| is_dot(s)); + if rest.is_empty() { + return dots; + } + let mut out: Vec> = vec![rest.remove(0)]; + for mut s in rest { + let Some(prev) = out.last_mut() else { break }; + let (Some(&end), Some(&first), Some(&last)) = (prev.last(), s.first(), s.last()) else { + continue; + }; + if end.dist(last) < NEAR && end.dist(first) >= NEAR { + s.reverse(); + } + let first = s[0]; + if end.dist(first) < NEAR { + prev.extend_from_slice(&s[1..]); + continue; + } + // Starts on the previous stroke: retrace back to that point. + if let Some((i, q)) = near_on_path(prev, first, NEAR, true) { + let back: Vec = prev[i + 1..prev.len() - 1].iter().rev().copied().collect(); + prev.extend(back); + prev.push(q); + prev.extend_from_slice(&s); + continue; + } + // Ends on this stroke, on a straight part: run on into its start. + if let Some((i, q)) = near_on_path(&s, end, NEAR, false) + && straight(&s[..=i + 1]) + && q.dist(first) > NEAR + { + prev.push(q); + prev.extend(s[..=i].iter().rev().copied()); + prev.extend_from_slice(&s[1..]); + continue; + } + out.push(s); + } + out.extend(dots); + out +} + +/// The segment of `path` passing within `tol` of `p` (the last such segment +/// when `from_end`), with the point on it closest to `p`. +fn near_on_path(path: &[Pt], p: Pt, tol: f32, from_end: bool) -> Option<(usize, Pt)> { + let n = path.len().checked_sub(1)?; + let test = |i: usize| { + let (a, b) = (path[i], path[i + 1]); + let (dx, dy) = (b.x - a.x, b.y - a.y); + let l2 = dx * dx + dy * dy; + let t = if l2 > 0.0 { + (((p.x - a.x) * dx + (p.y - a.y) * dy) / l2).clamp(0.0, 1.0) + } else { + 0.0 + }; + let q = a.lerp(b, t); + (q.dist(p) < tol).then_some((i, q)) + }; + if from_end { + (0..n).rev().find_map(test) + } else { + (0..n).find_map(test) + } +} + +/// True when the polyline is (nearly) a straight segment. +fn straight(pts: &[Pt]) -> bool { + let (Some(&a), Some(&b)) = (pts.first(), pts.last()) else { + return true; + }; + let len = a.dist(b); + if len < 1e-3 { + return true; + } + pts.iter().all(|p| { + let cross = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x); + (cross / len).abs() < 0.6 + }) +} + /// Join strokes that meet end to start, as one pen movement would draw them. fn join_touching(strokes: Vec>) -> Vec> { let mut out: Vec> = Vec::with_capacity(strokes.len()); @@ -227,9 +319,12 @@ impl GlyphSet { } } -/// Round a polyline's curves (Chaikin corner cutting, two passes) while -/// keeping its sharp corners and its end points: Hershey curves are coarse -/// polygons, a pen draws them smooth. +/// Round a polyline's curves while keeping its sharp corners and its end +/// points: Hershey curves are coarse polygons, a pen draws them smooth. +/// +/// Each run between corners is resampled along a centripetal Catmull-Rom +/// spline *through* the original points, so bowls keep their size (corner +/// cutting would shrink them) and the curve has no kinks at the vertices. pub fn smooth(pts: &[Pt]) -> Vec { if pts.len() < 3 { return pts.to_vec(); @@ -255,20 +350,7 @@ pub fn smooth(pts: &[Pt]) -> Vec { } let mut out: Vec = Vec::with_capacity(pts.len() * 4); for piece in pieces { - let mut cur = piece; - for _ in 0..2 { - if cur.len() < 3 { - break; - } - let mut next = Vec::with_capacity(cur.len() * 2); - next.push(cur[0]); - for w in cur.windows(2) { - next.push(w[0].lerp(w[1], 0.25)); - next.push(w[0].lerp(w[1], 0.75)); - } - next.push(cur[cur.len() - 1]); - cur = next; - } + let cur = catmull_rom(&piece); if out .last() .is_some_and(|l: &Pt| cur.first().is_some_and(|f| l.dist(*f) < 1e-4)) @@ -281,6 +363,68 @@ pub fn smooth(pts: &[Pt]) -> Vec { out } +/// Sample a centripetal Catmull-Rom spline through `pts` (ends kept), about +/// one point per writing unit and at least four per segment. +fn catmull_rom(pts: &[Pt]) -> Vec { + // Drop repeated points: they make the parametrisation degenerate. + let mut p: Vec = Vec::with_capacity(pts.len()); + for q in pts { + if p.last().is_none_or(|l: &Pt| l.dist(*q) > 1e-3) { + p.push(*q); + } + } + if p.len() < 3 { + return p; + } + let n = p.len(); + // Phantom end points continue the first and last segments. + let first = Pt::new(2.0 * p[0].x - p[1].x, 2.0 * p[0].y - p[1].y); + let last = Pt::new(2.0 * p[n - 1].x - p[n - 2].x, 2.0 * p[n - 1].y - p[n - 2].y); + let at = |i: isize| -> Pt { + if i < 0 { + first + } else if i as usize >= n { + last + } else { + p[i as usize] + } + }; + let mut out = Vec::with_capacity(n * 6); + out.push(p[0]); + for i in 0..n - 1 { + let (p0, p1, p2, p3) = ( + at(i as isize - 1), + at(i as isize), + at(i as isize + 1), + at(i as isize + 2), + ); + let knot = |a: Pt, b: Pt| a.dist(b).max(1e-4).sqrt(); + let t1 = knot(p0, p1); + let t2 = t1 + knot(p1, p2); + let t3 = t2 + knot(p2, p3); + let steps = (p1.dist(p2).ceil() as usize).clamp(4, 24); + for k in 1..=steps { + let t = t1 + (t2 - t1) * k as f32 / steps as f32; + let lerp = |a: Pt, b: Pt, ta: f32, tb: f32| -> Pt { + let w = if (tb - ta).abs() < 1e-6 { + 0.0 + } else { + (t - ta) / (tb - ta) + }; + a.lerp(b, w) + }; + let a1 = lerp(p0, p1, 0.0, t1); + let a2 = lerp(p1, p2, t1, t2); + let a3 = lerp(p2, p3, t2, t3); + let b1 = lerp(a1, a2, 0.0, t2); + let b2 = lerp(a2, a3, t1, t3); + let c = lerp(b1, b2, t1, t2); + out.push(if k == steps { p2 } else { c }); + } + } + out +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/rupok-ink/src/write/layout.rs b/crates/rupok-ink/src/write/layout.rs index f11859c..e685121 100644 --- a/crates/rupok-ink/src/write/layout.rs +++ b/crates/rupok-ink/src/write/layout.rs @@ -83,6 +83,9 @@ pub struct Variation { pub jitter: f32, /// Prefer the teacher's own forms when they exist. pub prefer_user: bool, + /// Join neighbouring lowercase letters of a word with a connecting + /// stroke where a hand would (the "joined" style). + pub connect: bool, } pub struct Layout<'a> { @@ -91,8 +94,15 @@ pub struct Layout<'a> { pub rng: Rng, /// Characters with no glyph (written as `?`). pub missing: Vec, + /// Where the hand's baseline has wandered to (writing units): a slow + /// random walk, so neighbouring letters sit at nearly the same height. + pub drift: f32, } +/// Gap between the ink of neighbouring letters, writing units (about a +/// fifth of an x-height, as in neat board writing). +const LETTER_GAP: f32 = 3.6; + impl Layout<'_> { fn normal(&mut self) -> f32 { self.rng.normal().clamp(-2.5, 2.5) @@ -138,8 +148,9 @@ impl Layout<'_> { } let j = self.var.jitter; let k = 1.0 + 0.04 * j * self.normal(); - let rot = (1.6 * j * self.normal()).to_radians(); - let dy = 0.5 * j * self.normal(); + let rot = (1.4 * j * self.normal()).to_radians(); + self.drift = 0.75 * self.drift + 0.35 * j * self.normal(); + let dy = self.drift; // A slow elastic wobble, so no two glyphs are the same shape. let amp = 0.8 * j; let (fx, fy) = (self.rng.range(0.35, 0.6), self.rng.range(0.35, 0.6)); @@ -188,27 +199,63 @@ impl Layout<'_> { let mut x = 0.0f32; let mut after_space = false; let mut first = true; + // The previous letter (for ink spacing and joins): its character, the + // right edge of its ink, and where its strokes start in `out`. + let mut prev: Option<(char, f32, usize)> = None; for n in nodes { if let Node::Space(em) = n { x += em * XH * s * (1.0 + 0.15 * self.var.jitter * (self.rng.f32() - 0.5)); after_space = true; + prev = None; continue; } let mut b = self.node(n, s); if b.strokes.is_empty() && b.w <= 0.0 { continue; } - if !first { - x += self.kern(s); - } + let letter = match n { + Node::Char(c) if !b.strokes.is_empty() => Some(*c), + _ => None, + }; + let ink = b.ink(); + // Letters after letters are spaced by their ink, not the font's + // side bearings: even, close spacing like a hand's. + let dx = match (letter, prev) { + (Some(c), Some((pc, right, _))) if !after_space && ink.x0.is_finite() => { + let joined_air = if self.var.connect { 1.4 } else { 0.0 }; + let gap = (LETTER_GAP + joined_air + optical(pc, c)) * s + + 0.5 * self.var.jitter * (self.rng.f32() - 0.5) * s; + right + gap - ink.x0 + } + _ => { + if !first { + x += self.kern(s); + } + x + } + }; if after_space && let Some(st) = b.strokes.first_mut() { st.pause = Pause::Word; } + b.shift(dx, 0.0); + let start = out.strokes.len(); + let joined = match (letter, prev) { + (Some(c), Some((pc, _, pstart))) if self.var.connect && !after_space => { + join_letters(&mut out, pstart, pc, &mut b, c, s) + } + _ => None, + }; after_space = false; first = false; - b.shift(x, 0.0); - x += b.w; + x = x.max(dx + b.w); + prev = letter.map(|c| (c, ink.x1 + dx, joined.unwrap_or(start))); out.absorb(b); + if joined.is_some() { + // The joined stroke may reach above or below the letters. + let all = out.ink(); + out.top = out.top.min(all.y0); + out.bottom = out.bottom.max(all.y1); + } } out.w = x.max(0.0); out @@ -346,6 +393,99 @@ impl Layout<'_> { } } +/// Extra space between two letters, writing units: round sides look +/// further apart than straight ones, so they sit a little closer; tall thin +/// letters get a touch more air. +fn optical(a: char, b: char) -> f32 { + let round_right = matches!(a, 'o' | 'c' | 'e' | 'b' | 'p' | 'O' | 'C' | 'D' | 'Q' | '0'); + let round_left = matches!( + b, + 'o' | 'c' | 'e' | 'd' | 'q' | 'a' | 'g' | 'O' | 'C' | 'G' | 'Q' | '0' + ); + let thin = |c: char| matches!(c, 'i' | 'l' | 'j' | '1' | 'I' | '!' | 't' | 'f'); + let mut g = 0.0; + if round_right { + g -= 0.4; + } + if round_left { + g -= 0.4; + } + if thin(a) || thin(b) { + g += 0.8; + } + if matches!(b, '.' | ',' | ')' | ']') || matches!(a, '(' | '[') { + g -= 0.8; + } + g +} + +/// Join the previous letter (its strokes start at `out.strokes[pstart]`) +/// to letter `b` with one connecting pen movement, when both are lowercase +/// and the previous letter's pen leaves on its right while `b`'s starts on +/// its left, close by. Returns the index in `out` of the stroke `b`'s first +/// stroke was merged into, if joined. +fn join_letters( + out: &mut LBox, + pstart: usize, + pc: char, + b: &mut LBox, + c: char, + s: f32, +) -> Option { + if !pc.is_ascii_lowercase() || !c.is_ascii_lowercase() || b.strokes.is_empty() { + return None; + } + let prev = &out.strokes[pstart.min(out.strokes.len())..]; + if prev.is_empty() { + return None; + } + let pink = BBox::of_strokes(prev.iter().map(|s| s.pts.as_slice())); + // The main stroke: the last one that is not a dot. + let mi = (0..prev.len()) + .rev() + .find(|&k| BBox::of(&prev[k].pts).size() > 2.5 * s)?; + let main = pstart + mi; + let a = *out.strokes[main].pts.last()?; + let z = *b.strokes[0].pts.first()?; + let bink = b.ink(); + let leaves_right = a.x >= pink.x0 + pink.w() * 0.5; + let enters_left = z.x <= bink.x0 + bink.w() * 0.55; + let low_enough = a.y > -XH * 1.15 * s && a.y < 1.0 * s; + let entry_ok = z.y > -XH * 1.2 * s && z.y < 1.0 * s; + let near = a.dist(z) < XH * 1.7 * s && z.x > a.x; + if !(leaves_right && enters_left && low_enough && entry_ok && near) { + return None; + } + // A swung connector: from near the baseline it dips a little, then rises + // into the next letter; from the top (o, v, w, r) it runs across. + let ctrl = if a.y > -XH * 0.45 * s { + Pt::new(a.x + (z.x - a.x) * 0.35, a.y.max(z.y) + 1.2 * s) + } else { + Pt::new((a.x + z.x) * 0.5, a.y.max(z.y) + 2.0 * s) + }; + let steps = 8; + let mut conn = Vec::with_capacity(steps); + for k in 1..steps { + let t = k as f32 / steps as f32; + let u = 1.0 - t; + conn.push(Pt::new( + u * u * a.x + 2.0 * u * t * ctrl.x + t * t * z.x, + u * u * a.y + 2.0 * u * t * ctrl.y + t * t * z.y, + )); + } + let first = b.strokes.remove(0); + let m = &mut out.strokes[main]; + m.pts.extend(conn); + m.pts.extend(first.pts); + // Strokes written after the main one (a dot) now follow the join. + let tail: Vec = out.strokes.drain(main + 1..).collect(); + for (k, mut t) in tail.into_iter().enumerate() { + t.pause = if k == 0 { Pause::Glyph } else { Pause::Stroke }; + b.strokes.insert(k, t); + } + Some(main) +} + /// Horizontal and vertical scale for font operators (drawn ~26 units wide). fn op_scale(c: char) -> Option<(f32, f32)> { match c { diff --git a/crates/rupok-ink/src/write/mod.rs b/crates/rupok-ink/src/write/mod.rs index 9d444f3..9e39acf 100644 --- a/crates/rupok-ink/src/write/mod.rs +++ b/crates/rupok-ink/src/write/mod.rs @@ -15,11 +15,18 @@ //! ([`GlyphSet::add_user`]; the same samples teach the recogniser), else //! from the Hershey single-stroke fonts, smoothed (see [`font`] for the //! data licence). -//! - **Variation** (slant, size, baseline wobble, rotation, spacing) is -//! gentle and comes from a seeded generator: the same input and seed always -//! give the same ink. +//! - **Variation** (slant, size, a slowly wandering baseline, rotation, +//! spacing) is gentle and comes from a seeded generator: the same input and +//! seed always give the same ink. +//! - **Spacing** follows the ink: letters sit an even, close gap apart (with +//! small optical corrections), not at the font's side bearings. +//! - **Pen order** is a hand's: strokes that meet are one movement (`v`, +//! retraced stems in `a`, `n`, `d`), dots come last, and the joined style +//! ([`WriteOptions::connect`]) links the letters of a word. //! - **Timing**: slower in curves, eased at pen-down and lift, pauses between //! strokes, glyphs, words and lines; `speed` scales it all. +//! - **Pressure** rises on downstrokes and in slow curves and tapers at both +//! ends, so the line breathes like a felt pen on a board. //! //! Pure Rust with no clock, so it runs in `wasm32-unknown-unknown`. @@ -61,6 +68,9 @@ pub struct WriteOptions { pub line_pitch: f32, /// Use the teacher's own glyphs where the set has them. pub prefer_user: bool, + /// Join the letters of a word where a hand would (a cursive-ish, + /// "joined" print). Off: neat separate letters. + pub connect: bool, } impl Default for WriteOptions { @@ -74,6 +84,7 @@ impl Default for WriteOptions { max_width: None, line_pitch: 3.0, prefer_user: true, + connect: false, } } } @@ -166,9 +177,11 @@ pub fn write>(lines: &[S], glyphs: &GlyphSet, opts: &WriteOptions) var: Variation { jitter, prefer_user: opts.prefer_user, + connect: opts.connect, }, rng: Rng::new(fnv(&joined, opts.seed)), missing: Vec::new(), + drift: 0.0, }; // Lay out every visual line in writing units, baseline at y = 0. @@ -200,7 +213,7 @@ pub fn write>(lines: &[S], glyphs: &GlyphSet, opts: &WriteOptions) baseline = (baseline + pitch).max(prev_bottom - top + XH * 0.5); } let wobble = 0.5 * jitter * lay.rng.normal().clamp(-2.0, 2.0); - let drift = 0.004 * jitter * lay.rng.normal().clamp(-2.0, 2.0); // baseline tilt + let drift = 0.003 * jitter * lay.rng.normal().clamp(-2.0, 2.0); // baseline tilt let mut first = true; let mut x1 = 0.0f32; for s in b.strokes { diff --git a/crates/rupok-ink/src/write/pen.rs b/crates/rupok-ink/src/write/pen.rs index 63c712e..99cf05b 100644 --- a/crates/rupok-ink/src/write/pen.rs +++ b/crates/rupok-ink/src/write/pen.rs @@ -9,7 +9,7 @@ use crate::StrokePoint; use crate::math::geom::Pt; /// Writing speed at `speed = 1`, in x-heights per second of pen travel. -const XH_PER_S: f32 = 22.0; +const XH_PER_S: f32 = 30.0; /// Time between emitted samples, ms (a pen digitiser reports ~120–240 Hz). const SAMPLE_MS: f32 = 7.0; /// Most points one stroke may have. @@ -38,10 +38,10 @@ impl PenStroke { fn pause_ms(p: Pause) -> f32 { match p { - Pause::Stroke => 45.0, - Pause::Glyph => 70.0, - Pause::Word => 200.0, - Pause::Line => 480.0, + Pause::Stroke => 32.0, + Pause::Glyph => 46.0, + Pause::Word => 140.0, + Pause::Line => 320.0, } } @@ -112,7 +112,10 @@ fn time_stroke(pts: &[Pt], xh_px: f32, speed: f32) -> Vec { let mut t = 0.0f32; let mut last_emit = f32::NEG_INFINITY; let mut out: Vec = Vec::with_capacity(n / 2 + 2); + let mut p_smooth = f32::NAN; for i in 0..n { + let mut down = 0.0f32; + let mut rel_v = 0.6f32; if i > 0 { let ds = r[i - 1].dist(r[i]); s_acc += ds; @@ -127,20 +130,37 @@ fn time_stroke(pts: &[Pt], xh_px: f32, speed: f32) -> Vec { } else { 0.0 }; - let curve = 0.3 + 0.7 / (1.0 + 2.6 * turn); + let curve = 0.35 + 0.65 / (1.0 + 2.2 * turn); let start = (0.3 + 0.7 * (s_acc / ease)).min(1.0); let end = (0.35 + 0.65 * ((len - s_acc) / ease)).min(1.0); - let v = vmax * curve * start.min(end).max(0.2); - t += ds / v.max(1e-4); + let k = curve * start.min(end).max(0.2); + t += ds / (vmax * k).max(1e-4); + rel_v = k; + if ds > 0.0 { + down = (r[i].y - r[i - 1].y) / ds; // y grows downwards + } } + // Pressure: heavier on downstrokes and where the pen slows, lighter + // on fast upstrokes, tapering at both ends; smoothed so the width + // swells and thins gradually. + let edge = (s_acc / ease).min((len - s_acc) / ease).clamp(0.0, 1.0); + let raw = 0.34 + 0.24 * edge.sqrt() + 0.12 * down - 0.12 * (rel_v - 0.6); + p_smooth = if p_smooth.is_nan() { + raw + } else { + p_smooth + 0.3 * (raw - p_smooth) + }; let last = i + 1 == n; if i == 0 || last || t - last_emit >= SAMPLE_MS { - let edge = (s_acc / ease).min((len - s_acc) / ease).clamp(0.0, 1.0); - let p = (0.38 + 0.3 * edge).clamp(0.0, 1.0); + let p = if i == 0 || last { + p_smooth.min(0.4) + } else { + p_smooth + }; out.push(StrokePoint { x: r[i].x, y: r[i].y, - p, + p: p.clamp(0.15, 0.95), dt: t.round() as u32, }); last_emit = t; @@ -159,7 +179,7 @@ fn time_stroke(pts: &[Pt], xh_px: f32, speed: f32) -> Vec { pub fn time_all(strokes: &[(Vec, Pause, usize)], xh_px: f32, speed: f32) -> Vec { let speed = speed.clamp(0.1, 10.0); let xh_px = xh_px.max(1.0); - let air = XH_PER_S * xh_px * speed / 1000.0 * 2.4; + let air = XH_PER_S * xh_px * speed / 1000.0 * 3.0; let mut out = Vec::with_capacity(strokes.len()); let mut clock = 0.0f64; let mut prev_end: Option = None; @@ -208,6 +228,31 @@ mod tests { assert!(fast < tl); } + #[test] + fn pressure_varies_downstrokes_heavier() { + // A zigzag: down, up, down at the same pace. + let mut pts = Vec::new(); + for k in 0..4 { + for i in 0..=20 { + let y = if k % 2 == 0 { + i as f32 + } else { + 20.0 - i as f32 + }; + pts.push(Pt::new(k as f32 * 6.0 + i as f32 * 0.3, y * 2.0)); + } + } + let s = time_stroke(&pts, 30.0, 1.0); + let ps: Vec = s.iter().map(|p| p.p).collect(); + let (lo, hi) = ps + .iter() + .fold((1.0f32, 0.0f32), |(a, b), p| (a.min(*p), b.max(*p))); + assert!(hi - lo > 0.15, "pressure should vary: {lo}..{hi}"); + assert!(ps.iter().all(|p| (0.0..=1.0).contains(p))); + // Ends are lighter than the middle of a downstroke. + assert!(ps[0] < hi && ps[ps.len() - 1] < hi); + } + #[test] fn dots_are_taps() { let d = time_stroke(&[Pt::new(5.0, 5.0)], 30.0, 1.0); diff --git a/crates/rupok-ink/src/write/tests.rs b/crates/rupok-ink/src/write/tests.rs index c3192a9..dc8fce3 100644 --- a/crates/rupok-ink/src/write/tests.rs +++ b/crates/rupok-ink/src/write/tests.rs @@ -1,4 +1,4 @@ -use super::layout::{Layout, Variation}; +use super::layout::{Layout, Pause, Variation}; use super::parse::parse_line; use super::*; use crate::math::geom::BBox; @@ -49,9 +49,11 @@ fn layout_boxes_follow_maths_structure() { var: Variation { jitter: 0.0, prefer_user: false, + connect: false, }, rng: crate::math::synth::Rng::new(1), missing: Vec::new(), + drift: 0.0, }; // Fraction: numerator ink above the bar, denominator below. let row = lay.row(&parse_line("$\\frac{12}{3}$"), 1.0); @@ -264,6 +266,7 @@ fn hostile_options_are_clamped() { max_width: Some(-1.0), line_pitch: f32::NAN, prefer_user: true, + connect: true, }, ); assert!(!w.strokes.is_empty()); @@ -272,3 +275,167 @@ fn hostile_options_are_clamped() { let empty: [&str; 0] = []; assert!(write(&empty, &g, &opts()).strokes.is_empty()); } + +// ------------------------------------------------- handwriting quality + +#[test] +fn letters_advance_left_to_right_with_even_gaps() { + let g = GlyphSet::new(); + for word in ["minimum", "Subtract", "quick", "x+y=12", "hello world"] { + let w = write(&[word], &g, &opts()); + // Left edges of successive strokes' glyphs never jump backwards by + // more than a letter: the writing moves left to right. + let mut starts: Vec = Vec::new(); + for s in &w.strokes { + let x0 = s.points.iter().map(|p| p.x).fold(f32::INFINITY, f32::min); + starts.push(x0); + } + let xh = opts().x_height; + let mut max_so_far = f32::NEG_INFINITY; + for x in &starts { + assert!( + *x >= max_so_far - xh * 1.2, + "{word}: a stroke starts {x} far left of {max_so_far}" + ); + max_so_far = max_so_far.max(*x); + } + } + // Letter gaps are even: ink-to-ink spacing within a word varies little. + let lay_word = |word: &str| { + let g = GlyphSet::new(); + let mut lay = Layout { + glyphs: &g, + var: Variation { + jitter: 0.0, + prefer_user: false, + connect: false, + }, + rng: crate::math::synth::Rng::new(1), + missing: Vec::new(), + drift: 0.0, + }; + let nodes = parse_line(word); + let mut gaps = Vec::new(); + let mut prev: Option = None; + let full = lay.row(&nodes, 1.0); + let mut boxes: Vec = Vec::new(); + for s in &full.strokes { + let b = BBox::of(&s.pts); + match boxes.last_mut() { + Some(last) if s.pause == Pause::Stroke => *last = last.union(b), + _ => boxes.push(b), + } + } + for b in &boxes { + if let Some(p) = prev { + gaps.push(b.x0 - p.x1); + } + prev = Some(*b); + } + gaps + }; + let gaps = lay_word("minimum"); + assert!(!gaps.is_empty()); + for g in &gaps { + assert!(*g > 1.0 && *g < 7.0, "letter gap {g} in {gaps:?}"); + } +} + +#[test] +fn writing_stays_inside_its_block_and_width() { + let g = GlyphSet::new(); + for connect in [false, true] { + let lines = [ + "Subtract 3 from both sides of the equation, then divide by two", + "$x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$", + "Check: $2(2) + 3 = 7$", + ]; + let o = WriteOptions { + max_width: Some(420.0), + connect, + ..opts() + }; + let w = write(&lines, &g, &o); + let b = bbox_of(&w.strokes); + assert!(b.x0 >= -0.01 && b.y0 >= -0.01, "{b:?}"); + assert!(b.x1 <= w.width + 0.5, "ink {} past width {}", b.x1, w.width); + assert!( + b.y1 <= w.height + 0.5, + "ink {} past height {}", + b.y1, + w.height + ); + // Wrapping keeps lines near the asked width (one long word may exceed). + assert!(w.width < 420.0 + 60.0, "{}", w.width); + for s in &w.strokes { + for p in &s.points { + assert!(p.x.is_finite() && p.y.is_finite()); + assert!((0.0..=1.0).contains(&p.p)); + } + } + } +} + +#[test] +fn pen_lifts_like_a_hand() { + let g = GlyphSet::new(); + // `v` and `w` are one movement each; `n` and `a` retrace their stem. + for c in ['v', 'w', 'n', 'a', 'd', 'm', 'u'] { + let gl = g.builtin(c).unwrap(); + assert_eq!(gl.strokes.len(), 1, "{c}: {} strokes", gl.strokes.len()); + } + // The dot of an i comes after its stem. + let i = g.builtin('i').unwrap(); + assert_eq!(i.strokes.len(), 2); + assert!(BBox::of(&i.strokes[1]).size() < 2.5, "dot last"); + // The joined style lifts the pen less often than neat print. + let neat = write(&["minimum quantum"], &g, &opts()); + let joined = write( + &["minimum quantum"], + &g, + &WriteOptions { + connect: true, + ..opts() + }, + ); + assert!( + joined.strokes.len() < neat.strokes.len(), + "joined {} vs neat {}", + joined.strokes.len(), + neat.strokes.len() + ); + // Same input, same ink, in both styles. + assert_eq!( + joined, + write( + &["minimum quantum"], + &g, + &WriteOptions { + connect: true, + ..opts() + } + ) + ); +} + +#[test] +fn neighbouring_letters_share_a_baseline() { + // The baseline wanders slowly: neighbours differ far less than the + // whole line's spread would allow with independent jitter. + let g = GlyphSet::new(); + let w = write(&["nnnnnnnnnnnnnnnnnnnn"], &g, &opts()); + let bottoms: Vec = w + .strokes + .iter() + .map(|s| { + s.points + .iter() + .map(|p| p.y) + .fold(f32::NEG_INFINITY, f32::max) + }) + .collect(); + let xh = opts().x_height; + for pair in bottoms.windows(2) { + assert!((pair[1] - pair[0]).abs() < xh * 0.2, "{pair:?}"); + } +} diff --git a/crates/rupok-live/src/apply.rs b/crates/rupok-live/src/apply.rs index 079e177..417fafd 100644 --- a/crates/rupok-live/src/apply.rs +++ b/crates/rupok-live/src/apply.rs @@ -28,6 +28,8 @@ pub const DEFAULT_TEXT_SIZE: f64 = 32.0; pub const MIN_PROJECTOR_TEXT: f64 = 24.0; const MAX_TEXT_CHARS: usize = 20_000; const MAX_ITEMS_PER_OP: usize = 5_000; +/// Most new pages one `add_text` may continue onto. +const MAX_SPILL_PAGES: usize = 8; const OUTLINE_TEXT_CHARS: usize = 4_000; /// Largest step a Smart Object without declared steps may be moved to. const MAX_STEPS: u32 = 500; @@ -201,6 +203,7 @@ fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result Op::Snapshot { .. } => Err(LiveError::Unsupported("snapshot")), Op::WriteHandwriting { .. } => crate::handwriting::run(ctx, op, msg, now, None), Op::PointAt { .. } => Err(LiveError::Unsupported("point_at")), + Op::ShowProgress(_) => Err(LiveError::Unsupported("show_progress")), // Shape geometry lives in the board engine (rupok-wasm `live.rs`). Op::AddShape { .. } => Err(LiveError::Unsupported("add_shape")), Op::AddTable { .. } => Err(LiveError::Unsupported("add_table")), @@ -302,7 +305,9 @@ fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result color, } => { check_text(text)?; - let size = positive("size", size.unwrap_or(DEFAULT_TEXT_SIZE))?; + if let Some(s) = size { + positive("size", *s)?; + } let x = finite("x", *x)?; let y = finite("y", *y)?; if let Some(w) = w { @@ -310,14 +315,9 @@ fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result } let (idx, info) = page_ref(ctx.lesson, ctx.page_id, *page)?; let frame = info.frame.unwrap_or(Frame::SLIDE_16_9); - let (w, h) = text_box(text, size, *w, x, frame); - let geom = BoxGeom { - x, - y, - w, - h, - rot: 0.0, - }; + let items = ctx.lesson.items(&info.id)?; + // Sensible size: as asked, else like the page's other text. + let size = size.unwrap_or_else(|| page_text_size(&items).unwrap_or(DEFAULT_TEXT_SIZE)); let color = match color { Some(c) => parse_color(c)?, None => default_ink(info.bg_color), @@ -331,22 +331,91 @@ fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result ), )); } + // Fit it inside the page: size, wrap, place; spill to new pages. + let above = free_above(&items, x, y, frame); + let fit = crate::fit::fit_text(text, size, x, y, *w, frame, Some(above)); + for n in &fit.notes { + warnings.push(warning("fit", n.clone())); + } + let geom = BoxGeom { + x: fit.x, + y: fit.y, + w: fit.w, + h: fit.h, + rot: 0.0, + }; warnings.extend(placement_warning(&geom, info.frame)); let data = ItemData::Text(TextData { latex: false, geom, - text: text.clone(), - size, + text: fit.text.clone(), + size: fit.size, color, stamp: None, }); tag(ctx.lesson, msg); let item_id = ctx.lesson.add_item(&info.id, &data, now)?; + // Text that does not fit continues on new pages after this one. + let mut more = Vec::new(); + let mut rest = fit.rest.clone(); + let mut at = idx; + while let Some(r) = rest.take() { + if more.len() >= MAX_SPILL_PAGES { + warnings.push(warning( + "fit", + format!("the text is too long: stopped after {MAX_SPILL_PAGES} extra pages; split it into shorter parts"), + )); + break; + } + let spec = new_page_spec(ctx.lesson, &info.id, &None, None, &None)?; + tag(ctx.lesson, msg); + let pid = ctx.lesson.add_page(Some(at + 1), spec)?; + at += 1; + let f = crate::fit::fit_text( + &r, + fit.size, + crate::fit::MARGIN, + crate::fit::MARGIN, + *w, + frame, + None, + ); + let data = ItemData::Text(TextData { + latex: false, + geom: BoxGeom { + x: f.x, + y: f.y, + w: f.w, + h: f.h, + rot: 0.0, + }, + text: f.text.clone(), + size: f.size, + color, + stamp: None, + }); + tag(ctx.lesson, msg); + let id = ctx.lesson.add_item(&pid, &data, now)?; + more.push(json!({ "page": at + 1, "item_id": id })); + rest = f.rest; + } + if !more.is_empty() { + warnings.push(warning( + "fit", + format!( + "the text did not fit on page {}; it continues on {} new page(s) after it", + idx + 1, + more.len() + ), + )); + } Ok(Outcome::changed(json!({ "item_id": item_id, "page": idx + 1, "page_id": info.id, "geometry": geometry_of(&geom), + "size": fit.size, + "continued": more, "warnings": warnings, }))) } @@ -692,9 +761,27 @@ fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result }; let x = finite("x", x.unwrap_or(b.x))?; let y = finite("y", y.unwrap_or(b.y))?; - let (est_w, _) = text_box(text, size, None, x, frame); - let w = est_w.max(b.w.min((frame.w - x).max(size * 2.0))); - let (w, h) = text_box(text, size, Some(w), x, frame); + // As wide as the ink (at least), wrapped and kept on the page. + let want_w = crate::fit::text_width( + text.split('\n') + .max_by_key(|l| l.chars().count()) + .unwrap_or(""), + size, + ) + .max(b.w); + let mut fit = crate::fit::fit_text(text, size, x, y, Some(want_w), frame, Some(y)); + if fit.rest.is_some() { + // One undo step replaces the ink: keep it all in one box. + let min = MIN_PROJECTOR_TEXT.min(size); + let f = + crate::fit::fit_text(text, min, x, y, None, frame, Some(crate::fit::MARGIN)); + fit = crate::fit::TextFit { + text: text.clone(), + rest: None, + ..f + }; + } + let (x, y, w, h, size) = (fit.x, fit.y, fit.w, fit.h, fit.size); let color = match color { Some(c) => parse_color(c)?, None => chosen @@ -729,6 +816,8 @@ fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result "removed": ids.len(), "page": idx + 1, "geometry": geometry_of(&geom), + "size": size, + "notes": fit.notes, }))) } Op::StepObject { @@ -1204,27 +1293,36 @@ pub fn default_ink(bg: u32) -> u32 { if is_dark(bg) { 0xf1f3f5ff } else { 0x1c2024ff } } -/// Rough text box size: ~0.55em per character, 1.3em line height (the same -/// estimate the file tools use). -fn text_box(text: &str, size: f64, w: Option, x: f64, frame: Frame) -> (f64, f64) { - let char_w = size * 0.55; - let lines: Vec<&str> = text.split('\n').collect(); - let longest = lines +/// The size of the page's own text (median of its text boxes, stamps +/// aside), so added text matches what is already there. +fn page_text_size(items: &[Item]) -> Option { + let mut sizes: Vec = items .iter() - .map(|l| l.chars().count()) - .max() - .unwrap_or(0) - .max(1) as f64; - let w = w.unwrap_or_else(|| (longest * char_w + size * 0.5).min((frame.w - x).max(size * 4.0))); - let rows: f64 = lines + .filter_map(|i| match &i.data { + ItemData::Text(t) if t.stamp.is_none() && t.size.is_finite() => Some(t.size), + _ => None, + }) + .collect(); + if sizes.is_empty() { + return None; + } + sizes.sort_by(f64::total_cmp); + Some(sizes[sizes.len() / 2].clamp(MIN_PROJECTOR_TEXT, 72.0)) +} + +/// The top-most y a text block starting at (`x`, `y`) may move up to +/// without covering what is above it on the page. +fn free_above(items: &[Item], x: f64, y: f64, frame: Frame) -> f64 { + items .iter() - .map(|l| { - ((l.chars().count().max(1) as f64 * char_w) / w) - .ceil() - .max(1.0) + .map(|i| i.data.aabb()) + .filter(|a| { + f64::from(a[2]) > x + && f64::from(a[0]) < frame.w - crate::fit::MARGIN + && f64::from(a[3]) <= y + 1.0 }) - .sum(); - (w, rows * size * 1.3) + .map(|a| f64::from(a[3]) + 16.0) + .fold(crate::fit::MARGIN, f64::max) } fn placement_warning(g: &BoxGeom, frame: Option) -> Option { @@ -1439,6 +1537,122 @@ mod tests { } } + fn text_geom(b: &Board, id: &str) -> (BoxGeom, f64) { + let it = b.lesson.item(&b.page, id).unwrap(); + let ItemData::Text(t) = it.data else { panic!() }; + (t.geom, t.size) + } + + #[test] + fn agent_text_never_leaves_the_page() { + // Regression: a paragraph at 96px near the right edge crossed the + // slide frame and the window. + let mut b = Board::new(); + let para = "Ohm's law: the current through a conductor is proportional to the voltage \ +across it when the temperature stays the same. We write V = IR, where R is the resistance in \ +ohms, I the current in amperes and V the voltage in volts. Doubling V doubles I."; + let out = b + .run(Op::AddText { + page: None, + text: para.into(), + x: 1500.0, + y: 900.0, + w: None, + size: Some(96.0), + color: None, + }) + .unwrap(); + let id = out.result["item_id"].as_str().unwrap().to_string(); + let (g, size) = text_geom(&b, &id); + let f = Frame::SLIDE_16_9; + assert!(g.x >= 0.0 && g.y >= 0.0, "{g:?}"); + assert!(g.x + g.w <= f.w && g.y + g.h <= f.h, "{g:?}"); + assert!(size <= 48.0 && size >= MIN_PROJECTOR_TEXT, "{size}"); + // The board wraps at the box width: every line fits it. + for l in crate::fit::wrap(para, size, g.w) { + assert!(crate::fit::text_width(&l, size) <= g.w + 0.5); + } + assert!( + out.result["warnings"] + .as_array() + .unwrap() + .iter() + .any(|w| w["code"] == "fit"), + "the agent is told what changed: {}", + out.result + ); + assert!( + !out.result["warnings"] + .as_array() + .unwrap() + .iter() + .any(|w| w["code"] == "placement") + ); + // Without a size, text matches the page's other text. + let out = b + .run(Op::AddText { + page: None, + text: "Next".into(), + x: 100.0, + y: 100.0, + w: None, + size: None, + color: None, + }) + .unwrap(); + assert_eq!(out.result["size"].as_f64(), Some(size)); + // Still one undo step each. + assert!(b.lesson.undo().unwrap()); + assert!(b.lesson.undo().unwrap()); + assert!(b.items().is_empty()); + } + + #[test] + fn very_long_agent_text_flows_onto_new_pages() { + let mut b = Board::new(); + let long: String = (0..1500) + .map(|i| format!("w{i}")) + .collect::>() + .join(" "); + let out = b.run(text(&long)).unwrap(); + let more = out.result["continued"].as_array().unwrap(); + assert!(!more.is_empty(), "{}", out.result); + assert_eq!(b.lesson.page_count(), 1 + more.len()); + // Every piece is inside its page and nothing is lost. + let mut words = 0; + for i in 0..b.lesson.page_count() { + let pid = b.lesson.page_id_at(i).unwrap(); + for it in b.lesson.items(&pid).unwrap() { + let ItemData::Text(t) = it.data else { continue }; + assert!(t.geom.y + t.geom.h <= 1080.0 && t.geom.x + t.geom.w <= 1920.0); + words += t.text.split_whitespace().count(); + } + } + assert_eq!(words, 1500); + // Each change is attributed to the agent. + assert!(last_message(&b.lesson).unwrap().contains("add_text")); + } + + #[test] + fn ink_to_text_stays_on_the_page() { + let mut b = Board::new(); + let id = b.stroke(); + let out = b + .run(Op::ReplaceItemsWithText { + page: None, + item_ids: vec![id], + text: "A much longer sentence than the scribble it replaces, which would run far past the right edge of the slide".into(), + x: Some(1700.0), + y: None, + size: Some(64.0), + color: None, + }) + .unwrap(); + let tid = out.result["item_id"].as_str().unwrap().to_string(); + let (g, _) = text_geom(&b, &tid); + assert!(g.x + g.w <= 1920.0 && g.y + g.h <= 1080.0, "{g:?}"); + } + fn last_message(l: &Lesson) -> Option { let f = l.loro().oplog_frontiers(); let id = f.iter().next()?; diff --git a/crates/rupok-live/src/fit.rs b/crates/rupok-live/src/fit.rs new file mode 100644 index 0000000..1bfcf6d --- /dev/null +++ b/crates/rupok-live/src/fit.rs @@ -0,0 +1,369 @@ +//! Fit agent text to the page: every text an agent adds (`add_text`, +//! `replace_items_with_text`) is sized, wrapped and placed so it stays +//! **inside the slide frame**, readable from the back of the room, never +//! running off the page or the window. +//! +//! An agent asks for a spot and maybe a size; the page decides: +//! +//! 1. **Size.** The asked size, else the size of the page's other text, else +//! [`crate::apply::DEFAULT_TEXT_SIZE`]; never bigger than an eighth of the +//! page height, and long passages are capped (a paragraph at title size is +//! what overflows). +//! 2. **Place.** The box is kept inside the frame's safe margin. +//! 3. **Wrap.** Lines wrap at the room left on the page (or the asked width, +//! if narrower), estimated with per-character widths of the board font. +//! 4. **Too tall?** Shrink step by step down to the projector minimum, then +//! move up into the free space above, then continue on a new page. +//! +//! The estimate errs wide (the board renders with Inter, `line-height` +//! 1.25), so the real text is never bigger than the box. + +use rupok_core::Frame; + +/// Space kept free from the slide edges, slide px. +pub const MARGIN: f64 = 48.0; +/// Line height of board text, in ems (`.item.text` in the board's CSS). +pub const LINE_HEIGHT: f64 = 1.25; +/// Largest text size as a fraction of the page height (a title). +const MAX_SIZE_OF_PAGE: f64 = 1.0 / 8.0; + +/// Where and how big a text goes. +#[derive(Clone, Debug, PartialEq)] +pub struct TextFit { + pub x: f64, + pub y: f64, + pub w: f64, + pub h: f64, + pub size: f64, + /// The text that fits on this page; `rest` continues on a new page. + pub text: String, + pub rest: Option, + /// What was changed from the request, for the agent. + pub notes: Vec, +} + +/// Width of one character in ems for the board font (Inter, medium): +/// a deliberately generous estimate. +pub fn char_em(c: char) -> f64 { + match c { + ' ' => 0.28, + 'i' | 'l' | 'j' | '.' | ',' | ':' | ';' | '!' | '|' | '\'' | '`' | 'I' => 0.3, + 'f' | 't' | 'r' | '(' | ')' | '[' | ']' | '{' | '}' | '"' | '1' | '-' => 0.42, + 'm' | 'w' | 'M' | 'W' | '@' | '%' | '&' => 0.9, + 'A'..='Z' => 0.7, + '0'..='9' => 0.6, + c if c.is_ascii() => 0.57, + // Emoji and CJK are a full em; Bangla and other scripts are wide. + c if (c as u32) >= 0x1F000 || ('\u{2E80}'..='\u{9FFF}').contains(&c) => 1.05, + _ => 0.66, + } +} + +/// Width of `s` in px at `size`. +pub fn text_width(s: &str, size: f64) -> f64 { + s.chars().map(char_em).sum::() * size +} + +/// Word-wrap `text` at `width` px (explicit newlines kept). Words longer +/// than a line are broken by character. +pub fn wrap(text: &str, size: f64, width: f64) -> Vec { + let width = width.max(size); + let mut out = Vec::new(); + for para in text.split('\n') { + let mut line = String::new(); + let mut lw = 0.0; + for word in para.split(' ') { + let ww = text_width(word, size); + let sp = if line.is_empty() { + 0.0 + } else { + char_em(' ') * size + }; + if !line.is_empty() && lw + sp + ww > width { + out.push(std::mem::take(&mut line)); + lw = 0.0; + } + if ww > width { + // A very long word: break it across lines. + for c in word.chars() { + let cw = char_em(c) * size; + if !line.is_empty() && lw + cw > width { + out.push(std::mem::take(&mut line)); + lw = 0.0; + } + line.push(c); + lw += cw; + } + continue; + } + if !line.is_empty() { + line.push(' '); + lw += sp; + } + line.push_str(word); + lw += ww; + } + out.push(line); + } + out +} + +/// Size of the wrapped block: `(width of the longest line, height)`. +fn block(lines: &[String], size: f64) -> (f64, f64) { + let w = lines + .iter() + .map(|l| text_width(l, size)) + .fold(0.0, f64::max); + (w, lines.len().max(1) as f64 * size * LINE_HEIGHT) +} + +/// The largest size worth using for `text` on `frame`: a title may be big, +/// a paragraph may not. +pub fn max_size_for(text: &str, frame: Frame) -> f64 { + let n = text.chars().count(); + let page_cap = frame.h * MAX_SIZE_OF_PAGE; + let cap = match n { + 0..=40 => page_cap, + 41..=120 => 64.0, + 121..=400 => 48.0, + _ => 40.0, + }; + cap.min(page_cap).max(crate::apply::MIN_PROJECTOR_TEXT) +} + +/// Fit `text` asked at (`x`, `y`) with an optional `size` and wrap width +/// `w` onto a page of `frame`. `min_size` is the smallest size it may be +/// shrunk to (the projector minimum, or the asked size when smaller). +/// `above_free` is the top-most y the block may move up to without covering +/// anything (`None`: don't move it). +pub fn fit_text( + text: &str, + size: f64, + x: f64, + y: f64, + w: Option, + frame: Frame, + above_free: Option, +) -> TextFit { + let mut notes = Vec::new(); + let asked = size; + let mut size = size.min(max_size_for(text, frame)); + if size < asked { + notes.push(format!( + "text size {asked:.0}px is too big for {} characters on a {:.0}×{:.0} page; used {size:.0}px", + text.chars().count(), + frame.w, + frame.h + )); + } + let min_size = crate::apply::MIN_PROJECTOR_TEXT.min(size); + let inner_w = (frame.w - 2.0 * MARGIN).max(size * 4.0); + + // Keep the start inside the safe area, leaving room for a few words. + let min_room = (size * 8.0).min(inner_w); + let nx = x.clamp(MARGIN, (frame.w - MARGIN - min_room).max(MARGIN)); + let ny = y.clamp(MARGIN, (frame.h - MARGIN - size * LINE_HEIGHT).max(MARGIN)); + if (nx - x).abs() > 0.5 || (ny - y).abs() > 0.5 { + notes.push(format!( + "moved from ({x:.0}, {y:.0}) to ({nx:.0}, {ny:.0}) to keep it on the page" + )); + } + let (x, mut y) = (nx, ny); + + let room_w = frame.w - MARGIN - x; + let wrap_w = match w { + Some(w) if w < room_w => w.max(size * 2.0), + _ => room_w, + }; + let fits = |size: f64, y: f64| -> (f64, f64, bool) { + let (bw, bh) = block(&wrap(text, size, wrap_w), size); + (bw, bh, y + bh <= frame.h - MARGIN + 0.5) + }; + + let (mut bw, mut bh, mut ok) = fits(size, y); + // Too tall: shrink, a step at a time, down to the minimum. + if !ok { + let start = size; + while !ok && size > min_size { + size = (size * 0.9).max(min_size).floor(); + (bw, bh, ok) = fits(size, y); + } + if (start - size).abs() > 0.5 { + notes.push(format!( + "shrank the text from {start:.0}px to {size:.0}px to fit the page" + )); + } + } + // Still too tall: move up into free space above. + if !ok && let Some(top) = above_free { + let ny = (frame.h - MARGIN - bh).max(top.max(MARGIN)); + if ny < y { + notes.push(format!("moved up to y {ny:.0} to fit the page")); + y = ny; + ok = y + bh <= frame.h - MARGIN + 0.5; + } + } + // Still too tall: what fits stays here, the rest goes on a new page. + let mut rest = None; + let mut kept = text.to_string(); + if !ok { + let per_page = (((frame.h - MARGIN - y) / (size * LINE_HEIGHT)).floor() as usize).max(1); + let (here, more) = split_lines(text, size, wrap_w, per_page); + kept = here; + rest = (!more.trim().is_empty()).then_some(more); + (bw, bh) = block(&wrap(&kept, size, wrap_w), size); + } + let w = (bw + size * 0.25).min(frame.w - MARGIN - x).max(size); + TextFit { + x, + y, + w, + h: bh, + size, + text: kept, + rest, + notes, + } +} + +/// Split `text` at a word boundary so the first part wraps into at most +/// `n` lines: `(first part, the rest)`. Paragraph breaks are kept. +fn split_lines(text: &str, size: f64, width: f64, n: usize) -> (String, String) { + // Tokens: words, and `None` for a paragraph break. + let mut tokens: Vec> = Vec::new(); + for (i, para) in text.split('\n').enumerate() { + if i > 0 { + tokens.push(None); + } + tokens.extend(para.split(' ').filter(|w| !w.is_empty()).map(Some)); + } + let render = |toks: &[Option<&str>]| -> String { + let mut out = String::new(); + for t in toks { + match t { + None => out.push('\n'), + Some(w) => { + if !out.is_empty() && !out.ends_with('\n') { + out.push(' '); + } + out.push_str(w); + } + } + } + out + }; + // The longest prefix of tokens that wraps into n lines (line counts + // only grow with the prefix: binary search). + let (mut lo, mut hi) = (1usize, tokens.len()); + while lo < hi { + let mid = (lo + hi).div_ceil(2); + if wrap(&render(&tokens[..mid]), size, width).len() <= n { + lo = mid; + } else { + hi = mid - 1; + } + } + let cut = lo.min(tokens.len()); + ( + render(&tokens[..cut]).trim_end().to_string(), + render(&tokens[cut..]).trim_start().to_string(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SLIDE: Frame = Frame::SLIDE_16_9; + + fn inside(f: &TextFit) -> bool { + f.x >= MARGIN - 0.5 + && f.y >= MARGIN - 0.5 + && f.x + f.w <= SLIDE.w - MARGIN + 0.5 + && f.y + f.h <= SLIDE.h - MARGIN + 0.5 + } + + #[test] + fn short_text_keeps_its_place_and_size() { + let f = fit_text("Ohm's law", 56.0, 200.0, 120.0, None, SLIDE, None); + assert_eq!((f.x, f.y, f.size), (200.0, 120.0, 56.0)); + assert!(f.notes.is_empty(), "{:?}", f.notes); + assert!(f.rest.is_none()); + assert!(inside(&f)); + assert!(f.w < 400.0, "{}", f.w); + } + + #[test] + fn long_text_wraps_inside_the_page_at_a_sensible_size() { + // What an agent sent in class: a paragraph at 96px, near the right. + let para = "Ohm's law says that the current through a conductor between two points is \ +directly proportional to the voltage across the two points, provided the temperature stays the same. \ +We write it as V = IR, where R is the resistance in ohms."; + let f = fit_text(para, 96.0, 1300.0, 700.0, None, SLIDE, Some(MARGIN)); + assert!(inside(&f), "{f:?}"); + assert!(f.size <= 48.0, "paragraph capped: {}", f.size); + assert!(f.size >= crate::apply::MIN_PROJECTOR_TEXT); + assert!(f.rest.is_none(), "fits on the page: {f:?}"); + // Every wrapped line fits the box. + for l in wrap(&f.text, f.size, f.w) { + assert!(text_width(&l, f.size) <= f.w + 0.5, "{l}"); + } + assert!(!f.notes.is_empty()); + } + + #[test] + fn off_page_starts_are_pulled_in() { + for (x, y) in [(-300.0, -50.0), (5000.0, 3000.0), (1900.0, 1070.0)] { + let f = fit_text("Answer: 42", 40.0, x, y, None, SLIDE, None); + assert!(inside(&f), "{x},{y}: {f:?}"); + } + let f = fit_text("x", 40.0, f64::MAX / 4.0, 0.0, Some(1e9), SLIDE, None); + assert!(inside(&f)); + } + + #[test] + fn too_much_text_continues_on_a_new_page() { + let long: String = (0..1200) + .map(|i| format!("word{i}")) + .collect::>() + .join(" "); + let f = fit_text(&long, 32.0, 100.0, 100.0, None, SLIDE, Some(MARGIN)); + assert!(inside(&f), "{f:?}"); + let rest = f.rest.as_deref().expect("continues"); + // Nothing is lost: both parts together hold every word, in order. + let joined = format!("{} {}", f.text, rest); + let words: Vec<&str> = joined.split_whitespace().collect(); + assert_eq!(words.len(), 1200); + assert_eq!(words[0], "word0"); + assert_eq!(words[1199], "word1199"); + assert_eq!(f.size, crate::apply::MIN_PROJECTOR_TEXT); + } + + #[test] + fn wrap_respects_newlines_and_breaks_long_words() { + let l = wrap("ab\ncd", 20.0, 1000.0); + assert_eq!(l, vec!["ab", "cd"]); + let l = wrap(&"x".repeat(200), 20.0, 300.0); + assert!(l.len() > 1); + for s in &l { + assert!(text_width(s, 20.0) <= 300.0 + 0.01); + } + // Bangla and emoji count as wide. + assert!(text_width("পদার্থবিজ্ঞান", 32.0) > text_width("abcdefghijklm", 32.0)); + } + + #[test] + fn narrow_width_asked_is_kept_when_it_fits() { + let f = fit_text( + "one two three four five six", + 32.0, + 100.0, + 100.0, + Some(200.0), + SLIDE, + None, + ); + assert!(f.w <= 200.0 + 8.0 + 0.5, "{}", f.w); + assert!(f.h > 32.0 * LINE_HEIGHT * 1.5, "wrapped onto several lines"); + } +} diff --git a/crates/rupok-live/src/handwriting.rs b/crates/rupok-live/src/handwriting.rs index 5e6e4e0..034f2d0 100644 --- a/crates/rupok-live/src/handwriting.rs +++ b/crates/rupok-live/src/handwriting.rs @@ -28,6 +28,8 @@ const MARGIN: f64 = 40.0; const MAX_STROKES: usize = 4_000; /// Default capital height when nothing on the board says otherwise. const DEFAULT_CAP: f64 = 40.0; +/// Sizes tried (of the asked letter height) to make the writing fit. +const SCALES: [f32; 5] = [1.0, 0.85, 0.7, 0.58, 0.48]; /// How the problem is written, so the solution matches it. #[derive(Clone, Copy, Debug, PartialEq)] @@ -192,12 +194,13 @@ pub fn run( } }; let teacher_available = glyphs.user_chars() > 0; - let prefer_user = match style.as_deref() { - None | Some("teacher") | Some("mine") => true, - Some("neat") => false, + let (prefer_user, connect) = match style.as_deref() { + None | Some("teacher") | Some("mine") => (true, false), + Some("neat") => (false, false), + Some("joined") | Some("cursive") => (false, true), Some(other) => { return Err(LiveError::Invalid(format!( - "style must be \"teacher\" or \"neat\", not {other:?}" + "style must be \"teacher\", \"neat\" or \"joined\", not {other:?}" ))); } }; @@ -210,7 +213,20 @@ pub fn run( // What we write next to: the anchor's items, else its region, else the // teacher's selection (on the board's page). let mut target_items: Vec<&Item> = Vec::new(); - if let Some(ids) = &anchor.item_ids { + let mut join_group: Option = None; + if let Some(g) = &anchor.group { + target_items = items + .iter() + .filter(|i| i.group.as_deref() == Some(g.as_str())) + .collect(); + if target_items.is_empty() { + return Err(LiveError::NotFound(format!( + "no writing with group {g:?} on page {}; use the group an earlier write_handwriting returned (and its page)", + idx + 1 + ))); + } + join_group = Some(g.clone()); + } else if let Some(ids) = &anchor.item_ids { let missing: Vec<&str> = ids .iter() .filter(|id| !items.iter().any(|i| &i.id == *id)) @@ -270,6 +286,7 @@ pub fn run( x_height: xh, max_width: Some(max_w as f32), prefer_user, + connect, speed: speed as f32, seed: joined.len() as u64, ..WriteOptions::default() @@ -296,13 +313,21 @@ pub fn run( let mut placed: Option<(f64, f64, Written)> = None; let mut new_page = false; if let (Some(x), Some(y)) = (anchor.x, anchor.y) { - let x = finite("anchor.x", x)?; - let y = finite("anchor.y", y)?; - let w = synth( - (frame.w - x - MARGIN).max(f64::from(x_height) * 6.0), - x_height, - ); - placed = Some((x, y, w)); + // An explicit spot, kept on the page: wrap at the room to the right, + // shrink if the block runs off the bottom, else continue on a new page. + let x = finite("anchor.x", x)?.clamp(MARGIN * 0.5, frame.w - MARGIN * 4.0); + let y = finite("anchor.y", y)?.clamp(MARGIN * 0.5, frame.h - MARGIN * 2.0); + let max_w = (frame.w - x - MARGIN).max(f64::from(x_height) * 6.0); + for scale in SCALES { + let w = synth(max_w, x_height * scale); + if y + f64::from(w.height) <= frame.h - MARGIN * 0.5 { + placed = Some((x, y, w)); + break; + } + } + if placed.is_none() { + new_page = true; + } } else { let t = target.unwrap_or([ MARGIN * 2.0, @@ -312,12 +337,15 @@ pub fn run( ]); let below = (t[0].clamp(MARGIN, frame.w - MARGIN * 4.0), t[3] + gap); let right = (t[2] + gap * 1.5, t[1]); - let sides = if anchor.side.as_deref() == Some("right") { + let sides = if join_group.is_some() { + // Continuing: always straight below, left-aligned with it. + [below, below] + } else if anchor.side.as_deref() == Some("right") { [right, below] } else { [below, right] }; - 'search: for scale in [1.0f32, 0.8, 0.65] { + 'search: for scale in SCALES { for (x, y) in sides { let max_w = frame.w - x - MARGIN; if max_w < f64::from(x_height) * 8.0 { @@ -350,7 +378,26 @@ pub fn run( tag(ctx.lesson, msg); page_id = ctx.lesson.add_page(Some(idx + 1), spec)?; page_no = idx + 2; - let w = synth(frame.w - MARGIN * 4.0, x_height); + // The whole block must fit the new page: shrink until it does. + let room = frame.h - MARGIN * 3.0; + let max_w = frame.w - MARGIN * 4.0; + let mut xh = x_height; + let mut w = synth(max_w, xh); + for scale in SCALES { + xh = x_height * scale; + w = synth(max_w, xh); + if f64::from(w.height) <= room { + break; + } + } + // Still too tall (many lines, huge letters): scale to the room. + for _ in 0..4 { + if f64::from(w.height) <= room { + break; + } + xh = (xh * (room / f64::from(w.height).max(1.0)) as f32 * 0.97).max(5.0); + w = synth(max_w, xh); + } placed = Some((MARGIN * 2.0, MARGIN * 2.0, w)); } let Some((x0, y0, written)) = placed else { @@ -363,7 +410,11 @@ pub fn run( ))); } - let group = ctx.lesson.new_group_id(); + // Continuing earlier writing on the same page joins its group. + let group = match &join_group { + Some(g) if !new_page => g.clone(), + _ => ctx.lesson.new_group_id(), + }; let (ox, oy) = (x0 as f32, y0 as f32); let list: Vec = written .strokes @@ -416,7 +467,7 @@ pub fn run( "h": (f64::from(written.height) * 10.0).round() / 10.0, }, "duration_ms": written.duration_ms.round(), - "style": if used_teacher { "teacher" } else { "neat" }, + "style": if connect { "joined" } else if used_teacher { "teacher" } else { "neat" }, "step_mode": step_mode, "speed": speed, "ink": { "color": crate::apply::color_hex(color), "width": width, "letter_height": (cap * 10.0).round() / 10.0 }, @@ -645,6 +696,77 @@ mod tests { assert_eq!(out.result["style"], "neat"); } + fn bounds(r: &Value) -> [f64; 4] { + let b = &r["bounds"]; + let (x, y) = (b["x"].as_f64().unwrap(), b["y"].as_f64().unwrap()); + [ + x, + y, + x + b["w"].as_f64().unwrap(), + y + b["h"].as_f64().unwrap(), + ] + } + + #[test] + fn handwriting_always_fits_the_page() { + // An explicit spot near the bottom right, big letters, many lines. + let mut b = Board::new(); + let lines: Vec = (0..14) + .map(|i| format!("Line {i}: $a_{i} + b = c$")) + .collect(); + let out = b + .run(json!({"op": "write_handwriting", "lines": lines, "anchor": {"x": 1800, "y": 1000}, "size": 90})) + .unwrap(); + let r = &out.result; + let bb = bounds(r); + assert!(bb[0] >= 0.0 && bb[1] >= 0.0, "{bb:?}"); + assert!( + bb[2] <= 1920.0 && bb[3] <= 1080.0, + "inside the slide: {bb:?}" + ); + // Every stroke point is on the page it was written on. + let page = r["page"].as_u64().unwrap() as usize - 1; + let pid = b.lesson.page_id_at(page).unwrap(); + for it in b.lesson.items(&pid).unwrap() { + let a = it.data.aabb(); + assert!( + a[0] >= 0.0 && a[1] >= 0.0 && a[2] <= 1920.0 && a[3] <= 1080.0, + "{a:?}" + ); + } + // Huge sizes are clamped and still fit. + let mut b = Board::new(); + let out = b + .run(json!({"op": "write_handwriting", "lines": vec!["$x^2 + y^2 = r^2$"; 12], "size": 200})) + .unwrap(); + let bb = bounds(&out.result); + assert!(bb[2] <= 1920.0 && bb[3] <= 1080.0, "{bb:?}"); + } + + #[test] + fn streamed_lines_continue_the_same_group() { + let mut b = Board::new(); + let ids = b.problem(200.0, 100.0); + let first = b + .run(json!({"op": "write_handwriting", "lines": ["$2x = 4$"], "anchor": {"item_ids": ids}})) + .unwrap(); + let group = first.result["group"].as_str().unwrap().to_string(); + let b1 = bounds(&first.result); + let second = b + .run(json!({"op": "write_handwriting", "lines": ["$x = 2$"], "anchor": {"group": group}, "style": "joined"})) + .unwrap(); + assert_eq!(second.result["group"], first.result["group"]); + assert_eq!(second.result["style"], "joined"); + let b2 = bounds(&second.result); + assert!(b2[1] >= b1[3] - 1.0, "below the first line: {b1:?} {b2:?}"); + assert!((b2[0] - b1[0]).abs() < 30.0, "left-aligned: {b1:?} {b2:?}"); + // Unknown groups are an error, not a guess. + assert!( + b.run(json!({"op": "write_handwriting", "lines": ["x"], "anchor": {"group": "nope"}})) + .is_err() + ); + } + #[test] fn bad_input_is_an_error_and_changes_nothing() { let mut b = Board::new(); diff --git a/crates/rupok-live/src/lib.rs b/crates/rupok-live/src/lib.rs index f0fa03c..228e6d0 100644 --- a/crates/rupok-live/src/lib.rs +++ b/crates/rupok-live/src/lib.rs @@ -29,8 +29,10 @@ pub mod apply; pub mod attribution; pub mod design; +pub mod fit; pub mod handwriting; pub mod op; +pub mod progress; pub mod protocol; pub use apply::{BoardCtx, LiveError, Outcome, apply, apply_with, doc_key}; diff --git a/crates/rupok-live/src/op.rs b/crates/rupok-live/src/op.rs index de30925..509f4a6 100644 --- a/crates/rupok-live/src/op.rs +++ b/crates/rupok-live/src/op.rs @@ -59,6 +59,11 @@ pub struct Anchor { /// `below` (default) or `right` of the items or region. #[serde(default, skip_serializing_if = "Option::is_none")] pub side: Option, + /// Continue earlier writing: the `group` an earlier `write_handwriting` + /// returned. The new lines go right below it, in its ink, and join its + /// group (so a solution streamed line by line selects and moves as one). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub group: Option, } /// Arguments of [`Op::SetPageDesign`]. @@ -429,6 +434,11 @@ pub enum Op { #[serde(default)] text_size: Option, }, + /// A "working" card on the board while the agent builds something: the + /// spot where the result will appear, the current step, the plan and an + /// optional live preview. Run by the board app; not saved in the lesson. + /// See [`crate::progress`]. + ShowProgress(Box), /// Move a Smart Object's build step: absolute `step`, or `delta` (default +1). StepObject { #[serde(default)] @@ -481,6 +491,7 @@ impl Op { Op::WriteHandwriting { .. } => "write_handwriting", Op::AddShape { .. } => "add_shape", Op::AddTable { .. } => "add_table", + Op::ShowProgress(_) => "show_progress", } } @@ -489,7 +500,7 @@ impl Op { Op::GetPage { .. } | Op::GetOutline | Op::GetSelection | Op::Snapshot { .. } => { Access::Read } - Op::GoToPage { .. } | Op::PointAt { .. } => Access::Control, + Op::GoToPage { .. } | Op::PointAt { .. } | Op::ShowProgress(_) => Access::Control, Op::SetBoardTheme { page_color, pattern, @@ -528,6 +539,7 @@ impl Op { Op::WriteHandwriting { .. } => "wrote on the board", Op::AddShape { .. } => "drew a shape", Op::AddTable { .. } => "drew a table", + Op::ShowProgress(_) => "showed its progress", } } } diff --git a/crates/rupok-live/src/progress.rs b/crates/rupok-live/src/progress.rs new file mode 100644 index 0000000..f64f16d --- /dev/null +++ b/crates/rupok-live/src/progress.rs @@ -0,0 +1,245 @@ +//! `show_progress`: the agent's "working" card on the board. +//! +//! While an agent builds something for the class (a simulation, a worked +//! solution, a diagram), the board shows a card where the result will land: +//! a soft animated outline, the agent's name, its current step ("Writing the +//! simulation…", "Testing…"), its plan as a checklist, an optional live +//! preview, and a cancel button for the teacher. When the result arrives the +//! card resolves into it (the board animates the result in). +//! +//! The in-app chat makes these cards by itself from the agent's ACP plan and +//! tool calls. Any agent can also post and update one explicitly with this +//! op, e.g. from `rupok mcp --live`: +//! +//! ```json +//! {"op": "show_progress", "id": "caffeine", "title": "Caffeine molecule", +//! "step": "Placing the atoms…", "kind": "object", "percent": 40, +//! "plan": [{"content": "Atoms", "status": "completed"}, +//! {"content": "Bonds", "status": "in_progress"}], +//! "x": 320, "y": 180, "w": 1280, "h": 720} +//! ``` +//! +//! then `{"op": "show_progress", "id": "caffeine", "state": "done"}` (or +//! simply place the object: a card whose area receives the result resolves +//! by itself). Cards are not saved in the lesson; they vanish after `done`, +//! `failed` + a while, `clear`, or two minutes without an update. + +use serde::{Deserialize, Serialize}; + +use crate::apply::LiveError; + +/// Most plan entries shown. +pub const MAX_PLAN: usize = 12; +/// Longest title and step, in characters. +pub const MAX_TITLE: usize = 120; +pub const MAX_STEP: usize = 200; +/// Largest live preview (HTML, rendered in the Smart Object sandbox). +pub const MAX_PREVIEW_BYTES: usize = 512 * 1024; + +/// One plan entry (ACP `PlanEntry` shape: `content`, `status`). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct PlanEntry { + #[serde(alias = "text", alias = "title")] + pub content: String, + /// `pending`, `in_progress` or `completed`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub status: Option, +} + +/// Arguments of [`crate::Op::ShowProgress`]. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct ProgressArgs { + /// The card to create or update. Omit to create a new card; the board + /// answers with its id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id: Option, + /// What is being made ("Caffeine molecule"). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + /// The current step ("Writing the simulation…"). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub step: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan: Option>, + /// 0–100, when the agent knows. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub percent: Option, + /// `working` (default), `done`, `failed` or `clear` (remove now). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub state: Option, + /// What will land: `object`, `handwriting`, `text`, `shape` or `other`; + /// sets the card's icon and how the result animates in. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kind: Option, + /// Where the result will go, slide px. Default: a free spot on the page. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub x: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub y: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub w: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub h: Option, + /// 1-based page; default the page on screen. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub page: Option, + /// A partial Smart Object (HTML) to show as a live preview thumbnail + /// while building. Runs in the same sandbox as Smart Objects. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preview_html: Option, + /// A short message for a failed card ("The simulation did not pass the + /// checks; fixing it"). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +const STATES: [&str; 4] = ["working", "done", "failed", "clear"]; +const KINDS: [&str; 5] = ["object", "handwriting", "text", "shape", "other"]; + +impl ProgressArgs { + /// Check an agent's card: known state and kind, finite geometry, bounded + /// text and preview. Long text is an error, not silently cut, so the + /// agent learns the limits. + pub fn validate(&self) -> Result<(), LiveError> { + let bad = |m: String| Err(LiveError::Invalid(m)); + if let Some(s) = &self.state + && !STATES.contains(&s.as_str()) + { + return bad(format!("state must be one of {STATES:?}, not {s:?}")); + } + if let Some(k) = &self.kind + && !KINDS.contains(&k.as_str()) + { + return bad(format!("kind must be one of {KINDS:?}, not {k:?}")); + } + if let Some(id) = &self.id + && (id.is_empty() || id.len() > 64) + { + return bad("id must be 1 to 64 characters".into()); + } + if self + .title + .as_ref() + .is_some_and(|t| t.chars().count() > MAX_TITLE) + { + return bad(format!("title is longer than {MAX_TITLE} characters")); + } + if self + .step + .as_ref() + .is_some_and(|t| t.chars().count() > MAX_STEP) + { + return bad(format!("step is longer than {MAX_STEP} characters")); + } + if let Some(p) = &self.plan { + if p.len() > MAX_PLAN { + return bad(format!("at most {MAX_PLAN} plan entries")); + } + if p.iter().any(|e| e.content.chars().count() > MAX_STEP) { + return bad(format!("plan entries are at most {MAX_STEP} characters")); + } + } + if let Some(v) = self.percent + && !(v.is_finite() && (0.0..=100.0).contains(&v)) + { + return bad("percent must be between 0 and 100".into()); + } + for (name, v) in [("x", self.x), ("y", self.y), ("w", self.w), ("h", self.h)] { + if let Some(v) = v + && !(v.is_finite() && v.abs() < 1e6) + { + return bad(format!("{name} must be a finite number of slide pixels")); + } + } + if self.w.is_some_and(|w| w <= 0.0) || self.h.is_some_and(|h| h <= 0.0) { + return bad("w and h must be positive".into()); + } + if self + .preview_html + .as_ref() + .is_some_and(|h| h.len() > MAX_PREVIEW_BYTES) + { + return bad(format!( + "preview_html is larger than {} KiB; send a smaller partial object", + MAX_PREVIEW_BYTES / 1024 + )); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::op::{Access, Op}; + use serde_json::json; + + fn op(v: serde_json::Value) -> Op { + serde_json::from_value(v).unwrap() + } + + #[test] + fn progress_op_shape_and_access() { + let o = op(json!({ + "op": "show_progress", "id": "caffeine", "title": "Caffeine", "step": "Bonds…", + "kind": "object", "percent": 40, + "plan": [{"content": "Atoms", "status": "completed"}, {"text": "Bonds"}], + "x": 320, "y": 180, "w": 1280, "h": 720 + })); + assert_eq!(o.name(), "show_progress"); + // It changes what the class sees, not the lesson: like point_at. + assert_eq!(o.access(), Access::Control); + let Op::ShowProgress(a) = &o else { panic!() }; + assert_eq!(a.plan.as_ref().unwrap()[1].content, "Bonds"); + a.validate().unwrap(); + // Round trip keeps the tag. + let v = serde_json::to_value(&o).unwrap(); + assert_eq!(v["op"], "show_progress"); + assert_eq!(v["id"], "caffeine"); + // The lesson document refuses it: the board app runs it. + let mut lesson = rupok_core::Lesson::new("t", 1.0); + let mut pkg = rupok_format::Package::from_lesson(&lesson, "t", 1.0); + let page = lesson.page_id_at(0).unwrap(); + let v0 = lesson.version(); + let r = crate::apply( + crate::BoardCtx { + pkg: &mut pkg, + lesson: &mut lesson, + page_id: &page, + selection: &[], + read_only: false, + }, + &o, + "Claude", + 1.0, + ); + assert!(matches!(r, Err(LiveError::Unsupported("show_progress")))); + assert_eq!(lesson.version(), v0); + } + + #[test] + fn progress_validation() { + for bad in [ + json!({"op": "show_progress", "state": "exploded"}), + json!({"op": "show_progress", "kind": "nuke"}), + json!({"op": "show_progress", "percent": 140}), + json!({"op": "show_progress", "w": -4}), + json!({"op": "show_progress", "id": ""}), + json!({"op": "show_progress", "title": "x".repeat(500)}), + json!({"op": "show_progress", "plan": vec![json!({"content": "a"}); 20]}), + json!({"op": "show_progress", "preview_html": "x".repeat(MAX_PREVIEW_BYTES + 1)}), + ] { + let Op::ShowProgress(a) = op(bad.clone()) else { + panic!() + }; + assert!(a.validate().is_err(), "{bad}"); + } + let Op::ShowProgress(a) = op(json!({"op": "show_progress", "state": "done", "id": "x"})) + else { + panic!() + }; + a.validate().unwrap(); + // Unknown ops are still refused. + assert!(serde_json::from_value::(json!({"op": "show_progress_now"})).is_err()); + } +} diff --git a/crates/rupok-wasm/src/engine/reveal.rs b/crates/rupok-wasm/src/engine/reveal.rs index 95ecb63..664afdd 100644 --- a/crates/rupok-wasm/src/engine/reveal.rs +++ b/crates/rupok-wasm/src/engine/reveal.rs @@ -9,6 +9,12 @@ //! //! In step mode (Teach, "one line per click") the writing pauses before each //! line until the teacher presses Next ([`Engine::reveal_next`]). +//! +//! Writing that arrives while a reveal is running (a solution streamed line by +//! line) is queued after it instead of cutting it short. Agent shapes and +//! tables are "drawn on" the same way ([`Engine::reveal_draw_on`]): their +//! strokes have no pen timing, so each is drawn along its points over a +//! moment set by its length. use rupok_core::{ItemData, ItemId}; @@ -21,6 +27,8 @@ struct RevealItem { start: f64, dur: f64, line: usize, + /// No pen timing (a shape): drawn by the share of its points. + synthetic: bool, } #[derive(Clone, Debug)] @@ -77,7 +85,6 @@ impl Engine { /// `lines[i]` is stroke i's line; with `step`, only the first line is /// written until [`Self::reveal_next`]. Strokes not on this page are skipped. pub fn reveal_start(&mut self, ids: &[ItemId], lines: &[usize], step: bool, now_ms: f64) { - self.reveal_finish(); let mut items: Vec = Vec::with_capacity(ids.len()); for (k, id) in ids.iter().enumerate() { let Some(it) = self.scene.get(id) else { @@ -91,8 +98,45 @@ impl Engine { start: it.created, dur: f64::from(s.points.last().map_or(0, |p| p.dt)), line: lines.get(k).copied().unwrap_or(0), + synthetic: false, }); } + self.push_reveal(items, step, now_ms); + } + + /// Draw agent shapes on stroke by stroke: each stroke grows along its + /// points over 150–700 ms (by its length), one after another. + pub fn reveal_draw_on(&mut self, ids: &[ItemId], now_ms: f64) { + let mut items = Vec::with_capacity(ids.len()); + let mut t = 0.0; + for id in ids { + let Some(it) = self.scene.get(id) else { + continue; + }; + let ItemData::Stroke(s) = &it.data else { + continue; + }; + let len: f64 = s + .points + .windows(2) + .map(|w| f64::from((w[1].x - w[0].x).hypot(w[1].y - w[0].y))) + .sum(); + let dur = (len / 2.2).clamp(150.0, 700.0); + items.push(RevealItem { + id: id.clone(), + start: t, + dur, + line: 0, + synthetic: true, + }); + t += dur + 60.0; + } + self.push_reveal(items, false, now_ms); + } + + /// Start revealing `items` (start times in any origin), or queue them + /// after a reveal already running (not in step mode). + fn push_reveal(&mut self, mut items: Vec, step: bool, now_ms: f64) { if items.is_empty() || self.replay.is_some() { return; } @@ -100,9 +144,30 @@ impl Engine { let t0 = items[0].start; for i in &mut items { i.start -= t0; - self.sink.remove_stroke(&i.id); } let n_lines = items.iter().map(|i| i.line + 1).max().unwrap_or(1); + if !step + && let Some(r) = &mut self.reveal + && !r.step + { + // Queue after what is being written, with a short breath. + let end = r.items.last().map_or(r.t, |i| i.start + i.dur).max(r.t); + let base = end + 150.0; + for i in &mut items { + i.start += base; + i.line += r.lines; + self.sink.remove_stroke(&i.id); + } + r.lines += n_lines; + r.gate = r.lines; + r.items.extend(items); + self.dirty = true; + return; + } + self.reveal_finish(); + for i in &items { + self.sink.remove_stroke(&i.id); + } self.reveal = Some(Reveal { items, t: 0.0, @@ -164,10 +229,19 @@ impl Engine { return None; }; let local = r.t - i.start; + let take = if i.synthetic { + let n = s.points.len(); + ((local / i.dur.max(1.0)).clamp(0.0, 1.0) * n as f64).ceil() as usize + } else { + s.points + .iter() + .take_while(|p| f64::from(p.dt) <= local) + .count() + }; let pts: Vec<_> = s .points .iter() - .take_while(|p| f64::from(p.dt) <= local) + .take(take.max(1)) .map(|p| rupok_ink::StrokePoint { x: p.x + s.offset[0], y: p.y + s.offset[1], diff --git a/crates/rupok-wasm/src/live.rs b/crates/rupok-wasm/src/live.rs index 2c3b104..088294f 100644 --- a/crates/rupok-wasm/src/live.rs +++ b/crates/rupok-wasm/src/live.rs @@ -115,7 +115,20 @@ pub fn apply( serde_json::from_str(op_json).map_err(|err| error_json(format!("bad op: {err}")))?; // Shapes and tables: geometry lives in the engine (`engine/insert.rs`). if matches!(op, Op::AddShape { .. } | Op::AddTable { .. }) { - return e.ai_insert(&op, agent, now_ms); + let out = e.ai_insert(&op, agent, now_ms)?; + // Draw the shape on in front of the class, stroke by stroke. + if let Ok(v) = serde_json::from_str::(&out) { + let ids: Vec = v["item_ids"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|x| x.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(); + e.reveal_draw_on(&ids, now_ms); + } + return Ok(out); } let page = e.page_id().to_string(); let selection = e.selection().to_vec(); @@ -317,6 +330,71 @@ mod tests { assert!(e.sink.strokes.is_empty()); } + #[test] + fn streamed_lines_queue_behind_the_writing() { + // A solution streamed line by line: the second write must not cut + // the first one short; both are written in order. + let mut e = engine(); + let r = apply( + &mut e, + r#"{"op":"write_handwriting","lines":["$2x = 4$"],"anchor":{"x":100,"y":100}}"#, + "Claude", + 1_000.0, + ) + .unwrap(); + let v: serde_json::Value = serde_json::from_str(&r).unwrap(); + let n1 = v["strokes"].as_u64().unwrap() as usize; + let group = v["group"].as_str().unwrap().to_string(); + e.tick(1_050.0); + let r2 = apply( + &mut e, + &format!( + r#"{{"op":"write_handwriting","lines":["$x = 2$"],"anchor":{{"group":"{group}"}}}}"# + ), + "Claude", + 1_100.0, + ) + .unwrap(); + let v2: serde_json::Value = serde_json::from_str(&r2).unwrap(); + let n2 = v2["strokes"].as_u64().unwrap() as usize; + assert!( + e.sink.strokes.len() < n1, + "the first line is still being written, not finished at once" + ); + let st = e.reveal_state().unwrap(); + assert_eq!(st.total, n1 + n2, "queued"); + let mut t = 1_100.0; + while e.reveal_state().is_some() && t < 60_000.0 { + t += 50.0; + e.tick(t); + } + assert_eq!(e.sink.strokes.len(), n1 + n2); + } + + #[test] + fn agent_shapes_are_drawn_on() { + let mut e = engine(); + let r = apply( + &mut e, + r##"{"op":"add_shape","shape":"rect","x":100,"y":100,"w":400,"h":200}"##, + "Claude", + 1_000.0, + ) + .unwrap(); + assert!(r.contains("item_ids")); + assert!(e.reveal_state().is_some(), "drawing on"); + assert_eq!(e.sink.strokes.len(), 0); + let mut t = 1_000.0; + let mut partial = false; + while e.reveal_state().is_some() && t < 10_000.0 { + t += 40.0; + e.tick(t); + partial |= e.has_animation(); + } + assert!(partial, "the outline grows"); + assert!(!e.sink.strokes.is_empty(), "then it is on the board"); + } + #[test] fn step_mode_waits_for_next_before_each_line() { let mut e = engine(); From da4200752b2d568cb0c3639421dc5d2543e402e5 Mon Sep 17 00:00:00 2001 From: shaitrish37 <244331886+shaitrish37@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:27:17 +0600 Subject: [PATCH 2/5] MCP: tool annotations, show_progress tool, act-don't-ask instructions Every tool says readOnlyHint / destructiveHint (real deletes only) / idempotentHint so clients can auto-allow safe calls. The fake ACP agent streams plans, progress cards, a failing then fixed Smart Object, long text, a delete, a streamed solve and a student's ask. --- crates/rupok-cli/src/lib.rs | 4 +- crates/rupok-cli/src/mcp.rs | 28 +++- crates/rupok-cli/src/mcp_live.rs | 19 ++- crates/rupok-cli/src/mcp_progress.rs | 149 ++++++++++++++++++++++ crates/rupok-cli/tests/fake-acp-agent.mjs | 133 +++++++++++++++++++ 5 files changed, 326 insertions(+), 7 deletions(-) create mode 100644 crates/rupok-cli/src/mcp_progress.rs diff --git a/crates/rupok-cli/src/lib.rs b/crates/rupok-cli/src/lib.rs index f084648..2680f58 100644 --- a/crates/rupok-cli/src/lib.rs +++ b/crates/rupok-cli/src/lib.rs @@ -4,7 +4,8 @@ //! - [`ops`]: lesson operations on resolved paths (shared by CLI and MCP). //! - [`tools`]: the MCP tool surface as plain Rust (params + [`tools::Tools`]). //! - [`mcp`]: the rmcp stdio server wrapping [`tools::Tools`]. -//! - [`live`], [`mcp_live`]: the live board channel (`rupok mcp --live`) and its tools. +//! - [`live`], [`mcp_live`]: the live board channel (`rupok mcp --live`) and its tools; +//! [`mcp_progress`]: `show_progress`, the agent's working card on the board. //! - [`cli`]: the clap command line. //! - [`spec`]: the Smart Object spec served to agents. @@ -14,6 +15,7 @@ pub mod live; pub mod mcp; pub mod mcp_http; pub mod mcp_live; +pub mod mcp_progress; pub mod ops; pub mod spec; pub mod tools; diff --git a/crates/rupok-cli/src/mcp.rs b/crates/rupok-cli/src/mcp.rs index 40fcf5a..600d917 100644 --- a/crates/rupok-cli/src/mcp.rs +++ b/crates/rupok-cli/src/mcp.rs @@ -55,7 +55,16 @@ Draw it as SVG; keep the content area calm, ink readable (light ink on dark page corner; read the current design first by calling the tool with only `path`.\n\ - To solve a problem written on the board, read it (`get_page_snapshot` with its item_ids), check every \ step, then `write_handwriting` the solution as short lines; the board writes it in handwriting next to \ -the problem. If the result says `preview`, the teacher is checking it first: do not write it again.", +the problem. If the result says `preview`, the teacher is checking it first: do not write it again. To write \ +line by line as you work, call it once per line with `anchor: {{\"group\": }}`.\n\ +\n\ +In class, act; don't ask. Routine requests (a page, text, a diagram, a Smart Object, a quiz, a solution, a \ +translation) are yours to just do with sensible defaults: no clarifying questions, no \"shall I?\". Ask only \ +before deleting or clearing anything, replacing the teacher's ink, or changing settings or the mode.\n\ +AI in action: for anything that takes more than a few seconds, first call `show_progress` with the box where \ +the result will go (and `kind`), update its `step` as you work (same `id`; `preview_html` for a partial Smart \ +Object), then place the result in exactly that box: the card turns into it in front of the class. Text you add \ +is fitted to the page (wrapped, shrunk if needed, never off the slide); prefer short lines and 32–48px.", libs = rupok_format::LIBS.join(", ") ) } @@ -81,7 +90,9 @@ impl McpServer { Self { tools: Arc::new(tools), live, - tool_router: Self::tool_router() + Self::live_tool_router(), + tool_router: Self::tool_router() + + Self::live_tool_router() + + Self::progress_tool_router(), } } @@ -155,6 +166,7 @@ Fails if the file already exists. Returns the page ids.", annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -184,6 +196,7 @@ title, bundle_id, declared steps and current step). Call this before editing an annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -203,6 +216,7 @@ update_smart_object), the placed geometry and any warnings. Default size 1280×7 annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -225,6 +239,7 @@ autoplay when the page is shown; offline, the board shows the poster and says it annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -240,6 +255,7 @@ Khan Academy (other sites are refused: write the link as text instead). Returns annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -255,6 +271,7 @@ with the clicker. Returns item_id and bundle_id.", annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -287,7 +304,7 @@ Optionally change its step count or allowed network hosts. Re-validated first: o the diagnostics are returned.", annotations( read_only_hint = false, - destructive_hint = true, + destructive_hint = false, idempotent_hint = true, open_world_hint = false ) @@ -310,6 +327,7 @@ frame. Font size defaults to 32px; keep it 24px or larger so it is readable on a annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -345,7 +363,7 @@ the item id shown in get_lesson_outline.", annotations( read_only_hint = false, destructive_hint = true, - idempotent_hint = false, + idempotent_hint = true, open_world_hint = false ) )] @@ -361,7 +379,7 @@ the item id shown in get_lesson_outline.", as #rrggbb.", annotations( read_only_hint = false, - destructive_hint = true, + destructive_hint = false, idempotent_hint = true, open_world_hint = false ) diff --git a/crates/rupok-cli/src/mcp_live.rs b/crates/rupok-cli/src/mcp_live.rs index a912457..36323b4 100644 --- a/crates/rupok-cli/src/mcp_live.rs +++ b/crates/rupok-cli/src/mcp_live.rs @@ -351,6 +351,11 @@ pub struct AnchorArg { /// full the board tries the other, then a new page. #[serde(default)] pub side: Option, + /// Continue earlier writing: the `group` an earlier write_handwriting + /// returned. The lines go right below it and join it, so you can write a + /// solution line by line as you work it out. + #[serde(default)] + pub group: Option, } #[derive(Clone, Debug, Deserialize, JsonSchema)] @@ -366,7 +371,8 @@ pub struct WriteHandwritingParams { #[serde(default)] pub anchor: Option, /// `teacher` (default): the teacher's own handwriting where they have - /// taught it to Rupok; `neat`: a neat standard hand. + /// taught it to Rupok; `neat`: a neat standard hand; `joined`: neat + /// letters joined within words, like quick cursive. #[serde(default)] pub style: Option, /// Pen speed, 0.25 to 4. Default: the teacher's setting (1 = brisk). @@ -514,6 +520,7 @@ with the lesson tools and the live tools (get_current_page, get_page_snapshot, annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = true, open_world_hint = false ) )] @@ -610,6 +617,7 @@ the teacher asks, or once a page you built is ready to present.", annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = true, open_world_hint = false ) )] @@ -625,6 +633,7 @@ content on it with path \"live\" and that page, then go_to_page when ready (or p annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -648,6 +657,7 @@ object you built, or when the teacher says \"next step\" / \"show the answer\"." annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -669,6 +679,7 @@ teacher's Ctrl+Z brings the ink back). Read the handwriting first with get_page_ annotations( read_only_hint = false, destructive_hint = true, + idempotent_hint = false, open_world_hint = false ) )] @@ -696,6 +707,7 @@ Coordinates are slide pixels on the page being shown.", annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = true, open_world_hint = false ) )] @@ -724,6 +736,7 @@ do NOT call it again; explain the steps in chat instead.", annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -742,6 +755,7 @@ do NOT call it again; explain the steps in chat instead.", x: a.x, y: a.y, side: a.side, + group: a.group, }); self.live_call(Op::WriteHandwriting { page: p.page, @@ -766,6 +780,7 @@ their own shapes. One undo step; returns the new item ids.", annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -793,6 +808,7 @@ can move, resize and edit (add or remove rows and columns, type in cells). One u annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = false, open_world_hint = false ) )] @@ -821,6 +837,7 @@ page colour automatically; new text you add picks a readable colour for it. Use annotations( read_only_hint = false, destructive_hint = false, + idempotent_hint = true, open_world_hint = false ) )] diff --git a/crates/rupok-cli/src/mcp_progress.rs b/crates/rupok-cli/src/mcp_progress.rs new file mode 100644 index 0000000..f88e1cb --- /dev/null +++ b/crates/rupok-cli/src/mcp_progress.rs @@ -0,0 +1,149 @@ +//! `show_progress`: the agent's "working" card on the live board, so the +//! class sees what the AI is doing while it builds something ("Planning…", +//! "Writing the simulation…", "Testing…") right where the result will land. +//! See [`rupok_live::progress`] and docs/ai-agents.md § "AI in action". + +use rmcp::handler::server::wrapper::Parameters; +use rmcp::model::CallToolResult; +use rmcp::{tool, tool_router}; +use rupok_live::Op; +use rupok_live::progress::{PlanEntry, ProgressArgs}; +use schemars::JsonSchema; +use serde::Deserialize; + +use crate::mcp::McpServer; + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PlanEntryArg { + /// What this step does, e.g. "Draw the atoms". + pub content: String, + /// `pending`, `in_progress` or `completed`. + #[serde(default)] + pub status: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ShowProgressParams { + /// The card to update (from an earlier call's result). Omit to start a + /// new card. + #[serde(default)] + pub id: Option, + /// What you are making, e.g. "Caffeine molecule (3D)". + #[serde(default)] + pub title: Option, + /// What you are doing now, e.g. "Writing the simulation…", "Testing…". + #[serde(default)] + pub step: Option, + /// Your plan as a short checklist (at most 12 entries). + #[serde(default)] + pub plan: Option>, + /// 0 to 100, if you know how far along you are. + #[serde(default)] + pub percent: Option, + /// `working` (default), `done`, `failed` or `clear`. + #[serde(default)] + pub state: Option, + /// What will land: `object`, `handwriting`, `text`, `shape` or `other`. + #[serde(default)] + pub kind: Option, + /// Where the result will go (slide pixels). Use the same box you will + /// pass to add_smart_object; default: a free spot on the page. + #[serde(default)] + pub x: Option, + #[serde(default)] + pub y: Option, + #[serde(default)] + pub w: Option, + #[serde(default)] + pub h: Option, + /// 1-based page. Omit for the page on screen. + #[serde(default)] + #[schemars(range(min = 1))] + pub page: Option, + /// A partial Smart Object (HTML, ≤ 512 KiB) to show as a live preview + /// thumbnail on the card while you build. Sandboxed like Smart Objects. + #[serde(default)] + pub preview_html: Option, + /// For `failed`: one short, friendly sentence for the teacher. + #[serde(default)] + pub error: Option, +} + +/// The op for `show_progress` (validated here so the agent gets a clear +/// error before anything reaches the board). +pub fn op_show_progress(p: ShowProgressParams) -> Result { + let args = ProgressArgs { + id: p.id, + title: p.title, + step: p.step, + plan: p.plan.map(|v| { + v.into_iter() + .map(|e| PlanEntry { + content: e.content, + status: e.status, + }) + .collect() + }), + percent: p.percent, + state: p.state, + kind: p.kind, + x: p.x, + y: p.y, + w: p.w, + h: p.h, + page: p.page, + preview_html: p.preview_html, + error: p.error, + }; + args.validate()?; + Ok(Op::ShowProgress(Box::new(args))) +} + +#[tool_router(router = progress_tool_router, vis = "pub(crate)")] +impl McpServer { + #[tool( + description = "Show the class what you are working on, live, on the board: a 'working' card at the \ +spot where your result will appear, with your current step (\"Planning…\", \"Writing the simulation…\", \ +\"Testing…\"), an optional checklist plan, percent and a live preview (partial Smart Object HTML). Call it \ +at the start of anything that takes more than a few seconds (a Smart Object, a worked solution, a diagram), \ +update it as you go (same `id`), and place the result in the card's box: the card turns into the result \ +with a short animation. Use state \"failed\" with a friendly `error` if something did not work (the board \ +offers a retry), \"done\" or \"clear\" to remove it. Nothing is saved in the lesson; it needs no permission.", + annotations( + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn show_progress(&self, Parameters(p): Parameters) -> CallToolResult { + match op_show_progress(p) { + Ok(op) => self.live_call(op).await, + Err(e) => CallToolResult::structured_error(e.to_json()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn progress_params_become_a_validated_op() { + let p: ShowProgressParams = serde_json::from_value(serde_json::json!({ + "title": "Caffeine", "step": "Bonds…", "kind": "object", + "plan": [{"content": "Atoms", "status": "completed"}], "x": 10, "y": 20, "w": 800, "h": 450 + })) + .unwrap(); + let op = op_show_progress(p).unwrap(); + assert_eq!(op.name(), "show_progress"); + let bad: ShowProgressParams = + serde_json::from_value(serde_json::json!({"state": "boom"})).unwrap(); + assert!(op_show_progress(bad).is_err()); + assert!( + serde_json::from_value::(serde_json::json!({"bogus": 1})).is_err() + ); + } +} diff --git a/crates/rupok-cli/tests/fake-acp-agent.mjs b/crates/rupok-cli/tests/fake-acp-agent.mjs index 3761ced..b19c8b2 100644 --- a/crates/rupok-cli/tests/fake-acp-agent.mjs +++ b/crates/rupok-cli/tests/fake-acp-agent.mjs @@ -13,6 +13,16 @@ // selection, points at it, writes a step-by-step // solution with write_handwriting, then explains. // "/review ..." one of its slash commands: answers "Reviewing: …". +// "...caffeine..." AI in action: a plan, show_progress cards with a live +// preview, a Smart Object that first fails validation, +// then the fixed one placed in the card's box. +// "...long text..." adds a long paragraph at 96px near the bottom right +// (the board must fit it inside the page). +// "...delete..." asks to delete an item (destructive: still asks). +// Solve prompts with "```board": streams the solution lines in a fenced +// block, one line at a time, instead of write_handwriting. +// "A student in my class asks..." (a student's ask): show_progress and a +// Smart Object (lands on the student's own layer). // It also offers Claude-style modes, a model picker (session config option // with category "model", mirrored in the unstable `models` field), slash // commands, usage updates, and session list/load (replaying the chat). @@ -204,6 +214,124 @@ async function solveThis(sid, text) { return "end_turn"; } + +// ------------------------------------------------------------ AI in action + +const permission = async (sid, toolCallId, title, rawInput) => { + if (alwaysAllowed) return true; + const r = await request("session/request_permission", { + sessionId: sid, + toolCall: { toolCallId, title, kind: "edit", rawInput }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "always", name: "Always allow", kind: "allow_always" }, + { optionId: "reject", name: "Reject", kind: "reject_once" }, + ], + }); + const o = r.result?.outcome; + if (o?.optionId === "always") alwaysAllowed = true; + return o?.outcome === "selected" && o.optionId !== "reject"; +}; + +const MOLECULE = (atoms) => `Caffeine +${atoms.map(([x, y, el, c], i) => `${el}`).join("")} +Caffeine, C8H10N4O2`; +const ATOMS = [[400, 260, "C", "#adb5bd"], [520, 200, "N", "#74c0fc"], [640, 260, "C", "#adb5bd"], [640, 400, "C", "#adb5bd"], [520, 460, "N", "#74c0fc"], [400, 400, "C", "#adb5bd"], [760, 200, "O", "#ff8787"], [760, 460, "N", "#74c0fc"], [880, 330, "C", "#adb5bd"], [280, 200, "O", "#ff8787"]]; + +async function caffeine(sid) { + const box = { x: 320, y: 180, w: 1280, h: 720 }; + const plan = (n) => ["Read the Smart Object spec", "Lay out the atoms", "Draw the bonds", "Test and place it"].map((content, i) => ({ content, priority: "high", status: i < n ? "completed" : i === n ? "in_progress" : "pending" })); + await say(sid, "Let me build a **caffeine** molecule for the class.\n\n"); + update(sid, { sessionUpdate: "plan", entries: plan(0) }); + update(sid, { sessionUpdate: "tool_call", toolCallId: "c0", title: "mcp__rupok__show_progress", kind: "other", status: "in_progress" }); + const card = await tool("show_progress", { title: "Caffeine molecule", step: "Reading the spec…", kind: "object", ...box, plan: plan(0).map(({ content, status }) => ({ content, status })) }); + update(sid, { sessionUpdate: "tool_call_update", toolCallId: "c0", status: "completed" }); + await sleep(700); + update(sid, { sessionUpdate: "plan", entries: plan(1) }); + for (let k = 3; k <= ATOMS.length; k += 3) { + await tool("show_progress", { id: card.id, step: `Placing the atoms (${Math.min(k, ATOMS.length)} of ${ATOMS.length})…`, percent: 20 + k * 4, preview_html: MOLECULE(ATOMS.slice(0, k)), plan: plan(1).map(({ content, status }) => ({ content, status })) }); + await sleep(450); + } + update(sid, { sessionUpdate: "plan", entries: plan(3) }); + update(sid, { sessionUpdate: "tool_call", toolCallId: "c1", title: "mcp__rupok__add_smart_object", kind: "edit", status: "pending", rawInput: { path: "live", title: "Caffeine", x: box.x, y: box.y, width: box.w, height: box.h } }); + if (!(await permission(sid, "c1", "mcp__rupok__add_smart_object", { path: "live", title: "Caffeine" }))) { + update(sid, { sessionUpdate: "tool_call_update", toolCallId: "c1", status: "failed" }); + await tool("show_progress", { id: card.id, state: "clear" }); + await say(sid, "OK, I won't place it."); + return "end_turn"; + } + // First try: loads a library from the network, which Rupok refuses. + try { + await tool("add_smart_object", { path: "live", title: "Caffeine", x: box.x, y: box.y, width: box.w, height: box.h, html: MOLECULE(ATOMS).replace("", '') }); + } catch { + update(sid, { sessionUpdate: "tool_call_update", toolCallId: "c1", status: "failed" }); + await sleep(900); + } + update(sid, { sessionUpdate: "tool_call", toolCallId: "c2", title: "mcp__rupok__add_smart_object", kind: "edit", status: "in_progress", rawInput: { path: "live", title: "Caffeine", x: box.x, y: box.y, width: box.w, height: box.h } }); + const o = await tool("add_smart_object", { path: "live", title: "Caffeine", x: box.x, y: box.y, width: box.w, height: box.h, html: MOLECULE(ATOMS) }); + update(sid, { sessionUpdate: "tool_call_update", toolCallId: "c2", status: "completed" }); + update(sid, { sessionUpdate: "plan", entries: plan(4) }); + await say(sid, `Done: caffeine is on page ${o.page}.`); + return "end_turn"; +} + +async function longText(sid) { + update(sid, { sessionUpdate: "tool_call", toolCallId: "l1", title: "mcp__rupok__add_text", kind: "edit", status: "pending" }); + if (!(await permission(sid, "l1", "mcp__rupok__add_text", { path: "live" }))) return "end_turn"; + const text = "Ohm's law says that the current through a conductor between two points is directly proportional to the voltage across the two points, as long as the temperature stays the same. We write it as V = IR, where V is the voltage in volts, I is the current in amperes and R is the resistance in ohms. If you double the voltage across a resistor, the current through it doubles too."; + const r = await tool("add_text", { path: "live", text, x: 1300, y: 700, size: 96 }); + update(sid, { sessionUpdate: "tool_call_update", toolCallId: "l1", status: "completed" }); + await say(sid, `Added the explanation (${r.size}px).`); + return "end_turn"; +} + +async function deleteSomething(sid) { + const pg = await tool("get_current_page", {}); + const victim = (pg.items ?? [])[0]; + if (!victim) { await say(sid, "There is nothing to delete."); return "end_turn"; } + update(sid, { sessionUpdate: "tool_call", toolCallId: "d1", title: "mcp__rupok__delete_item", kind: "delete", status: "pending" }); + const r = await request("session/request_permission", { + sessionId: sid, + toolCall: { toolCallId: "d1", title: "mcp__rupok__delete_item", kind: "delete", rawInput: { path: "live", item_id: victim.id } }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }, { optionId: "reject", name: "Reject", kind: "reject_once" }], + }); + const o = r.result?.outcome; + if (o?.outcome !== "selected" || o.optionId === "reject") { await say(sid, "OK, I left it."); return "end_turn"; } + await tool("delete_item", { path: "live", page: pg.page, item_id: victim.id }); + update(sid, { sessionUpdate: "tool_call_update", toolCallId: "d1", status: "completed" }); + await say(sid, "Deleted it."); + return "end_turn"; +} + +async function streamSolve(sid) { + await say(sid, "Let me work it out.\n\n"); + update(sid, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "2x+3=7, subtract 3, divide by 2." } }); + await sleep(600); + await say(sid, "```board\n", 20, 10); + for (const l of ["Subtract 3 from both sides:", "$2x = 4$", "Divide both sides by 2:", "$x = \\frac{4}{2} = 2$"]) { + await say(sid, l, 4, 40); + await say(sid, "\n", 1, 10); + await sleep(700); + } + await say(sid, "```\n\nSubtract 3, then divide by 2: $x = 2$."); + return "end_turn"; +} + +async function studentAsk(sid) { + const box = { x: 320, y: 180, w: 1280, h: 720 }; + const card = await tool("show_progress", { title: "Caffeine for you", step: "Building it…", kind: "object", ...box }); + await sleep(800); + update(sid, { sessionUpdate: "tool_call", toolCallId: "u1", title: "mcp__rupok__add_smart_object", kind: "edit", status: "pending" }); + if (!(await permission(sid, "u1", "mcp__rupok__add_smart_object", { path: "live", title: "Caffeine" }))) return "end_turn"; + const r = await tool("add_smart_object", { path: "live", title: "Caffeine", ...{ x: box.x, y: box.y, width: box.w, height: box.h }, html: MOLECULE(ATOMS) }); + void card; + await say(sid, r.status === "student_layer" ? "I made a caffeine model just for you." : "Placed it."); + return "end_turn"; +} + async function prompt(params) { const sid = params.sessionId; cancelled = false; @@ -217,7 +345,12 @@ async function prompt(params) { const res = (params.prompt || []).filter((b) => b.type === "resource"); const imgs = (params.prompt || []).filter((b) => b.type === "image"); try { + if (/^Solve this problem/i.test(text) && text.includes("```board")) return { stopReason: await streamSolve(sid) }; if (/^Solve this problem/i.test(text)) return { stopReason: await solveThis(sid, text) }; + if (/^A student in my class asks/i.test(text)) return { stopReason: await studentAsk(sid) }; + if (/caffeine|molecule/i.test(text)) return { stopReason: await caffeine(sid) }; + if (/long text/i.test(text)) return { stopReason: await longText(sid) }; + if (/\bdelete\b/i.test(text)) return { stopReason: await deleteSomething(sid) }; if (/context/i.test(text)) { const r = res[0]?.resource; let n = "no"; From cc9172199bb116b8f62849cd84f9349e1b701559 Mon Sep 17 00:00:00 2001 From: shaitrish37 <244331886+shaitrish37@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:27:17 +0600 Subject: [PATCH 3/5] Board: AI in action Working cards where results land (plan, step, live preview, cancel, retry), results animate in with a small sparkle, class mode (routine edits apply with an Undo toast, destructive ones still ask), Solve this streams line by line, students can ask AI onto their own layer, and the AI button is always there and reliable in Teach. --- apps/board/src/App.tsx | 5 + apps/board/src/aiAction/AiActionLayer.tsx | 244 ++++++++++++++ apps/board/src/aiAction/aiAction.css | 136 ++++++++ apps/board/src/aiAction/classMode.ts | 110 +++++++ apps/board/src/aiAction/index.ts | 39 +++ apps/board/src/aiAction/progress.ts | 373 ++++++++++++++++++++++ apps/board/src/aiAction/solveStream.ts | 136 ++++++++ apps/board/src/aiAction/state.ts | 77 +++++ apps/board/src/aiAction/student.ts | 117 +++++++ apps/board/src/chat.ts | 44 ++- apps/board/src/components/AiStatus.tsx | 19 +- apps/board/src/components/ChatPanel.tsx | 7 +- apps/board/src/components/Chrome.tsx | 6 +- apps/board/src/components/Header.tsx | 6 +- apps/board/src/components/World.tsx | 7 + apps/board/src/live.ts | 38 ++- apps/board/src/objects.ts | 10 +- apps/board/src/settings/defs/aiAction.tsx | 125 ++++++++ apps/board/src/solve/index.ts | 33 +- apps/board/src/styles.css | 2 +- 20 files changed, 1503 insertions(+), 31 deletions(-) create mode 100644 apps/board/src/aiAction/AiActionLayer.tsx create mode 100644 apps/board/src/aiAction/aiAction.css create mode 100644 apps/board/src/aiAction/classMode.ts create mode 100644 apps/board/src/aiAction/index.ts create mode 100644 apps/board/src/aiAction/progress.ts create mode 100644 apps/board/src/aiAction/solveStream.ts create mode 100644 apps/board/src/aiAction/state.ts create mode 100644 apps/board/src/aiAction/student.ts create mode 100644 apps/board/src/settings/defs/aiAction.tsx diff --git a/apps/board/src/App.tsx b/apps/board/src/App.tsx index 0ffbfcd..f1121cd 100644 --- a/apps/board/src/App.tsx +++ b/apps/board/src/App.tsx @@ -19,6 +19,8 @@ import { overlayRole } from "./overlay/role"; import { registerSettingsOpener } from "./components/ToText"; import LivePanel from "./components/LivePanel"; import ChatPanel from "./components/ChatPanel"; +import AiActionLayer from "./aiAction/AiActionLayer"; +import { initAiAction } from "./aiAction"; import VoiceLayer from "./voice/VoiceLayer"; import { LibraryRoot } from "./components/Library"; import { UpgradeHost } from "./components/Billing"; @@ -111,6 +113,7 @@ export default function App() { setReady(true); startUpdateChecks(); // desktop: new release; web: offline service worker, new build void import("./solve").then((m) => m.initSolve()); // Solve this: AI handwriting, preview, reveal + initAiAction(controller); // AI in action: working cards, class mode, live solve, students ask startLibrary(controller); // the Library home and saving lessons to their files (before files below arrive) // Back from a payment page (?billing=…) or sent by the pricing page (?upgrade=pro). const billingParams = takeBillingParams(); @@ -179,6 +182,8 @@ export default function App() { {/* AI chat with the teacher's own agent (chat.ts, `rupok agent`). */} + {/* AI in action: working cards, Undo toasts, students' own layer (aiAction/). */} + diff --git a/apps/board/src/aiAction/AiActionLayer.tsx b/apps/board/src/aiAction/AiActionLayer.tsx new file mode 100644 index 0000000..0b5addf --- /dev/null +++ b/apps/board/src/aiAction/AiActionLayer.tsx @@ -0,0 +1,244 @@ +// The "AI in action" layer over the board: working cards where results will +// land, the sparkle when they do, the class-mode Undo toast and destructive +// confirmations, and the students' "Ask AI" box and own layer. + +import { For, Show, createEffect, createSignal, on, onCleanup } from "solid-js"; +import { camera, isView, mode, pageIndex } from "../state"; +import { controller } from "../controller"; +import { liveHasChat } from "../live"; +import { renderMarkdown } from "../markdown"; +import { Icon } from "../components/Icon"; +import { cancelCard, removeCard, retryCard } from "./progress"; +import { aiToast, cards, confirmReq, setAiToast, sparkle, type Card } from "./state"; +import { askOpen, asksLeft, clearStudentLayer, setAskOpen, studentAsk, studentLayer, studentsMayAsk } from "./student"; +import "./aiAction.css"; + +/** Slide px → screen px on the board. */ +function screen(r: { x: number; y: number; w: number; h: number }) { + const [cx, cy, z] = camera(); + return { left: (r.x - cx) * z, top: (r.y - cy) * z, width: r.w * z, height: r.h * z }; +} + +const KIND_ICON: Record = { object: "smartink", handwriting: "pen", text: "text", shape: "rect", other: "smartink" }; + +function Preview(props: { html: string }) { + let frame!: HTMLIFrameElement; + // Re-render when the agent sends a new partial object (debounced a little). + let t: number | undefined; + createEffect(on(() => props.html, (h) => { + clearTimeout(t); + t = window.setTimeout(() => { if (frame) frame.srcdoc = controller.objects.wrap(h); }, 150); + })); + onCleanup(() => clearTimeout(t)); + return ( +
+