From dbb8fc24c3f890a05863ed3c643ea1756e2caf3f Mon Sep 17 00:00:00 2001 From: Scott Crawford Date: Fri, 4 Dec 2026 08:57:27 -0700 Subject: [PATCH] bl apps background on: walk owners through turning on background tool calls Add `bl apps background on APP_ID` (--no-browser, --timeout): it opens the approval link, polls until the app's sandbox has restarted and background tool calls are on and ready, and exits non-zero with a reason when approval is blocked, access is paused or revoked, or the wait times out. Progress goes to stderr; --json prints one final status object on stdout. Status now surfaces Kgoose's optional blockedReason (as blocked_reason), so owner_consent_required and no_read_capabilities are visible. Fix owner_consent_required being reported as "declared tools changed", and say "process or fetch-js apps" instead of process-only. Test builds never open a real browser. Co-Authored-By: Claude Opus 5.5 --- README.md | 50 ++- src/bl/apps.rs | 1079 +++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 1053 insertions(+), 76 deletions(-) diff --git a/README.md b/README.md index 3299a1a..79edfb3 100644 --- a/README.md +++ b/README.md @@ -423,33 +423,53 @@ Portal deep links require the matching portal and Kgoose workspace-selection cha An app you own can use your read-only tools (for example Jira or Slack reads) when nobody is signed in to it, such as from a schedule. This is available only where -the environment enables it (bb-block), and only for process runtime apps. +the environment enables it (bb-block), and only for process or fetch-js apps. ```sh +bl apps background on APP_ID bl apps background status APP_ID bl apps background off APP_ID ``` -Approval is browser-only by design. Only the app's owner can turn background tool -calls on, and only from the approval page: `bl apps background status` prints -`Approve in your browser: ` when approval is needed, and the CLI never -approves. Turning them on makes the app owner-only, so only you can deploy it -and calls pause while any other publisher exists. `status` shows whether you are the -sole publisher, whether the app is ready or restarting, and which tools are -approved or waiting for approval. `off` turns them off and confirms the new state; -it only reduces access, so it asks for no confirmation. `--json` prints `ok`, -`app_id`, `state`, `sole_publisher`, `ready`, `restarting`, `capabilities`, -`pending_capabilities`, `confirmed_at`, `message` and `approval_url`. - -On a BuilderLab Blox workstation, both commands use the workstation's user identity +Use `on` to turn them on. It opens the approval link in your browser, waits while +you approve and Compose restarts the app's sandbox so only your code runs (up to +about 10 minutes), and exits 0 when they are on and ready. Approval is +browser-only by design: only the app's owner can approve, and the CLI never +approves. Progress goes to stderr. With `--json`, stdout gets one final JSON object +(the status below). Options: + +- `--no-browser` prints the link instead of opening it. The link is also only + printed on a Blox workstation and when using the workstation proxy. +- `--timeout SECONDS` (default 600) bounds the wait. On timeout it exits non-zero + and says to check `bl apps background status APP_ID`. + +If the owner hasn't approved the app's own tool access yet, `on` says +`Can't turn on yet: ...`, opens the app for you to approve, and carries on once +that is done. It exits non-zero when the app declares no read-only tools +(`no_read_capabilities`), when other publishers pause access +(`other_publishers`), when access is turned off again, or when the wait times out. +Temporary network or server errors are retried until the timeout. + +Turning them on makes the app owner-only, so only you can deploy it and calls +pause while any other publisher exists. `status` changes nothing: it shows whether +you are the sole publisher, whether the app is ready or restarting, which tools +are approved or waiting for approval, what blocks approval (`blocked_reason`), +and prints `Approve in your browser: ` when approval is needed. `off` turns +them off and confirms the new state; it only reduces access, so it asks for no +confirmation. `--json` prints `ok`, `app_id`, `state`, `sole_publisher`, `ready`, +`restarting`, `capabilities`, `pending_capabilities`, `confirmed_at`, `message`, +`blocked_reason` (`code`, `message`, `next_step`, `url`; null when nothing is +known to block approval or Kgoose doesn't report it) and `approval_url`. + +On a BuilderLab Blox workstation, these commands use the workstation's user identity through the configured `BL_TOOLS_BASE_URL` proxy, without a local login or organization configuration. The proxy defaults to Kgoose's internal `/cash-app/goose` prefix; `--kgoose-service-path` or `KGOOSE_SERVICE_PATH` can override it. Elsewhere the commands use your `bl auth login` session. Neither needs `--base-url`. Exit codes follow the other `bl` commands: 3 when you need to log in, 4 when you are not the app's owner, 5 for a network or server failure, and 1 for refusals such as `background_disabled` (not -available in this environment), `other_publishers` or an unsupported runtime. Each -refusal carries a `next_action`. +available in this environment), `owner_consent_required`, `other_publishers` or an +unsupported runtime. Each refusal carries a `next_action`. ### App lifetime inspection and renewal diff --git a/src/bl/apps.rs b/src/bl/apps.rs index d90ff8c..4c84307 100644 --- a/src/bl/apps.rs +++ b/src/bl/apps.rs @@ -544,21 +544,24 @@ pub fn command() -> Command { ) .subcommand( Command::new("background") - .about("See or turn off background tool calls for an app") + .about("Turn on, check, or turn off background tool calls for an app") .long_about( "Background tool calls let a hosted app you own use your read-only tools, \ such as Jira or Slack reads, when nobody is signed in to it, for example \ - from a schedule. Only the app's owner can turn them on, and only in the \ - browser: this CLI cannot approve. `status` shows where things stand and, \ - when approval is needed, prints the link to open in your browser. `off` \ - turns background tool calls off. To use them the app becomes owner-only: \ - only you can deploy it, and calls pause while any other publisher exists. \ - Only process runtime apps are supported. Where background tool calls \ - aren't enabled, these commands say so.", + from a schedule. Only the app's owner can approve them, and only in the \ + browser: this CLI cannot approve. `on` is the way to turn them on: it \ + opens the approval link for you, waits while the app restarts so only \ + your code runs, and says when they are ready. `status` shows where \ + things stand without changing anything, and `off` turns background tool \ + calls off. To use them the app becomes owner-only: only you can deploy \ + it, and calls pause while any other publisher exists. Only process or \ + fetch-js apps are supported. Where background tool calls aren't \ + enabled, these commands say so.", ) .subcommand_required(true) .arg_required_else_help(true) .disable_help_subcommand(true) + .subcommand(background_command("on")) .subcommand(background_command("status")) .subcommand(background_command("off")), ) @@ -685,25 +688,36 @@ fn app_get_command(name: &'static str) -> Command { } fn background_command(action: &'static str) -> Command { - let (about, long_about) = if action == "status" { - ( + let (about, long_about) = match action { + "on" => ( + "Walk through turning on background tool calls for an app you own", + "Turn on background tool calls for an app you own. Opens the approval link in your \ + browser (or prints it with --no-browser, on a Blox workstation, or when the CLI \ + uses the workstation proxy), then waits while you approve and the app's sandbox \ + restarts so only your code runs, and exits 0 once they are on and ready. If the \ + app's own tool access still needs your approval first, it says so, opens the app \ + for you to approve, and carries on once that is done. Progress goes to stderr; \ + with --json, stdout gets one final JSON object. Exits non-zero if approval can't \ + be given, access is paused or revoked, or the wait times out.", + ), + "status" => ( "Show an app's background tool call state and the approval link", "Show whether background tool calls are on for an app you own, whether you are its \ - only publisher, whether it is ready, and which read-only tools are approved or \ - waiting for approval. When approval is needed, prints `Approve in your browser: \ - `. Open that link as the app's owner; approval is browser-only and this CLI \ + only publisher, whether it is ready, which read-only tools are approved or \ + waiting for approval, and anything that stops approval from working yet. When \ + approval is needed, prints `Approve in your browser: `; `bl apps \ + background on` opens it for you and waits. Approval is browser-only and this CLI \ never approves. Changes nothing. Add --json for the full response.", - ) - } else { - ( + ), + _ => ( "Turn off background tool calls for an app you own", "Turn off background tool calls for an app you own and confirm the new state. It \ only reduces access, so it asks for no confirmation. Turning them on again takes \ - the owner's approval in the browser; `bl apps background status` prints the link. \ - Add --json for the full response.", - ) + the owner's approval in the browser; `bl apps background on` walks you through \ + it. Add --json for the full response.", + ), }; - Command::new(action) + let command = Command::new(action) .about(about) .long_about(long_about) .arg( @@ -711,6 +725,24 @@ fn background_command(action: &'static str) -> Command { .value_name("APP_ID") .required(true) .help("App identifier returned by `bl apps list` or `bl apps create`"), + ); + if action != "on" { + return command; + } + command + .arg( + Arg::new("no-browser") + .long("no-browser") + .action(clap::ArgAction::SetTrue) + .help("Print the approval link instead of opening it in a browser"), + ) + .arg( + Arg::new("timeout") + .long("timeout") + .value_name("SECONDS") + .default_value("600") + .value_parser(clap::value_parser!(u64).range(1..=86_400)) + .help("How long to wait for approval and the app restart"), ) } @@ -2194,20 +2226,22 @@ const BACKGROUND_ACCESS_TIMEOUT: Duration = Duration::from_secs(30); const BACKGROUND_ACCESS_RESPONSE_MAX_BYTES: usize = 256 * 1024; /// `status` reads and `off` revokes an owner's background tool call access for -/// one app, through Kgoose with workstation authentication or a stored CLI session. Turning access on is -/// deliberately not here: Kgoose only takes that from the owner's browser, so -/// this prints the approval link and never approves. +/// one app, through Kgoose with workstation authentication or a stored CLI session. +/// `on` walks the owner through approving it. The approval itself is +/// deliberately not here: Kgoose only takes it from the owner's browser, so +/// the CLI opens or prints the approval link and never approves. fn run_background(config: &SkillsConfig, matches: &ArgMatches) -> Result<()> { let (action, action_matches) = matches .subcommand() - .context("expected background status or off")?; + .context("expected background on, status or off")?; let app_id = action_matches .get_one::("app-id") .context("expected app id")?; let turn_off = match action { + "on" => return run_background_on(config, action_matches, app_id), "status" => false, "off" => true, - _ => anyhow::bail!("expected background status or off"), + _ => anyhow::bail!("expected background on, status or off"), }; let method = if turn_off { reqwest::Method::DELETE @@ -2407,15 +2441,45 @@ fn background_access_response(app_id: &str, status: StatusCode, body: &str) -> R }; // The link is only ever printed for the owner to open, so keep it to a // plain web address. - let approval_url = object - .get("approvalUrl") - .or_else(|| object.get("approval_url")) - .and_then(Value::as_str) - .filter(|link| { - url::Url::parse(link) - .is_ok_and(|link| matches!(link.scheme(), "https" | "http") && link.has_host()) + let web_link = |link: Option<&Value>| { + link.and_then(Value::as_str) + .filter(|link| { + url::Url::parse(link) + .is_ok_and(|link| matches!(link.scheme(), "https" | "http") && link.has_host()) + }) + .map(|link| Value::String(link.to_string())) + .unwrap_or(Value::Null) + }; + let approval_url = web_link( + object + .get("approvalUrl") + .or_else(|| object.get("approval_url")), + ); + // Newer Kgoose builds say why approval would be refused. Older ones omit + // it, which reads as nothing known to be blocking. + let blocked_reason = object + .get("blockedReason") + .or_else(|| object.get("blocked_reason")) + .and_then(Value::as_object) + .and_then(|reason| { + let code = reason + .get("code") + .and_then(Value::as_str) + .filter(|code| is_stable_error_code(code))?; + let reason_text = |keys: &[&str]| { + keys.iter() + .find_map(|key| reason.get(*key).and_then(Value::as_str)) + .filter(|value| !value.is_empty()) + .map(|value| Value::String(value.to_string())) + .unwrap_or(Value::Null) + }; + Some(json!({ + "code": code, + "message": reason_text(&["message"]), + "next_step": reason_text(&["nextStep", "next_step"]), + "url": web_link(reason.get("url")), + })) }) - .map(|link| Value::String(link.to_string())) .unwrap_or(Value::Null); Ok(json!({ "ok": true, @@ -2428,6 +2492,7 @@ fn background_access_response(app_id: &str, status: StatusCode, body: &str) -> R "pending_capabilities": tools("pendingCapabilities"), "confirmed_at": text("confirmedAt"), "message": text("message"), + "blocked_reason": blocked_reason, "approval_url": approval_url, })) } @@ -2438,9 +2503,35 @@ fn background_access_failure( code: &str, parsed: Option<&Value>, ) -> anyhow::Error { + let (exit_code, explanation, next_action) = background_failure_parts(app_id, status, code); + let path = background_access_path(app_id); + let mut failure = CliFailure::new( + exit_code, + code, + format!( + "{path} failed with {} ({code})\n{explanation}\nnext_action: {next_action}", + status.as_u16() + ), + ); + failure.details = Some(json!({"http_status": status.as_u16()})); + failure.next_action = Some(json!(next_action)); + let correlation = parsed + .and_then(|value| { + value + .get("correlation_id") + .or_else(|| value.get("correlationId")) + }) + .and_then(Value::as_str) + .map(terminal_safe_text); + with_failure_trace_id(anyhow::Error::new(failure), correlation.as_deref()) +} + +/// The exit code, explanation and next step for a Kgoose refusal code. The +/// words are the CLI's own, since a response body can be anything. +fn background_failure_parts(app_id: &str, status: StatusCode, code: &str) -> (i32, String, String) { let app = terminal_safe_text(app_id); let retry = "Wait a minute, then run the command again."; - let (exit_code, explanation, next_action) = match code { + match code { "background_disabled" => ( exit_codes::GENERAL, "Background tool calls aren't available in this environment.".to_string(), @@ -2459,10 +2550,10 @@ fn background_access_failure( ), "sandbox_unavailable" | "unsupported_runtime" => ( exit_codes::GENERAL, - "Background tool calls only work for process runtime apps; this app's runtime \ + "Background tool calls only work for process or fetch-js apps; this app's runtime \ isn't supported." .to_string(), - "Deploy the app with the process runtime profile to use them.".to_string(), + "Deploy the app with the process or fetch-js profile to use them.".to_string(), ), "other_publishers" | "background_requires_sole_publisher" => ( exit_codes::GENERAL, @@ -2487,14 +2578,26 @@ fn background_access_failure( "no_read_capabilities" => ( exit_codes::GENERAL, "This app declares no read-only tools for background use.".to_string(), - "Declare the read tools it needs in the app, redeploy, then approve in your browser." + format!( + "Declare the read tools it needs in the app, redeploy, then run `bl apps \ + background on {app}`." + ), + ), + "owner_consent_required" => ( + exit_codes::GENERAL, + "You haven't approved this app's own tool access yet, so background tool calls \ + can't be approved." .to_string(), + format!( + "Open the app and approve its tool access, then run `bl apps background on \ + {app}`." + ), ), - "declaration_changed" | "owner_consent_required" => ( + "declaration_changed" => ( exit_codes::GENERAL, "The app's declared tools changed since they were approved.".to_string(), format!( - "Run `bl apps background status {app}` and approve the current tools in your \ + "Run `bl apps background on {app}` and approve the current tools in your \ browser." ), ), @@ -2512,27 +2615,7 @@ fn background_access_failure( "Kgoose didn't return a usable background tool call response.".to_string(), "Try again. If it keeps happening, tell the BuilderLab team.".to_string(), ), - }; - let path = background_access_path(app_id); - let mut failure = CliFailure::new( - exit_code, - code, - format!( - "{path} failed with {} ({code})\n{explanation}\nnext_action: {next_action}", - status.as_u16() - ), - ); - failure.details = Some(json!({"http_status": status.as_u16()})); - failure.next_action = Some(json!(next_action)); - let correlation = parsed - .and_then(|value| { - value - .get("correlation_id") - .or_else(|| value.get("correlationId")) - }) - .and_then(Value::as_str) - .map(terminal_safe_text); - with_failure_trace_id(anyhow::Error::new(failure), correlation.as_deref()) + } } fn background_state_text(state: &str) -> String { @@ -2607,6 +2690,7 @@ fn background_access_text(app_id: &str, response: &Value, turned_off: bool) -> S if let Some(message) = response["message"].as_str() { text.push_str(&format!("Note: {}\n", terminal_safe_text(message))); } + text.push_str(&blocked_reason_text(&response["blocked_reason"], "Open")); if let Some(link) = response["approval_url"].as_str() { let label = if turned_off { "To turn them on again, approve in your browser" @@ -2618,6 +2702,342 @@ fn background_access_text(app_id: &str, response: &Value, turned_off: bool) -> S text } +/// "Can't turn on yet", its next step and the link to open, or nothing when +/// the response names no blocker. +fn blocked_reason_text(blocked: &Value, url_label: &str) -> String { + let Some(code) = blocked["code"].as_str() else { + return String::new(); + }; + let message = blocked["message"].as_str().unwrap_or(code); + let mut text = format!("Can't turn on yet: {}\n", terminal_safe_text(message)); + if let Some(next_step) = blocked["next_step"].as_str() { + text.push_str(&format!("Next: {}\n", terminal_safe_text(next_step))); + } + if let Some(url) = blocked["url"].as_str() { + text.push_str(&format!("{url_label}: {}\n", terminal_safe_text(url))); + } + text +} + +const BACKGROUND_ON_POLL_INTERVAL: Duration = Duration::from_secs(3); + +/// Tests shorten the wait between polls; nothing outside a test build reads it. +fn background_on_poll_interval() -> Duration { + #[cfg(test)] + if let Some(millis) = std::env::var("BL_APPS_BACKGROUND_POLL_INTERVAL_MS") + .ok() + .and_then(|value| value.parse::().ok()) + { + return Duration::from_millis(millis); + } + BACKGROUND_ON_POLL_INTERVAL +} + +/// Opens a link for the owner. Test builds never start a browser; they print +/// what would have been opened so tests can check it. +fn open_in_browser(url: &str) -> bool { + #[cfg(test)] + { + eprintln!("[test] open browser: {url}"); + true + } + #[cfg(not(test))] + { + webbrowser::open(url).is_ok() + } +} + +/// The side effects of `background on`, so the wait can be driven without a +/// network, a clock or a browser. +struct BackgroundOnIo<'a> { + fetch: &'a mut dyn FnMut() -> Result, + sleep: &'a mut dyn FnMut(Duration), + now: &'a mut dyn FnMut() -> std::time::Instant, + /// Progress lines, which go to stderr. + say: &'a mut dyn FnMut(&str), + /// Returns whether a browser was started; `None` when the link is only printed. + open: Option<&'a mut dyn FnMut(&str) -> bool>, +} + +fn run_background_on(config: &SkillsConfig, matches: &ArgMatches, app_id: &str) -> Result<()> { + let timeout = Duration::from_secs( + *matches + .get_one::("timeout") + .context("expected timeout")?, + ); + // The workstation has no browser the owner is looking at, and Blox shows + // the link elsewhere: print it and let them open it on their own machine. + let may_open = !matches.get_flag("no-browser") + && !on_blox() + && super::workspace::workstation_base_url()?.is_none(); + let mut fetch = || background_access_call(config, app_id, reqwest::Method::GET); + let mut sleep = std::thread::sleep; + let mut now = std::time::Instant::now; + let mut say = |line: &str| eprintln!("{line}"); + let mut open = open_in_browser; + let (status, already_on) = walk_background_on( + app_id, + timeout, + background_on_poll_interval(), + BackgroundOnIo { + fetch: &mut fetch, + sleep: &mut sleep, + now: &mut now, + say: &mut say, + open: may_open.then_some(&mut open as &mut dyn FnMut(&str) -> bool), + }, + )?; + let app = terminal_safe_text(app_id); + if config.json { + return print_json(&status); + } + if already_on { + println!("Background tool calls are already on for {app}."); + } else { + println!("Background tool calls are on for {app}."); + } + Ok(()) +} + +fn is_transient_background_failure(error: &anyhow::Error) -> bool { + error + .chain() + .find_map(|cause| cause.downcast_ref::()) + .is_some_and(|failure| failure.exit_code == exit_codes::NETWORK) +} + +fn background_on_failure( + app_id: &str, + exit_code: i32, + code: &str, + explanation: &str, + next_action: &str, + status: Option<&Value>, +) -> anyhow::Error { + let mut failure = CliFailure::new( + exit_code, + code, + format!("{explanation}\nnext_action: {next_action}"), + ); + failure.next_action = Some(json!(next_action)); + failure.details = status.map(|status| { + json!({ + "app_id": app_id, + "state": status["state"], + "blocked_reason": status["blocked_reason"], + }) + }); + anyhow::Error::new(failure) +} + +/// The refusal a `blocked_reason` stands for, worded like the same code +/// arriving as an error. +fn background_blocked_failure(app_id: &str, status: &Value) -> anyhow::Error { + let blocked = &status["blocked_reason"]; + let code = blocked["code"].as_str().unwrap_or("background_blocked"); + let (exit_code, mut explanation, mut next_action) = + background_failure_parts(app_id, StatusCode::CONFLICT, code); + if !matches!( + code, + "owner_consent_required" | "no_read_capabilities" | "other_publishers" + ) { + // A reason this CLI has no words for: say what Kgoose said. + explanation = blocked["message"] + .as_str() + .map(terminal_safe_text) + .unwrap_or_else(|| "Background tool calls can't be turned on yet.".to_string()); + if let Some(next_step) = blocked["next_step"].as_str() { + next_action = terminal_safe_text(next_step); + } + } + background_on_failure( + app_id, + exit_code, + code, + &explanation, + &next_action, + Some(status), + ) +} + +fn background_tools_pending(status: &Value) -> bool { + status["pending_capabilities"] + .as_array() + .is_some_and(|tools| !tools.is_empty()) +} + +fn background_is_on(status: &Value) -> bool { + status["state"] == "active" && status["ready"] == true && !background_tools_pending(status) +} + +/// Drives `bl apps background on`: shows what blocks approval, hands the owner +/// the approval link, then follows Kgoose until background tool calls are on +/// and ready, or until something needs the owner to act or the wait runs out. +/// Returns the final status, and whether it was already on when we started. +fn walk_background_on( + app_id: &str, + timeout: Duration, + interval: Duration, + mut io: BackgroundOnIo<'_>, +) -> Result<(Value, bool)> { + let app = terminal_safe_text(app_id); + let deadline = (io.now)() + timeout; + let mut announced_blocker: Option = None; + // Set once the approval link has been handed over (or isn't needed). + let mut approval_started = false; + let mut approved = false; + let mut restarting_said = false; + let mut warned = false; + let mut baseline_confirmed_at = Value::Null; + let mut needed_state_change = false; + let mut had_pending = false; + let mut last_state = "unknown".to_string(); + let mut first = true; + loop { + match (io.fetch)() { + Ok(status) => { + last_state = status["state"].as_str().unwrap_or("unknown").to_string(); + let state = last_state.as_str(); + if first && background_is_on(&status) { + return Ok((status, true)); + } + first = false; + if status["blocked_reason"].is_object() { + if approval_started { + (io.say)(blocked_reason_text(&status["blocked_reason"], "Open").trim_end()); + return Err(background_blocked_failure(app_id, &status)); + } + let code = status["blocked_reason"]["code"] + .as_str() + .unwrap_or("") + .to_string(); + if announced_blocker.as_deref() != Some(code.as_str()) { + (io.say)(blocked_reason_text(&status["blocked_reason"], "Open").trim_end()); + let Some(url) = status["blocked_reason"]["url"].as_str() else { + return Err(background_blocked_failure(app_id, &status)); + }; + if let Some(open) = io.open.as_deref_mut() { + if !open(url) { + (io.say)( + "Could not open a browser automatically. Open the URL above manually.", + ); + } + } + announced_blocker = Some(code); + } + } else if matches!(state, "paused" | "paused_other_publishers") { + return Err(background_on_failure( + app_id, + exit_codes::GENERAL, + "other_publishers", + "Other publishers can still deploy this app, and background tool calls \ + need it to be owner-only.", + &format!( + "Remove them with `bl apps publishers remove {app} --publisher \ + IDENTITY` (see `bl apps publishers list {app}`), then run `bl apps \ + background on {app}`." + ), + Some(&status), + )); + } else { + if !approval_started { + if announced_blocker.take().is_some() { + (io.say)("Tool access approved."); + } + approval_started = true; + baseline_confirmed_at = status["confirmed_at"].clone(); + needed_state_change = matches!(state, "not_granted" | "revoked"); + had_pending = background_tools_pending(&status); + if needed_state_change || had_pending { + let Some(url) = status["approval_url"].as_str() else { + return Err(background_on_failure( + app_id, + exit_codes::GENERAL, + "approval_link_missing", + "Kgoose didn't return an approval link.", + &format!( + "Try again, or check `bl apps background status {app}`." + ), + Some(&status), + )); + }; + (io.say)(&format!( + "Approve background tool calls in your browser: {}", + terminal_safe_text(url) + )); + if let Some(open) = io.open.as_deref_mut() { + if !open(url) { + (io.say)( + "Could not open a browser automatically. Open the URL above manually.", + ); + } + } + } else { + // Already approved, such as an app still restarting. + approved = true; + } + } + if !approved { + let confirmed_at = &status["confirmed_at"]; + approved = (!confirmed_at.is_null() + && *confirmed_at != baseline_confirmed_at) + || (needed_state_change && !matches!(state, "not_granted" | "revoked")) + || (had_pending && !background_tools_pending(&status)); + if approved { + (io.say)("Approval received."); + } + } + if approved && state == "revoked" { + return Err(background_on_failure( + app_id, + exit_codes::GENERAL, + "background_revoked", + "Background tool calls were turned off again before they finished \ + turning on.", + &format!("Run `bl apps background on {app}` to start again."), + Some(&status), + )); + } + if approved + && !restarting_said + && (state == "restarting" || status["restarting"] == true) + { + restarting_said = true; + (io.say)("Restarting the app's sandbox so only your code runs…"); + } + if approved && background_is_on(&status) { + return Ok((status, false)); + } + } + } + Err(error) if is_transient_background_failure(&error) => { + if !warned { + warned = true; + (io.say)( + "Couldn't reach Kgoose just now; will keep trying until the wait ends.", + ); + } + } + Err(error) => return Err(error), + } + let now = (io.now)(); + if now >= deadline { + return Err(background_on_failure( + app_id, + exit_codes::GENERAL, + "background_wait_timeout", + &format!( + "Still waiting (state: {}). Check with `bl apps background status {app}`.", + terminal_safe_text(&last_state) + ), + &format!("Run `bl apps background on {app}` to keep waiting."), + None, + )); + } + (io.sleep)(interval.min(deadline - now)); + } +} + const JOINED_COMMUNITIES_PATH: &str = "/v1/buzz/joined-communities/list"; /// Kgoose resolves the caller's linked Buzz identity and asks the relay which @@ -12117,7 +12537,7 @@ mod tests { json!({"errorCode":"sandbox_unavailable"}).to_string(), "sandbox_unavailable", exit_codes::GENERAL, - "only work for process runtime apps", + "only work for process or fetch-js apps", ), ( StatusCode::CONFLICT, @@ -12192,6 +12612,543 @@ mod tests { assert!(!text.contains("Approve in your browser")); } + const APP_URL: &str = "https://demo.apps.example/"; + const APPROVAL_URL: &str = + "https://block.builderlab.xyz/api/goose/v1/hosted-apps/demo/background-access/approve"; + + fn consent_blocker() -> Value { + json!({ + "code": "owner_consent_required", + "message": "You haven't approved this app's own tool access yet.", + "nextStep": "Open the app and approve its tool access.", + "url": APP_URL, + }) + } + + /// `bl apps background on` with a fast poll and no way to reach a real + /// browser: test builds only print the link they would have opened. + fn background_on_process( + kgoose: &ProcessServer, + extra_args: &[&str], + poll_interval_ms: u32, + ) -> std::process::Output { + let control_plane = ProcessServer::start(vec![]); + let mut args = vec!["apps", "background", "on", "demo"]; + args.extend_from_slice(extra_args); + let output = process_command( + kgoose, + &control_plane, + &args, + "apps-e2e-only.background-on.session", + ) + .env( + "BL_APPS_BACKGROUND_POLL_INTERVAL_MS", + poll_interval_ms.to_string(), + ) + .env_remove("IS_BLOX") + .env_remove("BLOX_WORKSTATION_ID") + .output() + .expect("run background on process"); + assert!(control_plane.finish().is_empty()); + output + } + + fn stderr_text(output: &std::process::Output) -> String { + String::from_utf8_lossy(&output.stderr).to_string() + } + + fn browser_opens(output: &std::process::Output) -> Vec { + stderr_text(output) + .lines() + .filter_map(|line| line.strip_prefix("[test] open browser: ")) + .map(str::to_string) + .collect() + } + + fn happy_path_responses() -> Vec { + let pending = json!([{"extension": "jira", "access": "read"}]); + let granted = json!([{"extension": "jira", "access": "read"}]); + vec![ + ProcessResponse::json(background_body( + "not_granted", + json!({"pendingCapabilities": pending, "approvalUrl": APPROVAL_URL}), + )), + ProcessResponse::json(background_body( + "not_granted", + json!({"pendingCapabilities": pending, "approvalUrl": APPROVAL_URL}), + )), + ProcessResponse::json(background_body( + "restarting", + json!({ + "restarting": true, + "capabilities": granted, + "confirmedAt": "2026-12-04T10:00:00Z", + }), + )), + ProcessResponse::json(background_body( + "restarting", + json!({ + "restarting": true, + "capabilities": granted, + "confirmedAt": "2026-12-04T10:00:00Z", + }), + )), + ProcessResponse::json(background_body( + "active", + json!({"capabilities": granted, "confirmedAt": "2026-12-04T10:00:00Z"}), + )), + ] + } + + #[test] + fn bl_apps_background_status_shows_what_blocks_approval() { + let credential = "apps-e2e-only.background-blocked-status.session"; + let body = background_body( + "not_granted", + json!({"blockedReason": consent_blocker(), "approvalUrl": APPROVAL_URL}), + ); + for json_output in [false, true] { + let kgoose = ProcessServer::start(vec![ProcessResponse::json(body.clone())]); + let mut args = vec!["apps", "background", "status", "demo"]; + if json_output { + args.push("--json"); + } + let output = background_process(&kgoose, &args, credential); + assert!(output.status.success(), "{}", stderr_text(&output)); + let stdout = process_stdout(&output); + if json_output { + let got: Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!( + got["blocked_reason"], + json!({ + "code": "owner_consent_required", + "message": "You haven't approved this app's own tool access yet.", + "next_step": "Open the app and approve its tool access.", + "url": APP_URL, + }) + ); + } else { + assert_eq!( + stdout, + format!( + "Background tool calls for demo: off (never approved)\n\ + Only you can publish it: yes\n\ + Ready: no\n\ + Approved tools: none\n\ + Can't turn on yet: You haven't approved this app's own tool access yet.\n\ + Next: Open the app and approve its tool access.\n\ + Open: {APP_URL}\n\ + Approve in your browser: {APPROVAL_URL}" + ) + ); + } + kgoose.finish(); + } + } + + #[test] + fn bl_apps_background_status_without_a_blocker_reports_null() { + let credential = "apps-e2e-only.background-no-blocker.session"; + for body in [ + background_body("not_granted", json!({})), + background_body("not_granted", json!({"blockedReason": null})), + // A blocker without a code or with an unsafe link is not trusted. + background_body("not_granted", json!({"blockedReason": {"message": "x"}})), + ] { + let kgoose = ProcessServer::start(vec![ProcessResponse::json(body)]); + let output = background_process( + &kgoose, + &["apps", "background", "status", "demo", "--json"], + credential, + ); + let got: Value = serde_json::from_str(&process_stdout(&output)).unwrap(); + assert!(got["blocked_reason"].is_null(), "{got}"); + assert!(got.as_object().unwrap().contains_key("blocked_reason")); + kgoose.finish(); + } + let got = background_access_response( + "demo", + StatusCode::OK, + &background_body( + "not_granted", + json!({"blockedReason": {"code": "owner_consent_required", "url": "javascript:alert(1)"}}), + ) + .to_string(), + ) + .unwrap(); + assert_eq!(got["blocked_reason"]["code"], "owner_consent_required"); + assert!(got["blocked_reason"]["url"].is_null()); + assert!(got["blocked_reason"]["message"].is_null()); + } + + #[test] + fn background_owner_consent_required_has_its_own_failure_text() { + let body = json!({ + "errorCode": "owner_consent_required", + "message": "private upstream detail" + }) + .to_string(); + let error = background_access_response("demo", StatusCode::CONFLICT, &body).unwrap_err(); + let (exit, payload) = failure_info(&error); + assert_eq!(exit, exit_codes::GENERAL); + assert_eq!(payload["error"]["code"], "owner_consent_required"); + let message = payload["error"]["message"].as_str().unwrap(); + assert!(!message.contains("declared tools changed"), "{message}"); + assert!( + message.contains("approved this app's own tool access"), + "{message}" + ); + assert_eq!( + payload["next_action"], + "Open the app and approve its tool access, then run `bl apps background on demo`." + ); + assert!(!payload.to_string().contains("private upstream detail")); + // The declaration-changed refusal keeps its own wording. + let body = json!({"errorCode": "declaration_changed"}).to_string(); + let error = background_access_response("demo", StatusCode::CONFLICT, &body).unwrap_err(); + let (_, payload) = failure_info(&error); + assert!(payload["error"]["message"] + .as_str() + .unwrap() + .contains("declared tools changed")); + } + + #[test] + fn bl_apps_background_on_walks_the_owner_through_approval() { + for json_output in [false, true] { + let kgoose = ProcessServer::start(happy_path_responses()); + let mut extra = vec!["--no-browser"]; + if json_output { + extra.push("--json"); + } + let output = background_on_process(&kgoose, &extra, 10); + assert!(output.status.success(), "{}", stderr_text(&output)); + assert!(browser_opens(&output).is_empty()); + let stderr = stderr_text(&output); + assert_eq!( + stderr, + format!( + "Approve background tool calls in your browser: {APPROVAL_URL}\n\ + Approval received.\n\ + Restarting the app's sandbox so only your code runs…\n" + ) + ); + let stdout = process_stdout(&output); + if json_output { + let got: Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(got["ok"], true); + assert_eq!(got["app_id"], "demo"); + assert_eq!(got["state"], "active"); + assert_eq!(got["ready"], true); + assert_eq!(got["confirmed_at"], "2026-12-04T10:00:00Z"); + assert!(got["blocked_reason"].is_null()); + assert!(got["pending_capabilities"].as_array().unwrap().is_empty()); + } else { + assert_eq!(stdout, "Background tool calls are on for demo."); + } + let requests = kgoose.finish(); + assert_eq!(requests.len(), 5); + assert!(requests.iter().all(|request| request.method == "GET")); + } + } + + #[test] + fn bl_apps_background_on_opens_the_approval_link_unless_told_not_to() { + let kgoose = ProcessServer::start(happy_path_responses()); + let output = background_on_process(&kgoose, &[], 10); + assert!(output.status.success(), "{}", stderr_text(&output)); + assert_eq!(browser_opens(&output), vec![APPROVAL_URL.to_string()]); + kgoose.finish(); + } + + #[test] + fn bl_apps_background_on_does_not_open_a_browser_through_the_workstation_proxy() { + let kgoose = ProcessServer::start(happy_path_responses()); + let control_plane = ProcessServer::start(vec![]); + let output = process_command( + &kgoose, + &control_plane, + &["apps", "background", "on", "demo"], + "apps-e2e-only.unused", + ) + .env("BL_APPS_E2E_PROXY", "true") + .env("BL_TOOLS_BASE_URL", &kgoose.base_url) + .env("BL_APPS_BACKGROUND_POLL_INTERVAL_MS", "10") + .output() + .expect("run workstation background on process"); + assert!(output.status.success(), "{}", stderr_text(&output)); + assert!(browser_opens(&output).is_empty()); + assert!(stderr_text(&output).starts_with(&format!( + "Approve background tool calls in your browser: {APPROVAL_URL}\n" + ))); + let requests = kgoose.finish(); + assert_eq!( + requests[0].path, + "/cash-app/goose/v1/hosted-apps/demo/background-access" + ); + assert!(control_plane.finish().is_empty()); + } + + #[test] + fn bl_apps_background_on_waits_for_owner_consent_to_clear() { + let blocked = || { + ProcessResponse::json(background_body( + "not_granted", + json!({"blockedReason": consent_blocker(), "approvalUrl": APPROVAL_URL}), + )) + }; + let mut responses = vec![blocked(), blocked()]; + responses.extend(happy_path_responses()); + // Without --no-browser: the app opens first, then the approval link. + let kgoose = ProcessServer::start(responses.clone()); + let output = background_on_process(&kgoose, &[], 10); + assert!(output.status.success(), "{}", stderr_text(&output)); + assert_eq!( + browser_opens(&output), + vec![APP_URL.to_string(), APPROVAL_URL.to_string()] + ); + assert_eq!( + stderr_text(&output), + format!( + "Can't turn on yet: You haven't approved this app's own tool access yet.\n\ + Next: Open the app and approve its tool access.\n\ + Open: {APP_URL}\n\ + [test] open browser: {APP_URL}\n\ + Tool access approved.\n\ + Approve background tool calls in your browser: {APPROVAL_URL}\n\ + [test] open browser: {APPROVAL_URL}\n\ + Approval received.\n\ + Restarting the app's sandbox so only your code runs…\n" + ) + ); + assert_eq!(kgoose.finish().len(), 7); + // With --no-browser the link is printed and nothing is opened. + let kgoose = ProcessServer::start(responses); + let output = background_on_process(&kgoose, &["--no-browser"], 10); + assert!(output.status.success(), "{}", stderr_text(&output)); + assert!(browser_opens(&output).is_empty()); + assert!(stderr_text(&output).contains(&format!("Open: {APP_URL}\n"))); + kgoose.finish(); + } + + #[test] + fn bl_apps_background_on_stops_when_the_app_declares_no_read_tools() { + let kgoose = ProcessServer::start(vec![ProcessResponse::json(background_body( + "not_granted", + json!({ + "blockedReason": { + "code": "no_read_capabilities", + "message": "This app declares no read-only tools.", + "nextStep": "Declare read tools and redeploy.", + }, + "approvalUrl": APPROVAL_URL, + }), + ))]); + let output = background_on_process(&kgoose, &["--json"], 10); + assert_eq!(output.status.code(), Some(exit_codes::GENERAL)); + assert!(browser_opens(&output).is_empty()); + let error = process_error(&output); + assert_eq!(error["error"]["code"], "no_read_capabilities"); + assert!(error["next_action"] + .as_str() + .unwrap() + .contains("bl apps background on demo")); + assert!(stderr_text(&output) + .contains("Can't turn on yet: This app declares no read-only tools.\n")); + assert_eq!(kgoose.finish().len(), 1); + } + + #[test] + fn bl_apps_background_on_exits_without_a_browser_when_already_on() { + let body = background_body( + "active", + json!({ + "capabilities": [{"extension": "jira", "access": "read"}], + "confirmedAt": "2026-11-20T10:00:00Z", + "approvalUrl": APPROVAL_URL, + }), + ); + for json_output in [false, true] { + let kgoose = ProcessServer::start(vec![ProcessResponse::json(body.clone())]); + let extra: &[&str] = if json_output { &["--json"] } else { &[] }; + let output = background_on_process(&kgoose, extra, 10); + assert!(output.status.success(), "{}", stderr_text(&output)); + assert!(browser_opens(&output).is_empty()); + assert_eq!(stderr_text(&output), ""); + let stdout = process_stdout(&output); + if json_output { + let got: Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(got["state"], "active"); + } else { + assert_eq!(stdout, "Background tool calls are already on for demo."); + } + assert_eq!(kgoose.finish().len(), 1); + } + } + + #[test] + fn bl_apps_background_on_times_out_with_the_state_and_a_status_hint() { + // One second with a one second interval is exactly two polls. + let waiting = || { + ProcessResponse::json(background_body( + "not_granted", + json!({ + "pendingCapabilities": [{"extension": "jira", "access": "read"}], + "approvalUrl": APPROVAL_URL, + }), + )) + }; + let kgoose = ProcessServer::start(vec![waiting(), waiting()]); + let output = background_on_process(&kgoose, &["--no-browser", "--timeout", "1"], 1000); + assert_eq!(output.status.code(), Some(exit_codes::GENERAL)); + let stderr = stderr_text(&output); + assert!( + stderr.contains( + "Still waiting (state: not_granted). Check with `bl apps background status demo`." + ), + "{stderr}" + ); + assert!(!stderr.contains("Approval received.")); + assert_eq!(kgoose.finish().len(), 2); + } + + #[test] + fn bl_apps_background_on_stops_when_other_publishers_pause_access_after_approval() { + let pending = json!([{"extension": "jira", "access": "read"}]); + let kgoose = ProcessServer::start(vec![ + ProcessResponse::json(background_body( + "not_granted", + json!({"pendingCapabilities": pending, "approvalUrl": APPROVAL_URL}), + )), + ProcessResponse::json(background_body( + "paused_other_publishers", + json!({ + "solePublisher": false, + "confirmedAt": "2026-12-04T10:00:00Z", + "message": "private upstream detail", + }), + )), + ]); + let output = background_on_process(&kgoose, &["--no-browser", "--json"], 10); + assert_eq!(output.status.code(), Some(exit_codes::GENERAL)); + let error = process_error(&output); + assert_eq!(error["error"]["code"], "other_publishers"); + assert!(error["next_action"] + .as_str() + .unwrap() + .contains("bl apps publishers remove demo")); + assert!(!error.to_string().contains("private upstream detail")); + kgoose.finish(); + } + + #[test] + fn bl_apps_background_on_stops_on_a_blocker_that_appears_after_approval() { + let pending = json!([{"extension": "jira", "access": "read"}]); + let kgoose = ProcessServer::start(vec![ + ProcessResponse::json(background_body( + "not_granted", + json!({"pendingCapabilities": pending, "approvalUrl": APPROVAL_URL}), + )), + ProcessResponse::json(background_body( + "not_granted", + json!({"blockedReason": consent_blocker(), "approvalUrl": APPROVAL_URL}), + )), + ]); + let output = background_on_process(&kgoose, &["--no-browser", "--json"], 10); + assert_eq!(output.status.code(), Some(exit_codes::GENERAL)); + let error = process_error(&output); + assert_eq!(error["error"]["code"], "owner_consent_required"); + assert!(error["next_action"] + .as_str() + .unwrap() + .starts_with("Open the app and approve its tool access")); + assert_eq!(kgoose.finish().len(), 2); + } + + #[test] + fn bl_apps_background_on_reports_server_refusals_without_retrying() { + let kgoose = ProcessServer::start(vec![ProcessResponse::json_status( + 403, + json!({"errorCode": "not_owner", "message": "private upstream detail"}), + )]); + let output = background_on_process(&kgoose, &["--json"], 10); + assert_eq!(output.status.code(), Some(exit_codes::FORBIDDEN)); + assert_eq!(process_error(&output)["error"]["code"], "not_owner"); + assert!(!stderr_text(&output).contains("private upstream detail")); + assert_eq!(kgoose.finish().len(), 1); + } + + #[test] + fn bl_apps_background_on_rides_out_transient_failures_with_one_warning() { + let granted = json!([{"extension": "jira", "access": "read"}]); + let kgoose = ProcessServer::start(vec![ + ProcessResponse::json(background_body( + "not_granted", + json!({ + "pendingCapabilities": granted, + "approvalUrl": APPROVAL_URL, + }), + )), + ProcessResponse::raw(502, "bad gateway"), + ProcessResponse::json_status(503, json!({"errorCode": "unavailable"})), + ProcessResponse::json(background_body( + "active", + json!({ + "capabilities": granted, + "confirmedAt": "2026-12-04T10:00:00Z", + }), + )), + ]); + let output = background_on_process(&kgoose, &["--no-browser"], 10); + assert!(output.status.success(), "{}", stderr_text(&output)); + let stderr = stderr_text(&output); + assert_eq!( + stderr.matches("Couldn't reach Kgoose").count(), + 1, + "{stderr}" + ); + assert!(!stderr.contains("bad gateway")); + kgoose.finish(); + } + + #[test] + fn walk_background_on_times_out_on_the_clock_even_when_every_poll_fails() { + let start = std::time::Instant::now(); + let elapsed = std::cell::Cell::new(Duration::ZERO); + let polls = std::cell::Cell::new(0); + let lines = std::cell::RefCell::new(Vec::::new()); + let mut fetch = || { + polls.set(polls.get() + 1); + Err(failure(exit_codes::NETWORK, "network_error", "down")) + }; + let mut sleep = |duration: Duration| elapsed.set(elapsed.get() + duration); + let mut now = || start + elapsed.get(); + let mut say = |line: &str| lines.borrow_mut().push(line.to_string()); + let error = walk_background_on( + "demo", + Duration::from_secs(10), + Duration::from_secs(3), + BackgroundOnIo { + fetch: &mut fetch, + sleep: &mut sleep, + now: &mut now, + say: &mut say, + open: None, + }, + ) + .unwrap_err(); + let (exit, payload) = failure_info(&error); + assert_eq!(exit, exit_codes::GENERAL); + assert_eq!(payload["error"]["code"], "background_wait_timeout"); + assert!(payload["error"]["message"].as_str().unwrap().contains( + "Still waiting (state: unknown). Check with `bl apps background status demo`." + )); + // Polls at 0s, 3s, 6s, 9s and a shortened wait to 10s. + assert_eq!(polls.get(), 5); + assert_eq!(elapsed.get(), Duration::from_secs(10)); + assert_eq!(lines.borrow().len(), 1); + } + #[test] fn community_names_ask_kgoose_only_when_a_community_is_shared() { for ids in [None, Some(Value::Null), Some(json!([]))] {