diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat/simple.rs b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat/simple.rs deleted file mode 100644 index dff0ccec10b..00000000000 --- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat/simple.rs +++ /dev/null @@ -1,69 +0,0 @@ -use super::*; - -/// A simplified chat interface that does not update the base configuration. -pub async fn agent_chat_simple( - ctx: &crate::core::runtime::DispatchCtx, - config: &Config, - message: &str, - model_override: Option, - temperature: Option, - thread_id: Option, -) -> Result, String> { - enforce_user_prompt_or_reject(config, message, "local_ai.ops.agent_chat_simple").await?; - - let mut effective = config.clone(); - // TAURI-RUST-RS: see `normalize_model_override` for the rationale. - if let Some(model) = normalize_model_override(model_override) { - effective.default_model = Some(model); - } - if let Some(temp) = temperature { - effective.default_temperature = temp; - } - - let default_model = effective - .default_model - .clone() - .unwrap_or_else(|| crate::config::DEFAULT_MODEL.to_string()); - - let (model, resolved_model): ( - std::sync::Arc>, - String, - ) = if providers::factory::resolves_to_managed_backend("chat", &effective) { - let (backend, resolved_model) = - providers::factory::make_openhuman_backend_model_for_thread( - "chat", - &effective, - &default_model, - true, - thread_id.as_deref(), - &crate::security::egress::EgressLedger::none(), - ) - .map_err(|e| e.to_string())?; - (backend, resolved_model) - } else { - providers::create_chat_model_with_model_id_in( - ctx, - "chat", - &effective, - effective.default_temperature, - ) - .map_err(|e| e.to_string())? - }; - tracing::debug!( - requested_model = %default_model, - resolved_model = %resolved_model, - temperature = effective.default_temperature, - "[inference] agent_chat_simple invoking crate-native chat model" - ); - let run = model.invoke( - &(), - tinyinference_llm::model::ModelRequest::new(vec![ - tinyinference_llm::message::Message::user(message.to_string()), - ]) - .with_model(default_model.clone()) - .with_temperature(effective.default_temperature), - ); - let response = run.await.map_err(|e| e.to_string())?.text(); - - Ok(Outcome::single_log(response, "agent simple chat completed")) -} diff --git a/crates/openhuman-core/src/platform/update/core.rs b/crates/openhuman-core/src/platform/update/core.rs index a0d0750ed42..7681050f3a0 100644 --- a/crates/openhuman-core/src/platform/update/core.rs +++ b/crates/openhuman-core/src/platform/update/core.rs @@ -524,7 +524,9 @@ pub async fn download_and_stage_with_version( // Stream to a temp file first, then rename for atomicity. let tmp_path = dir.join(format!(".{asset_name}.tmp")); - let streamed = download::stream_to_file(response, &tmp_path, max_bytes).await; + let mut file = std::fs::File::create(&tmp_path) + .map_err(|e| format!("failed to create the download temp file for {asset_name}: {e}"))?; + let streamed = download::stream_to_file(response, &mut file, max_bytes).await; let refusal = match streamed { Ok((written, digest)) => { log::info!("[update] downloaded {written} bytes"); diff --git a/crates/openhuman-core/src/platform/update/download.rs b/crates/openhuman-core/src/platform/update/download.rs index 7c198cd97bd..eb868f34f73 100644 --- a/crates/openhuman-core/src/platform/update/download.rs +++ b/crates/openhuman-core/src/platform/update/download.rs @@ -11,7 +11,6 @@ //! bundles, so there is no signature to verify here. use std::io::Write; -use std::path::Path; use sha2::{Digest, Sha256}; @@ -88,19 +87,18 @@ pub(super) fn check_declared_length( } } -/// Stream `response` into a new file at `path`, hashing as it goes. +/// Stream `response` into `file` (a freshly created temp file), hashing as it +/// goes. /// /// Stops reading once more than `max_bytes` arrive, without writing the /// excess; the returned count then exceeds `max_bytes` and `verify` refuses /// it. Returns the byte count and the SHA-256 digest of what was read. The -/// caller removes `path` on error. +/// caller creates the file and removes it on error. pub(super) async fn stream_to_file( mut response: reqwest::Response, - path: &Path, + file: &mut std::fs::File, max_bytes: u64, ) -> Result<(u64, [u8; 32]), String> { - let mut file = - std::fs::File::create(path).map_err(|e| format!("failed to create temp file: {e}"))?; let mut hasher = Sha256::new(); let mut read: u64 = 0; while let Some(chunk) = response diff --git a/crates/openhuman-core/src/sandbox/untrusted.rs b/crates/openhuman-core/src/sandbox/untrusted.rs deleted file mode 100644 index aef7e2219ef..00000000000 --- a/crates/openhuman-core/src/sandbox/untrusted.rs +++ /dev/null @@ -1,223 +0,0 @@ -//! The one gate for shell spawns whose argv the host did not author (issue -//! #7328, phase 5). -//! -//! A scheduled shell job is text a model, a flow or an operator typed into a -//! schedule long before it runs. The security module plans it onto an executor that -//! meets the isolation floor for untrusted code (the TinyBox native jail or a -//! container) and refuses it when none does. The operator's switch that turns the -//! sandbox off never reaches untrusted text: the module plans a run on the host only -//! for the trusted operator, so an untrusted spawn is planned onto a real executor -//! whatever the switch says, and under SaaS it runs in the user's container or not at -//! all. -//! -//! `scripts/ci/spawner-inventory.json` names every caller of this gate. - -use std::collections::{BTreeMap, HashMap}; -use std::ffi::OsString; -use std::path::Path; -use std::time::Duration; - -use super::types::{SandboxExecRequest, SandboxExecResult}; -use crate::config::Config; - -/// One untrusted shell command, already authorized by the security module. -pub(crate) struct UntrustedShell<'a> { - /// The dispatch that owns the policy context. `None` uses the ambient - /// context for legacy scheduler and hook callers. - pub(crate) dispatch_ctx: Option<&'a crate::core::runtime::DispatchCtx>, - /// Loaded configuration of the scope the command belongs to. - pub(crate) config: &'a Config, - /// Shell text. - pub(crate) command: &'a str, - /// Working directory; also the jail's writable workspace. - pub(crate) cwd: &'a Path, - /// The core's private state directory (per-call scratch is created below). - pub(crate) state_dir: &'a Path, - /// Wall-clock budget. - pub(crate) timeout: Duration, - /// Keep the shell's own last-stage pipeline status instead of `pipefail`. - pub(crate) preserve_pipeline_status: bool, - /// Extra environment variables for the command (none for a scheduled job). - pub(crate) env: &'a BTreeMap, - /// Bytes written to the command's stdin (a hook's event JSON), if any. - pub(crate) stdin: Option<&'a [u8]>, -} - -/// No extra environment, for callers that add none. -pub(crate) static NO_ENV: BTreeMap = BTreeMap::new(); - -/// Largest stdin the Docker path can carry. The container runs `sh -c ` -/// with no stdin channel, so input rides inside the command as base64 and must -/// fit one argument (Linux caps a single argument at 128 KiB). -const DOCKER_STDIN_MAX: usize = 72 * 1024; - -/// Wrap `command` so it reads `stdin` as its standard input. -fn with_inline_stdin(command: &str, stdin: &[u8]) -> anyhow::Result { - use base64::Engine as _; - if stdin.len() > DOCKER_STDIN_MAX { - anyhow::bail!( - "stdin of {} bytes exceeds the {DOCKER_STDIN_MAX}-byte limit of the Docker sandbox", - stdin.len() - ); - } - let encoded = base64::engine::general_purpose::STANDARD.encode(stdin); - Ok(format!( - "printf '%s' '{encoded}' | base64 -d | (\n{command}\n)" - )) -} - -/// Run `spawn` under the isolation floor. -/// -/// Errors are refusals, never a fallback: a spawn the module will not plan yields -/// [`super::ops::IsolationFloor`], and so does an executor that is unavailable. -pub(crate) async fn run(spawn: UntrustedShell<'_>) -> anyhow::Result { - use super::ops::Executor; - - let UntrustedShell { - dispatch_ctx, - config, - command, - cwd, - state_dir, - timeout, - preserve_pipeline_status, - env, - stdin, - } = spawn; - // The scheduler has no dispatch context of its own; the task's ambient one - // answers the component question (#7801 transitional). - let ambient_ctx; - let ctx = match dispatch_ctx { - Some(ctx) => ctx, - None => { - ambient_ctx = crate::core::runtime::DispatchCtx::ambient(); - &ambient_ctx - } - }; - let operator_off = super::operator::sandbox_off(ctx, config); - let policy = super::policy::command_policy(config, cwd, state_dir) - .map_err(|error| anyhow::anyhow!(error))?; - // The module binds the command text and a digest of its stdin. A container has no - // stdin channel, so it runs a deterministic wrapper of exactly those two inputs. - let text = SpawnText { - command, - cwd, - env, - stdin, - preserve_pipeline_status, - }; - let admitted = admit(config, &policy, &text, operator_off).await?; - let extra_env: HashMap = env - .iter() - .map(|(name, value)| (name.into(), value.into())) - .collect(); - match admitted.executor { - Executor::Host => { - tracing::debug!("[sandbox:untrusted] running on the host as the module planned"); - crate::config::ensure_usable_cwd(cwd)?; - std::fs::create_dir_all(state_dir).map_err(|error| { - anyhow::anyhow!("Cannot prepare sandbox state directory: {error}") - })?; - super::shell_exec::run_host_with_stdin( - config, - command, - cwd, - state_dir, - env.clone(), - timeout, - preserve_pipeline_status, - None, - stdin.map(<[u8]>::to_vec), - ) - .await - } - Executor::Jail => { - crate::config::ensure_usable_cwd(cwd)?; - tracing::debug!("[sandbox:untrusted] running under the native jail"); - super::native_jail::execute_with_stdin( - config, - &admitted.policy, - command, - cwd, - &extra_env, - timeout, - admitted.jail, - preserve_pipeline_status, - None, - stdin.map(<[u8]>::to_vec), - ) - .await - } - Executor::Docker => { - if admitted.policy.mount_workspace { - crate::config::ensure_usable_cwd(&admitted.policy.workspace_root)?; - } - tracing::debug!("[sandbox:untrusted] running in the sandbox container"); - let command = match stdin { - Some(stdin) => with_inline_stdin(command, stdin)?, - None => command.to_owned(), - }; - let request = SandboxExecRequest { - command, - working_dir: cwd.to_path_buf(), - env: extra_env, - timeout, - }; - super::docker::docker_exec(config, &admitted.policy, &request).await - } - } -} - -/// The concrete text of one untrusted spawn, as the module binds it. -struct SpawnText<'a> { - command: &'a str, - cwd: &'a Path, - env: &'a BTreeMap, - stdin: Option<&'a [u8]>, - preserve_pipeline_status: bool, -} - -/// Have the module plan and admit an untrusted spawn. Text the host did not author -/// carries the module's mandatory-isolation floor, whatever the operator's switches say. -#[cfg(feature = "security-module")] -async fn admit( - config: &Config, - policy: &super::types::SandboxPolicy, - spawn: &SpawnText<'_>, - operator_off: bool, -) -> anyhow::Result { - let operation = super::spawn_plan::SpawnOperation { - command: spawn.command, - cwd: spawn.cwd, - env: spawn - .env - .iter() - .map(|(name, value)| (name.clone(), value.clone())) - .collect(), - stdin: spawn.stdin, - preserve_pipeline_status: spawn.preserve_pipeline_status, - }; - super::ops::admit_planned( - config, - policy, - super::spawn_plan::SpawnSource::Untrusted, - &operation, - operator_off, - ) - .await -} - -/// Without the module there is no plan to ask for, and nothing runs unplanned. -#[cfg(not(feature = "security-module"))] -async fn admit( - _config: &Config, - _policy: &super::types::SandboxPolicy, - _spawn: &SpawnText<'_>, - _operator_off: bool, -) -> anyhow::Result { - anyhow::bail!("the security module is disabled; untrusted spawns are refused") -} - -#[cfg(test)] -#[path = "untrusted_tests.rs"] -mod tests; diff --git a/crates/openhuman-core/src/sandbox/untrusted_tests.rs b/crates/openhuman-core/src/sandbox/untrusted_tests.rs deleted file mode 100644 index a586df09021..00000000000 --- a/crates/openhuman-core/src/sandbox/untrusted_tests.rs +++ /dev/null @@ -1,239 +0,0 @@ -use super::*; -#[cfg(all(feature = "modules", target_os = "linux"))] -use crate::sandbox::types::SandboxStatus; - -fn config_in(root: &Path) -> Config { - let workspace = root.join("workspace"); - std::fs::create_dir_all(&workspace).unwrap(); - let mut config = Config { - workspace_dir: workspace.clone(), - action_dir: workspace, - config_path: root.join("config.toml"), - ..Config::default() - }; - config.modules.enabled = false; - config -} - -fn shell<'a>(config: &'a Config, command: &'a str) -> UntrustedShell<'a> { - UntrustedShell { - dispatch_ctx: None, - config, - command, - cwd: &config.action_dir, - state_dir: &config.workspace_dir, - timeout: Duration::from_secs(10), - preserve_pipeline_status: false, - env: &NO_ENV, - stdin: None, - } -} - -/// With no TinyBox module the jail cannot be reached, and an untrusted command -/// must be refused rather than started on the host. -#[tokio::test] -async fn an_untrusted_command_never_runs_when_the_jail_is_unreachable() { - let tmp = tempfile::tempdir().unwrap(); - let config = config_in(tmp.path()); - let marker = tmp.path().join("ran"); - let command = format!("touch '{}'", marker.display()); - - let result = run(shell(&config, &command)).await; - - assert!(result.is_err(), "the jail is unreachable: {result:?}"); - assert!( - !marker.exists(), - "a refused spawn must never run the command" - ); -} - -/// The operator's opt-out is only a setting declared to the module. Untrusted text never -/// runs on the host on the host's own say-so: without a module plan it is refused. -#[tokio::test] -async fn the_operator_opt_out_never_runs_untrusted_text_without_a_module_plan() { - let tmp = tempfile::tempdir().unwrap(); - let mut config = config_in(tmp.path()); - config.sandbox.enabled = Some(false); - let marker = tmp.path().join("ran"); - let command = format!("touch '{}'", marker.display()); - - let result = run(shell(&config, &command)).await; - - assert!(result.is_err(), "no plan, no run: {result:?}"); - assert!(!marker.exists(), "the command ran on the host unplanned"); -} - -const SAAS_CHILD: &str = "OPENHUMAN_UNTRUSTED_SAAS_TEST_CHILD"; - -/// SaaS never honours an opt-out: with the config and the host switch both -/// turning the sandbox off, the command still must not start on the host. -/// Deployment mode is process-owned and irreversible, so the SaaS half runs in -/// a fresh libtest process. -#[tokio::test] -async fn saas_refuses_an_untrusted_command_even_when_the_operator_opted_out() { - let module = module_path!().split_once("::").expect("crate module").1; - let test = - format!("{module}::saas_refuses_an_untrusted_command_even_when_the_operator_opted_out"); - if std::env::var(SAAS_CHILD).as_deref() == Ok(test.as_str()) { - crate::core::runtime::mode::lock_mode(crate::core::runtime::Mode::Saas).unwrap(); - let tmp = tempfile::tempdir().unwrap(); - let mut config = config_in(tmp.path()); - config.sandbox.enabled = Some(false); - let marker = tmp.path().join("ran"); - let command = format!("touch '{}'", marker.display()); - - let result = run(shell(&config, &command)).await; - - assert!(result.is_err(), "SaaS must not run it unjailed: {result:?}"); - assert!(!marker.exists(), "the command ran on the host under SaaS"); - return; - } - let output = std::process::Command::new(std::env::current_exe().expect("test binary")) - .args(["--exact", &test, "--nocapture", "--test-threads=1"]) - .env(SAAS_CHILD, &test) - .env(super::super::operator::SANDBOX_OFF_ENV, "off") - .output() - .expect("run isolated SaaS test"); - assert!( - output.status.success() && String::from_utf8_lossy(&output.stdout).contains("1 passed"), - "isolated test {test} failed: {}\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); -} - -/// Whether the module's plan, rather than the host's own floor, refused the spawn. -#[cfg(all(feature = "modules", target_os = "linux"))] -fn refused_by_module(error: &anyhow::Error) -> bool { - #[cfg(feature = "security-module")] - { - error - .downcast_ref::() - .is_some() - } - #[cfg(not(feature = "security-module"))] - { - let _ = error; - false - } -} - -/// Drives the real gate against the released TinyBox archive. What the jail -/// reports decides what must happen, and the two must agree: -/// -/// * suitable for untrusted code: the command runs, can write its workspace and -/// cannot write a sibling directory; -/// * not suitable (no process isolation, for example AppArmor restricting -/// unprivileged user namespaces): the command is refused with -/// [`IsolationFloor`] and never starts. -/// -/// Run with `cargo test -p openhuman --lib untrusted_gate_follows_the_released_jail -- --ignored` -/// (downloads the pinned archive into a scratch install under `target/tmp`). -#[cfg(all(feature = "modules", target_os = "linux"))] -#[tokio::test] -#[ignore = "requires the released TinyBox archive"] -async fn untrusted_gate_follows_the_released_jail() { - let _environment_lock = crate::config::TEST_ENV_LOCK.lock().await; - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/tmp"); - std::fs::create_dir_all(&root).unwrap(); - let tmp = tempfile::tempdir_in(&root).unwrap(); - let base = tmp.path().canonicalize().unwrap(); - let workspace = base.join("workspace"); - let outside = base.join("outside"); - std::fs::create_dir_all(&workspace).unwrap(); - std::fs::create_dir_all(&outside).unwrap(); - let mut config = Config { - workspace_dir: workspace.clone(), - action_dir: workspace.clone(), - config_path: base.join("config.toml"), - ..Config::default() - }; - config.modules.enabled = true; - config.modules.allow_download = true; - config.modules.install_dir = Some(base.join("modules").display().to_string()); - let state = base.join("state"); - - let (_backend, status, _isolation) = super::super::native_jail::status(&config) - .await - .expect("the released module reports its jail"); - - let inside = run(UntrustedShell { - dispatch_ctx: None, - config: &config, - command: "echo jailed > inside.txt && cat inside.txt", - cwd: &workspace, - state_dir: &state, - timeout: Duration::from_secs(30), - preserve_pipeline_status: false, - env: &NO_ENV, - stdin: None, - }) - .await; - let escape = outside.join("escaped.txt"); - let command = format!("echo escaped > '{}'", escape.display()); - let escaped = run(UntrustedShell { - dispatch_ctx: None, - config: &config, - command: &command, - cwd: &workspace, - state_dir: &state, - timeout: Duration::from_secs(30), - preserve_pipeline_status: false, - env: &NO_ENV, - stdin: None, - }) - .await; - - assert!( - !escape.exists(), - "an untrusted command wrote outside its workspace: {escaped:?}" - ); - match status { - SandboxStatus::Ready => { - let inside = inside.expect("a suitable jail runs a workspace write"); - assert!(inside.success(), "{inside:?}"); - assert!(inside.stdout.contains("jailed"), "{}", inside.stdout); - assert!(workspace.join("inside.txt").is_file()); - } - _ => { - let error = inside.expect_err("a jail below the floor must refuse"); - // Either floor refuses it: the module's plan (a jail that is not - // kernel-isolated is `Unsupported` for untrusted text) or, without the - // module, the host's own `IsolationFloor`. - let module_refused = refused_by_module(&error); - assert!( - module_refused - || error - .downcast_ref::() - .is_some(), - "{error}" - ); - assert!( - !workspace.join("inside.txt").exists(), - "the refused command ran" - ); - assert!(escaped.is_err()); - } - } -} - -/// The Docker path has no stdin channel, so input rides in the command as -/// base64 and the wrapped command reads it back byte for byte. -#[test] -fn docker_stdin_rides_inside_the_command_and_round_trips() { - let payload = b"{\"event\":\"it's \\\"quoted\\\"\"}\n"; - let wrapped = with_inline_stdin("cat", payload).unwrap(); - let output = std::process::Command::new("sh") - .arg("-c") - .arg(&wrapped) - .output() - .expect("sh runs"); - assert!(output.status.success(), "{wrapped}"); - assert_eq!(output.stdout, payload); -} - -#[test] -fn docker_stdin_over_the_argument_limit_is_refused() { - let error = with_inline_stdin("cat", &vec![b'x'; DOCKER_STDIN_MAX + 1]).unwrap_err(); - assert!(error.to_string().contains("exceeds"), "{error}"); -} diff --git a/crates/openhuman-core/src/security/approval/README.md b/crates/openhuman-core/src/security/approval/README.md index 8786881b100..57dd3b27bd9 100644 --- a/crates/openhuman-core/src/security/approval/README.md +++ b/crates/openhuman-core/src/security/approval/README.md @@ -20,6 +20,16 @@ pending request once after an audited decision; it cannot create a reusable grant or override a hard denial. OpenHuman's current TinySecurity config leaves Jev scoring disabled. +**Requests an earlier launch left waiting.** The one-time legacy import +carries an undecided request that is still inside its window into TinySecurity +as a pending orphan: a pending row no host instance owns, bound to a synthetic +call nothing can run. `approval_list_pending` lists orphans for the default +tenant after the requests this process parked. A person can only deny one +(`gate_orphans.rs`, `native/engine_orphans.rs`): the host verifies that denial +against the listed row byte for byte, and TinySecurity accepts nothing else for +a row another instance owns. Approving one is refused, and it stays listed until +it is denied or its window closes. + **SaaS secret master grant.** A SaaS core has no person to ask when a headless tenant request (a gateway call, a background or delivery job, the embed `profiles` API) must unlock that tenant's config secrets, which needs diff --git a/crates/openhuman-core/src/security/approval/engine.rs b/crates/openhuman-core/src/security/approval/engine.rs index b972df6ffae..8c51a9b5840 100644 --- a/crates/openhuman-core/src/security/approval/engine.rs +++ b/crates/openhuman-core/src/security/approval/engine.rs @@ -224,6 +224,12 @@ pub(crate) trait ApprovalEngine: sealed::Sealed + std::fmt::Debug + Send + Sync Ok(Vec::new()) } + /// Deny the pending orphan `request_id` (see [`Self::orphans`]) as a + /// person's decision. `Err(NotPending)` when it is not one. + async fn dismiss_orphan(&self, _request_id: &str, _label: &str) -> Result<(), EngineError> { + Err(EngineError::NotPending) + } + /// The most recently decided requests of the current scope, newest first. async fn history( &self, diff --git a/crates/openhuman-core/src/security/approval/engine_stub.rs b/crates/openhuman-core/src/security/approval/engine_stub.rs index a3443209778..eede6064a06 100644 --- a/crates/openhuman-core/src/security/approval/engine_stub.rs +++ b/crates/openhuman-core/src/security/approval/engine_stub.rs @@ -88,6 +88,9 @@ pub(crate) struct StubEngine { /// Legacy `auto_approve` entries already imported, per tenant. The module /// answers a repeat import as already done, so a revoked grant stays revoked. imported: Mutex>, + /// Requests an earlier launch left undecided (pending orphans): listed, and + /// only ever denied. + orphans: Mutex>, } impl std::fmt::Debug for StubEngine { @@ -222,6 +225,22 @@ impl StubEngine { ); } + /// [`Self::leave_pending`], as a pending orphan the import carried over. + pub(crate) fn leave_orphan(&self, request_id: &str, tool: &str, expires_in: Duration) { + self.leave_pending(request_id, tool, expires_in); + self.orphans + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(request_id.to_owned()); + } + + fn is_orphan(&self, request_id: &str) -> bool { + self.orphans + .lock() + .unwrap_or_else(PoisonError::into_inner) + .contains(request_id) + } + fn insert(&self, row: Row) -> String { let request_id = uuid::Uuid::new_v4().simple().to_string(); self.rows @@ -402,6 +421,10 @@ impl ApprovalEngine for StubEngine { if let Some(signal) = signal { signal.notified().await; } + // No host instance owns an orphan, so a decision cannot reach it. + if self.is_orphan(request_id) { + return Err(EngineError::NotPending); + } let now = now_ms(); self.with(request_id, |row| { if row.state != State::Pending || now >= row.expires_ms { @@ -583,6 +606,45 @@ impl ApprovalEngine for StubEngine { .collect()) } + async fn orphans(&self) -> Result, EngineError> { + let now = now_ms(); + let rows = self.rows.lock().unwrap_or_else(PoisonError::into_inner); + let mut listed: Vec<_> = rows + .iter() + .filter(|(id, row)| { + self.is_orphan(id) && row.state == State::Pending && now < row.expires_ms + }) + .map(|(id, row)| { + super::types::PendingApproval::new( + id.clone(), + row.tool.clone(), + "left by an earlier launch", + serde_json::Value::Null, + None, + ) + }) + .collect(); + listed.sort_by(|a, b| a.request_id.cmp(&b.request_id)); + Ok(listed) + } + + async fn dismiss_orphan(&self, request_id: &str, label: &str) -> Result<(), EngineError> { + if !self.is_orphan(request_id) { + return Err(EngineError::NotPending); + } + let now = now_ms(); + self.with(request_id, |row| { + if row.state != State::Pending || now >= row.expires_ms { + return Err(EngineError::NotPending); + } + row.state = State::Denied; + row.decided_ms = Some(now); + row.label = Some(label.to_owned()); + Ok(()) + }) + .unwrap_or(Err(EngineError::NotPending)) + } + async fn history(&self, limit: usize) -> Result, EngineError> { let rows = self.rows.lock().unwrap_or_else(PoisonError::into_inner); let mut decided: Vec<(&String, &Row)> = rows diff --git a/crates/openhuman-core/src/security/approval/gate.rs b/crates/openhuman-core/src/security/approval/gate.rs index 99196e6b6ec..603bd5a396d 100644 --- a/crates/openhuman-core/src/security/approval/gate.rs +++ b/crates/openhuman-core/src/security/approval/gate.rs @@ -467,6 +467,7 @@ include!("gate_surface.rs"); include!("gate_intercept.rs"); include!("gate_intercept_decision.rs"); include!("gate_state.rs"); +include!("gate_orphans.rs"); include!("gate_saas_grant.rs"); include!("gate_host_grant.rs"); fn now_ms() -> u64 { diff --git a/crates/openhuman-core/src/security/approval/gate_orphan_tests.rs b/crates/openhuman-core/src/security/approval/gate_orphan_tests.rs new file mode 100644 index 00000000000..b37011799a2 --- /dev/null +++ b/crates/openhuman-core/src/security/approval/gate_orphan_tests.rs @@ -0,0 +1,99 @@ +//! Requests an earlier launch left undecided (pending orphans): listed for the +//! default tenant, dismissed only by a denial. + +use super::*; +use crate::core::runtime::Tenant; +use crate::security::approval::engine_stub::State; + +#[tokio::test] +async fn an_orphan_is_listed_and_a_person_can_deny_it() { + let (gate, _dir) = test_gate(); + let stub = stub_of(&gate); + stub.leave_orphan("left-waiting", "shell", Duration::from_secs(600)); + let listed = gate.list_pending().unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].request_id, "left-waiting"); + + let dismissed = gate + .decide_as( + &Tenant::default(), + None, + "left-waiting", + ApprovalDecision::Deny, + ) + .unwrap() + .expect("the orphan is dismissed"); + assert_eq!(dismissed.request_id, "left-waiting"); + assert_eq!(dismissed.tool_name, "shell"); + assert_eq!(stub.state("left-waiting"), Some(State::Denied)); + assert_eq!(stub.label("left-waiting").as_deref(), Some("deny")); + assert!(gate.list_pending().unwrap().is_empty()); + + // Dismissed once: a second denial finds nothing to decide. + assert!(gate + .decide_as( + &Tenant::default(), + None, + "left-waiting", + ApprovalDecision::Deny + ) + .unwrap() + .is_none()); +} + +#[tokio::test] +async fn an_orphan_is_never_approved() { + let (gate, _dir) = test_gate(); + let stub = stub_of(&gate); + stub.leave_orphan("left-waiting", "shell", Duration::from_secs(600)); + for decision in [ + ApprovalDecision::ApproveOnce, + ApprovalDecision::ApproveAlwaysForTool, + ApprovalDecision::ApproveAlwaysForFlow, + ] { + let error = gate + .decide_as(&Tenant::default(), None, "left-waiting", decision) + .expect_err("approving an earlier launch's request is refused"); + assert!(error.to_string().contains("can only be denied"), "{error}"); + } + assert_eq!(stub.state("left-waiting"), Some(State::Pending)); + assert_eq!(gate.list_pending().unwrap().len(), 1); +} + +#[tokio::test] +async fn only_the_default_tenant_dismisses_an_orphan() { + let (gate, _dir) = test_gate(); + let stub = stub_of(&gate); + stub.leave_orphan("left-waiting", "shell", Duration::from_secs(600)); + let profile = Tenant { + profile: Some("someone-else".into()), + agent: None, + }; + assert!(gate + .decide_as(&profile, None, "left-waiting", ApprovalDecision::Deny) + .unwrap() + .is_none()); + // Naming an agent is a decision for that agent's own requests, which an + // orphan never is, whatever the agent path answers. + let _ = gate.decide_as( + &Tenant::default(), + Some("agent-1"), + "left-waiting", + ApprovalDecision::Deny, + ); + assert_eq!(stub.state("left-waiting"), Some(State::Pending)); +} + +#[tokio::test] +async fn an_expired_orphan_or_an_unknown_id_is_not_dismissed() { + let (gate, _dir) = test_gate(); + let stub = stub_of(&gate); + stub.leave_orphan("expired", "shell", Duration::ZERO); + for id in ["expired", "never-existed"] { + assert!(gate + .decide_as(&Tenant::default(), None, id, ApprovalDecision::Deny) + .unwrap() + .is_none()); + } + assert_eq!(stub.state("expired"), Some(State::Pending)); +} diff --git a/crates/openhuman-core/src/security/approval/gate_orphans.rs b/crates/openhuman-core/src/security/approval/gate_orphans.rs new file mode 100644 index 00000000000..f6b89f18ae9 --- /dev/null +++ b/crates/openhuman-core/src/security/approval/gate_orphans.rs @@ -0,0 +1,63 @@ +// Included into `gate.rs` beside `gate_state.rs`. + +impl ApprovalGate { + /// Dismiss a pending orphan: a request an earlier launch left undecided, + /// which [`Self::list_pending`] lists for the default tenant. Nothing in + /// this process can run the call it was for, so a denial is the only + /// decision it takes; approving one is refused and it stays listed. + /// + /// `Ok(None)` when `request_id` is not a pending orphan, which `decide` + /// reports as its miss. + fn decide_orphan( + &self, + request_id: &str, + decision: ApprovalDecision, + ) -> anyhow::Result> { + let listed = match self.run_engine(|engine| async move { engine.orphans().await })? { + Ok(listed) => listed, + Err(error) => { + tracing::warn!( + request_id = %request_id, + error = %error, + "[approval::gate] pending orphans could not be read for a decision" + ); + return Ok(None); + } + }; + let Some(orphan) = listed.into_iter().find(|row| row.request_id == request_id) else { + return Ok(None); + }; + if decision != ApprovalDecision::Deny { + tracing::debug!( + request_id = %request_id, + decision = decision.as_str(), + "[approval::gate] refused approving a request an earlier launch left" + ); + anyhow::bail!( + "this request was left by an earlier launch; it can only be denied, \ + because nothing in this launch can run it" + ); + } + let id = request_id.to_owned(); + let label = decision.as_str(); + match self.run_engine(|engine| async move { engine.dismiss_orphan(&id, label).await })? { + Ok(()) => {} + Err(EngineError::NotPending) => return Ok(None), + Err(error) => { + anyhow::bail!("the approval engine could not apply the decision: {error}") + } + } + tracing::debug!(request_id = %request_id, "[approval::gate] dismissed a pending orphan"); + BUS.publish(DomainEvent::ApprovalDecided { + request_id: request_id.to_string(), + tool_name: orphan.tool_name.clone(), + decision: decision.as_str().to_string(), + thread_id: None, + client_id: None, + tool_call_id: None, + resolution: None, + agent_id: None, + }); + Ok(Some(orphan)) + } +} diff --git a/crates/openhuman-core/src/security/approval/gate_state.rs b/crates/openhuman-core/src/security/approval/gate_state.rs index 194b89d5904..c1d61b9876b 100644 --- a/crates/openhuman-core/src/security/approval/gate_state.rs +++ b/crates/openhuman-core/src/security/approval/gate_state.rs @@ -239,13 +239,24 @@ impl ApprovalGate { ) -> anyhow::Result> { // One read of the route. If an expiry or a competing decision removes // it after this, `decide` reports the miss as the benign race it is. - if let Err(error) = self.validate_decision_context(request_id, dispatch, agent) { - tracing::warn!( - request_id = %request_id, - error = %error, - "[approval::gate] decision refused: the caller does not own the request" - ); - return Err(error); + let parked = match self.validate_decision_context(request_id, dispatch, agent) { + Ok(parked) => parked, + Err(error) => { + tracing::warn!( + request_id = %request_id, + error = %error, + "[approval::gate] decision refused: the caller does not own the request" + ); + return Err(error); + } + }; + // Pending orphans are listed only for the default tenant, so only it + // may dismiss one. + if parked.is_none() && agent.is_none() && *dispatch == crate::core::runtime::Tenant::default() + { + if let Some(dismissed) = self.decide_orphan(request_id, decision)? { + return Ok(Some(dismissed)); + } } match agent { Some(agent) => self.decide_for_agent(agent, request_id, decision), diff --git a/crates/openhuman-core/src/security/approval/gate_tests.rs b/crates/openhuman-core/src/security/approval/gate_tests.rs index 027c9e957eb..a4423bca890 100644 --- a/crates/openhuman-core/src/security/approval/gate_tests.rs +++ b/crates/openhuman-core/src/security/approval/gate_tests.rs @@ -231,6 +231,8 @@ mod gate_origin_class_tests; mod host_grant_tests; #[path = "gate_origin_intercept_tests.rs"] mod origin_intercept_tests; +#[path = "gate_orphan_tests.rs"] +mod orphan_tests; #[path = "gate_rpc_decide_tests.rs"] mod rpc_decide_tests; #[path = "gate_saas_grant_tests.rs"] diff --git a/crates/openhuman-core/src/security/approval/native/callbacks.rs b/crates/openhuman-core/src/security/approval/native/callbacks.rs index 9c7a0ee98ec..cf50b1f2391 100644 --- a/crates/openhuman-core/src/security/approval/native/callbacks.rs +++ b/crates/openhuman-core/src/security/approval/native/callbacks.rs @@ -159,10 +159,24 @@ pub(crate) async fn verify_human( let (request_id, choice, actor) = host() .ticket(&request.decision_ticket) .ok_or("human verification: the ticket is unknown or expired")?; - let known = host() - .request(&request.row.request_id) - .ok_or("human verification: the request is not pending in this process")?; - if request_id != request.row.request_id || known.delivered.as_ref() != Some(&request.row) { + // A request of this process must match the row it delivered; a pending + // orphan (an earlier launch's request) the row a person is dismissing, and + // only a denial is ever verified for one. + let shown = match host().request(&request.row.request_id) { + Some(known) => known.delivered, + None => { + let listed = host() + .orphan_review(&request.row.request_id) + .ok_or("human verification: the request is not pending in this process")?; + if choice != ApprovalChoice2::Deny { + return Err( + "human verification: an earlier launch's request can only be denied".into(), + ); + } + Some(listed) + } + }; + if request_id != request.row.request_id || shown.as_ref() != Some(&request.row) { tracing::warn!("{LOG} human ticket does not match the pending row"); return Err("human verification: the ticket is not for this request".into()); } diff --git a/crates/openhuman-core/src/security/approval/native/callbacks_tests.rs b/crates/openhuman-core/src/security/approval/native/callbacks_tests.rs index 8b66a27943c..17397514a4c 100644 --- a/crates/openhuman-core/src/security/approval/native/callbacks_tests.rs +++ b/crates/openhuman-core/src/security/approval/native/callbacks_tests.rs @@ -537,3 +537,56 @@ async fn only_the_choices_the_host_offers_are_verified() { ); host().revoke("ticket-deny"); } + +/// A pending orphan (an earlier launch's request) has no request of this +/// process behind it: only the row a person is dismissing, and only a denial, +/// is ever verified for one. +#[tokio::test] +async fn an_orphan_under_review_verifies_only_a_denial_of_the_listed_row() { + let orphan = row("verify-orphan", "0b", "abcd000a", "shell"); + for (ticket, choice) in [ + ("ticket-orphan-deny", ApprovalChoice2::Deny), + ("ticket-orphan-once", ApprovalChoice2::Once), + ] { + host().issue( + ticket.into(), + Ticket::new(orphan.request_id.clone(), choice, "operator".into()), + ); + } + // Not under review: nothing verifies it. + assert!(super::verify_human(verify(&orphan, "ticket-orphan-deny")) + .await + .is_err()); + + assert!(host().begin_orphan_review(orphan.clone())); + assert!( + !host().begin_orphan_review(orphan.clone()), + "one review at a time" + ); + let receipt = super::verify_human(verify(&orphan, "ticket-orphan-deny")) + .await + .expect("a denial of the listed row is verified"); + assert_eq!(receipt.choice, ApprovalChoice2::Deny); + assert_eq!(receipt.row, orphan); + let refused = super::verify_human(verify(&orphan, "ticket-orphan-once")).await; + assert!( + refused + .as_ref() + .is_err_and(|error| error.contains("can only be denied")), + "{:?}", + refused.map(|receipt| receipt.choice) + ); + let mut altered = orphan.clone(); + altered.summary = "a different action".into(); + assert!(super::verify_human(verify(&altered, "ticket-orphan-deny")) + .await + .is_err()); + + host().end_orphan_review(&orphan.request_id); + assert!(super::verify_human(verify(&orphan, "ticket-orphan-deny")) + .await + .is_err()); + for ticket in ["ticket-orphan-deny", "ticket-orphan-once"] { + host().revoke(ticket); + } +} diff --git a/crates/openhuman-core/src/security/approval/native/engine.rs b/crates/openhuman-core/src/security/approval/native/engine.rs index 932688d7c03..01b801ba458 100644 --- a/crates/openhuman-core/src/security/approval/native/engine.rs +++ b/crates/openhuman-core/src/security/approval/native/engine.rs @@ -309,6 +309,10 @@ impl NativeEngine { #[path = "engine_impl.rs"] mod engine_impl; +#[cfg(feature = "legacy-import")] +#[path = "engine_orphans.rs"] +mod engine_orphans; + #[cfg(test)] #[path = "engine_outcome_tests.rs"] mod outcome_tests; diff --git a/crates/openhuman-core/src/security/approval/native/engine_impl.rs b/crates/openhuman-core/src/security/approval/native/engine_impl.rs index c1d0e1e6384..25a58e8b6a3 100644 --- a/crates/openhuman-core/src/security/approval/native/engine_impl.rs +++ b/crates/openhuman-core/src/security/approval/native/engine_impl.rs @@ -413,6 +413,11 @@ impl ApprovalEngine for NativeEngine { .map_err(|error| unavailable(error.to_string())) } + #[cfg(feature = "legacy-import")] + async fn dismiss_orphan(&self, request_id: &str, label: &str) -> Result<(), EngineError> { + self.dismiss(request_id, label).await + } + async fn history(&self, limit: usize) -> Result, EngineError> { super::super::view::decided_history(&self.config, limit) .await diff --git a/crates/openhuman-core/src/security/approval/native/engine_orphans.rs b/crates/openhuman-core/src/security/approval/native/engine_orphans.rs new file mode 100644 index 00000000000..76384c07a82 --- /dev/null +++ b/crates/openhuman-core/src/security/approval/native/engine_orphans.rs @@ -0,0 +1,89 @@ +//! Dismissing a pending orphan: a request an earlier launch left undecided, +//! which the legacy import carried into the module as a pending row no host +//! instance owns. Nothing in this process can run the call it was for, so the +//! module verifies only a denial for it (`Decide2`), and the host offers only +//! that. + +use super::*; +use crate::core::runtime::Tenant; + +impl NativeEngine { + /// Deny the pending orphan `request_id` as a person's decision. + /// `Err(NotPending)` when it is not a pending orphan of this workspace: a + /// request of this process, one already decided or expired, or no row. + pub(super) async fn dismiss(&self, request_id: &str, label: &str) -> Result<(), EngineError> { + if host().request(request_id).is_some() { + return Err(EngineError::NotPending); + } + let proxy = self.proxy().await?; + // The import files every legacy row under the default tenant's + // standard subject, so that is the only scope an orphan lives in. + let scope = self.history_scope(&proxy, &Tenant::default()).await?; + let row = scope + .rows + .row(request_id) + .await + .map_err(EngineError::Unavailable)? + .map(|stored| stored.row) + .filter(|row| { + row.state == ApprovalLifecycle2::Pending + && row.legacy_history_json.is_some() + && row.expires_at_ms > now_ms() + }) + .ok_or(EngineError::NotPending)?; + if !host().begin_orphan_review(row) { + return Err(unavailable( + "the earlier request is already being dismissed", + )); + } + let ticket = opaque(); + host().issue( + ticket.clone(), + Ticket::new( + request_id.to_owned(), + ApprovalChoice2::Deny, + ACTOR.to_owned(), + ), + ); + let decided = async { + let _guard = scope.stream.lock().await; + let generation = Self::generation(&proxy).await?; + let audit = Self::correlation(&scope, generation).await?; + proxy + .call_confidential::( + names::methods::DECIDE2, + (DecideRequest2 { + scope_id: scope.scope_id.clone(), + request_id: request_id.to_owned(), + decision_ticket: ticket.clone(), + audit, + },), + ) + .await + .map_err(|error| { + tracing::debug!(error = %error, "{LOG} the module refused to dismiss the orphan"); + unavailable(format!("TinySecurity Decide2 failed: {error}")) + }) + } + .await; + host().revoke(&ticket); + host().end_orphan_review(request_id); + match decided { + Ok(row) if row.state == ApprovalLifecycle2::Denied => { + if let Err(error) = scope.rows.put_label(request_id, label).await { + tracing::debug!(error = %error, "{LOG} the dismissal label was not kept"); + } + tracing::debug!(request_id = %request_id, "{LOG} dismissed a pending orphan"); + Ok(()) + } + Ok(_) => Err(EngineError::NotPending), + Err(error) => match scope.rows.row(request_id).await { + // A competing decision or the expiry got there first. + Ok(Some(stored)) if stored.row.state != ApprovalLifecycle2::Pending => { + Err(EngineError::NotPending) + } + _ => Err(error), + }, + } + } +} diff --git a/crates/openhuman-core/src/security/approval/native/history_import.rs b/crates/openhuman-core/src/security/approval/native/history_import.rs index d2482cc5c49..ff0e4defb0b 100644 --- a/crates/openhuman-core/src/security/approval/native/history_import.rs +++ b/crates/openhuman-core/src/security/approval/native/history_import.rs @@ -347,7 +347,9 @@ impl NativeEngine { ) -> Result, EngineError> { let subject = self.subject(tenant, Variant::Standard)?; let generation = Self::generation(proxy).await?; - scopes::ensure( + // The import and an orphan's dismissal only need the scope to exist; + // a live check's posture for the same subject stays as it is. + scopes::ensure_keeping_posture( self.config(), proxy, subject, diff --git a/crates/openhuman-core/src/security/approval/native/mod.rs b/crates/openhuman-core/src/security/approval/native/mod.rs index 6517a820300..a0d9d6c5054 100644 --- a/crates/openhuman-core/src/security/approval/native/mod.rs +++ b/crates/openhuman-core/src/security/approval/native/mod.rs @@ -13,6 +13,7 @@ //! | File | Role | //! | --- | --- | //! | `engine.rs` | `NativeEngine`, the module calls | +//! | `engine_orphans.rs` | denying a pending orphan an earlier launch left | //! | `scopes.rs` | subject registration, posture and grants | //! | `audit_stream.rs` | a subject's audit stream, leased by the sandbox planner | //! | `rows.rs` | the document-port store behind `Load`, `Cas` and `Append` | diff --git a/crates/openhuman-core/src/security/approval/native/scopes.rs b/crates/openhuman-core/src/security/approval/native/scopes.rs index 506175b682b..2cd5f2a9235 100644 --- a/crates/openhuman-core/src/security/approval/native/scopes.rs +++ b/crates/openhuman-core/src/security/approval/native/scopes.rs @@ -135,6 +135,7 @@ impl ScopeEntry { posture: &Posture, generation: u64, preconfigured: bool, + keep_existing: bool, ) -> Result<(), String> { let grants = grants(); let fingerprint = serde_json::to_string(&( @@ -144,7 +145,7 @@ impl ScopeEntry { )) .map_err(|error| error.to_string())?; let mut registered = self.registered.lock().await; - if registered.as_deref() == Some(fingerprint.as_str()) { + if !needs_registration(registered.as_deref(), &fingerprint, keep_existing) { return Ok(()); } let first = registered.is_none(); @@ -277,7 +278,36 @@ pub(super) async fn ensure( posture: &Posture, generation: u64, ) -> Result, String> { - ensure_with_registration(config, proxy, subject, posture, generation, false).await + ensure_with_registration(config, proxy, subject, posture, generation, false, false).await +} + +/// [`ensure`] for a caller that needs the subject's scope registered but has +/// no posture of its own to impose, such as the legacy import or dismissing +/// an orphan. `fallback` is registered only when the module holds nothing for +/// the subject yet; a scope a live check already registered keeps its posture, +/// so this caller never makes an unrelated call prompt or pass differently. +pub(super) async fn ensure_keeping_posture( + config: &Config, + proxy: &SecurityProxy, + subject: SubjectScope, + fallback: &Posture, + generation: u64, +) -> Result, String> { + ensure_with_registration(config, proxy, subject, fallback, generation, false, true).await +} + +/// Whether `posture_fingerprint` must be registered over what the module holds +/// (`registered`). `keep_existing` accepts any registration already in place. +fn needs_registration( + registered: Option<&str>, + posture_fingerprint: &str, + keep_existing: bool, +) -> bool { + match registered { + None => true, + Some(_) if keep_existing => false, + Some(current) => current != posture_fingerprint, + } } async fn ensure_with_registration( @@ -287,6 +317,7 @@ async fn ensure_with_registration( posture: &Posture, generation: u64, preconfigured: bool, + keep_existing: bool, ) -> Result, String> { let key = subject_key(&subject); let entry = { @@ -305,7 +336,7 @@ async fn ensure_with_registration( } }; entry - .register(proxy, posture, generation, preconfigured) + .register(proxy, posture, generation, preconfigured, keep_existing) .await?; Ok(entry) } diff --git a/crates/openhuman-core/src/security/approval/native/scopes_tests.rs b/crates/openhuman-core/src/security/approval/native/scopes_tests.rs index c9c70ec477d..fabd8385845 100644 --- a/crates/openhuman-core/src/security/approval/native/scopes_tests.rs +++ b/crates/openhuman-core/src/security/approval/native/scopes_tests.rs @@ -94,3 +94,17 @@ fn a_sweep_is_due_once_per_interval() { assert!(!scope.sweep_due(std::time::Duration::from_secs(30))); assert!(scope.sweep_due(std::time::Duration::ZERO)); } + +#[test] +fn a_posture_free_caller_never_replaces_a_live_scopes_posture() { + let live = r#"[true,true,[]]"#; + let conservative = r#"[true,false,[]]"#; + // A check registers the posture it needs, replacing a different one. + assert!(needs_registration(None, live, false)); + assert!(needs_registration(Some(conservative), live, false)); + assert!(!needs_registration(Some(live), live, false)); + // The import or an orphan's dismissal registers its fallback only on a + // scope the module holds nothing for, and otherwise leaves it alone. + assert!(needs_registration(None, conservative, true)); + assert!(!needs_registration(Some(live), conservative, true)); +} diff --git a/crates/openhuman-core/src/security/approval/native/state.rs b/crates/openhuman-core/src/security/approval/native/state.rs index 806f427ed3e..419c6452316 100644 --- a/crates/openhuman-core/src/security/approval/native/state.rs +++ b/crates/openhuman-core/src/security/approval/native/state.rs @@ -96,6 +96,9 @@ pub(super) struct Host { secret_grants: Mutex>, requests: Mutex>, tickets: Mutex>, + /// Pending orphans a person is dismissing, by request id: the row as listed, + /// which the module's human verification must match byte for byte. + orphan_reviews: Mutex>, } /// One in-flight native master grant whose module-side keyed call correlation is @@ -122,6 +125,7 @@ pub(super) fn host() -> &'static Host { secret_grants: Mutex::new(HashMap::new()), requests: Mutex::new(HashMap::new()), tickets: Mutex::new(HashMap::new()), + orphan_reviews: Mutex::new(HashMap::new()), }) } @@ -274,6 +278,25 @@ impl Host { pub(super) fn revoke(&self, ticket: &str) { lock(&self.tickets).remove(ticket); } + + /// Hold the orphan row a person is dismissing until the module has verified + /// the denial. `false` when it is already under review or too many are. + pub(super) fn begin_orphan_review(&self, row: ApprovalRow2) -> bool { + let mut reviews = lock(&self.orphan_reviews); + if reviews.contains_key(&row.request_id) || reviews.len() >= CAPACITY { + return false; + } + reviews.insert(row.request_id.clone(), row); + true + } + + pub(super) fn orphan_review(&self, request_id: &str) -> Option { + lock(&self.orphan_reviews).get(request_id).cloned() + } + + pub(super) fn end_orphan_review(&self, request_id: &str) { + lock(&self.orphan_reviews).remove(request_id); + } } fn now_ms() -> u64 { diff --git a/crates/openhuman-core/src/security/approval/native/tool_trust.rs b/crates/openhuman-core/src/security/approval/native/tool_trust.rs deleted file mode 100644 index ada49262021..00000000000 --- a/crates/openhuman-core/src/security/approval/native/tool_trust.rs +++ /dev/null @@ -1,138 +0,0 @@ -//! Whole-tool trust methods on the native approval engine. - -use tinysecurity_bus::{ - names, GrantToolRequest2, ListToolTrustRequest2, RevokeToolByIdRequest2, ToolTrustList2, - ToolTrustOutcome2, ToolTrustReceipt2, -}; - -use super::super::super::engine::{EngineError, Posture, Variant}; -use super::super::super::types::ToolTrustEntry; -use super::scopes; -use super::{unavailable, NativeEngine, LOG}; - -impl NativeEngine { - pub(super) async fn grant_tool_trust( - &self, - tenant: &crate::core::runtime::Tenant, - variant: Variant, - tool: &str, - ) -> Result<(), EngineError> { - if variant != Variant::Standard { - return Err(unavailable( - "whole-tool grants are unavailable for strict or forced approval scopes", - )); - } - let proxy = self.proxy().await?; - let subject = self.subject(tenant, variant)?; - let scope = scopes::existing(&subject).await.ok_or_else(|| { - unavailable("the parked request's TinySecurity approval scope is unavailable") - })?; - let _guard = scope.stream.lock().await; - let generation = Self::generation(&proxy).await?; - let audit = Self::correlation(&scope, generation).await?; - let receipt: ToolTrustReceipt2 = proxy - .call_confidential( - names::methods::GRANT_TOOL2, - (GrantToolRequest2 { - scope_id: scope.scope_id.clone(), - tool: tool.to_owned(), - audit, - },), - ) - .await - .map_err(|error| { - tracing::warn!(error = %error, "{LOG} the module refused the whole-tool grant"); - unavailable(format!("TinySecurity GrantTool2 failed: {error}")) - })?; - if receipt.scope_id != scope.scope_id - || !matches!( - receipt.outcome, - ToolTrustOutcome2::Granted | ToolTrustOutcome2::Unchanged - ) - { - return Err(unavailable( - "TinySecurity returned a mismatched whole-tool grant receipt", - )); - } - tracing::debug!(outcome = ?receipt.outcome, "{LOG} whole-tool grant recorded"); - Ok(()) - } - - pub(super) async fn tool_trust( - &self, - tenant: &crate::core::runtime::Tenant, - variant: Variant, - posture: Posture, - ) -> Result, EngineError> { - if variant != Variant::Standard { - return Err(unavailable( - "whole-tool grants are unavailable for strict or forced approval scopes", - )); - } - let proxy = self.proxy().await?; - let scope = self.tool_scope(&proxy, tenant, &posture).await?; - let _guard = scope.stream.lock().await; - let listed: ToolTrustList2 = proxy - .call_confidential( - names::methods::LIST_TOOL_TRUST2, - (ListToolTrustRequest2 { - scope_id: scope.scope_id.clone(), - },), - ) - .await - .map_err(|error| unavailable(format!("TinySecurity ListToolTrust2 failed: {error}")))?; - Ok(listed - .entries - .into_iter() - .map(|entry| ToolTrustEntry { - tool: entry.tool, - request_id: entry.request_id, - granted_at_ms: entry.granted_at_ms, - }) - .collect()) - } - - pub(super) async fn revoke_tool_trust_by_id( - &self, - tenant: &crate::core::runtime::Tenant, - variant: Variant, - posture: Posture, - request_id: &str, - ) -> Result { - if variant != Variant::Standard { - return Err(unavailable( - "whole-tool grants are unavailable for strict or forced approval scopes", - )); - } - let proxy = self.proxy().await?; - let scope = self.tool_scope(&proxy, tenant, &posture).await?; - let _guard = scope.stream.lock().await; - let generation = Self::generation(&proxy).await?; - let audit = Self::correlation(&scope, generation).await?; - let receipt: ToolTrustReceipt2 = proxy - .call_confidential( - names::methods::REVOKE_TOOL_BY_ID2, - (RevokeToolByIdRequest2 { - scope_id: scope.scope_id.clone(), - request_id: request_id.to_owned(), - audit, - },), - ) - .await - .map_err(|error| { - tracing::warn!(error = %error, "{LOG} the module refused to revoke whole-tool trust"); - unavailable(format!("TinySecurity RevokeToolById2 failed: {error}")) - })?; - if receipt.scope_id != scope.scope_id - || !matches!( - receipt.outcome, - ToolTrustOutcome2::Revoked | ToolTrustOutcome2::Absent - ) - { - return Err(unavailable( - "TinySecurity returned a mismatched whole-tool revocation receipt", - )); - } - Ok(receipt.outcome == ToolTrustOutcome2::Revoked) - } -} diff --git a/crates/openhuman-core/src/security/approval/native/view.rs b/crates/openhuman-core/src/security/approval/native/view.rs index 49c2ae9f2c9..831a82686a4 100644 --- a/crates/openhuman-core/src/security/approval/native/view.rs +++ b/crates/openhuman-core/src/security/approval/native/view.rs @@ -156,24 +156,37 @@ pub(crate) async fn orphans( .map_err(|error| anyhow::anyhow!(error))?; Ok(open .iter() - .map(|stored| &stored.row) - .filter(|row| !live(&row.request_id)) - .map(|row| { - let mut pending = PendingApproval::new( - row.request_id.clone(), - row.tool_name.clone(), - row.summary.clone(), - serde_json::from_str::(&row.args_redacted).unwrap_or(Value::Null), - Some(instant( - i64::try_from(row.expires_at_ms).unwrap_or(i64::MAX), - )), - ); - pending.created_at = instant(i64::try_from(row.created_at_ms).unwrap_or(i64::MAX)); - pending - }) + .filter_map(|stored| orphan(&stored.row, &live)) .collect()) } +/// `row` as a pending orphan, or `None` when it is not one. +/// +/// Only the legacy import writes an orphan, and only it sets +/// `legacy_history_json`. A row of this launch never carries it, so a request +/// this process parks is never mistaken for an orphan, even in the moment +/// between the module storing its row and the host registering it, or after +/// the host has let it go but before its decision lands. +fn orphan(row: &ApprovalRow2, live: impl Fn(&str) -> bool) -> Option { + if row.state != ApprovalLifecycle2::Pending + || row.legacy_history_json.is_none() + || live(&row.request_id) + { + return None; + } + let mut pending = PendingApproval::new( + row.request_id.clone(), + row.tool_name.clone(), + row.summary.clone(), + serde_json::from_str::(&row.args_redacted).unwrap_or(Value::Null), + Some(instant( + i64::try_from(row.expires_at_ms).unwrap_or(i64::MAX), + )), + ); + pending.created_at = instant(i64::try_from(row.created_at_ms).unwrap_or(i64::MAX)); + Some(pending) +} + /// Whether the request was stored and has left `Pending`. `None` when it is not /// stored at all. pub(crate) async fn row_decided(config: &Config, request_id: &str) -> anyhow::Result> { diff --git a/crates/openhuman-core/src/security/approval/native/view_tests.rs b/crates/openhuman-core/src/security/approval/native/view_tests.rs index 92cfa0cdf2f..2da12f38dde 100644 --- a/crates/openhuman-core/src/security/approval/native/view_tests.rs +++ b/crates/openhuman-core/src/security/approval/native/view_tests.rs @@ -201,3 +201,21 @@ fn an_imported_legacy_request_keeps_the_request_id_it_had_in_the_earlier_version let shown = entry(&stored(imported.clone()), None).unwrap(); assert_eq!(shown.request_id, imported.request_id); } + +#[test] +fn only_an_imported_pending_row_no_live_request_owns_is_an_orphan() { + let mut imported = row(ApprovalLifecycle2::Pending); + imported.legacy_history_json = Some(r#"{"state":"pending"}"#.into()); + let listed = orphan(&imported, |_| false).expect("an imported pending row is an orphan"); + assert_eq!(listed.request_id, imported.request_id); + assert_eq!(listed.tool_name, "gmail_send"); + + // A request this launch parked carries no legacy record: it is never + // listed as an orphan, even while the host does not hold it. + assert!(orphan(&row(ApprovalLifecycle2::Pending), |_| false).is_none()); + // One the host is waiting on is its own, imported or not. + assert!(orphan(&imported, |_| true).is_none()); + // A decided row is history, not pending. + imported.state = ApprovalLifecycle2::Denied; + assert!(orphan(&imported, |_| false).is_none()); +} diff --git a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs deleted file mode 100644 index ff68201189e..00000000000 --- a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs +++ /dev/null @@ -1,301 +0,0 @@ -//! Forked (`QueueMode::Parallel`) turns: spawning one alongside whatever is -//! already in flight on a thread, and the request- or thread-scoped -//! cancellation paths that tear them down. - -use std::sync::Arc; -use std::time::Duration; - -use tinyagents_harness::run_queue::RunQueue; -use tokio_util::sync::CancellationToken; - -use crate::web_chat::WebChannelEvent; - -use super::super::event_bus::publish_web_channel_event_in; -use super::super::run_task::run_chat_task; -use super::super::types::{ChatRequestMetadata, ParallelEntry}; -use super::super::web_errors::classify_inference_error; -use super::state::{key_for, parallel_in_flight, unscope}; -use super::turn_guards::{ - run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag, -}; - -/// Spawn an independent, forked (`QueueMode::Parallel`) turn. It snapshots the -/// thread's history-at-start (inside `run_chat_task` with `fork = true`), runs -/// concurrently with any other turn on the thread, and on completion delivers -/// its response (append-only) and removes itself from [`parallel_in_flight`]. -/// Emits the same per-`request_id` stream events as a primary turn, so the UI -/// can render it as an interleaved branch. -#[allow(clippy::too_many_arguments)] -pub(crate) async fn spawn_parallel_turn( - ctx: &crate::core::runtime::DispatchCtx, - client_id: &str, - thread_id: &str, - request_id: String, - message: &str, - model_override: Option, - temperature: Option, - locale: Option, - metadata: ChatRequestMetadata, -) { - let cancel_token = CancellationToken::new(); - let task_cancel_token = cancel_token.clone(); - - let client_id_task = client_id.to_string(); - let thread_id_task = thread_id.to_string(); - let request_id_task = request_id.clone(); - // Request and thread ids are caller-chosen and only unique per agent, so - // the table is keyed in the caller's scope (see `key_for`). - let map_key = key_for(ctx, &request_id); - let map_key_task = map_key.clone(); - let user_message = message.to_string(); - let ctx_task = ctx.clone(); - // Forked turns don't participate in the steer/followup/collect queue, but - // `run_chat_task` requires a queue handle — give each its own. - let run_queue = Arc::new(RunQueue::new()); - - let handle = tokio::spawn(crate::core::runtime::context::CoreContext::propagate( - async move { - let approval_ctx = crate::security::approval::ApprovalChatContext { - thread_id: thread_id_task.clone(), - client_id: client_id_task.clone(), - request_id: Some(request_id_task.clone()), - }; - let origin = crate::core::runtime::turn_origin::AgentTurnOrigin::WebChat { - thread_id: thread_id_task.clone(), - client_id: client_id_task.clone(), - request_id: Some(request_id_task.clone()), - }; - let result = run_turn_under_cancel_and_deadline( - &ctx_task, - task_cancel_token, - origin.clone(), - approval_ctx, - |host_env, activity, approval| { - run_chat_task( - &ctx_task, - &client_id_task, - &thread_id_task, - &request_id_task, - &user_message, - model_override, - temperature, - locale, - run_queue, - metadata, - origin.clone(), - /* fork */ true, - host_env, - activity, - approval, - ) - }, - ) - .await; - - match result { - Some(Ok(chat_result)) => { - crate::web_chat::presentation::deliver_response( - &ctx_task, - &client_id_task, - &thread_id_task, - &request_id_task, - &chat_result.full_response, - &user_message, - &chat_result.citations, - chat_result.usage.as_ref(), - // The workspace the turn ran in, so the reply is stored - // there before it is announced (#6034). - Some(chat_result.workspace_dir.as_path()), - chat_result.timing, - // Parallel-fork delivery has no single human waiting - // on a next-message suggestion for this reply (C5). - false, - ) - .await; - } - Some(Err(err)) => { - log::warn!( - "[web-channel] parallel run_chat_task failed client_id={} thread_id={} request_id={} error={}", - client_id_task, - thread_id_task, - request_id_task, - err - ); - let detailed = format!( - "parallel run_chat_task failed client_id={} thread_id={} request_id={} error={}", - client_id_task, thread_id_task, request_id_task, err - ); - let classified = classify_inference_error(&err); - let classified_type = classified.error_type; - - // A parallel turn runs under the same deadline wrapper as the - // serial one and dies the same way, but this branch reported - // NOTHING to Sentry — not merely the timeouts this PR - // un-suppresses, but every error type, since the parallel path - // was added. So a discarded turn was invisible here even - // before the suppression arm existed, and fixing only - // `start_chat` would have left `QueueMode::Parallel` exactly - // as blind as it was (#5804 review). - // - // Same policy as the serial site, deliberately sharing - // `sentry_suppression_reason` rather than restating it: the - // outer backstop stays suppressed, a harness `Timeout` reports - // with the ceiling that fired. - if let Some(reason) = sentry_suppression_reason(&detailed) { - log::info!( - target: "web_channel", - "[web_channel.spawn_parallel_turn] suppressed Sentry emission for {} \ - client_id={} thread_id={} request_id={} error_type={} message={}", - reason, - client_id_task, - thread_id_task, - request_id_task, - classified_type, - detailed - ); - } else { - crate::core::observability::report_error_or_expected( - detailed.as_str(), - "web_channel", - "spawn_parallel_turn", - &[ - ("channel", "web"), - ("error_type", classified_type), - ("thread_id", thread_id_task.as_str()), - ("request_id", request_id_task.as_str()), - ("queue_mode", "parallel"), - ("timeout_bound", timeout_bound_tag(&detailed)), - ], - ); - } - - publish_web_channel_event_in( - &ctx_task, - WebChannelEvent { - event: "chat_error".to_string(), - client_id: client_id_task.clone(), - thread_id: thread_id_task.clone(), - request_id: request_id_task.clone(), - message: Some(classified.message), - error_type: Some(classified.error_type.to_string()), - error_source: Some(classified.source.to_string()), - error_retryable: Some(classified.retryable), - error_retry_after_ms: classified.retry_after_ms, - error_provider: classified.provider, - error_fallback_available: classified.fallback_available, - copy_key: Some(classified.copy_key.to_string()), - copy_params: classified.copy_params, - ..Default::default() - }, - ); - } - None => { - log::info!( - "[web-channel] parallel turn cancelled cooperatively thread_id={} request_id={}", - thread_id_task, - request_id_task - ); - // Cooperative cancel (deadline/cancel token) publishes no - // `chat_error` on this path today — leaving a client - // waiting on this request_id with no terminal event. - // `chat_cancelled` closes it out. - publish_web_channel_event_in( - &ctx_task, - WebChannelEvent { - event: "chat_cancelled".to_string(), - client_id: client_id_task.clone(), - thread_id: thread_id_task.clone(), - request_id: request_id_task.clone(), - cancel_reason: Some("user_stop".to_string()), - ..Default::default() - }, - ); - } - } - - parallel_in_flight(&ctx_task) - .lock_owned() - .await - .remove(&map_key_task); - }, - )); - - parallel_in_flight(ctx).lock_owned().await.insert( - map_key, - ParallelEntry { - thread_id: key_for(ctx, thread_id), - client_id: client_id.to_string(), - handle, - cancel_token, - }, - ); -} - -/// Cooperatively cancel every parallel turn on a thread. Returns the cancelled -/// `(request_id, client_id)` pairs. Used by the thread-level cancel paths so a cancel/stop also -/// tears down any concurrent forked turns, not just the primary turn. -pub(crate) async fn cancel_parallel_turns_for_thread( - ctx: &crate::core::runtime::DispatchCtx, - thread_id: &str, -) -> Vec<(String, String)> { - let mut cancelled = Vec::new(); - let scoped_thread = key_for(ctx, thread_id); - let mut parallel = parallel_in_flight(ctx).lock_owned().await; - let request_ids: Vec = parallel - .iter() - .filter(|(_, entry)| entry.thread_id == scoped_thread) - .map(|(request_id, _)| request_id.clone()) - .collect(); - for request_id in request_ids { - if let Some(entry) = parallel.remove(&request_id) { - entry.cancel_token.cancel(); - let mut handle = entry.handle; - tokio::spawn(async move { - tokio::select! { - _ = &mut handle => {} - _ = tokio::time::sleep(Duration::from_secs(5)) => { - handle.abort(); - } - } - }); - cancelled.push((unscope(ctx, &request_id), entry.client_id)); - } - } - cancelled -} - -/// Cancel a single parallel (forked) turn identified by `request_id`, but only -/// when it belongs to `thread_id`. Returns the cancelled id (as a one-element -/// vec of `(request_id, client_id)`, mirroring [`cancel_parallel_turns_for_thread`]) or empty when no such -/// parallel turn exists. Request-scoped cancel path (#4760). -pub(crate) async fn cancel_parallel_turn_by_request_id( - ctx: &crate::core::runtime::DispatchCtx, - thread_id: &str, - request_id: &str, -) -> Vec<(String, String)> { - let map_key = key_for(ctx, request_id); - let scoped_thread = key_for(ctx, thread_id); - let mut parallel = parallel_in_flight(ctx).lock_owned().await; - let matches = parallel - .get(&map_key) - .map(|entry| entry.thread_id == scoped_thread) - .unwrap_or(false); - if !matches { - return Vec::new(); - } - if let Some(entry) = parallel.remove(&map_key) { - entry.cancel_token.cancel(); - let client_id = entry.client_id.clone(); - let mut handle = entry.handle; - tokio::spawn(async move { - tokio::select! { - _ = &mut handle => {} - _ = tokio::time::sleep(Duration::from_secs(5)) => { - handle.abort(); - } - } - }); - return vec![(request_id.to_string(), client_id)]; - } - Vec::new() -} diff --git a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs deleted file mode 100644 index 8e7efb7b827..00000000000 --- a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs +++ /dev/null @@ -1,374 +0,0 @@ -//! The standard web-channel turn guards — the idle guard, the wall-clock -//! backstop and cooperative cancellation — plus the Sentry-suppression / -//! timeout-tagging policy applied to whatever error a guarded turn produces. - -use std::time::Duration; - -use tokio_util::sync::CancellationToken; - -use super::super::turn_activity::{self, TurnActivity}; -use super::super::turn_close::{StopCause, StoppedTurn}; -use super::super::types::WebChatTaskResult; -use crate::agent::turn_env::HostTurnEnv; - -/// Resolve the per-turn wall-clock backstop. Returns `None` when disabled -/// (env `OPENHUMAN_WEB_TURN_TIMEOUT_SECS=0`). -/// -/// This is the turn's fixed total ceiling (issue #4746), and the single source -/// of truth for the turn's deadlines (`web_chat::turn_guards::backstop`, default 3600s, -/// the harness's own turn ceiling). The harness derives two earlier points -/// from it: -/// -/// * **wind-down** at backstop minus `min(120s, backstop/5)`, 3480s by -/// default. The harness pauses the run at its next safe point, and the -/// session driver writes the grounded close from the work already done, so a -/// long turn still delivers an answer. -/// * **hard stop** at backstop minus `min(60s, backstop/10)`, 3540s by default. -/// The harness policy's `max_wall_clock_ms` (`tinyagents::run_policy_for`) -/// is clamped to it, so a tool or sub-agent call that runs across the -/// wind-down point ends in the harness's own typed `Timeout` → `chat_error`. -/// -/// It is not the hang detector. That is the idle guard -/// ([`turn_activity`](super::super::turn_activity)), which ends a turn that has -/// been silent with no model or tool call in flight. The backstop used to be -/// both, at 900s: a turn working steadily for 15 minutes was dropped exactly -/// like a wedged one. Override via `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`; set it to -/// `0` to disable the backstop and the derived deadlines with it. -fn web_turn_deadline() -> Option { - crate::web_chat::turn_guards::backstop::configured_backstop() -} - -/// The backstop for a turn that has to be allowed to run long: one on a local / -/// self-hosted provider (#6042), whose prefill alone can take many minutes. The -/// explicit `OPENHUMAN_WEB_TURN_TIMEOUT_SECS` override still wins; otherwise the -/// default is the local turn ceiling plus a grace period, never the hosted -/// backstop, which sits below the local harness ceilings and would pre-empt them. -async fn resolve_web_turn_deadline(ctx: &crate::core::runtime::DispatchCtx) -> Option { - if std::env::var("OPENHUMAN_WEB_TURN_TIMEOUT_SECS").is_ok() { - return web_turn_deadline(); - } - let local = match ctx.load_config().await { - Ok(config) => crate::agent::tinyagents::chat_provider_is_local(&config), - Err(error) => { - log::debug!("[web-channel] backstop locality probe skipped: {error}"); - false - } - }; - if local { - let secs = crate::agent::tinyagents::local_web_turn_backstop_secs(); - log::debug!("[web-channel] local provider: turn backstop {secs:?}s (#6042)"); - return secs.map(Duration::from_secs); - } - web_turn_deadline() -} - -/// The turn a guard may have to close: its thread and request ids. -pub(super) struct TurnIds { - pub(super) thread_id: String, - pub(super) request_id: String, -} - -/// Upper bound on closing a stopped turn: config, snapshot read and the -/// closing model call (itself bounded at 45s). Past it the stop is reported as -/// a `turn_timeout` error, so closing can never be what hangs the turn. -const CLOSE_REPLY_BUDGET: Duration = Duration::from_secs(60); - -/// Which guard stopped the turn. -enum Stop { - Ceiling(Duration), - Idle(Duration), -} - -/// Drive a chat-turn future under the idle guard and the wall-clock backstop. -/// -/// Either guard drops the inner future (cooperative teardown at its next -/// await point). The turn is then closed with a reply that says what it got -/// done and where it got stuck ([`turn_close`](super::super::turn_close)), -/// delivered like any other reply. Without `ids`, or when that reply cannot be -/// built, a synthetic `turn_timeout` error is returned instead, so the -/// caller's existing `chat_error` emission path fires. Either way a wedged -/// turn always ends in a terminal event rather than an empty reply / an -/// endless `inference_heartbeat` stream (issue #4746). -/// -/// The idle guard fires first for a turn that stopped emitting progress with -/// nothing in flight; the backstop bounds a turn that stays busy past the -/// harness wind-down. `run_chat_task` taps the turn's progress stream into the -/// [`TurnActivity`] built here and handed to the turn. -async fn drive_turn_with_deadline( - ctx: &crate::core::runtime::DispatchCtx, - deadline: Option, - idle_window: Option, - ids: Option, - build: B, -) -> Result -where - B: FnOnce(TurnActivity) -> F, - F: std::future::Future>, -{ - let activity = TurnActivity::new(); - // The turn future is boxed: it is very large, and the scope wrappers would - // otherwise hold it inline again and overflow the worker stack. It receives - // the activity record explicitly. - let turn = Box::pin(build(activity.clone())); - let bounded_turn = async move { - let Some(d) = deadline else { - return Ok(turn.await); - }; - // The session turn carries the matching `TurnDeadline` on its explicit - // host environment (`run_turn_under_cancel_and_deadline`), so the - // harness (`web_chat::turn_guards::backstop`) winds down before `d`. - tokio::time::timeout(d, turn) - .await - .map_err(|_elapsed| Stop::Ceiling(d)) - }; - let watched = activity.clone(); - let watchdog = async move { - match idle_window { - Some(window) => turn_activity::idle_watchdog(watched, window).await, - None => std::future::pending().await, - } - }; - let stop = tokio::select! { - biased; - res = bounded_turn => match res { - Ok(res) => return res, - Err(stop) => stop, - }, - idle = watchdog => Stop::Idle(idle), - }; - let stuck = activity.stuck_point(); - let (cause, fallback) = match stop { - Stop::Ceiling(d) => { - log::warn!( - "[web-channel] turn wall-clock backstop fired after {}s with no terminal event \ - (the harness wind-down did not close the turn in time); stuck={stuck:?} \ - (issue #4746)", - d.as_secs() - ); - ( - StopCause::Ceiling(d), - super::super::web_errors::turn_timeout_error_message(d.as_secs()), - ) - } - Stop::Idle(idle) => { - log::warn!( - "[web-channel] turn idle guard fired: no progress for {}s with no model or tool \ - call in flight; stuck={stuck:?}", - idle.as_secs() - ); - ( - StopCause::Idle(idle), - super::super::web_errors::turn_idle_error_message(idle.as_secs()), - ) - } - }; - let Some(ids) = ids else { - return Err(fallback); - }; - let (config, locale) = activity.turn_context(); - let stopped = StoppedTurn { - thread_id: &ids.thread_id, - request_id: &ids.request_id, - cause, - stuck, - config, - locale, - ctx: ctx.clone(), - }; - let close = super::super::turn_close::close_reply(stopped); - match tokio::time::timeout(CLOSE_REPLY_BUDGET, close).await { - Ok(Some(reply)) => Ok(reply), - Ok(None) => Err(fallback), - Err(_) => { - log::warn!( - "[web-channel] closing the stopped turn took over {}s; reporting turn_timeout", - CLOSE_REPLY_BUDGET.as_secs() - ); - Err(fallback) - } - } -} - -/// The host environment a guarded turn runs with: its own session cancellation -/// (returned too, so a Stop can fire it) and the `TurnDeadline` derived from the -/// backstop, `None` when the backstop is disabled. -fn turn_host_env( - backstop: Option, -) -> (HostTurnEnv, tinyagents_harness::cancel::CancellationToken) { - let turn_cancellation = tinyagents_harness::cancel::CancellationToken::new(); - let env = HostTurnEnv { - cancellation: Some(turn_cancellation.clone()), - turn_deadline: backstop.map(tinyagents_harness::turn_deadline::TurnDeadline::starting_now), - ..HostTurnEnv::default() - }; - (env, turn_cancellation) -} - -/// Run a chat-turn future under the standard web-channel guards, inside the -/// shared origin + approval-context scope: the cooperative cancel token -/// (interrupt/cancel paths tear the turn down at its next await point), the -/// idle guard and the wall-clock backstop ([`drive_turn_with_deadline`]). -/// -/// Returns `None` when the turn was cancelled cooperatively before producing a -/// result — the cancelling side already emitted the user-facing `chat_error`, -/// so the caller just unwinds quietly (see [`run_until_stopped`]). Otherwise `Some(res)` carries the turn's -/// `Result`. Extracted so `start_chat` and `spawn_parallel_turn` share one copy -/// of this wiring and can't drift apart (issue #4746 review); the only per-site -/// differences are the `fork` flag and run-queue handle passed to -/// `run_chat_task` when building `fut`. -/// -/// `build_turn` receives the turn's [`HostTurnEnv`] -- its own cancellation -/// token (fired by a Stop) and the backstop's [`TurnDeadline`] -- the guard's -/// [`TurnActivity`] record and the turn's [`ApprovalTurnContext`], and returns -/// the turn future, which hands the env to the session it runs. The env is an -/// explicit value, so it reaches the turn's whole run tree without any ambient -/// scope. -/// -/// [`TurnDeadline`]: tinyagents_harness::turn_deadline::TurnDeadline -pub(crate) async fn run_turn_under_cancel_and_deadline( - ctx: &crate::core::runtime::DispatchCtx, - cancel_token: CancellationToken, - origin: crate::core::runtime::turn_origin::AgentTurnOrigin, - approval_ctx: crate::security::approval::ApprovalChatContext, - build_turn: B, -) -> Option> -where - B: FnOnce(HostTurnEnv, TurnActivity, crate::security::approval::ApprovalTurnContext) -> F, - F: std::future::Future>, -{ - let ids = approval_ctx.request_id.clone().map(|request_id| TurnIds { - thread_id: approval_ctx.thread_id.clone(), - request_id, - }); - let deadline = resolve_web_turn_deadline(ctx).await; - let (env, turn_cancellation) = turn_host_env(deadline); - run_until_stopped( - cancel_token, - turn_cancellation, - drive_turn_with_deadline( - ctx, - deadline, - turn_activity::configured_idle_window(), - ids, - |activity| { - crate::core::runtime::turn_origin::with_origin( - origin, - build_turn( - env, - activity, - crate::security::approval::ApprovalTurnContext::chat(approval_ctx), - ), - ) - }, - ), - ) - .await -} - -/// Drive `turn` until it finishes or `cancel_token` fires. -/// -/// The turn runs under its own session cancellation (`turn_cancellation`, -/// which the turn's host environment hands to its run tree). A Stop fires it rather than -/// only dropping the turn, so the session driver can hand back the rounds it -/// already completed and the runtime persists them (#7715). The turn then gets -/// [`STOPPED_TURN_PERSIST_GRACE`] to finish before it is dropped; its result is -/// discarded either way. -async fn run_until_stopped( - cancel_token: CancellationToken, - turn_cancellation: tinyagents_harness::cancel::CancellationToken, - turn: impl std::future::Future, -) -> Option { - // Boxed rather than stack-pinned: a chat turn's future is very large. - let mut turn = Box::pin(turn); - tokio::select! { - biased; - _ = cancel_token.cancelled() => { - turn_cancellation.cancel(); - let persisted = tokio::time::timeout(STOPPED_TURN_PERSIST_GRACE, &mut turn).await; - log::debug!( - "[web-channel] stopped turn unwound within grace={}", - persisted.is_ok() - ); - None - } - res = &mut turn => Some(res), - } -} - -/// How long a cancelled turn may keep running so the session runtime can -/// persist its completed rounds. Just above the runtime's own 2 s driver -/// grace; the user-facing `chat_cancelled` has already been sent. -const STOPPED_TURN_PERSIST_GRACE: Duration = Duration::from_secs(3); - -/// Reason a terminal `run_chat_task` error should be kept OUT of Sentry, or -/// `None` when it is a genuine defect that must page. -/// -/// A suppressed case is a deterministic, user-surfaced, retryable agent-loop -/// outcome — a terminal `chat_error` already reaches the client, so a Sentry -/// event is pure noise (same tier as `MaxIterationsExceeded` / -/// `EmptyProviderResponse`, which are demoted the same way): -/// -/// - the max-iteration cap (`is_max_iterations_error`), and -/// - the **outer** web-turn wall-clock backstop (`is_outer_backstop_timeout`, -/// issue #4746) — the turn wedged outside the harness and produced no -/// terminal event, so without this arm every such turn would emit a spurious -/// Sentry event, contradicting the graceful `turn_timeout` framing. -/// -/// **Not suppressed: the harness's own `Timeout` (#5804).** This arm used to -/// cover both, via `is_turn_timeout_error`, because the two are hard to tell -/// apart once stringified. They are not the same event. The outer backstop -/// fires with *nothing in flight*; the harness `Timeout` fires while bounding -/// a real model or tool call, which means the run spent its budget doing work -/// — and every result that work produced is discarded along with the turn. A -/// turn that lost eighteen sub-agents' worth of accumulated work was reported -/// here as `suppressed Sentry emission for turn wall-clock backstop` and -/// reached telemetry as nothing at all, which is why the defect survived. See -/// [`is_outer_backstop_timeout`](super::super::web_errors::is_outer_backstop_timeout) -/// for the structural argument. -/// -/// The user-facing classification is deliberately untouched: both still render -/// the graceful `turn_timeout` copy via `is_turn_timeout_error`. Only the -/// telemetry decision splits. -/// -/// Kept as a pure predicate over the already-formatted error string so the -/// suppression policy is unit-testable without a Sentry harness. -pub(crate) fn sentry_suppression_reason(detailed: &str) -> Option<&'static str> { - if tinyagents_harness::agent_error::is_max_iterations_error(detailed) { - Some("max-iteration cap") - } else if super::super::web_errors::is_outer_backstop_timeout(detailed) { - Some("turn wall-clock backstop (no terminal event)") - } else { - None - } -} - -/// Which wall-clock bound a reported timeout hit, as a Sentry tag value. -/// -/// Only meaningful once [`sentry_suppression_reason`] has decided to report — -/// i.e. for a harness `Timeout`, never for the suppressed outer backstop. The -/// crate names the bound in the message (`RUN_BOUND_LABEL` vs -/// `PER_CALL_BOUND_LABEL`), and the two are different triage paths: a run that -/// spent its whole budget doing real work is a capacity/planning problem, while -/// one call that blew a per-call ceiling is a wedged provider. Emitting them -/// under one tag would rebuild, in the dashboard, exactly the conflation this -/// change removed from the code (#5804). -/// -/// The bound is a typed field on the harness's hosted error -/// (`HostedError::timeout_bound`); the turn runner turns it into a -/// [`TurnTimeoutBound`](tinyagents_harness::agent_error::TurnTimeoutBound) phrase in the -/// flattened error, and this function reads that phrase back through the same -/// type rather than a second spelling. Pure over the formatted error string, -/// for the same reason its neighbour is. -pub(crate) fn timeout_bound_tag(detailed: &str) -> &'static str { - if let Some(bound) = tinyagents_harness::agent_error::TurnTimeoutBound::from_message(detailed) { - bound.tag() - } else if super::super::web_errors::is_turn_timeout_error(detailed) { - "unclassified_timeout" - } else { - "none" - } -} - -#[cfg(test)] -#[path = "turn_guards_tests.rs"] -mod tests; diff --git a/crates/openhuman-core/src/web_chat/progress_bridge_attribution.rs b/crates/openhuman-core/src/web_chat/progress_bridge_attribution.rs deleted file mode 100644 index 0d86517ab12..00000000000 --- a/crates/openhuman-core/src/web_chat/progress_bridge_attribution.rs +++ /dev/null @@ -1,14 +0,0 @@ -/// Trace user attribution for a turn whose stored user payload carries no identity -/// (headless / autonomous / freshly booted cores): read the on-disk -/// app-session profile and return the user's email (preferred) or backend -/// user id. `None` when signed out or the profile is unreadable. -async fn session_profile_user_attribution(config: &crate::config::Config) -> Option { - let state = crate::credentials::session_state::build_session_state(config).await.ok()?; - state - .user - .as_ref() - .and_then(|u| u.get("email")) - .and_then(serde_json::Value::as_str) - .map(str::to_string) - .or(state.user_id) -} diff --git a/crates/openhuman-core/src/web_chat/progress_bridge_spawn.rs b/crates/openhuman-core/src/web_chat/progress_bridge_spawn.rs deleted file mode 100644 index 96c9551e9af..00000000000 --- a/crates/openhuman-core/src/web_chat/progress_bridge_spawn.rs +++ /dev/null @@ -1,259 +0,0 @@ -use super::*; - -/// Spawn a background task that reads [`AgentProgress`] events from the -/// agent turn loop and translates them into [`WebChannelEvent`]s tagged -/// with the correct client/thread/request IDs. The task runs until the -/// sender is dropped (i.e. when the agent turn finishes). -pub(crate) fn spawn_progress_bridge( - mut rx: tokio::sync::mpsc::Receiver, - client_id: String, - thread_id: String, - request_id: String, - turn_state_store: std::sync::Arc, - metadata: ChatRequestMetadata, - config: crate::config::Config, - dispatch_ctx: crate::core::runtime::DispatchCtx, -) -> ProgressBridgeHandle { - use crate::progress::AgentProgress; - use std::collections::HashMap; - use tinyagents_session::run_ledger::{ - AgentRunKind, AgentRunStatus, AgentRunUpsert, RunEventAppend, RunTelemetryUpsert, - }; - - let (drained_tx, drained_rx) = tokio::sync::watch::channel(false); - let timing_snapshot: std::sync::Arc< - std::sync::Mutex>, - > = std::sync::Arc::new(std::sync::Mutex::new(None)); - let timing_snapshot_for_task = timing_snapshot.clone(); - dispatch_ctx.clone().spawn(async move { - log::debug!( - "[web_channel][bridge] spawned client_id={} thread_id={} request_id={} speak_reply={:?} source={:?} session_id={:?}", - client_id, - thread_id, - request_id, - metadata.speak_reply, - metadata.source, - metadata.session_id, - ); - let mut round: u32 = 0; - // Accumulates the parent agent's streamed narration for the current - // round. When a tool call closes the round, this leading narration is - // flushed as an interim chat bubble (`chat_interim`) so it persists in - // the thread instead of vanishing on settle — the final answer arrives - // separately via `deliver_response` and is never part of this buffer - // (it belongs to the terminal round, which ends with no tool call). - let mut pending_narration = String::new(); - let mut timing = crate::web_chat::turn_timing::TurnTiming::start(); - let mut turn_cost_throttle = crate::web_chat::turn_timing::TurnCostThrottle::new(); - let mut events_seen: u64 = 0; - // Per-request monotonic ordering key stamped on every emitted - // web-channel event (see `publish_seq_stamped`). Unique per emission so - // the frontend can dedup by `(request_id, seq)`. - let mut emit_seq: u64 = 0; - let mut parent_completed = false; - let mut parent_tool_count: u64 = 0; - let mut child_tool_counts: HashMap = HashMap::new(); - // task_id -> the parent tool-call id that spawned it, remembered from - // `SubagentSpawned` so later lifecycle events for the same task - // (`subagent_completed`/`_failed`/`_awaiting_user`) can still carry - // it even though those `AgentProgress` variants don't repeat it. - let mut subagent_parent_call_ids: HashMap> = HashMap::new(); - let mut turn_state = - TurnStateMirror::new(turn_state_store, thread_id.clone(), request_id.clone()); - - // #3886: structured tracing export (`progress_bridge_trace.rs`). - let mut journal_trace_ctx = - trace::trace_context(&config, &metadata, &client_id, &thread_id, &request_id).await; - - // #4270: emit a periodic liveness beat for the whole in-flight turn so - // the frontend silence timer never false-fires during a long prefill or - // a buffered-reasoning phase that streams no progress events. The beat - // is gated on `turn_active` (set once `TurnStarted` is observed) so we - // never emit before the turn's `inference_start` has armed the timer. - let mut heartbeat = - tokio::time::interval(std::time::Duration::from_secs(INFERENCE_HEARTBEAT_SECS)); - // Wall-clock cadence: a slow turn must not produce a burst of catch-up - // beats once it finally yields control. - heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - // `interval`'s first tick resolves immediately — consume it so the first - // real beat lands one full interval after the turn begins. - heartbeat.tick().await; - let mut turn_active = false; - let bridge_ctx = - BridgeCtx::new(&client_id, &thread_id, &request_id, &config, &dispatch_ctx); - - loop { - let event = tokio::select! { - // Drain real progress events preferentially over the timer so a - // busy turn never starves event handling to emit a beat. - biased; - maybe = rx.recv() => match maybe { - Some(ev) => ev, - None => break, - }, - _ = heartbeat.tick() => { - if turn_active { - log::trace!( - "[web_channel][bridge] inference_heartbeat thread_id={} request_id={}", - thread_id, - request_id, - ); - publish_seq_stamped(&dispatch_ctx, &mut emit_seq, WebChannelEvent { - event: "inference_heartbeat".to_string(), - client_id: client_id.clone(), - thread_id: thread_id.clone(), - request_id: request_id.clone(), - ..Default::default() - }); - } - continue; - } - }; - events_seen += 1; - turn_state.observe(&event); - match &event { - AgentProgress::TextDelta { delta, iteration } => { - log::trace!( - "[web_channel][bridge] text_delta round={} chars={} request_id={}", - iteration, - delta.len(), - request_id, - ); - } - AgentProgress::ThinkingDelta { delta, iteration } => { - log::trace!( - "[web_channel][bridge] thinking_delta round={} chars={} request_id={}", - iteration, - delta.len(), - request_id, - ); - } - AgentProgress::ToolCallArgsDelta { - call_id, - tool_name, - delta, - iteration, - } => { - log::trace!( - "[web_channel][bridge] tool_args_delta round={} tool={} call_id={} chars={} request_id={}", - iteration, - tool_name, - call_id, - delta.len(), - request_id, - ); - } - AgentProgress::ToolCallStarted { - call_id, - tool_name, - iteration, - .. - } => { - log::debug!( - "[web_channel][bridge] tool_call round={} tool={} call_id={} request_id={}", - iteration, - tool_name, - call_id, - request_id, - ); - } - AgentProgress::ToolCallCompleted { - call_id, - tool_name, - success, - iteration, - .. - } => { - log::debug!( - "[web_channel][bridge] tool_result round={} tool={} call_id={} success={} request_id={}", - iteration, - tool_name, - call_id, - success, - request_id, - ); - } - AgentProgress::SubagentFailed { - agent_id, error, .. - } => { - log::warn!( - "[web_channel][bridge] subagent_failed agent_id={} err={} client_id={} thread_id={} request_id={}", - agent_id, - error, - client_id, - thread_id, - request_id, - ); - } - other => { - log::debug!( - "[web_channel][bridge] lifecycle event={:?} request_id={}", - std::mem::discriminant(other), - request_id, - ); - } - } - include!("progress_bridge_event_match.rs"); - } - turn_state.finish(); - if !parent_completed { - ledger_upsert_agent_run( - &config, - AgentRunUpsert { - id: request_id.clone(), - kind: AgentRunKind::BackgroundAgent, - parent_run_id: None, - parent_thread_id: Some(thread_id.clone()), - agent_id: Some("orchestrator".to_string()), - status: AgentRunStatus::Interrupted, - prompt_ref: Some(format!("thread:{thread_id}:request:{request_id}")), - worker_thread_id: None, - checkpoint_path: None, - checkpoint: None, - summary: None, - error: Some("progress bridge exited before turn completion".to_string()), - metadata: json!({}), - started_at: None, - completed_at: Some(chrono::Utc::now()), - }, - ); - ledger_append_event( - &config, - RunEventAppend { - run_id: request_id.clone(), - event_type: "turn_interrupted".to_string(), - payload: json!({ "eventsSeen": events_seen }), - }, - ); - } - // #3886: seal any spans still open after the stream closed and hand the - // run's trace to the configured tracing sink. Best-effort and gated; - // never affects the turn outcome. - // The response presenter waits only briefly for this signal before - // publishing an error. Trace export is best-effort I/O and must not - // hold up terminal delivery after the progress stream closed. - let _ = drained_tx.send(true); - if let Some(trace_ctx) = journal_trace_ctx.take() { - crate::core::observability::progress_tracing::export_run_trace_from_journal( - &dispatch_ctx, - &config, - &request_id, - trace_ctx, - ) - .await; - } - - log::debug!( - "[web_channel][bridge] exit client_id={} thread_id={} request_id={} round={} events_seen={}", - client_id, - thread_id, - request_id, - round, - events_seen, - ); - }); - ProgressBridgeHandle { - drained: drained_rx, - timing: timing_snapshot, - } -} diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs deleted file mode 100644 index b8ddbe7f98e..00000000000 --- a/crates/openhuman-core/src/web_chat/run_task.rs +++ /dev/null @@ -1,423 +0,0 @@ -//! `run_chat_task` — resolves or builds the cached session agent -//! (`session.rs`), spawns the progress bridge alongside the turn, runs it -//! through the agent harness, and applies the per-thread budget correlation -//! to a failed turn. Called from `start_chat` and `spawn_parallel_turn` -//! (`ops/start_chat.rs`/`ops/parallel_turn.rs`) once the message has been validated. - -use std::sync::Arc; -use tinyagents_harness::run_queue::RunQueue; - -use crate::progress::AgentProgress; - -use super::ops::BudgetCorrelation; -use super::progress_bridge::spawn_progress_bridge; -use super::session::{ - checkin_session_agent, checkout_session_agent, normalize_model_override, CheckedOutSession, - CheckoutPolicy, -}; -use super::types::{ChatRequestMetadata, WebChatTaskResult}; -use super::web_errors::{ - inference_budget_exceeded_user_message, is_inference_budget_exceeded_error, -}; -use tinyinference_llm::failure::is_empty_provider_response_text; - -#[cfg(any(test, debug_assertions))] -use super::ops::TEST_FORCED_RUN_CHAT_TASK_ERROR; - -pub(crate) async fn run_chat_task( - ctx: &crate::core::runtime::DispatchCtx, - client_id: &str, - thread_id: &str, - request_id: &str, - message: &str, - model_override: Option, - temperature: Option, - locale: Option, - run_queue: Arc>, - metadata: ChatRequestMetadata, - origin: crate::core::runtime::turn_origin::AgentTurnOrigin, - // When true, run as an isolated fork: build a fresh agent seeded from the - // thread's history-at-start and never touch the shared `THREAD_SESSIONS` - // cache, so a concurrent same-thread (parallel) turn cannot clobber — or be - // clobbered by — the primary turn's cached agent. See `QueueMode::Parallel`. - fork: bool, - // This turn's host environment (its Stop cancellation, the wall-clock - // backstop's deadline), handed to the session so the whole run tree sees it. - host_env: crate::agent::turn_env::HostTurnEnv, - // The web-turn guard's activity record for this turn, passed explicitly by - // `run_turn_under_cancel_and_deadline`. - activity: super::turn_activity::TurnActivity, - // Where this turn's parked approvals surface, handed to the turn itself. - approval: crate::security::approval::ApprovalTurnContext, -) -> Result { - // One turn at a time per profile: wait behind its relay and cron turns. - let _turn = crate::profiles::turn_gate::acquire(ctx).await; - - #[cfg(any(test, debug_assertions))] - { - let mut slot = TEST_FORCED_RUN_CHAT_TASK_ERROR.lock().await; - if let Some(forced) = slot.take() { - log::debug!( - "[web-channel][test] forced run_chat_task failure client_id={} thread_id={} request_id={}", - client_id, - thread_id, - request_id - ); - return Err(forced); - } - } - - // Test hook: park the turn in-flight so concurrency / cooperative - // cancellation can be observed. A `Drop` guard flips the supplied flag if - // this future is dropped (i.e. cancelled) before the sleep elapses, proving - // the turn was torn down cooperatively rather than left running. - #[cfg(any(test, debug_assertions))] - { - let block = { - let slot = super::ops::TEST_RUN_CHAT_TASK_BLOCK.lock().await; - slot.clone() - }; - if let Some(block) = block { - struct DropGuard(std::sync::Arc); - impl Drop for DropGuard { - fn drop(&mut self) { - self.0.store(true, std::sync::atomic::Ordering::SeqCst); - } - } - let _guard = DropGuard(block.dropped.clone()); - log::debug!( - "[web-channel][test] parking run_chat_task thread_id={} request_id={}", - thread_id, - request_id - ); - // Signal that the turn future is live and parked, so a test can - // cancel only after the guard exists (otherwise a `biased` cancel - // could short-circuit before this future is ever polled). - block - .started - .store(true, std::sync::atomic::Ordering::SeqCst); - tokio::select! { - _ = block.release.notified() => { - return match block.succeed_in.clone() { - Some(workspace_dir) => Ok(WebChatTaskResult { - full_response: "parked reply".to_string(), - citations: Vec::new(), - usage: None, - workspace_dir, - timing: None, - }), - None => Err("test block released".to_string()), - }; - } - _ = tokio::time::sleep(std::time::Duration::from_secs(30)) => { - return Err("test block elapsed".to_string()); - } - } - } - } - - let mut config = ctx.load_config().await?; - // A thread started in a chosen folder acts there, not in the global - // `action_dir`. Applied before checkout so the session agent, its security - // policy (which grants `action_dir` as a trusted root) and its tools are - // all built on the thread's folder. - let thread_dir = - crate::threads::ops::thread_working_dir(ctx, &config, config.workspace_dir.clone(), thread_id) - .await?; - if let Some(dir) = &thread_dir { - log::debug!("[web-channel] thread working folder applied thread_id={thread_id}"); - config.action_dir = dir.clone(); - } - // A guard that stops this turn closes it from this turn's own config and - // reply language, not from whatever profile is active when it fires. - activity.remember_turn(std::sync::Arc::new(config.clone()), locale.clone()); - let model_override = normalize_model_override(model_override); - // The cached session (or a cold-boot resumed one) is the thread's single - // live history; every turn on the thread checks it out through this path. - let CheckedOutSession { - mut agent, - fingerprint: current_fp, - } = checkout_session_agent( - ctx, - &config, - client_id, - thread_id, - model_override, - temperature, - locale.as_deref(), - if fork { - CheckoutPolicy::Fork - } else { - CheckoutPolicy::Exact - }, - ) - .await?; - - // Bounded to 256 (was 64): a heavy-event subagent (e.g. `workflow_builder`, - // 50+ progress events per run) can overflow a smaller buffer, and the - // sender side uses `try_send` — an overflow silently drops progress - // events (including the ones that create a subagent's timeline row), - // which can in turn hide UI state derived from those events. This is - // defense-in-depth; extraction of durable state (like a workflow - // proposal) must not depend on any single progress event surviving. - let (progress_tx, progress_rx) = tokio::sync::mpsc::channel(256); - // Under the web-turn guard, fold every event into the turn's activity - // record (the idle guard's input) on its way to the bridge. - let progress_rx = super::turn_activity::tap(ctx, activity, progress_rx, 256); - // The channel is fresh here. Record the user input even if the turn fails - // before a committed reply can emit its final TurnContent event. - let _ = progress_tx.try_send(AgentProgress::TurnContent { - input: Some(message.to_string()), - output: None, - }); - agent.set_on_progress(Some(progress_tx)); - agent.set_run_queue(Some(run_queue)); - agent.set_thread_id(Some(thread_id)); - agent.set_host_env(host_env); - // Also the turn's workspace, so attachment reads and delegated sub-agents - // (which load a fresh config) use the folder its uploads were staged in - // (#7714). Same pattern as `agent_chat`'s per-turn cwd. - if let Some(dir) = thread_dir { - agent.set_workspace_descriptor(Some(tinytools::WorkspaceDescriptor::new(dir))); - } - let turn_state_store = crate::storage::sessions::turn_states_for(&config.workspace_dir); - // Stamp the resolved agent onto the bridge metadata so the trace exporter - // can attribute the run (`agent.id` attr / `agent.turn:` trace name). - let mut bridge_metadata = metadata.clone(); - bridge_metadata.agent_id = Some(current_fp.target_agent_id.clone()); - let bridge = spawn_progress_bridge( - progress_rx, - client_id.to_string(), - thread_id.to_string(), - request_id.to_string(), - turn_state_store, - bridge_metadata, - config.clone(), - ctx.clone(), - ); - - // `run_single`'s future is very large; box it so the two ambient-scope - // wrappers below hold a pointer rather than inlining the whole future into - // this already-large `run_chat_task` frame (which otherwise overflows the - // default test-thread stack — see the channels web-turn coverage tests). - let turn = Box::pin(agent.run_single_with_approval(message, Some(origin), approval)); - let mut result = match turn.await { - Ok(response) => { - // A successful turn proves the thread's balance is usable, so drop - // any stale budget-exhausted signal before it could mislabel a - // later genuine empty response. See #3386. - super::ops::clear_budget_signal(ctx, thread_id).await; - let citations = crate::web_chat::citations::take_turn_citations(ctx, thread_id); - let usage = agent.take_last_turn_usage_totals(); - Ok(WebChatTaskResult { - full_response: response, - citations, - usage, - workspace_dir: config.workspace_dir.clone(), - timing: None, - }) - } - Err(err) => { - let err_message = err.to_string(); - let is_budget = is_inference_budget_exceeded_error(&err_message); - let is_empty = is_empty_provider_response_text(&err_message.to_lowercase()); - // Only consult the cross-turn signal for an empty response that is - // not already a budget error — avoids taking the lock on every turn. - let has_fresh_signal = if !is_budget && is_empty { - super::ops::has_fresh_budget_signal(ctx, thread_id, ¤t_fp.provider_binding) - .await - } else { - false - }; - match super::ops::classify_budget_correlation(is_budget, is_empty, has_fresh_signal) { - BudgetCorrelation::BudgetExhausted => { - // Remember the exhaustion (scoped to this provider binding) - // so a follow-up empty 200 on this thread+provider (managed - // route closes the SSE clean under credit exhaustion, no - // inline marker) reclassifies as budget. #3386. - super::ops::record_budget_signal(ctx, thread_id, ¤t_fp.provider_binding) - .await; - log::warn!( - "[web-channel] inference budget exhausted for client={} thread={} request_id={} error_category=budget_exhausted", - client_id, - thread_id, - request_id - ); - Ok(WebChatTaskResult { - full_response: inference_budget_exceeded_user_message().to_string(), - citations: Vec::new(), - usage: None, - workspace_dir: config.workspace_dir.clone(), - timing: None, - }) - } - BudgetCorrelation::UpgradeEmptyToBudget => { - // Empty provider response within the budget-signal window: - // the turn most likely failed for the same out-of-credits - // reason but arrived as a clean empty 200 with no budget - // marker. Surface the actionable budget copy. #3386. - log::warn!( - "[web-channel] reclassifying empty provider response as budget-exhausted \ - from recent same-thread signal client={} thread={} request_id={} error_category=budget_exhausted_correlated", - client_id, - thread_id, - request_id - ); - Ok(WebChatTaskResult { - full_response: inference_budget_exceeded_user_message().to_string(), - citations: Vec::new(), - usage: None, - workspace_dir: config.workspace_dir.clone(), - timing: None, - }) - } - BudgetCorrelation::PassThrough => Err(err_message), - } - } - }; - if let Ok(ref task_result) = result { - let speak_reply = matches!(metadata.speak_reply, Some(true)); - let trimmed_response = task_result.full_response.trim(); - if speak_reply && !trimmed_response.is_empty() { - // Resolved through the voice registry by the hosted slug: the - // provider is registered by the hosted-backend layer, so a core - // with none registered logs the error and skips the spoken reply. - #[cfg(feature = "voice")] - let speech = match crate::voice::create_tts_provider("cloud", "", &config).await { - Ok(provider) => provider - .synthesize(&config, &task_result.full_response, None) - .await - .map(|_| ()), - Err(err) => Err(err.to_string()), - }; - #[cfg(not(feature = "voice"))] - let speech: Result<(), String> = - Err("voice feature disabled at compile time".to_string()); - match speech { - Ok(()) => log::debug!( - "[web_channel] reply_speech dispatched chars={} client_id={} thread_id={} request_id={}", - task_result.full_response.len(), - client_id, - thread_id, - request_id, - ), - Err(err) => log::warn!( - "[web_channel] reply_speech failed: {err} client_id={} thread_id={} request_id={}", - client_id, - thread_id, - request_id, - ), - } - } - } - - // Test hook: wedge the turn after its run, as a stuck save would. - #[cfg(any(test, debug_assertions))] - if super::ops::TEST_PARK_AFTER_RUN.load(std::sync::atomic::Ordering::SeqCst) { - log::debug!( - "[web-channel][test] parking run_chat_task after the run request_id={request_id}" - ); - std::future::pending::<()>().await; - } - - agent.set_on_progress(None); - - // The caller publishes the terminal `chat_done`/`chat_error` as soon as - // this returns. Let the bridge forward everything the turn queued first, - // so the terminal event cannot overtake the turn's own last tool results - // and narration on the socket. Bounded (see `BRIDGE_DRAIN_TIMEOUT`). - if !bridge - .wait_drained(super::progress_bridge::BRIDGE_DRAIN_TIMEOUT) - .await - { - log::warn!( - "[web-channel] progress bridge did not drain within {:?}; delivering anyway \ - client={} thread={} request_id={}", - super::progress_bridge::BRIDGE_DRAIN_TIMEOUT, - client_id, - thread_id, - request_id - ); - } - - // Settle the turn's own snapshot now the turn is over. - // - // The bridge marks the snapshot terminal on its way out, but it only exits - // once every clone of its progress sender drops. The cached session no - // longer keeps the turn's commit receipt (which held two), yet a detached - // sub-agent may still hold one past the turn, and an exit the bridge never - // reaches would leave `Streaming` on disk: re-entering the thread then - // hydrates that snapshot and paints a live "Thinking..." indicator under a - // reply that was already delivered. The turn has ended here by - // construction, so record that. A bridge that later observes - // `TurnCompleted` overwrites this with `Completed`, terminal either way. - { - let lifecycle = if result.is_ok() { - tinyagents_session::turn_state::TurnLifecycle::Completed - } else { - tinyagents_session::turn_state::TurnLifecycle::Interrupted - }; - let now = chrono::Utc::now().to_rfc3339(); - if let Err(err) = crate::storage::sessions::turn_states_for(&config.workspace_dir) - .settle_turn(thread_id, request_id, lifecycle, &now) - { - log::warn!( - "[web-channel] failed to settle turn snapshot client={client_id} \ - thread={thread_id} request_id={request_id}: {err}" - ); - } - } - - // The bridge only stamps its `TurnTimingSnapshot` once it has seen the - // parent's `TurnCompleted`, which `wait_drained` above waits for — read - // it now so `chat_done.timing` reports the same first-token/first-tool/ - // total numbers as the bridge's own `time-to-first-visible` log line. - // `None` on a synthetic (budget-exhausted) result, an `Err`, or a bridge - // that never drained in time. - if let Ok(ref mut task_result) = result { - task_result.timing = bridge.timing_snapshot(); - } - - // Only the primary (non-fork) turn writes its agent back to the shared - // cache; a fork is fully isolated and lets its agent drop here. - if !fork { - // A harness error can leave its session prefix committed even when the - // turn itself did not complete (for example an in-stream credential - // failure after partial text). Re-caching that host makes the next - // request fail with "cannot change a session prefix after a committed - // turn". The durable transcript remains authoritative, so discard an - // agent after every failed turn and cold-boot it on the next request. - if turn_result_poisoned_session(&result) { - log::warn!( - "[web-channel] dropping session agent after failed turn — \ - next turn cold-boots from the durable transcript \ - client={} thread={} request_id={}", - client_id, - thread_id, - request_id - ); - } else { - checkin_session_agent(ctx, thread_id, agent, current_fp).await; - } - } - - result -} - -/// Whether a completed turn's checked-out agent must be dropped instead of -/// returned to the warm-session cache. Any `Err` can leave the underlying host -/// session partially advanced, so only completed task results are reusable. -fn turn_result_poisoned_session(result: &Result) -> bool { - result.is_err() -} - -/// The error-string half of [`turn_result_poisoned_session`], shared with the -/// host-authored turn path (`ops/system_turn.rs`) whose result carries no -/// `WebChatTaskResult`. -pub(super) fn turn_error_discards_session(_err: &str) -> bool { - true -} - -#[cfg(test)] -#[path = "run_task_tests.rs"] -mod tests; diff --git a/crates/openhuman-core/src/web_chat/run_task_tests.rs b/crates/openhuman-core/src/web_chat/run_task_tests.rs deleted file mode 100644 index 5a520d020db..00000000000 --- a/crates/openhuman-core/src/web_chat/run_task_tests.rs +++ /dev/null @@ -1,84 +0,0 @@ -use super::*; - -fn ok() -> Result { - Ok(WebChatTaskResult { - full_response: "hello".to_string(), - citations: Vec::new(), - usage: None, - workspace_dir: std::path::PathBuf::from("/tmp/ws"), - timing: None, - }) -} - -#[test] -fn poisoned_on_managed_sse_bad_request_frame() { - // Managed backend 400: flushed HTTP 200, then an in-stream SSE error - // frame stamped errorCode:"BAD_REQUEST" — the exact shape the de-poison - // guard must catch (no HTTP 400 status anywhere in the string). Payload - // mirrors the real backend frame verified against tinyhumansai/backend - // upstream/develop `routes/inference.ts::writeInferenceSSE` - // ({error:{message,type:"stream_error",errorCode}}), wrapped by the - // client's `sse_error_frame_bail_message` as - // "OpenHuman streaming API error: ". `validateToolMessageOrdering` - // throws BadRequestError (errorCode=BAD_REQUEST) for an orphaned tool_call_id. - let err: Result = Err( - "OpenHuman streaming API error: {\"error\":{\"message\":\"Message has tool role, \ - but there was no previous assistant message with a tool call!\",\ - \"type\":\"stream_error\",\"errorCode\":\"BAD_REQUEST\"}}" - .to_string(), - ); - assert!(turn_result_poisoned_session(&err)); -} - -#[test] -fn poisoned_on_byo_provider_tool_ordering_400() { - // BYO/direct provider tool-ordering rejection — classifies as a - // *retryable* provider_request_rejected (poisoned history), so it evicts. - let err: Result = Err( - "OpenAI API error (400 Bad Request): {\"error\":{\"message\":\"Invalid parameter: \ - messages with role 'tool' must be a response to a preceding message with \ - 'tool_calls'.\"}}" - .to_string(), - ); - assert!(turn_result_poisoned_session(&err)); -} - -#[test] -fn genuine_param_400_discards_session() { - // Even a non-retryable model/parameter error can have committed a prefix - // in the host session. It must never be checked back in. - let err: Result = Err( - "custom_openai API error (400 Bad Request): {\"error\":{\"message\":\ - \"Unsupported value: 'temperature' must be 1 for this model\"}}" - .to_string(), - ); - assert!( - turn_result_poisoned_session(&err), - "a failed turn must not return its host session to the cache" - ); -} - -#[test] -fn transient_failures_discard_session() { - for raw in [ - // rate limit / 429 — history is fine, user should retry warm - "OpenAI API error (429 Too Many Requests): slow down", - // timeout - "request timed out while reading response", - // upstream 5xx - "OpenAI API error (503 Service Unavailable): no healthy upstream", - // session expiry — not a payload problem - "SESSION_EXPIRED: backend session not active — sign in to resume LLM work", - ] { - let err: Result = Err(raw.to_string()); - assert!( - turn_result_poisoned_session(&err), - "a failed turn must not return its host session to the cache: {raw}" - ); - } -} - -#[test] -fn success_keeps_warm_session() { - assert!(!turn_result_poisoned_session(&ok())); -} diff --git a/scripts/__tests__/rust-e2e-enumeration.test.mjs b/scripts/__tests__/rust-e2e-enumeration.test.mjs index ae5c4a95df8..e17c53b59d3 100644 --- a/scripts/__tests__/rust-e2e-enumeration.test.mjs +++ b/scripts/__tests__/rust-e2e-enumeration.test.mjs @@ -302,6 +302,9 @@ test("the E2E runner stages released search and connector fixtures, and builds o "e2e_source_ids=(tinyconnectors tinysearch)", "unset OPENHUMAN_MODULE_PATH", 'stage_source_modules() { printf "built=%s\\n" "$*"; }', + // inbound_module_e2e loads the TinyEventQueues release in both modes. + "module_platform=linux-x86_64 module_ext=so", + 'stage_release_module() { printf "%s" "$STUB_DIR/released/$1-$2.$3"; }', source.slice(start, end), "printf 'path=%s\\n' \"${OPENHUMAN_MODULE_PATH:-}\"", ].join("\n"), @@ -311,7 +314,7 @@ test("the E2E runner stages released search and connector fixtures, and builds o assert.match(output, /built=tinyconnectors tinysearch/); assert.ok( output.includes( - `path=${dir}/target/module-sources/tinysearch:${dir}/target/module-sources/tinyconnectors`, + `path=${dir}/target/module-sources/tinysearch:${dir}/target/module-sources/tinyconnectors:${dir}/released/tinyeventqueues-linux-x86_64.so`, ), output, ); diff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.json index 0dc961e6696..9335d6430b9 100644 --- a/scripts/ci/agent-runtime-boundary-baseline.json +++ b/scripts/ci/agent-runtime-boundary-baseline.json @@ -237,13 +237,6 @@ "text": "let result = with_origin(origin, agent.run_single(prompt))", "occurrence": 1 }, - { - "rule": "openhuman-task-local", - "path": "crates/openhuman-core/src/web_chat/ops/turn_guards.rs", - "line": 254, - "text": "crate::core::runtime::turn_origin::with_origin(", - "occurrence": 1 - }, { "rule": "openhuman-task-local", "path": "crates/openhuman-embed/src/turn_control.rs", diff --git a/scripts/ci/check-gated-test-allowlist.sh b/scripts/ci/check-gated-test-allowlist.sh index 16e6d1146e8..8a2ec3e29cc 100755 --- a/scripts/ci/check-gated-test-allowlist.sh +++ b/scripts/ci/check-gated-test-allowlist.sh @@ -126,7 +126,6 @@ agent/queued_turn_tests.rs cron/ops_tests.rs cron/scheduler_tests.rs web_chat/web_tests_turn_lifecycle_tests.rs -web_chat/run_task.rs channels/host/voice_tests.rs EOF ) diff --git a/scripts/ci/ignored-test-baseline.json b/scripts/ci/ignored-test-baseline.json index 5653c6ba42d..97496186a25 100644 --- a/scripts/ci/ignored-test-baseline.json +++ b/scripts/ci/ignored-test-baseline.json @@ -1,7 +1,7 @@ { "openhuman-app": 5, "openhuman-cli": 0, - "openhuman-core": 9, + "openhuman-core": 8, "openhuman-embed": 2, "openhuman-modules-linked": 0, "openhuman-rpc": 0, diff --git a/scripts/ci/saas-ambient-baseline.json b/scripts/ci/saas-ambient-baseline.json index 4e0d2ad199a..e7d2c2b15e3 100644 --- a/scripts/ci/saas-ambient-baseline.json +++ b/scripts/ci/saas-ambient-baseline.json @@ -1007,27 +1007,6 @@ "text": "None => std::env::remove_var(name),", "occurrence": 1 }, - { - "rule": "bare-spawn", - "path": "crates/openhuman-core/src/web_chat/ops/parallel_turn.rs", - "line": 56, - "text": "let handle = tokio::spawn(crate::core::runtime::context::CoreContext::propagate(", - "occurrence": 1 - }, - { - "rule": "bare-spawn", - "path": "crates/openhuman-core/src/web_chat/ops/parallel_turn.rs", - "line": 253, - "text": "tokio::spawn(async move {", - "occurrence": 1 - }, - { - "rule": "bare-spawn", - "path": "crates/openhuman-core/src/web_chat/ops/parallel_turn.rs", - "line": 290, - "text": "tokio::spawn(async move {", - "occurrence": 2 - }, { "rule": "bare-spawn", "path": "crates/openhuman-core/src/web_chat/presentation.rs", diff --git a/tests/in_process/auth_e2e.rs b/tests/in_process/auth_e2e.rs index 27cde824dc5..7e6b99d85a1 100644 --- a/tests/in_process/auth_e2e.rs +++ b/tests/in_process/auth_e2e.rs @@ -1569,28 +1569,29 @@ async fn credentials_profile_store_recovers_dropped_entries_empty_files_and_date .expect("write missing oauth secret fixture"); // Only a keyring-backed store can tell that the keyring holds no access // token for this row; a keyring-less view must keep a possibly - // keyring-held OAuth row instead of dropping it. + // keyring-held OAuth row instead of dropping it. A file keyring keeps + // profile secrets out of the interactive keyring (#8670), so even a + // config-backed store is keyring-less here: it withholds the row from the + // view but never purges it, nor the active pointer to it. let missing_secret_config = profile_store_config(&missing_oauth_secret_dir); let missing_secret = AuthProfilesStore::new_with_config(&missing_oauth_secret_dir, false, &missing_secret_config) .load().await - .expect("oauth profile missing access token should be dropped"); + .expect("an oauth profile missing its access token still loads"); assert!(missing_secret.profiles.is_empty()); - assert!(missing_secret.active_profiles.is_empty()); - assert!(!missing_oauth_secret_dir.join("auth-profiles.json").exists()); + assert_eq!( + missing_secret.active_profiles.get("github").map(String::as_str), + Some("github:missing-access"), + "a keyring-less store never purges a possibly keyring-held profile" + ); let reread_missing_secret = AuthProfilesStore::new_with_config(&missing_oauth_secret_dir, false, &missing_secret_config) .load().await .expect("re-read the persisted missing oauth secret store"); - assert!( - !reread_missing_secret - .profiles - .contains_key("github:missing-access"), - "missing oauth secret profile should be purged from persisted store" - ); - assert!( - !reread_missing_secret.active_profiles.contains_key("github"), - "active pointer to missing oauth secret profile should be purged" + assert_eq!( + reread_missing_secret.active_profiles.get("github").map(String::as_str), + Some("github:missing-access"), + "the kept row survives a re-read" ); let public_api_dir = tmp.path().join("public-api-errors"); @@ -1740,8 +1741,11 @@ async fn credentials_profile_store_keychain_migration_and_fallback_paths_are_det .get(hit_profile_id) .and_then(|profile| profile.token_set.as_ref()) .expect("keychain hit token set"); - assert_eq!(hit_tokens.access_token, "kc-access"); - assert_eq!(hit_tokens.refresh_token.as_deref(), Some("kc-refresh")); + // A file keyring keeps profile secrets out of the interactive keyring + // (#8670): the store serves the document's own values and never consults + // the keyring entry another store seeded. + assert_eq!(hit_tokens.access_token, "legacy-access"); + assert_eq!(hit_tokens.refresh_token.as_deref(), Some("legacy-refresh")); assert!( !hit_dir.join("auth-profiles.json").exists(), "the legacy document is imported into the encrypted store" @@ -1799,22 +1803,23 @@ async fn credentials_profile_store_keychain_migration_and_fallback_paths_are_det ); assert!(!migrate_dir.join("auth-profiles.json").exists()); - // Saving through a config-backed store moves the secret to the keyring: - // a keyring-less view withholds the keyring-owned row. + // With a file keyring, saving through a config-backed store keeps the + // secret in the encrypted document (#8670): a keyring-less view still + // lists the row, because nothing about it lives in the keyring. migrate_store .update_profile(migrate_profile_id, |_| Ok(())) .await .expect("re-save the imported profile"); assert!( - !AuthProfilesStore::new(&migrate_dir, false) + AuthProfilesStore::new(&migrate_dir, false) .load().await .expect("keyring-less view") .profiles .contains_key(migrate_profile_id), - "a saved profile's secret lives in the keyring, not the document" + "a saved profile's secret lives in the document, not the keyring" ); - // A copy of this document (same keyring user) proves the keyring entry - // exists now and is gone after removal. + // A copy of this document (same keyring user) carries the secret itself, + // before and after the original is removed. let probe_dir = tmp.path().join("probe").join("keychain-migrate"); std::fs::create_dir_all(probe_dir.join("auth-profiles")).expect("create probe dir"); for entry in std::fs::read_dir(migrate_dir.join("auth-profiles")).expect("read store dir") { @@ -1833,7 +1838,7 @@ async fn credentials_profile_store_keychain_migration_and_fallback_paths_are_det .get(migrate_profile_id) .and_then(|profile| profile.token.as_deref()), Some("plain-token-for-migration"), - "the keyring holds the saved secret" + "the document copy holds the saved secret" ); // A malformed keyring payload for a legacy row falls back to the @@ -1887,11 +1892,12 @@ async fn credentials_profile_store_keychain_migration_and_fallback_paths_are_det "migrated profile should be removable" ); assert!( - !AuthProfilesStore::new_with_config(&probe_dir, true, &config) + AuthProfilesStore::new_with_config(&probe_dir, true, &config) .load().await .expect("probe after removal") .profiles .contains_key(migrate_profile_id), - "removing a profile should delete its keychain payload" + "removing a document-held profile leaves no keyring entry behind to delete: \ + the copy still carries its own secret" ); } diff --git a/tests/storage_default_import_e2e.rs b/tests/storage_default_import_e2e.rs index 188fed4acd1..03adc7b4554 100644 --- a/tests/storage_default_import_e2e.rs +++ b/tests/storage_default_import_e2e.rs @@ -224,3 +224,53 @@ fn serve_on_an_explicit_url_imports_legacy_approvals_without_touching_the_file() "an explicit URL replaces the workspace default" ); } + +/// The id the module listed the request an earlier version left waiting under. +fn carried_over_request_id(base: &str) -> String { + let listed = rpc(base, "openhuman.approval_list_pending", json!({})); + listed["result"]["result"] + .as_array() + .and_then(|rows| { + rows.iter() + .find(|row| row.to_string().contains("still-pending")) + }) + .and_then(|row| row["request_id"].as_str()) + .map(str::to_owned) + .unwrap_or_else(|| panic!("the carried-over request is listed: {listed}")) +} + +#[test] +fn a_request_an_earlier_version_left_waiting_can_be_denied_but_never_approved() { + let tmp = tempfile::tempdir().unwrap(); + let workspace = tmp.path().join("workspace"); + legacy_workspace(&workspace); + + let (server, base) = start(tmp.path(), &workspace, None); + let request_id = carried_over_request_id(&base); + + // Nothing in this launch can run the call it was for, so approving it is + // refused and it stays listed. + let approved = rpc( + &base, + "openhuman.approval_decide", + json!({ "request_id": request_id, "decision": "approve_once" }), + ); + assert!(approved.get("error").is_some(), "{approved}"); + assert_eq!(carried_over_request_id(&base), request_id); + + // A person can dismiss it. + let denied = rpc( + &base, + "openhuman.approval_decide", + json!({ "request_id": request_id, "decision": "deny" }), + ); + assert!(denied.get("error").is_none(), "{denied}"); + let listed = rpc(&base, "openhuman.approval_list_pending", json!({})).to_string(); + assert!(!listed.contains("still-pending"), "{listed}"); + drop(server); + + // The denial is durable: the next launch does not list it again. + let (_server, base) = start(tmp.path(), &workspace, None); + let listed = rpc(&base, "openhuman.approval_list_pending", json!({})).to_string(); + assert!(!listed.contains("still-pending"), "{listed}"); +}