agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
//! One-way import of live legacy Herdr layouts into the shared Herdr App document.
use super::{
    hc::{checkout, desktop_directory},
    hc_layout::{terminal_addresses, SPACE_PREFIX},
    hc_management::{Document, EDIT},
    HerdrControl, Snapshot,
};
use crate::core::herdr::hc::{local_address, Core};
use anyhow::{ensure, Context, Result};
use serde::Serialize;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::{
    collections::{HashMap, HashSet},
    path::{Path, PathBuf},
};

const IMPORT: &str = "agenthub.tui";
const TAB_LABEL: &str = "agenthub.tui_tab";

#[derive(Default, Serialize)]
pub(crate) struct SyncResult {
    sessions: usize,
    imported: usize,
    merged: usize,
    tabs: usize,
    skipped: usize,
}

pub(crate) fn sync_legacy(legacy: &HerdrControl, core: &Core) -> Result<SyncResult> {
    let mut sources = Vec::new();
    for session in legacy
        .sessions()?
        .into_iter()
        .filter(|session| session.running)
    {
        let snapshot = legacy
            .snapshot(&session.name)
            .with_context(|| format!("Could not read Herdr TUI session {}", session.name))?;
        sources.push((session.name, snapshot));
    }
    if sources.is_empty() {
        return Ok(SyncResult::default());
    }

    let _guard = EDIT.lock().unwrap_or_else(|error| error.into_inner());
    let mut document = Document::get(core)?;
    let live = core.snapshot(&core.session_key())?;
    let terminals = core.call("terminal.list", json!({}))?;
    let result = merge(&mut document, &live, &terminals, &sources)?;
    if result.tabs > 0 {
        document.save(core)?;
    }
    Ok(result)
}

fn valid_folder(path: &str) -> Option<PathBuf> {
    let path = Path::new(path);
    if !path.is_absolute() {
        return None;
    }
    path.canonicalize().ok().filter(|path| path.is_dir())
}

fn canonical_checkout(path: &str) -> Option<PathBuf> {
    valid_folder(path).and_then(|path| checkout(path.to_str()?))
}

fn import_key(session: &str, workspace: &str, tab: &str, directory: &Path) -> String {
    let mut hash = Sha256::new();
    for value in [session, workspace, tab, &directory.to_string_lossy()] {
        hash.update((value.len() as u64).to_le_bytes());
        hash.update(value.as_bytes());
    }
    hex::encode(hash.finalize())
}

fn display_name(name: &str) -> String {
    name.chars()
        .filter(|character| !character.is_control())
        .take(80)
        .collect()
}

