plexus-ui-engine 0.2.2

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
//! UI-6: **`live()`** — a component's collection bound to Plexus streams:
//! `{ rows, status }`.
//!
//! The snapshot method is called once (each data event's row is its one
//! object-valued field — `summary`, `ticket` — and an event with none, a
//! `page`, carries no row; PERF-15: a `rows { items }` event is a page's rows
//! at once, each item read as its own event would be); the changes stream (opened first, with its own
//! `changes_params`) is folded by the declaration's `on`:
//!
//! - `upsert:<field>` inserts or replaces, by `key`, the item at
//!   `event.<field>` — only if it matches every key of the snapshot's
//!   params that names a field of the item (`parent`, `epic`, `status`;
//!   `summary` and `limit` name none), so a filtered collection ignores
//!   what is not its own, and an item that stops matching is removed;
//! - `remove:<field>` removes the id, or each id of the list, at
//!   `event.<field>`;
//! - `lagged` runs the snapshot again, `resyncing` meanwhile.
//!
//! `status` moves `pending → live`; `resyncing` on a `lagged`, or when the
//! socket drops until [`LiveCache::reconnected`] has asked again.
//!
//! [`LiveCache`] shares one subscription between every reader asking the
//! same snapshot, params, changes and changes params, and keeps it
//! [`KEEP_MS`] past its last reader ([`LiveCache::sweep`] closes what has
//! waited longer).
//!
//! STUDIO-16: a change is folded as it is heard, and published — the
//! collection's value set, its readers drawn — once per animation frame
//! ([`Clock::frame`]): what a collection heard within a frame crosses as
//! one move, its deltas merged ([`Sub::merged`]). Any other move (an
//! answer, a status) publishes at once, the changes waiting carried in it.

use crate::signals::{Runtime, Signal};
use crate::transport::{CallId, Wire, WireItem};
use serde_json::{json, Map, Value};
use std::cell::{Cell, RefCell};
use std::collections::BTreeMap;
use std::rc::{Rc, Weak};

/// How long a subscription outlives its last reader, in milliseconds.
pub const KEEP_MS: u64 = 5_000;

/// Where a collection stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
    Pending,
    Live,
    Resyncing,
    Closed,
    Error,
    Refused,
}

impl Status {
    /// Its name, as it is written in a collection's value.
    pub fn as_str(self) -> &'static str {
        match self {
            Status::Pending => "pending",
            Status::Live => "live",
            Status::Resyncing => "resyncing",
            Status::Closed => "closed",
            Status::Error => "error",
            Status::Refused => "refused",
        }
    }
}

/// `{ "rows": […], "status": "live" }` of `rows` — STUDIO-16: one clone of
/// the rows, no serializer (each publish of a collection made it).
fn value_of(rows: &[Value], status: Status) -> Value {
    let mut o = Map::new();
    o.insert("rows".into(), Value::Array(rows.to_vec()));
    o.insert("status".into(), Value::String(status.as_str().into()));
    Value::Object(o)
}

/// One `on` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FoldRule {
    /// `upsert:<field>`.
    Upsert(String),
    /// `remove:<field>`.
    Remove(String),
}

impl std::str::FromStr for FoldRule {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, String> {
        match s.split_once(':') {
            Some(("upsert", f)) if !f.is_empty() => Ok(FoldRule::Upsert(f.into())),
            Some(("remove", f)) if !f.is_empty() => Ok(FoldRule::Remove(f.into())),
            _ => Err(format!("`{s}` is no fold: upsert:<field> or remove:<field>")),
        }
    }
}

/// A collection as a component reads it.
#[derive(Debug, Clone, PartialEq)]
pub struct Live {
    pub rows: Vec<Value>,
    pub status: Status,
}

impl Live {
    /// `{ "rows": […], "status": "live" }` — what an expression reads.
    pub fn to_value(&self) -> Value {
        value_of(&self.rows, self.status)
    }

    /// From [`Self::to_value`]'s shape.
    pub fn from_value(v: &Value) -> Option<Self> {
        Some(Self { rows: v.get("rows")?.as_array()?.clone(), status: serde_json::from_value(v.get("status")?.clone()).ok()? })
    }
}

/// A `live` declaration with its params evaluated: what a subscription is
/// keyed by (snapshot, params, changes, changes params) and how it folds.
#[derive(Debug, Clone, PartialEq)]
pub struct LiveSpec {
    pub snapshot: String,
    pub params: Value,
    /// UI-10: none — a one-shot read, no watch opened.
    pub changes: Option<String>,
    pub changes_params: Value,
    pub key: String,
    pub on: BTreeMap<String, FoldRule>,
}

impl LiveSpec {
    /// From its parts; an `on` rule that is no `upsert:`/`remove:` is refused.
    pub fn new(snapshot: &str, params: Value, changes: Option<&str>, changes_params: Value, key: &str, on: &[(&str, &str)]) -> Result<Self, String> {
        let on = on.iter().map(|(t, r)| Ok((t.to_string(), r.parse()?))).collect::<Result<_, String>>()?;
        let obj = |v: Value| if v.is_null() { json!({}) } else { v };
        Ok(Self { snapshot: snapshot.into(), params: obj(params), changes: changes.map(str::to_string), changes_params: obj(changes_params), key: key.into(), on })
    }

    /// FRAME-12: what is shared — the whole spec: two folds of one stream
    /// (another `key`, another `on`) are two collections.
    fn cache_key(&self) -> String {
        let on: Vec<String> = self.on.iter().map(|(t, r)| format!("{t}={r:?}")).collect();
        format!(
            "{}\u{0}{}\u{0}{}\u{0}{}\u{0}{}\u{0}{}",
            self.snapshot,
            self.params,
            self.changes.as_deref().unwrap_or(""),
            self.changes_params,
            self.key,
            on.join(",")
        )
    }

