xonecas.io
8447
Co

conveyor / commit ad60eef

Safe mode, panic isolation, and widget descriptions

A panic in a widget's new, view, update, event or on handler stops only
that instance, which draws a red card. If root or status stops, or the
user picks Safe mode from the Ctrl inspector or starts with --safe, the
core runs alone with the builds on trial, Keep, Discard and Leave. The
shared value safe_mode = off stops offering it.

gen.rs takes each widget's first //! paragraph as its description, read
with cx.about(kind).

Co-Authored-By: Claude Opus 5.5

sacenox2026-11-09 ad60eeff6746eb11c0cf25f7a4f8485f2df508df parent 6c86b40

11 files changed

DESIGN.md+1−0
@@ -207,6 +207,7 @@ Ctrl+click ─► conveyord: widgets ticket (kind, instance chain, tree, shared,
207207 - **Widgets act from anywhere.** `cx.act(|live| ..)` does from `view`, `update` and `event` what the free functions do from handlers.
208208 - **Library changes load in place** (spike 8). The app is a 7 KB binary over `libconveyor_app.so` (app, `api.rs`, Rune, std); the widgets are `libconveyor_widgets.so`, rebuilt in 0.45 s and `dlopen`ed by the running app. Every instance is dropped and made again from its folder, so widgets save as they go and stop their threads and processes in `Drop`. Widgets built against another build of the app wait for its `exec` restart, which now happens only when conveyor itself changes. Both are built wi …
209209 - **Hidden work survives reloads.** Instances exist once rendered; `cx.keep_running()` from `update` makes the app bring one back after a reload or restart even when nothing shows it.
210+- **A broken widget can't take the app down** (catching what it can: `new`, `view`, `update`, `event` and `on` handlers). A panic turns that one instance into a red card, Ctrl+clickable. If `root` or `status` stops, or the user Ctrl+clicks the inspector's Safe mode button, or starts with `--safe`, the core runs alone: no widget code, the builds on trial with Keep and Discard, and Leave. The shared value `safe_mode = off` stops offering it, for those who'd rather not.
210211 - **Widgets run with every permission the user has.** They are native code in the app, on the host: any file, any program, the network. The agent that writes them is sandboxed in a VM, the code it writes is not. That's deliberate for now, and may be a feature (a widget can drive the whole machine). Revisit before anyone runs someone else's library.
211212 - **`api.rs` is conveyor's contract**, copied into the library on every start along with `gen.rs`, `CLAUDE.md` and the preview. The preview is the app's own host (`api::Live`) with sample data, so the agent checks exactly what the app runs.
212213 - The app restarts (on a conveyor change) 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.
crates/conveyor-app/src/app.rs+24−4
@@ -1,7 +1,7 @@
11 //! The app's state and loop. It draws the library's `root` widget and three things of its own
2-//! above it: the Ctrl inspector and the prompt form. Over `root` it draws the library's `status`
2+//! above it: the Ctrl inspector, the prompt form and safe mode. Over `root` it draws the library's `status`
33 //! widget, build status, so the user can replace that too. Everything else is widgets.
4-use crate::{client, form::{self, Form}, inspect, reload::Loader};
4+use crate::{client, form::{self, Form}, inspect, reload::Loader, safe};
55 use crate::api::{Event, Host, Live};
66 use rune::{El, Tx, Waker, el};
77 use serde_json::Value;
@@ -37,6 +37,8 @@ pub struct State {
3737 pub window: std::cell::Cell<(f32, f32)>,
3838 /// What the form's field binds to in the frame it closes.
3939 pub spare: rune::TextEdit,
40+ /// Safe mode is up, and why: every widget is paused.
41+ pub safe: Option<String>,
4042 /// Builds whose new widgets were placed.
4143 placed: BTreeSet<u64>,
4244 widgets: Loader,
@@ -64,8 +66,10 @@ pub fn init() -> State {
6466 let base = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/conveyor/app");
6567 let _ = std::fs::create_dir_all(&base);
6668 let mut widgets = Loader::new();
67- let live = Live::new(base.clone(), widgets.poll().unwrap_or(&[]));
69+ let (kinds, about) = widgets.poll().unwrap_or((&[], &[]));
70+ let live = Live::new(base.clone(), kinds, about);
6871 State { placed: ids(&base, "placed").unwrap_or_default(), live, widgets,
72+ safe: std::env::args().any(|a| a == "--safe").then(|| "You started the app with --safe.".into()),
6973 builds: vec![], connected: false, sent: Instant::now(), started: Instant::now(), inbox: Default::default(), exe: None, built: None, ctrl: false, pointer: (0.0, 0.0),
7074 picked: vec![], element: String::new(), rects: RefCell::new(vec![]), form: None, window: Default::default(), spare: rune::TextEdit::new("") }
7175 }
@@ -84,7 +88,8 @@ pub fn setup(s: &mut State, waker: Waker) {
8488 }
8589
8690 pub fn poll(s: &mut State, _t: f64, tx: &mut Tx) -> bool {
87- let reloaded = s.widgets.poll().map(|kinds| s.live.reload(kinds)).is_some();
91+ if s.safe.is_some() { return safe_poll(s, tx); }
92+ let reloaded = s.widgets.poll().map(|(kinds, about)| s.live.reload(kinds, about)).is_some();
8893 let made = s.live.make_wanted();
8994 let mut again = made || reloaded;
9095 if let Some((asked, snap)) = s.inbox.lock().unwrap().take() {
@@ -105,11 +110,25 @@ pub fn poll(s: &mut State, _t: f64, tx: &mut Tx) -> bool {
105110 s.live.save();
106111 if s.live.animating() { tx.wake_after(Duration::from_millis(16)); }
107112 restart(s);
113+ safe::check(s);
108114 let ctrl = s.ctrl;
109115 on_modifiers(s, tx.mods(), tx);
110116 again || ctrl != s.ctrl
111117 }
112118
119+/// In safe mode only conveyord's news comes in: no widget code runs, and no new build loads.
120+fn safe_poll(s: &mut State, tx: &mut Tx) -> bool {
121+ if let Some((_, snap)) = s.inbox.lock().unwrap().take() {
122+ s.connected = snap.is_some();
123+ if let Some(snap) = snap { s.builds = client::builds(&snap); }
124+ }
125+ for r in s.live.take_outbox() { client::send(r); }
126+ s.live.save();
127+ restart(s);
128+ tx.wake_after(Duration::from_millis(500));
129+ true
130+}
131+
113132 /// Places the new widgets each build on trial asked for (`conveyor place <kind> --in <id>`),
114133 /// once: at the click, when that instance was clicked or is one of its parents.
115134 fn place(s: &mut State) {
@@ -160,6 +179,7 @@ fn paste(s: &mut State, c: &rune::ClipboardContent, _: &mut Tx) {
160179 }
161180
162181 pub fn view(s: &State, rcx: &mut rune::Cx<State>) -> El {
182+ if let Some(why) = &s.safe { return safe::view(s, why); }
163183 if let Some(r) = rcx.layout("app") { s.window.set((r[2], r[3])); }
164184 let mut app = el().key("app").w_full().h_full()
165185 .on_paste_content(paste)
crates/conveyor-app/src/inspect.rs+7−1
@@ -1,7 +1,7 @@
11 //! The building tool's eye: while Ctrl is held, a layer over the whole window outlines what's
22 //! under the pointer: the deepest keyed element, the widget it's in, and that widget's parents.
33 //! The layer takes the click, so no widget's own controls can swallow it. A click opens the
4-//! prompt about that widget and element.
4+//! prompt about that widget and element. A corner button opens safe mode.
55 use crate::{app::State, form};
66 use rune::{El, Tx, el, text, tok};
77
@@ -37,6 +37,12 @@ pub fn view(s: &State, rcx: &mut rune::Cx<State>) -> El {
3737 pick(s, tx);
3838 })
3939 .on_press_tx(|s: &mut State, _| form::open(s));
40+ if crate::safe::offered(s) {
41+ layer = layer.child(el().key("safe-mode").pin(Some(12.0), None, None, Some(12.0)).h(24.0).px(10.0).center_y().radius(12.0)
42+ .fill(t.card).border(1.0, accent).role("button").label("Safe mode").help("Pause every widget, and keep or discard builds on trial")
43+ .on_press_tx(|s: &mut State, _| s.safe = Some("You asked for it from the Ctrl inspector.".into()))
44+ .child(text("Safe mode").font(tok::type_::LABEL).color(t.text)));
45+ }
4046 for (i, (_, [x, y, w, h])) in rects.iter().enumerate().rev() {
4147 let (width, alpha) = if i == 0 { (1.5, 0.8) } else { (1.0, 0.3) };
4248 layer = layer.child(el().w(*w).h(*h).absolute(*x, *y).border(width, accent.alpha(alpha)).radius(4.0));
crates/conveyor-app/src/lib.rs+1−0
@@ -5,6 +5,7 @@ mod client;
55 mod form;
66 mod inspect;
77 mod reload;
8+mod safe;
89 #[path = "../../../templates/library/api.rs"]
910 pub mod api;
1011
crates/conveyor-app/src/reload.rs+5−5
@@ -1,7 +1,7 @@
11 //! Loads the widget library's latest build into this process: libconveyor_widgets.so, next to
22 //! the binary. Old builds stay mapped, since their threads may still be winding down. A build
33 //! made against another build of this app waits for the app's own restart.
4-use crate::api::Kinds;
4+use crate::api::{Abouts, Kinds};
55 use std::{ffi::{CStr, CString, c_char, c_void}, path::PathBuf, time::SystemTime};
66
77 unsafe extern "C" {
@@ -23,7 +23,7 @@ impl Loader {
2323 }
2424
2525 /// The widgets of a build not loaded yet, when there is one this app can run.
26- pub fn poll(&mut self) -> Option<Kinds> {
26+ pub fn poll(&mut self) -> Option<(Kinds, Abouts)> {
2727 let t = std::fs::metadata(&self.file).and_then(|m| m.modified()).ok()?;
2828 if Some(t) == self.loaded { return None; }
2929 self.count += 1;
@@ -35,7 +35,7 @@ impl Loader {
3535 let _ = std::fs::remove_file(&copy);
3636 self.loaded = Some(t);
3737 match loaded {
38- Ok((build, kinds)) if build == crate::BUILD => Some(kinds),
38+ Ok((build, kinds, about)) if build == crate::BUILD => Some((kinds, about)),
3939 Ok(_) => { eprintln!("widgets built against a newer app: waiting for its restart"); None }
4040 Err(e) => { eprintln!("widgets didn't load: {e}"); None }
4141 }
@@ -43,13 +43,13 @@ impl Loader {
4343 }
4444
4545 /// Safe while the library was built by the same compiler against this app: the build id says so.
46-unsafe fn open(path: &std::path::Path) -> Result<(&'static str, Kinds), String> {
46+unsafe fn open(path: &std::path::Path) -> Result<(&'static str, Kinds, Abouts), String> {
4747 let err = || unsafe { CStr::from_ptr(dlerror()).to_string_lossy().into_owned() };
4848 let path = CString::new(path.as_os_str().as_encoded_bytes()).map_err(|e| e.to_string())?;
4949 let handle = unsafe { dlopen(path.as_ptr(), 2) }; // RTLD_NOW
5050 if handle.is_null() { return Err(err()); }
5151 let entry = unsafe { dlsym(handle, c"conveyor_widgets".as_ptr()) };
5252 if entry.is_null() { return Err(err()); }
53- let entry: fn() -> (&'static str, Kinds) = unsafe { std::mem::transmute(entry) };
53+ let entry: fn() -> (&'static str, Kinds, Abouts) = unsafe { std::mem::transmute(entry) };
5454 Ok(entry())
5555 }
crates/conveyor-app/src/safe.rs+52−0
@@ -0,0 +1,52 @@
1+//! Safe mode: the core alone, with every widget paused, for when the library on trial is broken
2+//! (root or status panicked, or the user asked from the Ctrl inspector, or `--safe`). It lists the
3+//! builds on trial with Keep and Discard, and leaving it makes every widget again.
4+//! The shared value `safe_mode = off` stops offering it; `--safe` still opens it.
5+use crate::{app::State, client};
6+use rune::{El, col, el, row, text, tok};
7+
8+/// Whether the inspector offers it and a broken root or status opens it.
9+pub fn offered(s: &State) -> bool {
10+ s.live.shared("safe_mode") != Some("off")
11+}
12+
13+/// Opens it when root or status stopped.
14+pub fn check(s: &mut State) {
15+ if s.safe.is_some() || !offered(s) { return; }
16+ if let Some(msg) = ["root", "status"].iter().find_map(|id| Some(format!("`{id}` stopped: {}", s.live.broken(id)?))) {
17+ s.safe = Some(msg);
18+ }
19+}
20+
21+fn button(key: String, label: &'static str, fill: rune::Color, ink: rune::Color, f: impl Fn(&mut State) + 'static) -> El {
22+ row().key(key).h(28.0).px(12.0).center_y().radius(6.0).fill(fill).role("button").label(label)
23+ .on_press_tx(move |s: &mut State, _| f(s))
24+ .child(text(label).font(tok::type_::LABEL).color(ink))
25+}
26+
27+pub fn view(s: &State, why: &str) -> El {
28+ let t = tok::theme(true);
29+ let trial: Vec<_> = s.builds.iter().filter(|b| b["state"] == "review").collect();
30+ let mut list = col().w_full().gap(8.0);
31+ if trial.is_empty() { list = list.child(text("No builds on trial.").color(t.text_secondary)); }
32+ for b in trial {
33+ let id = b["id"].as_u64().unwrap_or(0);
34+ let send = move |op: &'static str| move |_: &mut State| client::send(format!("{{\"op\":\"{op}\",\"id\":{id}}}"));
35+ list = list.child(row().key(format!("build-{id}")).w_full().gap(8.0).center_y()
36+ .child(text(format!("#{id} {}", b["title"].as_str().unwrap_or(""))).color(t.text).grow(1.0).min_w(0.0).truncate())
37+ .child(button(format!("discard-{id}"), "Discard", t.hover, t.text, send("discard")))
38+ .child(button(format!("keep-{id}"), "Keep", tok::accent(0, true), t.bg, send("keep"))));
39+ }
40+ let offer = offered(s);
41+ let card = col().key("safe").w(560.0).padding(24.0).gap(12.0).radius(10.0).fill(t.card)
42+ .child(text("Safe mode").font(tok::type_::TITLE).color(t.text))
43+ .child(text(why.to_owned()).color(t.text_secondary).w_full().wrap())
44+ .child(text("Your widgets are paused. Builds on trial:").color(t.text))
45+ .child(list)
46+ .child(row().w_full().gap(8.0).center_y()
47+ .child(button("offer".into(), if offer { "Don't offer safe mode" } else { "Offer safe mode" }, t.hover, t.text,
48+ move |s| s.live.share("safe_mode", if offer { "off" } else { "on" })))
49+ .child(el().grow(1.0))
50+ .child(button("leave".into(), "Leave safe mode", tok::accent(0, true), t.bg, |s| { s.safe = None; s.live.remake(); })));
51+ col().key("safe-mode").w_full().h_full().fill(t.bg).center().window_drag().child(card)
52+}
crates/conveyor-widgets/src/lib.rs+3−3
@@ -1,8 +1,8 @@
11 //! The user's widget library, as the app loads it.
22 include!(concat!(env!("OUT_DIR"), "/widgets.rs"));
33
4-/// The app build these widgets were made against, and the widgets.
4+/// The app build these widgets were made against, the widgets, and what each one is.
55 #[unsafe(no_mangle)]
6-pub fn conveyor_widgets() -> (&'static str, api::Kinds) {
7- (conveyor_app::BUILD, ALL)
6+pub fn conveyor_widgets() -> (&'static str, api::Kinds, api::Abouts) {
7+ (conveyor_app::BUILD, ALL, ABOUT)
88 }
templates/library/CLAUDE.md+2−0
@@ -38,6 +38,8 @@ A widget is a struct with its own state that renders itself (`api::View`). Read
3838 - **Key what a user can point at.** Give cards, buttons, columns and panes stable, meaningful keys (`card-{id}`, `col-done`, `add-project`). The Ctrl+click outline and the ticket's element path come from keys; unkeyed parts are invisible to the builder.
3939 - **Animate.** Call `cx.animate()` in `view` while something moves, and draw from `cx.now`. Without it the app renders once a second.
4040 - **Files.** `cx.dir` is the instance's own folder and survives reloads and restarts.
41+- **Say what it is.** The first paragraph of a widget file's `//!` comment is its description: the library shows it to the user picking widgets (`cx.about(kind)`). One or two plain sentences on what it shows and does.
42+- **A panic stops only that instance.** It draws a red card with the message until the next build, and the user can Ctrl+click it to have it fixed. If `root` or `status` stops, the app opens safe mode, where no widget runs.
4143 - **Background work.** `std::thread`, and the system's programs with `std::process::Command` (`curl` for the network: std has no HTTPS). `rune::ImageCache` and `rune::Pixels` decode PNG and JPEG.
4244
4345 ## When to block instead
templates/library/api.rs+62−10
@@ -60,6 +60,8 @@ pub struct Data {
6060
6161 /// Every widget kind in the library, as (file name, widget): what a host loads.
6262 pub type Kinds = &'static [(&'static str, &'static Widget)];
63+/// Each kind's description: the first paragraph of its file's `//!` comment.
64+pub type Abouts = &'static [(&'static str, &'static str)];
6365
6466 /// Each widget file declares `pub const WIDGET: Widget`.
6567 pub struct Widget {
@@ -119,6 +121,11 @@ impl Cx<'_> {
119121 self.live.render(kind, &format!("{}.{key}", self.id))
120122 }
121123
124+ /// What widget `kind` is, from the first paragraph of its file's `//!` comment.
125+ pub fn about(&self, kind: &str) -> &'static str {
126+ self.live.about.iter().find(|(n, _)| *n == kind).map_or("", |(_, a)| a)
127+ }
128+
122129 /// A value any widget can read, set with `share`: the selected project, say.
123130 pub fn shared(&self, key: &str) -> Option<&str> {
124131 self.live.shared.get(key).map(String::as_str)
@@ -168,7 +175,25 @@ pub fn get<'a, W: View>(h: &'a mut HostState, id: &str) -> Option<&'a mut W> {
168175 /// A handler on instance `id`'s state, for on_press_tx, on_submit, on_input_change and the like.
169176 pub fn on<W: View>(id: &str, f: impl Fn(&mut W, &mut Tx) + 'static) -> impl Fn(&mut HostState, &mut Tx) + 'static {
170177 let id = id.to_owned();
171- move |h: &mut HostState, tx: &mut Tx| if let Some(w) = get::<W>(h, &id) { f(w, tx) }
178+ move |h: &mut HostState, tx: &mut Tx| {
179+ let Some(w) = get::<W>(h, &id) else { return };
180+ if let Err(msg) = catch(|| f(w, tx)) { Host::live(h).broken.get_mut().insert(id.clone(), msg); }
181+ }
182+}
183+
184+/// Runs widget code, turning a panic into its message.
185+fn catch<T>(f: impl FnOnce() -> T) -> Result<T, String> {
186+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|e| {
187+ e.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| e.downcast_ref::<String>().cloned()).unwrap_or_else(|| "it panicked".into())
188+ })
189+}
190+
191+/// What a broken instance draws instead of itself.
192+fn stopped(kind: &str, msg: &str) -> El {
193+ let (t, red) = (rune::tok::theme(true), rune::Color { r: 0.9, g: 0.35, b: 0.3, a: 1.0 });
194+ col().w_full().h_full().padding(12.0).gap(4.0).radius(6.0).fill(t.card).border(1.0, red)
195+ .child(rune::text(format!("{kind} stopped: {msg}")).color(red).w_full().wrap())
196+ .child(rune::text("Ctrl+click it to have it fixed").font(rune::tok::type_::LABEL).color(t.text_secondary))
172197 }
173198
174199 /// Binds a text field to a TextEdit in instance `id`'s state:
@@ -243,6 +268,9 @@ pub fn quote(s: &str) -> String {
243268 pub struct Live {
244269 pub data: Data,
245270 kinds: Kinds,
271+ about: Abouts,
272+ /// Instances whose code panicked, with the message. They draw `stopped` until the next build.
273+ broken: RefCell<BTreeMap<String, String>>,
246274 base: PathBuf,
247275 instances: HashMap<String, (String, Box<dyn View>)>,
248276 shared: BTreeMap<String, String>,
@@ -323,14 +351,14 @@ impl Live {
323351
324352 impl Live {
325353 /// Instances of `kinds` keep their folders under `base`, and shared values in `base/shared.tsv`.
326- pub fn new(base: PathBuf, kinds: Kinds) -> Self {
354+ pub fn new(base: PathBuf, kinds: Kinds, about: Abouts) -> Self {
327355 let shared = std::fs::read_to_string(base.join("shared.tsv")).unwrap_or_default().lines()
328356 .filter_map(|l| l.split_once('\t').map(|(k, v)| (k.to_owned(), v.replace("\\n", "\n"))))
329357 .collect();
330358 // Instances that were keeping work going come back now, shown or not.
331359 let wanted: Vec<(String, String)> = std::fs::read_to_string(base.join("running.tsv")).unwrap_or_default().lines()
332360 .filter_map(|l| l.split_once('\t').map(|(id, kind)| (id.to_owned(), kind.to_owned()))).collect();
333- Live { data: Data::default(), kinds, base, instances: HashMap::new(), shared, wanted: RefCell::new(wanted),
361+ Live { data: Data::default(), kinds, about, broken: RefCell::new(BTreeMap::new()), base, instances: HashMap::new(), shared, wanted: RefCell::new(wanted),
334362 animate: Cell::new(false), outbox: vec![], spare: TextEdit::new(""), dirty: false,
335363 later: RefCell::new(vec![]), running: RefCell::new(BTreeSet::new()), kept: BTreeSet::new() }
336364 }
@@ -341,8 +369,13 @@ impl Live {
341369
342370 /// Instance `id` of `kind`, keyed `w:<id>` so the app can find it under the pointer.
343371 pub fn render(&self, kind: &str, id: &str) -> El {
372+ let broken = self.broken.borrow().get(id).cloned();
373+ if let Some(msg) = broken { return stopped(kind, &msg).key(format!("w:{id}")); }
344374 match self.instances.get(id) {
345- Some((k, w)) if k == kind => w.view(&self.cx(id, now())).key(format!("w:{id}")),
375+ Some((k, w)) if k == kind => match catch(|| w.view(&self.cx(id, now()))) {
376+ Ok(el) => el.key(format!("w:{id}")),
377+ Err(msg) => { self.broken.borrow_mut().insert(id.to_owned(), msg.clone()); stopped(kind, &msg).key(format!("w:{id}")) }
378+ },
346379 // Made before the next render. A kind the library doesn't have (a discarded build's)
347380 // draws nothing.
348381 _ => {
@@ -361,8 +394,10 @@ impl Live {
361394 if self.instances.get(&id).is_some_and(|(k, _)| *k == kind) { continue; }
362395 let cx = self.cx(&id, now());
363396 let _ = std::fs::create_dir_all(&cx.dir);
364- let state = (w.new)(&cx);
365- self.instances.insert(id, (kind, state));
397+ match catch(|| (w.new)(&cx)) {
398+ Ok(state) => { self.instances.insert(id, (kind, state)); }
399+ Err(msg) => { self.broken.get_mut().insert(id, msg); }
400+ }
366401 made = true;
367402 }
368403 made
@@ -376,14 +411,30 @@ impl Live {
376411 /// A new build of the library: every instance is dropped, then made again from its kind's
377412 /// new code, before the next render. What they asked with `cx.act` runs first, against
378413 /// the old instances. Kinds the new build doesn't have are gone.
379- pub fn reload(&mut self, kinds: Kinds) {
414+ pub fn reload(&mut self, kinds: Kinds, about: Abouts) {
380415 self.apply();
381416 let all: Vec<(String, String)> = self.instances.drain().map(|(id, (kind, _))| (id, kind)).collect();
382- self.kinds = kinds;
417+ (self.kinds, self.about) = (kinds, about);
418+ self.broken.get_mut().clear();
383419 self.wanted.get_mut().extend(all);
384420 self.make_wanted();
385421 }
386422
423+ /// A shared value, as `cx.shared` reads it.
424+ pub fn shared(&self, key: &str) -> Option<&str> {
425+ self.shared.get(key).map(String::as_str)
426+ }
427+
428+ /// Every instance made again, from the same build: a fresh start for broken ones.
429+ pub fn remake(&mut self) {
430+ self.reload(self.kinds, self.about);
431+ }
432+
433+ /// Why instance `id` stopped, if its code panicked.
434+ pub fn broken(&self, id: &str) -> Option<String> {
435+ self.broken.borrow().get(id).cloned()
436+ }
437+
387438 /// Instances of `kind`, or any instance if `kind` is empty.
388439 pub fn ids(&self, kind: &str) -> Vec<String> {
389440 self.instances.iter().filter(|(_, (k, _))| kind.is_empty() || k == kind).map(|(id, _)| id.clone()).collect()
@@ -421,10 +472,11 @@ impl Live {
421472
422473 /// Instance `id`'s state, writable, beside a Cx for it.
423474 fn with<T>(&mut self, id: &str, f: impl FnOnce(&mut dyn View, &Cx) -> T) -> Option<T> {
475+ if self.broken.get_mut().contains_key(id) { return None; }
424476 let (k, mut w) = self.instances.remove(id)?;
425- let out = f(w.as_mut(), &self.cx(id, now()));
477+ let out = catch(|| f(w.as_mut(), &self.cx(id, now())));
426478 self.instances.insert(id.to_owned(), (k, w));
427- Some(out)
479+ out.map_err(|msg| self.broken.get_mut().insert(id.to_owned(), msg)).ok()
428480 }
429481
430482 /// Writes what the preview needs to show the app as it is now: `data.tsv` beside the
templates/library/gen.rs+8−1
@@ -1,4 +1,4 @@
1-// Writes $OUT_DIR/widgets.rs: the API, one module per widgets/<name>.rs, and ALL.
1+// Writes $OUT_DIR/widgets.rs: the API, one module per widgets/<name>.rs, ALL and ABOUT.
22 // `api` is how the API comes in: the preview compiles api.rs itself (and defines `HostState:
33 // api::Host`, the state every handler gets); the app's widgets build uses the app's.
44 // Shared by both build.rs files with include!, so keep it dependency free.
@@ -17,6 +17,13 @@ fn generate_widgets(lib: &std::path::Path, api: Option<&str>) {
1717 for n in &names { out += &format!("#[path = {:?}] pub mod {n};\n", dir.join(format!("{n}.rs"))); }
1818 out += "pub const ALL: &[(&str, &api::Widget)] = &[";
1919 for n in &names { out += &format!("({n:?}, &{n}::WIDGET), "); }
20+ out += "];\npub const ABOUT: &[(&str, &str)] = &[";
21+ for n in &names {
22+ // The first paragraph of the file's `//!` comment.
23+ let src = std::fs::read_to_string(dir.join(format!("{n}.rs"))).unwrap_or_default();
24+ let about: Vec<&str> = src.lines().map_while(|l| l.strip_prefix("//!")).map(str::trim).take_while(|l| !l.is_empty()).collect();
25+ out += &format!("({n:?}, {:?}), ", about.join(" "));
26+ }
2027 out += "];\n";
2128 std::fs::write(std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("widgets.rs"), out).unwrap();
2229 }
templates/library/preview/src/main.rs+1−1
@@ -92,7 +92,7 @@ fn init() -> State {
9292 Some(dir) => replay(&dir, &base),
9393 None => (sample(), None),
9494 };
95- let mut live = Live::new(base, widgets::ALL);
95+ let mut live = Live::new(base, widgets::ALL, widgets::ABOUT);
9696 live.data = data;
9797 let mut args = args.into_iter();
9898 State { live, kind: args.next().unwrap_or_default(), mounts: args.collect(), click }