Skip to content

Ghidrust provides a hyper fast, AI native reverse engineering platform built in Rust, inspired by Ghidra. Includes experimental GPU kernels to rapidly decompile large files, a decryption suite, and network monitor for packet to binary reverse engineering.

15.9 KB
Raw Blame
//! Grok Build pane — hosts the real Grok TUI via an in-tree PTY (`grok_term`).
//!
//! Thin glue only: find/install `grok`, write MCP + skill + context files, then
//! spawn the binary in the project directory. Slash commands, models, /goal,
//! sessions — all come from Grok itself.

use crate::grok_term::{self, GrokTermSession};
use eframe::egui::{self, Color32, RichText, Ui};
use ghidrust_agent::{
    ensure_project_skill, grok_binary_path, install_command_for_platform,
    register_mcp_with_grok_cli, start_checklist, write_project_mcp_config, ProgramFacts,
    SystemPromptBuilder,
};
use std::path::{Path, PathBuf};

/// Which tab of the bottom dock is currently active.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BottomTab {
    /// Embedded Grok Build TUI (default).
    #[default]
    Grok,
    /// Plain analyzer / script Console.
    Console,
}

/// Per-project Grok pane state.
pub struct GrokPaneState {
    pub tab: BottomTab,
    /// Live PTY session running `grok`.
    pub session: Option<GrokTermSession>,
    pub grok_bin: Option<PathBuf>,
    pub last_error: Option<String>,
    pub install_status: Option<String>,
    pub version_probe: Option<String>,
    /// Status line under the toolbar (e.g. "session ended").
    pub status: Option<String>,
    /// True while the embedded TUI owns the keyboard — listing hotkeys (G, L, …)
    /// must not fire.
    pub keyboard_captured: bool,
    /// Set after Start/Restart so the next paint focuses the terminal.
    pub request_term_focus: bool,
    /// Project root we last attempted to auto-wire skill for (avoids per-frame retries).
    pub skill_wired_root: Option<PathBuf>,
    /// Fail-loud skill wire error (shown above the checklist when auto-install fails).
    pub skill_wire_error: Option<String>,
    /// Start checklist drawer open (pre-session only; hidden once Grok runs).
    pub checklist_drawer_open: bool,
}

impl GrokPaneState {
    pub fn new() -> Self {
        Self {
            tab: BottomTab::Grok,
            session: None,
            grok_bin: grok_binary_path(),
            last_error: None,
            install_status: None,
            version_probe: None,
            status: None,
            keyboard_captured: false,
            request_term_focus: false,
            skill_wired_root: None,
            skill_wire_error: None,
            checklist_drawer_open: true,
        }
    }

    pub fn refresh_grok_binary(&mut self) {
        self.grok_bin = grok_binary_path();
    }

    pub fn stop_session(&mut self) {
        self.session = None;
        self.keyboard_captured = false;
        self.request_term_focus = false;
        self.status = Some("Grok session stopped.".into());
    }

    /// Poll child exit each frame.
    pub fn poll(&mut self) {
        if let Some(sess) = &mut self.session {
            if sess.poll_exited() {
                self.session = None;
                self.status =
                    Some("Grok exited. Click Start / Restart to open a new TUI session.".into());
            }
        }
    }
}

impl Default for GrokPaneState {
    fn default() -> Self {
        Self::new()
    }
}