    /// FRAME-12: a spec as a module writes it — `{ snapshot, params?,
    /// changes?, changes_params?, key, on? }`; `params` and
    /// `changes_params` left out are `{}` (and share with a spec that says
    /// so); a field it does not know, or a fold that is none, is refused,
    /// naming it.
    pub fn from_value(v: &Value) -> Result<Self, String> {
        let o = v.as_object().ok_or("a live spec is { snapshot, params?, changes?, changes_params?, key, on? }")?;
        if let Some(k) = o.keys().find(|k| !["snapshot", "params", "changes", "changes_params", "key", "on"].contains(&k.as_str())) {
            return Err(format!("a live spec has no `{k}`: {{ snapshot, params?, changes?, changes_params?, key, on? }}"));
        }
        let text = |k: &str| o.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or(format!("a live spec's `{k}` is a name"));
        let changes = match o.get("changes") {
            None | Some(Value::Null) => None,
            Some(Value::String(c)) if !c.is_empty() => Some(c.as_str()),
            Some(_) => return Err("a live spec's `changes` is a name".into()),
        };
        let map = |k: &str| match o.get(k) {
            None | Some(Value::Null) => Ok(json!({})),
            Some(m @ Value::Object(_)) => Ok(m.clone()),
            Some(_) => Err(format!("a live spec's `{k}` is a map")),
        };
        let mut on = Vec::new();
        match o.get("on") {
            None | Some(Value::Null) => {}
            Some(Value::Object(m)) => {
                for (t, r) in m {
                    on.push((t.as_str(), r.as_str().ok_or(format!("a live spec's on.{t} is a fold: upsert:<field> or remove:<field>"))?));
                }
            }
            Some(_) => return Err("a live spec's `on` is a map of event type to fold".into()),
        }
        Self::new(text("snapshot")?, map("params")?, changes, map("changes_params")?, text("key")?, &on)
    }

    /// Whether `item` matches every snapshot param that names a field of it.
    pub fn admits(&self, item: &Value) -> bool {
        let (Some(params), Some(item)) = (self.params.as_object(), item.as_object()) else { return true };
        params.iter().all(|(k, v)| item.get(k).is_none_or(|have| have == v))
    }
}

/// The clock the cache keeps time by, and its timers (UI-10: a `live`'s
/// `debounce_ms`).
pub trait Clock {
    fn now_ms(&self) -> u64;
    /// Runs `f` once, `after_ms` from now.
    fn schedule(&self, after_ms: u64, f: Box<dyn FnOnce()>);
    /// STUDIO-16: runs `f` once at the next animation frame — the changes
    /// heard until then published together. A clock with no frames (the
    /// tests' [`ManualClock`] unless [`ManualClock::with_frames`]) runs it now.
    fn frame(&self, f: Box<dyn FnOnce()>) {
        f()
    }
}

/// A timer of [`ManualClock`]: when it is due, its order, what it runs.
type Timer = (u64, u64, Box<dyn FnOnce()>);

/// The tests' clock: moves only when told, running each timer that comes
/// due on the way, in order.
#[derive(Clone, Default)]
pub struct ManualClock {
    now: Rc<Cell<u64>>,
    timers: Rc<RefCell<Vec<Timer>>>,
    seq: Rc<Cell<u64>>,
    /// STUDIO-16: frames asked, run by [`Self::next_frame`] — when on.
    frames: Option<Rc<RefCell<Vec<Box<dyn FnOnce()>>>>>,
}

impl std::fmt::Debug for ManualClock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ManualClock({} ms, {} timers)", self.now.get(), self.timers.borrow().len())
    }
}

impl ManualClock {
    pub fn new() -> Self {
        Self::default()
    }

    /// STUDIO-16: a clock with animation frames — [`Clock::frame`] waits
    /// for [`Self::next_frame`].
    pub fn with_frames() -> Self {
        Self { frames: Some(Rc::default()), ..Self::default() }
    }

    /// STUDIO-16: the next animation frame: what was asked for it runs.
    pub fn next_frame(&self) {
        let due = self.frames.as_ref().map(|f| std::mem::take(&mut *f.borrow_mut())).unwrap_or_default();
        for f in due {
            f();
        }
    }

    /// Moves `ms` on, running the timers that come due (a timer set by one
    /// that runs is run too, when due by the end).
    pub fn advance(&self, ms: u64) {
        let end = self.now.get() + ms;
        loop {
            let next = {
                let mut t = self.timers.borrow_mut();
                let i = t.iter().enumerate().filter(|(_, (due, _, _))| *due <= end).min_by_key(|(_, (due, seq, _))| (*due, *seq)).map(|(i, _)| i);
                i.map(|i| t.remove(i))
            };
            let Some((due, _, f)) = next else { break };
            self.now.set(due.max(self.now.get()));
            f();
        }
        self.now.set(end);
    }
}

impl Clock for ManualClock {
    fn now_ms(&self) -> u64 {
        self.now.get()
    }
    fn schedule(&self, after_ms: u64, f: Box<dyn FnOnce()>) {
        let seq = self.seq.get() + 1;
        self.seq.set(seq);
        self.timers.borrow_mut().push((self.now.get() + after_ms, seq, f));
    }
    fn frame(&self, f: Box<dyn FnOnce()>) {
        match &self.frames {
            Some(frames) => frames.borrow_mut().push(f),
            None => f(),
        }
    }
}

/// One kept subscription.
struct Sub {
    spec: LiveSpec,
    signal: Signal<Value>,
    rows: Vec<Value>,
    status: Status,
    readers: usize,
    released_at: u64,
    changes: Option<CallId>,
    snapshot: Option<CallId>,
    /// The snapshot's rows as they arrive.
    buffer: Vec<Value>,
    /// FRAME-48: the changes heard while the snapshot runs, folded again
    /// over its answer — the changes stream is opened first so nothing is
    /// missed, and an answer landing whole must not take back what came
    /// on it meanwhile (a `shown` said as a watch opens, a row created
    /// between the snapshot's read and its `done`). Upserts by key, in
    /// order: folding one again over a snapshot that has it already moves
    /// nothing. FRAME-48b: a remove heard meanwhile takes away only what an
    /// upsert heard meanwhile put there, never a row of the answer — a
    /// stream's opening word folded as a remove (menger's releases fold the
    /// watch's `live { version }` as `remove:version`, the pointer as it
    /// stands) took the live version out of the list.
    during: Vec<Value>,
    /// FRAME-48: which snapshot is the one asked last — each asked takes the
    /// next number, and an answer to an earlier one (a `lagged` heard while
    /// it ran asks again) is not heard: it neither fills the buffer nor
    /// takes `during` nor ends the snapshot that is running.
    asked: u64,
    /// UI-8: why the last snapshot was refused — an in-band `error` event's
    /// `message` (status `error`), or the call's refusal (status `refused`);
    /// published as the collection's `message`.
    message: Option<String>,
    /// An in-band `error` heard while the snapshot runs.
    erred: Option<String>,
    /// FRAME-17: when (the page's clock) its first answer with rows came.
    answered_at: Rc<Cell<Option<f64>>>,
    /// FRAME-20: how many times its value has moved, and the last move.
    moved: Moves,
    /// STUDIO-16: the changes folded since it was last published, merged —
    /// published at the next frame (or with the next move that cannot wait).
    pending: Option<Delta>,
}

