@@ -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 }