@@ -0,0 +1,158 @@
1+//! One ticket, opened from a board: its title and body (editable while it isn't running; Save
2+//! rewrites it), attached files, its conversation with times, and what its state allows next.
3+//! In review it shows the branch's diff stat; parked, the block and its recommendation.
4+use super::{api::*, board::ago, canvas};
5+use rune::{El, Family, ScrollSpec, TextEdit, Tx, col, el, oklch, row, text, text_input, tok};
6+use std::{path::PathBuf, sync::{Arc, Mutex}};
7+
8+pub const WIDGET: Widget = Widget { title: "Ticket", size: (480.0, 620.0), new: |cx| Box::new(TicketCard::load(cx)) };
9+
10+pub struct TicketCard {
11+ title: TextEdit,
12+ body: TextEdit,
13+ /// The title and body as conveyor last had them: the fields follow them until edited.
14+ base: (String, String),
15+ /// Unsaved edits, kept as a "draft" file (title, a line break, body) across reloads.
16+ draft: PathBuf,
17+ /// `git diff --stat HEAD...t-<id>`, run when the ticket entered review at this time.
18+ diff: Arc<Mutex<Option<String>>>,
19+ diff_for: u64,
20+}
21+
22+/// The ticket this card shows: its key is `ticket-<id>` on the project's desktop.
23+fn ticket<'a>(cx: &'a Cx) -> Option<&'a Ticket> {
24+ let id: u32 = cx.id.rsplit('.').next()?.strip_prefix("ticket-")?.parse().ok()?;
25+ let project = super::root::project_of(cx.id);
26+ cx.data.tickets.iter().find(|k| k.project == project && k.id == id)
27+}
28+
29+impl TicketCard {
30+ fn load(cx: &Cx) -> Self {
31+ let draft = cx.dir.join("draft");
32+ let (title, body) = std::fs::read_to_string(&draft).ok().and_then(|s| s.split_once('\n').map(|(a, b)| (a.to_owned(), b.to_owned())))
33+ .or_else(|| ticket(cx).map(|k| (k.title.clone(), k.body.clone()))).unwrap_or_default();
34+ let base = ticket(cx).map(|k| (k.title.clone(), k.body.clone())).unwrap_or_default();
35+ TicketCard { title: TextEdit::new(title), body: TextEdit::new(body), base, draft, diff: Arc::default(), diff_for: 0 }
36+ }
37+
38+ fn modified(&self) -> bool {
39+ (self.title.text.as_str(), self.body.text.as_str()) != (self.base.0.as_str(), self.base.1.as_str())
40+ }
41+}
42+
43+impl View for TicketCard {
44+ fn update(&mut self, cx: &Cx) {
45+ let Some(k) = ticket(cx) else { return };
46+ if (k.title.as_str(), k.body.as_str()) != (self.base.0.as_str(), self.base.1.as_str()) {
47+ if !self.modified() { (self.title, self.body) = (TextEdit::new(k.title.clone()), TextEdit::new(k.body.clone())) }
48+ self.base = (k.title.clone(), k.body.clone());
49+ }
50+ let draft = format!("{}\n{}", self.title.text, self.body.text);
51+ if !self.modified() { let _ = std::fs::remove_file(&self.draft); }
52+ else if std::fs::read_to_string(&self.draft).ok().as_deref() != Some(&draft) { let _ = std::fs::write(&self.draft, draft); }
53+ if k.state == "review" && self.diff_for != k.since {
54+ self.diff_for = k.since;
55+ let (out, path, branch) = (self.diff.clone(), cx.data.projects.iter().find(|p| p.slug == k.project).map(|p| p.path.clone()).unwrap_or_default(), format!("HEAD...t-{}", k.id));
56+ *out.lock().unwrap() = None;
57+ std::thread::spawn(move || {
58+ let r = std::process::Command::new("git").args(["diff", "--stat", &branch]).current_dir(&path).output();
59+ let s = match r {
60+ Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim_end().to_owned(),
61+ Ok(o) => String::from_utf8_lossy(&o.stderr).trim_end().to_owned(),
62+ Err(e) => format!("git: {e}"),
63+ };
64+ *out.lock().unwrap() = Some(if s.is_empty() { "No changes".into() } else { s });
65+ });
66+ }
67+ }
68+
69+ fn view(&self, cx: &Cx) -> El {
70+ let t = tok::theme(true);
71+ let Some(k) = ticket(cx) else {
72+ return col().w_full().h_full().center().gap(8.0).child(text("No ticket here: open one from a board").color(t.text_secondary)).child(canvas::close(cx, "Close"));
73+ };
74+ let running = k.state == "running";
75+ let label = |s: &str| text(s).font(tok::type_::LABEL).color(t.text_secondary);
76+ let field = |e: &TextEdit| text_input(e, tok::type_::BODY).w_full().px(8.0).py(6.0).radius(6.0).fill(t.bg).color(t.text);
77+ let mut body = col().w_full().gap(10.0);
78+ body = if running {
79+ body.child(text(&k.title).font(tok::type_::TITLE).color(t.text).w_full().wrap())
80+ .child(text(&k.body).color(t.text).w_full().wrap())
81+ .child(label("Running: editing waits until it settles"))
82+ } else {
83+ body.child(field(&self.title).key("title").single_line().on_edit(edit(cx.id, |c: &mut TicketCard| &mut c.title)))
84+ .child(field(&self.body).key("body").min_h(120.0).on_edit(edit(cx.id, |c: &mut TicketCard| &mut c.body)))
85+ };
86+ if !k.files.is_empty() {
87+ let mut files = col().key("files").w_full().gap(2.0).child(label("Files"));
88+ for f in &k.files {
89+ let path = f.clone();
90+ let name = std::path::Path::new(f).file_name().map_or(f.clone(), |n| n.to_string_lossy().into_owned());
91+ files = files.child(row().key(format!("file-{name}")).w_full().px(6.0).py(4.0).radius(5.0).role("button").label(name.as_str()).help(f.as_str()).hover(t.hover)
92+ .on_press_tx(move |_: &mut HostState, _: &mut Tx| { let _ = std::process::Command::new("xdg-open").arg(&path).spawn(); })
93+ .child(text(format!("▤ {name}")).font(tok::type_::LABEL).color(t.text).truncate()));
94+ }
95+ body = body.child(files);
96+ }
97+ if k.state == "review" {
98+ let diff = self.diff.lock().unwrap().clone().unwrap_or_else(|| "…".into());
99+ body = body.child(col().key("diff").w_full().gap(4.0).padding(8.0).radius(6.0).fill(t.bg)
100+ .child(text(format!("Branch t-{}", k.id)).font(tok::type_::LABEL).color(t.text))
101+ .child(text(diff).font(tok::type_::LABEL.family(Family::SystemMono)).color(t.text_secondary).w_full().wrap()));
102+ }
103+ if k.state == "parked" && let Some(b) = k.thread.iter().rev().find(|a| a.kind == "block") {
104+ body = body.child(col().key("block").w_full().gap(4.0).padding(8.0).radius(6.0).fill(t.bg).border(1.0, oklch(0.75, 0.14, 70.0))
105+ .child(text("Blocked").font(tok::type_::LABEL).color(oklch(0.8, 0.14, 70.0)))
106+ .child(text(&b.text).font(tok::type_::LABEL).color(t.text).w_full().wrap())
107+ .child(label("Answer it in the body, then Ready")));
108+ }
109+ let mut thread = col().key("thread").w_full().gap(6.0).child(label("Conversation"));
110+ for (i, a) in k.thread.iter().enumerate() {
111+ thread = thread.child(col().key(format!("entry-{i}")).w_full().gap(2.0)
112+ .child(row().w_full().gap(6.0).child(text(&a.kind).font(tok::type_::LABEL).color(t.text)).child(el().grow(1.0)).child(label(&ago(cx.now, a.at))))
113+ .child(text(&a.text).font(tok::type_::LABEL).color(t.text_secondary).w_full().wrap()));
114+ }
115+ col().w_full().h_full().gap(10.0)
116+ .child(row().key("header").w_full().center_y().gap(8.0)
117+ .child(text(format!("#{}", k.id)).font(tok::type_::TITLE).color(t.text))
118+ .child(row().px(8.0).py(2.0).radius(8.0).fill(t.press).child(text(&k.state).font(tok::type_::LABEL).color(t.text)))
119+ .child(label(&ago(cx.now, k.since)))
120+ .child(el().grow(1.0))
121+ .child(canvas::maximize(cx))
122+ .child(canvas::close(cx, "Close ticket")))
123+ .child(col().key("content").w_full().grow(1.0).min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(body.child(thread)))
124+ .child(self.actions(cx, k))
125+ }
126+}
127+
128+impl TicketCard {
129+ /// Save while edited, and the moves the ticket's state allows.
130+ fn actions(&self, cx: &Cx, k: &Ticket) -> El {
131+ let mut bar = row().key("actions").w_full().gap(8.0).child(el().grow(1.0));
132+ if k.state != "running" && self.modified() { bar = bar.child(button(cx, k, "save", "Save", None, true)) }
133+ // A parked ticket goes back once its body has the answer: it differs from what the agent was given.
134+ let answered = k.thread.iter().rev().find(|a| a.kind == "prompt").is_none_or(|p| p.text.trim() != self.body.text.trim());
135+ match k.state.as_str() {
136+ "draft" => bar.child(button(cx, k, "ready", "Ready", Some("ready"), true)),
137+ "failed" => bar.child(button(cx, k, "retry", "Ready to retry", Some("ready"), true)),
138+ "parked" => bar.child(button(cx, k, "ready", "Ready", Some("ready"), answered)),
139+ "review" => bar.child(button(cx, k, "back", "Back to draft", Some("draft"), true)).child(button(cx, k, "done", "Done", Some("done"), true)),
140+ _ => bar,
141+ }
142+ }
143+}
144+
145+/// A button that saves any edits, then moves the ticket to `to`. Dimmed and inert unless `on`.
146+fn button(cx: &Cx, k: &Ticket, key: &str, label: &str, to: Option<&'static str>, on: bool) -> El {
147+ let t = tok::theme(true);
148+ let (id, project, ticket) = (cx.id.to_owned(), k.project.clone(), k.id);
149+ let b = row().key(key).h(28.0).px(12.0).center().radius(6.0).role("button").label(label).disabled(!on).fill(t.press)
150+ .child(text(label).font(tok::type_::LABEL).color(if on { t.text } else { t.text_secondary }));
151+ if !on { return b.opacity(0.5) }
152+ b.hover(t.hover).on_press_tx(move |h: &mut HostState, _: &mut Tx| {
153+ let Some(c) = get::<TicketCard>(h, &id) else { return };
154+ let edits = c.modified().then(|| (c.title.text.trim().to_owned(), c.body.text.clone()));
155+ if let Some((title, body)) = edits { edit_ticket(h, &project, ticket, &title, &body) }
156+ if let Some(to) = to { set_state(h, &project, ticket, to) }
157+ })
158+}