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.

86.4 KB
Raw Blame
//! Ghidrust GUI · Debugger tool (tabbed host).
//!
//! One window with a tab strip. All panes call `ghidrust_core::process_*`
//! (same APIs as MCP/CLI). Mode **observe** (default) = read-only; **debug**
//! enables break/step/registers/stack.

use crate::layout_tokens::{FieldWidth, WinTier};
use ghidrust_core::ThemeDensity;
use eframe::egui::{self, Color32, RichText, Ui};
use ghidrust_core::process::{
    process_attach_opts, process_break_clear, process_break_list, process_break_set,
    process_continue, process_detach, process_export_snapshot, process_launch, process_list,
    process_modules, process_pause, process_read, process_regions, process_resume, process_scan_mem,
    process_stack, process_step_into, process_step_out, process_step_over,
    process_thread_context_get, process_thread_context_set, process_threads, process_wait,
    process_watch_expr, static_to_live, AttachOpts, BreakKind, BreakpointInfo, LaunchRequest,
    ModuleInfo, ProcessInfo, ProcessSession, ReadResult, RegionInfo, RegisterSet, ScanHit,
    ScanOpts, SessionMode, StackFrame, StopEvent, ThreadInfo, WatchResult,
};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// Host window egui / layout id.
pub const HOST_EGUI_ID: &str = "pane_dbg_host";

/// One provider in Debugger tool catalog.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DebuggerPane {
    Targets,
    Modules,
    MemoryBytes,
    Regions,
    Breakpoints,
    Watches,
    Threads,
    Registers,
    Stack,
    DebuggerConsole,
}

impl DebuggerPane {
    /// Tab strip order: live panes first, stubs last.
    pub const TAB_ORDER: &'static [DebuggerPane] = &[
        DebuggerPane::Targets,
        DebuggerPane::Modules,
        DebuggerPane::MemoryBytes,
        DebuggerPane::Regions,
        DebuggerPane::Breakpoints,
        DebuggerPane::Watches,
        DebuggerPane::Threads,
        DebuggerPane::Registers,
        DebuggerPane::Stack,
        DebuggerPane::DebuggerConsole,
    ];

    pub const ALL: &'static [DebuggerPane] = Self::TAB_ORDER;

    /// Short label for the tab strip.
    pub const fn short_title(self) -> &'static str {
        match self {
            DebuggerPane::Targets => "Targets",
            DebuggerPane::Modules => "Modules",
            DebuggerPane::MemoryBytes => "Memory Bytes",
            DebuggerPane::Regions => "Regions",
            DebuggerPane::Breakpoints => "Breakpoints",
            DebuggerPane::Watches => "Watches",
            DebuggerPane::Threads => "Threads",
            DebuggerPane::Registers => "Registers",
            DebuggerPane::Stack => "Stack",
            DebuggerPane::DebuggerConsole => "Console",
        }
    }

    /// display title (legacy Window menu / provider `TITLE`).
    #[cfg(test)]
    pub const fn title(self) -> &'static str {
        match self {
            DebuggerPane::Targets => "Debugger Targets",
            DebuggerPane::Threads => "Debugger Threads",
            DebuggerPane::Modules => "Debugger Modules",
            DebuggerPane::Regions => "Debugger Regions",
            DebuggerPane::Registers => "Debugger Registers",
            DebuggerPane::Stack => "Debugger Stack",
            DebuggerPane::Breakpoints => "Debugger Breakpoints",
            DebuggerPane::MemoryBytes => "Debugger Memory Bytes",
            DebuggerPane::Watches => "Debugger Watches",
            DebuggerPane::DebuggerConsole => "Debugger Console",
        }
    }

    /// plugin owner.
    pub const fn plugin(self) -> &'static str {
        match self {
            DebuggerPane::Targets => "DebuggerTargetsPlugin",
            DebuggerPane::Threads => "DebuggerThreadsPlugin",
            DebuggerPane::Modules => "DebuggerModulesPlugin",
            DebuggerPane::Regions => "DebuggerRegionsPlugin",
            DebuggerPane::Registers => "DebuggerRegistersPlugin",
            DebuggerPane::Stack => "DebuggerStackPlugin",
            DebuggerPane::Breakpoints => "DebuggerBreakpointsPlugin",
            DebuggerPane::MemoryBytes => "DebuggerMemoryBytesPlugin",
            DebuggerPane::Watches => "DebuggerWatchesPlugin",
            DebuggerPane::DebuggerConsole => "DebuggerConsolePlugin",
        }
    }

    /// Stable id for layout persistence (per-tab focus migration).
    pub const fn egui_id(self) -> &'static str {
        match self {
            DebuggerPane::Targets => "pane_dbg_targets",
            DebuggerPane::Threads => "pane_dbg_threads",
            DebuggerPane::Modules => "pane_dbg_modules",
            DebuggerPane::Regions => "pane_dbg_regions",
            DebuggerPane::Registers => "pane_dbg_registers",
            DebuggerPane::Stack => "pane_dbg_stack",
            DebuggerPane::Breakpoints => "pane_dbg_breakpoints",
            DebuggerPane::MemoryBytes => "pane_dbg_membytes",
            DebuggerPane::Watches => "pane_dbg_watches",
            DebuggerPane::DebuggerConsole => "pane_dbg_console",
        }
    }

    /// Columns rendered in the empty-state table (layout).
    #[cfg(test)]
    pub const fn columns(self) -> &'static [&'static str] {
        match self {
            DebuggerPane::Targets => &["Name", "Type", "State"],
            DebuggerPane::Threads => &["TID", "Name", "State", "Comment"],
            DebuggerPane::Modules => &["Base", "Name", "Path", "Size"],
            DebuggerPane::Regions => &["Start", "End", "Perms", "Kind"],
            DebuggerPane::Registers => &["Register", "Bits", "Value"],
            DebuggerPane::Stack => &["Level", "Frame", "PC", "Function"],
            DebuggerPane::Breakpoints => &["Enabled", "Address", "Kind", "Condition"],
            DebuggerPane::MemoryBytes => &["Address", "Bytes", "ASCII"],
            DebuggerPane::Watches => &["Expression", "Type", "Value"],
            DebuggerPane::DebuggerConsole => &["Line"],
        }
    }

    /// Copy pointing at the pending backend for this pane.
    #[cfg(test)]
    pub const fn backend_message(self) -> &'static str {
        match self {
            DebuggerPane::Targets => {
 "Live Process Bridge (Windows) — ghidrust_core::process_list/attach."
            }
            DebuggerPane::Threads => {
                "Live Process Bridge — process_threads (debug mode)."
            }
            DebuggerPane::Modules => {
                "Live Process Bridge (Windows) — ghidrust_core::process_modules + static_to_live."
            }
            DebuggerPane::Regions => {
                "Live Process Bridge (Windows) — ghidrust_core::process_regions (VirtualQueryEx)."
            }
            DebuggerPane::Registers => {
                "Live Process Bridge — process_thread_context_get/set (debug mode, editable x64 CONTEXT)."
            }
            DebuggerPane::Stack => {
                "Live Process Bridge — process_stack (debug mode, RBP/pdata unwind)."
            }
            DebuggerPane::Breakpoints => {
                "Live Process Bridge — process_break_set/clear/list (software INT3, debug mode)."
            }
            DebuggerPane::MemoryBytes => {
                "Live Process Bridge (Windows) — ghidrust_core::process_read (ReadProcessMemory)."
            }
            DebuggerPane::Watches => {
                "Live Process Bridge — process_watch_expr (pointer-chase DSL)."
            }
            DebuggerPane::DebuggerConsole => {
                "Debugger console — session log + command line (process helpers / mcp_host)."
            }
        }
    }
}

/// `Debugger` menu action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DebuggerAction {
    Launch,
    Attach,
    Disconnect,
    Continue,
    Interrupt,
    StepInto,
    StepOver,
    StepOut,
    ToggleBreakpoint,
    ShowWatches,
}

impl DebuggerAction {
    pub const ALL: &'static [DebuggerAction] = &[
        DebuggerAction::Launch,
        DebuggerAction::Attach,
        DebuggerAction::Disconnect,
        DebuggerAction::Continue,
        DebuggerAction::Interrupt,
        DebuggerAction::StepInto,
        DebuggerAction::StepOver,
        DebuggerAction::StepOut,
        DebuggerAction::ToggleBreakpoint,
        DebuggerAction::ShowWatches,
    ];
    pub const fn label(self) -> &'static str {
        match self {
            DebuggerAction::Launch => "Launch…",
            DebuggerAction::Attach => "Attach…",
            DebuggerAction::Disconnect => "Disconnect",
            DebuggerAction::Continue => "Continue (F5)",
            DebuggerAction::Interrupt => "Interrupt",
            DebuggerAction::StepInto => "Step Into (F7)",
            DebuggerAction::StepOver => "Step Over (F8)",
            DebuggerAction::StepOut => "Step Out (Shift+F8)",
            DebuggerAction::ToggleBreakpoint => "Toggle Breakpoint (F3)",
            DebuggerAction::ShowWatches => "Show Watches Pane",
        }
    }
}

