agent-ssh 0.3.0

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
use std::{collections::BTreeMap, env, path::PathBuf};

use anyhow::{Context, Result};
use serde::Serialize;

use crate::{
    config::Host,
    grid::{Step, grid_steps},
};

pub const SSH_EXE: &str = r"C:\Windows\System32\OpenSSH\ssh.exe";
const BASE_PROFILE: &str = "SSH";
const BASE_GUID: &str = "{a1f0c2b4-5e6d-4f70-9c8a-55e1a2b3c4d5}";
const ICON: &str = "\u{e968}";

#[derive(Serialize)]
pub struct Fragment {
    profiles: Vec<Profile>,
    actions: Vec<Action>,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Profile {
    #[serde(skip_serializing_if = "Option::is_none")]
    guid: Option<String>,
    name: String,
    commandline: String,
    icon: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    tab_title: Option<String>,
    close_on_exit: String,
    suppress_application_title: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    tab_color: Option<String>,
}

#[derive(Serialize)]
struct Action {
    id: String,
    name: String,
    command: MultipleActions,
}

#[derive(Serialize)]
struct MultipleActions {
    action: &'static str,
    actions: Vec<BTreeMap<String, serde_json::Value>>,
}

pub fn fragment_path() -> Result<PathBuf> {
    let local = env::var_os("LOCALAPPDATA").context("LOCALAPPDATA is not set")?;
    Ok(PathBuf::from(local).join("Microsoft/Windows Terminal/Fragments/SSH/ssh-sessions.json"))
}

pub fn pane_args(host: &Host) -> Vec<String> {
    let profile = if host.group == "adhoc" {
        BASE_PROFILE
    } else {
        &host.name
    };
    let mut args = vec![
        "-p".into(),
        profile.into(),
        "--title".into(),
        host.name.clone(),
    ];
    if let Some(color) = &host.color {
        args.extend(["--tabColor".into(), color.clone()]);
    }
    if host.group == "adhoc" {
        args.extend([SSH_EXE.into(), host.name.clone()]);
    }
    args
}

pub fn generate_fragment(hosts: &[Host]) -> Fragment {
    let mut profiles = vec![Profile {
        guid: Some(BASE_GUID.into()),
        name: BASE_PROFILE.into(),
        commandline: SSH_EXE.into(),
        icon: ICON.into(),
        tab_title: None,
        close_on_exit: "automatic".into(),
        suppress_application_title: true,
        tab_color: None,
    }];
    profiles.extend(hosts.iter().map(|host| Profile {
        guid: None,
        name: host.name.clone(),
        commandline: format!("{SSH_EXE} {}", host.name),
        icon: ICON.into(),
        tab_title: Some(host.name.clone()),
        close_on_exit: "automatic".into(),
        suppress_application_title: true,
        tab_color: host.color.clone(),
    }));

    let groups: BTreeMap<_, Vec<_>> =
        hosts
            .iter()
            .fold(BTreeMap::<String, Vec<Host>>::new(), |mut groups, host| {
                groups
                    .entry(host.group.clone())
                    .or_default()
                    .push(host.clone());
                groups
            });
    let actions = groups
        .into_iter()
        .map(|(group, members)| {
            let actions = grid_steps(&members).into_iter().map(step_json).collect();
            Action {
                id: format!("User.SshGrid.{group}"),
                name: format!("SSH grid: {group} ({} hosts)", members.len()),
                command: MultipleActions {
                    action: "multipleActions",
                    actions,
                },
            }
        })
        .collect();
    Fragment { profiles, actions }
}

fn step_json(step: Step<'_>) -> BTreeMap<String, serde_json::Value> {
    let mut value = BTreeMap::new();
    match step {
        Step::New(host) => {
            value.insert("action".into(), "newTab".into());
            add_host(&mut value, host);
        }
        Step::Split {
            direction,
            size,
            target,
        } => {
            value.insert("action".into(), "splitPane".into());
            value.insert("split".into(), direction.json_name().into());
            value.insert(
                "size".into(),
                serde_json::json!((size * 10_000.0).round() / 10_000.0),
            );
            add_host(&mut value, target);
        }
        Step::FocusLeft => {
            value.insert("action".into(), "moveFocus".into());
            value.insert("direction".into(), "left".into());
        }
    }
    value
}

fn add_host(value: &mut BTreeMap<String, serde_json::Value>, host: &Host) {
    // Use the host-specific profile so duplicate/reopen operations retain the SSH destination.
    value.insert("profile".into(), host.name.clone().into());
    value.insert("tabTitle".into(), host.name.clone().into());
    if let Some(color) = &host.color {
        value.insert("tabColor".into(), color.clone().into());
    }
}

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

    #[test]
    fn grid_actions_use_host_profile_without_command_override() {
        let hosts = vec![Host {
            name: "example-admin".into(),
            group: "production".into(),
            color: Some("#E57000".into()),
        }];
        let json = serde_json::to_value(generate_fragment(&hosts)).unwrap();
        let pane = &json["actions"][0]["command"]["actions"][0];
        assert_eq!(pane["profile"], "example-admin");
        assert!(pane.get("commandline").is_none());
    }
}