/// Write MCP + skill + Ghidrust context, then spawn the Grok TUI in a PTY.
pub fn start_pty_session(
    grok_bin: &Path,
    project_root: &Path,
    ghidrust_bin: &Path,
    skill_source: Option<&Path>,
    facts: &ProgramFacts,
    ctx: egui::Context,
    cols: u16,
    rows: u16,
) -> Result<GrokTermSession, String> {
    write_project_mcp_config(project_root, ghidrust_bin).map_err(|e| e.to_string())?;
    // Best-effort CLI registry sync (files above are the source of truth).
    let _ = register_mcp_with_grok_cli(grok_bin, project_root, ghidrust_bin);
    // Fail-loud skill: prefer disk source, else embedded SKILL.md (release installs).
    ensure_project_skill(project_root, skill_source).map_err(|e| {
        let dest = ghidrust_agent::project_skill_path(project_root);
        format!(
            "skill write failed ({e}); expected destination {}",
            dest.display()
        )
    })?;
    write_ghidrust_agent_files(project_root, facts)?;
    // Checklist is fail-loud in the Grok pane UI (red rows); do not abort Start
    // after files were written — agents still need the TUI.
    let _ = start_checklist(project_root);

    GrokTermSession::start(
        grok_bin.to_path_buf(),
        project_root.to_path_buf(),
        cols,
        rows,
        ctx,
    )
}

/// Persist identity + live program facts for the Grok TUI to load from disk.
fn write_ghidrust_agent_files(project_root: &Path, facts: &ProgramFacts) -> Result<(), String> {
    let grok_dir = project_root.join(".grok");
    std::fs::create_dir_all(&grok_dir).map_err(|e| e.to_string())?;

    let context = SystemPromptBuilder::new("")
        .facts(facts)
        .read_only_note(false)
        .airgap_note(false)
        .build();
    std::fs::write(grok_dir.join("ghidrust-context.md"), &context).map_err(|e| e.to_string())?;

    // AGENTS.md — Grok Build reads this on session start in the project cwd.
    let agents = format!(
        "# Ghidrust agent\n\n\
         You are Ghidrust's in-GUI reverse-engineering copilot.\n\
         The user is running Ghidrust with a project open at this working directory.\n\
         Use the `ghidrust` MCP server (see `.grok/mcp.json`) for all analysis — \
         never invent addresses, symbols, or decompile output.\n\
         Read `.grok/ghidrust-context.md` for live program facts and \
         `.grok/skills/ghidrust/SKILL.md` for the full tool catalog.\n\n\
         If a project file has saved analysis but nothing is loaded in the GUI, \
         say so and use MCP `load` with `project` + `file_id` (or absolute `path`) \
         from the facts JSON — never invent addresses.\n"
    );
    std::fs::write(project_root.join("AGENTS.md"), agents).map_err(|e| e.to_string())?;
    Ok(())
}

