GitCorner

Code

ossartcraftcraftanything🌐
642d5a256791
//! End-to-end tests of the built binary (run through the process runner).

use craft_anything_platform::process::{Output, Process};
use serde_json::{Value, json};
use std::time::Duration;

fn cli(args: &[&str], config: &std::path::Path) -> Output {
    Process::new(env!("CARGO_BIN_EXE_craft-anything-cli")).args(args).env("CRAFT_ANYTHING_CONFIG_DIR", config).timeout(Duration::from_secs(60)).run().unwrap()
}

/// The CLI lists installation-specific depths and refuses unsupported selections using an isolated agent fixture.
#[cfg(unix)]
#[test]
fn opencode_cli_lists_supported_depths_and_rejects_unsupported_choices() {
    use std::os::unix::fs::PermissionsExt;
    let cfg = tempfile::tempdir().unwrap();
    let program = cfg.path().join("agent");
    let response = json!({"data":[{"id":"model","providerID":"test","name":"Test model","enabled":true,"type":"chat","variants":[{"id":"low"},{"id":"max"}]}]});
    std::fs::write(&program, format!("#!/bin/sh\ncat <<'MODELS'\n{response}\nMODELS\n")).unwrap();
    std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o700)).unwrap();
    assert!(cli(&["ai", "add", "OpenCode", "--kind", "agent_cli", "--model", "opencode"], cfg.path()).success);
    assert!(cli(&["ai", "program", "OpenCode", program.to_str().unwrap()], cfg.path()).success);
    let listing = cli(&["ai", "model", "OpenCode", "--format", "json"], cfg.path());
    let list: Value = serde_json::from_slice(&listing.stdout).unwrap();
    assert_eq!(list["models"][0]["thinking"], json!(["low", "max"]));
    assert!(cli(&["ai", "model", "OpenCode", "test/model", "--thinking", "max"], cfg.path()).success);
    assert!(!cli(&["ai", "model", "OpenCode", "--thinking", "xhigh"], cfg.path()).success);
    let saved = std::fs::read_to_string(cfg.path().join("config.toml")).unwrap();
    assert!(saved.contains("cli_thinking = \"max\""), "invalid choices must not replace the saved choice");
    assert!(cli(&["ai", "model", "OpenCode", "--default"], cfg.path()).success);
    let saved = std::fs::read_to_string(cfg.path().join("config.toml")).unwrap();
    assert!(!saved.contains("cli_model") && !saved.contains("cli_thinking"));
    assert_eq!(cli(&["ai", "model", "OpenCode", "test/model", "--default"], cfg.path()).code, Some(2));
}

/// `ai model <Claude Code> --default` clears an explicit model through the same path as the
/// positional `default`, with no model-discovery run (Claude Code has no catalogue).
#[test]
fn claude_code_default_clears_the_model_without_discovery() {
    let cfg = tempfile::tempdir().unwrap();
    for (name, agent) in [("Claude Code", "claude-code"), ("Claude", "claude")] {
        assert!(cli(&["ai", "add", name, "--kind", "agent_cli", "--model", agent], cfg.path()).success);
        assert!(cli(&["ai", "model", name, "my-custom-model"], cfg.path()).success);
        let saved = std::fs::read_to_string(cfg.path().join("config.toml")).unwrap();
        assert!(saved.contains("my-custom-model"), "{saved}");
        assert!(cli(&["ai", "model", name, "--default"], cfg.path()).success);
        let saved = std::fs::read_to_string(cfg.path().join("config.toml")).unwrap();
        assert!(!saved.contains("cli_model"), "{saved}");
    }
}