/// FRAME-20: a collection's moves — how many, and the last one.
type Moves = Rc<RefCell<(u64, Delta)>>;

/// FRAME-20: `value` set on `signal` as one more move, `delta`, recorded in
/// `moved` before the signal's readers wake (they read it); a value equal to
/// the one held is no move.
fn moved_to(signal: &Signal<Value>, moved: &Moves, value: Value, delta: Delta) {
    let prev = {
        let mut m = moved.borrow_mut();
        let next = (m.0 + 1, delta);
        std::mem::replace(&mut *m, next)
    };
    if !signal.set_if(value) {
        *moved.borrow_mut() = prev;
    }
}

/// FRAME-12: the collection's value set on its signal with no borrow of
/// the subscription held — a reader woken by it (a module's `subscribe`
/// callback) may acquire, release or read the cache.
fn publish(sub: &Rc<RefCell<Sub>>, delta: Delta) {
    let (signal, value, moved) = {
        let s = sub.borrow();
        (s.signal.clone(), s.value(), s.moved.clone())
    };
    moved_to(&signal, &moved, value, delta);
}

/// STUDIO-16: a move published now, carrying the changes still waiting for
/// their frame.
fn publish_now(sub: &Rc<RefCell<Sub>>, delta: Delta) {
    let delta = {
        let mut s = sub.borrow_mut();
        match s.pending.take() {
            Some(p) => s.merged(p, delta),
            None => delta,
        }
    };
    publish(sub, delta);
}

/// FRAME-20: a move of the status alone — no row changed.
fn status_only() -> Delta {
    Delta::Change { upsert: Vec::new(), remove: Vec::new() }
}

impl Sub {
    fn value(&self) -> Value {
        let mut v = value_of(&self.rows, self.status);
        if let (Some(m), Some(o)) = (&self.message, v.as_object_mut()) {
            o.insert("message".into(), Value::String(m.clone()));
        }
        v
    }

    /// STUDIO-16: two moves as one, as `host.js`'s store applies a change
    /// (its removes, then each upsert in place or last): a row upserted and
    /// then removed is only removed; a row upserted twice is upserted once,
    /// as it is last, where it was first; a key removed then upserted is in
    /// both, so it goes and comes back last — as the fold left it.
    fn merged(&self, a: Delta, b: Delta) -> Delta {
        // Keys compared in place: no String made per comparison.
        let k = &self.spec.key;
        let same = |x: &Value, y: &Value| x.get(k).is_some() && x.get(k) == y.get(k);
        let named = |row: &Value, key: &str| match row.get(k) {
            Some(Value::String(s)) => s == key,
            Some(other) => other.to_string() == key,
            None => false,
        };
        match (a, b) {
            (Delta::Change { upsert: mut up, remove: mut gone }, Delta::Change { upsert: up2, remove: gone2 }) => {
                if !gone2.is_empty() {
                    up.retain(|row| !gone2.iter().any(|g| named(row, g)));
                    for g in gone2 {
                        if !gone.contains(&g) {
                            gone.push(g);
                        }
                    }
                }
                for row in up2 {
                    match up.iter().position(|x| same(x, &row)) {
                        Some(i) => up[i] = row,
                        None => up.push(row),
                    }
                }
                Delta::Change { upsert: up, remove: gone }
            }
            _ => Delta::Whole,
        }
    }

    fn key_of(&self, item: &Value) -> Option<String> {
        match item.get(&self.spec.key)? {
            Value::String(s) => Some(s.clone()),
            other => Some(other.to_string()),
        }
    }

    fn position(&self, key: &str) -> Option<usize> {
        // STUDIO-16: compared in place — key_of's String per row was a fold's
        // cost, row by row.
        self.rows.iter().position(|r| match r.get(&self.spec.key) {
            Some(Value::String(s)) => s == key,
            Some(other) => other.to_string() == key,
            None => false,
        })
    }

    /// FRAME-48b: `during` folded over a snapshot's answer — each upsert, and
    /// each remove of a key only an upsert of `during` put there.
    fn replay(&mut self, during: Vec<Value>) {
        let mut put = std::collections::BTreeSet::new();
        for event in during {
            let Some(kind) = event.get("type").and_then(Value::as_str) else { continue };
            match self.spec.on.get(kind).cloned() {
                Some(FoldRule::Upsert(field)) => {
                    let item = if field == "." { Some(event.clone()) } else { event.get(&field).cloned() };
                    if let Some(k) = item.as_ref().and_then(|i| self.key_of(i)) {
                        put.insert(k);
                    }
                    let _ = self.fold(&event);
                }
                Some(FoldRule::Remove(field)) => {
                    let ids: Vec<String> = match event.get(&field) {
                        Some(Value::Array(a)) => a.iter().map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).collect(),
                        Some(Value::String(s)) => vec![s.clone()],
                        Some(Value::Null) | None => continue,
                        Some(v) => vec![v.to_string()],
                    };
                    let ours: Vec<Value> = ids.into_iter().filter(|k| put.remove(k)).map(Value::String).collect();
                    if ours.is_empty() {
                        continue;
                    }
                    let mut e = event.clone();
                    if let Some(o) = e.as_object_mut() {
                        o.insert(field, Value::Array(ours));
                    }
                    let _ = self.fold(&e);
                }
                None => {}
            }
        }
    }

    /// Folds one change event; what moved (FRAME-20: by key — a row
    /// inserted or replaced, keys removed), none when nothing did.
    fn fold(&mut self, event: &Value) -> Option<Delta> {
        let Some(kind) = event.get("type").and_then(Value::as_str) else { return None };
        match self.spec.on.get(kind).cloned() {
            Some(FoldRule::Upsert(field)) => {
                // UI-10: `upsert:.` — the event itself, less `type`, is the row.
                let item = if field == "." {
                    let mut flat = event.as_object().cloned().unwrap_or_default();
                    flat.remove("type");
                    Some(Value::Object(flat))
                } else {
                    event.get(&field).filter(|i| i.is_object()).cloned()
                };
                let item = item?;
                let key = self.key_of(&item)?;
                let at = self.position(&key);
                match (self.spec.admits(&item), at) {
                    // FRAME-20: the row as it is kept: nothing moved.
                    (true, Some(i)) if self.rows[i] == item => None,
                    (true, Some(i)) => {
                        self.rows[i] = item.clone();
                        Some(Delta::Change { upsert: vec![item], remove: Vec::new() })
                    }
                    (true, None) => {
                        self.rows.push(item.clone());
                        Some(Delta::Change { upsert: vec![item], remove: Vec::new() })
                    }
                    (false, Some(i)) => {
                        self.rows.remove(i);
                        Some(Delta::Change { upsert: Vec::new(), remove: vec![key] })
                    }
                    (false, None) => None,
                }
            }
            Some(FoldRule::Remove(field)) => {
                let ids: Vec<String> = match event.get(&field) {
                    Some(Value::Array(a)) => a.iter().map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).collect(),
                    Some(Value::String(s)) => vec![s.clone()],
                    Some(Value::Null) | None => return None,
                    Some(v) => vec![v.to_string()],
                };
                let key = self.spec.key.clone();
                let mut removed = Vec::new();
                self.rows.retain(|r| {
                    let k = match r.get(&key) {
                        Some(Value::String(s)) => s.clone(),
                        Some(v) => v.to_string(),
                        None => return true,
                    };
                    let keep = !ids.contains(&k);
                    if !keep {
                        removed.push(k);
                    }
                    keep
                });
                (!removed.is_empty()).then_some(Delta::Change { upsert: Vec::new(), remove: removed })
            }
            None => None,
        }
    }
}

