gent-link 0.2.24

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
use super::*;

#[tokio::test]
async fn named_connectors_never_advertise_oauth_or_challenge_a_missing_url() {
    let root = tempfile::tempdir().unwrap();
    let home = root.path().join("web");
    config::initialize(&home, "web").unwrap();
    registry::capability::create(&home).unwrap();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let origin = format!("http://{address}");
    let server = Running::start(&home, listener, origin.clone(), address.to_string(), None).await;
    let client = client();
    for path in [
        "/mcp",
        "/.well-known/oauth-protected-resource",
        "/.well-known/oauth-protected-resource/mcp",
        "/.well-known/oauth-authorization-server",
        "/oauth/authorize",
        "/oauth/token",
    ] {
        let response = client.get(format!("{origin}{path}")).send().await.unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND, "{path}");
        assert!(!response.headers().contains_key("www-authenticate"));
    }
    let url = registry::capability::url(&home, &origin, false).unwrap();
    let response = rpc(
        &client,
        &url,
        "initialize",
        json!({
            "protocolVersion":"2026-07-28", "capabilities":{},
            "clientInfo":{"name":"connector-probe","version":"1"}
        }),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    assert!(!response.headers().contains_key("www-authenticate"));
    server.close().await;
}

async fn rpc(
    client: &reqwest::Client,
    url: &str,
    method: &str,
    params: Value,
) -> reqwest::Response {
    let mut request = client
        .post(url)
        .header("accept", "application/json, text/event-stream")
        .header("mcp-protocol-version", "2026-07-28")
        .header("mcp-method", method);
    if let Some(name) = params["name"].as_str() {
        request = request.header("mcp-name", name);
    }
    request
        .json(&json!({"jsonrpc":"2.0", "id":1, "method":method,
            "params":params}))
        .send()
        .await
        .unwrap()
}

async fn call(client: &reqwest::Client, url: &str, name: &str, arguments: Value) -> Value {
    let response = rpc(
        client,
        url,
        "tools/call",
        json!({"name":name,"arguments":arguments,
        "_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28",
            "io.modelcontextprotocol/clientCapabilities":{}}}),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    let value: Value = response.json().await.unwrap();
    assert!(value.get("error").is_none(), "{value}");
    assert_ne!(value["result"]["isError"], true, "{value}");
    serde_json::from_str(value["result"]["content"][0]["text"].as_str().unwrap()).unwrap()
}