#[test]
fn commands_and_exit_codes() {
    let cfg = tempfile::tempdir().unwrap();
    let out = cli(&["commands", "--format", "json"], cfg.path());
    assert!(out.success);
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert!(v.as_array().unwrap().iter().any(|c| c["command"] == "core-session-show"));
    assert_eq!(cli(&["no-such-tool"], cfg.path()).code, Some(2));
    assert_eq!(cli(&["--bogus-flag"], cfg.path()).code, Some(2));
    let fail = cli(&["core-finding-record", "--statement", "x", "--evidence-ids", "ev_nope"], cfg.path());
    assert_eq!(fail.code, Some(1));
    let e: Value = serde_json::from_slice(&fail.stdout).unwrap();
    assert_eq!(e["error"]["code"], "bad_input");
}

#[test]
fn ai_request_rate_reads_changes_and_clears_an_api_backends_limit() {
    let config = tempfile::tempdir().unwrap();
    let run = |args: &[&str]| cli(args, config.path());
    assert!(run(&["ai", "add", "Local", "--kind", "openai_compatible", "--model", "test"]).success);
    assert!(run(&["ai", "add", "Claude Code", "--kind", "agent_cli", "--model", "claude-code"]).success);
    let read_rate = || {
        let output = run(&["ai", "request-rate", "Local", "--format", "json"]);
        assert!(output.success);
        serde_json::from_slice::<Value>(&output.stdout).unwrap()["requests_per_minute"].clone()
    };
    assert_eq!(read_rate(), Value::Null);
    assert!(run(&["ai", "request-rate", "Local", "120"]).success);
    assert_eq!(read_rate(), 120);
    assert!(!run(&["ai", "request-rate", "Local", "4294967296"]).success);
    assert!(!run(&["ai", "request-rate", "Claude Code", "120"]).success);
    assert!(!run(&["ai", "request-rate", "Unknown", "120"]).success);
    assert_eq!(read_rate(), 120);
    assert!(run(&["ai", "request-rate", "Local", "0"]).success);
    assert_eq!(read_rate(), Value::Null);
    assert!(!std::fs::read_to_string(config.path().join("config.toml")).unwrap().contains("requests_per_minute"));
}

/// R5.4: an API backend's tool list is shown beside what Auto works out to there, changed, and
/// cleared back to Auto; agent apps and unknown lists are refused.
#[test]
fn ai_tools_reads_changes_and_clears_an_api_backends_tool_list() {
    let config = tempfile::tempdir().unwrap();
    let run = |args: &[&str]| cli(args, config.path());
    assert!(run(&["ai", "add", "Local", "--kind", "openai_compatible", "--model", "test"]).success);
    assert!(run(&["ai", "add", "Paid", "--kind", "anthropic", "--model", "test"]).success);
    assert!(run(&["ai", "add", "Claude Code", "--kind", "agent_cli", "--model", "claude-code"]).success);
    let read = |name: &str| {
        let output = run(&["ai", "tools", name, "--format", "json"]);
        assert!(output.success, "{}", String::from_utf8_lossy(&output.stdout));
        serde_json::from_slice::<Value>(&output.stdout).unwrap()
    };
    let local = read("Local");
    assert_eq!(local["tools"], "auto");
    assert!(local["auto"].as_str().unwrap().contains("64k"), "a local model's Auto depends on its window: {local}");
    assert_eq!(read("Paid")["auto"], "full", "a paid service always gets every tool");
    assert!(run(&["ai", "tools", "Local", "full"]).success);
    assert_eq!(read("Local")["tools"], "full");
    assert!(std::fs::read_to_string(config.path().join("config.toml")).unwrap().contains("tools = \"full\""));
    assert!(!run(&["ai", "tools", "Local", "some"]).success);
    assert!(!run(&["ai", "tools", "Claude Code", "lean"]).success);
    assert!(!run(&["ai", "tools", "Unknown", "lean"]).success);
    assert_eq!(read("Local")["tools"], "full");
    assert!(run(&["ai", "tools", "Local", "auto"]).success);
    assert_eq!(read("Local")["tools"], "auto");
    assert!(!std::fs::read_to_string(config.path().join("config.toml")).unwrap().contains("tools ="), "Auto is saved as no setting");
}