/// A snapshot event's row, as the spec's rule for its type makes it from a
/// change: `upsert:.` — the event itself less `type`; `upsert:<field>` —
/// that field. With no rule for its type: its one object-valued field;
/// else (a flat event) the event less `type` when it carries the key; else
/// none (a `page`).
fn row_of(event: &Value, spec: &LiveSpec) -> Option<Value> {
    let o = event.as_object()?;
    let flat = || {
        let mut flat = o.clone();
        flat.remove("type");
        Value::Object(flat)
    };
    let kind = o.get("type").and_then(Value::as_str).unwrap_or_default();
    match spec.on.get(kind) {
        Some(FoldRule::Upsert(f)) if f == "." => return Some(flat()),
        Some(FoldRule::Upsert(f)) => {
            if let Some(row) = o.get(f).filter(|v| v.is_object()) {
                return Some(row.clone());
            }
        }
        _ => {}
    }
    let mut objects = o.iter().filter(|(k, v)| k.as_str() != "type" && v.is_object());
    if let Some((_, row)) = objects.next() {
        return objects.next().is_none().then(|| row.clone());
    }
    o.contains_key(&spec.key).then(flat)
}

/// Every `live` subscription of the page.
pub struct LiveCache<W: Wire, C: Clock> {
    rt: Runtime,
    wire: W,
    clock: C,
    subs: RefCell<BTreeMap<String, Rc<RefCell<Sub>>>>,
    /// FRAME-50: what runs once the snapshots running when it was asked
    /// are answered — their keys, and it.
    answered: RefCell<Vec<(Vec<String>, Box<dyn FnOnce()>)>>,
    /// STUDIO-16: the collections with changes waiting for the frame, and
    /// whether the frame is asked.
    dirty: RefCell<Vec<String>>,
    frame_asked: Cell<bool>,
    me: Weak<Self>,
}

impl<W: Wire + Clone + 'static, C: Clock + Clone + 'static> LiveCache<W, C> {
    pub fn new(rt: &Runtime, wire: W, clock: C) -> Rc<Self> {
        Rc::new_cyclic(|me| Self { rt: rt.clone(), wire, clock, subs: RefCell::default(), answered: RefCell::default(), dirty: RefCell::default(), frame_asked: Cell::new(false), me: me.clone() })
    }

    /// FRAME-50: how many snapshots are asked and not yet answered (done,
    /// refused or failed).
    pub fn running(&self) -> usize {
        self.running_keys().len()
    }

    fn running_keys(&self) -> Vec<String> {
        self.subs.borrow().iter().filter(|(_, s)| s.borrow().snapshot.is_some()).map(|(k, _)| k.clone()).collect()
    }

    /// FRAME-50: `f` once every snapshot running now is answered (or let
    /// go) — now, when none is; one asked later is not waited for.
    pub fn when_answered(&self, f: Box<dyn FnOnce()>) {
        let keys = self.running_keys();
        if keys.is_empty() {
            return f();
        }
        self.answered.borrow_mut().push((keys, f));
    }

    fn answered_check(&self) {
        if self.answered.borrow().is_empty() {
            return;
        }
        let running = self.running_keys();
        let (done, wait): (Vec<_>, Vec<_>) = std::mem::take(&mut *self.answered.borrow_mut()).into_iter().partition(|(keys, _)| !keys.iter().any(|k| running.contains(k)));
        self.answered.borrow_mut().extend(wait);
        for (_, f) in done {
            f();
        }
    }

    /// A reader of `spec`'s collection: the subscription kept for it, else
    /// a new one (changes opened, then the snapshot).
    pub fn acquire(self: &Rc<Self>, spec: &LiveSpec) -> Reader {
        let key = spec.cache_key();
        let existing = self.subs.borrow().get(&key).cloned();
        let sub = match existing {
            Some(sub) => sub,
            None => {
                let signal = self.rt.signal(Live { rows: Vec::new(), status: Status::Pending }.to_value());
                let sub = Rc::new(RefCell::new(Sub {
                    spec: spec.clone(),
                    signal,
                    rows: Vec::new(),
                    status: Status::Pending,
                    readers: 0,
                    released_at: 0,
                    changes: None,
                    snapshot: None,
                    buffer: Vec::new(),
                    during: Vec::new(),
                    asked: 0,
                    message: None,
                    erred: None,
                    answered_at: Rc::default(),
                    moved: Rc::new(RefCell::new((0, Delta::Whole))),
                    pending: None,
                }));
                self.subs.borrow_mut().insert(key.clone(), sub.clone());
                self.open_changes(&key, &sub);
                self.open_snapshot(&key, &sub);
                sub
            }
        };
        let (signal, answered_at, moved) = {
            let mut s = sub.borrow_mut();
            s.readers += 1;
            (s.signal.clone(), s.answered_at.clone(), s.moved.clone())
        };
        let me = self.me.clone();
        Reader {
            signal,
            answered_at,
            moved,
            release: Some(Box::new(move || {
                if let Some(cache) = me.upgrade() {
                    cache.release(&key);
                }
            })),
        }
    }