/// Persistent state for the debugger tool mode.
#[derive(Debug, Clone)]
pub struct DebuggerState {
    /// Local VA list (also mirrored from live `process_break_list` when debug).
    pub breakpoints: Vec<u64>,
    /// Watch expression strings.
    pub watches: Vec<String>,
    pub enabled: bool,
    pub host_open: bool,
    pub active_tab: DebuggerPane,
    pub bp_input: String,
    pub bp_oneshot: bool,
    pub watch_input: String,
    pub watch_matrix_heuristic: bool,
    // ── Live Process Bridge ────────────────────────────────────────────
    pub session: Option<ProcessSession>,
    pub process_display_name: Option<String>,
    pub process_list_cache: Vec<ProcessInfo>,
    pub targets_filter: String,
    pub attach_pid_input: String,
    /// Attach/launch mode (default observe).
    pub attach_mode: SessionMode,
    pub modules_cache: Vec<ModuleInfo>,
    pub modules_filter: String,
    pub regions_cache: Vec<RegionInfo>,
    pub static_map_module_input: String,
    pub static_map_rva_input: String,
    pub static_map_result: Option<String>,
    pub mem_bytes_va_input: String,
    pub mem_bytes_size_input: String,
    pub mem_bytes_last: Option<ReadResult>,
    pub follow_pc: bool,
    pub live_error: Option<String>,
    pub suspended: bool,
    pub show_launch_dialog: bool,
    pub launch_image: String,
    pub launch_args: String,
    pub launch_cwd: String,
    pub launch_break_at_entry: bool,
    // Debug caches
    pub live_breakpoints: Vec<BreakpointInfo>,
    pub threads_cache: Vec<ThreadInfo>,
    pub active_thread_id: Option<u32>,
    pub registers_cache: Option<RegisterSet>,
    /// Editable hex strings keyed by register name (synced from `registers_cache`).
    pub reg_edit: BTreeMap<String, String>,
    pub stack_cache: Vec<StackFrame>,
    pub watch_results: Vec<WatchResult>,
    pub last_stop: Option<StopEvent>,
    pub console_log: Vec<String>,
    /// Debugger console command line (appends to log; optional process_* / mcp_host).
    pub console_input: String,
    pub scan_aob: String,
    pub scan_string: String,
    pub scan_hits: Vec<ScanHit>,
}

impl Default for DebuggerState {
    fn default() -> Self {
        Self {
            breakpoints: Vec::new(),
            watches: Vec::new(),
            enabled: false,
            host_open: false,
            active_tab: DebuggerPane::Targets,
            bp_input: String::new(),
            bp_oneshot: false,
            watch_input: String::new(),
            watch_matrix_heuristic: false,
            session: None,
            process_display_name: None,
            process_list_cache: Vec::new(),
            targets_filter: String::new(),
            attach_pid_input: String::new(),
            attach_mode: SessionMode::Observe,
            modules_cache: Vec::new(),
            modules_filter: String::new(),
            regions_cache: Vec::new(),
            static_map_module_input: String::new(),
            static_map_rva_input: String::new(),
            static_map_result: None,
            mem_bytes_va_input: String::new(),
            mem_bytes_size_input: String::new(),
            mem_bytes_last: None,
            follow_pc: true,
            live_error: None,
            suspended: false,
            show_launch_dialog: false,
            launch_image: String::new(),
            launch_args: String::new(),
            launch_cwd: String::new(),
            launch_break_at_entry: true,
            live_breakpoints: Vec::new(),
            threads_cache: Vec::new(),
            active_thread_id: None,
            registers_cache: None,
            reg_edit: BTreeMap::new(),
            stack_cache: Vec::new(),
            watch_results: Vec::new(),
            last_stop: None,
            console_log: Vec::new(),
            console_input: String::new(),
            scan_aob: String::new(),
            scan_string: String::new(),
            scan_hits: Vec::new(),
        }
    }
}

impl DebuggerState {
    pub fn toggle_breakpoint(&mut self, va: u64) {
        if let Some(pos) = self.breakpoints.iter().position(|b| *b == va) {
            self.breakpoints.remove(pos);
        } else {
            self.breakpoints.push(va);
            self.breakpoints.sort();
        }
    }

    /// Toggle a local breakpoint, mirroring it to the attached debug session when possible.
    pub fn toggle_breakpoint_live(&mut self, va: u64) {
        if let Some(sess) = self.session.clone().filter(|s| s.mode == SessionMode::Debug) {
            let existing = self
                .live_breakpoints
                .iter()
                .find(|bp| bp.addr == va)
                .map(|bp| bp.id);
            let result = match existing {
                Some(id) => process_break_clear(&sess.session_id, Some(id), None),
                None => process_break_set(&sess.session_id, va, BreakKind::Software, false)
                    .map(|_| ()),
            };
            match result {
                Ok(()) => {
                    self.log(format!("breakpoint toggled at {va:#x}"));
                    self.refresh_debug_views();
                    return;
                }
                Err(e) => self.live_error = Some(e),
            }
        }
        self.toggle_breakpoint(va);
    }

    #[cfg(test)]
    pub fn has_breakpoint(&self, va: u64) -> bool {
        self.breakpoints.contains(&va)
    }

    pub fn add_watch(&mut self, expr: impl Into<String>) {
        let e = expr.into();
        if !e.trim().is_empty() && !self.watches.iter().any(|w| w == &e) {
            self.watches.push(e);
        }
    }

    pub fn remove_watch(&mut self, idx: usize) {
        if idx < self.watches.len() {
            self.watches.remove(idx);
        }
    }

    /// Enable tool mode: open host, focus Targets, refresh process list if empty.
    pub fn enable_tool(&mut self) {
        self.enabled = true;
        self.host_open = true;
        self.active_tab = DebuggerPane::Targets;
        if self.process_list_cache.is_empty() {
            self.refresh_process_list();
        }
    }

    /// Debugger → Attach… : open host on Targets (and refresh list if needed).
    pub fn open_attach_ui(&mut self) {
        self.enable_tool();
        self.active_tab = DebuggerPane::Targets;
    }

    /// Debugger → Launch… : open host + launch dialog; prefill image when provided.
    pub fn open_launch_ui(&mut self, prefill_image: Option<&Path>) {
        self.enable_tool();
        if let Some(p) = prefill_image {
            if self.launch_image.trim().is_empty() {
                self.launch_image = p.display().to_string();
            }
            if self.launch_cwd.trim().is_empty() {
                if let Some(parent) = p.parent() {
                    self.launch_cwd = parent.display().to_string();
                }
            }
        }
        self.show_launch_dialog = true;
    }

    pub fn focus_tab(&mut self, tab: DebuggerPane) {
        self.host_open = true;
        self.enabled = true;
        self.active_tab = tab;
    }

    pub fn refresh_process_list(&mut self) {
        self.live_error = None;
        match process_list() {
            Ok(v) => self.process_list_cache = v,
            Err(e) => {
                self.process_list_cache.clear();
                self.live_error = Some(e);
            }
        }
    }

    pub fn clear_live_caches(&mut self) {
        self.modules_cache.clear();
        self.regions_cache.clear();
        self.mem_bytes_last = None;
        self.mem_bytes_va_input.clear();
        self.static_map_result = None;
        self.process_display_name = None;
        self.suspended = false;
        self.live_breakpoints.clear();
        self.threads_cache.clear();
        self.active_thread_id = None;
        self.registers_cache = None;
        self.reg_edit.clear();
        self.stack_cache.clear();
        self.watch_results.clear();
        self.last_stop = None;
        self.scan_hits.clear();
    }

    /// Sync editable register fields from the live cache.
    pub fn sync_reg_edit_from_cache(&mut self) {
        let Some(regs) = self.registers_cache.clone() else {
            self.reg_edit.clear();
            return;
        };
        self.reg_edit.clear();
        for (n, v) in register_pairs(&regs) {
            self.reg_edit.insert(n.to_string(), format!("{v:#x}"));
        }
    }

    /// Apply one edited register via `process_thread_context_set`.
    pub fn apply_register_edit(&mut self, name: &str) {
        let Some(sess) = self.session.clone() else {
            self.live_error = Some("no session".into());
            return;
        };
        if sess.mode != SessionMode::Debug {
            self.live_error = Some("registers require mode=debug".into());
            return;
        }
        let Some(tid) = self.active_thread_id else {
            self.live_error = Some("no active thread".into());
            return;
        };
        let Some(raw) = self.reg_edit.get(name).cloned() else {
            return;
        };
        let Some(val) = parse_hex(raw.trim_start_matches('!')) else {
            self.live_error = Some(format!("bad hex for {name}: {raw}"));
            return;
        };
        let mut regs = match self.registers_cache.clone() {
            Some(r) => r,
            None => match process_thread_context_get(&sess.session_id, tid) {
                Ok(r) => r,
                Err(e) => {
                    self.live_error = Some(e);
                    return;
                }
            },
        };
        if !set_register_field(&mut regs, name, val) {
            self.live_error = Some(format!("unknown register {name}"));
            return;
        }
        match process_thread_context_set(&sess.session_id, tid, &regs) {
            Ok(()) => {
                self.registers_cache = Some(regs);
                self.reg_edit.insert(name.to_string(), format!("{val:#x}"));
                self.log(format!("process_thread_context_set {name}={val:#x} tid={tid}"));
                self.live_error = None;
            }
            Err(e) => self.live_error = Some(e),
        }
    }

