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
test(e2e): cover 41 uncovered RPC controllers across 13 namespaces\n\nAdds three suites under tests/raw_coverage/ (modules of the aggregated\nraw_coverage_all target, so no new binary and no Cargo.toml change):\n\n billing_cost_e2e billing (10), cost (4), dashboard (1)\n team_referral_e2e team (9), referral (2), update (3), migrate (1)\n secrets_devices_e2e encrypt, decrypt, security, keyring_consent (3),\n devices (3), wallet (2)\n\nAll thirteen namespaces go to 100%; repo-wide invoked controllers move\n379 -> 420. Every case drives the real router from build_core_http_router\nover HTTP. The hosted domains assert on the request the adapter built\n(method, path, query string, body) as well as the response; the local\ndomains assert against real state -- a seeded costs.jsonl, the\npaired_devices SQLite table, the persisted app-state.json.\n\nTwo harness details worth knowing:\n\n * The RPC bearer is read, not asserted. core::auth::RPC_TOKEN is a\n process-global OnceLock and init_rpc_token is first-writer-wins, so a\n suite that hard-codes its own token 401s whenever another suite\n initialised first. w4_shared::rpc_token() asks for the live value.\n * env_lock binds to crate::SHARED_ENV_LOCK, not a private static, so\n HOME / OPENHUMAN_WORKSPACE mutations serialize against every other\n aggregated suite.\n\nVerified with 12 fault injections into src/ (13 sites), each confirmed to\nfail the named assertion and then reverted; src/ is unchanged by this\ncommit. One case is #[ignore]d, documenting that a hand-written\nallowed_commands is widened by the 3->4 autonomy migration.\n\nNo production code is changed.\n
M3gA-Mind522ab5d3f109
diff --git a/tests/raw_coverage/billing_cost_e2e.rs b/tests/raw_coverage/billing_cost_e2e.rsnew file mode 100644index 0000000000..2af527cd4d--- /dev/null+++ b/tests/raw_coverage/billing_cost_e2e.rs@@ -0,0 +1,767 @@+//! RPC-level e2e coverage for `openhuman.billing_*`, `openhuman.cost_*` and+//! `openhuman.dashboard_model_health`.+//!+//! Every case drives the real JSON-RPC router (`build_core_http_router`) over+//! HTTP, exactly as the desktop app does. The billing cases talk to an+//! in-process mock of the hosted payments API; the cost and dashboard cases are+//! entirely local — cost reads a seeded `costs.jsonl`, and model health is a+//! pure projection of `config.toml`.+//!+//! A module of the aggregated `raw_coverage_all` target, not a target of its+//! own. Run with:+//! cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" \+//! -- billing_cost_e2e++#[path = "w4_shared/mod.rs"]+mod support;++use serde_json::{json, Value};+use support::{assert_error, assert_no_error, error_message, logs, mock_log, peel, Harness};++/// Every persisted cost record the seeding helper writes, as one JSONL line.+fn cost_record_line(id: &str, model: &str, cost_usd: f64, input: u64, output: u64) -> String {+ let record = json!({+ "id": id,+ "session_id": "w4-seeded-session",+ "usage": {+ "model": model,+ "input_tokens": input,+ "output_tokens": output,+ "total_tokens": input + output,+ "cached_input_tokens": 0,+ "cache_creation_tokens": 0,+ "reasoning_tokens": 0,+ "cost_usd": cost_usd,+ "cost_source": "estimated",+ // Today, so it lands in the current day, the current month, and the+ // trailing-7-day dashboard window all at once.+ "timestamp": chrono::Utc::now().to_rfc3339(),+ }+ });+ format!("{record}\n")+}++// ── billing ──────────────────────────────────────────────────────────────────++/// The ten read/write billing controllers that had no e2e target, driven against+/// the mock payments backend with a stored session.+#[tokio::test]+async fn billing_uncovered_controllers_round_trip_against_the_backend() {+ let _lock = support::env_lock();+ let harness = Harness::start("", false).await;+ let log = mock_log();+ log.clear();+ harness.login().await;++ // --- billing_get_balance ------------------------------------------------+ let balance = harness+ .call(10, "openhuman.billing_get_balance", json!({}))+ .await;+ let balance = peel(assert_no_error(&balance, "billing_get_balance"));+ assert_eq!(+ balance.get("balanceUsd").and_then(Value::as_f64),+ Some(42.5),+ "the adapter must surface the backend's `data` payload verbatim: {balance}"+ );+ assert_eq!(+ balance.get("currency").and_then(Value::as_str),+ Some("USD"),+ "every field of `data` should survive, not just the first: {balance}"+ );++ // --- billing_get_transactions: defaults are part of the contract --------+ let txns = harness+ .call(11, "openhuman.billing_get_transactions", json!({}))+ .await;+ let txns_result = assert_no_error(&txns, "billing_get_transactions");+ let txns_inner = peel(txns_result);+ let rows = txns_inner+ .get("transactions")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("expected a `transactions` array: {txns_inner}"));+ assert_eq!(rows.len(), 2, "seeded two transactions: {txns_inner}");+ assert_eq!(+ rows[0].get("id").and_then(Value::as_str),+ Some("txn-1"),+ "order must be preserved through the adapter: {txns_inner}"+ );+ let recorded = log+ .first_with_path_prefix("/payments/credits/transactions")+ .expect("the transactions call must have reached the backend");+ assert_eq!(+ recorded.get("path").and_then(Value::as_str),+ Some("/payments/credits/transactions?limit=20&offset=0"),+ "an empty params map must still send the documented limit=20/offset=0 defaults: {recorded}"+ );++ // ...and an explicit page is forwarded as given.+ let paged = harness+ .call(+ 12,+ "openhuman.billing_get_transactions",+ json!({ "limit": 5, "offset": 10 }),+ )+ .await;+ assert_no_error(&paged, "billing_get_transactions paged");+ let paths: Vec<String> = log+ .entries()+ .iter()+ .filter_map(|e| e.get("path").and_then(Value::as_str).map(str::to_string))+ .collect();+ assert!(+ paths.contains(&"/payments/credits/transactions?limit=5&offset=10".to_string()),+ "explicit limit/offset must reach the backend as a query string; saw {paths:?}"+ );++ // --- billing_get_auto_recharge -----------------------------------------+ let auto = harness+ .call(13, "openhuman.billing_get_auto_recharge", json!({}))+ .await;+ let auto = peel(assert_no_error(&auto, "billing_get_auto_recharge"));+ assert_eq!(auto.get("enabled").and_then(Value::as_bool), Some(true));+ assert_eq!(+ auto.get("thresholdUsd").and_then(Value::as_f64),+ Some(5.0),+ "auto-recharge settings must round-trip unchanged: {auto}"+ );++ // --- billing_update_auto_recharge: the payload is forwarded verbatim ----+ let updated = harness+ .call(+ 14,+ "openhuman.billing_update_auto_recharge",+ json!({ "payload": { "enabled": false, "thresholdUsd": 2.0 } }),+ )+ .await;+ let updated = peel(assert_no_error(&updated, "billing_update_auto_recharge"));+ assert_eq!(+ updated.get("enabled").and_then(Value::as_bool),+ Some(false),+ "the mock echoes the PATCH body; a reshaped payload would show here: {updated}"+ );+ assert_eq!(updated.get("updated").and_then(Value::as_bool), Some(true));+ let patch = log+ .first_with_path_prefix("/payments/credits/auto-recharge")+ .expect("no auto-recharge request reached the backend");+ assert!(+ log.entries().iter().any(|e| {+ e.get("method").and_then(Value::as_str) == Some("PATCH")+ && e.get("body").and_then(|b| b.get("thresholdUsd")).and_then(Value::as_f64)+ == Some(2.0)+ }),+ "the PATCH body must carry the caller's payload unwrapped (no `payload` envelope); saw {:?}",+ patch+ );++ // --- billing_get_cards --------------------------------------------------+ let cards = harness+ .call(15, "openhuman.billing_get_cards", json!({}))+ .await;+ let cards = peel(assert_no_error(&cards, "billing_get_cards"));+ let cards_arr = cards+ .as_array()+ .unwrap_or_else(|| panic!("expected an array of cards: {cards}"));+ assert_eq!(cards_arr.len(), 2, "seeded two saved cards: {cards}");+ assert_eq!(+ cards_arr[0].get("last4").and_then(Value::as_str),+ Some("4242")+ );++ // --- billing_create_setup_intent ---------------------------------------+ let intent = harness+ .call(16, "openhuman.billing_create_setup_intent", json!({}))+ .await;+ let intent = peel(assert_no_error(&intent, "billing_create_setup_intent"));+ assert_eq!(+ intent.get("clientSecret").and_then(Value::as_str),+ Some("seti_w4_secret"),+ "a SetupIntent with no clientSecret is useless to the frontend: {intent}"+ );++ // --- billing_update_card: the id is percent-encoded into the path -------+ // `pm/with space` cannot escape its path segment; the mock decodes it back,+ // so an unencoded id would 404 here instead of echoing.+ let card_update = harness+ .call(+ 17,+ "openhuman.billing_update_card",+ json!({ "paymentMethodId": "pm/with space", "payload": { "isDefault": true } }),+ )+ .await;+ let card_update = peel(assert_no_error(&card_update, "billing_update_card"));+ assert_eq!(+ card_update.get("paymentMethodId").and_then(Value::as_str),+ Some("pm/with space"),+ "the id must survive percent-encoding into the path and decode back: {card_update}"+ );+ assert_eq!(+ card_update.get("isDefault").and_then(Value::as_bool),+ Some(true),+ "the PATCH payload must reach the backend: {card_update}"+ );++ // --- billing_delete_card ------------------------------------------------+ let deleted = harness+ .call(+ 18,+ "openhuman.billing_delete_card",+ json!({ "paymentMethodId": "pm_2" }),+ )+ .await;+ let deleted = peel(assert_no_error(&deleted, "billing_delete_card"));+ assert_eq!(+ deleted.get("deleted").and_then(Value::as_str),+ Some("pm_2"),+ "delete must name the card it removed: {deleted}"+ );++ // --- billing_redeem_coupon (happy) -------------------------------------+ let redeemed = harness+ .call(+ 19,+ "openhuman.billing_redeem_coupon",+ json!({ "code": "WELCOME10" }),+ )+ .await;+ let redeemed_outer = assert_no_error(&redeemed, "billing_redeem_coupon");+ assert!(+ logs(redeemed_outer).iter().any(|l| l == "coupon redeemed"),+ "the outcome must carry its log line: {redeemed_outer}"+ );+ let redeemed = peel(redeemed_outer);+ assert_eq!(+ redeemed.get("creditsUsd").and_then(Value::as_f64),+ Some(10.0),+ "the redemption result must reach the caller: {redeemed}"+ );++ // --- billing_get_coupons ------------------------------------------------+ let coupons = harness+ .call(20, "openhuman.billing_get_coupons", json!({}))+ .await;+ let coupons = peel(assert_no_error(&coupons, "billing_get_coupons"));+ let coupons_arr = coupons+ .as_array()+ .unwrap_or_else(|| panic!("expected an array of coupons: {coupons}"));+ assert_eq!(coupons_arr.len(), 1, "seeded one redeemed coupon: {coupons}");+ assert_eq!(+ coupons_arr[0].get("code").and_then(Value::as_str),+ Some("WELCOME10")+ );+}++/// The failure half: backend rejections must surface, and the pre-HTTP+/// validation in `billing/ops.rs` must reject before any request is made.+#[tokio::test]+async fn billing_rejects_bad_input_before_it_reaches_the_backend() {+ let _lock = support::env_lock();+ let harness = Harness::start("", false).await;+ harness.login().await;+ let log = mock_log();++ // A coupon the backend refuses — the 400 must reach the caller, not be+ // swallowed into an empty success.+ let bad_coupon = harness+ .call(+ 30,+ "openhuman.billing_redeem_coupon",+ json!({ "code": "NOPE" }),+ )+ .await;+ let message = error_message(&bad_coupon, "billing_redeem_coupon unknown code");+ assert!(+ message.contains("not redeemable"),+ "the backend's rejection text must survive to the caller; got: {message}"+ );++ // Everything below must fail *without* a network call. Clearing the log+ // first is what makes the "no request was made" assertion meaningful.+ log.clear();++ let blank_code = harness+ .call(31, "openhuman.billing_redeem_coupon", json!({ "code": " " }))+ .await;+ assert!(+ error_message(&blank_code, "blank coupon").contains("code is required"),+ "a whitespace-only coupon code must be rejected locally: {blank_code}"+ );++ let blank_card = harness+ .call(+ 32,+ "openhuman.billing_delete_card",+ json!({ "paymentMethodId": " " }),+ )+ .await;+ assert!(+ error_message(&blank_card, "blank paymentMethodId").contains("paymentMethodId is required"),+ "a blank card id must never be encoded into a DELETE path: {blank_card}"+ );++ assert!(+ log.entries().is_empty(),+ "input validation is documented as pre-HTTP, but these requests reached the backend: {:?}",+ log.entries()+ );+}++/// With no stored session the adapters must refuse locally rather than firing a+/// doomed unauthenticated request.+#[tokio::test]+async fn billing_without_a_session_refuses_locally() {+ let _lock = support::env_lock();+ let harness = Harness::start("", false).await;+ let log = mock_log();+ log.clear();++ let balance = harness+ .call(40, "openhuman.billing_get_balance", json!({}))+ .await;+ let message = error_message(&balance, "billing_get_balance with no session");+ assert!(+ message.contains("no backend session token")+ && message.contains("auth_store_session"),+ "the error must name the missing session *and* the call that fixes it, \+ so the UI can route to sign-in rather than show a bare failure; got: {message}"+ );++ let cards = harness+ .call(41, "openhuman.billing_get_cards", json!({}))+ .await;+ assert_error(&cards, "billing_get_cards with no session");++ assert!(+ !log.entries().iter().any(|e| e+ .get("path")+ .and_then(Value::as_str)+ .is_some_and(|p| p.starts_with("/payments"))),+ "a session-less billing call must not hit /payments at all: {:?}",+ log.entries()+ );+}++// ── cost ─────────────────────────────────────────────────────────────────────++/// All four `cost_*` controllers over a seeded `costs.jsonl`.+///+/// The seed deliberately mixes a **managed** tier slug with a **BYOK** model id:+/// #5016 makes the monthly budget count managed spend only, so `period_total_usd`+/// and `month_to_date_usd` must disagree. A dashboard that summed everything+/// into the budget would pass a "not empty" test and fail this one.+#[tokio::test]+async fn cost_controllers_report_seeded_usage_and_split_managed_from_byok() {+ let _lock = support::env_lock();+ let harness = Harness::start(+ r#"+[cost]+enabled = true+monthly_limit_usd = 10.0++[cost.dashboard]+enabled = true+currency = "USD"+warn_threshold = 0.5+alert_threshold = 0.9+"#,+ true,+ )+ .await;++ // Seed the append-only log the tracker reads. `chat-v1` is a managed tier+ // slug; `anthropic/claude-sonnet-4-20250514` is BYOK.+ let state_dir = harness.workspace().join("state");+ std::fs::create_dir_all(&state_dir).expect("create state dir");+ let mut jsonl = String::new();+ jsonl.push_str(&cost_record_line("rec-managed", "chat-v1", 6.0, 1_000, 500));+ jsonl.push_str(&cost_record_line(+ "rec-byok",+ "anthropic/claude-sonnet-4-20250514",+ 4.0,+ 2_000,+ 800,+ ));+ jsonl.push_str(&cost_record_line(+ "rec-embed",+ "openai/text-embedding-3-small",+ 0.5,+ 300,+ 0,+ ));+ std::fs::write(state_dir.join("costs.jsonl"), &jsonl).expect("seed costs.jsonl");++ // --- cost_get_summary ---------------------------------------------------+ let summary = harness+ .call(50, "openhuman.cost_get_summary", json!({}))+ .await;+ let summary = peel(assert_no_error(&summary, "cost_get_summary"));+ assert_eq!(+ summary.get("daily_cost_usd").and_then(Value::as_f64),+ Some(10.5),+ "today's total must be every seeded record, managed and BYOK alike: {summary}"+ );+ assert_eq!(+ summary.get("monthly_cost_usd").and_then(Value::as_f64),+ Some(10.5),+ "the seeded records are all in the current month: {summary}"+ );+ assert_eq!(+ summary.get("session_cost_usd").and_then(Value::as_f64),+ Some(0.0),+ "the RPC fallback tracker has recorded nothing itself, so the *session* \+ figure must stay zero even though the file is full: {summary}"+ );++ // --- cost_get_dashboard -------------------------------------------------+ let dashboard = harness+ .call(51, "openhuman.cost_get_dashboard", json!({}))+ .await;+ let dashboard = peel(assert_no_error(&dashboard, "cost_get_dashboard"));+ assert_eq!(+ dashboard.get("period_total_usd").and_then(Value::as_f64),+ Some(10.5),+ "the 7-day period total counts all routes: {dashboard}"+ );+ assert_eq!(+ dashboard.get("month_to_date_usd").and_then(Value::as_f64),+ Some(10.5),+ "month-to-date is the all-routes figure — the split lives in the budget \+ fields below, not here: {dashboard}"+ );+ assert_eq!(+ dashboard.get("budget_utilization").and_then(Value::as_f64),+ Some(0.6),+ "#5016: the gauge is driven by *managed* spend only — 6.0 of `chat-v1` \+ against a 10.0 monthly limit is 60%. Driving it off the 10.5 all-routes \+ total would read 100% against a cap BYOK spend can never trip: {dashboard}"+ );+ assert_eq!(+ dashboard.get("budget_status").and_then(Value::as_str),+ Some("warning"),+ "60% managed utilisation is past the configured 0.5 warn threshold and \+ short of 0.9; the all-routes 105% would have read `exceeded`: {dashboard}"+ );+ assert_eq!(+ dashboard.get("currency").and_then(Value::as_str),+ Some("USD")+ );+ let days = dashboard+ .get("days")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("dashboard must carry a `days` array: {dashboard}"));+ assert_eq!(+ days.len(),+ 7,+ "the dashboard window is 7 days, zero-filled: {dashboard}"+ );+ let today = days.last().expect("7 entries");+ assert_eq!(+ today.get("cost_usd").and_then(Value::as_f64),+ Some(10.5),+ "the newest day is last and holds every seeded record: {today}"+ );+ let by_model = dashboard+ .get("by_model")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("dashboard must carry `by_model`: {dashboard}"));+ assert_eq!(by_model.len(), 3, "three distinct models seeded: {by_model:?}");+ let managed = by_model+ .iter()+ .find(|m| m.get("model").and_then(Value::as_str) == Some("chat-v1"))+ .unwrap_or_else(|| panic!("`chat-v1` missing from by_model: {by_model:?}"));+ assert!(+ managed.get("provider").is_some_and(Value::is_null),+ "a bare tier slug has no `provider/` prefix, so provider stays null \+ rather than being invented: {managed}"+ );+ let byok = by_model+ .iter()+ .find(|m| {+ m.get("model").and_then(Value::as_str) == Some("anthropic/claude-sonnet-4-20250514")+ })+ .expect("BYOK model missing from by_model");+ assert_eq!(+ byok.get("provider").and_then(Value::as_str),+ Some("anthropic"),+ "provider is derived from the slash prefix: {byok}"+ );++ // --- cost_get_daily_history --------------------------------------------+ let history = harness+ .call(+ 52,+ "openhuman.cost_get_daily_history",+ json!({ "days": 3 }),+ )+ .await;+ let history = peel(assert_no_error(&history, "cost_get_daily_history"));+ let entries = history+ .as_array()+ .unwrap_or_else(|| panic!("daily history must be an array: {history}"));+ assert_eq!(entries.len(), 3, "asked for 3 days: {history}");+ assert_eq!(+ entries[0].get("cost_usd").and_then(Value::as_f64),+ Some(0.0),+ "gap days must be zero-filled, not omitted: {history}"+ );+ assert_eq!(+ entries[2].get("cost_usd").and_then(Value::as_f64),+ Some(10.5),+ "oldest first, so today is last: {history}"+ );+ assert_eq!(+ entries[2].get("request_count").and_then(Value::as_u64),+ Some(3),+ "three records landed today: {history}"+ );++ // An out-of-range span is clamped rather than rejected.+ let clamped = harness+ .call(+ 53,+ "openhuman.cost_get_daily_history",+ json!({ "days": 100_000 }),+ )+ .await;+ let clamped = peel(assert_no_error(&clamped, "cost_get_daily_history clamped"));+ assert_eq!(+ clamped.as_array().map(Vec::len),+ Some(366),+ "days is documented as clamped to [1, 366]: {clamped}"+ );++ // --- cost_get_usage_log -------------------------------------------------+ let usage = harness+ .call(54, "openhuman.cost_get_usage_log", json!({}))+ .await;+ let usage = peel(assert_no_error(&usage, "cost_get_usage_log"));+ assert_eq!(+ usage.get("request_count").and_then(Value::as_u64),+ Some(3),+ "every seeded record is inside the default 30-day window: {usage}"+ );+ assert_eq!(+ usage.get("total_cost_usd").and_then(Value::as_f64),+ Some(10.5)+ );+ assert_eq!(+ usage.get("days").and_then(Value::as_u64),+ Some(30),+ "the default span is echoed back: {usage}"+ );+ assert_eq!(+ usage.get("limit").and_then(Value::as_u64),+ Some(250),+ "the default limit is echoed back: {usage}"+ );+ let categories: Vec<(&str, f64)> = usage+ .get("by_category")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("usage log must carry `by_category`: {usage}"))+ .iter()+ .map(|c| {+ (+ c.get("category").and_then(Value::as_str).unwrap_or(""),+ c.get("cost_usd").and_then(Value::as_f64).unwrap_or(f64::NAN),+ )+ })+ .collect();+ assert_eq!(+ categories,+ vec![("AI chat and reasoning", 10.0), ("Embeddings", 0.5)],+ "categories are inferred from the model id and sorted by spend: {usage}"+ );+ let records = usage+ .get("records")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("usage log must carry `records`: {usage}"));+ assert_eq!(records.len(), 3);+ assert!(+ records.iter().all(|r| r.get("cost_source").and_then(Value::as_str)+ == Some("estimated")),+ "persisted cost provenance must survive into the DTO: {records:?}"+ );++ // An over-large limit is clamped, and the clamped value is what is reported.+ let capped = harness+ .call(+ 55,+ "openhuman.cost_get_usage_log",+ json!({ "days": 1, "limit": 99_999 }),+ )+ .await;+ let capped = peel(assert_no_error(&capped, "cost_get_usage_log clamped"));+ assert_eq!(+ capped.get("limit").and_then(Value::as_u64),+ Some(1000),+ "limit is documented as clamped to [1, 1000]: {capped}"+ );+ assert_eq!(capped.get("days").and_then(Value::as_u64), Some(1));+}++/// The empty-workspace path: no `costs.jsonl` at all must still answer, not error.+#[tokio::test]+async fn cost_controllers_answer_on_a_workspace_with_no_history() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;++ let summary = harness+ .call(60, "openhuman.cost_get_summary", json!({}))+ .await;+ let summary = peel(assert_no_error(&summary, "cost_get_summary empty"));+ assert_eq!(+ summary.get("daily_cost_usd").and_then(Value::as_f64),+ Some(0.0),+ "a fresh workspace has zero spend, not an error: {summary}"+ );+ assert_eq!(+ summary.get("request_count").and_then(Value::as_u64),+ Some(0)+ );++ let usage = harness+ .call(61, "openhuman.cost_get_usage_log", json!({}))+ .await;+ let usage = peel(assert_no_error(&usage, "cost_get_usage_log empty"));+ assert_eq!(+ usage.get("records").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "no records, but the envelope must still be well formed: {usage}"+ );+ assert_eq!(+ usage.get("by_category").and_then(Value::as_array).map(Vec::len),+ Some(0)+ );+}++// ── dashboard ────────────────────────────────────────────────────────────────++/// `dashboard_model_health` projects `model_registry` and the configured+/// thresholds, with telemetry fields held as documented placeholders.+#[tokio::test]+async fn dashboard_model_health_projects_the_registry_and_thresholds() {+ let _lock = support::env_lock();+ let harness = Harness::start(+ r#"+[dashboard.model_health]+enabled = true+hallucination_threshold = 0.11+min_tasks_for_rating = 7+evaluation_window_tasks = 42++[[model_registry]]+id = "w4/alpha"+provider = "w4"+cost_per_1m_input = 1.5+cost_per_1m_output = 6.0+context_window = 200000+vision = true++[[model_registry]]+id = "w4/beta"+provider = "w4"+cost_per_1m_input = 0.25+cost_per_1m_output = 1.0+context_window = 32000+vision = false+"#,+ true,+ )+ .await;++ let health = harness+ .call(70, "openhuman.dashboard_model_health", json!({}))+ .await;+ let health_outer = assert_no_error(&health, "dashboard_model_health");+ assert!(+ logs(health_outer)+ .iter()+ .any(|l| l.contains("returned 2 models")),+ "the log line must report the row count it actually built: {health_outer}"+ );+ let health = peel(health_outer);++ let models = health+ .get("models")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("expected a `models` array: {health}"));+ assert_eq!(+ models.len(),+ 2,+ "one row per registry entry, in registry order: {health}"+ );+ assert_eq!(models[0].get("id").and_then(Value::as_str), Some("w4/alpha"));+ assert_eq!(+ models[0].get("cost_per_1m_output").and_then(Value::as_f64),+ Some(6.0),+ "cost must come from the registry, not a default: {health}"+ );+ assert_eq!(+ models[0].get("context_window").and_then(Value::as_u64),+ Some(200_000)+ );+ assert_eq!(models[0].get("vision").and_then(Value::as_bool), Some(true));+ assert_eq!(models[1].get("vision").and_then(Value::as_bool), Some(false));++ // The placeholder contract, which the frontend reads as "no signal".+ for row in models {+ assert!(+ row.get("quality_score").is_some_and(Value::is_null),+ "quality_score is a documented `null` placeholder until telemetry lands: {row}"+ );+ assert!(+ row.get("hallucination_rate").is_some_and(Value::is_null),+ "hallucination_rate is a documented `null` placeholder: {row}"+ );+ assert_eq!(+ row.get("agents_using").and_then(Value::as_u64),+ Some(0),+ "`agents_using` is a documented `0` placeholder — there is no local \+ telemetry sink to populate it yet: {row}"+ );+ assert_eq!(+ row.get("tasks_evaluated").and_then(Value::as_u64),+ Some(0),+ "`tasks_evaluated` is a documented `0` placeholder: {row}"+ );+ }++ let cfg = health+ .get("config")+ .unwrap_or_else(|| panic!("expected a `config` view: {health}"));+ assert_eq!(+ cfg.get("hallucination_threshold").and_then(Value::as_f64),+ Some(0.11),+ "thresholds must come from config so the frontend can badge rows: {cfg}"+ );+ assert_eq!(+ cfg.get("min_tasks_for_rating").and_then(Value::as_u64),+ Some(7)+ );+ assert_eq!(+ cfg.get("evaluation_window_tasks").and_then(Value::as_u64),+ Some(42)+ );+}++/// The disabled-feature path is an error, not an empty table.+#[tokio::test]+async fn dashboard_model_health_refuses_when_disabled() {+ let _lock = support::env_lock();+ let harness = Harness::start(+ r#"+[dashboard.model_health]+enabled = false+"#,+ true,+ )+ .await;++ let health = harness+ .call(80, "openhuman.dashboard_model_health", json!({}))+ .await;+ let message = error_message(&health, "dashboard_model_health disabled");+ assert!(+ message.contains("model health disabled"),+ "a disabled panel must say so rather than return an empty list; got: {message}"+ );+}diff --git a/tests/raw_coverage/secrets_devices_e2e.rs b/tests/raw_coverage/secrets_devices_e2e.rsnew file mode 100644index 0000000000..574b825a70--- /dev/null+++ b/tests/raw_coverage/secrets_devices_e2e.rs@@ -0,0 +1,896 @@+//! RPC-level e2e coverage for the local credential surface:+//! `openhuman.encrypt_secret` / `decrypt_secret`, `openhuman.security_policy_info`,+//! `openhuman.keyring_consent_*`, `openhuman.devices_*`, and the two uncovered+//! `openhuman.wallet_*` controllers.+//!+//! Nothing here needs a backend — every case is local state, which is what makes+//! the assertions exact rather than tolerant.+//!+//! A module of the aggregated `raw_coverage_all` target, not a target of its+//! own. Run with:+//! cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" \+//! -- secrets_devices_e2e++#[path = "w4_shared/mod.rs"]+mod support;++use serde_json::{json, Value};+use support::{assert_no_error, error_message, logs, peel, Harness};++/// A `Config` pointing at the harness's workspace, for the few cases that seed+/// domain state directly rather than through an RPC that cannot create it.+fn config_for(harness: &Harness) -> openhuman_core::openhuman::config::Config {+ openhuman_core::openhuman::config::Config {+ workspace_dir: harness.workspace(),+ ..Default::default()+ }+}++// ── encrypt / decrypt ────────────────────────────────────────────────────────++/// The `encrypt_secret` → `decrypt_secret` round trip, plus the two edge shapes+/// the codec is documented to have.+#[tokio::test]+async fn encrypt_and_decrypt_secret_round_trip() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;+ let plaintext = "correct horse battery staple";++ let encrypted = harness+ .call(+ 10,+ "openhuman.encrypt_secret",+ json!({ "plaintext": plaintext }),+ )+ .await;+ let encrypted_outer = assert_no_error(&encrypted, "encrypt_secret");+ assert!(+ logs(encrypted_outer).iter().any(|l| l == "secret encrypted"),+ "the outcome must carry its log line: {encrypted_outer}"+ );+ let ciphertext = peel(encrypted_outer)+ .as_str()+ .unwrap_or_else(|| panic!("encrypt_secret must return a string: {encrypted_outer}"))+ .to_string();++ assert!(+ ciphertext.starts_with("enc2:"),+ "the current codec is ChaCha20-Poly1305 behind an `enc2:` tag; an \+ untagged value would be handed back verbatim by `decrypt_secret` and \+ so would never be detected as unencrypted: {ciphertext}"+ );+ assert!(+ !ciphertext.contains("horse"),+ "the plaintext must not survive into the ciphertext: {ciphertext}"+ );+ assert!(+ ciphertext.len() > plaintext.len(),+ "nonce + tag must be present: {ciphertext}"+ );++ let decrypted = harness+ .call(+ 11,+ "openhuman.decrypt_secret",+ json!({ "ciphertext": ciphertext }),+ )+ .await;+ let decrypted_outer = assert_no_error(&decrypted, "decrypt_secret");+ assert_eq!(+ peel(decrypted_outer).as_str(),+ Some(plaintext),+ "the round trip must return the exact plaintext: {decrypted_outer}"+ );++ // Encrypting twice must not produce the same ciphertext — a fresh nonce per+ // call is what stops two equal secrets being linkable on disk.+ let again = harness+ .call(+ 12,+ "openhuman.encrypt_secret",+ json!({ "plaintext": plaintext }),+ )+ .await;+ let second = peel(assert_no_error(&again, "encrypt_secret twice"))+ .as_str()+ .expect("encrypt_secret must return a string")+ .to_string();+ assert_ne!(+ second, ciphertext,+ "the same plaintext must encrypt to a different ciphertext each time"+ );+ let decrypted_second = harness+ .call(+ 13,+ "openhuman.decrypt_secret",+ json!({ "ciphertext": second }),+ )+ .await;+ assert_eq!(+ peel(assert_no_error(&decrypted_second, "decrypt second")).as_str(),+ Some(plaintext),+ "both ciphertexts must decrypt back to the same plaintext"+ );+}++/// The failure and pass-through shapes of the codec.+#[tokio::test]+async fn decrypt_secret_rejects_a_corrupted_payload_and_passes_plaintext_through() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;++ let encrypted = harness+ .call(20, "openhuman.encrypt_secret", json!({ "plaintext": "secret" }))+ .await;+ let ciphertext = peel(assert_no_error(&encrypted, "encrypt_secret"))+ .as_str()+ .expect("ciphertext")+ .to_string();++ // Flip the last hex nibble — the AEAD tag must reject it rather than+ // returning garbage plaintext.+ let mut corrupted: Vec<char> = ciphertext.chars().collect();+ let last = corrupted.len() - 1;+ corrupted[last] = if corrupted[last] == '0' { '1' } else { '0' };+ let corrupted: String = corrupted.into_iter().collect();+ assert_ne!(corrupted, ciphertext, "the corruption must actually change a byte");++ let failed = harness+ .call(+ 21,+ "openhuman.decrypt_secret",+ json!({ "ciphertext": corrupted }),+ )+ .await;+ error_message(&failed, "decrypt_secret corrupted payload");++ // An untagged value is documented as returned as-is (plaintext config+ // predates the codec). Pinned so the pass-through can't be removed silently.+ let untagged = harness+ .call(+ 22,+ "openhuman.decrypt_secret",+ json!({ "ciphertext": "plain-config-value" }),+ )+ .await;+ assert_eq!(+ peel(assert_no_error(&untagged, "decrypt_secret untagged")).as_str(),+ Some("plain-config-value"),+ "an unprefixed value must pass through unchanged, not error"+ );++ // A missing param is a controller-level error, not a panic.+ let missing = harness.call(23, "openhuman.decrypt_secret", json!({})).await;+ assert!(+ error_message(&missing, "decrypt_secret no params").contains("ciphertext"),+ "the error must name the parameter that was missing: {missing}"+ );+}++// ── security policy ──────────────────────────────────────────────────────────++/// `security_policy_info` is a pure projection of `[autonomy]`. Non-default+/// values are used throughout so a handler that returned struct defaults, or+/// read the wrong config block, fails here.+#[tokio::test]+async fn security_policy_info_reflects_the_configured_autonomy_block() {+ let _lock = support::env_lock();+ // `schema_version` above `CURRENT_SCHEMA_VERSION` makes `run_pending` return+ // early, so no startup migration touches this fixture. Without it the 3->4+ // "expand autonomy defaults" migration merges 28 commands into+ // `allowed_commands` — see the ignored case below and+ // `~/tinyhuman/bugs/e2e-wave-autonomy-migration-widens-allowlist.md`.+ let harness = Harness::start(+ r#"schema_version = 99++[autonomy]+level = "full"+workspace_only = false+allowed_commands = ["ls", "cat", "w4-only-command"]+max_actions_per_hour = 137+require_approval_for_medium_risk = false+block_high_risk_commands = false+"#,+ true,+ )+ .await;++ let info = harness+ .call(30, "openhuman.security_policy_info", json!({}))+ .await;+ let info_outer = assert_no_error(&info, "security_policy_info");+ assert!(+ logs(info_outer)+ .iter()+ .any(|l| l.contains("computed from active config")),+ "the log line must say the payload came from live config: {info_outer}"+ );+ let info = peel(info_outer);++ assert_eq!(+ info.get("autonomy").and_then(Value::as_str),+ Some("full"),+ "the autonomy level must be the configured one, not the `supervised` \+ default: {info}"+ );+ assert_eq!(+ info.get("workspace_only").and_then(Value::as_bool),+ Some(false),+ "workspace_only defaults to true, so `false` here proves config was read: {info}"+ );+ assert_eq!(+ info.get("max_actions_per_hour").and_then(Value::as_u64),+ Some(137),+ "the rate cap must come from config: {info}"+ );+ assert_eq!(+ info.get("require_approval_for_medium_risk")+ .and_then(Value::as_bool),+ Some(false)+ );+ assert_eq!(+ info.get("block_high_risk_commands").and_then(Value::as_bool),+ Some(false)+ );++ let allowed: Vec<&str> = info+ .get("allowed_commands")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("the payload must carry `allowed_commands`: {info}"))+ .iter()+ .filter_map(Value::as_str)+ .collect();+ assert_eq!(+ allowed,+ vec!["ls", "cat", "w4-only-command"],+ "the allowlist must be the configured one, in order: {info}"+ );+}++/// A narrowed `allowed_commands` must stay narrowed.+///+/// **Currently fails.** `schema_version` is `#[serde(default)]` → `0`, so a+/// `config.toml` written by hand (or by anything that omits the field) is treated+/// as pre-v4 and the 3->4 "expand autonomy defaults" migration merges 28 commands+/// into the user's allowlist — including the filesystem-mutating `mkdir`, `touch`,+/// `cp`, `mv`, `ln`. The migration's own doc claims "deliberate removals" are+/// preserved; they are not.+///+/// Ignored rather than deleted so the intended contract stays written down.+/// See `~/tinyhuman/bugs/e2e-wave-autonomy-migration-widens-allowlist.md`.+#[ignore = "openhuman: schema_version defaults to 0, so the 3->4 autonomy \+ migration widens a hand-written allowed_commands — see \+ ~/tinyhuman/bugs/e2e-wave-autonomy-migration-widens-allowlist.md"]+#[tokio::test]+async fn security_policy_info_does_not_widen_a_narrowed_command_allowlist() {+ let _lock = support::env_lock();+ // Deliberately no `schema_version`: this is what a hand-written config looks like.+ let harness = Harness::start(+ r#"+[autonomy]+allowed_commands = ["ls", "cat"]+"#,+ true,+ )+ .await;++ let info = harness+ .call(35, "openhuman.security_policy_info", json!({}))+ .await;+ let info = peel(assert_no_error(&info, "security_policy_info narrowed allowlist"));+ let allowed: Vec<&str> = info+ .get("allowed_commands")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("the payload must carry `allowed_commands`: {info}"))+ .iter()+ .filter_map(Value::as_str)+ .collect();++ assert_eq!(+ allowed,+ vec!["ls", "cat"],+ "a config that allows exactly two commands must not gain 28 more: {allowed:?}"+ );+ for widened in ["mkdir", "touch", "cp", "mv", "ln"] {+ assert!(+ !allowed.contains(&widened),+ "`{widened}` mutates the filesystem and was never allowed by this \+ config, but the startup migration added it: {allowed:?}"+ );+ }+}++// ── keyring consent ──────────────────────────────────────────────────────────++/// All three keyring-consent controllers.+///+/// The anchor is the **persisted file**, not `activeMode`. `policy::current_status`+/// reports `os_keyring` whenever *any* backend probes as available — and the+/// `file` dev backend always does — so `activeMode` cannot witness a consent+/// decision in a test process. `ops::keyring_consent_decide` documents that the+/// in-memory cache is only updated *after* a successful persist, so proving the+/// persist landed is the assertion that actually bites. See+/// `~/tinyhuman/bugs/e2e-wave-keyring-consent-os-keyring-mislabel.md`.+#[tokio::test]+async fn keyring_consent_status_decide_and_retry_probe() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;+ let stored_state = harness.workspace().join("state").join("app-state.json");++ fn stored_consent(path: &std::path::Path) -> Value {+ let raw = std::fs::read_to_string(path)+ .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));+ let state: Value = serde_json::from_str(&raw)+ .unwrap_or_else(|e| panic!("parse {}: {e}", path.display()));+ state+ .get("keyringConsent")+ .cloned()+ .unwrap_or_else(|| panic!("no `keyringConsent` in {raw}"))+ }++ // --- keyring_consent_status --------------------------------------------+ let status = harness+ .call(40, "openhuman.keyring_consent_status", json!({}))+ .await;+ let status = peel(assert_no_error(&status, "keyring_consent_status"));+ let available = status+ .get("available")+ .and_then(Value::as_bool)+ .unwrap_or_else(|| panic!("`available` must be a boolean the UI can branch on: {status}"));+ let mode = status+ .get("activeMode")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("status must report an `activeMode`: {status}"));+ assert!(+ ["os_keyring", "local_encrypted", "consent_pending", "declined"].contains(&mode),+ "activeMode must be one of the four documented storage modes; got {mode:?}"+ );+ assert!(+ status+ .get("backendName")+ .and_then(Value::as_str)+ .is_some_and(|n| !n.is_empty()),+ "the backend must be named so the settings panel can show it: {status}"+ );+ if available {+ assert_eq!(+ mode, "os_keyring",+ "with a working backend no consent is needed, so the mode must be \+ `os_keyring` and no failure reason may be attached: {status}"+ );+ assert!(+ status.get("failureReason").is_none(),+ "`failureReason` is skipped when the keyring works: {status}"+ );+ } else {+ assert!(+ status.get("failureReason").is_some(),+ "an unavailable keyring must say why, or the settings panel has \+ nothing to explain to the user: {status}"+ );+ }++ // --- keyring_consent_decide --------------------------------------------+ let declined = harness+ .call(+ 41,+ "openhuman.keyring_consent_decide",+ json!({ "mode": "declined" }),+ )+ .await;+ let declined_outer = assert_no_error(&declined, "keyring_consent_decide declined");+ assert!(+ logs(declined_outer)+ .iter()+ .any(|l| l.contains("keyring consent recorded: declined")),+ "the log must name the decision it recorded: {declined_outer}"+ );+ let declined = peel(declined_outer);+ assert_eq!(+ declined.get("storageMode").and_then(Value::as_str),+ Some("declined"),+ "the returned preference must echo the decision: {declined}"+ );+ let stamped = declined+ .get("consentedAtMs")+ .and_then(Value::as_u64)+ .unwrap_or_else(|| panic!("the decision must be timestamped: {declined}"));+ assert!(+ stamped > 1_600_000_000_000,+ "the timestamp must be plausible epoch-ms, not 0 or a seconds value: {declined}"+ );++ // The decision reached disk. `decide` returns its preference *before* the+ // cache update, so without this the RPC could report success on a persist+ // that never happened and the choice would be silently lost on restart.+ assert!(+ stored_state.exists(),+ "keyring_consent_decide reported success but wrote no app-state.json at \+ {} — the preference exists only in memory and is lost on restart",+ stored_state.display()+ );+ let persisted = stored_consent(&stored_state);+ assert_eq!(+ persisted.get("storageMode").and_then(Value::as_str),+ Some("declined"),+ "the decision must be written to <workspace>/state/app-state.json: {persisted}"+ );+ assert_eq!(+ persisted.get("consentedAtMs").and_then(Value::as_u64),+ Some(stamped),+ "the persisted timestamp must be the same one the caller was handed, \+ not re-stamped on write: {persisted}"+ );++ // The opposite decision must overwrite it, so the assertion above is about+ // `decide` and not about a value that happened to be there already.+ let accepted = harness+ .call(+ 42,+ "openhuman.keyring_consent_decide",+ json!({ "mode": "local_encrypted" }),+ )+ .await;+ assert_eq!(+ peel(assert_no_error(&accepted, "keyring_consent_decide local_encrypted"))+ .get("storageMode")+ .and_then(Value::as_str),+ Some("local_encrypted")+ );+ assert_eq!(+ stored_consent(&stored_state)+ .get("storageMode")+ .and_then(Value::as_str),+ Some("local_encrypted"),+ "a second decision must replace the first on disk, not append or be ignored"+ );++ // --- invalid input ------------------------------------------------------+ let invalid = harness+ .call(+ 43,+ "openhuman.keyring_consent_decide",+ json!({ "mode": "os_keyring" }),+ )+ .await;+ let message = error_message(&invalid, "keyring_consent_decide invalid mode");+ assert!(+ message.contains("expected 'local_encrypted' or 'declined'"),+ "the rejection must list the modes a user may choose — `os_keyring` is \+ a *status*, not a decision: {message}"+ );+ assert_eq!(+ stored_consent(&stored_state)+ .get("storageMode")+ .and_then(Value::as_str),+ Some("local_encrypted"),+ "a rejected mode must not have been persisted before validation"+ );++ let no_mode = harness+ .call(44, "openhuman.keyring_consent_decide", json!({}))+ .await;+ assert!(+ error_message(&no_mode, "keyring_consent_decide no mode").contains("mode"),+ "a missing `mode` must name the parameter: {no_mode}"+ );++ // --- keyring_consent_retry_probe ---------------------------------------+ let probe = harness+ .call(45, "openhuman.keyring_consent_retry_probe", json!({}))+ .await;+ let probe_outer = assert_no_error(&probe, "keyring_consent_retry_probe");+ assert!(+ logs(probe_outer).iter().any(|l| l.contains("probe retried")),+ "the probe must report that it re-ran: {probe_outer}"+ );+ let probe = peel(probe_outer);+ assert!(+ probe.get("available").is_some_and(Value::is_boolean),+ "the probe returns a full status, same shape as `status`: {probe}"+ );+ assert!(+ probe+ .get("backendName")+ .and_then(Value::as_str)+ .is_some_and(|n| !n.is_empty()),+ "the probe result must name the backend it probed: {probe}"+ );+ assert!(+ probe+ .get("activeMode")+ .and_then(Value::as_str)+ .is_some_and(|m| ["os_keyring", "local_encrypted", "consent_pending", "declined"]+ .contains(&m)),+ "the probe must return a valid storage mode: {probe}"+ );+}++// ── devices ──────────────────────────────────────────────────────────────────++/// `devices_list` and `devices_revoke` over the real SQLite store, and the+/// `devices_create_pairing` failure path when no tunnel is available.+#[tokio::test]+async fn devices_list_and_revoke_over_the_real_store() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;+ let config = config_for(&harness);++ // A fresh workspace lists nothing — and answers, rather than erroring on a+ // database that does not exist yet.+ let empty = harness.call(50, "openhuman.devices_list", json!({})).await;+ let empty = peel(assert_no_error(&empty, "devices_list empty"));+ assert_eq!(+ empty+ .get("devices")+ .and_then(Value::as_array)+ .map(Vec::len),+ Some(0),+ "a workspace with no pairings must return an empty list, not an error: {empty}"+ );++ // Seed two paired devices directly — `devices_create_pairing` cannot do it+ // without a live backend tunnel.+ openhuman_core::openhuman::security::devices::store::insert_device(+ &config,+ "chan-alpha",+ "iPhone 15",+ "pubkey-alpha",+ "hash-alpha",+ )+ .expect("seed the first paired device");+ openhuman_core::openhuman::security::devices::store::insert_device(+ &config,+ "chan-beta",+ "iPad",+ "pubkey-beta",+ "hash-beta",+ )+ .expect("seed the second paired device");++ let listed = harness.call(51, "openhuman.devices_list", json!({})).await;+ let listed = peel(assert_no_error(&listed, "devices_list seeded"));+ let devices = listed+ .get("devices")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("devices_list must return a `devices` array: {listed}"));+ assert_eq!(devices.len(), 2, "both seeded devices must be listed: {listed}");++ let alpha = devices+ .iter()+ .find(|d| d.get("channel_id").and_then(Value::as_str) == Some("chan-alpha"))+ .unwrap_or_else(|| panic!("chan-alpha missing: {listed}"));+ assert_eq!(+ alpha.get("label").and_then(Value::as_str),+ Some("iPhone 15"),+ "the stored label must reach the caller: {alpha}"+ );+ assert_eq!(+ alpha.get("device_pubkey").and_then(Value::as_str),+ Some("pubkey-alpha")+ );+ assert_eq!(+ alpha.get("peer_online").and_then(Value::as_bool),+ Some(false),+ "`peer_online` is not persisted — it is overlaid from the in-memory \+ peer map, and must default to false rather than be absent: {alpha}"+ );+ assert_eq!(+ alpha.get("revoked").and_then(Value::as_bool),+ Some(false),+ "a freshly paired device is not revoked: {alpha}"+ );+ assert!(+ alpha+ .get("created_at")+ .and_then(Value::as_str)+ .is_some_and(|t| t.contains('T')),+ "created_at must be an ISO 8601 timestamp: {alpha}"+ );++ // --- devices_revoke -----------------------------------------------------+ let revoked = harness+ .call(+ 52,+ "openhuman.devices_revoke",+ json!({ "channel_id": "chan-alpha" }),+ )+ .await;+ let revoked_outer = assert_no_error(&revoked, "devices_revoke");+ assert!(+ logs(revoked_outer)+ .iter()+ .any(|l| l.contains("chan-alpha") && l.contains("revoked")),+ "the log must name the channel it revoked: {revoked_outer}"+ );+ assert_eq!(+ peel(revoked_outer).get("success").and_then(Value::as_bool),+ Some(true),+ "revoking a live pairing must report success: {revoked_outer}"+ );++ // Revocation is a soft delete that `devices_list` filters out.+ let after = harness.call(53, "openhuman.devices_list", json!({})).await;+ let after = peel(assert_no_error(&after, "devices_list after revoke"));+ let remaining = after+ .get("devices")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("devices array missing: {after}"));+ assert_eq!(+ remaining.len(),+ 1,+ "a revoked device must disappear from the list: {after}"+ );+ assert_eq!(+ remaining[0].get("channel_id").and_then(Value::as_str),+ Some("chan-beta"),+ "revoking chan-alpha must not touch chan-beta: {after}"+ );+ // The row still exists, revoked — the list filters, it does not delete.+ let row = openhuman_core::openhuman::security::devices::store::get_device(+ &config,+ "chan-alpha",+ )+ .expect("read the revoked row back");+ assert!(+ row.is_some_and(|d| d.revoked),+ "revoke is documented as a soft delete; the row must survive with \+ `revoked = 1` so the pairing history is auditable"+ );++ // Revoking something that was never paired must report `false`, not error.+ let unknown = harness+ .call(+ 54,+ "openhuman.devices_revoke",+ json!({ "channel_id": "chan-never-existed" }),+ )+ .await;+ assert_eq!(+ peel(assert_no_error(&unknown, "devices_revoke unknown"))+ .get("success")+ .and_then(Value::as_bool),+ Some(false),+ "revoking an unknown channel must report that nothing was revoked, \+ rather than claiming success: {unknown}"+ );++ // A missing channel_id is a parameter error.+ let no_id = harness.call(55, "openhuman.devices_revoke", json!({})).await;+ assert!(+ error_message(&no_id, "devices_revoke no channel_id").contains("channel_id"),+ "the error must name the missing parameter: {no_id}"+ );+}++/// Pairing needs the shared backend socket. Without it the controller must fail+/// with a reason that points at the tunnel, and must not leave a half-built+/// pairing behind in the device list.+#[tokio::test]+async fn devices_create_pairing_fails_without_a_backend_tunnel() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;++ let pairing = harness+ .call(+ 60,+ "openhuman.devices_create_pairing",+ json!({ "label": "iPhone" }),+ )+ .await;+ let message = error_message(&pairing, "devices_create_pairing with no socket");+ assert!(+ message.contains("[devices/tunnel]"),+ "the failure must be attributed to the tunnel, so the user is not sent \+ hunting through the pairing UI; got: {message}"+ );++ // Nothing may be persisted from a pairing that never completed a handshake.+ let listed = harness.call(61, "openhuman.devices_list", json!({})).await;+ assert_eq!(+ peel(assert_no_error(&listed, "devices_list after failed pairing"))+ .get("devices")+ .and_then(Value::as_array)+ .map(Vec::len),+ Some(0),+ "a failed pairing must not leave a device row behind: {listed}"+ );+}++// ── wallet ───────────────────────────────────────────────────────────────────++/// `wallet_encode_erc20_transfer` builds `transfer(address,uint256)` calldata.+/// The selector and both padded words are checked byte for byte — an encoder+/// that produced *some* hex string would pass a "not empty" test and fail this.+#[tokio::test]+async fn wallet_encode_erc20_transfer_produces_exact_calldata() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;++ let encoded = harness+ .call(+ 70,+ "openhuman.wallet_encode_erc20_transfer",+ json!({+ "chain": "evm",+ "toAddress": "0x9858EfFD232B4033E47d90003D41EC34EcaEda94",+ "amountRaw": "1000000000000000000"+ }),+ )+ .await;+ let calldata = peel(assert_no_error(&encoded, "wallet_encode_erc20_transfer"))+ .as_str()+ .unwrap_or_else(|| panic!("calldata must be a string: {encoded}"))+ .to_string();++ assert!(+ calldata.starts_with("0xa9059cbb"),+ "`transfer(address,uint256)` has selector 0xa9059cbb: {calldata}"+ );+ assert_eq!(+ calldata.len(),+ 2 + 8 + 64 + 64,+ "0x + 4-byte selector + two 32-byte words: {calldata}"+ );+ assert!(+ calldata[10..74].ends_with("9858effd232b4033e47d90003d41ec34ecaeda94"),+ "the recipient must be left-padded into the first word, lower-cased: {calldata}"+ );+ assert!(+ calldata[10..74].starts_with(&"0".repeat(24)),+ "the address word must be zero-padded to 32 bytes: {calldata}"+ );+ assert_eq!(+ &calldata[74..],+ "0000000000000000000000000000000000000000000000000de0b6b3a7640000",+ "1e18 must encode as the big-endian 32-byte amount word: {calldata}"+ );++ // Failure paths — each names what the caller got wrong, because an agent+ // reads these messages to correct itself.+ let bad_address = harness+ .call(+ 71,+ "openhuman.wallet_encode_erc20_transfer",+ json!({ "chain": "evm", "toAddress": "not-an-address", "amountRaw": "1" }),+ )+ .await;+ let message = error_message(&bad_address, "encode with a bad address");+ assert!(+ message.contains("invalid EVM recipient address") && message.contains("not-an-address"),+ "the rejection must quote the address it rejected: {message}"+ );++ let bad_amount = harness+ .call(+ 72,+ "openhuman.wallet_encode_erc20_transfer",+ json!({+ "chain": "evm",+ "toAddress": "0x9858EfFD232B4033E47d90003D41EC34EcaEda94",+ "amountRaw": "1.5"+ }),+ )+ .await;+ assert!(+ error_message(&bad_amount, "encode with a fractional amount")+ .contains("is not a valid non-negative integer"),+ "`amountRaw` is the token's smallest unit, so a decimal must be \+ rejected with the documented wording: {bad_amount}"+ );++ let wrong_chain = harness+ .call(+ 73,+ "openhuman.wallet_encode_erc20_transfer",+ json!({+ "chain": "solana",+ "toAddress": "0x9858EfFD232B4033E47d90003D41EC34EcaEda94",+ "amountRaw": "1"+ }),+ )+ .await;+ assert!(+ error_message(&wrong_chain, "encode on a non-EVM chain")+ .contains("only supports the evm chain"),+ "ERC-20 calldata on a non-EVM chain must be refused: {wrong_chain}"+ );+}++/// `wallet_reveal_recovery_phrase` decrypts the stored mnemonic. Driven through+/// the RPC surface end to end: encrypt the phrase, set the wallet up with it,+/// then reveal it back.+#[tokio::test]+async fn wallet_reveal_recovery_phrase_returns_the_stored_mnemonic() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;++ // Before setup there is nothing to reveal, and the message has to tell the+ // user what to do about it.+ let before = harness+ .call(80, "openhuman.wallet_reveal_recovery_phrase", json!({}))+ .await;+ let message = error_message(&before, "reveal before setup");+ assert!(+ message.contains("No recovery phrase is available"),+ "an unconfigured wallet must say so plainly: {message}"+ );+ assert!(+ message.contains("Set up or unlock your wallet first"),+ "the message must tell the user the next step: {message}"+ );++ const MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon \+ abandon abandon abandon abandon abandon about";+ let normalized = MNEMONIC.split_whitespace().collect::<Vec<_>>().join(" ");++ openhuman_core::openhuman::security::keyring::init_workspace(&harness.workspace());+ let encrypted = harness+ .call(+ 81,+ "openhuman.encrypt_secret",+ json!({ "plaintext": normalized }),+ )+ .await;+ let encrypted_mnemonic = peel(assert_no_error(&encrypted, "encrypt the mnemonic"))+ .as_str()+ .expect("ciphertext")+ .to_string();++ let setup = harness+ .call(+ 82,+ "openhuman.wallet_setup",+ json!({+ "consentGranted": true,+ "source": "generated",+ "mnemonicWordCount": 12,+ "encryptedMnemonic": encrypted_mnemonic,+ // All four chains: `wallet_setup` rejects a partial account set+ // ("wallet setup must include exactly one 'btc' account").+ "accounts": [+ { "chain": "evm", "address": "0x9858EfFD232B4033E47d90003D41EC34EcaEda94", "derivationPath": "m/44'/60'/0'/0/0" },+ { "chain": "btc", "address": "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu", "derivationPath": "m/84'/0'/0'/0/0" },+ { "chain": "solana", "address": "HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk", "derivationPath": "m/44'/501'/0'/0'" },+ { "chain": "tron", "address": "TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH", "derivationPath": "m/44'/195'/0'/0/0" }+ ]+ }),+ )+ .await;+ let setup = peel(assert_no_error(&setup, "wallet_setup"));+ assert_eq!(+ setup.get("configured").and_then(Value::as_bool),+ Some(true),+ "the wallet must be configured before reveal can mean anything: {setup}"+ );+ assert_eq!(+ setup.get("accounts").and_then(Value::as_array).map(Vec::len),+ Some(4),+ "all four chains must be persisted: {setup}"+ );++ let revealed = harness+ .call(83, "openhuman.wallet_reveal_recovery_phrase", json!({}))+ .await;+ let revealed_outer = assert_no_error(&revealed, "wallet_reveal_recovery_phrase");+ assert!(+ logs(revealed_outer)+ .iter()+ .any(|l| l == "recovery phrase revealed"),+ "the outcome must carry its log line: {revealed_outer}"+ );+ let revealed = peel(revealed_outer);++ assert_eq!(+ revealed.get("phrase").and_then(Value::as_str),+ Some(normalized.as_str()),+ "reveal must return the exact phrase that was stored — a wrong or \+ re-derived phrase would lose the user's funds: {revealed}"+ );+ assert_eq!(+ revealed.get("wordCount").and_then(Value::as_u64),+ Some(12),+ "the word count must be counted from the decrypted phrase, not echoed \+ from the setup parameter: {revealed}"+ );+}diff --git a/tests/raw_coverage/team_referral_e2e.rs b/tests/raw_coverage/team_referral_e2e.rsnew file mode 100644index 0000000000..50420f3b11--- /dev/null+++ b/tests/raw_coverage/team_referral_e2e.rs@@ -0,0 +1,705 @@+//! RPC-level e2e coverage for `openhuman.team_*`, `openhuman.referral_*`,+//! `openhuman.update_*` and `openhuman.migrate_openclaw`.+//!+//! Team and referral are pure proxies over the hosted API, so they are driven+//! against an in-process mock backend and asserted on the *shape of the request+//! the adapter built* as well as the response it returned. Update and migrate+//! are local, and are asserted without any network at all.+//!+//! A module of the aggregated `raw_coverage_all` target, not a target of its+//! own. Run with:+//! cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" \+//! -- team_referral_e2e++#[path = "w4_shared/mod.rs"]+mod support;++use serde_json::{json, Value};+use support::{assert_no_error, error_message, logs, mock_log, peel, Harness};++// ── team ─────────────────────────────────────────────────────────────────────++/// The nine team controllers that had no e2e target, end to end against the+/// mock backend, plus the request each one actually put on the wire.+#[tokio::test]+async fn team_uncovered_controllers_round_trip_against_the_backend() {+ let _lock = support::env_lock();+ let harness = Harness::start("", false).await;+ let log = mock_log();+ log.clear();+ harness.login().await;++ // --- team_get_usage -----------------------------------------------------+ let usage = harness.call(10, "openhuman.team_get_usage", json!({})).await;+ let usage = peel(assert_no_error(&usage, "team_get_usage"));+ assert_eq!(+ usage.get("seatsUsed").and_then(Value::as_u64),+ Some(2),+ "usage must surface the backend payload, not a placeholder: {usage}"+ );+ assert_eq!(usage.get("spendUsd").and_then(Value::as_f64), Some(12.25));++ // --- team_list_teams ----------------------------------------------------+ let teams = harness.call(11, "openhuman.team_list_teams", json!({})).await;+ let teams = peel(assert_no_error(&teams, "team_list_teams"));+ let rows = teams+ .as_array()+ .unwrap_or_else(|| panic!("team_list_teams must return an array: {teams}"));+ assert_eq!(rows.len(), 2, "seeded two teams: {teams}");+ assert_eq!(rows[0].get("name").and_then(Value::as_str), Some("Alpha"));+ assert_eq!(rows[1].get("role").and_then(Value::as_str), Some("MEMBER"));++ // --- team_get_team ------------------------------------------------------+ let team = harness+ .call(12, "openhuman.team_get_team", json!({ "teamId": "team-1" }))+ .await;+ let team = peel(assert_no_error(&team, "team_get_team"));+ assert_eq!(team.get("id").and_then(Value::as_str), Some("team-1"));+ assert_eq!(+ team.get("memberCount").and_then(Value::as_u64),+ Some(2),+ "the whole backend row must survive the proxy: {team}"+ );++ // --- team_create_team ---------------------------------------------------+ let created = harness+ .call(+ 13,+ "openhuman.team_create_team",+ json!({ "name": " Gamma " }),+ )+ .await;+ let created_outer = assert_no_error(&created, "team_create_team");+ assert!(+ logs(created_outer)+ .iter()+ .any(|l| l == "team created via backend"),+ "the outcome must carry its log line: {created_outer}"+ );+ let created = peel(created_outer);+ assert_eq!(+ created.get("name").and_then(Value::as_str),+ Some("Gamma"),+ "the adapter trims the name before sending; the mock echoes what it got: {created}"+ );++ // --- team_update_team: a blank name is dropped, not sent as "" ----------+ let renamed = harness+ .call(+ 14,+ "openhuman.team_update_team",+ json!({ "teamId": "team-1", "name": "Renamed" }),+ )+ .await;+ let renamed = peel(assert_no_error(&renamed, "team_update_team"));+ assert_eq!(+ renamed.get("name").and_then(Value::as_str),+ Some("Renamed"),+ "the new name must reach the backend body: {renamed}"+ );++ let blank_rename = harness+ .call(+ 15,+ "openhuman.team_update_team",+ json!({ "teamId": "team-1", "name": " " }),+ )+ .await;+ let blank_rename = peel(assert_no_error(&blank_rename, "team_update_team blank name"));+ assert!(+ blank_rename.get("name").is_some_and(Value::is_null),+ "a whitespace-only name is documented as dropped from the PUT body, not \+ sent as an empty string that would blank the team's name: {blank_rename}"+ );++ // --- team_switch_team ---------------------------------------------------+ let switched = harness+ .call(+ 16,+ "openhuman.team_switch_team",+ json!({ "teamId": "team-2" }),+ )+ .await;+ let switched = peel(assert_no_error(&switched, "team_switch_team"));+ assert_eq!(+ switched.get("activeTeamId").and_then(Value::as_str),+ Some("team-2"),+ "switching must name the team that became active: {switched}"+ );++ // --- team_leave_team ----------------------------------------------------+ let left = harness+ .call(17, "openhuman.team_leave_team", json!({ "teamId": "team-2" }))+ .await;+ let left = peel(assert_no_error(&left, "team_leave_team"));+ assert_eq!(left.get("left").and_then(Value::as_str), Some("team-2"));++ // --- team_join_team -----------------------------------------------------+ let joined = harness+ .call(18, "openhuman.team_join_team", json!({ "code": "JOIN-OK" }))+ .await;+ let joined = peel(assert_no_error(&joined, "team_join_team"));+ assert_eq!(joined.get("joined").and_then(Value::as_bool), Some(true));+ assert_eq!(+ joined.get("role").and_then(Value::as_str),+ Some("MEMBER"),+ "the role the backend assigned must reach the caller: {joined}"+ );++ // --- team_delete_team ---------------------------------------------------+ let deleted = harness+ .call(+ 19,+ "openhuman.team_delete_team",+ json!({ "teamId": "team-1" }),+ )+ .await;+ let deleted = peel(assert_no_error(&deleted, "team_delete_team"));+ assert_eq!(deleted.get("deleted").and_then(Value::as_str), Some("team-1"));++ // Each verb reached its documented endpoint with its documented method.+ let calls: Vec<(String, String)> = log+ .entries()+ .iter()+ .map(|e| {+ (+ e.get("method")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string(),+ e.get("path").and_then(Value::as_str).unwrap_or("").to_string(),+ )+ })+ .collect();+ for expected in [+ ("GET", "/teams/me/usage"),+ ("GET", "/teams"),+ ("GET", "/teams/team-1"),+ ("POST", "/teams"),+ ("PUT", "/teams/team-1"),+ ("POST", "/teams/team-2/switch"),+ ("POST", "/teams/team-2/leave"),+ ("POST", "/teams/join"),+ ("DELETE", "/teams/team-1"),+ ] {+ assert!(+ calls.contains(&(expected.0.to_string(), expected.1.to_string())),+ "expected a {} {} on the wire; saw {calls:?}",+ expected.0,+ expected.1+ );+ }+}++/// Backend rejections must surface, and the id validation in `team/ops.rs` must+/// fire before any request — including the path-injection guard.+#[tokio::test]+async fn team_rejects_bad_ids_and_surfaces_backend_failures() {+ let _lock = support::env_lock();+ let harness = Harness::start("", false).await;+ harness.login().await;+ let log = mock_log();++ // A team the backend does not have.+ let missing = harness+ .call(+ 20,+ "openhuman.team_get_team",+ json!({ "teamId": "missing-team" }),+ )+ .await;+ let message = error_message(&missing, "team_get_team 404");+ assert!(+ message.contains("404") && message.contains("team not found"),+ "a backend 404 must surface with its status and body, not as a generic \+ 'backend request failed'; got: {message}"+ );++ // An unknown invite code.+ let bad_code = harness+ .call(21, "openhuman.team_join_team", json!({ "code": "WRONG" }))+ .await;+ assert!(+ error_message(&bad_code, "team_join_team bad code").contains("invite code not found"),+ "the backend's reason must reach the user: {bad_code}"+ );++ // An id that would escape its path segment if it were interpolated raw.+ // `build_api_path` pushes it through `path_segments_mut`, which percent-encodes+ // the separators, so the request must arrive as ONE segment.+ log.clear();+ let injected = harness+ .call(+ 22,+ "openhuman.team_get_team",+ json!({ "teamId": "a/../admin" }),+ )+ .await;+ let injected = peel(assert_no_error(&injected, "team_get_team with a traversal id"));+ assert_eq!(+ injected.get("id").and_then(Value::as_str),+ Some("a/../admin"),+ "the id must survive encoding and decode back intact: {injected}"+ );+ let raw_path = log+ .first_with_path_prefix("/teams/")+ .and_then(|e| e.get("path").and_then(Value::as_str).map(str::to_string))+ .expect("the lookup must have reached the backend");+ assert_eq!(+ raw_path, "/teams/a%2F..%2Fadmin",+ "the separators must be percent-encoded into a single path segment — an \+ unencoded `/teams/a/../admin` is what a server would resolve to \+ `/teams/admin`, i.e. a different team: {raw_path}"+ );+ assert_eq!(+ raw_path.split('/').count(),+ 3,+ "`/` + `teams` + one id segment; anything more means the id escaped: {raw_path}"+ );++ // Local validation, before any network call.+ log.clear();+ for (id, method, params) in [+ (+ 30,+ "openhuman.team_get_team",+ json!({ "teamId": " " }),+ ),+ (+ 31,+ "openhuman.team_delete_team",+ json!({ "teamId": "" }),+ ),+ (+ 32,+ "openhuman.team_switch_team",+ json!({ "teamId": " " }),+ ),+ ] {+ let response = harness.call(id, method, params).await;+ assert!(+ error_message(&response, method).contains("teamId is required"),+ "{method} must reject a blank teamId locally: {response}"+ );+ }+ let blank_name = harness+ .call(33, "openhuman.team_create_team", json!({ "name": " " }))+ .await;+ assert!(+ error_message(&blank_name, "team_create_team blank").contains("name is required"),+ "a blank team name must be rejected locally: {blank_name}"+ );+ let blank_join = harness+ .call(34, "openhuman.team_join_team", json!({ "code": "" }))+ .await;+ assert!(+ error_message(&blank_join, "team_join_team blank").contains("code is required"),+ "a blank invite code must be rejected locally: {blank_join}"+ );++ assert!(+ log.entries().is_empty(),+ "validation is documented as pre-HTTP, yet these reached the backend: {:?}",+ log.entries()+ );+}++// ── referral ─────────────────────────────────────────────────────────────────++/// Both referral controllers, happy path and the two failure shapes.+#[tokio::test]+async fn referral_stats_and_claim_round_trip() {+ let _lock = support::env_lock();+ let harness = Harness::start("", false).await;+ let log = mock_log();+ log.clear();+ harness.login().await;++ let stats = harness+ .call(40, "openhuman.referral_get_stats", json!({}))+ .await;+ let stats_outer = assert_no_error(&stats, "referral_get_stats");+ assert!(+ logs(stats_outer)+ .iter()+ .any(|l| l.contains("GET /referral/stats")),+ "the log line names the endpoint it called: {stats_outer}"+ );+ let stats = peel(stats_outer);+ assert_eq!(stats.get("code").and_then(Value::as_str), Some("W4REF"));+ assert_eq!(+ stats.get("referredCount").and_then(Value::as_u64),+ Some(3),+ "referral counts must survive the proxy: {stats}"+ );++ // The optional device fingerprint is only sent when non-blank.+ let claimed = harness+ .call(+ 41,+ "openhuman.referral_claim",+ json!({ "code": " W4REF ", "deviceFingerprint": "fp-123" }),+ )+ .await;+ let claimed = peel(assert_no_error(&claimed, "referral_claim"));+ assert_eq!(+ claimed.get("code").and_then(Value::as_str),+ Some("W4REF"),+ "the code is trimmed before it is sent: {claimed}"+ );+ assert_eq!(claimed.get("creditsUsd").and_then(Value::as_f64), Some(5.0));++ let with_fp = log+ .first_with_path_prefix("/referral/claim")+ .expect("no claim reached the backend");+ assert_eq!(+ with_fp+ .get("body")+ .and_then(|b| b.get("deviceFingerprint"))+ .and_then(Value::as_str),+ Some("fp-123"),+ "a supplied fingerprint must be forwarded: {with_fp}"+ );++ log.clear();+ let no_fp = harness+ .call(+ 42,+ "openhuman.referral_claim",+ json!({ "code": "W4REF", "deviceFingerprint": " " }),+ )+ .await;+ assert_no_error(&no_fp, "referral_claim blank fingerprint");+ let body = log+ .first_with_path_prefix("/referral/claim")+ .expect("no claim reached the backend");+ assert!(+ body.get("body")+ .and_then(|b| b.get("deviceFingerprint"))+ .is_none(),+ "a whitespace-only fingerprint is documented as omitted from the body \+ rather than sent as an empty string: {body}"+ );++ // No local validation on the code — the backend's rejection is what the+ // caller sees. Asserted so a later change of mind here is visible.+ let blank = harness+ .call(43, "openhuman.referral_claim", json!({ "code": " " }))+ .await;+ assert!(+ error_message(&blank, "referral_claim blank code").contains("referral code is required"),+ "a blank referral code currently reaches the backend and is rejected \+ there; the message the user sees must still be actionable: {blank}"+ );+}++/// Referral, like billing, must refuse locally when no session is stored.+#[tokio::test]+async fn referral_without_a_session_refuses_locally() {+ let _lock = support::env_lock();+ let harness = Harness::start("", false).await;+ let log = mock_log();+ log.clear();++ let stats = harness+ .call(50, "openhuman.referral_get_stats", json!({}))+ .await;+ let message = error_message(&stats, "referral_get_stats with no session");+ assert!(+ message.contains("auth_store_session"),+ "the error must tell the caller how to recover; got: {message}"+ );+ assert!(+ !log.entries().iter().any(|e| e+ .get("path")+ .and_then(Value::as_str)+ .is_some_and(|p| p.starts_with("/referral"))),+ "a session-less referral call must not reach /referral: {:?}",+ log.entries()+ );+}++// ── update ───────────────────────────────────────────────────────────────────++/// `update_version` is the cheap, no-network probe the frontend gates the other+/// two on. Its three fields have to agree with each other and with the crate.+#[tokio::test]+async fn update_version_reports_the_running_binary() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;++ let version = harness.call(60, "openhuman.update_version", json!({})).await;+ let version = peel(assert_no_error(&version, "update_version"));++ let reported = version+ .get("version")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("update_version must report a version: {version}"));+ assert!(+ reported.split('.').count() >= 3 && reported.chars().next().is_some_and(|c| c.is_ascii_digit()),+ "the version must be the crate's semver, not a placeholder; got {reported:?}"+ );++ let triple = version+ .get("target_triple")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("update_version must report a target triple: {version}"));+ assert!(+ !triple.is_empty() && triple.contains('-'),+ "the target triple must look like a triple; got {triple:?}"+ );++ assert_eq!(+ version.get("asset_prefix").and_then(Value::as_str),+ Some(format!("openhuman-core-{triple}").as_str()),+ "the asset prefix is what the updater matches release assets on, so it \+ must be derived from the same triple it just reported: {version}"+ );+}++/// `update_run` is gated by `config.update.rpc_mutations_enabled`. With the gate+/// closed it must refuse *before* reaching the network, and say why.+#[tokio::test]+async fn update_run_refuses_when_rpc_mutations_are_disabled() {+ let _lock = support::env_lock();+ let harness = Harness::start(+ r#"+[update]+rpc_mutations_enabled = false+"#,+ true,+ )+ .await;++ let run = harness.call(61, "openhuman.update_run", json!({})).await;+ // The policy refusal is reported inside the payload, not as an RPC error,+ // so the frontend can render `applied`/`restart_requested` uniformly.+ let run = peel(assert_no_error(&run, "update_run"));+ let error = run+ .get("error")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("a blocked update_run must report an `error`: {run}"));+ assert!(+ error.contains("rpc_mutations_enabled=false"),+ "the refusal must name the setting that caused it: {error}"+ );+ assert!(+ error.contains("update.check"),+ "the refusal must point at the discovery path that is still allowed: {error}"+ );+ assert_eq!(+ run.get("applied").and_then(Value::as_bool),+ Some(false),+ "a blocked run must not claim it applied anything: {run}"+ );+ assert_eq!(+ run.get("restart_requested").and_then(Value::as_bool),+ Some(false),+ "a blocked run must not ask the supervisor to restart: {run}"+ );+}++/// `update_check` never fails the RPC — it folds a transport failure into an+/// `{error}` payload — so this asserts it lands in exactly one of the two+/// documented shapes, and that the success shape agrees with `update_version`.+///+/// This is the weakest case in the file, and deliberately so: `check_available`+/// hard-codes `https://api.github.com/...` with no override, so an offline or+/// rate-limited run can only take the error branch. See+/// `~/tinyhuman/bugs/e2e-wave-update-check-unmockable.md`.+#[tokio::test]+async fn update_check_lands_in_one_of_its_two_documented_shapes() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;++ let version = harness.call(70, "openhuman.update_version", json!({})).await;+ let running = peel(assert_no_error(&version, "update_version"))+ .get("version")+ .and_then(Value::as_str)+ .expect("update_version must report a version")+ .to_string();++ let check = harness.call(71, "openhuman.update_check", json!({})).await;+ let check = peel(assert_no_error(&check, "update_check"));+ assert!(+ check.is_object(),+ "update_check must always answer with an object, never a bare string or \+ null, because the frontend indexes into it: {check}"+ );++ match check.get("error").and_then(Value::as_str) {+ Some(error) => {+ assert!(+ !error.is_empty(),+ "the failure shape must carry a non-empty reason: {check}"+ );+ assert!(+ check.get("update_available").is_none(),+ "the failure shape must not also claim an update verdict: {check}"+ );+ }+ None => {+ assert_eq!(+ check.get("current_version").and_then(Value::as_str),+ Some(running.as_str()),+ "the success shape must report the same running version \+ `update_version` does: {check}"+ );+ assert!(+ check.get("update_available").is_some_and(Value::is_boolean),+ "the success shape must carry a boolean verdict: {check}"+ );+ }+ }+}++// ── migrate ──────────────────────────────────────────────────────────────────++/// `migrate_openclaw` dry-run over a seeded OpenClaw workspace, plus the two+/// refusals it owes the caller.+#[tokio::test]+async fn migrate_openclaw_dry_run_counts_sources_without_importing() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;++ // A source workspace shaped like OpenClaw's: a top-level MEMORY.md and two+ // markdown notes under memory/. An empty file must not be counted.+ let source = harness.home.join("openclaw-workspace");+ std::fs::create_dir_all(source.join("memory")).expect("create the source workspace");+ std::fs::write(source.join("MEMORY.md"), "# Top level\nremember this")+ .expect("write MEMORY.md");+ std::fs::write(source.join("memory").join("alpha.md"), "alpha note")+ .expect("write alpha.md");+ std::fs::write(source.join("memory").join("beta.md"), "beta note").expect("write beta.md");+ std::fs::write(source.join("memory").join("blank.md"), " \n").expect("write blank.md");+ std::fs::write(source.join("memory").join("ignored.txt"), "not markdown")+ .expect("write ignored.txt");++ let report = harness+ .call(+ 80,+ "openhuman.migrate_openclaw",+ json!({ "source_workspace": source.to_string_lossy(), "dry_run": true }),+ )+ .await;+ let report_outer = assert_no_error(&report, "migrate_openclaw dry run");+ assert!(+ logs(report_outer).iter().any(|l| l == "migration completed"),+ "the outcome must carry its log line: {report_outer}"+ );+ let report = peel(report_outer);++ assert_eq!(+ report.get("dry_run").and_then(Value::as_bool),+ Some(true),+ "a dry run must say so in its report: {report}"+ );+ let stats = report+ .get("stats")+ .unwrap_or_else(|| panic!("the report must carry `stats`: {report}"));+ assert_eq!(+ stats.get("from_markdown").and_then(Value::as_u64),+ Some(3),+ "MEMORY.md plus two non-empty notes; the blank note and the .txt must \+ not be counted: {stats}"+ );+ assert_eq!(+ stats.get("from_sqlite").and_then(Value::as_u64),+ Some(0),+ "there is no brain.db in this fixture: {stats}"+ );+ assert_eq!(+ stats.get("imported").and_then(Value::as_u64),+ Some(0),+ "a dry run must import nothing: {stats}"+ );+ assert_eq!(+ report.get("source_workspace").and_then(Value::as_str),+ Some(source.to_string_lossy().as_ref()),+ "the report must name the source it read: {report}"+ );++ // The dry run promised to touch nothing; check the source rather than+ // taking the flag on trust.+ assert_eq!(+ std::fs::read_to_string(source.join("MEMORY.md")).expect("read back MEMORY.md"),+ "# Top level\nremember this",+ "a dry run must leave the source workspace byte-identical"+ );++ // An absent source is an error, not an empty success.+ let missing = harness+ .call(+ 81,+ "openhuman.migrate_openclaw",+ json!({+ "source_workspace": harness.home.join("no-such-workspace").to_string_lossy(),+ "dry_run": true+ }),+ )+ .await;+ let message = error_message(&missing, "migrate_openclaw missing source");+ assert!(+ message.contains("OpenClaw workspace not found"),+ "an absent source must be named, so the user can correct the path; got: {message}"+ );++ // Migrating a workspace into itself would duplicate every entry.+ let workspace = harness.workspace();+ let self_migrate = harness+ .call(+ 82,+ "openhuman.migrate_openclaw",+ json!({ "source_workspace": workspace.to_string_lossy(), "dry_run": true }),+ )+ .await;+ assert!(+ error_message(&self_migrate, "migrate_openclaw self").contains("refusing self-migration"),+ "pointing the migration at the active workspace must be refused: {self_migrate}"+ );+}++/// A source workspace with nothing importable reports *why* it found nothing.+#[tokio::test]+async fn migrate_openclaw_reports_where_it_looked_when_it_finds_nothing() {+ let _lock = support::env_lock();+ let harness = Harness::start("", true).await;++ let source = harness.home.join("empty-openclaw");+ std::fs::create_dir_all(&source).expect("create the empty source workspace");++ let report = harness+ .call(+ 90,+ "openhuman.migrate_openclaw",+ json!({ "source_workspace": source.to_string_lossy(), "dry_run": true }),+ )+ .await;+ let report = peel(assert_no_error(&report, "migrate_openclaw empty source"));++ let warnings: Vec<&str> = report+ .get("warnings")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("the report must carry `warnings`: {report}"))+ .iter()+ .filter_map(Value::as_str)+ .collect();+ assert!(+ warnings.iter().any(|w| w.contains("No importable memory")),+ "an empty source must warn rather than silently report success: {warnings:?}"+ );+ assert!(+ warnings+ .iter()+ .any(|w| w.contains("memory/brain.db") && w.contains("MEMORY.md")),+ "the warning must list the paths it checked, so a user with data \+ elsewhere knows why it was missed: {warnings:?}"+ );+ assert_eq!(+ report+ .get("stats")+ .and_then(|s| s.get("imported"))+ .and_then(Value::as_u64),+ Some(0)+ );+}diff --git a/tests/raw_coverage/w4_shared/mod.rs b/tests/raw_coverage/w4_shared/mod.rsnew file mode 100644index 0000000000..c7b6460293--- /dev/null+++ b/tests/raw_coverage/w4_shared/mod.rs@@ -0,0 +1,750 @@+//! Shared harness for the W4 e2e targets (`billing_cost_e2e`, `team_referral_e2e`,+//! `secrets_devices_e2e`).+//!+//! Included with `#[path]` rather than living in `tests/*.rs`, so cargo does not+//! auto-discover it as a fourth test binary. Every helper mirrors the equivalent+//! in `tests/json_rpc_e2e.rs`; the mock backend below only serves the routes the+//! billing / team / referral adapters actually call.+//!+//! All three suites are modules of the single `raw_coverage_all` target, so+//! every case here runs in one process alongside ~76 other suites. Two+//! consequences shape this file:+//!+//! 1. **`env_lock` binds to `crate::SHARED_ENV_LOCK`**, not a private static. A+//! per-file lock compiles and passes in isolation while racing another+//! suite's `HOME` / `OPENHUMAN_WORKSPACE` mutation under load.+//! 2. **The RPC bearer is read, never asserted.** `core::auth::RPC_TOKEN` is a+//! process-global `OnceLock` and `init_rpc_token` is first-writer-wins, so a+//! suite that hard-codes its own token gets a 401 whenever another suite+//! initialised first. `rpc_token()` below asks for whatever is actually+//! active. See `~/tinyhuman/bugs/e2e-wave-raw-coverage-shared-rpc-token.md`.++use std::net::SocketAddr;+use std::path::{Path, PathBuf};+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++use axum::extract::{Path as AxumPath, State};+use axum::http::{header::AUTHORIZATION, HeaderMap, StatusCode};+use axum::routing::{get, patch, post};+use axum::{Json, Router};+use serde_json::{json, Value};++use openhuman_core::core::auth::{get_rpc_token, init_rpc_token};++/// The one JWT the mock backend below accepts.+pub const SESSION_JWT: &str = "w4-e2e-session-jwt";+pub const SESSION_USER_ID: &str = "w4-user";++static AUTH_INIT: OnceLock<String> = OnceLock::new();+/// The crate-wide env mutex, not a private one — see the module note above.+static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;+static KEYRING_INIT: OnceLock<()> = OnceLock::new();++/// Serializes every case that touches process-global env (`HOME`,+/// `OPENHUMAN_WORKSPACE`, the backend-URL overrides) against every other+/// aggregated suite. Poison is recovered so one panicking case cannot wedge the+/// binary.+pub fn env_lock() -> std::sync::MutexGuard<'static, ()> {+ let guard = ENV_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ // Under the lock, so this `set_var` cannot race a concurrent env read.+ KEYRING_INIT.get_or_init(|| {+ std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");+ });+ guard+}++/// The RPC bearer this process actually validates against.+///+/// Deliberately *read* rather than chosen: `RPC_TOKEN` is a process-global+/// `OnceLock` and `init_rpc_token` returns early once it is set, so in the+/// aggregated binary the first suite to initialise fixes the token for everyone.+/// Asking for the live value makes these cases correct whether they win that+/// race or lose it. `init_rpc_token` with no `OPENHUMAN_CORE_TOKEN` set mints a+/// fresh token into a per-process directory, so we add no env racer of our own.+fn rpc_token() -> &'static str {+ AUTH_INIT.get_or_init(|| {+ let token_dir = std::env::temp_dir().join(format!("openhuman-w4-e2e-{}", std::process::id()));+ std::fs::create_dir_all(&token_dir).expect("create the rpc token dir");+ init_rpc_token(&token_dir).expect("init the core rpc auth token");+ get_rpc_token()+ .expect("init_rpc_token must leave a token in place")+ .to_string()+ })+}++pub struct EnvVarGuard {+ key: &'static str,+ old: Option<String>,+}++impl EnvVarGuard {+ pub fn set_to_path(key: &'static str, path: &Path) -> Self {+ let old = std::env::var(key).ok();+ std::env::set_var(key, path.as_os_str());+ Self { key, old }+ }++ pub fn set(key: &'static str, value: &str) -> Self {+ let old = std::env::var(key).ok();+ std::env::set_var(key, value);+ Self { key, old }+ }++ pub fn unset(key: &'static str) -> Self {+ let old = std::env::var(key).ok();+ std::env::remove_var(key);+ Self { key, old }+ }+}++impl Drop for EnvVarGuard {+ fn drop(&mut self) {+ match &self.old {+ Some(v) => std::env::set_var(self.key, v),+ None => std::env::remove_var(self.key),+ }+ }+}++pub async fn serve_on_ephemeral(+ app: Router,+) -> (+ SocketAddr,+ tokio::task::JoinHandle<Result<(), std::io::Error>>,+) {+ let _ = rpc_token();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind ephemeral port");+ let addr = listener.local_addr().expect("local addr");+ let handle = tokio::spawn(async move { axum::serve(listener, app).await });+ (addr, handle)+}++pub async fn post_json_rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(120))+ .build()+ .expect("reqwest client");+ let body = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });+ let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));+ let resp = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))+ .json(&body)+ .send()+ .await+ .unwrap_or_else(|e| panic!("POST {url}: {e}"));+ assert!(+ resp.status().is_success(),+ "HTTP {} for {method}",+ resp.status()+ );+ resp.json::<Value>()+ .await+ .unwrap_or_else(|e| panic!("decoding the response to {method}: {e}"))+}++pub fn assert_no_error<'a>(v: &'a Value, context: &str) -> &'a Value {+ if let Some(err) = v.get("error") {+ panic!("{context}: JSON-RPC error: {err}");+ }+ v.get("result")+ .unwrap_or_else(|| panic!("{context}: response carried no `result`: {v}"))+}++pub fn assert_error<'a>(v: &'a Value, context: &str) -> &'a Value {+ v.get("error")+ .unwrap_or_else(|| panic!("{context}: expected a JSON-RPC error, got: {v}"))+}++/// The message text of a JSON-RPC error, for `contains` assertions.+pub fn error_message(v: &Value, context: &str) -> String {+ assert_error(v, context)+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{context}: error object had no string `message`: {v}"))+ .to_string()+}++/// Peel the `{"result": inner, "logs": [...]}` envelope `into_cli_compatible_json`+/// adds when the outcome carries logs. Handlers that log conditionally return+/// both shapes, so every content assertion goes through here.+pub fn peel(v: &Value) -> &Value {+ if v.get("logs").is_some() {+ v.get("result").unwrap_or(v)+ } else {+ v+ }+}++/// The `logs` array of an outcome envelope, or empty when the handler logged nothing.+pub fn logs(v: &Value) -> Vec<String> {+ v.get("logs")+ .and_then(Value::as_array)+ .map(|entries| {+ entries+ .iter()+ .filter_map(Value::as_str)+ .map(str::to_string)+ .collect()+ })+ .unwrap_or_default()+}++/// Write the minimal `config.toml` the RPC handlers need, plus any extra TOML+/// the caller appends (a `[dashboard.model_health]` table, `[[model_registry]]`+/// entries, an `[update]` override…).+///+/// Mirrors `tests/json_rpc_e2e.rs::write_min_config`, including the pre-login+/// `users/local` copy, and round-trips the result through `Config` so a typo in+/// a test fixture fails here rather than as a mystery default.+pub fn write_config(openhuman_dir: &Path, api_origin: &str, extra_toml: &str) {+ // `extra_toml` goes **before** `[secrets]`, not after. TOML scopes bare keys to+ // the most recent table header, so appending `schema_version = 99` after+ // `[secrets]` silently makes it `secrets.schema_version` — an unknown field+ // serde drops, leaving the real setting at its default. That failure is+ // invisible: the file looks right and the config parses.+ let cfg = format!(+ r#"api_url = "{api_origin}"+default_model = "w4-e2e-mock-model"+default_temperature = 0.7+chat_onboarding_completed = true+{extra_toml}+[secrets]+encrypt = false+"#+ );++ // Guard for exactly that class: every top-level key the caller declared must+ // still be top-level after assembly. A reparented key fails here, naming+ // itself, instead of surfacing as "the RPC handler ignored my config".+ let declared: toml::Value =+ toml::from_str(extra_toml).expect("the extra TOML fixture must parse on its own");+ let merged: toml::Value =+ toml::from_str(&cfg).expect("the assembled config.toml must parse");+ if let (Some(declared), Some(merged)) = (declared.as_table(), merged.as_table()) {+ for key in declared.keys() {+ assert!(+ merged.contains_key(key),+ "`{key}` was declared at the top level of the fixture but is not \+ top-level in the assembled config.toml — it has been reparented \+ into a preceding table and will be silently ignored.\n{cfg}"+ );+ }+ }++ fn write_one(dir: &Path, cfg: &str) {+ std::fs::create_dir_all(dir).expect("create config dir");+ std::fs::write(dir.join("config.toml"), cfg).expect("write config.toml");+ }++ write_one(openhuman_dir, &cfg);+ if openhuman_dir+ .file_name()+ .is_some_and(|name| name == std::ffi::OsStr::new(".openhuman"))+ {+ write_one(&openhuman_dir.join("users").join("local"), &cfg);+ }++ let _: openhuman_core::openhuman::config::Config =+ toml::from_str(&cfg).expect("the fixture config.toml must match the Config schema");+}++/// A fully wired sandbox: temp `HOME`, a mock backend, and a live JSON-RPC server.+pub struct Harness {+ pub home: PathBuf,+ pub openhuman_dir: PathBuf,+ pub rpc_base: String,+ pub mock_origin: String,+ _tmp: tempfile::TempDir,+ _guards: Vec<EnvVarGuard>,+ mock_join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+ rpc_join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+}++impl Harness {+ /// `workspace_override`: when `Some`, exported as `OPENHUMAN_WORKSPACE`, which+ /// pins both `config.workspace_dir` and the config dir deterministically. Pass+ /// `None` for the session-backed cases, which need the `users/<id>` resolution+ /// path `auth_store_session` sets up.+ pub async fn start(extra_toml: &str, workspace_override: bool) -> Self {+ let tmp = tempfile::tempdir().expect("tempdir");+ let home = tmp.path().to_path_buf();+ let openhuman_dir = home.join(".openhuman");++ let mut guards = vec![+ EnvVarGuard::set_to_path("HOME", &home),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ ];++ let (mock_addr, mock_join) = serve_on_ephemeral(mock_backend_router()).await;+ let mock_origin = format!("http://{mock_addr}");+ write_config(&openhuman_dir, &mock_origin, extra_toml);++ // The user-scoped config `auth_store_session` will resolve to once a+ // session is stored. Written unconditionally so a case can log in later.+ write_config(+ &openhuman_dir.join("users").join(SESSION_USER_ID),+ &mock_origin,+ extra_toml,+ );++ if workspace_override {+ // `<home>/workspace`, deliberately a **sibling** of `.openhuman`.+ // `resolve_config_dir_for_workspace` looks for the config dir at+ // `workspace.parent()/.openhuman`, so a workspace *inside* `.openhuman`+ // resolves to `<home>/.openhuman/.openhuman` — which does not exist, and+ // the whole `config.toml` is then silently replaced by schema defaults+ // while `workspace_dir` still looks correct. That failure is invisible+ // except as "my `[cost]` block did nothing".+ let workspace = home.join("workspace");+ std::fs::create_dir_all(&workspace).expect("create workspace dir");+ guards.push(EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace));+ } else {+ guards.push(EnvVarGuard::unset("OPENHUMAN_WORKSPACE"));+ }++ let (rpc_addr, rpc_join) =+ serve_on_ephemeral(openhuman_core::core::jsonrpc::build_core_http_router(false)).await;+ tokio::time::sleep(Duration::from_millis(100)).await;++ Self {+ home,+ openhuman_dir,+ rpc_base: format!("http://{rpc_addr}"),+ mock_origin,+ _tmp: tmp,+ _guards: guards,+ mock_join,+ rpc_join,+ }+ }++ /// The workspace `OPENHUMAN_WORKSPACE` pins. Only meaningful when the harness+ /// was started with `workspace_override = true`.+ pub fn workspace(&self) -> PathBuf {+ self.home.join("workspace")+ }++ pub async fn call(&self, id: i64, method: &str, params: Value) -> Value {+ post_json_rpc(&self.rpc_base, id, method, params).await+ }++ /// Store `SESSION_JWT` so the hosted adapters have something to send.+ pub async fn login(&self) {+ let stored = self+ .call(+ 1,+ "openhuman.auth_store_session",+ json!({ "token": SESSION_JWT, "user_id": SESSION_USER_ID }),+ )+ .await;+ assert_no_error(&stored, "auth_store_session");+ }+}++impl Drop for Harness {+ fn drop(&mut self) {+ self.mock_join.abort();+ self.rpc_join.abort();+ }+}++// ── Mock hosted backend ──────────────────────────────────────────────────────++fn err_json(status: StatusCode, message: &str) -> (StatusCode, Json<Value>) {+ (+ status,+ Json(json!({ "success": false, "error": message, "message": message })),+ )+}++fn require_session(headers: &HeaderMap) -> Result<(), (StatusCode, Json<Value>)> {+ match headers+ .get(AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .map(str::trim)+ {+ Some(value) if value == format!("Bearer {SESSION_JWT}") => Ok(()),+ Some(_) => Err(err_json(StatusCode::UNAUTHORIZED, "invalid session token")),+ None => Err(err_json(StatusCode::UNAUTHORIZED, "missing Authorization")),+ }+}++/// Records every request the core made, so a test can assert the adapter built+/// the path and body it claims to (query string included).+#[derive(Clone, Default)]+pub struct MockLog(pub std::sync::Arc<Mutex<Vec<Value>>>);++static MOCK_LOG: OnceLock<MockLog> = OnceLock::new();++pub fn mock_log() -> MockLog {+ MOCK_LOG.get_or_init(MockLog::default).clone()+}++impl MockLog {+ fn record(&self, method: &str, path: &str, body: Option<&Value>) {+ let mut guard = match self.0.lock() {+ Ok(g) => g,+ Err(p) => p.into_inner(),+ };+ guard.push(json!({ "method": method, "path": path, "body": body }));+ }++ pub fn clear(&self) {+ match self.0.lock() {+ Ok(mut g) => g.clear(),+ Err(p) => p.into_inner().clear(),+ }+ }++ pub fn entries(&self) -> Vec<Value> {+ match self.0.lock() {+ Ok(g) => g.clone(),+ Err(p) => p.into_inner().clone(),+ }+ }++ /// The recorded entry for the first request whose path starts with `prefix`.+ pub fn first_with_path_prefix(&self, prefix: &str) -> Option<Value> {+ self.entries().into_iter().find(|entry| {+ entry+ .get("path")+ .and_then(Value::as_str)+ .is_some_and(|p| p.starts_with(prefix))+ })+ }+}++async fn current_user(headers: HeaderMap) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ Ok(Json(json!({+ "success": true,+ "data": { "_id": SESSION_USER_ID, "username": "w4" }+ })))+}++macro_rules! logged_get {+ ($name:ident, $path:expr, $body:expr) => {+ async fn $name(+ State(log): State<MockLog>,+ headers: HeaderMap,+ ) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record("GET", $path, None);+ Ok(Json(json!({ "success": true, "data": $body })))+ }+ };+}++logged_get!(+ credits_balance,+ "/payments/credits/balance",+ json!({ "balanceUsd": 42.5, "currency": "USD", "creditsCents": 4250 })+);+logged_get!(+ credits_auto_recharge,+ "/payments/credits/auto-recharge",+ json!({ "enabled": true, "thresholdUsd": 5.0, "rechargeAmountUsd": 25.0, "paymentMethodId": "pm_default" })+);+logged_get!(+ credits_cards,+ "/payments/credits/auto-recharge/cards",+ json!([+ { "id": "pm_1", "brand": "visa", "last4": "4242", "isDefault": true },+ { "id": "pm_2", "brand": "mastercard", "last4": "5555", "isDefault": false }+ ])+);+logged_get!(+ coupons_me,+ "/coupons/me",+ json!([{ "code": "WELCOME10", "creditsUsd": 10.0, "redeemedAt": "2026-01-02T03:04:05Z" }])+);+logged_get!(+ referral_stats,+ "/referral/stats",+ json!({ "code": "W4REF", "referredCount": 3, "creditsEarnedUsd": 15.0 })+);+logged_get!(+ teams_usage,+ "/teams/me/usage",+ json!({ "teamId": "team-1", "seatsUsed": 2, "seatsTotal": 5, "spendUsd": 12.25 })+);+logged_get!(+ teams_list,+ "/teams",+ json!([+ { "id": "team-1", "name": "Alpha", "role": "OWNER" },+ { "id": "team-2", "name": "Beta", "role": "MEMBER" }+ ])+);++async fn credits_transactions(+ State(log): State<MockLog>,+ headers: HeaderMap,+ uri: axum::http::Uri,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ // Path *and* query — the limit/offset defaults are part of the contract this+ // records, and a test asserts on the exact query string.+ log.record("GET", &uri.to_string(), None);+ Ok(Json(json!({+ "success": true,+ "data": {+ "transactions": [+ { "id": "txn-1", "amountUsd": -1.25, "kind": "usage" },+ { "id": "txn-2", "amountUsd": 20.0, "kind": "top_up" }+ ],+ "total": 2+ }+ })))+}++async fn credits_setup_intent(+ State(log): State<MockLog>,+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record("POST", "/payments/credits/auto-recharge/cards/setup-intent", None);+ Ok(Json(json!({+ "success": true,+ "data": { "clientSecret": "seti_w4_secret", "setupIntentId": "seti_w4" }+ })))+}++async fn credits_update_auto_recharge(+ State(log): State<MockLog>,+ headers: HeaderMap,+ Json(body): Json<Value>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record("PATCH", "/payments/credits/auto-recharge", Some(&body));+ // Echo the request so the test can prove the adapter forwarded the payload+ // verbatim rather than reshaping it.+ let mut echoed = body.clone();+ if let Some(obj) = echoed.as_object_mut() {+ obj.insert("updated".to_string(), json!(true));+ }+ Ok(Json(json!({ "success": true, "data": echoed })))+}++async fn card_update(+ State(log): State<MockLog>,+ AxumPath(payment_method_id): AxumPath<String>,+ headers: HeaderMap,+ Json(body): Json<Value>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record(+ "PATCH",+ &format!("/payments/credits/auto-recharge/cards/{payment_method_id}"),+ Some(&body),+ );+ Ok(Json(json!({+ "success": true,+ // `paymentMethodId` is echoed *decoded*, which is what proves the+ // adapter's percent-encoding survived a round trip through the path.+ "data": { "paymentMethodId": payment_method_id, "isDefault": body.get("isDefault") }+ })))+}++async fn card_delete(+ State(log): State<MockLog>,+ AxumPath(payment_method_id): AxumPath<String>,+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record(+ "DELETE",+ &format!("/payments/credits/auto-recharge/cards/{payment_method_id}"),+ None,+ );+ Ok(Json(json!({+ "success": true,+ "data": { "deleted": payment_method_id, "remaining": 1 }+ })))+}++async fn coupons_redeem(+ State(log): State<MockLog>,+ headers: HeaderMap,+ Json(body): Json<Value>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record("POST", "/coupons/redeem", Some(&body));+ let code = body.get("code").and_then(Value::as_str).unwrap_or_default();+ if code != "WELCOME10" {+ return Err(err_json(+ StatusCode::BAD_REQUEST,+ &format!("coupon '{code}' is not redeemable"),+ ));+ }+ Ok(Json(json!({+ "success": true,+ "data": { "code": code, "creditsUsd": 10.0, "newBalanceUsd": 52.5 }+ })))+}++async fn referral_claim(+ State(log): State<MockLog>,+ headers: HeaderMap,+ Json(body): Json<Value>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record("POST", "/referral/claim", Some(&body));+ let code = body.get("code").and_then(Value::as_str).unwrap_or_default();+ if code.is_empty() {+ return Err(err_json(StatusCode::BAD_REQUEST, "referral code is required"));+ }+ Ok(Json(json!({+ "success": true,+ "data": { "claimed": true, "code": code, "creditsUsd": 5.0 }+ })))+}++// ── Teams ────────────────────────────────────────────────────────────────────++fn team_row(id: &str) -> Value {+ json!({ "id": id, "name": format!("Team {id}"), "role": "OWNER", "memberCount": 2 })+}++async fn team_get(+ State(log): State<MockLog>,+ AxumPath(team_id): AxumPath<String>,+ headers: HeaderMap,+ uri: axum::http::Uri,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ // The **raw** path, not the decoded id: the path-injection case turns on+ // what actually went over the wire, and a decoded id would hide it.+ log.record("GET", uri.path(), None);+ if team_id == "missing-team" {+ return Err(err_json(StatusCode::NOT_FOUND, "team not found"));+ }+ Ok(Json(json!({ "success": true, "data": team_row(&team_id) })))+}++async fn team_create(+ State(log): State<MockLog>,+ headers: HeaderMap,+ Json(body): Json<Value>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record("POST", "/teams", Some(&body));+ let name = body.get("name").and_then(Value::as_str).unwrap_or_default();+ Ok(Json(json!({+ "success": true,+ "data": { "id": "team-new", "name": name, "role": "OWNER", "memberCount": 1 }+ })))+}++async fn team_update(+ State(log): State<MockLog>,+ AxumPath(team_id): AxumPath<String>,+ headers: HeaderMap,+ Json(body): Json<Value>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record("PUT", &format!("/teams/{team_id}"), Some(&body));+ Ok(Json(json!({+ "success": true,+ // `name` is echoed straight from the body — absent when the adapter+ // dropped a blank name, which is exactly what one case asserts.+ "data": { "id": team_id, "name": body.get("name"), "updated": true }+ })))+}++async fn team_delete(+ State(log): State<MockLog>,+ AxumPath(team_id): AxumPath<String>,+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record("DELETE", &format!("/teams/{team_id}"), None);+ Ok(Json(json!({ "success": true, "data": { "deleted": team_id } })))+}++async fn team_switch(+ State(log): State<MockLog>,+ AxumPath(team_id): AxumPath<String>,+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record("POST", &format!("/teams/{team_id}/switch"), None);+ Ok(Json(json!({+ "success": true,+ "data": { "activeTeamId": team_id, "switched": true }+ })))+}++async fn team_leave(+ State(log): State<MockLog>,+ AxumPath(team_id): AxumPath<String>,+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record("POST", &format!("/teams/{team_id}/leave"), None);+ Ok(Json(json!({ "success": true, "data": { "left": team_id } })))+}++async fn team_join(+ State(log): State<MockLog>,+ headers: HeaderMap,+ Json(body): Json<Value>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ log.record("POST", "/teams/join", Some(&body));+ let code = body.get("code").and_then(Value::as_str).unwrap_or_default();+ if code != "JOIN-OK" {+ return Err(err_json(StatusCode::NOT_FOUND, "invite code not found"));+ }+ Ok(Json(json!({+ "success": true,+ "data": { "joined": true, "teamId": "team-1", "role": "MEMBER" }+ })))+}++pub fn mock_backend_router() -> Router {+ let log = mock_log();+ Router::new()+ .route("/settings", get(current_user))+ .route("/auth/me", get(current_user))+ // billing+ .route("/payments/credits/balance", get(credits_balance))+ .route("/payments/credits/transactions", get(credits_transactions))+ .route(+ "/payments/credits/auto-recharge",+ get(credits_auto_recharge).patch(credits_update_auto_recharge),+ )+ .route("/payments/credits/auto-recharge/cards", get(credits_cards))+ .route(+ "/payments/credits/auto-recharge/cards/setup-intent",+ post(credits_setup_intent),+ )+ .route(+ "/payments/credits/auto-recharge/cards/{payment_method_id}",+ patch(card_update).delete(card_delete),+ )+ .route("/coupons/redeem", post(coupons_redeem))+ .route("/coupons/me", get(coupons_me))+ // referral+ .route("/referral/stats", get(referral_stats))+ .route("/referral/claim", post(referral_claim))+ // teams+ .route("/teams", get(teams_list).post(team_create))+ .route("/teams/me/usage", get(teams_usage))+ .route("/teams/join", post(team_join))+ .route(+ "/teams/{team_id}",+ get(team_get).put(team_update).delete(team_delete),+ )+ .route("/teams/{team_id}/switch", post(team_switch))+ .route("/teams/{team_id}/leave", post(team_leave))+ .with_state(log)+}