Cotton code
520 lines · 19.9 KB · RustRaw
//! Each adapter's argv, its hook files and its permission dialect, against//! fixtures.//!//! The fixtures are `include_str!`'d rather than read by path: a fixture that//! moved is then a BUILD failure naming the file it could not find, never a//! test that quietly starts passing over an empty read.//!//! Nothing here spawns an agent. That is not a limitation of the test//! environment — it is the point: an argv is a value, and a value is compared,//! not executed. `codex` is not installed on the Mac this was written on, and//! the Codex adapter is held entirely by what is pinned below.use std::collections::BTreeMap;use cotton_session_host::agents::{adapter, claude::Claude, codex::Codex, Adapter, Launch};use cotton_session_host::browser::Offer;use cotton_session_host::protocol::{Decision, PermissionMode, Provider, Tool};const CLAUDE_SETTINGS: &str = include_str!("fixtures/claude-settings.json");const CODEX_HOOKS: &str = include_str!("fixtures/codex-hooks-override.txt");const HOST: &str = "/Applications/CottonDB.app/Contents/Helpers/cotton-session-host";const SESSION: &str = "11111111-2222-3333-4444-555555555555";const LAUNCH_DIR: &str = "/Users/owner/Library/Application Support/CottonDB/sessions/11111111-2222-3333-4444-555555555555";fn launch(extras: &[&str], mode: PermissionMode) -> Launch {    resuming(extras, mode, None)}/// The same launch, continuing an agent session the host already knows.fn resuming(extras: &[&str], mode: PermissionMode, resume: Option<&str>) -> Launch {    Launch {        resume: resume.map(str::to_string),        launch_id: "launch-1".to_string(),        session_id: SESSION.to_string(),        argv_extras: extras.iter().map(|arg| (*arg).to_string()).collect(),        cwd: "/work/repo".to_string(),        env: BTreeMap::from([("TERM".to_string(), "xterm-256color".to_string())]),        cols: 120,        rows: 40,        permission_mode: mode,        host_binary: HOST.to_string(),        launch_dir: LAUNCH_DIR.to_string(),        browser: None,    }}#[test]fn claude_s_argv_names_the_session_the_settings_file_and_bypass() {    let plan = Claude.spawn_plan(&launch(&["--model", "opus"], PermissionMode::Bypass));    assert_eq!(        plan.argv,        vec![            "claude",            "--session-id",            SESSION,            "--settings",            "/Users/owner/Library/Application Support/CottonDB/sessions/11111111-2222-3333-4444-555555555555/claude-settings.json",            "--dangerously-skip-permissions",            "--model",            "opus",        ]    );    assert_eq!(plan.cwd, "/work/repo");    assert_eq!((plan.cols, plan.rows), (120, 40));}#[test]fn claude_in_ask_mode_carries_no_bypass_flag_so_the_permission_hook_fires() {    let plan = Claude.spawn_plan(&launch(&[], PermissionMode::Ask));    assert!(        !plan.argv.iter().any(|arg| arg == "--dangerously-skip-permissions"),        "ask mode is the absence of the flag — got {:?}",        plan.argv    );}/// RULE: A hosted Claude Code session never gets CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC or DISABLE_TELEMETRY, even from the login shell, because both take away Monitor and every claude.ai connector, so the phone cannot reach the session.#[test]fn claude_s_environment_quiets_the_updater_and_never_switches_off_the_tools_the_phone_needs() {    let mut launch = launch(&[], PermissionMode::Bypass);    for name in cotton_session_host::agents::claude::NEVER_SET {        launch.env.insert(name.to_string(), "1".to_string());    }    let plan = Claude.spawn_plan(&launch);    assert_eq!(plan.env.get("DISABLE_AUTOUPDATER").map(String::as_str), Some("1"));    for name in cotton_session_host::agents::claude::NEVER_SET {        assert_eq!(plan.env.get(name), None, "{name} would take Monitor and the connectors away");    }    assert_eq!(plan.env.get("TERM").map(String::as_str), Some("xterm-256color"));}#[test]fn claude_s_hook_settings_are_exactly_the_file_the_fixture_holds() {    let files = Claude.hook_files(&launch(&[], PermissionMode::Ask));    assert_eq!(files.len(), 1, "one file, inside the session's own directory");    assert_eq!(        files[0].path,        format!("{LAUNCH_DIR}/claude-settings.json"),        "never the settings.json in the person's own home"    );    let written: serde_json::Value =        serde_json::from_str(&files[0].contents).expect("the settings file is JSON");    let expected: serde_json::Value =        serde_json::from_str(CLAUDE_SETTINGS).expect("the fixture is JSON");    assert_eq!(written, expected);}#[test]fn claudes_task_list_arm_is_matched_to_one_tool_name_so_no_other_tool_costs_a_round_trip() {    let files = Claude.hook_files(&launch(&[], PermissionMode::Ask));    let written: serde_json::Value =        serde_json::from_str(&files[0].contents).expect("the settings file is JSON");    let arm = &written["hooks"]["PostToolUse"][0];    assert_eq!(        arm["matcher"], "TodoWrite",        "a bare PostToolUse would reach this host after every file the session read"    );    assert_eq!(        arm["hooks"][0]["command"],        format!("{HOST} hook PostToolUse")    );}#[test]fn codex_registers_no_task_list_hook_because_it_has_no_task_list_tool() {    let override_value = Codex::hooks_override(&launch(&[], PermissionMode::Ask));    assert!(        !override_value.contains("PostToolUse"),        "an unmatched PostToolUse on Codex is a round trip after every command — got {override_value}"    );}#[test]fn claude_files_a_transcript_under_the_slug_its_own_convention_makes() {    assert_eq!(        Claude::transcript_slug("/Users/owner/Code/cottondb"),        "-Users-owner-Code-cottondb"    );}#[test]fn codex_s_argv_names_the_directory_the_overrides_and_both_bypasses() {    let plan = Codex.spawn_plan(&launch(&["-m", "gpt-5-codex"], PermissionMode::Bypass));    assert_eq!(        plan.argv,        vec![            "codex",            "-C",            "/work/repo",            "-c",            "check_for_update_on_startup=false",            "-c",            CODEX_HOOKS,            "--dangerously-bypass-hook-trust",            "--dangerously-bypass-approvals-and-sandbox",            "-m",            "gpt-5-codex",        ]    );}#[test]fn codex_in_ask_mode_keeps_the_hook_trust_bypass_and_drops_the_approvals_one() {    let plan = Codex.spawn_plan(&launch(&[], PermissionMode::Ask));    assert!(        plan.argv.iter().any(|arg| arg == "--dangerously-bypass-hook-trust"),        "the hooks are still this host's own, and a trust prompt looks like a hang"    );    assert!(        !plan            .argv            .iter()            .any(|arg| arg == "--dangerously-bypass-approvals-and-sandbox"),        "ask mode is the absence of that flag — got {:?}",        plan.argv    );}#[test]fn codex_writes_no_file_at_all_so_a_crashed_host_leaves_nothing_behind() {    assert_eq!(Codex.hook_files(&launch(&[], PermissionMode::Ask)), Vec::new());}#[test]fn codex_never_moves_codex_home_because_that_is_where_the_person_s_login_lives() {    let plan = Codex.spawn_plan(&launch(&[], PermissionMode::Bypass));    assert!(        !plan.env.contains_key("CODEX_HOME"),        "an overlay would either copy the credential or break on a token refresh"    );    assert_eq!(plan.env.get("TERM").map(String::as_str), Some("xterm-256color"));}#[test]fn the_hooks_override_is_one_argument_carrying_every_event_this_host_handles() {    let override_value = Codex::hooks_override(&launch(&[], PermissionMode::Ask));    assert_eq!(override_value, CODEX_HOOKS);    for event in [        "SessionStart",        "UserPromptSubmit",        "Stop",        "SessionEnd",        "Notification",        "PermissionRequest",    ] {        assert!(            override_value.contains(&format!("hook {event}")),            "{event} is registered — got {override_value}"        );    }}#[test]fn claude_s_decision_is_claude_s_dialect() {    let allow = Claude.permission_reply(Decision::Allow);    assert_eq!(        allow["hookSpecificOutput"]["hookEventName"],        "PermissionRequest"    );    assert_eq!(allow["hookSpecificOutput"]["permissionDecision"], "allow");    let deny = Claude.permission_reply(Decision::Deny);    assert_eq!(deny["hookSpecificOutput"]["permissionDecision"], "deny");    assert!(deny["hookSpecificOutput"]["permissionDecisionReason"]        .as_str()        .is_some_and(|said| said.contains("Cotton")));}#[test]fn codex_s_decision_is_codex_s_dialect_and_they_are_not_the_same_shape() {    let allow = Codex.permission_reply(Decision::Allow);    assert_eq!(allow["hookSpecificOutput"]["decision"]["behavior"], "allow");    let deny = Codex.permission_reply(Decision::Deny);    assert_eq!(deny["hookSpecificOutput"]["decision"]["behavior"], "deny");    assert!(deny["hookSpecificOutput"]["decision"]["message"]        .as_str()        .is_some_and(|said| said.contains("Cotton")));    assert_ne!(        Claude.permission_reply(Decision::Allow),        Codex.permission_reply(Decision::Allow),        "the two dialects differ, which is why the encoding lives in the adapter"    );}#[test]fn a_session_wide_allow_travels_as_an_allow_on_both_because_neither_hook_has_the_form() {    assert_eq!(        Claude.permission_reply(Decision::AllowSession)["hookSpecificOutput"]["permissionDecision"],        "allow"    );    assert_eq!(        Codex.permission_reply(Decision::AllowSession)["hookSpecificOutput"]["decision"]["behavior"],        "allow"    );}#[test]fn the_adapter_for_a_tool_is_that_tool_s() {    assert_eq!(adapter(Tool::Claude).tool(), Tool::Claude);    assert_eq!(adapter(Tool::Codex).tool(), Tool::Codex);}// ── Resume: continuing a session that already exists ────────────────────────//// `session.resume` re-queues THE SAME ROW with its `external_id` kept, and the// executor hands that id down as `Request::Spawn.resume_from`. What the two// adapters do with it is the whole of the difference between "start" and// "carry on", and it is a value, so it is compared rather than executed.#[test]fn claude_resuming_says_resume_and_never_session_id() {    // The two flags are contradictory: one says "be this new session", the    // other "continue that one". An agent handed both has been told two things.    let plan = Claude.spawn_plan(&resuming(        &["--model", "opus"],        PermissionMode::Bypass,        Some("45d4f352-0000-0000-0000-000000000000"),    ));    assert_eq!(        plan.argv,        vec![            "claude",            "--resume",            "45d4f352-0000-0000-0000-000000000000",            "--settings",            "/Users/owner/Library/Application Support/CottonDB/sessions/11111111-2222-3333-4444-555555555555/claude-settings.json",            "--dangerously-skip-permissions",            "--model",            "opus",        ]    );    assert!(!plan.argv.iter().any(|arg| arg == "--session-id"), "{:?}", plan.argv);}#[test]fn claude_resuming_still_gets_its_own_hook_settings() {    // The hooks are what make a resumed session answer on the same row. A    // resume that quietly ran without them would be a card that never moved.    let launch = resuming(&[], PermissionMode::Bypass, Some("agent-1"));    let plan = Claude.spawn_plan(&launch);    assert!(plan.argv.iter().any(|arg| arg.ends_with("claude-settings.json")));    assert_eq!(Claude.hook_files(&launch).len(), 1);}#[test]fn codex_resuming_puts_the_subcommand_first_and_keeps_every_flag() {    let plan = Codex.spawn_plan(&resuming(        &["carry on"],        PermissionMode::Bypass,        Some("019-codex-own-id"),    ));    assert_eq!(plan.argv.first().map(String::as_str), Some("codex"));    assert_eq!(plan.argv.get(1).map(String::as_str), Some("resume"));    assert_eq!(plan.argv.get(2).map(String::as_str), Some("019-codex-own-id"));    // And nothing else moved: the working directory, the quieting override and    // the hook override are the same arguments a first start gets.    let fresh = Codex.spawn_plan(&launch(&["carry on"], PermissionMode::Bypass));    assert_eq!(plan.argv[3..], fresh.argv[1..]);}#[test]fn a_launch_that_resumes_nothing_is_exactly_what_it_always_was() {    for mode in [PermissionMode::Bypass, PermissionMode::Ask] {        assert_eq!(            Claude.spawn_plan(&launch(&[], mode)).argv,            Claude.spawn_plan(&resuming(&[], mode, None)).argv        );        assert_eq!(            Codex.spawn_plan(&launch(&[], mode)).argv,            Codex.spawn_plan(&resuming(&[], mode, None)).argv        );    }}// ── who is signed in ────────────────────────────────────────────────────────/// What `claude auth status` prints on 2.1.283, with every value that was/// somebody's replaced. Hand-copied from the agent's own output, so a version/// that renames a field is a test that fails here rather than a Mac that/// quietly reads as signed out.const CLAUDE_AUTH_STATUS: &str = include_str!("fixtures/claude-auth-status.json");#[test]fn claude_is_asked_who_is_signed_in_with_its_own_command() {    assert_eq!(Claude.account_argv(), Some(["auth", "status"].as_slice()));}#[test]fn claude_s_answer_is_read_as_the_provider_the_address_and_the_plan() {    let account = Claude        .read_account(CLAUDE_AUTH_STATUS)        .expect("somebody is signed in");    assert_eq!(account.provider, Provider::Anthropic);    assert_eq!(account.email, "owner@example.com");    assert_eq!(account.plan.as_deref(), Some("max"));}#[test]fn a_signed_out_claude_is_nobody_and_never_a_placeholder() {    // Signed out still prints an object, and exits 1.    assert_eq!(        Claude.read_account(r#"{"loggedIn": false, "authMethod": "none"}"#),        None    );    // `loggedIn` is READ, not inferred from an address being there.    assert_eq!(        Claude.read_account(r#"{"loggedIn": false, "email": "owner@example.com"}"#),        None    );}#[test]fn an_answer_that_names_no_address_is_nobody() {    // An API-key login names none, and an account row's key is the address.    assert_eq!(Claude.read_account(r#"{"loggedIn": true}"#), None);    assert_eq!(Claude.read_account(r#"{"loggedIn": true, "email": "  "}"#), None);    assert_eq!(Claude.read_account(r#"{"loggedIn": true, "email": 7}"#), None);}#[test]fn an_answer_that_is_not_the_agent_s_json_is_nobody() {    assert_eq!(Claude.read_account(""), None);    assert_eq!(Claude.read_account("Logged in as owner@example.com"), None);    assert_eq!(Claude.read_account("[]"), None);}#[test]fn a_plan_the_agent_does_not_name_is_absent_and_the_login_still_counts() {    let account = Claude        .read_account(r#"{"loggedIn": true, "email": "owner@example.com"}"#)        .expect("somebody is signed in");    assert_eq!(account.plan, None);}#[test]fn codex_is_not_asked_because_its_answer_names_nobody() {    assert_eq!(Codex.account_argv(), None);    assert_eq!(Codex.read_account("Logged in using ChatGPT"), None);}/// The same launch on a Mac that offers the browser tool.fn with_browser(extras: &[&str], mode: PermissionMode, resume: Option<&str>) -> Launch {    Launch {        browser: Some(Offer { data_dir: "/Users/owner/CottonDB".to_string(), flavor: cotton_session_host::data_dir::Flavor::Real }),        ..resuming(extras, mode, resume)    }}// RULE: An agent's browser MCP configuration explicitly carries the host's flavor, because an agent may filter inherited environment variables before launching Cotton's helper.#[test]fn browser_mcp_helpers_receive_the_host_flavor_explicitly() {    let launch = with_browser(&[], PermissionMode::Bypass, None);    for flavor in cotton_session_host::data_dir::Flavor::ALL {        let mut offer = launch.browser.clone().unwrap();        offer.flavor = flavor;        let claude = Claude::mcp_config(&launch, &offer);        assert_eq!(claude["mcpServers"]["cotton-browser"]["env"]["COTTON_FLAVOR"], flavor.as_str());        let codex = Codex::browser_override(&launch, &offer);        assert!(codex.contains(&format!("COTTON_FLAVOR=\"{}\"", flavor.as_str())), "{codex}");    }}/// RULE: A session on a Mac that offers the browser tool gets it as one more MCP server, added to the person's own.////// The server is this host's own binary (`browser mcp`) pointed at this/// host's data directory, so every session drives the one Chrome profile the/// owner signed in; `--strict-mcp-config` would throw the person's own/// servers away, and a file outside the launch directory would outlive it.#[test]fn claude_is_handed_the_browser_server_in_a_file_of_its_own_launch() {    let launch = with_browser(&["--model", "opus"], PermissionMode::Bypass, None);    let plan = Claude.spawn_plan(&launch);    let mcp_file = format!("{LAUNCH_DIR}/claude-mcp.json");    assert_eq!(        plan.argv[..7],        [            "claude".to_string(),            "--session-id".to_string(),            SESSION.to_string(),            "--mcp-config".to_string(),            mcp_file.clone(),            "--settings".to_string(),            format!("{LAUNCH_DIR}/claude-settings.json"),        ]    );    assert!(!plan.argv.iter().any(|arg| arg == "--strict-mcp-config"));    let files = Claude.hook_files(&launch);    assert_eq!(files.len(), 2);    assert_eq!(files[1].path, mcp_file);    let written: serde_json::Value =        serde_json::from_str(&files[1].contents).expect("the MCP file is JSON");    assert_eq!(        written,        serde_json::json!({            "mcpServers": {                "cotton-browser": {                    "type": "stdio",                    "command": HOST,                    "args": ["browser", "mcp"],                    "env": { "COTTON_MAC_DATA_DIR": "/Users/owner/CottonDB", "COTTON_FLAVOR": "real" }                }            }        })    );    // A Mac that does not offer it: no flag, no file — a session as before.    let plain = launch_without_browser();    assert!(!Claude.spawn_plan(&plain).argv.iter().any(|arg| arg == "--mcp-config"));    assert_eq!(Claude.hook_files(&plain).len(), 1);}fn launch_without_browser() -> Launch {    launch(&["--model", "opus"], PermissionMode::Bypass)}/// RULE: The argument after Claude's --mcp-config file is always another flag, never the prompt.////// `--mcp-config <configs...>` takes a LIST: a prompt placed right after the/// file would be read as a second config file and the session would start/// without its task.#[test]fn claude_s_mcp_config_file_is_always_followed_by_a_flag() {    for resume in [None, Some(SESSION)] {        for mode in [PermissionMode::Ask, PermissionMode::Bypass] {            let argv = Claude.spawn_plan(&with_browser(&["fix the build"], mode, resume)).argv;            let at = argv                .iter()                .position(|arg| arg == "--mcp-config")                .expect("the browser server is configured");            assert!(                argv[at + 2].starts_with("--"),                "{:?} follows the MCP config file — {argv:?}",                argv[at + 2]            );            assert_eq!(argv.last().map(String::as_str), Some("fix the build"));        }    }}#[test]fn codex_is_handed_the_browser_server_as_one_override_for_this_launch() {    let plan = Codex.spawn_plan(&with_browser(&[], PermissionMode::Ask, None));    let expected = format!(        "mcp_servers.cotton-browser={{command=\"{HOST}\",args=[\"browser\",\"mcp\"],\         env={{COTTON_FLAVOR=\"real\",COTTON_MAC_DATA_DIR=\"/Users/owner/CottonDB\"}},startup_timeout_sec=60}}"    );    let at = plan        .argv        .iter()        .position(|arg| *arg == expected)        .unwrap_or_else(|| panic!("no browser override in {:?}", plan.argv));    assert_eq!(plan.argv[at - 1], "-c");    assert_eq!(Codex.hook_files(&with_browser(&[], PermissionMode::Ask, None)), Vec::new());    assert!(!Codex        .spawn_plan(&launch(&[], PermissionMode::Ask))        .argv        .iter()        .any(|arg| arg.starts_with("mcp_servers.")));}