gent-link 0.2.1

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
use super::*;
use axum::{Json, Router, http::HeaderMap, routing::get};
use std::{
    fs,
    os::unix::fs::PermissionsExt,
    process::Command,
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    },
};
use tokio::net::TcpListener;

#[tokio::test]
async fn device_cursor_survives_reconnect_and_skips_future_event_kinds() {
    const TEST: &str =
        "auth::notifications::tests::device_cursor_survives_reconnect_and_skips_future_event_kinds";
    const FIXTURE: &str = "GENT_TEST_PRIVATE_NOTIFICATION_FIXTURE";
    let Some(root) = std::env::var_os(FIXTURE) else {
        let scratch = tempfile::tempdir().unwrap();
        let sender = scratch.path().join("notify-send");
        fs::write(
            &sender,
            r#"#!/bin/sh
dir="$GENT_TEST_PRIVATE_NOTIFICATION_FIXTURE"
if [ -e "$dir/reject" ]; then
    printf '%s\n' "$@" >> "$dir/rejected"
    exit 1
fi
printf '%s\n' "$@" >> "$dir/banners"
"#,
        )
        .unwrap();
        fs::set_permissions(sender, fs::Permissions::from_mode(0o700)).unwrap();
        // The child has a private PATH. No banner can reach the user's desktop.
        let result = Command::new(std::env::current_exe().unwrap())
            .args(["--exact", TEST])
            .env(FIXTURE, scratch.path())
            .env("PATH", scratch.path())
            .output()
            .unwrap();
        assert!(
            result.status.success(),
            "{}",
            String::from_utf8_lossy(&result.stdout)
        );
        return;
    };
    let root = Path::new(&root);
    let home = root.join("node");
    let icon = root.join("Gent Desktop icon.png");
    fs::write(&icon, include_bytes!("../../../branding/inkling-512.png")).unwrap();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let url = format!("http://{}/", listener.local_addr().unwrap());
    let login = Saved {
        version: 1,
        phase: Phase::Active,
        service: url,
        token: credential("gent_s1").unwrap(),
        session: Some(ServiceSession {
            account_id: "fixture".into(),
            github_subject: "1".into(),
            github_login: "fixture".into(),
            created_at: now().unwrap(),
            expires_at: now().unwrap() + 7200,
        }),
    };
    let session = source::directory(&home).unwrap().join("session.json");
    save(&session, Some(&login)).unwrap();
    let latest = now().unwrap();
    let oldest = latest - 20 * 60 * 60;
    let node = uuid::Uuid::from_u128(1);
    let chat = uuid::Uuid::from_u128(2);
    let recovery =
        json!({"kind":"goal_resumed","node":node,"chat":chat,"reason":"request_payload"});
    let update = json!({"kind":"update_installed","node":node,"commit":"a".repeat(40)});
    let mut rows = Vec::new();
    for seq in 1..=78_u64 {
        let event = match seq {
            1 | 68 | 74 => json!({"kind":"future_event"}),
            2 => json!({"kind":"goal_resumed","reason":"future_reason"}),
            3 | 69..=73 | 78 => update.clone(),
            _ => recovery.clone(),
        };
        let created_at = match seq {
            1..=4 => oldest - 60,
            75..=78 => latest,
            _ => oldest + (latest - oldest - 1) * (seq - 5) / 69,
        };
        rows.push(json!({"sequence":seq, "notice":{
            "id":uuid::Uuid::from_u128(100 + u128::from(seq)), "created_at":created_at, "event":event
        }}));
    }

    let rows = Arc::new(rows);
    let visible = Arc::new(AtomicUsize::new(4));
    let token = Arc::new(format!("Bearer {}", login.token));
    let app = Router::new().route(
        "/v1/notifications",
        get({
            let visible = visible.clone();
            move |headers: HeaderMap| {
                let token = token.clone();
                let rows = rows.clone();
                let visible = visible.load(Ordering::SeqCst);
                async move {
                    assert!(headers["authorization"].to_str().unwrap() == token.as_str());
                    let after: usize = headers["x-gent-after"].to_str().unwrap().parse().unwrap();
                    Json(
                        rows[..visible]
                            .iter()
                            .skip(after)
                            .take(64)
                            .cloned()
                            .collect::<Vec<_>>(),
                    )
                }
            }
        }),
    );
    let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    collect(&home, &login, &icon).await.unwrap();
    collect(&home, &login, &icon).await.unwrap();
    let (cursor, _) = cursor_paths(&home, &login).unwrap();
    assert_eq!(fs::read_to_string(&cursor).unwrap(), "4");
    let banners = root.join("banners");
    let first = fs::read_to_string(&banners).unwrap();
    let args: Vec<_> = first.lines().collect();
    let (banners_sent, remainder) = args.as_chunks::<7>();
    assert!(remainder.is_empty());
    assert_eq!(banners_sent.len(), 2);
    let hint = format!(
        "--hint=string:desktop-entry:{}",
        crate::desktop::desktop_entry_id(&home)
    );
    for (banner, title) in banners_sent
        .iter()
        .zip(["Gent updated", "Gent Babysitter resumed a goal"])
    {
        assert_eq!(
            banner[..6],
            [
                "--app-name=Gent",
                hint.as_str(),
                "--icon",
                icon.to_str().unwrap(),
                "--",
                title
            ]
        );
    }
    assert!(args[6].ends_with(" updated to aaaaaaaaaaaa."));
    // Finish the first page with an unknown event. All five updates occur
    // on the next page, which ends with another unknown sequence.
    visible.store(74, Ordering::SeqCst);
    let reject = root.join("reject");
    fs::write(&reject, b"").unwrap();
    assert!(collect(&home, &login, &icon).await.is_err());
    assert_eq!(fs::read_to_string(&cursor).unwrap(), "4");
    assert_eq!(fs::read_to_string(&banners).unwrap(), first);
    let rejected = fs::read_to_string(root.join("rejected")).unwrap();
    let summary: Vec<_> = rejected.lines().collect();
    assert_eq!(summary.len(), 7);
    assert_eq!(summary[..5], banners_sent[0][..5]);
    assert_eq!(
        summary[5..],
        [
            "Gent activity",
            "63 Babysitter recoveries · 5 updates installed"
        ]
    );

    // A new recovery arrives while the original summary awaits acknowledgment.
    // One retry delivers the same summary followed by that recovery in detail.
    visible.store(75, Ordering::SeqCst);
    fs::remove_file(reject).unwrap();
    collect(&home, &login, &icon).await.unwrap();
    assert_eq!(fs::read_to_string(&cursor).unwrap(), "75");
    let with_live = fs::read_to_string(&banners).unwrap();
    let accepted = with_live.strip_prefix(&first).unwrap();
    let live: Vec<_> = accepted
        .strip_prefix(&rejected)
        .expect("original summary retried")
        .lines()
        .collect();
    assert_eq!(live, banners_sent[1]);
    collect(&home, &login, &icon).await.unwrap();
    assert_eq!(fs::read_to_string(&banners).unwrap(), with_live);

    // Three fresh supported notices reach the threshold even within one page.
    visible.store(78, Ordering::SeqCst);
    collect(&home, &login, &icon).await.unwrap();
    let final_banners = fs::read_to_string(&banners).unwrap();
    let recent: Vec<_> = final_banners
        .strip_prefix(&with_live)
        .unwrap()
        .lines()
        .collect();
    assert_eq!(recent.len(), 7);
    assert_eq!(
        recent[5..],
        [
            "Gent activity",
            "2 Babysitter recoveries · 1 update installed"
        ]
    );
    assert_eq!(fs::read_to_string(&cursor).unwrap(), "78");
    save(&session, None).unwrap();
    fs::remove_file(&cursor).unwrap();
    collect(&home, &login, &icon).await.unwrap();
    assert!(!cursor.exists());
    assert_eq!(fs::read_to_string(banners).unwrap(), final_banners);
    server.abort();
}

