Cotton code
225 lines · 8.7 KB · RustRaw
//! The Code tool's owner methods — the three settings, and the two verbs that//! reach the session host by one of two routes (schema v15).//!//! Every fixture here is synthetic: a device key of a's, a project nobody owns//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).use serde_json::{json, Map, Value};use crate::shell::client::phone_tests::attached;use crate::shell::client::ClientController;const DEVICE_KEY: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";fn seed_device(client: &ClientController, revoked: bool) {    let workspace = client        .with_writer(|replica| Ok(replica.workspace_id.to_string()))        .expect("the workspace");    let revoked_at = if revoked {        "'2026-01-02T00:00:00.000Z'"    } else {        "NULL"    };    client        .with_writer(|replica| {            replica                .driver                .exec(&format!(                    "INSERT INTO cotton_devices \                       (id, workspace_id, device_id, name, approved_at, approved_by_device, \                        revoked_at, created_at, updated_at) \                     VALUES ('33333333-3333-4333-8333-333333333333', '{workspace}', \                             '{DEVICE_KEY}', 'A Mac', '2026-01-01T00:00:00.000Z', 'owner', \                             {revoked_at}, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')"                ))                .map_err(|error| error.to_string())?;            cotton_tools::test_fixtures::reconcile(replica.driver, "cotton_devices");            Ok(())        })        .expect("the device");}fn one_row(client: &ClientController, sql: &str) -> Option<Map<String, Value>> {    client        .with_writer(|replica| {            Ok(replica                .driver                .get(sql, &[])                .map_err(|error| error.to_string())?                .map(|row| {                    let mut out = Map::new();                    let names: Vec<String> =                        row.columns().iter().map(|(name, _)| name.clone()).collect();                    for name in names {                        out.insert(                            name.clone(),                            row.text(&name).map_or(Value::Null, Value::from),                        );                    }                    out                }))        })        .expect("the row")}// ── device.setSessions ──────────────────────────────────────────────────────#[test]fn a_macs_cap_is_the_one_switch_and_zero_is_a_real_answer() {    // A CAP AND NOT A PAUSE (v23): a Mac that should take no work is one at    // zero, which is a number the picking rule already reads.    let (_dir, client) = attached();    seed_device(&client, false);    client        .write_rows("device.setSessions", &mut |ctx| {            super::code::write_sessions(ctx, DEVICE_KEY, 0)        })        .expect("the cap");    let row = one_row(        &client,        "SELECT CAST(sessions_cap AS TEXT) AS sessions_cap FROM cotton_devices WHERE device_id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'",    )    .expect("the device");    assert_eq!(        row["sessions_cap"],        json!("0"),        "0 takes the Mac out of the household"    );    client        .write_rows("device.setSessions", &mut |ctx| {            super::code::write_sessions(ctx, DEVICE_KEY, 5)        })        .expect("the cap again");    let row = one_row(        &client,        "SELECT CAST(sessions_cap AS TEXT) AS sessions_cap FROM cotton_devices WHERE device_id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'",    )    .expect("the device");    assert_eq!(row["sessions_cap"], json!("5"));}#[test]fn a_revoked_mac_is_not_a_place_to_change_a_setting() {    let (_dir, client) = attached();    seed_device(&client, true);    let refused = client        .write_rows("device.setSessions", &mut |ctx| {            super::code::write_sessions(ctx, DEVICE_KEY, 1)        })        .expect_err("a refusal");    assert!(refused.contains("revoked"), "{refused}");}#[test]fn a_key_nobody_admitted_is_named_in_the_refusal() {    let (_dir, client) = attached();    let refused = client        .write_rows("device.setSessions", &mut |ctx| {            super::code::write_sessions(ctx, "nobody", 1)        })        .expect_err("a refusal");    assert!(refused.contains("nobody"), "{refused}");}#[test]fn the_cap_is_checked_before_anything_is_written() {    let nothing =        super::code::validate_sessions(&json!({ "deviceId": DEVICE_KEY })).expect_err("a refusal");    assert_eq!(nothing.code, "bad_request");    assert!(nothing.message.contains("0 to 32"), "{}", nothing.message);    let cap = super::code::validate_sessions(&json!({ "deviceId": DEVICE_KEY, "sessionsCap": 99 }))        .expect_err("a refusal");    assert!(cap.message.contains("0 to 32"), "{}", cap.message);    let id =        super::code::validate_sessions(&json!({ "sessionsCap": 1 })).expect_err("a refusal");    assert!(id.message.contains("`deviceId`"), "{}", id.message);    let zero =        super::code::validate_sessions(&json!({ "deviceId": DEVICE_KEY, "sessionsCap": 0 }))            .expect("the arguments");    assert_eq!(zero.sessions_cap, 0);}// ── workspace.setCode ───────────────────────────────────────────────────────#[test]fn the_households_default_is_one_of_two_and_bypass_is_where_it_starts() {    let (_dir, client) = attached();    let row = one_row(&client, "SELECT session_permission_default FROM cotton_workspaces")        .expect("the workspace");    assert_eq!(        row["session_permission_default"],        json!("bypass"),        "what a session starts in unless the person picks otherwise"    );    client        .write_rows("workspace.setCode", &mut |ctx| {            super::code::write_code_settings(ctx, "ask")        })        .expect("the default");    let row = one_row(&client, "SELECT session_permission_default FROM cotton_workspaces")        .expect("the workspace");    assert_eq!(row["session_permission_default"], json!("ask"));}#[test]fn a_permission_default_nobody_offers_is_refused_before_anything_is_written() {    let missing = super::code::validate_code_settings(&json!({})).expect_err("a refusal");    assert_eq!(missing.code, "bad_request");    assert!(missing.message.contains("bypass or ask"), "{}", missing.message);    let wrong = super::code::validate_code_settings(&json!({ "permissionDefault": "whenever" }))        .expect_err("a refusal");    assert!(wrong.message.contains("bypass or ask"), "{}", wrong.message);}#[test]fn every_method_this_module_names_is_one_the_core_answers() {    for method in super::code::METHODS {        assert!(            crate::methods::ALL_METHODS.contains(&method),            "{method} is dispatched but not declared"        );    }}// ── device.setAiCap ─────────────────────────────────────────────────────────/// RULE: the serving Mac's daily Claude API cap is the owner's number on its device row — set, changed, and cleared back to the $5 default by null; an out-of-range cap and a revoked device are refused.#[test]fn the_daily_ai_cap_is_set_and_cleared_on_the_device_row() {    let (_dir, client) = attached();    seed_device(&client, false);    let cap = |client: &ClientController| {        one_row(            client,            "SELECT CAST(ai_day_cap_usd AS TEXT) AS cap FROM cotton_devices WHERE device_id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'",        )        .expect("the device")["cap"]            .clone()    };    client        .write_rows("device.setAiCap", &mut |ctx| super::code::write_ai_cap(ctx, DEVICE_KEY, Some(2.5)))        .expect("the cap");    assert_eq!(cap(&client), json!("2.5"));    client        .write_rows("device.setAiCap", &mut |ctx| super::code::write_ai_cap(ctx, DEVICE_KEY, None))        .expect("cleared");    assert_eq!(cap(&client), Value::Null, "null is the default again");    assert!(super::code::validate_ai_cap(&json!({ "deviceId": DEVICE_KEY, "capUsd": -1 })).is_err());    assert!(super::code::validate_ai_cap(&json!({ "deviceId": DEVICE_KEY, "capUsd": 5000 })).is_err());    assert!(super::code::validate_ai_cap(&json!({ "deviceId": DEVICE_KEY, "capUsd": null })).unwrap().cap_usd.is_none());    let (_dir, revoked) = attached();    seed_device(&revoked, true);    assert!(revoked        .write_rows("device.setAiCap", &mut |ctx| super::code::write_ai_cap(ctx, DEVICE_KEY, Some(1.0)))        .is_err());}