Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

7.0 KB
Raw Blame
use super::*;
use crate::core::all::{assert_schema_controller_parity, expect_schema_fields};
use crate::core::runtime::DispatchCtx;

#[test]
fn tokenjuice_schema_catalog_matches_registered_controllers() {
    crate::core::all::expect_schema_namespace(&all_controller_schemas(), "tokenjuice");
    assert_schema_controller_parity(
        &all_controller_schemas(),
        &all_registered_controllers(),
        "compress",
    );
}

/* Module-backed behavior is covered by TinyJuice's loader E2E. */

// ── #6088: `compress` must expose all five ContentHint fields ────────────────

/// Before #6088 the handler built `ContentHint { source_tool, ..Default::default() }`,
/// so four of the five fields were unreachable and the debug controller could not
/// reproduce what the content router does. These assert the mapping directly —
/// no module, no router — so they run everywhere.
#[test]
fn compress_hint_carries_every_caller_supplied_field() {
    let mut p = Map::new();
    p.insert("tool_name".into(), Value::from("grep"));
    p.insert("mime".into(), Value::from("text/html"));
    p.insert("extension".into(), Value::from("rs"));
    p.insert("query".into(), Value::from("needle"));
    p.insert("explicit".into(), Value::from("search"));

    let hint = compress_hint_from_params(&p).expect("a well-formed hint must parse");
    for (field, actual, expected) in [
        ("tool_name", hint.source_tool.as_deref(), "grep"),
        ("mime", hint.mime.as_deref(), "text/html"),
        ("extension", hint.extension.as_deref(), "rs"),
        ("query", hint.query.as_deref(), "needle"),
    ] {
        assert_eq!(
            actual,
            Some(expected),
            "caller-supplied {field} must reach the router"
        );
    }
    assert_eq!(
        hint.explicit,
        Some(ContentKind::Search),
        "`explicit` is the field that skips detection entirely — without it the \
         controller cannot force a kind, which is the point of the fix"
    );
}

#[test]
fn compress_hint_defaults_every_field_to_none() {
    let mut p = Map::new();
    p.insert("content".into(), Value::from("hello"));
    let hint = compress_hint_from_params(&p).expect("an empty hint must parse");
    assert!(hint.source_tool.is_none());
    assert!(hint.mime.is_none());
    assert!(hint.extension.is_none());
    assert!(hint.query.is_none());
    assert!(hint.explicit.is_none());
}

#[test]
fn compress_hint_refuses_an_unknown_explicit_kind() {
    let mut p = Map::new();
    p.insert("explicit".into(), Value::from("nonsense"));
    let err = compress_hint_from_params(&p)
        .expect_err("an unrecognised kind must be refused, not silently detected");
    assert!(
        err.contains("nonsense") && err.contains("plain_text"),
        "the refusal must quote the bad value and list the accepted set: {err}"
    );
}

/// `plain_text` is the spelling `ContentKind::from_str` accepts; serde renders the
/// same variant as `plainText`. The vendored `from_str` doc calls this out as the
/// exact trap, so pin the spelling the schema advertises.
#[test]
fn compress_hint_accepts_the_documented_plain_text_spelling() {
    let mut p = Map::new();
    p.insert("explicit".into(), Value::from("plain_text"));
    assert_eq!(
        compress_hint_from_params(&p)
            .expect("plain_text must parse")
            .explicit,
        Some(ContentKind::PlainText),
        "`plain_text` is the spelling `ContentKind::from_str` accepts and the one \
         the schema advertises; serde's `plainText` must not be what we parse"
    );
}

#[test]
fn compress_schema_declares_all_five_hint_inputs() {
    expect_schema_fields(
        &schemas("compress"),
        &[
            ("content", Some(true)),
            ("tool_name", Some(false)),
            ("mime", Some(false)),
            ("extension", Some(false)),
            ("query", Some(false)),
            ("explicit", Some(false)),
        ],
    );
}

/// `/schema` is what generators and model-facing tool definitions read. Declaring
/// `explicit` as a bare string there invites a caller to propose a value that only
/// fails once the handler runs; as an enum, `check_type` rejects it at the dispatch
/// boundary and the published contract matches the rejection.
#[test]
fn compress_declares_explicit_as_an_enum_of_the_accepted_kinds() {
    let s = schemas("compress");
    let explicit = s
        .inputs
        .iter()
        .find(|f| f.name == "explicit")
        .expect("`compress` must declare `explicit`");

    let TypeSchema::Option(inner) = &explicit.ty else {
        panic!(
            "`explicit` is optional and must be declared as such: {:?}",
            explicit.ty
        );
    };
    let TypeSchema::Enum { variants } = inner.as_ref() else {
        panic!(
            "`explicit` must be an enum so the accepted kinds are discoverable \
             from /schema rather than only from the handler: {inner:?}"
        );
    };
    assert_eq!(
        variants,
        &[
            "json",
            "code",
            "log",
            "search",
            "diff",
            "html",
            "plain_text"
        ],
        "the declared variants must be exactly what `ContentKind::from_str` parses \
         — note `plain_text`, not serde's `plainText`"
    );
}

// ── [components] juice = false ────────────────────────────────────────

#[tokio::test]
async fn every_tokenjuice_method_answers_component_disabled_when_juice_is_off() {
    type ControllerHandler = fn(DispatchCtx, Map<String, Value>) -> ControllerFuture;
    let mut set = crate::core::runtime::ComponentSet::all();
    set.juice = false;
    let ctx = crate::core::runtime::context::CoreContext::for_test_with_components(set);
    let handlers: [ControllerHandler; 8] = [
        handle_detect,
        handle_compress,
        handle_cache_stats,
        handle_retrieve,
        handle_settings_get,
        handle_settings_update,
        handle_savings_stats,
        handle_savings_reset,
    ];
    let dispatch = DispatchCtx::new(ctx.clone());
    crate::core::runtime::context::CoreContext::scope(ctx, async {
        for handler in handlers {
            let err = handler(dispatch.clone(), Map::new()).await.unwrap_err();
            let decoded = crate::core::StructuredRpcError::decode(&err).expect("typed error");
            assert_eq!(decoded.message, "COMPONENT_DISABLED:juice");
        }
    })
    .await;
}

#[tokio::test]
async fn tokenjuice_methods_are_not_gated_when_juice_is_on() {
    let ctx = crate::core::runtime::context::CoreContext::for_test_with_components(
        crate::core::runtime::ComponentSet::all(),
    );
    crate::core::runtime::context::CoreContext::scope(ctx.clone(), async {
        // Gate passes; the handler then fails on its own missing param.
        let err = handle_detect(DispatchCtx::new(ctx.clone()), Map::new())
            .await
            .unwrap_err();
        assert!(!err.contains("COMPONENT_DISABLED"), "{err}");
    })
    .await;
}