/// #1358: the saved key can be reported, replaced and forgotten headlessly, and is never printed.
#[test]
fn ai_key_reports_replaces_and_forgets_without_printing_the_key() {
    let cfg = tempfile::tempdir().unwrap();
    let run = |args: &[&str], input: &str| {
        Process::new(env!("CARGO_BIN_EXE_craft-anything-cli"))
            .args(args)
            .env("CRAFT_ANYTHING_CONFIG_DIR", cfg.path())
            .env("CRAFT_ANYTHING_NO_KEYCHAIN", "1")
            .stdin_bytes(input.as_bytes().to_vec())
            .timeout(Duration::from_secs(60))
            .run()
            .unwrap()
    };

    assert!(run(&["ai", "add", "OpenAI", "--kind", "openai", "--model", "gpt-test", "--key-stdin"], "sk-old").success);
    let status = run(&["ai", "key", "OpenAI", "--format", "json"], "");
    let v: Value = serde_json::from_slice(&status.stdout).unwrap();
    assert_eq!(v["key_saved"], true, "{v}");
    assert!(!String::from_utf8_lossy(&status.stdout).contains("sk-old"));

    let replaced = run(&["ai", "key", "OpenAI", "--key-stdin", "--format", "json"], "sk-new");
    let v: Value = serde_json::from_slice(&replaced.stdout).unwrap();
    assert_eq!((v["key_saved"].as_bool(), v["changed"].as_str()), (Some(true), Some("replaced")), "{v}");
    assert!(!String::from_utf8_lossy(&replaced.stdout).contains("sk-old") && !String::from_utf8_lossy(&replaced.stdout).contains("sk-new"));

    let forgotten = run(&["ai", "key", "OpenAI", "--forget", "--format", "json"], "");
    let v: Value = serde_json::from_slice(&forgotten.stdout).unwrap();
    assert_eq!((v["key_saved"].as_bool(), v["changed"].as_str()), (Some(false), Some("forgotten")), "{v}");
    let status = run(&["ai", "key", "OpenAI", "--format", "json"], "");
    let v: Value = serde_json::from_slice(&status.stdout).unwrap();
    assert_eq!(v["key_saved"], false, "{v}");

    let from_env = Process::new(env!("CARGO_BIN_EXE_craft-anything-cli"))
        .args(["ai", "key", "OpenAI", "--key-env", "CRAFT_TEST_KEY", "--format", "json"])
        .env("CRAFT_ANYTHING_CONFIG_DIR", cfg.path())
        .env("CRAFT_ANYTHING_NO_KEYCHAIN", "1")
        .env("CRAFT_TEST_KEY", "sk-env")
        .timeout(Duration::from_secs(60))
        .run()
        .unwrap();
    let v: Value = serde_json::from_slice(&from_env.stdout).unwrap();
    assert_eq!((v["key_saved"].as_bool(), v["changed"].as_str()), (Some(true), Some("replaced")), "{v}");
    assert_eq!(run(&["ai", "key", "No such backend"], "").code, Some(1));
}

/// #249: in Clean room a target tool the mode refuses was listed as available, because nothing
/// being open yet was waived for every target tool.
#[test]
fn capabilities_keep_the_clean_room_refusal() {
    let cfg = tempfile::tempdir().unwrap();
    let tool = |args: &[&str], id: &str| {
        let out = cli(args, cfg.path());
        let v: Value = serde_json::from_slice(&out.stdout).unwrap();
        let tools = v["toolsets"].as_array().unwrap().iter().flat_map(|t| t["tools"].as_array().unwrap().clone());
        tools.into_iter().find(|t| t["tool"] == id).unwrap_or_else(|| panic!("{id} not in {v}"))
    };
    let clean = tool(&["--format", "json", "capabilities"], "native_function_pseudocode");
    assert_eq!((clean["available"].as_bool(), clean["needs_target"].as_bool()), (Some(false), Some(true)), "{clean}");
    assert!(clean["reason"].as_str().is_some_and(|r| !r.is_empty()), "{clean}");
    let deep = tool(&["--deep", "--format", "json", "capabilities"], "native_function_pseudocode");
    assert_eq!((deep["available"].as_bool(), deep["reason"].is_null()), (Some(true), true), "{deep}");
}