    fn release(&self, key: &str) {
        if let Some(sub) = self.subs.borrow().get(key) {
            let mut s = sub.borrow_mut();
            s.readers = s.readers.saturating_sub(1);
            if s.readers == 0 {
                s.released_at = self.clock.now_ms();
            }
        }
    }

    fn open_changes(&self, key: &str, sub: &Rc<RefCell<Sub>>) {
        let (method, params) = {
            let s = sub.borrow();
            (s.spec.changes.clone(), s.spec.changes_params.clone())
        };
        // UI-10: a live without changes is a one-shot read: no watch.
        let Some(method) = method else { return };
        let (me, k) = (self.me.clone(), key.to_string());
        let id = self.wire.open(&method, params, Box::new(move |item| {
            if let Some(cache) = me.upgrade() {
                cache.heard_change(&k, item);
            }
        }));
        sub.borrow_mut().changes = Some(id);
    }

    fn open_snapshot(&self, key: &str, sub: &Rc<RefCell<Sub>>) {
        let (method, params, asked) = {
            let mut s = sub.borrow_mut();
            s.buffer.clear();
            // FRAME-48: what was heard before this snapshot was asked is in
            // its answer, or older than it: never folded over it.
            s.during.clear();
            s.erred = None;
            s.asked += 1;
            (s.spec.snapshot.clone(), s.spec.params.clone(), s.asked)
        };
        let (me, k) = (self.me.clone(), key.to_string());
        crate::marks::once("first-call");
        let id = self.wire.open(&method, params, Box::new(move |item| {
            if let Some(cache) = me.upgrade() {
                cache.heard_snapshot(&k, asked, item);
            }
        }));
        let mut s = sub.borrow_mut();
        // A snapshot that answered at once (a fake, a cache) is done already.
        if s.snapshot.is_none() && matches!(s.status, Status::Live) {
            return;
        }
        s.snapshot = Some(id);
    }

    fn sub(&self, key: &str) -> Option<Rc<RefCell<Sub>>> {
        self.subs.borrow().get(key).cloned()
    }

    fn heard_snapshot(&self, key: &str, asked: u64, item: WireItem) {
        let Some(sub) = self.sub(key) else { return };
        let mut s = sub.borrow_mut();
        // FRAME-48: an earlier snapshot's answer, one asked again since.
        if asked != s.asked {
            return;
        }
        // FRAME-20: an answer is the whole collection; a refusal or a
        // failure moves the status alone, the rows kept.
        let mut delta = Delta::Whole;
        match item {
            WireItem::Data(event) => {
                // UI-8: an in-band refusal (`{ type: "error", message }`, a
                // filter not taken) makes the answer an error, not a row.
                if event.get("type").and_then(Value::as_str) == Some("error") {
                    s.erred = Some(event.get("message").and_then(Value::as_str).unwrap_or("refused").to_string());
                    return;
                }
                // PERF-15: a page's rows as one event — `rows { items }`,
                // each item the per-row event it stands for, its row taken
                // as that event's would be. A page may be several (past the
                // service's byte budget): each adds to the one buffer, and
                // the page lands whole at `done`, one move.
                if event.get("type").and_then(Value::as_str) == Some("rows") {
                    let spec = s.spec.clone();
                    let rows = event.get("items").and_then(Value::as_array).into_iter().flatten().filter_map(|item| row_of(item, &spec));
                    s.buffer.extend(rows);
                    return;
                }
                if let Some(row) = row_of(&event, &s.spec) {
                    s.buffer.push(row);
                }
                return;
            }
            WireItem::Done => match s.erred.take() {
                Some(m) => {
                    s.buffer.clear();
                    s.during.clear();
                    s.rows.clear();
                    s.status = Status::Error;
                    s.message = Some(m);
                }
                None => {
                    s.rows = std::mem::take(&mut s.buffer);
                    // FRAME-48: what the changes said meanwhile, over it.
                    let during = std::mem::take(&mut s.during);
                    s.replay(during);
                    s.status = Status::Live;
                    s.message = None;
                    if !s.rows.is_empty() && s.answered_at.get().is_none() {
                        s.answered_at.set(Some(crate::marks::now()));
                    }
                }
            },
            WireItem::Refused(m) => {
                s.during.clear();
                s.status = Status::Refused;
                s.message = Some(m);
                delta = status_only();
            }
            WireItem::Failed(_) | WireItem::Dropped => {
                s.during.clear();
                s.status = Status::Resyncing;
                delta = status_only();
            }
        }
        s.snapshot = None;
        // FRAME-17: rows a reader draws now (one asked at boot and not yet
        // read is drawn by its mount: `swap` marks it there).
        let drawn = (s.readers > 0 && s.status == Status::Live).then(|| s.answered_at.get()).flatten();
        let snapshot = s.spec.snapshot.clone();
        drop(s);
        if let Some(at) = drawn {
            crate::marks::once_at("first-answer", at);
            crate::marks::once_at(&format!("answered:{snapshot}"), at);
        }
        publish_now(&sub, delta);
        if drawn.is_some() {
            crate::marks::once("first-row");
            crate::marks::once(&format!("drawn:{snapshot}"));
        }
        self.answered_check();
    }

    fn heard_change(&self, key: &str, item: WireItem) {
        let Some(sub) = self.sub(key) else { return };
        match item {
            WireItem::Data(event) if event.get("type").and_then(Value::as_str) == Some("lagged") => {
                sub.borrow_mut().status = Status::Resyncing;
                publish_now(&sub, status_only());
                self.open_snapshot(key, &sub);
            }
            WireItem::Data(event) => {
                let moved = {
                    let mut s = sub.borrow_mut();
                    // FRAME-48: kept to fold again over the snapshot's answer.
                    if s.snapshot.is_some() || s.status == Status::Pending {
                        s.during.push(event.clone());
                    }
                    s.fold(&event)
                };
                if let Some(delta) = moved {
                    self.defer(key, &sub, delta);
                }
            }
            WireItem::Done => sub.borrow_mut().changes = None,
            WireItem::Refused(_) => {
                let mut s = sub.borrow_mut();
                s.changes = None;
                s.status = Status::Refused;
                drop(s);
                publish_now(&sub, status_only());
            }
            WireItem::Failed(_) | WireItem::Dropped => {
                let mut s = sub.borrow_mut();
                s.changes = None;
                s.status = Status::Resyncing;
                drop(s);
                publish_now(&sub, status_only());
            }
        }
    }

