xonecas.io
8447
Co

conveyor / commit 5df81e1

Builder v4: agents see the app, picks are elements, the API covers what spike 5 hit

Builder tool:
- Ctrl+click picks the deepest keyed element inside the widget, outlines it,
  and sends its key path; CLAUDE.md asks widgets to key what users point at.
- On submit the app saves its data and the click beside its instance state;
  conveyord attaches that state to the build ticket, and `preview --state`
  replays the user's window with the click outlined, before and after a change.

API (api.rs):
- Tickets carry body, created/since times, attached files and conversation.
- View::update (writable state per frame) and View::event (window-wide paste,
  pasted images saved as PNG, and file drops).
- set_state shows the move at once; new_ticket attaches files; add_project
  and set_slots; native folder and file dialogs.

conveyord:
- Ticket files/ travel into the agent's VM at ~/ticket/files.
- `project` op adds a project (making the folder and repo) or sets slots.
- `set` refuses moves into or out of running: a second play press on a
  running ticket started a second worker and VM.
- Build titles end on a word.

Co-Authored-By: Claude Opus 5.5

sacenox2026-11-09 5df81e1a4452f0242a9e204512f45df521f4e424 parent 18c4fd5

20 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.

Cargo.lock+27−0
@@ -706,6 +706,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
706706 checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
707707 dependencies = [
708708 "bitflags 2.13.2",
709+ "block2 0.6.2",
710+ "libc",
709711 "objc2 0.6.5",
710712 ]
711713
@@ -1699,6 +1701,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
16991701 checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
17001702 dependencies = [
17011703 "bitflags 2.13.2",
1704+ "block2 0.6.2",
17021705 "objc2 0.6.5",
17031706 "objc2-core-graphics",
17041707 "objc2-foundation 0.3.2",
@@ -2507,6 +2510,29 @@ dependencies = [
25072510 "usvg",
25082511 ]
25092512
2513+[[package]]
2514+name = "rfd"
2515+version = "0.17.2"
2516+source = "registry+https://github.com/rust-lang/crates.io-index"
2517+checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220"
2518+dependencies = [
2519+ "block2 0.6.2",
2520+ "dispatch2",
2521+ "js-sys",
2522+ "libc",
2523+ "log",
2524+ "objc2 0.6.5",
2525+ "objc2-app-kit 0.3.2",
2526+ "objc2-core-foundation",
2527+ "objc2-foundation 0.3.2",
2528+ "percent-encoding",
2529+ "raw-window-handle",
2530+ "wasm-bindgen",
2531+ "wasm-bindgen-futures",
2532+ "web-sys",
2533+ "windows-sys 0.61.2",
2534+]
2535+
25102536 [[package]]
25112537 name = "rgb"
25122538 version = "0.8.53"
@@ -2575,6 +2601,7 @@ dependencies = [
25752601 "raw-window-handle",
25762602 "raw-window-metal",
25772603 "resvg",
2604+ "rfd",
25782605 "rune-motion",
25792606 "rune-staging",
25802607 "rune-taffy",
Cargo.toml+1−1
@@ -5,7 +5,7 @@ resolver = "3"
55 [workspace.dependencies]
66 serde = { version = "1", features = ["derive"] }
77 serde_json = "1"
8-rune = { git = "https://github.com/anomalyco/rune", rev = "3ff3cc6152b9034a1d996e3a5575c51fab3b56b8" }
8+rune = { git = "https://github.com/anomalyco/rune", rev = "3ff3cc6152b9034a1d996e3a5575c51fab3b56b8", features = ["native-file-dialog"] }
99
1010 [profile.release]
1111 incremental = true
crates/conveyor-app/src/app.rs+40−14
@@ -1,17 +1,21 @@
11 //! The app's state and loop. It draws the library's `root` widget and three things of its own
22 //! above it: the Ctrl inspector, the prompt form, and build status. Everything else is widgets.
33 use crate::{client, form::{self, Form}, inspect, status};
4-use crate::widgets::api::{Host, Live};
4+use crate::widgets::api::{Event, Host, Live};
55 use rune::{El, Tx, Waker, el};
66 use serde_json::Value;
7-use std::{cell::RefCell, collections::BTreeSet, path::{Path, PathBuf}, sync::{Arc, Mutex}, time::{Duration, SystemTime}};
7+use std::{cell::RefCell, collections::BTreeSet, path::{Path, PathBuf}, sync::{Arc, Mutex}, time::{Duration, Instant, SystemTime}};
88
99 pub struct State {
1010 pub live: Live,
11- /// conveyord's last snapshot: builds and their threads.
12- pub snap: Value,
11+ /// The widget builds, with their tickets' state and conversation.
12+ pub builds: Vec<Value>,
1313 pub connected: bool,
14- inbox: Arc<Mutex<Option<Option<Value>>>>,
14+ /// The latest snapshot, and when its request started.
15+ inbox: Arc<Mutex<Option<(Instant, Option<Value>)>>>,
16+ /// When widgets last sent conveyord a request: a snapshot asked for before it is stale,
17+ /// and would undo what `set_state` already shows.
18+ sent: Instant,
1519 /// The binary at launch and its mtime. Read once: after cargo replaces it,
1620 /// current_exe() names the deleted file.
1721 exe: Option<PathBuf>,
@@ -26,6 +30,8 @@ pub struct State {
2630 /// Each picked instance's rect, as of the last render.
2731 pub rects: RefCell<Vec<(String, [f32; 4])>>,
2832 pub form: Option<Form>,
33+ /// The window's size in points, as of the last render.
34+ pub window: std::cell::Cell<(f32, f32)>,
2935 /// What the form's field binds to in the frame it closes.
3036 pub spare: rune::TextEdit,
3137 /// Builds whose reply was dismissed, and builds whose new widgets were placed.
@@ -55,8 +61,8 @@ pub fn init() -> State {
5561 let base = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/conveyor/app");
5662 let _ = std::fs::create_dir_all(&base);
5763 State { seen: ids(&base, "seen").unwrap_or_default(), placed: ids(&base, "placed").unwrap_or_default(), live: Live::new(base),
58- snap: Value::Null, connected: false, inbox: Default::default(), exe: None, built: None, ctrl: false, pointer: (0.0, 0.0),
59- picked: vec![], element: String::new(), rects: RefCell::new(vec![]), form: None, spare: rune::TextEdit::new("") }
64+ builds: vec![], connected: false, sent: Instant::now(), inbox: Default::default(), exe: None, built: None, ctrl: false, pointer: (0.0, 0.0),
65+ picked: vec![], element: String::new(), rects: RefCell::new(vec![]), form: None, window: Default::default(), spare: rune::TextEdit::new("") }
6066 }
6167
6268 /// Polls conveyord once a second on a thread. Every poll also re-renders, for clocks.
@@ -65,7 +71,8 @@ pub fn setup(s: &mut State, waker: Waker) {
6571 s.built = s.exe.as_deref().and_then(mtime);
6672 let inbox = s.inbox.clone();
6773 std::thread::spawn(move || loop {
68- *inbox.lock().unwrap() = Some(client::state());
74+ let asked = Instant::now();
75+ *inbox.lock().unwrap() = Some((asked, client::state()));
6976 waker();
7077 std::thread::sleep(Duration::from_secs(1));
7178 });
@@ -74,16 +81,20 @@ pub fn setup(s: &mut State, waker: Waker) {
7481 pub fn poll(s: &mut State, _t: f64, tx: &mut Tx) -> bool {
7582 let made = s.live.make_wanted();
7683 let mut again = made;
77- if let Some(snap) = s.inbox.lock().unwrap().take() {
84+ if let Some((asked, snap)) = s.inbox.lock().unwrap().take() {
7885 s.connected = snap.is_some();
79- if let Some(snap) = snap {
86+ if let Some(snap) = snap.filter(|_| asked > s.sent) {
8087 s.live.data = client::data(&snap);
81- s.snap = snap;
88+ s.builds = client::builds(&snap);
8289 }
8390 again = true;
8491 }
8592 if !made { place(s); }
86- for r in s.live.take_outbox() { client::send(r); }
93+ for r in s.live.take_outbox() {
94+ s.sent = Instant::now();
95+ client::send(r);
96+ }
97+ s.live.update();
8798 s.live.save();
8899 if s.live.animating() { tx.wake_after(Duration::from_millis(16)); }
89100 restart(s);
@@ -96,8 +107,8 @@ pub fn poll(s: &mut State, _t: f64, tx: &mut Tx) -> bool {
96107 /// one of its parents. Kinds already on screen (a parent the build changed shows them) are
97108 /// left alone.
98109 fn place(s: &mut State) {
99- let Some(builds) = s.snap["builds"].as_array() else { return };
100- if s.live.kind("root").is_none() { return; }
110+ if s.builds.is_empty() || s.live.kind("root").is_none() { return; }
111+ let builds = s.builds.clone();
101112 let first_run = !s.live.base().join("placed").exists();
102113 for b in builds.iter().filter(|b| b["state"] == "done") {
103114 let id = b["id"].as_u64().unwrap_or(0);
@@ -132,8 +143,23 @@ pub fn on_modifiers(s: &mut State, mods: rune::Mods, tx: &mut Tx) {
132143 if s.ctrl { inspect::pick(s, tx); }
133144 }
134145
146+/// A paste with no text field focused goes to the widgets; an image is saved as a PNG first.
147+fn paste(s: &mut State, c: &rune::ClipboardContent, _: &mut Tx) {
148+ let image = c.image().and_then(|img| {
149+ let dir = s.live.base().join("clips");
150+ let path = dir.join(format!("{}.png", (crate::widgets::api::now() * 1000.0) as u64));
151+ std::fs::create_dir_all(&dir).ok()?;
152+ std::fs::write(&path, img.png()).ok()?;
153+ Some(path)
154+ });
155+ if !s.live.event(&Event::Paste { text: c.text().to_owned(), image }) { eprintln!("no widget took the paste"); }
156+}
157+
135158 pub fn view(s: &State, rcx: &mut rune::Cx<State>) -> El {
159+ if let Some(r) = rcx.layout("app") { s.window.set((r[2], r[3])); }
136160 let mut app = el().key("app").w_full().h_full()
161+ .on_paste_content(paste)
162+ .on_drop_files(|s: &mut State, files: &[PathBuf], _: &mut Tx| { s.live.event(&Event::Drop(files.to_vec())); })
137163 .child(el().key("content").w_full().h_full().child(s.live.render("root", "root"))
138164 .on_pointer_move_local(|s: &mut State, e: rune::PointerEvent, tx: &mut Tx| {
139165 s.pointer = (e.window_x, e.window_y);
crates/conveyor-app/src/client.rs+18−1
@@ -29,7 +29,24 @@ pub fn data(v: &Value) -> Data {
2929 let all = |k: &str| v[k].as_array().cloned().unwrap_or_default();
3030 Data {
3131 projects: all("projects").iter().map(|p| Project { slug: s(p, "slug"), path: s(p, "path"), slots: n(p, "slots") as u32 }).collect(),
32- tickets: all("tickets").iter().map(|t| Ticket { project: s(t, "project"), id: n(t, "id") as u32, title: s(t, "title"), state: s(t, "state") }).collect(),
32+ tickets: all("tickets").iter().map(|t| Ticket {
33+ project: s(t, "project"), id: n(t, "id") as u32, title: s(t, "title"), state: s(t, "state"), body: s(t, "body"),
34+ created: n(t, "created"), since: n(t, "since"),
35+ files: t["files"].as_array().into_iter().flatten().filter_map(|f| Some(f.as_str()?.to_owned())).collect(),
36+ thread: t["thread"].as_array().into_iter().flatten()
37+ .map(|e| Activity { at: n(e, "at"), project: s(t, "project"), ticket: n(t, "id") as u32, kind: s(e, "kind"), text: s(e, "text") }).collect(),
38+ }).collect(),
3339 activity: all("activity").iter().map(|a| Activity { at: n(a, "at"), project: s(a, "project"), ticket: n(a, "ticket") as u32, kind: s(a, "kind"), text: s(a, "text") }).collect(),
3440 }
3541 }
42+
43+/// Each widget build, with its ticket's title, state, time in that state and conversation.
44+pub fn builds(v: &Value) -> Vec<Value> {
45+ let tickets = v["tickets"].as_array().cloned().unwrap_or_default();
46+ v["builds"].as_array().into_iter().flatten().filter_map(|b| {
47+ let t = tickets.iter().find(|t| t["project"] == "widgets" && t["id"] == b["id"])?;
48+ let mut b = b.clone();
49+ for k in ["title", "state", "since", "thread"] { b[k] = t[k].clone(); }
50+ Some(b)
51+ }).collect()
52+}
crates/conveyor-app/src/form.rs+5−2
@@ -27,13 +27,16 @@ fn submit(s: &mut State, tx: &mut Tx) {
2727 tx.blur();
2828 let Some(f) = s.form.take() else { return };
2929 if f.text.text.trim().is_empty() { return; }
30+ // conveyord copies the app's state into the ticket, so the agent can replay this moment.
31+ s.live.save_state(f.targets.first().map_or("root", |t| t.0.as_str()), &f.element);
32+ let (w, h) = s.window.get();
3033 client::send(json!({"op": "widget", "prompt": f.text.text, "kind": f.kind, "targets": f.targets, "element": f.element,
31- "tree": s.live.tree(), "shared": s.live.shared_line()}).to_string());
34+ "tree": s.live.tree(), "size": [w, h]}).to_string());
3235 }
3336
3437 /// What's been said about `kind`: each build asked from it or that changed it.
3538 fn thread<'a>(s: &'a State, kind: &str) -> Vec<&'a Value> {
36- s.snap["builds"].as_array().into_iter().flatten()
39+ s.builds.iter()
3740 .filter(|b| b["kind"] == kind || b["changed"].as_array().is_some_and(|c| c.iter().any(|k| k == kind)))
3841 .flat_map(|b| b["thread"].as_array().into_iter().flatten()).collect()
3942 }
crates/conveyor-app/src/inspect.rs+22−12
@@ -1,16 +1,20 @@
1-//! The building tool's eye: while Ctrl is held, a layer over the whole window outlines the
2-//! widget under the pointer and its parents, and takes the click, so no widget's own controls
3-//! can swallow it. A click opens the prompt about that widget.
1+//! The building tool's eye: while Ctrl is held, a layer over the whole window outlines what's
2+//! under the pointer: the deepest keyed element, the widget it's in, and that widget's parents.
3+//! 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.
45 use crate::{app::State, form};
56 use rune::{El, Tx, el, text, tok};
67
7-/// Finds the widget instances under the pointer: each renders keyed `w:<id>`.
8+/// Finds the widget instances under the pointer (each renders keyed `w:<id>`), and the keyed
9+/// elements inside the innermost one, as a key path such as `col-done/card-12`.
810 pub fn pick(s: &mut State, tx: &mut Tx) {
911 let (x, y) = s.pointer;
1012 tx.element_at_in("content", x, y, |s: &mut State, picked, _| {
1113 let Some(p) = picked else { (s.picked, s.element) = (vec![], String::new()); return };
1214 s.picked = p.path().split('/').filter_map(|seg| seg.strip_prefix("w:")).rev().map(String::from).collect();
13- s.element = p.key().filter(|k| !k.starts_with("w:")).unwrap_or("").to_owned();
15+ let inner = p.path().rsplit_once("/w:").map_or("", |(_, rest)| rest);
16+ let unkeyed = |seg: &&str| seg.starts_with('#') && seg[1..].bytes().all(|b| b.is_ascii_digit());
17+ s.element = inner.split('/').skip(1).filter(|seg| !unkeyed(seg)).collect::<Vec<_>>().join("/");
1418 });
1519 }
1620
@@ -25,15 +29,21 @@ pub fn view(s: &State, rcx: &mut rune::Cx<State>) -> El {
2529 pick(s, tx);
2630 })
2731 .on_press_tx(|s: &mut State, _| form::open(s));
28- for (i, (id, [x, y, w, h])) in rects.iter().enumerate().rev() {
29- let kind = s.live.kind(id).unwrap_or("?");
30- let (width, alpha) = if i == 0 { (2.0, 1.0) } else { (1.0, 0.35) };
32+ for (i, (_, [x, y, w, h])) in rects.iter().enumerate().rev() {
33+ let (width, alpha) = if i == 0 { (1.5, 0.8) } else { (1.0, 0.3) };
3134 layer = layer.child(el().w(*w).h(*h).absolute(*x, *y).border(width, accent.alpha(alpha)).radius(4.0));
32- if i == 0 {
33- layer = layer.child(el().absolute(*x, (*y - 22.0).max(0.0)).h(20.0).px(8.0).center_y().radius(4.0).fill(accent)
34- .child(text(format!("{kind} · {id} · {}", s.element)).font(tok::type_::LABEL).color(t.bg)));
35- }
3635 }
36+ let Some((id, inst)) = rects.first() else { *s.rects.borrow_mut() = rects; return layer };
37+ let leaf = s.element.rsplit('/').next().unwrap_or("");
38+ let part = if leaf.is_empty() { None } else { rcx.layout(&format!("w:{id}/{}", s.element)).or_else(|| rcx.layout(leaf)) };
39+ if let Some([x, y, w, h]) = part {
40+ layer = layer.child(el().w(w).h(h).absolute(x, y).border(2.5, accent).fill(accent.alpha(0.12)).radius(4.0));
41+ }
42+ let [x, y, ..] = part.unwrap_or(*inst);
43+ let kind = s.live.kind(id).unwrap_or("?");
44+ let name = if leaf.is_empty() { format!("{kind} · {id}") } else { format!("{kind} › {leaf}") };
45+ layer = layer.child(el().absolute(x, (y - 22.0).max(0.0)).h(20.0).px(8.0).center_y().radius(4.0).fill(accent)
46+ .child(text(name).font(tok::type_::LABEL).color(t.bg)));
3747 *s.rects.borrow_mut() = rects;
3848 layer
3949 }
crates/conveyor-app/src/status.rs+1−1
@@ -36,7 +36,7 @@ pub fn view(s: &State) -> El {
3636 let now = crate::widgets::api::now() as u64;
3737 let mut out = col().key("status").absolute(0.0, 0.0).w_full().h_full().padding(12.0).gap(8.0).items_end().justify_end();
3838 if !s.connected { out = out.child(text("conveyord isn't running").color(t.text_secondary)); }
39- for b in s.snap["builds"].as_array().into_iter().flatten() {
39+ for b in &s.builds {
4040 let state = b["state"].as_str().unwrap_or("");
4141 let id = b["id"].as_u64().unwrap_or(0);
4242 if FINISHED.contains(&state) {
crates/conveyor/src/agent.rs+11−1
@@ -37,6 +37,7 @@ fn run(p: &Project, id: u32) -> Result<String, String> {
3737 let (url, git_ssh) = vm.git_remote("/home/sacenox/work");
3838 git(&p.path, &git_ssh, &["push", "-q", &url, "main:main"])?;
3939 vm.sh(&format!("cd ~/work && git switch -qc {branch}"), b"")?;
40+ let files = give_files(&vm, p, id)?;
4041
4142 let local = crate::paths::vm_sock(&name, "verbs");
4243 let remote = format!("/home/{}/.conveyor/{name}-{}.sock", vm::USER, std::process::id());
@@ -50,7 +51,7 @@ fn run(p: &Project, id: u32) -> Result<String, String> {
5051 --disallowedTools=AskUserQuestion --append-system-prompt \"$(cat ~/.conveyor/rules.md)\""))
5152 .stdin(Stdio::piped()).stdout(stream).stderr(Stdio::piped())
5253 .spawn().map_err(|e| e.to_string())?;
53- agent.stdin.take().unwrap().write_all(format!("# #{id} {}\n\n{}", t.title, t.body).as_bytes()).map_err(|e| e.to_string())?;
54+ agent.stdin.take().unwrap().write_all(format!("# #{id} {}\n\n{}{files}", t.title, t.body).as_bytes()).map_err(|e| e.to_string())?;
5455 let out = agent.wait_with_output().map_err(|e| e.to_string())?;
5556 let outcome = verbs.finish();
5657 if let Some(reply) = reply(&store::dir(&p.slug, id).join("stream.jsonl")) {
@@ -77,6 +78,15 @@ fn run(p: &Project, id: u32) -> Result<String, String> {
7778 })
7879 }
7980
81+/// Copies the ticket's attached files to ~/ticket/files in the guest. What the prompt says of them.
82+fn give_files(vm: &Vm, p: &Project, id: u32) -> Result<String, String> {
83+ let names: Vec<String> = store::files(&p.slug, id).iter().filter_map(|f| Some(f.file_name()?.to_str()?.to_owned())).collect();
84+ if names.is_empty() { return Ok(String::new()); }
85+ let tar = Command::new("tar").arg("-C").arg(store::dir(&p.slug, id)).args(["-cf", "-", "files"]).output().map_err(|e| e.to_string())?;
86+ vm.sh("mkdir -p ~/ticket && tar -C ~/ticket -xf -", &tar.stdout)?;
87+ Ok(format!("\n\nAttached, in ~/ticket/files/: {}", names.join(", ")))
88+}
89+
8090 /// The agent's final message, from the end of its stream.
8191 fn reply(stream: &Path) -> Option<String> {
8292 let s = std::fs::read_to_string(stream).ok()?;
crates/conveyor/src/library.rs+31−21
@@ -60,30 +60,46 @@ fn about(kind: &str) -> Vec<u32> {
6060 store::tickets(SLUG).iter().filter(|t| build(t.id).is_some_and(|b| b.kind == kind || b.changed.iter().any(|c| c == kind))).map(|t| t.id).collect()
6161 }
6262
63-/// A Ctrl+click: the prompt, and everything the app knew about what was under the pointer.
64-pub fn request(r: &Value) -> u32 {
63+/// A Ctrl+click: the prompt, what was under the pointer, and a copy of the app's state so the
64+/// agent can render exactly what the user saw.
65+pub fn request(r: &Value) -> Result<u32, String> {
6566 let s = |k: &str| r[k].as_str().unwrap_or("").trim().to_owned();
6667 let (prompt, kind) = (s("prompt"), if s("kind").is_empty() { "root".into() } else { s("kind") });
6768 let targets: Vec<(String, f32, f32)> = serde_json::from_value(r["targets"].clone()).unwrap_or_default();
6869 let (target, x, y) = targets.first().cloned().unwrap_or(("root".into(), 0.0, 0.0));
6970 let parents: String = targets.iter().skip(1).map(|t| format!("`{}`", t.0)).collect::<Vec<_>>().join(", ");
70- let history: String = thread::of(&about(&kind)).iter()
71+ let (w, h) = (r["size"][0].as_f64().unwrap_or(1400.0), r["size"][1].as_f64().unwrap_or(900.0));
72+ let history: String = thread::of(SLUG, &about(&kind)).iter()
7173 .map(|e| format!("- #{} {}: {}\n", e["ticket"], e["kind"].as_str().unwrap_or(""), e["text"].as_str().unwrap_or("").replace('\n', "\n ")))
7274 .collect();
75+ let element = s("element");
7376 let context = format!(
7477 "The user Ctrl+clicked the `{kind}` widget (`widgets/{kind}.rs`), instance `{target}`, at ({x:.0}, {y:.0}) inside it.\n\
7578 Its parents, innermost first: {parents}\n\
76- The element under the pointer: `{element}`\n\n\
79+ The element under the pointer: {element}\n\n\
7780 The widgets on screen, as instance (kind):\n\n{tree}\n\n\
78- Shared values: {shared}\n\n\
81+ See what they saw, with what they clicked outlined: the app's state is in ~/ticket/files/app, so run\n\n\
82+ \tcargo run --release -p preview -- --state ~/ticket/files/app root --size {w:.0}x{h:.0} --snap /tmp/seen.png --at 1\n\n\
7983 The conversation about `{kind}` so far, oldest first:\n\n{history}",
80- parents = if parents.is_empty() { "none".into() } else { parents }, element = s("element"), tree = s("tree"),
81- shared = if s("shared").is_empty() { "none".into() } else { s("shared") },
84+ parents = if parents.is_empty() { "none".into() } else { parents },
85+ tree = s("tree"),
86+ element = if element.is_empty() { "none with a key".into() } else { format!("`{element}`") },
8287 history = if history.is_empty() { "- none yet\n".into() } else { history });
83- let title: String = prompt.lines().next().unwrap_or("widget").chars().take(70).collect();
84- let id = store::create(SLUG, &title, &format!("{prompt}\n\n---\n\n{context}"), "ready");
88+ let id = store::create(SLUG, &title(&prompt), &format!("{prompt}\n\n---\n\n{context}"), "ready");
89+ store::attach(SLUG, id, &[paths::data().join("app")])?;
8590 save_build(id, &Build { kind, targets, ..Default::default() });
86- id
91+ Ok(id)
92+}
93+
94+/// The prompt's first words, up to about 60 characters.
95+fn title(prompt: &str) -> String {
96+ let mut t = String::new();
97+ for w in prompt.split_whitespace() {
98+ if t.len() + w.len() > 60 { t.push('…'); break; }
99+ if !t.is_empty() { t.push(' '); }
100+ t.push_str(w);
101+ }
102+ if t.is_empty() { "widget".into() } else { t }
87103 }
88104
89105 /// Merges a done build ticket into the library, then rebuilds the app with it.
@@ -115,16 +131,10 @@ fn rebuild_app() -> Result<(), String> {
115131 .args(["build", "--release", "-q", "-p", "conveyor-app"])).map(|_| ())
116132 }
117133
118-/// Everything the app shows: projects, tickets, recent activity, and each build with its thread.
119-pub fn snapshot() -> Value {
120- let projects = store::projects();
121- let tickets: Vec<_> = projects.iter().flat_map(|p| store::tickets(&p.slug)).collect();
122- let builds: Vec<_> = store::tickets(SLUG).into_iter().filter_map(|t| {
134+/// Each build ticket with what it was asked about and changed, for the app's status.
135+pub fn builds() -> Vec<Value> {
136+ store::tickets(SLUG).into_iter().filter_map(|t| {
123137 let b = build(t.id)?;
124- let finished = store::events(SLUG, t.id).iter().rev().find(|e| e["kind"] == "state").and_then(|e| e["at"].as_u64()).unwrap_or(0);
125- Some(json!({"id": t.id, "title": t.title, "state": t.state, "kind": b.kind, "targets": b.targets,
126- "created": b.created, "changed": b.changed, "since": finished, "thread": thread::of(&[t.id])}))
127- }).collect();
128- let projects: Vec<_> = projects.iter().map(|p| json!({"slug": p.slug, "path": p.path, "slots": p.slots})).collect();
129- json!({"projects": projects, "tickets": tickets, "activity": store::activity(), "builds": builds})
138+ Some(json!({"id": t.id, "kind": b.kind, "targets": b.targets, "created": b.created, "changed": b.changed}))
139+ }).collect()
130140 }
crates/conveyor/src/main.rs+1−0
@@ -4,6 +4,7 @@ mod dispatch;
44 mod library;
55 mod paths;
66 mod server;
7+mod snapshot;
78 mod store;
89 mod thread;
910 mod verbs;
crates/conveyor/src/server.rs+54−15
@@ -1,10 +1,13 @@
11 //! The socket the app, widgets and the CLI use: one JSON request per line, one JSON reply per line.
2-//! {"op":"state"} projects, tickets, activity, builds
3-//! {"op":"widget","prompt":"…","target":"root","kind":"root","at":[10,20],"element":"…","tree":"…","shared":"…"}
4-//! a build ticket from a Ctrl+click
5-//! {"op":"ticket","project":"…","title":"…","body":"…","state":"draft"} state defaults to ready
6-//! {"op":"set","project":"…","id":3,"state":"review"} move a ticket
7-use crate::{library, paths, store};
2+//! {"op":"state"} projects, tickets, activity, builds
3+//! {"op":"widget","prompt":"…","kind":"…","targets":[["root.x",10,20]],"element":"…","size":[w,h]}
4+//! a build ticket from a Ctrl+click
5+//! {"op":"ticket","project":"…","title":"…","body":"…","state":"draft","files":["/abs/path"]}
6+//! state defaults to ready; files are copied in
7+//! {"op":"set","project":"…","id":3,"state":"review"} move a ticket; `running` is conveyor's
8+//! {"op":"project","slug":"…","path":"/abs/dir"} add a project (the folder is made if missing)
9+//! {"op":"project","slug":"…","slots":0} how many tickets run at once; 0 pauses it
10+use crate::{library, paths, snapshot, store};
811 use serde_json::{Value, json};
912 use std::{io::{BufRead, BufReader, Write}, os::unix::net::{UnixListener, UnixStream}};
1013
@@ -29,18 +32,54 @@ fn session(c: UnixStream) -> std::io::Result<()> {
2932 fn handle(r: &Value) -> Value {
3033 let s = |k: &str| r[k].as_str().unwrap_or("");
3134 let id = r["id"].as_u64().unwrap_or(0) as u32;
32- match s("op") {
33- "state" => library::snapshot(),
34- "widget" if !s("prompt").trim().is_empty() => json!({"id": library::request(r)}),
35+ let result = match s("op") {
36+ "state" => return snapshot::snapshot(),
37+ "widget" if !s("prompt").trim().is_empty() => library::request(r).map(|id| json!({"id": id})),
3538 "ticket" if store::project(s("project")).is_some() => {
36- json!({"id": store::create(s("project"), s("title"), s("body"), if s("state").is_empty() { "ready" } else { s("state") })})
39+ let id = store::create(s("project"), s("title"), s("body"), if s("state").is_empty() { "ready" } else { s("state") });
40+ let files: Vec<_> = r["files"].as_array().into_iter().flatten().filter_map(|f| Some(f.as_str()?.into())).collect();
41+ store::attach(s("project"), id, &files).map(|_| json!({"id": id}))
3742 }
38- "set" if store::ticket(s("project"), id).is_some() && !s("state").is_empty() => {
39- store::set_state(s("project"), id, s("state"));
40- json!({"ok": true})
41- }
42- _ => json!({"error": "bad request"}),
43+ "set" => set(s("project"), id, s("state")),
44+ "project" => project(s("slug"), r),
45+ _ => Err("bad request".into()),
46+ };
47+ result.unwrap_or_else(|e| json!({"error": e}))
48+}
49+
50+/// Moves a ticket, except into or out of `running`: only the dispatcher starts and settles runs.
51+fn set(project: &str, id: u32, state: &str) -> Result<Value, String> {
52+ let t = store::ticket(project, id).ok_or("no such ticket")?;
53+ if t.state == "running" || state == "running" {
54+ return Err("running belongs to conveyor: move a ticket to ready to start it".into());
4355 }
56+ if !["draft", "ready", "review", "parked", "failed", "done"].contains(&state) { return Err(format!("no state {state}")); }
57+ store::set_state(project, id, state);
58+ Ok(json!({"ok": true}))
59+}
60+
61+/// Adds a project at `path` (made, with an empty git repo, if missing), or sets its slots.
62+fn project(slug: &str, r: &Value) -> Result<Value, String> {
63+ if slug.is_empty() || !slug.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
64+ return Err("a slug is letters, digits, - and _".into());
65+ }
66+ let mut p = match (store::project(slug), r["path"].as_str()) {
67+ (Some(_), Some(_)) => return Err(format!("{slug} exists")),
68+ (Some(p), None) => p,
69+ (None, Some(path)) => {
70+ let path = std::path::PathBuf::from(path);
71+ std::fs::create_dir_all(&path).map_err(|e| e.to_string())?;
72+ if !path.join(".git").exists() {
73+ crate::agent::git(&path, "", &["init", "-q", "-b", "main"])?;
74+ crate::agent::git(&path, "", &["-c", "user.name=conveyor", "-c", "user.email=conveyor@localhost", "commit", "-q", "--allow-empty", "-m", "Start"])?;
75+ }
76+ store::Project { slug: slug.into(), path, slots: 1, auto_merge: false, library: false }
77+ }
78+ (None, None) => return Err(format!("no project {slug}")),
79+ };
80+ if let Some(n) = r["slots"].as_u64() { p.slots = n as usize; }
81+ store::save_project(&p);
82+ Ok(json!({"ok": true}))
4483 }
4584
4685 /// One request from the CLI.
crates/conveyor/src/snapshot.rs+18−0
@@ -0,0 +1,18 @@
1+//! Everything widgets read, as one JSON reply to `state`: projects, every ticket with its text,
2+//! times, attached files and conversation, the latest activity, and the widget builds.
3+use crate::{library, store, thread};
4+use serde_json::{Value, json};
5+
6+pub fn snapshot() -> Value {
7+ let projects = store::projects();
8+ let tickets: Vec<_> = projects.iter().flat_map(|p| store::tickets(&p.slug).into_iter().map(|t| {
9+ let events = store::events(&p.slug, t.id);
10+ let at = |e: Option<&Value>| e.and_then(|e| e["at"].as_u64()).unwrap_or(0);
11+ json!({"project": t.project, "id": t.id, "title": t.title, "state": t.state,
12+ "body": t.body.split("\n\n---\n\n").next().unwrap_or("").trim(),
13+ "created": at(events.first()), "since": at(events.iter().rev().find(|e| e["kind"] == "state")),
14+ "files": store::files(&p.slug, t.id), "thread": thread::of(&p.slug, &[t.id])})
15+ })).collect();
16+ let projects: Vec<_> = projects.iter().map(|p| json!({"slug": p.slug, "path": p.path, "slots": p.slots})).collect();
17+ json!({"projects": projects, "tickets": tickets, "activity": store::activity(), "builds": library::builds()})
18+}
crates/conveyor/src/store.rs+17−0
@@ -114,6 +114,23 @@ pub fn event(project: &str, id: u32, mut ev: Value) {
114114 writeln!(f, "{ev}").unwrap();
115115 }
116116
117+/// Copies files into the ticket's files/ folder, which travels with it into the agent's VM.
118+pub fn attach(project: &str, id: u32, files: &[PathBuf]) -> Result<(), String> {
119+ let to = dir(project, id).join("files");
120+ fs::create_dir_all(&to).map_err(|e| e.to_string())?;
121+ for f in files {
122+ crate::vm::run(std::process::Command::new("cp").arg("-r").arg(f).arg(&to))?;
123+ }
124+ Ok(())
125+}
126+
127+/// The ticket's attached files, as host paths.
128+pub fn files(project: &str, id: u32) -> Vec<PathBuf> {
129+ let mut v: Vec<PathBuf> = fs::read_dir(dir(project, id).join("files")).into_iter().flatten().flatten().map(|e| e.path()).collect();
130+ v.sort();
131+ v
132+}
133+
117134 pub fn events(project: &str, id: u32) -> Vec<Value> {
118135 fs::read_to_string(dir(project, id).join("events.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
119136 }
crates/conveyor/src/thread.rs+16−14
@@ -1,24 +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};
1+//! The conversation behind tickets, oldest first: each prompt, what the agent decided or left
2+//! out, and its reply. Widgets show it, so the loop closes in the app.
3+use crate::store;
44 use serde_json::{Value, json};
55
6-pub fn of(tickets: &[u32]) -> Vec<Value> {
6+pub fn of(project: &str, tickets: &[u32]) -> Vec<Value> {
77 let mut out = vec![];
88 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()));
9+ let entry = |kind: &str, text: String, at: &Value| json!({"ticket": id, "kind": kind, "text": text, "at": at});
10+ let events = store::events(project, id);
11+ if let Some(t) = store::ticket(project, id) {
12+ let at = events.first().map_or(Value::Null, |e| e["at"].clone());
13+ out.push(entry("prompt", t.body.split("\n\n---\n\n").next().unwrap_or("").trim().into(), &at));
1214 }
13- for e in store::events(SLUG, id) {
15+ for e in events {
1416 let a = |k: &str| e["args"][k].as_str().unwrap_or("").to_owned();
1517 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- (Some("conveyor"), _) if e["show"] == true => out.push(entry("conveyor", e["msg"].as_str().unwrap_or("").into())),
18+ (Some("verb"), Some("decide")) => out.push(entry("decide", format!("{} — {}", a("text"), a("why")), &e["at"])),
19+ (Some("verb"), Some("deviate")) => out.push(entry("deviate", format!("{} — recommends: {}", a("text"), a("recommend")), &e["at"])),
20+ (Some("verb"), Some("block")) => out.push(entry("block", format!("{} — recommends: {}", a("reason"), a("recommend")), &e["at"])),
21+ (Some("reply"), _) => out.push(entry("reply", e["text"].as_str().unwrap_or("").into(), &e["at"])),
22+ (Some("error"), _) => out.push(entry("error", e["msg"].as_str().unwrap_or("").into(), &e["at"])),
23+ (Some("conveyor"), _) if e["show"] == true => out.push(entry("conveyor", e["msg"].as_str().unwrap_or("").into(), &e["at"])),
2224 _ => {}
2325 }
2426 }
templates/library/CLAUDE.md+15−6
@@ -7,8 +7,11 @@ This repo is the user's whole app. The conveyor window draws `widgets/root.rs` a
77 Below the user's words, after `---`, conveyor says what they clicked:
88
99 - the widget kind (`widgets/<kind>.rs`) and its instance id, and the point inside it;
10+- the element under the pointer, as a key path inside that widget (`col-done/card-12`): grep for the key to find the code;
1011 - its parents, innermost first (`root.canvas.clock1` is `clock1` inside `root.canvas` inside `root`);
11-- every instance on screen, the shared values, and the conversation so far about that kind.
12+- every instance on screen, and the conversation so far about that kind.
13+
14+**Look before you change anything.** `~/ticket/files/app` is a copy of the user's app as it was when they clicked: its data, shared values and every instance's folder. The ticket gives the exact command; it renders their window with what they clicked outlined in orange. Read the PNG. Render it again after your change, with the same state, and compare: that's what they will see.
1215
1316 Read the words against that. "Make this purple" means the clicked kind. "Put a list of my projects here" means a new kind, or a change to the parent that lays this area out. "Add a sidebar" on the title bar or the canvas usually means changing `root.rs`. Change as many widgets as it takes; keep each file one widget.
1417
@@ -22,10 +25,14 @@ A widget is a struct with its own state that renders itself (`api::View`). Read
2225
2326 - **Compose.** `cx.child("kind", "key")` renders another widget inside this one, with its own state and folder. Keep keys stable. A layout widget (root is one) is mostly children.
2427 - **New widgets placed for you.** When your branch adds a widget kind and nothing on screen shows it yet, the app offers it to the widget the user clicked (`View::mount`, at the click, in its own points), then to each parent. A widget that holds a list of children (the canvas) keeps it there. So for "put an X here": write the X, and either let mount place it, or render it yourself with `cx.child` in the parent you change. Don't do both.
25-- **Conveyor's data.** `cx.data` has the projects, every ticket and the latest activity (state changes, agent notes, decisions, blocks, replies), refreshed every second.
26-- **Act on conveyor.** From a handler: `set_state(h, project, id, "ready")` moves a ticket (ready starts an agent), `new_ticket(...)` writes one, and `call(h, json)` sends any request in conveyor's `server.rs`.
28+- **Conveyor's data.** `cx.data` has the projects, every ticket (with its text, times, attached files and conversation) and the latest activity, refreshed every second. Never read conveyor's own files: if something is missing from `cx.data`, say so with `conveyor deviate`.
29+- **Act on conveyor.** From a handler: `set_state(h, project, id, "ready")` moves a ticket and shows the move at once (ready starts an agent when the project has a free slot; conveyor owns running), `new_ticket(h, project, title, body, state, &files)` writes one with files attached (the agent gets them), `add_project(h, slug, &path)` adds a project, `set_slots(h, project, n)` sets how many tickets run at once (0 pauses it). `tx.open_folder(...)` and `tx.open_file(...)` show the system's dialogs.
30+- **Draw.** Rune draws vector shapes (`rune::Shape`: lines, paths, arcs) with `.shape(...)`, blurs what's behind an element with `.backdrop_blur(sigma)`, and stacks absolute elements in the order you add them.
2731 - **Share.** `share(h, "project", "dotfiles")` in a handler, and `cx.shared("project")` in any widget's view: a sidebar picks, a board follows. Shared values survive restarts.
28-- **Input.** Buttons, fields, keys, drags. Reach the widget's state from a handler with `on`, `edit` or `get`.
32+- **Input.** Buttons, fields, keys, drags, file drops on an element (`on_drop_files`). Reach the widget's state from a handler with `on`, `edit` or `get`.
33+- **Window-wide events.** A paste with no text field focused, or files dropped on the window, arrive at `View::event` (pasted images are saved as PNGs first). Every instance is offered it, innermost first.
34+- **Writable state each frame.** `View::update(&mut self, cx)` runs before every render: note what changed in `cx.data`, step an animation's state. Keep `view` a pure drawing of state.
35+- **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.
2936 - **Animate.** Call `cx.animate()` in `view` while something moves, and draw from `cx.now`. Without it the app renders once a second.
3037 - **Files.** `cx.dir` is the instance's own folder and survives restarts. The app restarts whenever the library changes, so save what the user typed or arranged, as it changes.
3138 - **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.
@@ -37,6 +44,8 @@ Run `conveyor block --reason "<...>" --recommend "<...>"` and stop, without gues
3744 - the words don't ask for anything, such as a keyboard mash or a stray word;
3845 - it needs something no widget can reach with `rune`, `std`, the API and the system's programs, such as a new crate. Say exactly what's missing: that's how the API grows.
3946
47+When the API covers most of it, build that part and name the rest with `conveyor deviate` instead of blocking. Don't work around the API by reading or writing conveyor's files.
48+
4049 ## Make or change widgets
4150
4251 1. A new kind gets a short snake_case file name, such as `clock` or `project_list`, that isn't taken in `widgets/`.
@@ -75,10 +84,10 @@ Run `conveyor block --reason "<...>" --recommend "<...>"` and stop, without gues
7584
7685 ```sh
7786 cargo build --release -p preview
78-cargo run --release -p preview -- root <new kinds…> --snap /tmp/a.png --tree /tmp/a.json --size 1400x900
87+cargo run --release -p preview -- --state ~/ticket/files/app root --size 1400x900 --snap /tmp/a.png --tree /tmp/a.json --at 1
7988 ```
8089
81-The preview is the app's own host with sample projects, tickets and activity. The first name is rendered as the whole window. Names after it are mounted as the app would, so `root clock` shows the clock on the canvas. To see one widget alone, pass only its name. Use `--script` to press and type, and look at the PNG until it does what the ticket asks. `--tree` lists every element with its rect, so you can catch clipped content. Requests a widget sends to conveyor are printed. Instance folders liv …
90+The preview is the app's own host. With `--state` it replays the user's app; without it, it runs on sample projects and tickets. The first name is rendered as the whole window. Names after it are mounted as the app would, so `root clock` shows the clock on the canvas. To see one widget alone, pass only its name. Give it `--at 1` (or later, for animation) so the snap waits for the widgets to load. Use `--script` to press, drag and type, and look at the PNG until it does what the ticket asks. `--t …
8291
8392 Rune's docs are in the cargo git checkout: `~/.cargo/git/checkouts/rune-*/*/crates/rune/README.md`.
8493
templates/library/Cargo.lock+27−0
@@ -689,6 +689,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
689689 checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
690690 dependencies = [
691691 "bitflags 2.13.2",
692+ "block2 0.6.2",
693+ "libc",
692694 "objc2 0.6.5",
693695 ]
694696
@@ -1682,6 +1684,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
16821684 checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
16831685 dependencies = [
16841686 "bitflags 2.13.2",
1687+ "block2 0.6.2",
16851688 "objc2 0.6.5",
16861689 "objc2-core-graphics",
16871690 "objc2-foundation 0.3.2",
@@ -2497,6 +2500,29 @@ dependencies = [
24972500 "usvg",
24982501 ]
24992502
2503+[[package]]
2504+name = "rfd"
2505+version = "0.17.2"
2506+source = "registry+https://github.com/rust-lang/crates.io-index"
2507+checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220"
2508+dependencies = [
2509+ "block2 0.6.2",
2510+ "dispatch2",
2511+ "js-sys",
2512+ "libc",
2513+ "log",
2514+ "objc2 0.6.5",
2515+ "objc2-app-kit 0.3.2",
2516+ "objc2-core-foundation",
2517+ "objc2-foundation 0.3.2",
2518+ "percent-encoding",
2519+ "raw-window-handle",
2520+ "wasm-bindgen",
2521+ "wasm-bindgen-futures",
2522+ "web-sys",
2523+ "windows-sys 0.61.2",
2524+]
2525+
25002526 [[package]]
25012527 name = "rgb"
25022528 version = "0.8.53"
@@ -2565,6 +2591,7 @@ dependencies = [
25652591 "raw-window-handle",
25662592 "raw-window-metal",
25672593 "resvg",
2594+ "rfd",
25682595 "rune-motion",
25692596 "rune-staging",
25702597 "rune-taffy",
templates/library/api.rs+132−11
@@ -19,8 +19,18 @@ pub struct Ticket {
1919 pub project: String,
2020 pub id: u32,
2121 pub title: String,
22- /// draft, ready, running, review, parked, failed, done.
22+ /// draft, ready, running, review, parked, failed, done. Ready starts an agent when the
23+ /// project has a free slot; conveyor moves it to running and then settles it.
2324 pub state: String,
25+ /// What was asked, in Markdown.
26+ pub body: String,
27+ /// Unix seconds: when it was written, and when it last changed state.
28+ pub created: u64,
29+ pub since: u64,
30+ /// Attached files, as paths you can read.
31+ pub files: Vec<String>,
32+ /// Its conversation, oldest first: kinds prompt, decide, deviate, block, reply, error.
33+ pub thread: Vec<Activity>,
2434 }
2535
2636 /// One thing that happened to a ticket: a state change, an agent's note, decision, deviation,
@@ -58,6 +68,15 @@ pub struct Widget {
5868 /// A widget instance's state. It renders itself into the box its parent gives it.
5969 pub trait View: Any {
6070 fn view(&self, cx: &Cx) -> El;
71+ /// Runs before every render, with the state writable: note what changed in `cx.data`, step
72+ /// a simulation, start a fetch.
73+ fn update(&mut self, _cx: &Cx) {}
74+ /// Something happened that no single element owns: a paste with no text field focused, or
75+ /// files dropped on the window. Every instance is offered it, innermost first, until one
76+ /// returns true.
77+ fn event(&mut self, _event: &Event, _cx: &Cx) -> bool {
78+ false
79+ }
6180 /// The user Ctrl+clicked inside this widget at `at` (its own points) and asked for
6281 /// something that became a new widget `kind`. Keep it as a child and return true, or
6382 /// return false and root gets it.
@@ -66,6 +85,15 @@ pub trait View: Any {
6685 }
6786 }
6887
88+/// A window-wide happening, for `View::event`.
89+pub enum Event {
90+ /// Clipboard content pasted with no text field focused. A pasted image is saved as a PNG
91+ /// first, and `image` is its path.
92+ Paste { text: String, image: Option<PathBuf> },
93+ /// Files dropped on the window.
94+ Drop(Vec<PathBuf>),
95+}
96+
6997 /// What a widget gets when it's made and each time it renders.
7098 pub struct Cx<'a> {
7199 /// This instance: "root", or its parent's id, a dot and the key the parent gave it.
@@ -149,14 +177,35 @@ pub fn call(h: &mut HostState, request: String) {
149177 }
150178
151179 /// Moves a ticket: `set_state(h, "conveyor", 3, "review")`.
180+/// Shown at once: `cx.data` changes now, and conveyor's next snapshot confirms it.
181+/// Conveyor refuses moves into or out of running.
152182 pub fn set_state(h: &mut HostState, project: &str, id: u32, state: &str) {
183+ let live = Host::live(h);
184+ if let Some(t) = live.data.tickets.iter_mut().find(|t| t.project == project && t.id == id && t.state != "running") {
185+ (t.state, t.since) = (state.to_owned(), now() as u64);
186+ }
153187 call(h, format!("{{\"op\":\"set\",\"project\":{},\"id\":{id},\"state\":{}}}", quote(project), quote(state)));
154188 }
155189
156-/// Writes a ticket: `new_ticket(h, "conveyor", "Title", "What and why", "draft")`.
190+/// Writes a ticket: `new_ticket(h, "conveyor", "Title", "What and why", "draft", &[])`.
191+/// `files` are copied into the ticket, and the agent working it gets them.
157192 /// `ready` starts an agent on it as soon as a slot is free.
158-pub fn new_ticket(h: &mut HostState, project: &str, title: &str, body: &str, state: &str) {
159- call(h, format!("{{\"op\":\"ticket\",\"project\":{},\"title\":{},\"body\":{},\"state\":{}}}", quote(project), quote(title), quote(body), quote(state)));
193+pub fn new_ticket(h: &mut HostState, project: &str, title: &str, body: &str, state: &str, files: &[PathBuf]) {
194+ let files: Vec<String> = files.iter().map(|f| quote(&f.to_string_lossy())).collect();
195+ call(h, format!("{{\"op\":\"ticket\",\"project\":{},\"title\":{},\"body\":{},\"state\":{},\"files\":[{}]}}",
196+ quote(project), quote(title), quote(body), quote(state), files.join(",")));
197+}
198+
199+/// Adds a project: `slug` names it, `path` is its folder, made (with an empty git repo) if missing.
200+/// Pick a folder with `tx.open_folder(...)` (Rune's portal dialog).
201+pub fn add_project(h: &mut HostState, slug: &str, path: &Path) {
202+ call(h, format!("{{\"op\":\"project\",\"slug\":{},\"path\":{}}}", quote(slug), quote(&path.to_string_lossy())));
203+}
204+
205+/// How many of a project's tickets run at once. 0 pauses it.
206+pub fn set_slots(h: &mut HostState, project: &str, slots: u32) {
207+ if let Some(p) = Host::live(h).data.projects.iter_mut().find(|p| p.slug == project) { p.slots = slots; }
208+ call(h, format!("{{\"op\":\"project\",\"slug\":{},\"slots\":{slots}}}", quote(project)));
160209 }
161210
162211 /// A JSON string literal.
@@ -237,13 +286,7 @@ impl Live {
237286 /// Offers a new widget to each instance in turn, at its own point: the one clicked first,
238287 /// then its parents. The id of the one that kept it.
239288 pub fn mount(&mut self, targets: &[(String, (f32, f32))], kind: &str) -> Option<String> {
240- for (id, at) in targets {
241- let Some((k, mut w)) = self.instances.remove(id) else { continue };
242- let kept = w.mount(kind, *at, &self.cx(id, now()));
243- self.instances.insert(id.clone(), (k, w));
244- if kept { return Some(id.clone()); }
245- }
246- None
289+ targets.iter().find(|(id, at)| self.with(id, |w, cx| w.mount(kind, *at, cx)) == Some(true)).map(|(id, _)| id.clone())
247290 }
248291
249292 /// Instances of `kind`, or any instance if `kind` is empty.
@@ -251,6 +294,33 @@ impl Live {
251294 self.instances.iter().filter(|(_, (k, _))| kind.is_empty() || k == kind).map(|(id, _)| id.clone()).collect()
252295 }
253296
297+ /// Runs `update` on every instance.
298+ pub fn update(&mut self) {
299+ for id in self.ids("") { self.with(&id, |w, cx| w.update(cx)); }
300+ }
301+
302+ /// Offers an event to every instance, innermost first. True when one took it.
303+ pub fn event(&mut self, event: &Event) -> bool {
304+ let mut ids = self.ids("");
305+ ids.sort_by_key(|id| std::cmp::Reverse(id.matches('.').count()));
306+ ids.iter().any(|id| self.with(id, |w, cx| w.event(event, cx)).unwrap_or(false))
307+ }
308+
309+ /// Instance `id`'s state, writable, beside a Cx for it.
310+ fn with<T>(&mut self, id: &str, f: impl FnOnce(&mut dyn View, &Cx) -> T) -> Option<T> {
311+ let (k, mut w) = self.instances.remove(id)?;
312+ let out = f(w.as_mut(), &self.cx(id, now()));
313+ self.instances.insert(id.to_owned(), (k, w));
314+ Some(out)
315+ }
316+
317+ /// Writes what the preview needs to show the app as it is now: `data.tsv` beside the
318+ /// instance folders and shared values, and `click`, the instance and element to outline.
319+ pub fn save_state(&self, instance: &str, element: &str) {
320+ let _ = std::fs::write(self.base.join("data.tsv"), self.data.to_tsv());
321+ let _ = std::fs::write(self.base.join("click"), format!("{instance}\t{element}\n"));
322+ }
323+
254324 /// Which kind instance `id` is.
255325 pub fn kind(&self, id: &str) -> Option<&str> {
256326 self.instances.get(id).map(|(k, _)| k.as_str())
@@ -290,6 +360,57 @@ impl Live {
290360 }
291361 }
292362
363+// ── Data as text: the app saves it with its state, and the preview loads it ─────────────────
364+
365+fn esc(s: &str) -> String {
366+ s.replace('\\', "\\\\").replace('\t', "\\t").replace('\n', "\\n")
367+}
368+
369+fn unesc(s: &str) -> String {
370+ let (mut out, mut it) = (String::new(), s.chars());
371+ while let Some(c) = it.next() {
372+ out.push(if c != '\\' { c } else { match it.next() { Some('t') => '\t', Some('n') => '\n', Some(o) => o, None => break } });
373+ }
374+ out
375+}
376+
377+impl Data {
378+ /// One line per project (P), ticket (T), ticket conversation entry (H) and activity (A).
379+ pub fn to_tsv(&self) -> String {
380+ let line = |f: Vec<String>| f.iter().map(|x| esc(x)).collect::<Vec<_>>().join("\t") + "\n";
381+ let act = |tag: &str, a: &Activity| line(vec![tag.into(), a.at.to_string(), a.project.clone(), a.ticket.to_string(), a.kind.clone(), a.text.clone()]);
382+ let mut out = String::new();
383+ for p in &self.projects { out += &line(vec!["P".into(), p.slug.clone(), p.path.clone(), p.slots.to_string()]); }
384+ for t in &self.tickets {
385+ let mut f = vec!["T".into(), t.project.clone(), t.id.to_string(), t.state.clone(), t.created.to_string(), t.since.to_string(), t.title.clone(), t.body.clone()];
386+ f.extend(t.files.iter().cloned());
387+ out += &line(f);
388+ for a in &t.thread { out += &act("H", a); }
389+ }
390+ for a in &self.activity { out += &act("A", a); }
391+ out
392+ }
393+
394+ pub fn from_tsv(text: &str) -> Data {
395+ let mut d = Data::default();
396+ for l in text.lines() {
397+ let f: Vec<String> = l.split('\t').map(unesc).collect();
398+ let g = |i: usize| f.get(i).cloned().unwrap_or_default();
399+ let n = |i: usize| g(i).parse::<u64>().unwrap_or(0);
400+ let act = || Activity { at: n(1), project: g(2), ticket: n(3) as u32, kind: g(4), text: g(5) };
401+ match g(0).as_str() {
402+ "P" => d.projects.push(Project { slug: g(1), path: g(2), slots: n(3) as u32 }),
403+ "T" => d.tickets.push(Ticket { project: g(1), id: n(2) as u32, state: g(3), created: n(4), since: n(5), title: g(6), body: g(7),
404+ files: f.iter().skip(8).cloned().collect(), thread: vec![] }),
405+ "H" => if let Some(t) = d.tickets.last_mut() { t.thread.push(act()) },
406+ "A" => d.activity.push(act()),
407+ _ => {}
408+ }
409+ }
410+ d
411+ }
412+}
413+
293414 pub fn now() -> f64 {
294415 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64())
295416 }
templates/library/preview/Cargo.toml+1−1
@@ -4,4 +4,4 @@ version = "0.0.0"
44 edition = "2024"
55
66 [dependencies]
7-rune = { git = "https://github.com/anomalyco/rune", rev = "3ff3cc6152b9034a1d996e3a5575c51fab3b56b8" }
7+rune = { git = "https://github.com/anomalyco/rune", rev = "3ff3cc6152b9034a1d996e3a5575c51fab3b56b8", features = ["native-file-dialog"] }
templates/library/preview/src/main.rs+71−28
@@ -1,14 +1,17 @@
1-//! Runs one widget as the whole app, with sample data, so it can be checked headless:
2-//! cargo run --release -p preview -- <kind> [child kinds…] --snap /tmp/x.png --tree /tmp/x.json --size 1200x800
3-//! It's the app's own host: children, shared values, handlers, animation and the instance's
4-//! folder (/tmp/preview/w/root) all work. Child kinds after the first are mounted into it, as
5-//! if the user had asked for them there. Requests for conveyord are printed, not sent.
1+//! Runs the library as the app does, headless, so it can be checked:
2+//! cargo run --release -p preview -- [--state DIR] <kind> [child kinds…] --snap /tmp/x.png --tree /tmp/x.json --size 1400x900
3+//! It's the app's own host: children, shared values, handlers, update, events, animation and
4+//! instance folders (/tmp/preview/w/<id>) all work. Child kinds after the first are mounted,
5+//! innermost instance first, as the app does after a build. Requests for conveyord are printed.
6+//!
7+//! --state DIR replays the user's app: its data, shared values and instance folders, copied so
8+//! the run can't change them, with what they Ctrl+clicked outlined in orange.
69 mod widgets {
710 include!(concat!(env!("OUT_DIR"), "/widgets.rs"));
811 }
912
10-use rune::{AppSpec, El, Tx};
11-use std::time::Duration;
13+use rune::{AppSpec, El, Tx, el};
14+use std::{path::{Path, PathBuf}, time::Duration};
1215 use widgets::api::{Activity, Data, Host, Live, Project, Ticket};
1316
1417 pub type HostState = State;
@@ -17,6 +20,8 @@ pub struct State {
1720 live: Live,
1821 kind: String,
1922 mounts: Vec<String>,
23+ /// The instance and element the user clicked, from --state.
24+ click: Option<(String, String)>,
2025 }
2126
2227 impl Host for State {
@@ -27,22 +32,27 @@ impl Host for State {
2732
2833 fn sample() -> Data {
2934 let p = |slug: &str| Project { slug: slug.into(), path: format!("/home/me/{slug}"), slots: 1 };
30- let t = |project: &str, id, state: &str, title: &str| Ticket { project: project.into(), id, state: state.into(), title: title.into() };
3135 let now = widgets::api::now() as u64;
3236 let a = |ago: u64, project: &str, ticket, kind: &str, text: &str| Activity { at: now - ago, project: project.into(), ticket, kind: kind.into(), text: text.into() };
37+ let t = |project: &str, id, state: &str, title: &str, ago: u64| Ticket {
38+ project: project.into(), id, state: state.into(), title: title.into(), body: format!("{title}.\n\nWhy: it's the next step."),
39+ created: now - ago - 600, since: now - ago, thread: vec![a(ago + 600, project, id, "prompt", title)], ..Default::default()
40+ };
41+ let mut tickets = vec![
42+ t("conveyor", 1, "running", "conveyord: store, dispatcher, VM and agent drivers", 300),
43+ t("conveyor", 2, "review", "Guest CLI: the agent's verbs", 900),
44+ t("conveyor", 3, "parked", "App shell: canvas and widget prompt", 1800),
45+ t("conveyor", 4, "draft", "Window chrome: minimize and edge resize", 3600),
46+ t("conveyor", 5, "ready", "Snapshots on decide", 60),
47+ t("dotfiles", 7, "ready", "Swap the terminal font", 120),
48+ t("dotfiles", 8, "done", "Add a git alias for amend", 7200),
49+ t("game", 1, "running", "Player movement", 90),
50+ t("game", 2, "failed", "Sound effects", 10),
51+ ];
52+ tickets[0].thread.push(a(240, "conveyor", 1, "decide", "Use a ring buffer for activity — bounded memory"));
53+ tickets[2].thread.push(a(60, "conveyor", 3, "block", "Needs the signing key — recommends: add it to the vault"));
3354 Data {
3455 projects: vec![p("conveyor"), p("dotfiles"), p("game")],
35- tickets: vec![
36- t("conveyor", 1, "running", "conveyord: store, dispatcher, VM and agent drivers"),
37- t("conveyor", 2, "review", "Guest CLI: the agent's verbs"),
38- t("conveyor", 3, "parked", "App shell: canvas and widget prompt"),
39- t("conveyor", 4, "draft", "Window chrome: minimize and edge resize"),
40- t("conveyor", 5, "ready", "Snapshots on decide"),
41- t("dotfiles", 7, "ready", "Swap the terminal font"),
42- t("dotfiles", 8, "done", "Add a git alias for amend"),
43- t("game", 1, "running", "Player movement"),
44- t("game", 2, "failed", "Sound effects"),
45- ],
4656 activity: vec![
4757 a(300, "conveyor", 1, "state", "running"),
4858 a(240, "conveyor", 1, "decide", "Use a ring buffer for activity"),
@@ -50,26 +60,58 @@ fn sample() -> Data {
5060 a(60, "conveyor", 3, "block", "Needs the signing key"),
5161 a(10, "game", 2, "state", "failed"),
5262 ],
63+ tickets,
64+ }
65+}
66+
67+/// A fresh copy of the user's instance folders and shared values in `base`.
68+fn replay(state: &Path, base: &Path) -> (Data, Option<(String, String)>) {
69+ let _ = std::fs::remove_dir_all(base);
70+ let _ = std::fs::create_dir_all(base);
71+ for f in ["w", "shared.tsv"].map(|f| state.join(f)).iter().filter(|f| f.exists()) {
72+ let _ = std::process::Command::new("cp").arg("-r").arg(f).arg(base).status();
5373 }
74+ let data = Data::from_tsv(&std::fs::read_to_string(state.join("data.tsv")).unwrap_or_default());
75+ let click = std::fs::read_to_string(state.join("click")).ok()
76+ .and_then(|c| c.trim_end_matches('\n').split_once('\t').map(|(i, e)| (i.to_owned(), e.to_owned())));
77+ (data, click)
5478 }
5579
5680 fn init() -> State {
57- let mut args = rune::extra_args().iter().cloned();
58- let kind = args.next().unwrap_or_default();
81+ let mut args: Vec<String> = rune::extra_args().to_vec();
82+ let mut state = None;
83+ if let Some(i) = args.iter().position(|a| a == "--state") {
84+ state = args.get(i + 1).map(PathBuf::from);
85+ args.drain(i..(i + 2).min(args.len()));
86+ }
5987 let base = std::env::temp_dir().join("preview");
88+ let (data, click) = match state {
89+ Some(dir) => replay(&dir, &base),
90+ None => (sample(), None),
91+ };
6092 let mut live = Live::new(base);
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/canvas.rs+1−1
Cut short: this commit's diff is over 1000 lines.