/// After the tool name, `--project` is the tool's own option when it has one (it used to be taken
/// as the global investigation folder, which was then created there).
#[test]
fn a_tools_own_project_option_reaches_the_tool() {
    let cfg = tempfile::tempdir().unwrap();
    let folder = tempfile::tempdir().unwrap();
    let out = cli(&["project-show", "--project", folder.path().to_str().unwrap()], cfg.path());
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    // project_show read the folder (it isn't a project, so it says so) instead of missing its option.
    let msg = v["error"]["message"].as_str().unwrap_or_default();
    assert!(!msg.contains("missing field") && !msg.contains("`project`"), "{v}");
    assert_eq!(std::fs::read_dir(folder.path()).unwrap().count(), 0, "no investigation was created in the folder");
}

/// A builder that runs our CLI from its shell is an agent to the tools, so it can't allow itself to
/// push; the person, running the same command, can.
#[test]
fn the_cli_inside_an_agent_cant_loosen_a_projects_approvals() {
    use craft_anything_engine::workspace::{ActionKind, Approval, TargetRef, Workspace};
    let cfg = tempfile::tempdir().unwrap();
    let dir = tempfile::tempdir().unwrap();
    let ws = Workspace::create(dir.path(), "Notes", "A notes app", TargetRef::None).unwrap();
    let project = ws.root.to_str().unwrap().to_string();
    let args = ["project-approvals-set", "--project", project.as_str(), "--kind", "publish", "--mode", "allow"];
    let run = |agent: bool| {
        let p = Process::new(env!("CARGO_BIN_EXE_craft-anything-cli")).args(args).env("CRAFT_ANYTHING_CONFIG_DIR", cfg.path());
        let p = if agent { p.env(craft_anything_engine::AGENT_ENV, "1") } else { p };
        p.timeout(Duration::from_secs(60)).run().unwrap()
    };
    let saved = || Workspace::open(&ws.root).unwrap().manifest.approvals.get(&ActionKind::Publish).copied();
    let refused = run(true);
    assert!(!refused.success, "{}", refused.stdout_text());
    assert!(refused.stdout_text().contains("can't loosen"), "{}", refused.stdout_text());
    assert_eq!(saved(), None, "nothing changed");
    let allowed = run(false);
    assert!(allowed.success, "{}{}", allowed.stdout_text(), allowed.stderr_text());
    assert_eq!(saved(), Some(Approval::Allow));
}

#[test]
fn target_tools_open_then_close_and_project_journal() {
    let cfg = tempfile::tempdir().unwrap();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("sample.bin");
    std::fs::write(&file, b"\x7fELF not really").unwrap();
    let proj = dir.path().join("p.cany");
    let out = cli(&["--deep", "native-cursor-show", file.to_str().unwrap(), "--format", "json", "--project", proj.to_str().unwrap()], cfg.path());
    assert!(out.success, "{}", out.stdout_text());
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(v["result"]["document"], "sample.bin");
    let days: Vec<_> = std::fs::read_dir(proj.join("journal")).unwrap().collect();
    assert_eq!(days.len(), 1);
}

