@@ -1,7 +1,8 @@
1-//! The widget library: the `widgets` project. A prompt from the canvas becomes a ticket there;
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};
4-use serde_json::json;
1+//! The widget library: the `widgets` project. A Ctrl+click in the app becomes a build ticket
2+//! there, carrying what was clicked; a done ticket is merged and the app rebuilt with it.
3+use crate::{agent::git, paths, store::{self, Project}, thread, vm};
4+use serde::{Deserialize, Serialize};
5+use serde_json::{Value, json};
56 use std::{fs, process::Command, sync::Mutex};
67
78 pub const SLUG: &str = "widgets";
@@ -10,11 +11,30 @@ static BUILD: Mutex<()> = Mutex::new(());
1011 /// Conveyor's side of the library: kept in step with the template on every start.
1112 const OWNED: [&str; 8] = ["api.rs", "gen.rs", "CLAUDE.md", "Cargo.toml", "rust-toolchain.toml",
1213 "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-
1614 const COMMIT: [&str; 4] = ["-c", "user.name=conveyor", "-c", "user.email=conveyor@localhost"];
1715
16+/// What a build ticket was asked about, and what it changed: build.json beside ticket.md.
17+#[derive(Serialize, Deserialize, Default, Clone)]
18+pub struct Build {
19+ /// The kind (file name) of the widget clicked.
20+ pub kind: String,
21+ /// The instance clicked and then its parents, each with the point clicked in its own points.
22+ pub targets: Vec<(String, f32, f32)>,
23+ /// Widget kinds the merged branch added, and every kind it touched.
24+ #[serde(default)]
25+ pub created: Vec<String>,
26+ #[serde(default)]
27+ pub changed: Vec<String>,
28+}
29+
30+fn build(id: u32) -> Option<Build> {
31+ serde_json::from_str(&fs::read_to_string(store::dir(SLUG, id).join("build.json")).ok()?).ok()
32+}
33+
34+fn save_build(id: u32, b: &Build) {
35+ let _ = fs::write(store::dir(SLUG, id).join("build.json"), serde_json::to_string_pretty(b).unwrap());
36+}
37+
1838 /// Creates the library from conveyor's template on first run, and updates conveyor's files in it.
1939 pub fn ensure() -> Result<(), String> {
2040 let (lib, tpl) = (paths::library(), paths::source().join("templates/library"));
@@ -35,46 +55,56 @@ pub fn ensure() -> Result<(), String> {
3555 Ok(())
3656 }
3757
38-/// A prompt written on the canvas at (x, y): a ready ticket, and a placeholder where it was clicked.
39-/// With `about`, the user Ctrl+clicked that widget: the new ticket follows up on it.
40-pub fn request(prompt: &str, x: f32, y: f32, about: Option<u32>) -> u32 {
41- let title: String = prompt.lines().next().unwrap_or("widget").chars().take(70).collect();
42- let placed = about.and_then(|a| canvas::load().into_iter().find(|p| p.id == a));
43- let context = match &placed {
44- Some(p) => follow_up(p, x - p.x, y - p.y),
45- None => format!("The user asked for this widget by clicking at ({x:.0}, {y:.0}) on the canvas."),
46- };
47- let id = store::create(SLUG, &title, &format!("{prompt}\n\n---\n\n{context}"), "ready");
48- match placed {
49- Some(p) => canvas::follow(p.id, id),
50- None => canvas::place(id, x, y),
51- }
52- id
58+/// Tickets about a widget kind, oldest first: asked from it, or that changed it.
59+fn about(kind: &str) -> Vec<u32> {
60+ 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()
5361 }
5462
55-/// What the user clicked, and the conversation behind it so far.
56-fn follow_up(p: &Placed, x: f32, y: f32) -> String {
57- let what = match &p.widget {
58- 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."),
59- None => "The user Ctrl+clicked a widget that no ticket has built yet. Build what the conversation asks for.".into(),
60- };
61- let history: String = thread::of(&p.tickets).iter()
63+/// A Ctrl+click: the prompt, and everything the app knew about what was under the pointer.
64+pub fn request(r: &Value) -> u32 {
65+ let s = |k: &str| r[k].as_str().unwrap_or("").trim().to_owned();
66+ let (prompt, kind) = (s("prompt"), if s("kind").is_empty() { "root".into() } else { s("kind") });
67+ let targets: Vec<(String, f32, f32)> = serde_json::from_value(r["targets"].clone()).unwrap_or_default();
68+ let (target, x, y) = targets.first().cloned().unwrap_or(("root".into(), 0.0, 0.0));
69+ let parents: String = targets.iter().skip(1).map(|t| format!("`{}`", t.0)).collect::<Vec<_>>().join(", ");
70+ let history: String = thread::of(&about(&kind)).iter()
6271 .map(|e| format!("- #{} {}: {}\n", e["ticket"], e["kind"].as_str().unwrap_or(""), e["text"].as_str().unwrap_or("").replace('\n', "\n ")))
6372 .collect();
64- format!("{what}\n\nThe conversation so far, oldest first:\n\n{history}")
73+ let context = format!(
74+ "The user Ctrl+clicked the `{kind}` widget (`widgets/{kind}.rs`), instance `{target}`, at ({x:.0}, {y:.0}) inside it.\n\
75+ Its parents, innermost first: {parents}\n\
76+ The element under the pointer: `{element}`\n\n\
77+ The widgets on screen, as instance (kind):\n\n{tree}\n\n\
78+ Shared values: {shared}\n\n\
79+ 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") },
82+ 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");
85+ save_build(id, &Build { kind, targets, ..Default::default() });
86+ id
6587 }
6688
67-/// Merges a done widget ticket into the library, then rebuilds the app with it.
89+/// Merges a done build ticket into the library, then rebuilds the app with it.
6890 pub fn install(p: &Project, id: u32, branch: &str) -> Result<(), String> {
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"));
91+ let range = format!("main...{branch}");
92+ let changed = git(&p.path, "", &["diff", "--name-only", &range])?;
93+ if let Some(f) = changed.lines().find(|f| !f.starts_with("widgets/")) {
94+ return Err(format!("the branch changes {f}, which is conveyor's; only widgets/ is the library's"));
7295 }
73- let widget = changed.lines().find_map(|f| f.strip_prefix("widgets/")?.strip_suffix(".rs")).map(String::from);
96+ let kinds = |list: String| list.lines().filter_map(|f| f.strip_prefix("widgets/")?.strip_suffix(".rs").map(String::from)).collect::<Vec<_>>();
97+ let created = kinds(git(&p.path, "", &["diff", "--name-only", "--diff-filter=A", &range])?);
7498 git(&p.path, "", &[&COMMIT[..], &["merge", "-q", "--no-edit", branch]].concat())?;
7599 store::event(SLUG, id, json!({"kind": "conveyor", "msg": "merged; rebuilding the app"}));
76- rebuild_app()?;
77- if let Some(w) = widget { canvas::set_widget(id, &w); }
100+ // A library that doesn't build never stays on main: the app could not restart into it.
101+ if let Err(e) = rebuild_app() {
102+ git(&p.path, "", &["reset", "-q", "--hard", "ORIG_HEAD"])?;
103+ return Err(format!("the app doesn't build with this branch, so it was not merged:\n{e}"));
104+ }
105+ let mut b = build(id).unwrap_or_default();
106+ (b.created, b.changed) = (created, kinds(changed));
107+ save_build(id, &b);
78108 Ok(())
79109 }
80110
@@ -85,16 +115,16 @@ fn rebuild_app() -> Result<(), String> {
85115 .args(["build", "--release", "-q", "-p", "conveyor-app"])).map(|_| ())
86116 }
87117
88-/// Everything the app shows: tickets, and each widget with its frame and its thread.
89-pub fn snapshot() -> serde_json::Value {
90- let tickets: Vec<_> = store::projects().iter().flat_map(|p| store::tickets(&p.slug)).collect();
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
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| {
123+ 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])}))
98127 }).collect();
99- json!({"tickets": tickets, "canvas": canvas})
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})
100130 }