diff --git a/.release/desktop-candidate.json b/.release/desktop-candidate.json index 67979737a9..843ac0dd7d 100644 --- a/.release/desktop-candidate.json +++ b/.release/desktop-candidate.json @@ -1,10 +1,10 @@ { "schema": 2, - "version": "0.5.7", - "base_sha": "74b913cff8512c015dc6f1a7473b253fa803f954", - "previous_tag": "desktop-v0.5.6", - "previous_base_sha": "78c87ae20e182fffdd99744d6c9ff99df82b159c", - "previous_merge_sha": "3855687e7699f1b169f179122b8bc92f433abd6d", - "tag": "desktop-v0.5.7", - "commit_count": 5 + "version": "0.5.8", + "base_sha": "6a17d035f79ad582ca3f4f3cdc38d376f2c4087f", + "previous_tag": "desktop-v0.5.7", + "previous_base_sha": "74b913cff8512c015dc6f1a7473b253fa803f954", + "previous_merge_sha": "13c9e900c84cac1e2c8eeb7551bd1510ecb544d3", + "tag": "desktop-v0.5.8", + "commit_count": 4 } diff --git a/CHANGELOG.md b/CHANGELOG.md index 37a4753a6d..7ca9525074 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## v0.5.8 + +### Desktop and shared changes + +- feat(desktop): unify add agent flows ([#5015](https://github.com/block/buzz/pull/5015)) ([`02f640bc4559c48ac0c2ec595ef34dd2c294b0db`](https://github.com/block/buzz/commit/02f640bc4559c48ac0c2ec595ef34dd2c294b0db)) +- fix(buzz-agent): budget summarizer reasoning separately so it cannot starve the handoff summary ([#5248](https://github.com/block/buzz/pull/5248)) ([`c7b663680a29a837dbd2fdde810f239f3d303025`](https://github.com/block/buzz/commit/c7b663680a29a837dbd2fdde810f239f3d303025)) + +### Other repository changes + +- Revert "fix(acp): reject unattended permission requests" ([#5323](https://github.com/block/buzz/pull/5323)) ([`6a17d035f79ad582ca3f4f3cdc38d376f2c4087f`](https://github.com/block/buzz/commit/6a17d035f79ad582ca3f4f3cdc38d376f2c4087f)) +- infra: bind development services to loopback ([#4871](https://github.com/block/buzz/pull/4871)) ([`65834d68d0d3441c4e628540d6d5c8b0a2e757c9`](https://github.com/block/buzz/commit/65834d68d0d3441c4e628540d6d5c8b0a2e757c9)) + +[Compare desktop-v0.5.7...desktop-v0.5.8](https://github.com/block/buzz/compare/desktop-v0.5.7...desktop-v0.5.8) + ## v0.5.7 ### Desktop and shared changes diff --git a/benchmarks/harbor-buzz-orchestra/src/harbor_buzz_orchestra/container_runtime.py b/benchmarks/harbor-buzz-orchestra/src/harbor_buzz_orchestra/container_runtime.py index 5f5f3cc66e..80205f7a67 100644 --- a/benchmarks/harbor-buzz-orchestra/src/harbor_buzz_orchestra/container_runtime.py +++ b/benchmarks/harbor-buzz-orchestra/src/harbor_buzz_orchestra/container_runtime.py @@ -27,17 +27,16 @@ from .manifest import AgentClass, ExperimentManifest, GenerationConfig from .provisioning import AgentCredential, TrialHandle from .runtime import RuntimeResult - # Tool/LLM rounds allowed per agent turn (BUZZ_AGENT_MAX_ROUNDS). # -# Deliberately set high enough that no condition reaches it, because the cap is -# per *turn* and the counter resets on every wake (buzz-agent agent.rs:82). A -# solo agent is woken exactly once, so its cap is its whole budget for the task; -# a team member gets the same cap per assignment, across arbitrarily many -# assignments. Any value a real task can hit therefore handicaps the solo +# 0 = unbounded, buzz-agent's own documented "no cap" value. The cap is per +# *turn* and the counter resets on every wake (buzz-agent agent.rs:82). A +# solo agent is woken exactly once, so any finite cap is its whole budget for +# the task; a team member gets the same cap per assignment, across arbitrarily +# many assignments. Any value a real task can hit therefore handicaps the solo # baseline for a reason unrelated to team shape. Let the trial timeout and the # cost ceiling bind instead — those apply to every condition equally. -DEFAULT_MAX_AGENT_ROUNDS = 300 +DEFAULT_MAX_AGENT_ROUNDS = 0 # buzz-acp logs each agent's cumulative token counters under this tracing # target. It is the harness's only token source, so the directive is not # optional decoration — without it every trial reports zero cost. See @@ -284,8 +283,8 @@ class BuzzContainerRuntime: usage_settle_seconds: float = 60.0, poll_seconds: float = 1.0, ) -> None: - if max_agent_rounds <= 0: - raise ValueError("max_agent_rounds must be positive") + if max_agent_rounds < 0: + raise ValueError("max_agent_rounds must be >= 0 (0 = unbounded)") if readiness_timeout_seconds <= 0: raise ValueError("readiness_timeout_seconds must be positive") if usage_settle_seconds < 0: diff --git a/benchmarks/harbor-buzz-orchestra/tests/test_container_runtime.py b/benchmarks/harbor-buzz-orchestra/tests/test_container_runtime.py index fcb5746398..0053f93d2f 100644 --- a/benchmarks/harbor-buzz-orchestra/tests/test_container_runtime.py +++ b/benchmarks/harbor-buzz-orchestra/tests/test_container_runtime.py @@ -641,9 +641,12 @@ async def _value(value): return value -def test_runtime_rejects_unbounded_agent_rounds(tmp_path): - with pytest.raises(ValueError, match="positive"): - runtime(tmp_path, max_agent_rounds=0) +def test_runtime_validates_construction_bounds(tmp_path): + # 0 is legal and means unbounded (BUZZ_AGENT_MAX_ROUNDS=0); the trial + # budget is the clock. Only negatives are rejected. + runtime(tmp_path, max_agent_rounds=0) + with pytest.raises(ValueError, match="unbounded"): + runtime(tmp_path, max_agent_rounds=-1) with pytest.raises(ValueError, match="positive"): runtime(tmp_path, readiness_timeout_seconds=0) with pytest.raises(ValueError, match="negative"): diff --git a/benchmarks/harbor-buzz-orchestra/uv.lock b/benchmarks/harbor-buzz-orchestra/uv.lock index 05072d81a8..ab403d7ae3 100644 --- a/benchmarks/harbor-buzz-orchestra/uv.lock +++ b/benchmarks/harbor-buzz-orchestra/uv.lock @@ -677,6 +677,7 @@ name = "harbor-buzz-orchestra" version = "0.1.0" source = { editable = "." } dependencies = [ + { name = "certifi" }, { name = "harbor" }, { name = "pydantic" }, { name = "pyyaml" }, @@ -691,6 +692,7 @@ dev = [ [package.metadata] requires-dist = [ + { name = "certifi", specifier = ">=2024.2.2" }, { name = "harbor", specifier = ">=0.16.1,<0.18" }, { name = "pydantic", specifier = ">=2.11" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.4" }, diff --git a/crates/buzz-acp/src/acp.rs b/crates/buzz-acp/src/acp.rs index 466c327ef5..65c004d6d7 100644 --- a/crates/buzz-acp/src/acp.rs +++ b/crates/buzz-acp/src/acp.rs @@ -155,7 +155,7 @@ pub struct AcpClient { /// a `cancelled` outcome before the agent returns from `session/prompt`. pending_permission_id: Option, /// Whether we have already sent a response to the pending permission request. - /// Guards against double-response if a timeout fires after the rejection + /// Guards against double-response if a timeout fires after the allow_once /// response was written but before `pending_permission_id` was cleared. permission_responded: bool, /// The JSON-RPC id of the most recently sent `session/prompt` request. @@ -1162,8 +1162,7 @@ impl AcpClient { /// /// While waiting, handles: /// - `session/update` notifications → logged via tracing - /// - `session/request_permission` requests → rejected unless an owner has - /// already selected a non-interactive permission mode at session setup + /// - `session/request_permission` requests → auto-approved with `allow_once` /// - Any other messages → debug-logged and ignored; if they carry an `id` /// (i.e. they are requests, not notifications), a JSON-RPC -32601 error is sent. /// @@ -1874,12 +1873,12 @@ impl AcpClient { } } - /// Reject a `session/request_permission` request from the agent. + /// Auto-approve a `session/request_permission` request from the agent. /// - /// Buzz has no human permission prompt in this harness, so selecting - /// `allow_once` would turn any admitted prompt into an implicit approval. - /// Find `reject_once` by kind when the adapter offers it; otherwise use the - /// protocol's cancelled outcome, which is also fail-closed. + /// Finds the option with `kind == "allow_once"` and responds with its `optionId`. + /// If no `allow_once` option exists, falls back to `reject_once`. + /// + /// **Critical:** Never hardcode `optionId` — always find it dynamically by `kind`. /// /// The request `id` is stored as `serde_json::Value` to support both numeric /// and string IDs per JSON-RPC 2.0. @@ -1905,7 +1904,40 @@ impl AcpClient { options.len() ); - let response = permission_denial_response(&id, options)?; + // Find allow_once by kind — NEVER hardcode optionId. + let allow_once = options + .iter() + .find(|opt| opt.get("kind").and_then(|k| k.as_str()) == Some("allow_once")); + + let response = if let Some(opt) = allow_once { + let option_id = opt["optionId"] + .as_str() + .ok_or_else(|| AcpError::Protocol("allow_once option missing optionId".into()))?; + tracing::info!( + target: "acp::permission", + "auto-approving permission id={id} with allow_once optionId={option_id:?}" + ); + permission_response_selected(&id, option_id) + } else { + // No allow_once — fall back to reject_once. + tracing::warn!( + target: "acp::permission", + "no allow_once option found in permission request id={id}, falling back to reject_once" + ); + let reject = options + .iter() + .find(|opt| opt.get("kind").and_then(|k| k.as_str()) == Some("reject_once")); + + if let Some(opt) = reject { + let option_id = opt["optionId"].as_str().unwrap_or("reject"); + permission_response_selected(&id, option_id) + } else { + return Err(AcpError::Protocol( + "no suitable permission option found (neither allow_once nor reject_once)" + .into(), + )); + } + }; // Write the response first, then mark as responded. // @@ -2070,42 +2102,6 @@ fn permission_response_cancelled(id: &serde_json::Value) -> serde_json::Value { }) } -/// Choose the fail-closed response to a `session/request_permission` request. -/// -/// Buzz has no human permission prompt in this harness, so selecting -/// `allow_once` would turn any admitted prompt into an implicit approval. -/// Prefer the adapter's `reject_once` option — matched by `kind`, never by a -/// hardcoded `optionId` — and fall back to the protocol's cancelled outcome for -/// adapters that do not offer one. Both answers deny. -/// -/// Kept free of the client so the decision is testable without an agent -/// subprocess: `AcpClient` owns a real `Child` and its stdio pipes. -fn permission_denial_response( - id: &serde_json::Value, - options: &[serde_json::Value], -) -> Result { - let reject_once = options - .iter() - .find(|opt| opt.get("kind").and_then(|k| k.as_str()) == Some("reject_once")); - - let Some(opt) = reject_once else { - tracing::warn!( - target: "acp::permission", - "no reject_once option found in permission request id={id}, cancelling" - ); - return Ok(permission_response_cancelled(id)); - }; - - let option_id = opt["optionId"] - .as_str() - .ok_or_else(|| AcpError::Protocol("reject_once option missing optionId".into()))?; - tracing::info!( - target: "acp::permission", - "rejecting permission id={id} with reject_once optionId={option_id:?}" - ); - Ok(permission_response_selected(id, option_id)) -} - /// Full `session/new` response — session ID plus the raw JSON result. /// /// Callers use the extractor helpers to pull model info from `raw`. @@ -2415,96 +2411,63 @@ mod tests { assert_eq!(StopReason::from_str("Refusal"), Some(StopReason::Refusal)); } - fn options(json: &str) -> Vec { - serde_json::from_str(json).expect("option list") - } - - fn outcome(response: &serde_json::Value) -> Option<&str> { - response["result"]["outcome"]["outcome"].as_str() - } - - /// The offered `allow_once` and `allow_always` options must be ignored: - /// there is no human to click them, so choosing either would make every - /// admitted prompt an implicit approval. `optionId`s are deliberately - /// non-obvious to prove they are matched by `kind`, never hardcoded. #[test] - fn permission_requests_select_reject_once_not_allow_once() { - let options = options( + fn find_allow_once_by_kind_not_by_option_id() { + // optionId values are intentionally non-obvious to prove we don't hardcode them. + let options: Vec = serde_json::from_str( r#"[ {"optionId": "opt-reject-42", "name": "Reject", "kind": "reject_once"}, {"optionId": "opt-allow-99", "name": "Allow once", "kind": "allow_once"}, {"optionId": "opt-always-7", "name": "Always allow", "kind": "allow_always"} ]"#, - ); + ) + .unwrap(); - let response = - permission_denial_response(&serde_json::json!(7), &options).expect("denial response"); + let allow_once = options + .iter() + .find(|opt| opt.get("kind").and_then(|k| k.as_str()) == Some("allow_once")); - assert_eq!(outcome(&response), Some("selected")); - assert_eq!( - response["result"]["outcome"]["optionId"].as_str(), - Some("opt-reject-42"), - "must select reject_once even when allow options are offered" - ); + assert!(allow_once.is_some(), "should find allow_once option"); + let opt = allow_once.unwrap(); + // Found by kind, not by hardcoded optionId + assert_eq!(opt["kind"].as_str(), Some("allow_once")); + assert_eq!(opt["optionId"].as_str(), Some("opt-allow-99")); } - /// Fail-closed backstop: an adapter that offers no `reject_once` must still - /// be denied, via the protocol's cancelled outcome rather than an error or - /// an approval. #[test] - fn permission_request_without_reject_once_is_cancelled() { - let options = options( + fn find_allow_once_returns_none_when_absent() { + let options: Vec = serde_json::from_str( r#"[ - {"optionId": "opt-allow-99", "name": "Allow once", "kind": "allow_once"}, - {"optionId": "opt-always-7", "name": "Always allow", "kind": "allow_always"} + {"optionId": "reject-1", "name": "Reject", "kind": "reject_once"}, + {"optionId": "reject-always", "name": "Always reject", "kind": "reject_always"} ]"#, - ); + ) + .unwrap(); - let response = permission_denial_response(&serde_json::json!("req-1"), &options) - .expect("cancelled response"); + let allow_once = options + .iter() + .find(|opt| opt.get("kind").and_then(|k| k.as_str()) == Some("allow_once")); - assert_eq!(outcome(&response), Some("cancelled")); - assert_eq!( - response["id"].as_str(), - Some("req-1"), - "string ids must round-trip per JSON-RPC 2.0" - ); - } - - /// An empty option list is the degenerate form of the same backstop. - #[test] - fn permission_request_with_no_options_is_cancelled() { - let response = - permission_denial_response(&serde_json::json!(1), &[]).expect("cancelled response"); - - assert_eq!(outcome(&response), Some("cancelled")); - } - - /// A `reject_once` option missing its `optionId` is a protocol violation. - /// Erroring propagates to the caller, which tears the turn down — still no - /// approval is ever sent. - #[test] - fn reject_once_without_option_id_is_a_protocol_error() { - let options = options(r#"[{"name": "Reject", "kind": "reject_once"}]"#); - - let err = permission_denial_response(&serde_json::json!(1), &options) - .expect_err("missing optionId must error"); - - assert!(matches!(err, AcpError::Protocol(_)), "got {err:?}"); + assert!(allow_once.is_none()); } #[test] - fn find_reject_once_by_kind() { - let options = - options(r#"[{"optionId": "rej-x", "name": "Reject", "kind": "reject_once"}]"#); + fn find_reject_once_fallback_when_no_allow_once() { + let options: Vec = serde_json::from_str( + r#"[{"optionId": "rej-x", "name": "Reject", "kind": "reject_once"}]"#, + ) + .unwrap(); - let response = - permission_denial_response(&serde_json::json!(1), &options).expect("denial response"); + let allow_once = options + .iter() + .find(|opt| opt.get("kind").and_then(|k| k.as_str()) == Some("allow_once")); + assert!(allow_once.is_none()); - assert_eq!( - response["result"]["outcome"]["optionId"].as_str(), - Some("rej-x") - ); + let reject_once = options + .iter() + .find(|opt| opt.get("kind").and_then(|k| k.as_str()) == Some("reject_once")); + assert!(reject_once.is_some()); + assert_eq!(reject_once.unwrap()["optionId"].as_str(), Some("rej-x")); } #[test] diff --git a/crates/buzz-acp/src/config.rs b/crates/buzz-acp/src/config.rs index d959685846..35aaec188d 100644 --- a/crates/buzz-acp/src/config.rs +++ b/crates/buzz-acp/src/config.rs @@ -116,6 +116,7 @@ impl std::fmt::Display for RespondTo { /// /// - `default` — agent's built-in behaviour (permission requests per tool call). /// - `acceptEdits` — auto-approve file edits, still ask for other tools. +/// - `bypassPermissions` — skip the permission flow entirely. /// - `dontAsk` — never prompt; reject anything that would require permission. /// - `plan` — planning-only mode (no tool execution). #[derive(Debug, Clone, Copy, PartialEq, clap::ValueEnum)] @@ -126,6 +127,9 @@ pub enum PermissionMode { /// Auto-approve file edits, still ask for other tools. #[value(alias = "acceptEdits")] AcceptEdits, + /// Skip the permission flow entirely. + #[value(alias = "bypassPermissions")] + BypassPermissions, /// Never prompt; reject anything that would require permission. #[value(alias = "dontAsk")] DontAsk, @@ -141,6 +145,7 @@ impl PermissionMode { match self { Self::Default => "default", Self::AcceptEdits => "acceptEdits", + Self::BypassPermissions => "bypassPermissions", Self::DontAsk => "dontAsk", Self::Plan => "plan", } @@ -427,12 +432,13 @@ pub struct CliArgs { /// Permission mode for agents that support `session/set_config_option` /// with `configId: "mode"` (e.g. `claude-agent-acp`). /// - /// Defaults to `dontAsk`, which rejects operations that need interactive - /// approval because Buzz does not expose a human permission prompt. + /// Defaults to `bypassPermissions` which skips the per-tool-call + /// permission flow. Set to `default` to restore the agent's built-in + /// behaviour. #[arg( long, env = "BUZZ_ACP_PERMISSION_MODE", - default_value = "dont-ask", + default_value = "bypass-permissions", value_enum )] pub permission_mode: PermissionMode, @@ -1463,7 +1469,7 @@ mod tests { memory_enabled: true, model: None, session_title: None, - permission_mode: PermissionMode::DontAsk, + permission_mode: PermissionMode::BypassPermissions, respond_to: RespondTo::Anyone, respond_to_allowlist: HashSet::new(), allowed_respond_to: Vec::new(), @@ -2264,6 +2270,10 @@ channels = "ALL" fn test_permission_mode_wire_strings() { assert_eq!(PermissionMode::Default.as_wire_str(), "default"); assert_eq!(PermissionMode::AcceptEdits.as_wire_str(), "acceptEdits"); + assert_eq!( + PermissionMode::BypassPermissions.as_wire_str(), + "bypassPermissions" + ); assert_eq!(PermissionMode::DontAsk.as_wire_str(), "dontAsk"); assert_eq!(PermissionMode::Plan.as_wire_str(), "plan"); } @@ -2271,6 +2281,7 @@ channels = "ALL" #[test] fn test_permission_mode_is_default() { assert!(PermissionMode::Default.is_default()); + assert!(!PermissionMode::BypassPermissions.is_default()); assert!(!PermissionMode::AcceptEdits.is_default()); assert!(!PermissionMode::DontAsk.is_default()); assert!(!PermissionMode::Plan.is_default()); @@ -2278,17 +2289,20 @@ channels = "ALL" #[test] fn test_permission_mode_display() { - assert_eq!(format!("{}", PermissionMode::DontAsk), "dontAsk"); + assert_eq!( + format!("{}", PermissionMode::BypassPermissions), + "bypassPermissions" + ); assert_eq!(format!("{}", PermissionMode::Default), "default"); } #[test] fn test_summary_includes_permission_mode() { let mut config = test_config(SubscribeMode::Mentions); - config.permission_mode = PermissionMode::DontAsk; + config.permission_mode = PermissionMode::BypassPermissions; let s = config.summary(); assert!( - s.contains("permission_mode=dontAsk"), + s.contains("permission_mode=bypassPermissions"), "summary should include permission_mode, got: {s}" ); } @@ -2305,9 +2319,9 @@ channels = "ALL" } #[test] - fn test_default_config_rejects_interactive_permissions() { + fn test_default_config_uses_bypass_permissions() { let config = test_config(SubscribeMode::Mentions); - assert_eq!(config.permission_mode, PermissionMode::DontAsk); + assert_eq!(config.permission_mode, PermissionMode::BypassPermissions); } #[test] @@ -2318,6 +2332,7 @@ channels = "ALL" let cases = [ ("default", PermissionMode::Default), ("accept-edits", PermissionMode::AcceptEdits), + ("bypass-permissions", PermissionMode::BypassPermissions), ("dont-ask", PermissionMode::DontAsk), ("plan", PermissionMode::Plan), ]; @@ -2332,12 +2347,14 @@ channels = "ALL" #[test] fn test_permission_mode_value_enum_camel_case_aliases() { - // Operators may set env vars using the camelCase wire-format strings. - // The #[value(alias)] attributes ensure these parse correctly. + // Operators may set env vars using the camelCase wire-format strings + // (e.g. BUZZ_ACP_PERMISSION_MODE=bypassPermissions). The #[value(alias)] + // attributes ensure these parse correctly. use clap::ValueEnum; let cases = [ ("default", PermissionMode::Default), ("acceptEdits", PermissionMode::AcceptEdits), + ("bypassPermissions", PermissionMode::BypassPermissions), ("dontAsk", PermissionMode::DontAsk), ("plan", PermissionMode::Plan), ]; @@ -2350,18 +2367,6 @@ channels = "ALL" } } - #[test] - fn test_permission_mode_rejects_unattended_bypass() { - use clap::ValueEnum; - - for input in ["bypass-permissions", "bypassPermissions"] { - assert!( - PermissionMode::from_str(input, true).is_err(), - "{input:?} must not disable the ACP permission boundary" - ); - } - } - /// Helper: resolve idle_timeout_secs using the same precedence logic as Config::from_args. /// Precedence: explicit --idle-timeout > --turn-timeout (deprecated) > `DEFAULT_IDLE_TIMEOUT_SECS`. fn resolve_idle_timeout(idle: Option, turn: Option) -> u64 { diff --git a/crates/buzz-acp/src/lib.rs b/crates/buzz-acp/src/lib.rs index 65c9dd6203..b69a1f453a 100644 --- a/crates/buzz-acp/src/lib.rs +++ b/crates/buzz-acp/src/lib.rs @@ -6199,7 +6199,7 @@ mod build_mcp_servers_tests { memory_enabled: false, model: None, session_title: None, - permission_mode: config::PermissionMode::DontAsk, + permission_mode: config::PermissionMode::BypassPermissions, respond_to: config::RespondTo::Anyone, respond_to_allowlist: std::collections::HashSet::new(), allowed_respond_to: vec![], @@ -6421,7 +6421,7 @@ mod error_outcome_emission_tests { memory_enabled: false, model: None, session_title: None, - permission_mode: config::PermissionMode::DontAsk, + permission_mode: config::PermissionMode::BypassPermissions, respond_to: config::RespondTo::Anyone, respond_to_allowlist: HashSet::new(), allowed_respond_to: vec![], diff --git a/crates/buzz-acp/src/pool.rs b/crates/buzz-acp/src/pool.rs index 8430307d9c..ddc0330d9f 100644 --- a/crates/buzz-acp/src/pool.rs +++ b/crates/buzz-acp/src/pool.rs @@ -1017,7 +1017,7 @@ async fn create_session_and_apply_model( // Apply permission mode if not the agent's built-in default AND the agent // advertises the requested mode in session/new. Agents that don't support // the mode (e.g., goose crashes on unrecognized set_config_option values) - // are safely skipped — the harness rejects interactive permission requests. + // are safely skipped — the harness auto-approves via handle_permission_request. if !ctx.permission_mode.is_default() && agent_supports_mode(&resp.raw, ctx.permission_mode.as_wire_str()) { @@ -1130,7 +1130,11 @@ async fn apply_model_switch( Ok(()) } -/// Check whether the agent's `session/new` response advertises a given mode ID +/// Set the session permission mode via `session/set_config_option`. +/// +/// Non-fatal for most errors: logs and proceeds. The agent falls back +/// to its default permission mode (`"default"`), which still works via +/// Check if the agent's `session/new` response advertises a given mode ID /// in `result.modes.availableModes[].id`. Returns `false` if the modes /// field is absent or the mode isn't listed. fn agent_supports_mode(session_new_result: &serde_json::Value, mode_wire: &str) -> bool { @@ -1146,11 +1150,7 @@ fn agent_supports_mode(session_new_result: &serde_json::Value, mode_wire: &str) .unwrap_or(false) } -/// Set the session permission mode via `session/set_config_option`. -/// -/// Non-fatal for most errors: logs and proceeds. The agent falls back to its -/// default mode, and any interactive permission request is rejected by -/// `handle_permission_request`. +/// per-tool auto-approval in `handle_permission_request`. /// /// **Fatal exception:** if the agent process exits (e.g., goose crashes on /// unrecognized methods), returns `Err(AgentExited)` so the caller can respawn. @@ -1190,7 +1190,7 @@ async fn apply_permission_mode( Ok(Err(e)) => { tracing::warn!( target: "pool::permission", - "failed to set permission mode {wire:?}: {e} — falling back to per-tool rejection" + "failed to set permission mode {wire:?}: {e} — falling back to per-tool auto-approval" ); } Err(_) => { diff --git a/crates/buzz-agent/src/llm.rs b/crates/buzz-agent/src/llm.rs index 1be2b1ecf7..7872a33321 100644 --- a/crates/buzz-agent/src/llm.rs +++ b/crates/buzz-agent/src/llm.rs @@ -1933,9 +1933,24 @@ fn classify_body_read_error( } } +/// Provider bodies that mean "this model cannot accept image input", the +/// signal the agent loop uses to strip rejected images from history and +/// continue the turn (see `replace_unsupported_images`). +/// +/// Deliberately tight, same doctrine as [`is_context_length_error`]: each +/// phrase is a verbatim capability rejection observed live. Misclassifying a +/// generic 400 as recoverable would mutate history for an error that removing +/// images cannot fix. fn is_unsupported_image_input_error(body: &str) -> bool { - body.to_ascii_lowercase() - .contains("no endpoints found that support image input") + let b = body.to_ascii_lowercase(); + // OpenRouter 404: no provider endpoint accepts images for this model. + b.contains("no endpoints found that support image input") + // OpenAI-compatible 400 from text-only single-model deployments, + // e.g. Crusoe serverless GLM: `"crusoeai/GLM-5.2-NVFP4 is not a + // multimodal model"`. Without this arm the 400 is terminal, the image + // stays in history, and every subsequent request in the session fails + // identically — the turn wedges until the harness/user gives up. + || b.contains("is not a multimodal model") } /// Build the terminal `AgentError::Llm` for a `post()` exit that has given up @@ -2130,6 +2145,13 @@ where "{status}: {body}" )))); } + // Image-capability rejection is equally recoverable and equally + // deterministic: a text-only deployment 400s the same request + // forever. Typed here (not just on the 404 arm) because + // OpenAI-compatible providers report it as a 400. + if status == 400 && is_unsupported_image_input_error(&body) { + return Err(PostError::Agent(AgentError::UnsupportedImageInput(body))); + } return Err(PostError::Agent(AgentError::Llm(format!( "{status}: {body}" )))); @@ -2536,6 +2558,12 @@ async fn openrouter_post( if status == 400 && is_context_length_error(&body) { return Err(AgentError::LlmContextExceeded(format!("{status}: {body}"))); } + // Same 400-shaped image rejection as the shared `post()` terminal: + // OpenRouter normally reports this as a 404 (handled above), but a + // BYOK/passthrough upstream can surface the provider's own 400. + if status == 400 && is_unsupported_image_input_error(&body) { + return Err(AgentError::UnsupportedImageInput(body)); + } return Err(AgentError::Llm(format!("{status}: {body}"))); } if let Some(len) = resp.content_length() { @@ -7645,6 +7673,73 @@ mod tests { ); } + /// OpenAI-compatible text-only deployments report the image rejection as a + /// 400, not OpenRouter's 404 — Crusoe serverless GLM answers + /// `"crusoeai/GLM-5.2-NVFP4 is not a multimodal model"` to every request + /// whose history contains an image. Before the 400 arm existed, this fell + /// through to terminal `AgentError::Llm`: the image stayed in history and + /// every later call in the session failed identically (measured live: + /// 8 wedged benchmark trials, 40 min of doomed retries each). Asserted + /// through `complete()` so the arm's return path into the convergence + /// mapper is covered, same doctrine as the context-400 tests above. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn openai_400_unsupported_image_is_typed_through_complete() { + let (base_url, captured) = spawn_sequence_stub(vec![StubHttpResponse { + status: 400, + body: json!({"error":{"message":"crusoeai/GLM-5.2-NVFP4 is not a multimodal model","type":"invalid_request_error"}}), + }]) + .await; + let mut c = cfg(Provider::OpenAi); + c.base_url = base_url; + let llm = Llm::new(&c).unwrap(); + let err = complete_model(&llm, &c, "gpt-probe-model") + .await + .unwrap_err(); + assert!( + matches!(&err, AgentError::UnsupportedImageInput(s) if s.contains("not a multimodal model")), + "a text-only deployment's 400 must reach the history-recovery path: got {err:?}" + ); + assert_eq!( + captured.lock().await.len(), + 1, + "a deterministic capability rejection must not be retried" + ); + } + + /// Same 400-shaped rejection at the OpenRouter terminal, which has its own + /// status ladder: a BYOK/passthrough upstream can surface the provider's + /// own 400 body instead of OpenRouter's 404 routing error. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn openrouter_post_400_unsupported_image_is_typed_and_not_retried() { + let (url, _captured, attempts) = spawn_openrouter_stub(vec![CannedResponse::new( + 400, + r#"{"error":{"message":"crusoeai/GLM-5.2-NVFP4 is not a multimodal model"}}"#, + )]) + .await; + let http = Client::builder() + .timeout(Duration::from_secs(5)) + .build() + .unwrap(); + let err = openrouter_post( + &http, + &format!("{url}/x"), + &json!({}), + "key", + Duration::from_secs(5), + ) + .await + .unwrap_err(); + assert!( + matches!(&err, AgentError::UnsupportedImageInput(s) if s.contains("not a multimodal model")), + "image rejection must reach the history-recovery path: got {err:?}" + ); + assert_eq!( + attempts.load(std::sync::atomic::Ordering::SeqCst), + 1, + "a deterministic capability rejection must not be retried" + ); + } + /// Every other 404 still maps to `LlmModelNotFound`, including one that /// shares the `No endpoints found` prefix but is about the model rather than /// the parameters — the discriminator is narrow enough that a genuinely diff --git a/desktop/package.json b/desktop/package.json index 7cfef35e26..14c412ff1d 100644 --- a/desktop/package.json +++ b/desktop/package.json @@ -1,7 +1,7 @@ { "name": "buzz", "private": true, - "version": "0.5.7", + "version": "0.5.8", "type": "module", "scripts": { "dev": "vite", diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 94504f970d..c66bf4cb54 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -1061,7 +1061,7 @@ dependencies = [ [[package]] name = "buzz-desktop" -version = "0.5.7" +version = "0.5.8" dependencies = [ "anyhow", "arboard", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index b8f58568b4..9b2de6a575 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -7,7 +7,7 @@ members = ["crates/buzz-terminal"] [package] name = "buzz-desktop" -version = "0.5.7" +version = "0.5.8" description = "Buzz desktop app" authors = ["you"] edition = "2021" diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index da476c1e57..3f332ddbf1 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Buzz", - "version": "0.5.7", + "version": "0.5.8", "identifier": "xyz.block.buzz.app", "build": { "beforeDevCommand": { diff --git a/desktop/src/features/agents/ui/AgentDefinitionDialog.tsx b/desktop/src/features/agents/ui/AgentDefinitionDialog.tsx index 409ae6a821..b4606a0f68 100644 --- a/desktop/src/features/agents/ui/AgentDefinitionDialog.tsx +++ b/desktop/src/features/agents/ui/AgentDefinitionDialog.tsx @@ -8,8 +8,6 @@ import type { UpdatePersonaInput, } from "@/shared/api/types"; import { cn } from "@/shared/lib/cn"; -import { ChooserDialogContent } from "@/shared/ui/chooser-dialog-content"; -import { Dialog } from "@/shared/ui/dialog"; import { Input } from "@/shared/ui/input"; import { Textarea } from "@/shared/ui/textarea"; import { AgentCreationPreview } from "./AgentCreationPreview"; @@ -85,6 +83,7 @@ import { import { useProviderApiKeyFieldState } from "./providerApiKeyFieldState"; import { buildRuntimeModelProviderPayload } from "./agentDefinitionSubmitPayload"; import { AgentDefinitionDialogFooter } from "./AgentDefinitionDialogFooter"; +import { AgentDefinitionDialogShell } from "./AgentDefinitionDialogShell"; import { AddCustomHarnessDialog } from "./AddCustomHarnessDialog"; import { ADD_CUSTOM_HARNESS_OPTION, @@ -94,6 +93,7 @@ import { type AgentDefinitionDialogProps = { open: boolean; + embedded?: boolean; title: string; description: string; submitLabel: string; @@ -102,6 +102,7 @@ type AgentDefinitionDialogProps = { isPending: boolean; runtimes: AcpRuntimeCatalogEntry[]; runtimeCatalogStatus?: "loading" | "ready" | "error"; + onDirtyChange?: (dirty: boolean) => void; onOpenChange: (open: boolean) => void; onSubmit: ( input: CreatePersonaInput | UpdatePersonaInput, @@ -120,6 +121,7 @@ export type AgentDefinitionSubmitOptions = { export function AgentDefinitionDialog({ open, + embedded = false, title, description, submitLabel, @@ -128,6 +130,7 @@ export function AgentDefinitionDialog({ isPending, runtimes, runtimeCatalogStatus = "ready" as const, + onDirtyChange, onOpenChange, onSubmit, publishCatalogUpdatesOnSave = false, @@ -192,6 +195,10 @@ export function AgentDefinitionDialog({ (hasText(initialValues.model) || hasText(initialValues.provider)), ); + React.useEffect(() => { + onDirtyChange?.(hasUserChanges); + }, [hasUserChanges, onDirtyChange]); + React.useEffect(() => { if (!open || !initialValues) { return; @@ -295,7 +302,8 @@ export function AgentDefinitionDialog({ }, [defaultRuntime, isCreateMode, open, runtime, runtimesLoading]); function handleOpenChange(next: boolean) { - if (!next) { + // The catalog may veto embedded close requests; preserve the draft until unmount. + if (!next && !embedded) { setDisplayName(""); setAvatarUrl(""); setSystemPrompt(""); @@ -724,317 +732,309 @@ export function AgentDefinitionDialog({ ); } + const footer = ( + handleOpenChange(false)} + publishesCatalogUpdates={publishCatalogUpdatesOnSave && hasUserChanges} + submitBlockReason={null} + submitLabel={submitLabel} + /> + ); + const form = ( +
setHasUserChanges(true)} + onSubmit={handleSubmitForm} + > + { + setHasUserChanges(true); + setAvatarUrl(""); + }} + onUploadPendingChange={setIsAvatarUploadPending} + onSelectAvatar={(nextAvatarUrl) => { + setHasUserChanges(true); + setAvatarUrl(nextAvatarUrl); + }} + /> + +
+
+ +
+ setDisplayName(event.target.value)} + placeholder="Fizz" + value={displayName} + /> +
+
+ +
+ +
+