/// Render the Grok tab: toolbar + embedded TUI (or empty / error state).
pub fn render_grok_pane(
    ui: &mut Ui,
    state: &mut GrokPaneState,
    project_root: Option<&Path>,
    primary: Color32,
    muted: Color32,
    on_start: &mut dyn FnMut(u16, u16) -> Result<(), String>,
    on_install: &mut dyn FnMut(),
    on_rescan: &mut dyn FnMut(),
    on_probe: &mut dyn FnMut(),
) {
    ui.horizontal_wrapped(|ui| {
        ui.label(RichText::new("Grok").color(primary).strong());
        if let Some(sess) = &state.session {
            ui.small(RichText::new(format!("TUI · {}", sess.project_root.display())).color(muted));
        } else if let Some(bin) = &state.grok_bin {
            ui.small(RichText::new(format!("grok: {}", bin.display())).color(muted));
        } else {
            ui.small(
                RichText::new("grok binary not found on PATH")
                    .color(Color32::from_rgb(0xFB, 0xC0, 0x2D)),
            );
        }

        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            if state.session.is_some() {
                if ui.button("Stop").clicked() {
                    state.stop_session();
                }
                if ui.button("Restart").clicked() {
                    state.stop_session();
                    let (cols, rows) = (100u16, 28u16);
                    match on_start(cols, rows) {
                        Ok(()) => {
                            state.status = None;
                            state.checklist_drawer_open = false;
                        }
                        Err(e) => {
                            state.last_error = Some(e);
                        }
                    }
                }
            } else {
                if ui
                    .add_enabled(state.grok_bin.is_some(), egui::Button::new("Start"))
                    .clicked()
                {
                    let (cols, rows) = (100u16, 28u16);
                    match on_start(cols, rows) {
                        Ok(()) => {
                            state.last_error = None;
                            state.status = None;
                            // Drawer vanishes with the session; keep it closed for Stop.
                            state.checklist_drawer_open = false;
                        }
                        Err(e) => state.last_error = Some(e),
                    }
                }
                if state.grok_bin.is_none() && ui.button("Install Grok Build…").clicked() {
                    on_install();
                }
                if ui.button("Re-scan for grok").clicked() {
                    on_rescan();
                }
                if state.grok_bin.is_some() && ui.button("Probe version").clicked() {
                    on_probe();
                }
            }
        });
    });

    if let Some(v) = &state.version_probe {
        ui.small(RichText::new(format!("version: {v}")).color(muted));
    }
    if let Some(err) = &state.last_error {
        ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), err);
    }
    if let Some(status) = &state.install_status {
        ui.small(RichText::new(status).color(muted));
    }
    if let Some(status) = &state.status {
        ui.small(RichText::new(status).color(muted).italics());
    }

    ui.separator();

    // Pre-session only: auto-wire skill + Start checklist drawer. Once Grok is
    // running the drawer disappears so the TUI owns the pane.
    if let Some(root) = project_root {
        // Auto-place embedded skill as soon as a project is visible in the Grok
        // pane (not only on Start). Idempotent; fail-loud on write errors.
        ensure_skill_for_project(state, root, None);
        if state.session.is_none() {
            if let Some(err) = &state.skill_wire_error {
                ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), err);
            }
            render_start_checklist_drawer(ui, state, root, muted);
            ui.separator();
        }
    }

    if state.session.is_none() {
        state.keyboard_captured = false;
        ui.small(
            RichText::new(
                "Start embeds the real Grok Build TUI here (slash commands, /goal, /model, \
                 sessions). Opening a project auto-installs `.grok/skills/ghidrust/SKILL.md` \
                 from the embedded skill; Start also wires MCP, AGENTS.md, and context.",
            )
            .color(muted),
        );
        ui.allocate_space(ui.available_size());
        return;
    }

    let want_focus = state.request_term_focus;
    let sticky = state.keyboard_captured;
    if let Some(sess) = state.session.as_mut() {
        let capturing = grok_term::show_terminal(ui, sess, want_focus, sticky);
        // Sticky while the TUI session lives: once Start focuses the terminal,
        // keep Ctrl+C / keys routed here until Stop or Console tab.
        state.keyboard_captured = capturing || sticky || want_focus;
        if want_focus {
            state.request_term_focus = false;
        }
    }
}

/// One fail-loud row in the Start checklist (mcp / skill / agents / context).
pub struct StartChecklistRow {
    pub label: String,
    pub ok: bool,
    pub detail: String,
}

fn checklist_label(id: &str) -> &'static str {
    match id {
        "mcp" => "MCP config",
        "mcp_grok" => "MCP config (.grok)",
        "skill" => "Skill",
        "skill_hash" => "Skill hash",
        "agents" => "Agents (AGENTS.md)",
        "context" => "Context",
        _ => "Check",
    }
}

/// Verify the on-disk artifacts project-open / Start write actually exist —
/// fail-loud rather than silently trusting that wiring succeeded.
pub fn pane_start_checklist(project_root: &Path) -> Vec<StartChecklistRow> {
    start_checklist(project_root)
        .into_iter()
        // Hash is included in the Skill detail string; skip the extra row.
        .filter(|item| item.id != "skill_hash")
        .map(|item| StartChecklistRow {
            label: checklist_label(item.id).into(),
            ok: item.ok,
            detail: item.detail,
        })
        .collect()
}

