agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
//! Herdr App space mutations share its versioned Core document.
use super::{OpenedWorkspace, Pane, Target};
use crate::core::{
    herdr::hc::{local_address, Core},
    project_worktrees,
    skill_store::SkillStore,
};
use anyhow::{bail, ensure, Context, Result};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::Mutex;

use super::hc::{desktop_directory, standalone_workspace_id};
use super::hc_layout::{terminal_addresses, terminal_tab, valid_id, DOCUMENT_NAME, SPACE_PREFIX};

pub(super) static EDIT: Mutex<()> = Mutex::new(());

#[derive(Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub(crate) enum SpaceAction {
    Create {
        project_id: String,
        path: Option<String>,
        name: String,
    },
    Rename {
        workspace_id: String,
        name: String,
    },
    Move {
        workspace_id: String,
        over_workspace_id: String,
    },
    Close {
        workspace_id: String,
        confirmed: bool,
    },
}

pub(super) struct Document {
    version: u64,
    value: Value,
}

impl Document {
    #[cfg(test)]
    pub(super) fn for_test(value: Value) -> Self {
        Self { version: 0, value }
    }

    pub(super) fn get(core: &Core) -> Result<Self> {
        let raw = core.call("doc.get", json!({"name": DOCUMENT_NAME}))?;
        let mut value = raw["value"].clone();
        if value.is_null() {
            value = json!({"spaces":[]});
        }
        ensure!(
            value["spaces"].is_array(),
            "Unsupported Herdr App workspace layout"
        );
        Ok(Self {
            version: raw["version"]
                .as_u64()
                .context("Herdr Core did not return a layout version")?,
            value,
        })
    }

    pub(super) fn spaces(&self) -> &[Value] {
        self.value["spaces"]
            .as_array()
            .map(Vec::as_slice)
            .unwrap_or_default()
    }

    pub(super) fn spaces_mut(&mut self) -> Result<&mut Vec<Value>> {
        self.value["spaces"]
            .as_array_mut()
            .context("Unsupported Herdr App workspace layout")
    }

    pub(super) fn index(&self, workspace: &str) -> Result<usize> {
        let id = workspace
            .strip_prefix(SPACE_PREFIX)
            .filter(|id| valid_id(id))
            .context("Select a Herdr App workspace")?;
        self.spaces()
            .iter()
            .position(|space| space["id"].as_str() == Some(id))
            .context("Herdr App workspace changed; refresh the sidebar")
    }

    fn rename(&mut self, workspace: &str, label: &str) -> Result<()> {
        let index = self.index(workspace)?;
        self.spaces_mut()?[index]["name"] = json!(name(label)?);
        Ok(())
    }

    fn move_to(&mut self, workspace: &str, anchor: &str) -> Result<bool> {
        let from = self.index(workspace)?;
        let to = self.index(anchor)?;
        if from == to {
            return Ok(false);
        }
        let spaces = self.spaces_mut()?;
        let moved = spaces.remove(from);
        spaces.insert(to, moved);
        Ok(true)
    }

    pub(super) fn save(&self, core: &Core) -> Result<()> {
        core.call(
            "doc.set",
            json!({
                "name": DOCUMENT_NAME, "version": self.version, "value": self.value
            }),
        )
        .context("Could not confirm the Herdr App layout update; refresh before retrying")?;
        Ok(())
    }

    /// Repeat only a document edit, never the terminal launch that preceded it.
    pub(super) fn update<T>(
        core: &Core,
        mut edit: impl FnMut(&mut Self) -> Result<(T, bool)>,
    ) -> Result<T> {
        let _guard = EDIT.lock().unwrap_or_else(|error| error.into_inner());
        let mut document = Self::get(core)?;
        for attempt in 0..3 {
            let (value, changed) = edit(&mut document)?;
            if !changed {
                return Ok(value);
            }
            match document.save(core) {
                Ok(()) => return Ok(value),
                Err(error) if attempt < 2 => {
                    let latest = Self::get(core)?;
                    if latest.version == document.version {
                        return Err(error);
                    }
                    document = latest;
                }
                Err(error) => return Err(error),
            }
        }
        unreachable!("every document edit either succeeds or reports its last failure")
    }
}

