xonecas.io
8447
Co

conveyor / commit 09a098d

Widget base: frames, conversations, and controls the user owns

Every widget sits in frame.rs, which lives in the library and is
changed by prompt like a widget. The app owns the controls (drag,
Ctrl+click follow-up, right-click menu) and the capabilities frames ask
for through api::Act: maximize, stacking, chrome. Settings are data in
canvas.json behind one scriptable frame op. Each widget's conversation
(prompts, decisions, deviations, blocks and the agent's reply) shows in
its frame, and a follow-up carries all of it.

Conveyor owns api.rs and keeps it in the library; a ticket may change
only frame.rs and widgets/. Fixes copying conveyord into VMs after a
rebuild.

Co-Authored-By: Claude Opus 5.5

sacenox2026-11-09 09a098de237b7b214c119b469c8219bf617ec5ef parent f9bda85

19 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

DESIGN.md+21−6
@@ -193,12 +193,27 @@ Ctrl+click (x,y) ─▶ prompt ─▶ conveyord: widgets ticket #n (ready) + can
193193 app sees its binary change ─▶ exec() itself ─▶ widget at (x,y)
194194 ```
195195
196-- Until the widget is built, the canvas shows a card with the ticket's state at the spot you clicked.
197-- Ctrl+click a widget, or a red card, to follow up on it. The new ticket names the widget and its file, where you clicked inside it, the prompt before, and every `decide`, `deviate` and `block` from that run. The widget keeps its spot and shows the new ticket's state until it's rebuilt.
198-- Drag a widget to move it. The app sends the drop to conveyord (`move`), which writes `canvas.json`.
199-- A prompt that asks for nothing, such as a keyboard mash, is a `block`: the card turns red and you rewrite it. An agent that guesses fills your library with stand-ins.
200-- The app restarts with `exec` on the path it read at launch. After cargo replaces the binary, `current_exe()` names the deleted file, so it can't be read again later.
201-- The library API is deliberately small (`api.rs`): a widget is a title, a size and `fn view(&Cx) -> El`. `Cx` holds the time and the tickets. Widgets display only, and may use `rune` and `std` only.
196+- Until the widget is built, its frame shows the prompt and the ticket's state where you clicked.
197+- **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.
198+- **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.
200+
201+#### The widget base: three layers, each changed its own way
202+
203+```
204+core (conveyor-app) placement: drag · hover · Ctrl+click · right-click menu (every control, always)
205+ capabilities = api::Act: maximize/restore · front/back · chrome · conversation
206+library (yours) frame.rs the base around every widget: title bar, buttons, badge, thread
207+ widgets/* content
208+canvas.json (data) per widget: x, y, z, maximized, chrome shown|hover|hidden, ticket history
209+```
210+
211+- **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.
212+- **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`.
215+- 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.
216+- 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.
202217 - `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.
203218 - The base image carries the pinned toolchain and a warm `~/.cache/conveyor-target`, so the agent's first preview build is incremental.
204219
crates/conveyor-app/src/acts.rs+31−0
@@ -0,0 +1,31 @@
1+//! 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}};
3+use serde_json::json;
4+
5+pub fn chrome(s: &str) -> Chrome {
6+ match s { "shown" => Chrome::Shown, "hidden" => Chrome::Hidden, _ => Chrome::Hover }
7+}
8+
9+fn chrome_name(c: Chrome) -> &'static str {
10+ match c { Chrome::Shown => "shown", Chrome::Hover => "hover", Chrome::Hidden => "hidden" }
11+}
12+
13+impl Host for State {
14+ fn act(&mut self, id: u32, a: Act) {
15+ self.menu = None;
16+ if a == Act::Notes {
17+ if !self.notes.remove(&id) { self.notes.insert(id); }
18+ return;
19+ }
20+ let (top, bottom) = self.snap.canvas.iter().fold((0, 0), |(t, b), p| (t.max(p.z + 1), b.min(p.z - 1)));
21+ let Some(p) = self.snap.canvas.iter_mut().find(|p| p.id == id) else { return };
22+ let set = match a {
23+ Act::Maximize | Act::Restore => { p.maximized = a == Act::Maximize; json!({"maximized": p.maximized}) }
24+ Act::Front => { p.z = top; json!({"z": top}) }
25+ Act::Back => { p.z = bottom; json!({"z": bottom}) }
26+ Act::Chrome(c) => { p.chrome = chrome_name(c).into(); json!({"chrome": p.chrome}) }
27+ Act::Notes => unreachable!(),
28+ };
29+ client::frame(id, set);
30+ }
31+}
crates/conveyor-app/src/canvas.rs+28−110
@@ -1,23 +1,28 @@
1-//! The canvas: widgets where they were asked for, a card for each widget still being built,
2-//! and the Ctrl+click prompt that asks for a new one.
3-use crate::{client::{self, Snapshot}, titlebar, widgets};
4-use rune::{Drag, El, Phase, TextEdit, TextStyle, Tx, Waker, col, el, text, text_input, tok};
5-use std::{path::{Path, PathBuf}, sync::{Arc, Mutex}, time::{Duration, SystemTime, UNIX_EPOCH}};
1+//! 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};
3+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}};
65
76 pub struct State {
8- snap: Snapshot,
7+ pub snap: Snapshot,
98 connected: bool,
10- pointer: (f32, f32),
11- /// Where the prompt is open, and the widget ticket it follows up on, if a card was clicked.
12- prompt_at: Option<(f32, f32, Option<u32>)>,
13- prompt: TextEdit,
9+ /// The pointer, in canvas points.
10+ pub pointer: (f32, f32),
11+ /// Where the prompt is open, and the widget it follows up on, if one was Ctrl+clicked.
12+ pub prompt_at: Option<(f32, f32, Option<u32>)>,
13+ pub prompt: TextEdit,
1414 inbox: Arc<Mutex<Option<Option<Snapshot>>>>,
1515 /// The binary at launch and its mtime. Read once: after cargo replaces it,
1616 /// current_exe() names the deleted file.
1717 exe: Option<PathBuf>,
1818 built: Option<SystemTime>,
1919 /// A widget's position when the drag on it started.
20- drag: Option<(f32, f32)>,
20+ pub drag: Option<(f32, f32)>,
21+ pub hovered: Option<u32>,
22+ /// Widgets whose conversation is open.
23+ pub notes: HashSet<u32>,
24+ /// A widget's right-click menu, and where.
25+ pub menu: Option<(u32, f32, f32)>,
2126 }
2227
2328 fn mtime(p: &Path) -> Option<SystemTime> {
@@ -25,7 +30,8 @@ fn mtime(p: &Path) -> Option<SystemTime> {
2530 }
2631
2732 pub fn init() -> State {
28- State { snap: Snapshot::default(), connected: false, pointer: (0.0, 0.0), prompt_at: None, prompt: TextEdit::new(""), inbox: Default::default(), exe: None, built: None, drag: None }
33+ 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 }
2935 }
3036
3137 /// Polls conveyord once a second on a thread. Every poll also re-renders, for clocks.
@@ -55,117 +61,29 @@ pub fn poll(s: &mut State, _t: f64, _tx: &mut Tx) -> bool {
5561 true
5662 }
5763
58-fn submit(s: &mut State, tx: &mut Tx) {
59- if let Some((x, y, about)) = s.prompt_at.take() {
60- let prompt = s.prompt.text.clone();
61- s.prompt = TextEdit::new("");
62- if !prompt.trim().is_empty() && client::widget(&prompt, x, y, about).is_none() {
63- eprintln!("conveyord isn't running; the prompt was not sent");
64- }
65- }
66- tx.blur();
67-}
68-
69-fn open_prompt(s: &mut State, x: f32, y: f32, about: Option<u32>) {
70- s.prompt_at = Some((x, y, about));
71- s.prompt = TextEdit::new("");
72- s.prompt.focused = true;
73-}
74-
75-/// Moves a widget with the pointer, and tells conveyord where it landed.
76-/// Ctrl+press instead opens a prompt about the widget.
77-fn drag(s: &mut State, id: u32, d: &Drag, tx: &Tx) {
78- let Some(p) = s.snap.canvas.iter_mut().find(|p| p.ticket == id) else { return };
79- match (d.phase, s.drag) {
80- (Phase::Down, _) if tx.mods().ctrl => { let (x, y) = (p.x + d.x, p.y + d.y); open_prompt(s, x, y, Some(id)) }
81- (Phase::Down, _) => s.drag = Some((p.x, p.y)),
82- (Phase::Move, Some((x, y))) => (p.x, p.y) = ((x + d.dx).max(0.0), (y + d.dy).max(0.0)),
83- (Phase::Up, Some((x, y))) => {
84- s.drag = None;
85- if d.cancelled() { (p.x, p.y) = (x, y) } else { client::move_to(id, p.x, p.y); }
86- }
87- _ => {}
88- }
89-}
90-
91-fn card(key: String, w: f32, h: f32) -> El {
92- let t = tok::theme(true);
93- col().key(key).w(w).h(h).radius(10.0).fill(t.card).padding(12.0).gap(6.0)
94-}
95-
96-fn state_color(state: &str) -> rune::Color {
97- if state == "failed" || state == "parked" { tok::accent(3, true) } else { tok::accent(0, true) }
98-}
99-
100-fn pending(id: u32, title: &str, state: &str) -> El {
101- let t = tok::theme(true);
102- let color = state_color(state);
103- card(format!("pending-{id}"), 260.0, 90.0).label(format!("widget #{id} {state}"))
104- .child(text(format!("#{id} · {state}")).font(tok::type_::LABEL).color(color))
105- .child(text(title.to_owned()).font(tok::type_::BODY).color(t.text).wrap())
106-}
107-
108-fn placed(s: &State, cx: &widgets::api::Cx) -> Vec<El> {
109- s.snap.canvas.iter().map(|p| {
110- let built = p.widget.as_deref().and_then(|w| widgets::ALL.iter().find(|(n, _)| *n == w));
111- let t = s.snap.tickets.iter().find(|t| t.project == "widgets" && t.id == p.ticket);
112- let el = match built {
113- Some((name, w)) => {
114- let card = card(format!("w-{}", p.ticket), w.size.0, w.size.1).label(format!("widget {name}")).child((w.view)(cx));
115- // A follow-up in flight: the widget stays, with its ticket's state on top.
116- match t.filter(|t| t.state != "done") {
117- Some(t) => card.child(text(format!("#{} · {}", t.id, t.state)).font(tok::type_::LABEL).color(state_color(&t.state))
118- .padding(4.0).radius(6.0).fill(tok::theme(true).bg).absolute(8.0, 8.0)),
119- None => card,
120- }
121- }
122- None => {
123- let state = match (&p.widget, t) { (Some(_), _) => "installing", (_, Some(t)) => t.state.as_str(), _ => "?" };
124- pending(p.ticket, t.map_or("", |t| t.title.as_str()), state)
125- }
126- };
127- let id = p.ticket;
128- el.absolute(p.x, p.y).on_drag(move |s: &mut State, d: &mut Drag, tx: &mut Tx| drag(s, id, d, tx))
129- }).collect()
130-}
131-
132-fn prompt_box(s: &State, x: f32, y: f32, about: Option<u32>) -> El {
133- let t = tok::theme(true);
134- let heading = match about.and_then(|a| s.snap.canvas.iter().find(|p| p.ticket == a)) {
135- Some(p) => format!("Change {}", p.widget.clone().unwrap_or_else(|| format!("#{}", p.ticket))),
136- None => "New widget".into(),
137- };
138- card("prompt".into(), 360.0, 120.0).absolute(x, y).focus_ring(2.0, 0.0, tok::accent(0, true))
139- .child(text(heading).font(tok::type_::LABEL).color(t.text_secondary))
140- .child(text_input(&s.prompt, TextStyle::new(14.0, 400.0)).key("prompt-input").label("Widget prompt").w_full().grow(1.0)
141- .padding(6.0).radius(6.0).fill(t.bg).color(t.text).placeholder("A clock with the date… Enter to build, Shift+Enter for a new line, Esc to cancel", t.text_secondary)
142- .on_edit(|s: &mut State| &mut s.prompt)
143- .on_submit(submit)
144- .on_input_key(|s: &mut State, e: &rune::KeyEvent, tx| {
145- if !matches!(e.key, rune::Key::Escape) { return false; }
146- s.prompt_at = None;
147- tx.blur();
148- true
149- }))
150-}
151-
152-pub fn view(s: &State, _: &mut rune::Cx<State>) -> El {
64+pub fn view(s: &State, rcx: &mut rune::Cx<State>) -> El {
15365 let t = tok::theme(true);
15466 let tickets: Vec<widgets::api::TicketInfo> = s.snap.tickets.iter()
15567 .map(|t| widgets::api::TicketInfo { project: t.project.clone(), id: t.id, state: t.state.clone(), title: t.title.clone() })
15668 .collect();
15769 let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64());
15870 let cx = widgets::api::Cx { now, tickets: &tickets };
71+ let area = rcx.layout("canvas").map_or((1400.0, 864.0), |r| (r[2], r[3]));
15972 let mut canvas = el().key("canvas").role("canvas").label("Canvas").w_full().grow(1.0).min_h(0.0).fill(t.bg)
16073 .on_pointer_move_local(|s: &mut State, e: rune::PointerEvent, tx: &mut Tx| { s.pointer = (e.x, e.y); tx.live_only(); })
16174 .on_press_tx(|s: &mut State, tx: &mut Tx| {
162- if tx.mods().ctrl { open_prompt(s, s.pointer.0, s.pointer.1, None) }
75+ s.menu = None;
76+ if tx.mods().ctrl { let at = s.pointer; prompt::open(s, at, None) }
16377 });
16478 if s.snap.canvas.is_empty() && s.prompt_at.is_none() {
16579 canvas = canvas.child(col().w_full().h_full().center().child(text("Ctrl+click anywhere to make a widget").color(t.text_secondary)));
16680 }
167- for e in placed(s, &cx) { canvas = canvas.child(e); }
168- if let Some((x, y, about)) = s.prompt_at { canvas = canvas.child(prompt_box(s, x, y, about)); }
81+ let mut order: Vec<_> = s.snap.canvas.iter().collect();
82+ // A widget with its conversation open draws on top, so the panel isn't covered.
83+ 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)); }
85+ if let Some((x, y, about)) = s.prompt_at { canvas = canvas.child(prompt::view(s, x, y, about)); }
86+ if let Some((id, x, y)) = s.menu { canvas = canvas.child(menu::view(s, id, x, y)); }
16987 let status = if s.connected { String::new() } else { "conveyord isn't running".into() };
17088 col().key("root").w_full().h_full().fill(t.bg).child(titlebar::bar(status)).child(canvas)
17189 }
crates/conveyor-app/src/client.rs+23−4
@@ -1,4 +1,5 @@
1-//! Talks to conveyord over its socket. The app holds no state of its own beyond what it shows.
1+//! Talks to conveyord over its socket. The app holds no state of its own beyond what it shows,
2+//! and everything it does is a request here, so a script can do the same.
23 use serde::Deserialize;
34 use serde_json::{Value, json};
45 use std::{io::{BufRead, BufReader, Write}, os::unix::net::UnixStream, path::PathBuf};
@@ -17,12 +18,27 @@ pub struct Ticket {
1718 pub state: String,
1819 }
1920
21+/// A widget on the canvas, with its frame settings and its conversation.
2022 #[derive(Deserialize, Clone)]
2123 pub struct Placed {
22- pub ticket: u32,
24+ pub id: u32,
2325 pub x: f32,
2426 pub y: f32,
27+ pub z: i32,
28+ pub maximized: bool,
29+ pub chrome: String,
2530 pub widget: Option<String>,
31+ /// The latest ticket's state and title.
32+ pub state: String,
33+ pub title: String,
34+ pub thread: Vec<Entry>,
35+}
36+
37+#[derive(Deserialize, Clone)]
38+pub struct Entry {
39+ pub ticket: u32,
40+ pub kind: String,
41+ pub text: String,
2642 }
2743
2844 fn call(req: Value) -> Option<Value> {
@@ -42,6 +58,9 @@ pub fn widget(prompt: &str, x: f32, y: f32, about: Option<u32>) -> Option<u32> {
4258 call(json!({"op": "widget", "prompt": prompt, "x": x, "y": y, "about": about}))?["id"].as_u64().map(|id| id as u32)
4359 }
4460
45-pub fn move_to(ticket: u32, x: f32, y: f32) {
46- call(json!({"op": "move", "ticket": ticket, "x": x, "y": y}));
61+/// Frame settings: any of x, y, z, maximized, chrome.
62+pub fn frame(id: u32, mut set: Value) {
63+ set["op"] = json!("frame");
64+ set["id"] = json!(id);
65+ call(set);
4766 }
crates/conveyor-app/src/main.rs+7−0
@@ -1,7 +1,11 @@
11 //! The conveyor app: a view over conveyord. A blank canvas; Ctrl+click anywhere and write a
22 //! prompt, and the widget it asks for is built as a ticket and appears where you clicked.
3+mod acts;
34 mod canvas;
45 mod client;
6+mod menu;
7+mod place;
8+mod prompt;
59 mod titlebar;
610 mod widgets {
711 include!(concat!(env!("OUT_DIR"), "/widgets.rs"));
@@ -9,6 +13,9 @@ mod widgets {
913
1014 use rune::{App, AppSpec, WindowOptions};
1115
16+/// The state frame buttons act on (see the library's api.rs).
17+pub type HostState = canvas::State;
18+
1219 fn main() {
1320 let spec = AppSpec { setup: Some(canvas::setup), poll: Some(canvas::poll), ..AppSpec::new("Conveyor", (1400.0, 900.0), canvas::init, canvas::view) };
1421 App::new(spec).window_options(WindowOptions { borderless: true, ..Default::default() }).run();
crates/conveyor-app/src/menu.rs+22−0
@@ -0,0 +1,22 @@
1+//! A widget's right-click menu: every frame control, even when its chrome is hidden or the
2+//! library's frame.rs has dropped a button.
3+use crate::{canvas::State, widgets::api::{Act, Chrome, Host}};
4+use rune::{El, Tx, col, row, text, tok};
5+
6+pub fn view(s: &State, id: u32, x: f32, y: f32) -> El {
7+ let t = tok::theme(true);
8+ let Some(p) = s.snap.canvas.iter().find(|p| p.id == id) else { return col() };
9+ let item = |key: &str, label: String, a: Act| {
10+ row().key(format!("menu-{key}")).w_full().h(30.0).center_y().px(12.0).radius(6.0).hover(t.hover).role("menuitem").label(label.clone())
11+ .on_press_tx(move |s: &mut State, _: &mut Tx| s.act(id, a)).child(text(label).font(tok::type_::BODY).color(t.text))
12+ };
13+ let mark = |c: &str| if p.chrome == c { "● " } else { " " };
14+ col().key("menu").role("menu").label("Widget").w(220.0).padding(6.0).radius(10.0).fill(t.card).border(1.0, t.hover).absolute(x, y)
15+ .child(if p.maximized { item("restore", "Restore".into(), Act::Restore) } else { item("maximize", "Maximize".into(), Act::Maximize) })
16+ .child(item("front", "Bring to front".into(), Act::Front))
17+ .child(item("back", "Send to back".into(), Act::Back))
18+ .child(item("notes", "Conversation".into(), Act::Notes))
19+ .child(item("shown", format!("{}Title bar: always", mark("shown")), Act::Chrome(Chrome::Shown)))
20+ .child(item("hover", format!("{}Title bar: on hover", mark("hover")), Act::Chrome(Chrome::Hover)))
21+ .child(item("hidden", format!("{}Title bar: hidden", mark("hidden")), Act::Chrome(Chrome::Hidden)))
22+}
crates/conveyor-app/src/place.rs+46−0
@@ -0,0 +1,46 @@
1+//! One widget on the canvas: where it is, the frame around it, and what the pointer does to it.
2+//! 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}}};
4+use rune::{Drag, El, Phase, Tx, col, el, text, tok};
5+use serde_json::json;
6+
7+/// A widget no ticket has built yet: its prompt, in the frame.
8+const PENDING: (f32, f32) = (280.0, 120.0);
9+
10+pub fn view(s: &State, p: &Placed, cx: &Cx, area: (f32, f32)) -> El {
11+ let built = p.widget.as_deref().and_then(|w| widgets::ALL.iter().find(|(n, _)| *n == w)).map(|(_, w)| w);
12+ 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),
15+ None => col().w_full().h_full().center().child(text(p.title.clone()).font(tok::type_::BODY).color(tok::theme(true).text).wrap()),
16+ };
17+ let thread: Vec<Entry> = p.thread.iter().map(|e| Entry { ticket: e.ticket, kind: e.kind.clone(), text: e.text.clone() }).collect();
18+ let f = Frame { id: p.id, title: built.map_or("Building…", |w| w.title), size, state: &p.state, thread: &thread,
19+ maximized: p.maximized, chrome: acts::chrome(&p.chrome), hovered: s.hovered == Some(p.id), notes: s.notes.contains(&p.id) };
20+ let id = p.id;
21+ let (x, y) = if p.maximized { (0.0, 0.0) } else { (p.x, p.y) };
22+ el().key(format!("w-{id}")).label(format!("widget {}", f.title)).w(size.0).h(size.1).absolute(x, y)
23+ .child(widgets::frame::frame(&f, content))
24+ .on_drag(move |s: &mut State, d: &mut Drag, tx: &mut Tx| drag(s, id, d, tx))
25+ .on_hover_change(move |s: &mut State, on: bool, _: &mut Tx| {
26+ if on { s.hovered = Some(id) } else if s.hovered == Some(id) { s.hovered = None }
27+ })
28+ .on_secondary_press_local(move |s: &mut State, e: rune::PointerEvent, _: &mut Tx| s.menu = Some((id, x + e.x, y + e.y)))
29+}
30+
31+/// Moves a widget with the pointer, and tells conveyord where it landed.
32+/// Ctrl+press instead opens a prompt about the widget.
33+fn drag(s: &mut State, id: u32, d: &Drag, tx: &Tx) {
34+ s.menu = None;
35+ let Some(p) = s.snap.canvas.iter_mut().find(|p| p.id == id) else { return };
36+ match (d.phase, s.drag) {
37+ (Phase::Down, _) if tx.mods().ctrl => { let at = s.pointer; prompt::open(s, at, Some(id)) }
38+ (Phase::Down, _) if !p.maximized => s.drag = Some((p.x, p.y)),
39+ (Phase::Move, Some((x, y))) => (p.x, p.y) = ((x + d.dx).max(0.0), (y + d.dy).max(0.0)),
40+ (Phase::Up, Some((x, y))) => {
41+ s.drag = None;
42+ if d.cancelled() { (p.x, p.y) = (x, y) } else { client::frame(id, json!({"x": p.x, "y": p.y})) }
43+ }
44+ _ => {}
45+ }
46+}
crates/conveyor-app/src/prompt.rs+41−0
@@ -0,0 +1,41 @@
1+//! The Ctrl+click prompt: a new widget where you clicked, or a follow-up on the one you clicked.
2+use crate::{canvas::State, client};
3+use rune::{El, TextEdit, TextStyle, Tx, col, text, text_input, tok};
4+
5+pub fn open(s: &mut State, (x, y): (f32, f32), about: Option<u32>) {
6+ s.menu = None;
7+ s.prompt_at = Some((x, y, about));
8+ s.prompt = TextEdit::new("");
9+ s.prompt.focused = true;
10+}
11+
12+fn submit(s: &mut State, tx: &mut Tx) {
13+ if let Some((x, y, about)) = s.prompt_at.take() {
14+ let prompt = s.prompt.text.clone();
15+ s.prompt = TextEdit::new("");
16+ if !prompt.trim().is_empty() && client::widget(&prompt, x, y, about).is_none() {
17+ eprintln!("conveyord isn't running; the prompt was not sent");
18+ }
19+ }
20+ tx.blur();
21+}
22+
23+pub fn view(s: &State, x: f32, y: f32, about: Option<u32>) -> El {
24+ let t = tok::theme(true);
25+ let heading = match about.and_then(|a| s.snap.canvas.iter().find(|p| p.id == a)) {
26+ Some(p) => format!("Follow up on {}", p.widget.clone().unwrap_or_else(|| format!("#{}", p.id))),
27+ None => "New widget".into(),
28+ };
29+ col().key("prompt").w(360.0).h(120.0).radius(10.0).fill(t.card).padding(12.0).gap(6.0).absolute(x, y).focus_ring(2.0, 0.0, tok::accent(0, true))
30+ .child(text(heading).font(tok::type_::LABEL).color(t.text_secondary))
31+ .child(text_input(&s.prompt, TextStyle::new(14.0, 400.0)).key("prompt-input").label("Widget prompt").w_full().grow(1.0)
32+ .padding(6.0).radius(6.0).fill(t.bg).color(t.text).placeholder("A clock with the date… Enter to send, Shift+Enter for a new line, Esc to cancel", t.text_secondary)
33+ .on_edit(|s: &mut State| &mut s.prompt)
34+ .on_submit(submit)
35+ .on_input_key(|s: &mut State, e: &rune::KeyEvent, tx| {
36+ if !matches!(e.key, rune::Key::Escape) { return false; }
37+ s.prompt_at = None;
38+ tx.blur();
39+ true
40+ }))
41+}
crates/conveyor/src/agent.rs+12−1
@@ -27,7 +27,8 @@ fn run(p: &Project, id: u32) -> Result<String, String> {
2727 let vm = Vm::up(&name, 8192)?;
2828 give_agent_config(&vm)?;
2929 vm.sh("mkdir -p ~/.local/bin ~/.conveyor && cat > ~/.local/bin/conveyor && chmod +x ~/.local/bin/conveyor",
30- &std::fs::read(std::env::current_exe().map_err(|e| e.to_string())?).map_err(|e| e.to_string())?)?;
30+ // /proc/self/exe still reads after cargo replaces the binary; current_exe() would not.
31+ &std::fs::read("/proc/self/exe").map_err(|e| e.to_string())?)?;
3132 vm.sh("cat > ~/.conveyor/rules.md", RULES.as_bytes())?;
3233
3334 note("pushing the repo");
@@ -52,6 +53,9 @@ fn run(p: &Project, id: u32) -> Result<String, String> {
5253 agent.stdin.take().unwrap().write_all(format!("# #{id} {}\n\n{}", t.title, t.body).as_bytes()).map_err(|e| e.to_string())?;
5354 let out = agent.wait_with_output().map_err(|e| e.to_string())?;
5455 let outcome = verbs.finish();
56+ if let Some(reply) = reply(&store::dir(&p.slug, id).join("stream.jsonl")) {
57+ store::event(&p.slug, id, json!({"kind": "reply", "text": reply}));
58+ }
5559 if !out.status.success() {
5660 note(&format!("agent exited {}: {}", out.status, String::from_utf8_lossy(&out.stderr).trim()));
5761 }
@@ -73,6 +77,13 @@ fn run(p: &Project, id: u32) -> Result<String, String> {
7377 })
7478 }
7579
80+/// The agent's final message, from the end of its stream.
81+fn reply(stream: &Path) -> Option<String> {
82+ let s = std::fs::read_to_string(stream).ok()?;
83+ s.lines().rev().filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
84+ .find(|v| v["type"] == "result")?["result"].as_str().map(String::from)
85+}
86+
7687 fn give_agent_config(vm: &Vm) -> Result<(), String> {
7788 let home = std::env::var("HOME").map_err(|e| e.to_string())?;
7889 let files: Vec<&str> = AGENT_FILES.into_iter().filter(|f| Path::new(&home).join(f).exists()).collect();
crates/conveyor/src/canvas.rs+46−12
@@ -1,19 +1,41 @@
1-//! Where widgets sit on the app's canvas: canvas.json, one entry per widget ticket.
1+//! Where widgets sit on the app's canvas, and how their frames are set: canvas.json.
22 use crate::paths;
33 use serde::{Deserialize, Serialize};
4+use serde_json::Value;
45 use std::{fs, sync::Mutex};
56
67 static LOCK: Mutex<()> = Mutex::new(());
78
89 #[derive(Serialize, Deserialize, Clone)]
910 pub struct Placed {
10- pub ticket: u32,
11+ /// Stable for the widget's life: its first ticket.
12+ pub id: u32,
13+ /// Every ticket that built or changed it, oldest first. The last is current.
14+ pub tickets: Vec<u32>,
1115 pub x: f32,
1216 pub y: f32,
13- /// The widget's name in the library, once its ticket is done.
17+ /// Stacking order: higher draws on top.
18+ #[serde(default)]
19+ pub z: i32,
20+ #[serde(default)]
21+ pub maximized: bool,
22+ /// The frame's chrome: "shown", "hover" or "hidden".
23+ #[serde(default = "hover")]
24+ pub chrome: String,
25+ /// The widget's name in the library, once a ticket has built it.
1426 pub widget: Option<String>,
1527 }
1628
29+fn hover() -> String {
30+ "hover".into()
31+}
32+
33+impl Placed {
34+ pub fn current(&self) -> u32 {
35+ *self.tickets.last().unwrap()
36+ }
37+}
38+
1739 pub fn load() -> Vec<Placed> {
1840 fs::read_to_string(paths::canvas()).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
1941 }
@@ -25,19 +47,31 @@ fn update(f: impl FnOnce(&mut Vec<Placed>)) {
2547 fs::write(paths::canvas(), serde_json::to_string_pretty(&all).unwrap()).unwrap();
2648 }
2749
28-pub fn place(p: Placed) {
29- update(|all| all.push(p));
50+pub fn place(ticket: u32, x: f32, y: f32) {
51+ update(|all| {
52+ let z = all.iter().map(|p| p.z + 1).max().unwrap_or(0);
53+ all.push(Placed { id: ticket, tickets: vec![ticket], x, y, z, maximized: false, chrome: hover(), widget: None })
54+ });
3055 }
3156
32-pub fn set_widget(ticket: u32, widget: &str) {
33- update(|all| all.iter_mut().filter(|p| p.ticket == ticket).for_each(|p| p.widget = Some(widget.into())));
57+/// A follow-up ticket becomes the widget's current one.
58+pub fn follow(id: u32, ticket: u32) {
59+ update(|all| all.iter_mut().filter(|p| p.id == id).for_each(|p| p.tickets.push(ticket)));
3460 }
3561
36-pub fn move_to(ticket: u32, x: f32, y: f32) {
37- update(|all| all.iter_mut().filter(|p| p.ticket == ticket).for_each(|p| (p.x, p.y) = (x, y)));
62+pub fn set_widget(ticket: u32, widget: &str) {
63+ update(|all| all.iter_mut().filter(|p| p.current() == ticket).for_each(|p| p.widget = Some(widget.into())));
3864 }
3965
40-/// A follow-up ticket takes over the widget's spot from the ticket before it.
41-pub fn retarget(from: u32, to: u32) {
42- update(|all| all.iter_mut().filter(|p| p.ticket == from).for_each(|p| p.ticket = to));
66+/// Merges the frame settings given (x, y, z, maximized, chrome) into one widget.
67+pub fn set_frame(id: u32, v: &Value) {
68+ update(|all| {
69+ for p in all.iter_mut().filter(|p| p.id == id) {
70+ let mut j = serde_json::to_value(&*p).unwrap();
71+ for k in ["x", "y", "z", "maximized", "chrome"] {
72+ if !v[k].is_null() { j[k] = v[k].clone(); }
73+ }
74+ if let Ok(n) = serde_json::from_value(j) { *p = n; }
75+ }
76+ });
4377 }
crates/conveyor/src/library.rs+48−29
@@ -1,20 +1,33 @@
11 //! The widget library: the `widgets` project. A prompt from the canvas becomes a ticket there;
2-//! a done ticket's widget is merged into the library and the app is rebuilt with it.
3-use crate::{agent::git, canvas::{self, Placed}, paths, store::{self, Project}, vm};
2+//! a done ticket's change is merged into the library and the app is rebuilt with it.
3+use crate::{agent::git, canvas::{self, Placed}, paths, store::{self, Project}, thread, vm};
44 use serde_json::json;
5-use std::{process::Command, sync::Mutex};
5+use std::{fs, process::Command, sync::Mutex};
66
77 pub const SLUG: &str = "widgets";
88 static BUILD: Mutex<()> = Mutex::new(());
99
10-/// Creates the library from conveyor's template on first run.
10+/// Conveyor's side of the library: kept in step with the template on every start.
11+const OWNED: [&str; 8] = ["api.rs", "gen.rs", "CLAUDE.md", "Cargo.toml", "rust-toolchain.toml",
12+ "preview/Cargo.toml", "preview/build.rs", "preview/src/main.rs"];
13+/// The user's side: what a ticket may change.
14+const USERS: [&str; 2] = ["frame.rs", "widgets/"];
15+
16+const COMMIT: [&str; 4] = ["-c", "user.name=conveyor", "-c", "user.email=conveyor@localhost"];
17+
18+/// Creates the library from conveyor's template on first run, and updates conveyor's files in it.
1119 pub fn ensure() -> Result<(), String> {
12- let lib = paths::library();
20+ let (lib, tpl) = (paths::library(), paths::source().join("templates/library"));
1321 if !lib.exists() {
14- vm::run(Command::new("cp").arg("-r").arg(paths::source().join("templates/library")).arg(&lib))?;
22+ vm::run(Command::new("cp").arg("-r").arg(&tpl).arg(&lib))?;
1523 git(&lib, "", &["init", "-q", "-b", "main"])?;
16- git(&lib, "", &["add", "."])?;
17- git(&lib, "", &["-c", "user.name=conveyor", "-c", "user.email=conveyor@localhost", "commit", "-qm", "Widget library"])?;
24+ }
25+ for f in OWNED.into_iter().filter(|f| fs::read(tpl.join(f)).ok() != fs::read(lib.join(f)).ok()) {
26+ fs::copy(tpl.join(f), lib.join(f)).map_err(|e| e.to_string())?;
27+ }
28+ git(&lib, "", &["add", "-A"])?;
29+ if !git(&lib, "", &["status", "--porcelain"])?.is_empty() {
30+ git(&lib, "", &[&COMMIT[..], &["commit", "-qm", "Conveyor's library files"]].concat())?;
1831 }
1932 if store::project(SLUG).is_none() {
2033 store::save_project(&Project { slug: SLUG.into(), path: lib, slots: 2, auto_merge: true, library: true });
@@ -23,48 +36,45 @@ pub fn ensure() -> Result<(), String> {
2336 }
2437
2538 /// A prompt written on the canvas at (x, y): a ready ticket, and a placeholder where it was clicked.
26-/// With `about`, the user Ctrl+clicked the card of that ticket: the new ticket changes its widget.
39+/// With `about`, the user Ctrl+clicked that widget: the new ticket follows up on it.
2740 pub fn request(prompt: &str, x: f32, y: f32, about: Option<u32>) -> u32 {
2841 let title: String = prompt.lines().next().unwrap_or("widget").chars().take(70).collect();
29- let placed = about.and_then(|a| canvas::load().into_iter().find(|p| p.ticket == a));
42+ let placed = about.and_then(|a| canvas::load().into_iter().find(|p| p.id == a));
3043 let context = match &placed {
3144 Some(p) => follow_up(p, x - p.x, y - p.y),
3245 None => format!("The user asked for this widget by clicking at ({x:.0}, {y:.0}) on the canvas."),
3346 };
3447 let id = store::create(SLUG, &title, &format!("{prompt}\n\n---\n\n{context}"), "ready");
3548 match placed {
36- Some(p) => canvas::retarget(p.ticket, id),
37- None => canvas::place(Placed { ticket: id, x, y, widget: None }),
49+ Some(p) => canvas::follow(p.id, id),
50+ None => canvas::place(id, x, y),
3851 }
3952 id
4053 }
4154
42-/// What the user clicked: the widget, the ticket before this one, and what that run left out.
55+/// What the user clicked, and the conversation behind it so far.
4356 fn follow_up(p: &Placed, x: f32, y: f32) -> String {
44- let prev = store::ticket(SLUG, p.ticket).map(|t| (t.state, t.body)).unwrap_or_default();
4557 let what = match &p.widget {
4658 Some(w) => format!("The user Ctrl+clicked the `{w}` widget, at ({x:.0}, {y:.0}) inside it. Change `widgets/{w}.rs` and keep its name."),
47- None => format!("The user Ctrl+clicked the card of ticket #{}, which ended `{}` without a widget. Build what it asked for, corrected by this prompt.", p.ticket, prev.0),
59+ None => "The user Ctrl+clicked a widget that no ticket has built yet. Build what the conversation asks for.".into(),
4860 };
49- let left_out: String = store::events(SLUG, p.ticket).iter()
50- .filter(|e| matches!(e["verb"].as_str(), Some("deviate" | "block" | "decide")))
51- .map(|e| format!("- {}: {} {}\n", e["verb"].as_str().unwrap_or(""), e["args"]["text"].as_str().or(e["args"]["reason"].as_str()).unwrap_or(""),
52- e["args"]["recommend"].as_str().map(|r| format!("(recommended: {r})")).unwrap_or_default()))
61+ let history: String = thread::of(&p.tickets).iter()
62+ .map(|e| format!("- #{} {}: {}\n", e["ticket"], e["kind"].as_str().unwrap_or(""), e["text"].as_str().unwrap_or("").replace('\n', "\n ")))
5363 .collect();
54- let quoted: String = prev.1.lines().map(|l| format!("> {l}\n")).collect();
55- format!("{what}\n\nThe ticket before this one, #{}:\n\n{quoted}\nWhat its run decided or left out:\n\n{}", p.ticket,
56- if left_out.is_empty() { "- nothing recorded\n".into() } else { left_out })
64+ format!("{what}\n\nThe conversation so far, oldest first:\n\n{history}")
5765 }
5866
5967 /// Merges a done widget ticket into the library, then rebuilds the app with it.
6068 pub fn install(p: &Project, id: u32, branch: &str) -> Result<(), String> {
61- let changed = git(&p.path, "", &["diff", "--name-only", "--diff-filter=AM", &format!("main...{branch}"), "--", "widgets/"])?;
62- let widget = changed.lines().find_map(|f| f.strip_prefix("widgets/")?.strip_suffix(".rs")).map(String::from)
63- .ok_or("the branch changes no widgets/<name>.rs")?;
64- git(&p.path, "", &["-c", "user.name=conveyor", "-c", "user.email=conveyor@localhost", "merge", "-q", "--no-edit", branch])?;
65- store::event(SLUG, id, json!({"kind": "conveyor", "msg": format!("merged widget {widget}; rebuilding the app")}));
69+ let changed = git(&p.path, "", &["diff", "--name-only", &format!("main...{branch}")])?;
70+ if let Some(f) = changed.lines().find(|f| !USERS.iter().any(|u| f.starts_with(u))) {
71+ return Err(format!("the branch changes {f}, which is conveyor's; only frame.rs and widgets/ are the library's"));
72+ }
73+ let widget = changed.lines().find_map(|f| f.strip_prefix("widgets/")?.strip_suffix(".rs")).map(String::from);
74+ git(&p.path, "", &[&COMMIT[..], &["merge", "-q", "--no-edit", branch]].concat())?;
75+ store::event(SLUG, id, json!({"kind": "conveyor", "msg": "merged; rebuilding the app"}));
6676 rebuild_app()?;
67- canvas::set_widget(id, &widget);
77+ if let Some(w) = widget { canvas::set_widget(id, &w); }
6878 Ok(())
6979 }
7080
@@ -75,7 +85,16 @@ fn rebuild_app() -> Result<(), String> {
7585 .args(["build", "--release", "-q", "-p", "conveyor-app"])).map(|_| ())
7686 }
7787
88+/// Everything the app shows: tickets, and each widget with its frame and its thread.
7889 pub fn snapshot() -> serde_json::Value {
7990 let tickets: Vec<_> = store::projects().iter().flat_map(|p| store::tickets(&p.slug)).collect();
80- json!({"tickets": tickets, "canvas": canvas::load()})
91+ let canvas: Vec<_> = canvas::load().into_iter().map(|p| {
92+ let t = store::ticket(SLUG, p.current());
93+ let mut v = serde_json::to_value(&p).unwrap();
94+ v["state"] = json!(t.as_ref().map_or("", |t| t.state.as_str()));
95+ v["title"] = json!(t.as_ref().map_or("", |t| t.title.as_str()));
96+ v["thread"] = json!(thread::of(&p.tickets));
97+ v
98+ }).collect();
99+ json!({"tickets": tickets, "canvas": canvas})
81100 }
crates/conveyor/src/main.rs+6−0
@@ -6,6 +6,7 @@ mod library;
66 mod paths;
77 mod server;
88 mod store;
9+mod thread;
910 mod verbs;
1011 mod vm;
1112
@@ -16,6 +17,7 @@ const USAGE: &str = "usage:
1617 conveyor project SLUG PATH [SLOTS] add a project
1718 conveyor ticket SLUG TITLE [BODY] add a ready ticket
1819 conveyor ls list tickets
20+ conveyor call JSON one request to conveyord, as the app sends it
1921 conveyor note|decide|deviate|block|done ... inside a ticket's VM";
2022
2123 fn main() {
@@ -34,6 +36,10 @@ fn main() {
3436 0
3537 }
3638 "ticket" if !a(2).is_empty() => print(server::call(json!({"op": "ticket", "project": a(1), "title": a(2), "body": a(3)}))),
39+ "call" if !a(1).is_empty() => match serde_json::from_str(a(1)) {
40+ Ok(req) => print(server::call(req)),
41+ Err(e) => { eprintln!("not JSON: {e}"); 2 }
42+ },
3743 "ls" => {
3844 for p in store::projects() {
3945 for t in store::tickets(&p.slug) {
crates/conveyor/src/server.rs+3−4
@@ -2,7 +2,7 @@
22 //! {"op":"state"} tickets and canvas
33 //! {"op":"widget","prompt":"…","x":10,"y":20} a widget ticket, placed on the canvas
44 //! + "about":3 …or a follow-up on the widget ticket #3 placed
5-//! {"op":"move","ticket":1,"x":10,"y":20} a widget dragged on the canvas
5+//! {"op":"frame","id":1,"x":10,"maximized":true} any of x, y, z, maximized, chrome
66 //! {"op":"ticket","project":"…","title":"…","body":"…"}
77 use crate::{canvas, library, paths, store};
88 use serde_json::{Value, json};
@@ -34,9 +34,8 @@ fn handle(r: &Value) -> Value {
3434 let f = |k: &str| r[k].as_f64().unwrap_or(0.0) as f32;
3535 json!({"id": library::request(s("prompt").trim(), f("x"), f("y"), r["about"].as_u64().map(|a| a as u32))})
3636 }
37- "move" => {
38- let f = |k: &str| r[k].as_f64().unwrap_or(0.0) as f32;
39- canvas::move_to(r["ticket"].as_u64().unwrap_or(0) as u32, f("x"), f("y"));
37+ "frame" => {
38+ canvas::set_frame(r["id"].as_u64().unwrap_or(0) as u32, r);
4039 json!({"ok": true})
4140 }
4241 "ticket" if store::project(s("project")).is_some() => json!({"id": store::create(s("project"), s("title"), s("body"), "ready")}),
crates/conveyor/src/thread.rs+26−0
@@ -0,0 +1,26 @@
1+//! The conversation behind a widget, oldest first: each prompt, what the agent decided or left
2+//! out, and its reply. The app shows it in the widget's frame, so the loop closes there.
3+use crate::{library::SLUG, store};
4+use serde_json::{Value, json};
5+
6+pub fn of(tickets: &[u32]) -> Vec<Value> {
7+ let mut out = vec![];
8+ for &id in tickets {
9+ let entry = |kind: &str, text: String| json!({"ticket": id, "kind": kind, "text": text});
10+ if let Some(t) = store::ticket(SLUG, id) {
11+ out.push(entry("prompt", t.body.split("\n\n---\n\n").next().unwrap_or("").trim().into()));
12+ }
13+ for e in store::events(SLUG, id) {
14+ let a = |k: &str| e["args"][k].as_str().unwrap_or("").to_owned();
15+ match (e["kind"].as_str(), e["verb"].as_str()) {
16+ (Some("verb"), Some("decide")) => out.push(entry("decide", format!("{} — {}", a("text"), a("why")))),
17+ (Some("verb"), Some("deviate")) => out.push(entry("deviate", format!("{} — recommends: {}", a("text"), a("recommend")))),
18+ (Some("verb"), Some("block")) => out.push(entry("block", format!("{} — recommends: {}", a("reason"), a("recommend")))),
19+ (Some("reply"), _) => out.push(entry("reply", e["text"].as_str().unwrap_or("").into())),
20+ (Some("error"), _) => out.push(entry("error", e["msg"].as_str().unwrap_or("").into())),
21+ _ => {}
22+ }
23+ }
24+ }
25+ out
26+}
templates/library/CLAUDE.md+24−10
@@ -1,14 +1,26 @@
11 # Widget library
22
3-This repo is the user's widget library. Each ticket asks for one widget, in the user's own words. The conveyor app shows the widget on the user's canvas, at the spot they clicked.
3+This repo is the user's widget library. Each ticket is the user's words, typed on their canvas: a new widget, or a follow-up on one they Ctrl+clicked. The conveyor app shows each widget in a frame, where they clicked.
44
5-## If it isn't a widget request
5+## What's yours to change
66
7-If the ticket's words don't describe something to show, such as a keyboard mash or a stray word, don't guess a widget. Run `conveyor block --reason "<what's unclear>" --recommend "<what you'd build if they meant something>"` and stop. The card turns red on the user's canvas, and the user rewrites the prompt.
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.
89
9-## Make the widget
10+Everything else is conveyor's (`api.rs`, `gen.rs`, `preview/`, this file). A branch that changes those is rejected, so don't.
1011
11-1. 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/`.
12+## When to block instead
13+
14+Run `conveyor block --reason "<...>" --recommend "<...>"` and stop, without guessing, when:
15+
16+- 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.
20+
21+## Make or change the widget
22+
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.
1224 2. Write `widgets/<name>.rs`. Copy this shape:
1325
1426 ```rust
@@ -23,20 +35,22 @@ If the ticket's words don't describe something to show, such as a keyboard mash
2335 }
2436 ```
2537
26-3. Read `api.rs` for the data a widget can use. Widgets are display-only: no handlers, no state, no new dependencies. Only `rune` and `std` are available. The app re-renders every second, and `cx.now` is the time.
27-4. Use Rune's dark theme (`tok::theme(true)`) so the widget matches the app. The app draws the card around it, so don't add one.
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.
2840
2941 ## Check it
3042
3143 ```sh
3244 cargo build --release -p preview
33-cargo run --release -p preview -- <name> --snap /tmp/<name>.png --tree /tmp/<name>.json --size 600x400
45+cargo run --release -p preview -- <name> --snap /tmp/<name>.png --tree /tmp/<name>.json --size 900x500
3446 ```
3547
36-Look at the PNG, and fix the widget until it shows what the ticket asks for. `--tree` lists every element with its rect, so use it to catch clipped or overflowing content.
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.
3749
3850 Rune's docs are in the cargo git checkout: `~/.cargo/git/checkouts/rune-*/*/crates/rune/README.md`.
3951
4052 ## Finish
4153
42-Commit only `widgets/<name>.rs`, then run `conveyor done "<name>: <one line on what it shows>"`.
54+Commit only what you changed of `widgets/` and `frame.rs`, then run `conveyor done "<name>: <one line>"`.
55+
56+Your last message is shown to the user in the widget's conversation panel, next to their prompt. Keep it to a few short lines: what they'll see, and anything they should know. No headings, no diagrams.
templates/library/api.rs+61−6
@@ -1,10 +1,10 @@
1-//! The widget API, shared by the conveyor app and the preview. Widgets are views over a
2-//! snapshot of conveyor's state. They are display-only: no handlers, no state of their own.
3-use rune::El;
1+//! The contract between this library and conveyor. Conveyor owns this file and replaces it
2+//! when it changes. The library's own code is frame.rs and widgets/.
3+use rune::{El, Tx};
44
55 /// What a widget can read. The app fills it from conveyord; the preview with sample data.
66 pub struct Cx<'a> {
7- /// Unix time in seconds. The app re-renders widgets every second.
7+ /// Unix time in seconds. The app re-renders every second.
88 pub now: f64,
99 pub tickets: &'a [TicketInfo],
1010 }
@@ -16,10 +16,65 @@ pub struct TicketInfo {
1616 pub title: String,
1717 }
1818
19-/// Each widget file declares `pub const WIDGET: Widget`.
19+/// 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.
2021 pub struct Widget {
2122 pub title: &'static str,
22- /// Width and height in points. The app gives the widget exactly this box.
23+ /// Width and height in points when not maximized. Lay out to fill whatever box you get.
2324 pub size: (f32, f32),
2425 pub view: fn(&Cx) -> El,
2526 }
27+
28+/// One widget on the canvas, as its frame sees it. frame.rs draws it.
29+pub struct Frame<'a> {
30+ pub id: u32,
31+ pub title: &'a str,
32+ /// The box the frame fills, in points.
33+ pub size: (f32, f32),
34+ /// The state of the widget's latest ticket: ready, running, done, parked, failed.
35+ pub state: &'a str,
36+ /// The conversation behind the widget, oldest first.
37+ pub thread: &'a [Entry],
38+ pub maximized: bool,
39+ pub chrome: Chrome,
40+ pub hovered: bool,
41+ /// The thread is open.
42+ pub notes: bool,
43+}
44+
45+/// One step of a widget's conversation. `kind` is one of: prompt (the user's words),
46+/// 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).
48+pub struct Entry {
49+ pub ticket: u32,
50+ pub kind: String,
51+ pub text: String,
52+}
53+
54+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
55+pub enum Chrome { Shown, Hover, Hidden }
56+
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.
59+#[derive(Clone, Copy, PartialEq, Debug)]
60+pub enum Act {
61+ /// Fill the canvas, or go back to its own size and place.
62+ Maximize,
63+ Restore,
64+ /// Draw above, or below, every other widget.
65+ Front,
66+ Back,
67+ Chrome(Chrome),
68+ /// Open or close the thread.
69+ Notes,
70+}
71+
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+
77+/// 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)
80+}
templates/library/frame.rs+79−0
@@ -0,0 +1,79 @@
1+//! The base every widget sits in: its chrome, its buttons, and the conversation behind it.
2+//! This file is yours: change how every widget is framed by changing it.
3+use super::api::*;
4+use rune::{El, ScrollSpec, col, el, row, text, tok};
5+
6+pub fn frame(f: &Frame, content: El) -> El {
7+ let t = tok::theme(true);
8+ let mut card = col().w_full().h_full().radius(if f.maximized { 0.0 } else { 10.0 }).fill(if f.maximized { t.bg } else { t.card })
9+ .padding(if f.maximized { 0.0 } else { 12.0 }).child(content);
10+ if f.chrome == Chrome::Shown || (f.chrome == Chrome::Hover && f.hovered) {
11+ card = card.child(bar(f).absolute(0.0, 0.0));
12+ } else if let Some(b) = badge(f) {
13+ card = card.child(b.absolute(8.0, 8.0));
14+ }
15+ if f.notes {
16+ let x = if f.maximized { f.size.0 - 340.0 } else { f.size.0 + 8.0 };
17+ card = card.child(notes(f).absolute(x, if f.maximized { 44.0 } else { 0.0 }));
18+ }
19+ card
20+}
21+
22+fn button(f: &Frame, key: &str, glyph: &str, label: &str, a: Act) -> El {
23+ let t = tok::theme(true);
24+ row().key(format!("{key}-{}", f.id)).w(28.0).h(24.0).center().radius(6.0).hover(t.hover).role("button").label(label)
25+ .on_press_tx(act(f.id, a)).child(text(glyph.to_owned()).color(t.text))
26+}
27+
28+/// Title and buttons, over the top of the widget.
29+fn bar(f: &Frame) -> El {
30+ let t = tok::theme(true);
31+ let (glyph, label, a) = if f.maximized { ("❐", "Restore", Act::Restore) } else { ("□", "Maximize", Act::Maximize) };
32+ row().w_full().h(32.0).center_y().px(10.0).gap(2.0).fill(t.card).radius(10.0)
33+ .child(text(f.title.to_owned()).font(tok::type_::LABEL).color(t.text_secondary))
34+ .child(el().w(6.0))
35+ .child(badge(f).unwrap_or_else(el))
36+ .child(el().grow(1.0))
37+ .child(button(f, "notes", "≡", "Conversation", Act::Notes))
38+ .child(button(f, "back", "↓", "Send to back", Act::Back))
39+ .child(button(f, "max", glyph, label, a))
40+}
41+
42+fn color(kind: &str) -> rune::Color {
43+ let t = tok::theme(true);
44+ match kind {
45+ "block" | "error" => tok::accent(3, true),
46+ "deviate" => tok::accent(2, true),
47+ "prompt" => t.text,
48+ _ => t.text_secondary,
49+ }
50+}
51+
52+/// While a ticket runs, or when its run needs a look, a pill says so without hovering.
53+fn badge(f: &Frame) -> Option<El> {
54+ let t = tok::theme(true);
55+ let latest = f.thread.last().map_or(0, |e| e.ticket);
56+ let flagged = f.thread.iter().filter(|e| e.ticket == latest && matches!(e.kind.as_str(), "deviate" | "block" | "error")).count();
57+ let label = match f.state {
58+ "done" if flagged > 0 && !f.notes => format!("{flagged} to read"),
59+ "done" => return None,
60+ s => s.to_owned(),
61+ };
62+ let c = if matches!(f.state, "parked" | "failed") { tok::accent(3, true) } else if flagged > 0 { tok::accent(2, true) } else { tok::accent(0, true) };
63+ Some(row().key(format!("badge-{}", f.id)).padding(4.0).px(8.0).radius(8.0).fill(t.bg).role("button").label("Conversation")
64+ .on_press_tx(act(f.id, Act::Notes)).child(text(label).font(tok::type_::LABEL).color(c)))
65+}
66+
67+/// The conversation: your prompts, and what the agent chose, changed, couldn't do and said.
68+fn notes(f: &Frame) -> El {
69+ let t = tok::theme(true);
70+ let mut list = col().gap(10.0).padding(12.0).w_full();
71+ for e in f.thread {
72+ let who = match e.kind.as_str() { "prompt" => "you".to_owned(), "reply" => "agent".to_owned(), k => k.to_owned() };
73+ list = list.child(col().gap(2.0).w_full()
74+ .child(text(format!("#{} {who}", e.ticket)).font(tok::type_::LABEL).color(color(&e.kind)))
75+ .child(text(e.text.clone()).font(tok::type_::BODY).color(if e.kind == "prompt" { t.text } else { t.text_secondary }).wrap()));
76+ }
77+ col().key(format!("thread-{}", f.id)).w(320.0).h(f.size.1.max(240.0)).radius(10.0).fill(t.card).border(1.0, t.hover)
78+ .child(col().w_full().h_full().min_h(0.0).scroll(ScrollSpec { stick_bottom: true }).child(list))
79+}
templates/library/gen.rs+4−2
@@ -1,4 +1,5 @@
1-// Writes $OUT_DIR/widgets.rs: the API module, one module per widgets/<name>.rs, and ALL.
1+// Writes $OUT_DIR/widgets.rs: the API, the frame, one module per widgets/<name>.rs, and ALL.
2+// The including crate defines `HostState: api::Host`, the state frame buttons act on.
23 // Shared by the app's and the preview's build.rs with include!, so keep it dependency free.
34 fn generate_widgets(lib: &std::path::Path) {
45 let dir = lib.join("widgets");
@@ -8,7 +9,8 @@ fn generate_widgets(lib: &std::path::Path) {
89 .filter_map(|e| { let p = e.path(); (p.extension()? == "rs").then_some(p.file_stem()?.to_str()?.to_owned()) })
910 .collect();
1011 names.sort();
11- let mut out = format!("#[allow(dead_code)]\n#[path = {:?}] pub mod api;\n", lib.join("api.rs"));
12+ println!("cargo:rerun-if-changed={}", lib.join("frame.rs").display());
13+ let mut out = format!("#[allow(dead_code)]\n#[path = {:?}] pub mod api;\n#[path = {:?}] pub mod frame;\n", lib.join("api.rs"), lib.join("frame.rs"));
1214 for n in &names { out += &format!("#[path = {:?}] pub mod {n};\n", dir.join(format!("{n}.rs"))); }
1315 out += "pub const ALL: &[(&str, &api::Widget)] = &[";
1416 for n in &names { out += &format!("({n:?}, &{n}::WIDGET), "); }
templates/library/preview/src/main.rs+35−10
@@ -1,19 +1,37 @@
1-//! Renders one widget on its own, with sample data, so it can be checked headless:
2-//! cargo run --release -p preview -- <name> --snap /tmp/<name>.png --tree /tmp/<name>.json --size 600x400
1+//! Renders one widget in its frame, with sample data, so it can be checked headless:
2+//! 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.
34 mod widgets {
45 include!(concat!(env!("OUT_DIR"), "/widgets.rs"));
56 }
67
7-use rune::{AppSpec, El, col, text, tok};
8-use widgets::api::{Cx, TicketInfo};
8+use rune::{AppSpec, El, col, el, text, tok};
Cut short: this commit's diff is over 1000 lines.