#[tokio::test]
async fn named_connector_can_follow_pending_send_and_wait_actions() {
    let f = Fixture::new();
    registry::capability::create(&f.home).unwrap();
    let daemon = Daemon::start(&f.home).await;
    let server = f.start().await;
    let base = server.url.trim_end_matches("/mcp");
    let url = registry::capability::url(&f.home, base, false).unwrap();
    let client = client();
    let caller =
        call(&client, &url, "gent_conversation_open", json!({})).await["conversation"].clone();
    call(
        &client,
        &url,
        "gent_register",
        json!({"conversation":caller,"name":"caller","provider":"web"}),
    )
    .await;
    let target_call = |name, args| server.call(&client, &f.token, "target", name, args);
    let target = target_call(
        "gent_register",
        json!({"name":"target","provider":"native"}),
    )
    .await;
    let args = json!({"conversation":caller,"recipient":target["agent"]["id"],"request_id":request_id(),"text":"Question"});

    // Rotate after admission so the initial send's status read loses its permit.
    let rotate = async {
        loop {
            let inbox = target_call("gent_inbox", json!({})).await;
            if let Some(id) = inbox[0]["id"].as_str() {
                return (
                    registry::capability::url(&f.home, base, true).unwrap(),
                    id.to_owned(),
                );
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
    };
    let (fallback, rotation) = tokio::join!(
        call(&client, &url, "gent_send", args.clone()),
        tokio::time::timeout(Duration::from_secs(5), rotate),
    );
    let (rotated, turn) = rotation.unwrap();
    assert_eq!(fallback["state"], "pending");
    assert_eq!(fallback["message_id"], turn);
    assert!(
        fallback["next_action"]["arguments"]
            .get("after_message_id")
            .is_none()
    );
    assert!(
        fallback["instruction"]
            .as_str()
            .unwrap()
            .contains("lookup unavailable")
    );
    let progress = target_call(
        "gent_relay_respond",
        json!({"turn_id":turn,"request_id":request_id(),"text":"Working","outcome":"progress"}),
    )
    .await;
    // An identical send now takes the ordinary pending path with a response cursor.
    let sent = call(&client, &rotated, "gent_send", args).await;
    assert_eq!(sent["duplicate"], true);
    assert_eq!(sent["state"], "pending");
    assert_eq!(sent["next_after"], progress["message_id"]);
    let wait = |result: &Value| {
        assert_eq!(result["next_action"]["tool"], "gent_wait");
        call(
            &client,
            &rotated,
            "gent_wait",
            result["next_action"]["arguments"].clone(),
        )
    };
    let pending = wait(&fallback).await;
    assert_eq!(pending["state"], "pending");
    assert_eq!(pending["responses"][0]["id"], progress["message_id"]);
    target_call(
        "gent_reply",
        json!({"message_id":turn,"request_id":request_id(),"text":"Done"}),
    )
    .await;
    for result in [&sent, &pending] {
        let arguments = &result["next_action"]["arguments"];
        assert!(arguments["conversation"] == caller);
        assert_eq!(arguments["after_message_id"], progress["message_id"]);
        let completed = wait(result).await;
        assert_eq!(completed["turn_id"], turn);
        assert_eq!(completed["state"], "completed");
        assert_eq!(completed["responses"].as_array().unwrap().len(), 1);
        assert_eq!(completed["responses"][0]["text"], "Done");
    }
    server.close().await;
    daemon.close(&f.home).await;
}

#[tokio::test]
async fn url_authentication_rotation_and_revocation_keep_chat_identities() {
    let f = Fixture::new();
    registry::capability::create(&f.home).unwrap();
    registry::capability::create(&f.home).unwrap();
    let daemon = Daemon::start(&f.home).await;
    let server = f.start().await;
    let base = server.url.trim_end_matches("/mcp").to_owned();
    let url = registry::capability::url(&f.home, &base, false).unwrap();
    let client = client();
    let init = rpc(
        &client,
        &url,
        "initialize",
        json!({"protocolVersion":"2026-07-28",
        "capabilities":{},"clientInfo":{"name":"phone","version":"1"}}),
    )
    .await;
    assert_eq!(init.status(), StatusCode::OK);
    let init = init.text().await.unwrap();
    assert!(!init.contains("gent_g1."));
    let chat =
        call(&client, &url, "gent_conversation_open", json!({})).await["conversation"].clone();
    let other =
        call(&client, &url, "gent_conversation_open", json!({})).await["conversation"].clone();
    let agent = call(
        &client,
        &url,
        "gent_register",
        json!({"conversation":chat,"name":"phone","provider":"synthetic"}),
    )
    .await;
    let second = call(
        &client,
        &url,
        "gent_register",
        json!({"conversation":other,"name":"other","provider":"synthetic"}),
    )
    .await;
    assert_ne!(agent["agent"]["id"], second["agent"]["id"]);
    assert!(
        !Registry::open(&f.home)
            .unwrap()
            .listing()
            .unwrap()
            .to_string()
            .contains("gent_g1.")
    );
    let rotated = registry::capability::url(&f.home, &base, true).unwrap();
    assert_ne!(url, rotated);
    let invalid = rpc(&client, &url, "tools/list", json!({})).await;
    assert_eq!(invalid.status(), StatusCode::NOT_FOUND);
    assert!(!invalid.headers().contains_key("www-authenticate"));
    let identity = call(
        &client,
        &rotated,
        "gent_identity",
        json!({"conversation":chat}),
    )
    .await;
    assert_eq!(identity["agent"]["id"], agent["agent"]["id"]);
    for invalid in [
        format!("{base}/mcp/{}", f.token),
        format!("{rotated}?secret=x"),
        format!("{rotated}/more"),
    ] {
        assert!(
            !rpc(&client, &invalid, "tools/list", json!({}))
                .await
                .status()
                .is_success()
        );
    }
    // Copying a valid URL's secret to another node cannot authenticate it there.
    let different = Fixture::new();
    let second_server = different.start().await;
    let wrong = format!(
        "{}/{}",
        second_server.url,
        rotated.rsplit('/').next().unwrap()
    );
    assert_eq!(
        rpc(&client, &wrong, "tools/list", json!({})).await.status(),
        StatusCode::NOT_FOUND
    );
    second_server.close().await;
    server.close().await;
    let server = f.start().await;
    let url =
        registry::capability::url(&f.home, server.url.trim_end_matches("/mcp"), false).unwrap();
    assert_eq!(
        call(&client, &url, "gent_identity", json!({"conversation":chat})).await["agent"]["id"],
        agent["agent"]["id"]
    );
    registry::capability::revoke(&f.home).unwrap();
    assert_eq!(
        rpc(&client, &url, "tools/list", json!({})).await.status(),
        StatusCode::NOT_FOUND
    );
    assert!(registry::capability::url(&f.home, &base, true).is_err());
    server.close().await;
    daemon.close(&f.home).await;
}