    /// Run a console command line: always appends to the log; optionally
    /// dispatches built-in process helpers or `mcp_host` tool lines.
    pub fn run_console_command(&mut self, line: &str) {
        let line = line.trim();
        if line.is_empty() {
            return;
        }
        self.log(format!("> {line}"));
        let lower = line.to_ascii_lowercase();
        if let Some(sess) = self.session.clone() {
            let sid = sess.session_id.clone();
            match lower.as_str() {
                "continue" | "g" | "c" => {
                    match process_continue(&sid) {
                        Ok(()) => self.log("continue ok"),
                        Err(e) => self.log(format!("continue error: {e}")),
                    }
                    return;
                }
                "pause" | "break" | "interrupt" => {
                    match process_pause(&sid) {
                        Ok(()) => self.log("pause ok"),
                        Err(e) => self.log(format!("pause error: {e}")),
                    }
                    return;
                }
                "step" | "stepi" | "si" => {
                    match process_step_into(&sid, self.active_thread_id) {
                        Ok(()) => {
                            self.log("step-into requested");
                            self.poll_stop(2000);
                            self.refresh_debug_views();
                        }
                        Err(e) => self.log(format!("step error: {e}")),
                    }
                    return;
                }
                "stepover" | "next" | "ni" => {
                    match process_step_over(&sid, self.active_thread_id) {
                        Ok(()) => {
                            self.log("step-over requested");
                            self.poll_stop(2000);
                            self.refresh_debug_views();
                        }
                        Err(e) => self.log(format!("stepover error: {e}")),
                    }
                    return;
                }
                "regs" | "registers" => {
                    self.refresh_debug_views();
                    if let Some(r) = &self.registers_cache {
                        for (n, v) in register_pairs(r) {
                            self.log(format!("  {n}={v:#x}"));
                        }
                    } else {
                        self.log("no register cache");
                    }
                    return;
                }
                "threads" => {
                    self.refresh_debug_views();
                    let tids: Vec<u32> = self.threads_cache.iter().map(|t| t.thread_id).collect();
                    for tid in tids {
                        self.log(format!("  tid={tid}"));
                    }
                    return;
                }
                "help" => {
                    self.log(
                        "commands: continue|pause|step|stepover|regs|threads|help · or process_* / tool {json}",
                    );
                    return;
                }
                _ => {}
            }
        } else if matches!(
            lower.as_str(),
            "continue" | "g" | "c" | "pause" | "break" | "interrupt" | "step" | "stepi" | "si"
                | "stepover" | "next" | "ni" | "regs" | "registers" | "threads"
        ) {
            self.log("no live session — attach/launch first");
            return;
        }

        // Optional mcp_host path for process_* / other non-net tools.
        if lower.starts_with("process_") || line.contains('{') {
            match crate::mcp_host::parse_tool_line(line) {
                Ok((tool, args)) => {
                    let out = crate::mcp_host::invoke_tool(&tool, &args);
                    for l in out.lines().take(40) {
                        self.log(l.to_string());
                    }
                }
                Err(e) => self.log(format!("parse error: {e}")),
            }
        }
    }

    pub fn log(&mut self, line: impl Into<String>) {
        self.console_log.push(line.into());
        if self.console_log.len() > 500 {
            let n = self.console_log.len() - 400;
            self.console_log.drain(0..n);
        }
    }

    pub fn is_debug_mode(&self) -> bool {
        self.session
            .as_ref()
            .map(|s| s.mode == SessionMode::Debug)
            .unwrap_or(false)
    }

    pub fn detach_session(&mut self) {
        if let Some(sess) = self.session.take() {
            self.log(format!("detach {}", sess.session_id));
            let _ = process_detach(&sess.session_id);
        }
        self.clear_live_caches();
        self.live_error = None;
        self.active_tab = DebuggerPane::Targets;
    }

    /// Attach with current `attach_mode` and auto-populate.
    pub fn attach_and_populate(&mut self, pid: u32) {
        if pid == 0 {
            self.live_error = Some("invalid PID".into());
            return;
        }
        self.live_error = None;
        match process_attach_opts(pid, &AttachOpts { mode: self.attach_mode }) {
            Ok(sess) => {
                let name = self
                    .process_list_cache
                    .iter()
                    .find(|p| p.pid == pid)
                    .map(|p| p.name.clone());
                self.process_display_name = name;
                self.log(format!(
                    "attach pid={pid} mode={} session={}",
                    sess.mode.as_str(),
                    sess.session_id
                ));
                if let Some(a) = &sess.advisory {
                    if a.suspected_protection {
                        self.log(format!("advisory: {}", a.message));
                    }
                }
                self.session = Some(sess);
                self.suspended = false;
                self.refresh_after_attach();
                if self.is_debug_mode() {
                    self.poll_stop(500);
                }
            }
            Err(e) => {
                self.session = None;
                self.clear_live_caches();
                self.live_error = Some(e);
            }
        }
    }

    /// Launch with current attach_mode (+ break_at_entry when debug).
    pub fn launch_and_populate(&mut self) {
        let image = self.launch_image.trim();
        if image.is_empty() {
            self.live_error = Some("launch image path is required".into());
            return;
        }
        let req = LaunchRequest {
            image: PathBuf::from(image),
            args: {
                let a = self.launch_args.trim();
                if a.is_empty() {
                    None
                } else {
                    Some(a.to_string())
                }
            },
            cwd: {
                let c = self.launch_cwd.trim();
                if c.is_empty() {
                    None
                } else {
                    Some(PathBuf::from(c))
                }
            },
            mode: self.attach_mode,
            break_at_entry: self.attach_mode == SessionMode::Debug && self.launch_break_at_entry,
        };
        self.live_error = None;
        match process_launch(&req) {
            Ok(r) => {
                let name = Path::new(&r.image)
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| r.image.clone());
                self.process_display_name = Some(name);
                self.log(format!(
                    "launch mode={} session={} suspended={}",
                    r.session.mode.as_str(),
                    r.session.session_id,
                    r.suspended
                ));
                self.session = Some(r.session);
                self.suspended = r.suspended;
                self.show_launch_dialog = false;
                self.refresh_after_attach();
                if self.is_debug_mode() {
                    self.poll_stop(2000);
                }
            }
            Err(e) => {
                self.live_error = Some(e);
            }
        }
    }

    pub fn poll_stop(&mut self, timeout_ms: u64) {
        let Some(sess) = self.session.clone() else {
            return;
        };
        if sess.mode != SessionMode::Debug {
            return;
        }
        match process_wait(&sess.session_id, timeout_ms) {
            Ok(wr) => {
                if let Some(ev) = wr.event {
                    self.log(format!(
                        "stop reason={} tid={} rip={:#x}",
                        ev.reason, ev.thread_id, ev.rip
                    ));
                    self.active_thread_id = Some(ev.thread_id);
                    if let Some(regs) = &ev.registers {
                        self.registers_cache = Some(regs.clone());
                    }
                    if self.follow_pc {
                        self.mem_bytes_va_input = format!("{:#x}", ev.rip);
                    }
                    self.last_stop = Some(ev);
                    self.refresh_debug_views();
                } else if !wr.ok {
                    if wr.code.as_deref() != Some("wait_timeout") {
                        self.live_error = wr.message.or(wr.code);
                    }
                }
            }
            Err(e) => self.live_error = Some(e),
        }
    }

    pub fn refresh_debug_views(&mut self) {
        let Some(sess) = self.session.clone() else {
            return;
        };
        if sess.mode != SessionMode::Debug {
            return;
        }
        if let Ok(bps) = process_break_list(&sess.session_id) {
            self.live_breakpoints = bps;
            self.breakpoints = self.live_breakpoints.iter().map(|b| b.addr).collect();
        }
        if let Ok(ths) = process_threads(&sess.session_id) {
            self.threads_cache = ths;
            if self.active_thread_id.is_none() {
                self.active_thread_id = self.threads_cache.first().map(|t| t.thread_id);
            }
        }
        if let Some(tid) = self.active_thread_id {
            if let Ok(regs) = process_thread_context_get(&sess.session_id, tid) {
                self.registers_cache = Some(regs);
                self.sync_reg_edit_from_cache();
            }
            if let Ok(frames) = process_stack(&sess.session_id, tid, 32) {
                self.stack_cache = frames;
            }
        }
        self.refresh_watches();
    }

    pub fn refresh_watches(&mut self) {
        let Some(sess) = self.session.clone() else {
            return;
        };
        let mut out = Vec::new();
        for e in &self.watches {
            match process_watch_expr(&sess.session_id, e, self.watch_matrix_heuristic) {
                Ok(w) => out.push(w),
                Err(err) => out.push(WatchResult {
                    expr: e.clone(),
                    steps: vec![],
                    final_va: None,
                    value_hex: None,
                    as_u64: None,
                    as_f32: None,
                    as_f64: None,
                    heuristic_float4x4: None,
                    heuristic: false,
                    error: Some(err),
                }),
            }
        }
        self.watch_results = out;
    }

    pub fn debug_continue(&mut self) {
        let Some(sess) = self.session.clone() else {
            return;
        };
        match process_continue(&sess.session_id) {
            Ok(()) => {
                self.log("continue");
                self.live_error = None;
                self.poll_stop(100);
            }
            Err(e) => self.live_error = Some(e),
        }
    }

    pub fn debug_pause(&mut self) {
        let Some(sess) = self.session.clone() else {
            return;
        };
        match process_pause(&sess.session_id) {
            Ok(()) => {
                self.log("pause");
                self.poll_stop(2000);
            }
            Err(e) => self.live_error = Some(e),
        }
    }

    pub fn debug_step(&mut self, over: bool) {
        let Some(sess) = self.session.clone() else {
            return;
        };
        let tid = self.active_thread_id;
        let r = if over {
            process_step_over(&sess.session_id, tid)
        } else {
            process_step_into(&sess.session_id, tid)
        };
        match r {
            Ok(()) => {
                self.log(if over { "step over" } else { "step into" });
                self.poll_stop(2000);
            }
            Err(e) => self.live_error = Some(e),
        }
    }

    pub fn debug_step_out(&mut self) {
        let Some(sess) = self.session.clone() else {
            return;
        };
        let tid = self.active_thread_id;
        match process_step_out(&sess.session_id, tid) {
            Ok(()) => {
                self.log("step out");
                self.poll_stop(5000);
            }
            Err(e) => self.live_error = Some(e),
        }
    }

    pub fn resume_session(&mut self) {
        let Some(sess) = self.session.clone() else {
            self.live_error = Some("no live session to resume".into());
            return;
        };
        match process_resume(&sess.session_id) {
            Ok(()) => {
                self.suspended = false;
                self.live_error = None;
            }
            Err(e) => self.live_error = Some(e),
        }
    }

    /// After a successful attach: modules → seed memory → regions → focus Modules.
    pub fn refresh_after_attach(&mut self) {
        let Some(sess) = self.session.clone() else {
            return;
        };
        self.live_error = None;

        match process_modules(&sess.session_id) {
            Ok(v) => self.modules_cache = v,
            Err(e) => {
                self.modules_cache.clear();
                self.live_error = Some(e);
            }
        }

        if let Some(main) =
            pick_main_module(&self.modules_cache, self.process_display_name.as_deref())
        {
            self.mem_bytes_va_input = format!("{:#x}", main.base);
            if self.mem_bytes_size_input.trim().is_empty() {
                self.mem_bytes_size_input = "256".into();
            }
            match process_read(&sess.session_id, main.base, 256) {
                Ok(r) => {
                    if let Some(err) = &r.error {
                        if self.live_error.is_none() {
                            self.live_error = Some(err.clone());
                        }
                    }
                    self.mem_bytes_last = Some(r);
                }
                Err(e) => {
                    self.mem_bytes_last = None;
                    if self.live_error.is_none() {
                        self.live_error = Some(e);
                    }
                }
            }
        }

        match process_regions(&sess.session_id, 4096) {
            Ok(v) => self.regions_cache = v,
            Err(e) => {
                self.regions_cache.clear();
                if self.live_error.is_none() {
                    self.live_error = Some(e);
                }
            }
        }

        self.active_tab = DebuggerPane::Modules;
    }

    /// Status line for the host chrome.
    pub fn status_line(&self) -> String {
        match &self.session {
            Some(sess) => {
                let name = self.process_display_name.as_deref().unwrap_or("(unknown)");
                let mode = sess.mode.as_str();
                let rs = sess.run_state.as_str();
                if self.suspended {
                    format!(
                        "{mode}/{rs} · {name} · pid={} · session={} — Resume to run",
                        sess.pid, sess.session_id
                    )
                } else if let Some(stop) = &self.last_stop {
                    format!(
                        "{mode}/{rs} · {name} · pid={} · stop={} rip={:#x}",
                        sess.pid, stop.reason, stop.rip
                    )
                } else {
                    format!(
                        "{mode}/{rs} · {name} · pid={} · session={}",
                        sess.pid, sess.session_id
                    )
                }
            }
            None => "Detached — Attach a PID or Launch an image (Mode: observe|debug)".into(),
        }
    }

    /// Window title including process identity when attached.
    pub fn window_title(&self) -> String {
        match (&self.session, &self.process_display_name) {
            (Some(sess), Some(name)) if self.suspended => {
                format!("Debugger — {name} [suspended] (pid={})", sess.pid)
            }
            (Some(sess), Some(name)) => format!("Debugger — {name} (pid={})", sess.pid),
            (Some(sess), None) => format!("Debugger — pid={}", sess.pid),
            _ => "Debugger".into(),
        }
    }

    /// Module containing `va`, if any.
    pub fn module_for_va(&self, va: u64) -> Option<&ModuleInfo> {
        self.modules_cache
            .iter()
            .find(|m| va >= m.base && va < m.base.saturating_add(m.size))
    }
}