fn name(value: &str) -> Result<&str> {
    let name = value.trim();
    ensure!(
        name.chars().count() <= 80 && !name.chars().any(char::is_control),
        "Use a workspace name of up to 80 characters without control characters"
    );
    Ok(name)
}

fn space_terminals(space: &Value) -> HashSet<String> {
    let mut addresses = Vec::new();
    if let Some(tabs) = space["tabs"].as_array() {
        for tab in tabs {
            terminal_addresses(&tab["root"], &mut addresses);
        }
    }
    addresses
        .into_iter()
        .filter(|address| local_address(address))
        .collect()
}

pub(crate) fn manage(
    core: &Core,
    store: &SkillStore,
    action: SpaceAction,
) -> Result<Option<OpenedWorkspace>> {
    let _guard = EDIT.lock().unwrap_or_else(|error| error.into_inner());
    let mut document = Document::get(core)?;
    match action {
        SpaceAction::Create {
            project_id,
            path,
            name: label,
        } => {
            let label = name(&label)?;
            let folder = project_worktrees::directory(store, &project_id, path.as_deref())?;
            return create_space(core, document, project_id, &folder, label, None).map(Some);
        }
        SpaceAction::Rename {
            workspace_id,
            name: label,
        } => {
            document.rename(&workspace_id, &label)?;
            document.save(core)?;
        }
        SpaceAction::Move {
            workspace_id,
            over_workspace_id,
        } => {
            if document.move_to(&workspace_id, &over_workspace_id)? {
                document.save(core)?;
            }
        }
        SpaceAction::Close {
            workspace_id,
            confirmed,
        } => {
            ensure!(confirmed, "Closing a Herdr workspace requires confirmation");
            if workspace_id.starts_with(SPACE_PREFIX) {
                close(core, document, &workspace_id)?;
            } else {
                close_standalone(core, &document, &workspace_id)?;
            }
        }
    }
    Ok(None)
}

fn close_standalone(core: &Core, document: &Document, workspace: &str) -> Result<()> {
    let placed: HashSet<_> = document.spaces().iter().flat_map(space_terminals).collect();
    let snapshot = core.call("terminal.list", json!({}))?;
    let rows = snapshot["terminals"]
        .as_array()
        .context("Herdr Core did not return terminals")?;
    let candidates: Vec<_> = rows
        .iter()
        .filter_map(|row| {
            let address = row["address"].as_str()?;
            let identity = row["identity"].as_str()?;
            (local_address(address)
                && !identity.is_empty()
                && !placed.contains(address)
                && row["state"] == "live"
                && standalone_workspace_id(row).as_deref() == Some(workspace))
            .then_some((address, identity))
        })
        .collect();
    ensure!(
        !candidates.is_empty(),
        "Standalone workspace changed; refresh the sidebar"
    );
    let mut failures = Vec::new();
    for (address, identity) in candidates {
        let result = (|| -> Result<()> {
            let Some(row) = core.live_terminal(address)? else {
                return Ok(());
            };
            ensure!(
                row["identity"] == identity
                    && standalone_workspace_id(&row).as_deref() == Some(workspace)
                    && !Document::get(core)?
                        .spaces()
                        .iter()
                        .any(|space| space_terminals(space).contains(address)),
                "Terminal changed or joined a Herdr App space"
            );
            core.stop_terminal(address)
        })();
        if result.is_err() {
            failures.push(address);
        }
    }
    ensure!(
        failures.is_empty(),
        "Could not close these Core terminals: {}",
        failures.join(", ")
    );
    Ok(())
}

/// Open a worktree through the shared document. A standalone terminal can be
/// placed in a space without starting a second shell.
pub(super) fn open_worktree_space(
    core: &Core,
    project_id: &str,
    folder: &Path,
    existing: Option<&Pane>,
) -> Result<OpenedWorkspace> {
    let _guard = EDIT.lock().unwrap_or_else(|error| error.into_inner());
    let document = Document::get(core)?;
    create_space(core, document, project_id.to_owned(), folder, "", existing)
}

