The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(tests): update raw coverage e2e test files
Steven Enamakel133d2dbbea5c
diff --git a/tests/raw_coverage/inference_local_ops_piper_raw_coverage_e2e.rs b/tests/raw_coverage/inference_local_ops_piper_raw_coverage_e2e.rsdeleted file mode 100644index e1c7f9e97d..0000000000--- a/tests/raw_coverage/inference_local_ops_piper_raw_coverage_e2e.rs+++ /dev/null@@ -1,312 +0,0 @@-//! Round 18 raw/E2E coverage for local inference ops and Piper installer branches.-//!-//! This suite uses temp workspaces, temp PATH scripts, and loopback HTTP mocks only.-//! It must not call host Ollama, MLX, Python, Piper, or model binaries.--use std::path::{Path, PathBuf};-use std::sync::{Arc, Mutex, OnceLock};-use std::time::{Duration, Instant};--use axum::body::Body;-use axum::extract::State;-use axum::http::{Response, StatusCode};-use axum::response::IntoResponse;-use axum::routing::get;-use axum::Router;-use flate2::write::GzEncoder;-use flate2::Compression;-use openhuman_core::core::all::RegisteredController;-use openhuman_core::config::Config;-use openhuman_core::inference::host_runtime::{- all_local_inference_registered_controllers, local_ai_transcribe_bytes,-};-use serde_json::{json, Value};-use tempfile::{tempdir, TempDir};--#[derive(Clone)]-struct PiperMockState {- requests: Arc<Mutex<Vec<String>>>,- mode: Arc<Mutex<PiperMockMode>>,- archive: Arc<Vec<u8>>,-}--#[derive(Clone, Copy, Debug, Eq, PartialEq)]-enum PiperMockMode {- Valid,- SmallVoice,- InvalidArchive,-}--struct EnvVarGuard {- key: &'static str,- previous: Option<std::ffi::OsString>,-}--impl EnvVarGuard {- fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {- let previous = std::env::var_os(key);- // SAFETY: validation runs this integration test with --test-threads=1.- unsafe { std::env::set_var(key, value) };- Self { key, previous }- }-- fn unset(key: &'static str) -> Self {- let previous = std::env::var_os(key);- // SAFETY: validation runs this integration test with --test-threads=1.- unsafe { std::env::remove_var(key) };- Self { key, previous }- }-}--impl Drop for EnvVarGuard {- fn drop(&mut self) {- match &self.previous {- Some(value) => {- // SAFETY: validation runs this integration test with --test-threads=1.- unsafe { std::env::set_var(self.key, value) }- }- None => {- // SAFETY: validation runs this integration test with --test-threads=1.- unsafe { std::env::remove_var(self.key) }- }- }- }-}--static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;--fn env_lock() -> std::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| Mutex::new(()))- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())-}--#[tokio::test]-async fn piper_controller_rejects_insecure_download_overrides() {- let _lock = env_lock();- let (base, state) = serve_piper_mock().await;- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- config.local_ai.runtime_enabled = false;- config.local_ai.tts_voice_id = "en_US-lessac-medium".to_string();- config.save().await.expect("save config");-- let scripts = tempdir().expect("scripts");- write_stub_script(scripts.path(), "ollama", "#!/bin/sh\nexit 42\n");- write_stub_script(scripts.path(), "python", "#!/bin/sh\nexit 42\n");- write_stub_script(scripts.path(), "python3", "#!/bin/sh\nexit 42\n");- write_stub_script(scripts.path(), "mlx_lm.generate", "#!/bin/sh\nexit 42\n");- write_stub_script(scripts.path(), "piper", "#!/bin/sh\nexit 42\n");-- let _path = EnvVarGuard::set("PATH", scripts.path());- let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", tmp.path().join(".openhuman"));- let _release = EnvVarGuard::set("OPENHUMAN_PIPER_RELEASE_BASE_URL", &base);- let _voices = EnvVarGuard::set("OPENHUMAN_PIPER_VOICES_BASE_URL", format!("{base}/voices"));- let _ollama_bin = EnvVarGuard::unset("OLLAMA_BIN");- let _piper_bin = EnvVarGuard::unset("PIPER_BIN");- let _whisper_bin = EnvVarGuard::unset("WHISPER_BIN");-- let controllers = all_local_inference_registered_controllers();- let install = controller(&controllers, "install_piper");- let status = controller(&controllers, "piper_install_status");-- call(- install,- json!({"voice_id": "en_US-lessac-medium", "force": true}),- )- .await- .expect("queue install");- let failed = wait_for_piper_state(status, "error").await;- let detail = failed["error_detail"].as_str().unwrap_or_default();- assert!(- detail.contains("artifact URL must use HTTPS and an approved release host"),- "unexpected download policy error: {detail}"- );-- let requests = state.requests.lock().expect("requests").clone();- assert!(requests.is_empty(), "rejected URLs must not be requested");-}--#[tokio::test]-async fn local_transcribe_bytes_covers_temp_file_path_and_extension_validation() {- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- config.local_ai.runtime_enabled = false;-- let invalid = local_ai_transcribe_bytes(&config, b"audio", Some("../wav".to_string()))- .await- .expect_err("invalid extension");- assert_eq!(invalid, "Invalid audio extension");-- let disabled = local_ai_transcribe_bytes(&config, b"audio", Some(".WEBM".to_string()))- .await- .expect_err("hosted STT without a configured session");- assert!(- !disabled.contains("local ai is disabled"),- "hosted STT must not be gated on the local-AI runtime: {disabled}"- );-}--async fn serve_piper_mock() -> (String, PiperMockState) {- let state = PiperMockState {- requests: Arc::new(Mutex::new(Vec::new())),- mode: Arc::new(Mutex::new(PiperMockMode::Valid)),- archive: Arc::new(valid_tar_gz_archive()),- };- let app = Router::new()- .route("/{*path}", get(piper_download))- .with_state(state.clone());- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind mock");- let addr = listener.local_addr().expect("mock addr");- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve mock");- });- (format!("http://{addr}"), state)-}--async fn piper_download(- State(state): State<PiperMockState>,- axum::extract::Path(path): axum::extract::Path<String>,-) -> Response<Body> {- state- .requests- .lock()- .expect("requests")- .push(format!("/{path}"));- let mode = *state.mode.lock().expect("mode");- if path.ends_with(".onnx.json") {- return bytes_response(synthetic_voice_json());- }- if path.ends_with(".onnx") {- return match mode {- PiperMockMode::SmallVoice => bytes_response(vec![b'x'; 128]),- PiperMockMode::Valid | PiperMockMode::InvalidArchive => {- bytes_response(vec![b'v'; 31 * 1024 * 1024])- }- };- }- if path.ends_with(".tar.gz") || path.ends_with(".zip") {- return match mode {- PiperMockMode::InvalidArchive => bytes_response(vec![b'!'; 2 * 1024 * 1024]),- PiperMockMode::Valid | PiperMockMode::SmallVoice => {- bytes_response((*state.archive).clone())- }- };- }- (StatusCode::NOT_FOUND, "not found").into_response()-}--fn bytes_response(bytes: Vec<u8>) -> Response<Body> {- Response::builder()- .status(StatusCode::OK)- .body(Body::from(bytes))- .expect("response")-}--fn set_mode(state: &PiperMockState, mode: PiperMockMode) {- *state.mode.lock().expect("mode") = mode;-}--fn valid_tar_gz_archive() -> Vec<u8> {- let encoder = GzEncoder::new(Vec::new(), Compression::none());- let mut archive = tar::Builder::new(encoder);- append_tar_file(- &mut archive,- "piper/piper",- b"#!/bin/sh\nprintf piper\n".to_vec(),- 0o755,- );- let pad: Vec<u8> = (0..(2 * 1024 * 1024))- .map(|i| ((i * 31 + 17) % 251) as u8)- .collect();- append_tar_file(&mut archive, "piper/pad.bin", pad, 0o644);- archive.finish().expect("finish tar");- let encoder = archive.into_inner().expect("tar encoder");- encoder.finish().expect("finish gzip")-}--fn append_tar_file(- archive: &mut tar::Builder<GzEncoder<Vec<u8>>>,- path: &str,- bytes: Vec<u8>,- mode: u32,-) {- let mut header = tar::Header::new_gnu();- header.set_size(bytes.len() as u64);- header.set_mode(mode);- header.set_cksum();- archive- .append_data(&mut header, path, bytes.as_slice())- .expect("append tar file");-}--fn synthetic_voice_json() -> Vec<u8> {- let mut body = br#"{"audio":{"sample_rate":22050},"phoneme_id_map":{},"#.to_vec();- body.extend_from_slice(br#""filler":""#);- body.extend(std::iter::repeat_n(b'x', 512));- body.extend_from_slice(br#""}"#);- body-}--async fn wait_for_piper_state(status: &RegisteredController, wanted: &str) -> Value {- wait_for_piper(status, |value| value["state"] == wanted).await-}--async fn wait_for_piper_stage(status: &RegisteredController, wanted: &str) -> Value {- wait_for_piper(status, |value| value["stage"] == wanted).await-}--async fn wait_for_piper(status: &RegisteredController, done: impl Fn(&Value) -> bool) -> Value {- let deadline = Instant::now() + Duration::from_secs(20);- let mut last = Value::Null;- while Instant::now() < deadline {- last = call(status, json!({})).await.expect("status");- if done(&last) {- return last;- }- tokio::time::sleep(Duration::from_millis(100)).await;- }- panic!("timed out waiting for piper status, last={last}");-}--fn controller<'a>(- controllers: &'a [RegisteredController],- function: &str,-) -> &'a RegisteredController {- controllers- .iter()- .find(|controller| controller.schema.function == function)- .unwrap_or_else(|| panic!("controller {function} registered"))-}--async fn call(controller: &RegisteredController, params: Value) -> Result<Value, String> {- let params = params.as_object().cloned().unwrap_or_default();- (controller.handler)(params).await-}--fn temp_config(tmp: &TempDir) -> Config {- let root = tmp.path().join(".openhuman");- std::fs::create_dir_all(root.join("workspace")).expect("workspace dir");- let mut config = Config::default();- config.config_path = root.join("config.toml");- config.workspace_dir = root.join("workspace");- config.secrets.encrypt = false;- config.api_url = Some("http://127.0.0.1:9".to_string());- config-}--fn write_stub_script(dir: &Path, name: &str, body: &str) -> PathBuf {- let path = dir.join(name);- std::fs::write(&path, body).expect("write stub");- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let mut perms = std::fs::metadata(&path).expect("metadata").permissions();- perms.set_mode(0o755);- std::fs::set_permissions(&path, perms).expect("chmod");- }- path-}diff --git a/tests/raw_coverage/inference_local_services_round21_raw_coverage_e2e.rs b/tests/raw_coverage/inference_local_services_round21_raw_coverage_e2e.rsdeleted file mode 100644index 9b06b086fb..0000000000--- a/tests/raw_coverage/inference_local_services_round21_raw_coverage_e2e.rs+++ /dev/null@@ -1,429 +0,0 @@-//! Round 21 raw/E2E coverage for local inference service paths.-//!-//! This suite uses temp workspaces, temp PATH scripts, and loopback HTTP mocks only.-//! It must not call host Ollama, MLX, Python, Whisper, Piper, or model binaries.--use std::path::{Path, PathBuf};-use std::sync::{Arc, Mutex, OnceLock};-use std::time::{Duration, Instant};--use axum::body::Body;-use axum::extract::State;-use axum::http::{header, HeaderMap, Response, StatusCode};-use axum::response::IntoResponse;-use axum::routing::{get, post};-use axum::{Json, Router};-use openhuman_core::core::all::RegisteredController;-use openhuman_core::config::Config;-use openhuman_core::inference::host_runtime::ops::{- local_ai_assets_status, local_ai_chat, local_ai_download_asset, local_ai_downloads_progress,- local_ai_prompt, local_ai_transcribe, local_ai_transcribe_bytes,- LocalAiChatMessage,-};-use openhuman_core::inference::host_runtime::{- all_local_inference_registered_controllers, LocalAiService,-};-use serde_json::{json, Value};-use tempfile::{tempdir, TempDir};--#[derive(Clone, Default)]-struct MockState {- requests: Arc<Mutex<Vec<(String, Value)>>>,- ollama_models: Arc<Mutex<Vec<String>>>,-}--struct EnvVarGuard {- key: &'static str,- previous: Option<std::ffi::OsString>,-}--impl EnvVarGuard {- fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {- let previous = std::env::var_os(key);- // SAFETY: validation runs this integration test with --test-threads=1.- unsafe { std::env::set_var(key, value) };- Self { key, previous }- }-- fn unset(key: &'static str) -> Self {- let previous = std::env::var_os(key);- // SAFETY: validation runs this integration test with --test-threads=1.- unsafe { std::env::remove_var(key) };- Self { key, previous }- }-}--impl Drop for EnvVarGuard {- fn drop(&mut self) {- match &self.previous {- Some(value) => {- // SAFETY: validation runs this integration test with --test-threads=1.- unsafe { std::env::set_var(self.key, value) }- }- None => {- // SAFETY: validation runs this integration test with --test-threads=1.- unsafe { std::env::remove_var(self.key) }- }- }- }-}--static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;--fn env_lock() -> std::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| Mutex::new(()))- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())-}--#[tokio::test]-async fn local_services_cover_mocked_inference_assets_speech_and_ops_entry_points() {- let _lock = env_lock();- let (base, state) = serve_mock().await;- let tmp = tempdir().expect("tempdir");- let scripts = tempdir().expect("scripts");- write_stub_script(- scripts.path(),- "piper",- "#!/bin/sh\nwhile [ \"$#\" -gt 0 ]; do\n if [ \"$1\" = \"--output_file\" ]; then shift; out=\"$1\"; fi\n shift || true\ndone\ninput=''\nwhile IFS= read -r line || [ -n \"$line\" ]; do input=\"${input}${line}\"; done\n[ \"$input\" = 'hello from piper' ] || exit 1\nprintf 'RIFFmock' > \"$out\"\n",- );- write_stub_script(scripts.path(), "ollama", "#!/bin/sh\nexit 42\n");- write_stub_script(scripts.path(), "python", "#!/bin/sh\nexit 42\n");- write_stub_script(scripts.path(), "python3", "#!/bin/sh\nexit 42\n");- write_stub_script(scripts.path(), "mlx_lm.generate", "#!/bin/sh\nexit 42\n");-- let mut config = temp_config(&tmp);- config.local_ai.runtime_enabled = true;- config.local_ai.opt_in_confirmed = true;- config.local_ai.provider = "ollama".to_string();- config.local_ai.base_url = Some(base.clone());- config.local_ai.selected_tier = Some("custom".to_string());- config.local_ai.chat_model_id = "gemma3:1b-it-qat".to_string();- config.local_ai.embedding_model_id = "bge-m3".to_string();- config.local_ai.vision_model_id = String::new();- config.local_ai.preload_embedding_model = false;- config.local_ai.preload_vision_model = false;- config.local_ai.preload_tts_voice = false;- config.local_ai.tts_voice_id = "round21-voice".to_string();- config.local_ai.tts_download_url = Some(format!("{base}/asset/tts"));- config.local_ai.tts_config_download_url = Some(format!("{base}/asset/tts-json"));- config.save().await.expect("save config");-- let _path = EnvVarGuard::set("PATH", scripts.path());- let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", config.config_path.parent().unwrap());- let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base);- let _ollama_bin = EnvVarGuard::unset("OLLAMA_BIN");- let _piper_bin = EnvVarGuard::unset("PIPER_BIN");-- let runtime = openhuman_core::inference::local_runtime_config(&config);- let service = LocalAiService::new(&runtime);-- let initial_assets = service.assets_status(&runtime).await.expect("assets");- assert!(initial_assets.ollama_available);- assert_eq!(initial_assets.chat.state, "ready");- assert_eq!(initial_assets.vision.state, "disabled");- assert_eq!(initial_assets.embedding.state, "ready");- assert_eq!(initial_assets.tts.state, "ondemand");-- assert_eq!(- service- .prompt(&runtime, " say hello ", Some(12), true)- .await- .expect("prompt"),- "generated: say hello"- );- assert_eq!(- service- .summarize(&runtime, "decision: ship tests", Some(32))- .await- .expect("summary"),- "generated: Summarize this text in concise bullet points. Preserve decisions and commitments.\n\ndecision: ship tests"- );- assert_eq!(- service- .inline_complete(- &runtime,- "The patch",- "concise",- Some("technical"),- &["The patch adds tests".to_string()],- Some(8),- )- .await- .expect("inline"),- "adds tests"- );-- let _progress = service.downloads_progress(&runtime).await.expect("progress");- let after_tts = service- .download_asset(&runtime, "tts")- .await- .expect("download tts");- assert_eq!(after_tts.tts.state, "ready");-- // Transcription is no longer exercised here: the bundled whisper.cpp- // engine was deleted, so `transcribe` is a hosted call to the backend- // proxy with no local binary this offline test can stub.-- let tts_output = tmp.path().join("out").join("speech.wav");- let tts = openhuman_core::inference::host_runtime::service::tts(- &service,- &config,- "hello from piper",- Some(tts_output.to_string_lossy().as_ref()),- )- .await- .expect("tts");- assert_eq!(tts.voice_id, "round21-voice");- assert!(tts_output.is_file());-- let prompt_outcome = local_ai_prompt(&config, "ops prompt", Some(7), Some(true))- .await- .expect("ops prompt")- .value;- assert_eq!(prompt_outcome, "generated: ops prompt");- let chat_outcome = local_ai_chat(- &config,- vec![- LocalAiChatMessage {- role: "system".to_string(),- content: "stay short".to_string(),- },- LocalAiChatMessage {- role: "USER".to_string(),- content: "chat please".to_string(),- },- ],- Some(20),- )- .await- .expect("ops chat")- .value;- assert_eq!(chat_outcome, "chat generated");- let rejected = local_ai_chat(- &config,- vec![LocalAiChatMessage {- role: "critic".to_string(),- content: "bad role".to_string(),- }],- None,- )- .await- .expect_err("bad chat role");- assert!(rejected.contains("unsupported message role"));-- assert_eq!(- local_ai_downloads_progress(&config)- .await- .expect("ops progress")- .value- .chat- .id,- "gemma3:1b-it-qat"- );- assert_eq!(- local_ai_download_asset(&config, "embedding")- .await- .expect("ops asset")- .value- .embedding- .state,- "ready"- );-- // `install_whisper` / `whisper_install_status` were deleted with the- // bundled whisper.cpp engine, so there is no installer controller left to- // drive here. The remaining assertion proves the mocked Ollama endpoint was- // actually reached by the calls above.- let seen = state.requests.lock().expect("requests").clone();- assert!(seen- .iter()- .any(|(path, _)| path == "/v1/chat/completions"));-}--async fn serve_mock() -> (String, MockState) {- let state = MockState::default();- *state.ollama_models.lock().expect("models") = vec![- "gemma3:1b-it-qat".to_string(),- "bge-m3".to_string(),- "round21-vision".to_string(),- ];- let app = Router::new()- .route("/api/tags", get(ollama_tags))- .route("/api/show", post(ollama_show))- .route("/api/pull", post(ollama_pull))- .route("/v1/chat/completions", post(ollama_chat_completions))- .route("/asset/stt", get(asset_stt))- .route("/asset/tts", get(asset_tts))- .route("/asset/tts-json", get(asset_tts_json))- .with_state(state.clone());- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind mock");- let addr = listener.local_addr().expect("mock addr");- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve mock");- });- (format!("http://{addr}"), state)-}--async fn ollama_tags(State(state): State<MockState>) -> impl IntoResponse {- let models = state- .ollama_models- .lock()- .expect("models")- .iter()- .map(|name| json!({ "name": name, "model": name }))- .collect::<Vec<_>>();- Json(json!({ "models": models }))-}--async fn ollama_show(Json(body): Json<Value>) -> impl IntoResponse {- let model = body- .get("model")- .or_else(|| body.get("name"))- .and_then(Value::as_str)- .unwrap_or_default();- if model == "___nonexistent_probe___" {- return (- StatusCode::NOT_FOUND,- Json(json!({"error": "model not found"})),- )- .into_response();- }- Json(json!({- "model_info": {- "general.context_length": 8192,- "llama.context_length": 8192- }- }))- .into_response()-}--async fn ollama_pull(State(state): State<MockState>, Json(body): Json<Value>) -> impl IntoResponse {- let name = body["name"].as_str().unwrap_or_default().to_string();- if !name.is_empty() {- state.ollama_models.lock().expect("models").push(name);- }- Response::builder()- .status(StatusCode::OK)- .header(header::CONTENT_TYPE, "application/x-ndjson")- .body(Body::from(- json!({"status":"success","total":10,"completed":10}).to_string() + "\n",- ))- .expect("pull response")-}--async fn ollama_chat_completions(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> impl IntoResponse {- remember(&state, "/v1/chat/completions", &headers, body.clone());- let messages = body["messages"].as_array().cloned().unwrap_or_default();- let system = messages- .iter()- .find(|message| message["role"] == "system")- .and_then(|message| message["content"].as_str())- .unwrap_or_default();- let prompt = messages- .iter()- .rev()- .find(|message| message["role"] == "user")- .and_then(|message| message["content"].as_str())- .unwrap_or_default();- let response = if system.contains("inline text completion") {- "adds tests".to_string()- } else if prompt == "chat please" {- "chat generated".to_string()- } else {- format!("generated: {}", prompt.trim())- };- Json(json!({- "id": "chatcmpl-round21",- "choices": [{- "message": { "role": "assistant", "content": response },- "finish_reason": "stop"- }],- "usage": { "prompt_tokens": 2, "completion_tokens": 4, "total_tokens": 6 },- "prompt_eval_count": 2,- "prompt_eval_duration": 1_000_000,- "eval_count": 4,- "eval_duration": 2_000_000- }))-}--async fn asset_stt() -> impl IntoResponse {- bytes_response(vec![b's'; 4096])-}--async fn asset_tts() -> impl IntoResponse {- bytes_response(vec![b't'; 4096])-}--async fn asset_tts_json() -> impl IntoResponse {- bytes_response(br#"{"audio":{"sample_rate":22050}}"#.to_vec())-}--fn bytes_response(bytes: Vec<u8>) -> Response<Body> {- Response::builder()- .status(StatusCode::OK)- .body(Body::from(bytes))- .expect("bytes response")-}--fn remember(state: &MockState, path: &str, _headers: &HeaderMap, body: Value) {- state- .requests- .lock()- .expect("requests")- .push((path.to_string(), body));-}--fn remember_path(state: &MockState, path: &str) {- state- .requests- .lock()- .expect("requests")- .push((path.to_string(), Value::Null));-}--fn controller<'a>(- controllers: &'a [RegisteredController],- function: &str,-) -> &'a RegisteredController {- controllers- .iter()- .find(|controller| controller.schema.function == function)- .unwrap_or_else(|| panic!("controller {function} registered"))-}--async fn call(controller: &RegisteredController, params: Value) -> Result<Value, String> {- let params = params.as_object().cloned().unwrap_or_default();- (controller.handler)(params).await-}--fn temp_config(tmp: &TempDir) -> Config {- let root = tmp.path().join(".openhuman");- std::fs::create_dir_all(root.join("workspace")).expect("workspace dir");- let mut config = Config::default();- config.config_path = root.join("config.toml");- config.workspace_dir = root.join("workspace");- config.secrets.encrypt = false;- config.api_url = Some("http://127.0.0.1:9".to_string());- config-}--fn write_stub_script(dir: &Path, name: &str, body: &str) -> PathBuf {- let path = dir.join(name);- std::fs::write(&path, body).expect("write stub");- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let mut perms = std::fs::metadata(&path).expect("metadata").permissions();- perms.set_mode(0o755);- std::fs::set_permissions(&path, perms).expect("chmod");- }- path-}