#[test]
fn clean_room_refuses_to_look_inside_and_says_how_to_turn_on_deep_mode() {
    let cfg = tempfile::tempdir().unwrap();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("sample.bin");
    std::fs::write(&file, b"\x7fELF not really").unwrap();
    let out = cli(&["core-target-open", file.to_str().unwrap()], cfg.path());
    assert_eq!(out.code, Some(1), "{}", out.stdout_text());
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(v["error"]["details"]["reason"], "clean_room", "{v}");
    assert!(v["error"]["remediation"].as_str().unwrap_or_default().contains("--deep"), "{v}");
    // --deep is for this run only: nothing is saved.
    assert!(cli(&["--deep", "core-target-open", file.to_str().unwrap()], cfg.path()).success);
    assert!(!cfg.path().join("config.toml").exists(), "the run's mode isn't saved");
    assert_eq!(cli(&["--deep", "--clean-room", "core-session-show"], cfg.path()).code, Some(2));
    assert_eq!(cli(&["core-session-show", "--deep", "--clean-room"], cfg.path()).code, Some(2));
}

#[test]
fn mcp_over_stdio() {
    let cfg = tempfile::tempdir().unwrap();
    let input = [
        json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "t", "version": "0"}}}),
        json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
        json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
        json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "core_session_show", "arguments": {}}}),
    ]
    .iter()
    .map(|v| format!("{v}\n"))
    .collect::<String>();
    let out = Process::new(env!("CARGO_BIN_EXE_craft-anything-cli"))
        .arg("mcp")
        .env("CRAFT_ANYTHING_CONFIG_DIR", cfg.path())
        .stdin_bytes(input)
        .timeout(Duration::from_secs(30))
        .run()
        .unwrap();
    assert!(out.success);
    let msgs: Vec<Value> = out.stdout_text().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
    let by_id = |id: u64| msgs.iter().find(|m| m["id"] == json!(id)).unwrap().clone();
    assert_eq!(by_id(1)["result"]["serverInfo"]["name"], "craft-anything");
    assert!(by_id(2)["result"]["tools"].as_array().unwrap().iter().any(|t| t["name"] == "core_session_show"));
    assert_eq!(by_id(3)["result"]["isError"], false);
}

#[test]
fn mcp_restores_the_desktop_target_before_listing_tools() {
    use craft_anything_engine::target::{Target, TargetContext};
    let config = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let file = directory.path().join("shared.bin");
    std::fs::write(&file, b"shared-target").unwrap();
    let target = Target::load(&file).unwrap();
    let context = serde_json::to_string(&TargetContext::from_target(&target)).unwrap();
    let input = [
        json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}),
        json!({"jsonrpc":"2.0","method":"notifications/initialized"}),
        json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"core_targets_list","arguments":{}}}),
    ].iter().map(|message| format!("{message}\n")).collect::<String>();
    for mode in ["--deep", "--clean-room"] {
        let output = cli_with_stdin(&["mcp", mode, "--target", &context], config.path(), input.as_bytes());
        assert!(output.success, "{}", output.stderr_text());
        let messages: Vec<Value> = output.stdout_text().lines().map(|line| serde_json::from_str(line).unwrap()).collect();
        let response = messages.iter().find(|message| message["id"] == 2).unwrap();
        assert_eq!(response["result"]["isError"], false, "{response}");
        let value: Value = serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
        assert_eq!(value["result"]["targets"][0]["target_id"], target.id, "{value}");
    }
}

#[test]
fn raw_binary_open_params_tool_format_and_project_evidence_across_processes() {
    let cfg = tempfile::tempdir().unwrap();
    let dir = tempfile::tempdir().unwrap();
    let raw = dir.path().join("raw.bin");
    // push rbp; mov rbp, rsp; xor eax, eax; pop rbp; ret
    std::fs::write(&raw, [0x55, 0x48, 0x89, 0xe5, 0x31, 0xc0, 0x5d, 0xc3]).unwrap();
    let raw = raw.to_str().unwrap();
    let proj = dir.path().join("p.cany");
    let proj = proj.to_str().unwrap();

    // A tool's own --format reaches the tool; the output format has --output-format.
    let out = cli(
        &["core-target-open", raw, "--format", "raw-binary", "--architecture", "x86_64", "--entry-point", "0x1000", "--output-format", "json", "--deep"],
        cfg.path(),
    );
    assert!(out.success, "{}", out.stdout_text());
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(v["result"]["kind"], "raw-binary", "{v}");

    // A target tool reopens the path with the raw-binary options.
    let out = cli(
        &["--deep", "native-function-pseudocode", raw, "--architecture", "x86_64", "--entry-point", "0x1000", "--function", "0x1000", "--project", proj],
        cfg.path(),
    );
    assert!(out.success, "{}", out.stdout_text());

    // A new process on the same project sees the stored evidence.
    let out = cli(&["core-evidence-show", "--detail", "summary", "--project", proj], cfg.path());
    assert!(out.success, "{}", out.stdout_text());
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert!(v["result"]["total"].as_u64().unwrap() >= 1, "{v}");
    let out = cli(&["core-session-show", "--project", proj], cfg.path());
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert!(v["result"]["evidence_records"].as_u64().unwrap() >= 1, "{v}");
}

