gent-link 0.2.2

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
//! Resolve the presenter only in a graphical session, separately from the headless CLI.
use crate::build_info;
use anyhow::{Context, Result, ensure};
use gent_daemon::config;
use sha2::{Digest, Sha256};
use std::{
    env, fs,
    io::Write,
    os::unix::fs::{MetadataExt, PermissionsExt},
    path::{Path, PathBuf},
    process::Stdio,
    time::Duration,
};
use tokio::process::Command;

#[path = "../desktop_build.rs"]
mod desktop_build;
mod release;

const SOURCES: &[(&str, &[u8])] = include!(concat!(env!("OUT_DIR"), "/gent_desktop_sources.rs"));

fn cache_root(runtime: &Path) -> Result<PathBuf> {
    let cache = env::var_os("XDG_CACHE_HOME")
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
        .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache")))
        .context("cannot locate the Gent Desktop cache")?;
    fs::create_dir_all(&cache)?;
    let meta = fs::metadata(&cache)?;
    let uid = rustix::process::geteuid().as_raw();
    if !meta.is_dir() || meta.uid() != uid || meta.mode() & 0o022 != 0 {
        // The node's private runtime directory is also available on shared-cache installations.
        return Ok(runtime.join("desktop-cache"));
    }
    let gent = cache.join("gent");
    config::private_dir(&gent)?;
    Ok(gent.join("desktop"))
}

fn source_key() -> String {
    let mut digest = Sha256::new();
    for (path, bytes) in SOURCES {
        digest.update(path.as_bytes());
        digest.update([0]);
        digest.update(bytes.len().to_be_bytes());
        digest.update(bytes);
    }
    format!("{:x}", digest.finalize())
}

async fn matching(binary: &Path, revision: &str) -> bool {
    let Ok(meta) = fs::symlink_metadata(binary) else {
        return false;
    };
    if !meta.is_file()
        || meta.mode() & 0o022 != 0
        || (meta.uid() != rustix::process::geteuid().as_raw() && meta.uid() != 0)
    {
        return false;
    }
    let probe = Command::new(binary)
        .arg("--gent-revision")
        .kill_on_drop(true)
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output();
    matches!(tokio::time::timeout(Duration::from_secs(5), probe).await,
        Ok(Ok(result)) if result.status.success()
            && result.stdout.strip_suffix(b"\n") == Some(revision.as_bytes()))
}

fn from_source(work: &Path, target: &str, revision: &str) -> Result<PathBuf> {
    let source = work.join("source");
    for (name, contents) in SOURCES {
        let path = source.join(name);
        fs::create_dir_all(path.parent().context("missing source directory")?)?;
        fs::write(path, contents)?;
    }
    desktop_build::build(&source, &work.join("build"), target, revision).context(
        "could not build the bundled Gent Desktop; install the Linux development packages listed in docs/desktop.md",
    )
}

pub(super) async fn presenter(runtime: &Path) -> Result<PathBuf> {
    let build = build_info::current();
    let sibling = env::current_exe()?.with_file_name("gent-desktop");
    if sibling.is_file() && matching(&sibling, &build.commit).await {
        return Ok(sibling);
    }

    // Unreleased working trees can share a Git HEAD but contain different UI sources.
    let key = if build.dirty || !build_info::valid_commit(&build.commit) {
        format!("{}-{}", build.commit, source_key())
    } else {
        build.commit.clone()
    };
    let directory = cache_root(runtime)?.join(key).join(&build.target);
    config::private_dir(&directory)?;
    let binary = directory.join("gent-desktop");
    if binary.is_file() && matching(&binary, &build.commit).await {
        return Ok(binary);
    }
    // Different node profiles can share the same downloaded presenter.
    let _lock = loop {
        match config::state_lock(&directory, "install.lock") {
            Ok(lock) => break lock,
            Err(error)
                if error
                    .downcast_ref::<std::io::Error>()
                    .is_some_and(|e| e.kind() == std::io::ErrorKind::WouldBlock) =>
            {
                tokio::time::sleep(Duration::from_secs(1)).await;
            }
            Err(error) => return Err(error),
        }
    };
    if binary.is_file() && matching(&binary, &build.commit).await {
        return Ok(binary);
    }

    let work = tempfile::tempdir_in(&directory)?;
    let mut candidate = tempfile::NamedTempFile::new_in(&directory)?;
    let released = !build.dirty
        && build_info::valid_commit(&build.commit)
        && release::download(&build, candidate.as_file_mut()).await?;
    if !released {
        let target = build.target.clone();
        let revision = build.commit.clone();
        let (built, _work) = tokio::task::spawn_blocking(move || {
            from_source(work.path(), &target, &revision).map(|path| (path, work))
        })
        .await??;
        std::io::copy(&mut fs::File::open(built)?, candidate.as_file_mut())?;
    }
    activate(candidate, &binary, &build.commit).await?;
    Ok(binary)
}

async fn activate(
    mut candidate: tempfile::NamedTempFile,
    binary: &Path,
    revision: &str,
) -> Result<()> {
    candidate.flush()?;
    candidate
        .as_file()
        .set_permissions(fs::Permissions::from_mode(0o700))?;
    candidate.as_file().sync_all()?;
    // Close the writable descriptor before exec (ETXTBSY on Linux).
    let candidate = candidate.into_temp_path();
    ensure!(
        matching(&candidate, revision).await,
        "Gent Desktop could not report the installed revision; check WebKitGTK 4.1 and the Linux runtime packages in docs/desktop.md"
    );
    candidate.persist(binary)?;
    fs::File::open(binary.parent().context("missing cache directory")?)?.sync_all()?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn activate_only_a_presenter_that_reports_the_expected_revision() {
        let cache = tempfile::tempdir().unwrap();
        let binary = cache.path().join("gent-desktop");
        fs::write(&binary, b"previous installation").unwrap();
        let revision = "b".repeat(40);
        for advertised in ["a".repeat(40), revision.clone()] {
            let mut candidate = tempfile::NamedTempFile::new_in(cache.path()).unwrap();
            writeln!(
                candidate,
                "#!/bin/sh\ntest \"$1\" = --gent-revision && echo {advertised}"
            )
            .unwrap();
            let result = activate(candidate, &binary, &revision).await;
            if advertised == revision {
                result.unwrap();
                assert!(matching(&binary, &revision).await);
            } else {
                assert!(result.is_err());
                assert_eq!(fs::read(&binary).unwrap(), b"previous installation");
            }
        }
    }
}