    /// STUDIO-16: a change folded into `sub`, published at the next frame
    /// with whatever else it hears until then.
    fn defer(&self, key: &str, sub: &Rc<RefCell<Sub>>, delta: Delta) {
        let first = {
            let mut s = sub.borrow_mut();
            let (merged, first) = match s.pending.take() {
                Some(p) => (s.merged(p, delta), false),
                None => (delta, true),
            };
            s.pending = Some(merged);
            first
        };
        if first {
            self.dirty.borrow_mut().push(key.to_string());
        }
        if !self.frame_asked.replace(true) {
            let me = self.me.clone();
            self.clock.frame(Box::new(move || {
                if let Some(cache) = me.upgrade() {
                    cache.flush();
                }
            }));
        }
    }

    /// STUDIO-16: the frame — every collection with changes waiting
    /// published, its readers drawn once (one batch: a binding reading
    /// several runs once).
    pub fn flush(&self) {
        self.frame_asked.set(false);
        let keys = std::mem::take(&mut *self.dirty.borrow_mut());
        if keys.is_empty() {
            return;
        }
        self.rt.batch(|| {
            for k in keys {
                let Some(sub) = self.sub(&k) else { continue };
                let pending = sub.borrow_mut().pending.take();
                if let Some(delta) = pending {
                    publish(&sub, delta);
                }
            }
        });
    }

    /// Closes every subscription with no reader for longer than [`KEEP_MS`].
    pub fn sweep(&self) {
        let now = self.clock.now_ms();
        let gone: Vec<(String, Rc<RefCell<Sub>>)> = self
            .subs
            .borrow()
            .iter()
            .filter(|(_, s)| {
                let s = s.borrow();
                s.readers == 0 && now.saturating_sub(s.released_at) > KEEP_MS
            })
            .map(|(k, s)| (k.clone(), s.clone()))
            .collect();
        for (k, sub) in gone {
            self.subs.borrow_mut().remove(&k);
            let (changes, snapshot) = {
                let mut s = sub.borrow_mut();
                s.status = Status::Closed;
                (s.changes.take(), s.snapshot.take())
            };
            for id in [changes, snapshot].into_iter().flatten() {
                self.wire.close(id);
            }
        }
    }

    /// The socket came back: every kept subscription `resyncing`, its
    /// changes re-opened and its snapshot asked again.
    pub fn reconnected(&self) {
        let subs: Vec<(String, Rc<RefCell<Sub>>)> = self.subs.borrow().iter().map(|(k, s)| (k.clone(), s.clone())).collect();
        for (k, sub) in subs {
            let (changes, snapshot) = {
                let mut s = sub.borrow_mut();
                s.status = Status::Resyncing;
                (s.changes.take(), s.snapshot.take())
            };
            for id in [changes, snapshot].into_iter().flatten() {
                self.wire.close(id);
            }
            publish_now(&sub, status_only());
            self.open_changes(&k, &sub);
            self.open_snapshot(&k, &sub);
        }
    }

    /// How many subscriptions are kept (read or waiting out their 5 s).
    pub fn kept(&self) -> usize {
        self.subs.borrow().len()
    }
}

/// UI-10: a `live` as declared, before its params are known: the methods,
/// the key, the folds, and how long its params must be quiet before it
/// runs again.
#[derive(Debug, Clone, PartialEq)]
pub struct LiveQuery {
    pub snapshot: String,
    pub changes: Option<String>,
    pub key: String,
    pub on: Vec<(String, String)>,
    pub debounce_ms: Option<u64>,
}

impl<W: Wire + Clone + 'static, C: Clock + Clone + 'static> LiveCache<W, C> {
    /// UI-10: a collection whose params are `params()` — `(params,
    /// changes_params)`, read in a binding: when a signal it read changes,
    /// the snapshot runs again (after `debounce_ms` of quiet when given),
    /// the old rows kept, `resyncing`, until the new snapshot lands.
    pub fn follow(self: &Rc<Self>, query: LiveQuery, mut params: impl FnMut() -> (Value, Value) + 'static) -> Follow {
        self.follow_held(query, move || Some(params()))
    }

    /// FRAME-16: [`Self::follow`], held while `params()` answers `None` (its
    /// `when` is false): nothing is asked, and a reader it held is let go —
    /// the rows stay as they were; answered again, it runs with the params
    /// of that moment — after `debounce_ms` when it has one (a query typed
    /// into a held palette is one call, not one per key).
    pub fn follow_held(self: &Rc<Self>, query: LiveQuery, mut params: impl FnMut() -> Option<(Value, Value)> + 'static) -> Follow {
        let out = self.rt.signal(Live { rows: Vec::new(), status: Status::Pending }.to_value());
        let crossing: Moves = Rc::new(RefCell::new((0, Delta::Whole)));
        let st: Rc<RefCell<Following>> = Rc::new(RefCell::new(Following { reader: None, mirror: None, generation: 0, last: None, stopped: false }));
        let (me, st2, out2, q, cr2) = (Rc::downgrade(self), st.clone(), out.clone(), Rc::new(query), crossing.clone());
        let rt = self.rt.clone();
        let was_held = Rc::new(Cell::new(false));
        let binding = self.rt.bind(move || {
            let held = params();
            let Some(cache) = me.upgrade() else { return };
            let Some(p) = held else {
                was_held.set(true);
                let mut s = st2.borrow_mut();
                if s.last.take().is_some() {
                    s.generation += 1;
                    if let Some(m) = s.mirror.take() {
                        rt.dispose(m);
                    }
                    s.reader = None;
                }
                return;
            };
            let first = {
                let mut s = st2.borrow_mut();
                if s.last.as_ref() == Some(&p) {
                    return;
                }
                let first = s.last.is_none();
                s.last = Some(p.clone());
                s.generation += 1;
                first
            };
            let resumed = was_held.replace(false);
            match q.debounce_ms.filter(|_| !first || resumed) {
                None => rt.untracked(|| cache.switch(&st2, &out2, &cr2, &q, p, first)),
                Some(ms) => {
                    let generation = st2.borrow().generation;
                    let (me, st3, out3, q2, rt2, cr3) = (Rc::downgrade(&cache), st2.clone(), out2.clone(), q.clone(), rt.clone(), cr2.clone());
                    cache.clock.schedule(
                        ms,
                        Box::new(move || {
                            let current = { let s = st3.borrow(); !s.stopped && s.generation == generation };
                            if let (true, Some(cache)) = (current, me.upgrade()) {
                                rt2.untracked(|| cache.switch(&st3, &out3, &cr3, &q2, p, first));
                            }
                        }),
                    );
                }
            }
        });
        let rt = self.rt.clone();
        Follow {
            signal: out,
            crossing,
            st: st.clone(),
            stop: Some(Box::new(move || {
                rt.dispose(binding);
                let mut s = st.borrow_mut();
                s.stopped = true;
                if let Some(m) = s.mirror.take() {
                    rt.dispose(m);
                }
                s.reader = None;
            })),
        }
    }