fn cli_with_stdin(args: &[&str], config: &std::path::Path, input: &[u8]) -> Output {
    Process::new(env!("CARGO_BIN_EXE_craft-anything-cli"))
        .args(args)
        .env("CRAFT_ANYTHING_CONFIG_DIR", config)
        .stdin_bytes(input.to_vec())
        .timeout(Duration::from_secs(60))
        .run()
        .unwrap()
}

/// `--json -` takes a tool's parameters from a pipe, and `-` isn't read as the shorthand for JSON output.
#[test]
fn parameters_can_come_from_a_pipe() {
    let cfg = tempfile::tempdir().unwrap();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("plain.txt");
    std::fs::write(&file, b"nothing packed here").unwrap();
    let params = json!({"path": file}).to_string();
    let out = cli_with_stdin(&["core-packed-files-list", "--deep", "--json", "-"], cfg.path(), params.as_bytes());
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    // The file reached the tool: it says the file isn't packed, not that the path is missing.
    assert_eq!(v["error"]["code"], "not_supported", "{v}");
    let bad = cli_with_stdin(&["core-packed-files-list", "--deep", "--json", "-"], cfg.path(), b"not json");
    assert_eq!(bad.code, Some(2), "{}", String::from_utf8_lossy(&bad.stderr));
    let empty = cli_with_stdin(&["core-packed-files-list", "--deep", "--json", "-"], cfg.path(), b"");
    assert_eq!(empty.code, Some(2), "an empty pipe is an error, not a wait");
}

#[test]
fn csv_and_tsv_output_show_a_tools_rows() {
    let cfg = tempfile::tempdir().unwrap();
    let out = cli(&["core-session-show", "--output-format", "csv"], cfg.path());
    assert!(out.success);
    let text = String::from_utf8_lossy(&out.stdout);
    let mut lines = text.lines();
    assert!(lines.next().unwrap().split(',').any(|c| c == "clean_room"), "{text}");
    let tsv = cli(&["core-session-show", "--output-format", "tsv"], cfg.path());
    assert!(String::from_utf8_lossy(&tsv.stdout).lines().next().unwrap().split('\t').any(|c| c == "clean_room"));
}

/// A bare argument is the file, not whichever string option sorts first (`contains`, `detail`).
#[test]
fn a_bare_argument_is_the_path_even_when_other_options_sort_first() {
    let cfg = tempfile::tempdir().unwrap();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("plain.txt");
    std::fs::write(&file, b"nothing packed here").unwrap();
    let path = file.to_str().unwrap();
    let packed: Value = serde_json::from_slice(&cli(&["core-packed-files-list", "--deep", path], cfg.path()).stdout).unwrap();
    assert_eq!(packed["error"]["code"], "not_supported", "the file was read: {packed}");
    let model: Value = serde_json::from_slice(&cli(&["formats-ai-weights-show", "--deep", path], cfg.path()).stdout).unwrap();
    assert!(!model["error"]["message"].as_str().unwrap_or_default().contains("unknown variant"), "{model}");
}