#[test]
fn both_hosted_logins_resume_from_the_furthest_existing_cursor() -> Result<()> {
    let scratch = tempfile::tempdir()?;
    let home = scratch.path().join("node");
    gent_daemon::config::initialize(&home, "notifications")?;
    let mut login = Saved {
        version: 1,
        phase: Phase::Active,
        service: ACCOUNT.beta.into(),
        token: candidate()?,
        session: Some(ServiceSession {
            account_id: uuid::Uuid::new_v4().to_string(),
            github_subject: "1".into(),
            github_login: "fixture".into(),
            created_at: now()?,
            expires_at: now()? + 7200,
        }),
    };
    let (stable, legacy) = cursor_paths(&home, &login)?;
    let beta = legacy.context("missing beta cursor")?;
    Snapshot::read(&beta)?.write("23")?;
    Snapshot::read(&stable)?.write("12")?;
    login.service = DEFAULT_SERVICE.into();
    assert_eq!(
        cursor_paths(&home, &login)?,
        (stable.clone(), Some(beta.clone()))
    );
    assert_eq!(cursor_position(&stable, Some(&beta))?, 23);
    Snapshot::read(&stable)?.write("29")?;
    assert_eq!(cursor_position(&stable, Some(&beta))?, 29);
    login.service = STAGING_SERVICE.into();
    let (staging, legacy) = cursor_paths(&home, &login)?;
    assert!(legacy.is_none());
    assert_eq!(cursor_position(&staging, None)?, 0);
    Ok(())
}