/// Ensure `.grok/skills/ghidrust/SKILL.md` exists for `project_root`.
///
/// Called on project open and again from the Grok pane (once per root) so the
/// Skill checklist row turns green without requiring Start first.
pub fn ensure_skill_for_project(
    state: &mut GrokPaneState,
    project_root: &Path,
    skill_source: Option<&Path>,
) {
    // One attempt per project root (success or fail-loud). Re-open clears this.
    if state.skill_wired_root.as_deref() == Some(project_root) {
        return;
    }
    match ensure_project_skill(project_root, skill_source) {
        Ok(path) => {
            state.skill_wired_root = Some(project_root.to_path_buf());
            state.skill_wire_error = None;
            let _ = path;
        }
        Err(e) => {
            state.skill_wired_root = Some(project_root.to_path_buf());
            let dest = ghidrust_agent::project_skill_path(project_root);
            state.skill_wire_error = Some(format!(
                "Skill auto-install failed ({e}); looked/wrote {}",
                dest.display()
            ));
        }
    }
}

/// Render the Start checklist as a collapsible drawer of fail-loud rows
/// (red text + actionable detail on failure). Caller must only invoke this
/// when no Grok session is running — the drawer disappears after Start.
pub fn render_start_checklist_drawer(
    ui: &mut Ui,
    state: &mut GrokPaneState,
    project_root: &Path,
    muted: Color32,
) {
    let rows = pane_start_checklist(project_root);
    let fail_n = rows.iter().filter(|r| !r.ok).count();
    let title = if fail_n == 0 {
        "Start checklist".to_string()
    } else {
        format!("Start checklist ({fail_n} failing)")
    };
    let resp = egui::CollapsingHeader::new(RichText::new(title).color(muted).strong())
        .id_salt("grok_start_checklist_drawer")
        .default_open(state.checklist_drawer_open)
        .show(ui, |ui| {
            for row in &rows {
                let color = if row.ok {
                    Color32::from_rgb(0x66, 0xBB, 0x6A)
                } else {
                    Color32::from_rgb(0xE5, 0x39, 0x35)
                };
                ui.horizontal(|ui| {
                    ui.label(if row.ok { "✓" } else { "✗" });
                    ui.label(RichText::new(&row.label).color(color));
                    ui.small(RichText::new(&row.detail).color(muted));
                });
            }
        });
    state.checklist_drawer_open = resp.fully_open();
}

/// Attempt to spawn the platform's official Grok Build installer.
pub fn spawn_install_grok() -> String {
    let Some(cmd) = install_command_for_platform() else {
        return "Install: unsupported platform. See https://github.com/xai-org/grok-build".into();
    };
    match std::process::Command::new(&cmd.program)
        .args(&cmd.args)
        .spawn()
    {
        Ok(_child) => format!(
            "Started installer: {}\nWhen it finishes, click 'Re-scan for grok'.",
            cmd.display
        ),
        Err(e) => format!(
            "Failed to spawn installer ({e}).\nRun manually: {}\nDocs: {}",
            cmd.display, cmd.docs_url
        ),
    }
}

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

    #[test]
    fn default_tab_is_grok() {
        assert_eq!(BottomTab::default(), BottomTab::Grok);
    }

    #[test]
    fn pane_starts_without_session() {
        let s = GrokPaneState::new();
        assert!(s.session.is_none());
        assert_eq!(s.tab, BottomTab::Grok);
    }

    #[test]
    fn ensure_skill_turns_checklist_skill_green() {
        let dir = std::env::temp_dir().join(format!("ghidrust-gui-skill-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let mut state = GrokPaneState::new();
        ensure_skill_for_project(&mut state, &dir, None);
        assert!(
            state.skill_wire_error.is_none(),
            "{:?}",
            state.skill_wire_error
        );
        let skill = pane_start_checklist(&dir)
            .into_iter()
            .find(|r| r.label == "Skill")
            .expect("Skill row");
        assert!(skill.ok, "detail={}", skill.detail);
        let _ = std::fs::remove_dir_all(&dir);
    }
}