diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0d26e1b..134916b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,9 +33,8 @@ jobs: cache: npm # The Electron *package* is needed — `src/main` and `src/preload` are typed against - # it. The 100MB Electron *binary* is not: nothing here launches a window. The - # `drive:*` scripts do, and they want a macOS runner and a display, so they are not - # part of this workflow. + # it. The Electron *binary* is not needed in this job. + # The real Electron walkthrough runs with Xvfb in the bridge job below. - name: Install env: ELECTRON_SKIP_BINARY_DOWNLOAD: "1" @@ -87,6 +86,30 @@ jobs: working-directory: brave-bot-ui run: cargo test --all + # Reuse the compiled bridge for a credential-free, real Electron walkthrough. + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 24 + cache: npm + cache-dependency-path: brave-bot-ui/package-lock.json + + - name: Install desktop test dependencies + run: | + sudo apt-get update + sudo apt-get install -y xvfb libgtk-3-0 libnss3 libasound2t64 + + - name: Build desktop and run Node tests + working-directory: brave-bot-ui + run: | + npm ci + npm run build + node --test scripts/*.test.mjs + + - name: Manual walkthrough regression + working-directory: brave-bot-ui + timeout-minutes: 5 + run: xvfb-run -a node scripts/drive-manual-walkthrough.mjs + # Deliberately no `cargo fmt --all -- --check`, which the agent's own CI does run. The # bridge crate is not rustfmt-clean: rustfmt would rewrite around 490 lines, mostly # breaking method chains and `assert!` calls that are on one line on purpose. Adding diff --git a/Cargo.lock b/Cargo.lock index d31142a..b5b0a15 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "bravebot-agent" -version = "0.8.0" +version = "0.9.0" dependencies = [ "base64 0.22.1", "bravebot-aichat", @@ -116,7 +116,7 @@ dependencies = [ [[package]] name = "bravebot-aichat" -version = "0.8.0" +version = "0.9.0" dependencies = [ "bravebot-config", "bravebot-core", @@ -128,7 +128,7 @@ dependencies = [ [[package]] name = "bravebot-bedrock" -version = "0.8.0" +version = "0.9.0" dependencies = [ "bravebot-aichat", "bravebot-config", @@ -151,26 +151,27 @@ dependencies = [ "bravebot-tui", "serde", "serde_json", + "tempfile", ] [[package]] name = "bravebot-config" -version = "0.8.0" +version = "0.9.0" dependencies = [ "serde_json", ] [[package]] name = "bravebot-core" -version = "0.8.0" +version = "0.9.0" [[package]] name = "bravebot-i18n" -version = "0.8.0" +version = "0.9.0" [[package]] name = "bravebot-lsp" -version = "0.8.0" +version = "0.9.0" dependencies = [ "bravebot-core", "serde", @@ -179,7 +180,7 @@ dependencies = [ [[package]] name = "bravebot-net" -version = "0.8.0" +version = "0.9.0" dependencies = [ "bravebot-core", "ureq", @@ -187,7 +188,7 @@ dependencies = [ [[package]] name = "bravebot-sandbox" -version = "0.8.0" +version = "0.9.0" dependencies = [ "landlock", "libc", @@ -195,7 +196,7 @@ dependencies = [ [[package]] name = "bravebot-signing" -version = "0.8.0" +version = "0.9.0" dependencies = [ "base64 0.22.1", "hmac", @@ -204,7 +205,7 @@ dependencies = [ [[package]] name = "bravebot-skus" -version = "0.8.0" +version = "0.9.0" dependencies = [ "challenge-bypass-ristretto", "hmac", @@ -216,7 +217,7 @@ dependencies = [ [[package]] name = "bravebot-tui" -version = "0.8.0" +version = "0.9.0" dependencies = [ "base64 0.22.1", "bravebot-agent", diff --git a/crates/bravebot-bridge/Cargo.toml b/crates/bravebot-bridge/Cargo.toml index 8a238bc..ed25096 100644 --- a/crates/bravebot-bridge/Cargo.toml +++ b/crates/bravebot-bridge/Cargo.toml @@ -29,3 +29,6 @@ bravebot-core = { path = "../../vendor/bravebot/crates/core" } bravebot-tui = { path = "../../vendor/bravebot/crates/tui" } serde = { workspace = true } serde_json = { workspace = true } + +[dev-dependencies] +tempfile = "3" diff --git a/crates/bravebot-bridge/src/bin/bravebot-rpc.rs b/crates/bravebot-bridge/src/bin/bravebot-rpc.rs index c2c4ebc..554fddf 100644 --- a/crates/bravebot-bridge/src/bin/bravebot-rpc.rs +++ b/crates/bravebot-bridge/src/bin/bravebot-rpc.rs @@ -15,8 +15,14 @@ use std::sync::{Arc, Mutex}; fn main() { let mut args = std::env::args().skip(1); + let mut settings = None; if let Some(flag) = args.next() { match flag.as_str() { + "--settings" => { + let Some(path) = args.next() else { eprintln!("--settings requires a file path"); std::process::exit(2); }; + if args.next().is_some() { eprintln!("unexpected arguments after settings file"); std::process::exit(2); } + settings = Some(std::path::PathBuf::from(path)); + } "--version" | "-V" => { println!("bravebot-rpc {} (agent {})", env!("CARGO_PKG_VERSION"), bravebot_bridge::agent_build()); return; @@ -38,7 +44,7 @@ fn main() { let emitter = Arc::clone(&out); let mut bridge = Bridge::new(Box::new(move |event: Event| { write_line(&emitter, &event.to_value()); - })); + })).with_settings(settings); bridge.ready(); diff --git a/crates/bravebot-bridge/src/bridge.rs b/crates/bravebot-bridge/src/bridge.rs index 0c9c2b5..22c0384 100644 --- a/crates/bravebot-bridge/src/bridge.rs +++ b/crates/bravebot-bridge/src/bridge.rs @@ -46,12 +46,14 @@ struct Open { /// The turn in flight, if there is one. running: Option, model: Option, + watches: Arc>, } /// Drives the agent for a front-end. pub struct Bridge { open: HashMap, next_handle: u64, + settings: Option, emitter: Emitter, } @@ -60,10 +62,18 @@ impl Bridge { Self { open: HashMap::new(), next_handle: 0, + settings: None, emitter: Emitter::new(emit), } } + /// Preserve the selected path even if it disappeared: future requests must fail rather + /// than silently fall back to another destination after a process restart. + pub fn with_settings(mut self, path: Option) -> Self { + self.settings = path; + self + } + /// Announce what this is, before anything is asked. pub fn ready(&mut self) { let info = self.info(); @@ -77,10 +87,19 @@ impl Bridge { /// is a situation that will happen and should degrade rather than crash. pub fn dispatch(&mut self, request: &Request) -> Result { match request.method.as_str() { - "agent.info" => Ok(self.info()), + "agent.info" => { + let mut info = self.info(); + if let Some(handle) = request.optional_string("session") { + let open = self.open.get(&handle).ok_or_else(Failure::no_such_session)?; + let config = crate::settings::config(Some(&open.project), self.settings.as_deref()); + info["configured"] = json!(config.is_ok()); + info["defaultModel"] = json!(config.ok().map(|c| c.default_model)); + } + Ok(info) + }, "models.list" => { - let config = Config::from_env() - .map_err(|error| Failure::new(ErrorCode::Config, error.to_string()))?; + let directory = request.optional_string("directory").map(PathBuf::from); + let config = crate::settings::config(directory.as_deref(), self.settings.as_deref())?; Ok(crate::models::list(&config)) }, "session.list" => self.list(request), @@ -90,15 +109,28 @@ impl Bridge { "session.close" => self.close_session(request), "turn.send" => self.send_turn(request), "turn.cancel" => self.cancel_turn(request), + "watches.list" | "watches.add" | "watches.stop" => self.watches(request), + "watches.poll" => { self.poll_watches(); Ok(json!({})) }, "confirm.reply" => self.reply_confirm(request), "run.reply" => self.reply_run(request), "output.reply" => self.reply_output(request), "vouch.reply" => self.reply_vouch(request), + "vet.reply" => self.deliver(request, Reply::Vet(wire::decision(request.param("decision")))), "ask.reply" => self.reply_ask(request), "trust.reply" => self.reply_trust(request), "permissions.list" => self.permissions(request, false), "permissions.revoke" => self.permissions(request, true), - "doctor" => Ok(Self::doctor()), + "settings.inspect" => { + let project = request.optional_string("session").and_then(|id| self.open.get(&id)).map(|s| s.project.as_path()); + Ok(crate::settings::report(project, self.settings.as_deref())) + }, + "settings.select" => { + let path = request.optional_string("path").map(PathBuf::from); + if let Some(path) = &path { crate::settings::validate(path)?; } + self.settings = path; + Ok(crate::settings::report(None, self.settings.as_deref())) + }, + "doctor" => Ok(json!({"found": true, "structured": true, "text": serde_json::to_string_pretty(&crate::settings::report(None, self.settings.as_deref())).unwrap_or_default()})), other => Err(Failure::bad_request(format!("unknown method `{other}`"))), } } @@ -112,8 +144,8 @@ impl Bridge { json!({ "build": crate::agent_build(), "version": env!("CARGO_PKG_VERSION"), - "defaultModel": Config::from_env().ok().map(|config| config.default_model), - "configured": Config::from_env().is_ok(), + "defaultModel": crate::settings::config(None, self.settings.as_deref()).ok().map(|config| config.default_model), + "configured": crate::settings::config(None, self.settings.as_deref()).is_ok(), "home": bravebot_tui::store::directory().map(|d| d.display().to_string()), }) } @@ -168,6 +200,7 @@ impl Bridge { state: Arc::new(Mutex::new(state)), answered_trust, running: None, + watches: Arc::new(Mutex::new(bravebot_tui::watches::Watches::new())), model: None, }); @@ -195,7 +228,7 @@ impl Bridge { json!({ "session": handle, - "model": Config::from_env().ok().map(|config| config.default_model), + "model": crate::settings::config(Some(directory), self.settings.as_deref()).ok().map(|config| config.default_model), "record": { "id": record.id, "directory": record.directory, @@ -209,6 +242,7 @@ impl Bridge { }, "said": said, "context": record.conversation.context, + "contextTokens": record.conversation.measured, // As on `turn.done`, and read straight off the record rather than off the restored // conversation: it is written down, so a session resumed in a new process knows what // compaction had already taken without having to watch it happen. @@ -255,6 +289,7 @@ impl Bridge { state: Arc::new(Mutex::new(State::fresh(TrustStore::new(&directory)))), answered_trust: false, running: None, + watches: Arc::new(Mutex::new(bravebot_tui::watches::Watches::new())), model: None, }); @@ -268,7 +303,7 @@ impl Bridge { Ok(json!({ "session": handle, - "model": Config::from_env().ok().map(|config| config.default_model), + "model": crate::settings::config(Some(&directory), self.settings.as_deref()).ok().map(|config| config.default_model), "directory": directory.display().to_string(), "branch": branch, })) @@ -383,6 +418,7 @@ impl Bridge { // the same window, so asking again would be asking somebody to answer twice. answered_trust, running: None, + watches: Arc::new(Mutex::new(bravebot_tui::watches::Watches::new())), model: None, }); @@ -408,6 +444,7 @@ impl Bridge { "said": recounted, "prefill": cut.prompt, "context": snapshot.context, + "contextTokens": snapshot.measured, "turns": ordinal, "todos": todos_json(&todos), "trust": { "known": known, "rules": if known { Value::from(rules) } else { Value::Null } }, @@ -507,13 +544,13 @@ impl Bridge { } let model = requested_model.or_else(|| open.model.clone()); - let config = Config::from_env() - .map_err(|error| Failure::new(ErrorCode::Config, error.to_string()))?; + let config = crate::settings::config(Some(&open.project), self.settings.as_deref())?; let mut workspace = Workspace::new(open.project.clone()) .map_err(|error| Failure::new(ErrorCode::Internal, error.to_string()))?; let project = open.project.clone(); let state = Arc::clone(&open.state); + let watches = Arc::clone(&open.watches); let (turn_number, directories) = state .lock() .map(|s| (s.turns + 1, s.directories.clone())) @@ -549,9 +586,21 @@ impl Bridge { let session = handle.clone(); let worker_model = model.clone(); + + self.emitter.send(Event::new( + "turn.started", + &handle, + json!({ "turn": turn_number }), + )); + + if let Some(open) = self.open.get_mut(&handle) { + open.running = Some(running); + open.model = model; + } thread::spawn(move || { work(Work { model: worker_model, + watches, emitter, session, project, @@ -570,16 +619,6 @@ impl Bridge { }); }); - self.emitter.send(Event::new( - "turn.started", - &handle, - json!({ "turn": turn_number }), - )); - - if let Some(open) = self.open.get_mut(&handle) { - open.running = Some(running); - open.model = model; - } Ok(json!({ "turn": turn_number })) } @@ -595,6 +634,7 @@ impl Bridge { if let Some(running) = &open.running { running.cancel.cancel(); } + if let Ok(mut watches) = open.watches.lock() { watches.stop_firing(); } // Cancelling when nothing is running is not an error: the turn may have finished // between the user pressing the key and this arriving. Ok(json!({})) @@ -635,7 +675,7 @@ impl Bridge { /// Carry one answer to the turn that is waiting for it. /// - /// Shared by all four, because everything after "which question is this" is identical + /// Shared by every reply kind, because everything after "which question is this" is identical /// and the differences are all in the reading of the answer, above. Note what is *not* /// here: no check that the front-end sent the kind of reply matching what is /// outstanding. That is [`Running::answer`]'s job, and it is left there so there is one @@ -727,30 +767,70 @@ impl Bridge { })) } - /// Check the agent's configuration and confinement. - /// - /// Shelled out to, because these checks live in the CLI's own binary upstream and - /// cannot be called as a library without a change we do not make. `found: false` when - /// no `bravebot` is on PATH: a diagnostic that is unavailable should say so and leave the - /// rest of the app working. - fn doctor() -> Value { - match std::process::Command::new("bravebot").arg("doctor").output() { - Ok(output) => { - let mut text = String::from_utf8_lossy(&output.stdout).into_owned(); - text.push_str(&String::from_utf8_lossy(&output.stderr)); - json!({ - "found": true, - "structured": false, - "text": text, - "exitCode": output.status.code(), - }) + fn watches(&mut self, request: &Request) -> Result { + let handle = request.string("session")?; + self.reap(&handle); + let open = self.open.get(&handle).ok_or_else(Failure::no_such_session)?; + let mut watches = open.watches.lock().map_err(|_| Failure::bad_request("Watches unavailable."))?; + if request.method == "watches.add" { + if !open.answered_trust { return Err(Failure::bad_request("Answer the project trust question first.")); } + if open.running.is_some() { return Err(Failure::new(ErrorCode::TurnInFlight, "Wait for the current turn before adding a watch.")); } + let path = request.string("path")?; + if path.is_empty() || path.chars().any(char::is_control) { return Err(Failure::bad_request("Choose a project file.")); } + if !watches.live().iter().any(|w| w.path() == path) { + let workspace = Workspace::new(open.project.clone()).map_err(|_| Failure::bad_request("Project unavailable."))?; + watches.arm(path.clone(), 0, workspace.look(&path), std::time::Instant::now()) + .map_err(|_| Failure::bad_request("Cannot watch this file. It must exist inside the project, with fewer than eight active watches."))?; + } + } else if request.method == "watches.stop" { + if request.flag("all", false) { watches.stop_all(); } + else { let number = request.param("number").as_u64().ok_or_else(|| Failure::bad_request("A watch number is required."))?; watches.stop(number as usize); } + } + let now = std::time::Instant::now(); + Ok(json!({"watches": watches.live().iter().map(|w| json!({"number": w.number(), "path": w.path(), + "remainingSeconds": w.left(now).as_secs(), "armedBy": w.armed_by(), + "state": if watches.firing() == Some(w.number()) { "running" } else { "watching" } + })).collect::>(), "busy": open.running.is_some()})) + } + + /// Called by the desktop's clock, never a renderer-supplied generated prompt. + fn poll_watches(&mut self) { self.poll_watches_at(std::time::Instant::now()); } + + fn poll_watches_at(&mut self, now: std::time::Instant) { + let handles: Vec<_> = self.open.keys().cloned().collect(); + for handle in handles { + self.reap(&handle); + let Some(open) = self.open.get(&handle) else { continue }; + if open.running.is_some() || !open.answered_trust { continue; } + if open.watches.lock().map(|w| w.is_empty()).unwrap_or(true) { continue; } + let Ok(mut workspace) = Workspace::new(open.project.clone()) else { + if let Ok(mut watches) = open.watches.lock() { + for watch in watches.live() { self.emitter.send(Event::new("watch.ended", &handle, json!({"number": watch.number(), "reason": "project-unavailable"}))); } + watches.stop_all(); + } + continue; + }; + if let Ok(state) = open.state.try_lock() { for directory in &state.directories { let _ = workspace.add_directory(&directory.display().to_string()); } } + let due = { + let Ok(mut watches) = open.watches.lock() else { continue }; + let ended = watches.look(now, |path| workspace.look(path)); + for (number, reason) in ended { + self.emitter.send(Event::new("watch.ended", &handle, json!({"number": number, "reason": match reason { + bravebot_tui::watches::Reaped::Aged => "expired", bravebot_tui::watches::Reaped::OutOfReach => "out-of-reach", + }}))); + } + watches.due(now).map(|w| (w.number(), w.path().to_string())) + }; + let Some((number, path)) = due else { continue }; + let prompt = bravebot_agent::watch::fired(number, &path); + // Announce the cause before starting a worker, so early events follow it. + self.emitter.send(Event::new("watch.fired", &handle, json!({"number": number, "path": path}))); + if let Ok(mut watches) = open.watches.lock() { watches.dispatched(number); } + let request = Request::parse(&json!({"id": 0, "method": "turn.send", "params": {"session": handle, "prompt": prompt, "recall": false}}).to_string()); + if let Ok(request) = request && let Err(error) = self.send_turn(&request) { + if let Some(open) = self.open.get(&handle) && let Ok(mut watches) = open.watches.lock() { watches.stop(number); } + self.emitter.send(Event::new("watch.ended", &handle, json!({"number": number, "reason": "failed", "message": error.message}))); } - Err(error) => json!({ - "found": false, - "structured": false, - "text": format!("could not run `bravebot doctor`: {error}"), - "exitCode": null, - }), } } @@ -832,6 +912,7 @@ struct Work { project: PathBuf, state: Arc>, config: Config, + watches: Arc>, model: Option, workspace: Workspace, prompt: String, @@ -858,6 +939,7 @@ fn work(work: Work) { project, state, config, + watches, model, workspace, prompt, @@ -890,6 +972,8 @@ fn work(work: Work) { task = task.with_dropped_text(path); } + let free = watches.lock().map(|w| bravebot_tui::watches::MAX_LIVE.saturating_sub(w.live().len())).unwrap_or(0); + task = task.arming(if free == 0 { bravebot_agent::watch::Arming::Full } else { bravebot_agent::watch::Arming::Allowed { free } }); let mut reporter = BridgeReporter::new(emitter.clone(), &session); let mut confirmer = BridgeConfirmer::new(emitter.clone(), &session, pending, answers, cancel.clone()); let mut sink = BridgeSink::new(emitter.clone(), &session, turn); @@ -931,6 +1015,13 @@ fn work(work: Work) { match outcome { Ok(outcome) => { + if let Ok(mut watches) = watches.lock() { + for path in &outcome.watches { + if !watches.live().iter().any(|w| w.path() == path) { + let _ = watches.arm(path.clone(), turn, workspace.look(path), std::time::Instant::now()); + } + } + } // The map after the turn, which may differ from the one it started with: a // turn that writes untrusted data into a trusted path records that path as // untrusted, and the next turn must inherit that or it would read the data @@ -968,6 +1059,7 @@ fn work(work: Work) { "clean": outcome.clean, "tokens": outcome.tokens, "outputTokens": outcome.output_tokens, + "contextTokens": outcome.context_tokens, "notices": outcome.notices, "trust": { "rules": rules }, // The session's durable name, which is real from here and was not before: @@ -990,8 +1082,21 @@ fn work(work: Work) { Err(error) => { let _ = save(&project, &mut state, turn, sink.trail()); + let ending = error.ending(); + let diagnosis = ending.diagnosis(); + let category = diagnosis.map(|d| d.category.name()); + // A configured gateway does not serve the built-in Brave default. Keep this + // distinct from a missing token: re-entering the gateway key cannot fix routing. + let chosen = task.model.as_deref().unwrap_or(&config.default_model); + let category = if category == Some("unconfigured") + && (!config.providers.is_empty() || config.bedrock.is_some()) + && !config.serves_aichat() + && config.provider_for(chosen).is_none() + && config.bedrock_for(chosen).is_none() + { Some("model-unconfigured") } else { category }; + let attempts = match ending { bravebot_agent::outcome::Ending::Stopped { attempts } => attempts, _ => diagnosis.and_then(|d| d.attempts) }; let kind = match &error { - TurnError::Cancelled => "cancelled", + TurnError::Cancelled { .. } => "cancelled", TurnError::Precommit(_) => "precommit", TurnError::Workspace(_) => "workspace", TurnError::Chat(_) => "chat", @@ -1005,7 +1110,8 @@ fn work(work: Work) { emitter.send(Event::new( "turn.error", &session, - json!({ "turn": turn, "kind": kind, "message": error.to_string(), + json!({ "turn": turn, "kind": kind, "message": category.unwrap_or("cancelled"), "category": category, "attempts": attempts, "status": diagnosis.and_then(|d| d.status), + "contextTokens": state.conversation.last_request_tokens(), "id": state.handle.as_ref().map(|handle| handle.id()) }), )); } @@ -1013,6 +1119,7 @@ fn work(work: Work) { // Last, and after the record is on disk, so a front-end that reloads on being told // the turn ended reads the same thing this wrote. + if let Ok(mut watches) = watches.lock() { watches.turn_ended(std::time::Instant::now()); } finished.store(true, std::sync::atomic::Ordering::Release); } @@ -1088,3 +1195,104 @@ fn rules_json(trust: &TrustStore) -> Vec { }) .collect() } + +#[cfg(test)] +mod watch_tests { + use super::*; + use std::time::{Duration, Instant}; + + #[test] + fn a_failed_automatic_turn_stops_its_watch_and_never_reads_file_content_into_the_prompt() { + let mut builder = tempfile::Builder::new(); + builder.prefix("bravebot-watch-poll-"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o700)); + } + let directory = builder.tempdir().unwrap(); + let root = directory.path().to_path_buf(); + std::fs::write(root.join("watched"), "old").unwrap(); + let events = Arc::new(Mutex::new(Vec::new())); + let held = Arc::clone(&events); + let mut bridge = Bridge::new(Box::new(move |e| held.lock().unwrap().push(e))); + // A removed override must fail before making any model request. + bridge.settings = Some(root.join("missing.json")); + let now = Instant::now(); + let mut watches = bravebot_tui::watches::Watches::new(); + let workspace = Workspace::new(root.clone()).unwrap(); + watches.arm("watched".into(), 1, workspace.look("watched"), now).unwrap(); + let watches = Arc::new(Mutex::new(watches)); + let handle = bridge.mint(Open { + project: root.clone(), state: Arc::new(Mutex::new(State::fresh(TrustStore::new(&root)))), + answered_trust: true, running: None, model: None, watches: Arc::clone(&watches), + }); + std::fs::write(root.join("watched"), "PRIVATE FILE CONTENT MUST NOT BE SENT").unwrap(); + bridge.poll_watches_at(now + Duration::from_secs(6)); + assert!(watches.lock().unwrap().is_empty()); + let events = events.lock().unwrap(); + assert_eq!(events.iter().filter(|e| e.name == "watch.fired").count(), 1); + assert_eq!(events.last().unwrap().name, "watch.ended"); + assert!(events.iter().all(|e| e.session.as_deref() == Some(&handle))); + assert!(!events.iter().any(|e| e.data.to_string().contains("PRIVATE FILE"))); + } + + #[test] + fn cancelling_an_automatic_turn_stops_only_its_originating_watch() { + let mut builder = tempfile::Builder::new(); + builder.prefix("bravebot-watch-cancel-"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o700)); + } + let directory = builder.tempdir().unwrap(); + let project = directory.path().to_path_buf(); + let now = Instant::now(); + let mut watches = bravebot_tui::watches::Watches::new(); + let first = watches.arm("first".into(), 1, bravebot_agent::watch::Looked::Saw("a".into()), now).unwrap(); + let second = watches.arm("second".into(), 1, bravebot_agent::watch::Looked::Saw("b".into()), now).unwrap(); + watches.dispatched(first); + let watches = Arc::new(Mutex::new(watches)); + let cancel = Cancel::new(); + let (answers, _receiver) = mpsc::channel(); + let running = Running { cancel: cancel.clone(), answers, pending: Arc::new(Mutex::new(None)), turn: 1, + finished: Arc::new(std::sync::atomic::AtomicBool::new(false)) }; + let mut bridge = Bridge::new(Box::new(|_| {})); + let handle = bridge.mint(Open { project: project.clone(), + state: Arc::new(Mutex::new(State::fresh(TrustStore::new(&project)))), + answered_trust: true, running: Some(running), model: None, watches: Arc::clone(&watches) }); + let request = Request::parse(&json!({"id": 1, "method": "turn.cancel", "params": {"session": handle}}).to_string()).unwrap(); + bridge.dispatch(&request).unwrap(); + assert!(cancel.is_cancelled()); + let watches = watches.lock().unwrap(); + assert_eq!(watches.live().len(), 1); + assert_eq!(watches.live()[0].number(), second); + } + + #[test] + fn polling_expires_watches_without_starting_a_turn() { + let mut builder = tempfile::Builder::new(); + builder.prefix("bravebot-watch-expiry-"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o700)); + } + let directory = builder.tempdir().unwrap(); + let root = directory.path().to_path_buf(); + std::fs::write(root.join("file"), "original").unwrap(); + let now = Instant::now(); + let mut watches = bravebot_tui::watches::Watches::new(); + watches.arm("file".into(), 1, Workspace::new(root.clone()).unwrap().look("file"), now).unwrap(); + let watches = Arc::new(Mutex::new(watches)); + let events = Arc::new(Mutex::new(Vec::new())); + let held = Arc::clone(&events); + let mut bridge = Bridge::new(Box::new(move |e| held.lock().unwrap().push(e))); + bridge.mint(Open { project: root.clone(), state: Arc::new(Mutex::new(State::fresh(TrustStore::new(&root)))), + answered_trust: true, running: None, model: None, watches: Arc::clone(&watches) }); + bridge.poll_watches_at(now + Duration::from_secs(7 * 24 * 60 * 60)); + assert!(watches.lock().unwrap().is_empty()); + assert_eq!(events.lock().unwrap()[0].data["reason"], "expired"); + } +} diff --git a/crates/bravebot-bridge/src/lib.rs b/crates/bravebot-bridge/src/lib.rs index 5ed9781..5dcf466 100644 --- a/crates/bravebot-bridge/src/lib.rs +++ b/crates/bravebot-bridge/src/lib.rs @@ -23,6 +23,7 @@ pub mod models; pub mod protocol; pub mod running; pub mod store; +pub mod settings; pub mod turn; pub mod wire; diff --git a/crates/bravebot-bridge/src/models.rs b/crates/bravebot-bridge/src/models.rs index 0450497..5a2b4f9 100644 --- a/crates/bravebot-bridge/src/models.rs +++ b/crates/bravebot-bridge/src/models.rs @@ -2,7 +2,7 @@ use bravebot_aichat::models::{self, Model}; use bravebot_config::Config; -use bravebot_config::provider::Provider; +use bravebot_config::provider::{Credential, Provider}; use bravebot_core::capability::{Capability, CapabilitySet}; use bravebot_core::policy::{Policy, ReleasePlan, Routing}; use bravebot_core::{event::Sink, label::Label}; @@ -39,13 +39,14 @@ pub fn list(config: &Config) -> Value { })); continue; } - let Some(token) = provider.token(|name| std::env::var(name).ok()) else { + let credential = provider.credential(|name| std::env::var(name).ok()); + if credential == Credential::Absent { warnings.push(format!( "No credential configured for {}.", provider.display_name() )); continue; - }; + } let mut routing = Routing::new(); routing.insert_trusted("models", provider.models_url()); routing.insert_trusted("account-models", provider.account_models_url()); @@ -57,7 +58,7 @@ pub fn list(config: &Config) -> Value { &mut sink, ) .ok() - .and_then(|mut policy| gateway_models(&mut policy, provider, &token)); + .and_then(|mut policy| gateway_models(&mut policy, provider, &credential)); match result { Some(listed) => { for (model, badges) in listed { @@ -126,15 +127,13 @@ struct Architecture { fn gateway_models( policy: &mut Policy<'_, S>, provider: &Provider, - token: &str, + credential: &Credential, ) -> Option)>> { let fetch = |policy: &mut Policy<'_, S>, url: String| -> Option { let response = Egress::new() .fetch( policy, - Request::get(&url) - .header("accept", "application/json") - .header("authorization", format!("Bearer {token}")), + model_request(&url, credential)?, Label::untrusted_public(), ) .ok()?; @@ -147,6 +146,15 @@ fn gateway_models( Some(gateway_rows(provider, listed.data)) } +fn model_request(url: &str, credential: &Credential) -> Option { + let request = Request::get(url).header("accept", "application/json"); + match credential { + Credential::Token(token) => Some(request.header("authorization", format!("Bearer {token}"))), + Credential::NotNeeded => Some(request), + Credential::Absent => None, + } +} + fn gateway_rows(provider: &Provider, listed: Vec) -> Vec<(Model, Vec<&'static str>)> { listed .into_iter() @@ -266,6 +274,16 @@ pub fn selection(value: Option<&Value>) -> Result, crate::protoco mod tests { use super::*; + #[test] + fn model_discovery_respects_all_three_credential_states() { + let url = "https://gateway.example/v1/models"; + assert!(model_request(url, &Credential::Absent).is_none()); + let public = model_request(url, &Credential::NotNeeded).unwrap(); + assert_eq!(public.headers, vec![("accept".into(), "application/json".into())]); + let authenticated = model_request(url, &Credential::Token("test-token".into())).unwrap(); + assert!(authenticated.headers.contains(&("authorization".into(), "Bearer test-token".into()))); + } + #[test] fn capabilities_distinguish_input_from_output() { let entry = serde_json::from_value(json!({ diff --git a/crates/bravebot-bridge/src/running.rs b/crates/bravebot-bridge/src/running.rs index ae2b833..e93880d 100644 --- a/crates/bravebot-bridge/src/running.rs +++ b/crates/bravebot-bridge/src/running.rs @@ -254,6 +254,7 @@ impl Running { Kind::Run => Reply::Run(RunDecision::reject()), Kind::Output => Reply::Output(Decision::Reject), Kind::Vouch => Reply::Vouch(Decision::Reject), + Kind::Vet => Reply::Vet(Decision::Reject), // No answers at all, which is how this question says nobody was asked. Kind::Ask => Reply::Ask(Vec::new()), }); diff --git a/crates/bravebot-bridge/src/settings.rs b/crates/bravebot-bridge/src/settings.rs new file mode 100644 index 0000000..8d2b212 --- /dev/null +++ b/crates/bravebot-bridge/src/settings.rs @@ -0,0 +1,108 @@ +//! Configuration inspection uses the linked agent, never a separately installed CLI. +use crate::protocol::{ErrorCode, Failure}; +use bravebot_config::{Config, Settings, Managed}; +use serde_json::{Value, json}; +use std::path::Path; + +pub fn layers(project: Option<&Path>, selected: Option<&Path>) -> Settings { + Settings::layered(bravebot_agent::home::directory(), project, selected) +} + +pub fn config(project: Option<&Path>, selected: Option<&Path>) -> Result { + if let Some(path) = selected { validate(path)?; } + Config::from_env_and_settings(&layers(project, selected), &Managed::load()) + .map_err(|e| Failure::new(ErrorCode::Config, e.to_string())) +} + +pub fn validate(path: &Path) -> Result<(), Failure> { + let meta = std::fs::metadata(path).map_err(|_| Failure::bad_request("The settings file cannot be opened."))?; + if !meta.is_file() || meta.len() > 64 * 1024 { + return Err(Failure::bad_request("Choose a JSON settings file no larger than 64 KB.")); + } + let text = std::fs::read_to_string(path).map_err(|_| Failure::bad_request("The settings file cannot be read."))?; + let value: Value = serde_json::from_str(&text).map_err(|_| Failure::bad_request("The settings file is not valid JSON."))?; + if !value.is_object() { return Err(Failure::bad_request("Settings must be a JSON object.")); } + Ok(()) +} + +pub fn report(project: Option<&Path>, selected: Option<&Path>) -> Value { + let settings = layers(project, selected); + let managed = Managed::load(); + let configured = config(project, selected); + let transport = bravebot_net::transport::Transport::shared(); + let providers = configured.as_ref().map(|c| c.providers.iter().map(|p| json!({ + "name": p.display_name(), "credential": match p.credential(|key| std::env::var(key).ok()) { + bravebot_config::provider::Credential::Token(_) => "configured", + bravebot_config::provider::Credential::Absent => "missing", + bravebot_config::provider::Credential::NotNeeded => "not required", + } + })).collect::>()).unwrap_or_default(); + json!({ + "build": crate::agent_build(), "configured": configured.is_ok(), + "problem": configured.as_ref().err().map(|_| "No usable model service is configured. Choose a gateway, AWS Bedrock, or a configured Brave build."), + "model": configured.as_ref().ok().map(|c| &c.default_model), + "bedrock": configured.as_ref().is_ok_and(|c| c.bedrock.is_some()), + "brave": configured.as_ref().is_ok_and(|c| c.serves_aichat()), "providers": providers, + "selected": selected, "layers": settings.layers().collect::>(), + "overrides": settings.overridden().map(|(name, path)| json!({"name": name, "path": path})).collect::>(), + "managed": { "path": managed.path(), "keys": managed.pinned().collect::>() }, + "network": { "roots": transport.roots().paths(), + "problem": transport.trust_problem().map(ToString::to_string), + "trustsNothing": transport.trusts_nothing(), "proxy": transport.proxy_summary(), + "authenticated": transport.proxy_is_authenticated(), "unusableProxy": transport.unusable_proxy(), + "noProxy": transport.no_proxy() } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn selected_files_cannot_exceed_the_agents_read_limit() { + let mut builder = tempfile::Builder::new(); + builder.prefix("bravebot-settings-size-"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o700)); + } + let directory = builder.tempdir().unwrap(); + let root = directory.path().to_path_buf(); + let file = root.join("override.json"); + let mut text = r#"{"model":"selected/model"}"#.to_string(); + text.push_str(&" ".repeat(64 * 1024 - text.len())); + std::fs::write(&file, &text).unwrap(); + validate(&file).unwrap(); + assert_eq!(Settings::layered(None, None, Some(&file)).model(), Some("selected/model")); + text.push(' '); + std::fs::write(&file, text).unwrap(); + assert!(validate(&file).is_err(), "do not accept a file the agent silently ignores"); + } + + #[test] + fn a_selected_override_merges_after_project_files_without_editing_them() { + let mut builder = tempfile::Builder::new(); + builder.prefix("bravebot-settings-layers-"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o700)); + } + let directory = builder.tempdir().unwrap(); + let root = directory.path().to_path_buf(); + let home = root.join("home"); + let project = root.join("project"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(project.join(".bravebot")).unwrap(); + std::fs::write(home.join("settings.json"), r#"{"model":"home/model"}"#).unwrap(); + std::fs::write(project.join(".bravebot/settings.json"), r#"{"model":"project/model"}"#).unwrap(); + std::fs::write(project.join(".bravebot/settings.local.json"), r#"{"model":"local/model"}"#).unwrap(); + let selected = root.join("override.json"); + std::fs::write(&selected, r#"{"model":"selected/model"}"#).unwrap(); + validate(&selected).unwrap(); + let settings = Settings::layered(Some(home.clone()), Some(&project), Some(&selected)); + assert_eq!(settings.model(), Some("selected/model")); + assert_eq!(settings.layers().count(), 4); + assert_eq!(Settings::layered(Some(home), Some(&project), None).model(), Some("local/model")); + } +} diff --git a/crates/bravebot-bridge/src/turn.rs b/crates/bravebot-bridge/src/turn.rs index 267ccb7..5819dad 100644 --- a/crates/bravebot-bridge/src/turn.rs +++ b/crates/bravebot-bridge/src/turn.rs @@ -16,7 +16,7 @@ use crate::emit::Emitter; use crate::protocol::Event; use crate::wire; use bravebot_agent::confirm::{ - Confirmer, Decision, FetchRequest, ManifestRequest, ServerRequest, OutputRequest, RunDecision, RunRequest, VouchRequest, WriteRequest, + Confirmer, Decision, FetchRequest, ManifestRequest, ServerRequest, OutputRequest, RunDecision, RunRequest, VetRequest, VouchRequest, WriteRequest, }; use bravebot_core::ask::{Answer, Asking}; use bravebot_agent::report::{Activity, Landing, Phase, Reporter, Shown}; @@ -26,7 +26,7 @@ use serde_json::{Value, json}; use std::sync::mpsc::Receiver; use std::sync::{Arc, Mutex}; -/// Which of the four questions this is. +/// Which kind of approval or question this is. /// /// Recorded alongside the id so an answer has to be an answer to the question that was /// actually asked. Without it, a front-end that replied to a write while a run was @@ -38,6 +38,7 @@ pub enum Kind { Run, Output, Vouch, + Vet, Ask, } @@ -57,7 +58,7 @@ pub type Pending = Arc>>; /// What a front-end answered. /// -/// One variant per question rather than a bare [`Decision`] for all four, so a reply +/// One variant per question rather than a bare [`Decision`] for every kind, so a reply /// carries which question it is answering and the kernel's own types come back intact — /// [`RunDecision`] in particular, whose `remember` is a second answer that a `Decision` /// has nowhere to put. @@ -69,6 +70,7 @@ pub enum Reply { Run(RunDecision), Output(Decision), Vouch(Decision), + Vet(Decision), /// One answer per question, in the order they were asked. Empty means nobody could be /// asked — see [`Confirmer::ask_user`]. Ask(Vec), @@ -81,6 +83,7 @@ impl Reply { Reply::Run(_) => Kind::Run, Reply::Output(_) => Kind::Output, Reply::Vouch(_) => Kind::Vouch, + Reply::Vet(_) => Kind::Vet, Reply::Ask(_) => Kind::Ask, } } @@ -247,8 +250,8 @@ impl BridgeConfirmer { /// Put one question to whoever is watching, and block until it is answered. /// - /// The whole of the asking is here, once, because every one of the four questions has - /// the same failure modes and each of them must resolve to refusal. Writing that four + /// The whole of the asking is here, once, because every question has + /// the same failure modes and each of them must resolve to refusal. Writing that several /// times would be four chances to get it wrong in a way no test distinguishes. /// /// `None` means nobody answered — a poisoned lock, a departed front-end, a closed @@ -313,6 +316,13 @@ impl Confirmer for BridgeConfirmer { Decision::Reject } + fn confirm_vetted_read(&mut self, request: &VetRequest) -> Decision { + match self.ask(Kind::Vet, "vet.request", |id| wire::vet_request(id, request)) { + Some(Reply::Vet(decision)) => decision, + _ => Decision::Reject, + } + } + // The UI queues messages for the next turn; the protocol has no mid-turn input. // In particular, polling must neither block nor consume an approval reply. fn interjection(&mut self) -> Option { diff --git a/crates/bravebot-bridge/src/wire.rs b/crates/bravebot-bridge/src/wire.rs index 22c72ca..b93e530 100644 --- a/crates/bravebot-bridge/src/wire.rs +++ b/crates/bravebot-bridge/src/wire.rs @@ -20,7 +20,7 @@ use bravebot_agent::conversation::Said; use bravebot_agent::confirm::{ - Decision, Intent, OutputRequest, RunDecision, RunRequest, VouchRequest, WriteRequest, + Decision, Intent, VetRequest, OutputRequest, RunDecision, RunRequest, VouchRequest, WriteRequest, }; use bravebot_agent::diff::Change; use bravebot_agent::report::{Activity, Landing, Phase, Reach, Shown}; @@ -196,6 +196,7 @@ pub fn write_request(id: u64, request: &WriteRequest) -> Value { "path": request.path, "intent": intent(request.intent), "untrusted": request.untrusted, + "remark": request.remark.as_ref().map(|r| json!({"preview": r.preview, "lines": r.lines, "label": r.label})), "existing": request.existing.is_some(), "added": diff.added(), "removed": diff.removed(), @@ -276,6 +277,7 @@ pub fn output_request(id: u64, request: &OutputRequest) -> Value { "reference": request.reference, "lines": request.lines(), "output": request.output, + "vetting": vetting(request.verdict, request.reason.as_deref()), "summary": request.summary(), }) } @@ -291,6 +293,7 @@ pub fn vouch_request(id: u64, request: &VouchRequest) -> Value { "path": request.path, "preview": request.preview, "truncated": request.truncated, + "vetting": vetting(request.verdict, request.reason.as_deref()), }) } @@ -413,3 +416,16 @@ pub fn fitted(answers: Vec, asking: &Asking) -> Vec { }) .collect() } + +/// Advice for the person, never an approval or planner input. +fn vetting(verdict: bravebot_core::vetting::Verdict, reason: Option<&str>) -> Value { + json!({ "verdict": verdict.word(), "reason": reason, "detail": match verdict { + bravebot_core::vetting::Verdict::Inconclusive(detail) => Some(detail), _ => None, + } }) +} + +pub fn vet_request(id: u64, request: &VetRequest) -> Value { + json!({ "request": id, "origin": request.origin, "expects": request.expects, + "content": request.content, "lines": request.lines(), + "vetting": vetting(request.verdict, request.reason.as_deref()) }) +} diff --git a/crates/bravebot-bridge/tests/dispatch.rs b/crates/bravebot-bridge/tests/dispatch.rs index b6dded4..2d16313 100644 --- a/crates/bravebot-bridge/tests/dispatch.rs +++ b/crates/bravebot-bridge/tests/dispatch.rs @@ -232,13 +232,13 @@ fn cancelling_an_idle_session_is_not_an_error() { } #[test] -fn doctor_reports_rather_than_failing_when_bua_is_absent() { +fn doctor_reports_the_bundled_agent_without_an_external_cli() { let (mut bridge, _) = harness(); let report = call(&mut bridge, "doctor", json!({})).expect("doctor never errors"); assert!(report["found"].is_boolean()); assert_eq!( - report["structured"], json!(false), - "v1 shells out; the flag lets a client be written once" + report["structured"], json!(true), + "diagnostics come from the linked agent" ); assert!(report["text"].is_string()); } @@ -388,3 +388,61 @@ fn permission_review_can_only_remove_existing_grants() { let again = call(&mut bridge, "permissions.list", json!({"session": session})).unwrap(); assert_eq!(again, after); } + +#[test] +fn watches_require_trust_are_bounded_and_are_not_inherited_by_new_sessions() { + let mut builder = tempfile::Builder::new(); + builder.prefix("bravebot-ui-watch-test-"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o700)); + } + let directory = builder.tempdir().unwrap(); + let project = directory.path().to_path_buf(); + let (mut bridge, _) = harness(); + let session = call(&mut bridge, "session.new", json!({"directory": project})).unwrap()["session"].clone(); + std::fs::write(project.join("one"), "original").unwrap(); + assert_eq!(call(&mut bridge, "watches.add", json!({"session": session, "path": "one"})), Err(ErrorCode::BadRequest)); + call(&mut bridge, "trust.reply", json!({"session": session, "trusted": false})).unwrap(); + for i in 0..8 { + std::fs::write(project.join(format!("file-{i}")), "text").unwrap(); + call(&mut bridge, "watches.add", json!({"session": session, "path": format!("file-{i}")})).unwrap(); + } + assert_eq!(call(&mut bridge, "watches.add", json!({"session": session, "path": "one"})), Err(ErrorCode::BadRequest)); + let rows = call(&mut bridge, "watches.list", json!({"session": session})).unwrap(); + assert_eq!(rows["watches"].as_array().unwrap().len(), 8); + call(&mut bridge, "watches.stop", json!({"session": session, "all": true})).unwrap(); + assert_eq!(call(&mut bridge, "watches.add", json!({"session": session, "path": "../escape"})), Err(ErrorCode::BadRequest)); + assert_eq!(call(&mut bridge, "watches.add", json!({"session": session, "path": "line\nbreak"})), Err(ErrorCode::BadRequest)); + let fresh = call(&mut bridge, "session.new", json!({"directory": project})).unwrap()["session"].clone(); + assert_eq!(call(&mut bridge, "watches.list", json!({"session": fresh})).unwrap()["watches"], json!([])); + call(&mut bridge, "session.close", json!({"session": session})).unwrap(); + assert_eq!(call(&mut bridge, "watches.list", json!({"session": session})), Err(ErrorCode::NoSuchSession)); +} + +#[test] +fn settings_override_is_validated_and_diagnostics_use_the_linked_agent() { + let mut builder = tempfile::Builder::new(); + builder.prefix("bravebot-ui-settings-test-"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o700)); + } + let directory = builder.tempdir().unwrap(); + let project = directory.path().to_path_buf(); + let file = project.join("settings.json"); + let (mut bridge, _) = harness(); + std::fs::write(&file, "[]").unwrap(); + assert_eq!(call(&mut bridge, "settings.select", json!({"path": file})), Err(ErrorCode::BadRequest)); + std::fs::write(&file, r#"{"provider":{"local":{"options":{"baseURL":"http://localhost:11434/v1","apiKey":"NEVER-SHOW-THIS"},"models":{"test":{}}}},"model":"local/test"}"#).unwrap(); + let selected = call(&mut bridge, "settings.select", json!({"path": file})).unwrap(); + assert_eq!(selected["selected"], file.to_str().unwrap()); + assert!(!selected.to_string().contains("NEVER-SHOW-THIS")); + let doctor = call(&mut bridge, "doctor", json!({})).unwrap(); + assert_eq!(doctor["found"], true); + assert!(doctor["text"].as_str().unwrap().contains(bravebot_bridge::agent_build())); + let cleared = call(&mut bridge, "settings.select", json!({"path": null})).unwrap(); + assert!(cleared["selected"].is_null()); +} diff --git a/crates/bravebot-bridge/tests/refusal.rs b/crates/bravebot-bridge/tests/refusal.rs index a262b6f..f693825 100644 --- a/crates/bravebot-bridge/tests/refusal.rs +++ b/crates/bravebot-bridge/tests/refusal.rs @@ -35,6 +35,7 @@ fn a_write() -> WriteRequest { existing: Some("old\n".into()), intent: Intent::Edit, untrusted: false, + remark: None, } } @@ -101,7 +102,8 @@ fn an_answered_write_gets_the_answer_that_was_sent() { let answerer = std::thread::spawn(move || { // Wait for the question to be registered, then answer it. - for _ in 0..1000 { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while std::time::Instant::now() < deadline { let waiting = *running.pending.lock().expect("not poisoned"); if let Some(question) = waiting { assert!( @@ -110,7 +112,7 @@ fn an_answered_write_gets_the_answer_that_was_sent() { ); return; } - std::thread::yield_now(); + std::thread::sleep(std::time::Duration::from_millis(1)); } panic!("the write was never registered as pending"); }); @@ -166,12 +168,13 @@ fn refusing_the_pending_write_sends_a_rejection() { let running = harness.running; let closer = std::thread::spawn(move || { - for _ in 0..1000 { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while std::time::Instant::now() < deadline { if running.pending.lock().expect("not poisoned").is_some() { running.refuse_pending(); return; } - std::thread::yield_now(); + std::thread::sleep(std::time::Duration::from_millis(1)); } panic!("the write was never registered as pending"); }); @@ -203,12 +206,13 @@ fn refusing_nothing_queues_nothing() { // so we answer it explicitly and check the answer is ours. let pending = Arc::clone(&running.pending); let answerer = std::thread::spawn(move || { - for _ in 0..1000 { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while std::time::Instant::now() < deadline { let waiting = *pending.lock().expect("not poisoned"); if let Some(question) = waiting { return (running, question.id); } - std::thread::yield_now(); + std::thread::sleep(std::time::Duration::from_millis(1)); } panic!("never pending"); }); @@ -232,13 +236,14 @@ fn the_question_is_emitted_with_the_diff_and_not_the_body() { let pending = Arc::clone(&running.pending); let answerer = std::thread::spawn(move || { - for _ in 0..1000 { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while std::time::Instant::now() < deadline { let waiting = *pending.lock().expect("not poisoned"); if let Some(question) = waiting { running.answer(question.id, Reply::Write(Decision::Reject)); return; } - std::thread::yield_now(); + std::thread::sleep(std::time::Duration::from_millis(1)); } panic!("never pending"); }); @@ -296,6 +301,8 @@ fn an_unanswerable_output_read_refuses() { command: "git status".into(), output: "on branch main".into(), reference: "$1".into(), + verdict: bravebot_core::vetting::Verdict::Inconclusive("not checked"), + reason: None, }), Decision::Reject, "approving output nobody could see is the one thing this cannot mean" @@ -312,6 +319,8 @@ fn an_unanswerable_vouch_refuses() { path: "notes.md".into(), preview: "first line".into(), truncated: true, + verdict: bravebot_core::vetting::Verdict::Inconclusive("not checked"), + reason: None, }), Decision::Reject ); @@ -354,12 +363,13 @@ fn refusing_a_pending_run_reaches_the_turn_as_a_run() { let pending = Arc::clone(&running.pending); let answerer = std::thread::spawn(move || { - for _ in 0..1000 { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while std::time::Instant::now() < deadline { if pending.lock().expect("not poisoned").is_some() { running.refuse_pending(); return; } - std::thread::yield_now(); + std::thread::sleep(std::time::Duration::from_millis(1)); } panic!("the run was never registered as pending"); }); @@ -441,3 +451,30 @@ fn unsupported_approvals_refuse_without_consuming_other_answers() { assert!(h.events.lock().unwrap().is_empty()); assert_eq!(h.confirmer.confirm_write(&a_write()), Decision::Approve); } + +#[test] +fn vetted_content_never_approves_itself_or_consumes_another_kind_of_reply() { + use bravebot_agent::confirm::VetRequest; + use bravebot_core::vetting::Verdict; + for verdict in [Verdict::Safe, Verdict::Unsafe, Verdict::Inconclusive("offline")] { + let mut h = harness(); + h.running.answers.send(Reply::Write(Decision::Approve)).unwrap(); + assert_eq!(h.confirmer.confirm_vetted_read(&VetRequest { + origin: "untrusted.txt".into(), expects: "data".into(), + content: "untrusted content".into(), verdict, reason: None, + }), Decision::Reject); + assert!(h.running.pending.lock().unwrap().is_none()); + } +} + +#[test] +fn vetted_content_requires_its_own_explicit_approval() { + use bravebot_agent::confirm::VetRequest; + let mut h = harness(); + h.running.answers.send(Reply::Vet(Decision::Approve)).unwrap(); + assert_eq!(h.confirmer.confirm_vetted_read(&VetRequest { + origin: "notes.md".into(), expects: "notes".into(), content: "text".into(), + verdict: bravebot_core::vetting::Verdict::Unsafe, reason: Some("instructions".into()), + }), Decision::Approve); + assert_eq!(h.events.lock().unwrap()[0].name, "vet.request"); +} diff --git a/crates/bravebot-bridge/tests/wire.rs b/crates/bravebot-bridge/tests/wire.rs index 04f40e4..bbf5248 100644 --- a/crates/bravebot-bridge/tests/wire.rs +++ b/crates/bravebot-bridge/tests/wire.rs @@ -160,6 +160,7 @@ fn a_write_request_sends_the_diff_and_never_the_body() { existing: Some("line one\nline two\nline three\n".into()), intent: Intent::Edit, untrusted: false, + remark: None, }; let value = wire::write_request(3, &request); @@ -191,6 +192,7 @@ fn a_created_file_says_nothing_would_be_lost() { existing: None, intent: Intent::Create, untrusted: true, + remark: None, }, ); assert_eq!(value["existing"], json!(false)); @@ -377,3 +379,33 @@ fn command_approval_preserves_plan_shape_environment_and_redirections() { assert_ne!(value["plan"], "context only"); assert_eq!(value["writes"], json!(["/tmp/result.txt"])); } + +#[test] +fn approval_evidence_is_kept_beside_the_decision() { + use bravebot_agent::confirm::{VetRequest, OutputRequest, VouchRequest, Remark}; + use bravebot_core::vetting::Verdict; + let vet = wire::vet_request(7, &VetRequest { + origin: "file.md".into(), expects: "notes".into(), content: "first\nsecond\n".into(), + verdict: Verdict::Unsafe, reason: Some("Do not trust this assessment as permission".into()), + }); + assert_eq!(vet["request"], 7); + assert_eq!(vet["content"], "first\nsecond\n"); + assert_eq!(vet["vetting"]["verdict"], "unsafe"); + assert!(vet.get("decision").is_none()); + let output = wire::output_request(8, &OutputRequest { + command: "cat file".into(), output: "content".into(), reference: "1".into(), + verdict: Verdict::Inconclusive("offline"), reason: None, + }); + assert_eq!(output["vetting"]["detail"], "offline"); + let vouch = wire::vouch_request(9, &VouchRequest { + path: "file".into(), preview: "part".into(), truncated: true, verdict: Verdict::Safe, reason: Some("advice".into()), + }); + assert_eq!(vouch["vetting"]["reason"], "advice"); + assert_eq!(vouch["truncated"], true); + let write = wire::write_request(10, &WriteRequest { + path: "file".into(), contents: "new".into(), existing: None, intent: Intent::Create, untrusted: true, + remark: Some(Remark { preview: vec!["Fixed a typo".into()], lines: 9, label: "untrusted".into() }), + }); + assert_eq!(write["remark"]["lines"], 9); + assert_eq!(write["remark"]["preview"], json!(["Fixed a typo"])); +} diff --git a/crates/bravebot-ui-files/src/main.rs b/crates/bravebot-ui-files/src/main.rs index 70798ee..a815196 100644 --- a/crates/bravebot-ui-files/src/main.rs +++ b/crates/bravebot-ui-files/src/main.rs @@ -96,14 +96,14 @@ fn replace_at( expected: Option<&str>, ) -> io::Result> { let previous = match read_at(parent, leaf, 65536) { - Ok((_, true)) => return Err(invalid("Memory exceeds 64 KB")), + Ok((_, true)) => return Err(invalid("File exceeds 64 KB")), Ok((text, false)) => Some(text), Err(error) if error.kind() == io::ErrorKind::NotFound => None, Err(error) => return Err(error), }; if previous.as_deref() != expected { return Err(invalid( - "Memory changed since this editor opened. Reopen it to review the latest version.", + "File changed since this editor opened. Reopen it to review the latest version.", )); } // O_EXCL prevents a pre-existing file or link from becoming our temporary file. @@ -139,6 +139,22 @@ fn handle(request: Request) -> io::Result { let (text, truncated) = read_at(&parent, &leaf, limit)?; Ok(json!({"text": text, "truncated": truncated})) } + "hooks.read" | "hooks.replace" => { + if request.path != "hooks.json" { return Err(invalid("Only the hooks file is allowed")); } + let (parent, leaf) = parent_directory(&request.root, "hooks.json", false)?; + if request.operation == "hooks.read" { + return match read_at(&parent, &leaf, 65536) { + Ok((_, true)) => Err(invalid("Hooks exceed 64 KB")), + Ok((text, false)) => Ok(json!({"text": text})), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(json!({"text": null})), + Err(error) => Err(error), + }; + } + let text = request.text.ok_or_else(|| invalid("Missing hooks"))?; + if text.len() > 65536 || text.contains('\0') { return Err(invalid("Hooks must be text under 64 KB")); } + let previous = replace_at(&parent, &leaf, &text, request.expected.as_deref())?; + Ok(json!({"previous": previous})) + } "replace" => { // This channel writes only bot memory, never an arbitrary project file. let parts = components(Path::new(&request.path))?; @@ -323,3 +339,31 @@ mod tests { ); } } + +#[cfg(test)] +mod hooks_tests { + use super::*; + use std::fs; + #[test] + fn hooks_channel_only_replaces_its_fixed_file_and_preserves_concurrent_edits() { + let mut builder = tempfile::Builder::new(); + builder.prefix("bravebot-hook-helper-"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o700)); + } + let directory = builder.tempdir().unwrap(); + // Normalize the system temp alias before the helper's no-follow traversal. + let root = fs::canonicalize(directory.path()).unwrap(); + let call = |operation: &str, path: &str, text: Option<&str>, expected: Option<&str>| handle(Request { + root: root.display().to_string(), path: path.into(), operation: operation.into(), + limit: None, text: text.map(str::to_string), expected: expected.map(str::to_string), + }); + assert!(call("hooks.read", "hooks.json", None, None).unwrap()["text"].is_null()); + assert!(call("hooks.replace", "other.json", Some("{}"), None).is_err()); + assert!(call("hooks.replace", "hooks.json", Some("first"), None).is_ok()); + assert!(call("hooks.replace", "hooks.json", Some("overwrite"), None).is_err()); + assert_eq!(fs::read_to_string(root.join("hooks.json")).unwrap(), "first"); + } +} diff --git a/docs/interface.md b/docs/interface.md index 9247c9b..cc307b4 100644 --- a/docs/interface.md +++ b/docs/interface.md @@ -561,3 +561,36 @@ a palette written for one is recognisable in the other and `nord` means the same is a port and not a link: nothing here reads anything the agent owns. The agent is a subprocess this window drives, not something it is installed alongside, and a window that could not paint itself until the terminal had been run once would be depending on something it was never promised. + + +## Agent 0.9 controls + +**Agent settings** in the sidebar opens Connection, Hooks and Run settings. Connection +shows the bundled agent build, model services, certificate/proxy details and administrator +pins, with setup instructions for gateways, AWS Bedrock and Brave. Secrets are not shown. +Run settings selects a JSON model/connection override for this app run, lists loaded files +in precedence order, and provides Clear override. Existing turns retain their configuration; +future turns and model discovery use the selected override. Terminal-only preferences and +settings-file permission grants do not replace the desktop's approval controls. + +Hooks are shared with the terminal client. Add a lifecycle event, a program and separate +arguments, optionally limiting a tool-completion hook to a tool name. Save applies changes +to future turns. Reload resolves external-edit conflicts; malformed or unsupported existing +files are reported rather than silently rewritten. Hook failures appear in turn notices. + +**Watches** in the conversation toolbar lists up to eight live file watches, with their +remaining lifetime and Stop controls. Add a project file or ask the agent to watch one. +A change can start a model turn, so the dialog states that it may spend credits. Automatic +turns have their own transcript marker and retain the ordinary approval rules. Watches run +only while the conversation remains open, expire after seven days, and stop when the +conversation or app closes. Stopping an automatic turn also stops its originating watch. + +Approval cards now show checker advice for quarantined content. A one-time read approval +shows the complete content and grants no standing trust. The checker has already received +the content at the backend; its verdict is advice, never permission. Write approvals show +processor remarks directly above the diff, labelled untrusted, with any omitted-line count. + +The context line reports an unmeasured, measured or unavailable last-request size and +whether earlier messages were summarised. This is distinct from total billed usage. +Turn errors use stable categories with specific recovery guidance. Cancellation remains a +separate outcome, and request-attempt counts and HTTP status appear only when known. diff --git a/docs/phase-0-rpc-protocol.md b/docs/phase-0-rpc-protocol.md index ecdfe04..9d76c1e 100644 --- a/docs/phase-0-rpc-protocol.md +++ b/docs/phase-0-rpc-protocol.md @@ -159,7 +159,7 @@ Honest limits. Two things could eventually want an upstream change, and neither - **Structured `doctor` output.** The checks live in `crates/cli/src/main.rs`, a binary, so they cannot be called as a library. v1 shells out to `bravebot doctor` and shows its text (§7.3). A small upstream extraction would be nicer and is optional. -- **New approval types.** Command approval is implemented. The v0.8.0 fetch-host, +- **New approval types.** Command approval is implemented. The v0.9.0 fetch-host, language-server and manifest-plan requests are currently refused; adding UI support requires adapting the bridge, not editing upstream. @@ -981,3 +981,34 @@ Still open: Streaming is nicer for the right-hand column but means the client holds a trail the disk does not have yet, and they will differ if the turn dies. Streaming plus a reload on `turn.done` is the suggestion; it is not free. + + +## 0.9 desktop extensions + +- `vet.request` carries `request`, `origin`, `expects`, full `content`, `lines` and + `vetting: { verdict, reason, detail }`. `vet.reply` carries the session, request and + explicit decision. Its kind is distinct from output and path-vouch replies. +- `output.request` and `vouch.request` include `vetting`. `confirm.request` includes an + optional `remark: { preview, lines, label }`. None is interpreted as an approval. +- `watches.list/add/stop` operate on an open session. Add names a project-relative file; + stop names a number or `all: true`. Listings include remaining lifetime and state. + Main-process `watches.poll` advances the upstream watch clock and starts eligible turns. + `watch.fired` names the number/path; `watch.ended` names the number/reason. Both are + session-scoped. Watch prompts do not enter typed-prompt recall or title a conversation. +- `settings.inspect` optionally takes a session and reports the linked agent's effective + service configuration, file layers, managed keys and network transport, without credentials. + `settings.select` is main-process-only and selects/clears a validated file for future turns. + The native `bravebot:settings:select` picker grants the path; renderer requests cannot set it. + Model discovery uses the same override and the session's registered project directory. + `bravebot-rpc --settings ` restores the override on process restart. +- `doctor` no longer runs an external CLI. It returns `found: true`, `structured: true` + and the linked agent's configuration report as formatted `text` for existing consumers. +- Open/fork responses and completion/error events include `contextTokens`, the last + request's measured size (zero means unmeasured), separately from accumulated usage. + The desktop category `model-unconfigured` identifies a selected Brave model without + Brave configuration when another gateway or Bedrock service is configured; select + a model from that service instead of replacing its credential. + Error events include stable `category`, optional `status` and `attempts`; raw backend + diagnostic text is not sent as a turn error. +- `bravebot:hooks:read/save` are main-process IPC endpoints, not arbitrary RPC methods. + A save takes the edited JSON and the previously read text (null for an absent file). diff --git a/docs/security.md b/docs/security.md index 8aeac85..7f950c1 100644 --- a/docs/security.md +++ b/docs/security.md @@ -42,10 +42,30 @@ shutdown also refuse outstanding questions. There is no timeout that grants appr These properties depend on both bridge refusal handling and Electron lifetime handling; they are covered by the Rust refusal suites and Electron tests in [testing](testing.md). -The v0.8.0 agent also has fetch-host, language-server and manifest-plan approvals. +The v0.9.0 agent also has fetch-host, language-server and manifest-plan approvals. The UI does not present those requests yet; the bridge refuses them without taking an answer intended for another pending question. +Vetted-content approval releases only the displayed bytes once; it does not create a trust +rule for future reads. Checker verdicts are advisory. Checking already sends the content +to the backend before the approval; approving admits it to the planner. Processor remarks +are labelled untrusted and displayed beside the write diff. Neither kind of advice grants +authority. Cancellation invalidates pending vetted approvals as it does other requests. + +Watch prompts contain only the watch number and the path chosen when it was armed, never +file contents. Watches reuse upstream's eight-file limit, seven-day expiry and cooldown, +and automatic turns retain the normal trust and approval gates. Closing a session drops +its watches; cancelling an automatic turn stops the watch that started it. + +Hooks are the user's own commands in the agent home, shared with the CLI. They are edited +through a dedicated IPC API and saved with the descriptor-relative secure file helper, +which accepts only `hooks.json` for this operation. Saves check the previously read text, +refuse symlinks, and atomically replace the file. Hook commands use argument arrays; +no shell is added. Configuration diagnostics return credential presence, never tokens. +Settings overrides can only be selected through the native picker, and administrator +pins retain upstream precedence. Overrides configure model services; they do not enable +settings-file permission grants in this UI. + Command-output content is released for display so the person deciding can read it. Only the agent's approved path admits it to the planner. Confined material is labelled in the UI; showing it is not evidence that the planner read it. Not every write needs diff --git a/docs/setup.md b/docs/setup.md index 1345fcf..83dcaca 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -114,7 +114,7 @@ npm ci ``` `vendor/bravebot` points to [brave/bravebot](https://github.com/brave/bravebot), -currently at v0.8.0 (`3259f8b`). A URL update alone does not change that revision. +currently at v0.9.0 (`c23b2ed`). A URL update alone does not change that revision. `npm run bridge` warns if the checked-out submodule differs from the pin. ### Intentionally updating the pin diff --git a/docs/testing.md b/docs/testing.md index 2578829..f61c9be 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -2,17 +2,28 @@ The gates a change has to pass, and the drivers that prove the window works. Setup is in the [README](../README.md). -## Backend v0.8.0 compatibility +## Backend v0.9.0 compatibility -The submodule pins `3259f8b`, the upstream `v0.8.0` release. +The submodule pins `c23b2ed`, the upstream `v0.9.0` release. The bridge uses policy-audited model-list decoding and Bedrock's per-model names and context windows. Trust maps are rooted in the session project. Resuming a terminal session preserves its saved side conversations and rewind checkpoints. The UI does not yet present fetch-host, language-server, or manifest-plan approvals; those new requests are refused without consuming another pending approval. +Vetted reads now have one-time approval cards, existing output/path approvals include checker +advice, and write approvals show the processor's remark beside the diff. + ## Current regression checks +- `npm run drive:manual-walkthrough`: the manual 0.9 verification through the real app + and backend, with a local model fixture. Runs in CI; detailed coverage is below. +- After building, `node scripts/drive-agent-settings.mjs`: 0.9 settings, hook forms and + conflicts, watch controls, approval evidence, background cancellation, context/failure + states, focus restoration and narrow layouts. Uses deterministic IPC fixtures. +- After building, `node scripts/drive-agent-rpc.mjs`: an actual automatic watch turn against + a local fake gateway, real lifecycle hook subprocesses, context measurements and stop/close. + Uses an isolated agent home; no paid inference or real credentials. - `npm run build`: bridge and secure-file helper builds, TypeScript, and Electron bundles. - After building, `node --test scripts/*.test.mjs`: renderer state, models, file access, memory retention, avatar motion and traits. File tests use the actual secure-file helper. @@ -100,6 +111,46 @@ the file: the other keys are somebody's arrangement of this window. palettes into `themes/` beside it, so it removes the ones it wrote on the way out however it exits, and removes the directory too if it was the one that made it. +## Automated 0.9 manual walkthrough + +Run `npm run drive:manual-walkthrough` to build and exercise the manual verification +steps through the real Electron app, preload, main process, Rust bridge, file helper, +watch poller, and hook subprocesses. It uses a disposable HOME, app profile and project; +it neither reads your credentials nor changes your hooks. A local HTTP model fixture +returns scripted planner tool calls, checker verdicts, and processor output. No paid +model requests are made. + +The driver asserts: + +1. Actual agent diagnostics and refresh; valid/invalid run overrides and clearing; + arrow/Home/End tab navigation, Tab/Shift+Tab containment, Escape and restored focus. +2. A fake API key loaded from `provider.local.options.apiKey`, wrong-backend diagnosis + when the Brave default is selected, recovery through the model picker, measured + context, and cancellation of an in-flight model request. The gateway asserts the + expected Authorization header; no real credentials are used. +3. A hook saved through the UI executes; removing it through the UI prevents later execution. +4. Missing-file errors, an actual file change triggering an automatic turn without + leaking file bytes, individual watch stop, stop-all, and no turn after a stopped watch changes. +5. Standing-trust refusal followed by vetted-read rejection/approval, content isolation + at the planner boundary, no standing grant in fresh sessions, background-session + routing and cancellation of a pending approval. +6. Real isolated processor output and remarks, a rejected write leaving the file + unchanged, and an approved write producing exactly the expected file contents. +7. Narrow settings/watch/approval layouts with reachable decision controls and cleanup. + The Agent settings button stays within both sidebar tabs at the default, minimum + and maximum panel widths (250, 200 and 400 pixels). + +The native file-picker **result** is supplied by the test; the actual selection handler, +JSON validation and configuration loading run normally. OS dialog appearance, real +provider credentials/availability and live-model tool selection remain manual checks. +The existing `drive:agent-settings` driver separately covers fixture-only error and +checker states such as unsafe/inconclusive verdicts and summarised context. + +On failure, the walkthrough prints the current UI and fixture errors and writes +`/tmp/bravebot-walkthrough-failure.png`. It closes the app/server and removes its +isolated files on exit. On Linux it needs a display; use +`xvfb-run -a node scripts/drive-manual-walkthrough.mjs` after building for a headless run. + ## What CI runs `.github/workflows/ci.yml` is the gate on a pull request, and it is not the same set as the @@ -110,15 +161,16 @@ table above. Two jobs: `npm run typecheck`. - **Lint and test the bridge** — one checkout with submodules, so it compiles the same agent revision the gitlink pins, then `cargo clippy --all-targets --all-features -- -D warnings` - and `cargo test --all`. + and `cargo test --all`, followed by the desktop build, Node regression tests, and + the real manual walkthrough under Xvfb with a local model fixture. -The workflow does not run the Node regression tests, Electron drivers, packaged-app -checks, or the upstream agent's full test suite. Run the applicable local checks above. +The workflow does not run the other Electron drivers, packaged-app checks, or the +upstream agent's full test suite. Run the applicable local checks above. So Clippy *is* a lint step, on the Rust side; there is none on the TypeScript side, where `tsc` is the whole gate. `cargo fmt --all -- --check` is deliberately absent because the bridge is not rustfmt-clean; introducing that gate requires a separate formatting change. The reasoning for each of these lives in comments in the workflow itself. -No `drive:*` driver runs in CI: they want a macOS runner and a display, and eight of the live checks spend -tokens. +The manual walkthrough runs in CI without credentials. Drivers that require a live +provider or a packaged app remain local checks. diff --git a/docs/v0.9.0-implementation.md b/docs/v0.9.0-implementation.md new file mode 100644 index 0000000..a338838 --- /dev/null +++ b/docs/v0.9.0-implementation.md @@ -0,0 +1,47 @@ +# Desktop support for bravebot 0.9.0 + +## Plan and interaction design + +1. Complete approval cards. Put checker status and explanation beside existing output/path approvals. Add a separate one-time content approval showing source, expected contents and the complete content. Explain that checking already sent bytes to the backend, while approval releases them to the planner; never infer approval from a verdict. Show processor remarks above write diffs with an untrusted label and omitted-line count. Preserve cancellation, background-session routing and request-kind matching. +2. Add a Watches dialog to each conversation. Show path, state and expiry, an add-file form, Stop per watch and Stop all. Watches exist only while the conversation is open in this app; closing the app stops them. Reuse upstream watch policy and polling, cap at eight/seven days, defer automatic turns while busy and identify their source in the transcript. Cancellation stops automatic continuation. Do not ingest file contents into a generated prompt. +3. Add an Agent settings dialog accessible without a conversation. Its sections are Connection, Hooks and Run settings. Connection reports the bundled agent's configuration, setup routes, network environment and administrator-managed values without exposing credentials. Hooks use explicit program/argument fields, lifecycle selection and optional tool filtering, with validation and an explicit Save action. Existing hook failures remain visible as turn notices. Run settings selects a native JSON file, shows the selected path and precedence, and applies to future turns/model discovery without editing source files. +4. Improve turn status. Use stable failure categories with actionable descriptions and preserve cancellation as its own outcome. Show context as not measured, measured or unavailable, independent of accumulated billing tokens. +5. Verify incrementally: Rust protocol/refusal/lifecycle/config tests; Node state and configuration tests; TypeScript and build; isolated Electron acceptance covering new controls and background/cancellation behavior. Finish with workspace tests, Clippy, upstream locked suite and existing deterministic Electron checks. + +## Visual design + +Use the existing modal, transcript-card, disclosure and button patterns. Approval evidence stays inline next to the decision. Routine diagnostics and automation management live in labelled dialogs rather than enlarging the transcript toolbar with individual controls. Verdicts use text plus color, never color alone. Failures and loading states are explicit, form labels are associated with controls, Escape closes dialogs and focus returns to the invoking control. Narrow layouts stack forms and allow evidence to scroll without hiding decision controls. + +## Progress + +- Implemented approval evidence and separate vetted-read replies with refusal/cancellation tests. +- Implemented conversation watch management, upstream polling/limits, automatic-turn markers, + expiry and cancellation behavior, plus a real turn against a local deterministic gateway. +- Implemented Agent settings, native run-override selection, session-aware model discovery, + bundled diagnostics and secure, conflict-checked hook editing. +- Implemented stable failure categories, measured context status, responsive layouts and + keyboard/focus behavior. Run overrides affect model/connection configuration; desktop + approval controls remain authoritative rather than importing settings-file permission grants. +- Added a real Electron manual-walkthrough regression using a local model fixture, + including UI-saved hook execution, actual watch polling, one-time approval isolation, + processor writes, and keyboard/narrow-layout checks. CI now runs it under Xvfb. +- Verified: build/TypeScript, 110 workspace tests, Clippy, 36 Node tests, 4,277 upstream tests + (two ignored), and eight deterministic integration drivers. Visual checks covered approval + evidence and settings at desktop and narrow widths. + +## Verification commands + +```sh +npm run build +node --test scripts/*.test.mjs +cargo test --all +cargo clippy --all-targets --all-features -- -D warnings +cargo test --manifest-path vendor/bravebot/Cargo.toml --target-dir target --all --locked +node scripts/drive-agent-settings.mjs +node scripts/drive-agent-rpc.mjs +node scripts/drive-manual-walkthrough.mjs +``` + +Also run the existing turn-details, UX acceptance, bot-history, models, secure-files and +conversation-workflow drivers. The integration checks use isolated profiles and fixture +services; paid-provider and packaged-app runs are separate deployment checks. diff --git a/package.json b/package.json index c783dca..27f0197 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,10 @@ "drive:packaged": "node scripts/drive-packaged.mjs", "demo": "npm run bridge && electron-vite build && node scripts/demo.mjs", "setup:electron": "node scripts/setup-electron.mjs && node scripts/name-dev-app.mjs", - "prestart": "npm run setup:electron" + "prestart": "npm run setup:electron", + "drive:manual-walkthrough": "npm run build && node scripts/drive-manual-walkthrough.mjs", + "drive:agent-settings": "npm run build && node scripts/drive-agent-settings.mjs", + "drive:agent-rpc": "npm run bridge && node scripts/drive-agent-rpc.mjs" }, "devDependencies": { "@electron/packager": "^20.3.0", diff --git a/scripts/agent-settings.test.mjs b/scripts/agent-settings.test.mjs new file mode 100644 index 0000000..d038ace --- /dev/null +++ b/scripts/agent-settings.test.mjs @@ -0,0 +1,73 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { buildSync } from 'esbuild' +import { createRequire } from 'node:module' +import { mkdtempSync, writeFileSync, readFileSync, rmSync, symlinkSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +const require = createRequire(import.meta.url) +function load(path) { + const source = buildSync({ entryPoints: [path], bundle: true, write: false, platform: 'node', format: 'cjs', external: ['electron'] }).outputFiles[0].text + const module = { exports: {} } + new Function('require', 'module', 'exports', source)(id => id === 'electron' ? { app: { getAppPath: () => process.cwd(), isPackaged: false } } : require(id), module, module.exports) + return module.exports +} +const { parseHooks } = load('src/shared/agent-settings.ts') +const { readHooks, saveHooks } = load('src/main/agent-settings.ts') +const t = load('src/renderer/transcript.ts') + +test('hook arguments stay literal and unsupported documents cannot be silently rewritten', () => { + const text = JSON.stringify({ hooks: [{ on: 'tool-finished', tool: 'write_file', run: ['formatter', 'two words', '$(touch nope)', ''] }] }) + assert.deepEqual(parseHooks(text)[0].run, ['formatter', 'two words', '$(touch nope)', '']) + for (const document of [[], { hooks: [{ on: 'other', run: ['x'] }] }, { hooks: [{ on: 'turn-started', run: 'x y' }] }, { hooks: [{ on: 'turn-started', tool: 'write_file', run: ['x'] }] }, { hooks: [], extra: true }]) { + assert.throws(() => parseHooks(JSON.stringify(document))) + } +}) + +test('hook saves are explicit, reject conflicts and refuse symlinks', () => { + const directory = mkdtempSync(join(tmpdir(), 'bravebot-hooks-test-')) + try { + const before = readHooks(directory) + const text = JSON.stringify({ hooks: [{ on: 'turn-finished', run: ['echo', 'literal;argument'] }] }) + const after = saveHooks(directory, text, before.text) + assert.equal(after.text, text) + assert.throws(() => saveHooks(directory, '{"hooks":[]}', before.text), /changed on disk/) + assert.equal(readFileSync(after.path, 'utf8'), text) + rmSync(after.path) + const outside = join(directory, 'other.json') + writeFileSync(outside, text) + symlinkSync(outside, after.path) + assert.throws(() => readHooks(directory)) + assert.throws(() => saveHooks(directory, '{"hooks":[]}', text)) + assert.equal(readFileSync(outside, 'utf8'), text) + } finally { rmSync(directory, { recursive: true, force: true }) } +}) + +test('vetted approval requires the same kind and cancellation makes it unanswerable', () => { + const request = { request: 4, origin: 'notes', expects: 'notes', content: '', lines: 1, vetting: { verdict: 'safe' } } + const entries = [t.askedVet(request)] + assert.equal(t.outstanding(entries).kind, 'vet') + assert.equal(t.decide(entries, 'output', 4, 'approve')[0].decision, null) + assert.equal(t.decide(entries, 'vet', 4, 'approve')[0].decision, 'approve') + const cancelled = t.interruptPending(entries) + assert.equal(t.outstanding(cancelled), null) + assert.equal(t.decide(cancelled, 'vet', 4, 'approve')[0].decision, null) + assert.deepEqual(t.conversation(entries), [], 'untrusted evidence is not exported as a conversation message') +}) + +test('watch turns are visibly automatic, including after reopening', () => { + const prompt = 'Watch 3 fired: src/a.ts looks written to since the last look.\n\nNothing has been read. Read the file if you need it.' + const entries = t.fromSaid([{ kind: 'user', text: prompt }]) + assert.equal(entries[0].kind, 'watch') + assert.equal(t.beginTurn(entries, 2)[1].kind, 'turn-start') + assert.deepEqual(t.conversation(entries), []) +}) + +test('stable failure categories do not depend on service wording', () => { + const { failureSummary } = load('src/renderer/failure.ts') + assert.match(failureSummary('transport').description, /proxy and certificate/) + assert.equal(failureSummary('cancelled').title, 'Task stopped') + assert.equal(failureSummary('unauthorized').title, 'Authentication failed') + assert.equal(failureSummary('model-unconfigured').title, 'Choose a model from your configured service') + assert.match(failureSummary('unknown-future-category').title, /could not finish/) +}) diff --git a/scripts/drive-agent-rpc.mjs b/scripts/drive-agent-rpc.mjs new file mode 100644 index 0000000..c13eabd --- /dev/null +++ b/scripts/drive-agent-rpc.mjs @@ -0,0 +1,82 @@ +// Exercise a real watch-triggered turn and hooks against a local deterministic gateway. +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { spawn } from 'node:child_process' +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { createInterface } from 'node:readline' +import { setTimeout as delay } from 'node:timers/promises' +const root = mkdtempSync(join(tmpdir(), 'bravebot-rpc-09-')) +const home = join(root, 'home'), project = join(root, 'project') +mkdirSync(join(home, '.bravebot'), { recursive: true }); mkdirSync(project) +const requests = [], messages = [], pending = new Map() +let child, id = 0 +const server = createServer(async (request, response) => { + let body = '' + for await (const chunk of request) body += chunk + requests.push({ url: request.url, headers: request.headers, body: JSON.parse(body) }) + response.writeHead(200, { 'Content-Type': 'text/event-stream' }) + response.end(`data: ${JSON.stringify({ model: 'test', choices: [{ index: 0, delta: { content: 'The watch fired. No file content was read.' }, finish_reason: 'stop' }], usage: { prompt_tokens: 12, completion_tokens: 9, total_tokens: 21 } })}\n\ndata: [DONE]\n\n`) +}) +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) +const call = (method, params = {}) => new Promise((resolve, reject) => { + const key = ++id + const timer = setTimeout(() => { pending.delete(key); reject(new Error(`${method} timed out`)) }, 15000) + pending.set(key, { resolve: value => { clearTimeout(timer); resolve(value) }, reject: error => { clearTimeout(timer); reject(error) } }) + child.stdin.write(JSON.stringify({ id: key, method, params }) + '\n') +}) +async function until(predicate, label) { + const deadline = Date.now() + 20000 + while (!predicate()) { if (Date.now() > deadline) throw new Error(`${label} timed out: ${JSON.stringify(messages.slice(-4))}`); await delay(50) } +} +try { + const override = join(root, 'settings.json') + writeFileSync(override, JSON.stringify({ provider: { local: { options: { baseURL: `http://127.0.0.1:${server.address().port}/v1` }, models: { test: {} } } }, model: 'local/test' })) + const hookLog = join(root, 'hooks.log') + const hookScript = join(root, 'hook.cjs') + writeFileSync(hookScript, 'require("node:fs").appendFileSync(process.argv[2], process.argv[3] + "\\n")') + writeFileSync(join(home, '.bravebot/hooks.json'), JSON.stringify({ hooks: [ + { on: 'turn-started', run: [process.execPath, hookScript, hookLog, 'started'] }, + { on: 'turn-finished', run: [process.execPath, hookScript, hookLog, 'finished'] }, + ] })) + writeFileSync(join(project, 'watched.txt'), 'Original private bytes') + child = spawn(resolve('target/debug/bravebot-rpc'), ['--settings', override], { + cwd: project, env: { PATH: process.env.PATH, HOME: home, NO_PROXY: '127.0.0.1,localhost', BRAVEBOT_DEFAULT_MODEL: 'local/test' }, stdio: ['pipe', 'pipe', 'pipe'], + }) + let stderr = '' + child.stderr.on('data', chunk => { stderr += chunk }) + createInterface({ input: child.stdout }).on('line', line => { + const message = JSON.parse(line) + if (message.id !== undefined) { + const waiter = pending.get(message.id); pending.delete(message.id) + if (message.error) waiter?.reject(new Error(message.error.message)); else waiter?.resolve(message.ok) + } else messages.push(message) + }) + await until(() => messages.some(m => m.event === 'agent.ready'), 'ready') + const { session } = await call('session.new', { directory: project }) + await call('trust.reply', { session, trusted: false }) + await call('watches.add', { session, path: 'watched.txt' }) + writeFileSync(join(project, 'watched.txt'), 'NEVER PLACE THESE PRIVATE BYTES IN THE GENERATED PROMPT') + await delay(5100) + await call('watches.poll') + await until(() => messages.some(m => m.event === 'turn.done' || m.event === 'turn.error'), 'automatic turn') + const done = messages.find(m => m.event === 'turn.done') + assert(done, JSON.stringify(messages.filter(m => m.event === 'turn.error')) + stderr) + assert.equal(done.session, session) + assert.equal(done.data.contextTokens, 12) + assert.equal(requests.length, 1) + assert.equal(requests[0].headers.authorization, undefined) + assert(JSON.stringify(requests[0].body.messages).includes('Watch 1 fired: watched.txt')) + assert(!JSON.stringify(requests).includes('NEVER PLACE THESE PRIVATE BYTES')) + assert.equal(readFileSync(hookLog, 'utf8'), 'started\nfinished\n') + await call('watches.stop', { session, all: true }) + assert.deepEqual((await call('watches.list', { session })).watches, []) + await call('session.close', { session }) + assert(messages.findIndex(m => m.event === 'watch.fired') < messages.findIndex(m => m.event === 'turn.started')) + console.log('PASS: real watch-triggered turn, local gateway without credentials, context measurement, lifecycle hooks, private-content isolation and stop/close') +} finally { + if (child) { child.stdin.end(); child.kill(); await new Promise(resolve => child.once('close', resolve)) } + await new Promise(resolve => server.close(resolve)) + rmSync(root, { recursive: true, force: true }) +} diff --git a/scripts/drive-agent-settings.mjs b/scripts/drive-agent-settings.mjs new file mode 100644 index 0000000..d85c30f --- /dev/null +++ b/scripts/drive-agent-settings.mjs @@ -0,0 +1,143 @@ +// 0.9 desktop acceptance, isolated profile and deterministic agent replies. +import assert from 'node:assert/strict' +import { mkdtempSync, mkdirSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { _electron as electron } from 'playwright-core' +const profile = mkdtempSync(join(tmpdir(), 'bravebot-agent-settings-profile-')) +const directory = mkdtempSync(join(tmpdir(), 'bravebot-agent-settings-project-')) +const output = join(tmpdir(), 'bravebot-agent-settings') +mkdirSync(output, { recursive: true }) +const app = await electron.launch({ args: ['.', ...(process.platform === 'linux' ? ['--ozone-platform=x11'] : []), `--user-data-dir=${profile}`], cwd: process.cwd(), timeout: 40000 }) +let page +try { + page = await app.firstWindow() + await page.setViewportSize({ width: 1350, height: 900 }) + page.setDefaultTimeout(10000) + await page.emulateMedia({ reducedMotion: 'reduce' }) + const errors = [] + page.on('pageerror', e => errors.push(e.message)) + await app.evaluate(({ ipcMain, BrowserWindow }, directory) => { + const report = { build: 'bravebot 0.9.0 fixture', configured: true, problem: null, model: 'local/test', brave: false, bedrock: false, providers: [{ name: 'Local', credential: 'not required' }], selected: null, layers: [], overrides: [], managed: { path: '/etc/bravebot/managed.json', keys: ['provider'] }, network: { roots: ['/test/roots.pem'], problem: null, trustsNothing: false, proxy: 'proxy.example:8080', authenticated: true, unusableProxy: null, noProxy: 'localhost' } } + const state = { report, hooks: { path: '/test/.bravebot/hooks.json', text: '{"hooks":[]}', hooks: [] }, watches: [], replies: [], turns: 0, conflict: false } + const emit = (event, data, session = 's-a') => BrowserWindow.getAllWindows()[0].webContents.send('bravebot:event', { event, data, session }) + globalThis.agentSettingsFixture = { state, emit } + const replace = (name, fn) => { ipcMain.removeHandler(name); ipcMain.handle(name, fn) } + const rows = ['a', 'b'].map(id => ({ id, title: `Agent settings ${id}`, directory, project: 'Fixture', branch: null, updated: 1, bytes: 1 })) + replace('bravebot:request', (_, method, params = {}) => { + if (method === 'agent.info') return { ok: { configured: true, build: report.build } } + if (method === 'session.list') return { ok: { sessions: rows } } + if (method === 'session.open') return { ok: { session: `s-${params.id}`, model: 'local/test', record: { ...rows.find(r => r.id === params.id), turns: 0, tokens: 0 }, said: [], todos: {}, trust: { known: true, rules: [] }, archived: 0, contextTokens: 0 } } + if (method === 'models.list') return { ok: { models: [{ id: 'local/test', name: 'Test model', provider: 'Local', premium: false, contextWindow: 32000 }], defaultModel: 'local/test', warnings: [] } } + if (method === 'settings.inspect') return { ok: report } + if (method === 'watches.add') { state.watches.push({ number: 1, path: params.path, state: 'watching', remainingSeconds: 604800, armedBy: 0 }) } + if (method === 'watches.stop') state.watches = params.all ? [] : state.watches.filter(w => w.number !== params.number) + if (method.startsWith('watches.')) return { ok: { watches: state.watches, busy: false } } + if (method === 'turn.send') { emit('turn.started', { turn: ++state.turns }, params.session); return { ok: { turn: state.turns } } } + if (method.endsWith('.reply')) state.replies.push({ method, params }) + return { ok: {} } + }) + replace('bravebot:settings:select', (_, clear) => { report.selected = clear ? null : '/test/override.json'; report.layers = clear ? [] : [report.selected]; return report }) + replace('bravebot:hooks:read', () => state.hooks) + replace('bravebot:hooks:save', (_, text, expected) => { + if (state.conflict || expected !== state.hooks.text) throw new Error('Hooks changed on disk. Reload before saving.') + state.hooks = { ...state.hooks, text, hooks: JSON.parse(text).hooks }; return state.hooks + }) + replace('bravebot:files:list', () => ({ path: '', rows: [], truncated: false })) + }, directory) + const emit = (event, data, session = 's-a') => app.evaluate((_, args) => globalThis.agentSettingsFixture.emit(args.event, args.data, args.session), { event, data, session }) + const snap = name => page.screenshot({ path: join(output, name + '.png'), scale: 'css' }) + await page.reload() + await page.getByRole('button', { name: 'Agent settings', exact: true }).click() + const dialog = page.getByRole('dialog', { name: 'Agent settings', exact: true }) + await dialog.getByText('Model service configured', { exact: true }).waitFor() + await dialog.getByText('Locked by your administrator: provider', { exact: true }).waitFor() + await dialog.getByText('proxy.example:8080 · authenticated', { exact: true }).waitFor() + await snap('01-connection') + await dialog.getByRole('tab', { name: 'Run settings', exact: true }).click() + await dialog.getByRole('button', { name: 'Choose settings file…' }).click() + await dialog.getByRole('button', { name: 'Clear override' }).waitFor({ state: 'visible' }) + await page.waitForFunction(() => [...document.querySelectorAll('button')].some(b => b.textContent === 'Clear override' && !b.disabled)) + await dialog.getByRole('button', { name: 'Clear override' }).click() + await dialog.getByText('No override selected', { exact: true }).waitFor() + await dialog.getByRole('tab', { name: 'Hooks', exact: true }).click() + await dialog.getByText('No hooks configured.', { exact: true }).waitFor() + await dialog.getByRole('button', { name: 'Add hook', exact: true }).click() + await dialog.getByLabel('Program', { exact: true }).fill('/usr/bin/notify-send') + await dialog.getByRole('button', { name: 'Add argument', exact: true }).click() + await dialog.getByLabel('Argument 1', { exact: true }).fill('Done; $(never execute)') + await dialog.getByRole('button', { name: 'Save hooks', exact: true }).click() + await dialog.getByText('Hooks saved. They apply when the next turn starts.').waitFor() + assert.deepEqual(await app.evaluate(() => globalThis.agentSettingsFixture.state.hooks.hooks[0].run), ['/usr/bin/notify-send', 'Done; $(never execute)']) + await snap('02-hooks') + await app.evaluate(() => { globalThis.agentSettingsFixture.state.conflict = true }) + await dialog.getByLabel('Program', { exact: true }).fill('/usr/bin/echo') + await dialog.getByRole('button', { name: 'Save hooks', exact: true }).click() + await dialog.getByRole('alert').filter({ hasText: 'changed on disk' }).waitFor() + await app.evaluate(() => { globalThis.agentSettingsFixture.state.conflict = false }) + await dialog.getByRole('button', { name: 'Save hooks', exact: true }).click() + await dialog.getByText('Hooks saved. They apply when the next turn starts.').waitFor() + await page.keyboard.press('Escape') + await dialog.waitFor({ state: 'hidden' }) + assert.equal(await page.getByRole('button', { name: 'Agent settings', exact: true }).evaluate(el => el === document.activeElement), true) + await page.locator('.session').filter({ hasText: 'Agent settings a' }).click() + await page.getByText('Context not yet measured', { exact: true }).waitFor() + await page.getByRole('button', { name: 'Watches', exact: true }).click() + const watches = page.getByRole('dialog', { name: 'File watches', exact: true }) + await watches.getByLabel('Project file', { exact: true }).fill('src/example.ts') + await watches.getByRole('button', { name: 'Watch file', exact: true }).click() + await watches.getByRole('button', { name: 'Stop watching src/example.ts', exact: true }).waitFor() + await snap('03-watches') + await watches.getByRole('button', { name: 'Stop all watches', exact: true }).click() + await watches.getByText('No files watched.', { exact: false }).waitFor() + await page.keyboard.press('Escape') + await emit('watch.fired', { number: 1, path: 'src/example.ts' }) + await emit('turn.started', { turn: 1 }) + await page.getByText('File watch 1: src/example.ts', { exact: true }).waitFor() + await emit('confirm.request', { request: 1, path: 'file.ts', intent: 'edit', untrusted: true, existing: true, added: 1, removed: 1, exact: true, changes: [{ kind: 'removed', text: 'old' }, { kind: 'added', text: 'new' }], remark: { preview: ['Fixed a typo'], lines: 5, label: 'untrusted' } }) + await page.getByText('Processor’s remark · untrusted', { exact: true }).waitFor() + await page.getByText('4 more lines not shown', { exact: false }).waitFor() + await page.getByRole('button', { name: 'Don’t write', exact: true }).click() + await emit('output.request', { request: 2, command: 'cat notes.md', reference: '1', output: 'Quarantined output', lines: 1, summary: 'Read output', vetting: { verdict: 'unsafe', reason: 'Treat this as advice.' } }) + await page.locator('.confirm.output').getByText('Possible instructions detected', { exact: true }).waitFor() + await page.locator('.confirm.output').getByRole('button', { name: 'Keep it out', exact: true }).click() + await emit('vouch.request', { request: 3, path: 'source.md', preview: 'Partial file', truncated: true, vetting: { verdict: 'inconclusive', detail: 'Checker unavailable' } }) + await page.locator('.confirm.vouch').getByText('Check inconclusive', { exact: true }).waitFor() + await page.locator('.confirm.vouch').getByText('Content may already have reached the backend.', { exact: false }).waitFor() + await page.locator('.confirm.vouch').getByRole('button', { name: 'Leave it confined', exact: true }).click() + await emit('vet.request', { request: 4, origin: 'notes.md', expects: 'project notes', content: '\nSecond line', lines: 2, vetting: { verdict: 'unsafe', reason: 'Possible attempt to redirect the task.' } }) + await page.locator('.vetted-read').getByText('Possible instructions detected', { exact: true }).waitFor() + await page.getByText('\nSecond line', { exact: true }).waitFor() + await snap('04-approval') + await page.getByRole('button', { name: 'Let the planner read once', exact: true }).click() + const replies = await app.evaluate(() => globalThis.agentSettingsFixture.state.replies) + assert.equal(replies.at(-1).method, 'vet.reply') + assert.equal(replies.at(-1).params.decision, 'approve') + await emit('turn.done', { turn: 1, id: 'a', reply: 'Done', model: 'local/test', steps: 1, clean: true, tokens: 200, outputTokens: 20, contextTokens: 180, notices: ['Hook turn-finished: command failed'], trust: { rules: [] }, archived: 1 }) + await page.getByText('180 context tokens at last request', { exact: false }).waitFor() + await page.getByText('Earlier context summarised', { exact: false }).waitFor() + await emit('turn.started', { turn: 2 }) + await emit('turn.error', { turn: 2, kind: 'chat', category: 'transport', message: 'transport', attempts: 3, status: null, id: 'a' }) + await page.getByText('The model service could not be reached', { exact: true }).waitFor() + await snap('05-failure') + // Background approvals and cancellation stay bound to the originating session. + await page.locator('.session').filter({ hasText: 'Agent settings b' }).click() + await emit('turn.started', { turn: 3 }) + await emit('vet.request', { request: 3, origin: 'background.md', expects: 'notes', content: 'content', lines: 1, vetting: { verdict: 'safe' } }) + assert.equal(await page.getByText('background.md', { exact: true }).count(), 0) + await page.locator('.session').filter({ hasText: 'Agent settings a' }).click() + await page.getByText('background.md', { exact: true }).waitFor() + await emit('turn.error', { turn: 3, kind: 'cancelled', message: 'cancelled', id: 'a' }) + assert.equal(await page.getByRole('button', { name: 'Let the planner read once', exact: true }).count(), 0) + await page.setViewportSize({ width: 560, height: 780 }) + assert(await page.locator('.conversation-toolbar').evaluate(el => el.scrollWidth <= el.clientWidth + 1), 'toolbar fits narrow layout') + // The settings dialog is also accessible from the persistent sidebar on small screens. + if (await page.locator('.app.left-folded').count()) await page.getByRole('button', { name: 'Session list', exact: true }).click() + await page.getByRole('button', { name: 'Agent settings', exact: true }).click() + await dialog.getByText('Model service configured', { exact: true }).waitFor() + assert(await dialog.evaluate(el => el.scrollWidth <= el.clientWidth + 1), 'dialog fits narrow layout') + await snap('06-narrow-settings') + assert.deepEqual(errors, []) + console.log('PASS: connection and managed diagnostics, settings override, hook editing/conflicts, watches, automatic turns, approval evidence, background cancellation, context, stable failures, narrow layout and focus restoration') +} catch (error) { if (page) await page.screenshot({ path: join(output, 'failure.png') }); throw error } +finally { await app.close() } diff --git a/scripts/drive-bot-history.mjs b/scripts/drive-bot-history.mjs index ee28d50..e0f11ac 100644 --- a/scripts/drive-bot-history.mjs +++ b/scripts/drive-bot-history.mjs @@ -2,12 +2,13 @@ // No provider requests or changes to the user's projects. Screenshots accompany assertions. import assert from 'node:assert/strict' import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' import { join } from 'node:path' import { _electron as electron } from 'playwright-core' -const output = process.env.UX_OUTPUT || '/private/tmp/bravebot-bot-history' +const output = process.env.UX_OUTPUT || join(tmpdir(), 'bravebot-bot-history') mkdirSync(output, { recursive: true }) -const profile = mkdtempSync('/private/tmp/bravebot-ux-profile-') -const directory = mkdtempSync('/private/tmp/bravebot-ux-project-') +const profile = mkdtempSync(join(tmpdir(), 'bravebot-ux-profile-')) +const directory = mkdtempSync(join(tmpdir(), 'bravebot-ux-project-')) const idA = '11111111-1111-4111-8111-111111111111', idB = '22222222-2222-4222-8222-222222222222' writeFileSync(join(profile, 'bravebot-ui.json'), JSON.stringify({ bots: [{slug:'review-bot', name:'Review Bot', purpose:'Review a disposable project and remember preferences.', avatar:'review-bot', model:null, directory, session:idA, conversations:[idA,'44444444-4444-4444-8444-444444444444'], archived:0, remembered:0, quiet:0, retired:0, created:1}], recents:[directory] })) mkdirSync(join(directory,'.bravebot-ui/bots'), {recursive:true}) @@ -77,6 +78,9 @@ try { await overview();await page.locator('.bot-conversations button').filter({hasText:'Review the sample project'}).click(); await page.getByText('Review the project and show a code example.',{exact:true}).waitFor(); await snap('03-open-archived-conversation'); + if (!(await page.getByRole('tab',{name:'Files',exact:true}).isVisible())) { + await page.getByRole('button',{name:'Context panel',exact:true}).click(); + } await page.getByRole('tab',{name:'Files',exact:true}).click(); assert.equal(await page.locator('#panel-files .panel-head').count(),0); assert.equal(await page.getByRole('searchbox',{name:'Search project files by name'}).count(),0); diff --git a/scripts/drive-conversation-workflow.mjs b/scripts/drive-conversation-workflow.mjs index cbb164b..8189116 100644 --- a/scripts/drive-conversation-workflow.mjs +++ b/scripts/drive-conversation-workflow.mjs @@ -2,22 +2,23 @@ // No provider requests or changes to the user's projects. Screenshots accompany assertions. import assert from 'node:assert/strict' import { mkdtempSync, mkdirSync, writeFileSync, existsSync } from 'node:fs' +import { tmpdir } from 'node:os' import { join } from 'node:path' import { _electron as electron } from 'playwright-core' -const output = process.env.UX_OUTPUT || '/private/tmp/bravebot-conversation-regression' +const output = process.env.UX_OUTPUT || join(tmpdir(), 'bravebot-conversation-regression') mkdirSync(output, { recursive: true }) -const profile = mkdtempSync('/private/tmp/bravebot-ux-profile-') -const directory = mkdtempSync('/private/tmp/bravebot-ux-project-') +const profile = mkdtempSync(join(tmpdir(), 'bravebot-ux-profile-')) +const directory = mkdtempSync(join(tmpdir(), 'bravebot-ux-project-')) mkdirSync(directory+'-copy') const idA = '11111111-1111-4111-8111-111111111111', idB = '22222222-2222-4222-8222-222222222222' writeFileSync(join(profile, 'bravebot-ui.json'), JSON.stringify({ bots: [{slug:'review-bot', name:'Review Bot', purpose:'Review a disposable project and remember preferences.', avatar:'review-bot', model:null, directory, session:idA, conversations:[idA,idB], archived:0, remembered:0, quiet:0, retired:0, created:1}], recents:[directory] })) mkdirSync(join(directory,'.bravebot-ui/bots'), {recursive:true}) writeFileSync(join(directory,'.bravebot-ui/bots/review-bot.md'), '# Preferences\n\n- Keep reviews concise.\n') -const app = await electron.launch({args:['.',`--user-data-dir=${profile}`],cwd:process.cwd(),timeout:40000}) +const app = await electron.launch({args:['.', '--disable-renderer-backgrounding', '--disable-background-timer-throttling',`--user-data-dir=${profile}`],cwd:process.cwd(),timeout:40000}) let page const originalClipboard = await app.evaluate(({clipboard})=>clipboard.readText()) try { - page = await app.firstWindow(); page.setDefaultTimeout(7000) + page = await app.firstWindow(); await page.setViewportSize({ width: 1350, height: 900 }); page.setDefaultTimeout(7000) const errors=[]; page.on('pageerror',e=>{errors.push(e.message);console.error('RENDERER',e.message)}) await app.evaluate(({ipcMain,BrowserWindow}, {directory,idA,idB})=>{ const rows=[{id:idA,title:'Review the sample project'},{id:idB,title:'Plan the next iteration'}].map(r=>({...r,directory,project:'sample-project',branch:'main',updated:Date.now(),bytes:20})) diff --git a/scripts/drive-manual-walkthrough.mjs b/scripts/drive-manual-walkthrough.mjs new file mode 100644 index 0000000..220ca7f --- /dev/null +++ b/scripts/drive-manual-walkthrough.mjs @@ -0,0 +1,328 @@ +// The manual 0.9 walkthrough through real Electron IPC, Rust bridge and files. +// Only the model server and the OS file-picker result are substituted. +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { setTimeout as delay } from 'node:timers/promises' +import { _electron as electron } from 'playwright-core' + +const root = mkdtempSync(join(tmpdir(), 'bravebot-walkthrough-')) +const home = join(root, 'home'), project = join(root, 'project'), profile = join(root, 'profile') +for (const path of [join(home, '.bravebot'), project, profile]) mkdirSync(path, { recursive: true }) +const original = 'The release colour is blue.\n', changed = 'The release colour is green.\n' +writeFileSync(join(project, 'notes.txt'), original) +writeFileSync(join(project, 'watched.txt'), 'Waiting for changes.\n') +const override = join(root, 'override.json'), malformed = join(root, 'invalid.json') +writeFileSync(override, '{}\n'); writeFileSync(malformed, '{broken') +const hookLog = join(root, 'hook-ran'), hookScript = join(root, 'hook.cjs') +writeFileSync(hookScript, 'require("node:fs").appendFileSync(process.argv[2], "finished\\n")') +const fixtureToken = 'walkthrough-only-fake-token' +const requests = [], failures = [], steps = [] +let app, page, toolId = 0 +const content = text => ({ content: text }) +const tool = (name, args) => ({ tool_calls: [{ index: 0, id: `call_${++toolId}`, type: 'function', function: { name, arguments: JSON.stringify(args) } }] }) +const lastTool = body => body.messages.filter(m => m.role === 'tool').at(-1)?.content ?? '' +const reference = body => { + const ref = lastTool(body).match(/ref:\d+/)?.[0] + assert(ref, `Expected quarantined reference: ${lastTool(body)}`) + return ref +} +const server = createServer(async (req, res) => { + try { + let raw = ''; for await (const chunk of req) raw += chunk + const body = JSON.parse(raw); requests.push(body) + assert.equal(req.headers.authorization, `Bearer ${fixtureToken}`) + const next = steps.shift() + assert(next, `Unexpected model request: ${JSON.stringify(body.messages.slice(-2))}`) + const delta = await next(body) + if (delta === null) { res.writeHead(200, { 'Content-Type': 'text/event-stream' }); res.flushHeaders(); return } + res.writeHead(200, { 'Content-Type': 'text/event-stream' }) + res.end(`data: ${JSON.stringify({ model: 'test', choices: [{ index: 0, delta, finish_reason: delta.tool_calls ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 12, completion_tokens: 9, total_tokens: 21 } })}\n\ndata: [DONE]\n\n`) + } catch (error) { failures.push(String(error)); res.writeHead(500); res.end('Fixture assertion failed') } +}) +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) +function writeFixtureSettings(model) { + writeFileSync(join(home, '.bravebot/settings.json'), JSON.stringify({ provider: { local: { options: { baseURL: `http://127.0.0.1:${server.address().port}/v1`, apiKey: fixtureToken }, models: { test: {} } } }, model })) +} +writeFixtureSettings('local/test') +const env = Object.fromEntries(['PATH', 'DISPLAY', 'XAUTHORITY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS', 'LANG'].filter(k => process.env[k]).map(k => [k, process.env[k]])) +Object.assign(env, { HOME: home, XDG_CONFIG_HOME: join(home, '.config'), NO_PROXY: '127.0.0.1,localhost' }) +async function until(predicate, label) { + const deadline = Date.now() + 20000 + while (!await predicate()) { assert(Date.now() < deadline, `${label} timed out; fixture errors: ${failures}`); await delay(50) } +} +try { + app = await electron.launch({ args: ['.', ...(process.env.CI ? ['--no-sandbox'] : []), ...(process.platform === 'linux' ? ['--ozone-platform=x11'] : []), `--user-data-dir=${profile}`], env, timeout: 40000 }) + page = await app.firstWindow(); page.setDefaultTimeout(15000) + await page.setViewportSize({ width: 1350, height: 900 }) + const uiErrors = []; page.on('pageerror', error => uiErrors.push(error.message)) + await app.evaluate(({ dialog }, project) => { + globalThis.walkthroughPicker = { path: project, calls: [] } + dialog.showOpenDialog = async (_window, options) => { + globalThis.walkthroughPicker.calls.push(options) + return { canceled: false, filePaths: [globalThis.walkthroughPicker.path] } + } + }, project) + await page.evaluate(() => { + window.walkthroughEvents = [] + window.bravebot.onEvent(event => window.walkthroughEvents.push(event)) + }) + const events = () => page.evaluate(() => window.walkthroughEvents) + const completed = async () => (await events()).filter(e => e.event === 'turn.done' || e.event === 'turn.error').length + const send = async prompt => { + const before = await completed() + await page.getByRole('dialog', { name: 'Project trust', exact: true }).waitFor({ state: 'hidden' }) + await page.getByRole('textbox', { name: 'Message the agent' }).fill(prompt) + await page.getByRole('button', { name: 'Send', exact: true }).click() + return before + } + const done = async before => { + await until(async () => await completed() > before, 'turn completion') + assert.deepEqual(failures, []); assert.equal(steps.length, 0, 'all scripted responses consumed') + const terminal = (await events()).filter(e => e.event === 'turn.done' || e.event === 'turn.error').at(-1) + assert.equal(terminal.event, 'turn.done', JSON.stringify(terminal)) + return terminal + } + const settings = page.getByRole('dialog', { name: 'Agent settings', exact: true }) + const openSettings = () => page.getByRole('button', { name: 'Agent settings', exact: true }).click() + const closeSettings = async () => { await page.keyboard.press('Escape'); await settings.waitFor({ state: 'hidden' }) } + const fits = async locator => assert(await locator.evaluate(el => el.scrollWidth <= el.clientWidth + 1), 'content fits its width') + const tabCycle = async dialog => { + const buttons = dialog.locator('button:visible:enabled') + await buttons.last().focus(); await page.keyboard.press('Tab') + assert(await buttons.first().evaluate(el => el === document.activeElement), 'Tab wraps inside dialog') + await page.keyboard.press('Shift+Tab') + assert(await buttons.last().evaluate(el => el === document.activeElement), 'Shift+Tab wraps inside dialog') + } + + // Sidebar children retain their open width during folding; button margins must fit too. + const sidebar = page.locator('#sessions-column') + const settingsButton = sidebar.getByRole('button', { name: 'Agent settings', exact: true }) + await settingsButton.waitFor() + const divider = page.locator('.gutter').first() + for (const [key, presses, expectedWidth] of [['Home', 1, 250], ['Shift+ArrowLeft', 2, 200], ['Shift+ArrowRight', 7, 400]]) { + await divider.focus() + for (let i = 0; i < presses; i++) await page.keyboard.press(key) + await until(async () => Math.abs((await sidebar.boundingBox()).width - expectedWidth) < 1, 'sidebar resized') + for (const tab of ['Sessions', 'Bots']) { + await sidebar.getByRole('button', { name: tab, exact: true }).click() + const panel = await sidebar.boundingBox(), button = await settingsButton.boundingBox() + assert(button.x >= panel.x && button.x + button.width <= panel.x + panel.width, + `Agent settings stays inside ${tab} sidebar at ${expectedWidth}px: ${JSON.stringify({ panel, button })}`) + assert(await settingsButton.evaluate(el => el.scrollWidth <= el.clientWidth), 'settings label fits') + } + } + await sidebar.getByRole('button', { name: 'Sessions', exact: true }).click() + await divider.focus(); await page.keyboard.press('Home') + console.log('PASS: Agent settings button fits both sidebar tabs at default/minimum/maximum widths') + + // 1–2: diagnostics, keyboard navigation, real override validation and clearing. + await openSettings() + await settings.getByText('Model service configured', { exact: true }).waitFor() + assert.match(await settings.innerText(), /0\.9\.0/) + await settings.getByRole('button', { name: 'Refresh diagnostics' }).click() + await settings.getByRole('tab', { name: 'Connection', exact: true }).focus() + for (const [key, name] of [['ArrowRight', 'Hooks'], ['ArrowRight', 'Run settings'], ['ArrowRight', 'Connection'], ['ArrowLeft', 'Run settings'], ['Home', 'Connection'], ['End', 'Run settings']]) { + await page.keyboard.press(key) + const tab = settings.getByRole('tab', { name, exact: true }) + assert.equal(await tab.getAttribute('aria-selected'), 'true') + assert(await tab.evaluate(el => el === document.activeElement)) + } + await app.evaluate((_, path) => { globalThis.walkthroughPicker.path = path }, override) + await settings.getByRole('button', { name: 'Choose settings file…' }).click() + await settings.getByText('Run override selected. Future turns and model discovery use it.', { exact: true }).waitFor() + assert((await settings.innerText()).includes(override)) + await app.evaluate((_, path) => { globalThis.walkthroughPicker.path = path }, malformed) + await settings.getByRole('button', { name: 'Choose settings file…' }).click() + await settings.getByRole('alert').waitFor() + assert((await settings.innerText()).includes(override), 'invalid selection preserves previous override') + await settings.getByRole('button', { name: 'Clear override' }).click() + await settings.getByText('No override selected', { exact: true }).waitFor() + await tabCycle(settings) + await closeSettings() + assert(await page.getByRole('button', { name: 'Agent settings', exact: true }).evaluate(el => el === document.activeElement)) + console.log('PASS: real diagnostics, override selection/validation/clearing, keyboard tabs and focus') + + // Simulate a gateway settings file without a model selection: it retains the Brave default. + writeFixtureSettings('automatic-brave-bot') + await app.evaluate((_, path) => { globalThis.walkthroughPicker.path = path }, project) + await page.getByRole('button', { name: 'Open project', exact: true }).click() + await page.getByRole('button', { name: "Don't trust", exact: true }).click() + await page.getByText('Context not yet measured', { exact: true }).waitFor() + const failedSetup = await send('Reply with manual check ready. Do not use tools.') + await until(async () => await completed() > failedSetup, 'unconfigured selected model') + await page.getByText('Choose a model from your configured service', { exact: true }).waitFor() + assert.equal(requests.length, 0, 'wrong backend must not receive the gateway token') + await page.getByRole('button', { name: /^Choose model:/ }).click() + await page.getByRole('option').filter({ hasText: 'local ·' }).click() + // Set the default for later fresh-session scenarios; the active session is fixed by the UI selection. + writeFixtureSettings('local/test') + steps.push(() => content('manual check ready')) + await done(await send('Reply with manual check ready. Do not use tools.')) + await page.getByText('12 context tokens at last request', { exact: false }).waitFor() + steps.push(() => null) + const beforeCancel = await send('Wait while I test Stop.') + await until(() => steps.length === 0, 'held model request') + await page.getByRole('button', { name: 'Stop', exact: true }).click() + await until(async () => await completed() > beforeCancel, 'cancelled turn') + await page.getByText('Task stopped', { exact: true }).waitFor() + console.log('PASS: file API key, wrong-backend diagnosis and model-picker recovery, context and cancellation') + + // 4: edit hooks in the UI, execute the saved hook, then remove and prove it stays removed. + await openSettings(); await settings.getByRole('tab', { name: 'Hooks', exact: true }).click() + await settings.getByRole('button', { name: 'Add hook', exact: true }).click() + await settings.getByRole('combobox', { name: /^When/ }).selectOption('turn-finished') + await settings.getByLabel('Program', { exact: true }).fill(process.execPath) + for (const [i, arg] of [hookScript, hookLog].entries()) { + await settings.getByRole('button', { name: 'Add argument', exact: true }).click() + await settings.getByLabel(`Argument ${i + 1}`, { exact: true }).fill(arg) + } + await settings.getByRole('button', { name: 'Save hooks', exact: true }).click() + await settings.getByText('Hooks saved. They apply when the next turn starts.').waitFor() + assert.deepEqual(JSON.parse(readFileSync(join(home, '.bravebot/hooks.json'), 'utf8')).hooks[0].run, [process.execPath, hookScript, hookLog]) + await closeSettings() + steps.push(() => content('Hook verification finished.')) + await done(await send('Run the hook verification.')) + assert.equal(readFileSync(hookLog, 'utf8'), 'finished\n') + await openSettings(); await settings.getByRole('tab', { name: 'Hooks', exact: true }).click() + await settings.getByRole('button', { name: 'Remove hook', exact: true }).click() + await settings.getByRole('button', { name: 'Save hooks', exact: true }).click() + await settings.getByText('Hooks saved. They apply when the next turn starts.').waitFor(); await closeSettings() + steps.push(() => content('Hook removed.')) + await done(await send('Check the next turn after removing the hook.')) + assert.equal(readFileSync(hookLog, 'utf8'), 'finished\n') + console.log('PASS: UI-saved hook executes; removed hook no longer executes') + + // 5: actual poller (not a synthetic watch event), missing file, per-watch stop and stop-all. + await page.setViewportSize({ width: 560, height: 780 }) + await page.getByRole('button', { name: 'Watches', exact: true }).click() + const watches = page.getByRole('dialog', { name: 'File watches', exact: true }) + await watches.getByLabel('Project file').fill('missing.txt') + await watches.getByRole('button', { name: 'Watch file', exact: true }).click() + await watches.getByRole('alert').waitFor() + await watches.getByLabel('Project file').fill('watched.txt') + await watches.getByRole('button', { name: 'Watch file', exact: true }).click() + await watches.getByRole('button', { name: 'Stop watching watched.txt', exact: true }).waitFor() + assert.match(await watches.innerText(), /Watching · Expires in/) + await fits(watches); await tabCycle(watches) + await page.keyboard.press('Escape') + const beforeWatch = await completed() + steps.push(body => { assert(JSON.stringify(body).includes('watched.txt')); assert(!JSON.stringify(body).includes('PRIVATE_WATCH_CONTENT')); return content('File watch observed.') }) + writeFileSync(join(project, 'watched.txt'), 'PRIVATE_WATCH_CONTENT changed') + await done(beforeWatch) + await page.getByText(/File watch \d+: watched.txt/).waitFor() + await page.getByRole('button', { name: 'Watches', exact: true }).click() + await watches.getByRole('button', { name: 'Stop watching watched.txt', exact: true }).click() + await watches.getByText('No files watched.', { exact: false }).waitFor() + const requestCount = requests.length + writeFileSync(join(project, 'watched.txt'), 'Another PRIVATE_WATCH_CONTENT change') + await delay(6500) + assert.equal(requests.length, requestCount, 'stopped watch cannot start a turn') + for (const path of ['notes.txt', 'watched.txt']) { + await watches.getByLabel('Project file').fill(path) + await watches.getByRole('button', { name: 'Watch file', exact: true }).click() + await watches.getByRole('button', { name: `Stop watching ${path}`, exact: true }).waitFor() + } + await watches.getByRole('button', { name: 'Stop all watches', exact: true }).click() + await watches.getByText('No files watched.', { exact: false }).waitFor() + await page.keyboard.press('Escape'); await page.setViewportSize({ width: 1350, height: 900 }) + console.log('PASS: real file watch, missing-file error, narrow dialog, stop and stop-all') + + // 6: real quarantined read -> checker -> decision -> planner, across fresh sessions. + const checker = () => content('{"verdict":"safe","reason":"Plain release notes."}') + const leaveConfined = async () => { await page.locator('.confirm.vouch').getByRole('button', { name: 'Leave it confined', exact: true }).click() } + const vetSteps = accepted => [ + () => tool('read_file', { path: 'notes.txt' }), + checker, + body => { assert(!lastTool(body).includes(original.trim())); return tool('vet_content', { ref: reference(body), expects: 'Release notes, to identify the release colour.' }) }, + body => { assert(JSON.stringify(body).includes(original.trim()), 'checker receives content'); return content('{"verdict":"safe","reason":"Plain release notes."}') }, + body => { assert.equal(lastTool(body).includes(original.trim()), accepted, 'only an approved read reaches planner'); return content(accepted ? 'The release colour is blue.' : 'I respected the refusal.') }, + ] + for (const [caseIndex, accepted] of [false, true, false].entries()) { + await page.getByRole('button', { name: /New session$/, exact: false }).click() + await page.getByRole('button', { name: "Don't trust", exact: true }).click() + steps.push(...vetSteps(accepted)) + const before = await send(`Read notes.txt using vet_content. Verification ${caseIndex}: ${accepted ? 'approve' : 'reject'}.`) + await leaveConfined() + const card = page.locator('.vetted-read') + await card.getByText('No instructions detected', { exact: true }).waitFor() + assert((await card.innerText()).includes(original.trim())) + assert((await card.innerText()).includes('Release notes, to identify the release colour.')) + assert((await card.innerText()).includes('Plain release notes.')) + await page.setViewportSize({ width: 560, height: 780 }); await fits(card) + const action = card.getByRole('button', { name: accepted ? 'Let the planner read once' : 'Keep it out', exact: true }) + await action.scrollIntoViewIfNeeded(); await action.click() + const terminal = await done(before) + assert.deepEqual(terminal.data.trust.rules, [], 'one-time approval does not create standing trust') + await page.setViewportSize({ width: 1350, height: 900 }) + } + console.log('PASS: vetted rejection/approval, no standing trust in fresh sessions, narrow approval actions') + + // Pending approvals stay with their session, and a real Stop invalidates the request. + steps.push(...vetSteps(true).slice(0, 4)) + const beforePending = await send('Pending approval routing check for notes.txt.') + await leaveConfined() + await page.locator('.vetted-read').getByRole('button', { name: 'Let the planner read once', exact: true }).waitFor() + const pendingSession = (await events()).filter(e => e.event === 'vet.request').at(-1).session + await page.locator('.session').filter({ hasText: 'Reply with manual check ready.' }).click() + assert.equal(await page.locator('.vetted-read').count(), 0, 'another session must not show pending evidence') + // The active conversation was the last fresh session; find its sidebar row by its handle's persisted id. + const sessionRows = await page.evaluate(async () => (await window.bravebot.request('session.list')).ok.sessions) + const pendingDone = (await events()).filter(e => e.event === 'turn.done' && e.session === pendingSession).at(-1) + const pendingRow = sessionRows.find(row => row.id === pendingDone.data.id) + assert(pendingRow, 'originating session is persisted') + await page.locator('.session').filter({ hasText: pendingRow.title }).last().click() + await page.locator('.vetted-read').getByRole('button', { name: 'Let the planner read once', exact: true }).waitFor() + await page.getByRole('button', { name: 'Stop', exact: true }).click() + await until(async () => await completed() > beforePending, 'pending approval cancellation') + await until(async () => await page.getByRole('button', { name: 'Let the planner read once', exact: true }).count() === 0, 'approval invalidated') + assert.deepEqual(failures, []) + console.log('PASS: real background approval isolation and cancellation') + + // 7: real isolated processor -> write review -> decision, with filesystem assertions. + for (const accepted of [false, true]) { + steps.push( + () => tool('read_file', { path: 'notes.txt' }), + checker, + body => tool('spawn_processor', { reads: [reference(body)], instruction: 'Change blue to green; return the complete document.' }), + body => { assert(JSON.stringify(body).includes(original.trim())); return content(`Changed blue to green.\n===== the document starts here =====\n${changed}`) }, + body => tool('write_file', { path: 'notes.txt', contents_ref: reference(body) }), + () => content(accepted ? 'Approved write finished.' : 'Rejected write finished.'), + ) + const before = await send('Use an isolated processor to change blue to green in notes.txt and propose the write.') + await leaveConfined() + const card = page.locator('.confirm.untrusted').last() + await card.getByText('Processor’s remark · untrusted', { exact: true }).waitFor() + await card.getByText('Changed blue to green.', { exact: true }).waitFor() + assert.equal(readFileSync(join(project, 'notes.txt'), 'utf8'), original, 'no write before approval') + await page.setViewportSize({ width: 560, height: 780 }); await fits(card) + await card.getByRole('button', { name: accepted ? 'Apply this change' : 'Don’t write', exact: true }).click() + await done(before) + assert.equal(readFileSync(join(project, 'notes.txt'), 'utf8'), accepted ? changed : original) + await page.setViewportSize({ width: 1350, height: 900 }) + } + console.log('PASS: processor remarks and real rejected/approved file writes') + + // 8: settings narrow layout and cleanup assertions. + await page.setViewportSize({ width: 560, height: 780 }) + if (await page.locator('.app.left-folded').count()) await page.getByRole('button', { name: 'Session list', exact: true }).click() + await openSettings(); await settings.getByText('Model service configured', { exact: true }).waitFor() + await fits(settings); await tabCycle(settings); await closeSettings() + assert.deepEqual(JSON.parse(readFileSync(join(home, '.bravebot/hooks.json'), 'utf8')).hooks, []) + assert(existsSync(hookLog)); assert.deepEqual(uiErrors, []); assert.deepEqual(failures, []) + const picks = await app.evaluate(() => globalThis.walkthroughPicker.calls) + assert(picks.some(p => p.title === 'Choose run settings' && p.properties.includes('openFile'))) + assert(picks.some(p => p.properties.includes('openDirectory'))) + console.log('PASS: manual walkthrough against real application/backend; no paid model requests') +} catch (error) { + console.error('Fixture failures:', failures) + if (page) { await page.screenshot({ path: join(tmpdir(), 'bravebot-walkthrough-failure.png') }).catch(() => {}); console.error((await page.locator('body').innerText()).slice(-7000)) } + throw error +} finally { + if (app) await app.close() + server.closeAllConnections() + await new Promise(resolve => server.close(resolve)) + rmSync(root, { recursive: true, force: true }) +} diff --git a/scripts/drive-secure-files.mjs b/scripts/drive-secure-files.mjs index 394e541..2170961 100644 --- a/scripts/drive-secure-files.mjs +++ b/scripts/drive-secure-files.mjs @@ -1,10 +1,11 @@ // Real main-process IPC and file helper; isolated profile, no model calls. import assert from 'node:assert/strict' import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, symlinkSync } from 'node:fs' +import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { _electron as electron } from 'playwright-core' -const area = mkdtempSync('/private/tmp/bravebot-secure-files-') +const area = mkdtempSync(join(tmpdir(), 'bravebot-secure-files-')) const profile = join(area, 'profile'), project = join(area, 'project') mkdirSync(profile); mkdirSync(project) writeFileSync(join(project, 'notes.txt'), 'Project-only fixture') diff --git a/scripts/drive-turn-details.mjs b/scripts/drive-turn-details.mjs index b1b460b..ad478d8 100644 --- a/scripts/drive-turn-details.mjs +++ b/scripts/drive-turn-details.mjs @@ -1,16 +1,20 @@ // Isolated Electron acceptance: deterministic events, no provider calls or user records. import assert from 'node:assert/strict' import { mkdtempSync, mkdirSync } from 'node:fs' +import { tmpdir } from 'node:os' import { join } from 'node:path' import { _electron as electron } from 'playwright-core' -const profile = mkdtempSync('/private/tmp/bravebot-turn-details-profile-') -const directory = mkdtempSync('/private/tmp/bravebot-turn-details-project-') -const output = '/private/tmp/bravebot-turn-details' +const profile = mkdtempSync(join(tmpdir(), 'bravebot-turn-details-profile-')) +const directory = mkdtempSync(join(tmpdir(), 'bravebot-turn-details-project-')) +const output = join(tmpdir(), 'bravebot-turn-details') mkdirSync(output, { recursive: true }) -const app = await electron.launch({ args: ['.', `--user-data-dir=${profile}`], cwd: process.cwd(), timeout: 40000 }) +// XWayland keeps animation frames flowing during Playwright's stability checks. +const app = await electron.launch({ args: ['.', ...(process.platform === 'linux' ? ['--ozone-platform=x11'] : []), '--disable-renderer-backgrounding', '--disable-background-timer-throttling', `--user-data-dir=${profile}`], cwd: process.cwd(), timeout: 40000 }) try { const page = await app.firstWindow() + // Tiling compositors may ignore BrowserWindow.setSize; fix the renderer viewport too. + await page.setViewportSize({ width: 1350, height: 900 }) await page.emulateMedia({ reducedMotion: 'reduce' }) page.setDefaultTimeout(8000) const errors = [] diff --git a/scripts/drive-ux-acceptance.mjs b/scripts/drive-ux-acceptance.mjs index 13cac9e..fed6345 100644 --- a/scripts/drive-ux-acceptance.mjs +++ b/scripts/drive-ux-acceptance.mjs @@ -2,22 +2,23 @@ // No provider requests or changes to the user's projects. Screenshots accompany assertions. import assert from 'node:assert/strict' import { mkdtempSync, mkdirSync, writeFileSync, existsSync } from 'node:fs' +import { tmpdir } from 'node:os' import { join } from 'node:path' import { _electron as electron } from 'playwright-core' -const output = process.env.UX_OUTPUT || '/private/tmp/bravebot-ux-final' +const output = process.env.UX_OUTPUT || join(tmpdir(), 'bravebot-ux-final') mkdirSync(output, { recursive: true }) -const profile = mkdtempSync('/private/tmp/bravebot-ux-profile-') -const directory = mkdtempSync('/private/tmp/bravebot-ux-project-') +const profile = mkdtempSync(join(tmpdir(), 'bravebot-ux-profile-')) +const directory = mkdtempSync(join(tmpdir(), 'bravebot-ux-project-')) mkdirSync(directory+'-copy') const idA = '11111111-1111-4111-8111-111111111111', idB = '22222222-2222-4222-8222-222222222222' writeFileSync(join(profile, 'bravebot-ui.json'), JSON.stringify({ bots: [{slug:'review-bot', name:'Review Bot', purpose:'Review a disposable project and remember preferences.', avatar:'review-bot', model:null, directory, session:idA, conversations:[idA,idB], archived:0, remembered:0, quiet:0, retired:0, created:1}], recents:[directory] })) mkdirSync(join(directory,'.bravebot-ui/bots'), {recursive:true}) writeFileSync(join(directory,'.bravebot-ui/bots/review-bot.md'), '# Preferences\n\n- Keep reviews concise.\n') -const app = await electron.launch({args:['.',`--user-data-dir=${profile}`],cwd:process.cwd(),timeout:40000}) +const app = await electron.launch({args:['.', '--disable-renderer-backgrounding', '--disable-background-timer-throttling',`--user-data-dir=${profile}`],cwd:process.cwd(),timeout:40000}) let page const originalClipboard = await app.evaluate(({clipboard})=>clipboard.readText()) try { - page = await app.firstWindow(); page.setDefaultTimeout(7000) + page = await app.firstWindow(); await page.setViewportSize({ width: 1350, height: 900 }); page.setDefaultTimeout(7000) const errors=[]; page.on('pageerror',e=>{errors.push(e.message);console.error('RENDERER',e.message)}) await app.evaluate(({ipcMain,BrowserWindow}, {directory,idA,idB})=>{ const rows=[{id:idA,title:'Review the sample project'},{id:idB,title:'Plan the next iteration'}].map(r=>({...r,directory,project:'sample-project',branch:'main',updated:Date.now(),bytes:20})) @@ -28,6 +29,7 @@ try { replace('bravebot:request',async(_,method,p={})=>{ const ux=globalThis.ux if(method==='agent.info') return {ok:{configured:ux.configured,build:'acceptance fixture',version:'1'}} + if(method==='settings.inspect') return {ok:{build:'acceptance fixture',configured:ux.configured,problem:ux.configured?null:'No model service configured.',model:null,brave:false,bedrock:false,providers:[],selected:null,layers:[],overrides:[],managed:{path:null,keys:[]},network:{roots:[],problem:null,trustsNothing:false,proxy:null,authenticated:false,unusableProxy:null,noProxy:null}}} if(method==='doctor') return {ok:{found:true,text:'Backend not configured. Install a configured build or rebuild with the approved environment.'}} if(method==='session.list') return {ok:{sessions:rows}} if(method==='models.list') return {ok:{defaultModel:'sample/fast',warnings:[],models:[{id:'sample/fast',name:'Fast model',provider:'Sample',premium:false,contextWindow:200000,capabilities:['text','tools','vision']},{id:'sample/deep',name:'Deep model',provider:'Sample',premium:false,contextWindow:100000,capabilities:['text','tools']}]}} @@ -119,9 +121,9 @@ try { await page.getByRole('button',{name:'Edit memory',exact:true}).click();await page.getByRole('textbox',{name:'Edit persistent memory'}).fill('# Saved preference\n\n- Use a blue accent.');await page.getByRole('button',{name:'Save memory'}).click();await page.locator('.memory-readable').getByText('Saved preference',{exact:true}).waitFor();await snap('21-memory-read') await page.getByRole('button',{name:'Raw',exact:true}).click();await snap('22-memory-raw');await page.getByRole('button',{name:'Reset memory…',exact:true}).click();await snap('23-memory-reset');await page.getByRole('button',{name:'Reset saved memory'}).click() await page.getByRole('button',{name:'History',exact:true}).click();await page.locator('.memory-history details').filter({hasText:'Saved preference'}).locator('summary').first().click();await snap('24-memory-history');await page.locator('.memory-history details').filter({hasText:'Saved preference'}).getByRole('button',{name:'Review for restore'}).first().click();await page.getByRole('button',{name:'Save memory'}).click();await page.getByRole('button',{name:'Read',exact:true}).click();await page.locator('.memory-readable').getByText('Saved preference',{exact:true}).waitFor();await snap('25-memory-restored');await page.keyboard.press('Escape') - await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].setSize(950,780));await page.getByRole('button',{name:'Context panel',exact:true}).click();await snap('26-narrow-drawer');await page.getByRole('button',{name:'Close context panel'}).click() + await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].setSize(950,780));await page.setViewportSize({width:950,height:780});await page.getByRole('button',{name:'Context panel',exact:true}).click();await snap('26-narrow-drawer');await page.getByRole('button',{name:'Close context panel'}).click() await page.emulateMedia({colorScheme:'dark',reducedMotion:'reduce'});await page.waitForFunction(()=>matchMedia('(prefers-color-scheme: dark)').matches);await snap('27-dark');await page.emulateMedia({colorScheme:'light',reducedMotion:'reduce'}) - await app.evaluate(({BrowserWindow,nativeTheme})=>{BrowserWindow.getAllWindows()[0].setSize(1280,820);nativeTheme.themeSource='light';globalThis.ux.configured=false}) + await app.evaluate(({BrowserWindow,nativeTheme})=>{BrowserWindow.getAllWindows()[0].setSize(1280,820);nativeTheme.themeSource='light';globalThis.ux.configured=false});await page.setViewportSize({width:1280,height:820}) await page.reload();await page.getByRole('button',{name:'Sessions',exact:true}).click();await page.locator('.session').filter({hasText:'Plan the next iteration'}).click();await page.getByText('Backend setup needed',{exact:true}).waitFor();assert.equal(await composer.inputValue(),'Independent draft.');await snap('35-backend-not-ready');await page.getByRole('button',{name:'Diagnostics',exact:true}).click();await snap('38-diagnostics');await page.keyboard.press('Escape') await page.getByRole('button',{name:'Setup help'}).click();await snap('36-setup-help');await page.keyboard.press('Escape') await app.evaluate(()=>globalThis.ux.configured=true);await page.getByRole('button',{name:'Check again'}).click();await page.getByText('Backend setup needed',{exact:true}).waitFor({state:'hidden'}) diff --git a/src/main/agent-settings.ts b/src/main/agent-settings.ts new file mode 100644 index 0000000..08272f4 --- /dev/null +++ b/src/main/agent-settings.ts @@ -0,0 +1,25 @@ +import { mkdirSync, lstatSync } from 'node:fs' +import { join } from 'node:path' +import { parseHooks, type HooksDocument } from '../shared/agent-settings' +import { readAgentHooks, replaceAgentHooks } from './project-files' + +function homeExists(home: string): boolean { + try { + const stat = lstatSync(home) + if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('The agent state directory must be a real directory.') + return true + } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; throw error } +} +export function readHooks(home: string): HooksDocument { + const text = homeExists(home) ? readAgentHooks(home) : null + return { path: join(home, 'hooks.json'), text, hooks: text === null ? [] : parseHooks(text) } +} +export function saveHooks(home: string, text: string, expected: string | null): HooksDocument { + parseHooks(text) + mkdirSync(home, { recursive: true, mode: 0o700 }) + homeExists(home) + if (readHooks(home).text !== expected) throw new Error('Hooks changed on disk. Reload before saving to avoid overwriting another edit.') + // Pins each directory and atomically replaces the fixed leaf, refusing symlinks and stale text. + replaceAgentHooks(home, text, expected) + return readHooks(home) +} diff --git a/src/main/bridge.ts b/src/main/bridge.ts index b48094c..8f5b6c3 100644 --- a/src/main/bridge.ts +++ b/src/main/bridge.ts @@ -36,7 +36,7 @@ export class Bridge { /** Diagnostics from the agent, kept for a bug report rather than parsed. */ private diagnostics: string[] = [] - constructor(private readonly onEvent: (event: BridgeEvent) => void) {} + constructor(private readonly onEvent: (event: BridgeEvent) => void, private settingsPath: string | null = null) {} /** * Where the binary is. @@ -63,7 +63,7 @@ export class Bridge { ) } - const child = spawn(path, [], { stdio: ['pipe', 'pipe', 'pipe'] }) + const child = spawn(path, this.settingsPath ? ['--settings', this.settingsPath] : [], { stdio: ['pipe', 'pipe', 'pipe'] }) child.stdout.setEncoding('utf8') child.stderr.setEncoding('utf8') @@ -157,6 +157,12 @@ export class Bridge { }) } + async selectSettings(path: string | null): Promise { + const report = await this.request('settings.select', { path }) + this.settingsPath = path + return report + } + /** The agent's own diagnostics, for a bug report. */ stderr(): string { return this.diagnostics.join('') diff --git a/src/main/files.ts b/src/main/files.ts index 8a48c36..b920f64 100644 --- a/src/main/files.ts +++ b/src/main/files.ts @@ -46,6 +46,7 @@ import { * one on disk would be a root nothing is running in. */ const roots = new Map() +export const rootForSession = (handle: string): string | undefined => roots.get(handle) const attachments = new Map>() /** diff --git a/src/main/index.ts b/src/main/index.ts index af5d4e5..f154f35 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -7,6 +7,7 @@ * remote origins, and no navigation. */ +import { readHooks, saveHooks } from './agent-settings' import { app, BrowserWindow, ipcMain, dialog, shell } from 'electron' import { randomUUID } from 'node:crypto' import { newAvatarSeed } from '../shared/avatar' @@ -40,7 +41,7 @@ import { } from './bots' import { isBotModel, isSlug, slugFor, withoutBot, type Bot } from '../shared/bots' import { isSessionId, parseForkResult } from '../shared/forks' -import { forgetRoot, list, noteRoot, open as openInApp, preview, search, chooseAttachments, attachmentPaths } from './files' +import { rootForSession, forgetRoot, list, noteRoot, open as openInApp, preview, search, chooseAttachments, attachmentPaths } from './files' import { isSubpath } from '../shared/files' import { parseExportRequest, @@ -92,20 +93,27 @@ interface BotFailure { let window: BrowserWindow | null = null let bridge: Bridge | null = null // Model discovery uses its own process so a slow listing never blocks live turn replies. +let selectedSettings: string | null = null +let watchClock: ReturnType | null = null +let pollingWatches = false +let modelListingGeneration = 0 +let modelListingDirectory: string | undefined let modelListing: Promise | null = null -function listModels(): Promise { - if (modelListing) return modelListing - const discovery = new Bridge(() => {}) +function listModels(directory?: string): Promise { + if (modelListing && modelListingDirectory === directory) return modelListing + modelListingDirectory = directory + const generation = ++modelListingGeneration + const discovery = new Bridge(() => {}, selectedSettings) let timer: ReturnType modelListing = Promise.race([ - discovery.request('models.list'), + discovery.request('models.list', { directory }), new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Model discovery timed out. Try again.')), 60000) }), ]).finally(() => { clearTimeout(timer) discovery.dispose() - modelListing = null + if (generation === modelListingGeneration) modelListing = null }) return modelListing } @@ -315,7 +323,15 @@ function createWindow(): void { // after, which reads as though the app interrupted rather than followed. window?.webContents.send('bravebot:event', message) after?.() - }) + }, selectedSettings) + + if (watchClock) clearInterval(watchClock) + watchClock = setInterval(() => { + if (!bridge || !window || pollingWatches) return + pollingWatches = true + void bridge.request('watches.poll').catch(() => {}).finally(() => { pollingWatches = false }) + }, 1000) + window.on('closed', () => { if (watchClock) clearInterval(watchClock); watchClock = null }) // Watching the palettes directory, so that editing one is an editing loop rather than a relaunch // each time. Torn down with the window rather than at quit: on macOS the last window can close @@ -375,11 +391,16 @@ const ALLOWED = new Set([ 'run.reply', 'output.reply', 'vouch.reply', + 'vet.reply', 'ask.reply', 'trust.reply', 'permissions.list', 'permissions.revoke', 'doctor', + 'settings.inspect', + 'watches.list', + 'watches.add', + 'watches.stop', ]) /** What the save sheet offers per format. */ @@ -455,7 +476,10 @@ app.whenReady().then(() => { return { error: { code: 'no_bridge', message: 'the agent is not running' } } } try { - const ok = method === 'models.list' ? await listModels() : await bridge.request(method, sanitised(method, params)) + const session = (params as { session?: unknown } | null)?.session + const ok = method === 'models.list' + ? await listModels(rootForSession(typeof session === 'string' ? session : '')) + : await bridge.request(method, sanitised(method, params)) // Opening a session is the other way a project becomes recent, and this handler is // already the choke point that sees it. Reading one field it is forwarding anyway is // a smaller thing than a channel that would let the renderer write the list itself. @@ -752,6 +776,31 @@ app.whenReady().then(() => { // Choosing a project is a native affair: the renderer cannot see the filesystem and // should not be handed a path it invented. + ipcMain.handle('bravebot:settings:select', async (_event, clear: unknown) => { + if (!bridge || !window) throw new Error('The agent is unavailable.') + let path: string | null = null + if (clear !== true) { + const picked = await dialog.showOpenDialog(window, { title: 'Choose run settings', properties: ['openFile'], filters: [{ name: 'JSON settings', extensions: ['json'] }] }) + if (picked.canceled) return null + path = picked.filePaths[0] ?? null + if (!path) return null + } + const report = await bridge.selectSettings(path) + selectedSettings = path + modelListing = null + return report + }) + const agentHome = async () => { + const info = await bridge?.request<{ home: string | null }>('agent.info') + if (!info?.home) throw new Error('The agent state directory is unavailable.') + return info.home + } + ipcMain.handle('bravebot:hooks:read', async () => readHooks(await agentHome())) + ipcMain.handle('bravebot:hooks:save', async (_event, text: unknown, expected: unknown) => { + if (typeof text !== 'string' || (expected !== null && typeof expected !== 'string')) throw new Error('Invalid hooks document.') + return saveHooks(await agentHome(), text, expected) + }) + ipcMain.handle('bravebot:choose-directory', async () => { if (!window) return null const result = await dialog.showOpenDialog(window, { diff --git a/src/main/project-files.ts b/src/main/project-files.ts index 60b0962..dce0d5c 100644 --- a/src/main/project-files.ts +++ b/src/main/project-files.ts @@ -33,3 +33,13 @@ export function replaceProjectMemory(root: string, path: string, text: string, e if (value.previous !== null && typeof value.previous !== 'string') throw new Error('Invalid memory response') return value.previous } + +/** Only the main process supplies the agent home; these operations accept one fixed filename. */ +export function readAgentHooks(home: string): string | null { + const value = request(home, 'hooks.json', { operation: 'hooks.read' }) + if (value.text !== null && typeof value.text !== 'string') throw new Error('Invalid hooks response') + return value.text +} +export function replaceAgentHooks(home: string, text: string, expected: string | null): void { + request(home, 'hooks.json', { operation: 'hooks.replace', text, expected }) +} diff --git a/src/preload/index.ts b/src/preload/index.ts index bc05f91..9e7404a 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -298,6 +298,12 @@ const api = { return ipcRenderer.invoke('bravebot:files:open', session, path) as Promise }, + /** A native picker grants this app run access to a configuration override. */ + selectSettings(clear = false): Promise { + return ipcRenderer.invoke('bravebot:settings:select', clear) + }, + readHooks(): Promise { return ipcRenderer.invoke('bravebot:hooks:read') }, + saveHooks(text: string, expected: string | null): Promise { return ipcRenderer.invoke('bravebot:hooks:save', text, expected) }, /** Ask the user for a project directory, natively. */ chooseDirectory(): Promise { return ipcRenderer.invoke('bravebot:choose-directory') as Promise diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index ea5a76a..af834f5 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -1,3 +1,4 @@ +import { AgentSettings } from './components/AgentSettings' import type { FileAttachment } from '../shared/files' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { @@ -58,6 +59,7 @@ interface Live { quarantine: Shown[] phase: Phase | null tokens: number + contextTokens?: number running: boolean /** Set when a fresh session needs the trust question answered before it can run. */ askingTrust: string | null @@ -134,7 +136,7 @@ function cameFrom( class Unconfigurable extends Error {} /** Which kinds of question a person can be put. */ -export type Asked = 'confirm' | 'run' | 'output' | 'vouch' +export type Asked = 'confirm' | 'run' | 'output' | 'vouch' | 'vet' /** * Which method answers which question. @@ -148,6 +150,7 @@ const METHOD: Record = { run: 'run.reply', output: 'output.reply', vouch: 'vouch.reply', + vet: 'vet.reply', } async function call(method: string, params?: Record): Promise { @@ -184,6 +187,7 @@ async function callBot(request: { } export function App(): React.JSX.Element { + const [agentSettings, setAgentSettings] = useState(false) const [sessions, setSessions] = useState([]) const [live, renderLive] = useState(null) const liveRef = useRef(null) @@ -224,10 +228,10 @@ export function App(): React.JSX.Element { const [backendReady, setBackendReady] = useState(null) const checkBackend = useCallback(async () => { try { - const info = await call<{ configured?: boolean }>('agent.info') + const info = await call<{ configured?: boolean }>('agent.info', { session: live?.handle }) setBackendReady(info.configured ?? null) } catch { setBackendReady(false) } - }, []) + }, [live?.handle]) useEffect(() => { void checkBackend() }, [checkBackend]) const [notice, setNotice] = useState<{ title: string; body: string } | null>(null) const [aboutInfo, setAboutInfo] = useState(null) @@ -489,6 +493,7 @@ export function App(): React.JSX.Element { running: false, // A record with no stored map was written before maps were kept. Nothing // recorded is not the same as nothing trusted, so it is asked about again. + contextTokens: opened.contextTokens, askingTrust: opened.trust.known ? null : opened.record.directory, // Looked up rather than carried: this session may have been forked in another launch // entirely, and the file the main process keeps is where that is written down. @@ -541,6 +546,7 @@ export function App(): React.JSX.Element { phase: null, tokens: 0, running: false, + contextTokens: 0, askingTrust: chosen, forkedFrom: null, focus: null, @@ -1046,6 +1052,7 @@ export function App(): React.JSX.Element { phase: null, tokens: 0, running: false, + contextTokens: forked.contextTokens, askingTrust: forked.trust.known ? null : forked.directory, // A fork is a session and not a bot, even when it was cut out of a bot's. A bot is one // conversation resumed forever; a second one carrying its name would be a second bot @@ -1181,6 +1188,7 @@ export function App(): React.JSX.Element { onRetireBot={retireBot} onRemoveBot={removeBot} build={build} + onSettings={() => setAgentSettings(true)} /> void checkBackend()} onDiagnostics={() => void doctor()} - onSetup={() => setUnconfigured('Backend credentials are not available to this build.')} + onSetup={() => setAgentSettings(true)} storageKey={draftKey} attachments={live?.attachments ?? []} onAttach={() => { @@ -1265,6 +1273,7 @@ export function App(): React.JSX.Element { setNotice(null)} /> )} {unconfigured && setUnconfigured(null)} />} + {agentSettings && setAgentSettings(false)} onChanged={() => { void checkBackend() }} />} {live?.askingTrust && ( )} @@ -1305,6 +1314,10 @@ function apply( if (!old) return old old = { ...old, turns: receiveTurn(old.turns, message) } switch (message.event) { + case 'watch.fired': + return { ...old, entries: [...old.entries, t.watchFired(message.data.number, message.data.path)] } + case 'watch.ended': + return { ...old, entries: [...old.entries, t.narrated(`Watch ${message.data.number} ended: ${message.data.reason}${message.data.message ? `. ${message.data.message}` : ''}`)] } case 'turn.started': return { ...old, running: true, phase: null, tokens: 0, entries: t.beginTurn(old.entries, message.data.turn) } @@ -1336,6 +1349,8 @@ function apply( return { ...old, entries: [...old.entries, t.askedRun(message.data)] } case 'output.request': return { ...old, entries: [...old.entries, t.askedOutput(message.data)] } + case 'vet.request': + return { ...old, entries: [...old.entries, t.askedVet(message.data)] } case 'vouch.request': return { ...old, entries: [...old.entries, t.askedVouch(message.data)] } case 'ask.request': @@ -1348,6 +1363,7 @@ function apply( const compacted = message.data.archived > old.archived return { ...old, + contextTokens: message.data.contextTokens, summary: { ...old.summary, id: message.data.id ?? old.summary.id }, outcome: 'complete', running: message.data.consolidating === true, @@ -1362,10 +1378,11 @@ function apply( const { kind, message: detail } = message.data return { ...old, + contextTokens: message.data.contextTokens, summary: { ...old.summary, id: message.data.id ?? old.summary.id }, running: false, phase: null, - entries: [...t.interruptPending(old.entries), { ...t.errored(`${kind}: ${detail}`), turn: message.data.turn }], + entries: [...t.interruptPending(old.entries), { ...t.errored(`${kind}: ${detail}`), category: kind === 'cancelled' ? 'cancelled' : message.data.category, attempts: message.data.attempts, status: message.data.status, turn: message.data.turn }], queuePaused: true, } } diff --git a/src/renderer/components/AgentSettings.tsx b/src/renderer/components/AgentSettings.tsx new file mode 100644 index 0000000..4f5a1f7 --- /dev/null +++ b/src/renderer/components/AgentSettings.tsx @@ -0,0 +1,110 @@ +import { useEffect, useId, useState } from 'react' +import { Modal } from './Modal' +import type { AgentSettings as Report, Hook, HooksDocument } from '../../shared/agent-settings' +import { parseHooks } from '../../shared/agent-settings' + +export function AgentSettings({ session, onClose, onChanged }: { session?: string; onClose: () => void; onChanged: () => void }): React.JSX.Element { + const id = useId() + const tabs = ['Connection', 'Hooks', 'Run settings'] + const [tab, setTab] = useState('Connection') + const [report, setReport] = useState(null) + const [document, setDocument] = useState(null) + const [hooks, setHooks] = useState([]) + const [problem, setProblem] = useState('') + const [status, setStatus] = useState('') + const [busy, setBusy] = useState(false) + const [dirty, setDirty] = useState(false) + const load = async () => { + setBusy(true); setProblem('') + try { + const result = await window.bravebot.request('settings.inspect', { session }) + if (result.error) throw new Error(result.error.message) + if (result.ok) { + if (!Array.isArray(result.ok.providers) || !Array.isArray(result.ok.layers) || !result.ok.managed || !result.ok.network) throw new Error('This agent did not return configuration details. Rebuild or reinstall the app, then retry.') + setReport(result.ok) + } + } catch (error) { setProblem(String(error)) } finally { setBusy(false) } + } + useEffect(() => { void load() }, [session]) + const loadHooks = async () => { + setBusy(true); setProblem(''); setStatus('') + try { const doc = await window.bravebot.readHooks(); setDocument(doc); setHooks(doc.hooks); setDirty(false) } + catch (error) { setProblem(String(error)) } finally { setBusy(false) } + } + useEffect(() => { if (tab === 'Hooks' && !document) void loadHooks() }, [tab]) + const change = (index: number, hook: Hook) => { setHooks(rows => rows.map((row, i) => i === index ? hook : row)); setDirty(true); setStatus('') } + const save = async () => { + if (!document) return + setBusy(true); setProblem('') + try { + const text = JSON.stringify({ hooks }, null, 2) + '\n' + parseHooks(text) + const saved = await window.bravebot.saveHooks(text, document.text) + setDocument(saved); setHooks(saved.hooks); setDirty(false); setStatus('Hooks saved. They apply when the next turn starts.') + } catch (error) { setProblem(String(error)) } finally { setBusy(false) } + } + const select = async (clear: boolean) => { + setBusy(true); setProblem(''); setStatus('') + try { + const next = await window.bravebot.selectSettings(clear) + if (next) { setReport(next); onChanged(); setStatus(clear ? 'Run override cleared.' : 'Run override selected. Future turns and model discovery use it.'); await load() } + } catch (error) { setProblem(String(error)) } finally { setBusy(false) } + } + const close = () => { if (!dirty || window.confirm('Discard unsaved hook changes?')) onClose() } + return +

