Tell a running build what was asked in Just ask (R2.9)

This commit is contained in:
AlexJoaquimPereira
2026-11-07 15:02:18 +05:30
parent 4f3f2a69c4
commit 78d3963635
9 changed files with 187 additions and 21 deletions
@@ -144,6 +144,7 @@ fn run(cli: &Cli, a: &RebuildArgs) -> Result<bool, ToolError> {
max_rounds: a.rounds,
good_enough,
beginner: !cli.json,
clean_room: Some(engine.session().clean_room()),
..RunOptions::default()
};
let mut run = RebuildRun::start(&hub, ws, opts)?;
+82 -9
View File
@@ -21,6 +21,7 @@ use crate::cli_agents::{Builder, CliSpec};
use crate::{AgentEvent, AiHub, BackendKind, Conversation, Role};
use craft_anything_engine::inbox::{Answer, Inbox, InboxDir, Request};
use craft_anything_engine::project::{Project, Purpose};
use craft_anything_engine::questions::AskedQuestion;
use craft_anything_engine::workspace::progress::{AppFingerprintCache, BuildProgress};
use craft_anything_engine::workspace::{CheckResult, ProjectUsage, Status, TargetRef, Workspace};
use craft_anything_engine::{CallOptions, Caller, CancelToken, Engine, ToolOutput};
@@ -145,6 +146,10 @@ pub struct RunOptions {
pub adapters: crate::cli_agents::AgentAdapters,
/// Told after each event (the app repaints).
pub wake: Wake,
/// The run's mode when the caller knows it and the session may be busy (a tool starts a run).
/// A free session is read first; this is the fallback while it is held; the saved settings
/// are the last fallback.
pub clean_room: Option<bool>,
}
impl Default for RunOptions {
@@ -161,6 +166,7 @@ impl Default for RunOptions {
kinds: KindRegistry::built_in(),
adapters: Default::default(),
wake: Wake::default(),
clean_room: None,
}
}
}
@@ -176,6 +182,25 @@ pub struct Note {
pub shown: String,
/// The pictures attached to it (their copies in the project), for the feed's history.
pub pictures: Vec<PathBuf>,
/// The Just-ask answers the note's hand-over file carries (see [`RebuildRun::add_note`]), so
/// they're marked told when the builder reads the note or when the after-turn path sends it.
/// The raw note text stays in [`text`](Self::text), so a later run filters them by its mode.
pub questions: Vec<AskedQuestion>,
}
/// The note text with the latest Just-ask answers this mode may show. `skip` holds answers an
/// earlier waiting note already carries, so two notes don't repeat the same ones.
fn note_with_just_asked(text: String, ws: &Workspace, clean_room: bool, skip: &[AskedQuestion]) -> (String, Vec<AskedQuestion>) {
let asked: Vec<AskedQuestion> =
craft_anything_engine::questions::untold(ws, !clean_room).into_iter().filter(|q| !skip.iter().any(|s| same_question(s, q))).collect();
if asked.is_empty() {
return (text, asked);
}
(format!("{}{text}", just_asked(&asked)), asked)
}
fn same_question(a: &AskedQuestion, b: &AskedQuestion) -> bool {
a.at_ms == b.at_ms && a.question == b.question
}
/// A running (or finished) rebuild.
@@ -187,6 +212,8 @@ pub struct RebuildRun {
preview: Arc<Mutex<Option<StaticServer>>>,
/// What the person added while it works; the agent reads them at its next step.
notes: Arc<Mutex<Vec<Note>>>,
/// The mode this run started in, so a note carries only the Just-ask answers that mode may see.
clean_room: bool,
/// The project's conversation, kept in its folder.
feed: Arc<Mutex<feed::FeedLog>>,
pub root: PathBuf,
@@ -199,6 +226,15 @@ impl RebuildRun {
pub fn start(hub: &AiHub, ws: Workspace, opts: RunOptions) -> Result<RebuildRun, ToolError> {
let cfg = hub.config();
let entry = builder_backend(&cfg, opts.backend.as_deref().or_else(|| project_builder(&cfg, &ws)))?;
// The person's choice of mode is a session setting. A run that waited its turn uses the mode
// now, not the one when it was queued; a tool holds the session while it starts a run, so it
// passes the mode instead, and the saved settings are the last fallback.
let clean_room = hub
.engine
.try_session()
.map(|s| s.clean_room())
.or(opts.clean_room)
.unwrap_or_else(|| !craft_anything_engine::Settings::load_from(&hub.settings_path()).deep_mode);
// An API backend builds with our own agent loop and the Build tools; its conversation is
// kept in the project and continued by follow-ups (a fresh build starts a new one).
let api = match entry.config.kind {
@@ -288,20 +324,39 @@ impl RebuildRun {
})
.map_err(|e| ToolError::internal(e.to_string()))?;
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 })
Ok(RebuildRun { rx, stop, inbox, running, preview, notes, clean_room, feed, root, started: Instant::now(), activity })
}
/// Add something while it works; the agent reads it at its next step, and only then does it
/// join the feed (as `shown`, with `pictures`). Returns its id, to take it back with `unsend`
/// until then.
///
/// The hand-over file also carries the latest Just-ask answers this mode may show, so a
/// hand-over that bypasses the next message (Claude Code's tool hook) still has the context.
/// The in-memory text stays raw, and the answers are marked told only when the note is read or
/// sent.
pub fn add_note(&self, text: String, shown: String, pictures: Vec<PathBuf>) -> u64 {
static NEXT: AtomicU64 = AtomicU64::new(1);
let id = NEXT.fetch_add(1, Ordering::Relaxed);
let mut file_text = text.clone();
let mut questions = Vec::new();
if !text.trim().is_empty() {
// A note already waiting carries what it carries; this one adds only what's new.
let waiting: Vec<AskedQuestion> = {
let notes = self.notes.lock().unwrap_or_else(PoisonError::into_inner);
notes.iter().flat_map(|n| n.questions.iter().cloned()).collect()
};
if let Ok(ws) = Workspace::open(&self.root) {
(file_text, questions) = note_with_just_asked(file_text, &ws, self.clean_room, &waiting);
}
}
// Also left for an agent that takes notes at its next step; without it, after the turn.
if let Err(e) = notes::hand_over(&notes::notes_dir(self.inbox.dir()), id, &text) {
// The in-memory note keeps the raw text: if a later run takes it, that run filters the
// answers by its own mode instead of inheriting this run's.
if let Err(e) = notes::hand_over(&notes::notes_dir(self.inbox.dir()), id, &file_text) {
log::warn!("A note waits for the builder's turn to end: {}", e.message);
}
self.notes.lock().unwrap_or_else(PoisonError::into_inner).push(Note { id, text, shown, pictures });
self.notes.lock().unwrap_or_else(PoisonError::into_inner).push(Note { id, text, shown, pictures, questions });
id
}
@@ -327,7 +382,8 @@ impl RebuildRun {
self.notes.lock().unwrap_or_else(PoisonError::into_inner).len()
}
/// Notes the agent never got to (the run ended first), to send as the next message.
/// Notes the agent never got to (the run ended first), to send as the next message. Their
/// raw text leaves the Just-ask answers to the next run's own mode and message.
pub fn take_notes(&self) -> Vec<Note> {
std::mem::take(&mut *self.notes.lock().unwrap_or_else(PoisonError::into_inner))
}
@@ -525,8 +581,9 @@ impl Worker {
Ok(())
}
/// The prompt for notes the person added while the agent worked, if there are any.
fn added(&self, ws: &mut Workspace) -> Option<String> {
/// The prompt for notes the person added while the agent worked, if there are any, and the
/// Just-ask answers it carries so they're marked told once the turn finishes.
fn added(&self, ws: &mut Workspace, deep: bool) -> Option<(String, Vec<AskedQuestion>)> {
let mut notes = std::mem::take(&mut *self.notes.lock().unwrap_or_else(PoisonError::into_inner));
if notes.is_empty() {
return None;
@@ -545,8 +602,16 @@ impl Worker {
}
// A cancelled step can't be reported, but the notes go in either way.
let _ = self.step(ws, Step::Build, Status::Building, "Reading what you added…");
let attached: Vec<AskedQuestion> = notes.iter().flat_map(|n| n.questions.iter().cloned()).collect();
// A note taken before the person asked something carries no answer for it; put the
// remaining ones before the notes so the builder has both in this turn.
let extra: Vec<AskedQuestion> =
craft_anything_engine::questions::untold(ws, deep).into_iter().filter(|q| !attached.iter().any(|a| same_question(a, q))).collect();
let mut questions = attached;
questions.extend(extra);
let context = just_asked(&questions);
let texts: Vec<String> = notes.into_iter().map(|n| n.text).collect();
Some(added_prompt(&texts) + &pictures_reminder(ws))
Some((context + &added_prompt(&texts) + &pictures_reminder(ws), questions))
}
/// Decides an ACP builder's permission requests with the same policy Claude Code's approval
@@ -816,7 +881,8 @@ impl Worker {
progress.save(&ws.root)?;
}
// What the person added while the agent worked goes in before anything else.
if let Some(p) = self.added(ws) {
if let Some((p, more)) = self.added(ws, deep) {
asked.extend(more);
progress.reset();
progress.save(&ws.root)?;
ws.manifest.not_working_checks = 0;
@@ -842,7 +908,8 @@ impl Worker {
for c in &checks {
self.emit(RunEvent::Checked(c.clone()));
}
if let Some(p) = self.added(ws) {
if let Some((p, more)) = self.added(ws, deep) {
asked.extend(more);
progress.reset();
progress.save(&ws.root)?;
ws.manifest.not_working_checks = 0;
@@ -1178,6 +1245,12 @@ impl Worker {
};
let new_request = read.iter().any(|n| !n.text.trim().is_empty());
for n in read {
// The agent's hook took the note, so the Just-ask answers in its text were told.
if !n.questions.is_empty()
&& let Err(e) = craft_anything_engine::questions::mark_told(ws, &n.questions)
{
log::warn!("couldn't record which questions the builder was told: {}", e.message);
}
notes::forget(&dir, n.id);
self.emit(RunEvent::Note { shown: n.shown, pictures: n.pictures });
}
+2 -2
View File
@@ -3,7 +3,7 @@ use craft_anything_engine::workspace::progress::BUILD_PROGRESS_FILE;
fn consumed_notes(notes: &Mutex<Vec<Note>>, dir: &Path) {
for (id, text) in [(71, "Keep the header blue"), (72, "Use larger text")] {
notes.lock().unwrap().push(Note { id, text: text.into(), shown: text.into(), pictures: Vec::new() });
notes.lock().unwrap().push(Note { id, text: text.into(), shown: text.into(), pictures: Vec::new(), questions: Vec::new() });
notes::hand_over(dir, id, text).unwrap();
}
assert_eq!(notes::claim(dir).len(), 2);
@@ -165,7 +165,7 @@ fn consumed_note_resets_survive_failed_and_cancelled_turns() {
impl ChatModel for InterruptedNote {
fn turn(&mut self, _: &TurnRequest<'_>, _: &mut dyn FnMut(Delta), _: &Stop) -> Result<TurnResult, ToolError> {
self.calls.fetch_add(1, Ordering::SeqCst);
self.notes.lock().unwrap().push(Note { id: 73, text: self.text.into(), shown: self.text.into(), pictures: Vec::new() });
self.notes.lock().unwrap().push(Note { id: 73, text: self.text.into(), shown: self.text.into(), pictures: Vec::new(), questions: Vec::new() });
notes::hand_over(&self.notes_dir, 73, self.text).unwrap();
assert_eq!(notes::claim(&self.notes_dir), [self.text]);
if !self.record.is_empty() {
+2
View File
@@ -42,6 +42,7 @@ impl StandIns {
}
let (tx, rx) = std::sync::mpsc::channel();
let running = Arc::new(AtomicBool::new(true));
let clean_room = opts.clean_room.unwrap_or(false);
let feed = Arc::new(Mutex::new(feed::FeedLog::open(&ws)));
if let Some(shown) = opts.shown {
feed.lock().unwrap_or_else(PoisonError::into_inner).push(feed::FeedItem::User(feed::UserItem::new(shown, opts.shown_pictures)));
@@ -62,6 +63,7 @@ impl StandIns {
running,
preview: Arc::default(),
notes: Arc::default(),
clean_room,
feed,
root: ws.root.clone(),
started: std::time::Instant::now(),
+89 -9
View File
@@ -414,11 +414,17 @@ fn notes_added_while_it_works_reach_the_agent_at_its_next_step() {
self_check: None,
reset_progress_after_notes: false,
};
assert!(w.added(&mut ws).is_none(), "nothing added, nothing to say");
let note = |id, text: &str| Note { id, text: format!("{text} (pictures: a.png)"), shown: text.into(), pictures: Vec::new() };
notes.lock().unwrap().extend([note(1, "Make it faster"), note(2, "A blue sky")]);
let p = w.added(&mut ws).unwrap();
assert!(p.contains("- Make it faster (pictures: a.png)\n- A blue sky"), "{p}");
assert!(w.added(&mut ws, true).is_none(), "nothing added, nothing to say");
use craft_anything_engine::questions::{self, AskedQuestion};
let asked = AskedQuestion { deep: false, ..AskedQuestion::new("where is the score kept".into(), "In src.".into(), true, "Stand-in".into(), None, 0) };
questions::add(&ws, asked.clone()).unwrap();
let note = |id, text: &str| Note { id, text: format!("{text} (pictures: a.png)"), shown: text.into(), pictures: Vec::new(), questions: Vec::new() };
let mut first = note(1, "Make it faster");
first.questions = vec![asked];
notes.lock().unwrap().extend([first, note(2, "A blue sky")]);
let (p, more) = w.added(&mut ws, true).unwrap();
assert!(p.contains("where is the score kept") && p.contains("- Make it faster (pictures: a.png)\n- A blue sky"), "{p}");
assert_eq!(more.len(), 1, "the question is marked told after the turn");
assert!(notes.lock().unwrap().is_empty(), "each note goes in once");
// The notes join the feed as they're read, before the step that reads them.
let events: Vec<RunEvent> = rx.try_iter().collect();
@@ -427,6 +433,76 @@ fn notes_added_while_it_works_reach_the_agent_at_its_next_step() {
assert!(matches!(events.last(), Some(RunEvent::Step { text, .. }) if text == "Reading what you added…"));
}
/// #857: a note handed over by a coding agent's tool hook never sees the after-turn message, so
/// the Just-ask answers are put in the note itself (only the ones this mode may show).
#[test]
fn a_note_carries_the_just_ask_answers_once_and_only_in_their_mode() {
use craft_anything_engine::questions::{self, AskedQuestion};
let d = tempfile::tempdir().unwrap();
let ws = Workspace::create(d.path(), "x", "A thing", TargetRef::None).unwrap();
let clean =
AskedQuestion { deep: false, ..AskedQuestion::new("where is the score kept".into(), "In src/score.rs.".into(), true, "Stand-in".into(), None, 0) };
questions::add(&ws, clean.clone()).unwrap();
let (text, carried) = note_with_just_asked("make it blue".into(), &ws, false, &[]);
assert!(text.contains("where is the score kept") && text.contains("make it blue"), "{text}");
assert_eq!(carried.len(), 1);
// A note already waiting carries it; the next one doesn't repeat it.
let (again, none) = note_with_just_asked("make it green".into(), &ws, false, &carried);
assert!(!again.contains("where is the score kept") && none.is_empty(), "{again}");
// A Deep question stays out of a Clean room note.
questions::add(
&ws,
AskedQuestion { deep: true, ..AskedQuestion::new("what does the original do".into(), "It reads a file.".into(), true, "Stand-in".into(), None, 0) },
)
.unwrap();
let (clean_note, carried) = note_with_just_asked("make it blue".into(), &ws, true, &[]);
assert!(clean_note.contains("where is the score kept") && !clean_note.contains("what does the original do"), "{clean_note}");
assert_eq!(carried.len(), 1, "only the Clean room question");
}
/// The app writes the enriched note for both hand-over paths, so the hook prints the answers.
#[test]
fn a_note_written_for_the_hook_carries_its_answers() {
use craft_anything_engine::questions::{self, AskedQuestion};
let d = tempfile::tempdir().unwrap();
let ws = Workspace::create(d.path(), "x", "A thing", TargetRef::None).unwrap();
let asked =
AskedQuestion { deep: false, ..AskedQuestion::new("where is the score kept".into(), "In src/score.rs.".into(), true, "Stand-in".into(), None, 0) };
questions::add(&ws, asked.clone()).unwrap();
let (_tx, rx) = std::sync::mpsc::channel();
let feed = Arc::new(Mutex::new(feed::FeedLog::open(&ws)));
let activity = feed.lock().unwrap_or_else(PoisonError::into_inner).activity();
let run = RebuildRun {
rx,
stop: CancelToken::default(),
inbox: Inbox::new(ws.inbox_dir()),
running: Arc::new(AtomicBool::new(true)),
preview: Arc::default(),
notes: Arc::default(),
clean_room: false,
feed,
root: ws.root.clone(),
started: Instant::now(),
activity,
};
let id = run.add_note("make it blue".into(), "make it blue".into(), Vec::new());
let note = run.waiting().pop().unwrap();
assert_eq!(note.text, "make it blue", "the in-memory text stays raw for a later run's mode");
assert_eq!(note.questions.len(), 1);
let dir = notes::notes_dir(&ws.inbox_dir());
let claimed = notes::claim(&dir);
assert_eq!(claimed.len(), 1);
assert!(claimed[0].contains("where is the score kept"), "{}", claimed[0]);
assert!(notes::was_read(&dir, id));
// The run ended before relaying it: its raw text goes next, and the next run's mode decides
// whether the answers are included, so they stay untold here.
assert_eq!(run.take_notes().len(), 1);
assert_eq!(questions::untold(&ws, false).len(), 1, "the next run decides whether to tell it");
}
#[test]
fn pictures_of_the_original_reach_the_builder() {
let d = tempfile::tempdir().unwrap();
@@ -1872,7 +1948,7 @@ mod picking_up_a_build {
use crate::model::{Block, ChatModel, Delta, Stop, StopReason, TurnRequest, TurnResult};
type Notes = Arc<Mutex<Vec<Note>>>;
fn note(text: &str) -> Note {
Note { id: 42, text: text.into(), shown: text.into(), pictures: Vec::new() }
Note { id: 42, text: text.into(), shown: text.into(), pictures: Vec::new(), questions: Vec::new() }
}
struct NoteModel {
script: Scripted,
@@ -2848,8 +2924,11 @@ fn a_console_original_is_rebuilt_as_a_console_program() {
#[test]
fn a_note_the_builder_took_at_a_step_joins_the_feed_and_isnt_sent_again() {
use craft_anything_engine::questions::{self, AskedQuestion};
let d = tempfile::tempdir().unwrap();
let mut ws = Workspace::create(d.path(), "Site", "Clone it", TargetRef::None).unwrap();
let asked = AskedQuestion { deep: false, ..AskedQuestion::new("where is the score kept".into(), "In src.".into(), true, "Stand-in".into(), None, 0) };
questions::add(&ws, asked.clone()).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
let mut w = Worker {
wake: Default::default(),
@@ -2861,8 +2940,8 @@ fn a_note_the_builder_took_at_a_step_joins_the_feed_and_isnt_sent_again() {
inbox: Inbox::new(ws.inbox_dir()),
editor: None,
notes: Arc::new(Mutex::new(vec![
Note { id: 1, text: "make the header blue".into(), shown: "make the header blue".into(), pictures: Vec::new() },
Note { id: 2, text: "add a footer".into(), shown: "add a footer".into(), pictures: Vec::new() },
Note { id: 1, text: "make the header blue".into(), shown: "make the header blue".into(), pictures: Vec::new(), questions: vec![asked] },
Note { id: 2, text: "add a footer".into(), shown: "add a footer".into(), pictures: Vec::new(), questions: Vec::new() },
])),
feed: Arc::new(Mutex::new(feed::FeedLog::open(&ws))),
assets: false,
@@ -2879,11 +2958,12 @@ fn a_note_the_builder_took_at_a_step_joins_the_feed_and_isnt_sent_again() {
assert_eq!(notes::claim(&dir), ["make the header blue"]);
std::fs::rename(dir.join("2.wait"), dir.join("2.json")).unwrap();
w.relay_read_notes(&ws);
assert!(questions::untold(&ws, false).is_empty(), "the answers in a read note are told");
let shown: Vec<String> = rx.try_iter().filter_map(|e| if let RunEvent::Note { shown, .. } = e { Some(shown) } else { None }).collect();
assert_eq!(shown, ["make the header blue"], "it joins the feed as soon as the builder took it");
assert!(!notes::was_read(&dir, 1), "its files are gone");
// After the turn, only the note nobody took is sent, and no hook can hand it over again.
let follow = w.added(&mut ws).unwrap();
let (follow, _) = w.added(&mut ws, true).unwrap();
assert!(follow.contains("add a footer") && !follow.contains("make the header blue"), "{follow}");
assert!(notes::claim(&dir).is_empty());
}
+1
View File
@@ -359,6 +359,7 @@ fn rebuild_start(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolErr
continuing: p.resume,
max_rounds: p.rounds.unwrap_or(2),
beginner: false,
clean_room: Some(ctx.session.clean_room()),
..RunOptions::default()
};
// A tool runs with the session locked, so the hub reads the saved file: use this session's
+1
View File
@@ -154,6 +154,7 @@ impl CraftApp {
kinds: self.kinds.clone(),
max_rounds: build.max_rounds,
good_enough: build.good_enough,
clean_room: Some(!self.settings.deep_mode),
..RunOptions::default()
}
}
+1 -1
View File
File diff suppressed because one or more lines are too long
+8
View File
@@ -678,6 +678,14 @@ builder loop saved the reset only after a successful turn. A failed or cancelled
removed the note, so reopening kept the old unchanged-turn count. Persist deferred request state
on terminal errors too, outside provider retries; keep the original outcome if that save also fails.
**Context added to the message but not the note.** "Just ask" answers were prepended to the
builder's next message, but a note can reach a builder through its tool hook before any message,
so the note carried the request without what it referred to. Put shared context where every path
reads it (the note's hand-over file and the after-turn prompt), not in one delivery path, and test
the fast path (hook) and the fallback (after the turn) separately. Mark it told only when the note
is actually read or sent, never when it is written; and keep a note's raw text so a later run can
filter answers by its own mode.
**Lower-casing a command, then comparing its paths.** Auto mode lower-cased a shell command to
match keywords, then checked its paths against the project folder with that same text; Windows
compares paths without case, so only a Mac showed it: deleting `/Users/…/app/Build` in the