/// Prefer module whose name matches the process; else first with a path; else first.
pub fn pick_main_module<'a>(
    modules: &'a [ModuleInfo],
    process_name: Option<&str>,
) -> Option<&'a ModuleInfo> {
    if modules.is_empty() {
        return None;
    }
    if let Some(pname) = process_name {
        let pl = pname.to_ascii_lowercase();
        if let Some(m) = modules.iter().find(|m| m.name.to_ascii_lowercase() == pl) {
            return Some(m);
        }
        if let Some(m) = modules.iter().find(|m| {
            m.name
                .to_ascii_lowercase()
                .contains(pl.trim_end_matches(".exe"))
        }) {
            return Some(m);
        }
    }
    modules
        .iter()
        .find(|m| m.path.as_ref().map(|p| !p.is_empty()).unwrap_or(false))
        .or_else(|| modules.first())
}

/// Migrate legacy per-pane open flags + host key into host_open / active_tab / enabled.
pub fn apply_layout_flags(
    state: &mut DebuggerState,
    open_panes: &std::collections::BTreeMap<String, bool>,
) {
    let host = open_panes.get(HOST_EGUI_ID).copied().unwrap_or(false);
    let mut first_open: Option<DebuggerPane> = None;
    let mut any_tab = false;
    for p in DebuggerPane::TAB_ORDER {
        if open_panes.get(p.egui_id()).copied().unwrap_or(false) {
            any_tab = true;
            if first_open.is_none() {
                first_open = Some(*p);
            }
        }
    }
    if host || any_tab {
        state.host_open = true;
        state.enabled = true;
        if let Some(tab) = first_open {
            state.active_tab = tab;
        }
    } else if open_panes.contains_key(HOST_EGUI_ID) {
        state.host_open = host;
        if !host {
            state.enabled = false;
        }
    }
}

/// Snapshot debugger visibility into layout open_panes.
pub fn snapshot_layout_flags(
    state: &DebuggerState,
    open_panes: &mut std::collections::BTreeMap<String, bool>,
) {
    open_panes.insert(HOST_EGUI_ID.to_string(), state.host_open);
    for p in DebuggerPane::ALL {
        open_panes.insert(
            p.egui_id().to_string(),
            state.host_open && state.active_tab == *p,
        );
    }
}

/// Draw the single Debugger host window (tab strip + status + active pane).
pub fn draw_host(ctx: &egui::Context, state: &mut DebuggerState, muted: Color32) {
    if state.host_open {
        let mut open = true;
        let title = state.window_title();
        egui::Window::new(title)
            .id(egui::Id::new(HOST_EGUI_ID))
            .open(&mut open)
            .resizable(true)
            .default_size(WinTier::Lg.size(&ThemeDensity::FIB_DESKTOP))
            .min_size(WinTier::Lg.min_size(&ThemeDensity::FIB_DESKTOP))
            .show(ctx, |ui| {
                // Fill the resized window so vertical growth isn't clamped by content.
                let avail = ui.available_size();
                ui.set_min_size(avail);
                render_host_body(state, ui, muted);
            });
        if !open {
            state.host_open = false;
        }
    }
    draw_launch_dialog(ctx, state, muted);
}

/// Launch… dialog (image / args / cwd).
pub fn draw_launch_dialog(ctx: &egui::Context, state: &mut DebuggerState, muted: Color32) {
    if !state.show_launch_dialog {
        return;
    }
    let mut open = true;
    egui::Window::new("Launch process")
 .id(egui::Id::new("pane_dbg_launch_dialog"))
        .open(&mut open)
        .collapsible(false)
        .resizable(true)
        .default_width(WinTier::Md.width(&ThemeDensity::FIB_DESKTOP))
        .show(ctx, |ui| {
            ui.small(
                RichText::new(
 "CREATE_SUSPENDED spawn + read-only attach. Not a debug break-at-entry — use Resume after inspect.",
                )
                .color(muted),
            );
            ui.separator();
            ui.horizontal(|ui| {
 ui.label("Image:");
                ui.add(
                    egui::TextEdit::singleline(&mut state.launch_image)
                        .desired_width(FieldWidth::Wide.px(&ThemeDensity::FIB_DESKTOP))
 .hint_text(r"C:\path\to\app.exe"),
                );
 if ui.button("Browse…").clicked() {
                    if let Some(path) = rfd::FileDialog::new()
 .add_filter("Executable", &["exe"])
                        .pick_file()
                    {
                        if let Some(parent) = path.parent() {
                            if state.launch_cwd.trim().is_empty() {
                                state.launch_cwd = parent.display().to_string();
                            }
                        }
                        state.launch_image = path.display().to_string();
                    }
                }
            });
            ui.horizontal(|ui| {
 ui.label("Args:");
                ui.add(
                    egui::TextEdit::singleline(&mut state.launch_args)
                        .desired_width(FieldWidth::XWide.px(&ThemeDensity::FIB_DESKTOP))
 .hint_text("optional"),
                );
            });
            ui.horizontal(|ui| {
                ui.label("Cwd:");
                ui.add(
                    egui::TextEdit::singleline(&mut state.launch_cwd)
                        .desired_width(FieldWidth::Wide.px(&ThemeDensity::FIB_DESKTOP))
                        .hint_text("optional working directory"),
                );
                if ui.button("Browse…").clicked() {
                    if let Some(path) = rfd::FileDialog::new().pick_folder() {
                        state.launch_cwd = path.display().to_string();
                    }
                }
            });
            ui.horizontal(|ui| {
                ui.label("Mode:");
                egui::ComboBox::from_id_salt("dbg_launch_mode")
                    .selected_text(state.attach_mode.as_str())
                    .show_ui(ui, |ui| {
                        ui.selectable_value(&mut state.attach_mode, SessionMode::Observe, "observe");
                        ui.selectable_value(&mut state.attach_mode, SessionMode::Debug, "debug");
                    });
                ui.add_enabled(
                    state.attach_mode == SessionMode::Debug,
                    egui::Checkbox::new(&mut state.launch_break_at_entry, "Break at entry"),
                );
            });
            if let Some(e) = state.live_error.clone() {
                err_row(ui, &e);
            }
            ui.separator();
            ui.horizontal(|ui| {
                if ui
                    .add_enabled(
                        !state.launch_image.trim().is_empty() && state.session.is_none(),
                        egui::Button::new("Launch"),
                    )
                    .clicked()
                {
                    state.launch_and_populate();
                }
 if ui.button("Cancel").clicked() {
                    state.show_launch_dialog = false;
                }
            });
            if state.session.is_some() {
                ui.small(
 RichText::new("Detach the current session before launching.")
                        .color(muted),
                );
            }
        });
    if !open {
        state.show_launch_dialog = false;
    }
}