fn create_space(
    core: &Core,
    mut document: Document,
    project_id: String,
    folder: &Path,
    label: &str,
    existing: Option<&Pane>,
) -> Result<OpenedWorkspace> {
    let token = uuid::Uuid::new_v4().simple().to_string();
    let space_id = format!("sp{token}");
    let tab_id = format!("tb{token}");
    let pane_id = format!("p{token}");
    let terminal = if let Some(pane) = existing {
        let terminal = pane
            .pane_id
            .strip_prefix("hc:")
            .filter(|address| local_address(address))
            .context("The existing worktree terminal is unavailable; refresh and retry")?;
        ensure!(
            !document
                .spaces()
                .iter()
                .any(|space| space_terminals(space).contains(terminal)),
            "The worktree terminal now belongs to a shared space; refresh and retry"
        );
        let current = core.call("terminal.get", json!({"terminal": terminal}))?;
        let identity = current["identity"]
            .as_str()
            .context("Worktree terminal identity is unavailable")?;
        ensure!(
            current["state"] == "live"
                && pane.terminal_id == format!("hc:{identity}")
                && desktop_directory(&current).as_deref() == Some(folder),
            "The worktree terminal or its checkout changed; refresh and retry"
        );
        terminal.to_owned()
    } else {
        core.run(
            folder,
            &[],
            None,
            json!({"agenthub.checkout": folder, "herdr.space": space_id, "herdr.tab": tab_id}),
            json!({}),
        )?
    };
    document.spaces_mut()?.push(json!({
        "id": space_id, "name": label, "folder": folder,
        "tabs": [terminal_tab(&tab_id, &pane_id, "", &terminal)]
    }));
    document.save(core).map_err(|error| {
        anyhow::anyhow!("{error:#}. The shell is available in Standalone Core workspaces")
    })?;
    let session = core.session_key();
    let snapshot = core.snapshot(&session)?;
    let selected = snapshot
        .panes
        .iter()
        .find(|pane| {
            pane.pane_id == format!("hc:{terminal}")
                && pane.workspace_id == format!("{SPACE_PREFIX}{space_id}")
        })
        .context("The workspace was created; refresh to open its terminal")?;
    Ok(OpenedWorkspace {
        project_id,
        path: folder.to_string_lossy().into_owned(),
        target: Target::from_pane(&session, selected),
    })
}

fn close(core: &Core, mut document: Document, workspace: &str) -> Result<()> {
    let index = document.index(workspace)?;
    let removed = document.spaces_mut()?.remove(index);
    let shared: HashSet<_> = document.spaces().iter().flat_map(space_terminals).collect();
    let closing = space_terminals(&removed);
    let snapshot = core.call("terminal.list", json!({}))?;
    let rows = snapshot["terminals"]
        .as_array()
        .context("Herdr Core did not return terminals")?;
    let candidates: HashMap<_, _> = rows
        .iter()
        .filter(|row| row["state"] == "live")
        .filter_map(|row| Some((row["address"].as_str()?, row["identity"].as_str()?)))
        .filter(|(address, identity)| {
            !identity.is_empty() && closing.contains(*address) && !shared.contains(*address)
        })
        .collect();

    // A failed version check leaves the document and its programs untouched.
    document.save(core)?;
    let mut failures = Vec::new();
    for (address, identity) in candidates {
        let stopped = (|| -> Result<()> {
            let Some(row) = core.live_terminal(address)? else {
                return Ok(());
            };
            ensure!(row["identity"] == identity, "Terminal identity changed");
            core.stop_terminal(address)
        })();
        if stopped.is_err() {
            failures.push(address);
        }
    }
    if !failures.is_empty() {
        failures.sort_unstable();
        bail!(
            "Workspace removed; check these terminals in Standalone Core workspaces: {}",
            failures.join(", ")
        );
    }
    Ok(())
}

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