    /// The followed collection on the params `p`: a reader of their spec,
    /// mirrored into `out` — the old rows, `resyncing`, while the new one
    /// is pending.
    fn switch(self: &Rc<Self>, st: &Rc<RefCell<Following>>, out: &Signal<Value>, crossing: &Moves, q: &LiveQuery, p: (Value, Value), first: bool) {
        let on: Vec<(&str, &str)> = q.on.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect();
        let spec = match LiveSpec::new(&q.snapshot, p.0, q.changes.as_deref(), p.1, &q.key, &on) {
            Ok(spec) => spec,
            Err(_) => {
                moved_to(out, crossing, Live { rows: Vec::new(), status: Status::Error }.to_value(), Delta::Whole);
                return;
            }
        };
        let reader = self.acquire(&spec);
        let sig = reader.signal();
        let old_rows = if first { Vec::new() } else { Live::from_value(&out.peek()).map(|l| l.rows).unwrap_or_default() };
        let switching = Rc::new(Cell::new(!first));
        let (o, sw, cr, rm) = (out.clone(), switching.clone(), crossing.clone(), reader.moved.clone());
        // FRAME-20: the reader's move it saw last (none: this mirror's first
        // run, which crosses whole — another collection's rows).
        let seen = Cell::new(None::<u64>);
        let mirror = self.rt.bind(move || {
            let v = sig.get();
            let (at, delta) = rm.borrow().clone();
            let last = seen.replace(Some(at));
            // STUDIO-16: its status read in place (no copy of its rows).
            let pending = v.get("status").and_then(Value::as_str) == Some(Status::Pending.as_str());
            match pending {
                true if sw.get() => moved_to(&o, &cr, Live { rows: old_rows.clone(), status: Status::Resyncing }.to_value(), status_only()),
                _ => {
                    sw.set(false);
                    let delta = match last {
                        Some(p) if at == p + 1 => delta,
                        _ => Delta::Whole,
                    };
                    moved_to(&o, &cr, v, delta);
                }
            }
        });
        let mut s = st.borrow_mut();
        if let Some(old) = s.mirror.replace(mirror) {
            self.rt.dispose(old);
        }
        s.reader = Some(reader);
    }
}

/// FRAME-19: a module's `live` spec — [`LiveSpec::from_value`]'s keys,
/// plus what rhx's `live` has: `when` (a boolean, `true` when left out;
/// `false` holds it — nothing asked) and `debounce_ms` (how long its params
/// must be quiet before it runs again). `when` and `debounce_ms` are not
/// part of what is shared: two modules asking the same spec, held or not,
/// read one collection once both ask.
#[derive(Debug, Clone, PartialEq)]
pub struct ModuleSpec {
    pub query: LiveQuery,
    pub params: Value,
    pub changes_params: Value,
    pub when: bool,
}

impl ModuleSpec {
    /// From a module's spec as it crosses the bus (JSON): `{ snapshot,
    /// params?, changes?, changes_params?, key, on?, when?, debounce_ms? }`;
    /// a `when` that is no boolean, a `debounce_ms` that is no count, or a
    /// key it does not know is refused, naming it.
    pub fn from_value(v: &Value) -> Result<Self, String> {
        let o = v.as_object().ok_or("a live spec is { snapshot, params?, changes?, changes_params?, key, on?, when?, debounce_ms? }")?;
        let mut shared = o.clone();
        let when = match shared.remove("when") {
            None | Some(Value::Null) => true,
            Some(Value::Bool(b)) => b,
            Some(_) => return Err("a live spec's `when` is true or false".into()),
        };
        let debounce_ms = match shared.remove("debounce_ms") {
            None | Some(Value::Null) => None,
            Some(n) => Some(n.as_u64().ok_or("a live spec's `debounce_ms` is a count of milliseconds")?),
        };
        let s = LiveSpec::from_value(&Value::Object(shared)).map_err(|e| e.replace("on? }", "on?, when?, debounce_ms? }"))?;
        let on = o.get("on").and_then(Value::as_object).map(|m| m.iter().map(|(t, r)| (t.clone(), r.as_str().unwrap_or_default().to_string())).collect()).unwrap_or_default();
        Ok(Self {
            query: LiveQuery { snapshot: s.snapshot, changes: s.changes, key: s.key, on, debounce_ms },
            params: s.params,
            changes_params: s.changes_params,
            when,
        })
    }

    /// This spec with `patch` — `{ params?, changes_params?, when? }` —
    /// over it; anything else in the patch refused, naming it.
    pub fn patched(&self, patch: &Value) -> Result<Self, String> {
        let p = patch.as_object().ok_or("a live's update is { params?, changes_params?, when? }")?;
        let mut next = self.clone();
        for (k, v) in p {
            match (k.as_str(), v) {
                ("params" | "changes_params", Value::Null) => *(if k == "params" { &mut next.params } else { &mut next.changes_params }) = json!({}),
                ("params", Value::Object(_)) => next.params = v.clone(),
                ("changes_params", Value::Object(_)) => next.changes_params = v.clone(),
                ("params" | "changes_params", _) => return Err(format!("a live's update: `{k}` is a map")),
                ("when", Value::Bool(b)) => next.when = *b,
                ("when", _) => return Err("a live's update: `when` is true or false".into()),
                _ => return Err(format!("a live's update has no `{k}`: {{ params?, changes_params?, when? }}")),
            }
        }
        Ok(next)
    }
}

/// FRAME-19: a module's collection — [`LiveCache::follow_held`] over the
/// spec's params and `when`, which the module moves with
/// [`ModuleLive::update`]; the registry owns the timing (`debounce_ms`).
pub struct ModuleLive {
    follow: Follow,
    spec: Rc<RefCell<ModuleSpec>>,
    inputs: Signal<Value>,
}

impl ModuleLive {
    /// `patch` — `{ params?, changes_params?, when? }` — over what the
    /// collection follows now; the keys left out stay as they are. A patch
    /// that changes nothing asks nothing.
    pub fn update(&self, patch: &Value) -> Result<(), String> {
        let next = self.spec.borrow().patched(patch)?;
        let value = json!({ "params": next.params, "changes_params": next.changes_params, "when": next.when });
        *self.spec.borrow_mut() = next;
        if self.inputs.peek() != value {
            self.inputs.set(value);
        }
        Ok(())
    }