Agent settings

Configuration and automation for this app.

+
+ {tabs.map((name, index) => )} +
+ {problem &&

{problem}

{tab !== 'Hooks' && }
} + {status &&

{status}

} + {busy &&

Working…

} +
+ {tab === 'Connection' && report && <> +

{report.configured ? 'Model service configured' : 'Choose a model service'}

+ {report.problem &&

{report.problem}

} +
Agent build
{report.build}
Default model
{report.model ?? 'Not configured'}
+ {report.providers.map((p, i) =>

{p.name} · Credential {p.credential}

)} + {report.brave &&

Brave service enabled

}{report.bedrock &&

AWS Bedrock enabled

} +
+
Set up a model service +

Gateway or local model

Add a provider to your agent settings, or select a file in Run settings. Credential-free local services need no token.

{'{"provider":{"local":{"options":{"baseURL":"http://localhost:11434/v1"},"models":{"your-model":{}}}},"model":"local/your-model"}'}

For authenticated services, name the credential environment variable in the provider’s env array.

+

AWS Bedrock

Configure your AWS credentials and enable Bedrock in your agent settings or environment. Your AWS account must have access to the selected model.

BRAVEBOT_USE_BEDROCK=1{'\n'}AWS_REGION=us-east-1{'\n'}AWS_PROFILE=your-profile{'\n'}ANTHROPIC_DEFAULT_SONNET_MODEL=your-model-id-or-inference-profile-arn
+

Brave service

Use a configured Brave build, or launch from a shell with SERVICES_KEY_AICHAT, BRAVE_SERVICES_KEY_ID and BRAVE_AI_CHAT_ENDPOINT set to your supplied credentials and endpoint. Credentials are not stored in this window.

+
+

Network

Certificate roots
{report.network.roots.length ? report.network.roots.join(', ') : 'Bundled roots'}
Proxy
{report.network.proxy ?? 'No proxy configured'}{report.network.authenticated ? ' · authenticated' : ''}
Proxy bypass
{report.network.noProxy ?? 'None'}
+ {(report.network.problem || report.network.trustsNothing || report.network.unusableProxy) &&

{report.network.problem || (report.network.trustsNothing ? 'No usable trust roots.' : `Unsupported proxy: ${report.network.unusableProxy}`)}

} +

For a custom certificate authority, set SSL_CERT_FILE or SSL_CERT_DIR before opening the app. These replace bundled roots. Proxy and certificate changes require restarting the app.

+
+

Managed configuration

{report.managed.path ? <>

{report.managed.path}

{report.managed.keys.length ? `Locked by your administrator: ${report.managed.keys.join(', ')}` : 'File found; no recognized values are pinned.'}

:

No administrator-managed configuration found.

}

Administrator-pinned destinations take precedence over your settings and environment.

+ + } + {tab === 'Hooks' && <> +

Hooks are shared with the terminal client. Run your own programs at specific moments. These commands run with your account’s permissions in the project directory. They cannot approve or block the agent.

+ {document &&

{document.path}

} + {document && hooks.length === 0 &&

No hooks configured.

} + {hooks.map((hook, index) =>
Hook {index + 1} + + {hook.on === 'tool-finished' && } + + {hook.run.slice(1).map((argument, i) =>
)} +
+
)} +

Arguments are passed exactly as entered; shell syntax is not interpreted. Failed hooks appear in the turn’s notices.

+
+ } + {tab === 'Run settings' && report && <> +

Model and connection override

Choose a JSON settings file for this app run. It applies to future turns and model discovery, and is cleared when the app exits. Running turns keep their configuration. Terminal preferences and settings-file permission grants do not change this app’s approval controls.

+

{report.selected ?? 'No override selected'}

+

Effective configuration

Default model: {report.model ?? 'Not configured'}

+

Files merge in this order: home → project → project-local → selected override. Environment and built-in values can take precedence; administrator-pinned destinations always win.

+

Loaded files, in order

{report.layers.length ?
    {report.layers.map(path =>
  1. {path}
  2. )}
:

No settings files loaded.

} + {report.overrides.map(item =>

{item.name} overridden by {item.path}

)} + {report.managed.keys.length > 0 &&

Managed values: {report.managed.keys.join(', ')}. This override cannot change them.

} + } +
+
+} diff --git a/src/renderer/components/ErrorCard.tsx b/src/renderer/components/ErrorCard.tsx index fa92394..b22fd92 100644 --- a/src/renderer/components/ErrorCard.tsx +++ b/src/renderer/components/ErrorCard.tsx @@ -1,4 +1,6 @@ -export function ErrorCard({ detail, onRetry, onModel }: { +import { failureSummary } from '../failure' +export function ErrorCard({ detail, onRetry, onModel, category, attempts, status }: { + category?: string | null; attempts?: number | null; status?: number | null detail: string; onRetry?: () => void; onModel?: () => void }): React.JSX.Element { const denied = /401|403|unauthoriz|credential/i.test(detail) @@ -12,12 +14,13 @@ export function ErrorCard({ detail, onRetry, onModel }: { : limited ? 'Wait a moment before retrying, or choose another model.' : stopped ? 'Completed changes remain in the project. You can continue from here.' : 'Your conversation is preserved. Review the details, then continue from the current project state.' + const classified = category ? failureSummary(category) : { title, description } return
- {title}

{description}

+ {classified.title}

{classified.description}

{onRetry && } {onModel && }
-
Technical details
{detail}
+
Technical details
{detail}{attempts != null ? `\nRequests attempted: ${attempts}` : ''}{status != null ? `\nHTTP status: ${status}` : ''}
} diff --git a/src/renderer/components/Modal.tsx b/src/renderer/components/Modal.tsx index 3841d53..38552ae 100644 --- a/src/renderer/components/Modal.tsx +++ b/src/renderer/components/Modal.tsx @@ -17,17 +17,20 @@ export function Modal({ title, onClose, children, className = '' }: { const controls = () => [...(root.current?.querySelectorAll('button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select, a[href], [tabindex="0"]') ?? [])].filter((node) => node.getClientRects().length) if (!root.current?.contains(document.activeElement)) (controls()[0] ?? root.current)?.focus() const key = (event: KeyboardEvent) => { + // A saving form may disable its focused button and move focus to body. Keep + // Escape and Tab within the topmost modal even through that transition. + if ([...document.querySelectorAll('[role="dialog"]')].at(-1) !== root.current) return if (event.key === 'Escape' && close.current) { event.preventDefault(); event.stopPropagation(); close.current() } if (event.key !== 'Tab') return const items = controls(), first = items[0], last = items.at(-1) if (!first) { event.preventDefault(); root.current?.focus(); return } + if (!root.current?.contains(document.activeElement)) { event.preventDefault(); first.focus(); return } if (event.shiftKey && (document.activeElement === first || document.activeElement === root.current)) { event.preventDefault(); last?.focus() } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus() } } - root.current?.addEventListener('keydown', key) - const element = root.current + document.addEventListener('keydown', key, true) return () => { - element?.removeEventListener('keydown', key) + document.removeEventListener('keydown', key, true) if (app) app.inert = wasInert if (previous?.isConnected) previous.focus() } diff --git a/src/renderer/components/ModelPicker.tsx b/src/renderer/components/ModelPicker.tsx index be3a0a5..2a4f8cc 100644 --- a/src/renderer/components/ModelPicker.tsx +++ b/src/renderer/components/ModelPicker.tsx @@ -15,9 +15,10 @@ const CAPABILITIES: Record = { 'structured-output': ['Structured', 'Supports structured outputs'], } -export function ModelPicker({ model, disabled, onChoose, scope = 'conversation' }: { +export function ModelPicker({ model, disabled, onChoose, scope = 'conversation', session }: { model: string | null scope?: 'conversation' | 'bot' + session?: string disabled: boolean onChoose: (model: string) => void }): React.JSX.Element { @@ -42,7 +43,7 @@ export function ModelPicker({ model, disabled, onChoose, scope = 'conversation' setLoading(true) setProblem(null) search.current?.focus() - void window.bravebot.request('models.list').then((answer) => { + void window.bravebot.request('models.list', { session }).then((answer) => { if (gone) return if (answer.error) setProblem(answer.error.message) else setCatalogue(answer.ok ?? null) @@ -50,7 +51,7 @@ export function ModelPicker({ model, disabled, onChoose, scope = 'conversation' if (!gone) setProblem('Could not load models. Try again.') }).finally(() => { if (!gone) setLoading(false) }) return () => { gone = true } - }, [open, revision]) + }, [open, revision, session]) useEffect(() => { if (!open) return diff --git a/src/renderer/components/Sidebar.tsx b/src/renderer/components/Sidebar.tsx index 6aa4fe9..d3c5d69 100644 --- a/src/renderer/components/Sidebar.tsx +++ b/src/renderer/components/Sidebar.tsx @@ -46,6 +46,7 @@ interface Props { onSaveBot: (bot: { slug?: string; avatar?: string; model?: string | null; name: string; purpose: string; directory: string }) => Promise onRetireBot: (slug: string, retired: boolean) => void onRemoveBot: (slug: string) => void + onSettings: () => void build: string | null } @@ -64,6 +65,7 @@ export function Sidebar({ onRetireBot, onRemoveBot, build, + onSettings, }: Props): React.JSX.Element { const [tab, setTab] = useState('sessions') const [grouped, setGrouped] = useState(false) @@ -144,6 +146,7 @@ export function Sidebar({ /> + {build && (
{build} diff --git a/src/renderer/components/Transcript.tsx b/src/renderer/components/Transcript.tsx index b40fbb4..8e1b23d 100644 --- a/src/renderer/components/Transcript.tsx +++ b/src/renderer/components/Transcript.tsx @@ -1,3 +1,4 @@ +import { Watches } from './Watches' import type { FileAttachment } from '../../shared/files' import { Permissions } from './Permissions' import { useLayoutEffect, useEffect, useMemo, useRef, useState } from 'react' @@ -30,6 +31,8 @@ interface Live { todos: TodoRow[] quarantine: Shown[] phase: Phase | null + contextTokens?: number + archived?: number tokens: number running: boolean askingTrust: string | null @@ -188,6 +191,7 @@ export function Transcript({ const following = useRef(true) const lastScroll = useRef(0) const scrollSave = useRef | null>(null) + const [watches, setWatches] = useState(false) const [permissions, setPermissions] = useState(false) const [previewPath, setPreviewPath] = useState(null) useEffect(() => { @@ -352,6 +356,7 @@ export function Transcript({ {live &&
+
} {backendReady === false &&
Backend setup neededYou can browse conversations and prepare drafts.
} + {live &&
+ {live.phase === 'compacting' ? 'Summarising context…' : live.contextTokens === undefined ? 'Context measurement unavailable' : live.contextTokens === 0 ? 'Context not yet measured' : `${live.contextTokens.toLocaleString()} context tokens at last request`} + {!!live.archived && · Earlier context summarised} +
} {problem && } {searching &&
- + Enter to send · Shift+Enter for newline {live.running && } @@ -506,6 +515,7 @@ export function Transcript({
+ {watches && setWatches(false)} />} {permissions && setPermissions(false)} />} {previewPath && setPreviewPath(null)} />} @@ -941,8 +951,10 @@ function Row({ // otherwise. See `CONSOLIDATION_MARK`. return
Asked to bring its memory up to date
+ case 'watch': + return
{entry.text}Automatic turn · file contents still follow normal read permissions
case 'error': - return + return case 'replayed-tool': // No outcome, because the record does not keep one. Drawn quietly for the same @@ -1020,6 +1032,10 @@ function Row({ )}

{request.existing ? 'Update an existing project file.' : 'Create a new project file.'} This decision applies to the change shown below.

+ {request.remark &&
Processor’s remark · untrusted +
{request.remark.preview.join('\n')}
+ {request.remark.label}{request.remark.lines > request.remark.preview.length ? ` · ${request.remark.lines - request.remark.preview.length} more lines not shown` : ''}. Review the diff before approving. +
} {decision === null ? ( @@ -1127,6 +1143,7 @@ function Row({ {/* In full, never truncated. The answer to this question rests on the bytes, so a preview would be asking for an approval of what nobody saw. */} +
{request.output}
{decision === null ? ( @@ -1155,6 +1172,20 @@ function Row({ ) } + case 'vet': { + const { request, decision } = entry + return
+
read once{request.origin}{request.lines} lines
+

Expected contents: {request.expects}

+ +

Approval lets the planner read only this content. It does not trust this file for future reads.

+
{request.content}
+ {decision === null ?
+ + +
:
{decision === 'approve' ? 'You allowed this content once' : 'You kept this content out'}
} +
+ } case 'ask': return @@ -1172,6 +1203,7 @@ function Row({ well as this one. Only do it for content you know the origin of.

+
{request.preview}
{request.truncated && (
@@ -1222,6 +1254,8 @@ function waitingOn(kind: t.Asking['kind']): string { return 'Answer the command' case 'output': return 'Answer the output' + case 'vet': + return 'Review the checked content' case 'vouch': return 'Answer the vouch' case 'ask': @@ -1234,3 +1268,14 @@ function landingHint(landing: string): string { ? 'not in the planner’s context; only an isolated processor can be sent to read it' : 'read by nothing: only its name is known' } + +function VettingNotice({ vetting }: { vetting?: import('../../shared/protocol').Vetting }): React.JSX.Element { + const verdict = vetting?.verdict + const label = verdict === 'safe' ? 'No instructions detected' : verdict === 'unsafe' ? 'Possible instructions detected' : 'Check inconclusive' + return
+ {label} + {vetting?.reason &&

{vetting.reason}

} + {vetting?.detail &&

{vetting.detail}

} + {!vetting ? 'No checker assessment was recorded. Review the content before deciding.' : verdict === 'safe' || verdict === 'unsafe' ? 'The checker received this content at the backend before this question. Its assessment can be wrong; you decide whether the planner may read it.' : 'The check did not complete. Content may already have reached the backend. You still decide whether the planner may read it.'} +
+} diff --git a/src/renderer/components/Watches.tsx b/src/renderer/components/Watches.tsx new file mode 100644 index 0000000..c6d3682 --- /dev/null +++ b/src/renderer/components/Watches.tsx @@ -0,0 +1,34 @@ +import { useEffect, useState } from 'react' +import { Modal } from './Modal' +interface Watch { number: number; path: string; remainingSeconds: number; armedBy: number; state: string } +interface Listing { watches: Watch[]; busy: boolean } +export function Watches({ session, onClose }: { session: string; onClose: () => void }): React.JSX.Element { + const [listing, setListing] = useState(null) + const [path, setPath] = useState('') + const [problem, setProblem] = useState('') + const [busy, setBusy] = useState(false) + const [status, setStatus] = useState('') + const request = async (method = 'watches.list', params: Record = {}) => { + if (method !== 'watches.list') { setBusy(true); setProblem('') } + try { + const response = await window.bravebot.request(method, { session, ...params }) + if (response.error) throw new Error(response.error.message) + if (response.ok) setListing(response.ok) + if (method === 'watches.add') { setPath(''); setStatus('Watch added. File changes can now start a model turn.') } + if (method === 'watches.stop') setStatus('Watch stopped. Any turn already running can be stopped in the conversation.') + } catch (error) { setProblem(String(error)) } finally { if (method !== 'watches.list') setBusy(false) } + } + useEffect(() => { void request(); const timer = setInterval(() => void request(), 2000); return () => clearInterval(timer) }, [session]) + return +

File watches

+

A file change starts a turn in this conversation and may use model credits. Normal read and approval rules still apply.

+

Up to eight watches, for seven days each. They run while this conversation is open in the app. Closing it ends the watches.

+ {problem &&

{problem}

}{status &&

{status}

} + {!listing && !problem &&

Loading watches…

} + {listing?.watches.length === 0 &&

No files watched. Add one below, or ask the agent to watch a file.

} +
    {listing?.watches.map(w =>
  • {w.path}

    {w.state === 'running' ? 'Automatic turn running' : listing.busy ? 'Waiting for this turn to finish' : 'Watching'} · Expires in {Math.max(1, Math.ceil(w.remainingSeconds / 3600))} hours

    {w.armedBy ? `Armed by turn ${w.armedBy}` : 'Added by you'}
  • )}
+
{ e.preventDefault(); void request('watches.add', { path: path.trim() }) }}>
+ {listing?.busy &&

Wait for the current turn to finish before adding a watch.

} +
+
+} diff --git a/src/renderer/failure.ts b/src/renderer/failure.ts new file mode 100644 index 0000000..0549ab4 --- /dev/null +++ b/src/renderer/failure.ts @@ -0,0 +1,21 @@ +/** Stable agent categories, independent of backend wording or translated diagnostics. */ +export function failureSummary(category: string): { title: string; description: string } { + const rows: Record = { + cancelled: ['Task stopped', 'Completed changes remain in the project. You can continue from here.'], + unauthorized: ['Authentication failed', 'Check the model service credentials in Agent settings before continuing.'], + 'rate-limited': ['The provider is busy', 'Wait before retrying, or choose another available model.'], + unavailable: ['The model service is unavailable', 'Try again when the service recovers, or choose another model.'], + refused: ['The provider refused this request', 'Review the selected model and provider limits before continuing.'], + transport: ['The model service could not be reached', 'Check the connection, proxy and certificate settings in Agent settings.'], + incomplete: ['The model reply was interrupted', 'Your conversation is preserved. Review completed work before continuing.'], + undecodable: ['The model returned an unusable reply', 'Try again or choose another model.'], + 'too-long': ['The reply reached its output limit', 'Ask for a smaller next step or choose another model.'], + 'model-unconfigured': ['Choose a model from your configured service', 'The selected model uses a service that is not configured. Choose another model from your gateway or AWS Bedrock in the model picker. Your existing API key does not configure the Brave service.'], + unconfigured: ['The selected model needs configuration', 'Check the selected model and its service credentials in Agent settings, or choose another available model.'], + blocked: ['A policy blocked this request', 'Review the conversation permissions and managed settings.'], + workspace: ['The project could not be accessed', 'Check that the project still exists and that the required files are accessible.'], + internal: ['The turn could not finish', 'Your conversation is preserved. Review diagnostics before continuing.'], + } + const [title, description] = rows[category] ?? ['The turn could not finish', 'Your conversation is preserved. Review the details before continuing.'] + return { title, description } +} diff --git a/src/renderer/styles.css b/src/renderer/styles.css index 22bb9e7..83837af 100644 --- a/src/renderer/styles.css +++ b/src/renderer/styles.css @@ -2113,7 +2113,7 @@ button:focus-visible, input:focus-visible, textarea:focus-visible, summary:focus .app .bubble pre { font-size: 12px; } .app.compact .entries { gap: 10px; padding: 16px 22px; } .app.compact .bubble { font-size: 13px; line-height: 1.5; } -.conversation-toolbar { display: flex; gap: 6px; padding: 5px 20px 10px; align-items: center; } +.conversation-toolbar { display: flex; flex-wrap: wrap; gap: 6px; padding: 5px 20px 10px; align-items: center; } .conversation-toolbar > button, .conversation-toolbar .export-open { min-height: 30px; padding: 4px 10px; background: transparent; border: 1px solid var(--line); border-radius: 7px; font-size: 12px; } .conversation-toolbar .export-menu { margin-left: auto; } .conversation-search { display: flex; align-items: center; gap: 6px; padding: 8px 20px; border-top: 1px solid var(--line); } @@ -2379,3 +2379,41 @@ button:focus-visible, input:focus-visible, textarea:focus-visible, summary:focus @media (prefers-reduced-motion: reduce) { .modal.about { animation: none; } } + +/* Agent 0.9 controls share the existing modal and evidence hierarchy. */ +.agent-settings, .watch-settings { width: min(760px, calc(100vw - 32px)); max-height: calc(100dvh - 40px); overflow: auto; } +.settings-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; } +.settings-heading h2 { margin-bottom: 8px; } +.settings-heading p { margin-top: 0; color: var(--ink-dim); } +.settings-tabs { display: flex; gap: 6px; border-bottom: 1px solid var(--line); padding-bottom: 10px; margin: 12px 0; } +.settings-tabs button[aria-selected="true"] { color: var(--accent); border-color: var(--accent); } +.settings-body section { padding: 12px 0; border-bottom: 1px solid var(--line); } +.settings-body h3 { margin: 8px 0; } +.settings-body p, .watch-settings p { line-height: 1.5; } +.settings-body dl { display: grid; grid-template-columns: 140px 1fr; gap: 8px 16px; } +.settings-body dt { color: var(--ink-dim); } +.settings-body dd { margin: 0; overflow-wrap: anywhere; } +.settings-body pre { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; padding: 10px; background: var(--bg); border-radius: 6px; } +.settings-path { overflow-wrap: anywhere; font-family: var(--mono); font-size: 12px; } +.settings-error { border-left: 3px solid var(--accent); padding-left: 12px; } +.settings-actions { display: flex; gap: 8px; flex-wrap: wrap; margin: 14px 0 4px; } +.hook-editor { border: 1px solid var(--line); border-radius: 10px; margin: 16px 0; padding: 16px; } +.hook-editor label, .watch-settings label { display: grid; gap: 6px; margin: 10px 0; } +.hook-editor input, .hook-editor select, .watch-settings input { width: 100%; box-sizing: border-box; padding: 9px 10px; border: 1px solid var(--line); border-radius: 6px; color: inherit; background: var(--bg); } +.hook-argument { display: flex; align-items: center; gap: 8px; } +.hook-argument label { flex: 1; } +.watch-list { list-style: none; padding: 0; } +.watch-list li { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 14px 0; border-bottom: 1px solid var(--line); } +.watch-list strong { overflow-wrap: anywhere; } +.watch-list p { margin: 6px 0; } +.watch-list small { color: var(--ink-dim); } +/* Keep the open width during folding, with room for both horizontal margins. */ +.sessions > .agent-settings-open { min-width: calc(var(--col-left-open) - 32px); margin: 10px 16px; flex-shrink: 0; } +.vetting-notice, .processor-remark { padding: 12px 16px; margin: 12px; border: 1px solid var(--line); border-radius: 8px; } +.vetting-notice.caution { border-left: 3px solid var(--accent); } +.vetting-notice p, .processor-remark pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 8px 0; } +.vetting-notice small, .processor-remark small { color: var(--ink-dim); line-height: 1.5; } +.context-status { font-size: 11px; color: var(--ink-dim); padding: 6px 20px; flex-shrink: 0; } +.watch-turn { display: grid; gap: 6px; padding: 12px 16px; border-left: 2px solid var(--accent); } +.watch-turn span { font-size: 12px; color: var(--ink-dim); } +@media (max-width: 640px) { .settings-body dl { grid-template-columns: 1fr; gap: 5px; } .settings-body dd { margin-bottom: 10px; } .settings-tabs { flex-wrap: wrap; } } diff --git a/src/renderer/transcript.ts b/src/renderer/transcript.ts index e90adaf..fe93a26 100644 --- a/src/renderer/transcript.ts +++ b/src/renderer/transcript.ts @@ -22,6 +22,7 @@ import type { Said, Shown, VouchRequest, + VetRequest, } from '../shared/protocol' import type { ExportTurn } from '../shared/export' import { CONSOLIDATION_MARK } from '../shared/bots' @@ -92,8 +93,10 @@ export type Entry = ( * a no. `null` means it still stands; an empty array is a real reply that declined * everything. */ + | { kind: 'vet'; id: string; request: VetRequest; decision: 'approve' | 'reject' | null } | { kind: 'ask'; id: string; request: AskRequest; answers: AskAnswer[] | null } - | { kind: 'error'; id: string; text: string } + | { kind: 'error'; id: string; text: string; category?: string | null; attempts?: number | null; status?: number | null } + | { kind: 'watch'; id: string; text: string } /** A replayed tool line from a stored session: no outcome, because none was kept. */ | { kind: 'replayed-tool'; id: string; text: string } ) & { interrupted?: boolean; turn?: number } @@ -116,6 +119,8 @@ export function fromSaid(said: Said[]): Entry[] { // careful never to do, and it is a poor tool — but the alternative is drawing a lie, and // an attachment shown as a prompt is the kind of lie that matters here: it says a person // said something they did not. + const watch = /^Watch (\d+) fired: ([^\n]+) looks written to since the last look\.\n\nNothing has been read\./.exec(entry.text) + if (watch) return watchFired(Number(watch[1]), watch[2]!) const named = attached(entry.text) if (named) return { kind: 'attached', id: nextId(), path: named } as const // The same judgement one line up, for the same reason, on a string with none of that @@ -157,6 +162,7 @@ function attached(text: string): string | null { export const userSaid = (text: string): Entry => ({ kind: 'user', id: nextId(), text }) export const consolidating = (): Entry => ({ kind: 'consolidation', id: nextId() }) export const narrated = (text: string): Entry => ({ kind: 'narration', id: nextId(), text }) +export const watchFired = (number: number, path: string): Entry => ({ kind: 'watch', id: nextId(), text: `File watch ${number}: ${path}` }) export const errored = (text: string): Entry => ({ kind: 'error', id: nextId(), text }) export const quarantined = (shown: Shown): Entry => ({ kind: 'quarantined', id: nextId(), shown }) export const started = (activity: Activity): Entry => ({ @@ -184,6 +190,7 @@ export const askedOutput = (request: OutputRequest): Entry => ({ request, decision: null, }) +export const askedVet = (request: VetRequest): Entry => ({ kind: 'vet', id: nextId(), request, decision: null }) export const askedVouch = (request: VouchRequest): Entry => ({ kind: 'vouch', id: nextId(), @@ -206,7 +213,7 @@ export function beginTurn(entries: Entry[], number: number): Entry[] { for (let index = entries.length - 1; index >= 0; index--) { const entry = entries[index]! if (entry.kind === 'assistant' || entry.kind === 'turn-start') break - if (entry.kind === 'user' || entry.kind === 'consolidation') { at = index + 1; break } + if (entry.kind === 'user' || entry.kind === 'consolidation' || entry.kind === 'watch') { at = index + 1; break } } return [...entries.slice(0, at), turnStarted(number), ...entries.slice(at)] } @@ -248,21 +255,22 @@ export function land(entries: Entry[], landing: Landing): Entry[] { /** Every entry kind that puts something to the person. */ export type Asking = Extract< Entry, - { kind: 'confirm' | 'run' | 'output' | 'vouch' | 'ask' } + { kind: 'confirm' | 'run' | 'output' | 'vouch' | 'vet' | 'ask' } > -/** Whether an entry is one of the five questions. */ +/** Whether an entry awaits a decision or an answer. */ const isAsking = (entry: Entry): entry is Asking => entry.kind === 'confirm' || entry.kind === 'run' || entry.kind === 'output' || entry.kind === 'vouch' || + entry.kind === 'vet' || entry.kind === 'ask' /** * Whether it is still waiting. * - * Four of the five carry a decision and the fifth carries answers, so "unanswered" is not + * Approval requests carry a decision and a user question carries answers, so "unanswered" is not * one field. Note the asymmetry that matters: `answers: []` is *answered* — somebody * declined every question — where `null` means nobody has replied at all. */ @@ -356,6 +364,7 @@ export function plainText(entry: Entry): string | null { case 'user': case 'assistant': case 'narration': + case 'watch': case 'error': case 'replayed-tool': return entry.text @@ -422,6 +431,7 @@ export function searchableText(entry: Entry): string { case 'confirm': return [entry.request.path, entry.request.intent, ...entry.request.changes.map((change) => 'text' in change ? change.text : '')].join(' ') case 'run': return [entry.request.summary, entry.request.directory, ...entry.request.stages.map((stage) => stage.display)].join(' ') case 'output': return [entry.request.command, entry.request.summary, entry.request.output].join(' ') + case 'vet': return [entry.request.origin, entry.request.expects, entry.request.content].join(' ') case 'vouch': return [entry.request.path, entry.request.preview].join(' ') case 'ask': return entry.request.prompts.map((prompt) => [prompt.header, prompt.question, ...prompt.rows.map((row) => `${row.label} ${row.detail ?? ''}`)].join(' ')).join(' ') } diff --git a/src/shared/agent-settings.ts b/src/shared/agent-settings.ts new file mode 100644 index 0000000..132c72f --- /dev/null +++ b/src/shared/agent-settings.ts @@ -0,0 +1,26 @@ +export interface Hook { on: 'turn-started' | 'tool-finished' | 'turn-finished'; tool?: string; run: string[] } +export interface HooksDocument { path: string; text: string | null; hooks: Hook[] } +export interface AgentSettings { + build: string; configured: boolean; problem: string | null; model: string | null + brave: boolean; bedrock: boolean; providers: { name: string; credential: string }[] + selected: string | null; layers: string[]; overrides: { name: string; path: string }[] + managed: { path: string | null; keys: string[] } + network: { roots: string[]; problem: string | null; trustsNothing: boolean; proxy: string | null; authenticated: boolean; unusableProxy: string | null; noProxy: string | null } +} + +/** Reject unknown shapes instead of silently dropping commands during an edit. */ +export function parseHooks(text: string): Hook[] { + if (new TextEncoder().encode(text).length > 65536) throw new Error('Hooks must fit within 64 KB.') + const document = JSON.parse(text) + if (!document || typeof document !== 'object' || Array.isArray(document) || !Array.isArray(document.hooks)) throw new Error('Expected a hooks array.') + if (Object.keys(document).some(key => key !== 'hooks')) throw new Error('This hooks file has extra settings. Edit it directly to preserve them.') + return document.hooks.map((hook: unknown) => { + if (!hook || typeof hook !== 'object' || Array.isArray(hook)) throw new Error('Each hook needs a lifecycle event and program.') + const h = hook as Record + if (Object.keys(h).some(key => !['on', 'tool', 'run'].includes(key))) throw new Error('This hook has unsupported fields. Edit the file directly to preserve them.') + if (!['turn-started', 'tool-finished', 'turn-finished'].includes(String(h.on))) throw new Error('Choose a supported lifecycle event.') + if (!Array.isArray(h.run) || !h.run.length || h.run.some(word => typeof word !== 'string' || word.includes('\0')) || !h.run[0].trim()) throw new Error('Enter a program and separate text arguments.') + if (h.tool !== undefined && (typeof h.tool !== 'string' || !h.tool.trim() || h.on !== 'tool-finished')) throw new Error('Tool filters only apply to tool completion hooks.') + return { on: h.on, ...(h.tool ? { tool: h.tool } : {}), run: h.run } as Hook + }) +} diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index bb259d5..c2aa106 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -80,6 +80,7 @@ export interface SessionRecord { } export interface OpenedSession { + contextTokens?: number session: string model: string | null record: SessionRecord @@ -124,6 +125,7 @@ export interface ModelCatalogue { * point of forking is to ask it differently. */ export interface ForkedSession { + contextTokens?: number session: string /** The child's durable id. Real from here, though its record waits for the first turn. */ id: string @@ -145,7 +147,11 @@ export interface ForkedSession { } } +export interface Vetting { verdict: string; reason?: string | null; detail?: string | null } +export interface VetRequest { request: number; origin: string; expects: string; content: string; lines: number; vetting: Vetting } + export interface ConfirmRequest { + remark?: { preview: string[]; lines: number; label: string } | null request: number path: string intent: Intent @@ -158,6 +164,7 @@ export interface ConfirmRequest { } export interface TurnDone { + contextTokens?: number /** Added by the desktop main process while memory maintenance reserves this session. */ consolidating?: boolean turn: number @@ -183,6 +190,10 @@ export interface TurnDone { } export interface TurnError { + category?: string | null + attempts?: number | null + status?: number | null + contextTokens?: number /** A failed turn may still have saved a recoverable conversation. */ id?: string | null turn: number @@ -237,6 +248,7 @@ export interface RunRequest { * that path runs through the agent, never through here. */ export interface OutputRequest { + vetting?: Vetting request: number command: string reference: string @@ -247,6 +259,7 @@ export interface OutputRequest { /** A quarantined file the planner would like to read. */ export interface VouchRequest { + vetting?: Vetting request: number path: string preview: string @@ -303,6 +316,8 @@ export interface EventMap { 'agent.ready': { build: string; version: string; home: string | null } 'trust.request': { directory: string } 'turn.started': { turn: number } + 'watch.fired': { number: number; path: string } + 'watch.ended': { number: number; reason: string; message?: string } phase: { phase: Phase } narration: { text: string } 'tool.started': Activity @@ -316,6 +331,7 @@ export interface EventMap { 'run.request': RunRequest 'output.request': OutputRequest 'vouch.request': VouchRequest + 'vet.request': VetRequest 'ask.request': AskRequest 'turn.done': TurnDone 'turn.error': TurnError diff --git a/vendor/bravebot b/vendor/bravebot index 3259f8b..c23b2ed 160000 --- a/vendor/bravebot +++ b/vendor/bravebot @@ -1 +1 @@ -Subproject commit 3259f8bc2b6efd043c16766d15dd5f56e5052988 +Subproject commit c23b2ed525cbc732adeecd7dd0e45fbb0f05985f