diff --git a/README.md b/README.md
index 17ffeaf..c8d6470 100644
--- a/README.md
+++ b/README.md
@@ -22,6 +22,7 @@ An app runs on a watch with the patched firmware and the App Loader, both on the
| [`metrolist`](apps/metrolist) | Browse and play your Metrolist (YouTube Music) library, and control the phone's playback; the [Android companion](https://github.com/krtkygpta/metrolist/releases/latest) carries the link |
| [`trip-computer`](apps/trip-computer) | A GPS speedometer and trip computer on the watch's own GPS: speed, distance, moving time, average, top speed and ascent; a page next to the face and a widget card |
| [`connect-four`](apps/connect-four) | Connect Four against a negamax bot on three levels: tap a column to drop a disc |
+| [`tech-news`](apps/tech-news) | The Hacker News front page: top headlines with points, comments and age, a page next to the face and a widget card (needs FMC Companion) |
## Make your own app
diff --git a/apps/tech-news/Cargo.toml b/apps/tech-news/Cargo.toml
new file mode 100644
index 0000000..e0470fe
--- /dev/null
+++ b/apps/tech-news/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "tech-news"
+edition.workspace = true
+license.workspace = true
+version.workspace = true
+
+[dependencies]
+cmf-wp2-app.workspace = true
+cmf-wp2-ui.workspace = true
+companion-rpc.workspace = true
+
+[[bin]]
+name = "tech-news"
+bench = false
diff --git a/apps/tech-news/icon.svg b/apps/tech-news/icon.svg
new file mode 100644
index 0000000..159d3d8
--- /dev/null
+++ b/apps/tech-news/icon.svg
@@ -0,0 +1,26 @@
+
diff --git a/apps/tech-news/shots/list.png b/apps/tech-news/shots/list.png
new file mode 100644
index 0000000..4d1d070
Binary files /dev/null and b/apps/tech-news/shots/list.png differ
diff --git a/apps/tech-news/shots/page.png b/apps/tech-news/shots/page.png
new file mode 100644
index 0000000..a5026f3
Binary files /dev/null and b/apps/tech-news/shots/page.png differ
diff --git a/apps/tech-news/shots/story.png b/apps/tech-news/shots/story.png
new file mode 100644
index 0000000..bea4a92
Binary files /dev/null and b/apps/tech-news/shots/story.png differ
diff --git a/apps/tech-news/src/fixtures/front.json b/apps/tech-news/src/fixtures/front.json
new file mode 100644
index 0000000..e55a335
--- /dev/null
+++ b/apps/tech-news/src/fixtures/front.json
@@ -0,0 +1 @@
+{"exhaustive":{"nbHits":true,"typo":true},"exhaustiveNbHits":true,"exhaustiveTypo":true,"hits":[{"created_at_i":1796147550,"num_comments":335,"objectID":"50718402","points":780,"title":"Amazon Ergo: A fast, cost-effective open-weights model"},{"created_at_i":1796139469,"num_comments":247,"objectID":"50716305","points":429,"title":"Cryptopocalypse"},{"created_at_i":1796144952,"num_comments":155,"objectID":"50717648","points":417,"title":"Michael Caine has died"},{"created_at_i":1796122809,"num_comments":154,"objectID":"50713342","points":388,"title":"Goals don't work. Rely on your values"},{"created_at_i":1796144120,"num_comments":91,"objectID":"50717444","points":364,"title":"Ty 1.0: Fast Python type checker and language server"},{"created_at_i":1796142479,"num_comments":137,"objectID":"50717029","points":311,"title":"Claude 5-minute prompt cache vs GPT 30-minute cache: the cost of pauses"},{"created_at_i":1796039570,"num_comments":486,"objectID":"50698717","points":297,"title":"Advent of Code 2026"},{"created_at_i":1796134439,"num_comments":151,"objectID":"50715275","points":284,"title":"Micromorts \u2013 visualizing your chances of dying doing everyday activities"}],"hitsPerPage":8,"nbHits":30,"nbPages":4,"page":0,"params":"tags=front_page&hitsPerPage=8&attributesToRetrieve=title%2Cpoints%2Cnum_comments%2Ccreated_at_i&attributesToHighlight=none&advancedSyntax=true&analyticsTags=backend","processingTimeMS":1,"processingTimingsMS":{"_request":{"queue":3,"roundTrip":15},"total":0},"query":"","serverTimeMS":4}
diff --git a/apps/tech-news/src/format.rs b/apps/tech-news/src/format.rs
new file mode 100644
index 0000000..e61aee1
--- /dev/null
+++ b/apps/tech-news/src/format.rs
@@ -0,0 +1,315 @@
+//! The short texts the screens and the widget card show: times, ages, a story's points and comments, the card's two
+//! lines. Integers only. Titles are ASCII by now (`parse::ascii`); the separators here are the font's own `·`.
+
+/// A short text built in place; what doesn't fit is cut at a character boundary.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub struct Line {
+ buf: [u8; 48],
+ len: usize,
+}
+
+impl Line {
+ pub const fn new() -> Line {
+ Line { buf: [0; 48], len: 0 }
+ }
+
+ pub fn of(s: &str) -> Line {
+ let mut l = Line::new();
+ l.push(s);
+ l
+ }
+
+ /// Appends `s`, or as much of it as fits, whole characters only.
+ pub fn push(&mut self, s: &str) {
+ for ch in s.chars() {
+ let mut b = [0u8; 4];
+ let e = ch.encode_utf8(&mut b).as_bytes();
+ if self.len + e.len() > self.buf.len() {
+ return;
+ }
+ self.buf[self.len..self.len + e.len()].copy_from_slice(e);
+ self.len += e.len();
+ }
+ }
+
+ /// `n` in decimal, at least `width` digits (zero padded).
+ pub fn uint(&mut self, n: u64, width: usize) {
+ let mut d = [0u8; 20];
+ let (mut i, mut v) = (0, n);
+ while (v > 0 || i < width.max(1)) && i < d.len() {
+ d[i] = b'0' + (v % 10) as u8;
+ v /= 10;
+ i += 1;
+ }
+ while i > 0 {
+ i -= 1;
+ if self.len < self.buf.len() {
+ self.buf[self.len] = d[i];
+ self.len += 1;
+ }
+ }
+ }
+
+ pub fn as_str(&self) -> &str {
+ core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
+ }
+
+ pub fn len(&self) -> usize {
+ self.len
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len == 0
+ }
+}
+
+impl core::fmt::Debug for Line {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ core::fmt::Debug::fmt(self.as_str(), f)
+ }
+}
+
+/// The separator between the parts of a meta line.
+pub const DOT: &str = " \u{b7} ";
+
+/// "14:05" of wall-clock minutes.
+pub fn hhmm(wall: i32) -> Line {
+ let m = wall.rem_euclid(1440) as u64;
+ let mut l = Line::new();
+ l.uint(m / 60, 2);
+ l.push(":");
+ l.uint(m % 60, 2);
+ l
+}
+
+/// An age in minutes as its number and unit: `m` below an hour, `h` below two days, `d` after; `None` for less
+/// than a minute (or a post "from the future": a clock or zone off by a little).
+pub fn age_parts(min: i32) -> Option<(u32, &'static str)> {
+ match min {
+ m if m < 1 => None,
+ m if m < 60 => Some((m as u32, "m")),
+ m if m < 48 * 60 => Some(((m / 60) as u32, "h")),
+ m => Some(((m / 1440) as u32, "d")),
+ }
+}
+
+/// "now", "12m", "3h", "2d".
+pub fn age(min: i32) -> Line {
+ let mut l = Line::new();
+ match age_parts(min) {
+ None => l.push("now"),
+ Some((n, unit)) => {
+ l.uint(n as u64, 1);
+ l.push(unit);
+ }
+ }
+ l
+}
+
+/// What the clock changes in [`age`]: equal keys draw the same text.
+pub fn age_key(min: i32) -> u32 {
+ match age_parts(min) {
+ None => 0,
+ Some((n, unit)) => n.saturating_mul(4) + if unit == "m" { 1 } else if unit == "h" { 2 } else { 3 },
+ }
+}
+
+/// "3 hours ago", "1 minute ago", "just now", for the detail screen.
+pub fn age_long(min: i32) -> Line {
+ let mut l = Line::new();
+ match age_parts(min) {
+ None => l.push("just now"),
+ Some((n, unit)) => {
+ l.uint(n as u64, 1);
+ let word = match unit {
+ "m" => " minute",
+ "h" => " hour",
+ _ => " day",
+ };
+ l.push(word);
+ if n != 1 {
+ l.push("s");
+ }
+ l.push(" ago");
+ }
+ }
+ l
+}
+
+/// "780 points", "1 point" (`short`: "780 pts", "1 pt").
+pub fn points(n: u32, short: bool) -> Line {
+ let mut l = Line::new();
+ l.uint(n as u64, 1);
+ l.push(match (short, n == 1) {
+ (true, true) => " pt",
+ (true, false) => " pts",
+ (false, true) => " point",
+ (false, false) => " points",
+ });
+ l
+}
+
+/// "335 comments", "1 comment".
+pub fn comments(n: u32) -> Line {
+ let mut l = Line::new();
+ l.uint(n as u64, 1);
+ l.push(if n == 1 { " comment" } else { " comments" });
+ l
+}
+
+/// The grey line under a headline: "780 pts · 335 comments · 3h", or without the comments ("780 pts · 3h").
+pub fn meta(points_n: u32, comments_n: Option, age_min: i32) -> Line {
+ let mut l = points(points_n, true);
+ if let Some(c) = comments_n {
+ l.push(DOT);
+ l.push(comments(c).as_str());
+ }
+ l.push(DOT);
+ l.push(age(age_min).as_str());
+ l
+}
+
+/// `text` (ASCII) on two lines of at most `max` characters, cut at a space where it can be; a text that goes on
+/// past the second line ends it in "...". A word longer than a line is cut hard.
+pub fn two_lines(text: &str, max: usize) -> Line {
+ let text = text.trim();
+ let (first, rest) = take_line(text, max);
+ let mut l = Line::of(first);
+ let rest = rest.trim_start();
+ if rest.is_empty() {
+ return l;
+ }
+ let (second, more) = take_line(rest, max);
+ let second = if more.trim().is_empty() {
+ second
+ } else {
+ // room for the dots: a shorter second line, at a space if there is one
+ take_line(rest, max.saturating_sub(3)).0.trim_end_matches([' ', '.', ',', ':', ';', '-'])
+ };
+ l.push("\n");
+ l.push(second);
+ if !more.trim().is_empty() {
+ l.push("...");
+ }
+ l
+}
+
+/// The longest start of `s` (ASCII) of at most `max` characters that ends before a space (or at the end), and the
+/// rest; a first word longer than `max` is cut at `max`.
+fn take_line(s: &str, max: usize) -> (&str, &str) {
+ if s.len() <= max {
+ return (s, "");
+ }
+ let b = s.as_bytes();
+ // a space right after the cut keeps the whole last word
+ if b.get(max) == Some(&b' ') {
+ return (&s[..max], &s[max..]);
+ }
+ match s[..max].rfind(' ') {
+ Some(i) if i > 0 => (s[..i].trim_end(), &s[i..]),
+ _ => {
+ let mut k = max;
+ while k > 0 && !s.is_char_boundary(k) {
+ k -= 1;
+ }
+ (&s[..k], &s[k..])
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn times() {
+ assert_eq!(hhmm(14 * 60 + 5).as_str(), "14:05");
+ assert_eq!(hhmm(1440 * 20_000 + 59).as_str(), "00:59");
+ assert_eq!(hhmm(-1).as_str(), "23:59");
+ }
+
+ #[test]
+ fn ages() {
+ let a = |m| age(m).as_str().to_owned();
+ assert_eq!(a(-30), "now");
+ assert_eq!(a(0), "now");
+ assert_eq!(a(1), "1m");
+ assert_eq!(a(59), "59m");
+ assert_eq!(a(60), "1h");
+ assert_eq!(a(179), "2h");
+ assert_eq!(a(47 * 60 + 59), "47h");
+ assert_eq!(a(48 * 60), "2d");
+ assert_eq!(a(i32::MAX), "1491308d");
+ assert_eq!(age_long(0).as_str(), "just now");
+ assert_eq!(age_long(1).as_str(), "1 minute ago");
+ assert_eq!(age_long(61).as_str(), "1 hour ago");
+ assert_eq!(age_long(185).as_str(), "3 hours ago");
+ assert_eq!(age_long(3 * 1440).as_str(), "3 days ago");
+ // the key changes exactly when the text does
+ for m in -5..5000 {
+ assert_eq!(age_key(m) == age_key(m + 1), age(m) == age(m + 1), "{m}");
+ }
+ }
+
+ #[test]
+ fn meta_lines() {
+ assert_eq!(meta(780, Some(335), 150).as_str(), "780 pts \u{b7} 335 comments \u{b7} 2h");
+ assert_eq!(meta(1, Some(1), 0).as_str(), "1 pt \u{b7} 1 comment \u{b7} now");
+ assert_eq!(meta(42, None, 12).as_str(), "42 pts \u{b7} 12m");
+ assert_eq!(points(780, false).as_str(), "780 points");
+ assert_eq!(comments(0).as_str(), "0 comments");
+ // the longest there can be still fits the line's buffer
+ let l = meta(u32::MAX, Some(u32::MAX), i32::MAX);
+ assert!(l.as_str().starts_with("4294967295 pts") && l.len() <= 48, "{l:?}");
+ }
+
+ #[test]
+ fn card_lines() {
+ let t = |s: &str| two_lines(s, 15).as_str().to_owned();
+ assert_eq!(t("Cryptopocalypse"), "Cryptopocalypse");
+ assert_eq!(t("Michael Caine has died"), "Michael Caine\nhas died");
+ assert_eq!(t("Amazon Ergo: A fast, cost-effective open-weights model"), "Amazon Ergo: A\nfast...");
+ assert_eq!(t("Goals don't work. Rely on your values"), "Goals don't\nwork. Rely...");
+ assert_eq!(t("Advent of Code 2026"), "Advent of Code\n2026");
+ assert_eq!(t("Supercalifragilisticexpialidocious"), "Supercalifragil\nisticexpiali...");
+ assert_eq!(t("A Supercalifragilisticexpialidocious b"), "A\nSupercalifra...");
+ assert_eq!(t(""), "");
+ assert_eq!(t(" x "), "x");
+ assert_eq!(t("exactly fifteen"), "exactly fifteen");
+ assert_eq!(t("exactly fifteen and then fifteen"), "exactly fifteen\nand then...");
+ assert_eq!(t("exactly fifteen and then fiftee"), "exactly fifteen\nand then fiftee");
+ }
+
+ #[test]
+ fn card_lines_never_overflow() {
+ let words = ["a", "to", "the", "four", "fifty", "dozens", "fifteen", "Rust's", "eight888", "Kubernetes", "verylongword123", "evenlongerword12345"];
+ let mut seed = 7u32;
+ for _ in 0..4000 {
+ let mut s = std::string::String::new();
+ for _ in 0..(seed % 9 + 1) {
+ seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
+ s.push_str(words[(seed >> 16) as usize % words.len()]);
+ s.push(' ');
+ }
+ let l = two_lines(&s, 15);
+ assert!(l.len() <= 39, "{l:?}");
+ assert!(l.as_str().matches('\n').count() <= 1);
+ for line in l.as_str().split('\n') {
+ assert!(line.len() <= 15 && !line.is_empty(), "{s:?} -> {l:?}");
+ }
+ }
+ }
+
+ #[test]
+ fn line_cuts_at_characters() {
+ let mut l = Line::new();
+ for _ in 0..30 {
+ l.push("\u{b7}");
+ }
+ assert_eq!(l.len(), 48);
+ let mut l = Line::of(&"x".repeat(47));
+ l.push("\u{b7}");
+ assert_eq!(l.len(), 47);
+ assert!(l.as_str().is_ascii());
+ }
+}
diff --git a/apps/tech-news/src/main.rs b/apps/tech-news/src/main.rs
new file mode 100644
index 0000000..576d5d3
--- /dev/null
+++ b/apps/tech-news/src/main.rs
@@ -0,0 +1,206 @@
+//! tech-news: the Hacker News front page, through FMC Companion's `http.request` on the phone.
+//!
+//! - The menu app: the 8 top stories in a list the crown scrolls (`screen::menu`); a tap opens one (its whole title,
+//! points, comments, age; the crown steps to the next, a tap or back returns), the Refresh pill asks the phone now.
+//! BUTTON closes a story, else exits.
+//! - The page next to the watch face (`app_features!(PAGE)`): "Top on HN" and three headlines (`screen::page`); a tap
+//! shows the next three. Swiped away (PAUSE) it draws and asks nothing; back (RESUME) it asks again if the headlines
+//! are older than 10 minutes.
+//! - The widget card (`WIDGET`): the top story's points and its headline on two lines, written at start and whenever
+//! the text changes.
+//!
+//! The phone is asked when the app starts and every 15 minutes while it is shown (`model.rs`); the last headlines are
+//! kept in storage, so the list, the page and the card show at once without the phone.
+#![cfg_attr(any(target_os = "none", wp2_sim), no_main, cfg_attr(target_os = "none", no_std))]
+
+#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))]
+mod format;
+#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))]
+mod model;
+#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))]
+mod parse;
+#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))]
+mod screen;
+
+#[cfg(not(any(target_os = "none", wp2_sim)))]
+fn main() {}
+
+#[cfg(any(target_os = "none", wp2_sim))]
+mod device {
+ use crate::format::Line;
+ use crate::model::{BLOB_MAX, Clock, Got, Model, wall_min};
+ use crate::parse::N;
+ use crate::screen::{self, Hit, Ui};
+ use cmf_wp2_app::{Api, BUTTON, CROWN, MSG_MAX, PAUSE, RESUME, TOUCH_DOWN, TOUCH_UP};
+ use cmf_wp2_ui::haptic::{Motor, TICK};
+ use core::ptr::addr_of_mut;
+
+ cmf_wp2_app::entry!(main);
+ cmf_wp2_app::app_icon!();
+ cmf_wp2_app::app_features!(cmf_wp2_app::WIDGET | cmf_wp2_app::PAGE);
+
+ /// How often to look at the clock: the status line and the ages move.
+ const TICK_MS: u32 = 30_000;
+ /// Longest press that still counts as a tap.
+ const TAP_MS: u32 = 600;
+
+ // the model holds a 2 KiB body buffer: off the 8 KiB stack
+ static mut MODEL: Model = Model::new();
+ static mut BLOB: [u8; BLOB_MAX] = [0; BLOB_MAX];
+
+ fn clock(api: &Api) -> Clock {
+ api.time().map_or(Clock::new(0, 0), |t| {
+ let wall = wall_min(t.year as i32, t.month as u32, t.day as u32, t.hour as u32, t.minute as u32);
+ Clock::new(wall, t.utc_offset_min)
+ })
+ }
+
+ struct App {
+ api: &'static Api,
+ m: &'static mut Model,
+ ui: Ui,
+ on_page: bool,
+ /// The clock-dependent part of the last drawn screen.
+ shown: (Line, [u32; N]),
+ /// The card as last written.
+ card: Option<(Line, Line)>,
+ }
+
+ impl App {
+ fn draw(&mut self) {
+ let c = clock(self.api);
+ self.ui.fit(self.m);
+ let mut s = self.api;
+ if self.on_page {
+ screen::page(&mut s, self.m, &self.ui, c);
+ } else {
+ screen::menu(&mut s, self.m, &self.ui, c);
+ }
+ self.api.show();
+ self.shown = screen::clock_key(self.m, c);
+ }
+
+ /// The clock moved the status line or an age.
+ fn ticked(&self) -> bool {
+ screen::clock_key(self.m, clock(self.api)) != self.shown
+ }
+
+ /// Storage and the card, when they changed.
+ fn keep(&mut self) {
+ if self.m.take_dirty() {
+ let blob = unsafe { &mut *addr_of_mut!(BLOB) };
+ let n = self.m.save(blob);
+ self.api.save(&blob[..n]); // on change: the app can end without notice
+ }
+ let card = self.m.widget();
+ if self.card != Some(card) {
+ self.api.widget(card.0.as_str(), card.1.as_str()); // -22 on a loader without widgets
+ self.card = Some(card);
+ }
+ }
+ }
+
+ fn main(api: &'static Api) -> i32 {
+ let m = unsafe { &mut *addr_of_mut!(MODEL) };
+ let blob = unsafe { &mut *addr_of_mut!(BLOB) };
+ let n = api.load(blob);
+ if n > 0 {
+ m.load(&blob[..n as usize]);
+ }
+ let on_page = api.on_page();
+ if !on_page {
+ api.own_back(true); // BUTTON closes a story first; a no-op on a loader before ABI 1.3
+ }
+ let mut app = App { api, m, ui: Ui::new(), on_page, shown: (Line::new(), [0; N]), card: None };
+ let mut motor = Motor::new(api);
+ app.m.refresh(api.now());
+ let mut paused = false;
+ let mut redraw = true;
+ let mut touch: Option<(i32, i32, u32)> = None;
+ let mut msg = [0u8; MSG_MAX];
+ loop {
+ motor.update();
+ if !paused {
+ // a request is two parts: both go now, unless the outbox is full (then again in 100 ms)
+ while let Some(req) = app.m.poll(api.now()) {
+ let r = api.send(&req); // -107 with no phone: the retry timer asks again
+ app.m.sent(r, api.now());
+ if r < 0 {
+ break;
+ }
+ redraw = true; // "Updating..."
+ }
+ // an answer, a silent phone, the clock: the status line and the pill change too
+ if redraw || app.ticked() {
+ app.draw();
+ }
+ }
+ redraw = false;
+ app.keep();
+ let wait = if paused { u32::MAX } else { app.m.wait(api.now()).min(TICK_MS).min(motor.wait().unwrap_or(u32::MAX)) };
+ let e = api.event(wait);
+ // every turn: the inbox holds 4 messages and an answer is about 14
+ while let Some(r) = api.recv(&mut msg) {
+ if app.m.reply(r, api.now(), clock(api).wall) == Got::Changed {
+ redraw = true;
+ }
+ }
+ let Some(e) = e else { continue };
+ match e.kind {
+ BUTTON if app.ui.detail.is_some() => {
+ app.ui.detail = None;
+ redraw = true;
+ }
+ BUTTON => {
+ motor.off();
+ app.keep();
+ return 0;
+ }
+ PAUSE => {
+ touch = None; // a swipe away from the page starts with a TOUCH_DOWN
+ motor.off();
+ paused = true;
+ }
+ RESUME => {
+ paused = false;
+ app.m.resume(api.now(), clock(api).wall);
+ redraw = true; // the loader repainted the old frame
+ }
+ CROWN if !paused && !app.on_page => redraw |= app.ui.crown(app.m, e.delta),
+ // A tap acts on the finger's lift, at the place it went down (UP's x/y are unreliable).
+ TOUCH_DOWN if !paused => touch = Some((e.x as i32, e.y as i32, api.now())),
+ TOUCH_UP if !paused => {
+ let Some((x, y, at)) = touch.take() else { continue };
+ if api.now().wrapping_sub(at) > TAP_MS {
+ continue;
+ }
+ let hit = if app.on_page { screen::page_hit(app.m) } else { screen::menu_hit(app.m, &app.ui, x, y) };
+ match hit {
+ Hit::Open(i) => {
+ motor.play(TICK);
+ app.ui.detail = Some(i);
+ redraw = true;
+ }
+ Hit::Back => {
+ app.ui.detail = None;
+ redraw = true;
+ }
+ Hit::Next => {
+ app.ui.group = (app.ui.group + 1) % screen::groups(app.m);
+ redraw = true;
+ }
+ Hit::Refresh => {
+ if !app.m.busy() {
+ motor.play(TICK);
+ app.m.refresh(api.now());
+ redraw = true;
+ }
+ }
+ Hit::Nothing => {}
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+}
diff --git a/apps/tech-news/src/model.rs b/apps/tech-news/src/model.rs
new file mode 100644
index 0000000..a3222d6
--- /dev/null
+++ b/apps/tech-news/src/model.rs
@@ -0,0 +1,407 @@
+//! Tech News' state, without `Api`: the stories, the `http.request` call that refreshes them through FMC Companion,
+//! the cache blob and the widget card's text.
+//!
+//! One request at a time, each with a new id; replies for an older id are dropped by [`rpc::Call`]. The URL is 153
+//! bytes, past `http.get`'s 123, so it goes as `http.request` GET, a request of two parts sent back to back
+//! ([`Model::poll`], [`Model::sent`]). After an answer the next one is due in [`PERIOD_MS`], or sooner while the phone
+//! waits for the user's "allow" ([`ASK_AGAIN_MS`]) or after a failure ([`RETRY_FAILED_MS`]). A phone that doesn't
+//! answer is asked again after 3 s, then 6, 12, 24, 48 and every [`LONGEST_MS`].
+
+use crate::format::{self, Line};
+use crate::parse::{self, N, Story, TITLE_MAX};
+use companion_rpc as rpc;
+
+/// The front page's 8 top stories, only the fields shown, no highlighting (with it the answer is ~5 KB: TOO_LARGE).
+pub const URL: &str = "https://hn.algolia.com/api/v1/search?tags=front_page&hitsPerPage=8&attributesToRetrieve=title,points,num_comments,created_at_i&attributesToHighlight=none";
+
+/// A new request this often while the app or its page is shown.
+pub const PERIOD_MS: u32 = 15 * 60_000;
+/// While the phone waits for the user to allow the host.
+pub const ASK_AGAIN_MS: u32 = 10_000;
+/// After `DENIED`, `UNAVAILABLE`, an HTTP error or a body we can't read.
+pub const RETRY_FAILED_MS: u32 = 60_000;
+/// The longest wait between two tries while the phone is silent.
+pub const LONGEST_MS: u32 = 60_000;
+/// Before sending a part again that the full outbox refused.
+pub const PART_RETRY_MS: u32 = 100;
+/// Headlines fetched longer ago than this are marked as old.
+pub const STALE_MIN: i32 = 60;
+/// Coming back to the screen asks again when the headlines are this old.
+pub const RESUME_MIN: i32 = 10;
+/// The largest body `http.request` gives (`TOO_LARGE` above).
+pub const BODY_MAX: usize = 2048;
+/// Characters per widget card line that the stock card draws without wrapping (about 17 of its font fit; markets).
+pub const WIDGET_LINE_MAX: usize = 15;
+
+/// Messages of the request: `method ‖ url_len ‖ url` in chunks of 121 bytes.
+pub const PARTS: u8 = (2 + URL.len()).div_ceil(rpc::CHUNK_MAX) as u8;
+
+/// `api.send`'s "the outbox is full".
+const EAGAIN: i32 = -11;
+
+/// How the phone answered last.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Status {
+ /// Not answered yet in this run.
+ Waiting,
+ Ok,
+ /// The phone asked the user to allow the host.
+ Ask,
+ /// The user said no.
+ Denied,
+ /// No network, a timeout, an HTTP error or a body we can't read.
+ Failed,
+}
+
+/// What a message changed.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Got {
+ Nothing,
+ /// Redraw.
+ Changed,
+}
+
+/// The body of the open request: its records may come in any order.
+struct Body {
+ buf: [u8; BODY_MAX],
+ head: Option,
+ /// Bytes from 0 that some record covered (the end of the furthest chunk).
+ end: usize,
+ bad: bool,
+}
+
+impl Body {
+ const fn new() -> Body {
+ Body { buf: [0; BODY_MAX], head: None, end: 0, bad: false }
+ }
+
+ fn clear(&mut self) {
+ self.head = None;
+ self.end = 0;
+ self.bad = false;
+ }
+
+ /// Record `index` of `total`: the head first, then the body in chunks of 121 bytes (each but the last full).
+ fn put(&mut self, index: u8, total: u8, record: &[u8]) {
+ if index == 0 {
+ self.head = rpc::HttpHead::decode(record);
+ self.bad |= self.head.is_none();
+ return;
+ }
+ let at = (index as usize - 1) * rpc::RECORD_MAX;
+ let full = record.len() == rpc::RECORD_MAX;
+ let to = at + record.len();
+ if (index + 1 < total && !full) || record.len() > rpc::RECORD_MAX || to > BODY_MAX {
+ self.bad = true;
+ return;
+ }
+ self.buf[at..to].copy_from_slice(record);
+ self.end = self.end.max(to);
+ }
+
+ /// The whole body of a 200 answer.
+ fn ok(&self) -> Option<&[u8]> {
+ let h = self.head?;
+ let n = h.length as usize;
+ (!self.bad && h.code == 200 && n == self.end).then(|| &self.buf[..n])
+ }
+}
+
+pub struct Model {
+ pub stories: [Story; N],
+ pub count: usize,
+ /// Wall-clock minutes of the last answer with stories.
+ pub fetched: Option,
+ pub status: Status,
+ call: rpc::Call,
+ ids: u8,
+ /// The id of the open request.
+ id: u8,
+ /// The next part of the open request to send, and not before when.
+ part: u8,
+ part_at: u32,
+ /// The joined request, for [`rpc::http_request`].
+ out: [u8; rpc::JOINED_MAX],
+ body: Body,
+ /// A `BAD_REQUEST` was asked again at once (a request the phone got only part of); the next waits.
+ bad_again: bool,
+ /// Something worth keeping changed since the last [`Model::save`].
+ dirty: bool,
+}
+
+/// Storage: magic, version, count, the fetch minute, then per story points, comments (`u32::MAX`: none), time,
+/// title length and the title.
+const MAGIC: &[u8; 2] = b"TN";
+const VERSION: u8 = 1;
+const HEAD_BYTES: usize = 8;
+const STORY_HEAD: usize = 13;
+pub const BLOB_MAX: usize = HEAD_BYTES + N * (STORY_HEAD + TITLE_MAX);
+
+/// Days since 1970-01-01 of a civil date.
+pub fn days(y: i32, m: u32, d: u32) -> i32 {
+ let y = if m <= 2 { y - 1 } else { y };
+ let (era, yoe) = (y.div_euclid(400), y.rem_euclid(400));
+ let doy = (153 * ((m as i32 + 9) % 12) + 2) / 5 + d as i32 - 1;
+ era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468
+}
+
+/// Wall-clock minutes since 1970.
+pub fn wall_min(y: i32, m: u32, d: u32, hour: u32, minute: u32) -> i32 {
+ days(y, m, d) * 1440 + (hour * 60 + minute) as i32
+}
+
+/// The watch's clock as the screens need it: local minutes for "Updated 14:05", UTC minutes for a story's age.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct Clock {
+ pub wall: i32,
+ pub utc: i32,
+}
+
+impl Clock {
+ /// From local minutes and the zone's offset (`i16::MIN`: the phone never set one, taken as UTC).
+ pub fn new(wall: i32, offset_min: i16) -> Clock {
+ let off = if offset_min == i16::MIN { 0 } else { offset_min as i32 };
+ Clock { wall, utc: wall - off }
+ }
+
+ /// Minutes since a post at Unix second `t`.
+ pub fn age(&self, t: u32) -> i32 {
+ self.utc - (t / 60) as i32
+ }
+}
+
+fn reached(now: u32, at: u32) -> bool {
+ (now.wrapping_sub(at) as i32) >= 0
+}
+
+impl Model {
+ pub const fn new() -> Model {
+ Model {
+ stories: [Story::EMPTY; N],
+ count: 0,
+ fetched: None,
+ status: Status::Waiting,
+ call: rpc::Call::new(LONGEST_MS),
+ ids: 0,
+ id: 0,
+ part: u8::MAX,
+ part_at: 0,
+ out: [0; rpc::JOINED_MAX],
+ body: Body::new(),
+ bad_again: false,
+ dirty: false,
+ }
+ }
+
+ pub fn stories(&self) -> &[Story] {
+ &self.stories[..self.count]
+ }
+
+ /// Waiting for an answer.
+ pub fn running(&self) -> bool {
+ self.call.open()
+ }
+
+ /// The phone left the last request unanswered.
+ pub fn silent(&self) -> bool {
+ self.call.silent()
+ }
+
+ /// Ask at once, unless a request is open (start, the Refresh pill); a silent phone is asked again at once.
+ pub fn refresh(&mut self, now: u32) {
+ if !self.running() || self.silent() {
+ self.call.now(now);
+ }
+ }
+
+ /// Waiting for a phone that answers: what the Refresh pill can't speed up.
+ pub fn busy(&self) -> bool {
+ self.running() && !self.silent()
+ }
+
+ /// Back on screen after `PAUSE`: the open request again (its answer was refused while paused), or a new one when
+ /// the headlines are older than [`RESUME_MIN`].
+ pub fn resume(&mut self, now: u32, wall: i32) {
+ if self.running() || self.fetched.is_none_or(|at| wall - at >= RESUME_MIN) {
+ self.call.now(now);
+ }
+ }
+
+ /// The parts of the request.
+ fn parts(&mut self) -> Option> {
+ rpc::http_request(self.id, rpc::http::GET, URL, &[], &mut self.out)
+ }
+
+ /// The next message to send now, if one is due: a part of a new request, or the next part of the open one. Tell
+ /// [`Model::sent`] what `api.send` said.
+ pub fn poll(&mut self, now: u32) -> Option {
+ if let Some(id) = self.call.due(now, &mut self.ids) {
+ self.id = id;
+ self.part = 0;
+ self.part_at = now;
+ self.body.clear();
+ }
+ if !self.call.open() || self.part >= PARTS || !reached(now, self.part_at) {
+ return None;
+ }
+ let k = self.part;
+ self.parts()?.nth(k as usize)
+ }
+
+ /// `api.send`'s result for the message [`Model::poll`] gave: the next part, the same again soon when the outbox
+ /// was full, or no more (no phone: the call's timer asks again).
+ pub fn sent(&mut self, r: i32, now: u32) {
+ if r >= 0 {
+ self.part = self.part.saturating_add(1);
+ } else if r == EAGAIN {
+ self.part_at = now.wrapping_add(PART_RETRY_MS);
+ } else {
+ self.part = u8::MAX;
+ }
+ }
+
+ /// Ms until [`Model::poll`] has something to do.
+ pub fn wait(&self, now: u32) -> u32 {
+ let w = self.call.wait(now);
+ if self.call.open() && self.part < PARTS {
+ w.min((self.part_at.wrapping_sub(now) as i32).max(0) as u32)
+ } else {
+ w
+ }
+ }
+
+ /// One message from the phone, at `now` ms and `wall` minutes.
+ pub fn reply(&mut self, m: &[u8], now: u32, wall: i32) -> Got {
+ match self.call.take(m) {
+ rpc::Got::Nothing => Got::Nothing,
+ rpc::Got::Status(s) => {
+ self.part = u8::MAX;
+ let again = match s {
+ rpc::ASK => {
+ self.status = Status::Ask;
+ ASK_AGAIN_MS
+ }
+ rpc::DENIED => {
+ self.status = Status::Denied;
+ RETRY_FAILED_MS
+ }
+ // the phone may hold the first part of a request whose second never came: once more, at once
+ rpc::BAD_REQUEST if !self.bad_again => {
+ self.bad_again = true;
+ self.status = Status::Failed;
+ rpc::RETRY_MS
+ }
+ _ => {
+ // UNAVAILABLE, TOO_LARGE, BAD_REQUEST again, an empty OK
+ self.status = Status::Failed;
+ RETRY_FAILED_MS
+ }
+ };
+ self.call.after(now, again);
+ Got::Changed
+ }
+ rpc::Got::Record { index, total, record, last } => {
+ self.body.put(index, total, record);
+ if !last {
+ return Got::Nothing;
+ }
+ self.part = u8::MAX;
+ let again = if self.take_body(wall) {
+ self.status = Status::Ok;
+ self.bad_again = false;
+ PERIOD_MS
+ } else {
+ self.status = Status::Failed;
+ RETRY_FAILED_MS
+ };
+ self.call.after(now, again);
+ Got::Changed
+ }
+ }
+ }
+
+ /// The finished body into the stories; `false` if it had none.
+ fn take_body(&mut self, wall: i32) -> bool {
+ let Some(body) = self.body.ok() else { return false };
+ let mut got = [Story::EMPTY; N];
+ let n = parse::front_page(body, &mut got);
+ if n == 0 {
+ return false;
+ }
+ self.stories = got;
+ self.count = n;
+ self.fetched = Some(wall);
+ self.dirty = true;
+ true
+ }
+
+ /// Whether to [`Model::save`] now: new stories since the last time; one NAND write per answer.
+ pub fn take_dirty(&mut self) -> bool {
+ core::mem::replace(&mut self.dirty, false)
+ }
+
+ /// The cache blob into `out`; its length.
+ pub fn save(&self, out: &mut [u8; BLOB_MAX]) -> usize {
+ out[..2].copy_from_slice(MAGIC);
+ out[2] = VERSION;
+ out[3] = self.count as u8;
+ out[4..8].copy_from_slice(&self.fetched.unwrap_or(i32::MIN).to_le_bytes());
+ let mut at = HEAD_BYTES;
+ for s in self.stories() {
+ let t = s.title().as_bytes();
+ out[at..at + 4].copy_from_slice(&s.points.to_le_bytes());
+ out[at + 4..at + 8].copy_from_slice(&s.comments.unwrap_or(u32::MAX).to_le_bytes());
+ out[at + 8..at + 12].copy_from_slice(&s.time.to_le_bytes());
+ out[at + 12] = t.len() as u8;
+ out[at + STORY_HEAD..at + STORY_HEAD + t.len()].copy_from_slice(t);
+ at += STORY_HEAD + t.len();
+ }
+ at
+ }
+
+ /// A blob of [`Model::save`]; anything else leaves the model as it is. `true` if it loaded.
+ pub fn load(&mut self, b: &[u8]) -> bool {
+ if b.len() < HEAD_BYTES || b.len() > BLOB_MAX || &b[..2] != MAGIC || b[2] != VERSION || b[3] as usize > N {
+ return false;
+ }
+ let le4 = |a: usize| u32::from_le_bytes([b[a], b[a + 1], b[a + 2], b[a + 3]]);
+ let count = b[3] as usize;
+ let fetched = le4(4) as i32;
+ let mut stories = [Story::EMPTY; N];
+ let mut at = HEAD_BYTES;
+ for s in stories.iter_mut().take(count) {
+ let Some(&len) = b.get(at + 12) else { return false };
+ let Some(raw) = b.get(at + STORY_HEAD..at + STORY_HEAD + len as usize) else { return false };
+ let comments = le4(at + 4);
+ let comments = (comments != u32::MAX).then_some(comments);
+ let Some(story) = Story::with_raw_title(raw, le4(at), comments, le4(at + 8)) else { return false };
+ *s = story;
+ at += STORY_HEAD + len as usize;
+ }
+ if at != b.len() || (count > 0) == (fetched == i32::MIN) {
+ return false;
+ }
+ self.stories = stories;
+ self.count = count;
+ self.fetched = (fetched != i32::MIN).then_some(fetched);
+ true
+ }
+
+ /// The widget card: title (≤ 23 bytes) and value (≤ 39 bytes, two lines), e.g. "HN 780 pts" and
+ /// "Amazon Ergo: A\nfast...". Every line stays within [`WIDGET_LINE_MAX`] characters.
+ pub fn widget(&self) -> (Line, Line) {
+ let Some(top) = self.stories().first() else {
+ return (Line::of("Top on HN"), Line::of("No news yet\nOpen to load"));
+ };
+ let mut title = Line::of("HN ");
+ title.push(format::points(top.points, true).as_str());
+ if title.len() > WIDGET_LINE_MAX {
+ title = Line::of("Top on HN");
+ }
+ (title, format::two_lines(top.title(), WIDGET_LINE_MAX))
+ }
+}
+
+#[cfg(test)]
+#[path = "model_tests.rs"]
+mod tests;
diff --git a/apps/tech-news/src/model_tests.rs b/apps/tech-news/src/model_tests.rs
new file mode 100644
index 0000000..73db90d
--- /dev/null
+++ b/apps/tech-news/src/model_tests.rs
@@ -0,0 +1,444 @@
+extern crate std;
+
+use super::*;
+use std::vec::Vec;
+
+const FRONT: &[u8] = include_bytes!("fixtures/front.json");
+const WALL: i32 = 1440 * 20_000 + 14 * 60 + 5;
+
+/// `R1A id status index total record`.
+fn msg(id: u8, status: u8, index: u8, total: u8, record: &[u8]) -> Vec {
+ let mut m = Vec::from(&b"R1A"[..]);
+ m.extend_from_slice(&[id, status, index, total]);
+ m.extend_from_slice(record);
+ m
+}
+
+/// An `http.request` answer as the phone sends it: the head, then the body in 121-byte chunks.
+fn answer(id: u8, code: u16, body: &[u8]) -> Vec> {
+ let chunks: Vec<&[u8]> = body.chunks(rpc::RECORD_MAX).collect();
+ let total = 1 + chunks.len() as u8;
+ let mut head = Vec::from(code.to_le_bytes());
+ head.extend_from_slice(&(body.len() as u16).to_le_bytes());
+ let mut out = std::vec![msg(id, rpc::OK, 0, total, &head)];
+ for (i, c) in chunks.iter().enumerate() {
+ out.push(msg(id, rpc::OK, 1 + i as u8, total, c));
+ }
+ out
+}
+
+fn feed(m: &mut Model, msgs: &[Vec], now: u32) -> Got {
+ let mut got = Got::Nothing;
+ for x in msgs {
+ if m.reply(x, now, WALL) == Got::Changed {
+ got = Got::Changed;
+ }
+ }
+ got
+}
+
+/// Sends what is due at `now` as the main loop does (every send succeeding); the messages and the request's id.
+fn send_all(m: &mut Model, now: u32) -> (Vec, Option) {
+ let mut out = Vec::new();
+ while let Some(q) = m.poll(now) {
+ m.sent(0, now);
+ out.push(q);
+ assert!(out.len() <= 9);
+ }
+ let id = out.first().map(|q| q.as_bytes()[3]);
+ (out, id)
+}
+
+/// The joined payload of a multi-part request's messages.
+fn joined(msgs: &[rpc::Msg]) -> Vec {
+ let mut v = Vec::new();
+ for (k, q) in msgs.iter().enumerate() {
+ let b = q.as_bytes();
+ assert_eq!(&b[..3], b"R1Q");
+ assert_eq!(b[4], rpc::method::HTTP_REQUEST);
+ assert_eq!((b[5], b[6]), (k as u8, msgs.len() as u8));
+ assert_eq!(b[3], msgs[0].as_bytes()[3], "one id for every part");
+ v.extend_from_slice(&b[7..]);
+ }
+ v
+}
+
+#[test]
+fn the_request_is_an_http_get_in_two_parts() {
+ assert_eq!(URL.len(), 153);
+ assert!(URL.len() <= 255 && URL.len() > 123, "too long for http.get, fits http.request");
+ assert!(rpc::http_get(1, URL).is_none());
+ assert!(URL.contains("attributesToHighlight=none") && URL.contains("hitsPerPage=8"));
+ assert_eq!(PARTS, 2);
+ let mut m = Model::new();
+ m.refresh(0);
+ let (msgs, id) = send_all(&mut m, 0);
+ assert_eq!(msgs.len(), 2);
+ assert_eq!(id, Some(1));
+ let p = joined(&msgs);
+ assert_eq!(p[0], rpc::http::GET);
+ assert_eq!(p[1] as usize, URL.len());
+ assert_eq!(&p[2..], URL.as_bytes()); // no body
+ assert_eq!(msgs[0].as_bytes().len(), rpc::MSG_MAX);
+ // the same bytes as the crate's encoder
+ let mut out = [0; rpc::JOINED_MAX];
+ let want: Vec> =
+ rpc::http_request(1, rpc::http::GET, URL, &[], &mut out).unwrap().map(|q| q.as_bytes().to_vec()).collect();
+ assert_eq!(msgs.iter().map(|q| q.as_bytes().to_vec()).collect::>(), want);
+}
+
+#[test]
+fn a_full_outbox_sends_the_part_again_and_no_phone_stops() {
+ let mut m = Model::new();
+ m.refresh(0);
+ let a = m.poll(0).unwrap();
+ m.sent(0, 0);
+ let b = m.poll(0).unwrap();
+ m.sent(-11, 0);
+ assert!(m.poll(50).is_none());
+ assert_eq!(m.wait(50), PART_RETRY_MS - 50);
+ let b2 = m.poll(PART_RETRY_MS).unwrap();
+ assert_eq!(b.as_bytes(), b2.as_bytes());
+ assert_ne!(a.as_bytes(), b.as_bytes());
+ m.sent(0, PART_RETRY_MS);
+ assert!(m.poll(PART_RETRY_MS).is_none());
+ // -107: no more parts; the call's timer asks again, from part 0 with a new id
+ let mut m = Model::new();
+ m.refresh(0);
+ m.poll(0).unwrap();
+ m.sent(-107, 0);
+ assert!(m.poll(10).is_none());
+ assert_eq!(m.wait(10), rpc::RETRY_MS - 10);
+ let (msgs, id) = send_all(&mut m, rpc::RETRY_MS);
+ assert_eq!((msgs.len(), id), (2, Some(2)));
+ assert!(m.silent());
+}
+
+#[test]
+fn an_answer_fills_the_stories() {
+ let mut m = Model::new();
+ assert!(m.poll(0).is_none()); // nothing until asked
+ m.refresh(0);
+ let (_, id) = send_all(&mut m, 0);
+ let id = id.unwrap();
+ assert!(m.running() && m.busy());
+ let msgs = answer(id, 200, FRONT);
+ assert!(msgs.len() > 10);
+ // records in any order; nothing to redraw until the last one
+ for x in msgs.iter().rev().skip(1) {
+ assert_eq!(m.reply(x, 10, WALL), Got::Nothing);
+ }
+ assert_eq!(m.reply(&msgs[msgs.len() - 1], 10, WALL), Got::Changed);
+ assert_eq!(m.count, 8);
+ assert_eq!(m.stories[0].title(), "Amazon Ergo: A fast, cost-effective open-weights model");
+ assert_eq!((m.stories[0].points, m.stories[0].comments), (780, Some(335)));
+ assert_eq!(m.fetched, Some(WALL));
+ assert_eq!(m.status, Status::Ok);
+ assert!(!m.running());
+ assert!(m.take_dirty() && !m.take_dirty()); // one write per answer
+ // the next one in 15 minutes
+ assert_eq!(m.wait(10), PERIOD_MS);
+ assert!(m.poll(10 + PERIOD_MS - 1).is_none());
+ let (msgs, id2) = send_all(&mut m, 10 + PERIOD_MS);
+ assert_eq!((msgs.len(), id2), (2, Some(id + 1)));
+}
+
+#[test]
+fn replies_for_an_old_id_are_dropped() {
+ let mut m = Model::new();
+ m.refresh(0);
+ let (_, first) = send_all(&mut m, 0);
+ // silent: asked again with a new id after 3 s
+ let (_, again) = send_all(&mut m, rpc::RETRY_MS);
+ assert_ne!(first, again);
+ assert!(m.silent() && !m.busy());
+ assert_eq!(feed(&mut m, &answer(first.unwrap(), 200, FRONT), 3_100), Got::Nothing);
+ assert_eq!(m.count, 0);
+ assert_eq!(feed(&mut m, &answer(again.unwrap(), 200, FRONT), 3_200), Got::Changed);
+ assert!(m.count == 8 && !m.silent());
+ // other prefixes and garbage are nothing
+ assert_eq!(m.reply(b"hello", 0, WALL), Got::Nothing);
+ assert_eq!(m.reply(b"R1A", 0, WALL), Got::Nothing);
+ assert_eq!(m.reply(&msg(again.unwrap(), rpc::OK, 0, 2, &[200, 0, 5, 0]), 0, WALL), Got::Nothing); // answered
+}
+
+#[test]
+fn silence_backs_off() {
+ let mut m = Model::new();
+ m.refresh(0);
+ let mut t = 0;
+ send_all(&mut m, t);
+ let mut waits = Vec::new();
+ for _ in 0..7 {
+ let w = m.wait(t);
+ waits.push(w);
+ t += w;
+ assert_eq!(send_all(&mut m, t).0.len(), 2);
+ }
+ assert_eq!(waits, [3_000, 6_000, 12_000, 24_000, 48_000, 60_000, 60_000]);
+ assert!(m.silent() && m.running());
+ // the Refresh pill asks a silent phone at once, with a fresh back-off
+ m.refresh(t + 10);
+ assert_eq!(send_all(&mut m, t + 10).0.len(), 2);
+ assert_eq!(m.wait(t + 10), rpc::RETRY_MS);
+}
+
+#[test]
+fn ask_then_allowed() {
+ let mut m = Model::new();
+ m.refresh(0);
+ let (_, id) = send_all(&mut m, 0);
+ assert_eq!(feed(&mut m, &[msg(id.unwrap(), rpc::ASK, 0, 0, &[])], 5), Got::Changed);
+ assert_eq!(m.status, Status::Ask);
+ assert!(!m.running());
+ assert_eq!(m.wait(5), ASK_AGAIN_MS);
+ let (_, id) = send_all(&mut m, 5 + ASK_AGAIN_MS);
+ assert_eq!(m.status, Status::Ask); // until the phone says otherwise
+ feed(&mut m, &answer(id.unwrap(), 200, FRONT), 6 + ASK_AGAIN_MS);
+ assert_eq!(m.status, Status::Ok);
+ assert_eq!(m.wait(6 + ASK_AGAIN_MS), PERIOD_MS);
+}
+
+#[test]
+fn denied_and_failures() {
+ let mut m = Model::new();
+ m.refresh(0);
+ let (_, id) = send_all(&mut m, 0);
+ feed(&mut m, &[msg(id.unwrap(), rpc::DENIED, 0, 0, &[])], 0);
+ assert_eq!(m.status, Status::Denied);
+ assert_eq!(m.wait(0), RETRY_FAILED_MS);
+
+ // an HTTP error, a body that isn't the answer, TOO_LARGE, UNAVAILABLE: failed, again in a minute
+ let mut t = 0;
+ let fails: [Vec>; 5] = [
+ answer(0, 429, b"{}"),
+ answer(0, 200, b""),
+ answer(0, 200, br#"{"hits":[]}"#),
+ std::vec![msg(0, rpc::TOO_LARGE, 0, 0, &[])],
+ std::vec![msg(0, rpc::UNAVAILABLE, 0, 0, &[])],
+ ];
+ for f in fails {
+ let mut m = Model::new();
+ m.refresh(t);
+ let (_, id) = send_all(&mut m, t);
+ let f: Vec> = f
+ .into_iter()
+ .map(|mut x| {
+ x[3] = id.unwrap();
+ x
+ })
+ .collect();
+ assert_eq!(feed(&mut m, &f, t), Got::Changed);
+ assert_eq!(m.status, Status::Failed);
+ assert_eq!(m.count, 0);
+ assert_eq!(m.wait(t), RETRY_FAILED_MS);
+ t += 1;
+ }
+
+ // a failure keeps the stories there are
+ let mut m = Model::new();
+ m.refresh(0);
+ let (_, id) = send_all(&mut m, 0);
+ feed(&mut m, &answer(id.unwrap(), 200, FRONT), 0);
+ m.refresh(1); // not running: asks at once
+ let (_, id) = send_all(&mut m, 1);
+ feed(&mut m, &[msg(id.unwrap(), rpc::UNAVAILABLE, 0, 0, &[])], 1);
+ assert_eq!((m.status, m.count, m.fetched), (Status::Failed, 8, Some(WALL)));
+}
+
+#[test]
+fn bad_request_is_asked_again_once_at_once() {
+ let mut m = Model::new();
+ m.refresh(0);
+ let (_, id) = send_all(&mut m, 0);
+ feed(&mut m, &[msg(id.unwrap(), rpc::BAD_REQUEST, 0, 0, &[])], 0);
+ assert_eq!(m.wait(0), rpc::RETRY_MS);
+ let (_, id) = send_all(&mut m, rpc::RETRY_MS);
+ feed(&mut m, &[msg(id.unwrap(), rpc::BAD_REQUEST, 0, 0, &[])], rpc::RETRY_MS);
+ assert_eq!(m.wait(rpc::RETRY_MS), RETRY_FAILED_MS);
+ // an answer resets it
+ let t = rpc::RETRY_MS + RETRY_FAILED_MS;
+ let (_, id) = send_all(&mut m, t);
+ feed(&mut m, &answer(id.unwrap(), 200, FRONT), t);
+ m.refresh(t);
+ let (_, id) = send_all(&mut m, t);
+ feed(&mut m, &[msg(id.unwrap(), rpc::BAD_REQUEST, 0, 0, &[])], t);
+ assert_eq!(m.wait(t), rpc::RETRY_MS);
+}
+
+#[test]
+fn a_cut_or_odd_body_is_not_taken() {
+ // a head that claims more than came
+ let mut m = Model::new();
+ m.refresh(0);
+ let (_, id) = send_all(&mut m, 0);
+ let mut msgs = answer(id.unwrap(), 200, FRONT);
+ msgs[0][9] = msgs[0][9].wrapping_add(1); // the length's low byte
+ feed(&mut m, &msgs, 0);
+ assert_eq!((m.count, m.status), (0, Status::Failed));
+ // a short chunk in the middle
+ m.refresh(1);
+ let (_, id) = send_all(&mut m, 1);
+ let mut msgs = answer(id.unwrap(), 200, FRONT);
+ msgs[2].pop();
+ feed(&mut m, &msgs, 1);
+ assert_eq!(m.count, 0);
+ // a body over 2048 bytes in pieces past the buffer
+ m.refresh(2);
+ let (_, id) = send_all(&mut m, 2);
+ feed(&mut m, &answer(id.unwrap(), 200, &[b' '; 2100]), 2);
+ assert_eq!(m.count, 0);
+ // a bad head
+ m.refresh(3);
+ let (_, id) = send_all(&mut m, 3);
+ feed(&mut m, &[msg(id.unwrap(), rpc::OK, 0, 1, &[200])], 3);
+ assert_eq!((m.count, m.status), (0, Status::Failed));
+}
+
+#[test]
+fn resume_asks_again_when_old_or_open() {
+ let mut m = Model::new();
+ m.refresh(0);
+ let (_, id) = send_all(&mut m, 0);
+ feed(&mut m, &answer(id.unwrap(), 200, FRONT), 0);
+ let now = 1000;
+ m.resume(now, WALL + 1);
+ assert!(m.poll(now).is_none());
+ m.resume(now, WALL + RESUME_MIN);
+ assert!(m.poll(now).is_some());
+ // paused with a request open: asked again at once, not counted as silence
+ let mut m = Model::new();
+ m.refresh(0);
+ let (_, first) = send_all(&mut m, 0);
+ m.resume(500, WALL);
+ let (_, again) = send_all(&mut m, 500);
+ assert!(!m.silent());
+ assert_ne!(first, again);
+ // nothing cached: asked at once
+ let mut m = Model::new();
+ m.resume(7, WALL);
+ assert!(m.poll(7).is_some());
+}
+
+#[test]
+fn refresh_doesnt_restart_an_open_request() {
+ let mut m = Model::new();
+ m.refresh(0);
+ send_all(&mut m, 0);
+ assert!(m.busy());
+ m.refresh(100);
+ assert!(m.poll(100).is_none());
+}
+
+fn loaded() -> Model {
+ let mut m = Model::new();
+ m.refresh(0);
+ let (_, id) = send_all(&mut m, 0);
+ feed(&mut m, &answer(id.unwrap(), 200, FRONT), 0);
+ m
+}
+
+#[test]
+fn storage_round_trip() {
+ let mut m = loaded();
+ m.stories[2].comments = None;
+ m.stories[3] = Story::new(&"long words ".repeat(20), u32::MAX, Some(u32::MAX - 1), u32::MAX);
+ let mut blob = [0u8; BLOB_MAX];
+ let n = m.save(&mut blob);
+ assert!(n <= BLOB_MAX && BLOB_MAX <= cmf_wp2_app::STORE_MAX);
+ let mut k = Model::new();
+ assert!(k.load(&blob[..n]));
+ assert_eq!(k.stories, m.stories);
+ assert_eq!((k.count, k.fetched), (8, Some(WALL)));
+ // the largest blob there can be
+ for s in m.stories.iter_mut() {
+ *s = Story::new(&"x".repeat(200), 1, Some(2), 3);
+ assert_eq!(s.title().len(), parse::TITLE_MAX);
+ }
+ assert_eq!(m.save(&mut blob), BLOB_MAX);
+ assert!(k.load(&blob));
+ // nothing yet
+ let e = Model::new();
+ let n = e.save(&mut blob);
+ assert_eq!(n, 8);
+ let mut k = loaded();
+ assert!(k.load(&blob[..n]));
+ assert_eq!((k.count, k.fetched), (0, None));
+}
+
+#[test]
+fn a_bad_blob_loads_nothing() {
+ let m = loaded();
+ let mut blob = [0u8; BLOB_MAX];
+ let n = m.save(&mut blob);
+ let bad = |f: &dyn Fn(&mut Vec)| {
+ let mut b = blob[..n].to_vec();
+ f(&mut b);
+ let mut k = Model::new();
+ assert!(!k.load(&b), "{b:?}");
+ assert_eq!((k.count, k.fetched), (0, None));
+ };
+ bad(&|b| b[0] = b'X');
+ bad(&|b| b[2] = 9);
+ bad(&|b| b[3] = 9);
+ bad(&|b| b[3] = 7); // fewer stories than the bytes hold
+ bad(&|b| b[4..8].copy_from_slice(&i32::MIN.to_le_bytes())); // stories without a time
+ bad(&|b| b[8 + 12] = 0); // an empty title
+ bad(&|b| b[8 + 12] = 200); // a title past the end
+ bad(&|b| b[8 + 13] = 0xC3); // not ASCII
+ bad(&|b| b[8 + 13] = b'\n');
+ bad(&|b| {
+ b.pop();
+ });
+ bad(&|b| b.push(0));
+ bad(&|b| b.truncate(5));
+ bad(&|b| b.clear());
+ let mut k = Model::new();
+ assert!(!k.load(&[0; BLOB_MAX + 1]));
+ // a good blob still loads after all that
+ assert!(k.load(&blob[..n]));
+}
+
+#[test]
+fn widget_text_fits() {
+ let m = Model::new();
+ let (t, v) = m.widget();
+ assert_eq!((t.as_str(), v.as_str()), ("Top on HN", "No news yet\nOpen to load"));
+ let mut m = loaded();
+ let (t, v) = m.widget();
+ assert_eq!(t.as_str(), "HN 780 pts");
+ assert_eq!(v.as_str(), "Amazon Ergo: A\nfast...");
+ m.stories[0] = Story::new("Cryptopocalypse", 1, None, 0);
+ assert_eq!(m.widget().0.as_str(), "HN 1 pt");
+ assert_eq!(m.widget().1.as_str(), "Cryptopocalypse");
+ m.stories[0] = Story::new("x", u32::MAX, None, 0);
+ assert_eq!(m.widget().0.as_str(), "Top on HN"); // "HN 4294967295 pts" is too wide
+ // every headline of the fixture, and odd ones, on two lines of at most 15
+ let mut odd: Vec = m.stories().to_vec();
+ for t in ["a", "Supercalifragilisticexpialidocious and more", "I I I I I I I I I I I I I I I I I I I I", "-- -- -- -- -- -- -- --"] {
+ odd.push(Story::new(t, 99_999, None, 0));
+ }
+ odd.push(Story::new(&"w".repeat(90), 5, None, 0));
+ for s in odd.iter().chain(loaded().stories()) {
+ m.stories[0] = *s;
+ let (t, v) = m.widget();
+ assert!(t.len() <= 23 && v.len() <= 39, "{t:?} {v:?}");
+ assert!(v.as_str().matches('\n').count() <= 1);
+ for line in core::iter::once(t.as_str()).chain(v.as_str().split('\n')) {
+ assert!(line.len() <= WIDGET_LINE_MAX && line.is_ascii(), "{line:?} is wider than the card");
+ }
+ }
+}
+
+#[test]
+fn clock_and_ages() {
+ assert_eq!(days(1970, 1, 1), 0);
+ assert_eq!(wall_min(2026, 12, 1, 14, 5) % 1440, 14 * 60 + 5);
+ // the fixture's first story, 1796147550 = 2026-12-01 17:52:30 UTC, seen at 22:22 in UTC+2
+ let c = Clock::new(wall_min(2026, 12, 1, 22, 22), 120);
+ assert_eq!(c.age(1_796_147_550), 150);
+ assert_eq!(format::age(c.age(1_796_147_550)).as_str(), "2h");
+ // no zone from the phone: taken as UTC
+ let c = Clock::new(wall_min(2026, 12, 1, 18, 0), i16::MIN);
+ assert_eq!(c.age(1_796_147_550), 8);
+}
diff --git a/apps/tech-news/src/parse.rs b/apps/tech-news/src/parse.rs
new file mode 100644
index 0000000..31526fd
--- /dev/null
+++ b/apps/tech-news/src/parse.rs
@@ -0,0 +1,560 @@
+//! The Hacker News front page out of Algolia's search answer, without a heap, floats or a JSON library: a cursor walks
+//! the top object to `"hits"` and reads each hit's `title`, `points`, `num_comments` and `created_at_i`, skipping
+//! everything else whatever its order. Every byte is untrusted: nothing here indexes past a slice, recurses or panics,
+//! and a hit is only taken once its closing `}` has come, so a cut body gives the whole hits before the cut and nothing
+//! half-read.
+//!
+//! Titles are folded to ASCII on the way in ([`ascii`]): the watch's widget font has ASCII and Cyrillic, the canvas
+//! font ASCII and Latin-1, so typographic quotes and dashes become plain ones, accented Latin letters their base
+//! letter, and anything else (emoji, CJK, ...) is dropped rather than drawn as a box.
+
+/// Stories kept: the URL asks for this many.
+pub const N: usize = 8;
+/// Bytes of a title kept; a longer one is cut at a word and ends in "...". HN titles are at most 80 characters.
+pub const TITLE_MAX: usize = 90;
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct Story {
+ title: [u8; TITLE_MAX],
+ len: u8,
+ pub points: u32,
+ /// `None` when the answer had no count (`null`).
+ pub comments: Option,
+ /// Unix seconds (UTC) of the post.
+ pub time: u32,
+}
+
+impl Story {
+ pub const EMPTY: Story = Story { title: [0; TITLE_MAX], len: 0, points: 0, comments: None, time: 0 };
+
+ /// A story with this title (folded to ASCII like a parsed one).
+ #[cfg(test)]
+ pub fn new(title: &str, points: u32, comments: Option, time: u32) -> Story {
+ let mut t = Title::new();
+ for ch in title.chars() {
+ t.push(ch);
+ }
+ let mut s = Story { points, comments, time, ..Story::EMPTY };
+ s.set_title(&mut t);
+ s
+ }
+
+ /// From stored bytes: `None` unless they are ASCII text of at most [`TITLE_MAX`] bytes, not empty.
+ pub fn with_raw_title(raw: &[u8], points: u32, comments: Option, time: u32) -> Option {
+ if raw.is_empty() || raw.len() > TITLE_MAX || !raw.iter().all(|&c| (b' '..=b'~').contains(&c)) {
+ return None;
+ }
+ let mut s = Story { points, comments, time, ..Story::EMPTY };
+ s.title[..raw.len()].copy_from_slice(raw);
+ s.len = raw.len() as u8;
+ Some(s)
+ }
+
+ pub fn title(&self) -> &str {
+ core::str::from_utf8(&self.title[..self.len as usize]).unwrap_or("")
+ }
+
+ fn set_title(&mut self, t: &mut Title) {
+ let b = t.finish();
+ self.title[..b.len()].copy_from_slice(b);
+ self.len = b.len() as u8;
+ }
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// ASCII
+
+const PRINTABLE: &str = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
+/// U+00C0..U+00FF to a base letter; `*` = see [`ascii`].
+const LATIN1: &[u8; 64] = b"AAAAAA*CEEEEIIIIDNOOOOOxOUUUUY**aaaaaa*ceeeeiiiidnooooo/ouuuuy*y";
+/// U+0100..U+017F (Latin Extended-A) to a base letter; `*` = see [`ascii`].
+const EXT_A: &[u8; 128] = b"AaAaAaCcCcCcCcDdDdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIi**JjKkkLlLlLlLlLlNnNnNnnNnOoOoOo**RrRrRrSsSsSsSsTtTtTtUuUuUuUuUuUuWwYyYZzZzZzs";
+
+/// What `ch` is written as on the watch: itself if ASCII, its plain look-alike, its base letter, or nothing.
+pub fn ascii(ch: char) -> &'static str {
+ let c = ch as u32;
+ let table = |t: &'static [u8], i: usize| -> &'static str {
+ let b = t[i];
+ if b == b'*' { "" } else { &PRINTABLE[(b - b' ') as usize..(b - b' ' + 1) as usize] }
+ };
+ match c {
+ 0x20..=0x7E => &PRINTABLE[(c - 0x20) as usize..(c - 0x1F) as usize],
+ 0x09 | 0x0A | 0x0D | 0xA0 => " ",
+ 0xAB | 0xBB => "\"",
+ 0xB4 => "'",
+ 0xB7 => "-",
+ 0xC6 => "AE",
+ 0xE6 => "ae",
+ 0xDE => "Th",
+ 0xFE => "th",
+ 0xDF => "ss",
+ 0xC0..=0xFF => table(LATIN1, (c - 0xC0) as usize),
+ 0x132 => "IJ",
+ 0x133 => "ij",
+ 0x152 => "OE",
+ 0x153 => "oe",
+ 0x100..=0x17F => table(EXT_A, (c - 0x100) as usize),
+ 0x2000..=0x200A | 0x202F | 0x205F | 0x3000 => " ",
+ 0x2010..=0x2015 | 0x2212 | 0x2022 | 0x2043 => "-",
+ 0x2018..=0x201B | 0x2032 | 0x2039 | 0x203A => "'",
+ 0x201C..=0x201F | 0x2033 => "\"",
+ 0x2026 => "...",
+ 0x2044 | 0x2215 => "/",
+ 0x2122 => "TM",
+ 0x2190 => "<-",
+ 0x2192 => "->",
+ 0x2194 => "<->",
+ 0x21D2 => "=>",
+ 0x2248 => "~",
+ 0x2260 => "!=",
+ 0x2264 => "<=",
+ 0x2265 => ">=",
+ _ => "",
+ }
+}
+
+/// A title being built: ASCII, spaces collapsed, none at the start; what doesn't fit is noted.
+struct Title {
+ buf: [u8; TITLE_MAX],
+ len: usize,
+ over: bool,
+}
+
+impl Title {
+ const fn new() -> Title {
+ Title { buf: [0; TITLE_MAX], len: 0, over: false }
+ }
+
+ fn push(&mut self, ch: char) {
+ for b in ascii(ch).bytes() {
+ if b == b' ' && (self.len == 0 || self.buf[self.len - 1] == b' ') {
+ continue;
+ }
+ if self.len == TITLE_MAX {
+ self.over |= b != b' ';
+ return;
+ }
+ self.buf[self.len] = b;
+ self.len += 1;
+ }
+ }
+
+ /// The title without trailing spaces; a cut one ends in "..." after its last whole word (if that isn't too far
+ /// back).
+ fn finish(&mut self) -> &[u8] {
+ while self.len > 0 && self.buf[self.len - 1] == b' ' {
+ self.len -= 1;
+ }
+ if self.over {
+ let room = TITLE_MAX - 3;
+ let mut end = room;
+ if self.buf[room] != b' ' {
+ if let Some(i) = self.buf[..room].iter().rposition(|&c| c == b' ').filter(|&i| i >= TITLE_MAX / 2) {
+ end = i;
+ }
+ }
+ while end > 0 && matches!(self.buf[end - 1], b' ' | b',' | b':' | b';' | b'-') {
+ end -= 1;
+ }
+ self.buf[end..end + 3].copy_from_slice(b"...");
+ self.len = end + 3;
+ self.over = false;
+ }
+ &self.buf[..self.len]
+ }
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// JSON
+
+struct Cur<'a> {
+ b: &'a [u8],
+ i: usize,
+}
+
+impl<'a> Cur<'a> {
+ fn ws(&mut self) {
+ while self.b.get(self.i).is_some_and(|c| c.is_ascii_whitespace()) {
+ self.i += 1;
+ }
+ }
+
+ fn peek(&mut self) -> Option {
+ self.ws();
+ self.b.get(self.i).copied()
+ }
+
+ fn eat(&mut self, c: u8) -> bool {
+ if self.peek() == Some(c) {
+ self.i += 1;
+ true
+ } else {
+ false
+ }
+ }
+
+ /// The raw bytes of a string, between its quotes (escapes left in); the cursor after the closing quote.
+ fn string(&mut self) -> Option<&'a [u8]> {
+ if !self.eat(b'"') {
+ return None;
+ }
+ let start = self.i;
+ loop {
+ match *self.b.get(self.i)? {
+ b'\\' => self.i += 2,
+ b'"' => {
+ let s = self.b.get(start..self.i)?;
+ self.i += 1;
+ return Some(s);
+ }
+ _ => self.i += 1,
+ }
+ }
+ }
+
+ /// An unsigned integer that fits a `u32` (a larger one is clamped); `None` for `null`, a sign, a fraction, an
+ /// exponent or a number the body cuts off. The cursor goes past the value either way, if it can.
+ fn uint(&mut self) -> Option