    /// The spec as it stands, every update applied.
    pub fn spec(&self) -> ModuleSpec {
        self.spec.borrow().clone()
    }

    /// The collection as a signal of `{ rows, status }`.
    pub fn signal(&self) -> Signal<Value> {
        self.follow.signal()
    }

    /// The collection now, untracked.
    pub fn live(&self) -> Live {
        self.follow.live()
    }
}

/// FRAME-20: what crosses to a module when its collection moves — the
/// fold's own result by key, not the collection.
#[derive(Debug, Clone, PartialEq)]
pub enum Delta {
    /// The whole collection: the first page, a resync's snapshot, a switch
    /// to other params — or a subscriber that missed a move.
    Whole,
    /// The rows the fold inserted or replaced (each one whose value
    /// changed: an upsert equal to the row kept moves nothing), and the keys
    /// it removed (an upsert that stops matching the params is a remove).
    /// Both empty: only the status moved.
    Change { upsert: Vec<Value>, remove: Vec<String> },
}

/// FRAME-20: a move of a module's collection as a subscriber that last saw
/// move `seen` receives it — `seq` the move it now stands at.
#[derive(Debug, Clone, PartialEq)]
pub struct Crossing {
    pub seq: u64,
    pub delta: Delta,
}

impl ModuleLive {
    /// FRAME-20: how many times the collection has moved (0: never).
    pub fn seq(&self) -> u64 {
        self.follow.crossing.borrow().0
    }

    /// FRAME-20: what crosses to a subscriber that last saw move `seen`:
    /// the last move's change when it is the only one since, else (several
    /// since, or the last one whole) [`Delta::Whole`].
    pub fn since(&self, seen: u64) -> Crossing {
        let (seq, delta) = self.follow.crossing.borrow().clone();
        let delta = if seq == seen {
            status_only()
        } else if seen != 0 && seq == seen + 1 {
            delta
        } else {
            Delta::Whole
        };
        Crossing { seq, delta }
    }
}

impl<W: Wire + Clone + 'static, C: Clock + Clone + 'static> LiveCache<W, C> {
    /// FRAME-19: a module's collection, held by its `when` and its param
    /// changes coalesced by its `debounce_ms` — rhx's [`Self::follow_held`],
    /// its inputs a signal [`ModuleLive::update`] sets.
    pub fn follow_module(self: &Rc<Self>, spec: ModuleSpec) -> ModuleLive {
        let inputs = self.rt.signal(json!({ "params": spec.params, "changes_params": spec.changes_params, "when": spec.when }));
        let read = inputs.clone();
        let follow = self.follow_held(spec.query.clone(), move || {
            let v = read.get();
            (v["when"] != false).then(|| (v["params"].clone(), v["changes_params"].clone()))
        });
        ModuleLive { follow, spec: Rc::new(RefCell::new(spec)), inputs }
    }
}

/// What a [`Follow`] holds: its reader now, the binding mirroring it, the
/// params last seen and how many times they changed (a debounced run
/// checks it is still the last).
struct Following {
    reader: Option<Reader>,
    mirror: Option<crate::signals::BindingId>,
    generation: u64,
    last: Option<(Value, Value)>,
    stopped: bool,
}

/// UI-10: a collection that follows its params; dropping it stops that and
/// releases its reader.
pub struct Follow {
    signal: Signal<Value>,
    /// FRAME-20: the moves of `signal`.
    crossing: Moves,
    st: Rc<RefCell<Following>>,
    stop: Option<Box<dyn FnOnce()>>,
}

impl Follow {
    /// The collection as a signal of `{ rows, status }` — the same signal
    /// whatever the params become.
    pub fn signal(&self) -> Signal<Value> {
        self.signal.clone()
    }

    /// The collection now, untracked.
    pub fn live(&self) -> Live {
        Live::from_value(&self.signal.peek()).expect("a live collection's value")
    }

    /// FRAME-17: when the collection it reads now first answered with rows.
    pub fn answered_at(&self) -> Option<f64> {
        self.st.borrow().reader.as_ref().and_then(Reader::answered_at)
    }
}

impl Drop for Follow {
    fn drop(&mut self) {
        if let Some(stop) = self.stop.take() {
            stop();
        }
    }
}

/// One reader of a collection; dropping it releases the subscription
/// (kept [`KEEP_MS`] more).
pub struct Reader {
    signal: Signal<Value>,
    /// FRAME-20: its collection's moves.
    moved: Moves,
    answered_at: Rc<Cell<Option<f64>>>,
    release: Option<Box<dyn FnOnce()>>,
}

impl Reader {
    /// FRAME-17: when its collection's first answer with rows came (the
    /// page's clock), if it has.
    pub fn answered_at(&self) -> Option<f64> {
        self.answered_at.get()
    }

    /// The collection as a signal of `{ rows, status }` (what the tree binds).
    pub fn signal(&self) -> Signal<Value> {
        self.signal.clone()
    }

    /// The collection now, untracked.
    pub fn live(&self) -> Live {
        Live::from_value(&self.signal.peek()).expect("a live collection's value")
    }
}

impl Drop for Reader {
    fn drop(&mut self) {
        if let Some(release) = self.release.take() {
            release();
        }
    }
}

/// A `live` declaration's params resolved against the props: `{ "expr" }`
/// values evaluated (a prop by name, or a Rhai expression over the props).
pub fn resolve(params: &BTreeMap<String, Value>, props: &Map<String, Value>) -> Value {
    let mut out = Map::new();
    for (k, v) in params {
        let v = match v.as_object().and_then(|o| o.get("expr")).and_then(Value::as_str) {
            Some(e) => match props.get(e) {
                Some(p) => p.clone(),
                None => {
                    let mut scope = rhai::Scope::new();
                    for (pk, pv) in props {
                        scope.push_constant_dynamic(pk.clone(), crate::tree::expr::to_dynamic(pv));
                    }
                    crate::tree::expr::engine()
                        .eval_expression_with_scope::<rhai::Dynamic>(&mut scope, e)
                        .map(|d| crate::tree::expr::to_value(&d))
                        .unwrap_or(Value::Null)
                }
            },
            None => v.clone(),
        };
        out.insert(k.clone(), v);
    }
    Value::Object(out)
}

#[cfg(test)]
mod tests;