Craft Anything: understand how any software works, and craft your own.
Rust
Show what a build is on now, and open up into its activity as it arrives (#10)
Brandon Thomas4756633f8985
diff --git a/apps/craft-anything-cli/src/rebuild_cmd.rs b/apps/craft-anything-cli/src/rebuild_cmd.rsindex 0ae5a3b3..8375176b 100644--- a/apps/craft-anything-cli/src/rebuild_cmd.rs+++ b/apps/craft-anything-cli/src/rebuild_cmd.rs@@ -145,9 +145,9 @@ fn run(cli: &Cli, a: &RebuildArgs) -> Result<bool, ToolError> {print!("{text}");line_open = !text.ends_with('\n');}- RunEvent::Agent(AgentEvent::ToolStarted { tool, .. }) => {+ RunEvent::Agent(AgentEvent::ToolStarted { tool, input, .. }) => {end_line(&mut line_open);- println!(" · {tool}");+ println!(" · {}", rebuild::activity::describe(&tool, &input, &[]).words());}RunEvent::Agent(AgentEvent::Error { message, remediation, log }) => {end_line(&mut line_open);diff --git a/crates/ai/src/cli_agents/acp.rs b/crates/ai/src/cli_agents/acp.rsindex f5970165..28cda5ed 100644--- a/crates/ai/src/cli_agents/acp.rs+++ b/crates/ai/src/cli_agents/acp.rs@@ -474,6 +474,7 @@ impl AcpConversation {*self.lock() = Some(Shared { core, stdin: None, stderr: VecDeque::new(), approver: self.approver.clone() });let (shared, tx, busy) = (self.shared.clone(), self.tx.clone(), self.busy.clone());let shared_err = self.shared.clone();+ let tx_err = tx.clone();let mut proc = Process::new(&self.program).args(&self.args).cwd(&self.cwd)@@ -490,6 +491,9 @@ impl AcpConversation {}}).on_stderr_line(move |l| {+ if !l.trim().is_empty() {+ let _ = tx_err.send(AgentEvent::Output { text: l.to_string() });+ }let mut g = shared_err.lock().unwrap_or_else(PoisonError::into_inner);if let Some(s) = g.as_mut() {if s.stderr.len() >= 20 {diff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rsindex 35eb3e1c..e7b05460 100644--- a/crates/ai/src/cli_agents/mod.rs+++ b/crates/ai/src/cli_agents/mod.rs@@ -435,7 +435,7 @@ fn run_cli(spec: &CliSpec, text: &str, tx: &Sender<AgentEvent>, stop: &Stop, seslet _ =tx.send(AgentEvent::Status { text: format!("Asking {}{}…", display_for(&agent), remote.as_ref().map(|h| format!(" on {h}")).unwrap_or_default()) });let parser = Arc::new(Mutex::new(StreamParser::new(adapter.clone())));- let (p2, tx2) = (parser.clone(), tx.clone());+ let (p2, tx2, tx_err) = (parser.clone(), tx.clone(), tx.clone());let stop2 = stop.clone();// A builder turn may take hours and sit silent for long stretches: Ghidra's first look at a big// game, an engine build, or the person answering a question. Claude Code's own limits are@@ -464,6 +464,11 @@ fn run_cli(spec: &CliSpec, text: &str, tx: &Sender<AgentEvent>, stop: &Stop, seslet _ = tx2.send(e);}})+ .on_stderr_line(move |l| {+ if !l.trim().is_empty() {+ let _ = tx_err.send(AgentEvent::Output { text: l.to_string() });+ }+ }).remediation(format!("Install {} or set its path in Settings → AI.", display_for(&agent)));if let Some(p) = spec.project.as_ref().filter(|_| remote.is_none()) {proc = proc.cwd(p);diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rsindex e3678ae9..bf2cadd8 100644--- a/crates/ai/src/lib.rs+++ b/crates/ai/src/lib.rs@@ -144,6 +144,11 @@ pub enum AgentEvent {Status {text: String,},+ /// A line a program printed outside the conversation (its stderr), for logs: never part of+ /// the answer.+ Output {+ text: String,+ },ToolStarted {call_id: String,tool: String,diff --git a/crates/ai/src/rebuild/activity.rs b/crates/ai/src/rebuild/activity.rsnew file mode 100644index 00000000..6ab3ebd3--- /dev/null+++ b/crates/ai/src/rebuild/activity.rs@@ -0,0 +1,551 @@+//! What a run is doing, in more detail than the feed keeps: the action under way in words, the+//! last lines in memory for the screen, and every line in the project's `build-activity.log`.+//!+//! The screen reads only memory; the log is written by the run ([`ActivityFile`], from+//! [`super::feed::FeedLog`]), so a slow drive never holds up drawing. Everything written here went+//! through [`journal::scrubbed_line`]: commands can carry keys, and the log is a file people share.++use super::*;+use craft_anything_engine::journal;+use craft_anything_engine::workspace::{ACTIVITY_LOG, ACTIVITY_LOG_OLD};+use std::collections::VecDeque;+use std::io::Write;+use std::ops::Range;++/// Lines kept in memory for the screen; the log has them all.+const KEPT_LINES: usize = 1000;+/// The longest line kept, in characters.+const LONGEST_LINE: usize = 600;+/// The longest thing an action names, in characters.+const LONGEST_OBJECT: usize = 200;+/// A log this long is set aside as `build-activity.old.log` and a new one started.+const LOG_LIMIT: u64 = 8 << 20;++/// A kind of line, so a screen can colour it and a log can tag it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum LineKind {+ /// The workflow moved on to something new.+ Stage,+ /// A tool or program started.+ Started,+ Done,+ Failed,+ /// What the builder said.+ Said,+ Note,+ /// What a program printed that isn't part of the conversation.+ Output,+ Problem,+}++impl LineKind {+ pub fn tag(self) -> &'static str {+ match self {+ LineKind::Stage => "stage",+ LineKind::Started => "start",+ LineKind::Done => "done",+ LineKind::Failed => "FAIL",+ LineKind::Said => "said",+ LineKind::Note => "note",+ LineKind::Output => "out",+ LineKind::Problem => "ERROR",+ }+ }+}++#[derive(Debug, Clone, PartialEq)]+pub struct ActivityLine {+ /// How far into the run.+ pub at: Duration,+ pub kind: LineKind,+ pub text: String,+}++/// One thing the builder does, in parts, so a screen can use the tool's own title.+#[derive(Debug, Clone, PartialEq)]+pub struct Action {+ pub tool: String,+ /// How it reads, when it's a tool we have words for.+ pub verb: Option<&'static str>,+ /// What it's working on: a command, a file, an address.+ pub object: Option<String>,+}++/// How a tool's calls read: the words, and the fields that say what it's working on.+struct ToolWords {+ tools: &'static [&'static str],+ verb: &'static str,+ fields: &'static [&'static str],+}++const TOOL_WORDS: &[ToolWords] = &[+ ToolWords { tools: &["Bash", "PowerShell"], verb: "Running", fields: &["command"] },+ ToolWords { tools: &["Read"], verb: "Reading", fields: &["file_path"] },+ ToolWords { tools: &["Write"], verb: "Writing", fields: &["file_path"] },+ ToolWords { tools: &["Edit", "MultiEdit"], verb: "Editing", fields: &["file_path"] },+ ToolWords { tools: &["NotebookEdit"], verb: "Editing", fields: &["notebook_path"] },+ ToolWords { tools: &["Glob"], verb: "Looking for", fields: &["pattern"] },+ ToolWords { tools: &["Grep"], verb: "Searching for", fields: &["pattern"] },+ ToolWords { tools: &["WebFetch"], verb: "Fetching", fields: &["url"] },+ ToolWords { tools: &["WebSearch"], verb: "Searching the web for", fields: &["query"] },+ ToolWords { tools: &["Task", "Agent"], verb: "Handing off", fields: &["description"] },+];++/// The fields any other tool's input usually names its subject in.+const USUAL_FIELDS: &[&str] = &["path", "file_path", "file", "url", "target", "program", "query", "output_directory"];++/// `tool`'s call in parts. `roots` are left out of paths (the project's folders), so a line says+/// what it's working on rather than where the projects are kept.+pub fn describe(tool: &str, input: &Value, roots: &[PathBuf]) -> Action {+ let words = TOOL_WORDS.iter().find(|w| w.tools.contains(&tool));+ let fields = words.map_or(USUAL_FIELDS, |w| w.fields);+ let object = fields.iter().find_map(|f| input.get(*f)?.as_str().filter(|s| !s.trim().is_empty())).map(|s| {+ let mut s = s.lines().next().unwrap_or_default().trim().to_string();+ for root in roots {+ s = s.replace(&format!("{}/", root.display()), "");+ }+ cut(&journal::scrubbed_line(&s), LONGEST_OBJECT)+ });+ Action { tool: tool.to_string(), verb: words.map(|w| w.verb), object }+}++impl Action {+ /// In words, with `title` naming a tool there are no words for.+ pub fn words_with(&self, title: impl Fn(&str) -> Option<String>) -> String {+ let head = self.verb.map(str::to_string).or_else(|| title(&self.tool)).unwrap_or_else(|| self.tool.replace('_', " "));+ match &self.object {+ Some(o) if self.verb.is_some() => format!("{head} {o}"),+ Some(o) => format!("{head}: {o}"),+ None => head,+ }+ }++ pub fn words(&self) -> String {+ self.words_with(|_| None)+ }+}++/// What a run is on now.+#[derive(Debug, Clone, PartialEq, Default)]+pub struct ActivityNow {+ /// The latest action still going, and for how long.+ pub current: Option<(Action, Duration)>,+ /// How many others are going beside it.+ pub others: usize,+ /// The last one that finished.+ pub last: Option<Action>,+}++#[derive(Debug)]+struct Going {+ call_id: String,+ action: Action,+ since: Instant,+}++#[derive(Debug, Default)]+struct State {+ lines: VecDeque<ActivityLine>,+ going: Vec<Going>,+ last: Option<Action>,+ /// What the builder has said since the last full line.+ said: String,+}++/// When a run last had anything to say and what it's on, readable while drawing: its one lock is+/// never held over anything slow.+#[derive(Debug)]+pub struct Activity {+ began: Instant,+ last_ms: AtomicU64,+ roots: Vec<PathBuf>,+ state: Mutex<State>,+}++impl Activity {+ pub(super) fn new(roots: Vec<PathBuf>) -> Activity {+ Activity { began: Instant::now(), last_ms: 0.into(), roots, state: Mutex::default() }+ }++ 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)))+ }++ /// Take in one event. Returns the lines it added, for the log.+ pub(super) fn record(&self, e: &RunEvent) -> Vec<ActivityLine> {+ self.touch();+ let at = self.began.elapsed();+ let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);+ let mut new: Vec<(LineKind, String)> = Vec::new();+ if let RunEvent::Agent(AgentEvent::TextDelta { text }) = e {+ state.said.push_str(text);+ take_full_lines(&mut state.said, &mut new);+ } else if !matches!(e, RunEvent::Agent(AgentEvent::Output { .. })) {+ // Anything else ends what it was saying.+ let rest = std::mem::take(&mut state.said);+ let rest = rest.trim();+ if !rest.is_empty() {+ new.push((LineKind::Said, rest.to_string()));+ }+ }+ self.lines_for(e, &mut state, &mut new);+ let lines: Vec<ActivityLine> =+ new.into_iter().map(|(kind, text)| ActivityLine { at, kind, text: cut(&journal::scrubbed_line(&one_line(&text)), LONGEST_LINE) }).collect();+ for l in &lines {+ if state.lines.len() >= KEPT_LINES {+ state.lines.pop_front();+ }+ state.lines.push_back(l.clone());+ }+ lines+ }++ fn lines_for(&self, e: &RunEvent, state: &mut State, new: &mut Vec<(LineKind, String)>) {+ match e {+ RunEvent::Step { text, .. } => new.push((LineKind::Stage, text.clone())),+ RunEvent::Agent(a) => match a {+ AgentEvent::TextDelta { .. } => {}+ AgentEvent::Status { text } => new.push((LineKind::Note, text.clone())),+ AgentEvent::Output { text } => new.push((LineKind::Output, text.clone())),+ AgentEvent::ToolStarted { tool, .. } if is_checklist(tool) => new.push((LineKind::Note, "Updated its checklist".into())),+ AgentEvent::ToolStarted { call_id, tool, input } => {+ let action = describe(tool, input, &self.roots);+ new.push((LineKind::Started, action.words()));+ state.going.push(Going { call_id: call_id.clone(), action, since: Instant::now() });+ }+ AgentEvent::ToolFinished { tool, .. } if is_checklist(tool) => {}+ AgentEvent::ToolFinished { call_id, tool, ok, summary, .. } => {+ let found = state.going.iter().rposition(|g| g.call_id == *call_id).map(|i| state.going.remove(i));+ let took = found.as_ref().map(|g| g.since.elapsed()).filter(|d| *d >= Duration::from_secs(1));+ let action = found.map_or_else(|| Action { tool: tool.clone(), verb: None, object: None }, |g| g.action);+ let mut line = action.words();+ if let Some(d) = took {+ line.push_str(&format!(" ({} s)", d.as_secs()));+ }+ let summary = summary.trim();+ if !summary.is_empty() {+ line.push_str(&format!(": {summary}"));+ }+ new.push((if *ok { LineKind::Done } else { LineKind::Failed }, line));+ state.last = Some(action);+ }+ AgentEvent::ConsentNeeded { title, .. } => new.push((LineKind::Note, format!("Asking permission: {title}"))),+ // A cost isn't said here: a resumed agent's figure can't be tied to one turn.+ AgentEvent::TurnDone { input_tokens, output_tokens, .. } => {+ state.going.clear();+ new.push((LineKind::Note, format!("The builder's turn ended ({input_tokens} tokens in, {output_tokens} out)")));+ }+ AgentEvent::Error { message, remediation, log } => {+ new.push((LineKind::Problem, message.clone()));+ if let Some(r) = remediation {+ new.push((LineKind::Problem, r.clone()));+ }+ if let Some(l) = log {+ new.push((LineKind::Problem, format!("Details: {}", l.display())));+ }+ }+ },+ RunEvent::Note(shown) => new.push((LineKind::Note, format!("You added: {shown}"))),+ RunEvent::Ask(r) => new.push((LineKind::Note, format!("Waiting for your answer: {}", r.title))),+ RunEvent::Checked(c) => {+ let result = if c.passed { LineKind::Done } else { LineKind::Failed };+ new.push((result, format!("Check {}: {}", c.check, c.note)));+ }+ RunEvent::Preview(url) => new.push((LineKind::Note, format!("Preview at {url}"))),+ RunEvent::Finished { ok, message, paused } => {+ state.going.clear();+ new.push((if *ok || *paused { LineKind::Stage } else { LineKind::Problem }, message.clone()));+ }+ }+ }++ /// Note something about the log itself, for whoever is reading the lines.+ pub(super) fn problem(&self, text: String) {+ let at = self.began.elapsed();+ let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);+ state.lines.push_back(ActivityLine { at, kind: LineKind::Problem, text });+ }++ pub(super) fn now(&self) -> ActivityNow {+ let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);+ ActivityNow {+ current: state.going.last().map(|g| (g.action.clone(), g.since.elapsed())),+ others: state.going.len().saturating_sub(1),+ last: state.last.clone(),+ }+ }++ pub(super) fn len(&self) -> usize {+ self.state.lock().unwrap_or_else(PoisonError::into_inner).lines.len()+ }++ pub(super) fn lines_in(&self, range: Range<usize>) -> Vec<ActivityLine> {+ let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);+ state.lines.iter().skip(range.start).take(range.len()).cloned().collect()+ }+}++fn is_checklist(tool: &str) -> bool {+ tool == "TodoWrite" || tool == "build_checklist"+}++/// Move the full lines out of what the builder has said so far.+fn take_full_lines(said: &mut String, new: &mut Vec<(LineKind, String)>) {+ while let Some(end) = said.find('\n') {+ let rest = said.split_off(end + 1);+ let line = std::mem::replace(said, rest);+ if !line.trim().is_empty() {+ new.push((LineKind::Said, line.trim().to_string()));+ }+ }+}++/// One line of text, however many it came as.+fn one_line(s: &str) -> String {+ s.split_whitespace().collect::<Vec<_>>().join(" ")+}++fn cut(s: &str, most: usize) -> String {+ match s.char_indices().nth(most) {+ Some((end, _)) => format!("{}…", s.get(..end).unwrap_or_default()),+ None => s.to_string(),+ }+}++/// The run's side of `build-activity.log`, appended to as it goes. Readable only by its owner: it+/// names the commands the builder ran.+#[derive(Debug)]+pub(super) struct ActivityFile {+ root: PathBuf,+ file: Option<std::fs::File>,+ written: u64,+ /// A write failed and that was said: the run isn't told again for each line.+ told: bool,+}++impl ActivityFile {+ pub(super) fn new(root: &Path) -> ActivityFile {+ ActivityFile { root: root.to_path_buf(), file: None, written: 0, told: false }+ }++ fn open(&mut self) -> std::io::Result<&mut std::fs::File> {+ let path = self.root.join(ACTIVITY_LOG);+ if self.file.is_none() {+ let mut options = std::fs::OpenOptions::new();+ options.create(true).append(true);+ #[cfg(unix)]+ std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);+ let mut file = options.open(&path)?;+ self.written = file.metadata()?.len();+ let (_, date, time) = journal::now_utc();+ let head = format!("--- Craft Anything {}: a run started {date} {time} UTC ---\n", env!("CARGO_PKG_VERSION"));+ file.write_all(head.as_bytes())?;+ self.file = Some(file);+ }+ self.file.as_mut().ok_or_else(|| std::io::Error::other("the log isn't open"))+ }++ fn write(&mut self, lines: &[ActivityLine]) -> std::io::Result<()> {+ if lines.is_empty() {+ return Ok(());+ }+ if self.written >= LOG_LIMIT {+ self.file = None;+ self.written = 0;+ std::fs::rename(self.root.join(ACTIVITY_LOG), self.root.join(ACTIVITY_LOG_OLD))?;+ }+ let (_, _, time) = journal::now_utc();+ let text: String = lines.iter().map(|l| format!("{time} {:<5} {}\n", l.kind.tag(), l.text)).collect();+ self.open()?.write_all(text.as_bytes())?;+ self.written = self.written.saturating_add(text.len() as u64);+ Ok(())+ }++ /// Write `lines`. A log that can't be written never stops a run; the first failure is said+ /// where the lines are read, and in the app's log.+ pub(super) fn append(&mut self, lines: &[ActivityLine], activity: &Activity) {+ if let Err(e) = self.write(lines)+ && !std::mem::replace(&mut self.told, true)+ {+ log::warn!("couldn't write {ACTIVITY_LOG} in {}: {e}", self.root.display());+ activity.problem(format!("These lines can't be saved to {ACTIVITY_LOG}: {e}"));+ }+ }+}++/// The last lines of a project's log, `skip` lines back from the newest, and how many it holds.+/// Reads at most the last megabytes of it, so a tool never loads a whole long log.+pub(super) fn read_log(root: &Path, skip: usize, limit: usize) -> Result<(Vec<String>, usize), ToolError> {+ use std::io::{Read, Seek, SeekFrom};+ const MOST_READ: u64 = 4 << 20;+ let path = root.join(ACTIVITY_LOG);+ let mut file = match std::fs::File::open(&path) {+ Ok(f) => f,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((Vec::new(), 0)),+ Err(e) => return Err(ToolError::io(path.display(), e)),+ };+ let size = file.metadata().map_err(|e| ToolError::io(path.display(), e))?.len();+ let start = size.saturating_sub(MOST_READ);+ file.seek(SeekFrom::Start(start)).map_err(|e| ToolError::io(path.display(), e))?;+ let mut bytes = Vec::new();+ file.read_to_end(&mut bytes).map_err(|e| ToolError::io(path.display(), e))?;+ let text = String::from_utf8_lossy(&bytes);+ // Reading from the middle of the file starts in the middle of a line.+ let lines: Vec<&str> = text.lines().skip(usize::from(start > 0)).collect();+ let end = lines.len().saturating_sub(skip);+ let from = end.saturating_sub(limit);+ Ok((lines.get(from..end).unwrap_or_default().iter().map(ToString::to_string).collect(), lines.len()))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn started(tool: &str, input: Value) -> RunEvent {+ RunEvent::Agent(AgentEvent::ToolStarted { call_id: format!("id-{tool}"), tool: tool.into(), input })+ }++ fn finished(tool: &str, ok: bool, summary: &str) -> RunEvent {+ RunEvent::Agent(AgentEvent::ToolFinished { call_id: format!("id-{tool}"), tool: tool.into(), ok, summary: summary.into(), evidence_id: None })+ }++ #[test]+ fn an_action_says_what_it_is_working_on() {+ let roots = vec![PathBuf::from("/projects/x/app"), PathBuf::from("/projects/x")];+ assert_eq!(describe("Bash", &json!({"command": "cargo test\nmore"}), &roots).words(), "Running cargo test");+ assert_eq!(describe("Edit", &json!({"file_path": "/projects/x/app/src/main.rs"}), &roots).words(), "Editing src/main.rs");+ assert_eq!(describe("Read", &json!({"file_path": "/projects/x/capture/a.png"}), &roots).words(), "Reading capture/a.png");+ assert_eq!(describe("Grep", &json!({"pattern": "horse"}), &roots).words(), "Searching for horse");+ // Tools without words: the tool's own title, when the caller has one.+ let ours = describe("web_site_open", &json!({"url": "http://x.test/"}), &roots);+ assert_eq!(ours.words(), "web site open: http://x.test/");+ assert_eq!(ours.words_with(|_| Some("Open a website".into())), "Open a website: http://x.test/");+ assert_eq!(describe("Read", &Value::Null, &roots).words(), "Reading");+ assert_eq!(describe("rebuild_check", &Value::Null, &roots).words(), "rebuild check");+ }++ #[test]+ fn it_knows_what_is_going_and_what_finished_last() {+ let a = Activity::new(Vec::new());+ assert_eq!(a.now(), ActivityNow::default());+ a.record(&started("Bash", json!({"command": "npm test"})));+ a.record(&started("Read", json!({"file_path": "a.rs"})));+ let now = a.now();+ assert_eq!(now.current.unwrap().0.words(), "Reading a.rs");+ assert_eq!(now.others, 1);+ a.record(&finished("Read", true, "fn main"));+ a.record(&finished("Bash", false, "1 test failed"));+ let now = a.now();+ assert!(now.current.is_none());+ assert_eq!(now.last.unwrap().words(), "Running npm test");+ let lines = a.lines_in(0..10);+ assert_eq!(lines.iter().map(|l| l.kind).collect::<Vec<_>>(), [LineKind::Started, LineKind::Started, LineKind::Done, LineKind::Failed]);+ assert_eq!(lines[3].text, "Running npm test: 1 test failed");+ }++ #[test]+ fn a_tool_left_going_ends_with_the_turn() {+ let a = Activity::new(Vec::new());+ a.record(&started("Bash", json!({"command": "sleep 99"})));+ a.record(&RunEvent::Agent(AgentEvent::TurnDone {+ backend: "x".into(),+ input_tokens: 1,+ output_tokens: 2,+ cost_usd: Some(9.0),+ cost_is_estimate: true,+ }));+ assert!(a.now().current.is_none());+ assert!(!a.lines_in(0..9).iter().any(|l| l.text.contains('$') || l.text.contains("9.0")), "no cost it can't attribute");+ }++ #[test]+ fn the_builders_words_become_lines_as_they_arrive() {+ let a = Activity::new(Vec::new());+ a.record(&RunEvent::Agent(AgentEvent::TextDelta { text: "Looking at ".into() }));+ assert_eq!(a.len(), 0);+ a.record(&RunEvent::Agent(AgentEvent::TextDelta { text: "it.\nNext ".into() }));+ assert_eq!(a.lines_in(0..9)[0].text, "Looking at it.");+ // Printed output doesn't break up what it's saying.+ a.record(&RunEvent::Agent(AgentEvent::Output { text: "warning: x".into() }));+ assert_eq!(a.len(), 2);+ a.record(&RunEvent::Step { step: Step::Check, text: "Checking".into() });+ let texts: Vec<String> = a.lines_in(0..9).into_iter().map(|l| l.text).collect();+ assert_eq!(texts, ["Looking at it.", "warning: x", "Next", "Checking"]);+ }++ #[test]+ fn the_screen_keeps_the_newest_lines_and_cuts_long_ones() {+ let a = Activity::new(Vec::new());+ for i in 0..KEPT_LINES + 5 {+ a.record(&RunEvent::Agent(AgentEvent::Status { text: format!("line {i}") }));+ }+ assert_eq!(a.len(), KEPT_LINES);+ assert_eq!(a.lines_in(0..1)[0].text, "line 5");+ a.record(&RunEvent::Agent(AgentEvent::Status { text: "é".repeat(LONGEST_LINE * 2) }));+ let last = a.lines_in(KEPT_LINES - 1..KEPT_LINES).remove(0);+ assert_eq!(last.text.chars().count(), LONGEST_LINE + 1);+ }++ #[test]+ fn a_key_in_a_command_never_reaches_the_screen_or_the_log() {+ let d = tempfile::tempdir().unwrap();+ let a = Activity::new(Vec::new());+ let mut file = ActivityFile::new(d.path());+ let key = "sk-ant-abcdefghijklmnop";+ for e in [+ started("Bash", json!({"command": format!("curl -H \"x-api-key: {key}\" https://x.test")})),+ finished("Bash", true, &format!("echoed {key}")),+ RunEvent::Agent(AgentEvent::Output { text: format!("using {key}") }),+ RunEvent::Agent(AgentEvent::TextDelta { text: format!("The key is {key}\n") }),+ ] {+ let lines = a.record(&e);+ file.append(&lines, &a);+ }+ let log = std::fs::read_to_string(d.path().join(ACTIVITY_LOG)).unwrap();+ assert!(log.contains("Running curl"), "{log}");+ assert!(!log.contains(key), "{log}");+ assert!(!a.lines_in(0..9).iter().any(|l| l.text.contains(key)));+ }++ #[test]+ fn the_log_keeps_every_run_and_sets_a_long_one_aside() {+ let d = tempfile::tempdir().unwrap();+ let a = Activity::new(Vec::new());+ let line = |text: &str| ActivityLine { at: Duration::ZERO, kind: LineKind::Note, text: text.into() };+ let mut one = ActivityFile::new(d.path());+ one.append(&[line("first run")], &a);+ drop(one);+ let mut two = ActivityFile::new(d.path());+ two.append(&[line("second run")], &a);+ let (lines, count) = read_log(d.path(), 0, 100).unwrap();+ assert_eq!(count, 4, "{lines:?}");+ assert!(lines[1].ends_with("first run") && lines[3].ends_with("second run"), "{lines:?}");+ assert!(read_log(d.path(), 1, 1).unwrap().0[0].contains("a run started"), "paged from the newest");++ two.written = LOG_LIMIT;+ two.append(&[line("after")], &a);+ assert!(std::fs::read_to_string(d.path().join(ACTIVITY_LOG_OLD)).unwrap().contains("second run"));+ let now = std::fs::read_to_string(d.path().join(ACTIVITY_LOG)).unwrap();+ assert!(now.contains("after") && !now.contains("second run"));+ assert_eq!(read_log(&d.path().join("nowhere"), 0, 10).unwrap().1, 0, "no log yet is no lines");+ }++ #[test]+ fn a_log_that_cannot_be_written_says_so_once_and_the_run_goes_on() {+ let d = tempfile::tempdir().unwrap();+ let a = Activity::new(Vec::new());+ let mut file = ActivityFile::new(&d.path().join("nowhere"));+ let line = ActivityLine { at: Duration::ZERO, kind: LineKind::Note, text: "x".into() };+ file.append(std::slice::from_ref(&line), &a);+ file.append(std::slice::from_ref(&line), &a);+ let problems: Vec<_> = a.lines_in(0..9).into_iter().filter(|l| l.kind == LineKind::Problem).collect();+ assert_eq!(problems.len(), 1, "{problems:?}");+ assert!(problems[0].text.contains(ACTIVITY_LOG));+ }+}diff --git a/crates/ai/src/rebuild/feed.rs b/crates/ai/src/rebuild/feed.rsindex 2b73ae4a..9988c809 100644--- a/crates/ai/src/rebuild/feed.rs+++ b/crates/ai/src/rebuild/feed.rs@@ -3,6 +3,7 @@pub use craft_anything_engine::feed::*;+use super::activity::{Activity, ActivityFile};use super::*;/// Fold one workflow event into the feed.@@ -52,6 +53,8 @@ pub fn apply(feed: &mut Vec<FeedItem>, e: &RunEvent) {Some(FeedItem::Work { notes, .. }) => notes.push(text.clone()),_ => feed.push(FeedItem::Work { tools: Vec::new(), notes: vec![text.clone()] }),},+ // For the activity log; it doesn't interrupt what the builder is saying.+ RunEvent::Agent(AgentEvent::Output { .. }) => {}RunEvent::Agent(AgentEvent::Error { message, remediation, log }) => {end_stream(feed);feed.push(FeedItem::Error { message: message.clone(), remediation: remediation.clone(), log: log.clone() });@@ -103,31 +106,13 @@ pub(super) struct FeedLog {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)))- }+ log: ActivityFile,}impl FeedLog {pub(super) fn open(ws: &Workspace) -> FeedLog {- 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 }+ let activity = Arc::new(Activity::new(vec![ws.app_dir(), ws.root.clone()]));+ FeedLog { root: ws.root.clone(), feed: load(ws), saved_at: None, activity, log: ActivityFile::new(&ws.root) }}pub(super) fn activity(&self) -> Arc<Activity> {@@ -135,7 +120,8 @@ impl FeedLog {}pub(super) fn record(&mut self, e: &RunEvent) {- self.activity.touch();+ let lines = self.activity.record(e);+ self.log.append(&lines, &self.activity);apply(&mut self.feed, e);self.save(matches!(e, RunEvent::Finished { .. }));}@@ -184,10 +170,11 @@ mod tests {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));+ // Well apart: recording saves files, which takes a while on a busy machine.+ std::thread::sleep(Duration::from_millis(1500));+ assert!(activity.quiet_for() >= Duration::from_millis(1500));log.record(&RunEvent::Step { step: Step::Study, text: "Looking".into() });- assert!(activity.quiet_for() < Duration::from_millis(30));+ assert!(activity.quiet_for() < Duration::from_millis(1500));}#[test]diff --git a/crates/ai/src/rebuild/mod.rs b/crates/ai/src/rebuild/mod.rsindex 74cff321..a49ecd7b 100644--- a/crates/ai/src/rebuild/mod.rs+++ b/crates/ai/src/rebuild/mod.rs@@ -36,6 +36,7 @@ use std::sync::mpsc::{Receiver, Sender};use std::sync::{Arc, PoisonError};use std::time::{Duration, Instant};+pub mod activity;mod brief;mod check;pub mod feed;@@ -182,7 +183,7 @@ pub struct RebuildRun {feed: Arc<Mutex<feed::FeedLog>>,pub root: PathBuf,started: Instant,- activity: Arc<feed::Activity>,+ activity: Arc<activity::Activity>,}impl RebuildRun {@@ -356,6 +357,26 @@ impl RebuildRun {self.activity.quiet_for()}+ /// What it's on now. Cheap: safe to read while drawing.+ pub fn activity_now(&self) -> activity::ActivityNow {+ self.activity.now()+ }++ /// How many lines of its activity are at hand for [`RebuildRun::activity_lines`].+ pub fn activity_len(&self) -> usize {+ self.activity.len()+ }++ /// Some of its latest activity. Cheap: safe to read while drawing.+ pub fn activity_lines(&self, range: std::ops::Range<usize>) -> Vec<activity::ActivityLine> {+ self.activity.lines_in(range)+ }++ /// The file with all of it.+ pub fn activity_log(&self) -> PathBuf {+ self.root.join(craft_anything_engine::workspace::ACTIVITY_LOG)+ }+pub fn preview_url(&self) -> Option<String> {self.preview.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map(StaticServer::url)}diff --git a/crates/ai/src/rebuild/tools.rs b/crates/ai/src/rebuild/tools.rsindex 8d5b38e6..04ce87d4 100644--- a/crates/ai/src/rebuild/tools.rs+++ b/crates/ai/src/rebuild/tools.rs@@ -35,6 +35,17 @@ pub fn specs() -> Vec<ToolSpec> {input_schema: schema_of::<ProjectParams>,run: rebuild_status,},+ ToolSpec {+ id: "rebuild_activity_show",+ title: "Show a build's activity",+ summary: "What a project's builds did, line by line, newest last: each stage, every command and file the builder touched and how it ended, what it said, and what programs printed outside the conversation. Secrets are hidden. Works while a build runs and after. `limit` lines (200 by default, at most 2000), `offset` lines back from the newest.",+ beginner: "Shows the details of what a build has been doing.",+ toolset: Toolset::Projects,+ effects: Effects::READ_ONLY.union(Effects::CARRIES_TARGET_CONTENT),+ requires: Requires::Nothing,+ input_schema: schema_of::<ActivityParams>,+ run: rebuild_activity_show,+ },ToolSpec {id: "rebuild_note",title: "Add to a running build",@@ -174,6 +185,19 @@ pub struct ProjectParams {pub project: PathBuf,}+#[derive(Debug, Deserialize, JsonSchema)]+#[serde(deny_unknown_fields)]+pub struct ActivityParams {+ /// The project's folder.+ pub project: PathBuf,+ /// How many lines to return (200 by default, at most 2000).+ #[serde(default)]+ pub limit: Option<usize>,+ /// How many lines back from the newest to end at (0 by default).+ #[serde(default)]+ pub offset: Option<usize>,+}+#[derive(Debug, Deserialize, JsonSchema)]#[serde(deny_unknown_fields)]pub struct NoteParams {@@ -354,6 +378,19 @@ fn rebuild_status(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolEr})))}+fn rebuild_activity_show(_ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {+ let p: ActivityParams = parse_params(params)?;+ let ws = open(&p.project)?;+ let limit = p.limit.unwrap_or(200).min(2000);+ let (lines, total) = super::activity::read_log(&ws.root, p.offset.unwrap_or(0), limit)?;+ Ok(ToolOutput::Value(json!({+ "project": ws.root.display().to_string(),+ "log": ws.root.join(craft_anything_engine::workspace::ACTIVITY_LOG).display().to_string(),+ "lines": lines,+ "total_lines_read": total,+ })))+}+fn rebuild_note(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {let p: NoteParams = parse_params(params)?;let ws = open(&p.project)?;@@ -467,6 +504,12 @@ mod tests {assert!(e.call("rebuild_start", json!({"request": "x", "build_with": "cobol", "projects_dir": d.path()}), ok()).is_err());// Status, notes and stop on a project with nothing running.let ws = Workspace::create(d.path(), "Snake", "A snake game", TargetRef::None).unwrap();+ // A project's activity reads through the tool, none yet being no lines, not an error.+ let shown = e.call("rebuild_activity_show", json!({"project": ws.root}), ok()).unwrap().to_json();+ assert_eq!(shown["result"]["lines"], json!([]), "{shown}");+ std::fs::write(ws.root.join(craft_anything_engine::workspace::ACTIVITY_LOG), "one\ntwo\nthree\n").unwrap();+ let shown = e.call("rebuild_activity_show", json!({"project": ws.root, "limit": 1, "offset": 1}), ok()).unwrap().to_json();+ assert_eq!(shown["result"]["lines"], json!(["two"]), "{shown}");let st = e.call("rebuild_status", json!({"project": ws.root}), ok()).unwrap().to_json();assert_eq!(st["result"]["running"], false);assert_eq!(st["result"]["queued"], Value::Null);diff --git a/crates/engine/src/clean_room.rs b/crates/engine/src/clean_room.rsindex d1f12b60..750109ed 100644--- a/crates/engine/src/clean_room.rs+++ b/crates/engine/src/clean_room.rs@@ -64,6 +64,7 @@ pub const TOOLS: &[&str] = &["project_pin_delete","rebuild_start","rebuild_status",+ "rebuild_activity_show","rebuild_check","rebuild_note","rebuild_note_withdraw",diff --git a/crates/engine/src/journal.rs b/crates/engine/src/journal.rsindex b62fb380..774abf81 100644--- a/crates/engine/src/journal.rs+++ b/crates/engine/src/journal.rs@@ -63,6 +63,98 @@ pub fn redacted(v: &Value) -> Value {}}+/// Names whose value is a secret when they end a `name=value` or `name: value`.+const SECRET_NAMES: &[&str] =+ &["token", "secret", "password", "passwd", "passphrase", "apikey", "api_key", "api-key", "credential", "credentials", "authorization", "private_key"];++fn is_secret_name(name: &str) -> bool {+ let name = name.trim_start_matches('-').trim_matches(|c| c == '"' || c == '\'').to_ascii_lowercase();+ SECRET_NAMES.iter().any(|s| name == *s || name.ends_with(&format!("_{s}")) || name.ends_with(&format!("-{s}")) || name.ends_with(&format!(".{s}")))+}++const HIDDEN: &str = "[hidden]";++/// A word with its secrets hidden: `name=value` pairs with a secret's name, and anything that is+/// a credential by its form, including inside a URL or a quoted string.+fn scrubbed_word(word: &str) -> String {+ let is_break = |c: char| "?&,;\"'()[]{}<>".contains(c);+ let mut out = String::with_capacity(word.len());+ let mut rest = word;+ while !rest.is_empty() {+ let end = rest.find(is_break).unwrap_or(rest.len());+ let (part, after) = rest.split_at(end);+ out.push_str(&scrubbed_part(part));+ let mut chars = after.chars();+ if let Some(c) = chars.next() {+ out.push(c);+ }+ rest = chars.as_str();+ }+ out+}++fn scrubbed_part(part: &str) -> String {+ if let Some(at) = part.find(['=', ':']) {+ let (name, value) = part.split_at(at);+ if value.len() > 1 && is_secret_name(name) {+ return format!("{name}{}{HIDDEN}", value.get(..1).unwrap_or_default());+ }+ }+ // A credential after a separator: `ref=sk-…`, `https://user:ghp_…@host`.+ let mut out = String::with_capacity(part.len());+ let mut token = String::new();+ for c in part.chars() {+ if "=:/@".contains(c) {+ out.push_str(if craft_anything_analysis::standin::looks_secret(&token) { HIDDEN } else { &token });+ token.clear();+ out.push(c);+ } else {+ token.push(c);+ }+ }+ out.push_str(if craft_anything_analysis::standin::looks_secret(&token) { HIDDEN } else { &token });+ out+}++/// One line of text (a command, a program's output) with what looks like a secret hidden, for+/// logs and status lines. Whitespace is kept. Ordinary words survive, "tokens: 12" and+/// "Basic Membership" among them: a key's name hides only the value it names.+pub fn scrubbed_line(line: &str) -> String {+ let mut out = String::with_capacity(line.len());+ let mut hide_next = false;+ let mut rest = line;+ while !rest.is_empty() {+ let word_start = rest.find(|c: char| !c.is_whitespace()).unwrap_or(rest.len());+ out.push_str(rest.get(..word_start).unwrap_or_default());+ rest = rest.get(word_start..).unwrap_or_default();+ if rest.is_empty() {+ break;+ }+ let word_end = rest.find(char::is_whitespace).unwrap_or(rest.len());+ let (word, after) = rest.split_at(word_end);+ rest = after;+ if std::mem::take(&mut hide_next) {+ // "Authorization: Bearer abc": the scheme is a word, and the value comes next.+ if word.trim_matches(|c| c == '"' || c == '\'').eq_ignore_ascii_case("bearer") {+ out.push_str(word);+ hide_next = true;+ continue;+ }+ // Keep what closes the quote around it, so a line stays readable.+ let closing: String = word.chars().rev().take_while(|c| "\"'".contains(*c)).collect();+ out.push_str(HIDDEN);+ out.push_str(&closing);+ continue;+ }+ out.push_str(&scrubbed_word(word));+ let bare = word.trim_matches(|c| c == '"' || c == '\'');+ let names_a_secret = bare.strip_suffix(':').or_else(|| bare.strip_suffix('=')).is_some_and(is_secret_name);+ let secret_flag = bare.starts_with('-') && !bare.contains('=') && is_secret_name(bare);+ hide_next = names_a_secret || secret_flag || bare.eq_ignore_ascii_case("bearer");+ }+ out+}+pub fn journal_dir(project_root: &Path) -> PathBuf {project_root.join("journal")}@@ -121,6 +213,42 @@ pub fn read_day(project_root: &Path, day: &str) -> Vec<Value> {#[cfg(test)]mod tests {+ use super::scrubbed_line as scrub;++ #[test]+ fn a_line_loses_its_secrets_and_keeps_its_words() {+ for (line, gone) in [+ ("curl -H \"Authorization: Bearer abc123def\" https://x.test", "abc123def"),+ ("curl -H \"x-api-key: hunter2hunter2\" https://x.test", "hunter2hunter2"),+ ("GITHUB_TOKEN=abc123 cargo publish", "abc123"),+ ("tool --password hunter2 --verbose", "hunter2"),+ ("tool --api-key=hunter2", "hunter2"),+ ("fetch https://x.test/a?api_key=abc123&page=2", "abc123"),+ ("git clone https://me:[email protected]/x/y", "ghp_abcdefghijklmnop"),+ ("ref=sk-ant-abcdefghijklmnop", "sk-ant-abcdefghijklmnop"),+ ("found sk_live_abcdefgh in the file", "sk_live_abcdefgh"),+ ("Password: hunter2", "hunter2"),+ ] {+ let out = scrub(line);+ assert!(!out.contains(gone), "{line} -> {out}");+ assert!(out.contains("[hidden]"), "{line} -> {out}");+ }+ for line in [+ "cargo test --quiet",+ "Basic Membership",+ "tokens: 12 used",+ "max_tokens=100",+ "npm run build && node dist/a.js",+ "http://127.0.0.1:8080/legs.html?page=2",+ "Reading src/token.rs",+ " indented with spaces",+ "",+ ] {+ assert_eq!(scrub(line), line);+ }+ assert_eq!(scrub("--token abc --next"), "--token [hidden] --next");+ }+#[test]fn secrets_never_reach_the_journal() {let v = json!({"api_key": "sk-123", "nested": {"Token": "t"}, "list": [{"password": "p"}], "key": "auto_mode", "value": 1});diff --git a/crates/engine/src/workspace.rs b/crates/engine/src/workspace.rsindex fd9e3b2c..f3adefea 100644--- a/crates/engine/src/workspace.rs+++ b/crates/engine/src/workspace.rs@@ -10,6 +10,7 @@//! app/ the generated project (its own git repository)//! checks/ comparisons of the build against the target, one folder per round//! inbox/ questions and approvals waiting for the person+//! build-activity.log what the runs did, line by line (with .old.log, the one before it)//! ```//!//! A project can also start in a folder the person picks ([`Workspace::create_at`]). When it@@ -478,6 +479,11 @@ pub struct ProjectUsage {pub priced: bool,}+/// What a project's runs did, line by line; the run is its only writer.+pub const ACTIVITY_LOG: &str = "build-activity.log";+/// The log before it, set aside when it grew long.+pub const ACTIVITY_LOG_OLD: &str = "build-activity.old.log";+/// Where [`ProjectUsage`] is kept in the project folder.pub const USAGE_FILE: &str = "usage.json";pub const USAGE_VERSION: u32 = 1;@@ -878,6 +884,8 @@ pub const OWN_NAMES: &[&str] = &[crate::feed::FEED_FILE,crate::questions::QUESTIONS_FILE,USAGE_FILE,+ ACTIVITY_LOG,+ ACTIVITY_LOG_OLD,ASSETS,"transcript.json","extract-transcript.json",diff --git a/crates/ui-egui/src/chat.rs b/crates/ui-egui/src/chat.rsindex 2303468d..5bfe67b5 100644--- a/crates/ui-egui/src/chat.rs+++ b/crates/ui-egui/src/chat.rs@@ -24,6 +24,8 @@ pub fn apply_event(chat: &mut Vec<ChatItem>, e: AgentEvent) {chat.push(ChatItem::Assistant { text, backend: None, streaming: true });}}+ // For logs, not the conversation.+ AgentEvent::Output { .. } => {}AgentEvent::Status { text } => {if let Some(ChatItem::Status(s)) = chat.last_mut() {*s = text;diff --git a/crates/ui-egui/src/project.rs b/crates/ui-egui/src/project.rsindex d01a05fd..149604b4 100644--- a/crates/ui-egui/src/project.rs+++ b/crates/ui-egui/src/project.rs@@ -9,6 +9,7 @@ use crate::state::{FeedItem, MakeDraft, Modal, PlanStatus, PlanStep, Screen};use crate::theme::{self, Tokens};use crate::{CraftApp, Done, chat, icons, prompt_box, widgets};use craft_anything_ai::AgentEvent;+use craft_anything_ai::rebuild::activity::{Action, ActivityNow, LineKind};use craft_anything_ai::rebuild::feed::{self, apply};use craft_anything_ai::rebuild::{self, AppKind, KindRegistry, KindWords, Note, RebuildRun, RunEvent, RunOptions, Started, Step, Stopped, TargetKind};use craft_anything_engine::inbox::{Answer, Inbox, Request, RequestKind};@@ -947,7 +948,9 @@ fn feed(app: &mut CraftApp, ui: &mut Ui, ws: &Workspace) {let items = &app.state.feed;// With a plan pinned below, it shows the work and the clock; one progress display, not two.let pinned = plan(items).is_some();- if app.running() && !pinned && !matches!(items.last(), Some(FeedItem::Agent { streaming: true, .. }) | Some(FeedItem::Ask { answer: None, .. })) {+ let status_row =+ app.running() && !pinned && !matches!(items.last(), Some(FeedItem::Agent { streaming: true, .. }) | Some(FeedItem::Ask { answer: None, .. }));+ if status_row {// What it's on (the latest step) and how much it has done since, so progress is visible// even in Simple mode where the tool-by-tool work is hidden.let step = items.iter().rposition(|i| matches!(i, FeedItem::Step { .. }));@@ -966,23 +969,18 @@ fn feed(app: &mut CraftApp, ui: &mut Ui, ws: &Workspace) {_ => 0,}).sum();- // 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(" · ");+ // The action under way: the command or file it's on, not only how many went before.+ let now = app.open_run().map(RebuildRun::activity_now);+ let detail =+ [now.as_ref().and_then(|n| now_words(app, n)), (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);}+ run_details(app, ui, status_row);for (id, a, shown) in answers {app.answer_request(&id, a, shown);}@@ -991,6 +989,96 @@ fn feed(app: &mut CraftApp, ui: &mut Ui, ws: &Workspace) {}}+/// How much of a command or a path fits on the status line; the details have the rest.+const NOW_LENGTH: usize = 90;++/// "Now: Running cargo test (42s)", or what finished last between actions.+fn now_words(app: &CraftApp, now: &ActivityNow) -> Option<String> {+ let words = |a: &Action| {+ let registry = app.engine.registry();+ let w = a.words_with(|tool| registry.canonical(tool).and_then(|id| registry.get(id)).map(|s| s.title.to_string()));+ match w.char_indices().nth(NOW_LENGTH) {+ Some((end, _)) => format!("{}…", w.get(..end).unwrap_or_default()),+ None => w,+ }+ };+ match (&now.current, &now.last) {+ (Some((a, took)), _) => {+ let line = trf("Now: {what} ({time})", &[("what", &words(a)), ("time", &crate::usage::duration_words(*took))]);+ Some(if now.others > 0 { trf("{line}, and {n} more", &[("line", &line), ("n", &now.others.to_string())]) } else { line })+ }+ (None, Some(a)) => Some(trf("Last: {what}", &[("what", &words(a))])),+ (None, None) => None,+ }+}++/// The run's activity, folded away until it's wanted: its latest lines as they arrive, and the+/// whole log to open. Inside the feed's scroll area, so it can never push the prompt box away.+/// `status_row`: the row above already says what it's on.+fn run_details(app: &mut CraftApp, ui: &mut Ui, status_row: bool) {+ const LINE: f32 = 18.0;+ const MOST_SHOWN: f32 = 260.0;+ let t = Tokens::get(ui.ctx());+ let running = app.running();+ let Some(run) = app.open_run() else { return };+ let count = run.activity_len();+ if count == 0 {+ return;+ }+ let title = if !running {+ tr("What happened in this build")+ } else if status_row {+ tr("More detail")+ } else {+ now_words(app, &run.activity_now()).unwrap_or_else(|| tr("More detail"))+ };+ let log = run.activity_log();+ let mut open_log = false;+ egui::CollapsingHeader::new(RichText::new(title).color(t.text_dim).size(theme::CAPTION)).id_salt("run_details").icon(widgets::disclosure_icon).show(+ ui,+ |ui| {+ widgets::card(&t).inner_margin(Margin::symmetric(10, 8)).show(ui, |ui| {+ ui.set_width(ui.available_width());+ // The rows are exactly this tall, or the scroll area miscounts them.+ ui.spacing_mut().item_spacing.y = 0.0;+ ui.spacing_mut().interact_size.y = LINE;+ egui::ScrollArea::vertical().id_salt("run_details_lines").max_height(MOST_SHOWN).auto_shrink([false, true]).stick_to_bottom(true).show_rows(+ ui,+ LINE,+ count,+ |ui, range| {+ for line in run.activity_lines(range) {+ let (colour, words) = match line.kind {+ LineKind::Failed | LineKind::Problem => (t.warning, t.text),+ LineKind::Done => (t.success, t.text_dim),+ LineKind::Stage => (t.accent_ink, t.text),+ LineKind::Started | LineKind::Said => (t.text_dim, t.text),+ LineKind::Note | LineKind::Output => (t.text_faint, t.text_dim),+ };+ ui.horizontal(|ui| {+ ui.set_height(LINE);+ ui.label(RichText::new(crate::usage::duration_words(line.at)).font(theme::mono(11.5)).color(t.text_faint));+ ui.label(RichText::new(line.kind.tag()).font(theme::mono(11.5)).color(colour));+ ui.add(egui::Label::new(RichText::new(&line.text).font(theme::mono(11.5)).color(words)).truncate()).on_hover_text(&line.text);+ });+ }+ },+ );+ });+ ui.horizontal(|ui| {+ ui.label(RichText::new(tr("A command's output shows here when it finishes.")).color(t.text_faint).size(theme::CAPTION));+ open_log = widgets::open_log_button(ui, &log);+ });+ },+ );+ if running {+ ui.ctx().request_repaint_after(std::time::Duration::from_secs(1));+ }+ if open_log {+ app.open_log(&log);+ }+}+/// Each item of the feed, in order. Answers and "Try again" are collected, to act on afterwards.fn draw_items(app: &mut CraftApp,diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rsindex 3dd28cde..7fc1b6b6 100644--- a/crates/ui-egui/tests/smoke.rs+++ b/crates/ui-egui/tests/smoke.rs@@ -1377,6 +1377,64 @@ fn the_front_door_makes_something_or_just_looks_inside() {h.get_by_label("What do you want to recreate?");}+#[test]+fn a_running_build_says_what_it_is_on_and_opens_up_into_its_activity() {+ use craft_anything_ai::rebuild::{RunEvent, RunSet, StandIns};+ use craft_anything_ai::{AgentEvent, AiConfig, BackendConfig, BackendEntry, BackendKind, BackendOptions};+ use craft_anything_engine::workspace::{Step, TargetRef, Workspace};+ let d = tempfile::tempdir().unwrap();+ let ws = Workspace::create(d.path(), "Alpha", "A notes app", TargetRef::None).unwrap();+ let runs = StandIns::new();+ let (dir, starter) = (d.path().to_path_buf(), runs.starter());+ let mut h = harness(move || {+ let engine = demo::engine(Mode::Beginner, true);+ let mut cfg = AiConfig::default();+ let agent = BackendConfig {+ name: "Claude Code".into(),+ kind: BackendKind::AgentCli,+ model: "claude-code".into(),+ base_url: None,+ ssh_host: None,+ enabled: true,+ };+ cfg.upsert(BackendEntry { config: agent, options: BackendOptions::default() });+ engine.session().settings.ai = cfg.to_table().unwrap();+ let mut app = demo::app(engine);+ app.settings.projects_dir = Some(dir);+ app.runs = RunSet::new(1).with_starter(starter);+ app+ });+ h.run_steps(2);+ h.state_mut().open_workspace(ws.clone());+ h.state_mut().continue_build();+ h.run_steps(2);+ let tool = |id: &str, name: &str, input: serde_json::Value| RunEvent::Agent(AgentEvent::ToolStarted { call_id: id.into(), tool: name.into(), input });+ assert!(runs.send(&ws.root, RunEvent::Step { step: Step::Build, text: "Building the first version…".into() }));+ assert!(runs.send(&ws.root, tool("a", "Read", serde_json::json!({"file_path": "src/main.rs"}))));+ assert!(runs.send(+ &ws.root,+ RunEvent::Agent(AgentEvent::ToolFinished { call_id: "a".into(), tool: "Read".into(), ok: true, summary: "fn main".into(), evidence_id: None })+ ));+ h.run_steps(2);+ // Between actions it says what it did last.+ assert!(h.query_all_by_label_contains("Last: Reading src/main.rs").count() >= 1);+ assert!(runs.send(&ws.root, tool("b", "Bash", serde_json::json!({"command": "cargo test --quiet"}))));+ h.run_steps(2);+ assert!(h.query_all_by_label_contains("Now: Running cargo test --quiet").count() >= 1);+ // Folded until it's wanted, then the lines and the log.+ assert!(h.query_by_label("Open log").is_none());+ h.get_by_label("More detail").click();+ h.run_steps(3);+ h.get_by_label("Open log");+ h.get_by_label("Reading src/main.rs: fn main");+ h.get_by_label("Running cargo test --quiet");+ assert!(ws.root.join(craft_anything_engine::workspace::ACTIVITY_LOG).is_file());+ // Finished: the record stays, named for what it is now.+ assert!(runs.finish(&ws.root));+ h.run_steps(3);+ h.get_by_label("What happened in this build");+}+#[test]fn a_build_that_stopped_part_way_offers_to_continue() {use craft_anything_ai::rebuild::{RunSet, StandIns};diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex f43127dd..415642ff 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -779,6 +779,14 @@ Gaps found while using the app for real projects.so the project page says "AI cost (estimate)" with a note that it isn't the bill, and thetitle bar says "(estimate)"; what an API key was charged is kept apart (`api_billed_usd`in usage.json; older files count as estimates)+- [x] A running build says what it's on ("Now: Running cargo test (42s)", the last action between+ them), and "More detail" opens its activity as it arrives: stages, every command and file+ with how it ended, what the builder said and what programs printed outside the+ conversation, with secrets hidden. Kept in `build-activity.log` ("Open log",+ `rebuild_activity_show`, and every tool the CLI's `rebuild` prints)+- [ ] Show a command's output while it runs: Claude Code reports a tool's result only when it+ ends, so a long `cargo build` is one quiet line until then. Watching the agent's child+ processes from outside could say what's running and for how long- [ ] Sometimes starting the app shows nothing: find why from `desktop.log` (a GOG Galaxy Vulkanoverlay layer loads into the app; try DX12 first on Windows if that's it)- [x] Try again picks up where a run stopped instead of starting over: a project whose builderdiff --git a/docs/STATUS.md b/docs/STATUS.mdindex 22108f71..4905564b 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -22,7 +22,7 @@ secret scan of all history clean).| Agents over ACP | Opt-in per backend (`acp = true`): Gemini CLI, Qwen Code, opencode and goose in their ACP mode, one agent process per chat or build with our MCP server. In chat, permission requests become consent questions; in builds they go through the same approval policy as Claude Code's (inbox, Auto mode) | Protocol unit tests against scripted agent messages and an approval-policy test; not yet run against a real agent || WASM plugins | With `--features wasm-plugins`: `[[plugins.wasm]]` components exporting `craft-anything:plugin/tools` add tools, and ones exporting `craft-anything:plugin/checks` add checks run after each kind's own (they get the build's file list as JSON) (added, listed, turned on or off and removed in Settings → Plugins or with `plugins_add`/`plugins_remove`/`plugins_list`); no imports, fresh instance per call, fuel and memory limits | Tests with components written in WAT (describe, call, checks, a looping call stopped, imports refused, end to end through the engine); `examples/wasm-plugin-wordcount` built from Rust and loaded || Questions and approvals | A file inbox per project; `core_person_ask`, `core_action_approve` and MCP consent requests become cards in the app | Cross-handle round-trip tests, a full approval round trip through the engine |-| Desktop app | Simple mode: sidebar with New project and the project history (kept across restarts); New project either makes something or just looks inside an app or file, a website or a game's files; a Game files screen (a game's archives; pictures from Unreal paks, Unity .assets files and Unity bundles saved as PNG after the person confirms they may unpack the game; uncompressed textures and the block formats DXT1, DXT5 and BC4–BC7), make prompt with picture attachments and, for anything recreated, a Clean room / Deep choice (also in the title bar; in Clean room, Just look inside, Game files, opening a file and the workbench ask for Deep mode instead), project screen (steps with the time spent and the AI cost and tokens of every build, saved in the project's usage.json by the run (a coding agent's figure is shown as an estimate at API prices, not the bill), pinned builder checklist, feed, question and approval cards, a Continue card when a build was paused or stopped part-way (the app or computer closed; the project shows Interrupted) that carries on the builder's own session instead of starting over, checks with screenshots and the requirements not met yet, the builder's open questions, preview, play, folder, follow-ups while it builds, which Claude Code takes at its next step; Up in the prompt box takes back the last note still waiting). Projects can start in a folder the person picks, whose files are either the app, edited in place, or material to start from (asked, or the answer remembered in Settings), and are listed from any number of folders (`project_folders`, `project_list`, `rebuild --project-folder`). Make says which AI builds ("Built by": automatic, or any AI that can build, by name); a pick stays with the project and builds its later changes. With nothing to build with, Start offers the coding agents found on the computer. Settings → AI turns an AI off or removes it. In the prompt box, Up at the very start and Down at the very end go through earlier prompts when no note is waiting. Questions about a build ("Just ask" under the prompt box, or a message starting with `/btw`, the first slash command; `rebuild_question_ask`) are answered in the conversation, where each folds away and is kept in the project, without a build or a round and changing nothing: Claude Code answers from a read-only copy of the builder's own session. Under each project's prompt box, "Builder's questions: Ask me / Decide yourself" chooses whether the builder's questions come to the person as cards or are decided by the builder, which says what it chose (`project_questions_set`; the default is in Settings and follows Auto mode until picked). Projects can be renamed, duplicated and deleted (right-click in the sidebar, or the project's page; a delete keeps the person's own files). A build can be pinned (Pin this build on its page, or `project_pin_*` from the CLI and MCP): a frozen copy in the project's pinned/ folder (the default) or a light one that shares dependencies and media with the project through hard links (each one's size shown first), opened from the sidebar's collapsible Pinned section (icons with a running dot when folded); a pin or Play runs once per folder unless another copy is asked for, and a start that quits at once says so with its last output. Typed drafts survive a restart. In a narrow window the sidebar folds to icons and the project's details move above its feed; messages float over the screen and errors stay until dismissed. Advanced mode: workbench with every panel wired to real tools, as a screen beside the projects (builds and their questions stay a click away) | UI unit and smoke tests (egui_kittest), offscreen snapshots of every screen |+| Desktop app | Simple mode: sidebar with New project and the project history (kept across restarts); New project either makes something or just looks inside an app or file, a website or a game's files; a Game files screen (a game's archives; pictures from Unreal paks, Unity .assets files and Unity bundles saved as PNG after the person confirms they may unpack the game; uncompressed textures and the block formats DXT1, DXT5 and BC4–BC7), make prompt with picture attachments and, for anything recreated, a Clean room / Deep choice (also in the title bar; in Clean room, Just look inside, Game files, opening a file and the workbench ask for Deep mode instead), project screen (steps with the time spent and the AI cost and tokens of every build, saved in the project's usage.json by the run (a coding agent's figure is shown as an estimate at API prices, not the bill), what the build is on now and its activity as it arrives (kept in `build-activity.log`), pinned builder checklist, feed, question and approval cards, a Continue card when a build was paused or stopped part-way (the app or computer closed; the project shows Interrupted) that carries on the builder's own session instead of starting over, checks with screenshots and the requirements not met yet, the builder's open questions, preview, play, folder, follow-ups while it builds, which Claude Code takes at its next step; Up in the prompt box takes back the last note still waiting). Projects can start in a folder the person picks, whose files are either the app, edited in place, or material to start from (asked, or the answer remembered in Settings), and are listed from any number of folders (`project_folders`, `project_list`, `rebuild --project-folder`). Make says which AI builds ("Built by": automatic, or any AI that can build, by name); a pick stays with the project and builds its later changes. With nothing to build with, Start offers the coding agents found on the computer. Settings → AI turns an AI off or removes it. In the prompt box, Up at the very start and Down at the very end go through earlier prompts when no note is waiting. Questions about a build ("Just ask" under the prompt box, or a message starting with `/btw`, the first slash command; `rebuild_question_ask`) are answered in the conversation, where each folds away and is kept in the project, without a build or a round and changing nothing: Claude Code answers from a read-only copy of the builder's own session. Under each project's prompt box, "Builder's questions: Ask me / Decide yourself" chooses whether the builder's questions come to the person as cards or are decided by the builder, which says what it chose (`project_questions_set`; the default is in Settings and follows Auto mode until picked). Projects can be renamed, duplicated and deleted (right-click in the sidebar, or the project's page; a delete keeps the person's own files). A build can be pinned (Pin this build on its page, or `project_pin_*` from the CLI and MCP): a frozen copy in the project's pinned/ folder (the default) or a light one that shares dependencies and media with the project through hard links (each one's size shown first), opened from the sidebar's collapsible Pinned section (icons with a running dot when folded); a pin or Play runs once per folder unless another copy is asked for, and a start that quits at once says so with its last output. Typed drafts survive a restart. In a narrow window the sidebar folds to icons and the project's details move above its feed; messages float over the screen and errors stay until dismissed. Advanced mode: workbench with every panel wired to real tools, as a screen beside the projects (builds and their questions stay a click away) | UI unit and smoke tests (egui_kittest), offscreen snapshots of every screen || CLI | Every tool, `--deep` or `--clean-room` for one run (never saved), `rebuild` (including `--continue-in`, and `--resume` to carry on a stopped build), `mcp --inbox`, `ai`, `setup`, `doctor`, `report` | CLI integration tests |### Fixed during the audit