/// #254: the top-level help must not advise `report --format`, which the parser sends to the global output format.
#[test]
fn help_does_not_advise_a_report_format_option() {
    let cfg = tempfile::tempdir().unwrap();
    let help = cli(&["--help"], cfg.path());
    assert!(help.success);
    assert!(!help.stdout_text().contains("(core-target-open, report"));
    assert_eq!(cli(&["report", "--format", "html"], cfg.path()).code, Some(2));
}

/// #855, #856: CLI mcp --restricted omits machine and web tools, and refuses web_site_open.
#[test]
fn mcp_restricted_mode_cli() {
    let cfg = tempfile::tempdir().unwrap();
    let input = [
        json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "t", "version": "0"}}}),
        json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
        json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
        json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "web_site_open", "arguments": {"url": "https://example.com"}}}),
    ]
    .iter()
    .map(|v| format!("{v}\n"))
    .collect::<String>();

    let out = Process::new(env!("CARGO_BIN_EXE_craft-anything-cli"))
        .arg("mcp")
        .arg("--restricted")
        .arg("--all-tools")
        .env("CRAFT_ANYTHING_CONFIG_DIR", cfg.path())
        .stdin_bytes(input)
        .timeout(Duration::from_secs(30))
        .run()
        .unwrap();
    assert!(out.success, "{}", out.stderr_text());
    let msgs: Vec<Value> = out.stdout_text().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
    let by_id = |id: u64| msgs.iter().find(|m| m["id"] == json!(id)).unwrap().clone();

    // Tools list omits machine tools and web tools
    let tools = by_id(2)["result"]["tools"].as_array().unwrap().clone();
    assert!(!tools.iter().any(|t| t["name"] == "web_site_open"));
    assert!(!tools.iter().any(|t| t["name"] == "web_site_capture"));
    assert!(!tools.iter().any(|t| t["name"] == "build_command_run"));
    assert!(tools.iter().any(|t| t["name"] == "core_session_show"));

    // tools/call web_site_open is refused
    let call_res = by_id(3)["result"].clone();
    assert_eq!(call_res["isError"], true);
    let err_obj: Value = serde_json::from_str(call_res["content"][0]["text"].as_str().unwrap()).unwrap();
    assert!(err_obj["error"]["message"].as_str().unwrap().contains("turned off in restricted mode"));
}

/// Uninstall's text output says why a client blocked it and how to fix that, not just the client's name.
#[test]
fn uninstall_text_shows_why_a_client_blocks_it_and_the_fix() {
    let home = tempfile::tempdir().unwrap();
    let cursor = home.path().join(".cursor");
    std::fs::create_dir_all(&cursor).unwrap();
    std::fs::write(cursor.join("mcp.json"), [0xffu8, 0xfe, 0x00]).unwrap();
    for format in ["text", "md"] {
        let mut p = Process::new(env!("CARGO_BIN_EXE_craft-anything-cli"))
            .args(["--format", format, "uninstall"])
            .env("CRAFT_ANYTHING_CONFIG_DIR", home.path().join("config"))
            .env("HOME", home.path())
            .env("USERPROFILE", home.path());
        // Every client location the host reads from the environment stays inside the temporary home.
        for k in craft_anything_setup::clients::ENV_KEYS {
            p = p.env(k, home.path().join(k));
        }
        let out = p.timeout(Duration::from_secs(60)).run().unwrap();
        let text = String::from_utf8_lossy(&out.stdout);
        assert_eq!(out.code, Some(1), "{format}: {text}");
        assert!(text.contains("blocked by Cursor: Can't read ") && text.contains("the file is not valid UTF-8"), "{format}: {text}");
        assert!(text.contains("save it as UTF-8 where it is, then run uninstall again."), "{format}: {text}");
    }
    assert_eq!(std::fs::read(cursor.join("mcp.json")).unwrap(), [0xffu8, 0xfe, 0x00]);
}