From f86a4836fc62937538301f00af5bd80e200a307c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 21:01:10 +0100 Subject: [PATCH 01/13] Thing 2.0 cut 7a: commands (one activate primitive, Drafts, minted invocations, result lifecycle, effects as data) thing_core::command owns invocation minting, the lifecycle (Issued, Pending, Completed, Denied, Failed, Malformed, TimedOut), result validation, timeouts and the confirm state. thing_core::input::Drafts is the one owner of uncommitted input values. Core::frame runs the step after the Binder's and returns outbound invocations and host effects; Config gains the invocation timeout and client kind; Ports gains an IdSource. Resolve refuses a capture that names no input. BoundTree::index replaces render's private index and Instance::scope_prefix is the one instance id scheme. Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/bind/mod.rs | 22 + crates/thing-core/src/bind/repeat.rs | 7 +- crates/thing-core/src/bind/scope.rs | 111 +++ crates/thing-core/src/command/capture.rs | 89 ++ crates/thing-core/src/command/lifecycle.rs | 170 ++++ crates/thing-core/src/command/mod.rs | 427 +++++++++ crates/thing-core/src/command/validate.rs | 58 ++ crates/thing-core/src/diagnostic.rs | 16 +- crates/thing-core/src/frame.rs | 108 ++- crates/thing-core/src/input/drafts.rs | 47 + crates/thing-core/src/input/mod.rs | 5 +- crates/thing-core/src/lib.rs | 1 + crates/thing-core/src/port/mod.rs | 6 + crates/thing-core/src/render/mod.rs | 35 +- crates/thing-core/src/resolve/mod.rs | 2 +- crates/thing-core/src/resolve/validate.rs | 15 +- crates/thing-core/src/time.rs | 31 + crates/thing-core/tests/command.rs | 951 +++++++++++++++++++++ crates/thing-core/tests/frame.rs | 5 +- crates/thing-testkit/src/ids.rs | 58 ++ crates/thing-testkit/src/lib.rs | 1 + crates/thing-testkit/src/mem_state.rs | 5 +- crates/thing-testkit/src/store.rs | 3 + 23 files changed, 2118 insertions(+), 55 deletions(-) create mode 100644 crates/thing-core/src/bind/scope.rs create mode 100644 crates/thing-core/src/command/capture.rs create mode 100644 crates/thing-core/src/command/lifecycle.rs create mode 100644 crates/thing-core/src/command/mod.rs create mode 100644 crates/thing-core/src/command/validate.rs create mode 100644 crates/thing-core/src/input/drafts.rs create mode 100644 crates/thing-core/tests/command.rs create mode 100644 crates/thing-testkit/src/ids.rs diff --git a/crates/thing-core/src/bind/mod.rs b/crates/thing-core/src/bind/mod.rs index 7081e45..835fb44 100644 --- a/crates/thing-core/src/bind/mod.rs +++ b/crates/thing-core/src/bind/mod.rs @@ -8,8 +8,11 @@ mod format; mod repeat; +mod scope; mod walk; +pub use scope::Located; + use std::collections::{BTreeMap, HashMap, HashSet}; use thing_contract::{AssetEntry, NodeId, SelectOption}; @@ -81,9 +84,14 @@ pub enum Bound { /// One instance of a Repeat's template: its key, and the template with derived ids, whose sites /// are in the same table. A refused item's key is `!` and its record key. +/// +/// The one id scheme is `scope_prefix`: an id inside an instance is its prefix followed by the +/// template's id, so a node in nested instances is the inner prefix, then the outer, then its declared id. #[derive(Clone, Debug, PartialEq)] pub struct Instance { pub key: String, + /// What `Instance::scope_prefix` derived for this instance: each of the template's ids is this followed by the template id. + pub prefix: String, pub root: thing_contract::Node, } @@ -344,3 +352,17 @@ impl Binder { self.surfaces.get(surface).map(|surface| &surface.bound) } } + +impl Instance { + /// The prefix of every id of the instance of `repeat` (a laid id) whose key is `key`: + /// `#:/`; an item the port refused has no key to read, so its + /// identity is its record key in the distinct form `!:/`. Resolve's + /// instance ids and command captures both derive scope here, so there is one scheme. + pub fn scope_prefix(repeat: &str, key: &str, refused: bool) -> String { + if refused { + format!("{repeat}!{}:{key}/", key.len()) + } else { + format!("{repeat}#{}:{key}/", key.len()) + } + } +} diff --git a/crates/thing-core/src/bind/repeat.rs b/crates/thing-core/src/bind/repeat.rs index 2f5da1b..16d92cc 100644 --- a/crates/thing-core/src/bind/repeat.rs +++ b/crates/thing-core/src/bind/repeat.rs @@ -159,20 +159,21 @@ impl Walker<'_> { let (key, prefix) = match &entry.item { Item::Fault(_) => { let record = entry.record_key.clone().unwrap_or_default(); - (format!("!{record}"), format!("{id}!{}:{record}/", record.len())) + let prefix = Instance::scope_prefix(id, &record, true); + (format!("!{record}"), prefix) } Item::Value(value) => { let key = key_of(value, &repeat.key_member)?; if !keys.insert(key.clone()) { return Err(fault(Code::RepeatKeyDuplicate, format!("two items of {id} share one key"))); } - let prefix = format!("{id}#{}:{key}/", key.len()); + let prefix = Instance::scope_prefix(id, &key, false); (key, prefix) } }; let mut root = (*repeat.template).clone(); rewrite(&mut root, &prefix, &inside); - built.push((Instance { key, root }, entry.item)); + built.push((Instance { key, prefix, root }, entry.item)); } let mut ids = Vec::new(); diff --git a/crates/thing-core/src/bind/scope.rs b/crates/thing-core/src/bind/scope.rs new file mode 100644 index 0000000..58d2948 --- /dev/null +++ b/crates/thing-core/src/bind/scope.rs @@ -0,0 +1,111 @@ +//! Where a node sits in a bound tree: the one id -> node index, and the Repeat instances that +//! enclose a node, which commands read to name a row and to find the inputs beside a button. + +use std::collections::HashMap; + +use thing_contract::{Node, NodeId}; + +use super::walk::{children, common}; +use super::BoundTree; +use crate::resolve::grow; + +/// A node and the Repeat instances around it, read off the tree. +#[derive(Clone, Debug, PartialEq)] +pub struct Located<'a> { + pub node: &'a Node, + /// The id the author declared: the laid id with its instance prefixes removed. + pub declared: NodeId, + /// The prefix of each enclosing instance, innermost first. An id declared at the top of the + /// document, reached from here, is these joined in order followed by it. + pub prefixes: Vec, + /// The key of each enclosing instance, outermost first. + pub items: Vec, +} + +struct Walk<'a, 'b> { + tree: &'a BoundTree, + prefixes: Vec<&'a str>, + items: Vec<&'a str>, + visit: &'b mut dyn FnMut(Located<'a>) -> bool, +} + +impl<'a> Walk<'a, '_> { + /// Visit the node, then what it holds; stops (`true`) as soon as a visit says so. + fn node(&mut self, node: &'a Node) -> bool { + grow(|| { + let Some(common) = common(node) else { return false }; + let skip: usize = self.prefixes.iter().map(|prefix| prefix.len()).sum(); + let declared = NodeId::new(common.id.as_str().get(skip..).unwrap_or(common.id.as_str())); + let located = Located { + node, + declared, + prefixes: self.prefixes.iter().rev().map(|prefix| prefix.to_string()).collect(), + items: self.items.iter().map(|item| item.to_string()).collect(), + }; + if (self.visit)(located) { + return true; + } + if let Node::Repeat(repeat) = node { + for instance in self.tree.instances(&repeat.common.id) { + self.prefixes.push(&instance.prefix); + self.items.push(&instance.key); + let stop = self.node(&instance.root); + self.prefixes.pop(); + self.items.pop(); + if stop { + return true; + } + } + return false; + } + children(node).iter().any(|child| self.node(child)) + }) + } +} + +impl BoundTree { + /// Every node of the document by laid id, Repeat instances included (ids are unique after + /// resolve). The one index render, hit-test and commands share. + pub fn index(&self) -> HashMap<&NodeId, &Node> { + let mut found = HashMap::new(); + self.walk(&mut |located| { + if let Some(common) = common(located.node) { + found.insert(&common.id, located.node); + } + false + }); + found + } + + /// The node with laid id `id`, and where it sits. + pub fn locate(&self, id: &NodeId) -> Option> { + let mut found = None; + self.walk(&mut |located| { + let hit = common(located.node).is_some_and(|common| &common.id == id); + if hit { + found = Some(located); + } + hit + }); + found + } + + /// The first node declared as `declared` inside the instances keyed `items` (outermost first). + pub fn locate_source(&self, declared: &NodeId, items: &[String]) -> Option> { + let mut found = None; + self.walk(&mut |located| { + let hit = &located.declared == declared && located.items == items; + if hit { + found = Some(located); + } + hit + }); + found + } + + fn walk<'a>(&'a self, visit: &mut dyn FnMut(Located<'a>) -> bool) { + let mut walk = Walk { tree: self, prefixes: Vec::new(), items: Vec::new(), visit }; + walk.node(&self.resolved().document().root); + } +} + diff --git a/crates/thing-core/src/command/capture.rs b/crates/thing-core/src/command/capture.rs new file mode 100644 index 0000000..3179429 --- /dev/null +++ b/crates/thing-core/src/command/capture.rs @@ -0,0 +1,89 @@ +//! Captures: the values an invocation carries, read at the user's action from the drafts over the +//! bound values. An input beside a button in a Repeat row is found by scope: the activating node's +//! innermost instance first, then outward, then the declared id itself. + +use std::collections::HashMap; + +use thing_contract::{BoolValue, CapturedInput, ChoiceValue, CommandDecl, InputKind, InputValue, Node, NodeId, NumberValue, TextValue}; + +use crate::bind::{Bound, BoundTree, Field}; +use crate::input::Drafts; + +/// What the captures of one command came to: the values to send, and the laid ids they were read +/// from (the drafts a completed result clears). +pub(super) struct Captured { + pub inputs: Vec, + pub laid: Vec, +} + +/// The laid id of `declared` as seen from a node whose enclosing instance prefixes are `scope` +/// (innermost first): the most specific one the tree holds. +pub(super) fn laid_id(index: &HashMap<&NodeId, &Node>, scope: &[String], declared: &NodeId) -> Option { + (0..=scope.len()) + .map(|start| NodeId::new(format!("{}{}", scope[start..].concat(), declared.as_str()))) + .find(|candidate| index.contains_key(candidate)) +} + +fn number(text: &str) -> Option { + text.trim().parse::().ok().filter(|value| value.is_finite()) +} + +/// The value one input sends: its draft when it has one of the right kind, else what it is bound to. +fn value(tree: &BoundTree, drafts: &Drafts, surface: &str, laid: &NodeId, node: &Node) -> Option { + let draft = drafts.get(surface, laid); + let bound = |field| tree.value(laid, field); + match node { + Node::Toggle(_) => match (draft, bound(Field::Checked)) { + (Some(InputValue::Bool(held)), _) => Some(InputValue::Bool(held.clone())), + (_, Some(Bound::Bool(checked))) => Some(InputValue::Bool(BoolValue { value: *checked })), + _ => None, + }, + Node::Slider(_) => match (draft, bound(Field::Value)) { + (Some(InputValue::Number(held)), _) => Some(InputValue::Number(held.clone())), + (_, Some(Bound::Number(at))) => Some(InputValue::Number(NumberValue { value: *at })), + _ => None, + }, + Node::Select(_) => match (draft, bound(Field::Selected)) { + (Some(InputValue::Choice(held)), _) => Some(InputValue::Choice(held.clone())), + (_, Some(Bound::Text(selected))) => Some(InputValue::Choice(ChoiceValue { value: selected.clone() })), + _ => None, + }, + Node::TextInput(input) => { + let initial = match bound(Field::Initial) { + Some(Bound::Text(text)) => Some(text.as_str()), + _ => None, + }; + match input.input_kind { + InputKind::Text => match (draft, initial) { + (Some(InputValue::Text(held)), _) => Some(InputValue::Text(held.clone())), + (_, Some(text)) => Some(InputValue::Text(TextValue { value: text.to_string() })), + _ => None, + }, + InputKind::Number => { + let typed = match draft { + Some(InputValue::Text(held)) => number(&held.value), + Some(InputValue::Number(held)) => Some(held.value).filter(|value| value.is_finite()), + _ => initial.and_then(number), + }; + typed.map(|value| InputValue::Number(NumberValue { value })) + } + } + } + _ => None, + } +} + +/// The captures of `decl`, in declared order, resolved from the scope of the activating node. The +/// error is the declared id of the first capture with no value to send. +pub(super) fn capture(tree: &BoundTree, drafts: &Drafts, surface: &str, scope: &[String], decl: &CommandDecl) -> Result { + let index = tree.index(); + let mut captured = Captured { inputs: Vec::new(), laid: Vec::new() }; + for declared in &decl.captures { + let laid = laid_id(&index, scope, declared).ok_or_else(|| declared.clone())?; + let node = index.get(&laid).ok_or_else(|| declared.clone())?; + let value = value(tree, drafts, surface, &laid, node).ok_or_else(|| declared.clone())?; + captured.inputs.push(CapturedInput { node: declared.clone(), value }); + captured.laid.push(laid); + } + Ok(captured) +} diff --git a/crates/thing-core/src/command/lifecycle.rs b/crates/thing-core/src/command/lifecycle.rs new file mode 100644 index 0000000..0733ccb --- /dev/null +++ b/crates/thing-core/src/command/lifecycle.rs @@ -0,0 +1,170 @@ +//! The invocation lifecycle: `Issued -> Pending* -> Completed | Denied | Failed`, with the core-only +//! terminal states `Malformed` and `TimedOut`. Terminal is final: a later result is a diagnostic, +//! never a state change. Core decides every transition; a provider only offers results. + +use thing_contract::{CommandResult, DatabaseEntry, Outcome}; + +use super::{Commands, HostEffect, Live, Mark, State, capture, fault, validate}; +use crate::bind::BoundTree; +use crate::diagnostic::{Code, Diagnostic}; +use crate::input::Drafts; +use crate::port::{Change, Ledger, Record, StatePort}; +use crate::time::Timestamp; + +/// What one drained change did: the effects for the host to run, and what core says about it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Answered { + pub effects: Vec, + pub diagnostics: Vec, +} + +impl Commands { + /// One drained change. Only a command result is this module's; any other address is not and + /// answers empty. A result under no held invocation is `UnknownInvocation`, logged only. + /// `trees` finds a surface's bound tree by record key. + pub fn apply<'t>( + &mut self, + change: &Change, + now: Timestamp, + trees: &dyn Fn(&str) -> Option<&'t BoundTree>, + drafts: &mut Drafts, + port: &mut dyn StatePort, + ledger: &mut Ledger, + ) -> Answered { + let mut answered = Answered::default(); + let address = match change { + Change::Upsert(entry) => &entry.address, + Change::Delete(address) => address, + Change::Refused(refusal) => &refusal.address, + }; + if address.schema.as_str() != CommandResult::SCHEMA_NAME { + return answered; + } + let Some(at) = self.live.iter().position(|live| live.interest.matches(address)) else { + if !matches!(change, Change::Delete(_)) { + answered.diagnostics.push(fault( + address.key.as_str(), + None, + Code::UnknownInvocation, + "no invocation of this id is held", + )); + } + return answered; + }; + if matches!(change, Change::Delete(_)) { + return answered; + } + let surface = self.live[at].surface.clone(); + let issuing = self.live[at].issuing.clone(); + if self.live[at].state.is_terminal() { + answered.diagnostics.push(fault(&surface, issuing.as_ref(), Code::ResultAfterTerminal, "the invocation is already terminal")); + return answered; + } + let result = match change { + Change::Upsert(entry) => match &entry.record { + // One equality catches a body naming another invocation, and a seq that is not the key's. + Record::Result(result) if result.record_key() == address.key.as_str() => result, + Record::Result(_) => { + self.malformed(at, "the result is not the one its key names", &mut answered, port, ledger); + return answered; + } + _ => { + self.malformed(at, "the record at a result address is not a result", &mut answered, port, ledger); + return answered; + } + }, + _ => { + self.malformed(at, "the result was refused at decode", &mut answered, port, ledger); + return answered; + } + }; + let seq = result.seq().get(); + if seq <= self.live[at].highest { + return answered; + } + self.live[at].highest = seq; + match result.outcome() { + Outcome::Pending(pending) => { + self.live[at].state = State::Pending(pending.message.clone()); + self.live[at].deadline = now.plus_ms(self.timeout_ms); + } + Outcome::Completed(completed) => { + let effect = match &completed.effect { + None => None, + Some(effect) => match validate::effect(effect, trees(&surface), &self.live[at]) { + Ok(effect) => Some(effect), + Err(detail) => { + self.malformed(at, &detail, &mut answered, port, ledger); + return answered; + } + }, + }; + if completed.clear_drafts { + drafts.clear(&surface, &self.live[at].laid); + } + answered.effects.extend(effect); + self.settle(at, State::Completed, None, port, ledger); + } + Outcome::Denied(denied) => { + let mut target = issuing.clone(); + if let Some(declared) = &denied.node { + let found = trees(&surface).and_then(|tree| capture::laid_id(&tree.index(), &self.live[at].scope, declared)); + match found { + Some(laid) => target = Some(laid), + None => answered.diagnostics.push(fault( + &surface, + issuing.as_ref(), + Code::MalformedResult, + "denied node not in the surface", + )), + } + } + self.settle(at, State::Denied, None, port, ledger); + if let Some(node) = target { + self.marks.insert((surface, node), Mark::Denied { reason: denied.reason.clone() }); + } + } + Outcome::Failed(failed) => { + self.settle(at, State::Failed, Some(Mark::Failed { reason: failed.reason.clone() }), port, ledger); + } + } + answered + } + + /// Move every non-terminal invocation whose deadline has come to `TimedOut`. A deadline is + /// compared with the time given: a wall clock that went backward delays a timeout, never fires one early. + pub fn tick(&mut self, now: Timestamp, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec { + let mut diagnostics = Vec::new(); + for at in 0..self.live.len() { + let live = &self.live[at]; + if !live.state.is_terminal() && live.deadline <= now { + diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::InvocationTimedOut, "no result by the deadline")); + self.settle(at, State::TimedOut, Some(Mark::TimedOut), port, ledger); + } + } + diagnostics + } + + /// The earliest deadline of an invocation still waiting; the frame's `next_wake`. + pub fn next_deadline(&self) -> Option { + self.live.iter().filter(|live| !live.state.is_terminal()).map(|live: &Live| live.deadline).min() + } + + /// A result core will not take: the invocation is `Malformed`, and nothing it carried runs. + fn malformed(&mut self, at: usize, detail: &str, answered: &mut Answered, port: &mut dyn StatePort, ledger: &mut Ledger) { + let live = &self.live[at]; + answered.diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::MalformedResult, detail)); + self.settle(at, State::Malformed, Some(Mark::Malformed), port, ledger); + } + + /// Enter a terminal state: the interest in results is released in the same call, and the + /// issuing node shows the mark. + fn settle(&mut self, at: usize, state: State, mark: Option, port: &mut dyn StatePort, ledger: &mut Ledger) { + let live = &mut self.live[at]; + live.state = state; + ledger.release(port, &live.interest); + if let (Some(mark), Some(node)) = (mark, &live.issuing) { + self.marks.insert((live.surface.clone(), node.clone()), mark); + } + } +} diff --git a/crates/thing-core/src/command/mod.rs b/crates/thing-core/src/command/mod.rs new file mode 100644 index 0000000..6431661 --- /dev/null +++ b/crates/thing-core/src/command/mod.rs @@ -0,0 +1,427 @@ +//! Commands: the one owner of invocation minting, the invocation lifecycle and result validation. +//! It follows the Resolver and Binder: it is handed what the frame drained and never drains, reads +//! no clock (time is a parameter) and awaits nothing. Core writes no record but an invocation, and +//! that leaves through `take_outbound`, never through a port. +//! +//! Every way of minting (a press, a key, a confirmed dialog, a resume after an external step) +//! ends in `mint`. A user action mints one id; nothing re-mints. + +mod capture; +mod lifecycle; +mod validate; + +use std::collections::HashMap; + +use thing_contract::{ + CapturedInput, CommandDecl, CommandId, CommandInvocation, CommandRef, CommandResult, DatabaseEntry, InputValue, Node, NodeId, + ProviderId, RecordPayload, SchemaId, Seq, Version, +}; + +use crate::bind::{Bound, BoundTree, Field}; +use crate::diagnostic::{Code, Diagnostic}; +use crate::input::Drafts; +use crate::port::{IdSource, Interest, Ledger, Prefix, StatePort}; +use crate::time::Timestamp; + +pub use lifecycle::Answered; + +/// The empty MessagePack array: a payload record with no slots. Thing Script has no payload source yet. +const EMPTY_PAYLOAD: [u8; 1] = [0x90]; + +/// What the user did to one node. +#[derive(Clone, Debug, PartialEq)] +pub struct Activation { + /// The laid id, instance ids included. + pub node: NodeId, + pub kind: ActivationKind, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ActivationKind { + /// A Button or an Overlay's dismissal. + Press, + /// A Toggle, a Slider or a Select took a value; it is written to Drafts first, then the command fires. + Change(InputValue), + /// A TextInput's submit. + Submit, +} + +/// What the host runs for a provider's result. Closed. +#[derive(Clone, Debug, PartialEq)] +pub enum HostEffect { + OpenSurface { key: String }, + OpenExternal { url: String, resume: Resume }, +} + +/// The command to run when an external step returns. The host holds it across a navigation (the +/// session dies on `location.assign`) and hands it to `Core::resume`. `source` and `items` are the +/// invocation's, so a resumed command names the same row. +#[derive(Clone, Debug, PartialEq)] +pub struct Resume { + pub surface_key: String, + pub command: CommandId, + pub source: NodeId, + pub items: Vec, +} + +/// Why a node shows a fault: the last terminal answer of an invocation issued from it, until it mints again. +#[derive(Clone, Debug, PartialEq)] +pub enum Mark { + Denied { reason: String }, + Failed { reason: String }, + Malformed, + TimedOut, +} + +/// What render and accessibility read of one node. Derived from the live invocations; nothing is +/// stored on a node. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct NodeState { + /// A non-terminal invocation was issued from this node. + pub busy: bool, + pub mark: Option, + /// The message of the latest Pending result of a busy node's invocation. + pub pending: Option, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct NodeStates { + nodes: HashMap, +} + +impl NodeStates { + /// The state of a laid node; a node nothing happened to is the default. + pub fn get(&self, node: &NodeId) -> NodeState { + self.nodes.get(node).cloned().unwrap_or_default() + } +} + +/// A command waiting for the user's yes. Its captures are the values at the user's action. +#[derive(Clone, Debug, PartialEq)] +pub struct Confirming { + pub surface: String, + pub node: NodeId, + pub command: CommandId, + pub text: String, + prepared: Prepared, +} + +impl Confirming { + pub fn captured(&self) -> &[CapturedInput] { + &self.prepared.captured + } +} + +/// Everything an invocation is except its id and its time: what a confirm holds until the user answers. +#[derive(Clone, Debug, PartialEq)] +struct Prepared { + surface: String, + provider: ProviderId, + version: Version, + command: CommandId, + payload_schema: SchemaId, + captured: Vec, + laid: Vec, + source: NodeId, + items: Vec, + /// The laid node the user acted on; a resume has none. + issuing: Option, + /// The instance prefixes around the issuing node, innermost first. + scope: Vec, +} + +/// An invocation core issued. Terminal ones stay so a late result is judged, not lost. +#[derive(Clone, Debug)] +struct Live { + surface: String, + issuing: Option, + state: State, + /// The highest result `seq` taken. + highest: i32, + deadline: Timestamp, + laid: Vec, + scope: Vec, + interest: Interest, + source: NodeId, + items: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +enum State { + Issued, + Pending(String), + Completed, + Denied, + Failed, + Malformed, + TimedOut, +} + +impl State { + fn is_terminal(&self) -> bool { + !matches!(self, State::Issued | State::Pending(_)) + } +} + +pub struct Commands { + client: String, + timeout_ms: u32, + live: Vec, + marks: HashMap<(String, NodeId), Mark>, + confirming: Option, + outbound: Vec, +} + +fn fault(surface: &str, node: Option<&NodeId>, code: Code, detail: impl Into) -> Diagnostic { + Diagnostic { code, surface: surface.to_string(), node: node.cloned(), detail: detail.into() } +} + +/// A v4 UUID from 16 bytes: the version and variant bits are core's, so a minted id is always +/// UUID-shaped and dot-free (a result key splits at its last dot). +fn uuid(ids: &mut dyn IdSource) -> String { + let mut bytes = [0u8; 16]; + ids.fill(&mut bytes); + bytes[6] = bytes[6] & 0x0f | 0x40; + bytes[8] = bytes[8] & 0x3f | 0x80; + let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); + format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32]) +} + +/// The key prefix every result of `invocation` shares, derived from the contract's one key +/// scheme: a result's key is this followed by its `seq`. +fn result_prefix(invocation: &CommandInvocation) -> String { + let key = CommandResult::pending(invocation, Seq::FIRST, "").record_key(); + key[..key.rfind('.').map_or(key.len(), |dot| dot + 1)].to_string() +} + +/// The command a node fires for an activation, when the node takes that kind of activation. +fn command_of<'a>(node: &'a Node, kind: &ActivationKind) -> Option<&'a CommandRef> { + match (node, kind) { + (Node::Button(n), ActivationKind::Press) => Some(&n.on_activate), + (Node::Overlay(n), ActivationKind::Press) => Some(&n.dismiss), + (Node::TextInput(n), ActivationKind::Submit) => Some(&n.submit), + (Node::Toggle(n), ActivationKind::Change(InputValue::Bool(_))) => Some(&n.on_change), + (Node::Slider(n), ActivationKind::Change(InputValue::Number(_))) => Some(&n.commit), + (Node::Select(n), ActivationKind::Change(InputValue::Choice(_))) => Some(&n.on_change), + _ => None, + } +} + +/// Where a command is fired from: the declared id of its source, and the instances around it. +struct Origin { + issuing: Option, + source: NodeId, + scope: Vec, + items: Vec, +} + +impl Commands { + pub fn new(client: impl Into, timeout_ms: u32) -> Self { + Self { + client: client.into(), + timeout_ms, + live: Vec::new(), + marks: HashMap::new(), + confirming: None, + outbound: Vec::new(), + } + } + + /// The one commit primitive: the user acted on `act.node` of `tree`. Every path calls it. It + /// mints one invocation, or nothing: a node that is not a command source, a disabled or busy + /// button, an input with nothing to send, or a command waiting on confirmation. + #[allow(clippy::too_many_arguments)] + pub fn activate( + &mut self, + act: Activation, + tree: &BoundTree, + drafts: &mut Drafts, + now: Timestamp, + ids: &mut dyn IdSource, + port: &mut dyn StatePort, + ledger: &mut Ledger, + ) -> Vec { + if self.confirming.is_some() { + return Vec::new(); + } + let surface = tree.resolved().document().record_key(); + let Some(located) = tree.locate(&act.node) else { return Vec::new() }; + let Some(CommandRef::Id(command)) = command_of(located.node, &act.kind) else { return Vec::new() }; + if let ActivationKind::Change(value) = &act.kind { + drafts.set(&surface, &act.node, value.clone()); + } + if matches!(located.node, Node::Button(_)) && tree.value(&act.node, Field::Enabled) == Some(&Bound::Bool(false)) { + return Vec::new(); + } + if self.busy(&surface, &act.node) { + return Vec::new(); + } + let Some(decl) = tree.resolved().document().commands.iter().find(|decl| decl.id == command.id) else { + return vec![fault(&surface, Some(&act.node), Code::UndeclaredCommand, "the command is not declared")]; + }; + let origin = Origin { + issuing: Some(act.node.clone()), + source: located.declared, + scope: located.prefixes, + items: located.items, + }; + let prepared = match self.prepare(tree, drafts, decl, origin) { + Ok(prepared) => prepared, + Err(diagnostic) => return vec![diagnostic], + }; + match &decl.confirm { + Some(text) => { + self.confirming = + Some(Confirming { surface, node: act.node, command: decl.id.clone(), text: text.clone(), prepared }); + } + None => self.mint(prepared, now, ids, port, ledger), + } + Vec::new() + } + + /// Answer the command waiting on confirmation. Accepting mints with the captures taken at the + /// user's action; rejecting drops it and draws no id. + pub fn confirm(&mut self, accept: bool, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort, ledger: &mut Ledger) { + if let Some(confirming) = self.confirming.take() + && accept + { + self.mint(confirming.prepared, now, ids, port, ledger); + } + } + + pub fn confirming(&self) -> Option<&Confirming> { + self.confirming.as_ref() + } + + /// Run the command an external step named, as the invocation that asked for it: its declared + /// captures, its source and items, no issuing node (nothing is marked busy). + #[allow(clippy::too_many_arguments)] + pub fn resume( + &mut self, + resume: &Resume, + tree: &BoundTree, + drafts: &Drafts, + now: Timestamp, + ids: &mut dyn IdSource, + port: &mut dyn StatePort, + ledger: &mut Ledger, + ) -> Vec { + let surface = tree.resolved().document().record_key(); + let decl = tree.resolved().document().commands.iter().find(|decl| decl.id == resume.command); + let (Some(decl), true) = (decl, surface == resume.surface_key) else { + return vec![fault(&surface, None, Code::UndeclaredCommand, "the command to resume is not declared at the held version")]; + }; + let scope = tree.locate_source(&resume.source, &resume.items).map(|located| located.prefixes).unwrap_or_default(); + let origin = Origin { issuing: None, source: resume.source.clone(), scope, items: resume.items.clone() }; + match self.prepare(tree, drafts, decl, origin) { + Ok(prepared) => { + self.mint(prepared, now, ids, port, ledger); + Vec::new() + } + Err(diagnostic) => vec![diagnostic], + } + } + + /// The invocations minted since the last call, in order. + pub fn take_outbound(&mut self) -> Vec { + std::mem::take(&mut self.outbound) + } + + /// What render and accessibility read for `surface`. + pub fn view(&self, surface: &str) -> NodeStates { + let mut nodes: HashMap = HashMap::new(); + for ((held, node), mark) in &self.marks { + if held == surface { + nodes.entry(node.clone()).or_default().mark = Some(mark.clone()); + } + } + for live in self.live.iter().filter(|live| live.surface == surface && !live.state.is_terminal()) { + if let Some(node) = &live.issuing { + let state = nodes.entry(node.clone()).or_default(); + state.busy = true; + if let State::Pending(message) = &live.state { + state.pending = Some(message.clone()); + } + } + } + NodeStates { nodes } + } + + /// The surface is no longer shown: its invocations leave the table with their interests, its + /// marks go and a confirmation waiting on it is dropped. + pub fn forget(&mut self, surface: &str, port: &mut dyn StatePort, ledger: &mut Ledger) { + for live in self.live.iter().filter(|live| live.surface == surface && !live.state.is_terminal()) { + ledger.release(port, &live.interest); + } + self.live.retain(|live| live.surface != surface); + self.marks.retain(|(held, _), _| held != surface); + if self.confirming.as_ref().is_some_and(|confirming| confirming.surface == surface) { + self.confirming = None; + } + } + + fn busy(&self, surface: &str, node: &NodeId) -> bool { + self.live.iter().any(|live| !live.state.is_terminal() && live.surface == surface && live.issuing.as_ref() == Some(node)) + } + + fn prepare(&self, tree: &BoundTree, drafts: &Drafts, decl: &CommandDecl, origin: Origin) -> Result { + let document = tree.resolved().document(); + let surface = document.record_key(); + let captured = capture::capture(tree, drafts, &surface, &origin.scope, decl).map_err(|node| { + fault(&surface, Some(&node), Code::CaptureUnavailable, "the captured input has no value to send") + })?; + Ok(Prepared { + surface, + provider: document.provider_id.clone(), + version: document.version, + command: decl.id.clone(), + payload_schema: decl.payload_schema.clone(), + captured: captured.inputs, + laid: captured.laid, + source: origin.source, + items: origin.items, + issuing: origin.issuing, + scope: origin.scope, + }) + } + + /// The one mint: draw one id, hold the interest in its results before the host can send, and + /// queue the invocation. + fn mint(&mut self, prepared: Prepared, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort, ledger: &mut Ledger) { + let invocation = CommandInvocation { + invocation_id: uuid(ids), + surface_key: prepared.surface.clone(), + surface_version: prepared.version, + command: prepared.command, + payload: RecordPayload { schema: prepared.payload_schema, bytes: EMPTY_PAYLOAD.to_vec() }, + captured: prepared.captured, + client: self.client.clone(), + issued_at: now.rfc3339(), + delegation: None, + source: prepared.source.clone(), + items: prepared.items.clone(), + }; + let interest = Interest::Prefix(Prefix { + provider: prepared.provider, + schema: SchemaId::new(CommandResult::SCHEMA_NAME), + key_prefix: result_prefix(&invocation), + }); + ledger.hold(port, &interest); + if let Some(node) = &prepared.issuing { + self.marks.remove(&(prepared.surface.clone(), node.clone())); + } + self.live.push(Live { + surface: prepared.surface, + issuing: prepared.issuing, + state: State::Issued, + highest: 0, + deadline: now.plus_ms(self.timeout_ms), + laid: prepared.laid, + scope: prepared.scope, + interest, + source: prepared.source, + items: prepared.items, + }); + self.outbound.push(invocation); + } +} diff --git a/crates/thing-core/src/command/validate.rs b/crates/thing-core/src/command/validate.rs new file mode 100644 index 0000000..fd6a9f7 --- /dev/null +++ b/crates/thing-core/src/command/validate.rs @@ -0,0 +1,58 @@ +//! What core will run for a provider's result: the closed effects, judged before any is emitted. +//! A provider decides what to ask; core decides whether it is allowed. + +use thing_contract::{CommandId, CommandRef, Effect}; + +use super::{HostEffect, Live, Resume}; +use crate::bind::BoundTree; + +/// Whether `url` is absolute with the scheme http or https (ASCII case-insensitive) and a host. +fn web_url(url: &str) -> bool { + if url.chars().any(|c| c.is_control() || c.is_whitespace()) { + return false; + } + let Some((scheme, rest)) = url.split_once("://") else { return false }; + (scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")) + && !rest.starts_with(['/', '?', '#']) + && !rest.is_empty() +} + +/// The effect as data for the host, or why core refuses it. `tree` is the invocation's surface as +/// held now: a resume names a command that surface declares. +pub(super) fn effect(effect: &Effect, tree: Option<&BoundTree>, live: &Live) -> Result { + match effect { + Effect::OpenSurface(open) => { + if open.key.starts_with("thing:surface:") { + Ok(HostEffect::OpenSurface { key: open.key.clone() }) + } else { + Err("OpenSurface names a key that is not a surface".into()) + } + } + Effect::OpenExternal(open) => { + if !web_url(&open.url) { + return Err("OpenExternal names a url that is not absolute http or https".into()); + } + let CommandRef::Id(resume) = &open.resume else { + return Err("OpenExternal resumes through a parameter".into()); + }; + let declared = tree.is_some_and(|tree| declares(tree, &resume.id)); + if !declared { + return Err("OpenExternal resumes a command the surface does not declare".into()); + } + Ok(HostEffect::OpenExternal { + url: open.url.clone(), + resume: Resume { + surface_key: live.surface.clone(), + command: resume.id.clone(), + source: live.source.clone(), + items: live.items.clone(), + }, + }) + } + } +} + +pub(super) fn declares(tree: &BoundTree, command: &CommandId) -> bool { + tree.resolved().document().commands.iter().any(|decl| &decl.id == command) +} + diff --git a/crates/thing-core/src/diagnostic.rs b/crates/thing-core/src/diagnostic.rs index b9925a8..5625d05 100644 --- a/crates/thing-core/src/diagnostic.rs +++ b/crates/thing-core/src/diagnostic.rs @@ -45,12 +45,26 @@ pub enum Code { OverlayAnchorMissing, /// A colour or text token the theme does not hold; it drew as the fallback colour. ThemeTokenUnknown, + /// A result that could not be taken: refused by decode, not a result, filed under another key than its + /// own, or carrying an effect core will not run. The invocation is Malformed. + MalformedResult, + /// A result under the result key space for an invocation core does not hold. + UnknownInvocation, + /// A result for an invocation already terminal; the state does not change. + ResultAfterTerminal, + /// An invocation with no result by its deadline; it is TimedOut. + InvocationTimedOut, + /// A capture whose input has no value to send (a bound error, absent, or a number that does not parse); + /// nothing was minted. + CaptureUnavailable, + /// A command capture naming no node, or a node that holds no input value. + CaptureUndeclared, } impl Code { /// Whether the fault leaves no tree (the whole document is refused) or only a placeholder. pub fn refuses_document(self) -> bool { - matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve) + matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve | Code::CaptureUndeclared) } } diff --git a/crates/thing-core/src/frame.rs b/crates/thing-core/src/frame.rs index b732cc0..2a8a42e 100644 --- a/crates/thing-core/src/frame.rs +++ b/crates/thing-core/src/frame.rs @@ -3,13 +3,16 @@ //! `StatePort::drain`; it reads no clock, sleeps nowhere and never awaits. Later cuts extend //! `frame` in place with their own step; there is no second entry. -use thing_contract::{DatabaseEntry, ProviderId, RecordKey, SchemaId, SurfaceDocument}; +use thing_contract::{CommandInvocation, DatabaseEntry, ProviderId, RecordKey, SchemaId, SurfaceDocument}; + +use std::collections::HashSet; use crate::bind::Binder; +use crate::command::{Activation, Commands, Confirming, HostEffect, NodeStates, Resume}; use crate::diagnostic::Diagnostic; -use crate::input::InputEvent; +use crate::input::{Drafts, InputEvent}; use crate::layout::{LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout}; -use crate::port::{Address, Change, Interest, Ledger, Lookup, StatePort}; +use crate::port::{Address, Change, IdSource, Interest, Ledger, Lookup, StatePort}; use crate::render::{RenderCommand, RenderInput, Rendered, ScrollOffsets, render}; use crate::resolve::{Limits, Resolver}; use crate::theme::Theme; @@ -20,11 +23,17 @@ use crate::time::Timestamp; pub struct Config { pub limits: Limits, pub metrics: Metrics, + /// How long an invocation waits for a result, and for the next one after a Pending (a heartbeat). + /// A guess, to be measured (build-spec O5). + pub invocation_timeout_ms: u32, + /// The kind of host core runs in (`renderer.web`, `renderer.tui`), written to every invocation. It + /// is never a caller identity: core has no identity to write, the transport sets it. + pub client: String, } impl Config { - pub fn new(metrics: Metrics) -> Self { - Self { limits: Limits::default(), metrics } + pub fn new(metrics: Metrics, client: impl Into) -> Self { + Self { limits: Limits::default(), metrics, invocation_timeout_ms: 15_000, client: client.into() } } } @@ -33,6 +42,7 @@ impl Config { /// on that port. pub struct Ports<'a> { pub state: &'a mut dyn StatePort, + pub ids: &'a mut dyn IdSource, } /// What the host tells core each frame. `viewport` is the one writer of size: logical px @@ -55,6 +65,10 @@ pub struct FrameOutput { /// When the host should call `frame` again with nothing else to say; `None` while nothing in /// core depends on time. pub next_wake: Option, + /// The invocations minted since the last frame, in order: core's only outbound write. + pub outbound: Vec, + /// What the host runs for the results taken this frame. + pub effects: Vec, } pub struct Core { @@ -65,6 +79,8 @@ pub struct Core { ledger: Ledger, scroll: ScrollOffsets, theme: Theme, + commands: Commands, + drafts: Drafts, /// The surface `show` named, and the one whose interest and trees are held. wanted: Option
, shown: Option
, @@ -82,6 +98,8 @@ impl Core { ledger: Ledger::new(), scroll: ScrollOffsets::default(), theme: Theme::std(), + commands: Commands::new(config.client, config.invocation_timeout_ms), + drafts: Drafts::new(), wanted: None, shown: None, last: None, @@ -95,7 +113,7 @@ impl Core { pub fn frame(&mut self, input: FrameInput, ports: Ports<'_>) -> FrameOutput { // Input routes only to owners that exist; none does yet, so events change nothing. - let FrameInput { now: _, viewport, scale, events: _ } = input; + let FrameInput { now, viewport, scale, events: _ } = input; let port = ports.state; let mut changes = Vec::new(); if self.wanted != self.shown { @@ -104,23 +122,94 @@ impl Core { changes.extend(port.drain()); let mut diagnostics = Vec::new(); + let mut effects = Vec::new(); + let mut rebound = false; for change in &changes { let intake = self.resolver.apply(change, port, &mut self.ledger); diagnostics.extend(intake.diagnostics); for (key, replaced) in intake.changed { if replaced { if let Some(tree) = self.resolver.tree(&key).cloned() { - diagnostics.extend(self.binder.bind(tree, port, &mut self.ledger).diagnostics); + let bound = self.binder.bind(tree, port, &mut self.ledger); + rebound |= !bound.dirty.is_empty(); + diagnostics.extend(bound.diagnostics); } } else { self.binder.forget(&key, port, &mut self.ledger); } } - diagnostics.extend(self.binder.apply(change, port, &mut self.ledger).diagnostics); + let applied = self.binder.apply(change, port, &mut self.ledger); + rebound |= !applied.dirty.is_empty(); + diagnostics.extend(applied.diagnostics); + let binder = &self.binder; + let answered = self.commands.apply(change, now, &|key| binder.tree(key), &mut self.drafts, port, &mut self.ledger); + diagnostics.extend(answered.diagnostics); + effects.extend(answered.effects); } + if rebound { + self.retain_drafts(); + } + diagnostics.extend(self.commands.tick(now, port, &mut self.ledger)); let commands = self.draw(viewport, scale, &mut diagnostics); - FrameOutput { commands, diagnostics, next_wake: None } + FrameOutput { + commands, + diagnostics, + next_wake: self.commands.next_deadline(), + outbound: self.commands.take_outbound(), + effects, + } + } + + /// The user acted on a node of the shown surface: the one primitive every input path ends in. A + /// host or a test calls it directly until the pointer and keyboard routes (which call it from + /// `frame`) land. The invocation it mints is in the next frame's `outbound`. + pub fn activate(&mut self, act: Activation, now: Timestamp, ports: Ports<'_>) -> Vec { + let Some(tree) = self.shown.as_ref().and_then(|shown| self.binder.tree(shown.key.as_str())) else { + return Vec::new(); + }; + self.commands.activate(act, tree, &mut self.drafts, now, ports.ids, ports.state, &mut self.ledger) + } + + /// Answer the command waiting on confirmation (`confirming`). Until the confirmation dialog + /// lands after keyboard input, a host calls this from its own test or debug path. + pub fn confirm(&mut self, accept: bool, now: Timestamp, ports: Ports<'_>) { + self.commands.confirm(accept, now, ports.ids, ports.state, &mut self.ledger); + } + + pub fn confirming(&self) -> Option<&Confirming> { + self.commands.confirming() + } + + /// Run the command an `OpenExternal` effect named, once the external step has returned. The + /// host holds the `Resume` across the navigation. + pub fn resume(&mut self, resume: &Resume, now: Timestamp, ports: Ports<'_>) -> Vec { + let Some(tree) = self.binder.tree(&resume.surface_key) else { + return Vec::new(); + }; + self.commands.resume(resume, tree, &self.drafts, now, ports.ids, ports.state, &mut self.ledger) + } + + /// The busy, pending and fault state of the shown surface's nodes, for render and accessibility. + pub fn node_states(&self) -> NodeStates { + self.shown.as_ref().map(|shown| self.commands.view(shown.key.as_str())).unwrap_or_default() + } + + /// The one table of uncommitted input values. The pointer and keyboard routes write it from + /// inside `frame`; until they land a host or a test writes here. + pub fn drafts_mut(&mut self) -> &mut Drafts { + &mut self.drafts + } + + /// Drop the drafts of nodes the shown surface no longer has. + fn retain_drafts(&mut self) { + let Some(shown) = &self.shown else { return }; + let key = shown.key.as_str(); + let live: HashSet<_> = match self.binder.tree(key) { + Some(tree) => tree.index().keys().map(|id| (*id).clone()).collect(), + None => HashSet::new(), + }; + self.drafts.retain(key, &live); } /// Leave the surface shown and take the one wanted: the interest is held before the one read, @@ -129,6 +218,7 @@ impl Core { if let Some(old) = self.shown.take() { self.resolver.forget(old.key.as_str(), port, &mut self.ledger); self.binder.forget(old.key.as_str(), port, &mut self.ledger); + self.commands.forget(old.key.as_str(), port, &mut self.ledger); self.ledger.release(port, &Interest::Record(old)); self.scroll = ScrollOffsets::default(); self.last = None; diff --git a/crates/thing-core/src/input/drafts.rs b/crates/thing-core/src/input/drafts.rs new file mode 100644 index 0000000..50f6c79 --- /dev/null +++ b/crates/thing-core/src/input/drafts.rs @@ -0,0 +1,47 @@ +//! Drafts: the one owner of every input node's uncommitted value, keyed (surface key, laid node id). +//! A value enters when the user changes an input and leaves when a result clears it or a republish +//! removes its node. Nothing else in core, and no host, keeps a second copy. + +use std::collections::{HashMap, HashSet}; + +use thing_contract::{InputValue, NodeId}; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Drafts { + values: HashMap<(String, NodeId), InputValue>, +} + +impl Drafts { + pub fn new() -> Self { + Self::default() + } + + pub fn set(&mut self, surface: &str, node: &NodeId, value: InputValue) { + self.values.insert((surface.to_string(), node.clone()), value); + } + + pub fn get(&self, surface: &str, node: &NodeId) -> Option<&InputValue> { + self.values.get(&(surface.to_string(), node.clone())) + } + + /// Drop the drafts of `nodes`; a node with no draft is untouched. + pub fn clear(&mut self, surface: &str, nodes: &[NodeId]) { + for node in nodes { + self.values.remove(&(surface.to_string(), node.clone())); + } + } + + /// Keep only the drafts of `surface` whose node is in `live` (the ids of the republished tree); + /// other surfaces' drafts stay. + pub fn retain(&mut self, surface: &str, live: &HashSet) { + self.values.retain(|(held, node), _| held != surface || live.contains(node)); + } + + pub fn len(&self) -> usize { + self.values.len() + } + + pub fn is_empty(&self) -> bool { + self.values.is_empty() + } +} diff --git a/crates/thing-core/src/input/mod.rs b/crates/thing-core/src/input/mod.rs index d4f4881..c363949 100644 --- a/crates/thing-core/src/input/mod.rs +++ b/crates/thing-core/src/input/mod.rs @@ -1,5 +1,8 @@ -//! What a host tells core about its user: the closed `InputEvent` vocabulary. +//! What a host tells core about its user: the closed `InputEvent` vocabulary, and the `Drafts` +//! table that owns what the user has typed or chosen and not yet sent. +pub mod drafts; pub mod event; +pub use drafts::Drafts; pub use event::{InputEvent, Key, Modifiers, PointerButton, WheelUnit}; diff --git a/crates/thing-core/src/lib.rs b/crates/thing-core/src/lib.rs index 08e7210..c6eaabc 100644 --- a/crates/thing-core/src/lib.rs +++ b/crates/thing-core/src/lib.rs @@ -2,6 +2,7 @@ //! through ports; it reads no clock, spawns nothing and awaits nothing. pub mod bind; +pub mod command; pub mod diagnostic; pub mod frame; pub mod input; diff --git a/crates/thing-core/src/port/mod.rs b/crates/thing-core/src/port/mod.rs index 6c9962c..5276d39 100644 --- a/crates/thing-core/src/port/mod.rs +++ b/crates/thing-core/src/port/mod.rs @@ -111,6 +111,12 @@ pub trait StatePort { fn drain(&mut self) -> Vec; } +/// Where core gets the 16 random bytes of an invocation id. Core sets the UUID version and +/// variant bits itself, so a source need only be unpredictable; a test source is a script or a counter. +pub trait IdSource { + fn fill(&mut self, bytes: &mut [u8; 16]); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/thing-core/src/render/mod.rs b/crates/thing-core/src/render/mod.rs index 847e57b..d9e411c 100644 --- a/crates/thing-core/src/render/mod.rs +++ b/crates/thing-core/src/render/mod.rs @@ -20,7 +20,6 @@ pub use scroll::{ScrollOffsets, clamp}; use crate::bind::{Bound, BoundTree, Field}; use crate::diagnostic::{Code, Diagnostic}; use crate::layout::{ControlForm, LaidControl, LaidNode, LaidTree, MAX_DEVICE, Measure, Metrics, Rect}; -use crate::resolve::grow; use crate::theme::{Theme, fallback}; /// What a frame is drawn with. `viewport` is what layout was given (logical px or cells). @@ -52,8 +51,7 @@ pub struct Rendered { } pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut dyn Measure) -> Rendered { - let mut nodes = HashMap::new(); - index(tree, &tree.resolved().document().root, &mut nodes); + let nodes = tree.index(); let k = match input.metrics { Metrics::Pixels if input.scale.is_finite() && input.scale > 0.0 => input.scale, _ => 1.0, @@ -84,37 +82,6 @@ pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut painter.out } -/// Every node of the document by id, Repeat instances included (ids are unique after resolve). -fn index<'a>(tree: &'a BoundTree, node: &'a Node, out: &mut HashMap<&'a NodeId, &'a Node>) { - grow(|| { - let (id, children): (&NodeId, &[Node]) = match node { - Node::Box(n) => (&n.common.id, &n.children), - Node::Button(n) => (&n.common.id, &n.content), - Node::Overlay(n) => (&n.common.id, &n.children), - Node::Repeat(n) => { - for instance in tree.instances(&n.common.id) { - index(tree, &instance.root, out); - } - (&n.common.id, &[]) - } - Node::Text(n) => (&n.common.id, &[]), - Node::Image(n) => (&n.common.id, &[]), - Node::Toggle(n) => (&n.common.id, &[]), - Node::Slider(n) => (&n.common.id, &[]), - Node::TextInput(n) => (&n.common.id, &[]), - Node::Select(n) => (&n.common.id, &[]), - Node::Plot(n) => (&n.common.id, &[]), - Node::Embed(n) => (&n.common.id, &[]), - Node::Use(n) => (&n.common.id, &[]), - Node::Slot(_) => return, - }; - out.insert(id, node); - for child in children { - index(tree, child, out); - } - }) -} - struct Painter<'a> { tree: &'a BoundTree, laid: &'a LaidTree, diff --git a/crates/thing-core/src/resolve/mod.rs b/crates/thing-core/src/resolve/mod.rs index 4c0ac3d..5844f5f 100644 --- a/crates/thing-core/src/resolve/mod.rs +++ b/crates/thing-core/src/resolve/mod.rs @@ -93,7 +93,7 @@ pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits key(a).cmp(&key(b)) }); let tree = root.and_then(|root| { - diagnostics.extend(validate::check(&root, limits, &document.record_key())); + diagnostics.extend(validate::check(&root, &document.commands, limits, &document.record_key())); let refused = diagnostics.iter().any(|diagnostic| diagnostic.code.refuses_document()); // Field by field: `..document.clone()` would clone the whole input tree to discard it. (!refused).then(|| ResolvedTree { diff --git a/crates/thing-core/src/resolve/validate.rs b/crates/thing-core/src/resolve/validate.rs index 4244e42..0078b0a 100644 --- a/crates/thing-core/src/resolve/validate.rs +++ b/crates/thing-core/src/resolve/validate.rs @@ -4,7 +4,7 @@ use std::collections::HashSet; -use thing_contract::{Node, NodeId}; +use thing_contract::{CommandDecl, Node, NodeId}; use super::Limits; use crate::diagnostic::{Code, Diagnostic}; @@ -44,8 +44,8 @@ pub(super) fn size(node: &Node) -> usize { super::grow(|| 1 + children(node).iter().map(size).sum::()) } -/// Faults of the finished tree, in pre-order: duplicate ids, then depth. A tree deeper than the limit is not walked further. -pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec { +/// Faults of the finished tree, in pre-order: duplicate ids, then depth, then each command capture that is not an input node. A tree deeper than the limit is not walked further. +pub(super) fn check(root: &Node, commands: &[CommandDecl], limits: &Limits, surface: &str) -> Vec { let mut found = Vec::new(); let fault = |code, node: Option<&NodeId>, detail: String| Diagnostic { code, @@ -54,6 +54,7 @@ pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec = HashSet::new(); + let mut inputs: HashSet<&NodeId> = HashSet::new(); let mut too_deep = false; let mut stack = vec![(root, 1usize)]; while let Some((node, depth)) = stack.pop() { @@ -62,6 +63,9 @@ pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec Vec Timestamp { + Timestamp(self.0.saturating_add(i64::from(ms))) + } + + /// RFC 3339 in UTC to whole seconds (an instant inside a second is floored), as + /// `2026-01-01T00:00:00Z`. The civil date comes from days since 1970-01-01 by Hinnant's + /// `civil_from_days`, valid for every date this type holds in the proleptic Gregorian calendar. + pub fn rfc3339(self) -> String { + let seconds = self.0.div_euclid(1000); + let days = seconds.div_euclid(86_400); + let in_day = seconds.rem_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let day_of_era = z.rem_euclid(146_097); + let year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let shifted_month = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * shifted_month + 2) / 5 + 1; + let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 }; + let year = year_of_era + era * 400 + i64::from(month <= 2); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", + in_day / 3600, + in_day % 3600 / 60, + in_day % 60 + ) + } +} diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs new file mode 100644 index 0000000..b1b4503 --- /dev/null +++ b/crates/thing-core/tests/command.rs @@ -0,0 +1,951 @@ +//! Commands: one activation mints one invocation, results are judged by core alone, and every +//! transition of the lifecycle is a row here. Time is a parameter and ordering is forced: a test +//! that depends on two results arriving in one drain queues both before the drain. + +use thing_contract::*; +use thing_core::bind::{Binder, Instance}; +use thing_core::command::{Activation, ActivationKind, Answered, Commands, HostEffect, Mark, Resume}; +use thing_core::diagnostic::{Code, Diagnostic}; +use thing_core::input::Drafts; +use thing_core::port::{Address, Change, Entry, IdSource, Interest, Ledger, Prefix, Record, Refusal, StatePort}; +use thing_core::resolve::{Limits, resolve}; +use thing_core::time::Timestamp; +use thing_core::{Config, Core, FrameInput, Ports}; +use thing_testkit::build::*; +use thing_testkit::fixture::Fixture; +use thing_testkit::ids::{ScriptedIds, SeqIds}; +use thing_testkit::measure::FixedMeasure; +use thing_testkit::mem_state::MemState; +use thing_testkit::state::{self, Item, Settings}; +use thing_testkit::store::{PINNED_CLOCK, PINNED_NOW}; + +const PROVIDER: &str = "provider.cmd"; +const FEED: &str = "provider.feed"; + +fn at(ms: i64) -> Timestamp { + Timestamp(PINNED_NOW.0 + ms) +} + +// ----- surfaces ----- + +fn decl(id: &str, captures: &[&str], confirm: Option<&str>) -> CommandDecl { + CommandDecl { + id: CommandId::new(id), + payload_schema: SchemaId::new(format!("gamecult.thing.test.{id}.v1")), + captures: captures.iter().map(|node| nid(node)).collect(), + confirm: confirm.map(Into::into), + } +} + +fn button(id: &str, cmd: &str) -> Node { + Node::Button(ButtonNode { common: common(id), content: vec![], on_activate: command(cmd), enabled: lit_bool(true) }) +} + +fn toggle(id: &str, cmd: &str, checked: BoolSource) -> Node { + Node::Toggle(ToggleNode { common: common(id), checked, on_change: command(cmd) }) +} + +fn input(id: &str, kind: InputKind, initial: &str, cmd: &str) -> Node { + Node::TextInput(TextInputNode { + common: common(id), + multiline: false, + input_kind: kind, + placeholder: lit_text(""), + initial: lit_text(initial), + submit: command(cmd), + }) +} + +fn surface(provider: &str, root: Node, commands: Vec) -> SurfaceDocument { + SurfaceDocument { provider_id: ProviderId::new(provider), label: seg("main"), version: ver(1), title: "t".into(), root, commands } +} + +fn go_surface() -> SurfaceDocument { + surface( + PROVIDER, + boxed("root", vec![input("name", InputKind::Text, "", "go"), button("go", "go"), button("other", "go"), button("after", "after")]), + vec![decl("go", &["name"], None), decl("after", &[], None)], + ) +} + +/// A Repeat of the feed's items; each row has a note and a button whose command captures the row's +/// note and the one global toggle outside the Repeat. +fn rows_surface() -> SurfaceDocument { + let row = Node::Box(BoxNode { + common: common("row"), + style: style(), + paint: plain_paint(), + role: Role::ListItem, + children: vec![input("note", InputKind::Text, "n", "save-row"), button("save", "save-row")], + }); + let rows = Node::Repeat(RepeatNode { + common: common("rows"), + collection: CollectionSource::Records(RecordsSource { + provider: Some(ProviderId::new(FEED)), + schema: SchemaId::new("gamecult.thing.test.item.v1"), + key_prefix: "item-".into(), + }), + key_member: path(&["Id"]), + template: std::boxed::Box::new(row), + }); + surface( + PROVIDER, + boxed("root", vec![toggle("global", "save-row", lit_bool(true)), rows]), + vec![decl("save-row", &["note", "global"], None), decl("after", &["note"], None)], + ) +} + +fn rows_state() -> MemState { + let mut state = MemState::new(); + for n in 1..=3 { + let id = format!("item-{n:04}"); + state.put_state(&ProviderId::new(FEED), &id, &Item { id: id.clone(), title: id.clone() }); + } + state +} + +fn row(item: &str, node: &str) -> NodeId { + NodeId::new(format!("{}{node}", Instance::scope_prefix("rows", item, false))) +} + +// ----- the rig: the stages composed by hand, as Core::frame composes them ----- + +struct Rig { + state: MemState, + ledger: Ledger, + binder: Binder, + commands: Commands, + drafts: Drafts, + ids: SeqIds, + surface: String, + provider: ProviderId, +} + +impl Rig { + fn new(mut state: MemState, document: &SurfaceDocument) -> Self { + state.put(&document.provider_id, document); + let tree = resolve(document, &state, &Limits::default()).tree.expect("resolves"); + let mut ledger = Ledger::new(); + let mut binder = Binder::new(Limits::default()); + binder.bind(tree, &mut state, &mut ledger); + Self { + state, + ledger, + binder, + commands: Commands::new("renderer.web", 15_000), + drafts: Drafts::new(), + ids: SeqIds::new(), + surface: document.record_key(), + provider: document.provider_id.clone(), + } + } + + fn act(&mut self, node: &NodeId, kind: ActivationKind, now: Timestamp, ids: &mut dyn IdSource) -> Vec { + let tree = self.binder.tree(&self.surface).expect("bound"); + let act = Activation { node: node.clone(), kind }; + self.commands.activate(act, tree, &mut self.drafts, now, ids, &mut self.state, &mut self.ledger) + } + + fn press(&mut self, node: &str, now: Timestamp, ids: &mut dyn IdSource) -> Vec { + self.act(&nid(node), ActivationKind::Press, now, ids) + } + + fn mint(&mut self, node: &str, now: Timestamp) -> CommandInvocation { + let mut ids = std::mem::take(&mut self.ids); + self.press(node, now, &mut ids); + self.ids = ids; + self.commands.take_outbound().pop().expect("minted") + } + + fn set_draft(&mut self, node: &NodeId, value: InputValue) { + self.drafts.set(&self.surface, node, value); + } + + fn draft(&self, node: &NodeId) -> Option { + self.drafts.get(&self.surface, node).cloned() + } + + /// Put the result in the port and drain it: it arrives only if core holds the interest. + fn feed(&mut self, result: &CommandResult, now: Timestamp) -> Answered { + self.state.put(&self.provider, result); + self.drain(now) + } + + fn drain(&mut self, now: Timestamp) -> Answered { + let mut answered = Answered::default(); + for change in self.state.drain() { + let one = self.apply(&change, now); + answered.effects.extend(one.effects); + answered.diagnostics.extend(one.diagnostics); + } + answered + } + + fn apply(&mut self, change: &Change, now: Timestamp) -> Answered { + let binder = &self.binder; + self.commands.apply(change, now, &|key| binder.tree(key), &mut self.drafts, &mut self.state, &mut self.ledger) + } + + fn feed_direct(&mut self, result: &CommandResult, now: Timestamp) -> Answered { + let address = self.result_address(&result.record_key()); + let change = Change::Upsert(Entry { address, record: Record::Result(result.clone()) }); + self.apply(&change, now) + } + + fn result_address(&self, key: &str) -> Address { + Address { provider: self.provider.clone(), schema: SchemaId::new(CommandResult::SCHEMA_NAME), key: RecordKey::new(key) } + } + + fn tick(&mut self, now: Timestamp) -> Vec { + self.commands.tick(now, &mut self.state, &mut self.ledger) + } + + fn readers(&self, invocation: &CommandInvocation) -> usize { + let prefix = CommandResult::pending(invocation, seq(1), "").record_key(); + let prefix = prefix[..prefix.len() - 1].to_string(); + let interest = Interest::Prefix(Prefix { + provider: self.provider.clone(), + schema: SchemaId::new(CommandResult::SCHEMA_NAME), + key_prefix: prefix, + }); + self.ledger.readers(&interest) + } + + fn state_of(&self, node: &str) -> thing_core::command::NodeState { + self.commands.view(&self.surface).get(&nid(node)) + } +} + +fn codes(diagnostics: &[Diagnostic]) -> Vec { + diagnostics.iter().map(|diagnostic| diagnostic.code).collect() +} + +fn text_value(value: &str) -> InputValue { + InputValue::Text(TextValue { value: value.into() }) +} + +fn completed(invocation: &CommandInvocation, n: i32, clear: bool, effect: Option) -> CommandResult { + CommandResult::completed(invocation, seq(n), None, clear, effect) +} + +/// A source of one fixed run of bytes. +struct Bytes([u8; 16]); + +impl IdSource for Bytes { + fn fill(&mut self, bytes: &mut [u8; 16]) { + *bytes = self.0; + } +} + +// ----- ids and time ----- + +#[test] +fn a_minted_id_is_v4_shaped_for_any_bytes() { + for bytes in [[0u8; 16], [0xff; 16], std::array::from_fn(|i| i as u8), std::array::from_fn(|i| (i * 37 + 11) as u8)] { + let mut rig = Rig::new(MemState::new(), &go_surface()); + rig.press("go", PINNED_NOW, &mut Bytes(bytes)); + let id = rig.commands.take_outbound().pop().unwrap().invocation_id; + let chars: Vec = id.chars().collect(); + assert_eq!(chars.len(), 36, "{id}"); + for dash in [8, 13, 18, 23] { + assert_eq!(chars[dash], '-', "{id}"); + } + assert_eq!(chars[14], '4', "{id}"); + assert!(matches!(chars[19], '8' | '9' | 'a' | 'b'), "{id}"); + assert!(chars.iter().enumerate().all(|(i, c)| [8, 13, 18, 23].contains(&i) || (c.is_ascii_hexdigit() && !c.is_ascii_uppercase())), "{id}"); + assert!(!id.contains('.')); + } +} + +#[test] +fn rfc3339_formats_whole_seconds_in_utc() { + assert_eq!(PINNED_NOW.rfc3339(), PINNED_CLOCK); + assert_eq!(Timestamp(0).rfc3339(), "1970-01-01T00:00:00Z"); + // A leap day, a century that is not a leap year, a leap century. + assert_eq!(Timestamp(1_709_210_096_000).rfc3339(), "2024-02-29T12:34:56Z"); + assert_eq!(Timestamp(951_782_400_000).rfc3339(), "2000-02-29T00:00:00Z"); + assert_eq!(Timestamp(4_107_542_400_000).rfc3339(), "2100-03-01T00:00:00Z"); + // Before 1970 the second is floored, never rounded toward zero. + assert_eq!(Timestamp(-1000).rfc3339(), "1969-12-31T23:59:59Z"); + assert_eq!(Timestamp(-1).rfc3339(), "1969-12-31T23:59:59Z"); + assert_eq!(Timestamp(999).rfc3339(), "1970-01-01T00:00:00Z"); + assert_eq!(Timestamp(-62_135_596_800_000).rfc3339(), "0001-01-01T00:00:00Z"); +} + +// ----- drafts ----- + +#[test] +fn drafts_are_per_surface_and_clear_or_retain_exactly_what_is_named() { + let mut drafts = Drafts::new(); + for node in ["a", "b", "c"] { + drafts.set("s1", &nid(node), text_value(node)); + } + drafts.set("s2", &nid("a"), text_value("other")); + drafts.clear("s1", &[nid("a"), nid("missing")]); + assert_eq!(drafts.get("s1", &nid("a")), None); + assert_eq!(drafts.get("s1", &nid("b")), Some(&text_value("b"))); + assert_eq!(drafts.get("s2", &nid("a")), Some(&text_value("other"))); + drafts.retain("s1", &[nid("c")].into_iter().collect()); + assert_eq!(drafts.get("s1", &nid("b")), None); + assert_eq!(drafts.get("s1", &nid("c")), Some(&text_value("c"))); + assert_eq!(drafts.get("s2", &nid("a")), Some(&text_value("other"))); + assert_eq!(drafts.len(), 2); +} + +// ----- smokes: the fixtures' invocations are the expected output ----- + +#[test] +fn f02_login_mints_the_fixture_invocation_and_runs_its_effect() { + let set = Fixture::F02LoginEffect.load(); + let login = set.surfaces[0].clone(); + let expected = set.invocations[0].clone(); + let mut rig = Rig::new(MemState::from_fixture(Fixture::F02LoginEffect), &login); + rig.set_draft(&nid("username"), text_value("ada")); + let mut ids = ScriptedIds::new([expected.invocation_id.as_str()]); + + assert!(rig.press("sign-in-button", PINNED_NOW, &mut ids).is_empty()); + let minted = rig.commands.take_outbound(); + assert_eq!(minted, vec![expected.clone()]); + assert_eq!(minted[0].payload.bytes, vec![0x90]); + assert_eq!(rig.readers(&expected), 1); + assert!(rig.state_of("sign-in-button").busy); + + // A second press while the first is waiting mints nothing and draws no id. + let mut spare = ScriptedIds::new(["00000000-0000-4000-8000-000000000000"]); + rig.press("sign-in-button", at(1), &mut spare); + assert!(rig.commands.take_outbound().is_empty()); + assert_eq!(spare.remaining(), 1); + + let answered = rig.feed(&set.results[0], at(10_000)); + assert!(answered.diagnostics.is_empty() && answered.effects.is_empty()); + let state = rig.state_of("sign-in-button"); + assert!(state.busy); + assert_eq!(state.pending.as_deref(), Some("waiting for the identity provider")); + // The heartbeat renewed the deadline from the time of the Pending, not of the mint. + assert_eq!(rig.commands.next_deadline(), Some(at(25_000))); + + let answered = rig.feed(&set.results[1], at(11_000)); + assert!(answered.diagnostics.is_empty()); + assert_eq!( + answered.effects, + vec![HostEffect::OpenExternal { + url: "https://login.example.test/authorize".into(), + resume: Resume { + surface_key: login.record_key(), + command: CommandId::new("login-resume"), + source: nid("sign-in-button"), + items: vec![], + }, + }] + ); + assert_eq!(rig.readers(&expected), 0); + assert!(!rig.state_of("sign-in-button").busy); + assert_eq!(rig.commands.next_deadline(), None); +} + +fn settings_state(enabled: bool) -> MemState { + let mut state = MemState::new(); + state.put_state(&ProviderId::new("provider.settings"), "current", &Settings { enabled, volume: 0.75, theme: "dark".into() }); + state +} + +#[test] +fn f04_form_captures_in_declared_order_and_clears_exactly_those_drafts() { + let set = Fixture::F04Form.load(); + let form = set.surfaces[0].clone(); + let expected = set.invocations[0].clone(); + let mut rig = Rig::new(settings_state(false), &form); + let mut ids = ScriptedIds::new([expected.invocation_id.as_str()]); + + rig.act(&nid("enabled"), ActivationKind::Change(InputValue::Bool(BoolValue { value: true })), PINNED_NOW, &mut ids); + assert_eq!(rig.commands.take_outbound(), vec![expected.clone()]); + // The change was written to Drafts before the command fired. + assert_eq!(rig.draft(&nid("enabled")), Some(InputValue::Bool(BoolValue { value: true }))); + for (node, value) in [ + ("volume", InputValue::Number(NumberValue { value: 0.75 })), + ("theme", InputValue::Choice(ChoiceValue { value: "dark".into() })), + ("port", text_value("8080")), + ] { + rig.set_draft(&nid(node), value); + } + rig.set_draft(&nid("root"), text_value("not captured")); + + rig.feed(&set.results[0], at(1)); + for node in ["enabled", "volume", "theme", "port"] { + assert_eq!(rig.draft(&nid(node)), None, "{node}"); + } + assert_eq!(rig.draft(&nid("root")), Some(text_value("not captured"))); +} + +#[test] +fn clear_drafts_false_clears_none() { + let set = Fixture::F04Form.load(); + let mut rig = Rig::new(settings_state(false), &set.surfaces[0]); + let invocation = rig.mint_change_enabled(); + rig.set_draft(&nid("volume"), InputValue::Number(NumberValue { value: 0.5 })); + rig.feed(&completed(&invocation, 1, false, None), at(1)); + assert!(rig.draft(&nid("enabled")).is_some() && rig.draft(&nid("volume")).is_some()); +} + +impl Rig { + fn mint_change_enabled(&mut self) -> CommandInvocation { + self.act(&nid("enabled"), ActivationKind::Change(InputValue::Bool(BoolValue { value: true })), PINNED_NOW, &mut SeqIds::new()); + self.commands.take_outbound().pop().expect("minted") + } +} + +// ----- gates ----- + +#[test] +fn nothing_mints_for_a_mismatch_a_disabled_button_or_a_double_press() { + let mut disabled = go_surface(); + let Node::Box(root) = &mut disabled.root else { unreachable!() }; + root.children.push(Node::Button(ButtonNode { common: common("off"), content: vec![], on_activate: command("go"), enabled: lit_bool(false) })); + root.children.push(toggle("flag", "go", lit_bool(false))); + let mut rig = Rig::new(MemState::new(), &disabled); + let mut ids = SeqIds::new(); + + rig.press("off", PINNED_NOW, &mut ids); + // A kind the node does not take, a value of the wrong kind, an unknown node: caller bugs that mint + // nothing and write no draft. + rig.act(&nid("go"), ActivationKind::Submit, PINNED_NOW, &mut ids); + rig.act(&nid("flag"), ActivationKind::Press, PINNED_NOW, &mut ids); + rig.act(&nid("flag"), ActivationKind::Change(text_value("x")), PINNED_NOW, &mut ids); + rig.press("no-such-node", PINNED_NOW, &mut ids); + assert!(rig.commands.take_outbound().is_empty()); + assert_eq!(rig.draft(&nid("flag")), None); + + // One press mints; the same button is busy; a different button of the same command is not. + rig.press("go", PINNED_NOW, &mut ids); + rig.press("go", at(5), &mut ids); + assert_eq!(rig.commands.take_outbound().len(), 1); + rig.press("other", at(6), &mut ids); + assert_eq!(rig.commands.take_outbound().len(), 1); +} + +#[test] +fn a_button_is_free_again_once_its_invocation_is_terminal() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let first = rig.mint("go", PINNED_NOW); + assert!(rig.state_of("go").busy); + rig.feed(&CommandResult::failed(&first, seq(1), "no"), at(1)); + assert!(!rig.state_of("go").busy); + assert_eq!(rig.state_of("go").mark, Some(Mark::Failed { reason: "no".into() })); + // Minting again clears the mark. + let mut ids = ScriptedIds::new(["11111111-1111-4111-8111-111111111111"]); + rig.press("go", at(2), &mut ids); + assert_eq!(rig.commands.take_outbound().len(), 1); + assert_eq!(rig.state_of("go").mark, None); +} + +// ----- confirm ----- + +#[test] +fn confirm_holds_the_activation_time_captures_and_a_reject_draws_no_id() { + let mut document = go_surface(); + document.commands[0] = decl("go", &["name"], Some("Send it?")); + let mut rig = Rig::new(MemState::new(), &document); + let mut ids = ScriptedIds::new(["22222222-2222-4222-8222-222222222222"]); + rig.set_draft(&nid("name"), text_value("first")); + + rig.press("go", PINNED_NOW, &mut ids); + assert!(rig.commands.take_outbound().is_empty()); + let confirming = rig.commands.confirming().expect("waiting").clone(); + assert_eq!(confirming.text, "Send it?"); + assert_eq!(confirming.node, nid("go")); + assert_eq!(confirming.captured()[0].value, text_value("first")); + + // The draft moves on and a second activation arrives: neither changes what is confirmed or mints. + rig.set_draft(&nid("name"), text_value("second")); + rig.press("other", at(1), &mut ids); + assert_eq!(rig.commands.confirming(), Some(&confirming)); + + rig.commands.confirm(false, at(2), &mut ids, &mut rig.state, &mut rig.ledger); + assert!(rig.commands.confirming().is_none() && rig.commands.take_outbound().is_empty()); + assert_eq!(ids.remaining(), 1); + + rig.press("go", at(3), &mut ids); + rig.set_draft(&nid("name"), text_value("third")); + rig.commands.confirm(true, at(4), &mut ids, &mut rig.state, &mut rig.ledger); + let minted = rig.commands.take_outbound(); + assert_eq!(minted.len(), 1); + assert_eq!(minted[0].captured[0].value, text_value("second")); + assert_eq!(minted[0].issued_at, at(4).rfc3339()); + assert_eq!(ids.remaining(), 0); + // With nothing waiting, confirming again does nothing. + rig.commands.confirm(true, at(5), &mut ids, &mut rig.state, &mut rig.ledger); + assert!(rig.commands.take_outbound().is_empty()); +} + +#[test] +fn f01_restart_waits_for_confirmation() { + let set = Fixture::F01SwarmDashboard.load(); + let mut state = MemState::from_fixture(Fixture::F01SwarmDashboard); + state::script(Fixture::F01SwarmDashboard, &mut state); + let mut rig = Rig::new(state, &set.surfaces[0]); + rig.press("restart", PINNED_NOW, &mut SeqIds::new()); + assert!(rig.commands.take_outbound().is_empty()); + assert_eq!(rig.commands.confirming().unwrap().text, "Restart the swarm?"); +} + +// ----- the lifecycle table ----- + +#[test] +fn a_result_after_terminal_is_a_diagnostic_and_changes_nothing() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + // Both results are queued before either is delivered: the second arrives after the first was + // terminal, whatever order the host's frames fall in. + rig.state.put(&rig.provider.clone(), &completed(&invocation, 1, false, None)); + rig.state.put(&rig.provider.clone(), &CommandResult::pending(&invocation, seq(2), "late")); + let answered = rig.drain(at(1)); + assert_eq!(codes(&answered.diagnostics), vec![Code::ResultAfterTerminal]); + assert!(!rig.state_of("go").busy); + assert_eq!(rig.state_of("go").pending, None); + assert_eq!(rig.readers(&invocation), 0); + + // Failed then Completed likewise. + let second = rig.mint("other", at(2)); + rig.state.put(&rig.provider.clone(), &CommandResult::failed(&second, seq(1), "x")); + rig.state.put(&rig.provider.clone(), &completed(&second, 2, true, None)); + assert_eq!(codes(&rig.drain(at(3)).diagnostics), vec![Code::ResultAfterTerminal]); + assert_eq!(rig.state_of("other").mark, Some(Mark::Failed { reason: "x".into() })); +} + +#[test] +fn a_regressed_seq_is_ignored_silently() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + rig.feed(&CommandResult::pending(&invocation, seq(2), "newer"), at(1)); + let answered = rig.feed(&CommandResult::pending(&invocation, seq(1), "older"), at(5_000)); + assert_eq!(answered, Answered::default()); + assert_eq!(rig.state_of("go").pending.as_deref(), Some("newer")); + // Not renewed by the stale one. + assert_eq!(rig.commands.next_deadline(), Some(at(15_001))); + // The same seq again is a re-delivery. + assert_eq!(rig.feed_direct(&CommandResult::pending(&invocation, seq(2), "newer"), at(6_000)), Answered::default()); +} + +#[test] +fn a_result_that_is_not_what_its_key_says_is_malformed() { + let cases: Vec<(&str, Box Change>)> = vec![ + // A body naming another invocation at this invocation's key. + ("another invocation's body", Box::new(|rig, mine| { + let theirs = CommandResult::pending(&stranger(), seq(1), "x"); + Change::Upsert(Entry { address: rig.result_address(&CommandResult::pending(mine, seq(1), "").record_key()), record: Record::Result(theirs) }) + })), + // A seq that is not the key's. + ("another seq", Box::new(|rig, mine| { + let body = CommandResult::pending(mine, seq(1), "x"); + Change::Upsert(Entry { address: rig.result_address(&CommandResult::pending(mine, seq(2), "").record_key()), record: Record::Result(body) }) + })), + ("a record that is not a result", Box::new(|rig, mine| { + let address = rig.result_address(&CommandResult::pending(mine, seq(1), "").record_key()); + Change::Upsert(Entry { address, record: Record::Surface(go_surface()) }) + })), + ("refused at decode", Box::new(|rig, mine| { + let address = rig.result_address(&CommandResult::pending(mine, seq(1), "").record_key()); + Change::Refused(Refusal { kind: SchemaId::new(CommandResult::SCHEMA_NAME), address, detail: "extra field".into() }) + })), + ]; + for (name, make) in cases { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + let change = make(&mut rig, &invocation); + let answered = rig.apply(&change, at(1)); + assert_eq!(codes(&answered.diagnostics), vec![Code::MalformedResult], "{name}"); + assert_eq!(answered.effects, vec![], "{name}"); + assert_eq!(rig.state_of("go").mark, Some(Mark::Malformed), "{name}"); + assert!(!rig.state_of("go").busy, "{name}"); + assert_eq!(rig.readers(&invocation), 0, "{name}"); + // Malformed is final. + let late = rig.feed_direct(&completed(&invocation, 3, false, None), at(2)); + assert_eq!(codes(&late.diagnostics), vec![Code::ResultAfterTerminal], "{name}"); + } +} + +#[test] +fn a_delete_is_ignored_and_an_unknown_invocation_is_logged() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + let address = rig.result_address(&CommandResult::pending(&invocation, seq(1), "").record_key()); + assert_eq!(rig.apply(&Change::Delete(address), at(1)), Answered::default()); + assert!(rig.state_of("go").busy); + + let mut stranger = invocation.clone(); + stranger.invocation_id = "44444444-4444-4444-8444-444444444444".into(); + let answered = rig.feed_direct(&CommandResult::pending(&stranger, seq(1), "x"), at(2)); + assert_eq!(codes(&answered.diagnostics), vec![Code::UnknownInvocation]); + assert!(rig.state_of("go").busy); + // An address that is not a command result is not this module's. + let elsewhere = Address { provider: rig.provider.clone(), schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME), key: RecordKey::new("x") }; + assert_eq!(rig.apply(&Change::Delete(elsewhere), at(3)), Answered::default()); +} + +// ----- timeouts ----- + +#[test] +fn an_invocation_times_out_at_exactly_issued_plus_the_timeout() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + assert_eq!(rig.commands.next_deadline(), Some(at(15_000))); + assert!(rig.tick(at(14_999)).is_empty()); + assert!(rig.state_of("go").busy); + let fired = rig.tick(at(15_000)); + assert_eq!(codes(&fired), vec![Code::InvocationTimedOut]); + assert_eq!(fired[0].node, Some(nid("go"))); + assert_eq!(rig.state_of("go").mark, Some(Mark::TimedOut)); + assert!(!rig.state_of("go").busy); + assert_eq!(rig.readers(&invocation), 0); + assert_eq!(rig.commands.next_deadline(), None); + assert!(rig.tick(at(99_000)).is_empty()); + // A result after the timeout is judged, not taken. + let late = rig.feed_direct(&completed(&invocation, 1, false, None), at(16_000)); + assert_eq!(codes(&late.diagnostics), vec![Code::ResultAfterTerminal]); + assert_eq!(rig.state_of("go").mark, Some(Mark::TimedOut)); +} + +#[test] +fn a_pending_result_renews_the_deadline_and_the_earliest_deadline_wins() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let first = rig.mint("go", PINNED_NOW); + let _second = rig.mint("other", at(5_000)); + assert_eq!(rig.commands.next_deadline(), Some(at(15_000))); + rig.feed(&CommandResult::pending(&first, seq(1), "working"), at(10_000)); + // The first moved to +25 000; the second, at +20 000, is now the earliest. + assert_eq!(rig.commands.next_deadline(), Some(at(20_000))); + assert!(rig.tick(at(19_999)).is_empty()); + let fired = rig.tick(at(20_000)); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].node, Some(nid("other"))); + assert!(rig.state_of("go").busy); + assert_eq!(rig.commands.next_deadline(), Some(at(25_000))); + // A clock that went backward fires nothing early. + assert!(rig.tick(at(1)).is_empty()); +} + +// ----- effects ----- + +fn effect_outcome(effect: Effect) -> (Rig, CommandInvocation, Answered) { + let mut rig = Rig::new(MemState::new(), &go_surface()); + rig.set_draft(&nid("name"), text_value("keep me")); + let invocation = rig.mint("go", PINNED_NOW); + let answered = rig.feed(&completed(&invocation, 1, true, Some(effect)), at(1)); + (rig, invocation, answered) +} + +fn open_external(url: &str, resume: CommandRef) -> Effect { + Effect::OpenExternal(OpenExternalEffect { url: url.into(), resume }) +} + +#[test] +fn an_effect_core_will_not_run_makes_the_result_malformed_and_clears_nothing() { + let refused = [ + open_external("javascript:alert(1)", command("after")), + open_external("data:text/html,x", command("after")), + open_external("/relative/path", command("after")), + open_external("file:///etc/passwd", command("after")), + open_external("https://", command("after")), + open_external("https://ok.test/\nx", command("after")), + open_external("https://ok.test/", CommandRef::Param(param("p"))), + open_external("https://ok.test/", command("undeclared")), + Effect::OpenSurface(OpenSurfaceEffect { key: "thing:asset_catalog:x.y".into() }), + Effect::OpenSurface(OpenSurfaceEffect { key: "javascript:1".into() }), + ]; + for effect in refused { + let (rig, invocation, answered) = effect_outcome(effect.clone()); + assert_eq!(codes(&answered.diagnostics), vec![Code::MalformedResult], "{effect:?}"); + assert_eq!(answered.effects, vec![], "{effect:?}"); + assert_eq!(rig.draft(&nid("name")), Some(text_value("keep me")), "{effect:?}"); + assert_eq!(rig.state_of("go").mark, Some(Mark::Malformed), "{effect:?}"); + assert_eq!(rig.readers(&invocation), 0); + } +} + +#[test] +fn a_valid_effect_is_emitted_once_with_the_invocations_source_and_items() { + let (rig, _, answered) = effect_outcome(open_external("HTTPS://Example.test/a?b=c", command("after"))); + assert!(answered.diagnostics.is_empty()); + assert_eq!(answered.effects.len(), 1); + let HostEffect::OpenExternal { url, resume } = &answered.effects[0] else { panic!("{:?}", answered.effects) }; + assert_eq!(url, "HTTPS://Example.test/a?b=c"); + assert_eq!((resume.command.as_str(), resume.source.as_str(), resume.items.len()), ("after", "go", 0)); + // clear_drafts cleared the captured draft. + assert_eq!(rig.draft(&nid("name")), None); + + let (_, _, answered) = effect_outcome(Effect::OpenSurface(OpenSurfaceEffect { key: "thing:surface:provider.x.main".into() })); + assert_eq!(answered.effects, vec![HostEffect::OpenSurface { key: "thing:surface:provider.x.main".into() }]); +} + +#[test] +fn a_resume_mints_the_declared_command_for_the_same_row_and_only_when_declared() { + let mut rig = Rig::new(rows_state(), &rows_surface()); + rig.set_draft(&row("item-0002", "note"), text_value("two")); + rig.set_draft(&row("item-0001", "note"), text_value("one")); + let mut ids = SeqIds::new(); + let resume = Resume { + surface_key: rig.surface.clone(), + command: CommandId::new("after"), + source: nid("save"), + items: vec!["item-0002".into()], + }; + let tree = rig.binder.tree(&rig.surface.clone()).unwrap(); + let diagnostics = rig.commands.resume(&resume, tree, &rig.drafts, PINNED_NOW, &mut ids, &mut rig.state, &mut rig.ledger); + assert!(diagnostics.is_empty()); + let minted = rig.commands.take_outbound(); + assert_eq!(minted.len(), 1); + assert_eq!((minted[0].source.as_str(), minted[0].items.clone()), ("save", vec!["item-0002".to_string()])); + assert_eq!(minted[0].captured[0].value, text_value("two")); + // No issuing node, so nothing is busy. + assert!(!rig.state_of(row("item-0002", "save").as_str()).busy); + + let undeclared = Resume { command: CommandId::new("gone"), ..resume.clone() }; + let tree = rig.binder.tree(&rig.surface.clone()).unwrap(); + let diagnostics = rig.commands.resume(&undeclared, tree, &rig.drafts, PINNED_NOW, &mut ids, &mut rig.state, &mut rig.ledger); + assert_eq!(codes(&diagnostics), vec![Code::UndeclaredCommand]); + assert!(rig.commands.take_outbound().is_empty()); +} + +// ----- captures ----- + +#[test] +fn a_button_in_a_row_captures_its_own_rows_input_and_names_its_row() { + let mut rig = Rig::new(rows_state(), &rows_surface()); + rig.set_draft(&row("item-0001", "note"), text_value("one")); + rig.set_draft(&row("item-0002", "note"), text_value("two")); + rig.set_draft(&nid("global"), InputValue::Bool(BoolValue { value: false })); + let mut ids = SeqIds::new(); + rig.act(&row("item-0002", "save"), ActivationKind::Press, PINNED_NOW, &mut ids); + let minted = rig.commands.take_outbound().pop().unwrap(); + // The declared ids, the row's value for the row's input, the top-level one for the id outside any row. + assert_eq!( + minted.captured, + vec![ + CapturedInput { node: nid("note"), value: text_value("two") }, + CapturedInput { node: nid("global"), value: InputValue::Bool(BoolValue { value: false }) }, + ] + ); + assert_eq!((minted.source.clone(), minted.items.clone()), (nid("save"), vec!["item-0002".to_string()])); + // A row with no draft sends what its input is bound to. + rig.act(&row("item-0003", "save"), ActivationKind::Press, PINNED_NOW, &mut ids); + let third = rig.commands.take_outbound().pop().unwrap(); + assert_eq!(third.captured[0].value, text_value("n")); + assert_eq!(third.items, vec!["item-0003".to_string()]); + assert_eq!(third.captured[1].value, InputValue::Bool(BoolValue { value: false })); + // Completed clears the row's draft and no other row's. + let answered = rig.feed(&completed(&minted, 1, true, None), at(1)); + assert!(answered.diagnostics.is_empty()); + assert_eq!(rig.draft(&row("item-0002", "note")), None); + assert_eq!(rig.draft(&row("item-0001", "note")), Some(text_value("one"))); +} + +#[test] +fn a_capture_with_nothing_to_send_mints_nothing() { + let settings_ref = |member: &str| Bind { + source: StateSource::Record(StateRef { + provider: Some(ProviderId::new("provider.settings")), + schema: SchemaId::new("gamecult.thing.test.settings.v1"), + key: RecordKey::new("current"), + }), + member: path(&[member]), + format: None, + }; + let broken: [(&str, Node); 4] = [ + ("a bound error", toggle("c", "go", BoolSource::Bound(settings_ref("Nope")))), + ("an absent record", toggle("c", "go", BoolSource::Bound(record_bind(path(&["Enabled"]), None)))), + ("an unparseable number", input("c", InputKind::Number, "abc", "go")), + ("a number that is not finite", input("c", InputKind::Number, "NaN", "go")), + ]; + for (name, node) in broken { + let document = surface(PROVIDER, boxed("root", vec![node, button("go", "go")]), vec![decl("go", &["c"], None)]); + let mut rig = Rig::new(settings_state(true), &document); + let diagnostics = rig.press("go", PINNED_NOW, &mut SeqIds::new()); + assert_eq!(codes(&diagnostics), vec![Code::CaptureUnavailable], "{name}"); + assert_eq!(diagnostics[0].node, Some(nid("c")), "{name}"); + assert!(rig.commands.take_outbound().is_empty(), "{name}"); + assert!(!rig.state_of("go").busy, "{name}"); + } + // A Number input reads its Text draft; one that does not parse is the same fault. + let document = surface(PROVIDER, boxed("root", vec![input("n", InputKind::Number, "1", "go"), button("go", "go")]), vec![decl("go", &["n"], None)]); + let mut rig = Rig::new(MemState::new(), &document); + rig.set_draft(&nid("n"), text_value("12x")); + assert_eq!(codes(&rig.press("go", PINNED_NOW, &mut SeqIds::new())), vec![Code::CaptureUnavailable]); + rig.set_draft(&nid("n"), text_value(" 12.5 ")); + rig.press("go", PINNED_NOW, &mut SeqIds::new()); + assert_eq!(rig.commands.take_outbound()[0].captured[0].value, InputValue::Number(NumberValue { value: 12.5 })); +} + +#[test] +fn a_capture_naming_no_input_refuses_the_document() { + for (name, commands) in [ + ("a missing id", vec![decl("go", &["nowhere"], None)]), + ("a node that holds no input", vec![decl("go", &["label"], None)]), + ] { + let document = surface(PROVIDER, boxed("root", vec![text("label", "hi"), button("go", "go")]), commands); + let resolution = resolve(&document, &MemState::new(), &Limits::default()); + assert!(resolution.tree.is_none(), "{name}"); + let faults: Vec<_> = resolution.diagnostics.iter().filter(|d| d.code == Code::CaptureUndeclared).collect(); + assert_eq!(faults.len(), 1, "{name}"); + assert!(Code::CaptureUndeclared.refuses_document()); + } + // A template's ids count, so the rows surface resolves. + assert!(resolve(&rows_surface(), &rows_state(), &Limits::default()).tree.is_some()); +} + +// ----- denied ----- + +fn denied_surface() -> SurfaceDocument { + surface( + PROVIDER, + boxed("root", vec![button("go", "go"), input("field", InputKind::Text, "", "go")]), + vec![decl("go", &[], None)], + ) +} + +#[test] +fn denied_marks_the_named_node_only_and_the_issuing_node_when_none_or_unknown() { + // Some(node): that node is marked, the issuing one is not. + let mut rig = Rig::new(MemState::new(), &denied_surface()); + let invocation = rig.mint("go", PINNED_NOW); + let answered = rig.feed(&CommandResult::denied(&invocation, seq(1), "no", Some(nid("field"))), at(1)); + assert!(answered.diagnostics.is_empty()); + assert_eq!(rig.state_of("field").mark, Some(Mark::Denied { reason: "no".into() })); + assert_eq!(rig.state_of("go").mark, None); + assert!(!rig.state_of("go").busy); + + // None: the issuing node. + let mut rig = Rig::new(MemState::new(), &denied_surface()); + let invocation = rig.mint("go", PINNED_NOW); + rig.feed(&CommandResult::denied(&invocation, seq(1), "nope", None), at(1)); + assert_eq!(rig.state_of("go").mark, Some(Mark::Denied { reason: "nope".into() })); + assert_eq!(rig.state_of("field").mark, None); + + // A node the surface does not have: the issuing node, and a diagnostic. + let mut rig = Rig::new(MemState::new(), &denied_surface()); + let invocation = rig.mint("go", PINNED_NOW); + let answered = rig.feed(&CommandResult::denied(&invocation, seq(1), "huh", Some(nid("ghost"))), at(1)); + assert_eq!(codes(&answered.diagnostics), vec![Code::MalformedResult]); + assert_eq!(answered.diagnostics[0].detail, "denied node not in the surface"); + assert_eq!(rig.state_of("go").mark, Some(Mark::Denied { reason: "huh".into() })); + assert_eq!(rig.state_of("ghost").mark, None); +} + +#[test] +fn denied_in_a_row_marks_that_rows_node() { + let mut rig = Rig::new(rows_state(), &rows_surface()); + rig.act(&row("item-0003", "save"), ActivationKind::Press, PINNED_NOW, &mut SeqIds::new()); + let invocation = rig.commands.take_outbound().pop().unwrap(); + rig.feed(&CommandResult::denied(&invocation, seq(1), "bad note", Some(nid("note"))), at(1)); + assert_eq!(rig.state_of(row("item-0003", "note").as_str()).mark, Some(Mark::Denied { reason: "bad note".into() })); + assert_eq!(rig.state_of(row("item-0001", "note").as_str()).mark, None); +} + +// ----- the frame ----- + +fn core() -> Core { + Core::new(Config::new(thing_core::layout::Metrics::Cells, "renderer.web"), Box::new(FixedMeasure::cells())) +} + +fn frame_at(core: &mut Core, state: &mut MemState, now: Timestamp) -> thing_core::FrameOutput { + let input = FrameInput { now, viewport: (80.0, 24.0), scale: 1.0, events: vec![] }; + core.frame(input, Ports { state, ids: &mut SeqIds::new() }) +} + +#[test] +fn f02_through_the_frame() { + let set = Fixture::F02LoginEffect.load(); + let login = set.surfaces[0].clone(); + let expected = set.invocations[0].clone(); + let mut state = MemState::from_fixture(Fixture::F02LoginEffect); + let mut core = core(); + core.show(login.provider_id.clone(), RecordKey::new(login.record_key())); + let first = frame_at(&mut core, &mut state, PINNED_NOW); + assert!(first.outbound.is_empty() && first.effects.is_empty() && first.next_wake.is_none()); + + core.drafts_mut().set(&login.record_key(), &nid("username"), text_value("ada")); + let mut ids = ScriptedIds::new([expected.invocation_id.as_str()]); + let act = Activation { node: nid("sign-in-button"), kind: ActivationKind::Press }; + assert!(core.activate(act, PINNED_NOW, Ports { state: &mut state, ids: &mut ids }).is_empty()); + + let minted = frame_at(&mut core, &mut state, at(1)); + assert_eq!(minted.outbound, vec![expected.clone()]); + assert_eq!(minted.next_wake, Some(at(15_000))); + assert!(core.node_states().get(&nid("sign-in-button")).busy); + // The invocation left once. + assert!(frame_at(&mut core, &mut state, at(2)).outbound.is_empty()); + + // The results reach Commands::apply through the frame's drain; Pending renews the deadline. + state.put(&login.provider_id, &set.results[0]); + let pending = frame_at(&mut core, &mut state, at(1_000)); + assert_eq!(pending.next_wake, Some(at(16_000))); + assert!(pending.effects.is_empty()); + state.put(&login.provider_id, &set.results[1]); + let done = frame_at(&mut core, &mut state, at(2_000)); + assert_eq!(done.effects.len(), 1); + assert_eq!(done.next_wake, None); + assert!(!core.node_states().get(&nid("sign-in-button")).busy); + + // The host runs the effect, the session survives or not, and the resume comes back through Core. + let HostEffect::OpenExternal { resume, .. } = &done.effects[0] else { panic!() }; + let mut ids = ScriptedIds::new(["55555555-5555-4555-8555-555555555555"]); + assert!(core.resume(resume, at(3_000), Ports { state: &mut state, ids: &mut ids }).is_empty()); + let resumed = frame_at(&mut core, &mut state, at(3_001)); + assert_eq!(resumed.outbound.len(), 1); + assert_eq!(resumed.outbound[0].command, CommandId::new("login-resume")); + assert_eq!(resumed.outbound[0].source, nid("sign-in-button")); +} + +#[test] +fn the_frame_fires_a_timeout_once_and_leaving_the_surface_forgets_its_invocations() { + let set = Fixture::F02LoginEffect.load(); + let login = set.surfaces[0].clone(); + let mut state = MemState::from_fixture(Fixture::F02LoginEffect); + let mut core = core(); + core.show(login.provider_id.clone(), RecordKey::new(login.record_key())); + frame_at(&mut core, &mut state, PINNED_NOW); + core.drafts_mut().set(&login.record_key(), &nid("username"), text_value("ada")); + let act = Activation { node: nid("sign-in-button"), kind: ActivationKind::Press }; + core.activate(act, PINNED_NOW, Ports { state: &mut state, ids: &mut SeqIds::new() }); + frame_at(&mut core, &mut state, at(1)); + + assert!(frame_at(&mut core, &mut state, at(14_999)).diagnostics.is_empty()); + let late = frame_at(&mut core, &mut state, at(15_000)); + assert_eq!(codes(&late.diagnostics), vec![Code::InvocationTimedOut]); + assert_eq!(late.next_wake, None); + assert_eq!(core.node_states().get(&nid("sign-in-button")).mark, Some(Mark::TimedOut)); + assert!(frame_at(&mut core, &mut state, at(16_000)).diagnostics.is_empty()); + + // Showing nothing forgets the surface's marks. + core.show(login.provider_id.clone(), RecordKey::new("thing:surface:provider.login.none")); + frame_at(&mut core, &mut state, at(17_000)); + core.show(login.provider_id.clone(), RecordKey::new(login.record_key())); + frame_at(&mut core, &mut state, at(18_000)); + assert_eq!(core.node_states().get(&nid("sign-in-button")).mark, None); +} + +#[test] +fn a_republish_drops_the_drafts_of_the_nodes_it_removed() { + let provider = ProviderId::new(PROVIDER); + let two_inputs = surface(PROVIDER, boxed("root", vec![input("a", InputKind::Text, "", "go"), input("b", InputKind::Text, "", "go")]), vec![decl("go", &[], None)]); + let mut one_input = surface(PROVIDER, boxed("root", vec![input("a", InputKind::Text, "", "go")]), vec![decl("go", &[], None)]); + one_input.version = ver(2); + let mut state = MemState::new(); + state.put(&provider, &two_inputs); + let mut core = core(); + core.show(provider.clone(), RecordKey::new(two_inputs.record_key())); + frame_at(&mut core, &mut state, PINNED_NOW); + let key = two_inputs.record_key(); + core.drafts_mut().set(&key, &nid("a"), text_value("kept")); + core.drafts_mut().set(&key, &nid("b"), text_value("gone")); + state.put(&provider, &one_input); + frame_at(&mut core, &mut state, at(1)); + assert_eq!(core.drafts_mut().get(&key, &nid("a")), Some(&text_value("kept"))); + assert_eq!(core.drafts_mut().get(&key, &nid("b")), None); +} + +/// An invocation core never issued. +fn stranger() -> CommandInvocation { + let mut invocation = invocation(); + invocation.invocation_id = "33333333-3333-4333-8333-333333333333".into(); + invocation +} diff --git a/crates/thing-core/tests/frame.rs b/crates/thing-core/tests/frame.rs index 573c78d..c35559b 100644 --- a/crates/thing-core/tests/frame.rs +++ b/crates/thing-core/tests/frame.rs @@ -14,6 +14,7 @@ use thing_core::time::Timestamp; use thing_core::{Config, Core, FrameInput, FrameOutput, Ports}; use thing_testkit::build::*; use thing_testkit::fixture::Fixture; +use thing_testkit::ids::SeqIds; use thing_testkit::measure::FixedMeasure; use thing_testkit::mem_state::{Call, MemState}; use thing_testkit::state::{self, Swarm}; @@ -28,7 +29,7 @@ fn measure(metrics: Metrics) -> FixedMeasure { } fn fresh(metrics: Metrics) -> Core { - Core::new(Config::new(metrics), Box::new(measure(metrics))) + Core::new(Config::new(metrics, "renderer.test"), Box::new(measure(metrics))) } fn input(viewport: (f32, f32), scale: f32) -> FrameInput { @@ -36,7 +37,7 @@ fn input(viewport: (f32, f32), scale: f32) -> FrameInput { } fn run(core: &mut Core, state: &mut MemState, input: FrameInput) -> FrameOutput { - core.frame(input, Ports { state }) + core.frame(input, Ports { state, ids: &mut SeqIds::new() }) } fn show(core: &mut Core, document: &SurfaceDocument) { diff --git a/crates/thing-testkit/src/ids.rs b/crates/thing-testkit/src/ids.rs new file mode 100644 index 0000000..be63c1b --- /dev/null +++ b/crates/thing-testkit/src/ids.rs @@ -0,0 +1,58 @@ +//! Id sources for tests: a script of the UUIDs a fixture holds, and a counter. + +use thing_core::port::IdSource; + +/// Gives the UUIDs it was built with, in order, as the 16 bytes they spell. A fixture id is +/// already v4, so core's version and variant bits leave it as it was. Panics when exhausted. +#[derive(Debug)] +pub struct ScriptedIds { + left: std::vec::IntoIter<[u8; 16]>, +} + +impl ScriptedIds { + pub fn new>(uuids: impl IntoIterator) -> Self { + let decoded: Vec<[u8; 16]> = uuids + .into_iter() + .map(|uuid| { + let digits: Vec = uuid.as_ref().bytes().filter(|byte| *byte != b'-').collect(); + assert_eq!(digits.len(), 32, "{} is not a UUID", uuid.as_ref()); + let mut bytes = [0u8; 16]; + for (byte, pair) in bytes.iter_mut().zip(digits.chunks(2)) { + *byte = u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).expect("hex digits"); + } + bytes + }) + .collect(); + Self { left: decoded.into_iter() } + } + + /// How many ids have not been drawn. + pub fn remaining(&self) -> usize { + self.left.len() + } +} + +impl IdSource for ScriptedIds { + fn fill(&mut self, bytes: &mut [u8; 16]) { + *bytes = self.left.next().expect("ScriptedIds ran out of ids"); + } +} + +/// Counts: the first id spells 1, the next 2. +#[derive(Debug, Default)] +pub struct SeqIds { + next: u128, +} + +impl SeqIds { + pub fn new() -> Self { + Self::default() + } +} + +impl IdSource for SeqIds { + fn fill(&mut self, bytes: &mut [u8; 16]) { + self.next += 1; + *bytes = self.next.to_be_bytes(); + } +} diff --git a/crates/thing-testkit/src/lib.rs b/crates/thing-testkit/src/lib.rs index dc4511d..b4601b3 100644 --- a/crates/thing-testkit/src/lib.rs +++ b/crates/thing-testkit/src/lib.rs @@ -4,6 +4,7 @@ pub mod build; pub mod fixture; pub mod golden; +pub mod ids; pub mod measure; pub mod mem_state; pub mod state; diff --git a/crates/thing-testkit/src/mem_state.rs b/crates/thing-testkit/src/mem_state.rs index 2d254ba..39e603f 100644 --- a/crates/thing-testkit/src/mem_state.rs +++ b/crates/thing-testkit/src/mem_state.rs @@ -146,7 +146,10 @@ impl MemState { } } - /// A state holding every document of a fixture, each under the provider that publishes it. + /// A state holding every document of a fixture, each under the provider that publishes it. Invocations + /// and results are skipped: they are timeline data, not initial state. A test takes them from + /// `Fixture::load` and puts each result with `put` at its scripted step, after core minted its + /// invocation, and compares that invocation with the fixture's (the fixture is the expected output). pub fn from_fixture(fixture: crate::fixture::Fixture) -> Self { let set = fixture.load(); let mut state = Self::new(); diff --git a/crates/thing-testkit/src/store.rs b/crates/thing-testkit/src/store.rs index 919a24b..005d499 100644 --- a/crates/thing-testkit/src/store.rs +++ b/crates/thing-testkit/src/store.rs @@ -8,6 +8,9 @@ use thing_contract::ThingContract; pub const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z"; +/// `PINNED_CLOCK` as core is told time: Unix milliseconds. +pub const PINNED_NOW: thing_core::time::Timestamp = thing_core::time::Timestamp(1_767_225_600_000); + /// A cache with the contract registered and no backing store. pub fn memory() -> CultCache { let mut cache = CultCache::new(); -- 2.47.3 From bf7534859bbb9e8aaffd3ba596f48d6def0185c2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 22:00:56 +0100 Subject: [PATCH 02/13] Thing 2.0 cut 7a: tests for each command source kind and the wrong-key result Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/tests/command.rs | 56 ++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs index b1b4503..6b2addc 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -949,3 +949,59 @@ fn stranger() -> CommandInvocation { invocation.invocation_id = "33333333-3333-4333-8333-333333333333".into(); invocation } + +#[test] +fn every_command_source_kind_fires_its_command_and_captures_its_own_draft_kind() { + let slider = Node::Slider(SliderNode { common: common("vol"), min: 0.0, max: 1.0, step: 0.1, value: lit_number(0.2), commit: command("go") }); + let select = Node::Select(SelectNode { + common: common("pick"), + options: OptionList::Literal(LiteralOptions { options: vec![SelectOption { value: "a".into(), label: "A".into() }] }), + value: record_bind(path(&["Theme"]), None), + on_change: command("go"), + }); + let overlay = Node::Overlay(OverlayNode { + common: common("dialog"), + anchor: Anchor::Viewport, + modal: true, + dismiss: command("go"), + children: vec![], + }); + let number = input("num", InputKind::Number, "1", "go"); + let document = surface( + PROVIDER, + boxed("root", vec![slider, select, overlay, number, input("txt", InputKind::Text, "t", "go")]), + vec![decl("go", &["vol", "pick", "num"], None)], + ); + let mut rig = Rig::new(MemState::new(), &document); + // Drafts of each kind are what the captures send. + rig.set_draft(&nid("vol"), InputValue::Number(NumberValue { value: 0.9 })); + rig.set_draft(&nid("pick"), InputValue::Choice(ChoiceValue { value: "a".into() })); + rig.set_draft(&nid("num"), InputValue::Number(NumberValue { value: 7.0 })); + let mut ids = SeqIds::new(); + rig.act(&nid("dialog"), ActivationKind::Press, PINNED_NOW, &mut ids); + rig.act(&nid("txt"), ActivationKind::Submit, PINNED_NOW, &mut ids); + let minted = rig.commands.take_outbound(); + assert_eq!(minted.len(), 2); + assert_eq!(minted[0].source, nid("dialog")); + assert_eq!(minted[0].captured[0].value, InputValue::Number(NumberValue { value: 0.9 })); + assert_eq!(minted[0].captured[1].value, InputValue::Choice(ChoiceValue { value: "a".into() })); + assert_eq!(minted[0].captured[2].value, InputValue::Number(NumberValue { value: 7.0 })); + assert_eq!(minted[1].source, nid("txt")); + rig.act(&nid("vol"), ActivationKind::Change(InputValue::Number(NumberValue { value: 0.4 })), PINNED_NOW, &mut ids); + rig.act(&nid("pick"), ActivationKind::Change(InputValue::Choice(ChoiceValue { value: "a".into() })), PINNED_NOW, &mut ids); + let changed = rig.commands.take_outbound(); + assert_eq!(changed.len(), 2); + assert_eq!(changed[0].source, nid("vol")); + assert_eq!(changed[0].captured[0].value, InputValue::Number(NumberValue { value: 0.4 })); + assert_eq!(changed[1].source, nid("pick")); +} + +#[test] +fn a_result_filed_under_the_wrong_key_says_so() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let mine = rig.mint("go", PINNED_NOW); + let body = CommandResult::pending(&mine, seq(1), "x"); + let address = rig.result_address(&CommandResult::pending(&mine, seq(2), "").record_key()); + let answered = rig.apply(&Change::Upsert(Entry { address, record: Record::Result(body) }), at(1)); + assert_eq!(answered.diagnostics[0].detail, "the result is not the one its key names"); +} -- 2.47.3 From e920c6f766a52a0f4622929fc7b65ae53573dbd7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 22:57:41 +0100 Subject: [PATCH 03/13] Thing 2.0 cut 7a: tests that kill the surviving mutants (forget, locate_source, id sources, frame confirm and row removal) Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/tests/command.rs | 109 +++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs index 6b2addc..d046d3e 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -1005,3 +1005,112 @@ fn a_result_filed_under_the_wrong_key_says_so() { let answered = rig.apply(&Change::Upsert(Entry { address, record: Record::Result(body) }), at(1)); assert_eq!(answered.diagnostics[0].detail, "the result is not the one its key names"); } + +#[test] +fn forgetting_a_surface_releases_its_waiting_invocations_and_only_its_own() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let done = rig.mint("go", PINNED_NOW); + rig.feed(&completed(&done, 1, false, None), at(1)); + let waiting = rig.mint("other", at(2)); + let failed = rig.mint("after", at(3)); + rig.feed(&CommandResult::failed(&failed, seq(1), "x"), at(4)); + let mut document = go_surface(); + document.commands[0] = decl("go", &["name"], Some("ok?")); + // Another surface's forget touches nothing here. + rig.commands.forget("thing:surface:provider.else.main", &mut rig.state, &mut rig.ledger); + assert!(rig.state_of("other").busy); + assert_eq!(rig.readers(&waiting), 1); + assert_eq!(rig.state_of("after").mark, Some(Mark::Failed { reason: "x".into() })); + rig.commands.forget(&rig.surface.clone(), &mut rig.state, &mut rig.ledger); + assert!(!rig.state_of("other").busy); + assert_eq!(rig.state_of("after").mark, None); + assert_eq!(rig.readers(&waiting), 0); + assert_eq!(rig.readers(&done), 0); + assert_eq!(rig.commands.next_deadline(), None); +} + +#[test] +fn forgetting_drops_a_confirmation_of_that_surface_only() { + let mut document = go_surface(); + document.commands[0] = decl("go", &["name"], Some("ok?")); + let mut rig = Rig::new(MemState::new(), &document); + rig.press("go", PINNED_NOW, &mut SeqIds::new()); + rig.commands.forget("thing:surface:provider.else.main", &mut rig.state, &mut rig.ledger); + assert!(rig.commands.confirming().is_some()); + rig.commands.forget(&rig.surface.clone(), &mut rig.state, &mut rig.ledger); + assert!(rig.commands.confirming().is_none()); +} + +#[test] +fn locate_source_finds_the_node_declared_in_the_named_row() { + let rig = Rig::new(rows_state(), &rows_surface()); + let tree = rig.binder.tree(&rig.surface).unwrap(); + let found = tree.locate_source(&nid("save"), &["item-0002".to_string()]).expect("found"); + assert_eq!(found.declared, nid("save")); + assert_eq!(found.items, vec!["item-0002".to_string()]); + assert!(tree.locate_source(&nid("save"), &["item-9999".to_string()]).is_none()); + assert!(tree.locate_source(&nid("nothing"), &["item-0002".to_string()]).is_none()); + assert_eq!(tree.locate(&row("item-0001", "note")).unwrap().declared, nid("note")); +} + +#[test] +fn the_id_sources_give_what_they_say() { + let mut scripted = ScriptedIds::new(["6d1c0f52-7a0e-4b53-8f3d-2a9e4c7b1d10", "0b7e44aa-31c9-4e0d-a6f2-95d8c3e1b277"]); + assert_eq!(scripted.remaining(), 2); + let mut bytes = [0u8; 16]; + scripted.fill(&mut bytes); + assert_eq!(bytes[0], 0x6d); + assert_eq!(bytes[15], 0x10); + assert_eq!(scripted.remaining(), 1); + let mut counted = SeqIds::new(); + let mut seen = Vec::new(); + for _ in 0..3 { + counted.fill(&mut bytes); + seen.push(u128::from_be_bytes(bytes)); + } + assert_eq!(seen, vec![1, 2, 3]); + let mut drafts = Drafts::new(); + assert!(drafts.is_empty()); + drafts.set("s", &nid("a"), text_value("x")); + assert!(!drafts.is_empty()); +} + +#[test] +fn removing_a_row_through_the_frame_drops_its_draft() { + let provider = ProviderId::new(PROVIDER); + let document = rows_surface(); + let mut state = rows_state(); + state.put(&provider, &document); + let mut core = core(); + core.show(provider.clone(), RecordKey::new(document.record_key())); + frame_at(&mut core, &mut state, PINNED_NOW); + let key = document.record_key(); + core.drafts_mut().set(&key, &row("item-0001", "note"), text_value("stays")); + core.drafts_mut().set(&key, &row("item-0003", "note"), text_value("goes")); + state.delete(&Address { provider: ProviderId::new(FEED), schema: SchemaId::new("gamecult.thing.test.item.v1"), key: RecordKey::new("item-0003") }); + frame_at(&mut core, &mut state, at(1)); + assert_eq!(core.drafts_mut().get(&key, &row("item-0001", "note")), Some(&text_value("stays"))); + assert_eq!(core.drafts_mut().get(&key, &row("item-0003", "note")), None); +} + +#[test] +fn a_confirmation_is_answered_through_the_core() { + let provider = ProviderId::new(PROVIDER); + let mut document = go_surface(); + document.commands[0] = decl("go", &["name"], Some("ok?")); + let mut state = MemState::new(); + state.put(&provider, &document); + let mut core = core(); + core.show(provider, RecordKey::new(document.record_key())); + frame_at(&mut core, &mut state, PINNED_NOW); + let mut ids = SeqIds::new(); + let press = || Activation { node: nid("go"), kind: ActivationKind::Press }; + core.activate(press(), PINNED_NOW, Ports { state: &mut state, ids: &mut ids }); + assert_eq!(core.confirming().map(|c| c.text.as_str()), Some("ok?")); + core.confirm(false, at(1), Ports { state: &mut state, ids: &mut ids }); + assert!(core.confirming().is_none()); + assert!(frame_at(&mut core, &mut state, at(2)).outbound.is_empty()); + core.activate(press(), at(3), Ports { state: &mut state, ids: &mut ids }); + core.confirm(true, at(4), Ports { state: &mut state, ids: &mut ids }); + assert_eq!(frame_at(&mut core, &mut state, at(5)).outbound.len(), 1); +} -- 2.47.3 From 26501b0340eb2962527826aa7d1989aadf61069c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 23:31:16 +0100 Subject: [PATCH 04/13] Thing 2.0 cut 7a: a url with a space or a control character is refused Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/tests/command.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs index d046d3e..0746c9a 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -647,6 +647,8 @@ fn an_effect_core_will_not_run_makes_the_result_malformed_and_clears_nothing() { open_external("file:///etc/passwd", command("after")), open_external("https://", command("after")), open_external("https://ok.test/\nx", command("after")), + open_external("https://ok.test/a b", command("after")), + open_external("https://ok.test/\u{7f}", command("after")), open_external("https://ok.test/", CommandRef::Param(param("p"))), open_external("https://ok.test/", command("undeclared")), Effect::OpenSurface(OpenSurfaceEffect { key: "thing:asset_catalog:x.y".into() }), -- 2.47.3 From 2d4f4e0680779b37657e2f9a8072a94aef85d005 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 00:48:13 +0100 Subject: [PATCH 05/13] Thing 2.0 cut 7a h2: delete Core::drafts_mut, Commands own the one drafts table (drafts-mut-second-writer) Tests write drafts only through real change inputs and read them through the invocations they capture. Core tests that needed a text draft use what the node is bound to: Core has no text-edit route yet. Steward decision 1 of the h2 fix brief. Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/frame.rs | 6 - crates/thing-core/tests/command.rs | 181 ++++++++++++++++++++--------- 2 files changed, 127 insertions(+), 60 deletions(-) diff --git a/crates/thing-core/src/frame.rs b/crates/thing-core/src/frame.rs index 2a8a42e..ffdba2b 100644 --- a/crates/thing-core/src/frame.rs +++ b/crates/thing-core/src/frame.rs @@ -195,12 +195,6 @@ impl Core { self.shown.as_ref().map(|shown| self.commands.view(shown.key.as_str())).unwrap_or_default() } - /// The one table of uncommitted input values. The pointer and keyboard routes write it from - /// inside `frame`; until they land a host or a test writes here. - pub fn drafts_mut(&mut self) -> &mut Drafts { - &mut self.drafts - } - /// Drop the drafts of nodes the shown surface no longer has. fn retain_drafts(&mut self) { let Some(shown) = &self.shown else { return }; diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs index 0746c9a..ca777eb 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -355,12 +355,7 @@ fn f04_form_captures_in_declared_order_and_clears_exactly_those_drafts() { let form = set.surfaces[0].clone(); let expected = set.invocations[0].clone(); let mut rig = Rig::new(settings_state(false), &form); - let mut ids = ScriptedIds::new([expected.invocation_id.as_str()]); - - rig.act(&nid("enabled"), ActivationKind::Change(InputValue::Bool(BoolValue { value: true })), PINNED_NOW, &mut ids); - assert_eq!(rig.commands.take_outbound(), vec![expected.clone()]); - // The change was written to Drafts before the command fired. - assert_eq!(rig.draft(&nid("enabled")), Some(InputValue::Bool(BoolValue { value: true }))); + // Drafts held at the press are what the press captures, and what the result clears. for (node, value) in [ ("volume", InputValue::Number(NumberValue { value: 0.75 })), ("theme", InputValue::Choice(ChoiceValue { value: "dark".into() })), @@ -368,6 +363,12 @@ fn f04_form_captures_in_declared_order_and_clears_exactly_those_drafts() { ] { rig.set_draft(&nid(node), value); } + let mut ids = ScriptedIds::new([expected.invocation_id.as_str()]); + + rig.act(&nid("enabled"), ActivationKind::Change(InputValue::Bool(BoolValue { value: true })), PINNED_NOW, &mut ids); + assert_eq!(rig.commands.take_outbound(), vec![expected.clone()]); + // The change was written to Drafts before the command fired. + assert_eq!(rig.draft(&nid("enabled")), Some(InputValue::Bool(BoolValue { value: true }))); rig.set_draft(&nid("root"), text_value("not captured")); rig.feed(&set.results[0], at(1)); @@ -598,11 +599,11 @@ fn an_invocation_times_out_at_exactly_issued_plus_the_timeout() { assert!(!rig.state_of("go").busy); assert_eq!(rig.readers(&invocation), 0); assert_eq!(rig.commands.next_deadline(), None); - assert!(rig.tick(at(99_000)).is_empty()); // A result after the timeout is judged, not taken. let late = rig.feed_direct(&completed(&invocation, 1, false, None), at(16_000)); assert_eq!(codes(&late.diagnostics), vec![Code::ResultAfterTerminal]); assert_eq!(rig.state_of("go").mark, Some(Mark::TimedOut)); + assert!(rig.tick(at(99_000)).is_empty()); } #[test] @@ -857,22 +858,26 @@ fn frame_at(core: &mut Core, state: &mut MemState, now: Timestamp) -> thing_core fn f02_through_the_frame() { let set = Fixture::F02LoginEffect.load(); let login = set.surfaces[0].clone(); - let expected = set.invocations[0].clone(); + // Core has no text-edit route yet, so the username is what the node is bound to: empty. + let mut expected = set.invocations[0].clone(); + expected.captured[0].value = text_value(""); let mut state = MemState::from_fixture(Fixture::F02LoginEffect); let mut core = core(); core.show(login.provider_id.clone(), RecordKey::new(login.record_key())); let first = frame_at(&mut core, &mut state, PINNED_NOW); assert!(first.outbound.is_empty() && first.effects.is_empty() && first.next_wake.is_none()); - core.drafts_mut().set(&login.record_key(), &nid("username"), text_value("ada")); let mut ids = ScriptedIds::new([expected.invocation_id.as_str()]); let act = Activation { node: nid("sign-in-button"), kind: ActivationKind::Press }; - assert!(core.activate(act, PINNED_NOW, Ports { state: &mut state, ids: &mut ids }).is_empty()); + core.activate(act, PINNED_NOW, Ports { state: &mut state, ids: &mut ids }); let minted = frame_at(&mut core, &mut state, at(1)); assert_eq!(minted.outbound, vec![expected.clone()]); assert_eq!(minted.next_wake, Some(at(15_000))); - assert!(core.node_states().get(&nid("sign-in-button")).busy); + // The button is busy: a second press mints nothing and draws no id. + let mut spare = ScriptedIds::new(["00000000-0000-4000-8000-000000000000"]); + core.activate(Activation { node: nid("sign-in-button"), kind: ActivationKind::Press }, at(1), Ports { state: &mut state, ids: &mut spare }); + assert_eq!(spare.remaining(), 1); // The invocation left once. assert!(frame_at(&mut core, &mut state, at(2)).outbound.is_empty()); @@ -885,12 +890,11 @@ fn f02_through_the_frame() { let done = frame_at(&mut core, &mut state, at(2_000)); assert_eq!(done.effects.len(), 1); assert_eq!(done.next_wake, None); - assert!(!core.node_states().get(&nid("sign-in-button")).busy); // The host runs the effect, the session survives or not, and the resume comes back through Core. let HostEffect::OpenExternal { resume, .. } = &done.effects[0] else { panic!() }; let mut ids = ScriptedIds::new(["55555555-5555-4555-8555-555555555555"]); - assert!(core.resume(resume, at(3_000), Ports { state: &mut state, ids: &mut ids }).is_empty()); + core.resume(resume, at(3_000), Ports { state: &mut state, ids: &mut ids }); let resumed = frame_at(&mut core, &mut state, at(3_001)); assert_eq!(resumed.outbound.len(), 1); assert_eq!(resumed.outbound[0].command, CommandId::new("login-resume")); @@ -905,7 +909,6 @@ fn the_frame_fires_a_timeout_once_and_leaving_the_surface_forgets_its_invocation let mut core = core(); core.show(login.provider_id.clone(), RecordKey::new(login.record_key())); frame_at(&mut core, &mut state, PINNED_NOW); - core.drafts_mut().set(&login.record_key(), &nid("username"), text_value("ada")); let act = Activation { node: nid("sign-in-button"), kind: ActivationKind::Press }; core.activate(act, PINNED_NOW, Ports { state: &mut state, ids: &mut SeqIds::new() }); frame_at(&mut core, &mut state, at(1)); @@ -914,7 +917,6 @@ fn the_frame_fires_a_timeout_once_and_leaving_the_surface_forgets_its_invocation let late = frame_at(&mut core, &mut state, at(15_000)); assert_eq!(codes(&late.diagnostics), vec![Code::InvocationTimedOut]); assert_eq!(late.next_wake, None); - assert_eq!(core.node_states().get(&nid("sign-in-button")).mark, Some(Mark::TimedOut)); assert!(frame_at(&mut core, &mut state, at(16_000)).diagnostics.is_empty()); // Showing nothing forgets the surface's marks. @@ -922,27 +924,9 @@ fn the_frame_fires_a_timeout_once_and_leaving_the_surface_forgets_its_invocation frame_at(&mut core, &mut state, at(17_000)); core.show(login.provider_id.clone(), RecordKey::new(login.record_key())); frame_at(&mut core, &mut state, at(18_000)); - assert_eq!(core.node_states().get(&nid("sign-in-button")).mark, None); -} - -#[test] -fn a_republish_drops_the_drafts_of_the_nodes_it_removed() { - let provider = ProviderId::new(PROVIDER); - let two_inputs = surface(PROVIDER, boxed("root", vec![input("a", InputKind::Text, "", "go"), input("b", InputKind::Text, "", "go")]), vec![decl("go", &[], None)]); - let mut one_input = surface(PROVIDER, boxed("root", vec![input("a", InputKind::Text, "", "go")]), vec![decl("go", &[], None)]); - one_input.version = ver(2); - let mut state = MemState::new(); - state.put(&provider, &two_inputs); - let mut core = core(); - core.show(provider.clone(), RecordKey::new(two_inputs.record_key())); - frame_at(&mut core, &mut state, PINNED_NOW); - let key = two_inputs.record_key(); - core.drafts_mut().set(&key, &nid("a"), text_value("kept")); - core.drafts_mut().set(&key, &nid("b"), text_value("gone")); - state.put(&provider, &one_input); - frame_at(&mut core, &mut state, at(1)); - assert_eq!(core.drafts_mut().get(&key, &nid("a")), Some(&text_value("kept"))); - assert_eq!(core.drafts_mut().get(&key, &nid("b")), None); + // The timed-out invocation went with the surface: the button is free and mints again. + core.activate(Activation { node: nid("sign-in-button"), kind: ActivationKind::Press }, at(18_001), Ports { state: &mut state, ids: &mut SeqIds::new() }); + assert_eq!(frame_at(&mut core, &mut state, at(18_002)).outbound.len(), 1); } /// An invocation core never issued. @@ -1077,24 +1061,6 @@ fn the_id_sources_give_what_they_say() { assert!(!drafts.is_empty()); } -#[test] -fn removing_a_row_through_the_frame_drops_its_draft() { - let provider = ProviderId::new(PROVIDER); - let document = rows_surface(); - let mut state = rows_state(); - state.put(&provider, &document); - let mut core = core(); - core.show(provider.clone(), RecordKey::new(document.record_key())); - frame_at(&mut core, &mut state, PINNED_NOW); - let key = document.record_key(); - core.drafts_mut().set(&key, &row("item-0001", "note"), text_value("stays")); - core.drafts_mut().set(&key, &row("item-0003", "note"), text_value("goes")); - state.delete(&Address { provider: ProviderId::new(FEED), schema: SchemaId::new("gamecult.thing.test.item.v1"), key: RecordKey::new("item-0003") }); - frame_at(&mut core, &mut state, at(1)); - assert_eq!(core.drafts_mut().get(&key, &row("item-0001", "note")), Some(&text_value("stays"))); - assert_eq!(core.drafts_mut().get(&key, &row("item-0003", "note")), None); -} - #[test] fn a_confirmation_is_answered_through_the_core() { let provider = ProviderId::new(PROVIDER); @@ -1116,3 +1082,110 @@ fn a_confirmation_is_answered_through_the_core() { core.confirm(true, at(4), Ports { state: &mut state, ids: &mut ids }); assert_eq!(frame_at(&mut core, &mut state, at(5)).outbound.len(), 1); } + +// ----- the one drafts table: only commands write it ----- + +fn bool_value(value: bool) -> InputValue { + InputValue::Bool(BoolValue { value }) +} + +fn number_value(value: f64) -> InputValue { + InputValue::Number(NumberValue { value }) +} + +fn choice_value(value: &str) -> InputValue { + InputValue::Choice(ChoiceValue { value: value.into() }) +} + +/// Two toggles whose change fires `flagged`, and a button whose command captures them. +fn flags_surface(version: i64, with_b: bool) -> SurfaceDocument { + let mut children = vec![toggle("a", "flagged", lit_bool(false))]; + if with_b { + children.push(toggle("b", "flagged", lit_bool(false))); + } + children.push(button("go", "go")); + let mut document = surface( + PROVIDER, + boxed("root", children), + vec![decl("flagged", &[], None), decl("go", if with_b { &["a", "b"] } else { &["a"] }, None)], + ); + document.version = ver(version); + document +} + +fn change(node: &str, value: InputValue) -> Activation { + Activation { node: nid(node), kind: ActivationKind::Change(value) } +} + +fn press(node: &str) -> Activation { + Activation { node: nid(node), kind: ActivationKind::Press } +} + +#[test] +fn a_republish_drops_the_drafts_of_the_nodes_it_removed_and_keeps_the_rest() { + let provider = ProviderId::new(PROVIDER); + let mut state = MemState::new(); + state.put(&provider, &flags_surface(1, true)); + let mut core = core(); + core.show(provider.clone(), RecordKey::new(flags_surface(1, true).record_key())); + frame_at(&mut core, &mut state, PINNED_NOW); + // The only way into the table is a change input. + core.activate(change("a", bool_value(true)), at(1), Ports { state: &mut state, ids: &mut SeqIds::new() }); + core.activate(change("b", bool_value(true)), at(1), Ports { state: &mut state, ids: &mut SeqIds::new() }); + // b leaves in a republish and comes back in the next: its old draft must not come back with it. + state.put(&provider, &flags_surface(2, false)); + frame_at(&mut core, &mut state, at(2)); + state.put(&provider, &flags_surface(3, true)); + frame_at(&mut core, &mut state, at(3)); + core.activate(press("go"), at(4), Ports { state: &mut state, ids: &mut SeqIds::new() }); + let go = frame_at(&mut core, &mut state, at(5)).outbound.pop().expect("go minted"); + let captured: Vec<_> = go.captured.iter().map(|input| input.value.clone()).collect(); + assert_eq!(captured, vec![bool_value(true), bool_value(false)]); +} + +#[test] +fn removing_a_row_through_the_frame_drops_its_draft() { + let flag = Node::Toggle(ToggleNode { common: common("flag"), checked: lit_bool(false), on_change: command("flagged") }); + let row_node = Node::Box(BoxNode { + common: common("row"), + style: style(), + paint: plain_paint(), + role: Role::ListItem, + children: vec![flag, button("save", "save")], + }); + let rows = Node::Repeat(RepeatNode { + common: common("rows"), + collection: CollectionSource::Records(RecordsSource { + provider: Some(ProviderId::new(FEED)), + schema: SchemaId::new("gamecult.thing.test.item.v1"), + key_prefix: "item-".into(), + }), + key_member: path(&["Id"]), + template: std::boxed::Box::new(row_node), + }); + let document = surface(PROVIDER, boxed("root", vec![rows]), vec![decl("flagged", &[], None), decl("save", &["flag"], None)]); + let provider = ProviderId::new(PROVIDER); + let mut state = rows_state(); + state.put(&provider, &document); + let mut core = core(); + core.show(provider.clone(), RecordKey::new(document.record_key())); + frame_at(&mut core, &mut state, PINNED_NOW); + core.activate(change(row("item-0001", "flag").as_str(), bool_value(true)), at(1), Ports { state: &mut state, ids: &mut SeqIds::new() }); + core.activate(change(row("item-0003", "flag").as_str(), bool_value(true)), at(1), Ports { state: &mut state, ids: &mut SeqIds::new() }); + let feed = ProviderId::new(FEED); + state.delete(&Address { provider: feed.clone(), schema: SchemaId::new("gamecult.thing.test.item.v1"), key: RecordKey::new("item-0003") }); + frame_at(&mut core, &mut state, at(2)); + state.put_state(&feed, "item-0003", &Item { id: "item-0003".into(), title: "back".into() }); + frame_at(&mut core, &mut state, at(3)); + for item in ["item-0001", "item-0003"] { + core.activate(press(row(item, "save").as_str()), at(4), Ports { state: &mut state, ids: &mut SeqIds::new() }); + } + let saved = frame_at(&mut core, &mut state, at(5)).outbound; + assert_eq!(saved.len(), 2); + let flags: Vec<_> = saved.iter().map(|invocation| (invocation.items.clone(), invocation.captured[0].value.clone())).collect(); + assert_eq!( + flags, + vec![(vec!["item-0001".to_string()], bool_value(true)), (vec!["item-0003".to_string()], bool_value(false))] + ); +} + -- 2.47.3 From 7a38c397a09bc7c501a8f9db0a4c52b5a2be697c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 00:48:35 +0100 Subject: [PATCH 06/13] Thing 2.0 cut 7a h2: a completion clears only the drafts it captured, where still held (clear-drafts-clobbers-newer-edit) Steward decision 2 of the h2 fix brief. Drafts::clear becomes clear_held: a captured draft is dropped only while the table still holds the captured value, so an edit made after the press survives the result. Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/command/capture.rs | 12 ++++--- crates/thing-core/src/command/lifecycle.rs | 2 +- crates/thing-core/src/command/mod.rs | 8 ++--- crates/thing-core/src/input/drafts.rs | 12 ++++--- crates/thing-core/tests/command.rs | 37 +++++++++++++++++++++- 5 files changed, 56 insertions(+), 15 deletions(-) diff --git a/crates/thing-core/src/command/capture.rs b/crates/thing-core/src/command/capture.rs index 3179429..185a801 100644 --- a/crates/thing-core/src/command/capture.rs +++ b/crates/thing-core/src/command/capture.rs @@ -9,11 +9,11 @@ use thing_contract::{BoolValue, CapturedInput, ChoiceValue, CommandDecl, InputKi use crate::bind::{Bound, BoundTree, Field}; use crate::input::Drafts; -/// What the captures of one command came to: the values to send, and the laid ids they were read -/// from (the drafts a completed result clears). +/// What the captures of one command came to: the values to send, and the drafts they were read from +/// (laid id and the value the table held), which a completed result clears if still held. pub(super) struct Captured { pub inputs: Vec, - pub laid: Vec, + pub held: Vec<(NodeId, InputValue)>, } /// The laid id of `declared` as seen from a node whose enclosing instance prefixes are `scope` @@ -77,13 +77,15 @@ fn value(tree: &BoundTree, drafts: &Drafts, surface: &str, laid: &NodeId, node: /// error is the declared id of the first capture with no value to send. pub(super) fn capture(tree: &BoundTree, drafts: &Drafts, surface: &str, scope: &[String], decl: &CommandDecl) -> Result { let index = tree.index(); - let mut captured = Captured { inputs: Vec::new(), laid: Vec::new() }; + let mut captured = Captured { inputs: Vec::new(), held: Vec::new() }; for declared in &decl.captures { let laid = laid_id(&index, scope, declared).ok_or_else(|| declared.clone())?; let node = index.get(&laid).ok_or_else(|| declared.clone())?; let value = value(tree, drafts, surface, &laid, node).ok_or_else(|| declared.clone())?; captured.inputs.push(CapturedInput { node: declared.clone(), value }); - captured.laid.push(laid); + if let Some(draft) = drafts.get(surface, &laid) { + captured.held.push((laid, draft.clone())); + } } Ok(captured) } diff --git a/crates/thing-core/src/command/lifecycle.rs b/crates/thing-core/src/command/lifecycle.rs index 0733ccb..b09d4fe 100644 --- a/crates/thing-core/src/command/lifecycle.rs +++ b/crates/thing-core/src/command/lifecycle.rs @@ -100,7 +100,7 @@ impl Commands { }, }; if completed.clear_drafts { - drafts.clear(&surface, &self.live[at].laid); + drafts.clear_held(&surface, &self.live[at].held); } answered.effects.extend(effect); self.settle(at, State::Completed, None, port, ledger); diff --git a/crates/thing-core/src/command/mod.rs b/crates/thing-core/src/command/mod.rs index 6431661..b59feb5 100644 --- a/crates/thing-core/src/command/mod.rs +++ b/crates/thing-core/src/command/mod.rs @@ -121,7 +121,7 @@ struct Prepared { command: CommandId, payload_schema: SchemaId, captured: Vec, - laid: Vec, + held: Vec<(NodeId, InputValue)>, source: NodeId, items: Vec, /// The laid node the user acted on; a resume has none. @@ -139,7 +139,7 @@ struct Live { /// The highest result `seq` taken. highest: i32, deadline: Timestamp, - laid: Vec, + held: Vec<(NodeId, InputValue)>, scope: Vec, interest: Interest, source: NodeId, @@ -377,7 +377,7 @@ impl Commands { command: decl.id.clone(), payload_schema: decl.payload_schema.clone(), captured: captured.inputs, - laid: captured.laid, + held: captured.held, source: origin.source, items: origin.items, issuing: origin.issuing, @@ -416,7 +416,7 @@ impl Commands { state: State::Issued, highest: 0, deadline: now.plus_ms(self.timeout_ms), - laid: prepared.laid, + held: prepared.held, scope: prepared.scope, interest, source: prepared.source, diff --git a/crates/thing-core/src/input/drafts.rs b/crates/thing-core/src/input/drafts.rs index 50f6c79..887943a 100644 --- a/crates/thing-core/src/input/drafts.rs +++ b/crates/thing-core/src/input/drafts.rs @@ -24,10 +24,14 @@ impl Drafts { self.values.get(&(surface.to_string(), node.clone())) } - /// Drop the drafts of `nodes`; a node with no draft is untouched. - pub fn clear(&mut self, surface: &str, nodes: &[NodeId]) { - for node in nodes { - self.values.remove(&(surface.to_string(), node.clone())); + /// Drop each draft in `held` that the table still holds with that value. A draft edited since it + /// was held is newer than what was sent, and stays; a node with no draft is untouched. + pub fn clear_held(&mut self, surface: &str, held: &[(NodeId, InputValue)]) { + for (node, value) in held { + let key = (surface.to_string(), node.clone()); + if self.values.get(&key) == Some(value) { + self.values.remove(&key); + } } } diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs index ca777eb..3a12fa3 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -281,7 +281,9 @@ fn drafts_are_per_surface_and_clear_or_retain_exactly_what_is_named() { drafts.set("s1", &nid(node), text_value(node)); } drafts.set("s2", &nid("a"), text_value("other")); - drafts.clear("s1", &[nid("a"), nid("missing")]); + drafts.clear_held("s1", &[(nid("a"), text_value("a")), (nid("missing"), text_value("x"))]); + // A draft edited since it was held is newer: it stays. + drafts.clear_held("s1", &[(nid("b"), text_value("older"))]); assert_eq!(drafts.get("s1", &nid("a")), None); assert_eq!(drafts.get("s1", &nid("b")), Some(&text_value("b"))); assert_eq!(drafts.get("s2", &nid("a")), Some(&text_value("other"))); @@ -1189,3 +1191,36 @@ fn removing_a_row_through_the_frame_drops_its_draft() { ); } +// ----- completion clears what it captured, no more ----- + +fn tg_surface() -> SurfaceDocument { + surface(PROVIDER, boxed("root", vec![toggle("t", "tg", lit_bool(false)), button("b", "bc")]), vec![decl("tg", &["t"], None), decl("bc", &[], None)]) +} + +#[test] +fn a_completion_clears_the_drafts_it_captured_and_a_newer_edit_survives() { + for newer in [Some(false), None] { + let mut rig = Rig::new(MemState::new(), &tg_surface()); + let mut ids = SeqIds::new(); + rig.act(&nid("t"), ActivationKind::Change(bool_value(true)), PINNED_NOW, &mut ids); + let first = rig.commands.take_outbound().pop().expect("minted"); + if let Some(value) = newer { + // The node is busy: this edit mints nothing, and it is the draft now. + rig.act(&nid("t"), ActivationKind::Change(bool_value(value)), at(10), &mut ids); + assert!(rig.commands.take_outbound().is_empty()); + } + rig.feed(&completed(&first, 1, true, None), at(20)); + assert_eq!(rig.draft(&nid("t")), newer.map(bool_value), "newer edit {newer:?}"); + } +} + +#[test] +fn a_typed_draft_edited_after_the_press_survives_the_completion() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + rig.set_draft(&nid("name"), text_value("sent")); + let sent = rig.mint("go", PINNED_NOW); + rig.set_draft(&nid("name"), text_value("typed since")); + rig.feed(&completed(&sent, 1, true, None), at(1)); + assert_eq!(rig.draft(&nid("name")), Some(text_value("typed since"))); +} + -- 2.47.3 From 6e07c1d4cf0e8405bc0220c405eb00194d36e1f0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 00:48:48 +0100 Subject: [PATCH 07/13] Thing 2.0 cut 7a h2: a change value is validated before it is drafted (unvalidated-change-values) Steward decision 3 of the h2 fix brief. A non-finite slider value is refused, a finite one is clamped to the slider's range, and a select choice naming no declared option is refused. A refused change is not drafted and answers with Code::ActivationRefused. Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/command/capture.rs | 19 +++++++++++ crates/thing-core/src/command/mod.rs | 10 +++++- crates/thing-core/src/diagnostic.rs | 4 +++ crates/thing-core/tests/command.rs | 42 ++++++++++++++++++++++++ 4 files changed, 74 insertions(+), 1 deletion(-) diff --git a/crates/thing-core/src/command/capture.rs b/crates/thing-core/src/command/capture.rs index 185a801..12522ac 100644 --- a/crates/thing-core/src/command/capture.rs +++ b/crates/thing-core/src/command/capture.rs @@ -89,3 +89,22 @@ pub(super) fn capture(tree: &BoundTree, drafts: &Drafts, surface: &str, scope: & } Ok(captured) } + +/// The value a change input takes, or why it takes none. A slider is a range input: a value that is +/// not finite is refused, and a finite one outside its range is clamped to it. A select takes only an +/// option it declares (bound options included, as bound for this node). +pub(super) fn change(tree: &BoundTree, laid: &NodeId, node: &Node, value: &InputValue) -> Result { + match (node, value) { + (Node::Slider(slider), InputValue::Number(at)) => { + if !at.value.is_finite() { + return Err("the slider value is not a finite number"); + } + Ok(InputValue::Number(NumberValue { value: at.value.max(slider.min).min(slider.max) })) + } + (Node::Select(_), InputValue::Choice(chosen)) => match tree.value(laid, Field::Options) { + Some(Bound::Options(options)) if options.iter().any(|option| option.value == chosen.value) => Ok(value.clone()), + _ => Err("the choice names no declared option"), + }, + _ => Ok(value.clone()), + } +} diff --git a/crates/thing-core/src/command/mod.rs b/crates/thing-core/src/command/mod.rs index b59feb5..ef664a8 100644 --- a/crates/thing-core/src/command/mod.rs +++ b/crates/thing-core/src/command/mod.rs @@ -176,6 +176,11 @@ fn fault(surface: &str, node: Option<&NodeId>, code: Code, detail: impl Into Diagnostic { + fault(surface, Some(node), Code::ActivationRefused, detail) +} + /// A v4 UUID from 16 bytes: the version and variant bits are core's, so a minted id is always /// UUID-shaped and dot-free (a result key splits at its last dot). fn uuid(ids: &mut dyn IdSource) -> String { @@ -248,7 +253,10 @@ impl Commands { let Some(located) = tree.locate(&act.node) else { return Vec::new() }; let Some(CommandRef::Id(command)) = command_of(located.node, &act.kind) else { return Vec::new() }; if let ActivationKind::Change(value) = &act.kind { - drafts.set(&surface, &act.node, value.clone()); + match capture::change(tree, &act.node, located.node, value) { + Ok(taken) => drafts.set(&surface, &act.node, taken), + Err(detail) => return vec![refused(&surface, &act.node, detail)], + } } if matches!(located.node, Node::Button(_)) && tree.value(&act.node, Field::Enabled) == Some(&Bound::Bool(false)) { return Vec::new(); diff --git a/crates/thing-core/src/diagnostic.rs b/crates/thing-core/src/diagnostic.rs index 5625d05..e03c5a4 100644 --- a/crates/thing-core/src/diagnostic.rs +++ b/crates/thing-core/src/diagnostic.rs @@ -59,6 +59,10 @@ pub enum Code { CaptureUnavailable, /// A command capture naming no node, or a node that holds no input value. CaptureUndeclared, + /// An activation core refused to act on: a kind the node does not take, a node nobody laid, a change + /// value outside what the input allows, a command blocked by a confirmation, or a resume that can no + /// longer run. Nothing was minted; the detail says which. + ActivationRefused, } impl Code { diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs index 3a12fa3..aa7b698 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -1224,3 +1224,45 @@ fn a_typed_draft_edited_after_the_press_survives_the_completion() { assert_eq!(rig.draft(&nid("name")), Some(text_value("typed since"))); } +// ----- a change is validated before it is drafted ----- + +fn range_surface() -> SurfaceDocument { + let slider = Node::Slider(SliderNode { common: common("vol"), min: 0.0, max: 1.0, step: 0.1, value: lit_number(0.2), commit: command("go") }); + let select = Node::Select(SelectNode { + common: common("pick"), + options: OptionList::Literal(LiteralOptions { options: vec![SelectOption { value: "a".into(), label: "A".into() }] }), + value: record_bind(path(&["Theme"]), None), + on_change: command("pk"), + }); + surface(PROVIDER, boxed("root", vec![slider, select]), vec![decl("go", &["vol"], None), decl("pk", &["pick"], None)]) +} + +#[test] +fn a_slider_change_is_refused_when_not_finite_and_clamped_to_its_range() { + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let mut rig = Rig::new(MemState::new(), &range_surface()); + let refused = rig.act(&nid("vol"), ActivationKind::Change(number_value(value)), PINNED_NOW, &mut SeqIds::new()); + assert_eq!(codes(&refused), vec![Code::ActivationRefused], "{value}"); + assert!(rig.commands.take_outbound().is_empty()); + assert_eq!(rig.draft(&nid("vol")), None); + } + for (sent, taken) in [(5.0, 1.0), (-3.0, 0.0), (0.0, 0.0), (1.0, 1.0), (0.4, 0.4)] { + let mut rig = Rig::new(MemState::new(), &range_surface()); + let answered = rig.act(&nid("vol"), ActivationKind::Change(number_value(sent)), PINNED_NOW, &mut SeqIds::new()); + assert!(answered.is_empty(), "{sent}"); + assert_eq!(rig.draft(&nid("vol")), Some(number_value(taken))); + assert_eq!(rig.commands.take_outbound()[0].captured[0].value, number_value(taken)); + } +} + +#[test] +fn a_select_change_naming_no_declared_option_is_refused() { + let mut rig = Rig::new(MemState::new(), &range_surface()); + let refused = rig.act(&nid("pick"), ActivationKind::Change(choice_value("nope")), PINNED_NOW, &mut SeqIds::new()); + assert_eq!(codes(&refused), vec![Code::ActivationRefused]); + assert!(rig.commands.take_outbound().is_empty()); + assert_eq!(rig.draft(&nid("pick")), None); + assert!(rig.act(&nid("pick"), ActivationKind::Change(choice_value("a")), at(1), &mut SeqIds::new()).is_empty()); + assert_eq!(rig.draft(&nid("pick")), Some(choice_value("a"))); +} + -- 2.47.3 From 110acf5ef306907a9955c95c39016e88f6b65e1e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 00:49:06 +0100 Subject: [PATCH 08/13] Thing 2.0 cut 7a h2: a resumed confirm-gated command enters Confirming like an activation (resume-skips-confirm) Steward decision 5 of the h2 fix brief. activate and resume meet the confirmation in one place, Commands::begin. Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/command/mod.rs | 38 +++++++++++++++++++--------- crates/thing-core/tests/command.rs | 22 ++++++++++++++++ 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/crates/thing-core/src/command/mod.rs b/crates/thing-core/src/command/mod.rs index ef664a8..a1bcdb4 100644 --- a/crates/thing-core/src/command/mod.rs +++ b/crates/thing-core/src/command/mod.rs @@ -277,14 +277,7 @@ impl Commands { Ok(prepared) => prepared, Err(diagnostic) => return vec![diagnostic], }; - match &decl.confirm { - Some(text) => { - self.confirming = - Some(Confirming { surface, node: act.node, command: decl.id.clone(), text: text.clone(), prepared }); - } - None => self.mint(prepared, now, ids, port, ledger), - } - Vec::new() + self.begin(prepared, act.node, decl.confirm.as_ref(), now, ids, port, ledger) } /// Answer the command waiting on confirmation. Accepting mints with the captures taken at the @@ -322,10 +315,7 @@ impl Commands { let scope = tree.locate_source(&resume.source, &resume.items).map(|located| located.prefixes).unwrap_or_default(); let origin = Origin { issuing: None, source: resume.source.clone(), scope, items: resume.items.clone() }; match self.prepare(tree, drafts, decl, origin) { - Ok(prepared) => { - self.mint(prepared, now, ids, port, ledger); - Vec::new() - } + Ok(prepared) => self.begin(prepared, resume.source.clone(), decl.confirm.as_ref(), now, ids, port, ledger), Err(diagnostic) => vec![diagnostic], } } @@ -393,6 +383,30 @@ impl Commands { }) } + /// Where every way of acting on a command meets its confirmation: a command that asks waits for the + /// user's yes, holding the captures it was prepared with; any other mints. One command waits at a time. + #[allow(clippy::too_many_arguments)] + fn begin( + &mut self, + prepared: Prepared, + node: NodeId, + confirm: Option<&String>, + now: Timestamp, + ids: &mut dyn IdSource, + port: &mut dyn StatePort, + ledger: &mut Ledger, + ) -> Vec { + let Some(text) = confirm else { + self.mint(prepared, now, ids, port, ledger); + return Vec::new(); + }; + if self.confirming.is_some() { + return vec![refused(&prepared.surface, &node, "another command is waiting for confirmation")]; + } + self.confirming = Some(Confirming { surface: prepared.surface.clone(), node, command: prepared.command.clone(), text: text.clone(), prepared }); + Vec::new() + } + /// The one mint: draw one id, hold the interest in its results before the host can send, and /// queue the invocation. fn mint(&mut self, prepared: Prepared, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort, ledger: &mut Ledger) { diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs index aa7b698..72955ad 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -1266,3 +1266,25 @@ fn a_select_change_naming_no_declared_option_is_refused() { assert_eq!(rig.draft(&nid("pick")), Some(choice_value("a"))); } +// ----- a resume is an activation of a declared command ----- + +#[test] +fn a_resumed_command_that_asks_for_confirmation_waits_for_it() { + let mut document = go_surface(); + document.commands[1] = decl("after", &[], Some("really?")); + let mut rig = Rig::new(MemState::new(), &document); + let mut ids = SeqIds::new(); + let resume = Resume { surface_key: rig.surface.clone(), command: CommandId::new("after"), source: nid("after"), items: vec![] }; + let tree = rig.binder.tree(&rig.surface.clone()).unwrap(); + let said = rig.commands.resume(&resume, tree, &rig.drafts, PINNED_NOW, &mut ids, &mut rig.state, &mut rig.ledger); + assert!(said.is_empty()); + assert!(rig.commands.take_outbound().is_empty()); + assert_eq!(rig.commands.confirming().map(|waiting| waiting.text.as_str()), Some("really?")); + // One command waits at a time: a second resume that asks is refused, and the first still waits. + let tree = rig.binder.tree(&rig.surface.clone()).unwrap(); + let blocked = rig.commands.resume(&resume, tree, &rig.drafts, at(1), &mut ids, &mut rig.state, &mut rig.ledger); + assert_eq!(codes(&blocked), vec![Code::ActivationRefused]); + rig.commands.confirm(true, at(1), &mut ids, &mut rig.state, &mut rig.ledger); + assert_eq!(rig.commands.take_outbound()[0].command, CommandId::new("after")); +} + -- 2.47.3 From f5c6ec9048ac7d5a63db64053799c441c23dffe2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 00:49:35 +0100 Subject: [PATCH 09/13] Thing 2.0 cut 7a h2: every refused activation is a diagnostic in the frame output (silent-refusals) Steward decision 7 of the h2 fix brief. Kind mismatch, unknown node, blocked while confirming and a refused change answer Code::ActivationRefused from Commands::activate; Core queues what activate and resume say and the next frame's diagnostics carry it out, the channel the host already reads. A Param command cannot reach a tree (resolve refuses the document, tested), so it is the same refusal as a kind mismatch, not a separate branch. Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/command/mod.rs | 21 ++++++---- crates/thing-core/src/frame.rs | 40 ++++++++++++------- crates/thing-core/tests/command.rs | 58 ++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+), 22 deletions(-) diff --git a/crates/thing-core/src/command/mod.rs b/crates/thing-core/src/command/mod.rs index a1bcdb4..3318a4e 100644 --- a/crates/thing-core/src/command/mod.rs +++ b/crates/thing-core/src/command/mod.rs @@ -233,8 +233,10 @@ impl Commands { } /// The one commit primitive: the user acted on `act.node` of `tree`. Every path calls it. It - /// mints one invocation, or nothing: a node that is not a command source, a disabled or busy - /// button, an input with nothing to send, or a command waiting on confirmation. + /// mints one invocation, or nothing. A refusal (a node that is not a command source for this kind, a + /// node nobody laid, a change the input does not take, a command waiting on confirmation) answers with + /// a `Code::ActivationRefused` diagnostic. A disabled or busy button is not a refusal: the user sees + /// it, so it stays silent. #[allow(clippy::too_many_arguments)] pub fn activate( &mut self, @@ -246,12 +248,17 @@ impl Commands { port: &mut dyn StatePort, ledger: &mut Ledger, ) -> Vec { - if self.confirming.is_some() { - return Vec::new(); - } let surface = tree.resolved().document().record_key(); - let Some(located) = tree.locate(&act.node) else { return Vec::new() }; - let Some(CommandRef::Id(command)) = command_of(located.node, &act.kind) else { return Vec::new() }; + if self.confirming.is_some() { + return vec![refused(&surface, &act.node, "a command is waiting for confirmation")]; + } + let Some(located) = tree.locate(&act.node) else { + return vec![refused(&surface, &act.node, "the node is not in the surface")]; + }; + // A Param command is the same refusal: resolve leaves none in a tree, so none reaches here. + let Some(CommandRef::Id(command)) = command_of(located.node, &act.kind) else { + return vec![refused(&surface, &act.node, "the node fires no command for this activation")]; + }; if let ActivationKind::Change(value) = &act.kind { match capture::change(tree, &act.node, located.node, value) { Ok(taken) => drafts.set(&surface, &act.node, taken), diff --git a/crates/thing-core/src/frame.rs b/crates/thing-core/src/frame.rs index ffdba2b..b479659 100644 --- a/crates/thing-core/src/frame.rs +++ b/crates/thing-core/src/frame.rs @@ -9,7 +9,7 @@ use std::collections::HashSet; use crate::bind::Binder; use crate::command::{Activation, Commands, Confirming, HostEffect, NodeStates, Resume}; -use crate::diagnostic::Diagnostic; +use crate::diagnostic::{Code, Diagnostic}; use crate::input::{Drafts, InputEvent}; use crate::layout::{LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout}; use crate::port::{Address, Change, IdSource, Interest, Ledger, Lookup, StatePort}; @@ -81,6 +81,8 @@ pub struct Core { theme: Theme, commands: Commands, drafts: Drafts, + /// What activations said since the last frame; the frame's diagnostics carry it out. + notes: Vec, /// The surface `show` named, and the one whose interest and trees are held. wanted: Option
, shown: Option
, @@ -100,6 +102,7 @@ impl Core { theme: Theme::std(), commands: Commands::new(config.client, config.invocation_timeout_ms), drafts: Drafts::new(), + notes: Vec::new(), wanted: None, shown: None, last: None, @@ -121,7 +124,7 @@ impl Core { } changes.extend(port.drain()); - let mut diagnostics = Vec::new(); + let mut diagnostics = std::mem::take(&mut self.notes); let mut effects = Vec::new(); let mut rebound = false; for change in &changes { @@ -161,33 +164,40 @@ impl Core { } } - /// The user acted on a node of the shown surface: the one primitive every input path ends in. A - /// host or a test calls it directly until the pointer and keyboard routes (which call it from - /// `frame`) land. The invocation it mints is in the next frame's `outbound`. - pub fn activate(&mut self, act: Activation, now: Timestamp, ports: Ports<'_>) -> Vec { + /// The host's semantic activation: the user, or an accessibility action or an automation acting for + /// them, activated a node of the shown surface. It is the one primitive every input path ends in (pointer and + /// keyboard routes arrive here too). The invocation it mints is in the next + /// frame's `outbound`; a refusal (see `Commands::activate`) is said in that frame's `diagnostics`. + pub fn activate(&mut self, act: Activation, now: Timestamp, ports: Ports<'_>) { let Some(tree) = self.shown.as_ref().and_then(|shown| self.binder.tree(shown.key.as_str())) else { - return Vec::new(); + let node = Some(act.node); + self.notes.push(Diagnostic { code: Code::ActivationRefused, surface: String::new(), node, detail: "no surface is shown".into() }); + return; }; - self.commands.activate(act, tree, &mut self.drafts, now, ports.ids, ports.state, &mut self.ledger) + let said = self.commands.activate(act, tree, &mut self.drafts, now, ports.ids, ports.state, &mut self.ledger); + self.notes.extend(said); } - /// Answer the command waiting on confirmation (`confirming`). Until the confirmation dialog - /// lands after keyboard input, a host calls this from its own test or debug path. + /// Answer the command waiting on confirmation (`confirming`). The host shows the question and calls + /// this with the user's answer; accepting mints with the captures taken at the activation. pub fn confirm(&mut self, accept: bool, now: Timestamp, ports: Ports<'_>) { self.commands.confirm(accept, now, ports.ids, ports.state, &mut self.ledger); } + /// The command waiting for the user's yes or no, for the host to ask. pub fn confirming(&self) -> Option<&Confirming> { self.commands.confirming() } - /// Run the command an `OpenExternal` effect named, once the external step has returned. The - /// host holds the `Resume` across the navigation. - pub fn resume(&mut self, resume: &Resume, now: Timestamp, ports: Ports<'_>) -> Vec { + /// Run the command an `OpenExternal` effect named, once the external step has returned. The host + /// holds the `Resume` across the navigation and hands it back here; the command is minted, or asks + /// for confirmation, like an activation. A refusal is said in the next frame's `diagnostics`. + pub fn resume(&mut self, resume: &Resume, now: Timestamp, ports: Ports<'_>) { let Some(tree) = self.binder.tree(&resume.surface_key) else { - return Vec::new(); + return; }; - self.commands.resume(resume, tree, &self.drafts, now, ports.ids, ports.state, &mut self.ledger) + let said = self.commands.resume(resume, tree, &self.drafts, now, ports.ids, ports.state, &mut self.ledger); + self.notes.extend(said); } /// The busy, pending and fault state of the shown surface's nodes, for render and accessibility. diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs index 72955ad..64b05ce 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -1266,6 +1266,64 @@ fn a_select_change_naming_no_declared_option_is_refused() { assert_eq!(rig.draft(&nid("pick")), Some(choice_value("a"))); } +// ----- a refusal is said ----- + +#[test] +fn every_refusal_is_a_diagnostic_naming_the_surface_and_node() { + let mut confirming = go_surface(); + confirming.commands[1] = decl("after", &[], Some("sure?")); + let mut rig = Rig::new(MemState::new(), &confirming); + let mut ids = SeqIds::new(); + let surface_key = rig.surface.clone(); + // A kind the node does not take, a value of the wrong kind, a node nobody laid. + for (node, kind) in [("go", ActivationKind::Submit), ("name", ActivationKind::Press), ("no-such-node", ActivationKind::Press)] { + let refused = rig.act(&nid(node), kind, PINNED_NOW, &mut ids); + assert_eq!(codes(&refused), vec![Code::ActivationRefused], "{node}"); + assert_eq!(refused[0].surface, surface_key); + assert_eq!(refused[0].node, Some(nid(node))); + } + // Waiting on a confirmation blocks every other activation, and says so. + assert!(rig.press("after", PINNED_NOW, &mut ids).is_empty()); + let blocked = rig.press("go", at(1), &mut ids); + assert_eq!(codes(&blocked), vec![Code::ActivationRefused]); + assert!(rig.commands.take_outbound().is_empty()); + // A busy button stays silent: it is a state the user sees, not a fault. + let mut rig = Rig::new(MemState::new(), &go_surface()); + rig.press("go", PINNED_NOW, &mut ids); + assert!(rig.press("go", at(1), &mut ids).is_empty()); +} + +#[test] +fn a_command_param_outside_a_composition_leaves_no_tree_to_activate() { + let mut document = go_surface(); + let Node::Box(root) = &mut document.root else { unreachable!() }; + root.children.push(Node::Button(ButtonNode { + common: common("param"), + content: vec![], + on_activate: CommandRef::Param(param("cmd")), + enabled: lit_bool(true), + })); + let resolution = resolve(&document, &MemState::new(), &Limits::default()); + assert!(resolution.tree.is_none()); + assert!(codes(&resolution.diagnostics).contains(&Code::UnboundParam)); +} + +#[test] +fn the_core_says_a_refused_activation_in_the_frame_output() { + let provider = ProviderId::new(PROVIDER); + let document = go_surface(); + let mut state = MemState::new(); + state.put(&provider, &document); + let mut core = core(); + core.show(provider, RecordKey::new(document.record_key())); + frame_at(&mut core, &mut state, PINNED_NOW); + core.activate(press("no-such-node"), at(1), Ports { state: &mut state, ids: &mut SeqIds::new() }); + let out = frame_at(&mut core, &mut state, at(2)); + assert_eq!(codes(&out.diagnostics), vec![Code::ActivationRefused]); + // Said once. + assert!(frame_at(&mut core, &mut state, at(3)).diagnostics.is_empty()); +} + // ----- a resume is an activation of a declared command ----- #[test] -- 2.47.3 From 33281e2a9464a37b0a5325669bec3575909b2f4a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 00:49:51 +0100 Subject: [PATCH 10/13] Thing 2.0 cut 7a h2: a resume before its surface binds is held, not lost (resume-silent-before-bind) Steward decision 4 of the h2 fix brief. Core holds the Resume and runs it in the frame that first binds its surface, with that frame's now and ids, so it follows the normal lifecycle and timeout; leaving for another surface first drops it with an ActivationRefused diagnostic. Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/frame.rs | 27 ++++++++++++++++++++- crates/thing-core/tests/command.rs | 39 ++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/crates/thing-core/src/frame.rs b/crates/thing-core/src/frame.rs index b479659..31f5ef8 100644 --- a/crates/thing-core/src/frame.rs +++ b/crates/thing-core/src/frame.rs @@ -83,6 +83,9 @@ pub struct Core { drafts: Drafts, /// What activations said since the last frame; the frame's diagnostics carry it out. notes: Vec, + /// Resumes whose surface had not bound when the host handed them over; each runs at that surface's + /// first bind, or is dropped when the surface is left first. + held: Vec, /// The surface `show` named, and the one whose interest and trees are held. wanted: Option
, shown: Option
, @@ -103,6 +106,7 @@ impl Core { commands: Commands::new(config.client, config.invocation_timeout_ms), drafts: Drafts::new(), notes: Vec::new(), + held: Vec::new(), wanted: None, shown: None, last: None, @@ -152,6 +156,15 @@ impl Core { if rebound { self.retain_drafts(); } + for resume in std::mem::take(&mut self.held) { + match self.binder.tree(&resume.surface_key) { + Some(tree) => { + let said = self.commands.resume(&resume, tree, &self.drafts, now, ports.ids, port, &mut self.ledger); + diagnostics.extend(said); + } + None => self.held.push(resume), + } + } diagnostics.extend(self.commands.tick(now, port, &mut self.ledger)); let commands = self.draw(viewport, scale, &mut diagnostics); @@ -191,9 +204,11 @@ impl Core { /// Run the command an `OpenExternal` effect named, once the external step has returned. The host /// holds the `Resume` across the navigation and hands it back here; the command is minted, or asks - /// for confirmation, like an activation. A refusal is said in the next frame's `diagnostics`. + /// for confirmation, like an activation. A resume handed over before its surface has bound is held and runs at the first bind; one whose + /// surface is left first is dropped and said. Any other refusal is said in the next frame's `diagnostics`. pub fn resume(&mut self, resume: &Resume, now: Timestamp, ports: Ports<'_>) { let Some(tree) = self.binder.tree(&resume.surface_key) else { + self.held.push(resume.clone()); return; }; let said = self.commands.resume(resume, tree, &self.drafts, now, ports.ids, ports.state, &mut self.ledger); @@ -219,6 +234,16 @@ impl Core { /// Leave the surface shown and take the one wanted: the interest is held before the one read, /// and what the read finds enters as a change like any republish. fn switch(&mut self, port: &mut dyn StatePort, changes: &mut Vec) { + // A resume is for the surface it names: leaving for another one forgets it. + let wanted = self.wanted.as_ref().map(|address| address.key.as_str().to_string()); + for resume in std::mem::take(&mut self.held) { + if wanted.as_deref() == Some(resume.surface_key.as_str()) { + self.held.push(resume); + } else { + let detail = "the surface was left before it bound; the resume is dropped"; + self.notes.push(Diagnostic { code: Code::ActivationRefused, surface: resume.surface_key, node: Some(resume.source), detail: detail.into() }); + } + } if let Some(old) = self.shown.take() { self.resolver.forget(old.key.as_str(), port, &mut self.ledger); self.binder.forget(old.key.as_str(), port, &mut self.ledger); diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs index 64b05ce..e2c7f2e 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -1346,3 +1346,42 @@ fn a_resumed_command_that_asks_for_confirmation_waits_for_it() { assert_eq!(rig.commands.take_outbound()[0].command, CommandId::new("after")); } +#[test] +fn a_resume_before_its_surface_binds_is_held_and_runs_at_the_first_bind() { + let provider = ProviderId::new(PROVIDER); + let document = go_surface(); + let mut state = MemState::new(); + state.put(&provider, &document); + let mut core = core(); + core.show(provider.clone(), RecordKey::new(document.record_key())); + let resume = Resume { surface_key: document.record_key(), command: CommandId::new("after"), source: nid("go"), items: vec![] }; + core.resume(&resume, PINNED_NOW, Ports { state: &mut state, ids: &mut SeqIds::new() }); + let first = frame_at(&mut core, &mut state, at(1_000)); + assert!(first.diagnostics.is_empty()); + assert_eq!(first.outbound.len(), 1); + assert_eq!(first.outbound[0].command, CommandId::new("after")); + // It follows the lifecycle from the bind: the timeout counts from the frame that ran it. + assert_eq!(first.next_wake, Some(at(16_000))); + // It ran once. + assert!(frame_at(&mut core, &mut state, at(1_001)).outbound.is_empty()); +} + +#[test] +fn a_held_resume_for_a_surface_left_before_it_bound_is_dropped_and_said() { + let provider = ProviderId::new(PROVIDER); + let document = go_surface(); + let mut state = MemState::new(); + state.put(&provider, &document); + let mut core = core(); + core.show(provider.clone(), RecordKey::new(document.record_key())); + let resume = Resume { surface_key: document.record_key(), command: CommandId::new("after"), source: nid("go"), items: vec![] }; + core.resume(&resume, PINNED_NOW, Ports { state: &mut state, ids: &mut SeqIds::new() }); + core.show(provider.clone(), RecordKey::new("thing:surface:provider.cmd.elsewhere")); + let left = frame_at(&mut core, &mut state, at(1)); + assert_eq!(codes(&left.diagnostics), vec![Code::ActivationRefused]); + assert!(left.outbound.is_empty()); + core.show(provider, RecordKey::new(document.record_key())); + let back = frame_at(&mut core, &mut state, at(2)); + assert!(back.outbound.is_empty() && back.diagnostics.is_empty()); +} + -- 2.47.3 From 2d0afea19f2598703de08ee478ea4c3d0564b09f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 00:49:59 +0100 Subject: [PATCH 11/13] Thing 2.0 cut 7a h2: node_states is no longer public API; confirm, confirming, resume and activate are documented host API (public-test-seams) Steward decision 6 of the h2 fix brief. Core::node_states had no consumer but tests, and render does not read it yet, so it is deleted rather than kept private; tests read state through frame output and Commands::view. activate, confirm, confirming and resume carry docs naming the host as their caller. Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/frame.rs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/crates/thing-core/src/frame.rs b/crates/thing-core/src/frame.rs index 31f5ef8..45bf4fd 100644 --- a/crates/thing-core/src/frame.rs +++ b/crates/thing-core/src/frame.rs @@ -8,7 +8,7 @@ use thing_contract::{CommandInvocation, DatabaseEntry, ProviderId, RecordKey, Sc use std::collections::HashSet; use crate::bind::Binder; -use crate::command::{Activation, Commands, Confirming, HostEffect, NodeStates, Resume}; +use crate::command::{Activation, Commands, Confirming, HostEffect, Resume}; use crate::diagnostic::{Code, Diagnostic}; use crate::input::{Drafts, InputEvent}; use crate::layout::{LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout}; @@ -204,8 +204,9 @@ impl Core { /// Run the command an `OpenExternal` effect named, once the external step has returned. The host /// holds the `Resume` across the navigation and hands it back here; the command is minted, or asks - /// for confirmation, like an activation. A resume handed over before its surface has bound is held and runs at the first bind; one whose - /// surface is left first is dropped and said. Any other refusal is said in the next frame's `diagnostics`. + /// for confirmation, like an activation. A resume handed over before its surface has bound is held and + /// runs at the first bind; one whose surface is left first is dropped and said. Any other refusal is + /// said in the next frame's `diagnostics`. pub fn resume(&mut self, resume: &Resume, now: Timestamp, ports: Ports<'_>) { let Some(tree) = self.binder.tree(&resume.surface_key) else { self.held.push(resume.clone()); @@ -215,11 +216,6 @@ impl Core { self.notes.extend(said); } - /// The busy, pending and fault state of the shown surface's nodes, for render and accessibility. - pub fn node_states(&self) -> NodeStates { - self.shown.as_ref().map(|shown| self.commands.view(shown.key.as_str())).unwrap_or_default() - } - /// Drop the drafts of nodes the shown surface no longer has. fn retain_drafts(&mut self) { let Some(shown) = &self.shown else { return }; -- 2.47.3 From 4c6c4648194c7cd824364526919b93ad9e74c06e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 00:50:27 +0100 Subject: [PATCH 12/13] Thing 2.0 cut 7a h2: a terminal invocation is kept one timeout, then forgotten (terminal-invocations-unbounded) Steward decision 8 of the h2 fix brief. Each invocation records when it went terminal; apply and tick drop those a whole invocation timeout past that, and a result arriving later is UnknownInvocation. Tested by advancing now. Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/command/lifecycle.rs | 33 ++++++++++++------- crates/thing-core/src/command/mod.rs | 3 ++ crates/thing-core/tests/command.rs | 38 ++++++++++++++++++++++ 3 files changed, 63 insertions(+), 11 deletions(-) diff --git a/crates/thing-core/src/command/lifecycle.rs b/crates/thing-core/src/command/lifecycle.rs index b09d4fe..1cf8ad2 100644 --- a/crates/thing-core/src/command/lifecycle.rs +++ b/crates/thing-core/src/command/lifecycle.rs @@ -40,6 +40,7 @@ impl Commands { if address.schema.as_str() != CommandResult::SCHEMA_NAME { return answered; } + self.expire(now); let Some(at) = self.live.iter().position(|live| live.interest.matches(address)) else { if !matches!(change, Change::Delete(_)) { answered.diagnostics.push(fault( @@ -65,16 +66,16 @@ impl Commands { // One equality catches a body naming another invocation, and a seq that is not the key's. Record::Result(result) if result.record_key() == address.key.as_str() => result, Record::Result(_) => { - self.malformed(at, "the result is not the one its key names", &mut answered, port, ledger); + self.malformed(at, "the result is not the one its key names", now, &mut answered, port, ledger); return answered; } _ => { - self.malformed(at, "the record at a result address is not a result", &mut answered, port, ledger); + self.malformed(at, "the record at a result address is not a result", now, &mut answered, port, ledger); return answered; } }, _ => { - self.malformed(at, "the result was refused at decode", &mut answered, port, ledger); + self.malformed(at, "the result was refused at decode", now, &mut answered, port, ledger); return answered; } }; @@ -94,7 +95,7 @@ impl Commands { Some(effect) => match validate::effect(effect, trees(&surface), &self.live[at]) { Ok(effect) => Some(effect), Err(detail) => { - self.malformed(at, &detail, &mut answered, port, ledger); + self.malformed(at, &detail, now, &mut answered, port, ledger); return answered; } }, @@ -103,7 +104,7 @@ impl Commands { drafts.clear_held(&surface, &self.live[at].held); } answered.effects.extend(effect); - self.settle(at, State::Completed, None, port, ledger); + self.settle(at, State::Completed, None, now, port, ledger); } Outcome::Denied(denied) => { let mut target = issuing.clone(); @@ -119,13 +120,13 @@ impl Commands { )), } } - self.settle(at, State::Denied, None, port, ledger); + self.settle(at, State::Denied, None, now, port, ledger); if let Some(node) = target { self.marks.insert((surface, node), Mark::Denied { reason: denied.reason.clone() }); } } Outcome::Failed(failed) => { - self.settle(at, State::Failed, Some(Mark::Failed { reason: failed.reason.clone() }), port, ledger); + self.settle(at, State::Failed, Some(Mark::Failed { reason: failed.reason.clone() }), now, port, ledger); } } answered @@ -134,12 +135,13 @@ impl Commands { /// Move every non-terminal invocation whose deadline has come to `TimedOut`. A deadline is /// compared with the time given: a wall clock that went backward delays a timeout, never fires one early. pub fn tick(&mut self, now: Timestamp, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec { + self.expire(now); let mut diagnostics = Vec::new(); for at in 0..self.live.len() { let live = &self.live[at]; if !live.state.is_terminal() && live.deadline <= now { diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::InvocationTimedOut, "no result by the deadline")); - self.settle(at, State::TimedOut, Some(Mark::TimedOut), port, ledger); + self.settle(at, State::TimedOut, Some(Mark::TimedOut), now, port, ledger); } } diagnostics @@ -151,17 +153,26 @@ impl Commands { } /// A result core will not take: the invocation is `Malformed`, and nothing it carried runs. - fn malformed(&mut self, at: usize, detail: &str, answered: &mut Answered, port: &mut dyn StatePort, ledger: &mut Ledger) { + fn malformed(&mut self, at: usize, detail: &str, now: Timestamp, answered: &mut Answered, port: &mut dyn StatePort, ledger: &mut Ledger) { let live = &self.live[at]; answered.diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::MalformedResult, detail)); - self.settle(at, State::Malformed, Some(Mark::Malformed), port, ledger); + self.settle(at, State::Malformed, Some(Mark::Malformed), now, port, ledger); + } + + /// Forget the invocations that went terminal a whole timeout ago: a result after that is for an + /// invocation core no longer holds, so the table stays bounded by the work of one timeout. A + /// result inside the window is still judged against the invocation (`ResultAfterTerminal`). + fn expire(&mut self, now: Timestamp) { + let timeout = self.timeout_ms; + self.live.retain(|live| live.done.is_none_or(|done| now < done.plus_ms(timeout))); } /// Enter a terminal state: the interest in results is released in the same call, and the /// issuing node shows the mark. - fn settle(&mut self, at: usize, state: State, mark: Option, port: &mut dyn StatePort, ledger: &mut Ledger) { + fn settle(&mut self, at: usize, state: State, mark: Option, now: Timestamp, port: &mut dyn StatePort, ledger: &mut Ledger) { let live = &mut self.live[at]; live.state = state; + live.done = Some(now); ledger.release(port, &live.interest); if let (Some(mark), Some(node)) = (mark, &live.issuing) { self.marks.insert((live.surface.clone(), node.clone()), mark); diff --git a/crates/thing-core/src/command/mod.rs b/crates/thing-core/src/command/mod.rs index 3318a4e..0777e8d 100644 --- a/crates/thing-core/src/command/mod.rs +++ b/crates/thing-core/src/command/mod.rs @@ -139,6 +139,8 @@ struct Live { /// The highest result `seq` taken. highest: i32, deadline: Timestamp, + /// When it went terminal; `None` while it waits. + done: Option, held: Vec<(NodeId, InputValue)>, scope: Vec, interest: Interest, @@ -445,6 +447,7 @@ impl Commands { state: State::Issued, highest: 0, deadline: now.plus_ms(self.timeout_ms), + done: None, held: prepared.held, scope: prepared.scope, interest, diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs index e2c7f2e..36855b0 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -1385,3 +1385,41 @@ fn a_held_resume_for_a_surface_left_before_it_bound_is_dropped_and_said() { assert!(back.outbound.is_empty() && back.diagnostics.is_empty()); } +// ----- terminal invocations are kept as long as a late result could matter ----- + +#[test] +fn a_terminal_invocation_is_kept_for_one_timeout_and_then_forgotten() { + // Kept: a result one millisecond short of the timeout after it went terminal is judged against it. + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + rig.feed(&completed(&invocation, 1, false, None), at(100)); + let kept = rig.feed_direct(&completed(&invocation, 2, false, None), at(100 + 15_000 - 1)); + assert_eq!(codes(&kept.diagnostics), vec![Code::ResultAfterTerminal]); + + // Forgotten: at the timeout the result is for an invocation core does not hold. + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + rig.feed(&completed(&invocation, 1, false, None), at(100)); + let gone = rig.feed_direct(&completed(&invocation, 2, false, None), at(100 + 15_000)); + assert_eq!(codes(&gone.diagnostics), vec![Code::UnknownInvocation]); + + // A timeout is terminal too, and counts from the moment the deadline was taken. + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + assert_eq!(codes(&rig.tick(at(15_000))), vec![Code::InvocationTimedOut]); + let late = rig.feed_direct(&completed(&invocation, 1, false, None), at(29_999)); + assert_eq!(codes(&late.diagnostics), vec![Code::ResultAfterTerminal]); + let later = rig.feed_direct(&completed(&invocation, 1, false, None), at(30_000)); + assert_eq!(codes(&later.diagnostics), vec![Code::UnknownInvocation]); +} + +#[test] +fn a_tick_also_forgets_the_terminal_invocations_past_their_time() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + rig.feed(&completed(&invocation, 1, false, None), at(100)); + assert!(rig.tick(at(100 + 15_000)).is_empty()); + let gone = rig.feed_direct(&completed(&invocation, 2, false, None), at(100 + 15_000 - 1)); + assert_eq!(codes(&gone.diagnostics), vec![Code::UnknownInvocation]); +} + -- 2.47.3 From 7ac1366d0a1c55a028b700f2cb41ec2b216cb188 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 00:50:34 +0100 Subject: [PATCH 13/13] Thing 2.0 cut 7a h2: pin the apply-before-tick order (apply-tick-order-unpinned) Steward decision 9 of the h2 fix brief. The frame already applied drained results before tick; the order is now stated where it is decided and tested: a result queued for the frame its deadline passes completes the invocation, no InvocationTimedOut, no mark. Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/command/lifecycle.rs | 2 ++ crates/thing-core/src/frame.rs | 2 ++ crates/thing-core/tests/command.rs | 21 +++++++++++++++++++++ 3 files changed, 25 insertions(+) diff --git a/crates/thing-core/src/command/lifecycle.rs b/crates/thing-core/src/command/lifecycle.rs index 1cf8ad2..b8d142b 100644 --- a/crates/thing-core/src/command/lifecycle.rs +++ b/crates/thing-core/src/command/lifecycle.rs @@ -132,6 +132,8 @@ impl Commands { answered } + /// Within a frame results apply before `tick` (`Core::frame` drains and applies, then ticks), so a + /// result queued for the frame its deadline passes wins over the timeout. /// Move every non-terminal invocation whose deadline has come to `TimedOut`. A deadline is /// compared with the time given: a wall clock that went backward delays a timeout, never fires one early. pub fn tick(&mut self, now: Timestamp, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec { diff --git a/crates/thing-core/src/frame.rs b/crates/thing-core/src/frame.rs index 45bf4fd..8584278 100644 --- a/crates/thing-core/src/frame.rs +++ b/crates/thing-core/src/frame.rs @@ -165,6 +165,8 @@ impl Core { None => self.held.push(resume), } } + // Results of this frame are applied above, before the deadline is judged: a late result that was + // already queued wins over the timeout. diagnostics.extend(self.commands.tick(now, port, &mut self.ledger)); let commands = self.draw(viewport, scale, &mut diagnostics); diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs index 36855b0..fac8a63 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -1423,3 +1423,24 @@ fn a_tick_also_forgets_the_terminal_invocations_past_their_time() { assert_eq!(codes(&gone.diagnostics), vec![Code::UnknownInvocation]); } +// ----- a result in the frame its deadline passes wins ----- + +#[test] +fn a_result_queued_for_the_frame_its_deadline_passes_wins_over_the_timeout() { + let provider = ProviderId::new(PROVIDER); + let document = go_surface(); + let mut state = MemState::new(); + state.put(&provider, &document); + let mut core = core(); + core.show(provider.clone(), RecordKey::new(document.record_key())); + frame_at(&mut core, &mut state, PINNED_NOW); + core.activate(press("go"), PINNED_NOW, Ports { state: &mut state, ids: &mut SeqIds::new() }); + let invocation = frame_at(&mut core, &mut state, at(1)).outbound.pop().expect("minted"); + state.put(&provider, &completed(&invocation, 1, false, None)); + let late = frame_at(&mut core, &mut state, at(60_000)); + assert!(late.diagnostics.is_empty(), "{:?}", late.diagnostics); + assert_eq!(late.next_wake, None); + // Completed, not timed out: the button is free. + core.activate(press("go"), at(60_001), Ports { state: &mut state, ids: &mut SeqIds::new() }); + assert_eq!(frame_at(&mut core, &mut state, at(60_002)).outbound.len(), 1); +} -- 2.47.3