fn render_host_body(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
    // Status bar
    ui.horizontal(|ui| {
        ui.label(RichText::new(state.status_line()).color(muted));
        if state.session.is_some() && state.suspended {
            if ui
                .small_button("Resume")
                .on_hover_text("ResumeThread / continue debug session")
                .clicked()
            {
                state.resume_session();
            }
        }
        if state.session.is_some() {
            if ui.small_button("Detach").clicked() {
                state.detach_session();
            }
        }
    });
    // Debug toolbar
    let dbg = state.is_debug_mode();
    ui.horizontal(|ui| {
        let cont = ui
            .add_enabled(dbg, egui::Button::new("Continue (F5)").small())
            .on_hover_text(if dbg {
                "process_continue"
            } else {
                "Requires mode=debug"
            });
        if cont.clicked() {
            state.debug_continue();
        }
        let pause = ui
            .add_enabled(dbg, egui::Button::new("Interrupt").small())
            .on_hover_text(if dbg {
                "process_pause"
            } else {
                "Requires mode=debug"
            });
        if pause.clicked() {
            state.debug_pause();
        }
        if ui
            .add_enabled(dbg, egui::Button::new("Step Into (F7)").small())
            .clicked()
        {
            state.debug_step(false);
        }
        if ui
            .add_enabled(dbg, egui::Button::new("Step Over (F8)").small())
            .clicked()
        {
            state.debug_step(true);
        }
        if ui
            .add_enabled(dbg, egui::Button::new("Step Out (Shift+F8)").small())
            .on_hover_text(if dbg {
                "process_step_out"
            } else {
                "Requires mode=debug"
            })
            .clicked()
        {
            state.debug_step_out();
        }
        if ui
            .add_enabled(dbg, egui::Button::new("Wait stop").small())
            .on_hover_text("process_wait 5s")
            .clicked()
        {
            state.poll_stop(5000);
        }
        if ui
            .add_enabled(dbg, egui::Button::new("Refresh debug").small())
            .clicked()
        {
            state.refresh_debug_views();
        }
        ui.checkbox(&mut state.follow_pc, "Follow PC");
    });
    if let Some(e) = state.live_error.clone() {
        err_row(ui, &e);
    }
    ui.separator();

    // Tab strip
    egui::ScrollArea::horizontal()
        .id_salt("dbg_tab_strip")
        .show(ui, |ui| {
            ui.horizontal(|ui| {
                for tab in DebuggerPane::TAB_ORDER {
                    let selected = state.active_tab == *tab;
                    if ui.selectable_label(selected, tab.short_title()).clicked() {
                        state.active_tab = *tab;
                    }
                }
            });
        });
    ui.separator();

    let pane = state.active_tab;
    render_pane_body(pane, state, ui, muted);
}

/// Render pane content without the old per-window heading chrome.
pub fn render_pane_body(
    pane: DebuggerPane,
    state: &mut DebuggerState,
    ui: &mut Ui,
    muted: Color32,
) {
    ui.small(RichText::new(format!("Provider · {}", pane.plugin())).color(muted));
    ui.separator();

    match pane {
        DebuggerPane::Breakpoints => render_breakpoints(state, ui, muted),
        DebuggerPane::Watches => render_watches(state, ui, muted),
        DebuggerPane::Targets => render_targets(state, ui, muted),
        DebuggerPane::Modules => render_modules(state, ui, muted),
        DebuggerPane::Regions => render_regions(state, ui, muted),
        DebuggerPane::MemoryBytes => render_memory_bytes(state, ui, muted),
        DebuggerPane::Threads => render_threads(state, ui, muted),
        DebuggerPane::Registers => render_registers(state, ui, muted),
        DebuggerPane::Stack => render_stack(state, ui, muted),
        DebuggerPane::DebuggerConsole => render_console(state, ui, muted),
    }
}

fn err_row(ui: &mut Ui, err: &str) {
    ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), err);
}

