Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Show what a build is doing now and how long it has been quiet (#6)

Brandon Thomas6fe3d7f15864
diff --git a/crates/ai/src/rebuild/feed.rs b/crates/ai/src/rebuild/feed.rs
index 9b2a9e6a..2b73ae4a 100644
--- a/crates/ai/src/rebuild/feed.rs
+++ b/crates/ai/src/rebuild/feed.rs
@@ -102,14 +102,40 @@ pub(super) struct FeedLog {
root: PathBuf,
feed: Vec<FeedItem>,
saved_at: Option<std::time::Instant>,
+ activity: Arc<Activity>,
+}
+
+/// When a run last had anything to say, readable while drawing without taking any lock.
+#[derive(Debug)]
+pub(super) struct Activity {
+ began: std::time::Instant,
+ last_ms: std::sync::atomic::AtomicU64,
+}
+
+impl Activity {
+ fn touch(&self) {
+ let ms = u64::try_from(self.began.elapsed().as_millis()).unwrap_or(u64::MAX);
+ self.last_ms.store(ms, Ordering::Relaxed);
+ }
+
+ /// How long it has been since the last event.
+ pub(super) fn quiet_for(&self) -> Duration {
+ self.began.elapsed().saturating_sub(Duration::from_millis(self.last_ms.load(Ordering::Relaxed)))
+ }
}
impl FeedLog {
pub(super) fn open(ws: &Workspace) -> FeedLog {
- FeedLog { root: ws.root.clone(), feed: load(ws), saved_at: None }
+ let activity = Arc::new(Activity { began: std::time::Instant::now(), last_ms: 0.into() });
+ FeedLog { root: ws.root.clone(), feed: load(ws), saved_at: None, activity }
+ }
+
+ pub(super) fn activity(&self) -> Arc<Activity> {
+ self.activity.clone()
}
pub(super) fn record(&mut self, e: &RunEvent) {
+ self.activity.touch();
apply(&mut self.feed, e);
self.save(matches!(e, RunEvent::Finished { .. }));
}
@@ -152,6 +178,18 @@ impl FeedLog {
mod tests {
use super::*;
+ #[test]
+ fn every_event_counts_as_activity() {
+ let d = tempfile::tempdir().unwrap();
+ let ws = Workspace::create(d.path(), "x", "y", TargetRef::None).unwrap();
+ let mut log = FeedLog::open(&ws);
+ let activity = log.activity();
+ std::thread::sleep(Duration::from_millis(30));
+ assert!(activity.quiet_for() >= Duration::from_millis(30));
+ log.record(&RunEvent::Step { step: Step::Study, text: "Looking".into() });
+ assert!(activity.quiet_for() < Duration::from_millis(30));
+ }
+
#[test]
fn the_builders_checklist_is_one_list_updated_in_place() {
let todo = |status: &str| {
diff --git a/crates/ai/src/rebuild/mod.rs b/crates/ai/src/rebuild/mod.rs
index d7e03082..06989d0a 100644
--- a/crates/ai/src/rebuild/mod.rs
+++ b/crates/ai/src/rebuild/mod.rs
@@ -181,6 +181,7 @@ pub struct RebuildRun {
feed: Arc<Mutex<feed::FeedLog>>,
pub root: PathBuf,
started: Instant,
+ activity: Arc<feed::Activity>,
}
impl RebuildRun {
@@ -268,7 +269,8 @@ impl RebuildRun {
r2.store(false, Ordering::SeqCst);
})
.map_err(|e| ToolError::internal(e.to_string()))?;
- Ok(RebuildRun { rx, stop, inbox, running, preview, notes, feed, root, started: Instant::now() })
+ let activity = feed.lock().unwrap_or_else(PoisonError::into_inner).activity();
+ Ok(RebuildRun { rx, stop, inbox, running, preview, notes, feed, root, started: Instant::now(), activity })
}
/// Add something while it works; the agent reads it at its next step, and only then does it
@@ -348,6 +350,11 @@ impl RebuildRun {
self.started
}
+ /// How long since the run last had anything to say. Cheap: safe to read while drawing.
+ pub fn quiet_for(&self) -> Duration {
+ self.activity.quiet_for()
+ }
+
pub fn preview_url(&self) -> Option<String> {
self.preview.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map(StaticServer::url)
}
@@ -439,7 +446,12 @@ impl Worker {
self.stop.check()?;
// The person started this run for this target, which is the consent for opening it.
let opts = CallOptions::new(Caller::Ui).with_consent(craft_anything_engine::Consent::Granted).with_cancel(self.stop.clone());
- self.engine.call(tool, params, opts)
+ // Said as it happens, so a long step shows what it's doing and the feed counts it.
+ let call_id = format!("run-{tool}");
+ self.emit(RunEvent::Agent(AgentEvent::ToolStarted { call_id: call_id.clone(), tool: tool.to_string(), input: Value::Null }));
+ let result = self.engine.call(tool, params, opts);
+ self.emit(RunEvent::Agent(AgentEvent::ToolFinished { call_id, tool: tool.to_string(), ok: result.is_ok(), summary: String::new(), evidence_id: None }));
+ result
}
/// Point the engine at this workspace: its investigation project and inbox.
@@ -579,6 +591,7 @@ impl Worker {
let api_loop = api.is_some();
// A coding agent that never saved a session starts over, so it needs the brief.
let has_history = resumable && (api_loop || ws.manifest.agent_session.is_some());
+ self.step(ws, Step::Build, Status::Building, "Getting the builder ready…")?;
let spec = self.agent_spec(ws, &entry, opts);
let mut agent: Box<dyn Conversation> = match api {
Some(a) => Box::new(a),
diff --git a/crates/ai/src/rebuild/stand_in.rs b/crates/ai/src/rebuild/stand_in.rs
index 57bad996..acdd5e1c 100644
--- a/crates/ai/src/rebuild/stand_in.rs
+++ b/crates/ai/src/rebuild/stand_in.rs
@@ -53,7 +53,9 @@ impl StandIns {
tx,
feed: feed.clone(),
});
+ let activity = feed.lock().unwrap_or_else(PoisonError::into_inner).activity();
Ok(RebuildRun {
+ activity,
rx,
stop: CancelToken::default(),
inbox: Inbox::new(ws.inbox_dir()),
diff --git a/crates/ui-egui/src/project.rs b/crates/ui-egui/src/project.rs
index 4ed6d8b5..022ca372 100644
--- a/crates/ui-egui/src/project.rs
+++ b/crates/ui-egui/src/project.rs
@@ -961,9 +961,22 @@ fn feed(app: &mut CraftApp, ui: &mut Ui, ws: &Workspace) {
_ => 0,
})
.sum();
- let detail = (done > 0).then(|| crate::i18n::trf("{n} actions done so far", &[("n", &done.to_string())]));
- let began = app.open_run().map(RebuildRun::started);
- widgets::working_since(ui, title.unwrap_or("Working on it"), detail.as_deref(), began);
+ // The action under way, in words when it's one of ours.
+ let current = items[step.map_or(0, |s| s + 1)..].iter().rev().find_map(|i| match i {
+ FeedItem::Work { tools, .. } => tools.iter().rev().find(|(_, d)| d.is_none()).map(|(t, _)| t.as_str()),
+ _ => None,
+ });
+ let current = current.map(|t| app.engine.registry().canonical(t).and_then(|id| app.engine.registry().get(id)).map_or(t, |s| s.title));
+ let detail = [
+ current.map(|c| crate::i18n::trf("Now: {what}", &[("what", c)])),
+ (done > 0).then(|| crate::i18n::trf("{n} actions done so far", &[("n", &done.to_string())])),
+ ]
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>()
+ .join(" · ");
+ let (began, quiet) = app.open_run().map_or((None, None), |r| (Some(r.started()), Some(r.quiet_for())));
+ widgets::working_since(ui, title.unwrap_or("Working on it"), (!detail.is_empty()).then_some(detail.as_str()), began, quiet);
}
for (id, a, shown) in answers {
app.answer_request(&id, a, shown);
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 31d497fd..68c2ec22 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -397,16 +397,37 @@ pub fn thinking(ui: &mut Ui) {
animate(ui, FRAME);
}
+/// How long a run may say nothing before the note points it out.
+const QUIET_NOTE_AFTER: std::time::Duration = std::time::Duration::from_secs(60);
+
+fn wait_note(secs: u64, quiet: Option<std::time::Duration>) -> Option<String> {
+ match quiet {
+ Some(q) if q >= QUIET_NOTE_AFTER => Some(crate::i18n::trf(
+ "Nothing new for {time}. Long steps can be quiet; if it stays like this, press Pause.",
+ &[("time", &crate::usage::duration_words(q))],
+ )),
+ Some(_) => None,
+ None => match secs {
+ 0..20 => None,
+ 20..90 => Some(tr("Still working. Bigger jobs can take a few minutes.")),
+ _ => Some(tr("This is a big one. You can leave this open and come back later.")),
+ },
+ }
+}
+
/// "Still working" for waits longer than a moment: a spinning arc, what's happening, how long
/// it has taken, and a calm note once it runs long (so a quiet wait never looks stuck).
/// `title` is translated here; `detail` arrives already in the user's words.
pub fn working(ui: &mut Ui, title: &str, detail: Option<&str>) {
- working_since(ui, title, detail, None);
+ working_since(ui, title, detail, None, None);
}
/// [`working`] with its clock from `began` (a build's start), so it doesn't restart each time the
/// row comes back; without it, from when the row was last shown.
-pub fn working_since(ui: &mut Ui, title: &str, detail: Option<&str>, began: Option<std::time::Instant>) {
+///
+/// `quiet` is how long since the work last had anything to say, when that's known: then the note
+/// says so plainly, because a calm note can't tell a long step from one that has stopped.
+pub fn working_since(ui: &mut Ui, title: &str, detail: Option<&str>, began: Option<std::time::Instant>, quiet: Option<std::time::Duration>) {
let t = Tokens::get(ui.ctx());
let now = ui.input(|i| i.time);
// The clock restarts when the row wasn't on screen a moment ago.
@@ -415,11 +436,7 @@ pub fn working_since(ui: &mut Ui, title: &str, detail: Option<&str>, began: Opti
let since = if now - seen > 1.0 { now } else { since };
ui.data_mut(|d| d.insert_temp(id, (since, now)));
let secs = began.map_or((now - since) as u64, |b| b.elapsed().as_secs());
- let note = match secs {
- 0..20 => None,
- 20..90 => Some(tr("Still working. Bigger jobs can take a few minutes.")),
- _ => Some(tr("This is a big one. You can leave this open and come back later.")),
- };
+ let note = wait_note(secs, quiet);
let sub = [detail.map(str::to_string), note].into_iter().flatten().collect::<Vec<_>>().join(" · ");
card(&t).inner_margin(Margin::symmetric(16, 12)).show(ui, |ui| {
ui.set_width(ui.available_width());
@@ -460,3 +477,17 @@ pub fn open_log_button(ui: &mut Ui, path: &std::path::Path) -> bool {
ui.add_space(6.0);
secondary(ui, None, "Open log").on_hover_text(path.display().to_string()).clicked()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::Duration;
+
+ #[test]
+ fn the_wait_note_says_when_nothing_is_happening() {
+ let quiet = wait_note(4000, Some(Duration::from_secs(150))).unwrap();
+ assert!(quiet.contains("Nothing new for") && !quiet.contains("big one"), "{quiet}");
+ assert_eq!(wait_note(4000, Some(Duration::from_secs(5))), None, "it's visibly moving: nothing to add");
+ assert!(wait_note(4000, None).unwrap().contains("big one"), "without news to go on, the old note");
+ }
+}