fn merge(
    document: &mut Document,
    live: &Snapshot,
    terminals: &Value,
    sources: &[(String, Snapshot)],
) -> Result<SyncResult> {
    let mut result = SyncResult {
        sessions: sources.len(),
        ..SyncResult::default()
    };
    let current: HashMap<_, _> = live
        .workspaces
        .iter()
        .filter_map(|space| {
            let id = space.workspace_id.strip_prefix(SPACE_PREFIX)?;
            Some((id, canonical_checkout(space.directory.as_deref()?)?))
        })
        .collect();
    let standalone: HashSet<_> = live
        .panes
        .iter()
        .filter(|pane| !pane.workspace_id.starts_with(SPACE_PREFIX))
        .filter_map(|pane| {
            pane.pane_id
                .strip_prefix("hc:")
                .filter(|address| local_address(address))
        })
        .collect();
    let mut reusable = HashMap::new();
    for row in terminals["terminals"].as_array().into_iter().flatten() {
        if let Some(address) = row["address"]
            .as_str()
            .filter(|address| standalone.contains(address))
        {
            if row["state"] == "live" {
                if let Some(folder) =
                    desktop_directory(row).and_then(|path| canonical_checkout(path.to_str()?))
                {
                    reusable.entry(folder).or_insert(address.to_owned());
                }
            }
        }
    }
    let mut by_checkout = HashMap::new();
    let mut known = HashSet::new();
    let spaces = document.spaces_mut()?;
    for (index, space) in spaces.iter().enumerate() {
        if let Some(folder) = space["id"]
            .as_str()
            .and_then(|id| current.get(id).cloned())
            .or_else(|| space["folder"].as_str().and_then(canonical_checkout))
        {
            by_checkout.entry(folder).or_insert(index);
        }
        if let Some(tabs) = space["tabs"].as_array() {
            known.extend(
                tabs.iter()
                    .filter_map(|tab| tab[IMPORT]["key"].as_str())
                    .map(str::to_owned),
            );
        }
    }

    for (session, snapshot) in sources {
        for workspace in &snapshot.workspaces {
            let Some(folder) = workspace.directory.as_deref().and_then(canonical_checkout) else {
                result.skipped += 1;
                continue;
            };
            let tabs: Vec<_> = snapshot
                .tabs
                .iter()
                .filter(|tab| tab.workspace_id == workspace.workspace_id)
                .collect();
            let mut added = Vec::new();
            for (position, tab) in tabs.iter().enumerate() {
                let cwd = snapshot
                    .panes
                    .iter()
                    .filter(|pane| {
                        pane.tab_id == tab.tab_id && pane.workspace_id == workspace.workspace_id
                    })
                    .filter_map(|pane| pane.cwd.as_deref().and_then(valid_folder))
                    .find(|cwd| {
                        canonical_checkout(&cwd.to_string_lossy()).as_ref() == Some(&folder)
                    })
                    .unwrap_or_else(|| folder.clone());
                let key = import_key(session, &workspace.workspace_id, &tab.tab_id, &folder);
                if !known.insert(key.clone()) {
                    continue;
                }
                let tab_label = if tab.label.trim().is_empty() {
                    (position + 1).to_string()
                } else {
                    tab.label.clone()
                };
                let label = if session == super::super::session::SESSION {
                    tab_label
                } else {
                    format!("{session} · {tab_label}")
                };
                added.push(imported_tab(
                    &key,
                    session,
                    &workspace.workspace_id,
                    &cwd,
                    &label,
                ));
            }
            if tabs.is_empty() {
                let key = import_key(session, &workspace.workspace_id, "", &folder);
                if known.insert(key.clone()) {
                    added.push(imported_tab(
                        &key,
                        session,
                        &workspace.workspace_id,
                        &folder,
                        session,
                    ));
                }
            }
            if added.is_empty() {
                result.skipped += 1;
                continue;
            }
            result.tabs += added.len();
            let target = by_checkout.get(&folder).copied();
            let has_terminal = target.is_some_and(|index| {
                spaces[index]["tabs"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .any(|tab| !addresses(tab).is_empty())
            });
            if !has_terminal {
                if let Some(address) = reusable.remove(&folder) {
                    let tab_id = added[0]["id"]
                        .as_str()
                        .context("Imported tab id is unavailable")?;
                    added[0]["root"] = terminal_root(tab_id, &address);
                }
            }
            if let Some(index) = target {
                if spaces[index]["tabs"].is_null() {
                    spaces[index]["tabs"] = json!([]);
                }
                let tabs = spaces[index]["tabs"]
                    .as_array_mut()
                    .context("Unsupported Herdr App tabs")?;
                tabs.extend(added);
                result.merged += 1;
            } else {
                by_checkout.insert(folder.clone(), spaces.len());
                let name = display_name(&workspace.label);
                spaces.push(json!({
                    "id": format!("sp{}", uuid::Uuid::new_v4().simple()),
                    "name": name, "folder": folder, "tabs": added,
                }));
                result.imported += 1;
            }
        }
    }
    Ok(result)
}

fn imported_tab(key: &str, session: &str, workspace: &str, cwd: &Path, label: &str) -> Value {
    let tab_id = format!("tb{}", uuid::Uuid::new_v4().simple());
    json!({
        "id": tab_id, "name": display_name(label),
        "root": {"id": tab_id, "type": "row", "children": []},
        (IMPORT): {"key":key, "session":session, "workspace":workspace, "cwd":cwd}
    })
}

fn addresses(tab: &Value) -> Vec<String> {
    let mut frames = Vec::new();
    terminal_addresses(&tab["root"], &mut frames);
    frames
}

/// Opening a workspace is the only migration action that can start shells.
pub(super) fn restore_tabs(core: &Core, workspace: &str) -> Result<bool> {
    if !workspace.starts_with(SPACE_PREFIX) {
        return Ok(false);
    }
    let _guard = EDIT.lock().unwrap_or_else(|error| error.into_inner());
    let mut document = Document::get(core)?;
    let index = document.index(workspace)?;
    let space = &document.spaces()[index];
    let mut occupied = false;
    let pending: Vec<_> = space["tabs"]
        .as_array()
        .into_iter()
        .flatten()
        .enumerate()
        .filter_map(|(index, tab)| {
            let frames = addresses(tab);
            if !frames.is_empty() {
                occupied = true;
                return None;
            }
            let key = tab[IMPORT]["key"].as_str()?;
            if key.len() != 64 || !key.bytes().all(|b| b.is_ascii_hexdigit()) {
                return None;
            }
            let tab_id = tab["id"].as_str()?;
            let cwd = tab[IMPORT]["cwd"].as_str().and_then(valid_folder)?;
            Some((index, key.to_owned(), tab_id.to_owned(), cwd))
        })
        .collect();
    if pending.is_empty() {
        return Ok(false);
    }
    let space_id = space["id"]
        .as_str()
        .context("Herdr App space identity unavailable")?
        .to_owned();
    let layout_folder = space["folder"].as_str().and_then(canonical_checkout);
    let mut used: HashSet<_> = document
        .spaces()
        .iter()
        .flat_map(|space| space["tabs"].as_array().into_iter().flatten())
        .flat_map(addresses)
        .collect();
    let live = core.call("terminal.list", json!({}))?;
    let rows = live["terminals"]
        .as_array()
        .context("Herdr Core did not return terminals")?;
    let tabs = document.spaces_mut()?[index]["tabs"]
        .as_array_mut()
        .context("Unsupported Herdr App tabs")?;
    for (index, key, tab_id, cwd) in pending {
        let actual_checkout = canonical_checkout(&cwd.to_string_lossy());
        ensure!(
            actual_checkout.is_some(),
            "The imported tab directory is unavailable"
        );
        let find = |require_key: bool| {
            rows.iter().find_map(|row| {
                let address = row["address"]
                    .as_str()
                    .filter(|address| local_address(address))?;
                if row["state"] != "live" || used.contains(address) {
                    return None;
                }
                let same_tag = row["labels"][TAB_LABEL].as_str() == Some(key.as_str());
                let matches_checkout = desktop_directory(row)
                    .and_then(|path| canonical_checkout(path.to_str()?))
                    == actual_checkout;
                (matches_checkout && (!require_key || same_tag)).then(|| address.to_owned())
            })
        };
        let terminal = match find(true).or_else(|| {
            (!occupied && actual_checkout == layout_folder).then(|| find(false)).flatten()
        }) {
            Some(address) => address,
            None => core.run(
                &cwd,
                &[],
                Some(&format!("import-{}", &key[..24])),
                json!({"agenthub.checkout": cwd, "herdr.space": space_id, "herdr.tab": tab_id, (TAB_LABEL): key}),
                json!({}),
            )?,
        };
        occupied = true;
        used.insert(terminal.clone());
        tabs[index]["root"] = terminal_root(&tab_id, &terminal);
    }
    document.save(core)?;
    Ok(true)
}

fn terminal_root(tab: &str, terminal: &str) -> Value {
    json!({
        "id":tab, "type":"row", "children":[{
            "id":format!("p{}", uuid::Uuid::new_v4().simple()),
            "type":"block","content":{"terminal":terminal}
        }]
    })
}

#[cfg(test)]
#[path = "hc_migration_tests.rs"]
mod tests;