fn render_targets(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
    ui.small(
        RichText::new(
            "Mode observe = read-only. Mode debug = break/step/regs/stack (same as MCP process_attach mode).",
        )
        .color(muted),
    );
    ui.horizontal(|ui| {
        if ui.button("Refresh process list").clicked() {
            state.refresh_process_list();
        }
        if ui.button("Launch…").clicked() {
            state.show_launch_dialog = true;
        }
        ui.label("Mode:");
        egui::ComboBox::from_id_salt("dbg_attach_mode")
            .selected_text(state.attach_mode.as_str())
            .show_ui(ui, |ui| {
                ui.selectable_value(&mut state.attach_mode, SessionMode::Observe, "observe");
                ui.selectable_value(&mut state.attach_mode, SessionMode::Debug, "debug");
            });
        ui.label("Filter:");
        ui.add(
            egui::TextEdit::singleline(&mut state.targets_filter)
                .desired_width(FieldWidth::Compact.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("process name…"),
        );
    });
    if state.session.is_some() {
        ui.small(
            RichText::new("Already attached — use Detach in the status bar to switch targets.")
                .color(muted),
        );
    }
    ui.separator();
    ui.horizontal(|ui| {
        ui.label("PID:");
        ui.add(
            egui::TextEdit::singleline(&mut state.attach_pid_input)
                .desired_width(FieldWidth::Narrow.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("1234"),
        );
        if ui
            .add_enabled(
                !state.attach_pid_input.trim().is_empty() && state.session.is_none(),
                egui::Button::new("Attach by PID"),
            )
            .clicked()
        {
            attach(state, state.attach_pid_input.trim().parse().unwrap_or(0));
        }
    });
    if state.process_list_cache.is_empty() {
        ui.weak("No process list loaded — click Refresh (Windows Toolhelp32 snapshot).");
        return;
    }
    let q = state.targets_filter.to_ascii_lowercase();
    let rows: Vec<&ProcessInfo> = state
        .process_list_cache
        .iter()
        .filter(|p| q.is_empty() || p.name.to_ascii_lowercase().contains(&q))
        .collect();
    ui.small(format!(
        "{} / {} processes",
        rows.len(),
        state.process_list_cache.len()
    ));
    let mut attach_pid: Option<u32> = None;
    let can_attach = state.session.is_none();
    let list_h = ui.available_height().max(120.0);
    egui::ScrollArea::vertical()
        .id_salt("dbg_targets_scroll")
        .max_height(list_h)
        .auto_shrink([false, false])
        .show(ui, |ui| {
            egui::Grid::new("dbg_targets_grid")
                .num_columns(4)
                .striped(true)
                .show(ui, |ui| {
                    ui.strong("PID");
                    ui.strong("Name");
                    ui.strong("Path");
                    ui.strong("");
                    ui.end_row();
                    for p in &rows {
                        ui.monospace(format!("{}", p.pid));
                        ui.label(&p.name);
                        ui.small(p.path.as_deref().unwrap_or("—"));
                        if ui
                            .add_enabled(can_attach, egui::Button::new("Attach").small())
                            .clicked()
                        {
                            attach_pid = Some(p.pid);
                        }
                        ui.end_row();
                    }
                });
        });
    if let Some(pid) = attach_pid {
        attach(state, pid);
    }
}

fn attach(state: &mut DebuggerState, pid: u32) {
    state.attach_and_populate(pid);
}

fn render_modules(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
    let Some(sess) = state.session.clone() else {
        ui.weak("No live target — attach one from Targets first.");
        return;
    };
    ui.horizontal(|ui| {
        ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));
        if ui.button("Refresh modules").clicked() {
            state.live_error = None;
            match process_modules(&sess.session_id) {
                Ok(v) => state.modules_cache = v,
                Err(e) => {
                    state.modules_cache.clear();
                    state.live_error = Some(e);
                }
            }
        }
        ui.label("Filter:");
        ui.add(
            egui::TextEdit::singleline(&mut state.modules_filter)
                .desired_width(FieldWidth::Compact.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("module name…"),
        );
    });
    if state.modules_cache.is_empty() {
        ui.weak("No modules cached — click Refresh modules.");
    } else {
        let q = state.modules_filter.to_ascii_lowercase();
        let rows: Vec<&ModuleInfo> = state
            .modules_cache
            .iter()
            .filter(|m| {
                q.is_empty()
                    || m.name.to_ascii_lowercase().contains(&q)
                    || m.path
                        .as_deref()
                        .map(|p| p.to_ascii_lowercase().contains(&q))
                        .unwrap_or(false)
            })
            .collect();
        ui.small(format!(
            "{} / {} module(s)",
            rows.len(),
            state.modules_cache.len()
        ));
        let mut goto_base: Option<u64> = None;
        // Leave room below for Static Mappings; grow with the window.
        let list_h = (ui.available_height() - 140.0).max(80.0);
        egui::ScrollArea::vertical()
            .id_salt("dbg_modules_scroll")
            .max_height(list_h)
            .auto_shrink([false, false])
            .show(ui, |ui| {
                egui::Grid::new("dbg_modules_grid")
                    .num_columns(5)
                    .striped(true)
                    .show(ui, |ui| {
                        ui.strong("Base");
                        ui.strong("Size");
                        ui.strong("Name");
                        ui.strong("Path");
                        ui.strong("");
                        ui.end_row();
                        for m in &rows {
                            ui.monospace(format!("{:#x}", m.base));
                            ui.monospace(format!("{:#x}", m.size));
                            ui.label(&m.name);
                            ui.small(m.path.as_deref().unwrap_or("—"));
                            if ui
                                .small_button("Memory")
                                .on_hover_text("Read Memory Bytes at module base")
                                .clicked()
                            {
                                goto_base = Some(m.base);
                            }
                            ui.end_row();
                        }
                    });
            });
        if let Some(base) = goto_base {
            state.mem_bytes_va_input = format!("{base:#x}");
            if state.mem_bytes_size_input.trim().is_empty() {
                state.mem_bytes_size_input = "256".into();
            }
            match process_read(&sess.session_id, base, 256) {
                Ok(r) => {
                    state.live_error = r.error.clone();
                    state.mem_bytes_last = Some(r);
                }
                Err(e) => {
                    state.mem_bytes_last = None;
                    state.live_error = Some(e);
                }
            }
            state.active_tab = DebuggerPane::MemoryBytes;
        }
    }
    ui.separator();
    ui.label(RichText::new("Static Mappings").strong());
    ui.small(
        RichText::new(
            "ghidrust_core::process::static_to_live · static file RVA → live VA via module base",
        )
        .color(muted),
    );
    ui.horizontal(|ui| {
        ui.label("Module:");
        ui.add(
            egui::TextEdit::singleline(&mut state.static_map_module_input)
                .desired_width(FieldWidth::Compact.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("game.exe"),
        );
        ui.label("RVA:");
        ui.add(
            egui::TextEdit::singleline(&mut state.static_map_rva_input)
                .desired_width(FieldWidth::Compact.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("0x1000"),
        );
        if ui.button("Resolve").clicked() {
            let rva = parse_hex(&state.static_map_rva_input).unwrap_or(0);
            match static_to_live(&sess.session_id, state.static_map_module_input.trim(), rva) {
                Ok(r) => {
                    state.static_map_result = Some(format!(
                        "{} base={:#x} rva={:#x} → live_va={:#x}",
                        r.module, r.base, r.rva, r.live_va
                    ));
                    state.live_error = None;
                }
                Err(e) => {
                    state.static_map_result = None;
                    state.live_error = Some(e);
                }
            }
        }
    });
    if let Some(res) = &state.static_map_result {
        ui.monospace(res);
    }
}

fn render_regions(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
    let Some(sess) = state.session.clone() else {
        ui.weak("No live target — attach one from Targets first.");
        return;
    };
    ui.horizontal(|ui| {
        ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));
        if ui.button("Refresh regions").clicked() {
            state.live_error = None;
            match process_regions(&sess.session_id, 4096) {
                Ok(v) => state.regions_cache = v,
                Err(e) => {
                    state.regions_cache.clear();
                    state.live_error = Some(e);
                }
            }
        }
    });
    if state.regions_cache.is_empty() {
        ui.weak("No regions cached — click Refresh regions.");
        return;
    }
    ui.small(format!("{} region(s)", state.regions_cache.len()));
    let row_h = ui.text_style_height(&egui::TextStyle::Monospace) + 2.0;
    let regions = state.regions_cache.clone();
    let list_h = ui.available_height().max(120.0);
    egui::ScrollArea::vertical()
        .id_salt("dbg_regions_scroll")
        .auto_shrink([false, false])
        .max_height(list_h)
        .show_rows(ui, row_h, regions.len(), |ui, range| {
            for i in range {
                let r: &RegionInfo = &regions[i];
                ui.monospace(format!(
                    "{:#018x} +{:#x} protect={} state={} type={}",
                    r.base, r.size, r.protect, r.state, r.typ
                ));
            }
        });
}

fn render_memory_bytes(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
    let Some(sess) = state.session.clone() else {
        ui.weak("No live target — attach one from Targets first.");
        return;
    };
    ui.small(RichText::new(format!("pid={} · live ReadProcessMemory", sess.pid)).color(muted));
    ui.horizontal(|ui| {
        ui.label("VA:");
        ui.add(
            egui::TextEdit::singleline(&mut state.mem_bytes_va_input)
                .desired_width(FieldWidth::Compact.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("0x140001000"),
        );
        ui.label("Size:");
        ui.add(
            egui::TextEdit::singleline(&mut state.mem_bytes_size_input)
                .desired_width(FieldWidth::Narrow.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("256"),
        );
        if ui.button("Read").clicked() {
            let va = parse_hex(&state.mem_bytes_va_input).unwrap_or(0);
            let size: usize = state
                .mem_bytes_size_input
                .trim()
                .parse()
                .unwrap_or(256)
                .max(1);
            match process_read(&sess.session_id, va, size) {
                Ok(r) => {
                    state.live_error = r.error.clone();
                    state.mem_bytes_last = Some(r);
                }
                Err(e) => {
                    state.mem_bytes_last = None;
                    state.live_error = Some(e);
                }
            }
        }
    });
    // base+off subtitle when VA falls in a cached module
    if let Some(va) = parse_hex(&state.mem_bytes_va_input) {
        if let Some(m) = state.module_for_va(va) {
            let off = va.saturating_sub(m.base);
            ui.small(
                RichText::new(format!("{}+{:#x} (base {:#x})", m.name, off, m.base)).color(muted),
            );
        }
    }
    let Some(read) = &state.mem_bytes_last else {
        ui.weak("No read yet — enter a VA + size and click Read.");
        return;
    };
    let mod_subtitle = state
        .module_for_va(read.va)
        .map(|m| format!("{}+{:#x}", m.name, read.va.saturating_sub(m.base)));
    ui.small(format!(
        "va={:#x}{} requested={} read={}",
        read.va,
        mod_subtitle
            .as_deref()
            .map(|s| format!(" ({s})"))
            .unwrap_or_default(),
        read.size_requested,
        read.bytes_read
    ));
    let bytes = read.bytes.clone();
    let base_va = read.va;
    let list_h = ui.available_height().max(120.0);
    egui::ScrollArea::vertical()
        .id_salt("dbg_membytes_scroll")
        .max_height(list_h)
        .auto_shrink([false, false])
        .show(ui, |ui| {
            for (row, chunk) in bytes.chunks(16).enumerate() {
                let addr = base_va + (row as u64) * 16;
                let hex: String = chunk.iter().map(|b| format!("{b:02x} ")).collect();
                let ascii: String = chunk
                    .iter()
                    .map(|&b| {
                        if (0x20..0x7f).contains(&b) {
                            b as char
                        } else {
                            '.'
                        }
                    })
                    .collect();
                ui.monospace(format!("{addr:#018x} {hex:<48} {ascii}"));
            }
        });
}

fn render_breakpoints(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
    let Some(sess) = state.session.clone() else {
        ui.weak("No live target — attach with mode=debug to set software breakpoints.");
        return;
    };
    if sess.mode != SessionMode::Debug {
        ui.weak("Breakpoints require mode=debug. Re-attach/launch with Mode=debug on Targets.");
        return;
    }
    ui.small(RichText::new("process_break_set / clear / list (software INT3)").color(muted));
    ui.horizontal(|ui| {
        ui.label("Address:");
        ui.add(
            egui::TextEdit::singleline(&mut state.bp_input)
                .desired_width(FieldWidth::Compact.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("0x7ff…"),
        );
        ui.checkbox(&mut state.bp_oneshot, "oneshot");
        if ui.button("Add").clicked() {
            if let Some(va) = parse_hex(&state.bp_input) {
                match process_break_set(&sess.session_id, va, BreakKind::Software, state.bp_oneshot)
                {
                    Ok(bp) => {
                        state.log(format!("bp set id={} addr={:#x}", bp.id, bp.addr));
                        state.live_error = None;
                        state.bp_input.clear();
                        state.refresh_debug_views();
                    }
                    Err(e) => state.live_error = Some(e),
                }
            }
        }
        if ui.button("Refresh").clicked() {
            state.refresh_debug_views();
        }
    });
    ui.separator();
    if state.live_breakpoints.is_empty() {
        ui.weak("No live breakpoints.");
        return;
    }
    let mut clear_id: Option<u64> = None;
    let mut goto: Option<u64> = None;
    egui::Grid::new("dbg_bp_grid")
        .num_columns(5)
        .striped(true)
        .show(ui, |ui| {
            ui.strong("Id");
            ui.strong("Address");
            ui.strong("Kind");
            ui.strong("Oneshot");
            ui.strong("");
            ui.end_row();
            for bp in &state.live_breakpoints {
                ui.monospace(format!("{}", bp.id));
                if ui.link(format!("{:#x}", bp.addr)).clicked() {
                    goto = Some(bp.addr);
                }
                ui.label(format!("{:?}", bp.kind).to_ascii_lowercase());
                ui.label(if bp.oneshot { "yes" } else { "no" });
                if ui.small_button("Clear").clicked() {
                    clear_id = Some(bp.id);
                }
                ui.end_row();
            }
        });
    if let Some(id) = clear_id {
        match process_break_clear(&sess.session_id, Some(id), None) {
            Ok(()) => {
                state.log(format!("bp clear id={id}"));
                state.refresh_debug_views();
            }
            Err(e) => state.live_error = Some(e),
        }
    }
    if let Some(va) = goto {
        state.mem_bytes_va_input = format!("{va:#x}");
        state.active_tab = DebuggerPane::MemoryBytes;
    }
}

fn render_watches(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
    let Some(sess) = state.session.clone() else {
        ui.weak("No live target — attach first, then add pointer-chase expressions.");
        return;
    };
    ui.small(
        RichText::new("process_watch_expr · DSL: module+rva, u64@va, va->*+0x10 (bytes ≠ types)")
            .color(muted),
    );
    ui.horizontal(|ui| {
        ui.label("Expr:");
        ui.add(
            egui::TextEdit::singleline(&mut state.watch_input)
                .desired_width(FieldWidth::Wide.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("game.exe+0x1234->*+0x10"),
        );
        ui.checkbox(&mut state.watch_matrix_heuristic, "matrix heuristic");
        if ui.button("Add").clicked() {
            let e = state.watch_input.clone();
            state.add_watch(e);
            state.watch_input.clear();
            state.refresh_watches();
        }
        if ui.button("Refresh all").clicked() {
            state.refresh_watches();
        }
    });
    ui.separator();
    // Scan mini-tool
    ui.label(RichText::new("Scan (process_scan)").strong());
    ui.horizontal(|ui| {
        ui.label("AOB:");
        ui.add(
            egui::TextEdit::singleline(&mut state.scan_aob)
                .desired_width(FieldWidth::Std.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("48 8b ?? 90"),
        );
        ui.label("String:");
        ui.add(
            egui::TextEdit::singleline(&mut state.scan_string)
                .desired_width(FieldWidth::Compact.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("Camera"),
        );
        if ui.button("Scan").clicked() {
            let opts = ScanOpts {
                aob: {
                    let a = state.scan_aob.trim();
                    if a.is_empty() {
                        None
                    } else {
                        Some(a.to_string())
                    }
                },
                string: {
                    let s = state.scan_string.trim();
                    if s.is_empty() {
                        None
                    } else {
                        Some(s.to_string())
                    }
                },
                ..ScanOpts::default()
            };
            match process_scan_mem(&sess.session_id, &opts) {
                Ok(r) => {
                    state.scan_hits = r.hits;
                    state.log(format!(
                        "scan hits={} truncated={} bytes={}",
                        state.scan_hits.len(),
                        r.truncated,
                        r.bytes_scanned
                    ));
                    state.live_error = None;
                }
                Err(e) => state.live_error = Some(e),
            }
        }
    });
    if !state.scan_hits.is_empty() {
        ui.small(format!("{} scan hit(s)", state.scan_hits.len()));
        let mut goto = None;
        egui::ScrollArea::vertical()
            .id_salt("dbg_scan_hits")
            .max_height(ThemeDensity::FIB_DESKTOP.field_narrow)
            .show(ui, |ui| {
                for h in state.scan_hits.iter().take(64) {
                    if ui
                        .link(format!(
                            "{:#x} {} {:?}",
                            h.va,
                            h.module.as_deref().unwrap_or("?"),
                            h.preview_hex.as_deref().unwrap_or("")
                        ))
                        .clicked()
                    {
                        goto = Some(h.va);
                    }
                }
            });
        if let Some(va) = goto {
            state.mem_bytes_va_input = format!("{va:#x}");
            state.active_tab = DebuggerPane::MemoryBytes;
        }
    }
    ui.separator();
    if state.watches.is_empty() {
        ui.weak("No watches.");
        return;
    }
    let mut delete: Option<usize> = None;
    egui::Grid::new("dbg_watch_grid")
        .num_columns(4)
        .striped(true)
        .show(ui, |ui| {
            ui.strong("Expression");
            ui.strong("VA");
            ui.strong("Value");
            ui.strong("");
            ui.end_row();
            for (i, w) in state.watches.iter().enumerate() {
                ui.monospace(w);
                let res = state.watch_results.get(i);
                if let Some(r) = res {
                    ui.monospace(
                        r.final_va
                            .map(|v| format!("{v:#x}"))
                            .unwrap_or_else(|| "—".into()),
                    );
                    let val = r
                        .error
                        .clone()
                        .or_else(|| r.as_u64.map(|u| format!("{u:#x}")))
                        .or_else(|| r.value_hex.clone())
                        .unwrap_or_else(|| "—".into());
                    let t = if r.heuristic {
                        format!("{val} (heuristic)")
                    } else {
                        val
                    };
                    ui.small(t);
                } else {
                    ui.small("—");
                    ui.small(RichText::new("Refresh").color(muted));
                }
                if ui.small_button("Delete").clicked() {
                    delete = Some(i);
                }
                ui.end_row();
            }
        });
    if let Some(i) = delete {
        state.remove_watch(i);
        state.refresh_watches();
    }
}

fn render_threads(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
    let Some(sess) = state.session.clone() else {
        ui.weak("No live target.");
        return;
    };
    if sess.mode != SessionMode::Debug {
        ui.weak("Threads pane uses process_threads (debug mode).");
        return;
    }
    ui.horizontal(|ui| {
        ui.small(RichText::new("process_threads").color(muted));
        if ui.button("Refresh").clicked() {
            state.refresh_debug_views();
        }
    });
    if state.threads_cache.is_empty() {
        ui.weak("No threads — Refresh or wait for a stop.");
        return;
    }
    egui::Grid::new("dbg_threads_grid")
        .num_columns(2)
        .striped(true)
        .show(ui, |ui| {
            ui.strong("TID");
            ui.strong("Active");
            ui.end_row();
            for t in state.threads_cache.clone() {
                let selected = state.active_thread_id == Some(t.thread_id);
                if ui.selectable_label(selected, format!("{}", t.thread_id)).clicked() {
                    state.active_thread_id = Some(t.thread_id);
                    state.refresh_debug_views();
                }
                ui.label(if selected { "●" } else { "" });
                ui.end_row();
            }
        });
}

fn render_registers(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
    let Some(sess) = state.session.clone() else {
        ui.weak("No live target.");
        return;
    };
    if sess.mode != SessionMode::Debug {
        ui.weak("Registers require mode=debug (process_thread_context_get / set).");
        return;
    }
    ui.horizontal(|ui| {
        ui.small(
            RichText::new(format!(
                "tid={} · edit hex → Set → process_thread_context_set",
                state
                    .active_thread_id
                    .map(|t| t.to_string())
                    .unwrap_or_else(|| "—".into())
            ))
            .color(muted),
        );
        if ui.button("Refresh").clicked() {
            state.refresh_debug_views();
        }
    });
    if let Some(stop) = &state.last_stop {
        ui.small(format!(
            "last stop: {} rip={:#x}",
            stop.reason, stop.rip
        ));
    }
    if state.registers_cache.is_none() {
        ui.weak("No register cache — stop on a BP or Refresh after selecting a thread.");
        return;
    }
    if state.reg_edit.is_empty() {
        state.sync_reg_edit_from_cache();
    }
    let names: Vec<&'static str> = register_pairs(state.registers_cache.as_ref().unwrap())
        .into_iter()
        .map(|(n, _)| n)
        .collect();
    let mut apply_name: Option<String> = None;
    egui::ScrollArea::vertical()
        .id_salt("dbg_regs")
        .show(ui, |ui| {
            egui::Grid::new("dbg_regs_grid")
                .num_columns(3)
                .striped(true)
                .show(ui, |ui| {
                    ui.strong("Register");
                    ui.strong("Value");
                    ui.strong("");
                    ui.end_row();
                    for n in &names {
                        ui.monospace(*n);
                        let entry = state
                            .reg_edit
                            .entry((*n).to_string())
                            .or_insert_with(String::new);
                        let resp = ui.add(
                            egui::TextEdit::singleline(entry)
                                .desired_width(FieldWidth::Compact.px(&ThemeDensity::FIB_DESKTOP))
                                .font(egui::TextStyle::Monospace),
                        );
                        if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
                            apply_name = Some((*n).to_string());
                        }
                        if ui.small_button("Set").clicked() {
                            apply_name = Some((*n).to_string());
                        }
                        ui.end_row();
                    }
                });
        });
    if let Some(n) = apply_name {
        state.apply_register_edit(&n);
    }
}

fn render_stack(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
    let Some(sess) = state.session.clone() else {
        ui.weak("No live target.");
        return;
    };
    if sess.mode != SessionMode::Debug {
        ui.weak("Stack requires mode=debug (process_stack).");
        return;
    }
    ui.horizontal(|ui| {
        ui.small(RichText::new("process_stack · RBP unwind").color(muted));
        if ui.button("Refresh").clicked() {
            state.refresh_debug_views();
        }
    });
    if state.stack_cache.is_empty() {
        ui.weak("No frames — stop on a BP then Refresh.");
        return;
    }
    let mut goto = None;
    egui::ScrollArea::vertical()
        .id_salt("dbg_stack")
        .show(ui, |ui| {
            egui::Grid::new("dbg_stack_grid")
                .num_columns(5)
                .striped(true)
                .show(ui, |ui| {
                    ui.strong("#");
                    ui.strong("SP");
                    ui.strong("PC");
                    ui.strong("Module");
                    ui.strong("RVA");
                    ui.end_row();
                    for f in &state.stack_cache {
                        ui.monospace(format!("{}", f.level));
                        ui.monospace(format!("{:#x}", f.sp));
                        if ui.link(format!("{:#x}", f.rip)).clicked() {
                            goto = Some(f.rip);
                        }
                        ui.small(f.module.as_deref().unwrap_or("—"));
                        ui.monospace(
                            f.rva
                                .map(|r| format!("{r:#x}"))
                                .unwrap_or_else(|| "—".into()),
                        );
                        ui.end_row();
                    }
                });
        });
    if let Some(va) = goto {
        state.mem_bytes_va_input = format!("{va:#x}");
        state.active_tab = DebuggerPane::MemoryBytes;
    }
}

fn render_console(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
    ui.horizontal(|ui| {
        ui.small(
            RichText::new("Session events · command line (continue/step/regs or process_* {json})")
                .color(muted),
        );
        if ui.button("Clear log").clicked() {
            state.console_log.clear();
        }
        if ui
            .add_enabled(state.session.is_some(), egui::Button::new("Export snapshot"))
            .on_hover_text("process_export_snapshot")
            .clicked()
        {
            if let Some(sess) = state.session.clone() {
                match process_export_snapshot(&sess.session_id, &state.watches, &[]) {
                    Ok(snap) => {
                        if let Ok(j) = serde_json::to_string_pretty(&snap) {
                            state.log(format!("snapshot ok bytes={}", j.len()));
                            for line in j.lines().take(12) {
                                state.log(line.to_string());
                            }
                            state.live_error = None;
                        }
                    }
                    Err(e) => state.live_error = Some(e),
                }
            }
        }
    });
    ui.separator();
    egui::ScrollArea::vertical()
        .id_salt("dbg_console")
        .stick_to_bottom(true)
        .max_height(ThemeDensity::FIB_DESKTOP.scroll_sm)
        .show(ui, |ui| {
            if state.console_log.is_empty() {
                ui.weak("No events yet — type a command below.");
            }
            for line in &state.console_log {
                ui.monospace(line);
            }
        });
    ui.separator();
    let mut submit = false;
    ui.horizontal(|ui| {
        ui.label(">");
        let resp = ui.add(
            egui::TextEdit::singleline(&mut state.console_input)
                .desired_width(f32::INFINITY)
                .hint_text("continue · step · regs · process_threads {\"session_id\":\"…\"}"),
        );
        if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
            submit = true;
        }
        if ui.button("Run").clicked() {
            submit = true;
        }
    });
    if submit {
        let cmd = std::mem::take(&mut state.console_input);
        state.run_console_command(&cmd);
    }
}

fn parse_hex(s: &str) -> Option<u64> {
    let s = s.trim();
    let s = s
        .strip_prefix("0x")
        .or_else(|| s.strip_prefix("0X"))
        .unwrap_or(s);
    u64::from_str_radix(s, 16).ok()
}

fn register_pairs(regs: &RegisterSet) -> [(&'static str, u64); 18] {
    [
        ("rax", regs.rax),
        ("rbx", regs.rbx),
        ("rcx", regs.rcx),
        ("rdx", regs.rdx),
        ("rsi", regs.rsi),
        ("rdi", regs.rdi),
        ("rbp", regs.rbp),
        ("rsp", regs.rsp),
        ("r8", regs.r8),
        ("r9", regs.r9),
        ("r10", regs.r10),
        ("r11", regs.r11),
        ("r12", regs.r12),
        ("r13", regs.r13),
        ("r14", regs.r14),
        ("r15", regs.r15),
        ("rip", regs.rip),
        ("rflags", regs.rflags),
    ]
}

fn set_register_field(regs: &mut RegisterSet, name: &str, val: u64) -> bool {
    match name.to_ascii_lowercase().as_str() {
        "rax" => regs.rax = val,
        "rbx" => regs.rbx = val,
        "rcx" => regs.rcx = val,
        "rdx" => regs.rdx = val,
        "rsi" => regs.rsi = val,
        "rdi" => regs.rdi = val,
        "rbp" => regs.rbp = val,
        "rsp" => regs.rsp = val,
        "r8" => regs.r8 = val,
        "r9" => regs.r9 = val,
        "r10" => regs.r10 = val,
        "r11" => regs.r11 = val,
        "r12" => regs.r12 = val,
        "r13" => regs.r13 = val,
        "r14" => regs.r14 = val,
        "r15" => regs.r15 = val,
        "rip" => regs.rip = val,
        "rflags" => regs.rflags = val,
        _ => return false,
    }
    true
}

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

    fn modinfo(name: &str, base: u64, size: u64, path: Option<&str>) -> ModuleInfo {
        ModuleInfo {
            name: name.into(),
            path: path.map(|p| p.into()),
            base,
            size,
        }
    }

    #[test]
    fn debugger_catalog_covers_debugger_windows() {
        let names: Vec<&'static str> = DebuggerPane::ALL.iter().map(|p| p.title()).collect();
        for expected in [
            "Debugger Targets",
            "Debugger Threads",
            "Debugger Modules",
            "Debugger Regions",
            "Debugger Registers",
            "Debugger Stack",
            "Debugger Breakpoints",
            "Debugger Memory Bytes",
            "Debugger Watches",
            "Debugger Console",
        ] {
            assert!(
                names.contains(&expected),
                "missing debugger pane {expected}"
            );
        }
    }

    #[test]
    fn tab_order_puts_live_panes_first() {
        assert_eq!(DebuggerPane::TAB_ORDER[0], DebuggerPane::Targets);
        assert_eq!(DebuggerPane::TAB_ORDER[1], DebuggerPane::Modules);
        assert_eq!(DebuggerPane::TAB_ORDER[2], DebuggerPane::MemoryBytes);
        assert_eq!(DebuggerPane::TAB_ORDER[3], DebuggerPane::Regions);
    }

    #[test]
    fn every_debugger_pane_has_metadata() {
        for p in DebuggerPane::ALL {
            assert!(!p.title().is_empty());
            assert!(!p.short_title().is_empty());
            assert!(!p.plugin().is_empty());
            assert!(!p.egui_id().is_empty());
            assert!(!p.columns().is_empty());
            assert!(!p.backend_message().is_empty());
        }
    }

    #[test]
    fn breakpoint_toggle_flow() {
        let mut s = DebuggerState::default();
        s.toggle_breakpoint(0x1000);
        assert!(s.has_breakpoint(0x1000));
        s.toggle_breakpoint(0x1000);
        assert!(!s.has_breakpoint(0x1000));
    }

    #[test]
    fn watch_add_dedup_and_remove() {
        let mut s = DebuggerState::default();
        s.add_watch("rax");
        s.add_watch("rax");
        s.add_watch("");
        assert_eq!(s.watches.len(), 1);
        s.add_watch("rbx");
        assert_eq!(s.watches.len(), 2);
        s.remove_watch(0);
        assert_eq!(s.watches[0], "rbx");
    }

    #[test]
    fn pick_main_module_prefers_process_name() {
        let mods = vec![
            modinfo(
                "ntdll.dll",
                0x7ffe0000,
                0x1000,
                Some(r"C:\Windows\ntdll.dll"),
            ),
            modinfo("game.exe", 0x140000000, 0x10000, Some(r"C:\game\game.exe")),
        ];
        let m = pick_main_module(&mods, Some("game.exe")).unwrap();
        assert_eq!(m.name, "game.exe");
        assert_eq!(m.base, 0x140000000);
    }

    #[test]
    fn pick_main_module_falls_back_to_pathed() {
        let mods = vec![
            modinfo("a.dll", 0x1000, 0x100, None),
            modinfo("b.dll", 0x2000, 0x100, Some(r"C:\b.dll")),
        ];
        let m = pick_main_module(&mods, Some("missing.exe")).unwrap();
        assert_eq!(m.name, "b.dll");
    }

    #[test]
    fn clear_live_caches_and_detach_focus_targets() {
        let mut s = DebuggerState::default();
        s.modules_cache = vec![modinfo("x.exe", 0x1000, 0x10, None)];
        s.regions_cache = vec![RegionInfo {
            base: 0x1000,
            size: 0x1000,
            protect: "0x40".into(),
            state: "commit".into(),
            typ: "0x20000".into(),
        }];
        s.mem_bytes_last = Some(ReadResult {
            va: 0x1000,
            size_requested: 16,
            bytes_read: 0,
            hex: String::new(),
            bytes: Vec::new(),
            error: None,
            as_u64: None,
            as_f32: None,
        });
        s.process_display_name = Some("x.exe".into());
        s.active_tab = DebuggerPane::Modules;
        s.clear_live_caches();
        assert!(s.modules_cache.is_empty());
        assert!(s.regions_cache.is_empty());
        assert!(s.mem_bytes_last.is_none());
        assert!(s.process_display_name.is_none());
        // detach_session without a real session still focuses Targets
        s.active_tab = DebuggerPane::Modules;
        s.detach_session();
        assert_eq!(s.active_tab, DebuggerPane::Targets);
    }

    #[test]
    fn module_for_va_base_plus_off() {
        let mut s = DebuggerState::default();
        s.modules_cache = vec![modinfo("game.exe", 0x140000000, 0x1000, None)];
        let m = s.module_for_va(0x140000100).unwrap();
        assert_eq!(m.name, "game.exe");
        assert!(s.module_for_va(0x150000000).is_none());
    }

    #[test]
    fn layout_migration_opens_host_and_focuses_first_tab() {
        let mut s = DebuggerState::default();
        let mut panes = BTreeMap::new();
        panes.insert("pane_dbg_modules".into(), true);
        panes.insert("pane_dbg_regions".into(), true);
        apply_layout_flags(&mut s, &panes);
        assert!(s.host_open);
        assert!(s.enabled);
        assert_eq!(s.active_tab, DebuggerPane::Modules);
    }

    #[test]
    fn layout_snapshot_marks_active_tab_only() {
        let mut s = DebuggerState::default();
        s.host_open = true;
        s.active_tab = DebuggerPane::MemoryBytes;
        let mut panes = BTreeMap::new();
        snapshot_layout_flags(&s, &mut panes);
        assert_eq!(panes.get(HOST_EGUI_ID), Some(&true));
        assert_eq!(panes.get("pane_dbg_membytes"), Some(&true));
        assert_eq!(panes.get("pane_dbg_targets"), Some(&false));
    }

    #[test]
    fn enable_tool_opens_host_on_targets() {
        let mut s = DebuggerState::default();
        // May fail to list processes in CI/non-Windows — still must open host.
        s.enabled = false;
        s.host_open = false;
        s.active_tab = DebuggerPane::Stack;
        s.enable_tool();
        assert!(s.enabled);
        assert!(s.host_open);
        assert_eq!(s.active_tab, DebuggerPane::Targets);
    }

    #[test]
    fn open_attach_ui_focuses_targets() {
        let mut s = DebuggerState::default();
        s.open_attach_ui();
        assert!(s.host_open);
        assert_eq!(s.active_tab, DebuggerPane::Targets);
    }

    #[test]
    fn open_launch_ui_prefills_and_opens_dialog() {
        let mut s = DebuggerState::default();
        s.open_launch_ui(Some(Path::new(r"C:\games\app.exe")));
        assert!(s.host_open);
        assert!(s.show_launch_dialog);
        assert_eq!(s.launch_image, r"C:\games\app.exe");
        assert_eq!(s.launch_cwd, r"C:\games");
    }

    #[test]
    fn launch_and_populate_requires_image() {
        let mut s = DebuggerState::default();
        s.launch_and_populate();
        assert!(s.live_error.as_deref().unwrap().contains("required"));
    }

    #[test]
    fn detach_clears_suspended_flag() {
        let mut s = DebuggerState::default();
        s.suspended = true;
        s.process_display_name = Some("x.exe".into());
        s.detach_session();
        assert!(!s.suspended);
        assert!(s.process_display_name.is_none());
    }

    #[test]
    fn simulated_post_attach_focus_modules() {
        // Mimic refresh_after_attach's final focus without calling Win32.
        let mut s = DebuggerState::default();
        s.session = Some(ProcessSession::new(
            "ps-test".into(),
            1,
            ghidrust_core::SessionMode::Observe,
            ghidrust_core::RunState::Attached,
        ));
        s.process_display_name = Some("game.exe".into());
        s.modules_cache = vec![modinfo(
            "game.exe",
            0x140000000,
            0x1000,
            Some(r"C:\game.exe"),
        )];
        s.active_tab = DebuggerPane::Modules;
        assert_eq!(s.active_tab, DebuggerPane::Modules);
        assert!(!s.modules_cache.is_empty());
        assert_eq!(
            pick_main_module(&s.modules_cache, s.process_display_name.as_deref())
                .unwrap()
                .base,
            0x140000000
        );
    }
}