xonecas.io
8447
Co

conveyor / commit 12a1c6c

Widgets are programs: own state, input, files, threads

The stateless-view API sent every new idea back to conveyor as a
missing capability: a todo list, a scratchpad and a picture of the day
all blocked. A widget is now a struct that renders itself, with
handlers that reach its state through on/edit/get, a folder that
outlives restarts, threads and curl. The app keeps only what all
widgets share. conveyor retry reruns a parked ticket with a note.

Co-Authored-By: Claude Opus 5.5

sacenox2026-11-09 12a1c6cc93acd4d860a53e34b69b3df5674ea3fb parent 09a098d

11 files changed

DESIGN.md+7−4
@@ -196,7 +196,7 @@ Ctrl+click (x,y) ─▶ prompt ─▶ conveyord: widgets ticket #n (ready) + can
196196 - Until the widget is built, its frame shows the prompt and the ticket's state where you clicked.
197197 - **Ctrl+click a widget to follow up on it.** The new ticket carries where you clicked inside it and the whole conversation so far. The widget keeps its spot and shows the new ticket's state until it's rebuilt.
198198 - **The conversation closes the loop in the app**, as it does in a terminal: each widget's thread holds your prompts, every `decide`, `deviate` and `block`, and the agent's last message. When a run leaves something out, the frame says "N to read" without hovering.
199-- A prompt that asks for nothing, or needs a capability the app lacks, is a `block`: the badge turns red and you follow up. An agent that guesses fills your library with stand-ins.
199+- A prompt that asks for nothing, or needs something no widget can reach (a new crate, a change to the app), is a `block`: the badge turns red and you follow up. An agent that guesses fills your library with stand-ins.
200200
201201 #### The widget base: three layers, each changed its own way
202202
@@ -204,16 +204,19 @@ Ctrl+click (x,y) ─▶ prompt ─▶ conveyord: widgets ticket #n (ready) + can
204204 core (conveyor-app) placement: drag · hover · Ctrl+click · right-click menu (every control, always)
205205 capabilities = api::Act: maximize/restore · front/back · chrome · conversation
206206 library (yours) frame.rs the base around every widget: title bar, buttons, badge, thread
207- widgets/* content
207+ widgets/* programs: own state, input, files in cx.dir, threads, curl
208208 canvas.json (data) per widget: x, y, z, maximized, chrome shown|hover|hidden, ticket history
209209 ```
210210
211211 - **Data changes by hand, instantly.** Moving, stacking, maximizing and hiding the chrome never need an agent or a rebuild. Every one is a `frame` request to conveyord, so `conveyor call '{"op":"frame","id":3,"maximized":true}'` scripts it too.
212212 - **Code changes by prompt.** `frame.rs` is in your library, so restyling every frame is a follow-up like any other. A ticket may change only `frame.rs` and `widgets/`; conveyor rejects a branch that touches the rest.
213-- **Capabilities are conveyor's.** `api.rs` is the contract: conveyor owns it, copies it into the library on every start, and a frame or widget reaches the app only through `Act`. Sound or video later are new `Act`s and `Cx` fields. A ticket that needs one blocks and names it.
214-- Frame buttons need handlers typed to the app's state. The library's `api.rs` is compiled inside the app (and inside the preview), so `act(id, Act::X)` names `crate::HostState`, and each host implements `api::Host`.
213+- **Widgets are programs, not views.** A widget is a struct with its own state that renders itself (`api::View`), with handlers, text fields, threads, its own folder (`cx.dir`, which outlives the restarts every library change causes) and the system's `curl`. The first cut made widgets stateless views and had the app grant capabilities one at a time: the next three prompts (a todo list, a scratchpad, a picture of the day) all blocked on a missing capability. The app owns only what all widgets sha …
214+- **`api.rs` is conveyor's contract**: conveyor owns it and copies it into the library on every start. Shared controls are `Act`s; a widget's handlers reach its own state with `on`, `edit` and `get`.
215+- Rune handlers are typed to the app's state. The library's `api.rs` is compiled inside the app (and inside the preview), so its helpers name `crate::HostState`, and each host implements `api::Host`: frame acts, plus a lookup of each widget's state by id.
216+- A drag inside a widget's own control (a text field, say) stays the control's; a drag on the rest of the frame moves the widget.
215217 - The right-click menu is core, not library: it is the way back when the chrome is hidden or a `frame.rs` drops a button.
216218 - The app restarts with `exec` on the path it read at launch, and conveyord copies itself into VMs from `/proc/self/exe`: after cargo replaces a binary, `current_exe()` names the deleted file.
219+- A widget is a title, a size and `new: fn(&Cx) -> Box<dyn View>`, laid out to fill any box. `Cx` holds its id, the time, the tickets and its folder. Widgets may use `rune`, `std` and the system's programs.
217220 - `gen.rs` turns `widgets/*.rs` into `#[path]` modules and `ALL`. The app's `build.rs` and the library's own `preview` crate both include it, so the agent verifies with exactly the code the app compiles.
218221 - The base image carries the pinned toolchain and a warm `~/.cache/conveyor-target`, so the agent's first preview build is incremental.
219222
crates/conveyor-app/src/acts.rs+9−1
@@ -1,5 +1,5 @@
11 //! What frames ask of the app (api::Act), carried out on the canvas and saved by conveyord.
2-use crate::{canvas::State, client, widgets::api::{Act, Chrome, Host}};
2+use crate::{canvas::State, client, widgets::api::{Act, Chrome, Host, View}};
33 use serde_json::json;
44
55 pub fn chrome(s: &str) -> Chrome {
@@ -11,6 +11,14 @@ fn chrome_name(c: Chrome) -> &'static str {
1111 }
1212
1313 impl Host for State {
14+ fn widget(&mut self, id: u32) -> Option<&mut dyn View> {
15+ self.widgets.get_mut(&id).map(|(_, w)| w.as_mut())
16+ }
17+
18+ fn spare(&mut self) -> &mut rune::TextEdit {
19+ &mut self.spare
20+ }
21+
1422 fn act(&mut self, id: u32, a: Act) {
1523 self.menu = None;
1624 if a == Act::Notes {
crates/conveyor-app/src/canvas.rs+11−9
@@ -1,7 +1,7 @@
11 //! The canvas: the app's state, its link to conveyord, and the widgets drawn in stacking order.
2-use crate::{client::{self, Snapshot}, menu, place, prompt, titlebar, widgets};
2+use crate::{client::{self, Snapshot}, live, menu, place, prompt, titlebar, widgets::api::View};
33 use rune::{El, TextEdit, Tx, Waker, col, el, text, tok};
4-use std::{collections::HashSet, path::{Path, PathBuf}, sync::{Arc, Mutex}, time::{Duration, SystemTime, UNIX_EPOCH}};
4+use std::{collections::{HashMap, HashSet}, path::{Path, PathBuf}, sync::{Arc, Mutex}, time::{Duration, SystemTime}};
55
66 pub struct State {
77 pub snap: Snapshot,
@@ -23,6 +23,10 @@ pub struct State {
2323 pub notes: HashSet<u32>,
2424 /// A widget's right-click menu, and where.
2525 pub menu: Option<(u32, f32, f32)>,
26+ /// Each built widget's own state, by widget id, with the widget's name.
27+ pub widgets: HashMap<u32, (String, Box<dyn View>)>,
28+ /// What a text field binds to while its widget isn't there.
29+ pub spare: TextEdit,
2630 }
2731
2832 fn mtime(p: &Path) -> Option<SystemTime> {
@@ -31,7 +35,8 @@ fn mtime(p: &Path) -> Option<SystemTime> {
3135
3236 pub fn init() -> State {
3337 State { snap: Snapshot::default(), connected: false, pointer: (0.0, 0.0), prompt_at: None, prompt: TextEdit::new(""),
34- inbox: Default::default(), exe: None, built: None, drag: None, hovered: None, notes: HashSet::new(), menu: None }
38+ inbox: Default::default(), exe: None, built: None, drag: None, hovered: None, notes: HashSet::new(), menu: None,
39+ widgets: HashMap::new(), spare: TextEdit::new("") }
3540 }
3641
3742 /// Polls conveyord once a second on a thread. Every poll also re-renders, for clocks.
@@ -51,6 +56,7 @@ pub fn poll(s: &mut State, _t: f64, _tx: &mut Tx) -> bool {
5156 s.connected = snap.is_some();
5257 // Mid-drag, the daemon's copy would snap the widget back.
5358 if let Some(snap) = snap && s.drag.is_none() { s.snap = snap; }
59+ live::sync(s);
5460 // conveyord rebuilt the app with a new widget: become the new binary, in place.
5561 if let Some(exe) = &s.exe && let Some(t) = mtime(exe) && Some(t) != s.built {
5662 use std::os::unix::process::CommandExt;
@@ -63,11 +69,7 @@ pub fn poll(s: &mut State, _t: f64, _tx: &mut Tx) -> bool {
6369
6470 pub fn view(s: &State, rcx: &mut rune::Cx<State>) -> El {
6571 let t = tok::theme(true);
66- let tickets: Vec<widgets::api::TicketInfo> = s.snap.tickets.iter()
67- .map(|t| widgets::api::TicketInfo { project: t.project.clone(), id: t.id, state: t.state.clone(), title: t.title.clone() })
68- .collect();
69- let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64());
70- let cx = widgets::api::Cx { now, tickets: &tickets };
72+ let tickets = live::tickets(s);
7173 let area = rcx.layout("canvas").map_or((1400.0, 864.0), |r| (r[2], r[3]));
7274 let mut canvas = el().key("canvas").role("canvas").label("Canvas").w_full().grow(1.0).min_h(0.0).fill(t.bg)
7375 .on_pointer_move_local(|s: &mut State, e: rune::PointerEvent, tx: &mut Tx| { s.pointer = (e.x, e.y); tx.live_only(); })
@@ -81,7 +83,7 @@ pub fn view(s: &State, rcx: &mut rune::Cx<State>) -> El {
8183 let mut order: Vec<_> = s.snap.canvas.iter().collect();
8284 // A widget with its conversation open draws on top, so the panel isn't covered.
8385 order.sort_by_key(|p| (s.notes.contains(&p.id), p.z));
84- for p in order { canvas = canvas.child(place::view(s, p, &cx, area)); }
86+ for p in order { canvas = canvas.child(place::view(s, p, &tickets, area)); }
8587 if let Some((x, y, about)) = s.prompt_at { canvas = canvas.child(prompt::view(s, x, y, about)); }
8688 if let Some((id, x, y)) = s.menu { canvas = canvas.child(menu::view(s, id, x, y)); }
8789 let status = if s.connected { String::new() } else { "conveyord isn't running".into() };
crates/conveyor-app/src/live.rs+33−0
@@ -0,0 +1,33 @@
1+//! The widgets' own state: one instance per built widget on the canvas, made when it appears
2+//! (or the app starts) and dropped when it goes. Each gets a folder that outlives restarts.
3+use crate::{canvas::State, widgets::{self, api::{Cx, TicketInfo}}};
4+use std::{path::PathBuf, time::{SystemTime, UNIX_EPOCH}};
5+
6+pub fn dir(id: u32) -> PathBuf {
7+ PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/conveyor/widgets").join(id.to_string())
8+}
9+
10+pub fn now() -> f64 {
11+ SystemTime::now().duration_since(UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64())
12+}
13+
14+pub fn tickets(s: &State) -> Vec<TicketInfo> {
15+ s.snap.tickets.iter().map(|t| TicketInfo { project: t.project.clone(), id: t.id, state: t.state.clone(), title: t.title.clone() }).collect()
16+}
17+
18+/// Matches the instances to the canvas: new widgets get one, removed ones lose theirs.
19+pub fn sync(s: &mut State) {
20+ let built: Vec<(u32, &str)> = s.snap.canvas.iter()
21+ .filter_map(|p| Some((p.id, p.widget.as_deref()?)))
22+ .collect();
23+ s.widgets.retain(|id, (name, _)| built.iter().any(|(i, n)| i == id && n == name));
24+ let tickets = tickets(s);
25+ for (id, name) in built {
26+ if s.widgets.contains_key(&id) { continue; }
27+ let Some((_, w)) = widgets::ALL.iter().find(|(n, _)| *n == name) else { continue };
28+ let dir = dir(id);
29+ let _ = std::fs::create_dir_all(&dir);
30+ let state = (w.new)(&Cx { id, now: now(), tickets: &tickets, dir: &dir });
31+ s.widgets.insert(id, (name.to_owned(), state));
32+ }
33+}
crates/conveyor-app/src/main.rs+1−0
@@ -3,6 +3,7 @@
33 mod acts;
44 mod canvas;
55 mod client;
6+mod live;
67 mod menu;
78 mod place;
89 mod prompt;
crates/conveyor-app/src/place.rs+5−4
@@ -1,17 +1,18 @@
11 //! One widget on the canvas: where it is, the frame around it, and what the pointer does to it.
22 //! Drag moves it, Ctrl+click follows up on it, right-click opens its menu.
3-use crate::{acts, canvas::State, client::{self, Placed}, prompt, widgets::{self, api::{Cx, Entry, Frame}}};
3+use crate::{acts, canvas::State, client::{self, Placed}, live, prompt, widgets::{self, api::{Cx, Entry, Frame, TicketInfo}}};
44 use rune::{Drag, El, Phase, Tx, col, el, text, tok};
55 use serde_json::json;
66
77 /// A widget no ticket has built yet: its prompt, in the frame.
88 const PENDING: (f32, f32) = (280.0, 120.0);
99
10-pub fn view(s: &State, p: &Placed, cx: &Cx, area: (f32, f32)) -> El {
10+pub fn view(s: &State, p: &Placed, tickets: &[TicketInfo], area: (f32, f32)) -> El {
1111 let built = p.widget.as_deref().and_then(|w| widgets::ALL.iter().find(|(n, _)| *n == w)).map(|(_, w)| w);
1212 let size = if p.maximized { area } else { built.map_or(PENDING, |w| w.size) };
13- let content = match built {
14- Some(w) => (w.view)(cx),
13+ let dir = live::dir(p.id);
14+ let content = match s.widgets.get(&p.id) {
15+ Some((_, w)) => w.view(&Cx { id: p.id, now: live::now(), tickets, dir: &dir }),
1516 None => col().w_full().h_full().center().child(text(p.title.clone()).font(tok::type_::BODY).color(tok::theme(true).text).wrap()),
1617 };
1718 let thread: Vec<Entry> = p.thread.iter().map(|e| Entry { ticket: e.ticket, kind: e.kind.clone(), text: e.text.clone() }).collect();
crates/conveyor/src/main.rs+7−0
@@ -17,6 +17,7 @@ const USAGE: &str = "usage:
1717 conveyor project SLUG PATH [SLOTS] add a project
1818 conveyor ticket SLUG TITLE [BODY] add a ready ticket
1919 conveyor ls list tickets
20+ conveyor retry SLUG ID [NOTE] run a ticket again; the note shows in its conversation
2021 conveyor call JSON one request to conveyord, as the app sends it
2122 conveyor note|decide|deviate|block|done ... inside a ticket's VM";
2223
@@ -40,6 +41,12 @@ fn main() {
4041 Ok(req) => print(server::call(req)),
4142 Err(e) => { eprintln!("not JSON: {e}"); 2 }
4243 },
44+ "retry" if a(2).parse::<u32>().is_ok() => {
45+ let id = a(2).parse().unwrap();
46+ if !a(3).is_empty() { store::event(a(1), id, serde_json::json!({"kind": "conveyor", "msg": a(3), "show": true})); }
47+ store::set_state(a(1), id, "ready");
48+ 0
49+ }
4350 "ls" => {
4451 for p in store::projects() {
4552 for t in store::tickets(&p.slug) {
crates/conveyor/src/thread.rs+1−0
@@ -18,6 +18,7 @@ pub fn of(tickets: &[u32]) -> Vec<Value> {
1818 (Some("verb"), Some("block")) => out.push(entry("block", format!("{} — recommends: {}", a("reason"), a("recommend")))),
1919 (Some("reply"), _) => out.push(entry("reply", e["text"].as_str().unwrap_or("").into())),
2020 (Some("error"), _) => out.push(entry("error", e["msg"].as_str().unwrap_or("").into())),
21+ (Some("conveyor"), _) if e["show"] == true => out.push(entry("conveyor", e["msg"].as_str().unwrap_or("").into())),
2122 _ => {}
2223 }
2324 }
templates/library/CLAUDE.md+38−14
@@ -4,39 +4,63 @@ This repo is the user's widget library. Each ticket is the user's words, typed o
44
55 ## What's yours to change
66
7-- `widgets/<name>.rs`: a widget's content. Most tickets change one of these.
8-- `frame.rs`: the base around every widget: its title bar, buttons, badge and the conversation panel. Change it when the user asks about how all widgets are framed.
7+- `widgets/<name>.rs`: one widget. Most tickets add or change one of these.
8+- `frame.rs`: the base around every widget: its title bar, buttons, badge and conversation panel. Change it when the user asks about how all widgets are framed.
99
1010 Everything else is conveyor's (`api.rs`, `gen.rs`, `preview/`, this file). A branch that changes those is rejected, so don't.
1111
12+## A widget is a real program
13+
14+A widget is a Rust struct with its own state that renders itself (`api::View`). It can do what a small desktop app does, with `rune` and `std`:
15+
16+- **State and input**: buttons, text fields, lists, keys. Reach the widget's state from a handler with `on`, `edit` or `get` (see `api.rs`).
17+- **Files**: `cx.dir` is the widget's own folder, and it survives restarts. The app restarts whenever the library changes, so save anything the user typed or made there, as it changes.
18+- **Background work**: `std::thread`. The app re-renders every second, so results show up within a second.
19+- **The network**: run the system `curl` with `std::process::Command`, on a thread. `std` has no HTTPS.
20+- **Images**: `rune::ImageCache` and `rune::Pixels` decode PNG and JPEG from files.
21+
22+Don't build what the frame already gives every widget: moving, maximizing, stacking, hiding the chrome, the conversation.
23+
1224 ## When to block instead
1325
1426 Run `conveyor block --reason "<...>" --recommend "<...>"` and stop, without guessing, when:
1527
1628 - the words don't ask for anything, such as a keyboard mash or a stray word;
17-- the ticket needs something the app can't do. The capabilities are `Act` in `api.rs`, and a widget gets `Cx`. Playing sound or opening a file, for example, is conveyor's to add: say which capability is missing.
18-
19-Moving, maximizing, stacking and hiding the chrome are the user's controls on the frame, already there: don't build them into a widget.
29+- the ticket needs something no widget can reach with `rune`, `std` and the system's programs, such as a new crate or a change to the app or its window. Say exactly what's missing.
2030
2131 ## Make or change the widget
2232
23-1. For a new widget, pick a short snake_case name, such as `clock` or `parked_tickets`. It must be a valid Rust identifier and must not clash with a file in `widgets/`. For a follow-up, keep the name.
24-2. Write `widgets/<name>.rs`. Copy this shape:
33+1. For a new widget, pick a short snake_case name, such as `clock` or `todo`. It must be a valid Rust identifier and must not clash with a file in `widgets/`. For a follow-up, keep the name.
34+2. Write `widgets/<name>.rs`. This shape has state, a handler and a saved file:
2535
2636 ```rust
2737 use super::api::*;
2838 use rune::{El, col, text, tok};
39+ use std::path::PathBuf;
40+
41+ pub const WIDGET: Widget = Widget { title: "Counter", size: (240.0, 120.0), new: |cx| Box::new(Counter::load(cx)) };
2942
30- pub const WIDGET: Widget = Widget { title: "Clock", size: (240.0, 120.0), view };
43+ struct Counter { n: u32, file: PathBuf }
44+
45+ impl Counter {
46+ fn load(cx: &Cx) -> Self {
47+ let file = cx.dir.join("n");
48+ Counter { n: std::fs::read_to_string(&file).ok().and_then(|s| s.parse().ok()).unwrap_or(0), file }
49+ }
50+ }
3151
32- fn view(cx: &Cx) -> El {
33- let t = tok::theme(true);
34- col().w_full().h_full().center().child(text(format!("{:.0}", cx.now)).color(t.text))
52+ impl View for Counter {
53+ fn view(&self, cx: &Cx) -> El {
54+ let t = tok::theme(true);
55+ col().w_full().h_full().center().role("button").label("Count")
56+ .on_press_tx(on(cx.id, |c: &mut Counter, _| { c.n += 1; let _ = std::fs::write(&c.file, c.n.to_string()); }))
57+ .child(text(format!("{}", self.n)).color(t.text))
58+ }
3559 }
3660 ```
3761
38-3. Read `api.rs` for what a widget can use. Only `rune` and `std` are available. The app re-renders every second, and `cx.now` is the time. Lay out to fill the box: the user can maximize any widget.
39-4. Use Rune's dark theme (`tok::theme(true)`). The frame draws the card, so don't add one.
62+ A text field binds with `.on_edit(edit(cx.id, |w: &mut MyWidget| &mut w.text))`, and `.on_input_change(on(cx.id, ...))` runs after each change.
63+3. Use Rune's dark theme (`tok::theme(true)`). The frame draws the card and a title bar over the top 32 points when hovered, so leave that strip free of controls. Lay out to fill the box: the user can maximize any widget.
4064
4165 ## Check it
4266
@@ -45,7 +69,7 @@ cargo build --release -p preview
4569 cargo run --release -p preview -- <name> --snap /tmp/<name>.png --tree /tmp/<name>.json --size 900x500
4670 ```
4771
48-The preview draws the widget in its frame with the chrome showing. Look at the PNG, and fix it until it shows what the ticket asks for. `--tree` lists every element with its rect, so use it to catch clipped or overflowing content. To see it maximized or with the conversation open, add `--script` steps that tap the frame's buttons.
72+The preview runs the widget live in its frame, with its folder at `/tmp/preview-<name>`. Use `--script` to press and type into it, and look at the PNG until it does what the ticket asks. `--tree` lists every element with its rect, so use it to catch clipped or overflowing content. A widget that fetches in the background may need `--at` a few seconds later.
4973
5074 Rune's docs are in the cargo git checkout: `~/.cargo/git/checkouts/rune-*/*/crates/rune/README.md`.
5175
templates/library/api.rs+51−14
@@ -1,12 +1,18 @@
11 //! The contract between this library and conveyor. Conveyor owns this file and replaces it
22 //! when it changes. The library's own code is frame.rs and widgets/.
3-use rune::{El, Tx};
3+use rune::{El, TextEdit, Tx};
4+use std::{any::Any, path::Path};
45
5-/// What a widget can read. The app fills it from conveyord; the preview with sample data.
6+/// What a widget gets each render. The app fills it from conveyord; the preview with samples.
67 pub struct Cx<'a> {
8+ /// This widget's id on the canvas: pass it to `on`, `edit` and `get`.
9+ pub id: u32,
710 /// Unix time in seconds. The app re-renders every second.
811 pub now: f64,
912 pub tickets: &'a [TicketInfo],
13+ /// This widget's own folder. What it keeps here survives restarts, and the app restarts
14+ /// every time the library changes.
15+ pub dir: &'a Path,
1016 }
1117
1218 pub struct TicketInfo {
@@ -17,12 +23,49 @@ pub struct TicketInfo {
1723 }
1824
1925 /// Each widget file declares `pub const WIDGET: Widget`. A widget is content: the frame
20-/// around it, its position and its size on the canvas are the frame's and the user's.
26+/// around it, its position and size on the canvas are the frame's and the user's.
2127 pub struct Widget {
2228 pub title: &'static str,
2329 /// Width and height in points when not maximized. Lay out to fill whatever box you get.
2430 pub size: (f32, f32),
25- pub view: fn(&Cx) -> El,
31+ /// Makes the widget's state, once per widget on the canvas, each time the app starts.
32+ pub new: fn(&Cx) -> Box<dyn View>,
33+}
34+
35+/// A widget's state. It renders itself; its handlers reach it again through `on`, `edit` or `get`.
36+pub trait View: Any {
37+ fn view(&self, cx: &Cx) -> El;
38+}
39+
40+/// The state Rune hands every handler: the app's, or the preview's.
41+pub type HostState = crate::HostState;
42+
43+/// The app, or the preview.
44+pub trait Host: 'static {
45+ fn act(&mut self, id: u32, a: Act);
46+ fn widget(&mut self, id: u32) -> Option<&mut dyn View>;
47+ /// A field to bind to while a widget isn't there, so `edit` always has one.
48+ fn spare(&mut self) -> &mut TextEdit;
49+}
50+
51+/// Widget `id`'s state, inside any handler:
52+/// `.on_key(move |h: &mut HostState, e, tx| get::<Todo>(h, id).map_or(false, |t| t.key(e)))`.
53+pub fn get<W: View>(h: &mut HostState, id: u32) -> Option<&mut W> {
54+ let w: &mut dyn Any = Host::widget(h, id)?;
55+ w.downcast_mut()
56+}
57+
58+/// A handler on widget `id`'s state, for on_press_tx, on_submit, on_input_change and the like.
59+pub fn on<W: View>(id: u32, f: impl Fn(&mut W, &mut Tx) + 'static) -> impl Fn(&mut HostState, &mut Tx) + 'static {
60+ move |h: &mut HostState, tx: &mut Tx| if let Some(w) = get::<W>(h, id) { f(w, tx) }
61+}
62+
63+/// Binds a text field to a TextEdit in widget `id`'s state: `.on_edit(edit(cx.id, |p: &mut Pad| &mut p.text))`.
64+pub fn edit<W: View>(id: u32, f: impl Fn(&mut W) -> &mut TextEdit + 'static) -> impl for<'a> Fn(&'a mut HostState) -> &'a mut TextEdit + 'static {
65+ rune::edit_access(move |h: &mut HostState| {
66+ if get::<W>(h, id).is_none() { return Host::spare(h); }
67+ f(get::<W>(h, id).unwrap())
68+ })
2669 }
2770
2871 /// One widget on the canvas, as its frame sees it. frame.rs draws it.
@@ -44,7 +87,7 @@ pub struct Frame<'a> {
4487
4588 /// One step of a widget's conversation. `kind` is one of: prompt (the user's words),
4689 /// decide, deviate, block (what the agent chose, changed or couldn't do), reply (the agent's
47-/// last message), error (conveyor's, when a run failed).
90+/// last message), conveyor (a note from conveyor), error (when a run failed).
4891 pub struct Entry {
4992 pub ticket: u32,
5093 pub kind: String,
@@ -54,8 +97,7 @@ pub struct Entry {
5497 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
5598 pub enum Chrome { Shown, Hover, Hidden }
5699
57-/// What a frame can ask of the app. These are the only capabilities there are: if a ticket
58-/// needs another, it's conveyor's to add, so block and say which.
100+/// What a frame can ask of the app: the controls every widget shares.
59101 #[derive(Clone, Copy, PartialEq, Debug)]
60102 pub enum Act {
61103 /// Fill the canvas, or go back to its own size and place.
@@ -69,12 +111,7 @@ pub enum Act {
69111 Notes,
70112 }
71113
72-/// The app, or the preview: whatever carries out acts.
73-pub trait Host: 'static {
74- fn act(&mut self, id: u32, a: Act);
75-}
76-
77114 /// A press handler that asks for `a`: `button.on_press_tx(act(f.id, Act::Maximize))`.
78-pub fn act(id: u32, a: Act) -> impl Fn(&mut crate::HostState, &mut Tx) + 'static {
79- move |h: &mut crate::HostState, _: &mut Tx| Host::act(h, id, a)
115+pub fn act(id: u32, a: Act) -> impl Fn(&mut HostState, &mut Tx) + 'static {
116+ move |h: &mut HostState, _: &mut Tx| Host::act(h, id, a)
80117 }
templates/library/preview/src/main.rs+33−12
@@ -1,19 +1,24 @@
11 //! Renders one widget in its frame, with sample data, so it can be checked headless:
22 //! cargo run --release -p preview -- <name> --snap /tmp/<name>.png --tree /tmp/<name>.json --size 900x500
3-//! The frame's chrome is shown and its buttons work here, as in the app.
3+//! The widget is live: its handlers, its folder (/tmp/preview-<name>) and the frame's buttons
4+//! all work, so `--script` can type into it and press it.
45 mod widgets {
56 include!(concat!(env!("OUT_DIR"), "/widgets.rs"));
67 }
78
8-use rune::{AppSpec, El, col, el, text, tok};
9-use widgets::api::{Act, Chrome, Cx, Entry, Frame, Host, TicketInfo};
9+use rune::{AppSpec, El, TextEdit, col, el, text, tok};
10+use std::path::PathBuf;
11+use widgets::api::{Act, Chrome, Cx, Entry, Frame, Host, TicketInfo, View};
1012
1113 pub type HostState = State;
1214
1315 pub struct State {
1416 name: String,
17+ dir: PathBuf,
1518 tickets: Vec<TicketInfo>,
1619 thread: Vec<Entry>,
20+ widget: Option<Box<dyn View>>,
21+ spare: TextEdit,
1722 maximized: bool,
1823 notes: bool,
1924 }
@@ -27,13 +32,25 @@ impl Host for State {
2732 _ => {}
2833 }
2934 }
35+ fn widget(&mut self, _: u32) -> Option<&mut dyn View> {
36+ self.widget.as_deref_mut()
37+ }
38+ fn spare(&mut self) -> &mut TextEdit {
39+ &mut self.spare
40+ }
41+}
42+
43+fn now() -> f64 {
44+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0)
3045 }
3146
3247 fn init() -> State {
3348 let t = |project: &str, id, state: &str, title: &str| TicketInfo { project: project.into(), id, state: state.into(), title: title.into() };
3449 let e = |kind: &str, text: &str| Entry { ticket: 1, kind: kind.into(), text: text.into() };
35- State {
36- name: rune::extra_args().first().cloned().unwrap_or_default(),
50+ let name = rune::extra_args().first().cloned().unwrap_or_default();
51+ let dir = std::env::temp_dir().join(format!("preview-{name}"));
52+ let _ = std::fs::create_dir_all(&dir);
53+ let mut s = State {
3754 tickets: vec![
3855 t("conveyor", 1, "running", "conveyord: store, dispatcher, VM and agent drivers"),
3956 t("conveyor", 2, "review", "Guest CLI: the agent's verbs"),
@@ -42,26 +59,30 @@ fn init() -> State {
4259 t("dotfiles", 8, "done", "Add a git alias for amend"),
4360 ],
4461 thread: vec![e("prompt", "A sample prompt"), e("decide", "A sample decision — and why"), e("reply", "The agent's sample reply.")],
45- maximized: false,
46- notes: false,
62+ widget: None, spare: TextEdit::new(""), maximized: false, notes: false, name, dir,
63+ };
64+ if let Some((_, w)) = widgets::ALL.iter().find(|(n, _)| *n == s.name) {
65+ s.widget = Some((w.new)(&Cx { id: 1, now: now(), tickets: &s.tickets, dir: &s.dir }));
4766 }
67+ s
4868 }
4969
5070 fn view(s: &State, _: &mut rune::Cx<State>) -> El {
5171 let t = tok::theme(true);
52- let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0);
53- let cx = Cx { now, tickets: &s.tickets };
54- let Some((_, w)) = widgets::ALL.iter().find(|(n, _)| *n == s.name) else {
72+ let (Some((_, w)), Some(widget)) = (widgets::ALL.iter().find(|(n, _)| *n == s.name), &s.widget) else {
5573 let have: Vec<_> = widgets::ALL.iter().map(|(n, _)| *n).collect();
5674 return col().w_full().h_full().center().fill(t.bg).child(text(format!("no widget {:?}; have {have:?}", s.name)).color(t.text));
5775 };
76+ let cx = Cx { id: 1, now: now(), tickets: &s.tickets, dir: &s.dir };
5877 let f = Frame { id: 1, title: w.title, size: w.size, state: "done", thread: &s.thread, maximized: s.maximized,
5978 chrome: Chrome::Shown, hovered: true, notes: s.notes };
60- let framed = widgets::frame::frame(&f, (w.view)(&cx));
79+ let framed = widgets::frame::frame(&f, widget.view(&cx));
6180 if s.maximized { return col().w_full().h_full().fill(t.bg).child(framed); }
6281 col().w_full().h_full().center().fill(t.bg).child(el().w(w.size.0).h(w.size.1).child(framed))
6382 }
6483
6584 fn main() {
66- rune::run(AppSpec::new("preview", (900.0, 500.0), init, view));
85+ // Re-render every second, as the app does, so clocks and background work show up.
86+ let spec = AppSpec { poll: Some(|_: &mut State, _, _: &mut rune::Tx| true), ..AppSpec::new("preview", (900.0, 500.0), init, view) };
87+ rune::run(spec);
6788 }